PHP Manual

by:
Mehdi Achour
Friedhelm Betz
Antony Dovgal
Nuno Lopes
Hannes Magnusson
Georg Richter
Damien Seguy
Jakub Vrana
And several others
2020-02-11
Edited By: Peter Cowburn
© 1997-2020 the PHP Documentation Group
  • Copyright
  • PHP Manual
    • Preface
  • Getting Started
    • Introduction
    • A simple tutorial
  • Installation and Configuration
    • General Installation Considerations
    • Installation on Unix systems
    • Installation on macOS
    • Installation on Windows systems
    • Installation on Cloud Computing platforms
    • FastCGI Process Manager (FPM)
    • Installation of PECL extensions
    • Problems?
    • Runtime Configuration
  • Language Reference
    • Basic syntax
    • Types
    • Variables
    • Constants
    • Expressions
    • Operators
    • Control Structures
    • Functions
    • Classes and Objects
    • Namespaces
    • Errors
    • Exceptions
    • Generators
    • References Explained
    • Predefined Variables
    • Predefined Exceptions
    • Predefined Interfaces and Classes
    • Context options and parameters
    • Supported Protocols and Wrappers
  • Security
    • Introduction
    • General considerations
    • Installed as CGI binary
    • Installed as an Apache module
    • Session Security
    • Filesystem Security
    • Database Security
    • Error Reporting
    • Using Register Globals
    • User Submitted Data
    • Magic Quotes
    • Hiding PHP
    • Keeping Current
  • Features
    • HTTP authentication with PHP
    • Cookies
    • Sessions
    • Dealing with XForms
    • Handling file uploads
    • Using remote files
    • Connection handling
    • Persistent Database Connections
    • Safe Mode
    • Command line usage — Using PHP from the command line
    • Garbage Collection
    • DTrace Dynamic Tracing
  • Function Reference
    • Affecting PHP's Behaviour
    • Audio Formats Manipulation
    • Authentication Services
    • Command Line Specific Extensions
    • Compression and Archive Extensions
    • Credit Card Processing
    • Cryptography Extensions
    • Database Extensions
    • Date and Time Related Extensions
    • File System Related Extensions
    • Human Language and Character Encoding Support
    • Image Processing and Generation
    • Mail Related Extensions
    • Mathematical Extensions
    • Non-Text MIME Output
    • Process Control Extensions
    • Other Basic Extensions
    • Other Services
    • Search Engine Extensions
    • Server Specific Extensions
    • Session Extensions
    • Text Processing
    • Variable and Type Related Extensions
    • Web Services
    • Windows Only Extensions
    • XML Manipulation
    • GUI Extensions
  • PHP at the Core: A Hacker's Guide
    • Preface
    • Memory management
    • Working with Variables
    • Writing Functions
    • Writing Classes
    • Working with Resources
    • Working with INI settings
    • Working with streams
    • The "counter" Extension - A Continuing Example
    • The PHP 5 build system
    • Extension structure
    • PDO Driver How-To
    • Extension FAQs
    • Zend Engine 2 API reference
    • Zend Engine 2 Opcodes
    • Zend Engine 1
  • FAQ — FAQ: Frequently Asked Questions
    • General Information
    • Mailing lists
    • Obtaining PHP
    • Database issues
    • Installation
    • Build Problems
    • Using PHP
    • Password Hashing — Safe Password Hashing
    • PHP and HTML
    • PHP and COM
    • Miscellaneous Questions
  • Appendices
    • History of PHP and Related Projects
    • Migrating from PHP 7.3.x to PHP 7.4.x
    • Migrating from PHP 7.2.x to PHP 7.3.x
    • Migrating from PHP 7.1.x to PHP 7.2.x
    • Migrating from PHP 7.0.x to PHP 7.1.x
    • Migrating from PHP 5.6.x to PHP 7.0.x
    • Migrating from PHP 5.5.x to PHP 5.6.x
    • Migrating from PHP 5.4.x to PHP 5.5.x
    • Migrating from PHP 5.3.x to PHP 5.4.x
    • Migrating from PHP 5.2.x to PHP 5.3.x
    • Migrating from PHP 5.1.x to PHP 5.2.x
    • Migrating from PHP 5.0.x to PHP 5.1.x
    • Migrating from PHP 4 to PHP 5.0.x
    • Debugging in PHP
    • Configure options
    • php.ini directives
    • Extension List/Categorization
    • List of Function Aliases
    • List of Reserved Words
    • List of Resource Types
    • List of Available Filters
    • List of Supported Socket Transports
    • PHP type comparison tables
    • List of Parser Tokens
    • Userland Naming Guide
    • About the manual
    • Creative Commons Attribution 3.0
    • Index listing
    • Changelog
  • HTML Help Edition
    • About This Edition
    • Using PHP Manual CHM Edition
    • The Full Text Search
    • Integrating the PHP Manual


Copyright

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

If you are interested in redistribution or republishing of this document in whole or in part, either modified or unmodified, and you have questions, please contact the Copyright holders at » doc-license@lists.php.net. Note that this address is mapped to a publicly archived mailing list.


  • « Copyright
  • Preface »
  • PHP Manual
  • PHP Manual

PHP Manual

  • Preface


Preface

PHP, which stands for "PHP: Hypertext Preprocessor" is a widely-used Open Source general-purpose scripting language that is especially suited for web development and can be embedded into HTML. Its syntax draws upon C, Java, and Perl, and is easy to learn. The main goal of the language is to allow web developers to write dynamically generated web pages quickly, but you can do much more with PHP.

This manual consists primarily of a function reference, but also contains a language reference, explanations of some of PHP's major features, and other supplemental information.

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

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

Authors and Editors

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

The following contributors have done significant work editing the manual: Stig Bakken, Gabor Hojtsy, Hartmut Holzgraefe, 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

  • Introduction
    • What is PHP?
    • What can PHP do?
  • A simple tutorial
    • What do I need?
    • Your first PHP-enabled page
    • Something Useful
    • Dealing with Forms
    • Using old code with new versions of PHP
    • What's next?


  • « Getting Started
  • What is PHP? »
  • PHP Manual
  • Getting Started
  • Introduction

Introduction

Table of Contents

  • What is PHP?
  • What can PHP 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 you to jump into and out of "PHP mode."

What distinguishes PHP from something like client-side JavaScript is that the code is executed on the server, generating HTML which is then sent to the client. The client would receive the results of running that script, but would not know what the underlying code was. You can even configure your web server to process all your HTML files with PHP, and then there's really no way that users can tell what you have up your sleeve.

The best things in using PHP are that it is extremely simple for a newcomer, but offers many advanced features for a professional programmer. Don't be afraid reading the long list of PHP's features. You can jump in, in a short time, and start writing simple scripts in a few hours.

Although PHP's development is focused on server-side scripting, you can do much more with it. Read on, and see more in the What can PHP do? section, or go right to the introductory tutorial if you are only interested in web programming.


What can PHP do?

Anything. PHP is mainly focused on server-side scripting, so you can do anything any other CGI program can do, such as collect form data, generate dynamic page content, or send and receive cookies. But PHP can do much more.

There are three main areas where PHP scripts are used.

  • Server-side scripting. This is the most traditional and main target field for PHP. You need three things to make this work: the PHP parser (CGI or server module), a web server and a web browser. You need to run the web server, with a connected PHP installation. You can access the PHP program output with a web browser, viewing the PHP page through the server. All these can run on your home machine if you are just experimenting with PHP programming. See the installation instructions section for more information.
  • Command line scripting. You can make a PHP script to run it without any server or browser. You only need the PHP parser to use it this way. This type of usage is ideal for scripts regularly executed using cron (on *nix or Linux) or Task Scheduler (on Windows). These scripts can also be used for simple text processing tasks. See the section about Command line usage of PHP for more information.
  • Writing desktop applications. PHP is probably not the very best language to create a desktop application with a graphical user interface, but if you know PHP very well, and would like to use some advanced PHP features in your client-side applications you can also use PHP-GTK to write such programs. You also have the ability to write cross-platform applications this way. PHP-GTK is an extension to PHP, not available in the main distribution. If you are interested in PHP-GTK, visit » its own website.

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

With PHP you are not limited to output HTML. PHP's abilities includes outputting images, PDF files and even Flash movies (using libswf and Ming) generated on the fly. You can also output easily any text, such as XHTML and any other XML file. PHP can autogenerate these files, and save them in the file system, instead of printing it out, forming a server-side cache for your dynamic content.

One of the strongest and most significant features in PHP is its support for a wide range of databases. Writing a database-enabled web page is incredibly simple using one of the database specific extensions (e.g., for mysql), or using an abstraction layer like PDO, or connect to any database supporting the Open Database Connection standard via the ODBC extension. Other databases may utilize cURL or sockets, like CouchDB.

PHP also has support for talking to other services using protocols such as LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM (on Windows) and countless others. You can also open raw network sockets and interact using any other protocol. PHP has support for the WDDX complex data exchange between virtually all Web programming languages. Talking about interconnection, PHP has support for instantiation of Java objects and using them transparently as PHP objects.

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

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

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


A simple tutorial

Table of Contents

  • What do I need?
  • Your first PHP-enabled page
  • Something Useful
  • Dealing with Forms
  • Using old code with new versions of PHP
  • 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.


What do I need?

In this tutorial we assume that your server has activated support for PHP and that all files ending in .php are handled by PHP. On most servers, this is the default extension for PHP files, but ask your server administrator to be sure. If your server supports PHP, then you do not need to do anything. Just create your .php files, put them in your web directory and the server will automatically parse them for you. There is no need to compile anything nor do you need to install any extra tools. Think of these PHP-enabled files as simple HTML files with a whole new family of magical tags that let you do all sorts of things.

Let us say you want to save precious bandwidth and develop locally. In this case, you will want to install a web server, such as » Apache, and of course » PHP. You will most likely want to install a database as well, such as » MySQL.

You can either install these individually or choose a simpler way. Our manual has installation instructions for PHP (assuming you already have some web server set up). If you have problems with installing PHP yourself, we would suggest you ask your questions on our » installation mailing list. If you choose to go on the simpler route, then » locate a pre-configured package for your operating system, which automatically installs all of these with just a few mouse clicks. It is easy to setup a web server with PHP support on any operating system, including MacOSX, Linux and Windows. On Linux, you may find » rpmfind and » PBone helpful for locating RPMs. You may also want to visit » apt-get to find packages for Debian.


Your first PHP-enabled page

Create a file named hello.php and put it in your web server's root directory (DOCUMENT_ROOT) with the following content:

Example #1 Our first PHP script: hello.php

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

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

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

This program is extremely simple and you really did not need to use PHP to create a page like this. All it does is display: Hello World using the PHP echo statement. Note that the file does not need to be executable or special in any way. The server finds out that this file needs to be interpreted by PHP because you used the ".php" extension, which the server is configured to pass on to PHP. Think of this as a normal HTML file which happens to have a set of special tags available to you that do a lot of interesting things.

If you tried this example and it did not output anything, it prompted for download, or you see the whole file as text, chances are that the server you are on does not have PHP enabled, or is not configured properly. Ask your administrator to enable it for you using the Installation chapter of the manual. If you are developing locally, also read the installation chapter to make sure everything is configured properly. Make sure that you access the file via http with the server providing you the output. If you just call up the file from your file system, then it will not be parsed by PHP. If the problems persist anyway, do not hesitate to use one of the many » PHP support options.

The point of the example is to show the special PHP tag format. In this example we used <?php to indicate the start of a PHP tag. Then we put the PHP statement and left PHP mode by adding the closing tag, ?>. You may jump in and out of PHP mode in an HTML file like this anywhere you want. For more details, read the manual section on the basic PHP syntax.

Note: A Note on Line Feeds

Line feeds have little meaning in HTML, however it is still a good idea to make your HTML look nice and clean by putting line feeds in. A linefeed that follows immediately after a closing ?> will be removed by PHP. This can be extremely useful when you are putting in many blocks of PHP or include files containing PHP that aren't supposed to output anything. At the same time it can be a bit confusing. You can put a space after the closing ?> to force a space and a line feed to be output, or you can put an explicit line feed in the last echo/print from within your PHP block.

Note: A Note on Text Editors

There are many text editors and Integrated Development Environments (IDEs) that you can use to create, edit and manage PHP files. A partial list of these tools is maintained at » PHP Editors List. If you wish to recommend an editor, please visit the above page and ask the page maintainer to add the editor to the list. Having an editor with syntax highlighting can be helpful.

Note: A Note on Word Processors

Word processors such as StarOffice Writer, Microsoft Word and Abiword are not optimal for editing PHP files. If you wish to use one for this test script, you must ensure that you save the file as plain text or PHP will not be able to read and execute the script.

Note: A Note on Windows Notepad

If you are writing your PHP scripts using Windows Notepad, you will need to ensure that your files are saved with the .php extension. (Notepad adds a .txt extension to files automatically unless you take one of the following steps to prevent it.) When you save the file and are prompted to provide a name for the file, place the filename in quotes (i.e. "hello.php"). Alternatively, you can click on the 'Text Documents' drop-down menu in the 'Save' dialog box and change the setting to "All Files". You can then enter your filename without quotes.

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

Example #2 Get system information from PHP

<?php phpinfo(); ?>


Something Useful

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

Note:

$_SERVER is a special reserved PHP variable that contains all web server information. It is known as a superglobal. See the related manual page on superglobals for more information. These special variables were introduced in PHP » 4.1.0. Before this time, we used the older $HTTP_*_VARS arrays instead, such as $HTTP_SERVER_VARS. As of PHP 5.4.0 these older variables have been removed. (See also the note on old code.)

To display this variable, you can simply do:

Example #1 Printing a variable (Array element)

<?php
echo $_SERVER['HTTP_USER_AGENT'];
?>

A sample output of this script may be:

Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)

There are many types of variables available in PHP. In the above example we printed an Array element. Arrays can be very useful.

$_SERVER is just one variable that PHP automatically makes available to you. A list can be seen in the Reserved Variables section of the manual or you can get a complete list of them by looking at the output of the phpinfo() function used in the example in the previous section.

You can put multiple PHP statements inside a PHP tag and create little blocks of code that do more than just a single echo. For example, if you want to check for Internet Explorer you can do this:

Example #2 Example using control structures and functions

<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {
    echo 'You are using Internet Explorer.<br />';
}
?>

A sample output of this script may be:

You are using Internet Explorer.<br />

Here we introduce a couple of new concepts. We have an if statement. If you are familiar with the basic syntax used by the C language, this should look logical to you. Otherwise, you should probably pick up an introductory PHP book and read the first couple of chapters, or read the Language Reference part of the manual.

The second concept we introduced was the strpos() function call. strpos() is a function built into PHP which searches a string for another string. In this case we are looking for 'MSIE' (so-called needle) inside $_SERVER['HTTP_USER_AGENT'] (so-called haystack). If the needle is found inside the haystack, the function returns the position of the needle relative to the start of the haystack. Otherwise, it returns FALSE. If it does not return FALSE, the if expression evaluates to TRUE and the code within its {braces} is executed. Otherwise, the code is not run. Feel free to create similar examples, with if, else, and other functions such as strtoupper() and strlen(). Each related manual page contains examples too. If you are unsure how to use functions, you will want to read both the manual page on how to read a function definition and the section about PHP functions.

We can take this a step further and show how you can jump in and out of PHP mode even in the middle of a PHP block:

Example #3 Mixing both HTML and PHP modes

<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {
?>
<h3>strpos() must have returned non-false</h3>
<p>You are using Internet Explorer</p>
<?php
} else {
?>
<h3>strpos() must have returned false</h3>
<p>You are not using Internet Explorer</p>
<?php
}
?>

A sample output of this script may be:

<h3>strpos() must have returned non-false</h3>
<p>You are using Internet Explorer</p>

Instead of using a PHP echo statement to output something, we jumped out of PHP mode and just sent straight HTML. The important and powerful point to note here is that the logical flow of the script remains intact. Only one of the HTML blocks will end up getting sent to the viewer depending on the result of strpos(). In other words, it depends on whether the string MSIE was found or not.


Dealing with Forms

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

Example #1 A simple HTML form

<form action="action.php" method="post">
 <p>Your name: <input type="text" name="name" /></p>
 <p>Your age: <input type="text" name="age" /></p>
 <p><input type="submit" /></p>
</form>

There is nothing special about this form. It is a straight HTML form with no special tags of any kind. When the user fills in this form and hits the submit button, the action.php page is called. In this file you would write something like this:

Example #2 Printing data from our form

Hi <?php echo htmlspecialchars($_POST['name']); ?>.
You are <?php echo (int)$_POST['age']; ?> years old.

A sample output of this script may be:

Hi Joe. You are 22 years old.

Apart from the htmlspecialchars() and (int) parts, it should be obvious what this does. htmlspecialchars() makes sure any characters that are special in html are properly encoded so people can't inject HTML tags or Javascript into your page. For the age field, since we know it is a number, we can just convert it to an integer which will automatically get rid of any stray characters. You can also have PHP do this for you automatically by using the filter extension. The $_POST['name'] and $_POST['age'] variables are automatically set for you by PHP. Earlier we used the $_SERVER superglobal; above we just introduced the $_POST superglobal which contains all POST data. Notice how the method of our form is POST. If we used the method GET then our form information would live in the $_GET superglobal instead. You may also use the $_REQUEST superglobal, if you do not care about the source of your request data. It contains the merged information of GET, POST and COOKIE data.

You can also deal with XForms input in PHP, although you will find yourself comfortable with the well supported HTML forms for quite some time. While working with XForms is not for beginners, you might be interested in them. We also have a short introduction to handling data received from XForms in our features section.


Using old code with new versions of PHP

Now that PHP has grown to be a popular scripting language, there are a lot of public repositories and libraries containing code you can reuse. The PHP developers have largely tried to preserve backwards compatibility, so a script written for an older version will run (ideally) without changes in a newer version of PHP. In practice, some changes will usually be needed.

Two of the most important recent changes that affect old code are:

  • The old $HTTP_*_VARS arrays are not available as of PHP 5.4.0. The following superglobal arrays were introduced in PHP » 4.1.0. They are: $_GET, $_POST, $_COOKIE, $_SERVER, $_FILES, $_ENV, $_REQUEST, and $_SESSION.
  • External variables are no longer registered in the global scope by default. In other words, as of PHP » 4.2.0 the PHP directive register_globals is off by default in php.ini. The preferred method of accessing these values is via the superglobal arrays mentioned above. Older scripts, books, and tutorials may rely on this directive being on. If it were on, for example, one could use $id from the URL http://www.example.com/foo.php?id=42. Whether on or off, $_GET['id'] is available.
For more details on these changes, see the section on predefined variables and links therein.


What's next?

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

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


Installation and Configuration

  • General Installation Considerations
  • Installation on Unix systems
    • Apache 1.3.x on Unix systems
    • Apache 2.x on Unix systems
    • Nginx 1.4.x on Unix systems
    • Lighttpd 1.4 on Unix systems
    • Sun, iPlanet and Netscape servers on Sun Solaris
    • LiteSpeed Web Server/OpenLiteSpeed Web Server on Unix systems
    • CGI and command line setups
    • HP-UX specific installation notes
    • OpenBSD installation notes
    • Solaris specific installation tips
    • Debian GNU/Linux installation notes
  • Installation on macOS
    • Using Packages
    • Using the bundled PHP
    • Compiling PHP on macOS
  • Installation on Windows systems
    • Install Requirements
    • PECL
    • PHP Installer Tools on Windows
    • Recommended Configuration on Windows systems
    • Manual PHP Installation on Windows
    • Troubleshooting PHP on Windows
    • Installation on old Windows systems
  • Installation on Cloud Computing platforms
    • Azure App Services
    • Amazon EC2
  • 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
  • Problems?
    • Read the FAQ
    • Other problems
    • Bug reports
  • Runtime Configuration
    • The configuration file
    • .user.ini files
    • Where a configuration setting may be set
    • How to change configuration settings


General Installation Considerations

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

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

For the first and most common form, you need three things: PHP itself, a web server and a web browser. You probably already have a web browser, and depending on your operating system setup, you may also have a web server (e.g. Apache on Linux and macOS; IIS on Windows). You may also rent webspace at a company. This way, you don't need to set up anything on your own, only write your PHP scripts, upload it to the server you rent, and see the results in your browser.

In case of setting up the server and PHP on your own, you have two choices for the method of connecting PHP to the server. For many servers PHP has a direct module interface (also called SAPI). These servers include Apache, Microsoft Internet Information Server, Netscape and iPlanet servers. Many other servers have support for ISAPI, the Microsoft module interface (OmniHTTPd for example). If PHP has no module support for your web server, you can always use it as a CGI or FastCGI processor. This means you set up your server to use the CGI executable of PHP to process all PHP file requests on the server.

If you are also interested 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.

With PHP you can also write desktop GUI applications using the PHP-GTK extension. This is a completely different approach than writing web pages, as you do not output any HTML, but manage windows and objects within them. For more information about PHP-GTK, please » visit the site dedicated to this extension. PHP-GTK is not included in the official PHP distribution.

From now on, this section deals with setting up PHP for web servers on Unix and Windows with server module interfaces and CGI executables. You will also find information on the command line executable in the following sections.

PHP source code and binary distributions for Windows can be found at » https://www.php.net/downloads.php.


Installation on Unix systems

Table of Contents

  • Apache 1.3.x on Unix systems
  • Apache 2.x on Unix systems
  • Nginx 1.4.x on Unix systems
  • Lighttpd 1.4 on Unix systems
  • Sun, iPlanet and Netscape servers on Sun Solaris
  • LiteSpeed Web Server/OpenLiteSpeed Web Server on Unix systems
  • CGI and command line setups
  • HP-UX specific installation notes
  • OpenBSD installation notes
  • Solaris specific installation tips
  • Debian GNU/Linux installation notes

This section will guide you through the general configuration and installation of PHP on Unix systems. Be sure to investigate any sections specific to your platform or web server before you begin the process.

As our manual outlines in the General Installation Considerations section, we are mainly dealing with web centric setups of PHP in this section, although we will cover setting up PHP for command line usage as well.

There are several ways to install PHP for the Unix platform, either with a compile and configure process, or through various pre-packaged methods. This documentation is mainly focused around the process of compiling and configuring PHP. Many Unix like systems have some sort of package installation system. This can assist in setting up a standard configuration, but if you need to have a different set of features (such as a secure server, or a different database driver), you may need to build PHP and/or your web server. If you are unfamiliar with building and compiling your own software, it is worth checking to see whether somebody has already built a packaged version of PHP with the features you need.

Prerequisite knowledge and software for compiling:

  • Basic Unix skills (being able to operate "make" and a C compiler)
  • An ANSI C compiler
  • A web server
  • Any module specific components (such as GD, PDF libs, etc.)

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

  • autoconf: 2.13+ (for PHP < 5.4.0), 2.59+ (for PHP >= 5.4.0), 2.64+ (for PHP >= 7.2.0)
  • automake: 1.4+
  • libtool: 1.4.x+ (except 1.4.2)
  • re2c: Version 0.13.4 or newer
  • flex: Version 2.5.4 (for PHP <= 5.2)
  • bison:
    • PHP 5.4: 1.28, 1.35, 1.75, 1.875, 2.0, 2.1, 2.2, 2.3, 2.4, 2.4.1, 2.4.2, 2.4.3, 2.5, 2.5.1, 2.6, 2.6.1, 2.6.2, 2.6.4
    • PHP 5.5: 2.4, 2.4.1, 2.4.2, 2.4.3, 2.5, 2.5.1, 2.6, 2.6.1, 2.6.2, 2.6.3, 2.6.4, 2.6.5, 2.7
    • PHP 5.6: >= 2.4, < 3.0
    • PHP 7.0 - 7.3: 2.4 or later (including Bison 3.x)
    • PHP 7.4: > 3.0

The initial PHP setup and configuration process is controlled by the use of the command line options of the configure script. You could get a list of all available options along with short explanations running ./configure --help. Our manual documents the different options separately. You will find the core options in the appendix, while the different extension specific options are descibed on the reference pages.

When PHP is configured, you are ready to build the module and/or executables. The command make should take care of this. If it fails and you can't figure out why, see the Problems section.

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, however, 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.


Apache 1.3.x on Unix systems

This section contains notes and hints specific to Apache installs of PHP on Unix platforms. We also have instructions and notes for Apache 2 on a separate page.

You can select arguments to add to the configure on line 10 below from the list of core configure options and from extension specific options described at the respective places in the manual. The version numbers have been omitted here, to ensure the instructions are not incorrect. You will need to replace the 'xxx' here with the correct values from your files.

Example #1 Installation Instructions (Apache Shared Module Version) for PHP

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

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

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

11. make
12. make install

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

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

13. Setup your php.ini file:

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

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

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

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

      LoadModule php5_module libexec/libphp5.so

15. And in the AddModule section of httpd.conf, somewhere under the
    ClearModuleList, add this:

      AddModule mod_php5.c

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

      AddType application/x-httpd-php .php .phtml

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

      AddType application/x-httpd-php-source .phps

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

Alternatively, to install PHP as a static object:

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

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

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

10. cd ../apache_1.3.x

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

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

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

15. You can edit /usr/local/lib/php.ini file to set PHP options.
    Edit your httpd.conf or srm.conf file and add:
    AddType application/x-httpd-php .php

Depending on your Apache install and Unix variant, there are many possible ways to stop and restart the server. Below are some typical lines used in restarting the server, for different apache/unix installations. You should replace /path/to/ with the path to these applications on your systems.

Example #3 Example commands for restarting Apache

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

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

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

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

The locations of the apachectl and http(s)dctl binaries often vary. If your system has locate, whereis or which commands, these can assist you in finding your server control programs.

Different examples of compiling PHP for apache are as follows:

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

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

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

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

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

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

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

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

When choosing to build PHP in different ways, you should consider the advantages and drawbacks of each method. Building as a shared object will mean that you can compile apache separately, and don't have to recompile everything as you add to, or change, PHP. Building PHP into apache (static method) means that PHP will load and run faster. For more information, see the Apache » web page on DSO support.

Note:

Apache's default httpd.conf currently ships with a section that looks like this:

User nobody
Group "#-1"
Unless you change that to "Group nogroup" or something like that ("Group daemon" is also very common) PHP will not be able to open files.

Note:

Make sure you specify the installed version of apxs when using --with-apxs=/path/to/apxs . You must NOT use the apxs version that is in the apache sources but the one that is actually installed on your system.


Apache 2.x on Unix systems

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

Warning

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

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

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

There are currently two versions of Apache 2.x - there's 2.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-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 7:

    LoadModule php7_module modules/libphp7.so

    For PHP 5:

    LoadModule php5_module modules/libphp5.so

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

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

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

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

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

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

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

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

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

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

    /usr/local/apache2/bin/apachectl start

    OR

    service httpd restart

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

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

--with-mpm=worker

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

Note:

The Apache MultiViews FAQ discusses using multiviews with PHP.

Note:

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


Nginx 1.4.x on Unix systems

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

This guide will assume that you have built Nginx from source and therefore all binaries and configuration files are located at /usr/local/nginx. If this is not the case and you have obtained Nginx through other means then please refer to the » Nginx Wiki in order 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 recomended that you visit the Nginx Wiki » install page in order to obtain and install Nginx on your system.

  2. Obtain and unpack the PHP source:

    tar zxf php-x.x.x

  3. Configure and build PHP. This is where you customize PHP with various options, like which extensions will be enabled. Run ./configure --help for a list of available options. In our example we'll do a simple configure with PHP-FPM and 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 exists, allowing us to prevent arbitrarily script injection.

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

    Load up php.ini:

    vim /usr/local/php/php.ini

    Locate cgi.fix_pathinfo= and modify it as follows:

    cgi.fix_pathinfo=0

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

    vim /usr/local/etc/php-fpm.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 in PHP 5.3, but for older versions configure PHP with --enable-fastcgi. To confirm that PHP has fastcgi enabled, php -v should contain PHP 5.2.5 (cgi-fcgi) Before PHP 5.2.3, fastcgi was enabled on the php binary (there was no php-cgi).

Letting Lighttpd spawn php processes

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

Example #1 Partial lighttpd.conf

server.modules += ( "mod_fastcgi" )

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

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

Spawning with spawn-fcgi

Lighttpd provides a program called spawn-fcgi to 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 ))
)


Sun, iPlanet and Netscape servers on Sun Solaris

This section contains notes and hints specific to Sun Java System Web Server, Sun ONE Web Server, iPlanet and Netscape server installs of PHP on Sun Solaris.

From PHP 4.3.3 on you can use PHP scripts with the NSAPI module to generate custom directory listings and error pages. Additional functions for Apache compatibility are also available. For support in current web servers read the note about subrequests.

You can find more information about setting up PHP for the Netscape Enterprise Server (NES) here: » http://benoit.noss.free.fr/php/install-php4.html

To build PHP with Sun JSWS/Sun ONE WS/iPlanet/Netscape web servers, enter the proper install directory for the --with-nsapi=[DIR] option. The default directory is usually /opt/netscape/suitespot/. Please also read /php-xxx-version/sapi/nsapi/nsapi-readme.txt.

  1. Install the following packages from » http://www.sunfreeware.com/ or another download site:

    • autoconf-2.13
    • automake-1.4
    • bison-1_25-sol26-sparc-local
    • flex-2_5_4a-sol26-sparc-local
    • gcc-2_95_2-sol26-sparc-local
    • gzip-1.2.4-sol26-sparc-local
    • m4-1_4-sol26-sparc-local
    • make-3_76_1-sol26-sparc-local
    • mysql-3.23.24-beta (if you want mysql support)
    • perl-5_005_03-sol26-sparc-local
    • tar-1.13 (GNU tar)

  2. Make sure your path includes the proper directories PATH=.:/usr/local/bin:/usr/sbin:/usr/bin:/usr/ccs/bin and make it available to your system export PATH.
  3. gunzip php-x.x.x.tar.gz (if you have a .gz dist, otherwise go to 4).
  4. tar xvf php-x.x.x.tar
  5. Change to your extracted PHP directory: cd ../php-x.x.x

  6. For the following step, make sure /opt/netscape/suitespot/ is where your netscape server is installed. Otherwise, change to the correct path and run:

    ./configure --with-mysql=/usr/local/mysql \
--with-nsapi=/opt/netscape/suitespot/ \
--enable-libgcc

  7. Run make followed by make install.

After performing the base install and reading the appropriate readme file, you may need to perform some additional configuration steps.

Configuration Instructions for Sun/iPlanet/Netscape

Firstly you may need to add some paths to the LD_LIBRARY_PATH environment for the server to find all the shared libs. This can best done in the start script for your web server. The start script is often located in: /path/to/server/https-servername/start. You may also need to edit the configuration files that are located in: /path/to/server/https-servername/config/.

  1. Add the following line to mime.types (you can do that by the administration server):

    type=magnus-internal/x-httpd-php exts=php

  2. Edit magnus.conf (for servers >= 6) or obj.conf (for servers < 6) and add the following, shlib will vary depending on your system, it will be something like /opt/netscape/suitespot/bin/libphp4.so. You should place the following lines after mime types init.

    Init fn="load-modules" funcs="php4_init,php4_execute,php4_auth_trans" shlib="/opt/netscape/suitespot/bin/libphp4.so"
Init fn="php4_init" LateInit="yes" errorString="Failed to initialize PHP!" [php_ini="/path/to/php.ini"]
    (PHP >= 4.3.3) The php_ini parameter is optional but with it you can place your php.ini in your web server config directory.

  3. Configure the default object in obj.conf (for virtual server classes [version 6.0+] in their vserver.obj.conf):

    <Object name="default">
.
.
.
.#NOTE this next line should happen after all 'ObjectType' and before all 'AddLog' lines
Service fn="php4_execute" type="magnus-internal/x-httpd-php" [inikey=value inikey=value ...]
.
.
</Object>
    (PHP >= 4.3.3) As additional parameters you can add some special php.ini-values, for example you can set a docroot="/path/to/docroot" specific to the context php4_execute is called. For boolean ini-keys please use 0/1 as value, not "On","Off",... (this will not work correctly), e.g. zlib.output_compression=1 instead of zlib.output_compression="On"

  4. This is only needed if you want to configure a directory that only consists of PHP scripts (same like a cgi-bin directory):

    <Object name="x-httpd-php">
ObjectType fn="force-type" type="magnus-internal/x-httpd-php"
Service fn=php4_execute [inikey=value inikey=value ...]
</Object>
    After that you can configure a directory in the Administration server and assign it the style x-httpd-php. All files in it will get executed as PHP. This is nice to hide PHP usage by renaming files to .html.

  5. Setup of authentication: PHP authentication cannot be used with any other authentication. ALL AUTHENTICATION IS PASSED TO YOUR PHP SCRIPT. To configure PHP Authentication for the entire server, add the following line to your default object:

    <Object name="default">
AuthTrans fn=php4_auth_trans
.
.
.
</Object>

  6. To use PHP Authentication on a single directory, add the following:

    <Object ppath="d:\path\to\authenticated\dir\*">
AuthTrans fn=php4_auth_trans
</Object>

Note:

The stacksize that PHP uses depends on the configuration of the web server. If you get crashes with very large PHP scripts, it is recommended to raise it with the Admin Server (in the section "MAGNUS EDITOR").

CGI environment and recommended modifications in php.ini

Important when writing PHP scripts is the fact that Sun JSWS/Sun ONE WS/iPlanet/Netscape is a multithreaded web server. Because of that all requests are running in the same process space (the space of the web server itself) and this space has only one environment. If you want to get CGI variables like PATH_INFO, HTTP_HOST etc. it is not the correct way to try this in the old PHP way with getenv() or a similar way (register globals to environment, $_ENV). You would only get the environment of the running web server without any valid CGI variables!

Note:

Why are there (invalid) CGI variables in the environment?

Answer: This is because you started the web server process from the admin server which runs the startup script of the web server, you wanted to start, as a CGI script (a CGI script inside of the admin server!). This is why the environment of the started web server has some CGI environment variables in it. You can test this by starting the web server not from the administration server. Use the command line as root user and start it manually - you will see there are no CGI-like environment variables.

Simply change your scripts to get CGI variables in the correct way for PHP 4.x by using the superglobal $_SERVER. If you have older scripts which use $HTTP_HOST, etc., you should turn on register_globals in php.ini and change the variable order too (important: remove "E" from it, because you do not need the environment here):

variables_order = "GPCS"
register_globals = On

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

You can use PHP to generate the error pages for "404 Not Found" or similar. Add the following line to the object in obj.conf for every error page you want to overwrite:

Error fn="php4_execute" code=XXX script="/path/to/script.php" [inikey=value inikey=value...]
where XXX is the HTTP error code. Please delete any other Error directives which could interfere with yours. If you want to place a page for all errors that could exist, leave the code parameter out. Your script can get the HTTP status code with $_SERVER['ERROR_TYPE'].

Another possibility is to generate self-made directory listings. Just create a PHP script which displays a directory listing and replace the corresponding default Service line for type="magnus-internal/directory" in obj.conf with the following:

Service fn="php4_execute" type="magnus-internal/directory" script="/path/to/script.php" [inikey=value inikey=value...]
For both error and directory listing pages the original URI and translated URI are in the variables $_SERVER['PATH_INFO'] and $_SERVER['PATH_TRANSLATED'].

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

The NSAPI module now supports the nsapi_virtual() function (alias: virtual()) to make subrequests on the web server and insert the result in the web page. This function uses some undocumented features from the NSAPI library. On Unix the module automatically looks for the needed functions and uses them if available. If not, nsapi_virtual() is disabled.

Note:

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


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 wiki » install page or OpenLiteSpeed wiki » 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 wiki 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 wiki 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 » wiki 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 » wiki page


CGI and command line setups

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

Warning

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

Testing

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

Using Variables

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


HP-UX specific installation notes

This section contains notes and hints specific to installing PHP on HP-UX systems.

There are two main options for installing PHP on HP-UX systems. Either compile it, or install a pre-compiled binary.

Official pre-compiled packages are located here: » http://software.hp.com/

Until this manual section is rewritten, the documentation about compiling PHP (and related extensions) on HP-UX systems has been removed. For now, consider reading the following external resource: » Building Apache and PHP on HP-UX 11.11


OpenBSD installation notes

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

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 gettext and iconv). Next, take a look at the module packages, such as php-mysql 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-fpm
# pkg_add php-mysql
  (install the PEAR libraries)
# pkg_add pear

Follow the instructions shown with each package!

  (to remove packages)
# pkg_delete php
# pkg_delete php-fpm
# pkg_delete php-mysql
# 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 4 port is split into two sub-directories: core and extensions. The extensions directory generates sub-packages for all of the supported PHP modules. If you find you do not want to create some of these modules, use the no_* FLAVOR. For example, to skip building the imap module, set the FLAVOR to no_imap.

Common Problems

  • 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 5.7+ package for the » gd extension requires XFree86 to be installed. This can be added post-installation (See OpenBSD FAQ#4) by adding the xbase.tgz file set.

Older Releases

Older releases of OpenBSD used the FLAVORS system to compile up a statically linked PHP. Since it is hard to generate binary packages using this method, it is now deprecated. You can still use the old stable ports trees if you wish, but they are unsupported by the OpenBSD team. If you have any comments about this, the current maintainer for the port is Anil Madhavapeddy (avsm at openbsd dot org).


Solaris specific installation tips

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

Required software

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

For unpacking the PHP distribution you need

  • tar
  • gzip or
  • bzip2

For compiling PHP you need

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

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

  • flex (up to PHP 5.2)
  • re2c
  • bison
  • m4
  • autoconf
  • automake
In addition, you will need to install (and possibly compile) any additional software specific to your configuration, such as Oracle or MySQL.

Using Packages

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


Debian GNU/Linux installation notes

This section contains notes and hints specific to installing PHP on » Debian GNU/Linux.

Warning

Unofficial builds from third-parties are not supported here. Any bugs should be reported to the Debian team unless they can be reproduced using the latest builds from our » download area.

While the instructions for building PHP on Unix apply to Debian as well, this manual page contains specific information for other options, such as using either the apt-get or aptitude commands. This manual page uses these two commands interchangeably.

Using APT

First, note that other related packages may be desired like libapache2-mod-php5 to integrate with Apache 2, and php-pear for PEAR.

Second, before installing a package, it's wise to ensure the package list is up to date. Typically, this is done by running the command apt-get update.

Example #1 Debian Install Example with Apache 2

# apt-get install php5-common libapache2-mod-php5 php5-cli

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

Example #2 Stopping and starting Apache once PHP is installed

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

Better control of configuration

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

Example #3 Methods for listing additional PHP 5 packages

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

The examples will show a lot of packages including several PHP specific ones like php5-cgi, php5-cli and php5-dev. Determine which are needed and install them like any other with either apt-get or aptitude. And because Debian performs dependency checks, it'll prompt for those so for example to install MySQL and cURL:

Example #4 Install PHP with MySQL, cURL

# apt-get install php5-mysql php5-curl

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

Common Problems

  • If the PHP scripts are not parsing via the web server, then it's likely that PHP was not added to the web server's configuration file, which on Debian may be /etc/apache2/apache2.conf or similar. See the Debian manual for further details.
  • If an extension was seemingly installed yet the functions are undefined, be sure that the appropriate ini file is being loaded and/or the web server was restarted after installation.
  • There are two basic commands for installing packages on Debian (and other linux variants): apt-get and aptitude. However, explaining the subtle differences between these commands goes beyond the scope of this manual.


Installation on macOS

Table of Contents

  • Using Packages
  • Using the bundled PHP
  • Compiling PHP on macOS

This section contains notes and hints specific to installing PHP on macOS. PHP is bundled with Macs, and compiling is similar to the Unix installation guide.


Using Packages

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

The following resources offer easy to install packages and precompiled binaries for PHP on Mac OS:

  • MacPorts: » http://www.macports.org/
  • Liip: » http://php-osx.liip.ch/
  • Fink: » http://www.finkproject.org/
  • Homebrew: » https://github.com/Homebrew/homebrew-php


Using the bundled PHP

PHP has come standard with Macs since Mac OS X version 10.0.0. Enabling PHP with the default web server requires uncommenting a few lines in the Apache configuration file httpd.conf whereas the CGI and/or CLI are enabled by default (easily accessible via the Terminal program).

Enabling PHP using the instructions below is meant for quickly setting up a local development environment. It's highly recommended to always upgrade PHP to the newest version. Like most live software, newer versions are created to fix bugs and add features and PHP being is no different. See the appropriate 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.


  • « Using the bundled PHP
  • Installation on Windows systems »
  • PHP Manual
  • Installation on macOS
  • Compiling PHP on macOS

Compiling PHP on macOS

Use the Unix installation guide to compile PHP on macOS.


Installation on Windows systems

Table of Contents

  • Install Requirements
  • PECL
  • PHP Installer Tools on Windows
  • Recommended Configuration on Windows systems
  • Manual PHP Installation on Windows
  • Troubleshooting PHP on Windows
  • Installation on old Windows systems

Installing PHP on modern Microsoft Windows systems and recommended configuration with common web servers.

Note:

If you are looking for information about older systems, such as Windows XP, 2003, 98 or Apache 1.x, see the Legacy Info section.

The Official releases of PHP on Windows are recommended for production use. However, you are welcome to build PHP from Source. You will need a Visual Studio environment. See » Step by Step Build Instructions.

  • Using PHP on Windows Command line

  • Installing PHP on Azure App Services (aka Microsoft Azure, Windows Azure, or (Windows) Azure Web Apps).


Install Requirements

PHP 5.5+ require at least Windows 2008/Vista, or 2008r2, 2012, 2012r2, 2016 or 7, 8, 8.1, 10. Either 32-Bit or 64-bit (aka X86 or X64. PHP does not run on Windows RT/WOA/ARM). As of PHP 7.2.0 Windows 2008 and Vista are no longer supported.

PHP requires the Visual C runtime(CRT). Many applications require that so it may already be installed.

PHP 5.5 and 5.6 require VC CRT 11 (Visual Studio 2012). See: » https://www.microsoft.com/en-us/download/details.aspx?id=30679

PHP 7.0 and 7.1 require VC CRT 14 (Visual Studio 2015). PHP 7.2, 7.3 and 7.4 require VC CRT 15 (Visual Studio 2017). The Microsoft Visual C++ Redistributable for Visual Studio 2019 is suitable for all these PHP versions, see » https://visualstudio.microsoft.com/downloads/.

You MUST download the x86 CRT for PHP x86 builds and the x64 CRT for PHP x64 builds.

If CRT is already installed, the installer will tell you that and not change anything.

The CRT installer supports the /quiet and /norestart command-line switches, so you can script running it.

VC11 CRT DLLs can be copied from your local machine to a remote machine(a `Copy Deployment` installation) instead of running the installer on the remote machine (such as a web server you have restricted access to).

VC14 CRT does not support a `Copy Deployment` installation. VC14 CRT has many more DLLs(most in files with names starting with api-*). If you can find them all and copy them, it will also work (try a tool like Resource Hacker to get a list of all the DLLs to copy).


PECL

PECL extensions are pre-built for Windows and available from: » http://windows.php.net/downloads/pecl/releases/

Some extensions use features specific to some Unix systems and so are not available on Windows. Otherwise, all extensions are available for Windows.


PHP Installer Tools on Windows

PHP Install Tools

If you want to setup PHP and are using IIS, the easiest way is to use » Microsoft's Web Platform Installer (WebPI).

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

Setting up and configuring Nginx on Windows requires a bit more configuration. See the » Nginx documentation for additional setup help.


Recommended Configuration on Windows systems

OpCache

Highly Recommended that you 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.

In your php.ini, set

Example #1 Recommended OpCache configuration

zend_extension=php_opcache.dll
opcache.enable=On
opcache.enable_cli=On
And restart your web server. For more info, see: OpCache Configuration

WinCache

Recommended that you 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 you need high performance, you should use the object cache in your applications. See: » http://pecl.php.net/package/WinCache to download a WinCache DLL (or tgz) to your PHP extensions directory (extensions_dir in your php.ini). In your php.ini, set

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: » http://php.net/manual/en/wincache.configuration.php

IIS Configuration

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

You may use the APPCMD command line tool to script IIS configuration.

Database

You'll probably need a Database Server. Popular databases provide PHP extensions to use them. If your web site doesn't get a lot of traffic, you can run your database server on the same server as your web server. Many popular database servers run on Windows.

PHP includes mysqli and pdo_mysql extensions. PHP 5.5 and 5.6 include mysql extension (deprecated in 7.0).

See » https://dev.mysql.com/downloads/windows/


Manual PHP Installation on Windows

Choose Web Server

  • IIS is builtin to Windows. On Windows Server, use Server Manager to add the IIS role. Be sure to include the CGI Role Feature. On Windows Desktop, use Control Panel's Add/Remove Programs to add IIS. See: » https://msdn.microsoft.com/en-us/library/ms181052%28v=vs.80%29.aspx?f=255&MSPPError=-2147217396 For desktop web apps and web-development, you can also use IIS/Express or PHP Desktop

    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
    REM path to directory you decompressed PHP .ZIP file into
set phpdir=c:\php
set phppath=php-5.6.19-nts-Win32-VC11-x86

REM Clear current PHP handlers
%windir%\system32\inetsrv\appcmd clear config /section:system.webServer/fastCGI
%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='%phpdir%\%phppath%\php-cgi.exe']
%windir%\system32\inetsrv\appcmd set config /section:system.webServer/handlers /+[name='PHP_via_FastCGI',path='*.php',verb='*',modules='FastCgiModule',scriptProcessor='%phpdir%\%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='%phpdir%\%phppath%\php-cgi.exe'].instanceMaxRequests:10000
%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi /+"[fullPath='%phpdir%\%phppath%\php-cgi.exe'].environmentVariables.[name='PHP_FCGI_MAX_REQUESTS',value='10000']"
%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi /+"[fullPath='%phpdir%\%phppath%\php-cgi.exe'].environmentVariables.[name='PHPRC',value='%phpdir%\%phppath%\php.ini']"
    How to manually configure IIS

  • There are several builds of Apache2 for Windows. We support ApacheLounge, but other options include XAMPP, WampServer and BitNami, which provide automatic installer tools. You may use mod_php or mod_fastcgi to load PHP on Apache. If you use mod_php, you MUST use a TS build of Apache built with same version of Visual C and same CPU (x86 or x64). How to manually configure Apache2

Choose Build

Download PHP production releases from » http://windows.php.net/download/. A lot of testing and optimization is already done on the snapshot and qa releases, but you are welcome to help us do more. There are 4 types of PHP builds:

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

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

  • x86 - production use of PHP 5.5 or 5.6 or 7.0.

  • x64 - production use of PHP 7.0+ unless its a 32-bit only version of Windows. 5.5 and 5.6 x64 are experimental.


Troubleshooting PHP on Windows

Check Temp Directory Permissions

  1. Right-click temp directory in File Explorer to get the permissions.

  2. For IIS, check that user IIS_User has MODIFY permission. You can get the temporary directory from the configuration or php info.


Installation on old Windows systems

This section applies to Windows 98/Me and Windows NT/2000/XP/2003. PHP will not work on 16 bit platforms such as Windows 3.1 and sometimes we refer to the supported Windows platforms as Win32.

Note:

Windows XP/2003 are no longer supported as of PHP 5.5.0.

Note:

Windows 98/Me/NT4/2000 are no longer supported as of PHP 5.3.0.

Note:

Windows 95 is no longer supported as of PHP 4.3.0.

If you have a development environment such as Microsoft Visual Studio, you can also build PHP from the original source code.

Once you have PHP installed on your Windows system, you may also want to load various extensions for added functionality.

Manual Installation Steps

This section contains instructions for manually installing and configuring PHP on Microsoft Windows.

Selecting and downloading the PHP distribution package

Download the PHP zip binary distribution from » PHP for Windows: Binaries and Sources. There are several different versions of the zip package - to choose the right version for you, follow the detailed guide on the » download page.

The PHP package structure and content

Unpack the content of the zip archive into a directory of your choice, for example C:\PHP\. The directory and file structure extracted from the zip will look as below:

Example #1 PHP 5 package structure

c:\php
   |
   +--dev
   |  |
   |  |-php5ts.lib                 -- php5.lib in non thread safe version
   |
   +--ext                          -- extension DLLs for PHP
   |  |
   |  |-php_bz2.dll
   |  |
   |  |-php_cpdf.dll
   |  |
   |  |-...
   |
   +--extras                       -- empty
   |
   +--pear                         -- initial copy of PEAR
   |
   |
   |-go-pear.bat                   -- PEAR setup script
   |
   |-...
   |
   |-php-cgi.exe                   -- CGI executable
   |
   |-php-win.exe                   -- executes scripts without an opened command prompt
   |
   |-php.exe                       -- Command line PHP executable (CLI)
   |
   |-...
   |
   |-php.ini-development           -- default php.ini settings
   |
   |-php.ini-production            -- recommended php.ini settings
   |
   |-php5apache2_2.dll             -- does not exist in non thread safe version
   |
   |-php5apache2_2_filter.dll      -- does not exist in non thread safe version
   |
   |-...
   |
   |-php5ts.dll                    -- core PHP DLL ( php5.dll in non thread safe version)
   |
   |-...

Below is the list of the modules and executables included in the PHP zip distribution:

  • go-pear.bat - the PEAR setup script. Refer to » Installation (PEAR) for more details.

  • php-cgi.exe - CGI executable that can be used when running PHP on IIS via CGI or FastCGI.

  • php-win.exe - the PHP executable for executing PHP scripts without using a command line window (for example PHP applications that use Windows GUI).

  • php.exe - the PHP executable for executing PHP scripts within a command line interface (CLI).

  • php5apache2_2.dll - Apache 2.2.X module.

  • php5apache2_2_filter.dll - Apache 2.2.X filter.

Changing the php.ini file

After the php package content has been extracted, copy the php.ini-production into php.ini in the same folder. If necessary, it is also possible to place the php.ini into any other location of your choice but that will require additional configuration steps as described in PHP Configuration.

The php.ini file tells PHP how to configure itself, and how to work with the environment that it runs in. Here are a number of settings for the php.ini file that help PHP work better with Windows. Some of these are optional. There are many other directives that may be relevant to your environment - refer to the list of php.ini directives for more information.

Required directives:

  • extension_dir = <path to extension directory> - The extension_dir needs to point to the directory where PHP extensions files are stored. The path can be absolute (i.e. "C:\PHP\ext") or relative (i.e. ".\ext"). Extensions that are listed lower in the php.ini file need to be located in the extension_dir.

  • extension = xxxxx.dll - For each extension you wish to enable, you need a corresponding "extension=" directive that tells PHP which extensions in the extension_dir to load at startup time.

  • log_errors = On - PHP has an error logging facility that can be used to send errors to a file, or to a service (i.e. syslog) and works in conjunction with the error_log directive below. When running under IIS, the log_errors should be enabled, with a valid error_log.

  • error_log = <path to the error log file> - The error_log needs to specify the absolute, or relative path to the file where PHP errors should be logged. This file needs to be writable for the web server. The most common places for this file are in various TEMP directories, for example "C:\inetpub\temp\php-errors.log".

  • cgi.force_redirect = 0 - This directive is required for running under IIS. It is a directory security facility required by many other web servers. However, enabling it under IIS will cause the PHP engine to fail on Windows.

  • cgi.fix_pathinfo = 1 - This lets PHP access real path info following the CGI Spec. The IIS FastCGI implementation needs this set.

  • fastcgi.impersonate = 1 - FastCGI under IIS supports the ability to impersonate security tokens of the calling client. This allows IIS to define the security context that the request runs under.

  • fastcgi.logging = 0 - FastCGI logging should be disabled on IIS. If it is left enabled, then any messages of any class are treated by FastCGI as error conditions which will cause IIS to generate an HTTP 500 exception.

Optional directives

  • max_execution_time = ## - This directive tells PHP the maximum amount of time that it can spend executing any given script. The default for this is 30 seconds. Increase the value of this directive if PHP application take long time to execute.

  • memory_limit = ###M - The amount of memory available for the PHP process, in Megabytes. The default is 128, which is fine for most PHP applications. Some of the more complex ones might need more.

  • display_errors = Off - This directive tells PHP whether to include any error messages in the stream that it returns to the Web server. If this is set to "On", then PHP will send whichever classes of errors that you define with the error_reporting directive back to web server as part of the error stream. For security reasons it is recommended to set it to "Off" on production servers in order not to reveal any security sensitive information that is often included in the error messages.

  • open_basedir = <paths to directories, separated by semicolon>, e.g. openbasedir="C:\inetpub\wwwroot;C:\inetpub\temp". This directive specified the directory paths where PHP is allowed to perform file system operations. Any file operation outside of the specified paths will result in an error. This directive is especially useful for locking down the PHP installation in shared hosting environments to prevent PHP scripts from accessing any files outside of the web site's root directory.

  • upload_max_filesize = ###M and post_max_size = ###M - The maximum allowed size of an uploaded file and post data respectively. The values of these directives should be increased if PHP applications need to perform large uploads, such as for example photos or video files.

PHP is now setup on your system. The next step is to choose a web server, and enable it to run PHP. Choose a web server from the table of contents.

In addition to running PHP via a web server, PHP can run from the command line just like a .BAT script. See

Microsoft IIS

This section contains PHP installation instructions specific to Microsoft Internet Information Services (IIS).

  • Manually installing PHP on Microsoft IIS 5.1 and IIS 6.0
  • Manually installing PHP on Microsoft IIS 7.0 and later

Microsoft IIS 5.1 and IIS 6.0

This section contains instructions for manually setting up Internet Information Services (IIS) 5.1 and IIS 6.0 to work with PHP on Microsoft Windows XP and Windows Server 2003. For instructions on setting up IIS 7.0 and later versions on Windows Vista, Windows Server 2008, Windows 7 and Windows Server 2008 R2 refer to Microsoft IIS 7.0 and later.

Configuring IIS to process PHP requests

Download and install PHP in accordance to the instructions described in manual installation steps

Note:

Non-thread-safe build of PHP is recommended when using IIS. The non-thread-safe builds are available at » PHP for Windows: Binaries and Sources Releases.

Configure the CGI- and FastCGI-specific settings in php.ini file as shown below:

Example #2 CGI and FastCGI settings in php.ini

fastcgi.impersonate = 1
fastcgi.logging = 0
cgi.fix_pathinfo=1
cgi.force_redirect = 0

Download and install the » Microsoft FastCGI Extension for IIS 5.1 and 6.0. The extension is available for 32-bit and 64-bit platforms - select the right download package for your platform.

Configure the FastCGI extension to handle PHP-specific requests by running the command shown below. Replace the value of the "-path" parameter with the absolute file path to the php-cgi.exe file.

Example #3 Configuring FastCGI extension to handle PHP requests

cscript %windir%\system32\inetsrv\fcgiconfig.js -add -section:"PHP" ^
-extension:php -path:"C:\PHP\php-cgi.exe"

This command will create an IIS script mapping for *.php file extension, which will result in all URLs that end with .php being handled by FastCGI extension. Also, it will configure FastCGI extension to use the executable php-cgi.exe to process the PHP requests.

Note:

At this point the required installation and configuration steps are completed. The remaining instructions below are optional but highly recommended for achieving optimal functionality and performance of PHP on IIS.

Impersonation and file system access

It is recommended to enable FastCGI impersonation in PHP when using IIS. This is controlled by the fastcgi.impersonate directive in php.ini file. When impersonation is enabled, PHP will perform all the file system operations on behalf of the user account that has been determined by IIS authentication. This ensures that even if the same PHP process is shared across different IIS web sites, the PHP scripts in those web sites will not be able to access each others' files as long as different user accounts are used for IIS authentication on each web site.

For example IIS 5.1 and IIS 6.0, in its default configuration, has anonymous authentication enabled with built-in user account IUSR_<MACHINE_NAME> used as a default identity. This means that in order for IIS to execute PHP scripts, it is necessary to grant IUSR_<MACHINE_NAME> account read permission on those scripts. If PHP applications need to perform write operations on certain files or write files into some folders then IUSR_<MACHINE_NAME> account should have write permission to those.

To determine which user account is used by IIS anonymous authentication, follow these steps:

  1. In the Windows Start Menu choose "Run:", type "inetmgr" and click "Ok";

  2. Expand the list of web sites under the "Web Sites" node in the tree view, right-click on a web site that is being used and select "Properties";

  3. Click the "Directory Security" tab;

  4. Take note of a "User name:" field in the "Authentication Methods" dialog

Anonymous authenication for IIS 5.1 and IIS 6.0

To modify the permissions settings on files and folders, use the Windows Explorer user interface or icacls command.

Example #4 Configuring file access permissions

icacls C:\inetpub\wwwroot\upload /grant IUSR:(OI)(CI)(M)

Set index.php as a default document in IIS

The IIS default documents are used for HTTP requests that do not specify a document name. With PHP applications, index.php usually acts as a default document. To add index.php to the list of IIS default documents, follow these steps:

  1. In the Windows Start Menu choose "Run:", type "inetmgr" and click "Ok";

  2. Right-click on the "Web Sites" node in the tree view and select "Properties";

  3. Click the "Documents" tab;

  4. Click the "Add..." button and enter "index.php" for the "Default content page:".

Setting index.php as default document for IIS

FastCGI and PHP Recycling configuration

Configure IIS FastCGI extension settings for recycling of PHP processes by using the commands shown below. The FastCGI setting instanceMaxRequests controls how many requests will be processed by a single php-cgi.exe process before FastCGI extension shuts it down. The PHP environment variable PHP_FCGI_MAX_REQUESTS controls how many requests a single php-cgi.exe process will handle before it recycles itself. Make sure that the value specified for FastCGI InstanceMaxRequests setting is less than or equal to the value specified for PHP_FCGI_MAX_REQUESTS.

Example #5 Configuring FastCGI and PHP recycling

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^
-InstanceMaxRequests:10000

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^
-EnvironmentVars:PHP_FCGI_MAX_REQUESTS:10000

Configuring FastCGI timeout settings

Increase the timeout settings for FastCGI extension if there are applications that have long running PHP scripts. The two settings that control timeouts are ActivityTimeout and RequestTimeout. Refer to » Configuring FastCGI Extension for IIS 6.0 for more information about those settings.

Example #6 Configuring FastCGI timeout settings

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^
-ActivityTimeout:90

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^
-RequestTimeout:90

Changing the Location of php.ini file

PHP searches for php.ini file in several locations and it is possible to change the default locations of php.ini file by using PHPRC environment variable. To instruct PHP to load the configuration file from a custom location run the command shown below. The absolute path to the directory with php.ini file should be specified as a value of PHPRC environment variable.

Example #7 Changing the location of php.ini file

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^
-EnvironmentVars:PHPRC:"C:\Some\Directory\"

Microsoft IIS 7.0 and later

This section contains instructions for manually setting up Internet Information Services (IIS) 7.0 and later to work with PHP on Microsoft Windows Vista SP1, Windows 7, Windows Server 2008 and Windows Server 2008 R2. For instructions on setting up IIS 5.1 and IIS 6.0 on Windows XP and Windows Server 2003 refer to Microsoft IIS 5.1 and IIS 6.0.

Enabling FastCGI support in IIS

FastCGI module is disabled in default installation of IIS. The steps to enable it differ based on the version of Windows being used.

To enable FastCGI support on Windows Vista SP1 and Windows 7:

  1. In the Windows Start Menu choose "Run:", type "optionalfeatures.exe" and click "Ok";

  2. In the "Windows Features" dialog expand "Internet Information Services", "World Wide Web Services", "Application Development Features" and then enable the "CGI" checkbox;

  3. Click OK and wait until the installation is complete.

Enabling FastCGI support for IIS7 on Windows Vista SP1 and Windows 7

To enable FastCGI support on Windows Server 2008 and Windows Server 2008 R2:

  1. In the Windows Start Menu choose "Run:", type "CompMgmtLauncher" and click "Ok";

  2. If the "Web Server (IIS)" role is not present under the "Roles" node, then add it by clicking "Add Roles";

  3. If the "Web Server (IIS)" role is present, then click "Add Role Services" and then enable the "CGI" checkbox under "Application Development" group;

  4. Click "Next" and then "Install" and wait for the installation to complete.

Enabling FastCGI support on Windows Server 2008 and Windows Server 2008 R2

Configuring IIS to process PHP requests

Download and install PHP in accordance to the instructions described in manual installation steps

Note:

Non-thread-safe build of PHP is recommended when using IIS. The non-thread-safe builds are available at » PHP for Windows: Binaries and Sources Releases.

Configure the CGI- and FastCGI-specific settings in php.ini file as shown below:

Example #8 CGI and FastCGI settings in php.ini

fastcgi.impersonate = 1
fastcgi.logging = 0
cgi.fix_pathinfo=1
cgi.force_redirect = 0

Configure IIS handler mapping for PHP by using either IIS Manager user interface or a command line tool.

Using IIS Manager user interface to create a handler mapping for PHP

Follow these steps to create an IIS handler mapping for PHP in IIS Manager user interface:

  1. In the Windows Start Menu choose "Run:", type "inetmgr" and click "Ok";

  2. In the IIS Manager user interface select the server node in the "Connections" tree view;

  3. In the "Features View" page open the "Handler Mappings" feature;

    Create IIS handler mapping for PHP : Locate Handler Mappings

  4. In the "Actions" pane click "Add Module Mapping...";

  5. In the "Add Module Mapping" dialog enter the following:

    • Request path: *.php
    • Module: FastCgiModule
    • Executable: C:\[Path to PHP installation]\php-cgi.exe
    • Name: PHP_via_FastCGI

  6. Click "Request Restrictions" button and then configure the mapping to invoke handler only if request is mapped to a file or a folder;

  7. Click OK on all the dialogs to save the configuration.

Create IIS handler mapping for PHP : Add Handler Mapping

Using command line tool to create a handler mapping for PHP

Use the command shown below to create an IIS FastCGI process pool which will use php-cgi.exe executable for processing PHP requests. Replace the value of the fullPath parameter with the absolute file path to the php-cgi.exe file.

Example #9 Creating IIS FastCGI process pool

%windir%\system32\inetsrv\appcmd set config /section:system.webServer/fastCGI ^
/+[fullPath='c:\PHP\php-cgi.exe']

Configure IIS to handle PHP specific requests by running the command shown below. Replace the value of the scriptProcessor parameter with the absolute file path to the php-cgi.exe file.

Example #10 Creating handler mapping for PHP requests

%windir%\system32\inetsrv\appcmd set config /section:system.webServer/handlers ^
/+[name='PHP_via_FastCGI', path='*.php',verb='*',modules='FastCgiModule',^
scriptProcessor='c:\PHP\php-cgi.exe',resourceType='Either']

This command creates an IIS handler mapping for *.php file extension, which will result in all URLs that end with .php being handled by FastCGI module.

Note:

At this point the required installation and configuration steps are completed. The remaining instructions below are optional but highly recommended for achieving optimal functionality and performance of PHP on IIS.

Impersonation and file system access

It is recommended to enable FastCGI impersonation in PHP when using IIS. This is controlled by the fastcgi.impersonate directive in php.ini file. When impersonation is enabled, PHP will perform all the file system operations on behalf of the user account that has been determined by IIS authentication. This ensures that even if the same PHP process is shared across different IIS web sites, the PHP scripts in those web sites will not be able to access each other's files as long as different user accounts are used for IIS authentication on each web site.

For example IIS 7, in its default configuration, has anonymous authentication enabled with built-in user account IUSR used as a default identity. This means that in order for IIS to execute PHP scripts, it is necessary to grant IUSR account read permission on those scripts. If PHP applications need to perform write operations on certain files or write files into some folders then IUSR account should have write permission to those.

To determine what user account is used as an anonymous identity in IIS 7 use the following command. Replace the "Default Web Site" with the name of IIS web site that you use. In the output XML configuration element look for the userName attribute.

Example #11 Determining the account used as IIS anonymous identity

%windir%\system32\inetsrv\appcmd.exe list config "Default Web Site" ^
/section:anonymousAuthentication

<system.webServer>
  <security>
    <authentication>
      <anonymousAuthentication enabled="true" userName="IUSR" />
    </authentication>
   </security>
</system.webServer>

Note:

If userName attribute is not present in the anonymousAuthentication element, or is set to an empty string, then it means that the application pool identity is used as an anonymous identity for that web site.

To modify the permissions settings on files and folders, use the Windows Explorer user interface or icacls command.

Example #12 Configuring file access permissions

icacls C:\inetpub\wwwroot\upload /grant IUSR:(OI)(CI)(M)

Set index.php as a default document in IIS

The IIS default documents are used for HTTP requests that do not specify a document name. With PHP applications, index.php usually acts as a default document. To add index.php to the list of IIS default documents, use this command:

Example #13 Set index.php as a default document in IIS

%windir%\system32\inetsrv\appcmd.exe set config ^
-section:system.webServer/defaultDocument /+"files.[value='index.php']" ^
/commit:apphost

FastCGI and PHP Recycling configuration

Configure IIS FastCGI settings for recycling of PHP processes by using the commands shown below. The FastCGI setting instanceMaxRequests controls how many requests will be processed by a single php-cgi.exe process before IIS shuts it down. The PHP environment variable PHP_FCGI_MAX_REQUESTS controls how many requests a single php-cgi.exe process will handle before it recycles itself. Make sure that the value specified for FastCGI InstanceMaxRequests setting is less than or equal to the value specified for PHP_FCGI_MAX_REQUESTS.

Example #14 Configuring FastCGI and PHP recycling

%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^
/[fullPath='c:\php\php-cgi.exe'].instanceMaxRequests:10000

%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^
/+"[fullPath='C:\{php_folder}\php-cgi.exe'].environmentVariables.^
[name='PHP_FCGI_MAX_REQUESTS',value='10000']"

FastCGI timeout settings

Increase the timeout settings for FastCGI if it is expected to have long running PHP scripts. The two settings that control timeouts are activityTimeout and requestTimeout. Use the commands below to change the timeout settings. Make sure to replace the value in the fullPath parameter to contain the absolute path to the php-cgi.exe file.

Example #15 Configuring FastCGI timeout settings

%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^
/[fullPath='C:\php\php-cgi.exe',arguments=''].activityTimeout:"90"  /commit:apphost

%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^
/[fullPath='C:\php\php-cgi.exe',arguments=''].requestTimeout:"90"  /commit:apphost

Changing the Location of php.ini file

PHP searches for php.ini file in several locations and it is possible to change the default locations of php.ini file by using PHPRC environment variable. To instruct PHP to load the configuration file from a custom location run the command shown below. The absolute path to the directory with php.ini file should be specified as a value of PHPRC environment variable.

Example #16 Changing the location of php.ini file

appcmd.exe set config  -section:system.webServer/fastCgi ^
/+"[fullPath='C:\php\php.exe',arguments=''].environmentVariables.^
[name='PHPRC',value='C:\Some\Directory\']" /commit:apphost

Apache 1.3.x on Microsoft Windows

This section contains notes and hints specific to Apache 1.3.x installs of PHP on Microsoft Windows systems. There are also

Note:

Please read the manual installation steps first!

There are two ways to set up PHP to work with Apache 1.3.x on Windows. One is to use the CGI binary (php.exe for PHP 4 and php-cgi.exe for PHP 5), the other is to use the Apache Module DLL. In either case you need to edit your httpd.conf to configure Apache to work with PHP, and then restart the server.

It is worth noting here that now the SAPI module has been made more stable under Windows, we recommend it's use above the CGI binary, since it is more transparent and secure.

Although there can be a few variations of configuring PHP under Apache, these are simple enough to be used by the newcomer. Please consult the Apache Documentation for further configuration directives.

After changing the configuration file, remember to restart the server, for example, NET STOP APACHE followed by NET START APACHE, if you run Apache as a Windows Service, or use your regular shortcuts.

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

Installing as an Apache module

You should add the following lines to your Apache httpd.conf file:

Example #17 PHP as an Apache 1.3.x module

This assumes PHP is installed to c:\php. Adjust the path if this is not the case.

For PHP 4:

# Add to the end of the LoadModule section
# Don't forget to copy this file from the sapi directory!
LoadModule php4_module "C:/php/php4apache.dll"

# Add to the end of the AddModule section
AddModule mod_php4.c

For PHP 5:

# Add to the end of the LoadModule section
LoadModule php5_module "C:/php/php5apache.dll"

# Add to the end of the AddModule section
AddModule mod_php5.c

For both:

# Add this line inside the <IfModule mod_mime.c> conditional brace
AddType application/x-httpd-php .php

# For syntax highlighted .phps files, also add
AddType application/x-httpd-php-source .phps

Installing as a CGI binary

If you unzipped the PHP package to C:\php\ as described in the Manual Installation Steps section, you need to insert these lines to your Apache configuration file to set up the CGI binary:

Example #18 PHP and Apache 1.3.x as CGI

ScriptAlias /php/ "c:/php/"
AddType application/x-httpd-php .php

# For PHP 4
Action application/x-httpd-php "/php/php.exe"

# For PHP 5
Action application/x-httpd-php "/php/php-cgi.exe"

# specify the directory where php.ini is
SetEnv PHPRC C:/php
Note that the second line in the list above can be found in the actual versions of httpd.conf, but it is commented out. Remember also to substitute the c:/php/ for your actual path to PHP.

Warning

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

If you would like to present PHP source files syntax highlighted, there is no such convenient option as with the module version of PHP. If you chose to configure Apache to use PHP as a CGI binary, you will need to use the highlight_file() function. To do this simply create a PHP script file and add this code: <?php highlight_file('some_php_script.php'); ?>.

Apache 2.x on Microsoft Windows

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

Note:

You should read the manual installation steps first!

Note: Apache 2.2 Support

Users of Apache 2.2 should note that the DLL file for Apache 2.2 is named php5apache2_2.dll rather than php5apache2.dll and is available only for PHP 5.2.0 and later.

You are strongly encouraged to consult the » Apache Documentation to get a basic understanding of the Apache 2.x Server. Also consider reading the » Windows specific notes for Apache 2.x before reading on here.

Apache 2.x is designed to run on the Windows version designated as server platforms, such as Windows NT 4.0, Windows 2000, Windows XP, or Windows 7. While Apache 2.x works tolerably well on Windows 9x, support on these platforms is incomplete, and some things will not work correctly. There is no plan to remedy this situation.

Download the most recent version of » Apache 2.x and a fitting PHP version. Follow the Manual Installation Steps and come back to go on with the integration of PHP and Apache.

There are three ways to set up PHP to work with Apache 2.x on Windows. You can run PHP as a handler, as a CGI, or under FastCGI.

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

Installing as an Apache handler

You need to insert the following lines into your Apache httpd.conf configuration file to load the PHP module for Apache 2.x:

Example #19 PHP and Apache 2.x as handler

#
LoadModule php5_module "c:/php/php5apache2.dll"
AddHandler application/x-httpd-php .php

# configure the path to php.ini
PHPIniDir "C:/php"

Note: Remember to substitute your actual path to PHP for the C:/php/ in the above examples. Take care to use either php5apache2.dll or php5apache2_2.dll in your LoadModule directive and verify that the referenced file is in fact located at the file path that you point to in this directive.

The above configuration will enable PHP handling of any file that has a .php extension, even if there are other file extensions. For example, a file named example.php.txt will be executed by the PHP handler. To ensure that only files that end in .php are executed, use the following configuration instead:

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

Running PHP as CGI

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

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

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

Example #20 PHP and Apache 2.x as CGI

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

Warning

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

Running PHP under FastCGI

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

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

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

Example #21 Configure Apache to run PHP as FastCGI

LoadModule fcgid_module modules/mod_fcgid.so

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

AddHandler fcgid-script .php
FcgidWrapper "c:/php/php-cgi.exe" .php
Files with a .php extension will now be executed by the PHP FastCGI wrapper.

Sun, iPlanet and Netscape servers on Microsoft Windows

This section contains notes and hints specific to Sun Java System Web Server, Sun ONE Web Server, iPlanet and Netscape server installs of PHP on Windows.

From PHP 4.3.3 on you can use PHP scripts with the NSAPI module to Apache compatibility are also available. For support in current web servers

CGI setup on Sun, iPlanet and Netscape servers

To install PHP as a CGI handler, do the following:

  • Copy php4ts.dll to your systemroot (the directory where you installed Windows)

  • Make a file association from the command line. Type the following two lines:

    assoc .php=PHPScript
ftype PHPScript=c:\php\php.exe %1 %*

  • In the Netscape Enterprise Administration Server create a dummy shellcgi directory and remove it just after (this step creates 5 important lines in obj.conf and allow the web server to handle shellcgi scripts).
  • In the Netscape Enterprise Administration Server create a new mime type (Category: type, Content-Type: magnus-internal/shellcgi, File Suffix:php).
  • Do it for each web server instance you want PHP to run

More details about setting up PHP as a CGI executable can be found here: » http://benoit.noss.free.fr/php/install-php.html

NSAPI setup on Sun, iPlanet and Netscape servers

To install PHP with NSAPI, do the following:

  • Copy php4ts.dll to your systemroot (the directory where you installed Windows)

  • Make a file association from the command line. Type the following two lines:

    assoc .php=PHPScript
ftype PHPScript=c:\php\php.exe %1 %*

  • In the Netscape Enterprise Administration Server create a new mime type (Category: type, Content-Type: magnus-internal/x-httpd-php, File Suffix: php).

  • Edit magnus.conf (for servers >= 6) or obj.conf (for servers < 6) and add the following: You should place the lines after mime types init.

    Init fn="load-modules" funcs="php4_init,php4_execute,php4_auth_trans" shlib="c:/php/sapi/php4nsapi.dll"
Init fn="php4_init" LateInit="yes" errorString="Failed to initialise PHP!" [php_ini="c:/path/to/php.ini"]
    (PHP >= 4.3.3) The php_ini parameter is optional but with it you can place your php.ini in your web server configuration directory.

  • Configure the default object in obj.conf (for virtual server classes [Sun Web Server 6.0+] in their vserver.obj.conf): In the <Object name="default"> section, place this line necessarily after all 'ObjectType' and before all 'AddLog' lines:

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

  • This is only needed if you want to configure a directory that only consists of PHP scripts (same like a cgi-bin directory):

    <Object name="x-httpd-php">
ObjectType fn="force-type" type="magnus-internal/x-httpd-php"
Service fn=php4_execute [inikey=value inikey=value ...]
</Object>
    After that you can configure a directory in the Administration server and assign it the style x-httpd-php. All files in it will get executed as PHP. This is nice to hide PHP usage by renaming files to .html.

  • Restart your web service and apply changes
  • Do it for each web server instance you want PHP to run

Note:

More details about setting up PHP as an NSAPI filter can be found here: » http://benoit.noss.free.fr/php/install-php4.html

Note:

The stacksize that PHP uses depends on the configuration of the web server. If you get crashes with very large PHP scripts, it is recommended to raise it with the Admin Server (in the section "MAGNUS EDITOR").

CGI environment and recommended modifications in php.ini

Important when writing PHP scripts is the fact that Sun JSWS/Sun ONE WS/iPlanet/Netscape is a multithreaded web server. Because of that all requests are running in the same process space (the space of the web server itself) and this space has only one environment. If you want to get CGI variables like PATH_INFO, HTTP_HOST etc. it is not the correct way to try this in the old PHP way with getenv() or a similar way (register globals to environment, $_ENV). You would only get the environment of the running web server without any valid CGI variables!

Note:

Why are there (invalid) CGI variables in the environment?

Answer: This is because you started the web server process from the admin server which runs the startup script of the web server, you wanted to start, as a CGI script (a CGI script inside of the admin server!). This is why the environment of the started web server has some CGI environment variables in it. You can test this by starting the web server not from the administration server. Use the command line as root user and start it manually - you will see there are no CGI-like environment variables.

Simply change your scripts to get CGI variables in the correct way for PHP 4.x by using the superglobal $_SERVER. If you have older scripts which use $HTTP_HOST, etc., you should turn on register_globals in php.ini and change the variable order too (important: remove "E" from it, because you do not need the environment here):

variables_order = "GPCS"
register_globals = On

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

You can use PHP to generate the error pages for "404 Not Found" or similar. Add the following line to the object in obj.conf for every error page you want to overwrite:

Error fn="php4_execute" code=XXX script="/path/to/script.php" [inikey=value inikey=value...]
where XXX is the HTTP error code. Please delete any other Error directives which could interfere with yours. If you want to place a page for all errors that could exist, leave the code parameter out. Your script can get the HTTP status code with $_SERVER['ERROR_TYPE'].

Another possibility is to generate self-made directory listings. Just create a PHP script which displays a directory listing and replace the corresponding default Service line for type="magnus-internal/directory" in obj.conf with the following:

Service fn="php4_execute" type="magnus-internal/directory" script="/path/to/script.php" [inikey=value inikey=value...]
For both error and directory listing pages the original URI and translated URI are in the variables $_SERVER['PATH_INFO'] and $_SERVER['PATH_TRANSLATED'].

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

The NSAPI module now supports the nsapi_virtual() function (alias: virtual()) to make subrequests on the web server and insert the result in the web page. The problem is, that this function uses some undocumented features from the NSAPI library.

Under Unix this is not a problem, because the module automatically looks for the needed functions and uses them if available. If not, nsapi_virtual() is disabled.

Under Windows limitations in the DLL handling need the use of a automatic detection of the most recent ns-httpdXX.dll file. This is tested for servers till version 6.1. If a newer version of the Sun server is used, the detection fails and nsapi_virtual() is disabled.

If this is the case, try the following: Add the following parameter to php4_init in magnus.conf/obj.conf:

Init fn=php4_init ... server_lib="ns-httpdXX.dll"
where XX is the correct DLL version number. To get it, look in the server-root for the correct DLL name. The DLL with the biggest filesize is the right one.

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

Note:

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

Sambar Server on Microsoft Windows

This section contains notes and hints specific to the » Sambar Server for Windows.

Note:

You should read the manual installation steps first!

This list describes how to set up the ISAPI module to work with the Sambar server on Windows.

  • Find the file called mappings.ini (in the config directory) in the Sambar install directory.

  • Open mappings.ini and add the following line under [ISAPI]:

    Example #22 ISAPI configuration of Sambar

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

#for PHP 5
*.php = c:\php\php5isapi.dll
    (This line assumes that PHP was installed in c:\php.)

  • Now restart the Sambar server for the changes to take effect.

Note:

If you intend to use PHP to communicate with resources which are held on a different computer on your network, then you will need to alter the account used by the Sambar Server Service. The default account used for the Sambar Server Service is LocalSystem which will not have access to remote resources. The account can be amended by using the Services option from within the Windows Control Panel Administation Tools.

Xitami on Microsoft Windows

This section contains notes and hints specific to » Xitami on Windows.

Note:

You should read the manual installation steps first!

This list describes how to set up the PHP CGI binary to work with Xitami on Windows.

Note: Important for CGI users

Read the faq on cgi.force_redirect for important details. This directive needs to be set to 0. If you want to use $_SERVER['PHP_SELF'] you have to enable the cgi.fix_pathinfo directive.

Warning

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

  • Make sure the web server is running, and point your browser to xitamis admin console (usually http://127.0.0.1/admin), and click on Configuration.

  • Navigate to the Filters, and put the extension which PHP should parse (i.e. .php) into the field File extensions (.xxx).

  • In Filter command or script put the path and name of your PHP CGI executable i.e. C:\php\php.exe for PHP 4, or C:\php\php-cgi.exe for PHP 5.

  • Press the 'Save' icon.

  • Restart the server to reflect changes.

Building from source

This chapter teaches how to compile PHP from sources on windows, using Microsoft's tools. To compile PHP with cygwin, please refer to Installation on Unix systems.

See the Wiki documentation at: » https://wiki.php.net/internals/windows/stepbystepbuild

Installation of extensions on Windows

After installing PHP and a web server on Windows, you will probably want to install some extensions for added functionality. You can choose which extensions you would like to load when PHP starts by modifying your php.ini. You can also load a module dynamically in your script using dl().

The DLLs for PHP extensions are prefixed with php_.

Many extensions are built into the Windows version of PHP. This means additional DLL files, and the extension directive, are not used to load these extensions. The Windows PHP Extensions table lists extensions that require, or used to require, additional PHP DLL files. Here's a list of built in extensions (updated PHP 5.0.4): BCMath, Calendar, COM, Ctype, DOM, FTP, LibXML, Iconv, ODBC, PCRE, Session, SimpleXML, SPL, SQLite, WDDX, XML and Zlib.

The default location PHP searches for extensions is C:\php5. To change this setting to reflect your setup of PHP edit your php.ini file:

  • You will need to change the extension_dir setting to point to the directory where your extensions lives, or where you have placed your php_*.dll files. For example:

    extension_dir = C:\php\extensions

  • Enable the extension(s) in php.ini you want to use by uncommenting the extension=php_*.dll lines in php.ini. This is done by deleting the leading ; from the extension you want to load.

    Example #23 Enable Bzip2 extension for PHP-Windows

    // change the following line from ...
;extension=php_bz2.dll

// ... to
extension=php_bz2.dll

  • Some of the extensions need extra DLLs to work. Couple of them can be found in the distribution package, in the main folder, but some, for example Oracle (php_oci8.dll) require DLLs which are not bundled with the distribution package. Don't forget to include C:\php in the system PATH (this process is explained in a separate FAQ entry).

  • Some of these DLLs are not bundled with the PHP distribution. See each extensions documentation page for details. Also, read the manual section titled Installation of PECL extensions for details on PECL. An increasingly large number of PHP extensions are found in PECL, and these extensions require a separate download.

Note: If you are running a server module version of PHP remember to restart your web server to reflect your changes to php.ini.

The following table describes some of the extensions available and required additional dlls.

PHP Extensions
Extension | Description | Notes
php_bz2.dll | bzip2 compression functions | None
php_calendar.dll | Calendar conversion functions | None
php_crack.dll | Crack functions | None
php_ctype.dll | ctype family functions | None
php_curl.dll | CURL, Client URL library functions | Requires: libeay32.dll, ssleay32.dll (bundled), or, as of OpenSSL 1.1 libcrypto-*.dll and libssl-*.dll (bundled)
php_dba.dll | DBA: DataBase (dbm-style) Abstraction layer functions | None
php_dbase.dll | dBase functions | None
php_dbx.dll | dbx functions |
php_exif.dll | EXIF functions | php_mbstring.dll. And, php_exif.dll must be loaded after php_mbstring.dll in php.ini.
php_fbsql.dll | FrontBase functions | None
php_fdf.dll | FDF: Forms Data Format functions. | Requires: fdftk.dll (bundled)
php_filepro.dll | filePro functions | Read-only access
php_ftp.dll | FTP functions | None
php_gd2.dll | GD library image functions | GD2
php_gettext.dll | Gettext functions | PHP <= 4.2.0 requires gnu_gettext.dll (bundled), PHP >= 4.2.3 requires libintl-1.dll, iconv.dll (bundled).
php_hyperwave.dll | HyperWave functions | None
php_iconv.dll | ICONV characterset conversion | Requires: iconv-1.3.dll (bundled), iconv.dll
php_ifx.dll | Informix functions | Requires: Informix libraries
php_iisfunc.dll | IIS management functions | None
php_imap.dll | IMAP POP3 and NNTP functions | None
php_ingres.dll | Ingres functions | Requires: Ingres libraries
php_interbase.dll | InterBase functions | Requires: gds32.dll (bundled)
php_ldap.dll | LDAP functions | Requires libeay32.dll, ssleay32.dll (bundled), or, as of OpenSSL 1.1 libcrypto-*.dll and libssl-*.dll (bundled)
php_mbstring.dll | Multi-Byte String functions | None
php_mcrypt.dll | Mcrypt Encryption functions | Requires: libmcrypt.dll
php_mhash.dll | Mhash functions | Requires: libmhash.dll (bundled)
php_mime_magic.dll | Mimetype functions | Requires: magic.mime (bundled)
php_ming.dll | Ming functions for Flash | None
php_msql.dll | mSQL functions | Requires: msql.dll (bundled)
php_mssql.dll | MSSQL functions | Requires: ntwdblib.dll (bundled)
php_mysql.dll | MySQL functions | Requires libmysql.dll (bundled)
php_mysqli.dll | MySQLi functions | Requires libmysql.dll (libmysqli.dll in PHP <= 5.0.2) (bundled)
php_oci8.dll | Oracle 8 functions | Requires: Oracle 8.1+ client libraries
php_openssl.dll | OpenSSL functions | Requires: libeay32.dll (bundled), or, as of OpenSSL 1.1, liblibcrypto-*.dll (bundled)
php_pdf.dll | PDF functions | None
php_pgsql.dll | PostgreSQL functions | None
php_shmop.dll | Shared Memory functions | None
php_snmp.dll | SNMP get and walk functions | NT only!
php_soap.dll | SOAP functions | None
php_sockets.dll | Socket functions | None
php_sybase_ct.dll | Sybase functions | Requires: Sybase client libraries
php_tidy.dll | Tidy functions | None
php_tokenizer.dll | Tokenizer functions | None
php_w32api.dll | W32api functions | None
php_xmlrpc.dll | XML-RPC functions | Requires: iconv.dll (bundled)
php_xslt.dll | XSLT functions | Requires sablot.dll, expat.dll, iconv.dll (bundled).
php_yaz.dll | YAZ functions | Requires: yaz.dll (bundled)
php_zip.dll | Zip File functions | Read only access
php_zlib.dll | ZLib compression functions | None

Command Line PHP on Microsoft Windows

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

Note:

You should read the manual installation steps first!

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

C:\PHP5\php.exe -f "C:\PHP Scripts\script.php" -- -arg1 -arg2 -arg3

But there are some easy steps that can be followed to make this simpler. Some of these steps should already have been taken, but are repeated here to be able to provide a complete step-by-step sequence.

    Note:

    Both PATH and PATHEXT are important pre-existing system variables in Windows, and care should be taken to not overwrite either variable, only to add to them.

  • Append the location of the PHP executable (php.exe, php-win.exe or php-cli.exe depending upon your PHP version and display preferences) to the PATH environment variable. Read more about how to add your PHP directory to PATH in the corresponding FAQ entry.

  • Append the .PHP extension to the PATHEXT environment variable. This can be done at the same time as amending the PATH environment variable. Follow the same steps as described in the FAQ but amend the PATHEXT environment variable rather than the PATH environment variable.

    Note:

    The position in which you place the .PHP will determine which script or program is executed when there are matching filenames. For example, placing .PHP before .BAT will cause your script to run, rather than the batch file, if there is a batch file with the same name.

  • Associate the .PHP extension with a file type. This is done by running the following command:

    assoc .php=phpfile

  • Associate the phpfile file type with the appropriate PHP executable. This is done by running the following command:

    ftype phpfile="C:\PHP5\php.exe" -f "%1" -- %~2

Following these steps will allow PHP scripts to be run from any directory without the need to type the PHP executable or the .PHP extension and all parameters will be supplied to the script for processing.

The example below details some of the registry changes that can be made manually.

Example #24 Registry changes

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.php]
@="phpfile"
"Content Type"="application/php"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile]
@="PHP Script"
"EditFlags"=dword:00000000
"BrowserFlags"=dword:00000008
"AlwaysShowExt"=""

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\DefaultIcon]
@="C:\\PHP5\\php-win.exe,0"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell]
@="Open"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell\Open]
@="&Open"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell\Open\command]
@="\"C:\\PHP5\\php.exe\" -f \"%1\" -- %~2"

With these changes the same command can be written as:

"C:\PHP Scripts\script" -arg1 -arg2 -arg3
or, if your "C:\PHP Scripts" path is in the PATH environment variable:
script -arg1 -arg2 -arg3

Note:

There is a small problem if you intend to use this technique and use your PHP scripts as a command line filter, like the example below:

dir | "C:\PHP Scripts\script" -arg1 -arg2 -arg3
or
dir | script -arg1 -arg2 -arg3
You may find that the script simply hangs and nothing is output. To get this operational, you need to make another registry change.
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\Explorer]
"InheritConsoleHandles"=dword:00000001
Further information regarding this issue can be found in this » Microsoft Knowledgebase Article : 321788. 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 old Windows systems
  • Azure App Services »
  • PHP Manual
  • Installation and Configuration
  • Installation on Cloud Computing platforms

Installation on Cloud Computing platforms

Table of Contents

  • Azure App Services
  • Amazon EC2

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 it will on other Windows servers. Much of the knowledgebase is also portable, so see the Windows Troubleshooting Page too. However, the management interface for Azure App Services is different:

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

  • Kudu Dashboard: [your web site name].azurewebsites.net Then, the Kudu dashboard is » https://[your web site name].scm.azurewebsites.net/. The Dashboard gives you access to some debugging capabilities, file management and site extensions. Site extensions are an Azure mechanism to add extra programs, like PHP preview builds, to your web site.

  • 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 to php-cgi.exe file in your build.


  • « Azure App Services
  • FastCGI Process Manager (FPM) »
  • PHP Manual
  • Installation on Cloud Computing platforms
  • Amazon EC2

Amazon EC2

PHP installs on the » EC2 cloud platform.

See also the » AWS SDK for PHP.


FastCGI Process Manager (FPM)

Table of Contents

  • Installation
  • Configuration

FPM (FastCGI Process Manager) is an alternative PHP FastCGI implementation with some additional features (mostly) useful for heavy-loaded sites.

These features include:

  • advanced process management with graceful stop/start;

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

  • stdout and stderr logging;

  • emergency restart in case of accidental opcode cache destruction;

  • accelerated upload support;

  • "slowlog" - logging scripts (not just their names, but their PHP backtraces too, using ptrace and similar things to read remote process' execute_data) that are executed unusually slow;

  • fastcgi_finish_request() - special function to finish request and flush all data while continuing to do something time-consuming (video converting, stats processing etc.);

  • dynamic/static child spawning;

  • basic SAPI status info (similar to Apache mod_status);

  • php.ini-based config file.


Installation

Compiling from sources

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

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

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

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

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

  • --with-fpm-acl - Use POSIX Access Control Lists (default - no). Since PHP 5.6.5.


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 integer

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 boolean

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 boolean

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: Set open file descriptor rlimit for the master process.

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: select, pool, epoll, kqueue (*BSD), port (Solaris). Default value: not set (auto detection).

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 unlimited. Default value: -1.

listen.allowed_clients string

List of IPv4 addresses of FastCGI clients which are allowed to connect. Equivalent to the FCGI_WEB_SERVER_ADDRS environment variable in the original PHP FastCGI (5.2.2+). Makes sense only with a tcp listening socket. Each address must be separated by a comma. If this value is left blank, connections will be accepted from any ip address. Default value: any. IPv6 addresses are allowed since PHP 5.5.20 and 5.6.4.

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

listen.acl_groups string

See listen.acl_users. Value is a comma separated list of group names. Since PHP 5.6.5.

user string

Unix user of FPM processes. This option is mandatory.

group string

Unix group of FPM processes. If not set, the default user's group is used.

pm string

Choose how the process manager will control the number of child processes. Possible values: static, ondemand, dynamic. This option is mandatory.

static - the number of child processes is fixed (pm.max_children).

ondemand - the processes spawn on demand (when requested, as opposed to dynamic, where pm.start_servers are started when the service is started.

dynamic - the number of child processes is set dynamically based on the following directives: pm.max_children, pm.start_servers, pm.min_spare_servers, pm.max_spare_servers.

pm.max_children int

The number of child processes to be created when pm is set to static and the maximum number of child processes to be created when pm is set to dynamic. This option is mandatory.

This option sets the limit on the number of simultaneous requests that will be served. Equivalent to the ApacheMaxClients directive with mpm_prefork and to the PHP_FCGI_CHILDREN environment variable in the original PHP FastCGI.

pm.start_servers int

The number of child processes created on startup. Used only when pm is set to dynamic. Default Value: min_spare_servers + (max_spare_servers - min_spare_servers) / 2.

pm.min_spare_servers int

The desired minimum number of idle server processes. Used only when pm is set to dynamic. Also mandatory in this case.

pm.max_spare_servers int

The desired maximum number of idle server processes. Used only when pm is set to dynamic. Also mandatory in this case.

pm.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_path string

The URI to view the FPM status page. If this value is not set, no URI will be recognized as a status page. Default value: none.

ping.path string

The ping URI to call the monitoring page of FPM. If this value is not set, no URI will be recognized as a ping page. This could be used to test from outside that FPM is alive and responding. Please note that the value must start with a leading slash (/).

ping.response string

This directive may be used to customize the response to a ping request. The response is formatted as text/plain with a 200 response code. Default value: pong.

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 boolean

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_slowlog_timeout mixed

The timeout for serving a single request after which a PHP backtrace will be dumped to the 'slowlog' file. A value of '0' means 'Off'. Available units: s(econds)(default), m(inutes), h(ours), or d(ays). Default value: 0.

slowlog string

The log file for slow requests. Default value: #INSTALL_PREFIX#/log/php-fpm.log.slow.

rlimit_files int

Set open file descriptor rlimit 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 boolean

Redirect worker stdout and stderr into main error log. If not set, stdout and stderr will be redirected to /dev/null according to FastCGI specs. Default value: no.

decorate_workers_output boolean

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 boolean

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. Since PHP 5.4.27, 5.5.11, and 5.6.0. 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

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"

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 overriden with ini_set().

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

Example #2 set PHP settings in nginx.conf

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

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

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


Installation of PECL extensions

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

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

These instructions assume /your/phpsrcdir/ is the path to the PHP source distribution, and that extname is the name of the PECL extension. Adjust accordingly. These instructions also assume a familiarity with the » pear command. The information in the PEAR manual for the pear command also applies to the pecl command.

To be useful, a shared extension must be built, installed, and loaded. The methods described below provide you with various instructions on how to build and install the extensions, but they do not automatically load them. Extensions can be loaded by adding an extension directive to the php.ini file, or through the use of the dl() function.

When building PHP modules, it's important to have known-good versions of the required tools (autoconf, automake, libtool, etc.) See the » Anonymous Git Instructions for details on the required tools, and required versions.


Downloading PECL extensions

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 web site contains information about the different extensions that are offered by the PHP Development Team. The information available here includes: ChangeLog, release notes, requirements and other similar details.
  • pecl download extname PECL extensions that have releases listed on the PECL web site are available for download and installation using the » pecl command. Specific revisions may also be specified.
  • SVN Most PECL extensions also reside in SVN. A web-based view may be seen at » https://svn.php.net/viewvc/pecl/. To download straight from SVN, the following sequence of commands may be used:

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

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


Installing a PHP extension on Windows

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

To load an extension, you need to have it available as a ".dll" file on your system. All the extensions are automatically and periodically compiled by the PHP Group (see next section for the download).

To compile an extension into PHP, please refer to building from source documentation.

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

Where to find an extension?

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

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

However, if you need functionality not provided by any core extension, you may still be able to find one in PECL. The PHP Extension Community Library (PECL) is a repository for PHP Extensions, providing a directory of all known extensions and hosting facilities for downloading and development of PHP extensions.

If you have developed an extension for your own uses, you might want to think about hosting it on PECL so that others with the same needs can benefit from your time. A nice side effect is that you give them a good chance to give you feedback, (hopefully) thanks, bug reports and even fixes/patches. Before you submit your extension for hosting on PECL, please read » PECL submit.

Which extension to download?

Many times, you will find several versions of each DLL:

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

You should keep in mind that your extension settings should match all the settings of the PHP executable you are using. The following PHP script will tell you all about your PHP settings:

Example #1 phpinfo() call

<?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 your php.ini configuration file. Please note that many extensions are already present in your php.ini and that you only need to remove the semicolon to activate them.

Note that, on PHP version 7.2.0 and up, 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

; On PHP version 7.2 and up, prefer :
extension=extname
zend_extension=another_extension

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

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

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

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

Resolving problems

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

If you are using PHP from the command line (CLI), the extension loading error can be read directly on screen.

If you are using PHP with a web server, the location and format of the logs vary depending on your software. Please read your web server documentation to locate the logs, as it does not have anything to do with PHP itself.

Common problems are the location of the DLL, the value of the " extension_dir" setting inside php.ini and compile-time setting mismatches.

If the problem lies in a compile-time setting mismatch, you probably didn't download the right DLL. Try downloading again the extension with the right settings. Again, phpinfo() can be of great help.


Compiling shared PECL extensions with the pecl command

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

$ pecl install extname

This will download the source for extname, compile, and install extname.so into your extension_dir. extname.so may then be loaded via php.ini

By default, the pecl command will not install packages that are marked with the alpha or beta state. If no stable packages are available, you may install a beta package using the following command:

$ pecl install extname-beta

You may also install a specific version using this variant:

$ pecl install extname-0.1

Note:

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


Compiling shared PECL extensions with phpize

Sometimes, using the pecl installer is not an option. This could be because you're behind a firewall, or it could be because the extension you want to install is not available as a PECL compatible package, such as unreleased extensions from SVN. If you need to build such an extension, you can use the lower-level build tools to perform the build manually.

The phpize command is used to prepare the build environment for a PHP extension. In the following sample, the sources for an extension are in a directory named extname:

$ cd extname
$ phpize
$ ./configure
$ make
# make install

A successful install will have created extname.so and put it into the PHP extensions directory. You'll need to and adjust php.ini and add an extension=extname.so line before you can use the extension.

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

Execute phpize --help to display additional usage information.


php-config

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

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

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

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

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


Compiling PECL extensions statically into PHP

You might find that you need to build a PECL extension statically into your PHP binary. To do this, you'll need to place the extension source under the /your/phpsrcdir/ext/ directory and tell the PHP build system to regenerate its configure script.

$ cd /your/phpsrcdir/ext
$ pecl download extname
$ gzip -d < extname.tgz | tar -xvf -
$ mv extname-x.x.x extname

This will result in the following directory:

/your/phpsrcdir/ext/extname

From here, force PHP to rebuild the configure script, and then build PHP as normal:

$ cd /your/phpsrcdir
$ rm configure
$ ./buildconf --force
$ ./configure --help
$ ./configure --with-extname --enable-someotherext --with-foobar
$ make
$ make install

Note: To run the 'buildconf' script you need autoconf 2.13 and automake 1.4+ (newer versions of autoconf may work, but are not supported).

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

$ ./configure --help | grep extname


  • « Compiling PECL extensions statically into PHP
  • Read the FAQ »
  • PHP Manual
  • Installation and Configuration
  • Problems?

Problems?

Table of Contents

  • Read the FAQ
  • Other problems
  • Bug reports


Read the FAQ

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


Other problems

If you are still stuck, someone on the PHP installation mailing list may be able to help you. You should check out the archive first, in case someone already answered someone else who had the same problem as you. The archives are available from the support page on » https://www.php.net/support.php. To subscribe to the PHP installation mailing list, send an empty mail to » php-install-subscribe@lists.php.net. The mailing list address is » php-install@lists.php.net.

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


Bug reports

If you think you have found a bug in PHP, please report it. The PHP developers probably don't know about it, and unless you report it, chances are it won't be fixed. You can report bugs using the bug-tracking system at » https://bugs.php.net/. Please do not send bug reports in mailing list or personal letters. The bug system is also suitable to submit feature requests.

Read the » How to report a bug document before submitting any bug reports!


Runtime Configuration

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, php_ini parameter in NSAPI, PHP_INI_PATH environment variable in THTTPD)
  • The PHPRC environment variable. Before PHP 5.2.0, this was checked after the registry key mentioned below.
  • As of PHP 5.2.0, the location of the php.ini file can be set for different versions of PHP. The 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.

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

Example #1 php.ini Environment Variables

; PHP_MEMORY_LIMIT is taken from environment
memory_limit = ${PHP_MEMORY_LIMIT}

The php.ini directives handled by extensions are documented on the respective pages of the extensions themselves. A list of the core directives is available in the appendix. Not all PHP directives are necessarily documented in this manual: for a complete list of directives available in your PHP version, please read your well commented php.ini file. Alternatively, you may find » the latest php.ini from Git helpful too.

Example #2 php.ini example

; any text on a line after an unquoted semicolon (;) is ignored
[php] ; section markers (text within square brackets) are also ignored
; Boolean values can be set to either:
;    true, on, yes
; or false, off, no, none
register_globals = off
track_errors = yes

; you can enclose strings in double-quotes
include_path = ".:/usr/local/lib/php"

; backslashes are treated the same as any other character
include_path = ".;c:\php\lib"

Since PHP 5.1.0, it is possible to refer to existing .ini variables from within .ini files. Example: open_basedir = ${open_basedir} ":/new/dir".

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. In PHP 5.2.0 and later, 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.

Changelog

Version | Description
7.0.0 | Hash marks (#) are no longer recognized as comments.
5.3.0 | Hash marks (#) should no longer be used as comments and will throw a deprecation warning if used.
5.2.0 | The PHP_INI_SCAN_DIR environment variable can be set to override the scan directory set via the configure script.
5.1.0 | It is possible to refer to existing .ini variables from within .ini files.


.user.ini files

Since PHP 5.3.0, PHP includes support for configuration INI files on a per-directory basis. These files are processed only by the CGI/FastCGI SAPI. This functionality obsoletes the PECL htscanner extension. If you are 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 PHP_INI_PERDIR and PHP_INI_USER will be recognized in .user.ini-style INI files.

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

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

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


Where a configuration setting may be set

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

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

Definition of PHP_INI_* modes
Mode | Meaning
PHP_INI_USER | Entry can be set in user scripts (like with ini_set()) or in the Windows registry. Since PHP 5.3, entry can be set in .user.ini
PHP_INI_PERDIR | Entry can be set in php.ini, .htaccess, httpd.conf or .user.ini (since PHP 5.3)
PHP_INI_SYSTEM | Entry can be set in php.ini or httpd.conf
PHP_INI_ALL | Entry can be set anywhere


How to change configuration settings

Running PHP as an Apache module

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

There are several Apache directives that allow you to change the PHP configuration from within the Apache configuration files. For a listing of which directives are PHP_INI_ALL, PHP_INI_PERDIR, or PHP_INI_SYSTEM, have a look at the List of php.ini directives appendix.

php_value name value

Sets the value of the specified directive. Can be used only with PHP_INI_ALL and PHP_INI_PERDIR type directives. To clear a previously set value use none as the value.

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

php_flag name on|off

Used to set a boolean configuration directive. Can be used only with PHP_INI_ALL and PHP_INI_PERDIR type directives.

php_admin_value name value

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

php_admin_flag name on|off

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

Example #1 Apache configuration example

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

Caution

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

Changing PHP configuration via the Windows registry

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

Other interfaces to PHP

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

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


Language Reference

  • Basic syntax
    • PHP tags
    • Escaping from HTML
    • Instruction separation
    • Comments
  • Types
    • Introduction
    • Booleans
    • Integers
    • Floating point numbers
    • Strings
    • Arrays
    • Iterables
    • Objects
    • Resources
    • NULL
    • Callbacks / Callables
    • Pseudo-types and variables used in this documentation
    • Type Juggling
  • Variables
    • Basics
    • Predefined Variables
    • Variable scope
    • Variable variables
    • Variables From External Sources
  • Constants
    • Syntax
    • Magic constants
  • Expressions
  • Operators
    • Operator Precedence
    • Arithmetic Operators
    • Assignment Operators
    • Bitwise Operators
    • Comparison Operators
    • Error Control Operators
    • Execution Operators
    • Incrementing/Decrementing Operators
    • Logical Operators
    • String Operators
    • Array Operators
    • Type Operators
  • Control Structures
    • Introduction
    • if
    • else
    • elseif/else if
    • Alternative syntax for control structures
    • while
    • do-while
    • for
    • foreach
    • break
    • continue
    • switch
    • declare
    • return
    • require
    • include
    • require_once
    • include_once
    • goto
  • Functions
    • User-defined functions
    • Function arguments
    • Returning values
    • Variable functions
    • Internal (built-in) functions
    • Anonymous functions
  • Classes and Objects
    • Introduction
    • The Basics
    • Properties
    • 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
    • Type Hinting
    • Late Static Bindings
    • Objects and references
    • Object Serialization
    • Covariance and Contravariance
    • OOP Changelog
  • Namespaces
    • Namespaces overview
    • Defining namespaces
    • Declaring sub-namespaces
    • Defining multiple namespaces in the same file
    • Using namespaces: Basics
    • Namespaces and dynamic language features
    • namespace keyword and __NAMESPACE__ constant
    • Using namespaces: Aliasing/Importing
    • Global space
    • Using namespaces: fallback to global function/constant
    • Name resolution rules
    • FAQ: things you need to know about namespaces
  • Errors
    • Basics
    • Errors in PHP 7
  • Exceptions
    • Extending Exceptions
  • Generators
    • Generators overview
    • Generator syntax
    • Comparing generators with Iterator objects
  • References Explained
    • What References Are
    • What References Do
    • What References Are Not
    • Passing by Reference
    • Returning References
    • Unsetting References
    • Spotting References
  • Predefined Variables
    • Superglobals — Superglobals are 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 — HTTP GET variables
    • $_POST — HTTP POST variables
    • $_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_RAW_POST_DATA — Raw POST data
    • $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
    • Error
    • ArgumentCountError
    • ArithmeticError
    • AssertionError
    • DivisionByZeroError
    • CompileError
    • ParseError
    • TypeError
  • Predefined Interfaces and Classes
    • Traversable — The Traversable interface
    • Iterator — The Iterator interface
    • IteratorAggregate — The IteratorAggregate interface
    • Throwable
    • ArrayAccess — The ArrayAccess interface
    • Serializable — The Serializable interface
    • Closure — The Closure class
    • Generator — The Generator class
    • WeakReference — The WeakReference class
  • 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
    • CURL context options — CURL context option listing
    • Phar context options — Phar context option listing
    • MongoDB context options — MongoDB context option listing
    • Context parameters — Context parameter listing
    • Zip context options — Zip 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


Basic syntax

Table of Contents

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


PHP tags

When PHP parses a file, it looks for opening and closing tags, which are <?php and ?> which tell PHP to start and stop interpreting the code between them. Parsing in this manner allows PHP to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser.

PHP includes a short echo tag <?= which is a short-hand to the more verbose <?php echo.

PHP also allows for short open tag <? (which is discouraged since it is only available if enabled using the short_open_tag php.ini configuration file directive, or if PHP was configured with the --enable-short-tags option).

If a file contains only 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.

<?php
echo "Hello world";

// ... more code

echo "Last statement";

// the script ends here with no PHP closing tag

Changelog
Version | Description
7.0.0 | The ASP tags <%, %>, <%=, and the script tag <script language="php"> are removed from PHP.
5.4.0 | The tag <?= is always available regardless of the short_open_tag ini setting.


Escaping from HTML

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

<p>This is going to be ignored by PHP and displayed by the browser.</p>
<?php echo 'While this is going to be parsed.'; ?>
<p>This will also be ignored by PHP and displayed by the browser.</p>
This works as expected, because when the PHP interpreter hits the ?> closing tags, it simply starts outputting whatever it finds (except for an immediately following newline - see instruction separation) until it hits another opening tag unless in the middle of a conditional statement in which case the interpreter will determine the outcome of the conditional before making a decision of what to skip over. See the next example.

Using structures with conditions

Example #1 Advanced escaping using conditions

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

In PHP 5, there are up to five different pairs of opening and closing tags available in PHP, depending on how PHP is configured. Two of these, <?php ?> and <script language="php"> </script>, are always available. There is also the short echo tag <?= ?>, which is always available in PHP 5.4.0 and later.

The other two are short tags and ASP style tags. As such, while some people find short tags and ASP style tags convenient, they are less portable, and generally not recommended.

Note:

Also note that if you are embedding PHP within XML or XHTML you will need to use the <?php ?> tags to remain compliant with standards.

PHP 7 removes support for ASP tags and <script language="php"> tags. As such, we recommend only using <?php ?> and <?= ?> when writing PHP code to maximise compatibility.

Example #2 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 always enabled in PHP 5.4.0 and later, and is 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'; ?>

4.  <script language="php">
        echo 'some editors (like FrontPage) don\'t
              like processing instructions within these tags';
    </script>
    This syntax is removed in PHP 7.0.0.

5.  <% echo 'You may optionally use ASP-style tags'; %>
    Code within these tags <%= $variable; %> is a shortcut for this code <% echo $variable; %>
    Both of these syntaxes are removed in PHP 7.0.0.

Short tags (example three) are only available when they are enabled via the short_open_tag php.ini configuration file directive, or if PHP was configured with the --enable-short-tags option.

ASP style tags (example five) are only available when they are enabled via the asp_tags php.ini configuration file directive, and have been removed in PHP 7.0.0.

Note:

Using short tags should be avoided when developing applications or libraries that are meant for redistribution, or deployment on PHP servers which are not under your control, because short tags may not be supported on the target server. For portable, redistributable code, be sure not to use short tags.

Note:

In PHP 5.2 and earlier, the parser does not allow the <?php opening tag to be the only thing in a file. This is allowed as of PHP 5.3 provided there are one or more whitespace characters after the opening tag.

Note:

Starting with PHP 5.4, short echo tag <?= is always recognized and valid, regardless of the short_open_tag setting.


Instruction separation

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

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

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

<?php echo 'We omitted the last closing tag';

Note:

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


Comments

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

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

The "one-line" comment styles only comment to the end of the line or the current block of PHP code, whichever comes first. This means that HTML code after // ... ?> or # ... ?> WILL be printed: ?> breaks out of PHP mode and returns to HTML mode, and // or # cannot influence that. If the asp_tags configuration directive is enabled, it behaves the same with // %> and # %>. However, the </script> tag doesn't break out of PHP mode in a one-line comment.

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

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

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


Types

Table of Contents

  • Introduction
  • Booleans
  • Integers
  • Floating point numbers
  • Strings
  • Arrays
  • Iterables
  • Objects
  • Resources
  • NULL
  • Callbacks / Callables
  • Pseudo-types and variables used in this documentation
  • Type Juggling


Introduction

PHP supports ten primitive types.

Four scalar types:

  • boolean
  • integer
  • float (floating-point number, aka double)
  • string

Four compound types:

  • array
  • object
  • callable
  • iterable

And finally two special types:

  • resource
  • NULL

This manual also introduces some pseudo-types for readability reasons:

  • mixed
  • number
  • callback (aka callable)
  • array|object
  • void

And the pseudo-variable $....

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

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

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

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

<?php
$a_bool = TRUE;   // a boolean
$a_str  = "foo";  // a string
$a_str2 = 'foo';  // a string
$an_int = 12;     // an integer

echo gettype($a_bool); // prints out:  boolean
echo gettype($a_str);  // prints out:  string

// If this is an integer, increment it by four
if (is_int($an_int)) {
    $an_int += 4;
}

// If $a_bool is a string, print it out
// (does not print out anything)
if (is_string($a_bool)) {
    echo "String: $a_bool";
}
?>

To forcibly convert a variable to a certain type, either cast the variable or use the settype() function on it.

Note that a variable may be evaluated with different values in certain situations, depending on what type it is at the time. For more information, see the section on Type Juggling. The type comparison tables may also be useful, as they show examples of various type-related comparisons.


Booleans

This is the simplest type. A boolean expresses a truth value. It can be either TRUE or FALSE.

Syntax

To specify a boolean 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 boolean value is passed on to a control structure.

<?php
// == is an operator which tests
// equality and returns a boolean
if ($action == "show_version") {
    echo "The version is 1.23";
}

// this is not necessary...
if ($show_separators == TRUE) {
    echo "<hr>\n";
}

// ...because this can be used with exactly the same meaning:
if ($show_separators) {
    echo "<hr>\n";
}
?>

Converting to boolean

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

See also Type Juggling.

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

  • the boolean FALSE itself
  • the integers 0 and -0 (zero)
  • the floats 0.0 and -0.0 (zero)
  • the empty string, and the string "0"
  • an array with zero elements
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags

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

Warning

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

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


Integers

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

See also:

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

Syntax

Integers 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 integer.

Binary integer literals are available since PHP 5.4.0.

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

Example #1 Integer literals

<?php
$a = 1234; // decimal number
$a = 0123; // octal number (equivalent to 83 decimal)
$a = 0x1A; // hexadecimal number (equivalent to 26 decimal)
$a = 0b11111111; // binary number (equivalent to 255 decimal)
?>

Formally, the structure for integer literals is:

decimal     : [1-9][0-9]*
            | 0

hexadecimal : 0[xX][0-9a-fA-F]+

octal       : 0[0-7]+

binary      : 0[bB][01]+

integer     : decimal
            | hexadecimal
            | octal
            | binary

The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18, except on Windows prior to PHP 7, where it was always 32 bit. PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, maximum value using the constant PHP_INT_MAX since PHP 5.0.5, and minimum value using the constant PHP_INT_MIN since PHP 7.0.0.

Warning

Prior to PHP 7, if an invalid digit was given in an octal integer (i.e. 8 or 9), the rest of the number was ignored. Since PHP 7, a parse error is emitted.

Integer overflow

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

Example #2 Integer overflow on a 32-bit system

<?php
$large_number = 2147483647;
var_dump($large_number);                     // int(2147483647)

$large_number = 2147483648;
var_dump($large_number);                     // float(2147483648)

$million = 1000000;
$large_number =  50000 * $million;
var_dump($large_number);                     // float(50000000000)
?>

Example #3 Integer overflow on a 64-bit system

<?php
$large_number = 9223372036854775807;
var_dump($large_number);                     // int(9223372036854775807)

$large_number = 9223372036854775808;
var_dump($large_number);                     // float(9.2233720368548E+18)

$million = 1000000;
$large_number =  50000000000000 * $million;
var_dump($large_number);                     // float(5.0E+19)
?>

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

Note: As of PHP 7.0.0, the function intdiv() is available for integer division.

<?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 integer, use either the (int) or (integer) casts. However, in most cases the cast is not needed, since a value will be automatically converted if an operator, function or control structure requires an integer argument. A value can also be converted to integer with the intval() function.

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

See also Type Juggling.

From booleans

FALSE will yield 0 (zero), and TRUE will yield 1 (one).

From floating point numbers

When converting from float to integer, the number will be rounded towards zero.

If the float is beyond the boundaries of integer (usually +/- 2.15e+9 = 2^31 on 32-bit platforms and +/- 9.22e+18 = 2^63 on 64-bit platforms other than Windows), the result is undefined, since the float doesn't have enough precision to give an exact integer result. No warning, not even a notice will be issued when this happens!

Note:

As of PHP 7.0.0, instead of being undefined and platform-dependent, NaN and Infinity will always be zero when cast to integer.

Warning

Never cast an unknown fraction to integer, as this can sometimes lead to unexpected results.

<?php
echo (int) ( (0.1+0.7) * 10 ); // echoes 7!
?>

See also the warning about float precision.

From strings

See String conversion to numbers

From NULL

NULL is always converted to zero (0).

From other types

Caution

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


Floating point numbers

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

<?php
$a = 1.234;
$b = 1.2e3;
$c = 7E-10;
?>

Formally:

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

The size of a float is platform-dependent, although a maximum of 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

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

Comparing floats

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

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

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

<?php
$a = 1.23456789;
$b = 1.23456780;
$epsilon = 0.00001;

if(abs($a-$b) < $epsilon) {
    echo "true";
}
?>

NaN

Some numeric operations can result in a value represented by the constant NAN. This result represents an undefined or unrepresentable value in floating-point calculations. Any loose or strict comparisons of this value against any other value, including itself, 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 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: As of PHP 7.0.0, there are no particular restrictions regarding the length of a string on 64-bit builds. On 32-bit builds and in earlier versions, 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 (since PHP 5.3.0)

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.

<?php
echo 'this is a simple string';

echo 'You can also have embedded newlines in
strings this way as it is
okay to do';

// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I\'ll be back"';

// Outputs: You deleted C:\*.*?
echo 'You deleted C:\\*.*?';

// Outputs: You deleted C:\*.*?
echo 'You deleted C:\*.*?';

// Outputs: This will not expand: \n a newline
echo 'This will not expand: \n a newline';

// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
?>

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) (since PHP 5.2.5)
\e | escape (ESC or 0x1B (27) in ASCII) (since PHP 5.4.4)
\f | form feed (FF or 0x0C (12) in ASCII) (since PHP 5.2.5)
\\ | backslash
\$ | dollar sign
\" | double-quote
\[0-7]{1,3} | the sequence of characters matching the regular expression is a character in octal notation, which silently overflows to fit in a byte (e.g. "\400" === "\000")
\x[0-9A-Fa-f]{1,2} | the sequence of characters matching the regular expression is a character in hexadecimal notation
\u{[0-9A-Fa-f]+} | the sequence of characters matching the regular expression is a Unicode codepoint, which will be output to the string as that codepoint's UTF-8 representation (added in PHP 7.0.0)

As in single quoted strings, escaping any other character will result in the backslash being printed too. Before PHP 5.1.1, the backslash in \{$var} had not been printed.

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

Heredoc

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

The closing identifier must begin in the first column of the line. Also, the identifier must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore.

Warning

It is very important to note that the line with the closing identifier must contain no other characters, except a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by the local operating system. This is \n on UNIX systems, including 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 #1 Invalid example

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

Example #2 Valid example

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

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

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 #3 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 #4 Heredoc in arguments example

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

As of PHP 5.3.0, it's possible to initialize static variables and class properties/constants using the Heredoc syntax:

Example #5 Using Heredoc to initialize static values

<?php
// Static variables
function foo()
{
    static $bar = <<<LABEL
Nothing in here...
LABEL;
}

// Class properties/constants
class foo
{
    const BAR = <<<FOOBAR
Constant example
FOOBAR;

    public $baz = <<<FOOBAR
Property example
FOOBAR;
}
?>

Starting with PHP 5.3.0, the opening Heredoc identifier may optionally be enclosed in double quotes:

Example #6 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 parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping. It shares some features in common with the SGML <![CDATA[ ]]> construct, in that it declares a block of text which is not for parsing.

A nowdoc is identified with the same <<< sequence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<'EOT'. All the rules for heredoc identifiers also apply to nowdoc identifiers, especially those regarding the appearance of the closing identifier.

Example #7 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 #8 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 #9 Static data example

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

Note:

Nowdoc support was added in PHP 5.3.0.

Variable parsing

When a string is specified in double quotes or with heredoc, variables are parsed within it.

There are two types of syntax: a simple one and a complex one. The simple syntax is the most common and convenient. It provides a way to embed a variable, an array value, or an object property in a string with a minimum of effort.

The complex syntax can be recognised by the curly braces surrounding the expression.

Simple syntax

If a dollar sign ($) is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. Enclose the variable name in curly braces to explicitly specify the end of the name.

<?php
$juice = "apple";

echo "He drank some $juice juice.".PHP_EOL;
// Invalid. "s" is a valid character for a variable name, but the variable is $juice.
echo "He drank some juice made of $juices.";
// Valid. Explicitly specify the end of the variable name by enclosing it in braces:
echo "He drank some juice made of ${juice}s.";
?>

The above example will output:

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

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

Example #10 Simple syntax example

<?php
$juices = array("apple", "orange", "koolaid1" => "purple");

echo "He drank some $juices[0] juice.".PHP_EOL;
echo "He drank some $juices[1] juice.".PHP_EOL;
echo "He drank some $juices[koolaid1] juice.".PHP_EOL;

class people {
    public $john = "John Smith";
    public $jane = "Jane Smith";
    public $robert = "Robert Paulsen";

    public $smith = "Smith";
}

$people = new people();

echo "$people->john drank some $juices[0] juice.".PHP_EOL;
echo "$people->john then said hello to $people->jane.".PHP_EOL;
echo "$people->john's wife greeted $people->robert.".PHP_EOL;
echo "$people->robert greeted the two $people->smiths."; // Won't work
?>

The above example will output:

He drank some apple juice.
He drank some orange juice.
He drank some purple juice.
John Smith drank some apple juice.
John Smith then said hello to Jane Smith.
John Smith's wife greeted Robert Paulsen.
Robert Paulsen greeted the two .

As of PHP 7.1.0 also negative numeric indices are supported.

Example #11 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, you should use the complex syntax.

Complex (curly) syntax

This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.

Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$. Some examples to make it clear:

<?php
// Show all errors
error_reporting(E_ALL);

$great = 'fantastic';

// Won't work, outputs: This is { fantastic}
echo "This is { $great}";

// Works, outputs: This is fantastic
echo "This is {$great}";

// Works
echo "This square is {$square->width}00 centimeters broad.";

// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";

// Works
echo "This works: {$arr[4][3]}";

// This is wrong for the same reason as $foo[bar] is wrong  outside a string.
// In other words, it will still work, but only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
echo "This is wrong: {$arr[foo][3]}";

// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][3]}";

// Works.
echo "This works: " . $arr['foo'][3];

echo "This works too: {$obj->values[3]->name}";

echo "This is the value of the var named $name: {${$name}}";

echo "This is the value of the var named by the return value of getName(): {${getName()}}";

echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";

// Won't work, outputs: This is the return value of getName(): {getName()}
echo "This is the return value of getName(): {getName()}";
?>

It is also possible to access class properties using variables within strings using this syntax.

<?php
class foo {
    var $bar = 'I am bar.';
}

$foo = new foo();
$bar = 'bar';
$baz = array('foo', 'bar', 'baz', 'quux');
echo "{$foo->$bar}\n";
echo "{$foo->{$baz[1]}}\n";
?>

The above example will output:

I am bar.
I am bar.

Note:

Functions, method calls, static class variables, and class constants inside {$} work since PHP 5. However, the value accessed will be interpreted as the name of a variable in the scope in which the string is defined. Using single curly braces ({}) will not work for accessing the return values of functions or methods or the values of class constants or static class variables.

<?php
// Show all errors.
error_reporting(E_ALL);

class beers {
    const softdrink = 'rootbeer';
    public static $ale = 'ipa';
}

$rootbeer = 'A & W';
$ipa = 'Alexander Keith\'s';

// This works; outputs: I'd like an A & W
echo "I'd like an {${beers::softdrink}}\n";

// This works too; outputs: I'd like an Alexander Keith's
echo "I'd like an {${beers::$ale}}\n";
?>

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: Strings may also be accessed using braces, as in $str{42}, for the same purpose.

Warning

Writing to an out of range offset pads the string with spaces. Non-integer types are converted to integer. Illegal offset type emits E_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 #12 Some string examples

<?php
// Get the first character of a string
$str = 'This is a test.';
$first = $str[0];

// Get the third character of a string
$third = $str[2];

// Get the last character of a string.
$str = 'This is still a test.';
$last = $str[strlen($str)-1];

// Modify the last character of a string
$str = 'Look at the sea';
$str[strlen($str)-1] = 'e';

?>

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

Example #13 Differences between PHP 5.3 and PHP 5.4

<?php
$str = 'abc';

var_dump($str['1']);
var_dump(isset($str['1']));

var_dump($str['1.0']);
var_dump(isset($str['1.0']));

var_dump($str['x']);
var_dump(isset($str['x']));

var_dump($str['1x']);
var_dump(isset($str['1x']));
?>

Output of the above example in PHP 5.3:

string(1) "b"
bool(true)
string(1) "b"
bool(true)
string(1) "a"
bool(true)
string(1) "b"
bool(true)

Output of the above example in PHP 5.4:

string(1) "b"
bool(true)

Warning: Illegal string offset '1.0' in /tmp/t.php on line 7
string(1) "b"
bool(false)

Warning: Illegal string offset 'x' in /tmp/t.php on line 9
string(1) "a"
bool(false)
string(1) "b"
bool(false)

Note:

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

Note:

PHP 5.5 added support for accessing characters within string literals using [] or {}.

Useful functions and operators

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

There are a number of useful functions for string manipulation.

See the string functions section for general functions, and the 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 boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values.

An integer or float is converted to a string representing the number textually (including the exponent part for floats). Floating point numbers can be converted using exponential notation (4.1E+6).

Note:

The decimal point character is defined in the script's locale (category LC_NUMERIC). See the setlocale() function.

Arrays are always converted to the string "Array"; because of this, echo and print can not by themselves show the contents of an array. To view a single element, use a construction such as echo $arr['foo']. See below for tips on viewing the entire contents.

In order to convert objects to string 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.

String conversion to numbers

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

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

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.

<?php
$foo = 1 + "10.5";                // $foo is float (11.5)
$foo = 1 + "-1.3e3";              // $foo is float (-1299)
$foo = 1 + "bob-1.3e3";           // $foo is integer (1)
$foo = 1 + "bob3";                // $foo is integer (1)
$foo = 1 + "10 Small Pigs";       // $foo is integer (11)
$foo = 4 + "10.2 Little Piggies"; // $foo is float (14.2)
$foo = "10.0 pigs " + 1;          // $foo is float (11)
$foo = "10.0 pigs " + 1.0;        // $foo is float (11)
?>

For more information on this conversion, see the Unix manual page for strtod(3).

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

<?php
echo "\$foo==$foo; type is " . gettype ($foo) . "<br />\n";
?>

Do not expect to get the code of one character by converting it to integer, as is done in C. Use the ord() and chr() functions to convert between ASCII codes and characters.

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. This is the case of strcasecmp(), strtoupper() and ucfirst(). This means they can be used only with single-byte encodings, as long as the encoding is matched by the locale. For instance strtoupper("á") may return "Á" if the locale is correctly set and á is encoded with a single byte. If it is encoded in UTF-8, the correct result will not be returned and the resulting string may or may not be returned corrupted, depending on the current locale.
  • Finally, they may just assume the string is using a specific encoding, usually UTF-8. This is the case of most functions in the intl extension and in the PCRE extension (in the last case, only when the u modifier is used). Although this is due to their special purpose, the function utf8_decode() assumes a UTF-8 encoding and the function utf8_encode() assumes an ISO-8859-1 encoding.

Ultimately, this means writing correct programs using Unicode depends on carefully avoiding functions that will not work and that most likely will corrupt the data and using instead the functions that do behave correctly, generally from the intl and mbstring extensions. However, using functions that can handle Unicode encodings is just the beginning. No matter the functions the language provides, it is essential to know the Unicode specification. For instance, a program that assumes there is only uppercase and lowercase is making a wrong assumption.


Arrays

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

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

Syntax

Specifying with array()

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

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

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

As of PHP 5.4 you can also use the short array syntax, which replaces array() with [].

Example #1 A simple array

<?php
$array = array(
    "foo" => "bar",
    "bar" => "foo",
);

// as of PHP 5.4
$array = [
    "foo" => "bar",
    "bar" => "foo",
];
?>

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

Additionally the following key casts will occur:

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

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

Example #2 Type Casting and Overwriting example

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

The above example will output:

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

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

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

Example #3 Mixed integer and string keys

<?php
$array = array(
    "foo" => "bar",
    "bar" => "foo",
    100   => -100,
    -100  => 100,
);
var_dump($array);
?>

The above example will output:

array(4) {
  ["foo"]=>
  string(3) "bar"
  ["bar"]=>
  string(3) "foo"
  [100]=>
  int(-100)
  [-100]=>
  int(100)
}

The key is optional. If it is not specified, PHP will use the increment of the largest previously used integer key.

Example #4 Indexed arrays without key

<?php
$array = array("foo", "bar", "hello", "world");
var_dump($array);
?>

The above example will output:

array(4) {
  [0]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  [2]=>
  string(5) "hello"
  [3]=>
  string(5) "world"
}

It is possible to specify the key only for some elements and leave it out for others:

Example #5 Keys not on all elements

<?php
$array = array(
         "a",
         "b",
    6 => "c",
         "d",
);
var_dump($array);
?>

The above example will output:

array(4) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [6]=>
  string(1) "c"
  [7]=>
  string(1) "d"
}

As you can see the last value "d" was assigned the key 7. This is because the largest integer key before that was 6.

Accessing array elements with square bracket syntax

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

Example #6 Accessing array elements

<?php
$array = array(
    "foo" => "bar",
    42    => 24,
    "multi" => array(
         "dimensional" => array(
             "array" => "foo"
         )
    )
);

var_dump($array["foo"]);
var_dump($array[42]);
var_dump($array["multi"]["dimensional"]["array"]);
?>

The above example will output:

string(3) "bar"
int(24)
string(3) "foo"

Note:

Both square brackets and curly braces can be used interchangeably for accessing array elements (e.g. $array[42] and $array{42} will both do the same thing in the example above).

As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.

As of PHP 5.5 it is possible to array dereference an array literal.

Example #7 Array dereferencing

<?php
function getArray() {
    return array(1, 2, 3);
}

// on PHP 5.4
$secondElement = getArray()[1];

// previously
$tmp = getArray();
$secondElement = $tmp[1];

// or
list(, $secondElement) = getArray();
?>

Note:

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

Note:

Array dereferencing a scalar value which is not a string silently yields NULL, i.e. without issuing an error message.

Creating/modifying with square bracket syntax

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

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

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

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

To change a certain value, assign a new value to that element using its key. To remove a key/value pair, call the unset() function on it.

<?php
$arr = array(5 => 1, 12 => 2);

$arr[] = 56;    // This is the same as $arr[13] = 56;
                // at this point of the script

$arr["x"] = 42; // This adds a new element to
                // the array with key "x"

unset($arr[5]); // This removes the element from the array

unset($arr);    // This deletes the whole array
?>

Note:

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

Note that the maximum integer key used for this need not currently exist in the array. It need only have existed in the array at some time since the last time the array was re-indexed. The following example illustrates:

<?php
// Create a simple array.
$array = array(1, 2, 3, 4, 5);
print_r($array);

// Now delete every item, but leave the array itself intact:
foreach ($array as $i => $value) {
    unset($array[$i]);
}
print_r($array);

// Append an item (note that the new key is 5, instead of 0).
$array[] = 6;
print_r($array);

// Re-index:
$array = array_values($array);
$array[] = 7;
print_r($array);
?>

The above example will output:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
Array
(
)
Array
(
    [5] => 6
)
Array
(
    [0] => 6
    [1] => 7
)

Useful functions

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

Note:

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

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

$b = array_values($a);
// Now $b is array(0 => 'one', 1 =>'three')
?>

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

Array do's and don'ts

Why is $foo[bar] wrong?

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

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

This is wrong, but it works. The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes). 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 is deprecated as of PHP 7.2.0, and issues an error of level E_WARNING. Formerly, an error of level E_NOTICE has been issued.

Note: This does not mean to always quote the key. Do not quote keys which are constants or variables, as this will prevent PHP from interpreting them.

<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('html_errors', false);
// Simple array:
$array = array(1, 2);
$count = count($array);
for ($i = 0; $i < $count; $i++) {
    echo "\nChecking $i: \n";
    echo "Bad: " . $array['$i'] . "\n";
    echo "Good: " . $array[$i] . "\n";
    echo "Bad: {$array['$i']}\n";
    echo "Good: {$array[$i]}\n";
}
?>

The above example will output:

Checking 0:
Notice: Undefined index:  $i in /path/to/script.html on line 9
Bad:
Good: 1
Notice: Undefined index:  $i in /path/to/script.html on line 11
Bad:
Good: 1

Checking 1:
Notice: Undefined index:  $i in /path/to/script.html on line 9
Bad:
Good: 2
Notice: Undefined index:  $i in /path/to/script.html on line 11
Bad:
Good: 2

More examples to demonstrate this behaviour:

<?php
// Show all errors
error_reporting(E_ALL);

$arr = array('fruit' => 'apple', 'veggie' => 'carrot');

// Correct
print $arr['fruit'];  // apple
print $arr['veggie']; // carrot

// Incorrect.  This works but also throws a PHP error of level E_NOTICE because
// of an undefined constant named fruit
//
// Notice: Use of undefined constant fruit - assumed 'fruit' in...
print $arr[fruit];    // apple

// This defines a constant to demonstrate what's going on.  The value 'veggie'
// is assigned to a constant named fruit.
define('fruit', 'veggie');

// Notice the difference now
print $arr['fruit'];  // apple
print $arr[fruit];    // carrot

// The following is okay, as it's inside a string. Constants are not looked for
// within strings, so no E_NOTICE occurs here
print "Hello $arr[fruit]";      // Hello apple

// With one exception: braces surrounding arrays within strings allows constants
// to be interpreted
print "Hello {$arr[fruit]}";    // Hello carrot
print "Hello {$arr['fruit']}";  // Hello apple

// This will not work, and will result in a parse error, such as:
// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING'
// This of course applies to using superglobals in strings as well
print "Hello $arr['fruit']";
print "Hello $_GET['foo']";

// Concatenation is another option
print "Hello " . $arr['fruit']; // Hello apple
?>

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

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

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

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

<?php
$error_descriptions[E_ERROR]   = "A fatal error has occurred";
$error_descriptions[E_WARNING] = "PHP issued a warning";
$error_descriptions[E_NOTICE]  = "This is just an informal notice";
?>

Note that E_ERROR is also a valid identifier, just like bar in the first example. But the last example is in fact the same as writing:

<?php
$error_descriptions[1] = "A fatal error has occurred";
$error_descriptions[2] = "PHP issued a warning";
$error_descriptions[8] = "This is just an informal notice";
?>

because E_ERROR equals 1, etc.

So why is it bad then?

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

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

Converting to array

For any of the types integer, float, string, boolean and resource, converting a value to an array results in an array with a single element with index zero and the value of the scalar which was converted. In other words, (array)$scalarValue is exactly the same as array($scalarValue).

If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side. This can result in some unexpected behaviour:

<?php

class A {
    private $A; // This will become '\0A\0A'
}

class B extends A {
    private $A; // This will become '\0B\0A'
    public $AA; // This will become 'AA'
}

var_dump((array) new B());
?>

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

Converting NULL to an array results in an empty array.

Comparing

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

Examples

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

<?php
// This:
$a = array( 'color' => 'red',
            'taste' => 'sweet',
            'shape' => 'round',
            'name'  => 'apple',
            4        // key will be 0
          );

$b = array('a', 'b', 'c');

// . . .is completely equivalent with this:
$a = array();
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a['name']  = 'apple';
$a[]        = 4;        // key will be 0

$b = array();
$b[] = 'a';
$b[] = 'b';
$b[] = 'c';

// After the above code is executed, $a will be the array
// array('color' => 'red', 'taste' => 'sweet', 'shape' => 'round',
// 'name' => 'apple', 0 => 4), and $b will be the array
// array(0 => 'a', 1 => 'b', 2 => 'c'), or simply array('a', 'b', 'c').
?>

Example #8 Using array()

<?php
// Array as (property-)map
$map = array( 'version'    => 4,
              'OS'         => 'Linux',
              'lang'       => 'english',
              'short_tags' => true
            );

// strictly numerical keys
$array = array( 7,
                8,
                0,
                156,
                -10
              );
// this is the same as array(0 => 7, 1 => 8, ...)

$switching = array(         10, // key = 0
                    5    =>  6,
                    3    =>  7,
                    'a'  =>  4,
                            11, // key = 6 (maximum of integer-indices was 5)
                    '8'  =>  2, // key = 8 (integer!)
                    '02' => 77, // key = '02'
                    0    => 12  // the value 10 will be overwritten by 12
                  );

// empty array
$empty = array();
?>

Example #9 Collection

<?php
$colors = array('red', 'blue', 'green', 'yellow');

foreach ($colors as $color) {
    echo "Do you like $color?\n";
}

?>

The above example will output:

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

Changing the values of the array directly is possible by passing them by reference.

Example #10 Changing element in the loop

<?php
foreach ($colors as &$color) {
    $color = 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 #11 One-based index

<?php
$firstquarter  = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>

The above example will output:

Array
(
    [1] => 'January'
    [2] => 'February'
    [3] => 'March'
)

Example #12 Filling an array

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

Arrays are ordered. The order can be changed using various sorting functions. See the array functions section for more information. The count() function can be used to count the number of items in an array.

Example #13 Sorting an array

<?php
sort($files);
print_r($files);
?>

Because the value of an array can be anything, it can also be another array. This enables the creation of recursive and multi-dimensional arrays.

Example #14 Recursive and multi-dimensional arrays

<?php
$fruits = array ( "fruits"  => array ( "a" => "orange",
                                       "b" => "banana",
                                       "c" => "apple"
                                     ),
                  "numbers" => array ( 1,
                                       2,
                                       3,
                                       4,
                                       5,
                                       6
                                     ),
                  "holes"   => array (      "first",
                                       5 => "second",
                                            "third"
                                     )
                );

// Some examples to address values in the array above
echo $fruits["holes"][5];    // prints "second"
echo $fruits["fruits"]["a"]; // prints "orange"
unset($fruits["holes"][0]);  // remove "first"

// Create a new multi-dimensional array
$juices["apple"]["green"] = "good";
?>

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

<?php
$arr1 = array(2, 3);
$arr2 = $arr1;
$arr2[] = 4; // $arr2 is changed,
             // $arr1 is still array(2, 3)

$arr3 = &$arr1;
$arr3[] = 4; // now $arr1 and $arr3 are the same
?>


Iterables

Iterable is a pseudo-type introduced in PHP 7.1. It accepts any array or object implementing the Traversable interface. Both of these types are iterable using foreach and can be used with yield from within a generator.

Using Iterables

Iterable can be used as a parameter type to indicate that a function requires a set of values, but does not care about the form of the value set since it will be used with foreach. If a value is not an array or instance of Traversable, a TypeError will be thrown.

Example #1 Iterable parameter type example

<?php

function foo(iterable $iterable) {
    foreach ($iterable as $value) {
        // ...
    }
}

?>

Parameters declared as iterable may use NULL or an array as a default value.

Example #2 Iterable parameter default value example

<?php

function foo(iterable $iterable = []) {
    // ...
}

?>

Iterable can also be used as a return type to indicate a function will return an iterable value. If the returned value is not an array or instance of Traversable, a TypeError will be thrown.

Example #3 Iterable return type example

<?php

function bar(): iterable {
    return [1, 2, 3];
}

?>

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

Example #4 Iterable generator return type example

<?php

function gen(): iterable {
    yield 1;
    yield 2;
    yield 3;
}

?>

Iterable Type Variance

Classes extending/implementing may broaden methods using array or Traversable as parameter types to iterable or narrow return types from iterable to array or Traversable.

Example #5 Iterable type variance example

<?php

interface Example {
    public function method(array $array): iterable;
}

class ExampleImplementation implements Example {
    public function method(iterable $iterable): array {
        // Parameter broadened and return type narrowed.
    }
}

?>


Objects

Object Initialization

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

<?php
class foo
{
    function do_foo()
    {
        echo "Doing foo.";
    }
}

$bar = new foo;
$bar->do_foo();
?>

For a full discussion, see the Classes and Objects chapter.

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.

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

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

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


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.


NULL

The special NULL value represents a variable with no value. NULL is the only possible value of type null.

A variable is considered to be null if:

  • it has been assigned the constant NULL.

  • it has not been set to any value yet.

  • it has been unset().

Syntax

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

<?php
$var = NULL;
?>

See also the functions is_null() and unset().

Casting to NULL

Warning

This feature has been DEPRECATED as of PHP 7.2.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.


Callbacks / Callables

Callbacks can be denoted by callable type hint as of PHP 5.4. This documentation used callback type information for the same purpose.

Some functions like call_user_func() or usort() accept user-defined callback functions as a parameter. Callback functions can not only be simple functions, but also object methods, including static class methods.

Passing

A PHP function is passed by its name as a string. Any built-in
or user-defined function can be used, except language constructs such as:
array(), echo,
empty(), eval(),
exit(), isset(),
list(), print or
unset().

A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1. Accessing protected and private methods from within a class is allowed.

Static class methods can also be passed without instantiating an object of that class by passing the class name instead of an object at index 0. As of PHP 5.2.3, it is also possible to pass 'ClassName::methodName'.

Apart from common user-defined function, anonymous functions can also be passed to a callback parameter.

Example #1 Callback function examples

<?php

// An example callback function
function my_callback_function() {
    echo 'hello world!';
}

// An example callback method
class MyClass {
    static function myCallbackMethod() {
        echo 'Hello World!';
    }
}

// Type 1: Simple callback
call_user_func('my_callback_function');

// Type 2: Static class method call
call_user_func(array('MyClass', 'myCallbackMethod'));

// Type 3: Object method call
$obj = new MyClass();
call_user_func(array($obj, 'myCallbackMethod'));

// Type 4: Static class method call (As of PHP 5.2.3)
call_user_func('MyClass::myCallbackMethod');

// Type 5: Relative static class method call (As of PHP 5.3.0)
class A {
    public static function who() {
        echo "A\n";
    }
}

class B extends A {
    public static function who() {
        echo "B\n";
    }
}

call_user_func(array('B', 'parent::who')); // A

// Type 6: Objects implementing __invoke can be used as callables (since PHP 5.3)
class C {
    public function __invoke($name) {
        echo 'Hello ', $name, "\n";
    }
}

$c = new C();
call_user_func($c, 'PHP!');
?>

Example #2 Callback example using a Closure

<?php
// Our closure
$double = function($a) {
    return $a * 2;
};

// This is our range of numbers
$numbers = range(1, 5);

// Use the closure as a callback here to
// double the size of each element in our
// range
$new_numbers = array_map($double, $numbers);

print implode(' ', $new_numbers);
?>

The above example will output:

2 4 6 8 10

Note:

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.


Pseudo-types and variables used in this documentation

Pseudo-types are keywords used in the PHP documentation to specify the types or values an argument can have. Please note that they are not primitives of the PHP language. So you cannot use pseudo-types as typehints in your own custom functions.

mixed

mixed indicates that a parameter may accept multiple (but not necessarily all) types.

gettype() for example will accept all PHP types, while str_replace() will accept strings and arrays.

number

number indicates that a parameter can be either integer or float.

callback

callback pseudo-types was used in this documentation before callable type hint was introduced by PHP 5.4. It means exactly the same.

array|object

array|object indicates that a parameter can be either array or object.

void

void as a return type means that the return value is useless. void in a parameter list means that the function doesn't accept any parameters. As of PHP 7.1 void is accepted as a function return type hint.

...

$... in function prototypes means and so on. This variable name is used when a function can take an endless number of arguments.


Type Juggling

PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used. That is to say, if a string value is assigned to variable $var, $var becomes a string. If an integer value is then assigned to $var, it becomes an integer.

An example of PHP's automatic type conversion is the multiplication operator '*'. If either operand is a float, then both operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does not change the types of the operands themselves; the only change is in how the operands are evaluated and what the type of the expression itself is.

<?php
$foo = "1";  // $foo is string (ASCII 49)
$foo *= 2;   // $foo is now an integer (2)
$foo = $foo * 1.3;  // $foo is now a float (2.6)
$foo = 5 * "10 Little Piggies"; // $foo is integer (50)
$foo = 5 * "10 Small Pigs";     // $foo is integer (50)
?>

If the last two examples above seem odd, see String conversion to numbers.

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

To test any of the examples in this section, use the var_dump() function.

Note:

The behaviour of an automatic conversion to array is currently undefined.

Also, because PHP supports indexing into strings via offsets using the same syntax as array indexing, the following example holds true for all PHP versions:

<?php
$a    = 'car'; // $a is a string
$a[0] = 'b';   // $a is still a string
echo $a;       // bar
?>

See the section titled String access by character for more information.

Type Casting

Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast.

<?php
$foo = 10;   // $foo is an integer
$bar = (boolean) $foo;   // $bar is a boolean
?>

The casts allowed are:

  • (int), (integer) - cast to integer
  • (bool), (boolean) - cast to boolean
  • (float), (double), (real) - cast to float
  • (string) - cast to string
  • (array) - cast to array
  • (object) - cast to object
  • (unset) - cast to NULL

(binary) casting and b prefix forward support was added in PHP 5.2.1. Note that the (binary) cast is essential the same as (string), but it should not be relied upon.

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 will be removed as of PHP 8.0.0.

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

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

Casting literal strings and variables to binary strings:

<?php
$binary = (binary) $string;
$binary = b"binary string";
?>

Note:

Instead of casting a variable to a string, it is also possible to enclose the variable in double quotes.

<?php
$foo = 10;            // $foo is an integer
$str = "$foo";        // $str is a string
$fst = (string) $foo; // $fst is also a string

// This prints out that "they are the same"
if ($fst === $str) {
    echo "they are the same";
}
?>

It may not be obvious exactly what will happen when casting between certain types. For more information, see these sections:

  • 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


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.

Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: ^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$

Note: For our purposes here, a letter is a-z, A-Z, and the bytes from 128 through 255 (0x80-0xff).

Note: $this is a special variable that can't be assigned.

Tip

See also the Userland Naming Guide.

For information on variable related functions, see the Variable Functions Reference.

<?php
$var = 'Bob';
$Var = 'Joe';
echo "$var, $Var";      // outputs "Bob, Joe"

$4site = 'not yet';     // invalid; starts with a number
$_4site = 'not yet';    // valid; starts with an underscore
$täyte = 'mansikka';    // valid; 'ä' is (Extended) ASCII 228.
?>

By default, variables are always assigned by value. That is to say, when you assign an expression to a variable, the entire value of the original expression is copied into the destination variable. This means, for instance, that after assigning one variable's value to another, changing one of those variables will have no effect on the other. For more information on this kind of assignment, see the chapter on Expressions.

PHP also offers another way to assign values to variables: assign by reference. This means that the new variable simply references (in other words, "becomes an alias for" or "points to") the original variable. Changes to the new variable affect the original, and vice versa.

To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is being assigned (the source variable). For instance, the following code snippet outputs 'My name is Bob' twice:

<?php
$foo = 'Bob';              // Assign the value 'Bob' to $foo
$bar = &$foo;              // Reference $foo via $bar.
$bar = "My name is $bar";  // Alter $bar...
echo $bar;
echo $foo;                 // $foo is altered too.
?>

One important thing to note is that only named variables may be assigned by reference.

<?php
$foo = 25;
$bar = &$foo;      // This is a valid assignment.
$bar = &(24 * 7);  // Invalid; references an unnamed expression.

function test()
{
   return 25;
}

$bar = &test();    // Invalid.
?>

It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized variables have a default value of their type depending on the context in which they are used - booleans default to FALSE, integers and floats default to zero, strings (e.g. used in echo) are set as an empty string and arrays become to an empty array.

Example #1 Default values of uninitialized variables

<?php
// Unset AND unreferenced (no use context) variable; outputs NULL
var_dump($unset_var);

// Boolean usage; outputs 'false' (See ternary operators for more on this syntax)
echo($unset_bool ? "true\n" : "false\n");

// String usage; outputs 'string(3) "abc"'
$unset_str .= 'abc';
var_dump($unset_str);

// Integer usage; outputs 'int(25)'
$unset_int += 25; // 0 + 25 => 25
var_dump($unset_int);

// Float/double usage; outputs 'float(1.25)'
$unset_float += 1.25;
var_dump($unset_float);

// Array usage; outputs array(1) {  [3]=>  string(3) "def" }
$unset_arr[3] = "def"; // array() + array(3 => "def") => array(3 => "def")
var_dump($unset_arr);

// Object usage; creates new stdClass object (see http://www.php.net/manual/en/reserved.classes.php)
// Outputs: object(stdClass)#1 (1) {  ["foo"]=>  string(3) "bar" }
$unset_obj->foo = 'bar';
var_dump($unset_obj);
?>

Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name. It is also a major security risk with register_globals turned on. E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset() language construct can be used to detect if a variable has been already initialized.


Predefined Variables

PHP provides a large number of predefined variables to any script which it runs. Many of these variables, however, cannot be fully documented as they are dependent upon which server is running, the version and setup of the server, and other factors. Some of these variables will not be available when PHP is run on the command line. For a listing of these variables, please see the section on Reserved Predefined Variables.

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 rather special in that they are automatically global - i.e., automatically available in every scope. For this reason, they are often known as "superglobals". (There is no mechanism in PHP for user-defined superglobals.) The superglobals can be found here; however, for a listing of their contents and further discussion on PHP predefined variables and their natures, please see the section Reserved Predefined Variables.

Note:

Prior to PHP 5.4, the old way of retrieving information related to the HTTP request with the HTTP_*_VARS variables instead of superglobals was still possible. This feature could be disabled as of PHP 5.0.0 with the register_long_arrays directive.

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. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well. For example:

<?php
$a = 1;
include 'b.inc';
?>

Here the $a variable will be available within the included b.inc script. However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. For example:

<?php
$a = 1; /* global scope */

function test()
{
    echo $a; /* reference to local scope variable */
}

test();
?>

This script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function.

The global keyword

First, an example use of global:

Example #1 Using global

<?php
$a = 1;
$b = 2;

function Sum()
{
    global $a, $b;

    $b = $a + $b;
}

Sum();
echo $b;
?>

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

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

Example #2 Using $GLOBALS instead of global

<?php
$a = 1;
$b = 2;

function Sum()
{
    $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}

Sum();
echo $b;
?>

The $GLOBALS array is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element. Notice how $GLOBALS exists in any scope, this is because $GLOBALS is a superglobal. Here's an example demonstrating the power of superglobals:

Example #3 Example demonstrating superglobals and scope

<?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 #4 Example demonstrating need for static variables

<?php
function test()
{
    $a = 0;
    echo $a;
    $a++;
}
?>

This function is quite useless since every time it is called it sets $a to 0 and prints 0. The $a++ which increments the variable serves no purpose since as soon as the function exits the $a variable disappears. To make a useful counting function which will not lose track of the current count, the $a variable is declared static:

Example #5 Example use of static variables

<?php
function test()
{
    static $a = 0;
    echo $a;
    $a++;
}
?>

Now, $a is initialized only in first call of function and every time the test() function is called it will print the value of $a and increment it.

Static variables also provide one way to deal with recursive functions. A recursive function is one which calls itself. Care must be taken when writing a recursive function because it is possible to make it recurse indefinitely. You must make sure you have an adequate way of terminating the recursion. The following simple function recursively counts to 10, using the static variable $count to know when to stop:

Example #6 Static variables with recursive functions

<?php
function test()
{
    static $count = 0;

    $count++;
    echo $count;
    if ($count < 10) {
        test();
    }
    $count--;
}
?>

Note:

Static variables may be declared as seen in the examples above. From PHP 5.6 you can assign values to these variables which are the result of expressions, but you can't use any function here, what will cause a parse error.

Example #7 Declaring static variables

<?php
function foo(){
    static $int = 0;          // correct
    static $int = 1+2;        // correct (as of PHP 5.6)
    static $int = sqrt(121);  // wrong  (as it is a function)

    $int++;
    echo $int;
}
?>

Note:

Static declarations are resolved in compile-time.

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;
    $obj = &new stdclass;
}

function test_global_noref() {
    global $obj;
    $obj = new stdclass;
}

test_global_ref();
var_dump($obj);
test_global_noref();
var_dump($obj);
?>

The above example will output:

NULL
object(stdClass)(0) {
}

A similar behaviour applies to the static statement. References are not stored statically:

<?php
function &get_instance_ref() {
    static $obj;

    echo 'Static object: ';
    var_dump($obj);
    if (!isset($obj)) {
        // Assign a reference to the static variable
        $obj = &new stdclass;
    }
    $obj->property++;
    return $obj;
}

function &get_instance_noref() {
    static $obj;

    echo 'Static object: ';
    var_dump($obj);
    if (!isset($obj)) {
        // Assign the object to the static variable
        $obj = new stdclass;
    }
    $obj->property++;
    return $obj;
}

$obj1 = get_instance_ref();
$still_obj1 = get_instance_ref();
echo "\n";
$obj2 = get_instance_noref();
$still_obj2 = get_instance_noref();
?>

The above example will output:

Static object: NULL
Static object: NULL

Static object: NULL
Static object: object(stdClass)(1) {
["property"]=>
int(1)
}

This example demonstrates that when assigning a reference to a static variable, it's not remembered when you call the &get_instance_ref() function a second time.


Variable variables

Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as:

<?php
$a = 'hello';
?>

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

<?php
$$a = 'world';
?>

At this point two variables have been defined and stored in the PHP symbol tree: $a with contents "hello" and $hello with contents "world". Therefore, this statement:

<?php
echo "$a ${$a}";
?>

produces the exact same output as:

<?php
echo "$a $hello";
?>

i.e. they both produce: hello world.

In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.

Class properties may also be accessed using variable property names. The variable property name will be resolved within the scope from which the call is made. For instance, if you have an expression such as $foo->$bar, then the local scope will be examined for $bar and its value will be used as the name of the property of $foo. This is also true if $bar is an array access.

Caution

Further dereferencing a variable property that is an array has different semantics between PHP 5 and PHP 7. The PHP 7.0 migration guide includes further details on the types of expressions that have changed, and how to place curly braces to avoid ambiguity.

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 {
    var $bar = 'I am bar.';
    var $arr = array('I am A.', 'I am B.', 'I am C.');
    var $r   = 'I am r.';
}

$foo = new foo();
$bar = 'bar';
$baz = array('foo', 'bar', 'baz', 'quux');
echo $foo->$bar . "\n";
echo $foo->{$baz[1]} . "\n";

$start = 'b';
$end   = 'ar';
echo $foo->{$start . $end} . "\n";

$arr = 'arr';
echo $foo->{$arr[1]} . "\n";

?>

The above example will output:

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

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>

As of PHP 5.4.0, there are only two ways to access data from your 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'];
?>

There were some other ways of accessing user input in old PHP versions. These are listed below. See changelog at the bottom of the page for more details.

Example #3 Old methods of accessing user input

<?php
// WATCH OUT: these methods ARE NOT supported anymore.
// Valid ones were described above.

// Using import_request_variables() - this function has been removed in PHP 5.4.0
   import_request_variables('p', 'p_');
   echo $p_username;

// These long predefined variables were removed in PHP 5.4.0
   echo $HTTP_POST_VARS['username'];

// Using register_globals. This feature was removed in PHP 5.4.0
   echo $username;
?>

Using a GET form is similar except you'll use the appropriate GET predefined variable instead. GET also applies to the QUERY_STRING (the information after the '?' in a URL). So, for example, http://www.example.com/test.php?id=3 contains GET data which is accessible with $_GET['id']. See also $_REQUEST.

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). You may, for example, group related variables together, or use this feature to retrieve values from a multiple select input. For example, let's post a form to itself and upon submission display the data:

Example #4 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. You can set cookies using the setcookie() function. Cookies are part of the HTTP header, so the SetCookie function must be called before any output is sent to the browser. This is the same restriction as for the header() function. Cookie data is then available in the appropriate cookie data arrays, such as $_COOKIE as well as in $_REQUEST. See the setcookie() manual page for more details and examples.

If you wish to assign multiple values to a single cookie variable, you may assign it as an array. For example:

<?php
  setcookie("MyCookie[foo]", 'Testing 1', time()+3600);
  setcookie("MyCookie[bar]", 'Testing 2', time()+3600);
?>

That will create two separate cookies although MyCookie will now be a single array in your script. If you want to set just one cookie with multiple values, consider using serialize() or explode() on the value first.

Note that a cookie will replace a previous cookie by the same name in your browser unless the path or domain is different. So, for a shopping cart application you may want to keep a counter and pass this along. i.e.

Example #5 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
5.4.0 | Register Globals, Magic Quotes and register_long_arrays has been removed
5.3.0 | Register Globals, Magic Quotes and register_long_arrays became deprecated


Constants

Table of Contents

  • Syntax
  • 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). A constant is case-sensitive by default. By convention, constant identifiers are always uppercase.

The name of a constant follows the same rules as any label in PHP. A valid constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thusly: ^[a-zA-Z_\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 constant(). 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. You can access constants anywhere in your script without regard to scope. For more information on scope, read the manual section on variable scope.


Syntax

You can define a constant by using the define()-function or by using the const keyword outside a class definition as of PHP 5.3.0. 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 data (boolean, integer, float and string) can be contained in constants prior to PHP 5.6. From PHP 5.6 onwards, it is possible to define a constant as a scalar expression, and it is also possible to define an array constant. It is possible to define constants as a resource, but it should be avoided, as it can cause unexpected results.

You can get the value of a constant by simply specifying its name. Unlike with variables, you should not prepend a constant with a $. You can also use the function constant() to read a constant's value if you wish to obtain the constant's name dynamically. Use get_defined_constants() to get a list of all defined constants.

Note: Constants and (global) variables are in a different namespace. This implies that for example TRUE and $TRUE are generally different.

If you use an undefined constant, PHP assumes that you mean the name of the constant itself, just as if you called it as a string (CONSTANT vs "CONSTANT"). This fallback is deprecated as of PHP 7.2.0, and an error of level E_WARNING is issued when it happens (previously, an error of level E_NOTICE has been issued instead.) See also the manual entry on why $foo[bar] is wrong (unless you first define() bar as a constant). This does not apply to (fully) qualified constants, which will raise a fatal error if undefined. If you simply want to check if a constant is set, use the defined() function.

These are the differences between constants and variables:

  • Constants do not have a dollar sign ($) before them;
  • Prior to PHP 5.3, Constants may only be defined using the define() function, not by simple assignment;
  • Constants may be defined and accessed anywhere without regard to variable scoping rules;
  • Constants may not be redefined or undefined once they have been set; and
  • Constants may only evaluate to scalar values. As of PHP 5.6 it is possible to define array constant using const keywords and as of PHP 7 array constants can also be defined using define() You may use arrays in constant scalar expressions (for example, const FOO = array(1,2,3)[0];), but the end result must be a value of allowed type.

Example #1 Defining Constants

<?php
define("CONSTANT", "Hello world.");
echo CONSTANT; // outputs "Hello world."
echo Constant; // outputs "Constant" and issues a notice.
?>

Example #2 Defining Constants using the const keyword

<?php
// Works as of PHP 5.3.0
const CONSTANT = 'Hello World';

echo CONSTANT;

// Works as of PHP 5.6.0
const ANOTHER_CONST = CONSTANT.'; Goodbye World';
echo ANOTHER_CONST;

const ANIMALS = array('dog', 'cat', 'bird');
echo ANIMALS[1]; // outputs "cat"

// Works as of PHP 7
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.

Note:

Constants defined using the const keyword are always case-sensitive, while constants defined using define() may be case-insensitive.

See also Class Constants.


Magic constants

PHP provides a large number of predefined constants to any script which it runs. Many of these constants, however, are created by various extensions, and will only be present when those extensions are available, either via dynamic loading or because they have been compiled in.

There are nine magical constants that change depending on where they are used. For example, the value of __LINE__ depends on the line that it's used on in your script. 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:

A few "magical" PHP 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). Note that as of PHP 5.4 __CLASS__ works also in traits. When used in a trait method, __CLASS__ is the name of the class the trait is used in.
__TRAIT__ | The trait name. The trait name includes the namespace it was declared in (e.g. Foo\Bar).
__METHOD__ | The class method name.
__NAMESPACE__ | The name of the current namespace.
ClassName::class | The fully qualified class name. See also ::class.

See also
get_class(),
get_object_vars(),
file_exists() and
function_exists().

Changelog

Version | Description
5.5.0 | Added ::class magic constant
5.4.0 | Added __TRAIT__ constant
5.3.0 | Added __DIR__ and __NAMESPACE__ constants


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: integer values, floating point values (float), string values and boolean values (scalar values are values that you can't 'break' into smaller pieces, unlike arrays, for instance). PHP also supports two composite (non-scalar) types: arrays and objects. Each of these value types can be assigned into variables or returned from functions.

PHP takes expressions much further, in the same way many other languages do. PHP is an expression-oriented language, in the sense that almost everything is an expression. Consider the example we've already dealt with, '$a = 5'. It's easy to see that there are two values involved here, the value of the integer constant '5', and the value of $a which is being updated to 5 as well. But the truth is that there's one additional value involved here, and that's the value of the assignment itself. The assignment itself evaluates to the assigned value, in this case 5. In practice, it means that '$a = 5', regardless of what it does, is an expression with the value 5. Thus, writing something like '$b = ($a = 5)' is like writing '$a = 5; $b = 5;' (a semicolon marks the end of a statement). Since assignments are parsed in a right to left order, you can also write '$b = $a = 5'.

Another good example of expression orientation is pre- and post-increment and decrement. Users of PHP and many other languages may be familiar with the notation of variable++ and variable--. These are increment and decrement operators. In PHP, like in C, there are two types of increment - pre-increment and post-increment. Both pre-increment and post-increment essentially increment the variable, and the effect on the variable is identical. The difference is with the value of the increment expression. Pre-increment, which is written '++$variable', evaluates to the incremented value (PHP increments the variable before reading its value, thus the name 'pre-increment'). Post-increment, which is written '$variable++' evaluates to the original value of $variable, before it was incremented (PHP increments the variable after reading its value, thus the name 'post-increment').

A very common type of expressions are comparison expressions. These expressions evaluate to either FALSE or TRUE. PHP supports > (bigger than), >= (bigger than or equal to), == (equal), != (not equal), < (smaller than) and <= (smaller than or equal to). The language also supports a set of strict equivalence operators: === (equal to and same type) and !== (not equal to or not same type). These expressions are most commonly used inside conditional execution, such as if statements.

The last example of expressions we'll deal with here is combined operator-assignment expressions. You already know that if you want to increment $a by 1, you can simply write '$a++' or '++$a'. But what if you want to add more than one to it, for instance 3? You could write '$a++' multiple times, but this is obviously not a very efficient or comfortable way. A much more common practice is to write '$a = $a + 3'. '$a + 3' evaluates to the value of $a plus 3, and is assigned back into $a, which results in incrementing $a by 3. In PHP, as in several other languages like C, you can write this in a shorter way, which with time would become clearer and quicker to understand as well. Adding 3 to the current value of $a can be written '$a += 3'. This means exactly "take the value of $a, add 3 to it, and assign it back into $a". In addition to being shorter and clearer, this also results in faster execution. The value of '$a += 3', like the value of a regular assignment, is the assigned value. Notice that it is NOT 3, but the combined value of $a plus 3 (this is the value that's assigned into $a). Any two-place operator can be used in this operator-assignment mode, for example '$a -= 5' (subtract 5 from the value of $a), '$b *= 7' (multiply the value of $b by 7), etc.

There is one more expression that may seem odd if you haven't seen it in other languages, the ternary conditional operator:

<?php
$first ? $second : $third
?>

If the value of the first subexpression is TRUE (non-zero), then the second subexpression is evaluated, and that is the result of the conditional expression. Otherwise, the third subexpression is evaluated, and that is the value.

The following example should help you understand pre- and post-increment and expressions in general a bit better:

<?php
function double($i)
{
    return $i*2;
}
$b = $a = 5;        /* assign the value five into the variable $a and $b */
$c = $a++;          /* post-increment, assign original value of $a
                       (5) to $c */
$e = $d = ++$b;     /* pre-increment, assign the incremented value of
                       $b (6) to $d and $e */

/* at this point, both $d and $e are equal to 6 */

$f = double($d++);  /* assign twice the value of $d before
                       the increment, 2*6 = 12 to $f */
$g = double(++$e);  /* assign twice the value of $e after
                       the increment, 2*7 = 14 to $g */
$h = $g += 10;      /* first, $g is incremented by 10 and ends with the
                       value of 24. the value of the assignment (24) is
                       then assigned into $h, and $h ends with the value
                       of 24 as well. */
?>

Some expressions can be considered as statements. In this case, a statement has the form of 'expr ;' that is, an expression followed by a semicolon. In '$b = $a = 5;', '$a = 5' is a valid expression, but it's not a statement by itself. '$b = $a = 5;' however is a valid statement.

One last thing worth mentioning is the truth value of expressions. In many events, mainly in conditional execution and loops, you're not interested in the specific value of the expression, but only care about whether it means TRUE or FALSE. The constants TRUE and FALSE (case-insensitive) are the two possible boolean values. When necessary, an expression is automatically converted to boolean. See the section about type-casting for details about how.

PHP provides a full and powerful implementation of expressions, and documenting it entirely goes beyond the scope of this manual. The above examples should give you a good idea about what expressions are and how you can construct useful expressions. Throughout the rest of this manual we'll write expr to indicate any valid PHP expression.


Operators

Table of Contents

  • Operator Precedence
  • Arithmetic Operators
  • Assignment Operators
  • Bitwise Operators
  • Comparison Operators
  • Error Control Operators
  • Execution Operators
  • Incrementing/Decrementing Operators
  • Logical Operators
  • String Operators
  • Array Operators
  • Type Operators

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

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

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


Operator Precedence

The precedence of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator. Parentheses may be used to force precedence, if necessary. For instance: (1 + 5) * 3 evaluates to 18.

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

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

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

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

Operator Precedence
Associativity | Operators | Additional Information
non-associative | clone new | clone and new
right | ** | arithmetic
right | ++ -- ~ (int) (float) (string) (array) (object) (bool) @ | types and increment/decrement
non-associative | instanceof | types
right | ! | logical
left | * / % | arithmetic
left | + - . | arithmetic and string
left | << >> | bitwise
non-associative | < <= > >= | comparison
non-associative | == != === !== <> <=> | comparison
left | & | bitwise and references
left | ^ | bitwise
left | | | bitwise
left | && | logical
left | || | logical
right | ?? | null coalescing
left | ? : | ternary
right | = += -= *= **= /= .= %= &= |= ^= <<= >>= | assignment
right | yield from | yield from
right | yield | yield
left | and | logical
left | xor | logical
left | or | logical

Example #1 Associativity

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

$a = 1;
$b = 2;
$a = $b += 3; // $a = ($b += 3) -> $a = 5, $b = 5
?>

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

Example #2 Undefined order of evaluation

<?php
$a = 1;
echo $a + $a++; // may print either 2 or 3

$i = 1;
$array[$i] = $i++; // may set either index 1 or 2
?>

Example #3 +, - and . have 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:
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.


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. Introduced in PHP 5.6.

The division operator ("/") returns a float value unless the two operands are integers (or strings that get converted to integers) and the numbers are evenly divisible, in which case an integer value will be returned. For integer division, see intdiv().

Operands of modulo are converted to integers (by stripping the decimal part) 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:

<?php

echo (5 % 3)."\n";           // prints 2
echo (5 % -3)."\n";          // prints 2
echo (-5 % 3)."\n";          // prints -2
echo (-5 % -3)."\n";         // prints -2

?>

See also the manual page on Math functions.


Assignment Operators

The basic assignment operator is "=". Your first inclination might be to think of this as "equal to". Don't. It really means that the left operand gets set to the value of the expression on the right (that is, "gets set to").

The value of an assignment expression is the value assigned. That is, the value of "$a = 3" is 3. This allows you to do some tricky things:

<?php

$a = ($b = 4) + 5; // $a is equal to 9 now, and $b has been set to 4.

?>

In addition to the basic assignment operator, there are "combined operators" for all of the binary arithmetic, array union and string operators that allow you to use a value in an expression and then set its value to the result of that expression. For example:

<?php

$a = 3;
$a += 5; // sets $a to 8, as if we had said: $a = $a + 5;
$b = "Hello ";
$b .= "There!"; // sets $b to "Hello There!", just like $b = $b . "There!";

?>

Note that the assignment copies the original variable to the new one (assignment by value), so changes to one will not affect the other. This may also have relevance if you need to copy something like a large array inside a tight loop.

An exception to the usual assignment by value behaviour within PHP occurs with objects, which are assigned by reference. Objects may be explicitly copied via the clone keyword.

Assignment by Reference

Assignment by reference is also supported, using the "$var = &$othervar;" syntax. Assignment by reference means that both variables end up pointing at the same data, and nothing is copied anywhere.

Example #1 Assigning by reference

<?php
$a = 3;
$b = &$a; // $b is a reference to $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, so assigning the result of new by reference is not allowed as of PHP 7.0.0, results in an E_DEPRECATED message as of PHP 5.3.0, and an E_STRICT message in earlier versions.

For example, this code will result in an error or warning:

<?php
class C {}

$o = &new C;
?>

Output of the above example in PHP 7:

Parse error: syntax error, unexpected 'new' (T_NEW) in …

Output of the above example in PHP 5.3:

Deprecated: Assigning the return value of new by reference is deprecated in …

Output of the above example in PHP 5:

Strict Standards: Assigning the return value of new by reference is deprecated in …

More information on references and their potential uses can be found in the References Explained section of the manual.


Bitwise Operators

Bitwise operators allow evaluation and manipulation of specific bits within an integer.

Bitwise Operators
Example | Name | Result
$a & $b | And | Bits that are set in both $a and $b are set.
$a | $b | Or (inclusive or) | Bits that are set in either $a or $b are set.
$a ^ $b | Xor (exclusive or) | Bits that are set in $a or $b but not both are set.
~ $a | Not | Bits that are set in $a are not set, and vice versa.
$a << $b | Shift left | Shift the bits of $a $b steps to the left (each step means "multiply by two")
$a >> $b | Shift right | Shift the bits of $a $b steps to the right (each step means "divide by two")

Bit shifting in PHP is arithmetic. Bits shifted off either end are discarded. Left shifts have zeros shifted in on the right while the sign bit is shifted out on the left, meaning the sign of an operand is not preserved. Right shifts have copies of the sign bit shifted in on the left, meaning the sign of an operand is preserved.

Use parentheses to ensure the desired precedence. For example, $a & $b == true evaluates the equivalency then the bitwise and; while ($a & $b) == true evaluates the bitwise and then the equivalency.

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; // Outputs '5'

echo "12" ^ "9"; // Outputs the Backspace character (ascii 8)
                 // ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8

echo "hallo" ^ "hello"; // Outputs the ascii values #0 #4 #0 #0 #0
                        // 'a' ^ 'e' = #4

echo 2 ^ "3"; // Outputs 1
              // 2 ^ ((int)"3") == 1

echo "2" ^ 3; // Outputs 1
              // ((int)"2") ^ 3 == 1
?>

Example #3 Bit shifting on integers

<?php
/*
 * Here are the examples.
 */

echo "\n--- BIT SHIFT RIGHT ON POSITIVE INTEGERS ---\n";

$val = 4;
$places = 1;
$res = $val >> $places;
p($res, $val, '>>', $places, 'copy of sign bit shifted into left side');

$val = 4;
$places = 2;
$res = $val >> $places;
p($res, $val, '>>', $places);

$val = 4;
$places = 3;
$res = $val >> $places;
p($res, $val, '>>', $places, 'bits shift out right side');

$val = 4;
$places = 4;
$res = $val >> $places;
p($res, $val, '>>', $places, 'same result as above; can not shift beyond 0');

echo "\n--- BIT SHIFT RIGHT ON NEGATIVE INTEGERS ---\n";

$val = -4;
$places = 1;
$res = $val >> $places;
p($res, $val, '>>', $places, 'copy of sign bit shifted into left side');

$val = -4;
$places = 2;
$res = $val >> $places;
p($res, $val, '>>', $places, 'bits shift out right side');

$val = -4;
$places = 3;
$res = $val >> $places;
p($res, $val, '>>', $places, 'same result as above; can not shift beyond -1');

echo "\n--- BIT SHIFT LEFT ON POSITIVE INTEGERS ---\n";

$val = 4;
$places = 1;
$res = $val << $places;
p($res, $val, '<<', $places, 'zeros fill in right side');

$val = 4;
$places = (PHP_INT_SIZE * 8) - 4;
$res = $val << $places;
p($res, $val, '<<', $places);

$val = 4;
$places = (PHP_INT_SIZE * 8) - 3;
$res = $val << $places;
p($res, $val, '<<', $places, 'sign bits get shifted out');

$val = 4;
$places = (PHP_INT_SIZE * 8) - 2;
$res = $val << $places;
p($res, $val, '<<', $places, 'bits shift out left side');

echo "\n--- BIT SHIFT LEFT ON NEGATIVE INTEGERS ---\n";

$val = -4;
$places = 1;
$res = $val << $places;
p($res, $val, '<<', $places, 'zeros fill in right side');

$val = -4;
$places = (PHP_INT_SIZE * 8) - 3;
$res = $val << $places;
p($res, $val, '<<', $places);

$val = -4;
$places = (PHP_INT_SIZE * 8) - 2;
$res = $val << $places;
p($res, $val, '<<', $places, 'bits shift out left side, including sign bit');

/*
 * Ignore this bottom section,
 * it is just formatting to make output clearer.
 */

function p($res, $val, $op, $places, $note = '') {
    $format = '%0' . (PHP_INT_SIZE * 8) . "b\n";

    printf("Expression: %d = %d %s %d\n", $res, $val, $op, $places);

    echo " Decimal:\n";
    printf("  val=%d\n", $val);
    printf("  res=%d\n", $res);

    echo " Binary:\n";
    printf('  val=' . $format, $val);
    printf('  res=' . $format, $res);

    if ($note) {
        echo " NOTE: $note\n";
    }

    echo "\n";
}
?>

Output of the above example on 32 bit machines:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Output of the above example on 64 bit machines:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Warning

Prior to PHP 7.0, shifting integers by values greater than or equal to the system long integer width, or by negative numbers, results in undefined behavior. In other words, if you're using PHP 5.x, don't shift more than 31 bits on a 32-bit system, and don't shift more than 63 bits on 64-bit system.

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 integer less than, equal to, or greater than zero when $a is less than, equal to, or greater than $b, respectively. Available as of PHP 7.

If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.

<?php
var_dump(0 == "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true
var_dump("10" == "1e1"); // 10 == 10 -> true
var_dump(100 == "1e2"); // 100 == 100 -> true

switch ("a") {
case 0:
    echo "0";
    break;
case "a": // never reached because "a" is already matched with 0
    echo "a";
    break;
}
?>
<?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 uncomparable, same class see Object Comparison
string, resource or number | string, resource or number | Translate strings and resources to numbers, usual math
array | array | Array with fewer members is smaller, if key from operand 1 is not found in operand 2 then arrays are uncomparable, otherwise - compare value by value (see following example)
object | anything | object is always greater
array | anything | array is always greater

Example #1 Boolean/null comparison

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

Example #2 Transcription of standard array comparison

<?php
// Arrays are compared like this with standard comparison operators
function standard_array_compare($op1, $op2)
{
    if (count($op1) < count($op2)) {
        return -1; // $op1 < $op2
    } elseif (count($op1) > count($op2)) {
        return 1; // $op1 > $op2
    }
    foreach ($op1 as $key => $val) {
        if (!array_key_exists($key, $op2)) {
            return null; // uncomparable
        } elseif ($val < $op2[$key]) {
            return -1;
        } elseif ($val > $op2[$key]) {
            return 1;
        }
    }
    return 0; // $op1 == $op2
}
?>

See also strcasecmp(), strcmp(), Array operators, and the manual section on Types.

Warning

Comparison of floating point numbers

Because of the way floats are represented internally, you should not test two floats for equality.

See the documentation for float for more information.

Ternary Operator

Another conditional operator is the "?:" (or ternary) operator.

Example #3 Assigning a default value

<?php
// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];

// The above is identical to this if/else 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.

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

Note: Please note that the ternary operator is an expression, and that it doesn't evaluate to a variable, but to the result of an expression. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued.

Note:

It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious:

Example #4 Non-obvious Ternary Behaviour

<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');

// however, the actual output of the above is 't'
// this is because ternary expressions are evaluated from left to right

// the following is a more obvious version of the same code as above
echo ((true ? 'true' : false) ? 't' : 'f');

// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>

Null Coalescing Operator

Further exists the "??" (or null coalescing) operator, available as of PHP 7.

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

Please note that the null coalescing operator allows for simple nesting:

Example #6 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 error messages that might be generated by that expression will be ignored.

If you have set a custom error handler function with set_error_handler() then it will still get called, but this custom error handler can (and should) call error_reporting() which will return 0 when the call that triggered the error was preceded by an @.

If the track_errors feature is enabled, any error message generated by the expression will be saved in the variable $php_errormsg. This variable will be overwritten on each error, so check early if you want to use it.

<?php
/* Intentional file error */
$my_file = @file ('non_existent_file') or
    die ("Failed opening file: error was '$php_errormsg'");

// this works for any expression, not just functions:
$value = @$cache[$key];
// will not issue a notice if the index $key doesn't exist.

?>

Note: The @-operator works only on expressions. A simple rule of thumb is: if you can take the value of something, you can prepend the @ operator to it. For instance, you can prepend it to variables, function and include calls, constants, and so forth. You cannot prepend it to function or class definitions, or conditional structures such as if and foreach, and so forth.

See also error_reporting() and the manual section for Error Handling and Logging functions.

Warning

Currently the "@" error-control operator prefix will even disable error reporting for critical errors that will terminate script execution. Among other things, this means that if you use "@" to suppress errors from a certain function and either it isn't available or has been mistyped, the script will die right there with no indication as to why.


Execution Operators

PHP supports one execution operator: backticks (``). Note that these are not single-quotes! PHP will attempt to execute the contents of the backticks as a shell command; the output will be returned (i.e., it won't simply be dumped to output; it can be assigned to a variable). Use of the backtick operator is identical to shell_exec().

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

Note:

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

Note:

Unlike some other languages, backticks have no special meaning within double-quoted strings.

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


Incrementing/Decrementing Operators

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

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

Increment/decrement Operators
Example | Name | Effect
++$a | Pre-increment | Increments $a by one, then returns $a.
$a++ | Post-increment | Returns $a, then increments $a by one.
--$a | Pre-decrement | Decrements $a by one, then returns $a.
$a-- | Post-decrement | Returns $a, then decrements $a by one.

Here's a simple example script:

<?php
echo "<h3>Postincrement</h3>";
$a = 5;
echo "Should be 5: " . $a++ . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";

echo "<h3>Preincrement</h3>";
$a = 5;
echo "Should be 6: " . ++$a . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";

echo "<h3>Postdecrement</h3>";
$a = 5;
echo "Should be 5: " . $a-- . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";

echo "<h3>Predecrement</h3>";
$a = 5;
echo "Should be 4: " . --$a . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";
?>

PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in PHP and Perl $a = 'Z'; $a++; turns $a into 'AA', while in C a = 'Z'; a++; turns a into '[' (ASCII value of 'Z' is 90, ASCII value of '[' is 91). Note that character variables can be incremented but not decremented and even so only plain ASCII alphabets and digits (a-z, A-Z and 0-9) are supported. Incrementing/decrementing other character variables has no effect, the original string is unchanged.

Example #1 Arithmetic Operations on Character Variables

<?php
echo '== Alphabets ==' . PHP_EOL;
$s = 'W';
for ($n=0; $n<6; $n++) {
    echo ++$s . PHP_EOL;
}
// Digit characters behave differently
echo '== Digits ==' . PHP_EOL;
$d = 'A8';
for ($n=0; $n<6; $n++) {
    echo ++$d . PHP_EOL;
}
$d = 'A08';
for ($n=0; $n<6; $n++) {
    echo ++$d . PHP_EOL;
}
?>

The above example will output:

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

Incrementing or decrementing booleans has no effect.


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.

<?php
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"

$a = "Hello ";
$a .= "World!";     // now $a contains "Hello World!"
?>

See also the manual sections on the String type and String functions.


Array Operators

Array Operators
Example | Name | Result
$a + $b | Union | Union of $a and $b.
$a == $b | Equality | TRUE if $a and $b have the same key/value pairs.
$a === $b | Identity | TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
$a != $b | Inequality | TRUE if $a is not equal to $b.
$a <> $b | Inequality | TRUE if $a is not equal to $b.
$a !== $b | Non-identity | TRUE if $a is not identical to $b.

The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.

<?php
$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");

$c = $a + $b; // Union of $a and $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);
?>
When executed, this script will print the following:
Union of $a and $b:
array(3) {
  ["a"]=>
  string(5) "apple"
  ["b"]=>
  string(6) "banana"
  ["c"]=>
  string(6) "cherry"
}
Union of $b and $a:
array(3) {
  ["a"]=>
  string(4) "pear"
  ["b"]=>
  string(10) "strawberry"
  ["c"]=>
  string(6) "cherry"
}
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 #1 Comparing arrays

<?php
$a = array("apple", "banana");
$b = array(1 => "banana", "0" => "apple");

var_dump($a == $b); // bool(true)
var_dump($a === $b); // bool(false)
?>

See also the manual sections on the Array type and Array functions.


Type Operators

instanceof is used to determine whether a PHP variable is an instantiated object of a certain class:

Example #1 Using instanceof with classes

<?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, are not allowed.

Example #6 Using instanceof to test other variables

<?php
$a = 1;
$b = NULL;
$c = imagecreate(5, 5);
var_dump($a instanceof stdClass); // $a is an integer
var_dump($b instanceof stdClass); // $b is NULL
var_dump($c instanceof stdClass); // $c is a resource
var_dump(FALSE instanceof stdClass);
?>

The above example will output:

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

There are a few pitfalls to be aware of. Before PHP version 5.1.0, instanceof would call __autoload() if the class name did not exist. In addition, if the class was not loaded, a fatal error would occur. This can be worked around by using a dynamic class reference, or a string variable containing the class name:

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

<?php
$d = 'NotMyClass';
var_dump($a instanceof $d); // no fatal error here
?>

The above example will output:

bool(false)

The instanceof operator was introduced in PHP 5. Before this time is_a() was used but is_a() has since been deprecated in favor of instanceof. Note that as of PHP 5.3.0, is_a() is no longer deprecated.

See also get_class() and is_a().


Control Structures

Table of Contents

  • Introduction
  • if
  • else
  • elseif/else if
  • Alternative syntax for control structures
  • while
  • do-while
  • for
  • foreach
  • break
  • continue
  • switch
  • 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.


if

(PHP 4, PHP 5, PHP 7)

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)

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


elseif/else if

(PHP 4, PHP 5, PHP 7)

elseif, as its name suggests, is a combination of if and else. Like else, it extends an if statement to execute a different statement in case the original if expression evaluates to FALSE. However, unlike else, it will execute that alternative expression only if the elseif conditional expression evaluates to TRUE. For example, the following code would display a is bigger than b, a equal to b or a is smaller than b:

<?php
if ($a > $b) {
    echo "a is bigger than b";
} elseif ($a == $b) {
    echo "a is equal to b";
} else {
    echo "a is smaller than b";
}
?>

There may be several elseifs within the same if statement. The first elseif expression (if any) that evaluates to TRUE would be executed. In PHP, you can also write 'else if' (in two words) and the behavior would be identical to the one of 'elseif' (in a single word). The syntactic meaning is slightly different (if you're familiar with C, this is the same behavior) but the bottom line is that both would result in exactly the same behavior.

The elseif statement is only executed if the preceding if expression and any preceding elseif expressions evaluated to FALSE, and the current elseif expression evaluated to TRUE.

Note: Note that elseif and else if will only be considered exactly the same when using curly brackets as in the above example. When using a colon to define your if/elseif conditions, you must not separate else if into two words, or PHP will fail with a parse error.

<?php

/* Incorrect Method: */
if ($a > $b):
    echo $a." is greater than ".$b;
else if ($a == $b): // Will not compile.
    echo "The above line causes a parse error.";
endif;

/* Correct Method: */
if ($a > $b):
    echo $a." is greater than ".$b;
elseif ($a == $b): // Note the combination of the words.
    echo $a." equals ".$b;
else:
    echo $a." is neither greater than or equal to ".$b;
endif;

?>


Alternative syntax for control structures

(PHP 4, PHP 5, PHP 7)

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)

while loops are the simplest type of loop in PHP. They behave just like their C counterparts. The basic form of a while statement is:

while (expr)
    statement

The meaning of a while statement is simple. It tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE. The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration (each time PHP runs the statements in the loop is one iteration). Sometimes, if the while expression evaluates to FALSE from the very beginning, the nested statement(s) won't even be run once.

Like with the if statement, you can group multiple statements within the same while loop by surrounding a group of statements with curly braces, or by using the alternate syntax:

while (expr):
    statement
    ...
endwhile;

The following examples are identical, and both print the numbers 1 through 10:

<?php
/* example 1 */

$i = 1;
while ($i <= 10) {
    echo $i++;  /* the printed value would be
                   $i before the increment
                   (post-increment) */
}

/* example 2 */

$i = 1;
while ($i <= 10):
    echo $i;
    $i++;
endwhile;
?>


do-while

(PHP 4, PHP 5, PHP 7)

do-while loops are very similar to while loops, except the truth expression is checked at the end of each iteration instead of in the beginning. The main difference from regular while loops is that the first iteration of a do-while loop is guaranteed to run (the truth expression is only checked at the end of the iteration), whereas it may not necessarily run with a regular while loop (the truth expression is checked at the beginning of each iteration, if it evaluates to FALSE right from the beginning, the loop execution would end immediately).

There is just one syntax for do-while loops:

<?php
$i = 0;
do {
    echo $i;
} while ($i > 0);
?>

The above loop would run one time exactly, since after the first iteration, when truth expression is checked, it evaluates to FALSE ($i is not bigger than 0) and the loop execution ends.

Advanced C users may be familiar with a different usage of the do-while loop, to allow stopping execution in the middle of code blocks, by encapsulating them with do-while (0), and using the break statement. The following code fragment demonstrates this:

<?php
do {
    if ($i < 5) {
        echo "i is not big enough";
        break;
    }
    $i *= $factor;
    if ($i < $minimum_limit) {
        break;
    }
   echo "i is ok";

    /* process i */

} while (0);
?>

Don't worry if you don't understand this right away or at all. You can code scripts and even powerful scripts without using this 'feature'. Since PHP 5.3.0, it is possible to use goto operator instead of this hack.


for

(PHP 4, PHP 5, PHP 7)

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)

The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes:

foreach (array_expression as $value)
    statement
foreach (array_expression as $key => $value)
    statement

The first form loops over the array given by array_expression. On each iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next iteration, you'll be looking at the next element).

The second form will additionally assign the current element's key to the $key variable on each iteration.

It is possible to customize object iteration.

Note:

In PHP 5, when foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop.

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

In PHP 7, foreach does not use the internal array pointer.

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>

Warning

Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset(). Otherwise you will experience the following behavior:

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(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

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

Before PHP 5.5.0, referencing $value is only possible if the iterated array can be referenced (i.e. if it is a variable). The following code works only as of PHP 5.5.0:

<?php
foreach (array(1, 2, 3, 4) as &$value) {
    $value = $value * 2;
}
?>

Note:

foreach does not support the ability to suppress error messages using '@'.

Some more examples to demonstrate usage:

<?php
/* foreach example 1: value only */

$a = array(1, 2, 3, 17);

foreach ($a as $v) {
    echo "Current value of \$a: $v.\n";
}

/* foreach example 2: value (with its manual access notation printed for illustration) */

$a = array(1, 2, 3, 17);

$i = 0; /* for illustrative purposes only */

foreach ($a as $v) {
    echo "\$a[$i] => $v.\n";
    $i++;
}

/* foreach example 3: key and value */

$a = array(
    "one" => 1,
    "two" => 2,
    "three" => 3,
    "seventeen" => 17
);

foreach ($a as $k => $v) {
    echo "\$a[$k] => $v.\n";
}

/* foreach example 4: multi-dimensional arrays */
$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";

foreach ($a as $v1) {
    foreach ($v1 as $v2) {
        echo "$v2\n";
    }
}

/* foreach example 5: dynamic arrays */

foreach (array(1, 2, 3, 4, 5) as $v) {
    echo "$v\n";
}
?>

Unpacking nested arrays with list()

(PHP 5 >= 5.5.0, PHP 7)

PHP 5.5 added the ability to iterate over an array of arrays and unpack the nested array into loop variables by providing a list() as the value.

For example:

<?php
$array = [
    [1, 2],
    [3, 4],
];

foreach ($array as list($a, $b)) {
    // $a contains the first element of the nested array,
    // and $b contains the second element.
    echo "A: $a; B: $b\n";
}
?>

The above example will output:

A: 1; B: 2
A: 3; B: 4

You can provide fewer elements in the list() than there are in the nested array, in which case the leftover array values will be ignored:

<?php
$array = [
    [1, 2],
    [3, 4],
];

foreach ($array as list($a)) {
    // Note that there is no $b here.
    echo "$a\n";
}
?>

The above example will output:

1
3

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

<?php
$array = [
    [1, 2],
    [3, 4],
];

foreach ($array as list($a, $b, $c)) {
    echo "A: $a; B: $b; C: $c\n";
}
?>

The above example will output:

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

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

Changelog

Version | Description
7.0.0 | foreach does not use the internal array pointer anymore.
5.5.0 | Referencing of $value is supported for expressions. Formerly, only variables have been supported.
5.5.0 | Unpacking nested arrays with list() is supported.


break

(PHP 4, PHP 5, PHP 7)

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

Changelog for break
Version | Description
7.0.0 | break outside of a loop or switch control structure is now detected at compile-time instead of run-time as before, and triggers an E_COMPILE_ERROR.
5.4.0 | break 0; is no longer valid. In previous versions it was interpreted the same as break 1;.
5.4.0 | Removed the ability to pass in variables (e.g., $num = 2; break $num;) as the numerical argument.


continue

(PHP 4, PHP 5, PHP 7)

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
foreach ($arr as $key => $value) {
    if (!($key % 2)) { // skip even members
        continue;
    }
    do_something_odd($value);
}

$i = 0;
while ($i++ < 5) {
    echo "Outer<br />\n";
    while (1) {
        echo "Middle<br />\n";
        while (1) {
            echo "Inner<br />\n";
            continue 3;
        }
        echo "This never gets output.<br />\n";
    }
    echo "Neither does this.<br />\n";
}
?>

Omitting the semicolon after continue can lead to confusion. Here's an example of what you shouldn't do.

<?php
for ($i = 0; $i < 5; ++$i) {
    if ($i == 2)
        continue
    print "$i\n";
}
?>

One can expect the result to be:

0
1
3
4

but, in PHP versions below 5.4.0, this script will output:

2

because the entire continue print "$i\n"; is evaluated as a single expression, and so print is called only when $i == 2 is true. (The return value of print is passed to continue as the numeric argument.)

Note:

As of PHP 5.4.0, the above example will raise an E_COMPILE_ERROR error.

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.
7.0.0 | continue outside of a loop or switch control structure is now detected at compile-time instead of run-time as before, and triggers an E_COMPILE_ERROR.
5.4.0 | continue 0; is no longer valid. In previous versions it was interpreted the same as continue 1;.
5.4.0 | Removed the ability to pass in variables (e.g., $num = 2; continue $num;) as the numerical argument.


switch

(PHP 4, PHP 5, PHP 7)

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.

Changelog
Version | Description
7.0.0 | Multiple default cases will raise a E_COMPILE_ERROR error.

The following two examples are two different ways to write the same thing, one using a series of if and elseif statements, and the other using the switch statement:

Example #1 switch structure

<?php
if ($i == 0) {
    echo "i equals 0";
} elseif ($i == 1) {
    echo "i equals 1";
} elseif ($i == 2) {
    echo "i equals 2";
}

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

Example #2 switch structure allows usage of strings

<?php
switch ($i) {
    case "apple":
        echo "i is apple";
        break;
    case "bar":
        echo "i is bar";
        break;
    case "cake":
        echo "i is cake";
        break;
}
?>

It is important to understand how the switch statement is executed in order to avoid mistakes. The switch statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a case statement is found 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";
}
?>

The alternative syntax for control structures is supported with switches. For more information, see Alternative syntax for control structures.

<?php
switch ($i):
    case 0:
        echo "i equals 0";
        break;
    case 1:
        echo "i equals 1";
        break;
    case 2:
        echo "i equals 2";
        break;
    default:
        echo "i is not equal to 0, 1 or 2";
endswitch;
?>

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

<?php
switch($beer)
{
    case 'tuborg';
    case 'carlsberg';
    case 'heineken';
        echo 'Good choice';
    break;
    default;
        echo 'Please make a new selection...';
    break;
}
?>


declare

(PHP 4, PHP 5, PHP 7)

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: the ticks directive (See below for more information on the ticks directive), the encoding directive (See below for more information on the encoding directive) and the strict_types directive (See for more information the strict section on the Function arguments page)

Version | Description
7.0.0 | Added strict_types directive
7.0.0 | The ticks directive does no longer leak into different compilation units.
5.3.0 | Added encoding directive

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');

$a = 1;

if ($a > 0) {
    $a += 2;
    print($a);
}

?>

Example #2 Ticks usage example

<?php

function tick_handler()
{
  echo "tick_handler() called\n";
}

$a = 1;
tick_handler();

if ($a > 0) {
    $a += 2;
    tick_handler();
    print($a);
    tick_handler();
}
tick_handler();

?>

See also register_tick_function() and unregister_tick_function().

Encoding

A script's encoding can be specified per-script using the encoding directive.

Example #3 Declaring an encoding for the script.

<?php
declare(encoding='ISO-8859-1');
// code here
?>

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.

The encoding declare value is ignored in PHP 5.3 unless php is compiled with --enable-zend-multibyte.

Note that PHP does not expose whether --enable-zend-multibyte was used to compile PHP other than by phpinfo().

See also zend.script_encoding.


return

(PHP 4, PHP 5, PHP 7)

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.


require

(PHP 4, PHP 5, PHP 7)

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

See the include documentation for how this works.


include

(PHP 4, PHP 5, PHP 7)

The include statement includes and evaluates the specified file.

The documentation below also applies to require.

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

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

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

When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.

Example #1 Basic include example

vars.php
<?php

$color = 'green';
$fruit = 'apple';

?>

test.php
<?php

echo "A $color $fruit"; // A

include 'vars.php';

echo "A $color $fruit"; // A green apple

?>

If the include occurs inside a function within the calling file, then all of the code contained in the called file will behave as though it had been defined inside that function. So, it will follow the variable scope of that function. An exception to this rule are magic constants which are evaluated by the parser before the include occurs.

Example #2 Including within functions

<?php

function foo()
{
    global $color;

    include 'vars.php';

    echo "A $color $fruit";
}

/* vars.php is in the scope of foo() so     *
* $fruit is NOT available outside of this  *
* scope.  $color is because we declared it *
* as global.                               */

foo();                    // A green apple
echo "A $color $fruit";   // A green

?>

When a file is included, parsing drops out of PHP mode and into HTML mode at the beginning of the target file, and resumes again at the end. For this reason, any code inside the target file which should be executed as PHP code must be enclosed within valid PHP start and end tags.

If "URL include wrappers" are enabled in PHP, you can specify the file to be included using a URL (via HTTP or other supported wrapper - see Supported Protocols and Wrappers for a list of protocols) instead of a local pathname. If the target server interprets the target file as PHP code, variables may be passed to the included file using a URL request string as used with HTTP GET. This is not strictly speaking the same thing as including the file and having it inherit the parent file's variable scope; the script is actually being run on the remote server and the result is then being included into the local script.

Example #3 include through HTTP

<?php

/* This example assumes that www.example.com is configured to parse .php
* files and not .txt files. Also, 'Works' here means that the variables
* $foo and $bar are available within the included file. */

// Won't work; file.txt wasn't handled by www.example.com as PHP
include 'http://www.example.com/file.txt?foo=1&bar=2';

// Won't work; looks for a file named 'file.php?foo=1&bar=2' on the
// local filesystem.
include 'file.php?foo=1&bar=2';

// Works.
include 'http://www.example.com/file.php?foo=1&bar=2';

$foo = 1;
$bar = 2;
include 'file.txt';  // Works.
include 'file.php';  // Works.

?>

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

See also require, require_once, include_once, get_included_files(), readfile(), virtual(), and include_path.


require_once

(PHP 4, PHP 5, PHP 7)

The require_once statement is identical to require except PHP will check if the file has already been included, and if so, not include (require) it again.

See the include_once documentation for information about the _once behaviour, and how it differs from its non _once siblings.


include_once

(PHP 4, PHP 5, PHP 7)

The include_once statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include statement, with the only difference being that if the code from a file has already been included, it will not be included again, 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)

What's the worse thing that could happen if you use goto?
Image courtesy of » xkcd

The goto operator can be used to jump to another section in the program. The target point is specified by a label followed by a colon, and the instruction is given as goto followed by the desired target label. This is not a full unrestricted goto. The target label must be within the same file and context, meaning that you cannot jump out of a function or method, nor can you jump into one. You also cannot jump into any sort of loop or switch structure. You may jump out of these, and a common use is to use a goto in place of a multi-level break.

Example #1 goto example

<?php
goto a;
echo 'Foo';

a:
echo 'Bar';
?>

The above example will output:

Bar

Example #2 goto loop example

<?php
for($i=0,$j=50; $i<100; $i++) {
  while($j--) {
    if($j==17) goto end;
  }
}
echo "i = $i";
end:
echo 'j hit 17';
?>

The above example will output:

j hit 17

Example #3 This will not work

<?php
goto loop;
for($i=0,$j=50; $i<100; $i++) {
  while($j--) {
    loop:
  }
}
echo "$i = $i";
?>

The above example will output:

Fatal error: 'goto' into loop or switch statement is disallowed in
script on line 2

Note:

The goto operator is available as of PHP 5.3.


Functions

Table of Contents

  • User-defined functions
  • Function arguments
  • Returning values
  • Variable functions
  • Internal (built-in) functions
  • Anonymous functions


User-defined functions

A function may be defined using syntax such as the following:

Example #1 Pseudo code to demonstrate function uses

<?php
function foo($arg_1, $arg_2, /* ..., */ $arg_n)
{
    echo "Example function.\n";
    return $retval;
}
?>

Any valid PHP code may appear inside a function, even other functions and class definitions.

Function names follow the same rules as other labels in PHP. A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: ^[a-zA-Z_\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, 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 arguments

Information may be passed to functions via the argument list, which is a comma-delimited list of expressions. The arguments are evaluated from left to right.

PHP supports passing arguments by value (the default), passing by reference, and default argument values. Variable-length argument lists are also supported.

Example #1 Passing arrays to functions

<?php
function takes_array($input)
{
    echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
?>

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 argument name in the function definition:

Example #2 Passing function parameters by reference

<?php
function add_some_extra(&$string)
{
    $string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str;    // outputs 'This is a string, and something extra.'
?>

Default argument values

A function may define C++-style default values for scalar arguments as follows:

Example #3 Use of default parameters in functions

<?php
function makecoffee($type = "cappuccino")
{
    return "Making a cup of $type.\n";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("espresso");
?>

The above example will output:

Making a cup of cappuccino.
Making a cup of .
Making a cup of espresso.

PHP also allows the use of arrays and the special type NULL as default values, for example:

Example #4 Using non-scalar types as default values

<?php
function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL)
{
    $device = is_null($coffeeMaker) ? "hands" : $coffeeMaker;
    return "Making a cup of ".join(", ", $types)." with $device.\n";
}
echo makecoffee();
echo makecoffee(array("cappuccino", "lavazza"), "teapot");
?>

The default value must be a constant expression, not (for example) a variable, a class member or a function call.

Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected. Consider the following code snippet:

Example #5 Incorrect usage of default function arguments

<?php
function makeyogurt($type = "acidophilus", $flavour)
{
    return "Making a bowl of $type $flavour.\n";
}

echo makeyogurt("raspberry");   // won't work as expected
?>

The above example will output:

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

Now, compare the above with this:

Example #6 Correct usage of default function arguments

<?php
function makeyogurt($flavour, $type = "acidophilus")
{
    return "Making a bowl of $type $flavour.\n";
}

echo makeyogurt("raspberry");   // works as expected
?>

The above example will output:

Making a bowl of acidophilus raspberry.

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

Type declarations

Note:

Type declarations were also known as type hints in PHP 5.

Type declarations allow functions to require that parameters are of a certain type at call time. If the given value is of the incorrect type, then an error is generated: in PHP 5, this will be a recoverable fatal error, while PHP 7 will throw a TypeError exception.

To specify a type declaration, the type name should be added before the parameter name. The declaration can be made to accept NULL values if the default value of the parameter is set to NULL.

Valid types

Type | Description | Minimum PHP version
Class/interface name | The parameter must be an instanceof the given class or interface name. | PHP 5.0.0
self | The parameter must be an instanceof the same class as the one the method is defined on. This can only be used on class and instance methods. | PHP 5.0.0
array | The parameter must be an array. | PHP 5.1.0
callable | The parameter must be a valid callable. | PHP 5.4.0
bool | The parameter must be a boolean value. | PHP 7.0.0
float | The parameter must be a floating point number. | PHP 7.0.0
int | The parameter must be an integer. | PHP 7.0.0
string | The parameter must be a string. | PHP 7.0.0
iterable | The parameter must be either an array or an instanceof Traversable. | PHP 7.1.0
object | The parameter must be an object. | PHP 7.2.0
Warning

Aliases for the above scalar types are not supported. Instead, they are treated as class or interface names. For example, using boolean as a parameter or return type will require an argument or return value that is an instanceof the class or interface boolean, rather than of type bool:

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

The above example will output:

 Fatal error: Uncaught TypeError: Argument 1 passed to test() must be an instance of boolean, boolean given, called in - on line 1 and defined in -:1

Examples

Example #7 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);
?>

The above example will output:

C
D

Fatal error: Uncaught TypeError: Argument 1 passed to f() must be an instance of C, instance of E given, called in - on line 14 and defined in -:8
Stack trace:
#0 -(14): f(Object(E))
#1 {main}
  thrown in - on line 8

Example #8 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);
?>

The above example will output:

C

Fatal error: Uncaught TypeError: Argument 1 passed to f() must implement interface I, instance of 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 #9 Typed pass-by-reference Parameters

Declared types of reference parameters are checked on function entry, but not when the function returns, so after the function had returned, the argument's type may have changed.

<?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: Argument 1 passed to array_baz() must be of the type array, int given, called in %s on line %d

Example #10 Nullable type declaration

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

Strict typing

By default, PHP will coerce values of the wrong type into the expected scalar type if possible. For example, a function that is given an integer 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 variable of exact type of the type declaration will be accepted, or a TypeError will be thrown. The only exception to this rule is that an integer may be given to a function expecting a float. 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:

Caution

Enabling strict mode will also affect return type declarations.

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 (weak typing) will be respected, and the value will be coerced.

Note:

Strict typing is only defined for scalar type declarations, and as such, requires PHP 7.0.0 or later, as scalar type declarations were added in that version.

Example #11 Strict typing

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

The above example will output:

int(3)

Fatal error: Uncaught TypeError: Argument 1 passed to sum() must be of the type integer, 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 #12 Weak typing

<?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 #13 Catching TypeError

<?php
declare(strict_types=1);

function sum(int $a, int $b) {
    return $a + $b;
}

try {
    var_dump(sum(1, 2));
    var_dump(sum(1.5, 2.5));
} catch (TypeError $e) {
    echo 'Error: '.$e->getMessage();
}
?>

The above example will output:

int(3)
Error: Argument 1 passed to sum() must be of the type integer, float given, called in - on line 10

Variable-length argument lists

PHP has support for variable-length argument lists in user-defined functions. This is implemented using the ... token in PHP 5.6 and later, and using the func_num_args(), func_get_arg(), and func_get_args() functions in PHP 5.5 and earlier.

... in PHP 5.6+

In PHP 5.6 and later, argument 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; for example:

Example #14 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

You can also use ... when calling functions to unpack an array or Traversable variable or literal into the argument list:

Example #15 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 arguments 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 hint before the ... token. If this is present, then all arguments captured by ... must be objects of the hinted class.

Example #16 Type hinted 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, you may also pass variable arguments by reference by prefixing the ... with an ampersand (&).

Older versions of PHP

No special syntax is required to note that a function is variadic; however access to the function's arguments must use func_num_args(), func_get_arg() and func_get_args().

The first example above would be implemented as follows in PHP 5.5 and earlier:

Example #17 Accessing variable arguments in PHP 5.5 and earlier

<?php
function sum() {
    $acc = 0;
    foreach (func_get_args() as $n) {
        $acc += $n;
    }
    return $acc;
}

echo sum(1, 2, 3, 4);
?>

The above example will output:

10


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 array (0, 1, 2);
}
list ($zero, $one, $two) = small_numbers();
?>

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

Example #3 Returning a reference from a function

<?php
function &returns_reference()
{
    return $someref;
}

$newref =& returns_reference();
?>

For more information on references, please check out References Explained.

Return type declarations

PHP 7 adds support for return type declarations. Similarly to argument type declarations, return type declarations specify the type of the value that will be returned from a function. The same types are available for return type declarations as are available for argument type declarations.

Strict typing also has an effect on return type declarations. In the default weak mode, returned values will be coerced to the correct type if they are not already of that type. In strong mode, the returned value must be of the correct type, otherwise a TypeError will be thrown.

As of PHP 7.1.0, return values can be marked as nullable by prefixing the type name with a question mark (?). This signifies that the function returns either the specified type or NULL.

Note:

When overriding a parent method, the child's method must match any return type declaration on the parent. If the parent doesn't define a return type, then the child method may do so.

Examples

Example #4 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 #5 Strict mode in action

<?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: Return value of sum() must be of the type integer, float returned in - on line 5 in -:5
Stack trace:
#0 -(9): sum(1, 2.5)
#1 {main}
  thrown in - on line 5

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 return type declaration (as of PHP 7.1.0)

<?php
function get_item(): ?string {
    if (isset($_GET['item'])) {
        return $_GET['item'];
    } else {
        return null;
    }
}
?>


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.

?>

As of PHP 5.4.0, you can call any callable stored in a variable.

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" as of PHP 7.0.0; prior, it raised a fatal error
?>

See also is_callable(), call_user_func(), variable variables and function_exists().

Changelog

Version | Description
7.0.0 | 'ClassName::methodName' is allowed as variable function.
5.4.0 | Arrays, which are valid callables, are allowed as variable functions.


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.

See also function_exists(), the function reference, get_extension_funcs(), and dl().


Anonymous functions

Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses.

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. From PHP 7.1, these variables must not include superglobals, $this, or variables with the same name as a parameter.

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");
?>

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"

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) {
}

Output of the above example in PHP 5.3:

Notice: Undefined variable: this in script.php on line 8
NULL

As of PHP 5.4.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

As of PHP 5.4, 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
7.1.0 | Anonymous functions may not close over superglobals, $this, or any variable with the same name as a parameter.
5.4.0 | Anonymous functions may use $this, as well as be declared statically.
5.3.0 | Anonymous functions become available.

Notes

Note: It is possible to use func_num_args(), func_get_arg(), and func_get_args() from within a closure.


Classes and Objects

Table of Contents

  • Introduction
  • The Basics
  • Properties
  • 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
  • Type Hinting
  • Late Static Bindings
  • Objects and references
  • Object Serialization
  • Covariance and Contravariance
  • OOP Changelog


Introduction

As of PHP 5, PHP includes a complete object model. Some of its features are: visibility, abstract and final classes and methods, additional magic methods, interfaces, cloning and typehinting.

PHP treats objects in the same way as references or handles, meaning that each variable contains an object reference rather than a copy of the entire object. See Objects and References

Tip

See also the Userland Naming Guide.


The Basics

class

Basic class definitions begin with the keyword class, followed by a class name, followed by a pair of curly braces which enclose the definitions of the properties and methods belonging to the class.

The class name can be any valid label, provided it is not a PHP reserved word. A valid class name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: ^[a-zA-Z_\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 a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object). As of PHP 7.0.0 calling a non-static method statically from an incompatible context results in $this being undefined inside the method. Calling a non-static method statically from an incompatible context has been deprecated as of PHP 5.6.0. As of PHP 7.0.0 calling a non-static method statically has been generally deprecated (even if called from a compatible context). Before PHP 5.6.0 such calls already triggered a strict notice.

Example #2 Some examples of the $this pseudo-variable

We're assuming that error_reporting is disabled for this example; otherwise the following code would trigger deprecated and strict notices, respectively, depending on the PHP version.

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

$this is defined (A)
$this is not defined.
$this is defined (B)
$this is not defined.

Output of the above example in PHP 7:

$this is defined (A)
$this is not defined.
$this is not defined.
$this is not defined.

new

To create an instance of a class, the new keyword must be used. An object will always be created unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation (and in some cases this is a requirement).

If a string containing the name of a class is used with new, a new instance of that class will be created. If the class is in a namespace, its fully qualified name must be used when doing this.

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
$instance = new SimpleClass();

// This can also be done with a variable:
$className = 'SimpleClass';
$instance = new $className(); // new SimpleClass()
?>

In the class context, it is possible to create a new object by new self and new parent.

When assigning an already created instance of a class to a new variable, the new variable will access the same instance as the object that was assigned. This behaviour is the same when passing instances to a function. A copy of an already created object can be made by cloning it.

Example #4 Object Assignment

<?php

$instance = new SimpleClass();

$assigned   =  $instance;
$reference  =& $instance;

$instance->var = '$assigned will have this value';

$instance = null; // $instance and $reference become null

var_dump($instance);
var_dump($reference);
var_dump($assigned);
?>

The above example will output:

NULL
NULL
object(SimpleClass)#1 (1) {
   ["var"]=>
     string(30) "$assigned will have this value"
}

PHP 5.3.0 introduced a couple of new ways to create instances of an object:

Example #5 Creating new objects

<?php
class Test
{
    static public function getNew()
    {
        return new static;
    }
}

class Child extends Test
{}

$obj1 = new Test();
$obj2 = new $obj1;
var_dump($obj1 !== $obj2);

$obj3 = Test::getNew();
var_dump($obj3 instanceof Test);

$obj4 = Child::getNew();
var_dump($obj4 instanceof Child);
?>

The above example will output:

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

PHP 5.4.0 introduced the possibility to access a member of a newly created object in a single expression:

Example #6 Access member of newly created object

<?php
echo (new DateTime())->format('Y');
?>

The above example will output something similar to:

2016

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 #7 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. As of PHP 7.0.0 it is possible to call such a property directly by enclosing it in parentheses.

Example #8 Calling an anonymous function stored in a property

<?php
class Foo
{
    public $bar;

    public function __construct() {
        $this->bar = function() {
            return 42;
        };
    }
}

$obj = new Foo();

// as of PHP 5.3.0:
$func = $obj->bar;
echo $func(), PHP_EOL;

// alternatively, as of PHP 7.0.0:
echo ($obj->bar)(), PHP_EOL;

The above example will output:

42

extends

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

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

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

Example #9 Simple Class Inheritance

<?php
class ExtendClass extends SimpleClass
{
    // Redefine the parent method
    function displayVar()
    {
        echo "Extending class\n";
        parent::displayVar();
    }
}

$extended = new ExtendClass();
$extended->displayVar();
?>

The above example will output:

Extending class
a default value

::class

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

Example #10 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.


Properties

Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywords public, protected, or private, optionally 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--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

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

Note:

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

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

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

The pseudo-variable $this is available inside any class method when that method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).

Example #1 property declarations

<?php
class SimpleClass
{
   // valid as of PHP 5.6.0:
   public $var1 = 'hello ' . 'world';
   // valid as of PHP 5.3.0:
   public $var2 = <<<EOD
hello world
EOD;
   // valid as of PHP 5.6.0:
   public $var3 = 1+2;
   // invalid property declarations:
   public $var4 = self::myStaticMethod();
   public $var5 = $myVar;

   // valid property declarations:
   public $var6 = myConstant;
   public $var7 = array(true, false);

   // valid as of PHP 5.3.0:
   public $var8 = <<<'EOD'
hello world
EOD;
}
?>

Note:

There are some nice functions to handle classes and objects. You might want to take a look at the Class/Object Functions.

As of PHP 5.3.0 heredocs and nowdocs can be used in any static data context, including property declarations.

Example #2 Example of using a nowdoc to initialize a property

<?php
class foo {
   // As of PHP 5.3.0
   public $bar = <<<'EOT'
bar
EOT;
   public $baz = <<<EOT
baz
EOT;
}
?>

Note:

Nowdoc and Heredoc support was added in PHP 5.3.0.

As of PHP 7.4.0, property definitions can include a type declaration, with the exception of the callable type.

Example #3 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, "php");
echo "ID: " . $user->id;
echo "\n";
echo "Name: " . $user->name;

?>

The above example will output:

ID: 1234
Name: php


Class Constants

It is possible to define constant values on a per-class basis remaining the same and unchangeable. Constants differ from normal variables in that you don't use the $ symbol to declare or use them. The default visibility of class constants is public.

The value must be a constant expression, not (for example) a variable, a property, or a function call.

It's also possible for interfaces to have constants. Look at the interface documentation for examples.

As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static).

Note that class constants are allocated once per class, and not for each class instance.

Example #1 Defining and using a constant

<?php
class MyClass
{
    const CONSTANT = 'constant value';

    function showConstant() {
        echo  self::CONSTANT . "\n";
    }
}

echo MyClass::CONSTANT . "\n";

$classname = "MyClass";
echo $classname::CONSTANT . "\n"; // As of PHP 5.3.0

$class = new MyClass();
$class->showConstant();

echo $class::CONSTANT."\n"; // As of PHP 5.3.0
?>

Example #2 Static data example

<?php
class foo {
    // As of PHP 5.3.0
    const BAR = <<<'EOT'
bar
EOT;
    // As of PHP 5.3.0
    const BAZ = <<<EOT
baz
EOT;
}
?>

Note:

Support for initializing constants with Heredoc and Nowdoc syntax was added in PHP 5.3.0.

The special ::class constant is available as of PHP 5.5.0, and allows for fully qualified class name resolution at compile time, this is useful for namespaced classes:

Example #3 Namespaced ::class example

<?php
namespace foo {
    class bar {
    }

    echo bar::class; // foo\bar
}
?>

Example #4 Constant expression example

<?php
const ONE = 1;

class foo {
    // As of PHP 5.6.0
    const TWO = ONE * 2;
    const THREE = ONE + self::TWO;
    const SENTENCE = 'The value of THREE is '.self::THREE;
}
?>

It is possible to provide a scalar expression involving numeric and string literals and/or constants in context of a class constant.

Note:

Constant expression support was added in PHP 5.6.0.

Example #5 Class constant visibility modifiers

<?php
class Foo {
    // As of PHP 7.1.0
    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.


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

In PHP 5, this is no longer necessary. 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.

Tip

Although the __autoload() function can also be used for autoloading classes and interfaces, it's preferred to use the spl_autoload_register() function. This is because it is a more flexible alternative (enabling for any number of autoloaders to be specified in the application, such as in third party libraries). For this reason, using __autoload() is discouraged and deprecated as of PHP 7.2.0.

Note:

Prior to PHP 5.3, exceptions thrown in the __autoload() function could not be caught in the catch block and would result in a fatal error. From PHP 5.3 and upwards, this is possible provided that if a custom exception is thrown, then the custom exception class is available. The __autoload() function may be used recursively to autoload the custom exception class.

Note:

Autoloading is not available if using PHP in CLI interactive mode.

Note:

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

Example #1 Autoload example

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

<?php
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 Autoloading with exception handling for 5.3.0+

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

<?php
spl_autoload_register(function ($name) {
    echo "Want to load $name.\n";
    throw new Exception("Unable to load $name.");
});

try {
    $obj = new NonLoadableClass();
} catch (Exception $e) {
    echo $e->getMessage(), "\n";
}
?>

The above example will output:

Want to load NonLoadableClass.
Unable to load NonLoadableClass.

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

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

<?php
spl_autoload_register(function ($name) {
    echo "Want to load $name.\n";
    throw new MissingException("Unable to load $name.");
});

try {
    $obj = new NonLoadableClass();
} catch (Exception $e) {
    echo $e->getMessage(), "\n";
}
?>

The above example will output:

Want to load NonLoadableClass.
Want to load MissingException.

Fatal error: Class 'MissingException' not found in testMissingException.php on line 4

See Also

  • unserialize()
  • unserialize_callback_func
  • spl_autoload_register()
  • spl_autoload()
  • __autoload()


Constructors and Destructors

Constructor

__construct ([ mixed $args = "" [, $... ]] ) : void

PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.

Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private).

Example #1 using new unified constructors

<?php
class BaseClass {
    function __construct() {
        print "In BaseClass constructor\n";
    }
}

class SubClass extends BaseClass {
    function __construct() {
        parent::__construct();
        print "In SubClass constructor\n";
    }
}

class OtherSubClass extends BaseClass {
    // inherits BaseClass's constructor
}

// In BaseClass constructor
$obj = new BaseClass();

// In BaseClass constructor
// In SubClass constructor
$obj = new SubClass();

// In BaseClass constructor
$obj = new OtherSubClass();
?>

For backwards compatibility with PHP 3 and 4, if PHP cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class. Effectively, it means that the only case that would have compatibility issues is if the class had a method named __construct() which was used for different semantics.

Warning

Old style constructors are DEPRECATED in PHP 7.0, and will be removed in a future version. You should always use __construct() in new code.

Unlike with other methods, PHP will not generate an E_STRICT level error message when __construct() is overridden with different parameters than the parent __construct() method has.

As of PHP 5.3.3, methods with the same name as the last element of a namespaced class name will no longer be treated as constructor. This change doesn't affect non-namespaced classes.

Example #2 Constructors in namespaced classes

<?php
namespace Foo;
class Bar {
    public function Bar() {
        // treated as constructor in PHP 5.3.0-5.3.2
        // treated as regular method as of PHP 5.3.3
    }
}
?>

Destructor

__destruct ( void ) : void

PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.

Example #3 Destructor Example

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

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 must be defined as public, private, or protected. If declared using var, the property will be defined as public.

Example #1 Property declaration

<?php
/**
 * Define MyClass
 */
class MyClass
{
    public $public = 'Public';
    protected $protected = 'Protected';
    private $private = 'Private';

    function printHello()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}

$obj = new MyClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private

/**
 * Define MyClass2
 */
class MyClass2 extends MyClass
{
    // We can redeclare the public and protected 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

?>

Note: The PHP 4 method of declaring a variable with the var keyword is still supported for compatibility reasons (as a synonym for the public keyword). In PHP 5 before 5.1.3, its usage would generate an E_STRICT warning.

Method Visibility

Class methods may be defined as public, private, or protected. Methods declared without any explicit visibility keyword are defined as public.

Example #2 Method Declaration

<?php
/**
 * Define MyClass
 */
class MyClass
{
    // Declare a public constructor
    public function __construct() { }

    // Declare a public method
    public function MyPublic() { }

    // Declare a protected method
    protected function MyProtected() { }

    // Declare a private method
    private function MyPrivate() { }

    // This is public
    function Foo()
    {
        $this->MyPublic();
        $this->MyProtected();
        $this->MyPrivate();
    }
}

$myclass = new MyClass;
$myclass->MyPublic(); // Works
$myclass->MyProtected(); // Fatal Error
$myclass->MyPrivate(); // Fatal Error
$myclass->Foo(); // Public, Protected and Private work

/**
 * Define MyClass2
 */
class MyClass2 extends MyClass
{
    // This is public
    function Foo2()
    {
        $this->MyPublic();
        $this->MyProtected();
        $this->MyPrivate(); // Fatal Error
    }
}

$myclass2 = new MyClass2;
$myclass2->MyPublic(); // Works
$myclass2->Foo2(); // Public and Protected work, not Private

class Bar
{
    public function test() {
        $this->testPrivate();
        $this->testPublic();
    }

    public function testPublic() {
        echo "Bar::testPublic\n";
    }

    private function testPrivate() {
        echo "Bar::testPrivate\n";
    }
}

class Foo extends Bar
{
    public function testPublic() {
        echo "Foo::testPublic\n";
    }

    private function testPrivate() {
        echo "Foo::testPrivate\n";
    }
}

$myFoo = new Foo();
$myFoo->test(); // Bar::testPrivate
                // Foo::testPublic
?>

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 #3 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 #4 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 you extend a class, the subclass inherits all of the public and protected methods from the parent class. Unless a class overrides those methods, they will retain their original functionality.

This is useful for defining and abstracting functionality, and permits the implementation of additional functionality in similar objects without the need to reimplement all of the shared functionality.

Note:

Unless autoloading is used, then classes must be defined before they are used. If a class extends another, then the parent class must be declared before the child class structure. This rule applies to classes that inherit other classes and interfaces.

Example #1 Inheritance Example

<?php

class Foo
{
    public function printItem($string)
    {
        echo 'Foo: ' . $string . PHP_EOL;
    }

    public function printPHP()
    {
        echo 'PHP is great.' . PHP_EOL;
    }
}

class Bar extends Foo
{
    public function printItem($string)
    {
        echo 'Bar: ' . $string . PHP_EOL;
    }
}

$foo = new Foo();
$bar = new Bar();
$foo->printItem('baz'); // Output: 'Foo: baz'
$foo->printPHP();       // Output: 'PHP is great'
$bar->printItem('baz'); // Output: 'Bar: baz'
$bar->printPHP();       // Output: 'PHP is great'

?>


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 static, constant, and overridden properties or methods of a class.

When referencing these items from outside the class definition, use the name of the class.

As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static).

Paamayim Nekudotayim would, at first, seem like a strange choice for naming a double-colon. However, while writing the Zend Engine 0.5 (which powers PHP 3), that's what the Zend team decided to call it. It actually does mean double-colon - in Hebrew!

Example #1 :: from outside the class definition

<?php
class MyClass {
    const CONST_VALUE = 'A constant value';
}

$classname = 'MyClass';
echo $classname::CONST_VALUE; // As of PHP 5.3.0

echo MyClass::CONST_VALUE;
?>

Three special keywords self, parent and static are used to access properties or methods from inside the class definition.

Example #2 :: from inside the class definition

<?php
class OtherClass extends MyClass
{
    public static $my_static = 'static var';

    public static function doubleColon() {
        echo parent::CONST_VALUE . "\n";
        echo self::$my_static . "\n";
    }
}

$classname = 'OtherClass';
$classname::doubleColon(); // As of PHP 5.3.0

OtherClass::doubleColon();
?>

When an extending class overrides the parents definition of a method, PHP will not call the parent's method. It's up to the extended class on whether or not the parent's method is called. This also applies to Constructors and Destructors, Overloading, and Magic method definitions.

Example #3 Calling a parent's method

<?php
class MyClass
{
    protected function myFunc() {
        echo "MyClass::myFunc()\n";
    }
}

class OtherClass extends MyClass
{
    // Override parent's definition
    public function myFunc()
    {
        // But still call the parent function
        parent::myFunc();
        echo "OtherClass::myFunc()\n";
    }
}

$class = new OtherClass();
$class->myFunc();
?>

See also some examples of static call trickery.


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 and for late static bindings. Please refer to those pages for information on those meanings of static.

Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static cannot be accessed with an instantiated class object (though a static method can).

For compatibility with PHP 4, if no visibility declaration is used, then the property or method will be treated as if it was declared as public.

Static methods

Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside the method declared as static.

Caution

In PHP 5, calling non-static methods statically generates an E_STRICT level warning.

Warning

In PHP 7, calling non-static methods statically is deprecated, and will generate an E_DEPRECATED warning. Support for calling non-static methods statically may be removed in the future.

Example #1 Static method example

<?php
class Foo {
    public static function aStaticMethod() {
        // ...
    }
}

Foo::aStaticMethod();
$classname = 'Foo';
$classname::aStaticMethod(); // As of PHP 5.3.0
?>

Static properties

Static properties cannot be accessed through the object using the arrow operator ->.

Like any other PHP static variable, static properties may only be initialized using a literal or constant before PHP 5.6; expressions are not allowed. In PHP 5.6 and later, the same rules apply as const expressions: some limited expressions are possible, provided they can be evaluated at compile time.

As of PHP 5.3.0, 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"; // As of PHP 5.3.0

print Bar::$my_static . "\n";
$bar = new Bar();
print $bar->fooStatic() . "\n";
?>


Class Abstraction

PHP 5 introduces abstract classes and methods. Classes defined as abstract cannot be instantiated, and any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method's signature - they cannot define the implementation.

When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same (or a less restricted) visibility. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private. Furthermore the signatures of the methods must match, i.e. the type hints and the number of required arguments must be the same. For example, if the child class defines an optional argument, where the abstract method's signature does not, there is no conflict in the signature. This also applies to constructors as of PHP 5.4. Before 5.4 constructor signatures could differ.

Example #1 Abstract class example

<?php
abstract class AbstractClass
{
    // Force Extending class to define this method
    abstract protected function getValue();
    abstract protected function prefixValue($prefix);

    // Common method
    public function printOut() {
        print $this->getValue() . "\n";
    }
}

class ConcreteClass1 extends AbstractClass
{
    protected function getValue() {
        return "ConcreteClass1";
    }

    public function prefixValue($prefix) {
        return "{$prefix}ConcreteClass1";
    }
}

class ConcreteClass2 extends AbstractClass
{
    public function getValue() {
        return "ConcreteClass2";
    }

    public function prefixValue($prefix) {
        return "{$prefix}ConcreteClass2";
    }
}

$class1 = new ConcreteClass1;
$class1->printOut();
echo $class1->prefixValue('FOO_') ."\n";

$class2 = new ConcreteClass2;
$class2->printOut();
echo $class2->prefixValue('FOO_') ."\n";
?>

The above example will output:

ConcreteClass1
FOO_ConcreteClass1
ConcreteClass2
FOO_ConcreteClass2

Example #2 Abstract class example

<?php
abstract class AbstractClass
{
    // Our abstract method only needs to define the required arguments
    abstract protected function prefixName($name);

}

class ConcreteClass extends AbstractClass
{

    // Our child class may define optional arguments not in the parent's signature
    public function prefixName($name, $separator = ".") {
        if ($name == "Pacman") {
            $prefix = "Mr";
        } elseif ($name == "Pacwoman") {
            $prefix = "Mrs";
        } else {
            $prefix = "";
        }
        return "{$prefix}{$separator} {$name}";
    }
}

$class = new ConcreteClass;
echo $class->prefixName("Pacman"), "\n";
echo $class->prefixName("Pacwoman"), "\n";
?>

The above example will output:

Mr. Pacman
Mrs. Pacwoman

Old code that has no user-defined classes or functions named 'abstract' should run without modifications.


Object Interfaces

Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are implemented.

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.

Note that it is possible to declare a constructor in an interface, which can be useful in some contexts, e.g. for use by factories.

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.

Note:

Prior to PHP 5.3.9, a class could not implement two interfaces that specified a method with the same name, since it would cause ambiguity. More recent versions of PHP allow this as long as the duplicate methods have the same signature.

Note:

Interfaces can be extended like classes using the extends operator.

Note:

The class implementing the interface must use a method signatures which is compatible with LSP (Liskov Substitution Principle). Not doing so will result in a fatal error.

Constants

It's possible for interfaces to have constants. Interface constants work exactly like class constants except they cannot be overridden by a class/interface that inherits them.

Examples

Example #1 Interface example

<?php

// Declare the interface 'iTemplate'
interface iTemplate
{
    public function setVariable($name, $var);
    public function getHtml($template);
}

// Implement the interface
// This will work
class Template implements iTemplate
{
    private $vars = array();

    public function setVariable($name, $var)
    {
        $this->vars[$name] = $var;
    }

    public function getHtml($template)
    {
        foreach($this->vars as $name => $value) {
            $template = str_replace('{' . $name . '}', $value, $template);
        }

        return $template;
    }
}

// This will not work
// Fatal error: Class BadTemplate contains 1 abstract methods
// and must therefore be declared abstract (iTemplate::getHtml)
class BadTemplate implements iTemplate
{
    private $vars = array();

    public function setVariable($name, $var)
    {
        $this->vars[$name] = $var;
    }
}
?>

Example #2 Extendable Interfaces

<?php
interface a
{
    public function foo();
}

interface b extends a
{
    public function baz(Baz $baz);
}

// This will work
class c implements b
{
    public function foo()
    {
    }

    public function baz(Baz $baz)
    {
    }
}

// This will not work and result in a fatal error
class d implements b
{
    public function foo()
    {
    }

    public function baz(Foo $foo)
    {
    }
}
?>

Example #3 Multiple interface inheritance

<?php
interface a
{
    public function foo();
}

interface b
{
    public function bar();
}

interface c extends a, b
{
    public function baz();
}

class d implements c
{
    public function foo()
    {
    }

    public function bar()
    {
    }

    public function baz()
    {
    }
}
?>

Example #4 Interfaces with constants

<?php
interface a
{
    const b = 'Interface constant';
}

// Prints: Interface constant
echo a::b;

// This will however not work because it's not allowed to
// override constants.
class b implements a
{
    const b = 'Class constant';
}
?>

An interface, together with type-hinting, provides a good way to make sure that a particular object contains particular methods. See instanceof operator and type hinting.


Traits

As of PHP 5.4.0, PHP implements a method of code reuse called Traits.

Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. The semantics of the combination of Traits and classes is defined in a way which reduces complexity, and avoids the typical problems associated with multiple inheritance and Mixins.

A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own. It is an addition to traditional inheritance and enables horizontal composition of behavior; that is, the application of class members without requiring inheritance.

Example #1 Trait example

<?php
trait ezcReflectionReturnInfo {
    function getReturnType() { /*1*/ }
    function getReturnDescription() { /*2*/ }
}

class ezcReflectionMethod extends ReflectionMethod {
    use ezcReflectionReturnInfo;
    /* ... */
}

class ezcReflectionFunction extends ReflectionFunction {
    use ezcReflectionReturnInfo;
    /* ... */
}
?>

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

Note:

Prior to PHP 7.0, defining a property in a class with the same name as in a trait would throw an E_STRICT if the class definition was compatible (same visibility and initial value).

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.

Caution

A concrete class fulfills this requirement by defining a concrete method with the same name; its signature may 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 both static members and static methods.

Example #9 Static Variables

<?php
trait Counter {
    public function inc() {
        static $c = 0;
        $c = $c + 1;
        echo "$c\n";
    }
}

class C1 {
    use Counter;
}

class C2 {
    use Counter;
}

$o = new C1(); $o->inc(); // echo 1
$p = new C2(); $p->inc(); // echo 1
?>

Example #10 Static Methods

<?php
trait StaticExample {
    public static function doSomething() {
        return 'Doing something';
    }
}

class Example {
    use StaticExample;
}

Example::doSomething();
?>

Properties

Traits can also define properties.

Example #11 Defining Properties

<?php
trait PropertiesTrait {
    public $x = 1;
}

class PropertiesExample {
    use PropertiesTrait;
}

$example = new PropertiesExample;
$example->x;
?>

If a trait defines a property then a class can not define a property with the same name unless it is compatible (same visibility and initial value), otherwise a fatal error is issued. Before PHP 7.0.0, defining a property in the class with the same visibility and initial value as in the trait, raised an E_STRICT notice.

Example #12 Conflict Resolution

<?php
trait PropertiesTrait {
    public $same = true;
    public $different = false;
}

class PropertiesExample {
    use PropertiesTrait;
    public $same = true; // Allowed as of PHP 7.0.0; E_STRICT notice formerly
    public $different = true; // Fatal error
}
?>


Anonymous classes

Support for anonymous classes was added in PHP 7. Anonymous classes are useful when simple, one-off objects need to be created.

<?php

// Pre PHP 7 code
class Logger
{
    public function log($msg)
    {
        echo $msg;
    }
}

$util->setLogger(new Logger());

// PHP 7+ code
$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


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.

Changelog

Version | Description
5.3.0 | Added __callStatic(). Added warning to enforce public visibility and non-static declaration.
5.1.0 | Added __isset() and __unset(). Added support for __get() for overloading of private properties.
5.0.0 | Added __get().

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. As of PHP 5.3.0, a warning is issued if one of the magic overloading methods is declared static.

Note:

The return value of __set() is ignored because of the way PHP processes the assignment operator. Similarly, __get() is never called when chaining assignments together like this:

 $a = $obj->b = 8;

Example #1
     Overloading properties via the __get(),
     __set(), __isset()
     and __unset() methods

<?php
class PropertyTest
{
    /**  Location for overloaded data.  */
    private $data = array();

    /**  Overloading not used on declared properties.  */
    public $declared = 1;

    /**  Overloading only used on this when accessed outside the class.  */
    private $hidden = 2;

    public function __set($name, $value)
    {
        echo "Setting '$name' to '$value'\n";
        $this->data[$name] = $value;
    }

    public function __get($name)
    {
        echo "Getting '$name'\n";
        if (array_key_exists($name, $this->data)) {
            return $this->data[$name];
        }

        $trace = debug_backtrace();
        trigger_error(
            'Undefined property via __get(): ' . $name .
            ' in ' . $trace[0]['file'] .
            ' on line ' . $trace[0]['line'],
            E_USER_NOTICE);
        return null;
    }

    /**  As of PHP 5.1.0  */
    public function __isset($name)
    {
        echo "Is '$name' set?\n";
        return isset($this->data[$name]);
    }

    /**  As of PHP 5.1.0  */
    public function __unset($name)
    {
        echo "Unsetting '$name'\n";
        unset($this->data[$name]);
    }

    /**  Not a magic method, just here for example.  */
    public function getHidden()
    {
        return $this->hidden;
    }
}

echo "<pre>\n";

$obj = new PropertyTest;

$obj->a = 1;
echo $obj->a . "\n\n";

var_dump(isset($obj->a));
unset($obj->a);
var_dump(isset($obj->a));
echo "\n";

echo $obj->declared . "\n\n";

echo "Let's experiment with the private property named 'hidden':\n";
echo "Privates are visible inside the class, so __get() not used...\n";
echo $obj->getHidden() . "\n";
echo "Privates not visible outside of class, so __get() is used...\n";
echo $obj->hidden . "\n";
?>

The above example will output:

Setting 'a' to '1'
Getting 'a'
1

Is 'a' set?
bool(true)
Unsetting 'a'
Is 'a' set?
bool(false)

1

Let's experiment with the private property named 'hidden':
Privates are visible inside the class, so __get() not used...
2
Privates not visible outside of class, so __get() is used...
Getting 'hidden'

Notice:  Undefined property via __get(): hidden in <file> on line 70 in <file> on line 29

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

    /**  As of PHP 5.3.0  */
    public static function __callStatic($name, $arguments)
    {
        // Note: value of $name is case sensitive.
        echo "Calling static method '$name' "
             . implode(', ', $arguments). "\n";
    }
}

$obj = new MethodTest;
$obj->runTest('in object context');

MethodTest::runTest('in static context');  // As of PHP 5.3.0
?>

The above example will output:

Calling object method 'runTest' in object context
Calling static method 'runTest' in static context


Object Iteration

PHP 5 provides a way for objects to be defined so it is possible to iterate through a list of items, with, for example a foreach statement. By default, all visible properties will be used for the iteration.

Example #1 Simple Object Iteration

<?php
class MyClass
{
    public $var1 = 'value 1';
    public $var2 = 'value 2';
    public $var3 = 'value 3';

    protected $protected = 'protected var';
    private   $private   = 'private var';

    function iterateVisible() {
       echo "MyClass::iterateVisible:\n";
       foreach ($this as $key => $value) {
           print "$key => $value\n";
       }
    }
}

$class = new MyClass();

foreach($class as $key => $value) {
    print "$key => $value\n";
}
echo "\n";

$class->iterateVisible();

?>

The above example will output:

var1 => value 1
var2 => value 2
var3 => value 3

MyClass::iterateVisible:
var1 => value 1
var2 => value 2
var3 => value 3
protected => protected var
private => private var

As the output shows, the foreach iterated through all of the visible properties that could be accessed.

To take it a step further, the Iterator interface may be implemented. This allows the object to dictate how it will be iterated and what values will be available on each iteration.

Example #2 Object Iteration implementing Iterator

<?php
class MyIterator implements Iterator
{
    private $var = array();

    public function __construct($array)
    {
        if (is_array($array)) {
            $this->var = $array;
        }
    }

    public function rewind()
    {
        echo "rewinding\n";
        reset($this->var);
    }

    public function current()
    {
        $var = current($this->var);
        echo "current: $var\n";
        return $var;
    }

    public function key()
    {
        $var = key($this->var);
        echo "key: $var\n";
        return $var;
    }

    public function next()
    {
        $var = next($this->var);
        echo "next: $var\n";
        return $var;
    }

    public function valid()
    {
        $key = key($this->var);
        $var = ($key !== NULL && $key !== FALSE);
        echo "valid: $var\n";
        return $var;
    }

}

$values = array(1,2,3);
$it = new MyIterator($values);

foreach ($it as $a => $b) {
    print "$a: $b\n";
}
?>

The above example will output:

rewinding
valid: 1
current: 1
key: 0
0: 1
next: 2
valid: 1
current: 2
key: 1
1: 2
next: 3
valid: 1
current: 3
key: 2
2: 3
next:
valid:

The IteratorAggregate interface can be used as an alternative to implementing all of the Iterator methods. IteratorAggregate only requires the implementation of a single method, IteratorAggregate::getIterator(), which should return an instance of a class implementing Iterator.

Example #3 Object Iteration implementing IteratorAggregate

<?php
class MyCollection implements IteratorAggregate
{
    private $items = array();
    private $count = 0;

    // Required definition of interface IteratorAggregate
    public function getIterator() {
        return new MyIterator($this->items);
    }

    public function add($value) {
        $this->items[$this->count++] = $value;
    }
}

$coll = new MyCollection();
$coll->add('value 1');
$coll->add('value 2');
$coll->add('value 3');

foreach ($coll as $key => $val) {
    echo "key/value: [$key -> $val]\n\n";
}
?>

The above example will output:

rewinding
current: value 1
valid: 1
current: value 1
key: 0
key/value: [0 -> value 1]

next: value 2
current: value 2
valid: 1
current: value 2
key: 1
key/value: [1 -> value 2]

next: value 3
current: value 3
valid: 1
current: value 3
key: 2
key/value: [2 -> value 3]

next:
current:
valid:

Note:

For more examples of iterators, see the SPL Extension.

Note:

Users of PHP 5.5 and later may also want to investigate generators, which provide an alternative way of defining iterators.


Magic Methods

The function names
__construct(),
__destruct(),
__call(),
__callStatic(),
__get(),
__set(),
__isset(),
__unset(),
__sleep(),
__wakeup(),
__toString(),
__invoke(),
__set_state(),
__clone() and
__debugInfo()
are magical in PHP classes. You
cannot have functions with these names in any of your
classes unless you want the magic functionality associated
with them.

Note: All magic methods MUST be declared as public

Caution

PHP reserves all function names starting with __ as magical. It is recommended that you do not use function names with __ in PHP unless you want some documented magic functionality.

__sleep() and __wakeup()

public __sleep ( void ) : array
__wakeup ( void ) : void

serialize() checks if your class has a function with the magic name __sleep(). If so, that function is executed prior to any serialization. It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized. If the method doesn't return anything then NULL is serialized and E_NOTICE is issued.

Note:

It is not possible for __sleep() to return names of private properties in parent classes. Doing this will result in an E_NOTICE level error. Instead you may use the Serializable interface.

The intended use of __sleep() is to commit pending data or perform similar cleanup tasks. Also, the function is useful if you have very large objects which do not need to be saved completely.

Conversely, unserialize() checks for the presence of a function with the magic name __wakeup(). If present, this function can reconstruct any resources that the object may have.

The intended use of __wakeup() is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks.

Example #1 Sleep and wakeup

<?php
class Connection
{
    protected $link;
    private $dsn, $username, $password;

    public function __construct($dsn, $username, $password)
    {
        $this->dsn = $dsn;
        $this->username = $username;
        $this->password = $password;
        $this->connect();
    }

    private function connect()
    {
        $this->link = new PDO($this->dsn, $this->username, $this->password);
    }

    public function __sleep()
    {
        return array('dsn', 'username', 'password');
    }

    public function __wakeup()
    {
        $this->connect();
    }
}?>

__toString()

public __toString ( void ) : 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. This method must return a string, as otherwise a fatal E_RECOVERABLE_ERROR level error is emitted.

Warning

It was not possible to throw an exception from within a __toString() method before PHP 7.4.0. Doing so will result in a fatal error.

Example #2 Simple example

<?php
// Declare a simple class
class TestClass
{
    public $foo;

    public function __construct($foo)
    {
        $this->foo = $foo;
    }

    public function __toString()
    {
        return $this->foo;
    }
}

$class = new TestClass('Hello');
echo $class;
?>

The above example will output:

Hello

It is worth noting that before PHP 5.2.0 the __toString() method was only called when it was directly combined with echo or print. Since PHP 5.2.0, it is called in any string context (e.g. in printf() with %s modifier) but not in other types contexts (e.g. with %d modifier). Since PHP 5.2.0, converting objects without __toString() method to string would cause E_RECOVERABLE_ERROR.

__invoke()

__invoke ([ $... ] ) : mixed

The __invoke() method is called when a script tries to call an object as a function.

Note:

This feature is available since PHP 5.3.0.

Example #3 Using __invoke()

<?php
class CallableClass
{
    public function __invoke($x)
    {
        var_dump($x);
    }
}
$obj = new CallableClass;
$obj(5);
var_dump(is_callable($obj));
?>

The above example will output:

int(5)
bool(true)

__set_state()

static __set_state ( array $properties ) : object

This static method is called for classes exported by var_export() since PHP 5.1.0.

The only parameter of this method is an array containing exported properties in the form array('property' => value, ...).

Example #4 Using __set_state() (since PHP 5.1.0)

<?php

class A
{
    public $var1;
    public $var2;

    public static function __set_state($an_array) // As of PHP 5.1.0
    {
        $obj = new A;
        $obj->var1 = $an_array['var1'];
        $obj->var2 = $an_array['var2'];
        return $obj;
    }
}

$a = new A;
$a->var1 = 5;
$a->var2 = 'foo';

eval('$b = ' . var_export($a, true) . ';'); // $b = A::__set_state(array(
                                            //    'var1' => 5,
                                            //    'var2' => 'foo',
                                            // ));
var_dump($b);

?>

The above example will output:

object(A)#2 (2) {
  ["var1"]=>
  int(5)
  ["var2"]=>
  string(3) "foo"
}

Note: When exporting an object, var_export() does not check whether __set_state() is implemented by the object's class, so re-importing such objects will fail, 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 ( void ) : 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.

This feature was added in PHP 5.6.0.

Example #5 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

PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.

Example #1 Final methods example

<?php
class BaseClass {
   public function test() {
       echo "BaseClass::test() called\n";
   }

   final public function moreTesting() {
       echo "BaseClass::moreTesting() called\n";
   }
}

class ChildClass extends BaseClass {
   public function moreTesting() {
       echo "ChildClass::moreTesting() called\n";
   }
}
// Results in Fatal error: Cannot override final method BaseClass::moreTesting()
?>

Example #2 Final class example

<?php
final class BaseClass {
   public function test() {
       echo "BaseClass::test() called\n";
   }

   // Here it doesn't matter if you specify the function as final or not
   final public function moreTesting() {
       echo "BaseClass::moreTesting() called\n";
   }
}

class ChildClass extends BaseClass {
}
// Results in Fatal error: Class ChildClass may not inherit from final class (BaseClass)
?>

Note: Properties and constants cannot be declared final, only classes and methods may be declared as 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). An object's __clone() method cannot be called directly.

$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 ) : 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
        )

)

PHP 7.0.0 introduced the possibility 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 in PHP 5

<?php
function bool2str($bool)
{
    if ($bool === false) {
        return 'FALSE';
    } else {
        return 'TRUE';
    }
}

function compareObjects(&$o1, &$o2)
{
    echo 'o1 == o2 : ' . bool2str($o1 == $o2) . "\n";
    echo 'o1 != o2 : ' . bool2str($o1 != $o2) . "\n";
    echo 'o1 === o2 : ' . bool2str($o1 === $o2) . "\n";
    echo 'o1 !== o2 : ' . bool2str($o1 !== $o2) . "\n";
}

class Flag
{
    public $flag;

    function __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 (==).


  • « Comparing Objects
  • Late Static Bindings »
  • PHP Manual
  • Classes and Objects
  • Type Hinting

Type Hinting

This documentation has moved to the function reference.


Late Static Bindings

As of PHP 5.3.0, PHP implements a feature called late static bindings which can be used to reference the called class in a context of static inheritance.

More precisely, late static bindings work by storing the class named in the last "non-forwarding call". In case of static method calls, this is the class explicitly named (usually the one on the left of the :: operator); in case of non static method calls, it is the class of the object. A "forwarding call" is a static one that is introduced by self::, parent::, static::, or, if going up in the class hierarchy, forward_static_call(). The function get_called_class() can be used to retrieve a string with the name of the called class and static:: introduces its scope.

This feature was named "late static bindings" with an internal perspective in mind. "Late binding" comes from the fact that static:: will not be resolved using the class where the method is defined but it will rather be computed using runtime information. It was also called a "static binding" as it can be used for (but is not limited to) static method calls.

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 you to reference B from test() in the previous example. It was decided not to introduce a new keyword but rather use static that was already reserved.

Example #2 static:: simple usage

<?php
class A {
    public static function who() {
        echo __CLASS__;
    }
    public static function test() {
        static::who(); // Here comes Late Static Bindings
    }
}

class B extends A {
    public static function who() {
        echo __CLASS__;
    }
}

B::test();
?>

The above example will output:

B

Note:

In non-static contexts, the called class will be the class of the object instance. Since $this-> will try to call private methods from the same scope, using static:: may give different results. Another difference is that static:: can only refer to static properties.

Example #3 static:: usage in a non-static context

<?php
class A {
    private function foo() {
        echo "success!\n";
    }
    public function test() {
        $this->foo();
        static::foo();
    }
}

class B extends A {
   /* foo() will be copied to B, hence its scope will still be A and
    * the call be successful */
}

class C extends A {
    private function foo() {
        /* original method is replaced; the scope of the new one is C */
    }
}

$b = new B();
$b->test();
$c = new C();
$c->test();   //fails
?>

The above example will output:

success!
success!
success!

Fatal error:  Call to private method C::foo() from context 'A' in /tmp/test.php on line 9

Note:

Late static bindings' resolution will stop at a fully resolved static call with no fallback. On the other hand, static calls using keywords like parent:: or self:: will forward the calling information.

Example #4 Forwarding and non-forwarding calls

<?php
class A {
    public static function foo() {
        static::who();
    }

    public static function who() {
        echo __CLASS__."\n";
    }
}

class B extends A {
    public static function test() {
        A::foo();
        parent::foo();
        self::foo();
    }

    public static function who() {
        echo __CLASS__."\n";
    }
}
class C extends B {
    public static function who() {
        echo __CLASS__."\n";
    }
}

C::test();
?>

The above example will output:

A
C
C


Objects and references

One of the key-points of PHP 5 OOP that is often mentioned is that "objects are passed by references by default". This is not completely true. This section rectifies that general thought using some examples.

A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP 5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.

Example #1 References and Objects

<?php
class A {
    public $foo = 1;
}

$a = new A;
$b = $a;     // $a and $b are copies of the same identifier
             // ($a) = ($b) = <id>
$b->foo = 2;
echo $a->foo."\n";

$c = new A;
$d = &$c;    // $c and $d are references
             // ($c,$d) = <id>

$d->foo = 2;
echo $c->foo."\n";

$e = new A;

function foo($obj) {
    // ($obj) = ($e) = <id>
    $obj->foo = 2;
}

foo($e);
echo $e->foo."\n";

?>

The above example will output:

2
2
2


Object Serialization

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
// classa.inc:

  class A {
      public $one = 1;

      public function show_one() {
          echo $this->one;
      }
  }

// page1.php:

  include("classa.inc");

  $a = new A;
  $s = serialize($a);
  // store $s somewhere where page2.php can find it.
  file_put_contents('store', $s);

// page2.php:

  // this is needed for the unserialize to work properly.
  include("classa.inc");

  $s = file_get_contents('store');
  $a = unserialize($s);

  // now use the function show_one() of the $a object.
  $a->show_one();
?>

If an application is using sessions and uses session_register() to register objects, these objects are serialized automatically at the end of each PHP page, and are unserialized automatically on each of the following pages. This means that these objects can show up on any of the application's pages once they become part of the session. However, the session_register() is removed since PHP 5.4.0.

It is strongly recommended that if an application serializes objects, for use later in the application, that the application includes the class definition for that object throughout the application. Not doing so might result in an object being unserialized without a class definition, which will result in PHP giving the object a class of __PHP_Incomplete_Class_Name, which has no methods and would render the object useless.

So if in the example above $a became part of a session by running session_register("a"), you should include the file classa.inc on all of your pages, not only page1.php and page2.php.

Beyond the above advice, note that you can also hook into the serialization and unserialization events on an object using the __sleep() and __wakeup() methods. Using __sleep() also allows you to only serialize a subset of the object's properties.


Covariance and Contravariance

Prior to PHP 7.4.0, class methods support mainly invariant parameter types and invariant return types. This means that if a method within a parent class has a parameter type or return type of T, any child method with corresponding parameter type or return type must also be type T.

As of PHP 7.4.0, covariance and contravariance is supported. While these concepts may sound confusing, in practice they're rather simple, and extremely useful to object-oriented programming.

Covariance

Covariance allows a child's method to return a more specific type than the return type of its parent's method. This is better illustrated with an example.

We'll start with a simple abstract parent class, Animal, which is 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. We will build upon these classes with a few factories which return a new object of class type Animal, Cat, or Dog. Covariance will come into play in the next example.

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

Contravariance, on the other hand, allows a parameter type to be less specific in a child method, than that of its parent. Continuing with our previous example with the classes Animal, Cat, and Dog, we're adding a class called Food and AnimalFood, and adding a method eat(AnimalFood $food) to our 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 . " nom noms " . get_class($food);
    }
}

In order to see the behavior of contravariance, we will override the eat method 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 . " nom noms " . get_class($food);
    }
}

Now, we can see how contravariance works.

<?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 nom noms AnimalFood
Mavrick nom noms 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


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

  • Namespaces overview
  • Defining namespaces
  • Declaring sub-namespaces
  • Defining multiple namespaces in the same file
  • Using namespaces: Basics
  • Namespaces and dynamic language features
  • namespace keyword and __NAMESPACE__ constant
  • Using namespaces: Aliasing/Importing
  • Global space
  • Using namespaces: fallback to global function/constant
  • Name resolution rules
  • FAQ: things you need to know about namespaces


Namespaces overview

(PHP 5 >= 5.3.0, PHP 7)

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.

Version | Description
7.0.0 | Added Group use Declarations.

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)

Although any valid PHP code can be contained within a namespace, only the following types of code are affected by namespaces: classes (including abstracts and traits), interfaces, functions and constants.

Namespaces are declared using the namespace keyword. A file containing a namespace must declare the namespace at the top of the file before any other code - with one exception: the declare keyword.

Example #1 Declaring a single namespace

<?php
namespace MyProject;

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }

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

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)

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)

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


namespace keyword and __NAMESPACE__ constant

(PHP 5 >= 5.3.0, PHP 7)

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)

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.

All versions of PHP that support namespaces support three kinds of aliasing or importing: aliasing a class name, aliasing an interface name, and aliasing a namespace name. PHP 5.6+ also allows aliasing or importing function and constant names.

In PHP, 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 (PHP 5.6+)
use function My\Full\functionName;

// aliasing a function (PHP 5.6+)
use function My\Full\functionName as func;

// importing a constant (PHP 5.6+)
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

From PHP 7.0 onwards, classes, functions and constants being imported from the same namespace can be grouped together in a single use statement.

<?php

// Pre PHP 7 code
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;

// PHP 7+ code
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)

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 global function/constant

(PHP 5 >= 5.3.0, PHP 7)

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)

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\fn; a usage such as fn() resolves to the name A\B\fn.
  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)

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 cannot conflict with classes defined in the same file.
  2. Nested namespaces are not allowed.
  3. Before PHP 5.6 neither functions nor constants can be imported via the use statement.
  4. Dynamic namespace names (quoted identifiers) should escape backslash.
  5. Undefined Constants referenced using any backslash die with fatal error
  6. Cannot override special constants NULL, TRUE, FALSE, ZEND_THREAD_SAFE or ZEND_DEBUG_BUILD

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 $typehintexample = 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 type hint
function test(MyClass $typehintexample = null) {}
// another way to use a class from the current namespace as a type hint
function test(\foo\MyClass $typehintexample = null) {}

// extending a class from the current namespace
class Extended extends MyClass {}

// accessing a global function
$a = \globalfunc();

// accessing a global constant
$b = \INI_ALL;
?>

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 cannot 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 {}
}
?>

Before PHP 5.6 neither functions nor constants can be imported via the use statement.

Before PHP 5.6 the only elements that are affected by use statements are namespaces and class names. In order to shorten a long constant or function, import its containing namespace.

<?php
namespace mine;
use ultra\long\ns\name;

$a = name\CONSTANT;
name\func();
?>
As of PHP 5.6 aliasing or importing function and constant names is allowed.

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, FALSE, ZEND_THREAD_SAFE or ZEND_DEBUG_BUILD

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


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 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_STRICT & ~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
    • Exception
      • ...


Exceptions

Table of Contents

  • Extending Exceptions

PHP has an exception model similar to that of other programming languages. An exception can be thrown, and caught ("catched") within PHP. Code may be surrounded in a try block, to facilitate the catching of potential exceptions. Each try must have at least one corresponding catch or finally block.

The thrown object must be an instance of the Exception class or a subclass of Exception. Trying to throw an object that is not will result in a PHP Fatal Error.

catch

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 thrown (or re-thrown) within a catch block.

When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception ..." message, unless a handler has been defined with set_exception_handler().

In PHP 7.1 and later, 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.

finally

In PHP 5.5 and later, 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. Additionaly, if the finally block also contains a return statement, the value from the finally block is returned.

Notes

Note:

Internal PHP functions mainly use Error reporting, only modern Object oriented extensions use exceptions. However, errors can be simply translated to exceptions with ErrorException.

Tip

The Standard PHP Library (SPL) provides a good number of built-in exceptions.

Examples

Example #3 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 #4 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 #5 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 #6 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 #7 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"


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 extends 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 = null, $code = 0, Exception $previous = null);

    final private function __clone();           // Inhibits cloning of exceptions.

    final public  function getMessage();        // message of exception
    final public  function getCode();           // code of exception
    final public  function getFile();           // source filename
    final public  function getLine();           // source line
    final public  function getTrace();          // an array of the backtrace()
    final public  function getPrevious();       // previous exception
    final public  function getTraceAsString();  // formatted string of trace

    // Overrideable
    public function __toString();               // formatted string for display
}
?>

If a class extends the built-in Exception class and re-defines the constructor, it is highly recommended that it also call parent::__construct() to ensure all available data has been properly assigned. The __toString() method can be overridden to provide a custom output when the object is presented as a string.

Note:

Exceptions cannot be cloned. Attempting to clone an Exception will result in a fatal E_ERROR error.

Example #2 Extending the Exception class (PHP 5.3.0+)

<?php
/**
 * Define a custom exception class
 */
class MyException extends Exception
{
    // Redefine the exception so message isn't optional
    public function __construct($message, $code = 0, Exception $previous = null) {
        // some code

        // make sure everything is assigned properly
        parent::__construct($message, $code, $previous);
    }

    // custom string representation of object
    public function __toString() {
        return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
    }

    public function customFunction() {
        echo "A custom function for this type of exception\n";
    }
}

/**
 * Create a class to test the exception
 */
class TestException
{
    public $var;

    const THROW_NONE    = 0;
    const THROW_CUSTOM  = 1;
    const THROW_DEFAULT = 2;

    function __construct($avalue = self::THROW_NONE) {

        switch ($avalue) {
            case self::THROW_CUSTOM:
                // throw custom exception
                throw new MyException('1 is an invalid parameter', 5);
                break;

            case self::THROW_DEFAULT:
                // throw default one.
                throw new Exception('2 is not allowed as a parameter', 6);
                break;

            default:
                // No exception, object will be created.
                $this->var = $avalue;
                break;
        }
    }
}

// Example 1
try {
    $o = new TestException(TestException::THROW_CUSTOM);
} catch (MyException $e) {      // Will be caught
    echo "Caught my exception\n", $e;
    $e->customFunction();
} catch (Exception $e) {        // Skipped
    echo "Caught Default Exception\n", $e;
}

// Continue execution
var_dump($o); // Null
echo "\n\n";

// Example 2
try {
    $o = new TestException(TestException::THROW_DEFAULT);
} catch (MyException $e) {      // Doesn't match this type
    echo "Caught my exception\n", $e;
    $e->customFunction();
} catch (Exception $e) {        // Will be caught
    echo "Caught Default Exception\n", $e;
}

// Continue execution
var_dump($o); // Null
echo "\n\n";

// Example 3
try {
    $o = new TestException(TestException::THROW_CUSTOM);
} catch (Exception $e) {        // Will be caught
    echo "Default Exception caught\n", $e;
}

// Continue execution
var_dump($o); // Null
echo "\n\n";

// Example 4
try {
    $o = new TestException();
} catch (Exception $e) {        // Skipped, no exception
    echo "Default Exception caught\n", $e;
}

// Continue execution
var_dump($o); // TestException
echo "\n\n";
?>

Note:

Versions of PHP 5, prior to PHP 5.3.0 do not support nesting of exceptions. The following code fragment can be used as a replacement MyException class if you wish to run this example.

<?php
/**
 * Define a custom exception class
 */
class MyException extends Exception
{
    // Redefine the exception so message isn't optional
    public function __construct($message, $code = 0) {
        // some code

        // make sure everything is assigned properly
        parent::__construct($message, $code);
    }

    // custom string representation of object
    public function __toString() {
        return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
    }

    public function customFunction() {
        echo "A custom function for this type of exception\n";
    }
}
?>


Generators

Table of Contents

  • Generators overview
  • Generator syntax
  • Comparing generators with Iterator objects


Generators overview

(PHP 5 >= 5.5.0, PHP 7)

Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the Iterator interface.

A generator allows you to write code that uses foreach to iterate over a set of data without needing to build an array in memory, which may cause you to exceed a memory limit, or require a considerable amount of processing time to generate. Instead, you can write a generator function, which is the same as a normal function, except that instead of returning once, a generator can yield as many times as it needs to in order to provide the values to be iterated over.

A simple example of this is to reimplement the range() function as a generator. The standard range() function has to generate an array with every value in it and return it, which can result in large arrays: for example, calling range(0, 1000000) will result in well over 100 MB of memory being used.

As an alternative, we can implement an xrange() generator, which will only ever need enough memory to create an Iterator object and track the current state of the generator internally, which turns out to be less than 1 kilobyte.

Example #1 Implementing range() as a generator

<?php
function xrange($start, $limit, $step = 1) {
    if ($start <= $limit) {
        if ($step <= 0) {
            throw new LogicException('Step must be 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 yields 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 exit, and the calling code continues just as if an array has run out of values.

Note:

In PHP 5, a generator could not return a value: doing so would result in a compile error. An empty return statement was valid syntax within a generator and it would terminate the generator. Since PHP 7.0, 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.

Caution

If you use yield in an expression context (for example, on the right hand side of an assignment), you must surround the yield statement with parentheses in PHP 5. For example, this is valid:

$data = (yield $value);

But this is not, and will result in a parse error in PHP 5:

$data = yield $value;

The parenthetical restrictions do not apply in PHP 7.

The value that will be assigned to $data is the value passed to Generator::send(), or NULL if Generator::next() is called instead.

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
Caution

As with the simple value yields shown earlier, yielding a key/value pair in an expression context requires the yield statement to be parenthesised:

$data = (yield $key => $value);

Yielding null values

Yield can be called without an argument to yield a NULL value with an automatic key.

Example #3 Yielding NULLs

<?php
function gen_three_nulls() {
    foreach (range(1, 3) as $i) {
        yield;
    }
}

var_dump(iterator_to_array(gen_three_nulls()));
?>

The above example will output:

array(3) {
  [0]=>
  NULL
  [1]=>
  NULL
  [2]=>
  NULL
}

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

In PHP 7, 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 use_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.


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);
?>
Since PHP 5, new returns a reference automatically, so using =& in this context is deprecated and produces an E_DEPRECATED message in PHP 5.3 and later, and an E_STRICT message in earlier versions. As of PHP 7.0 it is syntactically invalid. (Technically, the difference is that, in PHP 5, object variables, much like resources, are a mere pointer to the actual object data, so these object references are not "references" in the same sense used before (aliases). For more information, see Objects and references.)

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. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);. And as of PHP 5.4.0, call-time pass-by-reference was removed, so using it will raise a fatal error.

The following things can be passed by reference:

  • 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 fatal error as of PHP 5.0.5, strict standards notice
            // as of PHP 5.1.1, and notice as of PHP 7.0.0

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. Since PHP 5.1.0, an E_NOTICE error is issued if the code tries to return a dynamic expression or a result of the new operator.

To use the returned reference, you must use reference assignment:

<?php
function &collector() {
  static $collection = array();
  return $collection;
}
$collection = &collector();
$collection[] = 'foo';
?>
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.

$this

In an object method, $this is always a reference to the called object.


Predefined Variables

PHP provides a large number of predefined variables to all scripts. The variables represent everything from external variables to built-in environment variables, last error messages to last retrieved headers.

See also the FAQ titled "How does register_globals affect me?"

Table of Contents

  • Superglobals — Superglobals are 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 — HTTP GET variables
  • $_POST — HTTP POST variables
  • $_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_RAW_POST_DATA — Raw POST data
  • $http_response_header — HTTP response headers
  • $argc — The number of arguments passed to script
  • $argv — Array of arguments passed to script


Superglobals are built-in variables that are always available in all scopes

  • « Predefined Variables
  • $GLOBALS »
  • PHP Manual
  • Predefined Variables
  • Superglobals are built-in variables that are always available in all scopes

Superglobals

Superglobals — Superglobals are 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: Dealing with register_globals

If the deprecated register_globals directive is set to on then the variables within will also be made available in the global scope of the script. For example, $_POST['foo'] would also exist as $foo.

For related information, see the FAQ titled "How does register_globals affect me?"

Note: Variable variables

Superglobals cannot be used as variable variables inside functions or class methods.

See Also

  • variable scope
  • The variables_order directive
  • The filter extension


References all variables available in global scope

  • « Superglobals
  • $_SERVER »
  • PHP Manual
  • Predefined Variables
  • References all variables available in global scope

$GLOBALS

(PHP 4, PHP 5, PHP 7)

$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

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.


Server and execution environment information

  • « $GLOBALS
  • $_GET »
  • PHP Manual
  • Predefined Variables
  • Server and execution environment information

$_SERVER

$HTTP_SERVER_VARS [removed]

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

$_SERVER -- $HTTP_SERVER_VARS [removed] — 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. There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here. That said, a large number of these variables are accounted for in the » CGI/1.1 specification, so you should be able to expect those.

Note: Prior to PHP 5.4.0, $HTTP_SERVER_VARS contained the same initial information, but was not a superglobal. (Note that $HTTP_SERVER_VARS and $_SERVER were different variables and that PHP handled them as such.)

Indices

You may or may not find any of the following elements in $_SERVER. Note that few, if any, of these will be available (or indeed have any meaning) if running PHP on the command line.

'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 since PHP 4.3.0. Previously it was not available.
'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, you must set UseCanonicalName = On and ServerName. 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 of the start of the request. Available since PHP 5.1.0.
'REQUEST_TIME_FLOAT'
The timestamp of the start of the request, with microsecond precision. Available since PHP 5.4.0.
'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.
'HTTP_ACCEPT'
Contents of the Accept: header from the current request, if there is one.
'HTTP_ACCEPT_CHARSET'
Contents of the Accept-Charset: header from the current request, if there is one. Example: 'iso-8859-1,*,utf-8'.
'HTTP_ACCEPT_ENCODING'
Contents of the Accept-Encoding: header from the current request, if there is one. Example: 'gzip'.
'HTTP_ACCEPT_LANGUAGE'
Contents of the Accept-Language: header from the current request, if there is one. Example: 'en'.
'HTTP_CONNECTION'
Contents of the Connection: header from the current request, if there is one. Example: 'Keep-Alive'.
'HTTP_HOST'
Contents of the Host: header from the current request, if there is one.
'HTTP_REFERER'
The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.
'HTTP_USER_AGENT'
Contents of the User-Agent: header from the current request, if there is one. This is a string denoting the user agent being which is accessing the page. A typical example is: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586). Among other things, you can use this value with get_browser() to tailor your page's output to the capabilities of the user agent.
'HTTPS'
Set to a non-empty value if the script was queried through the HTTPS protocol.

Note: Note that when using ISAPI with IIS, the value will be off if the request was not made 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: Your web server must be configured to create this variable. For example in Apache you'll need HostnameLookups On inside httpd.conf for it to exist. See also gethostbyaddr().

'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 the Apache 2, you must set UseCanonicalName = On, as well as UseCanonicalPhysicalPort = On in order to get the physical (real) port, otherwise, this value can be spoofed and it may or may not return the physical port value. It is not safe to rely on this value in security-dependent contexts.

'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: As of PHP 4.3.2, PATH_TRANSLATED is no longer set implicitly under the Apache 2 SAPI in contrast to the situation in Apache 1, where it's set to the same value as the SCRIPT_FILENAME server variable when it's not populated by Apache. This change was made to comply with the CGI specification that PATH_TRANSLATED should only exist if PATH_INFO is defined. Apache 2 users may use AcceptPathInfo = On inside httpd.conf to define PATH_INFO.

'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 URL 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.

Changelog

Version | Description
5.4.0 | $HTTP_SERVER_VARS isn't available anymore due to the removal of long arrays registering.
5.3.0 | Directive register_long_arrays which caused $HTTP_SERVER_VARS to be available has been deprecated.

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


HTTP GET variables

  • « $_SERVER
  • $_POST »
  • PHP Manual
  • Predefined Variables
  • HTTP GET variables

$_GET

$HTTP_GET_VARS [deprecated]

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

$_GET -- $HTTP_GET_VARS [deprecated] — HTTP GET variables

Description

An associative array of variables passed to the current script via the URL parameters (aka. query string). Note that the array is not only populated for GET requests, but rather for all requests with a query string.

$HTTP_GET_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_GET_VARS and $_GET are different variables and that PHP handles them as such)

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 GET variables are passed through urldecode().

See Also

  • Handling external variables
  • The filter extension


HTTP POST variables

  • « $_GET
  • $_FILES »
  • PHP Manual
  • Predefined Variables
  • HTTP POST variables

$_POST

$HTTP_POST_VARS [deprecated]

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

$_POST -- $HTTP_POST_VARS [deprecated] — HTTP POST variables

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.

$HTTP_POST_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_POST_VARS and $_POST are different variables and that PHP handles them as such)

Examples

Example #1 $_POST example

<?php
echo 'Hello ' . htmlspecialchars($_POST["name"]) . '!';
?>

Assuming the user POSTed name=Hannes

The above example will output something similar to:

Hello Hannes!

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

  • Handling external variables
  • The filter extension


HTTP File Upload variables

  • « $_POST
  • $_REQUEST »
  • PHP Manual
  • Predefined Variables
  • HTTP File Upload variables

$_FILES

$HTTP_POST_FILES [deprecated]

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

$_FILES -- $HTTP_POST_FILES [deprecated] — 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.

$HTTP_POST_FILES contains the same initial information, but is not a superglobal. (Note that $HTTP_POST_FILES and $_FILES are different variables and that PHP handles them as such)

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


HTTP Request variables

  • « $_FILES
  • $_SESSION »
  • PHP Manual
  • Predefined Variables
  • HTTP Request variables

$_REQUEST

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

$_REQUEST — HTTP Request variables

Description

An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE.

Changelog

Version | Description
5.3.0 | Introduced request_order. This directive affects the contents of $_REQUEST.

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 variables_order configuration directive.

See Also

  • import_request_variables() - Import GET/POST/Cookie variables into the global scope
  • Handling external variables
  • The filter extension


Session variables

  • « $_REQUEST
  • $_ENV »
  • PHP Manual
  • Predefined Variables
  • Session variables

$_SESSION

$HTTP_SESSION_VARS [deprecated]

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

$_SESSION -- $HTTP_SESSION_VARS [deprecated] — 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.

$HTTP_SESSION_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_SESSION_VARS and $_SESSION are different variables and that PHP handles them as such)

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


Environment variables

  • « $_SESSION
  • $_COOKIE »
  • PHP Manual
  • Predefined Variables
  • Environment variables

$_ENV

$HTTP_ENV_VARS [deprecated]

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

$_ENV -- $HTTP_ENV_VARS [deprecated] — 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.

$HTTP_ENV_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_ENV_VARS and $_ENV are different variables and that PHP handles them as such)

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 an environment variable
  • The filter extension


HTTP Cookies

  • « $_ENV
  • $php_errormsg »
  • PHP Manual
  • Predefined Variables
  • HTTP Cookies

$_COOKIE

$HTTP_COOKIE_VARS [deprecated]

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

$_COOKIE -- $HTTP_COOKIE_VARS [deprecated] — HTTP Cookies

Description

An associative array of variables passed to the current script via HTTP Cookies.

$HTTP_COOKIE_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_COOKIE_VARS and $_COOKIE are different variables and that PHP handles them as such)

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


The previous error message

  • « $_COOKIE
  • $HTTP_RAW_POST_DATA »
  • PHP Manual
  • Predefined Variables
  • The previous error message

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

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


Raw POST data

  • « $php_errormsg
  • $http_response_header »
  • PHP Manual
  • Predefined Variables
  • Raw POST data

$HTTP_RAW_POST_DATA

(PHP 4, PHP 5)

$HTTP_RAW_POST_DATA — Raw POST data

Description

Warning

This feature was DEPRECATED in PHP 5.6.0, and REMOVED as of PHP 7.0.0.

$HTTP_RAW_POST_DATA contains the raw POST data. See always_populate_raw_post_data.

In general, php://input should be used instead of $HTTP_RAW_POST_DATA.


HTTP response headers

  • « $HTTP_RAW_POST_DATA
  • $argc »
  • PHP Manual
  • Predefined Variables
  • HTTP response headers

$http_response_header

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

$http_response_header — HTTP response headers

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);
}
get_contents();
var_dump($http_response_header);
?>

The above example will output something similar to:

array(9) {
  [0]=>
  string(15) "HTTP/1.1 200 OK"
  [1]=>
  string(35) "Date: Sat, 12 Apr 2008 17:30:38 GMT"
  [2]=>
  string(29) "Server: Apache/2.2.3 (CentOS)"
  [3]=>
  string(44) "Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT"
  [4]=>
  string(27) "ETag: "280100-1b6-80bfd280""
  [5]=>
  string(20) "Accept-Ranges: bytes"
  [6]=>
  string(19) "Content-Length: 438"
  [7]=>
  string(17) "Connection: close"
  [8]=>
  string(38) "Content-Type: text/html; charset=UTF-8"
}
NULL


The number of arguments passed to script

  • « $http_response_header
  • $argv »
  • PHP Manual
  • Predefined Variables
  • The number of arguments passed to script

$argc

(PHP 4, PHP 5, PHP 7)

$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


Array of arguments passed to script

  • « $argc
  • Predefined Exceptions »
  • PHP Manual
  • Predefined Variables
  • Array of arguments passed to script

$argv

(PHP 4, PHP 5, PHP 7)

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

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


Predefined Exceptions

Table of Contents

  • Exception
  • ErrorException
  • Error
  • ArgumentCountError
  • ArithmeticError
  • AssertionError
  • DivisionByZeroError
  • CompileError
  • ParseError
  • TypeError

See also the SPL Exceptions


Exception

(PHP 5, PHP 7)

Introduction

Exception is the base class for all Exceptions in PHP 5, and the base class for all user exceptions in PHP 7.

Before PHP 7, Exception did not implement the Throwable interface.

Class synopsis

Exception implements Throwable {
/* Properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Methods */
public __construct ([ string $message = "" [, int $code = 0 [, Throwable $previous = NULL ]]] )
final public getMessage ( void ) : string
final public getPrevious ( void ) : Throwable
final public getCode ( void ) : mixed
final public getFile ( void ) : string
final public getLine ( void ) : int
final public getTrace ( void ) : array
final public getTraceAsString ( void ) : string
public __toString ( void ) : string
final private __clone ( void ) : 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

Table of Contents

  • Exception::__construct — Construct the exception
  • Exception::getMessage — Gets the Exception message
  • Exception::getPrevious — Returns previous Exception
  • 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


Construct the exception

  • « Exception
  • Exception::getMessage »
  • PHP Manual
  • Exception
  • Construct the exception

Exception::__construct

(PHP 5, PHP 7)

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.

Changelog

Version | Description
7.0.0 | The previous parameter is now of type Throwable.
5.3.0 | The previous parameter was added.

Notes

Note:

The message is NOT binary safe.


Gets the Exception message

  • « Exception::__construct
  • Exception::getPrevious »
  • PHP Manual
  • Exception
  • Gets the Exception message

Exception::getMessage

(PHP 5, PHP 7)

Exception::getMessage — Gets the Exception message

Description

final public Exception::getMessage ( void ) : 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


Returns previous Exception

  • « Exception::getMessage
  • Exception::getCode »
  • PHP Manual
  • Exception
  • Returns previous Exception

Exception::getPrevious

(PHP 5 >= 5.3.0, PHP 7)

Exception::getPrevious — Returns previous Exception

Description

final public Exception::getPrevious ( void ) : Throwable

Returns previous exception (the third parameter of Exception::__construct()).

Parameters

This function has no parameters.

Return Values

Returns the previous Throwable if available or NULL otherwise.

Changelog

Version | Description
7.0.0 | The return type declaration changed to Throwable.

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


Gets the Exception code

  • « Exception::getPrevious
  • Exception::getFile »
  • PHP Manual
  • Exception
  • Gets the Exception code

Exception::getCode

(PHP 5, PHP 7)

Exception::getCode — Gets the Exception code

Description

final public Exception::getCode ( void ) : mixed

Returns the Exception code.

Parameters

This function has no parameters.

Return Values

Returns the exception code as integer 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


Gets the file in which the exception was created

  • « Exception::getCode
  • Exception::getLine »
  • PHP Manual
  • Exception
  • Gets the file in which the exception was created

Exception::getFile

(PHP 5, PHP 7)

Exception::getFile — Gets the file in which the exception was created

Description

final public Exception::getFile ( void ) : 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


Gets the line in which the exception was created

  • « Exception::getFile
  • Exception::getTrace »
  • PHP Manual
  • Exception
  • Gets the line in which the exception was created

Exception::getLine

(PHP 5, PHP 7)

Exception::getLine — Gets the line in which the exception was created

Description

final public Exception::getLine ( void ) : 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


Gets the stack trace

  • « Exception::getLine
  • Exception::getTraceAsString »
  • PHP Manual
  • Exception
  • Gets the stack trace

Exception::getTrace

(PHP 5, PHP 7)

Exception::getTrace — Gets the stack trace

Description

final public Exception::getTrace ( void ) : 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


Gets the stack trace as a string

  • « Exception::getTrace
  • Exception::__toString »
  • PHP Manual
  • Exception
  • Gets the stack trace as a string

Exception::getTraceAsString

(PHP 5, PHP 7)

Exception::getTraceAsString — Gets the stack trace as a string

Description

final public Exception::getTraceAsString ( void ) : 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


String representation of the exception

  • « Exception::getTraceAsString
  • Exception::__clone »
  • PHP Manual
  • Exception
  • String representation of the exception

Exception::__toString

(PHP 5, PHP 7)

Exception::__toString — String representation of the exception

Description

public Exception::__toString ( void ) : 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


Clone the exception

  • « Exception::__toString
  • ErrorException »
  • PHP Manual
  • Exception
  • Clone the exception

Exception::__clone

(PHP 5, PHP 7)

Exception::__clone — Clone the exception

Description

final private Exception::__clone ( void ) : void

Tries to clone the Exception, which results in Fatal error.

Parameters

This function has no parameters.

Return Values

No value is returned.

Errors/Exceptions

Exceptions are not clonable.


ErrorException

(PHP 5 >= 5.1.0, PHP 7)

Introduction

An Error Exception.

Class synopsis

ErrorException extends Exception {
/* Properties */
protected int $severity ;
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Methods */
public __construct ([ string $message = "" [, int $code = 0 [, int $severity = E_ERROR [, string $filename = __FILE__ [, int $lineno = __LINE__ [, Exception $previous = NULL ]]]]]] )
final public getSeverity ( void ) : int
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}

Properties

severity

The severity of the exception

Examples

Example #1 Use set_error_handler() to change error messages into ErrorException.

<?php
function exception_error_handler($severity, $message, $file, $line) {
    if (!(error_reporting() & $severity)) {
        // This error code is not included in error_reporting
        return;
    }
    throw new ErrorException($message, 0, $severity, $file, $line);
}
set_error_handler("exception_error_handler");

/* Trigger exception */
strpos();
?>

The above example will output something similar to:

Fatal error: Uncaught exception 'ErrorException' with message 'strpos() expects at least 2 parameters, 0 given' in /home/bjori/tmp/ex.php:12
Stack trace:
#0 [internal function]: exception_error_handler(2, 'strpos() expect...', '/home/bjori/php...', 12, Array)
#1 /home/bjori/php/cleandocs/test.php(12): strpos()
#2 {main}
  thrown in /home/bjori/tmp/ex.php on line 12

Table of Contents

  • ErrorException::__construct — Constructs the exception
  • ErrorException::getSeverity — Gets the exception severity


Constructs the exception

  • « ErrorException
  • ErrorException::getSeverity »
  • PHP Manual
  • ErrorException
  • Constructs the exception

ErrorException::__construct

(PHP 5 >= 5.1.0, PHP 7)

ErrorException::__construct — Constructs the exception

Description

public ErrorException::__construct ([ string $message = "" [, int $code = 0 [, int $severity = E_ERROR [, string $filename = __FILE__ [, int $lineno = __LINE__ [, Exception $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 integer value, it is intended that the error constants be used.

filename

The filename where the exception is thrown.

lineno

The line number where the exception is thrown.

previous

The previous exception used for the exception chaining.

Changelog

Version | Description
5.3.0 | The previous parameter was added.


Gets the exception severity

  • « ErrorException::__construct
  • Error »
  • PHP Manual
  • ErrorException
  • Gets the exception severity

ErrorException::getSeverity

(PHP 5 >= 5.1.0, PHP 7)

ErrorException::getSeverity — Gets the exception severity

Description

final public ErrorException::getSeverity ( void ) : 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)


Error

(PHP 7)

Introduction

Error is the base class for all internal PHP errors.

Class synopsis

Error implements Throwable {
/* Properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Methods */
public __construct ([ string $message = "" [, int $code = 0 [, Throwable $previous = NULL ]]] )
final public getMessage ( void ) : string
final public getPrevious ( void ) : Throwable
final public getCode ( void ) : mixed
final public getFile ( void ) : string
final public getLine ( void ) : int
final public getTrace ( void ) : array
final public getTraceAsString ( void ) : string
public __toString ( void ) : string
final private __clone ( void ) : void
}

Properties

message

The error message

code

The error code

file

The filename where the error happened

line

The line where the error happened

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


Construct the error object

  • « Error
  • Error::getMessage »
  • PHP Manual
  • Error
  • Construct the error object

Error::__construct

(No version information available, might only be in Git)

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.


Gets the error message

  • « Error::__construct
  • Error::getPrevious »
  • PHP Manual
  • Error
  • Gets the error message

Error::getMessage

(No version information available, might only be in Git)

Error::getMessage — Gets the error message

Description

final public Error::getMessage ( void ) : 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


Returns previous Throwable

  • « Error::getMessage
  • Error::getCode »
  • PHP Manual
  • Error
  • Returns previous Throwable

Error::getPrevious

(No version information available, might only be in Git)

Error::getPrevious — Returns previous Throwable

Description

final public Error::getPrevious ( void ) : 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


Gets the error code

  • « Error::getPrevious
  • Error::getFile »
  • PHP Manual
  • Error
  • Gets the error code

Error::getCode

(No version information available, might only be in Git)

Error::getCode — Gets the error code

Description

final public Error::getCode ( void ) : mixed

Returns the error code.

Parameters

This function has no parameters.

Return Values

Returns the error code as integer

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


Gets the file in which the error occurred

  • « Error::getCode
  • Error::getLine »
  • PHP Manual
  • Error
  • Gets the file in which the error occurred

Error::getFile

(No version information available, might only be in Git)

Error::getFile — Gets the file in which the error occurred

Description

final public Error::getFile ( void ) : 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


Gets the line in which the error occurred

  • « Error::getFile
  • Error::getTrace »
  • PHP Manual
  • Error
  • Gets the line in which the error occurred

Error::getLine

(No version information available, might only be in Git)

Error::getLine — Gets the line in which the error occurred

Description

final public Error::getLine ( void ) : 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


Gets the stack trace

  • « Error::getLine
  • Error::getTraceAsString »
  • PHP Manual
  • Error
  • Gets the stack trace

Error::getTrace

(No version information available, might only be in Git)

Error::getTrace — Gets the stack trace

Description

final public Error::getTrace ( void ) : 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


Gets the stack trace as a string

  • « Error::getTrace
  • Error::__toString »
  • PHP Manual
  • Error
  • Gets the stack trace as a string

Error::getTraceAsString

(No version information available, might only be in Git)

Error::getTraceAsString — Gets the stack trace as a string

Description

final public Error::getTraceAsString ( void ) : 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


String representation of the error

  • « Error::getTraceAsString
  • Error::__clone »
  • PHP Manual
  • Error
  • String representation of the error

Error::__toString

(No version information available, might only be in Git)

Error::__toString — String representation of the error

Description

public Error::__toString ( void ) : 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


Clone the error

  • « Error::__toString
  • ArgumentCountError »
  • PHP Manual
  • Error
  • Clone the error

Error::__clone

(No version information available, might only be in Git)

Error::__clone — Clone the error

Description

final private Error::__clone ( void ) : 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.


ArgumentCountError

(PHP 7 >= PHP 7.1.0)

Introduction

ArgumentCountError is thrown when too few arguments are passed to a user-defined function or method.

Class synopsis

ArgumentCountError extends TypeError {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Error::getMessage ( void ) : string
final public Error::getPrevious ( void ) : Throwable
final public Error::getCode ( void ) : mixed
final public Error::getFile ( void ) : string
final public Error::getLine ( void ) : int
final public Error::getTrace ( void ) : array
final public Error::getTraceAsString ( void ) : string
public Error::__toString ( void ) : string
final private Error::__clone ( void ) : void
}


ArithmeticError

(PHP 7)

Introduction

ArithmeticError is thrown when an error occurs while performing mathematical operations. In PHP 7.0, 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 integer.

Class synopsis

ArithmeticError extends Error {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Error::getMessage ( void ) : string
final public Error::getPrevious ( void ) : Throwable
final public Error::getCode ( void ) : mixed
final public Error::getFile ( void ) : string
final public Error::getLine ( void ) : int
final public Error::getTrace ( void ) : array
final public Error::getTraceAsString ( void ) : string
public Error::__toString ( void ) : string
final private Error::__clone ( void ) : void
}


AssertionError

(PHP 7)

Introduction

AssertionError is thrown when an assertion made via assert() fails.

Class synopsis

AssertionError extends Error {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Error::getMessage ( void ) : string
final public Error::getPrevious ( void ) : Throwable
final public Error::getCode ( void ) : mixed
final public Error::getFile ( void ) : string
final public Error::getLine ( void ) : int
final public Error::getTrace ( void ) : array
final public Error::getTraceAsString ( void ) : string
public Error::__toString ( void ) : string
final private Error::__clone ( void ) : void
}


DivisionByZeroError

(PHP 7)

Introduction

DivisionByZeroError is thrown when an attempt is made to divide a number by zero.

Class synopsis

DivisionByZeroError extends ArithmeticError {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Error::getMessage ( void ) : string
final public Error::getPrevious ( void ) : Throwable
final public Error::getCode ( void ) : mixed
final public Error::getFile ( void ) : string
final public Error::getLine ( void ) : int
final public Error::getTrace ( void ) : array
final public Error::getTraceAsString ( void ) : string
public Error::__toString ( void ) : string
final private Error::__clone ( void ) : void
}


CompileError

(PHP 7 > 7.3.0)

Introduction

CompileError is thrown for some compilation errors, which formerly issued a fatal error.

Class synopsis

CompileError extends Error {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Error::getMessage ( void ) : string
final public Error::getPrevious ( void ) : Throwable
final public Error::getCode ( void ) : mixed
final public Error::getFile ( void ) : string
final public Error::getLine ( void ) : int
final public Error::getTrace ( void ) : array
final public Error::getTraceAsString ( void ) : string
public Error::__toString ( void ) : string
final private Error::__clone ( void ) : void
}


ParseError

(PHP 7)

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

ParseError extends CompileError {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Error::getMessage ( void ) : string
final public Error::getPrevious ( void ) : Throwable
final public Error::getCode ( void ) : mixed
final public Error::getFile ( void ) : string
final public Error::getLine ( void ) : int
final public Error::getTrace ( void ) : array
final public Error::getTraceAsString ( void ) : string
public Error::__toString ( void ) : string
final private Error::__clone ( void ) : void
}


TypeError

(PHP 7)

Introduction

There are three scenarios where a TypeError may be thrown. The first is where the argument type being passed to a function does not match its corresponding declared parameter type. The second is where a value being returned from a function does not match the declared function return type. The third is where an invalid number of arguments are passed to a built-in PHP function (strict mode only).

Class synopsis

TypeError extends Error {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Error::getMessage ( void ) : string
final public Error::getPrevious ( void ) : Throwable
final public Error::getCode ( void ) : mixed
final public Error::getFile ( void ) : string
final public Error::getLine ( void ) : int
final public Error::getTrace ( void ) : array
final public Error::getTraceAsString ( void ) : string
public Error::__toString ( void ) : string
final private Error::__clone ( void ) : void
}


Predefined Interfaces and Classes

Table of Contents

  • Traversable
  • Iterator
  • IteratorAggregate
  • Throwable
  • ArrayAccess
  • Serializable
  • Closure
  • Generator
  • WeakReference

See also the SPL Interfaces and reserved classes.


The Traversable interface

(PHP 5, PHP 7)

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.

Note:

Internal (built-in) classes that implement this interface can be used in a foreach construct and do not need to implement IteratorAggregate or Iterator.

Note:

This is an internal engine interface which cannot be implemented in PHP scripts. Either IteratorAggregate or Iterator must be used instead. When implementing an interface which extends Traversable, make sure to list IteratorAggregate or Iterator before its name in the implements clause.

Interface synopsis

Traversable {
}

This interface has no methods, its only purpose is to be the base interface for all traversable classes.


The Iterator interface

(PHP 5, PHP 7)

Introduction

Interface for external iterators or objects that can be iterated themselves internally.

Interface synopsis

Iterator extends Traversable {
/* Methods */
abstract public current ( void ) : mixed
abstract public key ( void ) : scalar
abstract public next ( void ) : void
abstract public rewind ( void ) : void
abstract public valid ( void ) : 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() {
        var_dump(__METHOD__);
        $this->position = 0;
    }

    public function current() {
        var_dump(__METHOD__);
        return $this->array[$this->position];
    }

    public function key() {
        var_dump(__METHOD__);
        return $this->position;
    }

    public function next() {
        var_dump(__METHOD__);
        ++$this->position;
    }

    public function valid() {
        var_dump(__METHOD__);
        return isset($this->array[$this->position]);
    }
}

$it = new myIterator;

foreach($it as $key => $value) {
    var_dump($key, $value);
    echo "\n";
}
?>

The above example will output something similar to:

string(18) "myIterator::rewind"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
int(0)
string(12) "firstelement"

string(16) "myIterator::next"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
int(1)
string(13) "secondelement"

string(16) "myIterator::next"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
int(2)
string(11) "lastelement"

string(16) "myIterator::next"
string(17) "myIterator::valid"

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


Return the current element

  • « Iterator
  • Iterator::key »
  • PHP Manual
  • Iterator
  • Return the current element

Iterator::current

(PHP 5, PHP 7)

Iterator::current — Return the current element

Description

abstract public Iterator::current ( void ) : mixed

Returns the current element.

Parameters

This function has no parameters.

Return Values

Can return any type.


Return the key of the current element

  • « Iterator::current
  • Iterator::next »
  • PHP Manual
  • Iterator
  • Return the key of the current element

Iterator::key

(PHP 5, PHP 7)

Iterator::key — Return the key of the current element

Description

abstract public Iterator::key ( void ) : scalar

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.


Move forward to next element

  • « Iterator::key
  • Iterator::rewind »
  • PHP Manual
  • Iterator
  • Move forward to next element

Iterator::next

(PHP 5, PHP 7)

Iterator::next — Move forward to next element

Description

abstract public Iterator::next ( void ) : 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.


Rewind the Iterator to the first element

  • « Iterator::next
  • Iterator::valid »
  • PHP Manual
  • Iterator
  • Rewind the Iterator to the first element

Iterator::rewind

(PHP 5, PHP 7)

Iterator::rewind — Rewind the Iterator to the first element

Description

abstract public Iterator::rewind ( void ) : 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.

Parameters

This function has no parameters.

Return Values

Any returned value is ignored.


Checks if current position is valid

  • « Iterator::rewind
  • IteratorAggregate »
  • PHP Manual
  • Iterator
  • Checks if current position is valid

Iterator::valid

(PHP 5, PHP 7)

Iterator::valid — Checks if current position is valid

Description

abstract public Iterator::valid ( void ) : 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 boolean and then evaluated. Returns TRUE on success or FALSE on failure.


The IteratorAggregate interface

(PHP 5, PHP 7)

Introduction

Interface to create an external Iterator.

Interface synopsis

IteratorAggregate extends Traversable {
/* Methods */
abstract public getIterator ( void ) : Traversable
}

Example #1 Basic usage

<?php
class myData implements IteratorAggregate {
    public $property1 = "Public property one";
    public $property2 = "Public property two";
    public $property3 = "Public property three";

    public function __construct() {
        $this->property4 = "last property";
    }

    public function getIterator() {
        return new ArrayIterator($this);
    }
}

$obj = new myData;

foreach($obj as $key => $value) {
    var_dump($key, $value);
    echo "\n";
}
?>

The above example will output something similar to:

string(9) "property1"
string(19) "Public property one"

string(9) "property2"
string(19) "Public property two"

string(9) "property3"
string(21) "Public property three"

string(9) "property4"
string(13) "last property"

Table of Contents

  • IteratorAggregate::getIterator — Retrieve an external iterator


Retrieve an external iterator

  • « IteratorAggregate
  • Throwable »
  • PHP Manual
  • IteratorAggregate
  • Retrieve an external iterator

IteratorAggregate::getIterator

(PHP 5, PHP 7)

IteratorAggregate::getIterator — Retrieve an external iterator

Description

abstract public IteratorAggregate::getIterator ( void ) : Traversable

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.


Throwable

(PHP 7)

Introduction

Throwable is the base interface for any object that can be thrown via a throw statement in PHP 7, including Error and Exception.

Note:

PHP classes cannot implement the Throwable interface directly, and must instead extend Exception.

Interface synopsis

Throwable {
/* Methods */
abstract public getMessage ( void ) : string
abstract public getCode ( void ) : int
abstract public getFile ( void ) : string
abstract public getLine ( void ) : int
abstract public getTrace ( void ) : array
abstract public getTraceAsString ( void ) : string
abstract public getPrevious ( void ) : Throwable
abstract public __toString ( void ) : string
}

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


Gets the message

  • « Throwable
  • Throwable::getCode »
  • PHP Manual
  • Throwable
  • Gets the message

Throwable::getMessage

(PHP 7)

Throwable::getMessage — Gets the message

Description

abstract public Throwable::getMessage ( void ) : 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


Gets the exception code

  • « Throwable::getMessage
  • Throwable::getFile »
  • PHP Manual
  • Throwable
  • Gets the exception code

Throwable::getCode

(PHP 7)

Throwable::getCode — Gets the exception code

Description

abstract public Throwable::getCode ( void ) : int

Returns the error code associated with the thrown object.

Parameters

This function has no parameters.

Return Values

Returns the exception code as integer in Exception but possibly as other type in Exception descendants (for example as string in PDOException).

See Also

  • Exception::getCode() - Gets the Exception code


Gets the file in which the object was created

  • « Throwable::getCode
  • Throwable::getLine »
  • PHP Manual
  • Throwable
  • Gets the file in which the object was created

Throwable::getFile

(PHP 7)

Throwable::getFile — Gets the file in which the object was created

Description

abstract public Throwable::getFile ( void ) : 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


Gets the line on which the object was instantiated

  • « Throwable::getFile
  • Throwable::getTrace »
  • PHP Manual
  • Throwable
  • Gets the line on which the object was instantiated

Throwable::getLine

(PHP 7)

Throwable::getLine — Gets the line on which the object was instantiated

Description

abstract public Throwable::getLine ( void ) : 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


Gets the stack trace

  • « Throwable::getLine
  • Throwable::getTraceAsString »
  • PHP Manual
  • Throwable
  • Gets the stack trace

Throwable::getTrace

(PHP 7)

Throwable::getTrace — Gets the stack trace

Description

abstract public Throwable::getTrace ( void ) : 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


Gets the stack trace as a string

  • « Throwable::getTrace
  • Throwable::getPrevious »
  • PHP Manual
  • Throwable
  • Gets the stack trace as a string

Throwable::getTraceAsString

(PHP 7)

Throwable::getTraceAsString — Gets the stack trace as a string

Description

abstract public Throwable::getTraceAsString ( void ) : 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


Returns the previous Throwable

  • « Throwable::getTraceAsString
  • Throwable::__toString »
  • PHP Manual
  • Throwable
  • Returns the previous Throwable

Throwable::getPrevious

(PHP 7)

Throwable::getPrevious — Returns the previous Throwable

Description

abstract public Throwable::getPrevious ( void ) : 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 Exception


Gets a string representation of the thrown object

  • « Throwable::getPrevious
  • ArrayAccess »
  • PHP Manual
  • Throwable
  • Gets a string representation of the thrown object

Throwable::__toString

(PHP 7)

Throwable::__toString — Gets a string representation of the thrown object

Description

abstract public Throwable::__toString ( void ) : 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


The ArrayAccess interface

(PHP 5, PHP 7)

Introduction

Interface to provide accessing objects as arrays.

Interface synopsis

ArrayAccess {
/* Methods */
abstract public offsetExists ( mixed $offset ) : bool
abstract public offsetGet ( mixed $offset ) : mixed
abstract public offsetSet ( mixed $offset , mixed $value ) : void
abstract public offsetUnset ( mixed $offset ) : void
}

Example #1 Basic usage

<?php
class obj implements ArrayAccess {
    private $container = array();

    public function __construct() {
        $this->container = array(
            "one"   => 1,
            "two"   => 2,
            "three" => 3,
        );
    }

    public function offsetSet($offset, $value) {
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    public function offsetExists($offset) {
        return isset($this->container[$offset]);
    }

    public function offsetUnset($offset) {
        unset($this->container[$offset]);
    }

    public function offsetGet($offset) {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }
}

$obj = new obj;

var_dump(isset($obj["two"]));
var_dump($obj["two"]);
unset($obj["two"]);
var_dump(isset($obj["two"]));
$obj["two"] = "A value";
var_dump($obj["two"]);
$obj[] = 'Append 1';
$obj[] = 'Append 2';
$obj[] = 'Append 3';
print_r($obj);
?>

The above example will output something similar to:

bool(true)
int(2)
bool(false)
string(7) "A value"
obj Object
(
    [container:obj:private] => Array
        (
            [one] => 1
            [three] => 3
            [two] => A value
            [0] => Append 1
            [1] => Append 2
            [2] => Append 3
        )

)

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


Whether an offset exists

  • « ArrayAccess
  • ArrayAccess::offsetGet »
  • PHP Manual
  • ArrayAccess
  • Whether an offset exists

ArrayAccess::offsetExists

(PHP 5, PHP 7)

ArrayAccess::offsetExists — Whether an offset exists

Description

abstract 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 boolean if non-boolean was returned.

Examples

Example #1 ArrayAccess::offsetExists() example

<?php
class obj implements arrayaccess {
    public function offsetSet($offset, $value) {
        var_dump(__METHOD__);
    }
    public function offsetExists($var) {
        var_dump(__METHOD__);
        if ($var == "foobar") {
            return true;
        }
        return false;
    }
    public function offsetUnset($var) {
        var_dump(__METHOD__);
    }
    public function offsetGet($var) {
        var_dump(__METHOD__);
        return "value";
    }
}

$obj = new obj;

echo "Runs obj::offsetExists()\n";
var_dump(isset($obj["foobar"]));

echo "\nRuns obj::offsetExists() and obj::offsetGet()\n";
var_dump(empty($obj["foobar"]));

echo "\nRuns obj::offsetExists(), *not* obj:offsetGet() as there is nothing to get\n";
var_dump(empty($obj["foobaz"]));
?>

The above example will output something similar to:

Runs obj::offsetExists()
string(17) "obj::offsetExists"
bool(true)

Runs obj::offsetExists() and obj::offsetGet()
string(17) "obj::offsetExists"
string(14) "obj::offsetGet"
bool(false)

Runs obj::offsetExists(), *not* obj:offsetGet() as there is nothing to get
string(17) "obj::offsetExists"
bool(true)


Offset to retrieve

  • « ArrayAccess::offsetExists
  • ArrayAccess::offsetSet »
  • PHP Manual
  • ArrayAccess
  • Offset to retrieve

ArrayAccess::offsetGet

(PHP 5, PHP 7)

ArrayAccess::offsetGet — Offset to retrieve

Description

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

Notes

Note:

Starting with PHP 5.3.4, the prototype checks were relaxed and it's possible for implementations of this method to return by reference. This makes indirect modifications to the overloaded array dimensions of ArrayAccess objects possible.

A direct modification is one that replaces completely the value of the array dimension, as in $obj[6] = 7. An indirect modification, on the other hand, only changes part of the dimension, or attempts to assign the dimension by reference to another variable, as in $obj[6][7] = 7 or $var =& $obj[6]. Increments with ++ and decrements with -- are also implemented in a way that requires indirect modification.

While direct modification triggers a call to ArrayAccess::offsetSet(), indirect modification triggers a call to ArrayAccess::offsetGet(). In that case, the implementation of ArrayAccess::offsetGet() must be able to return by reference, otherwise an E_NOTICE message is raised.

Return Values

Can return all value types.

See Also

  • ArrayAccess::offsetExists() - Whether an offset exists


Assign a value to the specified offset

  • « ArrayAccess::offsetGet
  • ArrayAccess::offsetUnset »
  • PHP Manual
  • ArrayAccess
  • Assign a value to the specified offset

ArrayAccess::offsetSet

(PHP 5, PHP 7)

ArrayAccess::offsetSet — Assign a value to the specified offset

Description

abstract 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, which is only possible since PHP 5.3.4.


Unset an offset

  • « ArrayAccess::offsetSet
  • Serializable »
  • PHP Manual
  • ArrayAccess
  • Unset an offset

ArrayAccess::offsetUnset

(PHP 5, PHP 7)

ArrayAccess::offsetUnset — Unset an offset

Description

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


The Serializable interface

(PHP 5 >= 5.1.0, PHP 7)

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.

Interface synopsis

Serializable {
/* Methods */
abstract public serialize ( void ) : string
abstract public unserialize ( string $serialized ) : void
}

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"

Table of Contents

  • Serializable::serialize — String representation of object
  • Serializable::unserialize — Constructs the object


String representation of object

  • « Serializable
  • Serializable::unserialize »
  • PHP Manual
  • Serializable
  • String representation of object

Serializable::serialize

(PHP 5 >= 5.1.0, PHP 7)

Serializable::serialize — String representation of object

Description

abstract public Serializable::serialize ( void ) : 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()


Constructs the object

  • « Serializable::serialize
  • Closure »
  • PHP Manual
  • Serializable
  • Constructs the object

Serializable::unserialize

(PHP 5 >= 5.1.0, PHP 7)

Serializable::unserialize — Constructs the object

Description

abstract public Serializable::unserialize ( string $serialized ) : 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

serialized

The string representation of the object.

Return Values

The return value from this method is ignored.

See Also

  • __wakeup()


The Closure class

(PHP 5 >= 5.3.0, PHP 7)

Introduction

Class used to represent anonymous functions.

Anonymous functions, implemented in PHP 5.3, yield objects of this type. This fact used to be considered an implementation detail, but it can now be relied upon. Starting with PHP 5.4, this class has methods that allow further control of the anonymous function after it has been created.

Besides the methods listed here, this class also has an __invoke method. This is for consistency with other classes that implement calling magic, as this method is not used for calling the function.

Class synopsis

Closure {
/* Methods */
private __construct ( void )
public static bind ( Closure $closure , object $newthis [, mixed $newscope = "static" ] ) : Closure
public bindTo ( object $newthis [, mixed $newscope = "static" ] ) : Closure
public call ( object $newthis [, mixed $... ] ) : mixed
public static fromCallable ( callable $callable ) : Closure
}

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


Constructor that disallows instantiation

  • « Closure
  • Closure::bind »
  • PHP Manual
  • Closure
  • Constructor that disallows instantiation

Closure::__construct

(PHP 5 >= 5.3.0, PHP 7)

Closure::__construct — Constructor that disallows instantiation

Description

private Closure::__construct ( void )

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.

Return Values

This method has no return value; it simply emits an error (of type E_RECOVERABLE_ERROR).

See Also

  • Anonymous functions


Duplicates a closure with a specific bound object and class scope

  • « Closure::__construct
  • Closure::bindTo »
  • PHP Manual
  • Closure
  • Duplicates a closure with a specific bound object and class scope

Closure::bind

(PHP 5 >= 5.4.0, PHP 7)

Closure::bind — Duplicates a closure with a specific bound object and class scope

Description

public static Closure::bind ( Closure $closure , object $newthis [, mixed $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 associate the closure is to be associated, or 'static' to keep the current one. If an object is given, the type of the object will be used instead. This determines the visibility of protected and private methods of the bound object. It is not allowed to pass (an object of) an internal class as this parameter.

Return Values

Returns a new Closure object or FALSE on failure

Changelog

Version | Description
7.0.0 | newscope can not be (an object of) an internal class anymore, what was possible prior to this version.

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


Duplicates the closure with a new bound object and class scope

  • « Closure::bind
  • Closure::call »
  • PHP Manual
  • Closure
  • Duplicates the closure with a new bound object and class scope

Closure::bindTo

(PHP 5 >= 5.4.0, PHP 7)

Closure::bindTo — Duplicates the closure with a new bound object and class scope

Description

public Closure::bindTo ( object $newthis [, mixed $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 function can nevertheless be used to change their class scope.

This function will ensure that for a non-static closure, having a bound instance will imply being scoped and vice-versa. To this end, non-static closures that are given a scope but a NULL instance are made static and non-static non-scoped closures that are given a non-null instance are scoped to an unspecified class.

Note:

If you only want to duplicate the anonymous functions, you can use cloning instead.

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 associate the closure is to be associated, or 'static' to keep the current one. If an object is given, the type of the object will be used instead. This determines the visibility of protected and private methods of the bound object. It is not allowed to pass (an object of) an internal class as this parameter.

Return Values

Returns the newly created Closure object or FALSE on failure

Changelog

Version | Description
7.0.0 | newscope can not be (an object of) an internal class anymore, what was possible prior to this version.

Examples

Example #1 Closure::bindTo() example

<?php

class A {
    function __construct($val) {
        $this->val = $val;
    }
    function getClosure() {
        //returns closure bound to this object and scope
        return function() { return $this->val; };
    }
}

$ob1 = new A(1);
$ob2 = new A(2);

$cl = $ob1->getClosure();
echo $cl(), "\n";
$cl = $cl->bindTo($ob2);
echo $cl(), "\n";
?>

The above example will output something similar to:

1
2

See Also

  • Anonymous functions
  • Closure::bind() - Duplicates a closure with a specific bound object and class scope


Binds and calls the closure

  • « Closure::bindTo
  • Closure::fromCallable »
  • PHP Manual
  • Closure
  • Binds and calls the closure

Closure::call

(PHP 7)

Closure::call — Binds and calls the closure

Description

public Closure::call ( object $newthis [, mixed $... ] ) : 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.

...

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)


Converts a callable into a closure

  • « Closure::call
  • Generator »
  • PHP Manual
  • Closure
  • Converts a callable into a closure

Closure::fromCallable

(PHP 7 >= 7.1.0)

Closure::fromCallable — Converts a callable into a closure

Description

public static Closure::fromCallable ( callable $callable ) : Closure

Create and return a new anonymous function from given callable using the current scope. This method checks if the callable is callable in the current scope and throws a TypeError if it is not.

Parameters

callable

The callable to convert.

Return Values

Returns the newly created Closure or throws a TypeError if the callable is not callable in the current scope.


The Generator class

(PHP 5 >= 5.5.0, PHP 7)

Introduction

Generator objects are returned from generators.

Caution

Generator objects cannot be instantiated via new.

Class synopsis

Generator implements Iterator {
/* Methods */
public current ( void ) : mixed
public getReturn ( void ) : mixed
public key ( void ) : mixed
public next ( void ) : void
public rewind ( void ) : void
public send ( mixed $value ) : mixed
public throw ( Throwable $exception ) : mixed
public valid ( void ) : bool
public __wakeup ( void ) : void
}

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 — Rewind the iterator
  • 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


Get the yielded value

  • « Generator
  • Generator::getReturn »
  • PHP Manual
  • Generator
  • Get the yielded value

Generator::current

(PHP 5 >= 5.5.0, PHP 7)

Generator::current — Get the yielded value

Description

public Generator::current ( void ) : mixed

Parameters

This function has no parameters.

Return Values

Returns the yielded value.


Get the return value of a generator

  • « Generator::current
  • Generator::key »
  • PHP Manual
  • Generator
  • Get the return value of a generator

Generator::getReturn

(PHP 7)

Generator::getReturn — Get the return value of a generator

Description

public Generator::getReturn ( void ) : 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


Get the yielded key

  • « Generator::getReturn
  • Generator::next »
  • PHP Manual
  • Generator
  • Get the yielded key

Generator::key

(PHP 5 >= 5.5.0, PHP 7)

Generator::key — Get the yielded key

Description

public Generator::key ( void ) : 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


Resume execution of the generator

  • « Generator::key
  • Generator::rewind »
  • PHP Manual
  • Generator
  • Resume execution of the generator

Generator::next

(PHP 5 >= 5.5.0, PHP 7)

Generator::next — Resume execution of the generator

Description

public Generator::next ( void ) : void

Calling Generator::next() is equivalent to calling Generator::send() with NULL as argument.

Parameters

This function has no parameters.

Return Values

No value is returned.


Rewind the iterator

  • « Generator::next
  • Generator::send »
  • PHP Manual
  • Generator
  • Rewind the iterator

Generator::rewind

(PHP 5 >= 5.5.0, PHP 7)

Generator::rewind — Rewind the iterator

Description

public Generator::rewind ( void ) : void

If iteration has already begun, this will throw an exception.

Parameters

This function has no parameters.

Return Values

No value is returned.


Send a value to the generator

  • « Generator::rewind
  • Generator::throw »
  • PHP Manual
  • Generator
  • Send a value to the generator

Generator::send

(PHP 5 >= 5.5.0, PHP 7)

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!


Throw an exception into the generator

  • « Generator::send
  • Generator::valid »
  • PHP Manual
  • Generator
  • Throw an exception into the generator

Generator::throw

(PHP 5 >= 5.5.0, PHP 7)

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.

Changelog

Version | Description
7.0.0 | The exception parameter also accepts Throwable now.

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


Check if the iterator has been closed

  • « Generator::throw
  • Generator::__wakeup »
  • PHP Manual
  • Generator
  • Check if the iterator has been closed

Generator::valid

(PHP 5 >= 5.5.0, PHP 7)

Generator::valid — Check if the iterator has been closed

Description

public Generator::valid ( void ) : bool

Parameters

This function has no parameters.

Return Values

Returns FALSE if the iterator has been closed. Otherwise returns TRUE.


Serialize callback

  • « Generator::valid
  • WeakReference »
  • PHP Manual
  • Generator
  • Serialize callback

Generator::__wakeup

(PHP 5 >= 5.5.0, PHP 7)

Generator::__wakeup — Serialize callback

Description

public Generator::__wakeup ( void ) : void

Throws an exception as generators can't be serialized.

Parameters

This function has no parameters.

Return Values

No value is returned.


The WeakReference class

(PHP 7 >= 7.4.0)

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.

Note:

The class WeakReference is not to be confused with the class WeakRef of the Weakref extension.

WeakReferences cannot be serialized.

Class synopsis

WeakReference {
/* Methods */
public __construct ( void )
public static create ( object $referent ) : WeakReference
public get ( void ) : ?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

Table of Contents

  • WeakReference::__construct — Constructor that disallows instantiation
  • WeakReference::create — Create a new weak reference
  • WeakReference::get — Get a weakly referenced Object


Constructor that disallows instantiation

  • « WeakReference
  • WeakReference::create »
  • PHP Manual
  • WeakReference
  • Constructor that disallows instantiation

WeakReference::__construct

(PHP 7 >= 7.4.0)

WeakReference::__construct — Constructor that disallows instantiation

Description

public WeakReference::__construct ( void )

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


Create a new weak reference

  • « WeakReference::__construct
  • WeakReference::get »
  • PHP Manual
  • WeakReference
  • Create a new weak reference

WeakReference::create

(PHP 7 >= 7.4.0)

WeakReference::create — Create a new weak reference

Description

public static WeakReference::create ( object $referent ) : WeakReference

Creates a new WeakReference.

Parameters

referent

The object to be weakly referenced.

Return Values

Returns the freshly instantiated object.


Get a weakly referenced Object

  • « WeakReference::create
  • Context options and parameters »
  • PHP Manual
  • WeakReference
  • Get a weakly referenced Object

WeakReference::get

(PHP 7 >= 7.4.0)

WeakReference::get — Get a weakly referenced Object

Description

public WeakReference::get ( void ) : ?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.


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

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
  • CURL context options — CURL context option listing
  • Phar context options — Phar context option listing
  • MongoDB context options — MongoDB context option listing
  • Context parameters — Context parameter listing
  • Zip context options — Zip context option listing


Socket context option listing

  • « Context options and parameters
  • HTTP context options »
  • PHP Manual
  • Context options and parameters
  • Socket context option listing

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.
7.0.0 | Added so_broadcast.
7.0.0 | Added so_reuseport.
5.3.3 | Added backlog.
5.1.0 | Added bindto.

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 option listing

  • « Socket context options
  • FTP context options »
  • PHP Manual
  • Context options and parameters
  • HTTP context option listing

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

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 boolean

When set to TRUE, the entire URI will be used when constructing the request. (i.e. 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 integer

Follow Location header redirects. Set to 0 to disable.

Defaults to 1.

max_redirects integer

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

Note:

PHP prior to 5.3.0 does not implement chunked transfer decoding. If this value is set to 1.1 it is your responsibility to be 1.1 compliant.

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 boolean

Fetch the content even on failure status codes.

Defaults to FALSE.

Changelog

Version | Description
5.3.4 | Added follow_location.
5.3.0 | The protocol_version supports chunked transfer decoding when set to 1.1.
5.2.10 | Added ignore_errors.
5.2.10 | The header can now be an numerically indexed array.
5.2.1 | Added timeout.
5.1.0 | Added HTTPS proxying through HTTP proxies.
5.1.0 | Added max_redirects.
5.1.0 | Added protocol_version.

Examples

Example #1 Fetch a page and send POST data

<?php

$postdata = http_build_query(
    array(
        'var1' => 'some content',
        'var2' => 'doh'
    )
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context = stream_context_create($opts);

$result = file_get_contents('http://example.com/submit.php', false, $context);

?>

Example #2 Ignore redirects but fetch headers and content

<?php

$url = "http://www.example.org/header.php";

$opts = array('http' =>
    array(
        'method' => 'GET',
        'max_redirects' => '0',
        'ignore_errors' => '1'
    )
);

$context = stream_context_create($opts);
$stream = fopen($url, 'r', false, $context);

// header information as well as meta data
// about the stream
var_dump(stream_get_meta_data($stream));

// actual data at $url
var_dump(stream_get_contents($stream));
fclose($stream);
?>

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 Permantenly',
    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 option listing

  • « HTTP context options
  • SSL context options »
  • PHP Manual
  • Context options and parameters
  • FTP context option listing

FTP context options

FTP context options — FTP context option listing

Description

Context options for ftp:// and ftps:// transports.

Options

overwrite boolean

Allow overwriting of already existing files on remote server. Applies to write mode (uploading) only.

Defaults to FALSE.

resume_pos integer

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.

Changelog

Version | Description
5.1.0 | Added proxy.

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 option listing

  • « FTP context options
  • CURL context options »
  • PHP Manual
  • Context options and parameters
  • SSL context option listing

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 boolean

Require verification of SSL certificate used.

Defaults to TRUE.

verify_peer_name boolean

Require verification of peer name.

Defaults to TRUE.

allow_self_signed boolean

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.

CN_match string

Common Name we are expecting. PHP will perform limited wildcard matching. If the Common Name does not match this, the connection attempt will fail.

Note: This option is deprecated, in favour of peer_name, as of PHP 5.6.0.

verify_depth integer

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 boolean

If set to TRUE a peer_certificate context option will be created containing the peer certificate.

capture_peer_cert_chain boolean

If set to TRUE a peer_certificate_chain context option will be created containing the certificate chain.

SNI_enabled boolean

If set to TRUE server name indication will be enabled. Enabling SNI allows multiple certificates on the same IP address.

SNI_server_name string

If set, then this value will be used as server name for server name indication. If this value is not set, then the server name is guessed based on the hostname used when opening the stream.

Note: This option is deprecated, in favour of peer_name, as of PHP 5.6.0.

disable_compression boolean

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.

Changelog

Version | Description
5.6.0 | Added peer_fingerprint and verify_peer_name. verify_peer default changed to TRUE.
5.4.13 | Added disable_compression. Requires OpenSSL >= 1.0.0.
5.3.2 | Added SNI_enabled and SNI_server_name.

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


CURL context option listing

  • « SSL context options
  • Phar context options »
  • PHP Manual
  • Context options and parameters
  • CURL context option listing

CURL context options

CURL context options — CURL context option listing

Description

CURL context options are available when the CURL extension was compiled using the --with-curlwrappers configure option.

Options

method string

GET, POST, or any other HTTP method supported by the remote server.

Defaults to GET.

header string

Additional headers to be sent during request. Values in this option will override other values (such as User-agent:, Host:, and Authentication:).

user_agent string

Value to send with User-Agent: header.

By default the user_agent php.ini setting is used.

content string

Additional data to be sent after the headers. This option is not used for GET or HEAD requests.

proxy string

URI specifying address of proxy server. (e.g. tcp://proxy.example.com:5100).

max_redirects integer

The max number of redirects to follow. Value 1 or less means that no redirects are followed.

Defaults to 20.

curl_verify_ssl_host boolean

Verify the host.

Defaults to FALSE

Note:

This option is available for both the http and ftp protocol wrappers.

curl_verify_ssl_peer boolean

Require verification of SSL certificate used.

Defaults to FALSE

Note:

This option is available for both the http and ftp protocol wrappers.

Examples

Example #1 Fetch a page and send POST data

<?php

$postdata = http_build_query(
    array(
        'var1' => 'some content',
        'var2' => 'doh'
    )
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context = stream_context_create($opts);

$result = file_get_contents('http://example.com/submit.php', false, $context);

?>

See Also

  • Socket context options


Phar context option listing

  • « CURL context options
  • MongoDB context options »
  • PHP Manual
  • Context options and parameters
  • Phar context option listing

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


MongoDB context option listing

  • « Phar context options
  • Context parameters »
  • PHP Manual
  • Context options and parameters
  • MongoDB context option listing

MongoDB context options

MongoDB context options — MongoDB context option listing

Description

Context options for mongodb:// transports.

Options

log_cmd_insert callable

A callback function called when inserting a document, see log_cmd_insert().

log_cmd_delete callable

A callback function called when deleting a document, see log_cmd_delete().

log_cmd_update callable

A callback function called when updating a document, see log_cmd_update().

log_write_batch callable

A callback function called when executing a Write Batch, see log_write_batch().

log_reply callable

A callback function called when reading a reply from MongoDB, see log_reply().

log_getmore callable

A callback function called when retrieving more results from a MongoDB cursor, see log_getmore().

log_killcursor callable

A callback function called executing a killcursor opcode, see log_killcursor().

Changelog

Version | Description
pecl/mongo 1.5.0 | Added Write API Context options

See Also

  • Socket context options
  • SSL context options


Context parameter listing

  • « MongoDB context options
  • Zip context options »
  • PHP Manual
  • Context options and parameters
  • Context parameter listing

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 option listing

  • « Context parameters
  • Supported Protocols and Wrappers »
  • PHP Manual
  • Context options and parameters
  • Zip context option listing

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
PHP 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);

?>


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.

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


Accessing local filesystem

  • « Supported Protocols and Wrappers
  • http:// »
  • PHP Manual
  • Supported Protocols and Wrappers
  • Accessing local filesystem

file://

file:// — Accessing local filesystem

Description

Filesystem is the default wrapper used with PHP and represents the local filesystem. When a relative path is specified (a path which does not begin with /, \, \\, or a Windows drive letter) the path provided will be applied against the current working directory. In many cases this is the directory in which the script resides unless it has been changed. Using the CLI sapi, this defaults to the directory from which the script was called.

With some functions, such as fopen() and file_get_contents(), include_path may be optionally searched for relative paths as well.

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


Accessing HTTP(s) URLs

  • « file://
  • ftp:// »
  • PHP Manual
  • Supported Protocols and Wrappers
  • Accessing HTTP(s) URLs

http://

https://

http:// -- https:// — Accessing HTTP(s) URLs

Description

Allows read-only access to files/resources via HTTP 1.0, using the HTTP GET method. A Host: header is sent with the request to handle name-based virtual hosts. If you have configured a user_agent string using your php.ini file or the stream context, it will also be included in the request.

The stream allows access to the body of the resource; the headers are stored in the $http_response_header variable.

If it's important to know the URL of the resource where your document came from (after all redirects have been processed), you'll need to process the series of response headers returned by the stream.

The from directive will be used for the From: header if set and not overwritten by the Context options and parameters.

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


Accessing FTP(s) URLs

  • « http://
  • php:// »
  • PHP Manual
  • Supported Protocols and Wrappers
  • Accessing FTP(s) URLs

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(), filetype(), file_exists(), is_file(), and is_dir() elements only. As of PHP 5.1.0: filemtime().
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


Accessing various I/O streams

  • « ftp://
  • zlib:// »
  • PHP Manual
  • Supported Protocols and Wrappers
  • Accessing various I/O streams

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. Note that PHP exhibited buggy behavior in this regard until PHP 5.2.1. It is recommended that you simply use the constants STDIN, STDOUT and STDERR instead of manually opening streams using these wrappers.

php://stdin is read-only, whereas php://stdout and php://stderr are write-only.

php://input

php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data".

Note: Prior to PHP 5.6, a stream opened with php://input could only be read once; the stream did not support seek operations. However, depending on the SAPI implementation, it may be possible to open another php://input stream and restart reading. This is only possible if the request body data has been saved. Typically, this is the case for POST requests, but not other request methods, such as PUT or PROPFIND.

php://output

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. The only difference between the two is that php://memory will always store its data in memory, whereas php://temp will use a temporary file once the amount of data stored hits a predefined limit (the default is 2 MB). The location of this temporary file is determined in the same way as the sys_get_temp_dir() function.

The memory limit of php://temp can be controlled by appending /maxmemory:NN, where NN is the maximum amount of data to keep in memory before using a temporary file, in bytes.

php://filter

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() | php://memory and php://temp only.
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.

Changelog

Version | Description
5.6.0 | php://input was made reusable.
5.3.6 | php://fd was added.
5.1.0 | php://memory and php://temp were added.

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.

file_put_contents('php://memory', 'PHP');
echo file_get_contents('php://memory'); // prints nothing


Compression Streams

  • « php://
  • data:// »
  • PHP Manual
  • Supported Protocols and Wrappers
  • Compression Streams

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


Data (RFC 2397)

  • « zlib://
  • glob:// »
  • PHP Manual
  • Supported Protocols and Wrappers
  • Data (RFC 2397)

data://

data:// — Data (RFC 2397)

Description

The data: (» RFC 2397) stream wrapper is available since PHP 5.2.0.

Usage

  • data://text/plain;base64,

Options

Wrapper Summary
Attribute | Supported
Restricted by allow_url_fopen | No
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'];
?>


Find pathnames matching pattern

  • « data://
  • phar:// »
  • PHP Manual
  • Supported Protocols and Wrappers
  • Find pathnames matching pattern

glob://

glob:// — Find pathnames matching pattern

Description

The glob: stream wrapper is available since PHP 5.3.0.

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


PHP Archive

  • « glob://
  • ssh2:// »
  • PHP Manual
  • Supported Protocols and Wrappers
  • PHP Archive

phar://

phar:// — PHP Archive

Description

The phar:// stream wrapper is available since PHP 5.3.0. See Phar stream wrapper for 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


Secure Shell 2

  • « phar://
  • rar:// »
  • PHP Manual
  • Supported Protocols and Wrappers
  • Secure Shell 2

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 you must install the » SSH2 extension available from » PECL.

In addition to accepting traditional URI login details, the ssh2 wrappers will also reuse open connections by passing the connection resource in the host portion of the URL.

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 you must keep the $session resource variable. The code below will not have the desired effect:

<?php
$session = ssh2_connect('example.com', 22);
ssh2_auth_pubkey_file($session, 'username', '/home/username/.ssh/id_rsa.pub',
                                            '/home/username/.ssh/id_rsa', 'secret');
$connection_string = "ssh2.sftp://$session/";
unset($session);
$stream = fopen($connection_string . "path/to/file", 'r');
?>

unset() closes the session, because $connection_string does not hold a reference to the $session variable, just a string cast derived from it. This also happens when the unset() is implicit because of leaving scope (like in a function).


RAR

  • « ssh2://
  • ogg:// »
  • PHP Manual
  • Supported Protocols and Wrappers
  • RAR

rar://

rar:// — RAR

Description

The wrapper takes the url encoded path to the RAR archive (relative or absolute), an optional asterik (*), an optional number sign (#) and an optional url encoded entry name, as stored in the archive. Specifying an entry name requires the number sign; a leading forward slash in the entry name is optional.

This wrapper can open both files and directories. When opening directories, the asterisk sign forces the directory entries names to be returned unencoded. If it's not specified, they will be returned url encoded – the reason for this is to allow the wrapper to be correctly used with built-in functionality like the RecursiveDirectoryIterator in the presence of file names that seem like url encoded data.

If the pound sign and the entry name part are not included, the root of the archive will be displayed. This differs from regular directories in that the resulting stream will not contain information such as the modification time, as the root directory is not stored in an individual entry in the archive. The usage of the wrapper with RecursiveDirectoryIterator requires the number sign to be included in the URL when accessing the root, so that the URLs of the children may be constructed correctly.

Note: This wrapper is not enabled by default
In order to use the rar:// wrapper, you must install the » rar extension available from » PECL.

rar:// Available since PECL rar 3.0.0

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
)


Audio streams

  • « rar://
  • expect:// »
  • PHP Manual
  • Supported Protocols and Wrappers
  • Audio streams

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 you must install the » OGG/Vorbis extension available from » PECL.

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

Examples


Process Interaction Streams

  • « ogg://
  • Security »
  • PHP Manual
  • Supported Protocols and Wrappers
  • Process Interaction Streams

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 you must install the » Expect extension available from » PECL.

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

Examples


Security

  • 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
  • Using Register Globals
  • User Submitted Data
  • Magic Quotes
    • What are Magic Quotes
    • Why did we use Magic Quotes
    • Why not to use Magic Quotes
    • Disabling Magic Quotes
  • Hiding PHP
  • Keeping Current


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 specify the option --enable-force-cgi-redirect to the configure script. You still have to make sure your PHP scripts do not rely on one or another way of calling the script, neither by directly http://my.host/cgi-bin/php/dir/script.php nor by redirection http://my.host/dir/script.php.

Redirection can be configured in Apache by using AddHandler and Action directives (see below).


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 PHP parser should be compiled with the --enable-discard-path configure option.


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 keeping HTTP session management secure. Session releated security is described in 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 Mcrypt and Mhash, covering a wide variety of encryption algorithms. The script encrypts the data before inserting it into the database, and decrypts it when retrieving. See the references for further examples of how encryption works.

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.

In PHP 5.5 or newer password functions provide a convenient way to hash sensitive data and work with these hashes. In PHP 5.3.7+ » password_compat library can also be used.

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) . '.';
}

?>

In older versions of PHP this can be achieved using crypt() function.

Example #2 Hashing password using crypt()s

<?php

// storing password hash
// $random_chars retrieved e.g. using /dev/random
$query  = sprintf("INSERT INTO users(name,pwd) VALUES('%s','%s');",
            pg_escape_string($username),
            pg_escape_string(crypt($password, '$2a$07$' . $random_chars . '$')));
$result = pg_query($connection, $query);

// querying if user submitted the right password
$query = sprintf("SELECT pwd FROM users WHERE name='%s';",
            pg_escape_string($username));
$row = pg_fetch_assoc(pg_query($connection, $query));

if ($row && crypt($password, $row['pwd']) == $row['pwd']) {
    echo 'Welcome, ' . htmlspecialchars($username) . '!';
} else {
    echo 'Authentication failed for ' . htmlspecialchars($username) . '.';
}

?>


SQL Injection

Many web developers are unaware of how SQL queries can be tampered with, and assume that an SQL query is a trusted command. It means that SQL queries are able to circumvent access controls, thereby bypassing standard authentication and authorization checks, and sometimes SQL queries even may allow access to host operating system level commands.

Direct SQL Command Injection is a technique where an attacker creates or alters existing SQL commands to expose hidden data, or to override valuable ones, or even to execute dangerous system level commands on the database host. This is accomplished by the application taking user input and combining it with static parameters to build an SQL query. The following examples are based on true stories, unfortunately.

Owing to the lack of input validation and connecting to the database on behalf of a superuser or the one who can create users, the attacker may create a superuser in your database.

Example #1 Splitting the result set into pages ... and making superusers (PostgreSQL)

<?php

$offset = $argv[0]; // beware, no input validation!
$query  = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
$result = pg_query($conn, $query);

?>
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 decimal number. However, what if someone tries to break in by appending a urlencode()'d form of the following to the URL
0;
insert into pg_shadow(usename,usesysid,usesuper,usecatupd,passwd)
    select 'crack', usesysid, 't','t','crack'
    from pg_shadow where usename='postgres';
--
If it happened, then the script would present a superuser access to him. Note that 0; is to supply a valid offset to the original query and to terminate it.

Note:

It is common technique to force the SQL parser to ignore the rest of the query written by the developer with -- which is the comment sign in SQL.

A feasible way to gain passwords is to circumvent your search result pages. The only thing the attacker needs to do is to see if there are any submitted variables used in SQL statements which are not handled properly. These filters can be set commonly in a preceding form to customize WHERE, ORDER BY, LIMIT and OFFSET clauses in SELECT statements. If your database supports the UNION construct, the attacker may try to append an entire query to the original one to list passwords from an arbitrary table. Using encrypted password fields is strongly encouraged.

Example #2 Listing out articles ... and some passwords (any database server)

<?php

$query  = "SELECT id, name, inserted, size FROM products
           WHERE size = '$size'";
$result = odbc_exec($conn, $query);

?>
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;
--
If this query (playing with the ' and --) were assigned to one of the variables used in $query, the query beast awakened.

SQL UPDATE's are also susceptible to attack. These queries are also threatened by chopping and appending an entirely new query to it. But the attacker might fiddle with the SET clause. In this case some schema information must be possessed to manipulate the query successfully. This can be acquired by examining the form variable names, or just simply brute forcing. There are not so many naming conventions for fields storing passwords or usernames.

Example #3 From resetting a password ... to gaining more privileges (any database server)

<?php
$query = "UPDATE usertable SET pwd='$pwd' WHERE uid='$uid';";
?>
But 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
...;";

?>

A frightening example of how operating system level commands can be accessed on some database hosts.

Example #4 Attacking the database hosts operating system (MSSQL Server)

<?php

$query  = "SELECT * FROM products WHERE id LIKE '%$prod%'";
$result = mssql_query($query);

?>
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 is running with sufficient privileges, the attacker would now have an account with which to access this machine.

Note:

Some of the examples above is tied to a specific database server. This does not mean that a similar attack is impossible against other products. Your database server may be similarly vulnerable in another manner.

A worked example of the issues regarding SQL Injection
Image courtesy of » xkcd

Avoidance Techniques

While it remains obvious that an attacker must possess at least some knowledge of the database architecture in order to conduct a successful attack, obtaining this information is often very simple. For example, if the database is part of an open source or other publicly-available software package with a default installation, this information is completely open and available. This information may also be divulged by closed-source code - even if it's encoded, obfuscated, or compiled - and even by your very own code through the display of error messages. Other methods include the user of common table and column names. For example, a login form that uses a 'users' table with column names 'id', 'username', and 'password'.

These attacks are mainly based on exploiting the code not being written with security in mind. Never trust any kind of input, especially that which comes from the client side, even though it comes from a select box, a hidden input field or a cookie. The first example shows that such a blameless query can cause disasters.

  • Never connect to the database as a superuser or as the database owner. Use always customized users with very limited privileges.
  • Use prepared statements with bound variables. They are provided by PDO, by MySQLi and by other libraries.
  • Check if the given input has the expected data type. PHP has a wide range of input validating functions, from the simplest ones found in Variable Functions and in Character Type Functions (e.g. is_numeric(), ctype_digit() respectively) and onwards to the Perl compatible Regular Expressions support.

  • If the application waits for numerical input, consider verifying data with ctype_digit(), or silently change its type using settype(), or use its numeric representation by sprintf().

    Example #5 A more secure way to compose a query for paging

    <?php

    settype    ($offset, 'integer');
    $query = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";

    // please note %d in the format string, using %s would be meaningless
    $query = sprintf("SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET %d;",
                         $offset);

    ?>

  • 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.
  • You may use stored procedures and previously defined cursors to abstract data access so that users do not directly access tables or views, but this solution has another impacts.

Besides these, you benefit from logging queries either within your script or by the database itself, if it supports logging. Obviously, the logging is unable to prevent any harmful attempt, but it can be helpful to trace back which application has been circumvented. The log is not useful by itself, but through the information it contains. More detail is generally better than less.


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


Using Register Globals

Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

Perhaps the most controversial change in PHP is when the default value for the PHP directive register_globals went from ON to OFF in PHP » 4.2.0. Reliance on this directive was quite common and many people didn't even know it existed and assumed it's just how PHP works. This page will explain how one can write insecure code with this directive but keep in mind that the directive itself isn't insecure but rather it's the misuse of it.

When on, register_globals will inject your scripts with all sorts of variables, like request variables from HTML forms. This coupled with the fact that PHP doesn't require variable initialization means writing insecure code is that much easier. It was a difficult decision, but the PHP community decided to disable this directive by default. When on, people use variables yet really don't know for sure where they come from and can only assume. Internal variables that are defined in the script itself get mixed up with request data sent by users and disabling register_globals changes this. Let's demonstrate with an example misuse of register_globals:

Example #1 Example misuse with register_globals = on

<?php
// define $authorized = true only if user is authenticated
if (authenticated_user()) {
    $authorized = true;
}

// Because we didn't first initialize $authorized as false, this might be
// defined through register_globals, like from GET auth.php?authorized=1
// So, anyone can be seen as authenticated!
if ($authorized) {
    include "/highly/sensitive/data.php";
}
?>

When register_globals = on, our logic above may be compromised. When off, $authorized can't be set via request so it'll be fine, although it really is generally a good programming practice to initialize variables first. For example, in our example above we might have first done $authorized = false. Doing this first means our above code would work with register_globals on or off as users by default would be unauthorized.

Another example is that of sessions. When register_globals = on, we could also use $username in our example below but again you must realize that $username could also come from other means, such as GET (through the URL).

Example #2 Example use of sessions with register_globals on or off

<?php
// We wouldn't know where $username came from but do know $_SESSION is
// for session data
if (isset($_SESSION['username'])) {

    echo "Hello <b>{$_SESSION['username']}</b>";

} else {

    echo "Hello <b>Guest</b><br />";
    echo "Would you like to login?";

}
?>

It's even possible to take preventative measures to warn when forging is being attempted. If you know ahead of time exactly where a variable should be coming from, you can check to see if the submitted data is coming from an inappropriate kind of submission. While it doesn't guarantee that data has not been forged, it does require an attacker to guess the right kind of forging. If you don't care where the request data comes from, you can use $_REQUEST as it contains a mix of GET, POST and COOKIE data. See also the manual section on using variables from external sources.

Example #3 Detecting simple variable poisoning

<?php
if (isset($_COOKIE['MAGIC_COOKIE'])) {

    // MAGIC_COOKIE comes from a cookie.
    // Be sure to validate the cookie data!

} elseif (isset($_GET['MAGIC_COOKIE']) || isset($_POST['MAGIC_COOKIE'])) {

   mail("admin@example.com", "Possible breakin attempt", $_SERVER['REMOTE_ADDR']);
   echo "Security violation, admin has been alerted.";
   exit;

} else {

   // MAGIC_COOKIE isn't set through this REQUEST

}
?>

Of course, simply turning off register_globals does not mean your code is secure. For every piece of data that is submitted, it should also be checked in other ways. Always validate your user data and initialize your variables! To check for uninitialized variables you may turn up error_reporting() to show E_NOTICE level errors.

For information about emulating register_globals being On or Off, see this FAQ.


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.

You may also want to consider turning off register_globals, magic_quotes, or other convenience settings which may confuse you as to the validity, source, or value of a given variable. Working with PHP in error_reporting(E_ALL) mode can also help warn you about variables being used before they are checked or initialized (so you can prevent unusual data from being operated upon).


Magic Quotes

Table of Contents

  • What are Magic Quotes
  • Why did we use Magic Quotes
  • Why not to use Magic Quotes
  • Disabling Magic Quotes
Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

Magic Quotes is a process that automagically escapes incoming data to the PHP script. It's preferred to code with magic quotes off and to instead escape the data at runtime, as needed.


What are Magic Quotes

Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

When on, all ' (single-quote), " (double quote), \ (backslash) and NULL characters are escaped with a backslash automatically. This is identical to what addslashes() does.

There are three magic quote directives:

  • magic_quotes_gpc Affects HTTP Request data (GET, POST, and COOKIE). Cannot be set at runtime, and defaults to on in PHP. See also get_magic_quotes_gpc().
  • magic_quotes_runtime If enabled, most functions that return data from an external source, including databases and text files, will have quotes escaped with a backslash. Can be set at runtime, and defaults to off in PHP. See also set_magic_quotes_runtime() and get_magic_quotes_runtime().
  • magic_quotes_sybase If enabled, a single-quote is escaped with a single-quote instead of a backslash. If on, it completely overrides magic_quotes_gpc. Having both directives enabled means only single quotes are escaped as ''. Double quotes, backslashes and NULL's will remain untouched and unescaped. See also ini_get() for retrieving its value.


Why did we use Magic Quotes

Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

  • There is no reason to use magic quotes because they are no longer a supported part of PHP. However, they did exist and did help a few beginners blissfully and unknowingly write better (more secure) code. But, when dealing with code that relies upon this behavior it's better to update the code instead of turning magic quotes on. So why did this feature exist? Simple, to help prevent SQL Injection. Today developers are better aware of security and end up using database specific escaping mechanisms and/or prepared statements instead of relying upon features like magical quotes.


Why not to use Magic Quotes

Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

  • Portability Assuming it to be on, or off, affects portability. Use get_magic_quotes_gpc() to check for this, and code accordingly.
  • Performance Because not every piece of escaped data is inserted into a database, there is a performance loss for escaping all this data. Simply calling on the escaping functions (like addslashes()) at runtime is more efficient. Although php.ini-development enables these directives by default, php.ini-production disables it. This recommendation is mainly due to performance reasons.
  • Inconvenience Because not all data needs escaping, it's often annoying to see escaped data where it shouldn't be. For example, emailing from a form, and seeing a bunch of \' within the email. To fix, this may require excessive use of stripslashes().


Disabling Magic Quotes

The magic_quotes_gpc directive may only be disabled at the system level, and not at runtime. In otherwords, use of ini_set() is not an option.

Example #1 Disabling magic quotes server side

An example that sets the value of these directives to Off in php.ini. For additional details, read the manual section titled How to change configuration settings.

; Magic quotes
;

; Magic quotes for incoming GET/POST/Cookie data.
magic_quotes_gpc = Off

; Magic quotes for runtime-generated data, e.g. data from SQL, from exec(), etc.
magic_quotes_runtime = Off

; Use Sybase-style magic quotes (escape ' with '' instead of \').
magic_quotes_sybase = Off

If access to the server configuration is unavailable, use of .htaccess is also an option. For example:

php_flag magic_quotes_gpc Off

In the interest of writing portable code (code that works in any environment), like if setting at the server level is not possible, here's an example to disable magic_quotes_gpc at runtime. This method is inefficient so it's preferred to instead set the appropriate directives elsewhere.

Example #2 Disabling magic quotes at runtime

<?php
if (get_magic_quotes_gpc()) {
    $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
    while (list($key, $val) = each($process)) {
        foreach ($val as $k => $v) {
            unset($process[$key][$k]);
            if (is_array($v)) {
                $process[$key][stripslashes($k)] = $v;
                $process[] = &$process[$key][stripslashes($k)];
            } else {
                $process[$key][stripslashes($k)] = stripslashes($v);
            }
        }
    }
    unset($process);
}
?>


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.


Features

  • HTTP authentication with PHP
  • Cookies
  • Sessions
  • Dealing with XForms
  • 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
  • Safe Mode
    • Security and Safe Mode
    • Functions restricted/disabled by safe mode
  • Command line usage — Using PHP from the command line
    • Introduction
    • 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


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. Both "Basic" and "Digest" (since PHP 5.1.0) authentication methods are 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('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Text to send if user hits Cancel button';
    exit;
} else {
    echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
    echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
}
?>

Example #2 Digest HTTP Authentication example

This example shows you how to implement a simple Digest HTTP authentication script. For more information read the » RFC 2617.

<?php
$realm = 'Restricted area';

//user => password
$users = array('admin' => 'mypass', 'guest' => 'guest');

if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
    header('HTTP/1.1 401 Unauthorized');
    header('WWW-Authenticate: Digest realm="'.$realm.
           '",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');

    die('Text to send if user hits Cancel button');
}

// analyze the PHP_AUTH_DIGEST variable
if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) ||
    !isset($users[$data['username']]))
    die('Wrong Credentials!');

// generate the valid response
$A1 = md5($data['username'] . ':' . $realm . ':' . $users[$data['username']]);
$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
$valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);

if ($data['response'] != $valid_response)
    die('Wrong Credentials!');

// ok, valid username & password
echo 'You are logged in as: ' . $data['username'];

// function to parse the http auth header
function http_digest_parse($txt)
{
    // protect against missing data
    $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
    $data = array();
    $keys = implode('|', array_keys($needed_parts));

    preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER);

    foreach ($matches as $m) {
        $data[$m[1]] = $m[3] ? $m[3] : $m[4];
        unset($needed_parts[$m[1]]);
    }

    return $needed_parts ? false : $data;
}
?>

Note: Compatibility Note

Please be careful when coding the HTTP header lines. In order to guarantee maximum compatibility with all clients, the keyword "Basic" should be written with an uppercase "B", the realm string must be enclosed in double (not single) quotes, and exactly one space should precede the 401 code in the HTTP/1.0 401 header line. Authentication parameters have to be comma-separated as seen in the digest example above.

Instead of simply printing out PHP_AUTH_USER and PHP_AUTH_PW, as done in the above example, you may want to check the username and password for validity. Perhaps by sending a query to a database, or by looking up the user in a dbm file.

Watch out for buggy Internet Explorer browsers out there. They seem very picky about the order of the headers. Sending the WWW-Authenticate header before the HTTP/1.0 401 header seems to do the trick for now.

In order to prevent someone from writing a script which reveals the password for a page that was authenticated through a traditional external mechanism, the PHP_AUTH variables will not be set if external authentication is enabled for that particular page and safe mode is enabled. Regardless, REMOTE_USER can be used to identify the externally-authenticated user. So, you can use $_SERVER['REMOTE_USER'].

Note: Configuration Note

PHP uses the presence of an AuthType directive to determine whether external authentication is in effect.

Note, however, that the above does not prevent someone who controls a non-authenticated URL from stealing passwords from authenticated URLs on the same server.

Both Netscape Navigator and Internet Explorer will clear the local browser window's authentication cache for the realm upon receiving a server response of 401. This can effectively "log out" a user, forcing them to re-enter their username and password. Some people use this to "time out" logins, or provide a "log-out" button.

Example #3 HTTP Authentication example forcing a new name/password

<?php
function authenticate() {
    header('WWW-Authenticate: Basic realm="Test Authentication System"');
    header('HTTP/1.0 401 Unauthorized');
    echo "You must enter a valid login ID and password to access this resource\n";
    exit;
}

if (!isset($_SERVER['PHP_AUTH_USER']) ||
    ($_POST['SeenBefore'] == 1 && $_POST['OldAuth'] == $_SERVER['PHP_AUTH_USER'])) {
    authenticate();
} else {
    echo "<p>Welcome: " . htmlspecialchars($_SERVER['PHP_AUTH_USER']) . "<br />";
    echo "Old: " . htmlspecialchars($_REQUEST['OldAuth']);
    echo "<form action='' method='post'>\n";
    echo "<input type='hidden' name='SeenBefore' value='1' />\n";
    echo "<input type='hidden' name='OldAuth' value=\"" . htmlspecialchars($_SERVER['PHP_AUTH_USER']) . "\" />\n";
    echo "<input type='submit' value='Re Authenticate' />\n";
    echo "</form></p>\n";
}
?>

This behavior is not required by the HTTP Basic authentication standard, so you should never depend on this. Testing with Lynx has shown that Lynx does not clear the authentication credentials with a 401 server response, so pressing back and then forward again will open the resource as long as the credential requirements haven't changed. The user can press the '_' key to clear their authentication information, however.

In order to get HTTP Authentication to work using IIS server with the CGI version of PHP you must edit your IIS configuration "Directory Security". Click on "Edit" and only check "Anonymous Access", all other fields should be left unchecked.

Note: IIS Note:
For HTTP Authentication to work with IIS, the PHP directive cgi.rfc2616_headers must be set to 0 (the default value).

Note:

If safe mode is enabled, the uid of the script is added to the realm part of the WWW-Authenticate header.


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.

On older PHP systems (5.3 or earlier), register_globals may be enabled, which may cause undesirable and insecure operation. If this is enabled, cookies will be registered as global variables.

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.


Dealing with XForms

» XForms defines a variation on traditional webforms which allows them to be used on a wider variety of platforms and browsers or even non-traditional media such as PDF documents.

The first key difference in XForms is how the form is sent to the client. » XForms for HTML Authors contains a detailed description of how to create XForms, for the purpose of this tutorial we'll only be looking at a simple example.

Example #1 A simple XForms search form

<h:html xmlns:h="http://www.w3.org/1999/xhtml"
        xmlns="http://www.w3.org/2002/xforms">
<h:head>
 <h:title>Search</h:title>
 <model>
  <submission action="http://example.com/search"
              method="post" id="s"/>
 </model>
</h:head>
<h:body>
 <h:p>
  <input ref="q"><label>Find</label></input>
  <submit submission="s"><label>Go</label></submit>
 </h:p>
</h:body>
</h:html>

The above form displays a text input box (named q), and a submit button. When the submit button is clicked, the form will be sent to the page referred to by action.

Here's where it starts to look different from your web application's point of view. In a normal HTML form, the data would be sent as application/x-www-form-urlencoded, in the XForms world however, this information is sent as XML formatted data.

If you're choosing to work with XForms then you probably want that data as XML, in that case, look in $HTTP_RAW_POST_DATA where you'll find the XML document generated by the browser which you can pass into your favorite XSLT engine or document parser.

If you're not interested in formatting and just want your data to be loaded into the traditional $_POST variable, you can instruct the client browser to send it as application/x-www-form-urlencoded by changing the method attribute to urlencoded-post.

Example #2 Using an XForm to populate $_POST

<h:html xmlns:h="http://www.w3.org/1999/xhtml"
        xmlns="http://www.w3.org/2002/xforms">
<h:head>
 <h:title>Search</h:title>
 <model>
  <submission action="http://example.com/search"
              method="urlencoded-post" id="s"/>
 </model>
</h:head>
<h:body>
 <h:p>
  <input ref="q"><label>Find</label></input>
  <submit submission="s"><label>Go</label></submit>
 </h:p>
</h:body>
</h:html>

Note: As of this writing, many browsers do not support XForms. Check your browser version if the above examples fails.


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

UPLOAD_ERR_OK

Value: 0; There is no error, the file uploaded with success.

UPLOAD_ERR_INI_SIZE

Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.

UPLOAD_ERR_FORM_SIZE

Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.

UPLOAD_ERR_PARTIAL

Value: 3; The uploaded file was only partially uploaded.

UPLOAD_ERR_NO_FILE

Value: 4; No file was uploaded.

UPLOAD_ERR_NO_TMP_DIR

Value: 6; Missing a temporary folder. Introduced in PHP 5.0.3.

UPLOAD_ERR_CANT_WRITE

Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.

UPLOAD_ERR_EXTENSION

Value: 8; A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help. Introduced in PHP 5.2.0.


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.

As of PHP 5.2.12, the max_file_uploads configuration setting controls the maximum number of files that can uploaded in one request. If more files are uploaded than the limit, then $_FILES will stop processing files once the limit is reached. For example, if max_file_uploads is set to 10, then $_FILES will never contain more than 10 items.

Not validating which file you operate on may mean that users can access sensitive information in other directories.

Please note that the CERN httpd seems to strip off everything starting at the first whitespace in the content-type mime header it gets from the client. As long as this is the case, CERN httpd will not support the file upload feature.

Due to the large amount of directory listing styles we cannot guarantee that files with exotic names (like containing spaces) are handled properly.

A developer may not mix normal input fields and file upload fields in the same form variable (by using an input name like foo[]).


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. When register_globals is on, globals for uploaded files are also initialized. Each of these will be a numerically indexed array of the appropriate values for the submitted files.

For instance, assume that the filenames /home/test/review.html and /home/test/xwp.out are submitted. In this case, $_FILES['userfile']['name'][0] would contain the value review.html, and $_FILES['userfile']['name'][1] would contain the value xwp.out. Similarly, $_FILES['userfile']['size'][0] would contain review.html's file size, and so forth.

$_FILES['userfile']['name'][0], $_FILES['userfile']['tmp_name'][0], $_FILES['userfile']['size'][0], and $_FILES['userfile']['type'][0] are also set.

Warning

As of PHP 5.2.12, the max_file_uploads configuration setting acts as a limit on the number of files that can be uploaded in one request. You will need to ensure that your form does not try to upload more files in one request than this limit.


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


  • « PUT method support
  • Using remote files »
  • PHP Manual
  • Handling file uploads
  • See Also

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 (since PHP 5.2.0, allow_url_include must be enabled for these). See Supported Protocols and Wrappers for more information about the protocols supported by PHP.

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

Persistent connections are links that do not close when the execution of your script ends. When a persistent connection is requested, PHP checks if there's already an identical persistent connection (that remained open from earlier) - and if it exists, it uses it. If it does not exist, it creates the link. An 'identical' connection is a connection that was opened to the same host, with the same username and the same password (where applicable).

People who aren't thoroughly familiar with the way web servers work and distribute the load may mistake persistent connects for what they're not. In particular, they do not give you an ability to open 'user sessions' on the same link, they do not give you an ability to build up a transaction efficiently, and they don't do a whole lot of other things. In fact, to be extremely clear about the subject, persistent connections don't give you any functionality that wasn't possible with their non-persistent brothers.

Why?

This has to do with the way web servers work. There are three ways in which your web server can utilize PHP to generate web pages.

The first method is to use PHP as a CGI "wrapper". When run this way, an instance of the PHP interpreter is created and destroyed for every page request (for a PHP page) to your web server. Because it is destroyed after every request, any resources that it acquires (such as a link to an SQL database server) are closed when it is destroyed. In this case, you do not gain anything from trying to use persistent connections -- they simply don't persist.

The second, and most popular, method is to run PHP as a module in a multiprocess web server, which currently only includes Apache. A multiprocess server typically has one process (the parent) which coordinates a set of processes (its children) who actually do the work of serving up web pages. When a request comes in from a client, it is handed off to one of the children that is not already serving another client. This means that when the same client makes a second request to the server, it may be served by a different child process than the first time. When opening a persistent connection, every following page requesting SQL services can reuse the same established connection to the SQL server.

The last method is to use PHP as a plug-in for a multithreaded web server. Currently PHP 4 has support for ISAPI, WSAPI, and NSAPI (on Windows), which all allow PHP to be used as a plug-in on multithreaded servers like Netscape FastTrack (iPlanet), Microsoft's Internet Information Server (IIS), and O'Reilly's WebSite Pro. The behavior is essentially the same as for the multiprocess model described before.

If persistent connections don't have any added functionality, what are they good for?

The answer here is extremely simple -- efficiency. Persistent connections are good if the overhead to create a link to your SQL server is high. Whether or not this overhead is really high depends on many factors. Like, what kind of database it is, whether or not it sits on the same computer on which your web server sits, how loaded the machine the SQL server sits on is and so forth. The bottom line is that if that connection overhead is high, persistent connections help you considerably. They cause the child process to simply connect only once for its entire lifespan, instead of every time it processes a page that requires connecting to the SQL server. This means that for every child that opened a persistent connection will have its own open persistent connection to the server. For example, if you had 20 different child processes that ran a script that made a persistent connection to your SQL server, you'd have 20 different connections to the SQL server, one from each child.

Note, however, that this can have some drawbacks if you are using a database with connection limits that are exceeded by persistent child connections. If your database has a limit of 16 simultaneous connections, and in the course of a busy server session, 17 child threads attempt to connect, one will not be able to. If there are bugs in your scripts which do not allow the connections to shut down (such as infinite loops), the database with only 16 connections may be rapidly swamped. Check your database documentation for information on handling abandoned or idle connections.

Warning

There are a couple of additional caveats to keep in mind when using persistent connections. One is that when using table locking on a persistent connection, if the script for whatever reason cannot release the lock, then subsequent scripts using the same connection will block indefinitely and may require that you either restart the httpd server or the database server. Another is that when using transactions, a transaction block will also carry over to the next script which uses that connection if script execution ends before the transaction block does. In either case, you can use register_shutdown_function() to register a simple cleanup function to unlock your tables or roll back your transactions. Better yet, avoid the problem entirely by not using persistent connections in scripts which use table locks or transactions (you can still use them elsewhere).

An important summary. Persistent connections were designed to have one-to-one mapping to regular connections. That means that you should always be able to replace persistent connections with non-persistent connections, and it won't change the way your script behaves. It may (and probably will) change the efficiency of the script, but not its behavior!

See also fbsql_pconnect(),
ibase_pconnect(), ifx_pconnect(),
ingres_pconnect(),
msql_pconnect(), mssql_pconnect(),
mysql_pconnect(), ociplogon(),
odbc_pconnect(), oci_pconnect(),
pfsockopen(), pg_pconnect(), and
sybase_pconnect().


Safe Mode

Table of Contents

  • Security and Safe Mode
  • Functions restricted/disabled by safe mode

The PHP safe mode is an attempt to solve the shared-server security problem. It is architecturally incorrect to try to solve this problem at the PHP level, but since the alternatives at the web server and OS levels aren't very realistic, many people, especially ISP's, use safe mode for now.

Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

Changelog for safe mode
Version | Description
5.4.0 | Removed from PHP, and generates a fatal E_CORE_ERROR level error when enabled.
5.3.0 | Deprecated, and E_DEPRECATED errors were added.


Security and Safe Mode

Security and Safe Mode Configuration Directives
Name | Default | Changeable | Changelog
safe_mode | "0" | PHP_INI_SYSTEM | Removed in PHP 5.4.0.
safe_mode_gid | "0" | PHP_INI_SYSTEM | Removed in PHP 5.4.0.
safe_mode_include_dir | NULL | PHP_INI_SYSTEM | Removed in PHP 5.4.0.
safe_mode_exec_dir | "" | PHP_INI_SYSTEM | Removed in PHP 5.4.0.
safe_mode_allowed_env_vars | "PHP_" | PHP_INI_SYSTEM | Removed in PHP 5.4.0.
safe_mode_protected_env_vars | "LD_LIBRARY_PATH" | PHP_INI_SYSTEM | Removed in PHP 5.4.0.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

safe_mode boolean

Whether to enable PHP's safe mode. If PHP is compiled with --enable-safe-mode then defaults to On, otherwise Off.

Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

safe_mode_gid boolean

By default, Safe Mode does a UID compare check when opening files. If you want to relax this to a GID compare, then turn on safe_mode_gid. Whether to use UID (FALSE) or GID (TRUE) checking upon file access.

safe_mode_include_dir string

UID/GID checks are bypassed when including files from this directory and its subdirectories (directory must also be in include_path or full path must including).

This directive can take a colon (semi-colon on Windows) separated path in a fashion similar to the include_path directive, rather than just a single directory. The restriction specified is actually a prefix, not a directory name. This means that "safe_mode_include_dir = /dir/incl" also allows access to "/dir/include" and "/dir/incls" if they exist. When you want to restrict access to only the specified directory, end with a slash. For example: "safe_mode_include_dir = /dir/incl/" If the value of this directive is empty, no files with different UID/GID can be included.
safe_mode_exec_dir string

If PHP is used in safe mode, system() and the other functions executing system programs refuse to start programs that are not in this directory. You have to use / as directory separator on all environments including Windows.

safe_mode_allowed_env_vars string

Setting certain environment variables may be a potential security breach. This directive contains a comma-delimited list of prefixes. In Safe Mode, the user may only alter environment variables whose names begin with the prefixes supplied here. By default, users will only be able to set environment variables that begin with PHP_ (e.g. PHP_FOO=BAR).

Note:

If this directive is empty, PHP will let the user modify ANY environment variable!

safe_mode_protected_env_vars string

This directive contains a comma-delimited list of environment variables that the end user won't be able to change using putenv(). These variables will be protected even if safe_mode_allowed_env_vars is set to allow to change them.

See also: open_basedir, disable_functions, disable_classes, register_globals, display_errors, and log_errors.

When safe_mode is on, PHP checks to see if the owner of the current script matches the owner of the file to be operated on by a file function or its directory. For example:

-rw-rw-r--    1 rasmus   rasmus       33 Jul  1 19:20 script.php
-rw-r--r--    1 root     root       1116 May 26 18:01 /etc/passwd
Running script.php:
<?php
 readfile('/etc/passwd');
?>
results in this error when safe mode is enabled:
Warning: SAFE MODE Restriction in effect. The script whose uid is 500 is not
allowed to access /etc/passwd owned by uid 0 in /docroot/script.php on line 2

However, there may be environments where a strict UID check is not appropriate and a relaxed GID check is sufficient. This is supported by means of the safe_mode_gid switch. Setting it to On performs the relaxed GID checking, setting it to Off (the default) performs UID checking.

If instead of safe_mode, you set an open_basedir directory then all file operations will be limited to files under the specified directory. For example (Apache httpd.conf example):

<Directory /docroot>
  php_admin_value open_basedir /docroot
</Directory>
If you run the same script.php with this open_basedir setting then this is the result:
Warning: open_basedir restriction in effect. File is in wrong directory in
/docroot/script.php on line 2

You can also disable individual functions. Note that the disable_functions directive can not be used outside of the php.ini file which means that you cannot disable functions on a per-virtualhost or per-directory basis in your httpd.conf file. If we add this to our php.ini file:

disable_functions = readfile,system
Then we get this output:
Warning: readfile() has been disabled for security reasons in
/docroot/script.php on line 2

Warning

These PHP restrictions are not valid in executed binaries, of course.


Functions restricted/disabled by safe mode

This is a still probably incomplete and possibly incorrect listing of the functions limited by safe mode.

Safe mode limited functions
Function | Limitations
dbmopen() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.
dbase_open() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.
filepro() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.
filepro_rowcount() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.
filepro_retrieve() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.
ifx_* | sql_safe_mode restrictions, (!= safe mode)
ingres_* | sql_safe_mode restrictions, (!= safe mode)
mysql_* | sql_safe_mode restrictions, (!= safe mode)
pg_lo_import() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.
posix_mkfifo() | Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.
putenv() | Obeys the safe_mode_protected_env_vars and safe_mode_allowed_env_vars ini-directives. See also the documentation on putenv()
move_uploaded_file() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.
chdir() | Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.
dl() | This function is disabled when PHP is running in safe mode.
backtick operator | This function is disabled when PHP is running in safe mode.
shell_exec() (functional equivalent of backticks) | This function is disabled when PHP is running in safe mode.
exec() | You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. escapeshellcmd() is executed on the argument of this function.
system() | You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. escapeshellcmd() is executed on the argument of this function.
passthru() | You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. escapeshellcmd() is executed on the argument of this function.
popen() | You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable. escapeshellcmd() is executed on the argument of this function.
fopen() | Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.
mkdir() | Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.
rmdir() | Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.
rename() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.
unlink() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.
copy() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed. (on source and target)
chgrp() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.
chown() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.
chmod() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. In addition, you cannot set the SUID, SGID and sticky bits
touch() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.
symlink() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed. (note: only the target is checked)
link() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed. (note: only the target is checked)
apache_request_headers() | In safe mode, headers beginning with authorization (case-insensitive) will not be returned.
header() | In safe mode, the uid of the script is added to the realm part of the WWW-Authenticate header if you set this header (used for HTTP Authentication).
PHP_AUTH variables | In safe mode, the variables PHP_AUTH_USER, PHP_AUTH_PW, and AUTH_TYPE are not available in $_SERVER. Regardless, you can still use REMOTE_USER for the USER. (note: only affected since PHP 4.3.0)
highlight_file(), show_source() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.
parse_ini_file() | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.
set_time_limit() | Has no effect when PHP is running in safe mode.
max_execution_time | Has no effect when PHP is running in safe mode.
mail() | In safe mode, the fifth parameter is disabled.
session_start() | The owner of a script must be the same as owner of a session.save_path directory if the default files session.save_handler is used.
All filesystem and stream functions. | Checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed. Checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed. (see the safe_mode_include_dir php.ini option.


Using PHP from the command line

Table of Contents

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

As of PHP 5, the CLI binary is distributed in the main folder as php.exe on Windows. The CGI version is distributed as php-cgi.exe. Additionally, a php-win.exe is distributed if PHP is configured using --enable-cli-win32 . This does the same as the CLI version, except that it doesn't output anything and thus provides no console.

Note: What SAPI do I have?

From a shell, typing php -v will tell you whether php is CGI or CLI. See also the function php_sapi_name() and the constant PHP_SAPI.

Note:

A Unix manual page is available by typing man php in the shell environment.


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 enviroment when they are cluttered up with uninterpreted HTML tags.
    implicit_flush | TRUE | In a shell environment, it is usually desirable for output, such as from print, echo and friends, to be displayed immediately, and not held in a buffer. Nonetheless, it is still possible to use output buffering to defer or manipulate standard output.
    max_execution_time | 0 (unlimited) | PHP in a shell environment tends to be used for a much more diverse range of purposes than typical Web-based scripts, and as these can be very long-running, the maximum execution time is set to unlimited.
    register_argc_argv TRUE

    Setting this to 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'].

    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]

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

Note:

To pass arguments to a script, the first argument must be --, otherwise PHP will interpret them as PHP options.

-h and -? | --help and --usage | Output a list of command line options with one line descriptions of what they do.
-i | --info | Calls phpinfo(), and prints out the results. If PHP is not working correctly, it is advisable to use the command php -i and see whether any error messages are printed out before or in place of the information tables. Beware that when using the CGI mode the output is in HTML and therefore very large.
-l --syntax-check

Provides a convenient way to perform only a syntax check on the given PHP code. On success, the text No syntax errors detected in <filename> is written to standard output and the shell return code is 0. On failure, the text Errors parsing <filename> in addition to the internal parser error message is written to standard output and the shell return code is set to -1.

This option won't find fatal errors (like undefined functions). Use the -f to test for fatal errors too.

Note:

This option does not work together with the -r option.

-m --modules

Example #1 Printing built in (and loaded) PHP and Zend modules

$ php -m
[PHP Modules]
xml
tokenizer
standard
session
posix
pcre
overload
mysql
mbstring
ctype

[Zend Modules]

-r --run

Allows execution of PHP included directly on the command line. The PHP start and end tags (<?php and ?>) are not needed and will cause a parse error if present.

Note:

Care must be taken when using this form of PHP not to collide with command line variable substitution done by the shell.

Example #2 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 #3 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://bugs.php.net/. It is still easy to run into trouble when trying to use variables (shell or PHP) in commnad-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. Added in PHP 5.

-R --process-code

PHP code to execute for every input line. Added in PHP 5.

There are two special variables available in this mode: $argn and $argi. $argn will contain the line PHP is processing at that moment, while $argi will contain the line number.

-F --process-file

PHP file to execute for every input line. Added in PHP 5.

-E --process-end

PHP code to execute after processing the input. Added in PHP 5.

Example #4 Using the -B , -R and -E options to count the number of lines of a project.

$ find my_proj | php -B '$l=0;' -R '$l += count(@file($argn));' -E 'echo "Total Lines: $l\n";'
Total Lines: 37328

-S --server

Starts built-in web server. Available as of PHP 5.4.0.

-t | --docroot | Specifies document root for built-in web server. Available as of PHP 5.4.0.
-s --syntax-highlight and --syntax-highlighting

Display colour syntax highlighted source.

This option uses the internal mechanism to parse the file and writes an HTML highlighted version of it to standard output. Note that all it does is generate a block of <code> [...] </code> HTML tags, no HTML headers.

Note:

This option does not work together with the -r option.

-v --version

Example #5 Using -v to get the SAPI name and the version of PHP and Zend

$ php -v
PHP 5.3.1 (cli) (built: Dec 11 2009 19:55:07)
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2009 Zend Technologies

-w --strip

Display source with comments and whitespace stripped.

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. Available as of PHP 5.2.3.

Example #6 --ini example

$ php --ini
Configuration File (php.ini) Path: /usr/dev/php/5.2/lib
Loaded Configuration File:         /usr/dev/php/5.2/lib/php.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed:      (none)
--rf --rfunction

Show information about the given function or class method (e.g. number and name of the parameters). Available as of PHP 5.1.2.

This option is only available if PHP was compiled with Reflection support.

Example #7 basic --rf usage

$ php --rf var_dump
Function [ <internal> public function var_dump ] {

  - Parameters [2] {
    Parameter #0 [ <required> $var ]
    Parameter #1 [ <optional> $... ]
  }
}
--rc --rclass

Show information about the given class (list of constants, properties and methods). Available as of PHP 5.1.2.

This option is only available if PHP was compiled with Reflection support.

Example #8 --rc example

$ php --rc Directory
Class [ <internal:standard> class Directory ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [0] {
  }

  - Methods [3] {
    Method [ <internal> public method close ] {
    }

    Method [ <internal> public method rewind ] {
    }

    Method [ <internal> public method read ] {
    }
  }
}
--re --rextension

Show information about the given extension (list of php.ini options, defined functions, constants and classes). Available as of PHP 5.1.2.

This option is only available if PHP was compiled with Reflection support.

Example #9 --re example

$ php --re json
Extension [ <persistent> extension #19 json version 1.2.1 ] {

  - Functions {
    Function [ <internal> function json_encode ] {
    }
    Function [ <internal> function json_decode ] {
    }
  }
}
--rz --rzendextension

Show the configuration information for the given Zend extension (the same information that is returned by phpinfo()). Available as of PHP 5.4.0.

--ri --rextinfo

Show the configuration information for the given extension (the same information that is returned by phpinfo()). Available as of PHP 5.2.2. The core configuration information is available using "main" as extension name.

Example #10 --ri example

$ php --ri date

date

date/time support => enabled
"Olson" Timezone Database Version => 2009.20
Timezone Database => internal
Default timezone => Europe/Oslo

Directive => Local Value => Master Value
date.timezone => Europe/Oslo => Europe/Oslo
date.default_latitude => 59.930972 => 59.930972
date.default_longitude => 10.776699 => 10.776699
date.sunset_zenith => 90.583333 => 90.583333
date.sunrise_zenith => 90.583333 => 90.583333

Note:

Options -rBRFEH, --ini and --r[fcezi] are available only in CLI.


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.

    Note:

    If arguments need to be passed to the script when using -f , the first argument must be --.

  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 just a dash (-). The same is true if the code is executed via a pipe from STDIN.

A second global variable, $argc, contains the number of elements in the $argv array (not the number of arguments passed to the script).

As long as the arguments to be passed to the script do not start with the - character, there's nothing special to watch out for. Passing an argument to the script which starts with a - will cause trouble because the PHP interpreter thinks it has to handle it itself, even before executing the script. To prevent this, use the argument list separator --. After this separator has been parsed by PHP, every following argument is passed untouched to the script.

# This will not execute the given code but will show the PHP usage
$ php -r 'var_dump($argv);' -h
Usage: php [options] [-f] <file> [args...]
[...]

# This will pass the '-h' argument to the script and prevent PHP from showing its usage
$ php -r 'var_dump($argv);' -- -h
array(2) {
  [0]=>
  string(1) "-"
  [1]=>
  string(2) "-h"
}

However, on Unix systems there's another way of using PHP for shell scripting: make the first line of the script start with #!/usr/bin/php (or whatever the path to your PHP CLI binary is if different). The rest of the file should contain normal PHP code within the usual PHP starting and end tags. Once the execution attributes of the file are set appropriately (e.g. chmod +x test), the script can be executed like any other shell or perl script:

Example #1 Execute PHP script as shell script

#!/usr/bin/php
<?php
var_dump($argv);
?>

Assuming this file is named test in the current directory, it is now possible to do the following:

$ chmod +x test
$ ./test -h -- foo
array(4) {
  [0]=>
  string(6) "./test"
  [1]=>
  string(2) "-h"
  [2]=>
  string(2) "--"
  [3]=>
  string(3) "foo"
}

As can be seen, in this case no special care needs to be taken when passing parameters starting with -.

The PHP executable can be used to run PHP scripts absolutely independent of the web server. On Unix systems, the special #! (or "shebang") first line should be added to PHP scripts so that the system can automatically tell which program should run the script. On Windows platforms, it's possible to associate php.exe with the double click option of the .php extension, or a batch file can be created to run scripts through PHP. The special shebang first line for Unix does no harm on Windows (as it's formatted as a PHP comment), so cross platform programs can be written by including it. A simple example of writing a command line PHP program is shown below.

Example #2 Script intended to be run from command line (script.php)

#!/usr/bin/php
<?php

if ($argc != 2 || in_array($argv[1], array('--help', '-help', '-h', '-?'))) {
?>

This is a command line PHP script with one option.

  Usage:
  <?php echo $argv[0]; ?> <option>

  <option> can be some word you would like
  to print out. With the --help, -help, -h,
  or -? options, you can get this help.

<?php
} else {
    echo $argv[1];
}
?>

The script above includes the Unix shebang first line to indicate that this file should be run by PHP. We are working with a CLI version here, so no HTTP headers will be output.

The program first checks that there is the required one argument (in addition to the script name, which is also counted). If not, or if the argument was --help , -help , -h or -? , the help message is printed out, using $argv[0] to dynamically print the script name as typed on the command line. Otherwise, the argument is echoed out exactly as received.

To run the above script on Unix, it must be made executable, and called simply as script.php echothis or script.php -h. On Windows, a batch file similar to the following can be created for this task:

Example #3 Batch file to run a command line PHP script (script.bat)

@echo OFF
"C:\php\php.exe" script.php %*

Assuming the above program is named script.php, and the CLI php.exe is in C:\php\php.exe, this batch file will run it, passing on all appended options: script.bat echothis or script.bat -h.

See also the Readline extension documentation for more functions which can be used to enhance command line applications in PHP.

On Windows, PHP can be configured to run without the need to supply the C:\php\php.exe or the .php extension, as described in Command Line PHP on Microsoft Windows.


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

As of PHP 5.1.0, the CLI SAPI provides an interactive shell using the -a option if PHP is compiled with the --with-readline option. 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 5.4.0, the CLI SAPI provides the php.ini settings cli.pager and cli.prompt. The cli.pager setting allows an external program (such as less) to act as a pager for the output instead of being displayed directly on the screen. The cli.prompt setting makes it possible to change the php > prompt.

In PHP 5.4.0 it was also made possible to set php.ini settings in the interactive shell using a shorthand notation.

Example #3 Setting php.ini settings in the interactive shell

The cli.prompt setting:

php > #cli.prompt=hello world :>
hello world :>

Using backticks it is possible to have PHP code executed in the prompt:

php > #cli.prompt=`echo date('H:i:s');` php >
15:49:35 php > echo 'hi';
hi
15:49:43 php > sleep(2);
15:49:45 php >

Setting the pager to less:

php > #cli.pager=less
php > phpinfo();
(output displayed in less)
php >

The cli.prompt setting supports a few escape sequences:

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.

Note:

Autoloading is not available if using PHP in CLI interactive mode.


Built-in web server

Warning

This web server was designed to aid application development. It may also be useful for testing purposes or for application demonstrations that are run in controlled environments. It is not intended to be a full-featured web server. It should not be used on a public network.

As of PHP 5.4.0, the CLI SAPI provides a built-in web server.

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, .pdf, .png, .pps, .pptx, .qt, .svg, .swf, .tar, .text, .tif, .txt, .wav, .webm, .wmv, .xls, .xlsx, .xml, .xsl, .xsd, and .zip.

Changelog: Supported MIME Types (file extensions)
Version | Description
5.5.12 | .xml, .xsl, and .xsd
5.5.7 | .3gp, .apk, .avi, .bmp, .csv, .doc, .docx, .flac, .gz, .gzip, .ics, .kml, .kmz, .m4a, .mp3, .mp4, .mpg, .mpeg, .mov, .odp, .ods, .odt, .oga, .pdf, .pptx, .pps, .qt, .swf, .tar, .text, .tif, .wav, .wmv, .xls, .xlsx, and .zip
5.5.5 | .pdf
5.4.11 | .ogg, .ogv, and .webm
5.4.4 | .htm and .svg

Example #1 Starting the web server

$ cd ~/public_html
$ php -S localhost:8000

The terminal will show:

PHP 5.4.0 Development Server started at Thu Jul 21 10:43:28 2011
Listening on localhost:8000
Document root is /home/me/public_html
Press Ctrl-C to quit

After URI requests for http://localhost:8000/ and http://localhost:8000/myscript.html the terminal will show something similar to:

PHP 5.4.0 Development Server started at Thu Jul 21 10:43:28 2011
Listening on localhost:8000
Document root is /home/me/public_html
Press Ctrl-C to quit.
[Thu Jul 21 10:48:48 2011] ::1:39144 GET /favicon.ico - Request read
[Thu Jul 21 10:48:50 2011] ::1:39146 GET / - Request read
[Thu Jul 21 10:48:50 2011] ::1:39147 GET /favicon.ico - Request read
[Thu Jul 21 10:48:52 2011] ::1:39148 GET /myscript.html - Request read
[Thu Jul 21 10:48:52 2011] ::1:39149 GET /favicon.ico - Request read

Example #2 Starting with a specific document root directory

$ cd ~/public_html
$ php -S localhost:8000 -t foo/

The terminal will show:

PHP 5.4.0 Development Server started at Thu Jul 21 10:50:26 2011
Listening on localhost:8000
Document root is /home/me/public_html/foo
Press Ctrl-C to quit

Example #3 Using a Router Script

In this example, requests for images will display them, but requests for HTML files will display "Welcome to PHP":

<?php
// router.php
if (preg_match('/\.(?:png|jpg|jpeg|gif)$/', $_SERVER["REQUEST_URI"])) {
    return false;    // serve the requested resource as-is.
} else {
    echo "<p>Welcome to PHP</p>";
}
?>
$ php -S localhost:8000 router.php

Example #4 Checking for CLI Web Server Use

To reuse a framework router script during development with the CLI web server and later also with a production web server:

<?php
// router.php
if (php_sapi_name() == 'cli-server') {
    /* route static assets and return false */
}
/* go on with normal index.php operations */
?>
$ php -S localhost:8000 router.php

Example #5 Handling Unsupported File Types

If you need to serve a static resource whose MIME type is not handled by the CLI web server, use:

<?php
// router.php
$path = pathinfo($_SERVER["SCRIPT_FILENAME"]);
if ($path["extension"] == "el") {
    header("Content-Type: text/x-script.elisp");
    readfile($_SERVER["SCRIPT_FILENAME"]);
}
else {
    return FALSE;
}
?>
$ php -S localhost:8000 router.php

Example #6 Accessing the CLI Web Server From Remote Machines

You can make the web server accessible on port 8000 to any interface with:

$ php -S 0.0.0.0:8000


INI settings

CLI SAPI Configuration Options
Name | Default | Changeable | Changelog
cli_server.color | "0" | PHP_INI_ALL | Available since PHP 5.4.0.

Here's a short explanation of the configuration directives.

cli_server.color boolean

Enable the built-in development web server to use ANSI color coding in terminal output.


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 if "refcount" is 1, "is_ref" is always FALSE. If you have » Xdebug installed, you can display this information by calling xdebug_debug_zval().

Example #2 Displaying zval information

<?php
$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

Zvals for a simple array

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

Zvals for a simple array with a reference

From the above Xdebug output, we see that both the old and new array elements now point to a zval container whose "refcount" is 2. Although Xdebug's output shows two zval containers with value 'life', they are the same one. The xdebug_debug_zval() function does not show this, but you could see it by also displaying the memory pointer.

Removing an element from the array is like removing a symbol from a scope. By doing so, the "refcount" of a container that an array element points to is decreased. Again, when the "refcount" reaches zero, the variable container is removed from memory. Again, an example to show this:

Example #7 Removing an element from an array

<?php
$a = array( 'meaning' => 'life', 'number' => 42 );
$a['life'] = $a['meaning'];
unset( $a['meaning'], $a['number'] );
xdebug_debug_zval( 'a' );
?>

The above example will output something similar to:

a: (refcount=1, is_ref=0)=array (
   'life' => (refcount=1, is_ref=0)='life'
)

Now, things get interesting if we add the array itself as an element of the array, which we do in the next example, in which we also sneak in a reference operator, since otherwise PHP would create a copy:

Example #8 Adding the array itself as an element of it self

<?php
$a = array( 'one' );
$a[] =& $a;
xdebug_debug_zval( 'a' );
?>

The above example will output something similar to:

a: (refcount=2, is_ref=1)=array (
   0 => (refcount=1, is_ref=0)='one',
   1 => (refcount=2, is_ref=1)=...
)

Or graphically

Zvals for an array with a circular reference

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

Zvals after removal of array with a circular reference demonstrating the memory leak

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.

Garbage collection algorithm

To avoid having to call the checking of garbage cycles with every possible decrease of a refcount, the algorithm instead puts all possible roots (zvals) in the "root buffer" (marking them "purple"). It also makes sure that each possible garbage root ends up in the buffer only once. Only when the root buffer is full does the collection mechanism start for all the different zvals inside. See step A in the figure above.

In step B, the algorithm runs a depth-first search on all possible roots to decrease by one the refcounts of each zval it finds, making sure not to decrease a refcount on the same zval twice (by marking them as "grey"). In step C, the algorithm again runs a depth-first search from each root node, to check the refcount of each zval again. If it finds that the refcount is zero, the zval is marked "white" (blue in the figure). If it's larger than zero, it reverts the decreasing of the refcount by one with a depth-first search from that point on, and they are marked "black" again. In the last step (D), the algorithm walks over the root buffer removing the zval roots from there, and meanwhile, checks which zvals have been marked "white" in the previous step. Every zval marked as "white" will be freed.

Now that you have a basic understanding of how the algorithm works, we will look back at how this integrates with PHP. By default, PHP's garbage collector is turned on. There is, however, a php.ini setting that allows you to change this: zend.enable_gc.

When the garbage collector is turned on, the cycle-finding algorithm as described above is executed whenever the root buffer runs full. The root buffer has a fixed size of 10,000 possible roots (although you can alter this by changing the GC_ROOT_BUFFER_MAX_ENTRIES constant in Zend/zend_gc.c in the PHP source code, and re-compiling PHP). When the garbage collector is turned off, the cycle-finding algorithm will never run. However, possible roots will always be recorded in the root buffer, no matter whether the garbage collection mechanism has been activated with this configuration setting.

If the root buffer becomes full with possible roots while the garbage collection mechanism is turned off, further possible roots will simply not be recorded. Those possible roots that are not recorded will never be analyzed by the algorithm. If they were part of a circular reference cycle, they would never be cleaned up and would create a memory leak.

The reason why possible roots are recorded even if the mechanism has been disabled is because it's faster to record possible roots than to have to check whether the mechanism is turned on every time a possible root could be found. The garbage collection and analysis mechanism itself, however, can take a considerable amount of time.

Besides changing the zend.enable_gc configuration setting, it is also possible to turn the garbage collecting mechanism on and off by calling gc_enable() or gc_disable() respectively. Calling those functions has the same effect as turning on or off the mechanism with the configuration setting. It is also possible to force the collection of cycles even if the possible root buffer is not full yet. For this, you can use the gc_collect_cycles() function. This function will return how many cycles were collected by the algorithm.

The rationale behind the ability to turn the mechanism on and off, and to initiate cycle collection yourself, is that some parts of your application could be highly time-sensitive. In those cases, you might not want the garbage collection mechanism to kick in. Of course, by turning off the garbage collection for certain parts of your application, you do risk creating memory leaks because some possible roots might not fit into the limited root buffer. Therefore, it is probably wise to call gc_collect_cycles() just before you call gc_disable() to free up the memory that could be lost through possible roots that are already recorded in the root buffer. This then leaves an empty buffer so that there is more space for storing possible roots while the cycle collecting mechanism is turned off.


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

$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";
    }
}
?>
Comparison of memory usage between PHP 5.2 and PHP 5.3

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

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.

DTrace static probes are included in PHP 5.4. Prior to this they were available via a » PECL extension, which is now obsolete.

The static DTrace probes in PHP can alternatively be used with the SystemTap facility on some Linux distributions.


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 enables the static probes in core PHP. Any PHP extensions that provide their own probes should be built separately as shared extensions.

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


Function Reference

Tip

See also Extension List/Categorization.

  • Affecting PHP's Behaviour
    • APC — Alternative PHP Cache
    • APCu — APC User Cache
    • APD — Advanced PHP debugger
    • bcompiler — PHP bytecode Compiler
    • BLENC — Blenc - BLowfish ENCoder for PHP source scripts
    • Componere
    • Error Handling — Error Handling and Logging
    • FFI — Foreign Function Interface
    • htscanner — htaccess-like support for all SAPIs
    • inclued — Inclusion hierarchy viewer
    • Memtrack
    • OPcache
    • Output Control — Output Buffering Control
    • PHP Options/Info — PHP Options and Information
    • phpdbg — Interactive PHP Debugger
    • runkit
    • runkit7
    • scream — Break the silence operator
    • uopz — User Operations for Zend
    • Weakref — Weak References
    • WinCache — Windows Cache for PHP
    • Xhprof — Hierarchical Profiler
  • Audio Formats Manipulation
    • ID3 — ID3 Tags
    • KTaglib
    • oggvorbis — OGG/Vorbis
    • OpenAL — OpenAL Audio Bindings
  • Authentication Services
    • KADM5 — Kerberos V
    • Radius
  • Command Line Specific Extensions
    • Ncurses — Ncurses Terminal Screen Control
    • Newt
    • Readline — GNU Readline
  • Compression and Archive Extensions
    • Bzip2
    • LZF
    • Phar
    • Rar — Rar Archiving
    • Zip
    • Zlib — Zlib Compression
  • Credit Card Processing
    • MCVE — MCVE (Monetra) Payment
  • Cryptography Extensions
    • Crack — Cracklib
    • CSPRNG
    • Hash — HASH Message Digest Framework
    • Mcrypt
    • Mhash
    • OpenSSL
    • Password Hashing
    • Sodium
  • Database Extensions
    • Abstraction Layers
    • Vendor Specific Database Extensions
  • Date and Time Related Extensions
    • Calendar
    • Date/Time — Date and Time
    • HRTime — High resolution timing
  • File System Related Extensions
    • Direct IO
    • Directories
    • Fileinfo — File Information
    • Filesystem
    • Inotify
    • Mimetype
    • Phdfs
    • Proctitle
    • xattr
    • xdiff
  • Human Language and Character Encoding Support
    • Enchant — Enchant spelling library
    • FriBiDi
    • Gender — Determine gender of firstnames
    • Gettext
    • iconv
    • intl — Internationalization Functions
    • Multibyte String
    • Pspell
    • Recode — GNU Recode
  • Image Processing and Generation
    • Cairo
    • Exif — Exchangeable image information
    • GD — Image Processing and GD
    • Gmagick
    • ImageMagick — Image Processing (ImageMagick)
  • Mail Related Extensions
    • Cyrus — Cyrus IMAP administration
    • IMAP — IMAP, POP3 and NNTP
    • Mail
    • Mailparse
    • vpopmail
  • Mathematical Extensions
    • BC Math — BCMath Arbitrary Precision Mathematics
    • GMP — GNU Multiple Precision
    • Lapack
    • Math — Mathematical Functions
    • Statistics
    • Trader — Technical Analysis for Traders
  • Non-Text MIME Output
    • FDF — Forms Data Format
    • GnuPG — GNU Privacy Guard
    • haru — Haru PDF
    • Ming — Ming (flash)
    • PDF
    • wkhtmltox
    • PS — PostScript document creation
    • RPM Reader — RPM Header Reading
    • XLSWriter
  • Process Control Extensions
    • Eio
    • Ev
    • Expect
    • Libevent
    • PCNTL — Process Control
    • POSIX
    • Program execution — System program execution
    • parallel
    • pthreads
    • pht
    • Semaphore — Semaphore, Shared Memory and IPC
    • Shared Memory
    • Sync
  • Other Basic Extensions
    • GeoIP — Geo IP Location
    • FANN — FANN (Fast Artificial Neural Network)
    • JSON — JavaScript Object Notation
    • Judy — Judy Arrays
    • Lua
    • LuaSandbox
    • Misc. — Miscellaneous Functions
    • Parsekit
    • Seaslog
    • SPL — Standard PHP Library (SPL)
    • SPL Types — SPL Type Handling
    • Streams
    • Swoole
    • Tidy
    • Tokenizer
    • URLs
    • V8js — V8 Javascript Engine Integration
    • Yaml — YAML Data Serialization
    • Yaf — Yet Another Framework
    • Yaconf
    • Taint
    • Data Structures
  • Other Services
    • chdb — Constant hash database
    • cURL — Client URL Library
    • Event
    • FAM — File Alteration Monitor
    • FTP
    • Gearman
    • Gopher — Net Gopher
    • Gupnp
    • Hyperwave API
    • LDAP — Lightweight Directory Access Protocol
    • Memcache
    • Memcached
    • mqseries
    • Network
    • RRD — RRDtool
    • SAM — Simple Asynchronous Messaging
    • ScoutAPM
    • SNMP
    • Sockets
    • SSH2 — Secure Shell2
    • Stomp — Stomp Client
    • SVM — Support Vector Machine
    • SVN — Subversion
    • TCP — TCP Wrappers
    • Varnish
    • YAZ
    • YP/NIS
    • 0MQ messaging — ZMQ
    • ZooKeeper
  • Search Engine Extensions
    • mnoGoSearch
    • Solr — Apache Solr
    • Sphinx — Sphinx Client
    • Swish — Swish Indexing
  • Server Specific Extensions
    • Apache
    • FastCGI Process Manager
    • IIS — IIS Administration
    • NSAPI
  • Session Extensions
    • Msession — Mohawk Software Session Handler Functions
    • Sessions — Session Handling
    • Session PgSQL — PostgreSQL Session Save Handler
  • Text Processing
    • BBCode — Bulletin Board Code
    • CommonMark
    • Parle — Parsing and lexing
    • PCRE — Regular Expressions (Perl-Compatible)
    • POSIX Regex — Regular Expression (POSIX Extended)
    • ssdeep — ssdeep Fuzzy Hashing
    • Strings
  • Variable and Type Related Extensions
    • Arrays
    • Classes/Objects — Class/Object Information
    • Classkit
    • Ctype — Character type checking
    • Filter — Data Filtering
    • Function Handling
    • Quickhash
    • Reflection
    • Variable handling
  • Web Services
    • OAuth
    • SCA
    • SOAP
    • Yar — Yet Another RPC Framework
    • XML-RPC
  • Windows Only Extensions
    • COM — COM and .Net (Windows)
    • win32ps
    • win32service
  • XML Manipulation
    • DOM — Document Object Model
    • libxml
    • SDO — Service Data Objects
    • SDO-DAS-Relational — SDO Relational Data Access Service
    • SDO DAS XML — SDO XML Data Access Service
    • SimpleXML
    • WDDX
    • XMLDiff — XML diff and merge
    • XML Parser
    • XMLReader
    • XMLWriter
    • XSL
  • GUI Extensions
    • UI


Affecting PHP's Behaviour

  • APC — Alternative PHP Cache
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • APC Functions
    • APCIterator — The APCIterator class
  • APCu — APC User Cache
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • APCu Functions
    • APCUIterator — The APCUIterator class
  • APD — Advanced PHP debugger
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • APD Functions
  • bcompiler — PHP bytecode Compiler
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • bcompiler Functions
  • BLENC — Blenc - BLowfish ENCoder for PHP source scripts
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Blenc Functions
  • Componere
    • Introduction
    • 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
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Error Handling Functions
  • FFI — Foreign Function Interface
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • 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
  • htscanner — htaccess-like support for all SAPIs
    • Introduction
    • Installing/Configuring
  • inclued — Inclusion hierarchy viewer
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • inclued Functions
  • Memtrack
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
  • OPcache
    • Introduction
    • Installing/Configuring
    • OPcache Functions
  • Output Control — Output Buffering Control
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Output Control Functions
  • PHP Options/Info — PHP Options and Information
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • PHP Options/Info Functions
  • phpdbg — Interactive PHP Debugger
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • phpdbg Functions
  • runkit
    • Introduction
    • Predefined Constants
    • Installing/Configuring
    • runkit Functions
  • runkit7
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • runkit7 Functions
  • scream — Break the silence operator
    • Introduction
    • Installing/Configuring
    • Examples
  • uopz — User Operations for Zend
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Uopz Functions
  • Weakref — Weak References
    • Introduction
    • Installing/Configuring
    • WeakRef — The WeakRef class
    • WeakMap — The WeakMap class
  • WinCache — Windows Cache for PHP
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • WinCache Functions
    • Building for Windows
  • Xhprof — Hierarchical Profiler
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Xhprof Functions


Alternative PHP Cache

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • APC Functions
    • apc_add — Cache a new variable in the data store
    • apc_bin_dump — Get a binary dump of the given files and user variables
    • apc_bin_dumpfile — Output a binary dump of cached files and user variables to a file
    • apc_bin_load — Load a binary dump into the APC file/user cache
    • apc_bin_loadfile — Load a binary dump from a file into the APC file/user cache
    • apc_cache_info — Retrieves cached information from APC's data store
    • apc_cas — Updates an old value with a new value
    • apc_clear_cache — Clears the APC cache
    • apc_compile_file — Stores a file in the bytecode cache, bypassing all filters
    • apc_dec — Decrease a stored number
    • apc_define_constants — Defines a set of constants for retrieval and mass-definition
    • apc_delete_file — Deletes files from the opcode cache
    • apc_delete — Removes a stored variable from the cache
    • apc_exists — Checks if APC key exists
    • apc_fetch — Fetch a stored variable from the cache
    • apc_inc — Increase a stored number
    • apc_load_constants — Loads a set of constants from the cache
    • apc_sma_info — Retrieves APC's Shared Memory Allocation information
    • apc_store — Cache a variable in the data store
  • APCIterator — The APCIterator class
    • APCIterator::__construct — Constructs an APCIterator iterator object
    • APCIterator::current — Get current item
    • APCIterator::getTotalCount — Get total count
    • APCIterator::getTotalHits — Get total cache hits
    • APCIterator::getTotalSize — Get total cache size
    • APCIterator::key — Get iterator key
    • APCIterator::next — Move pointer to next item
    • APCIterator::rewind — Rewinds iterator
    • APCIterator::valid — Checks if current position is valid


Introduction

The Alternative PHP Cache (APC) is a free and open opcode cache for PHP. Its goal is to provide a free, open, and robust framework for caching and optimizing PHP intermediate code.

Warning

This extension is considered unmaintained and dead. However, the source code for this extension is still available within PECL GIT here: https://git.php.net/?p=pecl/caching/apc.git.

Note:

Alternatives to this extension are OPcache, APCu, Windows Cache for PHP and the Session Upload Progress API.


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

No external libraries are needed to build this extension.


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

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Note: On Windows, APC needs a temp path to exist, and be writable by the web server. It checks the TMP, TEMP and USERPROFILE environment variables in that order and finally tries the WINDOWS directory if none of those are set.

Note: For more in-depth, highly technical implementation details, see the » developer-supplied TECHNOTES file .


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Although the default APC settings are fine for many installations, serious users should consider tuning the following parameters.

There are two primary decisions to be made configuring APC. First, how much memory is going to be allocated to APC; and second, whether APC will check if a file has been modified on every request. The two ini directives that control these settings are apc.shm_size and apc.stat, respectively. Read the sections on these two directive carefully below.

Once the server is running, the apc.php script that is bundled with the extension should be copied somewhere into the docroot and viewed with a browser as it provides a detailed analysis of the internal workings of APC. If GD is enabled in PHP, it will even display some interesting graphs. The first thing to ensure, of course, is that it is actually caching files. If APC is working, the Cache full count number (on the left) will display the number of times the cache has reached maximum capacity and has had to forcefully clean any entries that haven't been accessed in the last apc.ttl seconds. This number is minimized in a well-configured cache. If the cache is constantly being filled, and thusly forcefully freed, the resulting churning will have disparaging effects on script performance. The easiest way to minimize this number is to allocate more memory for APC. Barring that, the apc.filters ought to be used to cache fewer scripts.

When APC is compiled with mmap support (Memory Mapping), it will use only one memory segment, unlike when APC is built with SHM (SysV Shared Memory) support that uses multiple memory segments. MMAP does not have a maximum limit like SHM does in /proc/sys/kernel/shmmax. In general MMAP support is recommeded because it will reclaim the memory faster when the webserver is restarted and all in all reduces memory allocation impact at startup.

APC configuration options
Name | Default | Changeable | Changelog
apc.enabled | "1" | PHP_INI_SYSTEM | PHP_INI_SYSTEM in APC 2. PHP_INI_ALL in APC <= 3.0.12.
apc.shm_segments | "1" | PHP_INI_SYSTEM |
apc.shm_size | "32M" | PHP_INI_SYSTEM |
apc.shm_strings_buffer | "4M" | PHP_INI_SYSTEM | Available since APC 3.1.4.
apc.optimization | "0" | PHP_INI_ALL | PHP_INI_SYSTEM in APC 2. Removed in APC 3.0.13.
apc.num_files_hint | "1000" | PHP_INI_SYSTEM |
apc.user_entries_hint | "4096" | PHP_INI_SYSTEM | Available since APC 3.0.0.
apc.ttl | "0" | PHP_INI_SYSTEM | Available since APC 3.0.0.
apc.user_ttl | "0" | PHP_INI_SYSTEM | Available since APC 3.0.0.
apc.gc_ttl | "3600" | PHP_INI_SYSTEM |
apc.cache_by_default | "1" | PHP_INI_ALL | PHP_INI_SYSTEM in APC <= 3.0.12. Available since APC 3.0.0.
apc.filters | NULL | PHP_INI_SYSTEM |
apc.mmap_file_mask | NULL | PHP_INI_SYSTEM |
apc.slam_defense | "1" | PHP_INI_SYSTEM | Available since APC 3.0.0. Prior to APC 3.1.4, the default value was "0" (disabled).
apc.file_update_protection | "2" | PHP_INI_SYSTEM | Available since APC 3.0.6.
apc.enable_cli | "0" | PHP_INI_SYSTEM | Available since APC 3.0.7.
apc.max_file_size | "1M" | PHP_INI_SYSTEM | Available since APC 3.0.7.
apc.use_request_time | "1" | PHP_INI_ALL | Available since APC 3.1.3.
apc.stat | "1" | PHP_INI_SYSTEM | Available since APC 3.0.10.
apc.write_lock | "1" | PHP_INI_SYSTEM | Available since APC 3.0.11.
apc.report_autofilter | "0" | PHP_INI_SYSTEM | Available since APC 3.0.11.
apc.serializer | "default" | PHP_INI_SYSTEM | Available since APC 3.1.0.
apc.include_once_override | "0" | PHP_INI_SYSTEM | Available since APC 3.0.12.
apc.rfc1867 | "0" | PHP_INI_SYSTEM | Available since APC 3.0.13.
apc.rfc1867_prefix | "upload_" | PHP_INI_SYSTEM |
apc.rfc1867_name | "APC_UPLOAD_PROGRESS" | PHP_INI_SYSTEM |
apc.rfc1867_freq | "0" | PHP_INI_SYSTEM |
apc.rfc1867_ttl | "3600" | PHP_INI_SYSTEM | Available since APC 3.1.1.
apc.localcache | "0" | PHP_INI_SYSTEM | Available in APC 3.0.14 - 3.1.11.
apc.localcache.size | "512" | PHP_INI_SYSTEM | vailable in APC 3.0.14 - 3.1.11.
apc.coredump_unmap | "0" | PHP_INI_SYSTEM | Available since APC 3.0.16.
apc.stat_ctime | "0" | PHP_INI_SYSTEM | Available since APC 3.0.13.
apc.preload_path | NULL | PHP_INI_SYSTEM | Available since APC 3.1.1.
apc.file_md5 | "0" | PHP_INI_SYSTEM | Available since APC 3.1.1.
apc.canonicalize | "1" | PHP_INI_SYSTEM | Available since APC 3.1.1.
apc.lazy_functions | 0 | PHP_INI_SYSTEM | Available since APC 3.1.3.
apc.lazy_classes | 0 | PHP_INI_SYSTEM | Available since APC 3.1.3.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

apc.enabled boolean

apc.enabled can be set to 0 to disable APC. This is primarily useful when APC is statically compiled into PHP, since there is no other way to disable it (when compiled as a DSO, the extension line in php.ini can just be commented-out).

apc.shm_segments integer

The number of shared memory segments to allocate for the compiler cache. If APC is running out of shared memory but apc.shm_size is set as high as the system allows, raising this value might prevent APC from exhausting its memory.

apc.shm_size 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.shm_strings_buffer string

The size of memory to use as a shared buffer for strings used internally by APC. Size Should be suffixed by M for megabytes, G for gigabytes. Enabling this option will reduce the amount of memory used per PHP-FPM worker as strings will be stored once rather than for each worker.

apc.optimization integer

The optimization level. Zero disables the optimizer, and higher values use more aggressive optimizations. Expect very modest speed improvements. This is experimental.

apc.num_files_hint integer

A "hint" about the number of distinct source files that will be included or requested on your web server. Set to zero or omit if unsure; this setting is mainly useful for sites that have many thousands of source files.

apc.user_entries_hint integer

Just like apc.num_files_hint, a "hint" about the number of distinct user cache variables to store. Set to zero or omit if not sure.

apc.ttl integer

The number of seconds a cache entry is allowed to idle in a slot in case this cache entry slot is needed by another entry. Leaving this at zero means that APC's cache could potentially fill up with stale entries while newer entries won't be cached. In the event of a cache running out of available memory, the cache will be completely expunged if ttl is equal to 0. Otherwise, if the ttl is greater than 0, APC will attempt to remove expired entries.

apc.user_ttl integer

The number of seconds a cache entry is allowed to idle in a slot in case this cache entry slot is needed by another entry. Leaving this at zero means that APC's cache could potentially fill up with stale entries while newer entries won't be cached. In the event of a cache running out of available memory, the cache will be completely expunged if ttl is equal to 0. Otherwise, if the ttl is greater than 0, APC will attempt to remove expired entries.

apc.gc_ttl integer

The number of seconds that a cache entry may remain on the garbage-collection list. This value provides a fail-safe in the event that a server process dies while executing a cached source file; if that source file is modified, the memory allocated for the old version will not be reclaimed until this TTL reached. Set to zero to disable this feature.

apc.cache_by_default boolean

On by default, but can be set to off and used in conjunction with positive apc.filters so that files are only cached if matched by a positive filter.

apc.filters string

A comma-separated list of POSIX extended regular expressions. If any pattern matches the source filename, the file will not be cached. Note that the filename used for matching is the one passed to include/require, not the absolute path. If the first character of the expression is a + then the expression will be additive in the sense that any files matched by the expression will be cached, and if the first character is a - then anything matched will not be cached. The - case is the default, so it can be left off.

apc.mmap_file_mask string

If compiled with MMAP support by using --enable-mmap this is the mktemp-style file_mask to pass to the mmap module for determining whether your mmap'ed memory region is going to be file-backed or shared memory backed. For straight file-backed mmap, set it to something like /tmp/apc.XXXXXX (exactly 6 Xs). To use POSIX-style shm_open/mmap put a .shm somewhere in your mask. e.g. /apc.shm.XXXXXX You can also set it to /dev/zero to use your kernel's /dev/zero interface to anonymous mmap'ed memory. Leaving it undefined will force an anonymous mmap.

apc.slam_defense integer

On very busy servers whenever you start the server or modify files you can create a race of many processes all trying to cache the same file at the same time. This option sets the percentage of processes that will skip trying to cache an uncached file. Or think of it as the probability of a single process to skip caching. For example, setting apc.slam_defense to 75 would mean that there is a 75% chance that the process will not cache an uncached file. So, the higher the setting the greater the defense against cache slams. Setting this to 0 disables this feature.

Deprecated by apc.write_lock.

apc.file_update_protection integer

When a file is modified on a live web server it really ought to be done in an atomic manner. That is, written to a temporary file and renamed (mv) the file into its permanent position when it is ready. Many text editors, cp, tar and other such programs don't do this. This means that there is a chance that a file is accessed (and cached) while it is still being written to. This apc.file_update_protection setting puts a delay on caching brand new files. The default is 2 seconds, which means that if the modification timestamp (mtime) on a file shows that it is less than 2 seconds old when it is accessed, it will not be cached. The unfortunate person who accessed this half-written file will still see weirdness, but at least it won't persist. If all of the webserver's files are atomically updated, via some method like rsync (which updates correctly), this protection can be disabled by setting this directive to 0. If the system is flooded with i/o and some update procedures are taking longer than 2 seconds, this setting should be increased to enable the protection on those slower update operations.

apc.enable_cli integer

Mostly for testing and debugging. Setting this enables APC for the CLI version of PHP. Under normal circumstances, it is not ideal to create, populate and destroy the APC cache on every CLI request, but for various test scenarios it is useful to be able to enable APC for the CLI version of PHP easily.

apc.max_file_size integer

Prevent files larger than this value from getting cached. Defaults to 1M.

apc.stat integer

Be careful changing this setting. This defaults to on, forcing APC to stat (check) the script on each request to determine if it has been modified. If it has been modified it will recompile and cache the new version. If this setting is off, APC will not check, which usually means that to force APC to recheck files, the web server will have to be restarted or the cache will have to be manually cleared. Note that FastCGI web server configurations may not clear the cache on restart. On a production server where the script files rarely change, a significant performance boost can be achieved by disabled stats.

For included/required files this option applies as well, but note that for relative path includes (any path that doesn't start with / on Unix) APC has to check in order to uniquely identify the file. If you use absolute path includes APC can skip the stat and use that absolute path as the unique identifier for the file.

apc.write_lock boolean

On busy servers, when the web server is first started, or when many files have been modified at the same time, APC may try to compile and cache the same file multiple times. Write_lock guarantees that only one process will attempt to compile and cache an uncached script. The other processes attempting to use the script will run without using the opcode cache, rather than locking and waiting for the cache to prime.

apc.report_autofilter boolean

Logs any scripts that were automatically excluded from being cached due to early/late binding issues.

apc.serializer string

Used to configure APC to use a third party serializer.

apc.include_once_override boolean

Optimize include_once and require_once calls and avoid the expensive system calls used.

Warning

This feature is EXPERIMENTAL. The behaviour of this directive, its name, and surrounding documentation may change without notice in a future release of APC. This feature should be used at your own risk.

apc.rfc1867 boolean

RFC1867 File Upload Progress hook handler is only available if APC was compiled against PHP 5.2.0 or later. When enabled, any file uploads which includes a field called APC_UPLOAD_PROGRESS before the file field in an upload form will cause APC to automatically create an upload_key user cache entry where key is the value of the APC_UPLOAD_PROGRESS form entry.

Note that the hidden field specified by APC_UPLOAD_PROGRESS must come before the file field, otherwise the upload progress will not work correctly.

Note that the file upload tracking is not threadsafe at this point, so new uploads that happen while a previous one is still going will disable the tracking for the previous.

Note that the rate is only available once all file transfers are completed.

Example #1 An apc.rfc1867 example

<?php
print_r(apc_fetch("upload_$_POST[APC_UPLOAD_PROGRESS]"));
?>

The above example will output something similar to:

Array
(
    [total] => 1142543
    [current] => 1142543
    [rate] => 1828068.8
    [filename] => test
    [name] => file
    [temp_filename] => /tmp/php8F
    [cancel_upload] => 0
    [done] => 1
)

apc.rfc1867_prefix string

Key prefix to use for the user cache entry generated by rfc1867 upload progress functionality.

apc.rfc1867_name string

Specify the hidden form entry name that activates APC upload progress and specifies the user cache key suffix.

apc.rfc1867_freq string

The frequency that updates should be made to the user cache entry for upload progress. This can take the form of a percentage of the total file size or a size in bytes optionally suffixed with "k", "m", or "g" for kilobytes, megabytes, or gigabytes respectively (case insensitive). A setting of 0 updates as often as possible, which may cause slower uploads.

apc.rfc1867_ttl integer

TTL for rfc1867 entries.

apc.localcache boolean

This enables a lock-free local process shadow-cache which reduces lock contention when the cache is being written to.

apc.localcache.size integer

The size of the local process shadow-cache, should be set to a sufficiently large value, approximately half of apc.num_files_hint.

apc.coredump_unmap boolean

Enables APC handling of signals, such as SIGSEGV, that write core files when signaled. When these signals are received, APC will attempt to unmap the shared memory segment in order to exclude it from the core file. This setting may improve system stability when fatal signals are received and a large APC shared memory segment is configured.

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.stat_ctime integer

Verification with ctime will avoid problems caused by programs such as svn or rsync by making sure inodes haven't changed since the last stat. APC will normally only check mtime.

apc.canonicalize bool

If on, then relative paths are canonicalized in no-stat mode. If set, then files included via stream wrappers can not be cached as realpath() does not support stream wrappers.

apc.preload_path string

Optionally, set a path to the directory that APC will load cache data at startup.

apc.use_request_time bool

Use the SAPI request start time for TTL.

apc.file_md5 bool

Records a md5 hash of files.

apc.lazy_functions integer

Enables lazy loading for functions.

apc.lazy_classes integer

Enables lazy loading for classes.


  • « Runtime Configuration
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

This extension has no resource types 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.

APC_BIN_VERIFY_CRC32 (integer)
APC_BIN_VERIFY_MD5 (integer)
APC_ITER_ALL (integer)
APC_ITER_ATIME (integer)
APC_ITER_CTIME (integer)
APC_ITER_DEVICE (integer)
APC_ITER_DTIME (integer)
APC_ITER_FILENAME (integer)
APC_ITER_INODE (integer)
APC_ITER_KEY (integer)
APC_ITER_MD5 (integer)
APC_ITER_MEM_SIZE (integer)
APC_ITER_MTIME (integer)
APC_ITER_NONE (integer)
APC_ITER_NUM_HITS (integer)
APC_ITER_REFCOUNT (integer)
APC_ITER_TTL (integer)
APC_ITER_TYPE (integer)
APC_ITER_VALUE (integer)
APC_LIST_ACTIVE (integer)
APC_LIST_DELETED (integer)


APC Functions

Table of Contents

  • apc_add — Cache a new variable in the data store
  • apc_bin_dump — Get a binary dump of the given files and user variables
  • apc_bin_dumpfile — Output a binary dump of cached files and user variables to a file
  • apc_bin_load — Load a binary dump into the APC file/user cache
  • apc_bin_loadfile — Load a binary dump from a file into the APC file/user cache
  • apc_cache_info — Retrieves cached information from APC's data store
  • apc_cas — Updates an old value with a new value
  • apc_clear_cache — Clears the APC cache
  • apc_compile_file — Stores a file in the bytecode cache, bypassing all filters
  • apc_dec — Decrease a stored number
  • apc_define_constants — Defines a set of constants for retrieval and mass-definition
  • apc_delete_file — Deletes files from the opcode cache
  • apc_delete — Removes a stored variable from the cache
  • apc_exists — Checks if APC key exists
  • apc_fetch — Fetch a stored variable from the cache
  • apc_inc — Increase a stored number
  • apc_load_constants — Loads a set of constants from the cache
  • apc_sma_info — Retrieves APC's Shared Memory Allocation information
  • apc_store — Cache a variable in the data store


Cache a new variable in the data store

  • « APC Functions
  • apc_bin_dump »
  • PHP Manual
  • APC Functions
  • Cache a new variable in the data store

apc_add

(PECL apc >= 3.0.13)

apc_add — Cache a new variable in the data store

Description

apc_add ( string $key , mixed $var [, int $ttl = 0 ] ) : bool
apc_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 apc_add() will persist between requests (until the value is removed from the cache).

Parameters

key

Store the variable using this name. keys are cache-unique, so attempting to use apc_add() to store data with a key that already exists will not overwrite the existing data, and will instead return FALSE. (This is the only difference between apc_add() and apc_store().)

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 apc_add() example

<?php
$bar = 'BAR';
apc_add('foo', $bar);
var_dump(apc_fetch('foo'));
echo "\n";
$bar = 'NEVER GETS SET';
apc_add('foo', $bar);
var_dump(apc_fetch('foo'));
echo "\n";
?>

The above example will output:

string(3) "BAR"
string(3) "BAR"

See Also

  • apc_store() - Cache a variable in the data store
  • apc_fetch() - Fetch a stored variable from the cache
  • apc_delete() - Removes a stored variable from the cache


Get a binary dump of the given files and user variables

  • « apc_add
  • apc_bin_dumpfile »
  • PHP Manual
  • APC Functions
  • Get a binary dump of the given files and user variables

apc_bin_dump

(PECL apc >= 3.1.4)

apc_bin_dump — Get a binary dump of the given files and user variables

Description

apc_bin_dump ([ array $files = NULL [, array $user_vars = NULL ]] ) : string

Returns a binary dump of the given files and user variables from the APC cache. A NULL for files or user_vars signals a dump of every entry, whereas array() will dump nothing.

Parameters

files

The files. Passing in NULL signals a dump of every entry, while passing in array() will dump nothing.

user_vars

The user vars. Passing in NULL signals a dump of every entry, while passing in array() will dump nothing.

Return Values

Returns a binary dump of the given files and user variables from the APC cache, FALSE if APC is not enabled, or NULL if an unknown error is encountered.

See Also

  • apc_bin_dumpfile() - Output a binary dump of cached files and user variables to a file
  • apc_bin_load() - Load a binary dump into the APC file/user cache


Output a binary dump of cached files and user variables to a file

  • « apc_bin_dump
  • apc_bin_load »
  • PHP Manual
  • APC Functions
  • Output a binary dump of cached files and user variables to a file

apc_bin_dumpfile

(PECL apc >= 3.1.4)

apc_bin_dumpfile — Output a binary dump of cached files and user variables to a file

Description

apc_bin_dumpfile ( array $files , array $user_vars , string $filename [, int $flags = 0 [, resource $context = NULL ]] ) : int

Outputs a binary dump of the given files and user variables from the APC cache to the named file.

Parameters

files

The file names being dumped.

user_vars

The user variables being dumped.

filename

The filename where the dump is being saved.

flags

Flags passed to the filename stream. See the file_put_contents() documentation for details.

context

The context passed to the filename stream. See the file_put_contents() documentation for details.

Return Values

The number of bytes written to the file, otherwise FALSE if APC is not enabled, filename is an invalid file name, filename can't be opened, the file dump can't be completed (e.g., the hard drive is out of disk space), or an unknown error was encountered.

See Also

  • apc_bin_dump() - Get a binary dump of the given files and user variables
  • apc_bin_load() - Load a binary dump into the APC file/user cache


Load a binary dump into the APC file/user cache

  • « apc_bin_dumpfile
  • apc_bin_loadfile »
  • PHP Manual
  • APC Functions
  • Load a binary dump into the APC file/user cache

apc_bin_load

(PECL apc >= 3.1.4)

apc_bin_load — Load a binary dump into the APC file/user cache

Description

apc_bin_load ( string $data [, int $flags = 0 ] ) : bool

Loads the given binary dump into the APC file/user cache.

Parameters

data

The binary dump being loaded, likely from apc_bin_dump().

flags

Either APC_BIN_VERIFY_CRC32, APC_BIN_VERIFY_MD5, or both.

Return Values

Returns TRUE if the binary dump data was loaded with success, otherwise FALSE is returned. FALSE is returned if APC is not enabled, or if the data is not a valid APC binary dump (e.g., unexpected size).

Examples

Example #1 apc_bin_load() example

<?php
$data = apc_bin_dump(NULL, NULL);
apc_bin_load($data, APC_BIN_VERIFY_MD5 | APC_BIN_VERIFY_CRC32);
?>

See Also

  • apc_bin_dump() - Get a binary dump of the given files and user variables
  • apc_bin_loadfile() - Load a binary dump from a file into the APC file/user cache


Load a binary dump from a file into the APC file/user cache

  • « apc_bin_load
  • apc_cache_info »
  • PHP Manual
  • APC Functions
  • Load a binary dump from a file into the APC file/user cache

apc_bin_loadfile

(PECL apc >= 3.1.4)

apc_bin_loadfile — Load a binary dump from a file into the APC file/user cache

Description

apc_bin_loadfile ( string $filename [, resource $context = NULL [, int $flags = 0 ]] ) : bool

Loads a binary dump from a file into the APC file/user cache.

Parameters

filename

The file name containing the dump, likely from apc_bin_dumpfile().

context

The files context.

flags

Either APC_BIN_VERIFY_CRC32, APC_BIN_VERIFY_MD5, or both.

Return Values

Returns TRUE on success, otherwise FALSE Reasons it may return FALSE include APC is not enabled, filename is an invalid file name or empty, filename can't be opened, the file dump can't be completed, or if the data is not a valid APC binary dump (e.g., unexpected size).

See Also

  • apc_bin_dumpfile() - Output a binary dump of cached files and user variables to a file
  • apc_bin_load() - Load a binary dump into the APC file/user cache


Retrieves cached information from APC's data store

  • « apc_bin_loadfile
  • apc_cas »
  • PHP Manual
  • APC Functions
  • Retrieves cached information from APC's data store

apc_cache_info

(PECL apc >= 2.0.0)

apc_cache_info — Retrieves cached information from APC's data store

Description

apc_cache_info ([ string $cache_type = "" [, bool $limited = FALSE ]] ) : array

Retrieves cached information and meta-data from APC's data store.

Parameters

cache_type

If cache_type is "user", information about the user cache will be returned.

If cache_type is "filehits", information about which files have been served from the bytecode cache for the current request will be returned. This feature must be enabled at compile time using --enable-filehits .

If an invalid or no cache_type is specified, information about the system cache (cached files) will be returned.

limited

If limited is TRUE, the return value will exclude the individual list of cache entries. This is useful when trying to optimize calls for statistics gathering.

Return Values

Array of cached data (and meta-data) or FALSE on failure

Note: apc_cache_info() will raise a warning if it is unable to retrieve APC cache data. This typically occurs when APC is not enabled.

Changelog

Version | Description
3.0.11 | The limited parameter was introduced.
3.0.16 | The "filehits" option for the cache_type parameter was introduced.

Examples

Example #1 A apc_cache_info() example

<?php
print_r(apc_cache_info());
?>

The above example will output something similar to:

Array
(
    [num_slots] => 2000
    [ttl] => 0
    [num_hits] => 9
    [num_misses] => 3
    [start_time] => 1123958803
    [cache_list] => Array
        (
            [0] => Array
                (
                    [filename] => /path/to/apc_test.php
                    [device] => 29954
                    [inode] => 1130511
                    [type] => file
                    [num_hits] => 1
                    [mtime] => 1123960686
                    [creation_time] => 1123960696
                    [deletion_time] => 0
                    [access_time] => 1123962864
                    [ref_count] => 1
                    [mem_size] => 677
                )
            [1] => Array (...iterates for each cached file)
)

See Also

  • APC configuration directives
  • APCIterator::getTotalSize() - Get total cache size
  • APCIterator::getTotalHits() - Get total cache hits
  • APCIterator::getTotalCount() - Get total count


Updates an old value with a new value

  • « apc_cache_info
  • apc_clear_cache »
  • PHP Manual
  • APC Functions
  • Updates an old value with a new value

apc_cas

(PECL apc >= 3.1.1)

apc_cas — Updates an old value with a new value

Description

apc_cas ( string $key , int $old , int $new ) : bool

apc_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 apc_cas() example

<?php
apc_store('foobar', 2);
echo '$foobar = 2', PHP_EOL;
echo '$foobar == 1 ? 2 : 1 = ', (apc_cas('foobar', 1, 2) ? 'ok' : 'fail'), PHP_EOL;
echo '$foobar == 2 ? 1 : 2 = ', (apc_cas('foobar', 2, 1) ? 'ok' : 'fail'), PHP_EOL;

echo '$foobar = ', apc_fetch('foobar'), PHP_EOL;

echo '$f__bar == 1 ? 2 : 1 = ', (apc_cas('f__bar', 1, 2) ? 'ok' : 'fail'), PHP_EOL;

apc_store('perfection', 'xyz');
echo '$perfection == 2 ? 1 : 2 = ', (apc_cas('perfection', 2, 1) ? 'ok' : 'epic fail'), PHP_EOL;

echo '$foobar = ', apc_fetch('foobar'), PHP_EOL;
?>

The above example will output something similar to:

$foobar = 2
$foobar == 1 ? 2 : 1 = fail
$foobar == 2 ? 1 : 2 = ok
$foobar = 1
$f__bar == 1 ? 2 : 1 = fail
$perfection == 2 ? 1 : 2 = epic fail
$foobar = 1

See Also

  • apc_dec() - Decrease a stored number
  • apc_store() - Cache a variable in the data store


Clears the APC cache

  • « apc_cas
  • apc_compile_file »
  • PHP Manual
  • APC Functions
  • Clears the APC cache

apc_clear_cache

(PECL apc >= 2.0.0)

apc_clear_cache — Clears the APC cache

Description

apc_clear_cache ([ string $cache_type = "" ] ) : bool

Clears the user/system cache.

Parameters

cache_type

If cache_type is "user", the user cache will be cleared; otherwise, the system cache (cached files) will be cleared.

Return Values

Returns TRUE always

See Also

  • apc_cache_info() - Retrieves cached information from APC's data store


Stores a file in the bytecode cache, bypassing all filters

  • « apc_clear_cache
  • apc_dec »
  • PHP Manual
  • APC Functions
  • Stores a file in the bytecode cache, bypassing all filters

apc_compile_file

(PECL apc >= 3.0.13)

apc_compile_file — Stores a file in the bytecode cache, bypassing all filters

Description

apc_compile_file ( string $filename [, bool $atomic = TRUE ] ) : mixed

Stores a file in the bytecode cache, bypassing all filters.

Parameters

filename

Full or relative path to a PHP file that will be compiled and stored in the bytecode cache.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • apc_bin_dumpfile() - Output a binary dump of cached files and user variables to a file
  • apc_bin_loadfile() - Load a binary dump from a file into the APC file/user cache


Decrease a stored number

  • « apc_compile_file
  • apc_define_constants »
  • PHP Manual
  • APC Functions
  • Decrease a stored number

apc_dec

(PECL apc >= 3.1.1)

apc_dec — Decrease a stored number

Description

apc_dec ( string $key [, int $step = 1 [, bool &$success ]] ) : int

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.

Return Values

Returns the current value of key's value on success, or FALSE on failure

Examples

Example #1 apc_dec() example

<?php
echo "Let's do something with success", PHP_EOL;

apc_store('anumber', 42);

echo apc_fetch('anumber'), PHP_EOL;

echo apc_dec('anumber'), PHP_EOL;
echo apc_dec('anumber', 10), PHP_EOL;
echo apc_dec('anumber', 10, $success), PHP_EOL;

var_dump($success);

echo "Now, let's fail", PHP_EOL, PHP_EOL;

apc_store('astring', 'foo');

$ret = apc_dec('astring', 1, $fail);

var_dump($ret);
var_dump($fail);
?>

The above example will output something similar to:

Let's do something with success
42
41
31
21
bool(true)

Now, let's fail
bool(false)
bool(false)

See Also

  • apc_inc() - Increase a stored number


Defines a set of constants for retrieval and mass-definition

  • « apc_dec
  • apc_delete_file »
  • PHP Manual
  • APC Functions
  • Defines a set of constants for retrieval and mass-definition

apc_define_constants

(PECL apc >= 3.0.0)

apc_define_constants — Defines a set of constants for retrieval and mass-definition

Description

apc_define_constants ( string $key , array $constants [, bool $case_sensitive = TRUE ] ) : bool

define() is notoriously slow. Since the main benefit of APC is to increase the performance of scripts/applications, this mechanism is provided to streamline the process of mass constant definition. However, this function does not perform as well as anticipated.

For a better-performing solution, try the » hidef extension from PECL.

Note: To remove a set of stored constants (without clearing the entire cache), an empty array may be passed as the constants parameter, effectively clearing the stored value(s).

Parameters

key

The key serves as the name of the constant set being stored. This key is used to retrieve the stored constants in apc_load_constants().

constants

An associative array of constant_name => value pairs. The constant_name must follow the normal constant naming rules. value must evaluate to a scalar value.

case_sensitive

The default behaviour for constants is to be declared case-sensitive; i.e. CONSTANT and Constant represent different values. If this parameter evaluates to FALSE the constants will be declared as case-insensitive symbols.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 apc_define_constants() example

<?php
$constants = array(
    'ONE'   => 1,
    'TWO'   => 2,
    'THREE' => 3,
);
apc_define_constants('numbers', $constants);
echo ONE, TWO, THREE;
?>

The above example will output:

123

See Also

  • apc_load_constants() - Loads a set of constants from the cache
  • define() - Defines a named constant
  • constant() - Returns the value of a constant
  • Or the PHP constants reference


Deletes files from the opcode cache

  • « apc_define_constants
  • apc_delete »
  • PHP Manual
  • APC Functions
  • Deletes files from the opcode cache

apc_delete_file

(PECL apc >= 3.1.1)

apc_delete_file — Deletes files from the opcode cache

Description

apc_delete_file ( mixed $keys ) : mixed

Deletes the given files from the opcode cache.

Parameters

keys

The files to be deleted. Accepts a string, array of strings, or an APCIterator object.

Return Values

Returns TRUE on success or FALSE on failure. Or if keys is an array, then an empty array is returned on success, or an array of failed files is returned.

Examples

Example #1 apc_delete_file() example

<?php
$filename = 'file.php';

if (apc_compile_file($filename)) {

    if (apc_delete_file($filename)) {
        echo "Successfully deleted file $filename from APC cache.", PHP_EOL;
    }
}

if (apc_compile_file($filename)) {

    if ($good = apc_delete_file(array($filename, 'donotexist.php'))) {
        var_dump($good);
    }
}

$bad = apc_delete_file('donotexist.php');
var_dump($bad);
?>

The above example will output something similar to:

Successfully deleted file file.php from APC cache.
[Mon May 24 09:30:33 2010] [apc-warning] Could not stat file donotexist.php, unable to delete from cache. in /tmp/test.php on line 13.
array(1) {
  [0]=>
  string(14) "donotexist.php"
}
[Mon May 24 09:30:33 2010] [apc-warning] Could not stat file donotexist.php, unable to delete from cache. in /tmp/test.php on line 18.
bool(false)

See Also

  • apc_clear_cache() - Clears the APC cache
  • apc_delete() - Removes a stored variable from the cache
  • apc_exists() - Checks if APC key exists


Removes a stored variable from the cache

  • « apc_delete_file
  • apc_exists »
  • PHP Manual
  • APC Functions
  • Removes a stored variable from the cache

apc_delete

(PECL apc >= 3.0.0)

apc_delete — Removes a stored variable from the cache

Description

apc_delete ( string $key ) : mixed

Removes a stored variable from the cache.

Parameters

key

The key used to store the value (with apc_store()).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A apc_delete() example

<?php
$bar = 'BAR';
apc_store('foo', $bar);
apc_delete('foo');
// this is obviously useless in this form
?>

See Also

  • apc_store() - Cache a variable in the data store
  • apc_fetch() - Fetch a stored variable from the cache


Checks if APC key exists

  • « apc_delete
  • apc_fetch »
  • PHP Manual
  • APC Functions
  • Checks if APC key exists

apc_exists

(PECL apc >= 3.1.4)

apc_exists — Checks if APC key exists

Description

apc_exists ( mixed $keys ) : mixed

Checks if one or more APC keys 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 apc_exists() example

<?php
$fruit  = 'apple';
$veggie = 'carrot';

apc_store('foo', $fruit);
apc_store('bar', $veggie);

if (apc_exists('foo')) {
    echo "Foo exists: ";
    echo apc_fetch('foo');
} else {
    echo "Foo does not exist";
}

echo PHP_EOL;
if (apc_exists('baz')) {
    echo "Baz exists.";
} else {
    echo "Baz does not exist";
}

echo PHP_EOL;

$ret = apc_exists(array('foo', 'donotexist', 'bar'));
var_dump($ret);

?>

The above example will output something similar to:

Foo exists: apple
Baz does not exist
array(2) {
  ["foo"]=>
  bool(true)
  ["bar"]=>
  bool(true)
}

See Also

  • apc_cache_info() - Retrieves cached information from APC's data store
  • apc_fetch() - Fetch a stored variable from the cache


Fetch a stored variable from the cache

  • « apc_exists
  • apc_inc »
  • PHP Manual
  • APC Functions
  • Fetch a stored variable from the cache

apc_fetch

(PECL apc >= 3.0.0)

apc_fetch — Fetch a stored variable from the cache

Description

apc_fetch ( mixed $key [, bool &$success ] ) : mixed

Fetchs a stored variable from the cache.

Parameters

key

The key used to store the value (with apc_store()). If an array is passed then each element is fetched and returned.

success

Set to TRUE in success and FALSE in failure.

Return Values

The stored variable or array of variables on success; FALSE on failure

Examples

Example #1 A apc_fetch() example

<?php
$bar = 'BAR';
apc_store('foo', $bar);
var_dump(apc_fetch('foo'));
?>

The above example will output:

string(3) "BAR"

Changelog

Version | Description
3.0.17 | The success parameter was added.

See Also

  • apc_store() - Cache a variable in the data store
  • apc_delete() - Removes a stored variable from the cache
  • APCIterator


Increase a stored number

  • « apc_fetch
  • apc_load_constants »
  • PHP Manual
  • APC Functions
  • Increase a stored number

apc_inc

(PECL apc >= 3.1.1)

apc_inc — Increase a stored number

Description

apc_inc ( string $key [, int $step = 1 [, bool &$success ]] ) : int

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.

Return Values

Returns the current value of key's value on success, or FALSE on failure

Examples

Example #1 apc_inc() example

<?php
echo "Let's do something with success", PHP_EOL;

apc_store('anumber', 42);

echo apc_fetch('anumber'), PHP_EOL;

echo apc_inc('anumber'), PHP_EOL;
echo apc_inc('anumber', 10), PHP_EOL;
echo apc_inc('anumber', 10, $success), PHP_EOL;

var_dump($success);

echo "Now, let's fail", PHP_EOL, PHP_EOL;

apc_store('astring', 'foo');

$ret = apc_inc('astring', 1, $fail);

var_dump($ret);
var_dump($fail);
?>

The above example will output something similar to:

42
43
53
63
bool(true)
Now, let's fail

bool(false)
bool(false)

See Also

  • apc_dec() - Decrease a stored number


Loads a set of constants from the cache

  • « apc_inc
  • apc_sma_info »
  • PHP Manual
  • APC Functions
  • Loads a set of constants from the cache

apc_load_constants

(PECL apc >= 3.0.0)

apc_load_constants — Loads a set of constants from the cache

Description

apc_load_constants ( string $key [, bool $case_sensitive = TRUE ] ) : bool

Loads a set of constants from the cache.

Parameters

key

The name of the constant set (that was stored with apc_define_constants()) to be retrieved.

case_sensitive

The default behaviour for constants is to be declared case-sensitive; i.e. CONSTANT and Constant represent different values. If this parameter evaluates to FALSE the constants will be declared as case-insensitive symbols.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 apc_load_constants() example

<?php
$constants = array(
    'ONE'   => 1,
    'TWO'   => 2,
    'THREE' => 3,
);
apc_define_constants('numbers', $constants);
apc_load_constants('numbers');
echo ONE, TWO, THREE;
?>

The above example will output:

123

See Also

  • apc_define_constants() - Defines a set of constants for retrieval and mass-definition
  • define() - Defines a named constant
  • constant() - Returns the value of a constant
  • Or the PHP constants reference


Retrieves APC's Shared Memory Allocation information

  • « apc_load_constants
  • apc_store »
  • PHP Manual
  • APC Functions
  • Retrieves APC's Shared Memory Allocation information

apc_sma_info

(PECL apc >= 2.0.0)

apc_sma_info — Retrieves APC's Shared Memory Allocation information

Description

apc_sma_info ([ bool $limited = FALSE ] ) : array

Retrieves APC's Shared Memory Allocation information.

Parameters

limited

When set to FALSE (default) apc_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 apc_sma_info() example

<?php
print_r(apc_sma_info());
?>

The above example will output something similar to:

Array
(
    [num_seg] => 1
    [seg_size] => 31457280
    [avail_mem] => 31448408
    [block_lists] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [size] => 31448408
                            [offset] => 8864
                        )

                )

        )

)

See Also

  • APC configuration directives


Cache a variable in the data store

  • « apc_sma_info
  • APCIterator »
  • PHP Manual
  • APC Functions
  • Cache a variable in the data store

apc_store

(PECL apc >= 3.0.0)

apc_store — Cache a variable in the data store

Description

apc_store ( string $key , mixed $var [, int $ttl = 0 ] ) : bool
apc_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 apc_store() will persist between requests (until the value is removed from the cache).

Parameters

key

Store the variable using this name. keys are cache-unique, so storing a second value with the same key will overwrite the original value.

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 apc_store() example

<?php
$bar = 'BAR';
apc_store('foo', $bar);
var_dump(apc_fetch('foo'));
?>

The above example will output:

string(3) "BAR"

See Also

  • apc_add() - Cache a new variable in the data store
  • apc_fetch() - Fetch a stored variable from the cache
  • apc_delete() - Removes a stored variable from the cache


The APCIterator class

(PECL apc >= 3.1.1)

Introduction

The APCIterator class makes it easier to iterate over large APC caches. This is helpful as it allows iterating over large caches in steps, while grabbing a defined number of entries per lock instance, so it frees the cache locks for other activities rather than hold up the entire cache to grab 100 (the default) entries. Also, using regular expression matching is more efficient as it's been moved to the C level.

Class synopsis

APCIterator implements Iterator {
/* Methods */
public __construct ( string $cache [, mixed $search = NULL [, int $format = APC_ITER_ALL [, int $chunk_size = 100 [, int $list = APC_LIST_ACTIVE ]]]] )
public current ( void ) : mixed
public getTotalCount ( void ) : int
public getTotalHits ( void ) : int
public getTotalSize ( void ) : int
public key ( void ) : string
public next ( void ) : bool
public rewind ( void ) : void
public valid ( void ) : bool
}

Table of Contents

  • APCIterator::__construct — Constructs an APCIterator iterator object
  • APCIterator::current — Get current item
  • APCIterator::getTotalCount — Get total count
  • APCIterator::getTotalHits — Get total cache hits
  • APCIterator::getTotalSize — Get total cache size
  • APCIterator::key — Get iterator key
  • APCIterator::next — Move pointer to next item
  • APCIterator::rewind — Rewinds iterator
  • APCIterator::valid — Checks if current position is valid


Constructs an APCIterator iterator object

  • « APCIterator
  • APCIterator::current »
  • PHP Manual
  • APCIterator
  • Constructs an APCIterator iterator object

APCIterator::__construct

(PECL apc >= 3.1.1)

APCIterator::__construct — Constructs an APCIterator iterator object

Description

public APCIterator::__construct ( string $cache [, mixed $search = NULL [, int $format = APC_ITER_ALL [, int $chunk_size = 100 [, int $list = APC_LIST_ACTIVE ]]]] )

Constructs an APCIterator object.

Parameters

cache

The cache type, which will be user or file.

search

A PCRE regular expression that matches against APC key names, either as a string for a single regular expression, or as an array of regular expressions. Or, optionally pass in NULL to skip the search.

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.

Return Values

An APCIterator object on success, or NULL on failure.

Examples

Example #1 A APCIterator::__construct() example

<?php
foreach (new APCIterator('user', '/^counter\./') as $counter) {
    echo "$counter[key]: $counter[value]\n";
    apc_dec($counter['key'], $counter['value']);
}
?>

See Also

  • apc_exists() - Checks if APC key exists
  • apc_cache_info() - Retrieves cached information from APC's data store


Get current item

  • « APCIterator::__construct
  • APCIterator::getTotalCount »
  • PHP Manual
  • APCIterator
  • Get current item

APCIterator::current

(PECL apc >= 3.1.1)

APCIterator::current — Get current item

Description

public APCIterator::current ( void ) : mixed

Gets the current item from the APCIterator 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

  • APCIterator::next() - Move pointer to next item
  • Iterator::current() - Return the current element


Get total count

  • « APCIterator::current
  • APCIterator::getTotalHits »
  • PHP Manual
  • APCIterator
  • Get total count

APCIterator::getTotalCount

(PECL apc >= 3.1.1)

APCIterator::getTotalCount — Get total count

Description

public APCIterator::getTotalCount ( void ) : 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

  • APCIterator::getTotalHits() - Get total cache hits
  • APCIterator::getTotalSize() - Get total cache size
  • apc_cache_info() - Retrieves cached information from APC's data store


Get total cache hits

  • « APCIterator::getTotalCount
  • APCIterator::getTotalSize »
  • PHP Manual
  • APCIterator
  • Get total cache hits

APCIterator::getTotalHits

(PECL apc >= 3.1.1)

APCIterator::getTotalHits — Get total cache hits

Description

public APCIterator::getTotalHits ( void ) : 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

  • APCIterator::getTotalCount() - Get total count
  • APCIterator::getTotalSize() - Get total cache size
  • apc_cache_info() - Retrieves cached information from APC's data store


Get total cache size

  • « APCIterator::getTotalHits
  • APCIterator::key »
  • PHP Manual
  • APCIterator
  • Get total cache size

APCIterator::getTotalSize

(PECL apc >= 3.1.1)

APCIterator::getTotalSize — Get total cache size

Description

public APCIterator::getTotalSize ( void ) : 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

  • APCIterator::getTotalCount() - Get total count
  • APCIterator::getTotalHits() - Get total cache hits
  • apc_cache_info() - Retrieves cached information from APC's data store


Get iterator key

  • « APCIterator::getTotalSize
  • APCIterator::next »
  • PHP Manual
  • APCIterator
  • Get iterator key

APCIterator::key

(PECL apc >= 3.1.1)

APCIterator::key — Get iterator key

Description

public APCIterator::key ( void ) : 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

  • APCIterator::current() - Get current item
  • Iterator::key() - Return the key of the current element


Move pointer to next item

  • « APCIterator::key
  • APCIterator::rewind »
  • PHP Manual
  • APCIterator
  • Move pointer to next item

APCIterator::next

(PECL apc >= 3.1.1)

APCIterator::next — Move pointer to next item

Description

public APCIterator::next ( void ) : 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

  • APCIterator::current() - Get current item
  • APCIterator::rewind() - Rewinds iterator
  • Iterator::next() - Move forward to next element


Rewinds iterator

  • « APCIterator::next
  • APCIterator::valid »
  • PHP Manual
  • APCIterator
  • Rewinds iterator

APCIterator::rewind

(PECL apc >= 3.1.1)

APCIterator::rewind — Rewinds iterator

Description

public APCIterator::rewind ( void ) : void

Rewinds back the iterator to the first element.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • APCIterator::next() - Move pointer to next item
  • Iterator::next() - Move forward to next element


Checks if current position is valid

  • « APCIterator::rewind
  • APCu »
  • PHP Manual
  • APCIterator
  • Checks if current position is valid

APCIterator::valid

(PECL apc >= 3.1.1)

APCIterator::valid — Checks if current position is valid

Description

public APCIterator::valid ( void ) : 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

  • APCIterator::current() - Get current item
  • Iterator::valid() - Checks if current position is valid


APC User Cache

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • 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_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_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


Introduction

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.

APCu can provide a compatibility mode, such that it can provide a drop in replacement for the applicable parts of APC.


Installation

If backward compatibility with the applicable parts of APC is required, APCu must be configured with the option --enable-apcu-bc.

Warning

PHP 7 has a separate module (» apc.so) 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.

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 forcefully clean any entries that haven't been accessed in the last apc.ttl seconds. This number is minimized in a well-configured cache. If the cache is constantly being filled, and thusly forcefully freed, the resulting churning will have disparaging effects on script performance. The easiest way to minimize this number is to allocate more memory for 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 recommeded 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" | PHP_INI_SYSTEM |
apc.shm_segments | "1" | PHP_INI_SYSTEM |
apc.shm_size | "32M" | PHP_INI_SYSTEM |
apc.entries_hint | "4096" | PHP_INI_SYSTEM |
apc.ttl | "0" | PHP_INI_SYSTEM |
apc.gc_ttl | "3600" | PHP_INI_SYSTEM |
apc.mmap_file_mask | NULL | PHP_INI_SYSTEM |
apc.slam_defense | "1" | PHP_INI_SYSTEM |
apc.enable_cli | "0" | PHP_INI_SYSTEM |
apc.use_request_time | "1" | PHP_INI_ALL |
apc.serializer | "default" | PHP_INI_SYSTEM |
apc.coredump_unmap | "0" | PHP_INI_SYSTEM |
apc.preload_path | NULL | PHP_INI_SYSTEM |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

apc.enabled boolean

apc.enabled can be set to 0 to disable APC. This is primarily useful when APC is statically compiled into PHP, since there is no other way to disable it (when compiled as a DSO, the extension line in php.ini can just be commented-out).

apc.shm_segments integer

The number of shared memory segments to allocate for the compiler cache. If APC is running out of shared memory but apc.shm_size is set as high as the system allows, raising this value might prevent APC from exhausting its memory.

apc.shm_size 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 integer

A "hint" about the number of distinct variables that might be stored. Set to zero or omit if not sure.

apc.ttl integer

The number of seconds a cache entry is allowed to idle in a slot in case this cache entry slot is needed by another entry. Leaving this at zero means that APC's cache could potentially fill up with stale entries while newer entries won't be cached. In the event of a cache running out of available memory, the cache will be completely expunged if ttl is equal to 0. Otherwise, if the ttl is greater than 0, APC will attempt to remove expired entries.

apc.gc_ttl integer

The number of seconds that a cache entry may remain on the garbage-collection list. This value provides a fail-safe in the event that a server process dies while executing a cached source file; if that source file is modified, the memory allocated for the old version will not be reclaimed until this TTL reached. Set to zero to disable this feature.

apc.mmap_file_mask string

If compiled with MMAP support by using --enable-mmap this is the mktemp-style file_mask to pass to the mmap module for determining whether your mmap'ed memory region is going to be file-backed or shared memory backed. For straight file-backed mmap, set it to something like /tmp/apc.XXXXXX (exactly 6 Xs). To use POSIX-style shm_open/mmap put a .shm somewhere in your mask. e.g. /apc.shm.XXXXXX You can also set it to /dev/zero to use your kernel's /dev/zero interface to anonymous mmap'ed memory. Leaving it undefined will force an anonymous mmap.

apc.slam_defense integer

On very busy servers whenever you start the server or modify files you can create a race of many processes all trying to cache the same file at the same time. This option sets the percentage of processes that will skip trying to cache an uncached file. Or think of it as the probability of a single process to skip caching. For example, setting apc.slam_defense to 75 would mean that there is a 75% chance that the process will not cache an uncached file. So, the higher the setting the greater the defense against cache slams. Setting this to 0 disables this feature.

apc.enable_cli integer

Mostly for testing and debugging. Setting this enables APC for the CLI version of PHP. Under normal circumstances, it is not ideal to create, populate and destroy the APC cache on every CLI request, but for various test scenarios it is useful to be able to enable APC for the CLI version of PHP easily.

apc.serializer string

Used to configure APC to use a third party serializer.

apc.coredump_unmap boolean

Enables APC handling of signals, such as SIGSEGV, that write core files when signaled. When these signals are received, APC will attempt to unmap the shared memory segment in order to exclude it from the core file. This setting may improve system stability when fatal signals are received and a large APC shared memory segment is configured.

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 (integer)
APC_ITER_ATIME (integer)
APC_ITER_CTIME (integer)
APC_ITER_DEVICE (integer)
APC_ITER_DTIME (integer)
APC_ITER_FILENAME (integer)
APC_ITER_INODE (integer)
APC_ITER_KEY (integer)
APC_ITER_MD5 (integer)
APC_ITER_MEM_SIZE (integer)
APC_ITER_MTIME (integer)
APC_ITER_NONE (integer)
APC_ITER_NUM_HITS (integer)
APC_ITER_REFCOUNT (integer)
APC_ITER_TTL (integer)
APC_ITER_TYPE (integer)
APC_ITER_VALUE (integer)
APC_LIST_ACTIVE (integer)
APC_LIST_DELETED (integer)


APCu Functions

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_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_sma_info — Retrieves APCu Shared Memory Allocation information
  • apcu_store — Cache a variable in the data store


Cache a new variable in the data store

  • « APCu Functions
  • apcu_cache_info »
  • PHP Manual
  • APCu Functions
  • Cache a new variable in the data store

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


Retrieves cached information from APCu's data store

  • « apcu_add
  • apcu_cas »
  • PHP Manual
  • APCu Functions
  • Retrieves cached information from APCu's data store

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

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
3.0.11 | The limited parameter was introduced.
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


Updates an old value with a new value

  • « apcu_cache_info
  • apcu_clear_cache »
  • PHP Manual
  • APCu Functions
  • Updates an old value with a new value

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


Clears the APCu cache

  • « apcu_cas
  • apcu_dec »
  • PHP Manual
  • APCu Functions
  • Clears the APCu cache

apcu_clear_cache

(PECL apcu >= 4.0.0)

apcu_clear_cache — Clears the APCu cache

Description

apcu_clear_cache ( void ) : 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


Decrease a stored number

  • « apcu_clear_cache
  • apcu_delete »
  • PHP Manual
  • APCu Functions
  • Decrease a stored number

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

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

Changelog

Version | Description
5.1.12 | The ttl parameter has been added.

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


Removes a stored variable from the cache

  • « apcu_dec
  • apcu_entry »
  • PHP Manual
  • APCu Functions
  • Removes a stored variable from the cache

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


Atomically fetch or generate a cache entry

  • « apcu_delete
  • apcu_exists »
  • PHP Manual
  • APCu Functions
  • Atomically fetch or generate a cache entry

apcu_entry

(PECL apcu >= 5.1.0)

apcu_entry — Atomically fetch or generate a cache entry

Description

apcu_entry ( string $key , callable $generator [, int $ttl = 0 ] ) : mixed

Atomically attempts to find key in the cache, if it cannot be found generator 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 generator 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 generator is apcu_entry().

Parameters

key

Identity of cache entry

generator

A callable that accepts key as the only argument and returns the value to cache.

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

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


Checks if entry exists

  • « apcu_entry
  • apcu_fetch »
  • PHP Manual
  • APCu Functions
  • Checks if entry exists

apcu_exists

(PECL apcu >= 4.0.0)

apcu_exists — Checks if entry exists

Description

apcu_exists ( mixed $keys ) : mixed

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


Fetch a stored variable from the cache

  • « apcu_exists
  • apcu_inc »
  • PHP Manual
  • APCu Functions
  • 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

Fetchs 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

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"

Changelog

Version | Description
3.0.17 | The success parameter was added.

See Also

  • apcu_store() - Cache a variable in the data store
  • apcu_delete() - Removes a stored variable from the cache
  • APCUIterator


Increase a stored number

  • « apcu_fetch
  • apcu_sma_info »
  • PHP Manual
  • APCu Functions
  • Increase a stored number

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

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

Changelog

Version | Description
5.1.12 | The ttl parameter has been added.

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


Retrieves APCu Shared Memory Allocation information

  • « apcu_inc
  • apcu_store »
  • PHP Manual
  • APCu Functions
  • Retrieves APCu Shared Memory Allocation information

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

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


Cache a variable in the data store

  • « apcu_sma_info
  • APCUIterator »
  • PHP Manual
  • APCu Functions
  • Cache a variable in the data store

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


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

APCUIterator implements Iterator {
/* Methods */
public __construct ([ mixed $search = NULL [, int $format = APC_ITER_ALL [, int $chunk_size = 100 [, int $list = APC_LIST_ACTIVE ]]]] )
public current ( void ) : mixed
public getTotalCount ( void ) : int
public getTotalHits ( void ) : int
public getTotalSize ( void ) : int
public key ( void ) : string
public next ( void ) : bool
public rewind ( void ) : void
public valid ( void ) : bool
}

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


Constructs an APCUIterator iterator object

  • « APCUIterator
  • APCUIterator::current »
  • PHP Manual
  • APCUIterator
  • Constructs an APCUIterator iterator object

APCUIterator::__construct

(PECL apcu >= 5.0.0)

APCUIterator::__construct — Constructs an APCUIterator iterator object

Description

public APCUIterator::__construct ([ mixed $search = NULL [, int $format = APC_ITER_ALL [, int $chunk_size = 100 [, int $list = APC_LIST_ACTIVE ]]]] )

Constructs an APCUIterator object.

Parameters

search

A PCRE regular expression that matches against APCu key names, either as a string for a single regular expression, or as an array of regular expressions. Or, optionally pass in NULL to skip the search.

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.

Return Values

An APCUIterator object on success, or NULL on failure.

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


Get current item

  • « APCUIterator::__construct
  • APCUIterator::getTotalCount »
  • PHP Manual
  • APCUIterator
  • Get current item

APCUIterator::current

(PECL apcu >= 5.0.0)

APCUIterator::current — Get current item

Description

public APCUIterator::current ( void ) : 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


Get total count

  • « APCUIterator::current
  • APCUIterator::getTotalHits »
  • PHP Manual
  • APCUIterator
  • Get total count

APCUIterator::getTotalCount

(PECL apcu >= 5.0.0)

APCUIterator::getTotalCount — Get total count

Description

public APCUIterator::getTotalCount ( void ) : 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


Get total cache hits

  • « APCUIterator::getTotalCount
  • APCUIterator::getTotalSize »
  • PHP Manual
  • APCUIterator
  • Get total cache hits

APCUIterator::getTotalHits

(PECL apcu >= 5.0.0)

APCUIterator::getTotalHits — Get total cache hits

Description

public APCUIterator::getTotalHits ( void ) : 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


Get total cache size

  • « APCUIterator::getTotalHits
  • APCUIterator::key »
  • PHP Manual
  • APCUIterator
  • Get total cache size

APCUIterator::getTotalSize

(PECL apcu >= 5.0.0)

APCUIterator::getTotalSize — Get total cache size

Description

public APCUIterator::getTotalSize ( void ) : 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() - Retrieves cached information from APC's data store


Get iterator key

  • « APCUIterator::getTotalSize
  • APCUIterator::next »
  • PHP Manual
  • APCUIterator
  • Get iterator key

APCUIterator::key

(PECL apcu >= 5.0.0)

APCUIterator::key — Get iterator key

Description

public APCUIterator::key ( void ) : 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


Move pointer to next item

  • « APCUIterator::key
  • APCUIterator::rewind »
  • PHP Manual
  • APCUIterator
  • Move pointer to next item

APCUIterator::next

(PECL apcu >= 5.0.0)

APCUIterator::next — Move pointer to next item

Description

public APCUIterator::next ( void ) : 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


Rewinds iterator

  • « APCUIterator::next
  • APCUIterator::valid »
  • PHP Manual
  • APCUIterator
  • Rewinds iterator

APCUIterator::rewind

(PECL apcu >= 5.0.0)

APCUIterator::rewind — Rewinds iterator

Description

public APCUIterator::rewind ( void ) : 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


Checks if current position is valid

  • « APCUIterator::rewind
  • APD »
  • PHP Manual
  • APCUIterator
  • Checks if current position is valid

APCUIterator::valid

(PECL apcu >= 5.0.0)

APCUIterator::valid — Checks if current position is valid

Description

public APCUIterator::valid ( void ) : 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


Advanced PHP debugger

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Building on Win32
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • How to use PHP-APD in your scripts
  • APD Functions
    • apd_breakpoint — Stops the interpreter and waits on a CR from the socket
    • apd_callstack — Returns the current call stack as an array
    • apd_clunk — Throw a warning and a callstack
    • apd_continue — Restarts the interpreter
    • apd_croak — Throw an error, a callstack and then exit
    • apd_dump_function_table — Outputs the current function table
    • apd_dump_persistent_resources — Return all persistent resources as an array
    • apd_dump_regular_resources — Return all current regular resources as an array
    • apd_echo — Echo to the debugging socket
    • apd_get_active_symbols — Get an array of the current variables names in the local scope
    • apd_set_pprof_trace — Starts the session debugging
    • apd_set_session_trace_socket — Starts the remote session debugging
    • apd_set_session_trace — Starts the session debugging
    • apd_set_session — Changes or sets the current debugging level
    • override_function — Overrides built-in functions
    • rename_function — Renames orig_name to new_name in the global function table


Introduction

APD is the Advanced PHP Debugger. It was written to provide profiling and debugging capabilities for PHP code, as well as to provide the ability to print out a full stack backtrace. APD supports interactive debugging, but by default it writes data to trace files. It also offers event based logging so that varying levels of information (including function calls, arguments passed, timings, etc.) can be turned on or off for individual scripts.

Caution

APD is a Zend Extension, modifying the way the internals of PHP handle function calls, and thus may or may not be compatible with other Zend Extensions (for example Zend Optimizer).


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Building on Win32
  • Runtime Configuration
  • 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/apd.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

In your INI file, add the following lines:

zend_extension = /absolute/path/to/apd.so
apd.dumpdir = /absolute/path/to/trace/directory
apd.statement_tracing = 0

Depending on your PHP build, the zend_extension directive can be one of the following:

zend_extension              (non ZTS, non debug build)
zend_extension_ts           (    ZTS, non debug build)
zend_extension_debug        (non ZTS,     debug build)
zend_extension_debug_ts     (    ZTS,     debug build)


Building on Win32

To build APD under Windows you need a working PHP compilation environment as described on http://php.net/ -- basically, it requires you to have Microsoft Visual C++, win32build.zip, bison/flex, and some know how to get it to work. Also ensure that adp.dsp has DOS line endings; if it has unix line endings, Microsoft Visual C++ will complain about it.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

APD Configuration Options
Name | Default | Changeable | Changelog
apd.dumpdir | NULL | PHP_INI_ALL |
apd.statement_tracing | "0" | PHP_INI_ALL | Available since apd 0.9.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

apd.dumpdir string

Sets the directory in which APD writes profile dump files. You can specify an absolute path or a relative path.

You can specify a different directory as an argument to apd_set_pprof_trace().

apd.statement_tracing boolean

Specfies whether or not to do per-line tracings. Turning this on (1) will impact the performance of your application.


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.

APD constants
Constant | Value | Description
FUNCTION_TRACE (integer) | 1 |
ARGS_TRACE (integer) | 2 |
ASSIGNMENT_TRACE (integer) | 4 |
STATEMENT_TRACE (integer) | 8 |
MEMORY_TRACE (integer) | 16 |
TIMING_TRACE (integer) | 32 |
SUMMARY_TRACE (integer) | 64 |
ERROR_TRACE (integer) | 128 |
PROF_TRACE (integer) | 256 |
APD_VERSION (string) | example: 1.0.2-dev |


  • « Predefined Constants
  • How to use PHP-APD in your scripts »
  • PHP Manual
  • APD
  • Examples

Examples

Table of Contents

  • How to use PHP-APD in your scripts


How to use PHP-APD in your scripts

  1. As the first line of your PHP script, call the apd_set_pprof_trace() function to start the trace:

    <?php
    apd_set_pprof_trace    ();
    ?>

    You can insert the line anywhere in your script, but if you do not start tracing at the beginning of your script you discard profile data that might otherwise lead you to a performance bottleneck.

  2. Now run your script. The dump output will be written to apd.dumpdir/pprof_pid.ext.

    Tip

    If you're running the CGI version of PHP, you will need to add the '-e' flag to enable extended information for apd to work properly. For example: php -e -f script.php

  3. To display formatted profile data, issue the pprofp command with the sort and display options of your choice. The formatted output will look something like:

    bash-2.05b$ pprofp -R /tmp/pprof.22141.0

Trace for /home/dan/testapd.php
Total Elapsed Time = 0.00
Total System Time  = 0.00
Total User Time    = 0.00

Real         User        System             secs/    cumm
%Time (excl/cumm)  (excl/cumm)  (excl/cumm) Calls    call    s/call  Memory Usage Name
--------------------------------------------------------------------------------------
100.0 0.00 0.00  0.00 0.00  0.00 0.00     1  0.0000   0.0009            0 main
56.9 0.00 0.00  0.00 0.00  0.00 0.00     1  0.0005   0.0005            0 apd_set_pprof_trace
28.0 0.00 0.00  0.00 0.00  0.00 0.00    10  0.0000   0.0000            0 preg_replace
14.3 0.00 0.00  0.00 0.00  0.00 0.00    10  0.0000   0.0000            0 str_replace

    The -R option used in this example sorts the profile table by the amount of real time the script spent executing a given function. The "cumm call" column reveals how many times each function was called, and the "s/call" column reveals how many seconds each call to the function required, on average.

  4. To generate a calltree file that you can import into the KCacheGrind profile analysis application, issue the pprof2calltree comand.


APD Functions

Contact information

If you have comments, bugfixes, enhancements or want to help developing this beast, you can send an mail to » apd@mail.communityconnect.com. Any help is very welcome.

Table of Contents

  • apd_breakpoint — Stops the interpreter and waits on a CR from the socket
  • apd_callstack — Returns the current call stack as an array
  • apd_clunk — Throw a warning and a callstack
  • apd_continue — Restarts the interpreter
  • apd_croak — Throw an error, a callstack and then exit
  • apd_dump_function_table — Outputs the current function table
  • apd_dump_persistent_resources — Return all persistent resources as an array
  • apd_dump_regular_resources — Return all current regular resources as an array
  • apd_echo — Echo to the debugging socket
  • apd_get_active_symbols — Get an array of the current variables names in the local scope
  • apd_set_pprof_trace — Starts the session debugging
  • apd_set_session_trace_socket — Starts the remote session debugging
  • apd_set_session_trace — Starts the session debugging
  • apd_set_session — Changes or sets the current debugging level
  • override_function — Overrides built-in functions
  • rename_function — Renames orig_name to new_name in the global function table


Stops the interpreter and waits on a CR from the socket

  • « APD Functions
  • apd_callstack »
  • PHP Manual
  • APD Functions
  • Stops the interpreter and waits on a CR from the socket

apd_breakpoint

(PECL apd >= 0.2)

apd_breakpoint — Stops the interpreter and waits on a CR from the socket

Description

apd_breakpoint ( int $debug_level ) : bool

This can be used to stop the running of your script, and await responses on the connected socket. To step the program, just send enter (a blank line), or enter a php command to be executed.

Parameters

debug_level

An integer which is formed by adding together the XXX_TRACE constants.

It is not recommended to use MEMORY_TRACE. It is very slow and does not appear to be accurate. ASSIGNMENT_TRACE is not implemented yet.

To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Typical session using tcplisten

bash#tcplisten localhost 7777

APD - Advanced PHP Debugger Trace File
---------------------------------------------------------------------------
Process Pid (6118)
Trace Begun at Sun Mar 10 23:13:12 2002
---------------------------------------------------------------------------
(  0.000000): apd_set_session_trace called at /home/alan/Projects/project2/test.
php:5
(  0.074824): apd_set_session_trace_socket() at /home/alan/Projects/project2/tes
t.php:5 returned.  Elapsed (0.074824)
(  0.074918): apd_breakpoint() /home/alan/Projects/project2/test.php:7
              ++ argv[0] $(??) = 9
apd_breakpoint() at /home/alan/Projects/project2/test.php:7 returned.  Elapsed (
-2089521468.1073275368)
>\n
statement: /home/alan/Projects/project2/test.php:8
>\n
statement: /home/alan/Projects/project2/test.php:8
>\n
statement: /home/alan/Projects/project2/test.php:10
>apd_echo($i);
EXEC: apd_echo($i);
0
>apd_echo(serialize(apd_get_active_symbols()));
EXEC:  apd_echo(serialize(apd_get_active_symbols()));
a:47:{i:0;s:4:"PWD";i:1;s:10:"COLORFGBG";i:2;s:11:"XAUTHORITY";i:3;s:14:"
COLORTERM_BCE";i:4;s:9:"WINDOWID";i:5;s:14:"ETERM_VERSION";i:6;s:16:"SE
SSION_MANAGER";i:7;s:4:"PS1";i:8;s:11:"GDMSESSION";i:9;s:5:"USER";i:10;s:5:"
MAIL";i:11;s:7:"OLDPWD";i:12;s:5:"LANG";i:13;s:10:"COLORTERM";i:14;s:8:"DISP
LAY";i:15;s:8:"LOGNAME";i:16;s:6:"
>apd_echo(system('ls /home/mydir'));
........
>apd_continue(0);


Returns the current call stack as an array

  • « apd_breakpoint
  • apd_clunk »
  • PHP Manual
  • APD Functions
  • Returns the current call stack as an array

apd_callstack

(PECL apd 0.2-0.4)

apd_callstack — Returns the current call stack as an array

Description

apd_callstack ( void ) : array

Returns the current call stack as an array

Return Values

An array containing the current call stack.

Examples

Example #1 apd_callstack() example

<?php
print_r(apd_callstack());
?>


Throw a warning and a callstack

  • « apd_callstack
  • apd_continue »
  • PHP Manual
  • APD Functions
  • Throw a warning and a callstack

apd_clunk

(PECL apd 0.2-0.4)

apd_clunk — Throw a warning and a callstack

Description

apd_clunk ( string $warning [, string $delimiter = "<BR />" ] ) : void

Behaves like perl's Carp::cluck. Throw a warning and a callstack.

Parameters

warning

The warning to throw.

delimiter

The delimiter. Default to <BR />.

Return Values

No value is returned.

Examples

Example #1 apd_clunk() example

<?php
apd_clunk("Some Warning", "<br/>");
?>

See Also

  • apd_croak() - Throw an error, a callstack and then exit


Restarts the interpreter

  • « apd_clunk
  • apd_croak »
  • PHP Manual
  • APD Functions
  • Restarts the interpreter

apd_continue

(PECL apd >= 0.2)

apd_continue — Restarts the interpreter

Description

apd_continue ( int $debug_level ) : bool

Usually sent via the socket to restart the interpreter.

Parameters

debug_level

An integer which is formed by adding together the XXX_TRACE constants.

It is not recommended to use MEMORY_TRACE. It is very slow and does not appear to be accurate. ASSIGNMENT_TRACE is not implemented yet.

To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 apd_continue() example

<?php
apd_continue(0);
?>


Throw an error, a callstack and then exit

  • « apd_continue
  • apd_dump_function_table »
  • PHP Manual
  • APD Functions
  • Throw an error, a callstack and then exit

apd_croak

(PECL apd 0.2-0.4)

apd_croak — Throw an error, a callstack and then exit

Description

apd_croak ( string $warning [, string $delimiter = "<BR />" ] ) : void

Behaves like perl's Carp::croak. Throw an error, a callstack and then exit.

Parameters

warning

The warning to throw.

delimiter

The delimiter. Default to <BR />.

Return Values

No value is returned.

Examples

Example #1 apd_croak() example

<?php
apd_croak("Some Warning","<P>");
?>

See Also

  • apd_clunk() - Throw a warning and a callstack


Outputs the current function table

  • « apd_croak
  • apd_dump_persistent_resources »
  • PHP Manual
  • APD Functions
  • Outputs the current function table

apd_dump_function_table

(Unknown)

apd_dump_function_table — Outputs the current function table

Description

apd_dump_function_table ( void ) : void

Outputs the current function table.

Return Values

No value is returned.

Examples

Example #1 apd_dump_function_table() example

<?php
apd_dump_function_table();
?>


Return all persistent resources as an array

  • « apd_dump_function_table
  • apd_dump_regular_resources »
  • PHP Manual
  • APD Functions
  • Return all persistent resources as an array

apd_dump_persistent_resources

(PECL apd 0.2-0.4)

apd_dump_persistent_resources — Return all persistent resources as an array

Description

apd_dump_persistent_resources ( void ) : array

Return all persistent resources as an array.

Return Values

An array containing the current persistent resources.

Examples

Example #1 apd_dump_persistent_resources() example

<?php
print_r(apd_dump_persistent_resources());
?>

See Also

  • apd_dump_regular_resources() - Return all current regular resources as an array


Return all current regular resources as an array

  • « apd_dump_persistent_resources
  • apd_echo »
  • PHP Manual
  • APD Functions
  • Return all current regular resources as an array

apd_dump_regular_resources

(PECL apd 0.2-0.4)

apd_dump_regular_resources — Return all current regular resources as an array

Description

apd_dump_regular_resources ( void ) : array

Return all current regular resources as an array.

Return Values

An array containing the current regular resources.

Examples

Example #1 apd_dump_regular_resources() example

<?php
print_r(apd_dump_regular_resources());
?>

See Also

  • apd_dump_persistent_resources() - Return all persistent resources as an array


Echo to the debugging socket

  • « apd_dump_regular_resources
  • apd_get_active_symbols »
  • PHP Manual
  • APD Functions
  • Echo to the debugging socket

apd_echo

(PECL apd >= 0.2)

apd_echo — Echo to the debugging socket

Description

apd_echo ( string $output ) : bool

Usually sent via the socket to request information about the running script.

Parameters

output

The debugged variable.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 apd_echo() example

<?php
apd_echo($i);
?>


Get an array of the current variables names in the local scope

  • « apd_echo
  • apd_set_pprof_trace »
  • PHP Manual
  • APD Functions
  • Get an array of the current variables names in the local scope

apd_get_active_symbols

(PECL apd 0.2)

apd_get_active_symbols — Get an array of the current variables names in the local scope

Description

apd_get_active_symbols ( void ) : array

Returns the names of all the variables defined in the active scope, (not their values).

Return Values

A multidimensional array with all the variables.

Examples

Example #1 apd_get_active_symbols() example

<?php
apd_echo(apd_get_active_symbols());
?>


Starts the session debugging

  • « apd_get_active_symbols
  • apd_set_session_trace_socket »
  • PHP Manual
  • APD Functions
  • Starts the session debugging

apd_set_pprof_trace

(PECL apd >= 0.2)

apd_set_pprof_trace — Starts the session debugging

Description

apd_set_pprof_trace ([ string $dump_directory = ini_get("apd.dumpdir") [, string $fragment = "pprof" ]] ) : string

Starts debugging to pprof_{process_id} in the dump directory.

Parameters

dump_directory

The directory in which the profile dump file is written. If not set, the apd.dumpdir setting from the php.ini file is used.

fragment

Return Values

Returns path of the destination file.

Examples

Example #1 apd_set_pprof_trace() example

<?php
apd_set_pprof_trace();
?>

See Also

  • apd_set_session_trace() - Starts the session debugging


Starts the remote session debugging

  • « apd_set_pprof_trace
  • apd_set_session_trace »
  • PHP Manual
  • APD Functions
  • Starts the remote session debugging

apd_set_session_trace_socket

(PECL apd >= 0.2)

apd_set_session_trace_socket — Starts the remote session debugging

Description

apd_set_session_trace_socket ( string $tcp_server , int $socket_type , int $port , int $debug_level ) : bool

Connects to the specified tcp_server (eg. tcplisten) and sends debugging data to the socket.

Parameters

tcp_server

IP or Unix Domain socket (like a file) of the TCP server.

socket_type

Can be AF_UNIX for file based sockets or APD_AF_INET for standard tcp/ip.

port

You can use any port, but higher numbers are better as most of the lower numbers may be used by other system services.

debug_level

An integer which is formed by adding together the XXX_TRACE constants.

It is not recommended to use MEMORY_TRACE. It is very slow and does not appear to be accurate. ASSIGNMENT_TRACE is not implemented yet.

To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 apd_set_session_trace_socket() example

<?php
  apd_set_session_trace_socket("127.0.0.1",APD_AF_INET,7112,0);
?>


Starts the session debugging

  • « apd_set_session_trace_socket
  • apd_set_session »
  • PHP Manual
  • APD Functions
  • Starts the session debugging

apd_set_session_trace

(PECL apd 0.2-0.4)

apd_set_session_trace — Starts the session debugging

Description

apd_set_session_trace ( int $debug_level [, string $dump_directory = ini_get("apd.dumpdir") ] ) : void

Starts debugging to apd_dump_{process_id} in the dump directory.

Parameters

debug_level

An integer which is formed by adding together the XXX_TRACE constants.

It is not recommended to use MEMORY_TRACE. It is very slow and does not appear to be accurate. ASSIGNMENT_TRACE is not implemented yet.

To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99

dump_directory

The directory in which the profile dump file is written. If not set, the apd.dumpdir setting from the php.ini file is used.

Return Values

No value is returned.

Examples

Example #1 apd_set_session_trace() example

<?php
apd_set_session_trace(99);
?>


Changes or sets the current debugging level

  • « apd_set_session_trace
  • override_function »
  • PHP Manual
  • APD Functions
  • Changes or sets the current debugging level

apd_set_session

(PECL apd 0.2-0.4)

apd_set_session — Changes or sets the current debugging level

Description

apd_set_session ( int $debug_level ) : void

This can be used to increase or decrease debugging in a different area of your application.

Parameters

debug_level

An integer which is formed by adding together the XXX_TRACE constants.

It is not recommended to use MEMORY_TRACE. It is very slow and does not appear to be accurate. ASSIGNMENT_TRACE is not implemented yet.

To turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99

Return Values

No value is returned.

Examples

Example #1 apd_set_session() example

<?php
apd_set_session(9);
?>


Overrides built-in functions

  • « apd_set_session
  • rename_function »
  • PHP Manual
  • APD Functions
  • Overrides built-in functions

override_function

(PECL apd >= 0.2)

override_function — Overrides built-in functions

Description

override_function ( string $function_name , string $function_args , string $function_code ) : bool

Overrides built-in functions by replacing them in the symbol table.

Parameters

function_name

The function to override.

function_args

The function arguments, as a comma separated string.

Usually you will want to pass this parameter, as well as the function_code parameter, as a single quote delimited string. The reason for using single quoted strings, is to protect the variable names from parsing, otherwise, if you use double quotes there will be a need to escape the variable names, e.g. \$your_var.

function_code

The new code for the function.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 override_function() example

<?php
override_function('test', '$a,$b', 'echo "DOING TEST"; return $a * $b;');
?>


Renames orig_name to new_name in the global function table

  • « override_function
  • bcompiler »
  • PHP Manual
  • APD Functions
  • Renames orig_name to new_name in the global function table

rename_function

(PECL apd >= 0.2)

rename_function — Renames orig_name to new_name in the global function table

Description

rename_function ( string $original_name , string $new_name ) : bool

Renames a orig_name to new_name in the global function table. Useful for temporarily overriding built-in functions.

Parameters

original_name

The original function name.

new_name

The new name for the original_name function.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 rename_function() example

<?php
rename_function('mysql_connect', 'debug_mysql_connect' );
?>


PHP bytecode Compiler

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • bcompiler Functions
    • bcompiler_load_exe — Reads and creates classes from a bcompiler exe file
    • bcompiler_load — Reads and creates classes from a bz compressed file
    • bcompiler_parse_class — Reads the bytecodes of a class and calls back to a user function
    • bcompiler_read — Reads and creates classes from a filehandle
    • bcompiler_write_class — Writes a defined class as bytecodes
    • bcompiler_write_constant — Writes a defined constant as bytecodes
    • bcompiler_write_exe_footer — Writes the start pos, and sig to the end of a exe type file
    • bcompiler_write_file — Writes a php source file as bytecodes
    • bcompiler_write_footer — Writes the single character \x00 to indicate End of compiled data
    • bcompiler_write_function — Writes a defined function as bytecodes
    • bcompiler_write_functions_from_file — Writes all functions defined in a file as bytecodes
    • bcompiler_write_header — Writes the bcompiler header
    • bcompiler_write_included_filename — Writes an included file as bytecodes


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.

Bcompiler was written for several reasons:

  • To encode entire script in a proprietary PHP application
  • To encode some classes and/or functions in a proprietary PHP application
  • To enable the production of php-gtk applications that could be used on client desktops, without the need for a php.exe.
  • To do the feasibility study for a PHP to C converter
The first of these goals is achieved using the bcompiler_write_header(), bcompiler_write_file() and bcompiler_write_footer() functions. The bytecode files can be written as either uncompressed or plain. To use the generated bytecode, you can simply include it with include or require statements.

The second of these goals is achieved using the bcompiler_write_header(), bcompiler_write_class(), bcompiler_write_footer(), bcompiler_read(), and bcompiler_load() functions. The bytecode files can be written as either uncompressed or plain. The bcompiler_load() reads a bzip compressed bytecode file, which tends to be 1/3 of the size of the original file.

To create EXE type files, bcompiler has to be used with a modified sapi file or a version of PHP which has been compiled as a shared library. In this scenario, bcompiler reads the compressed bytecode from the end of the exe file.

bcompiler can improve performance by about 30% when used with uncompressed bytecodes only. But keep in mind that uncompressed bytecode can be up to 5 times larger than the original source code. Using bytecode compression can save your space, but decompression requires much more time than parsing a source. bcompiler also does not do any bytecode optimization, this could be added in the future...

In terms of code protection, it is safe to say that it would be impossible to recreate the exact source code that it was built from, and without the accompanying source code comments. It would effectively be useless to use the bcompiler bytecodes to recreate and modify a class. However it is possible to retrieve data from a bcompiled bytecode file - so don't put your private passwords or anything in it.


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

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.


  • « Installation
  • Resource Types »
  • PHP Manual
  • Installing/Configuring
  • Runtime Configuration

Runtime Configuration

This extension has no configuration directives defined in php.ini.


  • « Resource Types
  • bcompiler Functions »
  • PHP Manual
  • bcompiler
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


bcompiler Functions

Contact Information

If you have comments, bugfixes, enhancements or want to help developing this beast, you can drop me a mail at » alan_k@php.net. Any help is very welcome.

Table of Contents

  • bcompiler_load_exe — Reads and creates classes from a bcompiler exe file
  • bcompiler_load — Reads and creates classes from a bz compressed file
  • bcompiler_parse_class — Reads the bytecodes of a class and calls back to a user function
  • bcompiler_read — Reads and creates classes from a filehandle
  • bcompiler_write_class — Writes a defined class as bytecodes
  • bcompiler_write_constant — Writes a defined constant as bytecodes
  • bcompiler_write_exe_footer — Writes the start pos, and sig to the end of a exe type file
  • bcompiler_write_file — Writes a php source file as bytecodes
  • bcompiler_write_footer — Writes the single character \x00 to indicate End of compiled data
  • bcompiler_write_function — Writes a defined function as bytecodes
  • bcompiler_write_functions_from_file — Writes all functions defined in a file as bytecodes
  • bcompiler_write_header — Writes the bcompiler header
  • bcompiler_write_included_filename — Writes an included file as bytecodes


Reads and creates classes from a bcompiler exe file

  • « bcompiler Functions
  • bcompiler_load »
  • PHP Manual
  • bcompiler Functions
  • Reads and creates classes from a bcompiler exe file

bcompiler_load_exe

(PECL bcompiler >= 0.4)

bcompiler_load_exe — Reads and creates classes from a bcompiler exe file

Description

bcompiler_load_exe ( string $filename ) : bool

Reads data from a bcompiler exe file and creates classes from the bytecodes.

Parameters

filename

The exe file path, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_load_exe() example

<?php

bcompiler_load_exe("/tmp/example.exe");
print_r(get_defined_classes());

?>

Notes

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.

See Also

  • bcompiler_load() - Reads and creates classes from a bz compressed file


Reads and creates classes from a bz compressed file

  • « bcompiler_load_exe
  • bcompiler_parse_class »
  • PHP Manual
  • bcompiler Functions
  • Reads and creates classes from a bz compressed file

bcompiler_load

(PECL bcompiler >= 0.4)

bcompiler_load — Reads and creates classes from a bz compressed file

Description

bcompiler_load ( string $filename ) : bool

Reads data from a bzcompressed file and creates classes from the bytecodes.

Parameters

filename

The bzcompressed file path, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_load() example

<?php

bcompiler_load("/tmp/example");

print_r(get_defined_classes());

?>

Notes

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.

Note:

Please use include or require statements to parse bytecodes, it's more portable and convenient way than using this function.

Please note that this function won't execute script body code contained in the bytecode file.

See Also

  • bcompiler_load_exe() - Reads and creates classes from a bcompiler exe file


Reads the bytecodes of a class and calls back to a user function

  • « bcompiler_load
  • bcompiler_read »
  • PHP Manual
  • bcompiler Functions
  • Reads the bytecodes of a class and calls back to a user function

bcompiler_parse_class

(PECL bcompiler >= 0.4)

bcompiler_parse_class — Reads the bytecodes of a class and calls back to a user function

Description

bcompiler_parse_class ( string $class , string $callback ) : bool

Reads the bytecodes of a class and calls back to a user function.

Parameters

class

The class name, as a string.

callback

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_parse_class() example

<?php

function readByteCodes($data) {
    print_r($data);
}

bcompiler_parse_class("DB","readByteCodes");

?>

Notes

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.

Note:

This function has been removed from bcompiler and is no longer available as of bcompiler 0.5.


Reads and creates classes from a filehandle

  • « bcompiler_parse_class
  • bcompiler_write_class »
  • PHP Manual
  • bcompiler Functions
  • Reads and creates classes from a filehandle

bcompiler_read

(PECL bcompiler >= 0.4)

bcompiler_read — Reads and creates classes from a filehandle

Description

bcompiler_read ( resource $filehandle ) : bool

Reads data from a open file handle and creates classes from the bytecodes.

Parameters

filehandle

A file handle as returned by fopen().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_read() example

<?php
$fh = fopen("/tmp/example","r");
bcompiler_read($fh);
fclose($fh);
print_r(get_defined_classes());

?>

Notes

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.

Note:

Please use include or require statements to parse bytecodes, it's more portable and convenient way than using this function.

Please note that this function won't execute script body code contained in the bytecode file.


Writes a defined class as bytecodes

  • « bcompiler_read
  • bcompiler_write_constant »
  • PHP Manual
  • bcompiler Functions
  • Writes a defined class as bytecodes

bcompiler_write_class

(PECL bcompiler >= 0.4)

bcompiler_write_class — Writes a defined class as bytecodes

Description

bcompiler_write_class ( resource $filehandle , string $className [, string $extends ] ) : bool

Reads the bytecodes from PHP for an existing class, and writes them to the open file handle.

Parameters

filehandle

A file handle as returned by fopen().

className

The class name, as a string.

extends

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_write_class() example

<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_class($fh,"DB");
// you must write DB_common before DB_mysql, as DB_mysql extends DB_common.
bcompiler_write_class($fh,"DB_common");
bcompiler_write_class($fh,"DB_mysql");
bcompiler_write_footer($fh);
fclose($fh);

?>

Notes

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.

Note:

This function does not perform dependency checking, so make sure you write the classes in an order that will not result in an undefined class error occurring when you load it.

See Also

  • bcompiler_write_header() - Writes the bcompiler header
  • bcompiler_write_footer() - Writes the single character \x00 to indicate End of compiled data


Writes a defined constant as bytecodes

  • « bcompiler_write_class
  • bcompiler_write_exe_footer »
  • PHP Manual
  • bcompiler Functions
  • Writes a defined constant as bytecodes

bcompiler_write_constant

(PECL bcompiler >= 0.5)

bcompiler_write_constant — Writes a defined constant as bytecodes

Description

bcompiler_write_constant ( resource $filehandle , string $constantName ) : bool

Reads the bytecodes from PHP for an existing constant, and writes them to the open file handle.

Parameters

filehandle

A file handle as returned by fopen().

constantName

The name of the defined constant, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_write_constant() example

<?php
define("MODULE_MAX", 30);

$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_constant($fh,"MODULE_MAX");
bcompiler_write_footer($fh);
fclose($fh);

?>

Notes

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.

See Also

  • bcompiler_write_header() - Writes the bcompiler header
  • bcompiler_write_footer() - Writes the single character \x00 to indicate End of compiled data


Writes the start pos, and sig to the end of a exe type file

  • « bcompiler_write_constant
  • bcompiler_write_file »
  • PHP Manual
  • bcompiler Functions
  • Writes the start pos, and sig to the end of a exe type file

bcompiler_write_exe_footer

(PECL bcompiler >= 0.4)

bcompiler_write_exe_footer — Writes the start pos, and sig to the end of a exe type file

Description

bcompiler_write_exe_footer ( resource $filehandle , int $startpos ) : bool

An EXE (or self executable) file consists of 3 parts:

  • The stub (executable code, e.g. a compiled C program) that loads PHP interpreter, bcompiler extension, stored Bytecodes and initiates a call for the specified function (e.g. main) or class method (e.g. main::main)
  • The Bytecodes (uncompressed only for the moment)
  • The bcompiler EXE footer

To obtain a suitable stub you can compile php_embed-based stub phpe.c located in the examples/embed directory on bcompiler's CVS.

Parameters

filehandle

A file handle as returned by fopen().

startpos

The file position at which the Bytecodes start, and can be obtained using ftell().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_write_exe_footer() example

<?php

/* creating the output file (example.exe) */
$fh = fopen("example.exe", "w");

/* 1) writing a stub (phpe.exe) */
$size = filesize("phpe.exe");
$fr = fopen("phpe.exe", "r");
fwrite($fh, fread($fr, $size), $size);
$startpos = ftell($fh);

/* 2) writing bytecodes */
bcompiler_write_header($fh);
bcompiler_write_class($fh, "myclass");
bcompiler_write_function($fh, "main");
bcompiler_write_footer($fh);

/* 3) writing EXE footer */
bcompiler_write_exe_footer($fh, $startpos);

/* closing the output file */
fclose($fh);
?>

Notes

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.

See Also

  • bcompiler_write_header() - Writes the bcompiler header
  • bcompiler_write_class() - Writes a defined class as bytecodes
  • bcompiler_write_footer() - Writes the single character \x00 to indicate End of compiled data


Writes a php source file as bytecodes

  • « bcompiler_write_exe_footer
  • bcompiler_write_footer »
  • PHP Manual
  • bcompiler Functions
  • Writes a php source file as bytecodes

bcompiler_write_file

(PECL bcompiler >= 0.6)

bcompiler_write_file — Writes a php source file as bytecodes

Description

bcompiler_write_file ( resource $filehandle , string $filename ) : bool

This function compiles specified source file into bytecodes, and writes them to the open file handle.

Parameters

filehandle

A file handle as returned by fopen().

filename

The source file path, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_write_file() example

<?php
$fh = fopen("example.phb", "w");
bcompiler_write_header($fh);
bcompiler_write_file($fh, "example.php");
bcompiler_write_footer($fh);
fclose($fh);
/* the following should be equivalent:
include "example.php";
   and
include "example.phb";
*/
?>

Notes

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.

See Also

  • bcompiler_write_header() - Writes the bcompiler header
  • bcompiler_write_footer() - Writes the single character \x00 to indicate End of compiled data


Writes the single character \x00 to indicate End of compiled data

  • « bcompiler_write_file
  • bcompiler_write_function »
  • PHP Manual
  • bcompiler Functions
  • Writes the single character \x00 to indicate End of compiled data

bcompiler_write_footer

(PECL bcompiler >= 0.4)

bcompiler_write_footer — Writes the single character \x00 to indicate End of compiled data

Description

bcompiler_write_footer ( resource $filehandle ) : bool

Writes the single character \x00 to indicate End of compiled data.

Parameters

filehandle

A file handle as returned by fopen().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_write_footer() example

<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_class($fh,"DB");
bcompiler_write_class($fh,"DB_common");
bcompiler_write_footer($fh);
fclose($fh);

?>

Notes

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.

See Also

  • bcompiler_write_header() - Writes the bcompiler header


Writes a defined function as bytecodes

  • « bcompiler_write_footer
  • bcompiler_write_functions_from_file »
  • PHP Manual
  • bcompiler Functions
  • Writes a defined function as bytecodes

bcompiler_write_function

(PECL bcompiler >= 0.5)

bcompiler_write_function — Writes a defined function as bytecodes

Description

bcompiler_write_function ( resource $filehandle , string $functionName ) : bool

Reads the bytecodes from PHP for an existing function, and writes them to the open file handle. Order is not important, (eg. if function b uses function a, and you compile it like the example below, it will work perfectly OK).

Parameters

filehandle

A file handle as returned by fopen().

functionName

The function name, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_write_function() example

<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_function($fh,"my_function_a");
bcompiler_write_function($fh,"my_function_b");
bcompiler_write_footer($fh);
fclose($fh);

?>

Notes

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.

See Also

  • bcompiler_write_header() - Writes the bcompiler header
  • bcompiler_write_footer() - Writes the single character \x00 to indicate End of compiled data


Writes all functions defined in a file as bytecodes

  • « bcompiler_write_function
  • bcompiler_write_header »
  • PHP Manual
  • bcompiler Functions
  • Writes all functions defined in a file as bytecodes

bcompiler_write_functions_from_file

(PECL bcompiler >= 0.5)

bcompiler_write_functions_from_file — Writes all functions defined in a file as bytecodes

Description

bcompiler_write_functions_from_file ( resource $filehandle , string $fileName ) : bool

Searches for all functions declared in the given file, and writes their correspondent bytecodes to the open file handle.

Parameters

filehandle

A file handle as returned by fopen().

fileName

The file to be compiled. You must always include or require the file you intend to compile.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_write_functions_from_file() example

<?php
require('module.php');

$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_functions_from_file($fh,'module.php');
bcompiler_write_footer($fh);
fclose($fh);

?>

Notes

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.

See Also

  • bcompiler_write_header() - Writes the bcompiler header
  • bcompiler_write_footer() - Writes the single character \x00 to indicate End of compiled data


Writes the bcompiler header

  • « bcompiler_write_functions_from_file
  • bcompiler_write_included_filename »
  • PHP Manual
  • bcompiler Functions
  • Writes the bcompiler header

bcompiler_write_header

(PECL bcompiler >= 0.3)

bcompiler_write_header — Writes the bcompiler header

Description

bcompiler_write_header ( resource $filehandle [, string $write_ver ] ) : bool

Writes the header part of a bcompiler file.

Parameters

filehandle

A file handle as returned by fopen().

write_ver

Can be used to write bytecode in a previously used format, so that you can use it with older versions of bcompiler.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bcompiler_write_header() example

<?php
$fh = fopen("/tmp/example","w");
bcompiler_write_header($fh);
bcompiler_write_class($fh,"DB");
bcompiler_write_footer($fh);
fclose($fh);

?>

Notes

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.

See Also

  • bcompiler_write_footer() - Writes the single character \x00 to indicate End of compiled data


Writes an included file as bytecodes

  • « bcompiler_write_header
  • BLENC »
  • PHP Manual
  • bcompiler Functions
  • Writes an included file as bytecodes

bcompiler_write_included_filename

(PECL bcompiler >= 0.5)

bcompiler_write_included_filename — Writes an included file as bytecodes

Description

bcompiler_write_included_filename ( resource $filehandle , string $filename ) : bool
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

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.


Blenc - BLowfish ENCoder for PHP source scripts

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Blenc Functions
    • blenc_encrypt — Encrypt a PHP script with BLENC


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.

BLENC is a PHP source script protector that:

  • Encodes your source code with the blowfish algorithm.
  • Allows transparent decryption and execution of PHP scripts previously encoded with BLENC.

BLENC is an extension which hooks into the Zend Engine, allowing for transparent encryption and execution of PHP scripts using the blowfish algorithm. It is not designed for complete security (it is still possible to disassemble the script into op codes using a package such as XDebug), however it does keep people out of your code and make reverse engineering difficult.

In order to protect your PHP script you must encrypt each script with blenc_encrypt() function. After you can include the encoded script like the example below:

<?php

/* PHP script encoded with BLENC */
$my_source_encoded = 'my_source_encoded.phpe';

include($my_source_encoded);
?>

BLENC supports also expiration time for the module. So, if you want deploy your source code with a expiration time, you have to compile the extension modifying the header file related to encryption and expiration time. Please see configuration section for further informations.


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

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/blenc

It's strongly recommended to install BLENC from sources without 'pecl' command. In this way you can:

  • Specify your personal encryption key used to create redistributable keys. Your sourcecode will be more difficult to decrypt also for users that can read your key_file on webserver.
  • Specify a expiration date for the BLENC module. With expiration date you can decide that BLENC module on target system will work until a date. After that BLENC will not decrypt any files.
All these configuration options are stored into header file: blenc_protect.h

Please read the content of blenc_protect.h in sources of BLENC to know how set these hardcoded options.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Blenc Configure Options
Name | Default | Changeable | Changelog
blenc.key_file | /usr/local/etc/blenckeys | PHP_INI_ALL |

Here's a short explanation of the configuration directives.

blenc.key_file string

It's the location where BLENC can find the file containing a list of available decryption keys. This file must be readable by webserver.


  • « Runtime Configuration
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

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.

BLENC_EXT_VERSION (string)


  • « Predefined Constants
  • blenc_encrypt »
  • PHP Manual
  • BLENC
  • Blenc Functions

Blenc Functions

Table of Contents

  • blenc_encrypt — Encrypt a PHP script with BLENC


Encrypt a PHP script with BLENC

  • « Blenc Functions
  • Componere »
  • PHP Manual
  • Blenc Functions
  • Encrypt a PHP script with BLENC

blenc_encrypt

(PECL blenc >= 5)

blenc_encrypt — Encrypt a PHP script with BLENC

Description

blenc_encrypt ( string $plaintext , string $encodedfile [, string $encryption_key ] ) : string

Encrypt the plaintext content and write it into encodedfile

Parameters

plaintext

A source code to encrypt. Does not need to contain opening/closing PHP tags

encodedfile

The filename where BLENC will save the encoded source.

encryption_key

The key that BLENC will use to encrypt plaintext content. If not given BLENC will create a valid key.

Return Values

BLENC will return the redistributable key that must be saved into key_file: the path of key_file is specified at runtime with the option blenc.key_file

Examples

Example #1 blenc_encrypt() example

<?php

/* read the PHP source code */
$source_code = file_get_contents("my_source_to_protect.php");

/* create the encrypted version */
$redistributable_key = blenc_encrypt($source_code, "my_source_encoded.php");

/* read which is the key_file */
$key_file = ini_get('blenc.key_file');

/* save the redistributable key */
file_put_contents($key_file, $redistributable_key, FILE_APPEND);
?>


Componere

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


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 ( Type $type , $object ) : Type
Componere\cast_by_ref ( Type $type , $object ) : Type


  • « Introduction
  • Requirements »
  • PHP Manual
  • Componere
  • Installing/Configuring

Installing/Configuring

Table of Contents

  • Requirements
  • Installation


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

Reflection is required


  • « Requirements
  • Componere\Abstract\Definition »
  • PHP Manual
  • Installing/Configuring
  • Installation

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 Componere\Abstract\Definition {
/* Methods */
public addInterface ( string $interface ) : Definition
public addMethod ( string $name , \Componere\Method $method ) : Definition
public addTrait ( string $trait ) : Definition
public getReflector ( void ) : \ReflectionClass
}

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


Add Interface

  • « Componere\Abstract\Definition
  • Componere\Abstract\Definition::addMethod »
  • PHP Manual
  • Componere\Abstract\Definition
  • Add Interface

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


Add Method

  • « Componere\Abstract\Definition::addInterface
  • Componere\Abstract\Definition::addTrait »
  • PHP Manual
  • Componere\Abstract\Definition
  • Add Method

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


Add Trait

  • « Componere\Abstract\Definition::addMethod
  • Componere\Abstract\Definition::getReflector »
  • PHP Manual
  • Componere\Abstract\Definition
  • Add Trait

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


Reflection

  • « Componere\Abstract\Definition::addTrait
  • Componere\Definition »
  • PHP Manual
  • Componere\Abstract\Definition
  • Reflection

Componere\Abstract\Definition::getReflector

(Componere 2 >= 2.1.0)

Componere\Abstract\Definition::getReflector — Reflection

Description

public Componere\Abstract\Definition::getReflector ( void ) : \ReflectionClass

Shall create or return a ReflectionClass

Return Values

A ReflectionClass for the current definition (cached)


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 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 ) : void
public isRegistered ( void ) : bool
public getClosure ( string $name ) : \Closure
public getClosures ( void ) : 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 ( void ) : \ReflectionClass
}

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


Definition Construction

  • « Componere\Definition
  • Componere\Definition::addConstant »
  • PHP Manual
  • Componere\Definition
  • Definition Construction

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 an class in interfaces is not an interface


Add Constant

  • « Componere\Definition::__construct
  • Componere\Definition::addProperty »
  • PHP Manual
  • Componere\Definition
  • Add Constant

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


Add Property

  • « Componere\Definition::addConstant
  • Componere\Definition::register »
  • PHP Manual
  • Componere\Definition
  • Add Property

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


Registration

  • « Componere\Definition::addProperty
  • Componere\Definition::isRegistered »
  • PHP Manual
  • Componere\Definition
  • Registration

Componere\Definition::register

(Componere 2 >= 2.1.0)

Componere\Definition::register — Registration

Description

public Componere\Definition::register ( void ) : void

Shall register the current Definition

Exceptions

Warning

Shall throw RuntimeException if Definition was registered


State Detection

  • « Componere\Definition::register
  • Componere\Definition::getClosure »
  • PHP Manual
  • Componere\Definition
  • State Detection

Componere\Definition::isRegistered

(Componere 2 >= 2.1.0)

Componere\Definition::isRegistered — State Detection

Description

public Componere\Definition::isRegistered ( void ) : bool

Shall detect the registration state of this Definition

Return Values

Shall return true if this Definition is registered


Get Closure

  • « Componere\Definition::isRegistered
  • Componere\Definition::getClosures »
  • PHP Manual
  • Componere\Definition
  • Get Closure

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


Get Closures

  • « Componere\Definition::getClosure
  • Componere\Patch »
  • PHP Manual
  • Componere\Definition
  • Get Closures

Componere\Definition::getClosures

(Componere 2 >= 2.1.0)

Componere\Definition::getClosures — Get Closures

Description

public Componere\Definition::getClosures ( void ) : 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


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 Componere\Patch extends Componere\Abstract\Definition {
/* Constructors */
public __construct ( object $instance )
public __construct ( object $instance , array $interfaces )
/* Methods */
public apply ( void ) : void
public revert ( void ) : void
public isApplied ( void ) : bool
public derive ( object $instance ) : Patch
public getClosure ( string $name ) : \Closure
public getClosures ( void ) : 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 ( void ) : \ReflectionClass
}

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


Patch Construction

  • « Componere\Patch
  • Componere\Patch::apply »
  • PHP Manual
  • Componere\Patch
  • Patch Construction

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 an class in interfaces is not an interface


Application

  • « Componere\Patch::__construct
  • Componere\Patch::revert »
  • PHP Manual
  • Componere\Patch
  • Application

Componere\Patch::apply

(Componere 2 >= 2.1.0)

Componere\Patch::apply — Application

Description

public Componere\Patch::apply ( void ) : void

Shall apply the current patch


Reversal

  • « Componere\Patch::apply
  • Componere\Patch::isApplied »
  • PHP Manual
  • Componere\Patch
  • Reversal

Componere\Patch::revert

(Componere 2 >= 2.1.0)

Componere\Patch::revert — Reversal

Description

public Componere\Patch::revert ( void ) : void

Shall revert the current patch


State Detection

  • « Componere\Patch::revert
  • Componere\Patch::derive »
  • PHP Manual
  • Componere\Patch
  • State Detection

Componere\Patch::isApplied

(Componere 2 >= 2.1.0)

Componere\Patch::isApplied — State Detection

Description

public Componere\Patch::isApplied ( void ) : bool


Patch Derivation

  • « Componere\Patch::isApplied
  • Componere\Patch::getClosure »
  • PHP Manual
  • Componere\Patch
  • Patch Derivation

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


Get Closure

  • « Componere\Patch::derive
  • Componere\Patch::getClosures »
  • PHP Manual
  • Componere\Patch
  • Get Closure

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


Get Closures

  • « Componere\Patch::getClosure
  • Componere\Method »
  • PHP Manual
  • Componere\Patch
  • Get Closures

Componere\Patch::getClosures

(Componere 2 >= 2.1.0)

Componere\Patch::getClosures — Get Closures

Description

public Componere\Patch::getClosures ( void ) : 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


The Componere\Method class

(Componere 2 >= 2.1.0)

Introduction

A Method represents a function with modifiable accessibility flags

Class synopsis

final Componere\Method {
/* Constructor */
public __construct ( \Closure $closure )
/* Methods */
public setPrivate ( void ) : Method
public setProtected ( void ) : Method
public setStatic ( void ) : Method
public getReflector ( void ) : \ReflectionMethod
}

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


Method Construction

  • « Componere\Method
  • Componere\Method::setPrivate »
  • PHP Manual
  • Componere\Method
  • Method Construction

Componere\Method::__construct

(Componere 2 >= 2.1.0)

Componere\Method::__construct — Method Construction

Description

public Componere\Method::__construct ( \Closure $closure )

Parameters

closure


Accessibility Modification

  • « Componere\Method::__construct
  • Componere\Method::setProtected »
  • PHP Manual
  • Componere\Method
  • Accessibility Modification

Componere\Method::setPrivate

(Componere 2 >= 2.1.0)

Componere\Method::setPrivate — Accessibility Modification

Description

public Componere\Method::setPrivate ( void ) : Method

Return Values

The current Method

Exceptions

Warning

Shall throw RuntimeException if access level was previously set


Accessibility Modification

  • « Componere\Method::setPrivate
  • Componere\Method::setStatic »
  • PHP Manual
  • Componere\Method
  • Accessibility Modification

Componere\Method::setProtected

(Componere 2 >= 2.1.0)

Componere\Method::setProtected — Accessibility Modification

Description

public Componere\Method::setProtected ( void ) : Method

Return Values

The current Method

Exceptions

Warning

Shall throw RuntimeException if access level was previously set


Accessibility Modification

  • « Componere\Method::setProtected
  • Componere\Method::getReflector »
  • PHP Manual
  • Componere\Method
  • Accessibility Modification

Componere\Method::setStatic

(Componere 2 >= 2.1.0)

Componere\Method::setStatic — Accessibility Modification

Description

public Componere\Method::setStatic ( void ) : Method

Return Values

The current Method


Reflection

  • « Componere\Method::setStatic
  • Componere\Value »
  • PHP Manual
  • Componere\Method
  • Reflection

Componere\Method::getReflector

(Componere 2 >= 2.1.0)

Componere\Method::getReflector — Reflection

Description

public Componere\Method::getReflector ( void ) : \ReflectionMethod

Shall create or return a ReflectionMethod

Return Values

A ReflectionMethod for the current method (cached)


The Componere\Value class

(Componere 2 >= 2.1.0)

Introduction

A Value represents a PHP variable of all types, including undefined

Class synopsis

final Componere\Value {
/* Constructor */
public __construct ([ $default ] )
/* Methods */
public setPrivate ( void ) : Value
public setProtected ( void ) : Value
public setStatic ( void ) : Value
public isPrivate ( void ) : bool
public isProtected ( void ) : bool
public isStatic ( void ) : bool
public hasDefault ( void ) : 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


Value Construction

  • « Componere\Value
  • Componere\Value::setPrivate »
  • PHP Manual
  • Componere\Value
  • Value Construction

Componere\Value::__construct

(Componere 2 >= 2.1.0)

Componere\Value::__construct — Value Construction

Description

public Componere\Value::__construct ([ $default ] )

Parameters

default

Exceptions

Warning

Shall throw InvalidArgumentException if default does not have a suitable value


Accessibility Modification

  • « Componere\Value::__construct
  • Componere\Value::setProtected »
  • PHP Manual
  • Componere\Value
  • Accessibility Modification

Componere\Value::setPrivate

(Componere 2 >= 2.1.0)

Componere\Value::setPrivate — Accessibility Modification

Description

public Componere\Value::setPrivate ( void ) : Value

Return Values

The current Value

Exceptions

Warning

Shall throw RuntimeException if access level was previously set


Accessibility Modification

  • « Componere\Value::setPrivate
  • Componere\Value::setStatic »
  • PHP Manual
  • Componere\Value
  • Accessibility Modification

Componere\Value::setProtected

(Componere 2 >= 2.1.0)

Componere\Value::setProtected — Accessibility Modification

Description

public Componere\Value::setProtected ( void ) : Value

Return Values

The current Value

Exceptions

Warning

Shall throw RuntimeException if access level was previously set


Accessibility Modification

  • « Componere\Value::setProtected
  • Componere\Value::isPrivate »
  • PHP Manual
  • Componere\Value
  • Accessibility Modification

Componere\Value::setStatic

(Componere 2 >= 2.1.0)

Componere\Value::setStatic — Accessibility Modification

Description

public Componere\Value::setStatic ( void ) : Value

Return Values

The current Value


Accessibility Detection

  • « Componere\Value::setStatic
  • Componere\Value::isProtected »
  • PHP Manual
  • Componere\Value
  • Accessibility Detection

Componere\Value::isPrivate

(Componere 2 >= 2.1.0)

Componere\Value::isPrivate — Accessibility Detection

Description

public Componere\Value::isPrivate ( void ) : bool


Accessibility Detection

  • « Componere\Value::isPrivate
  • Componere\Value::isStatic »
  • PHP Manual
  • Componere\Value
  • Accessibility Detection

Componere\Value::isProtected

(Componere 2 >= 2.1.0)

Componere\Value::isProtected — Accessibility Detection

Description

public Componere\Value::isProtected ( void ) : bool


Accessibility Detection

  • « Componere\Value::isProtected
  • Componere\Value::hasDefault »
  • PHP Manual
  • Componere\Value
  • Accessibility Detection

Componere\Value::isStatic

(Componere 2 >= 2.1.0)

Componere\Value::isStatic — Accessibility Detection

Description

public Componere\Value::isStatic ( void ) : bool


Value Interaction

  • « Componere\Value::isStatic
  • Componere Functions »
  • PHP Manual
  • Componere\Value
  • Value Interaction

Componere\Value::hasDefault

(Componere 2 >= 2.1.0)

Componere\Value::hasDefault — Value Interaction

Description

public Componere\Value::hasDefault ( void ) : bool


  • « Componere\Value::hasDefault
  • Componere\cast »
  • PHP Manual
  • Componere
  • Componere Functions

Componere Functions

Table of Contents

  • Componere\cast — Casting
  • Componere\cast_by_ref — Casting


Casting

  • « Componere Functions
  • Componere\cast_by_ref »
  • PHP Manual
  • Componere Functions
  • Casting

Componere\cast

(Componere 2 >= 2.1.2)

Componere\cast — Casting

Description

Componere\cast ( Type $type , $object ) : Type

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

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


Casting

  • « Componere\cast
  • Error Handling »
  • PHP Manual
  • Componere Functions
  • Casting

Componere\cast_by_ref

(Componere 2 >= 2.1.2)

Componere\cast_by_ref — Casting

Description

Componere\cast_by_ref ( Type $type , $object ) : Type

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

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


Error Handling and Logging

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • 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
    • 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


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.


  • « Requirements
  • Runtime Configuration »
  • PHP Manual
  • Installing/Configuring
  • Installation

Installation

There is no installation needed to use these functions; they are part of the PHP core.


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 | PHP_INI_ALL |
display_errors | "1" | PHP_INI_ALL |
display_startup_errors | "0" | PHP_INI_ALL |
log_errors | "0" | PHP_INI_ALL |
log_errors_max_len | "1024" | PHP_INI_ALL |
ignore_repeated_errors | "0" | PHP_INI_ALL |
ignore_repeated_source | "0" | PHP_INI_ALL |
report_memleaks | "1" | PHP_INI_ALL |
track_errors | "0" | PHP_INI_ALL | Deprecated as of PHP 7.2.0.
html_errors | "1" | PHP_INI_ALL |
xmlrpc_errors | "0" | PHP_INI_SYSTEM |
xmlrpc_error_number | "0" | PHP_INI_ALL |
docref_root | "" | PHP_INI_ALL |
docref_ext | "" | PHP_INI_ALL |
error_prepend_string | NULL | PHP_INI_ALL |
error_append_string | NULL | PHP_INI_ALL |
error_log | NULL | PHP_INI_ALL |
syslog.facility | "LOG_USER" | PHP_INI_SYSTEM | Available as of PHP 7.3.0.
syslog.filter | "no-ctrl" | PHP_INI_ALL | Available as of PHP 7.3.0.
syslog.ident | "php" | PHP_INI_SYSTEM | Available as of PHP 7.3.0.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

error_reporting integer

Set the error reporting level. The parameter is either an integer representing a bit field, or named constants. The error_reporting levels and constants are described in Predefined Constants, and in php.ini. To set at runtime, use the error_reporting() function. See also the display_errors directive.

PHP 5.3 or later, the default value is E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED. This setting does not show E_NOTICE, E_STRICT and E_DEPRECATED level errors. You may want to show them during development. Prior to PHP 5.3.0, the default value is E_ALL & ~E_NOTICE & ~E_STRICT.

Note:

Enabling E_NOTICE during development has some benefits. For debugging purposes: NOTICE messages will warn you about possible bugs in your code. For example, use of unassigned values is warned. It is extremely useful to find typos and to save time for debugging. NOTICE messages will warn you about bad style. For example, $arr[item] is better to be written as $arr['item'] since PHP tries to treat "item" as constant. If it is not a constant, PHP assumes it is a string index for the array.

Note:

Prior to PHP 5.4.0 E_STRICT was not included within E_ALL, so you would have to explicitly enable this kind of error level in PHP < 5.4.0. Enabling E_STRICT during development has some benefits. STRICT messages provide suggestions that can help ensure the best interoperability and forward compatibility of your code. These messages may include things such as calling non-static methods statically, defining properties in a compatible class definition while defined in a used trait, and prior to PHP 5.3 some deprecated features would issue E_STRICT errors such as assigning objects by reference upon instantiation.

Note: PHP Constants outside of PHP

Using PHP Constants outside of PHP, like in httpd.conf, will have no useful meaning so in such cases the integer values are required. And since error levels will be added over time, the maximum value (for E_ALL) will likely change. So in place 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. The value is available as of PHP 5.2.4. In earlier versions, this directive was of type boolean.

Note:

This is a feature to support your development and should never be used on production systems (e.g. systems connected to the internet).

Note:

Although display_errors may be set at runtime (with ini_set()), it won't have any effect if the script has fatal errors. This is because the desired runtime action does not get executed.

display_startup_errors boolean

Even when display_errors is on, errors that occur during PHP's startup sequence are not displayed. It's strongly recommended to keep display_startup_errors off, except for debugging.

log_errors boolean

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

Note:

You're strongly advised to use error logging in place of error displaying on production web sites.

log_errors_max_len integer

Set the maximum length of log_errors in bytes. In error_log information about the source is added. The default is 1024 and 0 allows to not apply any maximum length at all. This length is applied to logged errors, displayed errors and also to $php_errormsg, but not to explicitly called functions such as error_log().

When an integer is used, the value is measured in bytes. Shorthand notation, as described in this FAQ, may also be used.
ignore_repeated_errors boolean

Do not log repeated messages. Repeated errors must occur in the same file on the same line unless ignore_repeated_source is set true.

ignore_repeated_source boolean

Ignore source of message when ignoring repeated messages. When this setting is On you will not log errors with repeated messages from different files or sourcelines.

report_memleaks boolean

If this parameter is set to On (the default), this parameter will show a report of memory leaks detected by the Zend memory manager. This report will be 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 boolean

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

html_errors boolean

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 boolean

If enabled, turns off normal error reporting and formats errors as XML-RPC error message.

xmlrpc_error_number integer

Used as the value of the XML-RPC faultCode element.

docref_root string

The new error format contains a reference to a page describing the error or function causing the error. In case of manual pages you can download the manual in your language and set this ini directive to the URL of your local copy. If your local copy of the manual can be reached by "/manual/" you can simply use docref_root=/manual/. Additional you have to set docref_ext to match the fileextensions of your copy docref_ext=.html. It is possible to use external references. For example you can use docref_root=http://manual/en/ or docref_root="http://landonize.it/?how=url&theme=classic&filter=Landon &url=http%3A%2F%2Fwww.php.net%2F"

Most of the time you want the docref_root value to end with a slash "/". But see the second example above which does not have nor need it.

Note:

This is a feature to support your development since it makes it easy to lookup a function description. However it should never be used on production systems (e.g. systems connected to the internet).

docref_ext string

See docref_root.

Note:

The value of docref_ext must begin with a dot ".".

error_prepend_string string

String to output before an error message.

error_append_string string

String to output after an error message.

error_log string

Name of the file where script errors should be logged. The file should be writable by the web server's user. If the special value syslog is used, the errors are sent to the system logger instead. On Unix, this means syslog(3) and on Windows 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().

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. There are three supported filter types:

  • all – all characters
  • no-ctrl – all characters except control characters
  • ascii – all printable ASCII characters and NL
Only effective if error_log is set to "syslog".

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.

Note: You may use these constant names in php.ini but not outside of PHP, like in httpd.conf, where you'd use the bitmask values instead.

Errors and Logging
Value | Constant | Description | Note
1 | E_ERROR (integer) | Fatal run-time errors. These indicate errors that can not be recovered from, such as a memory allocation problem. Execution of the script is halted. |
2 | E_WARNING (integer) | Run-time warnings (non-fatal errors). Execution of the script is not halted. |
4 | E_PARSE (integer) | Compile-time parse errors. Parse errors should only be generated by the parser. |
8 | E_NOTICE (integer) | Run-time notices. Indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script. |
16 | E_CORE_ERROR (integer) | Fatal errors that occur during PHP's initial startup. This is like an E_ERROR, except it is generated by the core of PHP. |
32 | E_CORE_WARNING (integer) | Warnings (non-fatal errors) that occur during PHP's initial startup. This is like an E_WARNING, except it is generated by the core of PHP. |
64 | E_COMPILE_ERROR (integer) | Fatal compile-time errors. This is like an E_ERROR, except it is generated by the Zend Scripting Engine. |
128 | E_COMPILE_WARNING (integer) | Compile-time warnings (non-fatal errors). This is like an E_WARNING, except it is generated by the Zend Scripting Engine. |
256 | E_USER_ERROR (integer) | User-generated error message. This is like an E_ERROR, except it is generated in PHP code by using the PHP function trigger_error(). |
512 | E_USER_WARNING (integer) | User-generated warning message. This is like an E_WARNING, except it is generated in PHP code by using the PHP function trigger_error(). |
1024 | E_USER_NOTICE (integer) | User-generated notice message. This is like an E_NOTICE, except it is generated in PHP code by using the PHP function trigger_error(). |
2048 | E_STRICT (integer) | Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code. | Not included in E_ALL prior to PHP 5.4.0
4096 | E_RECOVERABLE_ERROR (integer) | Catchable fatal error. It indicates that a probably dangerous error occurred, but did not leave the Engine in an unstable state. If the error is not caught by a user defined handle (see also set_error_handler()), the application aborts as it was an E_ERROR. | As of PHP 5.2.0
8192 | E_DEPRECATED (integer) | Run-time notices. Enable this to receive warnings about code that will not work in future versions. | As of PHP 5.3.0
16384 | E_USER_DEPRECATED (integer) | User-generated warning message. This is like an E_DEPRECATED, except it is generated in PHP code by using the PHP function trigger_error(). | As of PHP 5.3.0
32767 | E_ALL (integer) | All errors and warnings, as supported, except of level E_STRICT prior to PHP 5.4.0. | 32767 in PHP 5.4.x, 30719 in PHP 5.3.x, 6143 in PHP 5.2.x, 2047 previously

The above values (either numerical or symbolic) are used to build up a bitmask that specifies which errors to report. You can use the bitwise operators to combine these values or mask out certain types of errors. Note that only '|', '~', '!', '^' and '&' will be understood within php.ini.


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

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


Generates a backtrace

  • « Error Handling Functions
  • debug_print_backtrace »
  • PHP Manual
  • Error Handling Functions
  • Generates a backtrace

debug_backtrace

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

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

As of 5.3.6, 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.
Before 5.3.6, the only values recognized are TRUE or FALSE, which are the same as setting or not setting the DEBUG_BACKTRACE_PROVIDE_OBJECT option respectively.

limit

As of 5.4.0, this parameter can be used to limit the number of stack frames returned. By default (limit=0) it returns all stack frames.

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 | integer | The current line number. See also __LINE__.
file | string | The current file name. See also __FILE__.
class | string | The current class name. See also __CLASS__
object | object | The current object.
type | string | The current call type. If a method call, "->" is returned. If a static method call, "::" is returned. If a function call, nothing is returned.
args | array | If inside a function, this lists the functions arguments. If inside an included file, this lists the included file name(s).

Changelog

Version | Description
5.4.0 | Added the optional parameter limit.
5.3.6 | The parameter provide_object changed to options and additional option DEBUG_BACKTRACE_IGNORE_ARGS is added.
5.2.5 | Added the optional parameter provide_object.
5.1.1 | Added the current object as a possible return element.

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


Prints a backtrace

  • « debug_backtrace
  • error_clear_last »
  • PHP Manual
  • Error Handling Functions
  • Prints a backtrace

debug_print_backtrace

(PHP 5, PHP 7)

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

As of 5.3.6, 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

As of 5.4.0, this parameter can be used to limit the number of stack frames printed. By default (limit=0) it prints all stack frames.

Return Values

No value is returned.

Changelog

Version | Description
5.4.0 | Added the optional parameter limit.
5.3.6 | Added the optional parameter options.

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


Clear the most recent error

  • « debug_print_backtrace
  • error_get_last »
  • PHP Manual
  • Error Handling Functions
  • Clear the most recent error

error_clear_last

(PHP 7)

error_clear_last — Clear the most recent error

Description

error_clear_last ( void ) : void

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


Get the last occurred error

  • « error_clear_last
  • error_log »
  • PHP Manual
  • Error Handling Functions
  • Get the last occurred error

error_get_last

(PHP 5 >= 5.2.0, PHP 7)

error_get_last — Get the last occurred error

Description

error_get_last ( void ) : array

Gets information about the last error that occurred.

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


Send an error message to the defined error handling routines

  • « error_get_last
  • error_reporting »
  • PHP Manual
  • Error Handling Functions
  • Send an error message to the defined error handling routines

error_log

(PHP 4, PHP 5, PHP 7)

error_log — Send an error message to the defined error handling routines

Description

error_log ( string $message [, int $message_type = 0 [, string $destination [, string $extra_headers ]]] ) : 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, extra_headers is used.
2 | No longer an option.
3 | message is appended to the file destination. A newline is not automatically added to the end of the message string.
4 | message is sent directly to the SAPI logging handler.

destination

The destination. Its meaning depends on the message_type parameter as described above.

extra_headers

The extra headers. It's used when the message_type parameter is set to 1. This message type uses the same internal function as mail() does.

Return Values

Returns TRUE on success or FALSE on failure.

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

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");
?>

Changelog

Version | Description
5.2.7 | The possible value of 4 was added to message_type.


Sets which PHP errors are reported

  • « error_log
  • restore_error_handler »
  • PHP Manual
  • Error Handling Functions
  • Sets which PHP errors are reported

error_reporting

(PHP 4, PHP 5, PHP 7)

error_reporting — Sets which PHP errors are reported

Description

error_reporting ([ int $level ] ) : 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 level is not set, error_reporting() will just return the current error reporting level.

Parameters

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 old error_reporting level or the current level if no level parameter is given.

Changelog

Version | Description
5.4.0 | E_STRICT became part of E_ALL.
5.3.0 | E_DEPRECATED and E_USER_DEPRECATED introduced.
5.2.0 | E_RECOVERABLE_ERROR introduced.

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 (see changelog)
error_reporting(E_ALL);

// Report all PHP errors
error_reporting(-1);

// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);

?>

Notes

Warning

Most of E_STRICT errors are evaluated at the compile time thus such errors are not reported in the file where error_reporting is enhanced to include E_STRICT errors (and vice versa).

Tip

Passing in the value -1 will show every possible error, even when new levels and constants are added in future PHP versions. The E_ALL constant also behaves this way as of PHP 5.4.

See Also

  • The display_errors directive
  • The html_errors directive
  • The xmlrpc_errors directive
  • ini_set() - Sets the value of a configuration option


Restores the previous error handler function

  • « error_reporting
  • restore_exception_handler »
  • PHP Manual
  • Error Handling Functions
  • Restores the previous error handler function

restore_error_handler

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

restore_error_handler — Restores the previous error handler function

Description

restore_error_handler ( void ) : bool

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

Return Values

This function 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
  • restore_exception_handler() - Restores the previously defined exception handler function
  • trigger_error() - Generates a user-level error/warning/notice message


Restores the previously defined exception handler function

  • « restore_error_handler
  • set_error_handler »
  • PHP Manual
  • Error Handling Functions
  • Restores the previously defined exception handler function

restore_exception_handler

(PHP 5, PHP 7)

restore_exception_handler — Restores the previously defined exception handler function

Description

restore_exception_handler ( void ) : bool

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

Return Values

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


Sets a user-defined error handler function

  • « restore_exception_handler
  • set_exception_handler »
  • PHP Manual
  • Error Handling Functions
  • Sets a user-defined error handler function

set_error_handler

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

set_error_handler — Sets a user-defined error handler function

Description

set_error_handler ( callable $error_handler [, int $error_types = E_ALL | E_STRICT ] ) : mixed

Sets a user function (error_handler) to handle errors in a script.

This function can be used for defining your own way of handling errors during runtime, for example in applications in which you need to do cleanup of data/files when a critical error happens, or when you need to trigger an error under certain conditions (using trigger_error()).

It is important to remember that the standard PHP error handler is completely bypassed for the error types specified by error_types unless the callback function returns FALSE. error_reporting() settings will have no effect and your error handler will be called regardless - however you are still able to read the current value of error_reporting and act appropriately. Of particular note is that this value will be 0 if the statement that caused the error was prepended by the @ error-control operator.

Also note that it is your responsibility to die() if necessary. If the error-handler function returns, script execution will continue with the next statement after the one that caused an error.

The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING 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

error_handler

A callback with the following signature. NULL may be passed instead, to reset this handler to its default state. Instead of a function name, an array containing an object reference and a method name can also be supplied.

handler ( int $errno , string $errstr [, string $errfile [, int $errline [, array $errcontext ]]] ) : bool
errno
The first parameter, errno, contains the level of the error raised, as an integer.
errstr
The second parameter, errstr, contains the error message, as a string.
errfile
The third parameter is optional, errfile, which contains the filename that the error was raised in, as a string.
errline
The fourth parameter is optional, errline, which contains the line number the error was raised at, as an integer.
errcontext
The fifth parameter is optional, errcontext, which is an array that points to the active symbol table at the point the error occurred. In other words, errcontext will contain an array of every variable that existed in the scope the error was triggered in. User error handler must not modify error context.
Warning

This parameter has been DEPRECATED as of PHP 7.2.0. Relying on it is highly discouraged.

If the function returns FALSE then the normal error handler continues.

error_types

Can be used to mask the triggering of the error_handler function just like the error_reporting ini setting controls which errors are shown. Without this mask set the error_handler will be called for every error regardless to the setting of the error_reporting setting.

Return Values

Returns a string containing the previously defined error handler (if any). If the built-in error handler is used NULL is returned. NULL is also returned in case of an error such as an invalid callback. If the previous error handler was a class method, this function will return an indexed array with the class and the method name.

Changelog

Version | Description
7.2.0 | errcontext became deprecated. Usage of this parameter now emits an E_DEPRECATED notice.
5.5.0 | error_handler now accepts NULL.
5.2.0 | The error handler must return FALSE to populate $php_errormsg.

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

    switch ($errno) {
    case E_USER_ERROR:
        echo "<b>My ERROR</b> [$errno] $errstr<br />\n";
        echo "  Fatal error on line $errline in file $errfile";
        echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
        echo "Aborting...<br />\n";
        exit(1);
        break;

    case E_USER_WARNING:
        echo "<b>My WARNING</b> [$errno] $errstr<br />\n";
        break;

    case E_USER_NOTICE:
        echo "<b>My NOTICE</b> [$errno] $errstr<br />\n";
        break;

    default:
        echo "Unknown error type: [$errno] $errstr<br />\n";
        break;
    }

    /* Don't execute PHP internal error handler */
    return true;
}

// function to test the error handling
function scale_by_log($vect, $scale)
{
    if (!is_numeric($scale) || $scale <= 0) {
        trigger_error("log(x) for x <= 0 is undefined, you used: scale = $scale", E_USER_ERROR);
    }

    if (!is_array($vect)) {
        trigger_error("Incorrect input vector, array of values expected", E_USER_WARNING);
        return null;
    }

    $temp = array();
    foreach($vect as $pos => $value) {
        if (!is_numeric($value)) {
            trigger_error("Value at position $pos is not a number, using 0 (zero)", E_USER_NOTICE);
            $value = 0;
        }
        $temp[$pos] = log($scale) * $value;
    }

    return $temp;
}

// set to the user defined error handler
$old_error_handler = set_error_handler("myErrorHandler");

// trigger some errors, first define a mixed array with a non-numeric item
echo "vector a\n";
$a = array(2, 3, "foo", 5.5, 43.3, 21.11);
print_r($a);

// now generate second array
echo "----\nvector b - a notice (b = log(PI) * a)\n";
/* Value at position $pos is not a number, using 0 (zero) */
$b = scale_by_log($a, M_PI);
print_r($b);

// this is trouble, we pass a string instead of an array
echo "----\nvector c - a warning\n";
/* Incorrect input vector, array of values expected */
$c = scale_by_log("not array", 2.3);
var_dump($c); // NULL

// this is a critical error, log of zero or negative number is undefined
echo "----\nvector d - fatal error\n";
/* log(x) for x <= 0 is undefined, you used: scale = $scale" */
$d = scale_by_log($a, -2.5);
var_dump($d); // Never reached
?>

The above example will output something similar to:

vector a
Array
(
    [0] => 2
    [1] => 3
    [2] => foo
    [3] => 5.5
    [4] => 43.3
    [5] => 21.11
)
----
vector b - a notice (b = log(PI) * a)
<b>My NOTICE</b> [1024] Value at position 2 is not a number, using 0 (zero)<br />
Array
(
    [0] => 2.2894597716988
    [1] => 3.4341896575482
    [2] => 0
    [3] => 6.2960143721717
    [4] => 49.566804057279
    [5] => 24.165247890281
)
----
vector c - a warning
<b>My WARNING</b> [512] Incorrect input vector, array of values expected<br />
NULL
----
vector d - fatal error
<b>My ERROR</b> [256] log(x) for x <= 0 is undefined, you used: scale = -2.5<br />
  Fatal error on line 35 in file trigger_error.php, PHP 5.2.1 (FreeBSD)<br />
Aborting...<br />

See Also

  • ErrorException
  • error_reporting() - Sets which PHP errors are reported
  • restore_error_handler() - Restores the previous error handler function
  • trigger_error() - Generates a user-level error/warning/notice message
  • error level constants
  • information about the callback type


Sets a user-defined exception handler function

  • « set_error_handler
  • trigger_error »
  • PHP Manual
  • Error Handling Functions
  • Sets a user-defined exception handler function

set_exception_handler

(PHP 5, PHP 7)

set_exception_handler — Sets a user-defined exception handler function

Description

set_exception_handler ( callable $exception_handler ) : callable

Sets the default exception handler if an exception is not caught within a try/catch block. Execution will stop after the exception_handler is called.

Parameters

exception_handler

Name of the function to be called when an uncaught exception occurs. This handler function needs to accept one parameter, which will be the exception object that was thrown. This is the handler signature before PHP 7:

handler ( Exception $ex ) : void

Since PHP 7, most errors are reported by throwing Error exceptions, which will be caught by the handler as well. Both Error and Exception implements the Throwable interface. This is the handler signature since PHP 7:

handler ( Throwable $ex ) : void

NULL may be passed instead, to reset this handler to its default state.

Caution

Note that providing an explicit Exception type hint for the ex parameter in your callback will cause issues with the changed exception hierarchy in PHP 7.

Return Values

Returns the name of the previously defined exception handler, or NULL on error. If no previous handler was defined, NULL is also returned.

Changelog

Version | Description
7.0.0 | The type of parameter passed into exception_handler changed from Exception to Throwable
5.5.0 | Previously, if NULL was passed then this function returned TRUE. It returns the previous handler since PHP 5.5.0.

Examples

Example #1 set_exception_handler() example

<?php
function exception_handler($exception) {
  echo "Uncaught exception: " , $exception->getMessage(), "\n";
}

set_exception_handler('exception_handler');

throw new Exception('Uncaught Exception');
echo "Not Executed\n";
?>

See Also

  • 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
  • information about the callback type
  • PHP 5 Exceptions


Generates a user-level error/warning/notice message

  • « set_exception_handler
  • user_error »
  • PHP Manual
  • Error Handling Functions
  • Generates a user-level error/warning/notice message

trigger_error

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

trigger_error — Generates a user-level error/warning/notice message

Description

trigger_error ( string $error_msg [, int $error_type = E_USER_NOTICE ] ) : bool

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

error_msg

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_type

The designated error type for this error. It only works with the E_USER family of constants, and will default to E_USER_NOTICE.

Return Values

This function returns FALSE if wrong error_type is specified, TRUE otherwise.

Examples

Example #1 trigger_error() example

See set_error_handler() for a more extensive example.

<?php
if ($divisor == 0) {
    trigger_error("Cannot divide by zero", E_USER_ERROR);
}
?>

Notes

Warning

HTML entities in error_msg 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


Alias of trigger_error

  • « trigger_error
  • FFI »
  • PHP Manual
  • Error Handling Functions
  • Alias of trigger_error

user_error

(PHP 4, PHP 5, PHP 7)

user_error — Alias of trigger_error()

Description

This function is an alias of: trigger_error().


Foreign Function Interface

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • 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\Exception — FFI Exceptions
  • FFI\ParserException — FFI Parser Exceptions


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 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
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

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" | PHP_INI_SYSTEM |
ffi.preload | "" | PHP_INI_SYSTEM |
For further details and definitions of the PHP_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().


  • « Resource Types
  • Examples »
  • PHP Manual
  • FFI
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


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!

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)


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:

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

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

FFI {
/* Methods */
public static addr ( FFI\CData &$ptr ) : FFI\CData
public static alignof ( mixed &$ptr ) : int
public static arrayType ( FFI\CType $type , array $dims ) : FFI\CType
public static cast ( mixed $type , FFI\CData &$ptr ) : FFI\CData
public cast ( mixed $type , FFI\CData &$ptr ) : FFI\CData
public static cdef ([ string $code = "" [, string $lib ]] ) : FFI
public static free ( FFI\CData &$ptr ) : void
public static isNull ( FFI\CData &$ptr ) : bool
public static load ( string $filename ) : FFI
public static memcmp ( mixed &$ptr1 , mixed &$ptr2 , int $size ) : int
public static memcpy ( FFI\CData &$dst , mixed &$src , int $size ) : void
public static memset ( FFI\CData &$ptr , int $ch , int $size ) : void
public static new ( mixed $type [, bool $owned = TRUE [, bool $persistent = FALSE ]] ) : FFI\CData
public new ( mixed $type [, bool $owned = TRUE [, bool $persistent = FALSE ]] ) : FFI\CData
public static scope ( string $scope_name ) : FFI
public static sizeof ( mixed &$ptr ) : int
public static string ( FFI\CData &$ptr [, int $size ] ) : string
public static type ( mixed $type ) : FFI\CType
public type ( mixed $type ) : FFI\CType
public static typeof ( FFI\CData &$ptr ) : FFI\CType
}

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


Creates an unmanaged pointer to C data

  • « FFI
  • FFI::alignof »
  • PHP Manual
  • FFI
  • Creates an unmanaged pointer to C data

FFI::addr

(PHP 7 >= 7.4.0)

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.


Gets the alignment

  • « FFI::addr
  • FFI::arrayType »
  • PHP Manual
  • FFI
  • Gets the alignment

FFI::alignof

(PHP 7 >= 7.4.0)

FFI::alignof — Gets the alignment

Description

public static FFI::alignof ( mixed &$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.


Dynamically constructs a new C array type

  • « FFI::alignof
  • FFI::cast »
  • PHP Manual
  • FFI
  • Dynamically constructs a new C array type

FFI::arrayType

(PHP 7 >= 7.4.0)

FFI::arrayType — Dynamically constructs a new C array type

Description

public static FFI::arrayType ( FFI\CType $type , array $dims ) : FFI\CType

Dynamically constructs a new C array type with elements of type defined by type, and dimensions specified by dims. 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.

dims

The dimensions of the type as array.

Return Values

Returns the freshly created FFI\CType object.


Performs a C type cast

  • « FFI::arrayType
  • FFI::cdef »
  • PHP Manual
  • FFI
  • Performs a C type cast

FFI::cast

(PHP 7 >= 7.4.0)

FFI::cast — Performs a C type cast

Description

public static FFI::cast ( mixed $type , FFI\CData &$ptr ) : FFI\CData
public FFI::cast ( mixed $type , FFI\CData &$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. If this method is called statically, it must only use predefined C type names (e.g. int, char, etc.); if the method is called as instance method, 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.


Creates a new FFI object

  • « FFI::cast
  • FFI::free »
  • PHP Manual
  • FFI
  • Creates a new FFI object

FFI::cdef

(PHP 7 >= 7.4.0)

FFI::cdef — Creates a new FFI object

Description

public static FFI::cdef ([ string $code = "" [, string $lib ]] ) : 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, 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.


Releases an unmanaged data structure

  • « FFI::cdef
  • FFI::isNull »
  • PHP Manual
  • FFI
  • Releases an unmanaged data structure

FFI::free

(PHP 7 >= 7.4.0)

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.


Checks whether a FFI\CData is a null pointer

  • « FFI::free
  • FFI::load »
  • PHP Manual
  • FFI
  • Checks whether a FFI\CData is a null pointer

FFI::isNull

(PHP 7 >= 7.4.0)

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.


Loads C declarations from a C header file

  • « FFI::isNull
  • FFI::memcmp »
  • PHP Manual
  • FFI
  • Loads C declarations from a C header file

FFI::load

(PHP 7 >= 7.4.0)

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.

Note:

C preprocessor directives are not supported, i.e. #include, #define and CPP macros do not work.

Return Values

Returns the freshly created FFI object.

See Also

  • FFI::scope() - Instantiates an FFI object with C declarations parsed during preloading


Compares memory areas

  • « FFI::load
  • FFI::memcpy »
  • PHP Manual
  • FFI
  • Compares memory areas

FFI::memcmp

(PHP 7 >= 7.4.0)

FFI::memcmp — Compares memory areas

Description

public static FFI::memcmp ( mixed &$ptr1 , mixed &$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 < 0 if the contents of the memory area starting at ptr1 are considered less than the contents of the memory area starting at ptr2, > 0 if the contents of the first memory area are considered greater than the second, and 0 if they are equal.


Copies one memory area to another

  • « FFI::memcmp
  • FFI::memset »
  • PHP Manual
  • FFI
  • Copies one memory area to another

FFI::memcpy

(PHP 7 >= 7.4.0)

FFI::memcpy — Copies one memory area to another

Description

public static FFI::memcpy ( FFI\CData &$dst , mixed &$src , int $size ) : void

Copies size bytes from the memory area src to the memory area dst. Both src and dst can be any native data structures (FFI\CData) or PHP strings.

Parameters

dst

The start of the memory area to copy to.

src

The start of the memory area to copy from.

size

The number of bytes to copy.

Return Values

No value is returned.


Fills a memory area

  • « FFI::memcpy
  • FFI::new »
  • PHP Manual
  • FFI
  • Fills a memory area

FFI::memset

(PHP 7 >= 7.4.0)

FFI::memset — Fills a memory area

Description

public static FFI::memset ( FFI\CData &$ptr , int $ch , int $size ) : void

Fills size bytes of the memory area pointed to by ptr with the given byte ch.

Parameters

ptr

The start of the memory area to fill.

ch

The byte to fill with.

size

The number of bytes to fill.

Return Values

No value is returned.


Creates a C data structure

  • « FFI::memset
  • FFI::scope »
  • PHP Manual
  • FFI
  • Creates a C data structure

FFI::new

(PHP 7 >= 7.4.0)

FFI::new — Creates a C data structure

Description

public static FFI::new ( mixed $type [, bool $owned = TRUE [, bool $persistent = FALSE ]] ) : FFI\CData
public FFI::new ( mixed $type [, bool $owned = TRUE [, bool $persistent = FALSE ]] ) : FFI\CData

Creates a native data structure of the given C type. If this method is called statically, it must only use predefined C type names (e.g. int, char, etc.); if the method is called as instance method, 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.


Instantiates an FFI object with C declarations parsed during preloading

  • « FFI::new
  • FFI::sizeof »
  • PHP Manual
  • FFI
  • Instantiates an FFI object with C declarations parsed during preloading

FFI::scope

(PHP 7 >= 7.4.0)

FFI::scope — Instantiates an FFI object with C declarations parsed during preloading

Description

public static FFI::scope ( string $scope_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

scope_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


Gets the size of C data or types

  • « FFI::scope
  • FFI::string »
  • PHP Manual
  • FFI
  • Gets the size of C data or types

FFI::sizeof

(PHP 7 >= 7.4.0)

FFI::sizeof — Gets the size of C data or types

Description

public static FFI::sizeof ( mixed &$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.


Creates a PHP string from a memory area

  • « FFI::sizeof
  • FFI::type »
  • PHP Manual
  • FFI
  • Creates a PHP string from a memory area

FFI::string

(PHP 7 >= 7.4.0)

FFI::string — Creates a PHP string from a memory area

Description

public static FFI::string ( FFI\CData &$ptr [, int $size ] ) : 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, ptr must be a zero terminated array of C chars.

Return Values

The freshly created PHP string.


Creates an FFI\CType object from a C declaration

  • « FFI::string
  • FFI::typeof »
  • PHP Manual
  • FFI
  • Creates an FFI\CType object from a C declaration

FFI::type

(PHP 7 >= 7.4.0)

FFI::type — Creates an FFI\CType object from a C declaration

Description

public static FFI::type ( mixed $type ) : FFI\CType
public FFI::type ( mixed $type ) : FFI\CType

This function creates and returns a FFI\CType object for the given string containing a C type declaration. If this method is called statically, it must only use predefined C type names (e.g. int, char, etc.); if the method is called as instance method, 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.

Return Values

Returns the freshly created FFI\CType object.


Gets the FFI\CType of FFI\CData

  • « FFI::type
  • FFI\CData »
  • PHP Manual
  • FFI
  • Gets the FFI\CType of FFI\CData

FFI::typeof

(PHP 7 >= 7.4.0)

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.


C Data Handles

(PHP 7 >= 7.4.0)

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

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

FFI\CData {
}


  • « FFI\CData
  • FFI\Exception »
  • PHP Manual
  • FFI
  • C Type Handles

C Type Handles

(PHP 7 >= 7.4.0)

Introduction

Class synopsis

FFI\CType {
}


FFI Exceptions

(PHP 7 >= 7.4.0)

Introduction

Class synopsis

FFI\Exception extends Error implements Throwable {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Error::getMessage ( void ) : string
final public Error::getPrevious ( void ) : Throwable
final public Error::getCode ( void ) : mixed
final public Error::getFile ( void ) : string
final public Error::getLine ( void ) : int
final public Error::getTrace ( void ) : array
final public Error::getTraceAsString ( void ) : string
public Error::__toString ( void ) : string
final private Error::__clone ( void ) : void
}


FFI Parser Exceptions

(PHP 7 >= 7.4.0)

Introduction

Class synopsis

FFI\ParserException extends FFI\Exception implements Throwable {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
}


htaccess-like support for all SAPIs

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types


Introduction

The htscanner extension gives the possibility to use htaccess-like file to configure PHP per directory, just like apache's htaccess. It is especially useful with fastcgi (IIS5/6/7, lighttpd, etc.).


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

PHP version 5.2.0 or greater.


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/htscanner


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

htscanner Configure Options
Name | Default | Changeable | Changelog
htscanner.config_file | ".htscanner" | PHP_INI_SYSTEM |
htscanner.default_docroot | "/" | PHP_INI_SYSTEM |
htscanner.default_ttl | "300" | PHP_INI_SYSTEM |
htscanner.stop_on_error | "Off" | PHP_INI_SYSTEM |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

htscanner.config_file string

Filename to use as configuration file.

htscanner.default_docroot string

Default document root.

htscanner.default_ttl int

Cache time out for the configuration data, in seconds.

htscanner.stop_on_error int

Stop on error (parse error, cannot set an ini setting).


  • « Runtime Configuration
  • inclued »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

This extension has no resource types defined.


Inclusion hierarchy viewer

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Example that implements inclued into an application
  • inclued Functions
    • inclued_get_data — Get the inclued data


Introduction

Traces through and dumps the hierarchy of file inclusions and class inheritance at runtime.

The files may have been included using include, include_once, require, or require_once.

Class inheritance dependencies are also reported.


Requirements

PHP version 5.1.0 or greater.

The included gengraph.php file utilizes the » graphviz library, however, this is not 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/inclued


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

inclued Configure Options
Name | Default | Changeable | Changelog
inclued.enabled | Off | PHP_INI_SYSTEM |
inclued.dumpdir | NULL | PHP_INI_SYSTEM |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

inclued.enabled bool

Whether or not to enable inclued.

inclued.dumpdir string

Location (path) to the directory that stores inclued files. If set, each PHP request will create a file. These files are serialized versions of what inclued_get_data() would produce, so may be unserialized with unserialize().

Caution

Because every request creates a file, this directory may fill up fast!


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.

This extension has no constants defined.


  • « Predefined Constants
  • Example that implements inclued into an application »
  • PHP Manual
  • inclued
  • Examples

Examples

Table of Contents

  • Example that implements inclued into an application


Example that implements inclued into an application

This example demonstrates the process of implementing inclued into an existing application, and viewing the results.

Example #1 Getting the data within the PHP application itself (function)

<?php
// File to store the inclued information
$fp = fopen('/tmp/wp.ser', 'w');
if ($fp) {
    $clue = inclued_get_data();
    if ($clue) {
        fwrite($fp, serialize($clue));
    }
    fclose($fp);
}
?>

Now that some data exists, it's time to make sense of it in the form of a graph. The inclued extension includes a PHP file named gengraph.php that creates a dot file that requires the » graphviz library. However, this form is not required.

Example #2 Example use of gengraph.php

This example creates an image named inclued.png that shows the inclued data.

# First, create the dot file
$ php gengraph.php -i /tmp/wp.ser -o wp.dot

# Next, create the image
$ dot -Tpng -o inclued.png wp.dot

Example #3 Listing data via inclued dumps (configuration)

When using the inclued.dumpdir directive, files (include clues) are dumped with every request. Here's one way to list those files, and unserialize() them.

<?php
$path = ini_get('inclued.dumpdir');
if ($path && is_dir($path)) {

    echo "Path: $path", PHP_EOL;

    $inclues = new GlobIterator($path . DIRECTORY_SEPARATOR . 'inclued*');

    if ($inclues->count() === 0) {
        echo 'No clues today', PHP_EOL;
        exit;
    }

    foreach ($inclues as $inclue) {

        echo 'Inclued file: ', $inclue->getFilename(), PHP_EOL;

        $data = file_get_contents($inclue->getPathname());
        if ($data) {
            $inc = unserialize($data);
            echo ' -- filename: ', $inc['request']['SCRIPT_FILENAME'], PHP_EOL;
            echo ' -- number of includes: ', count($inc['includes']), PHP_EOL;
        }
        echo PHP_EOL;
    }
} else {
    echo 'I am totally clueless today.', PHP_EOL;
}
?>

The above example will output something similar to:

PATH: /tmp/inclued
Inclued file: inclued.56521.1
 -- filename: /Users/philip/test.php
 -- number of includes: 1

Inclued file: inclued.56563.1
 -- filename: /tmp/none.php
 -- number of includes: 0

Inclued file: inclued.56636.1
 -- filename: /tmp/three.php
 -- number of includes: 3


  • « Example that implements inclued into an application
  • inclued_get_data »
  • PHP Manual
  • inclued
  • inclued Functions

inclued Functions

Table of Contents

  • inclued_get_data — Get the inclued data


Get the inclued data

  • « inclued Functions
  • Memtrack »
  • PHP Manual
  • inclued Functions
  • Get the inclued data

inclued_get_data

(PECL inclued >= 0.1.0)

inclued_get_data — Get the inclued data

Description

inclued_get_data ( void ) : array

Get the inclued data.

Parameters

This function has no parameters.

Return Values

The inclued data.

Examples

Example #1 inclued_get_data() example

See the inclued examples section for ways to create graphs with this data.

<?php
include 'x.php';

$clue = inclued_get_data();

print_r($clue);
?>

The above example will output something similar to:

Array
(
  [includes] => Array
    (
      [0] => Array
        (
          [operation] => include
          [op_type] => 2
          [filename] => x.php
          [opened_path] => /tmp/x.php
          [fromfile] => /tmp/z.php
          [fromline] => 2
        )
    )
)

See Also

  • inclued examples
  • debug_backtrace() - Generates a backtrace
  • include - include


Memtrack

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage


Introduction

The purpose of this extension is to detect the most memory hungry scripts and functions.

memtrack tracks memory consumption in PHP scripts and produces reports (warnings) when the consumption reaches certain levels set by the user. This is achieved by replacing default executor function by a special function which compares memory usage before and after running the original executor - this way we can tell how much the memory usage has changed during the execution of the current part of the code.

Zend Engine runs its executor for each opcode array (op_array), which usually means function, plain script and such, so memtrack doesn't have any noticeable effect on performance.

memtrack doesn't provide any functions, there are only INI directives which allow you to configure the way it should work.

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.


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/memtrack


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Memtrack Configuration Options
Name | Default | Changeable
memtrack.enabled | "0" | PHP_INI_SYSTEM
memtrack.soft_limit | "0" | PHP_INI_ALL
memtrack.hard_limit | "0" | PHP_INI_ALL
memtrack.vm_limit | "0" | PHP_INI_ALL
memtrack.ignore_functions | "" | PHP_INI_SYSTEM
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

memtrack.enabled boolean

Disables or enables the extension. Default value is 0, i.e. disabled.

memtrack.soft_limit int

Soft memory limit.

The extension checks memory consumption before and after executing an op_array and produces a warning is the difference between the two values is equal to or greater than the soft limit, but only if the function is not ignored.

Setting this option to 0 also disables both soft and hard limit warnings. Default value is 0, i.e. no warnings is produced.

memtrack.hard_limit int

Hard memory limit.

The extension checks memory consumption before and after executing an op_array and produces a warning is the difference between the two values is equal to or greater than the hard limit, even if the function is ignored. Setting this option to 0 disables hard limit warnings completely. Default value is 0, i.e. no hard limit warnings is produced.

memtrack.vm_limit int

Virtual memory limit (set on a process).

This limit is checked only on shutdown and a warning is produced if the value is greater than or equal to the limit.

This option is currently supported only on OSes where mallinfo() function is available (i.e. Linux).

memtrack.ignore_functions string

A comma or whitespace-separated list of functions which are to be ignored by soft_limit. The values are case-insensitive, for class methods use class::method syntax.


  • « Resource Types
  • Examples »
  • PHP Manual
  • Memtrack
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


  • « Predefined Constants
  • Basic usage »
  • PHP Manual
  • Memtrack
  • Examples

Examples

Table of Contents

  • Basic usage


Basic usage

Basic example on using memtrack extension:

Example #1 Creating large array in a function

<?php

/* /tmp/example1.php */

function foo() {
    $a = array();
    for ($i = 0; $i < 10000; $i++) $a[] = "test";
    return $a;
}
$arr = foo();

?>

Run the example with the following command:

php -d memtrack.enabled=1 -d memtrack.soft_limit=1M -d memtrack.vm_limit=3M /tmp/example1.php

The above example will output something similar to:

Warning: [memtrack] [pid 26177] user function foo() executed in /tmp/example1.php on line 10 allocated 4194304 bytes in /tmp/example1.php on line 0
Warning: [memtrack] [pid 26177] virtual memory usage on shutdown: 32911360 bytes in Unknown on line 0


OPcache

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • 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_reset — Resets the contents of the opcode cache


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.


Installation

The process of installing OPcache varies depending on which version of PHP you're running. Please refer to the appropriate section below.

Note:

If you want to use OPcache with » Xdebug, you must load OPcache before Xdebug.

PHP 5.5.0 and later

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.

PHP 5.2, 5.3 and 5.4

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

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

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
opcache.enable_cli=1

You may also want to consider disabling opcache.save_comments and enabling opcache.enable_file_override, however note that you will have to test your code before using these in production as they are known to break some frameworks and applications, particularly in cases where documentation comment annotations are used.

A full list of configuration directives supported by OPcache is also available.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

OPcache configuration options
Name | Default | Changeable | Changelog
opcache.enable | "1" | PHP_INI_ALL |
opcache.enable_cli | "0" | PHP_INI_SYSTEM | Between PHP 7.1.2 and 7.1.6 inclusive, the default was "1"
opcache.memory_consumption | "128" | PHP_INI_SYSTEM | Before PHP 7.0.0 the default was "64"
opcache.interned_strings_buffer | "8" | PHP_INI_SYSTEM | Before PHP 7.0.0 the default was "4"
opcache.max_accelerated_files | "10000" | PHP_INI_SYSTEM | Before PHP 7.0.0 the default was "2000"
opcache.max_wasted_percentage | "5" | PHP_INI_SYSTEM |
opcache.use_cwd | "1" | PHP_INI_SYSTEM |
opcache.validate_timestamps | "1" | PHP_INI_ALL |
opcache.revalidate_freq | "2" | PHP_INI_ALL |
opcache.revalidate_path | "0" | PHP_INI_ALL |
opcache.save_comments | "1" | PHP_INI_SYSTEM |
opcache.load_comments | "1" | PHP_INI_ALL | Removed in PHP 7.0.0.
opcache.fast_shutdown | "0" | PHP_INI_SYSTEM | Removed in PHP 7.2.0
opcache.enable_file_override | "0" | PHP_INI_SYSTEM |
opcache.optimization_level | "0x7FFEBFFF" | PHP_INI_SYSTEM | Changed from 0x7FFFBFFF in PHP 7.3.0, and from 0xFFFFFFFF in PHP 5.6.18
opcache.inherited_hack | "1" | PHP_INI_SYSTEM | Removed in PHP 7.3.0
opcache.dups_fix | "0" | PHP_INI_ALL |
opcache.blacklist_filename | "" | PHP_INI_SYSTEM |
opcache.max_file_size | "0" | PHP_INI_SYSTEM |
opcache.consistency_checks | "0" | PHP_INI_ALL |
opcache.force_restart_timeout | "180" | PHP_INI_SYSTEM |
opcache.error_log | "" | PHP_INI_SYSTEM |
opcache.log_verbosity_level | "1" | PHP_INI_SYSTEM |
opcache.preferred_memory_model | "" | PHP_INI_SYSTEM |
opcache.protect_memory | "0" | PHP_INI_SYSTEM |
opcache.mmap_base | NULL | PHP_INI_SYSTEM |
opcache.restrict_api | "" | PHP_INI_SYSTEM |
opcache.file_update_protection | "2" | PHP_INI_ALL |
opcache.huge_code_pages | "0" | PHP_INI_SYSTEM |
opcache.lockfile_path | "/tmp" | PHP_INI_SYSTEM |
opcache.opt_debug_level | "0" | PHP_INI_SYSTEM |
opcache.file_cache | NULL | PHP_INI_SYSTEM | Available as of PHP 7.0.0
opcache.file_cache_only | "0" | PHP_INI_SYSTEM | Available as of PHP 7.0.0
opcache.file_cache_consistency_checks | "1" | PHP_INI_SYSTEM | Available as of PHP 7.0.0
opcache.file_cache_fallback | "1" | PHP_INI_SYSTEM | Windows only. Available as of PHP 7.0.0
opcache.validate_permission | "0" | PHP_INI_SYSTEM | Available as of PHP 7.0.14
opcache.validate_root | "0" | PHP_INI_SYSTEM | Available as of PHP 7.0.14
opcache.preload | "" | PHP_INI_SYSTEM | Available as of PHP 7.4.0
opcache.preload_user | "" | PHP_INI_SYSTEM | Available as of PHP 7.4.0
opcache.cache_id | "1" | PHP_INI_SYSTEM | Windows only. Available as of PHP 7.4.0
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

opcache.enable boolean

Enables the opcode cache. When disabled, code is not optimised or cached. The setting opcache.enable can not be enabled at runtime through ini_set(), it can only be disabled. Trying to enable it at in a script will generate a warning.

opcache.enable_cli boolean

Enables the opcode cache for the CLI version of PHP.

opcache.memory_consumption integer

The size of the shared memory storage used by OPcache, in megabytes.

opcache.interned_strings_buffer integer

The amount of memory used to store interned strings, in megabytes. This configuration directive is ignored in PHP < 5.3.0.

opcache.max_accelerated_files integer

The maximum number of keys (and therefore scripts) in the OPcache hash table. The actual value used will be the first number in the set of prime numbers { 223, 463, 983, 1979, 3907, 7963, 16229, 32531, 65407, 130987 } that is greater than or equal to the configured value. The minimum value is 200. The maximum value is 100000 in PHP < 5.5.6, and 1000000 in later versions.

opcache.max_wasted_percentage integer

The maximum percentage of wasted memory that is allowed before a restart is scheduled.

opcache.use_cwd boolean

If enabled, OPcache appends the current working directory to the script key, thereby eliminating possible collisions between files with the same base name. Disabling this directive improves performance, but may break existing applications.

opcache.validate_timestamps boolean

If enabled, OPcache will check for updated scripts every opcache.revalidate_freq seconds. When this directive is disabled, you must reset OPcache manually via opcache_reset(), opcache_invalidate() or by restarting the Web server for changes to the filesystem to take effect.

opcache.revalidate_freq integer

How often to check script timestamps for updates, in seconds. 0 will result in OPcache checking for updates on every request.

This configuration directive is ignored if opcache.validate_timestamps is disabled.

opcache.revalidate_path boolean

If disabled, existing cached files using the same include_path will be reused. Thus, if a file with the same name is elsewhere in the include_path, it won't be found.

opcache.save_comments boolean

If disabled, all documentation comments will be discarded from the opcode cache to reduce the size of the optimised code. Disabling this configuration directive may break applications and frameworks that rely on comment parsing for annotations, including Doctrine, Zend Framework 2 and PHPUnit.

opcache.load_comments boolean

If disabled, documentation comments won't be loaded from the opcode cache even if they exist. This can be used with opcache.save_comments to only load comments for applications that require them.

opcache.fast_shutdown boolean

If enabled, a fast shutdown sequence is used that doesn't free each allocated block, but relies on the Zend Engine memory manager to deallocate the entire set of request variables en masse.

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 boolean

When enabled, the opcode cache will be checked for whether a file has already been cached when file_exists(), is_file() and is_readable() are called. This may increase performance in applications that check the existence and readability of PHP scripts, but risks returning stale data if opcache.validate_timestamps is disabled.

opcache.optimization_level integer

A bitmask that controls which optimisation passes are executed.

opcache.inherited_hack boolean

In PHP < 5.3, OPcache stores the places where DECLARE_CLASS opcodes used inheritance; when the file is loaded, OPcache then tries to bind the inherited classes using the current environment. The problem is that while the DECLARE_CLASS opcode may not be needed for the current script, if the script requires that the opcode be defined, it may not run.

This configuration directive is ignored in PHP 5.3 and later.

opcache.dups_fix boolean

This hack should only be enabled to work around "Cannot redeclare class" errors.

opcache.blacklist_filename string

The location of the OPcache blacklist file. A blacklist file is a text file containing the names of files that should not be accelerated, one per line. Wildcards are allowed, and prefixes can also be provided. Lines starting with a semi-colon are ignored as comments.

A simple blacklist file might look as follows:

; Matches a specific file.
/var/www/broken.php
; A prefix that matches all files starting with x.
/var/www/x
; A wildcard match.
/var/www/*-broken.php
opcache.max_file_size integer

The maximum file size that will be cached, in bytes. If this is 0, all files will be cached.

opcache.consistency_checks integer

If non-zero, OPcache will verify the cache checksum every N requests, where N is the value of this configuration directive. This should only be enabled when debugging, as it will impair performance.

opcache.force_restart_timeout integer

The length of time to wait for a scheduled restart to begin if the cache isn't active, in seconds. If the timeout is hit, then OPcache assumes that something is wrong and will kill the processes holding locks on the cache to permit a restart.

If opcache.log_verbosity_level is set to 2 or above, a warning will be recorded in the error log when this occurs.

opcache.error_log string

The error log for OPcache errors. An empty string is treated the same as stderr, and will result in logs being sent to standard error (which will be the Web server error log in most cases).

opcache.log_verbosity_level integer

The log verbosity level. By default, only fatal errors (level 0) and errors (level 1) are logged. Other levels available are warnings (level 2), information messages (level 3) and debug messages (level 4).

opcache.preferred_memory_model string

The preferred memory model for OPcache to use. If left empty, OPcache will choose the most appropriate model, which is the correct behaviour in virtually all cases.

Possible values include mmap, shm, posix and win32.

opcache.protect_memory boolean

Protects shared memory from unexpected writes while executing scripts. This is useful for internal debugging only.

opcache.mmap_base string

The base used for shared memory segments on Windows. All PHP processes have to map shared memory into the same address space. Using this directive allows "Unable to reattach to base address" errors to be fixed.

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 on your site are atomic, you may increase performance by setting it to "0".

opcache.huge_code_pages string

Enables or disables copying of PHP code (text segment) into HUGE PAGES. This should improve performance, but requires appropriate OS configuration.

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 boolean

Enables or disables opcode caching in shared memory.

opcache.file_cache_consistency_checks boolean

Enables or disables checksum validation when script loaded from file cache.

opcache.file_cache_fallback boolean

Implies opcache.file_cache_only=1 for a certain process that failed to reattach to the shared memory (for Windows only). Explicitly enabled file cache is required.

Caution

Disabling this configuration option may prevent processes to start, and is therefore discouraged.

opcache.validate_permission boolean

Validates the cached file permissions against the current user.

opcache.validate_root boolean

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.

opcache.preload_user string

Preloading code as root is not allowed for security reasons. This directive facilitates to let the preloading to be run as another user.

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.


  • « Runtime Configuration
  • OPcache Functions »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

This extension has no resource types defined.


OPcache Functions

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_reset — Resets the contents of the opcode cache


Compiles and caches a PHP script without executing it

  • « OPcache Functions
  • opcache_get_configuration »
  • PHP Manual
  • OPcache Functions
  • Compiles and caches a PHP script without executing it

opcache_compile_file

(PHP 5 >= 5.5.5, PHP 7, PECL ZendOpcache > 7.0.2)

opcache_compile_file — Compiles and caches a PHP script without executing it

Description

opcache_compile_file ( string $file ) : 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

file

The path to the PHP script to be compiled.

Return Values

Returns TRUE if file was compiled successfully or FALSE on failure.

Errors/Exceptions

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


Get configuration information about the cache

  • « opcache_compile_file
  • opcache_get_status »
  • PHP Manual
  • OPcache Functions
  • Get configuration information about the cache

opcache_get_configuration

(PHP 5 >= 5.5.0, PHP 7, PECL ZendOpcache > 7.0.2)

opcache_get_configuration — Get configuration information about the cache

Description

opcache_get_configuration ( void ) : array

This function returns configuration information about the cache instance

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


Get status information about the cache

  • « opcache_get_configuration
  • opcache_invalidate »
  • PHP Manual
  • OPcache Functions
  • Get status information about the cache

opcache_get_status

(PHP 5 >= 5.5.0, PHP 7, PECL ZendOpcache > 7.0.2)

opcache_get_status — Get status information about the cache

Description

opcache_get_status ([ bool $get_scripts = TRUE ] ) : array

This function returns state information about the cache instance

Parameters

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

See Also

  • opcache_get_configuration() - Get configuration information about the cache


Invalidates a cached script

  • « opcache_get_status
  • opcache_is_script_cached »
  • PHP Manual
  • OPcache Functions
  • Invalidates a cached script

opcache_invalidate

(PHP 5 >= 5.5.0, PHP 7, PECL ZendOpcache >= 7.0.0)

opcache_invalidate — Invalidates a cached script

Description

opcache_invalidate ( string $script [, 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.

Parameters

script

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


Tells whether a script is cached in OPCache

  • « opcache_invalidate
  • opcache_reset »
  • PHP Manual
  • OPcache Functions
  • Tells whether a script is cached in OPCache

opcache_is_script_cached

(PHP 5 >= 5.5.11, PHP 7, PECL ZendOpcache >= 7.0.4)

opcache_is_script_cached — Tells whether a script is cached in OPCache

Description

opcache_is_script_cached ( string $file ) : 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.

Parameters

file

The path to the PHP script to be checked.

Return Values

Returns TRUE if file is cached in OPCache, FALSE otherwise.

See Also

  • opcache_compile_file() - Compiles and caches a PHP script without executing it


Resets the contents of the opcode cache

  • « opcache_is_script_cached
  • Output Control »
  • PHP Manual
  • OPcache Functions
  • Resets the contents of the opcode cache

opcache_reset

(PHP 5 >= 5.5.0, PHP 7, PECL ZendOpcache >= 7.0.0)

opcache_reset — Resets the contents of the opcode cache

Description

opcache_reset ( void ) : 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.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the opcode cache was reset, or FALSE if the opcode cache is disabled.

See Also

  • opcache_invalidate() - Invalidates a cached script


Output Buffering Control

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
    • Output rewrite usage
  • Output Control Functions
    • flush — Flush system output buffer
    • ob_clean — Clean (erase) the output buffer
    • ob_end_clean — Clean (erase) the output buffer and turn off output buffering
    • ob_end_flush — Flush (send) the output buffer and turn off output buffering
    • ob_flush — Flush (send) the output buffer
    • ob_get_clean — Get current buffer contents and delete current output buffer
    • ob_get_contents — Return the contents of the output buffer
    • ob_get_flush — Flush the output buffer, return it as a string and turn off output buffering
    • 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_gzhandler — ob_start callback function to gzip output buffer
    • 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


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.


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" | PHP_INI_PERDIR |
output_handler | NULL | PHP_INI_PERDIR |
implicit_flush | "0" | PHP_INI_ALL |
url_rewriter.tags | "a=href,area=href,frame=src,form=,fieldset=" | PHP_INI_ALL | Before PHP 7.1.0, this was used to set session's trans sid rewrite. From PHP 7.1.0, it is only used by output_add_rewrite_var().
url_rewriter.hosts | $_SERVER['HTTP_HOST'] is used as default. | PHP_INI_ALL | Available as of PHP 7.1.0
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

output_buffering boolean/integer

You can enable output buffering for all files by setting this directive to 'On'. If you wish to limit the size of the buffer to a certain size - you can use a maximum number of bytes instead of 'On', as a value for this directive (e.g., output_buffering=4096). This directive is always Off in PHP-CLI.

output_handler string

You can redirect all of the output of your scripts to a function. For example, if you set output_handler to mb_output_handler(), character encoding will be transparently converted to the specified encoding. Setting any output handler automatically turns on output buffering.

Note:

You cannot use both mb_output_handler() with
ob_iconv_handler() and you cannot use both
ob_gzhandler() and
zlib.output_compression.

Note:

Only built-in functions can be used with this directive. For user defined functions, use ob_start().

implicit_flush boolean

FALSE by default. Changing this to TRUE tells PHP to tell the output layer to flush itself automatically after every output block. This is equivalent to calling the PHP function flush() after each and every call to print or echo and each and every HTML block.

When using PHP within an web environment, turning this option on has serious performance implications and is generally recommended for debugging purposes only. This value defaults to TRUE when operating under the CLI SAPI.

See also ob_implicit_flush().

url_rewriter.tags string
url_rewriter.tags specifies which HTML tags are rewritten by output_add_rewrite_var() values. Defaults to a=href,area=href,frame=src,input=src,form= form is special tag. <input hidden="session_id" name="session_name"> is added as form variable.

Note: Before PHP 7.1.0, url_rewriter.tags was used to specify session.trans_sid_tags. As of PHP 7.1.0, fieldset is no longer considered as special tag.

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 ",", no space is allowed between hosts. e.g. php.net,wiki.php.net,bugs.php.net


Predefined Constants

The constants below are always available as part of the PHP core.

PHP_OUTPUT_HANDLER_START (integer)

Indicates that output buffering has begun.

PHP_OUTPUT_HANDLER_WRITE (integer)

Indicates that the output buffer is being flushed, and had data to output.

Available since PHP 5.4.

PHP_OUTPUT_HANDLER_FLUSH (integer)

Indicates that the buffer has been flushed.

Available since PHP 5.4.

PHP_OUTPUT_HANDLER_CLEAN (integer)

Indicates that the output buffer has been cleaned.

Available since PHP 5.4.

PHP_OUTPUT_HANDLER_FINAL (integer)

Indicates that this is the final output buffering operation.

Available since PHP 5.4.

PHP_OUTPUT_HANDLER_CONT (integer)

Indicates that the buffer has been flushed, but output buffering will continue.

As of PHP 5.4, this is an alias for PHP_OUTPUT_HANDLER_WRITE.

PHP_OUTPUT_HANDLER_END (integer)

Indicates that output buffering has ended.

As of PHP 5.4, this is an alias for PHP_OUTPUT_HANDLER_FINAL.

PHP_OUTPUT_HANDLER_CLEANABLE (integer)

Controls whether an output buffer created by ob_start() can be cleaned.

Available since PHP 5.4.

PHP_OUTPUT_HANDLER_FLUSHABLE (integer)

Controls whether an output buffer created by ob_start() can be flushed.

Available since PHP 5.4.

PHP_OUTPUT_HANDLER_REMOVABLE (integer)

Controls whether an output buffer created by ob_start() can be removed before the end of the script.

Available since PHP 5.4.

PHP_OUTPUT_HANDLER_STDFLAGS (integer)

The default set of output buffer flags; currently equivalent to PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_FLUSHABLE | PHP_OUTPUT_HANDLER_REMOVABLE.

Available since PHP 5.4.


  • « Predefined Constants
  • Basic usage »
  • PHP Manual
  • Output Control
  • Examples

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" action="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 it's own INI settings, url_rewriter.tags and url_rewriter.hosts.


Output Control Functions

See Also

See also header() and setcookie().

Table of Contents

  • flush — Flush system output buffer
  • ob_clean — Clean (erase) the output buffer
  • ob_end_clean — Clean (erase) the output buffer and turn off output buffering
  • ob_end_flush — Flush (send) the output buffer and turn off output buffering
  • ob_flush — Flush (send) the output buffer
  • ob_get_clean — Get current buffer contents and delete current output buffer
  • ob_get_contents — Return the contents of the output buffer
  • ob_get_flush — Flush the output buffer, return it as a string and turn off output buffering
  • 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_gzhandler — ob_start callback function to gzip output buffer
  • 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


Flush system output buffer

  • « Output Control Functions
  • ob_clean »
  • PHP Manual
  • Output Control Functions
  • Flush system output buffer

flush

(PHP 4, PHP 5, PHP 7)

flush — Flush system output buffer

Description

flush ( void ) : void

Flushes the system write buffers of PHP and whatever backend PHP is using (CGI, a web server, etc). This attempts to push current output all the way to the browser with a few caveats.

flush() may not be able to override the buffering scheme of your web server and it has no effect on any client-side buffering in the browser. It also doesn't affect PHP's userspace output buffering mechanism. This means you will have to call both ob_flush() and flush() to flush the ob output buffers if you are using those.

Several servers, especially on Win32, will still buffer the output from your script until it terminates before transmitting the results to the browser.

Server modules for Apache like mod_gzip may do buffering of their own that will cause flush() to not result in data being sent immediately to the client.

Even the browser may buffer its input before displaying it. Netscape, for example, buffers text until it receives an end-of-line or the beginning of a tag, and it won't render tables until the </table> tag of the outermost table is seen.

Some versions of Microsoft Internet Explorer will only start to display the page after they have received 256 bytes of output, so you may need to send extra whitespace before flushing to get those browsers to display the page.

Return Values

No value is returned.

See Also

  • ob_flush() - Flush (send) the output buffer
  • ob_clean() - Clean (erase) the output buffer
  • ob_end_flush() - Flush (send) the output buffer and turn off output buffering
  • ob_end_clean() - Clean (erase) the output buffer and turn off output buffering


Clean (erase) the output buffer

  • « flush
  • ob_end_clean »
  • PHP Manual
  • Output Control Functions
  • Clean (erase) the output buffer

ob_clean

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

ob_clean — Clean (erase) the output buffer

Description

ob_clean ( void ) : void

This function discards the contents of the output buffer.

This function does not destroy the output buffer like ob_end_clean() does.

The output buffer must be started by ob_start() with PHP_OUTPUT_HANDLER_CLEANABLE flag. Otherwise ob_clean() will not work.

Return Values

No value is returned.

See Also

  • ob_flush() - Flush (send) the output buffer
  • ob_end_flush() - Flush (send) the output buffer and turn off output buffering
  • ob_end_clean() - Clean (erase) the output buffer and turn off output buffering


Clean (erase) the output buffer and turn off output buffering

  • « ob_clean
  • ob_end_flush »
  • PHP Manual
  • Output Control Functions
  • Clean (erase) the output buffer and turn off output buffering

ob_end_clean

(PHP 4, PHP 5, PHP 7)

ob_end_clean — Clean (erase) the output buffer and turn off output buffering

Description

ob_end_clean ( void ) : bool

This function discards the contents of the topmost output buffer and turns off this output buffering. If you want to further process the buffer's contents you have to call ob_get_contents() before ob_end_clean() as the buffer contents are discarded when ob_end_clean() is called.

The output buffer must be started by ob_start() with PHP_OUTPUT_HANDLER_CLEANABLE and PHP_OUTPUT_HANDLER_REMOVABLE flags. Otherwise ob_end_clean() will not work.

Return Values

Returns TRUE on success or FALSE on failure. Reasons for failure are first that you called the function without an active buffer or that for some reason a buffer could not be deleted (possible for special buffer).

Errors/Exceptions

If the function fails it generates an E_NOTICE.

Examples

The following example shows an easy way to get rid of all output buffers:

Example #1 ob_end_clean() example

<?php
ob_start();
echo 'Text that won\'t get displayed.';
ob_end_clean();
?>

See Also

  • ob_start() - Turn on output buffering
  • ob_get_contents() - Return the contents of the output buffer
  • ob_flush() - Flush (send) the output buffer


Flush (send) the output buffer and turn off output buffering

  • « ob_end_clean
  • ob_flush »
  • PHP Manual
  • Output Control Functions
  • Flush (send) the output buffer and turn off output buffering

ob_end_flush

(PHP 4, PHP 5, PHP 7)

ob_end_flush — Flush (send) the output buffer and turn off output buffering

Description

ob_end_flush ( void ) : bool

This function will send the contents of the topmost output buffer (if any) and turn this output buffer off. If you want to further process the buffer's contents you have to call ob_get_contents() before ob_end_flush() as the buffer contents are discarded after ob_end_flush() is called.

The output buffer must be started by ob_start() with PHP_OUTPUT_HANDLER_FLUSHABLE and PHP_OUTPUT_HANDLER_REMOVABLE flags. Otherwise ob_end_flush() will not work.

Note: This function is similar to ob_get_flush(), except that ob_get_flush() returns the buffer as a string.

Return Values

Returns TRUE on success or FALSE on failure. Reasons for failure are first that you called the function without an active buffer or that for some reason a buffer could not be deleted (possible for special buffer).

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_get_flush() - Flush the output buffer, return it as a string and turn off output buffering
  • ob_flush() - Flush (send) the output buffer
  • ob_end_clean() - Clean (erase) the output buffer and turn off output buffering


Flush (send) the output buffer

  • « ob_end_flush
  • ob_get_clean »
  • PHP Manual
  • Output Control Functions
  • Flush (send) the output buffer

ob_flush

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

ob_flush — Flush (send) the output buffer

Description

ob_flush ( void ) : void

This function will send the contents of the output buffer (if any). If you want to further process the buffer's contents you have to call ob_get_contents() before ob_flush() as the buffer contents are discarded after ob_flush() is called.

This function does not destroy the output buffer like ob_end_flush() does.

Return Values

No value is returned.

See Also

  • ob_get_contents() - Return the contents of the output buffer
  • ob_clean() - Clean (erase) the output buffer
  • ob_end_flush() - Flush (send) the output buffer and turn off output buffering
  • ob_end_clean() - Clean (erase) the output buffer and turn off output buffering


Get current buffer contents and delete current output buffer

  • « ob_flush
  • ob_get_contents »
  • PHP Manual
  • Output Control Functions
  • Get current buffer contents and delete current output buffer

ob_get_clean

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

ob_get_clean — Get current buffer contents and delete current output buffer

Description

ob_get_clean ( void ) : string

Gets the current buffer contents and delete current output buffer.

ob_get_clean() essentially executes both
ob_get_contents() and
ob_end_clean().

The output buffer must be started by ob_start() with PHP_OUTPUT_HANDLER_CLEANABLE and PHP_OUTPUT_HANDLER_REMOVABLE flags. Otherwise ob_get_clean() will not work.

Return Values

Returns the contents of the output buffer and end output buffering. If output buffering isn't active then FALSE is returned.

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_get_contents() - Return the contents of the output buffer
  • ob_start() - Turn on output buffering


Return the contents of the output buffer

  • « ob_get_clean
  • ob_get_flush »
  • PHP Manual
  • Output Control Functions
  • Return the contents of the output buffer

ob_get_contents

(PHP 4, PHP 5, PHP 7)

ob_get_contents — Return the contents of the output buffer

Description

ob_get_contents ( void ) : string

Gets the contents of the output buffer without clearing it.

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


Flush the output buffer, return it as a string and turn off output buffering

  • « ob_get_contents
  • ob_get_length »
  • PHP Manual
  • Output Control Functions
  • Flush the output buffer, return it as a string and turn off output buffering

ob_get_flush

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

ob_get_flush — Flush the output buffer, return it as a string and turn off output buffering

Description

ob_get_flush ( void ) : string

ob_get_flush() flushes the output buffer, return it as a string and turns off output buffering.

The output buffer must be started by ob_start() with PHP_OUTPUT_HANDLER_FLUSHABLE flag. Otherwise ob_get_flush() will not work.

Note: This function is similar to ob_end_flush(), except that this function also returns the buffer as a string.

Return Values

Returns the output buffer or FALSE if no buffering is active.

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_end_clean() - Clean (erase) the output buffer and turn off output buffering
  • ob_end_flush() - Flush (send) the output buffer and turn off output buffering
  • ob_list_handlers() - List all output handlers in use


Return the length of the output buffer

  • « ob_get_flush
  • ob_get_level »
  • PHP Manual
  • Output Control Functions
  • Return the length of the output buffer

ob_get_length

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

ob_get_length — Return the length of the output buffer

Description

ob_get_length ( void ) : int

This will return the length of the contents in the output buffer, in bytes.

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


Return the nesting level of the output buffering mechanism

  • « ob_get_length
  • ob_get_status »
  • PHP Manual
  • Output Control Functions
  • Return the nesting level of the output buffering mechanism

ob_get_level

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

ob_get_level — Return the nesting level of the output buffering mechanism

Description

ob_get_level ( void ) : int

Returns the nesting level of the output buffering mechanism.

Return Values

Returns the level of nested output buffering handlers or zero if output buffering is not active.

See Also

  • ob_start() - Turn on output buffering
  • ob_get_contents() - Return the contents of the output buffer


Get status of output buffers

  • « ob_get_level
  • ob_gzhandler »
  • PHP Manual
  • Output Control Functions
  • Get status of output buffers

ob_get_status

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

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 called without the full_status parameter or with full_status = FALSE a simple array with the following elements is returned:

Array
(
    [level] => 2
    [type] => 0
    [status] => 0
    [name] => URL-Rewriter
    [del] => 1
)
Simple ob_get_status() results
Key | Value
level | Output nesting level
type | PHP_OUTPUT_HANDLER_INTERNAL (0) or PHP_OUTPUT_HANDLER_USER (1)
status | One of PHP_OUTPUT_HANDLER_START (0), PHP_OUTPUT_HANDLER_CONT (1) or PHP_OUTPUT_HANDLER_END (2)
name | Name of active output handler or ' default output handler' if none is set
del | Erase-flag as set by ob_start()

If called with full_status = TRUE an array with one element for each active output buffer level is returned. The output level is used as key of the top level array and each array element itself is another array holding status information on one active output level.

Array
(
    [0] => Array
        (
            [chunk_size] => 0
            [size] => 40960
            [block_size] => 10240
            [type] => 1
            [status] => 0
            [name] => default output handler
            [del] => 1
        )

    [1] => Array
        (
            [chunk_size] => 0
            [size] => 40960
            [block_size] => 10240
            [type] => 0
            [buffer_size] => 0
            [status] => 0
            [name] => URL-Rewriter
            [del] => 1
        )

)

The full output contains these additional elements:

Full ob_get_status() results
Key | Value
chunk_size | Chunk size as set by ob_start()
size | ...
blocksize | ...

See Also

  • ob_get_level() - Return the nesting level of the output buffering mechanism
  • ob_list_handlers() - List all output handlers in use


ob_start callback function to gzip output buffer

  • « ob_get_status
  • ob_implicit_flush »
  • PHP Manual
  • Output Control Functions
  • ob_start callback function to gzip output buffer

ob_gzhandler

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

ob_gzhandler — ob_start callback function to gzip output buffer

Description

ob_gzhandler ( string $buffer , int $mode ) : string

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

buffer

mode

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 output buffer and turn off output buffering


Turn implicit flush on/off

  • « ob_gzhandler
  • ob_list_handlers »
  • PHP Manual
  • Output Control Functions
  • Turn implicit flush on/off

ob_implicit_flush

(PHP 4, PHP 5, PHP 7)

ob_implicit_flush — Turn implicit flush on/off

Description

ob_implicit_flush ([ int $flag = 1 ] ) : void

ob_implicit_flush() will turn implicit flushing on or off. Implicit flushing will result in a flush operation after every output call, so that explicit calls to flush() will no longer be needed.

Parameters

flag

1 to turn implicit flushing on, 0 otherwise.

Return Values

No value is returned.

See Also

  • flush() - Flush system output buffer
  • ob_start() - Turn on output buffering
  • ob_end_flush() - Flush (send) the output buffer and turn off output buffering


List all output handlers in use

  • « ob_implicit_flush
  • ob_start »
  • PHP Manual
  • Output Control Functions
  • List all output handlers in use

ob_list_handlers

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

ob_list_handlers — List all output handlers in use

Description

ob_list_handlers ( void ) : array

Lists all output handlers in use.

Return Values

This will return an array with the output handlers in use (if any). If output_buffering is enabled or an anonymous function was used with ob_start(), ob_list_handlers() will return "default output handler".

Examples

Example #1 ob_list_handlers() example

<?php
//using output_buffering=On
print_r(ob_list_handlers());
ob_end_flush();

ob_start("ob_gzhandler");
print_r(ob_list_handlers());
ob_end_flush();

// anonymous functions
ob_start(function($string) { return $string; });
print_r(ob_list_handlers());
ob_end_flush();
?>

The above example will output:

Array
(
    [0] => default output handler
)

Array
(
    [0] => ob_gzhandler
)

Array
(
    [0] => Closure::__invoke
)

See Also

  • ob_end_clean() - Clean (erase) the output buffer and turn off output buffering
  • ob_end_flush() - Flush (send) the output buffer and turn off output buffering
  • ob_get_flush() - Flush the output buffer, return it as a string and turn off output buffering
  • ob_start() - Turn on output buffering


Turn on output buffering

  • « ob_list_handlers
  • output_add_rewrite_var »
  • PHP Manual
  • Output Control Functions
  • Turn on output buffering

ob_start

(PHP 4, PHP 5, PHP 7)

ob_start — Turn on output buffering

Description

ob_start ([ callable $output_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 (other than headers), instead the output is stored in an internal buffer.

The contents of this internal buffer may be copied into a string variable using ob_get_contents(). To output what is stored in the internal buffer, use ob_end_flush(). Alternatively, ob_end_clean() will silently discard the buffer contents.

Warning

Some web servers (e.g. Apache) change the working directory of a script when calling the callback function. You can change it back by e.g. chdir(dirname($_SERVER['SCRIPT_FILENAME'])) in the callback function.

Output buffers are stackable, that is, you may call ob_start() while another ob_start() is active. Just make sure that you call ob_end_flush() the appropriate number of times. If multiple output callback functions are active, output is being filtered sequentially through each of them in nesting order.

Parameters

output_callback

An optional output_callback function may be specified. This function takes a string as a parameter and should return a string. The function will be called when the output buffer is flushed (sent) or cleaned (with ob_flush(), ob_clean() or similar function) or when the output buffer is flushed to the browser at the end of the request. When output_callback is called, it will receive the contents of the output buffer as its parameter and is expected to return a new output buffer as a result, which will be sent to the browser. If the output_callback is not a callable function, this function will return FALSE. This is the callback signature:

handler ( string $buffer [, int $phase ] ) : string
buffer
Contents of the output buffer.
phase
Bitmask of PHP_OUTPUT_HANDLER_* constants.

If output_callback returns FALSE original input is sent to the browser.

The output_callback parameter may be bypassed by passing a NULL value.

ob_end_clean(), ob_end_flush(), ob_clean(), ob_flush() and ob_start() may not be called from a callback function. If you call them from callback function, the behavior is undefined. If you would like to delete the contents of a buffer, return "" (a null string) from callback function. You can't even call functions using the output buffering functions like print_r($expression, true) or highlight_file($filename, true) from a callback function.

Note:

ob_gzhandler() function exists to facilitate sending gz-encoded data to web browsers that support compressed web pages. ob_gzhandler() determines what type of content encoding the browser will accept and will return its output accordingly.

chunk_size

If the optional parameter chunk_size is passed, the buffer will be flushed after any output call which causes the buffer's length to equal or exceed chunk_size. The default value 0 means that the output function will only be called when the output buffer is closed.

Prior to PHP 5.4.0, the value 1 was a special case value that set the chunk size to 4096 bytes.

flags

The flags parameter is a bitmask that controls the operations that can be performed on the output buffer. The default is to allow output buffers to be cleaned, flushed and removed, which can be set explicitly via PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_FLUSHABLE | PHP_OUTPUT_HANDLER_REMOVABLE, or PHP_OUTPUT_HANDLER_STDFLAGS as shorthand.

Each flag controls access to a set of functions, as described below:

Constant | Functions
PHP_OUTPUT_HANDLER_CLEANABLE | ob_clean(), ob_end_clean(), and ob_get_clean().
PHP_OUTPUT_HANDLER_FLUSHABLE | ob_end_flush(), ob_flush(), and ob_get_flush().
PHP_OUTPUT_HANDLER_REMOVABLE | ob_end_clean(), ob_end_flush(), and ob_get_flush().

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.0.0 | In case ob_start() is used inside an output buffer callback, this function will no longer issue an E_ERROR but instead an E_RECOVERABLE_ERROR, allowing custom error handlers to catch such errors.
5.4.0 | The third parameter of ob_start() changed from a boolean parameter called erase (which, if set to FALSE, would prevent the output buffer from being deleted until the script finished executing) to an integer parameter called flags. Unfortunately, this results in an API compatibility break for code written prior to PHP 5.4.0 that uses the third parameter. See the flags example for an example of how to handle this with code that needs to be compatible with both.
5.4.0 | A chunk size of 1 now results in chunks of 1 byte being sent to the output buffer.

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 uneraseable output buffer in a way compatible with both PHP 5.3 and 5.4

<?php

if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
  ob_start(null, 0, PHP_OUTPUT_HANDLER_STDFLAGS ^
    PHP_OUTPUT_HANDLER_REMOVABLE);
} else {
  ob_start(null, 0, false);
}

?>

See Also

  • ob_get_contents() - Return the contents of the output buffer
  • ob_end_clean() - Clean (erase) the output buffer and turn off output buffering
  • ob_end_flush() - Flush (send) the output buffer and turn off output buffering
  • 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


Add URL rewriter values

  • « ob_start
  • output_reset_rewrite_vars »
  • PHP Manual
  • Output Control Functions
  • Add URL rewriter values

output_add_rewrite_var

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

output_add_rewrite_var — Add URL rewriter values

Description

output_add_rewrite_var ( string $name , string $value ) : bool

This function adds another name/value pair to the URL rewrite mechanism. The name and value will be added to URLs (as GET parameter) and forms (as hidden input fields) the same way as the session ID when transparent URL rewriting is enabled with session.use_trans_sid.

This function's behaviour is controlled by the url_rewriter.tags and url_rewriter.hosts php.ini parameters.

Note: Calling this function will implicitly start output buffering if it is not active already.

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 | 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, url_rewriter.tags is used solely for output functions, url_rewriter.hosts is added.

Examples

Example #1 output_add_rewrite_var() example

<?php
output_add_rewrite_var('var', 'value');

// some links
echo '<a href="file.php">link</a>
<a href="http://example.com">link2</a>';

// a form
echo '<form action="script.php" method="post">
<input type="text" name="var2" />
</form>';

print_r(ob_list_handlers());
?>

The above example will output:

<a href="file.php?var=value">link</a>
<a href="http://example.com">link2</a>

<form action="script.php" method="post">
<input type="hidden" name="var" value="value" />
<input type="text" name="var2" />
</form>

Array
(
    [0] => URL-Rewriter
)

See Also

  • output_reset_rewrite_vars() - Reset URL rewriter values
  • ob_flush() - Flush (send) the output buffer
  • ob_list_handlers() - List all output handlers in use
  • url_rewriter.tags
  • url_rewriter.hosts
  • session.trans_sid_tags
  • session.trans_sid_hosts


Reset URL rewriter values

  • « output_add_rewrite_var
  • PHP Options/Info »
  • PHP Manual
  • Output Control Functions
  • Reset URL rewriter values

output_reset_rewrite_vars

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

output_reset_rewrite_vars — Reset URL rewriter values

Description

output_reset_rewrite_vars ( void ) : bool

This function resets the URL rewriter and removes all rewrite variables previously set by the output_add_rewrite_var() function.

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
session_start();
output_add_rewrite_var('var', 'value');

echo '<a href="file.php">link</a>';
ob_flush();

output_reset_rewrite_vars();
echo '<a href="file.php">link</a>';
?>

The above example will output:

<a href="file.php?PHPSESSID=xxx&var=value">link</a>
<a href="file.php">link</a>

See Also

  • output_add_rewrite_var() - Add URL rewriter values
  • ob_flush() - Flush (send) the output buffer
  • ob_list_handlers() - List all output handlers in use
  • url_rewriter.tags
  • url_rewriter.hosts
  • session.trans_sid_tags
  • session.trans_sid_hosts


PHP Options and Information

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • PHP Options/Info Functions
    • assert_options — Set/get the various assert flags
    • assert — Checks if assertion is FALSE
    • 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 an environment variable
    • 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_all — Gets all configuration options
    • 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
    • magic_quotes_runtime — Alias of set_magic_quotes_runtime
    • main — Dummy for main
    • memory_get_peak_usage — Returns the peak of memory allocated by PHP
    • memory_get_usage — Returns the amount of memory allocated to PHP
    • 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_logo_guid — Gets the logo guid
    • 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_magic_quotes_runtime — Sets the current active configuration setting of magic_quotes_runtime
    • 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_logo_guid — Gets the Zend guid
    • zend_thread_id — Returns a unique identifier for the current thread
    • zend_version — Gets the version of the current Zend engine


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.


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" | PHP_INI_ALL |
assert.bail | "0" | PHP_INI_ALL |
assert.warning | "1" | PHP_INI_ALL |
assert.callback | NULL | PHP_INI_ALL |
assert.quiet_eval | "0" | PHP_INI_ALL |
assert.exception | "0" | PHP_INI_ALL | Available as of PHP 7.0.0.
enable_dl | "1" | PHP_INI_SYSTEM | This deprecated feature will certainly be removed in the future.
max_execution_time | "30" | PHP_INI_ALL |
max_input_time | "-1" | PHP_INI_PERDIR |
max_input_nesting_level | "64" | PHP_INI_PERDIR | Available as of PHP 5.2.3.
max_input_vars | 1000 | PHP_INI_PERDIR | Available as of PHP 5.3.9.
magic_quotes_gpc | "1" | PHP_INI_PERDIR | Removed in PHP 5.4.0.
magic_quotes_runtime | "0" | PHP_INI_ALL | Removed in PHP 5.4.0.
zend.enable_gc | "1" | PHP_INI_ALL | Available as of PHP 5.3.0.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

assert.active boolean

Enable assert() evaluation.

assert.bail boolean

Terminate script execution on failed assertions.

assert.warning boolean

Issue a PHP warning for each failed assertion.

assert.callback string

User function to call on failed assertions.

assert.quiet_eval boolean

Use the current setting of error_reporting() during assertion expression evaluation. If enabled, no errors are shown (implicit error_reporting(0)) while evaluation. If disabled, errors are shown according to the settings of error_reporting()

assert.exception boolean

Issue an AssertionError exception for the failed assertion.

enable_dl boolean

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

The main reason for turning dynamic loading off is security. With dynamic loading, it's possible to ignore all open_basedir restrictions. The default is to allow dynamic loading, except when using safe mode. In safe mode, it's always impossible to use dl().

max_execution_time integer

This sets the maximum time in seconds a script is allowed to run before it is terminated by the parser. This helps prevent poorly written scripts from tying up the server. The default setting is 30. When running PHP from the command line the default setting is 0.

The maximum execution time is not affected by system calls, stream operations etc. Please see the set_time_limit() function for more details.

You can not change this setting with ini_set() when running in safe mode. The only workaround is to turn off safe mode or by changing the time limit in the php.ini.

Your web server can have other timeout configurations that may also interrupt PHP execution. Apache has a Timeout directive and IIS has a CGI timeout function. Both default to 300 seconds. See your web server documentation for specific details.

max_input_time integer

This sets the maximum time in seconds a script is allowed to parse input data, like POST and GET. Timing begins at the moment PHP is invoked at the server and ends when execution begins. 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 integer

Sets the max nesting depth of input variables (i.e. $_GET, $_POST.)

max_input_vars integer

How many input variables may be accepted (limit is applied to $_GET, $_POST and $_COOKIE superglobal separately). Use of this directive mitigates the possibility of denial of service attacks which use hash collisions. If there are more input variables than specified by this directive, an E_WARNING is issued, and further input variables are truncated from the request.

magic_quotes_gpc boolean
Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

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

Note:

If the magic_quotes_sybase directive is also ON it will completely override magic_quotes_gpc. Having both directives enabled means only single quotes are escaped as ''. Double quotes, backslashes and NUL's will remain untouched and unescaped.

See also get_magic_quotes_gpc()

magic_quotes_runtime boolean
Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

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

Functions affected by magic_quotes_runtime (does not include functions from PECL):

  • get_meta_tags()
  • file_get_contents()
  • file()
  • fgets()
  • fwrite()
  • fread()
  • fputcsv()
  • stream_socket_recvfrom()
  • exec()
  • system()
  • passthru()
  • stream_get_contents()
  • bzread()
  • gzfile()
  • gzgets()
  • gzwrite()
  • gzread()
  • exif_read_data()
  • dba_insert()
  • dba_replace()
  • dba_fetch()
  • ibase_fetch_row()
  • ibase_fetch_assoc()
  • ibase_fetch_object()
  • mssql_fetch_row()
  • mssql_fetch_object()
  • mssql_fetch_array()
  • mssql_fetch_assoc()
  • mysqli_fetch_row()
  • mysqli_fetch_array()
  • mysqli_fetch_assoc()
  • mysqli_fetch_object()
  • pg_fetch_row()
  • pg_fetch_assoc()
  • pg_fetch_array()
  • pg_fetch_object()
  • pg_fetch_all()
  • pg_select()
  • sybase_fetch_object()
  • sybase_fetch_array()
  • sybase_fetch_assoc()
  • SplFileObject::fgets()
  • SplFileObject::fgetcsv()
  • SplFileObject::fwrite()

zend.enable_gc boolean

Enables or disables the circular reference collector.


Predefined Constants

The constants below are always available as part of the PHP core.

Pre-defined phpcredits() constants
Constant | Value | Description
CREDITS_GROUP | 1 | A list of the core developers
CREDITS_GENERAL | 2 | General credits: Language design and concept, PHP authors and SAPI module.
CREDITS_SAPI | 4 | A list of the server API modules for PHP, and their authors.
CREDITS_MODULES | 8 | A list of the extension modules for PHP, and their authors.
CREDITS_DOCS | 16 | The credits for the documentation team.
CREDITS_FULLPAGE | 32 | Usually used in combination with the other flags. Indicates that a complete stand-alone HTML page needs to be printed including the information indicated by the other flags.
CREDITS_QA | 64 | The credits for the quality assurance team.
CREDITS_ALL | -1 | All the credits, equivalent to using: CREDITS_DOCS + CREDITS_GENERAL + CREDITS_GROUP + CREDITS_MODULES + CREDITS_QA CREDITS_FULLPAGE. It generates a complete stand-alone HTML page with the appropriate tags. This is the default value.
phpinfo() constants
Constant | Value | Description
INFO_GENERAL | 1 | The configuration line, php.ini location, build date, Web Server, System and more.
INFO_CREDITS | 2 | PHP Credits. See also phpcredits().
INFO_CONFIGURATION | 4 | Current Local and Master values for PHP directives. See also ini_get().
INFO_MODULES | 8 | Loaded modules and their respective settings.
INFO_ENVIRONMENT | 16 | Environment Variable information that's also available in $_ENV.
INFO_VARIABLES | 32 | Shows all predefined variables from EGPCS (Environment, GET, POST, Cookie, Server).
INFO_LICENSE | 64 | PHP License information. See also the » license faq.
INFO_ALL | -1 | Shows all of the above. This is the default value.
INI constants
Constant | Value | Description
INI_USER | 1 | Unused
INI_PERDIR | 2 | Unused
INI_SYSTEM | 4 | Unused
INI_ALL | 7 | Unused

Assert constants, these values are used to set the assertion options in assert_options().

assert() constants
Constant | INI Setting | Description
ASSERT_ACTIVE | assert.active | Enable assert() evaluation.
ASSERT_CALLBACK | assert.callback | Callback to call on failed assertions.
ASSERT_BAIL | assert.bail | Terminate execution on failed assertions.
ASSERT_WARNING | assert.warning | Issues a PHP warning for each failed assertion
ASSERT_QUIET_EVAL | assert.quiet_eval | Disable error_reporting during assertion expression evaluation.

The following constants are only available if the host operating system is Windows, and can tell different versioning information so its possible to detect various features and make use of them. They are all available as of PHP 5.3.0.

Windows specific constants
Constant | Description
PHP_WINDOWS_VERSION_MAJOR | The major version of Windows, this can be either 4 (NT4/Me/98/95), 5 (XP/2003 R2/2003/2000) or 6 (Vista/2008/7/8/8.1).
PHP_WINDOWS_VERSION_MINOR | The minor version of Windows, this can be either 0 (Vista/2008/2000/NT4/95), 1 (XP), 2 (2003 R2/2003/XP x64), 10 (98) or 90 (ME).
PHP_WINDOWS_VERSION_BUILD | The Windows build number (for example, Windows Vista with SP1 applied is build 6001)
PHP_WINDOWS_VERSION_PLATFORM | The platform that PHP currently is running on, this value is 2 on Windows Vista/XP/2000/NT4, Server 2008/2003 and on Windows ME/98/95 this value is 1.
PHP_WINDOWS_VERSION_SP_MAJOR | The major version of the service pack installed, this value is 0 if no service pack is installed. For example, Windows XP with service pack 3 installed will make this value 3.
PHP_WINDOWS_VERSION_SP_MINOR | The minor version of the service pack installed, this value is 0 if no service pack is installed.
PHP_WINDOWS_VERSION_SUITEMASK | The suitemask is a bitmask that can tell if various features of Windows is installed, see the table below for possible bitfield values.
PHP_WINDOWS_VERSION_PRODUCTTYPE | This contains the value used to determine the PHP_WINDOWS_NT_* constants. This value may be one of the PHP_WINDOWS_NT_* constants indicating the platform type.
PHP_WINDOWS_NT_DOMAIN_CONTROLLER | This is a domain controller
PHP_WINDOWS_NT_SERVER | This is a server system (eg. Server 2008/2003/2000), note that if this is a domain controller its reported as PHP_WINDOWS_NT_DOMAIN_CONTROLLER.
PHP_WINDOWS_NT_WORKSTATION | This is a workstation system (eg. Vista/XP/2000/NT4)

This table shows a list of features that can be checked for using the PHP_WINDOWS_VERSION_SUITEMASK bitmask.

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

Table of Contents

  • assert_options — Set/get the various assert flags
  • assert — Checks if assertion is FALSE
  • 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 an environment variable
  • 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_all — Gets all configuration options
  • 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
  • magic_quotes_runtime — Alias of set_magic_quotes_runtime
  • main — Dummy for main
  • memory_get_peak_usage — Returns the peak of memory allocated by PHP
  • memory_get_usage — Returns the amount of memory allocated to PHP
  • 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_logo_guid — Gets the logo guid
  • 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_magic_quotes_runtime — Sets the current active configuration setting of magic_quotes_runtime
  • 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_logo_guid — Gets the Zend guid
  • zend_thread_id — Returns a unique identifier for the current thread
  • zend_version — Gets the version of the current Zend engine


Set/get the various assert flags

  • « PHP Options/Info Functions
  • assert »
  • PHP Manual
  • PHP Options/Info Functions
  • Set/get the various assert flags

assert_options

(PHP 4, PHP 5, PHP 7)

assert_options — Set/get the various assert flags

Description

assert_options ( int $what [, mixed $value ] ) : mixed

Set the various assert() control options or just query their current settings.

Note: As of PHP 7.0.0, 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

what

Assert Options
Option | INI Setting | Default value | Description
ASSERT_ACTIVE | assert.active | 1 | enable assert() evaluation
ASSERT_WARNING | assert.warning | 1 | issue a PHP warning for each failed assertion
ASSERT_BAIL | assert.bail | 0 | terminate execution on failed assertions
ASSERT_QUIET_EVAL | assert.quiet_eval | 0 | disable error_reporting during assertion expression evaluation
ASSERT_CALLBACK | assert.callback | (NULL) | Callback to call on failed assertions

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
The assertion that has been passed to assert(), converted to a string.
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 or FALSE on errors.

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 if assertion is FALSE


Checks if assertion is FALSE

  • « assert_options
  • cli_get_process_title »
  • PHP Manual
  • PHP Options/Info Functions
  • Checks if assertion is FALSE

assert

(PHP 4, PHP 5, PHP 7)

assert — Checks if assertion is FALSE

Description

PHP 5 and 7

assert ( mixed $assertion [, string $description ] ) : bool

PHP 7

assert ( mixed $assertion [, Throwable $exception ] ) : bool

assert() will check the given assertion and take appropriate action if its result is FALSE.

Traditional assertions (PHP 5 and 7)

If the assertion is given as a string it will be evaluated as PHP code by assert(). If you pass a boolean condition as assertion, this condition will not show up as parameter to the assertion function which you may have defined with assert_options(). The condition is converted to a string before calling that handler function, and the boolean FALSE is converted as the empty string.

Assertions should be used as a debugging feature only. You may use them for sanity-checks that test for conditions that should always be TRUE and that indicate some programming errors if not or to check for the presence of certain features like extension functions or certain system limits and features.

Assertions should not be used for normal runtime operations like input parameter checks. As a rule of thumb your code should always be able to work correctly if assertion checking is not activated.

The behavior of assert() may be configured by assert_options() or by .ini-settings described in that functions manual page.

The assert_options() function and/or ASSERT_CALLBACK configuration directive allow a callback function to be set to handle failed assertions.

assert() callbacks are particularly useful for building automated test suites because they allow you to easily capture the code passed to the assertion, along with information on where the assertion was made. While this information can be captured via other methods, using assertions makes it much faster and easier!

The callback function should accept three arguments. The first argument will contain the file the assertion failed in. The second argument will contain the line the assertion failed on and the third argument will contain the expression that failed (if any — literal values such as 1 or "two" will not be passed via this argument). Users of PHP 5.4.8 and later may also provide a fourth optional argument, which will contain the description given to assert(), if it was set.

Expectations (PHP 7 only)

assert() is a language construct in PHP 7, allowing for the definition of expectations: assertions that take effect in development and testing environments, but are optimised away to have zero cost in production.

While assert_options() can still be used to control behaviour as described above for backward compatibility reasons, PHP 7 only code should use the two new configuration directives to control the behaviour of assert() and not call assert_options().

PHP 7 configuration directives for assert()
Directive Default value Possible values
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.exception 0
  • 1: throw when the assertion fails, either by throwing the object provided as the exception or by throwing a new AssertionError object if exception wasn't provided
  • 0: use or generate a Throwable as described above, but only generate a warning based on that object rather than throwing it (compatible with PHP 5 behaviour)

Parameters

assertion

The assertion. In PHP 5, this must be either a string to be evaluated or a boolean to be tested. In PHP 7, this may also be any expression that returns a value, which will be executed and the result used to indicate whether the assertion succeeded or failed.

Warning

Using string as the assertion is DEPRECATED as of PHP 7.2.

description

An optional description that will be included in the failure message if the assertion fails.

exception

In PHP 7, the second parameter can be a Throwable object instead of a descriptive string, in which case this is the object that will be thrown if the assertion fails and the assert.exception configuration directive is enabled.

Return Values

FALSE if the assertion is false, TRUE otherwise.

Changelog

Version | Description
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.
7.0.0 | assert() is now a language construct and not a function. assertion can now be an expression. The second parameter is now interpreted either as an exception (if a Throwable object is given), or as the description supported from PHP 5.4.8 onwards.
5.4.8 | The description parameter was added. The description is also now provided to a callback function in ASSERT_CALLBACK mode as the fourth argument.

Examples

Traditional assertions (PHP 5 and 7)

Example #1 Handle a failed assertion with a custom handler

<?php
// Active assert and make it quiet
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);

// Create a handler function
function my_assert_handler($file, $line, $code)
{
    echo "<hr>Assertion Failed:
        File '$file'<br />
        Line '$line'<br />
        Code '$code'<br /><hr />";
}

// Set up the callback
assert_options(ASSERT_CALLBACK, 'my_assert_handler');

// Make an assertion that should fail
assert('mysql_query("")');
?>

Example #2 Using a custom handler to print a description

<?php
// Active assert and make it quiet
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);

// Create a handler function
function my_assert_handler($file, $line, $code, $desc = null)
{
    echo "Assertion failed at $file:$line: $code";
    if ($desc) {
        echo ": $desc";
    }
    echo "\n";
}

// Set up the callback
assert_options(ASSERT_CALLBACK, 'my_assert_handler');

// Make an assertion that should fail
assert('2 < 1');
assert('2 < 1', 'Two is less than one');
?>

The above example will output:

 Assertion failed at test.php:21: 2 < 1
 Assertion failed at test.php:22: 2 < 1: Two is less than one

Expectations (PHP 7 only)

Example #3 Expectations without a custom exception

<?php
assert(true == false);
echo 'Hi!';
?>

With zend.assertions set to 0, the above example will output:

Hi!

With zend.assertions set to 1 and assert.exception set to 0, the above example will output:

Warning: assert(): assert(true == false) failed in - on line 2
Hi!

With zend.assertions set to 1 and assert.exception set to 1, the above example will output:

Fatal error: Uncaught AssertionError: assert(true == false) in -:2
Stack trace:
#0 -(2): assert(false, 'assert(true == ...')
#1 {main}
  thrown in - on line 2

Example #4 Expectations with a custom exception

<?php
class CustomError extends AssertionError {}

assert(true == false, new CustomError('True is not false!'));
echo 'Hi!';
?>

With zend.assertions set to 0, the above example will output:

Hi!

With zend.assertions set to 1 and assert.exception set to 0, the above example will output:

Warning: assert(): CustomError: True is not false! in -:4
Stack trace:
#0 {main} failed in - on line 4
Hi!

With zend.assertions set to 1 and assert.exception set to 1, the above example will output:

Fatal error: Uncaught CustomError: True is not false! in -:4
Stack trace:
#0 {main}
  thrown in - on line 4

See Also

  • assert_options() - Set/get the various assert flags


Returns the current process title

  • « assert
  • cli_set_process_title »
  • PHP Manual
  • PHP Options/Info Functions
  • Returns the current process title

cli_get_process_title

(PHP 5 >= 5.5.0, PHP 7)

cli_get_process_title — Returns the current process title

Description

cli_get_process_title ( void ) : 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


Sets the process title

  • « cli_get_process_title
  • dl »
  • PHP Manual
  • PHP Options/Info Functions
  • Sets the process title

cli_set_process_title

(PHP 5 >= 5.5.0, PHP 7)

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
  • setproctitle() - Set the process title


Loads a PHP extension at runtime

  • « cli_set_process_title
  • extension_loaded »
  • PHP Manual
  • PHP Options/Info Functions
  • Loads a PHP extension at runtime

dl

(PHP 4, PHP 5, PHP 7)

dl — Loads a PHP extension at runtime

Description

dl ( string $library ) : bool

Loads the PHP extension given by the parameter library.

Use extension_loaded() to test whether a given extension is already available or not. This works on both built-in extensions and dynamically loaded ones (either through php.ini or dl()).

Warning

This function was removed from most SAPIs in PHP 5.3.0, and was removed from PHP-FPM in PHP 7.0.0.

Parameters

library

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 (experimental) 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 (either by setting enable_dl off or by enabling safe mode in php.ini) an E_ERROR is emitted and execution is stopped. If dl() fails because the specified library couldn't be loaded, in addition to FALSE an E_WARNING message is emitted.

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

Changelog

Version | Description
7.0.0 | dl() is disabled in PHP-FPM.
5.3.9 | dl() is enabled in PHP-FPM, albeit discouraged.
5.3.0 | dl() is now disabled in some SAPIs due to stability issues. The only SAPIs that allow dl() are CLI and Embed. Use the Extension Loading Directives instead.

Notes

Note:

dl() is not supported when PHP is built with ZTS support. Use the Extension Loading Directives instead.

Note:

dl() is case sensitive on Unix platforms.

Note: This function is disabled when PHP is running in safe mode.

See Also

  • Extension Loading Directives
  • extension_loaded() - Find out whether an extension is loaded


Find out whether an extension is loaded

  • « dl
  • gc_collect_cycles »
  • PHP Manual
  • PHP Options/Info Functions
  • Find out whether an extension is loaded

extension_loaded

(PHP 4, PHP 5, PHP 7)

extension_loaded — Find out whether an extension is loaded

Description

extension_loaded ( string $name ) : bool

Finds out whether the extension is loaded.

Parameters

name

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


Forces collection of any existing garbage cycles

  • « extension_loaded
  • gc_disable »
  • PHP Manual
  • PHP Options/Info Functions
  • Forces collection of any existing garbage cycles

gc_collect_cycles

(PHP 5 >= 5.3.0, PHP 7)

gc_collect_cycles — Forces collection of any existing garbage cycles

Description

gc_collect_cycles ( void ) : 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


Deactivates the circular reference collector

  • « gc_collect_cycles
  • gc_enable »
  • PHP Manual
  • PHP Options/Info Functions
  • Deactivates the circular reference collector

gc_disable

(PHP 5 >= 5.3.0, PHP 7)

gc_disable — Deactivates the circular reference collector

Description

gc_disable ( void ) : 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


Activates the circular reference collector

  • « gc_disable
  • gc_enabled »
  • PHP Manual
  • PHP Options/Info Functions
  • Activates the circular reference collector

gc_enable

(PHP 5 >= 5.3.0, PHP 7)

gc_enable — Activates the circular reference collector

Description

gc_enable ( void ) : 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


Returns status of the circular reference collector

  • « gc_enable
  • gc_mem_caches »
  • PHP Manual
  • PHP Options/Info Functions
  • Returns status of the circular reference collector

gc_enabled

(PHP 5 >= 5.3.0, PHP 7)

gc_enabled — Returns status of the circular reference collector

Description

gc_enabled ( void ) : 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


Reclaims memory used by the Zend Engine memory manager

  • « gc_enabled
  • gc_status »
  • PHP Manual
  • PHP Options/Info Functions
  • Reclaims memory used by the Zend Engine memory manager

gc_mem_caches

(PHP 7)

gc_mem_caches — Reclaims memory used by the Zend Engine memory manager

Description

gc_mem_caches ( void ) : 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


Gets information about the garbage collector

  • « gc_mem_caches
  • get_cfg_var »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets information about the garbage collector

gc_status

(PHP 7 >= 7.3.0)

gc_status — Gets information about the garbage collector

Description

gc_status ( void ) : 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"

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

See Also

  • Garbage Collection


Gets the value of a PHP configuration option

  • « gc_status
  • get_current_user »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets the value of a PHP configuration option

get_cfg_var

(PHP 4, PHP 5, PHP 7)

get_cfg_var — Gets the value of a PHP configuration option

Description

get_cfg_var ( string $option ) : mixed

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.

Changelog

Version | Description
5.3.0 | get_cfg_var() was fixed to be able to return "array" ini options.

See Also

  • ini_get() - Gets the value of a configuration option
  • ini_get_all() - Gets all configuration options


Gets the name of the owner of the current PHP script

  • « get_cfg_var
  • get_defined_constants »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets the name of the owner of the current PHP script

get_current_user

(PHP 4, PHP 5, PHP 7)

get_current_user — Gets the name of the owner of the current PHP script

Description

get_current_user ( void ) : string

Returns the name of the owner of the current PHP script.

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


Returns an associative array with the names of all the constants and their values

  • « get_current_user
  • get_extension_funcs »
  • PHP Manual
  • PHP Options/Info Functions
  • Returns an associative array with the names of all the constants and their values

get_defined_constants

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

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.

Changelog

Version | Description
5.3.1 | Windows only: Core constants are categorized under Core, previously mhash.
5.3.0 | Core constants are categorized under Core, previously internal. On Windows, the Core Constants are categorized under mhash.
5.2.11 | The categorize parameter now operates appropriately. Previously, the categorize parameter was interpreted as !is_null($categorize), making any value other than NULL force the constants to be categorized.

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 given named constant exists
  • 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


Returns an array with the names of the functions of a module

  • « get_defined_constants
  • get_include_path »
  • PHP Manual
  • PHP Options/Info Functions
  • Returns an array with the names of the functions of a module

get_extension_funcs

(PHP 4, PHP 5, PHP 7)

get_extension_funcs — Returns an array with the names of the functions of a module

Description

get_extension_funcs ( string $module_name ) : array

This function returns the names of all the functions defined in the module indicated by module_name.

Parameters

module_name

The module name.

Note:

This parameter must be in lowercase.

Return Values

Returns an array with all the functions, or FALSE if module_name 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
    [22] => utf8_encode
    [23] => utf8_decode
)

See Also

  • get_loaded_extensions() - Returns an array with the names of all modules compiled and loaded
  • ReflectionExtension::getFunctions() - Gets extension functions


Gets the current include_path configuration option

  • « get_extension_funcs
  • get_included_files »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets the current include_path configuration option

get_include_path

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

get_include_path — Gets the current include_path configuration option

Description

get_include_path ( void ) : string

Gets the current include_path configuration option value.

Return Values

Returns the path, as a string.

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


Returns an array with the names of included or required files

  • « get_include_path
  • get_loaded_extensions »
  • PHP Manual
  • PHP Options/Info Functions
  • Returns an array with the names of included or required files

get_included_files

(PHP 4, PHP 5, PHP 7)

get_included_files — Returns an array with the names of included or required files

Description

get_included_files ( void ) : array

Gets the names of all files that have been included using include, include_once, require or require_once.

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


Returns an array with the names of all modules compiled and loaded

  • « get_included_files
  • get_magic_quotes_gpc »
  • PHP Manual
  • PHP Options/Info Functions
  • Returns an array with the names of all modules compiled and loaded

get_loaded_extensions

(PHP 4, PHP 5, PHP 7)

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.

Changelog

Version | Description
5.2.4 | The optional zend_extensions parameter was added

Examples

Example #1 get_loaded_extensions() Example

<?php
print_r(get_loaded_extensions());
?>

The above example will output something similar to:

Array
(
   [0] => xml
   [1] => wddx
   [2] => standard
   [3] => session
   [4] => posix
   [5] => pgsql
   [6] => pcre
   [7] => gd
   [8] => ftp
   [9] => db
   [10] => calendar
   [11] => bcmath
)

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


Gets the current configuration setting of magic_quotes_gpc

  • « get_loaded_extensions
  • get_magic_quotes_runtime »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets the current configuration setting of magic_quotes_gpc

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. Relying on this function is highly discouraged.

Description

get_magic_quotes_gpc ( void ) : bool

Returns the current configuration setting of magic_quotes_gpc

Keep in mind that attempting to set magic_quotes_gpc at runtime will not work.

For more information about magic_quotes, see this security section.

Return Values

Returns 0 if magic_quotes_gpc is off, 1 otherwise. Or always returns FALSE as of PHP 5.4.0.

Changelog

Version | Description
7.4.0 | This function has been deprecated.
5.4.0 | Always returns FALSE because the magic quotes feature was removed from PHP.

Examples

Example #1 get_magic_quotes_gpc() example

<?php
// If magic quotes are enabled
echo $_POST['lastname'];             // O\'reilly
echo addslashes($_POST['lastname']); // O\\\'reilly

// Usage across all PHP versions
if (get_magic_quotes_gpc()) {
    $lastname = stripslashes($_POST['lastname']);
}
else {
    $lastname = $_POST['lastname'];
}

// If using MySQL
$lastname = mysql_real_escape_string($lastname);

echo $lastname; // O\'reilly
$sql = "INSERT INTO lastnames (lastname) VALUES ('$lastname')";
?>

Notes

Note:

If the directive magic_quotes_sybase is ON it will completely override magic_quotes_gpc. So even when get_magic_quotes_gpc() returns TRUE neither double quotes, backslashes or NUL's will be escaped. Only single quotes will be escaped. In this case they'll look like: ''

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


Gets the current active configuration setting of magic_quotes_runtime

  • « get_magic_quotes_gpc
  • get_required_files »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets the current active configuration setting of magic_quotes_runtime

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. Relying on this function is highly discouraged.

Description

get_magic_quotes_runtime ( void ) : bool

Returns the current active configuration setting of magic_quotes_runtime.

Return Values

Returns 0 if magic_quotes_runtime is off, 1 otherwise. Or always returns FALSE as of PHP 5.4.0.

Changelog

Version | Description
7.4.0 | This function has been deprecated.
5.4.0 | Always returns FALSE because the magic quotes feature was removed from PHP.

Examples

Example #1 get_magic_quotes_runtime() example

<?php
// Check if magic_quotes_runtime is active
if(get_magic_quotes_runtime())
{
    // Deactivate
    set_magic_quotes_runtime(false);
}
?>

See Also

  • get_magic_quotes_gpc() - Gets the current configuration setting of magic_quotes_gpc
  • set_magic_quotes_runtime() - Sets the current active configuration setting of magic_quotes_runtime


Alias of get_included_files

  • « get_magic_quotes_runtime
  • get_resources »
  • PHP Manual
  • PHP Options/Info Functions
  • Alias of get_included_files

get_required_files

(PHP 4, PHP 5, PHP 7)

get_required_files — Alias of get_included_files()

Description

This function is an alias of: get_included_files().


Returns active resources

  • « get_required_files
  • getenv »
  • PHP Manual
  • PHP Options/Info Functions
  • Returns active resources

get_resources

(PHP 7)

get_resources — Returns active resources

Description

get_resources ([ string $type ] ) : array

Returns an array of all currently active resources, optionally filtered by resource type.

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.

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


Gets the value of an environment variable

  • « get_resources
  • getlastmod »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets the value of an environment variable

getenv

(PHP 4, PHP 5, PHP 7)

getenv — Gets the value of an environment variable

Description

getenv ( string $varname [, bool $local_only = FALSE ] ) : string
getenv ( void ) : array

Gets the value of an environment variable.

You can see a list of all the environmental variables by using phpinfo(). Many of these variables are listed within » RFC 3875, specifically section 4.1, "Request Meta-Variables".

Parameters

varname

The variable name.

local_only

Set to true to only return local environment variables (set by the operating system or putenv).

Return Values

Returns the value of the environment variable varname, or FALSE if the environment variable varname does not exist. If varname is omitted, all environment variables are returned as associative array.

Changelog

Version | Description
7.1.0 | The varname can now be omitted to retrieve an associative array of all environment variables.
5.5.38, 5.6.24, 7.0.9 | The local_only parameter has been added.

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.

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

See Also

  • putenv() - Sets the value of an environment variable
  • apache_getenv() - Get an Apache subprocess_env variable
  • Superglobals


Gets time of last page modification

  • « getenv
  • getmygid »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets time of last page modification

getlastmod

(PHP 4, PHP 5, PHP 7)

getlastmod — Gets time of last page modification

Description

getlastmod ( void ) : int

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

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 local time/date
  • 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


Get PHP script owner's GID

  • « getlastmod
  • getmyinode »
  • PHP Manual
  • PHP Options/Info Functions
  • Get PHP script owner's GID

getmygid

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

getmygid — Get PHP script owner's GID

Description

getmygid ( void ) : int

Gets the group ID of the current script.

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


Gets the inode of the current script

  • « getmygid
  • getmypid »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets the inode of the current script

getmyinode

(PHP 4, PHP 5, PHP 7)

getmyinode — Gets the inode of the current script

Description

getmyinode ( void ) : int

Gets the inode of the current script.

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


Gets PHP's process ID

  • « getmyinode
  • getmyuid »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets PHP's process ID

getmypid

(PHP 4, PHP 5, PHP 7)

getmypid — Gets PHP's process ID

Description

getmypid ( void ) : int

Gets the current PHP process ID.

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


Gets PHP script owner's UID

  • « getmypid
  • getopt »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets PHP script owner's UID

getmyuid

(PHP 4, PHP 5, PHP 7)

getmyuid — Gets PHP script owner's UID

Description

getmyuid ( void ) : int

Gets the user ID of the current script.

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


Gets options from the command line argument list

  • « getmyuid
  • getrusage »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets options from the command line argument list

getopt

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

getopt — Gets options from the command line argument list

Description

getopt ( string $options [, array $longopts [, int &$optind ]] ) : array

Parses options passed to the script.

Parameters

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.
longopts
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.
optind
If the optind parameter is present, then the index where argument parsing stopped will be written to this variable.

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

Note:

The format for the options and longopts is almost the same, the only difference is that longopts takes an array of options (where each element is the option) whereas 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 optind parameter.
5.3.0 | Added support for "=" as argument/value separator.
5.3.0 | Added support for optional values (specified with "::").
5.3.0 | Parameter longopts is available on all systems.
5.3.0 | This function is no longer system dependent, and now works on Windows, too.

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 optind

<?php
// Script example.php
$optind = null;
$opts = getopt('a:b:', [], $optind);
$pos_args = array_slice($argv, $optind);
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


Gets the current resource usages

  • « getopt
  • ini_alter »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets the current resource usages

getrusage

(PHP 4, PHP 5, PHP 7)

getrusage — Gets the current resource usages

Description

getrusage ([ int $who = 0 ] ) : array

This is an interface to getrusage(2). It gets data returned from the system call.

Parameters

who

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

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

Changelog

Version | Description
7.0.0 | This function is now supported on Windows.

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 who is RUSAGE_SELF)
  • "ru_maxrss" (only if who is RUSAGE_SELF)

If getrusage() is called with who 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)


Alias of ini_set

  • « getrusage
  • ini_get_all »
  • PHP Manual
  • PHP Options/Info Functions
  • Alias of ini_set

ini_alter

(PHP 4, PHP 5, PHP 7)

ini_alter — Alias of ini_set()

Description

This function is an alias of: ini_set().


Gets all configuration options

  • « ini_alter
  • ini_get »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets all configuration options

ini_get_all

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

ini_get_all — Gets all configuration options

Description

ini_get_all ([ string $extension [, bool $details = TRUE ]] ) : array

Returns all the registered configuration options.

Parameters

extension

An optional extension name. If set, the function return only options specific for that extension.

details

Retrieve details settings or only the current value for each setting. Default is TRUE (retrieve details).

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.

Notes

Note:

ini_get_all() ignores "array" ini options such as pdo.dsn.*.

Changelog

Version | Description
5.3.0 | Added details.

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

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


Gets the value of a configuration option

  • « ini_get_all
  • ini_restore »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets the value of a configuration option

ini_get

(PHP 4, PHP 5, PHP 7)

ini_get — Gets the value of a configuration option

Description

ini_get ( string $varname ) : string

Returns the value of the configuration option on success.

Parameters

varname

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
register_globals = Off
post_max_size = 8M
*/

echo 'display_errors = ' . ini_get('display_errors') . "\n";
echo 'register_globals = ' . ini_get('register_globals') . "\n";
echo 'post_max_size = ' . ini_get('post_max_size') . "\n";
echo 'post_max_size+1 = ' . (ini_get('post_max_size')+1) . "\n";
echo 'post_max_size in bytes = ' . return_bytes(ini_get('post_max_size'));

function return_bytes($val) {
    $val = trim($val);
    $last = strtolower($val[strlen($val)-1]);
    switch($last) {
        // The 'G' modifier is available since PHP 5.1.0
        case 'g':
            $val *= 1024;
        case 'm':
            $val *= 1024;
        case 'k':
            $val *= 1024;
    }

    return $val;
}

?>

The above example will output something similar to:

display_errors = 1
register_globals = 0
post_max_size = 8M
post_max_size+1 = 9
post_max_size in bytes = 8388608

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 integer equivalent. Attempting normal arithmetic functions on these values will not have otherwise expected results. The example above shows one way to convert shorthand notation into bytes, much like how the PHP source does it.

Note:

ini_get() can't read "array" ini options such as pdo.dsn.*, and returns FALSE in this case.

Changelog

Version | Description
5.3.0 | Previously, the empty string was returned if the configuration option didn't exist. now, FALSE is returned instead.

See Also

  • get_cfg_var() - Gets the value of a PHP configuration option
  • ini_get_all() - Gets all configuration options
  • ini_restore() - Restores the value of a configuration option
  • ini_set() - Sets the value of a configuration option


Restores the value of a configuration option

  • « ini_get
  • ini_set »
  • PHP Manual
  • PHP Options/Info Functions
  • Restores the value of a configuration option

ini_restore

(PHP 4, PHP 5, PHP 7)

ini_restore — Restores the value of a configuration option

Description

ini_restore ( string $varname ) : void

Restores a given configuration option to its original value.

Parameters

varname

The configuration option name.

Return Values

No value is returned.

Examples

Example #1 ini_restore() example

<?php
$setting = 'y2k_compliance';

echo 'Current value for \'' . $setting . '\': ' . ini_get($setting), PHP_EOL;

ini_set($setting, ini_get($setting) ? 0 : 1);
echo 'New value for \'' . $setting . '\': ' . ini_get($setting), PHP_EOL;

ini_restore($setting);
echo 'Original value for \'' . $setting . '\': ' . ini_get($setting), PHP_EOL;
?>

The above example will output:

Current value for 'y2k_compliance': 1
New value for 'y2k_compliance': 0
Original value for 'y2k_compliance': 1

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


Sets the value of a configuration option

  • « ini_restore
  • magic_quotes_runtime »
  • PHP Manual
  • PHP Options/Info Functions
  • Sets the value of a configuration option

ini_set

(PHP 4, PHP 5, PHP 7)

ini_set — Sets the value of a configuration option

Description

ini_set ( string $varname , string $newvalue ) : string

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

varname

Not all the available options can be changed using ini_set(). There is a list of all available options in the appendix.

newvalue

The new value for the option.

Return Values

Returns the old value on success, FALSE on failure.

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


Alias of set_magic_quotes_runtime

  • « ini_set
  • main »
  • PHP Manual
  • PHP Options/Info Functions
  • Alias of set_magic_quotes_runtime

magic_quotes_runtime

(PHP 4, PHP 5)

magic_quotes_runtime — Alias of set_magic_quotes_runtime()

Warning

This alias was DEPRECATED in PHP 5.3.0, and REMOVED as of PHP 7.0.0.

Description

This function is an alias of: set_magic_quotes_runtime()


Dummy for main

  • « magic_quotes_runtime
  • memory_get_peak_usage »
  • PHP Manual
  • PHP Options/Info Functions
  • Dummy for main

main

main — Dummy for main()

Description

There is no function named main() except in the PHP source. In PHP 4.3.0, a new type of error handling in the PHP source (php_error_docref) was introduced. One feature is to provide links to a manual page in PHP error messages when the PHP directives html_errors (on by default) and docref_root (on by default until PHP 4.3.2) are set.

Sometimes error messages refer to a manual page for the function main() which is why this page exists. If you discover such a reference, please » file a bug report, indicating the PHP function caused the error that linked to main() and it will be fixed and properly documented.

Known errors that point to main()
Function name | No longer points here as of
include | 5.1.0
include_once | 5.1.0
require | 5.1.0
require_once | 5.1.0

See Also

  • html_errors
  • display_errors


Returns the peak of memory allocated by PHP

  • « main
  • memory_get_usage »
  • PHP Manual
  • PHP Options/Info Functions
  • Returns the peak of memory allocated by PHP

memory_get_peak_usage

(PHP 5 >= 5.2.0, PHP 7)

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.

Changelog

Version | Description
5.2.1 | Compiling with --enable-memory-limit is no longer required for this function to exist.
5.2.0 | real_usage was added.

See Also

  • memory_get_usage() - Returns the amount of memory allocated to PHP
  • memory_limit


Returns the amount of memory allocated to PHP

  • « memory_get_peak_usage
  • php_ini_loaded_file »
  • PHP Manual
  • PHP Options/Info Functions
  • Returns the amount of memory allocated to PHP

memory_get_usage

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

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.

Changelog

Version | Description
5.2.1 | Compiling with --enable-memory-limit is no longer required for this function to exist.
5.2.0 | real_usage was added.

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


Retrieve a path to the loaded php.ini file

  • « memory_get_usage
  • php_ini_scanned_files »
  • PHP Manual
  • PHP Options/Info Functions
  • Retrieve a path to the loaded php.ini file

php_ini_loaded_file

(PHP 5 >= 5.2.4, PHP 7)

php_ini_loaded_file — Retrieve a path to the loaded php.ini file

Description

php_ini_loaded_file ( void ) : string

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


Return a list of .ini files parsed from the additional ini dir

  • « php_ini_loaded_file
  • php_logo_guid »
  • PHP Manual
  • PHP Options/Info Functions
  • Return a list of .ini files parsed from the additional ini dir

php_ini_scanned_files

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

php_ini_scanned_files — Return a list of .ini files parsed from the additional ini dir

Description

php_ini_scanned_files ( void ) : string

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.

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


Gets the logo guid

  • « php_ini_scanned_files
  • php_sapi_name »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets the logo guid

php_logo_guid

(PHP 4, PHP 5 < 5.5.0)

php_logo_guid — Gets the logo guid

Description

php_logo_guid ( void ) : string

This function returns the ID which can be used to display the PHP logo using the built-in image. Logo is displayed only if expose_php is On.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.5.0.

Return Values

Returns PHPE9568F34-D428-11d2-A769-00AA001ACF42.

Changelog

Version | Description
5.5.0 | php_logo_guid() has been removed from PHP.

Examples

Example #1 php_logo_guid() example

<?php

echo '<img src="' . $_SERVER['PHP_SELF'] .
     '?=' . php_logo_guid() . '" alt="PHP Logo !" />';

?>

See Also

  • phpinfo() - Outputs information about PHP's configuration
  • phpversion() - Gets the current PHP version
  • phpcredits() - Prints out the credits for PHP
  • zend_logo_guid() - Gets the Zend guid


Returns the type of interface between web server and PHP

  • « php_logo_guid
  • php_uname »
  • PHP Manual
  • PHP Options/Info Functions
  • Returns the type of interface between web server and PHP

php_sapi_name

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

php_sapi_name — Returns the type of interface between web server and PHP

Description

php_sapi_name ( void ) : string

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.

Return Values

Returns the interface type, as a lowercase string.

Although not exhaustive, the possible return values include aolserver, apache, apache2filter, apache2handler, caudium, cgi (until PHP 5.3), cgi-fcgi, cli, cli-server, continuity, embed, fpm-fcgi, isapi, litespeed, milter, nsapi, phpdbg, phttpd, pi3web, roxen, thttpd, tux, and webjames.

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 or apache2filter.

See Also

  • PHP_SAPI


Returns information about the operating system PHP is running on

  • « php_sapi_name
  • phpcredits »
  • PHP Manual
  • PHP Options/Info Functions
  • Returns information about the operating system PHP is running on

php_uname

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

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. Contains all modes in the sequence "s n r v m".
  • '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.

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


Prints out the credits for PHP

  • « php_uname
  • phpinfo »
  • PHP Manual
  • PHP Options/Info Functions
  • Prints out the credits for PHP

phpcredits

(PHP 4, PHP 5, PHP 7)

phpcredits — Prints out the credits for PHP

Description

phpcredits ([ int $flag = CREDITS_ALL ] ) : bool

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

flag

To generate a custom credits page, you may want to use the flag 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

Returns TRUE on success or FALSE on failure.

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
  • php_logo_guid() - Gets the logo guid
  • phpinfo() - Outputs information about PHP's configuration


Outputs information about PHP's configuration

  • « phpcredits
  • phpversion »
  • PHP Manual
  • PHP Options/Info Functions
  • Outputs information about PHP's configuration

phpinfo

(PHP 4, PHP 5, PHP 7)

phpinfo — Outputs information about PHP's configuration

Description

phpinfo ([ int $what = INFO_ALL ] ) : bool

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

what

The output may be customized by passing one or more of the following constants bitwise values summed together in the optional what parameter. One can also combine the respective constants or bitwise values together with the 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

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.5.0 | Logo GUIDs were replaced with data URIs, and so turning off expose_php now has no effect on the result of phpinfo(). Credits are also now embedded within the output itself instead of linked.
5.2.2 | The "Loaded Configuration File" information was added, when before only "Configuration File (php.ini) Path" existed.

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
  • php_logo_guid() - Gets the logo guid
  • 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


Gets the current PHP version

  • « phpinfo
  • putenv »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets the current PHP version

phpversion

(PHP 4, PHP 5, PHP 7)

phpversion — Gets the current PHP version

Description

phpversion ([ string $extension ] ) : string

Returns a string containing the version of the currently running PHP parser or extension.

Parameters

extension

An optional extension name.

Return Values

If the optional extension parameter is specified, phpversion() returns the version of that extension, or FALSE if there is no version information associated or the extension isn't enabled.

Examples

Example #1 phpversion() example

<?php
// prints e.g. 'Current PHP version: 4.1.1'
echo 'Current PHP version: ' . phpversion();

// prints e.g. '2.0' or nothing if the extension isn't enabled
echo phpversion('tidy');
?>

Example #2 PHP_VERSION_ID example and usage

<?php
// PHP_VERSION_ID is available as of PHP 5.2.7, if our
// version is lower than that, then emulate it
if (!defined('PHP_VERSION_ID')) {
    $version = explode('.', PHP_VERSION);

    define('PHP_VERSION_ID', ($version[0] * 10000 + $version[1] * 100 + $version[2]));
}

// PHP_VERSION_ID is defined as a number, where the higher the number
// is, the newer a PHP version is used. It's defined as used in the above
// expression:
//
// $version_id = $major_version * 10000 + $minor_version * 100 + $release_version;
//
// Now with PHP_VERSION_ID we can check for features this PHP version
// may have, this doesn't require to use version_compare() everytime
// you check if the current PHP version may not support a feature.
//
// For example, we may here define the PHP_VERSION_* constants thats
// not available in versions prior to 5.2.7

if (PHP_VERSION_ID < 50207) {
    define('PHP_MAJOR_VERSION',   $version[0]);
    define('PHP_MINOR_VERSION',   $version[1]);
    define('PHP_RELEASE_VERSION', $version[2]);

    // and so on, ...
}
?>

Notes

Note:

This information is also available in the predefined constant PHP_VERSION. More versioning information is available using the PHP_VERSION_* constants.

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
  • php_logo_guid() - Gets the logo guid
  • zend_version() - Gets the version of the current Zend engine


Sets the value of an environment variable

  • « phpversion
  • restore_include_path »
  • PHP Manual
  • PHP Options/Info Functions
  • Sets the value of an environment variable

putenv

(PHP 4, PHP 5, PHP 7)

putenv — Sets the value of an environment variable

Description

putenv ( string $setting ) : bool

Adds setting to the server environment. The environment variable will only exist for the duration of the current request. At the end of the request the environment is restored to its original state.

Setting certain environment variables may be a potential security breach. The safe_mode_allowed_env_vars directive contains a comma-delimited list of prefixes. In Safe Mode, the user may only alter environment variables whose names begin with the prefixes supplied by this directive. By default, users will only be able to set environment variables that begin with PHP_ (e.g. PHP_FOO=BAR). Note: if this directive is empty, PHP will let the user modify ANY environment variable!

The safe_mode_protected_env_vars directive contains a comma-delimited list of environment variables, that the end user won't be able to change using putenv(). These variables will be protected even if safe_mode_allowed_env_vars is set to allow to change them.

Parameters

setting

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");
?>

Notes

Warning

The safe_mode_allowed_env_vars and safe_mode_protected_env_vars directives only take effect when safe_mode is enabled.

See Also

  • getenv() - Gets the value of an environment variable
  • apache_setenv() - Set an Apache subprocess_env variable


Restores the value of the include_path configuration option

  • « putenv
  • set_include_path »
  • PHP Manual
  • PHP Options/Info Functions
  • Restores the value of the include_path configuration option

restore_include_path

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

restore_include_path — Restores the value of the include_path configuration option

Description

restore_include_path ( void ) : void

Restores the include_path configuration option back to its original master value as set in php.ini

Return Values

No value is returned.

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


Sets the include_path configuration option

  • « restore_include_path
  • set_magic_quotes_runtime »
  • PHP Manual
  • PHP Options/Info Functions
  • Sets the include_path configuration option

set_include_path

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

set_include_path — Sets the include_path configuration option

Description

set_include_path ( string $new_include_path ) : string

Sets the include_path configuration option for the duration of the script.

Parameters

new_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


Sets the current active configuration setting of magic_quotes_runtime

  • « set_include_path
  • set_time_limit »
  • PHP Manual
  • PHP Options/Info Functions
  • Sets the current active configuration setting of magic_quotes_runtime

set_magic_quotes_runtime

(PHP 4, PHP 5)

set_magic_quotes_runtime — Sets the current active configuration setting of magic_quotes_runtime

Warning

This function was DEPRECATED in PHP 5.3.0, and REMOVED as of PHP 7.0.0.

Description

set_magic_quotes_runtime ( bool $new_setting ) : bool

Set the current active configuration setting of magic_quotes_runtime.

Errors/Exceptions

Since PHP 5.3 this function has been deprecated and will raise an E_DEPRECATED warning upon execution. Since PHP 5.4 this function will also raise an E_CORE_ERROR on trying to enable magic quotes.

Parameters

new_setting

FALSE for off, TRUE for on.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 set_magic_quotes_runtime() example

<?php
// Create a temporary file pointer
$fp = tmpfile();

// Write some data to the pointer
fwrite($fp, '\'PHP\' is a Recursive acronym');

// Without magic_quotes_runtime
rewind($fp);
set_magic_quotes_runtime(false);

echo 'Without magic_quotes_runtime: ' . fread($fp, 64), PHP_EOL;

// With magic_quotes_runtime
rewind($fp);
set_magic_quotes_runtime(true);

echo 'With magic_quotes_runtime: ' . fread($fp, 64), PHP_EOL;

// Clean up
fclose($fp);
?>

The above example will output:

Without magic_quotes_runtime: 'PHP' is a Recursive acronym
With magic_quotes_runtime: \'PHP\' is a Recursive acronym

See Also

  • 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


Limits the maximum execution time

  • « set_magic_quotes_runtime
  • sys_get_temp_dir »
  • PHP Manual
  • PHP Options/Info Functions
  • Limits the maximum execution time

set_time_limit

(PHP 4, PHP 5, PHP 7)

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

Warning

This function has no effect when PHP is running in safe mode. There is no workaround other than turning off safe mode or changing the time limit in the php.ini.

Note:

The set_time_limit() function and the configuration directive max_execution_time only affect the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system(), stream operations, database queries, etc. is not included when determining the maximum time that the script has been running. This is not true on Windows where the measured time is real.

See Also

  • max_execution_time
  • max_input_time


Returns directory path used for temporary files

  • « set_time_limit
  • version_compare »
  • PHP Manual
  • PHP Options/Info Functions
  • Returns directory path used for temporary files

sys_get_temp_dir

(PHP 5 >= 5.2.1, PHP 7)

sys_get_temp_dir — Returns directory path used for temporary files

Description

sys_get_temp_dir ( void ) : string

Returns the path of the directory PHP stores temporary files in by default.

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


Compares two "PHP-standardized" version number strings

  • « sys_get_temp_dir
  • zend_logo_guid »
  • PHP Manual
  • PHP Options/Info Functions
  • Compares two "PHP-standardized" version number strings

version_compare

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

version_compare — Compares two "PHP-standardized" version number strings

Description

version_compare ( string $version1 , string $version2 ) : int
version_compare ( string $version1 , string $version2 , string $operator ) : 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

If the third optional operator argument is specified, test for a particular relationship. 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. If an unsupported operator is given, NULL is returned.

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


Gets the Zend guid

  • « version_compare
  • zend_thread_id »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets the Zend guid

zend_logo_guid

(PHP 4, PHP < 5.5.0)

zend_logo_guid — Gets the Zend guid

Description

zend_logo_guid ( void ) : string

This function returns the ID which can be used to display the Zend logo using the built-in image.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.5.0.

Return Values

Returns PHPE9568F35-D428-11d2-A769-00AA001ACF42.

Changelog

Version | Description
5.5.0 | zend_logo_guid() has been removed from PHP.

Examples

Example #1 zend_logo_guid() example

<?php

echo '<img src="' . $_SERVER['PHP_SELF'] .
     '?=' . zend_logo_guid() . '" alt="Zend Logo !" />';

?>

See Also

  • php_logo_guid() - Gets the logo guid


Returns a unique identifier for the current thread

  • « zend_logo_guid
  • zend_version »
  • PHP Manual
  • PHP Options/Info Functions
  • Returns a unique identifier for the current thread

zend_thread_id

(PHP 5, PHP 7)

zend_thread_id — Returns a unique identifier for the current thread

Description

zend_thread_id ( void ) : int

This function returns a unique identifier for the current thread.

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


Gets the version of the current Zend engine

  • « zend_thread_id
  • phpdbg »
  • PHP Manual
  • PHP Options/Info Functions
  • Gets the version of the current Zend engine

zend_version

(PHP 4, PHP 5, PHP 7)

zend_version — Gets the version of the current Zend engine

Description

zend_version ( void ) : string

Returns a string containing the version of the currently running Zend Engine.

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
  • php_logo_guid() - Gets the logo guid
  • phpversion() - Gets the current PHP version


Interactive PHP Debugger

  • Introduction
  • 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 — Description
    • phpdbg_exec — Attempts to set the execution context
    • phpdbg_get_executable — Description
    • phpdbg_prompt — Sets the command prompt
    • phpdbg_start_oplog — Description


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


  • « Introduction
  • Runtime Configuration »
  • PHP Manual
  • phpdbg
  • Installing/Configuring

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 | PHP_INI_ALL | Available as of PHP 7.0.0
phpdbg.path |  | 6 | Available as of PHP 5.6.3

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 (integer)
Removed as of PHP 7.3.0.
PHPDBG_METHOD (integer)
Removed as of PHP 7.3.0.
PHPDBG_LINENO (integer)
Removed as of PHP 7.3.0.
PHPDBG_FUNC (integer)
Removed as of PHP 7.3.0.
PHPDBG_COLOR_PROMPT (integer)
PHPDBG_COLOR_NOTICE (integer)
PHPDBG_COLOR_ERROR (integer)


phpdbg Functions

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 — Description
  • phpdbg_exec — Attempts to set the execution context
  • phpdbg_get_executable — Description
  • phpdbg_prompt — Sets the command prompt
  • phpdbg_start_oplog — Description


Inserts a breakpoint at a line in a file

  • « phpdbg Functions
  • phpdbg_break_function »
  • PHP Manual
  • phpdbg Functions
  • Inserts a breakpoint at a line in a file

phpdbg_break_file

(PHP 5 >= 5.6.3, PHP 7)

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


Inserts a breakpoint at entry to a function

  • « phpdbg_break_file
  • phpdbg_break_method »
  • PHP Manual
  • phpdbg Functions
  • Inserts a breakpoint at entry to a function

phpdbg_break_function

(PHP 5 >= 5.6.3, PHP 7)

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


Inserts a breakpoint at entry to a method

  • « phpdbg_break_function
  • phpdbg_break_next »
  • PHP Manual
  • phpdbg Functions
  • Inserts a breakpoint at entry to a method

phpdbg_break_method

(PHP 5 >= 5.6.3, PHP 7)

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


Inserts a breakpoint at the next opcode

  • « phpdbg_break_method
  • phpdbg_clear »
  • PHP Manual
  • phpdbg Functions
  • Inserts a breakpoint at the next opcode

phpdbg_break_next

(PHP 5 >= 5.6.3, PHP 7)

phpdbg_break_next — Inserts a breakpoint at the next opcode

Description

phpdbg_break_next ( void ) : 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


Clears all breakpoints

  • « phpdbg_break_next
  • phpdbg_color »
  • PHP Manual
  • phpdbg Functions
  • Clears all breakpoints

phpdbg_clear

(PHP 5 >= 5.6.0, PHP 7)

phpdbg_clear — Clears all breakpoints

Description

phpdbg_clear ( void ) : void

Clear all breakpoints that have been set, either via one of the phpdbg_break_*() functions or interactively in the console.

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.

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


Sets the color of certain elements

  • « phpdbg_clear
  • phpdbg_end_oplog »
  • PHP Manual
  • phpdbg Functions
  • Sets the color of certain elements

phpdbg_color

(PHP 5 >= 5.6.0, PHP 7)

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


Description

  • « phpdbg_color
  • phpdbg_exec »
  • PHP Manual
  • phpdbg Functions
  • Description

phpdbg_end_oplog

(PHP 7)

phpdbg_end_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


Attempts to set the execution context

  • « phpdbg_end_oplog
  • phpdbg_get_executable »
  • PHP Manual
  • phpdbg Functions
  • Attempts to set the execution context

phpdbg_exec

(PHP 5 >= 5.6.0, PHP 7)

phpdbg_exec — Attempts to set the execution context

Description

phpdbg_exec ([ string $context ] ) : mixed

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.


Description

  • « phpdbg_exec
  • phpdbg_prompt »
  • PHP Manual
  • phpdbg Functions
  • Description

phpdbg_get_executable

(PHP 7)

phpdbg_get_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


Sets the command prompt

  • « phpdbg_get_executable
  • phpdbg_start_oplog »
  • PHP Manual
  • phpdbg Functions
  • Sets the command prompt

phpdbg_prompt

(PHP 5 >= 5.6.0, PHP 7)

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


Description

  • « phpdbg_prompt
  • runkit »
  • PHP Manual
  • phpdbg Functions
  • Description

phpdbg_start_oplog

(PHP 7)

phpdbg_start_oplog —

Description

phpdbg_start_oplog ( void ) : 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.


runkit

  • Introduction
  • Predefined Constants
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • runkit Functions
    • Runkit_Sandbox — Runkit Sandbox Class -- PHP Virtual Machine
    • Runkit_Sandbox_Parent — Runkit Anti-Sandbox Class
    • runkit_class_adopt — Convert a base class to an inherited class, add ancestral methods when appropriate
    • runkit_class_emancipate — Convert an inherited class to a base class, removes any method whose scope is ancestral
    • runkit_constant_add — Similar to define(), but allows defining in class definitions as well
    • runkit_constant_redefine — Redefine an already defined constant
    • runkit_constant_remove — Remove/Delete an already defined constant
    • runkit_function_add — Add a new function, similar to create_function
    • runkit_function_copy — Copy a function to a new function name
    • runkit_function_redefine — Replace a function definition with a new implementation
    • runkit_function_remove — Remove a function definition
    • runkit_function_rename — Change a function's name
    • runkit_import — Process a PHP file importing function and class definitions, overwriting where appropriate
    • runkit_lint_file — Check the PHP syntax of the specified file
    • runkit_lint — Check the PHP syntax of the specified php code
    • runkit_method_add — Dynamically adds a new method to a given class
    • runkit_method_copy — Copies a method from class to another
    • runkit_method_redefine — Dynamically changes the code of the given method
    • runkit_method_remove — Dynamically removes the given method
    • runkit_method_rename — Dynamically changes the name of the given method
    • runkit_return_value_used — Determines if the current functions return value will be used
    • runkit_sandbox_output_handler — Specify a function to capture and/or process output from a runkit sandbox
    • runkit_superglobals — Return numerically indexed array of registered superglobals


Introduction

The runkit extension provides means to modify constants, user-defined functions, and user-defined classes. It also provides for custom superglobal variables and embeddable sub-interpreters via sandboxing.

This package is meant as a feature added replacement for the » classkit package. When compiled with the --enable-runkit=classkit option to ./configure, it will export classkit compatible function definitions and constants.


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.

RUNKIT_IMPORT_FUNCTIONS (integer)
runkit_import() flag indicating that normal functions should be imported from the specified file.
RUNKIT_IMPORT_CLASS_METHODS (integer)
runkit_import() flag indicating that class methods should be imported from the specified file.
RUNKIT_IMPORT_CLASS_CONSTS (integer)
runkit_import() flag indicating that class constants should be imported from the specified file. Note that this flag is only meaningful in PHP versions 5.1.0 and above.
RUNKIT_IMPORT_CLASS_PROPS (integer)
runkit_import() flag indicating that class standard properties should be imported from the specified file.
RUNKIT_IMPORT_CLASS_STATIC_PROPS (integer)
runkit_import() flag indicating that class static properties should be imported from the specified file. Available since Runkit 1.0.1.
RUNKIT_IMPORT_CLASSES (integer)
runkit_import() flag representing a bitwise OR of the RUNKIT_IMPORT_CLASS_* constants.
RUNKIT_IMPORT_OVERRIDE (integer)
runkit_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.
RUNKIT_ACC_PUBLIC (integer)
PHP 5 specific flag to runkit_method_add() and runkit_method_redefine()
RUNKIT_ACC_PROTECTED (integer)
PHP 5 specific flag to runkit_method_add() and runkit_method_redefine()
RUNKIT_ACC_PRIVATE (integer)
PHP 5 specific flag to runkit_method_add() and runkit_method_redefine()
RUNKIT_ACC_STATIC (integer)
PHP 5 specific flag to runkit_method_add() and runkit_method_redefine(). Available since Runkit 1.0.1.
CLASSKIT_ACC_PUBLIC (integer)
PHP 5 specific flag to classkit_method_add() Only defined when classkit compatibility is enabled.
CLASSKIT_ACC_PROTECTED (integer)
PHP 5 specific flag to classkit_method_add() Only defined when classkit compatibility is enabled.
CLASSKIT_ACC_PRIVATE (integer)
PHP 5 specific flag to classkit_method_add() Only defined when classkit compatibility is enabled.
CLASSKIT_AGGREGATE_OVERRIDE (integer)
PHP 5 specific flag to classkit_import() Only defined when classkit compatibility is enabled.
RUNKIT_VERSION (string)
Defined to the current version of the runkit package.
CLASSKIT_VERSION (string)
Defined to the current version of the runkit package. Only defined when classkit compatibility is enabled.


Requirements

Modifying Constants, Functions, Classes, and Methods as well as Custom Superglobals works with all releases of PHP 5. No special requirements are necessary.

Sandboxing requires PHP 5.1.0 or later, or PHP 5.0.0 with a special TSRM patch applied. Regardless of which version of PHP is in use it must be compiled with the --enable-maintainer-zts option. See the README file in the runkit package for additional information.


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

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 | "" | PHP_INI_PERDIR |
runkit.internal_override | "0" | PHP_INI_SYSTEM |
For further details and definitions of the PHP_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 boolean
Enables ability to modify/rename/remove internal functions.


  • « Runtime Configuration
  • runkit Functions »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

This extension has no resource types defined.


runkit Functions

Table of Contents

  • Runkit_Sandbox — Runkit Sandbox Class -- PHP Virtual Machine
  • Runkit_Sandbox_Parent — Runkit Anti-Sandbox Class
  • runkit_class_adopt — Convert a base class to an inherited class, add ancestral methods when appropriate
  • runkit_class_emancipate — Convert an inherited class to a base class, removes any method whose scope is ancestral
  • runkit_constant_add — Similar to define(), but allows defining in class definitions as well
  • runkit_constant_redefine — Redefine an already defined constant
  • runkit_constant_remove — Remove/Delete an already defined constant
  • runkit_function_add — Add a new function, similar to create_function
  • runkit_function_copy — Copy a function to a new function name
  • runkit_function_redefine — Replace a function definition with a new implementation
  • runkit_function_remove — Remove a function definition
  • runkit_function_rename — Change a function's name
  • runkit_import — Process a PHP file importing function and class definitions, overwriting where appropriate
  • runkit_lint_file — Check the PHP syntax of the specified file
  • runkit_lint — Check the PHP syntax of the specified php code
  • runkit_method_add — Dynamically adds a new method to a given class
  • runkit_method_copy — Copies a method from class to another
  • runkit_method_redefine — Dynamically changes the code of the given method
  • runkit_method_remove — Dynamically removes the given method
  • runkit_method_rename — Dynamically changes the name of the given method
  • runkit_return_value_used — Determines if the current functions return value will be used
  • runkit_sandbox_output_handler — Specify a function to capture and/or process output from a runkit sandbox
  • runkit_superglobals — Return numerically indexed array of registered superglobals


Runkit Sandbox Class -- PHP Virtual Machine

  • « runkit Functions
  • Runkit_Sandbox_Parent »
  • PHP Manual
  • runkit Functions
  • Runkit Sandbox Class -- PHP Virtual Machine

Runkit_Sandbox

(PECL runkit >= 0.7.0)

Runkit_Sandbox — Runkit Sandbox Class -- PHP Virtual Machine

Description

Instantiating the Runkit_Sandbox class creates a new thread with its own scope and program stack. Using a set of options passed to the constructor, this environment may be restricted to a subset of what the primary interpreter can do and provide a safer environment for executing user supplied code.

Note: Sandbox support (required for runkit_lint(), runkit_lint_file(), and the Runkit_Sandbox class) is only available as of PHP 5.1.0 or specially patched versions of PHP 5.0, and requires that thread safety be enabled. See the README file included in the runkit package for more information.

Constructor

Runkit_Sandbox::__construct ([ array $options ] ) : void

options is an associative array containing any combination of the special ini options listed below.

safe_mode

If the outer script which is instantiating the Runkit_Sandbox class is configured with safe_mode = off, then safe_mode may be turned on for the sandbox environment. This setting can not be used to disable safe_mode when it's already enabled in the outer script.

safe_mode_gid

If the outer script which is instantiating the Runkit_Sandbox class is configured with safe_mode_gid = on, then safe_mode_gid may be turned off for the sandbox environment. This setting can not be used to enable safe_mode_gid when it's already disabled in the outer script.

safe_mode_include_dir

If the outer script which is instantiating the Runkit_Sandbox class is configured with a safe_mode_include_dir, then a new safe_mode_include_dir may be set for sandbox environments below the currently defined value. safe_mode_include_dir may also be cleared to indicate that the bypass feature is disabled. If safe_mode_include_dir was blank in the outer script, but safe_mode was not enabled, then any arbitrary safe_mode_include_dir may be set while turning safe_mode on.

open_basedir

open_basedir may be set to any path below the current setting of open_basedir. If open_basedir is not set within the global scope, then it is assumed to be the root directory and may be set to any location.

allow_url_fopen

Like safe_mode, this setting can only be made more restrictive, in this case by setting it to FALSE when it is previously set to TRUE

disable_functions

Comma separated list of functions to disable within the sandbox sub-interpreter. This list need not contain the names of the currently disabled functions, they will remain disabled whether listed here or not.

disable_classes

Comma separated list of classes to disable within the sandbox sub-interpreter. This list need not contain the names of the currently disabled classes, they will remain disabled whether listed here or not.

runkit.superglobal

Comma separated list of variables to be treated as superglobals within the sandbox sub-interpreter. These variables will be used in addition to any variables defined internally or through the global runkit.superglobal setting.

runkit.internal_override

Ini option runkit.internal_override may be disabled (but not re-enabled) within sandboxes.

Example #1 Instantiating a restricted sandbox

<?php
$options = array(
  'safe_mode'=>true,
  'open_basedir'=>'/var/www/users/jdoe/',
  'allow_url_fopen'=>'false',
  'disable_functions'=>'exec,shell_exec,passthru,system',
  'disable_classes'=>'myAppClass');
$sandbox = new Runkit_Sandbox($options);
/* Non-protected ini settings may set normally */
$sandbox->ini_set('html_errors',true);
?>

Accessing Variables

All variables in the global scope of the sandbox environment are accessible as properties of the sandbox object. The first thing to note is that because of the way memory between these two threads is managed, object and resource variables can not currently be exchanged between interpreters. Additionally, all arrays are deep copied and any references will be lost. This also means that references between interpreters are not possible.

Example #2 Working with variables in a sandbox

<?php
$sandbox = new Runkit_Sandbox();

$sandbox->foo = 'bar';
$sandbox->eval('echo "$foo\n"; $bar = $foo . "baz";');
echo "{$sandbox->bar}\n";
if (isset($sandbox->foo)) unset($sandbox->foo);
$sandbox->eval('var_dump(isset($foo));');
?>

The above example will output:

bar
barbaz
bool(false)

Calling PHP Functions

Any function defined within the sandbox may be called as a method on the sandbox object. This also includes a few pseudo-function language constructs: eval(), include, include_once, require, require_once, echo, print, die(), and exit().

Example #3 Calling sandbox functions

<?php
$sandbox = new Runkit_Sandbox();

echo $sandbox->str_replace('a','f','abc');
?>

The above example will output:

fbc

When passing arguments to a sandbox function, the arguments are taken from the outer instance of PHP. If you wish to pass arguments from the sandbox's scope, be sure to access them as properties of the sandbox object as illustrated above.

Example #4 Passing arguments to sandbox functions

<?php
$sandbox = new Runkit_Sandbox();

$foo = 'bar';
$sandbox->foo = 'baz';
echo $sandbox->str_replace('a',$foo,'a');
echo $sandbox->str_replace('a',$sandbox->foo,'a');
?>

The above example will output:

bar
baz

Changing Sandbox Settings

As of runkit version 0.5, certain Sandbox settings may be modified on the fly using ArrayAccess syntax. Some settings, such as active are read-only and meant to provide status information. Other settings, such as output_handler may be set and read much like a normal array offset. Future settings may be write-only, however no such settings currently exist.

Sandbox Settings / Status Indicators
Setting | Type | Purpose | Default
active | Boolean (Read Only) | TRUE if the Sandbox is still in a usable state, FALSE if the request is in bailout due to a call to die(), exit(), or because of a fatal error condition. | TRUE (Initial)
output_handler | Callback | When set to a valid callback, all output generated by the Sandbox instance will be processed through the named function. Sandbox output handlers follow the same calling conventions as the system-wide output handler. | None
parent_access | Boolean | May the sandbox use instances of the Runkit_Sandbox_Parent class? Must be enabled for other Runkit_Sandbox_Parent related settings to work. | FALSE
parent_read | Boolean | May the sandbox read variables in its parent's context? | FALSE
parent_write | Boolean | May the sandbox modify variables in its parent's context? | FALSE
parent_eval | Boolean | May the sandbox evaluate arbitrary code in its parent's context? DANGEROUS | FALSE
parent_include | Boolean | May the sandbox include php code files in its parent's context? DANGEROUS | FALSE
parent_echo | Boolean | May the sandbox echo data in its parent's context effectively bypassing its own output_handler? | FALSE
parent_call | Boolean | May the sandbox call functions in its parent's context? | FALSE
parent_die | Boolean | May the sandbox kill its own parent? (And thus itself) | FALSE
parent_scope | Integer | What scope will parental property access look at? 0 == Global scope, 1 == Calling scope, 2 == Scope preceding calling scope, 3 == The scope before that, etc..., etc... | 0 (Global)
parent_scope | String | When parent_scope is set to a string value, it refers to a named array variable in the global scope. If the named variable does not exist at the time of access it will be created as an empty array. If the variable exists but it not an array, a dummy array will be created containing a reference to the named global variable. |


Runkit Anti-Sandbox Class

  • « Runkit_Sandbox
  • runkit_class_adopt »
  • PHP Manual
  • runkit Functions
  • Runkit Anti-Sandbox Class

Runkit_Sandbox_Parent

(PECL runkit >= 0.7.0)

Runkit_Sandbox_Parent — Runkit Anti-Sandbox Class

Description

Runkit_Sandbox_Parent::__construct ( void ) : void

Instantiating the Runkit_Sandbox_Parent class from within a sandbox environment created from the Runkit_Sandbox class provides some (controlled) means for a sandbox child to access its parent.

Note: Sandbox support (required for runkit_lint(), runkit_lint_file(), and the Runkit_Sandbox class) is only available as of PHP 5.1.0 or specially patched versions of PHP 5.0, and requires that thread safety be enabled. See the README file included in the runkit package for more information.

In order for any of the Runkit_Sandbox_Parent features to function. Support must be enabled on a per-sandbox basis by enabling the parent_access flag from the parent's context.

Example #1 Working with variables in a sandbox

<?php
$sandbox = new Runkit_Sandbox();
$sandbox['parent_access'] = true;
?>

Accessing the Parent's Variables

Just as with sandbox variable access, a sandbox parent's variables may be read from and written to as properties of the Runkit_Sandbox_Parent class. Read access to parental variables may be enabled with the parent_read setting (in addition to the base parent_access setting). Write access, in turn, is enabled through the parent_write setting.

Unlike sandbox child variable access, the variable scope is not limited to globals only. By setting the parent_scope setting to an appropriate integer value, other scopes in the active call stack may be inspected instead. A value of 0 (Default) will direct variable access at the global scope. 1 will point variable access at whatever variable scope was active at the time the current block of sandbox code was executed. Higher values progress back through the functions that called the functions that led to the sandbox executing code that tried to access its own parent's variables.

Example #2 Accessing parental variables

<?php
$php = new Runkit_Sandbox();
$php['parent_access'] = true;
$php['parent_read'] = true;

$test = "Global";

$php->eval('$PARENT = new Runkit_Sandbox_Parent;');

$php['parent_scope'] = 0;
one();

$php['parent_scope'] = 1;
one();

$php['parent_scope'] = 2;
one();

$php['parent_scope'] = 3;
one();

$php['parent_scope'] = 4;
one();

$php['parent_scope'] = 5;
one();

function one() {
    $test = "one()";
    two();
}

function two() {
    $test = "two()";
    three();
}

function three() {
    $test = "three()";
    $GLOBALS['php']->eval('var_dump($PARENT->test);');
}
?>

The above example will output:

string(6) "Global"
string(7) "three()"
string(5) "two()"
string(5) "one()"
string(6) "Global"
string(6) "Global"

Calling the Parent's Functions

Just as with sandbox access, a sandbox may access its parents functions providing that the proper settings have been enabled. Enabling parent_call will allow the sandbox to call all functions available to the parent scope. Language constructs are each controlled by their own setting: print and echo are enabled with parent_echo. die() and exit() are enabled with parent_die. eval() is enabled with parent_eval while include, include_once, require, and require_once are enabled through parent_include.


Convert a base class to an inherited class, add ancestral methods when appropriate

  • « Runkit_Sandbox_Parent
  • runkit_class_emancipate »
  • PHP Manual
  • runkit Functions
  • Convert a base class to an inherited class, add ancestral methods when appropriate

runkit_class_adopt

(PECL runkit >= 0.7.0)

runkit_class_adopt — Convert a base class to an inherited class, add ancestral methods when appropriate

Description

runkit_class_adopt ( string $classname , string $parentname ) : bool

Parameters

classname

Name of class to be adopted

parentname

Parent class which child class is extending

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A runkit_class_adopt() example

<?php
class myParent {
  function parentFunc() {
    echo "Parent Function Output\n";
  }
}

class myChild {
}

runkit_class_adopt('myChild','myParent');
myChild::parentFunc();
?>

The above example will output:

Parent Function Output

See Also

  • runkit_class_emancipate() - Convert an inherited class to a base class, removes any method whose scope is ancestral


Convert an inherited class to a base class, removes any method whose scope is ancestral

  • « runkit_class_adopt
  • runkit_constant_add »
  • PHP Manual
  • runkit Functions
  • Convert an inherited class to a base class, removes any method whose scope is ancestral

runkit_class_emancipate

(PECL runkit >= 0.7.0)

runkit_class_emancipate — Convert an inherited class to a base class, removes any method whose scope is ancestral

Description

runkit_class_emancipate ( string $classname ) : bool

Parameters

classname

Name of class to emancipate

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A runkit_class_emancipate() example

<?php
class myParent {
  function parentFunc () {
    echo "Parent Function Output\n";
  }
}
class myChild extends myParent {
}

myChild::parentFunc();
runkit_class_emancipate('myChild');
myChild::parentFunc();
?>

The above example will output:

Parent Function Output
Fatal error: Call to undefined function:  parentFunc() in example.php on line 12

See Also

  • runkit_class_adopt() - Convert a base class to an inherited class, add ancestral methods when appropriate


Similar to define(), but allows defining in class definitions as well

  • « runkit_class_emancipate
  • runkit_constant_redefine »
  • PHP Manual
  • runkit Functions
  • Similar to define(), but allows defining in class definitions as well

runkit_constant_add

(PECL runkit >= 0.7.0)

runkit_constant_add — Similar to define(), but allows defining in class definitions as well

Description

runkit_constant_add ( string $constname , mixed $value ) : bool

Parameters

constname

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, or Resource value to store in the new constant.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • define() - Defines a named constant
  • runkit_constant_redefine() - Redefine an already defined constant
  • runkit_constant_remove() - Remove/Delete an already defined constant


Redefine an already defined constant

  • « runkit_constant_add
  • runkit_constant_remove »
  • PHP Manual
  • runkit Functions
  • Redefine an already defined constant

runkit_constant_redefine

(PECL runkit >= 0.7.0)

runkit_constant_redefine — Redefine an already defined constant

Description

runkit_constant_redefine ( string $constname , mixed $newvalue ) : bool

Parameters

constname

Constant to redefine. Either string indicating global constant, or classname::constname indicating class constant.

newvalue

New value to assign to constant.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • runkit_constant_add() - Similar to define(), but allows defining in class definitions as well
  • runkit_constant_remove() - Remove/Delete an already defined constant


Remove/Delete an already defined constant

  • « runkit_constant_redefine
  • runkit_function_add »
  • PHP Manual
  • runkit Functions
  • Remove/Delete an already defined constant

runkit_constant_remove

(PECL runkit >= 0.7.0)

runkit_constant_remove — Remove/Delete an already defined constant

Description

runkit_constant_remove ( string $constname ) : bool

Parameters

constname

Name of constant to remove. Either a string indicating 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
  • runkit_constant_add() - Similar to define(), but allows defining in class definitions as well
  • runkit_constant_redefine() - Redefine an already defined constant


Add a new function, similar to create_function

  • « runkit_constant_remove
  • runkit_function_copy »
  • PHP Manual
  • runkit Functions
  • Add a new function, similar to create_function

runkit_function_add

(PECL runkit >= 0.7.0)

runkit_function_add — Add a new function, similar to create_function()

Description

runkit_function_add ( string $funcname , string $arglist , string $code [, bool $return_by_reference = NULL [, string $doc_comment = NULL ]] ) : bool
runkit_function_add ( string $funcname , Closure $closure [, string $doc_comment = NULL ] ) : bool

Parameters

funcname

Name of function to be created

arglist

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 Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
runkit 1.0.4 | An alternative syntax expecting a closure has been added.
runkit 1.0.4 | The optional parameters return_by_reference and doc_comment have been added.

Examples

Example #1 A runkit_function_add() example

<?php
runkit_function_add('testme','$a,$b','echo "The value of a is $a\n"; echo "The value of b is $b\n";');
testme(1,2);
?>

The above example will output:

The value of a is 1
The value of b is 2

See Also

  • create_function() - Create an anonymous (lambda-style) function
  • runkit_function_redefine() - Replace a function definition with a new implementation
  • runkit_function_copy() - Copy a function to a new function name
  • runkit_function_rename() - Change a function's name
  • runkit_function_remove() - Remove a function definition
  • runkit_method_add() - Dynamically adds a new method to a given class


Copy a function to a new function name

  • « runkit_function_add
  • runkit_function_redefine »
  • PHP Manual
  • runkit Functions
  • Copy a function to a new function name

runkit_function_copy

(PECL runkit >= 0.7.0)

runkit_function_copy — Copy a function to a new function name

Description

runkit_function_copy ( string $funcname , string $targetname ) : bool

Parameters

funcname

Name of existing function

targetname

Name of new function to copy definition to

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A runkit_function_copy() example

<?php
function original() {
  echo "In a function\n";
}
runkit_function_copy('original','duplicate');
original();
duplicate();
?>

The above example will output:

In a function
In a function

See Also

  • runkit_function_add() - Add a new function, similar to create_function
  • runkit_function_redefine() - Replace a function definition with a new implementation
  • runkit_function_rename() - Change a function's name
  • runkit_function_remove() - Remove a function definition


Replace a function definition with a new implementation

  • « runkit_function_copy
  • runkit_function_remove »
  • PHP Manual
  • runkit Functions
  • Replace a function definition with a new implementation

runkit_function_redefine

(PECL runkit >= 0.7.0)

runkit_function_redefine — Replace a function definition with a new implementation

Description

runkit_function_redefine ( string $funcname , string $arglist , string $code [, bool $return_by_reference = NULL [, string $doc_comment = NULL ]] ) : bool
runkit_function_redefine ( string $funcname , Closure $closure [, string $doc_comment = NULL ] ) : 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

funcname

Name of function to redefine

arglist

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 Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
runkit 1.0.4 | An alternative syntax expecting a closure has been added.
runkit 1.0.4 | The optional parameters return_by_reference and doc_comment have been added.

Examples

Example #1 A runkit_function_redefine() example

<?php
function testme() {
  echo "Original Testme Implementation\n";
}
testme();
runkit_function_redefine('testme','','echo "New Testme Implementation\n";');
testme();
?>

The above example will output:

Original Testme Implementation
New Testme Implementation

See Also

  • runkit_function_add() - Add a new function, similar to create_function
  • runkit_function_copy() - Copy a function to a new function name
  • runkit_function_rename() - Change a function's name
  • runkit_function_remove() - Remove a function definition
  • runkit_method_redefine() - Dynamically changes the code of the given method


Remove a function definition

  • « runkit_function_redefine
  • runkit_function_rename »
  • PHP Manual
  • runkit Functions
  • Remove a function definition

runkit_function_remove

(PECL runkit >= 0.7.0)

runkit_function_remove — Remove a function definition

Description

runkit_function_remove ( string $funcname ) : 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

funcname

Name of function to be deleted

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • runkit_function_add() - Add a new function, similar to create_function
  • runkit_function_copy() - Copy a function to a new function name
  • runkit_function_redefine() - Replace a function definition with a new implementation
  • runkit_function_rename() - Change a function's name


Change a function's name

  • « runkit_function_remove
  • runkit_import »
  • PHP Manual
  • runkit Functions
  • Change a function's name

runkit_function_rename

(PECL runkit >= 0.7.0)

runkit_function_rename — Change a function's name

Description

runkit_function_rename ( string $funcname , string $newname ) : 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

funcname

Current function name

newname

New function name

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • runkit_function_add() - Add a new function, similar to create_function
  • runkit_function_copy() - Copy a function to a new function name
  • runkit_function_redefine() - Replace a function definition with a new implementation
  • runkit_function_remove() - Remove a function definition


Process a PHP file importing function and class definitions, overwriting where appropriate

  • « runkit_function_rename
  • runkit_lint_file »
  • PHP Manual
  • runkit Functions
  • Process a PHP file importing function and class definitions, overwriting where appropriate

runkit_import

(PECL runkit >= 0.7.0)

runkit_import — Process a PHP file importing function and class definitions, overwriting where appropriate

Description

runkit_import ( string $filename [, int $flags = RUNKIT_IMPORT_CLASS_METHODS ] ) : 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 RUNKIT_IMPORT_* family of constants.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 runkit_import() example

<?php
// import classes entirely
runkit_import('myfile.inc', RUNKIT_IMPORT_CLASSES);

/* import classes, but not imports their static properties
   (RUNKIT_IMPORT_CLASS_STATIC_PROPS is available since 1.0.1) */
runkit_import('myfile.inc', RUNKIT_IMPORT_CLASSES & ~RUNKIT_IMPORT_CLASS_STATIC_PROPS);

/* import only static properties of classes
   (RUNKIT_IMPORT_CLASS_STATIC_PROPS is available since 1.0.1) */
runkit_import('myfile.inc', RUNKIT_IMPORT_CLASS_STATIC_PROPS);
?>


Check the PHP syntax of the specified file

  • « runkit_import
  • runkit_lint »
  • PHP Manual
  • runkit Functions
  • Check the PHP syntax of the specified file

runkit_lint_file

(PECL runkit >= 0.7.0)

runkit_lint_file — Check the PHP syntax of the specified file

Description

runkit_lint_file ( string $filename ) : bool

The runkit_lint_file() function performs a syntax (lint) check on the specified filename testing for scripting errors. This is similar to using php -l from the commandline.

Note: Sandbox support (required for runkit_lint(), runkit_lint_file(), and the Runkit_Sandbox class) is only available as of PHP 5.1.0 or specially patched versions of PHP 5.0, and requires that thread safety be enabled. See the README file included in the runkit package for more information.

Parameters

filename

File containing PHP Code to be lint checked

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • runkit_lint() - Check the PHP syntax of the specified php code


Check the PHP syntax of the specified php code

  • « runkit_lint_file
  • runkit_method_add »
  • PHP Manual
  • runkit Functions
  • Check the PHP syntax of the specified php code

runkit_lint

(PECL runkit >= 0.7.0)

runkit_lint — Check the PHP syntax of the specified php code

Description

runkit_lint ( string $code ) : bool

The runkit_lint() function performs a syntax (lint) check on the specified php code testing for scripting errors. This is similar to using php -l from the command line except runkit_lint() accepts actual code rather than a filename.

Note: Sandbox support (required for runkit_lint(), runkit_lint_file(), and the Runkit_Sandbox class) is only available as of PHP 5.1.0 or specially patched versions of PHP 5.0, and requires that thread safety be enabled. See the README file included in the runkit package for more information.

Parameters

code

PHP Code to be lint checked

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • runkit_lint_file() - Check the PHP syntax of the specified file


Dynamically adds a new method to a given class

  • « runkit_lint
  • runkit_method_copy »
  • PHP Manual
  • runkit Functions
  • Dynamically adds a new method to a given class

runkit_method_add

(PECL runkit >= 0.7.0)

runkit_method_add — Dynamically adds a new method to a given class

Description

runkit_method_add ( string $classname , string $methodname , string $args , string $code [, int $flags = RUNKIT_ACC_PUBLIC [, string $doc_comment = NULL ]] ) : bool
runkit_method_add ( string $classname , string $methodname , Closure $closure [, int $flags = RUNKIT_ACC_PUBLIC [, string $doc_comment = NULL ]] ) : bool

Parameters

classname

The class to which this method will be added

methodname

The name of the method to add

args

Comma-delimited list of arguments for the newly-created method

code

The code to be evaluated when methodname is called

closure

A closure that defines the method.

flags

The type of method to create, can be RUNKIT_ACC_PUBLIC, RUNKIT_ACC_PROTECTED or RUNKIT_ACC_PRIVATE optionally combined via bitwise OR with RUNKIT_ACC_STATIC (since 1.0.1)

doc_comment

The doc comment of the function.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
runkit 1.0.4 | An alternative syntax expecting a closure has been added.
runkit 1.0.4 | The optional parameter doc_comment has been added.

Examples

Example #1 runkit_method_add() example

<?php
class Example {
    function foo() {
        echo "foo!\n";
    }
}

// create an Example object
$e = new Example();

// Add a new public method
runkit_method_add(
    'Example',
    'add',
    '$num1, $num2',
    'return $num1 + $num2;',
    RUNKIT_ACC_PUBLIC
);

// add 12 + 4
echo $e->add(12, 4);
?>

The above example will output:

16

See Also

  • runkit_method_copy() - Copies a method from class to another
  • runkit_method_redefine() - Dynamically changes the code of the given method
  • runkit_method_remove() - Dynamically removes the given method
  • runkit_method_rename() - Dynamically changes the name of the given method
  • runkit_function_add() - Add a new function, similar to create_function


Copies a method from class to another

  • « runkit_method_add
  • runkit_method_redefine »
  • PHP Manual
  • runkit Functions
  • Copies a method from class to another

runkit_method_copy

(PECL runkit >= 0.7.0)

runkit_method_copy — Copies a method from class to another

Description

runkit_method_copy ( string $dClass , string $dMethod , string $sClass [, string $sMethod ] ) : bool

Parameters

dClass

Destination class for copied method

dMethod

Destination method name

sClass

Source class of the method to copy

sMethod

Name of the method to copy from the source class. If this parameter is omitted, the value of dMethod is assumed.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 runkit_method_copy() example

<?php
class Foo {
    function example() {
        return "foo!\n";
    }
}

class Bar {
    // initially, no methods
}

// copy the example() method from the Foo class to the Bar class, as baz()
runkit_method_copy('Bar', 'baz', 'Foo', 'example');

// output copied function
echo Bar::baz();
?>

The above example will output:

foo!

See Also

  • runkit_method_add() - Dynamically adds a new method to a given class
  • runkit_method_redefine() - Dynamically changes the code of the given method
  • runkit_method_remove() - Dynamically removes the given method
  • runkit_method_rename() - Dynamically changes the name of the given method
  • runkit_function_copy() - Copy a function to a new function name


Dynamically changes the code of the given method

  • « runkit_method_copy
  • runkit_method_remove »
  • PHP Manual
  • runkit Functions
  • Dynamically changes the code of the given method

runkit_method_redefine

(PECL runkit >= 0.7.0)

runkit_method_redefine — Dynamically changes the code of the given method

Description

runkit_method_redefine ( string $classname , string $methodname , string $args , string $code [, int $flags = RUNKIT_ACC_PUBLIC [, string $doc_comment = NULL ]] ) : bool
runkit_method_redefine ( string $classname , string $methodname , Closure $closure [, int $flags = RUNKIT_ACC_PUBLIC [, string $doc_comment = NULL ]] ) : bool

Note: This function cannot be used to manipulate the currently running (or chained) method.

Parameters

classname

The class in which to redefine the method

methodname

The name of the method to redefine

args

Comma-delimited list of arguments for the redefined method

code

The new code to be evaluated when methodname is called

closure

A closure that defines the method.

flags

The redefined method can be RUNKIT_ACC_PUBLIC, RUNKIT_ACC_PROTECTED or RUNKIT_ACC_PRIVATE optionally combined via bitwise OR with RUNKIT_ACC_STATIC (since 1.0.1)

doc_comment

The doc comment of the function.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
runkit 1.0.4 | An alternative syntax expecting a closure has been added.
runkit 1.0.4 | The optional parameter doc_comment has been added.

Examples

Example #1 runkit_method_redefine() example

<?php
class Example {
    function foo() {
        return "foo!\n";
    }
}

// create an Example object
$e = new Example();

// output Example::foo() (before redefine)
echo "Before: " . $e->foo();

// Redefine the 'foo' method
runkit_method_redefine(
    'Example',
    'foo',
    '',
    'return "bar!\n";',
    RUNKIT_ACC_PUBLIC
);

// output Example::foo() (after redefine)
echo "After: " . $e->foo();
?>

The above example will output:

Before: foo!
After: bar!

See Also

  • runkit_method_add() - Dynamically adds a new method to a given class
  • runkit_method_copy() - Copies a method from class to another
  • runkit_method_remove() - Dynamically removes the given method
  • runkit_method_rename() - Dynamically changes the name of the given method
  • runkit_function_redefine() - Replace a function definition with a new implementation


Dynamically removes the given method

  • « runkit_method_redefine
  • runkit_method_rename »
  • PHP Manual
  • runkit Functions
  • Dynamically removes the given method

runkit_method_remove

(PECL runkit >= 0.7.0)

runkit_method_remove — Dynamically removes the given method

Description

runkit_method_remove ( string $classname , string $methodname ) : bool

Note: This function cannot be used to manipulate the currently running (or chained) method.

Parameters

classname

The class in which to remove the method

methodname

The name of the method to remove

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 runkit_method_remove() example

<?php
class Example {
    function foo() {
        return "foo!\n";
    }

    function bar() {
        return "bar!\n";
    }
}

// Remove the 'foo' method
runkit_method_remove(
    'Example',
    'foo'
);

echo implode(' ', get_class_methods('Example'));

?>

The above example will output:

bar

See Also

  • runkit_method_add() - Dynamically adds a new method to a given class
  • runkit_method_copy() - Copies a method from class to another
  • runkit_method_redefine() - Dynamically changes the code of the given method
  • runkit_method_rename() - Dynamically changes the name of the given method
  • runkit_function_remove() - Remove a function definition


Dynamically changes the name of the given method

  • « runkit_method_remove
  • runkit_return_value_used »
  • PHP Manual
  • runkit Functions
  • Dynamically changes the name of the given method

runkit_method_rename

(PECL runkit >= 0.7.0)

runkit_method_rename — Dynamically changes the name of the given method

Description

runkit_method_rename ( string $classname , string $methodname , string $newname ) : bool

Note: This function cannot be used to manipulate the currently running (or chained) method.

Parameters

classname

The class in which to rename the method

methodname

The name of the method to rename

newname

The new name to give to the renamed method

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 runkit_method_rename() example

<?php
class Example {
    function foo() {
        return "foo!\n";
    }
}

// Rename the 'foo' method to 'bar'
runkit_method_rename(
    'Example',
    'foo',
    'bar'
);

// output renamed function
echo Example::bar();
?>

The above example will output:

foo!

See Also

  • runkit_method_add() - Dynamically adds a new method to a given class
  • runkit_method_copy() - Copies a method from class to another
  • runkit_method_redefine() - Dynamically changes the code of the given method
  • runkit_method_remove() - Dynamically removes the given method
  • runkit_function_rename() - Change a function's name


Determines if the current functions return value will be used

  • « runkit_method_rename
  • runkit_sandbox_output_handler »
  • PHP Manual
  • runkit Functions
  • Determines if the current functions return value will be used

runkit_return_value_used

(PECL runkit >= 0.8.0)

runkit_return_value_used — Determines if the current functions return value will be used

Description

runkit_return_value_used ( void ) : bool

Return Values

Returns TRUE if the function's return value is used by the calling scope, otherwise FALSE

Examples

Example #1 runkit_return_value_used() example

<?php
function foo() {
  var_dump(runkit_return_value_used());
}

foo();
$f = foo();
?>

The above example will output:

bool(false)
bool(true)


Specify a function to capture and/or process output from a runkit sandbox

  • « runkit_return_value_used
  • runkit_superglobals »
  • PHP Manual
  • runkit Functions
  • Specify a function to capture and/or process output from a runkit sandbox

runkit_sandbox_output_handler

(PECL runkit >= 0.7.0)

runkit_sandbox_output_handler — Specify a function to capture and/or process output from a runkit sandbox

Description

runkit_sandbox_output_handler ( object $sandbox [, mixed $callback ] ) : mixed

Ordinarily, anything output (such as with echo or print) will be output as though it were printed from the parent's scope. Using runkit_sandbox_output_handler() however, output generated by the sandbox (including errors), can be captured by a function outside of the sandbox.

Note: Sandbox support (required for runkit_lint(), runkit_lint_file(), and the Runkit_Sandbox class) is only available as of PHP 5.1.0 or specially patched versions of PHP 5.0, and requires that thread safety be enabled. See the README file included in the runkit package for more information.

Note: Deprecated

As of runkit version 0.5, this function is deprecated and is scheduled to be removed from the package prior to a 1.0 release. The output handler for a given Runkit_Sandbox instance may be read/set using the array offset syntax shown on the Runkit_Sandbox class definition page.

Parameters

sandbox

Object instance of Runkit_Sandbox class on which to set output handling.

callback

Name of a function which expects one parameter. Output generated by sandbox will be passed to this callback. Anything returned by the callback will be displayed normally. If this parameter is not passed then output handling will not be changed. If a non-truth value is passed, output handling will be disabled and will revert to direct display.

Return Values

Returns the name of the previously defined output handler callback, or FALSE if no handler was previously defined.

Examples

Example #1 Feeding output to a variable

<?php
function capture_output($str) {
  $GLOBALS['sandbox_output'] .= $str;

  return '';
}

$sandbox_output = '';

$php = new Runkit_Sandbox();
runkit_sandbox_output_handler($php, 'capture_output');
$php->echo("Hello\n");
$php->eval('var_dump("Excuse me");');
$php->die("I lost myself.");
unset($php);

echo "Sandbox Complete\n\n";
echo $sandbox_output;
?>

The above example will output:

Sandbox Complete

Hello
string(9) "Excuse me"
I lost myself.


Return numerically indexed array of registered superglobals

  • « runkit_sandbox_output_handler
  • runkit7 »
  • PHP Manual
  • runkit Functions
  • Return numerically indexed array of registered superglobals

runkit_superglobals

(PECL runkit >= 0.7.0)

runkit_superglobals — Return numerically indexed array of registered superglobals

Description

runkit_superglobals ( void ) : array

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

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • runkit7 Functions
    • runkit7_constant_add — Similar to define(), but allows defining in class definitions as well
    • runkit7_constant_redefine — Description
    • 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


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.


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.

Currently the same as Runkit Configuration Options


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 (integer)
runkit7_import() flag indicating that normal functions should be imported from the specified file.
RUNKIT7_IMPORT_CLASS_METHODS (integer)
runkit7_import() flag indicating that class methods should be imported from the specified file.
RUNKIT7_IMPORT_CLASS_CONSTS (integer)
runkit7_import() flag indicating that class constants should be imported from the specified file.
RUNKIT7_IMPORT_CLASS_PROPS (integer)
runkit7_import() flag indicating that class standard properties should be imported from the specified file.
RUNKIT7_IMPORT_CLASS_STATIC_PROPS (integer)
runkit7_import() flag indicating that class static properties should be imported from the specified file. Available since Runkit 1.0.1.
RUNKIT7_IMPORT_CLASSES (integer)
runkit7_import() flag representing a bitwise OR of the RUNKIT7_IMPORT_CLASS_* constants.
RUNKIT7_IMPORT_OVERRIDE (integer)
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 (integer)
Include this flag to make the function or method being created or redeclared return a reference.
RUNKIT7_ACC_PUBLIC (integer)
Flag for runkit7_method_add() and runkit7_method_redefine() to make the method public.
RUNKIT7_ACC_PROTECTED (integer)
Flag for runkit7_method_add() and runkit7_method_redefine() to make the method protected.
RUNKIT7_ACC_PRIVATE (integer)
Flag for runkit7_method_add() and runkit7_method_redefine() to make the method private.
RUNKIT7_ACC_STATIC (integer)
Flag for runkit7_method_add() and runkit7_method_redefine() to make the method static.
RUNKIT7_FEATURE_MANIPULATION (integer)
Equal to 1 if runtime manipulation is enabled, and 0 otherwise.
RUNKIT7_FEATURE_SUPERGLOBALS (integer)
Equal to 1 if custom superglobals are enabled, and 0 otherwise.
RUNKIT7_FEATURE_SANDBOX (integer)
Always 0, it's impractical to implement the sandbox feature in php 7.


runkit7 Functions

Table of Contents

  • runkit7_constant_add — Similar to define(), but allows defining in class definitions as well
  • runkit7_constant_redefine — Description
  • 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


Similar to define(), but allows defining in class definitions as well

  • « runkit7 Functions
  • runkit7_constant_redefine »
  • PHP Manual
  • runkit7 Functions
  • Similar to define(), but allows defining in class definitions as well

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 $constname , mixed $value [, int $newVisibility ] ) : bool

Parameters

constname

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() - Description
  • runkit7_constant_remove() - Remove/Delete an already defined constant


Description

  • « runkit7_constant_add
  • runkit7_constant_remove »
  • PHP Manual
  • runkit7 Functions
  • Description

runkit7_constant_redefine

(PECL runkit7 >= Unknown)

runkit7_constant_redefine — Description

Description

runkit7_constant_redefine ( string $constname , mixed $value [, string $newVisibility ] ) : bool

Parameters

constname

Constant to redefine. Either the name of a global constant, or classname::constname indicating class constant.

value

Value to assign to the constant.

newVisibility

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


Remove/Delete an already defined constant

  • « runkit7_constant_redefine
  • runkit7_function_add »
  • PHP Manual
  • runkit7 Functions
  • 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 $constname ) : bool

Parameters

constname

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


Add a new function, similar to create_function

  • « runkit7_constant_remove
  • runkit7_function_copy »
  • PHP Manual
  • runkit7 Functions
  • Add a new function, similar to create_function

runkit7_function_add

(PECL runkit7 >= Unknown)

runkit7_function_add — Add a new function, similar to create_function()

Description

runkit7_function_add ( string $funcname , string $arglist , string $code [, bool $return_by_reference = NULL [, string $doc_comment = NULL [, string $return_type [, bool $is_strict ]]]] ) : bool
runkit7_function_add ( string $funcname , Closure $closure [, string $doc_comment = NULL [, string $return_type [, bool $is_strict ]]] ) : bool

Parameters

funcname

Name of the function to be created

arglist

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 an anonymous (lambda-style) function
  • 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


Copy a function to a new function name

  • « runkit7_function_add
  • runkit7_function_redefine »
  • PHP Manual
  • runkit7 Functions
  • Copy a function to a new function name

runkit7_function_copy

(PECL runkit7 >= Unknown)

runkit7_function_copy — Copy a function to a new function name

Description

runkit7_function_copy ( string $funcname , string $targetname ) : bool

Parameters

funcname

Name of the existing function

targetname

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


Replace a function definition with a new implementation

  • « runkit7_function_copy
  • runkit7_function_remove »
  • PHP Manual
  • runkit7 Functions
  • Replace a function definition with a new implementation

runkit7_function_redefine

(PECL runkit7 >= Unknown)

runkit7_function_redefine — Replace a function definition with a new implementation

Description

runkit7_function_redefine ( string $funcname , string $arglist , string $code [, bool $return_by_reference = NULL [, string $doc_comment = NULL [, string $return_type [, string $is_strict ]]]] ) : bool
runkit7_function_redefine ( string $funcname , Closure $closure [, string $doc_comment = NULL [, string $return_type [, string $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

funcname

Name of function to redefine

arglist

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


Remove a function definition

  • « runkit7_function_redefine
  • runkit7_function_rename »
  • PHP Manual
  • runkit7 Functions
  • Remove a function definition

runkit7_function_remove

(PECL runkit7 >= Unknown)

runkit7_function_remove — Remove a function definition

Description

runkit7_function_remove ( string $funcname ) : 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

funcname

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


Change a function's name

  • « runkit7_function_remove
  • runkit7_import »
  • PHP Manual
  • runkit7 Functions
  • Change a function's name

runkit7_function_rename

(PECL runkit7 >= Unknown)

runkit7_function_rename — Change a function's name

Description

runkit7_function_rename ( string $funcname , string $newname ) : 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

funcname

Current function name

newname

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


Process a PHP file importing function and class definitions, overwriting where appropriate

  • « runkit7_function_rename
  • runkit7_method_add »
  • PHP Manual
  • runkit7 Functions
  • Process a PHP file importing function and class definitions, overwriting where appropriate

runkit7_import

(PECL runkit7 >= Unknown)

runkit7_import — Process a PHP file importing function and class definitions, overwriting where appropriate

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.


Dynamically adds a new method to a given class

  • « runkit7_import
  • runkit7_method_copy »
  • PHP Manual
  • runkit7 Functions
  • Dynamically adds a new method to a given class

runkit7_method_add

(PECL runkit7 >= Unknown)

runkit7_method_add — Dynamically adds a new method to a given class

Description

runkit7_method_add ( string $classname , string $methodname , string $args , string $code [, int $flags = RUNKIT7_ACC_PUBLIC [, string $doc_comment = NULL [, string $return_type [, bool $is_strict ]]]] ) : bool
runkit7_method_add ( string $classname , string $methodname , Closure $closure [, int $flags = RUNKIT7_ACC_PUBLIC [, string $doc_comment = NULL [, string $return_type [, bool $is_strict ]]]] ) : bool

Parameters

classname

The class to which this method will be added

methodname

The name of the method to add

args

Comma-delimited list of arguments for the newly-created method

code

The code to be evaluated when methodname 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


Copies a method from class to another

  • « runkit7_method_add
  • runkit7_method_redefine »
  • PHP Manual
  • runkit7 Functions
  • Copies a method from class to another

runkit7_method_copy

(PECL runkit7 >= Unknown)

runkit7_method_copy — Copies a method from class to another

Description

runkit7_method_copy ( string $dClass , string $dMethod , string $sClass [, string $sMethod ] ) : bool

Parameters

dClass

Destination class for copied method

dMethod

Destination method name

sClass

Source class of the method to copy

sMethod

Name of the method to copy from the source class. If this parameter is omitted, the value of dMethod is assumed.

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


Dynamically changes the code of the given method

  • « runkit7_method_copy
  • runkit7_method_remove »
  • PHP Manual
  • runkit7 Functions
  • Dynamically changes the code of the given method

runkit7_method_redefine

(PECL runkit7 >= Unknown)

runkit7_method_redefine — Dynamically changes the code of the given method

Description

runkit7_method_redefine ( string $classname , string $methodname , string $args , string $code [, int $flags = RUNKIT7_ACC_PUBLIC [, string $doc_comment = NULL [, string $return_type [, bool $is_strict ]]]] ) : bool
runkit7_method_redefine ( string $classname , string $methodname , Closure $closure [, int $flags = RUNKIT7_ACC_PUBLIC [, string $doc_comment = NULL [, string $return_type [, bool $is_strict ]]]] ) : bool

Parameters

classname

The class in which to redefine the method

methodname

The name of the method to redefine

args

Comma-delimited list of arguments for the redefined method

code

The new code to be evaluated when methodname 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


Dynamically removes the given method

  • « runkit7_method_redefine
  • runkit7_method_rename »
  • PHP Manual
  • runkit7 Functions
  • Dynamically removes the given method

runkit7_method_remove

(PECL runkit7 >= Unknown)

runkit7_method_remove — Dynamically removes the given method

Description

runkit7_method_remove ( string $classname , string $methodname ) : bool

Note: This function cannot be used to manipulate the currently running (or chained) method.

Parameters

classname

The class in which to remove the method

methodname

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


Dynamically changes the name of the given method

  • « runkit7_method_remove
  • runkit7_object_id »
  • PHP Manual
  • runkit7 Functions
  • Dynamically changes the name of the given method

runkit7_method_rename

(PECL runkit7 >= Unknown)

runkit7_method_rename — Dynamically changes the name of the given method

Description

runkit7_method_rename ( string $classname , string $methodname , string $newname ) : bool

Note: This function cannot be used to manipulate the currently running (or chained) method.

Parameters

classname

The class in which to rename the method

methodname

The name of the method to rename

newname

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


Return the integer object handle for given object

  • « runkit7_method_rename
  • runkit7_superglobals »
  • PHP Manual
  • runkit7 Functions
  • Return the integer object handle for given object

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


Return numerically indexed array of registered superglobals

  • « runkit7_object_id
  • runkit7_zval_inspect »
  • PHP Manual
  • runkit7 Functions
  • Return numerically indexed array of registered superglobals

runkit7_superglobals

(PECL runkit7 >= Unknown)

runkit7_superglobals — Return numerically indexed array of registered superglobals

Description

runkit7_superglobals ( void ) : 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


Returns information about the passed in value with data types, reference counts, etc

  • « runkit7_superglobals
  • scream »
  • PHP Manual
  • runkit7 Functions
  • Returns information about the passed in value with data types, reference counts, etc

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


Break the silence operator

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Examples
    • Example that shows the effect of scream


Introduction

The scream extension gives the possibility to disable the silencing error control operator so all errors are being reported. This feature is controlled by an ini setting.


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/scream


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

scream Configure Options
Name | Default | Changeable | Changelog
scream.enabled | Off | PHP_INI_ALL |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

scream.enabled int

Whether or not to enable scream.


  • « Runtime Configuration
  • Examples »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

This extension has no resource types defined.


  • « Resource Types
  • Example that shows the effect of scream »
  • PHP Manual
  • scream
  • Examples

Examples

Table of Contents

  • Example that shows the effect of scream


Example that shows the effect of scream

This example demonstrates how scream affects the behaviour of PHP's error handler.

Example #1 Enabling and disabling scream at runtime

<?php
// Make sure errors will be shown
ini_set('display_errors', true);
error_reporting(E_ALL);

// Disable scream - this is the default and produce an error
ini_set('scream.enabled', false);
echo "Opening http://example.com/not-existing-file\n";
@fopen('http://example.com/not-existing-file', 'r');

// Now enable scream and try again
ini_set('scream.enabled', true);
echo "Opening http://example.com/not-existing-file\n";
@fopen('http://example.com/not-existing-file', 'r');
?>

The above example will output something similar to:

Opening http://example.com/not-existing-file
Opening http://example.com/not-existing-file

Warning: fopen(http://example.com/not-existing-file): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in example.php on line 14

Note: Usually one would set this in the php.ini configuration file instead of changing the code.


User Operations for Zend

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • 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


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


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

uopz 2 requires PHP 5.4+. uopz 5.0 requires PHP 7. 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" | PHP_INI_SYSTEM | Available as of uopz 5.0.2
uopz.exit | "0" | PHP_INI_SYSTEM | Available as of uopz 6.0.1
For further details and definitions of the PHP_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().


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 (integer)
Invoked by exit() and die(), receives no arguments. Return boolean TRUE to exit, FALSE to continue
ZEND_NEW (integer)
Invoked by object construction, receives the class of object being created as the only argument
ZEND_THROW (integer)
Invoked by the throw construct, receives the class of exception being thrown as the only argument
ZEND_FETCH_CLASS (integer)
Invoked upon composure, receives the class the name of the class being fetched as the only argument
ZEND_ADD_TRAIT (integer)
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 (integer)
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 (integer)
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 (integer)
Advance 1 opcode and continuue
ZEND_USER_OPCODE_ENTER (integer)
Enter into new op_array without recursion
ZEND_USER_OPCODE_LEAVE (integer)
Return to calling op_array within the same executor
ZEND_USER_OPCODE_DISPATCH (integer)
Dispatch to original opcode handler
ZEND_USER_OPCODE_DISPATCH_TO (integer)
Dispatch to a specific handler (OR'd with ZEND opcode constant)
ZEND_USER_OPCODE_RETURN (integer)
Exit from executor (return from function)

The following modifiers are registered as constants by uopz

ZEND_ACC_PUBLIC (integer)
Mark function as public, the default
ZEND_ACC_PROTECTED (integer)
Mark function as protected
ZEND_ACC_PRIVATE (integer)
Mark function as private
ZEND_ACC_STATIC (integer)
Mark function as static
ZEND_ACC_FINAL (integer)
Mark function as final
ZEND_ACC_ABSTRACT (integer)
Mark function as abstract
ZEND_ACC_CLASS (integer)
Dummy registered for consistency, the default kind of class entry. Removed as of uopz 5.0.0.
ZEND_ACC_INTERFACE (integer)
Mark class as interface. Removed as of uopz 5.0.0.
ZEND_ACC_TRAIT (integer)
Mark class as trait. Removed as of uopz 5.0.0.
ZEND_ACC_FETCH (integer)
Used for getting flags only. Removed as of uopz 5.0.0.


Uopz Functions

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


Adds non-existent function or method

  • « Uopz Functions
  • uopz_allow_exit »
  • PHP Manual
  • Uopz Functions
  • Adds non-existent function or method

uopz_add_function

(PECL uopz 5, PECL uopz 6)

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


Allows control over disabled exit opcode

  • « uopz_add_function
  • uopz_backup »
  • PHP Manual
  • Uopz Functions
  • Allows control over disabled exit opcode

uopz_allow_exit

(PECL uopz 5, PECL uopz 6)

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


Backup a function

  • « uopz_allow_exit
  • uopz_compose »
  • PHP Manual
  • Uopz Functions
  • Backup a function

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)


Compose a class

  • « uopz_backup
  • uopz_copy »
  • PHP Manual
  • Uopz Functions
  • Compose a class

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


Copy a function

  • « uopz_compose
  • uopz_del_function »
  • PHP Manual
  • Uopz Functions
  • Copy a function

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"


Deletes previously added function or method

  • « uopz_copy
  • uopz_delete »
  • PHP Manual
  • Uopz Functions
  • Deletes previously added function or method

uopz_del_function

(PECL uopz 5, PECL uopz 6)

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


Delete a function

  • « uopz_del_function
  • uopz_extend »
  • PHP Manual
  • Uopz Functions
  • Delete 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


Extend a class at runtime

  • « uopz_delete
  • uopz_flags »
  • PHP Manual
  • Uopz Functions
  • Extend a class at runtime

uopz_extend

(PECL uopz 1, PECL uopz 2, PECL uopz 5, PECL uopz 6)

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.

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


Get or set flags on function or class

  • « uopz_extend
  • uopz_function »
  • PHP Manual
  • Uopz Functions
  • Get or set flags on function or class

uopz_flags

(PECL uopz 2 >= 2.0.2, PECL uopz 5, PECL uopz 6)

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

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

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)


Creates a function at runtime

  • « uopz_flags
  • uopz_get_exit_status »
  • PHP Manual
  • Uopz Functions
  • Creates a function at runtime

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


Retrieve the last set exit status

  • « uopz_function
  • uopz_get_hook »
  • PHP Manual
  • Uopz Functions
  • Retrieve the last set exit status

uopz_get_exit_status

(PECL uopz 5, PECL uopz 6)

uopz_get_exit_status — Retrieve the last set exit status

Description

uopz_get_exit_status ( void ) : 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


Gets previously set hook on function or method

  • « uopz_get_exit_status
  • uopz_get_mock »
  • PHP Manual
  • Uopz Functions
  • Gets previously set hook on function or method

uopz_get_hook

(PECL uopz 5, PECL uopz 6)

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


Get the current mock for a class

  • « uopz_get_hook
  • uopz_get_property »
  • PHP Manual
  • Uopz Functions
  • Get the current mock for a class

uopz_get_mock

(PECL uopz 5, PECL uopz 6)

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


Gets value of class or instance property

  • « uopz_get_mock
  • uopz_get_return »
  • PHP Manual
  • Uopz Functions
  • Gets value of class or instance property

uopz_get_property

(PECL uopz 5, PECL uopz 6)

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


Gets a previous set return value for a function

  • « uopz_get_property
  • uopz_get_static »
  • PHP Manual
  • Uopz Functions
  • Gets a previous set return value for a function

uopz_get_return

(PECL uopz 5, PECL uopz 6)

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


Gets the static variables from function or method scope

  • « uopz_get_return
  • uopz_implement »
  • PHP Manual
  • Uopz Functions
  • Gets the static variables from function or method scope

uopz_get_static

(PECL uopz 5, PECL uopz 6)

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.

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

  • uopz_set_static() - Sets the static variables in function or method scope


Implements an interface at runtime

  • « uopz_get_static
  • uopz_overload »
  • PHP Manual
  • Uopz Functions
  • Implements an interface at runtime

uopz_implement

(PECL uopz 1, PECL uopz 2, PECL uopz 5, PECL uopz 6)

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.

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


Overload a VM opcode

  • « uopz_implement
  • uopz_redefine »
  • PHP Manual
  • Uopz Functions
  • Overload a VM opcode

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


Redefine a constant

  • « uopz_overload
  • uopz_rename »
  • PHP Manual
  • Uopz Functions
  • Redefine a constant

uopz_redefine

(PECL uopz 1, PECL uopz 2, PECL uopz 5, PECL uopz 6)

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


Rename a function at runtime

  • « uopz_redefine
  • uopz_restore »
  • PHP Manual
  • Uopz Functions
  • Rename a function at runtime

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


Restore a previously backed up function

  • « uopz_rename
  • uopz_set_hook »
  • PHP Manual
  • Uopz Functions
  • Restore a previously backed up function

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


Sets hook to execute when entering a function or method

  • « uopz_restore
  • uopz_set_mock »
  • PHP Manual
  • Uopz Functions
  • Sets hook to execute when entering a function or method

uopz_set_hook

(PECL uopz 5, PECL uopz 6)

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


Use mock instead of class for new objects

  • « uopz_set_hook
  • uopz_set_property »
  • PHP Manual
  • Uopz Functions
  • Use mock instead of class for new objects

uopz_set_mock

(PECL uopz 5, PECL uopz 6)

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.

Changelog

Version | Description
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


Sets value of existing class or instance property

  • « uopz_set_mock
  • uopz_set_return »
  • PHP Manual
  • Uopz Functions
  • Sets value of existing class or instance property

uopz_set_property

(PECL uopz 5, PECL uopz 6)

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


Provide a return value for an existing function

  • « uopz_set_property
  • uopz_set_static »
  • PHP Manual
  • Uopz Functions
  • Provide a return value for an existing function

uopz_set_return

(PECL uopz 5, PECL uopz 6)

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


Sets the static variables in function or method scope

  • « uopz_set_return
  • uopz_undefine »
  • PHP Manual
  • Uopz Functions
  • Sets the static variables in function or method scope

uopz_set_static

(PECL uopz 5, PECL uopz 6)

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


Undefine a constant

  • « uopz_set_static
  • uopz_unset_hook »
  • PHP Manual
  • Uopz Functions
  • Undefine a constant

uopz_undefine

(PECL uopz 1, PECL uopz 2, PECL uopz 5, PECL uopz 6)

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)


Removes previously set hook on function or method

  • « uopz_undefine
  • uopz_unset_mock »
  • PHP Manual
  • Uopz Functions
  • Removes previously set hook on function or method

uopz_unset_hook

(PECL uopz 5, PECL uopz 6)

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


Unset previously set mock

  • « uopz_unset_hook
  • uopz_unset_return »
  • PHP Manual
  • Uopz Functions
  • Unset previously set mock

uopz_unset_mock

(PECL uopz 5, PECL uopz 6)

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.

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


Unsets a previously set return value for a function

  • « uopz_unset_mock
  • Weakref »
  • PHP Manual
  • Uopz Functions
  • Unsets a previously set return value for a function

uopz_unset_return

(PECL uopz 5, PECL uopz 6)

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


Weak References

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Resource Types
  • WeakRef — The WeakRef class
    • Weakref::acquire — Acquires a strong reference on that object
    • Weakref::__construct — Constructs a new weak reference
    • Weakref::get — Returns the object pointed to by the weak reference
    • Weakref::release — Releases a previously acquired reference
    • Weakref::valid — Checks whether the object referenced still exists
  • WeakMap — The WeakMap class
    • WeakMap::__construct — Constructs a new map
    • WeakMap::count — Counts the number of live entries in the map
    • WeakMap::current — Returns the current value under iteration
    • WeakMap::key — Returns the current key under iteration
    • WeakMap::next — Advances to the next map element
    • 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
    • WeakMap::rewind — Rewinds the iterator to the beginning of the map
    • WeakMap::valid — Returns whether the iterator is still on a valid map element


Introduction

Weak references provide a non-intrusive gateway to ephemeral objects. Unlike normal (strong) references, weak references do not prevent the garbage collector from freeing that object. For this reason, an object may be destroyed even though a weak reference to that object still exists. In such conditions, the weak reference seamlessly becomes invalid.

Example #1 Weakref usage example

<?php
class MyClass {
    public function __destruct() {
        echo "Destroying object!\n";
    }
}

$o1 = new MyClass;

$r1 = new Weakref($o1);

if ($r1->valid()) {
    echo "Object still exists!\n";
    var_dump($r1->get());
} else {
    echo "Object is dead!\n";
}

unset($o1);

if ($r1->valid()) {
    echo "Object still exists!\n";
    var_dump($r1->get());
} else {
    echo "Object is dead!\n";
}
?>

The above example will output:

Object still exists!
object(MyClass)#1 (0) {
}
Destroying object!
Object is dead!


Installing/Configuring

Table of Contents

  • Requirements
  • 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/weakref.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.


  • « Installation
  • WeakRef »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

This extension has no resource types defined.


The WeakRef class

(PECL weakref >= 0.1.0)

Introduction

The WeakRef class provides a gateway to objects without preventing the garbage collector from freeing those objects. It also provides a way to turn a weak reference into a strong one.

Note:

The class WeakRef is not to be confused with the class WeakReference.

Class synopsis

WeakRef {
/* Methods */
public Weakref::__construct ( object $object )
public Weakref::acquire ( void ) : bool
public Weakref::get ( void ) : object
public Weakref::release ( void ) : bool
public Weakref::valid ( void ) : bool
}

Examples

Example #1 WeakRef usage example

<?php
class MyClass {
    public function __destruct() {
        echo "Destroying object!\n";
    }
}

$o1 = new MyClass;

$r1 = new WeakRef($o1);

if ($r1->valid()) {
    echo "Object still exists!\n";
    var_dump($r1->get());
} else {
    echo "Object is dead!\n";
}

unset($o1);

if ($r1->valid()) {
    echo "Object still exists!\n";
    var_dump($r1->get());
} else {
    echo "Object is dead!\n";
}
?>

The above example will output:

Object still exists!
object(MyClass)#1 (0) {
}
Destroying object!
Object is dead!

Table of Contents

  • Weakref::acquire — Acquires a strong reference on that object
  • Weakref::__construct — Constructs a new weak reference
  • Weakref::get — Returns the object pointed to by the weak reference
  • Weakref::release — Releases a previously acquired reference
  • Weakref::valid — Checks whether the object referenced still exists


Acquires a strong reference on that object

  • « WeakRef
  • Weakref::__construct »
  • PHP Manual
  • WeakRef
  • Acquires a strong reference on that object

Weakref::acquire

(PECL weakref >= 0.1.0)

Weakref::acquire — Acquires a strong reference on that object

Description

public Weakref::acquire ( void ) : bool

Acquires a strong reference on that object, virtually turning the weak reference into a strong one.

The Weakref instance maintains an internal acquired counter to track outstanding strong references. If the call to Weakref::acquire() is successful, this counter will be incremented by one.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the reference was valid and could be turned into a strong reference, FALSE otherwise.

Examples

Example #1 Weakref::acquire() example

<?php
class MyClass {
    public function __destruct() {
        echo "Destroying object!\n";
    }
}

$o1 = new MyClass;

$r1 = new Weakref($o1);

$r1->acquire();

echo "Unsetting o1...\n";
unset($o1);

$o2 = $r1->get();

$r1->release();

echo "Unsetting o2...\n";
unset($o2);
?>

The above example will output:

Unsetting o1...
Unsetting o2...
Destroying object!

Example #2 Nested acquire/release example

<?php
class MyClass {
    public function __destruct() {
        echo "Destroying object!\n";
    }
}

$o1 = new MyClass;

$r1 = new Weakref($o1);

echo "Acquiring...\n";
$r1->acquire();

echo "  Unsetting...\n";
unset($o1);

echo "  Acquiring...\n";
$r1->acquire();

echo "    Acquiring...\n";
$r1->acquire();

echo "    Releasing...\n";
$r1->release();

echo "  Releasing...\n";
$r1->release();

echo "Releasing...\n";
$r1->release();

?>

The above example will output:

Acquiring...
  Unsetting...
  Acquiring...
    Acquiring...
    Releasing...
  Releasing...
Releasing...
Destroying object!

See Also

  • Weakref::release() - Releases a previously acquired reference


Constructs a new weak reference

  • « Weakref::acquire
  • Weakref::get »
  • PHP Manual
  • WeakRef
  • Constructs a new weak reference

Weakref::__construct

(PECL weakref >= 0.1.0)

Weakref::__construct — Constructs a new weak reference

Description

public Weakref::__construct ( object $object )

Constructs a new weak reference.

Parameters

object

The object to reference.

Return Values

No value is returned.

Examples

Example #1 Weakref::__construct() example

<?php
class MyClass {
    public function __destruct() {
        echo "Destroying object!\n";
    }
}

$o1 = new MyClass;

$r1 = new Weakref($o1);

if ($r1->valid()) {
    echo "Object still exists!\n";
    var_dump($r1->get());
} else {
    echo "Object is dead!\n";
}

unset($o1);

if ($r1->valid()) {
    echo "Object still exists!\n";
    var_dump($r1->get());
} else {
    echo "Object is dead!\n";
}
?>

The above example will output:

Object still exists!
object(MyClass)#1 (0) {
}
Destroying object!
Object is dead!


Returns the object pointed to by the weak reference

  • « Weakref::__construct
  • Weakref::release »
  • PHP Manual
  • WeakRef
  • Returns the object pointed to by the weak reference

Weakref::get

(PECL weakref >= 0.1.0)

Weakref::get — Returns the object pointed to by the weak reference

Description

public Weakref::get ( void ) : object

Returns the object pointed to by the weak reference.

Parameters

This function has no parameters.

Return Values

Returns the object if the reference is still valid, NULL otherwise.

See Also

  • Weakref::valid() - Checks whether the object referenced still exists


Releases a previously acquired reference

  • « Weakref::get
  • Weakref::valid »
  • PHP Manual
  • WeakRef
  • Releases a previously acquired reference

Weakref::release

(PECL weakref >= 0.1.0)

Weakref::release — Releases a previously acquired reference

Description

public Weakref::release ( void ) : bool

Releases a previously acquired reference, potentially turning a strong reference back into a weak reference.

The Weakref instance maintains an internal acquired counter to track outstanding strong references. If the call to Weakref::release() is successful, this counter will be decremented by one. Once this counter reaches zero, the strong reference is turned back into a weak reference.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the reference was previously acquired and thus could be released, FALSE otherwise.

Examples

Example #1 Weakref::release() example

<?php
class MyClass {
    public function __destruct() {
        echo "Destroying object!\n";
    }
}

$o1 = new MyClass;

$r1 = new Weakref($o1);

$r1->acquire();

echo "Unsetting o1...\n";
unset($o1);

$o2 = $r1->get();

$r1->release();

echo "Unsetting o2...\n";
unset($o2);
?>

The above example will output:

Unsetting o1...
Unsetting o2...
Destroying object!

See Also

  • Weakref::acquire() - Acquires a strong reference on that object


Checks whether the object referenced still exists

  • « Weakref::release
  • WeakMap »
  • PHP Manual
  • WeakRef
  • Checks whether the object referenced still exists

Weakref::valid

(PECL weakref >= 0.1.0)

Weakref::valid — Checks whether the object referenced still exists

Description

public Weakref::valid ( void ) : bool

Checks whether the object referenced still exists.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the object still exists and is thus still accessible via Weakref::get(), FALSE otherwise.

See Also

  • Weakref::get() - Returns the object pointed to by the weak reference


The WeakMap class

(PECL weakref >= 0.2.0)

Introduction

Class synopsis

WeakMap implements Countable , ArrayAccess , Iterator {
/* Methods */
public __construct ( void )
public count ( void ) : int
public current ( void ) : mixed
public key ( void ) : object
public next ( void ) : void
public offsetExists ( object $object ) : bool
public offsetGet ( object $object ) : mixed
public offsetSet ( object $object , mixed $value ) : void
public offsetUnset ( object $object ) : void
public rewind ( void ) : void
public valid ( void ) : bool
}

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)

Table of Contents

  • WeakMap::__construct — Constructs a new map
  • WeakMap::count — Counts the number of live entries in the map
  • WeakMap::current — Returns the current value under iteration
  • WeakMap::key — Returns the current key under iteration
  • WeakMap::next — Advances to the next map element
  • 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
  • WeakMap::rewind — Rewinds the iterator to the beginning of the map
  • WeakMap::valid — Returns whether the iterator is still on a valid map element


Constructs a new map

  • « WeakMap
  • WeakMap::count »
  • PHP Manual
  • WeakMap
  • Constructs a new map

WeakMap::__construct

(PECL weakref >= 0.2.0)

WeakMap::__construct — Constructs a new map

Description

public WeakMap::__construct ( void )

Constructs a new map.

Parameters

This function has no parameters.

Return Values

No value is returned.


Counts the number of live entries in the map

  • « WeakMap::__construct
  • WeakMap::current »
  • PHP Manual
  • WeakMap
  • Counts the number of live entries in the map

WeakMap::count

(PECL weakref >= 0.2.0)

WeakMap::count — Counts the number of live entries in the map

Description

public WeakMap::count ( void ) : 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.


Returns the current value under iteration

  • « WeakMap::count
  • WeakMap::key »
  • PHP Manual
  • WeakMap
  • Returns the current value under iteration

WeakMap::current

(PECL weakref >= 0.2.0)

WeakMap::current — Returns the current value under iteration

Description

public WeakMap::current ( void ) : mixed

Returns the current value being iterated on in the map.

Parameters

This function has no parameters.

Return Values

The value currently being iterated on.


Returns the current key under iteration

  • « WeakMap::current
  • WeakMap::next »
  • PHP Manual
  • WeakMap
  • Returns the current key under iteration

WeakMap::key

(PECL weakref >= 0.2.0)

WeakMap::key — Returns the current key under iteration

Description

public WeakMap::key ( void ) : object

Returns the object serving as key in the map, at the current iterating position.

Parameters

This function has no parameters.

Return Values

The object key currently being iterated.


Advances to the next map element

  • « WeakMap::key
  • WeakMap::offsetExists »
  • PHP Manual
  • WeakMap
  • Advances to the next map element

WeakMap::next

(PECL weakref >= 0.2.0)

WeakMap::next — Advances to the next map element

Description

public WeakMap::next ( void ) : void

Advances to the next map element.

Parameters

This function has no parameters.

Return Values

No value is returned.


Checks whether a certain object is in the map

  • « WeakMap::next
  • WeakMap::offsetGet »
  • PHP Manual
  • WeakMap
  • Checks whether a certain object is in the map

WeakMap::offsetExists

(PECL weakref >= 0.2.0)

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.


Returns the value pointed to by a certain object

  • « WeakMap::offsetExists
  • WeakMap::offsetSet »
  • PHP Manual
  • WeakMap
  • Returns the value pointed to by a certain object

WeakMap::offsetGet

(PECL weakref >= 0.2.0)

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, NULL otherwise.


Updates the map with a new key-value pair

  • « WeakMap::offsetGet
  • WeakMap::offsetUnset »
  • PHP Manual
  • WeakMap
  • Updates the map with a new key-value pair

WeakMap::offsetSet

(PECL weakref >= 0.2.0)

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.


Removes an entry from the map

  • « WeakMap::offsetSet
  • WeakMap::rewind »
  • PHP Manual
  • WeakMap
  • Removes an entry from the map

WeakMap::offsetUnset

(PECL weakref >= 0.2.0)

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.


Rewinds the iterator to the beginning of the map

  • « WeakMap::offsetUnset
  • WeakMap::valid »
  • PHP Manual
  • WeakMap
  • Rewinds the iterator to the beginning of the map

WeakMap::rewind

(PECL weakref >= 0.2.0)

WeakMap::rewind — Rewinds the iterator to the beginning of the map

Description

public WeakMap::rewind ( void ) : void

Rewinds the iterator to the beginning of the map.

Parameters

This function has no parameters.

Return Values

No value is returned.


Returns whether the iterator is still on a valid map element

  • « WeakMap::rewind
  • WinCache »
  • PHP Manual
  • WeakMap
  • Returns whether the iterator is still on a valid map element

WeakMap::valid

(PECL weakref >= 0.2.0)

WeakMap::valid — Returns whether the iterator is still on a valid map element

Description

public WeakMap::valid ( void ) : bool

Returns whether the iterator is still on a valid map element.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the iterator is on a valid element that can be accessed, FALSE otherwise.


Windows Cache for PHP

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • WinCache Statistics Script
    • WinCache Session Handler
    • WinCache Functions Reroutes
    • Resource Types
  • Predefined Constants
  • 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


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 as of PHP 5.5.0.

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


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" | PHP_INI_ALL | Available as of WinCache 1.0.0
wincache.fcenabledfilter | "NULL" | "NULL" | "NULL" | PHP_INI_SYSTEM | Available as of WinCache 1.0.0
wincache.fcachesize | "24" | "5" | "255" | PHP_INI_SYSTEM | Available as of WinCache 1.0.0
wincache.fcndetect | "1" | "0" | "1" | PHP_INI_SYSTEM | Available as of WinCache 1.1.0
wincache.maxfilesize | "256" | "10" | "2048" | PHP_INI_SYSTEM | Available as of WinCache 1.0.0
wincache.ocenabled | "1" | "0" | "1" | PHP_INI_ALL | Available as of WinCache 1.0.0. Removed as of 2.0.0.0
wincache.ocenabledfilter | "NULL" | "NULL" | "NULL" | PHP_INI_SYSTEM | Available as of WinCache 1.0.0. Removed as of 2.0.0.0
wincache.ocachesize | "96" | "15" | "255" | PHP_INI_SYSTEM | Available as of WinCache 1.0.0. Removed as of 2.0.0.0
wincache.filecount | "4096" | "1024" | "16384" | PHP_INI_SYSTEM | Available as of WinCache 1.0.0
wincache.chkinterval | "30" | "0" | "300" | PHP_INI_SYSTEM | Available as of WinCache 1.0.0
wincache.ttlmax | "1200" | "0" | "7200" | PHP_INI_SYSTEM | Available as of WinCache 1.0.0
wincache.enablecli | 0 | 0 | 1 | PHP_INI_SYSTEM | Available as of WinCache 1.0.0
wincache.ignorelist | NULL | NULL | NULL | PHP_INI_ALL | Available as of WinCache 1.0.0
wincache.namesalt | NULL | NULL | NULL | PHP_INI_SYSTEM | Available as of WinCache 1.0.0
wincache.ucenabled | 1 | 0 | 1 | PHP_INI_SYSTEM | Available as of WinCache 1.1.0
wincache.ucachesize | 8 | 5 | 85 | PHP_INI_SYSTEM | Available as of WinCache 1.1.0
wincache.scachesize | 8 | 5 | 85 | PHP_INI_SYSTEM | Available as of WinCache 1.1.0
wincache.rerouteini | NULL | NULL | NULL | PHP_INI_SYSTEM | Available as of WinCache 1.2.0. Removed as of 1.3.7
wincache.reroute_enabled | 1 | 0 | 1 | PHP_INI_SYSTEM | PHP_INI_PERDIR | Available as of WinCache 1.3.7
wincache.srwlocks | 1 | 0 | 1 | PHP_INI_SYSTEM | Available as of WinCache 1.3.6.3. Removed as of 2.0.0.0
wincache.filemapdir | NULL | NULL | NULL | PHP_INI_SYSTEM | Available as of WinCache 1.3.7.4
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

wincache.fcenabled boolean
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 integer
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 boolean
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 integer
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 boolean
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 integer
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 integer
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 integer
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 integer
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 boolean
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 boolean
Enables or disables the user cache functionality.
wincache.ucachesize integer
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 integer
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 boolean
Enables or disables the rerouting of certain file I/O functions through the file cache.
wincache.srwlocks boolean
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 Reroutes
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

This extension has no resource types defined.


  • « Resource Types
  • WinCache Functions »
  • PHP Manual
  • WinCache
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


WinCache Functions

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


Retrieves information about files cached in the file cache

  • « WinCache Functions
  • wincache_fcache_meminfo »
  • PHP Manual
  • WinCache Functions
  • Retrieves information about files cached in the file cache

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

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


Retrieves information about file cache memory usage

  • « wincache_fcache_fileinfo
  • wincache_lock »
  • PHP Manual
  • WinCache Functions
  • Retrieves information about file 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 ( void ) : array

Retrieves information about memory usage by file cache.

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


Acquires an exclusive lock on a given key

  • « wincache_fcache_meminfo
  • wincache_ocache_fileinfo »
  • PHP Manual
  • WinCache Functions
  • Acquires an exclusive lock on a given key

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


Retrieves information about files cached in the opcode cache

  • « wincache_lock
  • wincache_ocache_meminfo »
  • PHP Manual
  • WinCache Functions
  • Retrieves information about files cached in the opcode 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

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


Retrieves information about opcode cache memory usage

  • « wincache_ocache_fileinfo
  • wincache_refresh_if_changed »
  • PHP Manual
  • WinCache Functions
  • Retrieves information about opcode 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 ( void ) : array

Retrieves information about memory usage by opcode cache.

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


Refreshes the cache entries for the cached files

  • « wincache_ocache_meminfo
  • wincache_rplist_fileinfo »
  • PHP Manual
  • WinCache Functions
  • Refreshes the cache entries for the cached files

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


Retrieves information about resolve file path cache

  • « wincache_refresh_if_changed
  • wincache_rplist_meminfo »
  • PHP Manual
  • WinCache Functions
  • Retrieves information about resolve file path 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

Retrieves information about cached mappings between relative file paths and corresponding absolute file paths.

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


Retrieves information about memory usage by the resolve file path cache

  • « wincache_rplist_fileinfo
  • wincache_scache_info »
  • PHP Manual
  • WinCache Functions
  • Retrieves information about memory usage by the resolve file path cache

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 ( void ) : array

Retrieves information about memory usage by resolve file path cache.

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


Retrieves information about files cached in the session cache

  • « wincache_rplist_meminfo
  • wincache_scache_meminfo »
  • PHP Manual
  • WinCache Functions
  • Retrieves information about files cached in the session cache

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

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


Retrieves information about session cache memory usage

  • « wincache_scache_info
  • wincache_ucache_add »
  • PHP Manual
  • WinCache Functions
  • 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 ( void ) : array

Retrieves information about memory usage by session cache.

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


Adds a variable in user cache only if variable does not already exist in the cache

  • « wincache_scache_meminfo
  • wincache_ucache_cas »
  • PHP Manual
  • WinCache Functions
  • Adds a variable in user cache only if variable does not already exist in the 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 paramter is ignored if first argument is an array. A general guidance is to pass NULL as value while using array as key. If value is an object, or an array containing objects, then the objects will be serialized. See __sleep() for details on serializing objects.

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


Compares the variable with old value and assigns new value to it

  • « wincache_ucache_add
  • wincache_ucache_clear »
  • PHP Manual
  • WinCache Functions
  • Compares the variable with old value and assigns new value to it

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


Deletes entire content of the user cache

  • « wincache_ucache_cas
  • wincache_ucache_dec »
  • PHP Manual
  • WinCache Functions
  • Deletes entire content of the user cache

wincache_ucache_clear

(PECL wincache >= 1.1.0)

wincache_ucache_clear — Deletes entire content of the user cache

Description

wincache_ucache_clear ( void ) : bool

Clears/deletes all the values stored in the user cache.

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


Decrements the value associated with the key

  • « wincache_ucache_clear
  • wincache_ucache_delete »
  • PHP Manual
  • WinCache Functions
  • Decrements the value associated with the key

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


Deletes variables from the user cache

  • « wincache_ucache_dec
  • wincache_ucache_exists »
  • PHP Manual
  • WinCache Functions
  • Deletes variables from the user cache

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


Checks if a variable exists in the user cache

  • « wincache_ucache_delete
  • wincache_ucache_get »
  • PHP Manual
  • WinCache Functions
  • Checks if a variable exists 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


Gets a variable stored in the user cache

  • « wincache_ucache_exists
  • wincache_ucache_inc »
  • PHP Manual
  • WinCache Functions
  • Gets a variable 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()


Increments the value associated with the key

  • « wincache_ucache_get
  • wincache_ucache_info »
  • PHP Manual
  • WinCache Functions
  • Increments the value associated with the key

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


Retrieves information about data stored in the user cache

  • « wincache_ucache_inc
  • wincache_ucache_meminfo »
  • PHP Manual
  • WinCache Functions
  • Retrieves information about data stored in the user cache

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

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


Retrieves information about user cache memory usage

  • « wincache_ucache_info
  • wincache_ucache_set »
  • PHP Manual
  • WinCache Functions
  • Retrieves information about user 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 ( void ) : array

Retrieves information about memory usage by user cache.

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


Adds a variable in user cache and overwrites a variable if it already exists in the cache

  • « wincache_ucache_meminfo
  • wincache_unlock »
  • PHP Manual
  • WinCache Functions
  • Adds a variable in user cache and overwrites a variable if it already exists in the cache

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 paramter is ignored if first argument is an array. A general guidance is to pass NULL as value while using array as key. If value is an object, or an array containing objects, then the objects will be serialized. See __sleep() for details on serializing objects.

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


Releases an exclusive lock on a given key

  • « wincache_ucache_set
  • Building for Windows »
  • PHP Manual
  • WinCache Functions
  • Releases an exclusive lock on a given key

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


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.


Hierarchical Profiler

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • 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


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.


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

Here's a short explanation of the configuration directives.

xhprof.output_dir string

Directory used by the default implementation of the iXHProfRuns interface (namely, the XHProfRuns_Default class) for storing XHProf runs.


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 (integer)
Used to skip all built-in (internal) functions.
XHPROF_FLAGS_CPU (integer)
Used to add CPU profiling information to the output.
XHPROF_FLAGS_MEMORY (integer)
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

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


Stops xhprof profiler

  • « Xhprof Functions
  • xhprof_enable »
  • PHP Manual
  • Xhprof Functions
  • Stops xhprof profiler

xhprof_disable

(PECL xhprof >= 0.9.0)

xhprof_disable — Stops xhprof profiler

Description

xhprof_disable ( void ) : 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.

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
        )

)


Start xhprof profiler

  • « xhprof_disable
  • xhprof_sample_disable »
  • PHP Manual
  • Xhprof Functions
  • Start xhprof profiler

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


Stops xhprof sample profiler

  • « xhprof_enable
  • xhprof_sample_enable »
  • PHP Manual
  • Xhprof Functions
  • Stops xhprof sample profiler

xhprof_sample_disable

(PECL xhprof >= 0.9.0)

xhprof_sample_disable — Stops xhprof sample profiler

Description

xhprof_sample_disable ( void ) : array

Stops the sample mode xhprof profiler, and

Parameters

This function has no parameters.

Return Values

An array of xhprof sample data, from the run.

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


Start XHProf profiling in sampling mode

  • « xhprof_sample_disable
  • Audio Formats Manipulation »
  • PHP Manual
  • Xhprof Functions
  • Start XHProf profiling in sampling mode

xhprof_sample_enable

(PECL xhprof >= 0.9.0)

xhprof_sample_enable — Start XHProf profiling in sampling mode

Description

xhprof_sample_enable ( void ) : 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


Audio Formats Manipulation

  • ID3 — ID3 Tags
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • ID3 Functions
  • KTaglib
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • KTaglib_MPEG_File — The KTaglib_MPEG_File class
    • KTaglib_MPEG_AudioProperties — The KTaglib_MPEG_AudioProperties class
    • KTaglib_Tag — The KTaglib_Tag class
    • KTaglib_ID3v2_Tag — The KTaglib_ID3v2_Tag class
    • KTaglib_ID3v2_Frame — The KTaglib_ID3v2_Frame class
    • KTaglib_ID3v2_AttachedPictureFrame — The KTaglib_ID3v2_AttachedPictureFrame class
  • oggvorbis — OGG/Vorbis
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Context options
    • Examples
  • OpenAL — OpenAL Audio Bindings
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • OpenAL Functions


ID3 Tags

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • ID3 Functions
    • id3_get_frame_long_name — Get the long name of an ID3v2 frame
    • id3_get_frame_short_name — Get the short name of an ID3v2 frame
    • id3_get_genre_id — Get the id for a genre
    • id3_get_genre_list — Get all possible genre values
    • id3_get_genre_name — Get the name for a genre id
    • id3_get_tag — Get all information stored in an ID3 tag
    • id3_get_version — Get version of an ID3 tag
    • id3_remove_tag — Remove an existing ID3 tag
    • id3_set_tag — Update information stored in an ID3 tag


Introduction

These functions let you read and manipulate ID3 tags. ID3 tags are used in MP3 files to store title of the song, as well as information about the artist, album, genre, year and track number.

Since version 0.2 it is also possible to extract text frames from ID3 v2.2+ tags.


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

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.


Predefined Constants

Most of the id3 functions either let you specify or return a tag version. In order to specify the version please use on of these constants.

ID3_V1_0 (integer)
ID3_V1_0 is used if you are working with ID3 V1.0 tags. These tags may contain the fields title, artist, album, genre, year and comment.
ID3_V1_1 (integer)
ID3_V1_1 is used if you are working with ID3 V1.1 tags. These tags may all information contained in v1.0 tags plus the track number.
ID3_V2_1 (integer)
ID3_V2_1 is used if you are working with ID3 V2.1 tags.
ID3_V2_2 (integer)
ID3_V2_2 is used if you are working with ID3 V2.2 tags.
ID3_V2_3 (integer)
ID3_V2_3 is used if you are working with ID3 V2.3 tags.
ID3_V2_4 (integer)
ID3_V2_4 is used if you are working with ID3 V2.4 tags.
ID3_BEST (integer)
ID3_BEST is used if would like to let the id3 functions determine which tag version should be used.


ID3 Functions

Table of Contents

  • id3_get_frame_long_name — Get the long name of an ID3v2 frame
  • id3_get_frame_short_name — Get the short name of an ID3v2 frame
  • id3_get_genre_id — Get the id for a genre
  • id3_get_genre_list — Get all possible genre values
  • id3_get_genre_name — Get the name for a genre id
  • id3_get_tag — Get all information stored in an ID3 tag
  • id3_get_version — Get version of an ID3 tag
  • id3_remove_tag — Remove an existing ID3 tag
  • id3_set_tag — Update information stored in an ID3 tag


Get the long name of an ID3v2 frame

  • « ID3 Functions
  • id3_get_frame_short_name »
  • PHP Manual
  • ID3 Functions
  • Get the long name of an ID3v2 frame

id3_get_frame_long_name

(PECL id3 >= 0.2)

id3_get_frame_long_name — Get the long name of an ID3v2 frame

Description

id3_get_frame_long_name ( string $frameId ) : string

id3_get_frame_long_name() returns the long name for an ID3v2 frame.

Parameters

frameId

An ID3v2 frame

Return Values

Returns the frame long name or FALSE on errors.

Examples

Example #1 id3_get_frame_long_name() example

<?php
$longName = id3_get_frame_long_name("TOLY");
echo $longName;
?>

The above example will output:

Original lyricist(s)/text writer(s)

See Also

  • id3_get_frame_short_name() - Get the short name of an ID3v2 frame


Get the short name of an ID3v2 frame

  • « id3_get_frame_long_name
  • id3_get_genre_id »
  • PHP Manual
  • ID3 Functions
  • Get the short name of an ID3v2 frame

id3_get_frame_short_name

(PECL id3 >= 0.2)

id3_get_frame_short_name — Get the short name of an ID3v2 frame

Description

id3_get_frame_short_name ( string $frameId ) : string

id3_get_frame_short_name() returns the short name for an ID3v2 frame.

Parameters

frameId

An ID3v2 frame

Return Values

Returns the frame short name or FALSE on errors.

The values returned by id3_get_frame_short_name() are used in the array returned by id3_get_tag().

Examples

Example #1 id3_get_frame_short_name() example

<?php
$shortName = id3_get_frame_short_name("TOLY");
echo $shortName;
?>

The above example will output:

originalLyricist

See Also

  • id3_get_frame_long_name() - Get the long name of an ID3v2 frame


Get the id for a genre

  • « id3_get_frame_short_name
  • id3_get_genre_list »
  • PHP Manual
  • ID3 Functions
  • Get the id for a genre

id3_get_genre_id

(PECL id3 >= 0.1)

id3_get_genre_id — Get the id for a genre

Description

id3_get_genre_id ( string $genre ) : int

id3_get_genre_id() returns the id for a genre.

Parameters

genre

Genre name as string.

Return Values

The genre id or FALSE on errors.

Examples

Example #1 id3_get_genre_id() example

<?php
$id = id3_get_genre_id("Alternative");
echo $id;
?>

The above example will output:

20

See Also

  • id3_get_genre_name() - Get the name for a genre id
  • id3_get_genre_list() - Get all possible genre values


Get all possible genre values

  • « id3_get_genre_id
  • id3_get_genre_name »
  • PHP Manual
  • ID3 Functions
  • Get all possible genre values

id3_get_genre_list

(PECL id3 >= 0.1)

id3_get_genre_list — Get all possible genre values

Description

id3_get_genre_list ( void ) : array

id3_get_genre_list() returns an array containing all possible genres that may be stored in an ID3 tag. This list has been created by Eric Kemp and later extended by WinAmp.

This function is useful to provide you users a list of genres from which they may choose one. When updating the ID3 tag you will always have to specify the genre as an integer ranging from 0 to 147.

Return Values

Returns an array containing all possible genres that may be stored in an ID3 tag.

Examples

Example #1 id3_get_genre_list() example

<?php
$genres = id3_get_genre_list();
print_r($genres);
?>

The above example will output:

Array
(
    [0] => Blues
    [1] => Classic Rock
    [2] => Country
    [3] => Dance
    [4] => Disco
    [5] => Funk
    [6] => Grunge
    [7] => Hip-Hop
    [8] => Jazz
    [9] => Metal
    [10] => New Age
    [11] => Oldies
    [12] => Other
    [13] => Pop
    [14] => R&B
    [15] => Rap
    [16] => Reggae
    [17] => Rock
    [18] => Techno
    [19] => Industrial
    [20] => Alternative
    [21] => Ska
    [22] => Death Metal
    [23] => Pranks
    [24] => Soundtrack
    [25] => Euro-Techno
    [26] => Ambient
    [27] => Trip-Hop
    [28] => Vocal
    [29] => Jazz+Funk
    [30] => Fusion
    [31] => Trance
    [32] => Classical
    [33] => Instrumental
    [34] => Acid
    [35] => House
    [36] => Game
    [37] => Sound Clip
    [38] => Gospel
    [39] => Noise
    [40] => Alternative Rock
    [41] => Bass
    [42] => Soul
    [43] => Punk
    [44] => Space
    [45] => Meditative
    [46] => Instrumental Pop
    [47] => Instrumental Rock
    [48] => Ethnic
    [49] => Gothic
    [50] => Darkwave
    [51] => Techno-Industrial
    [52] => Electronic
    [53] => Pop-Folk
    [54] => Eurodance
    [55] => Dream
    [56] => Southern Rock
    [57] => Comedy
    [58] => Cult
    [59] => Gangsta
    [60] => Top 40
    [61] => Christian Rap
    [62] => Pop/Funk
    [63] => Jungle
    [64] => Native US
    [65] => Cabaret
    [66] => New Wave
    [67] => Psychadelic
    [68] => Rave
    [69] => Showtunes
    [70] => Trailer
    [71] => Lo-Fi
    [72] => Tribal
    [73] => Acid Punk
    [74] => Acid Jazz
    [75] => Polka
    [76] => Retro
    [77] => Musical
    [78] => Rock & Roll
    [79] => Hard Rock
    [80] => Folk
    [81] => Folk-Rock
    [82] => National Folk
    [83] => Swing
    [84] => Fast Fusion
    [85] => Bebob
    [86] => Latin
    [87] => Revival
    [88] => Celtic
    [89] => Bluegrass
    [90] => Avantgarde
    [91] => Gothic Rock
    [92] => Progressive Rock
    [93] => Psychedelic Rock
    [94] => Symphonic Rock
    [95] => Slow Rock
    [96] => Big Band
    [97] => Chorus
    [98] => Easy Listening
    [99] => Acoustic
    [100] => Humour
    [101] => Speech
    [102] => Chanson
    [103] => Opera
    [104] => Chamber Music
    [105] => Sonata
    [106] => Symphony
    [107] => Booty Bass
    [108] => Primus
    [109] => Porn Groove
    [110] => Satire
    [111] => Slow Jam
    [112] => Club
    [113] => Tango
    [114] => Samba
    [115] => Folklore
    [116] => Ballad
    [117] => Power Ballad
    [118] => Rhytmic Soul
    [119] => Freestyle
    [120] => Duet
    [121] => Punk Rock
    [122] => Drum Solo
    [123] => Acapella
    [124] => Euro-House
    [125] => Dance Hall
    [126] => Goa
    [127] => Drum & Bass
    [128] => Club-House
    [129] => Hardcore
    [130] => Terror
    [131] => Indie
    [132] => BritPop
    [133] => Negerpunk
    [134] => Polsk Punk
    [135] => Beat
    [136] => Christian Gangsta
    [137] => Heavy Metal
    [138] => Black Metal
    [139] => Crossover
    [140] => Contemporary C
    [141] => Christian Rock
    [142] => Merengue
    [143] => Salsa
    [144] => Thrash Metal
    [145] => Anime
    [146] => JPop
    [147] => SynthPop
)

See Also

  • id3_get_genre_name() - Get the name for a genre id
  • id3_get_genre_id() - Get the id for a genre


Get the name for a genre id

  • « id3_get_genre_list
  • id3_get_tag »
  • PHP Manual
  • ID3 Functions
  • Get the name for a genre id

id3_get_genre_name

(PECL id3 >= 0.1)

id3_get_genre_name — Get the name for a genre id

Description

id3_get_genre_name ( int $genre_id ) : string

id3_get_genre_name() returns the name for a genre id.

Parameters

genre_id

An integer ranging from 0 to 147

Return Values

Returns the name as a string.

Examples

Example #1 id3_get_genre_name() example

<?php
$genre = id3_get_genre_name(20);
echo $genre;
?>

The above example will output:

Alternative

See Also

  • id3_get_genre_list() - Get all possible genre values
  • id3_get_genre_id() - Get the id for a genre


Get all information stored in an ID3 tag

  • « id3_get_genre_name
  • id3_get_version »
  • PHP Manual
  • ID3 Functions
  • Get all information stored in an ID3 tag

id3_get_tag

(PECL id3 >= 0.1)

id3_get_tag — Get all information stored in an ID3 tag

Description

id3_get_tag ( string $filename [, int $version = ID3_BEST ] ) : array

id3_get_tag() is used to get all information stored in the id3 tag of the specified file.

Parameters

filename

The path to the MP3 file

Instead of a filename you may also pass a valid stream resource

version

Allows you to specify the version of the tag as MP3 files may contain both, version 1.x and version 2.x tags

Since version 0.2 id3_get_tag() also supports ID3 tags of version 2.2, 2.3 and 2.4. To extract information from these tags, pass one of the constants ID3_V2_2, ID3_V2_3 or ID3_V2_4 as the second parameter. ID3 v2.x tags can contain a lot more information about the MP3 file than ID3 v1.x tags.

Return Values

Returns an associative array with various keys like: title, artist, ..

The key genre will contain an integer between 0 and 147. You may use id3_get_genre_name() to convert it to a human readable string.

Examples

Example #1 id3_get_tag() example

<?php
$tag = id3_get_tag( "path/to/example.mp3" );
print_r($tag);
?>

The above example will output something similar to:

Array
(
    [title] => DN-38416
    [artist] => Re:\Legion
    [album] => Reflections
    [year] => 2004
    [genre] => 19
)

Example #2 id3_get_tag() example

<?php
$tag = id3_get_tag( "path/to/example2.mp3", ID3_V2_3 );
print_r($tag);
?>

The above example will output something similar to:

Array
(
    [copyright] => Dirty Mac
    [originalArtist] => Dirty Mac
    [composer] => Marcus Götze
    [artist] => Dirty Mac
    [title] => Little Big Man
    [album] => Demo-Tape
    [track] => 5/12
    [genre] => (17)Rock
    [year] => 2001
)

See Also

  • id3_set_tag() - Update information stored in an ID3 tag
  • id3_remove_tag() - Remove an existing ID3 tag
  • id3_get_version() - Get version of an ID3 tag


Get version of an ID3 tag

  • « id3_get_tag
  • id3_remove_tag »
  • PHP Manual
  • ID3 Functions
  • Get version of an ID3 tag

id3_get_version

(PECL id3 >= 0.1)

id3_get_version — Get version of an ID3 tag

Description

id3_get_version ( string $filename ) : int

id3_get_version() retrieves the version(s) of the ID3 tag(s) in the MP3 file.

If a file contains an ID3 v1.1 tag, it always contains a 1.0 tag, as version 1.1 is just an extension of 1.0.

Parameters

filename

The path to the MP3 file

Instead of a filename you may also pass a valid stream resource

Return Values

Returns the version number of the ID3 tag of the file. As a tag can contain ID3 v1.x and v2.x tags, the return value of this function should be bitwise compared with the predefined constants ID3_V1_0, ID3_V1_1 and ID3_V2.

Examples

Example #1 id3_get_version() example

<?php
$version = id3_get_version( "path/to/example.mp3" );
if ($version & ID3_V1_0) {
    echo "Contains a 1.x tag\n";
}
if ($version & ID3_V1_1) {
    echo "Contains a 1.1 tag\n";
}
if ($version & ID3_V2) {
    echo "Contains a 2.x tag\n";
}
?>

The above example will output something similar to:

Contains a 1.x tag
Contains a 1.1 tag

See Also

  • id3_set_tag() - Update information stored in an ID3 tag
  • id3_get_tag() - Get all information stored in an ID3 tag
  • id3_remove_tag() - Remove an existing ID3 tag


Remove an existing ID3 tag

  • « id3_get_version
  • id3_set_tag »
  • PHP Manual
  • ID3 Functions
  • Remove an existing ID3 tag

id3_remove_tag

(PECL id3 >= 0.1)

id3_remove_tag — Remove an existing ID3 tag

Description

id3_remove_tag ( string $filename [, int $version = ID3_V1_0 ] ) : bool

id3_remove_tag() is used to remove the information stored of an ID3 tag.

Parameters

filename

The path to the MP3 file

Instead of a filename you may also pass a valid stream resource

version

Allows you to specify the version of the tag as MP3 files may contain both, version 1.x and version 2.x tags.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 id3_remove_tag() example

<?php
$result = id3_remove_tag( "path/to/example.mp3", ID3_V1_0 );
if ($result === true) {
    echo "Tag successfully removed\n";
}
?>

If the file is writable and contained a 1.0 tag, this will output:

Tag successfully removed

Notes

Note: Currently id3_remove_tag() only supports version 1.0 and 1.1. If you choose to remove a 1.0 tag and the file contains a 1.1 tag, this tag will be removed, as v1.1 is only an extension of 1.0.

See Also

  • id3_set_tag() - Update information stored in an ID3 tag
  • id3_get_tag() - Get all information stored in an ID3 tag
  • id3_get_version() - Get version of an ID3 tag


Update information stored in an ID3 tag

  • « id3_remove_tag
  • KTaglib »
  • PHP Manual
  • ID3 Functions
  • Update information stored in an ID3 tag

id3_set_tag

(PECL id3 >= 0.1)

id3_set_tag — Update information stored in an ID3 tag

Description

id3_set_tag ( string $filename , array $tag [, int $version = ID3_V1_0 ] ) : bool

id3_set_tag() is used to change the information stored of an ID3 tag. If no tag has been present, it will be added to the file.

Parameters

filename

The path to the MP3 file

Instead of a filename you may also pass a valid stream resource

tag

An associative array of tag keys and values

The following keys may be used in the associative array:

Keys in the associative array
key | possible value | available in version
title | string with maximum of 30 characters | v1.0, v1.1
artist | string with maximum of 30 characters | v1.0, v1.1
album | string with maximum of 30 characters | v1.0, v1.1
year | 4 digits | v1.0, v1.1
genre | integer value between 0 and 147 | v1.0, v1.1
comment | string with maximum of 30 characters (28 in v1.1) | v1.0, v1.1
track | integer between 0 and 255 | v1.1

version

Allows you to specify the version of the tag as MP3 files may contain both, version 1.x and version 2.x tags

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 id3_set_tag() example

<?php
$data = array(
              "title" => "Re:Start",
              "artist" => "Re:\Legion",
              "comment" => "A nice track"
             );
$result = id3_set_tag( "path/to/example.mp3", $data, ID3_V1_0 );
if ($result === true) {
    echo "Tag successfully updated\n";
}
?>

If the file is writable, this will output:

Tag successfully updated

Notes

Note: Currently id3_set_tag() only supports version 1.0 and 1.1.

See Also

  • id3_remove_tag() - Remove an existing ID3 tag
  • id3_get_tag() - Get all information stored in an ID3 tag
  • id3_get_version() - Get version of an ID3 tag


KTaglib

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
  • Predefined Constants
  • KTaglib_MPEG_File — The KTaglib_MPEG_File class
    • KTaglib_MPEG_File::__construct — Opens a new file
    • KTaglib_MPEG_File::getAudioProperties — Returns an object that provides access to the audio properties
    • KTaglib_MPEG_File::getID3v1Tag — Returns an object representing an ID3v1 tag
    • KTaglib_MPEG_File::getID3v2Tag — Returns a ID3v2 object
  • KTaglib_MPEG_AudioProperties — The KTaglib_MPEG_AudioProperties class
    • KTaglib_MPEG_AudioProperties::getBitrate — Returns the bitrate of the MPEG file
    • KTaglib_MPEG_AudioProperties::getChannels — Returns the amount of channels of a MPEG file
    • KTaglib_MPEG_AudioProperties::getLayer — Returns the layer of a MPEG file
    • KTaglib_MPEG_AudioProperties::getLength — Returns the length of a MPEG file
    • KTaglib_MPEG_AudioProperties::getSampleBitrate — Returns the sample bitrate of a MPEG file
    • KTaglib_MPEG_AudioProperties::getVersion — Returns the version of a MPEG file
    • KTaglib_MPEG_AudioProperties::isCopyrighted — Returns the copyright status of an MPEG file
    • KTaglib_MPEG_AudioProperties::isOriginal — Returns if the file is marked as the original file
    • KTaglib_MPEG_AudioProperties::isProtectionEnabled — Returns if protection mechanisms of an MPEG file are enabled
  • KTaglib_Tag — The KTaglib_Tag class
    • KTaglib_Tag::getAlbum — Returns the album string from a ID3 tag
    • KTaglib_Tag::getArtist — Returns the artist string from a ID3 tag
    • KTaglib_Tag::getComment — Returns the comment from a ID3 tag
    • KTaglib_Tag::getGenre — Returns the genre from a ID3 tag
    • KTaglib_Tag::getTitle — Returns the title string from a ID3 tag
    • KTaglib_Tag::getTrack — Returns the track number from a ID3 tag
    • KTaglib_Tag::getYear — Returns the year from a ID3 tag
    • KTaglib_Tag::isEmpty — Returns true if the tag is empty
  • KTaglib_ID3v2_Tag — The KTaglib_ID3v2_Tag class
    • KTaglib_ID3v2_Tag::addFrame — Add a frame to the ID3v2 tag
    • KTaglib_ID3v2_Tag::getFrameList — Returns an array of ID3v2 frames, associated with the ID3v2 tag
  • KTaglib_ID3v2_Frame — The KTaglib_ID3v2_Frame class
    • KTaglib_ID3v2_Frame::getSize — Returns the size of the frame in bytes
    • KTaglib_ID3v2_Frame::__toString — Returns a string representation of the frame
  • KTaglib_ID3v2_AttachedPictureFrame — The KTaglib_ID3v2_AttachedPictureFrame class
    • KTaglib_ID3v2_AttachedPictureFrame::getDescription — Returns a description for the picture in a picture frame
    • KTaglib_ID3v2_AttachedPictureFrame::getMimeType — Returns the mime type of the picture
    • KTaglib_ID3v2_AttachedPictureFrame::getType — Returns the type of the image
    • KTaglib_ID3v2_AttachedPictureFrame::savePicture — Saves the picture to a file
    • KTaglib_ID3v2_AttachedPictureFrame::setMimeType — Set's the mime type of the picture
    • KTaglib_ID3v2_AttachedPictureFrame::setPicture — Sets the frame picture to the given image
    • KTaglib_ID3v2_AttachedPictureFrame::setType — Set the type of the image


Introduction

KTaglib is an object oriented binding to the taglib library from the KDE project used in projects like Amarok to read and write ID3 and Ogg tags. The library also provides access to audio information. The bindings are designed usually follow the underlying C++ API, but were changed whenever there is a more PHP-like way.

Note:

At the moment ktaglib is able to read and write ID3v1 and ID3v2 tags.


  • « Introduction
  • Requirements »
  • PHP Manual
  • KTaglib
  • Installing/Configuring

Installing/Configuring

Table of Contents

  • Requirements
  • Installation


Requirements

If you want to build ktaglib you need at least taglib 1.5 installed. To obtain the taglib see the » taglib project page. Windows DLL's are build static against taglib, therefore there is no need to have taglib installed.


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

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.

KTaglib uses class constants. Most of the constants are mappings to the according Taglib enums and constants.

KTaglib_MPEG_Header::Version1 (integer)
ID3 version is 1.0
KTaglib_MPEG_Header::Version2 (integer)
ID3 version is 2.0
KTaglib_MPEG_Header::Version2_5 (integer)
ID3 version is 2.5
KTaglib_ID3v2_AttachedPictureFrame::Other (integer)
Picture type Other
KTaglib_ID3v2_AttachedPictureFrame::FileIcon (integer)
Picture type FileIcon
KTaglib_ID3v2_AttachedPictureFrame::OtherFileIcon (integer)
Picture type OtherFileIcon
KTaglib_ID3v2_AttachedPictureFrame::FrontCover (integer)
Picture type FrontCover
KTaglib_ID3v2_AttachedPictureFrame::BackCover (integer)
Picture type BackCover
KTaglib_ID3v2_AttachedPictureFrame::LeafletPage (integer)
Picture type LeafletPage
KTaglib_ID3v2_AttachedPictureFrame::Media (integer)
Picture type Media
KTaglib_ID3v2_AttachedPictureFrame::LeadArtist (integer)
Picture type LeadArtist
KTaglib_ID3v2_AttachedPictureFrame::Artist (integer)
Picture type Artist
KTaglib_ID3v2_AttachedPictureFrame::Conductor (integer)
Picture type Conductor
KTaglib_ID3v2_AttachedPictureFrame::Band (integer)
Picture type Band
KTaglib_ID3v2_AttachedPictureFrame::Composer (integer)
Picture type Composer
KTaglib_ID3v2_AttachedPictureFrame::Lyricist (integer)
Picture type Lyricist
KTaglib_ID3v2_AttachedPictureFrame::RecordingLocation (integer)
Picture type RecordingLocation
KTaglib_ID3v2_AttachedPictureFrame::DuringRecording (integer)
Picture type DuringRecording
KTaglib_ID3v2_AttachedPictureFrame::DuringPerformance (integer)
Picture type DuringPerformance
KTaglib_ID3v2_AttachedPictureFrame::MovieScreenCapture (integer)
Picture type MovieScreenCapture
KTaglib_ID3v2_AttachedPictureFrame::ColouredFish (integer)
Picture type ColouredFish
KTaglib_ID3v2_AttachedPictureFrame::Illustration (integer)
Picture type Illustration
KTaglib_ID3v2_AttachedPictureFrame::BandLogo (integer)
Picture type BandLogo


The KTaglib_MPEG_File class

(0.0.1)

Introduction

Represents an MPEG file. MPEG files can have ID3v1, ID3v2 tags and audio properties.

Class synopsis

KTaglib_MPEG_File {
/* Methods */
public getAudioProperties ( void ) : KTaglib_MPEG_File
public getID3v1Tag ([ bool $create = FALSE ] ) : KTaglib_ID3v1_Tag
public getID3v2Tag ([ bool $create = FALSE ] ) : KTaglib_ID3v2_Tag
}

Table of Contents

  • KTaglib_MPEG_File::__construct — Opens a new file
  • KTaglib_MPEG_File::getAudioProperties — Returns an object that provides access to the audio properties
  • KTaglib_MPEG_File::getID3v1Tag — Returns an object representing an ID3v1 tag
  • KTaglib_MPEG_File::getID3v2Tag — Returns a ID3v2 object


Opens a new file

  • « KTaglib_MPEG_File
  • KTaglib_MPEG_File::getAudioProperties »
  • PHP Manual
  • KTaglib_MPEG_File
  • Opens a new file

KTaglib_MPEG_File::__construct

(0.0.1)

KTaglib_MPEG_File::__construct — Opens a new file

Description

public KTaglib_MPEG_File::__construct ( string $filename )

Opens a new MPEG file.

Parameters

filename

The file to read

Examples

Example #1 Opens a new MP3 file and read the title

<?php
$mpeg = new KTaglib_MPEG_File('example.mp3');
echo $mpeg->getID3v1Tag()->getTitle();
?>


Returns an object that provides access to the audio properties

  • « KTaglib_MPEG_File::__construct
  • KTaglib_MPEG_File::getID3v1Tag »
  • PHP Manual
  • KTaglib_MPEG_File
  • Returns an object that provides access to the audio properties

KTaglib_MPEG_File::getAudioProperties

(0.0.1)

KTaglib_MPEG_File::getAudioProperties — Returns an object that provides access to the audio properties

Description

public KTaglib_MPEG_File::getAudioProperties ( void ) : KTaglib_MPEG_File

Returns an object that provides access to the audio properties of the mpeg file.

Return Values

Returns an KTaglib_MPEG_AudioProperties object or false.


Returns an object representing an ID3v1 tag

  • « KTaglib_MPEG_File::getAudioProperties
  • KTaglib_MPEG_File::getID3v2Tag »
  • PHP Manual
  • KTaglib_MPEG_File
  • Returns an object representing an ID3v1 tag

KTaglib_MPEG_File::getID3v1Tag

(0.0.1)

KTaglib_MPEG_File::getID3v1Tag — Returns an object representing an ID3v1 tag

Description

public KTaglib_MPEG_File::getID3v1Tag ([ bool $create = FALSE ] ) : KTaglib_ID3v1_Tag

Returns an object that represents an ID3v1 tag, which can be used to get information about the ID3v1 tag.

Return Values

Returns an KTaglib_MPEG_ID3v1Tag object or false if there is no ID3v1 tag.


Returns a ID3v2 object

  • « KTaglib_MPEG_File::getID3v1Tag
  • KTaglib_MPEG_AudioProperties »
  • PHP Manual
  • KTaglib_MPEG_File
  • Returns a ID3v2 object

KTaglib_MPEG_File::getID3v2Tag

(0.0.1)

KTaglib_MPEG_File::getID3v2Tag — Returns a ID3v2 object

Description

public KTaglib_MPEG_File::getID3v2Tag ([ bool $create = FALSE ] ) : KTaglib_ID3v2_Tag

Returns a ID3v2 object for the mpeg file. If no ID3v2 Tag is present, an KTaglib_TagNotFoundException is thrown.

Return Values

Returns the KTaglib_ID3v2_Tag object of the MPEG file or false if there is no ID3v2 tag


The KTaglib_MPEG_AudioProperties class

(0.0.1)

Introduction

Represents the audio properties of a MPEG file, like length, bitrate or samplerate.

Class synopsis

KTaglib_MPEG_AudioProperties {
/* Methods */
public KTaglib_MPEG_AudioProperties::getBitrate ( void ) : int
public KTaglib_MPEG_AudioProperties::getChannels ( void ) : int
public KTaglib_MPEG_AudioProperties::getLayer ( void ) : int
public KTaglib_MPEG_AudioProperties::getLength ( void ) : int
public KTaglib_MPEG_AudioProperties::getSampleBitrate ( void ) : int
public KTaglib_MPEG_AudioProperties::getVersion ( void ) : int
public KTaglib_MPEG_AudioProperties::isCopyrighted ( void ) : bool
public KTaglib_MPEG_AudioProperties::isOriginal ( void ) : bool
public KTaglib_MPEG_AudioProperties::isProtectionEnabled ( void ) : bool
}

Table of Contents

  • KTaglib_MPEG_AudioProperties::getBitrate — Returns the bitrate of the MPEG file
  • KTaglib_MPEG_AudioProperties::getChannels — Returns the amount of channels of a MPEG file
  • KTaglib_MPEG_AudioProperties::getLayer — Returns the layer of a MPEG file
  • KTaglib_MPEG_AudioProperties::getLength — Returns the length of a MPEG file
  • KTaglib_MPEG_AudioProperties::getSampleBitrate — Returns the sample bitrate of a MPEG file
  • KTaglib_MPEG_AudioProperties::getVersion — Returns the version of a MPEG file
  • KTaglib_MPEG_AudioProperties::isCopyrighted — Returns the copyright status of an MPEG file
  • KTaglib_MPEG_AudioProperties::isOriginal — Returns if the file is marked as the original file
  • KTaglib_MPEG_AudioProperties::isProtectionEnabled — Returns if protection mechanisms of an MPEG file are enabled


Returns the bitrate of the MPEG file

  • « KTaglib_MPEG_AudioProperties
  • KTaglib_MPEG_AudioProperties::getChannels »
  • PHP Manual
  • KTaglib_MPEG_AudioProperties
  • Returns the bitrate of the MPEG file

KTaglib_MPEG_AudioProperties::getBitrate

(0.0.1)

KTaglib_MPEG_AudioProperties::getBitrate — Returns the bitrate of the MPEG file

Description

public KTaglib_MPEG_AudioProperties::getBitrate ( void ) : int

Returns the bitrate of the MPEG file

Return Values

Returns the bitrate as an integer


Returns the amount of channels of a MPEG file

  • « KTaglib_MPEG_AudioProperties::getBitrate
  • KTaglib_MPEG_AudioProperties::getLayer »
  • PHP Manual
  • KTaglib_MPEG_AudioProperties
  • Returns the amount of channels of a MPEG file

KTaglib_MPEG_AudioProperties::getChannels

(0.0.1)

KTaglib_MPEG_AudioProperties::getChannels — Returns the amount of channels of a MPEG file

Description

public KTaglib_MPEG_AudioProperties::getChannels ( void ) : int

Returns the amount of channels of the MPEG file

Return Values

Returns the channel count as an integer


Returns the layer of a MPEG file

  • « KTaglib_MPEG_AudioProperties::getChannels
  • KTaglib_MPEG_AudioProperties::getLength »
  • PHP Manual
  • KTaglib_MPEG_AudioProperties
  • Returns the layer of a MPEG file

KTaglib_MPEG_AudioProperties::getLayer

(0.0.1)

KTaglib_MPEG_AudioProperties::getLayer — Returns the layer of a MPEG file

Description

public KTaglib_MPEG_AudioProperties::getLayer ( void ) : int

Returns the layer of the MPEG file (usually 3 for MP3).

Return Values

Returns the layer as an integer


Returns the length of a MPEG file

  • « KTaglib_MPEG_AudioProperties::getLayer
  • KTaglib_MPEG_AudioProperties::getSampleBitrate »
  • PHP Manual
  • KTaglib_MPEG_AudioProperties
  • Returns the length of a MPEG file

KTaglib_MPEG_AudioProperties::getLength

(0.0.1)

KTaglib_MPEG_AudioProperties::getLength — Returns the length of a MPEG file

Description

public KTaglib_MPEG_AudioProperties::getLength ( void ) : int

Returns the length of the MPEG file

Return Values

Returns the length as an integer


Returns the sample bitrate of a MPEG file

  • « KTaglib_MPEG_AudioProperties::getLength
  • KTaglib_MPEG_AudioProperties::getVersion »
  • PHP Manual
  • KTaglib_MPEG_AudioProperties
  • Returns the sample bitrate of a MPEG file

KTaglib_MPEG_AudioProperties::getSampleBitrate

(0.0.1)

KTaglib_MPEG_AudioProperties::getSampleBitrate — Returns the sample bitrate of a MPEG file

Description

public KTaglib_MPEG_AudioProperties::getSampleBitrate ( void ) : int

Returns the sample bitrate of the MPEG file

Return Values

Returns the sample bitrate as an integer


Returns the version of a MPEG file

  • « KTaglib_MPEG_AudioProperties::getSampleBitrate
  • KTaglib_MPEG_AudioProperties::isCopyrighted »
  • PHP Manual
  • KTaglib_MPEG_AudioProperties
  • Returns the version of a MPEG file

KTaglib_MPEG_AudioProperties::getVersion

(0.0.1)

KTaglib_MPEG_AudioProperties::getVersion — Returns the version of a MPEG file

Description

public KTaglib_MPEG_AudioProperties::getVersion ( void ) : int

Returns the version of the MPEG file header. The possible versions are defined in Tag_MPEG_Header (Version1, Version2, Version2.5).

Return Values

Returns the version


Returns the copyright status of an MPEG file

  • « KTaglib_MPEG_AudioProperties::getVersion
  • KTaglib_MPEG_AudioProperties::isOriginal »
  • PHP Manual
  • KTaglib_MPEG_AudioProperties
  • Returns the copyright status of an MPEG file

KTaglib_MPEG_AudioProperties::isCopyrighted

(0.0.1)

KTaglib_MPEG_AudioProperties::isCopyrighted — Returns the copyright status of an MPEG file

Description

public KTaglib_MPEG_AudioProperties::isCopyrighted ( void ) : bool

Returns true if the MPEG file is copyrighted

Return Values

Returns true if the MPEG file is copyrighted


Returns if the file is marked as the original file

  • « KTaglib_MPEG_AudioProperties::isCopyrighted
  • KTaglib_MPEG_AudioProperties::isProtectionEnabled »
  • PHP Manual
  • KTaglib_MPEG_AudioProperties
  • Returns if the file is marked as the original file

KTaglib_MPEG_AudioProperties::isOriginal

(0.0.1)

KTaglib_MPEG_AudioProperties::isOriginal — Returns if the file is marked as the original file

Description

public KTaglib_MPEG_AudioProperties::isOriginal ( void ) : bool

Returns true if the file is marked as the original file

Return Values

Returns true if the file is marked as the original file


Returns if protection mechanisms of an MPEG file are enabled

  • « KTaglib_MPEG_AudioProperties::isOriginal
  • KTaglib_Tag »
  • PHP Manual
  • KTaglib_MPEG_AudioProperties
  • Returns if protection mechanisms of an MPEG file are enabled

KTaglib_MPEG_AudioProperties::isProtectionEnabled

(0.0.1)

KTaglib_MPEG_AudioProperties::isProtectionEnabled — Returns if protection mechanisms of an MPEG file are enabled

Description

public KTaglib_MPEG_AudioProperties::isProtectionEnabled ( void ) : bool

Returns true if protection mechanisms (like DRM) are enabled for this file

Return Values

Returns true if protection mechanisms (like DRM) are enabled for this file


The KTaglib_Tag class

(0.0.1)

Introduction

Base class for ID3v1 or ID3v2 tags

Class synopsis

KTaglib_Tag {
/* Methods */
public getAlbum ( void ) : string
public getArtist ( void ) : string
public getComment ( void ) : string
public getGenre ( void ) : string
public getTitle ( void ) : string
public getTrack ( void ) : int
public getYear ( void ) : int
public isEmpty ( void ) : bool
}

Table of Contents

  • KTaglib_Tag::getAlbum — Returns the album string from a ID3 tag
  • KTaglib_Tag::getArtist — Returns the artist string from a ID3 tag
  • KTaglib_Tag::getComment — Returns the comment from a ID3 tag
  • KTaglib_Tag::getGenre — Returns the genre from a ID3 tag
  • KTaglib_Tag::getTitle — Returns the title string from a ID3 tag
  • KTaglib_Tag::getTrack — Returns the track number from a ID3 tag
  • KTaglib_Tag::getYear — Returns the year from a ID3 tag
  • KTaglib_Tag::isEmpty — Returns true if the tag is empty


Returns the album string from a ID3 tag

  • « KTaglib_Tag
  • KTaglib_Tag::getArtist »
  • PHP Manual
  • KTaglib_Tag
  • Returns the album string from a ID3 tag

KTaglib_Tag::getAlbum

(0.0.1)

KTaglib_Tag::getAlbum — Returns the album string from a ID3 tag

Description

public KTaglib_Tag::getAlbum ( void ) : string

Returns the album string of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Return Values

Returns the album string


Returns the artist string from a ID3 tag

  • « KTaglib_Tag::getAlbum
  • KTaglib_Tag::getComment »
  • PHP Manual
  • KTaglib_Tag
  • Returns the artist string from a ID3 tag

KTaglib_Tag::getArtist

(0.0.1)

KTaglib_Tag::getArtist — Returns the artist string from a ID3 tag

Description

public KTaglib_Tag::getArtist ( void ) : string

Returns the artist string of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Return Values

Returns the artist string


Returns the comment from a ID3 tag

  • « KTaglib_Tag::getArtist
  • KTaglib_Tag::getGenre »
  • PHP Manual
  • KTaglib_Tag
  • Returns the comment from a ID3 tag

KTaglib_Tag::getComment

(0.0.1)

KTaglib_Tag::getComment — Returns the comment from a ID3 tag

Description

public KTaglib_Tag::getComment ( void ) : string

Returns the comment of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Return Values

Returns the comment string


Returns the genre from a ID3 tag

  • « KTaglib_Tag::getComment
  • KTaglib_Tag::getTitle »
  • PHP Manual
  • KTaglib_Tag
  • Returns the genre from a ID3 tag

KTaglib_Tag::getGenre

(0.0.1)

KTaglib_Tag::getGenre — Returns the genre from a ID3 tag

Description

public KTaglib_Tag::getGenre ( void ) : string

Returns the genre of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Return Values

Returns the genre string


Returns the title string from a ID3 tag

  • « KTaglib_Tag::getGenre
  • KTaglib_Tag::getTrack »
  • PHP Manual
  • KTaglib_Tag
  • Returns the title string from a ID3 tag

KTaglib_Tag::getTitle

(0.0.1)

KTaglib_Tag::getTitle — Returns the title string from a ID3 tag

Description

public KTaglib_Tag::getTitle ( void ) : string

Returns the title string of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Return Values

Returns the title string


Returns the track number from a ID3 tag

  • « KTaglib_Tag::getTitle
  • KTaglib_Tag::getYear »
  • PHP Manual
  • KTaglib_Tag
  • Returns the track number from a ID3 tag

KTaglib_Tag::getTrack

(0.0.1)

KTaglib_Tag::getTrack — Returns the track number from a ID3 tag

Description

public KTaglib_Tag::getTrack ( void ) : int

Returns the track number of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Return Values

Returns the track number as an integer


Returns the year from a ID3 tag

  • « KTaglib_Tag::getTrack
  • KTaglib_Tag::isEmpty »
  • PHP Manual
  • KTaglib_Tag
  • Returns the year from a ID3 tag

KTaglib_Tag::getYear

(0.0.1)

KTaglib_Tag::getYear — Returns the year from a ID3 tag

Description

public KTaglib_Tag::getYear ( void ) : int

Returns the year of an ID3 tag. This method is implemented in ID3v1 and ID3v2 tags.

Return Values

Returns the year as an integer


Returns true if the tag is empty

  • « KTaglib_Tag::getYear
  • KTaglib_ID3v2_Tag »
  • PHP Manual
  • KTaglib_Tag
  • Returns true if the tag is empty

KTaglib_Tag::isEmpty

(0.0.1)

KTaglib_Tag::isEmpty — Returns true if the tag is empty

Description

public KTaglib_Tag::isEmpty ( void ) : bool

Returns true if the tag exists, but is empty. This method is implemented in ID3v1 and ID3v2 tags.

Return Values

Returns true if the tag is empty, otherwise false.


The KTaglib_ID3v2_Tag class

(0.0.1)

Introduction

Represents and ID3v2 tag. It provides a list of ID3v2 frames and can be used to add and remove additional frames.

Class synopsis

extends KTaglib_Tag {
/* Methods */
public addFrame ( KTaglib_ID3v2_Frame $frame ) : bool
public getFrameList ( void ) : array
/* Inherited methods */
public KTaglib_Tag::getAlbum ( void ) : string
public KTaglib_Tag::getArtist ( void ) : string
public KTaglib_Tag::getComment ( void ) : string
public KTaglib_Tag::getGenre ( void ) : string
public KTaglib_Tag::getTitle ( void ) : string
public KTaglib_Tag::getTrack ( void ) : int
public KTaglib_Tag::getYear ( void ) : int
public KTaglib_Tag::isEmpty ( void ) : bool
}

Table of Contents

  • KTaglib_ID3v2_Tag::addFrame — Add a frame to the ID3v2 tag
  • KTaglib_ID3v2_Tag::getFrameList — Returns an array of ID3v2 frames, associated with the ID3v2 tag


Add a frame to the ID3v2 tag

  • « KTaglib_ID3v2_Tag
  • KTaglib_ID3v2_Tag::getFrameList »
  • PHP Manual
  • KTaglib_ID3v2_Tag
  • Add a frame to the ID3v2 tag

KTaglib_ID3v2_Tag::addFrame

(0.0.1)

KTaglib_ID3v2_Tag::addFrame — Add a frame to the ID3v2 tag

Description

public KTaglib_ID3v2_Tag::addFrame ( KTaglib_ID3v2_Frame $frame ) : bool

Adds a frame to the ID3v2 tag. The frame must be a valid KTaglib_ID3v2_Frame object. To save the tag, the save function needs to be invoked.

Return Values

Returns true on success, otherwise false.


Returns an array of ID3v2 frames, associated with the ID3v2 tag

  • « KTaglib_ID3v2_Tag::addFrame
  • KTaglib_ID3v2_Frame »
  • PHP Manual
  • KTaglib_ID3v2_Tag
  • Returns an array of ID3v2 frames, associated with the ID3v2 tag

KTaglib_ID3v2_Tag::getFrameList

(0.0.1)

KTaglib_ID3v2_Tag::getFrameList — Returns an array of ID3v2 frames, associated with the ID3v2 tag

Description

public KTaglib_ID3v2_Tag::getFrameList ( void ) : array

Returns an array of ID3v2 frames, associated with the ID3v2 tag.

Return Values

Return an array of KTaglib_ID3v2_Frame objects


The KTaglib_ID3v2_Frame class

(0.0.1)

Introduction

The base class for ID3v2 frames. ID3v2 tags are separated in various specialized frames. Some frames can exists multiple times.

Class synopsis

extends KTaglib_Tag {
/* Methods */
public getSize ( void ) : int
public __toString ( void ) : string
/* Inherited methods */
public KTaglib_Tag::getAlbum ( void ) : string
public KTaglib_Tag::getArtist ( void ) : string
public KTaglib_Tag::getComment ( void ) : string
public KTaglib_Tag::getGenre ( void ) : string
public KTaglib_Tag::getTitle ( void ) : string
public KTaglib_Tag::getTrack ( void ) : int
public KTaglib_Tag::getYear ( void ) : int
public KTaglib_Tag::isEmpty ( void ) : bool
}

Table of Contents

  • KTaglib_ID3v2_Frame::getSize — Returns the size of the frame in bytes
  • KTaglib_ID3v2_Frame::__toString — Returns a string representation of the frame


Returns the size of the frame in bytes

  • « KTaglib_ID3v2_Frame
  • KTaglib_ID3v2_Frame::__toString »
  • PHP Manual
  • KTaglib_ID3v2_Frame
  • Returns the size of the frame in bytes

KTaglib_ID3v2_Frame::getSize

(0.0.1)

KTaglib_ID3v2_Frame::getSize — Returns the size of the frame in bytes

Description

public KTaglib_ID3v2_Frame::getSize ( void ) : int

Returns the size of the frame in bytes. Please refer to id3.org to see what ID3v2 frames are and how they are defined.

Return Values

Returns the size of the frame in bytes


Returns a string representation of the frame

  • « KTaglib_ID3v2_Frame::getSize
  • KTaglib_ID3v2_AttachedPictureFrame »
  • PHP Manual
  • KTaglib_ID3v2_Frame
  • Returns a string representation of the frame

KTaglib_ID3v2_Frame::__toString

(0.0.1)

KTaglib_ID3v2_Frame::__toString — Returns a string representation of the frame

Description

public KTaglib_ID3v2_Frame::__toString ( void ) : string

Returns a string representation of the frame. This might be just the frame id, but might contain more information. Please see the ktaglib documentation for more information

Return Values

Returns a string representation of the frame.


The KTaglib_ID3v2_AttachedPictureFrame class

(0.0.1)

Introduction

Represents an ID3v2 frame that can hold a picture.

Class synopsis

extends KTaglib_ID3v2_Frame {
/* Methods */
public getDescription ( void ) : string
public getMimeType ( void ) : string
public getType ( void ) : int
public savePicture ( string $filename ) : bool
public getMimeType ( string $type ) : string
public setPicture ( string $filename ) : void
public setType ( int $type ) : void
/* Inherited methods */
public KTaglib_ID3v2_Frame::getSize ( void ) : int
public KTaglib_ID3v2_Frame::__toString ( void ) : string
public KTaglib_Tag::getAlbum ( void ) : string
public KTaglib_Tag::getArtist ( void ) : string
public KTaglib_Tag::getComment ( void ) : string
public KTaglib_Tag::getGenre ( void ) : string
public KTaglib_Tag::getTitle ( void ) : string
public KTaglib_Tag::getTrack ( void ) : int
public KTaglib_Tag::getYear ( void ) : int
public KTaglib_Tag::isEmpty ( void ) : bool
}

Table of Contents

  • KTaglib_ID3v2_AttachedPictureFrame::getDescription — Returns a description for the picture in a picture frame
  • KTaglib_ID3v2_AttachedPictureFrame::getMimeType — Returns the mime type of the picture
  • KTaglib_ID3v2_AttachedPictureFrame::getType — Returns the type of the image
  • KTaglib_ID3v2_AttachedPictureFrame::savePicture — Saves the picture to a file
  • KTaglib_ID3v2_AttachedPictureFrame::setMimeType — Set's the mime type of the picture
  • KTaglib_ID3v2_AttachedPictureFrame::setPicture — Sets the frame picture to the given image
  • KTaglib_ID3v2_AttachedPictureFrame::setType — Set the type of the image


Returns a description for the picture in a picture frame

  • « KTaglib_ID3v2_AttachedPictureFrame
  • KTaglib_ID3v2_AttachedPictureFrame::getMimeType »
  • PHP Manual
  • KTaglib_ID3v2_AttachedPictureFrame
  • Returns a description for the picture in a picture frame

KTaglib_ID3v2_AttachedPictureFrame::getDescription

(0.0.1)

KTaglib_ID3v2_AttachedPictureFrame::getDescription — Returns a description for the picture in a picture frame

Description

public KTaglib_ID3v2_AttachedPictureFrame::getDescription ( void ) : string

Returns the attached description for a picture frame in an ID3v2.x frame.

Return Values

Returns a description for the picture in a picture frame


Returns the mime type of the picture

  • « KTaglib_ID3v2_AttachedPictureFrame::getDescription
  • KTaglib_ID3v2_AttachedPictureFrame::getType »
  • PHP Manual
  • KTaglib_ID3v2_AttachedPictureFrame
  • Returns the mime type of the picture

KTaglib_ID3v2_AttachedPictureFrame::getMimeType

(0.2.0)

KTaglib_ID3v2_AttachedPictureFrame::getMimeType — Returns the mime type of the picture

Description

public KTaglib_ID3v2_AttachedPictureFrame::getMimeType ( void ) : string

Returns the mime type of the image represented by the attached picture frame.

Please notice that this method might return different types. While ID3v2.2 have a mime type that doesn't start with "image/", ID3v2.3 and v2.4 usually start with "image/". Therefore the method might return "image/png" for IDv2.3 frames and just "PNG" for ID3v2.2 frames.

Notice that even the frame is an attached picture, the mime type might not be set and therefore an empty string might be returned.

Return Values

Returns the mime type of the image represented by the attached picture frame.


Returns the type of the image

  • « KTaglib_ID3v2_AttachedPictureFrame::getMimeType
  • KTaglib_ID3v2_AttachedPictureFrame::savePicture »
  • PHP Manual
  • KTaglib_ID3v2_AttachedPictureFrame
  • Returns the type of the image

KTaglib_ID3v2_AttachedPictureFrame::getType

(0.2.0)

KTaglib_ID3v2_AttachedPictureFrame::getType — Returns the type of the image

Description

public KTaglib_ID3v2_AttachedPictureFrame::getType ( void ) : int

Returns the type of the image.

The ID3v2 specification allows an AttachedPictureFrame to set the type of an image. This can be e.g. FrontCover or FileIcon. Please refer to the KTaglib_ID3v2_AttachedPictureFrame class description for a list of available types.

Return Values

Returns the integer representation of the type.


Saves the picture to a file

  • « KTaglib_ID3v2_AttachedPictureFrame::getType
  • KTaglib_ID3v2_AttachedPictureFrame::setMimeType »
  • PHP Manual
  • KTaglib_ID3v2_AttachedPictureFrame
  • Saves the picture to a file

KTaglib_ID3v2_AttachedPictureFrame::savePicture

(0.0.1)

KTaglib_ID3v2_AttachedPictureFrame::savePicture — Saves the picture to a file

Description

public KTaglib_ID3v2_AttachedPictureFrame::savePicture ( string $filename ) : bool

Saves the attached picture to the given filename.

Return Values

Returns true on success, otherwise false


Set's the mime type of the picture

  • « KTaglib_ID3v2_AttachedPictureFrame::savePicture
  • KTaglib_ID3v2_AttachedPictureFrame::setPicture »
  • PHP Manual
  • KTaglib_ID3v2_AttachedPictureFrame
  • Set's the mime type of the picture

KTaglib_ID3v2_AttachedPictureFrame::setMimeType

(0.2.0)

KTaglib_ID3v2_AttachedPictureFrame::setMimeType — Set's the mime type of the picture

Description

public KTaglib_ID3v2_AttachedPictureFrame::getMimeType ( string $type ) : string

Sets the mime type of the image. This should in most cases be "image/png" or "image/jpeg".


Sets the frame picture to the given image

  • « KTaglib_ID3v2_AttachedPictureFrame::setMimeType
  • KTaglib_ID3v2_AttachedPictureFrame::setType »
  • PHP Manual
  • KTaglib_ID3v2_AttachedPictureFrame
  • Sets the frame picture to the given image

KTaglib_ID3v2_AttachedPictureFrame::setPicture

(0.0.1)

KTaglib_ID3v2_AttachedPictureFrame::setPicture — Sets the frame picture to the given image

Description

public KTaglib_ID3v2_AttachedPictureFrame::setPicture ( string $filename ) : void

Sets the picture to the give image. The image is loaded from the given filename. Please note that the picture is not saved unless you call the save method of the corresponding file object.

Return Values

Returns true on success, otherwise false


Set the type of the image

  • « KTaglib_ID3v2_AttachedPictureFrame::setPicture
  • oggvorbis »
  • PHP Manual
  • KTaglib_ID3v2_AttachedPictureFrame
  • Set the type of the image

KTaglib_ID3v2_AttachedPictureFrame::setType

(0.2.0)

KTaglib_ID3v2_AttachedPictureFrame::setType — Set the type of the image

Description

public KTaglib_ID3v2_AttachedPictureFrame::setType ( int $type ) : void

Sets the type of the image. This can be e.g. FrontCover or FileIcon. Please refer to the KTaglib_ID3v2_AttachedPictureFrame class description for a list of available types and their constant mappings.


OGG/Vorbis

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Context options
  • Examples
    • Examples on using the ogg:// wrapper.


Introduction

The OGG/Vorbis file format, as defined by » http://www.vorbis.com/, is a scheme for compressing audio streams by multiple factors with a minimum of quality loss. This extension adds Ogg Vorbis support to PHP's URL Wrappers. When used in read mode, compressed OGG/Vorbis data is expanded to raw PCM audio in one of six PCM encoding formats listed in the predefined constants section.


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

This extension requires PHP >= 4.3.0, » libogg >= 1.0, and » libvorbis >= 1.0.


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/oggvorbis


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.

OGG/Vorbis supports PCM encodings in the following formats
Constant | Definition
OGGVORBIS_PCM_U8 | Unsigned 8-bit PCM.
OGGVORBIS_PCM_S8 | Signed 8-bit PCM.
OGGVORBIS_PCM_U16_LE | Unsigned 16-bit PCM. Little Endian byte order.
OGGVORBIS_PCM_U16_BE | Unsigned 16-bit PCM. Big Endian byte order.
OGGVORBIS_PCM_S16_LE | Signed 16-bit PCM. Little Endian byte order.
OGGVORBIS_PCM_S16_BE | Signed 16-bit PCM. Big Endian byte order.


Context options

OGG/Vorbis tuning options
Option | Definition | Relevance | Default
pcm_mode | PCM byte encoding used. See constants below. | Read / Write | OGGVORBIS_PCM_S16_LE
rate | PCM Sampling rate. Measured in Hz. | Write only | 44100
bitrate | Vorbis Average Bitrate Encoding / Variable Bitrate Encoding. Measured in bps (ABR) or Quality level (VBR: 0.0 to 1.0). 128000 ABR is rough equal to 0.4 VBR. | Write only | 128000
channels | Number of PCM channels. 1 == Mono, 2 == Stereo. | Write only | 2
serialno | Serial Number of stream within file. Must be unique within file. Because of the potential to select a duplicate serial number within a chained file, make efforts to manually assign unique numbers when encoding. | Write only | Random
comments | Associative array of file comments. Will be translated to strtoupper($name) . "=$value". Note: This context option is not available in oggvorbis-0.1 | Write only | array('ENCODER' => 'PHP/OggVorbis, http://pear.php.net/oggvorbis')


  • « Context options
  • Examples on using the ogg:// wrapper. »
  • PHP Manual
  • oggvorbis
  • Examples

Examples

Table of Contents

  • Examples on using the ogg:// wrapper.


Examples on using the ogg:// wrapper.

Example #1 Reading an OGG/Vorbis file

<?php
dl("oggvorbis.so");

/* By default, ogg:// will decode to Signed 16-bit Little Endian */
$fp = fopen('ogg://myaudio.ogg', 'r');

/* Collect some information about the file. */
$metadata = stream_get_meta_data($fp);

/* Inspect the first song (usually the only song,
   but OGG/Vorbis files may be chained) */
$songdata = $metadata['wrapper_data'][0];

echo "OGG/Vorbis file encoded by: {$songdata['vendor']}\n.";
echo "  {$songdata['channels']} channels of {$songdata['rate']}Hz sampling encoded at {$songdata['bitrate_nominal']}bps.\n";
foreach($songdata['comments'] as $comment) {
    echo "  $comment\n";
}

while ($audio_data = fread($fp, 8192)) {
  /* Do something with the PCM audio we're extracting from the OGG.
     Copying to /dev/dsp is a good target on linux systems,
     just remember to setup the device for your sampling mode first. */
}

fclose($fp);

?>

Example #2 Encode an audio file to OGG/Vorbis

<?php
dl('oggvorbis.so');

$context = stream_context_create(array('ogg'=>array(
             'pcm_mode' => OGGVORBIS_PCM_S8,  /* Signed 8bit audio */
             'rate' => 44100,                 /* 44kHz CD quality */
             'bitrate' => 0.5,                /* Midquality VBR */
             'channels' => 1,                 /* Mono */
             'serialno' => 12345)));          /* Unique within our stream */

/* Open file for appending.  This will "chain" a second OGG stream at the end of the first. */
$ogg = fopen('ogg://mysong.ogg', 'a', false, $context);

$pcm = fopen('mysample.pcm', 'r');

/* Compress the raw PCM audio from mysample.pcm into mysong.ogg */
stream_copy_to_stream($pcm, $ogg);

fclose($pcm);
fclose($ogg);
?>


OpenAL Audio Bindings

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • 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
  • Installing/Configuring »
  • PHP Manual
  • OpenAL
  • Introduction

Introduction

Platform independent audio bindings. Requires the » OpenAL library.


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 (integer)
Context Attribute
ALC_REFRESH (integer)
Context Attribute
ALC_SYNC (integer)
Context Attribute
AL_FREQUENCY (integer)
Buffer Setting
AL_BITS (integer)
Buffer Setting
AL_CHANNELS (integer)
Buffer Setting
AL_SIZE (integer)
Buffer Setting
AL_BUFFER (integer)
Source/Listener Setting (Integer)
AL_SOURCE_RELATIVE (integer)
Source/Listener Setting (Integer)
AL_SOURCE_STATE (integer)
Source/Listener Setting (Integer)
AL_PITCH (integer)
Source/Listener Setting (Float)
AL_GAIN (integer)
Source/Listener Setting (Float)
AL_MIN_GAIN (integer)
Source/Listener Setting (Float)
AL_MAX_GAIN (integer)
Source/Listener Setting (Float)
AL_MAX_DISTANCE (integer)
Source/Listener Setting (Float)
AL_ROLLOFF_FACTOR (integer)
Source/Listener Setting (Float)
AL_CONE_OUTER_GAIN (integer)
Source/Listener Setting (Float)
AL_CONE_INNER_ANGLE (integer)
Source/Listener Setting (Float)
AL_CONE_OUTER_ANGLE (integer)
Source/Listener Setting (Float)
AL_REFERENCE_DISTANCE (integer)
Source/Listener Setting (Float)
AL_POSITION (integer)
Source/Listener Setting (Float Vector)
AL_VELOCITY (integer)
Source/Listener Setting (Float Vector)
AL_DIRECTION (integer)
Source/Listener Setting (Float Vector)
AL_ORIENTATION (integer)
Source/Listener Setting (Float Vector)
AL_FORMAT_MONO8 (integer)
PCM Format
AL_FORMAT_MONO16 (integer)
PCM Format
AL_FORMAT_STEREO8 (integer)
PCM Format
AL_FORMAT_STEREO16 (integer)
PCM Format
AL_INITIAL (integer)
Source State
AL_PLAYING (integer)
Source State
AL_PAUSED (integer)
Source State
AL_STOPPED (integer)
Source State
AL_LOOPING (integer)
Source State
AL_TRUE (integer)
Boolean value recognized by OpenAL
AL_FALSE (integer)
Boolean value recognized by OpenAL


OpenAL Functions

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


Generate OpenAL buffer

  • « OpenAL Functions
  • openal_buffer_data »
  • PHP Manual
  • OpenAL Functions
  • Generate OpenAL buffer

openal_buffer_create

(PECL openal >= 0.1.0)

openal_buffer_create — Generate OpenAL buffer

Description

openal_buffer_create ( void ) : resource

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


Load a buffer with data

  • « openal_buffer_create
  • openal_buffer_destroy »
  • PHP Manual
  • OpenAL Functions
  • 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


Destroys an OpenAL buffer

  • « openal_buffer_data
  • openal_buffer_get »
  • PHP Manual
  • OpenAL Functions
  • Destroys an OpenAL buffer

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


Retrieve an OpenAL buffer property

  • « openal_buffer_destroy
  • openal_buffer_loadwav »
  • PHP Manual
  • OpenAL Functions
  • Retrieve an OpenAL buffer property

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

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


Load a .wav file into a buffer

  • « openal_buffer_get
  • openal_context_create »
  • PHP Manual
  • OpenAL Functions
  • Load a .wav file into a 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


Create an audio processing context

  • « openal_buffer_loadwav
  • openal_context_current »
  • PHP Manual
  • OpenAL Functions
  • Create an audio processing context

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


Make the specified context current

  • « openal_context_create
  • openal_context_destroy »
  • PHP Manual
  • OpenAL Functions
  • Make the specified context current

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


Destroys a context

  • « openal_context_current
  • openal_context_process »
  • PHP Manual
  • OpenAL Functions
  • Destroys a 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


Process the specified context

  • « openal_context_destroy
  • openal_context_suspend »
  • PHP Manual
  • OpenAL Functions
  • Process the specified 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


Suspend the specified context

  • « openal_context_process
  • openal_device_close »
  • PHP Manual
  • OpenAL Functions
  • 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


Close an OpenAL device

  • « openal_context_suspend
  • openal_device_open »
  • PHP Manual
  • OpenAL Functions
  • Close an OpenAL device

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


Initialize the OpenAL audio layer

  • « openal_device_close
  • openal_listener_get »
  • PHP Manual
  • OpenAL Functions
  • 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


Retrieve a listener property

  • « openal_device_open
  • openal_listener_set »
  • PHP Manual
  • OpenAL Functions
  • Retrieve a listener property

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


Set a listener property

  • « openal_listener_get
  • openal_source_create »
  • PHP Manual
  • OpenAL Functions
  • 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


Generate a source resource

  • « openal_listener_set
  • openal_source_destroy »
  • PHP Manual
  • OpenAL Functions
  • Generate a source resource

openal_source_create

(PECL openal >= 0.1.0)

openal_source_create — Generate a source resource

Description

openal_source_create ( void ) : resource

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


Destroy a source resource

  • « openal_source_create
  • openal_source_get »
  • PHP Manual
  • OpenAL Functions
  • 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


Retrieve an OpenAL source property

  • « openal_source_destroy
  • openal_source_pause »
  • PHP Manual
  • OpenAL Functions
  • Retrieve an OpenAL source property

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


Pause the source

  • « openal_source_get
  • openal_source_play »
  • PHP Manual
  • OpenAL Functions
  • Pause 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


Start playing the source

  • « openal_source_pause
  • openal_source_rewind »
  • PHP Manual
  • OpenAL Functions
  • Start playing 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


Rewind the source

  • « openal_source_play
  • openal_source_set »
  • PHP Manual
  • OpenAL Functions
  • 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


Set source property

  • « openal_source_rewind
  • openal_source_stop »
  • PHP Manual
  • OpenAL Functions
  • Set source property

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


Stop playing the source

  • « openal_source_set
  • openal_stream »
  • PHP Manual
  • OpenAL Functions
  • Stop 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


Begin streaming on a source

  • « openal_source_stop
  • Authentication Services »
  • PHP Manual
  • OpenAL Functions
  • Begin streaming on a 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

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


Authentication Services

  • KADM5 — Kerberos V
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • KADM5 Functions
  • Radius
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Radius Functions


Kerberos V

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
    • Constants for Attribute Flags
    • Constants for Options
  • Examples
    • Basic usage
  • KADM5 Functions
    • kadm5_chpass_principal — Changes the principal's password
    • kadm5_create_principal — Creates a kerberos principal with the given parameters
    • kadm5_delete_principal — Deletes a kerberos principal
    • kadm5_destroy — Closes the connection to the admin server and releases all related resources
    • kadm5_flush — Flush all changes to the Kerberos database
    • kadm5_get_policies — Gets all policies from the Kerberos database
    • kadm5_get_principal — Gets the principal's entries from the Kerberos database
    • kadm5_get_principals — Gets all principals from the Kerberos database
    • kadm5_init_with_password — Opens a connection to the KADM5 library
    • kadm5_modify_principal — Modifies a kerberos principal with the given parameters


Introduction

These package allows you to access Kerberos V administration servers. You can create, modify, and delete Kerberos V principals and policies.

More information about Kerberos can be found at » http://web.mit.edu/kerberos/www/.

Documentation for Kerberos and KADM5 can be found at » http://web.mit.edu/kerberos/www/krb5-1.2/krb5-1.2.8/doc/admin_toc.html.


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

Note:

If this option is used without specifying the path to KADM5, PHP will use the built-in KADM5 client libraries. Users who run other applications that use KADM5 (for example, running PHP 4 and PHP 5 as concurrent apache modules, or auth-kadm5) should always specify the path to KADM5: --with-kadm5=/path/to/kadm5. This will force PHP to use the client libraries installed by KADM5, avoiding any conflicts.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.


  • « Runtime Configuration
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

This extension defines a KADM5 handle returned by kadm5_init_with_password().


Predefined Constants

Table of Contents

  • Constants for Attribute Flags
  • Constants for Options

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.


Constants for Attribute Flags

The functions kadm5_create_principal(),
kadm5_modify_principal(), and
kadm5_modify_principal() allow to specify
special attributes using a bitfield. The symbols are defined below:

Attributes for use by the KDC
constant
KRB5_KDB_DISALLOW_POSTDATED
KRB5_KDB_DISALLOW_FORWARDABLE
KRB5_KDB_DISALLOW_TGT_BASED
KRB5_KDB_DISALLOW_RENEWABLE
KRB5_KDB_DISALLOW_PROXIABLE
KRB5_KDB_DISALLOW_DUP_SKEY
KRB5_KDB_DISALLOW_ALL_TIX
KRB5_KDB_REQUIRES_PRE_AUTH
KRB5_KDB_REQUIRES_HW_AUTH
KRB5_KDB_REQUIRES_PWCHANGE
KRB5_KDB_DISALLOW_SVR
KRB5_KDB_PWCHANGE_SERVER
KRB5_KDB_SUPPORT_DESMD5
KRB5_KDB_NEW_PRINC


Constants for Options

The functions kadm5_create_principal(),
kadm5_modify_principal(), and
kadm5_get_principal() allow to specify or return
principal's options as an associative array. The keys for the associative
array are defined as string constants below:

Options for creating/modifying/retrieving principals
constant | funcdef | description
KADM5_PRINCIPAL | long | The expire time of the princial as a Kerberos timestamp.
KADM5_PRINC_EXPIRE_TIME | long | The expire time of the princial as a Kerberos timestamp.
KADM5_LAST_PW_CHANGE | long | The time this principal's password was last changed.
KADM5_PW_EXPIRATION | long | The expire time of the principal's current password, as a Kerberos timestamp.
KADM5_MAX_LIFE | long | The maximum lifetime of any Kerberos ticket issued to this principal.
KADM5_MAX_RLIFE | long | The maximum renewable lifetime of any Kerberos ticket issued to or for this principal.
KADM5_MOD_NAME | string | The name of the Kerberos principal that most recently modified this principal.
KADM5_MOD_TIME | long | The time this principal was last modified, as a Kerberos timestamp.
KADM5_KVNO | long | The version of the principal's current key.
KADM5_POLICY | string | The name of the policy controlling this principal.
KADM5_CLEARPOLICY | long | Standard procedure is to assign the 'default' policy to new principals. KADM5_CLEARPOLICY suppresses this behaviour.
KADM5_LAST_SUCCESS | long | The KDC time of the last successfull AS_REQ.
KADM5_LAST_FAILED | long | The KDC time of the last failed AS_REQ.
KADM5_FAIL_AUTH_COUNT | long | The number of consecutive failed AS_REQs.
KADM5_RANDKEY | long | Generates a random password for the principal. The parameter password will be ignored.
KADM5_ATTRIBUTES | long | A bitfield of attributes for use by the KDC.


  • « Constants for Options
  • Basic usage »
  • PHP Manual
  • KADM5
  • Examples

Examples

Table of Contents

  • Basic usage


Basic usage

This simple example shows how to connect, query, print resulting principals and disconnect from a KADM5 database.

Example #1 KADM5 extension overview example

<?php

  $handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

  print "<h1>get_principals</h1>\n";
  $principals = kadm5_get_principals($handle);
  for( $i=0; $i<count($principals); $i++)
      print "$principals[$i]<br>\n";

  print "<h1>get_policies</h1>\n";
  $policies = kadm5_get_policies($handle);
  for( $i=0; $i<count($policies); $i++)
      print "$policies[$i]<br>\n";

  print "<h1>get_principal burbach@GONICUS.LOCAL</h1>\n";

  $options = kadm5_get_principal($handle, "burbach@GONICUS.LOCAL" );
  $keys = array_keys($options);
  for( $i=0; $i<count($keys); $i++) {
    $value = $options[$keys[$i]];
    print "$keys[$i]: $value<br>\n";
  }

  $options = array(KADM5_PRINC_EXPIRE_TIME => 0);
  kadm5_modify_principal($handle, "burbach@GONICUS.LOCAL", $options);

  kadm5_destroy($handle);
?>


KADM5 Functions

Table of Contents

  • kadm5_chpass_principal — Changes the principal's password
  • kadm5_create_principal — Creates a kerberos principal with the given parameters
  • kadm5_delete_principal — Deletes a kerberos principal
  • kadm5_destroy — Closes the connection to the admin server and releases all related resources
  • kadm5_flush — Flush all changes to the Kerberos database
  • kadm5_get_policies — Gets all policies from the Kerberos database
  • kadm5_get_principal — Gets the principal's entries from the Kerberos database
  • kadm5_get_principals — Gets all principals from the Kerberos database
  • kadm5_init_with_password — Opens a connection to the KADM5 library
  • kadm5_modify_principal — Modifies a kerberos principal with the given parameters


Changes the principal's password

  • « KADM5 Functions
  • kadm5_create_principal »
  • PHP Manual
  • KADM5 Functions
  • Changes the principal's password

kadm5_chpass_principal

(PECL kadm5 >= 0.2.3)

kadm5_chpass_principal — Changes the principal's password

Description

kadm5_chpass_principal ( resource $handle , string $principal , string $password ) : bool

kadm5_chpass_principal() sets the new password password for the principal.

Parameters

handle

A KADM5 handle.

principal

The principal.

password

The new password.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Example of changing principal's password

<?php

$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

kadm5_chpass_principal($handle, "burbach@GONICUS.LOCAL", "newpassword");

kadm5_destroy($handle);
?>


Creates a kerberos principal with the given parameters

  • « kadm5_chpass_principal
  • kadm5_delete_principal »
  • PHP Manual
  • KADM5 Functions
  • Creates a kerberos principal with the given parameters

kadm5_create_principal

(PECL kadm5 >= 0.2.3)

kadm5_create_principal — Creates a kerberos principal with the given parameters

Description

kadm5_create_principal ( resource $handle , string $principal [, string $password [, array $options ]] ) : bool

Creates a principal with the given password.

Parameters

handle

A KADM5 handle.

principal

The principal.

password

If password is omitted or is NULL, a random key will be generated.

options

It is possible to specify several optional parameters within the array options. Allowed are the following options: KADM5_PRINC_EXPIRE_TIME, KADM5_PW_EXPIRATION, KADM5_ATTRIBUTES, KADM5_MAX_LIFE, KADM5_KVNO, KADM5_POLICY, KADM5_CLEARPOLICY, KADM5_MAX_RLIFE.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Example of principal's creation

<?php

$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

$attributes = KRB5_KDB_REQUIRES_PRE_AUTH | KRB5_KDB_DISALLOW_PROXIABLE;
$options = array(KADM5_PRINC_EXPIRE_TIME => 0,
                 KADM5_POLICY => "default",
                 KADM5_ATTRIBUTES => $attributes);

kadm5_create_principal($handle, "burbach@GONICUS.LOCAL", "password", $options);

kadm5_destroy($handle);
?>

See Also

  • kadm5_modify_principal() - Modifies a kerberos principal with the given parameters
  • kadm5_delete_principal() - Deletes a kerberos principal


Deletes a kerberos principal

  • « kadm5_create_principal
  • kadm5_destroy »
  • PHP Manual
  • KADM5 Functions
  • Deletes a kerberos principal

kadm5_delete_principal

(PECL kadm5 >= 0.2.3)

kadm5_delete_principal — Deletes a kerberos principal

Description

kadm5_delete_principal ( resource $handle , string $principal ) : bool

Removes the principal from the Kerberos database.

Parameters

handle

A KADM5 handle.

principal

The removed principal.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 kadm5_delete_principal() example

<?php

$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

kadm5_delete_principal($handle, "burbach@GONICUS.LOCAL");

kadm5_destroy($handle);
?>

See Also

  • kadm5_modify_principal() - Modifies a kerberos principal with the given parameters
  • kadm5_create_principal() - Creates a kerberos principal with the given parameters


Closes the connection to the admin server and releases all related resources

  • « kadm5_delete_principal
  • kadm5_flush »
  • PHP Manual
  • KADM5 Functions
  • Closes the connection to the admin server and releases all related resources

kadm5_destroy

(PECL kadm5 >= 0.2.3)

kadm5_destroy — Closes the connection to the admin server and releases all related resources

Description

kadm5_destroy ( resource $handle ) : bool

Closes the connection to the admin server and releases all related resources.

Parameters

handle

A KADM5 handle.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • kadm5_init_with_password() - Opens a connection to the KADM5 library


Flush all changes to the Kerberos database

  • « kadm5_destroy
  • kadm5_get_policies »
  • PHP Manual
  • KADM5 Functions
  • Flush all changes to the Kerberos database

kadm5_flush

(PECL kadm5 >= 0.2.3)

kadm5_flush — Flush all changes to the Kerberos database

Description

kadm5_flush ( resource $handle ) : bool

Flush all changes to the Kerberos database, leaving the connection to the Kerberos admin server open.

Parameters

handle

A KADM5 handle.

Return Values

Returns TRUE on success or FALSE on failure.


Gets all policies from the Kerberos database

  • « kadm5_flush
  • kadm5_get_principal »
  • PHP Manual
  • KADM5 Functions
  • Gets all policies from the Kerberos database

kadm5_get_policies

(PECL kadm5 >= 0.2.3)

kadm5_get_policies — Gets all policies from the Kerberos database

Description

kadm5_get_policies ( resource $handle ) : array

Gets an array containing the policies's names.

Parameters

handle

A KADM5 handle.

Return Values

Returns array of policies on success or FALSE on failure.

Examples

Example #1 kadm5_get_policies() example

<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

print "<h1>get_policies</h1>\n";
foreach (kadm5_get_policies($handle) as $policy) {
    echo "$policy<br />\n";
}

kadm5_destroy($handle);
?>


Gets the principal's entries from the Kerberos database

  • « kadm5_get_policies
  • kadm5_get_principals »
  • PHP Manual
  • KADM5 Functions
  • Gets the principal's entries from the Kerberos database

kadm5_get_principal

(PECL kadm5 >= 0.2.3)

kadm5_get_principal — Gets the principal's entries from the Kerberos database

Description

kadm5_get_principal ( resource $handle , string $principal ) : array

Gets the principal's entries from the Kerberos database.

Parameters

handle

A KADM5 handle.

principal

The principal.

Return Values

Returns array of options containing the following keys: KADM5_PRINCIPAL, KADM5_PRINC_EXPIRE_TIME, KADM5_PW_EXPIRATION, KADM5_ATTRIBUTES, KADM5_MAX_LIFE, KADM5_MOD_NAME, KADM5_MOD_TIME, KADM5_KVNO, KADM5_POLICY, KADM5_MAX_RLIFE, KADM5_LAST_SUCCESS, KADM5_LAST_FAILED, KADM5_FAIL_AUTH_COUNT on success or FALSE on failure.

Examples

Example #1 kadm5_get_principal() example

<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

print "<h1>get_principal burbach@GONICUS.LOCAL</h1>\n";

$options = kadm5_get_principal($handle, "burbach@GONICUS.LOCAL" );

foreach ($options as $key => $value) {
    echo "$key: $value<br />\n";
}

kadm5_destroy($handle);
?>

See Also

  • kadm5_get_principals() - Gets all principals from the Kerberos database


Gets all principals from the Kerberos database

  • « kadm5_get_principal
  • kadm5_init_with_password »
  • PHP Manual
  • KADM5 Functions
  • Gets all principals from the Kerberos database

kadm5_get_principals

(PECL kadm5 >= 0.2.3)

kadm5_get_principals — Gets all principals from the Kerberos database

Description

kadm5_get_principals ( resource $handle ) : array

kadm5_get_principals() returns an array containing the principals's names.

Parameters

handle

A KADM5 handle.

Return Values

Returns array of principals on success or FALSE on failure.

Examples

Example #1 kadm5_get_principals() example

<?php
$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

print "<h1>get_principals</h1>\n";
foreach (kadm5_get_principals($handle) as $principal) {
    echo "$principal<br />\n";
}

kadm5_destroy($handle);
?>

See Also

  • kadm5_get_principal() - Gets the principal's entries from the Kerberos database


Opens a connection to the KADM5 library

  • « kadm5_get_principals
  • kadm5_modify_principal »
  • PHP Manual
  • KADM5 Functions
  • Opens a connection to the KADM5 library

kadm5_init_with_password

(PECL kadm5 >= 0.2.3)

kadm5_init_with_password — Opens a connection to the KADM5 library

Description

kadm5_init_with_password ( string $admin_server , string $realm , string $principal , string $password ) : resource

Opens a connection with the KADM5 library using the principal and the given password to obtain initial credentials from the admin_server.

Parameters

admin_server

The server.

realm

Defines the authentication domain for the connection.

principal

The principal.

password

If password is omitted or is NULL, a random key will be generated.

Return Values

Returns a KADM5 handle on success or FALSE on failure.

Examples

Example #1 KADM5 initialization example

<?php

$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

$attributes = KRB5_KDB_REQUIRES_PRE_AUTH | KRB5_KDB_DISALLOW_PROXIABLE;
$options = array(KADM5_PRINC_EXPIRE_TIME => 0,
                 KADM5_POLICY => "default",
                 KADM5_ATTRIBUTES => $attributes);

kadm5_create_principal($handle, "burbach@GONICUS.LOCAL", "password", $options);

kadm5_destroy($handle);
?>

Notes

Note:

Connection should be closed after use with kadm5_destroy().

See Also

  • kadm5_destroy() - Closes the connection to the admin server and releases all related resources


Modifies a kerberos principal with the given parameters

  • « kadm5_init_with_password
  • Radius »
  • PHP Manual
  • KADM5 Functions
  • Modifies a kerberos principal with the given parameters

kadm5_modify_principal

(PECL kadm5 >= 0.2.3)

kadm5_modify_principal — Modifies a kerberos principal with the given parameters

Description

kadm5_modify_principal ( resource $handle , string $principal , array $options ) : bool

Modifies a principal according to the given options.

Parameters

handle

A KADM5 handle.

principal

The principal.

options

It is possible to specify several optional parameters within the array options. Allowed are the following options: KADM5_PRINC_EXPIRE_TIME, KADM5_PW_EXPIRATION, KADM5_ATTRIBUTES, KADM5_MAX_LIFE, KADM5_KVNO, KADM5_POLICY, KADM5_CLEARPOLICY, KADM5_MAX_RLIFE. KADM5_FAIL_AUTH_COUNT.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Example of modifying principal

<?php

$handle = kadm5_init_with_password("afs-1", "GONICUS.LOCAL", "admin/admin", "password");

$attributes = KRB5_KDB_REQUIRES_PRE_AUTH;
$options = array(KADM5_PRINC_EXPIRE_TIME => 3451234,
                 KADM5_POLICY => "gonicus",
                 KADM5_ATTRIBUTES => $attributes);

kadm5_modify_principal($handle, "burbach@GONICUS.LOCAL", $options);

kadm5_destroy($handle);
?>

See Also

  • kadm5_create_principal() - Creates a kerberos principal with the given parameters
  • kadm5_delete_principal() - Deletes a kerberos principal


Radius

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • 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_mppe_key — Derives mppe-keys from mangled data
    • radius_demangle — Demangles 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


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.


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.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.


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

When set, this option will result in the attribute value being salt-encrypted.

RADIUS_OPTION_TAGGED (integer)

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

An Access-Request, used to authenticate a user against a RADIUS server. Access request packets must include a RADIUS_NAS_IP_ADDRESS or a RADIUS_NAS_IDENTIFIER attribute, must also include a RADIUS_USER_PASSWORD, RADIUS_CHAP_PASSWORD or a RADIUS_STATE attribute, and should include a RADIUS_USER_NAME attribute.

RADIUS_ACCESS_ACCEPT (integer)

An Access-Accept response to an Access-Request indicating that the RADIUS server authenticated the user successfully.

RADIUS_ACCESS_REJECT (integer)

An Access-Reject response to an Access-Request indicating that the RADIUS server could not authenticate the user.

RADIUS_ACCESS_CHALLENGE (integer)

An Access-Challenge response to an Access-Request indicating that the RADIUS server requires further information in another Access-Request before authenticating the user.

RADIUS_ACCOUNTING_REQUEST (integer)

An Accounting-Request, used to convey accounting information for a service to the RADIUS server.

RADIUS_ACCOUNTING_RESPONSE (integer)

An Accounting-Response response to an Accounting-Request.

RADIUS_COA_REQUEST (integer)

A CoA-Request, sent from the RADIUS server to indicate that the authorisations within the user session have changed. A response must be sent in the form of a CoA-ACK or a CoA-NAK.

This constant is available in PECL radius 1.3.0 and later.

RADIUS_COA_ACK (integer)

A CoA-ACK, sent to the RADIUS server to indicate that the user authorisations have been updated.

This constant is available in PECL radius 1.3.0 and later.

RADIUS_COA_NAK (integer)

A CoA-NAK, sent to the RADIUS server to indicate that the user authorisations could not be updated.

This constant is available in PECL radius 1.3.0 and later.

RADIUS_DISCONNECT_REQUEST (integer)

A Disconnect-Request, sent from the RADIUS server to indicate that the user session must be terminated.

This constant is available in PECL radius 1.3.0 and later.

RADIUS_DISCONNECT_ACK (integer)

A Disconnect-ACK, sent to the RADIUS server to indicate that the user session has been terminated.

This constant is available in PECL radius 1.3.0 and later.

RADIUS_DISCONNECT_NAK (integer)

A Disconnect-NAK, sent to the RADIUS server to indicate that the user session could not be terminated.

This constant is available in PECL radius 1.3.0 and later.


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

The User-Name attribute. The attribute value is expected to be a string containing the name of the user being authenticated, and can be set using radius_put_attr().

RADIUS_USER_PASSWORD (integer)

The User-Password attribute. The attribute value is expected to be a string containing the user's password, and can be set using radius_put_attr(). This value will be obfuscated on transmission as described in » section 5.2 of RFC 2865.

RADIUS_CHAP_PASSWORD (integer)

The Chap-Password attribute. The attribute value is expected to be a string with the first byte containing the CHAP identifier, and the subsequent 16 bytes containing the MD5 hash of the CHAP identifier, the plaintext password and the CHAP challenge value concatenated together. Note that the CHAP challenge value should also be sent separately in a RADIUS_CHAP_CHALLENGE attribute.

Example #1 Using CHAP passwords

<?php
// Firstly, we'll create an authentication handle and request.
$radh = radius_auth_open();
radius_add_server($radh, $server, $port, $secret, 3, 3);
radius_create_request($radh, RADIUS_ACCESS_REQUEST);

// Assuming $password contains the plaintext password, we now:

// Generate a challenge.
$challenge = mt_rand();

// Specify a CHAP identifier.
$ident = 1;

// Add the Chap-Password attribute.
$cp = md5(pack('Ca*', $ident, $password.$challenge), true);
radius_put_attr($radh, RADIUS_CHAP_PASSWORD, pack('C', $ident).$cp);

// Add the Chap-Challenge attribute.
radius_put_attr($radh, RADIUS_CHAP_CHALLENGE, $challenge);

/* From here, you would add the remaining attributes and
 * call radius_send_request(). */
?>

RADIUS_NAS_IP_ADDRESS (integer)

The NAS-IP-Address attribute. The attribute value is expected to the IP address of the RADIUS client encoded as an integer, which can be set using radius_put_addr().

RADIUS_NAS_PORT (integer)

The NAS-Port attribute. The attribute value is expected to be the physical port of the user on the RADIUS client encoded as an integer, which can be set using radius_put_int().

RADIUS_SERVICE_TYPE (integer)

The Service-Type attribute. The attribute value indicates the service type the user is requesting, and is expected to be an integer, which can be set using radius_put_int().

A number of constants are provided to represent the possible values of this attribute. They include:

  • RADIUS_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 (integer)

The Framed-Protocol attribute. The attribute value is expected to be an integer indicating the framing to be used for framed access, and can be set using radius_put_int(). The possible attribute values include these constants:

  • RADIUS_PPP
  • RADIUS_SLIP
  • RADIUS_ARAP
  • RADIUS_GANDALF
  • RADIUS_XYLOGICS

RADIUS_FRAMED_IP_ADDRESS (integer)

The Framed-IP-Address attribute. The attribute value is expected to be the address of the user's network encoded as an integer, which can be set using radius_put_addr() and retrieved using radius_cvt_addr().

RADIUS_FRAMED_IP_NETMASK (integer)

The Framed-IP-Netmask attribute. The attribute value is expected to be the netmask of the user's network encoded as an integer, which can be set using radius_put_addr() and retrieved using radius_cvt_addr().

RADIUS_FRAMED_ROUTING (integer)

The Framed-Routing attribute. The attribute value is expected to be an integer indicating the routing method for the user, which can be set using radius_put_int().

Possible values include:

  • 0: No routing
  • 1: Send routing packets
  • 2: Listen for routing packets
  • 3: Send and listen

RADIUS_FILTER_ID (integer)

The Filter-ID attribute. The attribute value is expected to be an implementation-specific, human-readable string of filters, which can be set using radius_put_attr().

RADIUS_FRAMED_MTU (integer)

The Framed-MTU attribute. The attribute value is expected to be an integer indicating the MTU to be configured for the user, and can be set using radius_put_int().

RADIUS_FRAMED_COMPRESSION (integer)

The Framed-Compression attribute. The attribute value is expected to be an integer indicating the compression protocol to be used, and can be set using radius_put_int(). Possible values include these constants:

  • RADIUS_COMP_NONE: No 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 (integer)

The Login-IP-Host attribute. The attribute value is expected to the IP address to connect the user to, encoded as an integer, which can be set using radius_put_addr().

RADIUS_LOGIN_SERVICE (integer)

The Login-Service attribute. The attribute value is an integer indicating the service to connect the user to on the login host. The value can be converted to a PHP integer via radius_cvt_int().

RADIUS_LOGIN_TCP_PORT (integer)

The Login-TCP-Port attribute. The attribute value is an integer indicating the port to connect the user to on the login host. The value can be converted to a PHP integer via radius_cvt_int().

RADIUS_REPLY_MESSAGE (integer)

The Reply-Message attribute. The attribute value is a string containing text that may be displayed to the user in response to an access request.

RADIUS_CALLBACK_NUMBER (integer)

The Callback-Number attribute. The attribute value is a string containing the dialing string to use for callback.

RADIUS_CALLBACK_ID (integer)

The Callback-Id attribute. The attribute value is a string containing an implementation-specific name of the place to be called.

RADIUS_FRAMED_ROUTE (integer)

The Framed-Route attribute. The attribute value is a string containing an implementation-specific set of routes to be configured for the user.

RADIUS_FRAMED_IPX_NETWORK (integer)

The Framed-IPX-Network attribute. The attribute value is an integer containing the IPX network to be configured for the user, or 0xFFFFFFFE to indicate that the RADIUS client should select the network, and can be accessed via radius_cvt_int().

RADIUS_STATE (integer)

The State attribute. The attribute value is an implementation-defined string included in an Access-Challenge from a server that must be included in the subsequent Access-Request, and can be set using radius_put_attr().

RADIUS_CLASS (integer)

The Class attribute. The attribute value is an arbitrary string included in an Access-Accept message that should then be sent to the accounting server in Accounting-Request messages, and can be set using radius_put_attr().

RADIUS_VENDOR_SPECIFIC (integer)

The Vendor-Specific attribute. In general, vendor attribute values
should be set using radius_put_vendor_addr(),
radius_put_vendor_attr(),
radius_put_vendor_int() and
radius_put_vendor_string(), rather than directly.

This constant is mostly useful when interpreting vendor specific attributes in responses from a RADIUS server; when a vendor specific attribute is received, the radius_get_vendor_attr() function should be used to access the vendor ID, attribute type and attribute value.

RADIUS_SESSION_TIMEOUT (integer)

Session timeout

RADIUS_IDLE_TIMEOUT (integer)

Idle timeout

RADIUS_TERMINATION_ACTION (integer)

Termination action

RADIUS_CALLED_STATION_ID (integer)

Called Station Id

RADIUS_CALLING_STATION_ID (integer)

Calling Station Id

RADIUS_NAS_IDENTIFIER (integer)

NAS ID

RADIUS_PROXY_STATE (integer)

Proxy State

RADIUS_LOGIN_LAT_SERVICE (integer)

Login LAT Service

RADIUS_LOGIN_LAT_NODE (integer)

Login LAT Node

RADIUS_LOGIN_LAT_GROUP (integer)

Login LAT Group

RADIUS_FRAMED_APPLETALK_LINK (integer)

Framed Appletalk Link

RADIUS_FRAMED_APPLETALK_NETWORK (integer)

Framed Appletalk Network

RADIUS_FRAMED_APPLETALK_ZONE (integer)

Framed Appletalk Zone

RADIUS_CHAP_CHALLENGE (integer)

Challenge

RADIUS_NAS_PORT_TYPE (integer)

NAS port type, one of:

  • RADIUS_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 (integer)

Port Limit

RADIUS_LOGIN_LAT_PORT (integer)

Login LAT Port

RADIUS_CONNECT_INFO (integer)

Connect info

RADIUS_ACCT_STATUS_TYPE (integer)

Accounting status type, one of:

  • RADIUS_START
  • RADIUS_STOP
  • RADIUS_ACCOUNTING_ON
  • RADIUS_ACCOUNTING_OFF

RADIUS_ACCT_DELAY_TIME (integer)

Accounting delay time

RADIUS_ACCT_INPUT_OCTETS (integer)

Accounting input bytes

RADIUS_ACCT_OUTPUT_OCTETS (integer)

Accounting output bytes

RADIUS_ACCT_SESSION_ID (integer)

Accounting session ID

RADIUS_ACCT_AUTHENTIC (integer)

Accounting authentic, one of:

  • RADIUS_AUTH_RADIUS
  • RADIUS_AUTH_LOCAL
  • RADIUS_AUTH_REMOTE

RADIUS_ACCT_SESSION_TIME (integer)

Accounting session time

RADIUS_ACCT_INPUT_PACKETS (integer)

Accounting input packets

RADIUS_ACCT_OUTPUT_PACKETS (integer)

Accounting output packets

RADIUS_ACCT_TERMINATE_CAUSE (integer)

Accounting terminate cause, one of:

  • RADIUS_TERM_USER_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 (integer)

Accounting multi session ID

RADIUS_ACCT_LINK_COUNT (integer)

Accounting link count


RADIUS Vendor Specific Attribute Types

RADIUS_VENDOR_MICROSOFT (integer)

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


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

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_mppe_key — Derives mppe-keys from mangled data
  • radius_demangle — Demangles 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


Creates a Radius handle for accounting

  • « Radius Functions
  • radius_add_server »
  • PHP Manual
  • Radius Functions
  • Creates a Radius handle for accounting

radius_acct_open

(PECL radius >= 1.1.0)

radius_acct_open — Creates a Radius handle for accounting

Description

radius_acct_open ( void ) : resource

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");
?>


Adds a server

  • « radius_acct_open
  • radius_auth_open »
  • PHP Manual
  • Radius Functions
  • Adds a server

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


Creates a Radius handle for authentication

  • « radius_add_server
  • radius_close »
  • PHP Manual
  • Radius Functions
  • Creates a Radius handle for authentication

radius_auth_open

(PECL radius >= 1.1.0)

radius_auth_open — Creates a Radius handle for authentication

Description

radius_auth_open ( void ) : resource

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


Frees all ressources

  • « radius_auth_open
  • radius_config »
  • PHP Manual
  • Radius Functions
  • Frees all ressources

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.

Return Values

Returns TRUE on success or FALSE on failure.


Causes the library to read the given configuration file

  • « radius_close
  • radius_create_request »
  • PHP Manual
  • Radius Functions
  • Causes the library to read the given configuration file

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


Create accounting or authentication request

  • « radius_config
  • radius_cvt_addr »
  • PHP Manual
  • Radius Functions
  • Create accounting or authentication request

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


Converts raw data to IP-Address

  • « radius_create_request
  • radius_cvt_int »
  • PHP Manual
  • Radius Functions
  • Converts raw data to IP-Address

radius_cvt_addr

(PECL radius >= 1.1.0)

radius_cvt_addr — Converts raw data to IP-Address

Description

radius_cvt_addr ( string $data ) : string

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


Converts raw data to integer

  • « radius_cvt_addr
  • radius_cvt_string »
  • PHP Manual
  • Radius Functions
  • Converts raw data to integer

radius_cvt_int

(PECL radius >= 1.1.0)

radius_cvt_int — Converts raw data to integer

Description

radius_cvt_int ( string $data ) : int

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


Converts raw data to string

  • « radius_cvt_int
  • radius_demangle_mppe_key »
  • PHP Manual
  • Radius Functions
  • 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

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


Derives mppe-keys from mangled data

  • « radius_cvt_string
  • radius_demangle »
  • PHP Manual
  • Radius Functions
  • Derives mppe-keys from mangled data

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.

Return Values

Returns the demangled string, or FALSE on error.


Demangles data

  • « radius_demangle_mppe_key
  • radius_get_attr »
  • PHP Manual
  • Radius Functions
  • Demangles data

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.

Return Values

Returns the demangled string, or FALSE on error.


Extracts an attribute

  • « radius_demangle
  • radius_get_tagged_attr_data »
  • PHP Manual
  • Radius Functions
  • Extracts an attribute

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.

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


Extracts the data from a tagged attribute

  • « radius_get_attr
  • radius_get_tagged_attr_tag »
  • PHP Manual
  • Radius Functions
  • Extracts the data from a tagged attribute

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

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


Extracts the tag from a tagged attribute

  • « radius_get_tagged_attr_data
  • radius_get_vendor_attr »
  • PHP Manual
  • Radius Functions
  • 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

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


Extracts a vendor specific attribute

  • « radius_get_tagged_attr_tag
  • radius_put_addr »
  • PHP Manual
  • Radius Functions
  • Extracts a vendor specific 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.

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


Attaches an IP address attribute

  • « radius_get_vendor_attr
  • radius_put_attr »
  • PHP Manual
  • Radius Functions
  • Attaches an IP address 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.


Attaches a binary attribute

  • « radius_put_addr
  • radius_put_int »
  • PHP Manual
  • Radius Functions
  • Attaches a binary attribute

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.

Examples

Example #1 radius_put_attr() example

<?php
mt_srand(time());
$chall = mt_rand();
$chapval = md5(pack('Ca*',1 , 'sepp' . $chall));
$pass = pack('CH*', 1, $chapval);
if (!radius_put_attr($res, RADIUS_CHAP_PASSWORD, $pass)) {
    echo 'RadiusError:' . radius_strerror($res). "\n<br />";
    exit;
}
?>

Changelog

Version | Description
PECL radius 1.3.0 | The options and tag parameters were added.

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


Attaches an integer attribute

  • « radius_put_attr
  • radius_put_string »
  • PHP Manual
  • Radius Functions
  • Attaches an integer 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


Attaches a string attribute

  • « radius_put_int
  • radius_put_vendor_addr »
  • PHP Manual
  • Radius Functions
  • Attaches a 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


Attaches a vendor specific IP address attribute

  • « radius_put_string
  • radius_put_vendor_attr »
  • PHP Manual
  • Radius Functions
  • Attaches a vendor specific IP address 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.


Attaches a vendor specific binary attribute

  • « radius_put_vendor_addr
  • radius_put_vendor_int »
  • PHP Manual
  • Radius Functions
  • Attaches a vendor specific binary attribute

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


Attaches a vendor specific integer attribute

  • « radius_put_vendor_attr
  • radius_put_vendor_string »
  • PHP Manual
  • Radius Functions
  • Attaches a vendor specific integer 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


Attaches a vendor specific string attribute

  • « radius_put_vendor_int
  • radius_request_authenticator »
  • PHP Manual
  • Radius Functions
  • 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


Returns the request authenticator

  • « radius_put_vendor_string
  • radius_salt_encrypt_attr »
  • PHP Manual
  • Radius Functions
  • Returns the request authenticator

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.

Return Values

Returns the request authenticator as string, or FALSE on error.

See Also

  • radius_demangle() - Demangles data


Salt-encrypts a value

  • « radius_request_authenticator
  • radius_send_request »
  • PHP Manual
  • Radius Functions
  • Salt-encrypts a value

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

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


Sends the request and waits for a reply

  • « radius_salt_encrypt_attr
  • radius_server_secret »
  • PHP Manual
  • Radius Functions
  • Sends the request and waits for a reply

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.

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


Returns the shared secret

  • « radius_send_request
  • radius_strerror »
  • PHP Manual
  • Radius Functions
  • Returns the shared secret

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.

Return Values

Returns the server's shared secret as string, or FALSE on error.


Returns an error message

  • « radius_server_secret
  • Command Line Specific Extensions »
  • PHP Manual
  • Radius Functions
  • Returns an error message

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.

Return Values

Returns error messages as string from failed radius functions.


Command Line Specific Extensions

  • Ncurses — Ncurses Terminal Screen Control
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Ncurses Functions
  • Newt
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Newt Functions
  • Readline — GNU Readline
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Readline Functions


Ncurses Terminal Screen Control

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
    • Error codes
    • Colors
    • Keys
    • Mouse
  • Ncurses Functions
    • ncurses_addch — Add character at current position and advance cursor
    • ncurses_addchnstr — Add attributed string with specified length at current position
    • ncurses_addchstr — Add attributed string at current position
    • ncurses_addnstr — Add string with specified length at current position
    • ncurses_addstr — Output text at current position
    • ncurses_assume_default_colors — Define default colors for color 0
    • ncurses_attroff — Turn off the given attributes
    • ncurses_attron — Turn on the given attributes
    • ncurses_attrset — Set given attributes
    • ncurses_baudrate — Returns baudrate of terminal
    • ncurses_beep — Let the terminal beep
    • ncurses_bkgd — Set background property for terminal screen
    • ncurses_bkgdset — Control screen background
    • ncurses_border — Draw a border around the screen using attributed characters
    • ncurses_bottom_panel — Moves a visible panel to the bottom of the stack
    • ncurses_can_change_color — Checks if terminal color definitions can be changed
    • ncurses_cbreak — Switch off input buffering
    • ncurses_clear — Clear screen
    • ncurses_clrtobot — Clear screen from current position to bottom
    • ncurses_clrtoeol — Clear screen from current position to end of line
    • ncurses_color_content — Retrieves RGB components of a color
    • ncurses_color_set — Set active foreground and background colors
    • ncurses_curs_set — Set cursor state
    • ncurses_def_prog_mode — Saves terminals (program) mode
    • ncurses_def_shell_mode — Saves terminals (shell) mode
    • ncurses_define_key — Define a keycode
    • ncurses_del_panel — Remove panel from the stack and delete it (but not the associated window)
    • ncurses_delay_output — Delay output on terminal using padding characters
    • ncurses_delch — Delete character at current position, move rest of line left
    • ncurses_deleteln — Delete line at current position, move rest of screen up
    • ncurses_delwin — Delete a ncurses window
    • ncurses_doupdate — Write all prepared refreshes to terminal
    • ncurses_echo — Activate keyboard input echo
    • ncurses_echochar — Single character output including refresh
    • ncurses_end — Stop using ncurses, clean up the screen
    • ncurses_erase — Erase terminal screen
    • ncurses_erasechar — Returns current erase character
    • ncurses_filter — Set LINES for iniscr() and newterm() to 1
    • ncurses_flash — Flash terminal screen (visual bell)
    • ncurses_flushinp — Flush keyboard input buffer
    • ncurses_getch — Read a character from keyboard
    • ncurses_getmaxyx — Returns the size of a window
    • ncurses_getmouse — Reads mouse event
    • ncurses_getyx — Returns the current cursor position for a window
    • ncurses_halfdelay — Put terminal into halfdelay mode
    • ncurses_has_colors — Checks if terminal has color capabilities
    • ncurses_has_ic — Check for insert- and delete-capabilities
    • ncurses_has_il — Check for line insert- and delete-capabilities
    • ncurses_has_key — Check for presence of a function key on terminal keyboard
    • ncurses_hide_panel — Remove panel from the stack, making it invisible
    • ncurses_hline — Draw a horizontal line at current position using an attributed character and max. n characters long
    • ncurses_inch — Get character and attribute at current position
    • ncurses_init_color — Define a terminal color
    • ncurses_init_pair — Define a color pair
    • ncurses_init — Initialize ncurses
    • ncurses_insch — Insert character moving rest of line including character at current position
    • ncurses_insdelln — Insert lines before current line scrolling down (negative numbers delete and scroll up)
    • ncurses_insertln — Insert a line, move rest of screen down
    • ncurses_insstr — Insert string at current position, moving rest of line right
    • ncurses_instr — Reads string from terminal screen
    • ncurses_isendwin — Ncurses is in endwin mode, normal screen output may be performed
    • ncurses_keyok — Enable or disable a keycode
    • ncurses_keypad — Turns keypad on or off
    • ncurses_killchar — Returns current line kill character
    • ncurses_longname — Returns terminals description
    • ncurses_meta — Enables/Disable 8-bit meta key information
    • ncurses_mouse_trafo — Transforms coordinates
    • ncurses_mouseinterval — Set timeout for mouse button clicks
    • ncurses_mousemask — Sets mouse options
    • ncurses_move_panel — Moves a panel so that its upper-left corner is at [startx, starty]
    • ncurses_move — Move output position
    • ncurses_mvaddch — Move current position and add character
    • ncurses_mvaddchnstr — Move position and add attributed string with specified length
    • ncurses_mvaddchstr — Move position and add attributed string
    • ncurses_mvaddnstr — Move position and add string with specified length
    • ncurses_mvaddstr — Move position and add string
    • ncurses_mvcur — Move cursor immediately
    • ncurses_mvdelch — Move position and delete character, shift rest of line left
    • ncurses_mvgetch — Move position and get character at new position
    • ncurses_mvhline — Set new position and draw a horizontal line using an attributed character and max. n characters long
    • ncurses_mvinch — Move position and get attributed character at new position
    • ncurses_mvvline — Set new position and draw a vertical line using an attributed character and max. n characters long
    • ncurses_mvwaddstr — Add string at new position in window
    • ncurses_napms — Sleep
    • ncurses_new_panel — Create a new panel and associate it with window
    • ncurses_newpad — Creates a new pad (window)
    • ncurses_newwin — Create a new window
    • ncurses_nl — Translate newline and carriage return / line feed
    • ncurses_nocbreak — Switch terminal to cooked mode
    • ncurses_noecho — Switch off keyboard input echo
    • ncurses_nonl — Do not translate newline and carriage return / line feed
    • ncurses_noqiflush — Do not flush on signal characters
    • ncurses_noraw — Switch terminal out of raw mode
    • ncurses_pair_content — Retrieves foreground and background colors of a color pair
    • ncurses_panel_above — Returns the panel above panel
    • ncurses_panel_below — Returns the panel below panel
    • ncurses_panel_window — Returns the window associated with panel
    • ncurses_pnoutrefresh — Copies a region from a pad into the virtual screen
    • ncurses_prefresh — Copies a region from a pad into the virtual screen
    • ncurses_putp — Apply padding information to the string and output it
    • ncurses_qiflush — Flush on signal characters
    • ncurses_raw — Switch terminal into raw mode
    • ncurses_refresh — Refresh screen
    • ncurses_replace_panel — Replaces the window associated with panel
    • ncurses_reset_prog_mode — Resets the prog mode saved by def_prog_mode
    • ncurses_reset_shell_mode — Resets the shell mode saved by def_shell_mode
    • ncurses_resetty — Restores saved terminal state
    • ncurses_savetty — Saves terminal state
    • ncurses_scr_dump — Dump screen content to file
    • ncurses_scr_init — Initialize screen from file dump
    • ncurses_scr_restore — Restore screen from file dump
    • ncurses_scr_set — Inherit screen from file dump
    • ncurses_scrl — Scroll window content up or down without changing current position
    • ncurses_show_panel — Places an invisible panel on top of the stack, making it visible
    • ncurses_slk_attr — Returns current soft label key attribute
    • ncurses_slk_attroff — Turn off the given attributes for soft function-key labels
    • ncurses_slk_attron — Turn on the given attributes for soft function-key labels
    • ncurses_slk_attrset — Set given attributes for soft function-key labels
    • ncurses_slk_clear — Clears soft labels from screen
    • ncurses_slk_color — Sets color for soft label keys
    • ncurses_slk_init — Initializes soft label key functions
    • ncurses_slk_noutrefresh — Copies soft label keys to virtual screen
    • ncurses_slk_refresh — Copies soft label keys to screen
    • ncurses_slk_restore — Restores soft label keys
    • ncurses_slk_set — Sets function key labels
    • ncurses_slk_touch — Forces output when ncurses_slk_noutrefresh is performed
    • ncurses_standend — Stop using 'standout' attribute
    • ncurses_standout — Start using 'standout' attribute
    • ncurses_start_color — Initializes color functionality
    • ncurses_termattrs — Returns a logical OR of all attribute flags supported by terminal
    • ncurses_termname — Returns terminals (short)-name
    • ncurses_timeout — Set timeout for special key sequences
    • ncurses_top_panel — Moves a visible panel to the top of the stack
    • ncurses_typeahead — Specify different filedescriptor for typeahead checking
    • ncurses_ungetch — Put a character back into the input stream
    • ncurses_ungetmouse — Pushes mouse event to queue
    • ncurses_update_panels — Refreshes the virtual screen to reflect the relations between panels in the stack
    • ncurses_use_default_colors — Assign terminal default colors to color id -1
    • ncurses_use_env — Control use of environment information about terminal size
    • ncurses_use_extended_names — Control use of extended names in terminfo descriptions
    • ncurses_vidattr — Display the string on the terminal in the video attribute mode
    • ncurses_vline — Draw a vertical line at current position using an attributed character and max. n characters long
    • ncurses_waddch — Adds character at current position in a window and advance cursor
    • ncurses_waddstr — Outputs text at current postion in window
    • ncurses_wattroff — Turns off attributes for a window
    • ncurses_wattron — Turns on attributes for a window
    • ncurses_wattrset — Set the attributes for a window
    • ncurses_wborder — Draws a border around the window using attributed characters
    • ncurses_wclear — Clears window
    • ncurses_wcolor_set — Sets windows color pairings
    • ncurses_werase — Erase window contents
    • ncurses_wgetch — Reads a character from keyboard (window)
    • ncurses_whline — Draws a horizontal line in a window at current position using an attributed character and max. n characters long
    • ncurses_wmouse_trafo — Transforms window/stdscr coordinates
    • ncurses_wmove — Moves windows output position
    • ncurses_wnoutrefresh — Copies window to virtual screen
    • ncurses_wrefresh — Refresh window on terminal screen
    • ncurses_wstandend — End standout mode for a window
    • ncurses_wstandout — Enter standout mode for a window
    • ncurses_wvline — Draws a vertical line in a window at current position using an attributed character and max. n characters long


Introduction

ncurses (new curses) is a free software emulation of curses in System V Rel 4.0 (and above). It uses terminfo format, supports pads, colors, multiple highlights, form characters and function key mapping. Because of the interactive nature of this library, it will be of little use for writing Web applications, but may be useful when writing scripts meant using PHP from the command line.

The features available, such as colors, depend on the terminal that you are using. Use functions such as ncurses_has_colors(), ncurses_can_change_color(), and ncurses_has_ic() to check for individual capabilities.

Note:

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.3.0.

ncurses is available for the following platforms:

  • AIX
  • BeOS
  • BSD variants (FreeBSD, NetBSD, OpenBSD)
  • Cygwin
  • Digital Unix (aka OSF1)
  • GNU/Linux
  • HPUX
  • IRIX64
  • macOS
  • OS/2
  • QNX
  • SCO OpenServer
  • Solaris
  • Tru64


Requirements

You need the ncurses libraries and headerfiles. Download the latest version from the » ftp://ftp.gnu.org/pub/gnu/ncurses/ or from an other GNU-Mirror.


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

Wide character CRT screen handling (ncursesw) support was added in version 1.0.1 of this PECL extension.


  • « Runtime Configuration
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

This extension defines window, panel and pad resources.


Predefined Constants

Table of Contents

  • Error codes
  • Colors
  • Keys
  • Mouse

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.


Error codes

On error ncurses functions return -1. Some functions return 0 on success. See the relevant pages in the documentation for actual return values.


Colors

ncurses color constants
constant | meaning
NCURSES_COLOR_BLACK | no color (black)
NCURSES_COLOR_WHITE | white
NCURSES_COLOR_RED | red - supported when terminal is in color mode
NCURSES_COLOR_GREEN | green - supported when terminal is in color mode
NCURSES_COLOR_YELLOW | yellow - supported when terminal is in color mode
NCURSES_COLOR_BLUE | blue - supported when terminal is in color mode
NCURSES_COLOR_CYAN | cyan - supported when terminal is in color mode
NCURSES_COLOR_MAGENTA | magenta - supported when terminal is in color mode


Keys

ncurses key constants
constant | meaning
NCURSES_KEY_F0 - NCURSES_KEY_F64 | function keys F1 - F64
NCURSES_KEY_DOWN | down arrow
NCURSES_KEY_UP | up arrow
NCURSES_KEY_LEFT | left arrow
NCURSES_KEY_RIGHT | right arrow
NCURSES_KEY_HOME | home key (upward+left arrow)
NCURSES_KEY_BACKSPACE | backspace
NCURSES_KEY_DL | delete line
NCURSES_KEY_IL | insert line
NCURSES_KEY_DC | delete character
NCURSES_KEY_IC | insert char or enter insert mode
NCURSES_KEY_EIC | exit insert char mode
NCURSES_KEY_CLEAR | clear screen
NCURSES_KEY_EOS | clear to end of screen
NCURSES_KEY_EOL | clear to end of line
NCURSES_KEY_SF | scroll one line forward
NCURSES_KEY_SR | scroll one line backward
NCURSES_KEY_NPAGE | next page
NCURSES_KEY_PPAGE | previous page
NCURSES_KEY_STAB | set tab
NCURSES_KEY_CTAB | clear tab
NCURSES_KEY_CATAB | clear all tabs
NCURSES_KEY_SRESET | soft (partial) reset
NCURSES_KEY_RESET | reset or hard reset
NCURSES_KEY_PRINT | print
NCURSES_KEY_LL | lower left
NCURSES_KEY_A1 | upper left of keypad
NCURSES_KEY_A3 | upper right of keypad
NCURSES_KEY_B2 | center of keypad
NCURSES_KEY_C1 | lower left of keypad
NCURSES_KEY_C3 | lower right of keypad
NCURSES_KEY_BTAB | back tab
NCURSES_KEY_BEG | beginning
NCURSES_KEY_CANCEL | cancel
NCURSES_KEY_CLOSE | close
NCURSES_KEY_COMMAND | cmd (command)
NCURSES_KEY_COPY | copy
NCURSES_KEY_CREATE | create
NCURSES_KEY_END | end
NCURSES_KEY_EXIT | exit
NCURSES_KEY_FIND | find
NCURSES_KEY_HELP | help
NCURSES_KEY_MARK | mark
NCURSES_KEY_MESSAGE | message
NCURSES_KEY_MOVE | move
NCURSES_KEY_NEXT | next
NCURSES_KEY_OPEN | open
NCURSES_KEY_OPTIONS | options
NCURSES_KEY_PREVIOUS | previous
NCURSES_KEY_REDO | redo
NCURSES_KEY_REFERENCE | ref (reference)
NCURSES_KEY_REFRESH | refresh
NCURSES_KEY_REPLACE | replace
NCURSES_KEY_RESTART | restart
NCURSES_KEY_RESUME | resume
NCURSES_KEY_SAVE | save
NCURSES_KEY_SBEG | shiftet beg (beginning)
NCURSES_KEY_SCANCEL | shifted cancel
NCURSES_KEY_SCOMMAND | shifted command
NCURSES_KEY_SCOPY | shifted copy
NCURSES_KEY_SCREATE | shifted create
NCURSES_KEY_SDC | shifted delete char
NCURSES_KEY_SDL | shifted delete line
NCURSES_KEY_SELECT | select
NCURSES_KEY_SEND | shifted end
NCURSES_KEY_SEOL | shifted end of line
NCURSES_KEY_SEXIT | shifted exit
NCURSES_KEY_SFIND | shifted find
NCURSES_KEY_SHELP | shifted help
NCURSES_KEY_SHOME | shifted home
NCURSES_KEY_SIC | shifted input
NCURSES_KEY_SLEFT | shifted left arrow
NCURSES_KEY_SMESSAGE | shifted message
NCURSES_KEY_SMOVE | shifted move
NCURSES_KEY_SNEXT | shifted next
NCURSES_KEY_SOPTIONS | shifted options
NCURSES_KEY_SPREVIOUS | shifted previous
NCURSES_KEY_SPRINT | shifted print
NCURSES_KEY_SREDO | shifted redo
NCURSES_KEY_SREPLACE | shifted replace
NCURSES_KEY_SRIGHT | shifted right arrow
NCURSES_KEY_SRSUME | shifted resume
NCURSES_KEY_SSAVE | shifted save
NCURSES_KEY_SSUSPEND | shifted suspend
NCURSES_KEY_UNDO | undo
NCURSES_KEY_MOUSE | mouse event has occurred
NCURSES_KEY_MAX | maximum key value


Mouse

mouse constants
Constant | meaning
NCURSES_BUTTON1_RELEASED - NCURSES_BUTTON4_RELEASED | button (1-4) released
NCURSES_BUTTON1_PRESSED - NCURSES_BUTTON4_PRESSED | button (1-4) pressed
NCURSES_BUTTON1_CLICKED - NCURSES_BUTTON4_CLICKED | button (1-4) clicked
NCURSES_BUTTON1_DOUBLE_CLICKED - NCURSES_BUTTON4_DOUBLE_CLICKED | button (1-4) double clicked
NCURSES_BUTTON1_TRIPLE_CLICKED - NCURSES_BUTTON4_TRIPLE_CLICKED | button (1-4) triple clicked
NCURSES_BUTTON_CTRL | ctrl pressed during click
NCURSES_BUTTON_SHIFT | shift pressed during click
NCURSES_BUTTON_ALT | alt pressed during click
NCURSES_ALL_MOUSE_EVENTS | report all mouse events
NCURSES_REPORT_MOUSE_POSITION | report mouse position


Ncurses Functions

Table of Contents

  • ncurses_addch — Add character at current position and advance cursor
  • ncurses_addchnstr — Add attributed string with specified length at current position
  • ncurses_addchstr — Add attributed string at current position
  • ncurses_addnstr — Add string with specified length at current position
  • ncurses_addstr — Output text at current position
  • ncurses_assume_default_colors — Define default colors for color 0
  • ncurses_attroff — Turn off the given attributes
  • ncurses_attron — Turn on the given attributes
  • ncurses_attrset — Set given attributes
  • ncurses_baudrate — Returns baudrate of terminal
  • ncurses_beep — Let the terminal beep
  • ncurses_bkgd — Set background property for terminal screen
  • ncurses_bkgdset — Control screen background
  • ncurses_border — Draw a border around the screen using attributed characters
  • ncurses_bottom_panel — Moves a visible panel to the bottom of the stack
  • ncurses_can_change_color — Checks if terminal color definitions can be changed
  • ncurses_cbreak — Switch off input buffering
  • ncurses_clear — Clear screen
  • ncurses_clrtobot — Clear screen from current position to bottom
  • ncurses_clrtoeol — Clear screen from current position to end of line
  • ncurses_color_content — Retrieves RGB components of a color
  • ncurses_color_set — Set active foreground and background colors
  • ncurses_curs_set — Set cursor state
  • ncurses_def_prog_mode — Saves terminals (program) mode
  • ncurses_def_shell_mode — Saves terminals (shell) mode
  • ncurses_define_key — Define a keycode
  • ncurses_del_panel — Remove panel from the stack and delete it (but not the associated window)
  • ncurses_delay_output — Delay output on terminal using padding characters
  • ncurses_delch — Delete character at current position, move rest of line left
  • ncurses_deleteln — Delete line at current position, move rest of screen up
  • ncurses_delwin — Delete a ncurses window
  • ncurses_doupdate — Write all prepared refreshes to terminal
  • ncurses_echo — Activate keyboard input echo
  • ncurses_echochar — Single character output including refresh
  • ncurses_end — Stop using ncurses, clean up the screen
  • ncurses_erase — Erase terminal screen
  • ncurses_erasechar — Returns current erase character
  • ncurses_filter — Set LINES for iniscr() and newterm() to 1
  • ncurses_flash — Flash terminal screen (visual bell)
  • ncurses_flushinp — Flush keyboard input buffer
  • ncurses_getch — Read a character from keyboard
  • ncurses_getmaxyx — Returns the size of a window
  • ncurses_getmouse — Reads mouse event
  • ncurses_getyx — Returns the current cursor position for a window
  • ncurses_halfdelay — Put terminal into halfdelay mode
  • ncurses_has_colors — Checks if terminal has color capabilities
  • ncurses_has_ic — Check for insert- and delete-capabilities
  • ncurses_has_il — Check for line insert- and delete-capabilities
  • ncurses_has_key — Check for presence of a function key on terminal keyboard
  • ncurses_hide_panel — Remove panel from the stack, making it invisible
  • ncurses_hline — Draw a horizontal line at current position using an attributed character and max. n characters long
  • ncurses_inch — Get character and attribute at current position
  • ncurses_init_color — Define a terminal color
  • ncurses_init_pair — Define a color pair
  • ncurses_init — Initialize ncurses
  • ncurses_insch — Insert character moving rest of line including character at current position
  • ncurses_insdelln — Insert lines before current line scrolling down (negative numbers delete and scroll up)
  • ncurses_insertln — Insert a line, move rest of screen down
  • ncurses_insstr — Insert string at current position, moving rest of line right
  • ncurses_instr — Reads string from terminal screen
  • ncurses_isendwin — Ncurses is in endwin mode, normal screen output may be performed
  • ncurses_keyok — Enable or disable a keycode
  • ncurses_keypad — Turns keypad on or off
  • ncurses_killchar — Returns current line kill character
  • ncurses_longname — Returns terminals description
  • ncurses_meta — Enables/Disable 8-bit meta key information
  • ncurses_mouse_trafo — Transforms coordinates
  • ncurses_mouseinterval — Set timeout for mouse button clicks
  • ncurses_mousemask — Sets mouse options
  • ncurses_move_panel — Moves a panel so that its upper-left corner is at [startx, starty]
  • ncurses_move — Move output position
  • ncurses_mvaddch — Move current position and add character
  • ncurses_mvaddchnstr — Move position and add attributed string with specified length
  • ncurses_mvaddchstr — Move position and add attributed string
  • ncurses_mvaddnstr — Move position and add string with specified length
  • ncurses_mvaddstr — Move position and add string
  • ncurses_mvcur — Move cursor immediately
  • ncurses_mvdelch — Move position and delete character, shift rest of line left
  • ncurses_mvgetch — Move position and get character at new position
  • ncurses_mvhline — Set new position and draw a horizontal line using an attributed character and max. n characters long
  • ncurses_mvinch — Move position and get attributed character at new position
  • ncurses_mvvline — Set new position and draw a vertical line using an attributed character and max. n characters long
  • ncurses_mvwaddstr — Add string at new position in window
  • ncurses_napms — Sleep
  • ncurses_new_panel — Create a new panel and associate it with window
  • ncurses_newpad — Creates a new pad (window)
  • ncurses_newwin — Create a new window
  • ncurses_nl — Translate newline and carriage return / line feed
  • ncurses_nocbreak — Switch terminal to cooked mode
  • ncurses_noecho — Switch off keyboard input echo
  • ncurses_nonl — Do not translate newline and carriage return / line feed
  • ncurses_noqiflush — Do not flush on signal characters
  • ncurses_noraw — Switch terminal out of raw mode
  • ncurses_pair_content — Retrieves foreground and background colors of a color pair
  • ncurses_panel_above — Returns the panel above panel
  • ncurses_panel_below — Returns the panel below panel
  • ncurses_panel_window — Returns the window associated with panel
  • ncurses_pnoutrefresh — Copies a region from a pad into the virtual screen
  • ncurses_prefresh — Copies a region from a pad into the virtual screen
  • ncurses_putp — Apply padding information to the string and output it
  • ncurses_qiflush — Flush on signal characters
  • ncurses_raw — Switch terminal into raw mode
  • ncurses_refresh — Refresh screen
  • ncurses_replace_panel — Replaces the window associated with panel
  • ncurses_reset_prog_mode — Resets the prog mode saved by def_prog_mode
  • ncurses_reset_shell_mode — Resets the shell mode saved by def_shell_mode
  • ncurses_resetty — Restores saved terminal state
  • ncurses_savetty — Saves terminal state
  • ncurses_scr_dump — Dump screen content to file
  • ncurses_scr_init — Initialize screen from file dump
  • ncurses_scr_restore — Restore screen from file dump
  • ncurses_scr_set — Inherit screen from file dump
  • ncurses_scrl — Scroll window content up or down without changing current position
  • ncurses_show_panel — Places an invisible panel on top of the stack, making it visible
  • ncurses_slk_attr — Returns current soft label key attribute
  • ncurses_slk_attroff — Turn off the given attributes for soft function-key labels
  • ncurses_slk_attron — Turn on the given attributes for soft function-key labels
  • ncurses_slk_attrset — Set given attributes for soft function-key labels
  • ncurses_slk_clear — Clears soft labels from screen
  • ncurses_slk_color — Sets color for soft label keys
  • ncurses_slk_init — Initializes soft label key functions
  • ncurses_slk_noutrefresh — Copies soft label keys to virtual screen
  • ncurses_slk_refresh — Copies soft label keys to screen
  • ncurses_slk_restore — Restores soft label keys
  • ncurses_slk_set — Sets function key labels
  • ncurses_slk_touch — Forces output when ncurses_slk_noutrefresh is performed
  • ncurses_standend — Stop using 'standout' attribute
  • ncurses_standout — Start using 'standout' attribute
  • ncurses_start_color — Initializes color functionality
  • ncurses_termattrs — Returns a logical OR of all attribute flags supported by terminal
  • ncurses_termname — Returns terminals (short)-name
  • ncurses_timeout — Set timeout for special key sequences
  • ncurses_top_panel — Moves a visible panel to the top of the stack
  • ncurses_typeahead — Specify different filedescriptor for typeahead checking
  • ncurses_ungetch — Put a character back into the input stream
  • ncurses_ungetmouse — Pushes mouse event to queue
  • ncurses_update_panels — Refreshes the virtual screen to reflect the relations between panels in the stack
  • ncurses_use_default_colors — Assign terminal default colors to color id -1
  • ncurses_use_env — Control use of environment information about terminal size
  • ncurses_use_extended_names — Control use of extended names in terminfo descriptions
  • ncurses_vidattr — Display the string on the terminal in the video attribute mode
  • ncurses_vline — Draw a vertical line at current position using an attributed character and max. n characters long
  • ncurses_waddch — Adds character at current position in a window and advance cursor
  • ncurses_waddstr — Outputs text at current postion in window
  • ncurses_wattroff — Turns off attributes for a window
  • ncurses_wattron — Turns on attributes for a window
  • ncurses_wattrset — Set the attributes for a window
  • ncurses_wborder — Draws a border around the window using attributed characters
  • ncurses_wclear — Clears window
  • ncurses_wcolor_set — Sets windows color pairings
  • ncurses_werase — Erase window contents
  • ncurses_wgetch — Reads a character from keyboard (window)
  • ncurses_whline — Draws a horizontal line in a window at current position using an attributed character and max. n characters long
  • ncurses_wmouse_trafo — Transforms window/stdscr coordinates
  • ncurses_wmove — Moves windows output position
  • ncurses_wnoutrefresh — Copies window to virtual screen
  • ncurses_wrefresh — Refresh window on terminal screen
  • ncurses_wstandend — End standout mode for a window
  • ncurses_wstandout — Enter standout mode for a window
  • ncurses_wvline — Draws a vertical line in a window at current position using an attributed character and max. n characters long


Add character at current position and advance cursor

  • « Ncurses Functions
  • ncurses_addchnstr »
  • PHP Manual
  • Ncurses Functions
  • Add character at current position and advance cursor

ncurses_addch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addch — Add character at current position and advance cursor

Description

ncurses_addch ( int $ch ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

ch


Add attributed string with specified length at current position

  • « ncurses_addch
  • ncurses_addchstr »
  • PHP Manual
  • Ncurses Functions
  • Add attributed string with specified length at current position

ncurses_addchnstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addchnstr — Add attributed string with specified length at current position

Description

ncurses_addchnstr ( string $s , int $n ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

s

n


Add attributed string at current position

  • « ncurses_addchnstr
  • ncurses_addnstr »
  • PHP Manual
  • Ncurses Functions
  • Add attributed string at current position

ncurses_addchstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addchstr — Add attributed string at current position

Description

ncurses_addchstr ( string $s ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

s


Add string with specified length at current position

  • « ncurses_addchstr
  • ncurses_addstr »
  • PHP Manual
  • Ncurses Functions
  • Add string with specified length at current position

ncurses_addnstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addnstr — Add string with specified length at current position

Description

ncurses_addnstr ( string $s , int $n ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

s

n


Output text at current position

  • « ncurses_addnstr
  • ncurses_assume_default_colors »
  • PHP Manual
  • Ncurses Functions
  • Output text at current position

ncurses_addstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_addstr — Output text at current position

Description

ncurses_addstr ( string $text ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

text


Define default colors for color 0

  • « ncurses_addstr
  • ncurses_attroff »
  • PHP Manual
  • Ncurses Functions
  • Define default colors for color 0

ncurses_assume_default_colors

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_assume_default_colors — Define default colors for color 0

Description

ncurses_assume_default_colors ( int $fg , int $bg ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

fg

bg


Turn off the given attributes

  • « ncurses_assume_default_colors
  • ncurses_attron »
  • PHP Manual
  • Ncurses Functions
  • Turn off the given attributes

ncurses_attroff

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_attroff — Turn off the given attributes

Description

ncurses_attroff ( int $attributes ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

attributes


Turn on the given attributes

  • « ncurses_attroff
  • ncurses_attrset »
  • PHP Manual
  • Ncurses Functions
  • Turn on the given attributes

ncurses_attron

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_attron — Turn on the given attributes

Description

ncurses_attron ( int $attributes ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

attributes


Set given attributes

  • « ncurses_attron
  • ncurses_baudrate »
  • PHP Manual
  • Ncurses Functions
  • Set given attributes

ncurses_attrset

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_attrset — Set given attributes

Description

ncurses_attrset ( int $attributes ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

attributes


Returns baudrate of terminal

  • « ncurses_attrset
  • ncurses_beep »
  • PHP Manual
  • Ncurses Functions
  • Returns baudrate of terminal

ncurses_baudrate

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_baudrate — Returns baudrate of terminal

Description

ncurses_baudrate ( void ) : int
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.

Warning

This function is currently not documented; only its argument list is available.


Let the terminal beep

  • « ncurses_baudrate
  • ncurses_bkgd »
  • PHP Manual
  • Ncurses Functions
  • Let the terminal beep

ncurses_beep

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_beep — Let the terminal beep

Description

ncurses_beep ( void ) : int
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.

ncurses_beep() sends an audible alert (bell) and if its not possible flashes the screen.

See Also

  • ncurses_flash() - Flash terminal screen (visual bell)


Set background property for terminal screen

  • « ncurses_beep
  • ncurses_bkgdset »
  • PHP Manual
  • Ncurses Functions
  • Set background property for terminal screen

ncurses_bkgd

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_bkgd — Set background property for terminal screen

Description

ncurses_bkgd ( int $attrchar ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

attrchar


Control screen background

  • « ncurses_bkgd
  • ncurses_border »
  • PHP Manual
  • Ncurses Functions
  • Control screen background

ncurses_bkgdset

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_bkgdset — Control screen background

Description

ncurses_bkgdset ( int $attrchar ) : void
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

attrchar


Draw a border around the screen using attributed characters

  • « ncurses_bkgdset
  • ncurses_bottom_panel »
  • PHP Manual
  • Ncurses Functions
  • Draw a border around the screen using attributed characters

ncurses_border

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_border — Draw a border around the screen using attributed characters

Description

ncurses_border ( int $left , int $right , int $top , int $bottom , int $tl_corner , int $tr_corner , int $bl_corner , int $br_corner ) : int
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.

Draws the specified lines and corners around the main window.

Use ncurses_wborder() for borders around subwindows!

Parameters

Every parameter expects 0 to draw a line or 1 to skip it.

left

right

top

bottom

tl_corner

Top left corner

tr_corner

Top right corner

bl_corner

Bottom left corner

br_corner

Bottom right corner

See Also

  • ncurses_wborder() - Draws a border around the window using attributed characters


Moves a visible panel to the bottom of the stack

  • « ncurses_border
  • ncurses_can_change_color »
  • PHP Manual
  • Ncurses Functions
  • Moves a visible panel to the bottom of the stack

ncurses_bottom_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_bottom_panel — Moves a visible panel to the bottom of the stack

Description

ncurses_bottom_panel ( resource $panel ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

panel


Checks if terminal color definitions can be changed

  • « ncurses_bottom_panel
  • ncurses_cbreak »
  • PHP Manual
  • Ncurses Functions
  • Checks if terminal color definitions can be changed

ncurses_can_change_color

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_can_change_color — Checks if terminal color definitions can be changed

Description

ncurses_can_change_color ( void ) : bool

Checks whether the terminal has color capabilities and whether the programmer can change color definitions using ncurses_init_color(). ncurses must be initialized using ncurses_init() before calling this function.

Parameters

This function has no parameters.

Return Values

Return TRUE if the programmer can change color definitions, FALSE otherwise.

See Also

  • ncurses_has_colors() - Checks if terminal has color capabilities
  • ncurses_init_color() - Define a terminal color
  • ncurses_start_color() - Initializes color functionality


Switch off input buffering

  • « ncurses_can_change_color
  • ncurses_clear »
  • PHP Manual
  • Ncurses Functions
  • Switch off input buffering

ncurses_cbreak

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_cbreak — Switch off input buffering

Description

ncurses_cbreak ( void ) : bool
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.

Disables line buffering and character processing (interrupt and flow control characters are unaffected), making characters typed by the user immediately available to the program.

Return Values

Returns TRUE or NCURSES_ERR if any error occurred.

See Also

  • ncurses_nocbreak() - Switch terminal to cooked mode


Clear screen

  • « ncurses_cbreak
  • ncurses_clrtobot »
  • PHP Manual
  • Ncurses Functions
  • Clear screen

ncurses_clear

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_clear — Clear screen

Description

ncurses_clear ( void ) : bool
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.

Clears the screen completely without setting blanks.

Note: ncurses_clear() clears the screen without setting blanks, which have the current background rendition. To clear screen with blanks, use ncurses_erase().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ncurses_erase() - Erase terminal screen


Clear screen from current position to bottom

  • « ncurses_clear
  • ncurses_clrtoeol »
  • PHP Manual
  • Ncurses Functions
  • Clear screen from current position to bottom

ncurses_clrtobot

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_clrtobot — Clear screen from current position to bottom

Description

ncurses_clrtobot ( void ) : bool
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.

Erases all lines from cursor to end of screen and creates blanks. Blanks created by ncurses_clrtobot() have the current background rendition.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ncurses_clear() - Clear screen
  • ncurses_clrtoeol() - Clear screen from current position to end of line


Clear screen from current position to end of line

  • « ncurses_clrtobot
  • ncurses_color_content »
  • PHP Manual
  • Ncurses Functions
  • Clear screen from current position to end of line

ncurses_clrtoeol

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_clrtoeol — Clear screen from current position to end of line

Description

ncurses_clrtoeol ( void ) : bool
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.

Erases the current line from cursor position to the end. Blanks created by ncurses_clrtoeol() have the current background rendition.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ncurses_clear() - Clear screen
  • ncurses_clrtobot() - Clear screen from current position to bottom


Retrieves RGB components of a color

  • « ncurses_clrtoeol
  • ncurses_color_set »
  • PHP Manual
  • Ncurses Functions
  • Retrieves RGB components of a color

ncurses_color_content

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_color_content — Retrieves RGB components of a color

Description

ncurses_color_content ( int $color , int &$r , int &$g , int &$b ) : int

Retrieves the red, green, and blue components for the given color definition. Terminal color capabilities must be initialized with ncurses_start_color() prior to calling this function.

Parameters

color

The number of the color to retrieve information for. May be one of the pre-defined color constants.

r

A reference to which to return the red component of the color. The value returned to the reference will be between 0 and 1000.

g

A reference to which to return the green component of the color. The value returned to the reference will be between 0 and 1000.

b

A reference to which to return the blue component of the color. The value returned to the reference will be between 0 and 1000.

Return Values

Returns -1 if the function was successful, and 0 if ncurses or terminal color capabilities have not been initialized.

See Also

  • ncurses_init_color() - Define a terminal color
  • ncurses_start_color() - Initializes color functionality


Set active foreground and background colors

  • « ncurses_color_content
  • ncurses_curs_set »
  • PHP Manual
  • Ncurses Functions
  • Set active foreground and background colors

ncurses_color_set

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_color_set — Set active foreground and background colors

Description

ncurses_color_set ( int $pair ) : int

Sets the active foreground and background colors. Any characters written after this function is invoked will have these colors. This function requires terminal colors to be supported and initialized using ncurses_start_color() beforehand.

ncurses uses color pairs to specify both foreground and background colors. Use ncurses_init_pair() to define a color pair.

Parameters

pair

The color pair from which to get the foreground and background colors to set as the active colors.

Return Values

Returns -1 on success, and 0 on failure.

Examples

Example #1 Writing a string with a specified color to the screen

<?php
ncurses_init();

// If the terminal supports colors, initialize and set active color
if (ncurses_has_colors()) {
    ncurses_start_color();
    ncurses_init_pair(1, NCURSES_COLOR_YELLOW, NCURSES_COLOR_BLUE);
    ncurses_color_set(1);
}

// Write a string at specified location
ncurses_mvaddstr(10, 10, "Hello world! Yellow on blue text!");

// Flush output to screen
ncurses_refresh();

ncurses_end();
?>

See Also

  • ncurses_init_pair() - Define a color pair
  • ncurses_start_color() - Initializes color functionality


Set cursor state

  • « ncurses_color_set
  • ncurses_def_prog_mode »
  • PHP Manual
  • Ncurses Functions
  • Set cursor state

ncurses_curs_set

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_curs_set — Set cursor state

Description

ncurses_curs_set ( int $visibility ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

visibility


Saves terminals (program) mode

  • « ncurses_curs_set
  • ncurses_def_shell_mode »
  • PHP Manual
  • Ncurses Functions
  • Saves terminals (program) mode

ncurses_def_prog_mode

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_def_prog_mode — Saves terminals (program) mode

Description

ncurses_def_prog_mode ( void ) : bool
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.

Saves the current terminal modes for program (in curses) for use by ncurses_reset_prog_mode().

Return Values

Returns FALSE on success, otherwise TRUE.

See Also

  • ncurses_reset_prog_mode() - Resets the prog mode saved by def_prog_mode


Saves terminals (shell) mode

  • « ncurses_def_prog_mode
  • ncurses_define_key »
  • PHP Manual
  • Ncurses Functions
  • Saves terminals (shell) mode

ncurses_def_shell_mode

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_def_shell_mode — Saves terminals (shell) mode

Description

ncurses_def_shell_mode ( void ) : bool
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.

Saves the current terminal modes for shell (not in curses) for use by ncurses_reset_shell_mode().

Return Values

Returns FALSE on success, TRUE otherwise.

See Also

  • ncurses_reset_shell_mode() - Resets the shell mode saved by def_shell_mode


Define a keycode

  • « ncurses_def_shell_mode
  • ncurses_del_panel »
  • PHP Manual
  • Ncurses Functions
  • Define a keycode

ncurses_define_key

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_define_key — Define a keycode

Description

ncurses_define_key ( string $definition , int $keycode ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

definition

keycode


Remove panel from the stack and delete it (but not the associated window)

  • « ncurses_define_key
  • ncurses_delay_output »
  • PHP Manual
  • Ncurses Functions
  • Remove panel from the stack and delete it (but not the associated window)

ncurses_del_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_del_panel — Remove panel from the stack and delete it (but not the associated window)

Description

ncurses_del_panel ( resource $panel ) : bool
Warning

This function is currently not documented; only its argument list is available.

Parameters

panel


Delay output on terminal using padding characters

  • « ncurses_del_panel
  • ncurses_delch »
  • PHP Manual
  • Ncurses Functions
  • Delay output on terminal using padding characters

ncurses_delay_output

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_delay_output — Delay output on terminal using padding characters

Description

ncurses_delay_output ( int $milliseconds ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

milliseconds


Delete character at current position, move rest of line left

  • « ncurses_delay_output
  • ncurses_deleteln »
  • PHP Manual
  • Ncurses Functions
  • Delete character at current position, move rest of line left

ncurses_delch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_delch — Delete character at current position, move rest of line left

Description

ncurses_delch ( void ) : bool
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.

Deletes the character under the cursor. All characters to the right of the cursor on the same line are moved to the left one position and the last character on the line is filled with a blank. The cursor position does not change.

Return Values

Returns FALSE on success, TRUE otherwise.

See Also

  • ncurses_deleteln() - Delete line at current position, move rest of screen up


Delete line at current position, move rest of screen up

  • « ncurses_delch
  • ncurses_delwin »
  • PHP Manual
  • Ncurses Functions
  • Delete line at current position, move rest of screen up

ncurses_deleteln

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_deleteln — Delete line at current position, move rest of screen up

Description

ncurses_deleteln ( void ) : bool
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.

Deletes the current line under cursor position. All lines below the current line are moved up one line. The bottom line of window is cleared. Cursor position does not change.

Return Values

Returns FALSE on success, otherwise TRUE.

See Also

  • ncurses_delch() - Delete character at current position, move rest of line left


Delete a ncurses window

  • « ncurses_deleteln
  • ncurses_doupdate »
  • PHP Manual
  • Ncurses Functions
  • Delete a ncurses window

ncurses_delwin

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_delwin — Delete a ncurses window

Description

ncurses_delwin ( resource $window ) : bool
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

window


Write all prepared refreshes to terminal

  • « ncurses_delwin
  • ncurses_echo »
  • PHP Manual
  • Ncurses Functions
  • Write all prepared refreshes to terminal

ncurses_doupdate

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_doupdate — Write all prepared refreshes to terminal

Description

ncurses_doupdate ( void ) : bool
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.

Compares the virtual screen to the physical screen and updates the physical screen. This way is more effective than using multiple refresh calls.

Return Values

Returns TRUE on success or FALSE on failure.


Activate keyboard input echo

  • « ncurses_doupdate
  • ncurses_echochar »
  • PHP Manual
  • Ncurses Functions
  • Activate keyboard input echo

ncurses_echo

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_echo — Activate keyboard input echo

Description

ncurses_echo ( void ) : bool
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.

Enables echo mode. All characters typed by user are echoed by ncurses_getch().

Return Values

Returns FALSE on success, TRUE if any error occurred.

See Also

  • ncurses_noecho() - Switch off keyboard input echo to disable echo mode


Single character output including refresh

  • « ncurses_echo
  • ncurses_end »
  • PHP Manual
  • Ncurses Functions
  • Single character output including refresh

ncurses_echochar

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_echochar — Single character output including refresh

Description

ncurses_echochar ( int $character ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

character


Stop using ncurses, clean up the screen

  • « ncurses_echochar
  • ncurses_erase »
  • PHP Manual
  • Ncurses Functions
  • Stop using ncurses, clean up the screen

ncurses_end

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_end — Stop using ncurses, clean up the screen

Description

ncurses_end ( void ) : int
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.

Warning

This function is currently not documented; only its argument list is available.


Erase terminal screen

  • « ncurses_end
  • ncurses_erasechar »
  • PHP Manual
  • Ncurses Functions
  • Erase terminal screen

ncurses_erase

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_erase — Erase terminal screen

Description

ncurses_erase ( void ) : bool
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.

Fills the terminal screen with blanks.

Created blanks have the current background rendition, set by ncurses_bkgd().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ncurses_bkgd() - Set background property for terminal screen
  • ncurses_clear() - Clear screen


Returns current erase character

  • « ncurses_erase
  • ncurses_filter »
  • PHP Manual
  • Ncurses Functions
  • Returns current erase character

ncurses_erasechar

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_erasechar — Returns current erase character

Description

ncurses_erasechar ( void ) : string
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.

Returns the current erase character.

Return Values

The current erase char, as a string.

See Also

  • ncurses_killchar() - Returns current line kill character


Set LINES for iniscr() and newterm() to 1

  • « ncurses_erasechar
  • ncurses_flash »
  • PHP Manual
  • Ncurses Functions
  • Set LINES for iniscr() and newterm() to 1

ncurses_filter

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_filter — Set LINES for iniscr() and newterm() to 1

Description

ncurses_filter ( void ) : void
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.

Warning

This function is currently not documented; only its argument list is available.


Flash terminal screen (visual bell)

  • « ncurses_filter
  • ncurses_flushinp »
  • PHP Manual
  • Ncurses Functions
  • Flash terminal screen (visual bell)

ncurses_flash

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_flash — Flash terminal screen (visual bell)

Description

ncurses_flash ( void ) : bool
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.

Flashes the screen, and if its not possible, sends an audible alert (bell).

Return Values

Returns FALSE on success, otherwise TRUE.

See Also

  • ncurses_beep() - Let the terminal beep


Flush keyboard input buffer

  • « ncurses_flash
  • ncurses_getch »
  • PHP Manual
  • Ncurses Functions
  • Flush keyboard input buffer

ncurses_flushinp

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_flushinp — Flush keyboard input buffer

Description

ncurses_flushinp ( void ) : bool
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.

Throws away any typeahead that has been typed and has not yet been read by your program.

Return Values

Returns FALSE on success, otherwise TRUE.


Read a character from keyboard

  • « ncurses_flushinp
  • ncurses_getmaxyx »
  • PHP Manual
  • Ncurses Functions
  • Read a character from keyboard

ncurses_getch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_getch — Read a character from keyboard

Description

ncurses_getch ( void ) : int
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.

Warning

This function is currently not documented; only its argument list is available.


Returns the size of a window

  • « ncurses_getch
  • ncurses_getmouse »
  • PHP Manual
  • Ncurses Functions
  • Returns the size of a window

ncurses_getmaxyx

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_getmaxyx — Returns the size of a window

Description

ncurses_getmaxyx ( resource $window , int &$y , int &$x ) : void
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.

Gets the horizontal and vertical size of the given window into the given variables.

Variables must be passed as reference, so they are updated when the user changes the terminal size.

Parameters

window

The measured window

y

This will be set to the window height

x

This will be set to the window width

Return Values

No value is returned.


Reads mouse event

  • « ncurses_getmaxyx
  • ncurses_getyx »
  • PHP Manual
  • Ncurses Functions
  • Reads mouse event

ncurses_getmouse

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_getmouse — Reads mouse event

Description

ncurses_getmouse ( array &$mevent ) : bool
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.

ncurses_getmouse() reads mouse event out of queue.

Parameters

mevent

Event options will be delivered in this parameter which has to be an array, passed by reference (see example below).

On success an associative array with following keys will be delivered:

  • "id" : Id to distinguish multiple devices

  • "x" : screen relative x-position in character cells

  • "y" : screen relative y-position in character cells

  • "z" : currently not supported

  • "mmask" : Mouse action

Return Values

Returns FALSE if a mouse event is actually visible in the given window, otherwise returns TRUE.

Examples

Example #1 ncurses_getmouse() example

<?php
switch (ncurses_getch()){
  case NCURSES_KEY_MOUSE:
    if (!ncurses_getmouse($mevent)){
      if ($mevent["mmask"] & NCURSES_MOUSE_BUTTON1_PRESSED){
        $mouse_x = $mevent["x"]; // Save mouse position
        $mouse_y = $mevent["y"];
      }
    }
  break;

  default:
    /* .... */
}
?>

See Also

  • ncurses_ungetmouse() - Pushes mouse event to queue


Returns the current cursor position for a window

  • « ncurses_getmouse
  • ncurses_halfdelay »
  • PHP Manual
  • Ncurses Functions
  • Returns the current cursor position for a window

ncurses_getyx

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_getyx — Returns the current cursor position for a window

Description

ncurses_getyx ( resource $window , int &$y , int &$x ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

y

x


Put terminal into halfdelay mode

  • « ncurses_getyx
  • ncurses_has_colors »
  • PHP Manual
  • Ncurses Functions
  • Put terminal into halfdelay mode

ncurses_halfdelay

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_halfdelay — Put terminal into halfdelay mode

Description

ncurses_halfdelay ( int $tenth ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

tenth


Checks if terminal has color capabilities

  • « ncurses_halfdelay
  • ncurses_has_ic »
  • PHP Manual
  • Ncurses Functions
  • Checks if terminal has color capabilities

ncurses_has_colors

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_has_colors — Checks if terminal has color capabilities

Description

ncurses_has_colors ( void ) : bool

Checks whether the terminal has color capabilities. This function can be used to write terminal-independent programs. ncurses must be initialized using ncurses_init() before calling this function.

Parameters

This function has no parameters.

Return Values

Return TRUE if the terminal has color capabilities, FALSE otherwise.

Examples

Example #1 Writing a string with a specified color to the screen

<?php
ncurses_init();

// If the terminal supports colors, initialize and set active color
if (ncurses_has_colors()) {
    ncurses_start_color();
    ncurses_init_pair(1, NCURSES_COLOR_YELLOW, NCURSES_COLOR_BLUE);
    ncurses_color_set(1);
}

// Write a string at specified location
ncurses_mvaddstr(10, 10, "Hello world! Yellow on blue text!");

// Flush output to screen
ncurses_refresh();

ncurses_end();
?>

See Also

  • ncurses_can_change_color() - Checks if terminal color definitions can be changed
  • ncurses_start_color() - Initializes color functionality


Check for insert- and delete-capabilities

  • « ncurses_has_colors
  • ncurses_has_il »
  • PHP Manual
  • Ncurses Functions
  • Check for insert- and delete-capabilities

ncurses_has_ic

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_has_ic — Check for insert- and delete-capabilities

Description

ncurses_has_ic ( void ) : bool
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.

Checks whether the terminal has insert and delete capabilities.

Return Values

Returns TRUE if the terminal has insert/delete-capabilities, FALSE otherwise.

See Also

  • ncurses_has_il() - Check for line insert- and delete-capabilities


Check for line insert- and delete-capabilities

  • « ncurses_has_ic
  • ncurses_has_key »
  • PHP Manual
  • Ncurses Functions
  • Check for line insert- and delete-capabilities

ncurses_has_il

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_has_il — Check for line insert- and delete-capabilities

Description

ncurses_has_il ( void ) : bool
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.

Checks whether the terminal has insert- and delete-line-capabilities.

Return Values

Returns TRUE if the terminal has insert/delete-line capabilities, FALSE otherwise.

See Also

  • ncurses_has_ic() - Check for insert- and delete-capabilities


Check for presence of a function key on terminal keyboard

  • « ncurses_has_il
  • ncurses_hide_panel »
  • PHP Manual
  • Ncurses Functions
  • Check for presence of a function key on terminal keyboard

ncurses_has_key

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_has_key — Check for presence of a function key on terminal keyboard

Description

ncurses_has_key ( int $keycode ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

keycode


Remove panel from the stack, making it invisible

  • « ncurses_has_key
  • ncurses_hline »
  • PHP Manual
  • Ncurses Functions
  • Remove panel from the stack, making it invisible

ncurses_hide_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_hide_panel — Remove panel from the stack, making it invisible

Description

ncurses_hide_panel ( resource $panel ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

panel


Draw a horizontal line at current position using an attributed character and max. n characters long

  • « ncurses_hide_panel
  • ncurses_inch »
  • PHP Manual
  • Ncurses Functions
  • Draw a horizontal line at current position using an attributed character and max. n characters long

ncurses_hline

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_hline — Draw a horizontal line at current position using an attributed character and max. n characters long

Description

ncurses_hline ( int $charattr , int $n ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

charattr

n


Get character and attribute at current position

  • « ncurses_hline
  • ncurses_init_color »
  • PHP Manual
  • Ncurses Functions
  • Get character and attribute at current position

ncurses_inch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_inch — Get character and attribute at current position

Description

ncurses_inch ( void ) : string
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.

Returns the character from the current position.

Return Values

Returns the character, as a string.


Define a terminal color

  • « ncurses_inch
  • ncurses_init_pair »
  • PHP Manual
  • Ncurses Functions
  • Define a terminal color

ncurses_init_color

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_init_color — Define a terminal color

Description

ncurses_init_color ( int $color , int $r , int $g , int $b ) : int

Defines or redefines the given color. When this function is called, all occurrences of the given color on the screen, if any, immediately change to the new definition.

Color capabilities must be supported by the terminal and initialized using ncurses_start_color() prior to calling this function. In addition, the terminal must have color changing capabilities; use ncurses_can_change_color() to check for this.

Parameters

color

The identification number of the color to redefine. It may be one of the default color constants.

r

A color value, between 0 and 1000, for the red component.

g

A color value, between 0 and 1000, for the green component.

b

A color value, between 0 and 1000, for the blue component.

Return Values

Returns -1 if the function was successful, and 0 if ncurses or terminal color capabilities have not been initialized or the terminal does not have color changing capabilities.

See Also

  • ncurses_color_content() - Retrieves RGB components of a color
  • ncurses_start_color() - Initializes color functionality


Define a color pair

  • « ncurses_init_color
  • ncurses_init »
  • PHP Manual
  • Ncurses Functions
  • Define a color pair

ncurses_init_pair

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_init_pair — Define a color pair

Description

ncurses_init_pair ( int $pair , int $fg , int $bg ) : int

Defines or redefines the given color pair to have the given foreground and background colors. If the color pair was previously initialized, the screen is refreshed and all occurrences of it are changed to reflect the new definition.

Color capabilities must be initialized using ncurses_start_color() before calling this function. The first color pair (color pair 0) is assumed to be white on black by default, but can be changed using ncurses_assume_default_colors().

Parameters

pair

The number of the color pair to define.

fg

The foreground color for the color pair. May be one of the pre-defined colors or one defined by ncurses_init_color() if the terminal has color changing capabilities.

bg

The background color for the color pair. May be one of the pre-defined colors or one defined by ncurses_init_color() if the terminal has color changing capabilities.

Return Values

Returns -1 if the function was successful, and 0 if ncurses or color support were not initialized.

Notes

Note that color changing capabilities are not required for defining color pairs of pre-existing colors, but only for changing definitions (red, green, and blue components) of colors themselves per ncurses_init_color().

Examples

Example #1 Writing a string with a specified color to the screen

<?php
ncurses_init();

// If the terminal supports colors, initialize and set active color
if (ncurses_has_colors()) {
    ncurses_start_color();
    ncurses_init_pair(1, NCURSES_COLOR_YELLOW, NCURSES_COLOR_BLUE);
    ncurses_color_set(1);
}

// Write a string at specified location
ncurses_mvaddstr(10, 10, "Hello world! Yellow on blue text!");

// Flush output to screen
ncurses_refresh();

ncurses_end();
?>

See Also

  • ncurses_pair_content() - Retrieves foreground and background colors of a color pair
  • ncurses_start_color() - Initializes color functionality


Initialize ncurses

  • « ncurses_init_pair
  • ncurses_insch »
  • PHP Manual
  • Ncurses Functions
  • Initialize ncurses

ncurses_init

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_init — Initialize ncurses

Description

ncurses_init ( void ) : void

Initializes the ncurses interface. This function must be used before any other ncurses function call.

Note that ncurses_end() must be called before exiting from the program, or the terminal will not be restored to its proper non-visual mode.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • ncurses_end() - Stop using ncurses, clean up the screen


Insert character moving rest of line including character at current position

  • « ncurses_init
  • ncurses_insdelln »
  • PHP Manual
  • Ncurses Functions
  • Insert character moving rest of line including character at current position

ncurses_insch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_insch — Insert character moving rest of line including character at current position

Description

ncurses_insch ( int $character ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

character


Insert lines before current line scrolling down (negative numbers delete and scroll up)

  • « ncurses_insch
  • ncurses_insertln »
  • PHP Manual
  • Ncurses Functions
  • Insert lines before current line scrolling down (negative numbers delete and scroll up)

ncurses_insdelln

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_insdelln — Insert lines before current line scrolling down (negative numbers delete and scroll up)

Description

ncurses_insdelln ( int $count ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

count


Insert a line, move rest of screen down

  • « ncurses_insdelln
  • ncurses_insstr »
  • PHP Manual
  • Ncurses Functions
  • Insert a line, move rest of screen down

ncurses_insertln

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_insertln — Insert a line, move rest of screen down

Description

ncurses_insertln ( void ) : int
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.

Inserts a new line above the current line. The bottom line will be lost.


Insert string at current position, moving rest of line right

  • « ncurses_insertln
  • ncurses_instr »
  • PHP Manual
  • Ncurses Functions
  • Insert string at current position, moving rest of line right

ncurses_insstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_insstr — Insert string at current position, moving rest of line right

Description

ncurses_insstr ( string $text ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

text


Reads string from terminal screen

  • « ncurses_insstr
  • ncurses_isendwin »
  • PHP Manual
  • Ncurses Functions
  • Reads string from terminal screen

ncurses_instr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_instr — Reads string from terminal screen

Description

ncurses_instr ( string &$buffer ) : int
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.

Reads a string from the terminal screen and returns the number of characters read from the current character position until end of line.

Parameters

buffer

The characters. Attributes will be stripped.

Return Values

Returns the number of characters.


Ncurses is in endwin mode, normal screen output may be performed

  • « ncurses_instr
  • ncurses_keyok »
  • PHP Manual
  • Ncurses Functions
  • Ncurses is in endwin mode, normal screen output may be performed

ncurses_isendwin

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_isendwin — Ncurses is in endwin mode, normal screen output may be performed

Description

ncurses_isendwin ( void ) : bool
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.

Checks if ncurses is in endwin mode.

Return Values

Returns TRUE, if ncurses_end() has been called without any subsequent calls to ncurses_wrefresh(), FALSE otherwise.

See Also

  • ncurses_end() - Stop using ncurses, clean up the screen
  • ncurses_wrefresh() - Refresh window on terminal screen


Enable or disable a keycode

  • « ncurses_isendwin
  • ncurses_keypad »
  • PHP Manual
  • Ncurses Functions
  • Enable or disable a keycode

ncurses_keyok

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_keyok — Enable or disable a keycode

Description

ncurses_keyok ( int $keycode , bool $enable ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

keycode

enable


Turns keypad on or off

  • « ncurses_keyok
  • ncurses_killchar »
  • PHP Manual
  • Ncurses Functions
  • Turns keypad on or off

ncurses_keypad

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_keypad — Turns keypad on or off

Description

ncurses_keypad ( resource $window , bool $bf ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

bf


Returns current line kill character

  • « ncurses_keypad
  • ncurses_longname »
  • PHP Manual
  • Ncurses Functions
  • Returns current line kill character

ncurses_killchar

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_killchar — Returns current line kill character

Description

ncurses_killchar ( void ) : string
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.

Returns the current line kill character.

Return Values

Returns the kill character, as a string.

See Also

  • ncurses_erasechar() - Returns current erase character


Returns terminals description

  • « ncurses_killchar
  • ncurses_meta »
  • PHP Manual
  • Ncurses Functions
  • Returns terminals description

ncurses_longname

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_longname — Returns terminals description

Description

ncurses_longname ( void ) : string
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.

Returns a verbose description of the terminal.

Return Values

Returns the description, as a string truncated to 128 characters. On errors, returns NULL.

See Also

  • ncurses_termname() - Returns terminals (short)-name


Enables/Disable 8-bit meta key information

  • « ncurses_longname
  • ncurses_mouse_trafo »
  • PHP Manual
  • Ncurses Functions
  • Enables/Disable 8-bit meta key information

ncurses_meta

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_meta — Enables/Disable 8-bit meta key information

Description

ncurses_meta ( resource $window , bool $8bit ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

8bit


Transforms coordinates

  • « ncurses_meta
  • ncurses_mouseinterval »
  • PHP Manual
  • Ncurses Functions
  • Transforms coordinates

ncurses_mouse_trafo

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mouse_trafo — Transforms coordinates

Description

ncurses_mouse_trafo ( int &$y , int &$x , bool $toscreen ) : bool
Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

toscreen


Set timeout for mouse button clicks

  • « ncurses_mouse_trafo
  • ncurses_mousemask »
  • PHP Manual
  • Ncurses Functions
  • Set timeout for mouse button clicks

ncurses_mouseinterval

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mouseinterval — Set timeout for mouse button clicks

Description

ncurses_mouseinterval ( int $milliseconds ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

milliseconds


Sets mouse options

  • « ncurses_mouseinterval
  • ncurses_move_panel »
  • PHP Manual
  • Ncurses Functions
  • Sets mouse options

ncurses_mousemask

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mousemask — Sets mouse options

Description

ncurses_mousemask ( int $newmask , int &$oldmask ) : int
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.

Sets mouse events to be reported. By default no mouse events will be reported.

Mouse events are represented by NCURSES_KEY_MOUSE in the ncurses_wgetch() input stream. To read the event data and pop the event of queue, call ncurses_getmouse().

Parameters

newmask

Mouse mask options can be set with the following predefined constants:

  • NCURSES_BUTTON1_PRESSED

  • NCURSES_BUTTON1_RELEASED

  • NCURSES_BUTTON1_CLICKED

  • NCURSES_BUTTON1_DOUBLE_CLICKED

  • NCURSES_BUTTON1_TRIPLE_CLICKED

  • NCURSES_BUTTON2_PRESSED

  • NCURSES_BUTTON2_RELEASED

  • NCURSES_BUTTON2_CLICKED

  • NCURSES_BUTTON2_DOUBLE_CLICKED

  • NCURSES_BUTTON2_TRIPLE_CLICKED

  • NCURSES_BUTTON3_PRESSED

  • NCURSES_BUTTON3_RELEASED

  • NCURSES_BUTTON3_CLICKED

  • NCURSES_BUTTON3_DOUBLE_CLICKED

  • NCURSES_BUTTON3_TRIPLE_CLICKED

  • NCURSES_BUTTON4_PRESSED

  • NCURSES_BUTTON4_RELEASED

  • NCURSES_BUTTON4_CLICKED

  • NCURSES_BUTTON4_DOUBLE_CLICKED

  • NCURSES_BUTTON4_TRIPLE_CLICKED

  • NCURSES_BUTTON_SHIFT>

  • NCURSES_BUTTON_CTRL

  • NCURSES_BUTTON_ALT

  • NCURSES_ALL_MOUSE_EVENTS

  • NCURSES_REPORT_MOUSE_POSITION

As a side effect, setting a zero mousemask in newmask turns off the mouse pointer. Setting a non zero value turns mouse pointer on.

oldmask

This will be set to the previous value of the mouse event mask.

Return Values

Returns the mask of reportable events. On complete failure, it returns 0.

Examples

Example #1 ncurses_mousemask() example

<?php
$newmask = NCURSES_BUTTON1_CLICKED + NCURSES_BUTTON1_RELEASED;
$mask = ncurses_mousemask($newmask, $oldmask);
if ($mask & $newmask){
    printf("All specified mouse options will be supported\n");
}
?>

See Also

  • ncurses_getch() - Read a character from keyboard
  • ncurses_getmouse() - Reads mouse event
  • ncurses_ungetmouse() - Pushes mouse event to queue


Moves a panel so that its upper-left corner is at [startx, starty]

  • « ncurses_mousemask
  • ncurses_move »
  • PHP Manual
  • Ncurses Functions
  • Moves a panel so that its upper-left corner is at [startx, starty]

ncurses_move_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_move_panel — Moves a panel so that its upper-left corner is at [startx, starty]

Description

ncurses_move_panel ( resource $panel , int $startx , int $starty ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

panel

startx

starty


Move output position

  • « ncurses_move_panel
  • ncurses_mvaddch »
  • PHP Manual
  • Ncurses Functions
  • Move output position

ncurses_move

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_move — Move output position

Description

ncurses_move ( int $y , int $x ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x


Move current position and add character

  • « ncurses_move
  • ncurses_mvaddchnstr »
  • PHP Manual
  • Ncurses Functions
  • Move current position and add character

ncurses_mvaddch

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvaddch — Move current position and add character

Description

ncurses_mvaddch ( int $y , int $x , int $c ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

c


Move position and add attributed string with specified length

  • « ncurses_mvaddch
  • ncurses_mvaddchstr »
  • PHP Manual
  • Ncurses Functions
  • Move position and add attributed string with specified length

ncurses_mvaddchnstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvaddchnstr — Move position and add attributed string with specified length

Description

ncurses_mvaddchnstr ( int $y , int $x , string $s , int $n ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

s

n


Move position and add attributed string

  • « ncurses_mvaddchnstr
  • ncurses_mvaddnstr »
  • PHP Manual
  • Ncurses Functions
  • Move position and add attributed string

ncurses_mvaddchstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvaddchstr — Move position and add attributed string

Description

ncurses_mvaddchstr ( int $y , int $x , string $s ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

s


Move position and add string with specified length

  • « ncurses_mvaddchstr
  • ncurses_mvaddstr »
  • PHP Manual
  • Ncurses Functions
  • Move position and add string with specified length

ncurses_mvaddnstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvaddnstr — Move position and add string with specified length

Description

ncurses_mvaddnstr ( int $y , int $x , string $s , int $n ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

s

n


Move position and add string

  • « ncurses_mvaddnstr
  • ncurses_mvcur »
  • PHP Manual
  • Ncurses Functions
  • Move position and add string

ncurses_mvaddstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvaddstr — Move position and add string

Description

ncurses_mvaddstr ( int $y , int $x , string $s ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

s


Move cursor immediately

  • « ncurses_mvaddstr
  • ncurses_mvdelch »
  • PHP Manual
  • Ncurses Functions
  • Move cursor immediately

ncurses_mvcur

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvcur — Move cursor immediately

Description

ncurses_mvcur ( int $old_y , int $old_x , int $new_y , int $new_x ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

old_y

old_x

new_y

new_x


Move position and delete character, shift rest of line left

  • « ncurses_mvcur
  • ncurses_mvgetch »
  • PHP Manual
  • Ncurses Functions
  • Move position and delete character, shift rest of line left

ncurses_mvdelch

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvdelch — Move position and delete character, shift rest of line left

Description

ncurses_mvdelch ( int $y , int $x ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x


Move position and get character at new position

  • « ncurses_mvdelch
  • ncurses_mvhline »
  • PHP Manual
  • Ncurses Functions
  • Move position and get character at new position

ncurses_mvgetch

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvgetch — Move position and get character at new position

Description

ncurses_mvgetch ( int $y , int $x ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x


Set new position and draw a horizontal line using an attributed character and max. n characters long

  • « ncurses_mvgetch
  • ncurses_mvinch »
  • PHP Manual
  • Ncurses Functions
  • Set new position and draw a horizontal line using an attributed character and max. n characters long

ncurses_mvhline

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvhline — Set new position and draw a horizontal line using an attributed character and max. n characters long

Description

ncurses_mvhline ( int $y , int $x , int $attrchar , int $n ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

attrchar

n


Move position and get attributed character at new position

  • « ncurses_mvhline
  • ncurses_mvvline »
  • PHP Manual
  • Ncurses Functions
  • Move position and get attributed character at new position

ncurses_mvinch

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvinch — Move position and get attributed character at new position

Description

ncurses_mvinch ( int $y , int $x ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x


Set new position and draw a vertical line using an attributed character and max. n characters long

  • « ncurses_mvinch
  • ncurses_mvwaddstr »
  • PHP Manual
  • Ncurses Functions
  • Set new position and draw a vertical line using an attributed character and max. n characters long

ncurses_mvvline

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvvline — Set new position and draw a vertical line using an attributed character and max. n characters long

Description

ncurses_mvvline ( int $y , int $x , int $attrchar , int $n ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

y

x

attrchar

n


Add string at new position in window

  • « ncurses_mvvline
  • ncurses_napms »
  • PHP Manual
  • Ncurses Functions
  • Add string at new position in window

ncurses_mvwaddstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvwaddstr — Add string at new position in window

Description

ncurses_mvwaddstr ( resource $window , int $y , int $x , string $text ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

window

y

x

text


Sleep

  • « ncurses_mvwaddstr
  • ncurses_new_panel »
  • PHP Manual
  • Ncurses Functions
  • Sleep

ncurses_napms

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_napms — Sleep

Description

ncurses_napms ( int $milliseconds ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

milliseconds


Create a new panel and associate it with window

  • « ncurses_napms
  • ncurses_newpad »
  • PHP Manual
  • Ncurses Functions
  • Create a new panel and associate it with window

ncurses_new_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_new_panel — Create a new panel and associate it with window

Description

ncurses_new_panel ( resource $window ) : resource
Warning

This function is currently not documented; only its argument list is available.

Parameters

window


Creates a new pad (window)

  • « ncurses_new_panel
  • ncurses_newwin »
  • PHP Manual
  • Ncurses Functions
  • Creates a new pad (window)

ncurses_newpad

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_newpad — Creates a new pad (window)

Description

ncurses_newpad ( int $rows , int $cols ) : resource
Warning

This function is currently not documented; only its argument list is available.

Parameters

rows

cols


Create a new window

  • « ncurses_newpad
  • ncurses_nl »
  • PHP Manual
  • Ncurses Functions
  • Create a new window

ncurses_newwin

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_newwin — Create a new window

Description

ncurses_newwin ( int $rows , int $cols , int $y , int $x ) : resource
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.

Creates a new window to draw elements in.

When creating additional windows, remember to use ncurses_getmaxyx() to check for available space, as terminal size is individual and may vary.

Parameters

rows

Number of rows

cols

Number of columns

y

y-coordinate of the origin

x

x-coordinate of the origin

Return Values

Returns a resource ID for the new window.


Translate newline and carriage return / line feed

  • « ncurses_newwin
  • ncurses_nocbreak »
  • PHP Manual
  • Ncurses Functions
  • Translate newline and carriage return / line feed

ncurses_nl

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_nl — Translate newline and carriage return / line feed

Description

ncurses_nl ( void ) : bool
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.

Warning

This function is currently not documented; only its argument list is available.


Switch terminal to cooked mode

  • « ncurses_nl
  • ncurses_noecho »
  • PHP Manual
  • Ncurses Functions
  • Switch terminal to cooked mode

ncurses_nocbreak

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_nocbreak — Switch terminal to cooked mode

Description

ncurses_nocbreak ( void ) : bool
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.

Returns terminal to normal (cooked) mode. Initially the terminal may or may not be in cbreak mode as the mode is inherited. Therefore a program should call ncurses_cbreak() and ncurses_nocbreak() explicitly.

Return Values

Returns TRUE if any error occurred, otherwise FALSE.

See Also

  • ncurses_cbreak() - Switch off input buffering


Switch off keyboard input echo

  • « ncurses_nocbreak
  • ncurses_nonl »
  • PHP Manual
  • Ncurses Functions
  • Switch off keyboard input echo

ncurses_noecho

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_noecho — Switch off keyboard input echo

Description

ncurses_noecho ( void ) : bool
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.

Prevents echoing of user typed characters.

Return Values

Returns TRUE if any error occurred, FALSE otherwise.

See Also

  • ncurses_echo() - Activate keyboard input echo
  • ncurses_getch() - Read a character from keyboard


Do not translate newline and carriage return / line feed

  • « ncurses_noecho
  • ncurses_noqiflush »
  • PHP Manual
  • Ncurses Functions
  • Do not translate newline and carriage return / line feed

ncurses_nonl

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_nonl — Do not translate newline and carriage return / line feed

Description

ncurses_nonl ( void ) : bool
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.

Warning

This function is currently not documented; only its argument list is available.


Do not flush on signal characters

  • « ncurses_nonl
  • ncurses_noraw »
  • PHP Manual
  • Ncurses Functions
  • Do not flush on signal characters

ncurses_noqiflush

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_noqiflush — Do not flush on signal characters

Description

ncurses_noqiflush ( void ) : void
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.

Warning

This function is currently not documented; only its argument list is available.


Switch terminal out of raw mode

  • « ncurses_noqiflush
  • ncurses_pair_content »
  • PHP Manual
  • Ncurses Functions
  • Switch terminal out of raw mode

ncurses_noraw

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_noraw — Switch terminal out of raw mode

Description

ncurses_noraw ( void ) : bool
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.

Switches the terminal out of raw mode. Raw mode is similar to cbreak mode, in that characters typed are immediately passed through to the user program. The difference is that in raw mode, the interrupt, quit, suspend and flow control characters are all passed through uninterpreted, instead of generating a signal.

Return Values

Returns TRUE if any error occurred, otherwise FALSE.

See Also

  • ncurses_raw() - Switch terminal into raw mode
  • ncurses_cbreak() - Switch off input buffering
  • ncurses_nocbreak() - Switch terminal to cooked mode


Retrieves foreground and background colors of a color pair

  • « ncurses_noraw
  • ncurses_panel_above »
  • PHP Manual
  • Ncurses Functions
  • Retrieves foreground and background colors of a color pair

ncurses_pair_content

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_pair_content — Retrieves foreground and background colors of a color pair

Description

ncurses_pair_content ( int $pair , int &$f , int &$b ) : int

Retrieves the foreground and background colors that constitute the given color pair. Terminal color capabilities must be initialized with ncurses_start_color() prior to calling this function.

Parameters

pair

The number of the color pair to retrieve information for.

f

A reference to which to return the foreground color of the color pair. The information returned will be a color number referring to one of the pre-defined colors or a color defined previously by ncurses_init_color() if the terminal supports color changing.

b

A reference to which to return the background color of the color pair. The information returned will be a color number referring to one of the pre-defined colors or a color defined previously by ncurses_init_color() if the terminal supports color changing.

Return Values

Returns -1 if the function was successful, and 0 if ncurses or terminal color capabilities have not been initialized.

See Also

  • ncurses_init_pair() - Define a color pair
  • ncurses_start_color() - Initializes color functionality


Returns the panel above panel

  • « ncurses_pair_content
  • ncurses_panel_below »
  • PHP Manual
  • Ncurses Functions
  • Returns the panel above panel

ncurses_panel_above

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_panel_above — Returns the panel above panel

Description

ncurses_panel_above ( resource $panel ) : resource
Warning

This function is currently not documented; only its argument list is available.

Parameters

panel

Return Values

If panel is null, returns the bottom panel in the stack.


Returns the panel below panel

  • « ncurses_panel_above
  • ncurses_panel_window »
  • PHP Manual
  • Ncurses Functions
  • Returns the panel below panel

ncurses_panel_below

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_panel_below — Returns the panel below panel

Description

ncurses_panel_below ( resource $panel ) : resource
Warning

This function is currently not documented; only its argument list is available.

Parameters

panel

Parameters

If panel is null, returns the top panel in the stack.


Returns the window associated with panel

  • « ncurses_panel_below
  • ncurses_pnoutrefresh »
  • PHP Manual
  • Ncurses Functions
  • Returns the window associated with panel

ncurses_panel_window

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_panel_window — Returns the window associated with panel

Description

ncurses_panel_window ( resource $panel ) : resource
Warning

This function is currently not documented; only its argument list is available.

Parameters

panel


Copies a region from a pad into the virtual screen

  • « ncurses_panel_window
  • ncurses_prefresh »
  • PHP Manual
  • Ncurses Functions
  • Copies a region from a pad into the virtual screen

ncurses_pnoutrefresh

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_pnoutrefresh — Copies a region from a pad into the virtual screen

Description

ncurses_pnoutrefresh ( resource $pad , int $pminrow , int $pmincol , int $sminrow , int $smincol , int $smaxrow , int $smaxcol ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

pad

pminrow

pmincol

sminrow

smincol

smaxrow

smaxcol


Copies a region from a pad into the virtual screen

  • « ncurses_pnoutrefresh
  • ncurses_putp »
  • PHP Manual
  • Ncurses Functions
  • Copies a region from a pad into the virtual screen

ncurses_prefresh

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_prefresh — Copies a region from a pad into the virtual screen

Description

ncurses_prefresh ( resource $pad , int $pminrow , int $pmincol , int $sminrow , int $smincol , int $smaxrow , int $smaxcol ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

pad

pminrow

pmincol

sminrow

smincol

smaxrow

smaxcol


Apply padding information to the string and output it

  • « ncurses_prefresh
  • ncurses_qiflush »
  • PHP Manual
  • Ncurses Functions
  • Apply padding information to the string and output it

ncurses_putp

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_putp — Apply padding information to the string and output it

Description

ncurses_putp ( string $text ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

text


Flush on signal characters

  • « ncurses_putp
  • ncurses_raw »
  • PHP Manual
  • Ncurses Functions
  • Flush on signal characters

ncurses_qiflush

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_qiflush — Flush on signal characters

Description

ncurses_qiflush ( void ) : void
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.

Warning

This function is currently not documented; only its argument list is available.


Switch terminal into raw mode

  • « ncurses_qiflush
  • ncurses_refresh »
  • PHP Manual
  • Ncurses Functions
  • Switch terminal into raw mode

ncurses_raw

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_raw — Switch terminal into raw mode

Description

ncurses_raw ( void ) : bool
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.

Places the terminal in raw mode. Raw mode is similar to cbreak mode, in that characters typed are immediately passed through to the user program. The difference is that in raw mode, the interrupt, quit, suspend and flow control characters are all passed through uninterpreted, instead of generating a signal.

Return Values

Returns TRUE if any error occurred, otherwise FALSE.

See Also

  • ncurses_noraw() - Switch terminal out of raw mode
  • ncurses_cbreak() - Switch off input buffering
  • ncurses_nocbreak() - Switch terminal to cooked mode


Refresh screen

  • « ncurses_raw
  • ncurses_replace_panel »
  • PHP Manual
  • Ncurses Functions
  • Refresh screen

ncurses_refresh

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_refresh — Refresh screen

Description

ncurses_refresh ( int $ch ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

ch


Replaces the window associated with panel

  • « ncurses_refresh
  • ncurses_reset_prog_mode »
  • PHP Manual
  • Ncurses Functions
  • Replaces the window associated with panel

ncurses_replace_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_replace_panel — Replaces the window associated with panel

Description

ncurses_replace_panel ( resource $panel , resource $window ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

panel

window


Resets the prog mode saved by def_prog_mode

  • « ncurses_replace_panel
  • ncurses_reset_shell_mode »
  • PHP Manual
  • Ncurses Functions
  • Resets the prog mode saved by def_prog_mode

ncurses_reset_prog_mode

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_reset_prog_mode — Resets the prog mode saved by def_prog_mode

Description

ncurses_reset_prog_mode ( void ) : int
Warning

This function is currently not documented; only its argument list is available.


Resets the shell mode saved by def_shell_mode

  • « ncurses_reset_prog_mode
  • ncurses_resetty »
  • PHP Manual
  • Ncurses Functions
  • Resets the shell mode saved by def_shell_mode

ncurses_reset_shell_mode

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_reset_shell_mode — Resets the shell mode saved by def_shell_mode

Description

ncurses_reset_shell_mode ( void ) : int
Warning

This function is currently not documented; only its argument list is available.


Restores saved terminal state

  • « ncurses_reset_shell_mode
  • ncurses_savetty »
  • PHP Manual
  • Ncurses Functions
  • Restores saved terminal state

ncurses_resetty

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_resetty — Restores saved terminal state

Description

ncurses_resetty ( void ) : bool
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.

Restores the terminal state, which was previously saved by calling ncurses_savetty().

Return Values

Always returns FALSE.

See Also

  • ncurses_savetty() - Saves terminal state


Saves terminal state

  • « ncurses_resetty
  • ncurses_scr_dump »
  • PHP Manual
  • Ncurses Functions
  • Saves terminal state

ncurses_savetty

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_savetty — Saves terminal state

Description

ncurses_savetty ( void ) : bool
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.

Saves the current terminal state. The saved terminal state can be restored with ncurses_resetty().

Return Values

Always returns FALSE.

See Also

  • ncurses_resetty() - Restores saved terminal state


Dump screen content to file

  • « ncurses_savetty
  • ncurses_scr_init »
  • PHP Manual
  • Ncurses Functions
  • Dump screen content to file

ncurses_scr_dump

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_scr_dump — Dump screen content to file

Description

ncurses_scr_dump ( string $filename ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

filename


Initialize screen from file dump

  • « ncurses_scr_dump
  • ncurses_scr_restore »
  • PHP Manual
  • Ncurses Functions
  • Initialize screen from file dump

ncurses_scr_init

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_scr_init — Initialize screen from file dump

Description

ncurses_scr_init ( string $filename ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

filename


Restore screen from file dump

  • « ncurses_scr_init
  • ncurses_scr_set »
  • PHP Manual
  • Ncurses Functions
  • Restore screen from file dump

ncurses_scr_restore

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_scr_restore — Restore screen from file dump

Description

ncurses_scr_restore ( string $filename ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

filename


Inherit screen from file dump

  • « ncurses_scr_restore
  • ncurses_scrl »
  • PHP Manual
  • Ncurses Functions
  • Inherit screen from file dump

ncurses_scr_set

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_scr_set — Inherit screen from file dump

Description

ncurses_scr_set ( string $filename ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

filename


Scroll window content up or down without changing current position

  • « ncurses_scr_set
  • ncurses_show_panel »
  • PHP Manual
  • Ncurses Functions
  • Scroll window content up or down without changing current position

ncurses_scrl

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_scrl — Scroll window content up or down without changing current position

Description

ncurses_scrl ( int $count ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

count


Places an invisible panel on top of the stack, making it visible

  • « ncurses_scrl
  • ncurses_slk_attr »
  • PHP Manual
  • Ncurses Functions
  • Places an invisible panel on top of the stack, making it visible

ncurses_show_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_show_panel — Places an invisible panel on top of the stack, making it visible

Description

ncurses_show_panel ( resource $panel ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

panel


Returns current soft label key attribute

  • « ncurses_show_panel
  • ncurses_slk_attroff »
  • PHP Manual
  • Ncurses Functions
  • Returns current soft label key attribute

ncurses_slk_attr

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_attr — Returns current soft label key attribute

Description

ncurses_slk_attr ( void ) : int
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.

Returns the current soft label key attribute.

Return Values

The attribute, as an integer.


Turn off the given attributes for soft function-key labels

  • « ncurses_slk_attr
  • ncurses_slk_attron »
  • PHP Manual
  • Ncurses Functions
  • Turn off the given attributes for soft function-key labels

ncurses_slk_attroff

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_attroff — Turn off the given attributes for soft function-key labels

Description

ncurses_slk_attroff ( int $intarg ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

intarg


Turn on the given attributes for soft function-key labels

  • « ncurses_slk_attroff
  • ncurses_slk_attrset »
  • PHP Manual
  • Ncurses Functions
  • Turn on the given attributes for soft function-key labels

ncurses_slk_attron

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_attron — Turn on the given attributes for soft function-key labels

Description

ncurses_slk_attron ( int $intarg ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

intarg


Set given attributes for soft function-key labels

  • « ncurses_slk_attron
  • ncurses_slk_clear »
  • PHP Manual
  • Ncurses Functions
  • Set given attributes for soft function-key labels

ncurses_slk_attrset

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_attrset — Set given attributes for soft function-key labels

Description

ncurses_slk_attrset ( int $intarg ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

intarg


Clears soft labels from screen

  • « ncurses_slk_attrset
  • ncurses_slk_color »
  • PHP Manual
  • Ncurses Functions
  • Clears soft labels from screen

ncurses_slk_clear

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_clear — Clears soft labels from screen

Description

ncurses_slk_clear ( void ) : bool
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.

The function ncurses_slk_clear() clears soft label keys from screen.

Return Values

Returns TRUE on errors, FALSE otherwise.


Sets color for soft label keys

  • « ncurses_slk_clear
  • ncurses_slk_init »
  • PHP Manual
  • Ncurses Functions
  • Sets color for soft label keys

ncurses_slk_color

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_color — Sets color for soft label keys

Description

ncurses_slk_color ( int $intarg ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

intarg


Initializes soft label key functions

  • « ncurses_slk_color
  • ncurses_slk_noutrefresh »
  • PHP Manual
  • Ncurses Functions
  • Initializes soft label key functions

ncurses_slk_init

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_init — Initializes soft label key functions

Description

ncurses_slk_init ( int $format ) : bool
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.

Initializes soft label key functions

This function must be called before ncurses_init() or ncurses_newwin() is called.

Parameters

format

If ncurses_init() eventually uses a line from stdscr to emulate the soft labels, then this parameter determines how the labels are arranged of the screen.

0 indicates a 3-2-3 arrangement of the labels, 1 indicates a 4-4 arrangement and 2 indicates the PC like 4-4-4 mode, but in addition an index line will be created.

Return Values

Returns TRUE on success or FALSE on failure.


Copies soft label keys to virtual screen

  • « ncurses_slk_init
  • ncurses_slk_refresh »
  • PHP Manual
  • Ncurses Functions
  • Copies soft label keys to virtual screen

ncurses_slk_noutrefresh

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_noutrefresh — Copies soft label keys to virtual screen

Description

ncurses_slk_noutrefresh ( void ) : bool
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.

Warning

This function is currently not documented; only its argument list is available.


Copies soft label keys to screen

  • « ncurses_slk_noutrefresh
  • ncurses_slk_restore »
  • PHP Manual
  • Ncurses Functions
  • Copies soft label keys to screen

ncurses_slk_refresh

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_refresh — Copies soft label keys to screen

Description

ncurses_slk_refresh ( void ) : int
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.

Copies soft label keys from virtual screen to physical screen.


Restores soft label keys

  • « ncurses_slk_refresh
  • ncurses_slk_set »
  • PHP Manual
  • Ncurses Functions
  • Restores soft label keys

ncurses_slk_restore

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_restore — Restores soft label keys

Description

ncurses_slk_restore ( void ) : int
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.

Restores the soft label keys after ncurses_slk_clear() has been performed.


Sets function key labels

  • « ncurses_slk_restore
  • ncurses_slk_touch »
  • PHP Manual
  • Ncurses Functions
  • Sets function key labels

ncurses_slk_set

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_set — Sets function key labels

Description

ncurses_slk_set ( int $labelnr , string $label , int $format ) : bool
Warning

This function is currently not documented; only its argument list is available.

Parameters

labelnr

label

format


Forces output when ncurses_slk_noutrefresh is performed

  • « ncurses_slk_set
  • ncurses_standend »
  • PHP Manual
  • Ncurses Functions
  • Forces output when ncurses_slk_noutrefresh is performed

ncurses_slk_touch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_touch — Forces output when ncurses_slk_noutrefresh is performed

Description

ncurses_slk_touch ( void ) : int
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.

Forces all the soft labels to be output the next time a ncurses_slk_noutrefresh() is performed.


Stop using 'standout' attribute

  • « ncurses_slk_touch
  • ncurses_standout »
  • PHP Manual
  • Ncurses Functions
  • Stop using 'standout' attribute

ncurses_standend

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_standend — Stop using 'standout' attribute

Description

ncurses_standend ( void ) : int
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.

Warning

This function is currently not documented; only its argument list is available.


Start using 'standout' attribute

  • « ncurses_standend
  • ncurses_start_color »
  • PHP Manual
  • Ncurses Functions
  • Start using 'standout' attribute

ncurses_standout

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_standout — Start using 'standout' attribute

Description

ncurses_standout ( void ) : int
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.

Warning

This function is currently not documented; only its argument list is available.


Initializes color functionality

  • « ncurses_standout
  • ncurses_termattrs »
  • PHP Manual
  • Ncurses Functions
  • Initializes color functionality

ncurses_start_color

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_start_color — Initializes color functionality

Description

ncurses_start_color ( void ) : int

Initializes color functionality in ncurses. This function must be called before any color manipulation functions are called and after ncurses_init() is called. It is good practice to call this function right after ncurses_init().

Parameters

This function has no parameters.

Return Values

Returns 0 on success, or -1 if the color table could not be allocated or ncurses was not initialized.

Examples

Example #1 Writing a string with a specified color to the screen

<?php
ncurses_init();

// If the terminal supports colors, initialize and set active color
if (ncurses_has_colors()) {
    ncurses_start_color();
    ncurses_init_pair(1, NCURSES_COLOR_YELLOW, NCURSES_COLOR_BLUE);
    ncurses_color_set(1);
}

// Write a string at specified location
ncurses_mvaddstr(10, 10, "Hello world! Yellow on blue text!");

// Flush output to screen
ncurses_refresh();

ncurses_end();
?>

See Also

  • ncurses_can_change_color() - Checks if terminal color definitions can be changed
  • ncurses_has_colors() - Checks if terminal has color capabilities


Returns a logical OR of all attribute flags supported by terminal

  • « ncurses_start_color
  • ncurses_termname »
  • PHP Manual
  • Ncurses Functions
  • Returns a logical OR of all attribute flags supported by terminal

ncurses_termattrs

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_termattrs — Returns a logical OR of all attribute flags supported by terminal

Description

ncurses_termattrs ( void ) : bool
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.

Warning

This function is currently not documented; only its argument list is available.


Returns terminals (short)-name

  • « ncurses_termattrs
  • ncurses_timeout »
  • PHP Manual
  • Ncurses Functions
  • Returns terminals (short)-name

ncurses_termname

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_termname — Returns terminals (short)-name

Description

ncurses_termname ( void ) : string
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.

Returns terminals shortname.

Return Values

Returns the shortname of the terminal, truncated to 14 characters. On errors, returns NULL.

See Also

  • ncurses_longname() - Returns terminals description


Set timeout for special key sequences

  • « ncurses_termname
  • ncurses_top_panel »
  • PHP Manual
  • Ncurses Functions
  • Set timeout for special key sequences

ncurses_timeout

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_timeout — Set timeout for special key sequences

Description

ncurses_timeout ( int $millisec ) : void
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

millisec


Moves a visible panel to the top of the stack

  • « ncurses_timeout
  • ncurses_typeahead »
  • PHP Manual
  • Ncurses Functions
  • Moves a visible panel to the top of the stack

ncurses_top_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_top_panel — Moves a visible panel to the top of the stack

Description

ncurses_top_panel ( resource $panel ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

panel


Specify different filedescriptor for typeahead checking

  • « ncurses_top_panel
  • ncurses_ungetch »
  • PHP Manual
  • Ncurses Functions
  • Specify different filedescriptor for typeahead checking

ncurses_typeahead

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_typeahead — Specify different filedescriptor for typeahead checking

Description

ncurses_typeahead ( int $fd ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

fd


Put a character back into the input stream

  • « ncurses_typeahead
  • ncurses_ungetmouse »
  • PHP Manual
  • Ncurses Functions
  • Put a character back into the input stream

ncurses_ungetch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_ungetch — Put a character back into the input stream

Description

ncurses_ungetch ( int $keycode ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

keycode


Pushes mouse event to queue

  • « ncurses_ungetch
  • ncurses_update_panels »
  • PHP Manual
  • Ncurses Functions
  • Pushes mouse event to queue

ncurses_ungetmouse

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_ungetmouse — Pushes mouse event to queue

Description

ncurses_ungetmouse ( array $mevent ) : bool
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.

Pushes a KEY_MOUSE event onto the input queue and associates with this event the given state data and screen-relative character cell coordinates, specified in mevent.

Parameters

mevent

An associative array specifying the event options:

  • "id" : Id to distinguish multiple devices

  • "x" : screen relative x-position in character cells

  • "y" : screen relative y-position in character cells

  • "z" : currently not supported

  • "mmask" : Mouse action

Return Values

Returns FALSE on success, TRUE otherwise.

See Also

  • ncurses_getmouse() - Reads mouse event


Refreshes the virtual screen to reflect the relations between panels in the stack

  • « ncurses_ungetmouse
  • ncurses_use_default_colors »
  • PHP Manual
  • Ncurses Functions
  • Refreshes the virtual screen to reflect the relations between panels in the stack

ncurses_update_panels

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_update_panels — Refreshes the virtual screen to reflect the relations between panels in the stack

Description

ncurses_update_panels ( void ) : void
Warning

This function is currently not documented; only its argument list is available.


Assign terminal default colors to color id -1

  • « ncurses_update_panels
  • ncurses_use_env »
  • PHP Manual
  • Ncurses Functions
  • Assign terminal default colors to color id -1

ncurses_use_default_colors

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_use_default_colors — Assign terminal default colors to color id -1

Description

ncurses_use_default_colors ( void ) : bool
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.

Warning

This function is currently not documented; only its argument list is available.


Control use of environment information about terminal size

  • « ncurses_use_default_colors
  • ncurses_use_extended_names »
  • PHP Manual
  • Ncurses Functions
  • Control use of environment information about terminal size

ncurses_use_env

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_use_env — Control use of environment information about terminal size

Description

ncurses_use_env ( bool $flag ) : void
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

flag


Control use of extended names in terminfo descriptions

  • « ncurses_use_env
  • ncurses_vidattr »
  • PHP Manual
  • Ncurses Functions
  • Control use of extended names in terminfo descriptions

ncurses_use_extended_names

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_use_extended_names — Control use of extended names in terminfo descriptions

Description

ncurses_use_extended_names ( bool $flag ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

flag


Display the string on the terminal in the video attribute mode

  • « ncurses_use_extended_names
  • ncurses_vline »
  • PHP Manual
  • Ncurses Functions
  • Display the string on the terminal in the video attribute mode

ncurses_vidattr

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_vidattr — Display the string on the terminal in the video attribute mode

Description

ncurses_vidattr ( int $intarg ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

intarg


Draw a vertical line at current position using an attributed character and max. n characters long

  • « ncurses_vidattr
  • ncurses_waddch »
  • PHP Manual
  • Ncurses Functions
  • Draw a vertical line at current position using an attributed character and max. n characters long

ncurses_vline

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_vline — Draw a vertical line at current position using an attributed character and max. n characters long

Description

ncurses_vline ( int $charattr , int $n ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

charattr

n


Adds character at current position in a window and advance cursor

  • « ncurses_vline
  • ncurses_waddstr »
  • PHP Manual
  • Ncurses Functions
  • Adds character at current position in a window and advance cursor

ncurses_waddch

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_waddch — Adds character at current position in a window and advance cursor

Description

ncurses_waddch ( resource $window , int $ch ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

ch


Outputs text at current postion in window

  • « ncurses_waddch
  • ncurses_wattroff »
  • PHP Manual
  • Ncurses Functions
  • Outputs text at current postion in window

ncurses_waddstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_waddstr — Outputs text at current postion in window

Description

ncurses_waddstr ( resource $window , string $str [, int $n ] ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

str

n


Turns off attributes for a window

  • « ncurses_waddstr
  • ncurses_wattron »
  • PHP Manual
  • Ncurses Functions
  • Turns off attributes for a window

ncurses_wattroff

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wattroff — Turns off attributes for a window

Description

ncurses_wattroff ( resource $window , int $attrs ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

attrs


Turns on attributes for a window

  • « ncurses_wattroff
  • ncurses_wattrset »
  • PHP Manual
  • Ncurses Functions
  • Turns on attributes for a window

ncurses_wattron

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wattron — Turns on attributes for a window

Description

ncurses_wattron ( resource $window , int $attrs ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

attrs


Set the attributes for a window

  • « ncurses_wattron
  • ncurses_wborder »
  • PHP Manual
  • Ncurses Functions
  • Set the attributes for a window

ncurses_wattrset

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wattrset — Set the attributes for a window

Description

ncurses_wattrset ( resource $window , int $attrs ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

attrs


Draws a border around the window using attributed characters

  • « ncurses_wattrset
  • ncurses_wclear »
  • PHP Manual
  • Ncurses Functions
  • Draws a border around the window using attributed characters

ncurses_wborder

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wborder — Draws a border around the window using attributed characters

Description

ncurses_wborder ( resource $window , int $left , int $right , int $top , int $bottom , int $tl_corner , int $tr_corner , int $bl_corner , int $br_corner ) : int
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.

Draws the specified lines and corners around the passed window.

Use ncurses_border() for borders around the main window.

Parameters

Each parameter expects 0 to draw a line and 1 to skip it.

window

The window on which we operate

left

right

top

bottom

tl_corner

Top left corner

tr_corner

Top right corner

bl_corner

Bottom left corner

br_corner

Bottom right corner

See Also

  • ncurses_border() - Draw a border around the screen using attributed characters


Clears window

  • « ncurses_wborder
  • ncurses_wcolor_set »
  • PHP Manual
  • Ncurses Functions
  • Clears window

ncurses_wclear

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wclear — Clears window

Description

ncurses_wclear ( resource $window ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

window


Sets windows color pairings

  • « ncurses_wclear
  • ncurses_werase »
  • PHP Manual
  • Ncurses Functions
  • Sets windows color pairings

ncurses_wcolor_set

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wcolor_set — Sets windows color pairings

Description

ncurses_wcolor_set ( resource $window , int $color_pair ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

color_pair


Erase window contents

  • « ncurses_wcolor_set
  • ncurses_wgetch »
  • PHP Manual
  • Ncurses Functions
  • Erase window contents

ncurses_werase

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_werase — Erase window contents

Description

ncurses_werase ( resource $window ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

window


Reads a character from keyboard (window)

  • « ncurses_werase
  • ncurses_whline »
  • PHP Manual
  • Ncurses Functions
  • Reads a character from keyboard (window)

ncurses_wgetch

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wgetch — Reads a character from keyboard (window)

Description

ncurses_wgetch ( resource $window ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

window


Draws a horizontal line in a window at current position using an attributed character and max. n characters long

  • « ncurses_wgetch
  • ncurses_wmouse_trafo »
  • PHP Manual
  • Ncurses Functions
  • Draws a horizontal line in a window at current position using an attributed character and max. n characters long

ncurses_whline

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_whline — Draws a horizontal line in a window at current position using an attributed character and max. n characters long

Description

ncurses_whline ( resource $window , int $charattr , int $n ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

charattr

n


Transforms window/stdscr coordinates

  • « ncurses_whline
  • ncurses_wmove »
  • PHP Manual
  • Ncurses Functions
  • Transforms window/stdscr coordinates

ncurses_wmouse_trafo

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wmouse_trafo — Transforms window/stdscr coordinates

Description

ncurses_wmouse_trafo ( resource $window , int &$y , int &$x , bool $toscreen ) : bool
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

x

y

toscreen


Moves windows output position

  • « ncurses_wmouse_trafo
  • ncurses_wnoutrefresh »
  • PHP Manual
  • Ncurses Functions
  • Moves windows output position

ncurses_wmove

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wmove — Moves windows output position

Description

ncurses_wmove ( resource $window , int $y , int $x ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

y

x


Copies window to virtual screen

  • « ncurses_wmove
  • ncurses_wrefresh »
  • PHP Manual
  • Ncurses Functions
  • Copies window to virtual screen

ncurses_wnoutrefresh

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wnoutrefresh — Copies window to virtual screen

Description

ncurses_wnoutrefresh ( resource $window ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

window


Refresh window on terminal screen

  • « ncurses_wnoutrefresh
  • ncurses_wstandend »
  • PHP Manual
  • Ncurses Functions
  • Refresh window on terminal screen

ncurses_wrefresh

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wrefresh — Refresh window on terminal screen

Description

ncurses_wrefresh ( resource $window ) : int
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.

Warning

This function is currently not documented; only its argument list is available.

Parameters

window


End standout mode for a window

  • « ncurses_wrefresh
  • ncurses_wstandout »
  • PHP Manual
  • Ncurses Functions
  • End standout mode for a window

ncurses_wstandend

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wstandend — End standout mode for a window

Description

ncurses_wstandend ( resource $window ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

window


Enter standout mode for a window

  • « ncurses_wstandend
  • ncurses_wvline »
  • PHP Manual
  • Ncurses Functions
  • Enter standout mode for a window

ncurses_wstandout

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wstandout — Enter standout mode for a window

Description

ncurses_wstandout ( resource $window ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

window


Draws a vertical line in a window at current position using an attributed character and max. n characters long

  • « ncurses_wstandout
  • Newt »
  • PHP Manual
  • Ncurses Functions
  • Draws a vertical line in a window at current position using an attributed character and max. n characters long

ncurses_wvline

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wvline — Draws a vertical line in a window at current position using an attributed character and max. n characters long

Description

ncurses_wvline ( resource $window , int $charattr , int $n ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

window

charattr

n


Newt

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
    • Newt form exit reasons
    • Newt colorsets
    • Newt argument flags
    • Newt Flags Sense
    • Newt Components Flags
    • File Descriptor Flags
    • Checkbox Tree Flags
    • Entry Flags
    • Listbox Flags
    • Textbox Flags
    • Form Flags
    • Newt Keys
    • Newt Anchors
    • Grid Flags
  • Examples
    • Basic usage
  • Newt Functions
    • newt_bell — Send a beep to the terminal
    • newt_button_bar — This function returns a grid containing the buttons created
    • newt_button — Create a new button
    • newt_centered_window — Open a centered window of the specified size
    • newt_checkbox_get_value — Retreives value of checkox resource
    • newt_checkbox_set_flags — Configures checkbox resource
    • newt_checkbox_set_value — Sets the value of the checkbox
    • newt_checkbox_tree_add_item — Adds new item to the checkbox tree
    • newt_checkbox_tree_find_item — Finds an item in the checkbox tree
    • newt_checkbox_tree_get_current — Returns checkbox tree selected item
    • newt_checkbox_tree_get_entry_value — Description
    • newt_checkbox_tree_get_multi_selection — Description
    • newt_checkbox_tree_get_selection — Description
    • newt_checkbox_tree_multi — Description
    • newt_checkbox_tree_set_current — Description
    • newt_checkbox_tree_set_entry_value — Description
    • newt_checkbox_tree_set_entry — Description
    • newt_checkbox_tree_set_width — Description
    • newt_checkbox_tree — Description
    • newt_checkbox — Description
    • newt_clear_key_buffer — Discards the contents of the terminal's input buffer without waiting for additional input
    • newt_cls — Description
    • newt_compact_button — Description
    • newt_component_add_callback — Description
    • newt_component_takes_focus — Description
    • newt_create_grid — Description
    • newt_cursor_off — Description
    • newt_cursor_on — Description
    • newt_delay — Description
    • newt_draw_form — Description
    • newt_draw_root_text — Displays the string text at the position indicated
    • newt_entry_get_value — Description
    • newt_entry_set_filter — Description
    • newt_entry_set_flags — Description
    • newt_entry_set — Description
    • newt_entry — Description
    • newt_finished — Uninitializes newt interface
    • newt_form_add_component — Adds a single component to the form
    • newt_form_add_components — Add several components to the form
    • newt_form_add_hot_key — Description
    • newt_form_destroy — Destroys a form
    • newt_form_get_current — Description
    • newt_form_run — Runs a form
    • newt_form_set_background — Description
    • newt_form_set_height — Description
    • newt_form_set_size — Description
    • newt_form_set_timer — Description
    • newt_form_set_width — Description
    • newt_form_watch_fd — Description
    • newt_form — Create a form
    • newt_get_screen_size — Fills in the passed references with the current size of the terminal
    • newt_grid_add_components_to_form — Description
    • newt_grid_basic_window — Description
    • newt_grid_free — Description
    • newt_grid_get_size — Description
    • newt_grid_h_close_stacked — Description
    • newt_grid_h_stacked — Description
    • newt_grid_place — Description
    • newt_grid_set_field — Description
    • newt_grid_simple_window — Description
    • newt_grid_v_close_stacked — Description
    • newt_grid_v_stacked — Description
    • newt_grid_wrapped_window_at — Description
    • newt_grid_wrapped_window — Description
    • newt_init — Initialize newt
    • newt_label_set_text — Description
    • newt_label — Description
    • newt_listbox_append_entry — Description
    • newt_listbox_clear_selection — Description
    • newt_listbox_clear — Description
    • newt_listbox_delete_entry — Description
    • newt_listbox_get_current — Description
    • newt_listbox_get_selection — Description
    • newt_listbox_insert_entry — Description
    • newt_listbox_item_count — Description
    • newt_listbox_select_item — Description
    • newt_listbox_set_current_by_key — Description
    • newt_listbox_set_current — Description
    • newt_listbox_set_data — Description
    • newt_listbox_set_entry — Description
    • newt_listbox_set_width — Description
    • newt_listbox — Description
    • newt_listitem_get_data — Description
    • newt_listitem_set — Description
    • newt_listitem — Description
    • newt_open_window — Open a window of the specified size and position
    • newt_pop_help_line — Replaces the current help line with the one from the stack
    • newt_pop_window — Removes the top window from the display
    • newt_push_help_line — Saves the current help line on a stack, and displays the new line
    • newt_radio_get_current — Description
    • newt_radiobutton — Description
    • newt_redraw_help_line — Description
    • newt_reflow_text — Description
    • newt_refresh — Updates modified portions of the screen
    • newt_resize_screen — Description
    • newt_resume — Resume using the newt interface after calling newt_suspend
    • newt_run_form — Runs a form
    • newt_scale_set — Description
    • newt_scale — Description
    • newt_scrollbar_set — Description
    • newt_set_help_callback — Description
    • newt_set_suspend_callback — Set a callback function which gets invoked when user presses the suspend key
    • newt_suspend — Tells newt to return the terminal to its initial state
    • newt_textbox_get_num_lines — Description
    • newt_textbox_reflowed — Description
    • newt_textbox_set_height — Description
    • newt_textbox_set_text — Description
    • newt_textbox — Description
    • newt_vertical_scrollbar — Description
    • newt_wait_for_key — Doesn't return until a key has been pressed
    • newt_win_choice — Description
    • newt_win_entries — Description
    • newt_win_menu — Description
    • newt_win_message — Description
    • newt_win_messagev — Description
    • newt_win_ternary — Description


Introduction

This is a PHP language extension for RedHat Newt library, a terminal-based window and widget library for writing applications with user friendly interface. Once this extension is enabled in PHP it will provide the use of Newt widgets, such as windows, buttons, checkboxes, radiobuttons, labels, editboxes, scrolls, textareas, scales, etc. Use of this extension is very similar to the original Newt API of C programming language.


Requirements

This module uses the functions of the RedHat Newt library. You need libnewt version >= 0.51.0.


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

In order to use these functions you must compile CGI or CLI PHP with newt support by using the --with-newt[=DIR] configure option.

Note:

This extension is not available for Windows platform.

You may need also curses and slang libraries, in order to compile this extension. To specify locations of these libraries, use the following configuration options: --with-curses-dir=/path/to/libcurses --with-slang-dir=/path/to/libslang


Resource Types

This extension uses two resource types: "newt component" and "newt grid".

Resource type "newt component" is returned by functions, which create common newt widgets (for example: newt_button())

Resource type "newt grid" is a special link identifier for components, returned by newt grid factory functions (for example: newt_create_grid())


Predefined Constants

Table of Contents

  • Newt form exit reasons
  • Newt colorsets
  • Newt argument flags
  • Newt Flags Sense
  • Newt Components Flags
  • File Descriptor Flags
  • Checkbox Tree Flags
  • Entry Flags
  • Listbox Flags
  • Textbox Flags
  • Form Flags
  • Newt Keys
  • Newt Anchors
  • Grid Flags

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.


Newt form exit reasons

Newt form exit reasons
constant | meaning
NEWT_EXIT_HOTKEY | hotkey defined by newt_form_add_hot_key() was pressed
NEWT_EXIT_COMPONENT | some component has caused form to exit
NEWT_EXIT_FDREADY | file descriptor specified in newt_form_watch_fd() is ready to be read or written to
NEWT_EXIT_TIMER | time specified in newt_form_set_timer() has elapsed


Newt colorsets

Newt colorsets
constant | meaning
NEWT_COLORSET_ROOT |
NEWT_COLORSET_BORDER |
NEWT_COLORSET_WINDOW |
NEWT_COLORSET_SHADOW |
NEWT_COLORSET_TITLE |
NEWT_COLORSET_BUTTON |
NEWT_COLORSET_ACTBUTTON |
NEWT_COLORSET_CHECKBOX |
NEWT_COLORSET_ACTCHECKBOX |
NEWT_COLORSET_ENTRY |
NEWT_COLORSET_LABEL |
NEWT_COLORSET_LISTBOX |
NEWT_COLORSET_ACTLISTBOX |
NEWT_COLORSET_TEXTBOX |
NEWT_COLORSET_ACTTEXTBOX |
NEWT_COLORSET_HELPLINE |
NEWT_COLORSET_ROOTTEXT |
NEWT_COLORSET_EMPTYSCALE |
NEWT_COLORSET_FULLSCALE |
NEWT_COLORSET_DISENTRY |
NEWT_COLORSET_COMPACTBUTTON |
NEWT_COLORSET_ACTSELLISTBOX |
NEWT_COLORSET_SELLISTBOX |


  • « Newt colorsets
  • Newt Flags Sense »
  • PHP Manual
  • Predefined Constants
  • Newt argument flags

Newt argument flags

Newt argument flags
constant | meaning
NEWT_ARG_LAST |
NEWT_ARG_APPEND |


  • « Newt argument flags
  • Newt Components Flags »
  • PHP Manual
  • Predefined Constants
  • Newt Flags Sense

Newt Flags Sense

Newt Flags Sense
constant | meaning
NEWT_FLAGS_SET |
NEWT_FLAGS_RESET |
NEWT_FLAGS_TOGGLE |


Newt Components Flags

Newt Components Flags
constant | meaning
NEWT_FLAG_RETURNEXIT | Exit form, when component is activated
NEWT_FLAG_HIDDEN | Component is hidden
NEWT_FLAG_SCROLL | Component is scrollable
NEWT_FLAG_DISABLED | Component is disabled
NEWT_FLAG_BORDER |
NEWT_FLAG_WRAP | Wrap text
NEWT_FLAG_NOF12 | Don't exit form on pressing F12
NEWT_FLAG_MULTIPLE |
NEWT_FLAG_SELECTED | Component is selected
NEWT_FLAG_CHECKBOX | Component is checkbox
NEWT_FLAG_PASSWORD | Entry component is password entry
NEWT_FLAG_SHOWCURSOR | Show cursor


  • « Newt Components Flags
  • Checkbox Tree Flags »
  • PHP Manual
  • Predefined Constants
  • File Descriptor Flags

File Descriptor Flags

File Descriptor Flags
constant | meaning
NEWT_FD_READ |
NEWT_FD_WRITE |
NEWT_FD_EXCEPT |


Checkbox Tree Flags

Checkbox Tree Flags
constant | meaning
NEWT_CHECKBOXTREE_UNSELECTABLE |
NEWT_CHECKBOXTREE_HIDE_BOX |
NEWT_CHECKBOXTREE_COLLAPSED |
NEWT_CHECKBOXTREE_EXPANDED |
NEWT_CHECKBOXTREE_UNSELECTED |
NEWT_CHECKBOXTREE_SELECTED |


Entry Flags

Entry Flags
constant | meaning
NEWT_ENTRY_SCROLL |
NEWT_ENTRY_HIDDEN |
NEWT_ENTRY_RETURNEXIT |
NEWT_ENTRY_DISABLED |


  • « Entry Flags
  • Textbox Flags »
  • PHP Manual
  • Predefined Constants
  • Listbox Flags

Listbox Flags

Listbox Flags
constant | meaning
NEWT_LISTBOX_RETURNEXIT |


Textbox Flags

Textbox Flags
constant | meaning
NEWT_TEXTBOX_WRAP | Wrap text in the textbox
NEWT_TEXTBOX_SCROLL | Scroll text in the textbox


  • « Textbox Flags
  • Newt Keys »
  • PHP Manual
  • Predefined Constants
  • Form Flags

Form Flags

Form Flags
constant | meaning
NEWT_FORM_NOF12 | Don't exit form on F12 press


Newt Keys

Newt Keys
constant | meaning
NEWT_KEY_TAB |
NEWT_KEY_ENTER |
NEWT_KEY_SUSPEND |
NEWT_KEY_ESCAPE |
NEWT_KEY_RETURN |
NEWT_KEY_EXTRA_BASE |
NEWT_KEY_UP |
NEWT_KEY_DOWN |
NEWT_KEY_LEFT |
NEWT_KEY_RIGHT |
NEWT_KEY_BKSPC |
NEWT_KEY_DELETE |
NEWT_KEY_HOME |
NEWT_KEY_END |
NEWT_KEY_UNTAB |
NEWT_KEY_PGUP |
NEWT_KEY_PGDN |
NEWT_KEY_INSERT |
NEWT_KEY_F1 |
NEWT_KEY_F2 |
NEWT_KEY_F3 |
NEWT_KEY_F4 |
NEWT_KEY_F5 |
NEWT_KEY_F6 |
NEWT_KEY_F7 |
NEWT_KEY_F8 |
NEWT_KEY_F9 |
NEWT_KEY_F10 |
NEWT_KEY_F11 |
NEWT_KEY_F12 |
NEWT_KEY_RESIZE |


Newt Anchors

Newt Anchors
constant | meaning
NEWT_ANCHOR_LEFT |
NEWT_ANCHOR_RIGHT |
NEWT_ANCHOR_TOP |
NEWT_ANCHOR_BOTTOM |


Grid Flags

Grid Flags
constant | meaning
NEWT_GRID_FLAG_GROWX |
NEWT_GRID_FLAG_GROWY |
NEWT_GRID_EMPTY |
NEWT_GRID_COMPONENT |
NEWT_GRID_SUBGRID |


  • « Grid Flags
  • Basic usage »
  • PHP Manual
  • Newt
  • Examples

Examples

Table of Contents

  • Basic usage


Basic usage

This example is a PHP port of RedHat 'setup' utility dialog, executed in text mode.

Example #1 Newt Usage Example

<?php
newt_init ();
newt_cls ();

newt_draw_root_text (0, 0, "Test Mode Setup Utility 1.12");
newt_push_help_line (null);
newt_draw_root_text (-30, 0, "(c) 1999-2002 RedHat, Inc");

newt_get_screen_size ($rows, $cols);

newt_open_window ($rows/2-17, $cols/2-10, 34, 17, "Choose a Tool");

$form = newt_form ();

$list = newt_listbox (3, 2, 10);

foreach (array (
    "Authentication configuration",
    "Firewall configuration",
    "Mouse configuration",
    "Network configuration",
    "Printer configuration",
    "System services") as $l_item)
{
    newt_listbox_add_entry ($list, $l_item, $l_item);
}

$b1 = newt_button (5, 12, "Run Tool");
$b2 = newt_button (21, 12, "Quit");

newt_form_add_component ($form, $list);
newt_form_add_components ($form, array($b1, $b2));

newt_refresh ();
newt_run_form ($form);

newt_pop_window ();
newt_pop_help_line ();
newt_finished ();
newt_form_destroy ($form);
?>


Newt Functions

Table of Contents

  • newt_bell — Send a beep to the terminal
  • newt_button_bar — This function returns a grid containing the buttons created
  • newt_button — Create a new button
  • newt_centered_window — Open a centered window of the specified size
  • newt_checkbox_get_value — Retreives value of checkox resource
  • newt_checkbox_set_flags — Configures checkbox resource
  • newt_checkbox_set_value — Sets the value of the checkbox
  • newt_checkbox_tree_add_item — Adds new item to the checkbox tree
  • newt_checkbox_tree_find_item — Finds an item in the checkbox tree
  • newt_checkbox_tree_get_current — Returns checkbox tree selected item
  • newt_checkbox_tree_get_entry_value — Description
  • newt_checkbox_tree_get_multi_selection — Description
  • newt_checkbox_tree_get_selection — Description
  • newt_checkbox_tree_multi — Description
  • newt_checkbox_tree_set_current — Description
  • newt_checkbox_tree_set_entry_value — Description
  • newt_checkbox_tree_set_entry — Description
  • newt_checkbox_tree_set_width — Description
  • newt_checkbox_tree — Description
  • newt_checkbox — Description
  • newt_clear_key_buffer — Discards the contents of the terminal's input buffer without waiting for additional input
  • newt_cls — Description
  • newt_compact_button — Description
  • newt_component_add_callback — Description
  • newt_component_takes_focus — Description
  • newt_create_grid — Description
  • newt_cursor_off — Description
  • newt_cursor_on — Description
  • newt_delay — Description
  • newt_draw_form — Description
  • newt_draw_root_text — Displays the string text at the position indicated
  • newt_entry_get_value — Description
  • newt_entry_set_filter — Description
  • newt_entry_set_flags — Description
  • newt_entry_set — Description
  • newt_entry — Description
  • newt_finished — Uninitializes newt interface
  • newt_form_add_component — Adds a single component to the form
  • newt_form_add_components — Add several components to the form
  • newt_form_add_hot_key — Description
  • newt_form_destroy — Destroys a form
  • newt_form_get_current — Description
  • newt_form_run — Runs a form
  • newt_form_set_background — Description
  • newt_form_set_height — Description
  • newt_form_set_size — Description
  • newt_form_set_timer — Description
  • newt_form_set_width — Description
  • newt_form_watch_fd — Description
  • newt_form — Create a form
  • newt_get_screen_size — Fills in the passed references with the current size of the terminal
  • newt_grid_add_components_to_form — Description
  • newt_grid_basic_window — Description
  • newt_grid_free — Description
  • newt_grid_get_size — Description
  • newt_grid_h_close_stacked — Description
  • newt_grid_h_stacked — Description
  • newt_grid_place — Description
  • newt_grid_set_field — Description
  • newt_grid_simple_window — Description
  • newt_grid_v_close_stacked — Description
  • newt_grid_v_stacked — Description
  • newt_grid_wrapped_window_at — Description
  • newt_grid_wrapped_window — Description
  • newt_init — Initialize newt
  • newt_label_set_text — Description
  • newt_label — Description
  • newt_listbox_append_entry — Description
  • newt_listbox_clear_selection — Description
  • newt_listbox_clear — Description
  • newt_listbox_delete_entry — Description
  • newt_listbox_get_current — Description
  • newt_listbox_get_selection — Description
  • newt_listbox_insert_entry — Description
  • newt_listbox_item_count — Description
  • newt_listbox_select_item — Description
  • newt_listbox_set_current_by_key — Description
  • newt_listbox_set_current — Description
  • newt_listbox_set_data — Description
  • newt_listbox_set_entry — Description
  • newt_listbox_set_width — Description
  • newt_listbox — Description
  • newt_listitem_get_data — Description
  • newt_listitem_set — Description
  • newt_listitem — Description
  • newt_open_window — Open a window of the specified size and position
  • newt_pop_help_line — Replaces the current help line with the one from the stack
  • newt_pop_window — Removes the top window from the display
  • newt_push_help_line — Saves the current help line on a stack, and displays the new line
  • newt_radio_get_current — Description
  • newt_radiobutton — Description
  • newt_redraw_help_line — Description
  • newt_reflow_text — Description
  • newt_refresh — Updates modified portions of the screen
  • newt_resize_screen — Description
  • newt_resume — Resume using the newt interface after calling newt_suspend
  • newt_run_form — Runs a form
  • newt_scale_set — Description
  • newt_scale — Description
  • newt_scrollbar_set — Description
  • newt_set_help_callback — Description
  • newt_set_suspend_callback — Set a callback function which gets invoked when user presses the suspend key
  • newt_suspend — Tells newt to return the terminal to its initial state
  • newt_textbox_get_num_lines — Description
  • newt_textbox_reflowed — Description
  • newt_textbox_set_height — Description
  • newt_textbox_set_text — Description
  • newt_textbox — Description
  • newt_vertical_scrollbar — Description
  • newt_wait_for_key — Doesn't return until a key has been pressed
  • newt_win_choice — Description
  • newt_win_entries — Description
  • newt_win_menu — Description
  • newt_win_message — Description
  • newt_win_messagev — Description
  • newt_win_ternary — Description


Send a beep to the terminal

  • « Newt Functions
  • newt_button_bar »
  • PHP Manual
  • Newt Functions
  • Send a beep to the terminal

newt_bell

(PECL newt >= 0.1)

newt_bell — Send a beep to the terminal

Description

newt_bell ( void ) : void

This function sends a beep to the terminal.

Note:

Depending on the terminal's settings, this beep may or may not be audible.

Return Values

No value is returned.


This function returns a grid containing the buttons created

  • « newt_bell
  • newt_button »
  • PHP Manual
  • Newt Functions
  • This function returns a grid containing the buttons created

newt_button_bar

(PECL newt >= 0.1)

newt_button_bar — This function returns a grid containing the buttons created

Description

newt_button_bar ( array &$buttons ) : resource

This function returns a grid containing the buttons created.

Parameters

buttons

Return Values

Returns grid containing the buttons created.


Create a new button

  • « newt_button_bar
  • newt_centered_window »
  • PHP Manual
  • Newt Functions
  • Create a new button

newt_button

(PECL newt >= 0.1)

newt_button — Create a new button

Description

newt_button ( int $left , int $top , string $text ) : resource

Creates a new button.

Parameters

left

X-coordinate of the button.

top

Y-coordinate of the button.

text

The text which should be displayed in the button.

Return Values

Returns a resource link to the created button component, or FALSE on error.

Examples

Example #1 A newt_button() example

<?php

$form = newt_form();

$ok_button = newt_button(5, 12, "Run Tool");

newt_form_add_component($form, $ok_button);

?>

See Also

  • newt_button_bar() - This function returns a grid containing the buttons created


Open a centered window of the specified size

  • « newt_button
  • newt_checkbox_get_value »
  • PHP Manual
  • Newt Functions
  • Open a centered window of the specified size

newt_centered_window

(PECL newt >= 0.1)

newt_centered_window — Open a centered window of the specified size

Description

newt_centered_window ( int $width , int $height [, string $title ] ) : int

Open a centered window of the specified size.

Parameters

width

Window width

height

Window height

title

Window title

Return Values

Undefined value.

See Also

  • newt_pop_window() - Removes the top window from the display
  • newt_open_window() - Open a window of the specified size and position


Retreives value of checkox resource

  • « newt_centered_window
  • newt_checkbox_set_flags »
  • PHP Manual
  • Newt Functions
  • Retreives value of checkox resource

newt_checkbox_get_value

(PECL newt >= 0.1)

newt_checkbox_get_value — Retreives value of checkox resource

Description

newt_checkbox_get_value ( resource $checkbox ) : string

This function returns the character in the sequence which indicates the current value of the checkbox.

Parameters

checkbox

Return Values

Returns character indicating the value of the checkbox.


Configures checkbox resource

  • « newt_checkbox_get_value
  • newt_checkbox_set_value »
  • PHP Manual
  • Newt Functions
  • Configures checkbox resource

newt_checkbox_set_flags

(PECL newt >= 0.1)

newt_checkbox_set_flags — Configures checkbox resource

Description

newt_checkbox_set_flags ( resource $checkbox , int $flags , int $sense ) : void

This function allows to set various flags on checkbox resource.

Parameters

checkbox

flags

sense

Return Values

No value is returned.


Sets the value of the checkbox

  • « newt_checkbox_set_flags
  • newt_checkbox_tree_add_item »
  • PHP Manual
  • Newt Functions
  • Sets the value of the checkbox

newt_checkbox_set_value

(PECL newt >= 0.1)

newt_checkbox_set_value — Sets the value of the checkbox

Description

newt_checkbox_set_value ( resource $checkbox , string $value ) : void

This function allows to set the current value of the checkbox resource.

Parameters

checkbox

value

Return Values

No value is returned.


Adds new item to the checkbox tree

  • « newt_checkbox_set_value
  • newt_checkbox_tree_find_item »
  • PHP Manual
  • Newt Functions
  • Adds new item to the checkbox tree

newt_checkbox_tree_add_item

(PECL newt >= 0.1)

newt_checkbox_tree_add_item — Adds new item to the checkbox tree

Description

newt_checkbox_tree_add_item ( resource $checkboxtree , string $text , mixed $data , int $flags , int $index [, int $... ] ) : void

This function allows to add new item to the checkbox tree.

Parameters

checkboxtree

text

data

flags

index

Return Values

No value is returned.


Finds an item in the checkbox tree

  • « newt_checkbox_tree_add_item
  • newt_checkbox_tree_get_current »
  • PHP Manual
  • Newt Functions
  • Finds an item in the checkbox tree

newt_checkbox_tree_find_item

(PECL newt >= 0.1)

newt_checkbox_tree_find_item — Finds an item in the checkbox tree

Description

newt_checkbox_tree_find_item ( resource $checkboxtree , mixed $data ) : array

Finds an item in the checkbox tree by item's data.

Parameters

checkboxtree

data

Return Values

Returns checkbox tree item resource, or NULL if it wasn't found.


Returns checkbox tree selected item

  • « newt_checkbox_tree_find_item
  • newt_checkbox_tree_get_entry_value »
  • PHP Manual
  • Newt Functions
  • Returns checkbox tree selected item

newt_checkbox_tree_get_current

(PECL newt >= 0.1)

newt_checkbox_tree_get_current — Returns checkbox tree selected item

Description

newt_checkbox_tree_get_current ( resource $checkboxtree ) : mixed

This method returns checkbox tree selected tem.

Parameters

checkboxtree

Return Values

Returns current (selected) checkbox tree item.


Description

  • « newt_checkbox_tree_get_current
  • newt_checkbox_tree_get_multi_selection »
  • PHP Manual
  • Newt Functions
  • Description

newt_checkbox_tree_get_entry_value

(PECL newt >= 0.1)

newt_checkbox_tree_get_entry_value —

Description

newt_checkbox_tree_get_entry_value ( resource $checkboxtree , mixed $data ) : string
Warning

This function is currently not documented; only its argument list is available.

Parameters

checkboxtree

data

Return Values


Description

  • « newt_checkbox_tree_get_entry_value
  • newt_checkbox_tree_get_selection »
  • PHP Manual
  • Newt Functions
  • Description

newt_checkbox_tree_get_multi_selection

(PECL newt >= 0.1)

newt_checkbox_tree_get_multi_selection —

Description

newt_checkbox_tree_get_multi_selection ( resource $checkboxtree , string $seqnum ) : array
Warning

This function is currently not documented; only its argument list is available.

Parameters

checkboxtree

seqnum

Return Values


Description

  • « newt_checkbox_tree_get_multi_selection
  • newt_checkbox_tree_multi »
  • PHP Manual
  • Newt Functions
  • Description

newt_checkbox_tree_get_selection

(PECL newt >= 0.1)

newt_checkbox_tree_get_selection —

Description

newt_checkbox_tree_get_selection ( resource $checkboxtree ) : array
Warning

This function is currently not documented; only its argument list is available.

Parameters

checkboxtree

Return Values


Description

  • « newt_checkbox_tree_get_selection
  • newt_checkbox_tree_set_current »
  • PHP Manual
  • Newt Functions
  • Description

newt_checkbox_tree_multi

(PECL newt >= 0.1)

newt_checkbox_tree_multi —

Description

newt_checkbox_tree_multi ( int $left , int $top , int $height , string $seq [, int $flags ] ) : resource
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

height

seq

flags

Return Values


Description

  • « newt_checkbox_tree_multi
  • newt_checkbox_tree_set_entry_value »
  • PHP Manual
  • Newt Functions
  • Description

newt_checkbox_tree_set_current

(PECL newt >= 0.1)

newt_checkbox_tree_set_current —

Description

newt_checkbox_tree_set_current ( resource $checkboxtree , mixed $data ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

checkboxtree

data

Return Values

No value is returned.


Description

  • « newt_checkbox_tree_set_current
  • newt_checkbox_tree_set_entry »
  • PHP Manual
  • Newt Functions
  • Description

newt_checkbox_tree_set_entry_value

(PECL newt >= 0.1)

newt_checkbox_tree_set_entry_value —

Description

newt_checkbox_tree_set_entry_value ( resource $checkboxtree , mixed $data , string $value ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

checkboxtree

data

value

Return Values

No value is returned.


Description

  • « newt_checkbox_tree_set_entry_value
  • newt_checkbox_tree_set_width »
  • PHP Manual
  • Newt Functions
  • Description

newt_checkbox_tree_set_entry

(PECL newt >= 0.1)

newt_checkbox_tree_set_entry —

Description

newt_checkbox_tree_set_entry ( resource $checkboxtree , mixed $data , string $text ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

checkboxtree

data

text

Return Values

No value is returned.


Description

  • « newt_checkbox_tree_set_entry
  • newt_checkbox_tree »
  • PHP Manual
  • Newt Functions
  • Description

newt_checkbox_tree_set_width

(PECL newt >= 0.1)

newt_checkbox_tree_set_width —

Description

newt_checkbox_tree_set_width ( resource $checkbox_tree , int $width ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

checkbox_tree

width

Return Values

No value is returned.


Description

  • « newt_checkbox_tree_set_width
  • newt_checkbox »
  • PHP Manual
  • Newt Functions
  • Description

newt_checkbox_tree

(PECL newt >= 0.1)

newt_checkbox_tree —

Description

newt_checkbox_tree ( int $left , int $top , int $height [, int $flags ] ) : resource
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

height

flags

Return Values


Description

  • « newt_checkbox_tree
  • newt_clear_key_buffer »
  • PHP Manual
  • Newt Functions
  • Description

newt_checkbox

(PECL newt >= 0.1)

newt_checkbox —

Description

newt_checkbox ( int $left , int $top , string $text , string $def_value [, string $seq ] ) : resource
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

text

def_value

seq

Return Values


Discards the contents of the terminal's input buffer without waiting for additional input

  • « newt_checkbox
  • newt_cls »
  • PHP Manual
  • Newt Functions
  • Discards the contents of the terminal's input buffer without waiting for additional input

newt_clear_key_buffer

(PECL newt >= 0.1)

newt_clear_key_buffer — Discards the contents of the terminal's input buffer without waiting for additional input

Description

newt_clear_key_buffer ( void ) : void

Discards the contents of the terminal's input buffer without waiting for additional input.

Return Values

No value is returned.

See Also

  • newt_wait_for_key() - Doesn't return until a key has been pressed


Description

  • « newt_clear_key_buffer
  • newt_compact_button »
  • PHP Manual
  • Newt Functions
  • Description

newt_cls

(PECL newt >= 0.1)

newt_cls —

Description

newt_cls ( void ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

Return Values

No value is returned.


Description

  • « newt_cls
  • newt_component_add_callback »
  • PHP Manual
  • Newt Functions
  • Description

newt_compact_button

(PECL newt >= 0.1)

newt_compact_button —

Description

newt_compact_button ( int $left , int $top , string $text ) : resource
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

text

Return Values


Description

  • « newt_compact_button
  • newt_component_takes_focus »
  • PHP Manual
  • Newt Functions
  • Description

newt_component_add_callback

(PECL newt >= 0.1)

newt_component_add_callback —

Description

newt_component_add_callback ( resource $component , mixed $func_name , mixed $data ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

component

func_name

data

Return Values

No value is returned.


Description

  • « newt_component_add_callback
  • newt_create_grid »
  • PHP Manual
  • Newt Functions
  • Description

newt_component_takes_focus

(PECL newt >= 0.1)

newt_component_takes_focus —

Description

newt_component_takes_focus ( resource $component , bool $takes_focus ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

component

takes_focus

Return Values

No value is returned.


Description

  • « newt_component_takes_focus
  • newt_cursor_off »
  • PHP Manual
  • Newt Functions
  • Description

newt_create_grid

(PECL newt >= 0.1)

newt_create_grid —

Description

newt_create_grid ( int $cols , int $rows ) : resource
Warning

This function is currently not documented; only its argument list is available.

Parameters

cols

rows

Return Values


Description

  • « newt_create_grid
  • newt_cursor_on »
  • PHP Manual
  • Newt Functions
  • Description

newt_cursor_off

(PECL newt >= 0.1)

newt_cursor_off —

Description

newt_cursor_off ( void ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

Return Values

No value is returned.


Description

  • « newt_cursor_off
  • newt_delay »
  • PHP Manual
  • Newt Functions
  • Description

newt_cursor_on

(PECL newt >= 0.1)

newt_cursor_on —

Description

newt_cursor_on ( void ) : void
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.


Description

  • « newt_cursor_on
  • newt_draw_form »
  • PHP Manual
  • Newt Functions
  • Description

newt_delay

(PECL newt >= 0.1)

newt_delay —

Description

newt_delay ( int $microseconds ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

microseconds

Return Values

No value is returned.


Description

  • « newt_delay
  • newt_draw_root_text »
  • PHP Manual
  • Newt Functions
  • Description

newt_draw_form

(PECL newt >= 0.1)

newt_draw_form —

Description

newt_draw_form ( resource $form ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

form

Return Values

No value is returned.


Displays the string text at the position indicated

  • « newt_draw_form
  • newt_entry_get_value »
  • PHP Manual
  • Newt Functions
  • Displays the string text at the position indicated

newt_draw_root_text

(PECL newt >= 0.1)

newt_draw_root_text — Displays the string text at the position indicated

Description

newt_draw_root_text ( int $left , int $top , string $text ) : void

Displays the string text at the position indicated.

Parameters

left

Column number

Note:

If left is negative, the position is measured from the opposite side of the screen.

top

Line number

Note:

If top is negative, the position is measured from the opposite side of the screen.

text

Text to display.

Return Values

No value is returned.

Examples

Example #1 A newt_draw_root_text() example

This code demonstrates drawing of titles in the both corners of the screen.

<?php
 newt_init();
 newt_cls();

 newt_draw_root_text (2, 0, "Some root text");
 newt_refresh();
 sleep(1);

 newt_draw_root_text (-30, 0, "Root text in the other corner");
 newt_refresh();
 sleep(1);

 newt_finished();
?>

See Also

  • newt_push_help_line() - Saves the current help line on a stack, and displays the new line
  • newt_pop_help_line() - Replaces the current help line with the one from the stack


Description

  • « newt_draw_root_text
  • newt_entry_set_filter »
  • PHP Manual
  • Newt Functions
  • Description

newt_entry_get_value

(PECL newt >= 0.1)

newt_entry_get_value —

Description

newt_entry_get_value ( resource $entry ) : string
Warning

This function is currently not documented; only its argument list is available.

Parameters

entry

Return Values


Description

  • « newt_entry_get_value
  • newt_entry_set_flags »
  • PHP Manual
  • Newt Functions
  • Description

newt_entry_set_filter

(PECL newt >= 0.1)

newt_entry_set_filter —

Description

newt_entry_set_filter ( resource $entry , callable $filter , mixed $data ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

entry

filter

data

Return Values

No value is returned.


Description

  • « newt_entry_set_filter
  • newt_entry_set »
  • PHP Manual
  • Newt Functions
  • Description

newt_entry_set_flags

(PECL newt >= 0.1)

newt_entry_set_flags —

Description

newt_entry_set_flags ( resource $entry , int $flags , int $sense ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

entry

flags

sense

Return Values

No value is returned.


Description

  • « newt_entry_set_flags
  • newt_entry »
  • PHP Manual
  • Newt Functions
  • Description

newt_entry_set

(PECL newt >= 0.1)

newt_entry_set —

Description

newt_entry_set ( resource $entry , string $value [, bool $cursor_at_end ] ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

entry

value

cursor_at_end

Return Values

No value is returned.


Description

  • « newt_entry_set
  • newt_finished »
  • PHP Manual
  • Newt Functions
  • Description

newt_entry

(PECL newt >= 0.1)

newt_entry —

Description

newt_entry ( int $left , int $top , int $width [, string $init_value [, int $flags ]] ) : resource
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

width

init_value

flags

Return Values


Uninitializes newt interface

  • « newt_entry
  • newt_form_add_component »
  • PHP Manual
  • Newt Functions
  • Uninitializes newt interface

newt_finished

(PECL newt >= 0.1)

newt_finished — Uninitializes newt interface

Description

newt_finished ( void ) : int

Uninitializes newt interface. This function be called, when program is ready to exit.

Return Values

Returns 1 on success, 0 on failure.

See Also

  • newt_init() - Initialize newt


Adds a single component to the form

  • « newt_finished
  • newt_form_add_components »
  • PHP Manual
  • Newt Functions
  • Adds a single component to the form

newt_form_add_component

(PECL newt >= 0.1)

newt_form_add_component — Adds a single component to the form

Description

newt_form_add_component ( resource $form , resource $component ) : void

Adds a single component to the form.

Parameters

form

Form to which component will be added

component

Component to add to the form

Return Values

No value is returned.

Examples

Example #1 A newt_form_add_component() example

<?php
$form = newt_form();

$options = array("Authentication configuration", "Firewall configuration",
"Mouse configuration", "Network configuration", "Printer configuration",
"System services");

$list = newt_listbox(3, 2, 10);

foreach ($options as $l_item) {
    newt_listbox_add_entry($list, $l_item, $l_item);
}

newt_form_add_component($form, $list);
?>

See Also

  • newt_form_add_components() - Add several components to the form


Add several components to the form

  • « newt_form_add_component
  • newt_form_add_hot_key »
  • PHP Manual
  • Newt Functions
  • Add several components to the form

newt_form_add_components

(PECL newt >= 0.1)

newt_form_add_components — Add several components to the form

Description

newt_form_add_components ( resource $form , array $components ) : void

Adds several components to the form.

Parameters

form

Form to which components will be added

components

Array of components to add to the form

Return Values

No value is returned.

Examples

Example #1 A newt_form_add_components() example

<?php
$form = newt_form();

$b1 = newt_button(5, 12, "Run Tool");
$b2 = newt_button(21, 12, "Quit");

newt_form_add_components($form, array($b1, $b2));
?>

See Also

  • newt_form_add_component() - Adds a single component to the form


Description

  • « newt_form_add_components
  • newt_form_destroy »
  • PHP Manual
  • Newt Functions
  • Description

newt_form_add_hot_key

(PECL newt >= 0.1)

newt_form_add_hot_key —

Description

newt_form_add_hot_key ( resource $form , int $key ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

form

key

Return Values

No value is returned.


Destroys a form

  • « newt_form_add_hot_key
  • newt_form_get_current »
  • PHP Manual
  • Newt Functions
  • Destroys a form

newt_form_destroy

(PECL newt >= 0.1)

newt_form_destroy — Destroys a form

Description

newt_form_destroy ( resource $form ) : void

This function frees the memory resources used by the form and all of the components which have been added to the form (including those components which are on subforms). Once a form has been destroyed, none of the form's components can be used.

Parameters

form

Form component, which is going to be destroyed

Return Values

No value is returned.

See Also

  • newt_form_run() - Runs a form
  • newt_run_form() - Runs a form


Description

  • « newt_form_destroy
  • newt_form_run »
  • PHP Manual
  • Newt Functions
  • Description

newt_form_get_current

(PECL newt >= 0.1)

newt_form_get_current —

Description

newt_form_get_current ( resource $form ) : resource
Warning

This function is currently not documented; only its argument list is available.

Parameters

form

Return Values


Runs a form

  • « newt_form_get_current
  • newt_form_set_background »
  • PHP Manual
  • Newt Functions
  • Runs a form

newt_form_run

(PECL newt >= 0.1)

newt_form_run — Runs a form

Description

newt_form_run ( resource $form , array &$exit_struct ) : void

This function runs the form passed to it.

Parameters

form

Form component

exit_struct

Array, used for returning information after running the form component. Keys and values are described in the following table:

Form Exit Structure
Index Key | Value Type | Description
reason | integer | The reason, why the form has been exited. Possible values are defined here.
watch | resource | Resource link, specified in newt_form_watch_fd()
key | integer | Hotkey
component | resource | Component, which caused the form to exit

Return Values

No value is returned.

See Also

  • newt_run_form() - Runs a form


Description

  • « newt_form_run
  • newt_form_set_height »
  • PHP Manual
  • Newt Functions
  • Description

newt_form_set_background

(PECL newt >= 0.1)

newt_form_set_background —

Description

newt_form_set_background ( resource $from , int $background ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

from

background

Return Values

No value is returned.


Description

  • « newt_form_set_background
  • newt_form_set_size »
  • PHP Manual
  • Newt Functions
  • Description

newt_form_set_height

(PECL newt >= 0.1)

newt_form_set_height —

Description

newt_form_set_height ( resource $form , int $height ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

form

height

Return Values

No value is returned.


Description

  • « newt_form_set_height
  • newt_form_set_timer »
  • PHP Manual
  • Newt Functions
  • Description

newt_form_set_size

(PECL newt >= 0.1)

newt_form_set_size —

Description

newt_form_set_size ( resource $form ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

form

Return Values

No value is returned.


Description

  • « newt_form_set_size
  • newt_form_set_width »
  • PHP Manual
  • Newt Functions
  • Description

newt_form_set_timer

(PECL newt >= 0.1)

newt_form_set_timer —

Description

newt_form_set_timer ( resource $form , int $milliseconds ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

form

milliseconds

Return Values

No value is returned.


Description

  • « newt_form_set_timer
  • newt_form_watch_fd »
  • PHP Manual
  • Newt Functions
  • Description

newt_form_set_width

(PECL newt >= 0.1)

newt_form_set_width —

Description

newt_form_set_width ( resource $form , int $width ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

form

width

Return Values

No value is returned.


Description

  • « newt_form_set_width
  • newt_form »
  • PHP Manual
  • Newt Functions
  • Description

newt_form_watch_fd

(PECL newt >= 0.1)

newt_form_watch_fd —

Description

newt_form_watch_fd ( resource $form , resource $stream [, int $flags ] ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

form

stream

flags

Return Values

No value is returned.


Create a form

  • « newt_form_watch_fd
  • newt_get_screen_size »
  • PHP Manual
  • Newt Functions
  • Create a form

newt_form

(PECL newt >= 0.1)

newt_form — Create a form

Description

newt_form ([ resource $vert_bar [, string $help [, int $flags ]]] ) : resource

Create a new form.

Parameters

vert_bar

Vertical scrollbar which should be associated with the form

help

Help text string

flags

Various flags

Return Values

Returns a resource link to the created form component, or FALSE on error.

Examples

Example #1 A newt_form() example

Displays a single button "Quit", which closes the application once it's pressed.

<?php
newt_init();
newt_cls();

$myform = newt_form();
$button = newt_button (5, 12, "Quit");

newt_form_add_component ($myform, $button);
newt_refresh ();
newt_run_form ($myform);

newt_finished ();
newt_form_destroy ($myform);
?>

See Also

  • newt_form_run() - Runs a form
  • newt_run_form() - Runs a form
  • newt_form_add_component() - Adds a single component to the form
  • newt_form_add_components() - Add several components to the form
  • newt_form_destroy() - Destroys a form


Fills in the passed references with the current size of the terminal

  • « newt_form
  • newt_grid_add_components_to_form »
  • PHP Manual
  • Newt Functions
  • Fills in the passed references with the current size of the terminal

newt_get_screen_size

(PECL newt >= 0.1)

newt_get_screen_size — Fills in the passed references with the current size of the terminal

Description

newt_get_screen_size ( int &$cols , int &$rows ) : void

Fills in the passed references with the current size of the terminal.

Parameters

cols

Number of columns in the terminal

rows

Number of rows in the terminal

Return Values

No value is returned.

Examples

Example #1 A newt_get_screen_size() example

This code prints out the screen size of your terminal.

<?php
 newt_init();
 newt_get_screen_size (&$cols, &$rows);
 newt_finished();

 print "Your terminal size is: {$cols}x{$rows}\n";
?>

The above example will output:

Your terminal size is: 138x47


Description

  • « newt_get_screen_size
  • newt_grid_basic_window »
  • PHP Manual
  • Newt Functions
  • Description

newt_grid_add_components_to_form

(PECL newt >= 0.1)

newt_grid_add_components_to_form —

Description

newt_grid_add_components_to_form ( resource $grid , resource $form , bool $recurse ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

grid

form

recurse

Return Values

No value is returned.


Description

  • « newt_grid_add_components_to_form
  • newt_grid_free »
  • PHP Manual
  • Newt Functions
  • Description

newt_grid_basic_window

(PECL newt >= 0.1)

newt_grid_basic_window —

Description

newt_grid_basic_window ( resource $text , resource $middle , resource $buttons ) : resource
Warning

This function is currently not documented; only its argument list is available.

Parameters

text

middle

buttons

Return Values


Description

  • « newt_grid_basic_window
  • newt_grid_get_size »
  • PHP Manual
  • Newt Functions
  • Description

newt_grid_free

(PECL newt >= 0.1)

newt_grid_free —

Description

newt_grid_free ( resource $grid , bool $recurse ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

grid

recurse

Return Values

No value is returned.


Description

  • « newt_grid_free
  • newt_grid_h_close_stacked »
  • PHP Manual
  • Newt Functions
  • Description

newt_grid_get_size

(PECL newt >= 0.1)

newt_grid_get_size —

Description

newt_grid_get_size ( resouce $grid , int &$width , int &$height ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

grid

width

height

Return Values

No value is returned.


Description

  • « newt_grid_get_size
  • newt_grid_h_stacked »
  • PHP Manual
  • Newt Functions
  • Description

newt_grid_h_close_stacked

(PECL newt >= 0.1)

newt_grid_h_close_stacked —

Description

newt_grid_h_close_stacked ( int $element1_type , resource $element1 [, int $... [, resource $... ]] ) : resource
Warning

This function is currently not documented; only its argument list is available.

Parameters

element1_type

element1

Return Values


Description

  • « newt_grid_h_close_stacked
  • newt_grid_place »
  • PHP Manual
  • Newt Functions
  • Description

newt_grid_h_stacked

(PECL newt >= 0.1)

newt_grid_h_stacked —

Description

newt_grid_h_stacked ( int $element1_type , resource $element1 [, int $... [, resource $... ]] ) : resource
Warning

This function is currently not documented; only its argument list is available.

Parameters

element1_type

element1

Return Values


Description

  • « newt_grid_h_stacked
  • newt_grid_set_field »
  • PHP Manual
  • Newt Functions
  • Description

newt_grid_place

(PECL newt >= 0.1)

newt_grid_place —

Description

newt_grid_place ( resource $grid , int $left , int $top ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

grid

left

top

Return Values

No value is returned.


Description

  • « newt_grid_place
  • newt_grid_simple_window »
  • PHP Manual
  • Newt Functions
  • Description

newt_grid_set_field

(PECL newt >= 0.1)

newt_grid_set_field —

Description

newt_grid_set_field ( resource $grid , int $col , int $row , int $type , resource $val , int $pad_left , int $pad_top , int $pad_right , int $pad_bottom , int $anchor [, int $flags ] ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

grid

col

row

type

val

pad_left

pad_top

pad_right

pad_bottom

anchor

flags

Return Values

No value is returned.


Description

  • « newt_grid_set_field
  • newt_grid_v_close_stacked »
  • PHP Manual
  • Newt Functions
  • Description

newt_grid_simple_window

(PECL newt >= 0.1)

newt_grid_simple_window —

Description

newt_grid_simple_window ( resource $text , resource $middle , resource $buttons ) : resource
Warning

This function is currently not documented; only its argument list is available.

Parameters

text

middle

buttons

Return Values


Description

  • « newt_grid_simple_window
  • newt_grid_v_stacked »
  • PHP Manual
  • Newt Functions
  • Description

newt_grid_v_close_stacked

(PECL newt >= 0.1)

newt_grid_v_close_stacked —

Description

newt_grid_v_close_stacked ( int $element1_type , resource $element1 [, int $... [, resource $... ]] ) : resource
Warning

This function is currently not documented; only its argument list is available.

Parameters

element1_type

element1

Return Values


Description

  • « newt_grid_v_close_stacked
  • newt_grid_wrapped_window_at »
  • PHP Manual
  • Newt Functions
  • Description

newt_grid_v_stacked

(PECL newt >= 0.1)

newt_grid_v_stacked —

Description

newt_grid_v_stacked ( int $element1_type , resource $element1 [, int $... [, resource $... ]] ) : resource
Warning

This function is currently not documented; only its argument list is available.

Parameters

element1_type

element1

Return Values


Description

  • « newt_grid_v_stacked
  • newt_grid_wrapped_window »
  • PHP Manual
  • Newt Functions
  • Description

newt_grid_wrapped_window_at

(PECL newt >= 0.1)

newt_grid_wrapped_window_at —

Description

newt_grid_wrapped_window_at ( resource $grid , string $title , int $left , int $top ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

grid

title

left

top

Return Values

No value is returned.


Description

  • « newt_grid_wrapped_window_at
  • newt_init »
  • PHP Manual
  • Newt Functions
  • Description

newt_grid_wrapped_window

(PECL newt >= 0.1)

newt_grid_wrapped_window —

Description

newt_grid_wrapped_window ( resource $grid , string $title ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

grid

title

Return Values

No value is returned.


Initialize newt

  • « newt_grid_wrapped_window
  • newt_label_set_text »
  • PHP Manual
  • Newt Functions
  • Initialize newt

newt_init

(PECL newt >= 0.1)

newt_init — Initialize newt

Description

newt_init ( void ) : int

Initializes the newt interface. This function must be called before any other newt function.

Return Values

Returns 1 on success, 0 on failure.

See Also

  • newt_finished() - Uninitializes newt interface


Description

  • « newt_init
  • newt_label »
  • PHP Manual
  • Newt Functions
  • Description

newt_label_set_text

(PECL newt >= 0.1)

newt_label_set_text —

Description

newt_label_set_text ( resource $label , string $text ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

label

text

Return Values

No value is returned.


Description

  • « newt_label_set_text
  • newt_listbox_append_entry »
  • PHP Manual
  • Newt Functions
  • Description

newt_label

(PECL newt >= 0.1)

newt_label —

Description

newt_label ( int $left , int $top , string $text ) : resource
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

text

Return Values


Description

  • « newt_label
  • newt_listbox_clear_selection »
  • PHP Manual
  • Newt Functions
  • Description

newt_listbox_append_entry

(PECL newt >= 0.1)

newt_listbox_append_entry —

Description

newt_listbox_append_entry ( resource $listbox , string $text , mixed $data ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

text

data

Return Values

No value is returned.


Description

  • « newt_listbox_append_entry
  • newt_listbox_clear »
  • PHP Manual
  • Newt Functions
  • Description

newt_listbox_clear_selection

(PECL newt >= 0.1)

newt_listbox_clear_selection —

Description

newt_listbox_clear_selection ( resource $listbox ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

Return Values

No value is returned.


Description

  • « newt_listbox_clear_selection
  • newt_listbox_delete_entry »
  • PHP Manual
  • Newt Functions
  • Description

newt_listbox_clear

(PECL newt >= 0.1)

newt_listbox_clear —

Description

newt_listbox_clear ( resource $listobx ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

listobx

Return Values

No value is returned.


Description

  • « newt_listbox_clear
  • newt_listbox_get_current »
  • PHP Manual
  • Newt Functions
  • Description

newt_listbox_delete_entry

(PECL newt >= 0.1)

newt_listbox_delete_entry —

Description

newt_listbox_delete_entry ( resource $listbox , mixed $key ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

key

Return Values

No value is returned.


Description

  • « newt_listbox_delete_entry
  • newt_listbox_get_selection »
  • PHP Manual
  • Newt Functions
  • Description

newt_listbox_get_current

(PECL newt >= 0.1)

newt_listbox_get_current —

Description

newt_listbox_get_current ( resource $listbox ) : string
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

Return Values


Description

  • « newt_listbox_get_current
  • newt_listbox_insert_entry »
  • PHP Manual
  • Newt Functions
  • Description

newt_listbox_get_selection

(PECL newt >= 0.1)

newt_listbox_get_selection —

Description

newt_listbox_get_selection ( resource $listbox ) : array
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

Return Values


Description

  • « newt_listbox_get_selection
  • newt_listbox_item_count »
  • PHP Manual
  • Newt Functions
  • Description

newt_listbox_insert_entry

(PECL newt >= 0.1)

newt_listbox_insert_entry —

Description

newt_listbox_insert_entry ( resource $listbox , string $text , mixed $data , mixed $key ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

text

data

key

Return Values

No value is returned.


Description

  • « newt_listbox_insert_entry
  • newt_listbox_select_item »
  • PHP Manual
  • Newt Functions
  • Description

newt_listbox_item_count

(PECL newt >= 0.1)

newt_listbox_item_count —

Description

newt_listbox_item_count ( resource $listbox ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

Return Values


Description

  • « newt_listbox_item_count
  • newt_listbox_set_current_by_key »
  • PHP Manual
  • Newt Functions
  • Description

newt_listbox_select_item

(PECL newt >= 0.1)

newt_listbox_select_item —

Description

newt_listbox_select_item ( resource $listbox , mixed $key , int $sense ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

key

sense

Return Values

No value is returned.


Description

  • « newt_listbox_select_item
  • newt_listbox_set_current »
  • PHP Manual
  • Newt Functions
  • Description

newt_listbox_set_current_by_key

(PECL newt >= 0.1)

newt_listbox_set_current_by_key —

Description

newt_listbox_set_current_by_key ( resource $listbox , mixed $key ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

key

Return Values

No value is returned.


Description

  • « newt_listbox_set_current_by_key
  • newt_listbox_set_data »
  • PHP Manual
  • Newt Functions
  • Description

newt_listbox_set_current

(PECL newt >= 0.1)

newt_listbox_set_current —

Description

newt_listbox_set_current ( resource $listbox , int $num ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

num

Return Values

No value is returned.


Description

  • « newt_listbox_set_current
  • newt_listbox_set_entry »
  • PHP Manual
  • Newt Functions
  • Description

newt_listbox_set_data

(PECL newt >= 0.1)

newt_listbox_set_data —

Description

newt_listbox_set_data ( resource $listbox , int $num , mixed $data ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

num

data

Return Values

No value is returned.


Description

  • « newt_listbox_set_data
  • newt_listbox_set_width »
  • PHP Manual
  • Newt Functions
  • Description

newt_listbox_set_entry

(PECL newt >= 0.1)

newt_listbox_set_entry —

Description

newt_listbox_set_entry ( resource $listbox , int $num , string $text ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

num

text

Return Values

No value is returned.


Description

  • « newt_listbox_set_entry
  • newt_listbox »
  • PHP Manual
  • Newt Functions
  • Description

newt_listbox_set_width

(PECL newt >= 0.1)

newt_listbox_set_width —

Description

newt_listbox_set_width ( resource $listbox , int $width ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

listbox

width

Return Values

No value is returned.


Description

  • « newt_listbox_set_width
  • newt_listitem_get_data »
  • PHP Manual
  • Newt Functions
  • Description

newt_listbox

(PECL newt >= 0.1)

newt_listbox —

Description

newt_listbox ( int $left , int $top , int $height [, int $flags ] ) : resource
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

height

flags

Return Values


Description

  • « newt_listbox
  • newt_listitem_set »
  • PHP Manual
  • Newt Functions
  • Description

newt_listitem_get_data

(PECL newt >= 0.1)

newt_listitem_get_data —

Description

newt_listitem_get_data ( resource $item ) : mixed
Warning

This function is currently not documented; only its argument list is available.

Parameters

item

Return Values


Description

  • « newt_listitem_get_data
  • newt_listitem »
  • PHP Manual
  • Newt Functions
  • Description

newt_listitem_set

(PECL newt >= 0.1)

newt_listitem_set —

Description

newt_listitem_set ( resource $item , string $text ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

item

text

Return Values

No value is returned.


Description

  • « newt_listitem_set
  • newt_open_window »
  • PHP Manual
  • Newt Functions
  • Description

newt_listitem

(PECL newt >= 0.1)

newt_listitem —

Description

newt_listitem ( int $left , int $top , string $text , bool $is_default , resouce $prev_item , mixed $data [, int $flags ] ) : resource
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

text

is_default

prev_item

data

flags

Return Values


Open a window of the specified size and position

  • « newt_listitem
  • newt_pop_help_line »
  • PHP Manual
  • Newt Functions
  • Open a window of the specified size and position

newt_open_window

(PECL newt >= 0.1)

newt_open_window — Open a window of the specified size and position

Description

newt_open_window ( int $left , int $top , int $width , int $height [, string $title ] ) : int

Open a window of the specified size and position.

Parameters

left

Location of the upper left-hand corner of the window (column number)

top

Location of the upper left-hand corner of the window (row number)

width

Window width

height

Window height

title

Window title

Return Values

Returns 1 on success, 0 on failure.

See Also

  • newt_pop_window() - Removes the top window from the display
  • newt_centered_window() - Open a centered window of the specified size


Replaces the current help line with the one from the stack

  • « newt_open_window
  • newt_pop_window »
  • PHP Manual
  • Newt Functions
  • Replaces the current help line with the one from the stack

newt_pop_help_line

(PECL newt >= 0.1)

newt_pop_help_line — Replaces the current help line with the one from the stack

Description

newt_pop_help_line ( void ) : void

Replaces the current help line with the one from the stack.

Note:

It's important not to call to newt_pop_help_line() more than newt_push_help_line().

Return Values

No value is returned.

See Also

  • newt_push_help_line() - Saves the current help line on a stack, and displays the new line


Removes the top window from the display

  • « newt_pop_help_line
  • newt_push_help_line »
  • PHP Manual
  • Newt Functions
  • Removes the top window from the display

newt_pop_window

(PECL newt >= 0.1)

newt_pop_window — Removes the top window from the display

Description

newt_pop_window ( void ) : void

Removes the top window from the display, and redraws the display areas which the window overwrote.

Return Values

No value is returned.

See Also

  • newt_open_window() - Open a window of the specified size and position
  • newt_centered_window() - Open a centered window of the specified size


Saves the current help line on a stack, and displays the new line

  • « newt_pop_window
  • newt_radio_get_current »
  • PHP Manual
  • Newt Functions
  • Saves the current help line on a stack, and displays the new line

newt_push_help_line

(PECL newt >= 0.1)

newt_push_help_line — Saves the current help line on a stack, and displays the new line

Description

newt_push_help_line ([ string $text ] ) : void

Saves the current help line on a stack, and displays the new line.

Parameters

text

New help text message

Note:

If not specified, the help line is cleared.

Return Values

No value is returned.

See Also

  • newt_pop_help_line() - Replaces the current help line with the one from the stack


Description

  • « newt_push_help_line
  • newt_radiobutton »
  • PHP Manual
  • Newt Functions
  • Description

newt_radio_get_current

(PECL newt >= 0.1)

newt_radio_get_current —

Description

newt_radio_get_current ( resource $set_member ) : resource
Warning

This function is currently not documented; only its argument list is available.

Parameters

set_member

Return Values


Description

  • « newt_radio_get_current
  • newt_redraw_help_line »
  • PHP Manual
  • Newt Functions
  • Description

newt_radiobutton

(PECL newt >= 0.1)

newt_radiobutton —

Description

newt_radiobutton ( int $left , int $top , string $text , bool $is_default [, resource $prev_button ] ) : resource
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

text

is_default

prev_button

Return Values


Description

  • « newt_radiobutton
  • newt_reflow_text »
  • PHP Manual
  • Newt Functions
  • Description

newt_redraw_help_line

(PECL newt >= 0.1)

newt_redraw_help_line —

Description

newt_redraw_help_line ( void ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

Return Values

No value is returned.


Description

  • « newt_redraw_help_line
  • newt_refresh »
  • PHP Manual
  • Newt Functions
  • Description

newt_reflow_text

(PECL newt >= 0.1)

newt_reflow_text —

Description

newt_reflow_text ( string $text , int $width , int $flex_down , int $flex_up , int &$actual_width , int &$actual_height ) : string
Warning

This function is currently not documented; only its argument list is available.

Parameters

text

width

flex_down

flex_up

actual_width

actual_height

Return Values


Updates modified portions of the screen

  • « newt_reflow_text
  • newt_resize_screen »
  • PHP Manual
  • Newt Functions
  • Updates modified portions of the screen

newt_refresh

(PECL newt >= 0.1)

newt_refresh — Updates modified portions of the screen

Description

newt_refresh ( void ) : void

To increase performance, newt only updates the display when it needs to, not when the program tells it to write to the terminal. Applications can force newt to immediately update modified portions of the screen by calling this function.

Return Values

No value is returned.


Description

  • « newt_refresh
  • newt_resume »
  • PHP Manual
  • Newt Functions
  • Description

newt_resize_screen

(PECL newt >= 0.1)

newt_resize_screen —

Description

newt_resize_screen ([ bool $redraw ] ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

redraw

Return Values

No value is returned.


Resume using the newt interface after calling newt_suspend

  • « newt_resize_screen
  • newt_run_form »
  • PHP Manual
  • Newt Functions
  • Resume using the newt interface after calling newt_suspend

newt_resume

(PECL newt >= 0.1)

newt_resume — Resume using the newt interface after calling newt_suspend()

Description

newt_resume ( void ) : void

Resume using the newt interface after calling newt_suspend().

Return Values

No value is returned.

See Also

  • newt_suspend() - Tells newt to return the terminal to its initial state


Runs a form

  • « newt_resume
  • newt_scale_set »
  • PHP Manual
  • Newt Functions
  • Runs a form

newt_run_form

(PECL newt >= 0.1)

newt_run_form — Runs a form

Description

newt_run_form ( resource $form ) : resource

This function runs the form passed to it.

Parameters

form

Form component

Return Values

The component which caused the form to stop running.

Note:

Notice that this function doesn't fit in with newt's normal naming convention. It is an older interface which will not work for all forms. It was left in newt only for legacy applications. It is a simpler interface than the new newt_form_run() though, and is still used quite often as a result. When an application is done with a form, it destroys the form and all of the components the form contains.

See Also

  • newt_form_run() - Runs a form
  • newt_form_destroy() - Destroys a form


Description

  • « newt_run_form
  • newt_scale »
  • PHP Manual
  • Newt Functions
  • Description

newt_scale_set

(PECL newt >= 0.1)

newt_scale_set —

Description

newt_scale_set ( resource $scale , int $amount ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

scale

amount

Return Values

No value is returned.


Description

  • « newt_scale_set
  • newt_scrollbar_set »
  • PHP Manual
  • Newt Functions
  • Description

newt_scale

(PECL newt >= 0.1)

newt_scale —

Description

newt_scale ( int $left , int $top , int $width , int $full_value ) : resource
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

width

full_value

Return Values


Description

  • « newt_scale
  • newt_set_help_callback »
  • PHP Manual
  • Newt Functions
  • Description

newt_scrollbar_set

(PECL newt >= 0.1)

newt_scrollbar_set —

Description

newt_scrollbar_set ( resource $scrollbar , int $where , int $total ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

scrollbar

where

total

Return Values

No value is returned.


Description

  • « newt_scrollbar_set
  • newt_set_suspend_callback »
  • PHP Manual
  • Newt Functions
  • Description

newt_set_help_callback

(PECL newt >= 0.1)

newt_set_help_callback —

Description

newt_set_help_callback ( mixed $function ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

function

Return Values

No value is returned.


Set a callback function which gets invoked when user presses the suspend key

  • « newt_set_help_callback
  • newt_suspend »
  • PHP Manual
  • Newt Functions
  • Set a callback function which gets invoked when user presses the suspend key

newt_set_suspend_callback

(PECL newt >= 0.1)

newt_set_suspend_callback — Set a callback function which gets invoked when user presses the suspend key

Description

newt_set_suspend_callback ( callable $function , mixed $data ) : void

Set a callback function which gets invoked when user presses the suspend key (normally ^Z). If no suspend callback is registered, the suspend keystroke is ignored.

Parameters

function

A callback function, which accepts one argument: data

data

This data is been passed to the callback function

Return Values

No value is returned.

See Also

  • newt_suspend() - Tells newt to return the terminal to its initial state
  • newt_resume() - Resume using the newt interface after calling newt_suspend


Tells newt to return the terminal to its initial state

  • « newt_set_suspend_callback
  • newt_textbox_get_num_lines »
  • PHP Manual
  • Newt Functions
  • Tells newt to return the terminal to its initial state

newt_suspend

(PECL newt >= 0.1)

newt_suspend — Tells newt to return the terminal to its initial state

Description

newt_suspend ( void ) : void

Tells newt to return the terminal to its initial state. Once this is done, the application can suspend itself (by sending itself a SIGTSTP, fork a child program, or do whatever else it likes).

Return Values

No value is returned.

See Also

  • newt_resume() - Resume using the newt interface after calling newt_suspend


Description

  • « newt_suspend
  • newt_textbox_reflowed »
  • PHP Manual
  • Newt Functions
  • Description

newt_textbox_get_num_lines

(PECL newt >= 0.1)

newt_textbox_get_num_lines —

Description

newt_textbox_get_num_lines ( resource $textbox ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

textbox

Return Values


Description

  • « newt_textbox_get_num_lines
  • newt_textbox_set_height »
  • PHP Manual
  • Newt Functions
  • Description

newt_textbox_reflowed

(PECL newt >= 0.1)

newt_textbox_reflowed —

Description

newt_textbox_reflowed ( int $left , int $top , char $*text , int $width , int $flex_down , int $flex_up [, int $flags ] ) : resource
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

*text

width

flex_down

flex_up

flags

Return Values


Description

  • « newt_textbox_reflowed
  • newt_textbox_set_text »
  • PHP Manual
  • Newt Functions
  • Description

newt_textbox_set_height

(PECL newt >= 0.1)

newt_textbox_set_height —

Description

newt_textbox_set_height ( resource $textbox , int $height ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

textbox

height

Return Values

No value is returned.


Description

  • « newt_textbox_set_height
  • newt_textbox »
  • PHP Manual
  • Newt Functions
  • Description

newt_textbox_set_text

(PECL newt >= 0.1)

newt_textbox_set_text —

Description

newt_textbox_set_text ( resource $textbox , string $text ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

textbox

text

Return Values

No value is returned.


Description

  • « newt_textbox_set_text
  • newt_vertical_scrollbar »
  • PHP Manual
  • Newt Functions
  • Description

newt_textbox

(PECL newt >= 0.1)

newt_textbox —

Description

newt_textbox ( int $left , int $top , int $width , int $height [, int $flags ] ) : resource
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

width

height

flags

Return Values


Description

  • « newt_textbox
  • newt_wait_for_key »
  • PHP Manual
  • Newt Functions
  • Description

newt_vertical_scrollbar

(PECL newt >= 0.1)

newt_vertical_scrollbar —

Description

newt_vertical_scrollbar ( int $left , int $top , int $height [, int $normal_colorset [, int $thumb_colorset ]] ) : resource
Warning

This function is currently not documented; only its argument list is available.

Parameters

left

top

height

normal_colorset

thumb_colorset

Return Values


Doesn't return until a key has been pressed

  • « newt_vertical_scrollbar
  • newt_win_choice »
  • PHP Manual
  • Newt Functions
  • Doesn't return until a key has been pressed

newt_wait_for_key

(PECL newt >= 0.1)

newt_wait_for_key — Doesn't return until a key has been pressed

Description

newt_wait_for_key ( void ) : void

This function doesn't return until a key has been pressed. The keystroke is then ignored. If a key is already in the terminal's buffer, this function discards a keystroke and returns immediately.

Return Values

No value is returned.

See Also

  • newt_clear_key_buffer() - Discards the contents of the terminal's input buffer without waiting for additional input


Description

  • « newt_wait_for_key
  • newt_win_entries »
  • PHP Manual
  • Newt Functions
  • Description

newt_win_choice

(PECL newt >= 0.1)

newt_win_choice —

Description

newt_win_choice ( string $title , string $button1_text , string $button2_text , string $format [, mixed $args [, mixed $... ]] ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

title

button1_text

button2_text

format

args

Return Values


Description

  • « newt_win_choice
  • newt_win_menu »
  • PHP Manual
  • Newt Functions
  • Description

newt_win_entries

(PECL newt >= 0.1)

newt_win_entries —

Description

newt_win_entries ( string $title , string $text , int $suggested_width , int $flex_down , int $flex_up , int $data_width , array &$items , string $button1 [, string $... ] ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

title

text

suggested_width

flex_down

flex_up

data_width

items

button1

button2

Return Values

Examples

Example #1 A newt_win_entries() example

<?php

newt_init();
newt_cls();

$entries[] = array('text' => 'First name:', 'value' => &$f_name);
$entries[] = array('text' => 'Last name:',  'value' => &$l_name);

$rc = newt_win_entries("User information", "Please enter your credentials:", 50, 7, 7, 30, $entries, "Ok", "Back");
newt_finished ();

if ($rc != 2) {
    echo "Your name is: $f_name $l_name\n";
}
?>


Description

  • « newt_win_entries
  • newt_win_message »
  • PHP Manual
  • Newt Functions
  • Description

newt_win_menu

(PECL newt >= 0.1)

newt_win_menu —

Description

newt_win_menu ( string $title , string $text , int $suggestedWidth , int $flexDown , int $flexUp , int $maxListHeight , array $items , int &$listItem [, string $button1 [, string $... ]] ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

title

text

suggestedWidth

flexDown

flexUp

maxListHeight

items

listItem

button1

Return Values

No value is returned.


Description

  • « newt_win_menu
  • newt_win_messagev »
  • PHP Manual
  • Newt Functions
  • Description

newt_win_message

(PECL newt >= 0.1)

newt_win_message —

Description

newt_win_message ( string $title , string $button_text , string $format [, mixed $args [, mixed $... ]] ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

title

button_text

format

args

Return Values

No value is returned.


Description

  • « newt_win_message
  • newt_win_ternary »
  • PHP Manual
  • Newt Functions
  • Description

newt_win_messagev

(PECL newt >= 0.1)

newt_win_messagev —

Description

newt_win_messagev ( string $title , string $button_text , string $format , array $args ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

title

button_text

format

args

Return Values

No value is returned.


Description

  • « newt_win_messagev
  • Readline »
  • PHP Manual
  • Newt Functions
  • Description

newt_win_ternary

(PECL newt >= 0.1)

newt_win_ternary —

Description

newt_win_ternary ( string $title , string $button1_text , string $button2_text , string $button3_text , string $format [, mixed $args [, mixed $... ]] ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

title

Its description

button1_text

Its description

button2_text

Its description

button3_text

Its description

format

Its description

args

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity


GNU Readline

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Readline Functions
    • 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 — Reads a line


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.


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 » http://cnswww.cns.cwru.edu/~chet/readline/rltop.html. It's maintained by Chet Ramey, who's also the author of Bash.

You can also use these functions with the libedit library, a non-GPL replacement for the readline library. The libedit library is BSD licensed and available for download from » http://www.thrysoee.dk/editline/.


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 | "" | PHP_INI_ALL | Available since PHP 5.4.0.
cli.prompt | "\\b \\> " | PHP_INI_ALL | Available since PHP 5.4.0.

Here's a short explanation of the configuration directives.

cli.pager string

External tool to display output from command line.

cli.prompt string

Command line prompt.


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. Available as of PHP 5.5.0.


Readline Functions

Table of Contents

  • 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 — Reads a line


Adds a line to the history

  • « Readline Functions
  • readline_callback_handler_install »
  • PHP Manual
  • Readline Functions
  • Adds a line to the history

readline_add_history

(PHP 4, PHP 5, PHP 7)

readline_add_history — Adds a line to the history

Description

readline_add_history ( string $line ) : bool

This function adds a line to the command line history.

Parameters

line

The line to be added in the history.

Return Values

Returns TRUE on success or FALSE on failure.


Initializes the readline callback interface and terminal, prints the prompt and returns immediately

  • « readline_add_history
  • readline_callback_handler_remove »
  • PHP Manual
  • Readline Functions
  • Initializes the readline callback interface and terminal, prints the prompt and returns immediately

readline_callback_handler_install

(PHP 5 >= 5.1.0, PHP 7)

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 ) : bool

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

Returns TRUE on success or FALSE on failure.

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 tv_sec and tv_usec


Removes a previously installed callback handler and restores terminal settings

  • « readline_callback_handler_install
  • readline_callback_read_char »
  • PHP Manual
  • Readline Functions
  • Removes a previously installed callback handler and restores terminal settings

readline_callback_handler_remove

(PHP 5 >= 5.1.0, PHP 7)

readline_callback_handler_remove — Removes a previously installed callback handler and restores terminal settings

Description

readline_callback_handler_remove ( void ) : bool

Removes a previously installed callback handler and restores terminal settings.

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


Reads a character and informs the readline callback interface when a line is received

  • « readline_callback_handler_remove
  • readline_clear_history »
  • PHP Manual
  • Readline Functions
  • 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)

readline_callback_read_char — Reads a character and informs the readline callback interface when a line is received

Description

readline_callback_read_char ( void ) : 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.

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


Clears the history

  • « readline_callback_read_char
  • readline_completion_function »
  • PHP Manual
  • Readline Functions
  • Clears the history

readline_clear_history

(PHP 4, PHP 5, PHP 7)

readline_clear_history — Clears the history

Description

readline_clear_history ( void ) : bool

This function clears the entire command line history.

Return Values

Returns TRUE on success or FALSE on failure.


Registers a completion function

  • « readline_clear_history
  • readline_info »
  • PHP Manual
  • Readline Functions
  • Registers a completion function

readline_completion_function

(PHP 4, PHP 5, PHP 7)

readline_completion_function — Registers a completion function

Description

readline_completion_function ( callable $function ) : 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

function

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.


Gets/sets various internal readline variables

  • « readline_completion_function
  • readline_list_history »
  • PHP Manual
  • Readline Functions
  • Gets/sets various internal readline variables

readline_info

(PHP 4, PHP 5, PHP 7)

readline_info — Gets/sets various internal readline variables

Description

readline_info ([ string $varname [, string $newvalue ]] ) : mixed

Gets or sets various internal readline variables.

Parameters

varname

A variable name.

newvalue

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 setting readline uses. The elements will be indexed by the following values: done, end, erase_empty_line, library_version, line_buffer, mark, pending_input, point, prompt, readline_name, and terminal_name.

If called with one or two parameters, the old value is returned.


Lists the history

  • « readline_info
  • readline_on_new_line »
  • PHP Manual
  • Readline Functions
  • Lists the history

readline_list_history

(PHP 4, PHP 5, PHP 7)

readline_list_history — Lists the history

Description

readline_list_history ( void ) : array

Gets the entire command line history.

Return Values

Returns an array of the entire command line history. The elements are indexed by integers starting at zero.


Inform readline that the cursor has moved to a new line

  • « readline_list_history
  • readline_read_history »
  • PHP Manual
  • Readline Functions
  • Inform readline that the cursor has moved to a new line

readline_on_new_line

(PHP 5 >= 5.1.0, PHP 7)

readline_on_new_line — Inform readline that the cursor has moved to a new line

Description

readline_on_new_line ( void ) : void

Tells readline that the cursor has moved to a new line.

Return Values

No value is returned.


Reads the history

  • « readline_on_new_line
  • readline_redisplay »
  • PHP Manual
  • Readline Functions
  • Reads the history

readline_read_history

(PHP 4, PHP 5, PHP 7)

readline_read_history — Reads the history

Description

readline_read_history ([ string $filename ] ) : 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.


Redraws the display

  • « readline_read_history
  • readline_write_history »
  • PHP Manual
  • Readline Functions
  • Redraws the display

readline_redisplay

(PHP 5 >= 5.1.0, PHP 7)

readline_redisplay — Redraws the display

Description

readline_redisplay ( void ) : void

Redraws readline to redraw the display.

Return Values

No value is returned.


Writes the history

  • « readline_redisplay
  • readline »
  • PHP Manual
  • Readline Functions
  • Writes the history

readline_write_history

(PHP 4, PHP 5, PHP 7)

readline_write_history — Writes the history

Description

readline_write_history ([ string $filename ] ) : 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.


Reads a line

  • « readline_write_history
  • Compression and Archive Extensions »
  • PHP Manual
  • Readline Functions
  • Reads a line

readline

(PHP 4, PHP 5, PHP 7)

readline — Reads a line

Description

readline ([ string $prompt = NULL ] ) : string

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.

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());
?>


Compression and Archive Extensions

  • Bzip2
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Bzip2 Functions
  • LZF
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • LZF Functions
  • Phar
    • Introduction
    • 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
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Rar Functions
    • RarArchive — The RarArchive class
    • RarEntry — The RarEntry class
    • RarException — The RarException class
  • Zip
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • ZipArchive — The ZipArchive class
    • Zip Functions
  • Zlib — Zlib Compression
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Zlib Functions


Bzip2

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • 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 — Force a write of all buffered data
    • bzopen — Opens a bzip2 compressed file
    • bzread — Binary safe bzip2 file read
    • bzwrite — Binary safe bzip2 file write


Introduction

The bzip2 functions are used to transparently read and write bzip2 (.bz2) compressed files.


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.


  • « Runtime Configuration
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

This extension defines one resource type: a file pointer identifying the bz2-file to work on.


  • « Resource Types
  • Examples »
  • PHP Manual
  • Bzip2
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


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

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 — Force a write of all buffered data
  • bzopen — Opens a bzip2 compressed file
  • bzread — Binary safe bzip2 file read
  • bzwrite — Binary safe bzip2 file write


Close a bzip2 file

  • « Bzip2 Functions
  • bzcompress »
  • PHP Manual
  • Bzip2 Functions
  • Close a bzip2 file

bzclose

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

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


Compress a string into bzip2 encoded data

  • « bzclose
  • bzdecompress »
  • PHP Manual
  • Bzip2 Functions
  • Compress a string into bzip2 encoded data

bzcompress

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

bzcompress — Compress a string into bzip2 encoded data

Description

bzcompress ( string $source [, int $blocksize = 4 [, int $workfactor = 0 ]] ) : mixed

bzcompress() compresses the given string and returns it as bzip2 encoded data.

Parameters

source

The string to compress.

blocksize

Specifies the blocksize used during compression and should be a number from 1 to 9 with 9 giving the best compression, but using more resources to do so.

workfactor

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 workfactor, 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


Decompresses bzip2 encoded data

  • « bzcompress
  • bzerrno »
  • PHP Manual
  • Bzip2 Functions
  • Decompresses bzip2 encoded data

bzdecompress

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

bzdecompress — Decompresses bzip2 encoded data

Description

bzdecompress ( string $source [, int $small = 0 ] ) : mixed

bzdecompress() decompresses the given string containing bzip2 encoded data.

Parameters

source

The string to decompress.

small

If TRUE, an alternative decompression algorithm will be used which uses less memory (the maximum memory requirement drops to around 2300K) but works at roughly half the speed.

See the » bzip2 documentation for more information about this feature.

Return Values

The decompressed string, or an error number if an error occurred.

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


Returns a bzip2 error number

  • « bzdecompress
  • bzerror »
  • PHP Manual
  • Bzip2 Functions
  • Returns a bzip2 error number

bzerrno

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

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


Returns the bzip2 error number and error string in an array

  • « bzerrno
  • bzerrstr »
  • PHP Manual
  • Bzip2 Functions
  • Returns the bzip2 error number and error string in an array

bzerror

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

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


Returns a bzip2 error string

  • « bzerror
  • bzflush »
  • PHP Manual
  • Bzip2 Functions
  • Returns a bzip2 error string

bzerrstr

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

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


Force a write of all buffered data

  • « bzerrstr
  • bzopen »
  • PHP Manual
  • Bzip2 Functions
  • Force a write of all buffered data

bzflush

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

bzflush — Force a write of all buffered data

Description

bzflush ( resource $bz ) : bool

Forces a write of all buffered bzip2 data for the file pointer bz.

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


Opens a bzip2 compressed file

  • « bzflush
  • bzread »
  • PHP Manual
  • Bzip2 Functions
  • Opens a bzip2 compressed file

bzopen

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

bzopen — Opens a bzip2 compressed file

Description

bzopen ( mixed $file , string $mode ) : resource

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


Binary safe bzip2 file read

  • « bzopen
  • bzwrite »
  • PHP Manual
  • Bzip2 Functions
  • Binary safe bzip2 file read

bzread

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

bzread — Binary safe bzip2 file read

Description

bzread ( resource $bz [, int $length = 1024 ] ) : string

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


Binary safe bzip2 file write

  • « bzread
  • LZF »
  • PHP Manual
  • Bzip2 Functions
  • Binary safe bzip2 file write

bzwrite

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

bzwrite — Binary safe bzip2 file write

Description

bzwrite ( resource $bz , string $data [, int $length ] ) : int

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.

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


LZF

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • LZF Functions
    • lzf_compress — LZF compression
    • lzf_decompress — LZF decompression
    • lzf_optimized_for — Determines what LZF extension was optimized for


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.


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. A DLL for this PECL extension is currently unavailable. See also the building on Windows section.


  • « Resource Types
  • LZF Functions »
  • PHP Manual
  • LZF
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


LZF Functions

Table of Contents

  • lzf_compress — LZF compression
  • lzf_decompress — LZF decompression
  • lzf_optimized_for — Determines what LZF extension was optimized for


LZF compression

  • « LZF Functions
  • lzf_decompress »
  • PHP Manual
  • LZF Functions
  • LZF compression

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 decompression

  • « lzf_compress
  • lzf_optimized_for »
  • PHP Manual
  • LZF Functions
  • 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


Determines what LZF extension was optimized for

  • « lzf_decompress
  • Phar »
  • PHP Manual
  • LZF Functions
  • Determines what LZF extension was optimized for

lzf_optimized_for

(PECL lzf >= 1.0.0)

lzf_optimized_for — Determines what LZF extension was optimized for

Description

lzf_optimized_for ( void ) : int

Determines what was LZF extension optimized for during compilation.

Return Values

Returns 1 if LZF was optimized for speed, 0 for compression.


Phar

  • Introduction
  • 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::compressAllFilesBZIP2 — Compresses all files in the current Phar archive using Bzip2 compression
    • Phar::compressAllFilesGZ — Compresses all files in the current Phar archive using Gzip 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::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::uncompressAllFiles — Uncompresses all files in the current Phar archive
    • Phar::unlinkArchive — Completely remove a phar archive from disk and from memory
    • Phar::webPhar — mapPhar for web-based phars. front controller for web applications
  • 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 the filesystem 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 phar archive to another new file within the phar
    • 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::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)
    • Phar::setMetadata — Sets phar archive meta-data
    • Phar::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::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::isCompressedBZIP2 — Returns whether the entry is compressed using bzip2
    • PharFileInfo::isCompressedGZ — Returns whether the entry is compressed using gz
    • PharFileInfo::setCompressedBZIP2 — Compresses the current Phar entry within the phar using Bzip2 compression
    • PharFileInfo::setCompressedGZ — Compresses the current Phar entry within the phar using gz compression
    • PharFileInfo::setMetadata — Sets file-specific meta-data saved with a file
    • PharFileInfo::setUncompressed — Uncompresses the current Phar entry within the phar, if it is compressed
  • PharException — The PharException class


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.


Requirements

Phar requires PHP 5.2.0 or newer. Additional features require the SPL extension in order to take advantage of iteration and array access to a Phar's file contents. The phar stream does not require any additional extensions to function.

You may optionally wish to enable the zlib and bzip2 extensions to take advantage of compressed phar support. In addition, to take advantage of OpenSSL signing, the OpenSSL extension must be enabled.

Note that a bug in the zlib.deflate stream filter fixed in PHP version 5.2.6 and newer may cause truncation of gzip and bzip2-compressed phar archives.

PHP 5.3 configured with --enable-zend-multibyte makes phar dependant on the ini option detect_unicode.


Installation

The Phar extension is bundled with PHP as of PHP version 5.3.0, 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" | PHP_INI_ALL |
phar.require_hash | "1" | PHP_INI_ALL |
phar.extract_list | "" | PHP_INI_ALL | Available from phar 1.1.0 to 1.2.3, removed in 2.0.0.
phar.cache_list | "" | PHP_INI_SYSTEM | Available from phar 2.0.0.

Here's a short explanation of the configuration directives.

phar.readonly boolean

This option disables creation or modification of Phar archives using the phar stream or Phar object's write support. This setting should always be enabled on production machines, as the phar extension's convenient write support could allow straightforward creation of a php-based virus when coupled with other common security vulnerabilities.

Note:

This setting can only be unset in php.ini due to security reasons. If phar.readonly is disabled in php.ini, the user may enable phar.readonly in a script or disable it later. If phar.readonly is enabled in php.ini, a script may harmlessly "re-enable" the INI variable, but may not disable it.

phar.require_hash boolean

This option will force all opened Phar archives to contain some kind of signature (currently MD5, SHA1, SHA256 and SHA512 are supported), and will refuse to process any Phar archive that does not contain a signature.

Note:

This setting can only be unset in php.ini due to security reasons. If phar.require_hash is disabled in php.ini, the user may enable phar.require_hash in a script or disable it later. If phar.require_hash is enabled in php.ini, a script may harmlessly "re-enable" the INI variable, but may not disable it.

This setting does not affect reading plain tar files with the PharData class.

phar.extract_list string

This INI setting has been removed as of phar 2.0.0

Allows mappings from a full path to a phar archive or its alias to the location of its extracted files. The format of the parameter is name=archive,name2=archive2. This allows extraction of phar files to disk, and allows phar to act as a kind of mapper to extracted disk files. This is often done for performance reasons, or to assist with debugging a phar.

Example #1 phar.extract_list usage example

in php.ini:
phar.extract_list = archive=/full/path/to/archive/,arch2=/full/path/to/arch2
<?php
include "phar://archive/content.php";
include "phar://arch2/foo.php";
?>

phar.cache_list string

This INI setting was added in phar 2.0.0

Allows mapping phar archives to be pre-parsed at web server startup, providing a performance improvement that brings running files out of a phar archive very close to the speed of running those files from a traditional disk-based installation.

Example #2 phar.cache_list usage example

in php.ini (windows):
phar.cache_list =C:\path\to\phar1.phar;C:\path\to\phar2.phar
in php.ini (unix):
phar.cache_list =/path/to/phar1.phar:/path/to/phar2.phar


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 (integer) | 0x00000000 | no compression
Phar::COMPRESSED (integer) | 0x0000F000 | bitmask that can be used with file flags to determine if any compression is present
Phar::GZ (integer) | 0x00001000 | zlib (gzip) compression
Phar::BZ2 (integer) | 0x00002000 | bzip2 compression
Phar file format constants
Constant | Value | Description
Phar::PHAR (integer) | 1 | phar file format
Phar::TAR (integer) | 2 | tar file format
Phar::ZIP (integer) | 3 | zip file format
Phar signature constants
Constant | Value | Description
Phar::MD5 (integer) | 0x0001 | signature with md5 hash algorithm
Phar::SHA1 (integer) | 0x0002 | signature with sha1 hash algorithm
Phar::SHA256 (integer) | 0x0003 | signature with sha256 hash algorithm (requires hash extension)
Phar::SHA512 (integer) | 0x0004 | signature with sha512 hash algorithm (requires hash extension)
Phar::OPENSSL (integer) | 0x0010 | signature with OpenSSL public/private key pair. This is a true, asymmetric key signature.
Phar webPhar mime override constants
Constant | Value | Description
Phar::PHP (integer) | 0 | used to instruct the mimeoverrides parameter of Phar::webPhar() that the extension should be parsed as a PHP file
Phar::PHPS (integer) | 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 (new in Phar 2.0.0). To take advantage of OpenSSL signing, you need to generate a public/private key pair, and use the private key to set the signature using Phar::setSignatureAlgorithm(). In addition, the public key as extracted using this code:

<?php
$public = openssl_get_publickey(file_get_contents('private.pem'));
$pkey = '';
openssl_pkey_export($public, $pkey);
?>
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.

As of version 2.0.0, The Phar class also provides 3 static methods, Phar::webPhar(), Phar::mungServer() and Phar::interceptFileFuncs() that are crucial to packaging up PHP applications designed for usage on regular filesystems and for web-based applications. Phar::webPhar() implements a front controller that routes HTTP calls to the correct location within the phar archive. Phar::mungServer() is used to modify the values of the $_SERVER array to trick applications that process these values. Phar::interceptFileFuncs() instructs Phar to intercept calls to fopen(), file_get_contents(), opendir(), and all of the stat-based functions (file_exists(), is_readable() and so on) and route all relative paths to locations within the phar archive.

As an example, packaging up a release of the popular phpMyAdmin application for use as a phar archive requires only this simple script and then phpMyAdmin.phar.tar.php can be accessed as a regular file from your web server after modifying the user/password:

<?php
@unlink('phpMyAdmin.phar.tar.php');
copy('phpMyAdmin-2.11.3-english.tar.gz', 'phpMyAdmin.phar.tar.php');
$a = new Phar('phpMyAdmin.phar.tar.php');
$a->startBuffering();
$a["phpMyAdmin-2.11.3-english/config.inc.php"] = '<?php
/* Servers configuration */
$i = 0;

/* Server localhost (config:root) [1] */
$i++;
$cfg[\'Servers\'][$i][\'host\'] = \'localhost\';
$cfg[\'Servers\'][$i][\'extension\'] = \'mysqli\';
$cfg[\'Servers\'][$i][\'connect_type\'] = \'tcp\';
$cfg[\'Servers\'][$i][\'compress\'] = false;
$cfg[\'Servers\'][$i][\'auth_type\'] = \'config\';
$cfg[\'Servers\'][$i][\'user\'] = \'root\';
$cfg[\'Servers\'][$i][\'password\'] = \'\';

/* End of servers configuration */
if (strpos(PHP_OS, \'WIN\') !== false) {
    $cfg[\'UploadDir\'] = getcwd();
} else {
    $cfg[\'UploadDir\'] = \'/tmp/pharphpmyadmin\';
    @mkdir(\'/tmp/pharphpmyadmin\');
    @chmod(\'/tmp/pharphpmyadmin\', 0777);
}';
$a->setStub('<?php
Phar::interceptFileFuncs();
Phar::webPhar("phpMyAdmin.phar", "phpMyAdmin-2.11.3-english/index.php");
echo "phpMyAdmin is intended to be executed from a web browser\n";
exit -1;
__HALT_COMPILER();
');
$a->stopBuffering();
?>


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 as of version 2.0.0, rmdir() and mkdir().

Individual file compression and per-file metadata can also be manipulated in a Phar archive using stream contexts:

<?php
$context = stream_context_create(array('phar' =>
                                    array('compress' => Phar::GZ)),
                                    array('metadata' => array('user' => 'cellog')));
file_put_contents('phar://my.phar/somefile.php', 0, $context);
?>

The phar stream wrapper does not operate on remote files, and cannot operate on remote files, and so is allowed even when the allow_url_fopen and allow_url_include INI options are disabled.

Although it is possible to create phar archives from scratch just using stream operations, it is best to use the functionality built into the Phar class. The stream wrapper is best used for read-only operations.


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.


  • « Using Phar Archives: the Phar and PharData class
  • Creating Phar Archives: Introduction »
  • PHP Manual
  • Phar
  • Creating Phar Archives

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 (PHP 5.3.1+)
Web-specific application support | Yes | Yes | Yes
Per-file Meta-data | Yes | Yes | Yes
Whole-Archive Meta-data | Yes | Yes | Yes
Archive creation/modification [2] | Yes | Yes | Yes
Full support for all stream wrapper functions | Yes | Yes | Yes
Can be created/modified even if phar.readonly=1 [3] | No | Yes | Yes

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.

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 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 compression
0x00002000 | If set, this Phar contains at least 1 file that is compressed with bzip 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 compression
0x00002000 | If set, this file is compressed with bzip 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 two signature formats supported at this time are MD5 and SHA1.

Signature format
Length in bytes | Description
16 or 20 bytes | The actual signature, 20 bytes for an SHA1 signature, 16 bytes for an MD5 signature, 32 bytes for an SHA256 signature, and 64 bytes for an SHA512 signature.
4 bytes | Signature flags. 0x0001 is used to define an MD5 signature, 0x0002 is used to define an SHA1 signature, 0x0004 is used to define an SHA256 signature, and 0x0008 is used to define an SHA512 signature. The SHA256 and SHA512 signature support was introduced with API version 1.1.0.
4 bytes | Magic GBMB used to define the presence of a signature.


The Phar class

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.0.0)

Introduction

The Phar class provides a high-level interface to accessing and creating phar archives.

Class synopsis

Phar extends RecursiveDirectoryIterator implements Countable , ArrayAccess {
/* Inherited constants */
const integer FilesystemIterator::CURRENT_AS_PATHNAME = 32 ;
const integer FilesystemIterator::CURRENT_AS_FILEINFO = 0 ;
const integer FilesystemIterator::CURRENT_AS_SELF = 16 ;
const integer FilesystemIterator::CURRENT_MODE_MASK = 240 ;
const integer FilesystemIterator::KEY_AS_PATHNAME = 0 ;
const integer FilesystemIterator::KEY_AS_FILENAME = 256 ;
const integer FilesystemIterator::FOLLOW_SYMLINKS = 512 ;
const integer FilesystemIterator::KEY_MODE_MASK = 3840 ;
const integer FilesystemIterator::NEW_CURRENT_AND_KEY = 256 ;
const integer FilesystemIterator::SKIP_DOTS = 4096 ;
const integer FilesystemIterator::UNIX_PATHS = 8192 ;
/* Methods */
public addEmptyDir ( string $dirname ) : void
public addFile ( string $file [, string $localname ] ) : void
public addFromString ( string $localname , string $contents ) : void
final public static apiVersion ( void ) : string
public buildFromDirectory ( string $base_dir [, string $regex ] ) : array
public buildFromIterator ( Iterator $iter [, string $base_directory ] ) : array
final public static canCompress ([ int $type = 0 ] ) : bool
final public static canWrite ( void ) : bool
public compress ( int $compression [, string $extension ] ) : object
public compressAllFilesBZIP2 ( void ) : bool
public compressAllFilesGZ ( void ) : bool
public compressFiles ( int $compression ) : void
public __construct ( string $fname [, int $flags [, string $alias ]] )
public convertToData ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] ) : PharData
public convertToExecutable ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] ) : Phar
public copy ( string $oldfile , string $newfile ) : bool
public count ( void ) : int
final public static createDefaultStub ([ string $indexfile [, string $webindexfile ]] ) : string
public decompress ([ string $extension ] ) : object
public decompressFiles ( void ) : bool
public delMetadata ( void ) : bool
public delete ( string $entry ) : bool
public extractTo ( string $pathto [, string|array $files [, bool $overwrite = FALSE ]] ) : bool
public getAlias ( void ) : string
public getMetadata ( void ) : mixed
public getModified ( void ) : bool
public getPath ( void ) : string
public getSignature ( void ) : array
public getStub ( void ) : string
final public static getSupportedCompression ( void ) : array
final public static getSupportedSignatures ( void ) : array
public getVersion ( void ) : string
public hasMetadata ( void ) : bool
final public static interceptFileFuncs ( void ) : void
public isBuffering ( void ) : bool
public isCompressed ( void ) : mixed
public isFileFormat ( int $format ) : bool
final public static isValidPharFilename ( string $filename [, bool $executable = TRUE ] ) : bool
public isWritable ( void ) : bool
final public static loadPhar ( string $filename [, string $alias ] ) : bool
final public static mapPhar ([ string $alias [, int $dataoffset = 0 ]] ) : bool
final public static mount ( string $pharpath , string $externalpath ) : void
final public static mungServer ( array $munglist ) : void
public offsetExists ( string $offset ) : bool
public offsetGet ( string $offset ) : int
public offsetSet ( string $offset , string $value ) : void
public offsetUnset ( string $offset ) : bool
final public static running ([ bool $retphar = TRUE ] ) : string
public setAlias ( string $alias ) : bool
public setDefaultStub ([ string $index [, string $webindex ]] ) : bool
public setMetadata ( mixed $metadata ) : void
public setSignatureAlgorithm ( int $sigtype [, string $privatekey ] ) : void
public setStub ( string $stub [, int $len = -1 ] ) : bool
public startBuffering ( void ) : void
public stopBuffering ( void ) : void
public uncompressAllFiles ( void ) : bool
final public static unlinkArchive ( string $archive ) : bool
final public static webPhar ([ string $alias [, string $index = "index.php" [, string $f404 [, array $mimetypes [, callable $rewrites ]]]]] ) : void
}

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::compressAllFilesBZIP2 — Compresses all files in the current Phar archive using Bzip2 compression
  • Phar::compressAllFilesGZ — Compresses all files in the current Phar archive using Gzip 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::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::uncompressAllFiles — Uncompresses all files in the current Phar archive
  • Phar::unlinkArchive — Completely remove a phar archive from disk and from memory
  • Phar::webPhar — mapPhar for web-based phars. front controller for web applications


Add an empty directory to the phar archive

  • « Phar
  • Phar::addFile »
  • PHP Manual
  • Phar
  • Add an empty directory to the phar archive

Phar::addEmptyDir

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

Phar::addEmptyDir — Add an empty directory to the phar archive

Description

public Phar::addEmptyDir ( string $dirname ) : 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

dirname

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


Add a file from the filesystem to the phar archive

  • « Phar::addEmptyDir
  • Phar::addFromString »
  • PHP Manual
  • Phar
  • Add a file from the filesystem to the phar archive

Phar::addFile

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

Phar::addFile — Add a file from the filesystem to the phar archive

Description

public Phar::addFile ( string $file [, 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.

With this method, any file or URL can be added to the phar archive. If the optional second parameter localname is specified, the file will be stored in the archive with that name, otherwise the file parameter is used as the path to store within the archive. URLs must have a localname or an exception is thrown. This method is similar to ZipArchive::addFile().

Parameters

file

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.

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

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


Add a file from a string to the phar archive

  • « Phar::addFile
  • Phar::apiVersion »
  • PHP Manual
  • Phar
  • Add a file from a string to the phar archive

Phar::addFromString

(PHP 5 >= 5.3.0, PHP 7, 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
}
?>

See Also

  • Phar::offsetSet() - Set the contents of an internal file to those of an external file
  • PharData::addFromString() - Add a file from the filesystem 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


Returns the api version

  • « Phar::addFromString
  • Phar::buildFromDirectory »
  • PHP Manual
  • Phar
  • Returns the api version

Phar::apiVersion

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.0.0)

Phar::apiVersion — Returns the api version

Description

final public static Phar::apiVersion ( void ) : 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


Construct a phar archive from the files within a directory

  • « Phar::apiVersion
  • Phar::buildFromIterator »
  • PHP Manual
  • Phar
  • Construct a phar archive from the files within a directory

Phar::buildFromDirectory

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

Phar::buildFromDirectory — Construct a phar archive from the files within a directory

Description

public Phar::buildFromDirectory ( string $base_dir [, string $regex ] ) : 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

base_dir

The full or relative path to the directory that contains all files to add to the archive.

regex

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.

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


Construct a phar archive from an iterator

  • « Phar::buildFromDirectory
  • Phar::canCompress »
  • PHP Manual
  • Phar
  • Construct a phar archive from an iterator

Phar::buildFromIterator

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

Phar::buildFromIterator — Construct a phar archive from an iterator

Description

public Phar::buildFromIterator ( Iterator $iter [, string $base_directory ] ) : 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

iter

Any iterator that either associatively maps phar file to location or returns SplFileInfo objects

base_directory

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.

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'));
?>

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 base_directory parameter, or a PharException if there were errors saving the phar archive.

See Also

  • Phar::buildFromDirectory() - Construct a phar archive from the files within a directory


Returns whether phar extension supports compression using either zlib or bzip2

  • « Phar::buildFromIterator
  • Phar::canWrite »
  • PHP Manual
  • Phar
  • Returns whether phar extension supports compression using either zlib or bzip2

Phar::canCompress

(PHP 5 >= 5.3.0, PHP 7, 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 $type = 0 ] ) : bool

This should be used to test whether compression is possible prior to loading a phar archive containing compressed files.

Parameters

type

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


Returns whether phar extension supports writing and creating phars

  • « Phar::canCompress
  • Phar::compress »
  • PHP Manual
  • Phar
  • Returns whether phar extension supports writing and creating phars

Phar::canWrite

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.0.0)

Phar::canWrite — Returns whether phar extension supports writing and creating phars

Description

final public static Phar::canWrite ( void ) : 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


Compresses the entire Phar archive using Gzip or Bzip2 compression

  • « Phar::canWrite
  • Phar::compressAllFilesBZIP2 »
  • PHP Manual
  • Phar
  • Compresses the entire Phar archive using Gzip or Bzip2 compression

Phar::compress

(PHP 5 >= 5.3.0, PHP 7, 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 ] ) : object

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.

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.

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


Compresses all files in the current Phar archive using Bzip2 compression

  • « Phar::compress
  • Phar::compressAllFilesGZ »
  • PHP Manual
  • Phar
  • Compresses all files in the current Phar archive using Bzip2 compression

Phar::compressAllFilesBZIP2

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.0.0)

Phar::compressAllFilesBZIP2 — Compresses all files in the current Phar archive using Bzip2 compression

Description

public Phar::compressAllFilesBZIP2 ( void ) : bool

Note:

This
method has been removed from the phar extension as of version 2.0.0.  Alternative
implementations are available using Phar::compress(),
Phar::decompress(), Phar::compressFiles() and
Phar::decompressFiles().

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

This method compresses all files in the Phar archive using bzip2 compression. The bzip2 extension must be enabled to take advantage of this feature. In addition, if any files are already compressed using gzip compression, the zlib extension must be enabled in order to decompress the files prior to re-compressing with bzip2 compression. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws BadMethodCallException if the phar.readonly INI variable is on, the bzip2 extension is not available, or if any files are compressed using gzip compression and the zlib extension is not enabled.

Examples

Example #1 A Phar::compressAllFilesBZIP2() example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressedBZIP2());
    var_dump($file->isCompressedGZ());
}
$p->compressAllFilesBZIP2();
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressedBZIP2());
    var_dump($file->isCompressedGZ());
}
?>

The above example will output:

string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)
string(10) "myfile.txt"
bool(true)
bool(true)
bool(false)
string(11) "myfile2.txt"
bool(true)
bool(true)
bool(false)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressedBZIP2() - Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::isCompressedGZ() - Returns whether the entry is compressed using gz
  • PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry within the phar using Bzip2 compression
  • PharFileInfo::setUncompressed() - Uncompresses the current Phar entry within the phar, if it is compressed
  • PharFileInfo::setCompressedGZ() - Compresses the current Phar entry within the phar using gz 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::compressAllFilesGZ() - Compresses all files in the current Phar archive using Gzip compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::uncompressAllFiles() - Uncompresses all files in the current Phar archive


Compresses all files in the current Phar archive using Gzip compression

  • « Phar::compressAllFilesBZIP2
  • Phar::compressFiles »
  • PHP Manual
  • Phar
  • Compresses all files in the current Phar archive using Gzip compression

Phar::compressAllFilesGZ

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.0.0)

Phar::compressAllFilesGZ — Compresses all files in the current Phar archive using Gzip compression

Description

public Phar::compressAllFilesGZ ( void ) : bool

Note:

This
method has been removed from the phar extension as of version 2.0.0.  Alternative
implementations are available using Phar::compress(),
Phar::decompress(), Phar::compressFiles() and
Phar::decompressFiles().

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

For tar-based phar archives, this method compresses the entire archive using gzip compression. The resulting file can be processed with the gunzip command, or accessed directly and transparently with the Phar extension.

For Zip-based and phar-based phar archives, this method compresses all files in the Phar archive using gzip compression. The zlib extension must be enabled to take advantage of this feature. In addition, if any files are already compressed using bzip2 compression, the bzip2 extension must be enabled in order to decompress the files prior to re-compressing with gzip compression. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

Return Values

Returns TRUE on success or FALSE on failure.

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::compressAllFilesGZ() example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressedBZIP2());
    var_dump($file->isCompressedGZ());
}
$p->compressAllFilesGZ();
foreach ($p as $file) {
    var_dump($file->getFileName());
    var_dump($file->isCompressed());
    var_dump($file->isCompressedBZIP2());
    var_dump($file->isCompressedGZ());
}
?>

The above example will output:

string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)
string(10) "myfile.txt"
bool(true)
bool(false)
bool(true)
string(11) "myfile2.txt"
bool(true)
bool(false)
bool(true)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressedBZIP2() - Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::isCompressedGZ() - Returns whether the entry is compressed using gz
  • PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry within the phar using Bzip2 compression
  • PharFileInfo::setUncompressed() - Uncompresses the current Phar entry within the phar, if it is compressed
  • PharFileInfo::setCompressedGZ() - Compresses the current Phar entry within the phar using gz 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::compressAllFilesBZIP2() - Compresses all files in the current Phar archive using Bzip2 compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::uncompressAllFiles() - Uncompresses all files in the current Phar archive


Compresses all files in the current Phar archive

  • « Phar::compressAllFilesGZ
  • Phar::__construct »
  • PHP Manual
  • Phar
  • Compresses all files in the current Phar archive

Phar::compressFiles

(PHP 5 >= 5.3.0, PHP 7, 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


Construct a Phar archive object

  • « Phar::compressFiles
  • Phar::convertToData »
  • PHP Manual
  • Phar
  • Construct a Phar archive object

Phar::__construct

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.0.0)

Phar::__construct — Construct a Phar archive object

Description

public Phar::__construct ( string $fname [, int $flags [, string $alias ]] )

Parameters

fname

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');
?>


Convert a phar archive to a non-executable tar or zip file

  • « Phar::__construct
  • Phar::convertToExecutable »
  • PHP Manual
  • Phar
  • Convert a phar archive to a non-executable tar or zip file

Phar::convertToData

(PHP 5 >= 5.3.0, PHP 7, 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 = 9021976 [, int $compression = 9021976 [, string $extension ]]] ) : 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 and throws an exception 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.

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


Convert a phar archive to another executable phar archive file format

  • « Phar::convertToData
  • Phar::copy »
  • PHP Manual
  • Phar
  • Convert a phar archive to another executable phar archive file format

Phar::convertToExecutable

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

Phar::convertToExecutable — Convert a phar archive to another executable phar archive file format

Description

public Phar::convertToExecutable ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] ) : 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 and throws an exception 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.

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


Copy a file internal to the phar archive to another new file within the phar

  • « Phar::convertToExecutable
  • Phar::count »
  • PHP Manual
  • Phar
  • Copy a file internal to the phar archive to another new file within the phar

Phar::copy

(PHP 5 >= 5.3.0, PHP 7, 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 $oldfile , string $newfile ) : 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.

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

oldfile

newfile

Return Values

returns TRUE on success, but it is safer to encase method call in a try/catch block and assume success if no exception is thrown.

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 "hi"
} catch (Exception $e) {
    // handle error
}

// the stream wrapper equivalent of the above code.
// E_WARNINGS are triggered on error rather than exceptions.
copy('phar://myphar.phar/a', 'phar//myphar.phar/c');
echo file_get_contents('phar://myphar.phar/c'); // outputs "hi"
?>


Returns the number of entries (files) in the Phar archive

  • « Phar::copy
  • Phar::createDefaultStub »
  • PHP Manual
  • Phar
  • Returns the number of entries (files) in the Phar archive

Phar::count

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.0.0)

Phar::count — Returns the number of entries (files) in the Phar archive

Description

public Phar::count ( void ) : int

Parameters

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


Create a phar-file format specific stub

  • « Phar::count
  • Phar::decompress »
  • PHP Manual
  • Phar
  • Create a phar-file format specific stub

Phar::createDefaultStub

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

Phar::createDefaultStub — Create a phar-file format specific stub

Description

final public static Phar::createDefaultStub ([ string $indexfile [, string $webindexfile ]] ) : 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.

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.

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


Decompresses the entire Phar archive

  • « Phar::createDefaultStub
  • Phar::decompressFiles »
  • PHP Manual
  • Phar
  • Decompresses the entire Phar archive

Phar::decompress

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

Phar::decompress — Decompresses the entire Phar archive

Description

public Phar::decompress ([ string $extension ] ) : object

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.

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.

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


Decompresses all files in the current Phar archive

  • « Phar::decompress
  • Phar::delMetadata »
  • PHP Manual
  • Phar
  • Decompresses all files in the current Phar archive

Phar::decompressFiles

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

Phar::decompressFiles — Decompresses all files in the current Phar archive

Description

public Phar::decompressFiles ( void ) : 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.

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.

Return Values

Returns TRUE on success or FALSE on failure.

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


Deletes the global metadata of the phar

  • « Phar::decompressFiles
  • Phar::delete »
  • PHP Manual
  • Phar
  • Deletes the global metadata of the phar

Phar::delMetadata

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.2.0)

Phar::delMetadata — Deletes the global metadata of the phar

Description

public Phar::delMetadata ( void ) : 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.

Deletes the global metadata of the phar

Parameters

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


Delete a file within a phar archive

  • « Phar::delMetadata
  • Phar::extractTo »
  • PHP Manual
  • Phar
  • Delete a file within a phar archive

Phar::delete

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

Phar::delete — Delete a file within a phar archive

Description

public Phar::delete ( string $entry ) : 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.

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

entry

Path within an archive to the file to delete.

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


Extract the contents of a phar archive to a directory

  • « Phar::delete
  • Phar::getAlias »
  • PHP Manual
  • Phar
  • Extract the contents of a phar archive to a directory

Phar::extractTo

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

Phar::extractTo — Extract the contents of a phar archive to a directory

Description

public Phar::extractTo ( string $pathto [, string|array $files [, 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

pathto

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

See Also

  • PharData::extractTo() - Extract the contents of a tar/zip archive to a directory


Get the alias for Phar

  • « Phar::extractTo
  • Phar::getMetadata »
  • PHP Manual
  • Phar
  • Get the alias for Phar

Phar::getAlias

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.2.1)

Phar::getAlias — Get the alias for Phar

Description

public Phar::getAlias ( void ) : 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.


Returns phar archive meta-data

  • « Phar::getAlias
  • Phar::getModified »
  • PHP Manual
  • Phar
  • Returns phar archive meta-data

Phar::getMetadata

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.0.0)

Phar::getMetadata — Returns phar archive meta-data

Description

public Phar::getMetadata ( void ) : mixed

Retrieve archive meta-data. Meta-data can be any PHP variable that can be serialized.

Parameters

No parameters.

Return Values

any PHP variable that can be serialized and is stored as meta-data for the Phar archive, or NULL if no meta-data is stored.

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


Return whether phar was modified

  • « Phar::getMetadata
  • Phar::getPath »
  • PHP Manual
  • Phar
  • Return whether phar was modified

Phar::getModified

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.0.0)

Phar::getModified — Return whether phar was modified

Description

public Phar::getModified ( void ) : 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.


Get the real path to the Phar archive on disk

  • « Phar::getModified
  • Phar::getSignature »
  • PHP Manual
  • Phar
  • Get the real path to the Phar archive on disk

Phar::getPath

(PHP 5 >= 5.3.0, PHP 7)

Phar::getPath — Get the real path to the Phar archive on disk

Description

public Phar::getPath ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive

  • « Phar::getPath
  • Phar::getStub »
  • PHP Manual
  • Phar
  • Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive

Phar::getSignature

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.0.0)

Phar::getSignature — Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive

Description

public Phar::getSignature ( void ) : array

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.


Return the PHP loader or bootstrap stub of a Phar archive

  • « Phar::getSignature
  • Phar::getSupportedCompression »
  • PHP Manual
  • Phar
  • Return the PHP loader or bootstrap stub of a Phar archive

Phar::getStub

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.0.0)

Phar::getStub — Return the PHP loader or bootstrap stub of a Phar archive

Description

public Phar::getStub ( void ) : 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

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


Return array of supported compression algorithms

  • « Phar::getStub
  • Phar::getSupportedSignatures »
  • PHP Manual
  • Phar
  • Return array of supported compression algorithms

Phar::getSupportedCompression

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.2.0)

Phar::getSupportedCompression — Return array of supported compression algorithms

Description

final public static Phar::getSupportedCompression ( void ) : 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


Return array of supported signature types

  • « Phar::getSupportedCompression
  • Phar::getVersion »
  • PHP Manual
  • Phar
  • Return array of supported signature types

Phar::getSupportedSignatures

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.1.0)

Phar::getSupportedSignatures — Return array of supported signature types

Description

final public static Phar::getSupportedSignatures ( void ) : 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


Return version info of Phar archive

  • « Phar::getSupportedSignatures
  • Phar::hasMetadata »
  • PHP Manual
  • Phar
  • Return version info of Phar archive

Phar::getVersion

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.0.0)

Phar::getVersion — Return version info of Phar archive

Description

public Phar::getVersion ( void ) : 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


Returns whether phar has global meta-data

  • « Phar::getVersion
  • Phar::interceptFileFuncs »
  • PHP Manual
  • Phar
  • Returns whether phar has global meta-data

Phar::hasMetadata

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.2.0)

Phar::hasMetadata — Returns whether phar has global meta-data

Description

public Phar::hasMetadata ( void ) : 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


Instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions

  • « Phar::hasMetadata
  • Phar::isBuffering »
  • PHP Manual
  • Phar
  • Instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions

Phar::interceptFileFuncs

(PHP 5 >= 5.3.0, PHP 7, 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 ) : 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.


Used to determine whether Phar write operations are being buffered, or are flushing directly to disk

  • « Phar::interceptFileFuncs
  • Phar::isCompressed »
  • PHP Manual
  • Phar
  • Used to determine whether Phar write operations are being buffered, or are flushing directly to disk

Phar::isBuffering

(PHP 5 >= 5.3.0, PHP 7, 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 ( void ) : 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.

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


Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)

  • « Phar::isBuffering
  • Phar::isFileFormat »
  • PHP Manual
  • Phar
  • Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)

Phar::isCompressed

(PHP 5 >= 5.3.0, PHP 7, 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 ( void ) : mixed

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


Returns true if the phar archive is based on the tar/phar/zip file format depending on the parameter

  • « Phar::isCompressed
  • Phar::isValidPharFilename »
  • PHP Manual
  • Phar
  • Returns true if the phar archive is based on the tar/phar/zip file format depending on the parameter

Phar::isFileFormat

(PHP 5 >= 5.3.0, PHP 7, 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


Returns whether the given filename is a valid phar filename

  • « Phar::isFileFormat
  • Phar::isWritable »
  • PHP Manual
  • Phar
  • Returns whether the given filename is a valid phar filename

Phar::isValidPharFilename

(PHP 5 >= 5.3.0, PHP 7, 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.


Returns true if the phar archive can be modified

  • « Phar::isValidPharFilename
  • Phar::loadPhar »
  • PHP Manual
  • Phar
  • Returns true if the phar archive can be modified

Phar::isWritable

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

Phar::isWritable — Returns true if the phar archive can be modified

Description

public Phar::isWritable ( void ) : 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


Loads any phar archive with an alias

  • « Phar::isWritable
  • Phar::mapPhar »
  • PHP Manual
  • Phar
  • Loads any phar archive with an alias

Phar::loadPhar

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.0.0)

Phar::loadPhar — Loads any phar archive with an alias

Description

final public static Phar::loadPhar ( string $filename [, string $alias ] ) : 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


Reads the currently executed file (a phar) and registers its manifest

  • « Phar::loadPhar
  • Phar::mount »
  • PHP Manual
  • Phar
  • Reads the currently executed file (a phar) and registers its manifest

Phar::mapPhar

(PHP 5 >= 5.3.0, PHP 7, 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 [, int $dataoffset = 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.

dataoffset

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


Mount an external path or file to a virtual location within the phar archive

  • « Phar::mapPhar
  • Phar::mungServer »
  • PHP Manual
  • Phar
  • Mount an external path or file to a virtual location within the phar archive

Phar::mount

(PHP 5 >= 5.3.0, PHP 7, 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';
?>


Defines a list of up to 4 $_SERVER variables that should be modified for execution

  • « Phar::mount
  • Phar::offsetExists »
  • PHP Manual
  • Phar
  • Defines a list of up to 4 $_SERVER variables that should be modified for execution

Phar::mungServer

(PHP 5 >= 5.3.0, PHP 7, 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 $munglist ) : 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

munglist

an array containing as string indices any of REQUEST_URI, PHP_SELF, SCRIPT_NAME and SCRIPT_FILENAME. Other values trigger an exception, and Phar::mungServer() is case-sensitive.

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() - mapPhar for web-based phars. front controller for web applications
  • Phar::setStub() - Used to set the PHP loader or bootstrap stub of a Phar archive


Determines whether a file exists in the phar

  • « Phar::mungServer
  • Phar::offsetGet »
  • PHP Manual
  • Phar
  • Determines whether a file exists in the phar

Phar::offsetExists

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.0.0)

Phar::offsetExists — Determines whether a file exists in the phar

Description

public Phar::offsetExists ( string $offset ) : 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

offset

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


Gets a PharFileInfo object for a specific file

  • « Phar::offsetExists
  • Phar::offsetSet »
  • PHP Manual
  • Phar
  • Gets a PharFileInfo object for a specific file

Phar::offsetGet

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.0.0)

Phar::offsetGet — Gets a PharFileInfo object for a specific file

Description

public Phar::offsetGet ( string $offset ) : int

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

offset

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


Set the contents of an internal file to those of an external file

  • « Phar::offsetGet
  • Phar::offsetUnset »
  • PHP Manual
  • Phar
  • Set the contents of an internal file to those of an external file

Phar::offsetSet

(PHP 5 >= 5.3.0, PHP 7, 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 $offset , 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

offset

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

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


Remove a file from a phar

  • « Phar::offsetSet
  • Phar::running »
  • PHP Manual
  • Phar
  • Remove a file from a phar

Phar::offsetUnset

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.0.0)

Phar::offsetUnset — Remove a file from a phar

Description

public Phar::offsetUnset ( string $offset ) : 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 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

offset

The filename (relative path) to modify in a Phar.

Return Values

Returns TRUE on success or FALSE on failure.

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


Returns the full path on disk or full phar URL to the currently executing Phar archive

  • « Phar::offsetUnset
  • Phar::setAlias »
  • PHP Manual
  • Phar
  • Returns the full path on disk or full phar URL to the currently executing Phar archive

Phar::running

(PHP 5 >= 5.3.0, PHP 7, 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 $retphar = 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

retphar

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


Set the alias for the Phar archive

  • « Phar::running
  • Phar::setDefaultStub »
  • PHP Manual
  • Phar
  • Set the alias for the Phar archive

Phar::setAlias

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.2.1)

Phar::setAlias — Set the alias for the Phar archive

Description

public Phar::setAlias ( string $alias ) : 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.

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

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.

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


Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader

  • « Phar::setAlias
  • Phar::setMetadata »
  • PHP Manual
  • Phar
  • Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader

Phar::setDefaultStub

(PHP 5 >= 5.3.0, PHP 7, 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 [, string $webindex ]] ) : 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 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

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.

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


Sets phar archive meta-data

  • « Phar::setDefaultStub
  • Phar::setSignatureAlgorithm »
  • PHP Manual
  • Phar
  • Sets phar archive meta-data

Phar::setMetadata

(PHP 5 >= 5.3.0, PHP 7, 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


Set the signature algorithm for a phar and apply it

  • « Phar::setMetadata
  • Phar::setStub »
  • PHP Manual
  • Phar
  • Set the signature algorithm for a phar and apply it

Phar::setSignatureAlgorithm

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.1.0)

Phar::setSignatureAlgorithm — Set the signature algorithm for a phar and apply it

Description

public Phar::setSignatureAlgorithm ( int $sigtype [, string $privatekey ] ) : 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

sigtype

    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.

See Also

  • Phar::getSupportedSignatures() - Return array of supported signature types
  • Phar::getSignature() - Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive


Used to set the PHP loader or bootstrap stub of a Phar archive

  • « Phar::setSignatureAlgorithm
  • Phar::startBuffering »
  • PHP Manual
  • Phar
  • Used to set the PHP loader or bootstrap stub of a Phar archive

Phar::setStub

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.0.0)

Phar::setStub — Used to set the PHP loader or bootstrap stub of a Phar archive

Description

public Phar::setStub ( string $stub [, int $len = -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.

len

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.

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(); ?>"

Changelog

Version | Description
5.4.0 | Added len parameter.

See Also

  • Phar::getStub() - Return the PHP loader or bootstrap stub of a Phar archive
  • Phar::createDefaultStub() - Create a phar-file format specific stub


Start buffering Phar write operations, do not modify the Phar object on disk

  • « Phar::setStub
  • Phar::stopBuffering »
  • PHP Manual
  • Phar
  • Start buffering Phar write operations, do not modify the Phar object on disk

Phar::startBuffering

(PHP 5 >= 5.3.0, PHP 7, 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 ) : 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.

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


Stop buffering write requests to the Phar archive, and save changes to disk

  • « Phar::startBuffering
  • Phar::uncompressAllFiles »
  • PHP Manual
  • Phar
  • Stop buffering write requests to the Phar archive, and save changes to disk

Phar::stopBuffering

(PHP 5 >= 5.3.0, PHP 7, 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 ) : 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.

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


Uncompresses all files in the current Phar archive

  • « Phar::stopBuffering
  • Phar::unlinkArchive »
  • PHP Manual
  • Phar
  • Uncompresses all files in the current Phar archive

Phar::uncompressAllFiles

(PECL phar < 2.0.0)

Phar::uncompressAllFiles — Uncompresses all files in the current Phar archive

Description

public Phar::uncompressAllFiles ( void ) : bool

Note:

This
method has been removed from the phar extension as of version 2.0.0.  Alternative
implementations are available using Phar::compress(),
Phar::decompress(), Phar::compressFiles() and
Phar::decompressFiles().

Note:

This method requires the php.ini setting phar.readonly to be set to 0 in order to work for Phar objects. Otherwise, a PharException will be thrown.

This method decompresses all files in the Phar archive. If any files are already compressed using gzip compression, the zlib extension must be enabled in order to decompress the files, and any files compressed using bzip2 compression require the bzip2 extension to decompress the files. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws BadMethodCallException if the phar.readonly INI variable is on, the bzip2 extension is not enabled and any files are compressed using bzip2 compression, or if any files are compressed using gzip compression and the zlib extension is not enabled.

Examples

Example #1 A Phar::uncompressAllFiles() example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $p['myfile2.txt'] = 'hi';
    $p->compressAllFilesGZ();
    foreach ($p as $file) {
        var_dump($file->getFileName());
        var_dump($file->isCompressed());
        var_dump($file->isCompressedBZIP2());
        var_dump($file->isCompressedGZ());
    }
    $p->uncompressAllFiles();
    foreach ($p as $file) {
        var_dump($file->getFileName());
        var_dump($file->isCompressed());
        var_dump($file->isCompressedBZIP2());
        var_dump($file->isCompressedGZ());
    }
} catch (Exception $e) {
    echo 'Write operations failed on my.phar: ', $e;
}
?>

The above example will output:

string(10) "myfile.txt"
bool(true)
bool(false)
bool(true)
string(11) "myfile2.txt"
bool(true)
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::isCompressedBZIP2() - Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::isCompressedGZ() - Returns whether the entry is compressed using gz
  • PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry within the phar using Bzip2 compression
  • PharFileInfo::setUncompressed() - Uncompresses the current Phar entry within the phar, if it is compressed
  • PharFileInfo::setCompressedGZ() - Compresses the current Phar entry within the phar using gz 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::compressAllFilesBZIP2() - Compresses all files in the current Phar archive using Bzip2 compression
  • Phar::compressAllFilesGZ() - Compresses all files in the current Phar archive using Gzip compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms


Completely remove a phar archive from disk and from memory

  • « Phar::uncompressAllFiles
  • Phar::webPhar »
  • PHP Manual
  • Phar
  • Completely remove a phar archive from disk and from memory

Phar::unlinkArchive

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

Phar::unlinkArchive — Completely remove a phar archive from disk and from memory

Description

final public static Phar::unlinkArchive ( string $archive ) : bool

Removes a phar archive from disk and memory.

Parameters

archive

The path on disk to the phar archive.

Return Values

Returns TRUE on success or FALSE on failure.

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


mapPhar for web-based phars. front controller for web applications

  • « Phar::unlinkArchive
  • PharData »
  • PHP Manual
  • Phar
  • mapPhar for web-based phars. front controller for web applications

Phar::webPhar

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

Phar::webPhar — mapPhar for web-based phars. front controller for web applications

Description

final public static Phar::webPhar ([ string $alias [, string $index = "index.php" [, string $f404 [, array $mimetypes [, callable $rewrites ]]]]] ) : void

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. In essence, it simulates a web server, routing requests to the correct file, echoing the correct headers and parsing PHP files as needed. This powerful method is part of what makes it easy to convert an existing PHP application into a phar archive. 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.

f404

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',
);
?>

rewrites

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 rewrites, then UnexpectedValueException is thrown.

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


The PharData class

(PHP 5 >= 5.3.0, PHP 7, 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

PharData extends RecursiveDirectoryIterator {
/* Inherited constants */
const integer FilesystemIterator::CURRENT_AS_PATHNAME = 32 ;
const integer FilesystemIterator::CURRENT_AS_FILEINFO = 0 ;
const integer FilesystemIterator::CURRENT_AS_SELF = 16 ;
const integer FilesystemIterator::CURRENT_MODE_MASK = 240 ;
const integer FilesystemIterator::KEY_AS_PATHNAME = 0 ;
const integer FilesystemIterator::KEY_AS_FILENAME = 256 ;
const integer FilesystemIterator::FOLLOW_SYMLINKS = 512 ;
const integer FilesystemIterator::KEY_MODE_MASK = 3840 ;
const integer FilesystemIterator::NEW_CURRENT_AND_KEY = 256 ;
const integer FilesystemIterator::SKIP_DOTS = 4096 ;
const integer FilesystemIterator::UNIX_PATHS = 8192 ;
/* Methods */
addEmptyDir ( string $dirname ) : void
public Phar::addFile ( string $file [, string $localname ] ) : void
addFromString ( string $localname , string $contents ) : void
public Phar::buildFromDirectory ( string $base_dir [, string $regex ] ) : array
buildFromIterator ( Iterator $iter [, string $base_directory ] ) : array
compress ( int $compression [, string $extension ] ) : object
compressFiles ( int $compression ) : void
__construct ( string $fname [, int $flags [, string $alias [, int $format = Phar::TAR ]]] )
convertToData ([ int $format [, int $compression [, string $extension ]]] ) : PharData
convertToExecutable ([ int $format [, int $compression [, string $extension ]]] ) : Phar
copy ( string $oldfile , string $newfile ) : bool
decompress ([ string $extension ] ) : object
decompressFiles ( void ) : bool
delMetadata ( void ) : bool
delete ( string $entry ) : bool
extractTo ( string $pathto [, string|array $files [, bool $overwrite = FALSE ]] ) : bool
isWritable ( void ) : bool
offsetSet ( string $offset , string $value ) : void
offsetUnset ( string $offset ) : bool
setAlias ( string $alias ) : bool
setDefaultStub ([ string $index [, string $webindex ]] ) : bool
public Phar::setMetadata ( mixed $metadata ) : void
public Phar::setSignatureAlgorithm ( int $sigtype ) : void
setStub ( string $stub [, int $len = -1 ] ) : bool
/* Inherited methods */
public Phar::addEmptyDir ( string $dirname ) : void
public Phar::addFile ( string $file [, string $localname ] ) : void
public Phar::addFromString ( string $localname , string $contents ) : void
final public static Phar::apiVersion ( void ) : string
public Phar::buildFromDirectory ( string $base_dir [, string $regex ] ) : array
public Phar::buildFromIterator ( Iterator $iter [, string $base_directory ] ) : array
final public static Phar::canCompress ([ int $type = 0 ] ) : bool
final public static Phar::canWrite ( void ) : bool
public Phar::compress ( int $compression [, string $extension ] ) : object
public Phar::compressAllFilesBZIP2 ( void ) : bool
public Phar::compressAllFilesGZ ( void ) : bool
public Phar::compressFiles ( int $compression ) : void
public Phar::__construct ( string $fname [, int $flags [, string $alias ]] )
public Phar::convertToData ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] ) : PharData
public Phar::convertToExecutable ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] ) : Phar
public Phar::copy ( string $oldfile , string $newfile ) : bool
public Phar::count ( void ) : int
final public static Phar::createDefaultStub ([ string $indexfile [, string $webindexfile ]] ) : string
public Phar::decompress ([ string $extension ] ) : object
public Phar::decompressFiles ( void ) : bool
public Phar::delMetadata ( void ) : bool
public Phar::delete ( string $entry ) : bool
public Phar::extractTo ( string $pathto [, string|array $files [, bool $overwrite = FALSE ]] ) : bool
public Phar::getAlias ( void ) : string
public Phar::getMetadata ( void ) : mixed
public Phar::getModified ( void ) : bool
public Phar::getPath ( void ) : string
public Phar::getSignature ( void ) : array
public Phar::getStub ( void ) : string
final public static Phar::getSupportedCompression ( void ) : array
final public static Phar::getSupportedSignatures ( void ) : array
public Phar::getVersion ( void ) : string
public Phar::hasMetadata ( void ) : bool
final public static Phar::interceptFileFuncs ( void ) : void
public Phar::isBuffering ( void ) : bool
public Phar::isCompressed ( void ) : mixed
public Phar::isFileFormat ( int $format ) : bool
final public static Phar::isValidPharFilename ( string $filename [, bool $executable = TRUE ] ) : bool
public Phar::isWritable ( void ) : bool
final public static Phar::loadPhar ( string $filename [, string $alias ] ) : bool
final public static Phar::mapPhar ([ string $alias [, int $dataoffset = 0 ]] ) : bool
final public static Phar::mount ( string $pharpath , string $externalpath ) : void
final public static Phar::mungServer ( array $munglist ) : void
public Phar::offsetExists ( string $offset ) : bool
public Phar::offsetGet ( string $offset ) : int
public Phar::offsetSet ( string $offset , string $value ) : void
public Phar::offsetUnset ( string $offset ) : bool
final public static Phar::running ([ bool $retphar = TRUE ] ) : string
public Phar::setAlias ( string $alias ) : bool
public Phar::setDefaultStub ([ string $index [, string $webindex ]] ) : bool
public Phar::setMetadata ( mixed $metadata ) : void
public Phar::setSignatureAlgorithm ( int $sigtype [, string $privatekey ] ) : void
public Phar::setStub ( string $stub [, int $len = -1 ] ) : bool
public Phar::startBuffering ( void ) : void
public Phar::stopBuffering ( void ) : void
public Phar::uncompressAllFiles ( void ) : bool
final public static Phar::unlinkArchive ( string $archive ) : bool
final public static Phar::webPhar ([ string $alias [, string $index = "index.php" [, string $f404 [, array $mimetypes [, callable $rewrites ]]]]] ) : void
}

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 the filesystem 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 phar archive to another new file within the phar
  • 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::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)
  • Phar::setMetadata — Sets phar archive meta-data
  • Phar::setSignatureAlgorithm — Set the signature algorithm for a phar and apply it
  • PharData::setStub — Dummy function (Phar::setStub is not valid for PharData)


Add an empty directory to the tar/zip archive

  • « PharData
  • PharData::addFile »
  • PHP Manual
  • PharData
  • Add an empty directory to the tar/zip archive

PharData::addEmptyDir

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

PharData::addEmptyDir — Add an empty directory to the tar/zip archive

Description

PharData::addEmptyDir ( string $dirname ) : void

With this method, an empty directory is created with path dirname. This method is similar to ZipArchive::addEmptyDir().

Parameters

dirname

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 the filesystem to the tar/zip archive


Add a file from the filesystem to the tar/zip archive

  • « PharData::addEmptyDir
  • PharData::addFromString »
  • PHP Manual
  • PharData
  • Add a file from the filesystem to the tar/zip archive

PharData::addFile

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

PharData::addFile — Add a file from the filesystem to the tar/zip archive

Description

public Phar::addFile ( string $file [, string $localname ] ) : 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

file

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.

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

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 the filesystem to the tar/zip archive
  • PharData::addEmptyDir() - Add an empty directory to the tar/zip archive


Add a file from the filesystem to the tar/zip archive

  • « PharData::addFile
  • PharData::buildFromDirectory »
  • PHP Manual
  • PharData
  • Add a file from the filesystem to the tar/zip archive

PharData::addFromString

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

PharData::addFromString — Add a file from the filesystem to the tar/zip archive

Description

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

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


Construct a tar/zip archive from the files within a directory

  • « PharData::addFromString
  • PharData::buildFromIterator »
  • PHP Manual
  • PharData
  • Construct a tar/zip archive from the files within a directory

PharData::buildFromDirectory

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

PharData::buildFromDirectory — Construct a tar/zip archive from the files within a directory

Description

public Phar::buildFromDirectory ( string $base_dir [, string $regex ] ) : 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

base_dir

The full or relative path to the directory that contains all files to add to the archive.

regex

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.

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


Construct a tar or zip archive from an iterator

  • « PharData::buildFromDirectory
  • PharData::compress »
  • PHP Manual
  • PharData
  • Construct a tar or zip archive from an iterator

PharData::buildFromIterator

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

PharData::buildFromIterator — Construct a tar or zip archive from an iterator

Description

PharData::buildFromIterator ( Iterator $iter [, string $base_directory ] ) : 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.

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'),
     )));
?>

Parameters

iter

Any iterator that either associatively maps tar/zip file to location or returns SplFileInfo objects

base_directory

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 base_directory parameter, or a PharException if there were errors saving the phar archive.

See Also

  • Phar::buildFromIterator() - Construct a phar archive from an iterator


Compresses the entire tar/zip archive using Gzip or Bzip2 compression

  • « PharData::buildFromIterator
  • PharData::compressFiles »
  • PHP Manual
  • PharData
  • Compresses the entire tar/zip archive using Gzip or Bzip2 compression

PharData::compress

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

PharData::compress — Compresses the entire tar/zip archive using Gzip or Bzip2 compression

Description

PharData::compress ( int $compression [, string $extension ] ) : object

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.

Errors/Exceptions

Throws BadMethodCallException if the zlib extension is not available, or the bzip2 extension is not enabled.

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


Compresses all files in the current tar/zip archive

  • « PharData::compress
  • PharData::__construct »
  • PHP Manual
  • PharData
  • Compresses all files in the current tar/zip archive

PharData::compressFiles

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

PharData::compressFiles — Compresses all files in the current tar/zip archive

Description

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


Construct a non-executable tar or zip archive object

  • « PharData::compressFiles
  • PharData::convertToData »
  • PHP Manual
  • PharData
  • Construct a non-executable tar or zip archive object

PharData::__construct

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

PharData::__construct — Construct a non-executable tar or zip archive object

Description

PharData::__construct ( string $fname [, int $flags [, string $alias [, int $format = Phar::TAR ]]] )

Parameters

fname

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');
?>


Convert a phar archive to a non-executable tar or zip file

  • « PharData::__construct
  • PharData::convertToExecutable »
  • PHP Manual
  • PharData
  • Convert a phar archive to a non-executable tar or zip file

PharData::convertToData

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

PharData::convertToData — Convert a phar archive to a non-executable tar or zip file

Description

PharData::convertToData ([ int $format [, int $compression [, string $extension ]]] ) : 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 and throws an exception 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.

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


Convert a non-executable tar/zip archive to an executable phar archive

  • « PharData::convertToData
  • PharData::copy »
  • PHP Manual
  • PharData
  • Convert a non-executable tar/zip archive to an executable phar archive

PharData::convertToExecutable

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

PharData::convertToExecutable — Convert a non-executable tar/zip archive to an executable phar archive

Description

PharData::convertToExecutable ([ int $format [, int $compression [, string $extension ]]] ) : 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 and throws an exception 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.

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


Copy a file internal to the phar archive to another new file within the phar

  • « PharData::convertToExecutable
  • PharData::decompress »
  • PHP Manual
  • PharData
  • Copy a file internal to the phar archive to another new file within the phar

PharData::copy

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

PharData::copy — Copy a file internal to the phar archive to another new file within the phar

Description

PharData::copy ( string $oldfile , string $newfile ) : bool

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

oldfile

newfile

Return Values

returns TRUE on success, but it is safer to encase method call in a try/catch block and assume success if no exception is thrown.

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_WARNINGS 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"
?>


Decompresses the entire Phar archive

  • « PharData::copy
  • PharData::decompressFiles »
  • PHP Manual
  • PharData
  • Decompresses the entire Phar archive

PharData::decompress

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

PharData::decompress — Decompresses the entire Phar archive

Description

PharData::decompress ([ string $extension ] ) : object

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.

Errors/Exceptions

Throws BadMethodCallException if the zlib extension is not available, or the bzip2 extension is not enabled.

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


Decompresses all files in the current zip archive

  • « PharData::decompress
  • PharData::delMetadata »
  • PHP Manual
  • PharData
  • Decompresses all files in the current zip archive

PharData::decompressFiles

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

PharData::decompressFiles — Decompresses all files in the current zip archive

Description

PharData::decompressFiles ( void ) : 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.

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.

Return Values

Returns TRUE on success or FALSE on failure.

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


Deletes the global metadata of a zip archive

  • « PharData::decompressFiles
  • PharData::delete »
  • PHP Manual
  • PharData
  • Deletes the global metadata of a zip archive

PharData::delMetadata

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

PharData::delMetadata — Deletes the global metadata of a zip archive

Description

PharData::delMetadata ( void ) : 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.

Deletes the global metadata of the zip archive

Parameters

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


Delete a file within a tar/zip archive

  • « PharData::delMetadata
  • PharData::extractTo »
  • PHP Manual
  • PharData
  • Delete a file within a tar/zip archive

PharData::delete

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

PharData::delete — Delete a file within a tar/zip archive

Description

PharData::delete ( string $entry ) : bool

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

entry

Path within an archive to the file to delete.

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


Extract the contents of a tar/zip archive to a directory

  • « PharData::delete
  • PharData::isWritable »
  • PHP Manual
  • PharData
  • Extract the contents of a tar/zip archive to a directory

PharData::extractTo

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

PharData::extractTo — Extract the contents of a tar/zip archive to a directory

Description

PharData::extractTo ( string $pathto [, string|array $files [, 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

pathto

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

See Also

  • Phar::extractTo() - Extract the contents of a phar archive to a directory


Returns true if the tar/zip archive can be modified

  • « PharData::extractTo
  • PharData::offsetSet »
  • PHP Manual
  • PharData
  • Returns true if the tar/zip archive can be modified

PharData::isWritable

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

PharData::isWritable — Returns true if the tar/zip archive can be modified

Description

PharData::isWritable ( void ) : 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


Set the contents of a file within the tar/zip to those of an external file or string

  • « PharData::isWritable
  • PharData::offsetUnset »
  • PHP Manual
  • PharData
  • Set the contents of a file within the tar/zip to those of an external file or string

PharData::offsetSet

(PHP 5 >= 5.3.0, PHP 7, 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

PharData::offsetSet ( string $offset , 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

offset

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

See Also

  • Phar::offsetSet() - Set the contents of an internal file to those of an external file


Remove a file from a tar/zip archive

  • « PharData::offsetSet
  • PharData::setAlias »
  • PHP Manual
  • PharData
  • Remove a file from a tar/zip archive

PharData::offsetUnset

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

PharData::offsetUnset — Remove a file from a tar/zip archive

Description

PharData::offsetUnset ( string $offset ) : bool

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

offset

The filename (relative path) to modify in the tar/zip archive.

Return Values

Returns TRUE on success or FALSE on failure.

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


Dummy function (Phar::setAlias is not valid for PharData)

  • « PharData::offsetUnset
  • PharData::setDefaultStub »
  • PHP Manual
  • PharData
  • Dummy function (Phar::setAlias is not valid for PharData)

PharData::setAlias

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

PharData::setAlias — Dummy function (Phar::setAlias is not valid for PharData)

Description

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


Dummy function (Phar::setDefaultStub is not valid for PharData)

  • « PharData::setAlias
  • Phar::setMetadata »
  • PHP Manual
  • PharData
  • Dummy function (Phar::setDefaultStub is not valid for PharData)

PharData::setDefaultStub

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

PharData::setDefaultStub — Dummy function (Phar::setDefaultStub is not valid for PharData)

Description

PharData::setDefaultStub ([ string $index [, string $webindex ]] ) : 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

See Also

  • Phar::setDefaultStub() - Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader


Sets phar archive meta-data

  • « PharData::setDefaultStub
  • Phar::setSignatureAlgorithm »
  • PHP Manual
  • PharData
  • Sets phar archive meta-data

Phar::setMetadata

(PHP 5 >= 5.3.0, PHP 7, 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


Set the signature algorithm for a phar and apply it

  • « Phar::setMetadata
  • PharData::setStub »
  • PHP Manual
  • PharData
  • Set the signature algorithm for a phar and apply it

Phar::setSignatureAlgorithm

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.1.0)

Phar::setSignatureAlgorithm — Set the signature algorithm for a phar and apply it

Description

public Phar::setSignatureAlgorithm ( int $sigtype ) : 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::PGP (pgp not yet supported and falls back to SHA-1).

Parameters

sigtype

    One of Phar::MD5,
Phar::SHA1, Phar::SHA256,
Phar::SHA512, or Phar::PGP

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.

See Also

  • Phar::getSupportedSignatures() - Return array of supported signature types
  • Phar::getSignature() - Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive


Dummy function (Phar::setStub is not valid for PharData)

  • « Phar::setSignatureAlgorithm
  • PharFileInfo »
  • PHP Manual
  • PharData
  • Dummy function (Phar::setStub is not valid for PharData)

PharData::setStub

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

PharData::setStub — Dummy function (Phar::setStub is not valid for PharData)

Description

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

Changelog

Version | Description
5.4.0 | Added len parameter.

See Also

  • Phar::setStub() - Used to set the PHP loader or bootstrap stub of a Phar archive


The PharFileInfo class

(PHP 5 >= 5.3.0, PHP 7, 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

PharFileInfo extends SplFileInfo {
/* Methods */
public chmod ( int $permissions ) : void
public compress ( int $compression ) : bool
public __construct ( string $entry )
public decompress ( void ) : bool
public delMetadata ( void ) : bool
public getCRC32 ( void ) : int
public getCompressedSize ( void ) : int
public getContent ( void ) : string
public getMetadata ( void ) : mixed
public getPharFlags ( void ) : int
public hasMetadata ( void ) : bool
public isCRCChecked ( void ) : bool
public isCompressed ([ int $compression_type = 9021976 ] ) : bool
public isCompressedBZIP2 ( void ) : bool
public isCompressedGZ ( void ) : bool
public setCompressedBZIP2 ( void ) : bool
public setCompressedGZ ( void ) : bool
public setMetadata ( mixed $metadata ) : void
public setUncompressed ( void ) : bool
}

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::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::isCompressedBZIP2 — Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressedGZ — Returns whether the entry is compressed using gz
  • PharFileInfo::setCompressedBZIP2 — Compresses the current Phar entry within the phar using Bzip2 compression
  • PharFileInfo::setCompressedGZ — Compresses the current Phar entry within the phar using gz compression
  • PharFileInfo::setMetadata — Sets file-specific meta-data saved with a file
  • PharFileInfo::setUncompressed — Uncompresses the current Phar entry within the phar, if it is compressed


Sets file-specific permission bits

  • « PharFileInfo
  • PharFileInfo::compress »
  • PHP Manual
  • PharFileInfo
  • Sets file-specific permission bits

PharFileInfo::chmod

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.0.0)

PharFileInfo::chmod — Sets file-specific permission bits

Description

public PharFileInfo::chmod ( int $permissions ) : 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

permissions

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)


Compresses the current Phar entry with either zlib or bzip2 compression

  • « PharFileInfo::chmod
  • PharFileInfo::__construct »
  • PHP Manual
  • PharFileInfo
  • Compresses the current Phar entry with either zlib or bzip2 compression

PharFileInfo::compress

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

PharFileInfo::compress — Compresses the current Phar entry with either zlib or bzip2 compression

Description

public PharFileInfo::compress ( int $compression ) : bool

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.

Return Values

Returns TRUE on success or FALSE on failure.

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


Construct a Phar entry object

  • « PharFileInfo::compress
  • PharFileInfo::decompress »
  • PHP Manual
  • PharFileInfo
  • Construct a Phar entry object

PharFileInfo::__construct

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.0.0)

PharFileInfo::__construct — Construct a Phar entry object

Description

public PharFileInfo::__construct ( string $entry )

This should not be called directly. Instead, a PharFileInfo object is initialized by calling Phar::offsetGet() through array access.

Parameters

entry

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


Decompresses the current Phar entry within the phar

  • « PharFileInfo::__construct
  • PharFileInfo::delMetadata »
  • PHP Manual
  • PharFileInfo
  • Decompresses the current Phar entry within the phar

PharFileInfo::decompress

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 2.0.0)

PharFileInfo::decompress — Decompresses the current Phar entry within the phar

Description

public PharFileInfo::decompress ( void ) : bool

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.

Return Values

Returns TRUE on success or FALSE on failure.

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


Deletes the metadata of the entry

  • « PharFileInfo::decompress
  • PharFileInfo::getCRC32 »
  • PHP Manual
  • PharFileInfo
  • Deletes the metadata of the entry

PharFileInfo::delMetadata

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.2.0)

PharFileInfo::delMetadata — Deletes the metadata of the entry

Description

public PharFileInfo::delMetadata ( void ) : bool

Deletes the metadata of the entry, if any.

Parameters

No parameters.

Return Values

Returns TRUE if successful, FALSE if the entry had no metadata. 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


Returns CRC32 code or throws an exception if CRC has not been verified

  • « PharFileInfo::delMetadata
  • PharFileInfo::getCompressedSize »
  • PHP Manual
  • PharFileInfo
  • Returns CRC32 code or throws an exception if CRC has not been verified

PharFileInfo::getCRC32

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.0.0)

PharFileInfo::getCRC32 — Returns CRC32 code or throws an exception if CRC has not been verified

Description

public PharFileInfo::getCRC32 ( void ) : int

This returns the crc32() checksum of the file within the Phar archive.

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


Returns the actual size of the file (with compression) inside the Phar archive

  • « PharFileInfo::getCRC32
  • PharFileInfo::getContent »
  • PHP Manual
  • PharFileInfo
  • Returns the actual size of the file (with compression) inside the Phar archive

PharFileInfo::getCompressedSize

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.0.0)

PharFileInfo::getCompressedSize — Returns the actual size of the file (with compression) inside the Phar archive

Description

public PharFileInfo::getCompressedSize ( void ) : 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()

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


Get the complete file contents of the entry

  • « PharFileInfo::getCompressedSize
  • PharFileInfo::getMetadata »
  • PHP Manual
  • PharFileInfo
  • Get the complete file contents of the entry

PharFileInfo::getContent

(PHP 5 >= 5.3.0, PHP 7)

PharFileInfo::getContent — Get the complete file contents of the entry

Description

public PharFileInfo::getContent ( void ) : string

This function behaves like file_get_contents() but for Phar.

Parameters

This function has no parameters.

Return Values

Returns the file contents.


Returns file-specific meta-data saved with a file

  • « PharFileInfo::getContent
  • PharFileInfo::getPharFlags »
  • PHP Manual
  • PharFileInfo
  • Returns file-specific meta-data saved with a file

PharFileInfo::getMetadata

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.0.0)

PharFileInfo::getMetadata — Returns file-specific meta-data saved with a file

Description

public PharFileInfo::getMetadata ( void ) : 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.

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


Returns the Phar file entry flags

  • « PharFileInfo::getMetadata
  • PharFileInfo::hasMetadata »
  • PHP Manual
  • PharFileInfo
  • Returns the Phar file entry flags

PharFileInfo::getPharFlags

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.0.0)

PharFileInfo::getPharFlags — Returns the Phar file entry flags

Description

public PharFileInfo::getPharFlags ( void ) : int

This returns the flags set in the manifest for a Phar. This will always return 0 in the current implementation.

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)


Returns the metadata of the entry

  • « PharFileInfo::getPharFlags
  • PharFileInfo::isCRCChecked »
  • PHP Manual
  • PharFileInfo
  • Returns the metadata of the entry

PharFileInfo::hasMetadata

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.2.0)

PharFileInfo::hasMetadata — Returns the metadata of the entry

Description

public PharFileInfo::hasMetadata ( void ) : 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


Returns whether file entry has had its CRC verified

  • « PharFileInfo::hasMetadata
  • PharFileInfo::isCompressed »
  • PHP Manual
  • PharFileInfo
  • Returns whether file entry has had its CRC verified

PharFileInfo::isCRCChecked

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.0.0)

PharFileInfo::isCRCChecked — Returns whether file entry has had its CRC verified

Description

public PharFileInfo::isCRCChecked ( void ) : bool

This returns whether a file within a Phar archive has had its CRC verified.

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)


Returns whether the entry is compressed

  • « PharFileInfo::isCRCChecked
  • PharFileInfo::isCompressedBZIP2 »
  • PHP Manual
  • PharFileInfo
  • Returns whether the entry is compressed

PharFileInfo::isCompressed

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.0.0)

PharFileInfo::isCompressed — Returns whether the entry is compressed

Description

public PharFileInfo::isCompressed ([ int $compression_type = 9021976 ] ) : bool

This returns whether a file is compressed within a Phar archive with either Gzip or Bzip2 compression.

Parameters

compression_type

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.

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


Returns whether the entry is compressed using bzip2

  • « PharFileInfo::isCompressed
  • PharFileInfo::isCompressedGZ »
  • PHP Manual
  • PharFileInfo
  • Returns whether the entry is compressed using bzip2

PharFileInfo::isCompressedBZIP2

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.0.0)

PharFileInfo::isCompressedBZIP2 — Returns whether the entry is compressed using bzip2

Description

public PharFileInfo::isCompressedBZIP2 ( void ) : bool

Note:

This method has been removed from the phar extension as of version 2.0.0. Alternative implementations are available using PharFileInfo::isCompressed(), PharFileInfo::decompress(), and PharFileInfo::compress().

This returns whether a file is compressed within a Phar archive with Bzip2 compression.

Return Values

TRUE if the file is compressed within the Phar archive using Bzip2, FALSE if not.

Examples

Example #1 A PharFileInfo::isCompressedBZIP2() example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $p['myfile2.txt'] = 'hi';
    $p['myfile3.txt'] = 'hi';
    $p['myfile2.txt']->setCompressedGZ();
    $p['myfile3.txt']->setCompressedBZIP2();
    $file = $p['myfile.txt'];
    $file2 = $p['myfile2.txt'];
    $file3 = $p['myfile3.txt'];
    var_dump($file->isCompressedBZIP2());
    var_dump($file2->isCompressedBZIP2());
    var_dump($file3->isCompressedBZIP2());
} catch (Exception $e) {
    echo 'Create/modify on phar my.phar failed: ', $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::isCompressedGZ() - Returns whether the entry is compressed using gz
  • PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry within the phar using Bzip2 compression
  • PharFileInfo::setUncompressed() - Uncompresses the current Phar entry within the phar, if it is compressed
  • PharFileInfo::setCompressedGZ() - Compresses the current Phar entry within the phar using gz 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::compressAllFilesBZIP2() - Compresses all files in the current Phar archive using Bzip2 compression
  • Phar::compressAllFilesGZ() - Compresses all files in the current Phar archive using Gzip compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::uncompressAllFiles() - Uncompresses all files in the current Phar archive


Returns whether the entry is compressed using gz

  • « PharFileInfo::isCompressedBZIP2
  • PharFileInfo::setCompressedBZIP2 »
  • PHP Manual
  • PharFileInfo
  • Returns whether the entry is compressed using gz

PharFileInfo::isCompressedGZ

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.0.0)

PharFileInfo::isCompressedGZ — Returns whether the entry is compressed using gz

Description

public PharFileInfo::isCompressedGZ ( void ) : bool

Note:

This method has been removed from the phar extension as of version 2.0.0. Alternative implementations are available using PharFileInfo::isCompressed(), PharFileInfo::decompress(), and PharFileInfo::compress().

This returns whether a file is compressed within a Phar archive with Gzip compression.

Return Values

TRUE if the file is compressed within the Phar archive using Gzip, FALSE if not.

Examples

Example #1 A PharFileInfo::isCompressedGZ() example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $p['myfile2.txt'] = 'hi';
    $p['myfile3.txt'] = 'hi';
    $p['myfile2.txt']->setCompressedGZ();
    $p['myfile3.txt']->setCompressedBZIP2();
    $file = $p['myfile.txt'];
    $file2 = $p['myfile2.txt'];
    $file3 = $p['myfile3.txt'];
    var_dump($file->isCompressedGZ());
    var_dump($file2->isCompressedGZ());
    var_dump($file3->isCompressedGZ());
} catch (Exception $e) {
    echo 'Create/modify on phar my.phar failed: ', $e;
}
?>

The above example will output:

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

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressedBZIP2() - Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry within the phar using Bzip2 compression
  • PharFileInfo::setUncompressed() - Uncompresses the current Phar entry within the phar, if it is compressed
  • PharFileInfo::setCompressedGZ() - Compresses the current Phar entry within the phar using gz 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::compressAllFilesBZIP2() - Compresses all files in the current Phar archive using Bzip2 compression
  • Phar::compressAllFilesGZ() - Compresses all files in the current Phar archive using Gzip compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::uncompressAllFiles() - Uncompresses all files in the current Phar archive


Compresses the current Phar entry within the phar using Bzip2 compression

  • « PharFileInfo::isCompressedGZ
  • PharFileInfo::setCompressedGZ »
  • PHP Manual
  • PharFileInfo
  • Compresses the current Phar entry within the phar using Bzip2 compression

PharFileInfo::setCompressedBZIP2

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.0.0)

PharFileInfo::setCompressedBZIP2 — Compresses the current Phar entry within the phar using Bzip2 compression

Description

public PharFileInfo::setCompressedBZIP2 ( void ) : bool

Note:

This method has been removed from the phar extension as of version 2.0.0. Alternative implementations are available using PharFileInfo::isCompressed(), PharFileInfo::decompress(), and PharFileInfo::compress().

This method compresses the file inside the Phar archive using bzip2 compression. The bzip2 extension must be enabled to take advantage of this feature. In addition, if the file is already compressed using gzip compression, the zlib 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.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws BadMethodCallException if the phar.readonly INI variable is on, or if the bzip2 extension is not available.

Examples

Example #1 A PharFileInfo::setCompressedBZIP2() example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    var_dump($file->isCompressedBZIP2());
    $p['myfile.txt']->setCompressedBZIP2();
    var_dump($file->isCompressedBZIP2());
} 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::isCompressedBZIP2() - Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::isCompressedGZ() - Returns whether the entry is compressed using gz
  • PharFileInfo::setUncompressed() - Uncompresses the current Phar entry within the phar, if it is compressed
  • PharFileInfo::setCompressedGZ() - Compresses the current Phar entry within the phar using gz 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::compressAllFilesBZIP2() - Compresses all files in the current Phar archive using Bzip2 compression
  • Phar::compressAllFilesGZ() - Compresses all files in the current Phar archive using Gzip compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::uncompressAllFiles() - Uncompresses all files in the current Phar archive


Compresses the current Phar entry within the phar using gz compression

  • « PharFileInfo::setCompressedBZIP2
  • PharFileInfo::setMetadata »
  • PHP Manual
  • PharFileInfo
  • Compresses the current Phar entry within the phar using gz compression

PharFileInfo::setCompressedGZ

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.0.0)

PharFileInfo::setCompressedGZ — Compresses the current Phar entry within the phar using gz compression

Description

public PharFileInfo::setCompressedGZ ( void ) : bool

Note:

This method has been removed from the phar extension as of version 2.0.0. Alternative implementations are available using PharFileInfo::isCompressed(), PharFileInfo::decompress(), and PharFileInfo::compress().

This method compresses the file inside the Phar archive using gzip compression. The zlib extension must be enabled to take advantage of this feature. In addition, if the file is already compressed using bzip2 compression, the bzip2 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.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws BadMethodCallException if the phar.readonly INI variable is on, or if the zlib extension is not available.

Examples

Example #1 A PharFileInfo::setCompressedGZ() example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    var_dump($file->isCompressedGZ());
    $p['myfile.txt']->setCompressedGZ();
    var_dump($file->isCompressedGZ());
} 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::isCompressedBZIP2() - Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::isCompressedGZ() - Returns whether the entry is compressed using gz
  • PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry within the phar using Bzip2 compression
  • PharFileInfo::setUncompressed() - Uncompresses the current Phar entry within the phar, if it is compressed
  • 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::compressAllFilesBZIP2() - Compresses all files in the current Phar archive using Bzip2 compression
  • Phar::compressAllFilesGZ() - Compresses all files in the current Phar archive using Gzip compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::uncompressAllFiles() - Uncompresses all files in the current Phar archive


Sets file-specific meta-data saved with a file

  • « PharFileInfo::setCompressedGZ
  • PharFileInfo::setUncompressed »
  • PHP Manual
  • PharFileInfo
  • Sets file-specific meta-data saved with a file

PharFileInfo::setMetadata

(PHP 5 >= 5.3.0, PHP 7, 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


Uncompresses the current Phar entry within the phar, if it is compressed

  • « PharFileInfo::setMetadata
  • PharException »
  • PHP Manual
  • PharFileInfo
  • Uncompresses the current Phar entry within the phar, if it is compressed

PharFileInfo::setUncompressed

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.0.0)

PharFileInfo::setUncompressed — Uncompresses the current Phar entry within the phar, if it is compressed

Description

public PharFileInfo::setUncompressed ( void ) : bool

Note:

This method has been removed from the phar extension as of version 2.0.0. Alternative implementations are available using PharFileInfo::isCompressed(), PharFileInfo::decompress(), and PharFileInfo::compress().

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.

Return Values

Returns TRUE on success or FALSE on failure.

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::setUncompressed() example

<?php
try {
    $p = new Phar('/path/to/my.phar', 0, 'my.phar');
    $p['myfile.txt'] = 'hi';
    $file = $p['myfile.txt'];
    $file->setCompressedGZ();
    var_dump($file->isCompressed());
    $p['myfile.txt']->setUncompressed();
    var_dump($file->isCompressed());
} catch (Exception $e) {
    echo 'Create/modify failed for my.phar: ', $e;
}
?>

The above example will output:

bool(true)
bool(false)

See Also

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressedBZIP2() - Returns whether the entry is compressed using bzip2
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::isCompressedGZ() - Returns whether the entry is compressed using gz
  • PharFileInfo::setCompressedBZIP2() - Compresses the current Phar entry within the phar using Bzip2 compression
  • PharFileInfo::setCompressedGZ() - Compresses the current Phar entry within the phar using gz 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::compressAllFilesBZIP2() - Compresses all files in the current Phar archive using Bzip2 compression
  • Phar::compressAllFilesGZ() - Compresses all files in the current Phar archive using Gzip compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::uncompressAllFiles() - Uncompresses all files in the current Phar archive


The PharException class

(PHP 5 >= 5.3.0, PHP 7, PECL phar >= 1.0.0)

Introduction

The PharException class provides a phar-specific exception class for try/catch blocks.

Class synopsis

PharException extends Exception {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


Rar Archiving

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • 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


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


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. A DLL for this PECL extension is currently unavailable. See also the building on Windows section.


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 (integer)
Use RarEntry::HOST_MSDOS instead.
RAR_HOST_OS2 (integer)
Use RarEntry::HOST_OS2 instead.
RAR_HOST_WIN32 (integer)
Use RarEntry::HOST_WIN32 instead.
RAR_HOST_UNIX (integer)
Use RarEntry::HOST_UNIX instead.
RAR_HOST_BEOS (integer)
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

Table of Contents

  • rar_wrapper_cache_stats — Cache hits and misses for the URL wrapper


Cache hits and misses for the URL wrapper

  • « Rar Functions
  • RarArchive »
  • PHP Manual
  • Rar Functions
  • Cache hits and misses for the URL wrapper

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 ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


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 RarArchive implements Traversable {
/* Methods */
public close ( void ) : bool
public getComment ( void ) : string
public getEntries ( void ) : array
public getEntry ( string $entryname ) : RarEntry
public isBroken ( void ) : bool
public isSolid ( void ) : bool
public static open ( string $filename [, string $password = NULL [, callable $volume_callback = NULL ]] ) : RarArchive
public setAllowBroken ( bool $allow_broken ) : bool
public __toString ( void ) : string
}

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


Close RAR archive and free all resources

  • « RarArchive
  • RarArchive::getComment »
  • PHP Manual
  • RarArchive
  • Close RAR archive and free all resources

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 ( void ) : 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
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";
?>


Get comment text from the RAR archive

  • « RarArchive::close
  • RarArchive::getEntries »
  • PHP Manual
  • RarArchive
  • Get comment text from the RAR archive

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 ( void ) : 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);
?>


Get full list of entries from the RAR archive

  • « RarArchive::getComment
  • RarArchive::getEntry »
  • PHP Manual
  • RarArchive
  • Get full list of entries from the RAR archive

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 ( void ) : array

Procedural style:

rar_list ( RarArchive $rarfile ) : array

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


Get entry object from the RAR archive

  • « RarArchive::getEntries
  • RarArchive::isBroken »
  • PHP Manual
  • RarArchive
  • Get entry object from the RAR archive

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

Procedural style:

rar_entry_get ( RarArchive $rarfile , string $entryname ) : RarEntry

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


Test whether an archive is broken (incomplete)

  • « RarArchive::getEntry
  • RarArchive::isSolid »
  • PHP Manual
  • RarArchive
  • Test whether an archive is broken (incomplete)

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 ( void ) : 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


Check whether the RAR archive is solid

  • « RarArchive::isBroken
  • RarArchive::open »
  • PHP Manual
  • RarArchive
  • Check whether the RAR archive is solid

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 ( void ) : 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";
?>


Open RAR archive

  • « RarArchive::isSolid
  • RarArchive::setAllowBroken »
  • PHP Manual
  • RarArchive
  • Open RAR archive

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

Procedural style:

rar_open ( string $filename [, string $password = NULL [, callable $volume_callback = NULL ]] ) : RarArchive

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


Whether opening broken archives is allowed

  • « RarArchive::open
  • RarArchive::__toString »
  • PHP Manual
  • RarArchive
  • Whether opening broken archives is allowed

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)


Get text representation

  • « RarArchive::setAllowBroken
  • RarEntry »
  • PHP Manual
  • RarArchive
  • Get text representation

RarArchive::__toString

(PECL rar >= 2.0.0)

RarArchive::__toString — Get text representation

Description

public RarArchive::__toString ( void ) : 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)


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 RarEntry {
/* Constants */
const integer HOST_MSDOS = 0 ;
const integer HOST_OS2 = 1 ;
const integer HOST_WIN32 = 2 ;
const integer HOST_UNIX = 3 ;
const integer HOST_MACOS = 4 ;
const integer HOST_BEOS = 5 ;
const integer ATTRIBUTE_WIN_READONLY = 1 ;
const integer ATTRIBUTE_WIN_HIDDEN = 2 ;
const integer ATTRIBUTE_WIN_SYSTEM = 4 ;
const integer ATTRIBUTE_WIN_DIRECTORY = 16 ;
const integer ATTRIBUTE_WIN_ARCHIVE = 32 ;
const integer ATTRIBUTE_WIN_DEVICE = 64 ;
const integer ATTRIBUTE_WIN_NORMAL = 128 ;
const integer ATTRIBUTE_WIN_TEMPORARY = 256 ;
const integer ATTRIBUTE_WIN_SPARSE_FILE = 512 ;
const integer ATTRIBUTE_WIN_REPARSE_POINT = 1024 ;
const integer ATTRIBUTE_WIN_COMPRESSED = 2048 ;
const integer ATTRIBUTE_WIN_OFFLINE = 4096 ;
const integer ATTRIBUTE_WIN_NOT_CONTENT_INDEXED = 8192 ;
const integer ATTRIBUTE_WIN_ENCRYPTED = 16384 ;
const integer ATTRIBUTE_WIN_VIRTUAL = 65536 ;
const integer ATTRIBUTE_UNIX_WORLD_EXECUTE = 1 ;
const integer ATTRIBUTE_UNIX_WORLD_WRITE = 2 ;
const integer ATTRIBUTE_UNIX_WORLD_READ = 4 ;
const integer ATTRIBUTE_UNIX_GROUP_EXECUTE = 8 ;
const integer ATTRIBUTE_UNIX_GROUP_WRITE = 16 ;
const integer ATTRIBUTE_UNIX_GROUP_READ = 32 ;
const integer ATTRIBUTE_UNIX_OWNER_EXECUTE = 64 ;
const integer ATTRIBUTE_UNIX_OWNER_WRITE = 128 ;
const integer ATTRIBUTE_UNIX_OWNER_READ = 256 ;
const integer ATTRIBUTE_UNIX_STICKY = 512 ;
const integer ATTRIBUTE_UNIX_SETGID = 1024 ;
const integer ATTRIBUTE_UNIX_SETUID = 2048 ;
const integer ATTRIBUTE_UNIX_FINAL_QUARTET = 61440 ;
const integer ATTRIBUTE_UNIX_FIFO = 4096 ;
const integer ATTRIBUTE_UNIX_CHAR_DEV = 8192 ;
const integer ATTRIBUTE_UNIX_DIRECTORY = 16384 ;
const integer ATTRIBUTE_UNIX_BLOCK_DEV = 24576 ;
const integer ATTRIBUTE_UNIX_REGULAR_FILE = 32768 ;
const integer ATTRIBUTE_UNIX_SYM_LINK = 40960 ;
const integer ATTRIBUTE_UNIX_SOCKET = 49152 ;
/* Methods */
public extract ( string $dir [, string $filepath = "" [, string $password = NULL [, bool $extended_data = FALSE ]]] ) : bool
public getAttr ( void ) : int
public getCrc ( void ) : string
public getFileTime ( void ) : string
public getHostOs ( void ) : int
public getMethod ( void ) : int
public getName ( void ) : string
public getPackedSize ( void ) : int
public getStream ([ string $password ] ) : resource
public getUnpackedSize ( void ) : int
public getVersion ( void ) : int
public isDirectory ( void ) : bool
public isEncrypted ( void ) : bool
public __toString ( void ) : 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.

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


Extract entry from the archive

  • « RarEntry
  • RarEntry::getAttr »
  • PHP Manual
  • RarEntry
  • Extract entry from the archive

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
3.0.0 | extended_data was added.
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


Get attributes of the entry

  • « RarEntry::extract
  • RarEntry::getCrc »
  • PHP Manual
  • RarEntry
  • Get attributes of the entry

RarEntry::getAttr

(PECL rar >= 0.1)

RarEntry::getAttr — Get attributes of the entry

Description

public RarEntry::getAttr ( void ) : 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


Get CRC of the entry

  • « RarEntry::getAttr
  • RarEntry::getFileTime »
  • PHP Manual
  • RarEntry
  • Get CRC of the entry

RarEntry::getCrc

(PECL rar >= 0.1)

RarEntry::getCrc — Get CRC of the entry

Description

public RarEntry::getCrc ( void ) : 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
2.0.0 | This method now returns correct values for multiple volume archives.


Get entry last modification time

  • « RarEntry::getCrc
  • RarEntry::getHostOs »
  • PHP Manual
  • RarEntry
  • Get entry last modification time

RarEntry::getFileTime

(PECL rar >= 0.1)

RarEntry::getFileTime — Get entry last modification time

Description

public RarEntry::getFileTime ( void ) : 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.


Get entry host OS

  • « RarEntry::getFileTime
  • RarEntry::getMethod »
  • PHP Manual
  • RarEntry
  • Get entry host OS

RarEntry::getHostOs

(PECL rar >= 0.1)

RarEntry::getHostOs — Get entry host OS

Description

public RarEntry::getHostOs ( void ) : 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


Get pack method of the entry

  • « RarEntry::getHostOs
  • RarEntry::getName »
  • PHP Manual
  • RarEntry
  • Get pack method of the entry

RarEntry::getMethod

(PECL rar >= 0.1)

RarEntry::getMethod — Get pack method of the entry

Description

public RarEntry::getMethod ( void ) : 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();

?>


Get name of the entry

  • « RarEntry::getMethod
  • RarEntry::getPackedSize »
  • PHP Manual
  • RarEntry
  • Get name of the entry

RarEntry::getName

(PECL rar >= 0.1)

RarEntry::getName — Get name of the entry

Description

public RarEntry::getName ( void ) : 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
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"
);

?>


Get packed size of the entry

  • « RarEntry::getName
  • RarEntry::getStream »
  • PHP Manual
  • RarEntry
  • Get packed size of the entry

RarEntry::getPackedSize

(PECL rar >= 0.1)

RarEntry::getPackedSize — Get packed size of the entry

Description

public RarEntry::getPackedSize ( void ) : 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
2.0.0 | This method now returns correct values of packed sizes bigger than 2 GiB on platforms with 64-bit integers 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";

?>


Get file handler for entry

  • « RarEntry::getPackedSize
  • RarEntry::getUnpackedSize »
  • PHP Manual
  • RarEntry
  • Get file handler for entry

RarEntry::getStream

(PECL rar >= 2.0.0)

RarEntry::getStream — Get file handler for entry

Description

public RarEntry::getStream ([ string $password ] ) : resource

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


Get unpacked size of the entry

  • « RarEntry::getStream
  • RarEntry::getVersion »
  • PHP Manual
  • RarEntry
  • Get unpacked size of the entry

RarEntry::getUnpackedSize

(PECL rar >= 0.1)

RarEntry::getUnpackedSize — Get unpacked size of the entry

Description

public RarEntry::getUnpackedSize ( void ) : 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
2.0.0 | This method now returns correct values of unpacked sizes bigger than 2 GiB on platforms with 64-bit integers 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";

?>


Get minimum version of RAR program required to unpack the entry

  • « RarEntry::getUnpackedSize
  • RarEntry::isDirectory »
  • PHP Manual
  • RarEntry
  • Get minimum version of RAR program required to unpack the entry

RarEntry::getVersion

(PECL rar >= 0.1)

RarEntry::getVersion — Get minimum version of RAR program required to unpack the entry

Description

public RarEntry::getVersion ( void ) : 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();

?>


Test whether an entry represents a directory

  • « RarEntry::getVersion
  • RarEntry::isEncrypted »
  • PHP Manual
  • RarEntry
  • Test whether an entry represents a directory

RarEntry::isDirectory

(PECL rar >= 2.0.0)

RarEntry::isDirectory — Test whether an entry represents a directory

Description

public RarEntry::isDirectory ( void ) : 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)));
?>


Test whether an entry is encrypted

  • « RarEntry::isDirectory
  • RarEntry::__toString »
  • PHP Manual
  • RarEntry
  • Test whether an entry is encrypted

RarEntry::isEncrypted

(PECL rar >= 2.0.0)

RarEntry::isEncrypted — Test whether an entry is encrypted

Description

public RarEntry::isEncrypted ( void ) : 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.


Get text representation of entry

  • « RarEntry::isEncrypted
  • RarException »
  • PHP Manual
  • RarEntry
  • Get text representation of entry

RarEntry::__toString

(PECL rar >= 2.0.0)

RarEntry::__toString — Get text representation of entry

Description

public RarEntry::__toString ( void ) : 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.


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 RarException extends Exception {
/* Methods */
public static isUsingExceptions ( void ) : bool
public static setUsingExceptions ( bool $using_exceptions ) : void
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}

Table of Contents

  • RarException::isUsingExceptions — Check whether error handling with exceptions is in use
  • RarException::setUsingExceptions — Activate and deactivate error handling with exceptions


Check whether error handling with exceptions is in use

  • « RarException
  • RarException::setUsingExceptions »
  • PHP Manual
  • RarException
  • Check whether error handling with exceptions is in use

RarException::isUsingExceptions

(PECL rar >= 2.0.0)

RarException::isUsingExceptions — Check whether error handling with exceptions is in use

Description

public static RarException::isUsingExceptions ( void ) : 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


Activate and deactivate error handling with exceptions

  • « RarException::isUsingExceptions
  • Zip »
  • PHP Manual
  • RarException
  • 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).

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


Zip

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • 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::close — Close the active archive (opened or newly created)
    • ZipArchive::count — Counts the number of files in the achive
    • 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::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::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::setArchiveComment — Set the comment 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


Introduction

This extension enables you to transparently read or write ZIP compressed archives and the files inside them.


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

This extension requires » libzip which is bundled with PHP.


Installation

Linux systems

In order to use these functions you must compile PHP with zip support by using the --enable-zip configure option.

As of PHP 5.6.0 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.

As of PHP 7.3.0, building against the bundled libzip is discouraged, but still possible by adding --without-libzip to the configuration.

Windows

As of PHP 5.3 this extension is built-in. Before, Windows users need to enable php_zip.dll inside of php.ini in order to use these functions.

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 three types of constants : Flags (prefixed with FL_), errors (prefixed with ER_) and mode (no prefix).

ZipArchive::CREATE (integer)
Create the archive if it does not exist.
ZipArchive::OVERWRITE (integer)
If archive exists, ignore its current contents. In other words, handle it the same way as an empty archive.
ZipArchive::EXCL (integer)
Error if archive already exists.
ZipArchive::RDONLY (integer)
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 (integer)
Perform additional consistency checks on the archive, and error if they fail.
ZipArchive::FL_NOCASE (integer)
Ignore case on name lookup
ZipArchive::FL_NODIR (integer)
Ignore directory component
ZipArchive::FL_COMPRESSED (integer)
Read compressed data
ZipArchive::FL_UNCHANGED (integer)
Use original data, ignoring changes.
ZipArchive::FL_ENC_GUESS (integer)
Guess string encoding (is default). Available as of PHP 7.0.8.
ZipArchive::FL_ENC_RAW (integer)
Get unmodified string. Available as of PHP 7.0.8.
ZipArchive::FL_ENC_STRICT (integer)
Follow specification strictly. Available as of PHP 7.0.8.
ZipArchive::FL_ENC_UTF_8 (integer)
String is UTF-8 encoded. Available as of PHP 7.0.8.
ZipArchive::FL_ENC_CP437 (integer)
String is CP437 encoded. Available as of PHP 7.0.8.
ZipArchive::CM_DEFAULT (integer)
better of deflate or store.
ZipArchive::CM_STORE (integer)
stored (uncompressed).
ZipArchive::CM_SHRINK (integer)
shrunk
ZipArchive::CM_REDUCE_1 (integer)
reduced with factor 1
ZipArchive::CM_REDUCE_2 (integer)
reduced with factor 2
ZipArchive::CM_REDUCE_3 (integer)
reduced with factor 3
ZipArchive::CM_REDUCE_4 (integer)
reduced with factor 4
ZipArchive::CM_IMPLODE (integer)
imploded
ZipArchive::CM_DEFLATE (integer)
deflated
ZipArchive::CM_DEFLATE64 (integer)
deflate64
ZipArchive::CM_PKWARE_IMPLODE (integer)
PKWARE imploding
ZipArchive::CM_BZIP2 (integer)
BZIP2 algorithm
ZipArchive::CM_LZMA (integer)
LZMA algorithm
ZipArchive::CM_LZMA2 (integer)
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_XZ (integer)
XZ algorithm. Available as of PHP 7.4.3 and PECL zip 1.16.1, respectively, if built against libzip ≥ 1.6.0.
ZipArchive::ER_OK (integer)
No error.
ZipArchive::ER_MULTIDISK (integer)
Multi-disk zip archives not supported.
ZipArchive::ER_RENAME (integer)
Renaming temporary file failed.
ZipArchive::ER_CLOSE (integer)
Closing zip archive failed
ZipArchive::ER_SEEK (integer)
Seek error
ZipArchive::ER_READ (integer)
Read error
ZipArchive::ER_WRITE (integer)
Write error
ZipArchive::ER_CRC (integer)
CRC error
ZipArchive::ER_ZIPCLOSED (integer)
Containing zip archive was closed
ZipArchive::ER_NOENT (integer)
No such file.
ZipArchive::ER_EXISTS (integer)
File already exists
ZipArchive::ER_OPEN (integer)
Can't open file
ZipArchive::ER_TMPOPEN (integer)
Failure to create temporary file.
ZipArchive::ER_ZLIB (integer)
Zlib error
ZipArchive::ER_MEMORY (integer)
Memory allocation failure
ZipArchive::ER_CHANGED (string)
Entry has been changed
ZipArchive::ER_COMPNOTSUPP (integer)
Compression method not supported.
ZipArchive::ER_EOF (integer)
Premature EOF
ZipArchive::ER_INVAL (integer)
Invalid argument
ZipArchive::ER_NOZIP (integer)
Not a zip archive
ZipArchive::ER_INTERNAL (integer)
Internal error
ZipArchive::ER_INCONS (integer)
Zip archive inconsistent
ZipArchive::ER_REMOVE (integer)
Can't remove file
ZipArchive::ER_DELETED (integer)
Entry has been deleted
ZipArchive::ER_ENCRNOTSUPP (integer)
Encryption method not supported. Available as of PHP 7.4.3 and PECL zip 1.16.1, respectively.
ZipArchive::ER_RDONLY (integer)
Read-only archive. Available as of PHP 7.4.3 and PECL zip 1.16.1, respectively.
ZipArchive::ER_NOPASSWD (integer)
No password provided. Available as of PHP 7.4.3 and PECL zip 1.16.1, respectively.
ZipArchive::ER_WRONGPASSWD (integer)
Wrong password provided. Available as of PHP 7.4.3 and PECL zip 1.16.1, respectively.
ZipArchive::ZIP_ER_OPNOTSUPP (integer)
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::ZIP_ER_INUSE (integer)
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::ZIP_ER_TELL (integer)
Tell error. Available as of PHP 7.4.3 and PECL zip 1.16.1, respectively, if built against libzip ≥ 1.0.0.
ZipArchive::ZIP_ER_COMPRESSED_DATA (integer)
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 (integer)
Operation cancelled. Available as of PHP 7.4.3 and PECL zip 1.16.1, respectively, if built against libzip ≥ 1.6.0.
ZipArchive::EM_NONE (integer)
No 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_128 (integer)
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 (integer)
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 (integer)
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::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 (integer)
ZipArchive::OPSYS_AMIGA (integer)
ZipArchive::OPSYS_OPENVMS (integer)
ZipArchive::OPSYS_UNIX (integer)
ZipArchive::OPSYS_VM_CMS (integer)
ZipArchive::OPSYS_ATARI_ST (integer)
ZipArchive::OPSYS_OS_2 (integer)
ZipArchive::OPSYS_MACINTOSH (integer)
ZipArchive::OPSYS_Z_SYSTEM (integer)
ZipArchive::OPSYS_CPM (integer)
ZipArchive::OPSYS_WINDOWS_NTFS (integer)
ZipArchive::OPSYS_MVS (integer)
ZipArchive::OPSYS_VSE (integer)
ZipArchive::OPSYS_ACORN_RISC (integer)
ZipArchive::OPSYS_VFAT (integer)
ZipArchive::OPSYS_ALTERNATE_MVS (integer)
ZipArchive::OPSYS_BEOS (integer)
ZipArchive::OPSYS_TANDEM (integer)
ZipArchive::OPSYS_OS_400 (integer)
ZipArchive::OPSYS_OS_X (integer)
ZipArchive::OPSYS_DEFAULT (integer)
Since PHP 5.6.0, 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, PECL zip >= 1.1.0)

Introduction

A file archive, compressed with Zip.

Class synopsis

ZipArchive implements Countable {
/* Properties */
int $status;
int $statusSys;
int $numFiles;
string $filename;
string $comment;
/* Methods */
addEmptyDir ( string $dirname ) : bool
addFile ( string $filename [, string $localname = NULL [, int $start = 0 [, int $length = 0 ]]] ) : bool
addFromString ( string $localname , string $contents ) : bool
addGlob ( string $pattern [, int $flags = 0 [, array $options = array() ]] ) : bool
addPattern ( string $pattern [, string $path = "." [, array $options = array() ]] ) : bool
close ( void ) : bool
public count ( void ) : int
deleteIndex ( int $index ) : bool
deleteName ( string $name ) : bool
extractTo ( string $destination [, mixed $entries ] ) : bool
getArchiveComment ([ int $flags ] ) : string
getCommentIndex ( int $index [, int $flags ] ) : string
getCommentName ( string $name [, int $flags ] ) : string
GetExternalAttributesIndex ( int $index , int &$opsys , int &$attr [, int $flags ] ) : bool
getExternalAttributesName ( string $name , int &$opsys , int &$attr [, int $flags ] ) : bool
getFromIndex ( int $index [, int $length = 0 [, int $flags ]] ) : string
getFromName ( string $name [, int $length = 0 [, int $flags ]] ) : string
getNameIndex ( int $index [, int $flags ] ) : string
getStatusString ( void ) : string
getStream ( string $name ) : resource
locateName ( string $name [, int $flags ] ) : int
open ( string $filename [, int $flags ] ) : mixed
registerCancelCallback ( callable $callback ) : bool
registerProgressCallback ( float $rate , callable $callback ) : bool
renameIndex ( int $index , string $newname ) : bool
renameName ( string $name , string $newname ) : bool
setArchiveComment ( string $comment ) : bool
setCommentIndex ( int $index , string $comment ) : bool
setCommentName ( string $name , string $comment ) : bool
setCompressionIndex ( int $index , int $comp_method [, int $comp_flags = 0 ] ) : bool
setCompressionName ( string $name , int $comp_method [, int $comp_flags = 0 ] ) : bool
setEncryptionIndex ( int $index , string $method [, string $password ] ) : bool
setEncryptionName ( string $name , int $method [, string $password ] ) : bool
setExternalAttributesIndex ( int $index , int $opsys , int $attr [, int $flags ] ) : bool
setExternalAttributesName ( string $name , int $opsys , int $attr [, int $flags ] ) : bool
setMtimeIndex ( int $index , int $timestamp [, int $flags ] ) : bool
setMtimeName ( string $name , int $timestamp [, int $flags ] ) : bool
public setPassword ( string $password ) : bool
statIndex ( int $index [, int $flags ] ) : array
statName ( string $name [, int $flags ] ) : array
unchangeAll ( void ) : bool
unchangeArchive ( void ) : bool
unchangeIndex ( int $index ) : bool
unchangeName ( string $name ) : bool
}

Properties

status

Status of the Zip Archive

statusSys

System status of the Zip Archive

numFiles

Number of files in archive

filename

File name in the file system

comment

Comment for the archive

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::close — Close the active archive (opened or newly created)
  • ZipArchive::count — Counts the number of files in the achive
  • 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::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::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::setArchiveComment — Set the comment 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


Add a new directory

  • « ZipArchive
  • ZipArchive::addFile »
  • PHP Manual
  • ZipArchive
  • Add a new directory

ZipArchive::addEmptyDir

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.8.0)

ZipArchive::addEmptyDir — Add a new directory

Description

ZipArchive::addEmptyDir ( string $dirname ) : bool

Adds an empty directory in the archive.

Parameters

dirname

The directory to add.

Return Values

Returns TRUE on success or FALSE on failure.

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


Adds a file to a ZIP archive from the given path

  • « ZipArchive::addEmptyDir
  • ZipArchive::addFromString »
  • PHP Manual
  • ZipArchive
  • Adds a file to a ZIP archive from the given path

ZipArchive::addFile

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.1.0)

ZipArchive::addFile — Adds a file to a ZIP archive from the given path

Description

ZipArchive::addFile ( string $filename [, string $localname = NULL [, int $start = 0 [, int $length = 0 ]]] ) : 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

filename

The path to the file to add.

localname

If supplied, this is the local name inside the ZIP archive that will override the filename.

start

This parameter is not used but is required to extend ZipArchive.

length

This parameter is not used but is required to extend ZipArchive.

Return Values

Returns TRUE on success or FALSE on failure.

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.


Add a file to a ZIP archive using its contents

  • « ZipArchive::addFile
  • ZipArchive::addGlob »
  • PHP Manual
  • ZipArchive
  • Add a file to a ZIP archive using its contents

ZipArchive::addFromString

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.1.0)

ZipArchive::addFromString — Add a file to a ZIP archive using its contents

Description

ZipArchive::addFromString ( string $localname , string $contents ) : 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

localname

The name of the entry to create.

contents

The contents to use to create the entry. It is used in a binary safe mode.

Return Values

Returns TRUE on success or FALSE on failure.

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


Add files from a directory by glob pattern

  • « ZipArchive::addFromString
  • ZipArchive::addPattern »
  • PHP Manual
  • ZipArchive
  • Add files from a directory by glob pattern

ZipArchive::addGlob

(PHP 5 >= 5.3.0, PHP 7, PECL zip >= 1.9.0)

ZipArchive::addGlob — Add files from a directory by glob pattern

Description

ZipArchive::addGlob ( string $pattern [, int $flags = 0 [, array $options = array() ]] ) : bool

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.

Return Values

Returns TRUE on success or FALSE on failure.

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


Add files from a directory by PCRE pattern

  • « ZipArchive::addGlob
  • ZipArchive::close »
  • PHP Manual
  • ZipArchive
  • Add files from a directory by PCRE pattern

ZipArchive::addPattern

(PHP 5 >= 5.3.0, PHP 7, PECL zip >= 1.9.0)

ZipArchive::addPattern — Add files from a directory by PCRE pattern

Description

ZipArchive::addPattern ( string $pattern [, string $path = "." [, array $options = array() ]] ) : bool

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

Returns TRUE 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


Close the active archive (opened or newly created)

  • « ZipArchive::addPattern
  • ZipArchive::count »
  • PHP Manual
  • ZipArchive
  • Close the active archive (opened or newly created)

ZipArchive::close

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.1.0)

ZipArchive::close — Close the active archive (opened or newly created)

Description

ZipArchive::close ( void ) : bool

Close opened or created archive and save changes. This method is automatically called at the end of the script.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.


Counts the number of files in the achive

  • « ZipArchive::close
  • ZipArchive::deleteIndex »
  • PHP Manual
  • ZipArchive
  • Counts the number of files in the achive

ZipArchive::count

(PHP 7 >= 7.2.0, PECL zip >= 1.15.0)

ZipArchive::count — Counts the number of files in the achive

Description

public ZipArchive::count ( void ) : int

Parameters

This function has no parameters.

Return Values

Returns the number of files in the archive.


Delete an entry in the archive using its index

  • « ZipArchive::count
  • ZipArchive::deleteName »
  • PHP Manual
  • ZipArchive
  • Delete an entry in the archive using its index

ZipArchive::deleteIndex

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.5.0)

ZipArchive::deleteIndex — Delete an entry in the archive using its index

Description

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


Delete an entry in the archive using its name

  • « ZipArchive::deleteIndex
  • ZipArchive::extractTo »
  • PHP Manual
  • ZipArchive
  • Delete an entry in the archive using its name

ZipArchive::deleteName

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.5.0)

ZipArchive::deleteName — Delete an entry in the archive using its name

Description

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


Extract the archive contents

  • « ZipArchive::deleteName
  • ZipArchive::getArchiveComment »
  • PHP Manual
  • ZipArchive
  • Extract the archive contents

ZipArchive::extractTo

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.1.0)

ZipArchive::extractTo — Extract the archive contents

Description

ZipArchive::extractTo ( string $destination [, mixed $entries ] ) : bool

Extract the complete archive or the given files to the specified destination.

Parameters

destination

Location where to extract the files.

entries

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


Returns the Zip archive comment

  • « ZipArchive::extractTo
  • ZipArchive::getCommentIndex »
  • PHP Manual
  • ZipArchive
  • Returns the Zip archive comment

ZipArchive::getArchiveComment

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.1.0)

ZipArchive::getArchiveComment — Returns the Zip archive comment

Description

ZipArchive::getArchiveComment ([ int $flags ] ) : string

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


Returns the comment of an entry using the entry index

  • « ZipArchive::getArchiveComment
  • ZipArchive::getCommentName »
  • PHP Manual
  • ZipArchive
  • Returns the comment of an entry using the entry index

ZipArchive::getCommentIndex

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.4.0)

ZipArchive::getCommentIndex — Returns the comment of an entry using the entry index

Description

ZipArchive::getCommentIndex ( int $index [, int $flags ] ) : string

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


Returns the comment of an entry using the entry name

  • « ZipArchive::getCommentIndex
  • ZipArchive::getExternalAttributesIndex »
  • PHP Manual
  • ZipArchive
  • Returns the comment of an entry using the entry name

ZipArchive::getCommentName

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.4.0)

ZipArchive::getCommentName — Returns the comment of an entry using the entry name

Description

ZipArchive::getCommentName ( string $name [, int $flags ] ) : string

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


Retrieve the external attributes of an entry defined by its index

  • « ZipArchive::getCommentName
  • ZipArchive::getExternalAttributesName »
  • PHP Manual
  • ZipArchive
  • Retrieve the external attributes of an entry defined by its index

ZipArchive::getExternalAttributesIndex

(PHP 5 >= 5.6.0, PHP 7, PECL zip >= 1.12.4)

ZipArchive::getExternalAttributesIndex — Retrieve the external attributes of an entry defined by its index

Description

ZipArchive::GetExternalAttributesIndex ( int $index , int &$opsys , int &$attr [, int $flags ] ) : 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";
}
?>


Retrieve the external attributes of an entry defined by its name

  • « ZipArchive::getExternalAttributesIndex
  • ZipArchive::getFromIndex »
  • PHP Manual
  • ZipArchive
  • Retrieve the external attributes of an entry defined by its name

ZipArchive::getExternalAttributesName

(PHP 5 >= 5.6.0, PHP 7, PECL zip >= 1.12.4)

ZipArchive::getExternalAttributesName — Retrieve the external attributes of an entry defined by its name

Description

ZipArchive::getExternalAttributesName ( string $name , int &$opsys , int &$attr [, int $flags ] ) : 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.


Returns the entry contents using its index

  • « ZipArchive::getExternalAttributesName
  • ZipArchive::getFromName »
  • PHP Manual
  • ZipArchive
  • Returns the entry contents using its index

ZipArchive::getFromIndex

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.1.0)

ZipArchive::getFromIndex — Returns the entry contents using its index

Description

ZipArchive::getFromIndex ( int $index [, int $length = 0 [, int $flags ]] ) : string

Returns the entry contents using its index.

Parameters

index

Index of the entry

length

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


Returns the entry contents using its name

  • « ZipArchive::getFromIndex
  • ZipArchive::getNameIndex »
  • PHP Manual
  • ZipArchive
  • Returns the entry contents using its name

ZipArchive::getFromName

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.1.0)

ZipArchive::getFromName — Returns the entry contents using its name

Description

ZipArchive::getFromName ( string $name [, int $length = 0 [, int $flags ]] ) : string

Returns the entry contents using its name.

Parameters

name

Name of the entry

length

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


Returns the name of an entry using its index

  • « ZipArchive::getFromName
  • ZipArchive::getStatusString »
  • PHP Manual
  • ZipArchive
  • Returns the name of an entry using its index

ZipArchive::getNameIndex

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.5.0)

ZipArchive::getNameIndex — Returns the name of an entry using its index

Description

ZipArchive::getNameIndex ( int $index [, int $flags ] ) : string

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);
     // ...
 }
}
?>


Returns the status error message, system and/or zip messages

  • « ZipArchive::getNameIndex
  • ZipArchive::getStream »
  • PHP Manual
  • ZipArchive
  • Returns the status error message, system and/or zip messages

ZipArchive::getStatusString

(PHP 5 >= 5.2.7, PHP 7)

ZipArchive::getStatusString — Returns the status error message, system and/or zip messages

Description

ZipArchive::getStatusString ( void ) : 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 on success or FALSE on failure.


Get a file handler to the entry defined by its name (read only)

  • « ZipArchive::getStatusString
  • ZipArchive::locateName »
  • PHP Manual
  • ZipArchive
  • Get a file handler to the entry defined by its name (read only)

ZipArchive::getStream

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.1.0)

ZipArchive::getStream — Get a file handler to the entry defined by its name (read only)

Description

ZipArchive::getStream ( string $name ) : resource

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');
?>


Returns the index of the entry in the archive

  • « ZipArchive::getStream
  • ZipArchive::open »
  • PHP Manual
  • ZipArchive
  • Returns the index of the entry in the archive

ZipArchive::locateName

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.5.0)

ZipArchive::locateName — Returns the index of the entry in the archive

Description

ZipArchive::locateName ( string $name [, int $flags ] ) : int

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


Open a ZIP file archive

  • « ZipArchive::locateName
  • ZipArchive::registerCancelCallback »
  • PHP Manual
  • ZipArchive
  • Open a ZIP file archive

ZipArchive::open

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.1.0)

ZipArchive::open — Open a ZIP file archive

Description

ZipArchive::open ( string $filename [, int $flags ] ) : mixed

Opens a new zip archive for reading, writing or modifying.

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

  • ZipArchive::CHECKCONS

Return Values

Error codes

Returns TRUE on success or the error code.

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


Register a callback to allow cancellation during archive close.

  • « ZipArchive::open
  • ZipArchive::registerProgressCallback »
  • PHP Manual
  • ZipArchive
  • Register a callback to allow cancellation during archive close.

ZipArchive::registerCancelCallback

(PHP >= 8.0.0, PECL zip >= 1.17.0)

ZipArchive::registerCancelCallback — Register a callback to allow cancellation during archive close.

Description

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.

Notes

Note:

This function is only available if built against libzip ≥ 1.6.0.

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();
}

See Also

  • ZipArchive::registerProgressCallback() - Register a callback to provide updates during archive close.


Register a callback to provide updates during archive close.

  • « ZipArchive::registerCancelCallback
  • ZipArchive::renameIndex »
  • PHP Manual
  • ZipArchive
  • 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

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.

Notes

Note:

This function is only available if built against libzip ≥ 1.3.0.

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();
}

See Also

  • ZipArchive::registerCancelCallback() - Register a callback to allow cancellation during archive close.


Renames an entry defined by its index

  • « ZipArchive::registerProgressCallback
  • ZipArchive::renameName »
  • PHP Manual
  • ZipArchive
  • Renames an entry defined by its index

ZipArchive::renameIndex

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.5.0)

ZipArchive::renameIndex — Renames an entry defined by its index

Description

ZipArchive::renameIndex ( int $index , string $newname ) : bool

Renames an entry defined by its index.

Parameters

index

Index of the entry to rename.

newname

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


Renames an entry defined by its name

  • « ZipArchive::renameIndex
  • ZipArchive::setArchiveComment »
  • PHP Manual
  • ZipArchive
  • Renames an entry defined by its name

ZipArchive::renameName

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.5.0)

ZipArchive::renameName — Renames an entry defined by its name

Description

ZipArchive::renameName ( string $name , string $newname ) : bool

Renames an entry defined by its name.

Parameters

name

Name of the entry to rename.

newname

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


Set the comment of a ZIP archive

  • « ZipArchive::renameName
  • ZipArchive::setCommentIndex »
  • PHP Manual
  • ZipArchive
  • Set the comment of a ZIP archive

ZipArchive::setArchiveComment

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.4.0)

ZipArchive::setArchiveComment — Set the comment of a ZIP archive

Description

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


Set the comment of an entry defined by its index

  • « ZipArchive::setArchiveComment
  • ZipArchive::setCommentName »
  • PHP Manual
  • ZipArchive
  • Set the comment of an entry defined by its index

ZipArchive::setCommentIndex

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.4.0)

ZipArchive::setCommentIndex — Set the comment of an entry defined by its index

Description

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


Set the comment of an entry defined by its name

  • « ZipArchive::setCommentIndex
  • ZipArchive::setCompressionIndex »
  • PHP Manual
  • ZipArchive
  • Set the comment of an entry defined by its name

ZipArchive::setCommentName

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.4.0)

ZipArchive::setCommentName — Set the comment of an entry defined by its name

Description

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


Set the compression method of an entry defined by its index

  • « ZipArchive::setCommentName
  • ZipArchive::setCompressionName »
  • PHP Manual
  • ZipArchive
  • Set the compression method of an entry defined by its index

ZipArchive::setCompressionIndex

(PHP 7, PECL zip >= 1.13.0)

ZipArchive::setCompressionIndex — Set the compression method of an entry defined by its index

Description

ZipArchive::setCompressionIndex ( int $index , int $comp_method [, int $comp_flags = 0 ] ) : bool

Set the compression method of an entry defined by its index.

Parameters

index

Index of the entry.

comp_method

The compression method. Either
ZipArchive::CM_DEFAULT,
ZipArchive::CM_STORE or
ZipArchive::CM_DEFLATE.

comp_flags

Compression flags. Currently unused.

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


Set the compression method of an entry defined by its name

  • « ZipArchive::setCompressionIndex
  • ZipArchive::setEncryptionIndex »
  • PHP Manual
  • ZipArchive
  • Set the compression method of an entry defined by its name

ZipArchive::setCompressionName

(PHP 7, PECL zip >= 1.13.0)

ZipArchive::setCompressionName — Set the compression method of an entry defined by its name

Description

ZipArchive::setCompressionName ( string $name , int $comp_method [, int $comp_flags = 0 ] ) : bool

Set the compression method of an entry defined by its name.

Parameters

name

Name of the entry.

comp_method

The compression method. Either
ZipArchive::CM_DEFAULT,
ZipArchive::CM_STORE or
ZipArchive::CM_DEFLATE.

comp_flags

Compression flags. Currently unused.

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


Set the encryption method of an entry defined by its index

  • « ZipArchive::setCompressionName
  • ZipArchive::setEncryptionName »
  • PHP Manual
  • ZipArchive
  • Set the encryption method of an entry defined by its index

ZipArchive::setEncryptionIndex

(PHP >= 7.2.0, PECL zip >= 1.14.0)

ZipArchive::setEncryptionIndex — Set the encryption method of an entry defined by its index

Description

ZipArchive::setEncryptionIndex ( int $index , string $method [, string $password ] ) : 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.

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


Set the encryption method of an entry defined by its name

  • « ZipArchive::setEncryptionIndex
  • ZipArchive::setExternalAttributesIndex »
  • PHP Manual
  • ZipArchive
  • Set the encryption method of an entry defined by its name

ZipArchive::setEncryptionName

(PHP >= 7.2.0, PECL zip >= 1.14.0)

ZipArchive::setEncryptionName — Set the encryption method of an entry defined by its name

Description

ZipArchive::setEncryptionName ( string $name , int $method [, string $password ] ) : 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.

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


Set the external attributes of an entry defined by its index

  • « ZipArchive::setEncryptionName
  • ZipArchive::setExternalAttributesName »
  • PHP Manual
  • ZipArchive
  • Set the external attributes of an entry defined by its index

ZipArchive::setExternalAttributesIndex

(PHP 5 >= 5.6.0, PHP 7, PECL zip >= 1.12.4)

ZipArchive::setExternalAttributesIndex — Set the external attributes of an entry defined by its index

Description

ZipArchive::setExternalAttributesIndex ( int $index , int $opsys , int $attr [, int $flags ] ) : 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.


Set the external attributes of an entry defined by its name

  • « ZipArchive::setExternalAttributesIndex
  • ZipArchive::setMtimeIndex »
  • PHP Manual
  • ZipArchive
  • Set the external attributes of an entry defined by its name

ZipArchive::setExternalAttributesName

(PHP 5 >= 5.6.0, PHP 7, PECL zip >= 1.12.4)

ZipArchive::setExternalAttributesName — Set the external attributes of an entry defined by its name

Description

ZipArchive::setExternalAttributesName ( string $name , int $opsys , int $attr [, int $flags ] ) : 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";
}
?>


Set the modification time of an entry defined by its index

  • « ZipArchive::setExternalAttributesName
  • ZipArchive::setMtimeName »
  • PHP Manual
  • ZipArchive
  • Set the modification time of an entry defined by its index

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

ZipArchive::setMtimeIndex ( int $index , int $timestamp [, int $flags ] ) : 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->setMtimIndex(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


Set the modification time of an entry defined by its name

  • « ZipArchive::setMtimeIndex
  • ZipArchive::setPassword »
  • PHP Manual
  • ZipArchive
  • 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

ZipArchive::setMtimeName ( string $name , int $timestamp [, int $flags ] ) : 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


Set the password for the active archive

  • « ZipArchive::setMtimeName
  • ZipArchive::statIndex »
  • PHP Manual
  • ZipArchive
  • Set the password for the active archive

ZipArchive::setPassword

(PHP 5 >= 5.6.0, PHP 7, PECL zip >= 1.12.4)

ZipArchive::setPassword — Set the password for the active archive

Description

public ZipArchive::setPassword ( 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


Get the details of an entry defined by its index

  • « ZipArchive::setPassword
  • ZipArchive::statName »
  • PHP Manual
  • ZipArchive
  • Get the details of an entry defined by its index

ZipArchive::statIndex

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.1.0)

ZipArchive::statIndex — Get the details of an entry defined by its index

Description

ZipArchive::statIndex ( int $index [, int $flags ] ) : array

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
)


Get the details of an entry defined by its name

  • « ZipArchive::statIndex
  • ZipArchive::unchangeAll »
  • PHP Manual
  • ZipArchive
  • Get the details of an entry defined by its name

ZipArchive::statName

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.5.0)

ZipArchive::statName — Get the details of an entry defined by its name

Description

ZipArchive::statName ( string $name [, int $flags ] ) : array

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
)


Undo all changes done in the archive

  • « ZipArchive::statName
  • ZipArchive::unchangeArchive »
  • PHP Manual
  • ZipArchive
  • Undo all changes done in the archive

ZipArchive::unchangeAll

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.1.0)

ZipArchive::unchangeAll — Undo all changes done in the archive

Description

ZipArchive::unchangeAll ( void ) : bool

Undo all changes done in the archive.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.


Revert all global changes done in the archive

  • « ZipArchive::unchangeAll
  • ZipArchive::unchangeIndex »
  • PHP Manual
  • ZipArchive
  • Revert all global changes done in the archive

ZipArchive::unchangeArchive

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.1.0)

ZipArchive::unchangeArchive — Revert all global changes done in the archive

Description

ZipArchive::unchangeArchive ( void ) : 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.


Revert all changes done to an entry at the given index

  • « ZipArchive::unchangeArchive
  • ZipArchive::unchangeName »
  • PHP Manual
  • ZipArchive
  • Revert all changes done to an entry at the given index

ZipArchive::unchangeIndex

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.1.0)

ZipArchive::unchangeIndex — Revert all changes done to an entry at the given index

Description

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.


Revert all changes done to an entry with the given name

  • « ZipArchive::unchangeIndex
  • Zip Functions »
  • PHP Manual
  • ZipArchive
  • Revert all changes done to an entry with the given name

ZipArchive::unchangeName

(PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.5.0)

ZipArchive::unchangeName — Revert all changes done to an entry with the given name

Description

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.


Zip Functions

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


Close a ZIP file archive

  • « Zip Functions
  • zip_entry_close »
  • PHP Manual
  • Zip Functions
  • Close a ZIP file archive

zip_close

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.0.0)

zip_close — Close a ZIP file archive

Description

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.

See Also

  • zip_open() - Open a ZIP file archive
  • zip_read() - Read next entry in a ZIP file archive


Close a directory entry

  • « zip_close
  • zip_entry_compressedsize »
  • PHP Manual
  • Zip Functions
  • Close a directory entry

zip_entry_close

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.0.0)

zip_entry_close — Close a directory entry

Description

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.

See Also

  • zip_entry_open() - Open a directory entry for reading
  • zip_entry_read() - Read from an open directory entry


Retrieve the compressed size of a directory entry

  • « zip_entry_close
  • zip_entry_compressionmethod »
  • PHP Manual
  • Zip Functions
  • Retrieve the compressed size of a directory entry

zip_entry_compressedsize

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.0.0)

zip_entry_compressedsize — Retrieve the compressed size of a directory entry

Description

zip_entry_compressedsize ( resource $zip_entry ) : int

Returns the compressed size of the specified directory entry.

Parameters

zip_entry

A directory entry returned by zip_read().

Return Values

The compressed size.

See Also

  • zip_open() - Open a ZIP file archive
  • zip_read() - Read next entry in a ZIP file archive


Retrieve the compression method of a directory entry

  • « zip_entry_compressedsize
  • zip_entry_filesize »
  • PHP Manual
  • Zip Functions
  • Retrieve the compression method of a directory entry

zip_entry_compressionmethod

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.0.0)

zip_entry_compressionmethod — Retrieve the compression method of a directory entry

Description

zip_entry_compressionmethod ( resource $zip_entry ) : string

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.

See Also

  • zip_open() - Open a ZIP file archive
  • zip_read() - Read next entry in a ZIP file archive


Retrieve the actual file size of a directory entry

  • « zip_entry_compressionmethod
  • zip_entry_name »
  • PHP Manual
  • Zip Functions
  • Retrieve the actual file size of a directory entry

zip_entry_filesize

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.0.0)

zip_entry_filesize — Retrieve the actual file size of a directory entry

Description

zip_entry_filesize ( resource $zip_entry ) : int

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.

See Also

  • zip_open() - Open a ZIP file archive
  • zip_read() - Read next entry in a ZIP file archive


Retrieve the name of a directory entry

  • « zip_entry_filesize
  • zip_entry_open »
  • PHP Manual
  • Zip Functions
  • Retrieve the name of a directory entry

zip_entry_name

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.0.0)

zip_entry_name — Retrieve the name of a directory entry

Description

zip_entry_name ( resource $zip_entry ) : string

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.

See Also

  • zip_open() - Open a ZIP file archive
  • zip_read() - Read next entry in a ZIP file archive


Open a directory entry for reading

  • « zip_entry_name
  • zip_entry_read »
  • PHP Manual
  • Zip Functions
  • Open a directory entry for reading

zip_entry_open

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.0.0)

zip_entry_open — Open a directory entry for reading

Description

zip_entry_open ( resource $zip , resource $zip_entry [, string $mode ] ) : bool

Opens a directory entry in a zip file for reading.

Parameters

zip

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.

See Also

  • zip_entry_close() - Close a directory entry
  • zip_entry_read() - Read from an open directory entry


Read from an open directory entry

  • « zip_entry_open
  • zip_open »
  • PHP Manual
  • Zip Functions
  • Read from an open directory entry

zip_entry_read

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.0.0)

zip_entry_read — Read from an open directory entry

Description

zip_entry_read ( resource $zip_entry [, int $length = 1024 ] ) : string

Reads from an open directory entry.

Parameters

zip_entry

A directory entry returned by zip_read().

length

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.

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


Open a ZIP file archive

  • « zip_entry_read
  • zip_read »
  • PHP Manual
  • Zip Functions
  • Open a ZIP file archive

zip_open

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.0.0)

zip_open — Open a ZIP file archive

Description

zip_open ( string $filename ) : resource

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 the number of error if filename does not exist or in case of other error.

See Also

  • zip_read() - Read next entry in a ZIP file archive
  • zip_close() - Close a ZIP file archive


Read next entry in a ZIP file archive

  • « zip_open
  • Zlib »
  • PHP Manual
  • Zip Functions
  • Read next entry in a ZIP file archive

zip_read

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PECL zip >= 1.0.0)

zip_read — Read next entry in a ZIP file archive

Description

zip_read ( resource $zip ) : resource

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.

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


Zlib Compression

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


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:

Version 4.0.4 introduced a fopen-wrapper for .gz-files, so that you can use a special zlib: URL to access compressed files transparently using the normal f*() file access functions if you prefix the filename or path with zlib: when calling fopen(). This feature requires a C runtime library that provides the fopencookie() function. Up to now the GNU libc seems to be the only library that provides this feature.

In PHP 4.3.0, zlib: has been changed to compress.zlib:// to prevent ambiguities with filenames containing ':' characters. The fopencookie() function is no longer required. More information is available in the section about zlib://.


Requirements

This module uses the functions of » zlib by Jean-loup Gailly and Mark Adler. You have to use a zlib version >= 1.0.9 with this module. As of PHP 5.4.0 you have to use zlib >= 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" | PHP_INI_ALL |
zlib.output_compression_level | "-1" | PHP_INI_ALL |
zlib.output_handler | "" | PHP_INI_ALL |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

zlib.output_compression boolean/integer

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 integer

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.


  • « Runtime Configuration
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

This extension defines a file pointer resource returned by gzopen().


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 (integer)
FORCE_DEFLATE (integer)
ZLIB_ENCODING_RAW (integer)
DEFLATE algorithm as per RFC 1951. Available as of PHP 7.0.0.
ZLIB_ENCODING_DEFLATE (integer)
ZLIB compression algorithm as per RFC 1950. Available as of PHP 7.0.0.
ZLIB_ENCODING_GZIP (integer)
GZIP algorithm as per RFC 1952. Available as of PHP 7.0.0.
ZLIB_FILTERED (integer)
Available as of PHP 7.0.0.
ZLIB_HUFFMAN_ONLY (integer)
Available as of PHP 7.0.0.
ZLIB_FIXED (integer)
Available as of PHP 7.0.0.
ZLIB_RLE (integer)
Available as of PHP 7.0.0.
ZLIB_DEFAULT_STRATEGY (integer)
Available as of PHP 7.0.0.
ZLIB_BLOCK (integer)
Available as of PHP 7.0.0.
ZLIB_NO_FLUSH (integer)
Available as of PHP 7.0.0.
ZLIB_PARTIAL_FLUSH (integer)
Available as of PHP 7.0.0.
ZLIB_SYNC_FLUSH (integer)
Available as of PHP 7.0.0.
ZLIB_FULL_FLUSH (integer)
Available as of PHP 7.0.0.
ZLIB_FINISH (integer)
Available as of PHP 7.0.0.


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 as of PHP 7.0.0

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

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


Incrementally deflate data

  • « Zlib Functions
  • deflate_init »
  • PHP Manual
  • Zlib Functions
  • Incrementally deflate data

deflate_add

(PHP 7)

deflate_add — Incrementally deflate data

Description

deflate_add ( resource $context , string $data [, int $flush_mode = ZLIB_SYNC_FLUSH ] ) : string

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.

See Also

  • deflate_init() - Initialize an incremental deflate context


Initialize an incremental deflate context

  • « deflate_add
  • gzclose »
  • PHP Manual
  • Zlib Functions
  • Initialize an incremental deflate context

deflate_init

(PHP 7)

deflate_init — Initialize an incremental deflate context

Description

deflate_init ( int $encoding [, array $options = array() ] ) : resource

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.

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.

See Also

  • deflate_add() - Incrementally deflate data
  • inflate_init() - Initialize an incremental inflate context


Close an open gz-file pointer

  • « deflate_init
  • gzcompress »
  • PHP Manual
  • Zlib Functions
  • Close an open gz-file pointer

gzclose

(PHP 4, PHP 5, PHP 7)

gzclose — Close an open gz-file pointer

Description

gzclose ( resource $zp ) : bool

Closes the given gz-file pointer.

Parameters

zp

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


Compress a string

  • « gzclose
  • gzdecode »
  • PHP Manual
  • Zlib Functions
  • Compress a string

gzcompress

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

gzcompress — Compress a string

Description

gzcompress ( string $data [, int $level = -1 [, int $encoding = ZLIB_ENCODING_DEFLATE ]] ) : string

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

Changelog

Version | Description
5.4.0 | Added encoding parameter.

See Also

  • gzdeflate() - Deflate a string
  • gzinflate() - Inflate a deflated string
  • gzuncompress() - Uncompress a compressed string
  • gzencode() - Create a gzip compressed string


Decodes a gzip compressed string

  • « gzcompress
  • gzdeflate »
  • PHP Manual
  • Zlib Functions
  • Decodes a gzip compressed string

gzdecode

(PHP 5 >= 5.4.0, PHP 7)

gzdecode — Decodes a gzip compressed string

Description

gzdecode ( string $data [, int $length ] ) : string

This function returns a decoded version of the input data.

Parameters

data

The data to decode, encoded by gzencode().

length

The maximum length of data to decode.

Return Values

The decoded string, or FALSE if an error occurred.

See Also

  • gzencode() - Create a gzip compressed string


Deflate a string

  • « gzdecode
  • gzencode »
  • PHP Manual
  • Zlib Functions
  • Deflate a string

gzdeflate

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gzdeflate — Deflate a string

Description

gzdeflate ( string $data [, int $level = -1 [, int $encoding = ZLIB_ENCODING_RAW ]] ) : string

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

Changelog

Version | Description
5.4.0 | Added encoding parameter.

See Also

  • gzinflate() - Inflate a deflated string
  • gzcompress() - Compress a string
  • gzuncompress() - Uncompress a compressed string
  • gzencode() - Create a gzip compressed string


Create a gzip compressed string

  • « gzdeflate
  • gzeof »
  • PHP Manual
  • Zlib Functions
  • Create a gzip compressed string

gzencode

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gzencode — Create a gzip compressed string

Description

gzencode ( string $data [, int $level = -1 [, int $encoding_mode = FORCE_GZIP ]] ) : string

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_mode

The encoding mode. Can be FORCE_GZIP (the default) or FORCE_DEFLATE.

Prior to PHP 5.4.0, using FORCE_DEFLATE results in a standard zlib deflated string (inclusive zlib headers) after a gzip file header but without the trailing crc32 checksum.

In PHP 5.4.0 and later, 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.

Changelog

Version | Description
5.4.0 | FORCE_DEFLATE now generates RFC 1950 compliant output.

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 = implode("", file("bigfile.txt"));
$gzdata = gzencode($data, 9);
$fp = fopen("bigfile.txt.gz", "w");
fwrite($fp, $gzdata);
fclose($fp);
?>

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)


Test for EOF on a gz-file pointer

  • « gzencode
  • gzfile »
  • PHP Manual
  • Zlib Functions
  • Test for EOF on a gz-file pointer

gzeof

(PHP 4, PHP 5, PHP 7)

gzeof — Test for EOF on a gz-file pointer

Description

gzeof ( resource $zp ) : int

Tests the given GZ file pointer for EOF.

Parameters

zp

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


Read entire gz-file into an array

  • « gzeof
  • gzgetc »
  • PHP Manual
  • Zlib Functions
  • Read entire gz-file into an array

gzfile

(PHP 4, PHP 5, PHP 7)

gzfile — Read entire gz-file into an array

Description

gzfile ( string $filename [, int $use_include_path = 0 ] ) : array

This function is identical to readgzfile(), except that it returns the file in an array.

Parameters

filename

The file name.

use_include_path

You can set this optional parameter to 1, if you want to search for the file in the include_path too.

Return Values

An array containing the file, one line per cell, empty lines included, and with newlines still attached.

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


Get character from gz-file pointer

  • « gzfile
  • gzgets »
  • PHP Manual
  • Zlib Functions
  • Get character from gz-file pointer

gzgetc

(PHP 4, PHP 5, PHP 7)

gzgetc — Get character from gz-file pointer

Description

gzgetc ( resource $zp ) : string

Returns a string containing a single (uncompressed) character read from the given gz-file pointer.

Parameters

zp

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


Get line from file pointer

  • « gzgetc
  • gzgetss »
  • PHP Manual
  • Zlib Functions
  • Get line from file pointer

gzgets

(PHP 4, PHP 5, PHP 7)

gzgets — Get line from file pointer

Description

gzgets ( resource $zp [, int $length ] ) : string

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

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.

Return Values

The uncompressed string, or FALSE on error.

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


Get line from gz-file pointer and strip HTML tags

  • « gzgets
  • gzinflate »
  • PHP Manual
  • Zlib Functions
  • Get line from gz-file pointer and strip HTML tags

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


Inflate a deflated string

  • « gzgetss
  • gzopen »
  • PHP Manual
  • Zlib Functions
  • Inflate a deflated string

gzinflate

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gzinflate — Inflate a deflated string

Description

gzinflate ( string $data [, int $length = 0 ] ) : string

This function inflates a deflated string.

Parameters

data

The data compressed by gzdeflate().

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


Open gz-file

  • « gzinflate
  • gzpassthru »
  • PHP Manual
  • Zlib Functions
  • Open gz-file

gzopen

(PHP 4, PHP 5, PHP 7)

gzopen — Open gz-file

Description

gzopen ( string $filename , string $mode [, int $use_include_path = 0 ] ) : resource

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

You can set this optional parameter to 1, if you want to search for the file in the include_path 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.

Examples

Example #1 gzopen() Example

<?php
$fp = gzopen("/tmp/file.gz", "r");
?>

See Also

  • gzclose() - Close an open gz-file pointer


Output all remaining data on a gz-file pointer

  • « gzopen
  • gzputs »
  • PHP Manual
  • Zlib Functions
  • Output all remaining data on a gz-file pointer

gzpassthru

(PHP 4, PHP 5, PHP 7)

gzpassthru — Output all remaining data on a gz-file pointer

Description

gzpassthru ( resource $zp ) : 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

zp

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, or FALSE on error.

Examples

Example #1 gzpassthru() example

<?php
$fp = gzopen('file.gz', 'r');
gzpassthru($fp);
gzclose($fp);
?>


Alias of gzwrite

  • « gzpassthru
  • gzread »
  • PHP Manual
  • Zlib Functions
  • Alias of gzwrite

gzputs

(PHP 4, PHP 5, PHP 7)

gzputs — Alias of gzwrite()

Description

This function is an alias of: gzwrite().


Binary-safe gz-file read

  • « gzputs
  • gzrewind »
  • PHP Manual
  • Zlib Functions
  • Binary-safe gz-file read

gzread

(PHP 4, PHP 5, PHP 7)

gzread — Binary-safe gz-file read

Description

gzread ( resource $zp , int $length ) : string

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

zp

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.

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


Rewind the position of a gz-file pointer

  • « gzread
  • gzseek »
  • PHP Manual
  • Zlib Functions
  • Rewind the position of a gz-file pointer

gzrewind

(PHP 4, PHP 5, PHP 7)

gzrewind — Rewind the position of a gz-file pointer

Description

gzrewind ( resource $zp ) : bool

Sets the file position indicator of the given gz-file pointer to the beginning of the file stream.

Parameters

zp

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


Seek on a gz-file pointer

  • « gzrewind
  • gztell »
  • PHP Manual
  • Zlib Functions
  • Seek on a gz-file pointer

gzseek

(PHP 4, PHP 5, PHP 7)

gzseek — Seek on a gz-file pointer

Description

gzseek ( resource $zp , 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

zp

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


Tell gz-file pointer read/write position

  • « gzseek
  • gzuncompress »
  • PHP Manual
  • Zlib Functions
  • Tell gz-file pointer read/write position

gztell

(PHP 4, PHP 5, PHP 7)

gztell — Tell gz-file pointer read/write position

Description

gztell ( resource $zp ) : int

Gets the position of the given file pointer; i.e., its offset into the uncompressed file stream.

Parameters

zp

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


Uncompress a compressed string

  • « gztell
  • gzwrite »
  • PHP Manual
  • Zlib Functions
  • Uncompress a compressed string

gzuncompress

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

gzuncompress — Uncompress a compressed string

Description

gzuncompress ( string $data [, int $length = 0 ] ) : string

This function uncompress a compressed string.

Parameters

data

The data compressed by gzcompress().

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


Binary-safe gz-file write

  • « gzuncompress
  • inflate_add »
  • PHP Manual
  • Zlib Functions
  • Binary-safe gz-file write

gzwrite

(PHP 4, PHP 5, PHP 7)

gzwrite — Binary-safe gz-file write

Description

gzwrite ( resource $zp , string $string [, int $length ] ) : int

gzwrite() writes the contents of string to the given gz-file.

Parameters

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

string

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 string is reached, whichever comes first.

Note:

Note that if the length argument is given, then the magic_quotes_runtime configuration option will be ignored and no slashes will be stripped from string.

Return Values

Returns the number of (uncompressed) bytes written to the given gz-file stream.

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


Incrementally inflate encoded data

  • « gzwrite
  • inflate_get_read_len »
  • PHP Manual
  • Zlib Functions
  • Incrementally inflate encoded data

inflate_add

(PHP 7)

inflate_add — Incrementally inflate encoded data

Description

inflate_add ( resource $context , string $encoded_data [, int $flush_mode = ZLIB_SYNC_FLUSH ] ) : string

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

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

See Also

  • inflate_init() - Initialize an incremental inflate context


Get number of bytes read so far

  • « inflate_add
  • inflate_get_status »
  • PHP Manual
  • Zlib Functions
  • Get number of bytes read so far

inflate_get_read_len

(PHP 7 >= 7.2.0)

inflate_get_read_len — Get number of bytes read so far

Description

inflate_get_read_len ( resource $resource ) : int

Warning

This function is currently not documented; only its argument list is available.

Parameters

resource

Return Values

Returns number of bytes read so far or FALSE on failure.


Get decompression status

  • « inflate_get_read_len
  • inflate_init »
  • PHP Manual
  • Zlib Functions
  • Get decompression status

inflate_get_status

(PHP 7 >= 7.2.0)

inflate_get_status — Get decompression status

Description

inflate_get_status ( resource $resource ) : int

Usually returns either ZLIB_OK or ZLIB_STREAM_END.

Parameters

resource

Return Values

Returns decompression status or FALSE on failure.


Initialize an incremental inflate context

  • « inflate_get_status
  • readgzfile »
  • PHP Manual
  • Zlib Functions
  • Initialize an incremental inflate context

inflate_init

(PHP 7)

inflate_init — Initialize an incremental inflate context

Description

inflate_init ( int $encoding [, array $options = array() ] ) : resource

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.

See Also

  • inflate_add() - Incrementally inflate encoded data
  • deflate_init() - Initialize an incremental deflate context


Output a gz-file

  • « inflate_init
  • zlib_decode »
  • PHP Manual
  • Zlib Functions
  • Output a gz-file

readgzfile

(PHP 4, PHP 5, PHP 7)

readgzfile — Output a gz-file

Description

readgzfile ( string $filename [, int $use_include_path = 0 ] ) : int

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

You can set this optional parameter to 1, if you want to search for the file in the include_path too.

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.

See Also

  • gzpassthru() - Output all remaining data on a gz-file pointer
  • gzfile() - Read entire gz-file into an array
  • gzopen() - Open gz-file


Uncompress any raw/gzip/zlib encoded data

  • « readgzfile
  • zlib_encode »
  • PHP Manual
  • Zlib Functions
  • Uncompress any raw/gzip/zlib encoded data

zlib_decode

(PHP 5 >= 5.4.0, PHP 7)

zlib_decode — Uncompress any raw/gzip/zlib encoded data

Description

zlib_decode ( string $data [, string $max_decoded_len ] ) : string

Uncompress any raw/gzip/zlib encoded data.

Warning

This function is currently not documented; only its argument list is available.

Parameters

data

max_decoded_len

Return Values

Returns the uncompressed data, or FALSE on failure.

See Also

  • zlib_encode() - Compress data with the specified encoding


Compress data with the specified encoding

  • « zlib_decode
  • zlib_get_coding_type »
  • PHP Manual
  • Zlib Functions
  • Compress data with the specified encoding

zlib_encode

(PHP 5 >= 5.4.0, PHP 7)

zlib_encode — Compress data with the specified encoding

Description

zlib_encode ( string $data , int $encoding [, int $level = -1 ] ) : string

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


Returns the coding type used for output compression

  • « zlib_encode
  • Credit Card Processing »
  • PHP Manual
  • Zlib Functions
  • Returns the coding type used for output compression

zlib_get_coding_type

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

zlib_get_coding_type — Returns the coding type used for output compression

Description

zlib_get_coding_type ( void ) : string

Returns the coding type used for output compression.

Return Values

Possible return values are gzip, deflate, or FALSE.

See Also

  • The zlib.output_compression directive


Credit Card Processing

  • MCVE — MCVE (Monetra) Payment
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • MCVE Functions


MCVE (Monetra) Payment

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • MCVE Functions
    • m_checkstatus — Check to see if a transaction has completed
    • m_completeauthorizations — Number of complete authorizations in queue, returning an array of their identifiers
    • m_connect — Establish the connection to MCVE
    • m_connectionerror — Get a textual representation of why a connection failed
    • m_deletetrans — Delete specified transaction from MCVE_CONN structure
    • m_destroyconn — Destroy the connection and MCVE_CONN structure
    • m_destroyengine — Free memory associated with IP/SSL connectivity
    • m_getcell — Get a specific cell from a comma delimited response by column name
    • m_getcellbynum — Get a specific cell from a comma delimited response by column number
    • m_getcommadelimited — Get the RAW comma delimited data returned from MCVE
    • m_getheader — Get the name of the column in a comma-delimited response
    • m_initconn — Create and initialize an MCVE_CONN structure
    • m_initengine — Ready the client for IP/SSL Communication
    • m_iscommadelimited — Checks to see if response is comma delimited
    • m_maxconntimeout — The maximum amount of time the API will attempt a connection to MCVE
    • m_monitor — Perform communication with MCVE (send/receive data) Non-blocking
    • m_numcolumns — Number of columns returned in a comma delimited response
    • m_numrows — Number of rows returned in a comma delimited response
    • m_parsecommadelimited — Parse the comma delimited response so m_getcell, etc will work
    • m_responsekeys — Returns array of strings which represents the keys that can be used for response parameters on this transaction
    • m_responseparam — Get a custom response parameter
    • m_returnstatus — Check to see if the transaction was successful
    • m_setblocking — Set blocking/non-blocking mode for connection
    • m_setdropfile — Set the connection method to Drop-File
    • m_setip — Set the connection method to IP
    • m_setssl_cafile — Set SSL CA (Certificate Authority) file for verification of server certificate
    • m_setssl_files — Set certificate key files and certificates if server requires client certificate verification
    • m_setssl — Set the connection method to SSL
    • m_settimeout — Set maximum transaction time (per trans)
    • m_sslcert_gen_hash — Generate hash for SSL client certificate verification
    • m_transactionssent — Check to see if outgoing buffer is clear
    • m_transinqueue — Number of transactions in client-queue
    • m_transkeyval — Add key/value pair to a transaction. Replaces deprecated transparam()
    • m_transnew — Start a new transaction
    • m_transsend — Finalize and send the transaction
    • m_uwait — Wait x microsecs
    • m_validateidentifier — Whether or not to validate the passed identifier on any transaction it is passed to
    • m_verifyconnection — Set whether or not to PING upon connect to verify connection
    • m_verifysslcert — Set whether or not to verify the server ssl certificate


Introduction

These functions interface the MCVE (Monetra) API (libmonetra, formerly known as libmcve), allowing you to work directly with MCVE/Monetra from your PHP scripts. MCVE/Monetra is Main Street Softworks' solution to direct credit/debit/gift card processing for Linux/Unix/MacOSX/Windows ( » http://www.mainstreetsoftworks.com/ ). It lets you directly address the credit card clearing houses via your *nix box, modem and/or internet connection (bypassing the need for an additional service such as Authorize.Net or Pay Flow Pro). Using the MCVE/Monetra module for PHP, you can process credit cards directly through MCVE/Monetra via your PHP scripts. The following references will outline the process.

Note:

MCVE/Monetra is the replacement for RedHat's CCVS. They contracted with RedHat in late 2001 to migrate all existing clientele to the MCVE platform.

Note:

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.1.0.

Note: This extension is not available on Windows platforms.


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

The LibMonetra (formerly libmcve) library.


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

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

If installing without specifying the libmonetra path, PHP will attempt to look in the default LibMonetra Install location (/usr/local). If Monetra (MCVE) is in a non-standard location, run configure with: --with-mcve=$mcve_path , where $mcve_path is the path to your MCVE/Monetra installation. Please note that MCVE/Monetra support requires that $mcve_path/lib and $mcve_path/include exist, and include mcve.h or monetra.h under the include directory and libmcve.so and/or libmcve.a and/or libmonetra.so and/or libmonetra.a under the lib directory.

Since MCVE/Monetra has true server/client separation, there are no additional requirements for running PHP with MCVE support. To test your MCVE/Monetra extension in PHP, you may connect to testbox.monetra.com on port 8333 for IP, or port 8444 for SSL using the MCVE/Monetra PHP API. Use 'vitale' for your username, and 'test' for your password. Additional information about test facilities are available at » http://www.mainstreetsoftworks.com/.


  • « Runtime Configuration
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

This extension defines a MCVE_CONN resource returned by m_initconn().


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.

M_PENDING (integer)
M_DONE (integer)
M_ERROR (integer)
M_FAIL (integer)
M_SUCCESS (integer)


MCVE Functions

See Also

Additional documentation about MCVE/Monetra's PHP API can be found at » http://www.mainstreetsoftworks.com/documentation.html. Main Street's documentation is complete and should be the primary reference for functions.

Table of Contents

  • m_checkstatus — Check to see if a transaction has completed
  • m_completeauthorizations — Number of complete authorizations in queue, returning an array of their identifiers
  • m_connect — Establish the connection to MCVE
  • m_connectionerror — Get a textual representation of why a connection failed
  • m_deletetrans — Delete specified transaction from MCVE_CONN structure
  • m_destroyconn — Destroy the connection and MCVE_CONN structure
  • m_destroyengine — Free memory associated with IP/SSL connectivity
  • m_getcell — Get a specific cell from a comma delimited response by column name
  • m_getcellbynum — Get a specific cell from a comma delimited response by column number
  • m_getcommadelimited — Get the RAW comma delimited data returned from MCVE
  • m_getheader — Get the name of the column in a comma-delimited response
  • m_initconn — Create and initialize an MCVE_CONN structure
  • m_initengine — Ready the client for IP/SSL Communication
  • m_iscommadelimited — Checks to see if response is comma delimited
  • m_maxconntimeout — The maximum amount of time the API will attempt a connection to MCVE
  • m_monitor — Perform communication with MCVE (send/receive data) Non-blocking
  • m_numcolumns — Number of columns returned in a comma delimited response
  • m_numrows — Number of rows returned in a comma delimited response
  • m_parsecommadelimited — Parse the comma delimited response so m_getcell, etc will work
  • m_responsekeys — Returns array of strings which represents the keys that can be used for response parameters on this transaction
  • m_responseparam — Get a custom response parameter
  • m_returnstatus — Check to see if the transaction was successful
  • m_setblocking — Set blocking/non-blocking mode for connection
  • m_setdropfile — Set the connection method to Drop-File
  • m_setip — Set the connection method to IP
  • m_setssl_cafile — Set SSL CA (Certificate Authority) file for verification of server certificate
  • m_setssl_files — Set certificate key files and certificates if server requires client certificate verification
  • m_setssl — Set the connection method to SSL
  • m_settimeout — Set maximum transaction time (per trans)
  • m_sslcert_gen_hash — Generate hash for SSL client certificate verification
  • m_transactionssent — Check to see if outgoing buffer is clear
  • m_transinqueue — Number of transactions in client-queue
  • m_transkeyval — Add key/value pair to a transaction. Replaces deprecated transparam()
  • m_transnew — Start a new transaction
  • m_transsend — Finalize and send the transaction
  • m_uwait — Wait x microsecs
  • m_validateidentifier — Whether or not to validate the passed identifier on any transaction it is passed to
  • m_verifyconnection — Set whether or not to PING upon connect to verify connection
  • m_verifysslcert — Set whether or not to verify the server ssl certificate


Check to see if a transaction has completed

  • « MCVE Functions
  • m_completeauthorizations »
  • PHP Manual
  • MCVE Functions
  • Check to see if a transaction has completed

m_checkstatus

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_checkstatus — Check to see if a transaction has completed

Description

m_checkstatus ( resource $conn , int $identifier ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Return Values


Number of complete authorizations in queue, returning an array of their identifiers

  • « m_checkstatus
  • m_connect »
  • PHP Manual
  • MCVE Functions
  • Number of complete authorizations in queue, returning an array of their identifiers

m_completeauthorizations

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_completeauthorizations — Number of complete authorizations in queue, returning an array of their identifiers

Description

m_completeauthorizations ( resource $conn , int &$array ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

array

Its description

Return Values

What the function returns, first on success, then on failure. See also the &return.success; entity


Establish the connection to MCVE

  • « m_completeauthorizations
  • m_connectionerror »
  • PHP Manual
  • MCVE Functions
  • Establish the connection to MCVE

m_connect

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_connect — Establish the connection to MCVE

Description

m_connect ( resource $conn ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

Return Values


Get a textual representation of why a connection failed

  • « m_connect
  • m_deletetrans »
  • PHP Manual
  • MCVE Functions
  • Get a textual representation of why a connection failed

m_connectionerror

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_connectionerror — Get a textual representation of why a connection failed

Description

m_connectionerror ( resource $conn ) : string
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

Return Values


Delete specified transaction from MCVE_CONN structure

  • « m_connectionerror
  • m_destroyconn »
  • PHP Manual
  • MCVE Functions
  • Delete specified transaction from MCVE_CONN structure

m_deletetrans

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_deletetrans — Delete specified transaction from MCVE_CONN structure

Description

m_deletetrans ( resource $conn , int $identifier ) : bool
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Return Values


Destroy the connection and MCVE_CONN structure

  • « m_deletetrans
  • m_destroyengine »
  • PHP Manual
  • MCVE Functions
  • Destroy the connection and MCVE_CONN structure

m_destroyconn

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_destroyconn — Destroy the connection and MCVE_CONN structure

Description

m_destroyconn ( resource $conn ) : bool
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

Return Values

Returns TRUE.

See Also

  • m_initconn() - Create and initialize an MCVE_CONN structure


Free memory associated with IP/SSL connectivity

  • « m_destroyconn
  • m_getcell »
  • PHP Manual
  • MCVE Functions
  • Free memory associated with IP/SSL connectivity

m_destroyengine

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_destroyengine — Free memory associated with IP/SSL connectivity

Description

m_destroyengine ( void ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

Return Values

No value is returned.


Get a specific cell from a comma delimited response by column name

  • « m_destroyengine
  • m_getcellbynum »
  • PHP Manual
  • MCVE Functions
  • Get a specific cell from a comma delimited response by column name

m_getcell

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_getcell — Get a specific cell from a comma delimited response by column name

Description

m_getcell ( resource $conn , int $identifier , string $column , int $row ) : string
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

column

row

Return Values


Get a specific cell from a comma delimited response by column number

  • « m_getcell
  • m_getcommadelimited »
  • PHP Manual
  • MCVE Functions
  • Get a specific cell from a comma delimited response by column number

m_getcellbynum

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_getcellbynum — Get a specific cell from a comma delimited response by column number

Description

m_getcellbynum ( resource $conn , int $identifier , int $column , int $row ) : string
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

column

row

Return Values


Get the RAW comma delimited data returned from MCVE

  • « m_getcellbynum
  • m_getheader »
  • PHP Manual
  • MCVE Functions
  • Get the RAW comma delimited data returned from MCVE

m_getcommadelimited

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_getcommadelimited — Get the RAW comma delimited data returned from MCVE

Description

m_getcommadelimited ( resource $conn , int $identifier ) : string
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Return Values


Get the name of the column in a comma-delimited response

  • « m_getcommadelimited
  • m_initconn »
  • PHP Manual
  • MCVE Functions
  • Get the name of the column in a comma-delimited response

m_getheader

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_getheader — Get the name of the column in a comma-delimited response

Description

m_getheader ( resource $conn , int $identifier , int $column_num ) : string
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

column_num

Return Values


Create and initialize an MCVE_CONN structure

  • « m_getheader
  • m_initengine »
  • PHP Manual
  • MCVE Functions
  • Create and initialize an MCVE_CONN structure

m_initconn

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_initconn — Create and initialize an MCVE_CONN structure

Description

m_initconn ( void ) : resource
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns an MCVE_CONN resource.

See Also

  • m_destroyconn() - Destroy the connection and MCVE_CONN structure


Ready the client for IP/SSL Communication

  • « m_initconn
  • m_iscommadelimited »
  • PHP Manual
  • MCVE Functions
  • Ready the client for IP/SSL Communication

m_initengine

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_initengine — Ready the client for IP/SSL Communication

Description

m_initengine ( string $location ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

location

Return Values


Checks to see if response is comma delimited

  • « m_initengine
  • m_maxconntimeout »
  • PHP Manual
  • MCVE Functions
  • Checks to see if response is comma delimited

m_iscommadelimited

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_iscommadelimited — Checks to see if response is comma delimited

Description

m_iscommadelimited ( resource $conn , int $identifier ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Return Values


The maximum amount of time the API will attempt a connection to MCVE

  • « m_iscommadelimited
  • m_monitor »
  • PHP Manual
  • MCVE Functions
  • The maximum amount of time the API will attempt a connection to MCVE

m_maxconntimeout

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_maxconntimeout — The maximum amount of time the API will attempt a connection to MCVE

Description

m_maxconntimeout ( resource $conn , int $secs ) : bool
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

secs

Return Values


Perform communication with MCVE (send/receive data) Non-blocking

  • « m_maxconntimeout
  • m_numcolumns »
  • PHP Manual
  • MCVE Functions
  • Perform communication with MCVE (send/receive data) Non-blocking

m_monitor

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_monitor — Perform communication with MCVE (send/receive data) Non-blocking

Description

m_monitor ( resource $conn ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

Return Values


Number of columns returned in a comma delimited response

  • « m_monitor
  • m_numrows »
  • PHP Manual
  • MCVE Functions
  • Number of columns returned in a comma delimited response

m_numcolumns

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_numcolumns — Number of columns returned in a comma delimited response

Description

m_numcolumns ( resource $conn , int $identifier ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Return Values


Number of rows returned in a comma delimited response

  • « m_numcolumns
  • m_parsecommadelimited »
  • PHP Manual
  • MCVE Functions
  • Number of rows returned in a comma delimited response

m_numrows

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_numrows — Number of rows returned in a comma delimited response

Description

m_numrows ( resource $conn , int $identifier ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Return Values


Parse the comma delimited response so m_getcell, etc will work

  • « m_numrows
  • m_responsekeys »
  • PHP Manual
  • MCVE Functions
  • Parse the comma delimited response so m_getcell, etc will work

m_parsecommadelimited

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_parsecommadelimited — Parse the comma delimited response so m_getcell, etc will work

Description

m_parsecommadelimited ( resource $conn , int $identifier ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Return Values


Returns array of strings which represents the keys that can be used for response parameters on this transaction

  • « m_parsecommadelimited
  • m_responseparam »
  • PHP Manual
  • MCVE Functions
  • Returns array of strings which represents the keys that can be used for response parameters on this transaction

m_responsekeys

(PHP 5 >= 5.0.5 < 5.1.0, PECL mcve >= 1.0.0)

m_responsekeys — Returns array of strings which represents the keys that can be used for response parameters on this transaction

Description

m_responsekeys ( resource $conn , int $identifier ) : array
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Return Values


Get a custom response parameter

  • « m_responsekeys
  • m_returnstatus »
  • PHP Manual
  • MCVE Functions
  • Get a custom response parameter

m_responseparam

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_responseparam — Get a custom response parameter

Description

m_responseparam ( resource $conn , int $identifier , string $key ) : string
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

key

Return Values


Check to see if the transaction was successful

  • « m_responseparam
  • m_setblocking »
  • PHP Manual
  • MCVE Functions
  • Check to see if the transaction was successful

m_returnstatus

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_returnstatus — Check to see if the transaction was successful

Description

m_returnstatus ( resource $conn , int $identifier ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Return Values


Set blocking/non-blocking mode for connection

  • « m_returnstatus
  • m_setdropfile »
  • PHP Manual
  • MCVE Functions
  • Set blocking/non-blocking mode for connection

m_setblocking

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_setblocking — Set blocking/non-blocking mode for connection

Description

m_setblocking ( resource $conn , int $tf ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

tf

Return Values


Set the connection method to Drop-File

  • « m_setblocking
  • m_setip »
  • PHP Manual
  • MCVE Functions
  • Set the connection method to Drop-File

m_setdropfile

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_setdropfile — Set the connection method to Drop-File

Description

m_setdropfile ( resource $conn , string $directory ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

directory

Return Values


Set the connection method to IP

  • « m_setdropfile
  • m_setssl_cafile »
  • PHP Manual
  • MCVE Functions
  • Set the connection method to IP

m_setip

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_setip — Set the connection method to IP

Description

m_setip ( resource $conn , string $host , int $port ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

host

port

Return Values


Set SSL CA (Certificate Authority) file for verification of server certificate

  • « m_setip
  • m_setssl_files »
  • PHP Manual
  • MCVE Functions
  • Set SSL CA (Certificate Authority) file for verification of server certificate

m_setssl_cafile

(PHP 5 >= 5.0.5 < 5.1.0, PECL mcve >= 1.0.0)

m_setssl_cafile — Set SSL CA (Certificate Authority) file for verification of server certificate

Description

m_setssl_cafile ( resource $conn , string $cafile ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

cafile

Return Values


Set certificate key files and certificates if server requires client certificate verification

  • « m_setssl_cafile
  • m_setssl »
  • PHP Manual
  • MCVE Functions
  • Set certificate key files and certificates if server requires client certificate verification

m_setssl_files

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_setssl_files — Set certificate key files and certificates if server requires client certificate verification

Description

m_setssl_files ( resource $conn , string $sslkeyfile , string $sslcertfile ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

sslkeyfile

sslcertfile

Return Values


Set the connection method to SSL

  • « m_setssl_files
  • m_settimeout »
  • PHP Manual
  • MCVE Functions
  • Set the connection method to SSL

m_setssl

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_setssl — Set the connection method to SSL

Description

m_setssl ( resource $conn , string $host , int $port ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

host

port

Return Values


Set maximum transaction time (per trans)

  • « m_setssl
  • m_sslcert_gen_hash »
  • PHP Manual
  • MCVE Functions
  • Set maximum transaction time (per trans)

m_settimeout

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_settimeout — Set maximum transaction time (per trans)

Description

m_settimeout ( resource $conn , int $seconds ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

seconds

Return Values


Generate hash for SSL client certificate verification

  • « m_settimeout
  • m_transactionssent »
  • PHP Manual
  • MCVE Functions
  • Generate hash for SSL client certificate verification

m_sslcert_gen_hash

(PECL mcve >= 5.2.0)

m_sslcert_gen_hash — Generate hash for SSL client certificate verification

Description

m_sslcert_gen_hash ( string $filename ) : string
Warning

This function is currently not documented; only its argument list is available.

Parameters

filename

Return Values


Check to see if outgoing buffer is clear

  • « m_sslcert_gen_hash
  • m_transinqueue »
  • PHP Manual
  • MCVE Functions
  • Check to see if outgoing buffer is clear

m_transactionssent

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_transactionssent — Check to see if outgoing buffer is clear

Description

m_transactionssent ( resource $conn ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

Return Values


Number of transactions in client-queue

  • « m_transactionssent
  • m_transkeyval »
  • PHP Manual
  • MCVE Functions
  • Number of transactions in client-queue

m_transinqueue

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_transinqueue — Number of transactions in client-queue

Description

m_transinqueue ( resource $conn ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

Return Values


Add key/value pair to a transaction. Replaces deprecated transparam()

  • « m_transinqueue
  • m_transnew »
  • PHP Manual
  • MCVE Functions
  • Add key/value pair to a transaction. Replaces deprecated transparam()

m_transkeyval

(PHP 5 >= 5.0.5 < 5.1.0, PECL mcve >= 1.0.0)

m_transkeyval — Add key/value pair to a transaction. Replaces deprecated transparam()

Description

m_transkeyval ( resource $conn , int $identifier , string $key , string $value ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

key

value

Return Values


Start a new transaction

  • « m_transkeyval
  • m_transsend »
  • PHP Manual
  • MCVE Functions
  • Start a new transaction

m_transnew

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_transnew — Start a new transaction

Description

m_transnew ( resource $conn ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

Return Values


Finalize and send the transaction

  • « m_transnew
  • m_uwait »
  • PHP Manual
  • MCVE Functions
  • Finalize and send the transaction

m_transsend

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_transsend — Finalize and send the transaction

Description

m_transsend ( resource $conn , int $identifier ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

identifier

Return Values


Wait x microsecs

  • « m_transsend
  • m_validateidentifier »
  • PHP Manual
  • MCVE Functions
  • Wait x microsecs

m_uwait

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_uwait — Wait x microsecs

Description

m_uwait ( int $microsecs ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

microsecs

Return Values


Whether or not to validate the passed identifier on any transaction it is passed to

  • « m_uwait
  • m_verifyconnection »
  • PHP Manual
  • MCVE Functions
  • Whether or not to validate the passed identifier on any transaction it is passed to

m_validateidentifier

(PHP 5 >= 5.0.5 < 5.1.0, PECL mcve >= 1.0.0)

m_validateidentifier — Whether or not to validate the passed identifier on any transaction it is passed to

Description

m_validateidentifier ( resource $conn , int $tf ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

tf

Return Values


Set whether or not to PING upon connect to verify connection

  • « m_validateidentifier
  • m_verifysslcert »
  • PHP Manual
  • MCVE Functions
  • Set whether or not to PING upon connect to verify connection

m_verifyconnection

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_verifyconnection — Set whether or not to PING upon connect to verify connection

Description

m_verifyconnection ( resource $conn , int $tf ) : bool
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

tf

Return Values


Set whether or not to verify the server ssl certificate

  • « m_verifyconnection
  • Cryptography Extensions »
  • PHP Manual
  • MCVE Functions
  • Set whether or not to verify the server ssl certificate

m_verifysslcert

(PHP 4 >= 4.3.9, PHP 5 < 5.1.0, PECL mcve >= 1.0.0)

m_verifysslcert — Set whether or not to verify the server ssl certificate

Description

m_verifysslcert ( resource $conn , int $tf ) : bool
Warning

This function is currently not documented; only its argument list is available.

Parameters

conn

An MCVE_CONN resource returned by m_initengine().

tf

Return Values


Cryptography Extensions

  • Crack — Cracklib
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Crack Functions
  • CSPRNG
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • CSPRNG Functions
  • Hash — HASH Message Digest Framework
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • HashContext — The HashContext class
    • Hash Functions
  • Mcrypt
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Mcrypt ciphers
    • Examples
    • Mcrypt Functions
  • Mhash
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Mhash Functions
  • OpenSSL
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Key/Certificate parameters
    • Certificate Verification
    • OpenSSL Functions
  • Password Hashing
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Password Hashing Functions
  • Sodium
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Sodium Functions


Cracklib

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Crack Functions
    • crack_check — Performs an obscure check with the given password
    • crack_closedict — Closes an open CrackLib dictionary
    • crack_getlastmessage — Returns the message from the last obscure check
    • crack_opendict — Opens a new CrackLib dictionary


Introduction

These functions allow you to use the CrackLib library to test the 'strength' of a password. The 'strength' of a password is tested by that checks length, use of upper and lower case and checked against the specified CrackLib dictionary. CrackLib will also give helpful diagnostic messages that will help 'strengthen' the password.

Note:

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.0.0.


Requirements

More information regarding CrackLib along with the library can be found at » http://sourceforge.net/projects/cracklib.


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

In order to use these functions you must compile PHP with Crack support by using the --with-crack[=DIR] configuration option.

Windows users will enable php_crack.dll inside of php.ini in order to use these functions. A DLL for this PECL extension is currently unavailable. See also the building on Windows section.


  • « Runtime Configuration
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

The CrackLib extension defines a dictionary resource identifier returned by crack_opendict().


  • « Resource Types
  • Examples »
  • PHP Manual
  • Crack
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


Examples

This example shows how to open a CrackLib dictionary, test a given password, retrieve any diagnostic messages, and close the dictionary.

Example #1 CrackLib example

<?php
// Open CrackLib Dictionary
$dictionary = crack_opendict('/usr/local/lib/pw_dict')
     or die('Unable to open CrackLib dictionary');

// Perform password check
$check = crack_check($dictionary, 'gx9A2s0x');

// Retrieve messages
$diag = crack_getlastmessage();
echo $diag; // 'strong password'

// Close dictionary
crack_closedict($dictionary);
?>

Note:

If crack_check() returns TRUE, crack_getlastmessage() will return 'strong password'.


Crack Functions

Table of Contents

  • crack_check — Performs an obscure check with the given password
  • crack_closedict — Closes an open CrackLib dictionary
  • crack_getlastmessage — Returns the message from the last obscure check
  • crack_opendict — Opens a new CrackLib dictionary


Performs an obscure check with the given password

  • « Crack Functions
  • crack_closedict »
  • PHP Manual
  • Crack Functions
  • Performs an obscure check with the given password

crack_check

(PECL crack >= 0.1)

crack_check — Performs an obscure check with the given password

Description

crack_check ( resource $dictionary , string $password ) : bool
crack_check ( string $password , string $username = "" , string $gecos = "" , resource $dictionary = NULL ) : bool

Performs an obscure check with the given password on the specified dictionary. The alternative signature also takes into account the username and the GECOS information.

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.

Parameters

dictionary

The crack lib dictionary. If not specified, the last opened dictionary is used.

password

The password to be checked.

username

The username of the account with the password.

gecos

The GECOS information associated with the user account.

Return Values

Returns TRUE if password is strong, or FALSE otherwise.

Changelog

Version | Description
0.3 | The username, gecos and dictionary parameters were added to the alternative signature.


Closes an open CrackLib dictionary

  • « crack_check
  • crack_getlastmessage »
  • PHP Manual
  • Crack Functions
  • Closes an open CrackLib dictionary

crack_closedict

(PECL crack >= 0.1)

crack_closedict — Closes an open CrackLib dictionary

Description

crack_closedict ([ resource $dictionary ] ) : bool

crack_closedict() closes the specified dictionary identifier.

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.

Parameters

dictionary

The dictionary to close. If not specified, the current dictionary is closed.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • crack_opendict() - Opens a new CrackLib dictionary


Returns the message from the last obscure check

  • « crack_closedict
  • crack_opendict »
  • PHP Manual
  • Crack Functions
  • Returns the message from the last obscure check

crack_getlastmessage

(PECL crack >= 0.1)

crack_getlastmessage — Returns the message from the last obscure check

Description

crack_getlastmessage ( void ) : string

crack_getlastmessage() returns the message from the last obscure check.

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.

Return Values

The message from the last obscure check or FALSE if there was no obscure checks made so far.

The returned message is one of:

  • it's WAY too short
  • it is too short
  • it does not contain enough DIFFERENT characters
  • it is all whitespace
  • it is too simplistic/systematic
  • it looks like a National Insurance number.
  • it is based on a dictionary word
  • it is based on a (reversed) dictionary word
  • strong password

See Also

  • crack_check() - Performs an obscure check with the given password


Opens a new CrackLib dictionary

  • « crack_getlastmessage
  • CSPRNG »
  • PHP Manual
  • Crack Functions
  • Opens a new CrackLib dictionary

crack_opendict

(PECL crack >= 0.1)

crack_opendict — Opens a new CrackLib dictionary

Description

crack_opendict ( string $dictionary ) : resource

crack_opendict() opens the specified CrackLib dictionary for use with crack_check().

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.

Note:

Only one dictionary may be open at a time.

Parameters

dictionary

The path to the Cracklib dictionary.

Return Values

Returns a dictionary resource identifier on success or FALSE on failure.

See Also

  • crack_check() - Performs an obscure check with the given password
  • crack_closedict() - Closes an open CrackLib dictionary


CSPRNG

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • CSPRNG Functions
    • random_bytes — Generates cryptographically secure pseudo-random bytes
    • random_int — Generates cryptographically secure pseudo-random integers


Introduction

The » cryptographically secure pseudo-random number generator (CSPRNG) API provides an easy and reliable way to generate crypto-strong random integers and bytes for use within cryptographic contexts.

This exists as of PHP 7.0.0 but there is also a » userland implementation for PHP >= 5.2.0.


  • « Resource Types
  • CSPRNG Functions »
  • PHP Manual
  • CSPRNG
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


CSPRNG Functions

Table of Contents

  • random_bytes — Generates cryptographically secure pseudo-random bytes
  • random_int — Generates cryptographically secure pseudo-random integers


Generates cryptographically secure pseudo-random bytes

  • « CSPRNG Functions
  • random_int »
  • PHP Manual
  • CSPRNG Functions
  • Generates cryptographically secure pseudo-random bytes

random_bytes

(PHP 7)

random_bytes — Generates cryptographically secure pseudo-random bytes

Description

random_bytes ( int $length ) : string

Generates an arbitrary length string of cryptographic random bytes that are suitable for cryptographic use, such as when generating salts, keys or initialization vectors.

The sources of randomness used for this function are as follows:

  • On Windows, » CryptGenRandom() will always be used. As of PHP 7.2.0, the » CNG-API will always be used instead.
  • On Linux, the » getrandom(2) syscall will be used if available.
  • On other platforms, /dev/urandom will be used.
  • If none of the aforementioned sources are available, then an Exception will be thrown.

Note: Although this function was added to PHP in PHP 7.0, a » userland implementation is available for PHP 5.2 to 5.6, inclusive.

Parameters

length

The length of the random string that should be returned in bytes.

Return Values

Returns a string containing the requested number of cryptographically secure random bytes.

Errors/Exceptions

  • If an appropriate source of randomness cannot be found, an Exception will be thrown.
  • If invalid parameters are given, a TypeError will be thrown.
  • If an invalid length of bytes is given, an Error will be thrown.

Examples

Example #1 random_bytes() example

<?php
$bytes = random_bytes(5);
var_dump(bin2hex($bytes));
?>

The above example will output something similar to:

string(10) "385e33f741"

See Also

  • random_int() - Generates cryptographically secure pseudo-random integers
  • openssl_random_pseudo_bytes() - Generate a pseudo-random string of bytes
  • bin2hex() - Convert binary data into hexadecimal representation


Generates cryptographically secure pseudo-random integers

  • « random_bytes
  • Hash »
  • PHP Manual
  • CSPRNG Functions
  • Generates cryptographically secure pseudo-random integers

random_int

(PHP 7)

random_int — Generates cryptographically secure pseudo-random integers

Description

random_int ( int $min , int $max ) : int

Generates cryptographic random integers that are suitable for use where unbiased results are critical, such as when shuffling a deck of cards for a poker game.

The sources of randomness used for this function are as follows:

  • On Windows, » CryptGenRandom() will always be used. As of PHP 7.2.0, the » CNG-API will always be used instead.
  • On Linux, the » getrandom(2) syscall will be used if available.
  • On other platforms, /dev/urandom will be used.
  • If none of the aforementioned sources are available, then an Exception will be thrown.

Note: Although this function was added to PHP in PHP 7.0, a » userland implementation is available for PHP 5.2 to 5.6, inclusive.

Parameters

min

The lowest value to be returned, which must be PHP_INT_MIN or higher.

max

The highest value to be returned, which must be less than or equal to PHP_INT_MAX.

Return Values

Returns a cryptographically secure random integer in the range min to max, inclusive.

Errors/Exceptions

  • If an appropriate source of randomness cannot be found, an Exception will be thrown.
  • If invalid parameters are given, a TypeError will be thrown.
  • If max is less than min, an Error will be thrown.

Examples

Example #1 random_int() example

<?php
var_dump(random_int(100, 999));
var_dump(random_int(-1000, 0));
?>

The above example will output something similar to:

int(248)
int(-898)

See Also

  • random_bytes() - Generates cryptographically secure pseudo-random bytes


HASH Message Digest Framework

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • HashContext — The HashContext class
    • HashContext::__construct — Private constructor to disallow direct instantiation
  • Hash Functions
    • 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_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_hmac — Generate a keyed hash value using the HMAC method
    • hash_init — Initialize an incremental hashing context
    • hash_pbkdf2 — Generate a PBKDF2 key derivation of a supplied password
    • 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_update — Pump data into an active hashing context
    • hash — Generate a hash value (message digest)


Introduction

Message Digest (hash) engine. Allows direct or incremental processing of arbitrary length messages using a variety of hashing algorithms.


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

There is no installation needed to use these functions; they are part of the PHP core.


Installation

As of PHP 5.1.2, the Hash extension is bundled and compiled into PHP by default.

It may be explicitly disabled by using the --disable-hash switch to configure. Earlier versions of PHP may incorporate the Hash extension by installing the » PECL module.

As of PHP 7.4.0, the Hash extension is a core PHP extension, so it is always enabled.


  • « Runtime Configuration
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

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

Introduction

Class synopsis

HashContext {
/* Methods */
private __construct ( void )
}

Table of Contents

  • HashContext::__construct — Private constructor to disallow direct instantiation


Private constructor to disallow direct instantiation

  • « HashContext
  • Hash Functions »
  • PHP Manual
  • HashContext
  • Private constructor to disallow direct instantiation

HashContext::__construct

(PHP 7 >= 7.2.0)

HashContext::__construct — Private constructor to disallow direct instantiation

Description

private HashContext::__construct ( void )

Parameters

This function has no parameters.


Hash Functions

Table of Contents

  • 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_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_hmac — Generate a keyed hash value using the HMAC method
  • hash_init — Initialize an incremental hashing context
  • hash_pbkdf2 — Generate a PBKDF2 key derivation of a supplied password
  • 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_update — Pump data into an active hashing context
  • hash — Generate a hash value (message digest)


Return a list of registered hashing algorithms

  • « Hash Functions
  • hash_copy »
  • PHP Manual
  • Hash Functions
  • Return a list of registered hashing algorithms

hash_algos

(PHP 5 >= 5.1.2, PHP 7, PECL hash >= 1.1)

hash_algos — Return a list of registered hashing algorithms

Description

hash_algos ( void ) : array

Return Values

Returns a numerically indexed array containing the list of supported hashing algorithms.

Changelog

Version | Description
7.1.0 | Support for sha512/224, sha512/256, sha3-224, sha3-256, sha3-384 and sha3-512 has been added.
5.6.0 | Support for gost-crypto was added. This implements the GOST hash function using the CryptoPro S-box tables as specified by » RFC 4357, section 11.2.
5.4.0 | Support for joaat, fnv132 and fnv164 was added. Support for Salsa10 and Salsa20 was removed.
5.3.0 | Support for md2, ripemd256, ripemd320, salsa10, salsa20, snefru256 and sha224 was added

Examples

Example #1 hash_algos() example

As of PHP 5.6.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
    [8] => ripemd128
    [9] => ripemd160
    [10] => ripemd256
    [11] => ripemd320
    [12] => whirlpool
    [13] => tiger128,3
    [14] => tiger160,3
    [15] => tiger192,3
    [16] => tiger128,4
    [17] => tiger160,4
    [18] => tiger192,4
    [19] => snefru
    [20] => snefru256
    [21] => gost
    [22] => gost-crypto
    [23] => adler32
    [24] => crc32
    [25] => crc32b
    [26] => fnv132
    [27] => fnv1a32
    [28] => fnv164
    [29] => fnv1a64
    [30] => joaat
    [31] => haval128,3
    [32] => haval160,3
    [33] => haval192,3
    [34] => haval224,3
    [35] => haval256,3
    [36] => haval128,4
    [37] => haval160,4
    [38] => haval192,4
    [39] => haval224,4
    [40] => haval256,4
    [41] => haval128,5
    [42] => haval160,5
    [43] => haval192,5
    [44] => haval224,5
    [45] => haval256,5
)

See Also

  • hash_hmac_algos() - Return a list of registered hashing algorithms suitable for hash_hmac


Copy hashing context

  • « hash_algos
  • hash_equals »
  • PHP Manual
  • Hash Functions
  • Copy hashing context

hash_copy

(PHP 5 >= 5.3.0, PHP 7)

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("md5");
hash_update($context, "data");

/* copy context to be able to continue using it */
$copy_context = hash_copy($context);

echo hash_final($context), "\n";

hash_update($copy_context, "data");
echo hash_final($copy_context), "\n";
?>

The above example will output:

8d777f385d3dfec8815d20f7496026dc
511ae0b1c13f95e5f08f1a0dd3da3d93


Timing attack safe string comparison

  • « hash_copy
  • hash_file »
  • PHP Manual
  • Hash Functions
  • Timing attack safe string comparison

hash_equals

(PHP 5 >= 5.6.0, PHP 7)

hash_equals — Timing attack safe string comparison

Description

hash_equals ( string $known_string , string $user_string ) : bool

Compares two strings using the same time whether they're equal or not.

This function should be used to mitigate timing attacks; for instance, when testing crypt() password hashes.

Parameters

known_string

The string of known length to compare against

user_string

The user-supplied string

Return Values

Returns TRUE when the two strings are equal, FALSE otherwise.

Errors/Exceptions

Emits an E_WARNING message when either of the supplied parameters is not a string.

Examples

Example #1 hash_equals() example

<?php
$expected  = crypt('12345', '$2a$07$usesomesillystringforsalt$');
$correct   = crypt('12345', '$2a$07$usesomesillystringforsalt$');
$incorrect = crypt('apple',  '$2a$07$usesomesillystringforsalt$');

var_dump(hash_equals($expected, $correct));
var_dump(hash_equals($expected, $incorrect));
?>

The above example will output:

bool(true)
bool(false)

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.

Note:

It is important to provide the user-supplied string as the second parameter, rather than the first.


Generate a hash value using the contents of a given file

  • « hash_equals
  • hash_final »
  • PHP Manual
  • Hash Functions
  • Generate a hash value using the contents of a given file

hash_file

(PHP 5 >= 5.1.2, PHP 7, 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 $raw_output = FALSE ] ) : string

Parameters

algo

Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..)

filename

URL describing location of file to be hashed; Supports fopen wrappers.

raw_output

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 raw_output is set to true in which case the raw binary representation of the message digest is returned.

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('md5', 'example.txt');
?>

The above example will output:

5c6ffbdd40d9556b73a21e63c3e0e904

See Also

  • hash() - Generate a hash value (message digest)
  • hash_hmac_file() - Generate a keyed hash value using the HMAC method and the contents of a given file
  • hash_update_file() - Pump data into an active hashing context from a file
  • md5_file() - Calculates the md5 hash of a given file
  • sha1_file() - Calculate the sha1 hash of a file


Finalize an incremental hash and return resulting digest

  • « hash_file
  • hash_hkdf »
  • PHP Manual
  • Hash Functions
  • Finalize an incremental hash and return resulting digest

hash_final

(PHP 5 >= 5.1.2, PHP 7, PECL hash >= 1.1)

hash_final — Finalize an incremental hash and return resulting digest

Description

hash_final ( HashContext $context [, bool $raw_output = FALSE ] ) : string

Parameters

context

Hashing context returned by hash_init().

raw_output

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

Examples

Example #1 hash_final() example

<?php
$ctx = hash_init('sha1');
hash_update($ctx, 'The quick brown fox jumped over the lazy dog.');
echo hash_final($ctx);
?>

The above example will output:

c0854fb9fb03c41cce3802cb0d220529e6eef94e

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


Generate a HKDF key derivation of a supplied key input

  • « hash_final
  • hash_hmac_algos »
  • PHP Manual
  • Hash Functions
  • Generate a HKDF key derivation of a supplied key input

hash_hkdf

(PHP 7 >= 7.1.2)

hash_hkdf — Generate a HKDF key derivation of a supplied key input

Description

hash_hkdf ( string $algo , string $ikm [, int $length = 0 [, string $info = '' [, string $salt = '' ]]] ) : string

Parameters

algo

Name of selected hashing algorithm (i.e. "sha256", "sha512", "haval160,4", etc..) See hash_algos() for a list of supported algorithms.

Note:

Non-cryptographic hash functions are not allowed.

ikm

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); or FALSE on failure.

Errors/Exceptions

An E_WARNING will be raised if ikm 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).

Examples

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

The above example 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.

See Also

  • hash_pbkdf2() - Generate a PBKDF2 key derivation of a supplied password
  • » RFC 5869
  • » userland implementation


Return a list of registered hashing algorithms suitable for hash_hmac

  • « hash_hkdf
  • hash_hmac_file »
  • PHP Manual
  • Hash Functions
  • Return a list of registered hashing algorithms suitable for hash_hmac

hash_hmac_algos

(PHP 7 >= 7.2.0)

hash_hmac_algos — Return a list of registered hashing algorithms suitable for hash_hmac

Description

hash_hmac_algos ( void ) : array

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


Generate a keyed hash value using the HMAC method and the contents of a given file

  • « hash_hmac_algos
  • hash_hmac »
  • PHP Manual
  • Hash Functions
  • Generate a keyed hash value using the HMAC method and the contents of a given file

hash_hmac_file

(PHP 5 >= 5.1.2, PHP 7, 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 , string $key [, bool $raw_output = FALSE ] ) : string

Parameters

algo

Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..) See hash_hmac_algos() for a list of supported algorithms.

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.

raw_output

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 raw_output is set to true in which case the raw binary representation of the message digest is returned. Returns FALSE when algo is unknown or is a non-cryptographic hash function, or if the file filename cannot be read.

Changelog

Version | Description
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('md5', 'example.txt', 'secret');
?>

The above example will output:

7eb2b5c37443418fc77c136dd20e859c

See Also

  • hash_hmac_algos() - Return a list of registered hashing algorithms suitable for hash_hmac
  • hash_hmac() - Generate a keyed hash value using the HMAC method
  • hash_file() - Generate a hash value using the contents of a given file


Generate a keyed hash value using the HMAC method

  • « hash_hmac_file
  • hash_init »
  • PHP Manual
  • Hash Functions
  • Generate a keyed hash value using the HMAC method

hash_hmac

(PHP 5 >= 5.1.2, PHP 7, PECL hash >= 1.1)

hash_hmac — Generate a keyed hash value using the HMAC method

Description

hash_hmac ( string $algo , string $data , string $key [, bool $raw_output = FALSE ] ) : string

Parameters

algo

Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..) See hash_hmac_algos() for a list of supported algorithms.

data

Message to be hashed.

key

Shared secret key used for generating the HMAC variant of the message digest.

raw_output

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 raw_output is set to true in which case the raw binary representation of the message digest is returned. Returns FALSE when algo is unknown or is a non-cryptographic hash function.

Changelog

Version | Description
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('ripemd160', 'The quick brown fox jumped over the lazy dog.', 'secret');
?>

The above example will output:

b8e7ae12510bdfb1812e463a7f086122cf37e4f7

See Also

  • hash() - Generate a hash value (message digest)
  • hash_hmac_algos() - Return a list of registered hashing algorithms suitable for hash_hmac
  • 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


Initialize an incremental hashing context

  • « hash_hmac
  • hash_pbkdf2 »
  • PHP Manual
  • Hash Functions
  • Initialize an incremental hashing context

hash_init

(PHP 5 >= 5.1.2, PHP 7, PECL hash >= 1.1)

hash_init — Initialize an incremental hashing context

Description

hash_init ( string $algo [, int $options = 0 [, string $key = NULL ]] ) : HashContext

Parameters

algo

Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..). For a list of supported algorithms see hash_algos().

options

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 options, a shared secret key to be used with the HMAC hashing method must be supplied in this parameter.

Return Values

Returns a Hashing Context for use with hash_update(), hash_update_stream(), hash_update_file(), and hash_final().

Changelog

Version | Description
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
$ctx = hash_init('md5');
hash_update($ctx, 'The quick brown fox ');
hash_update($ctx, 'jumped over the lazy dog.');
echo hash_final($ctx);
?>

The above example will output:

5c6ffbdd40d9556b73a21e63c3e0e904

See Also

  • hash() - Generate a hash value (message digest)
  • hash_algos() - Return a list of registered hashing algorithms
  • 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_hmac_file() - Generate a keyed hash value using the HMAC method and the contents of a given file


Generate a PBKDF2 key derivation of a supplied password

  • « hash_init
  • hash_update_file »
  • PHP Manual
  • Hash Functions
  • Generate a PBKDF2 key derivation of a supplied password

hash_pbkdf2

(PHP 5 >= 5.5.0, PHP 7)

hash_pbkdf2 — Generate a PBKDF2 key derivation of a supplied password

Description

hash_pbkdf2 ( string $algo , string $password , string $salt , int $iterations [, int $length = 0 [, bool $raw_output = FALSE ]] ) : string

Parameters

algo

Name of selected hashing algorithm (i.e. md5, sha256, haval160,4, etc..) See hash_algos() for a list of supported algorithms.

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 raw_output is TRUE this corresponds to the byte-length of the derived key, if raw_output 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.

raw_output

When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.

Return Values

Returns a string containing the derived key as lowercase hexits unless raw_output is set to TRUE in which case the raw binary representation of the derived key is returned.

Errors/Exceptions

An E_WARNING will be raised 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
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 = 1000;

// Generate a random IV using openssl_random_pseudo_bytes()
// random_bytes() or another suitable source of randomness
$salt = openssl_random_pseudo_bytes(16);

$hash = hash_pbkdf2("sha256", $password, $salt, $iterations, 20);
echo $hash;
?>

The above example will output something similar to:

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

  • crypt() - One-way string hashing
  • password_hash() - Creates a password hash
  • hash() - Generate a hash value (message digest)
  • hash_algos() - Return a list of registered hashing algorithms
  • hash_init() - Initialize an incremental hashing context
  • hash_hmac() - Generate a keyed hash value using the HMAC method
  • hash_hmac_file() - Generate a keyed hash value using the HMAC method and the contents of a given file
  • openssl_pbkdf2() - Generates a PKCS5 v2 PBKDF2 string


Pump data into an active hashing context from a file

  • « hash_pbkdf2
  • hash_update_stream »
  • PHP Manual
  • Hash Functions
  • Pump data into an active hashing context from a file

hash_update_file

(PHP 5 >= 5.1.2, PHP 7, PECL hash >= 1.1)

hash_update_file — Pump data into an active hashing context from a file

Description

hash_update_file ( HashContext $hcontext , string $filename [, resource $scontext = NULL ] ) : bool

Parameters

hcontext

Hashing context returned by hash_init().

filename

URL describing location of file to be hashed; Supports fopen wrappers.

scontext

Stream context as returned by stream_context_create().

Return Values

Returns TRUE on success or FALSE on failure.

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_final() - Finalize an incremental hash and return resulting digest
  • hash() - Generate a hash value (message digest)
  • hash_file() - Generate a hash value using the contents of a given file


Pump data into an active hashing context from an open stream

  • « hash_update_file
  • hash_update »
  • PHP Manual
  • Hash Functions
  • Pump data into an active hashing context from an open stream

hash_update_stream

(PHP 5 >= 5.1.2, PHP 7, 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 $handle [, int $length = -1 ] ) : int

Parameters

context

Hashing context returned by hash_init().

handle

Open file handle as returned by any stream creation function.

length

Maximum number of characters to copy from handle into the hashing context.

Return Values

Actual number of bytes added to the hashing context from handle.

Changelog

Version | Description
7.2.0 | Accept HashContext instead of resource.

Examples

Example #1 hash_update_stream() example

<?php
$fp = tmpfile();
fwrite($fp, 'The quick brown fox jumped over the lazy dog.');
rewind($fp);

$ctx = hash_init('md5');
hash_update_stream($ctx, $fp);
echo hash_final($ctx);
?>

The above example will output:

5c6ffbdd40d9556b73a21e63c3e0e904

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
  • hash() - Generate a hash value (message digest)
  • hash_file() - Generate a hash value using the contents of a given file


Pump data into an active hashing context

  • « hash_update_stream
  • hash »
  • PHP Manual
  • Hash Functions
  • Pump data into an active hashing context

hash_update

(PHP 5 >= 5.1.2, PHP 7, PECL hash >= 1.1)

hash_update — Pump data into an active hashing context

Description

hash_update ( HashContext $context , string $data ) : bool

Parameters

context

Hashing context returned by hash_init().

data

Message to be included in the hash digest.

Return Values

Returns TRUE.

Changelog

Version | Description
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


Generate a hash value (message digest)

  • « hash_update
  • Mcrypt »
  • PHP Manual
  • Hash Functions
  • Generate a hash value (message digest)

hash

(PHP 5 >= 5.1.2, PHP 7, PECL hash >= 1.1)

hash — Generate a hash value (message digest)

Description

hash ( string $algo , string $data [, bool $raw_output = FALSE ] ) : string

Parameters

algo

Name of selected hashing algorithm (e.g. "md5", "sha256", "haval160,4", etc..)

data

Message to be hashed.

raw_output

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 raw_output is set to true in which case the raw binary representation of the message digest is returned.

Changelog

Version | Description
5.4.0 | The tiger algorithm now uses big-endian byte ordering. See also example below.

Examples

Example #1 A hash() example

<?php
echo hash('ripemd160', 'The quick brown fox jumped over the lazy dog.');
?>

The above example will output:

ec457d0a974c48d5685a7efa03d137dc8bbde7e3

Example #2 Calculate pre PHP-5.4 tiger hashes with PHP-5.4 and higher

<?php
function old_tiger($data = "", $width=192, $rounds = 3) {
    return substr(
        implode(
            array_map(
                function ($h) {
                    return str_pad(bin2hex(strrev($h)), 16, "0");
                },
                str_split(hash("tiger192,$rounds", $data, true), 8)
            )
        ),
        0, 48-(192-$width)/4
    );
}
echo hash('tiger192,3', 'a-string'), PHP_EOL;
echo old_tiger('a-string'), PHP_EOL;
?>

Output of the above example in PHP 5.3:

146a7492719b3564094efe7abbd40a7416fd900179d02773
64359b7192746a14740ad4bb7afe4e097327d0790190fd16

Output of the above example in PHP 5.4:

64359b7192746a14740ad4bb7afe4e097327d0790190fd16
146a7492719b3564094efe7abbd40a7416fd900179d02773

See Also

  • 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_init() - Initialize an incremental hashing context
  • md5() - Calculate the md5 hash of a string
  • sha1() - Calculate the sha1 hash of a string


Mcrypt

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Mcrypt ciphers
  • Examples
  • Mcrypt Functions
    • mcrypt_cbc — Encrypts/decrypts data in CBC mode
    • mcrypt_cfb — Encrypts/decrypts data in CFB mode
    • mcrypt_create_iv — Creates an initialization vector (IV) from a random source
    • mcrypt_decrypt — Decrypts crypttext with given parameters
    • mcrypt_ecb — Deprecated: Encrypts/decrypts data in ECB mode
    • 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_mode — Checks whether the encryption of the opened mode works on blocks
    • mcrypt_enc_is_block_algorithm — Checks whether the algorithm of the opened mode is a block algorithm
    • 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_deinit — This function deinitializes an encryption module
    • mcrypt_generic_end — This function terminates encryption
    • mcrypt_generic_init — This function initializes all buffers needed for encryption
    • mcrypt_generic — This function encrypts data
    • 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_mode — Returns if the specified module is a block algorithm or not
    • mcrypt_module_is_block_algorithm — This function checks whether the specified algorithm is a block algorithm
    • 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
    • mcrypt_ofb — Encrypts/decrypts data in OFB mode
    • mdecrypt_generic — Decrypts data


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.


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 » 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/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 | PHP_INI_ALL |
mcrypt.modes_dir | NULL | PHP_INI_ALL |
For further details and definitions of the PHP_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.


  • « Runtime Configuration
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

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 (integer)
MCRYPT_DECRYPT (integer)
MCRYPT_DEV_RANDOM (integer)
MCRYPT_DEV_URANDOM (integer)
MCRYPT_RAND (integer)


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


Examples

Mcrypt can be used to encrypt and decrypt using the above mentioned ciphers. If you linked against libmcrypt-2.2.x, the four important mcrypt commands (mcrypt_cfb(), mcrypt_cbc(), mcrypt_ecb(), and mcrypt_ofb()) can operate in both modes which are named MCRYPT_ENCRYPT and MCRYPT_DECRYPT, respectively.

If you linked against libmcrypt 2.4.x or 2.5.x, these functions are still available, but it is recommended that you use the advanced functions.

Example #1 Encrypt an input value with AES with a 256-bit key under 2.4.x and higher in CBC mode

<?php
    $key = hash('sha256', 'this is a secret key', true);
    $input = "Let us meet at 9 o'clock at the secret place.";

    $td = mcrypt_module_open('rijndael-128', '', 'cbc', '');
    $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_URANDOM);
    mcrypt_generic_init($td, $key, $iv);
    $encrypted_data = mcrypt_generic($td, $input);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
?>
This example will give you the encrypted data as a string in $encrypted_data. For a full example see mcrypt_module_open().


Mcrypt Functions

Table of Contents

  • mcrypt_cbc — Encrypts/decrypts data in CBC mode
  • mcrypt_cfb — Encrypts/decrypts data in CFB mode
  • mcrypt_create_iv — Creates an initialization vector (IV) from a random source
  • mcrypt_decrypt — Decrypts crypttext with given parameters
  • mcrypt_ecb — Deprecated: Encrypts/decrypts data in ECB mode
  • 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_mode — Checks whether the encryption of the opened mode works on blocks
  • mcrypt_enc_is_block_algorithm — Checks whether the algorithm of the opened mode is a block algorithm
  • 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_deinit — This function deinitializes an encryption module
  • mcrypt_generic_end — This function terminates encryption
  • mcrypt_generic_init — This function initializes all buffers needed for encryption
  • mcrypt_generic — This function encrypts data
  • 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_mode — Returns if the specified module is a block algorithm or not
  • mcrypt_module_is_block_algorithm — This function checks whether the specified algorithm is a block algorithm
  • 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
  • mcrypt_ofb — Encrypts/decrypts data in OFB mode
  • mdecrypt_generic — Decrypts data


Encrypts/decrypts data in CBC mode

  • « Mcrypt Functions
  • mcrypt_cfb »
  • PHP Manual
  • Mcrypt Functions
  • Encrypts/decrypts data in CBC mode

mcrypt_cbc

(PHP 4, PHP 5)

mcrypt_cbc — Encrypts/decrypts data in CBC mode

Warning

This function was DEPRECATED in PHP 5.5.0, and REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • mcrypt_decrypt()
  • mcrypt_encrypt()

Description

mcrypt_cbc ( int $cipher , string $key , string $data , int $mode [, string $iv ] ) : string
mcrypt_cbc ( string $cipher , string $key , string $data , int $mode [, string $iv ] ) : string

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.


Encrypts/decrypts data in CFB mode

  • « mcrypt_cbc
  • mcrypt_create_iv »
  • PHP Manual
  • Mcrypt Functions
  • Encrypts/decrypts data in CFB mode

mcrypt_cfb

(PHP 4, PHP 5)

mcrypt_cfb — Encrypts/decrypts data in CFB mode

Warning

This function was DEPRECATED in PHP 5.5.0, and REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • mcrypt_decrypt()
  • mcrypt_encrypt()

Description

mcrypt_cfb ( int $cipher , string $key , string $data , int $mode , string $iv ) : string
mcrypt_cfb ( string $cipher , string $key , string $data , int $mode [, string $iv ] ) : string

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.


Creates an initialization vector (IV) from a random source

  • « mcrypt_cfb
  • mcrypt_decrypt »
  • PHP Manual
  • Mcrypt Functions
  • Creates an initialization vector (IV) from a random source

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.

Changelog

Version | Description
5.6.0 | MCRYPT_DEV_URANDOM is now the default value of source.
5.3.0 | MCRYPT_DEV_RANDOM and MCRYPT_DEV_URANDOM became available on Windows platforms.
5.3.0 | It is no longer required to call srand() first. This is now done automatically.

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() - Generates cryptographically secure pseudo-random bytes


Decrypts crypttext with given parameters

  • « mcrypt_create_iv
  • mcrypt_ecb »
  • PHP Manual
  • Mcrypt Functions
  • Decrypts crypttext with given parameters

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

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.

Changelog

Version | Description
5.6.0 | Invalid key and iv sizes are no longer accepted. mcrypt_decrypt() will now throw a warning and return FALSE if the inputs are invalid. Previously keys and IVs were padded with '\0' bytes to the next valid size.

See Also

  • mcrypt_encrypt() - Encrypts plaintext with given parameters


Deprecated: Encrypts/decrypts data in ECB mode

  • « mcrypt_decrypt
  • mcrypt_enc_get_algorithms_name »
  • PHP Manual
  • Mcrypt Functions
  • Deprecated: Encrypts/decrypts data in ECB mode

mcrypt_ecb

(PHP 4, PHP 5)

mcrypt_ecb — Deprecated: Encrypts/decrypts data in ECB mode

Warning

This function was DEPRECATED in PHP 5.5.0, and REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • mcrypt_decrypt()
  • mcrypt_encrypt()

Description

mcrypt_ecb ( int $cipher , string $key , string $data , int $mode ) : string
mcrypt_ecb ( string $cipher , string $key , string $data , int $mode [, string $iv ] ) : string

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.


Returns the name of the opened algorithm

  • « mcrypt_ecb
  • mcrypt_enc_get_block_size »
  • PHP Manual
  • Mcrypt Functions
  • Returns the name of the opened algorithm

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


Returns the blocksize of the opened algorithm

  • « mcrypt_enc_get_algorithms_name
  • mcrypt_enc_get_iv_size »
  • PHP Manual
  • Mcrypt Functions
  • Returns the blocksize of the opened algorithm

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.


Returns the size of the IV of the opened algorithm

  • « mcrypt_enc_get_block_size
  • mcrypt_enc_get_key_size »
  • PHP Manual
  • Mcrypt Functions
  • Returns the size of the IV of the opened algorithm

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


Returns the maximum supported keysize of the opened mode

  • « mcrypt_enc_get_iv_size
  • mcrypt_enc_get_modes_name »
  • PHP Manual
  • Mcrypt Functions
  • Returns the maximum supported keysize of the opened mode

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


Returns the name of the opened mode

  • « mcrypt_enc_get_key_size
  • mcrypt_enc_get_supported_key_sizes »
  • PHP Manual
  • Mcrypt Functions
  • Returns the name of the opened mode

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


Returns an array with the supported keysizes of the opened algorithm

  • « mcrypt_enc_get_modes_name
  • mcrypt_enc_is_block_algorithm_mode »
  • PHP Manual
  • Mcrypt Functions
  • Returns an array with the supported keysizes of the opened algorithm

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


Checks whether the encryption of the opened mode works on blocks

  • « mcrypt_enc_get_supported_key_sizes
  • mcrypt_enc_is_block_algorithm »
  • PHP Manual
  • Mcrypt Functions
  • Checks whether the encryption of the opened mode works on blocks

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


Checks whether the algorithm of the opened mode is a block algorithm

  • « mcrypt_enc_is_block_algorithm_mode
  • mcrypt_enc_is_block_mode »
  • PHP Manual
  • Mcrypt Functions
  • Checks whether the algorithm of the opened mode is a block algorithm

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


Checks whether the opened mode outputs blocks

  • « mcrypt_enc_is_block_algorithm
  • mcrypt_enc_self_test »
  • PHP Manual
  • Mcrypt Functions
  • Checks whether the opened mode outputs blocks

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


Runs a self test on the opened module

  • « mcrypt_enc_is_block_mode
  • mcrypt_encrypt »
  • PHP Manual
  • Mcrypt Functions
  • Runs a self test on the opened module

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. 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 integer on failure.


Encrypts plaintext with given parameters

  • « mcrypt_enc_self_test
  • mcrypt_generic_deinit »
  • PHP Manual
  • Mcrypt Functions
  • Encrypts plaintext with given parameters

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. Relying on this function is highly discouraged.

Description

mcrypt_encrypt ( string $cipher , string $key , string $data , string $mode [, string $iv ] ) : string

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.

Changelog

Version | Description
5.6.0 | Invalid key and iv sizes are no longer accepted. mcrypt_encrypt() will now throw a warning and return FALSE if the inputs are invalid. Previously keys and IVs were padded with '\0' bytes to the next valid size.

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


This function deinitializes an encryption module

  • « mcrypt_encrypt
  • mcrypt_generic_end »
  • PHP Manual
  • Mcrypt Functions
  • 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. 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


This function terminates encryption

  • « mcrypt_generic_deinit
  • mcrypt_generic_init »
  • PHP Manual
  • Mcrypt Functions
  • This function terminates encryption

mcrypt_generic_end

(PHP 4 >= 4.0.2, PHP 5)

mcrypt_generic_end — This function terminates encryption

Warning

This function was DEPRECATED in PHP 5.3.0, and REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • mcrypt_generic_deinit()

Description

mcrypt_generic_end ( resource $td ) : bool

Warning

mcrypt_generic_deinit() should be used instead of this function, as it can cause crashes when used with mcrypt_module_close() due to multiple buffer frees.

This function terminates encryption specified by the encryption descriptor (td). Actually it clears all buffers, and closes all the modules used. Returns FALSE on error, or TRUE on success.


This function initializes all buffers needed for encryption

  • « mcrypt_generic_end
  • mcrypt_generic »
  • PHP Manual
  • Mcrypt Functions
  • 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. 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


This function encrypts data

  • « mcrypt_generic_init
  • mcrypt_get_block_size »
  • PHP Manual
  • Mcrypt Functions
  • This function encrypts data

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


Gets the block size of the specified cipher

  • « mcrypt_generic
  • mcrypt_get_cipher_name »
  • PHP Manual
  • Mcrypt Functions
  • Gets the block size of the specified cipher

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. Relying on this function is highly discouraged.

Description

mcrypt_get_block_size ( int $cipher ) : int
mcrypt_get_block_size ( string $cipher , string $mode ) : int

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


Gets the name of the specified cipher

  • « mcrypt_get_block_size
  • mcrypt_get_iv_size »
  • PHP Manual
  • Mcrypt Functions
  • Gets the name of the specified cipher

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


Returns the size of the IV belonging to a specific cipher/mode combination

  • « mcrypt_get_cipher_name
  • mcrypt_get_key_size »
  • PHP Manual
  • Mcrypt Functions
  • Returns the size of the IV belonging to a specific cipher/mode combination

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


Gets the key size of the specified cipher

  • « mcrypt_get_iv_size
  • mcrypt_list_algorithms »
  • PHP Manual
  • Mcrypt Functions
  • Gets the key size of the specified cipher

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. Relying on this function is highly discouraged.

Description

mcrypt_get_key_size ( int $cipher ) : int
mcrypt_get_key_size ( string $cipher , string $mode ) : int

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


Gets an array of all supported ciphers

  • « mcrypt_get_key_size
  • mcrypt_list_modes »
  • PHP Manual
  • Mcrypt Functions
  • Gets an array of all supported ciphers

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


Gets an array of all supported modes

  • « mcrypt_list_algorithms
  • mcrypt_module_close »
  • PHP Manual
  • Mcrypt Functions
  • Gets an array of all supported modes

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


Closes the mcrypt module

  • « mcrypt_list_modes
  • mcrypt_module_get_algo_block_size »
  • PHP Manual
  • Mcrypt Functions
  • Closes the mcrypt module

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


Returns the blocksize of the specified algorithm

  • « mcrypt_module_close
  • mcrypt_module_get_algo_key_size »
  • PHP Manual
  • Mcrypt Functions
  • Returns the blocksize of the specified algorithm

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


Returns the maximum supported keysize of the opened mode

  • « mcrypt_module_get_algo_block_size
  • mcrypt_module_get_supported_key_sizes »
  • PHP Manual
  • Mcrypt Functions
  • Returns the maximum supported keysize of the opened mode

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


Returns an array with the supported keysizes of the opened algorithm

  • « mcrypt_module_get_algo_key_size
  • mcrypt_module_is_block_algorithm_mode »
  • PHP Manual
  • Mcrypt Functions
  • Returns an array with the supported keysizes of the opened algorithm

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


Returns if the specified module is a block algorithm or not

  • « mcrypt_module_get_supported_key_sizes
  • mcrypt_module_is_block_algorithm »
  • PHP Manual
  • Mcrypt Functions
  • Returns if the specified module is a block algorithm or not

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


This function checks whether the specified algorithm is a block algorithm

  • « mcrypt_module_is_block_algorithm_mode
  • mcrypt_module_is_block_mode »
  • PHP Manual
  • Mcrypt Functions
  • This function checks whether the specified algorithm is a block 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. 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.


Returns if the specified mode outputs blocks or not

  • « mcrypt_module_is_block_algorithm
  • mcrypt_module_open »
  • PHP Manual
  • Mcrypt Functions
  • Returns if the specified mode outputs blocks or not

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


Opens the module of the algorithm and the mode to be used

  • « mcrypt_module_is_block_mode
  • mcrypt_module_self_test »
  • PHP Manual
  • Mcrypt Functions
  • Opens the module of the algorithm and the mode to be used

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. 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 */
    $key = substr(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


This function runs a self test on the specified module

  • « mcrypt_module_open
  • mcrypt_ofb »
  • PHP Manual
  • Mcrypt Functions
  • This function runs a self test on the specified 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. 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)


Encrypts/decrypts data in OFB mode

  • « mcrypt_module_self_test
  • mdecrypt_generic »
  • PHP Manual
  • Mcrypt Functions
  • Encrypts/decrypts data in OFB mode

mcrypt_ofb

(PHP 4, PHP 5)

mcrypt_ofb — Encrypts/decrypts data in OFB mode

Warning

This function was DEPRECATED in PHP 5.5.0, and REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • mcrypt_decrypt()
  • mcrypt_encrypt()

Description

mcrypt_ofb ( int $cipher , string $key , string $data , int $mode , string $iv ) : string
mcrypt_ofb ( string $cipher , string $key , string $data , int $mode [, string $iv ] ) : string

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.


Decrypts data

  • « mcrypt_ofb
  • Mhash »
  • PHP Manual
  • Mcrypt Functions
  • Decrypts data

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

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


Mhash

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Mhash Functions
    • 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
    • mhash — Computes hash


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.


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
  • MHASH_CRC32
  • MHASH_CRC32B
  • MHASH_GOST
  • MHASH_HAVAL128
  • MHASH_HAVAL160
  • MHASH_HAVAL192
  • MHASH_HAVAL224
  • MHASH_HAVAL256
  • MHASH_MD2
  • MHASH_MD4
  • MHASH_MD5
  • MHASH_RIPEMD128
  • MHASH_RIPEMD256
  • MHASH_RIPEMD320
  • MHASH_SHA1
  • MHASH_SHA192
  • MHASH_SHA224
  • MHASH_SHA256
  • MHASH_SHA384
  • MHASH_SHA512
  • MHASH_SNEFRU128
  • MHASH_SNEFRU256
  • MHASH_TIGER
  • MHASH_TIGER128
  • MHASH_TIGER160
  • MHASH_WHIRLPOOL


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

Table of Contents

  • 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
  • mhash — Computes hash


Gets the highest available hash ID

  • « Mhash Functions
  • mhash_get_block_size »
  • PHP Manual
  • Mhash Functions
  • Gets the highest available hash ID

mhash_count

(PHP 4, PHP 5, PHP 7)

mhash_count — Gets the highest available hash ID

Description

mhash_count ( void ) : int

Gets the highest available hash ID.

Return Values

Returns the highest available hash ID. Hashes are numbered from 0 to this hash ID.

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


Gets the block size of the specified hash

  • « mhash_count
  • mhash_get_hash_name »
  • PHP Manual
  • Mhash Functions
  • Gets the block size of the specified hash

mhash_get_block_size

(PHP 4, PHP 5, PHP 7)

mhash_get_block_size — Gets the block size of the specified hash

Description

mhash_get_block_size ( int $hash ) : int

Gets the size of a block of the specified hash.

Parameters

hash

The hash ID. One of the MHASH_hashname constants.

Return Values

Returns the size in bytes or FALSE, if the hash does not exist.

Examples

Example #1 mhash_get_block_size() Example

<?php

echo mhash_get_block_size(MHASH_MD5); // 16

?>


Gets the name of the specified hash

  • « mhash_get_block_size
  • mhash_keygen_s2k »
  • PHP Manual
  • Mhash Functions
  • Gets the name of the specified hash

mhash_get_hash_name

(PHP 4, PHP 5, PHP 7)

mhash_get_hash_name — Gets the name of the specified hash

Description

mhash_get_hash_name ( int $hash ) : string

Gets the name of the specified hash.

Parameters

hash

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.

Examples

Example #1 mhash_get_hash_name() Example

<?php

echo mhash_get_hash_name(MHASH_MD5); // MD5

?>


Generates a key

  • « mhash_get_hash_name
  • mhash »
  • PHP Manual
  • Mhash Functions
  • Generates a key

mhash_keygen_s2k

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

mhash_keygen_s2k — Generates a key

Description

mhash_keygen_s2k ( int $hash , string $password , string $salt , int $bytes ) : string

Generates a key according to the given hash, 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

hash

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.

bytes

The key length, in bytes.

Return Values

Returns the generated key as a string, or FALSE on error.


Computes hash

  • « mhash_keygen_s2k
  • OpenSSL »
  • PHP Manual
  • Mhash Functions
  • Computes hash

mhash

(PHP 4, PHP 5, PHP 7)

mhash — Computes hash

Description

mhash ( int $hash , string $data [, string $key ] ) : string

mhash() applies a hash function specified by hash to the data.

Parameters

hash

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.


OpenSSL

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
    • Purpose checking flags
    • Padding flags for asymmetric encryption
    • Key types
    • PKCS7 Flags/Constants
    • Signature Algorithms
    • Ciphers
    • Version constants
    • Server Name Indication constants
  • Key/Certificate parameters
  • Certificate Verification
  • OpenSSL Functions
    • openssl_cipher_iv_length — Gets the cipher iv length
    • openssl_csr_export_to_file — Exports a CSR to a file
    • openssl_csr_export — Exports a CSR as a string
    • 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_pbkdf2 — Generates a PKCS5 v2 PBKDF2 string
    • openssl_pkcs12_export_to_file — Exports a PKCS#12 Compatible Certificate Store File
    • openssl_pkcs12_export — Exports a PKCS#12 Compatible Certificate Store File to variable
    • 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_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_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_challenge — Exports the challenge assoicated with a signed public key and challenge
    • openssl_spki_export — Exports a valid PEM formatted public key 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_to_file — Exports a certificate to file
    • openssl_x509_export — Exports a certificate as a string
    • 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 a resource identifier for it


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.


Requirements

In order to use the OpenSSL functions you need to install the » OpenSSL library. PHP 5 requires at least OpenSSL >= 0.9.6. However later PHP 5 versions have some compilation issues and should be used at least with OpenSSL >= 0.9.8 which is also a minimal version for PHP 7.0. Other versions (PHP >= 7.1.0) require OpenSSL >= 1.0.1.

Warning

You are strongly encouraged to use the most recent 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[=DIR] .

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.

As of PHP 5.6.3, 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/openssl 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 configargs of the functions that require a configuration file.
Caution

Ensure that non-privileged users are not allowed to modify openssl.cnf.

Changelog

Version | Description
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, repectively.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

openssl Configure Options
Name | Default | Changeable | Changelog
openssl.cafile | "" | PHP_INI_PERDIR | Available as of PHP 5.6.0.
openssl.capath | "" | PHP_INI_PERDIR | Available as of PHP 5.6.0.
For further details and definitions of the PHP_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.

See also the SSL stream context options.


Resource Types

There are 3 resource types defined in the OpenSSL module. The first one is a pkey (public or private key) identifier, the second one is a X509 certificate identifier and the third one is a CSR (certificate signing request) identifier.


Predefined Constants

Table of Contents

  • Purpose checking flags
  • Padding flags for asymmetric encryption
  • Key types
  • PKCS7 Flags/Constants
  • Signature Algorithms
  • Ciphers
  • Version constants
  • Server Name Indication 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 (integer)
X509_PURPOSE_SSL_SERVER (integer)
X509_PURPOSE_NS_SSL_SERVER (integer)
X509_PURPOSE_SMIME_SIGN (integer)
X509_PURPOSE_SMIME_ENCRYPT (integer)
X509_PURPOSE_CRL_SIGN (integer)
X509_PURPOSE_ANY (integer)


Padding flags for asymmetric encryption

OPENSSL_PKCS1_PADDING (integer)
OPENSSL_SSLV23_PADDING (integer)
OPENSSL_NO_PADDING (integer)
OPENSSL_PKCS1_OAEP_PADDING (integer)


Key types

OPENSSL_KEYTYPE_RSA (integer)
OPENSSL_KEYTYPE_DSA (integer)
OPENSSL_KEYTYPE_DH (integer)
OPENSSL_KEYTYPE_EC (integer)
This constant is only available when PHP is compiled with OpenSSL 0.9.8+. Added in PHP 5.2.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 | 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 | 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 | 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 extracerts parameter of openssl_pkcs7_verify() are used. The supplied certificates can still be used as untrusted CAs however.
PKCS7_NOVERIFY | Do not verify the signers certificate of a signed message.
PKCS7_NOCHAIN | Do not chain verification of signers certificates: that is don't use the certificates in the signed message as untrusted CAs.
PKCS7_NOCERTS | 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 extracerts to openssl_pkcs7_verify() for example).
PKCS7_NOATTR | 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 | 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 | Don't try and verify the signatures on a message


Signature Algorithms

OPENSSL_ALGO_DSS1 (integer)
OPENSSL_ALGO_SHA1 (integer)
Used as default algorithm by openssl_sign() and openssl_verify().
OPENSSL_ALGO_SHA224 (integer)
Added in PHP 5.4.8.
OPENSSL_ALGO_SHA256 (integer)
Added in PHP 5.4.8.
OPENSSL_ALGO_SHA384 (integer)
Added in PHP 5.4.8.
OPENSSL_ALGO_SHA512 (integer)
Added in PHP 5.4.8.
OPENSSL_ALGO_RMD160 (integer)
Added in PHP 5.4.8.
OPENSSL_ALGO_MD5 (integer)
OPENSSL_ALGO_MD4 (integer)
OPENSSL_ALGO_MD2 (integer)
As of PHP 5.2.13 and PHP 5.3.2, 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_CIPHER_RC2_40 (integer)
OPENSSL_CIPHER_RC2_128 (integer)
OPENSSL_CIPHER_RC2_64 (integer)
OPENSSL_CIPHER_DES (integer)
OPENSSL_CIPHER_3DES (integer)
OPENSSL_CIPHER_AES_128_CBC (integer)
Added in PHP 5.4.0.
OPENSSL_CIPHER_AES_192_CBC (integer)
Added in PHP 5.4.0.
OPENSSL_CIPHER_AES_256_CBC (integer)
Added in PHP 5.4.0.


Version constants

OPENSSL_VERSION_TEXT (string)
Added in PHP 5.2.0.
OPENSSL_VERSION_NUMBER (integer)
Added in PHP 5.2.0.


Server Name Indication constants

OPENSSL_TLSEXT_SERVER_NAME (string)
Whether SNI support is available or not.

Note:

This constant was added in 5.3.2 and requires PHP to be built with OpenSSL 0.9.8j or greater.


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 X.509 resource 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. A CSR resource 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. A key resource returned from openssl_get_publickey() or openssl_get_privatekey()
    2. For public keys only: an X.509 resource
    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 cainfo 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

Table of Contents

  • openssl_cipher_iv_length — Gets the cipher iv length
  • openssl_csr_export_to_file — Exports a CSR to a file
  • openssl_csr_export — Exports a CSR as a string
  • 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_pbkdf2 — Generates a PKCS5 v2 PBKDF2 string
  • openssl_pkcs12_export_to_file — Exports a PKCS#12 Compatible Certificate Store File
  • openssl_pkcs12_export — Exports a PKCS#12 Compatible Certificate Store File to variable
  • 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_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_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_challenge — Exports the challenge assoicated with a signed public key and challenge
  • openssl_spki_export — Exports a valid PEM formatted public key 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_to_file — Exports a certificate to file
  • openssl_x509_export — Exports a certificate as a string
  • 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 a resource identifier for it


Gets the cipher iv length

  • « OpenSSL Functions
  • openssl_csr_export_to_file »
  • PHP Manual
  • OpenSSL Functions
  • Gets the cipher iv length

openssl_cipher_iv_length

(PHP 5 >= 5.3.3, PHP 7)

openssl_cipher_iv_length — Gets the cipher iv length

Description

openssl_cipher_iv_length ( string $method ) : int

Gets the cipher initialization vector (iv) length.

Parameters

method

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


Exports a CSR to a file

  • « openssl_cipher_iv_length
  • openssl_csr_export »
  • PHP Manual
  • OpenSSL Functions
  • Exports a CSR to a file

openssl_csr_export_to_file

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

openssl_csr_export_to_file — Exports a CSR to a file

Description

openssl_csr_export_to_file ( mixed $csr , string $outfilename [, bool $notext = 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 outfilename.

Parameters

csr

See CSR parameters for a list of valid values.

outfilename

Path to the output file.

notext

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.

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


Exports a CSR as a string

  • « openssl_csr_export_to_file
  • openssl_csr_get_public_key »
  • PHP Manual
  • OpenSSL Functions
  • Exports a CSR as a string

openssl_csr_export

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

openssl_csr_export — Exports a CSR as a string

Description

openssl_csr_export ( mixed $csr , string &$out [, bool $notext = TRUE ] ) : bool

openssl_csr_export() takes the Certificate Signing Request represented by csr and stores it in PEM format in out, which is passed by reference.

Parameters

csr

See CSR parameters for a list of valid values.

out

on success, this string will contain the PEM encoded CSR

notext

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.

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


Returns the public key of a CSR

  • « openssl_csr_export
  • openssl_csr_get_subject »
  • PHP Manual
  • OpenSSL Functions
  • Returns the public key of a CSR

openssl_csr_get_public_key

(PHP 5 >= 5.2.0, PHP 7)

openssl_csr_get_public_key — Returns the public key of a CSR

Description

openssl_csr_get_public_key ( mixed $csr [, bool $use_shortnames = TRUE ] ) : resource

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.

use_shortnames
Warning

This parameter is ignored

Return Values

Returns a positive key resource identifier on success, or FALSE on error.

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


Returns the subject of a CSR

  • « openssl_csr_get_public_key
  • openssl_csr_new »
  • PHP Manual
  • OpenSSL Functions
  • Returns the subject of a CSR

openssl_csr_get_subject

(PHP 5 >= 5.2.0, PHP 7)

openssl_csr_get_subject — Returns the subject of a CSR

Description

openssl_csr_get_subject ( mixed $csr [, bool $use_shortnames = TRUE ] ) : array

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.

use_shortnames

shortnames controls how the data is indexed in the array - if shortnames 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 TRUE on success or FALSE on failure.

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


Generates a CSR

  • « openssl_csr_get_subject
  • openssl_csr_sign »
  • PHP Manual
  • OpenSSL Functions
  • Generates a CSR

openssl_csr_new

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

openssl_csr_new — Generates a CSR

Description

openssl_csr_new ( array $dn , resource &$privkey [, array $configargs [, array $extraattribs ]] ) : mixed

openssl_csr_new() generates a new CSR (Certificate Signing Request) based on the information provided by dn.

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

dn

The Distinguished Name or subject fields to be used in the certificate.

privkey

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

configargs

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 of configargs. 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 configargs behave as their equivalents in the openssl.conf, as listed in the table below.

Configuration overrides
configargs 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 | integer | default_bits | Specifies how many bits should be used to generate a private key
private_key_type | integer | 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 | boolean | encrypt_key | Should an exported key (with passphrase) be encrypted?
encrypt_key_cipher | integer | 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.

extraattribs

extraattribs is used to specify additional configuration options for the CSR. Both dn and extraattribs are associative arrays whose keys are converted to OIDs and applied to the relevant part of the request.

Return Values

Returns the CSR or FALSE on failure.

Changelog

Version | Description
7.1.0 | configargs 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


Sign a CSR with another certificate (or itself) and generate a certificate

  • « openssl_csr_new
  • openssl_decrypt »
  • PHP Manual
  • OpenSSL Functions
  • Sign a CSR with another certificate (or itself) and generate a certificate

openssl_csr_sign

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

openssl_csr_sign — Sign a CSR with another certificate (or itself) and generate a certificate

Description

openssl_csr_sign ( mixed $csr , mixed $cacert , mixed $priv_key , int $days [, array $configargs [, int $serial = 0 ]] ) : resource

openssl_csr_sign() generates an x509 certificate resource 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().

cacert

The generated certificate will be signed by cacert. If cacert is NULL, the generated certificate will be a self-signed certificate.

priv_key

priv_key is the private key that corresponds to cacert.

days

days specifies the length of time for which the generated certificate will be valid, in days.

configargs

You can finetune the CSR signing by configargs. See openssl_csr_new() for more information about configargs.

serial

An optional the serial number of issued certificate. If not specified it will default to 0.

Return Values

Returns an x509 certificate resource on success, FALSE on failure.

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


Decrypts data

  • « openssl_csr_sign
  • openssl_dh_compute_key »
  • PHP Manual
  • OpenSSL Functions
  • Decrypts data

openssl_decrypt

(PHP 5 >= 5.3.0, PHP 7)

openssl_decrypt — Decrypts data

Description

openssl_decrypt ( string $data , string $method , string $key [, int $options = 0 [, string $iv = "" [, string $tag = "" [, string $aad = "" ]]]] ) : string

Takes a raw or base64 encoded string and decrypts it using a given method and key.

Parameters

data

The encrypted message to be decrypted.

method

The cipher method. For a list of available cipher methods, use openssl_get_cipher_methods().

key

The key.

options

options can be one of OPENSSL_RAW_DATA, OPENSSL_ZERO_PADDING.

iv

A non-NULL Initialization Vector.

tag

The authentication tag in AEAD cipher mode. If it is incorrect, the authentication fails and the function returns FALSE.

aad

Additional authentication 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 method 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 and aad parameters were added.
5.4.0 | The raw_output was changed to options.
5.3.3 | The iv parameter was added.

See Also

  • openssl_encrypt() - Encrypts data


Computes shared secret for public value of remote DH public key and local DH key

  • « openssl_decrypt
  • openssl_digest »
  • PHP Manual
  • OpenSSL Functions
  • Computes shared secret for public value of remote DH public key and local DH key

openssl_dh_compute_key

(PHP 5 >= 5.3.0, PHP 7)

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 $pub_key , resource $dh_key ) : string

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.

Parameters

pub_key

DH Public key of the remote party.

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

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


Computes a digest

  • « openssl_dh_compute_key
  • openssl_encrypt »
  • PHP Manual
  • OpenSSL Functions
  • Computes a digest

openssl_digest

(PHP 5 >= 5.3.0, PHP 7)

openssl_digest — Computes a digest

Description

openssl_digest ( string $data , string $method [, bool $raw_output = FALSE ] ) : string

Computes a digest hash value for the given data using a given method, and returns a raw or binhex encoded string.

Warning

This function is currently not documented; only its argument list is available.

Parameters

data

The data.

method

The digest method to use, e.g. "sha256", see openssl_get_md_methods() for a list of available digest methods.

raw_output

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 method parameter.

See Also

  • openssl_get_md_methods() - Gets available digest methods


Encrypts data

  • « openssl_digest
  • openssl_error_string »
  • PHP Manual
  • OpenSSL Functions
  • Encrypts data

openssl_encrypt

(PHP 5 >= 5.3.0, PHP 7)

openssl_encrypt — Encrypts data

Description

openssl_encrypt ( string $data , string $method , string $key [, int $options = 0 [, string $iv = "" [, string &$tag = NULL [, string $aad = "" [, int $tag_length = 16 ]]]]] ) : string

Encrypts given data with given method and key, returns a raw or base64 encoded string

Parameters

data

The plaintext message data to be encrypted.

method

The cipher method. For a list of available cipher methods, use openssl_get_cipher_methods().

key

The key.

options

options is a bitwise disjunction of the flags OPENSSL_RAW_DATA and OPENSSL_ZERO_PADDING.

iv

A non-NULL Initialization Vector.

tag

The authentication tag passed by reference when using AEAD cipher mode (GCM or CCM).

aad

Additional authentication 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 method 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.
5.4.0 | The raw_output was changed to options.
5.3.3 | The iv parameter was 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 for PHP 5.6+

<?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))//PHP 5.6+ timing attack safe comparison
{
    echo $original_plaintext."\n";
}
?>

See Also

  • openssl_decrypt() - Decrypts data


Return openSSL error message

  • « openssl_encrypt
  • openssl_free_key »
  • PHP Manual
  • OpenSSL Functions
  • Return openSSL error message

openssl_error_string

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

openssl_error_string — Return openSSL error message

Description

openssl_error_string ( void ) : string

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.

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


Free key resource

  • « openssl_error_string
  • openssl_get_cert_locations »
  • PHP Manual
  • OpenSSL Functions
  • Free key resource

openssl_free_key

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

openssl_free_key — Free key resource

Description

openssl_free_key ( resource $key_identifier ) : void

openssl_free_key() frees the key associated with the specified key_identifier from memory.

Parameters

key_identifier

Return Values

No value is returned.


Retrieve the available certificate locations

  • « openssl_free_key
  • openssl_get_cipher_methods »
  • PHP Manual
  • OpenSSL Functions
  • Retrieve the available certificate locations

openssl_get_cert_locations

(PHP 5 >= 5.6.0, PHP 7)

openssl_get_cert_locations — Retrieve the available certificate locations

Description

openssl_get_cert_locations ( void ) : 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) ""
}


Gets available cipher methods

  • « openssl_get_cert_locations
  • openssl_get_curve_names »
  • PHP Manual
  • OpenSSL Functions
  • Gets available cipher methods

openssl_get_cipher_methods

(PHP 5 >= 5.3.0, PHP 7)

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.

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-CFB
    [2] => AES-128-CFB1
    [3] => AES-128-CFB8
    [5] => AES-128-OFB
    [6] => AES-192-CBC
    [7] => AES-192-CFB
    [8] => AES-192-CFB1
    [9] => AES-192-CFB8
    [11] => AES-192-OFB
    [12] => AES-256-CBC
    [13] => AES-256-CFB
    [14] => AES-256-CFB1
    [15] => AES-256-CFB8
    [17] => AES-256-OFB
    [18] => BF-CBC
    [19] => BF-CFB
    [21] => BF-OFB
    [22] => CAST5-CBC
    [23] => CAST5-CFB
    [25] => CAST5-OFB
    [41] => IDEA-CBC
    [42] => IDEA-CFB
    [44] => IDEA-OFB
    [53] => aes-128-cbc
    [54] => aes-128-cfb
    [55] => aes-128-cfb1
    [56] => aes-128-cfb8
    [58] => aes-128-ofb
    [59] => aes-192-cbc
    [60] => aes-192-cfb
    [61] => aes-192-cfb1
    [62] => aes-192-cfb8
    [64] => aes-192-ofb
    [65] => aes-256-cbc
    [66] => aes-256-cfb
    [67] => aes-256-cfb1
    [68] => aes-256-cfb8
    [70] => aes-256-ofb
    [71] => bf-cbc
    [72] => bf-cfb
    [74] => bf-ofb
    [75] => cast5-cbc
    [76] => cast5-cfb
    [78] => cast5-ofb
    [94] => idea-cbc
    [95] => idea-cfb
    [97] => idea-ofb
)
Array
(
    [18] => AES128
    [19] => AES192
    [20] => AES256
    [21] => BF
    [26] => CAST
    [27] => CAST-cbc
    [50] => IDEA
    [82] => aes128
    [83] => aes192
    [84] => aes256
    [85] => bf
    [90] => blowfish
    [91] => cast
    [92] => cast-cbc
    [115] => idea
)

See Also

  • openssl_get_md_methods() - Gets available digest methods


Gets list of available curve names for ECC

  • « openssl_get_cipher_methods
  • openssl_get_md_methods »
  • PHP Manual
  • OpenSSL Functions
  • Gets list of available curve names for ECC

openssl_get_curve_names

(PHP 7 >= 7.1.0)

openssl_get_curve_names — Gets list of available curve names for ECC

Description

openssl_get_curve_names ( void ) : array

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.

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
)


Gets available digest methods

  • « openssl_get_curve_names
  • openssl_get_privatekey »
  • PHP Manual
  • OpenSSL Functions
  • Gets available digest methods

openssl_get_md_methods

(PHP 5 >= 5.3.0, PHP 7)

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


Alias of openssl_pkey_get_private

  • « openssl_get_md_methods
  • openssl_get_publickey »
  • PHP Manual
  • OpenSSL Functions
  • Alias of openssl_pkey_get_private

openssl_get_privatekey

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

openssl_get_privatekey — Alias of openssl_pkey_get_private()

Description

This function is an alias of: openssl_pkey_get_private().


Alias of openssl_pkey_get_public

  • « openssl_get_privatekey
  • openssl_open »
  • PHP Manual
  • OpenSSL Functions
  • Alias of openssl_pkey_get_public

openssl_get_publickey

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

openssl_get_publickey — Alias of openssl_pkey_get_public()

Description

This function is an alias of: openssl_pkey_get_public().


Open sealed data

  • « openssl_get_publickey
  • openssl_pbkdf2 »
  • PHP Manual
  • OpenSSL Functions
  • Open sealed data

openssl_open

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

openssl_open — Open sealed data

Description

openssl_open ( string $sealed_data , string &$open_data , string $env_key , mixed $priv_key_id [, string $method = "RC4" [, string $iv ]] ) : bool

openssl_open() opens (decrypts) sealed_data using the private key associated with the key identifier priv_key_id and the envelope key env_key, and fills open_data with the decrypted data. The envelope key is generated when the data are sealed and can only be used by one specific private key. See openssl_seal() for more information.

Parameters

sealed_data

open_data

If the call is successful the opened data is returned in this parameter.

env_key

priv_key_id

method

The cipher method.

iv

The initialization vector.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.0.0 | The iv has been added.
5.3.0 | The method has been added.

Examples

Example #1 openssl_open() example

<?php
// $sealed and $env_key are assumed to contain the sealed data
// and our envelope key, both given to us by the sealer.

// fetch private key from file and ready it
$fp = fopen("/src/openssl-0.9.6/demos/sign/key.pem", "r");
$priv_key = fread($fp, 8192);
fclose($fp);
$pkeyid = openssl_get_privatekey($priv_key);

// decrypt the data and store it in $open
if (openssl_open($sealed, $open, $env_key, $pkeyid)) {
    echo "here is the opened data: ", $open;
} else {
    echo "failed to open data";
}

// free the private key from memory
openssl_free_key($pkeyid);
?>

See Also

  • openssl_seal() - Seal (encrypt) data


Generates a PKCS5 v2 PBKDF2 string

  • « openssl_open
  • openssl_pkcs12_export_to_file »
  • PHP Manual
  • OpenSSL Functions
  • Generates a PKCS5 v2 PBKDF2 string

openssl_pbkdf2

(PHP 5 >= 5.5.0, PHP 7)

openssl_pbkdf2 — Generates a PKCS5 v2 PBKDF2 string

Description

openssl_pbkdf2 ( string $password , string $salt , int $key_length , int $iterations [, string $digest_algorithm = "sha1" ] ) : string

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 64 bits (8 bytes).

key_length

Length of desired output key.

iterations

The number of iterations desired. » NIST recommends at least 10,000.

digest_algorithm

Optional hash or digest algorithm from openssl_get_md_methods(). Defaults to SHA-1.

Return Values

Returns raw binary string or FALSE on failure.

Examples

Example #1 openssl_pbkdf2() example

<?php
$password = 'yOuR-pAs5w0rd-hERe';
$salt = openssl_random_pseudo_bytes(12);
$keyLength = 40;
$iterations = 10000;
$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


Exports a PKCS#12 Compatible Certificate Store File

  • « openssl_pbkdf2
  • openssl_pkcs12_export »
  • PHP Manual
  • OpenSSL Functions
  • Exports a PKCS#12 Compatible Certificate Store File

openssl_pkcs12_export_to_file

(PHP 5 >= 5.2.2, PHP 7)

openssl_pkcs12_export_to_file — Exports a PKCS#12 Compatible Certificate Store File

Description

openssl_pkcs12_export_to_file ( mixed $x509 , string $filename , mixed $priv_key , string $pass [, array $args ] ) : bool

openssl_pkcs12_export_to_file() stores x509 into a file named by filename in a PKCS#12 file format.

Parameters

x509

See Key/Certificate parameters for a list of valid values.

filename

Path to the output file.

priv_key

Private key component of PKCS#12 file. See Public/Private Key parameters for a list of valid values.

pass

Encryption password for unlocking the PKCS#12 file.

args

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.
"friendlyname" | string to be used for the supplied certificate and key

Return Values

Returns TRUE on success or FALSE on failure.


Exports a PKCS#12 Compatible Certificate Store File to variable

  • « openssl_pkcs12_export_to_file
  • openssl_pkcs12_read »
  • PHP Manual
  • OpenSSL Functions
  • Exports a PKCS#12 Compatible Certificate Store File to variable

openssl_pkcs12_export

(PHP 5 >= 5.2.2, PHP 7)

openssl_pkcs12_export — Exports a PKCS#12 Compatible Certificate Store File to variable

Description

openssl_pkcs12_export ( mixed $x509 , string &$out , mixed $priv_key , string $pass [, array $args ] ) : bool

openssl_pkcs12_export() stores x509 into a string named by out in a PKCS#12 file format.

Parameters

x509

See Key/Certificate parameters for a list of valid values.

out

On success, this will hold the PKCS#12.

priv_key

Private key component of PKCS#12 file. See Public/Private Key parameters for a list of valid values.

pass

Encryption password for unlocking the PKCS#12 file.

args

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.
"friendlyname" | string to be used for the supplied certificate and key

Return Values

Returns TRUE on success or FALSE on failure.


Parse a PKCS#12 Certificate Store into an array

  • « openssl_pkcs12_export
  • openssl_pkcs7_decrypt »
  • PHP Manual
  • OpenSSL Functions
  • Parse a PKCS#12 Certificate Store into an array

openssl_pkcs12_read

(PHP 5 >= 5.2.2, PHP 7)

openssl_pkcs12_read — Parse a PKCS#12 Certificate Store into an array

Description

openssl_pkcs12_read ( string $pkcs12 , array &$certs , string $pass ) : bool

openssl_pkcs12_read() parses the PKCS#12 certificate store supplied by pkcs12 into a array named certs.

Parameters

pkcs12

The certificate store contents, not its file name.

certs

On success, this will hold the Certificate Store Data.

pass

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


Decrypts an S/MIME encrypted message

  • « openssl_pkcs12_read
  • openssl_pkcs7_encrypt »
  • PHP Manual
  • OpenSSL Functions
  • Decrypts an S/MIME encrypted message

openssl_pkcs7_decrypt

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

openssl_pkcs7_decrypt — Decrypts an S/MIME encrypted message

Description

openssl_pkcs7_decrypt ( string $infilename , string $outfilename , mixed $recipcert [, mixed $recipkey ] ) : bool

Decrypts the S/MIME encrypted message contained in the file specified by infilename using the certificate and its associated private key specified by recipcert and recipkey.

Parameters

infilename

outfilename

The decrypted message is written to the file specified by outfilename.

recipcert

recipkey

Return Values

Returns TRUE on success or FALSE on failure.

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


Encrypt an S/MIME message

  • « openssl_pkcs7_decrypt
  • openssl_pkcs7_read »
  • PHP Manual
  • OpenSSL Functions
  • Encrypt an S/MIME message

openssl_pkcs7_encrypt

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

openssl_pkcs7_encrypt — Encrypt an S/MIME message

Description

openssl_pkcs7_encrypt ( string $infile , string $outfile , mixed $recipcerts , array $headers [, int $flags = 0 [, int $cipherid = OPENSSL_CIPHER_RC2_40 ]] ) : bool

openssl_pkcs7_encrypt() takes the contents of the file named infile and encrypts them using an RC2 40-bit cipher so that they can only be read by the intended recipients specified by recipcerts.

Parameters

infile

outfile

recipcerts

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.

cipherid

One of cipher constants.

Return Values

Returns TRUE on success or FALSE on failure.

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


Export the PKCS7 file to an array of PEM certificates

  • « openssl_pkcs7_encrypt
  • openssl_pkcs7_sign »
  • PHP Manual
  • OpenSSL Functions
  • Export the PKCS7 file to an array of PEM certificates

openssl_pkcs7_read

(PHP 7 >= 7.2.0)

openssl_pkcs7_read — Export the PKCS7 file to an array of PEM certificates

Description

openssl_pkcs7_read ( string $infilename , array &$certs ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

infilename

certs

Return Values

Returns TRUE on success or FALSE on failure.


Sign an S/MIME message

  • « openssl_pkcs7_read
  • openssl_pkcs7_verify »
  • PHP Manual
  • OpenSSL Functions
  • Sign an S/MIME message

openssl_pkcs7_sign

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

openssl_pkcs7_sign — Sign an S/MIME message

Description

openssl_pkcs7_sign ( string $infilename , string $outfilename , mixed $signcert , mixed $privkey , array $headers [, int $flags = PKCS7_DETACHED [, string $extracerts ]] ) : bool

openssl_pkcs7_sign() takes the contents of the file named infilename and signs them using the certificate and its matching private key specified by signcert and privkey parameters.

Parameters

infilename

The input file you are intending to digitally sign.

outfilename

The file which the digital signature will be written to.

signcert

The X.509 certificate used to digitally sign infilename. See Key/Certificate parameters for a list of valid values.

privkey

privkey is the private key corresponding to signcert. 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.

extracerts

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

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


Verifies the signature of an S/MIME signed message

  • « openssl_pkcs7_sign
  • openssl_pkey_export_to_file »
  • PHP Manual
  • OpenSSL Functions
  • Verifies the signature of an S/MIME signed message

openssl_pkcs7_verify

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

openssl_pkcs7_verify — Verifies the signature of an S/MIME signed message

Description

openssl_pkcs7_verify ( string $filename , int $flags [, string $outfilename [, array $cainfo [, string $extracerts [, string $content [, string $p7bfilename ]]]]] ) : mixed

openssl_pkcs7_verify() reads the S/MIME message contained in the given file and examines the digital signature.

Parameters

filename

Path to the message.

flags

flags can be used to affect how the signature is verified - see PKCS7 constants for more information.

outfilename

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

cainfo

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

extracerts

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

p7bfilename

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
7.2.0 | The p7bfilename parameter was added.
5.1.0 | The content parameter was added.

Notes

Note: As specified in RFC 2045, lines may not be longer than 76 characters in the filename parameter.


Gets an exportable representation of a key into a file

  • « openssl_pkcs7_verify
  • openssl_pkey_export »
  • PHP Manual
  • OpenSSL Functions
  • Gets an exportable representation of a key into a file

openssl_pkey_export_to_file

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

openssl_pkey_export_to_file — Gets an exportable representation of a key into a file

Description

openssl_pkey_export_to_file ( mixed $key , string $outfilename [, string $passphrase [, array $configargs ]] ) : bool

openssl_pkey_export_to_file() saves an ascii-armoured (PEM encoded) rendition of key into the file named by outfilename.

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

outfilename

Path to the output file.

passphrase

The key can be optionally protected by a passphrase.

configargs

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

Return Values

Returns TRUE on success or FALSE on failure.


Gets an exportable representation of a key into a string

  • « openssl_pkey_export_to_file
  • openssl_pkey_free »
  • PHP Manual
  • OpenSSL Functions
  • Gets an exportable representation of a key into a string

openssl_pkey_export

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

openssl_pkey_export — Gets an exportable representation of a key into a string

Description

openssl_pkey_export ( mixed $key , string &$out [, string $passphrase [, array $configargs ]] ) : bool

openssl_pkey_export() exports key as a PEM encoded string and stores it into out (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

out

passphrase

The key is optionally protected by passphrase.

configargs

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

Return Values

Returns TRUE on success or FALSE on failure.


Frees a private key

  • « openssl_pkey_export
  • openssl_pkey_get_details »
  • PHP Manual
  • OpenSSL Functions
  • Frees a private key

openssl_pkey_free

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

openssl_pkey_free — Frees a private key

Description

openssl_pkey_free ( resource $key ) : void

This function frees a private key created by openssl_pkey_new().

Parameters

key

Resource holding the key.

Return Values

No value is returned.


Returns an array with the key details

  • « openssl_pkey_free
  • openssl_pkey_get_private »
  • PHP Manual
  • OpenSSL Functions
  • Returns an array with the key details

openssl_pkey_get_details

(PHP 5 >= 5.2.0, PHP 7)

openssl_pkey_get_details — Returns an array with the key details

Description

openssl_pkey_get_details ( resource $key ) : array

This function returns the key details (bits, key, type).

Parameters

key

Resource holding the key.

Return Values

Returns an array with the key details in success or FALSE in 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 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_EC, an additional array key named "ec", containing the key data is returned.
    Key | Description
    "curve_name" | name of curve, see openssl_get_curve_names()
    "curve_oid" | ASN1 Object identifier (OID) for EC curve.
    "x" | x coordinate (public)
    "y" | y coordinate (public)
    "d" | private key


Get a private key

  • « openssl_pkey_get_details
  • openssl_pkey_get_public »
  • PHP Manual
  • OpenSSL Functions
  • Get a private key

openssl_pkey_get_private

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

openssl_pkey_get_private — Get a private key

Description

openssl_pkey_get_private ( mixed $key [, string $passphrase = "" ] ) : resource

openssl_pkey_get_private() parses key and prepares it for use by other functions.

Parameters

key

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 a positive key resource identifier on success, or FALSE on error.


Extract public key from certificate and prepare it for use

  • « openssl_pkey_get_private
  • openssl_pkey_new »
  • PHP Manual
  • OpenSSL Functions
  • Extract public key from certificate and prepare it for use

openssl_pkey_get_public

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

openssl_pkey_get_public — Extract public key from certificate and prepare it for use

Description

openssl_pkey_get_public ( mixed $certificate ) : resource

openssl_pkey_get_public() extracts the public key from certificate and prepares it for use by other functions.

Parameters

certificate

certificate can be one of the following:

  1. an X.509 certificate resource
  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 a positive key resource identifier on success, or FALSE on error.


Generates a new private key

  • « openssl_pkey_get_public
  • openssl_private_decrypt »
  • PHP Manual
  • OpenSSL Functions
  • Generates a new private key

openssl_pkey_new

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

openssl_pkey_new — Generates a new private key

Description

openssl_pkey_new ([ array $configargs ] ) : resource

openssl_pkey_new() generates a new private and public key pair. The public component of the key can be obtained using openssl_pkey_get_public().

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

configargs

You can finetune the key generation (such as specifying the number of bits) using configargs. See openssl_csr_new() for more information about configargs.

Return Values

Returns a resource identifier for the pkey on success, or FALSE on error.

Changelog

Version | Description
7.1.0 | The curve_name configarg was added to make it possible to create EC keys.


Decrypts data with private key

  • « openssl_pkey_new
  • openssl_private_encrypt »
  • PHP Manual
  • OpenSSL Functions
  • Decrypts data with private key

openssl_private_decrypt

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

openssl_private_decrypt — Decrypts data with private key

Description

openssl_private_decrypt ( string $data , string &$decrypted , mixed $key [, int $padding = OPENSSL_PKCS1_PADDING ] ) : bool

openssl_private_decrypt() decrypts data that was previously encrypted via openssl_public_encrypt() and stores the result into decrypted.

You can use this function e.g. to decrypt data which is supposed to only be available to you.

Parameters

data

decrypted

key

key must be the private key corresponding 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.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • openssl_public_encrypt() - Encrypts data with public key
  • openssl_public_decrypt() - Decrypts data with public key


Encrypts data with private key

  • « openssl_private_decrypt
  • openssl_public_decrypt »
  • PHP Manual
  • OpenSSL Functions
  • Encrypts data with private key

openssl_private_encrypt

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

openssl_private_encrypt — Encrypts data with private key

Description

openssl_private_encrypt ( string $data , string &$crypted , mixed $key [, int $padding = OPENSSL_PKCS1_PADDING ] ) : bool

openssl_private_encrypt() encrypts data with private key and stores the result into crypted. 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

crypted

key

padding

padding can be one of OPENSSL_PKCS1_PADDING, OPENSSL_NO_PADDING.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • openssl_public_encrypt() - Encrypts data with public key
  • openssl_public_decrypt() - Decrypts data with public key


Decrypts data with public key

  • « openssl_private_encrypt
  • openssl_public_encrypt »
  • PHP Manual
  • OpenSSL Functions
  • Decrypts data with public key

openssl_public_decrypt

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

openssl_public_decrypt — Decrypts data with public key

Description

openssl_public_decrypt ( string $data , string &$decrypted , mixed $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.

You can use this function e.g. to check if the message was written by the owner of the private key.

Parameters

data

decrypted

key

key must be the public key corresponding 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.

See Also

  • openssl_private_encrypt() - Encrypts data with private key
  • openssl_private_decrypt() - Decrypts data with private key


Encrypts data with public key

  • « openssl_public_decrypt
  • openssl_random_pseudo_bytes »
  • PHP Manual
  • OpenSSL Functions
  • Encrypts data with public key

openssl_public_encrypt

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

openssl_public_encrypt — Encrypts data with public key

Description

openssl_public_encrypt ( string $data , string &$crypted , mixed $key [, int $padding = OPENSSL_PKCS1_PADDING ] ) : bool

openssl_public_encrypt() encrypts data with public key and stores the result into crypted. 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

crypted

This will hold the result of the encryption.

key

The public key.

padding

padding can be one of OPENSSL_PKCS1_PADDING, OPENSSL_SSLV23_PADDING, OPENSSL_PKCS1_OAEP_PADDING, OPENSSL_NO_PADDING.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • openssl_private_encrypt() - Encrypts data with private key
  • openssl_private_decrypt() - Decrypts data with private key


Generate a pseudo-random string of bytes

  • « openssl_public_encrypt
  • openssl_seal »
  • PHP Manual
  • OpenSSL Functions
  • Generate a pseudo-random string of bytes

openssl_random_pseudo_bytes

(PHP 5 >= 5.3.0, PHP 7)

openssl_random_pseudo_bytes — Generate a pseudo-random string of bytes

Description

openssl_random_pseudo_bytes ( int $length [, bool &$crypto_strong ] ) : 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 crypto_strong 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. PHP will try to cast this parameter to a non-null integer to use it.

crypto_strong

If passed into the function, this will hold a boolean 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 on success, or FALSE on failure.

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: 0
string(0) ""
NULL

Lengths: Bytes: 0 and Hex: 0
string(0) ""
NULL

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() - Generates cryptographically secure pseudo-random bytes
  • bin2hex() - Convert binary data into hexadecimal representation
  • crypt() - One-way string hashing
  • mt_rand() - Generate a random value via the Mersenne Twister Random Number Generator
  • uniqid() - Generate a unique ID


Seal (encrypt) data

  • « openssl_random_pseudo_bytes
  • openssl_sign »
  • PHP Manual
  • OpenSSL Functions
  • Seal (encrypt) data

openssl_seal

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

openssl_seal — Seal (encrypt) data

Description

openssl_seal ( string $data , string &$sealed_data , array &$env_keys , array $pub_key_ids [, string $method = "RC4" [, string &$iv ]] ) : int

openssl_seal() seals (encrypts) data by using the given method with a randomly generated secret key. The key is encrypted with each of the public keys associated with the identifiers in pub_key_ids and each encrypted key is returned in env_keys. This means that one can send sealed data to multiple recipients (provided one has obtained their public keys). Each recipient must receive both the sealed data and the envelope key that was encrypted with the recipient's public key.

Parameters

data

The data to seal.

sealed_data

The sealed data.

env_keys

Array of encrypted keys.

pub_key_ids

Array of public key resource identifiers.

method

The cipher method.

iv

The initialization vector.

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

Changelog

Version | Description
7.0.0 | The iv has been added.
5.3.0 | The method has been added.

Examples

Example #1 openssl_seal() example

<?php
// $data is assumed to contain the data to be sealed

// fetch public keys for our recipients, and ready them
$fp = fopen("/src/openssl-0.9.6/demos/maurice/cert.pem", "r");
$cert = fread($fp, 8192);
fclose($fp);
$pk1 = openssl_get_publickey($cert);
// Repeat for second recipient
$fp = fopen("/src/openssl-0.9.6/demos/sign/cert.pem", "r");
$cert = fread($fp, 8192);
fclose($fp);
$pk2 = openssl_get_publickey($cert);

// seal message, only owners of $pk1 and $pk2 can decrypt $sealed with keys
// $ekeys[0] and $ekeys[1] respectively.
openssl_seal($data, $sealed, $ekeys, array($pk1, $pk2));

// free the keys from memory
openssl_free_key($pk1);
openssl_free_key($pk2);
?>

See Also

  • openssl_open() - Open sealed data


Generate signature

  • « openssl_seal
  • openssl_spki_export_challenge »
  • PHP Manual
  • OpenSSL Functions
  • Generate signature

openssl_sign

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

openssl_sign — Generate signature

Description

openssl_sign ( string $data , string &$signature , mixed $priv_key_id [, mixed $signature_alg = OPENSSL_ALGO_SHA1 ] ) : bool

openssl_sign() computes a signature for the specified data by generating a cryptographic digital signature using the private key associated with priv_key_id. 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.

priv_key_id

resource - a key, returned by openssl_get_privatekey()

string - a PEM formatted key

signature_alg

int - one of these Signature Algorithms.

string - a valid string returned by openssl_get_md_methods() example, "sha256WithRSAEncryption" or "sha384".

Return Values

Returns TRUE on success or FALSE on failure.

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


Exports the challenge assoicated with a signed public key and challenge

  • « openssl_sign
  • openssl_spki_export »
  • PHP Manual
  • OpenSSL Functions
  • Exports the challenge assoicated with a signed public key and challenge

openssl_spki_export_challenge

(PHP 5 >= 5.6.0, PHP 7)

openssl_spki_export_challenge — Exports the challenge assoicated with a signed public key and challenge

Description

openssl_spki_export_challenge ( string &$spkac ) : string

Exports challenge from encoded signed public key and challenge

Parameters

spkac

Expects a valid signed public key and challenge

Return Values

Returns the associated challenge string or NULL on failure.

Errors/Exceptions

Emits an E_WARNING level error if an invalid argument is passed via the spkac 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


Exports a valid PEM formatted public key signed public key and challenge

  • « openssl_spki_export_challenge
  • openssl_spki_new »
  • PHP Manual
  • OpenSSL Functions
  • Exports a valid PEM formatted public key signed public key and challenge

openssl_spki_export

(PHP 5 >= 5.6.0, PHP 7)

openssl_spki_export — Exports a valid PEM formatted public key signed public key and challenge

Description

openssl_spki_export ( string &$spkac ) : string

Exports PEM formatted public key from encoded signed public key and challenge

Parameters

spkac

Expects a valid signed public key and challenge

Return Values

Returns the associated PEM formatted public key or NULL on failure.

Errors/Exceptions

Emits an E_WARNING level error if an invalid argument is passed via the spkac 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 assoicated 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


Generate a new signed public key and challenge

  • « openssl_spki_export
  • openssl_spki_verify »
  • PHP Manual
  • OpenSSL Functions
  • Generate a new signed public key and challenge

openssl_spki_new

(PHP 5 >= 5.6.0, PHP 7)

openssl_spki_new — Generate a new signed public key and challenge

Description

openssl_spki_new ( resource &$privkey , string &$challenge [, int $algorithm = 0 ] ) : string

Generates a signed public key and challenge using specified hashing algorithm

Parameters

privkey

privkey 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

algorithm

The digest algorithm. See openssl_get_md_method().

Return Values

Returns a signed public key and challenge string or NULL on failure.

Errors/Exceptions

Emits an E_WARNING level error if an unknown signature algorithm is passed via the algorithm parameter.

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


Verifies a signed public key and challenge

  • « openssl_spki_new
  • openssl_verify »
  • PHP Manual
  • OpenSSL Functions
  • Verifies a signed public key and challenge

openssl_spki_verify

(PHP 5 >= 5.6.0, PHP 7)

openssl_spki_verify — Verifies a signed public key and challenge

Description

openssl_spki_verify ( string &$spkac ) : string

Validates the supplied signed public key and challenge

Parameters

spkac

Expects a valid signed public key and challenge

Return Values

Returns a boolean on success or failure.

Errors/Exceptions

Emits an E_WARNING level error if an invalid argument is passed via the spkac 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 assoicated 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


Verify signature

  • « openssl_spki_verify
  • openssl_x509_check_private_key »
  • PHP Manual
  • OpenSSL Functions
  • Verify signature

openssl_verify

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

openssl_verify — Verify signature

Description

openssl_verify ( string $data , string $signature , mixed $pub_key_id [, mixed $signature_alg = OPENSSL_ALGO_SHA1 ] ) : int

openssl_verify() verifies that the signature is correct for the specified data using the public key associated with pub_key_id. 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

pub_key_id

resource - a key, returned by openssl_get_publickey()

string - a PEM formatted key, example, "-----BEGIN PUBLIC KEY----- MIIBCgK..."

signature_alg

int - one of these Signature Algorithms.

string - a valid string returned by openssl_get_md_methods() example, "sha1WithRSAEncryption" or "sha512".

Return Values

Returns 1 if the signature is correct, 0 if it is incorrect, and -1 on error.

Changelog

Version | Description
5.2.0 | The signature_alg parameter was added.

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, "sha1WithRSAEncryption");

//verify signature
$ok = openssl_verify($data, $signature, $public_key_res, OPENSSL_ALGO_SHA1);
if ($ok == 1) {
    echo "valid";
} elseif ($ok == 0) {
    echo "invalid";
} else {
    echo "error: ".openssl_error_string();
}
?>

See Also

  • openssl_sign() - Generate signature


Checks if a private key corresponds to a certificate

  • « openssl_verify
  • openssl_x509_checkpurpose »
  • PHP Manual
  • OpenSSL Functions
  • Checks if a private key corresponds to a certificate

openssl_x509_check_private_key

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

openssl_x509_check_private_key — Checks if a private key corresponds to a certificate

Description

openssl_x509_check_private_key ( mixed $cert , mixed $key ) : bool

Checks whether the given key is the private key that corresponds to cert.

Warning

The function does not check if 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 key and the function may return TRUE.

Parameters

cert

The certificate.

key

The private key.

Return Values

Returns TRUE if key is the private key that corresponds to cert, or FALSE otherwise.


Verifies if a certificate can be used for a particular purpose

  • « openssl_x509_check_private_key
  • openssl_x509_export_to_file »
  • PHP Manual
  • OpenSSL Functions
  • Verifies if a certificate can be used for a particular purpose

openssl_x509_checkpurpose

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

openssl_x509_checkpurpose — Verifies if a certificate can be used for a particular purpose

Description

openssl_x509_checkpurpose ( mixed $x509cert , int $purpose [, array $cainfo = array() [, string $untrustedfile ]] ) : int

openssl_x509_checkpurpose() examines a certificate to see if it can be used for the specified purpose.

Parameters

x509cert

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!

cainfo

cainfo should be an array of trusted CA files/dirs as described in Certificate Verification.

untrustedfile

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.


Exports a certificate to file

  • « openssl_x509_checkpurpose
  • openssl_x509_export »
  • PHP Manual
  • OpenSSL Functions
  • Exports a certificate to file

openssl_x509_export_to_file

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

openssl_x509_export_to_file — Exports a certificate to file

Description

openssl_x509_export_to_file ( mixed $x509 , string $outfilename [, bool $notext = TRUE ] ) : bool

openssl_x509_export_to_file() stores x509 into a file named by outfilename in a PEM encoded format.

Parameters

x509

See Key/Certificate parameters for a list of valid values.

outfilename

Path to the output file.

notext

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.


Exports a certificate as a string

  • « openssl_x509_export_to_file
  • openssl_x509_fingerprint »
  • PHP Manual
  • OpenSSL Functions
  • Exports a certificate as a string

openssl_x509_export

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

openssl_x509_export — Exports a certificate as a string

Description

openssl_x509_export ( mixed $x509 , string &$output [, bool $notext = TRUE ] ) : bool

openssl_x509_export() stores x509 into a string named by output in a PEM encoded format.

Parameters

x509

See Key/Certificate parameters for a list of valid values.

output

On success, this will hold the PEM.

notext

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.


Calculates the fingerprint, or digest, of a given X.509 certificate

  • « openssl_x509_export
  • openssl_x509_free »
  • PHP Manual
  • OpenSSL Functions
  • Calculates the fingerprint, or digest, of a given X.509 certificate

openssl_x509_fingerprint

(PHP 5 >= 5.6.0, PHP 7)

openssl_x509_fingerprint — Calculates the fingerprint, or digest, of a given X.509 certificate

Description

openssl_x509_fingerprint ( mixed $x509 [, string $hash_algorithm = "sha1" [, bool $raw_output = FALSE ]] ) : string

openssl_x509_fingerprint() returns the digest of x509 as a string.

Parameters

x509

See Key/Certificate parameters for a list of valid values.

hash_algorithm

The digest method or hash algorithm to use, e.g. "sha256", one of openssl_get_md_methods().

raw_output

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 raw_output is set to TRUE in which case the raw binary representation of the message digest is returned.

Returns FALSE on failure.


Free certificate resource

  • « openssl_x509_fingerprint
  • openssl_x509_parse »
  • PHP Manual
  • OpenSSL Functions
  • Free certificate resource

openssl_x509_free

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

openssl_x509_free — Free certificate resource

Description

openssl_x509_free ( resource $x509cert ) : void

openssl_x509_free() frees the certificate associated with the specified x509cert resource from memory.

Parameters

x509cert

Return Values

No value is returned.


Parse an X509 certificate and return the information as an array

  • « openssl_x509_free
  • openssl_x509_read »
  • PHP Manual
  • OpenSSL Functions
  • Parse an X509 certificate and return the information as an array

openssl_x509_parse

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

openssl_x509_parse — Parse an X509 certificate and return the information as an array

Description

openssl_x509_parse ( mixed $x509cert [, bool $shortnames = TRUE ] ) : array

openssl_x509_parse() returns information about the supplied x509cert, including fields such as subject name, issuer name, purposes, valid from and valid to dates etc.

Parameters

x509cert

shortnames

shortnames controls how the data is indexed in the array - if shortnames 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.


Parse an X.509 certificate and return a resource identifier for it

  • « openssl_x509_parse
  • Password Hashing »
  • PHP Manual
  • OpenSSL Functions
  • Parse an X.509 certificate and return a resource identifier for it

openssl_x509_read

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

openssl_x509_read — Parse an X.509 certificate and return a resource identifier for it

Description

openssl_x509_read ( mixed $x509certdata ) : resource

openssl_x509_read() parses the certificate supplied by x509certdata and returns a resource identifier for it.

Parameters

x509certdata

X509 certificate. See Key/Certificate parameters for a list of valid values.

Return Values

Returns a resource identifier on success or FALSE on failure.


Password Hashing

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Password Hashing Functions
    • 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


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.

This extension is available since PHP 5.5.0 but there is also an » userland implementation for PHP >= 5.3.7.


Requirements

No external libraries are needed to build this extension.

For Argon2 password hashing, » libargon2 is required, though. As of PHP 7.3.0, libargon2 version 20161029 or later is required.


Installation

There is no installation needed to use these functions; they are part of the PHP core.

To enable Argon2 password hashing, however, PHP must be build with libargon2 support using the --with-password-argon2[=DIR] configure option.


Predefined Constants

The constants below are always available as part of the PHP core.

PASSWORD_BCRYPT (integer)

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 (integer) - 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 10 will be used. This is a good baseline cost, but you may want to consider increasing it depending on your hardware.

PASSWORD_ARGON2I (integer)

PASSWORD_ARGON2I is used to create new password hashes using the Argon2i algorithm.

Supported Options:

  • memory_cost (integer) - Maximum memory (in bytes) that may be used to compute the Argon2 hash. Defaults to PASSWORD_ARGON2_DEFAULT_MEMORY_COST.

  • time_cost (integer) - Maximum amount of time it may take to compute the Argon2 hash. Defaults to PASSWORD_ARGON2_DEFAULT_TIME_COST.

  • threads (integer) - Number of threads to use for computing the Argon2 hash. Defaults to PASSWORD_ARGON2_DEFAULT_THREADS.

Available as of PHP 7.2.0.

PASSWORD_ARGON2ID (integer)

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

Default amount of memory in bytes that Argon2lib will use while trying to compute a hash.

Available as of PHP 7.2.0.

PASSWORD_ARGON2_DEFAULT_TIME_COST (integer)

Default amount of time that Argon2lib will spend trying to compute a hash.

Available as of PHP 7.2.0.

PASSWORD_ARGON2_DEFAULT_THREADS (integer)

Default number of threads that Argon2lib will use.

Available as of PHP 7.2.0.

PASSWORD_DEFAULT (integer)

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 (and likely will) change. Therefore you should be aware that the length of the resulting hash can change. Therefore, if you use PASSWORD_DEFAULT you should store the resulting hash in a way that can store more than 60 characters (255 is the recommended width).

Values for this constant:

  • PHP 5.5.0 - PASSWORD_BCRYPT


Password Hashing Functions

Table of Contents

  • 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


Returns information about the given hash

  • « Password Hashing Functions
  • password_hash »
  • PHP Manual
  • Password Hashing Functions
  • Returns information about the given hash

password_get_info

(PHP 5 >= 5.5.0, PHP 7)

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


Creates a password hash

  • « password_get_info
  • password_needs_rehash »
  • PHP Manual
  • Password Hashing Functions
  • Creates a password hash

password_hash

(PHP 5 >= 5.5.0, PHP 7)

password_hash — Creates a password hash

Description

password_hash ( string $password , int $algo [, array $options ] ) : string

password_hash() creates a new password hash using a strong one-way hashing algorithm. password_hash() is compatible with crypt(). Therefore, password hashes created by crypt() can be used with password_hash().

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 characters (255 characters would be a good choice).
  • PASSWORD_BCRYPT - Use the CRYPT_BLOWFISH algorithm to create the hash. This will produce a standard crypt() compatible hash using the "$2y$" identifier. The result will always be a 60 character string, or FALSE on failure.
  • 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 has been deprecated as of PHP 7.0.0. It is now preferred to simply use the salt that is generated by default.

  • cost (integer) - 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 10 will be used. This is a good baseline cost, but you may want to consider increasing it depending on your hardware.

Supported options for PASSWORD_ARGON2I and PASSWORD_ARGON2ID:

  • memory_cost (integer) - Maximum memory (in kibibytes) that may be used to compute the Argon2 hash. Defaults to PASSWORD_ARGON2_DEFAULT_MEMORY_COST.

  • time_cost (integer) - Maximum amount of time it may take to compute the Argon2 hash. Defaults to PASSWORD_ARGON2_DEFAULT_TIME_COST.

  • threads (integer) - Number of threads to use for computing the Argon2 hash. Defaults to PASSWORD_ARGON2_DEFAULT_THREADS.

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

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.

If omitted, a random salt will be created and the default cost will be used.

Return Values

Returns the hashed password, or FALSE on failure.

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.

Examples

Example #1 password_hash() example

<?php
/**
 * We just want to hash our password using the current DEFAULT algorithm.
 * This is presently BCRYPT, and will produce a 60 character result.
 *
 * Beware that DEFAULT may change over time, so you would want to prepare
 * By allowing your storage to expand past 60 characters (255 would be good)
 */
echo password_hash("rasmuslerdorf", PASSWORD_DEFAULT);
?>

The above example will output something similar to:

$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a

Example #2 password_hash() example setting cost manually

<?php
/**
 * In this case, we want to increase the default cost for BCRYPT to 12.
 * Note that we also switched to BCRYPT, which will always be 60 characters.
 */
$options = [
    'cost' => 12,
];
echo password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options);
?>

The above example will output something similar to:

$2y$12$QjSH496pcT5CEbzjD/vtVeH03tfHKFy36d4J0Ltp3lRtee9HDxY3K

Example #3 password_hash() example finding a good cost

<?php
/**
 * This code will benchmark your server to determine how high of a cost you can
 * afford. You want to set the highest cost that you can without slowing down
 * you server too much. 8-10 is a good baseline, and more is good if your servers
 * are fast enough. The code below aims for ≤ 50 milliseconds stretching time,
 * which is a good baseline for systems handling interactive logins.
 */
$timeTarget = 0.05; // 50 milliseconds

$cost = 8;
do {
    $cost++;
    $start = microtime(true);
    password_hash("test", PASSWORD_BCRYPT, ["cost" => $cost]);
    $end = microtime(true);
} while (($end - $start) < $timeTarget);

echo "Appropriate Cost Found: " . $cost;
?>

The above example will output something similar to:

Appropriate Cost Found: 10

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 that you do not generate your own salt for this function. It will create a secure salt automatically for you if you do not specify one.

As noted above, providing the salt option in PHP 7.0 will generate a deprecation warning. Support for providing a salt manually may be removed in a future PHP release.

Note:

It is recommended that you test this function on your servers, and adjust the cost parameter so that execution of the function takes less than 100 milliseconds on interactive systems. The script in the above example will help you choose a good cost value for your hardware.

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.

Changelog

Version | Description
7.3.0 | Support for Argon2id passwords using PASSWORD_ARGON2ID was added.
7.2.0 | Support for Argon2i passwords using PASSWORD_ARGON2I was added.

See Also

  • password_verify() - Verifies that a password matches a hash
  • crypt() - One-way string hashing
  • » userland implementation
  • sodium_crypto_pwhash_str() - Get an ASCII-encoded hash


Checks if the given hash matches the given options

  • « password_hash
  • password_verify »
  • PHP Manual
  • Password Hashing Functions
  • Checks if the given hash matches the given options

password_needs_rehash

(PHP 5 >= 5.5.0, PHP 7)

password_needs_rehash — Checks if the given hash matches the given options

Description

password_needs_rehash ( string $hash , int $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.

Examples

Example #1 Usage of password_needs_rehash()

<?php

$password = 'rasmuslerdorf';
$hash = '$2y$10$YCFsG6elYca568hBi2pZ0.3LDL5wjgxct1N8w/oLR/jfHsiQwCqTS';

// The cost parameter can change over time as hardware improves
$options = array('cost' => 11);

// Verify stored hash against plain-text password
if (password_verify($password, $hash)) {
    // Check if a newer hashing algorithm is available
    // or the cost has changed
    if (password_needs_rehash($hash, PASSWORD_DEFAULT, $options)) {
        // If so, create a new hash, and replace the old one
        $newHash = password_hash($password, PASSWORD_DEFAULT, $options);
    }

    // Log user in
}
?>

Return Values

Returns TRUE if the hash should be rehashed to match the given algo and options, or FALSE otherwise.


Verifies that a password matches a hash

  • « password_needs_rehash
  • Sodium »
  • PHP Manual
  • Password Hashing Functions
  • Verifies that a password matches a hash

password_verify

(PHP 5 >= 5.5.0, PHP 7)

password_verify — Verifies that a password matches a hash

Description

password_verify ( string $password , string $hash ) : bool

Verifies that the given hash matches the given password.

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

<?php
// See the password_hash() example to see where this came from.
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';

if (password_verify('rasmuslerdorf', $hash)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}
?>

The above example will output:

Password is valid!

See Also

  • password_hash() - Creates a password hash
  • » userland implementation
  • sodium_crypto_pwhash_str_verify() - Verifies that a password matches a hash


Sodium

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Sodium Functions
    • sodium_add — Add large numbers
    • sodium_base642bin — Description
    • sodium_bin2base64 — Description
    • sodium_bin2hex — Encode to hexadecimal
    • sodium_compare — Compare large numbers
    • sodium_crypto_aead_aes256gcm_decrypt — Decrypt in combined mode with precalculation
    • sodium_crypto_aead_aes256gcm_encrypt — Encrypt in combined mode with precalculation
    • sodium_crypto_aead_aes256gcm_is_available — Check if hardware supports AES256-GCM
    • sodium_crypto_aead_aes256gcm_keygen — Get random bytes for key
    • sodium_crypto_aead_chacha20poly1305_decrypt — Verify that the ciphertext includes a valid tag
    • sodium_crypto_aead_chacha20poly1305_encrypt — Encrypt a message
    • 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 — Get random bytes for key
    • sodium_crypto_aead_chacha20poly1305_keygen — Get random bytes for key
    • sodium_crypto_aead_xchacha20poly1305_ietf_decrypt — Description
    • sodium_crypto_aead_xchacha20poly1305_ietf_encrypt — Description
    • sodium_crypto_aead_xchacha20poly1305_ietf_keygen — Description
    • sodium_crypto_auth_keygen — Get random bytes for key
    • sodium_crypto_auth_verify — Verifies that the tag is valid for the message
    • sodium_crypto_auth — Compute a tag for the message
    • sodium_crypto_box_keypair_from_secretkey_and_publickey — Description
    • sodium_crypto_box_keypair — Randomly generate a secret key and a corresponding public key
    • sodium_crypto_box_open — Verify and decrypt a ciphertext
    • sodium_crypto_box_publickey_from_secretkey — Description
    • sodium_crypto_box_publickey — Description
    • sodium_crypto_box_seal_open — Decrypt the ciphertext
    • sodium_crypto_box_seal — Encrypt a message
    • sodium_crypto_box_secretkey — Description
    • sodium_crypto_box_seed_keypair — Deterministically derive the key pair from a single key
    • sodium_crypto_box — Encrypt a message
    • sodium_crypto_generichash_final — Complete the hash
    • sodium_crypto_generichash_init — Initialize a hash
    • sodium_crypto_generichash_keygen — Get random bytes for key
    • sodium_crypto_generichash_update — Add message to a hash
    • sodium_crypto_generichash — Get a hash of the message
    • sodium_crypto_kdf_derive_from_key — Derive a subkey
    • sodium_crypto_kdf_keygen — Get random bytes for key
    • sodium_crypto_kx_client_session_keys — Description
    • sodium_crypto_kx_keypair — Creates a new sodium keypair
    • sodium_crypto_kx_publickey — Description
    • sodium_crypto_kx_secretkey — Description
    • sodium_crypto_kx_seed_keypair — Description
    • sodium_crypto_kx_server_session_keys — Description
    • sodium_crypto_pwhash_scryptsalsa208sha256_str_verify — Verify that the password is a valid password verification string
    • sodium_crypto_pwhash_scryptsalsa208sha256_str — Get an ASCII encoded hash
    • sodium_crypto_pwhash_scryptsalsa208sha256 — Derives a key from a password
    • sodium_crypto_pwhash_str_needs_rehash — Description
    • sodium_crypto_pwhash_str_verify — Verifies that a password matches a hash
    • sodium_crypto_pwhash_str — Get an ASCII-encoded hash
    • sodium_crypto_pwhash — Derive a key from a password
    • sodium_crypto_scalarmult_base — Alias of sodium_crypto_box_publickey_from_secretkey
    • sodium_crypto_scalarmult — Compute a shared secret given a user's secret key and another user's public key
    • sodium_crypto_secretbox_keygen — Get random bytes for key
    • sodium_crypto_secretbox_open — Verify and decrypt a ciphertext
    • sodium_crypto_secretbox — Encrypt a message
    • sodium_crypto_secretstream_xchacha20poly1305_init_pull — Description
    • sodium_crypto_secretstream_xchacha20poly1305_init_push — Description
    • sodium_crypto_secretstream_xchacha20poly1305_keygen — Description
    • sodium_crypto_secretstream_xchacha20poly1305_pull — Description
    • sodium_crypto_secretstream_xchacha20poly1305_push — Description
    • sodium_crypto_secretstream_xchacha20poly1305_rekey — Description
    • sodium_crypto_shorthash_keygen — Get random bytes for key
    • sodium_crypto_shorthash — Compute a fixed-size fingerprint for the 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_from_secretkey_and_publickey — Description
    • sodium_crypto_sign_keypair — Randomly generate a secret key and a corresponding public key
    • sodium_crypto_sign_open — Check that the signed message has a valid signature
    • sodium_crypto_sign_publickey_from_secretkey — Extract the public key from the secret key
    • sodium_crypto_sign_publickey — Description
    • sodium_crypto_sign_secretkey — Description
    • 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_sign — Sign a message
    • sodium_crypto_stream_keygen — Get random bytes for key
    • sodium_crypto_stream_xor — Encrypt a message
    • sodium_crypto_stream — Generate a deterministic sequence of bytes from a seed
    • sodium_hex2bin — Decodes a hexadecimally encoded binary string
    • sodium_increment — Increment large number
    • sodium_memcmp — Test for equality in constant-time
    • sodium_memzero — Overwrite buf with zeros
    • sodium_pad — Add padding data
    • sodium_unpad — Remove padding data


  • « Sodium
  • Installing/Configuring »
  • PHP Manual
  • Sodium
  • Introduction

Introduction


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

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 (integer)
SODIUM_LIBRARY_MINOR_VERSION (integer)
SODIUM_CRYPTO_AEAD_AES256GCM_KEYBYTES (integer)
SODIUM_CRYPTO_AEAD_AES256GCM_NSECBYTES (integer)
SODIUM_CRYPTO_AEAD_AES256GCM_NPUBBYTES (integer)
SODIUM_CRYPTO_AEAD_AES256GCM_ABYTES (integer)
SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES (integer)
SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_NSECBYTES (integer)
SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES (integer)
SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_ABYTES (integer)
SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_KEYBYTES (integer)
SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_NSECBYTES (integer)
SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES (integer)
SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_ABYTES (integer)
SODIUM_CRYPTO_AUTH_BYTES (integer)
SODIUM_CRYPTO_AUTH_KEYBYTES (integer)
SODIUM_CRYPTO_BOX_SEALBYTES (integer)
SODIUM_CRYPTO_BOX_SECRETKEYBYTES (integer)
SODIUM_CRYPTO_BOX_PUBLICKEYBYTES (integer)
SODIUM_CRYPTO_BOX_KEYPAIRBYTES (integer)
SODIUM_CRYPTO_BOX_MACBYTES (integer)
SODIUM_CRYPTO_BOX_NONCEBYTES (integer)
SODIUM_CRYPTO_BOX_SEEDBYTES (integer)
SODIUM_CRYPTO_KDF_BYTES_MIN (integer)
SODIUM_CRYPTO_KDF_BYTES_MAX (integer)
SODIUM_CRYPTO_KDF_CONTEXTBYTES (integer)
SODIUM_CRYPTO_KDF_KEYBYTES (integer)
SODIUM_CRYPTO_KX_SEEDBYTES (integer)
SODIUM_CRYPTO_KX_SESSIONKEYBYTES (integer)
SODIUM_CRYPTO_KX_PUBLICKEYBYTES (integer)
SODIUM_CRYPTO_KX_SECRETKEYBYTES (integer)
SODIUM_CRYPTO_KX_KEYPAIRBYTES (integer)
SODIUM_CRYPTO_GENERICHASH_BYTES (integer)
SODIUM_CRYPTO_GENERICHASH_BYTES_MIN (integer)
SODIUM_CRYPTO_GENERICHASH_BYTES_MAX (integer)
SODIUM_CRYPTO_GENERICHASH_KEYBYTES (integer)
SODIUM_CRYPTO_GENERICHASH_KEYBYTES_MIN (integer)
SODIUM_CRYPTO_GENERICHASH_KEYBYTES_MAX (integer)
SODIUM_CRYPTO_PWHASH_ALG_ARGON2I13 (integer)
SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13 (integer)
SODIUM_CRYPTO_PWHASH_ALG_DEFAULT (integer)
SODIUM_CRYPTO_PWHASH_SALTBYTES (integer)
SODIUM_CRYPTO_PWHASH_STRPREFIX (string)
SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE (integer)
SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE (integer)
SODIUM_CRYPTO_PWHASH_OPSLIMIT_MODERATE (integer)
SODIUM_CRYPTO_PWHASH_MEMLIMIT_MODERATE (integer)
SODIUM_CRYPTO_PWHASH_OPSLIMIT_SENSITIVE (integer)
SODIUM_CRYPTO_PWHASH_MEMLIMIT_SENSITIVE (integer)
SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_SALTBYTES (integer)
SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_STRPREFIX (string)
SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_INTERACTIVE (integer)
SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_INTERACTIVE (integer)
SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_SENSITIVE (integer)
SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_SENSITIVE (integer)
SODIUM_CRYPTO_SCALARMULT_BYTES (integer)
SODIUM_CRYPTO_SCALARMULT_SCALARBYTES (integer)
SODIUM_CRYPTO_SHORTHASH_BYTES (integer)
SODIUM_CRYPTO_SHORTHASH_KEYBYTES (integer)
SODIUM_CRYPTO_SECRETBOX_KEYBYTES (integer)
SODIUM_CRYPTO_SECRETBOX_MACBYTES (integer)
SODIUM_CRYPTO_SECRETBOX_NONCEBYTES (integer)
SODIUM_CRYPTO_SIGN_BYTES (integer)
SODIUM_CRYPTO_SIGN_SEEDBYTES (integer)
SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES (integer)
SODIUM_CRYPTO_SIGN_SECRETKEYBYTES (integer)
SODIUM_CRYPTO_SIGN_KEYPAIRBYTES (integer)
SODIUM_CRYPTO_STREAM_NONCEBYTES (integer)
SODIUM_CRYPTO_STREAM_KEYBYTES (integer)


Sodium Functions

Table of Contents

  • sodium_add — Add large numbers
  • sodium_base642bin — Description
  • sodium_bin2base64 — Description
  • sodium_bin2hex — Encode to hexadecimal
  • sodium_compare — Compare large numbers
  • sodium_crypto_aead_aes256gcm_decrypt — Decrypt in combined mode with precalculation
  • sodium_crypto_aead_aes256gcm_encrypt — Encrypt in combined mode with precalculation
  • sodium_crypto_aead_aes256gcm_is_available — Check if hardware supports AES256-GCM
  • sodium_crypto_aead_aes256gcm_keygen — Get random bytes for key
  • sodium_crypto_aead_chacha20poly1305_decrypt — Verify that the ciphertext includes a valid tag
  • sodium_crypto_aead_chacha20poly1305_encrypt — Encrypt a message
  • 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 — Get random bytes for key
  • sodium_crypto_aead_chacha20poly1305_keygen — Get random bytes for key
  • sodium_crypto_aead_xchacha20poly1305_ietf_decrypt — Description
  • sodium_crypto_aead_xchacha20poly1305_ietf_encrypt — Description
  • sodium_crypto_aead_xchacha20poly1305_ietf_keygen — Description
  • sodium_crypto_auth_keygen — Get random bytes for key
  • sodium_crypto_auth_verify — Verifies that the tag is valid for the message
  • sodium_crypto_auth — Compute a tag for the message
  • sodium_crypto_box_keypair_from_secretkey_and_publickey — Description
  • sodium_crypto_box_keypair — Randomly generate a secret key and a corresponding public key
  • sodium_crypto_box_open — Verify and decrypt a ciphertext
  • sodium_crypto_box_publickey_from_secretkey — Description
  • sodium_crypto_box_publickey — Description
  • sodium_crypto_box_seal_open — Decrypt the ciphertext
  • sodium_crypto_box_seal — Encrypt a message
  • sodium_crypto_box_secretkey — Description
  • sodium_crypto_box_seed_keypair — Deterministically derive the key pair from a single key
  • sodium_crypto_box — Encrypt a message
  • sodium_crypto_generichash_final — Complete the hash
  • sodium_crypto_generichash_init — Initialize a hash
  • sodium_crypto_generichash_keygen — Get random bytes for key
  • sodium_crypto_generichash_update — Add message to a hash
  • sodium_crypto_generichash — Get a hash of the message
  • sodium_crypto_kdf_derive_from_key — Derive a subkey
  • sodium_crypto_kdf_keygen — Get random bytes for key
  • sodium_crypto_kx_client_session_keys — Description
  • sodium_crypto_kx_keypair — Creates a new sodium keypair
  • sodium_crypto_kx_publickey — Description
  • sodium_crypto_kx_secretkey — Description
  • sodium_crypto_kx_seed_keypair — Description
  • sodium_crypto_kx_server_session_keys — Description
  • sodium_crypto_pwhash_scryptsalsa208sha256_str_verify — Verify that the password is a valid password verification string
  • sodium_crypto_pwhash_scryptsalsa208sha256_str — Get an ASCII encoded hash
  • sodium_crypto_pwhash_scryptsalsa208sha256 — Derives a key from a password
  • sodium_crypto_pwhash_str_needs_rehash — Description
  • sodium_crypto_pwhash_str_verify — Verifies that a password matches a hash
  • sodium_crypto_pwhash_str — Get an ASCII-encoded hash
  • sodium_crypto_pwhash — Derive a key from a password
  • sodium_crypto_scalarmult_base — Alias of sodium_crypto_box_publickey_from_secretkey
  • sodium_crypto_scalarmult — Compute a shared secret given a user's secret key and another user's public key
  • sodium_crypto_secretbox_keygen — Get random bytes for key
  • sodium_crypto_secretbox_open — Verify and decrypt a ciphertext
  • sodium_crypto_secretbox — Encrypt a message
  • sodium_crypto_secretstream_xchacha20poly1305_init_pull — Description
  • sodium_crypto_secretstream_xchacha20poly1305_init_push — Description
  • sodium_crypto_secretstream_xchacha20poly1305_keygen — Description
  • sodium_crypto_secretstream_xchacha20poly1305_pull — Description
  • sodium_crypto_secretstream_xchacha20poly1305_push — Description
  • sodium_crypto_secretstream_xchacha20poly1305_rekey — Description
  • sodium_crypto_shorthash_keygen — Get random bytes for key
  • sodium_crypto_shorthash — Compute a fixed-size fingerprint for the 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_from_secretkey_and_publickey — Description
  • sodium_crypto_sign_keypair — Randomly generate a secret key and a corresponding public key
  • sodium_crypto_sign_open — Check that the signed message has a valid signature
  • sodium_crypto_sign_publickey_from_secretkey — Extract the public key from the secret key
  • sodium_crypto_sign_publickey — Description
  • sodium_crypto_sign_secretkey — Description
  • 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_sign — Sign a message
  • sodium_crypto_stream_keygen — Get random bytes for key
  • sodium_crypto_stream_xor — Encrypt a message
  • sodium_crypto_stream — Generate a deterministic sequence of bytes from a seed
  • sodium_hex2bin — Decodes a hexadecimally encoded binary string
  • sodium_increment — Increment large number
  • sodium_memcmp — Test for equality in constant-time
  • sodium_memzero — Overwrite buf with zeros
  • sodium_pad — Add padding data
  • sodium_unpad — Remove padding data


Add large numbers

  • « Sodium Functions
  • sodium_base642bin »
  • PHP Manual
  • Sodium Functions
  • Add large numbers

sodium_add

(PHP 7 >= 7.2.0)

sodium_add — Add large numbers

Description

sodium_add ( string &$val , string $addv ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

val

addv

Return Values

No value is returned.


Description

  • « sodium_add
  • sodium_bin2base64 »
  • PHP Manual
  • Sodium Functions
  • Description

sodium_base642bin

(PHP 7 >= 7.2.0)

sodium_base642bin — Description

Description

sodium_base642bin ( string $b64 , int $id [, string $ignore ] ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

b64

id

ignore

Return Values


Description

  • « sodium_base642bin
  • sodium_bin2hex »
  • PHP Manual
  • Sodium Functions
  • Description

sodium_bin2base64

(PHP 7 >= 7.2.0)

sodium_bin2base64 — Description

Description

sodium_bin2base64 ( string $bin , int $id ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

bin

id

Return Values


Encode to hexadecimal

  • « sodium_bin2base64
  • sodium_compare »
  • PHP Manual
  • Sodium Functions
  • Encode to hexadecimal

sodium_bin2hex

(PHP 7 >= 7.2.0)

sodium_bin2hex — Encode to hexadecimal

Description

sodium_bin2hex ( string $bin ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

bin

Return Values


Compare large numbers

  • « sodium_bin2hex
  • sodium_crypto_aead_aes256gcm_decrypt »
  • PHP Manual
  • Sodium Functions
  • Compare large numbers

sodium_compare

(PHP 7 >= 7.2.0)

sodium_compare — Compare large numbers

Description

sodium_compare ( string $buf1 , string $buf2 ) : int

Warning

This function is currently not documented; only its argument list is available.

Parameters

buf1

buf2

Return Values


Decrypt in combined mode with precalculation

  • « sodium_compare
  • sodium_crypto_aead_aes256gcm_encrypt »
  • PHP Manual
  • Sodium Functions
  • Decrypt in combined mode with precalculation

sodium_crypto_aead_aes256gcm_decrypt

(PHP 7 >= 7.2.0)

sodium_crypto_aead_aes256gcm_decrypt — Decrypt in combined mode with precalculation

Description

sodium_crypto_aead_aes256gcm_decrypt ( string $ciphertext , string $ad , string $nonce , string $key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

ciphertext

ad

nonce

key

Return Values


Encrypt in combined mode with precalculation

  • « sodium_crypto_aead_aes256gcm_decrypt
  • sodium_crypto_aead_aes256gcm_is_available »
  • PHP Manual
  • Sodium Functions
  • Encrypt in combined mode with precalculation

sodium_crypto_aead_aes256gcm_encrypt

(PHP 7 >= 7.2.0)

sodium_crypto_aead_aes256gcm_encrypt — Encrypt in combined mode with precalculation

Description

sodium_crypto_aead_aes256gcm_encrypt ( string $msg , string $ad , string $nonce , string $key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

msg

ad

nonce

key

Return Values


Check if hardware supports AES256-GCM

  • « sodium_crypto_aead_aes256gcm_encrypt
  • sodium_crypto_aead_aes256gcm_keygen »
  • PHP Manual
  • Sodium Functions
  • Check if hardware supports AES256-GCM

sodium_crypto_aead_aes256gcm_is_available

(PHP 7 >= 7.2.0)

sodium_crypto_aead_aes256gcm_is_available — Check if hardware supports AES256-GCM

Description

sodium_crypto_aead_aes256gcm_is_available ( void ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Get random bytes for key

  • « sodium_crypto_aead_aes256gcm_is_available
  • sodium_crypto_aead_chacha20poly1305_decrypt »
  • PHP Manual
  • Sodium Functions
  • Get random bytes for key

sodium_crypto_aead_aes256gcm_keygen

(PHP 7 >= 7.2.0)

sodium_crypto_aead_aes256gcm_keygen — Get random bytes for key

Description

sodium_crypto_aead_aes256gcm_keygen ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Verify that the ciphertext includes a valid tag

  • « sodium_crypto_aead_aes256gcm_keygen
  • sodium_crypto_aead_chacha20poly1305_encrypt »
  • PHP Manual
  • Sodium Functions
  • Verify that the ciphertext includes a valid tag

sodium_crypto_aead_chacha20poly1305_decrypt

(PHP 7 >= 7.2.0)

sodium_crypto_aead_chacha20poly1305_decrypt — Verify that the ciphertext includes a valid tag

Description

sodium_crypto_aead_chacha20poly1305_decrypt ( string $ciphertext , string $ad , string $nonce , string $key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

ciphertext

ad

nonce

key

Return Values


Encrypt a message

  • « sodium_crypto_aead_chacha20poly1305_decrypt
  • sodium_crypto_aead_chacha20poly1305_ietf_decrypt »
  • PHP Manual
  • Sodium Functions
  • Encrypt a message

sodium_crypto_aead_chacha20poly1305_encrypt

(PHP 7 >= 7.2.0)

sodium_crypto_aead_chacha20poly1305_encrypt — Encrypt a message

Description

sodium_crypto_aead_chacha20poly1305_encrypt ( string $msg , string $ad , string $nonce , string $key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

msg

ad

nonce

key

Return Values


Verify that the ciphertext includes a valid tag

  • « sodium_crypto_aead_chacha20poly1305_encrypt
  • sodium_crypto_aead_chacha20poly1305_ietf_encrypt »
  • PHP Manual
  • Sodium Functions
  • Verify that the ciphertext includes a valid tag

sodium_crypto_aead_chacha20poly1305_ietf_decrypt

(PHP 7 >= 7.2.0)

sodium_crypto_aead_chacha20poly1305_ietf_decrypt — Verify that the ciphertext includes a valid tag

Description

sodium_crypto_aead_chacha20poly1305_ietf_decrypt ( string $ciphertext , string $ad , string $nonce , string $key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

ciphertext

ad

nonce

key

Return Values


Encrypt a message

  • « sodium_crypto_aead_chacha20poly1305_ietf_decrypt
  • sodium_crypto_aead_chacha20poly1305_ietf_keygen »
  • PHP Manual
  • Sodium Functions
  • Encrypt a message

sodium_crypto_aead_chacha20poly1305_ietf_encrypt

(PHP 7 >= 7.2.0)

sodium_crypto_aead_chacha20poly1305_ietf_encrypt — Encrypt a message

Description

sodium_crypto_aead_chacha20poly1305_ietf_encrypt ( string $msg , string $ad , string $nonce , string $key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

msg

ad

nonce

key

Return Values


Get random bytes for key

  • « sodium_crypto_aead_chacha20poly1305_ietf_encrypt
  • sodium_crypto_aead_chacha20poly1305_keygen »
  • PHP Manual
  • Sodium Functions
  • Get random bytes for key

sodium_crypto_aead_chacha20poly1305_ietf_keygen

(PHP 7 >= 7.2.0)

sodium_crypto_aead_chacha20poly1305_ietf_keygen — Get random bytes for key

Description

sodium_crypto_aead_chacha20poly1305_ietf_keygen ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Get random bytes for key

  • « sodium_crypto_aead_chacha20poly1305_ietf_keygen
  • sodium_crypto_aead_xchacha20poly1305_ietf_decrypt »
  • PHP Manual
  • Sodium Functions
  • Get random bytes for key

sodium_crypto_aead_chacha20poly1305_keygen

(PHP 7 >= 7.2.0)

sodium_crypto_aead_chacha20poly1305_keygen — Get random bytes for key

Description

sodium_crypto_aead_chacha20poly1305_keygen ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « sodium_crypto_aead_chacha20poly1305_keygen
  • sodium_crypto_aead_xchacha20poly1305_ietf_encrypt »
  • PHP Manual
  • Sodium Functions
  • Description

sodium_crypto_aead_xchacha20poly1305_ietf_decrypt

(PHP 7 >= 7.2.0)

sodium_crypto_aead_xchacha20poly1305_ietf_decrypt — Description

Description

sodium_crypto_aead_xchacha20poly1305_ietf_decrypt ( string $ciphertext , string $ad , string $nonce , string $key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

ciphertext

ad

nonce

key

Return Values


Description

  • « sodium_crypto_aead_xchacha20poly1305_ietf_decrypt
  • sodium_crypto_aead_xchacha20poly1305_ietf_keygen »
  • PHP Manual
  • Sodium Functions
  • Description

sodium_crypto_aead_xchacha20poly1305_ietf_encrypt

(PHP 7 >= 7.2.0)

sodium_crypto_aead_xchacha20poly1305_ietf_encrypt — Description

Description

sodium_crypto_aead_xchacha20poly1305_ietf_encrypt ( string $msg , string $ad , string $nonce , string $key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

msg

ad

nonce

key

Return Values


Description

  • « sodium_crypto_aead_xchacha20poly1305_ietf_encrypt
  • sodium_crypto_auth_keygen »
  • PHP Manual
  • Sodium Functions
  • Description

sodium_crypto_aead_xchacha20poly1305_ietf_keygen

(PHP 7 >= 7.2.0)

sodium_crypto_aead_xchacha20poly1305_ietf_keygen — Description

Description

sodium_crypto_aead_xchacha20poly1305_ietf_keygen ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Get random bytes for key

  • « sodium_crypto_aead_xchacha20poly1305_ietf_keygen
  • sodium_crypto_auth_verify »
  • PHP Manual
  • Sodium Functions
  • Get random bytes for key

sodium_crypto_auth_keygen

(PHP 7 >= 7.2.0)

sodium_crypto_auth_keygen — Get random bytes for key

Description

sodium_crypto_auth_keygen ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Verifies that the tag is valid for the message

  • « sodium_crypto_auth_keygen
  • sodium_crypto_auth »
  • PHP Manual
  • Sodium Functions
  • Verifies that the tag is valid for the message

sodium_crypto_auth_verify

(PHP 7 >= 7.2.0)

sodium_crypto_auth_verify — Verifies that the tag is valid for the message

Description

sodium_crypto_auth_verify ( string $signature , string $msg , string $key ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

signature

msg

key

Return Values


Compute a tag for the message

  • « sodium_crypto_auth_verify
  • sodium_crypto_box_keypair_from_secretkey_and_publickey »
  • PHP Manual
  • Sodium Functions
  • Compute a tag for the message

sodium_crypto_auth

(PHP 7 >= 7.2.0)

sodium_crypto_auth — Compute a tag for the message

Description

sodium_crypto_auth ( string $msg , string $key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

msg

key

Return Values


Description

  • « sodium_crypto_auth
  • sodium_crypto_box_keypair »
  • PHP Manual
  • Sodium Functions
  • Description

sodium_crypto_box_keypair_from_secretkey_and_publickey

(PHP 7 >= 7.2.0)

sodium_crypto_box_keypair_from_secretkey_and_publickey — Description

Description

sodium_crypto_box_keypair_from_secretkey_and_publickey ( string $secret_key , string $public_key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

secret_key

public_key

Return Values


Randomly generate a secret key and a corresponding public key

  • « sodium_crypto_box_keypair_from_secretkey_and_publickey
  • sodium_crypto_box_open »
  • PHP Manual
  • Sodium Functions
  • Randomly generate a secret key and a corresponding public key

sodium_crypto_box_keypair

(PHP 7 >= 7.2.0)

sodium_crypto_box_keypair — Randomly generate a secret key and a corresponding public key

Description

sodium_crypto_box_keypair ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Verify and decrypt a ciphertext

  • « sodium_crypto_box_keypair
  • sodium_crypto_box_publickey_from_secretkey »
  • PHP Manual
  • Sodium Functions
  • Verify and decrypt a ciphertext

sodium_crypto_box_open

(PHP 7 >= 7.2.0)

sodium_crypto_box_open — Verify and decrypt a ciphertext

Description

sodium_crypto_box_open ( string $ciphertext , string $nonce , string $key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

ciphertext

nonce

key

Return Values


Description

  • « sodium_crypto_box_open
  • sodium_crypto_box_publickey »
  • PHP Manual
  • Sodium Functions
  • Description

sodium_crypto_box_publickey_from_secretkey

(PHP 7 >= 7.2.0)

sodium_crypto_box_publickey_from_secretkey — Description

Description

sodium_crypto_box_publickey_from_secretkey ( string $key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

key

Return Values


Description

  • « sodium_crypto_box_publickey_from_secretkey
  • sodium_crypto_box_seal_open »
  • PHP Manual
  • Sodium Functions
  • Description

sodium_crypto_box_publickey

(PHP 7 >= 7.2.0)

sodium_crypto_box_publickey — Description

Description

sodium_crypto_box_publickey ( string $key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

key

Return Values


Decrypt the ciphertext

  • « sodium_crypto_box_publickey
  • sodium_crypto_box_seal »
  • PHP Manual
  • Sodium Functions
  • Decrypt the ciphertext

sodium_crypto_box_seal_open

(PHP 7 >= 7.2.0)

sodium_crypto_box_seal_open — Decrypt the ciphertext

Description

sodium_crypto_box_seal_open ( string $ciphertext , string $key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

ciphertext

key

Return Values


Encrypt a message

  • « sodium_crypto_box_seal_open
  • sodium_crypto_box_secretkey »
  • PHP Manual
  • Sodium Functions
  • Encrypt a message

sodium_crypto_box_seal

(PHP 7 >= 7.2.0)

sodium_crypto_box_seal — Encrypt a message

Description

sodium_crypto_box_seal ( string $msg , string $key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

msg

key

Return Values


Description

  • « sodium_crypto_box_seal
  • sodium_crypto_box_seed_keypair »
  • PHP Manual
  • Sodium Functions
  • Description

sodium_crypto_box_secretkey

(PHP 7 >= 7.2.0)

sodium_crypto_box_secretkey — Description

Description

sodium_crypto_box_secretkey ( string $key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

key

Return Values


Deterministically derive the key pair from a single key

  • « sodium_crypto_box_secretkey
  • sodium_crypto_box »
  • PHP Manual
  • Sodium Functions
  • Deterministically derive the key pair from a single key

sodium_crypto_box_seed_keypair

(PHP 7 >= 7.2.0)

sodium_crypto_box_seed_keypair — Deterministically derive the key pair from a single key

Description

sodium_crypto_box_seed_keypair ( string $key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

key

Return Values


Encrypt a message

  • « sodium_crypto_box_seed_keypair
  • sodium_crypto_generichash_final »
  • PHP Manual
  • Sodium Functions
  • Encrypt a message

sodium_crypto_box

(PHP 7 >= 7.2.0)

sodium_crypto_box — Encrypt a message

Description

sodium_crypto_box ( string $msg , string $nonce , string $key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

msg

nonce

key

Return Values


Complete the hash

  • « sodium_crypto_box
  • sodium_crypto_generichash_init »
  • PHP Manual
  • Sodium Functions
  • Complete the hash

sodium_crypto_generichash_final

(PHP 7 >= 7.2.0)

sodium_crypto_generichash_final — Complete the hash

Description

sodium_crypto_generichash_final ( string &$state [, int $length = SODIUM_CRYPTO_GENERICHASH_BYTES ] ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

state

length

Return Values


Initialize a hash

  • « sodium_crypto_generichash_final
  • sodium_crypto_generichash_keygen »
  • PHP Manual
  • Sodium Functions
  • Initialize a hash

sodium_crypto_generichash_init

(PHP 7 >= 7.2.0)

sodium_crypto_generichash_init — Initialize a hash

Description

sodium_crypto_generichash_init ([ string $key [, int $length = SODIUM_CRYPTO_GENERICHASH_BYTES ]] ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

key

length

Return Values


Get random bytes for key

  • « sodium_crypto_generichash_init
  • sodium_crypto_generichash_update »
  • PHP Manual
  • Sodium Functions
  • Get random bytes for key

sodium_crypto_generichash_keygen

(PHP 7 >= 7.2.0)

sodium_crypto_generichash_keygen — Get random bytes for key

Description

sodium_crypto_generichash_keygen ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Add message to a hash

  • « sodium_crypto_generichash_keygen
  • sodium_crypto_generichash »
  • PHP Manual
  • Sodium Functions
  • Add message to a hash

sodium_crypto_generichash_update

(PHP 7 >= 7.2.0)

sodium_crypto_generichash_update — Add message to a hash

Description

sodium_crypto_generichash_update ( string &$state , string $msg ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

state

msg

Return Values


Get a hash of the message

  • « sodium_crypto_generichash_update
  • sodium_crypto_kdf_derive_from_key »
  • PHP Manual
  • Sodium Functions
  • Get a hash of the message

sodium_crypto_generichash

(PHP 7 >= 7.2.0)

sodium_crypto_generichash — Get a hash of the message

Description

sodium_crypto_generichash ( string $msg [, string $key [, int $length = SODIUM_CRYPTO_GENERICHASH_BYTES ]] ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

msg

key

length

Return Values


Derive a subkey

  • « sodium_crypto_generichash
  • sodium_crypto_kdf_keygen »
  • PHP Manual
  • Sodium Functions
  • Derive a subkey

sodium_crypto_kdf_derive_from_key

(PHP 7 >= 7.2.0)

sodium_crypto_kdf_derive_from_key — Derive a subkey

Description

sodium_crypto_kdf_derive_from_key ( int $subkey_len , int $subkey_id , string $context , string $key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

subkey_len

subkey_id

context

key

Return Values


Get random bytes for key

  • « sodium_crypto_kdf_derive_from_key
  • sodium_crypto_kx_client_session_keys »
  • PHP Manual
  • Sodium Functions
  • Get random bytes for key

sodium_crypto_kdf_keygen

(PHP 7 >= 7.2.0)

sodium_crypto_kdf_keygen — Get random bytes for key

Description

sodium_crypto_kdf_keygen ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « sodium_crypto_kdf_keygen
  • sodium_crypto_kx_keypair »
  • PHP Manual
  • Sodium Functions
  • Description

sodium_crypto_kx_client_session_keys

(PHP 7 >= 7.2.0)

sodium_crypto_kx_client_session_keys — Description

Description

sodium_crypto_kx_client_session_keys ( string $client_keypair , string $server_key ) : array

Warning

This function is currently not documented; only its argument list is available.

Parameters

client_keypair

server_key

Return Values


Creates a new sodium keypair

  • « sodium_crypto_kx_client_session_keys
  • sodium_crypto_kx_publickey »
  • PHP Manual
  • Sodium Functions
  • Creates a new sodium keypair

sodium_crypto_kx_keypair

(PHP 7 >= 7.2.0)

sodium_crypto_kx_keypair — Creates a new sodium keypair

Description

sodium_crypto_kx_keypair ( void ) : 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", bin2hex($secret), bin2hex($public));
?>

The above example will output something similar to:

secret: e7c5c918fdc40762e6000542c0118f4368ce8fd242b0e48c1e17202797a25daf
public: d1f59fda8652caf40ed1a01d2b6f3802b60846986372cd8fa337b7c12c428b18


Description

  • « sodium_crypto_kx_keypair
  • sodium_crypto_kx_secretkey »
  • PHP Manual
  • Sodium Functions
  • Description

sodium_crypto_kx_publickey

(PHP 7 >= 7.2.0)

sodium_crypto_kx_publickey — Description

Description

sodium_crypto_kx_publickey ( string $key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

key

Return Values


Description

  • « sodium_crypto_kx_publickey
  • sodium_crypto_kx_seed_keypair »
  • PHP Manual
  • Sodium Functions
  • Description

sodium_crypto_kx_secretkey

(PHP 7 >= 7.2.0)

sodium_crypto_kx_secretkey — Description

Description

sodium_crypto_kx_secretkey ( string $key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

key

Return Values


Description

  • « sodium_crypto_kx_secretkey
  • sodium_crypto_kx_server_session_keys »
  • PHP Manual
  • Sodium Functions
  • Description

sodium_crypto_kx_seed_keypair

(PHP 7 >= 7.2.0)

sodium_crypto_kx_seed_keypair — Description

Description

sodium_crypto_kx_seed_keypair ( string $string ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

string

Return Values


Description

  • « sodium_crypto_kx_seed_keypair
  • sodium_crypto_pwhash_scryptsalsa208sha256_str_verify »
  • PHP Manual
  • Sodium Functions
  • Description

sodium_crypto_kx_server_session_keys

(PHP 7 >= 7.2.0)

sodium_crypto_kx_server_session_keys — Description

Description

sodium_crypto_kx_server_session_keys ( string $server_keypair , string $client_key ) : array

Warning

This function is currently not documented; only its argument list is available.

Parameters

server_keypair

client_key

Return Values


Verify that the password is a valid password verification string

  • « sodium_crypto_kx_server_session_keys
  • sodium_crypto_pwhash_scryptsalsa208sha256_str »
  • PHP Manual
  • Sodium Functions
  • Verify that the password is a valid password verification string

sodium_crypto_pwhash_scryptsalsa208sha256_str_verify

(PHP 7 >= 7.2.0)

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 , string $password ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

hash

password

Return Values


Get an ASCII encoded hash

  • « sodium_crypto_pwhash_scryptsalsa208sha256_str_verify
  • sodium_crypto_pwhash_scryptsalsa208sha256 »
  • PHP Manual
  • Sodium Functions
  • Get an ASCII encoded hash

sodium_crypto_pwhash_scryptsalsa208sha256_str

(PHP 7 >= 7.2.0)

sodium_crypto_pwhash_scryptsalsa208sha256_str — Get an ASCII encoded hash

Description

sodium_crypto_pwhash_scryptsalsa208sha256_str ( 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


Derives a key from a password

  • « sodium_crypto_pwhash_scryptsalsa208sha256_str
  • sodium_crypto_pwhash_str_needs_rehash »
  • PHP Manual
  • Sodium Functions
  • Derives a key from a password

sodium_crypto_pwhash_scryptsalsa208sha256

(PHP 7 >= 7.2.0)

sodium_crypto_pwhash_scryptsalsa208sha256 — Derives a key from a password

Description

sodium_crypto_pwhash_scryptsalsa208sha256 ( int $length , string $password , string $salt , int $opslimit , int $memlimit ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

length

password

salt

opslimit

memlimit

Return Values


Description

  • « sodium_crypto_pwhash_scryptsalsa208sha256
  • sodium_crypto_pwhash_str_verify »
  • PHP Manual
  • Sodium Functions
  • Description

sodium_crypto_pwhash_str_needs_rehash

(PHP 7 >= 7.2.0)

sodium_crypto_pwhash_str_needs_rehash — Description

Description

sodium_crypto_pwhash_str_needs_rehash ( string $password , int $opslimit , int $memlimit ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

password

opslimit

memlimit

Return Values


Verifies that a password matches a hash

  • « sodium_crypto_pwhash_str_needs_rehash
  • sodium_crypto_pwhash_str »
  • PHP Manual
  • Sodium Functions
  • Verifies that a password matches a hash

sodium_crypto_pwhash_str_verify

(PHP 7 >= 7.2.0)

sodium_crypto_pwhash_str_verify — Verifies that a password matches a hash

Description

sodium_crypto_pwhash_str_verify ( string $hash , 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_hash() 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


Get an ASCII-encoded hash

  • « sodium_crypto_pwhash_str_verify
  • sodium_crypto_pwhash »
  • PHP Manual
  • Sodium Functions
  • Get an ASCII-encoded hash

sodium_crypto_pwhash_str

(PHP 7 >= 7.2.0)

sodium_crypto_pwhash_str — Get an ASCII-encoded hash

Description

sodium_crypto_pwhash_str ( 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, or FALSE on failure.

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.

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.

Examples

Example #1 password_hash() 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

See Also

  • sodium_crypto_pwhash_str_verify() - Verifies that a password matches a hash
  • sodium_crypto_pwhash() - Derive a key from a password
  • password_hash() - Creates a password hash
  • password_verify() - Verifies that a password matches a hash
  • » Libsodium Argon2 docs


Derive a key from a password

  • « sodium_crypto_pwhash_str
  • sodium_crypto_scalarmult_base »
  • PHP Manual
  • Sodium Functions
  • Derive a key from a password

sodium_crypto_pwhash

(PHP 7 >= 7.2.0)

sodium_crypto_pwhash — Derive a key from a password

Description

sodium_crypto_pwhash ( int $length , string $password , string $salt , int $opslimit , int $memlimit [, int $alg ] ) : 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.

Parameters

length

integer; The length of the password hash to generate, in bytes.

password

string; The password to generate a hash for.

salt

string A salt to add to the password before hashing. The salt should be unpredictable, ideally generated from a good random mumber source such as random_bytes(), and have a length of at least 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.

alg

integer 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, or FALSE on failure. 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 password_hash() 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


Alias of sodium_crypto_box_publickey_from_secretkey

  • « sodium_crypto_pwhash
  • sodium_crypto_scalarmult »
  • PHP Manual
  • Sodium Functions
  • Alias of sodium_crypto_box_publickey_from_secretkey

sodium_crypto_scalarmult_base

(PHP 7 >= 7.2.0)

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


Compute a shared secret given a user's secret key and another user's public key

  • « sodium_crypto_scalarmult_base
  • sodium_crypto_secretbox_keygen »
  • PHP Manual
  • Sodium Functions
  • Compute a shared secret given a user's secret key and another user's public key

sodium_crypto_scalarmult

(PHP 7 >= 7.2.0)

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

Warning

This function is currently not documented; only its argument list is available.

Parameters

n

p

Return Values


Get random bytes for key

  • « sodium_crypto_scalarmult
  • sodium_crypto_secretbox_open »
  • PHP Manual
  • Sodium Functions
  • Get random bytes for key

sodium_crypto_secretbox_keygen

(PHP 7 >= 7.2.0)

sodium_crypto_secretbox_keygen — Get random bytes for key

Description

sodium_crypto_secretbox_keygen ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Verify and decrypt a ciphertext

  • « sodium_crypto_secretbox_keygen
  • sodium_crypto_secretbox »
  • PHP Manual
  • Sodium Functions
  • Verify and decrypt a ciphertext

sodium_crypto_secretbox_open

(PHP 7 >= 7.2.0)

sodium_crypto_secretbox_open — Verify and decrypt a ciphertext

Description

sodium_crypto_secretbox_open ( string $ciphertext , string $nonce , string $key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

ciphertext

nonce

key

Return Values


Encrypt a message

  • « sodium_crypto_secretbox_open
  • sodium_crypto_secretstream_xchacha20poly1305_init_pull »
  • PHP Manual
  • Sodium Functions
  • Encrypt a message

sodium_crypto_secretbox

(PHP 7 >= 7.2.0)

sodium_crypto_secretbox — Encrypt a message

Description

sodium_crypto_secretbox ( string $string , string $nonce , string $key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

string

nonce

key

Return Values


Description

  • « sodium_crypto_secretbox
  • sodium_crypto_secretstream_xchacha20poly1305_init_push »
  • PHP Manual
  • Sodium Functions
  • Description

sodium_crypto_secretstream_xchacha20poly1305_init_pull

(PHP 7 >= 7.2.0)

sodium_crypto_secretstream_xchacha20poly1305_init_pull — Description

Description

sodium_crypto_secretstream_xchacha20poly1305_init_pull ( string $header , string $key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

header

key

Return Values


Description

  • « sodium_crypto_secretstream_xchacha20poly1305_init_pull
  • sodium_crypto_secretstream_xchacha20poly1305_keygen »
  • PHP Manual
  • Sodium Functions
  • Description

sodium_crypto_secretstream_xchacha20poly1305_init_push

(PHP 7 >= 7.2.0)

sodium_crypto_secretstream_xchacha20poly1305_init_push — Description

Description

sodium_crypto_secretstream_xchacha20poly1305_init_push ( string $key ) : array

Warning

This function is currently not documented; only its argument list is available.

Parameters

key

Return Values


Description

  • « sodium_crypto_secretstream_xchacha20poly1305_init_push
  • sodium_crypto_secretstream_xchacha20poly1305_pull »
  • PHP Manual
  • Sodium Functions
  • Description

sodium_crypto_secretstream_xchacha20poly1305_keygen

(PHP 7 >= 7.2.0)

sodium_crypto_secretstream_xchacha20poly1305_keygen — Description

Description

sodium_crypto_secretstream_xchacha20poly1305_keygen ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « sodium_crypto_secretstream_xchacha20poly1305_keygen
  • sodium_crypto_secretstream_xchacha20poly1305_push »
  • PHP Manual
  • Sodium Functions
  • Description

sodium_crypto_secretstream_xchacha20poly1305_pull

(PHP 7 >= 7.2.0)

sodium_crypto_secretstream_xchacha20poly1305_pull — Description

Description

sodium_crypto_secretstream_xchacha20poly1305_pull ( string &$state , string $c [, string $ad ] ) : array

Warning

This function is currently not documented; only its argument list is available.

Parameters

state

c

ad

Return Values


Description

  • « sodium_crypto_secretstream_xchacha20poly1305_pull
  • sodium_crypto_secretstream_xchacha20poly1305_rekey »
  • PHP Manual
  • Sodium Functions
  • Description

sodium_crypto_secretstream_xchacha20poly1305_push

(PHP 7 >= 7.2.0)

sodium_crypto_secretstream_xchacha20poly1305_push — Description

Description

sodium_crypto_secretstream_xchacha20poly1305_push ( string &$state , string $msg [, string $ad [, int $tag ]] ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

state

msg

ad

tag

Return Values


Description

  • « sodium_crypto_secretstream_xchacha20poly1305_push
  • sodium_crypto_shorthash_keygen »
  • PHP Manual
  • Sodium Functions
  • Description

sodium_crypto_secretstream_xchacha20poly1305_rekey

(PHP 7 >= 7.2.0)

sodium_crypto_secretstream_xchacha20poly1305_rekey — Description

Description

sodium_crypto_secretstream_xchacha20poly1305_rekey ( string &$state ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

state

Return Values


Get random bytes for key

  • « sodium_crypto_secretstream_xchacha20poly1305_rekey
  • sodium_crypto_shorthash »
  • PHP Manual
  • Sodium Functions
  • Get random bytes for key

sodium_crypto_shorthash_keygen

(PHP 7 >= 7.2.0)

sodium_crypto_shorthash_keygen — Get random bytes for key

Description

sodium_crypto_shorthash_keygen ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Compute a fixed-size fingerprint for the message

  • « sodium_crypto_shorthash_keygen
  • sodium_crypto_sign_detached »
  • PHP Manual
  • Sodium Functions
  • Compute a fixed-size fingerprint for the message

sodium_crypto_shorthash

(PHP 7 >= 7.2.0)

sodium_crypto_shorthash — Compute a fixed-size fingerprint for the message

Description

sodium_crypto_shorthash ( string $msg , string $key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

msg

key

Return Values


Sign the message

  • « sodium_crypto_shorthash
  • sodium_crypto_sign_ed25519_pk_to_curve25519 »
  • PHP Manual
  • Sodium Functions
  • Sign the message

sodium_crypto_sign_detached

(PHP 7 >= 7.2.0)

sodium_crypto_sign_detached — Sign the message

Description

sodium_crypto_sign_detached ( string $msg , string $secretkey ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

msg

secretkey

Return Values


Convert an Ed25519 public key to a Curve25519 public key

  • « sodium_crypto_sign_detached
  • sodium_crypto_sign_ed25519_sk_to_curve25519 »
  • PHP Manual
  • Sodium Functions
  • Convert an Ed25519 public key to a Curve25519 public key

sodium_crypto_sign_ed25519_pk_to_curve25519

(PHP 7 >= 7.2.0)

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 $key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

key

Return Values


Convert an Ed25519 secret key to a Curve25519 secret key

  • « sodium_crypto_sign_ed25519_pk_to_curve25519
  • sodium_crypto_sign_keypair_from_secretkey_and_publickey »
  • PHP Manual
  • Sodium Functions
  • Convert an Ed25519 secret key to a Curve25519 secret key

sodium_crypto_sign_ed25519_sk_to_curve25519

(PHP 7 >= 7.2.0)

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 ( string $key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

key

Return Values


Description

  • « sodium_crypto_sign_ed25519_sk_to_curve25519
  • sodium_crypto_sign_keypair »
  • PHP Manual
  • Sodium Functions
  • Description

sodium_crypto_sign_keypair_from_secretkey_and_publickey

(PHP 7 >= 7.2.0)

sodium_crypto_sign_keypair_from_secretkey_and_publickey — Description

Description

sodium_crypto_sign_keypair_from_secretkey_and_publickey ( string $secret_key , string $public_key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

secret_key

public_key

Return Values


Randomly generate a secret key and a corresponding public key

  • « sodium_crypto_sign_keypair_from_secretkey_and_publickey
  • sodium_crypto_sign_open »
  • PHP Manual
  • Sodium Functions
  • Randomly generate a secret key and a corresponding public key

sodium_crypto_sign_keypair

(PHP 7 >= 7.2.0)

sodium_crypto_sign_keypair — Randomly generate a secret key and a corresponding public key

Description

sodium_crypto_sign_keypair ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Check that the signed message has a valid signature

  • « sodium_crypto_sign_keypair
  • sodium_crypto_sign_publickey_from_secretkey »
  • PHP Manual
  • Sodium Functions
  • Check that the signed message has a valid signature

sodium_crypto_sign_open

(PHP 7 >= 7.2.0)

sodium_crypto_sign_open — Check that the signed message has a valid signature

Description

sodium_crypto_sign_open ( string $string , string $public_key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

string

public_key

Return Values


Extract the public key from the secret key

  • « sodium_crypto_sign_open
  • sodium_crypto_sign_publickey »
  • PHP Manual
  • Sodium Functions
  • Extract the public key from the secret key

sodium_crypto_sign_publickey_from_secretkey

(PHP 7 >= 7.2.0)

sodium_crypto_sign_publickey_from_secretkey — Extract the public key from the secret key

Description

sodium_crypto_sign_publickey_from_secretkey ( string $key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

key

Return Values


Description

  • « sodium_crypto_sign_publickey_from_secretkey
  • sodium_crypto_sign_secretkey »
  • PHP Manual
  • Sodium Functions
  • Description

sodium_crypto_sign_publickey

(PHP 7 >= 7.2.0)

sodium_crypto_sign_publickey — Description

Description

sodium_crypto_sign_publickey ( string $keypair ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

keypair

Return Values


Description

  • « sodium_crypto_sign_publickey
  • sodium_crypto_sign_seed_keypair »
  • PHP Manual
  • Sodium Functions
  • Description

sodium_crypto_sign_secretkey

(PHP 7 >= 7.2.0)

sodium_crypto_sign_secretkey — Description

Description

sodium_crypto_sign_secretkey ( string $key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

key

Return Values


Deterministically derive the key pair from a single key

  • « sodium_crypto_sign_secretkey
  • sodium_crypto_sign_verify_detached »
  • PHP Manual
  • Sodium Functions
  • Deterministically derive the key pair from a single key

sodium_crypto_sign_seed_keypair

(PHP 7 >= 7.2.0)

sodium_crypto_sign_seed_keypair — Deterministically derive the key pair from a single key

Description

sodium_crypto_sign_seed_keypair ( string $key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

key

Return Values


Verify signature for the message

  • « sodium_crypto_sign_seed_keypair
  • sodium_crypto_sign »
  • PHP Manual
  • Sodium Functions
  • Verify signature for the message

sodium_crypto_sign_verify_detached

(PHP 7 >= 7.2.0)

sodium_crypto_sign_verify_detached — Verify signature for the message

Description

sodium_crypto_sign_verify_detached ( string $signature , string $msg , string $public_key ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

signature

msg

public_key

Return Values


Sign a message

  • « sodium_crypto_sign_verify_detached
  • sodium_crypto_stream_keygen »
  • PHP Manual
  • Sodium Functions
  • Sign a message

sodium_crypto_sign

(PHP 7 >= 7.2.0)

sodium_crypto_sign — Sign a message

Description

sodium_crypto_sign ( string $msg , string $secret_key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

msg

secret_key

Return Values


Get random bytes for key

  • « sodium_crypto_sign
  • sodium_crypto_stream_xor »
  • PHP Manual
  • Sodium Functions
  • Get random bytes for key

sodium_crypto_stream_keygen

(PHP 7 >= 7.2.0)

sodium_crypto_stream_keygen — Get random bytes for key

Description

sodium_crypto_stream_keygen ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Encrypt a message

  • « sodium_crypto_stream_keygen
  • sodium_crypto_stream »
  • PHP Manual
  • Sodium Functions
  • Encrypt a message

sodium_crypto_stream_xor

(PHP 7 >= 7.2.0)

sodium_crypto_stream_xor — Encrypt a message

Description

sodium_crypto_stream_xor ( string $msg , string $nonce , string $key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

msg

nonce

key

Return Values


Generate a deterministic sequence of bytes from a seed

  • « sodium_crypto_stream_xor
  • sodium_hex2bin »
  • PHP Manual
  • Sodium Functions
  • Generate a deterministic sequence of bytes from a seed

sodium_crypto_stream

(PHP 7 >= 7.2.0)

sodium_crypto_stream — Generate a deterministic sequence of bytes from a seed

Description

sodium_crypto_stream ( int $length , string $nonce , string $key ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

length

nonce

key

Return Values


Decodes a hexadecimally encoded binary string

  • « sodium_crypto_stream
  • sodium_increment »
  • PHP Manual
  • Sodium Functions
  • Decodes a hexadecimally encoded binary string

sodium_hex2bin

(PHP 7 >= 7.2.0)

sodium_hex2bin — Decodes a hexadecimally encoded binary string

Description

sodium_hex2bin ( string $hex [, 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

hex

Hexadecimal representation of data.

ignore

Optional string argument for characters to ignore.

Return Values

Returns the binary representation of the given hex data.


Increment large number

  • « sodium_hex2bin
  • sodium_memcmp »
  • PHP Manual
  • Sodium Functions
  • Increment large number

sodium_increment

(PHP 7 >= 7.2.0)

sodium_increment — Increment large number

Description

sodium_increment ( string &$val ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

val

Return Values


Test for equality in constant-time

  • « sodium_increment
  • sodium_memzero »
  • PHP Manual
  • Sodium Functions
  • Test for equality in constant-time

sodium_memcmp

(PHP 7 >= 7.2.0)

sodium_memcmp — Test for equality in constant-time

Description

sodium_memcmp ( string $buf1 , string $buf2 ) : int

Warning

This function is currently not documented; only its argument list is available.

Parameters

buf1

buf2

Return Values


Overwrite buf with zeros

  • « sodium_memcmp
  • sodium_pad »
  • PHP Manual
  • Sodium Functions
  • Overwrite buf with zeros

sodium_memzero

(PHP 7 >= 7.2.0)

sodium_memzero — Overwrite buf with zeros

Description

sodium_memzero ( string &$buf ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

buf

Return Values


Add padding data

  • « sodium_memzero
  • sodium_unpad »
  • PHP Manual
  • Sodium Functions
  • Add padding data

sodium_pad

(PHP 7 >= 7.2.0)

sodium_pad — Add padding data

Description

sodium_pad ( string $unpadded , int $length ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

unpadded

length

Return Values


Remove padding data

  • « sodium_pad
  • Database Extensions »
  • PHP Manual
  • Sodium Functions
  • Remove padding data

sodium_unpad

(PHP 7 >= 7.2.0)

sodium_unpad — Remove padding data

Description

sodium_unpad ( string $padded , int $length ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

padded

length

Return Values


Database Extensions

  • Abstraction Layers
    • DBA — Database (dbm-style) Abstraction Layer
    • dbx
    • ODBC — ODBC (Unified)
    • PDO — PHP Data Objects
  • Vendor Specific Database Extensions
    • CUBRID
    • DB++
    • dBase
    • filePro
    • Firebird/InterBase
    • FrontBase
    • IBM DB2 — IBM DB2, Cloudscape and Apache Derby
    • Informix
    • Ingres — Ingres DBMS, EDBC, and Enterprise Access Gateways
    • MaxDB
    • Mongo — MongoDB driver (legacy)
    • MongoDB — MongoDB driver
    • mSQL
    • Mssql — Microsoft SQL Server
    • MySQL — MySQL Drivers and Plugins
    • OCI8 — Oracle OCI8
    • Paradox — Paradox File Access
    • PostgreSQL
    • SQLite
    • SQLite3
    • SQLSRV — Microsoft SQL Server Driver for PHP
    • Sybase
    • tokyo_tyrant


Abstraction Layers

  • DBA — Database (dbm-style) Abstraction Layer
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • DBA Functions
  • dbx
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • dbx Functions
  • ODBC — ODBC (Unified)
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • ODBC Functions
  • PDO — PHP Data Objects
    • Introduction
    • 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
    • PDOException — The PDOException class
    • PDO Drivers


Database (dbm-style) Abstraction Layer

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
  • 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


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.


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 | This is available since PHP 5.4.0. 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:

This was added in PHP 5.4.0. 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 | PHP_INI_ALL |

Here's a short explanation of the configuration directives.

dba.default_handler string

The name of the default handler


Resource Types

The functions dba_open() and dba_popen() return a handle to the specified database file to access which is used by all other dba-function calls.


  • « Resource Types
  • Examples »
  • PHP Manual
  • DBA
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


  • « Predefined Constants
  • Basic usage »
  • PHP Manual
  • DBA
  • Examples

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

?>


DBA Functions

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


Close a DBA database

  • « DBA Functions
  • dba_delete »
  • PHP Manual
  • DBA Functions
  • Close a DBA database

dba_close

(PHP 4, PHP 5, PHP 7)

dba_close — Close a DBA database

Description

dba_close ( resource $handle ) : void

dba_close() closes the established database and frees all resources of the specified database handle.

Parameters

handle

The database handler, returned by dba_open() or dba_popen().

Return Values

No value is returned.

See Also

  • dba_open() - Open database
  • dba_popen() - Open database persistently


Delete DBA entry specified by key

  • « dba_close
  • dba_exists »
  • PHP Manual
  • DBA Functions
  • Delete DBA entry specified by key

dba_delete

(PHP 4, PHP 5, PHP 7)

dba_delete — Delete DBA entry specified by key

Description

dba_delete ( string $key , resource $handle ) : bool

dba_delete() deletes the specified entry from the database.

Parameters

key

The key of the entry which is deleted.

handle

The database handler, returned by dba_open() or dba_popen().

Return Values

Returns TRUE on success or FALSE on failure.

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


Check whether key exists

  • « dba_delete
  • dba_fetch »
  • PHP Manual
  • DBA Functions
  • Check whether key exists

dba_exists

(PHP 4, PHP 5, PHP 7)

dba_exists — Check whether key exists

Description

dba_exists ( string $key , resource $handle ) : bool

dba_exists() checks whether the specified key exists in the database.

Parameters

key

The key the check is performed for.

handle

The database handler, returned by dba_open() or dba_popen().

Return Values

Returns TRUE if the key exists, FALSE otherwise.

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


Fetch data specified by key

  • « dba_exists
  • dba_firstkey »
  • PHP Manual
  • DBA Functions
  • Fetch data specified by key

dba_fetch

(PHP 4, PHP 5, PHP 7)

dba_fetch — Fetch data specified by key

Description

dba_fetch ( string $key , resource $handle ) : string
dba_fetch ( string $key , int $skip , resource $handle ) : string

dba_fetch() fetches the data specified by key from the database specified with handle.

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

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.

handle

The database handler, returned by dba_open() or dba_popen().

Return Values

Returns the associated string if the key/data pair is found, FALSE otherwise.

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


Fetch first key

  • « dba_fetch
  • dba_handlers »
  • PHP Manual
  • DBA Functions
  • Fetch first key

dba_firstkey

(PHP 4, PHP 5, PHP 7)

dba_firstkey — Fetch first key

Description

dba_firstkey ( resource $handle ) : string

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

handle

The database handler, returned by dba_open() or dba_popen().

Return Values

Returns the key on success or FALSE on failure.

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


List all the handlers available

  • « dba_firstkey
  • dba_insert »
  • PHP Manual
  • DBA Functions
  • List all the handlers available

dba_handlers

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

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


Insert entry

  • « dba_handlers
  • dba_key_split »
  • PHP Manual
  • DBA Functions
  • Insert entry

dba_insert

(PHP 4, PHP 5, PHP 7)

dba_insert — Insert entry

Description

dba_insert ( string $key , string $value , resource $handle ) : 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.

handle

The database handler, returned by dba_open() or dba_popen().

Return Values

Returns TRUE on success or FALSE on failure.

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


Splits a key in string representation into array representation

  • « dba_insert
  • dba_list »
  • PHP Manual
  • DBA Functions
  • Splits a key in string representation into array representation

dba_key_split

(PHP 5, PHP 7)

dba_key_split — Splits a key in string representation into array representation

Description

dba_key_split ( mixed $key ) : mixed

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.

See Also

  • dba_firstkey() - Fetch first key
  • dba_nextkey() - Fetch next key
  • dba_fetch() - Fetch data specified by key


List all open database files

  • « dba_key_split
  • dba_nextkey »
  • PHP Manual
  • DBA Functions
  • List all open database files

dba_list

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

dba_list — List all open database files

Description

dba_list ( void ) : array

dba_list() list all open database files.

Return Values

An associative array, in the form resourceid => filename.


Fetch next key

  • « dba_list
  • dba_open »
  • PHP Manual
  • DBA Functions
  • Fetch next key

dba_nextkey

(PHP 4, PHP 5, PHP 7)

dba_nextkey — Fetch next key

Description

dba_nextkey ( resource $handle ) : string

dba_nextkey() returns the next key of the database and advances the internal key pointer.

Parameters

handle

The database handler, returned by dba_open() or dba_popen().

Return Values

Returns the key on success or FALSE on failure.

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


Open database

  • « dba_nextkey
  • dba_optimize »
  • PHP Manual
  • DBA Functions
  • Open database

dba_open

(PHP 4, PHP 5, PHP 7)

dba_open — Open database

Description

dba_open ( string $path , string $mode [, string $handler [, string $... ]] ) : resource

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 successfull.
  • wait: the second call waits until dba_close() is called for the first.
  • false: the second call returns false.
  • illegal: you must not mix "l" and "d" modifiers for 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.

...

Optional string parameters which are passed to the driver.

The cdb, cdb_make, flatfile, inifile, qdbm and tcadb drivers do not support additional parameters.

The db1, db2, db3, db4, dbm, gdbm, and ndbm drivers supports a single additional parameter $filemode, which has the same meaning as the $mode parameter of chmod(), and defaults to 0644.

The lmdb driver accepts two additional parameters. The first allows to specify the $filemode (see description above), and the second to specify the $mapsize, where the value should be a multiple of the page size of the OS, or zero, to use the default mapsize. The $mapsize parameter is supported as of PHP 7.3.14 and 7.4.2, respectively.

Return Values

Returns a positive handle on success or FALSE on failure.

Changelog

Version | Description
7.3.14, 7.4.2 | The lmdb driver now supports an additional $mapsize parameter.

See Also

  • dba_popen() - Open database persistently
  • dba_close() - Close a DBA database


Optimize database

  • « dba_open
  • dba_popen »
  • PHP Manual
  • DBA Functions
  • Optimize database

dba_optimize

(PHP 4, PHP 5, PHP 7)

dba_optimize — Optimize database

Description

dba_optimize ( resource $handle ) : bool

dba_optimize() optimizes the underlying database.

Parameters

handle

The database handler, returned by dba_open() or dba_popen().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • dba_sync() - Synchronize database


Open database persistently

  • « dba_optimize
  • dba_replace »
  • PHP Manual
  • DBA Functions
  • Open database persistently

dba_popen

(PHP 4, PHP 5, PHP 7)

dba_popen — Open database persistently

Description

dba_popen ( string $path , string $mode [, string $handler [, mixed $... ]] ) : resource

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.

Return Values

Returns a positive handle on success or FALSE on failure.

See Also

  • dba_open() - Open database
  • dba_close() - Close a DBA database


Replace or insert entry

  • « dba_popen
  • dba_sync »
  • PHP Manual
  • DBA Functions
  • Replace or insert entry

dba_replace

(PHP 4, PHP 5, PHP 7)

dba_replace — Replace or insert entry

Description

dba_replace ( string $key , string $value , resource $handle ) : bool

dba_replace() replaces or inserts the entry described with key and value into the database specified by handle.

Parameters

key

The key of the entry to be replaced.

value

The value to be replaced.

handle

The database handler, returned by dba_open() or dba_popen().

Return Values

Returns TRUE on success or FALSE on failure.

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


Synchronize database

  • « dba_replace
  • dbx »
  • PHP Manual
  • DBA Functions
  • Synchronize database

dba_sync

(PHP 4, PHP 5, PHP 7)

dba_sync — Synchronize database

Description

dba_sync ( resource $handle ) : bool

dba_sync() synchronizes the database. This will probably trigger a physical write to the disk, if supported.

Parameters

handle

The database handler, returned by dba_open() or dba_popen().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • dba_optimize() - Optimize database


dbx

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • dbx Functions
    • dbx_close — Close an open connection/database
    • dbx_compare — Compare two rows for sorting purposes
    • dbx_connect — Open a connection/database
    • dbx_error — Report the error message of the latest function call in the module
    • dbx_escape_string — Escape a string so it can safely be used in an sql-statement
    • dbx_fetch_row — Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set
    • dbx_query — Send a query and fetch all results (if any)
    • dbx_sort — Sort a result from a dbx_query by a custom sort function


Introduction

The dbx module is a database abstraction layer (db 'X', where 'X' is a supported database). The dbx functions allow you to access all supported databases using a single calling convention. The dbx-functions themselves do not interface directly to the databases, but interface to the modules that are used to support these databases.

Note:

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.1.0.


Requirements

To be able to use a database with the dbx-module, the module must be either linked or loaded into PHP, and the database module must be supported by the dbx-module. Currently, the following databases are supported, but others will follow:

  • FrontBase
  • Microsoft SQL Server
  • MySQL
  • ODBC
  • PostgreSQL
  • Sybase-CT
  • Oracle (oci8)
  • SQLite

Documentation for adding additional database support to dbx can be found at » http://www.guidance.nl/php/dbx/doc/.


Installation

In order to have these functions available, you must compile PHP with dbx support by using the --enable-dbx option and all options for the databases that will be used, e.g. for MySQL you must also specify --with-mysql=[DIR] . To get other supported databases to work with the dbx-module refer to their specific documentation.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

DBX Configuration Options
Name | Default | Changeable | Changelog
dbx.colnames_case | "unchanged" | PHP_INI_SYSTEM | Removed in PHP 5.1.0.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

dbx.colnames_case string

Columns names can be returned "unchanged" or converted to "uppercase" or "lowercase". This directive can be overridden with a flag to dbx_query().


Resource Types

There are two resource types used in the dbx module. The first one is the link-object for a database connection, the second a result-object which holds the result of a query.


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.

DBX_MYSQL (integer)
DBX_ODBC (integer)
DBX_PGSQL (integer)
DBX_MSSQL (integer)
DBX_FBSQL (integer)
DBX_OCI8 (integer)
DBX_SYBASECT (integer)
DBX_SQLITE (integer)
DBX_PERSISTENT (integer)
DBX_RESULT_INFO (integer)
DBX_RESULT_INDEX (integer)
DBX_RESULT_ASSOC (integer)
DBX_RESULT_UNBUFFERED (integer)
DBX_COLNAMES_UNCHANGED (integer)
DBX_COLNAMES_UPPERCASE (integer)
DBX_COLNAMES_LOWERCASE (integer)
DBX_CMP_NATIVE (integer)
DBX_CMP_TEXT (integer)
DBX_CMP_NUMBER (integer)
DBX_CMP_ASC (integer)
DBX_CMP_DESC (integer)


dbx Functions

Table of Contents

  • dbx_close — Close an open connection/database
  • dbx_compare — Compare two rows for sorting purposes
  • dbx_connect — Open a connection/database
  • dbx_error — Report the error message of the latest function call in the module
  • dbx_escape_string — Escape a string so it can safely be used in an sql-statement
  • dbx_fetch_row — Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set
  • dbx_query — Send a query and fetch all results (if any)
  • dbx_sort — Sort a result from a dbx_query by a custom sort function


Close an open connection/database

  • « dbx Functions
  • dbx_compare »
  • PHP Manual
  • dbx Functions
  • Close an open connection/database

dbx_close

(PHP 4 >= 4.0.6, PHP 5 < 5.1.0, PECL dbx >= 1.1.0)

dbx_close — Close an open connection/database

Description

dbx_close ( object $link_identifier ) : int

Parameters

link_identifier

The DBX link object to close.

Return Values

Returns 1 on success and 0 on errors.

Examples

Example #1 dbx_close() example

<?php
$link = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password")
    or die("Could not connect");

echo "Connected successfully";
dbx_close($link);
?>

Notes

Note:

Always refer to the module-specific documentation as well.

See Also

  • dbx_connect() - Open a connection/database


Compare two rows for sorting purposes

  • « dbx_close
  • dbx_connect »
  • PHP Manual
  • dbx Functions
  • Compare two rows for sorting purposes

dbx_compare

(PHP 4 >= 4.1.0, PHP 5 < 5.1.0, PECL dbx >= 1.1.0)

dbx_compare — Compare two rows for sorting purposes

Description

dbx_compare ( array $row_a , array $row_b , string $column_key [, int $flags = DBX_CMP_ASC | DBX_CMP_NATIVE ] ) : int

dbx_compare() is a helper function for dbx_sort() to ease the make and use of the custom sorting function.

Parameters

row_a

First row

row_b

Second row

column_key

The compared column

flags

The flags can be set to specify comparison direction:

  • DBX_CMP_ASC - ascending order
  • DBX_CMP_DESC - descending order
and the preferred comparison type:
  • DBX_CMP_NATIVE - no type conversion
  • DBX_CMP_TEXT - compare items as strings
  • DBX_CMP_NUMBER - compare items numerically
One of the direction and one of the type constant can be combined with bitwise OR operator (|).

Return Values

Returns 0 if the row_a[$column_key] is equal to row_b[$column_key], and 1 or -1 if the former is greater or is smaller than the latter one, respectively, or vice versa if the flag is set to DBX_CMP_DESC.

Examples

Example #1 dbx_compare() example

<?php
function user_re_order($a, $b)
{
    $rv = dbx_compare($a, $b, "parentid", DBX_CMP_DESC);
    if (!$rv) {
        $rv = dbx_compare($a, $b, "id", DBX_CMP_NUMBER);
    }
    return $rv;
}

$link   = dbx_connect(DBX_ODBC, "", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, "SELECT id, parentid, description FROM table ORDER BY id");
    // data in $result is now ordered by id

dbx_sort($result, "user_re_order");
    // date in $result is now ordered by parentid (descending), then by id

dbx_close($link);
?>

See Also

  • dbx_sort() - Sort a result from a dbx_query by a custom sort function


Open a connection/database

  • « dbx_compare
  • dbx_error »
  • PHP Manual
  • dbx Functions
  • Open a connection/database

dbx_connect

(PHP 4 >= 4.0.6, PHP 5 < 5.1.0, PECL dbx >= 1.1.0)

dbx_connect — Open a connection/database

Description

dbx_connect ( mixed $module , string $host , string $database , string $username , string $password [, int $persistent ] ) : object

Opens a connection to a database.

Parameters

module

The module parameter can be either a string or a constant, though the latter form is preferred. The possible values are given below, but keep in mind that they only work if the module is actually loaded.

  • DBX_MYSQL or "mysql"
  • DBX_ODBC or "odbc"
  • DBX_PGSQL or "pgsql"
  • DBX_MSSQL or "mssql"
  • DBX_FBSQL or "fbsql"
  • DBX_SYBASECT or "sybase_ct"
  • DBX_OCI8 or "oci8"
  • DBX_SQLITE or "sqlite"

host

The SQL server host

database

The database name

username

The username

password

The password

persistent

The persistent parameter can be set to DBX_PERSISTENT, if so, a persistent connection will be created.

The host, database, username and password parameters are expected, but not always used depending on the connect functions for the abstracted module.

Return Values

Returns an object on success, FALSE on error. If a connection has been made but the database could not be selected, the connection is closed and FALSE is returned.

The returned object has three properties:

database
It is the name of the currently selected database.
handle

It is a valid handle for the connected database, and as such it can be used in module-specific functions (if required).

<?php
$link = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password");
mysql_close($link->handle); // dbx_close($link) would be better here
?>

module
It is used internally by dbx only, and is actually the module number mentioned above.

Examples

Example #1 dbx_connect() example

<?php
$link = dbx_connect(DBX_ODBC, "", "db", "username", "password", DBX_PERSISTENT)
    or die("Could not connect");

echo "Connected successfully";
dbx_close($link);
?>

Notes

Note:

Always refer to the module-specific documentation as well.

See Also

  • dbx_close() - Close an open connection/database


Report the error message of the latest function call in the module

  • « dbx_connect
  • dbx_escape_string »
  • PHP Manual
  • dbx Functions
  • Report the error message of the latest function call in the module

dbx_error

(PHP 4 >= 4.0.6, PHP 5 < 5.1.0, PECL dbx >= 1.1.0)

dbx_error — Report the error message of the latest function call in the module

Description

dbx_error ( object $link_identifier ) : string

dbx_error() returns the last error message.

Parameters

link_identifier

The DBX link object returned by dbx_connect()

Return Values

Returns a string containing the error message from the last function call of the abstracted module (e.g. mysql module). If there are multiple connections in the same module, just the last error is given. If there are connections on different modules, the latest error is returned for the module specified by the link_identifier parameter.

Examples

Example #1 dbx_error() example

<?php
$link   = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, "select id from non_existing_table");
if ($result == 0) {
    echo dbx_error($link);
}
dbx_close($link);
?>

Notes

Note:

Always refer to the module-specific documentation as well.

The error message for Microsoft SQL Server is actually the result of the mssql_get_last_message() function.

The error message for Oracle (oci8) is not implemented yet.


Escape a string so it can safely be used in an sql-statement

  • « dbx_error
  • dbx_fetch_row »
  • PHP Manual
  • dbx Functions
  • Escape a string so it can safely be used in an sql-statement

dbx_escape_string

(PHP 4 >= 4.3.0, PHP 5 < 5.1.0, PECL dbx >= 1.1.0)

dbx_escape_string — Escape a string so it can safely be used in an sql-statement

Description

dbx_escape_string ( object $link_identifier , string $text ) : string

Escape the given string so that it can safely be used in an sql-statement.

Parameters

link_identifier

The DBX link object returned by dbx_connect()

text

The string to escape.

Return Values

Returns the text, escaped where necessary (such as quotes, backslashes etc). On error, NULL is returned.

Examples

Example #1 dbx_escape_string() example

<?php
$link   = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password")
    or die("Could not connect");

$text = dbx_escape_string($link, "It\'s quoted and backslashed (\\).");
$result = dbx_query($link, "insert into tbl (txt) values ('" . $text . "')");
if ($result == 0) {
    echo dbx_error($link);
}
dbx_close($link);
?>

See Also

  • dbx_query() - Send a query and fetch all results (if any)


Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set

  • « dbx_escape_string
  • dbx_query »
  • PHP Manual
  • dbx Functions
  • Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set

dbx_fetch_row

(PHP 5 < 5.1.0, PECL dbx >= 1.1.0)

dbx_fetch_row — Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set

Description

dbx_fetch_row ( object $result_identifier ) : mixed

dbx_fetch_row() fetches rows from a result identifier that had the DBX_RESULT_UNBUFFERED flag set.

When the DBX_RESULT_UNBUFFERED is not set in the query, dbx_fetch_row() will fail as all rows have already been fetched into the results data property.

As a side effect, the rows property of the query-result object is incremented for each successful call to dbx_fetch_row().

Parameters

result_identifier

A result set returned by dbx_query().

Return Values

Returns an object on success that contains the same information as any row would have in the dbx_query() result data property, including columns accessible by index or fieldname when the flags for dbx_query() were set that way.

Upon failure, returns 0 (e.g. when no more rows are available).

Examples

Example #1 How to handle the returned value

<?php
$result = dbx_query($link, 'SELECT id, parentid, description FROM table', DBX_RESULT_UNBUFFERED);

echo "<table>\n";
while ($row = dbx_fetch_row($result)) {
    echo "<tr>\n";
    foreach ($row as $field) {
        echo "<td>$field</td>";
    }
    echo "</tr>\n";
}
echo "</table>\n";
?>

See Also

  • dbx_query() - Send a query and fetch all results (if any)


Send a query and fetch all results (if any)

  • « dbx_fetch_row
  • dbx_sort »
  • PHP Manual
  • dbx Functions
  • Send a query and fetch all results (if any)

dbx_query

(PHP 4 >= 4.0.6, PHP 5 < 5.1.0, PECL dbx >= 1.1.0)

dbx_query — Send a query and fetch all results (if any)

Description

dbx_query ( object $link_identifier , string $sql_statement [, int $flags ] ) : mixed

Sends a query and fetch all results.

Parameters

link_identifier

The DBX link object returned by dbx_connect()

sql_statement

SQL statement.

Data inside the query should be properly escaped.

flags

The flags parameter is used to control the amount of information that is returned. It may be any combination of the following constants with the bitwise OR operator (|). The DBX_COLNAMES_* flags override the dbx.colnames_case setting from php.ini.

DBX_RESULT_INDEX
It is always set, that is, the returned object has a data property which is a 2 dimensional array indexed numerically. For example, in the expression data[2][3] 2 stands for the row (or record) number and 3 stands for the column (or field) number. The first row and column are indexed at 0. If DBX_RESULT_ASSOC is also specified, the returning object contains the information related to DBX_RESULT_INFO too, even if it was not specified.
DBX_RESULT_INFO
It provides info about columns, such as field names and field types.
DBX_RESULT_ASSOC
It effects that the field values can be accessed with the respective column names used as keys to the returned object's data property. Associated results are actually references to the numerically indexed data, so modifying data[0][0] causes that data[0]['field_name_for_first_column'] is modified as well.
DBX_RESULT_UNBUFFERED
This flag will not create the data property, and the rows property will initially be 0. Use this flag for large datasets, and use dbx_fetch_row() to retrieve the results row by row. The dbx_fetch_row() function will return rows that are conformant to the flags set with this query. Incidentally, it will also update the rows each time it is called.
DBX_COLNAMES_UNCHANGED
The case of the returned column names will not be changed.
DBX_COLNAMES_UPPERCASE
The case of the returned column names will be changed to uppercase.
DBX_COLNAMES_LOWERCASE
The case of the returned column names will be changed to lowercase.
Note that DBX_RESULT_INDEX is always used, regardless of the actual value of flags parameter. This means that only the following combinations are effective:
  • DBX_RESULT_INDEX
  • DBX_RESULT_INDEX | DBX_RESULT_INFO
  • DBX_RESULT_INDEX | DBX_RESULT_INFO | DBX_RESULT_ASSOC - this is the default, if flags is not specified.

Return Values

dbx_query() returns an object or 1 on success, and 0 on failure. The result object is returned only if the query given in sql_statement produces a result set (i.e. a SELECT query, even if the result set is empty).

The returned object has four or five properties depending on flags:

handle

It is a valid handle for the connected database, and as such it can be used in module specific functions (if required).

<?php
$result = dbx_query($link, "SELECT id FROM table");
mysql_field_len($result->handle, 0);
?>

cols and rows

These contain the number of columns (or fields) and rows (or records) respectively.

<?php
$result = dbx_query($link, 'SELECT id FROM table');
echo $result->rows; // number of records
echo $result->cols; // number of fields
?>

info (optional)
It is returned only if either DBX_RESULT_INFO or DBX_RESULT_ASSOC is specified in the flags parameter. It is a 2 dimensional array, that has two named rows (name and type) to retrieve column information.

Example #1 lists each field's name and type

<?php
$result = dbx_query($link, 'SELECT id FROM table',
                     DBX_RESULT_INDEX | DBX_RESULT_INFO);

for ($i = 0; $i < $result->cols; $i++ ) {
    echo $result->info['name'][$i] . "\n";
    echo $result->info['type'][$i] . "\n";
}
?>
data
This property contains the actual resulting data, possibly associated with column names as well depending on flags. If DBX_RESULT_ASSOC is set, it is possible to use $result->data[2]["field_name"].

Example #2 outputs the content of data property into HTML table

<?php
$result = dbx_query($link, 'SELECT id, parentid, description FROM table');

echo "<table>\n";
foreach ($result->data as $row) {
    echo "<tr>\n";
    foreach ($row as $field) {
        echo "<td>$field</td>";
    }
    echo "</tr>\n";
}
echo "</table>\n";
?>

Example #3 How to handle UNBUFFERED queries

<?php

$result = dbx_query ($link, 'SELECT id, parentid, description FROM table', DBX_RESULT_UNBUFFERED);

echo "<table>\n";
while ($row = dbx_fetch_row($result)) {
    echo "<tr>\n";
    foreach ($row as $field) {
        echo "<td>$field</td>";
    }
    echo "</tr>\n";
}
echo "</table>\n";

?>

Examples

Example #4 How to handle the returned value

<?php
$link   = dbx_connect(DBX_ODBC, "", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, 'SELECT id, parentid, description FROM table');

if (is_object($result) ) {
    // ... do some stuff here, see detailed examples below ...
    // first, print out field names and types
    // then, draw a table filled with the returned field values
} else {
    exit("Query failed");
}

dbx_close($link);
?>

Notes

Note:

Always refer to the module-specific documentation as well.

Column names for queries on an Oracle database are returned in lowercase.

See Also

  • dbx_escape_string() - Escape a string so it can safely be used in an sql-statement
  • dbx_fetch_row() - Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set
  • dbx_connect() - Open a connection/database


Sort a result from a dbx_query by a custom sort function

  • « dbx_query
  • ODBC »
  • PHP Manual
  • dbx Functions
  • Sort a result from a dbx_query by a custom sort function

dbx_sort

(PHP 4 >= 4.0.6, PHP 5 < 5.1.0, PECL dbx >= 1.1.0)

dbx_sort — Sort a result from a dbx_query by a custom sort function

Description

dbx_sort ( object $result , string $user_compare_function ) : bool

Sort a result from a dbx_query() call with a custom sort function.

Parameters

result

A result set returned by dbx_query().

user_compare_function

The user-defined comparison function. It must accept two arguments and return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 dbx_sort() example

<?php
function user_re_order($a, $b)
{
    $rv = dbx_compare($a, $b, "parentid", DBX_CMP_DESC);
    if (!$rv) {
        $rv = dbx_compare($a, $b, "id", DBX_CMP_NUMBER);
    }
    return $rv;
}

$link   = dbx_connect(DBX_ODBC, "", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, "SELECT id, parentid, description FROM tbl ORDER BY id");
    // data in $result is now ordered by id

dbx_sort($result, "user_re_order");
    // data in $result is now ordered by parentid (descending), then by id

dbx_close($link);
?>

Notes

Note:

It is always better to use ORDER BY SQL clause instead of dbx_sort() if possible.

See Also

  • dbx_compare() - Compare two rows for sorting purposes


ODBC (Unified)

  • Introduction
  • 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_all — Close all ODBC connections
    • odbc_close — Close an ODBC connection
    • 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_cursor — Get cursorname
    • odbc_data_source — Returns information about a current connection
    • odbc_do — Alias of odbc_exec
    • odbc_error — Get the last error code
    • odbc_errormsg — Get the last error message
    • odbc_exec — Prepare and 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 resources 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_all — Print result as HTML table
    • odbc_result — Get result data
    • 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


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.


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

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.

As of PHP 7.0.0, however, 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.default_db * | NULL | PHP_INI_ALL |
odbc.default_user * | NULL | PHP_INI_ALL |
odbc.default_pw * | NULL | PHP_INI_ALL |
odbc.allow_persistent | "1" | PHP_INI_SYSTEM |
odbc.check_persistent | "1" | PHP_INI_SYSTEM |
odbc.max_persistent | "-1" | PHP_INI_SYSTEM |
odbc.max_links | "-1" | PHP_INI_SYSTEM |
odbc.defaultlrl | "4096" | PHP_INI_ALL |
odbc.defaultbinmode | "1" | PHP_INI_ALL |
odbc.default_cursortype | "3" | PHP_INI_ALL | Available as of PHP 5.3.0

Note: Entries marked with * are not implemented yet.

For further details and definitions of the PHP_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 boolean

Whether to allow persistent ODBC connections.

odbc.check_persistent boolean

Check that a connection is still valid before reuse.

odbc.max_persistent integer

The maximum number of persistent ODBC connections per process.

odbc.max_links integer

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

odbc.defaultlrl integer

Handling of LONG fields. Specifies the number of bytes returned to variables.

When an integer is used, the value is measured in bytes. Shorthand notation, as described in this FAQ, may also be used.
odbc.defaultbinmode integer

Handling of binary data.

odbc.default_cursortype integer

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

This extension defines 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 (integer)
ODBC_BINMODE_PASSTHRU (integer)
ODBC_BINMODE_RETURN (integer)
ODBC_BINMODE_CONVERT (integer)
SQL_ODBC_CURSORS (integer)
SQL_CUR_USE_DRIVER (integer)
SQL_CUR_USE_IF_NEEDED (integer)
SQL_CUR_USE_ODBC (integer)
SQL_CONCURRENCY (integer)
SQL_CONCUR_READ_ONLY (integer)
SQL_CONCUR_LOCK (integer)
SQL_CONCUR_ROWVER (integer)
SQL_CONCUR_VALUES (integer)
SQL_CURSOR_TYPE (integer)
SQL_CURSOR_FORWARD_ONLY (integer)
SQL_CURSOR_KEYSET_DRIVEN (integer)
SQL_CURSOR_DYNAMIC (integer)
SQL_CURSOR_STATIC (integer)
SQL_KEYSET_SIZE (integer)
SQL_CHAR (integer)
SQL_VARCHAR (integer)
SQL_LONGVARCHAR (integer)
SQL_DECIMAL (integer)
SQL_NUMERIC (integer)
SQL_BIT (integer)
SQL_TINYINT (integer)
SQL_SMALLINT (integer)
SQL_INTEGER (integer)
SQL_BIGINT (integer)
SQL_REAL (integer)
SQL_FLOAT (integer)
SQL_DOUBLE (integer)
SQL_BINARY (integer)
SQL_VARBINARY (integer)
SQL_LONGVARBINARY (integer)
SQL_DATE (integer)
SQL_TIME (integer)
SQL_TIMESTAMP (integer)
SQL_TYPE_DATE (integer)
SQL_TYPE_TIME (integer)
SQL_TYPE_TIMESTAMP (integer)
SQL_BEST_ROWID (integer)
SQL_ROWVER (integer)
SQL_SCOPE_CURROW (integer)
SQL_SCOPE_TRANSACTION (integer)
SQL_SCOPE_SESSION (integer)
SQL_NO_NULLS (integer)
SQL_NULLABLE (integer)
SQL_INDEX_UNIQUE (integer)
SQL_INDEX_ALL (integer)
SQL_ENSURE (integer)
SQL_QUICK (integer)


ODBC Functions

Table of Contents

  • odbc_autocommit — Toggle autocommit behaviour
  • odbc_binmode — Handling of binary column data
  • odbc_close_all — Close all ODBC connections
  • odbc_close — Close an ODBC connection
  • 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_cursor — Get cursorname
  • odbc_data_source — Returns information about a current connection
  • odbc_do — Alias of odbc_exec
  • odbc_error — Get the last error code
  • odbc_errormsg — Get the last error message
  • odbc_exec — Prepare and 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 resources 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_all — Print result as HTML table
  • odbc_result — Get result data
  • 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


Toggle autocommit behaviour

  • « ODBC Functions
  • odbc_binmode »
  • PHP Manual
  • ODBC Functions
  • Toggle autocommit behaviour

odbc_autocommit

(PHP 4, PHP 5, PHP 7)

odbc_autocommit — Toggle autocommit behaviour

Description

odbc_autocommit ( resource $connection_id [, bool $OnOff = FALSE ] ) : mixed

Toggles autocommit behaviour.

By default, auto-commit is on for a connection. Disabling auto-commit is equivalent with starting a transaction.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

OnOff

If OnOff is TRUE, auto-commit is enabled, if it is FALSE auto-commit is disabled.

Return Values

Without the OnOff parameter, this function returns auto-commit status for connection_id. Non-zero is returned if auto-commit is on, 0 if it is off, or FALSE if an error occurs.

If OnOff is set, this function returns TRUE on success and FALSE on failure.

See Also

  • odbc_commit() - Commit an ODBC transaction
  • odbc_rollback() - Rollback a transaction


Handling of binary column data

  • « odbc_autocommit
  • odbc_close_all »
  • PHP Manual
  • ODBC Functions
  • Handling of binary column data

odbc_binmode

(PHP 4, PHP 5, PHP 7)

odbc_binmode — Handling of binary column data

Description

odbc_binmode ( resource $result_id , int $mode ) : bool

Enables handling of binary column data. ODBC SQL types affected are BINARY, VARBINARY, and LONGVARBINARY.

When binary SQL data is converted to character C data, 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".

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

Parameters

result_id

The result identifier.

If result_id is 0, the settings apply as default for new results.

Note: Default for longreadlen is 4096 and mode defaults to ODBC_BINMODE_RETURN. Handling of binary long columns is also affected by odbc_longreadlen().

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

Return Values

Returns TRUE on success or FALSE on failure.


Close all ODBC connections

  • « odbc_binmode
  • odbc_close »
  • PHP Manual
  • ODBC Functions
  • Close all ODBC connections

odbc_close_all

(PHP 4, PHP 5, PHP 7)

odbc_close_all — Close all ODBC connections

Description

odbc_close_all ( void ) : 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.


Close an ODBC connection

  • « odbc_close_all
  • odbc_columnprivileges »
  • PHP Manual
  • ODBC Functions
  • Close an ODBC connection

odbc_close

(PHP 4, PHP 5, PHP 7)

odbc_close — Close an ODBC connection

Description

odbc_close ( resource $connection_id ) : void

Closes down the connection to the database server.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

Return Values

No value is returned.

Notes

Note:

This function will fail if there are open transactions on this connection. The connection will remain open in this case.


Lists columns and associated privileges for the given table

  • « odbc_close
  • odbc_columns »
  • PHP Manual
  • ODBC Functions
  • Lists columns and associated privileges for the given table

odbc_columnprivileges

(PHP 4, PHP 5, PHP 7)

odbc_columnprivileges — Lists columns and associated privileges for the given table

Description

odbc_columnprivileges ( resource $connection_id , string $qualifier , string $owner , string $table_name , string $column_name ) : resource

Lists columns and associated privileges for the given table.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

qualifier

The qualifier.

owner

The owner.

table_name

The table name.

column_name

The column name.

The owner, table_name, and column_name accept search patterns ('%' to match zero or more characters and '_' to match a single character).

Return Values

Returns an ODBC result identifier or FALSE on failure. This result identifier can be used to fetch a list of columns and associated privileges.

The result set has the following columns:

  • TABLE_QUALIFIER
  • TABLE_OWNER
  • TABLE_NAME
  • GRANTOR
  • GRANTEE
  • PRIVILEGE
  • IS_GRANTABLE

The result set is ordered by TABLE_QUALIFIER, TABLE_OWNER and TABLE_NAME.


Lists the column names in specified tables

  • « odbc_columnprivileges
  • odbc_commit »
  • PHP Manual
  • ODBC Functions
  • Lists the column names in specified tables

odbc_columns

(PHP 4, PHP 5, PHP 7)

odbc_columns — Lists the column names in specified tables

Description

odbc_columns ( resource $connection_id [, string $qualifier [, string $schema [, string $table_name [, string $column_name ]]]] ) : resource

Lists all columns in the requested range.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

qualifier

The qualifier.

schema

The owner.

table_name

The table name.

column_name

The column name.

The schema, table_name, and column_name accept search patterns ('%' to match zero or more characters and '_' to match a single character).

Return Values

Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • TABLE_QUALIFIER
  • TABLE_SCHEM
  • TABLE_NAME
  • COLUMN_NAME
  • DATA_TYPE
  • TYPE_NAME
  • PRECISION
  • LENGTH
  • SCALE
  • RADIX
  • NULLABLE
  • REMARKS

The result set is ordered by TABLE_QUALIFIER, TABLE_SCHEM and TABLE_NAME.

See Also

  • odbc_columnprivileges() - Lists columns and associated privileges for the given table to retrieve associated privileges


Commit an ODBC transaction

  • « odbc_columns
  • odbc_connect »
  • PHP Manual
  • ODBC Functions
  • Commit an ODBC transaction

odbc_commit

(PHP 4, PHP 5, PHP 7)

odbc_commit — Commit an ODBC transaction

Description

odbc_commit ( resource $connection_id ) : bool

Commits all pending transactions on the connection.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

Return Values

Returns TRUE on success or FALSE on failure.


Connect to a datasource

  • « odbc_commit
  • odbc_cursor »
  • PHP Manual
  • ODBC Functions
  • Connect to a datasource

odbc_connect

(PHP 4, PHP 5, PHP 7)

odbc_connect — Connect to a datasource

Description

odbc_connect ( string $dsn , string $user , string $password [, int $cursor_type ] ) : resource

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.

password

The password.

cursor_type

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

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


Get cursorname

  • « odbc_connect
  • odbc_data_source »
  • PHP Manual
  • ODBC Functions
  • Get cursorname

odbc_cursor

(PHP 4, PHP 5, PHP 7)

odbc_cursor — Get cursorname

Description

odbc_cursor ( resource $result_id ) : string

Gets the cursorname for the given result_id.

Parameters

result_id

The result identifier.

Return Values

Returns the cursor name, as a string.


Returns information about a current connection

  • « odbc_cursor
  • odbc_do »
  • PHP Manual
  • ODBC Functions
  • Returns information about a current connection

odbc_data_source

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

odbc_data_source — Returns information about a current connection

Description

odbc_data_source ( resource $connection_id , int $fetch_type ) : array

This function will return the list of available DSN (after calling it several times).

Parameters

connection_id

The ODBC connection identifier, 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, and an array upon success.


Alias of odbc_exec

  • « odbc_data_source
  • odbc_error »
  • PHP Manual
  • ODBC Functions
  • Alias of odbc_exec

odbc_do

(PHP 4, PHP 5, PHP 7)

odbc_do — Alias of odbc_exec()

Description

This function is an alias of: odbc_exec().


Get the last error code

  • « odbc_do
  • odbc_errormsg »
  • PHP Manual
  • ODBC Functions
  • Get the last error code

odbc_error

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

odbc_error — Get the last error code

Description

odbc_error ([ resource $connection_id ] ) : string

Returns a six-digit ODBC state, or an empty string if there has been no errors.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

Return Values

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

See Also

  • odbc_errormsg() - Get the last error message
  • odbc_exec() - Prepare and execute an SQL statement


Get the last error message

  • « odbc_error
  • odbc_exec »
  • PHP Manual
  • ODBC Functions
  • Get the last error message

odbc_errormsg

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

odbc_errormsg — Get the last error message

Description

odbc_errormsg ([ resource $connection_id ] ) : string

Returns a string containing the last ODBC error message, or an empty string if there has been no errors.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

Return Values

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

See Also

  • odbc_error() - Get the last error code
  • odbc_exec() - Prepare and execute an SQL statement


Prepare and execute an SQL statement

  • « odbc_errormsg
  • odbc_execute »
  • PHP Manual
  • ODBC Functions
  • Prepare and execute an SQL statement

odbc_exec

(PHP 4, PHP 5, PHP 7)

odbc_exec — Prepare and execute an SQL statement

Description

odbc_exec ( resource $connection_id , string $query_string [, int $flags ] ) : resource

Sends an SQL statement to the database server.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

query_string

The SQL statement.

flags

This parameter is currently not used.

Return Values

Returns an ODBC result identifier if the SQL command was executed successfully, or FALSE on error.

See Also

  • odbc_prepare() - Prepares a statement for execution
  • odbc_execute() - Execute a prepared statement


Execute a prepared statement

  • « odbc_exec
  • odbc_fetch_array »
  • PHP Manual
  • ODBC Functions
  • Execute a prepared statement

odbc_execute

(PHP 4, PHP 5, PHP 7)

odbc_execute — Execute a prepared statement

Description

odbc_execute ( resource $result_id [, array $parameters_array ] ) : bool

Executes a statement prepared with odbc_prepare().

Parameters

result_id

The result id resource, from odbc_prepare().

parameters_array

Parameters in parameter_array 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 parameter_array 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.

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, mssql for MS SQL Server, or oci8 for Oracle).

See Also

  • odbc_prepare() - Prepares a statement for execution


Fetch a result row as an associative array

  • « odbc_execute
  • odbc_fetch_into »
  • PHP Manual
  • ODBC Functions
  • Fetch a result row as an associative array

odbc_fetch_array

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

odbc_fetch_array — Fetch a result row as an associative array

Description

odbc_fetch_array ( resource $result [, int $rownumber ] ) : array

Fetch an associative array from an ODBC query.

Parameters

result

The result resource from odbc_exec().

rownumber

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.

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


Fetch one result row into array

  • « odbc_fetch_array
  • odbc_fetch_object »
  • PHP Manual
  • ODBC Functions
  • Fetch one result row into array

odbc_fetch_into

(PHP 4, PHP 5, PHP 7)

odbc_fetch_into — Fetch one result row into array

Description

odbc_fetch_into ( resource $result_id , array &$result_array [, int $rownumber ] ) : int

Fetch one result row into array.

Parameters

result_id

The result resource.

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

rownumber

The row number.

Return Values

Returns the number of columns in the result; FALSE on error.

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


Fetch a result row as an object

  • « odbc_fetch_into
  • odbc_fetch_row »
  • PHP Manual
  • ODBC Functions
  • Fetch a result row as an object

odbc_fetch_object

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

odbc_fetch_object — Fetch a result row as an object

Description

odbc_fetch_object ( resource $result [, int $rownumber ] ) : object

Fetch an object from an ODBC query.

Parameters

result

The result resource from odbc_exec().

rownumber

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.

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


Fetch a row

  • « odbc_fetch_object
  • odbc_field_len »
  • PHP Manual
  • ODBC Functions
  • Fetch a row

odbc_fetch_row

(PHP 4, PHP 5, PHP 7)

odbc_fetch_row — Fetch a row

Description

odbc_fetch_row ( resource $result_id [, int $row_number = 1 ] ) : 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

result_id

The result identifier.

row_number

If row_number 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_number can be mixed.

To step through the result more than once, you can call odbc_fetch_row() with row_number 1, and then continue doing odbc_fetch_row() without row_number to review the result. If a driver doesn't support fetching rows by number, the row_number parameter is ignored.

Return Values

Returns TRUE if there was a row, FALSE otherwise.


Get the length (precision) of a field

  • « odbc_fetch_row
  • odbc_field_name »
  • PHP Manual
  • ODBC Functions
  • Get the length (precision) of a field

odbc_field_len

(PHP 4, PHP 5, PHP 7)

odbc_field_len — Get the length (precision) of a field

Description

odbc_field_len ( resource $result_id , int $field_number ) : int

Gets the length of the field referenced by number in the given result identifier.

Parameters

result_id

The result identifier.

field_number

The field number. Field numbering starts at 1.

Return Values

Returns the field length, or FALSE on error.

See Also

  • odbc_field_scale() - Get the scale of a field to get the scale of a floating point number


Get the columnname

  • « odbc_field_len
  • odbc_field_num »
  • PHP Manual
  • ODBC Functions
  • Get the columnname

odbc_field_name

(PHP 4, PHP 5, PHP 7)

odbc_field_name — Get the columnname

Description

odbc_field_name ( resource $result_id , int $field_number ) : string

Gets the name of the field occupying the given column number in the given result identifier.

Parameters

result_id

The result identifier.

field_number

The field number. Field numbering starts at 1.

Return Values

Returns the field name as a string, or FALSE on error.


Return column number

  • « odbc_field_name
  • odbc_field_precision »
  • PHP Manual
  • ODBC Functions
  • Return column number

odbc_field_num

(PHP 4, PHP 5, PHP 7)

odbc_field_num — Return column number

Description

odbc_field_num ( resource $result_id , string $field_name ) : int

Gets the number of the column slot that corresponds to the named field in the given result identifier.

Parameters

result_id

The result identifier.

field_name

The field name.

Return Values

Returns the field number as a integer, or FALSE on error. Field numbering starts at 1.


Alias of odbc_field_len

  • « odbc_field_num
  • odbc_field_scale »
  • PHP Manual
  • ODBC Functions
  • Alias of odbc_field_len

odbc_field_precision

(PHP 4, PHP 5, PHP 7)

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.


Get the scale of a field

  • « odbc_field_precision
  • odbc_field_type »
  • PHP Manual
  • ODBC Functions
  • Get the scale of a field

odbc_field_scale

(PHP 4, PHP 5, PHP 7)

odbc_field_scale — Get the scale of a field

Description

odbc_field_scale ( resource $result_id , int $field_number ) : int

Gets the scale of the field referenced by number in the given result identifier.

Parameters

result_id

The result identifier.

field_number

The field number. Field numbering starts at 1.

Return Values

Returns the field scale as a integer, or FALSE on error.


Datatype of a field

  • « odbc_field_scale
  • odbc_foreignkeys »
  • PHP Manual
  • ODBC Functions
  • Datatype of a field

odbc_field_type

(PHP 4, PHP 5, PHP 7)

odbc_field_type — Datatype of a field

Description

odbc_field_type ( resource $result_id , int $field_number ) : string

Gets the SQL type of the field referenced by number in the given result identifier.

Parameters

result_id

The result identifier.

field_number

The field number. Field numbering starts at 1.

Return Values

Returns the field type as a string, or FALSE on error.


Retrieves a list of foreign keys

  • « odbc_field_type
  • odbc_free_result »
  • PHP Manual
  • ODBC Functions
  • Retrieves a list of foreign keys

odbc_foreignkeys

(PHP 4, PHP 5, PHP 7)

odbc_foreignkeys — Retrieves a list of foreign keys

Description

odbc_foreignkeys ( resource $connection_id , string $pk_qualifier , string $pk_owner , string $pk_table , string $fk_qualifier , string $fk_owner , string $fk_table ) : resource

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

connection_id

The ODBC connection identifier, see odbc_connect() for details.

pk_qualifier

The primary key qualifier.

pk_owner

The primary key owner.

pk_table

The primary key table.

fk_qualifier

The foreign key qualifier.

fk_owner

The foreign key owner.

fk_table

The foreign key table.

Return Values

Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • PKTABLE_QUALIFIER
  • PKTABLE_OWNER
  • PKTABLE_NAME
  • PKCOLUMN_NAME
  • FKTABLE_QUALIFIER
  • FKTABLE_OWNER
  • FKTABLE_NAME
  • FKCOLUMN_NAME
  • KEY_SEQ
  • UPDATE_RULE
  • DELETE_RULE
  • FK_NAME
  • PK_NAME

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.


Free resources associated with a result

  • « odbc_foreignkeys
  • odbc_gettypeinfo »
  • PHP Manual
  • ODBC Functions
  • Free resources associated with a result

odbc_free_result

(PHP 4, PHP 5, PHP 7)

odbc_free_result — Free resources associated with a result

Description

odbc_free_result ( resource $result_id ) : bool

Free resources 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

result_id

The result identifier.

Return Values

Always returns TRUE.

Notes

Note:

If auto-commit is disabled (see odbc_autocommit()) and you call odbc_free_result() before committing, all pending transactions are rolled back.


Retrieves information about data types supported by the data source

  • « odbc_free_result
  • odbc_longreadlen »
  • PHP Manual
  • ODBC Functions
  • Retrieves information about data types supported by the data source

odbc_gettypeinfo

(PHP 4, PHP 5, PHP 7)

odbc_gettypeinfo — Retrieves information about data types supported by the data source

Description

odbc_gettypeinfo ( resource $connection_id [, int $data_type ] ) : resource

Retrieves information about data types supported by the data source.

Parameters

connection_id

The ODBC connection identifier, 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 identifier 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.


Handling of LONG columns

  • « odbc_gettypeinfo
  • odbc_next_result »
  • PHP Manual
  • ODBC Functions
  • Handling of LONG columns

odbc_longreadlen

(PHP 4, PHP 5, PHP 7)

odbc_longreadlen — Handling of LONG columns

Description

odbc_longreadlen ( resource $result_id , int $length ) : bool

Enables handling of LONG and LONGVARBINARY columns.

Parameters

result_id

The result identifier.

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.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note:

Handling of LONGVARBINARY columns is also affected by odbc_binmode().


Checks if multiple results are available

  • « odbc_longreadlen
  • odbc_num_fields »
  • PHP Manual
  • ODBC Functions
  • Checks if multiple results are available

odbc_next_result

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

odbc_next_result — Checks if multiple results are available

Description

odbc_next_result ( resource $result_id ) : 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

result_id

The result identifier.

Return Values

Returns TRUE if there are more result sets, FALSE otherwise.

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)


Number of columns in a result

  • « odbc_next_result
  • odbc_num_rows »
  • PHP Manual
  • ODBC Functions
  • Number of columns in a result

odbc_num_fields

(PHP 4, PHP 5, PHP 7)

odbc_num_fields — Number of columns in a result

Description

odbc_num_fields ( resource $result_id ) : int

Gets the number of fields (columns) in an ODBC result.

Parameters

result_id

The result identifier returned by odbc_exec().

Return Values

Returns the number of fields, or -1 on error.


Number of rows in a result

  • « odbc_num_fields
  • odbc_pconnect »
  • PHP Manual
  • ODBC Functions
  • Number of rows in a result

odbc_num_rows

(PHP 4, PHP 5, PHP 7)

odbc_num_rows — Number of rows in a result

Description

odbc_num_rows ( resource $result_id ) : 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

result_id

The result identifier returned by odbc_exec().

Return Values

Returns the number of rows in an ODBC result. This function will return -1 on error.

Notes

Note:

Using odbc_num_rows() to determine the number of rows available after a SELECT will return -1 with many drivers.


Open a persistent database connection

  • « odbc_num_rows
  • odbc_prepare »
  • PHP Manual
  • ODBC Functions
  • Open a persistent database connection

odbc_pconnect

(PHP 4, PHP 5, PHP 7)

odbc_pconnect — Open a persistent database connection

Description

odbc_pconnect ( string $dsn , string $user , string $password [, int $cursor_type ] ) : resource

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 id or 0 (FALSE) on error.

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


Prepares a statement for execution

  • « odbc_pconnect
  • odbc_primarykeys »
  • PHP Manual
  • ODBC Functions
  • Prepares a statement for execution

odbc_prepare

(PHP 4, PHP 5, PHP 7)

odbc_prepare — Prepares a statement for execution

Description

odbc_prepare ( resource $connection_id , string $query_string ) : resource

Prepares a statement for execution. The result identifier 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

connection_id

The ODBC connection identifier, see odbc_connect() for details.

query_string

The query string statement being prepared.

Return Values

Returns an ODBC result identifier if the SQL command was prepared successfully. Returns FALSE on error.

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, mssql for MS SQL Server, or oci8 for Oracle).

See Also

  • odbc_execute() - Execute a prepared statement


Gets the primary keys for a table

  • « odbc_prepare
  • odbc_procedurecolumns »
  • PHP Manual
  • ODBC Functions
  • Gets the primary keys for a table

odbc_primarykeys

(PHP 4, PHP 5, PHP 7)

odbc_primarykeys — Gets the primary keys for a table

Description

odbc_primarykeys ( resource $connection_id , string $qualifier , string $owner , string $table ) : resource

Returns a result identifier that can be used to fetch the column names that comprise the primary key for a table.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

qualifier

owner

table

Return Values

Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • TABLE_QUALIFIER
  • TABLE_OWNER
  • TABLE_NAME
  • COLUMN_NAME
  • KEY_SEQ
  • PK_NAME


Retrieve information about parameters to procedures

  • « odbc_primarykeys
  • odbc_procedures »
  • PHP Manual
  • ODBC Functions
  • Retrieve information about parameters to procedures

odbc_procedurecolumns

(PHP 4, PHP 5, PHP 7)

odbc_procedurecolumns — Retrieve information about parameters to procedures

Description

odbc_procedurecolumns ( resource $connection_id ) : resource
odbc_procedurecolumns ( resource $connection_id , string $qualifier , string $owner , string $proc , string $column ) : resource

Retrieve information about parameters to procedures.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

qualifier

The qualifier.

owner

The owner. This parameter accepts the following search patterns: "%" to match zero or more characters, and "_" to match a single character.

proc

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 identifier or FALSE on failure.

The result set has the following columns:

  • PROCEDURE_QUALIFIER
  • PROCEDURE_OWNER
  • PROCEDURE_NAME
  • COLUMN_NAME
  • COLUMN_TYPE
  • DATA_TYPE
  • TYPE_NAME
  • PRECISION
  • LENGTH
  • SCALE
  • RADIX
  • NULLABLE
  • REMARKS

The result set is ordered by PROCEDURE_QUALIFIER, PROCEDURE_OWNER, PROCEDURE_NAME and COLUMN_TYPE.


Get the list of procedures stored in a specific data source

  • « odbc_procedurecolumns
  • odbc_result_all »
  • PHP Manual
  • ODBC Functions
  • Get the list of procedures stored in a specific data source

odbc_procedures

(PHP 4, PHP 5, PHP 7)

odbc_procedures — Get the list of procedures stored in a specific data source

Description

odbc_procedures ( resource $connection_id ) : resource
odbc_procedures ( resource $connection_id , string $qualifier , string $owner , string $name ) : resource

Lists all procedures in the requested range.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

qualifier

The qualifier.

owner

The owner. This parameter accepts the following search patterns: "%" to match zero or more characters, and "_" to match a single character.

name

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 identifier containing the information or FALSE on failure.

The result set has the following columns:

  • PROCEDURE_QUALIFIER
  • PROCEDURE_OWNER
  • PROCEDURE_NAME
  • NUM_INPUT_PARAMS
  • NUM_OUTPUT_PARAMS
  • NUM_RESULT_SETS
  • REMARKS
  • PROCEDURE_TYPE


Print result as HTML table

  • « odbc_procedures
  • odbc_result »
  • PHP Manual
  • ODBC Functions
  • Print result as HTML table

odbc_result_all

(PHP 4, PHP 5, PHP 7)

odbc_result_all — Print result as HTML table

Description

odbc_result_all ( resource $result_id [, string $format ] ) : int

Prints all rows from a result identifier produced by odbc_exec(). The result is printed in HTML table format.

Parameters

result_id

The result identifier.

format

Additional overall table formatting.

Return Values

Returns the number of rows in the result or FALSE on error.


Get result data

  • « odbc_result_all
  • odbc_rollback »
  • PHP Manual
  • ODBC Functions
  • Get result data

odbc_result

(PHP 4, PHP 5, PHP 7)

odbc_result — Get result data

Description

odbc_result ( resource $result_id , mixed $field ) : mixed

Get result data

Parameters

result_id

The ODBC resource.

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.

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


Rollback a transaction

  • « odbc_result
  • odbc_setoption »
  • PHP Manual
  • ODBC Functions
  • Rollback a transaction

odbc_rollback

(PHP 4, PHP 5, PHP 7)

odbc_rollback — Rollback a transaction

Description

odbc_rollback ( resource $connection_id ) : bool

Rolls back all pending statements on the connection.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

Return Values

Returns TRUE on success or FALSE on failure.


Adjust ODBC settings

  • « odbc_rollback
  • odbc_specialcolumns »
  • PHP Manual
  • ODBC Functions
  • Adjust ODBC settings

odbc_setoption

(PHP 4, PHP 5, PHP 7)

odbc_setoption — Adjust ODBC settings

Description

odbc_setoption ( resource $id , int $function , int $option , int $param ) : 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

id

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.

function

Is the ODBC function to use. The value should be 1 for SQLSetConnectOption() and 2 for SQLSetStmtOption().

option

The option to set.

param

The value for the given option.

Return Values

Returns TRUE on success or FALSE on failure.

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


Retrieves special columns

  • « odbc_setoption
  • odbc_statistics »
  • PHP Manual
  • ODBC Functions
  • Retrieves special columns

odbc_specialcolumns

(PHP 4, PHP 5, PHP 7)

odbc_specialcolumns — Retrieves special columns

Description

odbc_specialcolumns ( resource $connection_id , int $type , string $qualifier , string $table , int $scope , int $nullable ) : resource

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

connection_id

The ODBC connection identifier, 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.
qualifier

The qualifier.

table

The table.

scope

The scope, which orders the result set.

nullable

The nullable option.

Return Values

Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • SCOPE
  • COLUMN_NAME
  • DATA_TYPE
  • TYPE_NAME
  • PRECISION
  • LENGTH
  • SCALE
  • PSEUDO_COLUMN


Retrieve statistics about a table

  • « odbc_specialcolumns
  • odbc_tableprivileges »
  • PHP Manual
  • ODBC Functions
  • Retrieve statistics about a table

odbc_statistics

(PHP 4, PHP 5, PHP 7)

odbc_statistics — Retrieve statistics about a table

Description

odbc_statistics ( resource $connection_id , string $qualifier , string $owner , string $table_name , int $unique , int $accuracy ) : resource

Get statistics about a table and its indexes.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

qualifier

The qualifier.

owner

The owner.

table_name

The table name.

unique

The unique attribute.

accuracy

The accuracy.

Return Values

Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • TABLE_QUALIFIER
  • TABLE_OWNER
  • TABLE_NAME
  • NON_UNIQUE
  • INDEX_QUALIFIER
  • INDEX_NAME
  • TYPE
  • SEQ_IN_INDEX
  • COLUMN_NAME
  • COLLATION
  • CARDINALITY
  • PAGES
  • FILTER_CONDITION

The result set is ordered by NON_UNIQUE, TYPE, INDEX_QUALIFIER, INDEX_NAME and SEQ_IN_INDEX.


Lists tables and the privileges associated with each table

  • « odbc_statistics
  • odbc_tables »
  • PHP Manual
  • ODBC Functions
  • Lists tables and the privileges associated with each table

odbc_tableprivileges

(PHP 4, PHP 5, PHP 7)

odbc_tableprivileges — Lists tables and the privileges associated with each table

Description

odbc_tableprivileges ( resource $connection_id , string $qualifier , string $owner , string $name ) : resource

Lists tables in the requested range and the privileges associated with each table.

Parameters

connection_id

The ODBC connection identifier, see odbc_connect() for details.

qualifier

The qualifier.

owner

The owner. Accepts the following search patterns: ('%' to match zero or more characters and '_' to match a single character)

name

The name. Accepts the following search patterns: ('%' to match zero or more characters and '_' to match a single character)

Return Values

An ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • TABLE_QUALIFIER
  • TABLE_OWNER
  • TABLE_NAME
  • GRANTOR
  • GRANTEE
  • PRIVILEGE
  • IS_GRANTABLE

The result set is ordered by TABLE_QUALIFIER, TABLE_OWNER and TABLE_NAME.


Get the list of table names stored in a specific data source

  • « odbc_tableprivileges
  • PDO »
  • PHP Manual
  • ODBC Functions
  • Get the list of table names stored in a specific data source

odbc_tables

(PHP 4, PHP 5, PHP 7)

odbc_tables — Get the list of table names stored in a specific data source

Description

odbc_tables ( resource $connection_id [, string $qualifier [, string $owner [, string $name [, string $types ]]]] ) : resource

Lists all tables in the requested range.

To support enumeration of qualifiers, owners, and table types, the following special semantics for the qualifier, owner, name, and table_type are available:

  • If qualifier is a single percent character (%) and owner and name 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 owner is a single percent character (%) and qualifier and name 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 qualifier, owner and name 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

connection_id

The ODBC connection identifier, see odbc_connect() for details.

qualifier

The qualifier.

owner

The owner. Accepts search patterns ('%' to match zero or more characters and '_' to match a single character).

name

The name. Accepts 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 identifier containing the information or FALSE on failure.

The result set has the following columns:

  • TABLE_QUALIFIER
  • TABLE_OWNER
  • TABLE_NAME
  • TABLE_TYPE
  • REMARKS

The result set is ordered by TABLE_TYPE, TABLE_QUALIFIER, TABLE_OWNER and TABLE_NAME.

See Also

  • odbc_tableprivileges() - Lists tables and the privileges associated with each table


PHP Data Objects

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • 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
    • PDO::beginTransaction — Initiates a transaction
    • PDO::commit — Commits a transaction
    • 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 — Executes an SQL statement, returning a result set as a PDOStatement object
    • 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 — Returns an array containing all of the result set rows
    • 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::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
  • PDOException — The PDOException class
  • PDO Drivers
    • CUBRID (PDO) — CUBRID Functions (PDO_CUBRID)
    • MS SQL Server (PDO) — Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
    • Firebird (PDO) — Firebird Functions (PDO_FIREBIRD)
    • IBM (PDO) — IBM Functions (PDO_IBM)
    • Informix (PDO) — Informix Functions (PDO_INFORMIX)
    • MySQL (PDO) — MySQL Functions (PDO_MYSQL)
    • MS SQL Server (PDO) — Microsoft SQL Server Functions (PDO_SQLSRV)
    • Oracle (PDO) — Oracle Functions (PDO_OCI)
    • ODBC and DB2 (PDO) — ODBC and DB2 Functions (PDO_ODBC)
    • PostgreSQL (PDO) — PostgreSQL Functions (PDO_PGSQL)
    • SQLite (PDO) — SQLite Functions (PDO_SQLITE)
    • 4D (PDO) — 4D Functions (PDO_4D)


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 5.1, and is available as a PECL extension for PHP 5.0; PDO requires the new OO features in the core of PHP 5, and so will not run with earlier versions of PHP.


Installation

Installing PDO on Unix systems

  1. PDO and the PDO_SQLITE driver is enabled by default as of PHP 5.1.0. 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 pdo.so 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.so

Windows users

  1. PDO and all the major drivers ship with PHP as shared extensions, and simply need to be activated by editing the php.ini file:

    extension=php_pdo.dll

    Note:

    This step is not necessary for PHP 5.3 and above, as a DLL is no longer required for PDO.

  2. Next, choose the other database-specific DLL files and either use dl() to load them at runtime, or enable them in php.ini below php_pdo.dll. For example:

    extension=php_pdo.dll
extension=php_pdo_firebird.dll
extension=php_pdo_informix.dll
extension=php_pdo_mssql.dll
extension=php_pdo_mysql.dll
extension=php_pdo_oci.dll
extension=php_pdo_oci8.dll
extension=php_pdo_odbc.dll
extension=php_pdo_pgsql.dll
extension=php_pdo_sqlite.dll

    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

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

Warning

PDO uses class constants since PHP 5.1. Prior releases use global constants in the form PDO_PARAM_BOOL.

PDO::PARAM_BOOL (integer)
Represents a boolean data type.
PDO::PARAM_NULL (integer)
Represents the SQL NULL data type.
PDO::PARAM_INT (integer)
Represents the SQL INTEGER data type.
PDO::PARAM_STR (integer)
Represents the SQL CHAR, VARCHAR, or other string data type.
PDO::PARAM_STR_NATL (integer)
Flag to denote a string uses the national character set. Available since PHP 7.2.0
PDO::PARAM_STR_CHAR (integer)
Flag to denote a string uses the regular character set. Available since PHP 7.2.0
PDO::PARAM_LOB (integer)
Represents the SQL large object data type.
PDO::PARAM_STMT (integer)
Represents a recordset type. Not currently supported by any drivers.
PDO::PARAM_INPUT_OUTPUT (integer)
Specifies that the parameter is an INOUT parameter for a stored procedure. You must bitwise-OR this value with an explicit PDO::PARAM_* data type.
PDO::FETCH_LAZY (integer)
Specifies that the fetch method shall return each row as an object with variable names that correspond to the column names returned in the result set. PDO::FETCH_LAZY creates the object variable names as they are accessed. Not valid inside PDOStatement::fetchAll().
PDO::FETCH_ASSOC (integer)
Specifies that the fetch method shall return each row as an array indexed by column name as returned in the corresponding result set. If the result set contains multiple columns with the same name, PDO::FETCH_ASSOC returns only a single value per column name.
PDO::FETCH_NAMED (integer)
Specifies that the fetch method shall return each row as an array indexed by column name as returned in the corresponding result set. If the result set contains multiple columns with the same name, PDO::FETCH_NAMED returns an array of values per column name.
PDO::FETCH_NUM (integer)
Specifies that the fetch method shall return each row as an array indexed by column number as returned in the corresponding result set, starting at column 0.
PDO::FETCH_BOTH (integer)
Specifies that the fetch method shall return each row as an array indexed by both column name and number as returned in the corresponding result set, starting at column 0.
PDO::FETCH_OBJ (integer)
Specifies that the fetch method shall return each row as an object with property names that correspond to the column names returned in the result set.
PDO::FETCH_BOUND (integer)
Specifies that the fetch method shall return TRUE and assign the values of the columns in the result set to the PHP variables to which they were bound with the PDOStatement::bindParam() or PDOStatement::bindColumn() methods.
PDO::FETCH_COLUMN (integer)
Specifies that the fetch method shall return only a single requested column from the next row in the result set.
PDO::FETCH_CLASS (integer)
Specifies that the fetch method shall return a new instance of the requested class, mapping the columns to named properties in the class.

Note: The magic __set() method is called if the property doesn't exist in the requested class

PDO::FETCH_INTO (integer)
Specifies that the fetch method shall update an existing instance of the requested class, mapping the columns to named properties in the class.
PDO::FETCH_FUNC (integer)
Allows completely customize the way data is treated on the fly (only valid inside PDOStatement::fetchAll()).
PDO::FETCH_GROUP (integer)
Group return by values. Usually combined with PDO::FETCH_COLUMN or PDO::FETCH_KEY_PAIR.
PDO::FETCH_UNIQUE (integer)
Fetch only the unique values.
PDO::FETCH_KEY_PAIR (integer)
Fetch a two-column result into an array where the first column is a key and the second column is the value. Available since PHP 5.2.3.
PDO::FETCH_CLASSTYPE (integer)
Determine the class name from the value of first column.
PDO::FETCH_SERIALIZE (integer)
As PDO::FETCH_INTO but object is provided as a serialized string. Available since PHP 5.1.0. Since PHP 5.3.0 the class constructor is never called if this flag is set.
PDO::FETCH_PROPS_LATE (integer)
Call the constructor before setting properties. Available since PHP 5.2.0.
PDO::ATTR_AUTOCOMMIT (integer)
If this value is FALSE, PDO attempts to disable autocommit so that the connection begins a transaction.
PDO::ATTR_PREFETCH (integer)
Setting the prefetch size allows you to balance speed against memory usage for your 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 (integer)
Sets the timeout value in seconds for communications with the database.
PDO::ATTR_ERRMODE (integer)
See the Errors and error handling section for more information about this attribute.
PDO::ATTR_SERVER_VERSION (integer)
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 (integer)
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 (integer)
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 (integer)
PDO::ATTR_CASE (integer)
Force column names to a specific case specified by the PDO::CASE_* constants.
PDO::ATTR_CURSOR_NAME (integer)
Get or set the name to use for a cursor. Most useful when using scrollable cursors and positioned updates.
PDO::ATTR_CURSOR (integer)
Selects the cursor type. PDO currently supports either PDO::CURSOR_FWDONLY and PDO::CURSOR_SCROLL. Stick with PDO::CURSOR_FWDONLY unless you know that you need a scrollable cursor.
PDO::ATTR_DRIVER_NAME (string)
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 (integer)
Convert empty strings to SQL NULL values on data fetches.
PDO::ATTR_PERSISTENT (integer)
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 (integer)
Sets the class name of which statements are returned as.
PDO::ATTR_FETCH_CATALOG_NAMES (integer)
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 your driver.
PDO::ATTR_FETCH_TABLE_NAMES (integer)
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 your driver.
PDO::ATTR_STRINGIFY_FETCHES (integer)
Forces all values fetched to be treated as strings.
PDO::ATTR_MAX_COLUMN_LEN (integer)
Sets the maximum column name length.
PDO::ATTR_DEFAULT_FETCH_MODE (integer)
Available since PHP 5.2.0
PDO::ATTR_EMULATE_PREPARES (integer)
Available since PHP 5.1.3.
PDO::ATTR_DEFAULT_STR_PARAM (integer)
Sets the default string parameter type, this can be one of PDO::PARAM_STR_NATL and PDO::PARAM_STR_CHAR. Available since PHP 7.2.0.
PDO::ERRMODE_SILENT (integer)
Do not raise an error or exception if an error occurs. The developer is expected to explicitly check for errors. This is the default mode. See Errors and error handling for more information about this attribute.
PDO::ERRMODE_WARNING (integer)
Issue a PHP E_WARNING message if an error occurs. See Errors and error handling for more information about this attribute.
PDO::ERRMODE_EXCEPTION (integer)
Throw a PDOException if an error occurs. See Errors and error handling for more information about this attribute.
PDO::CASE_NATURAL (integer)
Leave column names as returned by the database driver.
PDO::CASE_LOWER (integer)
Force column names to lower case.
PDO::CASE_UPPER (integer)
Force column names to upper case.
PDO::NULL_NATURAL (integer)
PDO::NULL_EMPTY_STRING (integer)
PDO::NULL_TO_STRING (integer)
PDO::FETCH_ORI_NEXT (integer)
Fetch the next row in the result set. Valid only for scrollable cursors.
PDO::FETCH_ORI_PRIOR (integer)
Fetch the previous row in the result set. Valid only for scrollable cursors.
PDO::FETCH_ORI_FIRST (integer)
Fetch the first row in the result set. Valid only for scrollable cursors.
PDO::FETCH_ORI_LAST (integer)
Fetch the last row in the result set. Valid only for scrollable cursors.
PDO::FETCH_ORI_ABS (integer)
Fetch the requested row by row number from the result set. Valid only for scrollable cursors.
PDO::FETCH_ORI_REL (integer)
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 (integer)
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 (integer)
Create a PDOStatement object with a scrollable cursor. Pass the PDO::FETCH_ORI_* constants to control the rows fetched from the result set.
PDO::ERR_NONE (string)
Corresponds to SQLSTATE '00000', meaning that the SQL statement was successfully issued with no errors or warnings. This constant is for your convenience when checking PDO::errorCode() or PDOStatement::errorCode() to determine if an error occurred. You will usually know if this is the case by examining the return code from the method that raised the error condition anyway.
PDO::PARAM_EVT_ALLOC (integer)
Allocation event
PDO::PARAM_EVT_FREE (integer)
Deallocation event
PDO::PARAM_EVT_EXEC_PRE (integer)
Event triggered prior to execution of a prepared statement.
PDO::PARAM_EVT_EXEC_POST (integer)
Event triggered subsequent to execution of a prepared statement.
PDO::PARAM_EVT_FETCH_PRE (integer)
Event triggered prior to fetching a result from a resultset.
PDO::PARAM_EVT_FETCH_POST (integer)
Event triggered subsequent to fetching a result from a resultset.
PDO::PARAM_EVT_NORMALIZE (integer)
Event triggered during bound parameter registration allowing the driver to normalize the parameter name.
PDO::SQLITE_DETERMINISTIC (integer)
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);
    foreach($dbh->query('SELECT * from FOO') as $row) {
        print_r($row);
    }
    $dbh = null;
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}
?>

Warning

If your application does not catch the exception thrown from the PDO constructor, the default action taken by the zend engine is to terminate the script and display a back trace. This back trace will likely reveal the full database connection details, including the username and password. It is your responsibility to catch this exception, either explicitly (via a catch statement) or implicitly via set_exception_handler().

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

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.

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.

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 #1 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 = ?");
if ($stmt->execute(array($_GET['name']))) {
  while ($row = $stmt->fetch()) {
    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(array($_GET['name']));

// placeholder must be used in the place of the whole value
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name LIKE ?");
$stmt->execute(array("%$_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

    This is 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

    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';

try {
    $dbh = new PDO($dsn, $user, $password);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

?>

Note:

PDO::__construct() will always throw a PDOException if the connection fails regardless of which PDO::ATTR_ERRMODE is currently set. Uncaught Exceptions are fatal.

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';

/*
    Using try/catch around the constructor is still valid even though we set the ERRMODE to WARNING since
    PDO::__construct will always throw a PDOException if the connection fails.
*/
try {
    $dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
    exit;
}

// 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 18


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, PECL pdo >= 0.1.0)

Introduction

Represents a connection between PHP and a database server.

Class synopsis

PDO {
public __construct ( string $dsn [, string $username [, string $passwd [, array $options ]]] )
public beginTransaction ( void ) : bool
public commit ( void ) : bool
public errorCode ( void ) : string
public errorInfo ( void ) : array
public exec ( string $statement ) : int
public getAttribute ( int $attribute ) : mixed
public static getAvailableDrivers ( void ) : array
public inTransaction ( void ) : bool
public lastInsertId ([ string $name = NULL ] ) : string
public prepare ( string $statement [, array $driver_options = array() ] ) : PDOStatement
public query ( string $statement ) : PDOStatement
public quote ( string $string [, int $parameter_type = PDO::PARAM_STR ] ) : string
public rollBack ( void ) : bool
public setAttribute ( int $attribute , mixed $value ) : bool
}

Table of Contents

  • PDO::beginTransaction — Initiates a transaction
  • PDO::commit — Commits a transaction
  • 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 — Executes an SQL statement, returning a result set as a PDOStatement object
  • PDO::quote — Quotes a string for use in a query
  • PDO::rollBack — Rolls back a transaction
  • PDO::setAttribute — Set an attribute


Initiates a transaction

  • « PDO
  • PDO::commit »
  • PHP Manual
  • PDO
  • Initiates a transaction

PDO::beginTransaction

(PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 0.1.0)

PDO::beginTransaction — Initiates a transaction

Description

public PDO::beginTransaction ( void ) : 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.

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


Commits a transaction

  • « PDO::beginTransaction
  • PDO::__construct »
  • PHP Manual
  • PDO
  • Commits a transaction

PDO::commit

(PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 0.1.0)

PDO::commit — Commits a transaction

Description

public PDO::commit ( void ) : bool

Commits a transaction, returning the database connection to autocommit mode until the next call to PDO::beginTransaction() starts a new transaction.

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


Creates a PDO instance representing a connection to a database

  • « PDO::commit
  • PDO::errorCode »
  • PHP Manual
  • PDO
  • Creates a PDO instance representing a connection to a database

PDO::__construct

(PHP 5 >= 5.1.0, PHP 7, 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 [, string $passwd [, array $options ]]] )

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.

passwd

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 a PDO object on success.

Errors/Exceptions

PDO::__construct() throws a PDOException if the attempt to connect to the requested database fails.

Examples

Example #1 Create a PDO instance via driver invocation

<?php
/* Connect to a MySQL database using driver invocation */
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

?>

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
/* Connect to an ODBC database using driver invocation */
$dsn = 'uri:file:///usr/local/dbconnect';
$user = '';
$password = '';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

?>

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
/* Connect to an ODBC database using an alias */
$dsn = 'mydb';
$user = '';
$password = '';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

?>

Changelog

Version | Description
5.3.0 | Classes which extends PDO and implements the __call magic method will now receive the method name in the declared casing. Previously this was always lower case.


Fetch the SQLSTATE associated with the last operation on the database handle

  • « PDO::__construct
  • PDO::errorInfo »
  • PHP Manual
  • PDO
  • Fetch the SQLSTATE associated with the last operation on the database handle

PDO::errorCode

(PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 0.1.0)

PDO::errorCode — Fetch the SQLSTATE associated with the last operation on the database handle

Description

public PDO::errorCode ( void ) : string

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


Fetch extended error information associated with the last operation on the database handle

  • « PDO::errorCode
  • PDO::exec »
  • PHP Manual
  • PDO
  • Fetch extended error information associated with the last operation on the database handle

PDO::errorInfo

(PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 0.1.0)

PDO::errorInfo — Fetch extended error information associated with the last operation on the database handle

Description

public PDO::errorInfo ( void ) : array

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


Execute an SQL statement and return the number of affected rows

  • « PDO::errorInfo
  • PDO::getAttribute »
  • PHP Manual
  • PDO
  • Execute an SQL statement and return the number of affected rows

PDO::exec

(PHP 5 >= 5.1.0, PHP 7, 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

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

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() - Executes an SQL statement, returning a result set as a PDOStatement object
  • PDOStatement::execute() - Executes a prepared statement


Retrieve a database connection attribute

  • « PDO::exec
  • PDO::getAvailableDrivers »
  • PHP Manual
  • PDO
  • Retrieve a database connection attribute

PDO::getAttribute

(PHP 5 >= 5.1.0, PHP 7, 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 constants 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

Return Values

A successful call returns the value of the requested PDO attribute. An unsuccessful call returns null.

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


Return an array of available PDO drivers

  • « PDO::getAttribute
  • PDO::inTransaction »
  • PHP Manual
  • PDO
  • Return an array of available PDO drivers

PDO::getAvailableDrivers

pdo_drivers

(PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 1.0.3)

PDO::getAvailableDrivers -- pdo_drivers — Return an array of available PDO drivers

Description

public static PDO::getAvailableDrivers ( void ) : array
pdo_drivers ( void ) : array

This function returns all currently available PDO drivers which can be used in DSN parameter of PDO::__construct().

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
)


Checks if inside a transaction

  • « PDO::getAvailableDrivers
  • PDO::lastInsertId »
  • PHP Manual
  • PDO
  • Checks if inside a transaction

PDO::inTransaction

(PHP 5 >= 5.3.3, Bundled pdo_pgsql, PHP 7)

PDO::inTransaction — Checks if inside a transaction

Description

public PDO::inTransaction ( void ) : 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.


Returns the ID of the last inserted row or sequence value

  • « PDO::inTransaction
  • PDO::prepare »
  • PHP Manual
  • PDO
  • Returns the ID of the last inserted row or sequence value

PDO::lastInsertId

(PHP 5 >= 5.1.0, PHP 7, 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

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 requires you to specify the name of a sequence object 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.


Prepares a statement for execution and returns a statement object

  • « PDO::lastInsertId
  • PDO::query »
  • PHP Manual
  • PDO
  • Prepares a statement for execution and returns a statement object

PDO::prepare

(PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 0.1.0)

PDO::prepare — Prepares a statement for execution and returns a statement object

Description

public PDO::prepare ( string $statement [, array $driver_options = array() ] ) : PDOStatement

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.

Parameters

statement

This must be a valid SQL statement template for the target database server.

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

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, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
$red = $sth->fetchAll();
$sth->execute(array(':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(array(150, 'red'));
$red = $sth->fetchAll();
$sth->execute(array(175, 'yellow'));
$yellow = $sth->fetchAll();
?>

See Also

  • PDO::exec() - Execute an SQL statement and return the number of affected rows
  • PDO::query() - Executes an SQL statement, returning a result set as a PDOStatement object
  • PDOStatement::execute() - Executes a prepared statement


Executes an SQL statement, returning a result set as a PDOStatement object

  • « PDO::prepare
  • PDO::quote »
  • PHP Manual
  • PDO
  • Executes an SQL statement, returning a result set as a PDOStatement object

PDO::query

(PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 0.2.0)

PDO::query — Executes an SQL statement, returning a result set as a PDOStatement object

Description

public PDO::query ( string $statement ) : PDOStatement
public PDO::query ( string $statement , int $fetch_style = PDO::FETCH_COLUMN , int $colno ) : PDOStatement
public PDO::query ( string $statement , int $fetch_style = PDO::FETCH_CLASS , string $classname , array $ctorargs ) : PDOStatement
public PDO::query ( string $statement , int $fetch_style = PDO::FETCH_INTO , object $object ) : PDOStatement

PDO::query() executes an SQL statement in a single function call, returning the result set (if any) returned by 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 more than one argument is passed to this function, the remaining arguments will be treated as though you called PDOStatement::setFetchMode() on the resultant statement object.

Parameters

statement

The SQL statement to prepare and execute.

Data inside the query should be properly escaped.

Return Values

PDO::query() returns a PDOStatement object, or FALSE on failure.

Examples

Example #1 Demonstrate PDO::query

A nice feature of PDO::query() is that it enables you to iterate over the rowset returned by a successfully executed SELECT statement.

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


Quotes a string for use in a query

  • « PDO::query
  • PDO::rollBack »
  • PHP Manual
  • PDO
  • Quotes a string for use in a query

PDO::quote

(PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 0.2.1)

PDO::quote — Quotes a string for use in a query

Description

public PDO::quote ( string $string [, int $parameter_type = PDO::PARAM_STR ] ) : string

PDO::quote() places quotes around the input string (if required) 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.

parameter_type

Provides a data type hint for drivers that have alternate quoting styles.

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


Rolls back a transaction

  • « PDO::quote
  • PDO::setAttribute »
  • PHP Manual
  • PDO
  • Rolls back a transaction

PDO::rollBack

(PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 0.1.0)

PDO::rollBack — Rolls back a transaction

Description

public PDO::rollBack ( void ) : 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.

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


Set an attribute

  • « PDO::rollBack
  • PDOStatement »
  • PHP Manual
  • PDO
  • Set an attribute

PDO::setAttribute

(PHP 5 >= 5.1.0, PHP 7, 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 of the available generic attributes are listed below; some drivers may make use of additional driver specific attributes.

  • PDO::ATTR_CASE: Force column names to a specific case.

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

    • PDO::ERRMODE_SILENT: Just set error codes.

    • PDO::ERRMODE_WARNING: Raise E_WARNING.

    • PDO::ERRMODE_EXCEPTION: Throw exceptions.

  • PDO::ATTR_ORACLE_NULLS (available with all drivers, not just Oracle): Conversion of NULL and empty strings.

    • PDO::NULL_NATURAL: No conversion.

    • PDO::NULL_EMPTY_STRING: Empty string is converted to NULL.

    • PDO::NULL_TO_STRING: NULL is converted to an empty string.

  • PDO::ATTR_STRINGIFY_FETCHES: Convert numeric values to strings when fetching. Requires bool.

  • PDO::ATTR_STATEMENT_CLASS: Set user-supplied statement class derived from PDOStatement. Cannot be used with persistent PDO instances. Requires array(string classname, array(mixed constructor_args)).

  • PDO::ATTR_TIMEOUT: Specifies the timeout duration in seconds. 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 an writable lock, but other drivers may interpret this as a connect or a read timeout interval. Requires int.

  • PDO::ATTR_AUTOCOMMIT (available in OCI, Firebird and MySQL): Whether to autocommit every single statement.

  • PDO::ATTR_EMULATE_PREPARES Enables or disables emulation of prepared statements. Some drivers do not support native prepared statements or have limited support for them. Use this setting to force PDO to either always emulate prepared statements (if TRUE and emulated prepares are supported by the driver), or to try to use native prepared statements (if FALSE). It will always fall back to emulating the prepared statement if the driver cannot successfully prepare the current query. Requires bool.

  • PDO::MYSQL_ATTR_USE_BUFFERED_QUERY (available in MySQL): Use buffered queries.

  • PDO::ATTR_DEFAULT_FETCH_MODE: Set default fetch mode. Description of modes is available in PDOStatement::fetch() documentation.

Return Values

Returns TRUE on success or FALSE on failure.


The PDOStatement class

(PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 1.0.0)

Introduction

Represents a prepared statement and, after the statement is executed, an associated result set.

Class synopsis

PDOStatement implements Traversable {
/* Properties */
readonly string $queryString;
/* Methods */
public bindColumn ( mixed $column , mixed &$param [, int $type [, int $maxlen [, mixed $driverdata ]]] ) : bool
public bindParam ( mixed $parameter , mixed &$variable [, int $data_type = PDO::PARAM_STR [, int $length [, mixed $driver_options ]]] ) : bool
public bindValue ( mixed $parameter , mixed $value [, int $data_type = PDO::PARAM_STR ] ) : bool
public closeCursor ( void ) : bool
public columnCount ( void ) : int
public debugDumpParams ( void ) : void
public errorCode ( void ) : string
public errorInfo ( void ) : array
public execute ([ array $input_parameters ] ) : bool
public fetch ([ int $fetch_style [, int $cursor_orientation = PDO::FETCH_ORI_NEXT [, int $cursor_offset = 0 ]]] ) : mixed
public fetchAll ([ int $fetch_style [, mixed $fetch_argument [, array $ctor_args = array() ]]] ) : array
public fetchColumn ([ int $column_number = 0 ] ) : mixed
public fetchObject ([ string $class_name = "stdClass" [, array $ctor_args ]] ) : mixed
public getAttribute ( int $attribute ) : mixed
public getColumnMeta ( int $column ) : array
public nextRowset ( void ) : bool
public rowCount ( void ) : int
public setAttribute ( int $attribute , mixed $value ) : bool
public setFetchMode ( int $mode ) : bool
}

Properties

queryString

Used query string.

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 — Returns an array containing all of the result set rows
  • 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::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


Bind a column to a PHP variable

  • « PDOStatement
  • PDOStatement::bindParam »
  • PHP Manual
  • PDOStatement
  • Bind a column to a PHP variable

PDOStatement::bindColumn

(PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 0.1.0)

PDOStatement::bindColumn — Bind a column to a PHP variable

Description

public PDOStatement::bindColumn ( mixed $column , mixed &$param [, int $type [, int $maxlen [, mixed $driverdata ]]] ) : 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.

param

Name of the PHP variable to which the column will be bound.

type

Data type of the parameter, specified by the PDO::PARAM_* constants.

maxlen

A hint for pre-allocation.

driverdata

Optional parameter(s) for the driver.

Return Values

Returns TRUE on success or FALSE on failure.

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
function readData($dbh) {
  $sql = 'SELECT name, colour, calories FROM fruit';
  try {
    $stmt = $dbh->prepare($sql);
    $stmt->execute();

    /* Bind by column number */
    $stmt->bindColumn(1, $name);
    $stmt->bindColumn(2, $colour);

    /* Bind by column name */
    $stmt->bindColumn('calories', $cals);

    while ($row = $stmt->fetch(PDO::FETCH_BOUND)) {
      $data = $name . "\t" . $colour . "\t" . $cals . "\n";
      print $data;
    }
  }
  catch (PDOException $e) {
    print $e->getMessage();
  }
}
readData($dbh);
?>

The above example will output:

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() - Returns an array containing all of the result set rows
  • PDOStatement::fetchColumn() - Returns a single column from the next row of a result set


Binds a parameter to the specified variable name

  • « PDOStatement::bindColumn
  • PDOStatement::bindValue »
  • PHP Manual
  • PDOStatement
  • Binds a parameter to the specified variable name

PDOStatement::bindParam

(PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 0.1.0)

PDOStatement::bindParam — Binds a parameter to the specified variable name

Description

public PDOStatement::bindParam ( mixed $parameter , mixed &$variable [, int $data_type = PDO::PARAM_STR [, int $length [, mixed $driver_options ]]] ) : 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. 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

parameter

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.

variable

Name of the PHP variable to bind to the SQL statement parameter.

data_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 data_type parameter.

length

Length of the data type. To indicate that a parameter is an OUT parameter from a stored procedure, you must explicitly set the length.

driver_options

Return Values

Returns TRUE on success or FALSE on failure.

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);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$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, 12);
$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


Binds a value to a parameter

  • « PDOStatement::bindParam
  • PDOStatement::closeCursor »
  • PHP Manual
  • PDOStatement
  • Binds a value to a parameter

PDOStatement::bindValue

(PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 1.0.0)

PDOStatement::bindValue — Binds a value to a parameter

Description

public PDOStatement::bindValue ( mixed $parameter , mixed $value [, int $data_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

parameter

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.

data_type

Explicit data type for the parameter using the PDO::PARAM_* constants.

Return Values

Returns TRUE on success or FALSE on failure.

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->bindValue(':calories', $calories, PDO::PARAM_INT);
$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


Closes the cursor, enabling the statement to be executed again

  • « PDOStatement::bindValue
  • PDOStatement::columnCount »
  • PHP Manual
  • PDOStatement
  • Closes the cursor, enabling the statement to be executed again

PDOStatement::closeCursor

(PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 0.9.0)

PDOStatement::closeCursor — Closes the cursor, enabling the statement to be executed again

Description

public PDOStatement::closeCursor ( void ) : 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);
?>

Return Values

Returns TRUE on success or FALSE on failure.

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


Returns the number of columns in the result set

  • « PDOStatement::closeCursor
  • PDOStatement::debugDumpParams »
  • PHP Manual
  • PDOStatement
  • Returns the number of columns in the result set

PDOStatement::columnCount

(PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 0.2.0)

PDOStatement::columnCount — Returns the number of columns in the result set

Description

public PDOStatement::columnCount ( void ) : 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().

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.

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


Dump an SQL prepared command

  • « PDOStatement::columnCount
  • PDOStatement::errorCode »
  • PHP Manual
  • PDOStatement
  • Dump an SQL prepared command

PDOStatement::debugDumpParams

(PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 0.9.0)

PDOStatement::debugDumpParams — Dump an SQL prepared command

Description

public PDOStatement::debugDumpParams ( void ) : void

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.

Return Values

No value is returned.

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

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.

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


Fetch the SQLSTATE associated with the last operation on the statement handle

  • « PDOStatement::debugDumpParams
  • PDOStatement::errorInfo »
  • PHP Manual
  • PDOStatement
  • Fetch the SQLSTATE associated with the last operation on the statement handle

PDOStatement::errorCode

(PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 0.1.0)

PDOStatement::errorCode — Fetch the SQLSTATE associated with the last operation on the statement handle

Description

public PDOStatement::errorCode ( void ) : string

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


Fetch extended error information associated with the last operation on the statement handle

  • « PDOStatement::errorCode
  • PDOStatement::execute »
  • PHP Manual
  • PDOStatement
  • Fetch extended error information associated with the last operation on the statement handle

PDOStatement::errorInfo

(PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 0.1.0)

PDOStatement::errorInfo — Fetch extended error information associated with the last operation on the statement handle

Description

public PDOStatement::errorInfo ( void ) : array

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


Executes a prepared statement

  • « PDOStatement::errorInfo
  • PDOStatement::fetch »
  • PHP Manual
  • PDOStatement
  • Executes a prepared statement

PDOStatement::execute

(PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 0.1.0)

PDOStatement::execute — Executes a prepared statement

Description

public PDOStatement::execute ([ array $input_parameters ] ) : 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

input_parameters

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

Changelog

Version | Description
5.2.0 | The keys from input_parameters must match the ones declared in the SQL. Before PHP 5.2.0 this was silently ignored.

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);
$sth->bindValue(':colour', "%{$colour}%");
$sth->execute();
?>

Example #2 Execute a prepared statement with an array of insert values (named parameters)

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

Example #3 Execute a prepared statement with an array of insert values (placeholders)

<?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 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, 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 = implode(',', array_fill(0, count($params), '?'));

/*
    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() - Returns an array containing all of the result set rows
  • PDOStatement::fetchColumn() - Returns a single column from the next row of a result set


Fetches the next row from a result set

  • « PDOStatement::execute
  • PDOStatement::fetchAll »
  • PHP Manual
  • PDOStatement
  • Fetches the next row from a result set

PDOStatement::fetch

(PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 0.1.0)

PDOStatement::fetch — Fetches the next row from a result set

Description

public PDOStatement::fetch ([ int $fetch_style [, int $cursor_orientation = PDO::FETCH_ORI_NEXT [, int $cursor_offset = 0 ]]] ) : mixed

Fetches a row from a result set associated with a PDOStatement object. The fetch_style parameter determines how PDO returns the row.

Parameters

fetch_style

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, mapping the columns of the result set to named properties in the class, and calling the constructor afterwards, unless PDO::FETCH_PROPS_LATE is also given. If fetch_style includes PDO::FETCH_CLASSTYPE (e.g. PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE) then the name of the class is determined from a 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, creating the object variable 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.

cursor_orientation

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

offset

For a PDOStatement object representing a scrollable cursor for which the cursor_orientation 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 cursor_orientation 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.

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 an anonymous 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 an anonymous 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';
  try {
    $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;
    }
    $stmt = null;
  }
  catch (PDOException $e) {
    print $e->getMessage();
  }
}
function readDataBackwards($dbh) {
  $sql = 'SELECT hand, won, bet FROM mynumbers ORDER BY bet';
  try {
    $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));
    $stmt = null;
  }
  catch (PDOException $e) {
    print $e->getMessage();
  }
}

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. If 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() - Returns an array containing all of the result set rows
  • 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


Returns an array containing all of the result set rows

  • « PDOStatement::fetch
  • PDOStatement::fetchColumn »
  • PHP Manual
  • PDOStatement
  • Returns an array containing all of the result set rows

PDOStatement::fetchAll

(PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 0.1.0)

PDOStatement::fetchAll — Returns an array containing all of the result set rows

Description

public PDOStatement::fetchAll ([ int $fetch_style [, mixed $fetch_argument [, array $ctor_args = array() ]]] ) : array

Parameters

fetch_style

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 fetch_argument parameter.

To fetch only the unique values of a single column from the result set, bitwise-OR PDO::FETCH_COLUMN with PDO::FETCH_UNIQUE.

To return an associative array grouped by the values of a specified column, bitwise-OR PDO::FETCH_COLUMN with PDO::FETCH_GROUP.

fetch_argument

This argument has a different meaning depending on the value of the fetch_style parameter:

  • PDO::FETCH_COLUMN: Returns the indicated 0-indexed column.

  • PDO::FETCH_CLASS: Returns instances of the specified class, mapping the columns of each row to named properties in the class.

  • PDO::FETCH_FUNC: Returns the results of calling the specified function, using each row's columns as parameters in the call.

ctor_args

Arguments of custom class constructor when the fetch_style parameter is PDO::FETCH_CLASS.

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, or FALSE on failure.

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.

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() - Executes an SQL statement, returning a result set as a PDOStatement object
  • 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


Returns a single column from the next row of a result set

  • « PDOStatement::fetchAll
  • PDOStatement::fetchObject »
  • PHP Manual
  • PDOStatement
  • Returns a single column from the next row of a result set

PDOStatement::fetchColumn

(PHP 5 >= 5.1.0, PHP 7, 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_number = 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_number

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.

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() - Executes an SQL statement, returning a result set as a PDOStatement object
  • PDOStatement::fetch() - Fetches the next row from a result set
  • PDOStatement::fetchAll() - Returns an array containing all of the result set rows
  • PDO::prepare() - Prepares a statement for execution and returns a statement object
  • PDOStatement::setFetchMode() - Set the default fetch mode for this statement


Fetches the next row and returns it as an object

  • « PDOStatement::fetchColumn
  • PDOStatement::getAttribute »
  • PHP Manual
  • PDOStatement
  • Fetches the next row and returns it as an object

PDOStatement::fetchObject

(PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 0.2.4)

PDOStatement::fetchObject — Fetches the next row and returns it as an object

Description

public PDOStatement::fetchObject ([ string $class_name = "stdClass" [, array $ctor_args ]] ) : mixed

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

Name of the created class.

ctor_args

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.

See Also

  • PDOStatement::fetch() - Fetches the next row from a result set


Retrieve a statement attribute

  • « PDOStatement::fetchObject
  • PDOStatement::getColumnMeta »
  • PHP Manual
  • PDOStatement
  • Retrieve a statement attribute

PDOStatement::getAttribute

(PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 0.2.0)

PDOStatement::getAttribute — Retrieve a statement attribute

Description

public PDOStatement::getAttribute ( int $attribute ) : 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.

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


Returns metadata for a column in a result set

  • « PDOStatement::getAttribute
  • PDOStatement::nextRowset »
  • PHP Manual
  • PDOStatement
  • Returns metadata for a column in a result set

PDOStatement::getColumnMeta

(PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 0.2.0)

PDOStatement::getColumnMeta — Returns metadata for a column in a result set

Description

public PDOStatement::getColumnMeta ( int $column ) : array

Retrieves the metadata for a 0-indexed column in a result set as an associative array.

Warning

Not all PDO drivers support PDOStatement::getColumnMeta().

The following drivers support this method:

  • PDO_DBLIB
  • PDO_MYSQL
  • PDO_PGSQL
  • PDO_SQLITE

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.

Changelog

Version | Description
5.4.0 | PDO_DBLIB driver support added
5.2.3 | table field

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


Advances to the next rowset in a multi-rowset statement handle

  • « PDOStatement::getColumnMeta
  • PDOStatement::rowCount »
  • PHP Manual
  • PDOStatement
  • Advances to the next rowset in a multi-rowset statement handle

PDOStatement::nextRowset

(PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 0.2.0)

PDOStatement::nextRowset — Advances to the next rowset in a multi-rowset statement handle

Description

public PDOStatement::nextRowset ( void ) : 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.

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, that returns three rowsets. We use a do / while loop to loop over the PDOStatement::nextRowset() method, which returns false and terminates the loop when no more rowsets can be returned.

<?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() - Executes an SQL statement, returning a result set as a PDOStatement object


Returns the number of rows affected by the last SQL statement

  • « PDOStatement::nextRowset
  • PDOStatement::setAttribute »
  • PHP Manual
  • PDOStatement
  • Returns the number of rows affected by the last SQL statement

PDOStatement::rowCount

(PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 0.1.0)

PDOStatement::rowCount — Returns the number of rows affected by the last SQL statement

Description

public PDOStatement::rowCount ( void ) : int

PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.

If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.

Note:

This method returns "0" (zero) with the SQLite driver at all times, and with the PostgreSQL driver only when setting the PDO::ATTR_CURSOR statement attribute to PDO::CURSOR_SCROLL.

Return Values

Returns the number of rows.

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:

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 rows that will be returned. Your application can then perform the correct action.

<?php
$sql = "SELECT COUNT(*) FROM fruit WHERE calories > 100";
if ($res = $conn->query($sql)) {

    /* Check the number of rows that match the SELECT statement */
    if ($res->fetchColumn() > 0) {

        /* Issue the real SELECT statement and work with the results */
        $sql = "SELECT name FROM fruit WHERE calories > 100";

        foreach ($conn->query($sql) as $row) {
            print "Name: " .  $row['NAME'] . "\n";
        }
    }
    /* No rows matched -- do something else */
    else {
        print "No rows matched the query.";
    }
}

$res = null;
$conn = null;
?>

The above example will output:

apple
banana
orange
pear

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() - Executes an SQL statement, returning a result set as a PDOStatement object


Set a statement attribute

  • « PDOStatement::rowCount
  • PDOStatement::setFetchMode »
  • PHP Manual
  • PDOStatement
  • Set a statement attribute

PDOStatement::setAttribute

(PHP 5 >= 5.1.0, PHP 7, 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.

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


Set the default fetch mode for this statement

  • « PDOStatement::setAttribute
  • PDOException »
  • PHP Manual
  • PDOStatement
  • Set the default fetch mode for this statement

PDOStatement::setFetchMode

(PHP 5 >= 5.1.0, PHP 7, 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 $classname , array $ctorargs ) : 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.

classname

Class name.

ctorargs

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
$sql = 'SELECT name, colour, calories FROM fruit';
try {
  $stmt = $dbh->query($sql);
  $result = $stmt->setFetchMode(PDO::FETCH_NUM);
  while ($row = $stmt->fetch()) {
    print $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
  }
}
catch (PDOException $e) {
  print $e->getMessage();
}
?>

The above example will output:

apple   red     150
banana  yellow  250
orange  orange  300
kiwi    brown   75
lemon   yellow  25
pear    green   150
watermelon      pink    90


The PDOException class

(PHP 5 >= 5.1.0, PHP 7)

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

PDOException extends RuntimeException {
/* Properties */
public array $errorInfo ;
protected string $code ;
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : 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)
  • MS SQL Server (PDO)
  • Firebird (PDO)
  • IBM (PDO)
  • Informix (PDO)
  • MySQL (PDO)
  • MS SQL Server (PDO)
  • Oracle (PDO)
  • ODBC and DB2 (PDO)
  • PostgreSQL (PDO)
  • SQLite (PDO)
  • 4D (PDO)

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
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
PDO_4D | 4D


CUBRID Functions (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 your 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.

Features

PDO_CUBRID Features
Feature | Description
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 that before disabling the 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 a function 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:(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.

Table of Contents

  • PDO_CUBRID DSN — Connecting to CUBRID databases
  • PDO::cubrid_schema — Get the requested schema information


Connecting to CUBRID databases

  • « CUBRID (PDO)
  • PDO::cubrid_schema »
  • PHP Manual
  • CUBRID (PDO)
  • Connecting to CUBRID databases

PDO_CUBRID DSN

(No version information available, might only be in Git)

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


Get the requested schema information

  • « PDO_CUBRID DSN
  • MS SQL Server (PDO) »
  • PHP Manual
  • CUBRID (PDO)
  • Get the requested schema information

PDO::cubrid_schema

(No version information available, might only be in Git)

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
        )

)


Microsoft SQL Server and Sybase Functions (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 with PHP 5.3 or later.

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.

Table of Contents

  • PDO_DBLIB DSN — Connecting to Microsoft SQL Server and Sybase databases


Connecting to Microsoft SQL Server and Sybase databases

  • « MS SQL Server (PDO)
  • Firebird (PDO) »
  • PHP Manual
  • MS SQL Server (PDO)
  • Connecting to Microsoft SQL Server and Sybase databases

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


Firebird Functions (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 (integer)

Available since PHP 5.3.0.

Sets the date format.

PDO::FB_ATTR_TIME_FORMAT (integer)

Sets the time format.

Available since PHP 5.3.0.

PDO::FB_ATTR_TIMESTAMP_FORMAT (integer)

Sets the timestamp format.

Available since PHP 5.3.0.

Table of Contents

  • PDO_FIREBIRD DSN — Connecting to Firebird databases


Connecting to Firebird databases

  • « Firebird (PDO)
  • IBM (PDO) »
  • PHP Manual
  • Firebird (PDO)
  • Connecting to Firebird databases

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


IBM Functions (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 your 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.

Table of Contents

  • PDO_IBM DSN — Connecting to IBM databases


Connecting to IBM databases

  • « IBM (PDO)
  • Informix (PDO) »
  • PHP Manual
  • IBM (PDO)
  • Connecting to IBM databases

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");


Informix Functions (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 your 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.

Table of Contents

  • PDO_INFORMIX DSN — Connecting to Informix databases


Connecting to Informix databases

  • « Informix (PDO)
  • MySQL (PDO) »
  • PHP Manual
  • Informix (PDO)
  • Connecting to Informix databases

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");


MySQL Functions (PDO_MYSQL)

Introduction

PDO_MYSQL is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to MySQL databases.

As of PHP 5.2.1, PDO_MYSQL uses emulated prepares by default. Formerly, PDO_MYSQL defaulted to native prepared statement support present in MySQL 4.1 and higher, and emulated them for older versions of the mysql client libraries.

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 will be supported in a future PHP release. In the meantime, 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.

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 than 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. As of PHP 5.4, 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 constants, 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.

Changelog
Version | Description
5.4.0 | mysqlnd became the default MySQL library when compiling PDO_MYSQL. Previously, libmysqlclient was the default MySQL library.
5.4.0 | MySQL client libraries 4.1 and below are no longer supported.
5.3.9 | Added SSL support with mysqlnd and OpenSSL.
5.3.7 | Added SSL support with libmysqlclient and OpenSSL.

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 (integer)
If this attribute is set to TRUE on a PDOStatement, the MySQL driver will use the buffered versions of the MySQL API. If you're writing portable code, you should use PDOStatement::fetchAll() instead.

Example #1 Forcing queries to be buffered in mysql

<?php
if ($db->getAttribute(PDO::ATTR_DRIVER_NAME) == 'mysql') {
    $stmt = $db->prepare('select * from foo',
        array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true));
} else {
    die("my application only works with mysql; I should use \$stmt->fetchAll() instead");
}
?>

PDO::MYSQL_ATTR_LOCAL_INFILE (integer)

Enable LOAD LOCAL INFILE.

Note, this constant can only be used in the driver_options array when constructing a new database handle.

PDO::MYSQL_ATTR_INIT_COMMAND (integer)

Command to execute when connecting to the MySQL server. Will automatically be re-executed when reconnecting.

Note, this constant can only be used in the driver_options array when constructing a new database handle.

PDO::MYSQL_ATTR_READ_DEFAULT_FILE (integer)

Read options from the named option file instead of from my.cnf. This option is not available if mysqlnd is used, because mysqlnd does not read the mysql configuration files.

PDO::MYSQL_ATTR_READ_DEFAULT_GROUP (integer)

Read options from the named group from my.cnf or the file specified with MYSQL_READ_DEFAULT_FILE. This option is not available if mysqlnd is used, because mysqlnd does not read the mysql configuration files.

PDO::MYSQL_ATTR_MAX_BUFFER_SIZE (integer)

Maximum buffer size. Defaults to 1 MiB. This constant is not supported when compiled against mysqlnd.

PDO::MYSQL_ATTR_DIRECT_QUERY (integer)

Perform direct queries, don't use prepared statements.

PDO::MYSQL_ATTR_FOUND_ROWS (integer)

Return the number of found (matched) rows, not the number of changed rows.

PDO::MYSQL_ATTR_IGNORE_SPACE (integer)

Permit spaces after function names. Makes all functions names reserved words.

PDO::MYSQL_ATTR_COMPRESS (integer)

Enable network communication compression. This is also supported when compiled against mysqlnd as of PHP 5.3.11.

PDO::MYSQL_ATTR_SSL_CA (integer)

The file path to the SSL certificate authority.

This exists as of PHP 5.3.7.

PDO::MYSQL_ATTR_SSL_CAPATH (integer)

The file path to the directory that contains the trusted SSL CA certificates, which are stored in PEM format.

This exists as of PHP 5.3.7.

PDO::MYSQL_ATTR_SSL_CERT (integer)

The file path to the SSL certificate.

This exists as of PHP 5.3.7.

PDO::MYSQL_ATTR_SSL_CIPHER (integer)

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

This exists as of PHP 5.3.7.

PDO::MYSQL_ATTR_SSL_KEY (integer)

The file path to the SSL key.

This exists as of PHP 5.3.7.

PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT (integer)

Provides a way to disable verification of the server SSL certificate.

This exists as of PHP 7.0.18 and PHP 7.1.4.

PDO::MYSQL_ATTR_MULTI_STATEMENTS (integer)

Disables multi query execution in both PDO::prepare() and PDO::query() when set to FALSE.

Note, this constant can only be used in the driver_options array when constructing a new database handle.

This exists as of PHP 5.5.21 and PHP 5.6.5.

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" | PHP_INI_SYSTEM
pdo_mysql.debug | NULL | PHP_INI_SYSTEM
For further details and definitions of the PHP_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 boolean

Enables debugging for PDO_MYSQL. This setting is only available when PDO_MYSQL is compiled against mysqlnd and in PDO debug mode.

Table of Contents

  • PDO_MYSQL DSN — Connecting to MySQL databases


Connecting to MySQL databases

  • « MySQL (PDO)
  • MS SQL Server (PDO) »
  • PHP Manual
  • MySQL (PDO)
  • Connecting to MySQL databases

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.

Prior to PHP 5.3.6, this element was silently ignored. The same behaviour can be partly replicated with the PDO::MYSQL_ATTR_INIT_COMMAND driver option, as the following example shows.

Warning

The method in the below example can only be used with character sets that share the same lower 7 bit representation as ASCII, such as ISO-8859-1 and UTF-8. Users using character sets that have different representations (such as UTF-16 or Big5) must use the charset option provided in PHP 5.3.6 and later versions.

Example #1 Setting the connection character set to UTF-8 prior to PHP 5.3.6

<?php
$dsn = 'mysql:host=localhost;dbname=testdb';
$username = 'username';
$password = 'password';
$options = array(
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);

$dbh = new PDO($dsn, $username, $password, $options);
?>

Changelog

Version | Description
5.3.6 | Prior to version 5.3.6, charset was ignored.

Examples

Example #2 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 thru 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 thru the pdo_mysql.default_socket setting.


Microsoft SQL Server Functions (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 PDO_SQLSRV extension is enabled by adding appropriate DLL file to your PHP extension directory and the corresponding entry to the php.ini file. The PDO_SQLSRV download comes 8 driver files, four of which are for PDO support. If you are running non-thread-safe PHP (PHP 5.3), use the php_pdo_sqlsrv_53_nts.dll file. (You should use a non-thread-safe version if you are using IIS as your web server). If you are running thread-safe PHP, use the php_pdo_sqlsrv_53_ts.dll file. Similarly for PHP 5.4, use the php_pdo_sqlsrv_54_nts.dll or php_pdo_sqlsrv_54_ts.dll depending on whether your PHP installation is non-thread-safe or thread-safe.

The most recent version of the driver is available for download here: » SQLSRV download. If you need support for PHP 5.2 and/or PHP compiled with VC6, use the 2.0 release of the driver: » SQLSRV 2.0 download. The driver sources are hosted in a » public repository.

For more information about system requirements, see » SQLSRV System Requirements.

The PDO_SQLSRV extension is only compatible with PHP running on Windows. For Linux, see ODBC and » Microsoft's SQL Server ODBC Driver for Linux.

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

Table of Contents

  • PDO_SQLSRV DSN — Connecting to MS SQL Server and SQL Azure databases


Connecting to MS SQL Server and SQL Azure databases

  • « MS SQL Server (PDO)
  • Oracle (PDO) »
  • PHP Manual
  • MS SQL Server (PDO)
  • Connecting to MS SQL Server and SQL Azure databases

PDO_SQLSRV DSN

(No version information available, might only be in Git)

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 connecto 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 connecto 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");


Oracle Functions (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.

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

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

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

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

Provides a way to specify the module on the database session.

This exists as of PHP 7.2.16 and 7.3.3

Table of Contents

  • PDO_OCI DSN — Connecting to Oracle databases


Connecting to Oracle databases

  • « Oracle (PDO)
  • ODBC and DB2 (PDO) »
  • PHP Manual
  • Oracle (PDO)
  • Connecting to Oracle databases

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


ODBC and DB2 Functions (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, and is the recommended driver for connecting to Microsoft SQL Server databases.

Installation

PDO_ODBC on UNIX systems

  1. As of PHP 5.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

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" | PHP_INI_ALL | Available since PHP 5.1.0.
pdo_odbc.db2_instance_name | NULL | PHP_INI_SYSTEM | Available since PHP 5.1.1. This deprecated feature will certainly be removed in the future.
For further details and definitions of the PHP_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.

Table of Contents

  • PDO_ODBC DSN — Connecting to ODBC or DB2 databases


Connecting to ODBC or DB2 databases

  • « ODBC and DB2 (PDO)
  • PostgreSQL (PDO) »
  • PHP Manual
  • ODBC and DB2 (PDO)
  • Connecting to ODBC or DB2 databases

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.

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


PostgreSQL Functions (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

Table of Contents

  • PDO_PGSQL DSN — Connecting to PostgreSQL databases
  • PDO::pgsqlCopyFromArray — Copy data from PHP array into table
  • PDO::pgsqlCopyFromFile — Copy data from file into table
  • PDO::pgsqlCopyToArray — Copy data from database table into PHP array
  • PDO::pgsqlCopyToFile — Copy data from table into file
  • PDO::pgsqlGetNotify — Get asynchronous notification
  • PDO::pgsqlGetPid — Get the server PID
  • PDO::pgsqlLOBCreate — Creates a new large object
  • PDO::pgsqlLOBOpen — Opens an existing large object stream
  • PDO::pgsqlLOBUnlink — Deletes the large object


Connecting to PostgreSQL databases

  • « PostgreSQL (PDO)
  • PDO::pgsqlCopyFromArray »
  • PHP Manual
  • PostgreSQL (PDO)
  • Connecting to PostgreSQL databases

PDO_PGSQL DSN

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

Note:

The bytea fields are returned as streams.

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


Copy data from PHP array into table

  • « PDO_PGSQL DSN
  • PDO::pgsqlCopyFromFile »
  • PHP Manual
  • PostgreSQL (PDO)
  • Copy data from PHP array into table

PDO::pgsqlCopyFromArray

(PHP 5 >= 5.3.3, PHP 7)

PDO::pgsqlCopyFromArray — Copy data from PHP array into table

Description

public PDO::pgsqlCopyFromArray ( string $table_name , array $rows [, string $delimiter = '\t' [, string $null_as = "\\\\N" [, string $fields ]]] ) : bool

Copies data from rows array to table table_name using delimiter as fields delimiter and fields list

Parameters

table_name

String containing table name

rows

Array of strings with fields separated by delimiter

delimiter

Delimiter used in rows array

null_as

How to interpret null values

fields

List of fields to insert

Return Values

Returns TRUE on success, or FALSE on failure.


Copy data from file into table

  • « PDO::pgsqlCopyFromArray
  • PDO::pgsqlCopyToArray »
  • PHP Manual
  • PostgreSQL (PDO)
  • Copy data from file into table

PDO::pgsqlCopyFromFile

(PHP 5 >= 5.3.3, PHP 7)

PDO::pgsqlCopyFromFile — Copy data from file into table

Description

public PDO::pgsqlCopyFromFile ( string $table_name , string $filename [, string $delimiter = '\t' [, string $null_as = "\\\\N" [, string $fields ]]] ) : bool

Copies data from file specified by filename into table table_name using delimiter as fields delimiter and fields list

Parameters

table_name

String containing table name

filename

Filename containing data to import

delimiter

Delimiter used in file specified by filename

null_as

How to interpret null values

fields

List of fields to insert

Return Values

Returns TRUE on success, or FALSE on failure.


Copy data from database table into PHP array

  • « PDO::pgsqlCopyFromFile
  • PDO::pgsqlCopyToFile »
  • PHP Manual
  • PostgreSQL (PDO)
  • Copy data from database table into PHP array

PDO::pgsqlCopyToArray

(PHP 5 >= 5.3.3, PHP 7)

PDO::pgsqlCopyToArray — Copy data from database table into PHP array

Description

public PDO::pgsqlCopyToArray ( string $table_name [, string $delimiter = '\t' [, string $null_as = "\\\\N" [, string $fields ]]] ) : array

Copies data from table into array using delimiter as fields delimiter and fields list

Parameters

table_name

String containing table name

delimiter

Delimiter used in rows

null_as

How to interpret null values

fields

List of fields to export

Return Values

Returns an array of rows, or FALSE on failure.


Copy data from table into file

  • « PDO::pgsqlCopyToArray
  • PDO::pgsqlGetNotify »
  • PHP Manual
  • PostgreSQL (PDO)
  • Copy data from table into file

PDO::pgsqlCopyToFile

(PHP 5 >= 5.3.3, PHP 7)

PDO::pgsqlCopyToFile — Copy data from table into file

Description

public PDO::pgsqlCopyToFile ( string $table_name , string $filename [, string $delimiter = '\t' [, string $null_as = "\\\\N" [, string $fields ]]] ) : bool

Copies data from table into file specified by filename using delimiter as fields delimiter and fields list

Parameters

table_name

String containing table name

filename

Filename to export data

delimiter

Delimiter used in file specified by filename

null_as

How to interpret null values

fields

List of fields to insert

Return Values

Returns TRUE on success, or FALSE on failure.


Get asynchronous notification

  • « PDO::pgsqlCopyToFile
  • PDO::pgsqlGetPid »
  • PHP Manual
  • PostgreSQL (PDO)
  • Get asynchronous notification

PDO::pgsqlGetNotify

(PHP 5 >= 5.6.0, PHP 7)

PDO::pgsqlGetNotify — Get asynchronous notification

Description

public PDO::pgsqlGetNotify ([ int $result_type = PDO::FETCH_USE_DEFAULT [, int $ms_timeout = 0 ]] ) : array

Returns a result set representing a pending asynchronous notification.

Parameters

result_type

The format the result set should be returned as, represented as a PDO::FETCH_* constant.

ms_timeout

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.


Get the server PID

  • « PDO::pgsqlGetNotify
  • PDO::pgsqlLOBCreate »
  • PHP Manual
  • PostgreSQL (PDO)
  • Get the server PID

PDO::pgsqlGetPid

(PHP 5 >= 5.6.0, PHP 7)

PDO::pgsqlGetPid — Get the server PID

Description

public PDO::pgsqlGetPid ( void ) : int

Returns the server's PID.

Return Values

The server's PID.


Creates a new large object

  • « PDO::pgsqlGetPid
  • PDO::pgsqlLOBOpen »
  • PHP Manual
  • PostgreSQL (PDO)
  • Creates a new large object

PDO::pgsqlLOBCreate

(PHP 5 >= 5.1.2, PHP 7, PECL pdo_pgsql >= 1.0.2)

PDO::pgsqlLOBCreate — Creates a new large object

Description

public PDO::pgsqlLOBCreate ( void ) : string

PDO::pgsqlLOBCreate() creates a large object and returns the OID of that object. You may then open a stream on the object using PDO::pgsqlLOBOpen() to read or write data to it. 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::pgsqlLOBUnlink().

Large objects can be up to 2GB in size, but are cumbersome to use; you need to ensure that PDO::pgsqlLOBUnlink() is called prior to deleting the last row that references its OID from your database. In addition, large objects have no access controls. As an alternative, try the bytea column type; recent versions of PostgreSQL allow bytea columns of up to 1GB in size and transparently manage the storage for optimal row size.

Note: This function must be called within a transaction.

Parameters

PDO::pgsqlLOBCreate() takes no parameters.

Return Values

Returns the OID of the newly created large object on success, or FALSE on failure.

Examples

Example #1 A PDO::pgsqlLOBCreate() 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:dbname=test host=localhost', $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->beginTransaction();
$oid = $db->pgsqlLOBCreate();
$stream = $db->pgsqlLOBOpen($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(array($some_id, $oid));
$db->commit();
?>

See Also

  • PDO::pgsqlLOBOpen() - Opens an existing large object stream
  • PDO::pgsqlLOBUnlink() - Deletes the large object
  • pg_lo_create() - Create a large object


Opens an existing large object stream

  • « PDO::pgsqlLOBCreate
  • PDO::pgsqlLOBUnlink »
  • PHP Manual
  • PostgreSQL (PDO)
  • Opens an existing large object stream

PDO::pgsqlLOBOpen

(PHP 5 >= 5.1.2, PHP 7, PECL pdo_pgsql >= 1.0.2)

PDO::pgsqlLOBOpen — Opens an existing large object stream

Description

public PDO::pgsqlLOBOpen ( string $oid [, string $mode = "rb" ] ) : resource

PDO::pgsqlLOBOpen() opens a stream to access the data referenced by oid. If mode is r, the stream is opened for reading, if mode is w, then the stream will be opened for writing. You can use all the usual filesystem functions, such as fread(), fwrite() and fgets() 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 A PDO::pgsqlLOBOpen() example

Following on from the PDO::pgsqlLOBCreate() example, this code snippet retrieves the large object from the database and outputs it to the browser.

<?php
$db = new PDO('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::pgsqlLOBCreate() - Creates a new large object
  • PDO::pgsqlLOBUnlink() - Deletes the large object
  • pg_lo_open() - Open a large object


Deletes the large object

  • « PDO::pgsqlLOBOpen
  • SQLite (PDO) »
  • PHP Manual
  • PostgreSQL (PDO)
  • Deletes the large object

PDO::pgsqlLOBUnlink

(PHP 5 >= 5.1.2, PHP 7, PECL pdo_pgsql >= 1.0.2)

PDO::pgsqlLOBUnlink — Deletes the large object

Description

public PDO::pgsqlLOBUnlink ( string $oid ) : bool

Deletes a large object from the database identified by OID.

Note: This function must be called within a transaction.

Parameters

oid

A large object identifier

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A PDO::pgsqlLOBUnlink() example

This example unlinks a large object from the database prior to deleting the row that references it from the blobs table we've been using in our PDO::pgsqlLOBCreate() and PDO::pgsqlLOBOpen() examples.

<?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::pgsqlLOBOpen() - Opens an existing large object stream
  • PDO::pgsqlLOBCreate() - Creates a new large object


SQLite Functions (PDO_SQLITE)

Introduction

PDO_SQLITE is a driver that implements the PHP Data Objects (PDO) interface to enable access to SQLite 3 databases.

In PHP 5.1, the SQLite extension also provides a driver for SQLite 2 databases; while it is not technically a part of the PDO_SQLITE driver, it behaves similarly, so it is documented alongside it. The SQLite 2 driver for PDO is provided primarily to make it easier to import legacy SQLite 2 database files into an application that uses the faster, more efficient SQLite 3 driver. As a result, the SQLite 2 driver is not as feature-rich as the SQLite 3 driver.

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.

Table of Contents

  • PDO_SQLITE DSN — Connecting to SQLite databases
  • PDO::sqliteCreateAggregate — Registers an aggregating User Defined Function for use in SQL statements
  • PDO::sqliteCreateCollation — Registers a User Defined Function for use as a collating function in SQL statements
  • PDO::sqliteCreateFunction — Registers a User Defined Function for use in SQL statements


Connecting to SQLite databases

  • « SQLite (PDO)
  • PDO::sqliteCreateAggregate »
  • PHP Manual
  • SQLite (PDO)
  • Connecting to SQLite databases

PDO_SQLITE DSN

(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, append the absolute path to the DSN prefix.

  • To create a database in memory, append :memory: to the DSN prefix.

DSN prefix (SQLite 2)

The SQLite extension in PHP 5.1 provides a PDO driver that supports accessing and creating SQLite 2 databases. This enables you to access databases you may have created with the SQLite extension in previous versions of PHP.

Note:

The sqlite2 driver is only available in PHP 5.1.x if you have enabled both PDO and ext/sqlite. It is not currently available via PECL.

The DSN prefix for connecting to SQLite 2 databases is sqlite2:.

  • To access a database on disk, append the absolute path to the DSN prefix.

  • To create a database in memory, append :memory: to the DSN prefix.

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:
sqlite2:/opt/databases/mydb.sq2
sqlite2::memory:


Registers an aggregating User Defined Function for use in SQL statements

  • « PDO_SQLITE DSN
  • PDO::sqliteCreateCollation »
  • PHP Manual
  • SQLite (PDO)
  • Registers an aggregating User Defined Function for use in SQL statements

PDO::sqliteCreateAggregate

(PHP 5 >= 5.1.0, PHP 7, PECL pdo_sqlite >= 1.0.0)

PDO::sqliteCreateAggregate — Registers an aggregating User Defined Function for use in SQL statements

Description

public PDO::sqliteCreateAggregate ( string $function_name , callable $step_func , callable $finalize_func [, int $num_args ] ) : bool
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.

This method is similar to PDO::sqliteCreateFunction 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::sqliteCreateFunction is that two functions are required to manage the aggregate.

Parameters

function_name

The name of the function used in SQL statements.

step_func

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 $value1 [, mixed $... ] ) : 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.

value1

The first argument passed to the aggregate.

...

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_func

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.

num_args

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 max_length aggregation function example

<?php
$data = array(
   'one',
   'two',
   'three',
   'four',
   'five',
   'six',
   'seven',
   'eight',
   'nine',
   'ten',
   );
$db = new PDO('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, $rownumber, $string)
{
    if (strlen($string) > $context) {
        $context = strlen($string);
    }
    return $context;
}

function max_len_finalize($context, $rowcount)
{
    return $context === null ? 0 : $context;
}

$db->sqliteCreateAggregate('max_len', 'max_len_step', 'max_len_finalize');

var_dump($db->query('SELECT max_len(a) from strings')->fetchAll());

?>

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 PDO::sqliteCreateFunction and PDO::sqliteCreateAggregate to override SQLite native SQL functions.

Note:

This method is not available with the SQLite2 driver. Use the old style sqlite API for that instead.

See Also

  • PDO::sqliteCreateFunction
  • sqlite_create_function() - Registers a "regular" User Defined Function for use in SQL statements
  • sqlite_create_aggregate() - Register an aggregating UDF for use in SQL statements


Registers a User Defined Function for use as a collating function in SQL statements

  • « PDO::sqliteCreateAggregate
  • PDO::sqliteCreateFunction »
  • PHP Manual
  • SQLite (PDO)
  • Registers a User Defined Function for use as a collating function in SQL statements

PDO::sqliteCreateCollation

(PHP 5 >= 5.3.11, PHP 7)

PDO::sqliteCreateCollation — Registers a User Defined Function for use as a collating function in SQL statements

Description

public PDO::sqliteCreateCollation ( string $name , callable $callback ) : bool
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.

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 strings 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 ( string $string1 , string $string2 ) : int

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 PDO::sqliteCreateCollation() example

<?php
$db = new PDO('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

Notes

Note:

This method is not available with the SQLite2 driver. Use the old style sqlite API for that instead.


Registers a User Defined Function for use in SQL statements

  • « PDO::sqliteCreateCollation
  • 4D (PDO) »
  • PHP Manual
  • SQLite (PDO)
  • Registers a User Defined Function for use in SQL statements

PDO::sqliteCreateFunction

(PHP 5 >= 5.1.0, PHP 7, PECL pdo_sqlite >= 1.0.0)

PDO::sqliteCreateFunction — Registers a User Defined Function for use in SQL statements

Description

public PDO::sqliteCreateFunction ( string $function_name , callable $callback [, int $num_args = -1 [, int $flags = 0 ]] ) : bool
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.

This method allows you to register a PHP function with SQLite as an UDF (User Defined Function), so that it can be called from within your SQL statements.

The UDF can be used in any SQL statement that can call functions, such as SELECT and UPDATE statements and also in triggers.

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 $value1 [, mixed $... ] ) : mixed
value1

The first argument passed to the SQL function.

...

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 bitwise conjunction 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.

Changelog

Version | Description
7.1.4 | The flags parameter has been added.

Examples

Example #1 PDO::sqliteCreateFunction() example

<?php
function md5_and_reverse($string)
{
    return strrev(md5($string));
}

$db = new PDO('sqlite:sqlitedb');
$db->sqliteCreateFunction('md5rev', 'md5_and_reverse', 1);
$rows = $db->query('SELECT md5rev(filename) FROM files')->fetchAll();
?>

In this example, we have a function that calculates the md5 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 you do not need to process the result using a foreach loop after you have queried for the data.

Tip

You can use PDO::sqliteCreateFunction and PDO::sqliteCreateAggregate to override SQLite native SQL functions.

Note:

This method is not available with the SQLite2 driver. Use the old style sqlite API for that instead.

See Also

  • PDO::sqliteCreateAggregate
  • sqlite_create_function() - Registers a "regular" User Defined Function for use in SQL statements
  • sqlite_create_aggregate() - Register an aggregating UDF for use in SQL statements


4D Functions (PDO_4D)

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.

PDO_4D is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to 4D databases.

4D is an integrated platform that speeds and simplifies the development and deployment of business applications, used in over 70 countries, by a community of thousands of developers and vertical solution providers, with millions of end-users worldwide.

By offering a suite of integrated tools such as an ANSI SQL relational and transactional database, a graphical development environment, a fourth-generation language with over 1000 high-level commands, a built-in HTTP server, application server, etc., 4D facilitates the creation and maintenance of applications from one to hundreds of simultaneous users, whether on Windows, Mac or from any Web client.

4D is also an open platform, offering a complete API for plug-in creation, including various connectors that allow it to act as a back-end or front-end for many environments (Oracle via OCI, SOAP client or server, Flex data source, all ODBC databases, XML over HTTP, etc.)

In addition to the ability to interact with 4D applications across Web Services, 4D databases can now be directly accessed using the PDO_4D driver.

More details about the 4D development environment on » http://www.4d.com/.

PDO_4D is known to work with 4D versions 12 beta and up, for macOS and Windows. Older plat-forms may work, but are unsupported.

Table of Contents

  • PDO_4D DSN — Connecting to 4D SQL server
  • Constants for PDO_4D — Constants for PDO_4D
  • SQL types with PDO_4D and PHP — SQL types with PDO_4D and PHP
  • SQL acceptable by 4D — PDO and SQL 4D
  • Examples with PDO_4D — Examples PDO_4D


Connecting to 4D SQL server

  • « 4D (PDO)
  • Constants for PDO_4D »
  • PHP Manual
  • 4D (PDO)
  • Connecting to 4D SQL server

PDO_4D DSN

(No version information available, might only be in Git)

PDO_4D DSN — Connecting to 4D SQL server

Description

The PDO_4D DSN consists of:

DSN prefix

The DSN prefix is 4D:.

host

The host on which the 4D SQL server is.

port

The port number for the server. This is optional.

user

The login name when connecting to the database.

password

The password for the above login.

dbname

The name of the database. This parameter is optional, and it is not used.

charset

The 4D character set.

Examples

Example #1 DSN examples for PDO_4D

The following examples has two DSN for PDO_4D, that connects to a 4D database :

4D:host=localhost;charset=UTF-8
Other possible values :
4D:host=localhost
4D:


Constants for PDO_4D

(No version information available, might only be in Git)

Constants for PDO_4D — Constants for PDO_4D

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::FOURD_ATTR_CHARSET (integer)

Change the charset in which 4D returns data. (Default is UTF-8).

PDO::FOURD_ATTR_PREFERRED_IMAGE_TYPES (integer)

The requested format of the image, when selecting a row with a column type PICTURE. It may be any type that 4D supports.


SQL types with PDO_4D and PHP

(No version information available, might only be in Git)

SQL types with PDO_4D and PHP — SQL types with PDO_4D and PHP

Supported SQL types
Type SQL 4D | Equivalent 4D | Note
ALPHA_NUMERIC | TEXT |
VARCHAR | TEXT |
TEXT | TEXT |
TIMESTAMP | DATE |
INTERVAL | HOUR |
DURATION | HOUR |
BOOLEAN | BOOLEAN |
BIT | BOOLEAN |
BYTE | INT32 |
INT16 | SMALLINT |
SMALLINT | SMALLINT |
INT32 | INT32 |
INT | INT32 |
INT64 | INT64 |
NUMERIC | INT64 |
REAL | REAL | Unsupported (use VARCHAR conversion)
FLOAT | FLOAT | Unsupported (use VARCHAR conversion)
DOUBLE PRECISION | FLOAT |
BLOB | BLOB | Must use a prepared statement, and PDO::PARAM_LOB
BIT VARYING | BLOB | Must use a prepared statement, and PDO::PARAM_LOB
CLOB | TEXT |
PICTURE | PICTURE | Must use a prepared statement, and PDO::PARAM_LOB


PDO and SQL 4D

  • « SQL types with PDO_4D and PHP
  • Examples with PDO_4D »
  • PHP Manual
  • 4D (PDO)
  • PDO and SQL 4D

SQL acceptable by 4D

(No version information available, might only be in Git)

SQL acceptable by 4D — PDO and SQL 4D

Description

4D implements strictly the ANSI 89 standard, and have it enforced. It is highly recommended to read the 4D SQL documentation to learn about the available commands. The URL of the manual is: » http://doc.4d.com/. Below is a list of 4D SQL characteristics: it is not exhaustive, but may serve as an introduction.

Characteristics of 4D SQL
Characteristics | Alternative | Note
INTEGER | Modify the SQL to use INT. | INT is the supported integer type in 4Dv12.0.
CHAR | Use VARCHAR instead. | Unsupported in 4Dv12.0
UNION | Unsupported. Make separate queries. | Unsupported in 4Dv12.0
SELECT 1 + 1; | SELECT 1 + 1 FROM _USER_SCHEMAS; | FROM is required
FLOAT | Cast the FLOAT value into a FLOAT or STRING, with an SQL 4D function (CAST, ROUND, TRUNC or TRUNCATE) | Unsupported in current versions of the PDO_4D driver
Strong typing | Take care your SQL query, or your PHP code provides data with the expected type | One must provide the right type that 4D expect. One can't insert '1' (as a string) in an INTEGER column.
PDO::execute($row)() : only works if all the table's column are of type TEXT or VARCHAR | Use the prepared statements, and use the right types. | The PDO extension cast all values through execute() as string, and expect the SQL database to parse the values.
SELECT NULL FROM TABLE | Do not use NULL constants. Extract them from the table | It is not allowed to use the NULL constant in the select list
SELECT * FROM TABLE WHERE 1 | Use WHERE 1 = 1 | A constant can't be used in a WHERE clause
SHOW TABLES | Use system tables | The list of tables, schemas, index, etc. are in these system tables : _USER_TABLES, _USER_COLUMNS, _USER_INDEXES, _USER_CONSTRAINTS, _USER_IND_COLUMNS, _USER_CONS_COLUMNS, and _USER_SCHEMAS.
SQL structure delimiter | Use the following function to protect SQL elements: function sqlEscapeElement(elem) { return '[' . str_replace(']',']]', $elem) . ']'; } | To escape SQL elements names (tables, fields, users, groups, schema, primary key, etc.), the whole identifier must be between square brackets, and the closing brackets ']' must be doubled.


Examples PDO_4D

  • « SQL acceptable by 4D
  • Vendor Specific Database Extensions »
  • PHP Manual
  • 4D (PDO)
  • Examples PDO_4D

Examples with PDO_4D

(No version information available, might only be in Git)

Examples with PDO_4D — Examples PDO_4D

This basic example show how to connect, execute a query, read data and disconnect from a 4D SQL server.

Example #1 Basic example with PDO_4D

<?php
$dsn = '4D:host=localhost;charset=UTF-8';
$user = 'test';
$pass = 'test';

// Connection to the 4D SQL server
$db = new PDO($dsn, $user, $pass);

try {
    $db->exec('CREATE TABLE test(id varCHAR(1) NOT NULL, val VARCHAR(10))');
} catch (PDOException $e) {
    die("Erreur 4D : " . $e->getMessage());
}

$db->exec("INSERT INTO test VALUES('A', 'B')");
$db->exec("INSERT INTO test VALUES('C', 'D')");
$db->exec("INSERT INTO test VALUES('E', 'F')");

$stmt = $db->prepare('SELECT id, val from test');

$stmt->execute();
print_r($stmt->fetchAll());

unset($stmt);
unset($db);
?>

The above example will output:

    Array
(
    [0] => Array
        (
            [ID] => A
            [0] => A
            [VAL] => B
            [1] => B
        )

    [1] => Array
        (
            [ID] => C
            [0] => C
            [VAL] => D
            [1] => D
        )

    [2] => Array
        (
            [ID] => E
            [0] => E
            [VAL] => F
            [1] => F
        )

)

This example shows how to execute a query in 4D language, and how to read the result through PDO_4D.

Example #2 Accessing 4D language from pdo_4d

Set up a 4D method, called method. Make sure in the method properties that the option Available via SQL is checked. The 4D code is the following.

C_TEXT($0)
$0:=Application Version(*)

The PHP code to use the above 4D method is :

<?php
$dsn = '4D:host=localhost;charset=UTF-8';
$user = 'test';
$pass = 'test';

// Connection to the 4D server
$db = new PDO($dsn, $user, $pass);

$stmt = $db->prepare('SELECT {FN method() AS VARCHAR } FROM _USER_SCHEMAS LIMIT 1');

$stmt->execute();
print_r($stmt->fetchAll());

unset($stmt);
unset($db);
?>

The above example will output:

(
    [0] => Array
        (
            [<expression>] => F0011140
            [0] => F0011140
        )

)

Example #3 Escaping 4D table names

This examples illustrates how to escape characters in a 4D SQL query.

<?php
$dsn = '4D:host=localhost;charset=UTF-8';
$user = 'test';
$pass = 'test';

// Connection to 4D server 4D
$db = new PDO($dsn, $user, $pass);

$objects = array('[',']','[]','][','[[',']]','[[[',']]]','TBL ]]32[23');

foreach($objects as $id => $object) {
    $object = str_replace(']',']]', $object);
    print "$object\n";

    $db->exec('CREATE TABLE IF NOT EXISTS ['.$object.'](['.$object.'] FLOAT)');

    $req = "INSERT INTO [$object] ([$object]) VALUES ($id);";
    $db->query($req);

    $q = $db->prepare("SELECT [$object] FROM [$object]");
    $q->execute();
    $x[] = $q->fetch(PDO::FETCH_NUM);

    $db->exec('DROP TABLE ['.$object.'];');
}

?>

The above example will output:

[
]]
[]]
]][
[[
]]]]
[[[
]]]]]]
TBL ]]]]32[23


Vendor Specific Database Extensions

  • CUBRID
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • CUBRID Functions
    • CUBRID MySQL Compatibility Functions
    • CUBRID Obsolete Aliases and Functions
  • DB++
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • DB++ Functions
  • dBase
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • dBase Functions
  • filePro
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • filePro Functions
  • Firebird/InterBase
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Firebird/InterBase Functions
  • FrontBase
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • FrontBase Functions
  • IBM DB2 — IBM DB2, Cloudscape and Apache Derby
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • IBM DB2 Functions
  • Informix
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Informix Functions
  • Ingres — Ingres DBMS, EDBC, and Enterprise Access Gateways
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Ingres Functions
  • MaxDB
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • MaxDB Functions
  • Mongo — MongoDB driver (legacy)
    • Installing/Configuring
    • Predefined Constants
    • Manual
    • Core Classes
    • Types
    • GridFS Classes
    • Batch Classes
    • Miscellaneous
    • Mongo Functions
    • Exceptions
    • Changelog
  • MongoDB — MongoDB driver
    • Installing/Configuring
    • Tutorials
    • Driver Architecture and Internals — Explains the driver architecture, and special features
    • Security
    • MongoDB\Driver — MongoDB driver classes
    • MongoDB\BSON — BSON type classes and serialization functions
    • MongoDB\Driver\Monitoring — Monitoring classes and subscriber functions
    • MongoDB\Driver\Exception — Exception classes
  • mSQL
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • mSQL Functions
  • Mssql — Microsoft SQL Server
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Mssql Functions
  • 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
    • mysqlnd_ms — Mysqlnd replication and load balancing plugin
    • mysqlnd_qc — Mysqlnd query result cache plugin
    • mysqlnd_uh — Mysqlnd user handler plugin
    • mysqlnd_mux — Mysqlnd connection multiplexing plugin
    • mysqlnd_memcache — Mysqlnd Memcache plugin
  • OCI8 — Oracle OCI8
    • Introduction
    • 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
    • OCI-Collection — The OCI-Collection class
    • OCI-Lob — The OCI-Lob class
    • OCI8 Obsolete Aliases and Functions
  • Paradox — Paradox File Access
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Paradox Functions
  • PostgreSQL
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • PostgreSQL Functions
  • SQLite
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • SQLite Functions
  • SQLite3
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • SQLite3 — The SQLite3 class
    • SQLite3Stmt — The SQLite3Stmt class
    • SQLite3Result — The SQLite3Result class
  • SQLSRV — Microsoft SQL Server Driver for PHP
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • SQLSRV Functions
  • Sybase
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Sybase Functions
  • tokyo_tyrant
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • TokyoTyrant — The TokyoTyrant class
    • TokyoTyrantTable — The TokyoTyrantTable class
    • TokyoTyrantQuery — The TokyoTyrantQuery class
    • TokyoTyrantIterator — The TokyoTyrantIterator class
    • TokyoTyrantException — The TokyoTyrantException class


CUBRID

  • Introduction
  • 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_with_url — Establish the environment for connecting to CUBRID server
    • cubrid_connect — Open a connection to a 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_facility — Get the facility code of error
    • 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_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_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_get — Get a column using OID
    • 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_seek64 — Move the cursor of a lob object
    • cubrid_lob2_seek — Move the cursor of a lob object
    • cubrid_lob2_size64 — Get a lob object's size
    • cubrid_lob2_size — Get a lob object's size
    • cubrid_lob2_tell64 — Tell the cursor position of the LOB object
    • cubrid_lob2_tell — 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_with_url — Open a persistent connection to CUBRID server
    • cubrid_pconnect — Open a persistent connection to a 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


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.


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.


  • « Installation
  • Resource Types »
  • PHP Manual
  • Installing/Configuring
  • Runtime Configuration

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

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_with_url — Establish the environment for connecting to CUBRID server
  • cubrid_connect — Open a connection to a 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_facility — Get the facility code of error
  • 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_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_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_get — Get a column using OID
  • 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_seek64 — Move the cursor of a lob object
  • cubrid_lob2_seek — Move the cursor of a lob object
  • cubrid_lob2_size64 — Get a lob object's size
  • cubrid_lob2_size — Get a lob object's size
  • cubrid_lob2_tell64 — Tell the cursor position of the LOB object
  • cubrid_lob2_tell — 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_with_url — Open a persistent connection to CUBRID server
  • cubrid_pconnect — Open a persistent connection to a 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


Bind variables to a prepared statement as parameters

  • « CUBRID Functions
  • cubrid_close_prepare »
  • PHP Manual
  • CUBRID Functions
  • Bind variables to a prepared statement as parameters

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

TRUE, when process is successful.

FALSE, when process is unsuccessful.

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


Close the request handle

  • « cubrid_bind
  • cubrid_close_request »
  • PHP Manual
  • CUBRID Functions
  • Close the request handle

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


Close the request handle

  • « cubrid_close_prepare
  • cubrid_col_get »
  • PHP Manual
  • CUBRID Functions
  • 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


Get contents of collection type column using OID

  • « cubrid_close_request
  • cubrid_col_size »
  • PHP Manual
  • CUBRID Functions
  • Get contents of collection type column using OID

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)


Get the number of elements in collection type column using OID

  • « cubrid_col_get
  • cubrid_column_names »
  • PHP Manual
  • CUBRID Functions
  • Get the number of elements in collection type column using OID

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.

FALSE, when process is unsuccessful.

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)


Get the column names in result

  • « cubrid_col_size
  • cubrid_column_types »
  • PHP Manual
  • CUBRID Functions
  • Get the column names in result

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.

FALSE, when process is unsuccessful.

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


Get column types in result

  • « cubrid_column_names
  • cubrid_commit »
  • PHP Manual
  • CUBRID Functions
  • 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.

FALSE, when process is unsuccessful.

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


Commit a transaction

  • « cubrid_column_types
  • cubrid_connect_with_url »
  • PHP Manual
  • CUBRID Functions
  • Commit a transaction

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

TRUE, when process is successful.

FALSE, when process is unsuccessful.

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


Establish the environment for connecting to CUBRID server

  • « cubrid_commit
  • cubrid_connect »
  • PHP Manual
  • CUBRID Functions
  • Establish the environment for connecting to CUBRID server

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.

FALSE, when process is unsuccessful.

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


Open a connection to a CUBRID Server

  • « cubrid_connect_with_url
  • cubrid_current_oid »
  • PHP Manual
  • CUBRID Functions
  • Open a connection to a CUBRID Server

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.

FALSE, when process is unsuccessful.

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


Get OID of the current cursor location

  • « cubrid_connect
  • cubrid_disconnect »
  • PHP Manual
  • CUBRID Functions
  • Get OID of the current cursor location

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

FALSE, when process is unsuccessful.

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


Close a database connection

  • « cubrid_current_oid
  • cubrid_drop »
  • PHP Manual
  • CUBRID Functions
  • Close a database connection

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

TRUE, when process is successful.

FALSE, when process is unsuccessful.

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


Delete an instance using OID

  • « cubrid_disconnect
  • cubrid_error_code_facility »
  • PHP Manual
  • CUBRID Functions
  • Delete an instance using OID

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

TRUE, when process is successful.

FALSE, when process is unsuccessful.

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


Get the facility code of error

  • « cubrid_drop
  • cubrid_error_code »
  • PHP Manual
  • CUBRID Functions
  • Get the facility code of error

cubrid_error_code_facility

(PECL CUBRID >= 8.3.0)

cubrid_error_code_facility — Get the facility code of error

Description

cubrid_error_code_facility ( void ) : 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


Get error code for the most recent function call

  • « cubrid_error_code_facility
  • cubrid_error_msg »
  • PHP Manual
  • CUBRID Functions
  • Get error code for the most recent function call

cubrid_error_code

(PECL CUBRID >= 8.3.0)

cubrid_error_code — Get error code for the most recent function call

Description

cubrid_error_code ( void ) : 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


Get last error message for the most recent function call

  • « cubrid_error_code
  • cubrid_execute »
  • PHP Manual
  • CUBRID Functions
  • 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 ( void ) : 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


Execute a prepared SQL statement

  • « cubrid_error_msg
  • cubrid_fetch »
  • PHP Manual
  • CUBRID Functions
  • Execute a prepared SQL statement

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.

FALSE, when process is unsuccessful.

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


Fetch the next row from a result set

  • « cubrid_execute
  • cubrid_free_result »
  • PHP Manual
  • CUBRID Functions
  • Fetch the next row from a result set

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


Free the memory occupied by the result data

  • « cubrid_fetch
  • cubrid_get_autocommit »
  • PHP Manual
  • CUBRID Functions
  • Free the memory occupied by the result data

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

TRUE on success.

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


Get auto-commit mode of the connection

  • « cubrid_free_result
  • cubrid_get_charset »
  • PHP Manual
  • CUBRID Functions
  • Get auto-commit mode of the connection

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


Return the current CUBRID connection charset

  • « cubrid_get_autocommit
  • cubrid_get_class_name »
  • PHP Manual
  • CUBRID Functions
  • Return the current CUBRID connection charset

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.

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


Get the class name using OID

  • « cubrid_get_charset
  • cubrid_get_client_info »
  • PHP Manual
  • CUBRID Functions
  • Get the class name using OID

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.

FALSE, when process is unsuccessful.

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


Return the client library version

  • « cubrid_get_class_name
  • cubrid_get_db_parameter »
  • PHP Manual
  • CUBRID Functions
  • Return the client library version

cubrid_get_client_info

(PECL CUBRID >= 8.3.0)

cubrid_get_client_info — Return the client library version

Description

cubrid_get_client_info ( void ) : 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.

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


Returns the CUBRID database parameters

  • « cubrid_get_client_info
  • cubrid_get_query_timeout »
  • PHP Manual
  • CUBRID Functions
  • Returns the CUBRID database parameters

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 it returns 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.

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


Get the query timeout value of the request

  • « cubrid_get_db_parameter
  • cubrid_get_server_info »
  • PHP Manual
  • CUBRID Functions
  • Get the query timeout value of the request

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

Success: the query timeout value of the current request. Units of msec.

Failure: FALSE

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


Return the CUBRID server version

  • « cubrid_get_query_timeout
  • cubrid_get »
  • PHP Manual
  • CUBRID Functions
  • Return the CUBRID server version

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.

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


Get a column using OID

  • « cubrid_get_server_info
  • cubrid_insert_id »
  • PHP Manual
  • CUBRID Functions
  • Get a column using OID

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


Return the ID generated for the last updated AUTO_INCREMENT column

  • « cubrid_get
  • cubrid_is_instance »
  • PHP Manual
  • CUBRID Functions
  • Return the ID generated for the last updated AUTO_INCREMENT column

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"


Check whether the instance pointed by OID exists

  • « cubrid_insert_id
  • cubrid_lob_close »
  • PHP Manual
  • CUBRID Functions
  • Check whether the instance pointed by OID exists

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


Close BLOB/CLOB data

  • « cubrid_is_instance
  • cubrid_lob_export »
  • PHP Manual
  • CUBRID Functions
  • Close BLOB/CLOB data

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 return from cubrid_lob_get.

Return Values

TRUE, when process is successful.

FALSE, when process is unsuccessful.

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


Export BLOB/CLOB data to file

  • « cubrid_lob_close
  • cubrid_lob_get »
  • PHP Manual
  • CUBRID Functions
  • Export BLOB/CLOB data to file

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

TRUE, when process is successful.

FALSE, when process is unsuccessful.

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


Get BLOB/CLOB data

  • « cubrid_lob_export
  • cubrid_lob_send »
  • PHP Manual
  • CUBRID Functions
  • Get BLOB/CLOB data

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.

FALSE, when process is unsuccessful.

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


Read BLOB/CLOB data and send straight to browser

  • « cubrid_lob_get
  • cubrid_lob_size »
  • PHP Manual
  • CUBRID Functions
  • 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

TRUE, when process is successful.

FALSE, when process is unsuccessful.

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


Get BLOB/CLOB data size

  • « cubrid_lob_send
  • cubrid_lob2_bind »
  • PHP Manual
  • CUBRID Functions
  • Get BLOB/CLOB data size

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.

FALSE, when process is unsuccessful.

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


Bind a lob object or a string as a lob object to a prepared statement as parameters

  • « cubrid_lob_size
  • cubrid_lob2_close »
  • PHP Manual
  • CUBRID Functions
  • Bind a lob object or a string as a lob object to a prepared statement as parameters

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

TRUE, when process is successful.

FALSE, when process is unsuccessful.

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


Close LOB object

  • « cubrid_lob2_bind
  • cubrid_lob2_export »
  • PHP Manual
  • CUBRID Functions
  • 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

TRUE, on success.

FALSE, on failure.

See Also

  • cubrid_lob2_new() - Create a lob object


Export the lob object to a file

  • « cubrid_lob2_close
  • cubrid_lob2_import »
  • PHP Manual
  • CUBRID Functions
  • Export the lob object to a file

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

TRUE if the process is successful and FALSE for 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


Import BLOB/CLOB data from a file

  • « cubrid_lob2_export
  • cubrid_lob2_new »
  • PHP Manual
  • CUBRID Functions
  • Import BLOB/CLOB data from a file

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

TRUE if the process is successful and FALSE for 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


Create a lob object

  • « cubrid_lob2_import
  • cubrid_lob2_read »
  • PHP Manual
  • CUBRID Functions
  • Create a lob object

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.

FALSE on failure.

See Also

  • cubrid_lob2_close() - Close LOB object


Read from BLOB/CLOB data

  • « cubrid_lob2_new
  • cubrid_lob2_seek64 »
  • PHP Manual
  • CUBRID Functions
  • Read from BLOB/CLOB data

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.

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


Move the cursor of a lob object

  • « cubrid_lob2_read
  • cubrid_lob2_seek »
  • PHP Manual
  • CUBRID Functions
  • Move the cursor of a lob object

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

TRUE if the process is successful and FALSE for 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


Move the cursor of a lob object

  • « cubrid_lob2_seek64
  • cubrid_lob2_size64 »
  • PHP Manual
  • CUBRID Functions
  • Move the cursor of a lob object

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

TRUE if the process is successful and FALSE for 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


Get a lob object's size

  • « cubrid_lob2_seek
  • cubrid_lob2_size »
  • PHP Manual
  • CUBRID Functions
  • 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.

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


Get a lob object's size

  • « cubrid_lob2_size64
  • cubrid_lob2_tell64 »
  • PHP Manual
  • CUBRID Functions
  • 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.

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


Tell the cursor position of the LOB object

  • « cubrid_lob2_size
  • cubrid_lob2_tell »
  • PHP Manual
  • CUBRID Functions
  • Tell the cursor position of the LOB object

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.

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


Tell the cursor position of the LOB object

  • « cubrid_lob2_tell64
  • cubrid_lob2_write »
  • PHP Manual
  • CUBRID Functions
  • Tell the cursor position of the LOB object

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.

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


Write to a lob object

  • « cubrid_lob2_tell
  • cubrid_lock_read »
  • PHP Manual
  • CUBRID Functions
  • Write to a lob object

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

TRUE if the process is successful and FALSE for 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


Set a read lock on the given OID

  • « cubrid_lob2_write
  • cubrid_lock_write »
  • PHP Manual
  • CUBRID Functions
  • Set a read lock on the given OID

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

TRUE, when process is successful.

FALSE, when process is unsuccessful.

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


Set a write lock on the given OID

  • « cubrid_lock_read
  • cubrid_move_cursor »
  • PHP Manual
  • CUBRID Functions
  • 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

TRUE, when process is successful.

FALSE, when process is unsuccessful.

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


Move the cursor in the result

  • « cubrid_lock_write
  • cubrid_next_result »
  • PHP Manual
  • CUBRID Functions
  • Move the cursor in the result

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

TRUE, when process is successful.

FALSE, when process is unsucceful.

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


Get result of next query when executing multiple SQL statements

  • « cubrid_move_cursor
  • cubrid_num_cols »
  • PHP Manual
  • CUBRID Functions
  • Get result of next query when executing multiple SQL statements

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

TRUE, when process is successful.

FALSE, when process is unsuccessful.

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


Return the number of columns in the result set

  • « cubrid_next_result
  • cubrid_num_rows »
  • PHP Manual
  • CUBRID Functions
  • Return the number of columns in the result set

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


Get the number of rows in the result set

  • « cubrid_num_cols
  • cubrid_pconnect_with_url »
  • PHP Manual
  • CUBRID Functions
  • 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. You can use it only when the query executed is a select statement. When you want to know such value for INSERT, UPDATE, or DELETE query, you have to 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


Open a persistent connection to CUBRID server

  • « cubrid_num_rows
  • cubrid_pconnect »
  • PHP Manual
  • CUBRID Functions
  • Open a persistent connection to CUBRID server

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.

FALSE, when process is unsuccessful.

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


Open a persistent connection to a CUBRID server

  • « cubrid_pconnect_with_url
  • cubrid_prepare »
  • PHP Manual
  • CUBRID Functions
  • Open a persistent connection to a CUBRID server

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.

FALSE, when process is unsuccessful.

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


Prepare a SQL statement for execution

  • « cubrid_pconnect
  • cubrid_put »
  • PHP Manual
  • CUBRID Functions
  • Prepare a SQL statement for execution

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;

FALSE, if process is unsuccessful.

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


Update a column using OID

  • « cubrid_prepare
  • cubrid_rollback »
  • PHP Manual
  • CUBRID Functions
  • Update a column using OID

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

TRUE, when process is successful.

FALSE, when process is unsuccessful.

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


Roll back a transaction

  • « cubrid_put
  • cubrid_schema »
  • PHP Manual
  • CUBRID Functions
  • Roll back a transaction

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

TRUE, when process is successful.

FALSE, when process is unsuccessful.

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


Get the requested schema information

  • « cubrid_rollback
  • cubrid_seq_drop »
  • PHP Manual
  • CUBRID Functions
  • Get the requested schema information

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. You have to designate class_name, if you want to get information on certain class, attr_name, if you want to get information on certain attribute (can be used only with CUBRID_ SCH_ATTR_PRIVILEGE).

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;

FALSE, when process is unsuccessful

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


Delete an element from sequence type column using OID

  • « cubrid_schema
  • cubrid_seq_insert »
  • PHP Manual
  • CUBRID Functions
  • Delete an element from sequence type column using OID

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

TRUE, when process is successful.

FALSE, when process is unsuccessful.

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


Insert an element to a sequence type column using OID

  • « cubrid_seq_drop
  • cubrid_seq_put »
  • PHP Manual
  • CUBRID Functions
  • Insert an element to a 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

TRUE, when process is successful.

FALSE, when process is unsuccessful.

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


Update the element value of sequence type column using OID

  • « cubrid_seq_insert
  • cubrid_set_add »
  • PHP Manual
  • CUBRID Functions
  • 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

TRUE, when process is successful.

FALSE, when process is unsuccessful.

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


Insert a single element to set type column using OID

  • « cubrid_seq_put
  • cubrid_set_autocommit »
  • PHP Manual
  • CUBRID Functions
  • Insert a single element to set 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

TRUE, when process is successful.

FALSE, when process is unsuccessful.

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


Set autocommit mode of the connection

  • « cubrid_set_add
  • cubrid_set_db_parameter »
  • PHP Manual
  • CUBRID Functions
  • Set autocommit mode of the connection

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

TRUE, when process is successful.

FALSE, when process is unsuccessful.

See Also

  • cubrid_get_autocommit() - Get auto-commit mode of the connection
  • cubrid_commit() - Commit a transaction


Sets the CUBRID database parameters

  • « cubrid_set_autocommit
  • cubrid_set_drop »
  • PHP Manual
  • CUBRID Functions
  • Sets the CUBRID database parameters

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

TRUE on success.

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


Delete an element from set type column using OID

  • « cubrid_set_db_parameter
  • cubrid_set_query_timeout »
  • PHP Manual
  • CUBRID Functions
  • Delete an element from set type column using OID

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

TRUE, when process is successful.

FALSE, when process is unsuccessful.

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


Set the timeout time of query execution

  • « cubrid_set_drop
  • cubrid_version »
  • PHP Manual
  • CUBRID Functions
  • Set the timeout time of query execution

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, unit of msec.

Return Values

TRUE, when process is successful.

FALSE, when process is unsuccessful.

See Also

  • cubrid_get_query_timeout() - Get the query timeout value of the request


Get the CUBRID PHP module's version

  • « cubrid_set_query_timeout
  • CUBRID MySQL Compatibility Functions »
  • PHP Manual
  • CUBRID Functions
  • Get the CUBRID PHP module's version

cubrid_version

(PECL CUBRID >= 8.3.0)

cubrid_version — Get the CUBRID PHP module's version

Description

cubrid_version ( void ) : 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


CUBRID MySQL Compatibility Functions

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


Return the number of rows affected by the last SQL statement

  • « CUBRID MySQL Compatibility Functions
  • cubrid_client_encoding »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Return the number of rows affected by the last SQL statement

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:

Rows deleted: 5

See Also

  • cubrid_execute() - Execute a prepared SQL statement


Return the current CUBRID connection charset

  • « cubrid_affected_rows
  • cubrid_close »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Return the current CUBRID connection charset

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


Close CUBRID connection

  • « cubrid_client_encoding
  • cubrid_data_seek »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Close CUBRID connection

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


Move the internal row pointer of the CUBRID result

  • « cubrid_close
  • cubrid_db_name »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Move the internal row pointer of the CUBRID result

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 current 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"
}


Get db name from results of cubrid_list_dbs

  • « cubrid_data_seek
  • cubrid_errno »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Get db name from results of cubrid_list_dbs

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


Return the numerical value of the error message from previous CUBRID operation

  • « cubrid_db_name
  • cubrid_error »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Return the numerical value of the error message from previous CUBRID operation

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


Get the error message

  • « cubrid_errno
  • cubrid_fetch_array »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Get the error message

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


Fetch a result row as an associative array, a numeric array, or both

  • « cubrid_error
  • cubrid_fetch_assoc »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Fetch a result row as an associative array, a numeric array, or both

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


Return the associative array that corresponds to the fetched row

  • « cubrid_fetch_array
  • cubrid_fetch_field »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Return the associative array that corresponds to the fetched row

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


Get column information from a result and return as an object

  • « cubrid_fetch_assoc
  • cubrid_fetch_lengths »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Get column information from a result and return 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 an 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


Return an array with the lengths of the values of each field from the current row

  • « cubrid_fetch_field
  • cubrid_fetch_object »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Return an array with the lengths of the values of each field from the current row

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

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


Fetch the next row and return it as an object

  • « cubrid_fetch_lengths
  • cubrid_fetch_row »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Fetch the next row and return it as an object

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


Return a numerical array with the values of the current row

  • « cubrid_fetch_object
  • cubrid_field_flags »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • 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


Return a string with the flags of the given field offset

  • « cubrid_fetch_row
  • cubrid_field_len »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Return a string with the flags of the given field offset

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


Get the maximum length of the specified field

  • « cubrid_field_flags
  • cubrid_field_name »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Get the maximum length of the specified field

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


Return the name of the specified field index

  • « cubrid_field_len
  • cubrid_field_seek »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Return the name of the specified field index

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


Move the result set cursor to the specified field offset

  • « cubrid_field_name
  • cubrid_field_table »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Move the result set cursor to the specified field offset

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


Return the name of the table of the specified field

  • « cubrid_field_seek
  • cubrid_field_type »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Return the name of the table of the specified field

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


Return the type of the column corresponding to the given field offset

  • « cubrid_field_table
  • cubrid_list_dbs »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Return the type of the column corresponding to the given field offset

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


Return an array with the list of all existing CUBRID databases

  • « cubrid_field_type
  • cubrid_num_fields »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Return an array with the list of all existing CUBRID databases

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


Return the number of columns in the result set

  • « cubrid_list_dbs
  • cubrid_ping »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Return the number of columns in the result set

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


Ping a server connection or reconnect if there is no connection

  • « cubrid_num_fields
  • cubrid_query »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Ping a server connection or reconnect if there is no connection

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


Send a CUBRID query

  • « cubrid_ping
  • cubrid_real_escape_string »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Send a CUBRID query

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


Escape special characters in a string for use in an SQL statement

  • « cubrid_query
  • cubrid_result »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Escape special characters in a string for use in an SQL statement

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{|}~"
}


Return the value of a specific field in a specific row

  • « cubrid_real_escape_string
  • cubrid_unbuffered_query »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Return the value of a specific field in a specific row

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"


Perform a query without fetching the results into memory

  • « cubrid_result
  • CUBRID Obsolete Aliases and Functions »
  • PHP Manual
  • CUBRID MySQL Compatibility Functions
  • Perform a query without fetching the results into memory

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.

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

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


CUBRID Obsolete Aliases and Functions

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


Read data from a GLO instance and save it in a file

  • « CUBRID Obsolete Aliases and Functions
  • cubrid_new_glo »
  • PHP Manual
  • CUBRID Obsolete Aliases and Functions
  • Read data from a GLO instance and save it in a file

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


Create a glo instance

  • « cubrid_load_from_glo
  • cubrid_save_to_glo »
  • PHP Manual
  • CUBRID Obsolete Aliases and Functions
  • Create a glo instance

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


Save requested file in a GLO instance

  • « cubrid_new_glo
  • cubrid_send_glo »
  • PHP Manual
  • CUBRID Obsolete Aliases and Functions
  • Save requested file in a GLO instance

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


Read data from glo and send it to std output

  • « cubrid_save_to_glo
  • DB++ »
  • PHP Manual
  • CUBRID Obsolete Aliases and Functions
  • 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


DB++

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
    • db++ error codes
  • DB++ Functions
    • dbplus_add — Add a tuple to a relation
    • dbplus_aql — Perform AQL query
    • dbplus_chdir — Get/Set database virtual current directory
    • dbplus_close — Close a relation
    • dbplus_curr — Get current tuple from relation
    • dbplus_errcode — Get error string for given errorcode or last error
    • dbplus_errno — Get error code for last operation
    • dbplus_find — Set a constraint on a relation
    • dbplus_first — Get first tuple from relation
    • dbplus_flush — Flush all changes made on a relation
    • dbplus_freealllocks — Free all locks held by this client
    • dbplus_freelock — Release write lock on tuple
    • dbplus_freerlocks — Free all tuple locks on given relation
    • dbplus_getlock — Get a write lock on a tuple
    • dbplus_getunique — Get an id number unique to a relation
    • dbplus_info — Get information about a relation
    • dbplus_last — Get last tuple from relation
    • dbplus_lockrel — Request write lock on relation
    • dbplus_next — Get next tuple from relation
    • dbplus_open — Open relation file
    • dbplus_prev — Get previous tuple from relation
    • dbplus_rchperm — Change relation permissions
    • dbplus_rcreate — Creates a new DB++ relation
    • dbplus_rcrtexact — Creates an exact but empty copy of a relation including indices
    • dbplus_rcrtlike — Creates an empty copy of a relation with default indices
    • dbplus_resolve — Resolve host information for relation
    • dbplus_restorepos — Restore position
    • dbplus_rkeys — Specify new primary key for a relation
    • dbplus_ropen — Open relation file local
    • dbplus_rquery — Perform local (raw) AQL query
    • dbplus_rrename — Rename a relation
    • dbplus_rsecindex — Create a new secondary index for a relation
    • dbplus_runlink — Remove relation from filesystem
    • dbplus_rzap — Remove all tuples from relation
    • dbplus_savepos — Save position
    • dbplus_setindex — Set index
    • dbplus_setindexbynumber — Set index by number
    • dbplus_sql — Perform SQL query
    • dbplus_tcl — Execute TCL code on server side
    • dbplus_tremove — Remove tuple and return new current tuple
    • dbplus_undo — Undo
    • dbplus_undoprepare — Prepare undo
    • dbplus_unlockrel — Give up write lock on relation
    • dbplus_unselect — Remove a constraint from relation
    • dbplus_update — Update specified tuple in relation
    • dbplus_xlockrel — Request exclusive lock on relation
    • dbplus_xunlockrel — Free exclusive lock on relation


Introduction

db++, made by the German company » Concept asa, is a relational database system with high performance and low memory and disk usage in mind. While providing SQL as an additional language interface, it is not really an SQL database in the first place but provides its own AQL query language which is much more influenced by the relational algebra than SQL is.

Concept asa always had an interest in supporting open source languages, db++ has had Perl and Tcl call interfaces for years now and uses Tcl as its internal stored procedure language.

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.


Requirements

This extension relies on external client libraries so you have to have a db++ client installed on the system you want to use this extension on.

» Concept asa provides » db++ Demo versions and » documentation for Linux, some other Unix versions. There is also a Windows version of db++, but this extension doesn't support it (yet).


Installation

In order to build this extension yourself you need the db++ client libraries and header files to be installed on your system (these are included in the db++ installation archives by default). You have to run configure with option --with-dbplus to build this extension.

configure looks for the client libraries and header files under the default paths /usr/dbplus, /usr/local/dbplus and /opt/dblus. If you have installed db++ in a different place you have add the installation path to the configure option like this: --with-dbplus=/your/installation/path .


Resource Types

dbplus_relation

Most db++ functions operate on or return dbplus_relation resources. A dbplus_relation is a handle to a stored relation or a relation generated as the result of a query.


Predefined Constants

Table of Contents

  • db++ error codes

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.


db++ error codes

DB++ Error Codes
PHP Constant | db++ constant | meaning
DBPLUS_ERR_NOERR (integer) | ERR_NOERR | Null error condition
DBPLUS_ERR_DUPLICATE (integer) | ERR_DUPLICATE | Tried to insert a duplicate tuple
DBPLUS_ERR_EOSCAN (integer) | ERR_EOSCAN | End of scan from rget()
DBPLUS_ERR_EMPTY (integer) | ERR_EMPTY | Relation is empty (server)
DBPLUS_ERR_CLOSE (integer) | ERR_CLOSE | The server can't close
DBPLUS_ERR_WLOCKED (integer) | ERR_WLOCKED | The record is write locked
DBPLUS_ERR_LOCKED (integer) | ERR_LOCKED | Relation was already locked
DBPLUS_ERR_NOLOCK (integer) | ERR_NOLOCK | Relation cannot be locked
DBPLUS_ERR_READ (integer) | ERR_READ | Read error on relation
DBPLUS_ERR_WRITE (integer) | ERR_WRITE | Write error on relation
DBPLUS_ERR_CREATE (integer) | ERR_CREATE | Create() system call failed
DBPLUS_ERR_LSEEK (integer) | ERR_LSEEK | Lseek() system call failed
DBPLUS_ERR_LENGTH (integer) | ERR_LENGTH | Tuple exceeds maximum length
DBPLUS_ERR_OPEN (integer) | ERR_OPEN | Open() system call failed
DBPLUS_ERR_WOPEN (integer) | ERR_WOPEN | Relation already opened for writing
DBPLUS_ERR_MAGIC (integer) | ERR_MAGIC | File is not a relation
DBPLUS_ERR_VERSION (integer) | ERR_VERSION | File is a very old relation
DBPLUS_ERR_PGSIZE (integer) | ERR_PGSIZE | Relation uses a different page size
DBPLUS_ERR_CRC (integer) | ERR_CRC | Invalid crc in the superpage
DBPLUS_ERR_PIPE (integer) | ERR_PIPE | Piped relation requires lseek()
DBPLUS_ERR_NIDX (integer) | ERR_NIDX | Too many secondary indices
DBPLUS_ERR_MALLOC (integer) | ERR_MALLOC | Malloc() call failed
DBPLUS_ERR_NUSERS (integer) | ERR_NUSERS | Error use of max users
DBPLUS_ERR_PREEXIT (integer) | ERR_PREEXIT | Caused by invalid usage
DBPLUS_ERR_ONTRAP (integer) | ERR_ONTRAP | Caused by a signal
DBPLUS_ERR_PREPROC (integer) | ERR_PREPROC | Error in the preprocessor
DBPLUS_ERR_DBPARSE (integer) | ERR_DBPARSE | Error in the parser
DBPLUS_ERR_DBRUNERR (integer) | ERR_DBRUNERR | Run error in db
DBPLUS_ERR_DBPREEXIT (integer) | ERR_DBPREEXIT | Exit condition caused by prexit() * procedure
DBPLUS_ERR_WAIT (integer) | ERR_WAIT | Wait a little (Simple only)
DBPLUS_ERR_CORRUPT_TUPLE (integer) | ERR_CORRUPT_TUPLE | A client sent a corrupt tuple
DBPLUS_ERR_WARNING0 (integer) | ERR_WARNING0 | The Simple routines encountered a non fatal error which was corrected
DBPLUS_ERR_PANIC (integer) | ERR_PANIC | The server should not really die but after a disaster send ERR_PANIC to all its clients
DBPLUS_ERR_FIFO (integer) | ERR_FIFO | Can't create a fifo
DBPLUS_ERR_PERM (integer) | ERR_PERM | Permission denied
DBPLUS_ERR_TCL (integer) | ERR_TCL | TCL_error
DBPLUS_ERR_RESTRICTED (integer) | ERR_RESTRICTED | Only two users
DBPLUS_ERR_USER (integer) | ERR_USER | An error in the use of the library by an application programmer
DBPLUS_ERR_UNKNOWN (integer) | ERR_UNKNOWN |


DB++ Functions

Table of Contents

  • dbplus_add — Add a tuple to a relation
  • dbplus_aql — Perform AQL query
  • dbplus_chdir — Get/Set database virtual current directory
  • dbplus_close — Close a relation
  • dbplus_curr — Get current tuple from relation
  • dbplus_errcode — Get error string for given errorcode or last error
  • dbplus_errno — Get error code for last operation
  • dbplus_find — Set a constraint on a relation
  • dbplus_first — Get first tuple from relation
  • dbplus_flush — Flush all changes made on a relation
  • dbplus_freealllocks — Free all locks held by this client
  • dbplus_freelock — Release write lock on tuple
  • dbplus_freerlocks — Free all tuple locks on given relation
  • dbplus_getlock — Get a write lock on a tuple
  • dbplus_getunique — Get an id number unique to a relation
  • dbplus_info — Get information about a relation
  • dbplus_last — Get last tuple from relation
  • dbplus_lockrel — Request write lock on relation
  • dbplus_next — Get next tuple from relation
  • dbplus_open — Open relation file
  • dbplus_prev — Get previous tuple from relation
  • dbplus_rchperm — Change relation permissions
  • dbplus_rcreate — Creates a new DB++ relation
  • dbplus_rcrtexact — Creates an exact but empty copy of a relation including indices
  • dbplus_rcrtlike — Creates an empty copy of a relation with default indices
  • dbplus_resolve — Resolve host information for relation
  • dbplus_restorepos — Restore position
  • dbplus_rkeys — Specify new primary key for a relation
  • dbplus_ropen — Open relation file local
  • dbplus_rquery — Perform local (raw) AQL query
  • dbplus_rrename — Rename a relation
  • dbplus_rsecindex — Create a new secondary index for a relation
  • dbplus_runlink — Remove relation from filesystem
  • dbplus_rzap — Remove all tuples from relation
  • dbplus_savepos — Save position
  • dbplus_setindex — Set index
  • dbplus_setindexbynumber — Set index by number
  • dbplus_sql — Perform SQL query
  • dbplus_tcl — Execute TCL code on server side
  • dbplus_tremove — Remove tuple and return new current tuple
  • dbplus_undo — Undo
  • dbplus_undoprepare — Prepare undo
  • dbplus_unlockrel — Give up write lock on relation
  • dbplus_unselect — Remove a constraint from relation
  • dbplus_update — Update specified tuple in relation
  • dbplus_xlockrel — Request exclusive lock on relation
  • dbplus_xunlockrel — Free exclusive lock on relation


Add a tuple to a relation

  • « DB++ Functions
  • dbplus_aql »
  • PHP Manual
  • DB++ Functions
  • Add a tuple to a relation

dbplus_add

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_add — Add a tuple to a relation

Description

dbplus_add ( resource $relation , array $tuple ) : int

Adds a tuple to a relation.

Parameters

relation

tuple

An array of attribute/value pairs to be inserted into the given relation.

After successful execution this array will contain the complete data of the newly created tuple, including all implicitly set domain fields like sequences.

Return Values

The function will return DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Notes

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.

See Also

  • dbplus_errcode() - Get error string for given errorcode or last error


Perform AQL query

  • « dbplus_add
  • dbplus_chdir »
  • PHP Manual
  • DB++ Functions
  • Perform AQL query

dbplus_aql

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_aql — Perform AQL query

Description

dbplus_aql ( string $query [, string $server [, string $dbpath ]] ) : resource

Executes an AQL query on the given server and dbpath.

Parameters

query

The AQL query to be executed. Further information on the AQL (Algebraic Query Language) is provided in the original db++ manual.

server

dbpath

Return Values

Returns a relation handle on success. The result data may be fetched from this relation by calling dbplus_next() and dbplus_curr(). Other relation access functions will not work on a result relation.

Notes

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.


Get/Set database virtual current directory

  • « dbplus_aql
  • dbplus_close »
  • PHP Manual
  • DB++ Functions
  • Get/Set database virtual current directory

dbplus_chdir

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_chdir — Get/Set database virtual current directory

Description

dbplus_chdir ([ string $newdir ] ) : string

Changes the virtual current directory where relation files will be looked for by dbplus_open().

Parameters

newdir

The new directory for relation files. You can omit this parameter to query the current working directory.

Return Values

Returns the absolute path of the current directory.

Notes

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.


Close a relation

  • « dbplus_chdir
  • dbplus_curr »
  • PHP Manual
  • DB++ Functions
  • Close a relation

dbplus_close

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_close — Close a relation

Description

dbplus_close ( resource $relation ) : mixed

Closes a relation previously opened by dbplus_open().

Parameters

relation

A relation opened by dbplus_open().

Return Values

Returns TRUE on success or DBPLUS_ERR_UNKNOWN on failure.

Notes

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.


Get current tuple from relation

  • « dbplus_close
  • dbplus_errcode »
  • PHP Manual
  • DB++ Functions
  • Get current tuple from relation

dbplus_curr

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_curr — Get current tuple from relation

Description

dbplus_curr ( resource $relation , array &$tuple ) : int

Reads the data for the current tuple for the given relation.

Parameters

relation

A relation opened by dbplus_open().

tuple

The data will be passed back in this parameter, as an associative array.

Return Values

The function will return zero (aka. DBPLUS_ERR_NOERR) on success or a db++ error code on failure.

Notes

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.

See Also

  • dbplus_first() - Get first tuple from relation
  • dbplus_prev() - Get previous tuple from relation
  • dbplus_next() - Get next tuple from relation
  • dbplus_last() - Get last tuple from relation
  • dbplus_errcode() - Get error string for given errorcode or last error


Get error string for given errorcode or last error

  • « dbplus_curr
  • dbplus_errno »
  • PHP Manual
  • DB++ Functions
  • Get error string for given errorcode or last error

dbplus_errcode

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_errcode — Get error string for given errorcode or last error

Description

dbplus_errcode ([ int $errno ] ) : string

Returns a clear error string for the given error code.

Parameters

errno

The error code. If not provided, the result code of the last db++ operation is assumed.

Return Values

Returns the error message.

Notes

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.


Get error code for last operation

  • « dbplus_errcode
  • dbplus_find »
  • PHP Manual
  • DB++ Functions
  • Get error code for last operation

dbplus_errno

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_errno — Get error code for last operation

Description

dbplus_errno ( void ) : int

Returns the error code returned by the last db++ operation.

Return Values

Returns the error code, as an integer.

Notes

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.

See Also

  • dbplus_errcode() - Get error string for given errorcode or last error


Set a constraint on a relation

  • « dbplus_errno
  • dbplus_first »
  • PHP Manual
  • DB++ Functions
  • Set a constraint on a relation

dbplus_find

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_find — Set a constraint on a relation

Description

dbplus_find ( resource $relation , array $constraints , mixed $tuple ) : int

Places a constraint on the given relation.

Further calls to functions like dbplus_curr() or dbplus_next() will only return tuples matching the given constraints.

Parameters

relation

A relation opened by dbplus_open().

constraints

Constraints are triplets of strings containing of a domain name, a comparison operator and a comparison value. The constraints parameter array may consist of a collection of string arrays, each of which contains a domain, an operator and a value, or of a single string array containing a multiple of three elements.

The comparison operator may be one of the following strings: '==', '>', '>=', '<', '<=', '!=', '~' for a regular expression match and 'BAND' or 'BOR' for bitwise operations.

tuple

Return Values

Notes

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.

See Also

  • dbplus_unselect() - Remove a constraint from relation


Get first tuple from relation

  • « dbplus_find
  • dbplus_flush »
  • PHP Manual
  • DB++ Functions
  • Get first tuple from relation

dbplus_first

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_first — Get first tuple from relation

Description

dbplus_first ( resource $relation , array &$tuple ) : int

Reads the data for the first tuple for the given relation, makes it the current tuple and pass it back as an associative array in tuple.

Parameters

relation

A relation opened by dbplus_open().

tuple

Return Values

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Notes

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.

See Also

  • dbplus_curr() - Get current tuple from relation
  • dbplus_prev() - Get previous tuple from relation
  • dbplus_next() - Get next tuple from relation
  • dbplus_last() - Get last tuple from relation
  • dbplus_errcode() - Get error string for given errorcode or last error


Flush all changes made on a relation

  • « dbplus_first
  • dbplus_freealllocks »
  • PHP Manual
  • DB++ Functions
  • Flush all changes made on a relation

dbplus_flush

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_flush — Flush all changes made on a relation

Description

dbplus_flush ( resource $relation ) : int

Writes all changes applied to relation since the last flush to disk.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Notes

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.

See Also

  • dbplus_errcode() - Get error string for given errorcode or last error


Free all locks held by this client

  • « dbplus_flush
  • dbplus_freelock »
  • PHP Manual
  • DB++ Functions
  • Free all locks held by this client

dbplus_freealllocks

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_freealllocks — Free all locks held by this client

Description

dbplus_freealllocks ( void ) : int

Frees all tuple locks held by this client.

Return Values

Notes

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.

See Also

  • dbplus_getlock() - Get a write lock on a tuple
  • dbplus_freelock() - Release write lock on tuple
  • dbplus_freerlocks() - Free all tuple locks on given relation


Release write lock on tuple

  • « dbplus_freealllocks
  • dbplus_freerlocks »
  • PHP Manual
  • DB++ Functions
  • Release write lock on tuple

dbplus_freelock

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_freelock — Release write lock on tuple

Description

dbplus_freelock ( resource $relation , string $tuple ) : int

Releases a write lock on the given tuple previously obtained by dbplus_getlock().

Parameters

relation

A relation opened by dbplus_open().

tuple

Return Values

Notes

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.

See Also

  • dbplus_getlock() - Get a write lock on a tuple
  • dbplus_freerlocks() - Free all tuple locks on given relation
  • dbplus_freealllocks() - Free all locks held by this client


Free all tuple locks on given relation

  • « dbplus_freelock
  • dbplus_getlock »
  • PHP Manual
  • DB++ Functions
  • Free all tuple locks on given relation

dbplus_freerlocks

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_freerlocks — Free all tuple locks on given relation

Description

dbplus_freerlocks ( resource $relation ) : int

Frees all tuple locks held on the given relation.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

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.

See Also

  • dbplus_getlock() - Get a write lock on a tuple
  • dbplus_freelock() - Release write lock on tuple
  • dbplus_freealllocks() - Free all locks held by this client


Get a write lock on a tuple

  • « dbplus_freerlocks
  • dbplus_getunique »
  • PHP Manual
  • DB++ Functions
  • Get a write lock on a tuple

dbplus_getlock

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_getlock — Get a write lock on a tuple

Description

dbplus_getlock ( resource $relation , string $tuple ) : int

Requests a write lock on the specified tuple.

Parameters

relation

A relation opened by dbplus_open().

tuple

Return Values

Returns zero on success or a non-zero error code, especially DBPLUS_ERR_WLOCKED on failure.

Notes

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.

See Also

  • dbplus_freelock() - Release write lock on tuple
  • dbplus_freerlocks() - Free all tuple locks on given relation
  • dbplus_freealllocks() - Free all locks held by this client


Get an id number unique to a relation

  • « dbplus_getlock
  • dbplus_info »
  • PHP Manual
  • DB++ Functions
  • Get an id number unique to a relation

dbplus_getunique

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_getunique — Get an id number unique to a relation

Description

dbplus_getunique ( resource $relation , int $uniqueid ) : int

Obtains a number guaranteed to be unique for the given relation and will pass it back in the variable given as uniqueid.

Parameters

relation

A relation opened by dbplus_open().

uniqueid

Return Values

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Notes

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.


Get information about a relation

  • « dbplus_getunique
  • dbplus_last »
  • PHP Manual
  • DB++ Functions
  • Get information about a relation

dbplus_info

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_info — Get information about a relation

Description

dbplus_info ( resource $relation , string $key , array &$result ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

relation

A relation opened by dbplus_open().

key

result

Notes

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.


Get last tuple from relation

  • « dbplus_info
  • dbplus_lockrel »
  • PHP Manual
  • DB++ Functions
  • Get last tuple from relation

dbplus_last

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_last — Get last tuple from relation

Description

dbplus_last ( resource $relation , array &$tuple ) : int

Reads the data for the last tuple for the given relation, makes it the current tuple and pass it back as an associative array in tuple.

Parameters

relation

A relation opened by dbplus_open().

tuple

Return Values

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Notes

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.

See Also

  • dbplus_first() - Get first tuple from relation
  • dbplus_curr() - Get current tuple from relation
  • dbplus_prev() - Get previous tuple from relation
  • dbplus_next() - Get next tuple from relation


Request write lock on relation

  • « dbplus_last
  • dbplus_next »
  • PHP Manual
  • DB++ Functions
  • Request write lock on relation

dbplus_lockrel

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_lockrel — Request write lock on relation

Description

dbplus_lockrel ( resource $relation ) : int

Requests a write lock on the given relation.

Other clients may still query the relation, but can't alter it while it is locked.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

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.


Get next tuple from relation

  • « dbplus_lockrel
  • dbplus_open »
  • PHP Manual
  • DB++ Functions
  • Get next tuple from relation

dbplus_next

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_next — Get next tuple from relation

Description

dbplus_next ( resource $relation , array &$tuple ) : int

Reads the data for the next tuple for the given relation, makes it the current tuple and will pass it back as an associative array in tuple.

Parameters

relation

A relation opened by dbplus_open().

tuple

Return Values

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Notes

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.

See Also

  • dbplus_first() - Get first tuple from relation
  • dbplus_curr() - Get current tuple from relation
  • dbplus_prev() - Get previous tuple from relation
  • dbplus_last() - Get last tuple from relation


Open relation file

  • « dbplus_next
  • dbplus_prev »
  • PHP Manual
  • DB++ Functions
  • Open relation file

dbplus_open

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_open — Open relation file

Description

dbplus_open ( string $name ) : resource

Opens the given relation file.

Parameters

name

Can be either a file name or a relative or absolute path name. This will be mapped in any case to an absolute relation file path on a specific host machine and server.

Return Values

On success a relation file resource (cursor) is returned which must be used in any subsequent commands referencing the relation. Failure leads to a zero return value, the actual error code may be asked for by calling dbplus_errno().

Notes

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.


Get previous tuple from relation

  • « dbplus_open
  • dbplus_rchperm »
  • PHP Manual
  • DB++ Functions
  • Get previous tuple from relation

dbplus_prev

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_prev — Get previous tuple from relation

Description

dbplus_prev ( resource $relation , array &$tuple ) : int

Reads the data for the previous tuple for the given relation, makes it the current tuple and will pass it back as an associative array in tuple.

Parameters

relation

A relation opened by dbplus_open().

tuple

Return Values

Returns DBPLUS_ERR_NOERR on success or a db++ error code on failure.

Notes

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.

See Also

  • dbplus_first() - Get first tuple from relation
  • dbplus_curr() - Get current tuple from relation
  • dbplus_next() - Get next tuple from relation
  • dbplus_last() - Get last tuple from relation


Change relation permissions

  • « dbplus_prev
  • dbplus_rcreate »
  • PHP Manual
  • DB++ Functions
  • Change relation permissions

dbplus_rchperm

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rchperm — Change relation permissions

Description

dbplus_rchperm ( resource $relation , int $mask , string $user , string $group ) : int

Changes access permissions as specified by mask, user and group. The values for these are operating system specific.

Parameters

relation

A relation opened by dbplus_open().

mask

user

group

Return Values

Notes

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.


Creates a new DB++ relation

  • « dbplus_rchperm
  • dbplus_rcrtexact »
  • PHP Manual
  • DB++ Functions
  • Creates a new DB++ relation

dbplus_rcreate

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rcreate — Creates a new DB++ relation

Description

dbplus_rcreate ( string $name , mixed $domlist [, bool $overwrite ] ) : resource

Creates a new relation. Any existing relation sharing the same name will be overwritten if the relation is currently not in use and overwrite is set to TRUE.

Parameters

name

domlist

A combination of domains. May be passed as a single domain name string or as an array of domain names.

This parameter should contain the domain specification for the new relation within an array of domain description strings. A domain description string consists of a domain name unique to this relation, a slash and a type specification character. See the db++ documentation, especially the dbcreate(1) manpage, for a description of available type specifiers and their meanings.

Note:

This function will also accept a string with space delimited domain description strings, but it is recommended to use an array

overwrite

Return Values

Notes

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.


Creates an exact but empty copy of a relation including indices

  • « dbplus_rcreate
  • dbplus_rcrtlike »
  • PHP Manual
  • DB++ Functions
  • Creates an exact but empty copy of a relation including indices

dbplus_rcrtexact

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rcrtexact — Creates an exact but empty copy of a relation including indices

Description

dbplus_rcrtexact ( string $name , resource $relation [, bool $overwrite ] ) : mixed

dbplus_rcrtexact() will create an exact but empty copy of the given relation under a new name.

Parameters

name

relation

The copied relation, opened by dbplus_open().

overwrite

An existing relation by the same name will only be overwritten if this parameter is set to TRUE and no other process is currently using the relation.

Return Values

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

Notes

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.


Creates an empty copy of a relation with default indices

  • « dbplus_rcrtexact
  • dbplus_resolve »
  • PHP Manual
  • DB++ Functions
  • Creates an empty copy of a relation with default indices

dbplus_rcrtlike

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rcrtlike — Creates an empty copy of a relation with default indices

Description

dbplus_rcrtlike ( string $name , resource $relation [, int $overwrite ] ) : mixed

dbplus_rcrtexact() will create an empty copy of the given relation under a new name, but with default indices.

Parameters

name

relation

The copied relation, opened by dbplus_open().

overwrite

An existing relation by the same name will only be overwritten if this parameter is set to TRUE and no other process is currently using the relation.

Return Values

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

Notes

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.


Resolve host information for relation

  • « dbplus_rcrtlike
  • dbplus_restorepos »
  • PHP Manual
  • DB++ Functions
  • Resolve host information for relation

dbplus_resolve

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_resolve — Resolve host information for relation

Description

dbplus_resolve ( string $relation_name ) : array

dbplus_resolve() will try to resolve the given relation_name and find out internal server id, real hostname and the database path on this host.

Parameters

relation_name

The relation name.

Return Values

Returns an array containing these values under the keys sid, host and host_path or FALSE on error.

Notes

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.

See Also

  • dbplus_tcl() - Execute TCL code on server side


Restore position

  • « dbplus_resolve
  • dbplus_rkeys »
  • PHP Manual
  • DB++ Functions
  • Restore position

dbplus_restorepos

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_restorepos — Restore position

Description

dbplus_restorepos ( resource $relation , array $tuple ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

relation

A relation opened by dbplus_open().

tuple

Return Values

Notes

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.


Specify new primary key for a relation

  • « dbplus_restorepos
  • dbplus_ropen »
  • PHP Manual
  • DB++ Functions
  • Specify new primary key for a relation

dbplus_rkeys

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rkeys — Specify new primary key for a relation

Description

dbplus_rkeys ( resource $relation , mixed $domlist ) : mixed

dbplus_rkeys() will replace the current primary key for relation with the combination of domains specified by domlist.

Parameters

relation

A relation opened by dbplus_open().

domlist

A combination of domains. May be passed as a single domain name string or as an array of domain names.

Return Values

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

Notes

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.


Open relation file local

  • « dbplus_rkeys
  • dbplus_rquery »
  • PHP Manual
  • DB++ Functions
  • Open relation file local

dbplus_ropen

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_ropen — Open relation file local

Description

dbplus_ropen ( string $name ) : resource

dbplus_ropen() will open the relation file locally for quick access without any client/server overhead. Access is read only and only dbplus_curr() and dbplus_next() may be applied to the returned relation.

Parameters

name

Return Values

Notes

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.


Perform local (raw) AQL query

  • « dbplus_ropen
  • dbplus_rrename »
  • PHP Manual
  • DB++ Functions
  • Perform local (raw) AQL query

dbplus_rquery

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rquery — Perform local (raw) AQL query

Description

dbplus_rquery ( string $query [, string $dbpath ] ) : resource

dbplus_rquery() performs a local (raw) AQL query using an AQL interpreter embedded into the db++ client library. dbplus_rquery() is faster than dbplus_aql() but will work on local data only.

Parameters

query

dbpath

Return Values

Notes

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.


Rename a relation

  • « dbplus_rquery
  • dbplus_rsecindex »
  • PHP Manual
  • DB++ Functions
  • Rename a relation

dbplus_rrename

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rrename — Rename a relation

Description

dbplus_rrename ( resource $relation , string $name ) : int

dbplus_rrename() will change the name of relation to name.

Parameters

relation

A relation opened by dbplus_open().

name

Return Values

Notes

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.


Create a new secondary index for a relation

  • « dbplus_rrename
  • dbplus_runlink »
  • PHP Manual
  • DB++ Functions
  • Create a new secondary index for a relation

dbplus_rsecindex

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rsecindex — Create a new secondary index for a relation

Description

dbplus_rsecindex ( resource $relation , mixed $domlist , int $type ) : mixed

dbplus_rsecindex() will create a new secondary index for relation with consists of the domains specified by domlist and is of type type

Parameters

relation

A relation opened by dbplus_open().

domlist

A combination of domains. May be passed as a single domain name string or as an array of domain names.

type

Return Values

Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.

Notes

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.


Remove relation from filesystem

  • « dbplus_rsecindex
  • dbplus_rzap »
  • PHP Manual
  • DB++ Functions
  • Remove relation from filesystem

dbplus_runlink

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_runlink — Remove relation from filesystem

Description

dbplus_runlink ( resource $relation ) : int

dbplus_runlink() will close and remove the relation.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

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.


Remove all tuples from relation

  • « dbplus_runlink
  • dbplus_savepos »
  • PHP Manual
  • DB++ Functions
  • Remove all tuples from relation

dbplus_rzap

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_rzap — Remove all tuples from relation

Description

dbplus_rzap ( resource $relation ) : int

dbplus_rzap() will remove all tuples from relation.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

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.


Save position

  • « dbplus_rzap
  • dbplus_setindex »
  • PHP Manual
  • DB++ Functions
  • Save position

dbplus_savepos

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_savepos — Save position

Description

dbplus_savepos ( resource $relation ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

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.


Set index

  • « dbplus_savepos
  • dbplus_setindexbynumber »
  • PHP Manual
  • DB++ Functions
  • Set index

dbplus_setindex

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_setindex — Set index

Description

dbplus_setindex ( resource $relation , string $idx_name ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

relation

A relation opened by dbplus_open().

idx_name

Return Values

Notes

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.


Set index by number

  • « dbplus_setindex
  • dbplus_sql »
  • PHP Manual
  • DB++ Functions
  • Set index by number

dbplus_setindexbynumber

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_setindexbynumber — Set index by number

Description

dbplus_setindexbynumber ( resource $relation , int $idx_number ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

relation

A relation opened by dbplus_open().

idx_number

Return Values

Notes

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.


Perform SQL query

  • « dbplus_setindexbynumber
  • dbplus_tcl »
  • PHP Manual
  • DB++ Functions
  • Perform SQL query

dbplus_sql

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_sql — Perform SQL query

Description

dbplus_sql ( string $query [, string $server [, string $dbpath ]] ) : resource
Warning

This function is currently not documented; only its argument list is available.

Parameters

query

server

dbpath

Return Values

Notes

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.


Execute TCL code on server side

  • « dbplus_sql
  • dbplus_tremove »
  • PHP Manual
  • DB++ Functions
  • Execute TCL code on server side

dbplus_tcl

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_tcl — Execute TCL code on server side

Description

dbplus_tcl ( int $sid , string $script ) : string

A db++ server will prepare a TCL interpreter for each client connection. This interpreter will enable the server to execute TCL code provided by the client as a sort of stored procedures to improve the performance of database operations by avoiding client/server data transfers and context switches.

dbplus_tcl() needs to pass the client connection id the TCL script code should be executed by. dbplus_resolve() will provide this connection id. The function will return whatever the TCL code returns or a TCL error message if the TCL code fails.

Parameters

sid

script

Return Values

Notes

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.

See Also

  • dbplus_resolve() - Resolve host information for relation


Remove tuple and return new current tuple

  • « dbplus_tcl
  • dbplus_undo »
  • PHP Manual
  • DB++ Functions
  • Remove tuple and return new current tuple

dbplus_tremove

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_tremove — Remove tuple and return new current tuple

Description

dbplus_tremove ( resource $relation , array $tuple [, array &$current ] ) : int

dbplus_tremove() removes tuple from relation if it perfectly matches a tuple within the relation. current, if given, will contain the data of the new current tuple after calling dbplus_tremove().

Parameters

relation

A relation opened by dbplus_open().

tuple

current

Return Values

Notes

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.


Undo

  • « dbplus_tremove
  • dbplus_undoprepare »
  • PHP Manual
  • DB++ Functions
  • Undo

dbplus_undo

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_undo — Undo

Description

dbplus_undo ( resource $relation ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

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.


Prepare undo

  • « dbplus_undo
  • dbplus_unlockrel »
  • PHP Manual
  • DB++ Functions
  • Prepare undo

dbplus_undoprepare

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_undoprepare — Prepare undo

Description

dbplus_undoprepare ( resource $relation ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

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.


Give up write lock on relation

  • « dbplus_undoprepare
  • dbplus_unselect »
  • PHP Manual
  • DB++ Functions
  • Give up write lock on relation

dbplus_unlockrel

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_unlockrel — Give up write lock on relation

Description

dbplus_unlockrel ( resource $relation ) : int

Release a write lock previously obtained by dbplus_lockrel().

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

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.


Remove a constraint from relation

  • « dbplus_unlockrel
  • dbplus_update »
  • PHP Manual
  • DB++ Functions
  • Remove a constraint from relation

dbplus_unselect

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_unselect — Remove a constraint from relation

Description

dbplus_unselect ( resource $relation ) : int

Calling dbplus_unselect() will remove a constraint previously set by dbplus_find() on relation.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

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.


Update specified tuple in relation

  • « dbplus_unselect
  • dbplus_xlockrel »
  • PHP Manual
  • DB++ Functions
  • Update specified tuple in relation

dbplus_update

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_update — Update specified tuple in relation

Description

dbplus_update ( resource $relation , array $old , array $new ) : int

dbplus_update() replaces the old tuple with the data from the new one, only if the old completely matches a tuple within relation.

Parameters

relation

A relation opened by dbplus_open().

old

The old tuple.

new

The new tuple.

Return Values

Notes

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.


Request exclusive lock on relation

  • « dbplus_update
  • dbplus_xunlockrel »
  • PHP Manual
  • DB++ Functions
  • Request exclusive lock on relation

dbplus_xlockrel

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_xlockrel — Request exclusive lock on relation

Description

dbplus_xlockrel ( resource $relation ) : int

Request an exclusive lock on relation preventing even read access from other clients.

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

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.

See Also

  • dbplus_xunlockrel() - Free exclusive lock on relation


Free exclusive lock on relation

  • « dbplus_xlockrel
  • dBase »
  • PHP Manual
  • DB++ Functions
  • Free exclusive lock on relation

dbplus_xunlockrel

(PHP 4 <= 4.1.0, PECL dbplus >= 0.9)

dbplus_xunlockrel — Free exclusive lock on relation

Description

dbplus_xunlockrel ( resource $relation ) : int

Releases an exclusive lock previously obtained by dbplus_xlockrel().

Parameters

relation

A relation opened by dbplus_open().

Return Values

Notes

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.


dBase

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • 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_with_names — Gets a record from a database as an associative array
    • dbase_get_record — Gets a record from a database as an indexed 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


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 such as ISAPI.

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. Available as of PHP 5.2.0
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.


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

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_with_names — Gets a record from a database as an associative array
  • dbase_get_record — Gets a record from a database as an indexed 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


Adds a record to a database

  • « dBase Functions
  • dbase_close »
  • PHP Manual
  • dBase Functions
  • Adds a record to a database

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 $dbase_identifier , array $record ) : bool

Adds the given data to the database.

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

record

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
dbase 7.0.0 | dbase_identifier 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


Closes a database

  • « dbase_add_record
  • dbase_create »
  • PHP Manual
  • dBase Functions
  • Closes a database

dbase_close

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_close — Closes a database

Description

dbase_close ( resource $dbase_identifier ) : bool

Closes the given database link identifier.

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
dbase 7.0.0 | dbase_identifier 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


Creates a database

  • « dbase_close
  • dbase_delete_record »
  • PHP Manual
  • dBase Functions
  • Creates a database

dbase_create

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_create — Creates a database

Description

dbase_create ( string $filename , 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: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

Note:

This function is affected by open_basedir.

Parameters

filename

The name 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 link identifier if the database is successfully created, or FALSE if an error occurred.

Changelog

Version | Description
dbase 7.0.0 | The type parameter has been added.
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


Deletes a record from a database

  • « dbase_create
  • dbase_get_header_info »
  • PHP Manual
  • dBase Functions
  • Deletes a record from 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 $dbase_identifier , int $record_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

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

record_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
dbase 7.0.0 | dbase_identifier 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


Gets the header info of a database

  • « dbase_delete_record
  • dbase_get_record_with_names »
  • PHP Manual
  • dBase Functions
  • Gets the header info of 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 $dbase_identifier ) : array

Returns information on the column structure of the given database link identifier.

Parameters

dbase_identifier

The database link identifier, 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
dbase 7.0.0 | dbase_identifier 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);
?>


Gets a record from a database as an associative array

  • « dbase_get_header_info
  • dbase_get_record »
  • PHP Manual
  • dBase Functions
  • 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 $dbase_identifier , int $record_number ) : array

Gets a record from a dBase database as an associative array.

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

record_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
dbase 7.0.0 | dbase_identifier 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


Gets a record from a database as an indexed array

  • « dbase_get_record_with_names
  • dbase_numfields »
  • PHP Manual
  • dBase Functions
  • Gets a record from a database as an indexed array

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 $dbase_identifier , int $record_number ) : array

Gets a record from a database as an indexed array.

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

record_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
dbase 7.0.0 | dbase_identifier 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


Gets the number of fields of a database

  • « dbase_get_record
  • dbase_numrecords »
  • PHP Manual
  • dBase Functions
  • Gets the number of fields of a database

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 $dbase_identifier ) : 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

dbase_identifier

The database link identifier, 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
dbase 7.0.0 | dbase_identifier 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


Gets the number of records in a database

  • « dbase_numfields
  • dbase_open »
  • PHP Manual
  • dBase Functions
  • 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 $dbase_identifier ) : 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

dbase_identifier

The database link identifier, 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
dbase 7.0.0 | dbase_identifier 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


Opens a database

  • « dbase_numrecords
  • dbase_pack »
  • PHP Manual
  • dBase Functions
  • Opens a database

dbase_open

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_open — Opens a database

Description

dbase_open ( string $filename , int $mode ) : resource

dbase_open() opens a dBase database with the given access mode.

Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

Note:

This function is affected by open_basedir.

Parameters

filename

The name 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.

Changelog

Version | Description
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);
}

?>

Return Values

Returns a database link identifier if the database is successfully opened, or FALSE if an error occurred.

See Also

  • dbase_create() - Creates a database
  • dbase_close() - Closes a database


Packs a database

  • « dbase_open
  • dbase_replace_record »
  • PHP Manual
  • dBase Functions
  • Packs a database

dbase_pack

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_pack — Packs a database

Description

dbase_pack ( resource $dbase_identifier ) : 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

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
dbase 7.0.0 | dbase_identifier 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


Replaces a record in a database

  • « dbase_pack
  • filePro »
  • PHP Manual
  • dBase Functions
  • Replaces a record in 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 $dbase_identifier , array $record , int $record_number ) : bool

Replaces the given record in the database with the given data.

Parameters

dbase_identifier

The database link identifier, returned by dbase_open() or dbase_create().

record

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.

record_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
dbase 7.0.0 | dbase_identifier 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 integer 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


filePro

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • filePro Functions
    • filepro_fieldcount — Find out how many fields are in a filePro database
    • filepro_fieldname — Gets the name of a field
    • filepro_fieldtype — Gets the type of a field
    • filepro_fieldwidth — Gets the width of a field
    • filepro_retrieve — Retrieves data from a filePro database
    • filepro_rowcount — Find out how many rows are in a filePro database
    • filepro — Read and verify the map file


Introduction

These functions allow read-only access to data stored in filePro databases.

filePro is a registered trademark of fP Technologies, Inc. You can find more information about filePro at » http://www.fptech.com/.

Note:

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.2.0.


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


  • « Resource Types
  • filePro Functions »
  • PHP Manual
  • filePro
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


filePro Functions

Table of Contents

  • filepro_fieldcount — Find out how many fields are in a filePro database
  • filepro_fieldname — Gets the name of a field
  • filepro_fieldtype — Gets the type of a field
  • filepro_fieldwidth — Gets the width of a field
  • filepro_retrieve — Retrieves data from a filePro database
  • filepro_rowcount — Find out how many rows are in a filePro database
  • filepro — Read and verify the map file


Find out how many fields are in a filePro database

  • « filePro Functions
  • filepro_fieldname »
  • PHP Manual
  • filePro Functions
  • Find out how many fields are in a filePro database

filepro_fieldcount

(PHP 4, PHP 5 < 5.2.0, PHP 7)

filepro_fieldcount — Find out how many fields are in a filePro database

Description

filepro_fieldcount ( void ) : int

Returns the number of fields (columns) in the opened filePro database.

Return Values

Returns the number of fields in the opened filePro database, or FALSE on errors.

See Also

  • filepro() - Read and verify the map file


Gets the name of a field

  • « filepro_fieldcount
  • filepro_fieldtype »
  • PHP Manual
  • filePro Functions
  • Gets the name of a field

filepro_fieldname

(PHP 4, PHP 5 < 5.2.0, PHP 7)

filepro_fieldname — Gets the name of a field

Description

filepro_fieldname ( int $field_number ) : string

Returns the name of the field corresponding to field_number.

Parameters

field_number

The field number.

Return Values

Returns the name of the field as a string, or FALSE on errors.


Gets the type of a field

  • « filepro_fieldname
  • filepro_fieldwidth »
  • PHP Manual
  • filePro Functions
  • Gets the type of a field

filepro_fieldtype

(PHP 4, PHP 5 < 5.2.0, PHP 7)

filepro_fieldtype — Gets the type of a field

Description

filepro_fieldtype ( int $field_number ) : string

Returns the edit type of the field corresponding to field_number.

Parameters

field_number

The field number.

Return Values

Returns the edit type of the field as a string, or FALSE on errors.


Gets the width of a field

  • « filepro_fieldtype
  • filepro_retrieve »
  • PHP Manual
  • filePro Functions
  • Gets the width of a field

filepro_fieldwidth

(PHP 4, PHP 5 < 5.2.0, PHP 7)

filepro_fieldwidth — Gets the width of a field

Description

filepro_fieldwidth ( int $field_number ) : int

Returns the width of the field corresponding to field_number.

Parameters

field_number

The field number.

Return Values

Returns the width of the field as a integer, or FALSE on errors.


Retrieves data from a filePro database

  • « filepro_fieldwidth
  • filepro_rowcount »
  • PHP Manual
  • filePro Functions
  • Retrieves data from a filePro database

filepro_retrieve

(PHP 4, PHP 5 < 5.2.0, PHP 7)

filepro_retrieve — Retrieves data from a filePro database

Description

filepro_retrieve ( int $row_number , int $field_number ) : string

Returns the data from the specified location in the database.

Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

Parameters

row_number

The row number. Must be between zero and the total number of rows minus one (0..filepro_rowcount() - 1)

field_number

The field number. Accepts values between zero and the total number of fields minus one (0..filepro_fieldcount() - 1)

Return Values

Returns the specified data, or FALSE on errors.


Find out how many rows are in a filePro database

  • « filepro_retrieve
  • filepro »
  • PHP Manual
  • filePro Functions
  • Find out how many rows are in a filePro database

filepro_rowcount

(PHP 4, PHP 5 < 5.2.0, PHP 7)

filepro_rowcount — Find out how many rows are in a filePro database

Description

filepro_rowcount ( void ) : int

Returns the number of rows in the opened filePro database.

Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

Return Values

Returns the number of rows in the opened filePro database, or FALSE on errors.

See Also

  • filepro() - Read and verify the map file


Read and verify the map file

  • « filepro_rowcount
  • Firebird/InterBase »
  • PHP Manual
  • filePro Functions
  • Read and verify the map file

filepro

(PHP 4, PHP 5 < 5.2.0, PHP 7)

filepro — Read and verify the map file

Description

filepro ( string $directory ) : bool

This reads and verifies the map file, storing the field count and info.

No locking is done, so you should avoid modifying your filePro database while it may be opened in PHP.

Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

Parameters

directory

The map directory.

Return Values

Returns TRUE on success or FALSE on failure.


Firebird/InterBase

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • 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_ret — Alias of ibase_commit_ret
    • fbird_commit — Alias of ibase_commit
    • 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_ret — Alias of ibase_rollback_ret
    • fbird_rollback — Alias of ibase_rollback
    • 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_ret — Commit a transaction without closing it
    • ibase_commit — Commit a transaction
    • 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_ret — Roll back a transaction without closing it
    • ibase_rollback — Roll back a transaction
    • 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


Introduction

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 supports InterBase versions 6 and up and Firebird version 2.0 and up.

This database uses a single quote (') character for escaping add to your php.ini the following directive(Deprecated in PHP 5.3.0. Removed in PHP 5.4.0):

magic_quotes_sybase = On


Installation

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" | PHP_INI_SYSTEM |
ibase.max_persistent | "-1" | PHP_INI_SYSTEM |
ibase.max_links | "-1" | PHP_INI_SYSTEM |
ibase.default_db | NULL | PHP_INI_SYSTEM |
ibase.default_user | NULL | PHP_INI_ALL |
ibase.default_password | NULL | PHP_INI_ALL |
ibase.default_charset | NULL | PHP_INI_ALL |
ibase.timestampformat | "%Y-%m-%d %H:%M:%S" | PHP_INI_ALL |
ibase.dateformat | "%Y-%m-%d" | PHP_INI_ALL |
ibase.timeformat | "%H:%M:%S" | PHP_INI_ALL |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

ibase.allow_persistent boolean

Whether to allow persistent connections to Firebird/InterBase.

ibase.max_persistent integer

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 integer

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

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_ret — Alias of ibase_commit_ret
  • fbird_commit — Alias of ibase_commit
  • 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_ret — Alias of ibase_rollback_ret
  • fbird_rollback — Alias of ibase_rollback
  • 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_ret — Commit a transaction without closing it
  • ibase_commit — Commit a transaction
  • 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_ret — Roll back a transaction without closing it
  • ibase_rollback — Roll back a transaction
  • 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


Alias of ibase_add_user

  • « Firebird/InterBase Functions
  • fbird_affected_rows »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_add_user

fbird_add_user

(PHP 5, PHP 7)

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


Alias of ibase_affected_rows

  • « fbird_add_user
  • fbird_backup »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_affected_rows

fbird_affected_rows

(PHP 5, PHP 7)

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


Alias of ibase_backup

  • « fbird_affected_rows
  • fbird_blob_add »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_backup

fbird_backup

(PHP 5, PHP 7)

fbird_backup — Alias of ibase_backup()

Description

This function is an alias of: ibase_backup().


Alias of ibase_blob_add

  • « fbird_backup
  • fbird_blob_cancel »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_blob_add

fbird_blob_add

(PHP 5, PHP 7)

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


Cancel creating blob

  • « fbird_blob_add
  • fbird_blob_close »
  • PHP Manual
  • Firebird/InterBase Functions
  • Cancel creating blob

fbird_blob_cancel

(PHP 5, PHP 7)

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


Alias of ibase_blob_close

  • « fbird_blob_cancel
  • fbird_blob_create »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_blob_close

fbird_blob_close

(PHP 5, PHP 7)

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


Alias of ibase_blob_create

  • « fbird_blob_close
  • fbird_blob_echo »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_blob_create

fbird_blob_create

(PHP 5, PHP 7)

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


Alias of ibase_blob_echo

  • « fbird_blob_create
  • fbird_blob_get »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_blob_echo

fbird_blob_echo

(PHP 5, PHP 7)

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


Alias of ibase_blob_get

  • « fbird_blob_echo
  • fbird_blob_import »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_blob_get

fbird_blob_get

(PHP 5, PHP 7)

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


Alias of ibase_blob_import

  • « fbird_blob_get
  • fbird_blob_info »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_blob_import

fbird_blob_import

(PHP 5, PHP 7)

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


Alias of ibase_blob_info

  • « fbird_blob_import
  • fbird_blob_open »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_blob_info

fbird_blob_info

(PHP 5, PHP 7)

fbird_blob_info — Alias of ibase_blob_info()

Description

This function is an alias of: ibase_blob_info().


Alias of ibase_blob_open

  • « fbird_blob_info
  • fbird_close »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_blob_open

fbird_blob_open

(PHP 5, PHP 7)

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


Alias of ibase_close

  • « fbird_blob_open
  • fbird_commit_ret »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_close

fbird_close

(PHP 5, PHP 7)

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


Alias of ibase_commit_ret

  • « fbird_close
  • fbird_commit »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_commit_ret

fbird_commit_ret

(PHP 5, PHP 7)

fbird_commit_ret — Alias of ibase_commit_ret()

Description

This function is an alias of: ibase_commit_ret().


Alias of ibase_commit

  • « fbird_commit_ret
  • fbird_connect »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_commit

fbird_commit

(PHP 5, PHP 7)

fbird_commit — Alias of ibase_commit()

Description

This function is an alias of: ibase_commit().


Alias of ibase_connect

  • « fbird_commit
  • fbird_db_info »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_connect

fbird_connect

(PHP 5, PHP 7)

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


Alias of ibase_db_info

  • « fbird_connect
  • fbird_delete_user »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_db_info

fbird_db_info

(PHP 5, PHP 7)

fbird_db_info — Alias of ibase_db_info()

Description

This function is an alias of: ibase_db_info().


Alias of ibase_delete_user

  • « fbird_db_info
  • fbird_drop_db »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_delete_user

fbird_delete_user

(PHP 5, PHP 7)

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


Alias of ibase_drop_db

  • « fbird_delete_user
  • fbird_errcode »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_drop_db

fbird_drop_db

(PHP 5, PHP 7)

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


Alias of ibase_errcode

  • « fbird_drop_db
  • fbird_errmsg »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_errcode

fbird_errcode

(PHP 5, PHP 7)

fbird_errcode — Alias of ibase_errcode()

Description

This function is an alias of: ibase_errcode().

See Also

  • fbird_errmsg() - Alias of ibase_errmsg


Alias of ibase_errmsg

  • « fbird_errcode
  • fbird_execute »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_errmsg

fbird_errmsg

(PHP 5, PHP 7)

fbird_errmsg — Alias of ibase_errmsg()

Description

This function is an alias of: ibase_errmsg().

See Also

  • fbird_errcode() - Alias of ibase_errcode


Alias of ibase_execute

  • « fbird_errmsg
  • fbird_fetch_assoc »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_execute

fbird_execute

(PHP 5, PHP 7)

fbird_execute — Alias of ibase_execute()

Description

This function is an alias of: ibase_execute().

See Also

  • fbird_query() - Alias of ibase_query


Alias of ibase_fetch_assoc

  • « fbird_execute
  • fbird_fetch_object »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_fetch_assoc

fbird_fetch_assoc

(PHP 5, PHP 7)

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


Alias of ibase_fetch_object

  • « fbird_fetch_assoc
  • fbird_fetch_row »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_fetch_object

fbird_fetch_object

(PHP 5, PHP 7)

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


Alias of ibase_fetch_row

  • « fbird_fetch_object
  • fbird_field_info »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_fetch_row

fbird_fetch_row

(PHP 5, PHP 7)

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


Alias of ibase_field_info

  • « fbird_fetch_row
  • fbird_free_event_handler »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_field_info

fbird_field_info

(PHP 5, PHP 7)

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


Alias of ibase_free_event_handler

  • « fbird_field_info
  • fbird_free_query »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_free_event_handler

fbird_free_event_handler

(PHP 5, PHP 7)

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


Alias of ibase_free_query

  • « fbird_free_event_handler
  • fbird_free_result »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_free_query

fbird_free_query

(PHP 5, PHP 7)

fbird_free_query — Alias of ibase_free_query()

Description

This function is an alias of: ibase_free_query().


Alias of ibase_free_result

  • « fbird_free_query
  • fbird_gen_id »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_free_result

fbird_free_result

(PHP 5, PHP 7)

fbird_free_result — Alias of ibase_free_result()

Description

This function is an alias of: ibase_free_result().


Alias of ibase_gen_id

  • « fbird_free_result
  • fbird_maintain_db »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_gen_id

fbird_gen_id

(PHP 5, PHP 7)

fbird_gen_id — Alias of ibase_gen_id()

Description

This function is an alias of: ibase_gen_id().


Alias of ibase_maintain_db

  • « fbird_gen_id
  • fbird_modify_user »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_maintain_db

fbird_maintain_db

(PHP 5, PHP 7)

fbird_maintain_db — Alias of ibase_maintain_db()

Description

This function is an alias of: ibase_maintain_db().


Alias of ibase_modify_user

  • « fbird_maintain_db
  • fbird_name_result »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_modify_user

fbird_modify_user

(PHP 5, PHP 7)

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


Alias of ibase_name_result

  • « fbird_modify_user
  • fbird_num_fields »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_name_result

fbird_name_result

(PHP 5, PHP 7)

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


Alias of ibase_num_fields

  • « fbird_name_result
  • fbird_num_params »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_num_fields

fbird_num_fields

(PHP 5, PHP 7)

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


Alias of ibase_num_params

  • « fbird_num_fields
  • fbird_param_info »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_num_params

fbird_num_params

(PHP 5, PHP 7)

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


Alias of ibase_param_info

  • « fbird_num_params
  • fbird_pconnect »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_param_info

fbird_param_info

(PHP 5, PHP 7)

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


Alias of ibase_pconnect

  • « fbird_param_info
  • fbird_prepare »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_pconnect

fbird_pconnect

(PHP 5, PHP 7)

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


Alias of ibase_prepare

  • « fbird_pconnect
  • fbird_query »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_prepare

fbird_prepare

(PHP 5, PHP 7)

fbird_prepare — Alias of ibase_prepare()

Description

This function is an alias of: ibase_prepare().


Alias of ibase_query

  • « fbird_prepare
  • fbird_restore »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_query

fbird_query

(PHP 5, PHP 7)

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


Alias of ibase_restore

  • « fbird_query
  • fbird_rollback_ret »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_restore

fbird_restore

(PHP 5, PHP 7)

fbird_restore — Alias of ibase_restore()

Description

This function is an alias of: ibase_restore().


Alias of ibase_rollback_ret

  • « fbird_restore
  • fbird_rollback »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_rollback_ret

fbird_rollback_ret

(PHP 5, PHP 7)

fbird_rollback_ret — Alias of ibase_rollback_ret()

Description

This function is an alias of: ibase_rollback_ret().


Alias of ibase_rollback

  • « fbird_rollback_ret
  • fbird_server_info »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_rollback

fbird_rollback

(PHP 5, PHP 7)

fbird_rollback — Alias of ibase_rollback()

Description

This function is an alias of: ibase_rollback().


Alias of ibase_server_info

  • « fbird_rollback
  • fbird_service_attach »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_server_info

fbird_server_info

(PHP 5, PHP 7)

fbird_server_info — Alias of ibase_server_info()

Description

This function is an alias of: ibase_server_info().


Alias of ibase_service_attach

  • « fbird_server_info
  • fbird_service_detach »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_service_attach

fbird_service_attach

(PHP 5, PHP 7)

fbird_service_attach — Alias of ibase_service_attach()

Description

This function is an alias of: ibase_service_attach().


Alias of ibase_service_detach

  • « fbird_service_attach
  • fbird_set_event_handler »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_service_detach

fbird_service_detach

(PHP 5, PHP 7)

fbird_service_detach — Alias of ibase_service_detach()

Description

This function is an alias of: ibase_service_detach().


Alias of ibase_set_event_handler

  • « fbird_service_detach
  • fbird_trans »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_set_event_handler

fbird_set_event_handler

(PHP 5, PHP 7)

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


Alias of ibase_trans

  • « fbird_set_event_handler
  • fbird_wait_event »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_trans

fbird_trans

(PHP 5, PHP 7)

fbird_trans — Alias of ibase_trans()

Description

This function is an alias of: ibase_trans().


Alias of ibase_wait_event

  • « fbird_trans
  • ibase_add_user »
  • PHP Manual
  • Firebird/InterBase Functions
  • Alias of ibase_wait_event

fbird_wait_event

(PHP 5, PHP 7)

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


Add a user to a security database

  • « fbird_wait_event
  • ibase_affected_rows »
  • PHP Manual
  • Firebird/InterBase Functions
  • Add a user to a security database

ibase_add_user

(PHP 5, PHP 7)

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


Return the number of rows that were affected by the previous query

  • « ibase_add_user
  • ibase_backup »
  • PHP Manual
  • Firebird/InterBase Functions
  • Return the number of rows that were affected by the previous query

ibase_affected_rows

(PHP 5, PHP 7)

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


Initiates a backup task in the service manager and returns immediately

  • « ibase_affected_rows
  • ibase_blob_add »
  • PHP Manual
  • Firebird/InterBase Functions
  • Initiates a backup task in the service manager and returns immediately

ibase_backup

(PHP 5, PHP 7)

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


Add data into a newly created blob

  • « ibase_backup
  • ibase_blob_cancel »
  • PHP Manual
  • Firebird/InterBase Functions
  • Add data into a newly created blob

ibase_blob_add

(PHP 5, PHP 7)

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


Cancel creating blob

  • « ibase_blob_add
  • ibase_blob_close »
  • PHP Manual
  • Firebird/InterBase Functions
  • Cancel creating blob

ibase_blob_cancel

(PHP 5, PHP 7)

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


Close blob

  • « ibase_blob_cancel
  • ibase_blob_create »
  • PHP Manual
  • Firebird/InterBase Functions
  • Close blob

ibase_blob_close

(PHP 5, PHP 7)

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


Create a new blob for adding data

  • « ibase_blob_close
  • ibase_blob_echo »
  • PHP Manual
  • Firebird/InterBase Functions
  • Create a new blob for adding data

ibase_blob_create

(PHP 5, PHP 7)

ibase_blob_create — Create a new blob for adding data

Description

ibase_blob_create ([ resource $link_identifier = NULL ] ) : resource

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


Output blob contents to browser

  • « ibase_blob_create
  • ibase_blob_get »
  • PHP Manual
  • Firebird/InterBase Functions
  • Output blob contents to browser

ibase_blob_echo

(PHP 5, PHP 7)

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


Get len bytes data from open blob

  • « ibase_blob_echo
  • ibase_blob_import »
  • PHP Manual
  • Firebird/InterBase Functions
  • Get len bytes data from open blob

ibase_blob_get

(PHP 5, PHP 7)

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


Create blob, copy file in it, and close it

  • « ibase_blob_get
  • ibase_blob_info »
  • PHP Manual
  • Firebird/InterBase Functions
  • Create blob, copy file in it, and close it

ibase_blob_import

(PHP 5, PHP 7)

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


Return blob length and other useful info

  • « ibase_blob_import
  • ibase_blob_open »
  • PHP Manual
  • Firebird/InterBase Functions
  • Return blob length and other useful info

ibase_blob_info

(PHP 5, PHP 7)

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.


Open blob for retrieving data parts

  • « ibase_blob_info
  • ibase_close »
  • PHP Manual
  • Firebird/InterBase Functions
  • Open blob for retrieving data parts

ibase_blob_open

(PHP 5, PHP 7)

ibase_blob_open — Open blob for retrieving data parts

Description

ibase_blob_open ( resource $link_identifier , string $blob_id ) : resource
ibase_blob_open ( string $blob_id ) : resource

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


Close a connection to an InterBase database

  • « ibase_blob_open
  • ibase_commit_ret »
  • PHP Manual
  • Firebird/InterBase Functions
  • Close a connection to an InterBase database

ibase_close

(PHP 5, PHP 7)

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


Commit a transaction without closing it

  • « ibase_close
  • ibase_commit »
  • PHP Manual
  • Firebird/InterBase Functions
  • Commit a transaction without closing it

ibase_commit_ret

(PHP 5, PHP 7)

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.


Commit a transaction

  • « ibase_commit_ret
  • ibase_connect »
  • PHP Manual
  • Firebird/InterBase Functions
  • Commit a transaction

ibase_commit

(PHP 5, PHP 7)

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.


Open a connection to a database

  • « ibase_commit
  • ibase_db_info »
  • PHP Manual
  • Firebird/InterBase Functions
  • Open a connection to a database

ibase_connect

(PHP 5, PHP 7)

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


Request statistics about a database

  • « ibase_connect
  • ibase_delete_user »
  • PHP Manual
  • Firebird/InterBase Functions
  • Request statistics about a database

ibase_db_info

(PHP 5, PHP 7)

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.


Delete a user from a security database

  • « ibase_db_info
  • ibase_drop_db »
  • PHP Manual
  • Firebird/InterBase Functions
  • Delete a user from a security database

ibase_delete_user

(PHP 5, PHP 7)

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


Drops a database

  • « ibase_delete_user
  • ibase_errcode »
  • PHP Manual
  • Firebird/InterBase Functions
  • Drops a database

ibase_drop_db

(PHP 5, PHP 7)

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


Return an error code

  • « ibase_drop_db
  • ibase_errmsg »
  • PHP Manual
  • Firebird/InterBase Functions
  • Return an error code

ibase_errcode

(PHP 5, PHP 7)

ibase_errcode — Return an error code

Description

ibase_errcode ( void ) : int

Returns the error code that resulted from the most recent InterBase function call.

Return Values

Returns the error code as an integer, or FALSE if no error occurred.

See Also

  • ibase_errmsg() - Return error messages


Return error messages

  • « ibase_errcode
  • ibase_execute »
  • PHP Manual
  • Firebird/InterBase Functions
  • Return error messages

ibase_errmsg

(PHP 5, PHP 7)

ibase_errmsg — Return error messages

Description

ibase_errmsg ( void ) : string

Returns the error message that resulted from the most recent InterBase function call.

Return Values

Returns the error message as a string, or FALSE if no error occurred.

See Also

  • ibase_errcode() - Return an error code


Execute a previously prepared query

  • « ibase_errmsg
  • ibase_fetch_assoc »
  • PHP Manual
  • Firebird/InterBase Functions
  • Execute a previously prepared query

ibase_execute

(PHP 5, PHP 7)

ibase_execute — Execute a previously prepared query

Description

ibase_execute ( resource $query [, mixed $... ] ) : 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().

...

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


Fetch a result row from a query as an associative array

  • « ibase_execute
  • ibase_fetch_object »
  • PHP Manual
  • Firebird/InterBase Functions
  • Fetch a result row from a query as an associative array

ibase_fetch_assoc

(PHP 5, PHP 7)

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


Get an object from a InterBase database

  • « ibase_fetch_assoc
  • ibase_fetch_row »
  • PHP Manual
  • Firebird/InterBase Functions
  • Get an object from a InterBase database

ibase_fetch_object

(PHP 5, PHP 7)

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


Fetch a row from an InterBase database

  • « ibase_fetch_object
  • ibase_field_info »
  • PHP Manual
  • Firebird/InterBase Functions
  • Fetch a row from an InterBase database

ibase_fetch_row

(PHP 5, PHP 7)

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


Get information about a field

  • « ibase_fetch_row
  • ibase_free_event_handler »
  • PHP Manual
  • Firebird/InterBase Functions
  • Get information about a field

ibase_field_info

(PHP 5, PHP 7)

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


Cancels a registered event handler

  • « ibase_field_info
  • ibase_free_query »
  • PHP Manual
  • Firebird/InterBase Functions
  • Cancels a registered event handler

ibase_free_event_handler

(PHP 5, PHP 7)

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


Free memory allocated by a prepared query

  • « ibase_free_event_handler
  • ibase_free_result »
  • PHP Manual
  • Firebird/InterBase Functions
  • Free memory allocated by a prepared query

ibase_free_query

(PHP 5, PHP 7)

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.


Free a result set

  • « ibase_free_query
  • ibase_gen_id »
  • PHP Manual
  • Firebird/InterBase Functions
  • Free a result set

ibase_free_result

(PHP 5, PHP 7)

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.


Increments the named generator and returns its new value

  • « ibase_free_result
  • ibase_maintain_db »
  • PHP Manual
  • Firebird/InterBase Functions
  • Increments the named generator and returns its new value

ibase_gen_id

(PHP 5, PHP 7)

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.


Execute a maintenance command on the database server

  • « ibase_gen_id
  • ibase_modify_user »
  • PHP Manual
  • Firebird/InterBase Functions
  • Execute a maintenance command on the database server

ibase_maintain_db

(PHP 5, PHP 7)

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.


Modify a user to a security database

  • « ibase_maintain_db
  • ibase_name_result »
  • PHP Manual
  • Firebird/InterBase Functions
  • Modify a user to a security database

ibase_modify_user

(PHP 5, PHP 7)

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


Assigns a name to a result set

  • « ibase_modify_user
  • ibase_num_fields »
  • PHP Manual
  • Firebird/InterBase Functions
  • Assigns a name to a result set

ibase_name_result

(PHP 5, PHP 7)

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


Get the number of fields in a result set

  • « ibase_name_result
  • ibase_num_params »
  • PHP Manual
  • Firebird/InterBase Functions
  • Get the number of fields in a result set

ibase_num_fields

(PHP 5, PHP 7)

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


Return the number of parameters in a prepared query

  • « ibase_num_fields
  • ibase_param_info »
  • PHP Manual
  • Firebird/InterBase Functions
  • Return the number of parameters in a prepared query

ibase_num_params

(PHP 5, PHP 7)

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


Return information about a parameter in a prepared query

  • « ibase_num_params
  • ibase_pconnect »
  • PHP Manual
  • Firebird/InterBase Functions
  • Return information about a parameter in a prepared query

ibase_param_info

(PHP 5, PHP 7)

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


Open a persistent connection to an InterBase database

  • « ibase_param_info
  • ibase_prepare »
  • PHP Manual
  • Firebird/InterBase Functions
  • Open a persistent connection to an InterBase database

ibase_pconnect

(PHP 5, PHP 7)

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


Prepare a query for later binding of parameter placeholders and execution

  • « ibase_pconnect
  • ibase_query »
  • PHP Manual
  • Firebird/InterBase Functions
  • Prepare a query for later binding of parameter placeholders and execution

ibase_prepare

(PHP 5, PHP 7)

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.


Execute a query on an InterBase database

  • « ibase_prepare
  • ibase_restore »
  • PHP Manual
  • Firebird/InterBase Functions
  • Execute a query on an InterBase database

ibase_query

(PHP 5, PHP 7)

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

Changelog

Version | Description
5.3.1 | On success the function now returns TRUE if there were no affected rows, where it previously returned 0 (a zero followed by an empty space).

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


Initiates a restore task in the service manager and returns immediately

  • « ibase_query
  • ibase_rollback_ret »
  • PHP Manual
  • Firebird/InterBase Functions
  • Initiates a restore task in the service manager and returns immediately

ibase_restore

(PHP 5, PHP 7)

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


Roll back a transaction without closing it

  • « ibase_restore
  • ibase_rollback »
  • PHP Manual
  • Firebird/InterBase Functions
  • Roll back a transaction without closing it

ibase_rollback_ret

(PHP 5, PHP 7)

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.


Roll back a transaction

  • « ibase_rollback_ret
  • ibase_server_info »
  • PHP Manual
  • Firebird/InterBase Functions
  • Roll back a transaction

ibase_rollback

(PHP 5, PHP 7)

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.


Request information about a database server

  • « ibase_rollback
  • ibase_service_attach »
  • PHP Manual
  • Firebird/InterBase Functions
  • Request information about a database server

ibase_server_info

(PHP 5, PHP 7)

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
)


Connect to the service manager

  • « ibase_server_info
  • ibase_service_detach »
  • PHP Manual
  • Firebird/InterBase Functions
  • Connect to the service manager

ibase_service_attach

(PHP 5, PHP 7)

ibase_service_attach — Connect to the service manager

Description

ibase_service_attach ( string $host , string $dba_username , string $dba_password ) : resource

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


Disconnect from the service manager

  • « ibase_service_attach
  • ibase_set_event_handler »
  • PHP Manual
  • Firebird/InterBase Functions
  • Disconnect from the service manager

ibase_service_detach

(PHP 5, PHP 7)

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

?>


Register a callback function to be called when events are posted

  • « ibase_service_detach
  • ibase_trans »
  • PHP Manual
  • Firebird/InterBase Functions
  • Register a callback function to be called when events are posted

ibase_set_event_handler

(PHP 5, PHP 7)

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_name1 [, string $... ] ) : resource
ibase_set_event_handler ( resource $connection , callable $event_handler , string $event_name1 [, string $... ] ) : 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_name1

An event name.

...

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


Begin a transaction

  • « ibase_set_event_handler
  • ibase_wait_event »
  • PHP Manual
  • Firebird/InterBase Functions
  • Begin a transaction

ibase_trans

(PHP 5, PHP 7)

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.


Wait for an event to be posted by the database

  • « ibase_trans
  • FrontBase »
  • PHP Manual
  • Firebird/InterBase Functions
  • Wait for an event to be posted by the database

ibase_wait_event

(PHP 5, PHP 7)

ibase_wait_event — Wait for an event to be posted by the database

Description

ibase_wait_event ( string $event_name1 [, string $... ] ) : string
ibase_wait_event ( resource $connection , string $event_name1 [, string $... ] ) : 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_name1

The event name.

...

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


FrontBase

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • FrontBase Functions
    • fbsql_affected_rows — Get number of affected rows in previous FrontBase operation
    • fbsql_autocommit — Enable or disable autocommit
    • fbsql_blob_size — Get the size of a BLOB
    • fbsql_change_user — Change logged in user of the active connection
    • fbsql_clob_size — Get the size of a CLOB
    • fbsql_close — Close FrontBase connection
    • fbsql_commit — Commits a transaction to the database
    • fbsql_connect — Open a connection to a FrontBase Server
    • fbsql_create_blob — Create a BLOB
    • fbsql_create_clob — Create a CLOB
    • fbsql_create_db — Create a FrontBase database
    • fbsql_data_seek — Move internal result pointer
    • fbsql_database_password — Sets or retrieves the password for a FrontBase database
    • fbsql_database — Get or set the database name used with a connection
    • fbsql_db_query — Send a FrontBase query
    • fbsql_db_status — Get the status for a given database
    • fbsql_drop_db — Drop (delete) a FrontBase database
    • fbsql_errno — Returns the error number from previous operation
    • fbsql_error — Returns the error message from previous operation
    • fbsql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
    • fbsql_fetch_assoc — Fetch a result row as an associative array
    • fbsql_fetch_field — Get column information from a result and return as an object
    • fbsql_fetch_lengths — Get the length of each output in a result
    • fbsql_fetch_object — Fetch a result row as an object
    • fbsql_fetch_row — Get a result row as an enumerated array
    • fbsql_field_flags — Get the flags associated with the specified field in a result
    • fbsql_field_len — Returns the length of the specified field
    • fbsql_field_name — Get the name of the specified field in a result
    • fbsql_field_seek — Set result pointer to a specified field offset
    • fbsql_field_table — Get name of the table the specified field is in
    • fbsql_field_type — Get the type of the specified field in a result
    • fbsql_free_result — Free result memory
    • fbsql_get_autostart_info — Description
    • fbsql_hostname — Get or set the host name used with a connection
    • fbsql_insert_id — Get the id generated from the previous INSERT operation
    • fbsql_list_dbs — List databases available on a FrontBase server
    • fbsql_list_fields — List FrontBase result fields
    • fbsql_list_tables — List tables in a FrontBase database
    • fbsql_next_result — Move the internal result pointer to the next result
    • fbsql_num_fields — Get number of fields in result
    • fbsql_num_rows — Get number of rows in result
    • fbsql_password — Get or set the user password used with a connection
    • fbsql_pconnect — Open a persistent connection to a FrontBase Server
    • fbsql_query — Send a FrontBase query
    • fbsql_read_blob — Read a BLOB from the database
    • fbsql_read_clob — Read a CLOB from the database
    • fbsql_result — Get result data
    • fbsql_rollback — Rollback a transaction to the database
    • fbsql_rows_fetched — Get the number of rows affected by the last statement
    • fbsql_select_db — Select a FrontBase database
    • fbsql_set_characterset — Change input/output character set
    • fbsql_set_lob_mode — Set the LOB retrieve mode for a FrontBase result set
    • fbsql_set_password — Change the password for a given user
    • fbsql_set_transaction — Set the transaction locking and isolation
    • fbsql_start_db — Start a database on local or remote server
    • fbsql_stop_db — Stop a database on local or remote server
    • fbsql_table_name — Get table name of field
    • fbsql_tablename — Alias of fbsql_table_name
    • fbsql_username — Get or set the username for the connection
    • fbsql_warnings — Enable or disable FrontBase warnings


Introduction

These functions allow you to access FrontBase database servers. More information about FrontBase can be found at » http://www.frontbase.com/.

Documentation for FrontBase can be found at » http://www.frontbase.com/cgi-bin/WebObjects/FBWebSite.woa.

Note:

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.3.0.


Requirements

You must install the FrontBase database server or at least the fbsql client libraries to use this functions. You can get FrontBase from » http://www.frontbase.com/.


Installation

In order to have these functions available, you must compile PHP with fbsql support by using the --with-fbsql[=DIR] option. If you use this option without specifying the path to fbsql, PHP will search for the fbsql client libraries in the default installation location for the platform. Users who installed FrontBase in a non standard directory should always specify the path to fbsql: --with-fbsql=/path/to/fbsql . This will force PHP to use the client libraries installed by FrontBase, avoiding any conflicts.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

FrontBase configuration options
Name | Default | Changeable | Changelog
fbsql.allow_persistent | "1" | PHP_INI_SYSTEM |
fbsql.generate_warnings | "0" | PHP_INI_SYSTEM |
fbsql.autocommit | "1" | PHP_INI_SYSTEM |
fbsql.max_persistent | "-1" | PHP_INI_SYSTEM |
fbsql.max_links | "128" | PHP_INI_SYSTEM |
fbsql.max_connections | "128" | PHP_INI_SYSTEM |
fbsql.max_results | "128" | PHP_INI_SYSTEM |
fbsql.batchSize | "1000" | PHP_INI_SYSTEM | Removed in PHP 5.1.0.
fbsql.default_host | NULL | PHP_INI_SYSTEM |
fbsql.default_user | "_SYSTEM" | PHP_INI_SYSTEM |
fbsql.default_password | "" | PHP_INI_SYSTEM |
fbsql.default_database | "" | PHP_INI_SYSTEM |
fbsql.default_database_password | "" | PHP_INI_SYSTEM |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be 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.

FBSQL_ASSOC (integer)
FBSQL_NUM (integer)
FBSQL_BOTH (integer)
FBSQL_LOCK_DEFERRED (integer)
FBSQL_LOCK_OPTIMISTIC (integer)
FBSQL_LOCK_PESSIMISTIC (integer)
FBSQL_ISO_READ_UNCOMMITTED (integer)
FBSQL_ISO_READ_COMMITTED (integer)
FBSQL_ISO_REPEATABLE_READ (integer)
FBSQL_ISO_SERIALIZABLE (integer)
FBSQL_ISO_VERSIONED (integer)
FBSQL_UNKNOWN (integer)
FBSQL_STOPPED (integer)
FBSQL_STARTING (integer)
FBSQL_RUNNING (integer)
FBSQL_STOPPING (integer)
FBSQL_NOEXEC (integer)
FBSQL_LOB_DIRECT (integer)
FBSQL_LOB_HANDLE (integer)


FrontBase Functions

Table of Contents

  • fbsql_affected_rows — Get number of affected rows in previous FrontBase operation
  • fbsql_autocommit — Enable or disable autocommit
  • fbsql_blob_size — Get the size of a BLOB
  • fbsql_change_user — Change logged in user of the active connection
  • fbsql_clob_size — Get the size of a CLOB
  • fbsql_close — Close FrontBase connection
  • fbsql_commit — Commits a transaction to the database
  • fbsql_connect — Open a connection to a FrontBase Server
  • fbsql_create_blob — Create a BLOB
  • fbsql_create_clob — Create a CLOB
  • fbsql_create_db — Create a FrontBase database
  • fbsql_data_seek — Move internal result pointer
  • fbsql_database_password — Sets or retrieves the password for a FrontBase database
  • fbsql_database — Get or set the database name used with a connection
  • fbsql_db_query — Send a FrontBase query
  • fbsql_db_status — Get the status for a given database
  • fbsql_drop_db — Drop (delete) a FrontBase database
  • fbsql_errno — Returns the error number from previous operation
  • fbsql_error — Returns the error message from previous operation
  • fbsql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
  • fbsql_fetch_assoc — Fetch a result row as an associative array
  • fbsql_fetch_field — Get column information from a result and return as an object
  • fbsql_fetch_lengths — Get the length of each output in a result
  • fbsql_fetch_object — Fetch a result row as an object
  • fbsql_fetch_row — Get a result row as an enumerated array
  • fbsql_field_flags — Get the flags associated with the specified field in a result
  • fbsql_field_len — Returns the length of the specified field
  • fbsql_field_name — Get the name of the specified field in a result
  • fbsql_field_seek — Set result pointer to a specified field offset
  • fbsql_field_table — Get name of the table the specified field is in
  • fbsql_field_type — Get the type of the specified field in a result
  • fbsql_free_result — Free result memory
  • fbsql_get_autostart_info — Description
  • fbsql_hostname — Get or set the host name used with a connection
  • fbsql_insert_id — Get the id generated from the previous INSERT operation
  • fbsql_list_dbs — List databases available on a FrontBase server
  • fbsql_list_fields — List FrontBase result fields
  • fbsql_list_tables — List tables in a FrontBase database
  • fbsql_next_result — Move the internal result pointer to the next result
  • fbsql_num_fields — Get number of fields in result
  • fbsql_num_rows — Get number of rows in result
  • fbsql_password — Get or set the user password used with a connection
  • fbsql_pconnect — Open a persistent connection to a FrontBase Server
  • fbsql_query — Send a FrontBase query
  • fbsql_read_blob — Read a BLOB from the database
  • fbsql_read_clob — Read a CLOB from the database
  • fbsql_result — Get result data
  • fbsql_rollback — Rollback a transaction to the database
  • fbsql_rows_fetched — Get the number of rows affected by the last statement
  • fbsql_select_db — Select a FrontBase database
  • fbsql_set_characterset — Change input/output character set
  • fbsql_set_lob_mode — Set the LOB retrieve mode for a FrontBase result set
  • fbsql_set_password — Change the password for a given user
  • fbsql_set_transaction — Set the transaction locking and isolation
  • fbsql_start_db — Start a database on local or remote server
  • fbsql_stop_db — Stop a database on local or remote server
  • fbsql_table_name — Get table name of field
  • fbsql_tablename — Alias of fbsql_table_name
  • fbsql_username — Get or set the username for the connection
  • fbsql_warnings — Enable or disable FrontBase warnings


Get number of affected rows in previous FrontBase operation

  • « FrontBase Functions
  • fbsql_autocommit »
  • PHP Manual
  • FrontBase Functions
  • Get number of affected rows in previous FrontBase operation

fbsql_affected_rows

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_affected_rows — Get number of affected rows in previous FrontBase operation

Description

fbsql_affected_rows ([ resource $link_identifier ] ) : int

fbsql_affected_rows() returns the number of rows affected by the last INSERT, UPDATE or DELETE query associated with link_identifier.

Note:

If you are using transactions, you need to call fbsql_affected_rows() after your INSERT, UPDATE, or DELETE query, not after the commit.

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.

Note:

When using UPDATE, FrontBase will not update columns where the new value is the same as the old value. This creates the possibility that fbsql_affected_rows() may not actually equal the number of rows matched, only the number of rows that were literally affected by the query.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

If the last query failed, this function will return -1.

See Also

  • fbsql_num_rows() - Get number of rows in result


Enable or disable autocommit

  • « fbsql_affected_rows
  • fbsql_blob_size »
  • PHP Manual
  • FrontBase Functions
  • Enable or disable autocommit

fbsql_autocommit

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_autocommit — Enable or disable autocommit

Description

fbsql_autocommit ( resource $link_identifier [, bool $OnOff ] ) : bool

Returns the current autocommit status.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

OnOff

If this optional parameter is given the auto commit status will be changed.

With OnOff set to TRUE each statement will be committed automatically, if no errors was found.

With OnOff set to FALSE the user must commit or rollback the transaction using either fbsql_commit() or fbsql_rollback().

Return Values

Returns the current autocommit status, as a boolean.

See Also

  • fbsql_commit() - Commits a transaction to the database
  • fbsql_rollback() - Rollback a transaction to the database


Get the size of a BLOB

  • « fbsql_autocommit
  • fbsql_change_user »
  • PHP Manual
  • FrontBase Functions
  • Get the size of a BLOB

fbsql_blob_size

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

fbsql_blob_size — Get the size of a BLOB

Description

fbsql_blob_size ( string $blob_handle [, resource $link_identifier ] ) : int

Returns the size of the given BLOB.

Parameters

blob_handle

A BLOB handle, returned by fbsql_create_blob().

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns the BLOB size as an integer, or FALSE on error.

See Also

  • fbsql_clob_size() - Get the size of a CLOB


Change logged in user of the active connection

  • « fbsql_blob_size
  • fbsql_clob_size »
  • PHP Manual
  • FrontBase Functions
  • Change logged in user of the active connection

fbsql_change_user

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_change_user — Change logged in user of the active connection

Description

fbsql_change_user ( string $user , string $password [, string $database [, resource $link_identifier ]] ) : bool

fbsql_change_user() changes the logged in user of the specified connection. If the new user and password authorization fails, the current connected user stays active.

Parameters

user

The new user name.

password

The new user password.

database

If specified, this will be the default or current database after the user has been changed.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns TRUE on success or FALSE on failure.


Get the size of a CLOB

  • « fbsql_change_user
  • fbsql_close »
  • PHP Manual
  • FrontBase Functions
  • Get the size of a CLOB

fbsql_clob_size

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

fbsql_clob_size — Get the size of a CLOB

Description

fbsql_clob_size ( string $clob_handle [, resource $link_identifier ] ) : int

Returns the size of the given CLOB.

Parameters

clob_handle

A CLOB handle, returned by fbsql_create_clob().

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns the CLOB size as an integer, or FALSE on error.

See Also

  • fbsql_blob_size() - Get the size of a BLOB


Close FrontBase connection

  • « fbsql_clob_size
  • fbsql_commit »
  • PHP Manual
  • FrontBase Functions
  • Close FrontBase connection

fbsql_close

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_close — Close FrontBase connection

Description

fbsql_close ([ resource $link_identifier ] ) : bool

Closes the connection to the FrontBase server that's associated with the specified link identifier.

Using fbsql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 fbsql_close() example

<?php
$link = fbsql_connect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
echo "Connected successfully";
fbsql_close($link);
?>

See Also

  • fbsql_connect() - Open a connection to a FrontBase Server
  • fbsql_pconnect() - Open a persistent connection to a FrontBase Server


Commits a transaction to the database

  • « fbsql_close
  • fbsql_connect »
  • PHP Manual
  • FrontBase Functions
  • Commits a transaction to the database

fbsql_commit

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_commit — Commits a transaction to the database

Description

fbsql_commit ([ resource $link_identifier ] ) : bool

Ends the current transaction by writing all inserts, updates and deletes to the disk and unlocking all row and table locks held by the transaction. This command is only needed if autocommit is set to false.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fbsql_autocommit() - Enable or disable autocommit
  • fbsql_rollback() - Rollback a transaction to the database


Open a connection to a FrontBase Server

  • « fbsql_commit
  • fbsql_create_blob »
  • PHP Manual
  • FrontBase Functions
  • Open a connection to a FrontBase Server

fbsql_connect

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_connect — Open a connection to a FrontBase Server

Description

 fbsql_connect
  ([ string $hostname = ini_get("fbsql.default_host")
 [, string $username = ini_get("fbsql.default_user")
 [, string $password = ini_get("fbsql.default_password")
]]] ) : resource

fbsql_connect() establishes a connection to a FrontBase server.

If a second call is made to fbsql_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 fbsql_close().

Parameters

hostname

The server host name.

username

The user name for the connection.

password

The password for the connection.

Return Values

Returns a positive FrontBase link identifier on success, or FALSE on errors.

Examples

Example #1 fbsql_connect() example

<?php

$link = fbsql_connect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
echo "Connected successfully";
fbsql_close($link);

?>

See Also

  • fbsql_pconnect() - Open a persistent connection to a FrontBase Server
  • fbsql_close() - Close FrontBase connection


Create a BLOB

  • « fbsql_connect
  • fbsql_create_clob »
  • PHP Manual
  • FrontBase Functions
  • Create a BLOB

fbsql_create_blob

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

fbsql_create_blob — Create a BLOB

Description

fbsql_create_blob ( string $blob_data [, resource $link_identifier ] ) : string

Creates a BLOB from the given data.

Parameters

blob_data

The BLOB data.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns a resource handle to the newly created BLOB, which can be used with insert and update commands to store the BLOB in the database.

Examples

Example #1 fbsql_create_blob() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
$filename = "blobfile.bin";
$fp = fopen($filename, "rb");
$blobdata = fread($fp, filesize($filename));
fclose($fp);

$blobHandle = fbsql_create_blob($blobdata, $link);

$sql = "INSERT INTO BLOB_TABLE (BLOB_COLUMN) VALUES ($blobHandle);";
$rs = fbsql_query($sql, $link);
?>

See Also

  • fbsql_create_clob() - Create a CLOB
  • fbsql_read_blob() - Read a BLOB from the database
  • fbsql_read_clob() - Read a CLOB from the database
  • fbsql_set_lob_mode() - Set the LOB retrieve mode for a FrontBase result set


Create a CLOB

  • « fbsql_create_blob
  • fbsql_create_db »
  • PHP Manual
  • FrontBase Functions
  • Create a CLOB

fbsql_create_clob

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

fbsql_create_clob — Create a CLOB

Description

fbsql_create_clob ( string $clob_data [, resource $link_identifier ] ) : string

Creates a CLOB from the given data.

Parameters

clob_data

The CLOB data.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns a resource handle to the newly created CLOB, which can be used with insert and update commands to store the CLOB in the database.

Examples

Example #1 fbsql_create_clob() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
$filename = "clob_file.txt";
$fp = fopen($filename, "rb");
$clobdata = fread($fp, filesize($filename));
fclose($fp);

$clobHandle = fbsql_create_clob($clobdata, $link);

$sql = "INSERT INTO CLOB_TABLE (CLOB_COLUMN) VALUES ($clobHandle);";
$rs = fbsql_query($sql, $link);
?>

See Also

  • fbsql_create_blob() - Create a BLOB
  • fbsql_read_blob() - Read a BLOB from the database
  • fbsql_read_clob() - Read a CLOB from the database
  • fbsql_set_lob_mode() - Set the LOB retrieve mode for a FrontBase result set


Create a FrontBase database

  • « fbsql_create_clob
  • fbsql_data_seek »
  • PHP Manual
  • FrontBase Functions
  • Create a FrontBase database

fbsql_create_db

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_create_db — Create a FrontBase database

Description

fbsql_create_db ( string $database_name [, resource $link_identifier [, string $database_options ]] ) : bool

Attempts to create a new database on the specified server.

Parameters

database_name

The database name, as a string.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

database_options

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 fbsql_create_db() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
if (fbsql_create_db("my_db")) {
    echo "Database created successfully\n";
} else {
    printf("Error creating database: %s\n", fbsql_error());
}
?>

See Also

  • fbsql_drop_db() - Drop (delete) a FrontBase database


Move internal result pointer

  • « fbsql_create_db
  • fbsql_database_password »
  • PHP Manual
  • FrontBase Functions
  • Move internal result pointer

fbsql_data_seek

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_data_seek — Move internal result pointer

Description

fbsql_data_seek ( resource $result , int $row_number ) : bool

Moves the internal row pointer of the FrontBase result associated with the specified result identifier to point to the specified row number.

The next call to fbsql_fetch_row() would return that row.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

row_number

The row number. Starts at 0.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 fbsql_data_seek() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");

fbsql_select_db("samp_db")
    or die("Could not select database");

$query = "SELECT last_name, first_name FROM friends;";
$result = fbsql_query($query)
    or die("Query failed");

// fetch rows in reverse order

for ($i = fbsql_num_rows($result) - 1; $i >=0; $i--) {
    if (!fbsql_data_seek($result, $i)) {
        printf("Cannot seek to row %d\n", $i);
        continue;
    }

    if (!($row = fbsql_fetch_object($result)))
        continue;

    echo $row->last_name . $row->first_name . "<br />\n";
}

fbsql_free_result($result);
?>


Sets or retrieves the password for a FrontBase database

  • « fbsql_data_seek
  • fbsql_database »
  • PHP Manual
  • FrontBase Functions
  • Sets or retrieves the password for a FrontBase database

fbsql_database_password

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_database_password — Sets or retrieves the password for a FrontBase database

Description

fbsql_database_password ( resource $link_identifier [, string $database_password ] ) : string

Sets and retrieves the database password used by the connection. If a database is protected by a database password, the user must call this function before calling fbsql_select_db().

If no link is open, the function will try to establish a link as if fbsql_connect() was called, and use it.

This function does not change the database password in the database nor can it be used to retrieve the database password for a database.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

database_password

The database password, as a string. If given, the function sets the database password for the specified link identifier.

Return Values

Returns the database password associated with the link identifier.

Examples

Example #1 fbsql_create_clob() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
fbsql_database_password($link, "secret db password");
fbsql_select_db($database, $link);
?>

See Also

  • fbsql_connect() - Open a connection to a FrontBase Server
  • fbsql_pconnect() - Open a persistent connection to a FrontBase Server
  • fbsql_select_db() - Select a FrontBase database


Get or set the database name used with a connection

  • « fbsql_database_password
  • fbsql_db_query »
  • PHP Manual
  • FrontBase Functions
  • Get or set the database name used with a connection

fbsql_database

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_database — Get or set the database name used with a connection

Description

fbsql_database ( resource $link_identifier [, string $database ] ) : string

Get or set the database name used with the connection.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

database

The database name. If given, the default database of the connexion will be changed to database.

Return Values

Returns the name of the database used with this connection.


Send a FrontBase query

  • « fbsql_database
  • fbsql_db_status »
  • PHP Manual
  • FrontBase Functions
  • Send a FrontBase query

fbsql_db_query

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_db_query — Send a FrontBase query

Description

fbsql_db_query ( string $database , string $query [, resource $link_identifier ] ) : resource

Selects a database and executes a query on it.

Parameters

database

The database to be selected.

query

The SQL query to be executed.

Note:

The query string shall always end with a semicolon.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns a positive FrontBase result identifier to the query result, or FALSE on error.

See Also

  • fbsql_query() - Send a FrontBase query
  • fbsql_connect() - Open a connection to a FrontBase Server


Get the status for a given database

  • « fbsql_db_query
  • fbsql_drop_db »
  • PHP Manual
  • FrontBase Functions
  • Get the status for a given database

fbsql_db_status

(PHP 4 >= 4.0.7, PHP 5, PHP 7)

fbsql_db_status — Get the status for a given database

Description

fbsql_db_status ( string $database_name [, resource $link_identifier ] ) : int

Gets the current status of the specified database.

Parameters

database_name

The database name.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns an integer value with the current status. This can be one of the following constants:

  • FALSE - The exec handler for the host was invalid. This error will occur when the link_identifier connects directly to a database by using a port number. FBExec can be available on the server but no connection has been made for it.
  • FBSQL_UNKNOWN - The Status is unknown.
  • FBSQL_STOPPED - The database is not running. Use fbsql_start_db() to start the database.
  • FBSQL_STARTING - The database is starting.
  • FBSQL_RUNNING - The database is running and can be used to perform SQL operations.
  • FBSQL_STOPPING - The database is stopping.
  • FBSQL_NOEXEC - FBExec is not running on the server and it is not possible to get the status of the database.

See Also

  • fbsql_start_db() - Start a database on local or remote server
  • fbsql_stop_db() - Stop a database on local or remote server


Drop (delete) a FrontBase database

  • « fbsql_db_status
  • fbsql_errno »
  • PHP Manual
  • FrontBase Functions
  • Drop (delete) a FrontBase database

fbsql_drop_db

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_drop_db — Drop (delete) a FrontBase database

Description

fbsql_drop_db ( string $database_name [, resource $link_identifier ] ) : bool

fbsql_drop_db() attempts to drop (remove) an entire database from the server associated with the specified link identifier.

Parameters

database_name

The database name, as a string.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fbsql_create_db() - Create a FrontBase database


Returns the error number from previous operation

  • « fbsql_drop_db
  • fbsql_error »
  • PHP Manual
  • FrontBase Functions
  • Returns the error number from previous operation

fbsql_errno

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_errno — Returns the error number from previous operation

Description

fbsql_errno ([ resource $link_identifier ] ) : int

Returns the numerical value of the error message from previous FrontBase operation.

Errors coming back from the fbsql database backend don't issue warnings. Instead, use fbsql_errno() to retrieve the error code. Note that this function only returns the error code from the most recently executed fbsql function (not including fbsql_error() and fbsql_errno()), so if you want to use it, make sure you check the value before calling another fbsql function.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns the error number from the last fbsql function, or 0 (zero) if no error occurred.

Examples

Example #1 fbsql_errno() Example

<?php
fbsql_connect("marliesle");
echo fbsql_errno() . ": " . fbsql_error() . "<br />";
fbsql_select_db("nonexistentdb");
echo fbsql_errno() . ": " . fbsql_error() . "<br />";
$conn = fbsql_query("SELECT * FROM nonexistenttable;");
echo fbsql_errno() . ": " . fbsql_error() . "<br />";
?>

See Also

  • fbsql_error() - Returns the error message from previous operation
  • fbsql_warnings() - Enable or disable FrontBase warnings


Returns the error message from previous operation

  • « fbsql_errno
  • fbsql_fetch_array »
  • PHP Manual
  • FrontBase Functions
  • Returns the error message from previous operation

fbsql_error

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_error — Returns the error message from previous operation

Description

fbsql_error ([ resource $link_identifier ] ) : string

Returns the error message from previous FrontBase operation.

Errors coming back from the fbsql database backend don't issue warnings. Instead, use fbsql_error() to retrieve the error text. Note that this function only returns the error code from the most recently executed fbsql function (not including fbsql_error() and fbsql_errno()), so if you want to use it, make sure you check the value before calling another fbsql function.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns the error text from the last fbsql function, or '' (the empty string) if no error occurred.

Examples

Example #1 fbsql_error() Example

<?php
fbsql_connect("marliesle");
echo fbsql_errno() . ": " . fbsql_error() . "<br />";
fbsql_select_db("nonexistentdb");
echo fbsql_errno() . ": " . fbsql_error() . "<br />";
$conn = fbsql_query("SELECT * FROM nonexistenttable;");
echo fbsql_errno() . ": " . fbsql_error() . "<br />";
?>

See Also

  • fbsql_errno() - Returns the error number from previous operation
  • fbsql_warnings() - Enable or disable FrontBase warnings


Fetch a result row as an associative array, a numeric array, or both

  • « fbsql_error
  • fbsql_fetch_assoc »
  • PHP Manual
  • FrontBase Functions
  • Fetch a result row as an associative array, a numeric array, or both

fbsql_fetch_array

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_fetch_array — Fetch a result row as an associative array, a numeric array, or both

Description

fbsql_fetch_array ( resource $result [, int $result_type ] ) : array

fbsql_fetch_array() is a combination of
fbsql_fetch_row() and
fbsql_fetch_assoc().

An important thing to note is that using fbsql_fetch_array() is NOT significantly slower than using fbsql_fetch_row(), while it provides a significant added value.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

result_type

A constant and can take the following values: FBSQL_ASSOC, FBSQL_NUM, or FBSQL_BOTH.

When using FBSQL_BOTH, in addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

Return Values

Returns an array 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 must the numeric index of the column or make an alias for the column.

select t1.f1 as foo t2.f1 as bar from t1, t2

Examples

Example #1 fbsql_fetch_array() example

<?php
fbsql_connect($host, $user, $password);
$result = fbsql_db_query("database", "select user_id, fullname from table");
while ($row = fbsql_fetch_array($result)) {
    echo "user_id: " . $row["user_id"] . "<br />\n";
    echo "user_id: " . $row[0] . "<br />\n";
    echo "fullname: " . $row["fullname"] . "<br />\n";
    echo "fullname: " . $row[1] . "<br />\n";
}
fbsql_free_result($result);
?>

See Also

  • fbsql_fetch_row() - Get a result row as an enumerated array
  • fbsql_fetch_assoc() - Fetch a result row as an associative array
  • fbsql_fetch_object() - Fetch a result row as an object


Fetch a result row as an associative array

  • « fbsql_fetch_array
  • fbsql_fetch_field »
  • PHP Manual
  • FrontBase Functions
  • Fetch a result row as an associative array

fbsql_fetch_assoc

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_fetch_assoc — Fetch a result row as an associative array

Description

fbsql_fetch_assoc ( resource $result ) : array

Calling fbsql_fetch_assoc() is equivalent to calling fbsql_fetch_array() with FBSQL_ASSOC as second parameter. It only returns an associative array.

This is the way fbsql_fetch_array() originally worked. If you need the numeric indices as well as the associative, use fbsql_fetch_array().

An important thing to note is that using fbsql_fetch_assoc() is NOT significantly slower than using fbsql_fetch_row(), while it provides a significant added value.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

Return Values

Returns an associative array 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 must use fbsql_fetch_array() and have it return the numeric indices as well.

Examples

Example #1 fbsql_fetch_assoc() example

<?php
fbsql_connect($host, $user, $password);
$result = fbsql_db_query("database", "select * from table");
while ($row = fbsql_fetch_assoc($result)) {
    echo $row["user_id"];
    echo $row["fullname"];
}
fbsql_free_result($result);
?>

See Also

  • fbsql_fetch_row() - Get a result row as an enumerated array
  • fbsql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • fbsql_fetch_object() - Fetch a result row as an object


Get column information from a result and return as an object

  • « fbsql_fetch_assoc
  • fbsql_fetch_lengths »
  • PHP Manual
  • FrontBase Functions
  • Get column information from a result and return as an object

fbsql_fetch_field

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_fetch_field — Get column information from a result and return as an object

Description

fbsql_fetch_field ( resource $result [, int $field_offset ] ) : object

Used in order to obtain information about fields in a certain query result.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

field_offset

The numerical offset of the field. The field index starts at 0. If not specified, the next field that wasn't yet retrieved by fbsql_fetch_field() is retrieved.

Return Values

Returns an object containing field information, or FALSE on errors.

The properties of the object are:

  • name - column name
  • table - name of the table the column belongs to
  • max_length - maximum length of the column
  • not_null - 1 if the column cannot be NULL
  • type - the type of the column

Examples

Example #1 fbsql_fetch_field() example

<?php
fbsql_connect($host, $user, $password)
    or die("Could not connect");
$result = fbsql_db_query("database", "select * from table")
    or die("Query failed");
# get column metadata
$i = 0;
while ($i < fbsql_num_fields($result)) {
    echo "Information for column $i:<br />\n";
    $meta = fbsql_fetch_field($result);
    if (!$meta) {
        echo "No information available<br />\n";
    }
    echo "<pre>
max_length:   $meta->max_length
name:         $meta->name
not_null:     $meta->not_null
table:        $meta->table
type:         $meta->type
</pre>";
    $i++;
}
fbsql_free_result($result);
?>

See Also

  • fbsql_field_seek() - Set result pointer to a specified field offset


Get the length of each output in a result

  • « fbsql_fetch_field
  • fbsql_fetch_object »
  • PHP Manual
  • FrontBase Functions
  • Get the length of each output in a result

fbsql_fetch_lengths

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_fetch_lengths — Get the length of each output in a result

Description

fbsql_fetch_lengths ( resource $result ) : array

Stores the lengths of each result column in the last row returned by
fbsql_fetch_row(),
fbsql_fetch_array() and
fbsql_fetch_object() in an array.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

Return Values

Returns an array, starting at offset 0, that corresponds to the lengths of each field in the last row fetched by fbsql_fetch_row(), or FALSE on error.

See Also

  • fbsql_fetch_row() - Get a result row as an enumerated array


Fetch a result row as an object

  • « fbsql_fetch_lengths
  • fbsql_fetch_row »
  • PHP Manual
  • FrontBase Functions
  • Fetch a result row as an object

fbsql_fetch_object

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_fetch_object — Fetch a result row as an object

Description

fbsql_fetch_object ( resource $result ) : object

fbsql_fetch_object() is similar to fbsql_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).

Speed-wise, the function is identical to fbsql_fetch_array(), and almost as quick as fbsql_fetch_row() (the difference is insignificant).

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

Return Values

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

Examples

Example #1 fbsql_fetch_object() example

<?php
fbsql_connect($host, $user, $password);
$result = fbsql_db_query("database", "select * from table");
while ($row = fbsql_fetch_object($result)) {
    echo $row->user_id;
    echo $row->fullname;
}
fbsql_free_result($result);
?>

See Also

  • fbsql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • fbsql_fetch_row() - Get a result row as an enumerated array
  • fbsql_fetch_assoc() - Fetch a result row as an associative array


Get a result row as an enumerated array

  • « fbsql_fetch_object
  • fbsql_field_flags »
  • PHP Manual
  • FrontBase Functions
  • Get a result row as an enumerated array

fbsql_fetch_row

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_fetch_row — Get a result row as an enumerated array

Description

fbsql_fetch_row ( resource $result ) : array

fbsql_fetch_row() fetches one row of data from the result associated with the specified result identifier.

Subsequent call to fbsql_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

Return Values

Returns an array that corresponds to the fetched row where each result column is stored in an offset, starting at offset 0, or FALSE if there are no more rows.

See Also

  • fbsql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • fbsql_fetch_assoc() - Fetch a result row as an associative array
  • fbsql_fetch_object() - Fetch a result row as an object
  • fbsql_data_seek() - Move internal result pointer
  • fbsql_fetch_lengths() - Get the length of each output in a result
  • fbsql_result() - Get result data


Get the flags associated with the specified field in a result

  • « fbsql_fetch_row
  • fbsql_field_len »
  • PHP Manual
  • FrontBase Functions
  • Get the flags associated with the specified field in a result

fbsql_field_flags

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_field_flags — Get the flags associated with the specified field in a result

Description

fbsql_field_flags ( resource $result [, int $field_offset ] ) : string

Gets the flags associated with the specified field in a result.

Parameters

result

A result pointer returned by fbsql_list_fields().

field_offset

The numerical offset of the field. The field index starts at 0.

Return Values

Returns the field flags of the specified field as a single word per flag separated by a single space, so that you can split the returned value using explode().


Returns the length of the specified field

  • « fbsql_field_flags
  • fbsql_field_name »
  • PHP Manual
  • FrontBase Functions
  • Returns the length of the specified field

fbsql_field_len

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_field_len — Returns the length of the specified field

Description

fbsql_field_len ( resource $result [, int $field_offset ] ) : int

Returns the length of the specified field.

Parameters

result

A result pointer returned by fbsql_list_fields().

field_offset

The numerical offset of the field. The field index starts at 0.

Return Values

Returns the length of the specified field.


Get the name of the specified field in a result

  • « fbsql_field_len
  • fbsql_field_seek »
  • PHP Manual
  • FrontBase Functions
  • Get the name of the specified field in a result

fbsql_field_name

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_field_name — Get the name of the specified field in a result

Description

fbsql_field_name ( resource $result [, int $field_index ] ) : string

Returns the name of the specified field index.

Parameters

result

A result pointer returned by fbsql_list_fields().

field_index

The numerical offset of the field. The field index starts at 0.

Return Values

Returns the name as a string, or FALSE if the field doesn't exist.

Examples

Example #1 fbsql_field_name() example

<?php
// The users table consists of three fields:
//   user_id
//   username
//   password.

$res = fbsql_db_query("users", "select * from users", $link);

echo fbsql_field_name($res, 0) . "\n";
echo fbsql_field_name($res, 2);
?>

The above example will output:

user_id
password

See Also

  • fbsql_field_type() - Get the type of the specified field in a result


Set result pointer to a specified field offset

  • « fbsql_field_name
  • fbsql_field_table »
  • PHP Manual
  • FrontBase Functions
  • Set result pointer to a specified field offset

fbsql_field_seek

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_field_seek — Set result pointer to a specified field offset

Description

fbsql_field_seek ( resource $result [, int $field_offset ] ) : bool

Seeks to the specified field offset. If the next call to fbsql_fetch_field() doesn't include a field offset, the field offset specified in fbsql_field_seek() will be returned.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

field_offset

The numerical offset of the field. The field index starts at 0.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fbsql_fetch_field() - Get column information from a result and return as an object


Get name of the table the specified field is in

  • « fbsql_field_seek
  • fbsql_field_type »
  • PHP Manual
  • FrontBase Functions
  • Get name of the table the specified field is in

fbsql_field_table

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_field_table — Get name of the table the specified field is in

Description

fbsql_field_table ( resource $result [, int $field_offset ] ) : string

Returns the name of the table that the specified field is in.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

field_offset

The numerical offset of the field. The field index starts at 0.

Return Values

Returns the name of the table, as a string.


Get the type of the specified field in a result

  • « fbsql_field_table
  • fbsql_free_result »
  • PHP Manual
  • FrontBase Functions
  • Get the type of the specified field in a result

fbsql_field_type

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_field_type — Get the type of the specified field in a result

Description

fbsql_field_type ( resource $result [, int $field_offset ] ) : string

fbsql_field_type() is similar to the fbsql_field_name() function, but the field type is returned instead.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

field_offset

The numerical offset of the field. The field index starts at 0.

Return Values

Returns the field type, as a string.

This can be one of int, real, string, blob, and others as detailed in the » FrontBase documentation.

Examples

Example #1 fbsql_field_type() example

<?php

fbsql_connect("localhost", "_SYSTEM", "");
fbsql_select_db("wisconsin");
$result = fbsql_query("SELECT * FROM onek;");
$fields = fbsql_num_fields($result);
$rows   = fbsql_num_rows($result);
$i = 0;
$table = fbsql_field_table($result, $i);
echo "Your '" . $table . "' table has " . $fields . " fields and " . $rows . " records <br />";
echo "The table has the following fields <br />";
while ($i < $fields) {
    $type  = fbsql_field_type($result, $i);
    $name  = fbsql_field_name($result, $i);
    $len   = fbsql_field_len($result, $i);
    $flags = fbsql_field_flags($result, $i);
    echo $type . " " . $name . " " . $len . " " . $flags . "<br />";
    $i++;
}
fbsql_close();

?>

See Also

  • fbsql_field_name() - Get the name of the specified field in a result


Free result memory

  • « fbsql_field_type
  • fbsql_get_autostart_info »
  • PHP Manual
  • FrontBase Functions
  • Free result memory

fbsql_free_result

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_free_result — Free result memory

Description

fbsql_free_result ( resource $result ) : bool

Frees all memory associated with the given result identifier.

fbsql_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

A result identifier returned by fbsql_query() or fbsql_db_query().

Return Values

Returns TRUE on success or FALSE on failure.


Description

  • « fbsql_free_result
  • fbsql_hostname »
  • PHP Manual
  • FrontBase Functions
  • Description

fbsql_get_autostart_info

(PHP 4 >= 4.0.7, PHP 5, PHP 7)

fbsql_get_autostart_info —

Description

fbsql_get_autostart_info ([ resource $link_identifier ] ) : array
Warning

This function is currently not documented; only its argument list is available.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.


Get or set the host name used with a connection

  • « fbsql_get_autostart_info
  • fbsql_insert_id »
  • PHP Manual
  • FrontBase Functions
  • Get or set the host name used with a connection

fbsql_hostname

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_hostname — Get or set the host name used with a connection

Description

fbsql_hostname ( resource $link_identifier [, string $host_name ] ) : string

Gets or sets the host name used with a connection.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

host_name

If provided, this will be the new connection host name.

Return Values

Returns the current host name used for the connection.

See Also

  • fbsql_username() - Get or set the username for the connection
  • fbsql_password() - Get or set the user password used with a connection


Get the id generated from the previous INSERT operation

  • « fbsql_hostname
  • fbsql_list_dbs »
  • PHP Manual
  • FrontBase Functions
  • Get the id generated from the previous INSERT operation

fbsql_insert_id

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_insert_id — Get the id generated from the previous INSERT operation

Description

fbsql_insert_id ([ resource $link_identifier ] ) : int

Gets the id generated from the previous INSERT operation which created a DEFAULT UNIQUE value.

Note:

The value of the FrontBase SQL function fbsql_insert_id() always contains the most recently generated DEFAULT UNIQUE value, and is not reset between queries.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns the ID generated from the previous INSERT query, or 0 if the previous query does not generate an DEFAULT UNIQUE value.

If you need to save the value for later, be sure to call this function immediately after the query that generates the value.

See Also

  • fbsql_affected_rows() - Get number of affected rows in previous FrontBase operation


List databases available on a FrontBase server

  • « fbsql_insert_id
  • fbsql_list_fields »
  • PHP Manual
  • FrontBase Functions
  • List databases available on a FrontBase server

fbsql_list_dbs

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_list_dbs — List databases available on a FrontBase server

Description

fbsql_list_dbs ([ resource $link_identifier ] ) : resource

Return a result pointer containing the databases available from the current fbsql daemon. Use the fbsql_tablename() to traverse this result pointer.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns a result pointer or FALSE on error.

Examples

Example #1 fbsql_list_dbs() example

<?php
$link = fbsql_connect('localhost', 'myname', 'secret');
$db_list = fbsql_list_dbs($link);

while ($row = fbsql_fetch_object($db_list)) {
    echo $row->Database . "\n";
}
?>

The above example will output something similar to:

database1
database2
database3
...

Note:

The above code would just as easily work with fbsql_fetch_row() or other similar functions.

See Also

  • fbsql_list_fields() - List FrontBase result fields
  • fbsql_list_tables() - List tables in a FrontBase database


List FrontBase result fields

  • « fbsql_list_dbs
  • fbsql_list_tables »
  • PHP Manual
  • FrontBase Functions
  • List FrontBase result fields

fbsql_list_fields

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_list_fields — List FrontBase result fields

Description

fbsql_list_fields ( string $database_name , string $table_name [, resource $link_identifier ] ) : resource

Retrieves information about the given table.

Parameters

database_name

The database name.

table_name

The table name.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns a result pointer which can be used with the fbsql_field_xxx functions, or FALSE on error.

Errors/Exceptions

A string describing the error will be placed in $phperrmsg, and unless the function was called as @fbsql() then this error string will also be printed out.

Examples

Example #1 fbsql_list_fields() example

<?php
$link = fbsql_connect('localhost', 'myname', 'secret');

$fields = fbsql_list_fields("database1", "table1", $link);
$columns = fbsql_num_fields($fields);

for ($i = 0; $i < $columns; $i++) {
    echo fbsql_field_name($fields, $i) . "\n";;
}
?>

The above example will output something similar to:

field1
field2
field3
...

See Also

  • fbsql_field_len() - Returns the length of the specified field
  • fbsql_field_name() - Get the name of the specified field in a result
  • fbsql_field_type() - Get the type of the specified field in a result
  • fbsql_field_flags() - Get the flags associated with the specified field in a result


List tables in a FrontBase database

  • « fbsql_list_fields
  • fbsql_next_result »
  • PHP Manual
  • FrontBase Functions
  • List tables in a FrontBase database

fbsql_list_tables

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_list_tables — List tables in a FrontBase database

Description

fbsql_list_tables ( string $database [, resource $link_identifier ] ) : resource

Returns a result pointer describing the database.

Parameters

database

The database name.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns a result pointer which can be used with the fbsql_tablename() function to read the actual table names, or FALSE on error.

See Also

  • fbsql_list_fields() - List FrontBase result fields
  • fbsql_list_dbs() - List databases available on a FrontBase server


Move the internal result pointer to the next result

  • « fbsql_list_tables
  • fbsql_num_fields »
  • PHP Manual
  • FrontBase Functions
  • Move the internal result pointer to the next result

fbsql_next_result

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_next_result — Move the internal result pointer to the next result

Description

fbsql_next_result ( resource $result ) : bool

When sending more than one SQL statement to the server or executing a stored procedure with multiple results will cause the server to return multiple result sets. This function will test for additional results available form the server. If an additional result set exists it will free the existing result set and prepare to fetch the words from the new result set.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

Return Values

Returns TRUE if an additional result set was available or FALSE otherwise.

Examples

Example #1 fbsql_next_result() example

<?php
$link = fbsql_connect("localhost", "_SYSTEM", "secret");
fbsql_select_db("MyDB", $link);
$SQL = "Select * from table1; select * from table2;";
$rs = fbsql_query($SQL, $link);
do {
    while ($row = fbsql_fetch_row($rs)) {
    }
} while (fbsql_next_result($rs));
fbsql_free_result($rs);
fbsql_close($link);
?>


Get number of fields in result

  • « fbsql_next_result
  • fbsql_num_rows »
  • PHP Manual
  • FrontBase Functions
  • Get number of fields in result

fbsql_num_fields

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_num_fields — Get number of fields in result

Description

fbsql_num_fields ( resource $result ) : int

Returns the number of fields in the given result set.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

Return Values

Returns the number of fields, as an integer.

See Also

  • fbsql_db_query() - Send a FrontBase query
  • fbsql_query() - Send a FrontBase query
  • fbsql_fetch_field() - Get column information from a result and return as an object
  • fbsql_num_rows() - Get number of rows in result


Get number of rows in result

  • « fbsql_num_fields
  • fbsql_password »
  • PHP Manual
  • FrontBase Functions
  • Get number of rows in result

fbsql_num_rows

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_num_rows — Get number of rows in result

Description

fbsql_num_rows ( resource $result ) : int

Gets the number of rows in the given result set.

This function is only valid for SELECT statements. To retrieve the number of rows returned from a INSERT, UPDATE or DELETE query, use fbsql_affected_rows().

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

Return Values

Returns the number of rows returned by the last SELECT statement.

Examples

Example #1 fbsql_num_rows() example

<?php

$link = fbsql_connect("localhost", "username", "password");
fbsql_select_db("database", $link);

$result = fbsql_query("SELECT * FROM table1;", $link);
$num_rows = fbsql_num_rows($result);

echo "$num_rows Rows\n";

?>

See Also

  • fbsql_affected_rows() - Get number of affected rows in previous FrontBase operation
  • fbsql_connect() - Open a connection to a FrontBase Server
  • fbsql_select_db() - Select a FrontBase database
  • fbsql_query() - Send a FrontBase query


Get or set the user password used with a connection

  • « fbsql_num_rows
  • fbsql_pconnect »
  • PHP Manual
  • FrontBase Functions
  • Get or set the user password used with a connection

fbsql_password

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_password — Get or set the user password used with a connection

Description

fbsql_password ( resource $link_identifier [, string $password ] ) : string

Get or set the user password used with a connection.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

password

If provided, this will be the new connection password.

Return Values

Returns the current password used for the connection.

See Also

  • fbsql_username() - Get or set the username for the connection
  • fbsql_hostname() - Get or set the host name used with a connection


Open a persistent connection to a FrontBase Server

  • « fbsql_password
  • fbsql_query »
  • PHP Manual
  • FrontBase Functions
  • Open a persistent connection to a FrontBase Server

fbsql_pconnect

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_pconnect — Open a persistent connection to a FrontBase Server

Description

 fbsql_pconnect
  ([ string $hostname = ini_get("fbsql.default_host")
 [, string $username = ini_get("fbsql.default_user")
 [, string $password = ini_get("fbsql.default_password")
]]] ) : resource

Establishes a persistent connection to a FrontBase server.

To set the server port number, use fbsql_select_db().

fbsql_pconnect() acts very much like fbsql_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.

This type of links is therefore called 'persistent'.

Parameters

hostname

The server host name.

username

The user name for the connection.

password

The password for the connection.

Return Values

Returns a positive FrontBase persistent link identifier on success, or FALSE on error.

See Also

  • fbsql_connect() - Open a connection to a FrontBase Server


Send a FrontBase query

  • « fbsql_pconnect
  • fbsql_read_blob »
  • PHP Manual
  • FrontBase Functions
  • Send a FrontBase query

fbsql_query

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_query — Send a FrontBase query

Description

fbsql_query ( string $query [, resource $link_identifier [, int $batch_size ]] ) : resource

Sends a query to the currently active database on the server.

If the query succeeds, you can call fbsql_num_rows() to find out how many rows were returned for a SELECT statement or fbsql_affected_rows() to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.

Parameters

query

The SQL query to be executed.

Note:

The query string shall always end with a semicolon.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

batch_size

Return Values

fbsql_query() returns TRUE (non-zero) or FALSE to indicate whether or not the query succeeded. A return value of TRUE means that the query was legal and could be executed by the server. It does not indicate anything about the number of rows affected or returned. It is perfectly possible for a query to succeed but affect no rows or return no rows.

For SELECT statements, fbsql_query() returns a new result identifier that you can pass to fbsql_result().

fbsql_query() will also fail and return FALSE if you don't have permission to access the table(s) referenced by the query.

Examples

The following query is syntactically invalid, so fbsql_query() fails and returns FALSE:

Example #1 fbsql_query() example

<?php
$result = fbsql_query("SELECT * WHERE 1=1")
    or die ("Invalid query");
?>

The following query is semantically invalid if my_col is not a column in the table my_tbl, so fbsql_query() fails and returns FALSE:

Example #2 fbsql_query() example

<?php
$result = fbsql_query ("SELECT my_col FROM my_tbl;")
    or die ("Invalid query");
?>

See Also

  • fbsql_affected_rows() - Get number of affected rows in previous FrontBase operation
  • fbsql_db_query() - Send a FrontBase query
  • fbsql_free_result() - Free result memory
  • fbsql_result() - Get result data
  • fbsql_select_db() - Select a FrontBase database
  • fbsql_connect() - Open a connection to a FrontBase Server


Read a BLOB from the database

  • « fbsql_query
  • fbsql_read_clob »
  • PHP Manual
  • FrontBase Functions
  • Read a BLOB from the database

fbsql_read_blob

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

fbsql_read_blob — Read a BLOB from the database

Description

fbsql_read_blob ( string $blob_handle [, resource $link_identifier ] ) : string

Reads BLOB data from the database.

If a select statement contains BLOB and/or CLOB columns FrontBase will return the data directly when data is fetched. This default behavior can be changed with fbsql_set_lob_mode() so the fetch functions will return handles to BLOB and CLOB data. If a handle is fetched a user must call fbsql_read_blob() to get the actual BLOB data from the database.

Parameters

blob_handle

A BLOB handle, returned by fbsql_create_blob().

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns a string containing the specified BLOB data.

Examples

Example #1 fbsql_read_blob() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
$sql = "SELECT BLOB_COLUMN FROM BLOB_TABLE;";
$rs = fbsql_query($sql, $link);
$row_data = fbsql_fetch_row($rs);
// $row_data[0] will now contain the blob data for the first row
fbsql_free_result($rs);

$rs = fbsql_query($sql, $link);
fbsql_set_lob_mode($rs, FBSQL_LOB_HANDLE);
$row_data = fbsql_fetch_row($rs);
// $row_data[0] will now contain a handle to the BLOB data in the first row
$blob_data = fbsql_read_blob($row_data[0]);
fbsql_free_result($rs);

?>

See Also

  • fbsql_create_blob() - Create a BLOB
  • fbsql_read_clob() - Read a CLOB from the database
  • fbsql_set_lob_mode() - Set the LOB retrieve mode for a FrontBase result set


Read a CLOB from the database

  • « fbsql_read_blob
  • fbsql_result »
  • PHP Manual
  • FrontBase Functions
  • Read a CLOB from the database

fbsql_read_clob

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

fbsql_read_clob — Read a CLOB from the database

Description

fbsql_read_clob ( string $clob_handle [, resource $link_identifier ] ) : string

Reads CLOB data from the database.

If a select statement contains BLOB and/or CLOB columns FrontBase will return the data directly when data is fetched. This default behavior can be changed with fbsql_set_lob_mode() so the fetch functions will return handles to BLOB and CLOB data. If a handle is fetched a user must call fbsql_read_clob() to get the actual CLOB data from the database.

Parameters

clob_handle

A CLOB handle, returned by fbsql_create_clob().

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns a string containing the specified CLOB data.

Examples

Example #1 fbsql_read_clob() example

<?php
$link = fbsql_pconnect("localhost", "_SYSTEM", "secret")
    or die("Could not connect");
$sql = "SELECT CLOB_COLUMN FROM CLOB_TABLE;";
$rs = fbsql_query($sql, $link);
$row_data = fbsql_fetch_row($rs);
// $row_data[0] will now contain the clob data for the first row
fbsql_free_result($rs);

$rs = fbsql_query($sql, $link);
fbsql_set_lob_mode($rs, FBSQL_LOB_HANDLE);
$row_data = fbsql_fetch_row($rs);
// $row_data[0] will now contain a handle to the CLOB data in the first row
$clob_data = fbsql_read_clob($row_data[0]);
fbsql_free_result($rs);

?>

See Also

  • fbsql_create_clob() - Create a CLOB
  • fbsql_read_blob() - Read a BLOB from the database
  • fbsql_set_lob_mode() - Set the LOB retrieve mode for a FrontBase result set


Get result data

  • « fbsql_read_clob
  • fbsql_rollback »
  • PHP Manual
  • FrontBase Functions
  • Get result data

fbsql_result

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_result — Get result data

Description

fbsql_result ( resource $result [, int $row [, mixed $field ]] ) : mixed

Returns the contents of one cell from a FrontBase 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 fbsql_result().

Calls to fbsql_result() should not be mixed with calls to other functions that deal with the result set.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

row

field

Can be the field's offset, or the field's name, or the field's table dot field's name (tablename.fieldname).

If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name.

Note:

Specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.

Return Values

See Also

Recommended high-performance alternatives:

  • fbsql_fetch_row() - Get a result row as an enumerated array
  • fbsql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • fbsql_fetch_assoc() - Fetch a result row as an associative array
  • fbsql_fetch_object() - Fetch a result row as an object


Rollback a transaction to the database

  • « fbsql_result
  • fbsql_rows_fetched »
  • PHP Manual
  • FrontBase Functions
  • Rollback a transaction to the database

fbsql_rollback

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_rollback — Rollback a transaction to the database

Description

fbsql_rollback ([ resource $link_identifier ] ) : bool

Ends the current transaction by rolling back all statements issued since last commit.

This command is only needed if autocommit is set to false.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fbsql_autocommit() - Enable or disable autocommit
  • fbsql_commit() - Commits a transaction to the database


Get the number of rows affected by the last statement

  • « fbsql_rollback
  • fbsql_select_db »
  • PHP Manual
  • FrontBase Functions
  • Get the number of rows affected by the last statement

fbsql_rows_fetched

(PHP 5 >= 5.1.0, PHP 7)

fbsql_rows_fetched — Get the number of rows affected by the last statement

Description

fbsql_rows_fetched ( resource $result ) : int

Gets the number of rows affected by the last statement.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

Return Values

Returns the number of rows, as an integer.


Select a FrontBase database

  • « fbsql_rows_fetched
  • fbsql_set_characterset »
  • PHP Manual
  • FrontBase Functions
  • Select a FrontBase database

fbsql_select_db

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_select_db — Select a FrontBase database

Description

fbsql_select_db ([ string $database_name [, resource $link_identifier ]] ) : bool

Sets the current active database on the given link identifier.

The client contacts FBExec to obtain the port number to use for the connection to the database. If the database name is a number the system will use that as a port number and it will not ask FBExec for the port number. The FrontBase server can be stared as FRontBase -FBExec=No -port=<port number> <database name>.

Every subsequent call to fbsql_query() will be made on the active database.

Parameters

database_name

The name of the database to be selected.

If the database is protected with a database password, the you must call fbsql_database_password() before selecting the database.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fbsql_connect() - Open a connection to a FrontBase Server
  • fbsql_pconnect() - Open a persistent connection to a FrontBase Server
  • fbsql_database_password() - Sets or retrieves the password for a FrontBase database
  • fbsql_query() - Send a FrontBase query


Change input/output character set

  • « fbsql_select_db
  • fbsql_set_lob_mode »
  • PHP Manual
  • FrontBase Functions
  • Change input/output character set

fbsql_set_characterset

(PHP 5 >= 5.1.0, PHP 7)

fbsql_set_characterset — Change input/output character set

Description

fbsql_set_characterset ( resource $link_identifier , int $characterset [, int $in_out_both ] ) : void
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.


Set the LOB retrieve mode for a FrontBase result set

  • « fbsql_set_characterset
  • fbsql_set_password »
  • PHP Manual
  • FrontBase Functions
  • Set the LOB retrieve mode for a FrontBase result set

fbsql_set_lob_mode

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

fbsql_set_lob_mode — Set the LOB retrieve mode for a FrontBase result set

Description

fbsql_set_lob_mode ( resource $result , int $lob_mode ) : bool

Sets the mode for retrieving LOB data from the database.

When BLOB and CLOB data is retrieved in FrontBase it can be retrieved direct or indirect. Direct retrieved LOB data will always be fetched no matter the setting of the lob mode. If the LOB data is less than 512 bytes it will always be retrieved directly.

Parameters

result

A result identifier returned by fbsql_query() or fbsql_db_query().

lob_mode

Can be one of:

  • FBSQL_LOB_DIRECT - LOB data is retrieved directly. When data is fetched from the database with fbsql_fetch_row(), and other fetch functions, all CLOB and BLOB columns will be returned as ordinary columns. This is the default value on a new FrontBase result.
  • FBSQL_LOB_HANDLE - LOB data is retrieved as handles to the data. When data is fetched from the database with fbsql_fetch_row(), and other fetch functions, LOB data will be returned as a handle to the data if the data is stored indirect or the data if it is stored direct. If a handle is returned it will be a 27 byte string formatted as @'000000000000000000000000'.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fbsql_create_blob() - Create a BLOB
  • fbsql_create_clob() - Create a CLOB
  • fbsql_read_blob() - Read a BLOB from the database
  • fbsql_read_clob() - Read a CLOB from the database


Change the password for a given user

  • « fbsql_set_lob_mode
  • fbsql_set_transaction »
  • PHP Manual
  • FrontBase Functions
  • Change the password for a given user

fbsql_set_password

(PHP 5, PHP 7)

fbsql_set_password — Change the password for a given user

Description

fbsql_set_password ( resource $link_identifier , string $user , string $password , string $old_password ) : bool

Changes the password for the given user.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

user

The user name.

password

The new password to be set.

old_password

The old password to be replaced.

Return Values

Returns TRUE on success or FALSE on failure.


Set the transaction locking and isolation

  • « fbsql_set_password
  • fbsql_start_db »
  • PHP Manual
  • FrontBase Functions
  • Set the transaction locking and isolation

fbsql_set_transaction

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

fbsql_set_transaction — Set the transaction locking and isolation

Description

fbsql_set_transaction ( resource $link_identifier , int $locking , int $isolation ) : void

Sets the transaction locking and isolation.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

locking

The type of locking to be set. It can be one of the following constants: FBSQL_LOCK_DEFERRED, FBSQL_LOCK_OPTIMISTIC, or FBSQL_LOCK_PESSIMISTIC.

isolation

The type of isolation to be set. It can be one of the following constants: FBSQL_ISO_READ_UNCOMMITTED, FBSQL_ISO_READ_COMMITTED, FBSQL_ISO_REPEATABLE_READ, FBSQL_ISO_SERIALIZABLE, or FBSQL_ISO_VERSIONED.

Return Values

No value is returned.


Start a database on local or remote server

  • « fbsql_set_transaction
  • fbsql_stop_db »
  • PHP Manual
  • FrontBase Functions
  • Start a database on local or remote server

fbsql_start_db

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_start_db — Start a database on local or remote server

Description

fbsql_start_db ( string $database_name [, resource $link_identifier [, string $database_options ]] ) : bool

Start a database on local or remote server.

Parameters

database_name

The database name.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

database_options

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fbsql_db_status() - Get the status for a given database
  • fbsql_stop_db() - Stop a database on local or remote server


Stop a database on local or remote server

  • « fbsql_start_db
  • fbsql_table_name »
  • PHP Manual
  • FrontBase Functions
  • Stop a database on local or remote server

fbsql_stop_db

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_stop_db — Stop a database on local or remote server

Description

fbsql_stop_db ( string $database_name [, resource $link_identifier ] ) : bool

Stops a database on local or remote server.

Parameters

database_name

The database name.

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fbsql_db_status() - Get the status for a given database
  • fbsql_start_db() - Start a database on local or remote server


Get table name of field

  • « fbsql_stop_db
  • fbsql_tablename »
  • PHP Manual
  • FrontBase Functions
  • Get table name of field

fbsql_table_name

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

fbsql_table_name — Get table name of field

Description

fbsql_table_name ( resource $result , int $index ) : string

fbsql_table_name() gets the name of the current table in the given result set.

The fbsql_num_rows() function may be used to determine the number of tables in the result pointer.

Parameters

result

A result pointer returned by fbsql_list_tables().

index

Integer index for the current table.

Return Values

Returns the name of the table, as a string.

Examples

Example #1 fbsql_table_name() example

<?php
fbsql_connect("localhost", "_SYSTEM", "");
$result = fbsql_list_tables("wisconsin");
$i = 0;
while ($i < fbsql_num_rows($result)) {
    $tb_names[$i] = fbsql_table_name($result, $i);
    echo $tb_names[$i] . "<br />";
    $i++;
}
?>


Alias of fbsql_table_name

  • « fbsql_table_name
  • fbsql_username »
  • PHP Manual
  • FrontBase Functions
  • Alias of fbsql_table_name

fbsql_tablename

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

fbsql_tablename — Alias of fbsql_table_name()

Description

This function is an alias of: fbsql_table_name().


Get or set the username for the connection

  • « fbsql_tablename
  • fbsql_warnings »
  • PHP Manual
  • FrontBase Functions
  • Get or set the username for the connection

fbsql_username

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_username — Get or set the username for the connection

Description

fbsql_username ( resource $link_identifier [, string $username ] ) : string

Get or set the username used for the connection.

Parameters

link_identifier

A FrontBase link identifier returned by fbsql_connect() or fbsql_pconnect().

If optional and not specified, the function will try to find an open link to the FrontBase server and if no such link is found it will try to create one as if fbsql_connect() was called with no arguments.

username

If provided, this is the new username to set.

Return Values

Returns the current username used with the connection, as a string.

See Also

  • fbsql_password() - Get or set the user password used with a connection
  • fbsql_hostname() - Get or set the host name used with a connection


Enable or disable FrontBase warnings

  • « fbsql_username
  • IBM DB2 »
  • PHP Manual
  • FrontBase Functions
  • Enable or disable FrontBase warnings

fbsql_warnings

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

fbsql_warnings — Enable or disable FrontBase warnings

Description

fbsql_warnings ([ bool $OnOff ] ) : bool

Enables or disables FrontBase warnings.

Parameters

OnOff

Whether to enable warnings or no.

Return Values

Returns TRUE if warnings is turned on, FALSE otherwise.

See Also

  • fbsql_errno() - Returns the error number from previous operation
  • fbsql_error() - Returns the error message from previous operation


IBM DB2, Cloudscape and Apache Derby

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


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


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 your system. DB2 does not install these by default, so you may have to return to your DB2 installer and add this option. The header files are included with the DB2 Application Development Client freely available for download from the IBM DB2 Universal Database » support site.

If you add the DB2 application development header files and libraries to a Linux or Unix operating system on which DB2 was already installed, you must issue the command db2iupdt -e to update the symbolic links to the header files and libraries in your 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 your 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 you are using the ibm_db2 driver with Microsoft Internet Information Server (IIS) you may have 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" | PHP_INI_ALL |
ibm_db2.i5_all_pconnect | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.6.5.
ibm_db2.i5_allow_commit | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.4.9.
ibm_db2.i5_dbcs_alloc | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.5.0.
ibm_db2.instance_name | NULL | PHP_INI_SYSTEM | Available since ibm_db2 1.0.2.
ibm_db2.i5_ignore_userid | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.8.0.

Here's a short explanation of the configuration directives.

ibm_db2.binmode integer

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 integer

This option overrides i5 db2_connect() full open and close in the PHP application. When ibm_db2.i5_all_pconnect = 1, all db2 connections become persistent (db2_pconnect()). On i5/OS, db2_pconnect() performs dramatically better with lower machine stress over db2_connect(). This is a convenience override of db2_connect() to evoke db2_pconnect() without PHP source code changes.

  • 0 db2_connect() default full open and close

  • 1 db2_connect() override to db2_pconnect() for persistent connection only

ibm_db2.i5_allow_commit integer

This option controls the isolation mode used for i5 schema collections in the PHP application (see i5_commit for override).

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

This option controls the internal ibm_db2 allocation scheme for large DBCS column buffers.

  • 0 no expanded allocations (see i5_dbcs_alloc for override)

  • 1 use expanded allocations (see i5_dbcs_alloc for override)

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. If this option is set, its value overrides the DB2INSTANCE environment variable setting.

This option is ignored on Windows operating systems.

ibm_db2.i5_ignore_userid integer

This option overrides i5 db2_(p)connect userid and password in the PHP application. When ibm_db2.i5_ignore_userid = 1, all db2 (p)connections become null userid and null password. Therefore Apache jobs connect with the current profile (NOBODY). Use of this override is only for simple DB2 based websites that never require profile switching and therefore can avoid all overhead of server mode additional QSQSRVR jobs. This is a convenience override of db2_(p)connect to set the userid and password values to null without PHP source code changes. This override can be used in combination with ibm_db2.i5_all_pconnect = 1.

  • 0 db2_(p)connect with specified userid and password

  • 1 db2_(p)connect override connect with null userid and null password


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 (integer)
Specifies that binary data shall be returned as is. This is the default mode.
DB2_CONVERT (integer)
Specifies that binary data shall be converted to a hexadecimal encoding and returned as an ASCII string.
DB2_PASSTHRU (integer)
Specifies that binary data shall be converted to a NULL value.
DB2_SCROLLABLE (integer)
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 (integer)
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 (integer)
Specifies the PHP variable should be bound as an IN parameter for a stored procedure.
DB2_PARAM_OUT (integer)
Specifies the PHP variable should be bound as an OUT parameter for a stored procedure.
DB2_PARAM_INOUT (integer)
Specifies the PHP variable should be bound as an INOUT parameter for a stored procedure.
DB2_PARAM_FILE (integer)
Specifies that the column should be bound directly to a file for input.
DB2_AUTOCOMMIT_ON (integer)
Specifies that autocommit should be turned on.
DB2_AUTOCOMMIT_OFF (integer)
Specifies that autocommit should be turned off.
DB2_DOUBLE (integer)
Specifies that the variable should be bound as a DOUBLE, FLOAT, or REAL data type.
DB2_LONG (integer)
Specifies that the variable should be bound as a SMALLINT, INTEGER, or BIGINT data type.
DB2_CHAR (integer)
Specifies that the variable should be bound as a CHAR or VARCHAR data type.
DB2_CASE_NATURAL (integer)
Specifies that column names will be returned in their natural case.
DB2_CASE_LOWER (integer)
Specifies that column names will be returned in lower case.
DB2_CASE_UPPER (integer)
Specifies that column names will be returned in upper case.
DB2_DEFERRED_PREPARE_ON (integer)
Specifies that deferred prepare should be turned on for the specified statement resource.
DB2_DEFERRED_PREPARE_OFF (integer)
Specifies that deferred prepare should be turned off for the specified statement resource.


IBM DB2 Functions

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


Returns or sets the AUTOCOMMIT state for a database connection

  • « IBM DB2 Functions
  • db2_bind_param »
  • PHP Manual
  • IBM DB2 Functions
  • Returns or sets the AUTOCOMMIT state for a database connection

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 [, bool $value ] ) : mixed

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


Binds a PHP variable to an SQL statement parameter

  • « db2_autocommit
  • db2_client_info »
  • PHP Manual
  • IBM DB2 Functions
  • Binds a PHP variable to an SQL statement parameter

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 [, 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


Returns an object with properties that describe the DB2 database client

  • « db2_bind_param
  • db2_close »
  • PHP Manual
  • IBM DB2 Functions
  • Returns an object with properties that describe the DB2 database client

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 ) : object

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


Closes a database connection

  • « db2_client_info
  • db2_column_privileges »
  • PHP Manual
  • IBM DB2 Functions
  • Closes a database connection

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


Returns a result set listing the columns and associated privileges for a table

  • « db2_close
  • db2_columns »
  • PHP Manual
  • IBM DB2 Functions
  • Returns a result set listing the columns and associated privileges for a table

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 [, string $schema [, string $table-name [, string $column-name ]]]] ) : 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


Returns a result set listing the columns and associated metadata for a table

  • « db2_column_privileges
  • db2_commit »
  • PHP Manual
  • IBM DB2 Functions
  • Returns a result set listing the columns and associated metadata for a table

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 [, string $schema [, string $table-name [, string $column-name ]]]] ) : 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


Commits a transaction

  • « db2_columns
  • db2_conn_error »
  • PHP Manual
  • IBM DB2 Functions
  • Commits a transaction

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


Returns a string containing the SQLSTATE returned by the last connection attempt

  • « db2_commit
  • db2_conn_errormsg »
  • PHP Manual
  • IBM DB2 Functions
  • Returns a string containing the SQLSTATE returned by the last connection attempt

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


Returns the last connection error message and SQLCODE value

  • « db2_conn_error
  • db2_connect »
  • PHP Manual
  • IBM DB2 Functions
  • Returns the last connection error message and SQLCODE value

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


Returns a connection to a database

  • « db2_conn_errormsg
  • db2_cursor_type »
  • PHP Manual
  • IBM DB2 Functions
  • Returns a connection to a database

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

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


Returns the cursor type used by a statement resource

  • « db2_connect
  • db2_escape_string »
  • PHP Manual
  • IBM DB2 Functions
  • Returns the cursor type used by a statement resource

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


Used to escape certain characters

  • « db2_cursor_type
  • db2_exec »
  • PHP Manual
  • IBM DB2 Functions
  • Used to escape certain characters

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


Executes an SQL statement directly

  • « db2_escape_string
  • db2_execute »
  • PHP Manual
  • IBM DB2 Functions
  • Executes an SQL statement directly

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

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


Executes a prepared SQL statement

  • « db2_exec
  • db2_fetch_array »
  • PHP Manual
  • IBM DB2 Functions
  • Executes a prepared SQL statement

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


Returns an array, indexed by column position, representing a row in a result set

  • « db2_execute
  • db2_fetch_assoc »
  • PHP Manual
  • IBM DB2 Functions
  • Returns an array, indexed by column position, representing a row in a 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

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


Returns an array, indexed by column name, representing a row in a result set

  • « db2_fetch_array
  • db2_fetch_both »
  • PHP Manual
  • IBM DB2 Functions
  • Returns an array, indexed by column name, representing a row in a 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

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


Returns an array, indexed by both column name and position, representing a row in a result set

  • « db2_fetch_assoc
  • db2_fetch_object »
  • PHP Manual
  • IBM DB2 Functions
  • Returns an array, indexed by both column name and position, representing a row in a 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

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


Returns an object with properties representing columns in the fetched row

  • « db2_fetch_both
  • db2_fetch_row »
  • PHP Manual
  • IBM DB2 Functions
  • Returns an object with properties representing columns in the fetched row

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

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


Sets the result set pointer to the next row or requested row

  • « db2_fetch_object
  • db2_field_display_size »
  • PHP Manual
  • IBM DB2 Functions
  • Sets the result set pointer to the next row or requested row

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


Returns the maximum number of bytes required to display a column

  • « db2_fetch_row
  • db2_field_name »
  • PHP Manual
  • IBM DB2 Functions
  • Returns the maximum number of bytes required to display a column

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 , mixed $column ) : int

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


Returns the name of the column in the result set

  • « db2_field_display_size
  • db2_field_num »
  • PHP Manual
  • IBM DB2 Functions
  • Returns the name of the column in the 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 , mixed $column ) : string

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


Returns the position of the named column in a result set

  • « db2_field_name
  • db2_field_precision »
  • PHP Manual
  • IBM DB2 Functions
  • Returns the position of the named 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 , mixed $column ) : int

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


Returns the precision of the indicated column in a result set

  • « db2_field_num
  • db2_field_scale »
  • PHP Manual
  • IBM DB2 Functions
  • Returns the precision 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 , mixed $column ) : int

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


Returns the scale of the indicated column in a result set

  • « db2_field_precision
  • db2_field_type »
  • PHP Manual
  • IBM DB2 Functions
  • Returns the scale 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 , mixed $column ) : int

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


Returns the data type of the indicated column in a result set

  • « db2_field_scale
  • db2_field_width »
  • PHP Manual
  • IBM DB2 Functions
  • Returns the data type 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 , mixed $column ) : string

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


Returns the width of the current value of the indicated column in a result set

  • « db2_field_type
  • db2_foreign_keys »
  • PHP Manual
  • IBM DB2 Functions
  • 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 , mixed $column ) : int

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


Returns a result set listing the foreign keys for a table

  • « db2_field_width
  • db2_free_result »
  • PHP Manual
  • IBM DB2 Functions
  • Returns a result set listing the foreign keys for a table

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


Frees resources associated with a result set

  • « db2_foreign_keys
  • db2_free_stmt »
  • PHP Manual
  • IBM DB2 Functions
  • Frees resources associated with a result set

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


Frees resources associated with the indicated statement resource

  • « db2_free_result
  • db2_get_option »
  • PHP Manual
  • IBM DB2 Functions
  • 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


Retrieves an option value for a statement resource or a connection resource

  • « db2_free_stmt
  • db2_last_insert_id »
  • PHP Manual
  • IBM DB2 Functions
  • Retrieves an option value for a statement resource or a connection resource

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

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


Returns the auto generated ID of the last insert query that successfully executed on this connection

  • « db2_get_option
  • db2_lob_read »
  • PHP Manual
  • IBM DB2 Functions
  • Returns the auto generated ID of the last insert query that successfully executed on this connection

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


Gets a user defined size of LOB files with each invocation

  • « db2_last_insert_id
  • db2_next_result »
  • PHP Manual
  • IBM DB2 Functions
  • Gets a user defined size of LOB files with each invocation

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

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


Requests the next result set from a stored procedure

  • « db2_lob_read
  • db2_num_fields »
  • PHP Manual
  • IBM DB2 Functions
  • Requests the next result set from a stored procedure

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

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


Returns the number of fields contained in a result set

  • « db2_next_result
  • db2_num_rows »
  • PHP Manual
  • IBM DB2 Functions
  • Returns the number of fields contained in a result set

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

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


Returns the number of rows affected by an SQL statement

  • « db2_num_fields
  • db2_pclose »
  • PHP Manual
  • IBM DB2 Functions
  • Returns the number of rows affected by an SQL statement

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

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


Closes a persistent database connection

  • « db2_num_rows
  • db2_pconnect »
  • PHP Manual
  • IBM DB2 Functions
  • Closes a persistent database connection

db2_pclose

(PECL ibm_db2 >= 1.8.0)

db2_pclose — Closes a persistent database connection

Description

db2_pclose ( resource $resource ) : 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


Returns a persistent connection to a database

  • « db2_pclose
  • db2_prepare »
  • PHP Manual
  • IBM DB2 Functions
  • 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

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

The database alias in the DB2 client catalog.

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
ibm_db2 1.9.0 | Active transactions within a persistent connection will be rolled back at the end of each request.
ibm_db2 1.8.0 | The i5_libl option is available for i5/OS users.
ibm_db2 1.7.0 | The trustedcontext option is available.
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


Prepares an SQL statement to be executed

  • « db2_pconnect
  • db2_primary_keys »
  • PHP Manual
  • IBM DB2 Functions
  • Prepares an SQL statement to be executed

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

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


Returns a result set listing primary keys for a table

  • « db2_prepare
  • db2_procedure_columns »
  • PHP Manual
  • IBM DB2 Functions
  • Returns a result set listing primary keys for a table

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


Returns a result set listing stored procedure parameters

  • « db2_primary_keys
  • db2_procedures »
  • PHP Manual
  • IBM DB2 Functions
  • Returns a result set listing stored procedure parameters

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


Returns a result set listing the stored procedures registered in a database

  • « db2_procedure_columns
  • db2_result »
  • PHP Manual
  • IBM DB2 Functions
  • Returns a result set listing the stored procedures registered 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


Returns a single column from a row in the result set

  • « db2_procedures
  • db2_rollback »
  • PHP Manual
  • IBM DB2 Functions
  • Returns a single column from a row in the result set

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 , mixed $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


Rolls back a transaction

  • « db2_result
  • db2_server_info »
  • PHP Manual
  • IBM DB2 Functions
  • Rolls back a transaction

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


Returns an object with properties that describe the DB2 database server

  • « db2_rollback
  • db2_set_option »
  • PHP Manual
  • IBM DB2 Functions
  • Returns an object with properties that describe the DB2 database server

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 ) : object

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


Set options for connection or statement resources

  • « db2_server_info
  • db2_special_columns »
  • PHP Manual
  • IBM DB2 Functions
  • Set options for connection or statement resources

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


Returns a result set listing the unique row identifier columns for a table

  • « db2_set_option
  • db2_statistics »
  • PHP Manual
  • IBM DB2 Functions
  • Returns a result set listing the unique row identifier columns for a table

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


Returns a result set listing the index and statistics for a table

  • « db2_special_columns
  • db2_stmt_error »
  • PHP Manual
  • IBM DB2 Functions
  • Returns a result set listing the index and statistics for a table

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

An integer value representing the type of index information to return.

0

Return only the information for unique indexes on the table.

1

Return the information for all indexes on the table.

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


Returns a string containing the SQLSTATE returned by an SQL statement

  • « db2_statistics
  • db2_stmt_errormsg »
  • PHP Manual
  • IBM DB2 Functions
  • Returns a string containing the SQLSTATE returned by an SQL statement

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


Returns a string containing the last SQL statement error message

  • « db2_stmt_error
  • db2_table_privileges »
  • PHP Manual
  • IBM DB2 Functions
  • 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 ] ) : 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


Returns a result set listing the tables and associated privileges in a database

  • « db2_stmt_errormsg
  • db2_tables »
  • PHP Manual
  • IBM DB2 Functions
  • Returns a result set listing the tables and associated privileges in a database

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 [, string $schema [, string $table_name ]]] ) : 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


Returns a result set listing the tables and associated metadata in a database

  • « db2_table_privileges
  • Informix »
  • PHP Manual
  • IBM DB2 Functions
  • 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 [, string $schema [, string $table-name [, string $table-type ]]]] ) : 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


Informix

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Informix Functions
    • ifx_affected_rows — Get number of rows affected by a query
    • ifx_blobinfile_mode — Set the default blob mode for all select queries
    • ifx_byteasvarchar — Set the default byte mode
    • ifx_close — Close Informix connection
    • ifx_connect — Open Informix server connection
    • ifx_copy_blob — Duplicates the given blob object
    • ifx_create_blob — Creates an blob object
    • ifx_create_char — Creates an char object
    • ifx_do — Execute a previously prepared SQL-statement
    • ifx_error — Returns error code of last Informix call
    • ifx_errormsg — Returns error message of last Informix call
    • ifx_fetch_row — Get row as an associative array
    • ifx_fieldproperties — List of SQL fieldproperties
    • ifx_fieldtypes — List of Informix SQL fields
    • ifx_free_blob — Deletes the blob object
    • ifx_free_char — Deletes the char object
    • ifx_free_result — Releases resources for the query
    • ifx_get_blob — Return the content of a blob object
    • ifx_get_char — Return the content of the char object
    • ifx_getsqlca — Get the contents of sqlca.sqlerrd[0..5] after a query
    • ifx_htmltbl_result — Formats all rows of a query into a HTML table
    • ifx_nullformat — Sets the default return value on a fetch row
    • ifx_num_fields — Returns the number of columns in the query
    • ifx_num_rows — Count the rows already fetched from a query
    • ifx_pconnect — Open persistent Informix connection
    • ifx_prepare — Prepare an SQL-statement for execution
    • ifx_query — Send Informix query
    • ifx_textasvarchar — Set the default text mode
    • ifx_update_blob — Updates the content of the blob object
    • ifx_update_char — Updates the content of the char object
    • ifxus_close_slob — Deletes the slob object
    • ifxus_create_slob — Creates an slob object and opens it
    • ifxus_free_slob — Deletes the slob object
    • ifxus_open_slob — Opens an slob object
    • ifxus_read_slob — Reads nbytes of the slob object
    • ifxus_seek_slob — Sets the current file or seek position
    • ifxus_tell_slob — Returns the current file or seek position
    • ifxus_write_slob — Writes a string into the slob object


Introduction

The Informix driver for Informix (IDS) 7.x, SE 7.x, Universal Server (IUS) 9.x and IDS 2000 is implemented in "ifx.ec" and "php_informix.h" in the informix extension directory. IDS 7.x support is fairly complete, with full support for BYTE and TEXT columns. IUS 9.x support is partly finished: the new data types are there, but SLOB and CLOB support is still under construction.

Note:

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.2.1.


Requirements

Note: Configuration notes

You need a version of ESQL/C to compile the PHP Informix driver. ESQL/C versions from 7.2x on should be OK. ESQL/C is now part of the Informix Client SDK.

Make sure that the "INFORMIXDIR" variable has been set, and that $INFORMIXDIR/bin is in your PATH before you run the "configure" script.


Installation

To be able to use the functions defined in this module you must compile your PHP interpreter using the configure line --with-informix[=DIR] , where DIR is the Informix base install directory, defaults to nothing.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Note:

Make sure that the Informix environment variables INFORMIXDIR and INFORMIXSERVER are available to the PHP ifx driver, and that the INFORMIX bin directory is in the PATH. Check this by running a script that contains a call to phpinfo() before you start testing. The phpinfo() output should list these environment variables. This is true for both CGI php and Apache mod_php. You may have to set these environment variables in your Apache startup script.

The Informix shared libraries should also be available to the loader (check LD_LIBRARY_PATH or ld.so.conf/ldconfig).

Note: Some notes on the use of BLOBs (TEXT and BYTE columns)

BLOBs are normally addressed by BLOB identifiers. Select queries return a "blob id" for every BYTE and TEXT column. You can get at the contents with "string_var = ifx_get_blob($blob_id);" if you choose to get the BLOBs in memory (with: "ifx_blobinfile(0);"). If you prefer to receive the content of BLOB columns in a file, use "ifx_blobinfile(1);", and "ifx_get_blob($blob_id);" will get you the filename. Use normal file I/O to get at the blob contents.

For insert/update queries you must create these "blob id's" yourself with "ifx_create_blob();". You then plug the blob id's into an array, and replace the blob columns with a question mark (?) in the query string. For updates/inserts, you are responsible for setting the blob contents with ifx_update_blob().

The behaviour of BLOB columns can be altered by configuration variables that also can be set at runtime:

configuration variable: ifx.textasvarchar

configuration variable: ifx.byteasvarchar

runtime functions:

ifx_textasvarchar(0): use blob id's for select queries with TEXT columns

ifx_byteasvarchar(0): use blob id's for select queries with BYTE columns

ifx_textasvarchar(1): return TEXT columns as if they were VARCHAR columns, so that you don't need to use blob id's for select queries.

ifx_byteasvarchar(1): return BYTE columns as if they were VARCHAR columns, so that you don't need to use blob id's for select queries.

configuration variable: ifx.blobinfile

runtime function:

ifx_blobinfile_mode(0): return BYTE columns in memory, the blob id lets you get at the contents.

ifx_blobinfile_mode(1): return BYTE columns in a file, the blob id lets you get at the file name.

If you set ifx_text/byteasvarchar to 1, you can use TEXT and BYTE columns in select queries just like normal (but rather long) VARCHAR fields. Since all strings are "counted" in PHP, this remains "binary safe". It is up to you to handle this correctly. The returned data can contain anything, you are responsible for the contents.

If you set ifx_blobinfile to 1, use the file name returned by ifx_get_blob(..) to get at the blob contents. Note that in this case YOU ARE RESPONSIBLE FOR DELETING THE TEMPORARY FILES CREATED BY INFORMIX when fetching the row. Every new row fetched will create new temporary files for every BYTE column.

The location of the temporary files can be influenced by the environment variable "blobdir", default is "." (the current directory). Something like: putenv(blobdir=tmpblob"); will ease the cleaning up of temp files accidentally left behind (their names all start with "blb").

Note: Automatically trimming "char" (SQLCHAR and SQLNCHAR) data

This can be set with the configuration variable

ifx.charasvarchar: if set to 1 trailing spaces will be automatically trimmed, to save you some "chopping".

Note: NULL values

The configuration variable ifx.nullformat (and the runtime function ifx_nullformat()) when set to TRUE will return NULL columns as the string "NULL", when set to FALSE they return the empty string. This allows you to discriminate between NULL columns and empty columns.

Informix configuration options
Name | Default | Changeable | Changelog
ifx.allow_persistent | "1" | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.max_persistent | "-1" | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.max_links | "-1" | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.default_host | NULL | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.default_user | NULL | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.default_password | NULL | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.blobinfile | "1" | PHP_INI_ALL | Removed in PHP 5.2.1.
ifx.textasvarchar | "0" | PHP_INI_ALL | Removed in PHP 5.2.1.
ifx.byteasvarchar | "0" | PHP_INI_ALL | Removed in PHP 5.2.1.
ifx.charasvarchar | "0" | PHP_INI_ALL | Removed in PHP 5.2.1.
ifx.nullformat | "0" | PHP_INI_ALL | Removed in PHP 5.2.1.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

ifx.allow_persistent boolean

Whether to allow persistent Informix connections.

ifx.max_persistent integer

The maximum number of persistent Informix connections per process.

ifx.max_links integer

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

ifx.default_host string

The default host to connect to when no host is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in safe mode.

ifx.default_user string

The default user id to use when none is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in safe mode.

ifx.default_password string

The default password to use when none is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in safe mode.

ifx.blobinfile boolean

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

ifx.textasvarchar boolean

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

ifx.byteasvarchar boolean

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

ifx.charasvarchar boolean

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

ifx.nullformat boolean

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


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.

IFX_SCROLL (integer)
IFX_HOLD (integer)
IFX_LO_RDONLY (integer)
IFX_LO_WRONLY (integer)
IFX_LO_APPEND (integer)
IFX_LO_RDWR (integer)
IFX_LO_BUFFER (integer)
IFX_LO_NOBUFFER (integer)


Informix Functions

Table of Contents

  • ifx_affected_rows — Get number of rows affected by a query
  • ifx_blobinfile_mode — Set the default blob mode for all select queries
  • ifx_byteasvarchar — Set the default byte mode
  • ifx_close — Close Informix connection
  • ifx_connect — Open Informix server connection
  • ifx_copy_blob — Duplicates the given blob object
  • ifx_create_blob — Creates an blob object
  • ifx_create_char — Creates an char object
  • ifx_do — Execute a previously prepared SQL-statement
  • ifx_error — Returns error code of last Informix call
  • ifx_errormsg — Returns error message of last Informix call
  • ifx_fetch_row — Get row as an associative array
  • ifx_fieldproperties — List of SQL fieldproperties
  • ifx_fieldtypes — List of Informix SQL fields
  • ifx_free_blob — Deletes the blob object
  • ifx_free_char — Deletes the char object
  • ifx_free_result — Releases resources for the query
  • ifx_get_blob — Return the content of a blob object
  • ifx_get_char — Return the content of the char object
  • ifx_getsqlca — Get the contents of sqlca.sqlerrd[0..5] after a query
  • ifx_htmltbl_result — Formats all rows of a query into a HTML table
  • ifx_nullformat — Sets the default return value on a fetch row
  • ifx_num_fields — Returns the number of columns in the query
  • ifx_num_rows — Count the rows already fetched from a query
  • ifx_pconnect — Open persistent Informix connection
  • ifx_prepare — Prepare an SQL-statement for execution
  • ifx_query — Send Informix query
  • ifx_textasvarchar — Set the default text mode
  • ifx_update_blob — Updates the content of the blob object
  • ifx_update_char — Updates the content of the char object
  • ifxus_close_slob — Deletes the slob object
  • ifxus_create_slob — Creates an slob object and opens it
  • ifxus_free_slob — Deletes the slob object
  • ifxus_open_slob — Opens an slob object
  • ifxus_read_slob — Reads nbytes of the slob object
  • ifxus_seek_slob — Sets the current file or seek position
  • ifxus_tell_slob — Returns the current file or seek position
  • ifxus_write_slob — Writes a string into the slob object


Get number of rows affected by a query

  • « Informix Functions
  • ifx_blobinfile_mode »
  • PHP Manual
  • Informix Functions
  • Get number of rows affected by a query

ifx_affected_rows

(PHP 4, PHP 5 < 5.2.1)

ifx_affected_rows — Get number of rows affected by a query

Description

ifx_affected_rows ( resource $result_id ) : int

Returns the number of rows affected by a query associated with result_id.

For inserts, updates and deletes the number is the real number (sqlerrd[2]) of affected rows. For selects it is an estimate (sqlerrd[0]). Don't rely on it. The database server can never return the actual number of rows that will be returned by a SELECT because it has not even begun fetching them at this stage (just after the "PREPARE" when the optimizer has determined the query plan).

Useful after ifx_prepare() to limit queries to reasonable result sets.

Parameters

result_id

A valid result id returned by ifx_query() or ifx_prepare().

Return Values

Returns the number of rows as an integer.

Examples

Example #1 Informix affected rows

<?php
$rid = ifx_prepare("select * from emp
                     where name like " . $name, $connid);
if (! $rid) {
    /* ... error ... */
}
$rowcount = ifx_affected_rows($rid);
if ($rowcount > 1000) {
    printf ("Too many rows in result set (%d)\n<br />", $rowcount);
    die ("Please restrict your query<br />\n");
}
?>

See Also

  • ifx_num_rows() - Count the rows already fetched from a query


Set the default blob mode for all select queries

  • « ifx_affected_rows
  • ifx_byteasvarchar »
  • PHP Manual
  • Informix Functions
  • Set the default blob mode for all select queries

ifx_blobinfile_mode

(PHP 4, PHP 5 < 5.2.1)

ifx_blobinfile_mode — Set the default blob mode for all select queries

Description

ifx_blobinfile_mode ( int $mode ) : bool

Set the default blob mode for all select queries.

Parameters

mode

Mode "0" means save Byte-Blobs in memory, and mode "1" means save Byte-Blobs in a file.

Return Values

Returns TRUE on success or FALSE on failure.


Set the default byte mode

  • « ifx_blobinfile_mode
  • ifx_close »
  • PHP Manual
  • Informix Functions
  • Set the default byte mode

ifx_byteasvarchar

(PHP 4, PHP 5 < 5.2.1)

ifx_byteasvarchar — Set the default byte mode

Description

ifx_byteasvarchar ( int $mode ) : bool

Sets the default byte mode for all select-queries.

Parameters

mode

Mode "0" will return a blob id, and mode "1" will return a varchar with text content.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ifx_textasvarchar() - Set the default text mode


Close Informix connection

  • « ifx_byteasvarchar
  • ifx_connect »
  • PHP Manual
  • Informix Functions
  • Close Informix connection

ifx_close

(PHP 4, PHP 5 < 5.2.1)

ifx_close — Close Informix connection

Description

ifx_close ([ resource $link_identifier ] ) : bool

ifx_close() closes the link to an Informix database that's associated with the specified link identifier.

Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

ifx_close() will not close persistent links generated by ifx_pconnect().

Parameters

link_identifier

The link identifier. If not specified, the last opened link is assumed.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Closing a Informix connection

<?php
$conn_id = ifx_connect ("mydb@ol_srv", "itsme", "mypassword");
/* ... some queries and stuff ... */
ifx_close($conn_id);
?>

See Also

  • ifx_connect() - Open Informix server connection
  • ifx_pconnect() - Open persistent Informix connection


Open Informix server connection

  • « ifx_close
  • ifx_copy_blob »
  • PHP Manual
  • Informix Functions
  • Open Informix server connection

ifx_connect

(PHP 4, PHP 5 < 5.2.1)

ifx_connect — Open Informix server connection

Description

ifx_connect ([ string $database [, string $userid [, string $password ]]] ) : resource

ifx_connect() establishes a connection to an Informix server.

In case a second call is made to ifx_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 ifx_close().

Parameters

All of the arguments are optional, and if they're missing, defaults are taken from values supplied in php.ini (ifx.default_host for the host (Informix libraries will use INFORMIXSERVER environment value if not defined), ifx.default_user for user, ifx.default_password for the password (none if not defined).

database

The database name, as a string.

userid

The username, as a string.

password

The password, as a string.

Return Values

Returns a connection identifier on success, or FALSE on error.

Examples

Example #1 Connect to a Informix database

<?php
$conn_id = ifx_connect ("mydb@ol_srv1", "imyself", "mypassword");
?>

See Also

  • ifx_pconnect() - Open persistent Informix connection
  • ifx_close() - Close Informix connection


Duplicates the given blob object

  • « ifx_connect
  • ifx_create_blob »
  • PHP Manual
  • Informix Functions
  • Duplicates the given blob object

ifx_copy_blob

(PHP 4, PHP 5 < 5.2.1)

ifx_copy_blob — Duplicates the given blob object

Description

ifx_copy_blob ( int $bid ) : int

Duplicates the given blob object.

Parameters

bid

A BLOB identifier.

Return Values

Returns the new blob object-id, or FALSE on errors.

See Also

  • ifx_create_blob() - Creates an blob object
  • ifx_free_blob() - Deletes the blob object


Creates an blob object

  • « ifx_copy_blob
  • ifx_create_char »
  • PHP Manual
  • Informix Functions
  • Creates an blob object

ifx_create_blob

(PHP 4, PHP 5 < 5.2.1)

ifx_create_blob — Creates an blob object

Description

ifx_create_blob ( int $type , int $mode , string $param ) : int

Creates a blob object.

Parameters

type

1 = TEXT, 0 = BYTE

mode

0 = blob-object holds the content in memory, 1 = blob-object holds the content in file.

param

if mode = 0: pointer to the content, if mode = 1: pointer to the filestring.

Return Values

Returns the new BLOB object-id, or FALSE on errors.

See Also

  • ifx_copy_blob() - Duplicates the given blob object
  • ifx_free_blob() - Deletes the blob object


Creates an char object

  • « ifx_create_blob
  • ifx_do »
  • PHP Manual
  • Informix Functions
  • Creates an char object

ifx_create_char

(PHP 4, PHP 5 < 5.2.1)

ifx_create_char — Creates an char object

Description

ifx_create_char ( string $param ) : int

Creates an char object.

Parameters

param

The char content.

Return Values

Returns the new char object id, or FALSE on errors.

See Also

  • ifx_free_char() - Deletes the char object


Execute a previously prepared SQL-statement

  • « ifx_create_char
  • ifx_error »
  • PHP Manual
  • Informix Functions
  • Execute a previously prepared SQL-statement

ifx_do

(PHP 4, PHP 5 < 5.2.1)

ifx_do — Execute a previously prepared SQL-statement

Description

ifx_do ( resource $result_id ) : bool

Executes a previously prepared query or opens a cursor for it.

Does NOT free result_id on error.

Also sets the real number of ifx_affected_rows() for non-select statements for retrieval by ifx_affected_rows().

Parameters

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

Return Values

Returns TRUE on success or FALSE on failure.

See Also

Example #1 ifx_do() Example

<?php
$conn = fx_connect( "db", "user", "password" );
$result = ifx_prepare("SELECT customer_num, company FROM customer", $conn);
ifx_do($result);
?>

See Also

  • ifx_prepare() - Prepare an SQL-statement for execution


Returns error code of last Informix call

  • « ifx_do
  • ifx_errormsg »
  • PHP Manual
  • Informix Functions
  • Returns error code of last Informix call

ifx_error

(PHP 4, PHP 5 < 5.2.1)

ifx_error — Returns error code of last Informix call

Description

ifx_error ([ resource $link_identifier ] ) : string

Returns in a string one character describing the general results of a statement and both SQLSTATE and SQLCODE associated with the most recent SQL statement executed.

Parameters

link_identifier

The link identifier.

Return Values

The Informix error codes (SQLSTATE & SQLCODE) formatted as x [SQLSTATE = aa bbb SQLCODE=cccc].

where x = space : no error

E : error

N : no more data

W : warning

? : undefined

If the "x" character is anything other than space, SQLSTATE and SQLCODE describe the error in more detail.

See the Informix manual for the description of SQLSTATE and SQLCODE

See Also

  • ifx_errormsg() - Returns error message of last Informix call


Returns error message of last Informix call

  • « ifx_error
  • ifx_fetch_row »
  • PHP Manual
  • Informix Functions
  • Returns error message of last Informix call

ifx_errormsg

(PHP 4, PHP 5 < 5.2.1)

ifx_errormsg — Returns error message of last Informix call

Description

ifx_errormsg ([ int $errorcode ] ) : string

Returns the Informix error message associated with the most recent Informix error.

Parameters

errorcode

If specified, the function will return the message corresponding to the specified code.

Return Values

Return the error message, as a string.

Examples

Example #1 ifx_errormsg() example

<?php
printf("%s\n<br>", ifx_errormsg(-201));
?>

See Also

  • ifx_error() - Returns error code of last Informix call


Get row as an associative array

  • « ifx_errormsg
  • ifx_fieldproperties »
  • PHP Manual
  • Informix Functions
  • Get row as an associative array

ifx_fetch_row

(PHP 4, PHP 5 < 5.2.1)

ifx_fetch_row — Get row as an associative array

Description

ifx_fetch_row ( resource $result_id [, mixed $position ] ) : array

Fetches one row of data from the result associated with the specified result identifier.

Subsequent calls to ifx_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Parameters

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

position

An optional parameter for a "fetch" operation on "scroll" cursors: NEXT, PREVIOUS, CURRENT, FIRST, LAST or a number. If you specify a number, an "absolute" row fetch is executed. This parameter is optional, and only valid for SCROLL cursors.

Return Values

Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.

Blob columns are returned as integer blob id values for use in ifx_get_blob() unless you have used ifx_textasvarchar(1) or ifx_byteasvarchar(1), in which case blobs are returned as string values.

Examples

Example #1 Informix fetch rows

<?php
$rid = ifx_prepare ("select * from emp where name like " . $name,
                     $connid, IFX_SCROLL);
if (! $rid) {
    /* ... error ... */
}
$rowcount = ifx_affected_rows($rid);
if ($rowcount > 1000) {
    printf ("Too many rows in result set (%d)\n<br />", $rowcount);
    die ("Please restrict your query<br />\n");
}
if (! ifx_do ($rid)) {
   /* ... error ... */
}
$row = ifx_fetch_row ($rid, "NEXT");
while (is_array($row)) {
    for (reset($row); $fieldname=key($row); next($row)) {
        $fieldvalue = $row[$fieldname];
        printf ("%s = %s,", $fieldname, $fieldvalue);
    }
    printf("\n<br />");
    $row = ifx_fetch_row($rid, "NEXT");
}
ifx_free_result ($rid);
?>


List of SQL fieldproperties

  • « ifx_fetch_row
  • ifx_fieldtypes »
  • PHP Manual
  • Informix Functions
  • List of SQL fieldproperties

ifx_fieldproperties

(PHP 4, PHP 5 < 5.2.1)

ifx_fieldproperties — List of SQL fieldproperties

Description

ifx_fieldproperties ( resource $result_id ) : array

Returns the Informix SQL fieldproperties of every field in the query as an associative array. Properties are encoded as: "SQLTYPE;length;precision;scale;ISNULLABLE" where SQLTYPE = the Informix type like "SQLVCHAR" etc. and ISNULLABLE = "Y" or "N".

Parameters

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

Return Values

Returns an associative array with fieldnames as key and the SQL fieldproperties as data for a query with result_id. Returns FALSE on errors.

Examples

Example #1 Informix SQL fieldproperties

<?php
$properties = ifx_fieldproperties($resultid);
if (!isset($properties)) {
    /* ... error ... */
}
foreach ($properties as $fname => $val) {
    echo "$fname:\t property = $val\n";
}
?>

See Also

  • ifx_fieldtypes() - List of Informix SQL fields


List of Informix SQL fields

  • « ifx_fieldproperties
  • ifx_free_blob »
  • PHP Manual
  • Informix Functions
  • List of Informix SQL fields

ifx_fieldtypes

(PHP 4, PHP 5 < 5.2.1)

ifx_fieldtypes — List of Informix SQL fields

Description

ifx_fieldtypes ( resource $result_id ) : array

Returns an associative array with fieldnames as key and the SQL fieldtypes as data for the query associated with result_id.

Parameters

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

Return Values

Returns an associative array with fieldnames as key and the SQL fieldtypes as data for query with result_id. Returns FALSE on error.

Examples

Example #1 Fieldnames and SQL fieldtypes

<?php
$types = ifx_fieldtypes($resultid);
if (is_array($types)) {
    foreach ($types as $fname => $val) {
        echo "$fname:\t type = $val\n";
    }
}
?>

See Also

  • ifx_fieldproperties() - List of SQL fieldproperties


Deletes the blob object

  • « ifx_fieldtypes
  • ifx_free_char »
  • PHP Manual
  • Informix Functions
  • Deletes the blob object

ifx_free_blob

(PHP 4, PHP 5 < 5.2.1)

ifx_free_blob — Deletes the blob object

Description

ifx_free_blob ( int $bid ) : bool

Deletes the blobobject for the given blob object-id.

Parameters

bid

The BLOB object id.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ifx_create_blob() - Creates an blob object


Deletes the char object

  • « ifx_free_blob
  • ifx_free_result »
  • PHP Manual
  • Informix Functions
  • Deletes the char object

ifx_free_char

(PHP 4, PHP 5 < 5.2.1)

ifx_free_char — Deletes the char object

Description

ifx_free_char ( int $bid ) : bool

Deletes the charobject for the given char object-id.

Parameters

bid

The char object id.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ifx_create_char() - Creates an char object


Releases resources for the query

  • « ifx_free_char
  • ifx_get_blob »
  • PHP Manual
  • Informix Functions
  • Releases resources for the query

ifx_free_result

(PHP 4, PHP 5 < 5.2.1)

ifx_free_result — Releases resources for the query

Description

ifx_free_result ( resource $result_id ) : bool

Releases resources for the query associated with result_id.

Parameters

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ifx_do() - Execute a previously prepared SQL-statement


Return the content of a blob object

  • « ifx_free_result
  • ifx_get_char »
  • PHP Manual
  • Informix Functions
  • Return the content of a blob object

ifx_get_blob

(PHP 4, PHP 5 < 5.2.1)

ifx_get_blob — Return the content of a blob object

Description

ifx_get_blob ( int $bid ) : string

Returns the content of the blob object.

Parameters

bid

The BLOB object id.

Return Values

The contents of the BLOB as a string, or FALSE on errors.

See Also

  • ifx_get_char() - Return the content of the char object


Return the content of the char object

  • « ifx_get_blob
  • ifx_getsqlca »
  • PHP Manual
  • Informix Functions
  • Return the content of the char object

ifx_get_char

(PHP 4, PHP 5 < 5.2.1)

ifx_get_char — Return the content of the char object

Description

ifx_get_char ( int $bid ) : string

Returns the content of the char object.

Parameters

bid

The char object-id.

Return Values

Returns the contents as a string, or FALSE on errors.

See Also

  • ifx_get_blob() - Return the content of a blob object


Get the contents of sqlca.sqlerrd[0..5] after a query

  • « ifx_get_char
  • ifx_htmltbl_result »
  • PHP Manual
  • Informix Functions
  • Get the contents of sqlca.sqlerrd[0..5] after a query

ifx_getsqlca

(PHP 4, PHP 5 < 5.2.1)

ifx_getsqlca — Get the contents of sqlca.sqlerrd[0..5] after a query

Description

ifx_getsqlca ( resource $result_id ) : array

Returns a pseudo-row with sqlca.sqlerrd[0] ... sqlca.sqlerrd[5] after the query associated with result_id.

For inserts, updates and deletes the values returned are those as set by the server after executing the query. This gives access to the number of affected rows and the serial insert value. For SELECTs the values are those saved after the PREPARE statement. This gives access to the *estimated* number of affected rows. The use of this function saves the overhead of executing a SELECT dbinfo('sqlca.sqlerrdx') query, as it retrieves the values that were saved by the ifx driver at the appropriate moment.

Parameters

result_id

result_id is a valid result id returned by ifx_query() or ifx_prepare() (select type queries only!).

Return Values

Returns an associative array with the following entries: sqlerrd0, sqlerrd1, sqlerrd2, sqlerrd3, sqlerrd4 and sqlerrd5.

Examples

Example #1 Retrieve Informix sqlca.sqlerrd[x] values

<?php
/* assume the first column of 'sometable' is a serial */
$qid = ifx_query("insert into sometable
                  values (0, '2nd column', 'another column') ", $connid);
if (!$qid) {
    /* ... error ... */
}
$sqlca = ifx_getsqlca($qid);
$serial_value = $sqlca["sqlerrd1"];
echo "The serial value of the inserted row is : $serial_value<br />\n";
?>


Formats all rows of a query into a HTML table

  • « ifx_getsqlca
  • ifx_nullformat »
  • PHP Manual
  • Informix Functions
  • Formats all rows of a query into a HTML table

ifx_htmltbl_result

(PHP 4, PHP 5 < 5.2.1)

ifx_htmltbl_result — Formats all rows of a query into a HTML table

Description

ifx_htmltbl_result ( resource $result_id [, string $html_table_options ] ) : int

Formats and prints all rows of the result_id query into a HTML table.

Parameters

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

html_table_options

This optional argument is a string of <table> tag options.

Return Values

Returns the number of fetched rows, or FALSE on errors.

Examples

Example #1 Informix results as HTML table

<?php
$rid = ifx_prepare ("select * from emp where name like " . $name,
                     $connid, IFX_SCROLL);
if (! $rid) {
    /* ... error ... */
}
$rowcount = ifx_affected_rows ($rid);
if ($rowcount > 1000) {
    printf ("Too many rows in result set (%d)\n<br />", $rowcount);
    die ("Please restrict your query<br />\n");
}
if (! ifx_do($rid)) {
    /* ... error ... */
}

ifx_htmltbl_result ($rid, "border=\"2\"");

ifx_free_result($rid);
?>


Sets the default return value on a fetch row

  • « ifx_htmltbl_result
  • ifx_num_fields »
  • PHP Manual
  • Informix Functions
  • Sets the default return value on a fetch row

ifx_nullformat

(PHP 4, PHP 5 < 5.2.1)

ifx_nullformat — Sets the default return value on a fetch row

Description

ifx_nullformat ( int $mode ) : bool

Sets the default return value of a NULL-value on a fetch row.

Parameters

mode

Mode "0" returns "", and mode "1" returns "NULL".

Return Values

Returns TRUE on success or FALSE on failure.


Returns the number of columns in the query

  • « ifx_nullformat
  • ifx_num_rows »
  • PHP Manual
  • Informix Functions
  • Returns the number of columns in the query

ifx_num_fields

(PHP 4, PHP 5 < 5.2.1)

ifx_num_fields — Returns the number of columns in the query

Description

ifx_num_fields ( resource $result_id ) : int

After preparing or executing a query, this call gives you the number of columns in the query.

Parameters

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

Return Values

Returns the number of columns in query for result_id, or FALSE on errors.

Examples

Example #1 ifx_num_fields() Example

<?php
$conn_id = ifx_connect("db", "user", "password");
$res_id = ifx_query("select * from systables", $conn_id);
echo ifx_num_fields($res_id);
?>

See Also

  • ifx_num_rows() - Count the rows already fetched from a query


Count the rows already fetched from a query

  • « ifx_num_fields
  • ifx_pconnect »
  • PHP Manual
  • Informix Functions
  • Count the rows already fetched from a query

ifx_num_rows

(PHP 4, PHP 5 < 5.2.1)

ifx_num_rows — Count the rows already fetched from a query

Description

ifx_num_rows ( resource $result_id ) : int

Gives the number of rows fetched so far for a query with result_id after a ifx_query() or ifx_do() query.

Parameters

result_id

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

Return Values

Returns the number of fetched rows or FALSE on errors.

See Also

  • ifx_num_fields() - Returns the number of columns in the query


Open persistent Informix connection

  • « ifx_num_rows
  • ifx_prepare »
  • PHP Manual
  • Informix Functions
  • Open persistent Informix connection

ifx_pconnect

(PHP 4, PHP 5 < 5.2.1)

ifx_pconnect — Open persistent Informix connection

Description

ifx_pconnect ([ string $database [, string $userid [, string $password ]]] ) : resource

ifx_pconnect() acts very much like ifx_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 (ifx_close() will not close links established by ifx_pconnect()).

This type of links is therefore called 'persistent'.

Parameters

All of the arguments are optional, and if they're missing, defaults are taken from values supplied in php.ini (ifx.default_host for the host (Informix libraries will use INFORMIXSERVER environment value if not defined), ifx.default_user for user, ifx.default_password for the password (none if not defined).

database

The database name, as a string.

userid

The username, as a string.

password

The password, as a string.

Return Values

Returns: valid Informix persistent link identifier on success, or FALSE on errors.

See Also

  • ifx_connect() - Open Informix server connection


Prepare an SQL-statement for execution

  • « ifx_pconnect
  • ifx_query »
  • PHP Manual
  • Informix Functions
  • Prepare an SQL-statement for execution

ifx_prepare

(PHP 4, PHP 5 < 5.2.1)

ifx_prepare — Prepare an SQL-statement for execution

Description

ifx_prepare ( string $query , resource $link_identifier [, int $cursor_def ], mixed $blobidarray ) : resource

Prepares a query for later use with ifx_do().

For "select-type" queries a cursor is declared and opened. Non-select queries are "execute immediate".

For either query type the number of (estimated or real) affected rows is saved for retrieval by ifx_affected_rows().

If the contents of the TEXT (or BYTE) column allow it, you can also use ifx_textasvarchar(1) and ifx_byteasvarchar(1). This allows you to treat TEXT (or BYTE) columns just as if they were ordinary (but long) VARCHAR columns for select queries, and you don't need to bother with blob id's.

With ifx_textasvarchar(0) or ifx_byteasvarchar(0) (the default situation), select queries will return BLOB columns as blob id's (integer value). You can get the value of the blob as a string or file with the blob functions (see below).

Parameters

query

The query string.

link_identifier

The link identifier.

cursor_def

This optional parameter allows you to make this a scroll and/or hold cursor. It's a bitmask and can be either IFX_SCROLL, IFX_HOLD, or both or'ed together.

blobidarray

If you have BLOB (BYTE or TEXT) columns in the query, you can add a blobidarray parameter containing the corresponding "blob ids", and you should replace those columns with a "?" in the query text.

Return Values

Returns a valid result identifier for use by ifx_do(), or FALSE on errors.

See Also

  • ifx_do() - Execute a previously prepared SQL-statement


Send Informix query

  • « ifx_prepare
  • ifx_textasvarchar »
  • PHP Manual
  • Informix Functions
  • Send Informix query

ifx_query

(PHP 4, PHP 5 < 5.2.1)

ifx_query — Send Informix query

Description

ifx_query ( string $query , resource $link_identifier [, int $cursor_type [, mixed $blobidarray ]] ) : resource

Sends a query to the currently active database on the server that's associated with the specified link identifier.

For "select-type" queries a cursor is declared and opened. Non-select queries are "execute immediate".

For either query type the number of (estimated or real) affected rows is saved for retrieval by ifx_affected_rows().

If the contents of the TEXT (or BYTE) column allow it, you can also use ifx_textasvarchar(1) and ifx_byteasvarchar(1). This allows you to treat TEXT (or BYTE) columns just as if they were ordinary (but long) VARCHAR columns for select queries, and you don't need to bother with blob id's.

With ifx_textasvarchar(0) or ifx_byteasvarchar(0) (the default situation), select queries will return BLOB columns as blob id's (integer value). You can get the value of the blob as a string or file with the blob functions (see below).

Parameters

query

The query string.

link_identifier

The link identifier.

cursor_def

This optional parameter allows you to make this a scroll and/or hold cursor. It's a bitmask and can be either IFX_SCROLL, IFX_HOLD, or both or'ed together. I you omit this parameter the cursor is a normal sequential cursor.

blobidarray

If you have BLOB (BYTE or TEXT) columns in the query, you can add a blobidarray parameter containing the corresponding "blob ids", and you should replace those columns with a "?" in the query text.

Return Values

Returns valid Informix result identifier on success, or FALSE on errors.

Examples

Example #1 Show all rows of the "orders" table as a HTML table

<?php
ifx_textasvarchar(1);      // use "text mode" for blobs
$res_id = ifx_query("select * from orders", $conn_id);
if (! $res_id) {
    printf("Can't select orders : %s\n<br />%s<br />\n", ifx_error(), ifx_errormsg());
    die;
}
ifx_htmltbl_result($res_id, "border=\"1\"");
ifx_free_result($res_id);
?>

Example #2 Insert some values into the "catalog" table

<?php

// create blob id's for a byte and text column
$textid = ifx_create_blob(0, 0, "Text column in memory");
$byteid = ifx_create_blob(1, 0, "Byte column in memory");

// store blob id's in a blobid array
$blobidarray[] = $textid;
$blobidarray[] = $byteid;

// launch query
$query = "insert into catalog (stock_num, manu_code, " .
         "cat_descr,cat_picture) values(1,'HRO',?,?)";
$res_id = ifx_query($query, $conn_id, $blobidarray);
if (! $res_id) {
    /* ... error ... */
}

// free result id
ifx_free_result($res_id);
?>

See Also

  • ifx_connect() - Open Informix server connection


Set the default text mode

  • « ifx_query
  • ifx_update_blob »
  • PHP Manual
  • Informix Functions
  • Set the default text mode

ifx_textasvarchar

(PHP 4, PHP 5 < 5.2.1)

ifx_textasvarchar — Set the default text mode

Description

ifx_textasvarchar ( int $mode ) : bool

Sets the default text mode for all select-queries.

Parameters

mode

Mode "0" will return a blob id, and mode "1" will return a varchar with text content.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ifx_byteasvarchar() - Set the default byte mode


Updates the content of the blob object

  • « ifx_textasvarchar
  • ifx_update_char »
  • PHP Manual
  • Informix Functions
  • Updates the content of the blob object

ifx_update_blob

(PHP 4, PHP 5 < 5.2.1)

ifx_update_blob — Updates the content of the blob object

Description

ifx_update_blob ( int $bid , string $content ) : bool

Updates the content of the blob object for the given blob object bid.

Parameters

bid

A BLOB object identifier.

content

The new data, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ifx_update_char() - Updates the content of the char object


Updates the content of the char object

  • « ifx_update_blob
  • ifxus_close_slob »
  • PHP Manual
  • Informix Functions
  • Updates the content of the char object

ifx_update_char

(PHP 4, PHP 5 < 5.2.1)

ifx_update_char — Updates the content of the char object

Description

ifx_update_char ( int $bid , string $content ) : bool

Updates the content of the char object for the given char object bid.

Parameters

bid

A char object identifier.

content

The new data, as a string.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ifx_update_blob() - Updates the content of the blob object


Deletes the slob object

  • « ifx_update_char
  • ifxus_create_slob »
  • PHP Manual
  • Informix Functions
  • Deletes the slob object

ifxus_close_slob

(PHP 4, PHP 5 < 5.2.1)

ifxus_close_slob — Deletes the slob object

Description

ifxus_close_slob ( int $bid ) : bool

Deletes the slob object on the given slob object-id bid.

Parameters

bid

An existing slob id.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ifxus_open_slob() - Opens an slob object


Creates an slob object and opens it

  • « ifxus_close_slob
  • ifxus_free_slob »
  • PHP Manual
  • Informix Functions
  • Creates an slob object and opens it

ifxus_create_slob

(PHP 4, PHP 5 < 5.2.1)

ifxus_create_slob — Creates an slob object and opens it

Description

ifxus_create_slob ( int $mode ) : int

Creates an slob object and opens it.

Parameters

mode

A combination of IFX_LO_RDONLY, IFX_LO_WRONLY, IFX_LO_APPEND IFX_LO_RDWR, IFX_LO_BUFFER, IFX_LO_NOBUFFER.

Return Values

Return the new slob object-id, or FALSE on errors.

See Also

  • ifxus_close_slob() - Deletes the slob object
  • ifxus_free_slob() - Deletes the slob object


Deletes the slob object

  • « ifxus_create_slob
  • ifxus_open_slob »
  • PHP Manual
  • Informix Functions
  • Deletes the slob object

ifxus_free_slob

(PHP 4, PHP 5 < 5.2.1)

ifxus_free_slob — Deletes the slob object

Description

ifxus_free_slob ( int $bid ) : bool

Deletes the slob object.

Parameters

bid

An existing slob id.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ifxus_close_slob() - Deletes the slob object


Opens an slob object

  • « ifxus_free_slob
  • ifxus_read_slob »
  • PHP Manual
  • Informix Functions
  • Opens an slob object

ifxus_open_slob

(PHP 4, PHP 5 < 5.2.1)

ifxus_open_slob — Opens an slob object

Description

ifxus_open_slob ( int $bid , int $mode ) : int

Opens an slob object. bid should be an existing slob id.

Parameters

bid

An existing slob id.

mode

A combination of IFX_LO_RDONLY, IFX_LO_WRONLY, IFX_LO_APPEND IFX_LO_RDWR, IFX_LO_BUFFER, IFX_LO_NOBUFFER.

Return Values

Returns the new slob object-id, or FALSE on errors.

See Also

  • ifxus_close_slob() - Deletes the slob object
  • ifxus_free_slob() - Deletes the slob object


Reads nbytes of the slob object

  • « ifxus_open_slob
  • ifxus_seek_slob »
  • PHP Manual
  • Informix Functions
  • Reads nbytes of the slob object

ifxus_read_slob

(PHP 4, PHP 5 < 5.2.1)

ifxus_read_slob — Reads nbytes of the slob object

Description

ifxus_read_slob ( int $bid , int $nbytes ) : string

Reads nbytes of the slob object.

Parameters

bid

An existing slob id.

nbytes

The number of bytes to read.

Return Values

Returns the slob contents as a string, or FALSE on errors.

See Also

  • ifxus_write_slob() - Writes a string into the slob object


Sets the current file or seek position

  • « ifxus_read_slob
  • ifxus_tell_slob »
  • PHP Manual
  • Informix Functions
  • Sets the current file or seek position

ifxus_seek_slob

(PHP 4, PHP 5 < 5.2.1)

ifxus_seek_slob — Sets the current file or seek position

Description

ifxus_seek_slob ( int $bid , int $mode , int $offset ) : int

Sets the current file or seek position of an open slob object.

Parameters

bid

An existing slob id.

mode

0 = LO_SEEK_SET, 1 = LO_SEEK_CUR, 2 = LO_SEEK_END.

offset

A byte offset.

Return Values

Returns the seek position as an integer, or FALSE on errors.

See Also

  • ifxus_tell_slob() - Returns the current file or seek position


Returns the current file or seek position

  • « ifxus_seek_slob
  • ifxus_write_slob »
  • PHP Manual
  • Informix Functions
  • Returns the current file or seek position

ifxus_tell_slob

(PHP 4, PHP 5 < 5.2.1)

ifxus_tell_slob — Returns the current file or seek position

Description

ifxus_tell_slob ( int $bid ) : int

Returns the current file or seek position of an open slob object

Parameters

bid

An existing slob id.

Return Values

Returns the seek position as an integer, or FALSE on errors.

See Also

  • ifxus_seek_slob() - Sets the current file or seek position


Writes a string into the slob object

  • « ifxus_tell_slob
  • Ingres »
  • PHP Manual
  • Informix Functions
  • Writes a string into the slob object

ifxus_write_slob

(PHP 4, PHP 5 < 5.2.1)

ifxus_write_slob — Writes a string into the slob object

Description

ifxus_write_slob ( int $bid , string $content ) : int

Writes a string into the slob object.

Parameters

bid

An existing slob id.

content

The content to write, as a string.

Return Values

Returns the bytes written as an integer, or FALSE on errors.

See Also

  • ifxus_read_slob() - Reads nbytes of the slob object


Ingres DBMS, EDBC, and Enterprise Access Gateways

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
  • Ingres Functions
    • ingres_autocommit_state — Test if the connection is using autocommit
    • ingres_autocommit — Switch autocommit on or off
    • ingres_charset — Returns the installation character set
    • ingres_close — Close an Ingres database connection
    • ingres_commit — Commit a transaction
    • ingres_connect — Open a connection to an Ingres database
    • ingres_cursor — Get a cursor name for a given result resource
    • ingres_errno — Get the last Ingres error number generated
    • ingres_error — Get a meaningful error message for the last error generated
    • ingres_errsqlstate — Get the last SQLSTATE error code generated
    • ingres_escape_string — Escape special characters for use in a query
    • ingres_execute — Execute a prepared query
    • ingres_fetch_array — Fetch a row of result into an array
    • ingres_fetch_assoc — Fetch a row of result into an associative array
    • ingres_fetch_object — Fetch a row of result into an object
    • ingres_fetch_proc_return — Get the return value from a procedure call
    • ingres_fetch_row — Fetch a row of result into an enumerated array
    • ingres_field_length — Get the length of a field
    • ingres_field_name — Get the name of a field in a query result
    • ingres_field_nullable — Test if a field is nullable
    • ingres_field_precision — Get the precision of a field
    • ingres_field_scale — Get the scale of a field
    • ingres_field_type — Get the type of a field in a query result
    • ingres_free_result — Free the resources associated with a result identifier
    • ingres_next_error — Get the next Ingres error
    • ingres_num_fields — Get the number of fields returned by the last query
    • ingres_num_rows — Get the number of rows affected or returned by a query
    • ingres_pconnect — Open a persistent connection to an Ingres database
    • ingres_prepare — Prepare a query for later execution
    • ingres_query — Send an SQL query to Ingres
    • ingres_result_seek — Set the row position before fetching data
    • ingres_rollback — Roll back a transaction
    • ingres_set_environment — Set environment features controlling output options
    • ingres_unbuffered_query — Send an unbuffered SQL query to Ingres


Introduction

The Ingres driver for PHP enables you to connect to and query the Ingres DBMS, EDBC, and Enterprise Access Gateways.

Note:

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.1.0.


Requirements

To use or build the PHP extension for Ingres you must have a working Ingres client environment. You can download the client software for Ingres from » http://esd.ingres.com/.


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

You can download the DLL for this PECL extension from » http://esd.ingres.com/product/drivers/PHP/.

To have these functions available, you must » download and compile this extension, enabling Ingres support using the --with-ingres[=DIR] option, where DIR is the Ingres base directory. If the II_SYSTEM environment variable is not set correctly you may need to use --with-ingres=DIR to specify your Ingres installation directory.

PHP code written for version 2.x and later is not backward-compatible with earlier versions of this PHP extension. However, it is possible to run two incompatible releases within the same PHP environment using the --enable-ingres2 option. This configuration option renames the extension to ingres2, changing function names, configuration settings, and constants. For example, with this option enabled, ingres_connect() becomes ingres2_connect().

To use this extension the system environment variable II_SYSTEM must be defined. Linux and UNIX users will also need to define the shared library search path, for example, LD_LIBRARY_PATH. When used with the Apache web server these variables must be set explicitly in the startup script for Apache. In addition, the PassEnv directive is required for the Ingres extension to load the correct shared libraries. For example:

Example #1 Example usage of PassEnv for Ingres

<IfModule mod_env.c>
    PassEnv II_SYSTEM
    PassEnv LD_LIBRARY_PATH
</IfModule>

Note:

For example configurations for different web servers and operating systems see » http://community.ingres.com/wiki/Ingres_Articles#Ingres_and_Web_Servers.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Ingres configuration options
Name | Default | Changeable | Changelog
ingres.allow_persistent | "1" | PHP_INI_SYSTEM | Available since ingres 1.0.0
ingres.array_index_start | "1" | PHP_INI_ALL | Available since ingres 1.4.0.
ingres.auto | "1" | PHP_INI_ALL | Available since ingres 2.0.0.
ingres.blob_segment_length | "4096" | PHP_INI_ALL | Available since ingres 1.2.0.
ingres.cursor_mode | "0" | PHP_INI_ALL | Available since ingres 1.1.0.
ingres.default_database | NULL | PHP_INI_ALL | Available since ingres 1.0.0
ingres.default_password | NULL | PHP_INI_ALL | Available since ingres 1.0.0
ingres.default_user | NULL | PHP_INI_ALL | Available since ingres 1.0.0
ingres.describe | 1 | PHP_INI_ALL | Available since ingres 2.1.0
ingres.fetch_buffer_size | 100 | PHP_INI_ALL | Available since ingres 2.1.0
ingres.max_links | "-1" | PHP_INI_SYSTEM | Available since ingres 1.0.0
ingres.max_persistent | "-1" | PHP_INI_SYSTEM | Available since ingres 1.0.0
ingres.reuse_connection | "1" | PHP_INI_ALL | Available since ingres 2.0.0
ingres.scrollable | "1" | PHP_INI_ALL | Available since ingres 2.0.0.
ingres.trace | "0" | PHP_INI_ALL | Available since ingres 2.0.0.
ingres.trace_connect | "0" | PHP_INI_ALL | Available since ingres 1.2.1.
ingres.utf8 | "1" | PHP_INI_ALL | Available since ingres 2.0.0.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

ingres.allow_persistent boolean

Specifies whether to allow persistent connections to Ingres

ingres.array_index_start integer

Specifies the start value for an integer key for arrays generated by ingres_fetch_row() or ingres_fetch_array(). By default ingres.array_index_start is set to 1. If you wish to make the ingres extension behave like other database extensions set this configuration option to 0.

ingres.auto boolean

Enables or disables autocommit emulation. Ingres cannot have multiple cursors open with autocommit enabled. When enabled, the driver emulates autocommit.

ingres.blob_segment_length integer

Specifies the amount of memory to use when reading BLOB data, in bytes

ingres.cursor_mode integer

Specifies the default mode for cursors opened with ingres_prepare(). Valid values are INGRES_CURSOR_UPDATE or INGRES_CURSOR_READONLY.

ingres.default_database string

Specifies the default database name to use when connecting to the database server if no other name is specified. Does not apply in SQL safe mode.

ingres.default_password string

Specifies the default password to use when connecting to the database server if no other name is specified. Does not apply in SQL safe mode.

ingres.default_user string

Specifies the default user name to use when connecting to the database server if no other name is specified. Does not apply in SQL safe mode.

ingres.describe boolean

Enables the use of DESCRIBE INPUT to determine the expected data types for queries that use parameters. Available with Ingres 9.1.0 and later. When disabled, queries that have parameters passed may need to manually describe the types of those parameters using the types parameter in ingres_query().

Note:

Enabling this feature with ingres_query() will cause additional communications traffic between this extension and the server. To minimize this additional traffic, use ingres_prepare() and ingres_execute().

ingres.fetch_buffer_size integer

Specifies the number of pre-fetch rows that ingres_fetch_array(), ingres_fetch_object() and ingres_fetch_row() will try and fetch in one fetch operation.

ingres.max_links integer

Specifies the maximum number of Ingres sessions allowed per process or thread. The number of sessions should not exceed the total number of connected sessions configured within Ingres.

ingres.max_persistent integer

Specifies the maximum number of persistent Ingres sessions allowed per process or thread. The number of sessions should not exceed the total number of connected sessions configured within Ingres.

ingres.reuse_connection boolean

Reuses an existing active connection if connecting to the same database with the same user name

ingres.scrollable boolean

Enables support for scrollable cursors. When fetching CLOB or BLOB data, this should be set to FALSE. Available with Ingres 9.2.0 or later.

ingres.trace boolean

Enables simple tracing using E_NOTICE messages

ingres.trace_connect boolean

Prints E_NOTICE messages during ingres_connect() or ingres_pconnect() calls

ingres.utf8 boolean

Assumes that strings being passed to National Character column types (NVARCHAR or NCHAR) are using UTF8 encoding and converts them to UTF16 for the server


Resource Types

ingres_connect() and ingres_pconnect() return an Ingres link identifier.

ingres_query() and ingres_unbuffered_query() return an Ingres 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.

INGRES_ASSOC (integer)
Columns are returned into the array having the fieldname as the array index. Used with ingres_fetch_array().
INGRES_NUM (integer)
Columns are returned into the array having a numerical index to the fields. By default this index starts at 1, the first field in the result. To change this value, see ingres.array_index_start. Used with ingres_fetch_array().
INGRES_BOTH (integer)
Columns are returned into the array having both a numerical index and the fieldname as the array index. Used with ingres_fetch_array().
INGRES_EXT_VERSION (string)
Specifies the version of the Ingres Extension. Available since version 1.2.0 of the PECL extension.
INGRES_API_VERSION (integer)
Specifies the version of Ingres OpenAPI that the extension was built against. Available since version 1.2.0 of the PECL extension.
INGRES_CURSOR_READONLY (integer)
Specifies that Ingres cursors should be opened in "readonly" mode. Available since version 1.2.0 of the PECL extension. Used with ingres.cursor_mode.
INGRES_CURSOR_UPDATE (integer)
Specifies that Ingres cursors should be opened "for update." Available since version 1.2.0 of the PECL extension. Used with ingres.cursor_mode.
INGRES_DATE_MULTINATIONAL (integer)
Equivalent to the II_DATE_FORMAT setting of MULTINATIONAL. Available since version 1.2.0 of the PECL extension. Used with ingres_connect(), ingres_pconnect() and ingres_set_environment(). See options in ingres_set_environment().
INGRES_DATE_MULTINATIONAL4 (integer)
Equivalent to the II_DATE_FORMAT setting of MULTINATIONAL4. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
INGRES_DATE_FINNISH (integer)
Equivalent to the II_DATE_FORMAT setting of FINNISH. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
INGRES_DATE_ISO (integer)
Equivalent to the II_DATE_FORMAT setting of ISO. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
INGRES_DATE_ISO4 (integer)
Equivalent to the II_DATE_FORMAT setting of ISO4. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
INGRES_DATE_GERMAN (integer)
Equivalent to the II_DATE_FORMAT setting of GERMAN. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
INGRES_DATE_MDY (integer)
Equivalent to the II_DATE_FORMAT setting of MDY. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
INGRES_DATE_DMY (integer)
Equivalent to the II_DATE_FORMAT setting of DMY. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
INGRES_DATE_YMD (integer)
Equivalent to the II_DATE_FORMAT setting of YMD. Available since version 1.2.0 of the PECL extension.
Used with
ingres_connect(), ingres_pconnect()
and ingres_set_environment(). See options
in ingres_set_environment().
INGRES_MONEY_LEADING (integer)
Specifies the currency character that should be placed at the start of a money value. Equivalent to setting II_MONEY_FORMAT to "L:". Available since version 1.2.0 of the PECL extension. Used with ingres_connect(), ingres_pconnect() and ingres_set_environment(). See options in ingres_set_environment().
INGRES_MONEY_TRAILING (integer)
Specifies the currency character that should be placed at the end of a money value. Equivalent to setting II_MONEY_FORMAT to "T:". Available since version 1.2.0 of the PECL extension. Used with ingres_connect(), ingres_pconnect() and ingres_set_environment(). See options in ingres_set_environment().
INGRES_STRUCTURE_BTREE (integer)
Specifies the default table or index structure to BTREE when used in combination with the
options or index_structure option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().
INGRES_STRUCTURE_CBTREE (integer)
Specifies the default table or index structure to COMPRESSED BTREE when used in combination with the
options or index_structure option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().
INGRES_STRUCTURE_HASH (integer)
Specifies the default table or index structure to HASH when used in combination with the
options or index_structure option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().
INGRES_STRUCTURE_CHASH (integer)
Specifies the default table or index structure to COMPRESSED HASH when used in combination with the
options or index_structure option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().
INGRES_STRUCTURE_HEAP (integer)
Specifies the default table structure to HEAP when used in combination with the
options option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().
INGRES_STRUCTURE_CHEAP (integer)
Specifies the default table structure to COMPRESSED HEAP when used in combination with the
options option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().
INGRES_STRUCTURE_ISAM (integer)
Specifies the default table or index structure to ISAM when used in combination with the
options or index_structure option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().
INGRES_STRUCTURE_CISAM (integer)
Specifies the default table or index structure to COMPRESSED ISAM when used in combination with the
options or index_structure option when connecting. Available since version 1.4.0 of the PECL extension.
Used with ingres_connect() and
ingres_pconnect(). See options
in ingres_connect().


  • « Predefined Constants
  • Basic usage »
  • PHP Manual
  • Ingres
  • Examples

Examples

Table of Contents

  • Basic usage


Basic usage

The following simple example shows how to connect to an Ingres database, execute a query, print resulting rows and disconnect from the database.

Example #1 Simple Ingres Example

<?php
// Connecting, selecting database
$link = ingres_connect("database", "user", "password")
    or die("Could not connect: " . ingres_error($link));
echo "Connected successfully";

// Select from a table that exists in all Ingres databases
$query = "SELECT * FROM iitables";
$result = ingres_query($link,$query) or die("Query failed: " .
ingres_error($link));

// Print results in HTML
// relid - table name
// relowner - table owner
echo "<table>\n";
while ($iitables = ingres_fetch_object($result)) {
    echo "\t<tr>\n";
    echo "\t\t<td>" . $iitables->relid . "</td>\n";
    echo "\t\t<td>" . $iitables->relowner . "</td>\n";
    echo "\t</tr>\n";
}
echo "</table>\n";

// Free results
ingres_free_result($result);

// Commit transaction
ingres_commit($link);

// Closing connection
ingres_close($link);
?>


Ingres Functions

Table of Contents

  • ingres_autocommit_state — Test if the connection is using autocommit
  • ingres_autocommit — Switch autocommit on or off
  • ingres_charset — Returns the installation character set
  • ingres_close — Close an Ingres database connection
  • ingres_commit — Commit a transaction
  • ingres_connect — Open a connection to an Ingres database
  • ingres_cursor — Get a cursor name for a given result resource
  • ingres_errno — Get the last Ingres error number generated
  • ingres_error — Get a meaningful error message for the last error generated
  • ingres_errsqlstate — Get the last SQLSTATE error code generated
  • ingres_escape_string — Escape special characters for use in a query
  • ingres_execute — Execute a prepared query
  • ingres_fetch_array — Fetch a row of result into an array
  • ingres_fetch_assoc — Fetch a row of result into an associative array
  • ingres_fetch_object — Fetch a row of result into an object
  • ingres_fetch_proc_return — Get the return value from a procedure call
  • ingres_fetch_row — Fetch a row of result into an enumerated array
  • ingres_field_length — Get the length of a field
  • ingres_field_name — Get the name of a field in a query result
  • ingres_field_nullable — Test if a field is nullable
  • ingres_field_precision — Get the precision of a field
  • ingres_field_scale — Get the scale of a field
  • ingres_field_type — Get the type of a field in a query result
  • ingres_free_result — Free the resources associated with a result identifier
  • ingres_next_error — Get the next Ingres error
  • ingres_num_fields — Get the number of fields returned by the last query
  • ingres_num_rows — Get the number of rows affected or returned by a query
  • ingres_pconnect — Open a persistent connection to an Ingres database
  • ingres_prepare — Prepare a query for later execution
  • ingres_query — Send an SQL query to Ingres
  • ingres_result_seek — Set the row position before fetching data
  • ingres_rollback — Roll back a transaction
  • ingres_set_environment — Set environment features controlling output options
  • ingres_unbuffered_query — Send an unbuffered SQL query to Ingres


Test if the connection is using autocommit

  • « Ingres Functions
  • ingres_autocommit »
  • PHP Manual
  • Ingres Functions
  • Test if the connection is using autocommit

ingres_autocommit_state

(PECL ingres >= 2.0.0)

ingres_autocommit_state — Test if the connection is using autocommit

Description

ingres_autocommit_state ( resource $link ) : bool

ingres_autocommit_state() is called to determine whether the current link has autocommit enabled or not.

Parameters

link

The connection link identifier

Return Values

Returns TRUE if autocommit is enabled or FALSE when autocommit is disabled

See Also

  • ingres_autocommit() - Switch autocommit on or off
  • ingres_query() - Send an SQL query to Ingres


Switch autocommit on or off

  • « ingres_autocommit_state
  • ingres_charset »
  • PHP Manual
  • Ingres Functions
  • Switch autocommit on or off

ingres_autocommit

(PHP 4 >= 4.0.2, PHP 5 < 5.1.0, PECL ingres >= 1.0.0)

ingres_autocommit — Switch autocommit on or off

Description

ingres_autocommit ( resource $link ) : bool

ingres_autocommit() is called before opening a transaction (before the first call to ingres_query() or just after a call to ingres_rollback() or ingres_commit()) to switch the autocommit mode of the server on or off (when the script begins the autocommit mode is off).

When autocommit mode is on, every query is automatically committed by the server, as if ingres_commit() was called after every call to ingres_query(). To see if autocommit is enabled use, ingres_autocommit_state().

By default Ingres will rollback any uncommitted transactions at the end of a request. Use this function or ingres_commit() to ensure your data is committed to the database.

Parameters

link

The connection link identifier

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ingres_autocommit_state() - Test if the connection is using autocommit
  • ingres_query() - Send an SQL query to Ingres
  • ingres_rollback() - Roll back a transaction
  • ingres_commit() - Commit a transaction


Returns the installation character set

  • « ingres_autocommit
  • ingres_close »
  • PHP Manual
  • Ingres Functions
  • Returns the installation character set

ingres_charset

(PECL ingres >= 2.1.0)

ingres_charset — Returns the installation character set

Description

ingres_charset ( resource $link ) : string

ingres_charset() is called to determine the character set being used by the Ingres client, from II_CHARSETxx (where xx is the installation code).

Note:

You can override the value returned by using the function putenv(). Changing the value of II_CHARSETxx in a running Ingres installation can cause data corruption.

Parameters

link

The connection link identifier

Return Values

Returns a string with the value for II_CHARSETxx or returns NULL if the value could not be determined.

Examples

Example #1 ingres_charset() - Get the installation character set

<?php
$link = ingres_connect($database, $user, $password);

echo ingres_charset($link) . "\n";

ingres_close($link);
?>

See Also

  • ingres_connect() - Open a connection to an Ingres database
  • ingres_query() - Send an SQL query to Ingres


Close an Ingres database connection

  • « ingres_charset
  • ingres_commit »
  • PHP Manual
  • Ingres Functions
  • Close an Ingres database connection

ingres_close

(PHP 4 >= 4.0.2, PHP 5 < 5.1.0, PECL ingres >= 1.0.0)

ingres_close — Close an Ingres database connection

Description

ingres_close ( resource $link ) : bool

ingres_close() closes the connection to the Ingres server that is associated with the specified link.

ingres_close() is usually unnecessary, as it will not close persistent connections and all non-persistent connections are automatically closed at the end of the script.

Parameters

link

The connection link identifier

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ingres_connect() - Open a connection to an Ingres database
  • ingres_pconnect() - Open a persistent connection to an Ingres database


Commit a transaction

  • « ingres_close
  • ingres_connect »
  • PHP Manual
  • Ingres Functions
  • Commit a transaction

ingres_commit

(PHP 4 >= 4.0.2, PHP 5 < 5.1.0, PECL ingres >= 1.0.0)

ingres_commit — Commit a transaction

Description

ingres_commit ( resource $link ) : bool

ingres_commit() commits the currently open transaction, making all changes made to the database permanent.

This closes the transaction. A new transaction can be opened by sending a query with ingres_query().

You can also have the server commit automatically after every query by calling ingres_autocommit() before opening the transaction.

By default Ingres will roll back any uncommitted transactions at the end of a request. Use this function or ingres_autocommit() to ensure your that data is committed to the database.

Parameters

link

The connection link identifier

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_rollback() - Roll back a transaction
  • ingres_autocommit() - Switch autocommit on or off


Open a connection to an Ingres database

  • « ingres_commit
  • ingres_cursor »
  • PHP Manual
  • Ingres Functions
  • Open a connection to an Ingres database

ingres_connect

(PHP 4 >= 4.0.2, PHP 5 < 5.1.0, PECL ingres >= 1.0.0)

ingres_connect — Open a connection to an Ingres database

Description

ingres_connect ([ string $database [, string $username [, string $password [, array $options ]]]] ) : resource

ingres_connect() opens a connection with the given Ingres database.

The connection is closed when the script ends or when ingres_close() is called on this link.

Parameters

If some parameters are missing, ingres_connect() uses the values in php.ini for ingres.default_database, ingres.default_user and ingres.default_password.

database

The database name. Must follow the syntax:

[vnode::]dbname[/svr_class]

username

The Ingres user name

password

The password associated with username

options

ingres_connect() options

Option name | Option type | Description | Example
date_century_boundary | integer | The threshold by which a 2-digit year is determined to be in the current century or in the next century. Equivalent to II_DATE_CENTURY_BOUNDARY. | 50
group | string | Specifies the group ID of the user, equivalent to the "-G" flag | payroll
role | string | The role ID of the application. If a role password is required, the parameter value should be specified as "role/password"
effective_user | string | The ingres user account being impersonated, equivalent to the "-u" flag | another_user
dbms_password | string | The internal database password for the user connecting to Ingres | s3cr3t
table_structure string

The default structure for new tables. Valid values for table_structure are:

  • INGRES_STRUCTURE_BTREE
  • INGRES_STRUCTURE_HASH
  • INGRES_STRUCTURE_HEAP
  • INGRES_STRUCTURE_ISAM
  • INGRES_STRUCTURE_CBTREE
  • INGRES_STRUCTURE_CISAM
  • INGRES_STRUCTURE_CHASH
  • INGRES_STRUCTURE_CHEAP

 INGRES_STRUCTURE_BTREE
index_structure string

The default structure for new secondary indexes. Valid values for index_structure are:

  • INGRES_STRUCTURE_CBTREE
  • INGRES_STRUCTURE_CISAM
  • INGRES_STRUCTURE_CHASH
  • INGRES_STRUCTURE_BTREE
  • INGRES_STRUCTURE_HASH
  • INGRES_STRUCTURE_ISAM

 INGRES_STRUCTURE_HASH
login_local | boolean | Determines how the connection user ID and password are used when a VNODE is included in the target database string. If set to TRUE, the user ID and password are used to locally access the VNODE, and the VNODE login information is used to establish the DBMS connection. If set to FALSE, the process user ID is used to access the VNODE, and the connection user ID and password are used in place of the VNODE login information to establish the DBMS connection. This parameter is ignored if no VNODE is included in the target database string. The default is FALSE. | TRUE
timezone | string | Controls the timezone of the session. If not set it will default to the value defined by II_TIMEZONE_NAME. If II_TIMEZONE_NAME is not defined, NA-PACIFIC (GMT-8 with Daylight Savings) is used.
date_format integer

Sets the allowable input and output format for Ingres dates. Defaults to the value defined by II_DATE_FORMAT. If II_DATE_FORMAT is not set the default date format is US, e.g. mm/dd/yy. Valid values for date_format are:

  • INGRES_DATE_DMY
  • INGRES_DATE_FINISH
  • INGRES_DATE_GERMAN
  • INGRES_DATE_ISO
  • INGRES_DATE_ISO4
  • INGRES_DATE_MDY
  • INGRES_DATE_MULTINATIONAL
  • INGRES_DATE_MULTINATIONAL4
  • INGRES_DATE_YMD
  • INGRES_DATE_US

 INGRES_DATE_MULTINATIONAL4
decimal_separator string The character identifier for decimal data ","
money_lort integer

Leading or trailing currency sign. Valid values for money_lort are:

  • INGRES_MONEY_LEADING
  • INGRES_MONEY_TRAILING

 INGRES_MONEY_TRAILING
money_sign string The currency symbol to be used with the MONEY datatype €
money_precision | integer | The precision of the MONEY datatype | 3
float4_precision | integer | Precision of the FLOAT4 datatype | 10
float8_precision | integer | Precision of the FLOAT8 data | 10
blob_segment_length | integer | The amount of data in bytes to fetch at a time when retrieving BLOB or CLOB data, defaults to 4096 bytes when not explicitly set | 8192

Return Values

Returns a Ingres link resource on success or FALSE on failure

Examples

Example #1 Open a connection to an Ingres database

<?php
$link = ingres_connect("mydb", "user", "pass")
    or die("Could not connect");
echo "Connected successfully";
ingres_close($link);
?>

See Also

  • ingres_pconnect() - Open a persistent connection to an Ingres database
  • ingres_close() - Close an Ingres database connection


Get a cursor name for a given result resource

  • « ingres_connect
  • ingres_errno »
  • PHP Manual
  • Ingres Functions
  • Get a cursor name for a given result resource

ingres_cursor

(PECL ingres >= 1.1.0)

ingres_cursor — Get a cursor name for a given result resource

Description

ingres_cursor ( resource $result ) : string

Returns a string with the active cursor name. If no cursor is active then NULL is returned.

Parameters

result

The query result identifier

Return Values

Returns a string containing the active cursor name. If no cursor is active then NULL is returned.

Examples

Example #1 Get cursor name for a query resource

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_prepare($link, "select * from table");

$cursor_name = ingres_cursor($result);

echo $cursor_name;

?>

See Also

  • ingres_prepare() - Prepare a query for later execution
  • ingres_execute() - Execute a prepared query


Get the last Ingres error number generated

  • « ingres_cursor
  • ingres_error »
  • PHP Manual
  • Ingres Functions
  • Get the last Ingres error number generated

ingres_errno

(PECL ingres >= 1.1.0)

ingres_errno — Get the last Ingres error number generated

Description

ingres_errno ([ resource $link ] ) : int

Returns an integer containing the last error number. If no error was reported 0 is returned.

If a link resource is passed to ingres_errno() it returns the last error recorded for the link. If no link is passed, then ingres_errno() returns the last error reported using the default link.

The function, ingres_errno(), should always be called after executing a database query. Calling another function before ingres_errno() is called will reset or change any error code from the last Ingres function call.

Parameters

link

The connection link identifier

Return Values

Returns an integer containing the last error number. If no error was reported, 0 is returned.

Examples

Example #1 Get the last Ingres error number generated

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_query($link, "select * from table");

$error_code = ingres_errno($link);

if ( $error_code != 0 ) {
   echo "An error occurred - " . $error_code;
}
?>

See Also

  • ingres_error() - Get a meaningful error message for the last error generated
  • ingres_errsqlstate() - Get the last SQLSTATE error code generated
  • ingres_next_error() - Get the next Ingres error


Get a meaningful error message for the last error generated

  • « ingres_errno
  • ingres_errsqlstate »
  • PHP Manual
  • Ingres Functions
  • Get a meaningful error message for the last error generated

ingres_error

(PECL ingres >= 1.1.0)

ingres_error — Get a meaningful error message for the last error generated

Description

ingres_error ([ resource $link ] ) : string

Returns a string containing the last error, or NULL if no error has occurred.

If a link resource is passed to ingres_error(), it returns the last error recorded for the link. If no link is passed then ingres_error() returns the last error reported using the default link.

The function, ingres_error(), should always be called after executing any database query. Calling another function before ingres_error() is called will reset or change any error message from the last Ingres function call.

Parameters

link

The connection link identifier

Return Values

Returns a string containing the last error, or NULL if no error has occurred.

Examples

Example #1 Get a message for the last error generated

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_query($link, "select * from table");

$error_text = ingres_error();

if (!is_null($error_text)) {
   echo "An error occurred - " . $error_text;
}
?>

See Also

  • ingres_errno() - Get the last Ingres error number generated
  • ingres_errsqlstate() - Get the last SQLSTATE error code generated
  • ingres_next_error() - Get the next Ingres error


Get the last SQLSTATE error code generated

  • « ingres_error
  • ingres_escape_string »
  • PHP Manual
  • Ingres Functions
  • Get the last SQLSTATE error code generated

ingres_errsqlstate

(PECL ingres >= 1.1.0)

ingres_errsqlstate — Get the last SQLSTATE error code generated

Description

ingres_errsqlstate ([ resource $link ] ) : string

Returns a string containing the last SQLSTATE, or NULL if no error has occurred.

If a link resource is passed to ingres_errsqlstate(), it returns the last error recorded for the link. If no link is passed, then ingres_errsqlstate() returns the last error reported using the default link.

The function, ingres_errsqlstate(), should always be called after executing any database query. Calling another function before ingres_errsqlstate() is called will reset or change any error message from the last Ingres function call.

Parameters

link

The connection link identifier

Return Values

Returns a string containing the last SQLSTATE, or NULL if no error has occurred.

Examples

Example #1 Get the last SQLSTATE error code generated

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_query($link, "select * from table");

$error_sqlstate = ingres_errsqlstate($link);

if (!is_null($error_sqlstate)) {
   echo "An error occurred - " . $error_sqlstate;
}
?>

See Also

  • ingres_errno() - Get the last Ingres error number generated
  • ingres_error() - Get a meaningful error message for the last error generated
  • ingres_next_error() - Get the next Ingres error


Escape special characters for use in a query

  • « ingres_errsqlstate
  • ingres_execute »
  • PHP Manual
  • Ingres Functions
  • Escape special characters for use in a query

ingres_escape_string

(PECL ingres >= 2.1.0)

ingres_escape_string — Escape special characters for use in a query

Description

ingres_escape_string ( resource $link , string $source_string ) : string

ingres_escape_string() is used to escape certain characters within a string before it is sent to the database server.

Parameters

link

The connection link identifier

source_string

The source string to be parsed

Return Values

Returns a string containing the escaped data.

Examples

Example #1 Escape special characters for use in a query

<?php
$link = ingres_connect($database, $user, $password);

$last_name = "O'Connor";

$sql = sprintf("select * from user_profile where up_last = '%s'", ingres_escape_string( $link, $last_name));

$result = ingres_query($link, $sql);

while ($user = ingres_fetch_object($result))
{
  echo $user->up_first . '<BR/>';
}

ingres_commit($link);

ingres_close($link);

?>

See Also

  • ingres_query() - Send an SQL query to Ingres


Execute a prepared query

  • « ingres_escape_string
  • ingres_fetch_array »
  • PHP Manual
  • Ingres Functions
  • Execute a prepared query

ingres_execute

(PECL ingres >= 1.1.0)

ingres_execute — Execute a prepared query

Description

ingres_execute ( resource $result [, array $params [, string $types ]] ) : bool

Execute a query prepared using ingres_prepare().

Note: Related Configurations

See also the ingres.describe, ingres.scrollable and ingres.utf8 directives in Runtime Configuration.

Parameters

result

The result query identifier

params

An array of parameter values to be used with the query

types

A string containing a sequence of types for the parameter values passed. See the types parameter in ingres_query() for the list of type codes.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ingres_unbuffered_query() - Send an unbuffered SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array
  • ingres_commit() - Commit a transaction
  • ingres_rollback() - Roll back a transaction
  • ingres_autocommit() - Switch autocommit on or off
  • ingres_set_environment() - Set environment features controlling output options
  • ingres_errno() - Get the last Ingres error number generated
  • ingres_error() - Get a meaningful error message for the last error generated


Fetch a row of result into an array

  • « ingres_execute
  • ingres_fetch_assoc »
  • PHP Manual
  • Ingres Functions
  • Fetch a row of result into an array

ingres_fetch_array

(PHP 5 < 5.1.0, PECL ingres >= 1.0.0)

ingres_fetch_array — Fetch a row of result into an array

Description

ingres_fetch_array ( resource $result [, int $result_type ] ) : array

This function is an extended version of ingres_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

If two or more columns of the result have the same field names, the last column will take precedence. To access the another column or columns of the same name, you must use the numeric index of the column or make an alias for the column. For example:

<?php

$result = ingres_query($link, "select ap_place as city, ap_ccode as country from airport where ap_iatacode = 'VLL'");
$result = ingres_fetch_array($result);
$foo = $result["city"];
$bar = $result["country"];

?>

With regard to speed, the function is identical to ingres_fetch_object(), and almost as quick as ingres_fetch_row() (the difference is insignificant).

By default, arrays created by ingres_fetch_array() start from position 1 and not 0 as with other DBMS extensions. The starting position can be adjusted to 0 using the configuration parameter ingres.array_index_start.

Note: Related Configurations

See also the ingres.array_index_start, ingres.fetch_buffer_size and ingres.utf8 directives in Runtime Configuration.

Parameters

result

The query result identifier

result_type

The result type. This result_type can be INGRES_NUM for enumerated array, INGRES_ASSOC for associative array, or INGRES_BOTH (default).

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows

Examples

Example #1 Fetch a row of result into an array

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_query($link,"select * from table");
while ($row = ingres_fetch_array($result)) {
    echo $row["user_id"];  // using associative array
    echo $row["fullname"];
    echo $row[1];          // using enumerated array
    echo $row[2];
}
?>

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_num_fields() - Get the number of fields returned by the last query
  • ingres_field_name() - Get the name of a field in a query result
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array


Fetch a row of result into an associative array

  • « ingres_fetch_array
  • ingres_fetch_object »
  • PHP Manual
  • Ingres Functions
  • Fetch a row of result into an associative array

ingres_fetch_assoc

(PECL ingres >= 2.2.2)

ingres_fetch_assoc — Fetch a row of result into an associative array

Description

ingres_fetch_assoc ( resource $result ) : array

This function is stores the data fetched from a query executed using ingres_query() in an associative array, using the field names as keys.

With regard to speed, the function is identical to ingres_fetch_object(), and almost as quick as ingres_fetch_row() (the difference is insignificant).

By default, arrays created by ingres_fetch_assoc() start from position 1 and not 0 as with other DBMS extensions. The starting position can be adjusted to 0 using the configuration parameter ingres.array_index_start.

Note: Related Configurations

See also the ingres.array_index_start, ingres.fetch_buffer_size and ingres.utf8 directives in Runtime Configuration.

Parameters

result

The query result identifier

Return Values

Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows

Examples

Example #1 Fetch a row into an associative array

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_query($link,"select * from table");
while ($row = ingres_fetch_assoc($result)) {
    echo $row["user_id"];  // using associative array
    echo $row["fullname"];
}
?>

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_num_fields() - Get the number of fields returned by the last query
  • ingres_field_name() - Get the name of a field in a query result
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array


Fetch a row of result into an object

  • « ingres_fetch_assoc
  • ingres_fetch_proc_return »
  • PHP Manual
  • Ingres Functions
  • Fetch a row of result into an object

ingres_fetch_object

(PHP 4 >= 4.0.2, PHP 5 < 5.1.0, PECL ingres >= 1.0.0)

ingres_fetch_object — Fetch a row of result into an object

Description

ingres_fetch_object ( resource $result [, int $result_type ] ) : object

This function is similar to ingres_fetch_array(), with one difference - an object is returned instead of an array. Indirectly, this means that you can access the data only by the field names and not by their offsets (numbers are illegal property names).

With regard to speed, the function is identical to ingres_fetch_array(), and almost as quick as ingres_fetch_row() (the difference is insignificant).

Note: Related Configurations

See also the ingres.fetch_buffer_size and ingres.utf8 directives in Runtime Configuration.

Parameters

link

The query result identifier

result_type

(Optional argument.) result_type is a constant and can take the following values: INGRES_ASSOC, INGRES_NUM, and INGRES_BOTH.

Return Values

Returns an object that corresponds to the fetched row, or FALSE if there are no more rows

Examples

Example #1 Fetch a row into an object

<?php
$link = ingres_connect($database, $user, $password);
$result = ingres_query($link, "select * from table");
while ($row = ingres_fetch_object($result)) {
    echo $row->user_id;
    echo $row->fullname;
}
?>

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_num_fields() - Get the number of fields returned by the last query
  • ingres_field_name() - Get the name of a field in a query result
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_row() - Fetch a row of result into an enumerated array


Get the return value from a procedure call

  • « ingres_fetch_object
  • ingres_fetch_row »
  • PHP Manual
  • Ingres Functions
  • Get the return value from a procedure call

ingres_fetch_proc_return

(PECL ingres >= 1.4.0)

ingres_fetch_proc_return — Get the return value from a procedure call

Description

ingres_fetch_proc_return ( resource $result ) : int

This function is used to retrieve the return value following the execution of an Ingres database procedure (stored procedure).

Note:

If used with a row-producing procedure, this function should be called after all the rows from the procedure have been fetched using ingres_fetch_array(), ingres_fetch_object() or ingres_fetch_row(). This function will eliminate any rows yet to be fetched should there be any left over.

Parameters

result

The result identifier for a query

Return Values

Returns an integer if there is a return value otherwise it will return NULL.

Examples

Example #1 Get the return value from a procedure call

<?php

$link = ingres_connect($database);

if ( ingres_errno() != 0 ) {
    $error_text = ingres_error();
    die($error_text);
}

$result = ingres_query($link, "execute procedure php_proc (value = 1000)");

if ( ingres_errno() != 0 ) {
    $error_text = ingres_error();
    die($error_text);
}

echo "return value - " . ingres_fetch_proc_return($result) . "\n";

ingres_close($link);

?>

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array


Fetch a row of result into an enumerated array

  • « ingres_fetch_proc_return
  • ingres_field_length »
  • PHP Manual
  • Ingres Functions
  • Fetch a row of result into an enumerated array

ingres_fetch_row

(PHP 4 >= 4.0.2, PHP 5 < 5.1.0, PECL ingres >= 1.0.0)

ingres_fetch_row — Fetch a row of result into an enumerated array

Description

ingres_fetch_row ( resource $result ) : array

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

Subsequent calls to ingres_fetch_row() return the next row in the result set, or FALSE if there are no more rows.

By default, arrays created by ingres_fetch_row() start from position 1 and not 0 as with other DBMS extensions. The starting position can be adjusted to 0 using the configuration parameter ingres.array_index_start.

Note: Related Configurations

See also the ingres.array_index_start, ingres.fetch_buffer_size and ingres.utf8 directives in Runtime Configuration.

Parameters

result

The query result identifier

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows

Examples

Example #1 Fetch a row of result into an enumerated array

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_query($link, "select * from table");
while ($row = ingres_fetch_row($result)) {
    echo $row[1];
    echo $row[2];
}
?>

See Also

  • ingres_num_fields() - Get the number of fields returned by the last query
  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object


Get the length of a field

  • « ingres_fetch_row
  • ingres_field_name »
  • PHP Manual
  • Ingres Functions
  • Get the length of a field

ingres_field_length

(PHP 4 >= 4.0.2, PHP 5 < 5.1.0, PECL ingres >= 1.0.0)

ingres_field_length — Get the length of a field

Description

ingres_field_length ( resource $result , int $index ) : int

ingres_field_length() returns the length of a field. This is the number of bytes the server uses to store the field. For detailed information, see the Ingres OpenAPI User Guide, Appendix "Data Types" in the Ingres documentation.

Note: Related Configurations

See ingres.array_index_start in Runtime Configuration

Parameters

result

The query result identifier

index

index is the column number whose length will be retrieved.

The possible values of index depend upon the value of ingres.array_index_start. If ingres.array_index_start is 1 (the default) then index must be between 1 and the value returned by ingres_num_fields(). If ingres.array_index_start is 0 then index must be between 0 and ingres_num_fields() - 1.

Return Values

Returns the length of a field.

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array


Get the name of a field in a query result

  • « ingres_field_length
  • ingres_field_nullable »
  • PHP Manual
  • Ingres Functions
  • Get the name of a field in a query result

ingres_field_name

(PHP 4 >= 4.0.2, PHP 5 < 5.1.0, PECL ingres >= 1.0.0)

ingres_field_name — Get the name of a field in a query result

Description

ingres_field_name ( resource $result , int $index ) : string

ingres_field_name() returns the name of a field in a query result.

Note: Related Configurations

See ingres.array_index_start in Runtime Configuration

Parameters

result

The query result identifier

index

index is the field whose name will be retrieved.

The possible values of index depend upon the value of ingres.array_index_start. If ingres.array_index_start is 1 (the default) then index must be between 1 and the value returned by ingres_num_fields(). If ingres.array_index_start is 0 then index must be between 0 and ingres_num_fields() - 1.

Return Values

Returns the name of a field in a query result or FALSE on failure

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array


Test if a field is nullable

  • « ingres_field_name
  • ingres_field_precision »
  • PHP Manual
  • Ingres Functions
  • Test if a field is nullable

ingres_field_nullable

(PHP 4 >= 4.0.2, PHP 5 < 5.1.0, PECL ingres >= 1.0.0)

ingres_field_nullable — Test if a field is nullable

Description

ingres_field_nullable ( resource $result , int $index ) : bool

Test if a field is nullable.

Note: Related Configurations

See ingres.array_index_start in Runtime Configuration

Parameters

result

The query result identifier

index

index is the field whose nullability will be retrieved.

The possible values of index depend upon the value of ingres.array_index_start. If ingres.array_index_start is 1 (the default) then index must be between 1 and the value returned by ingres_num_fields(). If ingres.array_index_start is 0 then index must be between 0 and ingres_num_fields() - 1.

Return Values

ingres_field_nullable() returns TRUE if the field can be set to the NULL value and FALSE if it cannot

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array


Get the precision of a field

  • « ingres_field_nullable
  • ingres_field_scale »
  • PHP Manual
  • Ingres Functions
  • Get the precision of a field

ingres_field_precision

(PHP 4 >= 4.0.2, PHP 5 < 5.1.0, PECL ingres >= 1.0.0)

ingres_field_precision — Get the precision of a field

Description

ingres_field_precision ( resource $result , int $index ) : int

ingres_field_precision() returns the precision of a field. This value is used only for decimal, float, and money SQL data types. For detailed information, see the Ingres OpenAPI User Guide, Appendix "Data Types" in the Ingres documentation.

Note: Related Configurations

See ingres.array_index_start in Runtime Configuration

Parameters

result

The query result identifier

index

index is the field whose precision will be retrieved.

The possible values of index depend upon the value of ingres.array_index_start. If ingres.array_index_start is 1 (the default) then index must be between 1 and the value returned by ingres_num_fields(). If ingres.array_index_start is 0 then index must be between 0 and ingres_num_fields() - 1.

Return Values

Returns the field precision as an integer

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array


Get the scale of a field

  • « ingres_field_precision
  • ingres_field_type »
  • PHP Manual
  • Ingres Functions
  • Get the scale of a field

ingres_field_scale

(PHP 4 >= 4.0.2, PHP 5 < 5.1.0, PECL ingres >= 1.0.0)

ingres_field_scale — Get the scale of a field

Description

ingres_field_scale ( resource $result , int $index ) : int

ingres_field_scale() returns the scale of a field. This value is used only for the decimal SQL data type. For detailed information, see the Ingres OpenAPI User Guide, Appendix "Data Types" in the Ingres documentation.

Note: Related Configurations

See ingres.array_index_start in Runtime Configuration

Parameters

result

The query result identifier

index

index is the field whose scale will be retrieved.

The possible values of index depend upon the value of ingres.array_index_start. If ingres.array_index_start is 1 (the default) then index must be between 1 and the value returned by ingres_num_fields(). If ingres.array_index_start is 0 then index must be between 0 and ingres_num_fields() - 1.

Return Values

Returns the scale of the field, as an integer

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array


Get the type of a field in a query result

  • « ingres_field_scale
  • ingres_free_result »
  • PHP Manual
  • Ingres Functions
  • Get the type of a field in a query result

ingres_field_type

(PHP 4 >= 4.0.2, PHP 5 < 5.1.0, PECL ingres >= 1.0.0)

ingres_field_type — Get the type of a field in a query result

Description

ingres_field_type ( resource $result , int $index ) : string

Get the type of a field in a query result.

Note: Related Configurations

See ingres.array_index_start in Runtime Configuration

Parameters

result

The query result identifier

index

index is the field whose type will be retrieved.

The possible values of index depend upon the value of ingres.array_index_start. If ingres.array_index_start is 1 (the default) then index must be between 1 and the value returned by ingres_num_fields(). If ingres.array_index_start is 0 then index must be between 0 and ingres_num_fields() - 1.

Return Values

ingres_field_type() returns the type of a field in a query result or FALSE on failure. Examples of types returned are IIAPI_BYTE_TYPE, IIAPI_CHA_TYPE, IIAPI_DTE_TYPE, IIAPI_FLT_TYPE, IIAPI_INT_TYPE, IIAPI_VCH_TYPE. Some of these types can map to more than one SQL type depending on the length of the field (see ingres_field_length()). For example IIAPI_FLT_TYPE can be a float4 or a float8. For detailed information, see the Ingres OpenAPI User Guide, Appendix "Data Types" in the Ingres documentation.

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array


Free the resources associated with a result identifier

  • « ingres_field_type
  • ingres_next_error »
  • PHP Manual
  • Ingres Functions
  • Free the resources associated with a result identifier

ingres_free_result

(PECL ingres >= 2.0.0)

ingres_free_result — Free the resources associated with a result identifier

Description

ingres_free_result ( resource $result ) : bool

Parameters

result

The query result identifier

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Free a result resource

<?php
$link = ingres_connect($database, $user, $password);

$result = ingres_query($link, "select * from table");

while ($row = ingres_fetch_row($result)) {
    echo $row[1];
    echo $row[2];
}
ingres_free_result($result);

ingres_close($link)

?>

See Also

  • ingres_query() - Send an SQL query to Ingres


Get the next Ingres error

  • « ingres_free_result
  • ingres_num_fields »
  • PHP Manual
  • Ingres Functions
  • Get the next Ingres error

ingres_next_error

(PECL ingres >= 2.0.0)

ingres_next_error — Get the next Ingres error

Description

ingres_next_error ([ resource $link ] ) : bool

Get the next Ingres error for the last executed query. Each call to ingres_next_error() can be followed by a call to ingres_errno(), ingres_error() or ingres_errsqlstate() to get the respective error number, error text, or SQL STATE. While ingres_next_error() returns TRUE, there are more errors to fetch.

Parameters

link

The connection link identifier

Return Values

ingres_next_error() returns TRUE if there is another error to retrieve or FALSE when there are no more errors

See Also

  • ingres_errno() - Get the last Ingres error number generated
  • ingres_error() - Get a meaningful error message for the last error generated
  • ingres_errsqlstate() - Get the last SQLSTATE error code generated


Get the number of fields returned by the last query

  • « ingres_next_error
  • ingres_num_rows »
  • PHP Manual
  • Ingres Functions
  • Get the number of fields returned by the last query

ingres_num_fields

(PHP 4 >= 4.0.2, PHP 5 < 5.1.0, PECL ingres >= 1.0.0)

ingres_num_fields — Get the number of fields returned by the last query

Description

ingres_num_fields ( resource $result ) : int

ingres_num_fields() returns the number of fields in the results returned by the Ingres server after a call to ingres_query().

Parameters

result

The query result identifier

Return Values

Returns the number of fields

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array


Get the number of rows affected or returned by a query

  • « ingres_num_fields
  • ingres_pconnect »
  • PHP Manual
  • Ingres Functions
  • Get the number of rows affected or returned by a query

ingres_num_rows

(PHP 4 >= 4.0.2, PHP 5 < 5.1.0, PECL ingres >= 1.0.0)

ingres_num_rows — Get the number of rows affected or returned by a query

Description

ingres_num_rows ( resource $result ) : int

This function primarily is meant to get the number of rows modified in the database. However, it can be used to retrieve the number of rows to fetch for a SELECT statement.

Note:

If scrollable cursors are disabled and this function is called before using ingres_fetch_array(), ingres_fetch_object(), or ingres_fetch_row(), the server will delete the result's data and the script will be unable to get them.

Instead, you should retrieve the result's data using one of these fetch functions in a loop until it returns FALSE, indicating that no more results are available.

Parameters

result

The result identifier for a query

Return Values

For delete, insert, or update queries, ingres_num_rows() returns the number of rows affected by the query. For other queries, ingres_num_rows() returns the number of rows in the query's result.

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array


Open a persistent connection to an Ingres database

  • « ingres_num_rows
  • ingres_prepare »
  • PHP Manual
  • Ingres Functions
  • Open a persistent connection to an Ingres database

ingres_pconnect

(PHP 4 >= 4.0.2, PHP 5 < 5.1.0, PECL ingres >= 1.0.0)

ingres_pconnect — Open a persistent connection to an Ingres database

Description

ingres_pconnect ([ string $database [, string $username [, string $password [, array $options ]]]] ) : resource

Open a persistent connection to an Ingres database.

There are only two differences between this function and ingres_connect(): First, when connecting, the function will initially try to find a (persistent) link that is 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 Ingres server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (ingres_close() will not close links established by ingres_pconnect()). This type of link is therefore called "persistent".

Parameters

database

The database name. Must follow the syntax:

[vnode::]dbname[/svr_class]

username

The Ingres user name

password

The password associated with username

options

See ingres_connect() for the list of options that can be passed

Return Values

Returns an Ingres link resource on success or FALSE on failure

See Also

  • ingres_connect() - Open a connection to an Ingres database
  • ingres_close() - Close an Ingres database connection


Prepare a query for later execution

  • « ingres_pconnect
  • ingres_query »
  • PHP Manual
  • Ingres Functions
  • Prepare a query for later execution

ingres_prepare

(PECL ingres >= 1.1.0)

ingres_prepare — Prepare a query for later execution

Description

ingres_prepare ( resource $link , string $query ) : mixed

Prepares a query for execution by ingres_execute().

The query becomes part of the currently open transaction. If there is no open transaction, ingres_query() opens a new transaction. To close the transaction, you can call either ingres_commit() to commit the changes made to the database or ingres_rollback() to cancel these changes. When the script ends, any open transaction is rolled back (by calling ingres_rollback()). You can also use ingres_autocommit() before opening a new transaction to have every SQL query immediately committed.

Note: Related Configurations

See also the ingres.describe, ingres.scrollable and ingres.utf8 directives in Runtime Configuration.

Parameters

link

The connection link identifier

query

A valid SQL query (see the Ingres SQL reference guide) in the Ingres documentation. See the query parameter in ingres_query() for a list of SQL statements which cannot be executed using ingres_prepare()

Return Values

ingres_prepare() returns a query result identifier that
is used with ingres_execute() to execute the query. To see
if an error occurred, use ingres_errno(),
ingres_error(), or
ingres_errsqlstate().

See Also

  • ingres_unbuffered_query() - Send an unbuffered SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array
  • ingres_commit() - Commit a transaction
  • ingres_rollback() - Roll back a transaction
  • ingres_autocommit() - Switch autocommit on or off
  • ingres_set_environment() - Set environment features controlling output options
  • ingres_errno() - Get the last Ingres error number generated
  • ingres_error() - Get a meaningful error message for the last error generated


Send an SQL query to Ingres

  • « ingres_prepare
  • ingres_result_seek »
  • PHP Manual
  • Ingres Functions
  • Send an SQL query to Ingres

ingres_query

(PHP 4 >= 4.0.2, PHP 5 < 5.1.0, PECL ingres >= 1.0.0)

ingres_query — Send an SQL query to Ingres

Description

ingres_query ( resource $link , string $query [, array $params [, string $types ]] ) : mixed

ingres_query() sends the given query to the Ingres server.

The query becomes part of the currently open transaction. If there is no open transaction, ingres_query() opens a new transaction. To close the transaction, you can call either ingres_commit() to commit the changes made to the database or ingres_rollback() to cancel these changes. When the script ends, any open transaction is rolled back (by calling ingres_rollback()). You can also use ingres_autocommit() before opening a new transaction to have every SQL query immediately committed.

Note: Related Configurations

See also the ingres.describe, ingres.scrollable and ingres.utf8 directives in Runtime Configuration

Parameters

link

The connection link identifier.

query

A valid SQL query (see the Ingres SQL reference guide) in the Ingres documentation.

Data inside the query should be properly escaped.

The following types of SQL queries cannot be sent with this function:

  • close (see ingres_close())
  • commit (see ingres_commit())
  • connect (see ingres_connect())
  • disconnect (see ingres_close())
  • get dbevent
  • prepare to commit
  • rollback (see ingres_rollback())
  • savepoint
  • set autocommit (see ingres_autocommit())
  • all cursor-related queries are unsupported

params

An array of parameter values to be used with the query

types

A string containing a sequence of types for the parameter values passed. When ingres.describe is enabled, this parameter can be ignored as the driver automatically fetches the expected parameter types from the server.

Type code | Ingres type
a | BOOLEAN
b | BYTE
B | LONG BYTE/BLOB
c | CHAR
d | DATE/ANSIDATE/TIMESTAMP/TIME
f | FLOAT
i | INTEGER
L | LONG TEXT
m | MONEY
M | LONG NVARCHAR
n | NCHAR
N | NVARCHAR
t | TEXT
v | VARCHAR
V | LONG VARCHAR

Return Values

ingres_query() returns a query result identifier on
success else it returns FALSE. To see if an error
occurred use ingres_errno(),
ingres_error() or
ingres_errsqlstate().

Examples

Example #1 Send a simple select

<?php
$link = ingres_connect("demodb");

$result = ingres_query($link, "select * from user_profile");
while ($row = ingres_fetch_row($result)) {
    echo $row[1];
    echo $row[2];
}
?>

Example #2 Passing query parameters to ingres_query()

<?php
$link = ingres_connect("demodb");

$params[] = "Emma";
$query = "select * from user_profile where up_first = ?";
$result = ingres_query($link, $query, $params);
while ($row = ingres_fetch_row($result)) {
    echo $row[1];
    echo $row[2];
}
?>

Example #3 Inserting a BLOB with parameter types

<?php
$link = ingres_connect("demodb");

//Open a photo
$fh = fopen("photo.jpg","r");
$blob_data = stream_get_contents($fh);
fclose($fh);

//Prepare parameters
$params[] = $blob_data;
$params[] = 1201;

//Define parameter types
$param_types = "Bi";

$query = "update user_profile set up_image = ? where up_id = ?";
$result = ingres_query($link, $query , $params, $param_types);

if (ingres_errno())
{
    echo ingres_errno() . "-" . ingres_error() . "\n";
}

ingres_commit($link);

ingres_close($link);
?>

See Also

  • ingres_unbuffered_query() - Send an unbuffered SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array
  • ingres_commit() - Commit a transaction
  • ingres_rollback() - Roll back a transaction
  • ingres_autocommit() - Switch autocommit on or off
  • ingres_set_environment() - Set environment features controlling output options
  • ingres_errno() - Get the last Ingres error number generated
  • ingres_error() - Get a meaningful error message for the last error generated


Set the row position before fetching data

  • « ingres_query
  • ingres_rollback »
  • PHP Manual
  • Ingres Functions
  • Set the row position before fetching data

ingres_result_seek

(PECL ingres >= 2.1.0)

ingres_result_seek — Set the row position before fetching data

Description

ingres_result_seek ( resource $result , int $position ) : bool

This function is used to position the cursor associated with the result resource before issuing a fetch. If ingres.array_index_start is set to 0 then the first row is 0 else it is 1. ingres_result_seek() can be used only with queries that make use of scrollable cursors. It cannot be used with ingres_unbuffered_query().

Note: Related Configurations

See also the ingres.scrollable and ingres.array_index_start directives in Runtime Configuration.

Parameters

result

The result identifier for a query

position

The row to position the cursor on. If ingres.array_index_start is set to 0, then the first row is 0, else it is 1

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Position the cursor on the 3rd row

<?php

$result=ingres_query($link, "select * from airport where ap_ccode = 'ES' order by ap_place asc");

/* goto row 3 */
if (!ingres_result_seek($result, 3))
{
    echo ingres_errno() . " - " . ingres_error . "\n";
    die("i died");
}
else
{
    $airport = ingres_fetch_object ($result);
    {
        echo $airport->ap_iatacode . " - " .  $airport->ap_name . "\n";
    }
}

ingres_commit($link);

?>

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array


Roll back a transaction

  • « ingres_result_seek
  • ingres_set_environment »
  • PHP Manual
  • Ingres Functions
  • Roll back a transaction

ingres_rollback

(PHP 4 >= 4.0.2, PHP 5 < 5.1.0, PECL ingres >= 1.0.0)

ingres_rollback — Roll back a transaction

Description

ingres_rollback ( resource $link ) : bool

ingres_rollback() rolls back the currently open transaction, actually cancelling all changes made to the database during the transaction.

This closes the transaction. A new transaction can be opened by sending a query with ingres_query().

Parameters

link

The connection link identifier

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_commit() - Commit a transaction
  • ingres_autocommit() - Switch autocommit on or off


Set environment features controlling output options

  • « ingres_rollback
  • ingres_unbuffered_query »
  • PHP Manual
  • Ingres Functions
  • Set environment features controlling output options

ingres_set_environment

(PECL ingres >= 1.2.0)

ingres_set_environment — Set environment features controlling output options

Description

ingres_set_environment ( resource $link , array $options ) : bool

ingres_set_environment() is called to set environmental options that affect the output of certain values from Ingres, such as the timezone, date format, decimal character separator, and float precision.

Parameters

link

The connection link identifier

options

An enumerated array of option name/value pairs. The following table lists the option name and the expected type

Option name | Option type | Description | Example
date_century_boundary | integer | The threshold by which a 2-digit year is determined to be in the current century or in the next century. Equivalent to II_DATE_CENTURY_BOUNDARY | 50
timezone | string | Controls the timezone of the session. If not set, it will default the value defined by II_TIMEZONE_NAME. If II_TIMEZONE_NAME is not defined, NA-PACIFIC (GMT-8 with Daylight Savings) is used. | UNITED-KINGDOM
date_format integer

Sets the allowable input and output format for Ingres dates. Defaults to the value defined by II_DATE_FORMAT. If II_DATE_FORMAT is not set, the default date format is US, for example mm/dd/yy. Valid values for date_format are:

  • INGRES_DATE_DMY
  • INGRES_DATE_FINISH
  • INGRES_DATE_GERMAN
  • INGRES_DATE_ISO
  • INGRES_DATE_ISO4
  • INGRES_DATE_MDY
  • INGRES_DATE_MULTINATIONAL
  • INGRES_DATE_MULTINATIONAL4
  • INGRES_DATE_YMD
  • INGRES_DATE_US

 INGRES_DATE_ISO4
decimal_separator string The character identifier for decimal data ","
money_lort integer

Leading or trailing currency sign. Valid values for money_lort are:

  • INGRES_MONEY_LEADING
  • INGRES_MONEY_TRAILING

 INGRES_MONEY_LEADING
money_sign string The currency symbol to be used with the MONEY datatype €
money_precision | integer | The precision of the MONEY datatype | 2
float4_precision | integer | Precision of the FLOAT4 datatype | 10
float8_precision | integer | Precision of the FLOAT8 data | 10
blob_segment_length | integer | The amount of data in bytes to fetch at a time when retrieving BLOB or CLOB data. Defaults to 4096 bytes when not set explicitly | 8192

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Set date_format to ISO4

<?php
$options = array( "date_format" => INGRES_DATE_ISO4 );

if (ingres_set_environment($link, $options))
{
    $result=ingres_query($link,"select date('now') as date");

    while ( $object = ingres_fetch_object ($result) ) {
        echo $object->date."\n";
    }
}
?>

Example #2 Set timezone to HONG-KONG

<?php

$options = array( "timezone" => "HONG-KONG");

if (ingres_set_environment($link, $options))
{
    $result=ingres_query($link,"select date('now') as date");

    while ( $object = ingres_fetch_object ($result) ) {
        echo $object->date."\n";
    }
}
?>

See Also

  • ingres_connect() - Open a connection to an Ingres database
  • ingres_query() - Send an SQL query to Ingres


Send an unbuffered SQL query to Ingres

  • « ingres_set_environment
  • MaxDB »
  • PHP Manual
  • Ingres Functions
  • Send an unbuffered SQL query to Ingres

ingres_unbuffered_query

(No version information available, might only be in Git)

ingres_unbuffered_query — Send an unbuffered SQL query to Ingres

Description

ingres_unbuffered_query ( resource $link , string $query [, array $params [, string $types ]] ) : mixed

ingres_unbuffered_query() sends the given query to the Ingres server.

The query becomes part of the currently open transaction. If there is no open transaction, ingres_unbuffered_query() opens a new transaction. To close the transaction, you can call either ingres_commit() to commit the changes made to the database or ingres_rollback() to cancel these changes. When the script ends, any open transaction is rolled back (by calling ingres_rollback()). You can also use ingres_autocommit() before opening a new transaction to have every SQL query immediately committed. Ingres allows only a single unbuffered statement to be active at any one time. The extension will close any active unbuffered statements before executing any SQL. In addition you cannot use ingres_result_seek() to position the row before fetching.

Note: Related Configurations

See also the ingres.describe and ingres.utf8 directives in Runtime Configuration.

Parameters

link

The connection link identifier

query

A valid SQL query (see the Ingres SQL reference guide) in the Ingres documentation. See the query parameter in ingres_query() for a list of SQL statements that cannot be executed via ingres_unbuffered_query().

Data inside the query should be properly escaped.

params

An array of parameter values to be used with the query

types

A string containing a sequence of types for the parameter values passed. See the types parameter in ingres_query() for the list of type codes.

Return Values

ingres_unbuffered_query() returns a query result identifier when there are rows to fetch; else it returns FALSE when there are no rows, as is the case of an INSERT, UPDATE, or DELETE statement. To see if an error occurred, use ingres_errno(), ingres_error(), or ingres_errsqlstate().

Examples

Example #1 Issue a simple un-buffered select

<?php
$link = ingres_connect("demodb");

$result = ingres_unbuffered_query($link, "select * from user_profile");
while ($row = ingres_fetch_row($result)) {
    echo $row[1];
    echo $row[2];
}
?>

Example #2 Passing query parameters to ingres_unbuffered_query()

<?php
$link = ingres_connect("demodb");

$params[] = "Emma";
$query = "select * from user_profile where up_first = ?";
$result = ingres_unbuffered_query($link, $query, $params);
while ($row = ingres_fetch_row($result)) {
    echo $row[1];
    echo $row[2];
}
?>

Example #3 Inserting a BLOB with parameter types

<?php
$link = ingres_connect("demodb");

//Open a photo
$fh = fopen("photo.jpg","r");
$blob_data = stream_get_contents($fh);
fclose($fh);

//Prepare parameters
$params[] = $blob_data;
$params[] = 1201;

//Define parameter types
$param_types = "Bi";

$query = "update user_profile set up_image = ? where up_id = ?";
$result = ingres_unbuffered_query($link, $query , $params, $param_types);

if (ingres_errno())
{
    echo ingres_errno() . "-" . ingres_error() . "\n";
}
?>

See Also

  • ingres_query() - Send an SQL query to Ingres
  • ingres_fetch_array() - Fetch a row of result into an array
  • ingres_fetch_assoc() - Fetch a row of result into an associative array
  • ingres_fetch_object() - Fetch a row of result into an object
  • ingres_fetch_row() - Fetch a row of result into an enumerated array
  • ingres_commit() - Commit a transaction
  • ingres_rollback() - Roll back a transaction
  • ingres_autocommit() - Switch autocommit on or off
  • ingres_set_environment() - Set environment features controlling output options
  • ingres_errno() - Get the last Ingres error number generated
  • ingres_error() - Get a meaningful error message for the last error generated


MaxDB

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
  • MaxDB Functions
    • maxdb_affected_rows — Gets the number of affected rows in a previous MaxDB operation
    • maxdb_autocommit — Turns on or off auto-commiting database modifications
    • maxdb_bind_param — Alias of maxdb_stmt_bind_param
    • maxdb_bind_result — Alias of maxdb_stmt_bind_result
    • maxdb_change_user — Changes the user of the specified database connection
    • maxdb_character_set_name — Returns the default character set for the database connection
    • maxdb_client_encoding — Alias of maxdb_character_set_name
    • maxdb_close_long_data — Alias of maxdb_stmt_close_long_data
    • maxdb_close — Closes a previously opened database connection
    • maxdb_commit — Commits the current transaction
    • maxdb_connect_errno — Returns the error code from last connect call
    • maxdb_connect_error — Returns a string description of the last connect error
    • maxdb_connect — Open a new connection to the MaxDB server
    • maxdb_data_seek — Adjusts the result pointer to an arbitary row in the result
    • maxdb_debug — Performs debugging operations
    • maxdb_disable_reads_from_master — Disable reads from master
    • maxdb_disable_rpl_parse — Disable RPL parse
    • maxdb_dump_debug_info — Dump debugging information into the log
    • maxdb_embedded_connect — Open a connection to an embedded MaxDB server
    • maxdb_enable_reads_from_master — Enable reads from master
    • maxdb_enable_rpl_parse — Enable RPL parse
    • maxdb_errno — Returns the error code for the most recent function call
    • maxdb_error — Returns a string description of the last error
    • maxdb_escape_string — Alias of maxdb_real_escape_string
    • maxdb_execute — Alias of maxdb_stmt_execute
    • maxdb_fetch_array — Fetch a result row as an associative, a numeric array, or both
    • maxdb_fetch_assoc — Fetch a result row as an associative array
    • maxdb_fetch_field_direct — Fetch meta-data for a single field
    • maxdb_fetch_field — Returns the next field in the result set
    • maxdb_fetch_fields — Returns an array of resources representing the fields in a result set
    • maxdb_fetch_lengths — Returns the lengths of the columns of the current row in the result set
    • maxdb_fetch_object — Returns the current row of a result set as an object
    • maxdb_fetch_row — Get a result row as an enumerated array
    • maxdb_fetch — Alias of maxdb_stmt_fetch
    • maxdb_field_count — Returns the number of columns for the most recent query
    • maxdb_field_seek — Set result pointer to a specified field offset
    • maxdb_field_tell — Get current field offset of a result pointer
    • maxdb_free_result — Frees the memory associated with a result
    • maxdb_get_client_info — Returns the MaxDB client version as a string
    • maxdb_get_client_version — Get MaxDB client info
    • maxdb_get_host_info — Returns a string representing the type of connection used
    • maxdb_get_metadata — Alias of maxdb_stmt_result_metadata
    • maxdb_get_proto_info — Returns the version of the MaxDB protocol used
    • maxdb_get_server_info — Returns the version of the MaxDB server
    • maxdb_get_server_version — Returns the version of the MaxDB server as an integer
    • maxdb_info — Retrieves information about the most recently executed query
    • maxdb_init — Initializes MaxDB and returns an resource for use with maxdb_real_connect
    • maxdb_insert_id — Returns the auto generated id used in the last query
    • maxdb_kill — Disconnects from a MaxDB server
    • maxdb_master_query — Enforce execution of a query on the master in a master/slave setup
    • maxdb_more_results — Check if there any more query results from a multi query
    • maxdb_multi_query — Performs a query on the database
    • maxdb_next_result — Prepare next result from multi_query
    • maxdb_num_fields — Get the number of fields in a result
    • maxdb_num_rows — Gets the number of rows in a result
    • maxdb_options — Set options
    • maxdb_param_count — Alias of maxdb_stmt_param_count
    • maxdb_ping — Pings a server connection, or tries to reconnect if the connection has gone down
    • maxdb_prepare — Prepare an SQL statement for execution
    • maxdb_query — Performs a query on the database
    • maxdb_real_connect — Opens a connection to a MaxDB server
    • maxdb_real_escape_string — Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
    • maxdb_real_query — Execute an SQL query
    • maxdb_report — Enables or disables internal report functions
    • maxdb_rollback — Rolls back current transaction
    • maxdb_rpl_parse_enabled — Check if RPL parse is enabled
    • maxdb_rpl_probe — RPL probe
    • maxdb_rpl_query_type — Returns RPL query type
    • maxdb_select_db — Selects the default database for database queries
    • maxdb_send_long_data — Alias of maxdb_stmt_send_long_data
    • maxdb_send_query — Send the query and return
    • maxdb_server_end — Shut down the embedded server
    • maxdb_server_init — Initialize embedded server
    • maxdb_set_opt — Alias of maxdb_options
    • maxdb_sqlstate — Returns the SQLSTATE error from previous MaxDB operation
    • maxdb_ssl_set — Used for establishing secure connections using SSL
    • maxdb_stat — Gets the current system status
    • maxdb_stmt_affected_rows — Returns the total number of rows changed, deleted, or inserted by the last executed statement
    • maxdb_stmt_bind_param — Binds variables to a prepared statement as parameters
    • maxdb_stmt_bind_result — Binds variables to a prepared statement for result storage
    • maxdb_stmt_close_long_data — Ends a sequence of maxdb_stmt_send_long_data
    • maxdb_stmt_close — Closes a prepared statement
    • maxdb_stmt_data_seek — Seeks to an arbitray row in statement result set
    • maxdb_stmt_errno — Returns the error code for the most recent statement call
    • maxdb_stmt_error — Returns a string description for last statement error
    • maxdb_stmt_execute — Executes a prepared Query
    • maxdb_stmt_fetch — Fetch results from a prepared statement into the bound variables
    • maxdb_stmt_free_result — Frees stored result memory for the given statement handle
    • maxdb_stmt_init — Initializes a statement and returns an resource for use with maxdb_stmt_prepare
    • maxdb_stmt_num_rows — Return the number of rows in statements result set
    • maxdb_stmt_param_count — Returns the number of parameter for the given statement
    • maxdb_stmt_prepare — Prepare an SQL statement for execution
    • maxdb_stmt_reset — Resets a prepared statement
    • maxdb_stmt_result_metadata — Returns result set metadata from a prepared statement
    • maxdb_stmt_send_long_data — Send data in blocks
    • maxdb_stmt_sqlstate — Returns SQLSTATE error from previous statement operation
    • maxdb_stmt_store_result — Transfers a result set from a prepared statement
    • maxdb_store_result — Transfers a result set from the last query
    • maxdb_thread_id — Returns the thread ID for the current connection
    • maxdb_thread_safe — Returns whether thread safety is given or not
    • maxdb_use_result — Initiate a result set retrieval
    • maxdb_warning_count — Returns the number of warnings from the last query for the given link


Introduction

The MaxDB PHP extension allows you to access the functionality provided by MaxDB 7.5.0 and above. More information about the MaxDB Database server can be found at » http://www.sdn.sap.com/irj/sdn/maxdb.

The MaxDB PHP extension is compatible to the MySQL mysqli extension. There are only minor differences in the behaviour of some functions due to the differences of the underlying database servers, MaxDB and MySQL.

The main differences to mysqli are in the following functions:

  • maxdb_character_set_name() - Returns only ascii or unicode.
  • maxdb_get_client_info() - Returns a different version string.
  • maxdb_get_client_version() - Returns a different version string.
  • maxdb_get_host_info() - Returns localhost or hostname.
  • maxdb_get_server_info() - Returns a different version string.
  • maxdb_get_server_version() - Returns a different version string.
  • maxdb_kill() - Only disconnects the session.
  • maxdb_multi_query() - Can not handle multiple SQL statements.
  • maxdb_next_result() - Function returns always FALSE.
  • maxdb_options() - Supports a different set of options.
  • maxdb_report() - Supports a different report mode.
  • maxdb_stat() - Returns a different system status string.
  • maxdb_stmt_store_result() - Is not necessary for MaxDB.
  • maxdb_store_result() - Is not necessary for MaxDB.

Documentation for MaxDB can be found at » http://maxdb.sap.com/documentation/.


Requirements

In order to have these functions available, you must compile PHP with MaxDB support. Additionally, you must have the MaxDB SQLDBC runtime library available to access the MaxDB server.

Documentation for MaxDB SQLDBC can be found at » http://maxdb.sap.com/documentation/.

Download the MaxDB SQLDBC package from » http://www.sdn.sap.com/irj/sdn/maxdb-downloads.


Installation

By using the --with-maxdb[=DIR] configuration option you enable PHP to access MaxDB databases. [DIR] points to the directory that contains the installed MaxDB SQLDBC package.

Windows users will need to enable php_maxdb.dll inside of php.ini.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

MaxDB Configuration Options
Name | Default | Changeable | Changelog
maxdb.default_host | NULL | PHP_INI_ALL |
maxdb.default_db | NULL | PHP_INI_ALL |
maxdb.default_user | NULL | PHP_INI_ALL |
maxdb.default_pw | NULL | PHP_INI_ALL |
maxdb.long_readlen | "200" | PHP_INI_ALL |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

maxdb.default_host string

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

maxdb.default_db string

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

maxdb.default_user string

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

maxdb.default_pw string

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

maxdb.long_readlen integer

The default maximum length of bytes that is transferred to the client if long data is retrieved from the MaxDB database server.


  • « Runtime Configuration
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

This extension defines 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.

The following constants to use with maxdb_options() are defined. For further description of these constants see » http://maxdb.sap.com/documentation/.

MaxDB PHP client constants
Constants | Description
MAXDB_COMPNAME | The component name used to initialise the SQLDBC runtime environment.
MAXDB_APPLICATION | The application to be connected to the database.
MAXDB_APPVERSION | The version of the application.
MAXDB_SQLMODE | The SQL mode.
MAXDB_UNICODE | TRUE, if the connection is an unicode (UCS2) client or FALSE, if not.
MAXDB_TIMEOUT | The maximum allowed time of inactivity after which the connection to the database is closed by the system.
MAXDB_ISOLATIONLEVEL | Specifies whether and how shared locks and exclusive locks are implicitly requested or released.
MAXDB_PACKETCOUNT | The number of different request packets used for the connection.
MAXDB_STATEMENTCACHESIZE | The number of prepared statements to be cached for the connection for re-use.
MAXDB_CURSORPREFIX | The prefix to use for result tables that are automatically named.

The function maxdb_fetch_array() uses a constant for the different types of result arrays. The following constants are defined:

MaxDB fetch constants
Constants | Description
MAXDB_ASSOC | Columns are returned into the array having the fieldname as the array index.
MAXDB_ASSOC_UPPER | Columns are returned into the array having the upper case fieldname as the array index.
MAXDB_ASSOC_LOWER | Columns are returned into the array having the lower case fieldname as the array index.
MAXDB_BOTH | Columns are returned into the array having both a numerical index and the fieldname as the array index.
MAXDB_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.


  • « Predefined Constants
  • Basic usage »
  • PHP Manual
  • MaxDB
  • Examples

Examples

Table of Contents

  • Basic usage


Basic usage

All examples in the MaxDB PHP documentation use the HOTELDB demo database from MaxDB. More about this database can be found at » http://maxdb.sap.com/doc/7_7/44/d8c25164bb38d0e10000000a1553f7/content.htm.

To use the examples in the MaxDB PHP documentation, you have to load the tutorial data into your database. Then you have to set maxdb.default_db in php.ini to the database that contains the tutorial data.

This simple example shows how to connect, execute a query, print resulting rows and disconnect from a MaxDB database.

Example #1 MaxDB extension overview example

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Performing SQL query */
$query = "SELECT * FROM hotel.city";
$result = maxdb_query($link, $query) or die("Query failed : " . maxdb_error());

/* Printing results in HTML */
echo "<table>\n";
while ($line = maxdb_fetch_array($result, MAXDB_ASSOC)) {
    echo "  <tr>\n";
    foreach ($line as $col_value) {
        echo "    <td>$col_value</td>\n";
    }
    echo "  </tr>\n";
}
echo "</table>\n";

/* Free resultset */
maxdb_free_result($result);

/* Closing connection */
maxdb_close($link);
?>

The following example shows how to bind variables to a SELECT INTO statement.

Example #2 Example for use of SELECT INTO statements

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Performing SQL query */
$stmt = maxdb_prepare ($link, "SELECT percentage INTO ? FROM hotel.countrylanguage where language = ?");
if (!$stmt) {
  printf ("Prepare failed: %s\n", maxdb_error($link));
}

$name = "Mbundu";

maxdb_stmt_bind_param($stmt, 'ds', $percentage, $name);
maxdb_stmt_execute($stmt);

printf ("%f\n", $percentage);

maxdb_stmt_close ($stmt);
?>

The following example shows how to use MaxDB database procedures.

Example #3 Example fore using database procedures

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_report (MAXDB_REPORT_OFF);
maxdb_query($link,"DROP DBPROC test_proc");
maxdb_report (MAXDB_REPORT_ERROR);

$query = "create dbproc test_proc (INOUT e_text char(72)) AS select * from SYSDBA.DUAL; fetch into :e_text;";

maxdb_query($link, $query);

/* Performing SQL query */
$stmt = maxdb_prepare ($link, "CALL test_proc (?)");
if (!$stmt) {
  printf ("Prepare failed: %s\n", maxdb_error($link));
}

maxdb_stmt_bind_param($stmt, 's', $result);
maxdb_stmt_execute($stmt);

printf ("%s\n", $result);

maxdb_stmt_close ($stmt);
?>


MaxDB Functions

Predefined Classes

maxdb

Represents a connection between PHP and a MaxDB database.

Constructor

  • maxdb - construct a new maxdb object

Methods

  • autocommit - turns on or off auto-commiting database modifications

  • change_user - changes the user of the specified database connection

  • character_set_name - returns the default character set for the database connection

  • close - closes a previously opened connection

  • commit - commits the current transaction

  • connect - opens a new connection to MaxDB database server

  • debug - performs debugging operations

  • dump_debug_info - dumps debug information

  • get_client_info - returns client version

  • get_host_info - returns type of connection used

  • get_server_info - returns version of the MaxDB server

  • get_server_version - returns version of the MaxDB server

  • init - initializes maxdb object

  • info - retrieves information about the most recently executed query

  • kill - asks the server to kill a MaxDB thread

  • multi_query - performs multiple queries

  • more_results - check if more results exist from currently executed multi-query

  • next_result - reads next result from currently executed multi-query

  • options - set options

  • ping - pings a server connection or reconnects if there is no connection

  • prepare - prepares an SQL query

  • query - performs a query

  • real_connect - attempts to open a connection to MaxDB database server

  • escape_string - escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

  • rollback - rolls back the current transaction

  • select_db - selects the default database

  • ssl_set - sets ssl parameters

  • stat - gets the current system status

  • stmt_init- initializes a statement for use with maxdb_stmt_prepare

  • store_result - transfers a resultset from last query

  • use_result - transfers an unbuffered resultset from last query

  • thread-safe - returns whether thread safety is given or not

Properties

  • affected_rows - gets the number of affected rows in a previous MaxDB operation

  • client_info - returns the MaxDB client version as a string

  • client_version - returns the MaxDB client version as an integer

  • errno - returns the error code for the most recent function call

  • error - returns the error string for the most recent function call

  • field_count - returns the number of columns for the most recent query

  • host_info - returns a string representing the type of connection used

  • info - retrieves information about the most recently executed query

  • insert_id - returns the auto generated id used in the last query

  • protocol_version - returns the version of the MaxDB protocol used

  • sqlstate - returns a string containing the SQLSTATE error code for the last error

  • thread_id - returns the thread ID for the current connection

  • warning_count - returns the number of warnings generated during execution of the previous SQL statement

maxdb_stmt

Represents a prepared statement.

Methods

  • bind_param - binds variables to a prepared statement

  • bind_result - binds variables to a prepared statement for result storage

  • close - closes a prepared statement

  • data-seek - seeks to an arbitrary row in a statement result set

  • execute - executes a prepared statement

  • fetch - fetches result from a prepared statement into bound variables

  • free_result - frees stored result memory for the given statement handle

  • result_metadata - retrieves a resultset from a prepared statement for metadata information

  • prepare - prepares an SQL query

  • send_long_data - sends data in chunks

  • close_long_data - end sending long data

  • reset - resets a prepared statement

  • store_result - buffers complete resultset from a prepared statement

Properties

  • affected_rows - returns affected rows from last statement execution

  • errno - returns errorcode for last statement function

  • errno - returns errormessage for last statement function

  • param_count - returns number of parameter for a given prepare statement

  • sqlstate - returns a string containing the SQLSTATE error code for the last statement function

maxdb_result

Represents the result set obtained from a query against the database.

Methods

  • close - closes resultset

  • data_seek - moves internal result pointer

  • fetch_field - gets column information from a resultset

  • fetch_fields - gets information for all columns from a resulset

  • fetch_field_direct - gets column information for specified column

  • fetch_array - fetches a result row as an associative array, a numeric array, or both.

  • fetch_assoc - fetches a result row as an associative array

  • fetch_object - fetches a result row as an object

  • fetch_row - gets a result row as an enumerated array

  • close - frees result memory

  • field_seek - set result pointer to a specified field offset

Properties

  • current_field - returns offset of current fieldpointer

  • field_count - returns number of fields in resultset

  • lengths - returns an array of columnlengths

  • num_rows - returns number of rows in resultset

Table of Contents

  • maxdb_affected_rows — Gets the number of affected rows in a previous MaxDB operation
  • maxdb_autocommit — Turns on or off auto-commiting database modifications
  • maxdb_bind_param — Alias of maxdb_stmt_bind_param
  • maxdb_bind_result — Alias of maxdb_stmt_bind_result
  • maxdb_change_user — Changes the user of the specified database connection
  • maxdb_character_set_name — Returns the default character set for the database connection
  • maxdb_client_encoding — Alias of maxdb_character_set_name
  • maxdb_close_long_data — Alias of maxdb_stmt_close_long_data
  • maxdb_close — Closes a previously opened database connection
  • maxdb_commit — Commits the current transaction
  • maxdb_connect_errno — Returns the error code from last connect call
  • maxdb_connect_error — Returns a string description of the last connect error
  • maxdb_connect — Open a new connection to the MaxDB server
  • maxdb_data_seek — Adjusts the result pointer to an arbitary row in the result
  • maxdb_debug — Performs debugging operations
  • maxdb_disable_reads_from_master — Disable reads from master
  • maxdb_disable_rpl_parse — Disable RPL parse
  • maxdb_dump_debug_info — Dump debugging information into the log
  • maxdb_embedded_connect — Open a connection to an embedded MaxDB server
  • maxdb_enable_reads_from_master — Enable reads from master
  • maxdb_enable_rpl_parse — Enable RPL parse
  • maxdb_errno — Returns the error code for the most recent function call
  • maxdb_error — Returns a string description of the last error
  • maxdb_escape_string — Alias of maxdb_real_escape_string
  • maxdb_execute — Alias of maxdb_stmt_execute
  • maxdb_fetch_array — Fetch a result row as an associative, a numeric array, or both
  • maxdb_fetch_assoc — Fetch a result row as an associative array
  • maxdb_fetch_field_direct — Fetch meta-data for a single field
  • maxdb_fetch_field — Returns the next field in the result set
  • maxdb_fetch_fields — Returns an array of resources representing the fields in a result set
  • maxdb_fetch_lengths — Returns the lengths of the columns of the current row in the result set
  • maxdb_fetch_object — Returns the current row of a result set as an object
  • maxdb_fetch_row — Get a result row as an enumerated array
  • maxdb_fetch — Alias of maxdb_stmt_fetch
  • maxdb_field_count — Returns the number of columns for the most recent query
  • maxdb_field_seek — Set result pointer to a specified field offset
  • maxdb_field_tell — Get current field offset of a result pointer
  • maxdb_free_result — Frees the memory associated with a result
  • maxdb_get_client_info — Returns the MaxDB client version as a string
  • maxdb_get_client_version — Get MaxDB client info
  • maxdb_get_host_info — Returns a string representing the type of connection used
  • maxdb_get_metadata — Alias of maxdb_stmt_result_metadata
  • maxdb_get_proto_info — Returns the version of the MaxDB protocol used
  • maxdb_get_server_info — Returns the version of the MaxDB server
  • maxdb_get_server_version — Returns the version of the MaxDB server as an integer
  • maxdb_info — Retrieves information about the most recently executed query
  • maxdb_init — Initializes MaxDB and returns an resource for use with maxdb_real_connect
  • maxdb_insert_id — Returns the auto generated id used in the last query
  • maxdb_kill — Disconnects from a MaxDB server
  • maxdb_master_query — Enforce execution of a query on the master in a master/slave setup
  • maxdb_more_results — Check if there any more query results from a multi query
  • maxdb_multi_query — Performs a query on the database
  • maxdb_next_result — Prepare next result from multi_query
  • maxdb_num_fields — Get the number of fields in a result
  • maxdb_num_rows — Gets the number of rows in a result
  • maxdb_options — Set options
  • maxdb_param_count — Alias of maxdb_stmt_param_count
  • maxdb_ping — Pings a server connection, or tries to reconnect if the connection has gone down
  • maxdb_prepare — Prepare an SQL statement for execution
  • maxdb_query — Performs a query on the database
  • maxdb_real_connect — Opens a connection to a MaxDB server
  • maxdb_real_escape_string — Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
  • maxdb_real_query — Execute an SQL query
  • maxdb_report — Enables or disables internal report functions
  • maxdb_rollback — Rolls back current transaction
  • maxdb_rpl_parse_enabled — Check if RPL parse is enabled
  • maxdb_rpl_probe — RPL probe
  • maxdb_rpl_query_type — Returns RPL query type
  • maxdb_select_db — Selects the default database for database queries
  • maxdb_send_long_data — Alias of maxdb_stmt_send_long_data
  • maxdb_send_query — Send the query and return
  • maxdb_server_end — Shut down the embedded server
  • maxdb_server_init — Initialize embedded server
  • maxdb_set_opt — Alias of maxdb_options
  • maxdb_sqlstate — Returns the SQLSTATE error from previous MaxDB operation
  • maxdb_ssl_set — Used for establishing secure connections using SSL
  • maxdb_stat — Gets the current system status
  • maxdb_stmt_affected_rows — Returns the total number of rows changed, deleted, or inserted by the last executed statement
  • maxdb_stmt_bind_param — Binds variables to a prepared statement as parameters
  • maxdb_stmt_bind_result — Binds variables to a prepared statement for result storage
  • maxdb_stmt_close_long_data — Ends a sequence of maxdb_stmt_send_long_data
  • maxdb_stmt_close — Closes a prepared statement
  • maxdb_stmt_data_seek — Seeks to an arbitray row in statement result set
  • maxdb_stmt_errno — Returns the error code for the most recent statement call
  • maxdb_stmt_error — Returns a string description for last statement error
  • maxdb_stmt_execute — Executes a prepared Query
  • maxdb_stmt_fetch — Fetch results from a prepared statement into the bound variables
  • maxdb_stmt_free_result — Frees stored result memory for the given statement handle
  • maxdb_stmt_init — Initializes a statement and returns an resource for use with maxdb_stmt_prepare
  • maxdb_stmt_num_rows — Return the number of rows in statements result set
  • maxdb_stmt_param_count — Returns the number of parameter for the given statement
  • maxdb_stmt_prepare — Prepare an SQL statement for execution
  • maxdb_stmt_reset — Resets a prepared statement
  • maxdb_stmt_result_metadata — Returns result set metadata from a prepared statement
  • maxdb_stmt_send_long_data — Send data in blocks
  • maxdb_stmt_sqlstate — Returns SQLSTATE error from previous statement operation
  • maxdb_stmt_store_result — Transfers a result set from a prepared statement
  • maxdb_store_result — Transfers a result set from the last query
  • maxdb_thread_id — Returns the thread ID for the current connection
  • maxdb_thread_safe — Returns whether thread safety is given or not
  • maxdb_use_result — Initiate a result set retrieval
  • maxdb_warning_count — Returns the number of warnings from the last query for the given link


Gets the number of affected rows in a previous MaxDB operation

  • « MaxDB Functions
  • maxdb_autocommit »
  • PHP Manual
  • MaxDB Functions
  • Gets the number of affected rows in a previous MaxDB operation

maxdb_affected_rows

maxdb::affected_rows

(PECL maxdb >= 1.0)

maxdb_affected_rows -- maxdb::affected_rows — Gets the number of affected rows in a previous MaxDB operation

Description

Procedural style

maxdb_affected_rows ( resource $link ) : int

Object oriented style

int $maxdb->affected_rows;

maxdb_affected_rows() returns the number of rows affected by the last INSERT, UPDATE, or DELETE query associated with the provided link parameter. If this number cannot be determined, this function will return -1.

Note:

For SELECT statements maxdb_affected_rows() works like maxdb_num_rows().

The maxdb_affected_rows() function only works with queries which modify a table. In order to return the number of rows from a SELECT query, use the maxdb_num_rows() function instead.

Return Values

An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where 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 number of rows affected can not be determined.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_report (MAXDB_REPORT_OFF);
$maxdb->query("DROP TABLE mycustomer");
maxdb_report (MAXDB_REPORT_ERROR);

/* Insert rows */
$maxdb->query("CREATE TABLE mycustomer AS SELECT * from hotel.customer");
printf("Affected rows (INSERT): %d\n", $maxdb->affected_rows);

$maxdb->query("ALTER TABLE mycustomer ADD Status int default 0");

/* update rows */
$maxdb->query("UPDATE mycustomer SET Status=1 WHERE cno > 50");
printf("Affected rows (UPDATE): %d\n", $maxdb->affected_rows);

/* delete rows */
$maxdb->query("DELETE FROM mycustomer WHERE cno < 50");
printf("Affected rows (DELETE): %d\n", $maxdb->affected_rows);

/* select all rows */
$result = $maxdb->query("SELECT title FROM mycustomer");
printf("Affected rows (SELECT): %d\n", $maxdb->affected_rows);

$result->close();

/* Delete table Language */
$maxdb->query("DROP TABLE mycustomer");

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

if (!$link) {
   printf("Can't connect to localhost. Error: %s\n", maxdb_connect_error());
   exit();
}

maxdb_report (MAXDB_REPORT_OFF);
maxdb_query($link,"DROP TABLE mycustomer");
maxdb_report (MAXDB_REPORT_ERROR);

/* Insert rows */
maxdb_query($link, "CREATE TABLE mycustomer AS SELECT * from hotel.customer");
printf("Affected rows (INSERT): %d\n", maxdb_affected_rows($link));

maxdb_query($link, "ALTER TABLE mycustomer ADD Status int default 0");

/* update rows */
maxdb_query($link, "UPDATE mycustomer SET Status=1 WHERE cno > 50");
printf("Affected rows (UPDATE): %d\n", maxdb_affected_rows($link));

/* delete rows */
maxdb_query($link, "DELETE FROM mycustomer WHERE cno < 50");
printf("Affected rows (DELETE): %d\n", maxdb_affected_rows($link));

/* select all rows */
$result = maxdb_query($link, "SELECT title FROM mycustomer");
printf("Affected rows (SELECT): %d\n", maxdb_affected_rows($link));

maxdb_free_result($result);

/* Delete table Language */
maxdb_query($link, "DROP TABLE mycustomer");

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Affected rows (INSERT): 15
Affected rows (UPDATE): 15
Affected rows (DELETE): 0
Affected rows (SELECT): 15

See Also

  • maxdb_num_rows() - Gets the number of rows in a result
  • maxdb_info() - Retrieves information about the most recently executed query


Turns on or off auto-commiting database modifications

  • « maxdb_affected_rows
  • maxdb_bind_param »
  • PHP Manual
  • MaxDB Functions
  • Turns on or off auto-commiting database modifications

maxdb_autocommit

maxdb::auto_commit

(PECL maxdb >= 1.0)

maxdb_autocommit -- maxdb::auto_commit — Turns on or off auto-commiting database modifications

Description

Procedural style

maxdb_autocommit ( resource $link , bool $mode ) : bool

Object oriented style

maxdb::auto_commit ( bool $mode ) : bool

maxdb_autocommit() is used to turn on or off auto-commit mode on queries for the database connection represented by the link resource.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* turn autocommit on */
$maxdb->autocommit(TRUE);

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

if (!$link) {
   printf("Can't connect to localhost. Error: %s\n", maxdb_connect_error());
   exit();
}

/* turn autocommit on */
maxdb_autocommit($link, TRUE);

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

See Also

  • maxdb_commit() - Commits the current transaction
  • maxdb_rollback() - Rolls back current transaction


Alias of maxdb_stmt_bind_param

  • « maxdb_autocommit
  • maxdb_bind_result »
  • PHP Manual
  • MaxDB Functions
  • Alias of maxdb_stmt_bind_param

maxdb_bind_param

(PECL maxdb 1.0)

maxdb_bind_param — Alias of maxdb_stmt_bind_param()

Description

This function is an alias of: maxdb_stmt_bind_param()

This function alias is deprecated and only exists for backwards compatibility reasons. The use of this function is not recommended, as it may be removed from PHP in the future.


Alias of maxdb_stmt_bind_result

  • « maxdb_bind_param
  • maxdb_change_user »
  • PHP Manual
  • MaxDB Functions
  • Alias of maxdb_stmt_bind_result

maxdb_bind_result

(PECL maxdb 1.0)

maxdb_bind_result — Alias of maxdb_stmt_bind_result()

Description

This function is an alias of: maxdb_stmt_bind_result().

This function alias is deprecated and only exists for backwards compatibility reasons. The use of this function is not recommended, as it may be removed from PHP in the future.


Changes the user of the specified database connection

  • « maxdb_bind_result
  • maxdb_character_set_name »
  • PHP Manual
  • MaxDB Functions
  • Changes the user of the specified database connection

maxdb_change_user

maxdb::change_user

(PECL maxdb >= 1.0)

maxdb_change_user -- maxdb::change_user — Changes the user of the specified database connection

Description

Procedural style

maxdb_change_user ( resource $link , string $user , string $password , string $database ) : bool

Object oriented style

maxdb::change_user ( string $user , string $password , string $database ) : bool

maxdb_change_user() is used to change the user of the specified database connection as given by the link parameter and to set the current database to that specified by the database parameter.

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.

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.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php

/* connect database test */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($result = $maxdb->query("SELECT * FROM dual")) {
   $row = $result->fetch_row();
   printf("Result: %s\n", $row[0]);
   $result->free();
}

/* reset all and select a new database */
if (!$maxdb->change_user("DBADMIN", "SECRET", "DEMODB")) {
  printf("Database not running\n");
} else {
  printf("Database running\n");
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($result = maxdb_query($link, "SELECT * FROM dual")) {
   $row = maxdb_fetch_row($result);
   printf("Result: %s\n", $row[0]);
   maxdb_free_result($result);
}

/* reset all and select a new database */
if (!maxdb_change_user($link, "DBADMIN", "SECRET", "DEMODB")) {
  printf("Database not running\n");
} else {
  printf("Database running\n");
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Result: a
Database running

See Also

  • maxdb_connect() - Open a new connection to the MaxDB server
  • maxdb_select_db() - Selects the default database for database queries


Returns the default character set for the database connection

  • « maxdb_change_user
  • maxdb_client_encoding »
  • PHP Manual
  • MaxDB Functions
  • Returns the default character set for the database connection

maxdb_character_set_name

maxdb::character_set_name

(PECL maxdb >= 1.0)

maxdb_character_set_name -- maxdb::character_set_name — Returns the default character set for the database connection

Description

Procedural style

maxdb_character_set_name ( resource $link ) : string

Object oriented style

maxdb::character_set_name ( void ) : string

Returns the current character set for the database connection specified by the link parameter.

Return Values

The default character set for the current connection, either ascii or unicode.

Examples

Example #1 Object oriented style

<?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Print current character set */
$charset = $maxdb->character_set_name();
printf ("Current character set is %s\n", $charset);

$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Print current character set */
$charset = maxdb_character_set_name($link);
printf ("Current character set is %s\n",$charset);

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Current character set is ascii

See Also

  • maxdb_client_encoding() - Alias of maxdb_character_set_name
  • maxdb_real_escape_string() - Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection


Alias of maxdb_character_set_name

  • « maxdb_character_set_name
  • maxdb_close_long_data »
  • PHP Manual
  • MaxDB Functions
  • Alias of maxdb_character_set_name

maxdb_client_encoding

(PECL maxdb 1.0)

maxdb_client_encoding — Alias of maxdb_character_set_name()

Description

This function is an alias of: maxdb_character_set_name().

This function alias is deprecated and only exists for backwards compatibility reasons. The use of this function is not recommended, as it may be removed from PHP in the future.


Alias of maxdb_stmt_close_long_data

  • « maxdb_client_encoding
  • maxdb_close »
  • PHP Manual
  • MaxDB Functions
  • Alias of maxdb_stmt_close_long_data

maxdb_close_long_data

maxdb::close_long_data

(PECL maxdb >= 1.0)

maxdb_close_long_data -- maxdb::close_long_data — Alias of maxdb_stmt_close_long_data()

Description

This function is an alias of: maxdb_stmt_close_long_data().

This function alias is deprecated and only exists for backwards compatibility reasons. The use of this function is not recommended, as it may be removed from PHP in the future.


Closes a previously opened database connection

  • « maxdb_close_long_data
  • maxdb_commit »
  • PHP Manual
  • MaxDB Functions
  • Closes a previously opened database connection

maxdb_close

maxdb::close

(PECL maxdb >= 1.0)

maxdb_close -- maxdb::close — Closes a previously opened database connection

Description

Procedural style

maxdb_close ( resource $link ) : bool

Object oriented style

maxdb::close ( void ) : bool

The maxdb_close() function closes a previously opened database connection specified by the link parameter.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • maxdb_connect() - Open a new connection to the MaxDB server
  • maxdb_init() - Initializes MaxDB and returns an resource for use with maxdb_real_connect
  • maxdb_real_connect() - Opens a connection to a MaxDB server


Commits the current transaction

  • « maxdb_close
  • maxdb_connect_errno »
  • PHP Manual
  • MaxDB Functions
  • Commits the current transaction

maxdb_commit

maxdb::commit

(PECL maxdb >= 1.0)

maxdb_commit -- maxdb::commit — Commits the current transaction

Description

Procedural style

maxdb_commit ( resource $link ) : bool

Object oriented style

maxdb::commit ( void ) : bool

Commits the current transaction for the database connection specified by the link parameter.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* set autocommit to off */
$maxdb->autocommit(FALSE);

maxdb_report (MAXDB_REPORT_OFF);
$maxdb->query("DROP TABLE mycustomer");
maxdb_report (MAXDB_REPORT_ERROR);

$maxdb->query("CREATE TABLE mycustomer LIKE hotel.customer");

/* Insert some values */
$maxdb->query("INSERT INTO mycustomer VALUES (3000,'Mrs','Jenny','Porter','10580','1340 N.Ash Street, #3')");
$maxdb->query("INSERT INTO mycustomer VALUES (3100,'Mr','Peter','Brown','48226','1001 34th Str., APT.3')");

/* commit transaction */
$maxdb->commit();

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* set autocommit to off */
maxdb_autocommit($link, FALSE);

maxdb_report (MAXDB_REPORT_OFF);
maxdb_query($link,"DROP TABLE mycustomer");
maxdb_report (MAXDB_REPORT_ERROR);

maxdb_query($link, "CREATE TABLE mycustomer LIKE hotel.customer");

/* Insert some values */
maxdb_query($link, "INSERT INTO mycustomer VALUES (3000,'Mrs','Jenny','Porter','10580','1340 N.Ash Street, #3')");
maxdb_query($link, "INSERT INTO mycustomer VALUES (3100,'Mr','Peter','Brown','48226','1001 34th Str., APT.3')");

/* commit transaction */
maxdb_commit($link);

/* close connection */
maxdb_close($link);
?>

The above examples produces no output.

See Also

  • maxdb_autocommit() - Turns on or off auto-commiting database modifications
  • maxdb_rollback() - Rolls back current transaction


Returns the error code from last connect call

  • « maxdb_commit
  • maxdb_connect_error »
  • PHP Manual
  • MaxDB Functions
  • Returns the error code from last connect call

maxdb_connect_errno

(PECL maxdb >= 1.0)

maxdb_connect_errno — Returns the error code from last connect call

Description

maxdb_connect_errno ( void ) : int

The maxdb_connect_errno() function will return the last error code number for last call to maxdb_connect(). If no errors have occurred, this function will return zero.

Return Values

An error code value for the last call to maxdb_connect(), if it failed. zero means no error occurred.

Examples

Example #1 maxdb_connect_errno sample

<?php
$link = maxdb_connect("localhost", "XXXXXXXX", "YYYYYYYYY");

if (!$link) {
   printf("Can't connect to localhost. Errorcode: %d\n", maxdb_connect_errno());
}
?>

The above example will output something similar to:

PHP Warning:  maxdb_connect(): -4008 POS(1) Unknown user name/password combination [08004] <...>
Can't connect to localhost. Errorcode: -4008

See Also

  • maxdb_connect() - Open a new connection to the MaxDB server
  • maxdb_connect_error() - Returns a string description of the last connect error
  • maxdb_errno() - Returns the error code for the most recent function call
  • maxdb_error() - Returns a string description of the last error
  • maxdb_sqlstate() - Returns the SQLSTATE error from previous MaxDB operation


Returns a string description of the last connect error

  • « maxdb_connect_errno
  • maxdb_connect »
  • PHP Manual
  • MaxDB Functions
  • Returns a string description of the last connect error

maxdb_connect_error

(PECL maxdb >= 1.0)

maxdb_connect_error — Returns a string description of the last connect error

Description

maxdb_connect_error ( void ) : string

The maxdb_connect_error() function is identical to the corresponding maxdb_connect_errno() function in every way, except instead of returning an integer error code the maxdb_connect_error() function will return a string representation of the last error to occur for the last maxdb_connect() call. If no error has occurred, this function will return an empty string.

Return Values

A string that describes the error. An empty string if no error occurred.

Examples

Example #1 maxdb_connect_error sample

<?php

$link = maxdb_connect("localhost", "nonexisting_user", "");

if (!$link) {
   printf("Can't connect to localhost. Error: %s\n", maxdb_connect_error());
}
?>

The above example will output something similar to:

PHP Warning:  maxdb_connect(): -4008 POS(1) Unknown user name/password combination <...>
Can't connect to localhost. Error: POS(1) Unknown user name/password combination

See Also

  • maxdb_connect() - Open a new connection to the MaxDB server
  • maxdb_connect_errno() - Returns the error code from last connect call
  • maxdb_errno() - Returns the error code for the most recent function call
  • maxdb_error() - Returns a string description of the last error
  • maxdb_sqlstate() - Returns the SQLSTATE error from previous MaxDB operation


Open a new connection to the MaxDB server

  • « maxdb_connect_error
  • maxdb_data_seek »
  • PHP Manual
  • MaxDB Functions
  • Open a new connection to the MaxDB server

maxdb_connect

maxdb::__construct

(PECL maxdb >= 1.0)

maxdb_connect -- maxdb::__construct — Open a new connection to the MaxDB server

Description

Procedural style

maxdb_connect ([ string $host [, string $username [, string $passwd [, string $dbname [, int $port = 0 [, string $socket ]]]]]] ) : resource

Object oriented style

maxdb::__construct ([ string $host [, string $username [, string $passwd [, string $dbname [, int $port = 0 [, string $socket ]]]]]] )

The maxdb_connect() function attempts to open a connection to the MaxDB Server running on host which can be either a host name or an IP address. Passing the string "localhost" to this parameter, the local host is assumed. If successful, the maxdb_connect() will return an resource representing the connection to the database or FALSE on failure.

The username and password parameters specify the username and password under which to connect to the MaxDB server. If the password is not provided (the NULL value is passed), the MaxDB server will attempt to authenticate the user against the maxdb.default_pw in php.ini.

The dbname parameter if provided will specify the default database to be used when performing queries. If not provied, the entry maxdb.default_db in php.ini is used.

The port and socket parameters are ignored for the MaxDB server.

Return Values

Returns a resource which represents the connection to a MaxDB Server or FALSE if the connection failed.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

printf("Host information: %s\n", $maxdb->host_info);

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

printf("Host information: %s\n", maxdb_get_host_info($link));

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Host information: localhost


Adjusts the result pointer to an arbitary row in the result

  • « maxdb_connect
  • maxdb_debug »
  • PHP Manual
  • MaxDB Functions
  • Adjusts the result pointer to an arbitary row in the result

maxdb_data_seek

maxdb_result::data_seek

(PECL maxdb >= 1.0)

maxdb_data_seek -- maxdb_result::data_seek — Adjusts the result pointer to an arbitary row in the result

Description

Procedural style

maxdb_data_seek ( resource $result , int $offset ) : bool

Object oriented style

maxdb_result::data_seek ( int $offset ) : bool

The maxdb_data_seek() function seeks to an arbitrary result pointer specified by the offset in the result set represented by result. The offset parameter must be between zero and the total number of rows minus one (0..maxdb_num_rows() - 1).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER BY name";
if ($result = $maxdb->query( $query)) {

   /* seek to row no. 10 */
   $result->data_seek(10);

   /* fetch row */
   $row = $result->fetch_row();

   printf ("City: %s  State: %s\n", $row[0], $row[1]);

   /* free result set*/
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER BY name";

if ($result = maxdb_query($link, $query)) {

   /* seek to row no. 400 */
   maxdb_data_seek($result, 10);

   /* fetch row */
   $row = maxdb_fetch_row($result);

   printf ("City: %s  State: %s\n", $row[0], $row[1]);

   /* free result set*/
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

City: Irvine  State: CA

See Also

  • maxdb_store_result() - Transfers a result set from the last query
  • maxdb_fetch_row() - Get a result row as an enumerated array
  • maxdb_num_rows() - Gets the number of rows in a result


Performs debugging operations

  • « maxdb_data_seek
  • maxdb_disable_reads_from_master »
  • PHP Manual
  • MaxDB Functions
  • Performs debugging operations

maxdb_debug

(PECL maxdb >= 1.0)

maxdb_debug — Performs debugging operations

Description

maxdb_debug ( string $debug ) : void

The maxdb_debug() can be used to trace the SQLDBC communication. The following strings can be used as a parameter to maxdb_debug():

  • TRACE SHORT ON|OFF - Enables/disables method call trace.
  • TRACE LONG ON|OFF - Enables/disables method argument and detail debug trace.
  • TRACE PACKET ON|OFF|<size> - Enables/disables packet trace, limiting the size of the traced object to the specified number of bytes, or 1000 if no size is specified.
  • TRACE SQL ON|OFF - Enables/disables high level api trace.
  • TRACE TIMESTAMP ON|OFF - Enables/disables a timestamp prefix on each line that is traced.
  • TRACE SIZE <size> - Limits the size of the trace file to <size> bytes, at least 8192 bytes are required.

Return Values

maxdb_debug() doesn't return any value.

Examples

Example #1 Procedural style

<?php

maxdb_debug("trace packet 200");

$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* close connection */
maxdb_close($link);
?>

The above example produces no output.


Disable reads from master

  • « maxdb_debug
  • maxdb_disable_rpl_parse »
  • PHP Manual
  • MaxDB Functions
  • Disable reads from master

maxdb_disable_reads_from_master

maxdb::disable_reads_from_master

(PECL maxdb >= 1.0)

maxdb_disable_reads_from_master -- maxdb::disable_reads_from_master — Disable reads from master

Description

Procedural style

maxdb_disable_reads_from_master ( resource $link ) : bool

Object oriented style

maxdb::disable_reads_from_master ( void ) : void
Warning

This function is currently not documented; only its argument list is available.


Disable RPL parse

  • « maxdb_disable_reads_from_master
  • maxdb_dump_debug_info »
  • PHP Manual
  • MaxDB Functions
  • Disable RPL parse

maxdb_disable_rpl_parse

(PECL maxdb >= 1.0)

maxdb_disable_rpl_parse — Disable RPL parse

Description

maxdb_disable_rpl_parse ( resource $link ) : bool
Warning

This function is currently not documented; only its argument list is available.


Dump debugging information into the log

  • « maxdb_disable_rpl_parse
  • maxdb_embedded_connect »
  • PHP Manual
  • MaxDB Functions
  • Dump debugging information into the log

maxdb_dump_debug_info

(PECL maxdb >= 1.0)

maxdb_dump_debug_info — Dump debugging information into the log

Description

maxdb_dump_debug_info ( resource $link ) : bool
Warning

This function is currently not documented; only its argument list is available.


Open a connection to an embedded MaxDB server

  • « maxdb_dump_debug_info
  • maxdb_enable_reads_from_master »
  • PHP Manual
  • MaxDB Functions
  • Open a connection to an embedded MaxDB server

maxdb_embedded_connect

(PECL maxdb >= 1.0)

maxdb_embedded_connect — Open a connection to an embedded MaxDB server

Description

maxdb_embedded_connect ([ string $dbname ] ) : resource
Warning

This function is currently not documented; only its argument list is available.


Enable reads from master

  • « maxdb_embedded_connect
  • maxdb_enable_rpl_parse »
  • PHP Manual
  • MaxDB Functions
  • Enable reads from master

maxdb_enable_reads_from_master

(PECL maxdb >= 1.0)

maxdb_enable_reads_from_master — Enable reads from master

Description

maxdb_enable_reads_from_master ( resource $link ) : bool
Warning

This function is currently not documented; only its argument list is available.


Enable RPL parse

  • « maxdb_enable_reads_from_master
  • maxdb_errno »
  • PHP Manual
  • MaxDB Functions
  • Enable RPL parse

maxdb_enable_rpl_parse

(PECL maxdb >= 1.0)

maxdb_enable_rpl_parse — Enable RPL parse

Description

maxdb_enable_rpl_parse ( resource $link ) : bool
Warning

This function is currently not documented; only its argument list is available.


Returns the error code for the most recent function call

  • « maxdb_enable_rpl_parse
  • maxdb_error »
  • PHP Manual
  • MaxDB Functions
  • Returns the error code for the most recent function call

maxdb_errno

maxdb::errno

(PECL maxdb >= 1.0)

maxdb_errno -- maxdb::errno — Returns the error code for the most recent function call

Description

Procedural style

maxdb_errno ( resource $link ) : int

Object oriented style

int $maxdb->errno;

The maxdb_errno() function will return the last error code for the most recent MaxDB function call that can succeed or fail with respect to the database link defined by the link parameter. If no errors have occurred, this function will return zero.

Return Values

An error code value for the last call, if it failed. zero means no error occurred.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if (!$maxdb->query("SELECT xxx FROM hotel.city")) {
   printf("Errorcode: %d\n", $maxdb->errno);
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if (!maxdb_query($link, "SELECT xxx FROM hotel.city")) {
   printf("Errorcode: %d\n", maxdb_errno($link));
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

PHP Warning:  maxdb_query(): -4005 POS(8) Unknown column name:XXX [42000] <...>
Errorcode: -4005

See Also

  • maxdb_connect_errno() - Returns the error code from last connect call
  • maxdb_connect_error() - Returns a string description of the last connect error
  • maxdb_error() - Returns a string description of the last error
  • maxdb_sqlstate() - Returns the SQLSTATE error from previous MaxDB operation


Returns a string description of the last error

  • « maxdb_errno
  • maxdb_escape_string »
  • PHP Manual
  • MaxDB Functions
  • Returns a string description of the last error

maxdb_error

maxdb::error

(PECL maxdb >= 1.0)

maxdb_error -- maxdb::error — Returns a string description of the last error

Description

Procedural style

maxdb_error ( resource $link ) : string

Object oriented style

string $maxdb->error;

The maxdb_error() function is identical to the corresponding maxdb_errno() function in every way, except instead of returning an integer error code the maxdb_error() function will return a string representation of the last error to occur for the database connection represented by the link parameter. If no error has occurred, this function will return an empty string.

Return Values

A string that describes the error. An empty string if no error occurred.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if (!$maxdb->query("SELECT xxx FROM hotel.city")) {
   printf("Errormessage: %s\n", $maxdb->error);
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if (!maxdb_query($link, "SELECT xxx FROM hotel.city")) {
   printf("Errormessgae: %s\n", maxdb_error($link));
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

PHP Warning:  maxdb_query(): -4005 POS(8) Unknown column name:XXX [42000]
Errormessgae: POS(8) Unknown column name:XXX

See Also

  • maxdb_connect_errno() - Returns the error code from last connect call
  • maxdb_connect_error() - Returns a string description of the last connect error
  • maxdb_errno() - Returns the error code for the most recent function call
  • maxdb_sqlstate() - Returns the SQLSTATE error from previous MaxDB operation


Alias of maxdb_real_escape_string

  • « maxdb_error
  • maxdb_execute »
  • PHP Manual
  • MaxDB Functions
  • Alias of maxdb_real_escape_string

maxdb_escape_string

(PECL maxdb 1.0)

maxdb_escape_string — Alias of maxdb_real_escape_string()

Description

This function is an alias of: maxdb_real_escape_string().


Alias of maxdb_stmt_execute

  • « maxdb_escape_string
  • maxdb_fetch_array »
  • PHP Manual
  • MaxDB Functions
  • Alias of maxdb_stmt_execute

maxdb_execute

(PECL maxdb 1.0)

maxdb_execute — Alias of maxdb_stmt_execute()

Description

This function is an alias of: maxdb_stmt_execute().

This function alias is deprecated and only exists for backwards compatibility reasons. The use of this function is not recommended, as it may be removed from PHP in the future.


Fetch a result row as an associative, a numeric array, or both

  • « maxdb_execute
  • maxdb_fetch_assoc »
  • PHP Manual
  • MaxDB Functions
  • Fetch a result row as an associative, a numeric array, or both

maxdb_fetch_array

maxdb_result::fetch_array

(PECL maxdb >= 1.0)

maxdb_fetch_array -- maxdb_result::fetch_array — Fetch a result row as an associative, a numeric array, or both

Description

Procedural style

maxdb_fetch_array ( resource $result [, int $resulttype ] ) : mixed

Object oriented style

maxdb_result::fetch_array ([ int $resulttype ] ) : mixed

Returns an array that corresponds to the fetched row or NULL if there are no more rows for the resultset represented by the result parameter.

maxdb_fetch_array() is an extended version of the maxdb_fetch_row() function. In addition to storing the data in the numeric indices of the result array, the maxdb_fetch_array() function can also store the data in associative indices, using the field names of the result set as keys.

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to the PHP NULL value.

If two or more columns of the result have the same field names, the last column will take precedence and overwrite the earlier data. In order to access multiple columns with the same name, the numerically indexed version of the row must be used.

The optional second argument resulttype 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 MAXDB_ASSOC, MAXDB_ASSOC_UPPER, MAXDB_ASSOC_LOWER, MAXDB_NUM, or MAXDB_BOTH. By default the maxdb_fetch_array() function will assume MAXDB_BOTH, which is a combination of MAXDB_NUM and MAXDB_ASSOC for this parameter.

By using the MAXDB_ASSOC constant this function will behave identically to the maxdb_fetch_assoc(), while MAXDB_NUM will behave identically to the maxdb_fetch_row() function. The final option MAXDB_BOTH will create a single array with the attributes of both.

By using the MAXDB_ASSOC_UPPER constant, the behaviour of this function is identical to the use of MAXDB_ASSOC except the array index of a column is the fieldname in upper case.

By using the MAXDB_ASSOC_LOWER constant, the behaviour of this function is identical to the use of MAXDB_ASSOC except the array index of a column is the fieldname in lower case.

Return Values

Returns an array that corresponds to the fetched row or NULL if there are no more rows in resultset.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";
$result = $maxdb->query($query);

/* numeric array */
$row = $result->fetch_array(MAXDB_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);

/* associative array */
$row = $result->fetch_array(MAXDB_ASSOC);
printf ("%s (%s)\n", $row["NAME"], $row["STATE"]);

/* associative and numeric array */
$row = $result->fetch_array(MAXDB_BOTH);
printf ("%s (%s)\n", $row[0], $row["STATE"]);

/* free result set */
$result->close();

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";
$result = maxdb_query($link, $query);

/* numeric array */
$row = maxdb_fetch_array($result, MAXDB_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);

/* associative array */
$row = maxdb_fetch_array($result, MAXDB_ASSOC);
printf ("%s (%s)\n", $row["NAME"], $row["STATE"]);

/* associative and numeric array */
$row = maxdb_fetch_array($result, MAXDB_BOTH);
printf ("%s (%s)\n", $row[0], $row["STATE"]);

/* free result set */
maxdb_free_result($result);

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

New York (NY)
New York (NY)
Long Island (NY)

See Also

  • maxdb_fetch_assoc() - Fetch a result row as an associative array
  • maxdb_fetch_row() - Get a result row as an enumerated array
  • maxdb_fetch_resource()


Fetch a result row as an associative array

  • « maxdb_fetch_array
  • maxdb_fetch_field_direct »
  • PHP Manual
  • MaxDB Functions
  • Fetch a result row as an associative array

maxdb_fetch_assoc

maxdb_result::fetch_assoc

(PECL maxdb >= 1.0)

maxdb_fetch_assoc -- maxdb_result::fetch_assoc — Fetch a result row as an associative array

Description

Procedural style

maxdb_fetch_assoc ( resource $result ) : array

Object oriented style

maxdb_result::fetch_assoc ( void ) : array

Returns an associative array that corresponds to the fetched row or NULL if there are no more rows.

The maxdb_fetch_assoc() function is used to return an associative array representing the next row in the result set for the result represented by the result parameter, where each key in the array represents the name of one of the result set's columns.

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 maxdb_fetch_row() or add alias names.

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to the PHP NULL value.

Return Values

Returns an array that corresponds to the fetched row or NULL if there are no more rows in resultset.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";

if ($result = $maxdb->query($query)) {

   /* fetch associative array */
   while ($row = $result->fetch_assoc()) {
       printf ("%s (%s)\n", $row["NAME"], $row["STATE"]);
   }

   /* free result set */
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";

if ($result = maxdb_query($link, $query)) {

   /* fetch associative array */
   while ($row = maxdb_fetch_assoc($result)) {
       printf ("%s (%s)\n", $row["NAME"], $row["STATE"]);
   }

   /* free result set */
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

New York (NY)
New York (NY)
Long Island (NY)
Albany (NY)
Washington (DC)
Washington (DC)
Washington (DC)
Silver Spring (MD)
Daytona Beach (FL)
Deerfield Beach (FL)
Clearwater (FL)
Cincinnati (OH)
Detroit (MI)
Rosemont (IL)
Chicago (IL)
Chicago (IL)
New Orleans (LA)
Dallas (TX)
Los Angeles (CA)
Hollywood (CA)
Long Beach (CA)
Palm Springs (CA)
Irvine (CA)
Santa Clara (CA)
Portland (OR)

See Also

  • maxdb_fetch_array() - Fetch a result row as an associative, a numeric array, or both
  • maxdb_fetch_row() - Get a result row as an enumerated array
  • maxdb_fetch_resource()


Fetch meta-data for a single field

  • « maxdb_fetch_assoc
  • maxdb_fetch_field »
  • PHP Manual
  • MaxDB Functions
  • Fetch meta-data for a single field

maxdb_fetch_field_direct

maxdb_result::fetch_field_direct

(PECL maxdb >= 1.0)

maxdb_fetch_field_direct -- maxdb_result::fetch_field_direct — Fetch meta-data for a single field

Description

Procedural style

maxdb_fetch_field_direct ( resource $result , int $fieldnr ) : mixed

Object oriented style

maxdb_result::fetch_field_direct ( int $fieldnr ) : mixed

maxdb_fetch_field_direct() returns an resource which contains field definition information from specified resultset. The value of fieldnr must be in the range from 0 to number of fields - 1.

Return Values

Returns an resource which contains field definition information or FALSE if no field information for specified fieldnr is available.

Object attributes
Attribute | Description
name | The name of the column
max_length | The maximum width of the field for the result set.
type | The data type used for this field
decimals | The number of decimals used (for integer fields)

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY name";

if ($result = $maxdb->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 */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY name";

if ($result = maxdb_query($link, $query)) {

   /* Get field information for column 'cno' */
   $finfo = maxdb_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);

   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Name:     CNO
Table:
max. Len: 4
Flags:    -1
Type:     0

See Also

  • maxdb_num_fields() - Get the number of fields in a result
  • maxdb_fetch_field() - Returns the next field in the result set
  • maxdb_fetch_fields() - Returns an array of resources representing the fields in a result set


Returns the next field in the result set

  • « maxdb_fetch_field_direct
  • maxdb_fetch_fields »
  • PHP Manual
  • MaxDB Functions
  • Returns the next field in the result set

maxdb_fetch_field

maxdb_result::fetch_field

(PECL maxdb >= 1.0)

maxdb_fetch_field -- maxdb_result::fetch_field — Returns the next field in the result set

Description

Procedural style

maxdb_fetch_field ( resource $result ) : mixed

Object oriented style

maxdb_result::fetch_field ( void ) : mixed

The maxdb_fetch_field() returns the definition of one column of a result set as an resource. Call this function repeatedly to retrieve information about all columns in the result set. maxdb_fetch_field() returns FALSE when no more fields are left.

Return Values

Returns an resource which contains field definition information or FALSE if no field information is available.

Object properties
Property | Description
name | The name of the column
max_length | The maximum width of the field for the result set.
type | The data type used for this field
decimals | The number of decimals used (for integer fields)

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = $maxdb->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 */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = maxdb_query($link, $query)) {

   /* Get field information for all fields */
   while ($finfo = maxdb_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);
   }
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Name:     NAME
Table:
max. Len: 10
Flags:    -1
Type:     2

Name:     CNO
Table:
max. Len: 4
Flags:    -1
Type:     0

See Also

  • maxdb_num_fields() - Get the number of fields in a result
  • maxdb_fetch_field_direct() - Fetch meta-data for a single field
  • maxdb_fetch_fields() - Returns an array of resources representing the fields in a result set
  • maxdb_field_seek() - Set result pointer to a specified field offset


Returns an array of resources representing the fields in a result set

  • « maxdb_fetch_field
  • maxdb_fetch_lengths »
  • PHP Manual
  • MaxDB Functions
  • Returns an array of resources representing the fields in a result set

maxdb_fetch_fields

maxdb_result::fetch_fields

(PECL maxdb >= 1.0)

maxdb_fetch_fields -- maxdb_result::fetch_fields — Returns an array of resources representing the fields in a result set

Description

Procedural style

maxdb_fetch_fields ( resource $result ) : mixed

Object oriented style

maxdb_result::fetch_fields ( void ) : mixed

This function serves an identical purpose to the maxdb_fetch_field() function with the single difference that, instead of returning one resource at a time for each field, the columns are returned as an array of resources.

Return Values

Returns an array of resources which contains field definition information or FALSE if no field information is available.

Object properties
Property | Description
name | The name of the column
max_length | The maximum width of the field for the result set.
type | The data type used for this field
decimals | The number of decimals used (for integer fields)

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = $maxdb->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("Flags:    %d\n", $val->flags);
       printf("Type:     %d\n\n", $val->type);
   }
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = maxdb_query($link, $query)) {

   /* Get field information for all columns */
   $finfo = maxdb_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("Flags:    %d\n", $val->flags);
       printf("Type:     %d\n\n", $val->type);
   }
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Name:     NAME
Table:
max. Len: 10
Flags:    -1
Type:     2

Name:     CNO
Table:
max. Len: 4
Flags:    -1
Type:     0

See Also

  • maxdb_num_fields() - Get the number of fields in a result
  • maxdb_fetch_field() - Returns the next field in the result set
  • maxdb_fetch_field_direct() - Fetch meta-data for a single field


Returns the lengths of the columns of the current row in the result set

  • « maxdb_fetch_fields
  • maxdb_fetch_object »
  • PHP Manual
  • MaxDB Functions
  • Returns the lengths of the columns of the current row in the result set

maxdb_fetch_lengths

maxdb_result::lengths

(PECL maxdb >= 1.0)

maxdb_fetch_lengths -- maxdb_result::lengths — Returns the lengths of the columns of the current row in the result set

Description

Procedural style

maxdb_fetch_lengths ( resource $result ) : array

Object oriented style

array $maxdb_result->lengths;

The maxdb_fetch_lengths() function returns an array containing the lengths of every column of the current row within the result set represented by the result parameter. If successful, a numerically indexed array representing the lengths of each column is returned or FALSE on failure.

Return Values

An array of integers representing the size of each column (not including any terminating null characters). FALSE if an error occurred.

maxdb_fetch_lengths() is valid only for the current row of the result set. It returns FALSE if you call it before calling maxdb_fetch_row/array/resource or after retrieving all rows in the result.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT * from hotel.customer WHERE cno = 3000";

if ($result = $maxdb->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 */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT * from hotel.customer WHERE cno = 3000";

if ($result = maxdb_query($link, $query)) {

   $row = maxdb_fetch_row($result);

   /* display column lengths */
   foreach (maxdb_fetch_lengths($result) as $i => $val) {
       printf("Field %2d has Length %2d\n", $i+1, $val);
   }
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Field  1 has Length  4
Field  2 has Length  3
Field  3 has Length  5
Field  4 has Length  6
Field  5 has Length  5
Field  6 has Length 21


Returns the current row of a result set as an object

  • « maxdb_fetch_lengths
  • maxdb_fetch_row »
  • PHP Manual
  • MaxDB Functions
  • Returns the current row of a result set as an object

maxdb_fetch_object

maxdb_result::fetch_object

(PECL maxdb >= 1.0)

maxdb_fetch_object -- maxdb_result::fetch_object — Returns the current row of a result set as an object

Description

Procedural style

maxdb_fetch_object ( object $result ) : object

Object oriented style

maxdb_result::fetch_object ( void ) : object

The maxdb_fetch_object() will return the current row result set as an object where the attributes of the object represent the names of the fields found within the result set. If no more rows exist in the current result set, NULL is returned.

Return Values

Returns an object that corresponds to the fetched row or NULL if there are no more rows in resultset.

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to the PHP NULL value.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";

if ($result = $maxdb->query($query)) {

   /* fetch object array */
   while ($obj = $result->fetch_object()) {
       printf ("%s (%s)\n", $obj->NAME, $obj->STATE);
   }

   /* free result set */
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";

if ($result = maxdb_query($link, $query)) {

   /* fetch object array */
   while ($obj = maxdb_fetch_object($result)) {
       printf ("%s (%s)\n", $obj->NAME, $obj->STATE);
   }

   /* free result set */
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

New York (NY)
New York (NY)
Long Island (NY)
Albany (NY)
Washington (DC)
Washington (DC)
Washington (DC)
Silver Spring (MD)
Daytona Beach (FL)
Deerfield Beach (FL)
Clearwater (FL)
Cincinnati (OH)
Detroit (MI)
Rosemont (IL)
Chicago (IL)
Chicago (IL)
New Orleans (LA)
Dallas (TX)
Los Angeles (CA)
Hollywood (CA)
Long Beach (CA)
Palm Springs (CA)
Irvine (CA)
Santa Clara (CA)
Portland (OR)

See Also

  • maxdb_fetch_array() - Fetch a result row as an associative, a numeric array, or both
  • maxdb_fetch_assoc() - Fetch a result row as an associative array
  • maxdb_fetch_row() - Get a result row as an enumerated array


Get a result row as an enumerated array

  • « maxdb_fetch_object
  • maxdb_fetch »
  • PHP Manual
  • MaxDB Functions
  • Get a result row as an enumerated array

maxdb_fetch_row

maxdb_result::fetch_row

(PECL maxdb >= 1.0)

maxdb_fetch_row -- maxdb_result::fetch_row — Get a result row as an enumerated array

Description

Procedural style

maxdb_fetch_row ( resource $result ) : mixed

Object oriented style

maxdb_result::fetch_row ( void ) : mixed

Returns an array that corresponds to the fetched row, or NULL if there are no more rows.

maxdb_fetch_row() fetches one row of data from the result set represented by result and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero). Each subsequent call to the maxdb_fetch_row() function will return the next row within the result set, or FALSE if there are no more rows.

Return Values

maxdb_fetch_row() returns an array that corresponds to the fetched row or NULL if there are no more rows in result set.

Note: This function sets NULL fields to the PHP NULL value.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";

if ($result = $maxdb->query($query)) {

   /* fetch enumerated array */
   while ($row = $result->fetch_row()) {
       printf ("%s (%s)\n", $row[0], $row[1]);
   }

   /* free result set */
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, state FROM hotel.city ORDER by zip";

if ($result = maxdb_query($link, $query)) {

   /* fetch enumerated array */
   while ($row = maxdb_fetch_row($result)) {
       printf ("%s (%s)\n", $row[0], $row[1]);
   }

   /* free result set */
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

New York (NY)
New York (NY)
Long Island (NY)
Albany (NY)
Washington (DC)
Washington (DC)
Washington (DC)
Silver Spring (MD)
Daytona Beach (FL)
Deerfield Beach (FL)
Clearwater (FL)
Cincinnati (OH)
Detroit (MI)
Rosemont (IL)
Chicago (IL)
Chicago (IL)
New Orleans (LA)
Dallas (TX)
Los Angeles (CA)
Hollywood (CA)
Long Beach (CA)
Palm Springs (CA)
Irvine (CA)
Santa Clara (CA)
Portland (OR)

See Also

  • maxdb_fetch_array() - Fetch a result row as an associative, a numeric array, or both
  • maxdb_fetch_assoc() - Fetch a result row as an associative array
  • maxdb_fetch_resource()


Alias of maxdb_stmt_fetch

  • « maxdb_fetch_row
  • maxdb_field_count »
  • PHP Manual
  • MaxDB Functions
  • Alias of maxdb_stmt_fetch

maxdb_fetch

(PECL maxdb 1.0)

maxdb_fetch — Alias of maxdb_stmt_fetch()

Description

This function is an alias of: maxdb_stmt_fetch().

This function alias is deprecated and only exists for backwards compatibility reasons. The use of this function is not recommended, as it may be removed from PHP in the future.


Returns the number of columns for the most recent query

  • « maxdb_fetch
  • maxdb_field_seek »
  • PHP Manual
  • MaxDB Functions
  • Returns the number of columns for the most recent query

maxdb_field_count

maxdb::field_count

(PECL maxdb >= 1.0)

maxdb_field_count -- maxdb::field_count — Returns the number of columns for the most recent query

Description

Procedural style

maxdb_field_count ( resource $link ) : int

Object oriented style

maxdb::field_count ( void ) : int

Returns the number of columns for the most recent query on the connection represented by the link parameter. This function can be useful when using the maxdb_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.

Return Values

An integer representing the number of fields in a result set.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

maxdb_report (MAXDB_REPORT_OFF);
$maxdb->query("DROP TABLE friends");
maxdb_report (MAXDB_REPORT_ERROR);

$maxdb->query( "CREATE TABLE friends (id int, name varchar(20))");

$maxdb->query( "INSERT INTO friends VALUES (1,'Hartmut')");
$maxdb->query( "INSERT INTO friends VALUES (2, 'Ulf')");

if ($maxdb->field_count()) {
   /* this was a select/show or describe query */
   $result = $maxdb->store_result();

   /* process resultset */
   $row = $result->fetch_row();

   /* free resultset */
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

maxdb_report (MAXDB_REPORT_OFF);
maxdb_query($link,"DROP TABLE friends");
maxdb_report (MAXDB_REPORT_ERROR);

maxdb_query($link, "CREATE TABLE friends (id int, name varchar(20))");

maxdb_query($link, "INSERT INTO friends VALUES (1,'Hartmut')");
maxdb_query($link, "INSERT INTO friends VALUES (2, 'Ulf')");

if (maxdb_field_count($link)) {
   /* this was a select/show or describe query */
   $result = maxdb_store_result($link);

   /* process resultset */
   $row = maxdb_fetch_row($result);

   /* free resultset */
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example produces no output.


Set result pointer to a specified field offset

  • « maxdb_field_count
  • maxdb_field_tell »
  • PHP Manual
  • MaxDB Functions
  • Set result pointer to a specified field offset

maxdb_field_seek

maxdb_result::field_seek

(PECL maxdb >= 1.0)

maxdb_field_seek -- maxdb_result::field_seek — Set result pointer to a specified field offset

Description

Procedural style

maxdb_field_seek ( resource $result , int $fieldnr ) : bool

Object oriented style

maxdb_result::field_seek ( int $fieldnr ) : bool

Sets the field cursor to the given offset. The next call to maxdb_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.

Return Values

maxdb_field_seek() returns previuos value of field cursor.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = $maxdb->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 */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = maxdb_query($link, $query)) {

   /* Get field information for 2nd column */
   maxdb_field_seek($result, 1);
   $finfo = maxdb_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);

   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Name:     NAME
Table:
max. Len: 10
Flags:    -1
Type:     2

See Also

  • maxdb_fetch_field() - Returns the next field in the result set


Get current field offset of a result pointer

  • « maxdb_field_seek
  • maxdb_free_result »
  • PHP Manual
  • MaxDB Functions
  • Get current field offset of a result pointer

maxdb_field_tell

maxdb_result::current_field

(PECL maxdb >= 1.0)

maxdb_field_tell -- maxdb_result::current_field — Get current field offset of a result pointer

Description

Procedural style

maxdb_field_tell ( resource $result ) : int

Object oriented style

int $maxdb_result->current_field;

Returns the position of the field cursor used for the last maxdb_fetch_field() call. This value can be used as an argument to maxdb_field_seek().

Return Values

Returns current offset of field cursor.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = $maxdb->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 */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, cno from hotel.customer ORDER BY cno";

if ($result = maxdb_query($link, $query)) {

   /* Get field information for all fields */
   while ($finfo = maxdb_fetch_field($result)) {

       /* get fieldpointer offset */
       $currentfield = maxdb_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);
   }
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Column    1:
Name:     NAME
Table:
max. Len: 10
Flags:    -1
Type:     2

Column    2:
Name:     CNO
Table:
max. Len: 4
Flags:    -1
Type:     0

See Also

  • maxdb_fetch_field() - Returns the next field in the result set
  • maxdb_field_seek() - Set result pointer to a specified field offset


Frees the memory associated with a result

  • « maxdb_field_tell
  • maxdb_get_client_info »
  • PHP Manual
  • MaxDB Functions
  • Frees the memory associated with a result

maxdb_free_result

maxdb_result::free

(PECL maxdb >= 1.0)

maxdb_free_result -- maxdb_result::free — Frees the memory associated with a result

Description

Procedural style

maxdb_free_result ( resource $result ) : void

Object oriented style

maxdb_result::free ( void ) : void

The maxdb_free_result() function frees the memory associated with the result represented by the result parameter, which was allocated by maxdb_query(), maxdb_store_result() or maxdb_use_result().

Note:

You should always free your result with maxdb_free_result(), when your result resource is not needed anymore.

Return Values

This function doesn't return any value.

See Also

  • maxdb_query() - Performs a query on the database
  • maxdb_stmt_store_result() - Transfers a result set from a prepared statement
  • maxdb_store_result() - Transfers a result set from the last query
  • maxdb_use_result() - Initiate a result set retrieval


Returns the MaxDB client version as a string

  • « maxdb_free_result
  • maxdb_get_client_version »
  • PHP Manual
  • MaxDB Functions
  • Returns the MaxDB client version as a string

maxdb_get_client_info

(PECL maxdb >= 1.0)

maxdb_get_client_info — Returns the MaxDB client version as a string

Description

maxdb_get_client_info ( void ) : string

The maxdb_get_client_info() function is used to return a string representing the client version being used in the MaxDB extension.

Return Values

A string that represents the MaxDB client library version

Examples

Example #1 maxdb_get_client_info

<?php

/* We don't need a connection to determine
   the version of MaxDB client library */

printf("Client library version: %s\n", maxdb_get_client_info());
?>

The above example will output something similar to:

Client library version: libSQLDBC <...>

See Also

  • maxdb_get_client_version() - Get MaxDB client info
  • maxdb_get_server_info() - Returns the version of the MaxDB server
  • maxdb_get_server_version() - Returns the version of the MaxDB server as an integer


Get MaxDB client info

  • « maxdb_get_client_info
  • maxdb_get_host_info »
  • PHP Manual
  • MaxDB Functions
  • Get MaxDB client info

maxdb_get_client_version

(PECL maxdb >= 1.0)

maxdb_get_client_version — Get MaxDB client info

Description

maxdb_get_client_version ( void ) : int

Returns client version number as an integer.

Return Values

A number that represents the MaxDB client library version in format: main_version*10000 + minor_version *100 + sub_version. For example, 7.5.0 is returned as 70500.

This is useful to quickly determine the version of the client library to know if some capability exists.

Examples

Example #1 maxdb_get_client_version

<?php

/* We don't need a connection to determine
   the version of MaxDB client library */

printf("Client library version: %d\n", maxdb_get_client_version());
?>

The above example will output something similar to:

Client library version: 7.<...>

See Also

  • maxdb_get_client_info() - Returns the MaxDB client version as a string
  • maxdb_get_server_info() - Returns the version of the MaxDB server
  • maxdb_get_server_version() - Returns the version of the MaxDB server as an integer


Returns a string representing the type of connection used

  • « maxdb_get_client_version
  • maxdb_get_metadata »
  • PHP Manual
  • MaxDB Functions
  • Returns a string representing the type of connection used

maxdb_get_host_info

maxdb::get_host_info

(PECL maxdb >= 1.0)

maxdb_get_host_info -- maxdb::get_host_info — Returns a string representing the type of connection used

Description

Procedural style

maxdb_get_host_info ( resource $link ) : string

Object oriented style

string $maxdb->host_info;

The maxdb_get_host_info() function returns a string describing the connection represented by the link parameter is using.

Return Values

A character string representing the server hostname and the connection type.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print host information */
printf("Host info: %s\n", $maxdb->host_info);

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print host information */
printf("Host info: %s\n", maxdb_get_host_info($link));

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Host info: localhost

See Also

  • maxdb_get_proto_info() - Returns the version of the MaxDB protocol used


Alias of maxdb_stmt_result_metadata

  • « maxdb_get_host_info
  • maxdb_get_proto_info »
  • PHP Manual
  • MaxDB Functions
  • Alias of maxdb_stmt_result_metadata

maxdb_get_metadata

(PECL maxdb 1.0)

maxdb_get_metadata — Alias of maxdb_stmt_result_metadata()

Description

This function is an alias of: maxdb_stmt_result_metadata().

This function alias is deprecated and only exists for backwards compatibility reasons. The use of this function is not recommended, as it may be removed from PHP in the future.


Returns the version of the MaxDB protocol used

  • « maxdb_get_metadata
  • maxdb_get_server_info »
  • PHP Manual
  • MaxDB Functions
  • Returns the version of the MaxDB protocol used

maxdb_get_proto_info

maxdb::protocol_version

(PECL maxdb >= 1.0)

maxdb_get_proto_info -- maxdb::protocol_version — Returns the version of the MaxDB protocol used

Description

Procedural style

maxdb_get_proto_info ( resource $link ) : int

Object oriented style

string $maxdb->protocol_version;

Returns an integer representing the MaxDB protocol version used by the connection represented by the link parameter.

Return Values

Returns an integer representing the protocol version (constant 10).

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print protocol version */
printf("Protocol version: %d\n", $maxdb->protocol_version);

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print protocol version */
printf("Protocol version: %d\n", maxdb_get_proto_info($link));

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Protocol version: 10

See Also

  • maxdb_get_host_info() - Returns a string representing the type of connection used


Returns the version of the MaxDB server

  • « maxdb_get_proto_info
  • maxdb_get_server_version »
  • PHP Manual
  • MaxDB Functions
  • Returns the version of the MaxDB server

maxdb_get_server_info

maxdb::server_info

(PECL maxdb >= 1.0)

maxdb_get_server_info -- maxdb::server_info — Returns the version of the MaxDB server

Description

Procedural style

maxdb_get_server_info ( resource $link ) : string

Object oriented style

string $maxdb->server_info;

Returns a string representing the version of the MaxDB server that the MaxDB extension is connected to (represented by the link parameter).

Return Values

A character string representing the server version.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print server version */
printf("Server version: %s\n", $maxdb->server_info);

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print server version */
printf("Server version: %s\n", maxdb_get_server_info($link));

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Server version: Kernel    7<...>

See Also

  • maxdb_get_client_info() - Returns the MaxDB client version as a string
  • maxdb_get_client_version() - Get MaxDB client info
  • maxdb_get_server_version() - Returns the version of the MaxDB server as an integer


Returns the version of the MaxDB server as an integer

  • « maxdb_get_server_info
  • maxdb_info »
  • PHP Manual
  • MaxDB Functions
  • Returns the version of the MaxDB server as an integer

maxdb_get_server_version

maxdb::server_version

(PECL maxdb >= 1.0)

maxdb_get_server_version -- maxdb::server_version — Returns the version of the MaxDB server as an integer

Description

Procedural style

maxdb_get_server_version ( resource $link ) : int

Object oriented style

int $maxdb->server_version;

The maxdb_get_server_version() function returns the version of the server connected to (represented by the link parameter) as an integer.

The form of this version number is main_version * 10000 + minor_version * 100 + sub_version (i.e. version 7.5.0 is 70500).

Return Values

An integer representing the server version.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print server version */
printf("Server version: %d\n", $maxdb->server_version);

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* print server version */
printf("Server version: %d\n", maxdb_get_server_version($link));

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Server version: 7<...>

See Also

  • maxdb_get_client_info() - Returns the MaxDB client version as a string
  • maxdb_get_client_version() - Get MaxDB client info
  • maxdb_get_server_info() - Returns the version of the MaxDB server


Retrieves information about the most recently executed query

  • « maxdb_get_server_version
  • maxdb_init »
  • PHP Manual
  • MaxDB Functions
  • Retrieves information about the most recently executed query

maxdb_info

maxdb::info

(PECL maxdb >= 1.0)

maxdb_info -- maxdb::info — Retrieves information about the most recently executed query

Description

Procedural style

maxdb_info ( resource $link ) : string

Object oriented style

string $maxdb->info;

The maxdb_info() function returns a string providing information about the last query executed. The nature of this string is provided below:

Possible maxdb_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 above formats are not supported. In these situations, maxdb_info() will return an empty string.

Return Values

A character string representing additional information about the most recently executed query.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query("CREATE TABLE temp.t1 LIKE hotel.city");

/* INSERT INTO .. SELECT */
$maxdb->query("INSERT INTO temp.t1 SELECT * FROM hotel.city");
printf("%s\n", $maxdb->info);

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.t1 LIKE hotel.city");

/* INSERT INTO .. SELECT */
maxdb_query($link, "INSERT INTO temp.t1 SELECT * FROM hotel.city");
printf("%s\n", maxdb_info($link));

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Records: 25 Duplicates: 0 Warnings: 0

See Also

  • maxdb_affected_rows() - Gets the number of affected rows in a previous MaxDB operation
  • maxdb_warning_count() - Returns the number of warnings from the last query for the given link
  • maxdb_num_rows() - Gets the number of rows in a result


Initializes MaxDB and returns an resource for use with maxdb_real_connect

  • « maxdb_info
  • maxdb_insert_id »
  • PHP Manual
  • MaxDB Functions
  • Initializes MaxDB and returns an resource for use with maxdb_real_connect

maxdb_init

(PECL maxdb >= 1.0)

maxdb_init — Initializes MaxDB and returns an resource for use with maxdb_real_connect

Description

maxdb_init ( void ) : resource

Allocates or initializes a MaxDB resource suitable for maxdb_options() and maxdb_real_connect().

Note:

Any subsequent calls to any maxdb function (except maxdb_options()) will fail until maxdb_real_connect() was called.

Return Values

Returns an resource.

See Also

  • maxdb_options() - Set options
  • maxdb_close() - Closes a previously opened database connection
  • maxdb_real_connect() - Opens a connection to a MaxDB server
  • maxdb_connect() - Open a new connection to the MaxDB server


Returns the auto generated id used in the last query

  • « maxdb_init
  • maxdb_kill »
  • PHP Manual
  • MaxDB Functions
  • Returns the auto generated id used in the last query

maxdb_insert_id

maxdb::insert_id

(PECL maxdb >= 1.0)

maxdb_insert_id -- maxdb::insert_id — Returns the auto generated id used in the last query

Description

Procedural style

maxdb_insert_id ( resource $link ) : mixed

Object oriented style

mixed $maxdb->insert_id;

The maxdb_insert_id() function returns the ID generated by a query on a table with a column having the DEFAULT SERIAL attribute. If the last query wasn't an INSERT or UPDATE statement or if the modified table does not have a column with the DEFAULT SERIAL attribute, this function will return zero.

Return Values

The value of the DEFAULT SERIAL 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 DEFAULT_SERIAL value.

Note:

If the number is greater than maximal int value, maxdb_insert_id() will return a string.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_report (MAXDB_REPORT_OFF);
$maxdb->query("DROP TABLE mycity");
maxdb_report (MAXDB_REPORT_ERROR);

$maxdb->query("CREATE TABLE mycity LIKE hotel.city");
$maxdb->query("ALTER TABLE mycity ADD id FIXED(11) DEFAULT SERIAL");

$query = "INSERT INTO mycity (zip,name,state) VALUES ('12203','Albany' ,'NY')";
$maxdb->query($query);

printf ("New Record has id %d.\n", $maxdb->insert_id);

/* drop table */
$maxdb->query("DROP TABLE mycity");

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_report (MAXDB_REPORT_OFF);
maxdb_query($link,"DROP TABLE mycity");
maxdb_report (MAXDB_REPORT_ERROR);

maxdb_query($link, "CREATE TABLE mycity LIKE hotel.city");
maxdb_query($link, "ALTER TABLE mycity ADD id FIXED(11) DEFAULT SERIAL");

$query = "INSERT INTO mycity (zip,name,state) VALUES ('12203','Albany' ,'NY')";
maxdb_query($link, $query);

printf ("New Record has id %d.\n", maxdb_insert_id($link));

/* drop table */
maxdb_query($link, "DROP TABLE mycity");

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

New Record has id 1.


Disconnects from a MaxDB server

  • « maxdb_insert_id
  • maxdb_master_query »
  • PHP Manual
  • MaxDB Functions
  • Disconnects from a MaxDB server

maxdb_kill

maxdb::kill

(PECL maxdb >= 1.0)

maxdb_kill -- maxdb::kill — Disconnects from a MaxDB server

Description

Procedural style

maxdb_kill ( resource $link , int $processid ) : bool

Object oriented style

maxdb::kill ( int $processid ) : bool

This function is used to disconnect from a MaxDB server specified by the processid parameter.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* determine our thread id */
$thread_id = $maxdb->thread_id;

/* Kill connection */
$maxdb->kill($thread_id);

/* This should produce an error */
if (!$maxdb->query("CREATE TABLE myCity LIKE City")) {
   printf("Error: %s\n", $maxdb->error);
   exit;
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* determine our thread id */
$thread_id = maxdb_thread_id($link);

/* Kill connection */
maxdb_kill($link, $thread_id);

/* This should produce an error */
if (!maxdb_query($link, "CREATE TABLE myCity LIKE City")) {
   printf("Error: %s\n", maxdb_error($link));
   exit;
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Error: Session not connected

See Also

  • maxdb_thread_id() - Returns the thread ID for the current connection


Enforce execution of a query on the master in a master/slave setup

  • « maxdb_kill
  • maxdb_more_results »
  • PHP Manual
  • MaxDB Functions
  • Enforce execution of a query on the master in a master/slave setup

maxdb_master_query

(PECL maxdb >= 1.0)

maxdb_master_query — Enforce execution of a query on the master in a master/slave setup

Description

maxdb_master_query ( resource $link , string $query ) : bool
Warning

This function is currently not documented; only its argument list is available.


Check if there any more query results from a multi query

  • « maxdb_master_query
  • maxdb_multi_query »
  • PHP Manual
  • MaxDB Functions
  • Check if there any more query results from a multi query

maxdb_more_results

maxdb::more_results

(PECL maxdb >= 1.0)

maxdb_more_results -- maxdb::more_results — Check if there any more query results from a multi query

Description

maxdb_more_results ( resource $link ) : bool

maxdb_more_results() indicates if one or more result sets are available from a previous call to maxdb_multi_query().

Return Values

Always FALSE.

Examples

See maxdb_multi_query().

See Also

  • maxdb_multi_query() - Performs a query on the database
  • maxdb_next_result() - Prepare next result from multi_query
  • maxdb_store_result() - Transfers a result set from the last query
  • maxdb_use_result() - Initiate a result set retrieval


Performs a query on the database

  • « maxdb_more_results
  • maxdb_next_result »
  • PHP Manual
  • MaxDB Functions
  • Performs a query on the database

maxdb_multi_query

maxdb::multi_query

(PECL maxdb >= 1.0)

maxdb_multi_query -- maxdb::multi_query — Performs a query on the database

Description

Procedural style

maxdb_multi_query ( resource $link , string $query ) : bool

Object oriented style

maxdb::multi_query ( string $query ) : bool

The maxdb_multi_query() works like the function maxdb_query(). Multiple queries are not yet supported.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query  = "SELECT * FROM dual";

/* execute multi query */
if ($maxdb->multi_query($query)) {
   do {
       /* store first result set */
       if ($result = $maxdb->store_result()) {
           while ($row = $result->fetch_row()) {
               printf("%s\n", $row[0]);
           }
           $result->close();
       }
       /* print divider */
       if ($maxdb->more_results()) {
           printf("-----------------\n");
       }
   } while ($maxdb->next_result());
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT * FROM dual";

/* execute multi query */
if (maxdb_multi_query($link, $query)) {
   do {
       /* store first result set */
       if ($result = maxdb_store_result($link)) {
           while ($row = maxdb_fetch_row($result)) {
               printf("%s\n", $row[0]);
           }
           maxdb_free_result($result);
       }
       /* print divider */
       if (maxdb_more_results($link)) {
           printf("-----------------\n");
       }
   } while (maxdb_next_result($link));
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

a

See Also

  • maxdb_use_result() - Initiate a result set retrieval
  • maxdb_store_result() - Transfers a result set from the last query
  • maxdb_next_result() - Prepare next result from multi_query
  • maxdb_more_results() - Check if there any more query results from a multi query


Prepare next result from multi_query

  • « maxdb_multi_query
  • maxdb_num_fields »
  • PHP Manual
  • MaxDB Functions
  • Prepare next result from multi_query

maxdb_next_result

maxdb::next_result

(PECL maxdb >= 1.0)

maxdb_next_result -- maxdb::next_result — Prepare next result from multi_query

Description

maxdb_next_result ( resource $link ) : bool

Since multiple queries are not yet supported, maxdb_next_result() returns always FALSE.

Return Values

Returns FALSE.

See Also

  • maxdb_multi_query() - Performs a query on the database
  • maxdb_more_results() - Check if there any more query results from a multi query
  • maxdb_store_result() - Transfers a result set from the last query
  • maxdb_use_result() - Initiate a result set retrieval


Get the number of fields in a result

  • « maxdb_next_result
  • maxdb_num_rows »
  • PHP Manual
  • MaxDB Functions
  • Get the number of fields in a result

maxdb_num_fields

maxdb_result::field_count

(PECL maxdb >= 1.0)

maxdb_num_fields -- maxdb_result::field_count — Get the number of fields in a result

Description

Procedural style

maxdb_num_fields ( resource $result ) : int

Object oriented style

int $maxdb_result->field_count;

maxdb_num_fields() returns the number of fields from specified result set.

Return Values

The number of fields from a result set

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($result = $maxdb->query("SELECT * FROM hotel.city ORDER BY zip")) {

   /* determine number of fields in result set */
   $field_cnt = $result->field_count;

   printf("Result set has %d fields.\n", $field_cnt);

   /* close result set */
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($result = maxdb_query($link, "SELECT * FROM hotel.city ORDER BY zip")) {

   /* determine number of fields in result set */
   $field_cnt = maxdb_num_fields($result);

   printf("Result set has %d fields.\n", $field_cnt);

   /* close result set */
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Result set has 3 fields.

See Also

  • maxdb_fetch_field() - Returns the next field in the result set


Gets the number of rows in a result

  • « maxdb_num_fields
  • maxdb_options »
  • PHP Manual
  • MaxDB Functions
  • Gets the number of rows in a result

maxdb_num_rows

maxdb::num_rows

(PECL maxdb >= 1.0)

maxdb_num_rows -- maxdb::num_rows — Gets the number of rows in a result

Description

Procedural style

maxdb_num_rows ( resource $result ) : int

Object oriented style

int $maxdb->num_rows;

Returns the number of rows in the result set.

The use of maxdb_num_rows() depends on whether you use buffered or unbuffered result sets. In case you use unbuffered resultsets maxdb_num_rows() will not correct the correct number of rows until all the rows in the result have been retrieved.

Return Values

Returns number of rows in the result set.

Note:

If the number of rows is greater than maximal int value, the number will be returned as a string.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($result = $maxdb->query("SELECT cno, name FROM hotel.customer ORDER BY name")) {

   /* determine number of rows result set */
   $row_cnt = $result->num_rows;

   printf("Result set has %d rows.\n", $row_cnt);

   /* close result set */
   $result->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($result = maxdb_query($link, "SELECT cno, name FROM hotel.customer ORDER BY name")) {

   /* determine number of rows result set */
   $row_cnt = maxdb_num_rows($result);

   printf("Result set has %d rows.\n", $row_cnt);

   /* close result set */
   maxdb_free_result($result);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Result set has 15 rows.

See Also

  • maxdb_affected_rows() - Gets the number of affected rows in a previous MaxDB operation
  • maxdb_store_result() - Transfers a result set from the last query
  • maxdb_use_result() - Initiate a result set retrieval
  • maxdb_query() - Performs a query on the database


Set options

  • « maxdb_num_rows
  • maxdb_param_count »
  • PHP Manual
  • MaxDB Functions
  • Set options

maxdb_options

maxdb::options

(PECL maxdb >= 1.0)

maxdb_options -- maxdb::options — Set options

Description

Procedural style

maxdb_options ( resource $link , int $option , mixed $value ) : bool

Object oriented style

maxdb::options ( int $option , mixed $value ) : bool

maxdb_options() can be used to set extra connect options and affect behavior for a connection.

This function may be called multiple times to set several options.

maxdb_options() should be called after maxdb_init() and before maxdb_real_connect().

The parameter option is the option that you want to set, the value is the value for the option. For detailed description of the options see » http://maxdb.sap.com/documentation/ The parameter option can be one of the following values:

Valid options
Name | Description
MAXDB_COMPNAME | The component name used to initialise the SQLDBC runtime environment.
MAXDB_APPLICATION | The application to be connected to the database.
MAXDB_APPVERSION | The version of the application.
MAXDB_SQLMODE | The SQL mode.
MAXDB_UNICODE | TRUE, if the connection is an unicode (UCS2) client or FALSE, if not.
MAXDB_TIMEOUT | The maximum allowed time of inactivity after which the connection to the database is closed by the system.
MAXDB_ISOLATIONLEVEL | Specifies whether and how shared locks and exclusive locks are implicitly requested or released.
MAXDB_PACKETCOUNT | The number of different request packets used for the connection.
MAXDB_STATEMENTCACHESIZE | The number of prepared statements to be cached for the connection for re-use.
MAXDB_CURSORPREFIX | The prefix to use for result tables that are automatically named.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

See maxdb_real_connect().

See Also

  • maxdb_init() - Initializes MaxDB and returns an resource for use with maxdb_real_connect
  • maxdb_real_connect() - Opens a connection to a MaxDB server


Alias of maxdb_stmt_param_count

  • « maxdb_options
  • maxdb_ping »
  • PHP Manual
  • MaxDB Functions
  • Alias of maxdb_stmt_param_count

maxdb_param_count

(PECL maxdb 1.0)

maxdb_param_count — Alias of maxdb_stmt_param_count()

Description

This function is an alias of: maxdb_stmt_param_count().

This function alias is deprecated and only exists for backwards compatibility reasons. The use of this function is not recommended, as it may be removed from PHP in the future.


Pings a server connection, or tries to reconnect if the connection has gone down

  • « maxdb_param_count
  • maxdb_prepare »
  • PHP Manual
  • MaxDB Functions
  • Pings a server connection, or tries to reconnect if the connection has gone down

maxdb_ping

maxdb::ping

(PECL maxdb >= 1.0)

maxdb_ping -- maxdb::ping — Pings a server connection, or tries to reconnect if the connection has gone down

Description

Procedural style

maxdb_ping ( resource $link ) : bool

Object oriented style

maxdb::ping ( void ) : bool

Checks whether the connection to the server is working. If it has gone down, and global option maxdb.reconnect is enabled an automatic reconnection is 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.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* check if server is alive */
if ($maxdb->ping()) {
   printf ("Our connection is ok!\n");
} else {
   printf ("Error: %s\n", $maxdb->error);
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* check if server is alive */
if (maxdb_ping($link)) {
   printf ("Our connection is ok!\n");
} else {
   printf ("Error: %s\n", maxdb_error($link));
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Our connection is ok!


Prepare an SQL statement for execution

  • « maxdb_ping
  • maxdb_query »
  • PHP Manual
  • MaxDB Functions
  • Prepare an SQL statement for execution

maxdb_prepare

maxdb::prepare

(PECL maxdb >= 1.0)

maxdb_prepare -- maxdb::prepare — Prepare an SQL statement for execution

Description

Procedural style

maxdb_prepare ( resource $link , string $query ) : resource

Object oriented style

maxdb::prepare ( string $query ) : maxdb_stmt

maxdb_prepare() prepares the SQL query pointed to by the null-terminated string query, and returns a statement handle to be used for further operations on the statement. The query must consist of a single SQL statement.

Note:

You should not add a terminating semicolon or \g to the statement.

The parameter query can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions.

Note:

The markers are legal only in certain places in SQL statements. For example, they are allowed 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 allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement), or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. In general, parameters are legal only in Data Manipulation Languange (DML) statements, and not in Data Defination Language (DDL) statements.

The parameter markers must be bound to application variables using maxdb_stmt_bind_param() and/or maxdb_stmt_bind_result() before executing the statement or fetching rows.

Return Values

maxdb_prepare() returns a statement resource or FALSE if an error occurred.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$city = "Rosemont";

/* create a prepared statement */
if ($stmt = $maxdb->prepare("SELECT state FROM hotel.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);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$city = "Rosemont";

/* create a prepared statement */
if ($stmt = maxdb_prepare($link, "SELECT state FROM hotel.city WHERE name=?")) {

   /* bind parameters for markers */
   maxdb_stmt_bind_param($stmt, "s", $city);

   /* execute query */
   maxdb_stmt_execute($stmt);

  /* bind result variables */
   maxdb_stmt_bind_result($stmt, $district);

   /* fetch value */
   maxdb_stmt_fetch($stmt);

   printf("%s is in district %s\n", $city, $district);

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Rosemont is in district IL

See Also

  • maxdb_stmt_execute() - Executes a prepared Query
  • maxdb_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • maxdb_stmt_bind_param() - Binds variables to a prepared statement as parameters
  • maxdb_stmt_bind_result() - Binds variables to a prepared statement for result storage
  • maxdb_stmt_close() - Closes a prepared statement


Performs a query on the database

  • « maxdb_prepare
  • maxdb_real_connect »
  • PHP Manual
  • MaxDB Functions
  • Performs a query on the database

maxdb_query

maxdb::query

(PECL maxdb >= 1.0)

maxdb_query -- maxdb::query — Performs a query on the database

Description

Procedural style

maxdb_query ( resource $link , string $query [, int $resultmode ] ) : mixed

Object oriented style

maxdb::query ( string $query ) : mixed

The maxdb_query() function is used to simplify the act of performing a query against the database represented by the link parameter.

Return Values

Returns TRUE on success or FALSE on failure. For SELECT, SHOW, DESCRIBE or EXPLAIN maxdb_query() will return a result resource.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Create table doesn't return a resultset */
if ($maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city") === TRUE) {
   printf("Table mycity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = $maxdb->query("SELECT name FROM hotel.city")) {
   printf("Select returned %d rows.\n", $result->num_rows);

   /* free result set */
   $result->close();
}

/* If we have to retrieve large amount of data we use MAXDB_USE_RESULT */
if ($result = $maxdb->query("SELECT * FROM hotel.city", MAXDB_USE_RESULT)) {
   $result->close();
}

$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Create table doesn't return a resultset */
if (maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city") === TRUE) {
   printf("Table mycity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = maxdb_query($link, "SELECT name FROM hotel.city")) {
   printf("Select returned %d rows.\n", maxdb_num_rows($result));

   /* free result set */
   maxdb_free_result($result);
}

/* If we have to retrieve large amount of data we use MAXDB_USE_RESULT */
if ($result = maxdb_query($link, "SELECT * FROM hotel.city", MAXDB_USE_RESULT)) {
   maxdb_free_result($result);
}

maxdb_close($link);
?>

The above example will output something similar to:

Table mycity successfully created.
Select returned 25 rows.

See Also

  • maxdb_real_query() - Execute an SQL query
  • maxdb_multi_query() - Performs a query on the database
  • maxdb_free_result() - Frees the memory associated with a result


Opens a connection to a MaxDB server

  • « maxdb_query
  • maxdb_real_escape_string »
  • PHP Manual
  • MaxDB Functions
  • Opens a connection to a MaxDB server

maxdb_real_connect

maxdb::real_connect

(PECL maxdb >= 1.0)

maxdb_real_connect -- maxdb::real_connect — Opens a connection to a MaxDB server

Description

Procedural style

maxdb_real_connect ( resource $link [, string $hostname [, string $username [, string $passwd [, string $dbname [, int $port = 0 [, string $socket ]]]]]] ) : bool

Object oriented style

maxdb::real_connect ([ string $hostname [, string $username [, string $passwd [, string $dbname [, int $port = 0 [, string $socket ]]]]]] ) : bool

maxdb_real_connect() attempts to establish a connection to a MaxDB database engine running on hostname.

This function differs from maxdb_connect():

  • maxdb_real_connect() needs a valid resource which has to be created by function maxdb_init()

  • With function maxdb_options() you can set various options for connection.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php

/* create a connection object which is not connected */
$maxdb = maxdb_init();

/* set connection options */
$maxdb->options(MAXDB_UNICODE, "FALSE");
$maxdb->options(MAXDB_TIMEOUT, 5);

/* connect to server */
$maxdb->real_connect('localhost', 'MONA', 'RED', 'DEMODB');

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

printf ("Connection: %s\n.", $maxdb->host_info);

$maxdb->close();
?>

Example #2 Procedural style

<?php

/* create a connection object which is not connected */
$link = maxdb_init();

/* set connection options */
maxdb_options($link, MAXDB_UNICODE, "FALSE");
maxdb_options($link, MAXDB_TIMEOUT, 5);

/* connect to server */
maxdb_real_connect($link, 'localhost', 'MONA', 'RED', 'DEMODB');

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

printf ("Connection: %s\n.", maxdb_get_host_info($link));

maxdb_close($link);
?>

The above example will output something similar to:

Connection: localhost <...>

See Also

  • maxdb_connect() - Open a new connection to the MaxDB server
  • maxdb_init() - Initializes MaxDB and returns an resource for use with maxdb_real_connect
  • maxdb_options() - Set options
  • maxdb_ssl_set() - Used for establishing secure connections using SSL
  • maxdb_close() - Closes a previously opened database connection


Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

  • « maxdb_real_connect
  • maxdb_real_query »
  • PHP Manual
  • MaxDB Functions
  • Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

maxdb_real_escape_string

maxdb::real_escape_string

(PECL maxdb >= 1.0)

maxdb_real_escape_string -- maxdb::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

Procedural style

maxdb_real_escape_string ( resource $link , string $escapestr ) : string

Object oriented style

maxdb::real_escape_string ( string $escapestr ) : string

This function is used to create a legal SQL string that you can use in an SQL statement. The string escapestr is encoded to an escaped SQL string, taking into account the current character set of the connection.

Characters encoded are ', ".

Return Values

Returns an escaped string.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");

$city = "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!$maxdb->query("INSERT into temp.mycity VALUES ('11111','$city','NY')")) {
   printf("Error: %s\n", $maxdb->sqlstate);
}

$city = $maxdb->real_escape_string($city);

/* this query with escaped $city will work */
if ($maxdb->query("INSERT into temp.mycity VALUES ('22222','$city','NY')")) {
   printf("%d Row inserted.\n", $maxdb->affected_rows);
}

$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");

$city = "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!maxdb_query($link, "INSERT into temp.mycity VALUES ('11111','$city','NY')")) {
   printf("Error: %s\n", maxdb_sqlstate($link));
}

$city = maxdb_real_escape_string($link, $city);

/* this query with escaped $city will work */
if (maxdb_query($link, "INSERT into temp.mycity VALUES ('22222','$city','NY')")) {
   printf("%d Row inserted.\n", maxdb_affected_rows($link));
}

maxdb_close($link);
?>

The above example will output something similar to:

Warning: maxdb_query(): -5016 POS(43) Missing delimiter: ) <...>
Error: 42000
1 Row inserted.

See Also

  • maxdb_character_set_name() - Returns the default character set for the database connection


Execute an SQL query

  • « maxdb_real_escape_string
  • maxdb_report »
  • PHP Manual
  • MaxDB Functions
  • Execute an SQL query

maxdb_real_query

maxdb::real_query

(PECL maxdb >= 1.0)

maxdb_real_query -- maxdb::real_query — Execute an SQL query

Description

Procedural style

maxdb_real_query ( resource $link , string $query ) : bool

Object oriented style

maxdb::real_query ( string $query ) : bool

The maxdb_real_query() is functionally identical with the maxdb_query().

Note:

In order to determine if a given query should return a result set or not, see maxdb_field_count().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • maxdb_query() - Performs a query on the database
  • maxdb_store_result() - Transfers a result set from the last query
  • maxdb_use_result() - Initiate a result set retrieval


Enables or disables internal report functions

  • « maxdb_real_query
  • maxdb_rollback »
  • PHP Manual
  • MaxDB Functions
  • Enables or disables internal report functions

maxdb_report

(PECL maxdb 1.0)

maxdb_report — Enables or disables internal report functions

Description

maxdb_report ( int $flags ) : bool

Parameters

flags

One of the MAXDB_REPORT_XXX constants.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Procedural style

<?php
/* activate reporting */
maxdb_report(MAXDB_REPORT_ERROR);

$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* this query should report an error */
$result = maxdb_query($link,"SELECT Name FROM Nonexistingtable WHERE population > 50000");

maxdb_close($link);
?>

The above example will output something similar to:

Warning: maxdb_query(): -4004 POS(18) Unknown table name:NONEXISTINGTABLE <...>


Rolls back current transaction

  • « maxdb_report
  • maxdb_rpl_parse_enabled »
  • PHP Manual
  • MaxDB Functions
  • Rolls back current transaction

maxdb_rollback

maxdb::rollback

(PECL maxdb >= 1.0)

maxdb_rollback -- maxdb::rollback — Rolls back current transaction

Description

Procedural style

maxdb_rollback ( resource $link ) : bool

Object oriented style

maxdb::rollback ( void ) : bool

Rollbacks the current transaction for the database specified by the link parameter.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* disable autocommit */
$maxdb->autocommit(FALSE);

$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query("INSERT INTO temp.mycity SELECT * FROM hotel.city");

/* commit insert */
$maxdb->commit();

/* delete all rows */
$maxdb->query("DELETE FROM temp.mycity");

if ($result = $maxdb->query("SELECT COUNT(*) FROM temp.mycity")) {
   $row = $result->fetch_row();
   printf("%d rows in table mycity.\n", $row[0]);
   /* Free result */
   $result->close();
}

/* Rollback */
$maxdb->rollback();

if ($result = $maxdb->query("SELECT COUNT(*) FROM temp.mycity")) {
   $row = $result->fetch_row();
   printf("%d rows in table mycity (after rollback).\n", $row[0]);
   /* Free result */
   $result->close();
}

/* Drop table myCity */
$maxdb->query("DROP TABLE temp.mycity");

$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* disable autocommit */
maxdb_autocommit($link, FALSE);

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");
maxdb_query($link, "INSERT INTO temp.mycity SELECT * FROM hotel.city");

/* commit insert */
maxdb_commit($link);

/* delete all rows */
maxdb_query($link, "DELETE FROM temp.mycity");

if ($result = maxdb_query($link, "SELECT COUNT(*) FROM temp.mycity")) {
   $row = maxdb_fetch_row($result);
   printf("%d rows in table mycity.\n", $row[0]);
   /* Free result */
   maxdb_free_result($result);
}

/* Rollback */
maxdb_rollback($link);

if ($result = maxdb_query($link, "SELECT COUNT(*) FROM temp.mycity")) {
   $row = maxdb_fetch_row($result);
   printf("%d rows in table mycity (after rollback).\n", $row[0]);
   /* Free result */
   maxdb_free_result($result);
}

/* Drop table myCity */
maxdb_query($link, "DROP TABLE temp.mycity");

maxdb_close($link);
?>

The above example will output something similar to:

0 rows in table mycity.
25 rows in table mycity (after rollback).

See Also

  • maxdb_commit() - Commits the current transaction
  • maxdb_autocommit() - Turns on or off auto-commiting database modifications


Check if RPL parse is enabled

  • « maxdb_rollback
  • maxdb_rpl_probe »
  • PHP Manual
  • MaxDB Functions
  • Check if RPL parse is enabled

maxdb_rpl_parse_enabled

(PECL maxdb >= 1.0)

maxdb_rpl_parse_enabled — Check if RPL parse is enabled

Description

maxdb_rpl_parse_enabled ( resource $link ) : int
Warning

This function is currently not documented; only its argument list is available.


RPL probe

  • « maxdb_rpl_parse_enabled
  • maxdb_rpl_query_type »
  • PHP Manual
  • MaxDB Functions
  • RPL probe

maxdb_rpl_probe

(PECL maxdb >= 1.0)

maxdb_rpl_probe — RPL probe

Description

maxdb_rpl_probe ( resource $link ) : bool
Warning

This function is currently not documented; only its argument list is available.


Returns RPL query type

  • « maxdb_rpl_probe
  • maxdb_select_db »
  • PHP Manual
  • MaxDB Functions
  • Returns RPL query type

maxdb_rpl_query_type

maxdb::rpl_query_type

(PECL maxdb >= 1.0)

maxdb_rpl_query_type -- maxdb::rpl_query_type — Returns RPL query type

Description

Procedural style

maxdb_rpl_query_type ( resource $link ) : int

Object oriented style

maxdb::rpl_query_type ( void ) : int
Warning

This function is currently not documented; only its argument list is available.


Selects the default database for database queries

  • « maxdb_rpl_query_type
  • maxdb_send_long_data »
  • PHP Manual
  • MaxDB Functions
  • Selects the default database for database queries

maxdb_select_db

maxdb::select_db

(PECL maxdb >= 1.0)

maxdb_select_db -- maxdb::select_db — Selects the default database for database queries

Description

maxdb_select_db ( resource $link , string $dbname ) : bool

The maxdb_select_db() function selects the default database (specified by the dbname parameter) to be used when performing queries against the database connection represented by the link parameter.

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

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* return name of current default database */
if ($result = $maxdb->query("SELECT SERVERDB FROM USERS WHERE USERNAME='MONA'")) {
   $row = $result->fetch_row();
   printf("Default database is %s.\n", $row[0]);
   $result->close();
}

/* change db to non existing db */
$maxdb->select_db("XXXXXXXX");

/* return name of current default database */
if ($result = $maxdb->query("SELECT SERVERDB FROM USERS WHERE USERNAME='MONA'")) {
   $row = $result->fetch_row();
   printf("Default database is %s.\n", $row[0]);
   $result->close();
}

$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* return name of current default database */
if ($result = maxdb_query($link, "SELECT SERVERDB FROM USERS WHERE USERNAME='MONA'")) {
   $row = maxdb_fetch_row($result);
   printf("Default database is %s.\n", $row[0]);
   maxdb_free_result($result);
}

/* change db to non existing db */
maxdb_select_db($link, "XXXXXXXX");

/* return name of current default database */
if ($result = maxdb_query($link, "SELECT SERVERDB FROM USERS WHERE USERNAME='MONA'")) {
   $row = maxdb_fetch_row($result);
   printf("Default database is %s.\n", $row[0]);
   maxdb_free_result($result);
}

maxdb_close($link);
?>

The above example will output something similar to:

Default database is <...>.

Warning: maxdb_select_db(): -10709 Connection failed (RTE:database not running) <...>

Warning: maxdb_query(): -10821 Session not connected [] <...>

Warning: maxdb_close(): -10821 Session not connected [] <...>

See Also

  • maxdb_connect() - Open a new connection to the MaxDB server
  • maxdb_real_connect() - Opens a connection to a MaxDB server


Alias of maxdb_stmt_send_long_data

  • « maxdb_select_db
  • maxdb_send_query »
  • PHP Manual
  • MaxDB Functions
  • Alias of maxdb_stmt_send_long_data

maxdb_send_long_data

(PECL maxdb >= 1.0)

maxdb_send_long_data — Alias of maxdb_stmt_send_long_data()

Description

This function is an alias of: maxdb_stmt_send_long_data().

This function alias is deprecated and only exists for backwards compatibility reasons. The use of this function is not recommended, as it may be removed from PHP in the future.


Send the query and return

  • « maxdb_send_long_data
  • maxdb_server_end »
  • PHP Manual
  • MaxDB Functions
  • Send the query and return

maxdb_send_query

maxdb::send_query

(PECL maxdb >= 1.0)

maxdb_send_query -- maxdb::send_query — Send the query and return

Description

Procedural style

maxdb_send_query ( resource $link , string $query ) : bool

Object oriented style

maxdb::send_query ( string $query ) : bool
Warning

This function is currently not documented; only its argument list is available.


Shut down the embedded server

  • « maxdb_send_query
  • maxdb_server_init »
  • PHP Manual
  • MaxDB Functions
  • Shut down the embedded server

maxdb_server_end

(PECL maxdb >= 1.0)

maxdb_server_end — Shut down the embedded server

Description

maxdb_server_end ( void ) : void
Warning

This function is currently not documented; only its argument list is available.


Initialize embedded server

  • « maxdb_server_end
  • maxdb_set_opt »
  • PHP Manual
  • MaxDB Functions
  • Initialize embedded server

maxdb_server_init

(PECL maxdb >= 1.0)

maxdb_server_init — Initialize embedded server

Description

maxdb_server_init ([ array $server [, array $groups ]] ) : bool
Warning

This function is currently not documented; only its argument list is available.


Alias of maxdb_options

  • « maxdb_server_init
  • maxdb_sqlstate »
  • PHP Manual
  • MaxDB Functions
  • Alias of maxdb_options

maxdb_set_opt

(PECL maxdb 1.0)

maxdb_set_opt — Alias of maxdb_options()

Description

This function is an alias of: maxdb_options().


Returns the SQLSTATE error from previous MaxDB operation

  • « maxdb_set_opt
  • maxdb_ssl_set »
  • PHP Manual
  • MaxDB Functions
  • Returns the SQLSTATE error from previous MaxDB operation

maxdb_sqlstate

maxdb::sqlstate

(PECL maxdb >= 1.0)

maxdb_sqlstate -- maxdb::sqlstate — Returns the SQLSTATE error from previous MaxDB operation

Description

Procedural style

maxdb_sqlstate ( resource $link ) : string

Object oriented style

string $maxdb->sqlstate;

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.

Note:

Note that not all MaxDB errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.

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
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Table City already exists, so we should get an error */
if (!$maxdb->query("CREATE TABLE hotel.city (ID INT, Name VARCHAR(30))")) {
   printf("Error - SQLSTATE %s.\n", $maxdb->sqlstate);
}

$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Table City already exists, so we should get an error */
if (!maxdb_query($link, "CREATE TABLE hotel.city (ID INT, Name VARCHAR(30))")) {
   printf("Error - SQLSTATE %s.\n", maxdb_sqlstate($link));
}

maxdb_close($link);
?>

The above example will output something similar to:

Warning: maxdb_query(): -6000 POS(20) Duplicate table name:CITY [I6000] <...>
Error - SQLSTATE I6000.

See Also

  • maxdb_errno() - Returns the error code for the most recent function call
  • maxdb_error() - Returns a string description of the last error


Used for establishing secure connections using SSL

  • « maxdb_sqlstate
  • maxdb_stat »
  • PHP Manual
  • MaxDB Functions
  • Used for establishing secure connections using SSL

maxdb_ssl_set

maxdb::ssl_set

(PECL maxdb >= 1.0)

maxdb_ssl_set -- maxdb::ssl_set — Used for establishing secure connections using SSL

Description

Procedural style

maxdb_ssl_set ( resource $link , string $key , string $cert , string $ca , string $capath , string $cipher ) : bool

Object oriented style

maxdb::ssl_set ( string $key , string $cert , string $ca , string $capath , string $cipher ) : bool
Warning

This function is currently not documented; only its argument list is available.


Gets the current system status

  • « maxdb_ssl_set
  • maxdb_stmt_affected_rows »
  • PHP Manual
  • MaxDB Functions
  • Gets the current system status

maxdb_stat

maxdb::stat

(PECL maxdb >= 1.0)

maxdb_stat -- maxdb::stat — Gets the current system status

Description

Procedural style

maxdb_stat ( resource $link ) : string

Object oriented style

maxdb::stat ( void ) : string

maxdb_stat() returns a string containing several information about the MaxDB server running.

Return Values

A string describing the server status. FALSE if an error occurred.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

printf ("System status: %s\n", $maxdb->stat());

$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

printf("System status: %s\n", maxdb_stat($link));

maxdb_close($link);
?>

The above example will output something similar to:

System status: Kernel    7<...>

See Also

  • maxdb_get_server_info() - Returns the version of the MaxDB server


Returns the total number of rows changed, deleted, or inserted by the last executed statement

  • « maxdb_stat
  • maxdb_stmt_bind_param »
  • PHP Manual
  • MaxDB Functions
  • Returns the total number of rows changed, deleted, or inserted by the last executed statement

maxdb_stmt_affected_rows

maxdb_stmt::affected_rows

(PECL maxdb >= 1.0)

maxdb_stmt_affected_rows -- maxdb_stmt::affected_rows — Returns the total number of rows changed, deleted, or inserted by the last executed statement

Description

Procedural style

maxdb_stmt_affected_rows ( resource $stmt ) : int

Object oriented style

int $maxdb_stmt->affected_rows;

maxdb_stmt_affected_rows() returns the number of rows affected by INSERT, UPDATE, or DELETE query. If the last query was invalid or the number of rows can not determined, this function will return -1.

Return Values

An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where updated for an UPDATE/DELETE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query has returned an error or the number of rows can not determined.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* create temp table */
$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");

$query = "INSERT INTO temp.mycity SELECT * FROM hotel.city WHERE state LIKE ?";

/* prepare statement */
if ($stmt = $maxdb->prepare($query)) {

   /* Bind variable for placeholder */
   $code = 'N%';
   $stmt->bind_param("s", $code);

   /* execute statement */
   $stmt->execute();

   printf("rows inserted: %d\n", $stmt->affected_rows);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* create temp table */
maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");

$query = "INSERT INTO temp.mycity SELECT * FROM hotel.city WHERE state LIKE ?";

/* prepare statement */
if ($stmt = maxdb_prepare($link, $query)) {

   /* Bind variable for placeholder */
   $code = 'N%';
   maxdb_stmt_bind_param($stmt, "s", $code);

   /* execute statement */
   maxdb_stmt_execute($stmt);

   printf("rows inserted: %d\n", maxdb_stmt_affected_rows($stmt));

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

rows inserted: 4

See Also

  • maxdb_stmt_num_rows() - Return the number of rows in statements result set
  • maxdb_prepare() - Prepare an SQL statement for execution


Binds variables to a prepared statement as parameters

  • « maxdb_stmt_affected_rows
  • maxdb_stmt_bind_result »
  • PHP Manual
  • MaxDB Functions
  • Binds variables to a prepared statement as parameters

maxdb_stmt_bind_param

maxdb_stmt::bind_param

(PECL maxdb >= 1.0)

maxdb_stmt_bind_param -- maxdb_stmt::bind_param — Binds variables to a prepared statement as parameters

Description

Procedural style

maxdb_stmt_bind_param ( resource $stmt , string $types , mixed &$var1 [, mixed &$... ] ) : bool

Object oriented style

maxdb_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$... ] ) : bool

Procedural style (extended syntax):

maxdb_stmt_bind_param ( resource $stmt , string $types , array &$var ) : bool

Object oriented style (extended syntax):

maxdb_stmt::bind_param ( string $types , array &$var ) : bool

maxdb_stmt_bind_param() is used to bind variables for the parameter markers in the SQL statement that was passed to maxdb_prepare(). The string types contains one or more characters which specify the types for the corresponding bind variables.

The extended syntax of maxdb_stmt_bind_param() allows to give the parameters as an array instead of a variable list of PHP variables to the function. If the array variable has not been used before calling maxdb_stmt_bind_param(), it has to be initialized as an emtpy array. See the examples how to use maxdb_stmt_bind_param() with extended syntax.

Variables for SELECT INTO SQL statements can also be bound using maxdb_stmt_bind_param(). Parameters for database procedures can be bound using maxdb_stmt_bind_param(). See the examples how to use maxdb_stmt_bind_param() in this cases.

If a variable bound as INTO variable to an SQL statement was used before, the content of this variable is overwritten by the data of the SELECT INTO statement. A reference to this variable will be invalid after a call to maxdb_stmt_bind_param().

For INOUT parameters of database procedures the content of the bound INOUT variable is overwritten by the output value of the database procedure. A reference to this variable will be invalid after a call to maxdb_stmt_bind_param().

Type specification chars
Character | Description
i | corresponding variable has type integer
d | corresponding variable has type double
s | corresponding variable has type string
b | corresponding variable is a blob and will be sent in packages

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb('localhost', 'MONA', 'RED', 'DEMODB');

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query ("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query ("INSERT INTO temp.mycity SELECT * FROM hotel.city");

$stmt = $maxdb->prepare("INSERT INTO temp.mycity VALUES (?, ?, ?)");
$stmt->bind_param('sss', $zip, $name, $state);

$zip = '11111';
$name = 'Georgetown';
$state = 'NY';

/* execute prepared statement */
$stmt->execute();

printf("%d Row inserted.\n", $stmt->affected_rows);

/* close statement and connection */
$stmt->close();

/* Clean up table CountryLanguage */
$maxdb->query("DELETE FROM temp.mycity WHERE name='Georgetown'");
printf("%d Row deleted.\n", $maxdb->affected_rows);

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query ($link, "CREATE TABLE temp.mycity LIKE hotel.city");
maxdb_query ($link, "INSERT INTO temp.mycity SELECT * FROM hotel.city");

$stmt = maxdb_prepare($link, "INSERT INTO temp.mycity VALUES (?, ?, ?)");
maxdb_stmt_bind_param($stmt, 'sss', $zip, $name, $state);

$zip = '11111';
$name = 'Georgetown';
$state = 'NY';

/* execute prepared statement */
maxdb_stmt_execute($stmt);

printf("%d Row inserted.\n", maxdb_stmt_affected_rows($stmt));

/* close statement and connection */
maxdb_stmt_close($stmt);

/* Clean up table CountryLanguage */
maxdb_query($link, "DELETE FROM temp.mycity WHERE name='Georgetown'");
printf("%d Row deleted.\n", maxdb_affected_rows($link));

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

1 Row inserted.
1 Row deleted.

Example #3 Procedural style (SELECT INTO)

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* Performing SQL query */
$stmt = maxdb_prepare ($link, "SELECT price INTO ? FROM hotel.room where hno = ? and type = ?");
if (!$stmt) {
  printf ("Prepare failed: %s\n", maxdb_error($link));
}

$hno = "50";
$rtype = "suite";

maxdb_stmt_bind_param($stmt, 'dss', $price, $hno, $rtype);
maxdb_stmt_execute($stmt);

printf ("%f\n", $price);

maxdb_stmt_close ($stmt);
?>

The above example will output something similar to:

21.600000

Example #4 Procedural style (DB procedure)

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_report (MAXDB_REPORT_OFF);
maxdb_query($link,"DROP DBPROC test_proc");
maxdb_report (MAXDB_REPORT_ERROR);

$query = "create dbproc test_proc (INOUT e_text char(72)) AS select * from SYSDBA.DUAL; fetch into :e_text;";

maxdb_query($link, $query);

/* Performing SQL query */
$stmt = maxdb_prepare ($link, "CALL test_proc (?)");
if (!$stmt) {
  printf ("Prepare failed: %s\n", maxdb_error($link));
}

maxdb_stmt_bind_param($stmt, 's', $result);
maxdb_stmt_execute($stmt);

printf ("%s\n", $result);

maxdb_stmt_close ($stmt);
?>

The above example will output something similar to:

a

Example #5 Object oriented style (extended syntax)

<?php
$maxdb = new maxdb('localhost', 'MONA', 'RED', 'DEMODB');

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query ("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query ("INSERT INTO temp.mycity SELECT * FROM hotel.city");

$stmt = $maxdb->prepare("INSERT INTO temp.mycity VALUES (?, ?, ?)");

$arr = array();

$stmt->bind_param('iss', $arr);

$arr[0] = 11111;
$arr[1] = 'Georgetown';
$arr[2] = 'NY';

/* execute prepared statement */
$stmt->execute();

printf("%d Row inserted.\n", maxdb_stmt_affected_rows($stmt));

$arr[0] = 22222;
$arr[1] = 'New Orleans';
$arr[2] = 'LA';

/* execute prepared statement */
$stmt->execute();

printf("%d Row inserted.\n", $stmt->affected_rows);

/* close statement and connection */
$stmt->close();

$result = $maxdb->query("SELECT * from temp.mycity WHERE zip = '11111' OR zip = '22222'");
if ($result) {
  while ($row = $result->fetch_row()) {
    printf ("%s %s %s\n", $row[0], $row[1], $row[2]);
  }
}

/* Clean up table CountryLanguage */
$maxdb->query("DELETE FROM temp.mycity WHERE name='Georgetown'");
$maxdb->query("DELETE FROM temp.mycity WHERE name='New Orleans'");
printf("%d Rows deleted.\n", $maxdb->affected_rows);

/* close connection */
$maxdb->close();
?>

The above example will output something similar to:

1 Row inserted.
1 Row inserted.
11111 Georgetown NY
22222 New Orleans LA
2 Rows deleted.

See Also

  • maxdb_stmt_bind_result() - Binds variables to a prepared statement for result storage
  • maxdb_stmt_execute() - Executes a prepared Query
  • maxdb_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • maxdb_prepare() - Prepare an SQL statement for execution
  • maxdb_stmt_send_long_data() - Send data in blocks
  • maxdb_stmt_errno() - Returns the error code for the most recent statement call
  • maxdb_stmt_error() - Returns a string description for last statement error


Binds variables to a prepared statement for result storage

  • « maxdb_stmt_bind_param
  • maxdb_stmt_close_long_data »
  • PHP Manual
  • MaxDB Functions
  • Binds variables to a prepared statement for result storage

maxdb_stmt_bind_result

maxdb_stmt::bind_result

(PECL maxdb >= 1.0)

maxdb_stmt_bind_result -- maxdb_stmt::bind_result — Binds variables to a prepared statement for result storage

Description

Procedural style

maxdb_stmt_bind_result ( resource $stmt , mixed &$var1 [, mixed &$... ] ) : bool

Object oriented style

maxdb_stmt::bind_result ( mixed &$var1 [, mixed &$... ] ) : bool

maxdb_stmt_bind_result() is used to associate (bind) columns in the result set to variables. When maxdb_stmt_fetch() is called to fetch data, the MaxDB client/server protocol places the data for the bound columns into the specified variables var1, ....

Note:

Note that all columns must be bound prior to calling maxdb_stmt_fetch(). Depending on column types bound variables can silently change to the corresponding PHP type.

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 maxdb_stmt_fetch() is called.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* prepare statement */
if ($stmt = $maxdb->prepare("SELECT zip, name FROM hotel.city ORDER BY name")) {
   $stmt->execute();

   /* bind variables to prepared statement */
   $stmt->bind_result($col1, $col2);

   /* fetch values */
   while ($stmt->fetch()) {
       printf("%s %s\n", $col1, $col2);
   }

   /* close statement */
   $stmt->close();
}
/* close connection */
$maxdb->close();

?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (!$link) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* prepare statement */
if ($stmt = maxdb_prepare($link, "SELECT zip, name FROM hotel.city ORDER BY name")) {
   maxdb_stmt_execute($stmt);

   /* bind variables to prepared statement */
   maxdb_stmt_bind_result($stmt, $col1, $col2);

   /* fetch values */
   while (maxdb_stmt_fetch($stmt)) {
       printf("%s %s\n", $col1, $col2);
   }

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

12203 Albany
60601 Chicago
60615 Chicago
45211 Cincinnati
33575 Clearwater
75243 Dallas
32018 Daytona Beach
33441 Deerfield Beach
48226 Detroit
90029 Hollywood
92714 Irvine
90804 Long Beach
11788 Long Island
90018 Los Angeles
70112 New Orleans
10019 New York
10580 New York
92262 Palm Springs
97213 Portland
60018 Rosemont
95054 Santa Clara
20903 Silver Spring
20005 Washington
20019 Washington
20037 Washington

See Also

  • maxdb_stmt_bind_param() - Binds variables to a prepared statement as parameters
  • maxdb_stmt_execute() - Executes a prepared Query
  • maxdb_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • maxdb_prepare() - Prepare an SQL statement for execution
  • maxdb_stmt_prepare() - Prepare an SQL statement for execution
  • maxdb_stmt_init() - Initializes a statement and returns an resource for use with maxdb_stmt_prepare
  • maxdb_stmt_errno() - Returns the error code for the most recent statement call
  • maxdb_stmt_error() - Returns a string description for last statement error


Ends a sequence of maxdb_stmt_send_long_data

  • « maxdb_stmt_bind_result
  • maxdb_stmt_close »
  • PHP Manual
  • MaxDB Functions
  • Ends a sequence of maxdb_stmt_send_long_data

maxdb_stmt_close_long_data

maxdb_stmt::close_long_data

(PECL maxdb 1.0)

maxdb_stmt_close_long_data -- maxdb_stmt::close_long_data — Ends a sequence of maxdb_stmt_send_long_data()

Description

Procedural style

maxdb_stmt_close_long_data ( resource $stmt , int $param_nr ) : bool

Object oriented style

maxdb_stmt::close_long_data ( void ) : bool

This function has to be called after a sequence of maxdb_stmt_send_long_data(), that was started after maxdb_execute().

param_nr indicates which parameter to associate the end of data with. Parameters are numbered beginning with 0.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • maxdb_prepare() - Prepare an SQL statement for execution
  • maxdb_stmt_bind_param() - Binds variables to a prepared statement as parameters


Closes a prepared statement

  • « maxdb_stmt_close_long_data
  • maxdb_stmt_data_seek »
  • PHP Manual
  • MaxDB Functions
  • Closes a prepared statement

maxdb_stmt_close

maxdb_stmt::close

(PECL maxdb >= 1.0)

maxdb_stmt_close -- maxdb_stmt::close — Closes a prepared statement

Description

Procedural style

maxdb_stmt_close ( resource $stmt ) : bool

Object oriented style

maxdb_stmt::close ( void ) : bool

Closes a prepared statement. maxdb_stmt_close() also deallocates the statement handle pointed to by stmt. If the current statement has pending or unread results, this function cancels them so that the next query can be executed.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • maxdb_prepare() - Prepare an SQL statement for execution


Seeks to an arbitray row in statement result set

  • « maxdb_stmt_close
  • maxdb_stmt_errno »
  • PHP Manual
  • MaxDB Functions
  • Seeks to an arbitray row in statement result set

maxdb_stmt_data_seek

maxdb_stmt::data_seek

(PECL maxdb >= 1.0)

maxdb_stmt_data_seek -- maxdb_stmt::data_seek — Seeks to an arbitray row in statement result set

Description

Procedural style

maxdb_stmt_data_seek ( resource $statement , int $offset ) : bool

Object oriented style

maxdb_stmt::data_seek ( int $offset ) : bool

The maxdb_stmt_data_seek() function seeks to an arbitrary result pointer specified by the offset in the statement result set represented by statement. The offset parameter must be between zero and the total number of rows minus one (0..maxdb_stmt_num_rows() - 1).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, zip FROM hotel.city ORDER BY name";
if ($stmt = $maxdb->prepare($query)) {

   /* execute query */
   $stmt->execute();

   /* bind result variables */
   $stmt->bind_result($name, $code);

   /* store result */
   $stmt->store_result();

   /* seek to row no. 5 */
   $stmt->data_seek(5);

   /* fetch values */
   $stmt->fetch();

   printf ("City: %s  Zip: %s\n", $name, $code);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
/* Open a connection */
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, zip FROM hotel.city ORDER BY name";
if ($stmt = maxdb_prepare($link, $query)) {

   /* execute query */
   maxdb_stmt_execute($stmt);

   /* bind result variables */
   maxdb_stmt_bind_result($stmt, $name, $code);

   /* store result */
   maxdb_stmt_store_result($stmt);

   /* seek to row no. 5 */
   maxdb_stmt_data_seek($stmt, 5);

   /* fetch values */
   maxdb_stmt_fetch($stmt);

   printf ("City: %s  Zip: %s\n", $name, $code);

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

City: Dallas  Zip: 75243

See Also

  • maxdb_prepare() - Prepare an SQL statement for execution


Returns the error code for the most recent statement call

  • « maxdb_stmt_data_seek
  • maxdb_stmt_error »
  • PHP Manual
  • MaxDB Functions
  • Returns the error code for the most recent statement call

maxdb_stmt_errno

maxdb_stmt::errno

(PECL maxdb >= 1.0)

maxdb_stmt_errno -- maxdb_stmt::errno — Returns the error code for the most recent statement call

Description

Procedural style

maxdb_stmt_errno ( resource $stmt ) : int

Object oriented style

int $maxdb_stmt->errno;

For the statement specified by stmt, maxdb_stmt_errno() returns the error code for the most recently invoked statement function that can succeed or fail.

Note:

For possible error codes see documentation of SQLDBC: » http://maxdb.sap.com/documentation/.

Return Values

An error code value. Zero means no error occurred.

Examples

Example #1 Object oriented style

<?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query("INSERT INTO temp.mycity SELECT * FROM hotel.city");

$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = $maxdb->prepare($query)) {

   /* drop table */
   $maxdb->query("DROP TABLE temp.mycity");

   /* execute query */
   $stmt->execute();

   printf("Error: %d.\n", $stmt->errno);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
/* Open a connection */
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");
maxdb_query($link, "INSERT INTO temp.mycity SELECT * FROM hotel.city");

$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = maxdb_prepare($link, $query)) {

   /* drop table */
   maxdb_query($link, "DROP TABLE temp.mycity");

   /* execute query */
   maxdb_stmt_execute($stmt);

   printf("Error: %d.\n", maxdb_stmt_errno($stmt));

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Warning: maxdb_stmt_execute(): -4004 POS(23) Unknown table name:MYCITY [42000] <...>
Error: -4004.

See Also

  • maxdb_stmt_error() - Returns a string description for last statement error
  • maxdb_stmt_sqlstate() - Returns SQLSTATE error from previous statement operation


Returns a string description for last statement error

  • « maxdb_stmt_errno
  • maxdb_stmt_execute »
  • PHP Manual
  • MaxDB Functions
  • Returns a string description for last statement error

maxdb_stmt_error

maxdb_stmt::error

(PECL maxdb >= 1.0)

maxdb_stmt_error -- maxdb_stmt::error — Returns a string description for last statement error

Description

Procedural style

maxdb_stmt_error ( resource $stmt ) : string

Object oriented style

string $maxdb_stmt->error;

For the statement specified by stmt, maxdb_stmt_error() returns a containing the error message for the most recently invoked statement function that can succeed or fail.

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 */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query("INSERT INTO temp.mycity SELECT * FROM hotel.city");

$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = $maxdb->prepare($query)) {

   /* drop table */
   $maxdb->query("DROP TABLE temp.mycity");

   /* execute query */
   $stmt->execute();

   printf("Error: %s.\n", $stmt->error);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
/* Open a connection */
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");
maxdb_query($link, "INSERT INTO temp.mycity SELECT * FROM hotel.city");

$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = maxdb_prepare($link, $query)) {

   /* drop table */
   maxdb_query($link, "DROP TABLE temp.mycity");

   /* execute query */
   maxdb_stmt_execute($stmt);

   printf("Error: %s.\n", maxdb_stmt_error($stmt));

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Warning: maxdb_stmt_execute(): -4004 POS(23) Unknown table name:MYCITY [42000] <...>
Error: POS(23) Unknown table name:MYCITY.

See Also

  • maxdb_stmt_errno() - Returns the error code for the most recent statement call
  • maxdb_stmt_sqlstate() - Returns SQLSTATE error from previous statement operation


Executes a prepared Query

  • « maxdb_stmt_error
  • maxdb_stmt_fetch »
  • PHP Manual
  • MaxDB Functions
  • Executes a prepared Query

maxdb_stmt_execute

maxdb_stmt::execute

(PECL maxdb >= 1.0)

maxdb_stmt_execute -- maxdb_stmt::execute — Executes a prepared Query

Description

Procedural style

maxdb_stmt_execute ( resource $stmt ) : bool

Object oriented style

maxdb_stmt::execute ( void ) : bool

The maxdb_stmt_execute() function executes a query that has been previously prepared using the maxdb_prepare() function represented by the stmt resource. When executed any parameter markers which exist will automatically be replaced with the appropriate data.

If the statement is UPDATE, DELETE, or INSERT, the total number of affected rows can be determined by using the maxdb_stmt_affected_rows() function. Likewise, if the query yields a result set the maxdb_fetch() function is used.

Note:

When using maxdb_stmt_execute(), the maxdb_fetch() function must be used to fetch the data prior to preforming any additional queries.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");

/* Prepare an insert statement */
$query = "INSERT INTO temp.mycity (zip, name, state) VALUES (?,?,?)";
$stmt = $maxdb->prepare($query);

$stmt->bind_param("sss", $val1, $val2, $val3);

$val1 = '11111';
$val2 = 'Georgetown';
$val3 = 'NY';

/* Execute the statement */
$stmt->execute();

$val1 = '22222';
$val2 = 'Hubbatown';
$val3 = 'CA';

/* Execute the statement */
$stmt->execute();

/* close statement */
$stmt->close();

/* retrieve all rows from myCity */
$query = "SELECT zip, name, state FROM temp.mycity";
if ($result = $maxdb->query($query)) {
   while ($row = $result->fetch_row()) {
       printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
   }
   /* free result set */
   $result->close();
}

/* remove table */
$maxdb->query("DROP TABLE temp.mycity");

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");

/* Prepare an insert statement */
$query = "INSERT INTO temp.mycity (zip, name, state) VALUES (?,?,?)";
$stmt = maxdb_prepare($link, $query);

maxdb_stmt_bind_param($stmt, "sss", $val1, $val2, $val3);

$val1 = '11111';
$val2 = 'Georgetown';
$val3 = 'NY';

/* Execute the statement */
maxdb_stmt_execute($stmt);

$val1 = '22222';
$val2 = 'Hubbatown';
$val3 = 'CA';

/* Execute the statement */
maxdb_stmt_execute($stmt);

/* close statement */
maxdb_stmt_close($stmt);

/* retrieve all rows from myCity */
$query = "SELECT zip, name, state FROM temp.mycity";
if ($result = maxdb_query($link, $query)) {
   while ($row = maxdb_fetch_row($result)) {
       printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
   }
   /* free result set */
   maxdb_free_result($result);
}

/* remove table */
maxdb_query($link, "DROP TABLE temp.mycity");

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

11111 (Georgetown,NY)
22222 (Hubbatown,CA)

See Also

  • maxdb_prepare() - Prepare an SQL statement for execution
  • maxdb_stmt_bind_param() - Binds variables to a prepared statement as parameters


Fetch results from a prepared statement into the bound variables

  • « maxdb_stmt_execute
  • maxdb_stmt_free_result »
  • PHP Manual
  • MaxDB Functions
  • Fetch results from a prepared statement into the bound variables

maxdb_stmt_fetch

maxdb_stmt::fetch

(PECL maxdb >= 1.0)

maxdb_stmt_fetch -- maxdb_stmt::fetch — Fetch results from a prepared statement into the bound variables

Description

Procedural style

maxdb_stmt_fetch ( resource $stmt ) : bool

Object oriented style

maxdb_stmt::fetch ( void ) : bool

maxdb_stmt_fetch() returns row data using the variables bound by maxdb_stmt_bind_result().

Note:

Note that all columns must be bound by the application before calling maxdb_stmt_fetch().

Return Values

Return values
Value | Description
TRUE | Success. Data has been fetched
FALSE | Error occurred
NULL | No more rows/data exists

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT zip, name FROM hotel.city ORDER by name";

if ($stmt = $maxdb->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 */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT zip, name FROM hotel.city ORDER by name";

if ($stmt = maxdb_prepare($link, $query)) {

   /* execute statement */
   maxdb_stmt_execute($stmt);

   /* bind result variables */
   maxdb_stmt_bind_result($stmt, $name, $code);

   /* fetch values */
   while (maxdb_stmt_fetch($stmt)) {
       printf ("%s (%s)\n", $name, $code);
   }

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

12203 (Albany)
60601 (Chicago)
60615 (Chicago)
45211 (Cincinnati)
33575 (Clearwater)
75243 (Dallas)
32018 (Daytona Beach)
33441 (Deerfield Beach)
48226 (Detroit)
90029 (Hollywood)
92714 (Irvine)
90804 (Long Beach)
11788 (Long Island)
90018 (Los Angeles)
70112 (New Orleans)
10019 (New York)
10580 (New York)
92262 (Palm Springs)
97213 (Portland)
60018 (Rosemont)
95054 (Santa Clara)
20903 (Silver Spring)
20005 (Washington)
20019 (Washington)
20037 (Washington)

See Also

  • maxdb_prepare() - Prepare an SQL statement for execution
  • maxdb_stmt_errno() - Returns the error code for the most recent statement call
  • maxdb_stmt_error() - Returns a string description for last statement error
  • maxdb_stmt_bind_result() - Binds variables to a prepared statement for result storage


Frees stored result memory for the given statement handle

  • « maxdb_stmt_fetch
  • maxdb_stmt_init »
  • PHP Manual
  • MaxDB Functions
  • Frees stored result memory for the given statement handle

maxdb_stmt_free_result

maxdb_stmt::free_result

(PECL maxdb >= 1.0)

maxdb_stmt_free_result -- maxdb_stmt::free_result — Frees stored result memory for the given statement handle

Description

Procedural style

maxdb_stmt_free_result ( resource $stmt ) : void

Object oriented style

maxdb_stmt::free_result ( void ) : void

The maxdb_stmt_free_result() function frees the result memory associated with the statement represented by the stmt parameter, which was allocated by maxdb_stmt_store_result().

Return Values

This function doesn't return any value.

See Also

  • maxdb_stmt_store_result() - Transfers a result set from a prepared statement


Initializes a statement and returns an resource for use with maxdb_stmt_prepare

  • « maxdb_stmt_free_result
  • maxdb_stmt_num_rows »
  • PHP Manual
  • MaxDB Functions
  • Initializes a statement and returns an resource for use with maxdb_stmt_prepare

maxdb_stmt_init

maxdb::stmt_init

(PECL maxdb >= 1.0)

maxdb_stmt_init -- maxdb::stmt_init — Initializes a statement and returns an resource for use with maxdb_stmt_prepare

Description

Procedural style

maxdb_stmt_init ( resource $link ) : resource

Object oriented style

maxdb::stmt_init ( void ) : object

Allocates and initializes a statement resource suitable for maxdb_stmt_prepare().

Note:

Any subsequent calls to any maxdb_stmt function will fail until maxdb_stmt_prepare() was called.

Return Values

Returns an resource.

See Also

  • maxdb_stmt_prepare() - Prepare an SQL statement for execution


Return the number of rows in statements result set

  • « maxdb_stmt_init
  • maxdb_stmt_param_count »
  • PHP Manual
  • MaxDB Functions
  • Return the number of rows in statements result set

maxdb_stmt_num_rows

maxdb_stmt::num_rows

(PECL maxdb >= 1.0)

maxdb_stmt_num_rows -- maxdb_stmt::num_rows — Return the number of rows in statements result set

Description

Procedural style

maxdb_stmt_num_rows ( resource $stmt ) : int

Object oriented style

int $maxdb_stmt->num_rows;

Returns the number of rows in the result set.

Return Values

An integer representing the number of rows in result set.

Examples

Example #1 Object oriented style

<?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT zip, name FROM hotel.city ORDER BY name";
if ($stmt = $maxdb->prepare($query)) {

   /* execute query */
   $stmt->execute();

   /* store result */
   $stmt->store_result();

   printf("Number of rows: %d.\n", $stmt->num_rows);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
/* Open a connection */
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT zip, name FROM hotel.city ORDER BY name";
if ($stmt = maxdb_prepare($link, $query)) {

   /* execute query */
   maxdb_stmt_execute($stmt);

   /* store result */
   maxdb_stmt_store_result($stmt);

   printf("Number of rows: %d.\n", maxdb_stmt_num_rows($stmt));

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Number of rows: 25.

See Also

  • maxdb_stmt_affected_rows() - Returns the total number of rows changed, deleted, or inserted by the last executed statement
  • maxdb_prepare() - Prepare an SQL statement for execution
  • maxdb_stmt_store_result() - Transfers a result set from a prepared statement


Returns the number of parameter for the given statement

  • « maxdb_stmt_num_rows
  • maxdb_stmt_prepare »
  • PHP Manual
  • MaxDB Functions
  • Returns the number of parameter for the given statement

maxdb_stmt_param_count

maxdb_stmt::param_count

(PECL maxdb >= 1.0)

maxdb_stmt_param_count -- maxdb_stmt::param_count — Returns the number of parameter for the given statement

Description

Procedural style

maxdb_stmt_param_count ( resource $stmt ) : int

Object oriented style

int $maxdb_stmt->param_count;

maxdb_stmt_param_count() returns the number of parameter markers present in the prepared statement.

Return Values

returns an integer representing the number of parameters.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($stmt = $maxdb->prepare("SELECT name FROM hotel.city WHERE name=? OR state=?")) {

   $marker = $stmt->param_count;
   printf("Statement has %d markers.\n", $marker);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

if ($stmt = maxdb_prepare($link, "SELECT name FROM hotel.city WHERE name=? OR state=?")) {

   $marker = maxdb_stmt_param_count($stmt);
   printf("Statement has %d markers.\n", $marker);

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Statement has 2 markers.

See Also

  • maxdb_prepare() - Prepare an SQL statement for execution


Prepare an SQL statement for execution

  • « maxdb_stmt_param_count
  • maxdb_stmt_reset »
  • PHP Manual
  • MaxDB Functions
  • Prepare an SQL statement for execution

maxdb_stmt_prepare

maxdb_stmt::prepare

(PECL maxdb >= 1.0)

maxdb_stmt_prepare -- maxdb_stmt::prepare — Prepare an SQL statement for execution

Description

Procedural style

maxdb_stmt_prepare ( resource $stmt , string $query ) : bool

Object oriented style

maxdb_stmt::prepare ( string $query ) : mixed

maxdb_stmt_prepare() prepares the SQL query pointed to by the null-terminated string query. The statement resource has to be allocated by maxdb_stmt_init(). The query must consist of a single SQL statement.

Note:

You should not add a terminating semicolon or \g to the statement.

The parameter query can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions.

Note:

The markers are legal only in certain places in SQL statements. For example, they are allowed 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 allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement), or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. In general, parameters are legal only in Data Manipulation Languange (DML) statements, and not in Data Defination Language (DDL) statements.

The parameter markers must be bound to application variables using maxdb_stmt_bind_param() and/or maxdb_stmt_bind_result() before executing the statement or fetching rows.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$city = "Portland";

/* create a prepared statement */
$stmt =  $maxdb->stmt_init();
if ($stmt->prepare("SELECT state FROM hotel.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);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$city = "Portland";

/* create a prepared statement */
$stmt = maxdb_stmt_init($link);
if (maxdb_stmt_prepare($stmt, "SELECT state FROM hotel.city WHERE name=?")) {

   /* bind parameters for markers */
   maxdb_stmt_bind_param($stmt, "s", $city);

   /* execute query */
   maxdb_stmt_execute($stmt);

   /* bind result variables */
   maxdb_stmt_bind_result($stmt, $district);

   /* fetch value */
   maxdb_stmt_fetch($stmt);

   printf("%s is in district %s\n", $city, $district);

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Portland is in district OR

See Also

  • maxdb_stmt_init() - Initializes a statement and returns an resource for use with maxdb_stmt_prepare
  • maxdb_stmt_execute() - Executes a prepared Query
  • maxdb_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • maxdb_stmt_bind_param() - Binds variables to a prepared statement as parameters
  • maxdb_stmt_bind_result() - Binds variables to a prepared statement for result storage
  • maxdb_stmt_close() - Closes a prepared statement


Resets a prepared statement

  • « maxdb_stmt_prepare
  • maxdb_stmt_result_metadata »
  • PHP Manual
  • MaxDB Functions
  • Resets a prepared statement

maxdb_stmt_reset

maxdb_stmt::reset

(PECL maxdb >= 1.0)

maxdb_stmt_reset -- maxdb_stmt::reset — Resets a prepared statement

Description

Procedural style

maxdb_stmt_reset ( resource $stmt ) : bool

Object oriented style

maxdb_stmt::reset ( void ) : bool
Warning

This function is currently not documented; only its argument list is available.


Returns result set metadata from a prepared statement

  • « maxdb_stmt_reset
  • maxdb_stmt_send_long_data »
  • PHP Manual
  • MaxDB Functions
  • Returns result set metadata from a prepared statement

maxdb_stmt_result_metadata

maxdb_stmt::result_metadata

(PECL maxdb >= 1.0)

maxdb_stmt_result_metadata -- maxdb_stmt::result_metadata — Returns result set metadata from a prepared statement

Description

Procedural style

maxdb_stmt_result_metadata ( resource $stmt ) : resource

Object oriented style

maxdb_stmt::result_metadata ( void ) : resource

If a statement passed to maxdb_prepare() is one that produces a result set, maxdb_stmt_result_metadata() returns the result resource that can be used to process the meta information such as total number of fields and individual field information.

Note:

This result set pointer can be passed as an argument to any of the field-based functions that process result set metadata, such as:

  • maxdb_num_fields()

  • maxdb_fetch_field()

  • maxdb_fetch_field_direct()

  • maxdb_fetch_fields()

  • maxdb_field_count()

  • maxdb_field_seek()

  • maxdb_field_tell()

  • maxdb_free_result()

The result set structure should be freed when you are done with it, which you can do by passing it to maxdb_free_result()

Note:

The result set returned by maxdb_stmt_result_metadata() contains only metadata. It does not contain any row results. The rows are obtained by using the statement handle with maxdb_fetch().

Return Values

maxdb_stmt_result_metadata() returns a result resource or FALSE if an error occurred.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

$maxdb->query("CREATE TABLE temp.friends (id int, name varchar(20))");

$maxdb->query("INSERT INTO temp.friends VALUES (1,'Hartmut')");
$maxdb->query("INSERT INTO temp.friends VALUES (2, 'Ulf')");

$stmt = $maxdb->prepare("SELECT id, name FROM temp.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);

/* close resultset */
$result->close();

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

maxdb_query($link, "CREATE TABLE temp.friends (id int, name varchar(20))");

maxdb_query($link, "INSERT INTO temp.friends VALUES (1,'Hartmut')");
maxdb_query($link, "INSERT INTO temp.friends VALUES (2, 'Ulf')");

$stmt = maxdb_prepare($link, "SELECT id, name FROM temp.friends");
maxdb_stmt_execute($stmt);

/* get resultset for metadata */
$result = maxdb_stmt_result_metadata($stmt);

/* retrieve field information from metadata result set */
$field = maxdb_fetch_field($result);

printf("Fieldname: %s\n", $field->name);

/* close resultset */
maxdb_free_result($result);

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Fieldname: ID

See Also

  • maxdb_prepare() - Prepare an SQL statement for execution
  • maxdb_free_result() - Frees the memory associated with a result


Send data in blocks

  • « maxdb_stmt_result_metadata
  • maxdb_stmt_sqlstate »
  • PHP Manual
  • MaxDB Functions
  • Send data in blocks

maxdb_stmt_send_long_data

maxdb_stmt::send_long_data

(PECL maxdb 1.0)

maxdb_stmt_send_long_data -- maxdb_stmt::send_long_data — Send data in blocks

Description

Procedural style

maxdb_stmt_send_long_data ( resource $stmt , int $param_nr , string $data ) : bool

Object oriented style

maxdb_stmt::stmt_send_long_data ( int $param_nr , string $data ) : bool

Allows to send parameter data to the server in pieces (or chunks). 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.

param_nr indicates which parameter to associate the data with. Parameters are numbered beginning with 0. data is a string containing data to be sent.

Note:

For efficiency reasons, this function should be used after calling maxdb_execute(). In this case, the data is not stored on the client side. The end of the sequence must end with a call to maxdb_stmt_close_long_data().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • maxdb_prepare() - Prepare an SQL statement for execution
  • maxdb_stmt_bind_param() - Binds variables to a prepared statement as parameters


Returns SQLSTATE error from previous statement operation

  • « maxdb_stmt_send_long_data
  • maxdb_stmt_store_result »
  • PHP Manual
  • MaxDB Functions
  • Returns SQLSTATE error from previous statement operation

maxdb_stmt_sqlstate

(PECL maxdb >= 1.0)

maxdb_stmt_sqlstate — Returns SQLSTATE error from previous statement operation

Description

maxdb_stmt_sqlstate ( resource $stmt ) : 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.

Note:

Note that not all MaxDB errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.

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 */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");
$maxdb->query("INSERT INTO temp.mycity SELECT * FROM hotel.city");

$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = $maxdb->prepare($query)) {

   /* drop table */
   $maxdb->query("DROP TABLE temp.mycity");

   /* execute query */
   $stmt->execute();

   printf("Error: %s.\n", $stmt->sqlstate);

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
/* Open a connection */
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");
maxdb_query($link, "INSERT INTO temp.mycity SELECT * FROM hotel.city");

$query = "SELECT name, zip FROM temp.mycity ORDER BY name";
if ($stmt = maxdb_prepare($link, $query)) {

   /* drop table */
   maxdb_query($link, "DROP TABLE temp.mycity");

   /* execute query */
   maxdb_stmt_execute($stmt);

   printf("Error: %s.\n", maxdb_stmt_sqlstate($stmt));

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Warning: maxdb_stmt_execute(): -4004 POS(23) Unknown table name:MYCITY [42000] <...>
Error: 42000.

See Also

  • maxdb_stmt_errno() - Returns the error code for the most recent statement call
  • maxdb_stmt_error() - Returns a string description for last statement error


Transfers a result set from a prepared statement

  • « maxdb_stmt_sqlstate
  • maxdb_store_result »
  • PHP Manual
  • MaxDB Functions
  • Transfers a result set from a prepared statement

maxdb_stmt_store_result

maxdb_stmt::store_result

(PECL maxdb >= 1.0)

maxdb_stmt_store_result -- maxdb_stmt::store_result — Transfers a result set from a prepared statement

Description

Procedural style

maxdb_stmt_store_result ( resource $stmt ) : bool

Object oriented style

maxdb_stmt::store_result ( void ) : object

maxdb_stmt_store_result() has no functionally effect and should not be used for retrieving data from MaxDB server.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
/* Open a connection */
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, zip FROM hotel.city ORDER BY name";
if ($stmt = $maxdb->prepare($query)) {

   /* execute query */
   $stmt->execute();

   /* store result */
   $stmt->store_result();

   printf("Number of rows: %d.\n", $stmt->num_rows);

   /* free result */
   $stmt->free_result();

   /* close statement */
   $stmt->close();
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
/* Open a connection */
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query = "SELECT name, zip FROM hotel.city ORDER BY name";
if ($stmt = maxdb_prepare($link, $query)) {

   /* execute query */
   maxdb_stmt_execute($stmt);

   /* store result */
   maxdb_stmt_store_result($stmt);

   printf("Number of rows: %d.\n", maxdb_stmt_num_rows($stmt));

   /* free result */
   maxdb_stmt_free_result($stmt);

   /* close statement */
   maxdb_stmt_close($stmt);
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Number of rows: 25.

See Also

  • maxdb_prepare() - Prepare an SQL statement for execution
  • maxdb_stmt_result_metadata() - Returns result set metadata from a prepared statement
  • maxdb_fetch() - Alias of maxdb_stmt_fetch


Transfers a result set from the last query

  • « maxdb_stmt_store_result
  • maxdb_thread_id »
  • PHP Manual
  • MaxDB Functions
  • Transfers a result set from the last query

maxdb_store_result

maxdb::store_result

(PECL maxdb >= 1.0)

maxdb_store_result -- maxdb::store_result — Transfers a result set from the last query

Description

Procedural style

maxdb_store_result ( resource $link ) : resource

Object oriented style

maxdb::store_result ( void ) : object

This function has no functionally effect.

Return Values

Returns a result resource or FALSE if an error occurred.

Examples

See maxdb_multi_query().

See Also

  • maxdb_real_query() - Execute an SQL query
  • maxdb_use_result() - Initiate a result set retrieval


Returns the thread ID for the current connection

  • « maxdb_store_result
  • maxdb_thread_safe »
  • PHP Manual
  • MaxDB Functions
  • Returns the thread ID for the current connection

maxdb_thread_id

maxdb::thread_id

(PECL maxdb >= 1.0)

maxdb_thread_id -- maxdb::thread_id — Returns the thread ID for the current connection

Description

Procedural style

maxdb_thread_id ( resource $link ) : int

Object oriented style

int $maxdb->thread_id;

The maxdb_thread_id() function returns the thread ID for the current connection which can then be killed using the maxdb_kill() function. If the connection is lost and you reconnect with maxdb_ping(), the thread ID will be other. 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.

Return Values

maxdb_thread_id() returns the Thread ID for the current connection.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* determine our thread id */
$thread_id = $maxdb->thread_id;

/* Kill connection */
$maxdb->kill($thread_id);

/* This should produce an error */
if (!$maxdb->query("CREATE TABLE mycity LIKE hotel.city")) {
   printf("Error: %s\n", $maxdb->error);
   exit;
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

/* determine our thread id */
$thread_id = maxdb_thread_id($link);

/* Kill connection */
maxdb_kill($link, $thread_id);

/* This should produce an error */
if (!maxdb_query($link, "CREATE TABLE mycity LIKE hotel.city")) {
   printf("Error: %s\n", maxdb_error($link));
   exit;
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Warning: maxdb_query(): -10821 Session not connected <...>
Error: Session not connected

See Also

  • maxdb_kill() - Disconnects from a MaxDB server


Returns whether thread safety is given or not

  • « maxdb_thread_id
  • maxdb_use_result »
  • PHP Manual
  • MaxDB Functions
  • Returns whether thread safety is given or not

maxdb_thread_safe

(PECL maxdb >= 7.6.06.04)

maxdb_thread_safe — Returns whether thread safety is given or not

Description

maxdb_thread_safe ( void ) : bool

maxdb_thread_safe() indicates whether the client library is compiled as thread-safe.

Return Values

TRUE if the client library is thread-safe, otherwise FALSE.


Initiate a result set retrieval

  • « maxdb_thread_safe
  • maxdb_warning_count »
  • PHP Manual
  • MaxDB Functions
  • Initiate a result set retrieval

maxdb_use_result

maxdb::use_result

(PECL maxdb >= 1.0)

maxdb_use_result -- maxdb::use_result — Initiate a result set retrieval

Description

Procedural style

maxdb_use_result ( resource $link ) : resource

Object oriented style

maxdb::use_result ( void ) : resource

maxdb_use_result() has no effect.

Return Values

Returns result or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query  = "SELECT * FROM DUAL";

/* execute multi query */
if ($maxdb->multi_query($query)) {
   do {
       /* store first result set */
       if ($result = $maxdb->use_result()) {
           while ($row = $result->fetch_row()) {
               printf("%s\n", $row[0]);
           }
           $result->close();
       }
       /* print divider */
       if ($maxdb->more_results()) {
           printf("-----------------\n");
       }
   } while ($maxdb->next_result());
}

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$query  = "SELECT * FROM DUAL";

/* execute multi query */
if (maxdb_multi_query($link, $query)) {
   do {
       /* store first result set */
       if ($result = maxdb_use_result($link)) {
           while ($row = maxdb_fetch_row($result)) {
               printf("%s\n", $row[0]);
           }
           maxdb_free_result($result);
       }
       /* print divider */
       if (maxdb_more_results($link)) {
           printf("-----------------\n");
       }
   } while (maxdb_next_result($link));
}

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

a

See Also

  • maxdb_real_query() - Execute an SQL query
  • maxdb_store_result() - Transfers a result set from the last query


Returns the number of warnings from the last query for the given link

  • « maxdb_use_result
  • Mongo »
  • PHP Manual
  • MaxDB Functions
  • Returns the number of warnings from the last query for the given link

maxdb_warning_count

maxdb::warning_count

(PECL maxdb >= 1.0)

maxdb_warning_count -- maxdb::warning_count — Returns the number of warnings from the last query for the given link

Description

Procedural style

maxdb_warning_count ( resource $link ) : int

Object oriented style

int $maxdb->warning_count;

maxdb_warning_count() returns the number of warnings from the last query in the connection represented by the link parameter.

Return Values

Number of warnings or zero if there are no warnings.

Examples

Example #1 Object oriented style

<?php
$maxdb = new maxdb("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

$maxdb->query("CREATE TABLE temp.mycity LIKE hotel.city");

/* a remarkable city in Wales */
$query = "INSERT INTO temp.mycity (zip, name) VALUES('11111',
       'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')";

$maxdb->query($query);

printf ("Number of warning: %d\n", $maxdb->warning_count);

/* close connection */
$maxdb->close();
?>

Example #2 Procedural style

<?php
$link = maxdb_connect("localhost", "MONA", "RED", "DEMODB");

/* check connection */
if (maxdb_connect_errno()) {
   printf("Connect failed: %s\n", maxdb_connect_error());
   exit();
}

maxdb_query($link, "CREATE TABLE temp.mycity LIKE hotel.city");

/* a remarkable long city name in Wales */
$query = "INSERT INTO temp.mycity (zip, name) VALUES('11111',
       'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')";

maxdb_query($link, $query);

printf ("Number of warning: %d\n", maxdb_warning_count($link));

/* close connection */
maxdb_close($link);
?>

The above example will output something similar to:

Warning: maxdb_query(): -8004 POS(62) Constant must be compatible with column type and length <...>
Number of warning: 0

See Also

  • maxdb_errno() - Returns the error code for the most recent function call
  • maxdb_error() - Returns a string description of the last error
  • maxdb_sqlstate() - Returns the SQLSTATE error from previous MaxDB operation


MongoDB driver (legacy)

  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
  • Predefined Constants
  • Manual
    • Tutorial
    • Read Preferences
    • Write Concerns
    • SQL to Mongo Mapping Chart
    • Connecting
    • Stream Context Options
    • Writes
    • Querying
    • Updates
    • Security
    • Troubleshooting
    • Running the Driver's Tests
  • Core Classes
    • MongoClient — The MongoClient class
    • MongoDB — The MongoDB class
    • MongoCollection — The MongoCollection class
    • MongoCursor — The MongoCursor class
    • MongoCursorInterface — The MongoCursorInterface interface
    • MongoCommandCursor — The MongoCommandCursor class
  • Types
    • MongoId — The MongoId class
    • MongoCode — The MongoCode class
    • MongoDate — The MongoDate class
    • MongoRegex — The MongoRegex class
    • MongoBinData — The MongoBinData class
    • MongoInt32 — The MongoInt32 class
    • MongoInt64 — The MongoInt64 class
    • MongoDBRef — The MongoDBRef class
    • MongoMinKey — The MongoMinKey class
    • MongoMaxKey — The MongoMaxKey class
    • MongoTimestamp — The MongoTimestamp class
  • GridFS Classes
    • MongoGridFS — The MongoGridFS class
    • MongoGridFSFile — The MongoGridFSFile class
    • MongoGridFSCursor — The MongoGridFSCursor class
  • Batch Classes
    • MongoWriteBatch — The MongoWriteBatch class
    • MongoInsertBatch — The MongoInsertBatch class
    • MongoUpdateBatch — The MongoUpdateBatch class
    • MongoDeleteBatch — The MongoDeleteBatch class
  • Miscellaneous
    • MongoLog — The MongoLog class
    • MongoPool — The MongoPool class
    • Mongo — The Mongo class [deprecated]
  • Mongo Functions
    • bson_decode — Deserializes a BSON object into a PHP array
    • bson_encode — Serializes a PHP variable into a BSON string
  • Exceptions
    • MongoException — The MongoException class
    • MongoResultException — The MongoResultException class
    • MongoCursorException — The MongoCursorException class
    • MongoCursorTimeoutException — The MongoCursorTimeoutException class
    • MongoConnectionException — The MongoConnectionException class
    • MongoGridFSException — The MongoGridFSException class
    • MongoDuplicateKeyException — The MongoDuplicateKeyException class
    • MongoProtocolException — The MongoProtocolException class
    • MongoExecutionTimeoutException — The MongoExecutionTimeoutException class
    • MongoWriteConcernException — The MongoWriteConcernException class
  • Changelog


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
Warning

This extension is deprecated. Instead, the MongoDB extension should be used.


Installation

Warning

This extension is deprecated. Instead, the MongoDB extension should be used.

The MongoDB PHP driver should work on nearly any system: Windows, macOS, Unix, and Linux; little- and big-endian machines; 32- and 64-bit machines; PHP 5.3 through 5.6 (versions prior to 1.6 also support PHP 5.2).

This » PECL extension is not bundled with PHP.

  • Manual Installation
  • Installing on *NIX
  • Installing on Windows
  • macOS
  • Gentoo
  • Red Hat
  • Third-Party Installation Instructions

Manual Installation

For driver developers and people interested in the latest bugfixes, you can compile the driver from the latest source code on » Github. Go to Github and click the "download" button. Then run:

$ tar zxvf mongo-php-driver-legacy-<commit_id>.tar.gz
$ cd mongo-php-driver-legacy-<commit_id>
$ phpize
$ ./configure
$ make all
$ sudo make install

Make the following changes to php.ini:

  • Make sure the extension_dir variable is pointing to the directory containing mongo.so. The build will display where it is installing the PHP driver with output that looks something like:

    Installing '/usr/lib/php/extensions/no-debug-non-zts-20060613/mongo.so'
    Make sure that it is the same as the PHP extension directory by running:
    $ php -i | grep extension_dir
  extension_dir => /usr/lib/php/extensions/no-debug-non-zts-20060613 =>
                   /usr/lib/php/extensions/no-debug-non-zts-20060613
    If it's not, change the extension_dir in php.ini or move mongo.so.

  • To load the extension on PHP startup, add a line:

    extension=mongo.so

Installing on *NIX

Run:

$ sudo pecl install mongo

Add the following line to your php.ini file:

extension=mongo.so

If pecl runs out of memory while installing, make sure memory_limit in php.ini is set to at least 128MB.

Installing on Windows

Precompiled binaries for each release are available from » PECL for a variety of combinations of versions, thread safety, and VC libraries. Unzip the archive and put php_mongo.dll in your PHP extension directory ("ext" by default).

Add the following line to your php.ini file:

extension=php_mongo.dll

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

macOS

In most cases installing from PECL is the easiest way:

$ sudo pecl install mongo

If your system has multiple version of PHP installed (e.g. macOS default, Homebrew, » XAMPP), note that that each version of PHP has its own pecl command and php.ini file.

Note: Xcode dependency for compiling on macOS

Compiling the driver on macOS will require Xcode developer tools, which may be installed with xcode-select --install. If that command is not available, you may first need to install the » Command Line Tools package.

Gentoo

Gentoo has a package for the PHP PECL driver called dev-php/pecl-mongo, which can be installed with:

$ sudo emerge -va dev-php/pecl-mongo

If you use PECL, you may get an error that libtool is the wrong version. Compiling from source you'll need to run aclocal and autoconf.

$ phpize
$ aclocal
$ autoconf
$ ./configure
$ make
$ sudo make install

Red Hat

This includes Fedora and CentOS.

The default Apache settings on these systems do not let requests make network connections, meaning that the driver will get "Permission denied" errors when it tries to connect to the database. If you run into this, try running:

$ /usr/sbin/setsebool -P httpd_can_network_connect 1
Then restart Apache. (This issue has also occurred with SELinux.)

Third-Party Installation Instructions

A number of people have created excellent tutorials on installing the PHP driver.

  • » (Re)installing PHP on macOS

    This article by Justin Hileman details the process of installing PHP and additional extensions with Homebrew on macOS. This complements the earlier instructions on this page for installing the driver with Homebrew.

  • » PHP 5.3.1 with Xdebug, MongoDB and Lithium on Ubuntu 9.10 / Apache 2.2

    This screencast by Jon Adams demonstrates how to quickly get up and running with PHP 5.3.1, Xdebug, and MongoDB on Ubuntu 9.10 with Apache.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Mongo Configure Options
Name | Default | Changeable | Changelog
mongo.allow_empty_keys | 0 | PHP_INI_ALL |
mongo.allow_persistent | 1 | PHP_INI_ALL | Removed in 1.2.0
mongo.chunk_size | 262144 | PHP_INI_ALL |
mongo.cmd | "$" | PHP_INI_ALL |
mongo.default_host | "localhost" | PHP_INI_ALL |
mongo.default_port | 27017 | PHP_INI_ALL |
mongo.is_master_interval | 15 | PHP_INI_ALL | Added in 1.2.10, before 1.3.0 the default value was 60.
mongo.long_as_object | 0 | PHP_INI_ALL |
mongo.native_long | 1 | PHP_INI_ALL | Before 1.5.0, the default value was 0.
mongo.ping_interval | 5 | PHP_INI_ALL | Added in 1.2.10
mongo.utf8 | 1 | PHP_INI_ALL |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

mongo.allow_empty_keys int

Added in version 1.0.11.

If empty strings ("") should be allowed as key names. By default, the driver will throw an exception if you attempt to pass the empty string as a key to the database. It is extremely easy to do this inavertently by using double quotes with $-operators, so it is recommended that you leave this setting as default. However, if you need to save keys that are empty strings, you can set this option to true and the driver will allow you to pass empty strings to the database.

mongo.allow_persistent int

If persistent connections are allowed. (Removed in 1.2.0 - all connections are now persistent).

mongo.chunk_size int

The number of bytes-per-chunk. Used in divvying up GridFS files. This number must be at least 100 less than 4 megabytes (max: 4194204) and it is recommended that it be less than that.

mongo.cmd string

A character to be used in place of $ in modifiers and comparisons.

As it is easy to forget to escape the "$", you can also choose your own special character to use instead of '$'. Choose a character that will not occur in your key names, e.g. ":":

mongo.cmd = ":"

Then, to do a comparison, for example:

<?php

$query = array( "i" => array( ":gt" => 20, ":lte" => 30 ) );

?>

You can also change it in your code using ini_set("mongo.cmd", ":"). Of course, you can also just use single quotes or backslash-escape the $.

mongo.default_host string

Default hostname when nothing is passed to the constructor.

mongo.default_port string

The default TCP port number to use when connecting to the database server if no other port is specified. The database's default is 27017.

mongo.is_master_interval int

Added in version 1.2.10.

For replicaset connections: The minimum interval with which the driver will send "isMaster" requests to the MongoDB server. If the value is lower, there will be more requests, but the driver finds faster whether the topology of the replicaset has been changed.

mongo.long_as_object int

Return a BSON_LONG as an instance of MongoInt64 (instead of a primitive type).

mongo.native_long int

The default behavior for this has been changed to TRUE in 1.5.0, so make sure to set this variable to the value you want (probably TRUE) so that the driver's behavior doesn't suddenly change when you upgrade.

On 64-bit platforms, the mongo.native_long setting allows for 64-bit integers to be stored in MongoDB. If it is not set, only 32-bits of the integer will be saved. The MongoDB data type that is used in this case is the BSON LONG, instead of the BSON INT that is used if this setting is turned off.

The setting also changes the way how BSON LONGs behave when they are read back from MongoDB. Without mongo.native_long enabled, the driver would convert every BSON LONG to a PHP double which can result in a loss of precision.

On 32-bit platforms, the mongo.native_long setting changes nothing for storing integers in MongoDB: the integer is stored as a BSON INT as before. However, when the setting is enabled and a BSON LONG is read from MongoDB a MongoCursorException is thrown alerting you that the data could not be read back without losing precision.

On 32-bit systems especially, it is recommended that you combine this with enabling mongo.long_as_object.

mongo.ping_interval int

Added in version 1.2.10.

For replicaset connections: The minimum interval with which the driver will send "ping" requests to the MongoDB server. If the value is lower, there will be more pings, but the driver finds faster whether a node is no longer reachable from the replicaset.

mongo.utf8 int

If an exception should be thrown for non-UTF8 strings. Until version 1.0.4, the PHP driver would ignore non-UTF8 strings, even though you're not supposed to insert them. As of 1.0.4, the driver throws a MongoException. To ease the transition for applications that insert non-UTF8 strings, you can turn this option off to emulate the old, non-exception-throwning behavior. This option will be eliminated and exceptions always thrown for non-UTF8 strings starting with version 1.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.

MONGO_STREAMS (integer)
Alias of MONGO_SUPPORTS_STREAMS
MONGO_SUPPORTS_STREAMS (integer)
1 when compiled against PHP Streams (default since 1.4.0).
MONGO_SUPPORTS_SSL (integer)
1 when OpenSSL is enabled and available.
MONGO_SUPPORTS_AUTH_MECHANISM_MONGODB_CR (integer)
1 when MongoDB-Challenge/Reponse authentication is compiled in.
MONGO_SUPPORTS_AUTH_MECHANISM_MONGODB_X509 (integer)
1 when x.509 authentication is compiled in.
MONGO_SUPPORTS_AUTH_MECHANISM_GSSAPI (integer)
1 when GSSAPI authentication is compiled in.
MONGO_SUPPORTS_AUTH_MECHANISM_PLAIN (integer)
1 when PLAIN authentication is compiled in.
MONGO_STREAM_NOTIFY_TYPE_IO_INIT (integer)
MONGO_STREAM_NOTIFY_TYPE_LOG (integer)
MONGO_STREAM_NOTIFY_IO_READ (integer)
MONGO_STREAM_NOTIFY_IO_WRITE (integer)
MONGO_STREAM_NOTIFY_IO_PROGRESS (integer)
MONGO_STREAM_NOTIFY_IO_COMPLETED (integer)
MONGO_STREAM_NOTIFY_LOG_INSERT (integer)
MONGO_STREAM_NOTIFY_LOG_QUERY (integer)
MONGO_STREAM_NOTIFY_LOG_UPDATE (integer)
MONGO_STREAM_NOTIFY_LOG_DELETE (integer)
MONGO_STREAM_NOTIFY_LOG_GETMORE (integer)
MONGO_STREAM_NOTIFY_LOG_KILLCURSOR (integer)
MONGO_STREAM_NOTIFY_LOG_BATCHINSERT (integer)
MONGO_STREAM_NOTIFY_LOG_RESPONSE_HEADER (integer)
MONGO_STREAM_NOTIFY_LOG_WRITE_REPLY (integer)
MONGO_STREAM_NOTIFY_LOG_CMD_INSERT (integer)
MONGO_STREAM_NOTIFY_LOG_CMD_UPDATE (integer)
MONGO_STREAM_NOTIFY_LOG_CMD_DELETE (integer)
MONGO_STREAM_NOTIFY_LOG_WRITE_BATCH (integer)


Manual

Table of Contents

  • Tutorial
  • Read Preferences
  • Write Concerns
  • SQL to Mongo Mapping Chart
  • Connecting
  • Stream Context Options
  • Writes
  • Querying
  • Updates
  • Security
  • Troubleshooting
  • Running the Driver's Tests
Warning

This extension is deprecated. Instead, the MongoDB extension should be used.

This manual goes into some detail about how to use MongoDB, but it mostly covers using the PHP driver. For information about how to design a schema, what terms means, and setting up the database server, check out the » MongoDB documentation.


Tutorial

Table of Contents

  • Making a Connection
  • Getting a Database
  • Getting A Collection
  • Inserting a Document
  • Finding Documents using MongoCollection::findOne
  • Adding Multiple Documents
  • Counting Documents in A Collection
  • Using a Cursor to Get All of the Documents
  • Setting Criteria for a Query
  • Getting A Set of Documents With a Query
  • Creating An Index
Warning

This extension is deprecated. Instead, the MongoDB extension should be used.

This is the official MongoDB driver for PHP.

Here's a quick code sample that connects, inserts documents, queries for documents, iterates through query results, and disconnects from MongoDB. There are more details on each step in the tutorial below.

<?php

// connect
$m = new MongoClient();

// select a database
$db = $m->comedy;

// select a collection (analogous to a relational database's table)
$collection = $db->cartoons;

// add a record
$document = array( "title" => "Calvin and Hobbes", "author" => "Bill Watterson" );
$collection->insert($document);

// add another record, with a different "shape"
$document = array( "title" => "XKCD", "online" => true );
$collection->insert($document);

// find everything in the collection
$cursor = $collection->find();

// iterate through the results
foreach ($cursor as $document) {
    echo $document["title"] . "\n";
}

?>

The above example will output:

Calvin and Hobbes
XKCD


Making a Connection

To connect to the database server, use one of the following:

<?php
$connection = new MongoClient(); // connects to localhost:27017
$connection = new MongoClient( "mongodb://example.com" ); // connect to a remote host (default port: 27017)
$connection = new MongoClient( "mongodb://example.com:65432" ); // connect to a remote host at a given port
?>

You do not have to explicitly disconnect from the database. The driver uses persistent connections and will re-use already established connections.

See Also

The chapter on connecting covers different types of connections.

The API documentation on the MongoClient class and MongoClient::__construct() give a comprehensive look at all possible options with a number of examples.


Getting a Database

To select a database, use:

<?php
$connection = new MongoClient();
$db = $connection->dbname;
?>

The database does not need to be created in advance, you can create new databases by selecting them.

Be careful of typos! You can inadvertently create a new database, which can cause confusing errors (here name is misspelled as anme in the second selection:

<?php
$connection = new MongoClient();

$db = $connection->mybiglongdbname;
// do some stuff

$db = $connection->mybiglongdbanme;
// now connected to a different database!
?>

See Also

The API documentation on the MongoDB class contains more information about database objects.


Getting A Collection

Getting a collection has the same syntax as getting a database:

<?php
$connection = new MongoClient();
$db = $connection->baz;

// select a collection:
$collection = $db->foobar;

// or, directly selecting a database and collection:
$collection = $connection->baz->foobar;
?>

A collection is analogous to a table (if you are familiar with relational databases).

See Also

The API documentation on the MongoCollection class contains more information about collection objects.


Inserting a Document

Associative arrays are the basic object that can be saved to a collection in the database. A somewhat random "document" might be:

<?php
$doc = array(
    "name" => "MongoDB",
    "type" => "database",
    "count" => 1,
    "info" => (object)array( "x" => 203, "y" => 102),
    "versions" => array("0.9.7", "0.9.8", "0.9.9")
);
?>

Note that you can have nested arrays and objects. The driver will always store an associative array as an object in the database. A numerically indexed array is stored as an array in case the keys start at 0 and are not interrupted, and as an object if the array keys don't start at 0 or have gaps (ie: 0, 1, 4, 5).

To insert this document, use MongoCollection::insert():

<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;

$collection->insert( $doc );
?>

See Also

The API documentation on MongoCollection::insert() contains more information about inserting data.


Finding Documents using MongoCollection::findOne

  • « Inserting a Document
  • Adding Multiple Documents »
  • PHP Manual
  • Tutorial
  • Finding Documents using MongoCollection::findOne

Finding Documents using MongoCollection::findOne()

To show that the document we inserted in the previous step is stored in the database, we can do a simple MongoCollection::findOne() operation to get a single document from the collection. This method is useful when there is only one document matching the query or you are only interested in one result.

<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;

$document = $collection->findOne();
var_dump( $document );
?>

The above example will output:

array(6) {
  ["_id"]=>
  object(MongoId)#8 (1) {
    ["$id"]=>
    string(24) "4e2995576803fab768000000"
  }
  ["name"]=>
  string(7) "MongoDB"
  ["type"]=>
  string(8) "database"
  ["count"]=>
  int(1)
  ["info"]=>
  array(2) {
    ["x"]=>
    int(203)
    ["y"]=>
    int(102)
  }
  ["versions"]=>
  array(3) {
    [0]=>
    string(5) "0.9.7"
    [1]=>
    string(5) "0.9.8"
    [2]=>
    string(5) "0.9.9"
  }
}

Note that there is an _id field that has been added automatically to your document. _id is the "primary key" field. If your document does not specify one, the driver will add one automatically.

If you specify your own _id field, it must be unique to the collection. See the example here:

<?php
$connection = new MongoClient();
$db = $connection->database;

$db->foo->insert(array("_id" => 1));
// this will throw an exception
$db->foo->insert(array("_id" => 1));

// this is fine, as it is a different collection
$db->bar->insert(array("_id" => 1));
?>

By default the driver will ensure the server has acknowledged the write before returning. You can optionally turn this behaviour off by passing array("w" => 0) as the second argument. This means that the driver should not wait for the database to acknowledge the write and would not throw the duplicate _id exception.

See Also

MongoCollection::findOne() for more information about finding data.

MongoId goes into more detail on unique ids.

The writes section covers writes in more depth, and the Write Concerns chapter goes into details of the various Write Concern options.


Adding Multiple Documents

In order to do more interesting things with queries, let's add multiple simple documents to the collection. These documents will just be of the form array( "i" => value ); and we can do this fairly efficiently in a loop:

<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;

for ( $i = 0; $i < 100; $i++ )
{
    $collection->insert( array( 'i' => $i, "field{$i}" => $i * 2 ) );
}
?>

Notice that we can insert arrays with different keys into the same collection. This aspect is what we mean when we say that MongoDB is "schema-free". In the example above each document has an i field, but also a field name in the form of field + $i.


Counting Documents in A Collection

Now that we've inserted 101 documents (the 100 we did in the loop, plus the first one), we can check to see if we have them all using the MongoCollection::count() method.

<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;

echo $collection->count();
?>
and it should print 101.


Using a Cursor to Get All of the Documents

In order to get all the documents in the collection, we will use MongoCollection::find(). The find() method returns a MongoCursor object which allows us to iterate over the set of documents that matched our query. So to query all of the documents and print them out:

<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;

$cursor = $collection->find();
foreach ( $cursor as $id => $value )
{
    echo "$id: ";
    var_dump( $value );
}
?>
and that should print all 101 documents in the collection. $id is the _id field of a document (cast to a string) and $value is the document itself.

See Also

The API documentation on MongoCollection::find() contains more information about finding data.


Setting Criteria for a Query

We can create a query to pass to the MongoCollection::find() method to get a subset of the documents in our collection. For example, if we wanted to find the document for which the value of the "i" field is 71, we would do the following:

<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;

$query = array( 'i' => 71 );
$cursor = $collection->find( $query );

while ( $cursor->hasNext() )
{
    var_dump( $cursor->getNext() );
}
?>

The above example will output:

array(2) {
  ["_id"]=>
  object(MongoId)#6 (0) {
  }
  ["i"]=>
  int(71)
  ["_ns"]=>
  "testCollection"
}


Getting A Set of Documents With a Query

We can use the query to get a set of documents from our collection. For example, if we wanted to get all documents where "i" > 50, we could write:

<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;

$query = array( "i" => array( '$gt' => 50 ) ); //note the single quotes around '$gt'
$cursor = $collection->find( $query );

while ( $cursor->hasNext() )
{
    var_dump( $cursor->getNext() );
}
?>

which should print the documents where "i" > 50. We could also get a range, say 20 < i <= 30:

<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;

$query = array( 'i' => array( '$gt' => 20, "\$lte" => 30 ) );
$cursor = $collection->find( $query );

while ( $cursor->hasNext() )
{
    var_dump( $cursor->getNext() );
}
?>

Remember to always escape the $-symbol or use single quotes. Otherwise PHP will interpret it to be the variable $gt.


Creating An Index

MongoDB supports indexes, and they are very easy to add on a collection. To create an index, you specify the field name and direction: ascending (1) or descending (-1). The following creates an ascending index on the "i" field:

<?php
$connection = new MongoClient();
$collection = $connection->database->collectionName;

$collection->ensureIndex( array( "i" => 1 ) );  // create index on "i"
$collection->ensureIndex( array( "i" => -1, "j" => 1 ) );  // index on "i" descending, "j" ascending
?>

Indexing is critical for good read performance as your data grows. If you are not familiar with indexing, check out the MongoCollection::ensureIndex() documentation and the core » MongoDB indexing documentation.


Read Preferences

MongoDB 2.2 and version 1.3.0 of the driver add support for » read preferences, which allow control over how queries are directed to mongod instances in a replica set environment. Read preferences may be specified on either a per-connection, per-database, or per-collection basis. Preferences defined at a higher level will be inherited by default (e.g. MongoCollection will inherit read preferences defined on the corresponding MongoDB instance).

Read preferences are specified with a combination of modes and tag sets. Modes determine how mongod instances are prioritized, while » tag sets specify criteria for eligible mongod instances. Mongod instances are only eligible if they are within a 15ms difference in ping time from the nearest mongod instance.

Read Preference Modes

Warning

All read preference modes except MongoClient::RP_PRIMARY may return stale data as secondaries replicate operations from the primary with some delay. Ensure that your application can tolerate stale data if you choose to use a mode other than MongoClient::RP_PRIMARY.

  • MongoClient::RP_PRIMARY

    All read operations use only the current replica set primary. This is the default. If the primary is unavailable, read operations will produce an exception.

    This mode is incompatible with use of tag sets. Specifying a tag set with MongoClient::RP_PRIMARY will result in an exception.

  • MongoClient::RP_PRIMARY_PREFERRED

    In most situations, operations read from the primary member of the set. However, if the primary is unavailable, as is the case during failover situations, operations read from secondary members.

    When the read preference includes a tag set, the client reads first from the primary, if available, and then from secondaries that match the specified tags. If no secondaries have matching tags, the read operation will produce an exception.

    Warning

    Version 2.2 of mongos added full support for read preferences. When connecting to older mongos instances, MongoClient::RP_PRIMARY_PREFERRED will send queries to secondaries.

  • MongoClient::RP_SECONDARY

    Operations read only from the secondary members of the set. If no secondaries are available, read operations will produce an exception.

    Most sets have at least one secondary, but there are situations where there may be no available secondary. For example, a set with a primary, a secondary, and an arbiter may not have any secondaries if a member is in recovering state or unavailable.

    When the read preference includes a tag set, the client attempts to find secondary members that match the specified tag set and directs reads to a random secondary from among the nearest group. If no secondaries have matching tags, the read operation will produce an exception.

  • MongoClient::RP_SECONDARY_PREFERRED

    In most situations, operations read from secondary members, but in situations where the set consists of a single primary with no other members, the read operation will use the set's primary.

    When the read preference includes a tag set, the client attempts to find a secondary member that matches the specified tag set and directs reads to a random secondary from among the nearest group. If no secondaries have matching tags, the read operation will produce an exception.

  • MongoClient::RP_NEAREST

    The driver reads from a random member of the set that has a ping time that is less than 15ms slower than the member with the lowest ping time. Reads in the MongoClient::RP_NEAREST mode do not consider the member's type and may read from both primaries and secondaries.

    Set this mode to minimize the effect of network latency on read operations without preference for current or stale data.

    If you specify a tag set, the client attempts to find a member that matches the specified tag set and directs reads to a random node from among the nearest group.

    Note:

    All operations read from the nearest member of the replica set that matches the specified read preference mode. The MongoClient::RP_NEAREST mode prefers low latency reads over a member's primary or secondary status.

Tag Sets

» Tag sets allow you to specify criteria so that your application can target read operations to specific members, based on custom parameters. Tag sets make it possible to ensure that read operations target members in a particular data center or target mongod instances designated for a particular class of operations, such as reporting or analytics.

You can specify tag sets with the following read preference modes:

  • MongoClient::RP_PRIMARY_PREFERRED

  • MongoClient::RP_SECONDARY

  • MongoClient::RP_SECONDARY_PREFERRED

  • MongoClient::RP_NEAREST

You cannot specify tag sets with the MongoClient::RP_PRIMARY read preference mode. Tags apply only when selecting a secondary member of a set, except for the when in the nearest mode.

Specifying Read Preferences

Read preferences may be specified in either the connection URI provided to MongoClient::__construct(), which uses a query string syntax, or via setter methods on the core classes, which use an array syntax for tag sets.

When specifying read preference modes in a query string, the tag sets for the readPreferenceTags value should be a comma-delimited sequence of colon-delimited key/value pairs.

Note:

Each tag set defined in the query string will use the readPreferenceTags name. Unlike how PHP might handle URL query strings, successive values for readPreferenceTags will not overwrite each other. The driver will collect tag sets in the order they appear in the query string.

Warning

If the driver cannot find a matching tag set the read will fail! It is your responsibility of providing suitable fallback, such as an empty readPreferenceTags value to fallback to "no tag set preference".

Example #1 Connection URI read preferences with query string syntax

<?php
// Prefer the nearest server with no tag preference
$uri  = 'mongodb://rs1.example.com,rs2.example.com/';
$uri .= '?readPreference=nearest';
$m = new MongoClient($uri, array('replicaSet' => 'rs'));

// Pick the nearest server in the "east" data center
$uri  = 'mongodb://rs1.example.com,rs2.example.com/';
$uri .= '?readPreference=nearest';
$uri .= '&readPreferenceTags=dc:east';
$m = new MongoClient($uri, array('replicaSet' => 'rs'));

// Prefer the nearest server in the "east" data center also used for reporting,
// but fall back to a server in the "west" data center
$uri  = 'mongodb://rs1.example.com,rs2.example.com/';
$uri .= '?readPreference=nearest';
$uri .= '&readPreferenceTags=dc:east,use:reporting';
$uri .= '&readPreferenceTags=dc:west';
$m = new MongoClient($uri, array('replicaSet' => 'rs'));

// Prefer the nearest server in the "east" data center, then a server in the
// "west" data center, and finally fall back to no tag set preference
$uri  = 'mongodb://rs1.example.com,rs2.example.com/';
$uri .= '?readPreference=nearest';
$uri .= '&readPreferenceTags=dc:east';
$uri .= '&readPreferenceTags=dc:west';
$uri .= '&readPreferenceTags=';
$m = new MongoClient($uri, array('replicaSet' => 'rs'));
?>

Example #2 Setting read preferences with array syntax for tag sets

<?php

$m = new MongoClient('mongodb://rs1.example.com,rs2.example.com', array(
    'replicaSet' => 'rs',
));

// Prefer the nearest server with no tag preference
$m->setReadPreference(MongoClient::RP_NEAREST, array());

// Pick the nearest server in the "east" data center
$m->setReadPreference(MongoClient::RP_NEAREST, array(
    array('dc' => 'east'),
));

// Prefer the nearest server in the "east" data center also used for reporting,
// but fall back to a server in the "west" data center
$m->setReadPreference(MongoClient::RP_NEAREST, array(
    array('dc' => 'east', 'use' => 'reporting'),
    array('dc' => 'west'),
));

// Prefer the nearest server in the "east" data center, then a server in the
// "west" data center, and finally fall back to no tag set preference
$m->setReadPreference(MongoClient::RP_NEAREST, array(
    array('dc' => 'east'),
    array('dc' => 'west'),
    array(),
));
?>


Write Concerns

MongoDB provides several different ways of selecting how durable a write to the database should be. These ways are called Write Concerns and span everything from completely ignoring all errors, to specifically targetting which servers are required to confirm the write before returning the operation.

When a write (such as with MongoCollection::insert(), MongoCollection::update(), and MongoCollection::remove()) is given a Write Concern option ("w") the driver will send the query to MongoDB and piggy back a getLastError command (GLE) with the Write Concern option at the same time. The server only returns when the Write Concern condition is verified to be fulfilled, or the query times out (controlled with the "wtimeout" option, 10000 milliseconds is the default).

Warning

Even though a getLastError command times out the data will most likely have been written to the primary server and will be replicated to all the secondaries once they have caught up.

The typical reasons for a timeout to happen is if you specify a Write Concern which requires confirmation from more servers then you currently have available.

When using acknowledged writes and the replica set has failed over, the driver will automatically disconnect from the primary, throw an exception, and attempt to find a new primary on the next operation (your application must decide whether or not to retry the operation on the new primary).

When using unacknowledged writes (w=0) and the replica set has failed over, there will be no way for the driver to know about the change so it will continue and silently fail to write.

The default Write Concern for the MongoClient is 1: acknowledge write operations.

Available Write Concerns
Write Concern | Meaning | Description
w=0 | Unacknowledged | A write will not be followed up with a GLE call, and therefore not checked ("fire and forget")
w=1 | Acknowledged | The write will be acknowledged by the server (the primary on replica set configuration)
w=N | Replica Set Acknowledged | The write will be acknowledged by the primary server, and replicated to N-1 secondaries.
w=majority | Majority Acknowledged | The write will be acknowledged by the majority of the replica set (including the primary). This is a special reserved string.
w=<tag set> | Replica Set Tag Set Acknowledged | The write will be acknowledged by members of the entire tag set
j=true | Journaled | The write will be acknowledged by primary and the journal flushed to disk

Using WriteConcerns

Each of the methods that causes writes (MongoCollection::insert(), MongoCollection::update(), MongoCollection::remove(), and MongoCollection::batchInsert()) allow an optional argument to send a set of options to the MongoDB server. With this option array you can set the WriteConcern as the following example illustrates:

Example #1 Passing a WriteConcern to a write operation

<?php
// Setting w=0 for insert:
$collection->insert($someDoc, array("w" => 0));

// Setting w=majority for update:
$collection->update($someDoc, $someUpdates, array("w" => "majority"));

// Setting w=5 and j=true for remove:
$collection->update($someDoc, array("w" => 5, "j" => true));

// Setting w="AllDCs" for batchInsert:
$collection->update(array($someDoc1, $someDoc2), array("w" => "AllDCs"));
?>

Besides setting WriteConcerns per operation as an option argument, it is also possible to set a default WriteConcern in different ways.

The first way is through the connection string. The connection string accepts the journal, w, and wTimeoutMS options:

Example #2 Connection string WriteConcerns

<?php
$m = new MongoClient("mongodb://localhost/?journal=true&w=majority&wTimeoutMS=20000");
?>

Since driver version 1.5 it is also possible to call MongoDB::setWriteConcern() and MongoCollection::setWriteConcern() to set a default WriteConcern for all operations created from that specific MongoDB or MongoCollection object:

Example #3 MongoDB::setWriteConcern and MongoCollection::setWriteConcern

<?php
$m = new MongoClient("mongodb://localhost/");
$d = $m->demoDb;
$c = $d->demoCollection;

// Set w=3 on the database object with a timeout of 25000ms
$d->setWriteConcern(3, 25000);

// Set w=majority on the collection object without changing the timeout
$c->setWriteConcern("majority");
?>

Unacknowledged Writes

By not requiring the server to acknowledge writes the writes can be performed extremely quickly, but you don't know whether or not they actually succeeded. Writes can fail for a number of reasons: if there are network problems, if a database server goes down, or if the write was simply invalid (e.g., writing to a system collection; or duplicate key errors).

While developing, you should always use acknowledged writes (to protect against inadvertent mistakes, such as syntax errors, invalid operators, duplicate key errors and so on). In production, unacknowledged writes can be used for "unimportant" data. Unimportant data varies on application, but it's generally automatically (instead of user generated) data, such as click tracking or GPS locations, where you can get thousands of records per second.

It is strongly recommended that you do an acknowledged write at the end of series of unacknowledged writes. Doing so will not incur in a too large performance penalty, but still allow you to catch any errors that may have occurred.

Example #4 Unacknowledged WriteConcern, followed with Acknowledged Write

<?php
$collection->insert($someDoc, array("w" => 0));
$collection->update($criteria, $newObj, array("w" => 0));
$collection->insert($somethingElse, array("w" => 0));
try {
    $collection->remove($something, array("w" => 1));
} catch(MongoCursorException $e) {
    /* Handle the exception.. */
    /* Here we should issue find() queries on the IDs generated for
    $somethingElse and $someDoc to verify they got written to the database and
    attempt to figureout where in the chain something happened. */
}
?>

If the last write throws an exception, you know that there's a problem with your database.

Acknowledged Writes

These type of write operations will make sure that the database has accepted the write operation before returning success. If the write failed, it will throw a MongoCursorException with an explanation of the failure. The MongoClient default behaviour is to acknowledge the write (w=1).

It is possible to specify how many members of an replica set have to acknowledge the write (i.e. have it replicated) before the write is deemed acknowledged and the operation returns.

Example #5 Acknowledged Writes

<?php
// Force acknowledgement from the primary only
$collection->insert($doc, array("w" => 1));

// Force acknowledgement from the primary, and one other member of the
// replica set
$collection->insert($doc, array("w" => 2));

// Force acknowledgement from the primary, and six other members of the
// replica set (you probably never should do this):
$collection->insert($doc, array("w" => 7));
?>

Keep in mind to select your Write Concern carefully. If you have a replica set with 5 members, and you select Write Concern of 4 you will risk the write blocking forever when one member of the replica set goes down for maintenance or a temporary network outage happens.

Warning

Passing in a string value for Write Concern has a specific meaning (Replica Set Tag Set Acknowledged). Please be careful of NOT using string values for numbers (i.e. array("w" => "1")) as it will be treated as a tag set name.

Majority Acknowledged Writes

Using the special majority Write Concern option is the recommended way for writes that are required to survive the apocalypse, as it will ensure the majority of your replica set will have the write and will therefore be guaranteed to survive all usual suspect outage scenarios.

Example #6 Majority Acknowledged Write

<?php
$collection->insert($someDoc, array("w" => "majority"));
?>

Journaled Writes

When connecting to a replica set the default Write Concern is only to have the primary server acknowledge the write. There is however a 100ms window until the write gets journaled and flushed to disk. It is possible to force the write to be journaled before acknowledging the write by setting the j option:

Example #7 Acknowledged and Journaled Write

Forcing journal flush

<?php
$options = array(
    "w" => 1,
    "j" => true,
);
try {
    $collection->insert($document, $options);
} catch(MongoCursorException $e) {
    /* handle the exception */
}
?>

See Also

  • » MongoDB WriteConcern docs

Changelog

Version | Description
1.3.0 | MongoClient was introduced and defaults to acknowledged writes. The deprecated Mongo defaults to unacknowledged writes.
1.3.0 | The "safe" write option has been deprecated and is not available with the new MongoClient class. Use the "w" option instead.


SQL to Mongo Mapping Chart

This is a PHP-specific version of the » SQL to Mongo mapping chart in the main docs.

SQL Statement | Mongo Query Language Statement
CREATE TABLE USERS (a Number, b Number) | Implicit or use MongoDB::createCollection().
INSERT INTO USERS VALUES(1,1) | $db->users->insert(array("a" => 1, "b" => 1));
SELECT a,b FROM users | $db->users->find(array(), array("a" => 1, "b" => 1));
SELECT * FROM users WHERE age=33 | $db->users->find(array("age" => 33));
SELECT a,b FROM users WHERE age=33 | $db->users->find(array("age" => 33), array("a" => 1, "b" => 1));
SELECT a,b FROM users WHERE age=33 ORDER BY name | $db->users->find(array("age" => 33), array("a" => 1, "b" => 1))->sort(array("name" => 1));
SELECT * FROM users WHERE age>33 | $db->users->find(array("age" => array('$gt' => 33)));
SELECT * FROM users WHERE age<33 | $db->users->find(array("age" => array('$lt' => 33)));
SELECT * FROM users WHERE name LIKE "%Joe%" | $db->users->find(array("name" => new MongoRegex("/Joe/")));
SELECT * FROM users WHERE name LIKE "Joe%" | $db->users->find(array("name" => new MongoRegex("/^Joe/")));
SELECT * FROM users WHERE age>33 AND age<=40 | $db->users->find(array("age" => array('$gt' => 33, '$lte' => 40)));
SELECT * FROM users ORDER BY name DESC | $db->users->find()->sort(array("name" => -1));
CREATE INDEX myindexname ON users(name) | $db->users->ensureIndex(array("name" => 1));
CREATE INDEX myindexname ON users(name,ts DESC) | $db->users->ensureIndex(array("name" => 1, "ts" => -1));
SELECT * FROM users WHERE a=1 and b='q' | $db->users->find(array("a" => 1, "b" => "q"));
SELECT * FROM users LIMIT 20, 10 | $db->users->find()->limit(10)->skip(20);
SELECT * FROM users WHERE a=1 or b=2 | $db->users->find(array('$or' => array(array("a" => 1), array("b" => 2))));
SELECT * FROM users LIMIT 1 | $db->users->find()->limit(1);
EXPLAIN SELECT * FROM users WHERE z=3 | $db->users->find(array("z" => 3))->explain()
SELECT DISTINCT last_name FROM users | $db->command(array("distinct" => "users", "key" => "last_name"));
SELECT COUNT(*y) FROM users | $db->users->count();
SELECT COUNT(*y) FROM users where AGE > 30 | $db->users->find(array("age" => array('$gt' => 30)))->count();
SELECT COUNT(AGE) from users | $db->users->find(array("age" => array('$exists' => true)))->count();
UPDATE users SET a=1 WHERE b='q' | $db->users->update(array("b" => "q"), array('$set' => array("a" => 1)));
UPDATE users SET a=a+2 WHERE b='q' | $db->users->update(array("b" => "q"), array('$inc' => array("a" => 2)));
DELETE FROM users WHERE z="abc" | $db->users->remove(array("z" => "abc"));


Connecting

Table of Contents

  • Connecting over SSL
  • Authentication
  • Replica Sets
  • Sharding
  • Domain Socket Support
  • Persistent Connections (version 1.3.0+)
  • Connection Pooling (version 1.2.0-1.2.12 *only*)
  • Manually Persistent Connections (version up to 1.1.4 *only*)

Connecting to MongoDB can be as easy as new MongoClient, but there are many additional options and configurations. The documentation for MongoClient::__construct() covers all of the API options, but this page gives some more details and advice for practical use cases.


Connecting over SSL

The driver supports connecting to » MongoDB over SSL and can optionally use SSL Stream Context options to provide more details, such as verifying certificates against specific certificate chain, or authenticate to » MongoDB using X509 certificates.

Example #1 Connect to MongoDB Instance with SSL Encryption

<?php
$mc = new MongoClient("mongodb://server1", array("ssl" => true));
?>

Example #2 Connect to MongoDB Instance with SSL Encryption, verifying it is who we think it is

<?php
$SSL_DIR = "/vagrant/certs";
$SSL_FILE = "CA_Root_Certificate.pem";

$ctx = stream_context_create(array(
    "ssl" => array(
        /* Certificate Authority the remote server certificate must be signed by */
        "cafile"            => $SSL_DIR . "/" . $SSL_FILE,

        /* Disable self signed certificates */
        "allow_self_signed" => false,

        /* Verify the peer certificate against our provided Certificate Authority root certificate */
        "verify_peer"       => true, /* Default to false pre PHP 5.6 */

        /* Verify the peer name (e.g. hostname validation) */
        /* Will use the hostname used to connec to the node */
        "verify_peer_name"  => true,

        /* Verify the server certificate has not expired */
        "verify_expiry"     => true, /* Only available in the MongoDB PHP Driver */
    ),
);

$mc = new MongoClient(
    "mongodb://server1",
    array("ssl" => true),
    array("context" => $ctx)
);
?>

Note:

The "verify_peer_name" is new in PHP 5.6.0. The MongoDB driver as of 1.6.5 however has backported this feature into the driver itself, so it works with PHP 5.3 and 5.4 too

Example #3 Connect to MongoDB Instance that Requires Client Certificates

<?php
$SSL_DIR  = "/vagrant/certs";
$SSL_FILE = "CA_Root_Certificate.pem";

$MYCERT   = "/vagrant/certs/ca-signed-client.pem";

$ctx = stream_context_create(array(
    "ssl" => array(
        "local_cert"        => $MYCERT,
        /* If the certificate we are providing was passphrase encoded, we need to set it here */
        "passphrase"        => "My Passphrase for the local_cert",

        /* Optionally verify the server is who he says he is */
        "cafile"            => $SSL_DIR . "/" . $SSL_FILE,
        "allow_self_signed" => false,
        "verify_peer"       => true,
        "verify_peer_name"  => true,
        "verify_expiry"     => true,
    ),
));

$mc = new MongoClient(
    "mongodb://server1/?ssl=true",
    array(),
    array("context" => $ctx)
);
?>

Example #4 Authenticating with X.509 certificates

The username is the certificate subject from the X509, which can be extracted like this:

openssl x509 -in /vagrant/certs/ca-signed-client.pem -inform PEM -subject -nameopt RFC2253
<?php
$ctx = stream_context_create( array(
    "ssl" => array(
        "local_cert" => "/vagrant/certs/ca-signed-client.pem",
    )
) );

$mc = new MongoClient(
    'mongodb://username@server1/?authSource=$external&authMechanism=MONGODB-X509&ssl=true',
    array(),
    array("context" => $ctx)
);
?>

Where username is the certificate subject.

Changelog

Version | Description
1.5.0 | Added support for X509 authentication.
1.4.0 | Added support for connecting to SSL enabled MongoDB.


Authentication

If MongoDB is started with the --auth or --keyFile options, you must authenticate before you can do any operations with the driver. You may authenticate a connection by specifying the username and password in either the connection URI or the "username" and "password" options for MongoClient::__construct().

Example #1 Authenticating against the "admin" database

<?php
// Specifying the username and password in the connection URI (preferred)
$m = new MongoClient("mongodb://${username}:${password}@localhost");

// Specifying the username and password via the options array (alternative)
$m = new MongoClient("mongodb://localhost", array("username" => $username, "password" => $password));
?>

By default, the driver will authenticate against the admin database. You may authenticate against a different database by specifying it in either the connection URI or the "db" option for MongoClient::__construct().

Example #2 Authenticating against normal databases

<?php
// Specifying the authentication database in the connection URI (preferred)
$m = new MongoClient("mongodb://${username}:${password}@localhost/myDatabase");

// Specifying the authentication database via the options array (alternative)
$m = new MongoClient("mongodb://${username}:${password}@localhost", array("db" => "myDatabase"));
?>

If your connection is dropped, the driver will automatically attempt to reconnect and reauthenticate you.


Replica Sets

To connect to a replica set, specify one or more members of the set and use the "replicaSet" option. Multiple servers may be delimited by a comma.

Example #1 ReplicaSet seed list

<?php
// Using multiple servers as the seed list (prefered)
$m = new MongoClient("mongodb://rs1.example.com:27017,rs2.example.com:27017/?replicaSet=myReplSetName");

// Using one server as the seed list
$m = new MongoClient("mongodb://rs1.example.com:27017", array("replicaSet" => "myReplSetName"));

// Using multiple servers as the seed list
$m = new MongoClient("mongodb://rs1.example.com:27017,rs2.example.com:27017", array("replicaSet" => "myReplSetName"));
?>

The PHP driver will query the database server(s) listed to determine the primary. So long as it can connect to at least one host listed and find a primary, the connection will succeed. If it cannot make a connection to any servers listed or cannot find a primary, a MongoConnectionException will be thrown.

Tip

You should always provide a seed list with more than one member of the ReplicaSet. For highest availability you should seed with at least one server from each of your datacenters.

Warning

The host names that you specify in the seed list must match the host names in the replica set configuration. This is because the driver only uses the host names in the replica set configuration to create the hash for its persistent connections.

For example, if an IP address is used in the seed list and the replica set is configured with host names, the driver will discard any seed list connection(s) that differ from the canonical host names reported by the replica set. Effectively, these non-canonical seed list connections will be recreated on each request, greatly reducing the benefit of using persistent connections.

Warning

The driver does not support connecting to different replica sets with the same name. This extends beyond one script so make sure to have separate names for each of your replica sets. That also means that you can not do this:

Example #2 Wrong replica set name duplication

<?php
$m = new MongoClient("mongodb://devserver1,devserver2,devserver3/?replicaSet=repset");
$m = new MongoClient("mongodb://prodserver1,prodserver2,prodserver3/?replicaSet=repset");
?>

Instead, you need to have two different names for your replica sets:

Example #3 Correct use of two replica set names

<?php
$m = new MongoClient("mongodb://devserver1,devserver2,devserver3/?replicaSet=devset");
$m = new MongoClient("mongodb://prodserver1,prodserver2,prodserver3/?replicaSet=prodset");
?>

If the primary becomes unavailable, an election will take place and a secondary will be promoted to the role of primary (unless a majority vote cannot be established). During this time (» 20-60 seconds), the connection will not be able to perform any write operations and attempts to do so will result in an exception. Connections to secondaries will still be able to perform reads.

Note:

The default Read Preference is to only read from the primary. During the election process there is no primary, and all read will therefore fail.

It is recommended to use MongoClient::RP_PRIMARY_PREFERRED Read Preference for applications that require high availability for reads, as reads will only be executed on the secondaries when there simply isn't a primary available.

Once a primary is elected, attempting to perform a read or write will allow the driver to detect the new primary. The driver will make this its primary database connection and continue operating normally.

The health and state of a secondary is checked every 5 seconds (configurable with mongo.ping_interval) or when the next operation occurs after 5 seconds. It will also recheck the configuration when the driver has a problem reaching a server.

Replica set failovers are checked every 60 seconds (configurable with mongo.is_master_interval), and whenever a write operation fails when using acknowledged writes.

Caution

Secondaries may be behind the primary in operations, so your application must be able to handle out-of-date data when using Read Preferences other then MongoClient::RP_PRIMARY.

For more information on replica sets, see the » core documentation.

See Also

  • Read Preferences
  • Write Concerns

Changelog

Version | Description
1.0.9 | Added support for connecting to ReplicaSet and automatic failover.


Sharding

To connect to a shard cluster, specify the address of one or more mongos instances in the connection string. Multiple servers may be delimited by a comma.

<?php
// Using one server as the seed list
$m = new MongoClient("mongodb://mongos1.example.com:27017");

// Using multiple servers as the seed list
$m = new MongoClient("mongodb://mongos1.example.com:27017,mongos2.example.com:27017");
?>

Regardless of whether each shard is a stand-alone mongod server or a full replica set, the driver's connection process is the same. All database communication will be routed through mongos.

For more information on sharding with MongoDB, see the » sharding documentation.


Domain Socket Support

MongoDB has built-in support for connecting via Unix Domain Sockets and will open the socket on startup. By default, the socket is located in /tmp/mongodb-<port>.sock.

To connect to the socket file, specify the path in your MongoDB connection string:

<?php
$m = new MongoClient("mongodb:///tmp/mongo-27017.sock");
?>

If you would like to authenticate against a database (as described above) with a socket file, you must specify a port of 0 so that the connection string parser can detect the end of the socket path. Alternatively, you can use the constructor options.

<?php
$m = new MongoClient("mongodb://username:password@/tmp/mongo-27017.sock:0/foo");
?>

Changelog

Version | Description
1.0.9 | Added support for Unix Domain Sockets.


Persistent Connections (version 1.3.0+)

All versions of the driver since 1.3.0 utilize persistent connections to minimize the number of connections made to each database server. These connections are saved by the PHP worker process and may be reused between multiple requests.

Before connecting to a database server, the driver will create a hash for the connection based on its host, port, replica set name (if any), any authentication credentials (e.g. username, password, database), and the process ID. If a connection already exists for that hash, it will be used in lieu of creating a new connection associated with that hash. MongoClient::getConnections() may be used to retrieve info about each persistent connection. Consider the following program:

<?php

$m1 = new MongoClient('mongodb://localhost');
$m2 = new MongoClient('mongodb://localhost');
$m3 = new MongoClient('mongodb://user:pw@localhost');
$m4 = new MongoClient('mongodb://127.0.0.1');
$m5 = new MongoClient('mongodb://rs1.local:30017,rs2.local:30018/?replicaSet=rs');
$m6 = new MongoClient('mongodb://sharding.local:40017');

foreach (MongoClient::getConnections() as $conn) {
    echo $conn['hash'], "\n";
}

?>

The above example will output something similar to:

localhost:27017;-;X;15487
localhost:27017;-;admin/user/c56c…8bbc;15487
127.0.0.1:27017;-;X;15487
rs1.local:30017;rs;X;15487
rs2.local:30018;rs;X;15487
sharding.local:40017;-;X;15487

In this example $m1 and $m2 have the same hash and share a persistent connection. Connections for each other MongoClient instance hash to unique values and use their own sockets. Note that "localhost" and "127.0.0.1" do not share the same hash; DNS resolution is not taken into account.


Connection Pooling (version 1.2.0-1.2.12 *only*)

Note:

This section is no longer relevant as of the 1.3.0 release of the driver and only serves as a historical information on how the pooling used to work.

The latest versions of the driver have no concept of pooling anymore and will maintain only one connection per process, for each connection type (ReplicaSet/standalone/mongos), for each credentials combination.

Creating connections is one of the most heavyweight things that the driver does. It can take hundreds of milliseconds to set up a connection correctly, even on a fast network. Thus, the driver tries to minimize the number of new connections created by reusing connections from a pool.

When a user creates a new instance of MongoClient, all necessary connections will be taken from their pools (replica sets may require multiple connections, one for each member of the set). When the MongoClient instance goes out of scope, the connections will be returned to the pool. When the PHP process exits, all connections in the pools will be closed.

"Why do I have so many open connections?"

Connection pools can generate a large number of connections. This is expected and, using a little arithmetic, you can figure out how many connections will be created. There are three factors in determining the total number of connections:

  • connections_per_pool

    Each connection pool will create, by default, an unlimited number of connections. One might assume that this is a problem: if it can create an unlimited number of connections, couldn't it create thousands and the server would run out of file descriptors? In practice, this is unlikely, as unused connections are returned to the pool to be used later, so future connections will use the same connection instead of creating a new one. Unless you create thousands of connections at once without letting any go out of scope, the number of connections open should stay at a reasonable number.

    You can see how many connections you have in a pool using the MongoPool::info() function. Add up the "in use" and "in pool" fields for a given server. That is the total number of connections for that pool.

  • pools_per_process

    Each MongoDB server address you're connecting to gets its own connection pool. For example, if your local hostname is "example.net", connecting to "example.net:27017", "localhost:27017", and "/tmp/mongodb-27017.sock" will create three connection pools. You can see how many connection pools you have open using MongoPool::info().

  • processes

    Each PHP process has a separate set of pools. PHP-FPM and Apache generally create between 6 and a couple of dozen PHP worker children. Check your settings to see what the max number of PHP processes is that can be spawned.

    If you are using PHP-FPM, estimating the number of connections can be tricky because it will spawn more PHP-FPM workers under heavy load. To be on the safe side, look at the max_children parameter or add up spare_servers + start_servers (choose whichever number is higher). That will indicate how many PHP processes (i.e. sets of pools) you should plan for.

The three variables above can be multiplied together to give the max number of connections expected: connections_per_pool * pools_per_process * processes. Note that connections_per_pool can be different for different pools, so connections_per_pool should be the max.

For example, suppose we're getting 30 connections per pool, 10 pools per PHP process, and 128 PHP processes. Then we can expect 38400 connections from this machine. Thus, we should set this machine's file descriptor limit to be high enough to handle all of these connections or it may run out of file descriptors.

See MongoPool for more information on connection pooling.


Manually Persistent Connections (version up to 1.1.4 *only*)

Note:

This section is not relevant for 1.2.0+. In 1.2.0+, connections are always persistent and managed automatically by the driver. If you are using a 1.2.x release (but not 1.3.x or later), see MongoPool for more information on pooling.

Creating new connection to the database is very slow. To minimize the number of connections that you need to make, you can use persistent connections. A persistent connection is saved by PHP, so you can use the same connection for multiple requests.

For example, this simple program connects to the database 1000 times:

<?php

for ($i=0; $i<1000; $i++) {
  $m = new MongoClient();
}

?>

It takes approximately 18 seconds to execute. If we change it to use a persistent connection:

<?php

for ($i=0; $i<1000; $i++) {
  $m = new MongoClient("localhost:27017", array("persist" => "x"));
}

?>

...it takes less than .02 seconds to execute, as it only makes one database connection.

Persistent connections need an identifier string (which is "x" in the above example) to uniquely identify them. For a persistent connection to be used, the hostname, port, persist string, and authentication credentials (username, password and database, if given) must match an existing persistent connection. Otherwise, a new connection will be created with this identifying information.

Persistent connections are highly recommended and should always be used in production unless there is a compelling reason not to. Most of the reasons that they are not recommended for relational databases are irrelevant to MongoDB.


Stream Context Options

The PHP MongoDB extension provides Stream Context Support using the mongodb context.

A stream context must be created with stream_context_create() and passed to the MongoClient::__construct() before the actual connection to MongoDB is made. It is not possible to apply a stream context to already created streams.

Additional context options and parameters, such as ssl and notification parameters, are also supported.

The MongoDB context options provide a rich interface to log network traffic between the driver and the MongoDB servers. This interface can be used to provide query logging, profiler, debuggers, or anything that would need to inspect the underlaying commands and protocol options.

See Also

  • SSL context options
  • Socket context options
  • Context parameters

Table of Contents

  • log_cmd_delete — Callback When Deleting Documents
  • log_cmd_insert — Callback When Inserting Documents
  • log_cmd_update — Callback When Updating Documents
  • log_getmore — Callback When Retrieving Next Cursor Batch
  • log_killcursor — Callback When Executing KILLCURSOR operations
  • log_reply — Callback When Reading the MongoDB reply
  • log_write_batch — Callback When Writing Batches


Callback When Deleting Documents

  • « Stream Context Options
  • log_cmd_insert »
  • PHP Manual
  • Stream Context Options
  • Callback When Deleting Documents

log_cmd_delete

(PECL mongo >= 1.5.0)

log_cmd_delete — Callback When Deleting Documents

Description

log_cmd_delete ( array $server , array $writeOptions , array $deleteOptions , array $protocolOptions )

A callable function, used by the log_cmd_delete context option, when deleteing a document

Note:

This is not a real function, only a prototype of how the function should be.

Parameters

server

An array containing the basic information about the server that was picked.

key | value
hash | server hash, example: localhost:27017;-;X;56052
type | Node type (primary/secondary/mongos/arbiter): 2
max_bson_size | The maximum BSON Size over the wire this node accepts: 16777216
max_message_size | The maximum Message Size over the wire this node accepts: 48000000
request_id | The request identifier for this message: 42

writeOptions

key | value
ordered | boolean, if the operation (in case of batch operation) must be executed sequentually (ordered=true)
writeConcern | An array of writeConcern options (see below)
writeConcern array values
key | value
fsync | boolean, force flushing to disk before returning
j | boolean, force journal write before returning
wtimeout | integer, milliseconds, maximum time the primary is allowed to wait to verify replication
w | integer=server count, or string=replication-tag

deleteOptions

key | value
limit | integer, 1 or 0. If 0, delete all matching documents.
q | Array, the search criteria

protocolOptions

key | value
message_length | The total size (in bytes) of the encoded message being sent over the wire
request_id | The request identifier for this message: 42
namespace | The MongoDB namespace used for the protocol message dbname.collectionname

Changelog

Version | Description
1.5.0 | Only available when connected to MongoDB 2.6.0+


Callback When Inserting Documents

  • « log_cmd_delete
  • log_cmd_update »
  • PHP Manual
  • Stream Context Options
  • Callback When Inserting Documents

log_cmd_insert

(PECL mongo >= 1.5.0)

log_cmd_insert — Callback When Inserting Documents

Description

log_cmd_insert ( array $server , array $document , array $writeOptions , array $protocolOptions )

A callable function, used by the log_cmd_insert context option, when inserting a document

Note:

This is not a real function, only a prototype of how the function should be.

Parameters

server

An array containing the basic information about the server that was picked.

key | value
hash | server hash, example: localhost:27017;-;X;56052
type | Node type (primary/secondary/mongos/arbiter): 2
max_bson_size | The maximum BSON Size over the wire this node accepts: 16777216
max_message_size | The maximum Message Size over the wire this node accepts: 48000000
request_id | The request identifier for this message: 42

document

The document that has been prepared to be inserted

writeOptions

key | value
ordered | boolean, if the operation (in case of batch operation) must be executed sequentually (ordered=true)
writeConcern | An array of writeConcern options (see below)
writeConcern array values
key | value
fsync | boolean, force flushing to disk before returning
j | boolean, force journal write before returning
wtimeout | integer, milliseconds, maximum time the primary is allowed to wait to verify replication
w | integer=server count, or string=replication-tag

protocolOptions

key | value
message_length | The total size (in bytes) of the encoded message being sent over the wire
request_id | The request identifier for this message: 42
namespace | The MongoDB namespace used for the protocol message dbname.collectionname

Changelog

Version | Description
1.5.0 | Only available when connected to MongoDB 2.6.0+


Callback When Updating Documents

  • « log_cmd_insert
  • log_getmore »
  • PHP Manual
  • Stream Context Options
  • Callback When Updating Documents

log_cmd_update

(PECL mongo >= 1.5.0)

log_cmd_update — Callback When Updating Documents

Description

log_cmd_update ( array $server , array $writeOptions , array $updateOptions , array $protocolOptions )

A callable function, used by the log_cmd_update context option, when updateing a document

Note:

This is not a real function, only a prototype of how the function should be.

Parameters

server

An array containing the basic information about the server that was picked.

key | value
hash | server hash, example: localhost:27017;-;X;56052
type | Node type (primary/secondary/mongos/arbiter): 2
max_bson_size | The maximum BSON Size over the wire this node accepts: 16777216
max_message_size | The maximum Message Size over the wire this node accepts: 48000000
request_id | The request identifier for this message: 42

writeOptions

key | value
ordered | boolean, if the operation (in case of batch operation) must be executed sequentually (ordered=true)
writeConcern | An array of writeConcern options (see below)
writeConcern array values
key | value
fsync | boolean, force flushing to disk before returning
j | boolean, force journal write before returning
wtimeout | integer, milliseconds, maximum time the primary is allowed to wait to verify replication
w | integer=server count, or string=replication-tag

updateOptions

key | value
multi | Boolean, true if this update is allowed to update all matched criteria
upsert | Boolean, true if the document should be created if criteria does not match
q | Array, the search criteria
u | Array, the new object/modifications

protocolOptions

key | value
message_length | The total size (in bytes) of the encoded message being sent over the wire
request_id | The request identifier for this message: 42
namespace | The MongoDB namespace used for the protocol message dbname.collectionname

Changelog

Version | Description
1.5.0 | Only available when connected to MongoDB 2.6.0+


Callback When Retrieving Next Cursor Batch

  • « log_cmd_update
  • log_killcursor »
  • PHP Manual
  • Stream Context Options
  • Callback When Retrieving Next Cursor Batch

log_getmore

(PECL mongo >= 1.5.0)

log_getmore — Callback When Retrieving Next Cursor Batch

Description

log_getmore ( array $server , array $info )

A callable function, used by the log_getmore context option, when executing a GET_MORE operation.

Note:

This is not a real function, only a prototype of how the function should be.

Parameters

server

An array containing the basic information about the server that was picked.

key | value
hash | server hash, example: localhost:27017;-;X;56052
type | Node type (primary/secondary/mongos/arbiter): 2
max_bson_size | The maximum BSON Size over the wire this node accepts: 16777216
max_message_size | The maximum Message Size over the wire this node accepts: 48000000
request_id | The request identifier for this message: 42

info

key | value
request_id | integer, the driver request identifier
cursor_id | integer, the cursor identifier being used to fetch more data
batch_size | integer, maximum number of documents being requested


Callback When Executing KILLCURSOR operations

  • « log_getmore
  • log_reply »
  • PHP Manual
  • Stream Context Options
  • Callback When Executing KILLCURSOR operations

log_killcursor

(PECL mongo >= 1.5.0)

log_killcursor — Callback When Executing KILLCURSOR operations

Description

log_killcursor ( array $server , array $info )

A callable function, used by the log_killcursor context option, when reading a killcursor from MongoDB.

Note:

This is not a real function, only a prototype of how the function should be.

Parameters

server

An array containing the basic information about the server that was picked.

key | value
hash | server hash, example: localhost:27017;-;X;56052
type | Node type (primary/secondary/mongos/arbiter): 2
max_bson_size | The maximum BSON Size over the wire this node accepts: 16777216
max_message_size | The maximum Message Size over the wire this node accepts: 48000000
request_id | The request identifier for this message: 42

info

key | value
cursor_id | integer, the cursor identifier to kill


Callback When Reading the MongoDB reply

  • « log_killcursor
  • log_write_batch »
  • PHP Manual
  • Stream Context Options
  • Callback When Reading the MongoDB reply

log_reply

(PECL mongo >= 1.5.0)

log_reply — Callback When Reading the MongoDB reply

Description

log_reply ( array $server , array $messageHeaders , array $operationHeaders )

A callable function, used by the log_reply context option, when reading a reply from MongoDB.

Note:

This is not a real function, only a prototype of how the function should be.

Parameters

server

An array containing the basic information about the server that was picked.

key | value
hash | server hash, example: localhost:27017;-;X;56052
type | Node type (primary/secondary/mongos/arbiter): 2
max_bson_size | The maximum BSON Size over the wire this node accepts: 16777216
max_message_size | The maximum Message Size over the wire this node accepts: 48000000
request_id | The request identifier for this message: 42

messageHeaders

key | value
length | integer, bytes, message reply length
request_id | integer, the server request identifier
response_id | integer, the driver request identifier this message is a response of
opcode | integer, the opcode id

operationHeaders

key | value
flags | integer, bitmask of protocol flags
cursor_id | integer, ID of the cursor created on the server (0 if none created, or its been exhausted)
start | The starting offset of this cursor
returned | integer, how many documents are returned in this trip

See Also

  • The » OP_REPLY definition in the Wire Protocol


Callback When Writing Batches

  • « log_reply
  • Writes »
  • PHP Manual
  • Stream Context Options
  • Callback When Writing Batches

log_write_batch

(PECL mongo >= 1.5.0)

log_write_batch — Callback When Writing Batches

Description

log_write_batch ( array $server , array $writeOptions , array $batch , array $protocolOptions )

A callable function, used by the log_write_batch context option, when executing a batch operation.

Note:

This is not a real function, only a prototype of how the function should be.

Parameters

server

An array containing the basic information about the server that was picked.

key | value
hash | server hash, example: localhost:27017;-;X;56052
type | Node type (primary/secondary/mongos/arbiter): 2
max_bson_size | The maximum BSON Size over the wire this node accepts: 16777216
max_message_size | The maximum Message Size over the wire this node accepts: 48000000
request_id | The request identifier for this message: 42

writeOptions

key | value
ordered | boolean, if the operation (in case of batch operation) must be executed sequentually (ordered=true)
writeConcern | An array of writeConcern options (see below)
writeConcern array values
key | value
fsync | boolean, force flushing to disk before returning
j | boolean, force journal write before returning
wtimeout | integer, milliseconds, maximum time the primary is allowed to wait to verify replication
w | integer=server count, or string=replication-tag

batch

Array, the actual batch operation.

protocolOptions

key | value
message_length | The total size (in bytes) of the encoded message being sent over the wire
request_id | The request identifier for this message: 42
namespace | The MongoDB namespace used for the protocol message dbname.collectionname

Changelog

Version | Description
1.5.0 | Only available when connected to MongoDB 2.6.0+


Writes

Updating Nested Objects

Suppose we wish to change the name of a comment's author in this document:

{
    "_id" : ObjectId("4b06c282edb87a281e09dad9"),
    "content" : "this is a blog post.",
    "comments" :
    [
        {
            "author" : "Mike",
            "comment" : "I think that blah blah blah...",
        },
        {
            "author" : "John",
            "comment" : "I disagree."
        }
    ]
}
In order to change an inner field, we use $set (so that all of the other fields are not removed!) with the index of comment to change:
<?php

$blog->update($criteria, array('$set' => array("comments.1" => array("author" => "Jim"))));

?>

The Positional Operator

The positional operator $ is useful for updating objects that are in arrays. In the example above, for instance, suppose that we did not know the index of the comment that we needed to change, merely that we needed to change "John" to "Jim". We can use $ to do so.

<?php

$blog->update(
    array('comments.author' => 'John'),
    array('$set' => array('comments.$.author' => 'Jim')));

?>


Querying

Distributing queries to secondaries

All queries (reads and writes) are only sent to the primary member of a replica set by default. This is however easily configurable by using the Read Preferences which allow you to set some generic read preferences (such as allowing secondary reads of the nearest server), and also provide ways to specifically target a server in a specific country, datacenter, or even hardware, by the use of replica set tag sets.

Read preferences can be configured at every level of the driver:

  • As a query parameter or option to MongoClient::__construct()
  • Specifically by calling MongoClient::setReadPreference()
  • At the database level with MongoDB::setReadPreference()
  • At the collection level with MongoCollection::setReadPreference()
  • At the cursor level with MongoCursor::setReadPreference() or MongoCommandCursor::setReadPreference()
Each class inherits its read preference setting from the "parent" context.

Example #1 Inheriting read preferences from the database level down to the cursor

<?php
$db->setReadPreference(MongoClient::RP_SECONDARY_PREFERRED);
$c = $db->myCollection;

$cursor = $c->find();
?>

In this example, the query will be executed against a secondary. The collection inherits MongoClient::RP_SECONDARY_PREFERRED from the database and the cursor inherits it from the collection.

How secondaries are chosen

Each instance of MongoClient chooses its own secondary using the available secondary with the lowest ping time. So, if we had a PHP client in Europe and one in Australia and we had one secondary in each of these data centers, we could do:

<?php
$options = array("replicaSet" => "setName", "readPreference" => MongoClient::RP_SECONDARY_PREFERRED);

// on the Australian client
$m = new MongoClient("mongodb://primary,australianhost.secondary,europeanhost.secondary", $options);
$cursor = $m->foo->bar->find();
$cursor->getNext();
echo "Reading from: ", $cursor->info()["server"], "\n";

// on the European client
$m = new MongoClient("mongodb://primary,australianhost.secondary,europeanhost.secondary", $options);
$cursor = $m->foo->bar->find();
$cursor->getNext();
echo "Reading from: ", $cursor->info()["server"], "\n";
?>

The above example will output something similar to:

Reading from: australianHost
Reading from: europeanHost

Note that we have to do a query before a secondary is chosen: secondaries are chosen lazily by the driver, and for each query separately.

You can see what the driver thinks is the current status of the set members by running MongoClient::getHosts() or MongoClient::getConnections().

If no secondary is readable, the driver will send reads to the primary as we specified MongoClient::RP_SECONDARY_PREFERRED which will fallback to execute a query on a primary if no secondaries are available. A server is considered readable if its state is 2 (SECONDARY) and its health is 1. You can check this with MongoClient::getHosts() and MongoClient::getConnections().

Random notes

Writes are always sent to the primary—and by default all reads are sent to the primary too.

Querying by _id

Every object inserted is automatically assigned a unique _id field, which is often a useful field to use in queries. This works similarly to "get last insert ID" functionality, except that the _id is chosen by the client.

Suppose that we wish to find the document we just inserted. Inserting adds an _id field to the document, so we can query by that:

<?php
$person = array("name" => "joe");

$people->insert($person);

// now $joe has an _id field
$joe = $people->findOne(array("_id" => $person['_id']));
?>

Unless the user has specified otherwise, the _id field is a MongoId. The most common mistake is attempting to use a string to match a MongoId. Keep in mind that these are two different datatypes, and will not match each other in the same way that the string "array()" is not the same as an empty array. For example:

<?php
$person = array("name" => "joe");

$people->insert($person);

// convert the _id to a string
$pid = $person['_id'] . "";

// FAILS - $pid is a string, not a MongoId
$joe = $people->findOne(array("_id" => $pid));
?>

Arrays

Arrays are special in a couple ways. First, there are two types that MongoDB uses: "normal" arrays and associative arrays. Associative arrays can have any mix of key types and values. "Normal" arrays are defined as arrays with ascending numeric indexes starting at 0 and increasing by one for each element. These are, typically, just your usual PHP array.

For instance, if you want to save a list of awards in a document, you could say:

<?php

$collection->save(array("awards" => array("gold", "silver", "bronze")));

?>

Queries can reach into arrays to search for elements. Suppose that we wish to find all documents with an array element of a given value. For example, documents with a "gold" award, such as:

{ "_id" : ObjectId("4b06c282edb87a281e09dad9"), "awards" : ["gold", "silver", "bronze"]}

This can be done with a simple query, ignoring the fact that "awards" is an array:

<?php

  $cursor = $collection->find(array("awards" => "gold"));

?>

Suppose we are querying for a more complex object, if each element of the array were an object itself, such as:

{
     "_id" : ObjectId("4b06c282edb87a281e09dad9"),
     "awards" :
     [
        {
            "first place" : "gold"
        },
        {
            "second place" : "silver"
        },
        {
            "third place" :  "bronze"
        }
     ]
}

Still ignoring that this is an array, we can use dot notation to query the subobject:

<?php

$cursor = $collection->find(array("awards.first place" => "gold"));

?>

Notice that it doesn't matter that there is a space in the field name (although it may be best not to use spaces, just to make things more readable).

You can also use an array to query for a number of possible values. For instance, if we were looking for documents "gold" or "copper", we could do:

<?php

$cursor = $collection->find(array("awards" => array('$in' => array("gold", "copper"))));

?>

Changelog

Version | Description
1.3.0 | Introduced the Read Preferences framework to allow more fine grained control over secondary reads.
1.3.0 | Deprecated slaveOkay usage, the alternative is Read Preferences.
1.1.0 | Introduced the possiblity of routing reads to secondaries of replica set members using Mongo::setSlaveOkay()


Updates

Updates can be one of the most complicated operation available with MongoDB. They combine a query with an action, modifying documents that match the criteria. They are also extremely powerful, allowing you to change documents quickly and replace them altogether. They are done in-place (when possible) with little overhead.

Modifying vs. replacing documents

There are two types of updates you can use: modifying updates and replacing updates. Modifying updates contain $-operators and change fields in a document: they might increment counters, push new elements onto an array, or change the type of a field.

For example, a modifying update could add a new field to a document.

<?php
/** suppose documents look like:
 * {"username" : "...", "password" : "...", "email" : "..."}
 */
$coll->update(array("username" => "joe"), array('$set' => array("twitter" => "@joe4153")));

/** now the document will look like:
 * {"username" : "joe", "password" : "...", "email" : "...", "twitter" : "@joe4153"}
 */
?>

Replacing updates replace the entire matching document with a new document. They are generally not as efficient as using $-modifiers, but can be very usefully for complex operations or updates that can't be expressed in terms of $-operators.

For example, a replacing update can completely change the structure of a document.

<?php
/** suppose documents look like:
 * {"username" : "...", "password" : "...", "email" : "..."}
 */
$coll->update(array("username" => "joe"), array("userId" => 12345, "info" => array(
    "name" => "joe", "twitter" => "@joe4153", "email" => "..."), "likes" => array()));

/** now the document will look like:
 * {
 *     "userId" : 12345,
 *     "info" : {
 *         "name" : "joe",
 *         "twitter" : "@joe4153",
 *         "email" : "..."
 *     },
 *     "likes" : []
 * }
 */
?>

Updating Nested Objects

Suppose we wish to change the name of a comment's author in this document:

{
    "_id" : ObjectId("4b06c282edb87a281e09dad9"),
    "content" : "this is a blog post.",
    "comments" :
    [
        {
            "author" : "Mike",
            "comment" : "I think that blah blah blah...",
        },
        {
            "author" : "John",
            "comment" : "I disagree."
        }
    ]
}
In order to change an inner field, we use $set (so that all of the other fields are not removed!) with the index of comment to change:
<?php

$blog->update($criteria, array('$set' => array("comments.1" => array("author" => "Jim"))));

?>

The Positional Operator

The positional operator $ is useful for updating objects that are in arrays. In the example above, for instance, suppose that we did not know the index of the comment that we needed to change, merely that we needed to change "John" to "Jim". We can use $ to do so.

<?php

$blog->update(
    array("comments.author" => "John"),
    array('$set' => array('comments.$.author' => "Jim")));

?>


Security

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 does the query $collection->find(array("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 $collection->find(array("username" => array('$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 (cast them to strings, in this case).

Note that this type of attack can be used with any databases interation that locates a document, including updates, upserts, find-and-modifies, and removes.

Thanks to » Phil for pointing this out.

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 MongoCode, not interpolated into the JavaScript string. This can come up when using MongoDB::execute(), $where clauses, MapReduces, group-bys, and any other time you may pass JavaScript into the database.

Note:

MapReduce ignore the scope field of MongoCode, but there is a scope option on the command that can be used instead.

For example, suppose we have some JavaScript to greet a user in the database logs. We could do:

<?php

// don't do this!

$username = $_POST['username'];
$db->execute("print('Hello, $username!');");

?>

However, what if a malicious user passes in some JavaScript?

<?php

// don't do this!

// $username is set to "'); db.users.drop(); print('"
$db->execute("print('Hello, $username!');");

?>

Now MongoDB executes the JavaScript string "print('Hello, '); db.users.drop(); print('!');". This attack is easy to avoid: use scope to pass variables from PHP to JavaScript:

<?php

$scope = array("user" => $username);
$db->execute(new MongoCode("print('Hello, '+user+'!');", $scope));

?>

This adds a variable user to the JavaScript scope. Now if someone tries to send malicious code, MongoDB will harmlessly print Hello, '); db.dropDatabase(); print('!.

Using scope helps 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! For example, never use the JavaScript eval function on user input:

<?php

// don't do this!

// $jsShellInput is "db.users.drop();"
$scope = array("input" => $jsShellInput);
$db->execute(new MongoCode("eval(input);", $scope));

?>

Always use scope and never allow the database to execute user input as code.


Troubleshooting

If you're having trouble, there are lots of resources you can turn to.

  • IRC

    The official MongoDB IRC room is irc.freenode.net/#mongodb. This is the fastest way to get help.

  • Mailing List

    » MongoDB's mailing list is a good (and usually very fast) way to get answers to questions.

  • Bug Tracker

    Found a bug? Want a feature? Have a question? File it in the » PHP driver's bug tracker.

You can make the driver log all kinds of error messages as E_NOTICE level PHP error messages. Have a look at the MongoLog for an example.


Running the Driver's Tests

The PECL package does not come with the tests, but they are available at » Github.

.phpt Tests

.phpt tests are the standard way of testing PHP extensions. After compiling the MongoDB driver with "make" you can then issue "make test" to run the tests. These tests require MongoDB to be working, and hence, you need to configure the test suite itself.

There is more information on running the tests in the contributing guidelines on » GitHub.

Reporting Errors

Please report any failures or errors in the » bugtracker. There may be skipped tests, these are normal and can be ignored.

New tests are always welcome! Please feel free to contribute new tests of any type testing any functionality.


Core Classes

Table of Contents

  • MongoClient
  • MongoDB
  • MongoCollection
  • MongoCursor
  • MongoCursorInterface
  • MongoCommandCursor
Warning

This extension is deprecated. Instead, the MongoDB extension should be used.

The core classes are the most important part of the driver.


The MongoClient class

(PECL mongo >=1.3.0)

Warning

This extension that defines this class is deprecated. Instead, the MongoDB extension should be used. Alternatives to this class include:

  • MongoDB\Driver\Manager

Introduction

A connection manager for PHP and MongoDB.

This class is used to create and manage connections. A typical use is:

Example #1 MongoClient basic usage

<?php

$m = new MongoClient(); // connect
$db = $m->foo; // get the database named "foo"

?>

See MongoClient::__construct() and the section on connecting for more information about creating connections.

Class synopsis

MongoClient {
/* Constants */
const string VERSION ;
const string DEFAULT_HOST = "localhost" ;
const int DEFAULT_PORT = 27017 ;
const string RP_PRIMARY = "primary" ;
const string RP_PRIMARY_PREFERRED = "primaryPreferred" ;
const string RP_SECONDARY = "secondary" ;
const string RP_SECONDARY_PREFERRED = "secondaryPreferred" ;
const string RP_NEAREST = "nearest" ;
/* Properties */
public boolean $connected = FALSE ;
public string $status = NULL ;
protected string $server = NULL ;
protected boolean $persistent = NULL ;
/* Methods */
public __construct ([ string $server = "mongodb://localhost:27017" [, array $options = array("connect" => TRUE) [, array $driver_options ]]] )
public close ([ boolean|string $connection ] ) : bool
public connect ( void ) : bool
public dropDB ( mixed $db ) : array
public __get ( string $dbname ) : MongoDB
public static getConnections ( void ) : array
public getHosts ( void ) : array
public getReadPreference ( void ) : array
public getWriteConcern ( void ) : array
public killCursor ( string $server_hash , int|MongoInt64 $id ) : bool
public listDBs ( void ) : array
public selectCollection ( string $db , string $collection ) : MongoCollection
public selectDB ( string $name ) : MongoDB
public setReadPreference ( string $read_preference [, array $tags ] ) : bool
public setWriteConcern ( mixed $w [, int $wtimeout ] ) : bool
public __toString ( void ) : string
}

Predefined Constants

MongoClient Constants

MongoClient::VERSION
PHP driver version. May be suffixed with "dev", "+" or "-" if it is in-between versions.
MongoClient::DEFAULT_HOST
Host to connect to if no host is given.
MongoClient::DEFAULT_PORT
Port to connect to if no port is given.
MongoClient::RP_PRIMARY
Read preference for the primary replica set member.
MongoClient::RP_PRIMARY_PREFERRED
Read preference for preferring the primary replica set member.
MongoClient::RP_SECONDARY
Read preference for a secondary replica set member.
MongoClient::RP_SECONDARY_PREFERRED
Read preference for preferring a secondary replica set member.
MongoClient::RP_NEAREST
Read preference for the nearest replica set member.

Fields

connected

This property will be set to TRUE if we have a open connection to the database, FALSE otherwise. If the connection is to a replica set, this property will only be TRUE if the driver has a connection to a node matching the current read preference. This property does not take authentication into account.

This property is deprecated since version 1.5.0.

status

This property is no longer used and will be set to NULL In driver versions 1.1.x and earlier, this may be set to a string value (e.g. "recycled", "new") when persistent connections are used.

This property is deprecated since version 1.5.0.

See Also

  • Read Preferences
  • Write Concerns
  • Connecting
  • MongoDB core docs on » connecting

Table of Contents

  • MongoClient::close — Closes this connection
  • MongoClient::connect — Connects to a database server
  • MongoClient::__construct — Creates a new database connection object
  • MongoClient::dropDB — Drops a database [deprecated]
  • MongoClient::__get — Gets a database
  • MongoClient::getConnections — Return info about all open connections
  • MongoClient::getHosts — Updates status for all associated hosts
  • MongoClient::getReadPreference — Get the read preference for this connection
  • MongoClient::getWriteConcern — Get the write concern for this connection
  • MongoClient::killCursor — Kills a specific cursor on the server
  • MongoClient::listDBs — Lists all of the databases available
  • MongoClient::selectCollection — Gets a database collection
  • MongoClient::selectDB — Gets a database
  • MongoClient::setReadPreference — Set the read preference for this connection
  • MongoClient::setWriteConcern — Set the write concern for this connection
  • MongoClient::__toString — String representation of this connection


Closes this connection

  • « MongoClient
  • MongoClient::connect »
  • PHP Manual
  • MongoClient
  • Closes this connection

MongoClient::close

(PECL mongo >=1.3.0)

MongoClient::close — Closes this connection

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this method in the new extension.

Description

public MongoClient::close ([ boolean|string $connection ] ) : bool

The MongoClient::close() method forcefully closes a connection to the database, even if persistent connections are being used. You should never have to do this under normal circumstances.

Parameters

connection

If connection is not given, or FALSE then connection that would be selected for writes would be closed. In a single-node configuration, that is then the whole connection, but if you are connected to a replica set, close() will only close the connection to the primary server.

If connection is TRUE then all connections as known by the connection manager will be closed. This can include connections that are not referenced in the connection string used to create the object that you are calling close on.

If connection is a string argument, then it will only close the connection identified by this hash. Hashes are identifiers for a connection and can be obtained by calling MongoClient::getConnections().

Return Values

Returns if the connection was successfully closed.

Examples

Example #1 MongoClient::close() example

This example demonstrates how to selectively close all connections for secondaries only.

<?php
// Connect to a replicaset
$a = new MongoClient("mongodb://whisky:13000/?replicaset=seta");

$connections = $a->getConnections();

foreach ( $connections as $con )
{
    // Loop over all the connections, and when the type is "SECONDARY"
    // we close the connection
    if ( $con['connection']['connection_type_desc'] == "SECONDARY" )
    {
        echo "Closing '{$con['hash']}': ";
        $closed = $a->close( $con['hash'] );
        echo $closed ? "ok" : "failed", "\n";
    }
}
?>

The above example will output:

Closing 'whisky:13001;X;4948': ok

Changelog

Version | Description
1.3.0 | The connection parameter to this function was added in 1.3.0. Before that, only the write connection would be closed by this method.
1.2.0 | Before version 1.2.0 the driver would not use persistent connections by default, and all connections would be closed as soon as a MongoDB connection went out if scope. Since version 1.2.0 this is no longer the case and it is a bad idea to call close as you might end up overloading the server with connections under high load.

See Also

  • MongoClient::getConnections() - Return info about all open connections


Connects to a database server

  • « MongoClient::close
  • MongoClient::__construct »
  • PHP Manual
  • MongoClient
  • Connects to a database server

MongoClient::connect

(PECL mongo >=1.3.0)

MongoClient::connect — Connects to a database server

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this method in the new extension.

Description

public MongoClient::connect ( void ) : bool

Parameters

This function has no parameters.

Return Values

If the connection was successful.

Errors/Exceptions

Throws MongoConnectionException if it fails to connect to the database.


Creates a new database connection object

  • « MongoClient::connect
  • MongoClient::dropDB »
  • PHP Manual
  • MongoClient
  • Creates a new database connection object

MongoClient::__construct

(PECL mongo >=1.3.0)

MongoClient::__construct — Creates a new database connection object

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. Alternatives to this method include:

  • MongoDB\Driver\Manager::__construct()

Description

 public MongoClient::__construct
  ([ string $server = "mongodb://localhost:27017"
 [, array $options = array("connect" => TRUE)
 [, array $driver_options
]]] )

If no parameters are passed, this connects to "localhost:27017" (or whatever was specified in php.ini for mongo.default_host and mongo.default_port).

server should have the form:

mongodb://[username:password@]host1[:port1][,host2[:port2:],...]/db

The connection string always starts with mongodb://, to indicate it is a connection string in this form.

If username and password are specified, the constructor will attempt to authenticate the connection with the database before returning. Username and password are optional and must be followed by an @, if specified.

At least one host must be given (port optional, always defaulting to 27017) and as many hosts as desired may be connected to. Host names are comma-separated and the constructor will return successfully if it connected to at least one host. If it could not connect to any of the hosts, it will throw a MongoConnectionException. Please see the Replica Sets section for information on how to connect to Replica Sets.

If you specified a username and password, you may specify a database to authenticate with. If db is not specified, "admin" will be used.

An optional query string may be used to specify extra options. The same options are supported through the options array as well, and are therefore redescribed there. See the examples below on how to set those options.

One part of the options governs how the driver reads from secondary nodes in a replica set environment. Extra information on how these read preferences work is available as well through the read preferences documentation page.

Parameters

server

The server name.

options

An array of options for the connection. Currently available options include:

  • "authMechanism"

    Available mechanisms are:

    authMechanism | Description | Availability
    MONGODB-CR | Authenticate using Challenge Response mechanism. This is the default value. | All MongoDB versions
    MONGODB-X509 | Authenticates using X509 certificates | MongoDB 2.6. Only available when OpenSSL is enabled
    PLAIN | Authenticates using unencrypted plain username+password. Must be used over SSL connections. Generally used by MongoDB to login via 3rd party LDAP server | MongoDB Enterprise 2.4. The Driver must be compiled against CyrusSASL2
    GSSAPI | Authenticates via kerberos systems | MongoDB Enterprise 2.4. The Driver must be compiled against CyrusSASL2
    SCRAM-SHA-1 | Authenticates using SCRAM-SHA-1 | MongoDB 3.0.

  • "authSource"

    Should be set to the database name where the user is defined it.

  • "connect"

    If the constructor should connect before returning. Default is TRUE. When set to FALSE the driver will automatically connect to the server whenever it is necessary to do a query. Alternatively, you can run MongoClient::connect() manually.

    Warning

    This option is not supported through the connection string.

  • "connectTimeoutMS"

    How long a connection can take to be opened before timing out in milliseconds. Defaults to 60000 (60 seconds).

    If -1 is specified, no connection timeout will be applied and PHP will use default_socket_timeout.

  • "db"

    The database to authenticate against can be specified here, instead of including it in the host list. This overrides a database given in the host list.

  • "fsync"

    When "fsync" is set, all write operations will block until the database has flushed the changes to disk. This makes the write operations slower, but it guarantees that writes have succeeded and that the operations can be recovered in case of total system failure.

    If the MongoDB server has journaling enabled, this option is identical to "journal". If journaling is not enabled, this option ensures that write operations will be synced to database files on disk.

    Note: If journaling is enabled, users are strongly encouraged to use the "journal" option instead of "fsync". Do not use "fsync" and "journal" simultaneously, as that will result in an error.

  • "journal"

    When "journal" is set, all write operations will block until the database has flushed the changes to the journal on disk. This makes the write operations slower, but it guarantees that writes have succeeded and that the operations can be recovered in case of total system failure.

    Note: If this option is used and journaling is disabled, MongoDB 2.6+ will raise an error and the write will fail; older server versions will simply ignore the option.

  • "gssapiServiceName"

    Sets the » Kerberos service principal. Only applicable when authMechanism=GSSAPI. Defaults to "mongodb".

  • "password"

    The password can be specified here, instead of including it in the host list. This is especially useful if a password has a "@" in it. This overrides a password set in the host list.

  • "readPreference"

    Specifies the read preference type. Read preferences provide you with control from which secondaries data can be read from.

    Allowed values are: MongoClient::RP_PRIMARY,
MongoClient::RP_PRIMARY_PREFERRED,
MongoClient::RP_SECONDARY,
MongoClient::RP_SECONDARY_PREFERRED and
MongoClient::RP_NEAREST.

    See the documentation on read preferences for more information.

  • "readPreferenceTags"

    Specifies the read preference tags as an array of strings. Tags can be used in combination with the readPreference option to further control which secondaries data might be read from.

    See the documentation on read preferences for more information.

  • "replicaSet"

    The name of the replica set to connect to. If this is given, the primary will be automatically be determined. This means that the driver may end up connecting to a server that was not even listed. See the replica set example below for details.

  • "secondaryAcceptableLatencyMS"

    When reading from a secondary (using ReadPreferences), do not read from secondaries known to be more then secondaryAcceptableLatencyMS away from us. Defaults to 15

  • "socketTimeoutMS"

    How long a socket operation (read or write) can take before timing out in milliseconds. Defaults to 30000 (30 seconds).

    If -1 is specified, socket operations may block indefinitely. This option may also be set on a per-operation basis using MongoCursor::timeout() for queries or the "socketTimeoutMS" option for write methods.

    Note: This is a client-side timeout. If a write operation times out, there is no way to know if the server actually handled the write or not, as a MongoCursorTimeoutException will be thrown in lieu of returning a write result.

  • "ssl"

    A boolean to specify whether you want to enable SSL for the connections to MongoDB. Extra options such as certificates can be set with SSL context options.

  • "username"

    The username can be specified here, instead of including it in the host list. This is especially useful if a username has a ":" in it. This overrides a username set in the host list.

  • "w"

    The w option specifies the Write Concern for the driver, which determines how long the driver blocks when writing. The default value is 1.

    This option is applicable when connecting to both single servers and replica sets. A positive value controls how many nodes must acknowledge the write instruction before the driver continues. A value of 1 would require the single server or primary (in a replica set) to acknowledge the write operation. A value of 3 would cause the driver to block until the write has been applied to the primary as well as two secondary servers (in a replica set).

    A string value is used to control which tag sets are taken into account for write concerns. "majority" is special and ensures that the write operation has been applied to the majority (more than 50%) of the participating nodes.

  • "wTimeoutMS"

    This option specifies the time limit, in milliseconds, for write concern acknowledgement. It is only applicable for write operations where "w" is greater than 1, as the timeout pertains to replication. If the write concern is not satisfied within the time limit, a MongoCursorException will be thrown. A value of 0 may be specified to block indefinitely. The default value is 10000 (ten seconds).

The following options are deprecated and should no longer be used:

  • "slaveOkay"

    Deprecated. Please use the read preference options.

  • "timeout"

    Deprecated alias for "connectTimeoutMS".

  • "wTimeout"

    Deprecated alias for "wTimeoutMS".

driver_options

An array of options for the MongoDB driver. Options include setting connection context options for SSL or logging callbacks.

  • "context"

    The Stream Context to attach to all new connections. This allows you for example to configure SSL certificates and are described at SSL context options. See the Connecting over SSL tutorial.

Return Values

Returns a new database connection object.

Errors/Exceptions

Throws MongoConnectionException if it tries and fails to connect to the database for all hostnames given. It will also throw a MongoConnnectionException if an invalid username or password is given. See MongoConnectionException documentation for common exceptions and their causes.

Examples

Example #1 MongoClient::__construct() replica set example

This example shows how to connect the driver to a replica set. It assumes that there is a set of three servers: sf1.example.com, sf2.example.com, and ny1.example.com. The primary could be any one of these servers.

<?php

// pass a comma-separated list of server names to the constructor
// Note that we don't need to pass in all the members of the replicaset, the driver
// will derive the full list.
$m1 = new MongoClient("mongodb://sf2.example.com,ny1.example.com", array("replicaSet" => "myReplSet"));

?>

If the current primary fails, the driver will figure out which secondary server became the new primary and automatically start using that connection. Automatic failover will not work correctly if replicaSet is not specified.

At least one seed in the seed list must be up for the driver to connect to the replica set.

If you include seeds from two separate replica sets, behavior is undefined.

See the » core documentation on replica sets for more information.

Example #2 Connecting to a domain socket

In version 1.0.9+, you can use a UNIX domain socket to connect to an instance of MongoDB running locally. This should be slightly faster than using a network connection.

In version 1.5.0, the MongoDB server automatically opens a socket at /tmp/mongodb-<port>.sock. You can connect to this by specifying the path in your connection string:

<?php

// MongoDB server running locally on port 20000
$m = new MongoClient("mongodb:///tmp/mongodb-20000.sock");

?>

You can combine this with any other connections you'd like:

<?php

// try to connect to the domain socket, fall back to localhost connection
$m = new MongoClient("mongodb:///tmp/mongodb-27017.sock,localhost:27017");

?>

Example #3 MongoClient::__construct() authentication example

A user must exist in the admin database before attempting to use authentication. You can create one with the Mongo shell by running:

> use admin
switched to db admin
> db.addUser("testUser", "testPass");
{
        "_id" : ObjectId("4b21272fd9ab21611d19095c"),
        "user" : "testUser",
        "pwd" : "03b9b27e0abf1865e2f6fcbd9845dd59"
}
>

After creating a user with, in this case, username "testUser" and password "testPass", you can create an authenticated connection:

<?php

$m = new MongoClient("mongodb://testUser:testPass@localhost");

?>

Example #4 MongoClient::__construct() read preference example

<?php

// Prefer the nearest server in the "east" data center
$uri  = 'mongodb://rs1.example.com,rs2.example.com/';
$uri .= '?readPreference=nearest';
$uri .= '&readPreferenceTags=dc:east';
$m = new MongoClient($uri, array('replicaSet' => 'rs'));
?>

See the read preferences section of this manual for further information.

Example #5 MongoClient::__construct() options example

Options can be passed both through the query string in the connection string, or as an array passed as second argument to the constructor.

Here we set the journal option to true and readPreference to secondary preferred as default for all write operations:

<?php
$m = new MongoClient("mongodb://localhost/?journal=true&readPreference=secondary");
?>

And now we do the same, but as an options array:

<?php
$options = array(
    'journal' => true,
    'readPreference' => 'secondary',
);
$m = new MongoClient("mongodb://localhost/", $options);
?>

Example #6 MongoClient::__construct() read preference example

<?php

// Prefer the nearest server in the "east" data center
$uri  = 'mongodb://rs1.example.com,rs2.example.com/';
$uri .= '?readPreference=nearest';
$uri .= '&readPreferenceTags=dc:east';
$m = new MongoClient($uri, array('replicaSet' => 'rs'));
?>

See the read preferences section of this manual for further information.

Changelog

Version | Description
1.6.0

Added support for "SCRAM-SHA-1" in "authMechanism" option.

1.5.0

Added "authMechanism", "gssapiServiceName", and "secondaryAcceptableLatencyMS".

1.4.0

Added "ssl" option and support for connecting over SSL.

Added "wTimeoutMS" option, which replaces "wTimeout".

Emits E_DEPRECATED when "slaveOkay" or "timeout" is used.

1.5.0

Added "authSource".

1.3.4

Added "connectTimeoutMS" and "socketTimeoutMS" options.

1.3.0

Added "readPreference", "readPreferenceTags", "w", and "wTimeout" options.

1.2.0

Added "username" and "password" options.

Removed "persist" option, as all connections are now persistent. It can still be used, but it doesn't affect anything.

"persist"

If the connection should be persistent. If set, the connection will be persistent. The string representation of the value is used as an ID for the connection, so two instances of MongoClient that are initialized with array("persist" => "foobar") will share the same database connection, whereas an instance initialized with array("persist" => "barbaz") will use a different database connection.

The "replicaSet" option now takes a string, not a boolean.

1.0.9 | Added "replicaSet" option.
1.0.2

Changed constructor to take an array of options. Pre-1.0.2, the constructor took the following parameters:

server

The server name.

connect

Optional boolean parameter specifying if the constructor should connect to the database before returning. Defaults to TRUE.

persistent

If the connection should be persistent.

paired

If the connection should be paired.


Drops a database [deprecated]

  • « MongoClient::__construct
  • MongoClient::__get »
  • PHP Manual
  • MongoClient
  • Drops a database [deprecated]

MongoClient::dropDB

(PECL mongo >=1.3.0)

MongoClient::dropDB — Drops a database [deprecated]

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this method in the new extension, but there is an alternative in the PHP library:

  • » MongoDB\Client::dropDatabase()

Description

public MongoClient::dropDB ( mixed $db ) : array
Warning

Deprecated

Use MongoDB::drop() instead.

Parameters

db

The database to drop. Can be a MongoDB object or the name of the database.

Return Values

Returns the database response.


Gets a database

  • « MongoClient::dropDB
  • MongoClient::getConnections »
  • PHP Manual
  • MongoClient
  • Gets a database

MongoClient::__get

(PECL mongo >=1.3.0)

MongoClient::__get — Gets a database

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this method in the new extension, but there is an alternative in the PHP library:

  • » MongoDB\Client::__get()

Description

public MongoClient::__get ( string $dbname ) : MongoDB

This is the cleanest way of getting a database. If the database name has any special characters, MongoClient::selectDB() will need to be used; however, this should be sufficient for most cases.

<?php

$mongo = new MongoClient();

// the following two lines are equivalent
$db = $mongo->selectDB("foo");
$db = $mongo->foo;

?>

Parameters

dbname

The database name.

Return Values

Returns a new db object.

Errors/Exceptions

Throws a generic exception if the database name is invalid.


Return info about all open connections

  • « MongoClient::__get
  • MongoClient::getHosts »
  • PHP Manual
  • MongoClient
  • Return info about all open connections

MongoClient::getConnections

(PECL mongo >=1.3.0)

MongoClient::getConnections — Return info about all open connections

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this method in the new extension.

Description

public static MongoClient::getConnections ( void ) : array

Returns an array of all open connections, and information about each of the servers

Parameters

This function has no parameters.

Return Values

An array of open connections.

Examples

Example #1 MongoClient::getConnections() example

<?php
$m = new MongoClient;
var_dump($m->getConnections());
?>

The above example will output something similar to:

array(1) {
  [0]=>
  array(3) {
    ["hash"]=>
    string(26) "localhost:27017;-;X;56052"
    ["server"]=>
    array(3) {
      ["host"]=>
      string(10) "localhost"
      ["port"]=>
      int(27017)
      ["pid"]=>
      int(56052)
    }
    ["connection"]=>
    array(8) {
      ["last_ping"]=>
      int(1354076401)
      ["last_ismaster"]=>
      int(0)
      ["ping_ms"]=>
      int(0)
      ["connection_type"]=>
      int(1)
      ["connection_type_desc"]=>
      string(10) "STANDALONE"
      ["max_bson_size"]=>
      int(16777216)
      ["tag_count"]=>
      int(0)
      ["tags"]=>
      array(0) {
      }
    }
  }
}


Updates status for all associated hosts

  • « MongoClient::getConnections
  • MongoClient::getReadPreference »
  • PHP Manual
  • MongoClient
  • Updates status for all associated hosts

MongoClient::getHosts

(PECL mongo >=1.3.0)

MongoClient::getHosts — Updates status for all associated hosts

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. Alternatives to this method include:

  • MongoDB\Driver\Manager::getServers()

Description

public MongoClient::getHosts ( void ) : array

This method is only useful with a connection to a replica set. It returns the status of all of the hosts in the set. Without a replica set, it will just return an array with one element containing the host that you are connected to.

See the query section of this manual for information on distributing reads to secondaries.

Parameters

This function has no parameters.

Return Values

Returns an array of information about the hosts in the set. Includes each host's hostname, its health (1 is healthy), its state (1 is primary, 2 is secondary, 0 is anything else), the amount of time it took to ping the server, and when the last ping occurred. For example, on a three-member replica set, it might look something like:

array(3) {
  ["A:27017"]=>
  array(4) {
    ["host"]=>
    "A"
    ["port"]=>
    27017
    ["health"]=>
    int(1)
    ["state"]=>
    int(2)
    ["ping"]=>
    int(369)
    ["lastPing"]=>
    int(1309470644)
  }
  ["B:27017"]=>
  array(4) {
    ["host"]=>
    "B"
    ["port"]=>
    27017
    ["health"]=>
    int(1)
    ["state"]=>
    int(1)
    ["ping"]=>
    int(139)
    ["lastPing"]=>
    int(1309470644)
  }
  ["C:27017"]=>
  array(4) {
    ["host"]=>
    "C"
    ["port"]=>
    27017
    ["health"]=>
    int(1)
    ["state"]=>
    int(2)
    ["ping"]=>
    int(1012)
    ["lastPing"]=>
    int(1309470644)
  }
}

Changelog

Version | Description
1.2.10 | Support for non-replicasets was added. The returned array elements now also include the hostname and port.

See Also

  • MongoClient::getConnections() - Return info about all open connections


Get the read preference for this connection

  • « MongoClient::getHosts
  • MongoClient::getWriteConcern »
  • PHP Manual
  • MongoClient
  • Get the read preference for this connection

MongoClient::getReadPreference

(PECL mongo >=1.3.0)

MongoClient::getReadPreference — Get the read preference for this connection

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this method in the new extension.

Description

public MongoClient::getReadPreference ( void ) : array

Parameters

This function has no parameters.

Return Values

This function returns an array describing the read preference. The array contains the values type for the string read preference mode (corresponding to the MongoClient constants), and tagsets containing a list of all tag set criteria. If no tag sets were specified, tagsets will not be present in the array.

Changelog

Version | Description
1.3.3 | The return value has changed to be consistent with MongoClient::setReadPreference(). The type value was changed from a number to a string, type_string was removed, and tagsets now expresses tags as key/value pairs instead of colon-delimited strings.

Examples

Example #1 MongoClient::getReadPreference() return value example

<?php

$m = new MongoClient();
$m->setReadPreference(MongoClient::RP_SECONDARY, array(
    array('dc' => 'east', 'use' => 'reporting'),
    array('dc' => 'west'),
    array(),
));
var_dump($m->getReadPreference());
?>

The above example will output:

array(2) {
  ["type"]=>
  string(9) "secondary"
  ["tagsets"]=>
  array(3) {
    [0]=>
    array(2) {
      ["dc"]=>
      string(4) "east"
      ["use"]=>
      string(9) "reporting"
    }
    [1]=>
    array(1) {
      ["dc"]=>
      string(7) "west"
    }
    [2]=>
    array(0) {
    }
  }
}

See Also

  • The read preferences documentation.
  • MongoClient::setReadPreference() - Set the read preference for this connection


Get the write concern for this connection

  • « MongoClient::getReadPreference
  • MongoClient::killCursor »
  • PHP Manual
  • MongoClient
  • Get the write concern for this connection

MongoClient::getWriteConcern

(PECL mongo >=1.5.0)

MongoClient::getWriteConcern — Get the write concern for this connection

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this method in the new extension.

Description

public MongoClient::getWriteConcern ( void ) : array

Parameters

This function has no parameters.

Return Values

This function returns an array describing the write concern. The array contains the values w for an integer acknowledgement level or string mode, and wtimeout denoting the maximum number of milliseconds to wait for the server to satisfy the write concern.

Examples

Example #1 MongoClient::getWriteConcern() return value example

<?php

$mc = new MongoClient('mongodb://localhost:27017', array('wTimeoutMS' => 500));
var_dump($mc->getWriteConcern());

$mc->setWriteConcern(1, 1000);
var_dump($mc->getWriteConcern());
?>

The above example will output:

array(2) {
  ["w"]=>
  int(1)
  ["wtimeout"]=>
  int(500)
}
array(2) {
  ["w"]=>
  int(1)
  ["wtimeout"]=>
  int(1000)
}

See Also

  • The write concern documentation.
  • MongoClient::setWriteConcern() - Set the write concern for this connection


Kills a specific cursor on the server

  • « MongoClient::getWriteConcern
  • MongoClient::listDBs »
  • PHP Manual
  • MongoClient
  • Kills a specific cursor on the server

MongoClient::killCursor

(PECL mongo >=1.5.0)

MongoClient::killCursor — Kills a specific cursor on the server

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this method in the new extension.

Description

public MongoClient::killCursor ( string $server_hash , int|MongoInt64 $id ) : bool

In certain situations it might be needed to kill a cursor on the server. Usually cursors time out after 10 minutes of inactivity, but it is possible to create an immortal cursor with MongoCursor::immortal() that never times out. In order to be able to kill such an immortal cursor, you can call this method with the information supplied by MongoCursor::info().

Parameters

server_hash

The server hash that has the cursor. This can be obtained through MongoCursor::info().

id

The ID of the cursor to kill. You can either supply an int containing the 64 bit cursor ID, or an object of the MongoInt64 class. The latter is necessary on 32 bit platforms (and Windows).

Return Values

Returns TRUE if the method attempted to kill a cursor, and FALSE if there was something wrong with the arguments (such as a wrong server_hash). The return status does not reflect where the cursor was actually killed as the server does not provide that information.

Errors/Exceptions

This method displays a warning if the supplied server_hash does not match up with an existing connection. No attempt to kill a cursor is attempted in that case either.

Examples

Example #1 MongoClient::killCursor() example

This example shows how to connect, do a query, obtain the cursor information and then kill the cursor.

<?php
$m = new MongoClient();
$c = $m->testdb->collection;
$cursor = $c->find();
$result = $cursor->next();

// Now the cursor is valid, so we can get the hash and ID out:
$info = $cursor->info();

// Kill the cursor
MongoClient::killCursor( $info['server'], $info['id'] );
?>


Lists all of the databases available

  • « MongoClient::killCursor
  • MongoClient::selectCollection »
  • PHP Manual
  • MongoClient
  • Lists all of the databases available

MongoClient::listDBs

(PECL mongo >=1.3.0)

MongoClient::listDBs — Lists all of the databases available

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this method in the new extension, but there is an alternative in the PHP library:

  • » MongoDB\Client::listDatabases()

Description

public MongoClient::listDBs ( void ) : array

Parameters

This function has no parameters.

Return Values

Returns an associative array containing three fields. The first field is databases, which in turn contains an array. Each element of the array is an associative array corresponding to a database, giving th database's name, size, and if it's empty. The other two fields are totalSize (in bytes) and ok, which is 1 if this method ran successfully.

Examples

Example #1 MongoClient::listDBs() example

Example demonstrating how to use listDBs and the returned data structure.

<?php

$mongo = new MongoClient();
$dbs = $mongo->listDBs();
print_r($dbs);

?>

The above example will output something similar to:

Array
(
    [databases] => Array
        (
            [0] => Array
                (
                    [name] => doctrine
                    [sizeOnDisk] => 218103808
                    [empty] =>
                )
        )

    [totalSize] => 218103808
    [ok] => 1
)


Gets a database collection

  • « MongoClient::listDBs
  • MongoClient::selectDB »
  • PHP Manual
  • MongoClient
  • Gets a database collection

MongoClient::selectCollection

(PECL mongo >=1.3.0)

MongoClient::selectCollection — Gets a database collection

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this method in the new extension, but there is an alternative in the PHP library:

  • » MongoDB\Client::selectCollection()

Description

public MongoClient::selectCollection ( string $db , string $collection ) : MongoCollection

Parameters

db

The database name.

collection

The collection name.

Return Values

Returns a new collection object.

Errors/Exceptions

Throws Exception if the database or collection name is invalid.

Examples

Example #1 MongoClient::selectCollection() example

<?php
$m = new MongoClient();

$c1 = $m->selectCollection("foo", "bar.baz");
// which is equivalent to
$c2 = $m->selectDB("foo")->selectCollection("bar.baz");

// $c1 and $c2 now represent the same collection
?>


Gets a database

  • « MongoClient::selectCollection
  • MongoClient::setReadPreference »
  • PHP Manual
  • MongoClient
  • Gets a database

MongoClient::selectDB

(PECL mongo >=1.3.0)

MongoClient::selectDB — Gets a database

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this method in the new extension, but there is an alternative in the PHP library:

  • » MongoDB\Client::selectDatabase()

Description

public MongoClient::selectDB ( string $name ) : MongoDB

Parameters

name

The database name.

Return Values

Returns a new database object.

Errors/Exceptions

Throws Exception if the database name is invalid.


Set the read preference for this connection

  • « MongoClient::selectDB
  • MongoClient::setWriteConcern »
  • PHP Manual
  • MongoClient
  • Set the read preference for this connection

MongoClient::setReadPreference

(PECL mongo >=1.3.0)

MongoClient::setReadPreference — Set the read preference for this connection

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this method in the new extension.

Description

public MongoClient::setReadPreference ( string $read_preference [, array $tags ] ) : bool

Parameters

read_preference

The read preference mode: MongoClient::RP_PRIMARY, MongoClient::RP_PRIMARY_PREFERRED, MongoClient::RP_SECONDARY, MongoClient::RP_SECONDARY_PREFERRED, or MongoClient::RP_NEAREST.

tags

An array of zero or more tag sets, where each tag set is itself an array of criteria used to match tags on replica set members.

Return Values

Returns TRUE on success, or FALSE otherwise.

Errors/Exceptions

Emits E_WARNING if either parameter is invalid, or if one or more tag sets are provided with the MongoClient::RP_PRIMARY read preference mode.

Examples

Example #1 MongoClient::setReadPreference() tag set array syntax example

<?php

$m = new MongoClient();

// Prefer the nearest server in the "east" data center also used for reporting,
// but fall back to a server in the "west" data center
$m->setReadPreference(MongoClient::RP_NEAREST, array(
    array('dc' => 'east', 'use' => 'reporting'),
    array('dc' => 'west'),
));
?>

See Also

  • The read preferences documentation.
  • MongoClient::getReadPreference() - Get the read preference for this connection


Set the write concern for this connection

  • « MongoClient::setReadPreference
  • MongoClient::__toString »
  • PHP Manual
  • MongoClient
  • Set the write concern for this connection

MongoClient::setWriteConcern

(PECL mongo >=1.5.0)

MongoClient::setWriteConcern — Set the write concern for this connection

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this method in the new extension.

Description

public MongoClient::setWriteConcern ( mixed $w [, int $wtimeout ] ) : bool

Parameters

w

The write concern. This may be an integer denoting the number of servers required to acknowledge the write, or a string mode (e.g. "majority").

wtimeout

The maximum number of milliseconds to wait for the server to satisfy the write concern.

Return Values

Returns TRUE on success, or FALSE otherwise.

Errors/Exceptions

Emits E_WARNING if the w parameter is not an integer or string value.

Examples

Example #1 MongoClient::setWriteConcern() example

<?php

$mc = new MongoClient('mongodb://rs1.example.com,rs2.example.com');

// Require that the majority of servers in the replica set acknowledge writes
// within three seconds.
$mc->setWriteConcern('majority', 3000);
?>

See Also

  • The write concern documentation.
  • MongoClient::getWriteConcern() - Get the write concern for this connection


String representation of this connection

  • « MongoClient::setWriteConcern
  • MongoDB »
  • PHP Manual
  • MongoClient
  • String representation of this connection

MongoClient::__toString

(PECL mongo >=1.3.0)

MongoClient::__toString — String representation of this connection

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this method in the new extension.

Description

public MongoClient::__toString ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns hostname and port for this connection.


The MongoDB class

(PECL mongo >=0.9.0)

Introduction

Instances of this class are used to interact with a database. To get a database:

Example #1 Selecting a database

<?php

$m = new MongoClient(); // connect
$db = $m->selectDB("example");

?>
Database names can use almost any character in the ASCII range. However, they cannot contain " ", "." or be the empty string. The name "system" is also reserved.

A few unusual, but valid, database names: "null", "[x,y]", "3", "\"", "/".

Unlike collection names, database names may contain "$".

Class synopsis

MongoDB {
/* Constants */
const int PROFILING_OFF = 0 ;
const int PROFILING_SLOW = 1 ;
const int PROFILING_ON = 2 ;
/* Fields */
public integer $w = 1 ;
public integer $wtimeout = 10000 ;
/* Methods */
public authenticate ( string $username , string $password ) : array
public command ( array $command [, array $options = array() [, string &$hash ]] ) : array
public __construct ( MongoClient $conn , string $name )
public createCollection ( string $name [, array $options ] ) : MongoCollection
public createDBRef ( string $collection , mixed $document_or_id ) : array
public drop ( void ) : array
public dropCollection ( mixed $coll ) : array
public execute ( mixed $code [, array $args = array() ] ) : array
public forceError ( void ) : bool
public __get ( string $name ) : MongoCollection
public getCollectionInfo ([ array $options = array() ] ) : array
public getCollectionNames ([ array $options = array() ] ) : array
public getDBRef ( array $ref ) : array
public getGridFS ([ string $prefix = "fs" ] ) : MongoGridFS
public getProfilingLevel ( void ) : int
public getReadPreference ( void ) : array
public getSlaveOkay ( void ) : bool
public getWriteConcern ( void ) : array
public lastError ( void ) : array
public listCollections ([ array $options = array() ] ) : array
public prevError ( void ) : array
public repair ([ bool $preserve_cloned_files = FALSE [, bool $backup_original_files = FALSE ]] ) : array
public resetError ( void ) : array
public selectCollection ( string $name ) : MongoCollection
public setProfilingLevel ( int $level ) : int
public setReadPreference ( string $read_preference [, array $tags ] ) : bool
public setSlaveOkay ([ bool $ok = TRUE ] ) : bool
public setWriteConcern ( mixed $w [, int $wtimeout ] ) : bool
public __toString ( void ) : string
}

Predefined Constants

MongoDB Log Levels

MongoDB::PROFILING_OFF
Profiling is off.
MongoDB::PROFILING_SLOW
Profiling is on for slow operations (>100 ms).
MongoDB::PROFILING_ON
Profiling is on for all operations.

Fields

w
1

The number of servers to replicate a change to before returning success. Inherited by instances of MongoCollection derived from this. w functionality is only available in version 1.5.1+ of the MongoDB server and 1.0.8+ of the driver.

w is used whenever you need to adjust the acknowledgement level (MongoCollection::insert(), MongoCollection::update(), MongoCollection::remove(), MongoCollection::save(), and MongoCollection::ensureIndex() all support this option). With the default value (1), an acknowledged operation will return once the database server has the operation. If the server goes down before the operation has been replicated to a secondary, it is possible to lose the operation forever. Thus, you can specify w to be higher than one and guarantee that at least one secondary has the operation before it is considered successful.

For example, if w is 2, the primary and one secondary must have a record of the operation or the driver will throw a MongoCursorException. It is tempting to set w to the total number of secondaries + primary, but then if one secondary is down the operation will fail and an exception will be thrown, so usually w=2 is safest (primary and one secondary).

wtimeout
10000

The number of milliseconds to wait for MongoDB::$w replications to take place. Inherited by instances of MongoCollection derived from this. w functionality is only available in version 1.5.1+ of the MongoDB server and 1.0.8+ of the driver.

Unless wtimeout is set, the server waits forever for replicating to w servers to finish. The driver defaults to waiting for 10 seconds, you can change this value to alter its behavior.

See Also

MongoDB core docs on » databases.

Table of Contents

  • MongoDB::authenticate — Log in to this database
  • MongoDB::command — Execute a database command
  • MongoDB::__construct — Creates a new database
  • MongoDB::createCollection — Creates a collection
  • MongoDB::createDBRef — Creates a database reference
  • MongoDB::drop — Drops this database
  • MongoDB::dropCollection — Drops a collection [deprecated]
  • MongoDB::execute — Runs JavaScript code on the database server [deprecated]
  • MongoDB::forceError — Creates a database error
  • MongoDB::__get — Gets a collection
  • MongoDB::getCollectionInfo — Returns information about collections in this database
  • MongoDB::getCollectionNames — Gets an array of names for all collections in this database
  • MongoDB::getDBRef — Fetches the document pointed to by a database reference
  • MongoDB::getGridFS — Fetches toolkit for dealing with files stored in this database
  • MongoDB::getProfilingLevel — Gets this database's profiling level
  • MongoDB::getReadPreference — Get the read preference for this database
  • MongoDB::getSlaveOkay — Get slaveOkay setting for this database
  • MongoDB::getWriteConcern — Get the write concern for this database
  • MongoDB::lastError — Check if there was an error on the most recent db operation performed
  • MongoDB::listCollections — Gets an array of MongoCollection objects for all collections in this database
  • MongoDB::prevError — Checks for the last error thrown during a database operation
  • MongoDB::repair — Repairs and compacts this database
  • MongoDB::resetError — Clears any flagged errors on the database
  • MongoDB::selectCollection — Gets a collection
  • MongoDB::setProfilingLevel — Sets this database's profiling level
  • MongoDB::setReadPreference — Set the read preference for this database
  • MongoDB::setSlaveOkay — Change slaveOkay setting for this database
  • MongoDB::setWriteConcern — Set the write concern for this database
  • MongoDB::__toString — The name of this database


Log in to this database

  • « MongoDB
  • MongoDB::command »
  • PHP Manual
  • MongoDB
  • Log in to this database

MongoDB::authenticate

(PECL mongo >=1.0.1)

MongoDB::authenticate — Log in to this database

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this method in the new extension.

Instead, you need to provide credentials through the connection string.

Description

public MongoDB::authenticate ( string $username , string $password ) : array

This method causes its connection to be authenticated. If authentication is enabled for the database server (it's not, by default), you need to log in before the database will allow you to do anything.

In general, you should use the authenticate built into MongoClient::__construct() in preference to this method. If you authenticate on connection and the connection drops and reconnects during your session, you'll be reauthenticated. If you manually authenticated using this method and the connection drops, you'll have to call this method again once you're reconnected.

This method is identical to running:

<?php

$salted = "${username}:mongo:${password}";
$hash = md5($salted);

$nonce = $db->command(array("getnonce" => 1));

$saltedHash = md5($nonce["nonce"]."${username}${hash}");

$result = $db->command(array("authenticate" => 1,
    "user" => $username,
    "nonce" => $nonce["nonce"],
    "key" => $saltedHash
));

?>

Once a connection has been authenticated, it can only be un-authenticated by using the "logout" database command:

<?php

$db->command(array("logout" => 1));

?>

Parameters

username

The username.

password

The password (in plaintext).

Return Values

Returns database response. If the login was successful, it will return

<?php
array("ok" => 1);
?>
If something went wrong, it will return
<?php
array("ok" => 0, "errmsg" => "auth fails");
?>
("auth fails" could be another message, depending on database version and what when wrong).

See Also

MongoDB core docs on » authenticate.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used. Please pass in the authentication details to the constructor.


Execute a database command

  • « MongoDB::authenticate
  • MongoDB::__construct »
  • PHP Manual
  • MongoDB
  • Execute a database command

MongoDB::command

(PECL mongo >=0.9.2)

MongoDB::command — Execute a database command

Description

public MongoDB::command ( array $command [, array $options = array() [, string &$hash ]] ) : array

Almost everything that is not a CRUD operation can be done with a database command. Need to know the database version? There's a command for that. Need to do aggregation? There's a command for that. Need to turn up logging? You get the idea.

This method is identical to:

<?php

public function command($data) {
    return $this->selectCollection('$cmd')->findOne($data);
}

?>

Parameters

command

The query to send.

options

An array of options for the index creation. Currently available options include:

  • "socketTimeoutMS"

    This option specifies the time limit, in milliseconds, for socket communication. If the server does not respond within the timeout period, a MongoCursorTimeoutException will be thrown and there will be no way to determine if the server actually handled the write or not. A value of -1 may be specified to block indefinitely. The default value for MongoClient is 30000 (30 seconds).

The following options are deprecated and should no longer be used:

  • "timeout"

    Deprecated alias for "socketTimeoutMS".

hash

Set to the connection hash of the server that executed the command. When the command result is suitable for creating a MongoCommandCursor, the hash is intended to be passed to MongoCommandCursor::createFromDocument().

The hash will also correspond to a connection returned from MongoClient::getConnections().

Changelog

Version | Description
1.5.0 | Renamed the "timeout" option to "socketTimeoutMS". Emits E_DEPRECATED when "timeout" is used. Added hash by-reference parameter.
1.2.0 | Added options parameter with a single option: "timeout".

Return Values

Returns database response. Every database response is always maximum one document, which means that the result of a database command can never exceed 16MB. The resulting document's structure depends on the command, but most results will have the ok field to indicate success or failure and results containing an array of each of the resulting documents.

Examples

Example #1 MongoDB::command() "distinct" example

Finding all of the distinct values for a key.

<?php

$people = $db->people;

$people->insert(array("name" => "Joe", "age" => 4));
$people->insert(array("name" => "Sally", "age" => 22));
$people->insert(array("name" => "Dave", "age" => 22));
$people->insert(array("name" => "Molly", "age" => 87));

$ages = $db->command(array("distinct" => "people", "key" => "age"));

foreach ($ages['values'] as $age) {
    echo "$age\n";
}

?>

The above example will output something similar to:

4
22
87

Example #2 MongoDB::command() "distinct" example

Finding all of the distinct values for a key, where the value is larger than or equal to 18.

<?php

$people = $db->people;

$people->insert(array("name" => "Joe", "age" => 4));
$people->insert(array("name" => "Sally", "age" => 22));
$people->insert(array("name" => "Dave", "age" => 22));
$people->insert(array("name" => "Molly", "age" => 87));

$ages = $db->command(
    array(
        "distinct" => "people",
        "key" => "age",
        "query" => array("age" => array('$gte' => 18))
    )
);

foreach ($ages['values'] as $age) {
    echo "$age\n";
}

?>

The above example will output something similar to:

22
87

Example #3 MongoDB::command() MapReduce example

Get all users with at least on "sale" event, and how many times each of these users has had a sale.

<?php

// sample event document
$events->insert(array("user_id" => $id,
    "type" => $type,
    "time" => new MongoDate(),
    "desc" => $description));

// construct map and reduce functions
$map = new MongoCode("function() { emit(this.user_id,1); }");
$reduce = new MongoCode("function(k, vals) { ".
    "var sum = 0;".
    "for (var i in vals) {".
        "sum += vals[i];".
    "}".
    "return sum; }");

$sales = $db->command(array(
    "mapreduce" => "events",
    "map" => $map,
    "reduce" => $reduce,
    "query" => array("type" => "sale"),
    "out" => array("merge" => "eventCounts")));

$users = $db->selectCollection($sales['result'])->find();

foreach ($users as $user) {
    echo "{$user['_id']} had {$user['value']} sale(s).\n";
}

?>

The above example will output something similar to:

User 47cc67093475061e3d9536d2 had 3 sale(s).
User 49902cde5162504500b45c2c had 14 sale(s).
User 4af467e4fd543cce7b0ea8e2 had 1 sale(s).

Note: Using MongoCode

This example uses MongoCode, which can also take a scope argument. However, at the moment, MongoDB does not support using scopes in MapReduce. If you would like to use client-side variables in the MapReduce functions, you can add them to the global scope by using the optional scope field with the database command. See the » MapReduce documentation for more information.

Note: The out argument

Before 1.8.0, the out argument was optional. If you did not use it, MapReduce results would be written to a temporary collection, which would be deleted when your connection was closed. In 1.8.0+, the out argument is required. See the » MapReduce documentation for more information.

Example #4 MongoDB::command() "geoNear" example

This example shows how to use the geoNear command.

<?php
$m = new MongoClient();
$d = $m->demo;
$c = $d->poiConcat;

$r = $d->command(array(
    'geoNear' => "poiConcat",      // Search in the poiConcat collection
    'near' => array(-0.08, 51.48), // Search near 51.48°N, 0.08°E
    'spherical' => true,           // Enable spherical search
    'num' => 5,                    // Maximum 5 returned documents
));
print_r($r);
?>

See Also

  • MongoCollection::aggregate() - Perform an aggregation using the aggregation framework
  • MongoCollection::findAndModify() - Update a document and return it
  • MongoCollection::group() - Performs an operation similar to SQL's GROUP BY command

MongoDB core docs on » database commands.


Creates a new database

  • « MongoDB::command
  • MongoDB::createCollection »
  • PHP Manual
  • MongoDB
  • Creates a new database

MongoDB::__construct

(PECL mongo >=0.9.0)

MongoDB::__construct — Creates a new database

Description

public MongoDB::__construct ( MongoClient $conn , string $name )

This method is not meant to be called directly. The preferred way to create an instance of MongoDB is through MongoClient::__get() or MongoClient::selectDB().

If you're ignoring the previous paragraph and want to call it directly you can do so:

<?php

$m = new MongoClient();
$db = new MongoDB($m, 'mydbname');

?>

But don't. Isn't this much nicer:

<?php

$m = new MongoClient();
$db = $m->mydbname;

// or, if the name contains weird characters:

$db = $m->selectDB('my,db:name');

?>

Parameters

MongoClient conn

Database connection.

name

Database name.

Return Values

Returns the database.

Errors/Exceptions

Throws default exception if the database name is invalid.


Creates a collection

  • « MongoDB::__construct
  • MongoDB::createDBRef »
  • PHP Manual
  • MongoDB
  • Creates a collection

MongoDB::createCollection

(PECL mongo >=0.9.0)

MongoDB::createCollection — Creates a collection

Description

public MongoDB::createCollection ( string $name [, array $options ] ) : MongoCollection

This method is used to create capped collections and other collections requiring special options. It is identical to running:

<?php

$collection = $db->command(array(
    "create" => $name,
    "capped" => $options["capped"],
    "size" => $options["size"],
    "max" => $options["max"],
    "autoIndexId" => $options["autoIndexId"],
));

?>
See MongoDB::command() for more information about database commands.

Parameters

name

The name of the collection.

options

An array containing options for the collections. Each option is its own element in the options array, with the option name listed below being the key of the element. The supported options depend on the MongoDB server version and storage engine, and the driver passes any option that you give it straight to the server. A few of the supported options are, but you can find a full list in the MongoDB core docs on » createCollection:

capped

If the collection should be a fixed size.

size

If the collection is fixed size, its size in bytes.

max

If the collection is fixed size, the maximum number of elements to store in the collection.

autoIndexId

If capped is TRUE you can specify FALSE to disable the automatic index created on the _id field. Before MongoDB 2.2, the default value for autoIndexId was FALSE.

Return Values

Returns a collection object representing the new collection.

Examples

Example #1 MongoDB::createCollection() capped collection example

A capped collection is a special type of collection that has either a fixed or a fixed number of elements. Once the collection is "full," the oldest elements will be removed when new elements are added. Capped collections can be very useful for applications like logging, where you may want to reserve a certain amount of space for logs and not worry about them getting too big.

This example creates a very tiny log collection that will keep a maximum of 10 documents.

<?php

$log = $db->createCollection(
    "logger",
    array(
        'capped' => true,
        'size' => 10*1024,
        'max' => 10
    )
);

for ($i = 0; $i < 100; $i++) {
    $log->insert(array("level" => WARN, "msg" => "sample log message #$i", "ts" => new MongoDate()));
}

$msgs = $log->find();

foreach ($msgs as $msg) {
    echo $msg['msg']."\n";
}

?>

The above example will output something similar to:

sample log message #90
sample log message #91
sample log message #92
sample log message #93
sample log message #94
sample log message #95
sample log message #96
sample log message #97
sample log message #98
sample log message #99

Changelog

Version Description
1.4.0

In versions before 1.4.0, the options were all arguments to the method. The function synopsis in those older versions is:

public MongoDB::createCollection ( string $name [, bool $capped = FALSE [, int $size = 0 [, int $max = 0 ]]] ) : MongoCollection

The meaning of the options is the same as described under the options argument above.


Creates a database reference

  • « MongoDB::createCollection
  • MongoDB::drop »
  • PHP Manual
  • MongoDB
  • Creates a database reference

MongoDB::createDBRef

(PECL mongo >=0.9.0)

MongoDB::createDBRef — Creates a database reference

Description

public MongoDB::createDBRef ( string $collection , mixed $document_or_id ) : array

This method is a flexible interface for creating database refrences (see MongoDBRef).

Parameters

collection

The collection to which the database reference will point.

document_or_id

If an array or object is given, its _id field will be used as the reference ID. If a MongoId or scalar is given, it will be used as the reference ID.

Return Values

Returns a database reference array.

If an array without an _id field was provided as the document_or_id parameter, NULL will be returned.

Examples

Example #1 MongoDB::createDBRef() example

Example demonstrating how to programatically create a DB reference array from a document.

<?php

$articles = $db->articles;

$article = array(
 'title' => 'Test article',
 'description' => 'Test article description'
);

$articles->insert($article);
$ref = $db->createDBRef('articles', $article);

print_r($article);
print_r($ref);
?>

The above example will output something similar to:

     Array
     (
         [title] => Test article
         [description] => Test article description
         [_id] => MongoId Object
             (
             )

     )
     Array
     (
         [$ref] => articles
         [$id] => MongoId Object
             (
             )

     )

Now the $ref can be stored on another document and retrieved later with MongoDB::getDBRef() or MongoCollection::getDBRef().

Example #2 MongoDB::createDBRef() example

Example demonstrating how to programatically create a DB reference from just an id.

<?php

$id = new MongoId('47cc67093475061e3d9536d2');
$ref = $db->createDBRef('articles', $id);
?>


Drops this database

  • « MongoDB::createDBRef
  • MongoDB::dropCollection »
  • PHP Manual
  • MongoDB
  • Drops this database

MongoDB::drop

(PECL mongo >=0.9.0)

MongoDB::drop — Drops this database

Description

public MongoDB::drop ( void ) : array

This drops the database currently being used.

This is identical to running:

<?php

public function drop() {
    $this->command(array("dropDatabase" => 1));
}

?>

Parameters

This function has no parameters.

Return Values

Returns the database response.

Examples

Example #1 MongoDB::drop() example

This example demonstrates how to drop a mongo database and the response to expect.

<?php

$db = $mongo->foo;
$response = $db->drop();
print_r($response);

?>

The above example will output something similar to:

Array
(
    [dropped] => foo.$cmd
    [ok] => 1
)


Drops a collection [deprecated]

  • « MongoDB::drop
  • MongoDB::execute »
  • PHP Manual
  • MongoDB
  • Drops a collection [deprecated]

MongoDB::dropCollection

(PECL mongo >=0.9.0)

MongoDB::dropCollection — Drops a collection [deprecated]

Description

public MongoDB::dropCollection ( mixed $coll ) : array
Warning

Deprecated

Use MongoCollection::drop() instead.

This function leaks memory in version 1.0.7 and earlier!

Parameters

coll

MongoCollection or name of collection to drop.

Return Values

Returns the database response.


Runs JavaScript code on the database server [deprecated]

  • « MongoDB::dropCollection
  • MongoDB::forceError »
  • PHP Manual
  • MongoDB
  • Runs JavaScript code on the database server [deprecated]

MongoDB::execute

(PECL mongo >=0.9.3)

MongoDB::execute — Runs JavaScript code on the database server [deprecated]

Description

public MongoDB::execute ( mixed $code [, array $args = array() ] ) : array
Warning

The » eval command, which this method invokes, is deprecated in MongoDB 3.0+.

The Mongo database server runs a JavaScript engine. This method allows you to run arbitary JavaScript on the database. This can be useful if you want touch a number of collections lightly, or process some results on the database side to reduce the amount that has to be sent to the client.

Running JavaScript in the database takes a write lock, meaning it blocks other operations. Make sure you consider this before running a long script.

This is a wrapper for the » eval database command. This method is basically:

<?php

public function execute($code, $args) {
    return $this->command(array('eval' => $code, 'args' => $args));
}

?>

MongoDB implies a return statement if you have a single statement on a single line. This can cause some unintuitive behavior. For example, this returns "foo":

<?php

$db->execute('"foo";');

?>

However, these return NULL:

<?php

$db->execute('"bar"; "foo";'); // more than one statement

$db->execute('db.foo.count(
);'); // more than one line

?>

To avoid surprising behavior, it is best not to depend on MongoDB to decide what to return, but to explicitly state a return value. In the examples above, we can change them to:

<?php

$db->execute('"bar"; return "foo";');

$db->execute('return db.foo.count(
);');

?>

Now the first statement will return "foo" and the second statement will return a count of the "foo" collection.

Parameters

code

MongoCode or string to execute.

args

Arguments to be passed to code.

Return Values

Returns the result of the evaluation.

Examples

Example #1 Simple MongoDB::execute() example

<?php

$response = $db->execute("function() { return 'Hello, world!'; }");
echo $response['retval'];

?>

The above example will output something similar to:

Hello, world!

Example #2 Parameter MongoDB::execute() example

The optional array of parameters will be passed to the JavaScript function.

<?php

$response = $db->execute("function(greeting, name) { return greeting+', '+name+'!'; }", array("Good bye", "Joe"));
echo $response['retval'];

?>

The above example will output something similar to:

Good bye, Joe!

Example #3 Scope example

If a MongoCode object is used instead of a string for the first parameter, a scope can be passed in which the JavaScript will be executed.

<?php

$func =
    "function(greeting, name) { ".
        "return greeting+', '+name+', says '+greeter;".
    "}";
$scope = array("greeter" => "Fred");

$code = new MongoCode($func, $scope);

$response = $db->execute($code, array("Goodbye", "Joe"));
echo $response['retval'];

?>

The above example will output something similar to:

Goodbye, Joe, says Fred

See Also

  • The MongoDB » eval command docs

Changelog

Version | Description
1.7.0 | This method has been deprecated as a result of the underlaying » eval command being deprecated in MongoDB 3.0+.


Creates a database error

  • « MongoDB::execute
  • MongoDB::__get »
  • PHP Manual
  • MongoDB
  • Creates a database error

MongoDB::forceError

(PECL mongo >=0.9.5)

MongoDB::forceError — Creates a database error

Description

public MongoDB::forceError ( void ) : bool

This method is not very useful for normal MongoDB use. It forces a database error to occur. This means that MongoDB::lastError() will return a generic database error after running this command.

This command is identical to running:

<?php

public function forceError() {
    return $this->command(array('forceerror' => 1));
}

?>

Parameters

This function has no parameters.

Return Values

Returns the database response.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.


Gets a collection

  • « MongoDB::forceError
  • MongoDB::getCollectionInfo »
  • PHP Manual
  • MongoDB
  • Gets a collection

MongoDB::__get

(PECL mongo >=1.0.2)

MongoDB::__get — Gets a collection

Description

public MongoDB::__get ( string $name ) : MongoCollection

This is the easiest way of getting a collection from a database object. If a collection name contains strange characters, you may have to use MongoDB::selectCollection() instead.

<?php

$mongo = new MongoClient();

// the following two lines are equivalent
$collection = $mongo->selectDB("foo")->selectCollection("bar");
$collection = $mongo->foo->bar;

?>

Parameters

name

The name of the collection.

Return Values

Returns the collection.


Returns information about collections in this database

  • « MongoDB::__get
  • MongoDB::getCollectionNames »
  • PHP Manual
  • MongoDB
  • Returns information about collections in this database

MongoDB::getCollectionInfo

(PECL mongo >=1.6.0)

MongoDB::getCollectionInfo — Returns information about collections in this database

Description

public MongoDB::getCollectionInfo ([ array $options = array() ] ) : array

Gets a list of all collections in the database and returns them as an array of documents, which contain their names and options.

Note: This method will use the » listCollections database command when communicating with MongoDB 2.8+. For previous database versions, the method will query the special system.namespaces collection.

Parameters

options

An array of options for listing the collections. Currently available options include:

  • "filter"

    Optional query criteria. If provided, this criteria will be used to filter the collections included in the result.

    Relevant fields that may be queried include "name" (collection name as a string, without the database name prefix) and "options" (object containing options used to create the collection)..

    Note: MongoDB 2.6 and earlier versions require the "name" criteria, if specified, to be a string value (i.e. equality match). This is because the driver must prefix the value with the database name in order to query the system.namespaces collection. Later versions of MongoDB do not have this limitation, as the driver will use the listCollections command.

  • "includeSystemCollections"

    Boolean, defaults to FALSE. Determines whether system collections should be included in the result.

The following option may be used with MongoDB 2.8+:

  • "maxTimeMS"

    Specifies a cumulative time limit in milliseconds for processing the operation on the server (does not include idle time). If the operation is not completed by the server within the timeout period, a MongoExecutionTimeoutException will be thrown.

Return Values

This function returns an array where each element is an array describing a collection. Elements will contain a name key denoting the name of the collection, and optionally contain an options key denoting an array of objects used to create the collection. For example, capped collections will include capped and size options.

Errors/Exceptions

For MongoDB 2.6 and earlier, MongoException will be thrown if a non-string value was specified for the "filter" option's "name" criteria.

Examples

Example #1 MongoDB::getCollectionInfo() example

<?php
$m = new MongoClient();
$db = $m->selectDB("demo");
var_dump($db->getCollectionInfo());
?>

The above example will output something similar to:

array(2) {
  [0]=>
  array(2) {
    ["name"]=>
    string(4) "logs"
    ["options"]=>
    array(2) {
      ["capped"]=>
      bool(true)
      ["size"]=>
      int(10240)
    }
  }
  [1]=>
  array(2) {
    ["name"]=>
    string(5) "users"
    ["options"]=>
    array(1) {
      ["flags"]=>
      int(1)
    }
  }
}

See Also

  • MongoDB::getCollectionNames() - Gets an array of names for all collections in this database
  • MongoDB::listCollections() - Gets an array of MongoCollection objects for all collections in this database


Gets an array of names for all collections in this database

  • « MongoDB::getCollectionInfo
  • MongoDB::getDBRef »
  • PHP Manual
  • MongoDB
  • Gets an array of names for all collections in this database

MongoDB::getCollectionNames

(PECL mongo >=1.3.0)

MongoDB::getCollectionNames — Gets an array of names for all collections in this database

Description

public MongoDB::getCollectionNames ([ array $options = array() ] ) : array

Gets a list of all collections in the database and returns their names as an array of strings.

Note: This method will use the » listCollections database command when communicating with MongoDB 2.8+. For previous database versions, the method will query the special system.namespaces collection.

Parameters

options

An array of options for listing the collections. Currently available options include:

  • "filter"

    Optional query criteria. If provided, this criteria will be used to filter the collections included in the result.

    Relevant fields that may be queried include "name" (collection name as a string, without the database name prefix) and "options" (object containing options used to create the collection)..

    Note: MongoDB 2.6 and earlier versions require the "name" criteria, if specified, to be a string value (i.e. equality match). This is because the driver must prefix the value with the database name in order to query the system.namespaces collection. Later versions of MongoDB do not have this limitation, as the driver will use the listCollections command.

  • "includeSystemCollections"

    Boolean, defaults to FALSE. Determines whether system collections should be included in the result.

The following option may be used with MongoDB 2.8+:

  • "maxTimeMS"

    Specifies a cumulative time limit in milliseconds for processing the operation on the server (does not include idle time). If the operation is not completed by the server within the timeout period, a MongoExecutionTimeoutException will be thrown.

Return Values

Returns the collection names as an array of strings.

Errors/Exceptions

For MongoDB 2.6 and earlier, MongoException will be thrown if a non-string value was specified for the "filter" option's "name" criteria.

Changelog

Version | Description
1.6.0 | Changed first parameter to be an array of options. Pre-1.6.0, the first parameter was a boolean indicating the "includeSystemCollections" option.

Examples

Example #1 MongoDB::getCollectionNames() example

<?php
$m = new MongoClient();
$db = $m->selectDB("demo");
$collections = $db->getCollectionNames();

foreach ($collections as $collectionName) {
    echo "Found collection: ", $collectionName, "\n";
}
?>

The above example will output something similar to:

...
Found collection: img
Found collection: beer
Found collection: collation
...

See Also

  • MongoDB::listCollections() - Gets an array of MongoCollection objects for all collections in this database
  • MongoDB::getCollectionInfo() - Returns information about collections in this database


Fetches the document pointed to by a database reference

  • « MongoDB::getCollectionNames
  • MongoDB::getGridFS »
  • PHP Manual
  • MongoDB
  • Fetches the document pointed to by a database reference

MongoDB::getDBRef

(PECL mongo >=0.9.0)

MongoDB::getDBRef — Fetches the document pointed to by a database reference

Description

public MongoDB::getDBRef ( array $ref ) : array

Parameters

ref

A database reference.

Return Values

Returns the document pointed to by the reference.

Examples

Example #1 MongoDB::getDBRef() example

Example demonstrating how to get a database reference and what the expected input is.

<?php

 $ref = array(
   '$ref' => 'profiles',
   '$id' => new MongoId('47cc67093475061e3d9536d2')
 );

 $profile = $db->getDBRef($ref);
 ?>

See MongoDB::createDBRef() for more information about how to programatically create DB references.


Fetches toolkit for dealing with files stored in this database

  • « MongoDB::getDBRef
  • MongoDB::getProfilingLevel »
  • PHP Manual
  • MongoDB
  • Fetches toolkit for dealing with files stored in this database

MongoDB::getGridFS

(PECL mongo >=0.9.0)

MongoDB::getGridFS — Fetches toolkit for dealing with files stored in this database

Description

public MongoDB::getGridFS ([ string $prefix = "fs" ] ) : MongoGridFS

Parameters

prefix

The prefix for the files and chunks collections.

Return Values

Returns a new gridfs object for this database.

Examples

Example #1 MongoDB::getGridFS() example

This example demonstrates how get a MongoGridFS instance.

<?php

$db = $mongo->my_db;

$prefix = 'files';
$collection = $db->getGridFS($prefix);

?>

Read more about the MongoGridFS to learn how to store files with MongoDB.


Gets this database's profiling level

  • « MongoDB::getGridFS
  • MongoDB::getReadPreference »
  • PHP Manual
  • MongoDB
  • Gets this database's profiling level

MongoDB::getProfilingLevel

(PECL mongo >=0.9.0)

MongoDB::getProfilingLevel — Gets this database's profiling level

Description

public MongoDB::getProfilingLevel ( void ) : int

This returns the current database profiling level.

The database profiler tracks query execution times. If you turn it on (say, using MongoDB::setProfilingLevel() or the shell), you can see how many queries took longer than a given number of milliseconds or the timing for all queries.

Note that profiling slows down queries, so it is better to use in development or testing than in a time-sensitive application.

This function is equivalent to running:

<?php

public function getProfilingLevel() {
    return $this->command(array('profile' => -1));
}

?>

Parameters

This function has no parameters.

Return Values

Returns the profiling level.

See Also

  • MongoDB core docs on » profiling
  • MongoDB::setProfilingLevel() - Sets this database's profiling level


Get the read preference for this database

  • « MongoDB::getProfilingLevel
  • MongoDB::getSlaveOkay »
  • PHP Manual
  • MongoDB
  • Get the read preference for this database

MongoDB::getReadPreference

(PECL mongo >=1.3.0)

MongoDB::getReadPreference — Get the read preference for this database

Description

public MongoDB::getReadPreference ( void ) : array

Parameters

This function has no parameters.

Return Values

This function returns an array describing the read preference. The array contains the values type for the string read preference mode (corresponding to the MongoClient constants), and tagsets containing a list of all tag set criteria. If no tag sets were specified, tagsets will not be present in the array.

Changelog

Version | Description
1.3.3 | The return value has changed to be consistent with MongoDB::setReadPreference(). The type value was changed from a number to a string, type_string was removed, and tagsets now expresses tags as key/value pairs instead of colon-delimited strings.

Examples

Example #1 MongoDB::getReadPreference() return value example

<?php

$m = new MongoClient();
$db = $m->test;
$db->setReadPreference(MongoClient::RP_SECONDARY, array(
    array('dc' => 'east', 'use' => 'reporting'),
    array('dc' => 'west'),
    array(),
));
var_dump($db->getReadPreference());
?>

The above example will output:

array(2) {
  ["type"]=>
  string(9) "secondary"
  ["tagsets"]=>
  array(3) {
    [0]=>
    array(2) {
      ["dc"]=>
      string(4) "east"
      ["use"]=>
      string(9) "reporting"
    }
    [1]=>
    array(1) {
      ["dc"]=>
      string(7) "west"
    }
    [2]=>
    array(0) {
    }
  }
}

See Also

  • The read preferences documentation.
  • MongoDB::setReadPreference() - Set the read preference for this database


Get slaveOkay setting for this database

  • « MongoDB::getReadPreference
  • MongoDB::getWriteConcern »
  • PHP Manual
  • MongoDB
  • Get slaveOkay setting for this database

MongoDB::getSlaveOkay

(PECL mongo >=1.1.0)

MongoDB::getSlaveOkay — Get slaveOkay setting for this database

Description

public MongoDB::getSlaveOkay ( void ) : bool

See the query section of this manual for information on distributing reads to secondaries.

Parameters

This function has no parameters.

Return Values

Returns the value of slaveOkay for this instance.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.

See Also

  • Read Preferences
  • MongoDB::getReadPreference() - Get the read preference for this database
  • MongoDB::setReadPreference() - Set the read preference for this database


Get the write concern for this database

  • « MongoDB::getSlaveOkay
  • MongoDB::lastError »
  • PHP Manual
  • MongoDB
  • Get the write concern for this database

MongoDB::getWriteConcern

(PECL mongo >=1.5.0)

MongoDB::getWriteConcern — Get the write concern for this database

Description

public MongoDB::getWriteConcern ( void ) : array

Parameters

This function has no parameters.

Return Values

This function returns an array describing the write concern. The array contains the values w for an integer acknowledgement level or string mode, and wtimeout denoting the maximum number of milliseconds to wait for the server to satisfy the write concern.

Examples

Example #1 MongoDB::getWriteConcern() return value example

<?php

$mc = new MongoClient('mongodb://localhost:27017', array('wTimeoutMS' => 500));
$db = $mc->selectDB('test');
var_dump($db->getWriteConcern());

$db->setWriteConcern(1, 1000);
var_dump($db->getWriteConcern());
?>

The above example will output:

array(2) {
  ["w"]=>
  int(1)
  ["wtimeout"]=>
  int(500)
}
array(2) {
  ["w"]=>
  int(1)
  ["wtimeout"]=>
  int(1000)
}

See Also

  • The write concern documentation.
  • MongoDB::setWriteConcern() - Set the write concern for this database


Check if there was an error on the most recent db operation performed

  • « MongoDB::getWriteConcern
  • MongoDB::listCollections »
  • PHP Manual
  • MongoDB
  • Check if there was an error on the most recent db operation performed

MongoDB::lastError

(PECL mongo >=0.9.5)

MongoDB::lastError — Check if there was an error on the most recent db operation performed

Description

public MongoDB::lastError ( void ) : array

This method is equivalent to:

<?php

public function lastError() {
    return $this->command(array('getlasterror' => 1));
}

?>

Parameters

This function has no parameters.

Return Values

Returns the error, if there was one.

Examples

Example #1 MongoDB::lastError() NULL error example

<?php
$db->resetError();
var_dump($db->lastError());
?>

The above example will output something similar to:

array(3) {
  ["err"]=>
  NULL
  ["n"]=>
  int(0)
  ["ok"]=>
  float(1)
}

Example #2 MongoDB::lastError() duplicate key example

<?php
$c = $db->selectCollection("foo");

// insert two documents with the same _id
$c->insert(array("_id" => 1));
$c->insert(array("_id" => 1));

var_dump($db->lastError());
?>

The above example will output something similar to:

array(3) {
  ["err"]=>
  string(64) "E11000 duplicate key errorindex: foo.foo.$_id_  dup key: { : 1 }"
  ["n"]=>
  int(0)
  ["ok"]=>
  float(1)
}


Gets an array of MongoCollection objects for all collections in this database

  • « MongoDB::lastError
  • MongoDB::prevError »
  • PHP Manual
  • MongoDB
  • Gets an array of MongoCollection objects for all collections in this database

MongoDB::listCollections

(PECL mongo >=0.9.0)

MongoDB::listCollections — Gets an array of MongoCollection objects for all collections in this database

Description

public MongoDB::listCollections ([ array $options = array() ] ) : array

Gets a list of all collections in the database and returns them as an array of MongoCollection objects.

Note: This method will use the » listCollections database command when communicating with MongoDB 2.8+. For previous database versions, the method will query the special system.namespaces collection.

Parameters

options

An array of options for listing the collections. Currently available options include:

  • "filter"

    Optional query criteria. If provided, this criteria will be used to filter the collections included in the result.

    Relevant fields that may be queried include "name" (collection name as a string, without the database name prefix) and "options" (object containing options used to create the collection)..

    Note: MongoDB 2.6 and earlier versions require the "name" criteria, if specified, to be a string value (i.e. equality match). This is because the driver must prefix the value with the database name in order to query the system.namespaces collection. Later versions of MongoDB do not have this limitation, as the driver will use the listCollections command.

  • "includeSystemCollections"

    Boolean, defaults to FALSE. Determines whether system collections should be included in the result.

The following option may be used with MongoDB 2.8+:

  • "maxTimeMS"

    Specifies a cumulative time limit in milliseconds for processing the operation on the server (does not include idle time). If the operation is not completed by the server within the timeout period, a MongoExecutionTimeoutException will be thrown.

Return Values

Returns an array of MongoCollection objects.

Errors/Exceptions

For MongoDB 2.6 and earlier, MongoException will be thrown if a non-string value was specified for the "filter" option's "name" criteria.

Changelog

Version | Description
1.6.0 | Changed first parameter to be an array of options. Pre-1.6.0, the first parameter was a boolean indicating the "includeSystemCollections" option.
1.3.0 | Added the includeSystemCollections parameter.

Examples

Example #1 MongoDB::listCollections() example

The following example demonstrates running count on each collection in a database.

<?php

$m = new MongoClient();
$db = $m->selectDB("demo");
$collections = $db->listCollections();

foreach ($collections as $collection) {
    echo "amount of documents in $collection: ";
    echo $collection->count(), "\n";
}

?>

The above example will output something similar to:

...
amount of documents in demo.pubs: 4
amount of documents in demo.elephpants: 3
amount of documents in demo.cities: 22840
...

See Also

  • MongoDB::getCollectionNames() - Gets an array of names for all collections in this database
  • MongoDB::getCollectionInfo() - Returns information about collections in this database


Checks for the last error thrown during a database operation

  • « MongoDB::listCollections
  • MongoDB::repair »
  • PHP Manual
  • MongoDB
  • Checks for the last error thrown during a database operation

MongoDB::prevError

(PECL mongo >=0.9.5)

MongoDB::prevError — Checks for the last error thrown during a database operation

Description

public MongoDB::prevError ( void ) : array

MongoDB::lastError() is usually preferred to this. This method returns the last database error that occurred and how many operations ago it occurred. It is mostly deprecated.

Parameters

This function has no parameters.

Return Values

Returns the error and the number of operations ago it occurred.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.


Repairs and compacts this database

  • « MongoDB::prevError
  • MongoDB::resetError »
  • PHP Manual
  • MongoDB
  • Repairs and compacts this database

MongoDB::repair

(PECL mongo >=0.9.0)

MongoDB::repair — Repairs and compacts this database

Description

public MongoDB::repair ([ bool $preserve_cloned_files = FALSE [, bool $backup_original_files = FALSE ]] ) : array

This creates a fresh copy of all database data. It will remove any corrupt data and compact and large stretches of free space it finds. This is a very slow operation on a large database.

This is usually run from the shell or the command line, not the driver.

It is equivalent to the function:

<?php

public function repair() {
    return $this->command(array('repairDatabase' => 1));
}

?>

Parameters

preserve_cloned_files

If cloned files should be kept if the repair fails.

backup_original_files

If original files should be backed up.

Return Values

Returns db response.

See Also

MongoDB core docs on » repairDatabase.

Examples

Example #1 MongoDB::repair() example

This example demonstrates how to repare and compact a database.

<?php

$db = $mongo->foo;

$response = $db->repair();
print_r($response);

?>

The above example will output something similar to:

Array
(
    [ok] => 1
)


Clears any flagged errors on the database

  • « MongoDB::repair
  • MongoDB::selectCollection »
  • PHP Manual
  • MongoDB
  • Clears any flagged errors on the database

MongoDB::resetError

(PECL mongo >=0.9.5)

MongoDB::resetError — Clears any flagged errors on the database

Description

public MongoDB::resetError ( void ) : array

This method is not used in normal operations. It resets the database error tracker (which can be incremented with MongoDB::forceError(), also not normally used).

It is equivalent to running:

<?php

public function resetError() {
    return $this->command(array('reseterror' => 1));
}

?>

Parameters

This function has no parameters.

Return Values

Returns the database response.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.


Gets a collection

  • « MongoDB::resetError
  • MongoDB::setProfilingLevel »
  • PHP Manual
  • MongoDB
  • Gets a collection

MongoDB::selectCollection

(PECL mongo >=0.9.0)

MongoDB::selectCollection — Gets a collection

Description

public MongoDB::selectCollection ( string $name ) : MongoCollection

Parameters

name

The collection name.

Return Values

Returns a new collection object.

Errors/Exceptions

Throws Exception if the collection name is invalid.


Sets this database's profiling level

  • « MongoDB::selectCollection
  • MongoDB::setReadPreference »
  • PHP Manual
  • MongoDB
  • Sets this database's profiling level

MongoDB::setProfilingLevel

(PECL mongo >=0.9.0)

MongoDB::setProfilingLevel — Sets this database's profiling level

Description

public MongoDB::setProfilingLevel ( int $level ) : int

This changes the current database profiling level.

This function is equivalent to running:

<?php

public function setProfilingLevel($level) {
    return $this->command(array('profile' => $level));
}

?>

The options for level are 0 (off), 1 (queries > 100ms), and 2 (all queries). If you would like to profile queries that take longer than another time period, use the database command and pass it a second option, the number of milliseconds. For example, to profile all queries that take longer than one second, run:

<?php

$result = $this->command(array('profile' => 1, 'slowms' => 1000));

?>

Profiled queries will appear in the system.profile collection of this database.

Parameters

level

Profiling level.

Return Values

Returns the previous profiling level.

See Also

  • MongoDB core docs on » profiling
  • MongoDB::getProfilingLevel() - Gets this database's profiling level


Set the read preference for this database

  • « MongoDB::setProfilingLevel
  • MongoDB::setSlaveOkay »
  • PHP Manual
  • MongoDB
  • Set the read preference for this database

MongoDB::setReadPreference

(PECL mongo >=1.3.0)

MongoDB::setReadPreference — Set the read preference for this database

Description

public MongoDB::setReadPreference ( string $read_preference [, array $tags ] ) : bool

Parameters

read_preference

The read preference mode: MongoClient::RP_PRIMARY, MongoClient::RP_PRIMARY_PREFERRED, MongoClient::RP_SECONDARY, MongoClient::RP_SECONDARY_PREFERRED, or MongoClient::RP_NEAREST.

tags

An array of zero or more tag sets, where each tag set is itself an array of criteria used to match tags on replica set members.

Return Values

Returns TRUE on success, or FALSE otherwise.

Errors/Exceptions

Emits E_WARNING if either parameter is invalid, or if one or more tag sets are provided with the MongoClient::RP_PRIMARY read preference mode.

Examples

Example #1 MongoDB::setReadPreference() tag set array syntax example

<?php

$m = new MongoClient();
$db = $m->test;

// Prefer the nearest server in the "east" data center also used for reporting,
// but fall back to a server in the "west" data center
$db->setReadPreference(MongoClient::RP_NEAREST, array(
    array('dc' => 'east', 'use' => 'reporting'),
    array('dc' => 'west'),
));
?>

See Also

  • The read preferences documentation.
  • MongoDB::getReadPreference() - Get the read preference for this database


Change slaveOkay setting for this database

  • « MongoDB::setReadPreference
  • MongoDB::setWriteConcern »
  • PHP Manual
  • MongoDB
  • Change slaveOkay setting for this database

MongoDB::setSlaveOkay

(PECL mongo >=1.1.0)

MongoDB::setSlaveOkay — Change slaveOkay setting for this database

Description

public MongoDB::setSlaveOkay ([ bool $ok = TRUE ] ) : bool

See the query section of this manual for information on distributing reads to secondaries.

Parameters

ok

If reads should be sent to secondary members of a replica set for all possible queries using this MongoDB instance.

Return Values

Returns the former value of slaveOkay for this instance.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.

See Also

  • Read Preferences
  • MongoDB::setReadPreference() - Set the read preference for this database
  • MongoDB::getReadPreference() - Get the read preference for this database


Set the write concern for this database

  • « MongoDB::setSlaveOkay
  • MongoDB::__toString »
  • PHP Manual
  • MongoDB
  • Set the write concern for this database

MongoDB::setWriteConcern

(PECL mongo >=1.5.0)

MongoDB::setWriteConcern — Set the write concern for this database

Description

public MongoDB::setWriteConcern ( mixed $w [, int $wtimeout ] ) : bool

Parameters

w

The write concern. This may be an integer denoting the number of servers required to acknowledge the write, or a string mode (e.g. "majority").

wtimeout

The maximum number of milliseconds to wait for the server to satisfy the write concern.

Return Values

Returns TRUE on success, or FALSE otherwise.

Errors/Exceptions

Emits E_WARNING if the w parameter is not an integer or string value.

Examples

Example #1 MongoDB::setWriteConcern() example

<?php

$mc = new MongoClient('mongodb://rs1.example.com,rs2.example.com');
$db = $mc->selectDB('test');

// Require that the majority of servers in the replica set acknowledge writes
// within three seconds.
$db->setWriteConcern('majority', 3000);
?>

See Also

  • The write concern documentation.
  • MongoDB::getWriteConcern() - Get the write concern for this database


The name of this database

  • « MongoDB::setWriteConcern
  • MongoCollection »
  • PHP Manual
  • MongoDB
  • The name of this database

MongoDB::__toString

(PECL mongo >=0.9.0)

MongoDB::__toString — The name of this database

Description

public MongoDB::__toString ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns this database's name.


The MongoCollection class

(PECL mongo >=0.9.0)

Introduction

Represents a MongoDB collection.

Collection names can use any character in the ASCII set. Some valid collection names are "", "...", "my collection", and "*&#@".

User-defined collection names cannot contain the $ symbol. There are certain system collections which use a $ in their names (e.g., local.oplog.$main), but it is a reserved character. If you attempt to create and use a collection with a $ in the name, MongoDB will assert.

Class synopsis

MongoCollection {
/* Constants */
const int ASCENDING = 1 ;
const int DESCENDING = -1 ;
/* Fields */
public MongoDB $db = NULL ;
public integer $w ;
public integer $wtimeout ;
/* Methods */
public aggregate ( array $pipeline [, array $options ] ) : array
public aggregateCursor ( array $command [, array $options ] ) : MongoCommandCursor
public batchInsert ( array $a [, array $options = array() ] ) : mixed
public __construct ( MongoDB $db , string $name )
public count ([ array $query = array() [, array $options = array() ]] ) : int
public createDBRef ( mixed $document_or_id ) : array
public createIndex ( array $keys [, array $options = array() ] ) : bool
public deleteIndex ( string|array $keys ) : array
public deleteIndexes ( void ) : array
public distinct ( string $key [, array $query ] ) : array
public drop ( void ) : array
public ensureIndex ( string|array $key|keys [, array $options = array() ] ) : bool
public find ([ array $query = array() [, array $fields = array() ]] ) : MongoCursor
public findAndModify ( array $query [, array $update [, array $fields [, array $options ]]] ) : array
 public findOne
  ([ array $query = array()
 [, array $fields = array()
 [, array $options = array()
]]] ) : array
public __get ( string $name ) : MongoCollection
public getDBRef ( array $ref ) : array
public getIndexInfo ( void ) : array
public getName ( void ) : string
public getReadPreference ( void ) : array
public getSlaveOkay ( void ) : bool
public getWriteConcern ( void ) : array
public group ( mixed $keys , array $initial , MongoCode $reduce [, array $options = array() ] ) : array
public insert ( array|object $document [, array $options = array() ] ) : bool|array
public parallelCollectionScan ( int $num_cursors ) : array[MongoCommandCursor]
public remove ([ array $criteria = array() [, array $options = array() ]] ) : bool|array
public save ( array|object $document [, array $options = array() ] ) : mixed
public setReadPreference ( string $read_preference [, array $tags ] ) : bool
public setSlaveOkay ([ bool $ok = TRUE ] ) : bool
public setWriteConcern ( mixed $w [, int $wtimeout ] ) : bool
static protected toIndexString ( mixed $keys ) : string
public __toString ( void ) : string
public update ( array $criteria , array $new_object [, array $options = array() ] ) : bool|array
public validate ([ bool $scan_data = FALSE ] ) : array
}

Predefined Constants

MongoCollection::ASCENDING
Ascending direction for sorts and index creation.
MongoCollection::DESCENDING
Descending direction for sorts and index creation.

Fields

db

The "parent" database for this collection.

w

The number of servers to replicate a change to before returning success. Value is inherited from the parent database. The MongoDB class has a more detailed description of how w works.

wtimeout

The number of milliseconds to wait for $this->w replications to take place. Value is inherited from the parent database. The MongoDB class has a more detailed description of how wtimeout works.

See Also

MongoDB core docs on » collections.

Table of Contents

  • MongoCollection::aggregate — Perform an aggregation using the aggregation framework
  • MongoCollection::aggregateCursor — Execute an aggregation pipeline command and retrieve results through a cursor
  • MongoCollection::batchInsert — Inserts multiple documents into this collection
  • MongoCollection::__construct — Creates a new collection
  • MongoCollection::count — Counts the number of documents in this collection
  • MongoCollection::createDBRef — Creates a database reference
  • MongoCollection::createIndex — Creates an index on the specified field(s) if it does not already exist
  • MongoCollection::deleteIndex — Deletes an index from this collection
  • MongoCollection::deleteIndexes — Delete all indices for this collection
  • MongoCollection::distinct — Retrieve a list of distinct values for the given key across a collection
  • MongoCollection::drop — Drops this collection
  • MongoCollection::ensureIndex — Creates an index on the specified field(s) if it does not already exist
  • MongoCollection::find — Queries this collection, returning a MongoCursor for the result set
  • MongoCollection::findAndModify — Update a document and return it
  • MongoCollection::findOne — Queries this collection, returning a single element
  • MongoCollection::__get — Gets a collection
  • MongoCollection::getDBRef — Fetches the document pointed to by a database reference
  • MongoCollection::getIndexInfo — Returns information about indexes on this collection
  • MongoCollection::getName — Returns this collection's name
  • MongoCollection::getReadPreference — Get the read preference for this collection
  • MongoCollection::getSlaveOkay — Get slaveOkay setting for this collection
  • MongoCollection::getWriteConcern — Get the write concern for this collection
  • MongoCollection::group — Performs an operation similar to SQL's GROUP BY command
  • MongoCollection::insert — Inserts a document into the collection
  • MongoCollection::parallelCollectionScan — Returns an array of cursors to iterator over a full collection in parallel
  • MongoCollection::remove — Remove records from this collection
  • MongoCollection::save — Saves a document to this collection
  • MongoCollection::setReadPreference — Set the read preference for this collection
  • MongoCollection::setSlaveOkay — Change slaveOkay setting for this collection
  • MongoCollection::setWriteConcern — Set the write concern for this database
  • MongoCollection::toIndexString — Converts keys specifying an index to its identifying string
  • MongoCollection::__toString — String representation of this collection
  • MongoCollection::update — Update records based on a given criteria
  • MongoCollection::validate — Validates this collection


Perform an aggregation using the aggregation framework

  • « MongoCollection
  • MongoCollection::aggregateCursor »
  • PHP Manual
  • MongoCollection
  • Perform an aggregation using the aggregation framework

MongoCollection::aggregate

(PECL mongo >=1.3.0)

MongoCollection::aggregate — Perform an aggregation using the aggregation framework

Description

public MongoCollection::aggregate ( array $pipeline [, array $options ] ) : array
public MongoCollection::aggregate ( array $op [, array $op [, array $... ]] ) : array

The MongoDB » aggregation framework provides a means to calculate aggregated values without having to use MapReduce. While MapReduce is powerful, it is often more difficult than necessary for many simple aggregation tasks, such as totaling or averaging field values.

This method accepts either a variable amount of pipeline operators, or a single array of operators constituting the pipeline.

Parameters

pipeline

An array of pipeline operators.

options

Options for the aggregation command. Valid options include:

  • "allowDiskUse"

    Allow aggregation stages to write to temporary files

  • "cursor"

    Options controlling the creation of the cursor object. This option causes the command to return a result document suitable for constructing a MongoCommandCursor. If you need to use this option, you should consider using MongoCollection::aggregateCursor().

  • "explain"

    Return information on the processing of the pipeline.

  • "maxTimeMS"

    Specifies a cumulative time limit in milliseconds for processing the operation on the server (does not include idle time). If the operation is not completed by the server within the timeout period, a MongoExecutionTimeoutException will be thrown.

Or

op

First pipeline operator.

op

The second pipeline operator.

...

Additional pipeline operators.

Return Values

The result of the aggregation as an array. The ok will be set to 1 on success, 0 on failure.

Errors/Exceptions

When an error occurs an array with the following keys will be returned:

  • errmsg - containing the reason for the failure
  • code - the errorcode of the failure
  • ok - will be set to 0.

Changelog

Version | Description
1.5.0 | Added optional options argument

Examples

Example #1 MongoCollection::aggregate() example

The following example aggregation operation pivots data to create a set of author names grouped by tags applied to an article. Call the aggregation framework by issuing the following command:

<?php
$m = new MongoClient("localhost");
$c = $m->selectDB("examples")->selectCollection("article");
$data = array (
    'title' => 'this is my title',
    'author' => 'bob',
    'posted' => new MongoDate,
    'pageViews' => 5,
    'tags' => array ( 'fun', 'good', 'fun' ),
    'comments' => array (
      array (
        'author' => 'joe',
        'text' => 'this is cool',
      ),
      array (
        'author' => 'sam',
        'text' => 'this is bad',
      ),
    ),
    'other' =>array (
      'foo' => 5,
    ),
);
$d = $c->insert($data, array("w" => 1));

$ops = array(
    array(
        '$project' => array(
            "author" => 1,
            "tags"   => 1,
        )
    ),
    array('$unwind' => '$tags'),
    array(
        '$group' => array(
            "_id" => array("tags" => '$tags'),
            "authors" => array('$addToSet' => '$author'),
        ),
    ),
);
$results = $c->aggregate($ops);
var_dump($results);
?>

The above example will output:

array(2) {
  ["result"]=>
  array(2) {
    [0]=>
    array(2) {
      ["_id"]=>
      array(1) {
        ["tags"]=>
        string(4) "good"
      }
      ["authors"]=>
      array(1) {
        [0]=>
        string(3) "bob"
      }
    }
    [1]=>
    array(2) {
      ["_id"]=>
      array(1) {
        ["tags"]=>
        string(3) "fun"
      }
      ["authors"]=>
      array(1) {
        [0]=>
        string(3) "bob"
      }
    }
  }
  ["ok"]=>
  float(1)
}

The following examples use the » zipcode data set. Use mongoimport to load this data set into your mongod instance.

Example #2 MongoCollection::aggregate() example

To return all states with a population greater than 10 million, use the following aggregation operation:

<?php
$m = new MongoClient("localhost");
$c = $m->selectDB("test")->selectCollection("zips");

$pipeline = array(
    array(
        '$group' => array(
            '_id' => array('state' => '$state'),
            'totalPop' => array('$sum' => '$pop')
        )
    ),
    array(
        '$match' => array(
            'totalPop' => array('$gte' => 10 * 1000 * 1000)
        )
    ),
);
$out = $c->aggregate($pipeline);
var_dump($out);
?>

The above example will output something similar to:

array(2) {
  ["result"]=>
  array(7) {
    [0]=>
    array(2) {
      ["_id"]=>
      string(2) "TX"
      ["totalPop"]=>
      int(16986510)
    }
    [1]=>
    array(2) {
      ["_id"]=>
      string(2) "PA"
      ["totalPop"]=>
      int(11881643)
    }
    [2]=>
    array(2) {
      ["_id"]=>
      string(2) "NY"
      ["totalPop"]=>
      int(17990455)
    }
    [3]=>
    array(2) {
      ["_id"]=>
      string(2) "IL"
      ["totalPop"]=>
      int(11430602)
    }
    [4]=>
    array(2) {
      ["_id"]=>
      string(2) "CA"
      ["totalPop"]=>
      int(29760021)
    }
    [5]=>
    array(2) {
      ["_id"]=>
      string(2) "OH"
      ["totalPop"]=>
      int(10847115)
    }
    [6]=>
    array(2) {
      ["_id"]=>
      string(2) "FL"
      ["totalPop"]=>
      int(12937926)
    }
  }
  ["ok"]=>
  float(1)
}

Example #3 MongoCollection::aggregate() example

To return the average populations for cities in each state, use the following aggregation operation:

<?php
$m = new MongoClient;
$c = $m->selectDB("test")->selectCollection("zips");

$out = $c->aggregate(
    array(
        '$group' => array(
            '_id' => array('state' => '$state', 'city' => '$city' ),
            'pop' => array('$sum' => '$pop' )
        )
    ),
    array(
        '$group' => array(
            '_id' => '$_id.state',
            'avgCityPop' => array('$avg' => '$pop')
        )
    )
);

var_dump($out);
?>

The above example will output something similar to:

array(2) {
  ["result"]=>
  array(51) {
    [0]=>
    array(2) {
      ["_id"]=>
      string(2) "DC"
      ["avgCityPop"]=>
      float(303450)
    }
    [1]=>
    array(2) {
      ["_id"]=>
      string(2) "DE"
      ["avgCityPop"]=>
      float(14481.913043478)
    }
...
    [49]=>
    array(2) {
      ["_id"]=>
      string(2) "WI"
      ["avgCityPop"]=>
      float(7323.0074850299)
    }
    [50]=>
    array(2) {
      ["_id"]=>
      string(2) "WV"
      ["avgCityPop"]=>
      float(2759.1953846154)
    }
  }
  ["ok"]=>
  float(1)
}

Example #4 MongoCollection::aggregate() with command options

To return information on how the pipeline will be processed we use the explain command option:

<?php
$m = new MongoClient;
$c = $m->selectDB("test")->selectCollection("zips");

$pipeline = array(
    array(
        '$group' => array(
            '_id' => '$state',
           'totalPop' => array('$sum' => '$pop'),
        ),
    ),
    array(
        '$match' => array(
            'totalPop' => array('$gte' => 10 * 1000 * 1000)
        )
    ),
    array(
        '$sort' => array("totalPop" => -1),
    ),
);

$options = array("explain" => true);
$out = $c->aggregate($pipeline, $options);
var_dump($out);
?>

The above example will output something similar to:

array(2) {
  ["stages"]=>
  array(4) {
    [0]=>
    array(1) {
      ["$cursor"]=>
      array(3) {
        ["query"]=>
        array(0) {
        }
        ["fields"]=>
        array(3) {
          ["pop"]=>
          int(1)
          ["state"]=>
          int(1)
          ["_id"]=>
          int(0)
        }
        ["plan"]=>
        array(4) {
          ["cursor"]=>
          string(11) "BasicCursor"
          ["isMultiKey"]=>
          bool(false)
          ["scanAndOrder"]=>
          bool(false)
          ["allPlans"]=>
          array(1) {
            [0]=>
            array(3) {
              ["cursor"]=>
              string(11) "BasicCursor"
              ["isMultiKey"]=>
              bool(false)
              ["scanAndOrder"]=>
              bool(false)
            }
          }
        }
      }
    }
    [1]=>
    array(1) {
      ["$group"]=>
      array(2) {
        ["_id"]=>
        string(6) "$state"
        ["totalPop"]=>
        array(1) {
          ["$sum"]=>
          string(4) "$pop"
        }
      }
    }
    [2]=>
    array(1) {
      ["$match"]=>
      array(1) {
        ["totalPop"]=>
        array(1) {
          ["$gte"]=>
          int(10000000)
        }
      }
    }
    [3]=>
    array(1) {
      ["$sort"]=>
      array(1) {
        ["sortKey"]=>
        array(1) {
          ["totalPop"]=>
          int(-1)
        }
      }
    }
  }
  ["ok"]=>
  float(1)
}

See Also

  • MongoCollection::aggregateCursor() - Execute an aggregation pipeline command and retrieve results through a cursor
  • The MongoDB » aggregation framework


Execute an aggregation pipeline command and retrieve results through a cursor

  • « MongoCollection::aggregate
  • MongoCollection::batchInsert »
  • PHP Manual
  • MongoCollection
  • Execute an aggregation pipeline command and retrieve results through a cursor

MongoCollection::aggregateCursor

(PECL mongo >=1.5.0)

MongoCollection::aggregateCursor — Execute an aggregation pipeline command and retrieve results through a cursor

Description

public MongoCollection::aggregateCursor ( array $command [, array $options ] ) : MongoCommandCursor

With this method you can execute Aggregation Framework pipelines and retrieve the results through a cursor, instead of getting just one document back as you would with MongoCollection::aggregate(). This method returns a MongoCommandCursor object. This cursor object implements the Iterator interface just like the MongoCursor objects that are returned by the MongoCollection::find() method.

Note: The resulting MongoCommandCursor will inherit this collection's read preference. MongoCommandCursor::setReadPreference() may be used to change the read preference before iterating on the cursor.

Parameters

pipeline

The Aggregation Framework pipeline to execute.

options

Options for the aggregation command. Valid options include:

  • "allowDiskUse"

    Allow aggregation stages to write to temporary files

  • "cursor"

    It is possible to configure how many initial documents the server should return with the first result set. The default initial batch size is 101. You can change it by adding the batchSize option:

    <?php
    $collection    ->aggregateCursor(
            $pipeline,
        [     "cursor" => [ "batchSize" => 4 ] ]
    );

    This option only configures the size of the first batch. To configure the size of future batches, please use the MongoCommandCursor::batchSize() method on the returned MongoCommandCursor object.

  • "explain"

    Return information on the processing of the pipeline. This option may cause the command to return a result document that is unsuitable for constructing a MongoCommandCursor. If you need to use this option, you should consider using MongoCollection::aggregate().

  • "maxTimeMS"

    Specifies a cumulative time limit in milliseconds for processing the operation on the server (does not include idle time). If the operation is not completed by the server within the timeout period, a MongoExecutionTimeoutException will be thrown.

Return Values

Returns a MongoCommandCursor object. Because this implements the Iterator interface you can iterate over each of the results as returned by the command query. The MongoCommandCursor also implements the MongoCursorInterface interface which adds the MongoCommandCursor::batchSize(), MongoCommandCursor::dead(), MongoCommandCursor::info() methods.

Examples

Example #1 MongoCollection::aggregateCursor() example

Finding all of the distinct values for a key.

<?php
$m = new MongoClient;
$db = $m->test;
$people = $db->people;
$people->drop();

$people->insert(array("name" => "Joe", "points" => 4));
$people->insert(array("name" => "Molly", "points" => 43));
$people->insert(array("name" => "Sally", "points" => 22));
$people->insert(array("name" => "Joe", "points" => 22));
$people->insert(array("name" => "Molly", "points" => 87));

$ages = $people->aggregateCursor( [
        [ '$group' => [ '_id' => '$name', 'points' => [ '$sum' => '$points' ] ] ],
        [ '$sort' => [ 'points' => -1 ] ],
] );

foreach ($ages as $person) {
    echo "{$person['_id']}: {$person['points']}\n";
}

?>

The above example will output something similar to:

Molly: 130
Joe: 26
Sally: 22

Example #2 MongoCollection::aggregateCursor() example with different initial batch size

Finding all of the distinct values for a key.

<?php
$m = new MongoClient;
$db = $m->test;
$people = $db->people;
$people->drop();

/* Insert some sample data */
$people->insert(array("name" => "Joe", "points" => 4));
$people->insert(array("name" => "Molly", "points" => 43));
$people->insert(array("name" => "Sally", "points" => 22));
$people->insert(array("name" => "Joe", "points" => 22));
$people->insert(array("name" => "Molly", "points" => 87));

/* Run the command cursor */
$ages = $people->aggregateCursor(
    [
        [ '$group' => [ '_id' => '$name', 'points' => [ '$sum' => '$points' ] ] ],
        [ '$sort' => [ 'points' => -1 ] ],
    ],
    [ "cursor" => [ "batchSize" => 4 ] ]
);

foreach ($ages as $person) {
    echo "{$person['_id']}: {$person['points']}\n";
}

?>

The above example will output something similar to:

Molly: 130
Joe: 26
Sally: 22

See Also

  • MongoDB::command() - Execute a database command
  • MongoCommandCursor
  • MongoCommandCursor::batchSize() - Limits the number of elements returned in one batch
  • MongoCollection::aggregate() - Perform an aggregation using the aggregation framework
  • The MongoDB » aggregation framework


Inserts multiple documents into this collection

  • « MongoCollection::aggregateCursor
  • MongoCollection::__construct »
  • PHP Manual
  • MongoCollection
  • Inserts multiple documents into this collection

MongoCollection::batchInsert

(PECL mongo >=0.9.0)

MongoCollection::batchInsert — Inserts multiple documents into this collection

Description

public MongoCollection::batchInsert ( array $a [, array $options = array() ] ) : mixed

Parameters

a

An array of arrays or objects. If any objects are used, they may not have protected or private properties.

Note:

If the documents to insert do not have an _id key or property, a new MongoId instance will be created and assigned to it. See MongoCollection::insert() for additional information on this behavior.

options

An array of options for the batch of insert operations. Currently available options include:

  • "continueOnError"

    Boolean, defaults to FALSE. If set, the database will not stop processing a bulk insert if one fails (eg due to duplicate IDs). This makes bulk insert behave similarly to a series of single inserts, except that calling MongoDB::lastError() will have an error set if any insert fails, not just the last one. If multiple errors occur, only the most recent will be reported by MongoDB::lastError().

    Note:

    Please note that continueOnError affects errors on the database side only. If you try to insert a document that has errors (for example it contains a key with an empty name), then the document is not even transferred to the database as the driver detects this error and bails out. continueOnError has no effect on errors detected in the documents by the driver.

  • "fsync"

    Boolean, defaults to FALSE. If journaling is enabled, it works exactly like "j". If journaling is not enabled, the write operation blocks until it is synced to database files on disk. If TRUE, an acknowledged insert is implied and this option will override setting "w" to 0.

    Note: If journaling is enabled, users are strongly encouraged to use the "j" option instead of "fsync". Do not use "fsync" and "j" simultaneously, as that will result in an error.

  • "j"

    Boolean, defaults to FALSE. Forces the write operation to block until it is synced to the journal on disk. If TRUE, an acknowledged write is implied and this option will override setting "w" to 0.

    Note: If this option is used and journaling is disabled, MongoDB 2.6+ will raise an error and the write will fail; older server versions will simply ignore the option.

  • "socketTimeoutMS"

    This option specifies the time limit, in milliseconds, for socket communication. If the server does not respond within the timeout period, a MongoCursorTimeoutException will be thrown and there will be no way to determine if the server actually handled the write or not. A value of -1 may be specified to block indefinitely. The default value for MongoClient is 30000 (30 seconds).

  • "w"

    See Write Concerns. The default value for MongoClient is 1.

  • "wTimeoutMS"

    This option specifies the time limit, in milliseconds, for write concern acknowledgement. It is only applicable when "w" is greater than 1, as the timeout pertains to replication. If the write concern is not satisfied within the time limit, a MongoCursorException will be thrown. A value of 0 may be specified to block indefinitely. The default value for MongoClient is 10000 (ten seconds).

The following options are deprecated and should no longer be used:

  • "safe"

    Deprecated. Please use the write concern "w" option.

  • "timeout"

    Deprecated alias for "socketTimeoutMS".

  • "wtimeout"

    Deprecated alias for "wTimeoutMS".

Return Values

If the w parameter is set to acknowledge the write, returns an associative array with the status of the inserts ("ok") and any error that may have occurred ("err"). Otherwise, returns TRUE if the batch insert was successfully sent, FALSE otherwise.

Errors/Exceptions

Throws MongoException if any inserted documents are empty or if they contains zero-length keys. Attempting to insert an object with protected and private properties will cause a zero-length key error.

Throws MongoCursorException if the "w" option is set and the write fails.

Throws MongoCursorTimeoutException if the "w" option is set to a value greater than one and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in MongoCollection::$wtimeout is milliseconds.

Changelog

Version | Description
1.5.0 | Added the "wTimeoutMS" option, which replaces "wtimeout". Emits E_DEPRECATED when "wtimeout" is used. Added the "socketTimeoutMS" option, which replaces "timeout". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
1.3.4 | Added "wtimeout" option.
1.3.0 | Added "w" option.
1.2.7 | Added "continueOnError" option.
1.0.9 | Added ability to pass integers to the "safe" option, which previously only accepted booleans. Added "fsync" option.
1.0.5 | Added options parameter.

Examples

Example #1 MongoCollection::batchInsert() example

Batch insertion is a quick way to add many elements to the database at once

<?php

$users = array();
for ($i = 0; $i<100; $i++) {
  $users[] = array('username' => 'user'.$i, 'i' => $i);
}

$mongo = new MongoClient();
$collection = $mongo->my_db->users;
$collection->drop();

$collection->batchInsert($users);

foreach ($users as $user) {
  echo $user['_id']."\n"; // populated with instanceof MongoId
}

$users = $collection->find()->sort(array('i' => 1));
foreach ($users as $user) {
    var_dump($user['username']);
}

?>

The above example will output something similar to:

4bf43ac68ead0e1971000000
4bf43ac68ead0e1971010000
4bf43ac68ead0e1971020000
...
string(5) "user1"
string(5) "user2"
string(5) "user3"
...

Example #2 MongoCollection::batchInsert() example with ignoring errors

<?php

$con = new Mongo;
$db = $con->demo;

$doc1 = array(
        '_id' => new MongoId('4cb4ab6d7addf98506010001'),
        'id' => 1,
        'desc' => "ONE",
);
$doc2 = array(
        '_id' => new MongoId('4cb4ab6d7addf98506010002'),
        'id' => 2,
        'desc' => "TWO",
);
$doc3 = array(
        '_id' => new MongoId('4cb4ab6d7addf98506010002'), // same _id as above
        'id' => 3,
        'desc' => "THREE",
);
$doc4 = array(
        '_id' => new MongoId('4cb4ab6d7addf98506010004'),
        'id' => 4,
        'desc' => "FOUR",
);

$c = $db->selectCollection('c');
$c->batchInsert(
    array($doc1, $doc2, $doc3, $doc4),
    array('continueOnError' => true)
);

$docs = $c->find();
foreach ($docs as $doc) {
    var_dump($doc['desc']);
}
?>

The above example will output something similar to:

string(3) "ONE"
string(3) "TWO"
string(4) "FOUR"

See Also

  • MongoCollection::insert() - Inserts a document into the collection
  • MongoCollection::update() - Update records based on a given criteria
  • MongoCollection::find() - Queries this collection, returning a MongoCursor for the result set
  • MongoCollection::remove() - Remove records from this collection
  • MongoDB core docs on » insert.


Creates a new collection

  • « MongoCollection::batchInsert
  • MongoCollection::count »
  • PHP Manual
  • MongoCollection
  • Creates a new collection

MongoCollection::__construct

(PECL mongo >=0.9.0)

MongoCollection::__construct — Creates a new collection

Description

public MongoCollection::__construct ( MongoDB $db , string $name )

Parameters

MongoDB db

Parent database.

name

Name for this collection.

Return Values

Returns a new collection object.

Errors/Exceptions

Throws default exception if the collection name is invalid.


Counts the number of documents in this collection

  • « MongoCollection::__construct
  • MongoCollection::createDBRef »
  • PHP Manual
  • MongoCollection
  • Counts the number of documents in this collection

MongoCollection::count

(PECL mongo >=0.9.0)

MongoCollection::count — Counts the number of documents in this collection

Description

 public MongoCollection::count
  ([ array $query = array()
 [, array $options = array()
]] ) : int

Parameters

query

Associative array or object with fields to match.

options

An array of options for the index creation. Currently available options include:

Name | Type | Description
hint mixed

Index to use for the query. If a string is passed, it should correspond to an index name. If an array or object is passed, it should correspond to the specification used to create the index (i.e. the first argument to MongoCollection::createIndex()).

This option is only supported in MongoDB 2.6+.
limit | integer | The maximum number of matching documents to return.
maxTimeMS integer

Specifies a cumulative time limit in milliseconds for processing the operation (does not include idle time). If the operation is not completed within the timeout period, a MongoExecutionTimeoutException will be thrown.

This option is only supported in MongoDB 2.6+.
skip | integer | The number of matching documents to skip before returning results.

Return Values

Returns the number of documents matching the query.

Errors/Exceptions

Throws MongoResultException if the server could not execute the command due to an error.

Throws MongoExecutionTimeoutException if command execution was terminated due to maxTimeMS.

Changelog

Version | Description
1.6.0 | The second parameter is now an options array. Passing limit and skip as the second and third parameters, respectively, is deprecated.
1.0.7 | Added limit and skip as second and third parameters, respectively.

Examples

Example #1 MongoCollection::count() example

<?php

$collection->insert(array('x'=>1));
$collection->insert(array('x'=>2));
$collection->insert(array('x'=>3));

var_dump($collection->count());
var_dump($collection->count(array('x'=>1)));

?>

The above example will output something similar to:

int(3)
int(1)


Creates a database reference

  • « MongoCollection::count
  • MongoCollection::createIndex »
  • PHP Manual
  • MongoCollection
  • Creates a database reference

MongoCollection::createDBRef

(PECL mongo >=0.9.0)

MongoCollection::createDBRef — Creates a database reference

Description

public MongoCollection::createDBRef ( mixed $document_or_id ) : array

Parameters

document_or_id

If an array or object is given, its _id field will be used as the reference ID. If a MongoId or scalar is given, it will be used as the reference ID.

Return Values

Returns a database reference array.

If an array without an _id field was provided as the document_or_id parameter, NULL will be returned.

Examples

Example #1 MongoCollection::createDBRef() example

<?php

$songs = $db->songs;
$playlists = $db->playlists;

// create a reference to a song
$manamana = $songs->findOne(array('title' => 'Ma na ma na'));
$refToSong = $songs->createDBRef($manamana);

// add the reference to my playlist
$playlists->update(array('username' => 'me'), array('$push' => array('songlist' => $refToSong)));

?>

See Also

  • MongoCollection::getDBRef() - Fetches the document pointed to by a database reference


Creates an index on the specified field(s) if it does not already exist

  • « MongoCollection::createDBRef
  • MongoCollection::deleteIndex »
  • PHP Manual
  • MongoCollection
  • Creates an index on the specified field(s) if it does not already exist

MongoCollection::createIndex

(PECL mongo >=1.5.0)

MongoCollection::createIndex — Creates an index on the specified field(s) if it does not already exist

Description

public MongoCollection::createIndex ( array $keys [, array $options = array() ] ) : bool

Creates an index on the specified field(s) if it does not already exist. Fields may be indexed with a direction (e.g. ascending or descending) or a special type (e.g. text, geospatial, hashed).

Note:

This method will use the » createIndexes database command when communicating with MongoDB 2.6+. For previous database versions, the method will perform an insert operation on the special system.indexes collection.

Parameters

keys

An array specifying the index's fields as its keys. For each field, the value is either the index direction or » index type. If specifying direction, specify 1 for ascending or -1 for descending.

options

An array of options for the index creation. We pass all given options straight to the server, but a non-exhaustive list of currently available options include:

  • "unique"

    Specify TRUE to create a unique index. The default value is FALSE. This option applies only to ascending/descending indexes.

    Note:

    When MongoDB indexes a field, if a document does not have a value for the field, a NULL value is indexed. If multiple documents do not contain a field, a unique index will reject all but the first of those documents. The "sparse" option may be used to overcome this, since it will prevent documents without the field from being indexed.

  • "sparse"

    Specify TRUE to create a sparse index, which only indexes documents containing a specified field. The default value is FALSE.

  • "expireAfterSeconds"

    The value of this option should specify the number of seconds after which a document should be considered expired and automatically removed from the collection. This option is only compatible with single-field indexes where the field will contain MongoDate values.

    Note:

    This feature is available in MongoDB 2.2+. See » Expire Data from Collections by Setting TTL for more information.

  • "name"

    A optional name that uniquely identifies the index.

    Note:

    By default, the driver will generate an index name based on the index's field(s) and ordering or type. For example, a compound index array("x" => 1, "y" => -1) would be named "x_1_y_-1" and a geospatial index array("loc" => "2dsphere") would be named "loc_2dsphere". For indexes with many fields, it is possible that the generated name might exceed MongoDB's » limit for index names. The "name" option may be used in that case to supply a shorter name.

  • "background"

    Builds the index in the background so that building an index does not block other database activities. Specify TRUE to build in the background. The default value is FALSE.

    Warning

    Prior to MongoDB 2.6.0, index builds on secondaries were executed as foreground operations, irrespective of this option. See » Building Indexes with Replica Sets for more information.

  • "socketTimeoutMS"

    This option specifies the time limit, in milliseconds, for socket communication. If the server does not respond within the timeout period, a MongoCursorTimeoutException will be thrown and there will be no way to determine if the server actually handled the write or not. A value of -1 may be specified to block indefinitely. The default value for MongoClient is 30000 (30 seconds).

The following option may be used with MongoDB 2.6+:

  • "maxTimeMS"

    Specifies a cumulative time limit in milliseconds for processing the operation on the server (does not include idle time). If the operation is not completed by the server within the timeout period, a MongoExecutionTimeoutException will be thrown.

The following options may be used with MongoDB versions before 2.8:

  • "dropDups"

    Specify TRUE to force creation of a unique index where the collection may contain duplicate values for a key. MongoDB will index the first occurrence of a key and delete all subsequent documents from the collection that contain a duplicate value for that key. The default value is FALSE.

    Warning

    "dropDups" may delete data from your database. Use with extreme caution.

    Note:

    This option is not supported on MongoDB 2.8+. Index creation will fail if the collection contains duplicate values.

The following options may be used with MongoDB versions before 2.6:

  • "w"

    See Write Concerns. The default value for MongoClient is 1.

  • "wTimeoutMS"

    This option specifies the time limit, in milliseconds, for write concern acknowledgement. It is only applicable when "w" is greater than 1, as the timeout pertains to replication. If the write concern is not satisfied within the time limit, a MongoCursorException will be thrown. A value of 0 may be specified to block indefinitely. The default value for MongoClient is 10000 (ten seconds).

The following options are deprecated and should no longer be used:

  • "safe"

    Deprecated. Please use the write concern "w" option.

  • "timeout"

    Deprecated alias for "socketTimeoutMS".

  • "wtimeout"

    Deprecated alias for "wTimeoutMS".

Return Values

Returns an array containing the status of the index creation. The array contains whether the operation succeeded ("ok"), the number of indexes before and after the operation ("numIndexesBefore" and "numIndexesAfter"), and whether the collection that the index belongs to has been created ("createdCollectionAutomatically"). If the index already existed and did not need to be created, a "note" field may be present in lieu of "numIndexesAfter".

With MongoDB 2.4 and earlier, a status document is only returned if the write concern is at least 1. Otherwise, TRUE is returned. The fields in the status document are different, except for the "ok" field, which signals whether the index creation was successful. Additional fields are described in the documentation for MongoCollection::insert().

Errors/Exceptions

Throws MongoException if the index name is longer than 128 bytes, or if the index specification is not an array.

Throws MongoDuplicateKeyException if the server could not create the unique index due to conflicting documents.

Throws MongoResultException if the server could not create the index due to an error.

Throws MongoCursorException if the "w" option is set and the write fails.

Throws MongoCursorTimeoutException if the "w" option is set to a value greater than one and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in MongoCollection::$wtimeout is milliseconds.

Examples

Example #1 MongoCollection::createIndex() example

<?php

$c = new MongoCollection($db, 'foo');

// create an index on 'x' ascending
$c->createIndex(array('x' => 1));

// create a unique index on 'y'
$c->createIndex(array('y' => 1), array('unique' => true));

// create a compound index on 'za' ascending and 'zb' descending
$c->createIndex(array('za' => 1, 'zb' => -1));

?>

Example #2 Geospatial Indexing

Mongo supports geospatial indexes, which allow you to search for documents near a given location or within a shape. The following example creates a geospatial index on the "loc" field:

<?php

$collection->createIndex(array('loc' => '2dsphere'));

?>

Example #3 Drop duplicates example

<?php

$collection->insert(array('username' => 'joeschmoe'));
$collection->insert(array('username' => 'joeschmoe'));

/* Index creation fails, since you cannot create a unique index on a field when
 * duplicates exist.
 */
$collection->createIndex(array('username' => 1), array('unique' => 1));

/* MongoDB will one of the conflicting documents and allow the unique index to
 * be created.
 */
$collection->createIndex(array('username' => 1), array('unique' => 1, 'dropDups' => 1));

/* We now have a unique index and subsequent inserts with the same username will
 * fail.
 */
$collection->insert(array('username' => 'joeschmoe'));

?>

See Also

  • MongoCollection::deleteIndex() - Deletes an index from this collection
  • MongoCollection::deleteIndexes() - Delete all indices for this collection
  • The MongoDB » index and » index type documentation.


Deletes an index from this collection

  • « MongoCollection::createIndex
  • MongoCollection::deleteIndexes »
  • PHP Manual
  • MongoCollection
  • Deletes an index from this collection

MongoCollection::deleteIndex

(PECL mongo >=0.9.0)

MongoCollection::deleteIndex — Deletes an index from this collection

Description

public MongoCollection::deleteIndex ( string|array $keys ) : array

This method is identical to:

<?php

public function deleteIndexes($keys) {
  $indexName = $this->toIndexString($keys);

  return $this->db->command(array(
    "deleteIndexes" => $this->getName(),
    "index" => $indexName,
  ));
}

?>

Each index is given a unique name when it is created. This is often generated by the driver based on the index key(s) and order/type, but custom names may also be specified with MongoCollection::createIndex()'s "name" option).

Unfortunately, MongoCollection::deleteIndex() cannot delete custom-named indexes due to a backwards compatibility issue. When a string argument is provided, it is assumed to be the single field name in an ascending index (e.g. the name "x_1" would be used for the argument "x"). If an array or object is provided, an index name is generated just as if that argument was passed to MongoCollection::createIndex().

In order to delete a custom-named index with the PHP driver, the deleteIndexes database command must be used. For instance, an index named "myIndex" could be deleted with the PHP driver by running:

<?php

$db->command(array(
  "deleteIndexes" => $collection->getName(),
  "index" => "myIndex",
));

?>

To determine the name of an index with the PHP driver, you can query the system.indexes collection of a database and look for the "name" field of each result. The "ns" field will indicate the collection to which each index belongs.

Parameters

keys

An array specifying the index's fields as its keys. For each field, the value is either the index direction or » index type. If specifying direction, specify 1 for ascending or -1 for descending.

If a string is provided, it is assumed to be the single field name in an ascending index.

Return Values

Returns the database response.

Examples

Example #1 MongoCollection::deleteIndex() example

This example passes the function string and array parameters.

<?php

$m = new MongoClient();
$c = $m->example->indices;

// create and remove a simple index
$c->createIndex(array("i"=>1));
$c->deleteIndex("i");

// create and remove a multi-key index
$c->ensureIndex(array("j" => 1, "k" => 1));
$c->deleteIndex(array("j" => 1, "k" => 1));

?>

See Also

  • MongoCollection::createIndex() - Creates an index on the specified field(s) if it does not already exist
  • MongoCollection::deleteIndexes() - Delete all indices for this collection
  • MongoCollection::toIndexString() - Converts keys specifying an index to its identifying string
  • The MongoDB » index and » index type documentation.


Delete all indices for this collection

  • « MongoCollection::deleteIndex
  • MongoCollection::distinct »
  • PHP Manual
  • MongoCollection
  • Delete all indices for this collection

MongoCollection::deleteIndexes

(PECL mongo >=0.9.0)

MongoCollection::deleteIndexes — Delete all indices for this collection

Description

public MongoCollection::deleteIndexes ( void ) : array

Parameters

This function has no parameters.

Return Values

Returns the database response.

Examples

Example #1 MongoCollection::deleteIndexes() example

This example demonstrates how to delete all indexes from a collection and the response to expect.

<?php

$collection = $mongo->my_db->articles;
$response = $collection->deleteIndexes();
print_r($response);

?>

The above example will output something similar to:

Array
(
    [nIndexesWas] => 1
    [msg] => all indexes deleted for collection
    [ok] => 1
)

See Also

  • MongoCollection::createIndex() - Creates an index on the specified field(s) if it does not already exist
  • MongoCollection::deleteIndex() - Deletes an index from this collection


Retrieve a list of distinct values for the given key across a collection

  • « MongoCollection::deleteIndexes
  • MongoCollection::drop »
  • PHP Manual
  • MongoCollection
  • Retrieve a list of distinct values for the given key across a collection

MongoCollection::distinct

(PECL mongo >=1.2.11)

MongoCollection::distinct — Retrieve a list of distinct values for the given key across a collection

Description

public MongoCollection::distinct ( string $key [, array $query ] ) : array

The distinct command returns a list of distinct values for the given key across a collection.

Parameters

key

The key to use.

query

An optional query parameters

Return Values

Returns an array of distinct values, or FALSE on failure

Examples

Example #1 MongoCollection::distinct() example

<?php
$m = new Mongo;
$db = $m->selectDB("test");
$db->dropCollection("distinct");
$c = $db->distinct;

$c->insert(array("stuff" => "bar", "zip-code" => 10010));
$c->insert(array("stuff" => "foo", "zip-code" => 10010));
$c->insert(array("stuff" => "bar", "zip-code" => 99701), array("w" => 1));

$retval = $c->distinct("zip-code");
var_dump($retval);

$retval = $c->distinct("zip-code", array("stuff" => "foo"));
var_dump($retval);

$retval = $c->distinct("zip-code", array("stuff" => "bar"));
var_dump($retval);

?>

The above example will output:

array(2) {
  [0]=>
  int(10010)
  [1]=>
  int(99701)
}
array(1) {
  [0]=>
  int(10010)
}
array(2) {
  [0]=>
  int(10010)
  [1]=>
  int(99701)
}

Example #2 MongoCollection::distinct() example on a embedded document

<?php
$c->insert(array("user" => array("points" => 25)));
$c->insert(array("user" => array("points" => 31)));
$c->insert(array("user" => array("points" => 25)));

$retval = $c->distinct("user.points");
var_dump($retval);

$retval = $c->distinct("user.nonexisting");
var_dump($retval);
?>

The above example will output:

array(2) {
  [0]=>
  int(25)
  [1]=>
  int(31)
}
array(0) {
}


Drops this collection

  • « MongoCollection::distinct
  • MongoCollection::ensureIndex »
  • PHP Manual
  • MongoCollection
  • Drops this collection

MongoCollection::drop

(PECL mongo >=0.9.0)

MongoCollection::drop — Drops this collection

Description

public MongoCollection::drop ( void ) : array

Drops this collection and deletes its indices.

Parameters

This function has no parameters.

Return Values

Returns the database response.

Examples

Example #1 MongoCollection::drop() example

This example demonstrates how to drop a collection and the response to expect.

<?php

$collection = $mongo->my_db->articles;
$response = $collection->drop();
print_r($response);

?>

The above example will output something similar to:

Array
(
    [nIndexesWas] => 1
    [msg] => all indexes deleted for collection
    [ns] => my_db.articles
    [ok] => 1
)


Creates an index on the specified field(s) if it does not already exist

  • « MongoCollection::drop
  • MongoCollection::find »
  • PHP Manual
  • MongoCollection
  • Creates an index on the specified field(s) if it does not already exist

MongoCollection::ensureIndex

(PECL mongo >=0.9.0)

MongoCollection::ensureIndex — Creates an index on the specified field(s) if it does not already exist

Description

public MongoCollection::ensureIndex ( string|array $key|keys [, array $options = array() ] ) : bool
Warning

This method is deprecated since version 1.5.0. Please use MongoCollection::createIndex() instead.

Creates an index on the specified field(s) if it does not already exist. Fields may be indexed with a direction (e.g. ascending or descending) or a special type (e.g. text, geospatial, hashed).

Note:

This method will use the » createIndexes database command when communicating with MongoDB 2.6+. For previous database versions, the method will perform an insert operation on the special system.indexes collection.

Parameters

keys

An array specifying the index's fields as its keys. For each field, the value is either the index direction or » index type. If specifying direction, specify 1 for ascending or -1 for descending.

options

An array of options for the index creation. Currently available options include:

  • "unique"

    Specify TRUE to create a unique index. The default value is FALSE. This option applies only to ascending/descending indexes.

    Note:

    When MongoDB indexes a field, if a document does not have a value for the field, a NULL value is indexed. If multiple documents do not contain a field, a unique index will reject all but the first of those documents. The "sparse" option may be used to overcome this, since it will prevent documents without the field from being indexed.

  • "sparse"

    Specify TRUE to create a sparse index, which only indexes documents containing a specified field. The default value is FALSE.

  • "expireAfterSeconds"

    The value of this option should specify the number of seconds after which a document should be considered expired and automatically removed from the collection. This option is only compatible with single-field indexes where the field will contain MongoDate values.

    Note:

    This feature is available in MongoDB 2.2+. See » Expire Data from Collections by Setting TTL for more information.

  • "name"

    A optional name that uniquely identifies the index.

    Note:

    By default, the driver will generate an index name based on the index's field(s) and ordering or type. For example, a compound index array("x" => 1, "y" => -1) would be named "x_1_y_-1" and a geospatial index array("loc" => "2dsphere") would be named "loc_2dsphere". For indexes with many fields, it is possible that the generated name might exceed MongoDB's » limit for index names. The "name" option may be used in that case to supply a shorter name.

  • "background"

    Builds the index in the background so that building an index does not block other database activities. Specify TRUE to build in the background. The default value is FALSE.

    Warning

    Prior to MongoDB 2.6.0, index builds on secondaries were executed as foreground operations, irrespective of this option. See » Building Indexes with Replica Sets for more information.

  • "socketTimeoutMS"

    This option specifies the time limit, in milliseconds, for socket communication. If the server does not respond within the timeout period, a MongoCursorTimeoutException will be thrown and there will be no way to determine if the server actually handled the write or not. A value of -1 may be specified to block indefinitely. The default value for MongoClient is 30000 (30 seconds).

The following option may be used with MongoDB 2.6+:

  • "maxTimeMS"

    Specifies a cumulative time limit in milliseconds for processing the operation on the server (does not include idle time). If the operation is not completed by the server within the timeout period, a MongoExecutionTimeoutException will be thrown.

The following options may be used with MongoDB versions before 2.8:

  • "dropDups"

    Specify TRUE to force creation of a unique index where the collection may contain duplicate values for a key. MongoDB will index the first occurrence of a key and delete all subsequent documents from the collection that contain a duplicate value for that key. The default value is FALSE.

    Warning

    "dropDups" may delete data from your database. Use with extreme caution.

    Note:

    This option is not supported on MongoDB 2.8+. Index creation will fail if the collection contains duplicate values.

The following options may be used with MongoDB versions before 2.6:

  • "w"

    See Write Concerns. The default value for MongoClient is 1.

  • "wTimeoutMS"

    This option specifies the time limit, in milliseconds, for write concern acknowledgement. It is only applicable when "w" is greater than 1, as the timeout pertains to replication. If the write concern is not satisfied within the time limit, a MongoCursorException will be thrown. A value of 0 may be specified to block indefinitely. The default value for MongoClient is 10000 (ten seconds).

The following options are deprecated and should no longer be used:

  • "safe"

    Deprecated. Please use the write concern "w" option.

  • "timeout"

    Deprecated alias for "socketTimeoutMS".

  • "wtimeout"

    Deprecated alias for "wTimeoutMS".

Return Values

Returns an array containing the status of the index creation. The array contains whether the operation succeeded ("ok"), the number of indexes before and after the operation ("numIndexesBefore" and "numIndexesAfter"), and whether the collection that the index belongs to has been created ("createdCollectionAutomatically"). If the index already existed and did not need to be created, a "note" field may be present in lieu of "numIndexesAfter".

With MongoDB 2.4 and earlier, a status document is only returned if the write concern is at least 1. Otherwise, TRUE is returned. The fields in the status document are different, except for the "ok" field, which signals whether the index creation was successful. Additional fields are described in the documentation for MongoCollection::insert().

Changelog

Version | Description
1.5.0 | Renamed the "wtimeout" option to "wTimeoutMS". Emits E_DEPRECATED when "wtimeout" is used. Renamed the "timeout" option to "socketTimeoutMS". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
1.3.4 | Added "wtimeout" option.
1.3.0 | Added "w" option. The options parameter no longer accepts a boolean to signify a unique index. Instead, this now has to be done with array('unique' => true).
1.2.11 | Emits E_DEPRECATED when options is scalar.
1.2.0 | Added "timeout" option.
1.0.11 | The "safe" option will trigger a primary failover, if necessary. MongoException will be thrown if the index name (either generated or set) is longer than 128 bytes.
1.0.5 | Added the "name" option to override index name creation.
1.0.2 | Changed options parameter from boolean to array. Pre-1.0.2, the second parameter was an optional boolean value specifying a unique index.

Errors/Exceptions

Throws MongoException if the index name is longer than 128 bytes, or if the index specification is not an array.

Throws MongoDuplicateKeyException if the server could not create the unique index due to conflicting documents.

Throws MongoResultException if the server could not create the index due to an error.

Throws MongoCursorException if the "w" option is set and the write fails.

Throws MongoCursorTimeoutException if the "w" option is set to a value greater than one and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in MongoCollection::$wtimeout is milliseconds.

Examples

Example #1 MongoCollection::ensureIndex() example

<?php

$c = new MongoCollection($db, 'foo');

// create an index on 'x' ascending
$c->ensureIndex(array('x' => 1));

// create a unique index on 'y'
$c->ensureIndex(array('y' => 1), array('unique' => true));

// create a compound index on 'za' ascending and 'zb' descending
$c->ensureIndex(array('za' => 1, 'zb' => -1));

?>

Example #2 Geospatial Indexing

Mongo supports geospatial indexes, which allow you to search for documents near a given location or within a shape. The following example creates a geospatial index on the "loc" field:

<?php

$collection->ensureIndex(array('loc' => '2dsphere'));

?>

Example #3 Drop duplicates example

<?php

$collection->insert(array('username' => 'joeschmoe'));
$collection->insert(array('username' => 'joeschmoe'));

/* Index creation fails, since you cannot create a unique index on a field when
 * duplicates exist.
 */
$collection->ensureIndex(array('username' => 1), array('unique' => 1));

/* MongoDB will one of the conflicting documents and allow the unique index to
 * be created.
 */
$collection->ensureIndex(array('username' => 1), array('unique' => 1, 'dropDups' => 1));

/* We now have a unique index and subsequent inserts with the same username will
 * fail.
 */
$collection->insert(array('username' => 'joeschmoe'));

?>

See Also

  • MongoCollection::createIndex() - Creates an index on the specified field(s) if it does not already exist
  • MongoCollection::deleteIndex() - Deletes an index from this collection
  • MongoCollection::deleteIndexes() - Delete all indices for this collection
  • The MongoDB » index and » index type documentation.


Queries this collection, returning a MongoCursor for the result set

  • « MongoCollection::ensureIndex
  • MongoCollection::findAndModify »
  • PHP Manual
  • MongoCollection
  • Queries this collection, returning a MongoCursor for the result set

MongoCollection::find

(PECL mongo >=0.9.0)

MongoCollection::find — Queries this collection, returning a MongoCursor for the result set

Description

 public MongoCollection::find
  ([ array $query = array()
 [, array $fields = array()
]] ) : MongoCursor

Parameters

query

The fields for which to search. MongoDB's query language is quite extensive. The PHP driver will in almost all cases pass the query straight through to the server, so reading the MongoDB core docs on » find is a good idea.

Warning

Please make sure that for all special query operators (starting with $) you use single quotes so that PHP doesn't try to replace "$exists" with the value of the variable $exists.

fields

Fields of the results to return. The array is in the format array('fieldname' => true, 'fieldname2' => true). The _id field is always returned.

Return Values

Returns a cursor for the search results.

Examples

Example #1 MongoCollection::find() example

This example demonstrates basic search options.

<?php

$m = new MongoClient();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'produce');

// search for fruits
$fruitQuery = array('Type' => 'Fruit');

$cursor = $collection->find($fruitQuery);
foreach ($cursor as $doc) {
    var_dump($doc);
}

// search for produce that is sweet. Taste is a child of Details.
$sweetQuery = array('Details.Taste' => 'Sweet');
echo "Sweet\n";
$cursor = $collection->find($sweetQuery);
foreach ($cursor as $doc) {
    var_dump($doc);
}

?>

The above example will output:

array(4) {
  ["_id"]=>
  object(MongoId)#7 (1) {
    ["$id"]=>
    string(24) "50a87dd084f045a19b220dd6"
  }
  ["Name"]=>
  string(5) "Apple"
  ["Type"]=>
  string(5) "Fruit"
  ["Details"]=>
  array(2) {
    ["Taste"]=>
    string(5) "Sweet"
    ["Colour"]=>
    string(3) "Red"
  }
}
array(4) {
  ["_id"]=>
  object(MongoId)#8 (1) {
    ["$id"]=>
    string(24) "50a87de084f045a19b220dd7"
  }
  ["Name"]=>
  string(5) "Lemon"
  ["Type"]=>
  string(5) "Fruit"
  ["Details"]=>
  array(2) {
    ["Taste"]=>
    string(4) "Sour"
    ["Colour"]=>
    string(5) "Green"
  }
}

Sweet:
array(4) {
  ["_id"]=>
  object(MongoId)#7 (1) {
    ["$id"]=>
    string(24) "50a87dd084f045a19b220dd6"
  }
  ["Name"]=>
  string(5) "Apple"
  ["Type"]=>
  string(5) "Fruit"
  ["Details"]=>
  array(2) {
    ["Taste"]=>
    string(5) "Sweet"
    ["Colour"]=>
    string(3) "Red"
  }
}

See MongoCursor for more information how to work with cursors.

Example #2 MongoCollection::find() example

This example demonstrates how to search for a range.

<?php

$m = new MongoClient();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'phpmanual');

// search for documents where 5 < x < 20
$rangeQuery = array('x' => array( '$gt' => 5, '$lt' => 20 ));

$cursor = $collection->find($rangeQuery);
foreach ($cursor as $doc) {
    var_dump($doc);
}

?>

The above example will output:

array(2) {
  ["_id"]=>
  object(MongoId)#10 (1) {
    ["$id"]=>
    string(24) "4ebc3e3710b89f2349000000"
  }
  ["x"]=>
  int(12)
}
array(2) {
  ["_id"]=>
  object(MongoId)#11 (1) {
    ["$id"]=>
    string(24) "4ebc3e3710b89f2349000001"
  }
  ["x"]=>
  int(12)
}

See MongoCursor for more information how to work with cursors.

Example #3 MongoCollection::find() example using $where

This example demonstrates how to search a collection using javascript code to reduce the resultset.

<?php

$m = new MongoClient();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'phpmanual');

$js = "function() {
    return this.name == 'Joe' || this.age == 50;
}";
$cursor = $collection->find(array('$where' => $js));
foreach ($cursor as $doc) {
    var_dump($doc);
}

?>

The above example will output:

array(3) {
  ["_id"]=>
  object(MongoId)#7 (1) {
    ["$id"]=>
    string(24) "4ebc3e3710b89f2349000002"
  }
  ["name"]=>
  string(3) "Joe"
  ["age"]=>
  int(20)
}

Example #4 MongoCollection::find() example using $in

This example demonstrates how to search a collection using the $in operator.

<?php

$m = new MongoClient();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'phpmanual');

$cursor = $collection->find(array(
    'name' => array('$in' => array('Joe', 'Wendy'))
));

?>

The above example will output:

array(3) {
  ["_id"]=>
  object(MongoId)#7 (1) {
    ["$id"]=>
    string(24) "4ebc3e3710b89f2349000002"
  }
  ["name"]=>
  string(3) "Joe"
  ["age"]=>
  int(20)
}

Example #5 Getting results as an array

This returns a MongoCursor. Often, when people are starting out, they are more comfortable using an array. To turn a cursor into an array, use the iterator_to_array() function.

<?php

$m = new MongoClient();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'phpmanual');

$cursor = $collection->find();
$array = iterator_to_array($cursor);

?>

The above example will output:

array(3) {
  ["4ebc40af10b89f5149000000"]=>
  array(2) {
    ["_id"]=>
    object(MongoId)#6 (1) {
      ["$id"]=>
      string(24) "4ebc40af10b89f5149000000"
    }
    ["x"]=>
    int(12)
  }
  ["4ebc40af10b89f5149000001"]=>
  array(2) {
    ["_id"]=>
    object(MongoId)#11 (1) {
      ["$id"]=>
      string(24) "4ebc40af10b89f5149000001"
    }
    ["x"]=>
    int(12)
  }
  ["4ebc40af10b89f5149000002"]=>
  array(3) {
    ["_id"]=>
    object(MongoId)#12 (1) {
      ["$id"]=>
      string(24) "4ebc40af10b89f5149000002"
    }
    ["name"]=>
    string(3) "Joe"
    ["age"]=>
    int(20)
  }
}

Using iterator_to_array() forces the driver to load all of the results into memory, so do not do this for result sets that are larger than memory!

Also, certain system collections do not have an _id field. If you are dealing with a collection that might have documents without _ids, pass FALSE as the second argument to iterator_to_array() (so that it will not try to use the non-existent _id values as keys).

See Also

  • MongoCollection::findOne() - Queries this collection, returning a single element
  • MongoCollection::insert() - Inserts a document into the collection
  • MongoDB core docs on » find.


Update a document and return it

  • « MongoCollection::find
  • MongoCollection::findOne »
  • PHP Manual
  • MongoCollection
  • Update a document and return it

MongoCollection::findAndModify

(PECL mongo >=1.3.0)

MongoCollection::findAndModify — Update a document and return it

Description

public MongoCollection::findAndModify ( array $query [, array $update [, array $fields [, array $options ]]] ) : array

The findAndModify command atomically modifies and returns a single document. By default, the returned document does not include the modifications made on the update. To return the document with the modifications made on the update, use the new option.

Parameters

query

The query criteria to search for.

update

The update criteria.

fields

Optionally only return these fields.

options

An array of options to apply, such as remove the match document from the DB and return it.

Option | Description
sort array | Determines which document the operation will modify if the query selects multiple documents. findAndModify will modify the first document in the sort order specified by this argument.
remove boolean | Optional if update field exists. When TRUE, removes the selected document. The default is FALSE.
update array | Optional if remove field exists. Performs an update of the selected document.
new boolean | Optional. When TRUE, returns the modified document rather than the original. The findAndModify method ignores the new option for remove operations. The default is FALSE.
upsert boolean | Optional. Used in conjunction with the update field. When TRUE, the findAndModify command creates a new document if the query returns no documents. The default is false. In MongoDB 2.2, the findAndModify command returns NULL when upsert is TRUE.

Return Values

Returns the original document, or the modified document when new is set.

Errors/Exceptions

Throws MongoResultException on failure.

Examples

Example #1 MongoCollection::findAndModify() example

<?php
$m = new Mongo;
$col = $m->selectDB("test")->jobs;

$col->insert(array(
     "name" => "Next promo",
     "inprogress" => false,
     "priority" => 0,
     "tasks" => array( "select product", "add inventory", "do placement"),
) );

$col->insert(array(
     "name" => "Biz report",
     "inprogress" => false,
     "priority" => 1,
     "tasks" => array( "run sales report", "email report" )
) );

$col->insert(array(
     "name" => "Biz report",
     "inprogress" => false,
     "priority" => 2,
     "tasks" => array( "run marketing report", "email report" )
    ),
    array("w" => 1)
);

$retval = $col->findAndModify(
     array("inprogress" => false, "name" => "Biz report"),
     array('$set' => array('inprogress' => true, "started" => new MongoDate())),
     null,
     array(
        "sort" => array("priority" => -1),
        "new" => true,
    )
);

var_dump($retval);
?>

The above example will output something similar to:

array(6) {
  ["_id"]=>
  object(MongoId)#7 (1) {
    ["$id"]=>
    string(24) "5091b5b244415e8cc3000002"
  }
  ["inprogress"]=>
  bool(true)
  ["name"]=>
  string(10) "Biz report"
  ["priority"]=>
  int(2)
  ["started"]=>
  object(MongoDate)#8 (2) {
    ["sec"]=>
    int(1351726514)
    ["usec"]=>
    int(925000)
  }
  ["tasks"]=>
  array(2) {
    [0]=>
    string(20) "run marketing report"
    [1]=>
    string(12) "email report"
  }
}

Example #2 MongoCollection::findAndModify() error handling

<?php
$m = new Mongo;
$col = $m->selectDB("test")->jobs;
try {
    $retval = $col->findAndModify(
         array("inprogress" => false, "name" => "Next promo"),
         array('$pop' => array("tasks" => -1)),
         array("tasks" => array('$pop' => array("stuff"))),
         array("new" => true)
    );
} catch(MongoResultException $e) {
    echo $e->getCode(), " : ", $e->getMessage(), "\n";
    var_dump($e->getDocument());
}

?>

The above example will output something similar to:

13097 : exception: Unsupported projection option: $pop
array(3) {
  ["errmsg"]=>
  string(46) "exception: Unsupported projection option: $pop"
  ["code"]=>
  int(13097)
  ["ok"]=>
  float(0)
}

See Also

  • The MongoDB » findAndModify command docs


Queries this collection, returning a single element

  • « MongoCollection::findAndModify
  • MongoCollection::__get »
  • PHP Manual
  • MongoCollection
  • Queries this collection, returning a single element

MongoCollection::findOne

(PECL mongo >=0.9.0)

MongoCollection::findOne — Queries this collection, returning a single element

Description

 public MongoCollection::findOne
  ([ array $query = array()
 [, array $fields = array()
 [, array $options = array()
]]] ) : array

As opposed to MongoCollection::find(), this method will return only the first result from the result set, and not a MongoCursor that can be iterated over.

Parameters

query

The fields for which to search. MongoDB's query language is quite extensive. The PHP driver will in almost all cases pass the query straight through to the server, so reading the MongoDB core docs on » find is a good idea.

Warning

Please make sure that for all special query operaters (starting with $) you use single quotes so that PHP doesn't try to replace "$exists" with the value of the variable $exists.

fields

Fields of the results to return. The array is in the format array('fieldname' => true, 'fieldname2' => true). The _id field is always returned.

options

This parameter is an associative array of the form array("name" => <value>, ...). Currently supported options are:

  • "maxTimeMS"

    Specifies a cumulative time limit in milliseconds for processing the operation on the server (does not include idle time). If the operation is not completed by the server within the timeout period, a MongoExecutionTimeoutException will be thrown.

Return Values

Returns record matching the search or NULL.

Errors/Exceptions

Throws MongoConnectionException if it cannot reach the database.

Changelog

Version | Description
1.5.0 | Added optional options argument.

Examples

Example #1 MongoCollection::findOne() document by its id.

This example demonstrates how to find a single document in a collection by its id.

<?php

$articles = $mongo->my_db->articles;

$article = $articles->findOne(array('_id' => new MongoId('47cc67093475061e3d9536d2')));

?>

Example #2 MongoCollection::findOne() document by some condition.

This example demonstrates how to find a single document in a collection by some condition and limiting the returned fields.

<?php

$users = $mongo->my_db->users;
$user = $users->findOne(array('username' => 'jwage'), array('password'));
print_r($user);

?>

The above example will output something similar to:

Array
(
    [_id] => MongoId Object
        (
        )

    [password] => test
)

Notice how even though the document does have a username field, we limited the results to only contain the password field.

See Also

  • MongoCollection::find() - Queries this collection, returning a MongoCursor for the result set
  • MongoCollection::insert() - Inserts a document into the collection
  • MongoDB core docs on » find.


Gets a collection

  • « MongoCollection::findOne
  • MongoCollection::getDBRef »
  • PHP Manual
  • MongoCollection
  • Gets a collection

MongoCollection::__get

(PECL mongo >=1.0.2)

MongoCollection::__get — Gets a collection

Description

public MongoCollection::__get ( string $name ) : MongoCollection

A concise syntax for getting a collection with a dot-separated name. If a collection name contains strange characters, you may have to use MongoDB::selectCollection() instead.

<?php

$mongo = new MongoClient();

// the following two lines are equivalent
$collection = $mongo->selectDB("foo")->selectCollection("bar.baz");
$collection = $mongo->foo->bar->baz;

?>

Parameters

name

The next string in the collection name.

Return Values

Returns the collection.


Fetches the document pointed to by a database reference

  • « MongoCollection::__get
  • MongoCollection::getIndexInfo »
  • PHP Manual
  • MongoCollection
  • Fetches the document pointed to by a database reference

MongoCollection::getDBRef

(PECL mongo >=0.9.0)

MongoCollection::getDBRef — Fetches the document pointed to by a database reference

Description

public MongoCollection::getDBRef ( array $ref ) : array

Parameters

ref

A database reference.

Return Values

Returns the database document pointed to by the reference.

Examples

Example #1 MongoCollection::getDBRef() example

<?php

$playlists = $db->playlists;

$myList = $playlists->findOne(array('username' => 'me'));

// fetch each song in the playlist
foreach ($myList['songlist'] as $songRef) {
    $song = $playlists->getDBRef($songRef);
    echo $song['title'] . "\n";
}

?>

The above example will output something similar to:

Dazed and Confused
Ma na ma na
Bohemian Rhapsody

In the above example each $songRef looks something like the following:
    Array
    (
        [$ref] => songs
        [$id] => 49902cde5162504500b45c2c
    )

See Also

  • MongoCollection::createDBRef() - Creates a database reference


Returns information about indexes on this collection

  • « MongoCollection::getDBRef
  • MongoCollection::getName »
  • PHP Manual
  • MongoCollection
  • Returns information about indexes on this collection

MongoCollection::getIndexInfo

(PECL mongo >=0.9.0)

MongoCollection::getIndexInfo — Returns information about indexes on this collection

Description

public MongoCollection::getIndexInfo ( void ) : array

Parameters

This function has no parameters.

Return Values

This function returns an array in which each element describes an index. Elements will contain the values name for the name of the index, ns for the namespace (a combination of the database and collection name), and key for a list of all fields in the index and their ordering. Additional values may be present for special indexes, such as unique or sparse.

Examples

Example #1 MongoCollection::getIndexInfo() example

<?php

$m = new MongoClient();
$c = $m->selectCollection('test', 'venues');
var_dump($c->getIndexInfo());

?>

The above example will output something similar to:

array(4) {
  [0]=>
  array(4) {
    ["v"]=>
    int(1)
    ["key"]=>
    array(1) {
      ["_id"]=>
      int(1)
    }
    ["name"]=>
    string(4) "_id_"
    ["ns"]=>
    string(11) "test.venues"
  }
  [1]=>
  array(4) {
    ["v"]=>
    int(1)
    ["key"]=>
    array(1) {
      ["name"]=>
      float(1)
    }
    ["name"]=>
    string(6) "name_1"
    ["ns"]=>
    string(11) "test.venues"
  }
  [2]=>
  array(4) {
    ["v"]=>
    int(1)
    ["key"]=>
    array(2) {
      ["type"]=>
      float(1)
      ["createdAt"]=>
      float(-1)
    }
    ["name"]=>
    string(19) "type_1_createdAt_-1"
    ["ns"]=>
    string(11) "test.venues"
  }
  [3]=>
  array(5) {
    ["v"]=>
    int(1)
    ["key"]=>
    array(1) {
      ["location"]=>
      string(8) "2dsphere"
    }
    ["name"]=>
    string(17) "location_2dsphere"
    ["ns"]=>
    string(11) "test.venues"
    ["2dsphereIndexVersion"]=>
    int(2)
  }
}

See Also

MongoDB core docs on » vanilla indexes and » geospatial indexes.


Returns this collection's name

  • « MongoCollection::getIndexInfo
  • MongoCollection::getReadPreference »
  • PHP Manual
  • MongoCollection
  • Returns this collection's name

MongoCollection::getName

(PECL mongo >=0.9.0)

MongoCollection::getName — Returns this collection's name

Description

public MongoCollection::getName ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns the name of this collection.

Examples

Example #1 MongoCollection::getName() example

<?php

$m = new MongoClient();
$c = $m->foo->bar->baz;

echo "Working with collection " . $c->getName() . ".\n";

// the full namespace is given by the MongoCollection::__toString() method
echo "Working in namespace $c.\n";

?>

The above example will output something similar to:

Working with collection bar.baz.
Working in namespace foo.bar.baz.


Get the read preference for this collection

  • « MongoCollection::getName
  • MongoCollection::getSlaveOkay »
  • PHP Manual
  • MongoCollection
  • Get the read preference for this collection

MongoCollection::getReadPreference

(PECL mongo >=1.3.0)

MongoCollection::getReadPreference — Get the read preference for this collection

Description

public MongoCollection::getReadPreference ( void ) : array

Parameters

This function has no parameters.

Return Values

This function returns an array describing the read preference. The array contains the values type for the string read preference mode (corresponding to the MongoClient constants), and tagsets containing a list of all tag set criteria. If no tag sets were specified, tagsets will not be present in the array.

Changelog

Version | Description
1.3.3 | The return value has changed to be consistent with MongoCollection::setReadPreference(). The type value was changed from a number to a string, type_string was removed, and tagsets now expresses tags as key/value pairs instead of colon-delimited strings.

Examples

Example #1 MongoCollection::getReadPreference() return value example

<?php

$m = new MongoClient();
$c = $m->test->users;
$c->setReadPreference(MongoClient::RP_SECONDARY, array(
    array('dc' => 'east', 'use' => 'reporting'),
    array('dc' => 'west'),
    array(),
));
var_dump($c->getReadPreference());
?>

The above example will output:

array(2) {
  ["type"]=>
  string(9) "secondary"
  ["tagsets"]=>
  array(3) {
    [0]=>
    array(2) {
      ["dc"]=>
      string(4) "east"
      ["use"]=>
      string(9) "reporting"
    }
    [1]=>
    array(1) {
      ["dc"]=>
      string(7) "west"
    }
    [2]=>
    array(0) {
    }
  }
}

See Also

  • The read preferences documentation.
  • MongoCollection::setReadPreference() - Set the read preference for this collection


Get slaveOkay setting for this collection

  • « MongoCollection::getReadPreference
  • MongoCollection::getWriteConcern »
  • PHP Manual
  • MongoCollection
  • Get slaveOkay setting for this collection

MongoCollection::getSlaveOkay

(PECL mongo >=1.1.0)

MongoCollection::getSlaveOkay — Get slaveOkay setting for this collection

Description

public MongoCollection::getSlaveOkay ( void ) : bool

See the query section of this manual for information on distributing reads to secondaries.

Parameters

This function has no parameters.

Return Values

Returns the value of slaveOkay for this instance.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.

See Also

  • Read Preferences
  • MongoCollection::getReadPreference() - Get the read preference for this collection


Get the write concern for this collection

  • « MongoCollection::getSlaveOkay
  • MongoCollection::group »
  • PHP Manual
  • MongoCollection
  • Get the write concern for this collection

MongoCollection::getWriteConcern

(PECL mongo >=1.5.0)

MongoCollection::getWriteConcern — Get the write concern for this collection

Description

public MongoCollection::getWriteConcern ( void ) : array

Parameters

This function has no parameters.

Return Values

This function returns an array describing the write concern. The array contains the values w for an integer acknowledgement level or string mode, and wtimeout denoting the maximum number of milliseconds to wait for the server to satisfy the write concern.

Examples

Example #1 MongoCollection::getWriteConcern() return value example

<?php

$mc = new MongoClient('mongodb://localhost:27017', array('wTimeoutMS' => 500));
$coll = $mc->selectCollection('test', 'foo');
var_dump($coll->getWriteConcern());

$coll->setWriteConcern(1, 1000);
var_dump($coll->getWriteConcern());
?>

The above example will output:

array(2) {
  ["w"]=>
  int(1)
  ["wtimeout"]=>
  int(500)
}
array(2) {
  ["w"]=>
  int(1)
  ["wtimeout"]=>
  int(1000)
}

See Also

  • The write concern documentation.
  • MongoCollection::setWriteConcern() - Set the write concern for this database


Performs an operation similar to SQL's GROUP BY command

  • « MongoCollection::getWriteConcern
  • MongoCollection::insert »
  • PHP Manual
  • MongoCollection
  • Performs an operation similar to SQL's GROUP BY command

MongoCollection::group

(PECL mongo >=0.9.2)

MongoCollection::group — Performs an operation similar to SQL's GROUP BY command

Description

public MongoCollection::group ( mixed $keys , array $initial , MongoCode $reduce [, array $options = array() ] ) : array

Parameters

keys

Fields to group by. If an array or non-code object is passed, it will be the key used to group results.

1.0.4+: If keys is an instance of MongoCode, keys will be treated as a function that returns the key to group by (see the "Passing a keys function" example below).

initial

Initial value of the aggregation counter object.

reduce

A function that takes two arguments (the current document and the aggregation to this point) and does the aggregation.

options

Optional parameters to the group command. Valid options include:

  • "condition"

    Criteria for including a document in the aggregation.

  • "finalize"

    Function called once per unique key that takes the final output of the reduce function.

  • "maxTimeMS"

    Specifies a cumulative time limit in milliseconds for processing the operation on the server (does not include idle time). If the operation is not completed by the server within the timeout period, a MongoExecutionTimeoutException will be thrown.

Return Values

Returns an array containing the result.

Changelog

Version | Description
1.5.0 | Added "maxTimeMS" option.
1.2.11 | Emits E_DEPRECATED when options is scalar.

Examples

Example #1 MongoCollection::group() example

This groups documents by category and creates a list of names within that category.

<?php

$collection->insert(array("category" => "fruit", "name" => "apple"));
$collection->insert(array("category" => "fruit", "name" => "peach"));
$collection->insert(array("category" => "fruit", "name" => "banana"));
$collection->insert(array("category" => "veggie", "name" => "corn"));
$collection->insert(array("category" => "veggie", "name" => "broccoli"));

$keys = array("category" => 1);

$initial = array("items" => array());

$reduce = "function (obj, prev) { prev.items.push(obj.name); }";

$g = $collection->group($keys, $initial, $reduce);

echo json_encode($g['retval']);

?>

The above example will output something similar to:

[{"category":"fruit","items":["apple","peach","banana"]},{"category":"veggie","items":["corn","broccoli"]}]

Example #2 MongoCollection::group() example

This example doesn't use any key, so every document will be its own group. It also uses a condition: only documents that match this condition will be processed by the grouping function.

<?php

$collection->save(array("a" => 2));
$collection->save(array("b" => 5));
$collection->save(array("a" => 1));

// use all fields
$keys = array();

// set intial values
$initial = array("count" => 0);

// JavaScript function to perform
$reduce = "function (obj, prev) { prev.count++; }";

// only use documents where the "a" field is greater than 1
$condition = array('condition' => array("a" => array( '$gt' => 1)));

$g = $collection->group($keys, $initial, $reduce, $condition);

var_dump($g);

?>

The above example will output something similar to:

array(4) {
  ["retval"]=>
  array(1) {
    [0]=>
    array(1) {
      ["count"]=>
      float(1)
    }
  }
  ["count"]=>
  float(1)
  ["keys"]=>
  int(1)
  ["ok"]=>
  float(1)
}

Example #3 Passing a keys function

If you want to group by something other than a field name, you can pass a function as the first parameter of MongoCollection::group() and it will be run against each document. The return value of the function will be used as its grouping value.

This example demonstrates grouping by the num field modulo 4.

<?php

$c->group(new MongoCode('function(doc) { return {mod : doc.num % 4}; }'),
     array("count" => 0),
     new MongoCode('function(current, total) { total.count++; }'));

?>


Inserts a document into the collection

  • « MongoCollection::group
  • MongoCollection::parallelCollectionScan »
  • PHP Manual
  • MongoCollection
  • Inserts a document into the collection

MongoCollection::insert

(PECL mongo >=0.9.0)

MongoCollection::insert — Inserts a document into the collection

Description

public MongoCollection::insert ( array|object $document [, array $options = array() ] ) : bool|array

All strings sent to the database must be UTF-8. If a string is not UTF-8, a MongoException will be thrown. To insert (or query for) a non-UTF-8 string, use MongoBinData.

Parameters

document

An array or object. If an object is used, it may not have protected or private properties.

Note:

If the parameter does not have an _id key or property, a new MongoId instance will be created and assigned to it. This special behavior does not mean that the parameter is passed by reference.

options

An array of options for the insert operation. Currently available options include:

  • "fsync"

    Boolean, defaults to FALSE. If journaling is enabled, it works exactly like "j". If journaling is not enabled, the write operation blocks until it is synced to database files on disk. If TRUE, an acknowledged insert is implied and this option will override setting "w" to 0.

    Note: If journaling is enabled, users are strongly encouraged to use the "j" option instead of "fsync". Do not use "fsync" and "j" simultaneously, as that will result in an error.

  • "j"

    Boolean, defaults to FALSE. Forces the write operation to block until it is synced to the journal on disk. If TRUE, an acknowledged write is implied and this option will override setting "w" to 0.

    Note: If this option is used and journaling is disabled, MongoDB 2.6+ will raise an error and the write will fail; older server versions will simply ignore the option.

  • "socketTimeoutMS"

    This option specifies the time limit, in milliseconds, for socket communication. If the server does not respond within the timeout period, a MongoCursorTimeoutException will be thrown and there will be no way to determine if the server actually handled the write or not. A value of -1 may be specified to block indefinitely. The default value for MongoClient is 30000 (30 seconds).

  • "w"

    See Write Concerns. The default value for MongoClient is 1.

  • "wTimeoutMS"

    This option specifies the time limit, in milliseconds, for write concern acknowledgement. It is only applicable when "w" is greater than 1, as the timeout pertains to replication. If the write concern is not satisfied within the time limit, a MongoCursorException will be thrown. A value of 0 may be specified to block indefinitely. The default value for MongoClient is 10000 (ten seconds).

The following options are deprecated and should no longer be used:

  • "safe"

    Deprecated. Please use the write concern "w" option.

  • "timeout"

    Deprecated alias for "socketTimeoutMS".

  • "wtimeout"

    Deprecated alias for "wTimeoutMS".

Return Values

Returns an array containing the status of the insertion if the "w" option is set. Otherwise, returns TRUE if the inserted array is not empty (a MongoException will be thrown if the inserted array is empty).

If an array is returned, the following keys may be present:

ok

This should almost always be 1 (unless last_error itself failed).

err

If this field is non-null, an error occurred on the previous operation. If this field is set, it will be a string describing the error that occurred.

code

If a database error occurred, the relevant error code will be passed back to the client.

errmsg

This field is set if something goes wrong with a database command. It is coupled with ok being 0. For example, if w is set and times out, errmsg will be set to "timed out waiting for slaves" and ok will be 0. If this field is set, it will be a string describing the error that occurred.

n

If the last operation was an update, upsert, or a remove, the number of documents affected will be returned. For insert operations, this value is always 0.

wtimeout

If the previous option timed out waiting for replication.

waited

How long the operation waited before timing out.

wtime

If w was set and the operation succeeded, how long it took to replicate to w servers.

upserted

If an upsert occurred, this field will contain the new record's _id field. For upserts, either this field or updatedExisting will be present (unless an error occurred).

updatedExisting

If an upsert updated an existing element, this field will be true. For upserts, either this field or upserted will be present (unless an error occurred).

Errors/Exceptions

Throws MongoException if the inserted document is empty or if it contains zero-length keys. Attempting to insert an object with protected and private properties will cause a zero-length key error.

Throws MongoCursorException if the "w" option is set and the write fails.

Throws MongoCursorTimeoutException if the "w" option is set to a value greater than one and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in MongoCollection::$wtimeout is milliseconds.

Changelog

Version | Description
1.5.0 | Added the "wTimeoutMS" option, which replaces "wtimeout". Emits E_DEPRECATED when "wtimeout" is used. Added the "socketTimeoutMS" option, which replaces "timeout". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
1.3.4 | Added "wtimeout" option.
1.3.0 | Added "w" option. The options parameter no longer accepts a boolean to signify an acknowledged write. Instead, this now has to be done with array('w' => 1) (the default behaviour of MongoClient).
1.2.0 | Added "timeout" option.
1.0.11 | Disconnects on "not master" errors if "safe" is set.
1.0.9 | Added ability to pass integers to the "safe" option, which previously only accepted booleans. Added "fsync" option. The return type was changed to be an array containing error information if the "safe" option is used. Otherwise, a boolean is returned as before.
1.0.2 | Changed second parameter to be an array of options. Pre-1.0.2, the second parameter was a boolean indicating the "safe" option.
1.0.1 | Throw a MongoCursorException if the "safe" option is set and the insert fails.

Examples

Example #1 MongoCollection::insert() _id example

An _id field will be added to the inserted document if not already present. Depending on how the parameter is passed, a generated _id may or may not be available to calling code.

<?php

$m = new MongoClient();
$collection = $m->selectCollection('test', 'phpmanual');

// If an array literal is used, there is no way to access the generated _id
$collection->insert(array('x' => 1));

// The _id is available on an array passed by value
$a = array('x' => 2);
$collection->insert($a);
var_dump($a);

// The _id is not available on an array passed by reference
$b = array('x' => 3);
$ref = &$b;
$collection->insert($ref);
var_dump($ref);

// The _id is available if a wrapping function does not trigger copy-on-write
function insert_no_cow($collection, $document)
{
    $collection->insert($document);
}

$c = array('x' => 4);
insert_no_cow($collection, $c);
var_dump($c);

// The _id is not available if a wrapping function triggers copy-on-write
function insert_cow($collection, $document)
{
    $document['y'] = 1;
    $collection->insert($document);
}

$d = array('x' => 5);
insert_cow($collection, $d);
var_dump($d);

?>

The above example will output something similar to:

array(2) {
  ["x"]=>
  int(2)
  ["_id"]=>
  object(MongoId)#4 (0) {
  }
}
array(1) {
  ["x"]=>
  int(3)
}
array(2) {
  ["x"]=>
  int(4)
  ["_id"]=>
  object(MongoId)#5 (0) {
  }
}
array(1) {
  ["x"]=>
  int(5)
}

Example #2 MongoCollection::insert() acknowledged write example

This example shows inserting two elements with the same _id, which causes a MongoCursorException to be thrown, as w was set.

<?php

$person = array("name" => "Joe", "age" => 20);
$collection->insert($person);

// now $person has an _id field, so if we save it
// again, we will get an exception
try {
    $collection->insert($person, array("w" => 1));
} catch(MongoCursorException $e) {
    echo "Can't save the same person twice!\n";
}

?>

See Also

  • MongoCollection::batchInsert() - Inserts multiple documents into this collection
  • MongoCollection::update() - Update records based on a given criteria
  • MongoCollection::find() - Queries this collection, returning a MongoCursor for the result set
  • MongoCollection::remove() - Remove records from this collection
  • MongoDB core docs on » insert.


Returns an array of cursors to iterator over a full collection in parallel

  • « MongoCollection::insert
  • MongoCollection::remove »
  • PHP Manual
  • MongoCollection
  • Returns an array of cursors to iterator over a full collection in parallel

MongoCollection::parallelCollectionScan

(PECL mongo >=1.5.0)

MongoCollection::parallelCollectionScan — Returns an array of cursors to iterator over a full collection in parallel

Description

public MongoCollection::parallelCollectionScan ( int $num_cursors ) : array[MongoCommandCursor]

This method returns an array of a maximum of num_cursors cursors. An iteration over one of the returned cursors results in a partial set of documents for a collection. Iteration over all the returned cursors results in getting every document back from the collection.

This method is a wrapper for the parallelCollectionScan MongoDB command.

Parameters

num_cursors

The number of cursors to request from the server. Please note, that the server can return less cursors than you requested.

Return Values

Returns an array of MongoCommandCursor objects.

Examples

Example #1 MongoCollection::parallelCollectionScan() example

Returning all documents in a collection by using multiple cursors.

<?php
$m = new MongoClient;
$c = $m->demo->cities;

/* Request three cursors */
$cursors = $c->parallelCollectionScan( 3 );

/* Add all the cursors to the MultipleIterator */
$mi = new MultipleIterator( MultipleIterator::MIT_NEED_ANY );
foreach ( $cursors as $cursor )
{
    $mi->attachIterator( $cursor );
}

/* Iterate over all the associated cursors */
foreach ( $mi as $items )
{
    foreach ( $items as $item )
    {
        if ( $item !== NULL )
        {
            echo $item['name'], "\n";
        }
    }
}
?>

See Also

  • MultipleIterator
  • MongoCommandCursor
  • MongoDB::command() - Execute a database command


Remove records from this collection

  • « MongoCollection::parallelCollectionScan
  • MongoCollection::save »
  • PHP Manual
  • MongoCollection
  • Remove records from this collection

MongoCollection::remove

(PECL mongo >=0.9.0)

MongoCollection::remove — Remove records from this collection

Description

 public MongoCollection::remove
  ([ array $criteria = array()
 [, array $options = array()
]] ) : bool|array

Parameters

criteria

Query criteria for the documents to delete.

options

An array of options for the remove operation. Currently available options include:

  • "w"

    See Write Concerns. The default value for MongoClient is 1.

  • "justOne"

    Specify TRUE to limit deletion to just one document. If FALSE or omitted, all documents matching the criteria will be deleted.

  • "fsync"

    Boolean, defaults to FALSE. If journaling is enabled, it works exactly like "j". If journaling is not enabled, the write operation blocks until it is synced to database files on disk. If TRUE, an acknowledged insert is implied and this option will override setting "w" to 0.

    Note: If journaling is enabled, users are strongly encouraged to use the "j" option instead of "fsync". Do not use "fsync" and "j" simultaneously, as that will result in an error.

  • "j"

    Boolean, defaults to FALSE. Forces the write operation to block until it is synced to the journal on disk. If TRUE, an acknowledged write is implied and this option will override setting "w" to 0.

    Note: If this option is used and journaling is disabled, MongoDB 2.6+ will raise an error and the write will fail; older server versions will simply ignore the option.

  • "socketTimeoutMS"

    This option specifies the time limit, in milliseconds, for socket communication. If the server does not respond within the timeout period, a MongoCursorTimeoutException will be thrown and there will be no way to determine if the server actually handled the write or not. A value of -1 may be specified to block indefinitely. The default value for MongoClient is 30000 (30 seconds).

  • "w"

    See Write Concerns. The default value for MongoClient is 1.

  • "wTimeoutMS"

    This option specifies the time limit, in milliseconds, for write concern acknowledgement. It is only applicable when "w" is greater than 1, as the timeout pertains to replication. If the write concern is not satisfied within the time limit, a MongoCursorException will be thrown. A value of 0 may be specified to block indefinitely. The default value for MongoClient is 10000 (ten seconds).

The following options are deprecated and should no longer be used:

  • "safe"

    Deprecated. Please use the write concern "w" option.

  • "timeout"

    Deprecated alias for "socketTimeoutMS".

  • "wtimeout"

    Deprecated alias for "wTimeoutMS".

Return Values

Returns an array containing the status of the removal if the "w" option is set. Otherwise, returns TRUE.

Fields in the status array are described in the documentation for MongoCollection::insert().

Errors/Exceptions

Throws MongoCursorException if the "w" option is set and the write fails.

Throws MongoCursorTimeoutException if the "w" option is set to a value greater than one and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in MongoCollection::$wtimeout is milliseconds.

Changelog

Version | Description
1.5.0 | Added "wTimeoutMS" option, which replaces "wtimeout". Emits E_DEPRECATED when "wtimeout" is used. Added "socketTimeoutMS" option, which replaces "timeout". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
1.3.4 | Added "wtimeout" option.
1.3.0 | Added "w" option. The options parameter no longer accepts a boolean to signify "justOne". Instead, this now has to be done with array('justOne' => true).
1.2.11 | Emits E_DEPRECATED when options is scalar.
1.2.0 | Added "timeout" option.
1.0.11 | Disconnects on "not master" errors if "safe" is set.
1.0.9 | Added ability to pass integers to the "safe" option, which previously only accepted booleans. Added "fsync" option. The return type was changed to be an array containing error information if the "safe" option is used. Otherwise, a boolean is returned as before.
1.0.5 | Changed second parameter to be an array of options. Pre-1.0.5, the second parameter was a boolean indicating the "safe" option.

Examples

Example #1 MongoCollection::remove() with justOne example

<?php

$radioactive = $db->radioactive;

// count how much more plutonium there is
$remaining = $radioactive->count(array('type' => 94));

$halflife = $remaining/2;

// remove half of it
while ($halflife > 0) {
    $radioactive->remove(array('type' => 94), array("justOne" => true));
    $halflife--;
}

?>

See Also

  • MongoCollection::insert() - Inserts a document into the collection
  • MongoCollection::update() - Update records based on a given criteria
  • MongoDB core docs on » remove.


Saves a document to this collection

  • « MongoCollection::remove
  • MongoCollection::setReadPreference »
  • PHP Manual
  • MongoCollection
  • Saves a document to this collection

MongoCollection::save

(PECL mongo >=0.9.0)

MongoCollection::save — Saves a document to this collection

Description

public MongoCollection::save ( array|object $document [, array $options = array() ] ) : mixed

If the object is from the database, update the existing database object, otherwise insert this object.

Parameters

document

Array or object to save. If an object is used, it may not have protected or private properties.

Note:

If the parameter does not have an _id key or property, a new MongoId instance will be created and assigned to it. See MongoCollection::insert() for additional information on this behavior.

options

Options for the save.

  • "fsync"

    Boolean, defaults to FALSE. If journaling is enabled, it works exactly like "j". If journaling is not enabled, the write operation blocks until it is synced to database files on disk. If TRUE, an acknowledged insert is implied and this option will override setting "w" to 0.

    Note: If journaling is enabled, users are strongly encouraged to use the "j" option instead of "fsync". Do not use "fsync" and "j" simultaneously, as that will result in an error.

  • "j"

    Boolean, defaults to FALSE. Forces the write operation to block until it is synced to the journal on disk. If TRUE, an acknowledged write is implied and this option will override setting "w" to 0.

    Note: If this option is used and journaling is disabled, MongoDB 2.6+ will raise an error and the write will fail; older server versions will simply ignore the option.

  • "socketTimeoutMS"

    This option specifies the time limit, in milliseconds, for socket communication. If the server does not respond within the timeout period, a MongoCursorTimeoutException will be thrown and there will be no way to determine if the server actually handled the write or not. A value of -1 may be specified to block indefinitely. The default value for MongoClient is 30000 (30 seconds).

  • "w"

    See Write Concerns. The default value for MongoClient is 1.

  • "wtimeout"

    Deprecated alias for "wTimeoutMS".

  • "wTimeoutMS"

    This option specifies the time limit, in milliseconds, for write concern acknowledgement. It is only applicable when "w" is greater than 1, as the timeout pertains to replication. If the write concern is not satisfied within the time limit, a MongoCursorException will be thrown. A value of 0 may be specified to block indefinitely. The default value for MongoClient is 10000 (ten seconds).

  • "safe"

    Deprecated. Please use the write concern "w" option.

  • "timeout"

    Deprecated alias for "socketTimeoutMS".

Return Values

If w was set, returns an array containing the status of the save. Otherwise, returns a boolean representing if the array was not empty (an empty array will not be inserted).

Errors/Exceptions

Throws MongoException if the inserted document is empty or if it contains zero-length keys. Attempting to insert an object with protected and private properties will cause a zero-length key error.

Throws MongoCursorException if the "w" option is set and the write fails.

Throws MongoCursorTimeoutException if the "w" option is set to a value greater than one and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in MongoCollection::$wtimeout is milliseconds.

Changelog

Version | Description
1.5.0 | Added "wTimeoutMS" option, which replaces "wtimeout". Emits E_DEPRECATED when "wtimeout" is used. Added "socketTimeoutMS" option, which replaces "timeout". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
1.2.0 | Added "timeout" option.
1.0.11 | Disconnects on "not master" errors if "safe" is set.
1.0.9 | Added "fsync" option.
1.0.5 | Added options parameter.

Examples

Example #1 MongoCollection::save() example

<?php

$obj = array('x' => 1);

// insert $obj into the db
$collection->save($obj);
var_dump($obj);

// add another field
$obj['foo'] = 'bar';

// $obj cannot be inserted again, causes duplicate _id error
$collection->insert($obj);

// save updates $obj with the new field
$collection->save($obj);

?>

The above example will output something similar to:

array(2) {
  ["x"]=>
  int(1)
  ["_id"]=>
  object(MongoId)#4 (1) {
    ["$id"]=>
    string(24) "50b6afe544415ed606000000"
  }
}


Set the read preference for this collection

  • « MongoCollection::save
  • MongoCollection::setSlaveOkay »
  • PHP Manual
  • MongoCollection
  • Set the read preference for this collection

MongoCollection::setReadPreference

(PECL mongo >=1.3.0)

MongoCollection::setReadPreference — Set the read preference for this collection

Description

public MongoCollection::setReadPreference ( string $read_preference [, array $tags ] ) : bool

Parameters

read_preference

The read preference mode: MongoClient::RP_PRIMARY, MongoClient::RP_PRIMARY_PREFERRED, MongoClient::RP_SECONDARY, MongoClient::RP_SECONDARY_PREFERRED, or MongoClient::RP_NEAREST.

tags

An array of zero or more tag sets, where each tag set is itself an array of criteria used to match tags on replica set members.

Return Values

Returns TRUE on success, or FALSE otherwise.

Errors/Exceptions

Emits E_WARNING if either parameter is invalid, or if one or more tag sets are provided with the MongoClient::RP_PRIMARY read preference mode.

Examples

Example #1 MongoCollection::setReadPreference() tag set array syntax example

<?php

$m = new MongoClient();
$c = $m->test->users;

// Prefer the nearest server in the "east" data center also used for reporting,
// but fall back to a server in the "west" data center
$c->setReadPreference(MongoClient::RP_NEAREST, array(
    array('dc' => 'east', 'use' => 'reporting'),
    array('dc' => 'west'),
));
?>

See Also

  • The read preferences documentation.
  • MongoCollection::getReadPreference() - Get the read preference for this collection


Change slaveOkay setting for this collection

  • « MongoCollection::setReadPreference
  • MongoCollection::setWriteConcern »
  • PHP Manual
  • MongoCollection
  • Change slaveOkay setting for this collection

MongoCollection::setSlaveOkay

(PECL mongo >=1.1.0)

MongoCollection::setSlaveOkay — Change slaveOkay setting for this collection

Description

public MongoCollection::setSlaveOkay ([ bool $ok = TRUE ] ) : bool

See the query section of this manual for information on distributing reads to secondaries.

Parameters

ok

If reads should be sent to secondary members of a replica set for all possible queries using this MongoCollection instance.

Return Values

Returns the former value of slaveOkay for this instance.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.

See Also

  • Read Preferences
  • MongoCollection::setReadPreference() - Set the read preference for this collection


Set the write concern for this database

  • « MongoCollection::setSlaveOkay
  • MongoCollection::toIndexString »
  • PHP Manual
  • MongoCollection
  • Set the write concern for this database

MongoCollection::setWriteConcern

(PECL mongo >=1.5.0)

MongoCollection::setWriteConcern — Set the write concern for this database

Description

public MongoCollection::setWriteConcern ( mixed $w [, int $wtimeout ] ) : bool

Parameters

w

The write concern. This may be an integer denoting the number of servers required to acknowledge the write, or a string mode (e.g. "majority").

wtimeout

The maximum number of milliseconds to wait for the server to satisfy the write concern.

Return Values

Returns TRUE on success, or FALSE otherwise.

Errors/Exceptions

Emits E_WARNING if the w parameter is not an integer or string value.

Examples

Example #1 MongoDB::setWriteConcern() example

<?php

$mc = new MongoClient('mongodb://rs1.example.com,rs2.example.com');
$coll = $mc->selectCollection('test', 'foo');

// Require that the majority of servers in the replica set acknowledge writes
// within three seconds.
$coll->setWriteConcern('majority', 3000);
?>

See Also

  • The write concern documentation.
  • MongoCollection::getWriteConcern() - Get the write concern for this collection


Converts keys specifying an index to its identifying string

  • « MongoCollection::setWriteConcern
  • MongoCollection::__toString »
  • PHP Manual
  • MongoCollection
  • Converts keys specifying an index to its identifying string

MongoCollection::toIndexString

(PECL mongo >=0.9.0)

MongoCollection::toIndexString — Converts keys specifying an index to its identifying string

Description

static protected MongoCollection::toIndexString ( mixed $keys ) : string
Warning

This method is deprecated since version 1.5.0.

Parameters

keys

Field or fields to convert to the identifying string

Return Values

Returns a string that describes the index.

Examples

Example #1 MongoCollection::toIndexString() example

This example shows how you can create an index name out of keys. Because this is a protected (static) method, you need to overload it in a child class first.

<?php
// Create inherited class to make the method "public".
class MyCollection extends MongoCollection
{
    static public function toIndexString($a)
    {
        return parent::toIndexString($a);
    }
}

echo MyCollection::toIndexString("foo"), "\n";
// Outputs: foo_1

echo MyCollection::toIndexString(array('name' => 1, 'age' => -1)), "\n";
// Outputs: name_1_age_-1
?>

See Also

MongoDB core docs on » indexes.

Changelog

Version | Description
1.5.0 | This method has been deprecated.


String representation of this collection

  • « MongoCollection::toIndexString
  • MongoCollection::update »
  • PHP Manual
  • MongoCollection
  • String representation of this collection

MongoCollection::__toString

(PECL mongo >=0.9.0)

MongoCollection::__toString — String representation of this collection

Description

public MongoCollection::__toString ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns the full name of this collection.

Examples

Example #1 MongoCollection::__toString() example

<?php

$m = new MongoClient();

$c1 = $m->foo->bar->baz;
echo "Working with collection $c1.";

$c2 = $m->selectCollection('[]', '&');
echo "Working with collection $c2.";

?>

The above example will output something similar to:

Working with collection foo.bar.baz.
Working with collection [].&.


Update records based on a given criteria

  • « MongoCollection::__toString
  • MongoCollection::validate »
  • PHP Manual
  • MongoCollection
  • Update records based on a given criteria

MongoCollection::update

(PECL mongo >=0.9.0)

MongoCollection::update — Update records based on a given criteria

Description

public MongoCollection::update ( array $criteria , array $new_object [, array $options = array() ] ) : bool|array

Parameters

criteria

Query criteria for the documents to update.

new_object

The object used to update the matched documents. This may either contain update operators (for modifying specific fields) or be a replacement document.

options

An array of options for the update operation. Currently available options include:

  • "upsert"

    If no document matches $criteria, a new document will be inserted.

    If a new document would be inserted and $new_object contains atomic modifiers (i.e. $ operators), those operations will be applied to the $criteria parameter to create the new document. If $new_object does not contain atomic modifiers, it will be used as-is for the inserted document. See the upsert examples below for more information.

  • "multiple"

    All documents matching $criteria will be updated. MongoCollection::update() has exactly the opposite behavior of MongoCollection::remove(): it updates one document by default, not all matching documents. It is recommended that you always specify whether you want to update multiple documents or a single document, as the database may change its default behavior at some point in the future.

  • "fsync"

    Boolean, defaults to FALSE. If journaling is enabled, it works exactly like "j". If journaling is not enabled, the write operation blocks until it is synced to database files on disk. If TRUE, an acknowledged insert is implied and this option will override setting "w" to 0.

    Note: If journaling is enabled, users are strongly encouraged to use the "j" option instead of "fsync". Do not use "fsync" and "j" simultaneously, as that will result in an error.

  • "j"

    Boolean, defaults to FALSE. Forces the write operation to block until it is synced to the journal on disk. If TRUE, an acknowledged write is implied and this option will override setting "w" to 0.

    Note: If this option is used and journaling is disabled, MongoDB 2.6+ will raise an error and the write will fail; older server versions will simply ignore the option.

  • "socketTimeoutMS"

    This option specifies the time limit, in milliseconds, for socket communication. If the server does not respond within the timeout period, a MongoCursorTimeoutException will be thrown and there will be no way to determine if the server actually handled the write or not. A value of -1 may be specified to block indefinitely. The default value for MongoClient is 30000 (30 seconds).

  • "w"

    See Write Concerns. The default value for MongoClient is 1.

  • "wTimeoutMS"

    This option specifies the time limit, in milliseconds, for write concern acknowledgement. It is only applicable when "w" is greater than 1, as the timeout pertains to replication. If the write concern is not satisfied within the time limit, a MongoCursorException will be thrown. A value of 0 may be specified to block indefinitely. The default value for MongoClient is 10000 (ten seconds).

The following options are deprecated and should no longer be used:

  • "safe"

    Deprecated. Please use the write concern "w" option.

  • "timeout"

    Deprecated alias for "socketTimeoutMS".

  • "wtimeout"

    Deprecated alias for "wTimeoutMS".

Return Values

Returns an array containing the status of the update if the "w" option is set. Otherwise, returns TRUE.

Fields in the status array are described in the documentation for MongoCollection::insert().

Errors/Exceptions

Throws MongoCursorException if the "w" option is set and the write fails.

Throws MongoCursorTimeoutException if the "w" option is set to a value greater than one and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in MongoCollection::$wtimeout is milliseconds.

Changelog

Version | Description
1.5.0 | Added the "wTimeoutMS" option, which replaces "wtimeout". Emits E_DEPRECATED when "wtimeout" is used. Added the "socketTimeoutMS" option, which replaces "timeout". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
1.3.4 | Added "wtimeout" option.
1.3.0 | Added "w" option. The options parameter no longer accepts a boolean to signify an upsert. Instead, this now has to be done with array('upsert' => true).
1.2.11 | Emits E_DEPRECATED when options is scalar.
1.2.0 | Added "timeout" option.
1.0.11 | Disconnects on "not master" errors if "safe" is set.
1.0.9 | Added ability to pass integers to the "safe" option, which previously only accepted booleans. Added "fsync" option. The return type was changed to be an array containing error information if the "safe" option is used. Otherwise, a boolean is returned as before.
1.0.5 | Added "safe" option.
1.0.1 | Changed options parameter from boolean to array. Pre-1.0.1, the second parameter was an optional boolean value specifying an upsert.

Examples

Example #1 MongoCollection::update()

Adding an address field to a document.

<?php

$c->insert(array("firstname" => "Bob", "lastname" => "Jones" ));
$newdata = array('$set' => array("address" => "1 Smith Lane"));
$c->update(array("firstname" => "Bob"), $newdata);

var_dump($c->findOne(array("firstname" => "Bob")));

?>

The above example will output something similar to:

array(4) {
  ["_id"]=>
  object(MongoId)#6 (0) {
  }
  ["firstname"]=>
  string(3) "Bob"
  ["lastname"]=>
  string(5) "Jones"
  ["address"]=>
  string(12) "1 Smith Lane"
}

Example #2 MongoCollection::update() upsert examples

Upserts can simplify code, as a single line can create the document if it does not exist (based on $criteria), or update an existing document if it matches.

In the following example, $new_object contains an atomic modifier. Since the collection is empty and upsert must insert a new document, it will apply those operations to the $criteria parameter in order to create the document.

<?php

$c->drop();
$c->update(
    array("uri" => "/summer_pics"),
    array('$inc' => array("page hits" => 1)),
    array("upsert" => true)
);
var_dump($c->findOne());

?>

The above example will output something similar to:

array(3) {
  ["_id"]=>
  object(MongoId)#9 (0) {
  }
  ["uri"]=>
  string(12) "/summer_pics"
  ["page hits"]=>
  int(1)
}

If $new_object does not contain atomic modifiers (i.e. $ operators), upsert will use $new_object as-is for the new document. This matches the behavior of a normal update, where not using atomic modifiers causes the document to be overwritten.

<?php

$c->drop();
$c->update(
    array("name" => "joe"),
    array("username" => "joe312", "createdAt" => new MongoDate()),
    array("upsert" => true)
);
var_dump($c->findOne());

?>

The above example will output something similar to:

array(3) {
  ["_id"]=>
  object(MongoId)#10 (0) {
  }
  ["username"]=>
  string(6) "joe312"
  ["createdAt"]=>
  object(MongoDate)#4 (0) {
  }
}

Example #3 MongoCollection::update() multiple example

By default, MongoCollection::update() will only update the first document matching $criteria that it finds. Using the "multiple" option can override this behavior, if needed.

This example adds a "gift" field to every person whose birthday is in the next day.

<?php

$today = array('$gt' => new MongoDate(), '$lt' => new MongoDate(strtotime("+1 day")));
$people->update(
    array("birthday" => $today),
    array('$set' => array('gift' => $surprise)),
    array("multiple" => true)
);

?>

See Also

The PHP documentation on updates and the » MongoDB core docs.


Validates this collection

  • « MongoCollection::update
  • MongoCursor »
  • PHP Manual
  • MongoCollection
  • Validates this collection

MongoCollection::validate

(PECL mongo >=0.9.0)

MongoCollection::validate — Validates this collection

Description

public MongoCollection::validate ([ bool $scan_data = FALSE ] ) : array

Parameters

scan_data

Only validate indices, not the base collection.

Return Values

Returns the database's evaluation of this object.


The MongoCursor class

(PECL mongo >=0.9.0)

Introduction

A cursor is used to iterate through the results of a database query. For example, to query the database and see all results, you could do:

Example #1 MongoCursor basic usage

<?php

$cursor = $collection->find();
var_dump(iterator_to_array($cursor));

?>

You don't generally create cursors using the MongoCursor constructor, you get a new cursor by calling MongoCollection::find() (as shown above).

Suppose that, in the example above, $collection was a 50GB collection. We certainly wouldn't want to load that into memory all at once, which is what a cursor is for: allowing the client to access the collection in dribs and drabs.

If we have a large result set, we can iterate through it, loading a few megabytes of results into memory at a time. For example, we could do:

Example #2 Iterating over MongoCursor

<?php

$cursor = $collection->find();

foreach ($cursor as $doc) {
    // do something to each document
}

?>
This will go through each document in the collection, loading and garbage collecting documents as needed.

Note that this means that a cursor does not "contain" the database results, it just manages them. Thus, if you print a cursor (with, say, var_dump() or print_r()), you'll just get the cursor object, not your documents. To get the documents themselves, you can use one of the methods shown above.

Cursor Stages

A MongoCursor has two "life stages": pre- and post- query. When a cursor is created, it has not yet contacted the database, so it is in its pre-query state. In this state, the client can further specify what they want the query to do, including adding limits, skips, sorts, and more advanced options.

When the client attempts to get a result (by calling MongoCursor::next(), directly or indirectly), the cursor moves into the post-query stage. At this point, the query has been executed by the database and cannot be modified anymore.

Example #3 Adding options to MongoCursor

<?php

$cursor = $collection->find()->limit(10);

// database has not yet been queried, so more search options can be added
$cursor = $cursor->sort(array("a" => 1));

var_dump($cursor->getNext());
// now database has been queried and more options cannot be added

// so this will throw an exception:
$cursor->skip(4);
?>

Class synopsis

MongoCursor implements MongoCursorInterface , Iterator {
/* Static Fields */
static boolean $slaveOkay = FALSE ;
static integer $timeout = 30000 ;
/* Methods */
public addOption ( string $key , mixed $value ) : MongoCursor
public awaitData ([ bool $wait = TRUE ] ) : MongoCursor
public batchSize ( int $batchSize ) : MongoCursor
public __construct ( MongoClient $connection , string $ns [, array $query = array() [, array $fields = array() ]] )
public count ([ bool $foundOnly = FALSE ] ) : int
public current ( void ) : array
public dead ( void ) : bool
protected doQuery ( void ) : void
public explain ( void ) : array
public fields ( array $f ) : MongoCursor
public getNext ( void ) : array
public getReadPreference ( void ) : array
public hasNext ( void ) : bool
public hint ( mixed $index ) : MongoCursor
public immortal ([ bool $liveForever = TRUE ] ) : MongoCursor
public info ( void ) : array
public key ( void ) : string|int
public limit ( int $num ) : MongoCursor
public maxTimeMS ( int $ms ) : MongoCursor
public next ( void ) : array
public partial ([ bool $okay = TRUE ] ) : MongoCursor
public reset ( void ) : void
public rewind ( void ) : void
public setFlag ( int $flag [, bool $set = TRUE ] ) : MongoCursor
public setReadPreference ( string $read_preference [, array $tags ] ) : MongoCursor
public skip ( int $num ) : MongoCursor
public slaveOkay ([ bool $okay = TRUE ] ) : MongoCursor
public snapshot ( void ) : MongoCursor
public sort ( array $fields ) : MongoCursor
public tailable ([ bool $tail = TRUE ] ) : MongoCursor
public timeout ( int $ms ) : MongoCursor
public valid ( void ) : bool
}

Static Variables

slaveOkay

If the query should have the "slaveOkay" flag set, which allows reads on the secondary (secondaries are, by default, just for backup and not queried). Can be overridden with MongoCursor::slaveOkay().

This functionality is deprecated. Please use Read Preferences instead.

timeout

Set timeout in milliseconds for all database responses. Use -1 to wait forever. Can be overridden with MongoCursor::timeout(). This does not cause the MongoDB server to cancel the operation; it only instructs the driver to stop waiting for a response and throw a MongoCursorTimeoutException after a set time.

See Also

MongoDB core docs on » cursors.

Table of Contents

  • MongoCursor::addOption — Adds a top-level key/value pair to a query
  • MongoCursor::awaitData — Sets whether this cursor will wait for a while for a tailable cursor to return more data
  • MongoCursor::batchSize — Limits the number of elements returned in one batch
  • MongoCursor::__construct — Create a new cursor
  • MongoCursor::count — Counts the number of results for this query
  • MongoCursor::current — Returns the current element
  • MongoCursor::dead — Checks if there are results that have not yet been sent from the database
  • MongoCursor::doQuery — Execute the query
  • MongoCursor::explain — Return an explanation of the query, often useful for optimization and debugging
  • MongoCursor::fields — Sets the fields for a query
  • MongoCursor::getNext — Advances the cursor to the next result, and returns that result
  • MongoCursor::getReadPreference — Get the read preference for this query
  • MongoCursor::hasNext — Checks if there are any more elements in this cursor
  • MongoCursor::hint — Gives the database a hint about the query
  • MongoCursor::immortal — Sets whether this cursor will timeout
  • MongoCursor::info — Gets information about the cursor's creation and iteration
  • MongoCursor::key — Returns the current result's _id, or its index within the result set
  • MongoCursor::limit — Limits the number of results returned
  • MongoCursor::maxTimeMS — Sets a server-side timeout for this query
  • MongoCursor::next — Advances the cursor to the next result, and returns that result
  • MongoCursor::partial — If this query should fetch partial results from mongos if a shard is down
  • MongoCursor::reset — Clears the cursor
  • MongoCursor::rewind — Returns the cursor to the beginning of the result set
  • MongoCursor::setFlag — Sets arbitrary flags in case there is no method available the specific flag
  • MongoCursor::setReadPreference — Set the read preference for this query
  • MongoCursor::skip — Skips a number of results
  • MongoCursor::slaveOkay — Sets whether this query can be done on a secondary [deprecated]
  • MongoCursor::snapshot — Use snapshot mode for the query
  • MongoCursor::sort — Sorts the results by given fields
  • MongoCursor::tailable — Sets whether this cursor will be left open after fetching the last results
  • MongoCursor::timeout — Sets a client-side timeout for this query
  • MongoCursor::valid — Checks if the cursor is reading a valid result


Adds a top-level key/value pair to a query

  • « MongoCursor
  • MongoCursor::awaitData »
  • PHP Manual
  • MongoCursor
  • Adds a top-level key/value pair to a query

MongoCursor::addOption

(PECL mongo >=1.0.4)

MongoCursor::addOption — Adds a top-level key/value pair to a query

Description

public MongoCursor::addOption ( string $key , mixed $value ) : MongoCursor

This is an advanced function and should not be used unless you know what you're doing.

A query can optionally be nested in a "query" field if other options, such as a sort or hint, are given. For instance, adding a sort causes the query to become a subfield of a bigger query object, like:

<?php

$query = array("query" => $query, "orderby" => $sort);

?>

This method is for adding a top-level field to a query. It makes the query a subobject (if it isn't already) and adds the key/value pair of your chosing to the top level.

Warning

It cannot be used to add extra criteria to a query on the fly. For instance, this will not work:

<?php

// NOT CORRECT
$cursor = $users->find()->addOption("name", "joe")->addOption("age", 20);

?>
This does not query for a user named "joe" with an age of 20.

Parameters

key

Fieldname to add.

value

Value to add.

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.

Examples

Example #1 Adding a comment with MongoCursor::addOption() example

MongoDB supports special options to be send to the server. The shell uses the _addSpecial option to send a $comment to the server. This comment will show up in the profiling log (for slow queries f.e.). In the PHP driver, you use the MongoCursor::addOption() method.

<?php
$m = new MongoClient;
$c = $m->demo->demo;
$cursor = $c->find();
$cursor->addOption('$comment', "This comment will show up in the profiling log");

foreach ($cursor as $document) { /* empty */ }
?>

The above example will output something similar to:

{
    "op" : "query",
    "ns" : "demo.demo",
    "query" : {
        "$query" : {

        },
        "$comment" : "This comment will show up in the profiling log"
    },
    "cursorid" : 168463566447,
    "ntoreturn" : 0,
    "ntoskip" : 0,
    "nscanned" : 101,
    "nscannedObjects" : 101,
    "keyUpdates" : 0,
    "numYield" : 0,
…

Example #2 MongoCursor::addOption() example

Using MongoCursor::skip() to skip over millions of results can become slow. One way around this is to use $min or $max options for the query. These can be handy, but they require an index on exactly the fields being searched for. This is an example of how to use $min as an alternative to MongoCursor::skip().

<?php

// make sure we have an index
$c->ensureIndex(array("ts" => 1));

// you may have to modify this to run in a reasonable amount of time on slow
// machines (should take about 30 seconds on a good machine)
for ($i = 0; $i < 30000000; $i++) {
    $c->insert(array("ts" => new MongoDate(), "i" => $i));
}

$now = strtotime("now");

// find documents inserted in the last 2 seconds
$cursor = $c->find()->addOption('$min', array("ts" => $now-2));

?>


Sets whether this cursor will wait for a while for a tailable cursor to return more data

  • « MongoCursor::addOption
  • MongoCursor::batchSize »
  • PHP Manual
  • MongoCursor
  • Sets whether this cursor will wait for a while for a tailable cursor to return more data

MongoCursor::awaitData

(PECL mongo >=1.2.11)

MongoCursor::awaitData — Sets whether this cursor will wait for a while for a tailable cursor to return more data

Description

public MongoCursor::awaitData ([ bool $wait = TRUE ] ) : MongoCursor

This method is to be used with tailable cursors. If we are at the end of the data, block for a while rather than returning no data. After a timeout period, we do return as normal.

Parameters

wait

If the cursor should wait for more data to become available.

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.

Examples

Example #1 MongoCursor::awaitData() example

In this example we tail the "oplog" and instead of sleeping during every iteration, we set the MongoCursor::awaitData() option. MongoCursor::hasNext() will now block until there is more data available.

<?php
$m = new MongoClient( 'mongodb://localhost:13000', array( 'replSet' => 'seta' ) );
$c = $m->local->selectCollection( 'oplog.rs' );
$cursor = $c->find( array( 'ns' => 'demo.article', 'op' => 'i' ) );
$cursor->tailable( true );
$cursor->awaitData( true );

while (true) {
    if (!$cursor->hasNext()) {
        // we've read all the results, exit
        if ($cursor->dead()) {
            break;
        }
    } else {
        var_dump( $cursor->getNext() );
    }
}
?>

See Also

MongoDB core docs on » tailable cursors.

  • MongoCursor::tailable() - Sets whether this cursor will be left open after fetching the last results


Limits the number of elements returned in one batch

  • « MongoCursor::awaitData
  • MongoCursor::__construct »
  • PHP Manual
  • MongoCursor
  • Limits the number of elements returned in one batch

MongoCursor::batchSize

(PECL mongo >=1.0.11)

MongoCursor::batchSize — Limits the number of elements returned in one batch

Description

public MongoCursor::batchSize ( int $batchSize ) : MongoCursor

A cursor typically fetches a batch of result objects and store them locally. This method sets the batchSize value to configure the amount of documents retrieved from the server in one round trip. However, it will never return more documents than fit in the max batch size limit (usually 4MB).

Parameters

batchSize

The number of results to return per batch. Each batch requires a round-trip to the server.

If batchSize is 2 or more, it represents the size of each batch of objects retrieved. It can be adjusted to optimize performance and limit data transfer.

If batchSize is 1 or negative, it will limit of number returned documents to the absolute value of batchSize, and the cursor will be closed. For example if batchSize is -10, then the server will return a maximum of 10 documents and as many as can fit in 4MB, then close the cursor.

Warning

A batchSize of 1 is special, and means the same as -1, i.e. a value of 1 makes the cursor only capable of returning one document.

Note that this feature is different from MongoCursor::limit() in that documents must fit within a maximum size, and it removes the need to send a request to close the cursor server-side. The batch size can be changed even after a cursor is iterated, in which case the setting will apply on the next batch retrieval.

This cannot override MongoDB's limit on the amount of data it will return to the client (i.e., if you set batch size to 1,000,000,000, MongoDB will still only return 4-16MB of results per batch).

To ensure consistent behavior, the rules of MongoCursor::batchSize() and MongoCursor::limit() behave a little complex but work "as expected". The rules are: hard limits override soft limits with preference given to MongoCursor::limit() over MongoCursor::batchSize(). After that, whichever is set and lower than the other will take precedence. See below. section for some examples.

Return Values

Returns this cursor.

Examples

Example #1 MongoCursor::batchSize() and combinations with MongoCursor::limit()

<?php

// one batch, at most 10 items. The -10 makes the server to return 10 items,
// and then remove the cursor.
$cursor->limit(20)->batchSize(-10);

// first batch: at most 10 items
$cursor->limit(10);

// first batch: at most 10 items
$cursor->limit(10)->batchSize(20);

// results are fetched in batches of 10 each, with a maximum of 20 items
// returned (that means two batches of 10).
$cursor->limit(20)->batchSize(10);

// results are fetched in batches of 7 each, with a maximum of 30 items
// returned (that means that the driver requests 4 batches of 7, and one batch
// of 2).
$cursor->limit(30)->batchSize(7)
?>

See Also

MongoDB core docs on » batchSize.

  • MongoCursor::limit() - Limits the number of results returned
  • MongoCursorInterface::batchSize() - Limits the number of elements returned in one batch

Changelog

Version | Description
1.4.5 | Before 1.4.5, this method would throw an MongoCursorException if the cursor had already started iterating.


Create a new cursor

  • « MongoCursor::batchSize
  • MongoCursor::count »
  • PHP Manual
  • MongoCursor
  • Create a new cursor

MongoCursor::__construct

(PECL mongo >=0.9.0)

MongoCursor::__construct — Create a new cursor

Description

public MongoCursor::__construct ( MongoClient $connection , string $ns [, array $query = array() [, array $fields = array() ]] )

Parameters

connection

Database connection.

ns

Full name of database and collection.

query

Database query.

fields

Fields to return.

Return Values

Returns the new cursor.


Counts the number of results for this query

  • « MongoCursor::__construct
  • MongoCursor::current »
  • PHP Manual
  • MongoCursor
  • Counts the number of results for this query

MongoCursor::count

(PECL mongo >=0.9.2)

MongoCursor::count — Counts the number of results for this query

Description

public MongoCursor::count ([ bool $foundOnly = FALSE ] ) : int

This method does not affect the state of the cursor: if you haven't queried yet, you can still apply limits, skips, etc. If you have started iterating through results, it will not move the current position of the cursor. If you have exhausted the cursor, it will not reset it.

Parameters

foundOnly

Send cursor limit and skip information to the count function, if applicable.

Return Values

The number of documents returned by this cursor's query.

Examples

Example #1 MongoCursor::count() example

<?php

$collection->insert(array('x'=>1));
$collection->insert(array('x'=>2));
$collection->insert(array('x'=>3));

$cursor = $collection->find();

var_dump($cursor->count());
var_dump($cursor->count(true));

$cursor->limit(2);

var_dump($cursor->count());
var_dump($cursor->count(true));

?>

The above example will output something similar to:

int(3)
int(3)
int(3)
int(2)

Errors/Exceptions

Throws MongoConnectionException if it cannot reach the database.


Returns the current element

  • « MongoCursor::count
  • MongoCursor::dead »
  • PHP Manual
  • MongoCursor
  • Returns the current element

MongoCursor::current

(PECL mongo >=0.9.0)

MongoCursor::current — Returns the current element

Description

public MongoCursor::current ( void ) : array

This returns NULL until MongoCursor::next() is called.

Parameters

This function has no parameters.

Return Values

The current result document as an associative array. NULL will be returned if there is no result.

See Also

  • Iterator::current() - Return the current element


Checks if there are results that have not yet been sent from the database

  • « MongoCursor::current
  • MongoCursor::doQuery »
  • PHP Manual
  • MongoCursor
  • Checks if there are results that have not yet been sent from the database

MongoCursor::dead

(PECL mongo >=0.9.6)

MongoCursor::dead — Checks if there are results that have not yet been sent from the database

Description

public MongoCursor::dead ( void ) : bool

The database sends responses in batches of documents, up to 4MB of documents per response. This method checks if the database has more batches or if the result set has been exhausted.

A cursor being "dead" does not mean that MongoCursor::hasNext() will return FALSE, it only means that the database is done sending results to the client. The client should continue iterating through results until MongoCursor::hasNext() is FALSE.

Parameters

This function has no parameters.

Return Values

Returns TRUE if there are more results that have not yet been sent to the client, and FALSE otherwise.

See Also

  • MongoCursorInterface::dead() - Checks if there are results that have not yet been sent from the database


Execute the query

  • « MongoCursor::dead
  • MongoCursor::explain »
  • PHP Manual
  • MongoCursor
  • Execute the query

MongoCursor::doQuery

(PECL mongo >=0.9.0 <1.6.0)

MongoCursor::doQuery — Execute the query

Description

protected MongoCursor::doQuery ( void ) : void
Warning

Please do not use me.

This function actually queries the database. All queries and commands go through this function. Thus, this function can be overridden to provide custom query handling.

This handles serializing your query, sending it to the database, receiving a response, and deserializing it. Thus, if you are planning to override this, your code should probably call out to the original to use the existing functionality (see the example below).

Parameters

This function has no parameters.

Return Values

NULL.

Errors/Exceptions

Throws MongoConnectionException if it cannot reach the database.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.

Examples

Example #1 MongoCursor::doQuery() example

You could override this function to attempt a query on a secondary and, if that fails, try it again on the primary.

<?php

class MyCursor extends MongoCursor {

    protected function doQuery() {

        $this->slaveOkay();

        try {
            MongoCursor::doQuery();
        }
        catch(MongoCursorException $e) {
            $this->slaveOkay(false);
            MongoCursor::doQuery();
        }
    }
}

?>


Return an explanation of the query, often useful for optimization and debugging

  • « MongoCursor::doQuery
  • MongoCursor::fields »
  • PHP Manual
  • MongoCursor
  • Return an explanation of the query, often useful for optimization and debugging

MongoCursor::explain

(PECL mongo >=0.9.2)

MongoCursor::explain — Return an explanation of the query, often useful for optimization and debugging

Description

public MongoCursor::explain ( void ) : array

Parameters

This function has no parameters.

Return Values

Returns an explanation of the query.

Examples

Example #1 MongoCursor::explain() example

<?php

$cursor = $collection->find(array("x"=>1), array("y"));
$cursor->sort(array("z" => 1))->limit(4)->skip(5);

var_dump($cursor->explain());

?>

The above example will output something similar to:

array(8) {
  ["cursor"]=>
  string(15) "BtreeCursor x_1"
  ["startKey"]=>
  array(1) {
    ["x"]=>
    int(1)
  }
  ["endKey"]=>
  array(1) {
    ["x"]=>
    int(1)
  }
  ["nscanned"]=>
  float(4)
  ["n"]=>
  int(4)
  ["scanAndOrder"]=>
  int(1)
  ["millis"]=>
  int(3)
  ["allPlans"]=>
  array(2) {
    [0]=>
    array(3) {
      ["cursor"]=>
      string(15) "BtreeCursor x_1"
      ["startKey"]=>
      array(1) {
        ["x"]=>
        int(1)
      }
      ["endKey"]=>
      array(1) {
        ["x"]=>
        int(1)
      }
    }
    [1]=>
    array(3) {
      ["cursor"]=>
      string(11) "BasicCursor"
      ["startKey"]=>
      array(0) {
      }
      ["endKey"]=>
      array(0) {
      }
    }
  }
}

Errors/Exceptions

Throws MongoConnectionException if it cannot reach the database.

See Also

MongoDB core docs on » explain.


Sets the fields for a query

  • « MongoCursor::explain
  • MongoCursor::getNext »
  • PHP Manual
  • MongoCursor
  • Sets the fields for a query

MongoCursor::fields

(PECL mongo >=1.0.6)

MongoCursor::fields — Sets the fields for a query

Description

public MongoCursor::fields ( array $f ) : MongoCursor

Fields are specified by "fieldname" : bool. TRUE indicates that a field should be returned, FALSE indicates that it should not be returned. You can also use 1 and 0 instead of TRUE and FALSE.

Thus, to return only the "summary" field, one could say:

<?php

$cursor->fields(array("summary" => true));

?>

To return all fields except the "hidden" field:

<?php

$cursor->fields(array("hidden" => false));

?>

Parameters

f

Fields to return (or not return).

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating or a scalar argument is given.


Advances the cursor to the next result, and returns that result

  • « MongoCursor::fields
  • MongoCursor::getReadPreference »
  • PHP Manual
  • MongoCursor
  • Advances the cursor to the next result, and returns that result

MongoCursor::getNext

(PECL mongo >=0.9.0)

MongoCursor::getNext — Advances the cursor to the next result, and returns that result

Description

public MongoCursor::getNext ( void ) : array

Note:

MongoCursor::getNext() is an alias of MongoCursor::next().


Get the read preference for this query

  • « MongoCursor::getNext
  • MongoCursor::hasNext »
  • PHP Manual
  • MongoCursor
  • Get the read preference for this query

MongoCursor::getReadPreference

(PECL mongo >=1.3.3)

MongoCursor::getReadPreference — Get the read preference for this query

Description

public MongoCursor::getReadPreference ( void ) : array

Parameters

This function has no parameters.

Return Values

This function returns an array describing the read preference. The array contains the values type for the string read preference mode (corresponding to the MongoClient constants), and tagsets containing a list of all tag set criteria. If no tag sets were specified, tagsets will not be present in the array.

Examples

Example #1 MongoCursor::getReadPreference() return value example

<?php

$m = new MongoClient();
$cursor = $m->test->users->find();
$cursor->setReadPreference(MongoClient::RP_SECONDARY, array(
    array('dc' => 'east', 'use' => 'reporting'),
    array('dc' => 'west'),
    array(),
));
var_dump($cursor->getReadPreference());
?>

The above example will output:

array(2) {
  ["type"]=>
  string(9) "secondary"
  ["tagsets"]=>
  array(3) {
    [0]=>
    array(2) {
      ["dc"]=>
      string(4) "east"
      ["use"]=>
      string(9) "reporting"
    }
    [1]=>
    array(1) {
      ["dc"]=>
      string(7) "west"
    }
    [2]=>
    array(0) {
    }
  }
}

See Also

  • The read preferences documentation.
  • MongoCursor::setReadPreference() - Set the read preference for this query
  • MongoCursorInterface::getReadPreference() - Get the read preference for this query


Checks if there are any more elements in this cursor

  • « MongoCursor::getReadPreference
  • MongoCursor::hint »
  • PHP Manual
  • MongoCursor
  • Checks if there are any more elements in this cursor

MongoCursor::hasNext

(PECL mongo >=0.9.0)

MongoCursor::hasNext — Checks if there are any more elements in this cursor

Description

public MongoCursor::hasNext ( void ) : bool

Parameters

This function has no parameters.

Return Values

Returns if there is another element.

Errors/Exceptions

Throws MongoConnectionException if it cannot reach the database and MongoCursorTimeoutException if the timeout is exceeded.


Gives the database a hint about the query

  • « MongoCursor::hasNext
  • MongoCursor::immortal »
  • PHP Manual
  • MongoCursor
  • Gives the database a hint about the query

MongoCursor::hint

(PECL mongo >=0.9.0)

MongoCursor::hint — Gives the database a hint about the query

Description

public MongoCursor::hint ( mixed $index ) : MongoCursor

Parameters

index

Index to use for the query. If a string is passed, it should correspond to an index name. If an array or object is passed, it should correspond to the specification used to create the index (i.e. the first argument to MongoCollection::ensureIndex()).

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.

Changelog

Version | Description
1.4.0 | The index argument now supports index names as string values. In versions before 1.4.0, only array or object values were accepted.


Sets whether this cursor will timeout

  • « MongoCursor::hint
  • MongoCursor::info »
  • PHP Manual
  • MongoCursor
  • Sets whether this cursor will timeout

MongoCursor::immortal

(PECL mongo >=1.0.1)

MongoCursor::immortal — Sets whether this cursor will timeout

Description

public MongoCursor::immortal ([ bool $liveForever = TRUE ] ) : MongoCursor

After remaining idle on the server for some amount of time, cursors, by default, "die." This is generally the behavior one wants. The database cleans up a cursor once all of its results have been sent to the client, but if the client doesn't request all of the results, the cursor will languish there, taking up resources. Thus, after a few minutes, the cursor "times out" and the database assumes the client has gotten everything it needs and cleans up its the cursor's resources.

If, for some reason, you need a cursor to hang around for a long time, you can prevent the database from cleaning it up by using this method. However, if you make a cursor immortal, you need to iterate through all of its results (or at least until MongoCursor::dead() returns TRUE) or the cursor will hang around the database forever, taking up resources.

Parameters

liveForever

If the cursor should be immortal.

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.


Gets information about the cursor's creation and iteration

  • « MongoCursor::immortal
  • MongoCursor::key »
  • PHP Manual
  • MongoCursor
  • Gets information about the cursor's creation and iteration

MongoCursor::info

(PECL mongo >=1.0.5)

MongoCursor::info — Gets information about the cursor's creation and iteration

Description

public MongoCursor::info ( void ) : array

This can be called before or after the cursor has started iterating.

Parameters

This function has no parameters.

Return Values

Returns the namespace, batch size, limit, skip, flags, query, and projected fields for this cursor. If the cursor has started iterating, additional information about iteration and the connection will be included.

Changelog

Version | Description
1.1.0 | Added a number of other fields, including id (the cursor id), at (the driver's counter of which document is current), numReturned (the number returned by the server in the current batch), and server (which server the query was sent to—useful in conjunction with Read Preferences.
1.0.10 | Added started_iterating field, a boolean indicating if cursor is pre- or post-query.

Examples

Example #1 MongoCursor::info() example

<?php
$m = new MongoClient();

$cursor = $m->test->foo->find(array("x" => 4), array("y" => 0));

echo "Before iteration started:\n";
var_dump($cursor->info());

echo "\nAfter iteration started:\n";
$cursor->rewind();
var_dump($cursor->info());

?>

The above example will output something similar to:

Before iteration started:
array(8) {
  ["ns"]=>
  string(8) "test.foo"
  ["limit"]=>
  int(0)
  ["batchSize"]=>
  int(0)
  ["skip"]=>
  int(0)
  ["flags"]=>
  int(0)
  ["query"]=>
  array(1) {
    ["x"]=>
    int(4)
  }
  ["fields"]=>
  array(1) {
    ["y"]=>
    int(0)
  }
  ["started_iterating"]=>
  bool(false)
}

After iteration started:
array(15) {
  ["ns"]=>
  string(8) "test.foo"
  ["limit"]=>
  int(0)
  ["batchSize"]=>
  int(0)
  ["skip"]=>
  int(0)
  ["flags"]=>
  int(0)
  ["query"]=>
  array(1) {
    ["x"]=>
    int(4)
  }
  ["fields"]=>
  array(1) {
    ["y"]=>
    int(0)
  }
  ["started_iterating"]=>
  bool(true)
  ["id"]=>
  int(0)
  ["at"]=>
  int(0)
  ["numReturned"]=>
  int(1)
  ["server"]=>
  string(25) "localhost:27017;-;.;26450"
  ["host"]=>
  string(9) "localhost"
  ["port"]=>
  int(27017)
  ["connection_type_desc"]=>
  string(10) "STANDALONE"
}

See Also

  • MongoCursorInterface::info() - Gets information about the cursor's creation and iteration


Returns the current result's _id, or its index within the result set

  • « MongoCursor::info
  • MongoCursor::limit »
  • PHP Manual
  • MongoCursor
  • Returns the current result's _id, or its index within the result set

MongoCursor::key

(PECL mongo >=0.9.0)

MongoCursor::key — Returns the current result's _id, or its index within the result set

Description

public MongoCursor::key ( void ) : string|int

Parameters

This function has no parameters.

Return Values

The current result's _id as a string. If the result has no _id, its numeric index within the result set will be returned as an integer.

See Also

  • Iterator::key() - Return the key of the current element


Limits the number of results returned

  • « MongoCursor::key
  • MongoCursor::maxTimeMS »
  • PHP Manual
  • MongoCursor
  • Limits the number of results returned

MongoCursor::limit

(PECL mongo >=0.9.0)

MongoCursor::limit — Limits the number of results returned

Description

public MongoCursor::limit ( int $num ) : MongoCursor

Parameters

num

The number of results to return.

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.

See Also

  • MongoDB core docs on » limit.
  • MongoCursor::batchSize() - Limits the number of elements returned in one batch
  • MongoCursor::skip() - Skips a number of results


Sets a server-side timeout for this query

  • « MongoCursor::limit
  • MongoCursor::next »
  • PHP Manual
  • MongoCursor
  • Sets a server-side timeout for this query

MongoCursor::maxTimeMS

(PECL mongo >=1.5.0)

MongoCursor::maxTimeMS — Sets a server-side timeout for this query

Description

public MongoCursor::maxTimeMS ( int $ms ) : MongoCursor

Specifies a cumulative time limit in milliseconds to be allowed by the server for processing operations on the cursor.

Parameters

ms

Specifies a cumulative time limit in milliseconds to be allowed by the server for processing operations on the cursor.

Return Values

This cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.

Causes methods that fetch results to throw a MongoExecutionTimeoutException if the query takes longer than the specified number of milliseconds in processing time.

Examples

Example #1 MongoCursor::maxTimeMS() example

In the following example, the server will abort the query if the cursor requires more than two seconds in processing time to return its results.

<?php

$cursor = $collection->find();
$cursor->maxTimeMS(2000);

try {
    $results = iterator_to_array($cursor);
} catch (MongoExecutionTimeoutException $e) {
    echo "query took too long!";
}

?>

Notes

Warning

Unlike MongoCursor::timeout(), which specifies a client-side timeout, MongoCursor::maxTimeMS() can be used to cause the MongoDB server to abort long-running queries. This timeout is cumulative for the lifetime of the cursor (i.e. each batch will contribute to this time limit). The timeout only considers processing time; idle time is not considered.


Advances the cursor to the next result, and returns that result

  • « MongoCursor::maxTimeMS
  • MongoCursor::partial »
  • PHP Manual
  • MongoCursor
  • Advances the cursor to the next result, and returns that result

MongoCursor::next

(PECL mongo >=0.9.0)

MongoCursor::next — Advances the cursor to the next result, and returns that result

Description

public MongoCursor::next ( void ) : array

Parameters

This function has no parameters.

Return Values

Returns the next document.

Errors/Exceptions

Throws MongoConnectionException if it cannot reach the database and MongoCursorTimeoutException if the timeout is exceeded.

See Also

  • Iterator::next() - Move forward to next element


If this query should fetch partial results from mongos if a shard is down

  • « MongoCursor::next
  • MongoCursor::reset »
  • PHP Manual
  • MongoCursor
  • If this query should fetch partial results from mongos if a shard is down

MongoCursor::partial

(PECL mongo >=1.2.0)

MongoCursor::partial — If this query should fetch partial results from mongos if a shard is down

Description

public MongoCursor::partial ([ bool $okay = TRUE ] ) : MongoCursor

This option allows mongos to send partial query results if a shard is unreachable. This is only applicable when running a sharded MongoDB cluster and connecting to a mongos.

If a shard goes down and a query needs to be sent to that shard, mongos will return the results (if any) from shards it already contacted, then an error message that it could not reach the shard (a MongoCursorException in PHP). If you would like to get whatever results mongos can provide and no exception, you can use this method. Note that this means that you won't have an indication that a shard is down in your query response.

This has no effect on the query if all shards are reachable. This flag was implemented in MongoDB version 1.7.5, so will only work with that version and higher.

Parameters

okay

If receiving partial results is okay.

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.


Clears the cursor

  • « MongoCursor::partial
  • MongoCursor::rewind »
  • PHP Manual
  • MongoCursor
  • Clears the cursor

MongoCursor::reset

(PECL mongo >=0.9.0)

MongoCursor::reset — Clears the cursor

Description

public MongoCursor::reset ( void ) : void

Parameters

This function has no parameters.

Return Values

NULL.


Returns the cursor to the beginning of the result set

  • « MongoCursor::reset
  • MongoCursor::setFlag »
  • PHP Manual
  • MongoCursor
  • Returns the cursor to the beginning of the result set

MongoCursor::rewind

(PECL mongo >=0.9.0)

MongoCursor::rewind — Returns the cursor to the beginning of the result set

Description

public MongoCursor::rewind ( void ) : void

This is identical to the function:

<?php

public function rewind() {
    $this->reset();
    $this->next();
}

?>

Parameters

This function has no parameters.

Return Values

NULL.

Errors/Exceptions

Throws MongoConnectionException if it cannot reach the database and MongoCursorTimeoutException if the timeout is exceeded.

See Also

  • Iterator::rewind() - Rewind the Iterator to the first element


Sets arbitrary flags in case there is no method available the specific flag

  • « MongoCursor::rewind
  • MongoCursor::setReadPreference »
  • PHP Manual
  • MongoCursor
  • Sets arbitrary flags in case there is no method available the specific flag

MongoCursor::setFlag

(PECL mongo >=1.2.11)

MongoCursor::setFlag — Sets arbitrary flags in case there is no method available the specific flag

Description

public MongoCursor::setFlag ( int $flag [, bool $set = TRUE ] ) : MongoCursor

The MongoCursor class has several methods for setting flags on the query object. This method is available in case the MongoDB wire protocol has acquired a new flag, and the driver has not been updated with a method for this new flag. In all other cases, the method should be used. See the "See also" section for available methods.

Parameters

flag

Which flag to set. You can not set flag 6 (EXHAUST) as the driver does not know how to handle them. You will get a warning if you try to use this flag. For available flags, please refer to the wire protocol » documentation.

set

Whether the flag should be set (TRUE) or unset (FALSE).

Return Values

Returns this cursor.

Errors/Exceptions

Shows a warning when an unsupport flag is attempted to be set.

Changelog

Version | Description
1.4.0 | Support for flag 3 (OPLOG_REPLAY) is added. Versions before 1.4.0 would throw a warning saying that the flag is unsupported.

Examples

Example #1 MongoCursor::setFlag() example

<?php
$m = new MongoClient( 'mongodb://localhost:13000', array( 'replSet' => 'seta' ) );
$c = $m->local->selectCollection( 'oplog.rs' );
$cursor = $c->find( array( 'ns' => 'demo.article', 'op' => 'i' ) );
$cursor->setFlag( 1, true ); // sets the tailable flag
$cursor->setFlag( 5, true ); // sets the await data flag
?>

See Also

  • MongoCursor::tailable() - Sets whether this cursor will be left open after fetching the last results
  • MongoCursor::immortal() - Sets whether this cursor will timeout
  • MongoCursor::awaitData() - Sets whether this cursor will wait for a while for a tailable cursor to return more data
  • MongoCursor::partial() - If this query should fetch partial results from mongos if a shard is down
  • MongoDB core docs on» wire protocol query flags


Set the read preference for this query

  • « MongoCursor::setFlag
  • MongoCursor::skip »
  • PHP Manual
  • MongoCursor
  • Set the read preference for this query

MongoCursor::setReadPreference

(PECL mongo >=1.3.3)

MongoCursor::setReadPreference — Set the read preference for this query

Description

public MongoCursor::setReadPreference ( string $read_preference [, array $tags ] ) : MongoCursor

Parameters

read_preference

The read preference mode: MongoClient::RP_PRIMARY, MongoClient::RP_PRIMARY_PREFERRED, MongoClient::RP_SECONDARY, MongoClient::RP_SECONDARY_PREFERRED, or MongoClient::RP_NEAREST.

tags

An array of zero or more tag sets, where each tag set is itself an array of criteria used to match tags on replica set members.

Return Values

Returns this cursor.

Errors/Exceptions

Emits E_WARNING if either parameter is invalid, or if one or more tag sets are provided with the MongoClient::RP_PRIMARY read preference mode.

Examples

Example #1 MongoCursor::setReadPreference() tag set array syntax example

<?php

$m = new MongoClient();
$cursor = $m->test->users->find();

// Prefer the nearest server in the "east" data center also used for reporting,
// but fall back to a server in the "west" data center
$cursor->setReadPreference(MongoClient::RP_NEAREST, array(
    array('dc' => 'east', 'use' => 'reporting'),
    array('dc' => 'west'),
));
?>

See Also

  • The read preferences documentation.
  • MongoCursor::getReadPreference() - Get the read preference for this query
  • MongoCursorInterface::setReadPreference() - Set the read preference for this query


Skips a number of results

  • « MongoCursor::setReadPreference
  • MongoCursor::slaveOkay »
  • PHP Manual
  • MongoCursor
  • Skips a number of results

MongoCursor::skip

(PECL mongo >=0.9.0)

MongoCursor::skip — Skips a number of results

Description

public MongoCursor::skip ( int $num ) : MongoCursor

Parameters

num

The number of results to skip.

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.

See Also

  • MongoCursor::limit() - Limits the number of results returned


Sets whether this query can be done on a secondary [deprecated]

  • « MongoCursor::skip
  • MongoCursor::snapshot »
  • PHP Manual
  • MongoCursor
  • Sets whether this query can be done on a secondary [deprecated]

MongoCursor::slaveOkay

(PECL mongo >=0.9.4)

MongoCursor::slaveOkay — Sets whether this query can be done on a secondary [deprecated]

Description

public MongoCursor::slaveOkay ([ bool $okay = TRUE ] ) : MongoCursor
Warning

This method is deprecated since version 1.5.0. Instead, please use MongoCursor::setReadPreference() and Read Preferences.

Calling this will make the driver route reads to secondaries if:

  • You are using a replica set, and
  • You created a MongoClient instance using the option "replicaSet" => "setName", and
  • There is a healthy secondary that can be reached by the driver.
You can check which server was used for this query by calling MongoCursor::info() after running the query. It's server field will show which server the query was sent to.

Note that you should use this function even if you do not use the automatic routing to secondaries. If you connect directly to a secondary in a replica set, you still need to call this function, which basically tells the database that you are aware that you might be getting older data and you're okay with that. If you do not call this, you'll get "not master" errors when you try to query.

This method will override the static class variable
MongoCursor::$slaveOkay.  It will also override
Mongo::setSlaveOkay(),
MongoDB::setSlaveOkay() and
MongoCollection::setSlaveOkay().

Parameters

okay

If it is okay to query the secondary.

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.

Examples

Example #1 MongoCursor::slaveOkay() example

<?php

MongoCursor::$slaveOkay = false;

// cannot query secondary
$cursor = $collection->find();

// can query secondary
$cursor = $collection->find()->slaveOkay();

MongoCursor::$slaveOkay = true;

// can query secondary
$cursor = $collection->find();

// cannot query secondary
$cursor = $collection->find()->slaveOkay(false);

?>

See Also

  • Read Preferences
  • MongoCursor::setReadPreference() - Set the read preference for this query
  • MongoCursor::getReadPreference() - Get the read preference for this query

Changelog

Version | Description
1.5.0 | This method has been deprecated in favour of MongoCursor::setReadPreference() and Read Preferences.


Use snapshot mode for the query

  • « MongoCursor::slaveOkay
  • MongoCursor::sort »
  • PHP Manual
  • MongoCursor
  • Use snapshot mode for the query

MongoCursor::snapshot

(PECL mongo >=0.9.4)

MongoCursor::snapshot — Use snapshot mode for the query

Description

public MongoCursor::snapshot ( void ) : MongoCursor

Use snapshot mode for the query. Snapshot mode ensures that a document will not be returned more than once because an intervening write operation results in a move of the document. Documents inserted or deleted during the lifetime of the cursor may or may not be returned, irrespective of snapshot mode.

Queries with short responses (less than 1MB) are always effectively snapshotted.

Snapshot mode may not be used with sorting, explicit hints, or queries on sharded collections.

Parameters

This function has no parameters.

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.

See Also

MongoDB core docs on » $snapshot operator.


Sorts the results by given fields

  • « MongoCursor::snapshot
  • MongoCursor::tailable »
  • PHP Manual
  • MongoCursor
  • Sorts the results by given fields

MongoCursor::sort

(PECL mongo >=0.9.0)

MongoCursor::sort — Sorts the results by given fields

Description

public MongoCursor::sort ( array $fields ) : MongoCursor

Parameters

fields

An array of fields by which to sort. Each element in the array has as key the field name, and as value either 1 for ascending sort, or -1 for descending sort.

Each result is first sorted on the first field in the array, then (if it exists) on the second field in the array, etc. This means that the order of the fields in the fields array is important. See also the examples section.

Return Values

Returns the same cursor that this method was called on.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.

Examples

Example #1 MongoCursor::sort() example

<?php
// Sort on field x, ascending
$cursor->sort(array('x' => 1));

// The order in the associative array is important. For instance, these two
// examples will yield different results:

// Sort on date ascending and age descending
$cursor->sort(array('date' => 1, 'age' => -1));

// Sort on age descending and date ascending
$cursor->sort(array('age' => -1, 'date' => 1));
?>


Sets whether this cursor will be left open after fetching the last results

  • « MongoCursor::sort
  • MongoCursor::timeout »
  • PHP Manual
  • MongoCursor
  • Sets whether this cursor will be left open after fetching the last results

MongoCursor::tailable

(PECL mongo >=0.9.4)

MongoCursor::tailable — Sets whether this cursor will be left open after fetching the last results

Description

public MongoCursor::tailable ([ bool $tail = TRUE ] ) : MongoCursor

Mongo has a feature known as tailable cursors which are similar to the Unix "tail -f" command.

Tailable means cursor is not closed when the last data is retrieved. Rather, the cursor marks the final object's position. you can resume using the cursor later, from where it was located, if more data were received.

Like any "latent cursor", the cursor may become invalid at some point -- for example if that final object it references were deleted. Thus, you should be prepared to requery if the cursor is MongoCursor::dead().

Parameters

tail

If the cursor should be tailable.

Return Values

Returns this cursor.

Errors/Exceptions

Throws MongoCursorException if this cursor has started iterating.

Examples

Example #1 MongoCursor::tailable() example

<?php

$cursor = $collection->find()->tailable();

$results = array();

while (1) {
    if (!$cursor->hasNext()) {
        // we've read all the results, exit
        if ($cursor->dead()) {
            break;
        }
        // read all results so far, wait for more
        sleep(10);
    }
    else {
        $results[] = $cursor->getNext();
    }
}

?>

See Also

MongoDB core docs on » tailable cursors.

  • MongoCursor::awaitData() - Sets whether this cursor will wait for a while for a tailable cursor to return more data


Sets a client-side timeout for this query

  • « MongoCursor::tailable
  • MongoCursor::valid »
  • PHP Manual
  • MongoCursor
  • Sets a client-side timeout for this query

MongoCursor::timeout

(PECL mongo >=1.0.3)

MongoCursor::timeout — Sets a client-side timeout for this query

Description

public MongoCursor::timeout ( int $ms ) : MongoCursor

A timeout can be set at any time and will affect subsequent queries on the cursor, including fetching more results from the database.

Parameters

ms

The number of milliseconds for the cursor to wait for a response. Use -1 to wait forever. By default, the cursor will wait 30000 milliseconds (30 seconds).

Return Values

This cursor.

Errors/Exceptions

Causes methods that fetch results to throw a MongoCursorTimeoutException if the query takes longer than the specified number of milliseconds.

Examples

Example #1 MongoCursor::timeout() example

In the following example, the driver will wait forever for the initial database response, and then wait 100ms for subsequent responses.

<?php

$cursor = $collection->find();
$cursor->timeout(-1);

/* $cursor->hasNext() executes the query. An infinite timeout has been set, so
 * the driver will wait as long as necessary for a response.
 */
while ($cursor->hasNext()) {
    $cursor->timeout(100);

    /* A timeout has now been set, so if the cursor needs to get more results
     * from the database, it will only wait 100ms for a response.
     */
    try {
        print_r($cursor->getNext());
    } catch (MongoCursorTimeoutException $e) {
        echo "query took too long!";
    }
}

?>

Notes

Warning

This does not cause the MongoDB server to cancel long-running operations; it only instructs the driver to stop waiting for a response and throw a MongoCursorTimeoutException after a set time. If you need to specify a server-side timeout for a query, consider using MongoCursor::maxTimeMS().

See Also

  • MongoCursorInterface::timeout() - Sets a client-side timeout for this query
  • The socketTimeoutMS option for MongoClient::__construct()


Checks if the cursor is reading a valid result

  • « MongoCursor::timeout
  • MongoCursorInterface »
  • PHP Manual
  • MongoCursor
  • Checks if the cursor is reading a valid result

MongoCursor::valid

(PECL mongo >=0.9.0)

MongoCursor::valid — Checks if the cursor is reading a valid result

Description

public MongoCursor::valid ( void ) : bool

Parameters

This function has no parameters.

Return Values

TRUE if the current result is not null, and FALSE otherwise.

See Also

  • Iterator::valid() - Checks if current position is valid


The MongoCursorInterface interface

(PECL mongo >=1.5.0)

Introduction

Interface for cursors, which can be used to iterate through results of a database query or command. This interface is implemented by the MongoCursor and MongoCommandCursor classes.

Note: Similar to Traversable, this interface cannot be implemented in PHP scripts.

Class synopsis

MongoCursorInterface extends Iterator {
/* Methods */
abstract public batchSize ( int $batchSize ) : MongoCursorInterface
abstract public dead ( void ) : bool
abstract public getReadPreference ( void ) : array
abstract public info ( void ) : array
abstract public setReadPreference ( string $read_preference [, array $tags ] ) : MongoCursorInterface
abstract public timeout ( int $ms ) : MongoCursorInterface
/* Inherited methods */
abstract public Iterator::current ( void ) : mixed
abstract public Iterator::key ( void ) : scalar
abstract public Iterator::next ( void ) : void
abstract public Iterator::rewind ( void ) : void
abstract public Iterator::valid ( void ) : bool
}

Table of Contents

  • MongoCursorInterface::batchSize — Limits the number of elements returned in one batch
  • MongoCursorInterface::dead — Checks if there are results that have not yet been sent from the database
  • MongoCursorInterface::getReadPreference — Get the read preference for this query
  • MongoCursorInterface::info — Gets information about the cursor's creation and iteration
  • MongoCursorInterface::setReadPreference — Set the read preference for this query
  • MongoCursorInterface::timeout — Sets a client-side timeout for this query


Limits the number of elements returned in one batch

  • « MongoCursorInterface
  • MongoCursorInterface::dead »
  • PHP Manual
  • MongoCursorInterface
  • Limits the number of elements returned in one batch

MongoCursorInterface::batchSize

(PECL mongo >=1.5.0)

MongoCursorInterface::batchSize — Limits the number of elements returned in one batch

Description

abstract public MongoCursorInterface::batchSize ( int $batchSize ) : MongoCursorInterface

A cursor typically fetches a batch of result objects and stores them locally. This method sets the batch size value to configure the amount of documents retrieved from the server in one round trip.

Parameters

batchSize

The number of results to return per batch.

Return Values

Returns this cursor.


Checks if there are results that have not yet been sent from the database

  • « MongoCursorInterface::batchSize
  • MongoCursorInterface::getReadPreference »
  • PHP Manual
  • MongoCursorInterface
  • Checks if there are results that have not yet been sent from the database

MongoCursorInterface::dead

(PECL mongo >=1.5.0)

MongoCursorInterface::dead — Checks if there are results that have not yet been sent from the database

Description

abstract public MongoCursorInterface::dead ( void ) : bool

This method checks whether the cursor has been exhausted and the database has no more results to send to the client. A cursor being "dead" does not necessarily mean that there are no more results available for iteration.

Parameters

This function has no parameters.

Return Values

Returns TRUE if there are more results that have not yet been sent to the client, and FALSE otherwise.


Get the read preference for this query

  • « MongoCursorInterface::dead
  • MongoCursorInterface::info »
  • PHP Manual
  • MongoCursorInterface
  • Get the read preference for this query

MongoCursorInterface::getReadPreference

(PECL mongo >=1.6.0)

MongoCursorInterface::getReadPreference — Get the read preference for this query

Description

abstract public MongoCursorInterface::getReadPreference ( void ) : array

Parameters

This function has no parameters.

Return Values

This function returns an array describing the read preference. The array contains the values type for the string read preference mode (corresponding to the MongoClient constants), and tagsets containing a list of all tag set criteria. If no tag sets were specified, tagsets will not be present in the array.

See Also

  • The read preferences documentation.
  • MongoCursorInterface::setReadPreference() - Set the read preference for this query


Gets information about the cursor's creation and iteration

  • « MongoCursorInterface::getReadPreference
  • MongoCursorInterface::setReadPreference »
  • PHP Manual
  • MongoCursorInterface
  • Gets information about the cursor's creation and iteration

MongoCursorInterface::info

(PECL mongo >=1.5.0)

MongoCursorInterface::info — Gets information about the cursor's creation and iteration

Description

abstract public MongoCursorInterface::info ( void ) : array

Returns information about the cursor's creation and iteration. This can be called before or after the cursor has started iterating.

Parameters

This function has no parameters.

Return Values

Returns the namespace, batch size, limit, skip, flags, query, and projected fields for this cursor. If the cursor has started iterating, additional information about iteration and the connection will be included.


Set the read preference for this query

  • « MongoCursorInterface::info
  • MongoCursorInterface::timeout »
  • PHP Manual
  • MongoCursorInterface
  • Set the read preference for this query

MongoCursorInterface::setReadPreference

(PECL mongo >=1.6.0)

MongoCursorInterface::setReadPreference — Set the read preference for this query

Description

abstract public MongoCursorInterface::setReadPreference ( string $read_preference [, array $tags ] ) : MongoCursorInterface

Parameters

read_preference

The read preference mode: MongoClient::RP_PRIMARY, MongoClient::RP_PRIMARY_PREFERRED, MongoClient::RP_SECONDARY, MongoClient::RP_SECONDARY_PREFERRED, or MongoClient::RP_NEAREST.

tags

An array of zero or more tag sets, where each tag set is itself an array of criteria used to match tags on replica set members.

Return Values

Returns this cursor.

Errors/Exceptions

Emits E_WARNING if either parameter is invalid, or if one or more tag sets are provided with the MongoClient::RP_PRIMARY read preference mode.

See Also

  • The read preferences documentation.
  • MongoCursorInterface::getReadPreference() - Get the read preference for this query


Sets a client-side timeout for this query

  • « MongoCursorInterface::setReadPreference
  • MongoCommandCursor »
  • PHP Manual
  • MongoCursorInterface
  • Sets a client-side timeout for this query

MongoCursorInterface::timeout

(PECL mongo >=1.5.0)

MongoCursorInterface::timeout — Sets a client-side timeout for this query

Description

abstract public MongoCursorInterface::timeout ( int $ms ) : MongoCursorInterface

A timeout can be set at any time and will affect subsequent data retrieval associated with this cursor, including fetching more results from the database.

Parameters

ms

The number of milliseconds for the cursor to wait for a response. Use -1 to wait forever. By default, the cursor will wait 30000 milliseconds (30 seconds).

Return Values

Returns this cursor.

Errors/Exceptions

Causes methods that fetch results to throw a MongoCursorTimeoutException if the data fetch takes longer than the specified number of milliseconds.

See Also

  • The socketTimeoutMS option for MongoClient::__construct()


The MongoCommandCursor class

(PECL mongo >=1.5.0)

Introduction

A command cursor is similar to a MongoCursor except that you use it for iterating through the results of a database command instead of a normal query. Command cursors are useful for iterating over large result sets that might exceed the document size limit (currently 16MB) of a single MongoDB::command() response.

While you can create command cursors using MongoCommandCursor::__construct() or the MongoCommandCursor::createFromDocument() factory method, you will generally want to use command-specific helpers such as MongoCollection::aggregateCursor().

Note that the cursor does not "contain" the database command's results; it just manages iteration through them. Thus, if you print a cursor (f.e. with var_dump() or print_r()), you will see the cursor object but not the result documents.

Cursor Stages

A MongoCommandCursor has two "life stages": pre- and post- command. When a cursor is created, it has not yet contacted the database, so it is in its pre-command state. When the client first attempts to get a result (by calling MongoCommandCursor::rewind(), directly or indirectly), the cursor moves into the post-command state.

The command cursor's batch size and socket timeout may be configured in both the pre- and post- command states.

Example #1 Adding options to MongoCommandCursor

<?php

$cursor = new MongoCommandCursor(...);

$cursor = $cursor->batchSize( 4 );

foreach ($cursor as $result) {
    var_dump($result);
}
?>

Class synopsis

MongoCommandCursor implements MongoCursorInterface , Iterator {
/* Methods */
public batchSize ( int $batchSize ) : MongoCommandCursor
public __construct ( MongoClient $connection , string $ns , array $command = array() )
public static createFromDocument ( MongoClient $connection , string $hash , array $document ) : MongoCommandCursor
public current ( void ) : array
public dead ( void ) : bool
public getReadPreference ( void ) : array
public info ( void ) : array
public key ( void ) : int
public next ( void ) : void
public rewind ( void ) : array
public setReadPreference ( string $read_preference [, array $tags ] ) : MongoCommandCursor
public timeout ( int $ms ) : MongoCommandCursor
public valid ( void ) : bool
}

See Also

  • MongoDB::command()
  • MongoCollection::aggregateCursor()

Table of Contents

  • MongoCommandCursor::batchSize — Limits the number of elements returned in one batch
  • MongoCommandCursor::__construct — Create a new command cursor
  • MongoCommandCursor::createFromDocument — Create a new command cursor from an existing command response document
  • MongoCommandCursor::current — Returns the current element
  • MongoCommandCursor::dead — Checks if there are results that have not yet been sent from the database
  • MongoCommandCursor::getReadPreference — Get the read preference for this command
  • MongoCommandCursor::info — Gets information about the cursor's creation and iteration
  • MongoCommandCursor::key — Returns the current result's index within the result set
  • MongoCommandCursor::next — Advances the cursor to the next result
  • MongoCommandCursor::rewind — Executes the command and resets the cursor to the start of the result set
  • MongoCommandCursor::setReadPreference — Set the read preference for this command
  • MongoCommandCursor::timeout — Sets a client-side timeout for this command
  • MongoCommandCursor::valid — Checks if the cursor is reading a valid result


Limits the number of elements returned in one batch

  • « MongoCommandCursor
  • MongoCommandCursor::__construct »
  • PHP Manual
  • MongoCommandCursor
  • Limits the number of elements returned in one batch

MongoCommandCursor::batchSize

(PECL mongo >=1.5.0)

MongoCommandCursor::batchSize — Limits the number of elements returned in one batch

Description

public MongoCommandCursor::batchSize ( int $batchSize ) : MongoCommandCursor

A cursor typically fetches a batch of result objects and store them locally. This method sets the batchSize value to configure the amount of documents retrieved from the server in one round trip.

Parameters

batchSize

The number of results to return per batch. Each batch requires a round-trip to the server.

This cannot override MongoDB's limit on the amount of data it will return to the client (i.e., if you set batch size to 1,000,000,000, MongoDB will still only return 4-16MB of results per batch).

Return Values

Returns this cursor.

Examples

Example #1 MongoCommandCursor::batchSize()

<?php
$commandCursor->batchSize(20);
?>

See Also

  • MongoCursorInterface::batchSize() - Limits the number of elements returned in one batch


Create a new command cursor

  • « MongoCommandCursor::batchSize
  • MongoCommandCursor::createFromDocument »
  • PHP Manual
  • MongoCommandCursor
  • Create a new command cursor

MongoCommandCursor::__construct

(PECL mongo >=1.5.0)

MongoCommandCursor::__construct — Create a new command cursor

Description

public MongoCommandCursor::__construct ( MongoClient $connection , string $ns , array $command = array() )

Generally, you should not have to construct a MongoCommandCursor manually, as there are helper functions such as MongoCollection::aggregateCursor() and MongoCollection::parallelCollectionScan(); however, if the server introduces new commands that can return cursors, this constructor will be useful in the absence of specific helper methods. You may also consider using MongoCommandCursor::createFromDocument().

Parameters

connection

Database connection.

ns

Full name of the database and collection (e.g. "test.foo")

command

Database command.

Return Values

Returns the new cursor.

Examples

Example #1 MongoCommandCursor example

<?php
$m = new MongoClient;

// Define the aggregation pipeline
$pipeline = [
    [ '$group' => [
        '_id' => '$country_code',
        'timezones' => [ '$addToSet' => '$timezone' ]
    ] ],
    [ '$sort' => [ '_id' => 1 ] ],
];

// Construct a MongoCommandCursor object
$cursor = new MongoCommandCursor(
    $m, // MongoClient object
    'demo.cities', // namespace
    [
        'aggregate' => 'cities',
        'pipeline' => $pipeline,
        'cursor' => [ 'batchSize' => 0 ],
    ]
);

foreach($cursor as $result) {
   …
}
?>

See Also

  • MongoCommandCursor::createFromDocument() - Create a new command cursor from an existing command response document
  • MongoCollection::aggregateCursor() - Execute an aggregation pipeline command and retrieve results through a cursor
  • MongoCollection::parallelCollectionScan() - Returns an array of cursors to iterator over a full collection in parallel


Create a new command cursor from an existing command response document

  • « MongoCommandCursor::__construct
  • MongoCommandCursor::current »
  • PHP Manual
  • MongoCommandCursor
  • Create a new command cursor from an existing command response document

MongoCommandCursor::createFromDocument

(PECL mongo >=1.5.0)

MongoCommandCursor::createFromDocument — Create a new command cursor from an existing command response document

Description

public static MongoCommandCursor::createFromDocument ( MongoClient $connection , string $hash , array $document ) : MongoCommandCursor

Use this method if you have a raw command result with cursor information in it. Note that cursors created with this method cannot be iterated multiple times, as they will lack the original command necessary for re-execution.

Parameters

connection

Database connection.

hash

The connection hash, as obtained through the third by-reference argument to MongoDB::command().

document

Document with cursor information in it. This document needs to contain the id, ns and firstBatch fields. Such a document is obtained by calling the MongoDB::command() with appropriate arguments to return a cursor, and not just an inline result. See the example below.

Return Values

Returns the new cursor.

Examples

Example #1 MongoCommandCursor::createFromDocument()

<?php
$m = new MongoClient;
$d = $m->demo;

// Define the aggregation pipeline
$pipeline = [
    [ '$group' => [
        '_id' => '$country_code',
        'timezones' => [ '$addToSet' => '$timezone' ]
    ] ],
    [ '$sort' => [ '_id' => 1 ] ],
];

// Execute the command. The "cursor" option instructs the server to return
// cursor information in the response instead of inline results.
$r = $d->command(
    [
        'aggregate' => 'cities',
        'pipeline' => $pipeline,
        'cursor' => [ 'batchSize' => 1 ],
    ],
    null,
    $hash
);

// Show result and hash
var_dump( $r, $hash );

// Construct the command cursor
$cursor = MongoCommandCursor::createFromDocument( $m, $hash, $r );
?>

The above example will output something similar to:

array(2) {
  ["cursor"]=>
  array(3) {
    ["id"]=>
    object(MongoInt64)#5 (1) {
      ["value"]=>
      string(12) "392143983421"
    }
    ["ns"]=>
    string(11) "demo.cities"
    ["firstBatch"]=>
    array(1) {
      [0]=>
      array(2) {
        ["_id"]=>
        string(2) "AD"
        ["timezones"]=>
        array(1) {
          [0]=>
          string(14) "Europe/Andorra"
        }
      }
    }
  }
  ["ok"]=>
  float(1)
}
string(25) "localhost:27017;-;.;17617"

As you can see, the returned cursor information has the id, ns and firstBatch fields.

See Also

  • MongoCommandCursor::__construct() - Create a new command cursor


Returns the current element

  • « MongoCommandCursor::createFromDocument
  • MongoCommandCursor::dead »
  • PHP Manual
  • MongoCommandCursor
  • Returns the current element

MongoCommandCursor::current

(PECL mongo >=1.5.0)

MongoCommandCursor::current — Returns the current element

Description

public MongoCommandCursor::current ( void ) : array

This returns NULL until MongoCommandCursor::rewind() is called.

Parameters

This function has no parameters.

Return Values

The current result document as an associative array. NULL will be returned if there is no result.

See Also

  • Iterator::current() - Return the current element


Checks if there are results that have not yet been sent from the database

  • « MongoCommandCursor::current
  • MongoCommandCursor::getReadPreference »
  • PHP Manual
  • MongoCommandCursor
  • Checks if there are results that have not yet been sent from the database

MongoCommandCursor::dead

(PECL mongo >=1.5.0)

MongoCommandCursor::dead — Checks if there are results that have not yet been sent from the database

Description

public MongoCommandCursor::dead ( void ) : bool

This method checks whether the MongoCommandCursor cursor has been exhausted and the database has no more results to send to the client. A cursor being "dead" does not necessarily mean that there are no more results available for iteration.

Parameters

This function has no parameters.

Return Values

Returns TRUE if there are more results that have not yet been sent to the client, and FALSE otherwise.

See Also

  • MongoCursorInterface::dead() - Checks if there are results that have not yet been sent from the database


Get the read preference for this command

  • « MongoCommandCursor::dead
  • MongoCommandCursor::info »
  • PHP Manual
  • MongoCommandCursor
  • Get the read preference for this command

MongoCommandCursor::getReadPreference

(PECL mongo >=1.6.0)

MongoCommandCursor::getReadPreference — Get the read preference for this command

Description

public MongoCommandCursor::getReadPreference ( void ) : array

Parameters

This function has no parameters.

Return Values

This function returns an array describing the read preference. The array contains the values type for the string read preference mode (corresponding to the MongoClient constants), and tagsets containing a list of all tag set criteria. If no tag sets were specified, tagsets will not be present in the array.

Examples

Example #1 MongoCommandCursor::getReadPreference() return value example

<?php

$m = new MongoClient('mongodb://rs1.example.com:27017', array('replicaSet' => 'myReplSetName'));
$collection = $m->selectCollection('test', 'people');

// If a MongoCommandCursor is constructed directly, it will inherit the read
// preference of the MongoClient instance passed to its constructor; however,
// MongoCollection::aggregateCursor() will have the MongoCommandCursor inherit
// the collection's read preference.
$collection->setReadPreference(MongoClient::RP_SECONDARY);

$cursor = $collection->aggregateCursor( [
    [ '$group' => [ '_id' => '$name', 'points' => [ '$sum' => '$points' ] ] ],
    [ '$sort' => [ 'points' => -1 ] ],
] );

var_dump($cursor->getReadPreference());

?>

The above example will output:

array(1) {
  ["type"]=>
  string(9) "secondary"
}

See Also

  • The read preferences documentation.
  • MongoCommandCursor::setReadPreference() - Set the read preference for this command
  • MongoCursorInterface::getReadPreference() - Get the read preference for this query


Gets information about the cursor's creation and iteration

  • « MongoCommandCursor::getReadPreference
  • MongoCommandCursor::key »
  • PHP Manual
  • MongoCommandCursor
  • Gets information about the cursor's creation and iteration

MongoCommandCursor::info

(PECL mongo >=1.5.0)

MongoCommandCursor::info — Gets information about the cursor's creation and iteration

Description

public MongoCommandCursor::info ( void ) : array

This can be called before or after the cursor has started iterating.

Parameters

This function has no parameters.

Return Values

Returns the namespace, batch size, limit, skip, flags, query, and projected fields for this cursor. If the cursor has started iterating, additional information about iteration and the connection will be included.

Examples

Example #1 MongoCommandCursor::info() example

<?php
$m = new MongoClient();

$cursor = new MongoCommandCursor(
    $m, // MongoClient object
    'demo.cities', // namespace
    [
        'aggregate' => 'cities',
        'pipeline' => [ [ '$match' => [ '_id' => [ '$exists' => true ] ] ] ],
        'cursor' => [ 'batchSize' => 1 ],
    ]
);

echo "Before iteration started:\n";
var_dump($cursor->info());

echo "\nAfter iteration started:\n";
$cursor->rewind();
var_dump($cursor->info());

?>

The above example will output something similar to:

Before iteration started:
array(8) {
  ["ns"]=>
  string(11) "demo.cities"
  ["limit"]=>
  int(0)
  ["batchSize"]=>
  int(0)
  ["skip"]=>
  int(0)
  ["flags"]=>
  int(0)
  ["query"]=>
  array(3) {
    ["aggregate"]=>
    string(6) "cities"
    ["pipeline"]=>
    array(1) {
      [0]=>
      array(1) {
        ["$match"]=>
        array(1) {
          ["_id"]=>
          array(1) {
            ["$exists"]=>
            bool(true)
          }
        }
      }
    }
    ["cursor"]=>
    array(1) {
      ["batchSize"]=>
      int(1)
    }
  }
  ["fields"]=>
  NULL
  ["started_iterating"]=>
  bool(false)
}

After iteration started:
array(17) {
  ["ns"]=>
  string(11) "demo.cities"
  ["limit"]=>
  int(0)
  ["batchSize"]=>
  int(0)
  ["skip"]=>
  int(0)
  ["flags"]=>
  int(0)
  ["query"]=>
  array(3) {
    ["aggregate"]=>
    string(6) "cities"
    ["pipeline"]=>
    array(1) {
      [0]=>
      array(1) {
        ["$match"]=>
        array(1) {
          ["_id"]=>
          array(1) {
            ["$exists"]=>
            bool(true)
          }
        }
      }
    }
    ["cursor"]=>
    array(1) {
      ["batchSize"]=>
      int(1)
    }
  }
  ["fields"]=>
  NULL
  ["started_iterating"]=>
  bool(true)
  ["id"]=>
  int(185840310129)
  ["at"]=>
  int(0)
  ["numReturned"]=>
  int(0)
  ["server"]=>
  string(25) "localhost:27017;-;.;23991"
  ["host"]=>
  string(9) "localhost"
  ["port"]=>
  int(27017)
  ["connection_type_desc"]=>
  string(10) "STANDALONE"
  ["firstBatchAt"]=>
  int(0)
  ["firstBatchNumReturned"]=>
  int(1)
}

See Also

  • MongoCursorInterface::info() - Gets information about the cursor's creation and iteration


Returns the current result's index within the result set

  • « MongoCommandCursor::info
  • MongoCommandCursor::next »
  • PHP Manual
  • MongoCommandCursor
  • Returns the current result's index within the result set

MongoCommandCursor::key

(PECL mongo >=1.5.0)

MongoCommandCursor::key — Returns the current result's index within the result set

Description

public MongoCommandCursor::key ( void ) : int

Parameters

This function has no parameters.

Return Values

The current result's index within the result set.

See Also

  • Iterator::key() - Return the key of the current element


Advances the cursor to the next result

  • « MongoCommandCursor::key
  • MongoCommandCursor::rewind »
  • PHP Manual
  • MongoCommandCursor
  • Advances the cursor to the next result

MongoCommandCursor::next

(PECL mongo >=1.5.0)

MongoCommandCursor::next — Advances the cursor to the next result

Description

public MongoCommandCursor::next ( void ) : void

Parameters

This function has no parameters.

Return Values

NULL.

Errors/Exceptions

Throws MongoConnectionException if it cannot reach the database and MongoCursorTimeoutException if the timeout is exceeded.

See Also

  • Iterator::next() - Move forward to next element


Executes the command and resets the cursor to the start of the result set

  • « MongoCommandCursor::next
  • MongoCommandCursor::setReadPreference »
  • PHP Manual
  • MongoCommandCursor
  • Executes the command and resets the cursor to the start of the result set

MongoCommandCursor::rewind

(PECL mongo >=1.5.0)

MongoCommandCursor::rewind — Executes the command and resets the cursor to the start of the result set

Description

public MongoCommandCursor::rewind ( void ) : array

If the cursor has already started iteration, the command will be re-executed.

Parameters

This function has no parameters.

Return Values

The raw server result document.

Errors/Exceptions

Throws MongoConnectionException if it cannot reach the database and MongoCursorTimeoutException if the timeout is exceeded.

Throws MongoCursorException if the cursor was created with MongoCommandCursor::createFromDocument() and has already started iteration. Such cursors cannot be iterated multiple times, as they lack the original command necessary for re-execution.

Examples

Example #1 MongoCommandCursor::rewind()

<?php
$rawResult = $commandCursor->rewind();

// Command cursor is now reset to the start of the result set

var_dump($rawResult);
?>

The above example will output something similar to:

array(2) {
  ["cursor"]=>
  array(3) {
    ["id"]=>
    object(MongoInt64)#5 (1) {
      ["value"]=>
      string(12) "310050110216"
    }
    ["ns"]=>
    string(9) "demo.test"
    ["firstBatch"]=>
    array(1) {
      [0]=>
      array(2) {
        ["_id"]=>
        object(MongoId)#6 (1) {
          ["$id"]=>
          string(24) "52f5691544670a8077b0dc51"
        }
        ["value"]=>
        string(2) "42"
      }
    }
  }
  ["ok"]=>
  float(1)
}

See Also

  • Iterator::rewind() - Rewind the Iterator to the first element


Set the read preference for this command

  • « MongoCommandCursor::rewind
  • MongoCommandCursor::timeout »
  • PHP Manual
  • MongoCommandCursor
  • Set the read preference for this command

MongoCommandCursor::setReadPreference

(PECL mongo >=1.6.0)

MongoCommandCursor::setReadPreference — Set the read preference for this command

Description

public MongoCommandCursor::setReadPreference ( string $read_preference [, array $tags ] ) : MongoCommandCursor

Parameters

read_preference

The read preference mode: MongoClient::RP_PRIMARY, MongoClient::RP_PRIMARY_PREFERRED, MongoClient::RP_SECONDARY, MongoClient::RP_SECONDARY_PREFERRED, or MongoClient::RP_NEAREST.

tags

An array of zero or more tag sets, where each tag set is itself an array of criteria used to match tags on replica set members.

Return Values

Returns this cursor.

Errors/Exceptions

Emits E_WARNING if either parameter is invalid, or if one or more tag sets are provided with the MongoClient::RP_PRIMARY read preference mode.

Examples

Example #1 MongoCommandCursor::setReadPreference() tag set array syntax example

<?php

$m = new MongoClient('mongodb://rs1.example.com:27017', array('replicaSet' => 'myReplSetName'));
$collection = $m->selectCollection('test', 'people');

$cursor = $collection->aggregateCursor( [
    [ '$group' => [ '_id' => '$name', 'points' => [ '$sum' => '$points' ] ] ],
    [ '$sort' => [ 'points' => -1 ] ],
] );

// Prefer the nearest server in the "east" data center also used for reporting,
// but fall back to a server in the "west" data center
$cursor->setReadPreference(MongoClient::RP_NEAREST, [
    [ 'dc' => 'east', 'use' => 'reporting' ],
    [ 'dc' => 'west' ],
] );

foreach ($cursor as $person) {
    // ...
}

// If the read preference is changed, it will be used the next time the cursor
// is rewound and the command is re-executed.
$cursor->setReadPreference(MongoClient::RP_PRIMARY);

foreach ($cursor as $person) {
    // ...
}

?>

See Also

  • The read preferences documentation.
  • MongoCommandCursor::getReadPreference() - Get the read preference for this command
  • MongoCursorInterface::setReadPreference() - Set the read preference for this query


Sets a client-side timeout for this command

  • « MongoCommandCursor::setReadPreference
  • MongoCommandCursor::valid »
  • PHP Manual
  • MongoCommandCursor
  • Sets a client-side timeout for this command

MongoCommandCursor::timeout

(PECL mongo >=1.6.0)

MongoCommandCursor::timeout — Sets a client-side timeout for this command

Description

public MongoCommandCursor::timeout ( int $ms ) : MongoCommandCursor

A timeout can be set at any time and will affect subsequent data retrieval associated with this cursor, including fetching more results from the database.

Parameters

ms

The number of milliseconds for the cursor to wait for a response. Use -1 to wait forever. By default, the cursor will wait 30000 milliseconds (30 seconds).

Return Values

This cursor.

Errors/Exceptions

Causes methods that fetch results to throw a MongoCursorTimeoutException if the data fetch takes longer than the specified number of milliseconds.

Examples

Example #1 MongoCommandCursor::timeout() example

In the following example, the driver will wait for 60 seconds for the first response from the aggregate command. It will also wait for 60 seconds each time the server needs to be polled for more information.

<?php

$m = new MongoClient;
$col = $m->database->collection;

$pipeline = [ … ];

$cursor = $col->aggregateCursor( $pipeline );
$cursor->timeout( 60000 ); // for 60 seconds

foreach ( $cursor as $result ) {
   …
}

?>

Notes

Warning

This does not cause the MongoDB server to cancel long-running operations; it only instructs the driver to stop waiting for a response and throw a MongoCursorTimeoutException after a set time. If you need to specify a server-side timeout for a command, considering passing the maxTimeMS option to MongoCollection::aggregateCursor().

See Also

  • MongoCollection::aggregateCursor() - Execute an aggregation pipeline command and retrieve results through a cursor
  • MongoCursorInterface::timeout() - Sets a client-side timeout for this query
  • The socketTimeoutMS option for MongoClient::__construct()


Checks if the cursor is reading a valid result

  • « MongoCommandCursor::timeout
  • Types »
  • PHP Manual
  • MongoCommandCursor
  • Checks if the cursor is reading a valid result

MongoCommandCursor::valid

(PECL mongo >=1.5.0)

MongoCommandCursor::valid — Checks if the cursor is reading a valid result

Description

public MongoCommandCursor::valid ( void ) : bool

Parameters

This function has no parameters.

Return Values

TRUE if the current result is not null, and FALSE otherwise.

See Also

  • Iterator::valid() - Checks if current position is valid


Types

Table of Contents

  • MongoId
  • MongoCode
  • MongoDate
  • MongoRegex
  • MongoBinData
  • MongoInt32
  • MongoInt64
  • MongoDBRef
  • MongoMinKey
  • MongoMaxKey
  • MongoTimestamp

MongoDB allows programmers to save and query for data expressed in all of the basic PHP types, compound types (arrays, associative arrays, and objects), and a half-dozen classes provided by the MongoDB PHP driver (for regular expressions, dates, and other specialized applications).

Booleans and NULL

TRUE, FALSE, and NULL can be used as-is.

Numbers

Numbers are distinct from strings in MongoDB: "123" does not match 123. Thus, if you want to make sure numbers are sorted and matched correctly, you must make sure that they are actually saved as numbers.

<?php

$doc = array("a" => 123, "b" => "123");
$collection->insert($doc);

$doc->find(array("a" => 123));   // matches
$doc->find(array("a" => "123")); // doesn't match
$doc->find(array("a" => 123.0)); // matches
$doc->find(array("b" => 123));   // doesn't match
$doc->find(array("b" => "123")); // matches

?>

As noted above, floating point numbers do compare with/match integer numbers as one would expect.

Large Numbers

By default, on a 32-bit system, numbers are sent to the database as 32-bit integers. On a 64-bit system, they are sent as 64-bit integers. For backwards compatibility, all systems deserialize 64-bit integers as floating point numbers. Floating point numbers are not exact. If you need exact values, you must tweak your php.ini settings.

On a 32-bit system, if mongo.long_as_object is set, 64-bit integers will be returns as MongoInt64 objects. The integer will be stored in the value field with perfect precision (as a string). You can also use MongoInt64 to save 64-bit integers on 32-bit machines.

On 64-bit systems, you can either set mongo.long_as_object or set mongo.native_long. mongo.native_long will return 64-bit integers and "normal" PHP integers. You can use MongoInt32 to save 32-bit integers on 64-bit machines.

You should set the mongo.long_as_object and mongo.native_long behavior that you plan to use, even if it is the default behavior (to protect against future changes to the defaults).

See also: php.ini Options, MongoInt32, MongoInt64.

Strings

Strings must be UTF-8. Non-UTF-8 strings must either be converted to UTF-8 before being sent to the database or saved as binary data.

Regular expressions can be used to match strings, and are expressed using the MongoRegex class.

Binary Data

Non-UTF-8 strings, images, and any other binary data should be sent to the database using the MongoBinData type.

Dates

Dates can be created using the MongoDate class. They are stored as milliseconds since the epoch.

MongoTimestamp is not for saving dates or timestamps, it is used internally by MongoDB. Unless you are creating a tool that interacts with the internals of replication or sharding, you should use MongoDate, not MongoTimestamp.

Unique Ids

The driver will automatically create an _id field before inserting a document (unless one is specified by the user). This field is an instance of MongoId (called "ObjectId" in most other languages).

These ids are 12 bytes long and composed of:

  • 4 bytes of timestamp

    No two records can have the same id if they were inserted at different times.

  • 3 bytes machine id

    No two records can have the same id if they were inserted on different machines

  • 2 bytes thread id

    No two records can have the same id if they were inserted by different threads running on the same machine.

  • 3 bytes incrementing value

    Each time an id is created, a global counter is incremented and used as the increment value of the next id.

Thus, no two records can have the same id unless a single process on a single machine managed to insert 256^3 (over 16 million) documents in one second, overflowing the increment field.

JavaScript

MongoDB comes with a JavaScript engine, so you can embed JavaScript in queries (using a $where clause), send it directly to the database to be executed, and use it to perform aggregations.

For security, use MongoCode's scope field to use PHP variables in JavaScript. Code that does not require external values can either use MongoCode or just be a string. See the section on security for more information about sending JavaScript to the database.

Arrays and Objects

Arrays and objects can also be saved to the database. An array with ascending numeric keys will be saved as a an array, anything else will be saved as an object.

<?php

// $scores will be saved as an array
$scores = array(98, 100, 73, 85);
$collection->insert(array("scores" => $scores));

// $scores will be saved as an object
$scores = array("quiz1" => 98, "midterm" => 100, "quiz2" => 73, "final" => 85);
$collection->insert(array("scores" => $scores));

?>

If you query for these objects using the database shell, they will look like:

> db.students.find()
{ "_id" : ObjectId("4b06beada9ad6390dab17c43"), "scores" : [ 98, 100, 73, 85 ] }
{ "_id" : ObjectId("4b06bebea9ad6390dab17c44"), "scores" : { "quiz1" : 98, "midterm" : 100, "quiz2" : 73, "final" : 85 } }

The database can also save arbitrary PHP objects (although they will be returned as associative arrays). The fields are used for the key/value pairs. For example, a blog post might look like:

<?php

  // the blog post class
  class Post {

  var $author;
  var $content;
  var $comments = array();
  var $date;

  public function __construct($author, $content) {
  $this->author = $author;
$this->content = $content;
    $this->date = new MongoDate();
  }

  public function setTitle($title) {
    $this->title = $title;
  }
}

// create a simple blog post and insert it into the database
$post1 = new Post("Adam", "This is a blog post");

$blog->insert($post1);

// there is nothing restricting the type of the "author" field, so we can make
// it a nested object
$author = array("name" => "Fred", "karma" => 42);
$post2 = new Post($author, "This is another blog post.");

// we create an extra field by setting the title
$post2->setTitle("Second Post");

$blog->insert($post2);

?>

From the database shell, this will look something like:

> db.blog.find()
{ "_id" : ObjectId("4b06c263edb87a281e09dad8"), "author" : "Adam", "content" : "This is a blog post", "comments" : [ ], "date" : "Fri Nov 20 2009 11:22:59 GMT-0500 (EST)" }
{ "_id" : ObjectId("4b06c282edb87a281e09dad9"), "author" : { "name" : "Fred", "karma" : 42 }, "content" : "This is a blog post", "comments" : [ ], "date" : "Fri Nov 20 2009 11:23:30 GMT-0500 (EST)", "title" : "Second Post" }

The driver will not detect reference loops in arrays and objects. For example, this will give a fatal error:

<?php

$collection->insert($GLOBALS);

?>
Fatal error: Nesting level too deep - recursive dependency?
If you need to insert documents that may have recursive dependency, you have to check for it yourself before passing it to the driver.


The MongoId class

(PECL mongo >=0.8.0)

Warning

This extension that defines this class is deprecated. Instead, the MongoDB extension should be used. Alternatives to this class include:

  • MongoDB\BSON\ObjectId

Introduction

A unique identifier created for database objects. If an object is inserted into the database without an _id field, an _id field will be added to it with a MongoId instance as its value. If the data has a naturally occuring unique field (e.g. username or timestamp) it is fine to use this as the _id field instead, and it will not be replaced with a MongoId.

Instances of the MongoId class fulfill the role that autoincrementing does in a relational database: to provide a unique key if the data does not naturally have one. Autoincrementing does not work well with a sharded database, as it is difficult to determine the next number in the sequence. This class fulfills the constraints of quickly generating a value that is unique across shards.

Each MongoId is 12 bytes (making its string form 24 hexadecimal characters). The first four bytes are a timestamp, the next three are a hash of the client machine's hostname, the next two are the two least significant bytes of the process id running the script, and the last three bytes are an incrementing value.

MongoIds are serializable/unserializable. Their serialized form is similar to their string form:

C:7:"MongoId":24:{4af9f23d8ead0e1d32000000}

Class synopsis

MongoId {
public string $$id = NULL ;
/* Methods */
public __construct ([ string|MongoId $id = NULL ] )
public static getHostname ( void ) : string
public getInc ( void ) : int
public getPID ( void ) : int
public getTimestamp ( void ) : int
public static isValid ( mixed $value ) : bool
public static __set_state ( array $props ) : MongoId
public __toString ( void ) : string
}

Fields

$id
This field contains the string representation of this object.

Note: The property name begins with a $ character. It may be accessed using complex variable parsed syntax (e.g. $mongoId->{'$id'}).

See Also

MongoDB core docs on » ObjectIds.

Table of Contents

  • MongoId::__construct — Creates a new id
  • MongoId::getHostname — Gets the hostname being used for this machine's ids
  • MongoId::getInc — Gets the incremented value to create this id
  • MongoId::getPID — Gets the process ID
  • MongoId::getTimestamp — Gets the number of seconds since the epoch that this id was created
  • MongoId::isValid — Check if a value is a valid ObjectId
  • MongoId::__set_state — Create a dummy MongoId
  • MongoId::__toString — Returns a hexidecimal representation of this id


Creates a new id

  • « MongoId
  • MongoId::getHostname »
  • PHP Manual
  • MongoId
  • Creates a new id

MongoId::__construct

(PECL mongo >= 0.8.0)

MongoId::__construct — Creates a new id

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. Alternatives to this method include:

  • MongoDB\BSON\ObjectId::__construct()

Description

public MongoId::__construct ([ string|MongoId $id = NULL ] )

Parameters

id

A string (must be 24 hexadecimal characters) or a MongoId instance.

Return Values

Returns a new id.

Changelog

Version | Description
1.4.0 | An exception is thrown when passed invalid string

Examples

Example #1 MongoId::__construct() example

This example shows how to create a new id. This is seldom necessary, as the driver adds an id to arrays automatically before storing them in the database.

<?php

  $id1 = new MongoId();
  echo "$id1\n";

  $id2 = new MongoId();
  echo "$id2\n";

  ?>

The above example will output something similar to:

49a7011a05c677b9a916612a
49a702d5450046d3d515d10d

Example #2 Parameter example

This example shows how to use a string parameter to initialize a MongoId with a given value.

<?php
  $id1 = new MongoId();

  // create a new id from $id1
  $id2 = new MongoId("$id1");

  // show that $id1 and $id2 have the same hexidecimal value
  var_dump($id1 == $id2);
  ?>

The above example will output something similar to:

bool(true)

See Also

  • MongoId::__toString() - Returns a hexidecimal representation of this id
  • MongoId::isvalid() - Check if a value is a valid ObjectId


Gets the hostname being used for this machine's ids

  • « MongoId::__construct
  • MongoId::getInc »
  • PHP Manual
  • MongoId
  • Gets the hostname being used for this machine's ids

MongoId::getHostname

(PECL mongo >= 1.0.8)

MongoId::getHostname — Gets the hostname being used for this machine's ids

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this method in the new extension.

Description

public static MongoId::getHostname ( void ) : string

This returns the hostname MongoId is using to generate unique ids. This should be the same value gethostname() returns.

It is identical to the function:

<?php

public static function getHostname() {
    return gethostname();
}

?>

Parameters

This function has no parameters.

Return Values

Returns the hostname.


Gets the incremented value to create this id

  • « MongoId::getHostname
  • MongoId::getPID »
  • PHP Manual
  • MongoId
  • Gets the incremented value to create this id

MongoId::getInc

(PECL mongo >= 1.0.11)

MongoId::getInc — Gets the incremented value to create this id

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this method in the new extension.

Description

public MongoId::getInc ( void ) : int

Parameters

This function has no parameters.

Return Values

Returns the incremented value used to create this MongoId.


Gets the process ID

  • « MongoId::getInc
  • MongoId::getTimestamp »
  • PHP Manual
  • MongoId
  • Gets the process ID

MongoId::getPID

(PECL mongo >= 1.0.11)

MongoId::getPID — Gets the process ID

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this method in the new extension.

Description

public MongoId::getPID ( void ) : int

Extracts the pid from the Mongo ID

Parameters

This function has no parameters.

Return Values

Returns the PID of the MongoId.


Gets the number of seconds since the epoch that this id was created

  • « MongoId::getPID
  • MongoId::isValid »
  • PHP Manual
  • MongoId
  • Gets the number of seconds since the epoch that this id was created

MongoId::getTimestamp

(PECL mongo >= 1.0.1)

MongoId::getTimestamp — Gets the number of seconds since the epoch that this id was created

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this method in the new extension.

Description

public MongoId::getTimestamp ( void ) : int

This returns the same thing as running time() when the id is created.

Parameters

This function has no parameters.

Return Values

Returns the number of seconds since the epoch that this id was created. There are only four bytes of timestamp stored, so MongoDate is a better choice for storing exact or wide-ranging times.


Check if a value is a valid ObjectId

  • « MongoId::getTimestamp
  • MongoId::__set_state »
  • PHP Manual
  • MongoId
  • Check if a value is a valid ObjectId

MongoId::isValid

(PECL mongo >= 1.5.0)

MongoId::isValid — Check if a value is a valid ObjectId

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this method in the new extension.

Description

public static MongoId::isValid ( mixed $value ) : bool

This method may be used to check a variable before passing it as an argument to MongoId::__construct().

Parameters

value

The value to check for validity.

Return Values

Returns TRUE if value is a MongoId instance or a string consisting of exactly 24 hexadecimal characters; otherwise, FALSE is returned.


Create a dummy MongoId

  • « MongoId::isValid
  • MongoId::__toString »
  • PHP Manual
  • MongoId
  • Create a dummy MongoId

MongoId::__set_state

(PECL mongo >= 1.0.8)

MongoId::__set_state — Create a dummy MongoId

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this method in the new extension.

Description

public static MongoId::__set_state ( array $props ) : MongoId

This function is only used by PHP internally, it shouldn't need to ever be called by the user.

It is identical to the function:

<?php

public static function __set_state($props) {
    return new MongoId("000000000000000000000000");
}

?>

Parameters

props

Theoretically, an array of properties used to create the new id. However, as MongoId instances have no properties, this is not used.

Return Values

A new id with the value "000000000000000000000000".


Returns a hexidecimal representation of this id

  • « MongoId::__set_state
  • MongoCode »
  • PHP Manual
  • MongoId
  • Returns a hexidecimal representation of this id

MongoId::__toString

(PECL mongo >= 0.8.0)

MongoId::__toString — Returns a hexidecimal representation of this id

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. Alternatives to this method include:

  • MongoDB\BSON\ObjectId::__toString()

Description

public MongoId::__toString ( void ) : string

Parameters

This function has no parameters.

Return Values

This id.

Examples

Example #1 MongoId::__toString() example

<?php

$m = new MongoClient();
$collection = $m->selectDB("foo")->selectCollection("bar");

$collection->insert(array( "x" => "y" ));
$collection->insert(array( "x" => "y" ));

$cursor = $collection->find();
$r1 = $cursor->next();
$r2 = $cursor->next();

echo $r1["_id"] . "\n";
echo $r2["_id"] . "\n";

?>

The above example will output something similar to:

49a7011a05c677b9a916612a
49a702d5450046d3d515d10d


The MongoCode class

(PECL mongo >=0.8.3)

Warning

This extension that defines this class is deprecated. Instead, the MongoDB extension should be used. Alternatives to this class include:

  • MongoDB\BSON\JavaScript

Introduction

Represents JavaScript code for the database.

MongoCode objects are composed of two parts: a string of code and an optional scope. The string of code must be valid JavaScript. The scope is a associative array of variable name/value pairs.

Class synopsis

MongoCode {
/* Methods */
public __construct ( string $code [, array $scope = array() ] )
public __toString ( void ) : string
}

Table of Contents

  • MongoCode::__construct — Creates a new code object
  • MongoCode::__toString — Returns this code as a string


Creates a new code object

  • « MongoCode
  • MongoCode::__toString »
  • PHP Manual
  • MongoCode
  • Creates a new code object

MongoCode::__construct

(PECL mongo >= 0.8.3)

MongoCode::__construct — Creates a new code object

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. Alternatives to this method include:

  • MongoDB\BSON\JavaScript::__construct()

Description

public MongoCode::__construct ( string $code [, array $scope = array() ] )

Parameters

code

A string of code.

scope

The scope to use for the code.

Return Values

Returns a new code object.

Examples

Example #1 MongoCode::__construct() example

<?php

$code = new MongoCode('function() { '.
    'for(i=0;i<10;i++) {'.
        'db.foo.update({z : i}, {z : x});'.
    '}'.
    'return x-1;'.
 '}', array("x" => 4));
var_dump($code);

?>

The above example will output something similar to:

object(MongoCode)#1 (2) {
  ["scope"]=>
  array(1) {
    ["x"]=>
    int(4)
  }
  ["code"]=>
  string(80) "function() { for(i=0;i<10;i++) { db.foo.update({z : i}, {z : x}); } return x-1; }"
}

Example #2 Using MongoCode with $where

This example queries a collection for elements where the 'x' fields is less than $y. Notice that PHP objects can be passed into the JavaScript scope and that the JavaScript function returns a boolean.

<?php

$cursor = $collection->find(array('$where' => new MongoCode('function() { return this.x < y; }', array('y'=>$y))));

?>


Returns this code as a string

  • « MongoCode::__construct
  • MongoDate »
  • PHP Manual
  • MongoCode
  • Returns this code as a string

MongoCode::__toString

(PECL mongo >= 0.8.3)

MongoCode::__toString — Returns this code as a string

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this method in the new extension.

Description

public MongoCode::__toString ( void ) : string

Parameters

This function has no parameters.

Return Values

This code, the scope is not returned.

Examples

Example #1 MongoCode::__toString() example

<?php

$code = new MongoCode('return x;', array("x"=>"hi"));
echo "$code\n";

$code = new MongoCode('function() { for(i=0;i<10;i++) { db.foo.update({x:i}, {x:i+1}); } }');
echo "$code\n";

?>

The above example will output something similar to:

return x;
function() { for(i=0;i<10;i++) { db.foo.update({x:i}, {x:i+1}); } }


The MongoDate class

(PECL mongo >=0.8.1)

Warning

This extension that defines this class is deprecated. Instead, the MongoDB extension should be used. Alternatives to this class include:

  • MongoDB\BSON\UTCDateTime

Introduction

Represent date objects for the database. This class should be used to save dates to the database and to query for dates. For example:

Example #1 Storing dates with MongoDate

<?php

// save a date to the database
$collection->save(array("ts" => new MongoDate()));

$start = new MongoDate(strtotime("2010-01-15 00:00:00"));
$end = new MongoDate(strtotime("2010-01-30 00:00:00"));

// find dates between 1/15/2010 and 1/30/2010
$collection->find(array("ts" => array('$gt' => $start, '$lte' => $end)));

?>

MongoDB stores dates as milliseconds past the epoch. This means that dates do not contain timezone information. Timezones must be stored in a separate field if needed. Second, this means that any precision beyond milliseconds will be lost when the document is sent to/from the database.

Class synopsis

MongoDate {
/* Fields */
public int $sec ;
public int $usec ;
/* Methods */
public __construct ([ int $sec = time() [, int $usec = 0 ]] )
public toDateTime ( void ) : DateTime
public __toString ( void ) : string
}

Table of Contents

  • MongoDate::__construct — Creates a new date
  • MongoDate::toDateTime — Returns a DateTime object representing this date
  • MongoDate::__toString — Returns a string representation of this date


Creates a new date

  • « MongoDate
  • MongoDate::toDateTime »
  • PHP Manual
  • MongoDate
  • Creates a new date

MongoDate::__construct

(PECL mongo >= 0.8.1)

MongoDate::__construct — Creates a new date

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. Alternatives to this method include:

  • MongoDB\BSON\UTCDateTime::__construct()

Description

public MongoDate::__construct ([ int $sec = time() [, int $usec = 0 ]] )

Creates a new date. If no parameters are given, the current time is used.

Parameters

sec

Number of seconds since the epoch (i.e. 1 Jan 1970 00:00:00.000 UTC).

usec

Microseconds. Please be aware though that MongoDB's resolution is milliseconds and not microseconds, which means this value will be truncated to millisecond resolution.

Return Values

Returns this new date.

Examples

Example #1 MongoDate::__construct() example

This example demonstrates creating a new date with the current time and a new date with a given time.

<?php

$d = new MongoDate();
echo "$d\n";
$d = new MongoDate(1234567890);
echo "$d\n";
$d = new MongoDate(strtotime("2009-05-01 00:00:01"));
echo "$d\n";

?>

The above example will output something similar to:

0.23660600 1235685067
0.00000000 1234567890
0.00000000 1241150401

See Also

  • MongoDate::__toString() - Returns a string representation of this date


Returns a DateTime object representing this date

  • « MongoDate::__construct
  • MongoDate::__toString »
  • PHP Manual
  • MongoDate
  • Returns a DateTime object representing this date

MongoDate::toDateTime

(PECL mongo >= 1.6.0)

MongoDate::toDateTime — Returns a DateTime object representing this date

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. Alternatives to this method include:

  • MongoDB\BSON\UTCDateTime::toDateTime()

Description

public MongoDate::toDateTime ( void ) : DateTime

Returns the DateTime representation of this date. The returned DateTime will use the UTC time zone.

Parameters

This function has no parameters.

Return Values

This date as a DateTime object.

Examples

Example #1 MongoDate::toDateTime() example

This example demonstrates creating a DateTime object from a MongoDate object.

<?php
$d = new MongoDate(strtotime("2014-11-18 11:01:25"));
var_dump( $d->toDateTime() );
?>

The above example will output something similar to:

class DateTime#2 (3) {
  public $date =>
  string(26) "2014-11-18 11:01:25.000000"
  public $timezone_type =>
  int(1)
  public $timezone =>
  string(6) "+00:00"
}


Returns a string representation of this date

  • « MongoDate::toDateTime
  • MongoRegex »
  • PHP Manual
  • MongoDate
  • Returns a string representation of this date

MongoDate::__toString

(PECL mongo >= 0.8.1)

MongoDate::__toString — Returns a string representation of this date

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. Alternatives to this method include:

  • MongoDB\BSON\UTCDateTime::__toString()

Description

public MongoDate::__toString ( void ) : string

Returns a string representation of this date, similar to the representation returned by microtime().

Parameters

This function has no parameters.

Return Values

This date.


The MongoRegex class

(PECL mongo >=0.8.1)

Warning

This extension that defines this class is deprecated. Instead, the MongoDB extension should be used. Alternatives to this class include:

  • MongoDB\BSON\Regex

Introduction

This class can be used to create regular expressions. Typically, these expressions will be used to query the database and find matching strings. More unusually, they can be saved to the database and retrieved.

Regular expressions consist of four parts. First a / as starting delimiter, then the pattern, another / and finally a string containing flags.

Example #1 Regular expression pattern

/pattern/flags

MongoDB recognizes six regular expression flags:

  • i: Case insensitive

  • m: Multiline

  • x: Can contain comments

  • l: locale

  • s: dotall, "." matches everything, including newlines

  • u: match unicode

Class synopsis

MongoRegex {
/* Fields */
public string $regex ;
public string $flags ;
/* Methods */
public __construct ( string $regex )
public __toString ( void ) : string
}

Table of Contents

  • MongoRegex::__construct — Creates a new regular expression
  • MongoRegex::__toString — A string representation of this regular expression


Creates a new regular expression

  • « MongoRegex
  • MongoRegex::__toString »
  • PHP Manual
  • MongoRegex
  • Creates a new regular expression

MongoRegex::__construct

(PECL mongo >= 0.8.1)

MongoRegex::__construct — Creates a new regular expression

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. Alternatives to this method include:

  • MongoDB\BSON\Regex::__construct()

Description

public MongoRegex::__construct ( string $regex )

Creates a new regular expression.

Parameters

regex

Regular expression string of the form /expr/flags.

Return Values

Returns a new regular expression.

Examples

Example #1 MongoRegex::__construct() example

This example uses a regular expression to query for all documents with a username field starting (^) with an l and a vowel ([aeiouy]), case-insensitive (/i).

<?php
$luke_search = new MongoRegex("/^l[aeiouy]/i");
$cursor = $collection->find(array("username" => $luke_search));
?>

See Also

  • MongoRegex::__toString() - A string representation of this regular expression


A string representation of this regular expression

  • « MongoRegex::__construct
  • MongoBinData »
  • PHP Manual
  • MongoRegex
  • A string representation of this regular expression

MongoRegex::__toString

(PECL mongo >= 0.8.1)

MongoRegex::__toString — A string representation of this regular expression

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. Alternatives to this method include:

  • MongoDB\BSON\Regex::__toString()

Description

public MongoRegex::__toString ( void ) : string

Returns a string representation of this regular expression.

Parameters

This function has no parameters.

Return Values

This regular expression in the form "/expr/flags".

Examples

Example #1 MongoRegex::__toString() example

<?php

$r = new MongoRegex( "/[a-fA-F0-9]{16}/g" );
echo $r->regex . "\n";
echo $r->flags . "\n";
echo "$r\n";

?>

The above example will output something similar to:

[a-fA-F0-9]{16}
g
/[a-fA-F0-9]{16}/g


The MongoBinData class

(PECL mongo >= 0.8.1)

Warning

This extension that defines this class is deprecated. Instead, the MongoDB extension should be used. Alternatives to this class include:

  • MongoDB\BSON\Binary

Introduction

An object that can be used to store or retrieve binary data from the database.

The maximum size of a single object that can be inserted into the database is 16MB. For data that is larger than this (movies, music, Henry Kissinger's autobiography), use MongoGridFS. For data that is smaller than 16MB, you may find it easier to embed it within the document using MongoBinData.

For example, to embed an image in a document, one could write:

<?php

$profile = array(
    "username" => "foobity",
    "pic" => new MongoBinData(file_get_contents("gravatar.jpg"), MongoBinData::GENERIC),
);

$users->save($profile);

?>

This class contains a type field, which currently gives no additional functionality in the PHP driver or the database. There are seven predefined types, which are defined as class constants below. For backwards compatibility, the PHP driver uses MongoBinData::BYTE_ARRAY as the default; however, this may change to MongoBinData::GENERIC in the future. Users are encouraged to specify a type in MongoBinData::__construct().

Class synopsis

MongoBinData {
/* Constants */
const int GENERIC = 0 ;
const int FUNC = 1 ;
const int BYTE_ARRAY = 2 ;
const int UUID = 3 ;
const int UUID_RFC4122 = 4 ;
const int MD5 = 5 ;
const int CUSTOM = 128 ;
/* Fields */
public string $bin ;
public int $type = 2 ;
/* Methods */
public __construct ( string $data [, int $type = 0 ] )
public __toString ( void ) : string
}

Predefined Constants

Binary Data Types

MongoBinData::GENERIC
Generic binary data.
MongoBinData::FUNC
Function.
MongoBinData::BYTE_ARRAY
Generic binary data (deprecated in favor of MongoBinData::GENERIC).
MongoBinData::UUID
Universally unique identifier (deprecated in favor of MongoBinData::UUID_RFC4122).
MongoBinData::UUID_RFC4122
Universally unique identifier (according to » RFC 4122).
MongoBinData::MD5
MD5.
MongoBinData::CUSTOM
User-defined type.

Changelog

Version | Description
1.5.0 | Added MongoBinData::GENERIC and MongoBinData::UUID_RFC4122 constants.

Table of Contents

  • MongoBinData::__construct — Creates a new binary data object
  • MongoBinData::__toString — The string representation of this binary data object


Creates a new binary data object

  • « MongoBinData
  • MongoBinData::__toString »
  • PHP Manual
  • MongoBinData
  • Creates a new binary data object

MongoBinData::__construct

(PECL mongo >= 0.8.1)

MongoBinData::__construct — Creates a new binary data object

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. Alternatives to this method include:

  • MongoDB\BSON\Binary::__construct()

Description

public MongoBinData::__construct ( string $data [, int $type = 0 ] )

Creates a new binary data object.

There are seven types of binary data currently recognized by the BSON spec, which are defined as class constants. For backwards compatibility, the PHP driver uses MongoBinData::BYTE_ARRAY as the default; however, this may change to MongoBinData::GENERIC in the future. Users are encouraged to specify a type instead of relying on the default.

Parameters

data

Binary data.

type

Data type.

Return Values

Returns a new binary data object.

Changelog

Version | Description
1.5.0 | The default changed from 2 (MongoBinData::BYTE_ARRAY) to 0 (MongoBinData::GENERIC).
1.2.11 | Emits E_DEPRECATED when the second argument is not used. The default value for type may change in the near future.


The string representation of this binary data object

  • « MongoBinData::__construct
  • MongoInt32 »
  • PHP Manual
  • MongoBinData
  • The string representation of this binary data object

MongoBinData::__toString

(PECL mongo >= 0.8.1)

MongoBinData::__toString — The string representation of this binary data object

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. Alternatives to this method include:

  • MongoDB\BSON\Binary::getData()

Description

public MongoBinData::__toString ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns the string "<Mongo Binary Data>". To access the contents of a MongoBinData, use the bin field.


The MongoInt32 class

(PECL mongo >=1.0.9)

Warning

This extension that defines this class is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this class in the new extension.

Instead, the new extension chooses the appropriate database type depending on the integer's value.

Introduction

The class can be used to save 32-bit integers to the database on a 64-bit system.

Class synopsis

MongoInt32 {
/* Fields */
public string $value ;
/* Methods */
public __construct ( string $value )
public __toString ( void ) : string
}

Fields

value
This is the string value of the 32-bit number. For instance, 123's value would be "123".

Table of Contents

  • MongoInt32::__construct — Creates a new 32-bit integer
  • MongoInt32::__toString — Returns the string representation of this 32-bit integer


Creates a new 32-bit integer

  • « MongoInt32
  • MongoInt32::__toString »
  • PHP Manual
  • MongoInt32
  • Creates a new 32-bit integer

MongoInt32::__construct

(PECL mongo >= 1.0.9)

MongoInt32::__construct — Creates a new 32-bit integer

This extension that defines this class is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this class in the new extension.

Instead, the new extension chooses the appropriate database type depending on the integer's value.

Description

public MongoInt32::__construct ( string $value )

Creates a new 32-bit number with the given value.

Parameters

value

A number.

Return Values

Returns a new integer.


Returns the string representation of this 32-bit integer

  • « MongoInt32::__construct
  • MongoInt64 »
  • PHP Manual
  • MongoInt32
  • Returns the string representation of this 32-bit integer

MongoInt32::__toString

(PECL mongo >= 1.0.9)

MongoInt32::__toString — Returns the string representation of this 32-bit integer

This extension that defines this class is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this class in the new extension.

Instead, the new extension chooses the appropriate database type depending on the integer's value.

Description

public MongoInt32::__toString ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns the string representation of this integer.


The MongoInt64 class

(PECL mongo >=1.0.9)

Warning

This extension that defines this class is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this class in the new extension.

Instead, the new extension chooses the appropriate database type depending on the integer's value.

Introduction

The class can be used to save 64-bit integers to the database on a 32-bit system.

Class synopsis

MongoInt64 {
/* Fields */
public string $value ;
/* Methods */
public __construct ( string $value )
public __toString ( void ) : string
}

Fields

value
This is the string value of the 64-bit number. For instance, 123's value would be "123".

Table of Contents

  • MongoInt64::__construct — Creates a new 64-bit integer
  • MongoInt64::__toString — Returns the string representation of this 64-bit integer


Creates a new 64-bit integer

  • « MongoInt64
  • MongoInt64::__toString »
  • PHP Manual
  • MongoInt64
  • Creates a new 64-bit integer

MongoInt64::__construct

(PECL mongo >= 1.0.9)

MongoInt64::__construct — Creates a new 64-bit integer

This extension that defines this class is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this class in the new extension.

Instead, the new extension chooses the appropriate database type depending on the integer's value.

Description

public MongoInt64::__construct ( string $value )

Creates a new 64-bit number with the given value.

Parameters

value

A number.

Return Values

Returns a new integer.


Returns the string representation of this 64-bit integer

  • « MongoInt64::__construct
  • MongoDBRef »
  • PHP Manual
  • MongoInt64
  • Returns the string representation of this 64-bit integer

MongoInt64::__toString

(PECL mongo >= 1.0.9)

MongoInt64::__toString — Returns the string representation of this 64-bit integer

This extension that defines this class is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this class in the new extension.

Instead, the new extension chooses the appropriate database type depending on the integer's value.

Description

public MongoInt64::__toString ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns the string representation of this integer.


The MongoDBRef class

(PECL mongo >=0.9.0)

Warning

This extension that defines this class is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this class in the new extension.

The concept of database references, and hence this class, has been deprecated in the database.

Introduction

This class can be used to create lightweight links between objects in different collections.

Motivation: Suppose we need to refer to a document in another collection. The easiest way is to create a field in the current document. For example, if we had a "people" collection and an "addresses" collection, we might want to create a link between each person document and an address document:

Example #1 Linking documents

<?php

$people = $db->people;
$addresses = $db->addresses;

$myAddress = array("line 1" => "123 Main Street",
    "line 2" => null,
    "city" => "Springfield",
    "state" => "Vermont",
    "country" => "USA");

// save the address
$addresses->insert($myAddress);

// save a person with a reference to the address
$me = array("name" => "Fred", "address" => $myAddress['_id']);
$people->insert($me);

?>

Then, later on, we can find the person's address by querying the "addresses" collection with the MongoId we saved in the "people" collection.

Suppose now that we have a more general case, where we don't know which collection (or even which database) contains the referenced document. MongoDBRef is a good choice for this case, as it is a common format that all of the drivers and the database understand.

If each person had a list of things they liked which could come from multiple collections, such as "hobbies", "sports", "books", etc., we could use MongoDBRefs to keep track of what "like" went with what collection:

Example #2 Creating MongoDBRef links

<?php

$people = $db->selectCollection("people");

// model trains are in the "hobbies" collection
$trainRef = MongoDBRef::create("hobbies", $modelTrains['_id']);
// soccer is in the "sports" collection
$soccerRef = MongoDBRef::create("sports", $soccer['_id']);

// now we'll know what collections the items in the "likes" array came from when
// we retrieve this document
$people->insert(array("name" => "Fred", "likes" => array($trainRef, $soccerRef)));

?>

Database references can be thought of as hyperlinks: they give the unique address of another document, but they do not load it or automatically follow the link/reference.

A database reference is just a normal associative array, not an instance of MongoDBRef, so this class is a little different than the other data type classes. This class contains exclusively static methods for manipulating database references.

Class synopsis

MongoDBRef {
/* Methods */
public static create ( string $collection , mixed $id [, string $database ] ) : array
public static get ( MongoDB $db , array $ref ) : array
public static isRef ( mixed $ref ) : bool
}

See Also

MongoDB core docs on » databases references.

Table of Contents

  • MongoDBRef::create — Creates a new database reference
  • MongoDBRef::get — Fetches the object pointed to by a reference
  • MongoDBRef::isRef — Checks if an array is a database reference


Creates a new database reference

  • « MongoDBRef
  • MongoDBRef::get »
  • PHP Manual
  • MongoDBRef
  • Creates a new database reference

MongoDBRef::create

(PECL mongo >= 0.9.0)

MongoDBRef::create — Creates a new database reference

This extension that defines this class is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this class in the new extension.

The concept of database references, and hence this class, has been deprecated.

Description

public static MongoDBRef::create ( string $collection , mixed $id [, string $database ] ) : array

If no database is given, the current database is used.

Parameters

collection

Collection name (without the database name).

id

The _id field of the object to which to link.

database

Database name.

Return Values

Returns the reference.

Examples

Example #1 MongoDBRef::create() example

This creates a database reference to a document in the addresses collection. The MongoCollection::getName() function returns the name of the collection (not including the database name).

<?php
$addresses = $db->addresses;
$people = $db->people;

// save $address so it has an _id
$addresses->insert($address);

// create a reference
$ref = MongoDBRef::create($addresses->getName(), $address['_id']);

// set the field in $person
$person['address'] = $ref;
$people->save($person);
?>

See Also

  • MongoDB::createDBRef() - Creates a database reference
  • MongoCollection::createDBRef() - Creates a database reference


Fetches the object pointed to by a reference

  • « MongoDBRef::create
  • MongoDBRef::isRef »
  • PHP Manual
  • MongoDBRef
  • Fetches the object pointed to by a reference

MongoDBRef::get

(PECL mongo >= 0.9.0)

MongoDBRef::get — Fetches the object pointed to by a reference

This extension that defines this class is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this class in the new extension.

The concept of database references, and hence this class, has been deprecated.

Description

public static MongoDBRef::get ( MongoDB $db , array $ref ) : array

Parameters

db

Database to use.

ref

Reference to fetch.

Return Values

Returns the document to which the reference refers or NULL if the document does not exist (the reference is broken).

Examples

Example #1 MongoCollection::createDBRef() example

<?php

// get $person out of the db
$person = $people->findOne();

// dereference the address
$address = MongoDBRef::get($people->db, $person['address']);

?>

See Also

  • MongoDB::getDBRef() - Fetches the document pointed to by a database reference
  • MongoCollection::getDBRef() - Fetches the document pointed to by a database reference


Checks if an array is a database reference

  • « MongoDBRef::get
  • MongoMinKey »
  • PHP Manual
  • MongoDBRef
  • Checks if an array is a database reference

MongoDBRef::isRef

(PECL mongo >= 0.9.0)

MongoDBRef::isRef — Checks if an array is a database reference

This extension that defines this class is deprecated. Instead, the MongoDB extension should be used. There is no equivalent for this class in the new extension.

The concept of database references, and hence this class, has been deprecated.

Description

public static MongoDBRef::isRef ( mixed $ref ) : bool

This method does not actually follow the reference, so it does not determine if it is broken or not. It merely checks that ref is in valid database reference format (in that it is an object or array with $ref and $id fields).

Parameters

ref

Array or object to check.

Return Values

Returns TRUE on success or FALSE on failure.


The MongoMinKey class

(PECL mongo >= 1.0.2)

Warning

This extension that defines this class is deprecated. Instead, the MongoDB extension should be used. Alternatives to this class include:

  • MongoDB\BSON\MinKey

Introduction

MongoMinKey is an special type used by the database that compares less than all other possible BSON values. Thus, if a query is sorted by a given field in ascending order, any document with a MongoMinKey as its value will be returned first.

MongoMinKey has no associated fields, methods, or constants. It is merely the "smallest" value that can be represented in the database.

Note: MongoMinKey is used internally by MongoDB for indexing and sharding. There is generally no reason to use this class in an application.

Class synopsis

MongoMinKey {
}

Using MongoMinKey as a value

<?php

$collection->insert(array("task" => "lunch", "doBy" => new MongoMinKey));
$collection->insert(array("task" => "staff meeting", "doBy" => new MongoDate(strtotime("+4 days"))));

$cursor = $collection->find()->sort(array("doBy" => 1));

?>

The cursor will return the lunch document followed by the staff meeting document. The lunch document will always be returned first, regardless of what else is added to the collection (unless other documents are added with MongoMinKey in their "doBy" field).

See Also

  • MongoMaxKey


The MongoMaxKey class

(PECL mongo >= 1.0.2)

Warning

This extension that defines this class is deprecated. Instead, the MongoDB extension should be used. Alternatives to this class include:

  • MongoDB\BSON\MaxKey

Introduction

MongoMaxKey is an special type used by the database that compares greater than all other possible BSON values. Thus, if a query is sorted by a given field in ascending order, any document with a MongoMaxKey as its value will be returned last.

MongoMaxKey has no associated fields, methods, or constants. It is merely the "greatest" value that can be represented in the database.

Note: MongoMaxKey is used internally by MongoDB for indexing and sharding. There is generally no reason to use this class in an application.

Class synopsis

MongoMaxKey {
}

Using MongoMaxKey as a value

<?php

$collection->insert(array("task" => "dishes", "doBy" => new MongoMaxKey));
$collection->insert(array("task" => "staff meeting", "doBy" => new MongoDate(strtotime("+4 days"))));

$cursor = $collection->find()->sort(array("doBy" => 1));

?>

The cursor will return the staff meeting document followed by the dishes document. The dishes document will always be returned last, regardless of what else is added to the collection (unless other documents are added with MongoMaxKey in their "doBy" field).

See Also

  • MongoMinKey


The MongoTimestamp class

(PECL mongo >=1.0.1)

Warning

This extension that defines this class is deprecated. Instead, the MongoDB extension should be used. Alternatives to this class include:

  • MongoDB\BSON\Timestamp

Introduction

MongoTimestamp is an internal type used by MongoDB for replication and sharding. It consists of a 4-byte timestamp (i.e. seconds since the epoch) and a 4-byte increment. This type is not intended for storing time or date values (e.g. a "createdAt" field on a document).

Note: Unless you are writing an application that interacts with MongoDB's replication oplog or sharding internals: stop, go directly to MongoDate, do not pass go, and do not collect 200 dollars. This is not the class you are looking for.

Class synopsis

MongoTimestamp {
/* Fields */
public int $sec = 0 ;
public int $inc = 0 ;
/* Methods */
public __construct ([ int $sec = time() [, int $inc ]] )
public __toString ( void ) : string
}

Table of Contents

  • MongoTimestamp::__construct — Creates a new timestamp
  • MongoTimestamp::__toString — Returns a string representation of this timestamp


Creates a new timestamp

  • « MongoTimestamp
  • MongoTimestamp::__toString »
  • PHP Manual
  • MongoTimestamp
  • Creates a new timestamp

MongoTimestamp::__construct

(PECL mongo >= 1.0.1)

MongoTimestamp::__construct — Creates a new timestamp

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. Alternatives to this method include:

  • MongoDB\BSON\Timestamp::__construct()

Description

public MongoTimestamp::__construct ([ int $sec = time() [, int $inc ]] )

Creates a new timestamp. If no parameters are given, the current time is used and the increment is automatically provided. The increment is set to 0 when the module is loaded and is incremented every time this constructor is called (without the $inc parameter passed in).

Parameters

sec

Number of seconds since the epoch (i.e. 1 Jan 1970 00:00:00.000 UTC).

inc

Increment.

Return Values

Returns this new timestamp.

See Also

  • MongoTimestamp::__toString() - Returns a string representation of this timestamp


Returns a string representation of this timestamp

  • « MongoTimestamp::__construct
  • GridFS Classes »
  • PHP Manual
  • MongoTimestamp
  • Returns a string representation of this timestamp

MongoTimestamp::__toString

(PECL mongo >= 1.0.1)

MongoTimestamp::__toString — Returns a string representation of this timestamp

This extension that defines this method is deprecated. Instead, the MongoDB extension should be used. Alternatives to this method include:

  • MongoDB\BSON\Timestamp::__toString()

Description

public MongoTimestamp::__toString ( void ) : string

Returns the "sec" field of this timestamp.

Parameters

This function has no parameters.

Return Values

The seconds since epoch represented by this timestamp.


  • « MongoTimestamp::__toString
  • MongoGridFS »
  • PHP Manual
  • Mongo
  • GridFS Classes

GridFS Classes

Table of Contents

  • MongoGridFS
  • MongoGridFSFile
  • MongoGridFSCursor


The MongoGridFS class

(PECL mongo >=0.9.0)

Introduction

Utilities for storing and retrieving files from the database.

GridFS is a storage specification all supported drivers implement. Basically, it defines two collections: files, for file metadata, and chunks, for file content. If the file is large, it will automatically be split into smaller chunks and each chunk will be saved as a document in the chunks collection.

Each document in the files collection contains the filename, upload date, and md5 hash. It also contains a unique _id field, which can be used to query the chunks collection for the file's content. Each document in the chunks collection contains a chunk of binary data, a files_id field that matches its file's _id, and the position of this chunk in the overall file.

For example, the files document is something like:

<?php
array("_id" => 123456789, "filename" => "foo.txt", "chunkSize" => 3, "length" => 12);
?>
and the chunks documents look like:
<?php
array("files_id" => 123456789, "n" => 0, "data" => new MongoBinData("abc"));
array("files_id" => 123456789, "n" => 1, "data" => new MongoBinData("def"));
array("files_id" => 123456789, "n" => 2, "data" => new MongoBinData("ghi"));
array("files_id" => 123456789, "n" => 3, "data" => new MongoBinData("jkl"));
?>
Of course, the default chunk size is thousands of bytes, but that makes an unwieldy example.

Inter-Language Compatibility

You should be able to use any files created by MongoGridFS with any other drivers, and vice versa. However, some drivers expect that all metadata associated with a file be in a "metadata" field. If you're going to be using other languages, it's a good idea to wrap info you might want them to see in a "metadata" field. For example, instead of:

<?php

$grid->storeFile("somefile.txt", array("date" => new MongoDate()));

?>

use something like:

<?php

$grid->storeFile("somefile.txt", array("metadata" => array("date" => new MongoDate())));

?>

The MongoGridFS Family

MongoGridFS represents the files and chunks collections. MongoGridFS extends MongoCollection, and an instance of MongoGridFS has access to all of MongoCollection methods, which act on the files collection:

<?php

$grid = $db->getGridFS();
$grid->update(array("filename" => "foo"), $newObj); // update on the files collection

?>

Another example of manipulating metadata:

<?php

// save a file
$id = $grid->storeFile("game.tgz");
$game = $grid->findOne();

// add a downloads counter
$game->file['downloads'] = 0;
$grid->save($game->file);

// increment the counter
$grid->update(array("_id" => $id), array('$inc' => array("downloads" => 1)));

?>

You can also access the chunks collection from an instance of MongoGridFS:

<?php

  $chunks = $grid->chunks; // $chunks is a normal MongoCollection
$chunks->insert(array("x" => 4));

?>

There are some methods for MongoGridFS with the same name as MongoCollection methods, that behave slightly differently. For example, MongoGridFS::remove() will remove any objects that match the criteria from the files collection and their content from the chunks collection.

To store something new in GridFS, there are a couple options. If you have a filename, you can say:

<?php

$grid->storeFile($filename, array("whatever" => "metadata", "you" => "want"));

?>

If you have a string of bytes that isn't a file, you can also store that using MongoGridFS::storeBytes():

<?php

$grid->storeBytes($bytes, array("whatever" => "metadata", "you" => "want"));

?>

Querying a MongoGridFS collection returns a MongoGridFSCursor, which behaves like a normal MongoCursor except that it returns MongoGridFSFiles instead of associative arrays.

MongoGridFSFiles can be written back to disc using MongoGridFSFile::write() or retrieved in memory using MongoGridFSFile::getBytes(). There is currently no method that automatically streams chunks, but it would be fairly easy to write by querying the $grid->chunks collection.

MongoGridFSFile objects contain a field file which contains any file metadata.

Class synopsis

extends MongoCollection {
/* Fields */
public MongoCollection $chunks = NULL ;
protected string $filesName = NULL ;
protected string $chunksName = NULL ;
/* Methods */
public __construct ( MongoDB $db [, string $prefix = "fs" [, mixed $chunks = "fs" ]] )
public delete ( mixed $id ) : bool|array
public drop ( void ) : array
public find ([ array $query = array() [, array $fields = array() ]] ) : MongoGridFSCursor
public findOne ([ mixed $query = array() [, mixed $fields = array() ]] ) : MongoGridFSFile
public get ( mixed $id ) : MongoGridFSFile
public put ( string $filename [, array $metadata = array() [, array $options = array() ]] ) : mixed
public remove ([ array $criteria = array() [, array $options = array() ]] ) : bool|array
public storeBytes ( string $bytes [, array $metadata = array() [, array $options = array() ]] ) : mixed
public storeFile ( string|resource $filename [, array $metadata = array() [, array $options = array() ]] ) : mixed
public storeUpload ( string $name [, array $metadata ] ) : mixed
}

See Also

  • MongoDB core docs on » GridFS
  • LightCube Solutions blog post on » saving user uploads
  • LightCube Solutions blog post on » adding metadata to files

Table of Contents

  • MongoGridFS::__construct — Creates new file collections
  • MongoGridFS::delete — Remove a file and its chunks from the database
  • MongoGridFS::drop — Drops the files and chunks collections
  • MongoGridFS::find — Queries for files
  • MongoGridFS::findOne — Returns a single file matching the criteria
  • MongoGridFS::get — Retrieve a file from the database
  • MongoGridFS::put — Stores a file in the database
  • MongoGridFS::remove — Remove files and their chunks from the database
  • MongoGridFS::storeBytes — Stores a string of bytes in the database
  • MongoGridFS::storeFile — Stores a file in the database
  • MongoGridFS::storeUpload — Stores an uploaded file in the database


Creates new file collections

  • « MongoGridFS
  • MongoGridFS::delete »
  • PHP Manual
  • MongoGridFS
  • Creates new file collections

MongoGridFS::__construct

(PECL mongo >=0.9.0)

MongoGridFS::__construct — Creates new file collections

Description

public MongoGridFS::__construct ( MongoDB $db [, string $prefix = "fs" [, mixed $chunks = "fs" ]] )

Files as stored across two collections, the first containing file meta information, the second containing chunks of the actual file. By default, fs.files and fs.chunks are the collection names used.

Use one argument to specify a prefix other than "fs":

$fs = new MongoGridFS($db, "myfiles");
uses myfiles.files and myfiles.chunks collections.

Parameters

db

Database.

files

Optional collection name prefix.


Remove a file and its chunks from the database

  • « MongoGridFS::__construct
  • MongoGridFS::drop »
  • PHP Manual
  • MongoGridFS
  • Remove a file and its chunks from the database

MongoGridFS::delete

(PECL mongo >=1.0.8)

MongoGridFS::delete — Remove a file and its chunks from the database

Description

public MongoGridFS::delete ( mixed $id ) : bool|array

Note:

MongoGridFS::delete() is a convenience method for calling MongoGridFS::remove() with specific criteria and default options parameters.

Parameters

id

_id of the file to remove.

Return Values

Returns an array containing the status of the removal (with respect to the files collection) if a write concern is applied. Otherwise, returns TRUE.

Fields in the status array are described in the documentation for MongoCollection::insert().

Errors/Exceptions

Throws MongoCursorException if the "w" option is set and the write fails.

Throws MongoCursorTimeoutException if the "w" option is set to a value greater than one and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in MongoCollection::$wtimeout is milliseconds.


Drops the files and chunks collections

  • « MongoGridFS::delete
  • MongoGridFS::find »
  • PHP Manual
  • MongoGridFS
  • Drops the files and chunks collections

MongoGridFS::drop

(PECL mongo >=0.9.0)

MongoGridFS::drop — Drops the files and chunks collections

Description

public MongoGridFS::drop ( void ) : array

Parameters

This function has no parameters.

Return Values

The database response.


Queries for files

  • « MongoGridFS::drop
  • MongoGridFS::findOne »
  • PHP Manual
  • MongoGridFS
  • Queries for files

MongoGridFS::find

(PECL mongo >=0.9.0)

MongoGridFS::find — Queries for files

Description

 public MongoGridFS::find
  ([ array $query = array()
 [, array $fields = array()
]] ) : MongoGridFSCursor

Parameters

query

The query.

fields

Fields to return.

Return Values

A MongoGridFSCursor.


Returns a single file matching the criteria

  • « MongoGridFS::find
  • MongoGridFS::get »
  • PHP Manual
  • MongoGridFS
  • Returns a single file matching the criteria

MongoGridFS::findOne

(PECL mongo >=0.9.0)

MongoGridFS::findOne — Returns a single file matching the criteria

Description

 public MongoGridFS::findOne
  ([ mixed $query = array()
 [, mixed $fields = array()
]] ) : MongoGridFSFile

Parameters

query

The filename or criteria for which to search.

Return Values

Returns a MongoGridFSFile or NULL.

Examples

Example #1 MongoGridFS::findOne() example

Example demonstrating how to find a single file from the MongoGridFS.

<?php

$downloads = $mongo->my_db->getGridFS('downloads');

$downloads->storeFile('filename.tgz');

$download = $downloads->findOne('filename.tgz'); // instance of MongoGridFSFile

print_r($download);
?>

See MongoGridFSFile for more information about how to work with files.

The above example will output something similar to:

MongoGridFSFile Object
(
    [file] => Array
        (
            [_id] => MongoId Object
                (
                )

            [filename] => filename.tgz
            [uploadDate] => MongoDate Object
                (
                    [sec] => 1274288014
                    [usec] => 467000
                )

            [chunkSize] => 262144
            [md5] => d41d8cd98f00b204e9800998ecf8427e
        )

    [gridfs:protected] => MongoGridFS Object
        (
            [chunks] => MongoCollection Object
                (
                )

            [filesName:protected] => downloads.files
            [chunksName:protected] => downloads.chunks
        )

)


Retrieve a file from the database

  • « MongoGridFS::findOne
  • MongoGridFS::put »
  • PHP Manual
  • MongoGridFS
  • Retrieve a file from the database

MongoGridFS::get

(PECL mongo >=1.0.8)

MongoGridFS::get — Retrieve a file from the database

Description

public MongoGridFS::get ( mixed $id ) : MongoGridFSFile

Parameters

id

_id of the file to find.

Return Values

Returns the file, if found, or NULL.


Stores a file in the database

  • « MongoGridFS::get
  • MongoGridFS::remove »
  • PHP Manual
  • MongoGridFS
  • Stores a file in the database

MongoGridFS::put

(PECL mongo >=1.0.8)

MongoGridFS::put — Stores a file in the database

Description

public MongoGridFS::put ( string $filename [, array $metadata = array() [, array $options = array() ]] ) : mixed

Note:

MongoGridFS::put() is an alias of MongoGridFS::storeFile().

Parameters

filename

Name of the file to store.

metadata

Other metadata fields to include in the file document.

Note:

These fields may also overwrite those that would be created automatically by the driver, as described in the MongoDB core documentation for the » files collection. Some practical use cases for this behavior would be to specify a custom chunkSize or _id for the file.

options

An array of options for the insert operations executed against the chunks and files collections. See MongoCollection::insert() for documentation on these these options.

Return Values

Returns the _id of the saved file document. This will be a generated MongoId unless an _id was explicitly specified in the metadata parameter.

Errors/Exceptions

Throws MongoGridFSException if there is an error reading filename or inserting into the chunks or files collections.

See Also

  • MongoGridFS::storeBytes() - Stores a string of bytes in the database
  • MongoGridFS::storeFile() - Stores a file in the database
  • MongoGridFS::storeUpload() - Stores an uploaded file in the database
  • MongoDB core docs on » GridFS


Remove files and their chunks from the database

  • « MongoGridFS::put
  • MongoGridFS::storeBytes »
  • PHP Manual
  • MongoGridFS
  • Remove files and their chunks from the database

MongoGridFS::remove

(PECL mongo >=0.9.0)

MongoGridFS::remove — Remove files and their chunks from the database

Description

 public MongoGridFS::remove
  ([ array $criteria = array()
 [, array $options = array()
]] ) : bool|array

Parameters

criteria

The filename or criteria for which to search.

options

An array of options for the remove operations executed against the chunks and files collections. See MongoCollection::remove() for documentation on these options.

Return Values

Returns an array containing the status of the removal (with respect to the files collection) if the "w" option is set. Otherwise, returns TRUE.

Fields in the status array are described in the documentation for MongoCollection::insert().

Errors/Exceptions

Throws MongoCursorException if the "w" option is set and the write fails.

Throws MongoCursorTimeoutException if the "w" option is set to a value greater than one and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in MongoCollection::$wtimeout is milliseconds.


Stores a string of bytes in the database

  • « MongoGridFS::remove
  • MongoGridFS::storeFile »
  • PHP Manual
  • MongoGridFS
  • Stores a string of bytes in the database

MongoGridFS::storeBytes

(PECL mongo >=0.9.2)

MongoGridFS::storeBytes — Stores a string of bytes in the database

Description

public MongoGridFS::storeBytes ( string $bytes [, array $metadata = array() [, array $options = array() ]] ) : mixed

Parameters

bytes

String of bytes to store.

metadata

Other metadata fields to include in the file document.

Note:

These fields may also overwrite those that would be created automatically by the driver, as described in the MongoDB core documentation for the » files collection. Some practical use cases for this behavior would be to specify a custom chunkSize or _id for the file.

options

An array of options for the insert operations executed against the chunks and files collections. See MongoCollection::insert() for documentation on these these options.

Return Values

Returns the _id of the saved file document. This will be a generated MongoId unless an _id was explicitly specified in the metadata parameter.

Errors/Exceptions

Throws MongoGridFSException if there is an error inserting into the chunks or files collections.

Examples

Example #1 MongoGridFS::storeBytes() with additional metadata

<?php
$m = new MongoClient();
$gridfs = $m->selectDB('test')->getGridFS();

$bytes = 'abcdefghijklmnopqrstuvwxyz';
$id = $gridfs->storeBytes($bytes, array('_id' => 'alphabet'));
$gridfsFile = $gridfs->get($id);

var_dump($gridfsFile->file);
?>

The above example will output something similar to:

array(7) {
  ["_id"]=>
  string(8) "alphabet"
  ["uploadDate"]=>
  object(MongoDate)#7 (0) {
  }
  ["length"]=>
  int(26)
  ["chunkSize"]=>
  int(262144)
  ["md5"]=>
  string(32) "c3fcd3d76192e4007dfb496cca67e13b"
}

See Also

  • MongoGridFS::put() - Stores a file in the database
  • MongoGridFS::storeFile() - Stores a file in the database
  • MongoGridFS::storeUpload() - Stores an uploaded file in the database
  • MongoDB core docs on » GridFS


Stores a file in the database

  • « MongoGridFS::storeBytes
  • MongoGridFS::storeUpload »
  • PHP Manual
  • MongoGridFS
  • Stores a file in the database

MongoGridFS::storeFile

(PECL mongo >=0.9.0)

MongoGridFS::storeFile — Stores a file in the database

Description

public MongoGridFS::storeFile ( string|resource $filename [, array $metadata = array() [, array $options = array() ]] ) : mixed

Parameters

filename

Name of the file or a readable stream to store.

metadata

Other metadata fields to include in the file document.

Note:

These fields may also overwrite those that would be created automatically by the driver, as described in the MongoDB core documentation for the » files collection. Some practical use cases for this behavior would be to specify a custom chunkSize or _id for the file.

options

An array of options for the insert operations executed against the chunks and files collections. See MongoCollection::insert() for documentation on these these options.

Return Values

Returns the _id of the saved file document. This will be a generated MongoId unless an _id was explicitly specified in the metadata parameter.

Errors/Exceptions

Throws MongoGridFSException if there is an error reading filename or inserting into the chunks or files collections.

Examples

Example #1 MongoGridFS::storeFile() with additional metadata

<?php
$m = new MongoClient();
$gridfs = $m->selectDB('test')->getGridFS();

$id = $gridfs->storeFile('example.txt', array('contentType' => 'plain/text'));
$gridfsFile = $gridfs->get($id);

var_dump($gridfsFile->file);
?>

The above example will output something similar to:

array(7) {
  ["_id"]=>
  object(MongoId)#6 (0) {
  }
  ["contentType"]=>
  string(10) "plain/text"
  ["filename"]=>
  string(11) "example.txt"
  ["uploadDate"]=>
  object(MongoDate)#7 (0) {
  }
  ["length"]=>
  int(26)
  ["chunkSize"]=>
  int(262144)
  ["md5"]=>
  string(32) "c3fcd3d76192e4007dfb496cca67e13b"
}

See Also

  • MongoGridFS::put() - Stores a file in the database
  • MongoGridFS::storeBytes() - Stores a string of bytes in the database
  • MongoGridFS::storeUpload() - Stores an uploaded file in the database
  • MongoDB core docs on » GridFS


Stores an uploaded file in the database

  • « MongoGridFS::storeFile
  • MongoGridFSFile »
  • PHP Manual
  • MongoGridFS
  • Stores an uploaded file in the database

MongoGridFS::storeUpload

(PECL mongo >=0.9.0)

MongoGridFS::storeUpload — Stores an uploaded file in the database

Description

public MongoGridFS::storeUpload ( string $name [, array $metadata ] ) : mixed

Parameters

name

The name of the uploaded file(s) to store. This should correspond to the file field's name attribute in the HTML form.

metadata

Other metadata fields to include in the file document.

Note:

These fields may also overwrite those that would be created automatically by the driver, as described in the MongoDB core documentation for the » files collection. Some practical use cases for this behavior would be to specify a custom chunkSize or _id for the file.

Note:

The filename field will be populated with the client's filename (e.g. $_FILES['foo']['name']).

Return Values

Returns the _id of the saved file document. This will be a generated MongoId unless an _id was explicitly specified in the metadata parameter.

Note:

If multiple files are uploaded using the same field name, this method will not return anything; however, the files themselves will still be processed.

Errors/Exceptions

Throws MongoGridFSException if there is an error reading the uploaded file(s) or inserting into the chunks or files collections.

Changelog

Version | Description
1.2.5 | Changed second parameter to an array of metadata. Pre-1.2.5, the second parameter was an optional string overriding the filename.

Examples

Example #1 MongoGridFS::storeUpload() HTML form example

Suppose you have the following HTML form:

<form method="POST" enctype="multipart/form-data">
    <label for="username">Username:</label>
    <input type="text" name="username" id="username" />

    <label for="pic">Please upload a profile picture:</label>
    <input type="file" name="pic" id="pic" />

    <input type="submit" />
</form>

If you wanted to store the uploaded image in MongoDB, you could do the following in the script handling the form submission:

<?php
$m = new MongoClient();
$gridfs = $m->selectDB('test')->getGridFS();

$gridfs->storeUpload('pic', array('username' => $_POST['username']));
?>

See Also

  • MongoGridFS::put() - Stores a file in the database
  • MongoGridFS::storeBytes() - Stores a string of bytes in the database
  • MongoGridFS::storeFile() - Stores a file in the database
  • MongoDB core docs on » GridFS


The MongoGridFSFile class

(PECL mongo >=0.9.0)

Introduction

A database file object.

Class synopsis

MongoGridFSFile {
/* Fields */
public array $file = NULL ;
protected MongoGridFS $gridfs = NULL ;
/* Methods */
public MongoGridfsFile::__construct ( MongoGridFS $gridfs , array $file )
public getBytes ( void ) : string
public getFilename ( void ) : string
public getResource ( void ) : resource
public getSize ( void ) : int
public write ([ string $filename = NULL ] ) : int
}

Table of Contents

  • MongoGridfsFile::__construct — Create a new GridFS file
  • MongoGridFSFile::getBytes — Returns this file's contents as a string of bytes
  • MongoGridFSFile::getFilename — Returns this file's filename
  • MongoGridFSFile::getResource — Returns a resource that can be used to read the stored file
  • MongoGridFSFile::getSize — Returns this file's size
  • MongoGridFSFile::write — Writes this file to the filesystem


Create a new GridFS file

  • « MongoGridFSFile
  • MongoGridFSFile::getBytes »
  • PHP Manual
  • MongoGridFSFile
  • Create a new GridFS file

MongoGridfsFile::__construct

(PECL mongo >=0.9.0)

MongoGridfsFile::__construct — Create a new GridFS file

Description

public MongoGridfsFile::__construct ( MongoGridFS $gridfs , array $file )

Parameters

gridfs

The parent MongoGridFS instance.

file

A file from the database.

Return Values

Returns a new MongoGridFSFile.


Returns this file's contents as a string of bytes

  • « MongoGridfsFile::__construct
  • MongoGridFSFile::getFilename »
  • PHP Manual
  • MongoGridFSFile
  • Returns this file's contents as a string of bytes

MongoGridFSFile::getBytes

(PECL mongo >=0.9.0)

MongoGridFSFile::getBytes — Returns this file's contents as a string of bytes

Description

public MongoGridFSFile::getBytes ( void ) : string

Warning: this will load the file into memory. If the file is bigger than your memory, this will cause problems!

Parameters

This function has no parameters.

Return Values

Returns a string of the bytes in the file.

Examples

Example #1 MongoGridFSFile::getBytes() example

<?php

$images = $db->my_db->getGridFS('images');

$image = $images->findOne('jwage.png');

header('Content-type: image/png;');
echo $image->getBytes();
?>


Returns this file's filename

  • « MongoGridFSFile::getBytes
  • MongoGridFSFile::getResource »
  • PHP Manual
  • MongoGridFSFile
  • Returns this file's filename

MongoGridFSFile::getFilename

(PECL mongo >=0.9.0)

MongoGridFSFile::getFilename — Returns this file's filename

Description

public MongoGridFSFile::getFilename ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns the filename.


Returns a resource that can be used to read the stored file

  • « MongoGridFSFile::getFilename
  • MongoGridFSFile::getSize »
  • PHP Manual
  • MongoGridFSFile
  • Returns a resource that can be used to read the stored file

MongoGridFSFile::getResource

(PECL mongo >=1.3.0)

MongoGridFSFile::getResource — Returns a resource that can be used to read the stored file

Description

public MongoGridFSFile::getResource ( void ) : resource

This method returns a stream resource that can be used with all file functions in PHP that deal with reading files. The contents of the file are pulled out of MongoDB on the fly, so that the whole file does not have to be loaded into memory first.

At most two GridFSFile chunks will be loaded in memory.

Parameters

This function has no parameters.

Return Values

Returns a resource that can be used to read the file with

Examples

Example #1 MongoGridFSFile::getResource() example

<?php
$m = new Mongo;
$images = $m->my_db->getGridFS('images');

$image = $images->findOne('mongo.png');

header('Content-type: image/png;');
$stream = $image->getResource();

while (!feof($stream)) {
    echo fread($stream, 8192);
}
?>


Returns this file's size

  • « MongoGridFSFile::getResource
  • MongoGridFSFile::write »
  • PHP Manual
  • MongoGridFSFile
  • Returns this file's size

MongoGridFSFile::getSize

(PECL mongo >=0.9.0)

MongoGridFSFile::getSize — Returns this file's size

Description

public MongoGridFSFile::getSize ( void ) : int

Parameters

This function has no parameters.

Return Values

Returns this file's size


Writes this file to the filesystem

  • « MongoGridFSFile::getSize
  • MongoGridFSCursor »
  • PHP Manual
  • MongoGridFSFile
  • Writes this file to the filesystem

MongoGridFSFile::write

(PECL mongo >=0.9.0)

MongoGridFSFile::write — Writes this file to the filesystem

Description

public MongoGridFSFile::write ([ string $filename = NULL ] ) : int

Parameters

filename

The location to which to write the file. If none is given, the stored filename will be used.

Return Values

Returns the number of bytes written.

Examples

Example #1 MongoGridFSFile::write() example

<?php

$images = $db->my_db->getGridFS('images');

$image = $images->findOne('jwage.png');
$image->write('/path/to/write/jwage.png');
?>


The MongoGridFSCursor class

(PECL mongo >=0.9.0)

Introduction

Cursor for database file results.

Class synopsis

extends MongoCursor {
/* Fields */
protected MongoGridFS $gridfs = NULL ;
/* Methods */
public __construct ( MongoGridFS $gridfs , resource $connection , string $ns , array $query , array $fields )
public current ( void ) : MongoGridFSFile
public getNext ( void ) : MongoGridFSFile
public key ( void ) : string
}

Table of Contents

  • MongoGridFSCursor::__construct — Create a new cursor
  • MongoGridFSCursor::current — Returns the current file
  • MongoGridFSCursor::getNext — Return the next file to which this cursor points, and advance the cursor
  • MongoGridFSCursor::key — Returns the current result's filename


Create a new cursor

  • « MongoGridFSCursor
  • MongoGridFSCursor::current »
  • PHP Manual
  • MongoGridFSCursor
  • Create a new cursor

MongoGridFSCursor::__construct

(PECL mongo >=0.9.0)

MongoGridFSCursor::__construct — Create a new cursor

Description

public MongoGridFSCursor::__construct ( MongoGridFS $gridfs , resource $connection , string $ns , array $query , array $fields )

Parameters

gridfs

Related GridFS collection.

connection

Database connection.

ns

Full name of database and collection.

query

Database query.

fields

Fields to return.

Return Values

Returns the new cursor.


Returns the current file

  • « MongoGridFSCursor::__construct
  • MongoGridFSCursor::getNext »
  • PHP Manual
  • MongoGridFSCursor
  • Returns the current file

MongoGridFSCursor::current

(PECL mongo >=0.9.0)

MongoGridFSCursor::current — Returns the current file

Description

public MongoGridFSCursor::current ( void ) : MongoGridFSFile

Parameters

This function has no parameters.

Return Values

The current file.


Return the next file to which this cursor points, and advance the cursor

  • « MongoGridFSCursor::current
  • MongoGridFSCursor::key »
  • PHP Manual
  • MongoGridFSCursor
  • Return the next file to which this cursor points, and advance the cursor

MongoGridFSCursor::getNext

(PECL mongo >=0.9.0)

MongoGridFSCursor::getNext — Return the next file to which this cursor points, and advance the cursor

Description

public MongoGridFSCursor::getNext ( void ) : MongoGridFSFile

Parameters

This function has no parameters.

Return Values

Returns the next file.


Returns the current result's filename

  • « MongoGridFSCursor::getNext
  • Batch Classes »
  • PHP Manual
  • MongoGridFSCursor
  • Returns the current result's filename

MongoGridFSCursor::key

(PECL mongo >=0.9.0)

MongoGridFSCursor::key — Returns the current result's filename

Description

public MongoGridFSCursor::key ( void ) : string

Parameters

This function has no parameters.

Return Values

The current result's _id as a string.

Changelog

Version | Description
1.3.0 | The document's _id is returned as a string value, since the key should be unique. Pre-1.3.0, filename was returned.


Batch Classes

Table of Contents

  • MongoWriteBatch
  • MongoInsertBatch
  • MongoUpdateBatch
  • MongoDeleteBatch


The MongoWriteBatch class

(PECL mongo >=1.5.0)

Introduction

MongoWriteBatch is the base class for the MongoInsertBatch, MongoUpdateBatch and MongoDeleteBatch classes.

MongoWriteBatch allows you to "batch up" multiple operations (of same type) and shipping them all to MongoDB at the same time. This can be especially useful when operating on many documents at the same time to reduce roundtrips.

Prior to version 1.5.0 of the driver it was possible to use MongoCollection::batchInsert(), however, as of 1.5.0 that method is now discouraged.

Note: This class is only available when talking to MongoDB 2.6.0 (and later) servers. It will throw MongoProtocolException if attempting to use it on older MongoDB servers.

Class synopsis

MongoWriteBatch {
/* Constants */
const int COMMAND_INSERT = 1 ;
const int COMMAND_UPDATE = 2 ;
const int COMMAND_DELETE = 3 ;
/* Methods */
protected __construct ( MongoCollection $collection [, string $batch_type [, array $write_options ]] )
public add ( array $item ) : bool
final public execute ( array $write_options ) : array
}

MongoWriteBatch types

MongoWriteBatch::COMMAND_INSERT

Create an Insert Write Batch

MongoWriteBatch::COMMAND_UPDATE

Create an Update Write Batch

MongoWriteBatch::COMMAND_DELETE

Create an Delete Write Batch

Description

When executing a batch by calling MongoWriteBatch::execute(), MongoWriteBatch will send up to maxWriteBatchSize (defaults to 1000) documents or maxBsonObjectSize (defaults to 16777216 bytes), whichever comes first.

Note:

Documents will never be partially transferred. When adding documents to the batch, that overflows the limit, a new batch will be created and the document put into the new batch.

Errors/Exceptions

  • Exception on parameter parsing failures
  • Exception on argument validation errors (e.g. missing keys)
  • MongoProtocolException when talking to MongoDB server older then 2.6.0.
  • MongoProtocolException on socket errors.
  • MongoWriteConcernException when a write fails due to WriteConcerns

Examples

Example #1 MongoWriteBatch example

Adding documents to a Insert batch and then execute it

<?php
$mc = new MongoClient("localhost");

$collection = $mc->selectCollection("test", "test");

$docs = array();
$docs[] = array("my" => "demo");
$docs[] = array("is" => "working");
$docs[] = array("pretty" => "well");

$batch = new MongoInsertBatch($collection);
foreach($docs as $document) {
    $batch->add($document);
}
$retval = $batch->execute(array("w" => 1));
var_dump($retval);
?>

The above example will output:

array(2) {
  ["nInserted"]=>
  int(3)
  ["ok"]=>
  bool(true)
}

Table of Contents

  • MongoWriteBatch::add — Adds a write operation to a batch
  • MongoWriteBatch::__construct — Creates a new batch of write operations
  • MongoWriteBatch::execute — Executes a batch of write operations


Adds a write operation to a batch

  • « MongoWriteBatch
  • MongoWriteBatch::__construct »
  • PHP Manual
  • MongoWriteBatch
  • Adds a write operation to a batch

MongoWriteBatch::add

(PECL mongo >= 1.5.0)

MongoWriteBatch::add — Adds a write operation to a batch

Description

public MongoWriteBatch::add ( array $item ) : bool

Adds a write operation to the batch.

If $item causes the batch to exceed the maxWriteBatchSize or maxBsonObjectSize limits, the driver will internally split the batches into multiple write commands upon calling MongoWriteBatch::execute().

Parameters

item

An array that describes a write operation. The structure of this value depends on the batch's operation type.

Batch type | Argument expectation
MongoWriteBatch::COMMAND_INSERT | The document to add.
MongoWriteBatch::COMMAND_UPDATE

Raw update operation.

Required keys are "q" and "u", which correspond to the $criteria and $new_object parameters of MongoCollection::update(), respectively.

Optional keys are "multi" and "upsert", which correspond to the "multiple" and "upsert" options for MongoCollection::update(), respectively. If unspecified, both options default to FALSE.
MongoWriteBatch::COMMAND_DELETE

Raw delete operation.

Required keys are: "q" and "limit", which correspond to the $criteria parameter and "justOne" option of MongoCollection::remove(), respectively.

The "limit" option is an integer; however, MongoDB only supports 0 (i.e. remove all matching documents) and 1 (i.e. remove at most one matching document) at this time.

Return Values

Returns TRUE on success and throws an exception on failure.

Errors/Exceptions

  • Exception on parameter parsing failures
  • Exception on argument validation errors (e.g. missing keys)

Examples

Example #1 MongoWriteBatch::add() example

Batching up multiple insert operations

<?php
$mc = new MongoClient("localhost");
$collection = $mc->selectCollection("test", "test");

$docs = array();
$docs[] = array("my" => "demo");
$docs[] = array("is" => "working");
$docs[] = array("pretty" => "well");

$batch = new MongoInsertBatch($collection);
foreach($docs as $document) {
    $batch->add($document);
}
$batch->execute(array("w" => 1));
?>

Example #2 MongoWriteBatch::add() example

Batching up multiple update operations

<?php
$mc = new MongoClient("localhost");
$collection = $mc->selectCollection("test", "test");

$item1 = array(
    "q" => array("my" => "demo"),
    "u" => array('$set' => array("try" => 1)),
    "multi"  => false, /* default value */
    "upsert" => false, /* default value */
);
$item2 = array(
    "q" => array("is" => "working"),
    "u" => array('$set' => array("try" => 2)),
    "multi" => true,
);
$item3 = array(
    "q" => array("created" => "new-document"),
    "u" => array('$set' => array("try" => 3)),
    "upsert" => true,
);

$batch = new MongoUpdateBatch($collection);
$batch->add($item1);
$batch->add($item2);
$batch->add($item3);
$batch->execute(array("w" => 1));

?>

Example #3 MongoWriteBatch::add() example

Batching up multiple delete operations

<?php
$mc = new MongoClient("localhost");
$collection = $mc->selectCollection("test", "test");

$item1 = array(
    "q" => array("my" => "demo"),
    "limit" => 1,
);
$item2 = array(
    "q" => array("try" => 3),
    "limit" => 1,
);

$batch = new MongoDeleteBatch($collection);
$batch->add($item1);
$batch->add($item2);
$batch->execute(array("w" => 1));
?>


Creates a new batch of write operations

  • « MongoWriteBatch::add
  • MongoWriteBatch::execute »
  • PHP Manual
  • MongoWriteBatch
  • Creates a new batch of write operations

MongoWriteBatch::__construct

(PECL mongo >= 1.5.0)

MongoWriteBatch::__construct — Creates a new batch of write operations

Description

protected MongoWriteBatch::__construct ( MongoCollection $collection [, string $batch_type [, array $write_options ]] )

Constructs a new MongoWriteBatch.

Note:

This is a protected constructor. Please use one of the classes inheriting MongoWriteBatch.

Parameters

collection

The MongoCollection to execute the batch on. Its write concern will be copied and used as the default write concern if none is given as $write_options or during MongoWriteBatch::execute().

batch_type

One of:

  • 0 - make an MongoWriteBatch::COMMAND_INSERT batch
  • 1 - make an MongoWriteBatch::COMMAND_UPDATE batch
  • 2 - make a MongoWriteBatch::COMMAND_DELETE batch

write_options

An array of Write Options.

key | value meaning
w (int|string) | Write concern value
wtimeout (int) | Maximum time to wait for replication
ordered | Determines if MongoDB must apply this batch in order. Ordered writes execute serially (i.e. one at a time) and execution will stop after the first error. Unordered writes may execute in parallel and execution will not stop after the first error. Defaults to TRUE
j (bool) | Wait for journaling on the primary. This value is discouraged, use WriteConcern instead
fsync (bool) | Wait for fsync on the primary. This value is discouraged, use WriteConcern instead

Return Values

A new MongoWriteBatch of type batch_type.

See Also

  • MongoInsertBatch
  • MongoUpdateBatch
  • MongoDeleteBatch


Executes a batch of write operations

  • « MongoWriteBatch::__construct
  • MongoInsertBatch »
  • PHP Manual
  • MongoWriteBatch
  • Executes a batch of write operations

MongoWriteBatch::execute

(PECL mongo >= 1.5.0)

MongoWriteBatch::execute — Executes a batch of write operations

Description

final public MongoWriteBatch::execute ( array $write_options ) : array

Executes the batch of write operations.

Parameters

write_options

See MongoWriteBatch::__construct.

Return Values

Returns an array containing statistical information for the full batch. If the batch had to be split into multiple batches, the return value will aggregate the values from individual batches and return only the totals.

If the batch was empty, an array containing only the 'ok' field is returned (as TRUE) although nothing will be shipped over the wire (NOOP).

Array key | Value meaning | Returned for batch type
nInserted | Number of inserted documents | MongoWriteBatch::COMMAND_INSERT batch
nMatched | Number of documents matching the query criteria | MongoWriteBatch::COMMAND_UPDATE batch
nModified | Number of documents actually needed to be modied | MongoWriteBatch::COMMAND_UPDATE batch
nUpserted | Number of upserted documents | MongoWriteBatch::COMMAND_UPDATE batch
nRemoved | Number of documents removed | MongoWriteBatch::COMMAND_DELETE batch
ok | Command success indicator | All

Errors/Exceptions

A MongoWriteConcernException exception is thrown on failure.

Examples

Example #1 MongoWriteBatch::add() example

Batching up multiple insert operations

<?php
$mc = new MongoClient("localhost");
$collection = $mc->selectCollection("test", "test");

$docs = array();
$docs[] = array("my" => "demo");
$docs[] = array("is" => "working");
$docs[] = array("pretty" => "well");

$batch = new MongoInsertBatch($collection);
foreach($docs as $document) {
    $batch->add($document);
}
$retval = $batch->execute(array("w" => 1));
var_dump($retval);
?>

The above example will output:

array(2) {
  ["nInserted"]=>
  int(3)
  ["ok"]=>
  bool(true)
}

Example #2 MongoWriteBatch::add() example

Batching up multiple update operations

<?php
$mc = new MongoClient("localhost");
$collection = $mc->selectCollection("test", "test");

$item1 = array(
    "q" => array("my" => "demo"),
    "u" => array('$set' => array("try" => 1)),
    "multi"  => false, /* default value */
    "upsert" => false, /* default value */
);
$item2 = array(
    "q" => array("is" => "working"),
    "u" => array('$set' => array("try" => 2)),
    "multi" => true,
);
$item3 = array(
    "q" => array("created" => "new-document"),
    "u" => array('$set' => array("try" => 3)),
    "upsert" => true,
);

$batch = new MongoUpdateBatch($collection);
$batch->add($item1);
$batch->add($item2);
$batch->add($item3);
$retval = $batch->execute(array("w" => 1));
var_dump($retval);

?>

The above example will output:

array(4) {
  ["nMatched"]=>
  int(18)
  ["nModified"]=>
  int(2)
  ["nUpserted"]=>
  int(0)
  ["ok"]=>
  bool(true)
}

Example #3 MongoWriteBatch::add() example

Batching up multiple delete operations

<?php
$mc = new MongoClient("localhost");
$collection = $mc->selectCollection("test", "test");

$item1 = array(
    "q" => array("my" => "demo"),
    "limit" => 1,
);
$item2 = array(
    "q" => array("try" => 3),
    "limit" => 1,
);

$batch = new MongoDeleteBatch($collection);
$batch->add($item1);
$batch->add($item2);
$retval = $batch->execute(array("w" => 1));
var_dump($retval);
?>

The above example will output:

array(2) {
  ["nRemoved"]=>
  int(1)
  ["ok"]=>
  bool(true)
}


The MongoInsertBatch class

(PECL mongo >=1.5.0)

Introduction

Constructs a batch of INSERT operations. See MongoWriteBatch.

Class synopsis

MongoInsertBatch extends MongoWriteBatch {
/* Methods */
public __construct ( MongoCollection $collection [, array $write_options ] )
/* Inherited methods */
public MongoWriteBatch::add ( array $item ) : bool
final public MongoWriteBatch::execute ( array $write_options ) : array
}

Table of Contents

  • MongoInsertBatch::__construct — Description


Description

  • « MongoInsertBatch
  • MongoUpdateBatch »
  • PHP Manual
  • MongoInsertBatch
  • Description

MongoInsertBatch::__construct

(PECL mongo >= 1.5.0)

MongoInsertBatch::__construct — Description

Description

public MongoInsertBatch::__construct ( MongoCollection $collection [, array $write_options ] )

Constructs a batch of INSERT operations. See MongoWriteBatch.

Parameters

collection

The MongoCollection to execute the batch on. Its write concern will be copied and used as the default write concern if none is given as $write_options or during MongoWriteBatch::execute().

write_options

An array of Write Options.

key | value meaning
w (int|string) | Write concern value
wtimeout (int) | Maximum time to wait for replication
ordered | Determines if MongoDB must apply this batch in order. Ordered writes execute serially (i.e. one at a time) and execution will stop after the first error. Unordered writes may execute in parallel and execution will not stop after the first error. Defaults to TRUE
j (bool) | Wait for journaling on the primary. This value is discouraged, use WriteConcern instead
fsync (bool) | Wait for fsync on the primary. This value is discouraged, use WriteConcern instead

Return Values

A new MongoInsertBatch.


The MongoUpdateBatch class

(PECL mongo >=1.5.0)

Introduction

Constructs a batch of UPDATE operations. See MongoWriteBatch.

Class synopsis

MongoUpdateBatch extends MongoWriteBatch {
/* Methods */
public __construct ( MongoCollection $collection [, array $write_options ] )
/* Inherited methods */
public MongoWriteBatch::add ( array $item ) : bool
final public MongoWriteBatch::execute ( array $write_options ) : array
}

Table of Contents

  • MongoUpdateBatch::__construct — Description


Description

  • « MongoUpdateBatch
  • MongoDeleteBatch »
  • PHP Manual
  • MongoUpdateBatch
  • Description

MongoUpdateBatch::__construct

(PECL mongo >= 1.5.0)

MongoUpdateBatch::__construct — Description

Description

public MongoUpdateBatch::__construct ( MongoCollection $collection [, array $write_options ] )

Constructs a batch of UPDATE operations. See MongoWriteBatch.

Parameters

collection

The MongoCollection to execute the batch on. Its write concern will be copied and used as the default write concern if none is given as $write_options or during MongoWriteBatch::execute().

write_options

An array of Write Options.

key | value meaning
w (int|string) | Write concern value
wtimeout (int) | Maximum time to wait for replication
ordered | Determines if MongoDB must apply this batch in order. Ordered writes execute serially (i.e. one at a time) and execution will stop after the first error. Unordered writes may execute in parallel and execution will not stop after the first error. Defaults to TRUE
j (bool) | Wait for journaling on the primary. This value is discouraged, use WriteConcern instead
fsync (bool) | Wait for fsync on the primary. This value is discouraged, use WriteConcern instead

Return Values

A new MongoUpdateBatch.


The MongoDeleteBatch class

(PECL mongo >=1.5.0)

Introduction

Constructs a batch of DELETE operations. See MongoWriteBatch.

Class synopsis

MongoDeleteBatch extends MongoWriteBatch {
/* Methods */
public __construct ( MongoCollection $collection [, array $write_options ] )
/* Inherited methods */
public MongoWriteBatch::add ( array $item ) : bool
final public MongoWriteBatch::execute ( array $write_options ) : array
}

Table of Contents

  • MongoDeleteBatch::__construct — Description


Description

  • « MongoDeleteBatch
  • Miscellaneous »
  • PHP Manual
  • MongoDeleteBatch
  • Description

MongoDeleteBatch::__construct

(PECL mongo >= 1.5.0)

MongoDeleteBatch::__construct — Description

Description

public MongoDeleteBatch::__construct ( MongoCollection $collection [, array $write_options ] )

Constructs a batch of DELETE operations. See MongoWriteBatch.

Parameters

collection

The MongoCollection to execute the batch on. Its write concern will be copied and used as the default write concern if none is given as $write_options or during MongoWriteBatch::execute().

write_options

An array of Write Options.

key | value meaning
w (int|string) | Write concern value
wtimeout (int) | Maximum time to wait for replication
ordered | Determines if MongoDB must apply this batch in order. Ordered writes execute serially (i.e. one at a time) and execution will stop after the first error. Unordered writes may execute in parallel and execution will not stop after the first error. Defaults to TRUE
j (bool) | Wait for journaling on the primary. This value is discouraged, use WriteConcern instead
fsync (bool) | Wait for fsync on the primary. This value is discouraged, use WriteConcern instead

Return Values

A new MongoDeleteBatch.


  • « MongoDeleteBatch::__construct
  • MongoLog »
  • PHP Manual
  • Mongo
  • Miscellaneous

Miscellaneous

Table of Contents

  • MongoLog
  • MongoPool
  • Mongo


The MongoLog class

(PECL mongo >=1.2.3)

Introduction

Logging can be used to get detailed information about what the driver is doing. Logging is disabled by default, but this class allows you to activate specific levels of logging for various parts of the driver. Some examples:

<?php

// print every log message possible
MongoLog::setLevel(MongoLog::ALL); // all log levels
MongoLog::setModule(MongoLog::ALL); // all parts of the driver

// print significant events about replica set failover
MongoLog::setLevel(MongoLog::INFO);
MongoLog::setModule(MongoLog::RS);

// print info- and diagnostic-level events for replica sets and connections
MongoLog::setLevel(MongoLog::INFO|MongoLog::FINE);
MongoLog::setModule(MongoLog::RS|MongoLog::CON);

?>

Note:

By default, MongoLog emits all log messages as PHP notices. Depending on the SAPI you use, messages may be sent to stderr (for CLI) or the web server's error log. If, after configuring MongoLog, log messages are not appearing as expected, ensure that the E_NOTICE bit is included in error_reporting and that display_errors is on.

Class synopsis

MongoLog {
/* Constants */
const int NONE = 0 ;
const int ALL = 31 ;
level constants {
const int WARNING = 1 ;
const int INFO = 2 ;
const int FINE = 4 ;
module constants {
const int RS = 1 ;
const int POOL = 1 ;
const int CON = 2 ;
const int IO = 4 ;
const int SERVER = 8 ;
const int PARSE = 16 ;
/* Fields */
private static int $callback ;
private static int $level ;
private static int $module ;
/* Methods */
public static getCallback ( void ) : callable
public static getLevel ( void ) : int
public static getModule ( void ) : int
public static setCallback ( callable $log_function ) : void
public static setLevel ( int $level ) : void
public static setModule ( int $module ) : void
}

Predefined Constants

MongoLog Constants

These constants can be used by both MongoLog::setLevel() and MongoLog::setModule().

MongoLog::NONE
Log nothing.
MongoLog::ALL
Log everything.

MongoLog Level Constants

These constants can be used by MongoLog::setLevel().

MongoLog::WARNING
Log events that are somewhat exceptional, but not quite worthy of an actual exception (e.g. recoverable connection errors).
MongoLog::INFO
Log events that may be of interest to administrators, but are not particularly noteworthy (e.g. option parsing, authentication steps).
MongoLog::FINE
Log most events that the driver performs (e.g. server selection, socket communication). Depending on the module being logged, this can be extremely noisy and is primarily useful for debugging.

MongoLog Module Constants

These constants can be used by MongoLog::setModule().

MongoLog::CON
Log connection activity. Creating new connections, authentication, pinging, timeouts, etc.
MongoLog::IO
Log traffic to/from the database. Unless your program is trivial, this will create an enormous number of log messages.
MongoLog::PARSE
Log parsing of the connection string and options when constructing MongoClient.
MongoLog::POOL
Previously used to log connection pool activity. This option is now a deprecated alias of MongoLog::RS.
MongoLog::RS
Log replica set activity. Failovers, read preference selection, etc.
MongoLog::SERVER
Previously used to log server status changes. This option is deprecated in favor of MongoLog::RS.

Changelog

Version | Description
1.3.0 | Added MongoLog::CON and deprecated MongoLog::POOL and MongoLog::SERVER.

Table of Contents

  • MongoLog::getCallback — Gets the previously set callback function
  • MongoLog::getLevel — Gets the level(s) currently being logged
  • MongoLog::getModule — Gets the module(s) currently being logged
  • MongoLog::setCallback — Sets a callback function to be invoked for events
  • MongoLog::setLevel — Sets the level(s) to be logged
  • MongoLog::setModule — Sets the module(s) to be logged


Gets the previously set callback function

  • « MongoLog
  • MongoLog::getLevel »
  • PHP Manual
  • MongoLog
  • Gets the previously set callback function

MongoLog::getCallback

(PECL mongo >= 1.3.0)

MongoLog::getCallback — Gets the previously set callback function

Description

public static MongoLog::getCallback ( void ) : callable

Retrieves the callback function.

Parameters

This function has no parameters.

Return Values

Returns the callback function, or FALSE if not set yet.

Notes

Caution

This function is only available with PHP 5.3.0 and later.


Gets the level(s) currently being logged

  • « MongoLog::getCallback
  • MongoLog::getModule »
  • PHP Manual
  • MongoLog
  • Gets the level(s) currently being logged

MongoLog::getLevel

(PECL mongo >= 1.2.3)

MongoLog::getLevel — Gets the level(s) currently being logged

Description

public static MongoLog::getLevel ( void ) : int

This function can be used to see which log levels are currently enabled. The returned integer may be compared with the MongoLog level constants using bitwise operators to check for specific log levels.

<?php

if (MongoLog::getLevel() & MongoLog::FINE) {
    echo "lots of logs\n";
}

if (MongoLog::getLevel() ^ MongoLog::NONE) {
    echo "logging, at least a little\n";
}

if (MongoLog::getLevel() == MongoLog::ALL) {
    echo "logging at the highest levels\n";
}

?>

Parameters

This function has no parameters.

Return Values

Returns the level(s) currently being logged.


Gets the module(s) currently being logged

  • « MongoLog::getLevel
  • MongoLog::setCallback »
  • PHP Manual
  • MongoLog
  • Gets the module(s) currently being logged

MongoLog::getModule

(PECL mongo >= 1.2.3)

MongoLog::getModule — Gets the module(s) currently being logged

Description

public static MongoLog::getModule ( void ) : int

This function can be used to see which driver modules are currently being logged. The returned integer may be compared with the MongoLog module constants using bitwise operators to check if specific modules are being logged.

<?php

if (MongoLog::getModule() & MongoLog::RS) {
    echo "logging replica sets\n";
}

if (MongoLog::getModule() ^ MongoLog::NONE) {
    echo "logging something\n";
}

if ((MongoLog::getModule() & MongoLog::IO) == 0) {
    echo "not logging io\n";
}

?>

Parameters

This function has no parameters.

Return Values

Returns the module(s) currently being logged.


Sets a callback function to be invoked for events

  • « MongoLog::getModule
  • MongoLog::setLevel »
  • PHP Manual
  • MongoLog
  • Sets a callback function to be invoked for events

MongoLog::setCallback

(PECL mongo >= 1.3.0)

MongoLog::setCallback — Sets a callback function to be invoked for events

Description

public static MongoLog::setCallback ( callable $log_function ) : void

This function will set a callback function to be invoked for events in lieu of emitting of PHP notice.

Parameters

log_function

The callback function to be invoked on events. It should have the following prototype:

log_function ( int $module , int $level , string $message )
module
One of the MongoLog module constants.
level
One of the MongoLog level constants.
message
The log message itself.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 MongoLog::setCallback() example

<?php

function module2string($module)
{
    switch ($module) {
        case MongoLog::RS: return "REPLSET";
        case MongoLog::CON: return "CON";
        case MongoLog::IO: return "IO";
        case MongoLog::SERVER: return "SERVER";
        case MongoLog::PARSE: return "PARSE";
        default: return "UNKNOWN";
    }
}

function level2string($level)
{
    switch ($level) {
        case MongoLog::WARNING: return "WARN";
        case MongoLog::INFO: return "INFO";
        case MongoLog::FINE: return "FINE";
        default: return "UNKNOWN";
    }
}

function callback($module, $level, $message)
{
    echo date("Y-m-d H:i:s - ");
    printf("%s (%s): %s\n", module2string($module), level2string($level), $message);
}

MongoLog::setLevel(MongoLog::ALL);
MongoLog::setModule(MongoLog::ALL);

// We specify the function name here, but any callable (e.g. anonymous function) will work
MongoLog::setCallback("callback");

new MongoClient();
?>

The above example will output something similar to:

2013-07-09 09:41:42 - PARSE (INFO): Parsing localhost:27017
2013-07-09 09:41:42 - PARSE (INFO): - Found node: localhost:27017
2013-07-09 09:41:42 - PARSE (INFO): - Connection type: STANDALONE
2013-07-09 09:41:42 - CON (INFO): mongo_get_read_write_connection: finding a STANDALONE connection
2013-07-09 09:41:42 - CON (INFO): connection_create: creating new connection for localhost:27017
2013-07-09 09:41:42 - CON (INFO): stream_connect: Not establishing SSL for localhost:27017
2013-07-09 09:41:42 - CON (INFO): get_server_flags: start
2013-07-09 09:41:42 - CON (FINE): send_packet: read from header: 36
2013-07-09 09:41:42 - CON (FINE): send_packet: data_size: 95
2013-07-09 09:41:42 - CON (FINE): get_server_flags: setting maxBsonObjectSize to 16777216
2013-07-09 09:41:42 - CON (FINE): get_server_flags: setting maxMessageSizeBytes to 48000000
2013-07-09 09:41:42 - CON (INFO): is_ping: pinging localhost:27017;-;.;1543
2013-07-09 09:41:42 - CON (FINE): send_packet: read from header: 36
2013-07-09 09:41:42 - CON (FINE): send_packet: data_size: 17
2013-07-09 09:41:42 - CON (INFO): is_ping: last pinged at 1373359302; time: 0ms
2013-07-09 09:41:42 - REPLSET (FINE): finding candidate servers
2013-07-09 09:41:42 - REPLSET (FINE): - all servers
2013-07-09 09:41:42 - REPLSET (FINE): filter_connections: adding connections:
2013-07-09 09:41:42 - REPLSET (FINE): - connection: type: STANDALONE, socket: 42, ping: 0, hash: localhost:27017;-;.;1543
2013-07-09 09:41:42 - REPLSET (FINE): filter_connections: done
2013-07-09 09:41:42 - REPLSET (FINE): limiting by seeded/discovered servers
2013-07-09 09:41:42 - REPLSET (FINE): - connection: type: STANDALONE, socket: 42, ping: 0, hash: localhost:27017;-;.;1543
2013-07-09 09:41:42 - REPLSET (FINE): limiting by seeded/discovered servers: done
2013-07-09 09:41:42 - REPLSET (FINE): limiting by credentials
2013-07-09 09:41:42 - REPLSET (FINE): - connection: type: STANDALONE, socket: 42, ping: 0, hash: localhost:27017;-;.;1543
2013-07-09 09:41:42 - REPLSET (FINE): limiting by credentials: done
2013-07-09 09:41:42 - REPLSET (FINE): sorting servers by priority and ping time
2013-07-09 09:41:42 - REPLSET (FINE): - connection: type: STANDALONE, socket: 42, ping: 0, hash: localhost:27017;-;.;1543
2013-07-09 09:41:42 - REPLSET (FINE): sorting servers: done
2013-07-09 09:41:42 - REPLSET (FINE): selecting near servers
2013-07-09 09:41:42 - REPLSET (FINE): selecting near servers: nearest is 0ms
2013-07-09 09:41:42 - REPLSET (FINE): - connection: type: STANDALONE, socket: 42, ping: 0, hash: localhost:27017;-;.;1543
2013-07-09 09:41:42 - REPLSET (FINE): selecting near server: done
2013-07-09 09:41:42 - REPLSET (INFO): pick server: random element 0
2013-07-09 09:41:42 - REPLSET (INFO): - connection: type: STANDALONE, socket: 42, ping: 0, hash: localhost:27017;-;.;1543

Notes

Caution

This function is only available with PHP 5.3.0 and later.


Sets the level(s) to be logged

  • « MongoLog::setCallback
  • MongoLog::setModule »
  • PHP Manual
  • MongoLog
  • Sets the level(s) to be logged

MongoLog::setLevel

(PECL mongo >= 1.2.3)

MongoLog::setLevel — Sets the level(s) to be logged

Description

public static MongoLog::setLevel ( int $level ) : void

This function can be used to control logging verbosity and the types of activities that should be logged. The MongoLog level constants may be used with bitwise operators to specify multiple levels.

<?php

// first, specify a logging module
MongoLog::setModule(MongoLog::CON);

// log messages for every level
MongoLog::setLevel(MongoLog::ALL);

// log warning and info messages only
MongoLog::setLevel(MongoLog::WARNING|MongoLog::INFO);

// log everything except fine activity
MongoLog::setLevel(MongoLog::ALL & (~MongoLog::FINE));

?>

Note that you must also call MongoLog::setModule() to specify which modules(s) of the driver should log.

Parameters

level

The level(s) you would like to log.


Sets the module(s) to be logged

  • « MongoLog::setLevel
  • MongoPool »
  • PHP Manual
  • MongoLog
  • Sets the module(s) to be logged

MongoLog::setModule

(PECL mongo >= 1.2.3)

MongoLog::setModule — Sets the module(s) to be logged

Description

public static MongoLog::setModule ( int $module ) : void

This function can be used to set which driver modules should be logged. The MongoLog module constants may be used with bitwise operators to specify multiple modules.

<?php

// first, specify a logging level
MongoLog::setLevel(MongoLog::ALL);

// log replica set activity
MongoLog::setModule(MongoLog::RS);

// log replica sets and connection activity
MongoLog::setModule(MongoLog::RS|MongoLog::CON);

// log everything except IO activity
MongoLog::setModule(MongoLog::ALL & (~MongoLog::IO));

?>

Note that you must also call MongoLog::setLevel() to enable logging.

Parameters

module

The module(s) you would like to log.


The MongoPool class

(PECL mongo >= 1.2.3)

Introduction

Warning

The current (1.3.0+) releases of the driver no longer implements pooling. This class and its methods are therefore deprecated and should not be used.

Class synopsis

MongoPool {
/* Methods */
public static getSize ( void ) : int
public info ( void ) : array
public static setSize ( int $size ) : bool
}

Changelog

Version | Description
1.3.0 | This functionality has been removed and no longer does anything other than emit deprecation warnings. This class is only kept around for backwards compatibility and will be removed in the near future.
1.2.11 | Emits E_DEPRECATED when used.

Table of Contents

  • MongoPool::getSize — Get pool size for connection pools
  • MongoPool::info — Returns information about all connection pools
  • MongoPool::setSize — Set the size for future connection pools


Get pool size for connection pools

  • « MongoPool
  • MongoPool::info »
  • PHP Manual
  • MongoPool
  • Get pool size for connection pools

MongoPool::getSize

(PECL mongo >= 1.2.3)

MongoPool::getSize — Get pool size for connection pools

Description

public static MongoPool::getSize ( void ) : int

Parameters

This function has no parameters.

Return Values

Returns the current pool size.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.

Examples

Example #1 Changing pool size

This returns the default pool size, sets a new pool size, then prints the new pool size and the pool debugging information. Note that changing the pool size only affects new connection pools, it does not change old ones.

<?php

$connection = new Mongo("host1");

// pool size is -1
echo "pool size is: ".MongoPool::getSize()."\n";

echo "setting pool size to 200\n";

MongoPool::setSize(200);

// pool size is 200
echo "pool size is: ".MongoPool::getSize()."\n";

$conn2 = new Mongo("host2");

// remaining for host1 is -2
// remaining for host2 is 199
var_dump(Mongo::poolDebug());

?>

See Also

  • MongoPool::setSize() - Set the size for future connection pools
  • MongoPool::info() - Returns information about all connection pools
  • The connection documentation.


Returns information about all connection pools

  • « MongoPool::getSize
  • MongoPool::setSize »
  • PHP Manual
  • MongoPool
  • Returns information about all connection pools

MongoPool::info

(PECL mongo >= 1.2.3)

MongoPool::info — Returns information about all connection pools

Description

public MongoPool::info ( void ) : array

Returns an array of information about all connection pools.

Parameters

This function has no parameters.

Return Values

Each connection pool has an identifier, which starts with the host. For each pool, this function shows the following fields:

in use

The number of connections currently being used by Mongo instances.

in pool

The number of connections currently in the pool (not being used).

remaining

The number of connections that could be created by this pool. For example, suppose a pool had 5 connections remaining and 3 connections in the pool. We could create 8 new instances of MongoClient before we exhausted this pool (assuming no instances of MongoClient went out of scope, returning their connections to the pool).

A negative number means that this pool will spawn unlimited connections.

Before a pool is created, you can change the max number of connections by calling Mongo::setPoolSize(). Once a pool is showing up in the output of this function, its size cannot be changed.

total

The total number of connections allowed for this pool. This should be greater than or equal to "in use" + "in pool" (or -1).

timeout

The socket timeout for connections in this pool. This is how long connections in this pool will attempt to connect to a server before giving up.

waiting

If you have capped the pool size, workers requesting connections from the pool may block until other workers return their connections. This field shows how many milliseconds workers have blocked for connections to be released. If this number keeps increasing, you may want to use MongoPool::setSize() to add more connections to your pool.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.


Set the size for future connection pools

  • « MongoPool::info
  • Mongo »
  • PHP Manual
  • MongoPool
  • Set the size for future connection pools

MongoPool::setSize

(PECL mongo >= 1.2.3)

MongoPool::setSize — Set the size for future connection pools

Description

public static MongoPool::setSize ( int $size ) : bool

Sets the max number of connections new pools will be able to create.

Parameters

size

The max number of connections future pools will be able to create. Negative numbers mean that the pool will spawn an infinite number of connections.

Return Values

Returns the former value of pool size.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.

Examples

Example #1 Mongo::setPoolSize() example

If you set the pool size to n and then create n connections, attempting to create an n+1st connection will throw a MongoConnectionException.

<?php

// only allow one connection to a server
MongoPool::setSize(1);

// creates one connection to localhost:27017
$m1 = new Mongo();

// attempt to create a second connection to localhost:27017
// only one connection is allowed, so this will throw an exception
$m2 = new Mongo();

?>

The above example will output something similar to:

Fatal error: Uncaught exception 'MongoConnectionException' with message 'no more connections in pool' in /path/to/php/script.php:10
Stack trace:
#0 /path/to/php/script.php(10): Mongo->__construct()
#1 {main}
  thrown in /path/to/php/script.php on line 10

See Also

  • MongoPool::getSize() - Get pool size for connection pools
  • MongoPool::info() - Returns information about all connection pools
  • The connection documentation.


The Mongo class [deprecated]

(PECL mongo >=0.9.0)

Introduction

A connection between PHP and MongoDB.

This class extends MongoClient and provides access to several deprecated methods.

For backwards compatibility, it also defaults the "w" option of its constructor argument to 0, which does not require write operations to be acknowledged by the server. See MongoClient::__construct() for more information.

Warning

This class has been DEPRECATED as of version 1.3.0. Relying on this feature is highly discouraged. Please use MongoClient instead.

Class synopsis

Mongo extends MongoClient {
/* Methods */
protected connectUtil ( void ) : bool
public static getPoolSize ( void ) : int
public getSlave ( void ) : string
public getSlaveOkay ( void ) : bool
public poolDebug ( void ) : array
public static setPoolSize ( int $size ) : bool
public setSlaveOkay ([ bool $ok = TRUE ] ) : bool
public switchSlave ( void ) : string
/* Inherited methods */
public MongoClient::close ([ boolean|string $connection ] ) : bool
public MongoClient::connect ( void ) : bool
public MongoClient::dropDB ( mixed $db ) : array
public MongoClient::__get ( string $dbname ) : MongoDB
public static MongoClient::getConnections ( void ) : array
public MongoClient::getHosts ( void ) : array
public MongoClient::getReadPreference ( void ) : array
public MongoClient::getWriteConcern ( void ) : array
public MongoClient::killCursor ( string $server_hash , int|MongoInt64 $id ) : bool
public MongoClient::listDBs ( void ) : array
public MongoClient::selectCollection ( string $db , string $collection ) : MongoCollection
public MongoClient::selectDB ( string $name ) : MongoDB
public MongoClient::setReadPreference ( string $read_preference [, array $tags ] ) : bool
public MongoClient::setWriteConcern ( mixed $w [, int $wtimeout ] ) : bool
public MongoClient::__toString ( void ) : string
}

Table of Contents

  • Mongo::connectUtil — Connects with a database server
  • Mongo::__construct — The __construct purpose
  • Mongo::getPoolSize — Get pool size for connection pools
  • Mongo::getSlave — Returns the address being used by this for slaveOkay reads
  • Mongo::getSlaveOkay — Get slaveOkay setting for this connection
  • Mongo::poolDebug — Returns information about all connection pools
  • Mongo::setPoolSize — Set the size for future connection pools
  • Mongo::setSlaveOkay — Change slaveOkay setting for this connection
  • Mongo::switchSlave — Choose a new secondary for slaveOkay reads


Connects with a database server

  • « Mongo
  • Mongo::__construct »
  • PHP Manual
  • Mongo
  • Connects with a database server

Mongo::connectUtil

(PECL mongo >=0.9.0)

Mongo::connectUtil — Connects with a database server

Description

protected Mongo::connectUtil ( void ) : bool
Warning

This is an internal function that you should never call yourself.

Parameters

This function has no parameters.

Return Values

If the connection was successful.

Errors/Exceptions

Throws MongoConnectionException if it fails to connect to the databases.


The __construct purpose

  • « Mongo::connectUtil
  • Mongo::getPoolSize »
  • PHP Manual
  • Mongo
  • The __construct purpose

Mongo::__construct

(PECL mongo >=0.9.0)

Mongo::__construct — The __construct purpose

Description

public Mongo::__construct ([ string $server [, array $options ]] )

This method overwrites the MongoClient constructor and turns off acknowledged writes.

Please see MongoClient::__construct() for description of the parameters.

Return Values

Warning

Instanciating this class will emit E_DEPRECATED warning, and turn off acknowledged writes.

Please use the MongoClient instead.


Get pool size for connection pools

  • « Mongo::__construct
  • Mongo::getSlave »
  • PHP Manual
  • Mongo
  • Get pool size for connection pools

Mongo::getPoolSize

(PECL mongo >=1.2.0)

Mongo::getPoolSize — Get pool size for connection pools

Description

public static Mongo::getPoolSize ( void ) : int
Warning

This feature has been DEPRECATED as of version 1.2.3. Relying on this feature is highly discouraged. Please use MongoPool::getSize() instead.

Parameters

This function has no parameters.

Return Values

Returns the current pool size.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.

Examples

Example #1 Changing pool size

This returns the default pool size, sets a new pool size, then prints the new pool size and the pool debugging information. Note that changing the pool size only affects new connection pools, it does not change old ones.

<?php

$connection = new Mongo("host1");

// pool size is -1
echo "pool size is: ".Mongo::getPoolSize()."\n";

echo "setting pool size to 200\n";

Mongo::setPoolSize(200);

// pool size is 200
echo "pool size is: ".Mongo::getPoolSize()."\n";

$conn2 = new Mongo("host2");

// remaining for host1 is -2
// remaining for host2 is 199
var_dump(Mongo::poolDebug());

?>

See Also

  • Mongo::setPoolSize() - Set the size for future connection pools
  • Mongo::poolDebug() - Returns information about all connection pools
  • The connection documentation.


Returns the address being used by this for slaveOkay reads

  • « Mongo::getPoolSize
  • Mongo::getSlaveOkay »
  • PHP Manual
  • Mongo
  • Returns the address being used by this for slaveOkay reads

Mongo::getSlave

(PECL mongo >=1.1.0)

Mongo::getSlave — Returns the address being used by this for slaveOkay reads

Description

public Mongo::getSlave ( void ) : string

This finds the address of the secondary currently being used for reads. It is a read-only method: it does not change anything about the internal state of the object.

When you create a connection to the database, the driver will not immediately decide on a secondary to use. Thus, after you connect, this function will return NULL even if there are secondaries available. When you first do a query with slaveOkay set, at that point the driver will choose a secondary for this connection. At that point, this function will return the chosen secondary.

See the query section of this manual for information on distributing reads to secondaries.

Parameters

This function has no parameters.

Return Values

The address of the secondary this connection is using for reads.

This returns NULL if this is not connected to a replica set or not yet initialized.

Errors/Exceptions

Issues E_DEPRECATED warning

The returned results aren't really useful as the secondary selection process is done on each query and database command execution.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.

See Also

  • MongoCursor::info() - Gets information about the cursor's creation and iteration


Get slaveOkay setting for this connection

  • « Mongo::getSlave
  • Mongo::poolDebug »
  • PHP Manual
  • Mongo
  • Get slaveOkay setting for this connection

Mongo::getSlaveOkay

(PECL mongo >=1.1.0)

Mongo::getSlaveOkay — Get slaveOkay setting for this connection

Description

public Mongo::getSlaveOkay ( void ) : bool

See the query section of this manual for information on distributing reads to secondaries.

Parameters

This function has no parameters.

Return Values

Returns the value of slaveOkay for this instance.

Errors/Exceptions

Issues E_DEPRECATED warning

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.

See Also

  • Read Preferences
  • MongoClient::getReadPreference() - Get the read preference for this connection


Returns information about all connection pools

  • « Mongo::getSlaveOkay
  • Mongo::setPoolSize »
  • PHP Manual
  • Mongo
  • Returns information about all connection pools

Mongo::poolDebug

(PECL mongo >=1.2.0)

Mongo::poolDebug — Returns information about all connection pools

Description

public Mongo::poolDebug ( void ) : array
Warning

This feature has been DEPRECATED as of version 1.2.3. Relying on this feature is highly discouraged. Please use MongoPool::info() instead.

Returns an array of information about all connection pools.

Parameters

This function has no parameters.

Return Values

Each connection pool has an identifier, which starts with the host. For each pool, this function shows the following fields:

in use

The number of connections currently being used by MongoClient instances.

in pool

The number of connections currently in the pool (not being used).

remaining

The number of connections that could be created by this pool. For example, suppose a pool had 5 connections remaining and 3 connections in the pool. We could create 8 new instances of MongoClient before we exhausted this pool (assuming no instances of MongoClient went out of scope, returning their connections to the pool).

A negative number means that this pool will spawn unlimited connections.

Before a pool is created, you can change the max number of connections by calling Mongo::setPoolSize(). Once a pool is showing up in the output of this function, its size cannot be changed.

timeout

The socket timeout for connections in this pool. This is how long connections in this pool will attempt to connect to a server before giving up.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.


Set the size for future connection pools

  • « Mongo::poolDebug
  • Mongo::setSlaveOkay »
  • PHP Manual
  • Mongo
  • Set the size for future connection pools

Mongo::setPoolSize

(PECL mongo >=1.2.0)

Mongo::setPoolSize — Set the size for future connection pools

Description

public static Mongo::setPoolSize ( int $size ) : bool
Warning

This method has been DEPRECATED as of version 1.2.3. Relying on this feature is highly discouraged. Please use MongoPool::setSize() instead.

Sets the max number of connections new pools will be able to create.

Parameters

size

The max number of connections future pools will be able to create. Negative numbers mean that the pool will spawn an infinite number of connections.

Return Values

Returns the former value of pool size.

Examples

Example #1 Mongo::setPoolSize() example

If you set the pool size to n and then create n connections, attempting to create an n+1st connection will throw a MongoConnectionException.

<?php

// only allow one connection to a server
Mongo::setPoolSize(1);

// creates one connection to localhost:27017
$m1 = new Mongo();

// attempt to create a second connection to localhost:27017
// only one connection is allowed, so this will throw an exception
$m2 = new Mongo();

?>

The above example will output something similar to:

Fatal error: Uncaught exception 'MongoConnectionException' with message 'no more connections in pool' in /path/to/php/script.php:10
Stack trace:
#0 /path/to/php/script.php(10): Mongo->__construct()
#1 {main}
  thrown in /path/to/php/script.php on line 10

See Also

  • Mongo::getPoolSize() - Get pool size for connection pools
  • Mongo::poolDebug() - Returns information about all connection pools
  • The connection documentation.


Change slaveOkay setting for this connection

  • « Mongo::setPoolSize
  • Mongo::switchSlave »
  • PHP Manual
  • Mongo
  • Change slaveOkay setting for this connection

Mongo::setSlaveOkay

(PECL mongo >=1.1.0)

Mongo::setSlaveOkay — Change slaveOkay setting for this connection

Description

public Mongo::setSlaveOkay ([ bool $ok = TRUE ] ) : bool

See the query section of this manual for information on distributing reads to secondaries.

Parameters

ok

If reads should be sent to secondary members of a replica set for all possible queries using this MongoClient instance.

Return Values

Returns the former value of slaveOkay for this instance.

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.

See Also

  • Read Preferences
  • MongoClient::setReadPreference() - Set the read preference for this connection


Choose a new secondary for slaveOkay reads

  • « Mongo::setSlaveOkay
  • Mongo Functions »
  • PHP Manual
  • Mongo
  • Choose a new secondary for slaveOkay reads

Mongo::switchSlave

(PECL mongo >=1.1.0)

Mongo::switchSlave — Choose a new secondary for slaveOkay reads

Description

public Mongo::switchSlave ( void ) : string

This choses a random secondary for a connection to read from. It is called automatically by the driver and should not need to be used. It calls MongoClient::getHosts() (to refresh the status of hosts) and Mongo::getSlave() (to get the return value).

See the query section of this manual for information on distributing reads to secondaries.

Parameters

This function has no parameters.

Return Values

The address of the secondary this connection is using for reads. This may be the same as the previous address as addresses are randomly chosen. It may return only one address if only one secondary (or only the primary) is available.

For example, if we had a three member replica set with a primary, secondary, and arbiter this method would always return the address of the secondary. If the secondary became unavailable, this method would always return the address of the primary. If the primary also became unavailable, this method would throw an exception, as an arbiter cannot handle reads.

Errors/Exceptions

Throws a MongoException (error code 15) if it is called on a non-replica-set connection. It will also throw MongoExceptions if it cannot find anyone (primary or secondary) to read from (error code 16).

Changelog

Version | Description
1.2.11 | Emits E_DEPRECATED when used.

See Also

  • Read Preferences


Mongo Functions

Table of Contents

  • bson_decode — Deserializes a BSON object into a PHP array
  • bson_encode — Serializes a PHP variable into a BSON string


Deserializes a BSON object into a PHP array

  • « Mongo Functions
  • bson_encode »
  • PHP Manual
  • Mongo Functions
  • Deserializes a BSON object into a PHP array

bson_decode

(PECL mongo >=1.0.1)

bson_decode — Deserializes a BSON object into a PHP array

Description

bson_decode ( string $bson ) : array

This function is very beta and entirely useless for 99% of users. It is only useful if you're doing something weird, such as writing your own driver on top of the PHP driver.

Parameters

bson

The BSON to be deserialized.

Return Values

Returns the deserialized BSON object.


Serializes a PHP variable into a BSON string

  • « bson_decode
  • Exceptions »
  • PHP Manual
  • Mongo Functions
  • Serializes a PHP variable into a BSON string

bson_encode

(PECL mongo >=1.0.1)

bson_encode — Serializes a PHP variable into a BSON string

Description

bson_encode ( mixed $anything ) : string

This function is very beta and entirely useless for 99% of users. It is only useful if you're doing something weird, such as writing your own driver on top of the PHP driver.

Parameters

anything

The variable to be serialized.

Return Values

Returns the serialized string.


Exceptions

Table of Contents

  • MongoException
  • MongoResultException
  • MongoCursorException
  • MongoCursorTimeoutException
  • MongoConnectionException
  • MongoGridFSException
  • MongoDuplicateKeyException
  • MongoProtocolException
  • MongoExecutionTimeoutException
  • MongoWriteConcernException

VMWare Oddities

If you are running VMWare on Windows and are using CIFS, pausing the VM will cause CIFS to go out of sync and cause weird errors on un-pausing it ("The Mongo object has not been correctly initialized by its constructor"). Permanently mounting the Windows shares will fix this and you'll be able to pause and unpause at will.

To permanently mount the Windows shares, run:

$ sudo update-rc.d -f umountnfs.sh remove
$ sudo update-rc.d umountnfs.sh stop 15 0 6 .

See » the Ubuntu docs for the most up-to-date instructions.


The MongoException class

(PECL mongo >= 1.0.0)

Introduction

Default Mongo exception.

This covers a bunch of different error conditions that may eventually be moved to more specific exceptions, but will always extend MongoException.

  • The MongoSomething object has not been correctly initialized by its constructor

    Code: 0

    Probably your Mongo object is not connected to a database server.

  • zero-length keys are not allowed, did you use $ with double quotes?

    Code: 1

    You tried to save "" as a key. You generally should not do this. "" can mess up subobject access and is used by MongoDB internally. However, if you really want, you can set mongo.allow_empty_keys to true in your php.ini file to override this sanity check. If you override this, it is highly recommended that you set error checking to strict to avoid string interpolation errors.

  • '.' not allowed in key: <key>

    Code: 2

    You attempted to write a key with '.' in it, which is prohibited.

  • insert too large: <size>, max: <max>

    Code: 3

    You're attempting to send too much data to the database at once: the database will only accept inserts up to a certain size (currently 16 MB).

  • no elements in doc

    Code: 4

    You're attempting to save a document with no fields.

  • size of BSON doc is <size> bytes, max <max>MB

    Code: 5

    You're attempting to save a document that is larger than MongoDB can save.

  • no documents given

    Code: 6

    You're attempting to batch insert an empty array of documents.

  • MongoCollection::group takes an array, object, or MongoCode key

    Code: 7

    Wrong type parameter send to MongoCollection::group().

  • field names must be strings

    Code: 8

    You should format field selectors as array("field1" => 1, "field2" => 1, ..., "fieldN" => 1).

  • invalid regex

    Code: 9

    The regex passed to MongoRegex is not of the correct form.

  • MongoDBRef::get: $ref field must be a string

    Code: 10

  • MongoDBRef::get: $db field must be a string

    Code: 11

  • non-utf8 string: <str>

    Code: 12

    This error occurs if you attempt to send a non-utf8 string to the database. All strings going into the database should be UTF8. See php.ini options for the transition option of quieting this exception.

  • mutex error: <err>

    Code: 13

    The driver uses mutexes for synchronizing requests and responses in multithreaded environments. This is a fairly serious error and may not have a stack trace. It's unusual and should be reported to maintainers with any system information and steps to reproduce that you can provide.

  • index name too long: <len>, max <max> characters

    Code: 14

    Indexes with names longer than 128 characters cannot be created. If you get this error, you should use MongoCollection::ensureIndex()'s "name" option to create a shorter name for your index.

Class synopsis

MongoException extends Exception {
}


The MongoResultException class

(PECL mongo >=1.3.0)

Introduction

The MongoResultException is thrown by several command helpers (such as MongoCollection::findAndModify()) in the event of failure. The original result document is available through MongoResultException::getDocument().

Class synopsis

MongoResultException extends MongoException {
/* Properties */
public $document ;
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Methods */
public getDocument ( void ) : array
}

Properties

document

The raw result document as an array.

Table of Contents

  • MongoResultException::getDocument — Retrieve the full result document


Retrieve the full result document

  • « MongoResultException
  • MongoCursorException »
  • PHP Manual
  • MongoResultException
  • Retrieve the full result document

MongoResultException::getDocument

(PECL mongo >=1.3.0)

MongoResultException::getDocument — Retrieve the full result document

Description

public MongoResultException::getDocument ( void ) : array

Retrieves the full error result document.

Parameters

This function has no parameters.

Return Values

The full result document as an array, including partial data if available and additional keys.

Examples

Example #1 MongoResultException::getDocument() example

<?php
$mc = new MongoClient("localhost");
$c = $mc->selectCollection("test", "test");

$c->insert(array(
     "name" => "Next promo",
     "inprogress" => false,
     "priority" => 0,
     "tasks" => array( "select product", "add inventory", "do placement"),
) );

$c->insert(array(
     "name" => "Biz report",
     "inprogress" => false,
     "priority" => 1,
     "tasks" => array( "run sales report", "email report" )
) );

$c->insert(array(
     "name" => "Biz report",
     "inprogress" => false,
     "priority" => 2,
     "tasks" => array( "run marketing report", "email report" )
    ),
    array("w" => true)
);

try {
    $retval = $c->findAndModify(
         array("inprogress" => false, "name" => "Biz report"),
         array('$set' => array('$set' => array('inprogress' => true, "started" => new MongoDate()))),
         null,
         array(
            "sort" => array("priority" => -1),
            "new" => true,
        )
    );
} catch(MongoResultException $e) {
    echo $e->getMessage(), "\n";
    $res = $e->getDocument();
    var_dump($res);
}
?>

The above examples will output something similar to:

$set is not valid for storage.
array(3) {
  ["lastErrorObject"]=>
  array(5) {
    ["connectionId"]=>
    int(6)
    ["err"]=>
    string(30) "$set is not valid for storage."
    ["code"]=>
    int(52)
    ["n"]=>
    int(0)
    ["ok"]=>
    float(1)
  }
  ["ok"]=>
  float(0)
  ["errmsg"]=>
  string(30) "$set is not valid for storage."
}


The MongoCursorException class

(PECL mongo >= 1.0.0)

Introduction

Caused by accessing a cursor incorrectly or a error receiving a reply. Note that this can be thrown by any database request that receives a reply, not just queries. Writes, commands, and any other operation that sends information to the database and waits for a response can throw a MongoCursorException. The only exception is new MongoClient() (creating a new connection), which will only throw MongoConnectionExceptions.

This returns a specific error message to help diagnose the problem and a numeric error code associated with the cause of the exception.

For example, suppose you tried to insert two documents with the same _id:

<?php

try {
    $collection->insert(array("_id" => 1), array("w" => 1));
    $collection->insert(array("_id" => 1), array("w" => 1));
}
catch (MongoCursorException $e) {
    echo "error message: ".$e->getMessage()."\n";
    echo "error code: ".$e->getCode()."\n";
}

?>
This would produce output like:
error message: E11000 duplicate key error index: foo.bar.$_id_  dup key: { : 1 }
error code: 11000
Note that the MongoDB error code (11000) is used for the PHP error code. The PHP driver uses the "native" error code wherever possible.

The following is a list of common errors, codes, and causes. Exact errors are in italics, errors where the message can vary are described in obliques.

  • cannot modify cursor after beginning iteration

    Code: 0

    You are calling a method that sets up the query after executing the query. Reset the cursor and try again.

    An example:

    <?php

    try {
            $cursor = $collection->find();
            var_dump($cursor->getNext());

            // getNext() queried the database, it's too late to set a limit
            $cursor->limit(1);
    }
    catch (    MongoCursorException $e) {
        echo     "error message: ".$e->getMessage()."\n";
        echo     "error code: ".$e->getCode()."\n";
    }

    // this will work, though:
    $cursor->getNext();
    $cursor->reset();
    $cursor->limit(1);

    ?>

  • Get next batch send errors

    Code: 1

    Could not send the query to the database. Make sure the database is still up and the network is okay.

  • cursor not found

    Code: 2

    The driver was trying to fetch more results from the database, but the database did not have a record of the query. This usually means that the cursor timed out on the server side: after a few minutes of inactivity, the database will kill a cursor (see MongoCursor::immortal() for information on preventing this).

    An example:

    <?php

    try {
            $cursor = $collection->find();
            $cursor->getNext();

            // sleep for 15 minutes
            sleep(60*15);

        while (    $cursor->hasNext()) {
                $cursor->getNext();
        }
    }
    catch (    MongoCursorException $e) {
        echo     "error message: ".$e->getMessage()."\n";
        echo     "error code: ".$e->getCode()."\n";
    }

    ?>

  • cursor->buf.pos is null

    Code: 3

    This may indicate you are out of RAM or some other extraordinary circumstance.

  • couldn't get response header

    Code: 4

    A common error if the database or network goes down. This means that the driver couldn't get a response from the connection.

  • no db response

    Code: 5

    This may not even be an error, for example, the database command "shutdown" returns no response. However, if you were expecting a response, this means the database didn't give one.

  • bad response length: %d, did the db assert?

    Code: 6

    This means that the database said that its response was less than 0. This error probably indicates a network error or database corruption.

  • incomplete header

    Code: 7

    Highly unusual. Occurs if the database response started out correctly, but broke off in the middle. Probably indicates a network problem.

  • incomplete response

    Code: 8

    Highly unusual. Occurs if the database response started out correctly, but broke off in the middle. Probably indicates a network problem.

  • couldn't find a response

    Code: 9

    If the response was cached and now cannot be located.

  • error getting socket

    Code: 10

    The socket was closed or encountered an error. The driver should automatically reconnect (if possible) on the next operation.

  • couldn't find reply, please try again

    Code: 11

    The driver saves any database responses it cannot immediately match with a request. This exception occurs if the driver has already passed your request's response and cannot find your response in its cache.

  • error getting database response: errstr

    WSA error getting database response: errstr

    "errstr" is an io error reported directly from the C socket subsystem. On Windows, the error message is prefixed with "WSA".

  • Timeout error

    Code: 13

    If there was an error while waiting for a query to complete.

  • couldn't send query: <various>

    Code: 14

    C socket error on send.

  • max number of retries exhausted, couldn't send query

    Code: 19

    The driver will automatically retry "plain" queries (not commands) a couple of times if the first attempt failed for certain reasons. This is to cause fewer exceptions during replica set failover (although you will probably still have to deal with some) and gloss over transient network issues.

    This can also be caused by the driver not being able to reconnect at all to the database (if, for example, the database is unreachable).

    Version 1.2.2+.

Errors passed through by the database

Database errors should always trigger MongoCursorExceptions on queries. Error messages and codes are sent directly from the database and you should be able to see matching errors in the database log.

A few common database errors are listed below:

  • E11000 duplicate key error index: foo.bar.$X dup key: { /* ... */ }

    Code: 11000

    Database error for duplicate keys.

  • not master

    Codes: 10107, 13435, and 10058

    Not master errors, piped through by the database. ach of these will cause the driver to disconnect and attempt to find a new primary. The actual error you get on failover may not be a "not master" error, depending on when the change in primary occurs.

Class synopsis

MongoCursorException extends MongoException {
}

Table of Contents

  • MongoCursorException::getHost — The hostname of the server that encountered the error


The hostname of the server that encountered the error

  • « MongoCursorException
  • MongoCursorTimeoutException »
  • PHP Manual
  • MongoCursorException
  • The hostname of the server that encountered the error

MongoCursorException::getHost

(PECL mongo >= 1.0.0)

MongoCursorException::getHost — The hostname of the server that encountered the error

Description

public MongoCursorException::getHost ( void ) : string

Returns the hostname of the server the query was sent too.

Parameters

This function has no parameters.

Return Values

Returns the hostname, or NULL if the hostname is unknown.


The MongoCursorTimeoutException class

(PECL mongo >= 1.0.0)

Introduction

Caused by a query timing out. You can set the length of time to wait before this exception is thrown by calling MongoCursor::timeout() on the cursor or setting MongoCursor::$timeout. The static variable is useful for queries such as database commands and MongoCollection::findOne(), both of which implicitly use cursors.

Class synopsis

MongoCursorTimeoutException extends MongoCursorException {
}


The MongoConnectionException class

(PECL mongo >= 1.0.0)

Introduction

Thrown when the driver fails to connect to the database.

There are a number of possible error messages to help you diagnose the connection problem. These are:

  • No candidate servers found

    Thrown when the driver cannot establish a connection to MongoDB (fulfilling the ReadPreferences, if specified).

  • No server name given.

    This error occurs if you pass in "" as the server name, probably because of an typo with string interpolation, e.g., "$servr" instead of "$server".

  • failed to get host [hostname] or port [portnum] from [server].

    This indicated that the server string was malformed. "[hostname]" and "[portnum]" will be as much as the driver could dicipher of it.

  • Operation in progress

    Connecting to the database timed out.

  • Transport endpoint is not connected

    Generally means that the connection string isn't correct, the driver couldn't even find the database server.

  • couldn't determine master

    No server in a replica set connection was identified as the primary.

  • couldn't get host info for [server]

    This indicated that DNS could not resolve the server address you gave. This could easily be caused by a typo, for example, "server" instead of "$server".

  • Invalid Argument

    This can be caused by attempting to connect to a machine that is up but that the database isn't actually running on. Make sure that you've started the database server before connecting.

  • Permission denied

    This means that the socket could not be opened due to permissions issues. On Red Hat variants, this can be caused by a default setting that does not allow Apache to create network connections. You can override this setting by running:

    $ /usr/sbin/setsebool -P httpd_can_network_connect 1
    then restarting Apache.

If the error message is not listed above, it is probably an error from the C socket, and you can search the web for its usual cause.

Class synopsis

MongoConnectionException extends MongoException {
}


The MongoGridFSException class

(PECL mongo >= 1.0.0)

Introduction

Thrown when there are errors reading or writing files to or from the database.

Class synopsis

MongoGridFSException extends MongoException {
}

Error codes

MongoGridFSException error codes
Code | Message | Reason
3 | Could not open file $filename | Attempting to store an invalid file, such as directory
4 | File $filename is too large: $filesize bytes | Maximum filesize in GridFS is 4GB
5 | could not find filehandle | Resource doesn't have a filehandle
6 | no file is associate with this filehandle | Resource isn't a file resource
7 | error setting up file: $filenames | Could not open file for reading
9 | error reading file $filenames | Failed reading file
10 | error reading filehandle | Failed reading from a resource
11 | could not find uploaded file %s | Filename doesn't seem to be uploaded file
12 | Couldn't find tmp_name in the $_FILES array. Are you sure the upload worked? | Uploaded filename probably failed
13 | tmp_name was not a string or an array | Invalid filename given
14 | couldn't find file size | The length property is missing
15 | Cannot find filename | No filename provided, and no filename property set
16 | could not open destination file %s | Destination filename not writable
17 | error reading chunk of file | Chunk corruption
18 | couldn't create a php_stream | Couldn't create a stream resource
19 | couldn't find property | Chunk corruption
20 | chunk number has wrong size (size) when the max is maxchunksize | Chunk larger then expected
21 | chunk has wrong format | Chunk corruption


The MongoDuplicateKeyException class

(PECL mongo >= 1.5.0)

Introduction

Thrown when attempting to insert a document into a collection which already contains the same values for the unique keys.

Class synopsis

MongoDuplicateKeyException extends MongoWriteConcernException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
public MongoWriteConcernException::getDocument ( void ) : array
}

Examples

Example #1 Catching MongoDuplicateKeyException

<?php
$mc = new MongoClient("localhost");

$c = $mc->selectCollection("test", "test");

$c->insert(array('_id' => 1));
try {
    $c->insert(array('_id' => 1));
} catch (MongoWriteConcernException $e) {
    echo $e->getMessage(), "\n";
}
?>

The above examples will output something similar to:

localhost:27017: insertDocument :: caused by :: 11000 E11000 duplicate key error index: test.test.$_id_  dup key: { : 1 }


The MongoProtocolException class

(PECL mongo >= 1.5.0)

Introduction

When talking to MongoDB 2.6.0, and later, certain operations (such as writes) may throw MongoProtocolException when the response from the server did not make sense - for example during network failure (we could read the entire response) or data corruption.

This exception is also thrown when attempting to talk newer protocols then the server supports, for example using the MongoWriteBatch when talking to a MongoDB server prior to 2.6.0.

Class synopsis

MongoProtocolException extends MongoException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
}

Examples

Example #1 Catching MongoProtocolException

Running the following example against MongoDB prior to 2.6.0 will throw an MongoProtocolException

<?php
$mc = new MongoClient("localhost");
$c = $mc->selectCollection("test", "test");

try {
    $batch = new MongoInsertBatch($c);
} catch(MongoProtocolException $e) {
    echo $e->getMessage();
}
?>

The above examples will output something similar to:

Current primary does not have a Write API


The MongoExecutionTimeoutException class

(PECL mongo >= 1.5.0)

Introduction

Thrown when a operation times out server side (i.e. in MongoDB).

To configure the operation timeout threshold, use MongoCursor::maxTimeMS() or the "maxTimeMS" command option.

Class synopsis

MongoExecutionTimeoutException extends MongoException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
}


The MongoWriteConcernException class

(PECL mongo >= 1.5.0)

Introduction

MongoWriteConcernException is thrown when a write fails. See Write Concerns for how to set failure thresholds.

Prior to MongoDB 2.6.0, the » getLastError command would determine whether a write failed.

Class synopsis

MongoWriteConcernException extends MongoCursorException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Methods */
public getDocument ( void ) : array
/* Inherited methods */
public MongoCursorException::getHost ( void ) : string
}

Table of Contents

  • MongoWriteConcernException::getDocument — Get the error document


Get the error document

  • « MongoWriteConcernException
  • Changelog »
  • PHP Manual
  • MongoWriteConcernException
  • Get the error document

MongoWriteConcernException::getDocument

(PECL mongo >= 1.5.0)

MongoWriteConcernException::getDocument — Get the error document

Description

public MongoWriteConcernException::getDocument ( void ) : array

Returns the actual response from the server that was interperated as an error.

Parameters

This function has no parameters.

Return Values

A MongoDB document, if available, as an array.


Changelog

The following changes have been made to classes/functions/methods of this extension.

MongoDB PHP Driver 1.5.0

It supports all new features for MongoDB 2.6, including:

  • Aggregate can now return a cursor
  • Aggregation pipelines can now be explained
  • Possible to set maxTimeMS for commands and queries
  • Transparent support for the new command-based MongoDB write API
  • New MongoWriteBatch classes (using the new MongoDB write API)
  • Support for MongoDB Enterprise features (e.g. Kerberos, LDAP, X509)
  • Option to tune acceptable server latency for secondary reads (secondaryAcceptableLatencyMS)

With this release, some driver functionality which was previously documented as deprecated will now formally raise deprecation notices. This includes:

  • Instantiating the Mongo class
  • Calling MongoCursor::slaveOkay()
  • "wtimeout" and "safe" options for MongoCollection write operations
  • Manipulating public properties on core classes (such as $collection->w)

Note:

No previously deprecated features have been removed.

Changes in behaviour:

  • Setting the mongo.native_long INI setting now raises an error on 32-bit platforms, and now defaults to true for 64-bit platforms.

MongoDB PHP Driver 1.4.0

The 1.4 series introduced fundemental changes in how connections are created to the MongoDB servers. The driver now utilizes PHP native streams, so all normal PHP stream options apply. Furthermore, an experimental Stream Context Support was added.

The 1.4.x series also added support for MongoDB 2.4.x.

The most important improvements however deal with the handling of replica sets, especially nodes that timeout and nodes that are unreachable for various reasons. Besides the improvements to replica set handling, this release addresses issues with read preferences through mongos nodes. It also adds support for SSL enabled connections as well as journal and fsync connection string options.

MongoDB PHP Driver 1.3.0

The 1.3 series introduced several major changes to the extension such as completely rewritten connection handling (and removal of the pooling mechanism), support for ReadPreferences and change the default WriteConcerns to be acknowledged by introducing a new class MongoClient which serves as a replacement class for the now deprecated Mongo class.

The driver now also supports connecting to multiple mongos instances (the Mongo Shard router) for loadbalancing.

Other enhancements include improved logging for easier connection handling debugging with MongoLog and support for the » Aggregation Framework via the MongoCollection::aggregate() method.

Changes to existing methods

Following is a list of all improvements to existing methods since their inception.

Version | Function | Description
1.7.0 | MongoDB::execute | This method has been deprecated as a result of the underlaying eval command being deprecated in MongoDB 3.0+.
1.6.0 | MongoClient::__construct | Added support for "SCRAM-SHA-1" in "authMechanism" option.
 | MongoCollection::count | The second parameter is now an options array. Passing limit and skip as the second and third parameters, respectively, is deprecated.
 | MongoDB::getCollectionNames | Changed first parameter to be an array of options. Pre-1.6.0, the first parameter was a boolean indicating the "includeSystemCollections" option.
 | MongoDB::listCollections | Changed first parameter to be an array of options. Pre-1.6.0, the first parameter was a boolean indicating the "includeSystemCollections" option.
1.5.0 | log_cmd_delete | Only available when connected to MongoDB 2.6.0+
 | log_cmd_insert | Only available when connected to MongoDB 2.6.0+
 | log_cmd_update | Only available when connected to MongoDB 2.6.0+
 | log_write_batch | Only available when connected to MongoDB 2.6.0+
 | MongoBinData::__construct | The default changed from 2 (MongoBinData::BYTE_ARRAY) to 0 (MongoBinData::GENERIC).
 | MongoClient::__construct | Added "authMechanism", "gssapiServiceName", and "secondaryAcceptableLatencyMS".
 | MongoClient::__construct | Added "authSource".
 | MongoCollection::aggregate | Added optional options argument
 | MongoCollection::batchInsert | Added the "wTimeoutMS" option, which replaces "wtimeout". Emits E_DEPRECATED when "wtimeout" is used. Added the "socketTimeoutMS" option, which replaces "timeout". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
 | MongoCollection::ensureIndex | Renamed the "wtimeout" option to "wTimeoutMS". Emits E_DEPRECATED when "wtimeout" is used. Renamed the "timeout" option to "socketTimeoutMS". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
 | MongoCollection::findOne | Added optional options argument.
 | MongoCollection::group | Added "maxTimeMS" option.
 | MongoCollection::insert | Added the "wTimeoutMS" option, which replaces "wtimeout". Emits E_DEPRECATED when "wtimeout" is used. Added the "socketTimeoutMS" option, which replaces "timeout". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
 | MongoCollection::remove | Added "wTimeoutMS" option, which replaces "wtimeout". Emits E_DEPRECATED when "wtimeout" is used. Added "socketTimeoutMS" option, which replaces "timeout". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
 | MongoCollection::save | Added "wTimeoutMS" option, which replaces "wtimeout". Emits E_DEPRECATED when "wtimeout" is used. Added "socketTimeoutMS" option, which replaces "timeout". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
 | MongoCollection::toIndexString | This method has been deprecated.
 | MongoCollection::update | Added the "wTimeoutMS" option, which replaces "wtimeout". Emits E_DEPRECATED when "wtimeout" is used. Added the "socketTimeoutMS" option, which replaces "timeout". Emits E_DEPRECATED when "timeout" is used. Emits E_DEPRECATED when "safe" is used.
 | MongoCursor::slaveOkay | This method has been deprecated in favour of MongoCursor::setReadPreference and .
 | MongoDB::command | Renamed the "timeout" option to "socketTimeoutMS". Emits E_DEPRECATED when "timeout" is used. Added hash by-reference parameter.
1.4.5 | MongoCursor::batchSize | Before 1.4.5, this method would throw an MongoCursorException if the cursor had already started iterating.
1.4.0 | MongoClient::__construct | Added "ssl" option and support for connecting over SSL. Added "wTimeoutMS" option, which replaces "wTimeout". Emits E_DEPRECATED when "slaveOkay" or "timeout" is used.
 | MongoCursor::hint | The index argument now supports index names as string values. In versions before 1.4.0, only array or object values were accepted.
 | MongoCursor::setFlag | Support for flag 3 (OPLOG_REPLAY) is added. Versions before 1.4.0 would throw a warning saying that the flag is unsupported.
 | MongoDB::createCollection | In versions before 1.4.0, the options were all arguments to the method. The function synopsis in those older versions is: public MongoCollectionMongoDB::createCollection stringname boolcappedFALSE intsize0 intmax0 The meaning of the options is the same as described under the options argument above.
 | MongoId::__construct | An exception is thrown when passed invalid string
1.3.4 | MongoClient::__construct | Added "connectTimeoutMS" and "socketTimeoutMS" options.
 | MongoCollection::batchInsert | Added "wtimeout" option.
 | MongoCollection::ensureIndex | Added "wtimeout" option.
 | MongoCollection::insert | Added "wtimeout" option.
 | MongoCollection::remove | Added "wtimeout" option.
 | MongoCollection::update | Added "wtimeout" option.
1.3.3 | MongoClient::getReadPreference | The return value has changed to be consistent with MongoClient::setReadPreference. The type value was changed from a number to a string, type_string was removed, and tagsets now expresses tags as key/value pairs instead of colon-delimited strings.
 | MongoCollection::getReadPreference | The return value has changed to be consistent with MongoCollection::setReadPreference. The type value was changed from a number to a string, type_string was removed, and tagsets now expresses tags as key/value pairs instead of colon-delimited strings.
 | MongoDB::getReadPreference | The return value has changed to be consistent with MongoDB::setReadPreference. The type value was changed from a number to a string, type_string was removed, and tagsets now expresses tags as key/value pairs instead of colon-delimited strings.
1.3.0 | MongoClient::close | The connection parameter to this function was added in 1.3.0. Before that, only the write connection would be closed by this method.
 | MongoClient::__construct | Added "readPreference", "readPreferenceTags", "w", and "wTimeout" options.
 | MongoCollection::batchInsert | Added "w" option.
 | MongoCollection::ensureIndex | Added "w" option. The options parameter no longer accepts a boolean to signify a unique index. Instead, this now has to be done with array('unique' => true).
 | MongoCollection::insert | Added "w" option. The options parameter no longer accepts a boolean to signify an acknowledged write. Instead, this now has to be done with array('w' => 1) (the default behaviour of MongoClient).
 | MongoCollection::remove | Added "w" option. The options parameter no longer accepts a boolean to signify "justOne". Instead, this now has to be done with array('justOne' => true).
 | MongoCollection::update | Added "w" option. The options parameter no longer accepts a boolean to signify an upsert. Instead, this now has to be done with array('upsert' => true).
 | MongoDB::listCollections | Added the includeSystemCollections parameter.
 | MongoGridFSCursor::key | The document's _id is returned as a string value, since the key should be unique. Pre-1.3.0, filename was returned.
1.2.11 | Mongo::getPoolSize | Emits E_DEPRECATED when used.
 | Mongo::getSlave | Emits E_DEPRECATED when used.
 | Mongo::getSlaveOkay | Emits E_DEPRECATED when used.
 | Mongo::poolDebug | Emits E_DEPRECATED when used.
 | Mongo::setSlaveOkay | Emits E_DEPRECATED when used.
 | Mongo::switchSlave | Emits E_DEPRECATED when used.
 | MongoBinData::__construct | Emits E_DEPRECATED when the second argument is not used. The default value for type may change in the near future.
 | MongoCollection::ensureIndex | Emits E_DEPRECATED when options is scalar.
 | MongoCollection::getSlaveOkay | Emits E_DEPRECATED when used.
 | MongoCollection::group | Emits E_DEPRECATED when options is scalar.
 | MongoCollection::remove | Emits E_DEPRECATED when options is scalar.
 | MongoCollection::setSlaveOkay | Emits E_DEPRECATED when used.
 | MongoCollection::update | Emits E_DEPRECATED when options is scalar.
 | MongoCursor::doQuery | Emits E_DEPRECATED when used.
 | MongoDB::authenticate | Emits E_DEPRECATED when used. Please pass in the authentication details to the constructor.
 | MongoDB::forceError | Emits E_DEPRECATED when used.
 | MongoDB::getSlaveOkay | Emits E_DEPRECATED when used.
 | MongoDB::prevError | Emits E_DEPRECATED when used.
 | MongoDB::resetError | Emits E_DEPRECATED when used.
 | MongoDB::setSlaveOkay | Emits E_DEPRECATED when used.
 | MongoPool::getSize | Emits E_DEPRECATED when used.
 | MongoPool::info | Emits E_DEPRECATED when used.
 | MongoPool::setSize | Emits E_DEPRECATED when used.
1.2.10 | MongoClient::getHosts | Support for non-replicasets was added. The returned array elements now also include the hostname and port.
1.2.7 | MongoCollection::batchInsert | Added "continueOnError" option.
1.2.5 | MongoGridFS::storeUpload | Changed second parameter to an array of metadata. Pre-1.2.5, the second parameter was an optional string overriding the filename.
1.2.0 | MongoClient::close | Before version 1.2.0 the driver would not use persistent connections by default, and all connections would be closed as soon as a MongoDB connection went out if scope. Since version 1.2.0 this is no longer the case and it is a bad idea to call close as you might end up overloading the server with connections under high load.
 | MongoClient::__construct | Added "username" and "password" options. Removed "persist" option, as all connections are now persistent. It can still be used, but it doesn't affect anything. "persist" If the connection should be persistent. If set, the connection will be persistent. The string representation of the value is used as an ID for the connection, so two instances of MongoClient that are initialized with array("persist" => "foobar") will share the same database connection, whereas an instance initialized with array("persist" => "barbaz") will use a different database connection. The "replicaSet" option now takes a string, not a boolean.
 | MongoCollection::ensureIndex | Added "timeout" option.
 | MongoCollection::insert | Added "timeout" option.
 | MongoCollection::remove | Added "timeout" option.
 | MongoCollection::save | Added "timeout" option.
 | MongoCollection::update | Added "timeout" option.
 | MongoDB::command | Added options parameter with a single option: "timeout".
1.1.0 | MongoCursor::info | Added a number of other fields, including id (the cursor id), at (the driver's counter of which document is current), numReturned (the number returned by the server in the current batch), and server (which server the query was sent to—useful in conjunction with .
1.0.11 | MongoCollection::ensureIndex | The "safe" option will trigger a primary failover, if necessary. MongoException will be thrown if the index name (either generated or set) is longer than 128 bytes.
 | MongoCollection::insert | Disconnects on "not master" errors if "safe" is set.
 | MongoCollection::remove | Disconnects on "not master" errors if "safe" is set.
 | MongoCollection::save | Disconnects on "not master" errors if "safe" is set.
 | MongoCollection::update | Disconnects on "not master" errors if "safe" is set.
1.0.10 | MongoCursor::info | Added started_iterating field, a boolean indicating if cursor is pre- or post-query.
1.0.9 | MongoClient::__construct | Added "replicaSet" option.
 | MongoCollection::batchInsert | Added ability to pass integers to the "safe" option, which previously only accepted booleans. Added "fsync" option.
 | MongoCollection::insert | Added ability to pass integers to the "safe" option, which previously only accepted booleans. Added "fsync" option. The return type was changed to be an array containing error information if the "safe" option is used. Otherwise, a boolean is returned as before.
 | MongoCollection::remove | Added ability to pass integers to the "safe" option, which previously only accepted booleans. Added "fsync" option. The return type was changed to be an array containing error information if the "safe" option is used. Otherwise, a boolean is returned as before.
 | MongoCollection::save | Added "fsync" option.
 | MongoCollection::update | Added ability to pass integers to the "safe" option, which previously only accepted booleans. Added "fsync" option. The return type was changed to be an array containing error information if the "safe" option is used. Otherwise, a boolean is returned as before.
1.0.7 | MongoCollection::count | Added limit and skip as second and third parameters, respectively.
1.0.5 | MongoCollection::batchInsert | Added options parameter.
 | MongoCollection::ensureIndex | Added the "name" option to override index name creation.
 | MongoCollection::remove | Changed second parameter to be an array of options. Pre-1.0.5, the second parameter was a boolean indicating the "safe" option.
 | MongoCollection::save | Added options parameter.
 | MongoCollection::update | Added "safe" option.
1.0.2 | MongoClient::__construct | Changed constructor to take an array of options. Pre-1.0.2, the constructor took the following parameters: server The server name. connect Optional boolean parameter specifying if the constructor should connect to the database before returning. Defaults to TRUE. persistent If the connection should be persistent. paired If the connection should be paired.
 | MongoCollection::ensureIndex | Changed options parameter from boolean to array. Pre-1.0.2, the second parameter was an optional boolean value specifying a unique index.
 | MongoCollection::insert | Changed second parameter to be an array of options. Pre-1.0.2, the second parameter was a boolean indicating the "safe" option.
1.0.1 | MongoCollection::insert | Throw a MongoCursorException if the "safe" option is set and the insert fails.
 | MongoCollection::update | Changed options parameter from boolean to array. Pre-1.0.1, the second parameter was an optional boolean value specifying an upsert.


MongoDB driver

Unlike the mongo 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 driver to focus on essential features for which an extension implementation is paramount for performance.

  • 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 driver 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\Session — The MongoDB\Driver\Session class
    • MongoDB\Driver\ClientEncryption — The MongoDB\Driver\ClientEncryption 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\WriteConcernError — The MongoDB\Driver\WriteConcernError class
    • MongoDB\Driver\WriteError — The MongoDB\Driver\WriteError class
    • MongoDB\Driver\WriteResult — The MongoDB\Driver\WriteResult class
  • MongoDB\BSON — BSON type classes and serialization functions
    • Functions
    • MongoDB\BSON\Binary — The MongoDB\BSON\Binary class
    • 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 (deprecated)
    • MongoDB\BSON\Int64 — The MongoDB\BSON\Int64 class
    • MongoDB\BSON\Symbol — The MongoDB\BSON\Symbol class (deprecated)
    • MongoDB\BSON\Undefined — The MongoDB\BSON\Undefined class (deprecated)
  • 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\CommandSubscriber — The MongoDB\Driver\Monitoring\CommandSubscriber 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\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 (deprecated)
    • 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


Installing/Configuring

  • Requirements
  • Installation
    • Installing the MongoDB PHP Driver with PECL
    • Installing the MongoDB PHP Driver on macOS with Homebrew
    • Installing the MongoDB PHP Driver on Windows
    • Manually Installing the MongoDB PHP Driver
  • Runtime Configuration
  • Predefined Constants


Requirements

The driver requires PHP 5.5 or higher.

The driver requires » libbson and » libmongoc, and will use bundled versions of both libraries by default.

The driver requires » OpenSSL and will rely on PHP to find its headers (i.e. PHP_SETUP_OPENSSL). If the build process fails to find OpenSSL, check that the OpenSSL development package (e.g. libssl-dev) and » pkg-config are both installed.

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.

» Cyrus SASL is an optional dependency and will be used if available.


Installation

Table of Contents

  • Installing the MongoDB PHP Driver with PECL
  • Installing the MongoDB PHP Driver on macOS with Homebrew
  • Installing the MongoDB PHP Driver on Windows
  • Manually Installing the MongoDB PHP Driver


Installing the MongoDB PHP Driver 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 driver:

$ sudo pecl install mongodb

If your system has multiple version of PHP installed (e.g. macOS default, Homebrew, » XAMPP), note that that each version of PHP has its own pecl command and php.ini file.

Installing the driver via PECL will use bundled versions of » libbson and » libmongoc 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 your php.ini file:

extension=mongodb.so


Installing the MongoDB PHP Driver 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.


Installing the MongoDB PHP Driver on Windows

Precompiled binaries for each release are available from » PECL for a variety of combinations of versions, thread safety, and VC libraries. Extract the archive and put php_mongodb.dll in your PHP extension directory ("ext" by default).

Add the following line to your php.ini file:

extension=php_mongodb.dll

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


Manually Installing the MongoDB PHP Driver

For driver developers and people interested in the latest bugfixes, you can compile the driver 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

If your system has multiple version of PHP installed (e.g. macOS default and » XAMPP), note that each version of PHP has its own phpize command and php.ini file.

By default, the driver will use bundled versions of » libbson, » libmongoc, and » libmongocrypt and attempt to configure them on its own. If these libraries are already installed as system libraries, you can instruct the driver to utilize them by specifying --with-libbson=yes --with--libmongoc=yes as arguments to configure. Starting with version 1.7.0 of the extension, these arguments are deprecated and you should use --with-mongodb-system-libs=yes instead.

For a complete list of configure options, run configure --help.

When using bundled versions of libbson and libmongoc, the driver will also attempt to select an SSL library according to the --with-mongodb-ssl option for configure. The default value is --with-mongodb-ssl=auto, which will search for Secure Transport (macOS only), OpenSSL, and LibreSSL, in that order. Additionally, you may specify openssl, libressl, or darwin to force selection of a particular library, respectively.

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. If pkg-config is not used, configure also supports a --with-openssl-dir=DIR argument, which can be used to specify a manual search path (for OpenSSL only).

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-20151012/

Ensure that the extension_dir option in php.ini points to the directory where mongodb.so was installed. You can query for the option by running:

$ php -i | grep extension_dir
  extension_dir => /usr/lib/php/extensions/debug-non-zts-20151012 =>
                   /usr/lib/php/extensions/debug-non-zts-20151012

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 your php.ini file:

extension=mongodb.so


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

mongodb Configure Options
Name | Default | Changeable | Changelog | Comments
mongodb.debug | "" | PHP_INI_ALL |  |

Here's a short explanation of the configuration directives.

mongodb.debug string

Store full activity debug log in this directory or stream. The special value "stderr" can be provided to write to STDERR.

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

In this section you will find several tutorials on how to use the MongoDB driver for PHP.

  • Using the PHP Library for MongoDB (PHPLIB)
  • Application Performance Monitoring (APM)


Using the PHP Library for MongoDB (PHPLIB)

After the initial driver set-up, we will continue explaining how to get started with the MongoDB driver and 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 previously used the old driver (i.e. mongo extension), the library's API should look familiar. It contains a » Client class for connecting to MongoDB, and » 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). Various Collection methods have been renamed for clarity, and to be in accordance with a new language-agnostic » specification.

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()}'";
?>

Instead of injecting the generated _id field into the input document (as was done in the old driver), it is now made available through the result object returned by the insertOne method.

After insertion, you can of course also query 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 type classes in the library by default. These classes ensure that values preserve their type when being serialized back into BSON, which avoids a caveat in the old driver where arrays might turn into documents, and vice versa. Additionally, the classes extend ArrayObject for enhanced usability. You can find more information on how serialization and deserialization between PHP variables and BSON is handled by the driver and library by reading the Persisting Data specification.


Application Performance Monitoring (APM)

Since version 1.3, the MongoDB driver contains an API for performance monitoring. This API allows you to find out how long specific operations take by setting up subscribers. Each subscriber is required to implement one or more interfaces under the MongoDB\Driver\Monitoring namespace. Currently, only the MongoDB\Driver\Monitoring\CommandSubscriber interface is available.

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 )
    {
    }

    public function commandSucceeded( \MongoDB\Driver\Monitoring\CommandSucceededEvent $event )
    {
    }

    public function commandFailed( \MongoDB\Driver\Monitoring\CommandFailedEvent $event )
    {
    }
}

?>

Registering the Subscriber

Once a subscriber object is instantiated, it needs to be registered with the driver's monitoring system. This is done by calling MongoDB\Driver\Monitoring\addSubscriber().

<?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 )
    {
        if ( array_key_exists( 'find', (array) $event->getCommand() ) )
        {
            $queryShape = $this->createQueryShape( (array) $event->getCommand()->filter );
            $this->pendingCommands[$event->getRequestId()] = $queryShape;
        }
    }

    public function commandSucceeded( \MongoDB\Driver\Monitoring\CommandSucceededEvent $event )
    {
        $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 )
    {
        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

  • Architecture — Architecture Overview
  • Connections — Connection handling and persistence
  • Persisting Data — Serialization and deserialization of PHP variables into MongoDB
    • Serialization to BSON
    • Deserialization from BSON


Architecture Overview

This section explains how all the different parts of the driver fit together. From the different language runtimes, through the extension and to the PHP libraries on top. This new architecture has replaced the old mongo extension. We refer to the new one as the mongodb extension.

At the top of this stack sits a pure » PHP library, which we will distribute as a Composer package. This library will provide an API similar to what users have come to expect from the old mongo driver (e.g. CRUD methods, database and collection objects, command helpers) and we expect it to be a common dependency for most applications built with MongoDB. This library will also implement common » specifications, in the interest of improving API consistency across all of the » drivers maintained by MongoDB (and hopefully some community drivers, too).

Sitting below that library we have the lower level driver. This extension will effectively form the glue between PHP and our system libraries (» libmongoc and » libbson). This extension will expose an identical public API for the most essential and performance-sensitive functionality:

  • Connection management
  • BSON encoding and decoding
  • Object document serialization (to support ODM libraries)
  • Executing commands and write operations
  • Handling queries and cursors

By decoupling the driver internals and a high-level API into an extension and PHP libraries, respectively, we hope to reduce our maintainence burden and allow for faster iteration on new features. As a welcome side effect, this also makes it easier for anyone to contribute to the driver. Additionally, an identical public API will make it that much easier to port an application across PHP runtimes, whether the application uses the low-level driver directly or a higher-level PHP library.

» GridFS is a great example of why we chose this direction. Although we implemented GridFS in C for our old mongo driver, it is actually quite a high-level specification. Its API is just an abstraction for accessing two collections: files (i.e. metadata) and chunks (i.e. blocks of data). Likewise, all of the syntactic sugar found in the old mongo driver, such as processing uploaded files or exposing GridFS files as PHP streams, can be implemented in pure PHP. Provided we have performant methods for reading from and writing to GridFS' collections – and thanks to our low level extensions, we will – shifting this API to PHP is win-win.

Earlier I mentioned that we expect the PHP library to be a common dependency for most applications, but not all. Some users may prefer to stick to the no-frills API offered by the extensions, or create their own high-level abstraction (akin to » Doctrine MongoDB for the old mongo driver). Future libraries could include a PHP library geared for MongoDB administration, which provides an API for various user management and ops commands. The next major version of » Doctrine MongoDB ODM will likely also sit directly atop the extensions.

While we will continue to maintain and support the old mongo driver and its users for the foreseeable future, we invite everyone to use the next-generation driver and consider it for any new projects going forward. You can find all of the essential components across GitHub and JIRA:

Driver Source Code and JIRA Locations
Project | GitHub | JIRA
PHP Library | » mongodb/mongo-php-library | » PHPLIB
PHP 5 and PHP 7 Driver (phongo) | » mongodb/mongo-php-driver | » PHPC

The existing » PHP project in JIRA will remain open for reporting bugs against the old mongo driver, but we would ask that you use the new projects above for anything pertaining to our next-generation drivers.


Connection handling and persistence

Note: On Unix platforms, the MongoDB driver 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 driver 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 driver 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).

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 driver 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 driver discovers additional members of the replica set after issuing isMaster 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 should be made. Depending on how long ago the previous request was served, the driver may need to issue additional isMaster commands to update its view of the topologies.

Socket persistence (PHP versions before 1.2.0)

Versions of the PHP driver 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 driver persists individual database connections but not authentication state or topology information. This means that the driver 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 driver >= 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 driver supports all SSL context options since it uses PHP's Streams API.


Serialization and deserialization of PHP variables into MongoDB

Table of Contents

  • Serialization to BSON
  • Deserialization from BSON

This document discusses the methods how compound structures (documents, arrays, objects) are persisted through the drivers. And how they are brought back into PHP land.


Serialization to BSON

Arrays

If an array is a packed array — i.e. 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";
  function bsonSerialize() {
      return [ 'foo' => $this->foo, 'prot' => $this->prot ];
  }
} // => { "foo" : 42, "prot" : "wine" }

class AnotherClass2 implements MongoDB\BSON\Serializable {
  public $foo = 42;
  function bsonSerialize() {
      return $this;
  }
} // => MongoDB\Driver\Exception\UnexpectedValueException("bsonSerialize() did not return an array or stdClass")

class AnotherClass3 implements MongoDB\BSON\Serializable {
  private $elements = [ 'foo', 'bar' ];
  function bsonSerialize() {
      return $this->elements;
  }
} // => { "0" : "foo", "1" : "bar" }

class ContainerClass implements MongoDB\BSON\Serializable {
  public $things = AnotherClass4 implements MongoDB\BSON\Serializable {
    private $elements = [ 0 => 'foo', 2 => 'bar' ];
    function bsonSerialize() {
      return $this->elements;
    }
  }
  function bsonSerialize() {
      return [ 'things' => $this->things ];
  }
} // => { "things" : { "0" : "foo", "2" : "bar" } }

class ContainerClass implements MongoDB\BSON\Serializable {
  public $things = AnotherClass5 implements MongoDB\BSON\Serializable {
    private $elements = [ 0 => 'foo', 2 => 'bar' ];
    function bsonSerialize() {
      return array_values($this->elements);
    }
  }
  function bsonSerialize() {
      return [ 'things' => $this->things ];
  }
} // => { "things" : [ "foo", "bar" ] }

class ContainerClass implements MongoDB\BSON\Serializable {
  public $things = AnotherClass6 implements MongoDB\BSON\Serializable {
    private $elements = [ 'foo', 'bar' ];
    function bsonSerialize() {
      return (object) $this->elements;
    }
  }
  function bsonSerialize() {
      return [ 'things' => $this->things ];
  }
} // => { "things" : { "0" : "foo", "1" : "bar" } }

class UpperClass implements MongoDB\BSON\Persistable {
  public $foo = 42;
  protected $prot = "wine";
  private $fpr = "cheese";
  function bsonSerialize() {
      return [ 'foo' => $this->foo, 'prot' => $this->prot ];
  }
} // => { "foo" : 42, "prot" : "wine", "__pclass" : { "$type" : "80", "$binary" : "VXBwZXJDbGFzcw==" } }


Deserialization from BSON

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 current driver 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.

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


  • « Deserialization from BSON
  • Request Injection Attacks »
  • PHP Manual
  • MongoDB
  • Security

Security

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

  • MongoDB\Driver\Manager — The MongoDB\Driver\Manager class
    • 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::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::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::selectServer — Select a server matching a read preference
    • MongoDB\Driver\Manager::startSession — Start a new client session for use with this client
  • MongoDB\Driver\Command — The MongoDB\Driver\Command class
    • MongoDB\Driver\Command::__construct — Create a new Command
  • MongoDB\Driver\Query — The MongoDB\Driver\Query class
    • MongoDB\Driver\Query::__construct — Create a new Query
  • MongoDB\Driver\BulkWrite — The MongoDB\Driver\BulkWrite class
    • 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
  • MongoDB\Driver\Session — The MongoDB\Driver\Session class
    • 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::isInTransaction — Returns whether a multi-document transaction is in progress
    • MongoDB\Driver\Session::startTransaction — Starts a transaction
  • MongoDB\Driver\ClientEncryption — The MongoDB\Driver\ClientEncryption class
    • MongoDB\Driver\ClientEncryption::createDataKey — Create a new encryption data key
    • MongoDB\Driver\ClientEncryption::decrypt — Decrypt a value
    • MongoDB\Driver\ClientEncryption::encrypt — Encrypt a value
  • MongoDB\Driver\WriteConcern — The MongoDB\Driver\WriteConcern class
    • 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
    • MongoDB\Driver\WriteConcern::serialize — Serialize a WriteConcern
    • MongoDB\Driver\WriteConcern::unserialize — Unserialize a WriteConcern
  • MongoDB\Driver\ReadPreference — The MongoDB\Driver\ReadPreference class
    • MongoDB\Driver\ReadPreference::bsonSerialize — Returns an object for BSON serialization
    • MongoDB\Driver\ReadPreference::__construct — Create a new ReadPreference
    • 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 as a string
    • MongoDB\Driver\ReadPreference::getTagSets — Returns the ReadPreference's "tagSets" option
    • MongoDB\Driver\ReadPreference::serialize — Serialize a ReadPreference
    • MongoDB\Driver\ReadPreference::unserialize — Unserialize a ReadPreference
  • MongoDB\Driver\ReadConcern — The MongoDB\Driver\ReadConcern class
    • 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
    • MongoDB\Driver\ReadConcern::serialize — Serialize a ReadConcern
    • MongoDB\Driver\ReadConcern::unserialize — Unserialize a ReadConcern
  • MongoDB\Driver\Cursor — The MongoDB\Driver\Cursor class
    • MongoDB\Driver\Cursor::__construct — Create a new Cursor (not used)
    • 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::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\CursorId — The MongoDB\Driver\CursorId class
    • MongoDB\Driver\CursorId::__construct — Create a new CursorId (not used)
    • MongoDB\Driver\CursorId::serialize — Serialize a CursorId
    • MongoDB\Driver\CursorId::__toString — String representation of the cursor ID
    • MongoDB\Driver\CursorId::unserialize — Unserialize a CursorId
  • MongoDB\Driver\CursorInterface — The MongoDB\Driver\CursorInterface interface
    • 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
  • MongoDB\Driver\Server — The MongoDB\Driver\Server class
    • 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::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 about this server
    • MongoDB\Driver\Server::getLatency — Returns the latency of this server
    • MongoDB\Driver\Server::getPort — Returns the port on which this server is listening
    • 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
  • MongoDB\Driver\WriteConcernError — The MongoDB\Driver\WriteConcernError class
    • MongoDB\Driver\WriteConcernError::getCode — Returns the WriteConcernError's error code
    • MongoDB\Driver\WriteConcernError::getInfo — Returns additional metadata for the WriteConcernError
    • MongoDB\Driver\WriteConcernError::getMessage — Returns the WriteConcernError's error message
  • MongoDB\Driver\WriteError — The MongoDB\Driver\WriteError class
    • 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 additional metadata for the WriteError
    • MongoDB\Driver\WriteError::getMessage — Returns the WriteError's error message
  • MongoDB\Driver\WriteResult — The MongoDB\Driver\WriteResult class
    • 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\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 MongoDB\Driver\Manager {
/* Methods */
 final public __construct
  ([ string $uri = "mongodb://127.0.0.1/"
 [, array $uriOptions = array()
 [, array $driverOptions = array()
]]] )
final public createClientEncryption ( array $options ) : MongoDB\Driver\ClientEncryption
final public executeBulkWrite ( string $namespace , MongoDB\Driver\BulkWrite $bulk [, array $options = array() ] ) : MongoDB\Driver\WriteResult
final public executeCommand ( string $db , MongoDB\Driver\Command $command [, array $options = array() ] ) : MongoDB\Driver\Cursor
final public executeQuery ( string $namespace , MongoDB\Driver\Query $query [, array $options = array() ] ) : MongoDB\Driver\Cursor
final public executeReadCommand ( string $db , MongoDB\Driver\Command $command [, array $options = array() ] ) : MongoDB\Driver\Cursor
final public executeReadWriteCommand ( string $db , MongoDB\Driver\Command $command [, array $options = array() ] ) : MongoDB\Driver\Cursor
final public executeWriteCommand ( string $db , MongoDB\Driver\Command $command [, array $options = array() ] ) : MongoDB\Driver\Cursor
final public getReadConcern ( void ) : MongoDB\Driver\ReadConcern
final public getReadPreference ( void ) : MongoDB\Driver\ReadPreference
final public getServers ( void ) : array
final public getWriteConcern ( void ) : MongoDB\Driver\WriteConcern
final public selectServer ( MongoDB\Driver\ReadPreference $readPreference ) : MongoDB\Driver\Server
final public startSession ([ array $options ] ) : 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 (3) {
  ["request_id"]=>
  int(1714636915)
  ["uri"]=>
  string(25) "mongodb://localhost:27017"
  ["cluster"]=>
  array(13) {
    ["mode"]=>
    string(6) "direct"
    ["state"]=>
    string(4) "born"
    ["request_id"]=>
    int(0)
    ["sockettimeoutms"]=>
    int(300000)
    ["last_reconnect"]=>
    int(0)
    ["uri"]=>
    string(25) "mongodb://localhost:27017"
    ["requires_auth"]=>
    int(0)
    ["nodes"]=>
    array(...)
    ["max_bson_size"]=>
    int(16777216)
    ["max_msg_size"]=>
    int(50331648)
    ["sec_latency_ms"]=>
    int(15)
    ["peers"]=>
    array(0) {
    }
    ["replSet"]=>
    NULL
  }
}

Table of Contents

  • 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::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::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::selectServer — Select a server matching a read preference
  • MongoDB\Driver\Manager::startSession — Start a new client session for use with this client


Create new MongoDB Manager

  • « MongoDB\Driver\Manager
  • MongoDB\Driver\Manager::createClientEncryption »
  • PHP Manual
  • MongoDB\Driver\Manager
  • Create new MongoDB Manager

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 = "mongodb://127.0.0.1/"
 [, array $uriOptions = array()
 [, array $driverOptions = array()
]]] )

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 driver 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 MongoDB driver 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]]][/[database][?options]]

For details on supported options, see » Connection String Options in the MongoDB manual. » Connection pool options are not supported, as the PHP driver 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.

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.

For authentication mechanisms that delegate credential storage to other services (e.g. GSSAPI), this should be "$external".

canonicalizeHostname boolean

If TRUE, the driver will resolve the real hostname for the server IP address before authenticating via SASL. Some underlying GSSAPI layers already do this, but the functionality may be disabled in their config (e.g. krb.conf). Defaults to FALSE.

This option is a deprecated alias for the "CANONICALIZE_HOST_NAME" property of the "authMechanismProperties" URI option.

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 integer

The time in milliseconds to attempt a connection before timing out. Defaults to 10,000 milliseconds.

gssapiServiceName string

Set the Kerberos service name when connecting to Kerberized MongoDB instances. This value must match the service name set on MongoDB instances (i.e. » saslServiceName server parameter). Defaults to "mongodb".

This option is a deprecated alias for the "SERVICE_NAME" property of the "authMechanismProperties" URI option.

heartbeatFrequencyMS integer

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 boolean

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.

localThresholdMS integer

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 integer

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 boolean

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 boolean

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.

safe boolean

If TRUE, specifies 1 for the default write concern's w parameter. If FALSE, 0 is specified. For details, see MongoDB\Driver\WriteConcern.

This option is deprecated and should not be used.

serverSelectionTimeoutMS integer

Specifies how long in milliseconds to block for server selection before throwing an exception. Defaults to 30,000 milliseconds.

serverSelectionTryOnce boolean

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.

slaveOk boolean

Specifies "secondaryPreferred" for the read preference mode if TRUE. For details, see MongoDB\Driver\ReadPreference.

This option is deprecated and should not be used.

socketCheckIntervalMS integer

If a socket has not been used recently, the driver must check it via an isMaster command before using it for any operation. Defaults to 5,000 milliseconds.

socketTimeoutMS integer

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

ssl boolean

Initiates the connection with TLS/SSL if TRUE. Defaults to FALSE.

This option is a deprecated alias for the "tls" URI option.

tls boolean

Initiates the connection with TLS/SSL if TRUE. Defaults to FALSE.

tlsAllowInvalidCertificates boolean

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 boolean

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.

tlsInsecure boolean

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 integer|string

Corresponds to the default write concern's w parameter. For details, see MongoDB\Driver\WriteConcern.

wTimeoutMS integer|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 integer

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
allow_invalid_hostname boolean

Disables hostname validation if TRUE. Defaults to FALSE.

Allowing invalid hostnames may expose the driver to a » man-in-the-middle attack.

This option is a deprecated alias for the "tlsAllowInvalidHostnames" URI option.

autoEncryption array

Provides options to enable automatic client-side field level encryption. The following options are supported:

Options for automatic encryption
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.
kmsProviders array

A document containing the configuration for one or more KMS providers, which are used to encrypt data keys. Currently aws or localare supported and at least one must be specified.

The format for aws is as follows:

aws: {
    accessKeyId: <string>,
    secretAccessKey: <string>
}

The format for local is as follows:

local: {
    // The master key used to encrypt/decrypt data keys
    key: <96-byte MongoDB\BSON\Binary with subtype 0>
}
schemaMap array

Allows specifying a local JSON schema that is used to configure encryption.

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 | boolean | With this option set to TRUE, mongocryptd will not be spawned automatically. This is used to disable automatic encryption.
extraOptions | array | The extraOptions relate to the mongocryptd process. 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 whitelisted operations, see the » Client-Side Encryption Specification.

ca_dir string

Path to a correctly hashed certificate directory. The system certificate store will be used by default.

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

This option is a deprecated alias for the "tlsCAFile" URI option.

context resource

SSL context options to be used as fallbacks if a driver option or its equivalent URI option, if any, is not specified. Note that the driver does not consult the default stream context (i.e. stream_context_get_default()). The following context options are supported:

SSL context option fallbacks
Driver option | Context option (fallback)
ca_dir | capath
ca_file | cafile
pem_file | local_cert
pem_pwd | passphrase
weak_cert_validation | allow_self_signed

This option is supported for backwards compatibility, but should be considered deprecated.

crl_file | string | Path to a certificate revocation list file.
pem_file string

Path to a PEM encoded certificate to use for client authentication.

This option is a deprecated alias for the "tlsCertificateKeyFile" URI option.

pem_pwd string

Passphrase for the PEM encoded certificate (if applicable).

This option is a deprecated alias for the "tlsCertificateKeyFilePassword" URI option.

weak_cert_validation boolean

Disables certificate validation if TRUE. Defaults to FALSE

This option is a deprecated alias for the "tlsAllowInvalidHostnames" URI option.

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

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.

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.

1.4.0

Added the "compressors", "retryWrites", and "zlibCompressionLevel" URI options.

1.3.0

The uriOptions argument now accepts "authMechanism" and "authMechanismProperties" options. Previously, these options were only supported in the uri argument.

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 driver no longer supports all SSL context options via the "context" driver option.

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/mydatabase");

?>

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/mydatabase");

?>

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


Create a new ClientEncryption object

  • « MongoDB\Driver\Manager::__construct
  • MongoDB\Driver\Manager::executeBulkWrite »
  • PHP Manual
  • MongoDB\Driver\Manager
  • Create a new ClientEncryption object

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.
kmsProviders array

A document containing the configuration for one or more KMS providers, which are used to encrypt data keys. Currently aws or localare supported and at least one must be specified.

The format for aws is as follows:

aws: {
    accessKeyId: <string>,
    secretAccessKey: <string>
}

The format for local is as follows:

local: {
    // The master key used to encrypt/decrypt data keys
    key: <96-byte MongoDB\BSON\Binary with subtype 0>
}

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

See Also

  • MongoDB\Driver\ClientEncryption
  • » Explicit (Manual) Client-Side Field Level Encryption in the MongoDB manual


Execute one or more write operations

  • « MongoDB\Driver\Manager::createClientEncryption
  • MongoDB\Driver\Manager::executeCommand »
  • PHP Manual
  • MongoDB\Driver\Manager
  • Execute one or more write operations

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 = array() ] ) : 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.

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
1.4.4 | MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the "session" option is used in combination with an unacknowledged write concern.
1.4.0 | The third parameter is now an options array. For backwards compatibility, this paramater will still accept a MongoDB\Driver\WriteConcern object.
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);

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


Execute a database command

  • « MongoDB\Driver\Manager::executeBulkWrite
  • MongoDB\Driver\Manager::executeQuery »
  • PHP Manual
  • MongoDB\Driver\Manager
  • Execute a database 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 = array() ] ) : MongoDB\Driver\Cursor

Selects a server according to the "readPreference" option and executes the command on that server. By default, the read preference from the MongoDB Connection URI will be used.

This method applies no special logic to the command. Although this method accepts "readConcern" and "writeConcern" options, which will be incorporated into the command document, those options will not default to corresponding values from the MongoDB Connection URI nor will the MongoDB server version be taken into account. 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
1.4.4 | MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the "session" option is used in combination with an unacknowledged write concern.
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.

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


Execute a database query

  • « MongoDB\Driver\Manager::executeCommand
  • MongoDB\Driver\Manager::executeReadCommand »
  • PHP Manual
  • MongoDB\Driver\Manager
  • Execute a database query

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 = array() ] ) : MongoDB\Driver\Cursor

Selects a server according to the "readPreference" option and executes the query on that server. By default, the read preference from the MongoDB Connection URI will be used.

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


Execute a database command that reads

  • « MongoDB\Driver\Manager::executeQuery
  • MongoDB\Driver\Manager::executeReadWriteCommand »
  • PHP Manual
  • MongoDB\Driver\Manager
  • Execute a database command that reads

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 = array() ] ) : MongoDB\Driver\Cursor

Selects a server according to the "readPreference" option and executes the command on that server. By default, the read preference from the MongoDB Connection URI will be used.

This method will apply logic that is specific to commands that read (e.g. » count) and take the MongoDB server version into account. The "readConcern" option will default to the corresponding value from the MongoDB 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


Execute a database command that reads and writes

  • « MongoDB\Driver\Manager::executeReadCommand
  • MongoDB\Driver\Manager::executeWriteCommand »
  • PHP Manual
  • MongoDB\Driver\Manager
  • Execute a database command that reads and writes

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 = array() ] ) : 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. » findAndModify) and take the MongoDB server version into account. The "readConcern" and "writeConcern" options will default to the corresponding values from the MongoDB 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
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


Execute a database command that writes

  • « MongoDB\Driver\Manager::executeReadWriteCommand
  • MongoDB\Driver\Manager::getReadConcern »
  • PHP Manual
  • MongoDB\Driver\Manager
  • Execute a database command that writes

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 = array() ] ) : 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) and take the MongoDB server version into account. The "writeConcern" option will default to the corresponding value from the MongoDB 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 commands.

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


Return the ReadConcern for the Manager

  • « MongoDB\Driver\Manager::executeWriteCommand
  • MongoDB\Driver\Manager::getReadPreference »
  • PHP Manual
  • MongoDB\Driver\Manager
  • Return the ReadConcern for the 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 ( void ) : 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


Return the ReadPreference for the Manager

  • « MongoDB\Driver\Manager::getReadConcern
  • MongoDB\Driver\Manager::getServers »
  • PHP Manual
  • MongoDB\Driver\Manager
  • Return the ReadPreference for the 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 ( void ) : 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


Return the servers to which this manager is connected

  • « MongoDB\Driver\Manager::getReadPreference
  • MongoDB\Driver\Manager::getWriteConcern »
  • PHP Manual
  • MongoDB\Driver\Manager
  • Return the servers to which this manager is connected

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 ( void ) : 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_is_master"]=>
    array(8) {
      ["ismaster"]=>
      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


Return the WriteConcern for the Manager

  • « MongoDB\Driver\Manager::getServers
  • MongoDB\Driver\Manager::selectServer »
  • PHP Manual
  • MongoDB\Driver\Manager
  • Return the WriteConcern for the Manager

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 ( void ) : 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


Select a server matching a read preference

  • « MongoDB\Driver\Manager::getWriteConcern
  • MongoDB\Driver\Manager::startSession »
  • PHP Manual
  • MongoDB\Driver\Manager
  • Select a server matching a read preference

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 ) : MongoDB\Driver\Server

Selects a MongoDB\Driver\Server matching readPreference. 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.

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.

See Also

  • MongoDB\Driver\Server
  • MongoDB\Driver\Manager::getServers() - Return the servers to which this manager is connected
  • » Server Selection Specification


Start a new client session for use with this client

  • « MongoDB\Driver\Manager::selectServer
  • MongoDB\Driver\Command »
  • PHP Manual
  • MongoDB\Driver\Manager
  • Start a new client session for use with this client

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

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

[]

Return Values

Returns a MongoDB\Driver\Session.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\RuntimeException if the session could not be created (e.g. libmongoc does not support crypto).

Changelog

Version | Description
1.6.0 | The "maxCommitTimeMS" option was added to "defaultTransactionOptions".
1.5.0 | The "defaultTransactionOptions" option was added.

See Also

  • MongoDB\Driver\Session
  • » Casual Consistency in the MongoDB manual


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 MongoDB\Driver\Command {
/* Methods */
final public __construct ( array|object $document [, array $commandOptions ] )
}

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

Table of Contents

  • MongoDB\Driver\Command::__construct — Create a new Command


Create a new Command

  • « MongoDB\Driver\Command
  • MongoDB\Driver\Query »
  • PHP Manual
  • MongoDB\Driver\Command
  • Create a new Command

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

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 integer

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


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 MongoDB\Driver\Query {
/* Methods */
final public __construct ( array|object $filter [, array $queryOptions ] )
}

Table of Contents

  • MongoDB\Driver\Query::__construct — Create a new Query


Create a new Query

  • « MongoDB\Driver\Query
  • MongoDB\Driver\BulkWrite »
  • PHP Manual
  • MongoDB\Driver\Query
  • Create a new Query

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

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
allowPartialResults boolean

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 | boolean | 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 integer

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 string

A comment to attach to the query to help interpret and trace query profile data.

Falls back to the deprecated "$comment" modifier if not specified.

exhaust boolean

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 boolean

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.

limit integer

The maximum number of documents to return. If unspecified, then defaults to no limit. A limit of 0 is equivalent to setting no limit.

A negative limit is will be interpreted as a positive limit with the "singleBatch" option set to TRUE. This behavior is supported for backwards compatibility, but should be considered deprecated.

max array|object

The exclusive upper bound for a specific index.

Falls back to the deprecated "$max" modifier if not specified.

maxAwaitTimeMS integer

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.

maxScan integer
Warning

This option is deprecated and should not be used.

Positive integer denoting the maximum number of documents or index keys to scan when executing the query.

Falls back to the deprecated "$maxScan" modifier if not specified.

maxTimeMS integer

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.

modifiers | array | » Meta operators modifying the output or behavior of a query. Use of these operators is deprecated in favor of named options.
noCursorTimeout | boolean | Prevents the server from timing out idle cursors after an inactivity period (10 minutes).
oplogReplay boolean

Internal use for replica sets. To use oplogReplay, you must include the following condition in the filter:

[ 'ts' => [ '$gte' => <timestamp> ] ]
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 driver 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 boolean

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 boolean

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 | boolean | Determines whether to close the cursor after the first batch. Defaults to FALSE.
skip | integer | Number of documents to skip. Defaults to 0.
slaveOk | boolean | Allow query of replica set secondaries
snapshot boolean
Warning

This option is deprecated and should not be used.

Prevents the cursor from returning a document more than once because of an intervening write operation.

Falls back to the deprecated "$snapshot" modifier if not specified.

sort array|object

The sort specification for the ordering of the results.

Falls back to the deprecated "$orderby" modifier if not specified.

tailable | boolean | Returns a tailable cursor for a capped collection.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

Changelog

Version | Description
1.5.0

The "maxScan" and "snapshot" options are deprecated.

1.3.0

Added the "maxAwaitTimeMS" option.

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 "slaveOk" option, which is obsolete. For queries using the legacy wire protocol OP_QUERY, the driver will set the slaveOk bit as needed in accordance with the » Server Selection Specification.

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::RP_PRIMARY);
$cursor = $manager->executeQuery('databaseName.collectionName', $query, $readPreference);

foreach($cursor as $document) {
    var_dump($document);
}

?>

See Also

  • MongoDB\Driver\Manager::executeQuery() - Execute a database query
  • MongoDB\Driver\Cursor


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 MongoDB\Driver\BulkWrite implements Countable {
/* Methods */
public __construct ([ array $options ] )
public count ( void ) : int
public delete ( array|object $filter [, array $deleteOptions ] ) : void
public insert ( array|object $document ) : mixed
public update ( array|object $filter , array|object $newObj [, array $updateOptions ] ) : 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);
} 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

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


Create a new BulkWrite

  • « MongoDB\Driver\BulkWrite
  • MongoDB\Driver\BulkWrite::count »
  • PHP Manual
  • MongoDB\Driver\BulkWrite
  • Create a new BulkWrite

MongoDB\Driver\BulkWrite::__construct

(mongodb >=1.0.0)

MongoDB\Driver\BulkWrite::__construct — Create a new BulkWrite

Description

public MongoDB\Driver\BulkWrite::__construct ([ array $options ] )

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 boolean

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
ordered | boolean | 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
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);
} 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


Count number of write operations in the bulk

  • « MongoDB\Driver\BulkWrite::__construct
  • MongoDB\Driver\BulkWrite::delete »
  • PHP Manual
  • MongoDB\Driver\BulkWrite
  • Count number of write operations in the bulk

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 ( void ) : 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
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)


Add a delete operation to the bulk

  • « MongoDB\Driver\BulkWrite::count
  • MongoDB\Driver\BulkWrite::insert »
  • PHP Manual
  • MongoDB\Driver\BulkWrite
  • Add a delete operation to the bulk

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

limit | boolean | 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
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


Add an insert operation to the bulk

  • « MongoDB\Driver\BulkWrite::delete
  • MongoDB\Driver\BulkWrite::update »
  • PHP Manual
  • MongoDB\Driver\BulkWrite
  • Add an insert operation to the bulk

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

$document1 = ['title' => 'one'];
$document2 = ['_id' => 'custom ID', 'title' => 'two'];
$document3 = ['_id' => new MongoDB\BSON\ObjectId, 'title' => 'three'];

$_id1 = $bulk->insert($document1);
$_id2 = $bulk->insert($document2);
$_id3 = $bulk->insert($document3);

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) "54d51146bd21b91405401d92"
}
NULL
NULL

See Also

  • MongoDB\Driver\Manager::executeBulkWrite() - Execute one or more write operations
  • MongoDB\Driver\WriteResult
  • MongoDB\BSON\ObjectId
  • MongoDB\BSON\Persistable


Add an update operation to the bulk

  • « MongoDB\Driver\BulkWrite::insert
  • MongoDB\Driver\Session »
  • PHP Manual
  • MongoDB\Driver\BulkWrite
  • Add an update operation to the bulk

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

multi | boolean | 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
upsert | boolean | 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
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.
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.
1.4.0 | Added the "arrayFilters" option.
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


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 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 ) : void
final public advanceClusterTime ( array|object $clusterTime ) : void
final public advanceOperationTime ( MongoDB\BSON\TimestampInterface $operationTime ) : void
final public commitTransaction ( void ) : void
final private __construct ( void )
final public endSession ( void ) : void
final public getClusterTime ( void ) : object|null
final public getLogicalSessionId ( void ) : object
final public getOperationTime ( void ) : MongoDB\BSON\Timestamp|null
final public getServer ( void ) : MongoDB\Driver\Server|null
final public getTransactionOptions ( void ) : array|null
final public getTransactionState ( void ) : string
final public isInTransaction ( void ) : boolean
final public startTransaction ([ array $options ] ) : 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.

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::isInTransaction — Returns whether a multi-document transaction is in progress
  • MongoDB\Driver\Session::startTransaction — Starts a transaction


Aborts a transaction

  • « MongoDB\Driver\Session
  • MongoDB\Driver\Session::advanceClusterTime »
  • PHP Manual
  • MongoDB\Driver\Session
  • Aborts a transaction

MongoDB\Driver\Session::abortTransaction

(mongodb >=1.5.0)

MongoDB\Driver\Session::abortTransaction — Aborts a transaction

Description

final public MongoDB\Driver\Session::abortTransaction ( void ) : 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


Advances the cluster time for this session

  • « MongoDB\Driver\Session::abortTransaction
  • MongoDB\Driver\Session::advanceOperationTime »
  • PHP Manual
  • MongoDB\Driver\Session
  • Advances the cluster time for this session

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


Advances the operation time for this session

  • « MongoDB\Driver\Session::advanceClusterTime
  • MongoDB\Driver\Session::commitTransaction »
  • PHP Manual
  • MongoDB\Driver\Session
  • Advances the operation 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


Commits a transaction

  • « MongoDB\Driver\Session::advanceOperationTime
  • MongoDB\Driver\Session::__construct »
  • PHP Manual
  • MongoDB\Driver\Session
  • Commits a transaction

MongoDB\Driver\Session::commitTransaction

(mongodb >=1.5.0)

MongoDB\Driver\Session::commitTransaction — Commits a transaction

Description

final public MongoDB\Driver\Session::commitTransaction ( void ) : 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 "UnUnknownTransactionCommitResult" value, it is safe to re-try the whole transaction. In newer versions of the driver, 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


Create a new Session (not used)

  • « MongoDB\Driver\Session::commitTransaction
  • MongoDB\Driver\Session::endSession »
  • PHP Manual
  • MongoDB\Driver\Session
  • Create a new Session (not used)

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

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


Terminates a session

  • « MongoDB\Driver\Session::__construct
  • MongoDB\Driver\Session::getClusterTime »
  • PHP Manual
  • MongoDB\Driver\Session
  • Terminates a session

MongoDB\Driver\Session::endSession

(mongodb >=1.5.0)

MongoDB\Driver\Session::endSession — Terminates a session

Description

final public MongoDB\Driver\Session::endSession ( void ) : 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


Returns the cluster time for this session

  • « MongoDB\Driver\Session::endSession
  • MongoDB\Driver\Session::getLogicalSessionId »
  • PHP Manual
  • MongoDB\Driver\Session
  • Returns the cluster time for this session

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 ( void ) : object|null

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


Returns the logical session ID for this session

  • « MongoDB\Driver\Session::getClusterTime
  • MongoDB\Driver\Session::getOperationTime »
  • PHP Manual
  • MongoDB\Driver\Session
  • Returns the logical session ID 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 ( void ) : 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.


Returns the operation time for this session

  • « MongoDB\Driver\Session::getLogicalSessionId
  • MongoDB\Driver\Session::getServer »
  • PHP Manual
  • MongoDB\Driver\Session
  • Returns the operation time for this session

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 ( void ) : MongoDB\BSON\Timestamp|null

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


Returns the server to which this session is pinned

  • « MongoDB\Driver\Session::getOperationTime
  • MongoDB\Driver\Session::getTransactionOptions »
  • PHP Manual
  • MongoDB\Driver\Session
  • Returns the server to which this session is pinned

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 ( void ) : MongoDB\Driver\Server|null

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.


Returns options for the currently running transaction

  • « MongoDB\Driver\Session::getServer
  • MongoDB\Driver\Session::getTransactionState »
  • PHP Manual
  • MongoDB\Driver\Session
  • Returns options for the currently running transaction

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 ( void ) : array|null

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


Returns the current transaction state for this session

  • « MongoDB\Driver\Session::getTransactionOptions
  • MongoDB\Driver\Session::isInTransaction »
  • PHP Manual
  • MongoDB\Driver\Session
  • 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 ( void ) : 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


Returns whether a multi-document transaction is in progress

  • « MongoDB\Driver\Session::getTransactionState
  • MongoDB\Driver\Session::startTransaction »
  • PHP Manual
  • MongoDB\Driver\Session
  • Returns whether a multi-document transaction is in progress

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 ( void ) : boolean

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


Starts a transaction

  • « MongoDB\Driver\Session::isInTransaction
  • MongoDB\Driver\ClientEncryption »
  • PHP Manual
  • MongoDB\Driver\Session
  • Starts a transaction

MongoDB\Driver\Session::startTransaction

(mongodb >=1.5.0)

MongoDB\Driver\Session::startTransaction — Starts a transaction

Description

final public MongoDB\Driver\Session::startTransaction ([ array $options ] ) : 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
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


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 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 ;
/* Methods */
final public createDataKey ( string $kmsProvider [, array $options ] ) : MongoDB\BSON\Binary
final public decrypt ( MongoDB\BSON\Binary $value ) : mixed
final public encrypt ( mixed $value [, array $options ] ) : MongoDB\BSON\Binary
}

Predefined Constants

MongoDB\Driver\ClientEncryption::AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC

Uses randomized encryption.

MongoDB\Driver\ClientEncryption::AEAD_AES_256_CBC_HMAC_SHA_512_RANDOM

Uses deterministic (queryable) encryption.

See Also

  • MongoDB\Driver\Manager::createClientEncryption()

Table of Contents

  • MongoDB\Driver\ClientEncryption::createDataKey — Create a new encryption data key
  • MongoDB\Driver\ClientEncryption::decrypt — Decrypt a value
  • MongoDB\Driver\ClientEncryption::encrypt — Encrypt a value


Create a new encryption data key

  • « MongoDB\Driver\ClientEncryption
  • MongoDB\Driver\ClientEncryption::decrypt »
  • PHP Manual
  • MongoDB\Driver\ClientEncryption
  • Create a new encryption data key

MongoDB\Driver\ClientEncryption::createDataKey

(mongodb >=1.7.0)

MongoDB\Driver\ClientEncryption::createDataKey — Create a new encryption data key

Description

final public MongoDB\Driver\ClientEncryption::createDataKey ( string $kmsProvider [, array $options ] ) : MongoDB\BSON\Binary

Creates a new key document and inserts it into the key vault collection.

Parameters

kmsProvider

The KMS provider ("local" or "aws") that will be used to encrypt the new encryption key.

options

Data key options
Option Type Description
masterKey array

The masterKey identifies a KMS-specific key used to encrypt the new data key. If the kmsProvider is aws it is required and has the following fields:

AWS masterKey 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.

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.

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\EncryptionException if an error occurs while creating the data key


Decrypt a value

  • « MongoDB\Driver\ClientEncryption::createDataKey
  • MongoDB\Driver\ClientEncryption::encrypt »
  • PHP Manual
  • MongoDB\Driver\ClientEncryption
  • Decrypt a value

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


Encrypt a value

  • « MongoDB\Driver\ClientEncryption::decrypt
  • MongoDB\Driver\WriteConcern »
  • PHP Manual
  • MongoDB\Driver\ClientEncryption
  • Encrypt a value

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 ] ) : 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. Use the constants defined in MongoDB\Driver\ClientEncryption.

keyAltName string

Identifies a key vault collection document by keyAltName.

keyId MongoDB\BSON\Binary

Identifies a data key by _id. The value is a UUID (binary subtype 4).

Note: Exactly one of keyId and keyAltName must be provided. The algorithm option is required.

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

See Also

  • MongoDB\Driver\ClientEncryption::decrypt() - Decrypt a value


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 MongoDB\Driver\WriteConcern implements MongoDB\BSON\Serializable , Serializable {
/* Constants */
const string MAJORITY = "majority" ;
/* Methods */
final public bsonSerialize ( void ) : object
final public __construct ( string|integer $w [, int $wtimeout [, bool $journal ]] )
final public getJournal ( void ) : boolean|null
final public getW ( void ) : string|integer|null
final public getWtimeout ( void ) : int|MongoDB\BSON\Int64
final public isDefault ( void ) : bool
final public serialize ( void ) : string
final public unserialize ( string $serialized ) : void
}

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
1.7.0 | Implements Serializable.
1.2.0 | Implements MongoDB\BSON\Serializable.

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
  • MongoDB\Driver\WriteConcern::serialize — Serialize a WriteConcern
  • MongoDB\Driver\WriteConcern::unserialize — Unserialize a WriteConcern


Returns an object for BSON serialization

  • « MongoDB\Driver\WriteConcern
  • MongoDB\Driver\WriteConcern::__construct »
  • PHP Manual
  • MongoDB\Driver\WriteConcern
  • Returns an object for BSON serialization

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 ( void ) : object

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\toJSON(MongoDB\BSON\fromPHP($wc));

?>

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\toJSON(MongoDB\BSON\fromPHP($wc));

?>

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


Create a new WriteConcern

  • « MongoDB\Driver\WriteConcern::bsonSerialize
  • MongoDB\Driver\WriteConcern::getJournal »
  • PHP Manual
  • MongoDB\Driver\WriteConcern
  • Create a new WriteConcern

MongoDB\Driver\WriteConcern::__construct

(mongodb >=1.0.0)

MongoDB\Driver\WriteConcern::__construct — Create a new WriteConcern

Description

final public MongoDB\Driver\WriteConcern::__construct ( string|integer $w [, int $wtimeout [, bool $journal ]] )

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


Returns the WriteConcern's "journal" option

  • « MongoDB\Driver\WriteConcern::__construct
  • MongoDB\Driver\WriteConcern::getW »
  • PHP Manual
  • MongoDB\Driver\WriteConcern
  • Returns the WriteConcern's "journal" option

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 ( void ) : boolean|null

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


Returns the WriteConcern's "w" option

  • « MongoDB\Driver\WriteConcern::getJournal
  • MongoDB\Driver\WriteConcern::getWtimeout »
  • PHP Manual
  • MongoDB\Driver\WriteConcern
  • Returns the WriteConcern's "w" option

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 ( void ) : string|integer|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


Returns the WriteConcern's "wtimeout" option

  • « MongoDB\Driver\WriteConcern::getW
  • MongoDB\Driver\WriteConcern::isDefault »
  • PHP Manual
  • MongoDB\Driver\WriteConcern
  • Returns the WriteConcern's "wtimeout" option

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 ( void ) : int|MongoDB\BSON\Int64

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
1.7.0 | On 32-bit systems, this method will return a MongoDB\BSON\Int64 instance if the WriteConcern object was created with a wTimeout that exceeds the 32-bit range. On 64-bit systems, this method will always return an integer value.

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


Checks if this is the default write concern

  • « MongoDB\Driver\WriteConcern::getWtimeout
  • MongoDB\Driver\WriteConcern::serialize »
  • PHP Manual
  • MongoDB\Driver\WriteConcern
  • Checks if this is the default write concern

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 ( void ) : 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


Serialize a WriteConcern

  • « MongoDB\Driver\WriteConcern::isDefault
  • MongoDB\Driver\WriteConcern::unserialize »
  • PHP Manual
  • MongoDB\Driver\WriteConcern
  • Serialize a WriteConcern

MongoDB\Driver\WriteConcern::serialize

(mongodb >=1.7.0)

MongoDB\Driver\WriteConcern::serialize — Serialize a WriteConcern

Description

final public MongoDB\Driver\WriteConcern::serialize ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns the serialized representation of the MongoDB\Driver\WriteConcern.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

See Also

  • MongoDB\Driver\WriteConcern::unserialize() - Unserialize a WriteConcern
  • serialize() - Generates a storable representation of a value
  • Serializing Objects


Unserialize a WriteConcern

  • « MongoDB\Driver\WriteConcern::serialize
  • MongoDB\Driver\ReadPreference »
  • PHP Manual
  • MongoDB\Driver\WriteConcern
  • Unserialize a WriteConcern

MongoDB\Driver\WriteConcern::unserialize

(mongodb >=1.7.0)

MongoDB\Driver\WriteConcern::unserialize — Unserialize a WriteConcern

Description

final public MongoDB\Driver\WriteConcern::unserialize ( string $serialized ) : void

Parameters

serialized

The serialized MongoDB\Driver\WriteConcern.

Return Values

Returns the unserialized MongoDB\Driver\WriteConcern.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

See Also

  • MongoDB\Driver\WriteConcern::serialize() - Serialize a WriteConcern
  • unserialize() - Creates a PHP value from a stored representation
  • Serializing Objects


The MongoDB\Driver\ReadPreference class

(mongodb >=1.0.0)

Introduction

Class synopsis

final MongoDB\Driver\ReadPreference implements MongoDB\BSON\Serializable , Serializable {
/* Constants */
const integer RP_PRIMARY = 1 ;
const integer RP_PRIMARY_PREFERRED = 5 ;
const integer RP_SECONDARY = 2 ;
const integer RP_SECONDARY_PREFERRED = 6 ;
const integer RP_NEAREST = 10 ;
const string PRIMARY = primary ;
const string PRIMARY_PREFERRED = primaryPreferred ;
const string SECONDARY = secondary ;
const string SECONDARY_PREFERRED = secondaryPreferred ;
const string NEAREST = nearest ;
const integer NO_MAX_STALENESS = -1 ;
const integer SMALLEST_MAX_STALENESS_SECONDS = 90 ;
/* Methods */
final public bsonSerialize ( void ) : object
final public __construct ( string|integer $mode [, array $tagSets = NULL [, array $options = array() ]] )
final public getMaxStalenessSeconds ( void ) : int
final public getMode ( void ) : int
final public getModeString ( void ) : string
final public getTagSets ( void ) : array
final public serialize ( void ) : string
final public unserialize ( string $serialized ) : void
}

Predefined Constants

MongoDB\Driver\ReadPreference::RP_PRIMARY

All operations read from the current replica set primary. This is the default read preference for MongoDB.

MongoDB\Driver\ReadPreference::RP_PRIMARY_PREFERRED

In most situations, operations read from the primary but if it is unavailable, operations read from secondary members.

MongoDB\Driver\ReadPreference::RP_SECONDARY

All operations read from the secondary members of the replica set.

MongoDB\Driver\ReadPreference::RP_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::RP_NEAREST

Operations read from member of the replica set with the least network latency, irrespective of the member's type.

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
1.7.0 | Added the MongoDB\Driver\ReadPreference::PRIMARY, MongoDB\Driver\ReadPreference::PRIMARY_PREFERRED, MongoDB\Driver\ReadPreference::SECONDARY, MongoDB\Driver\ReadPreference::SECONDARY_PREFERRED, MongoDB\Driver\ReadPreference::NEAREST constants. Implements Serializable.
1.2.0 | Added the MongoDB\Driver\ReadPreference::NO_MAX_STALENESS and MongoDB\Driver\ReadPreference::SMALLEST_MAX_STALENESS_SECONDS constants. Implements MongoDB\BSON\Serializable.

Table of Contents

  • MongoDB\Driver\ReadPreference::bsonSerialize — Returns an object for BSON serialization
  • MongoDB\Driver\ReadPreference::__construct — Create a new ReadPreference
  • 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 as a string
  • MongoDB\Driver\ReadPreference::getTagSets — Returns the ReadPreference's "tagSets" option
  • MongoDB\Driver\ReadPreference::serialize — Serialize a ReadPreference
  • MongoDB\Driver\ReadPreference::unserialize — Unserialize a ReadPreference


Returns an object for BSON serialization

  • « MongoDB\Driver\ReadPreference
  • MongoDB\Driver\ReadPreference::__construct »
  • PHP Manual
  • MongoDB\Driver\ReadPreference
  • Returns an object for BSON serialization

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 ( void ) : object

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::RP_PRIMARY);
var_dump($rp->bsonSerialize());

echo "\n", MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($rp));

?>

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::RP_SECONDARY,
    [
        ['dc' => 'ny'],
        ['dc' => 'sf', 'use' => 'reporting'],
        []
    ]
);
var_dump($rp->bsonSerialize());

echo "\n", MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($rp));

?>

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::RP_SECONDARY,
    null,
    ['maxStalenessSeconds' => 120]
);
var_dump($rp->bsonSerialize());

echo "\n", MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($rp));

?>

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


Create a new ReadPreference

  • « MongoDB\Driver\ReadPreference::bsonSerialize
  • MongoDB\Driver\ReadPreference::getMaxStalenessSeconds »
  • PHP Manual
  • MongoDB\Driver\ReadPreference
  • Create a new ReadPreference

MongoDB\Driver\ReadPreference::__construct

(mongodb >=1.0.0)

MongoDB\Driver\ReadPreference::__construct — Create a new ReadPreference

Description

final public MongoDB\Driver\ReadPreference::__construct ( string|integer $mode [, array $tagSets = NULL [, array $options = array() ]] )

Constructs a new MongoDB\Driver\ReadPreference, which is an immutable value object.

Parameters

mode

Read preference mode
Value Description
MongoDB\Driver\ReadPreference::RP_PRIMARY or "primary"

All operations read from the current replica set primary. This is the default read preference for MongoDB.

MongoDB\Driver\ReadPreference::RP_PRIMARY_PREFERRED or "primaryPreferred"

In most situations, operations read from the primary but if it is unavailable, operations read from secondary members.

MongoDB\Driver\ReadPreference::RP_SECONDARY or "secondary"

All operations read from the secondary members of the replica set.

MongoDB\Driver\ReadPreference::RP_SECONDARY_PREFERRED or "secondaryPreferred"

In most situations, operations read from secondary members but if no secondary members are available, operations read from the primary.

MongoDB\Driver\ReadPreference::RP_NEAREST or "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 MongoDB\Driver\ReadPreference::RP_PRIMARY mode and, in general, only apply when selecting a secondary member of a set for a read operation. However, the MongoDB\Driver\ReadPreference::RP_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
maxStalenessSeconds integer

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 MongoDB\Driver\ReadPreference::RP_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
1.3.0 | The mode argument now accepts a string value, which is consistent with the "readPreference" URI option for MongoDB\Driver\Manager::__construct().
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::RP_SECONDARY_PREFERRED));

/* Prefer a node in the New York data center with lowest latency. */
var_dump(new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_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::RP_SECONDARY, null, ['maxStalenessSeconds' => 120]));

?>

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

See Also

  • » Read Preference reference


Returns the ReadPreference's "maxStalenessSeconds" option

  • « MongoDB\Driver\ReadPreference::__construct
  • MongoDB\Driver\ReadPreference::getMode »
  • PHP Manual
  • MongoDB\Driver\ReadPreference
  • Returns the ReadPreference's "maxStalenessSeconds" option

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 ( void ) : 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::RP_SECONDARY);
var_dump($rp->getMaxStalenessSeconds());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY, null, [
    'maxStalenessSeconds' => MongoDB\Driver\ReadPreference::NO_MAX_STALENESS,
]);
var_dump($rp->getMaxStalenessSeconds());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY, null, [
    'maxStalenessSeconds' => MongoDB\Driver\ReadPreference::SMALLEST_MAX_STALENESS_SECONDS,
]);
var_dump($rp->getMaxStalenessSeconds());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_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


Returns the ReadPreference's "mode" option

  • « MongoDB\Driver\ReadPreference::getMaxStalenessSeconds
  • MongoDB\Driver\ReadPreference::getModeString »
  • PHP Manual
  • MongoDB\Driver\ReadPreference
  • Returns the ReadPreference's "mode" option

MongoDB\Driver\ReadPreference::getMode

(mongodb >=1.0.0)

MongoDB\Driver\ReadPreference::getMode — Returns the ReadPreference's "mode" option

Description

final public MongoDB\Driver\ReadPreference::getMode ( void ) : 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.

Examples

Example #1 MongoDB\Driver\ReadPreference::getMode() example

<?php

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
var_dump($rp->getMode());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY_PREFERRED);
var_dump($rp->getMode());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY);
var_dump($rp->getMode());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY_PREFERRED);
var_dump($rp->getMode());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_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 as a string
  • » Read Preference reference


Returns the ReadPreference's "mode" option as a string

  • « MongoDB\Driver\ReadPreference::getMode
  • MongoDB\Driver\ReadPreference::getTagSets »
  • PHP Manual
  • MongoDB\Driver\ReadPreference
  • Returns the ReadPreference's "mode" option as a string

MongoDB\Driver\ReadPreference::getModeString

(mongodb >=1.7.0)

MongoDB\Driver\ReadPreference::getModeString — Returns the ReadPreference's "mode" option as a string

Description

final public MongoDB\Driver\ReadPreference::getModeString ( void ) : 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


Returns the ReadPreference's "tagSets" option

  • « MongoDB\Driver\ReadPreference::getModeString
  • MongoDB\Driver\ReadPreference::serialize »
  • PHP Manual
  • MongoDB\Driver\ReadPreference
  • Returns the ReadPreference's "tagSets" option

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 ( void ) : 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::RP_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


Serialize a ReadPreference

  • « MongoDB\Driver\ReadPreference::getTagSets
  • MongoDB\Driver\ReadPreference::unserialize »
  • PHP Manual
  • MongoDB\Driver\ReadPreference
  • Serialize a ReadPreference

MongoDB\Driver\ReadPreference::serialize

(mongodb >=1.7.0)

MongoDB\Driver\ReadPreference::serialize — Serialize a ReadPreference

Description

final public MongoDB\Driver\ReadPreference::serialize ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns the serialized representation of the MongoDB\Driver\ReadPreference.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

See Also

  • MongoDB\Driver\ReadPreference::unserialize() - Unserialize a ReadPreference
  • serialize() - Generates a storable representation of a value
  • Serializing Objects


Unserialize a ReadPreference

  • « MongoDB\Driver\ReadPreference::serialize
  • MongoDB\Driver\ReadConcern »
  • PHP Manual
  • MongoDB\Driver\ReadPreference
  • Unserialize a ReadPreference

MongoDB\Driver\ReadPreference::unserialize

(mongodb >=1.7.0)

MongoDB\Driver\ReadPreference::unserialize — Unserialize a ReadPreference

Description

final public MongoDB\Driver\ReadPreference::unserialize ( string $serialized ) : void

Parameters

serialized

The serialized MongoDB\Driver\ReadPreference.

Return Values

Returns the unserialized MongoDB\Driver\ReadPreference.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

See Also

  • MongoDB\Driver\ReadPreference::serialize() - Serialize a ReadPreference
  • unserialize() - Creates a PHP value from a stored representation
  • Serializing Objects


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 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" ;
/* Methods */
final public bsonSerialize ( void ) : object
final public __construct ([ string $level ] )
final public getLevel ( void ) : string|null
final public isDefault ( void ) : bool
final public serialize ( void ) : string
final public unserialize ( string $serialized ) : void
}

Predefined Constants

MongoDB\Driver\ReadConcern::AVAILABLE

Default for reads against secondaries when afterClusterTimeand 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.

Changelog

Version | Description
1.7.0 | Implements Serializable.
1.4.0 | Added the MongoDB\Driver\ReadConcern::AVAILABLE constant.
1.2.0 | Added the MongoDB\Driver\ReadConcern::LINEARIZABLE constant. Implements MongoDB\BSON\Serializable.

See Also

  • » 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
  • MongoDB\Driver\ReadConcern::serialize — Serialize a ReadConcern
  • MongoDB\Driver\ReadConcern::unserialize — Unserialize a ReadConcern


Returns an object for BSON serialization

  • « MongoDB\Driver\ReadConcern
  • MongoDB\Driver\ReadConcern::__construct »
  • PHP Manual
  • MongoDB\Driver\ReadConcern
  • Returns an object for BSON serialization

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 ( void ) : object

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\toJSON(MongoDB\BSON\fromPHP($rc));

?>

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\toJSON(MongoDB\BSON\fromPHP($rc));

?>

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


Create a new ReadConcern

  • « MongoDB\Driver\ReadConcern::bsonSerialize
  • MongoDB\Driver\ReadConcern::getLevel »
  • PHP Manual
  • MongoDB\Driver\ReadConcern
  • Create a new ReadConcern

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

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


Returns the ReadConcern's "level" option

  • « MongoDB\Driver\ReadConcern::__construct
  • MongoDB\Driver\ReadConcern::isDefault »
  • PHP Manual
  • MongoDB\Driver\ReadConcern
  • Returns the ReadConcern's "level" option

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 ( void ) : string|null

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


Checks if this is the default read concern

  • « MongoDB\Driver\ReadConcern::getLevel
  • MongoDB\Driver\ReadConcern::serialize »
  • PHP Manual
  • MongoDB\Driver\ReadConcern
  • Checks if this is the default read concern

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 ( void ) : 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


Serialize a ReadConcern

  • « MongoDB\Driver\ReadConcern::isDefault
  • MongoDB\Driver\ReadConcern::unserialize »
  • PHP Manual
  • MongoDB\Driver\ReadConcern
  • Serialize a ReadConcern

MongoDB\Driver\ReadConcern::serialize

(mongodb >=1.7.0)

MongoDB\Driver\ReadConcern::serialize — Serialize a ReadConcern

Description

final public MongoDB\Driver\ReadConcern::serialize ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns the serialized representation of the MongoDB\Driver\ReadConcern.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

See Also

  • MongoDB\Driver\ReadConcern::unserialize() - Unserialize a ReadConcern
  • serialize() - Generates a storable representation of a value
  • Serializing Objects


Unserialize a ReadConcern

  • « MongoDB\Driver\ReadConcern::serialize
  • MongoDB\Driver\Cursor »
  • PHP Manual
  • MongoDB\Driver\ReadConcern
  • Unserialize a ReadConcern

MongoDB\Driver\ReadConcern::unserialize

(mongodb >=1.7.0)

MongoDB\Driver\ReadConcern::unserialize — Unserialize a ReadConcern

Description

final public MongoDB\Driver\ReadConcern::unserialize ( string $serialized ) : void

Parameters

serialized

The serialized MongoDB\Driver\ReadConcern.

Return Values

Returns the unserialized MongoDB\Driver\ReadConcern.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

See Also

  • MongoDB\Driver\ReadConcern::serialize() - Serialize a ReadConcern
  • unserialize() - Creates a PHP value from a stored representation
  • Serializing Objects


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 MongoDB\Driver\Cursor implements MongoDB\Driver\CursorInterface {
/* Methods */
final private __construct ( void )
final public getId ( void ) : MongoDB\Driver\CursorId
final public getServer ( void ) : MongoDB\Driver\Server
final public isDead ( void ) : bool
final public setTypeMap ( array $typemap ) : void
final public toArray ( void ) : array
}

Changelog

Version | Description
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.

Table of Contents

  • MongoDB\Driver\Cursor::__construct — Create a new Cursor (not used)
  • 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::setTypeMap — Sets a type map to use for BSON unserialization
  • MongoDB\Driver\Cursor::toArray — Returns an array containing all results for this cursor


Create a new Cursor (not used)

  • « MongoDB\Driver\Cursor
  • MongoDB\Driver\Cursor::getId »
  • PHP Manual
  • MongoDB\Driver\Cursor
  • Create a new Cursor (not used)

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

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


Returns the ID for this cursor

  • « MongoDB\Driver\Cursor::__construct
  • MongoDB\Driver\Cursor::getServer »
  • PHP Manual
  • MongoDB\Driver\Cursor
  • Returns the ID for this cursor

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 ( void ) : MongoDB\Driver\CursorId

Returns the MongoDB\Driver\CursorId associated with this cursor. A cursor ID uniquely identifies the cursor on the server.

Parameters

This function has no parameters.

Return Values

Returns the MongoDB\Driver\CursorId for this cursor.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

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

?>

The above example will output something similar to:

object(MongoDB\Driver\CursorId)#5 (1) {
  ["id"]=>
  int(94810124093)
}

See Also

  • MongoDB\Driver\CursorId
  • MongoDB\Driver\CursorId::__toString() - String representation of the cursor ID


Returns the server associated with this cursor

  • « MongoDB\Driver\Cursor::getId
  • MongoDB\Driver\Cursor::isDead »
  • PHP Manual
  • MongoDB\Driver\Cursor
  • Returns the server associated with this cursor

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 ( void ) : 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_is_master"]=>
  array(8) {
    ["ismaster"]=>
    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


Checks if the cursor is exhausted or may have additional results

  • « MongoDB\Driver\Cursor::getServer
  • MongoDB\Driver\Cursor::setTypeMap »
  • PHP Manual
  • MongoDB\Driver\Cursor
  • Checks if the cursor is exhausted or may have additional results

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 ( void ) : 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


Sets a type map to use for BSON unserialization

  • « MongoDB\Driver\Cursor::isDead
  • MongoDB\Driver\Cursor::toArray »
  • PHP Manual
  • MongoDB\Driver\Cursor
  • Sets a type map to use for BSON unserialization

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


Returns an array containing all results for this cursor

  • « MongoDB\Driver\Cursor::setTypeMap
  • MongoDB\Driver\CursorId »
  • PHP Manual
  • MongoDB\Driver\Cursor
  • Returns an array containing all results for this cursor

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 ( void ) : 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


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

Class synopsis

final MongoDB\Driver\CursorId implements Serializable {
/* Methods */
final private __construct ( void )
final public serialize ( void ) : string
final public __toString ( void ) : string
final public unserialize ( string $serialized ) : void
}

Changelog

Version | Description
1.7.0 | Implements Serializable.

Table of Contents

  • MongoDB\Driver\CursorId::__construct — Create a new CursorId (not used)
  • MongoDB\Driver\CursorId::serialize — Serialize a CursorId
  • MongoDB\Driver\CursorId::__toString — String representation of the cursor ID
  • MongoDB\Driver\CursorId::unserialize — Unserialize a CursorId


Create a new CursorId (not used)

  • « MongoDB\Driver\CursorId
  • MongoDB\Driver\CursorId::serialize »
  • PHP Manual
  • MongoDB\Driver\CursorId
  • Create a new CursorId (not used)

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

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


Serialize a CursorId

  • « MongoDB\Driver\CursorId::__construct
  • MongoDB\Driver\CursorId::__toString »
  • PHP Manual
  • MongoDB\Driver\CursorId
  • Serialize a CursorId

MongoDB\Driver\CursorId::serialize

(mongodb >=1.7.0)

MongoDB\Driver\CursorId::serialize — Serialize a CursorId

Description

final public MongoDB\Driver\CursorId::serialize ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns the serialized representation of the MongoDB\Driver\CursorId.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

See Also

  • MongoDB\Driver\CursorId::unserialize() - Unserialize a CursorId
  • serialize() - Generates a storable representation of a value
  • Serializing Objects


String representation of the cursor ID

  • « MongoDB\Driver\CursorId::serialize
  • MongoDB\Driver\CursorId::unserialize »
  • PHP Manual
  • MongoDB\Driver\CursorId
  • String representation of the cursor ID

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 ( void ) : 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


Unserialize a CursorId

  • « MongoDB\Driver\CursorId::__toString
  • MongoDB\Driver\CursorInterface »
  • PHP Manual
  • MongoDB\Driver\CursorId
  • Unserialize a CursorId

MongoDB\Driver\CursorId::unserialize

(mongodb >=1.7.0)

MongoDB\Driver\CursorId::unserialize — Unserialize a CursorId

Description

final public MongoDB\Driver\CursorId::unserialize ( string $serialized ) : void

Parameters

serialized

The serialized MongoDB\Driver\CursorId.

Return Values

Returns the unserialized MongoDB\Driver\CursorId.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

See Also

  • MongoDB\Driver\CursorId::serialize() - Serialize a CursorId
  • unserialize() - Creates a PHP value from a stored representation
  • Serializing Objects


The MongoDB\Driver\CursorInterface interface

(mongodb >=1.6.0)

Introduction

This interface is implemented by MongoDB\Driver\Cursor but may also be used for type-hinting and userland classes.

Class synopsis

MongoDB\Driver\CursorInterface implements Traversable {
/* Methods */
abstract public getId ( void ) : MongoDB\Driver\CursorId
abstract public getServer ( void ) : MongoDB\Driver\Server
abstract public isDead ( void ) : bool
abstract public setTypeMap ( array $typemap ) : void
abstract public toArray ( void ) : array
}

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


Returns the ID for this cursor

  • « MongoDB\Driver\CursorInterface
  • MongoDB\Driver\CursorInterface::getServer »
  • PHP Manual
  • MongoDB\Driver\CursorInterface
  • Returns the ID for this cursor

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 ( void ) : MongoDB\Driver\CursorId

Returns the MongoDB\Driver\CursorId associated with this cursor. A cursor ID uniquely identifies the cursor on the server.

Parameters

This function has no parameters.

Return Values

Returns the MongoDB\Driver\CursorId for this cursor.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

See Also

  • MongoDB\Driver\Cursor::getId() - Returns the ID for this cursor
  • MongoDB\Driver\CursorId
  • MongoDB\Driver\CursorId::__toString() - String representation of the cursor ID


Returns the server associated with this cursor

  • « MongoDB\Driver\CursorInterface::getId
  • MongoDB\Driver\CursorInterface::isDead »
  • PHP Manual
  • MongoDB\Driver\CursorInterface
  • Returns the server associated with this cursor

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 ( void ) : 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


Checks if the cursor may have additional results

  • « MongoDB\Driver\CursorInterface::getServer
  • MongoDB\Driver\CursorInterface::setTypeMap »
  • PHP Manual
  • MongoDB\Driver\CursorInterface
  • Checks if the cursor may have additional results

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 ( void ) : 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


Sets a type map to use for BSON unserialization

  • « MongoDB\Driver\CursorInterface::isDead
  • MongoDB\Driver\CursorInterface::toArray »
  • PHP Manual
  • MongoDB\Driver\CursorInterface
  • Sets a type map to use for BSON unserialization

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


Returns an array containing all results for this cursor

  • « MongoDB\Driver\CursorInterface::setTypeMap
  • MongoDB\Driver\Server »
  • PHP Manual
  • MongoDB\Driver\CursorInterface
  • Returns an array containing all results for this cursor

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 ( void ) : 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


The MongoDB\Driver\Server class

(mongodb >=1.0.0)

Introduction

Class synopsis

final MongoDB\Driver\Server {
/* Constants */
const integer TYPE_UNKNOWN = 0 ;
const integer TYPE_STANDALONE = 1 ;
const integer TYPE_MONGOS = 2 ;
const integer TYPE_POSSIBLE_PRIMARY = 3 ;
const integer TYPE_RS_PRIMARY = 4 ;
const integer TYPE_RS_SECONDARY = 5 ;
const integer TYPE_RS_ARBITER = 6 ;
const integer TYPE_RS_OTHER = 7 ;
const integer TYPE_RS_GHOST = 8 ;
/* Methods */
final private __construct ( void )
final public executeBulkWrite ( string $namespace , MongoDB\Driver\BulkWrite $bulk [, array $options = array() ] ) : MongoDB\Driver\WriteResult
final public executeCommand ( string $db , MongoDB\Driver\Command $command [, array $options = array() ] ) : MongoDB\Driver\Cursor
final public executeQuery ( string $namespace , MongoDB\Driver\Query $query [, array $options = array() ] ) : MongoDB\Driver\Cursor
final public executeReadCommand ( string $db , MongoDB\Driver\Command $command [, array $options = array() ] ) : MongoDB\Driver\Cursor
final public executeReadWriteCommand ( string $db , MongoDB\Driver\Command $command [, array $options = array() ] ) : MongoDB\Driver\Cursor
final public executeWriteCommand ( string $db , MongoDB\Driver\Command $command [, array $options = array() ] ) : MongoDB\Driver\Cursor
final public getHost ( void ) : string
final public getInfo ( void ) : array
final public getLatency ( void ) : string
final public getPort ( void ) : int
final public getTags ( void ) : array
final public getType ( void ) : int
final public isArbiter ( void ) : bool
final public isHidden ( void ) : bool
final public isPassive ( void ) : bool
final public isPrimary ( void ) : bool
final public isSecondary ( void ) : 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.

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::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 about this server
  • MongoDB\Driver\Server::getLatency — Returns the latency of this server
  • MongoDB\Driver\Server::getPort — Returns the port on which this server is listening
  • 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


Create a new Server (not used)

  • « MongoDB\Driver\Server
  • MongoDB\Driver\Server::executeBulkWrite »
  • PHP Manual
  • MongoDB\Driver\Server
  • Create a new Server (not used)

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

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


Execute one or more write operations on this server

  • « MongoDB\Driver\Server::__construct
  • MongoDB\Driver\Server::executeCommand »
  • PHP Manual
  • MongoDB\Driver\Server
  • Execute one or more write operations on this server

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 = array() ] ) : 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.

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
1.4.4 | MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the "session" option is used in combination with an unacknowledged write concern.
1.4.0 | The third parameter is now an options array. For backwards compatibility, this paramater will still accept a MongoDB\Driver\WriteConcern object.
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


Execute a database command on this server

  • « MongoDB\Driver\Server::executeBulkWrite
  • MongoDB\Driver\Server::executeQuery »
  • PHP Manual
  • MongoDB\Driver\Server
  • Execute a database command on this server

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 = array() ] ) : MongoDB\Driver\Cursor

Executes the command on this server.

This method applies no special logic to the command. Although this method accepts "readConcern" and "writeConcern" options, which will be incorporated into the command document, those options will not default to corresponding values from the MongoDB Connection URI nor will the MongoDB server version be taken into account. 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
1.4.4 | MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the "session" option is used in combination with an unacknowledged write concern.
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


Execute a database query on this server

  • « MongoDB\Driver\Server::executeCommand
  • MongoDB\Driver\Server::executeReadCommand »
  • PHP Manual
  • MongoDB\Driver\Server
  • Execute a database query on this server

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 = array() ] ) : MongoDB\Driver\Cursor

Executes the query on this server.

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


Execute a database command that reads on this server

  • « MongoDB\Driver\Server::executeQuery
  • MongoDB\Driver\Server::executeReadWriteCommand »
  • PHP Manual
  • MongoDB\Driver\Server
  • Execute a database command that reads on this server

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 = array() ] ) : MongoDB\Driver\Cursor

Executes the command on this server.

This method will apply logic that is specific to commands that read (e.g. » count) and take the MongoDB server version into account. The "readConcern" option will default to the corresponding value from the MongoDB 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


Execute a database command that reads and writes on this server

  • « MongoDB\Driver\Server::executeReadCommand
  • MongoDB\Driver\Server::executeWriteCommand »
  • PHP Manual
  • MongoDB\Driver\Server
  • Execute a database command that reads and writes on this server

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 = array() ] ) : 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. » findAndModify) and take the MongoDB server version into account. The "readConcern" and "writeConcern" options will default to the corresponding values from the MongoDB 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
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


Execute a database command that writes on this server

  • « MongoDB\Driver\Server::executeReadWriteCommand
  • MongoDB\Driver\Server::getHost »
  • PHP Manual
  • MongoDB\Driver\Server
  • Execute a database command that writes on this server

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 = array() ] ) : MongoDB\Driver\Cursor

Executes the command on this server.

This method will apply logic that is specific to commands that write (e.g. » drop) and take the MongoDB server version into account. The "writeConcern" option will default to the corresponding value from the MongoDB 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 commands.

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


Returns the hostname of this server

  • « MongoDB\Driver\Server::executeWriteCommand
  • MongoDB\Driver\Server::getInfo »
  • PHP Manual
  • MongoDB\Driver\Server
  • Returns the hostname of this server

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 ( void ) : 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/");

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
$server = $manager->selectServer($rp);

var_dump($server->getHost());

?>

The above example will output:

string(9) "localhost"

See Also

  • MongoDB\Driver\Server::getInfo() - Returns an array of information about this server


Returns an array of information about this server

  • « MongoDB\Driver\Server::getHost
  • MongoDB\Driver\Server::getLatency »
  • PHP Manual
  • MongoDB\Driver\Server
  • Returns an array of information about this server

MongoDB\Driver\Server::getInfo

(mongodb >=1.0.0)

MongoDB\Driver\Server::getInfo — Returns an array of information about this server

Description

final public MongoDB\Driver\Server::getInfo ( void ) : array

Returns an array of information about this server.

Parameters

This function has no parameters.

Return Values

Returns an array of information about 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(MongoDB\Driver\ReadPreference::RP_PRIMARY);
$server = $manager->selectServer($rp);

var_dump($server->getInfo());

?>

The above example will output something similar to:

array(8) {
  ["ismaster"]=>
  bool(true)
  ["maxBsonObjectSize"]=>
  int(16777216)
  ["maxMessageSizeBytes"]=>
  int(48000000)
  ["maxWriteBatchSize"]=>
  int(1000)
  ["localTime"]=>
  object(MongoDB\BSON\UTCDateTime)#4 (1) {
    ["milliseconds"]=>
    int(1447276242774)
  }
  ["maxWireVersion"]=>
  int(3)
  ["minWireVersion"]=>
  int(0)
  ["ok"]=>
  float(1)
}


Returns the latency of this server

  • « MongoDB\Driver\Server::getInfo
  • MongoDB\Driver\Server::getPort »
  • PHP Manual
  • MongoDB\Driver\Server
  • Returns the latency of this server

MongoDB\Driver\Server::getLatency

(mongodb >=1.0.0)

MongoDB\Driver\Server::getLatency — Returns the latency of this server

Description

final public MongoDB\Driver\Server::getLatency ( void ) : string

Returns the latency of this server (i.e. the client's measured » round trip time of an ismaster command).

Parameters

This function has no parameters.

Return Values

Returns the latency of this server.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

Examples

Example #1 MongoDB\Driver\Server::getLatency() example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017/");

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
$server = $manager->selectServer($rp);

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 about this server
  • » Server Discovery and Monitoring Specification


Returns the port on which this server is listening

  • « MongoDB\Driver\Server::getLatency
  • MongoDB\Driver\Server::getTags »
  • PHP Manual
  • MongoDB\Driver\Server
  • Returns the port on which this server is listening

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 ( void ) : 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/");

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
$server = $manager->selectServer($rp);

var_dump($server->getPort());

?>

The above example will output:

int(27017)

See Also

  • MongoDB\Driver\Server::getInfo() - Returns an array of information about this server


Returns an array of tags describing this server in a replica set

  • « MongoDB\Driver\Server::getPort
  • MongoDB\Driver\Server::getType »
  • PHP Manual
  • MongoDB\Driver\Server
  • Returns an array of tags describing this server in a replica set

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 ( void ) : 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 about this server


Returns an integer denoting the type of this server

  • « MongoDB\Driver\Server::getTags
  • MongoDB\Driver\Server::isArbiter »
  • PHP Manual
  • MongoDB\Driver\Server
  • Returns an integer denoting the type of 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 ( void ) : int

Returns an integer 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 integer 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 about this server


Checks if this server is an arbiter member of a replica set

  • « MongoDB\Driver\Server::getType
  • MongoDB\Driver\Server::isHidden »
  • PHP Manual
  • MongoDB\Driver\Server
  • Checks if this server is an arbiter member of a replica set

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 ( void ) : 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 about this server


Checks if this server is a hidden member of a replica set

  • « MongoDB\Driver\Server::isArbiter
  • MongoDB\Driver\Server::isPassive »
  • PHP Manual
  • MongoDB\Driver\Server
  • Checks if this server is a hidden member of a replica set

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 ( void ) : 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 about this server


Checks if this server is a passive member of a replica set

  • « MongoDB\Driver\Server::isHidden
  • MongoDB\Driver\Server::isPrimary »
  • PHP Manual
  • MongoDB\Driver\Server
  • Checks if this server is a passive member of a replica set

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 ( void ) : 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 about this server


Checks if this server is a primary member of a replica set

  • « MongoDB\Driver\Server::isPassive
  • MongoDB\Driver\Server::isSecondary »
  • PHP Manual
  • MongoDB\Driver\Server
  • Checks if this server is a primary member of a replica set

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 ( void ) : 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 about this server


Checks if this server is a secondary member of a replica set

  • « MongoDB\Driver\Server::isPrimary
  • MongoDB\Driver\WriteConcernError »
  • PHP Manual
  • MongoDB\Driver\Server
  • Checks if this server is a secondary member of a replica set

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 ( void ) : 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 about this 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 MongoDB\Driver\WriteConcernError {
/* Methods */
final public getCode ( void ) : int
final public getInfo ( void ) : mixed
final public getMessage ( void ) : string
}

Table of Contents

  • MongoDB\Driver\WriteConcernError::getCode — Returns the WriteConcernError's error code
  • MongoDB\Driver\WriteConcernError::getInfo — Returns additional metadata for the WriteConcernError
  • MongoDB\Driver\WriteConcernError::getMessage — Returns the WriteConcernError's error message


Returns the WriteConcernError's error code

  • « MongoDB\Driver\WriteConcernError
  • MongoDB\Driver\WriteConcernError::getInfo »
  • PHP Manual
  • MongoDB\Driver\WriteConcernError
  • Returns the WriteConcernError's error code

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 ( void ) : 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);
} 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


Returns additional metadata for the WriteConcernError

  • « MongoDB\Driver\WriteConcernError::getCode
  • MongoDB\Driver\WriteConcernError::getMessage »
  • PHP Manual
  • MongoDB\Driver\WriteConcernError
  • Returns additional metadata for the WriteConcernError

MongoDB\Driver\WriteConcernError::getInfo

(mongodb >=1.0.0)

MongoDB\Driver\WriteConcernError::getInfo — Returns additional metadata for the WriteConcernError

Description

final public MongoDB\Driver\WriteConcernError::getInfo ( void ) : mixed

Parameters

This function has no parameters.

Return Values

Returns additional metadata 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);
} 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


Returns the WriteConcernError's error message

  • « MongoDB\Driver\WriteConcernError::getInfo
  • MongoDB\Driver\WriteError »
  • PHP Manual
  • MongoDB\Driver\WriteConcernError
  • Returns the WriteConcernError's error message

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 ( void ) : 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);
} 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


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 MongoDB\Driver\WriteError {
/* Methods */
final public getCode ( void ) : int
final public getIndex ( void ) : int
final public getInfo ( void ) : mixed
final public getMessage ( void ) : string
}

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 additional metadata for the WriteError
  • MongoDB\Driver\WriteError::getMessage — Returns the WriteError's error message


Returns the WriteError's error code

  • « MongoDB\Driver\WriteError
  • MongoDB\Driver\WriteError::getIndex »
  • PHP Manual
  • MongoDB\Driver\WriteError
  • Returns the WriteError's error code

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 ( void ) : 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)


Returns the index of the write operation corresponding to this WriteError

  • « MongoDB\Driver\WriteError::getCode
  • MongoDB\Driver\WriteError::getInfo »
  • PHP Manual
  • MongoDB\Driver\WriteError
  • Returns the index of the write operation corresponding to this WriteError

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 ( void ) : 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


Returns additional metadata for the WriteError

  • « MongoDB\Driver\WriteError::getIndex
  • MongoDB\Driver\WriteError::getMessage »
  • PHP Manual
  • MongoDB\Driver\WriteError
  • Returns additional metadata for the WriteError

MongoDB\Driver\WriteError::getInfo

(mongodb >=1.0.0)

MongoDB\Driver\WriteError::getInfo — Returns additional metadata for the WriteError

Description

final public MongoDB\Driver\WriteError::getInfo ( void ) : mixed

Parameters

This function has no parameters.

Return Values

Returns additional metadata for the WriteError, or NULL if no metadata is available.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.


Returns the WriteError's error message

  • « MongoDB\Driver\WriteError::getInfo
  • MongoDB\Driver\WriteResult »
  • PHP Manual
  • MongoDB\Driver\WriteError
  • Returns the WriteError's error message

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 ( void ) : 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 }"


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 MongoDB\Driver\WriteResult {
/* Methods */
final public getDeletedCount ( void ) : integer|null
final public getInsertedCount ( void ) : integer|null
final public getMatchedCount ( void ) : integer|null
final public getModifiedCount ( void ) : integer|null
final public getServer ( void ) : MongoDB\Driver\Server
final public getUpsertedCount ( void ) : integer|null
final public getUpsertedIds ( void ) : array
final public getWriteConcernError ( void ) : MongoDB\Driver\WriteConcernError|null
final public getWriteErrors ( void ) : array
final public isAcknowledged ( void ) : bool
}

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


Returns the number of documents deleted

  • « MongoDB\Driver\WriteResult
  • MongoDB\Driver\WriteResult::getInsertedCount »
  • PHP Manual
  • MongoDB\Driver\WriteResult
  • Returns the number of documents deleted

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 ( void ) : integer|null

Parameters

This function has no parameters.

Return Values

Returns the number of documents deleted, or NULL if the write was not acknowledged.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

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


Returns the number of documents inserted (excluding upserts)

  • « MongoDB\Driver\WriteResult::getDeletedCount
  • MongoDB\Driver\WriteResult::getMatchedCount »
  • PHP Manual
  • MongoDB\Driver\WriteResult
  • Returns the number of documents inserted (excluding upserts)

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 ( void ) : integer|null

Parameters

This function has no parameters.

Return Values

Returns the number of documents inserted (excluding upserts), or NULL if the write was not acknowledged.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

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


Returns the number of documents selected for update

  • « MongoDB\Driver\WriteResult::getInsertedCount
  • MongoDB\Driver\WriteResult::getModifiedCount »
  • PHP Manual
  • MongoDB\Driver\WriteResult
  • Returns the number of documents selected for update

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 ( void ) : integer|null

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, or NULL if the write was not acknowledged.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

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


Returns the number of existing documents updated

  • « MongoDB\Driver\WriteResult::getMatchedCount
  • MongoDB\Driver\WriteResult::getServer »
  • PHP Manual
  • MongoDB\Driver\WriteResult
  • Returns the number of existing documents updated

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 ( void ) : integer|null

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, or NULL if the write was not acknowledged.

The modified count is not available on versions of MongoDB before 2.6, which used the legacy wire protocol version (i.e. OP_UPDATE). If this is the case, the modified count will also be NULL.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

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


Returns the server associated with this write result

  • « MongoDB\Driver\WriteResult::getModifiedCount
  • MongoDB\Driver\WriteResult::getUpsertedCount »
  • PHP Manual
  • MongoDB\Driver\WriteResult
  • Returns the server associated with this write result

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 ( void ) : 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(new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY));

$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


Returns the number of documents inserted by an upsert

  • « MongoDB\Driver\WriteResult::getServer
  • MongoDB\Driver\WriteResult::getUpsertedIds »
  • PHP Manual
  • MongoDB\Driver\WriteResult
  • Returns the number of documents inserted by an upsert

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 ( void ) : integer|null

Parameters

This function has no parameters.

Return Values

Returns the number of documents inserted by an upsert.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

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


Returns an array of identifiers for upserted documents

  • « MongoDB\Driver\WriteResult::getUpsertedCount
  • MongoDB\Driver\WriteResult::getWriteConcernError »
  • PHP Manual
  • MongoDB\Driver\WriteResult
  • Returns an array of identifiers for upserted documents

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 ( void ) : 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


Returns any write concern error that occurred

  • « MongoDB\Driver\WriteResult::getUpsertedIds
  • MongoDB\Driver\WriteResult::getWriteErrors »
  • PHP Manual
  • MongoDB\Driver\WriteResult
  • Returns any write concern error that occurred

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 ( void ) : MongoDB\Driver\WriteConcernError|null

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


Returns any write errors that occurred

  • « MongoDB\Driver\WriteResult::getWriteConcernError
  • MongoDB\Driver\WriteResult::isAcknowledged »
  • PHP Manual
  • MongoDB\Driver\WriteResult
  • Returns any write errors that occurred

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 ( void ) : 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


Returns whether the write was acknowledged

  • « MongoDB\Driver\WriteResult::getWriteErrors
  • MongoDB\BSON »
  • PHP Manual
  • MongoDB\Driver\WriteResult
  • Returns whether the write was acknowledged

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 ( void ) : 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]);

$result = $manager->executeBulkWrite('db.collection', $bulk, new MongoDB\Driver\WriteConcern(0));

var_dump($result->isAcknowledged());

?>

The above example will output:

bool(false)

See Also

  • MongoDB\Driver\WriteConcern
  • » Write Concern reference


BSON type classes and serialization functions

  • Functions
    • 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
  • MongoDB\BSON\Binary — The MongoDB\BSON\Binary class
    • MongoDB\BSON\Binary::__construct — Construct a new Binary
    • MongoDB\BSON\Binary::getData — Returns the Binary's data
    • MongoDB\BSON\Binary::getType — Returns the Binary's type
    • MongoDB\BSON\Binary::jsonSerialize — Returns a representation that can be converted to JSON
    • MongoDB\BSON\Binary::serialize — Serialize a Binary
    • MongoDB\BSON\Binary::__toString — Returns the Binary's data
    • MongoDB\BSON\Binary::unserialize — Unserialize a Binary
  • MongoDB\BSON\Decimal128 — The MongoDB\BSON\Decimal128 class
    • MongoDB\BSON\Decimal128::__construct — Construct a new Decimal128
    • MongoDB\BSON\Decimal128::jsonSerialize — Returns a representation that can be converted to JSON
    • MongoDB\BSON\Decimal128::serialize — Serialize a Decimal128
    • MongoDB\BSON\Decimal128::__toString — Returns the string representation of this Decimal128
    • MongoDB\BSON\Decimal128::unserialize — Unserialize a Decimal128
  • MongoDB\BSON\Javascript — The MongoDB\BSON\Javascript class
    • 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::serialize — Serialize a Javascript
    • MongoDB\BSON\Javascript::__toString — Returns the Javascript's code
    • MongoDB\BSON\Javascript::unserialize — Unserialize a Javascript
  • MongoDB\BSON\MaxKey — The MongoDB\BSON\MaxKey class
    • MongoDB\BSON\MaxKey::__construct — Construct a new MaxKey
    • MongoDB\BSON\MaxKey::jsonSerialize — Returns a representation that can be converted to JSON
    • MongoDB\BSON\MaxKey::serialize — Serialize a MaxKey
    • MongoDB\BSON\MaxKey::unserialize — Unserialize a MaxKey
  • MongoDB\BSON\MinKey — The MongoDB\BSON\MinKey class
    • MongoDB\BSON\MinKey::__construct — Construct a new MinKey
    • MongoDB\BSON\MinKey::jsonSerialize — Returns a representation that can be converted to JSON
    • MongoDB\BSON\MinKey::serialize — Serialize a MinKey
    • MongoDB\BSON\MinKey::unserialize — Unserialize a MinKey
  • MongoDB\BSON\ObjectId — The MongoDB\BSON\ObjectId class
    • 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::serialize — Serialize an ObjectId
    • MongoDB\BSON\ObjectId::__toString — Returns the hexidecimal representation of this ObjectId
    • MongoDB\BSON\ObjectId::unserialize — Unserialize an ObjectId
  • MongoDB\BSON\Regex — The MongoDB\BSON\Regex class
    • 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::serialize — Serialize a Regex
    • MongoDB\BSON\Regex::__toString — Returns the string representation of this Regex
    • MongoDB\BSON\Regex::unserialize — Unserialize a Regex
  • MongoDB\BSON\Timestamp — The MongoDB\BSON\Timestamp class
    • 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::serialize — Serialize a Timestamp
    • MongoDB\BSON\Timestamp::__toString — Returns the string representation of this Timestamp
    • MongoDB\BSON\Timestamp::unserialize — Unserialize a Timestamp
  • MongoDB\BSON\UTCDateTime — The MongoDB\BSON\UTCDateTime class
    • MongoDB\BSON\UTCDateTime::__construct — Construct a new UTCDateTime
    • MongoDB\BSON\UTCDateTime::jsonSerialize — Returns a representation that can be converted to JSON
    • MongoDB\BSON\UTCDateTime::serialize — Serialize a UTCDateTime
    • MongoDB\BSON\UTCDateTime::toDateTime — Returns the DateTime representation of this UTCDateTime
    • MongoDB\BSON\UTCDateTime::__toString — Returns the string representation of this UTCDateTime
    • MongoDB\BSON\UTCDateTime::unserialize — Unserialize a UTCDateTime
  • 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\Serializable::bsonSerialize — Provides an array or document to serialize as BSON
  • MongoDB\BSON\Unserializable — The MongoDB\BSON\Unserializable interface
    • MongoDB\BSON\Unserializable::bsonUnserialize — Constructs the object from a BSON array or document
  • MongoDB\BSON\BinaryInterface — The MongoDB\BSON\BinaryInterface interface
    • 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
  • MongoDB\BSON\Decimal128Interface — The MongoDB\BSON\Decimal128Interface interface
    • MongoDB\BSON\Decimal128Interface::__toString — Returns the string representation of this Decimal128Interface
  • MongoDB\BSON\JavascriptInterface — The MongoDB\BSON\JavascriptInterface interface
    • 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
  • 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\ObjectIdInterface::getTimestamp — Returns the timestamp component of this ObjectIdInterface
    • MongoDB\BSON\ObjectIdInterface::__toString — Returns the hexidecimal representation of this ObjectIdInterface
  • MongoDB\BSON\RegexInterface — The MongoDB\BSON\RegexInterface interface
    • 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
  • MongoDB\BSON\TimestampInterface — The MongoDB\BSON\TimestampInterface interface
    • 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
  • MongoDB\BSON\UTCDateTimeInterface — The MongoDB\BSON\UTCDateTimeInterface interface
    • MongoDB\BSON\UTCDateTimeInterface::toDateTime — Returns the DateTime representation of this UTCDateTimeInterface
    • MongoDB\BSON\UTCDateTimeInterface::__toString — Returns the string representation of this UTCDateTimeInterface
  • MongoDB\BSON\DBPointer — The MongoDB\BSON\DBPointer class (deprecated)
    • 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::serialize — Serialize a DBPointer
    • MongoDB\BSON\DBPointer::__toString — Returns an empty string
    • MongoDB\BSON\DBPointer::unserialize — Unserialize a DBPointer
  • MongoDB\BSON\Int64 — The MongoDB\BSON\Int64 class
    • MongoDB\BSON\Int64::__construct — Construct a new Int64 (unused)
    • MongoDB\BSON\Int64::jsonSerialize — Returns a representation that can be converted to JSON
    • MongoDB\BSON\Int64::serialize — Serialize an Int64
    • MongoDB\BSON\Int64::__toString — Returns the string representation of this Int64
    • MongoDB\BSON\Int64::unserialize — Unserialize an Int64
  • MongoDB\BSON\Symbol — The MongoDB\BSON\Symbol class (deprecated)
    • 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::serialize — Serialize a Symbol
    • MongoDB\BSON\Symbol::__toString — Returns the Symbol as a string
    • MongoDB\BSON\Symbol::unserialize — Unserialize a Symbol
  • MongoDB\BSON\Undefined — The MongoDB\BSON\Undefined class (deprecated)
    • 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::serialize — Serialize a Undefined
    • MongoDB\BSON\Undefined::__toString — Returns an empty string
    • MongoDB\BSON\Undefined::unserialize — Unserialize a Undefined


Functions

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


Returns the BSON representation of a JSON value

  • « Functions
  • MongoDB\BSON\fromPHP »
  • PHP Manual
  • Functions
  • Returns the BSON representation of a JSON value

MongoDB\BSON\fromJSON

(mongodb >=1.0.0)

MongoDB\BSON\fromJSON — Returns the BSON representation of a JSON value

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

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\toJSON() - Returns the Legacy Extended JSON representation of a BSON value
  • » MongoDB Extended JSON
  • » MongoDB BSON


Returns the BSON representation of a PHP value

  • « MongoDB\BSON\fromJSON
  • MongoDB\BSON\toCanonicalExtendedJSON »
  • PHP Manual
  • Functions
  • Returns the BSON representation of a PHP value

MongoDB\BSON\fromPHP

(mongodb >=1.0.0)

MongoDB\BSON\fromPHP — Returns the BSON representation of a PHP value

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.

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\toPHP() - Returns the PHP representation of a BSON value
  • » MongoDB BSON
  • Persisting Data


Returns the Canonical Extended JSON representation of a BSON value

  • « MongoDB\BSON\fromPHP
  • MongoDB\BSON\toJSON »
  • PHP Manual
  • Functions
  • Returns the Canonical Extended JSON representation of a BSON value

MongoDB\BSON\toCanonicalExtendedJSON

(mongodb >=1.3.0)

MongoDB\BSON\toCanonicalExtendedJSON — Returns the Canonical Extended JSON representation of a BSON value

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.

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


Returns the Legacy Extended JSON representation of a BSON value

  • « MongoDB\BSON\toCanonicalExtendedJSON
  • MongoDB\BSON\toPHP »
  • PHP Manual
  • Functions
  • Returns the Legacy Extended JSON representation of a BSON value

MongoDB\BSON\toJSON

(mongodb >=1.0.0)

MongoDB\BSON\toJSON — Returns the Legacy Extended JSON representation of a BSON value

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.

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


Returns the PHP representation of a BSON value

  • « MongoDB\BSON\toJSON
  • MongoDB\BSON\toRelaxedExtendedJSON »
  • PHP Manual
  • Functions
  • Returns the PHP representation of a BSON value

MongoDB\BSON\toPHP

(mongodb >=1.0.0)

MongoDB\BSON\toPHP — Returns the PHP representation of a BSON value

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

Fields containing deprecated BSON types (i.e. undefined, symbol, DBPointer) are represented only by bare-bones objects of the classes MongoDB\BSON\Undefined, MongoDB\BSON\Symbol, and MongoDB\BSON\DBPointer, when converting BSON to PHP. These objects are created from BSON data and used for storing these types back into the database, but can not be instantiated as they have a private constructor.

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
1.4.0 | If the input contains an unsupported, deprecated BSON type, the driver will now no longer log a warning to the debug log, but instead will create an object representing this type.
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 driver will now log a warning to the debug log (see: mongodb.debug).
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\fromPHP() - Returns the BSON representation of a PHP value
  • » MongoDB BSON
  • Persisting Data


Returns the Relaxed Extended JSON representation of a BSON value

  • « MongoDB\BSON\toPHP
  • MongoDB\BSON\Binary »
  • PHP Manual
  • Functions
  • Returns the Relaxed Extended JSON representation of a BSON value

MongoDB\BSON\toRelaxedExtendedJSON

(mongodb >=1.3.0)

MongoDB\BSON\toRelaxedExtendedJSON — Returns the Relaxed Extended JSON representation of a BSON value

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.

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


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 MongoDB\BSON\Binary implements MongoDB\BSON\BinaryInterface , MongoDB\BSON\Type , Serializable , JsonSerializable {
/* Constants */
const integer TYPE_GENERIC = 0 ;
const integer TYPE_FUNCTION = 1 ;
const integer TYPE_OLD_BINARY = 2 ;
const integer TYPE_OLD_UUID = 3 ;
const integer TYPE_UUID = 4 ;
const integer TYPE_MD5 = 5 ;
const integer TYPE_ENCRYPTED = 6 ;
const integer TYPE_USER_DEFINED = 128 ;
/* Methods */
final public __construct ( string $data , int $type )
final public getData ( void ) : string
final public getType ( void ) : int
final public jsonSerialize ( void ) : mixed
final public serialize ( void ) : string
final public __toString ( void ) : string
final public unserialize ( string $serialized ) : void
}

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 driver 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_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
1.3.0 | Implements MongoDB\BSON\BinaryInterface.
1.2.0 | Implements Serializable and JsonSerializable.

Table of Contents

  • MongoDB\BSON\Binary::__construct — Construct a new Binary
  • MongoDB\BSON\Binary::getData — Returns the Binary's data
  • MongoDB\BSON\Binary::getType — Returns the Binary's type
  • MongoDB\BSON\Binary::jsonSerialize — Returns a representation that can be converted to JSON
  • MongoDB\BSON\Binary::serialize — Serialize a Binary
  • MongoDB\BSON\Binary::__toString — Returns the Binary's data
  • MongoDB\BSON\Binary::unserialize — Unserialize a Binary


Construct a new Binary

  • « MongoDB\BSON\Binary
  • MongoDB\BSON\Binary::getData »
  • PHP Manual
  • MongoDB\BSON\Binary
  • Construct a new Binary

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 )

Parameters

data (string)

Binary data.

type (integer)

Unsigned 8-bit integer denoting the data's type.

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


Returns the Binary's data

  • « MongoDB\BSON\Binary::__construct
  • MongoDB\BSON\Binary::getType »
  • PHP Manual
  • MongoDB\BSON\Binary
  • Returns the Binary's data

MongoDB\BSON\Binary::getData

(mongodb >=1.0.0)

MongoDB\BSON\Binary::getData — Returns the Binary's data

Description

final public MongoDB\BSON\Binary::getData ( void ) : 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


Returns the Binary's type

  • « MongoDB\BSON\Binary::getData
  • MongoDB\BSON\Binary::jsonSerialize »
  • PHP Manual
  • MongoDB\BSON\Binary
  • Returns the Binary's type

MongoDB\BSON\Binary::getType

(mongodb >=1.0.0)

MongoDB\BSON\Binary::getType — Returns the Binary's type

Description

final public MongoDB\BSON\Binary::getType ( void ) : 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


Returns a representation that can be converted to JSON

  • « MongoDB\BSON\Binary::getType
  • MongoDB\BSON\Binary::serialize »
  • PHP Manual
  • MongoDB\BSON\Binary
  • Returns a representation that can be converted to JSON

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 ( void ) : 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


Serialize a Binary

  • « MongoDB\BSON\Binary::jsonSerialize
  • MongoDB\BSON\Binary::__toString »
  • PHP Manual
  • MongoDB\BSON\Binary
  • Serialize a Binary

MongoDB\BSON\Binary::serialize

(mongodb >=1.2.0)

MongoDB\BSON\Binary::serialize — Serialize a Binary

Description

final public MongoDB\BSON\Binary::serialize ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns the serialized representation of the MongoDB\BSON\Binary.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

See Also

  • MongoDB\BSON\Binary::unserialize() - Unserialize a Binary
  • serialize() - Generates a storable representation of a value
  • Serializing Objects


Returns the Binary's data

  • « MongoDB\BSON\Binary::serialize
  • MongoDB\BSON\Binary::unserialize »
  • PHP Manual
  • MongoDB\BSON\Binary
  • Returns the Binary's data

MongoDB\BSON\Binary::__toString

(mongodb >=1.2.0)

MongoDB\BSON\Binary::__toString — Returns the Binary's data

Description

final public MongoDB\BSON\Binary::__toString ( void ) : 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


Unserialize a Binary

  • « MongoDB\BSON\Binary::__toString
  • MongoDB\BSON\Decimal128 »
  • PHP Manual
  • MongoDB\BSON\Binary
  • Unserialize a Binary

MongoDB\BSON\Binary::unserialize

(mongodb >=1.2.0)

MongoDB\BSON\Binary::unserialize — Unserialize a Binary

Description

final public MongoDB\BSON\Binary::unserialize ( string $serialized ) : void

Parameters

serialized

The serialized MongoDB\BSON\Binary.

Return Values

Returns the unserialized MongoDB\BSON\Binary.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

See Also

  • MongoDB\BSON\Binary::serialize() - Serialize a Binary
  • unserialize() - Creates a PHP value from a stored representation
  • Serializing Objects


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 MongoDB\BSON\Decimal128 implements MongoDB\BSON\Decimal128Interface , MongoDB\BSON\Type , Serializable , JsonSerializable {
/* Methods */
final public __construct ([ string $value ] )
final public jsonSerialize ( void ) : mixed
final public serialize ( void ) : string
final public __toString ( void ) : string
final public unserialize ( string $serialized ) : void
}

Changelog

Version | Description
1.3.0 | Implements MongoDB\BSON\Decimal128Interface.
1.2.0 | Implements Serializable and JsonSerializable.

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::serialize — Serialize a Decimal128
  • MongoDB\BSON\Decimal128::__toString — Returns the string representation of this Decimal128
  • MongoDB\BSON\Decimal128::unserialize — Unserialize a Decimal128


Construct a new Decimal128

  • « MongoDB\BSON\Decimal128
  • MongoDB\BSON\Decimal128::jsonSerialize »
  • PHP Manual
  • MongoDB\BSON\Decimal128
  • Construct a new Decimal128

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


Returns a representation that can be converted to JSON

  • « MongoDB\BSON\Decimal128::__construct
  • MongoDB\BSON\Decimal128::serialize »
  • PHP Manual
  • MongoDB\BSON\Decimal128
  • Returns a representation that can be converted to JSON

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 ( void ) : 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


Serialize a Decimal128

  • « MongoDB\BSON\Decimal128::jsonSerialize
  • MongoDB\BSON\Decimal128::__toString »
  • PHP Manual
  • MongoDB\BSON\Decimal128
  • Serialize a Decimal128

MongoDB\BSON\Decimal128::serialize

(mongodb >=1.2.0)

MongoDB\BSON\Decimal128::serialize — Serialize a Decimal128

Description

final public MongoDB\BSON\Decimal128::serialize ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns the serialized representation of the MongoDB\BSON\Decimal128.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

See Also

  • MongoDB\BSON\Decimal128::unserialize() - Unserialize a Decimal128
  • serialize() - Generates a storable representation of a value
  • Serializing Objects


Returns the string representation of this Decimal128

  • « MongoDB\BSON\Decimal128::serialize
  • MongoDB\BSON\Decimal128::unserialize »
  • PHP Manual
  • MongoDB\BSON\Decimal128
  • Returns the string representation of this Decimal128

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 ( void ) : 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


Unserialize a Decimal128

  • « MongoDB\BSON\Decimal128::__toString
  • MongoDB\BSON\Javascript »
  • PHP Manual
  • MongoDB\BSON\Decimal128
  • Unserialize a Decimal128

MongoDB\BSON\Decimal128::unserialize

(mongodb >=1.2.0)

MongoDB\BSON\Decimal128::unserialize — Unserialize a Decimal128

Description

final public MongoDB\BSON\Decimal128::unserialize ( string $serialized ) : void

Parameters

serialized

The serialized MongoDB\BSON\Decimal128.

Return Values

Returns the unserialized MongoDB\BSON\Decimal128.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

See Also

  • MongoDB\BSON\Decimal128::serialize() - Serialize a Decimal128
  • unserialize() - Creates a PHP value from a stored representation
  • Serializing Objects


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 MongoDB\BSON\Javascript implements MongoDB\BSON\JavascriptInterface , MongoDB\BSON\Type , Serializable , JsonSerializable {
/* Methods */
final public __construct ( string $code [, array|object $scope ] )
final public getCode ( void ) : string
final public getScope ( void ) : object|null
final public jsonSerialize ( void ) : mixed
final public serialize ( void ) : string
final public __toString ( void ) : string
final public unserialize ( string $serialized ) : void
}

Changelog

Version | Description
1.3.0 | Implements MongoDB\BSON\JavascriptInterface.
1.2.0 | Implements Serializable and JsonSerializable.

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::serialize — Serialize a Javascript
  • MongoDB\BSON\Javascript::__toString — Returns the Javascript's code
  • MongoDB\BSON\Javascript::unserialize — Unserialize a Javascript


Construct a new Javascript

  • « MongoDB\BSON\Javascript
  • MongoDB\BSON\Javascript::getCode »
  • PHP Manual
  • MongoDB\BSON\Javascript
  • Construct a new Javascript

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 $scope ] )

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


Returns the Javascript's code

  • « MongoDB\BSON\Javascript::__construct
  • MongoDB\BSON\Javascript::getScope »
  • PHP Manual
  • MongoDB\BSON\Javascript
  • Returns the Javascript's code

MongoDB\BSON\Javascript::getCode

(mongodb >=1.2.0)

MongoDB\BSON\Javascript::getCode — Returns the Javascript's code

Description

final public MongoDB\BSON\Javascript::getCode ( void ) : 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


Returns the Javascript's scope document

  • « MongoDB\BSON\Javascript::getCode
  • MongoDB\BSON\Javascript::jsonSerialize »
  • PHP Manual
  • MongoDB\BSON\Javascript
  • Returns the Javascript's scope document

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 ( void ) : object|null

Parameters

This function has no parameters.

Return Values

Returns the Javascript's scope document.

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


Returns a representation that can be converted to JSON

  • « MongoDB\BSON\Javascript::getScope
  • MongoDB\BSON\Javascript::serialize »
  • PHP Manual
  • MongoDB\BSON\Javascript
  • Returns a representation that can be converted to JSON

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 ( void ) : 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


Serialize a Javascript

  • « MongoDB\BSON\Javascript::jsonSerialize
  • MongoDB\BSON\Javascript::__toString »
  • PHP Manual
  • MongoDB\BSON\Javascript
  • Serialize a Javascript

MongoDB\BSON\Javascript::serialize

(mongodb >=1.2.0)

MongoDB\BSON\Javascript::serialize — Serialize a Javascript

Description

final public MongoDB\BSON\Javascript::serialize ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns the serialized representation of the MongoDB\BSON\Javascript.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

See Also

  • MongoDB\BSON\Javascript::unserialize() - Unserialize a Javascript
  • serialize() - Generates a storable representation of a value
  • Serializing Objects


Returns the Javascript's code

  • « MongoDB\BSON\Javascript::serialize
  • MongoDB\BSON\Javascript::unserialize »
  • PHP Manual
  • MongoDB\BSON\Javascript
  • Returns the Javascript's code

MongoDB\BSON\Javascript::__toString

(mongodb >=1.2.0)

MongoDB\BSON\Javascript::__toString — Returns the Javascript's code

Description

final public MongoDB\BSON\Javascript::__toString ( void ) : 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


Unserialize a Javascript

  • « MongoDB\BSON\Javascript::__toString
  • MongoDB\BSON\MaxKey »
  • PHP Manual
  • MongoDB\BSON\Javascript
  • Unserialize a Javascript

MongoDB\BSON\Javascript::unserialize

(mongodb >=1.2.0)

MongoDB\BSON\Javascript::unserialize — Unserialize a Javascript

Description

final public MongoDB\BSON\Javascript::unserialize ( string $serialized ) : void

Parameters

serialized

The serialized MongoDB\BSON\Javascript.

Return Values

Returns the unserialized MongoDB\BSON\Javascript.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

See Also

  • MongoDB\BSON\Javascript::serialize() - Serialize a Javascript
  • unserialize() - Creates a PHP value from a stored representation
  • Serializing Objects


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 MongoDB\BSON\MaxKey implements MongoDB\BSON\MaxKeyInterface , MongoDB\BSON\Type , Serializable , JsonSerializable {
/* Methods */
final public __construct ( void )
final public jsonSerialize ( void ) : mixed
final public serialize ( void ) : string
final public unserialize ( string $serialized ) : void
}

Changelog

Version | Description
1.3.0 | Implements MongoDB\BSON\MaxKeyInterface.
1.2.0 | Implements Serializable and JsonSerializable.

Table of Contents

  • MongoDB\BSON\MaxKey::__construct — Construct a new MaxKey
  • MongoDB\BSON\MaxKey::jsonSerialize — Returns a representation that can be converted to JSON
  • MongoDB\BSON\MaxKey::serialize — Serialize a MaxKey
  • MongoDB\BSON\MaxKey::unserialize — Unserialize a MaxKey


Construct a new MaxKey

  • « MongoDB\BSON\MaxKey
  • MongoDB\BSON\MaxKey::jsonSerialize »
  • PHP Manual
  • MongoDB\BSON\MaxKey
  • Construct a new MaxKey

MongoDB\BSON\MaxKey::__construct

(mongodb >=1.0.0)

MongoDB\BSON\MaxKey::__construct — Construct a new MaxKey

Description

final public MongoDB\BSON\MaxKey::__construct ( void )

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


Returns a representation that can be converted to JSON

  • « MongoDB\BSON\MaxKey::__construct
  • MongoDB\BSON\MaxKey::serialize »
  • PHP Manual
  • MongoDB\BSON\MaxKey
  • Returns a representation that can be converted to JSON

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 ( void ) : 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


Serialize a MaxKey

  • « MongoDB\BSON\MaxKey::jsonSerialize
  • MongoDB\BSON\MaxKey::unserialize »
  • PHP Manual
  • MongoDB\BSON\MaxKey
  • Serialize a MaxKey

MongoDB\BSON\MaxKey::serialize

(mongodb >=1.2.0)

MongoDB\BSON\MaxKey::serialize — Serialize a MaxKey

Description

final public MongoDB\BSON\MaxKey::serialize ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns the serialized representation of the MongoDB\BSON\MaxKey.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

See Also

  • MongoDB\BSON\MaxKey::unserialize() - Unserialize a MaxKey
  • serialize() - Generates a storable representation of a value
  • Serializing Objects


Unserialize a MaxKey

  • « MongoDB\BSON\MaxKey::serialize
  • MongoDB\BSON\MinKey »
  • PHP Manual
  • MongoDB\BSON\MaxKey
  • Unserialize a MaxKey

MongoDB\BSON\MaxKey::unserialize

(mongodb >=1.2.0)

MongoDB\BSON\MaxKey::unserialize — Unserialize a MaxKey

Description

final public MongoDB\BSON\MaxKey::unserialize ( string $serialized ) : void

Parameters

serialized

The serialized MongoDB\BSON\MaxKey.

Return Values

Returns the unserialized MongoDB\BSON\MaxKey.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

See Also

  • MongoDB\BSON\MaxKey::serialize() - Serialize a MaxKey
  • unserialize() - Creates a PHP value from a stored representation
  • Serializing Objects


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 MongoDB\BSON\MinKey implements MongoDB\BSON\MinKeyInterface , MongoDB\BSON\Type , Serializable , JsonSerializable {
/* Methods */
final public __construct ( void )
final public jsonSerialize ( void ) : mixed
final public serialize ( void ) : string
final public unserialize ( string $serialized ) : void
}

Changelog

Version | Description
1.3.0 | Implements MongoDB\BSON\MinKeyInterface.
1.2.0 | Implements Serializable and JsonSerializable.

Table of Contents

  • MongoDB\BSON\MinKey::__construct — Construct a new MinKey
  • MongoDB\BSON\MinKey::jsonSerialize — Returns a representation that can be converted to JSON
  • MongoDB\BSON\MinKey::serialize — Serialize a MinKey
  • MongoDB\BSON\MinKey::unserialize — Unserialize a MinKey


Construct a new MinKey

  • « MongoDB\BSON\MinKey
  • MongoDB\BSON\MinKey::jsonSerialize »
  • PHP Manual
  • MongoDB\BSON\MinKey
  • Construct a new MinKey

MongoDB\BSON\MinKey::__construct

(mongodb >=1.0.0)

MongoDB\BSON\MinKey::__construct — Construct a new MinKey

Description

final public MongoDB\BSON\MinKey::__construct ( void )

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


Returns a representation that can be converted to JSON

  • « MongoDB\BSON\MinKey::__construct
  • MongoDB\BSON\MinKey::serialize »
  • PHP Manual
  • MongoDB\BSON\MinKey
  • Returns a representation that can be converted to JSON

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 ( void ) : 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


Serialize a MinKey

  • « MongoDB\BSON\MinKey::jsonSerialize
  • MongoDB\BSON\MinKey::unserialize »
  • PHP Manual
  • MongoDB\BSON\MinKey
  • Serialize a MinKey

MongoDB\BSON\MinKey::serialize

(mongodb >=1.2.0)

MongoDB\BSON\MinKey::serialize — Serialize a MinKey

Description

final public MongoDB\BSON\MinKey::serialize ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns the serialized representation of the MongoDB\BSON\MinKey.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

See Also

  • MongoDB\BSON\MinKey::unserialize() - Unserialize a MinKey
  • serialize() - Generates a storable representation of a value
  • Serializing Objects


Unserialize a MinKey

  • « MongoDB\BSON\MinKey::serialize
  • MongoDB\BSON\ObjectId »
  • PHP Manual
  • MongoDB\BSON\MinKey
  • Unserialize a MinKey

MongoDB\BSON\MinKey::unserialize

(mongodb >=1.2.0)

MongoDB\BSON\MinKey::unserialize — Unserialize a MinKey

Description

final public MongoDB\BSON\MinKey::unserialize ( string $serialized ) : void

Parameters

serialized

The serialized MongoDB\BSON\MinKey.

Return Values

Returns the unserialized MongoDB\BSON\MinKey.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

See Also

  • MongoDB\BSON\MinKey::serialize() - Serialize a MinKey
  • unserialize() - Creates a PHP value from a stored representation
  • Serializing Objects


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 driver 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 MongoDB\BSON\ObjectId implements MongoDB\BSON\ObjectIdInterface , MongoDB\BSON\Type , Serializable , JsonSerializable {
/* Methods */
final public __construct ([ string $id ] )
final public getTimestamp ( void ) : int
final public jsonSerialize ( void ) : mixed
final public serialize ( void ) : string
final public __toString ( void ) : string
final public unserialize ( string $serialized ) : void
}

Changelog

Version | Description
1.3.0 | Renamed from MongoDB\BSON\ObjectID to MongoDB\BSON\ObjectId. Implements MongoDB\BSON\ObjectIdInterface.
1.2.0 | Implements Serializable and JsonSerializable.

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::serialize — Serialize an ObjectId
  • MongoDB\BSON\ObjectId::__toString — Returns the hexidecimal representation of this ObjectId
  • MongoDB\BSON\ObjectId::unserialize — Unserialize an ObjectId


Construct a new ObjectId

  • « MongoDB\BSON\ObjectId
  • MongoDB\BSON\ObjectId::getTimestamp »
  • PHP Manual
  • MongoDB\BSON\ObjectId
  • Construct a new ObjectId

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

Parameters

id (string)

A 24-character hexadecimal string. If not provided, the driver 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


Returns the timestamp component of this ObjectId

  • « MongoDB\BSON\ObjectId::__construct
  • MongoDB\BSON\ObjectId::jsonSerialize »
  • PHP Manual
  • MongoDB\BSON\ObjectId
  • Returns the timestamp component of this 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 ( void ) : 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


Returns a representation that can be converted to JSON

  • « MongoDB\BSON\ObjectId::getTimestamp
  • MongoDB\BSON\ObjectId::serialize »
  • PHP Manual
  • MongoDB\BSON\ObjectId
  • Returns a representation that can be converted to JSON

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 ( void ) : 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


Serialize an ObjectId

  • « MongoDB\BSON\ObjectId::jsonSerialize
  • MongoDB\BSON\ObjectId::__toString »
  • PHP Manual
  • MongoDB\BSON\ObjectId
  • Serialize an ObjectId

MongoDB\BSON\ObjectId::serialize

(mongodb >=1.2.0)

MongoDB\BSON\ObjectId::serialize — Serialize an ObjectId

Description

final public MongoDB\BSON\ObjectId::serialize ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns the serialized representation of the MongoDB\BSON\ObjectId.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

See Also

  • MongoDB\BSON\ObjectId::unserialize() - Unserialize an ObjectId
  • serialize() - Generates a storable representation of a value
  • Serializing Objects


Returns the hexidecimal representation of this ObjectId

  • « MongoDB\BSON\ObjectId::serialize
  • MongoDB\BSON\ObjectId::unserialize »
  • PHP Manual
  • MongoDB\BSON\ObjectId
  • Returns the hexidecimal representation of this ObjectId

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 ( void ) : 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


Unserialize an ObjectId

  • « MongoDB\BSON\ObjectId::__toString
  • MongoDB\BSON\Regex »
  • PHP Manual
  • MongoDB\BSON\ObjectId
  • Unserialize an ObjectId

MongoDB\BSON\ObjectId::unserialize

(mongodb >=1.2.0)

MongoDB\BSON\ObjectId::unserialize — Unserialize an ObjectId

Description

final public MongoDB\BSON\ObjectId::unserialize ( string $serialized ) : void

Parameters

serialized

The serialized MongoDB\BSON\ObjectId.

Return Values

Returns the unserialized MongoDB\BSON\ObjectId.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

See Also

  • MongoDB\BSON\ObjectId::serialize() - Serialize an ObjectId
  • unserialize() - Creates a PHP value from a stored representation
  • Serializing Objects


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 MongoDB\BSON\Regex implements MongoDB\BSON\RegexInterface , MongoDB\BSON\Type , Serializable , JsonSerializable {
/* Methods */
final public __construct ( string $pattern [, string $flags = "" ] )
final public getFlags ( void ) : string
final public getPattern ( void ) : string
final public jsonSerialize ( void ) : mixed
final public serialize ( void ) : string
final public __toString ( void ) : string
final public unserialize ( string $serialized ) : void
}

Changelog

Version | Description
1.3.0 | Implements MongoDB\BSON\RegexInterface.
1.2.0 | Implements Serializable and JsonSerializable.

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::serialize — Serialize a Regex
  • MongoDB\BSON\Regex::__toString — Returns the string representation of this Regex
  • MongoDB\BSON\Regex::unserialize — Unserialize a Regex


Construct a new Regex

  • « MongoDB\BSON\Regex
  • MongoDB\BSON\Regex::getFlags »
  • PHP Manual
  • MongoDB\BSON\Regex
  • Construct a new Regex

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


Returns the Regex's flags

  • « MongoDB\BSON\Regex::__construct
  • MongoDB\BSON\Regex::getPattern »
  • PHP Manual
  • MongoDB\BSON\Regex
  • Returns the Regex's 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 ( void ) : 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


Returns the Regex's pattern

  • « MongoDB\BSON\Regex::getFlags
  • MongoDB\BSON\Regex::jsonSerialize »
  • PHP Manual
  • MongoDB\BSON\Regex
  • Returns the Regex's pattern

MongoDB\BSON\Regex::getPattern

(mongodb >=1.0.0)

MongoDB\BSON\Regex::getPattern — Returns the Regex's pattern

Description

final public MongoDB\BSON\Regex::getPattern ( void ) : 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


Returns a representation that can be converted to JSON

  • « MongoDB\BSON\Regex::getPattern
  • MongoDB\BSON\Regex::serialize »
  • PHP Manual
  • MongoDB\BSON\Regex
  • Returns a representation that can be converted to JSON

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 ( void ) : 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


Serialize a Regex

  • « MongoDB\BSON\Regex::jsonSerialize
  • MongoDB\BSON\Regex::__toString »
  • PHP Manual
  • MongoDB\BSON\Regex
  • Serialize a Regex

MongoDB\BSON\Regex::serialize

(mongodb >=1.2.0)

MongoDB\BSON\Regex::serialize — Serialize a Regex

Description

final public MongoDB\BSON\Regex::serialize ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns the serialized representation of the MongoDB\BSON\Regex.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

See Also

  • MongoDB\BSON\Regex::unserialize() - Unserialize a Regex
  • serialize() - Generates a storable representation of a value
  • Serializing Objects


Returns the string representation of this Regex

  • « MongoDB\BSON\Regex::serialize
  • MongoDB\BSON\Regex::unserialize »
  • PHP Manual
  • MongoDB\BSON\Regex
  • Returns the string representation of this Regex

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 ( void ) : 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


Unserialize a Regex

  • « MongoDB\BSON\Regex::__toString
  • MongoDB\BSON\Timestamp »
  • PHP Manual
  • MongoDB\BSON\Regex
  • Unserialize a Regex

MongoDB\BSON\Regex::unserialize

(mongodb >=1.2.0)

MongoDB\BSON\Regex::unserialize — Unserialize a Regex

Description

final public MongoDB\BSON\Regex::unserialize ( string $serialized ) : void

Parameters

serialized

The serialized MongoDB\BSON\Regex.

Return Values

Returns the unserialized MongoDB\BSON\Regex.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

See Also

  • MongoDB\BSON\Regex::serialize() - Serialize a Regex
  • unserialize() - Creates a PHP value from a stored representation
  • Serializing Objects


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 MongoDB\BSON\Timestamp implements MongoDB\BSON\TimestampInterface , MongoDB\BSON\Type , Serializable , JsonSerializable {
/* Methods */
final public __construct ( int $increment , int $timestamp )
final public getIncrement ( void ) : int
final public getTimestamp ( void ) : int
final public jsonSerialize ( void ) : mixed
final public serialize ( void ) : string
final public __toString ( void ) : string
final public unserialize ( string $serialized ) : void
}

Changelog

Version | Description
1.3.0 | Implements MongoDB\BSON\TimestampInterface.
1.2.0 | Implements Serializable and JsonSerializable.

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::serialize — Serialize a Timestamp
  • MongoDB\BSON\Timestamp::__toString — Returns the string representation of this Timestamp
  • MongoDB\BSON\Timestamp::unserialize — Unserialize a Timestamp


Construct a new Timestamp

  • « MongoDB\BSON\Timestamp
  • MongoDB\BSON\Timestamp::getIncrement »
  • PHP Manual
  • MongoDB\BSON\Timestamp
  • Construct a new Timestamp

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

32-bit integer denoting the incrementing ordinal for operations within a given second.

timestamp (integer)

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


Returns the increment component of this Timestamp

  • « MongoDB\BSON\Timestamp::__construct
  • MongoDB\BSON\Timestamp::getTimestamp »
  • PHP Manual
  • MongoDB\BSON\Timestamp
  • Returns the increment component of this Timestamp

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 ( void ) : 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


Returns the timestamp component of this Timestamp

  • « MongoDB\BSON\Timestamp::getIncrement
  • MongoDB\BSON\Timestamp::jsonSerialize »
  • PHP Manual
  • MongoDB\BSON\Timestamp
  • Returns the timestamp component of this Timestamp

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 ( void ) : 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


Returns a representation that can be converted to JSON

  • « MongoDB\BSON\Timestamp::getTimestamp
  • MongoDB\BSON\Timestamp::serialize »
  • PHP Manual
  • MongoDB\BSON\Timestamp
  • Returns a representation that can be converted to JSON

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 ( void ) : 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


Serialize a Timestamp

  • « MongoDB\BSON\Timestamp::jsonSerialize
  • MongoDB\BSON\Timestamp::__toString »
  • PHP Manual
  • MongoDB\BSON\Timestamp
  • Serialize a Timestamp

MongoDB\BSON\Timestamp::serialize

(mongodb >=1.2.0)

MongoDB\BSON\Timestamp::serialize — Serialize a Timestamp

Description

final public MongoDB\BSON\Timestamp::serialize ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns the serialized representation of the MongoDB\BSON\Timestamp.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

See Also

  • MongoDB\BSON\Timestamp::unserialize() - Unserialize a Timestamp
  • serialize() - Generates a storable representation of a value
  • Serializing Objects


Returns the string representation of this Timestamp

  • « MongoDB\BSON\Timestamp::serialize
  • MongoDB\BSON\Timestamp::unserialize »
  • PHP Manual
  • MongoDB\BSON\Timestamp
  • Returns the string representation of this Timestamp

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 ( void ) : 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


Unserialize a Timestamp

  • « MongoDB\BSON\Timestamp::__toString
  • MongoDB\BSON\UTCDateTime »
  • PHP Manual
  • MongoDB\BSON\Timestamp
  • Unserialize a Timestamp

MongoDB\BSON\Timestamp::unserialize

(mongodb >=1.2.0)

MongoDB\BSON\Timestamp::unserialize — Unserialize a Timestamp

Description

final public MongoDB\BSON\Timestamp::unserialize ( string $serialized ) : void

Parameters

serialized

The serialized MongoDB\BSON\Timestamp.

Return Values

Returns the unserialized MongoDB\BSON\Timestamp.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

See Also

  • MongoDB\BSON\Timestamp::serialize() - Serialize a Timestamp
  • unserialize() - Creates a PHP value from a stored representation
  • Serializing Objects


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 MongoDB\BSON\UTCDateTime implements MongoDB\BSON\UTCDateTimeInterface , MongoDB\BSON\Type , Serializable , JsonSerializable {
/* Methods */
final public __construct ([ integer|float|string|DateTimeInterface $milliseconds = NULL ] )
final public jsonSerialize ( void ) : mixed
final public serialize ( void ) : string
final public toDateTime ( void ) : DateTime
final public __toString ( void ) : string
final public unserialize ( string $serialized ) : void
}

Changelog

Version | Description
1.3.0 | Implements MongoDB\BSON\UTCDateTimeInterface.
1.2.0 | Implements Serializable and JsonSerializable.

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::serialize — Serialize a UTCDateTime
  • MongoDB\BSON\UTCDateTime::toDateTime — Returns the DateTime representation of this UTCDateTime
  • MongoDB\BSON\UTCDateTime::__toString — Returns the string representation of this UTCDateTime
  • MongoDB\BSON\UTCDateTime::unserialize — Unserialize a UTCDateTime


Construct a new UTCDateTime

  • « MongoDB\BSON\UTCDateTime
  • MongoDB\BSON\UTCDateTime::jsonSerialize »
  • PHP Manual
  • MongoDB\BSON\UTCDateTime
  • Construct a new UTCDateTime

MongoDB\BSON\UTCDateTime::__construct

(mongodb >=1.0.0)

MongoDB\BSON\UTCDateTime::__construct — Construct a new UTCDateTime

Description

final public MongoDB\BSON\UTCDateTime::__construct ([ integer|float|string|DateTimeInterface $milliseconds = NULL ] )

Parameters

milliseconds (integer|float|string|DateTimeInterface)

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 integer. For compatibility on 32-bit systems, this parameter may also be provided as a float or string.

If the argument is a DateTimeInterface, the number of milliseconds since the Unix epoch will be derived from that value. Note that in versions of PHP versions before 7.1.0, DateTime and DateTimeImmutable objects constructed from the current time did not incorporate sub-second precision.

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
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 integer, 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


Returns a representation that can be converted to JSON

  • « MongoDB\BSON\UTCDateTime::__construct
  • MongoDB\BSON\UTCDateTime::serialize »
  • PHP Manual
  • MongoDB\BSON\UTCDateTime
  • Returns a representation that can be converted to JSON

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 ( void ) : 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


Serialize a UTCDateTime

  • « MongoDB\BSON\UTCDateTime::jsonSerialize
  • MongoDB\BSON\UTCDateTime::toDateTime »
  • PHP Manual
  • MongoDB\BSON\UTCDateTime
  • Serialize a UTCDateTime

MongoDB\BSON\UTCDateTime::serialize

(mongodb >=1.2.0)

MongoDB\BSON\UTCDateTime::serialize — Serialize a UTCDateTime

Description

final public MongoDB\BSON\UTCDateTime::serialize ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns the serialized representation of the MongoDB\BSON\UTCDateTime.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

See Also

  • MongoDB\BSON\UTCDateTime::unserialize() - Unserialize a UTCDateTime
  • serialize() - Generates a storable representation of a value
  • Serializing Objects


Returns the DateTime representation of this UTCDateTime

  • « MongoDB\BSON\UTCDateTime::serialize
  • MongoDB\BSON\UTCDateTime::__toString »
  • PHP Manual
  • MongoDB\BSON\UTCDateTime
  • Returns the DateTime representation of this UTCDateTime

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 ( void ) : 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

  • » BSON Types: Date


Returns the string representation of this UTCDateTime

  • « MongoDB\BSON\UTCDateTime::toDateTime
  • MongoDB\BSON\UTCDateTime::unserialize »
  • PHP Manual
  • MongoDB\BSON\UTCDateTime
  • Returns the string representation of this UTCDateTime

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 ( void ) : 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


Unserialize a UTCDateTime

  • « MongoDB\BSON\UTCDateTime::__toString
  • MongoDB\BSON\Type »
  • PHP Manual
  • MongoDB\BSON\UTCDateTime
  • Unserialize a UTCDateTime

MongoDB\BSON\UTCDateTime::unserialize

(mongodb >=1.2.0)

MongoDB\BSON\UTCDateTime::unserialize — Unserialize a UTCDateTime

Description

final public MongoDB\BSON\UTCDateTime::unserialize ( string $serialized ) : void

Parameters

serialized

The serialized MongoDB\BSON\UTCDateTime.

Return Values

Returns the unserialized MongoDB\BSON\UTCDateTime.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

See Also

  • MongoDB\BSON\UTCDateTime::serialize() - Serialize a UTCDateTime
  • unserialize() - Creates a PHP value from a stored representation
  • Serializing Objects


The MongoDB\BSON\Type interface

(mongodb >=1.0.0)

Introduction

Abstract base interface that should not be implemented directly.

Interface synopsis

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 driver. During serialization, the driver 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

MongoDB\BSON\Persistable implements MongoDB\BSON\Unserializable , MongoDB\BSON\Serializable {
/* Inherited methods */
abstract public MongoDB\BSON\Serializable::bsonSerialize ( void ) : array|object
abstract public MongoDB\BSON\Unserializable::bsonUnserialize ( array $data ) : void
}


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

MongoDB\BSON\Serializable implements MongoDB\BSON\Type {
/* Methods */
abstract public bsonSerialize ( void ) : array|object
}

Table of Contents

  • MongoDB\BSON\Serializable::bsonSerialize — Provides an array or document to serialize as BSON


Provides an array or document to serialize as BSON

  • « MongoDB\BSON\Serializable
  • MongoDB\BSON\Unserializable »
  • PHP Manual
  • MongoDB\BSON\Serializable
  • Provides an array or document to serialize as BSON

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 ( void ) : array|object

Called during serialization of the object to BSON. The method must return an array or stdClass.

Root documents (e.g. a MongoDB\BSON\Serializable passed to MongoDB\BSON\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 your constructor) when returning data for a BSON root document; otherwise, the driver or database will need to generate a MongoDB\BSON\ObjectId when inserting or upserting the document, respectively.

Parameters

This function has no parameters.

Return Values

An array or stdClass to be serialized as a BSON array or document.

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()
    {
        return ['_id' => $this->id, 'foo' => 'bar'];
    }
}

$bson = MongoDB\BSON\fromPHP(new MyDocument);
echo MongoDB\BSON\toJSON($bson), "\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()
    {
        return [1, 2, 3];
    }
}

$bson = MongoDB\BSON\fromPHP(new MyArray);
echo MongoDB\BSON\toJSON($bson), "\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()
    {
        return ['foo' => 'bar'];
    }
}

$value = ['document' => new MyDocument];
$bson = MongoDB\BSON\fromPHP($value);
echo MongoDB\BSON\toJSON($bson), "\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()
    {
        return [1, 2, 3];
    }
}

$value = ['array' => new MyArray];
$bson = MongoDB\BSON\fromPHP($value);
echo MongoDB\BSON\toJSON($bson), "\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


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

MongoDB\BSON\Unserializable {
/* Methods */
abstract public bsonUnserialize ( array $data ) : void
}

Table of Contents

  • MongoDB\BSON\Unserializable::bsonUnserialize — Constructs the object from a BSON array or document


Constructs the object from a BSON array or document

  • « MongoDB\BSON\Unserializable
  • MongoDB\BSON\BinaryInterface »
  • PHP Manual
  • MongoDB\BSON\Unserializable
  • Constructs the object from a BSON array or document

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.

Examples

Example #1 MongoDB\BSON\Unserializable::bsonUnserialize() example

<?php

class MyDocument implements MongoDB\BSON\Unserializable
{
    private $data = [];

    function bsonUnserialize(array $data)
    {
        $this->data = $data;
    }
}

$bson = MongoDB\BSON\fromJSON('{ "foo": "bar" }');
$value = MongoDB\BSON\toPHP($bson, ['root' => 'MyDocument']);
var_dump($value);

?>

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


The MongoDB\BSON\BinaryInterface interface

(mongodb >=1.3.0)

Introduction

This interface is implemented by MongoDB\BSON\Binary but may also be used for type-hinting and userland classes.

Class synopsis

MongoDB\BSON\BinaryInterface {
/* Methods */
abstract public getData ( void ) : string
abstract public getType ( void ) : int
abstract public __toString ( void ) : string
}

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


Returns the BinaryInterface's data

  • « MongoDB\BSON\BinaryInterface
  • MongoDB\BSON\BinaryInterface::getType »
  • PHP Manual
  • MongoDB\BSON\BinaryInterface
  • Returns the BinaryInterface's data

MongoDB\BSON\BinaryInterface::getData

(mongodb >=1.3.0)

MongoDB\BSON\BinaryInterface::getData — Returns the BinaryInterface's data

Description

abstract public MongoDB\BSON\BinaryInterface::getData ( void ) : 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


Returns the BinaryInterface's type

  • « MongoDB\BSON\BinaryInterface::getData
  • MongoDB\BSON\BinaryInterface::__toString »
  • PHP Manual
  • MongoDB\BSON\BinaryInterface
  • Returns the BinaryInterface's type

MongoDB\BSON\BinaryInterface::getType

(mongodb >=1.3.0)

MongoDB\BSON\BinaryInterface::getType — Returns the BinaryInterface's type

Description

abstract public MongoDB\BSON\BinaryInterface::getType ( void ) : 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


Returns the BinaryInterface's data

  • « MongoDB\BSON\BinaryInterface::getType
  • MongoDB\BSON\Decimal128Interface »
  • PHP Manual
  • MongoDB\BSON\BinaryInterface
  • Returns the BinaryInterface's data

MongoDB\BSON\BinaryInterface::__toString

(mongodb >=1.3.0)

MongoDB\BSON\BinaryInterface::__toString — Returns the BinaryInterface's data

Description

abstract public MongoDB\BSON\BinaryInterface::__toString ( void ) : 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


The MongoDB\BSON\Decimal128Interface interface

(mongodb >=1.3.0)

Introduction

This interface is implemented by MongoDB\BSON\Decimal128 but may also be used for type-hinting and userland classes.

Class synopsis

MongoDB\BSON\Decimal128Interface {
/* Methods */
abstract public __toString ( void ) : string
}

Table of Contents

  • MongoDB\BSON\Decimal128Interface::__toString — Returns the string representation of this Decimal128Interface


Returns the string representation of this Decimal128Interface

  • « MongoDB\BSON\Decimal128Interface
  • MongoDB\BSON\JavascriptInterface »
  • PHP Manual
  • MongoDB\BSON\Decimal128Interface
  • Returns the string representation of this Decimal128Interface

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 ( void ) : 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


The MongoDB\BSON\JavascriptInterface interface

(mongodb >=1.3.0)

Introduction

This interface is implemented by MongoDB\BSON\Javascript but may also be used for type-hinting and userland classes.

Class synopsis

MongoDB\BSON\JavascriptInterface {
/* Methods */
abstract public getCode ( void ) : string
abstract public getScope ( void ) : object|null
abstract public __toString ( void ) : string
}

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


Returns the JavascriptInterface's code

  • « MongoDB\BSON\JavascriptInterface
  • MongoDB\BSON\JavascriptInterface::getScope »
  • PHP Manual
  • MongoDB\BSON\JavascriptInterface
  • Returns the JavascriptInterface's code

MongoDB\BSON\JavascriptInterface::getCode

(mongodb >=1.3.0)

MongoDB\BSON\JavascriptInterface::getCode — Returns the JavascriptInterface's code

Description

abstract public MongoDB\BSON\JavascriptInterface::getCode ( void ) : 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


Returns the JavascriptInterface's scope document

  • « MongoDB\BSON\JavascriptInterface::getCode
  • MongoDB\BSON\JavascriptInterface::__toString »
  • PHP Manual
  • MongoDB\BSON\JavascriptInterface
  • Returns the JavascriptInterface's scope document

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 ( void ) : object|null

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


Returns the JavascriptInterface's code

  • « MongoDB\BSON\JavascriptInterface::getScope
  • MongoDB\BSON\MaxKeyInterface »
  • PHP Manual
  • MongoDB\BSON\JavascriptInterface
  • Returns the JavascriptInterface's code

MongoDB\BSON\JavascriptInterface::__toString

(mongodb >=1.3.0)

MongoDB\BSON\JavascriptInterface::__toString — Returns the JavascriptInterface's code

Description

abstract public MongoDB\BSON\JavascriptInterface::__toString ( void ) : 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


The MongoDB\BSON\MaxKeyInterface interface

(mongodb >=1.3.0)

Introduction

This interface is implemented by MongoDB\BSON\MaxKey but may also be used for type-hinting and userland classes.

Class synopsis

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 but may also be used for type-hinting and userland classes.

Class synopsis

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 but may also be used for type-hinting and userland classes.

Class synopsis

MongoDB\BSON\ObjectIdInterface {
/* Methods */
abstract public getTimestamp ( void ) : int
abstract public __toString ( void ) : string
}

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


Returns the timestamp component of this ObjectIdInterface

  • « MongoDB\BSON\ObjectIdInterface
  • MongoDB\BSON\ObjectIdInterface::__toString »
  • PHP Manual
  • MongoDB\BSON\ObjectIdInterface
  • Returns the timestamp component of this ObjectIdInterface

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 ( void ) : 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


Returns the hexidecimal representation of this ObjectIdInterface

  • « MongoDB\BSON\ObjectIdInterface::getTimestamp
  • MongoDB\BSON\RegexInterface »
  • PHP Manual
  • MongoDB\BSON\ObjectIdInterface
  • Returns the hexidecimal representation of this ObjectIdInterface

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 ( void ) : 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


The MongoDB\BSON\RegexInterface interface

(mongodb >=1.3.0)

Introduction

This interface is implemented by MongoDB\BSON\Regex but may also be used for type-hinting and userland classes.

Class synopsis

MongoDB\BSON\RegexInterface {
/* Methods */
abstract public getFlags ( void ) : string
abstract public getPattern ( void ) : string
abstract public __toString ( void ) : string
}

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


Returns the RegexInterface's flags

  • « MongoDB\BSON\RegexInterface
  • MongoDB\BSON\RegexInterface::getPattern »
  • PHP Manual
  • MongoDB\BSON\RegexInterface
  • Returns the RegexInterface's flags

MongoDB\BSON\RegexInterface::getFlags

(mongodb >=1.3.0)

MongoDB\BSON\RegexInterface::getFlags — Returns the RegexInterface's flags

Description

abstract public MongoDB\BSON\RegexInterface::getFlags ( void ) : 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


Returns the RegexInterface's pattern

  • « MongoDB\BSON\RegexInterface::getFlags
  • MongoDB\BSON\RegexInterface::__toString »
  • PHP Manual
  • MongoDB\BSON\RegexInterface
  • Returns the RegexInterface's pattern

MongoDB\BSON\RegexInterface::getPattern

(mongodb >=1.3.0)

MongoDB\BSON\RegexInterface::getPattern — Returns the RegexInterface's pattern

Description

abstract public MongoDB\BSON\RegexInterface::getPattern ( void ) : 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


Returns the string representation of this RegexInterface

  • « MongoDB\BSON\RegexInterface::getPattern
  • MongoDB\BSON\TimestampInterface »
  • PHP Manual
  • MongoDB\BSON\RegexInterface
  • Returns the string representation of this RegexInterface

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 ( void ) : 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


The MongoDB\BSON\TimestampInterface interface

(mongodb >=1.3.0)

Introduction

This interface is implemented by MongoDB\BSON\Timestamp but may also be used for type-hinting and userland classes.

Class synopsis

MongoDB\BSON\TimestampInterface {
/* Methods */
abstract public getIncrement ( void ) : int
abstract public getTimestamp ( void ) : int
abstract public __toString ( void ) : string
}

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


Returns the increment component of this TimestampInterface

  • « MongoDB\BSON\TimestampInterface
  • MongoDB\BSON\TimestampInterface::getTimestamp »
  • PHP Manual
  • MongoDB\BSON\TimestampInterface
  • Returns the increment component of this TimestampInterface

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 ( void ) : 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


Returns the timestamp component of this TimestampInterface

  • « MongoDB\BSON\TimestampInterface::getIncrement
  • MongoDB\BSON\TimestampInterface::__toString »
  • PHP Manual
  • MongoDB\BSON\TimestampInterface
  • Returns the timestamp component of this TimestampInterface

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 ( void ) : 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


Returns the string representation of this TimestampInterface

  • « MongoDB\BSON\TimestampInterface::getTimestamp
  • MongoDB\BSON\UTCDateTimeInterface »
  • PHP Manual
  • MongoDB\BSON\TimestampInterface
  • Returns the string representation of this TimestampInterface

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 ( void ) : 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


The MongoDB\BSON\UTCDateTimeInterface interface

(mongodb >=1.3.0)

Introduction

This interface is implemented by MongoDB\BSON\UTCDateTime but may also be used for type-hinting and userland classes.

Class synopsis

MongoDB\BSON\UTCDateTimeInterface {
/* Methods */
abstract public toDateTime ( void ) : DateTime
abstract public __toString ( void ) : string
}

Table of Contents

  • MongoDB\BSON\UTCDateTimeInterface::toDateTime — Returns the DateTime representation of this UTCDateTimeInterface
  • MongoDB\BSON\UTCDateTimeInterface::__toString — Returns the string representation of this UTCDateTimeInterface


Returns the DateTime representation of this UTCDateTimeInterface

  • « MongoDB\BSON\UTCDateTimeInterface
  • MongoDB\BSON\UTCDateTimeInterface::__toString »
  • PHP Manual
  • MongoDB\BSON\UTCDateTimeInterface
  • Returns the DateTime representation of this UTCDateTimeInterface

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 ( void ) : 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


Returns the string representation of this UTCDateTimeInterface

  • « MongoDB\BSON\UTCDateTimeInterface::toDateTime
  • MongoDB\BSON\DBPointer »
  • PHP Manual
  • MongoDB\BSON\UTCDateTimeInterface
  • Returns the string representation of this UTCDateTimeInterface

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 ( void ) : 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


The MongoDB\BSON\DBPointer class (deprecated)

(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 MongoDB\BSON\DBPointer implements MongoDB\BSON\Type , Serializable , JsonSerializable {
/* Methods */
final private __construct ( void )
final public jsonSerialize ( void ) : mixed
final public serialize ( void ) : string
final public __toString ( void ) : string
final public unserialize ( string $serialized ) : void
}

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::serialize — Serialize a DBPointer
  • MongoDB\BSON\DBPointer::__toString — Returns an empty string
  • MongoDB\BSON\DBPointer::unserialize — Unserialize a DBPointer


Construct a new DBPointer (unused)

  • « MongoDB\BSON\DBPointer
  • MongoDB\BSON\DBPointer::jsonSerialize »
  • PHP Manual
  • MongoDB\BSON\DBPointer
  • Construct a new DBPointer (unused)

MongoDB\BSON\DBPointer::__construct

(mongodb >=1.4.0)

MongoDB\BSON\DBPointer::__construct — Construct a new DBPointer (unused)

Description

final private MongoDB\BSON\DBPointer::__construct ( void )

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


Returns a representation that can be converted to JSON

  • « MongoDB\BSON\DBPointer::__construct
  • MongoDB\BSON\DBPointer::serialize »
  • PHP Manual
  • MongoDB\BSON\DBPointer
  • Returns a representation that can be converted to JSON

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 ( void ) : 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


Serialize a DBPointer

  • « MongoDB\BSON\DBPointer::jsonSerialize
  • MongoDB\BSON\DBPointer::__toString »
  • PHP Manual
  • MongoDB\BSON\DBPointer
  • Serialize a DBPointer

MongoDB\BSON\DBPointer::serialize

(mongodb >=1.4.0)

MongoDB\BSON\DBPointer::serialize — Serialize a DBPointer

Description

final public MongoDB\BSON\DBPointer::serialize ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns the serialized representation of the MongoDB\BSON\DBPointer.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

See Also

  • MongoDB\BSON\DBPointer::unserialize() - Unserialize a DBPointer
  • serialize() - Generates a storable representation of a value
  • Serializing Objects


Returns an empty string

  • « MongoDB\BSON\DBPointer::serialize
  • MongoDB\BSON\DBPointer::unserialize »
  • PHP Manual
  • MongoDB\BSON\DBPointer
  • Returns an empty string

MongoDB\BSON\DBPointer::__toString

(mongodb >=1.4.0)

MongoDB\BSON\DBPointer::__toString — Returns an empty string

Description

final public MongoDB\BSON\DBPointer::__toString ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns an empty string.

See Also

  • » BSON Types


Unserialize a DBPointer

  • « MongoDB\BSON\DBPointer::__toString
  • MongoDB\BSON\Int64 »
  • PHP Manual
  • MongoDB\BSON\DBPointer
  • Unserialize a DBPointer

MongoDB\BSON\DBPointer::unserialize

(mongodb >=1.4.0)

MongoDB\BSON\DBPointer::unserialize — Unserialize a DBPointer

Description

final public MongoDB\BSON\DBPointer::unserialize ( string $serialized ) : void

Parameters

serialized

The serialized MongoDB\BSON\DBPointer.

Return Values

Returns the unserialized MongoDB\BSON\DBPointer.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

See Also

  • MongoDB\BSON\DBPointer::serialize() - Serialize a DBPointer
  • unserialize() - Creates a PHP value from a stored representation
  • Serializing Objects


The MongoDB\BSON\Int64 class

(mongodb >=1.5.0)

Introduction

BSON type for a 64-bit integer. This class cannot be instantiated and is only created during BSON decoding when a 64-bit integer cannot be represented as a PHP integer on a 32-bit platform. Versions of the driver before 1.5.0 would throw an exception when attempting to decode a 64-bit integer on a 32-bit platform.

During BSON encoding, objects of this class will convert back to a 64-bit integer type. This allows 64-bit integers to be roundtripped through a 32-bit PHP environment without any loss of precision. The __toString() method allows the 64-bit integer value to be accessed as a string.

Note: This class exists purely for 32-bit platforms. Applications on 64-bit platforms (i.e. PHP_INT_SIZE is 8) should never encounter this class during normal operation.

Class synopsis

final MongoDB\BSON\Int64 implements MongoDB\BSON\Type , Serializable , JsonSerializable {
/* Methods */
final private __construct ( void )
final public jsonSerialize ( void ) : mixed
final public serialize ( void ) : string
final public __toString ( void ) : string
final public unserialize ( string $serialized ) : void
}

Table of Contents

  • MongoDB\BSON\Int64::__construct — Construct a new Int64 (unused)
  • MongoDB\BSON\Int64::jsonSerialize — Returns a representation that can be converted to JSON
  • MongoDB\BSON\Int64::serialize — Serialize an Int64
  • MongoDB\BSON\Int64::__toString — Returns the string representation of this Int64
  • MongoDB\BSON\Int64::unserialize — Unserialize an Int64


Construct a new Int64 (unused)

  • « MongoDB\BSON\Int64
  • MongoDB\BSON\Int64::jsonSerialize »
  • PHP Manual
  • MongoDB\BSON\Int64
  • Construct a new Int64 (unused)

MongoDB\BSON\Int64::__construct

(mongodb >=1.5.0)

MongoDB\BSON\Int64::__construct — Construct a new Int64 (unused)

Description

final private MongoDB\BSON\Int64::__construct ( void )

MongoDB\BSON\Int64 objects are created through conversion from a 64-bit integer BSON type on a 32-bit platform and cannot be constructed directly.

Parameters

This function has no parameters.

See Also

  • » BSON Types


Returns a representation that can be converted to JSON

  • « MongoDB\BSON\Int64::__construct
  • MongoDB\BSON\Int64::serialize »
  • PHP Manual
  • MongoDB\BSON\Int64
  • Returns a representation that can be converted to JSON

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 ( void ) : 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


Serialize an Int64

  • « MongoDB\BSON\Int64::jsonSerialize
  • MongoDB\BSON\Int64::__toString »
  • PHP Manual
  • MongoDB\BSON\Int64
  • Serialize an Int64

MongoDB\BSON\Int64::serialize

(mongodb >=1.5.0)

MongoDB\BSON\Int64::serialize — Serialize an Int64

Description

final public MongoDB\BSON\Int64::serialize ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns the serialized representation of the MongoDB\BSON\Int64.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

See Also

  • MongoDB\BSON\Int64::unserialize() - Unserialize an Int64
  • serialize() - Generates a storable representation of a value
  • Serializing Objects


Returns the string representation of this Int64

  • « MongoDB\BSON\Int64::serialize
  • MongoDB\BSON\Int64::unserialize »
  • PHP Manual
  • MongoDB\BSON\Int64
  • Returns the string representation of this Int64

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 ( void ) : 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 = unserialize('C:18:"MongoDB\BSON\Int64":47:{a:1:{s:7:"integer";s:19:"9223372036854775807";}}');

var_dump((string) $int64);

?>

The above example will output something similar to:

string(19) "9223372036854775807"

See Also

  • » BSON Types


Unserialize an Int64

  • « MongoDB\BSON\Int64::__toString
  • MongoDB\BSON\Symbol »
  • PHP Manual
  • MongoDB\BSON\Int64
  • Unserialize an Int64

MongoDB\BSON\Int64::unserialize

(mongodb >=1.5.0)

MongoDB\BSON\Int64::unserialize — Unserialize an Int64

Description

final public MongoDB\BSON\Int64::unserialize ( string $serialized ) : void

Parameters

serialized

The serialized MongoDB\BSON\Int64.

Return Values

Returns the unserialized MongoDB\BSON\Int64.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

See Also

  • MongoDB\BSON\Int64::serialize() - Serialize an Int64
  • unserialize() - Creates a PHP value from a stored representation
  • Serializing Objects


The MongoDB\BSON\Symbol class (deprecated)

(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 MongoDB\BSON\Symbol implements MongoDB\BSON\Type , Serializable , JsonSerializable {
/* Methods */
final private __construct ( void )
final public jsonSerialize ( void ) : mixed
final public serialize ( void ) : string
final public __toString ( void ) : string
final public unserialize ( string $serialized ) : void
}

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::serialize — Serialize a Symbol
  • MongoDB\BSON\Symbol::__toString — Returns the Symbol as a string
  • MongoDB\BSON\Symbol::unserialize — Unserialize a Symbol


Construct a new Symbol (unused)

  • « MongoDB\BSON\Symbol
  • MongoDB\BSON\Symbol::jsonSerialize »
  • PHP Manual
  • MongoDB\BSON\Symbol
  • Construct a new Symbol (unused)

MongoDB\BSON\Symbol::__construct

(mongodb >=1.4.0)

MongoDB\BSON\Symbol::__construct — Construct a new Symbol (unused)

Description

final private MongoDB\BSON\Symbol::__construct ( void )

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


Returns a representation that can be converted to JSON

  • « MongoDB\BSON\Symbol::__construct
  • MongoDB\BSON\Symbol::serialize »
  • PHP Manual
  • MongoDB\BSON\Symbol
  • Returns a representation that can be converted to JSON

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 ( void ) : 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


Serialize a Symbol

  • « MongoDB\BSON\Symbol::jsonSerialize
  • MongoDB\BSON\Symbol::__toString »
  • PHP Manual
  • MongoDB\BSON\Symbol
  • Serialize a Symbol

MongoDB\BSON\Symbol::serialize

(mongodb >=1.4.0)

MongoDB\BSON\Symbol::serialize — Serialize a Symbol

Description

final public MongoDB\BSON\Symbol::serialize ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns the serialized representation of the MongoDB\BSON\Symbol.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

See Also

  • MongoDB\BSON\Symbol::unserialize() - Unserialize a Symbol
  • serialize() - Generates a storable representation of a value
  • Serializing Objects


Returns the Symbol as a string

  • « MongoDB\BSON\Symbol::serialize
  • MongoDB\BSON\Symbol::unserialize »
  • PHP Manual
  • MongoDB\BSON\Symbol
  • Returns the Symbol as a string

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 ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns the string representation of this Symbol.

See Also

  • » BSON Types


Unserialize a Symbol

  • « MongoDB\BSON\Symbol::__toString
  • MongoDB\BSON\Undefined »
  • PHP Manual
  • MongoDB\BSON\Symbol
  • Unserialize a Symbol

MongoDB\BSON\Symbol::unserialize

(mongodb >=1.4.0)

MongoDB\BSON\Symbol::unserialize — Unserialize a Symbol

Description

final public MongoDB\BSON\Symbol::unserialize ( string $serialized ) : void

Parameters

serialized

The serialized MongoDB\BSON\Symbol.

Return Values

Returns the unserialized MongoDB\BSON\Symbol.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

See Also

  • MongoDB\BSON\Symbol::serialize() - Serialize a Symbol
  • unserialize() - Creates a PHP value from a stored representation
  • Serializing Objects


The MongoDB\BSON\Undefined class (deprecated)

(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 MongoDB\BSON\Undefined implements MongoDB\BSON\Type , Serializable , JsonSerializable {
/* Methods */
final private __construct ( void )
final public jsonSerialize ( void ) : mixed
final public serialize ( void ) : string
final public __toString ( void ) : string
final public unserialize ( string $serialized ) : void
}

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::serialize — Serialize a Undefined
  • MongoDB\BSON\Undefined::__toString — Returns an empty string
  • MongoDB\BSON\Undefined::unserialize — Unserialize a Undefined


Construct a new Undefined (unused)

  • « MongoDB\BSON\Undefined
  • MongoDB\BSON\Undefined::jsonSerialize »
  • PHP Manual
  • MongoDB\BSON\Undefined
  • Construct a new Undefined (unused)

MongoDB\BSON\Undefined::__construct

(mongodb >=1.4.0)

MongoDB\BSON\Undefined::__construct — Construct a new Undefined (unused)

Description

final private MongoDB\BSON\Undefined::__construct ( void )

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


Returns a representation that can be converted to JSON

  • « MongoDB\BSON\Undefined::__construct
  • MongoDB\BSON\Undefined::serialize »
  • PHP Manual
  • MongoDB\BSON\Undefined
  • Returns a representation that can be converted to JSON

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 ( void ) : 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


Serialize a Undefined

  • « MongoDB\BSON\Undefined::jsonSerialize
  • MongoDB\BSON\Undefined::__toString »
  • PHP Manual
  • MongoDB\BSON\Undefined
  • Serialize a Undefined

MongoDB\BSON\Undefined::serialize

(mongodb >=1.4.0)

MongoDB\BSON\Undefined::serialize — Serialize a Undefined

Description

final public MongoDB\BSON\Undefined::serialize ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns the serialized representation of the MongoDB\BSON\Undefined.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

See Also

  • MongoDB\BSON\Undefined::unserialize() - Unserialize a Undefined
  • serialize() - Generates a storable representation of a value
  • Serializing Objects


Returns an empty string

  • « MongoDB\BSON\Undefined::serialize
  • MongoDB\BSON\Undefined::unserialize »
  • PHP Manual
  • MongoDB\BSON\Undefined
  • Returns an empty string

MongoDB\BSON\Undefined::__toString

(mongodb >=1.4.0)

MongoDB\BSON\Undefined::__toString — Returns an empty string

Description

final public MongoDB\BSON\Undefined::__toString ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns an empty string.

See Also

  • » BSON Types


Unserialize a Undefined

  • « MongoDB\BSON\Undefined::__toString
  • MongoDB\Driver\Monitoring »
  • PHP Manual
  • MongoDB\BSON\Undefined
  • Unserialize a Undefined

MongoDB\BSON\Undefined::unserialize

(mongodb >=1.4.0)

MongoDB\BSON\Undefined::unserialize — Unserialize a Undefined

Description

final public MongoDB\BSON\Undefined::unserialize ( string $serialized ) : void

Parameters

serialized

The serialized MongoDB\BSON\Undefined.

Return Values

Returns the unserialized MongoDB\BSON\Undefined.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

See Also

  • MongoDB\BSON\Undefined::serialize() - Serialize a Undefined
  • unserialize() - Creates a PHP value from a stored representation
  • Serializing Objects


Monitoring classes and subscriber functions

  • Functions
    • MongoDB\Driver\Monitoring\addSubscriber — Registers a new monitoring event subscriber
    • MongoDB\Driver\Monitoring\removeSubscriber — Unregisters an existing monitoring event subscriber
  • MongoDB\Driver\Monitoring\CommandFailedEvent — The MongoDB\Driver\Monitoring\CommandFailedEvent class
    • MongoDB\Driver\Monitoring\CommandFailedEvent::getCommandName — Returns the command name
    • 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::getOperationId — Returns the command's operation ID
    • 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\CommandStartedEvent — The MongoDB\Driver\Monitoring\CommandStartedEvent class
    • 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::getOperationId — Returns the command's operation ID
    • 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\CommandSucceededEvent — The MongoDB\Driver\Monitoring\CommandSucceededEvent class
    • MongoDB\Driver\Monitoring\CommandSucceededEvent::getCommandName — Returns the command name
    • MongoDB\Driver\Monitoring\CommandSucceededEvent::getDurationMicros — Returns the command's duration in microseconds
    • MongoDB\Driver\Monitoring\CommandSucceededEvent::getOperationId — Returns the command's operation ID
    • 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\CommandSubscriber — The MongoDB\Driver\Monitoring\CommandSubscriber interface
    • 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
  • MongoDB\Driver\Monitoring\Subscriber — The MongoDB\Driver\Monitoring\Subscriber interface


Functions

Table of Contents

  • MongoDB\Driver\Monitoring\addSubscriber — Registers a new monitoring event subscriber
  • MongoDB\Driver\Monitoring\removeSubscriber — Unregisters an existing monitoring event subscriber


Registers a new monitoring event subscriber

  • « Functions
  • MongoDB\Driver\Monitoring\removeSubscriber »
  • PHP Manual
  • Functions
  • Registers a new monitoring event subscriber

MongoDB\Driver\Monitoring\addSubscriber

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\addSubscriber — Registers a new monitoring event subscriber

Description

MongoDB\Driver\Monitoring\addSubscriber ( MongoDB\Driver\Monitoring\Subscriber $subscriber ) : void

Registers a new monitoring event subscriber with the driver. Registered subscribers will be notified of monitoring events through specific methods.

Note: If the object is already registered, this function is a no-op.

Parameters

subscriber (MongoDB\Driver\Monitoring\Subscriber)

A monitoring event subscriber object to register.

Return Values

No value is returned.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

See Also

  • MongoDB\Driver\Monitoring\Subscriber
  • MongoDB\Driver\Monitoring\CommandSubscriber
  • MongoDB\Driver\Monitoring\removeSubscriber() - Unregisters an existing monitoring event subscriber
  • Application Performance Monitoring (APM)


Unregisters an existing monitoring event subscriber

  • « MongoDB\Driver\Monitoring\addSubscriber
  • MongoDB\Driver\Monitoring\CommandFailedEvent »
  • PHP Manual
  • Functions
  • Unregisters an existing monitoring event subscriber

MongoDB\Driver\Monitoring\removeSubscriber

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\removeSubscriber — Unregisters an existing monitoring event subscriber

Description

MongoDB\Driver\Monitoring\removeSubscriber ( MongoDB\Driver\Monitoring\Subscriber $subscriber ) : void

Unregisters an existing monitoring event subscriber from the driver. Unregistered subscribers will no longer be notified of monitoring events.

Note: If the object is not registered, this function is a no-op.

Parameters

subscriber (MongoDB\Driver\Monitoring\Subscriber)

A monitoring event subscriber object to unregister.

Return Values

No value is returned.

Errors/Exceptions

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

See Also

  • MongoDB\Driver\Monitoring\Subscriber
  • MongoDB\Driver\Monitoring\CommandSubscriber
  • MongoDB\Driver\Monitoring\addSubscriber() - Registers a new monitoring event subscriber
  • Application Performance Monitoring (APM)


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 MongoDB\Driver\Monitoring\CommandFailedEvent {
/* Methods */
final public getCommandName ( void ) : string
final public getDurationMicros ( void ) : int
final public getError ( void ) : Exception
final public getOperationId ( void ) : string
final public getReply ( void ) : object
final public getRequestId ( void ) : string
final public getServer ( void ) : MongoDB\Driver\Server
}

Table of Contents

  • MongoDB\Driver\Monitoring\CommandFailedEvent::getCommandName — Returns the command name
  • 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::getOperationId — Returns the command's operation ID
  • 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


Returns the command name

  • « MongoDB\Driver\Monitoring\CommandFailedEvent
  • MongoDB\Driver\Monitoring\CommandFailedEvent::getDurationMicros »
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandFailedEvent
  • Returns the command name

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 ( void ) : 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)


Returns the command's duration in microseconds

  • « MongoDB\Driver\Monitoring\CommandFailedEvent::getCommandName
  • MongoDB\Driver\Monitoring\CommandFailedEvent::getError »
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandFailedEvent
  • Returns the command's duration in microseconds

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 ( void ) : 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)


Returns the Exception associated with the failed command

  • « MongoDB\Driver\Monitoring\CommandFailedEvent::getDurationMicros
  • MongoDB\Driver\Monitoring\CommandFailedEvent::getOperationId »
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandFailedEvent
  • Returns the Exception associated with the failed command

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 ( void ) : 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)


Returns the command's operation ID

  • « MongoDB\Driver\Monitoring\CommandFailedEvent::getError
  • MongoDB\Driver\Monitoring\CommandFailedEvent::getReply »
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandFailedEvent
  • Returns the command's operation ID

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 ( void ) : string

The operation ID is generated by the driver 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)


Returns the command reply document

  • « MongoDB\Driver\Monitoring\CommandFailedEvent::getOperationId
  • MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId »
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandFailedEvent
  • Returns the command reply document

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 ( void ) : 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


Returns the command's request ID

  • « MongoDB\Driver\Monitoring\CommandFailedEvent::getReply
  • MongoDB\Driver\Monitoring\CommandFailedEvent::getServer »
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandFailedEvent
  • Returns the command's request ID

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 ( void ) : string

The request ID is generated by the driver 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)


Returns the Server on which the command was executed

  • « MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId
  • MongoDB\Driver\Monitoring\CommandStartedEvent »
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandFailedEvent
  • Returns the Server on which the command was executed

MongoDB\Driver\Monitoring\CommandFailedEvent::getServer

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandFailedEvent::getServer — Returns the Server on which the command was executed

Description

final public MongoDB\Driver\Monitoring\CommandFailedEvent::getServer ( void ) : 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.

See Also

  • MongoDB\Driver\Monitoring\CommandStartedEvent::getServer() - Returns the Server on which the command was executed
  • Application Performance Monitoring (APM)


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 MongoDB\Driver\Monitoring\CommandStartedEvent {
/* Methods */
final public getCommand ( void ) : object
final public getCommandName ( void ) : string
final public getDatabaseName ( void ) : string
final public getOperationId ( void ) : string
final public getRequestId ( void ) : string
final public getServer ( void ) : MongoDB\Driver\Server
}

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::getOperationId — Returns the command's operation ID
  • 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


Returns the command document

  • « MongoDB\Driver\Monitoring\CommandStartedEvent
  • MongoDB\Driver\Monitoring\CommandStartedEvent::getCommandName »
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandStartedEvent
  • Returns the command document

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 ( void ) : 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


Returns the command name

  • « MongoDB\Driver\Monitoring\CommandStartedEvent::getCommand
  • MongoDB\Driver\Monitoring\CommandStartedEvent::getDatabaseName »
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandStartedEvent
  • Returns the command name

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 ( void ) : 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)


Returns the database on which the command was executed

  • « MongoDB\Driver\Monitoring\CommandStartedEvent::getCommandName
  • MongoDB\Driver\Monitoring\CommandStartedEvent::getOperationId »
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandStartedEvent
  • Returns the database on which the command was executed

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 ( void ) : 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)


Returns the command's operation ID

  • « MongoDB\Driver\Monitoring\CommandStartedEvent::getDatabaseName
  • MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId »
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandStartedEvent
  • Returns the command's operation ID

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 ( void ) : string

The operation ID is generated by the driver 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)


Returns the command's request ID

  • « MongoDB\Driver\Monitoring\CommandStartedEvent::getOperationId
  • MongoDB\Driver\Monitoring\CommandStartedEvent::getServer »
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandStartedEvent
  • Returns the command's request ID

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 ( void ) : string

The request ID is generated by the driver 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)


Returns the Server on which the command was executed

  • « MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId
  • MongoDB\Driver\Monitoring\CommandSucceededEvent »
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandStartedEvent
  • Returns the Server on which the command was executed

MongoDB\Driver\Monitoring\CommandStartedEvent::getServer

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandStartedEvent::getServer — Returns the Server on which the command was executed

Description

final public MongoDB\Driver\Monitoring\CommandStartedEvent::getServer ( void ) : 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.

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)


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 MongoDB\Driver\Monitoring\CommandSucceededEvent {
/* Methods */
final public getCommandName ( void ) : string
final public getDurationMicros ( void ) : int
final public getOperationId ( void ) : string
final public getReply ( void ) : object
final public getRequestId ( void ) : string
final public getServer ( void ) : MongoDB\Driver\Server
}

Table of Contents

  • MongoDB\Driver\Monitoring\CommandSucceededEvent::getCommandName — Returns the command name
  • MongoDB\Driver\Monitoring\CommandSucceededEvent::getDurationMicros — Returns the command's duration in microseconds
  • MongoDB\Driver\Monitoring\CommandSucceededEvent::getOperationId — Returns the command's operation ID
  • 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


Returns the command name

  • « MongoDB\Driver\Monitoring\CommandSucceededEvent
  • MongoDB\Driver\Monitoring\CommandSucceededEvent::getDurationMicros »
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandSucceededEvent
  • Returns the command name

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 ( void ) : 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)


Returns the command's duration in microseconds

  • « MongoDB\Driver\Monitoring\CommandSucceededEvent::getCommandName
  • MongoDB\Driver\Monitoring\CommandSucceededEvent::getOperationId »
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandSucceededEvent
  • Returns the command's duration in microseconds

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 ( void ) : 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)


Returns the command's operation ID

  • « MongoDB\Driver\Monitoring\CommandSucceededEvent::getDurationMicros
  • MongoDB\Driver\Monitoring\CommandSucceededEvent::getReply »
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandSucceededEvent
  • Returns the command's operation ID

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 ( void ) : string

The operation ID is generated by the driver 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)


Returns the command reply document

  • « MongoDB\Driver\Monitoring\CommandSucceededEvent::getOperationId
  • MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId »
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandSucceededEvent
  • Returns the command reply document

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 ( void ) : 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


Returns the command's request ID

  • « MongoDB\Driver\Monitoring\CommandSucceededEvent::getReply
  • MongoDB\Driver\Monitoring\CommandSucceededEvent::getServer »
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandSucceededEvent
  • Returns the command's request ID

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 ( void ) : string

The request ID is generated by the driver 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)


Returns the Server on which the command was executed

  • « MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId
  • MongoDB\Driver\Monitoring\CommandSubscriber »
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandSucceededEvent
  • Returns the Server on which the command was executed

MongoDB\Driver\Monitoring\CommandSucceededEvent::getServer

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandSucceededEvent::getServer — Returns the Server on which the command was executed

Description

final public MongoDB\Driver\Monitoring\CommandSucceededEvent::getServer ( void ) : 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.

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)


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

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
}

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


Notification method for a failed command

  • « MongoDB\Driver\Monitoring\CommandSubscriber
  • MongoDB\Driver\Monitoring\CommandSubscriber::commandStarted »
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandSubscriber
  • Notification method for a failed command

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 has been registered with MongoDB\Driver\Monitoring\addSubscriber(), the driver will call this method when a command has failed.

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 new monitoring event subscriber
  • Application Performance Monitoring (APM)


Notification method for a started command

  • « MongoDB\Driver\Monitoring\CommandSubscriber::commandFailed
  • MongoDB\Driver\Monitoring\CommandSubscriber::commandSucceeded »
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandSubscriber
  • Notification method for a started command

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 has been registered with MongoDB\Driver\Monitoring\addSubscriber(), the driver will call this method when a command has started.

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 new monitoring event subscriber
  • Application Performance Monitoring (APM)


Notification method for a successful command

  • « MongoDB\Driver\Monitoring\CommandSubscriber::commandStarted
  • MongoDB\Driver\Monitoring\Subscriber »
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandSubscriber
  • Notification method for a successful command

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 has been registered with MongoDB\Driver\Monitoring\addSubscriber(), the driver will call this method when a command has succeeded.

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 new monitoring event subscriber
  • Application Performance Monitoring (APM)


The MongoDB\Driver\Monitoring\Subscriber interface

(mongodb >=1.3.0)

Introduction

Base interface for event subscribers. This is used for type-hinting MongoDB\Driver\Monitoring\addSubscriber() and MongoDB\Driver\Monitoring\removeSubscriber() and should not be implemented directly.

Interface synopsis

MongoDB\Driver\Monitoring\Subscriber {
}

This interface has no methods. Its only purpose is to be the base interface for all event subscribers.


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\CommandException — The MongoDB\Driver\Exception\CommandException class
    • MongoDB\Driver\Exception\CommandException::getResultDocument — Returns the result document for the failed command
  • 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\RuntimeException::hasErrorLabel — Returns whether an error label is associated with an exception
  • MongoDB\Driver\Exception\ServerException — The MongoDB\Driver\Exception\ServerException class
  • MongoDB\Driver\Exception\SSLConnectionException — The MongoDB\Driver\Exception\SSLConnectionException class (deprecated)
  • MongoDB\Driver\Exception\UnexpectedValueException — The MongoDB\Driver\Exception\UnexpectedValueException class
  • MongoDB\Driver\Exception\WriteException — The MongoDB\Driver\Exception\WriteException class
    • MongoDB\Driver\Exception\WriteException::getWriteResult — Returns the WriteResult for the failed write operation
  • Class Tree — MongoDB Exception 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

MongoDB\Driver\Exception\AuthenticationException extends MongoDB\Driver\Exception\ConnectionException implements MongoDB\Driver\Exception\Exception {
/* Inherited properties */
protected bool $errorLabels ;
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel ( string $errorLabel ) : bool
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The MongoDB\Driver\Exception\BulkWriteException class

(mongodb >= 1.0.0)

Introduction

Thrown when a bulk write operation fails.

Class synopsis

MongoDB\Driver\Exception\BulkWriteException extends MongoDB\Driver\Exception\WriteException implements MongoDB\Driver\Exception\Exception {
/* Inherited properties */
protected MongoDB\Driver\WriteResult $writeResult ;
protected bool $errorLabels ;
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public MongoDB\Driver\Exception\WriteException::getWriteResult ( void ) : MongoDB\Driver\WriteResult
final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel ( string $errorLabel ) : bool
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The MongoDB\Driver\Exception\CommandException class

(mongodb >= 1.5.0)

Introduction

Thrown when a command fails.

Class synopsis

MongoDB\Driver\Exception\CommandException extends MongoDB\Driver\Exception\ServerException implements MongoDB\Driver\Exception\Exception {
/* Properties */
protected object $resultDocument ;
/* Inherited properties */
protected bool $errorLabels ;
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Methods */
final public getResultDocument ( void ) : object
/* Inherited methods */
final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel ( string $errorLabel ) : bool
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}

Properties

resultDocument

The result document associated with the failed command.

Table of Contents

  • MongoDB\Driver\Exception\CommandException::getResultDocument — Returns the result document for the failed command


Returns the result document for the failed command

  • « MongoDB\Driver\Exception\CommandException
  • MongoDB\Driver\Exception\ConnectionException »
  • PHP Manual
  • MongoDB\Driver\Exception\CommandException
  • Returns the result document for 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 ( void ) : 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


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

MongoDB\Driver\Exception\ConnectionException extends MongoDB\Driver\Exception\RuntimeException implements MongoDB\Driver\Exception\Exception {
/* Inherited properties */
protected bool $errorLabels ;
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel ( string $errorLabel ) : bool
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : 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 MongoDB\Driver\Exception\ConnectionTimeoutException extends MongoDB\Driver\Exception\ConnectionException implements MongoDB\Driver\Exception\Exception {
/* Inherited properties */
protected bool $errorLabels ;
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel ( string $errorLabel ) : bool
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The MongoDB\Driver\Exception\EncryptionException class

(mongodb >= 1.7.0)

Introduction

Base class for exceptions thrown during client-side encryption.

Class synopsis

MongoDB\Driver\Exception\EncryptionException extends MongoDB\Driver\Exception\RuntimeException implements MongoDB\Driver\Exception\Exception {
/* Inherited properties */
protected bool $errorLabels ;
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel ( string $errorLabel ) : bool
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The MongoDB\Driver\Exception\Exception interface

(mongodb >= 1.0.0)

Introduction

Common interface for all driver exceptions. This may be used to catch only exceptions originating from the driver itself.

Class synopsis

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 MongoDB\Driver\Exception\ExecutionTimeoutException extends MongoDB\Driver\Exception\ServerException implements MongoDB\Driver\Exception\Exception {
/* Inherited properties */
protected bool $errorLabels ;
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel ( string $errorLabel ) : bool
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}

Changelog

Version | Description
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

MongoDB\Driver\Exception\InvalidArgumentException extends InvalidArgumentException implements MongoDB\Driver\Exception\Exception {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : 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

MongoDB\Driver\Exception\LogicException extends LogicException implements MongoDB\Driver\Exception\Exception {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : 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

MongoDB\Driver\Exception\RuntimeException extends RuntimeException implements MongoDB\Driver\Exception\Exception {
/* Properties */
protected bool $errorLabels ;
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Methods */
final public hasErrorLabel ( string $errorLabel ) : bool
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : 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
1.6.0 | The MongoDB\Driver\Exception\RuntimeException::hasErrorLabel() method and MongoDB\Driver\Exception\RuntimeException::errorLabels property have been added.

Table of Contents

  • MongoDB\Driver\Exception\RuntimeException::hasErrorLabel — Returns whether an error label is associated with an exception


Returns whether an error label is associated with an exception

  • « MongoDB\Driver\Exception\RuntimeException
  • MongoDB\Driver\Exception\ServerException »
  • PHP Manual
  • MongoDB\Driver\Exception\RuntimeException
  • Returns whether an error label is associated with an exception

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 driver to indicated specific situations on which you might want to decide on how you want to handle a specific exception. A common situation might be to find out whether you can safely retry a transaction that failed due to a transient error (like a networking issue, or a 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


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

MongoDB\Driver\Exception\ServerException extends MongoDB\Driver\Exception\RuntimeException implements MongoDB\Driver\Exception\Exception {
/* Inherited properties */
protected bool $errorLabels ;
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel ( string $errorLabel ) : bool
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The MongoDB\Driver\Exception\SSLConnectionException class (deprecated)

(mongodb >= 1.0.0)

Warning

This exception class is deprecated and may be removed in a future major version. The driver has never thrown this exception.

Introduction

Thrown when the driver fails to establish an SSL connection with the server.

Class synopsis

final MongoDB\Driver\Exception\SSLConnectionException extends MongoDB\Driver\Exception\ConnectionException implements MongoDB\Driver\Exception\Exception {
/* Inherited properties */
protected bool $errorLabels ;
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel ( string $errorLabel ) : bool
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : 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

MongoDB\Driver\Exception\UnexpectedValueException extends UnexpectedValueException implements MongoDB\Driver\Exception\Exception {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The MongoDB\Driver\Exception\WriteException class

(mongodb >= 1.0.0)

Introduction

Base class for exceptions thrown by a failed write operation. The exception encapsulates a MongoDB\Driver\WriteResult object.

Class synopsis

abstract MongoDB\Driver\Exception\WriteException extends MongoDB\Driver\Exception\ServerException implements MongoDB\Driver\Exception\Exception {
/* Properties */
protected MongoDB\Driver\WriteResult $writeResult ;
/* Inherited properties */
protected bool $errorLabels ;
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Methods */
final public getWriteResult ( void ) : MongoDB\Driver\WriteResult
/* Inherited methods */
final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel ( string $errorLabel ) : bool
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}

Properties

writeResult

The MongoDB\Driver\WriteResult associated with the failed write operation.

Changelog

Version | Description
1.5.0 | This class now extends MongoDB\Driver\Exception\ServerException instead of MongoDB\Driver\Exception\RuntimeException.

Table of Contents

  • MongoDB\Driver\Exception\WriteException::getWriteResult — Returns the WriteResult for the failed write operation


Returns the WriteResult for the failed write operation

  • « MongoDB\Driver\Exception\WriteException
  • Class Tree »
  • PHP Manual
  • MongoDB\Driver\Exception\WriteException
  • Returns the WriteResult for the failed write operation

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 ( void ) : 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


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\CommandException
      • MongoDB\Driver\Exception\ExecutionTimeoutException
      • MongoDB\Driver\Exception\WriteException
        • MongoDB\Driver\Exception\BulkWriteException


mSQL

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
  • mSQL Functions
    • msql_affected_rows — Returns number of affected rows
    • msql_close — Close mSQL connection
    • msql_connect — Open mSQL connection
    • msql_create_db — Create mSQL database
    • msql_createdb — Alias of msql_create_db
    • msql_data_seek — Move internal row pointer
    • msql_db_query — Send mSQL query
    • msql_dbname — Alias of msql_result
    • msql_drop_db — Drop (delete) mSQL database
    • msql_error — Returns error message of last msql call
    • msql_fetch_array — Fetch row as array
    • msql_fetch_field — Get field information
    • msql_fetch_object — Fetch row as object
    • msql_fetch_row — Get row as enumerated array
    • msql_field_flags — Get field flags
    • msql_field_len — Get field length
    • msql_field_name — Get the name of the specified field in a result
    • msql_field_seek — Set field offset
    • msql_field_table — Get table name for field
    • msql_field_type — Get field type
    • msql_fieldflags — Alias of msql_field_flags
    • msql_fieldlen — Alias of msql_field_len
    • msql_fieldname — Alias of msql_field_name
    • msql_fieldtable — Alias of msql_field_table
    • msql_fieldtype — Alias of msql_field_type
    • msql_free_result — Free result memory
    • msql_list_dbs — List mSQL databases on server
    • msql_list_fields — List result fields
    • msql_list_tables — List tables in an mSQL database
    • msql_num_fields — Get number of fields in result
    • msql_num_rows — Get number of rows in result
    • msql_numfields — Alias of msql_num_fields
    • msql_numrows — Alias of msql_num_rows
    • msql_pconnect — Open persistent mSQL connection
    • msql_query — Send mSQL query
    • msql_regcase — Alias of sql_regcase
    • msql_result — Get result data
    • msql_select_db — Select mSQL database
    • msql_tablename — Alias of msql_result
    • msql — Alias of msql_db_query


Introduction

These functions allow you to access mSQL database servers. More information about mSQL can be found at » http://www.hughes.com.au/.


Installation

In order to have these functions available, you must compile PHP with msql support by using the --with-msql[=DIR] option. DIR is the mSQL base install directory, defaults to /usr/local/msql3.

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: msql.dll


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

mSQL configuration options
Name | Default | Changeable | Changelog
msql.allow_persistent | "1" | PHP_INI_ALL |
msql.max_persistent | "-1" | PHP_INI_ALL |
msql.max_links | "-1" | PHP_INI_ALL |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

msql.allow_persistent boolean

Whether to allow persistent mSQL connections.

msql.max_persistent integer

The maximum number of persistent mSQL connections per process.

msql.max_links integer

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


Resource Types

There are two resource types used in the mSQL 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.

MSQL_ASSOC (integer)
MSQL_NUM (integer)
MSQL_BOTH (integer)


  • « Predefined Constants
  • Basic usage »
  • PHP Manual
  • mSQL
  • Examples

Examples

Table of Contents

  • Basic usage


Basic usage

This simple example shows how to connect, execute a query, print resulting rows and disconnect from a mSQL database.

Example #1 mSQL usage example

<?php
/* Connecting, selecting database */
$link = msql_connect('localhost', 'username', 'password')
    or die('Could not connect : ' . msql_error($link));

msql_select_db('database', $link)
    or die('Could not select database');

/* Issue SQL query */
$query = 'SELECT * FROM my_table';
$result = msql_query($query, $link) or die('Query failed : ' . msql_error());

/* Printing results in HTML */
echo "<table>\n";
while ($row = msql_fetch_array($result, MSQL_ASSOC)) {
    echo "\t<tr>\n";
    foreach ($row as $col_value) {
        echo "\t\t<td>$col_value</td>\n";
    }
    echo "\t</tr>\n";
}
echo "</table>\n";

/* Free result set */
msql_free_result($result);

/* Close connection */
msql_close($link);
?>


mSQL Functions

Table of Contents

  • msql_affected_rows — Returns number of affected rows
  • msql_close — Close mSQL connection
  • msql_connect — Open mSQL connection
  • msql_create_db — Create mSQL database
  • msql_createdb — Alias of msql_create_db
  • msql_data_seek — Move internal row pointer
  • msql_db_query — Send mSQL query
  • msql_dbname — Alias of msql_result
  • msql_drop_db — Drop (delete) mSQL database
  • msql_error — Returns error message of last msql call
  • msql_fetch_array — Fetch row as array
  • msql_fetch_field — Get field information
  • msql_fetch_object — Fetch row as object
  • msql_fetch_row — Get row as enumerated array
  • msql_field_flags — Get field flags
  • msql_field_len — Get field length
  • msql_field_name — Get the name of the specified field in a result
  • msql_field_seek — Set field offset
  • msql_field_table — Get table name for field
  • msql_field_type — Get field type
  • msql_fieldflags — Alias of msql_field_flags
  • msql_fieldlen — Alias of msql_field_len
  • msql_fieldname — Alias of msql_field_name
  • msql_fieldtable — Alias of msql_field_table
  • msql_fieldtype — Alias of msql_field_type
  • msql_free_result — Free result memory
  • msql_list_dbs — List mSQL databases on server
  • msql_list_fields — List result fields
  • msql_list_tables — List tables in an mSQL database
  • msql_num_fields — Get number of fields in result
  • msql_num_rows — Get number of rows in result
  • msql_numfields — Alias of msql_num_fields
  • msql_numrows — Alias of msql_num_rows
  • msql_pconnect — Open persistent mSQL connection
  • msql_query — Send mSQL query
  • msql_regcase — Alias of sql_regcase
  • msql_result — Get result data
  • msql_select_db — Select mSQL database
  • msql_tablename — Alias of msql_result
  • msql — Alias of msql_db_query


Returns number of affected rows

  • « mSQL Functions
  • msql_close »
  • PHP Manual
  • mSQL Functions
  • Returns number of affected rows

msql_affected_rows

(PHP 4, PHP 5, PHP 7)

msql_affected_rows — Returns number of affected rows

Description

msql_affected_rows ( resource $result ) : int

Returns number of affected rows by the last SELECT, UPDATE or DELETE query associated with result.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

Return Values

Returns the number of affected rows on success, or FALSE on error.

See Also

  • msql_query() - Send mSQL query


Close mSQL connection

  • « msql_affected_rows
  • msql_connect »
  • PHP Manual
  • mSQL Functions
  • Close mSQL connection

msql_close

(PHP 4, PHP 5, PHP 7)

msql_close — Close mSQL connection

Description

msql_close ([ resource $link_identifier ] ) : bool

msql_close() closes the non-persistent connection to the mSQL server that's associated with the specified link identifier.

Using msql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution. See also freeing resources.

Parameters

link_identifier

The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • msql_connect() - Open mSQL connection
  • msql_pconnect() - Open persistent mSQL connection


Open mSQL connection

  • « msql_close
  • msql_create_db »
  • PHP Manual
  • mSQL Functions
  • Open mSQL connection

msql_connect

(PHP 4, PHP 5, PHP 7)

msql_connect — Open mSQL connection

Description

msql_connect ([ string $hostname ] ) : resource

msql_connect() establishes a connection to a mSQL server.

If a second call is made to msql_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 msql_close().

Parameters

hostname

The hostname can also include a port number. e.g. hostname,port.

If not specified, the connection is established by the means of a Unix domain socket, being then more efficient then a localhost TCP socket connection.

Note:

While this function will accept a colon (:) as a host/port separator, a comma (,) is the preferred method.

Return Values

Returns a positive mSQL link identifier on success, or FALSE on error.

See Also

  • msql_pconnect() - Open persistent mSQL connection
  • msql_close() - Close mSQL connection


Create mSQL database

  • « msql_connect
  • msql_createdb »
  • PHP Manual
  • mSQL Functions
  • Create mSQL database

msql_create_db

(PHP 4, PHP 5, PHP 7)

msql_create_db — Create mSQL database

Description

msql_create_db ( string $database_name [, resource $link_identifier ] ) : bool

msql_create_db() attempts to create a new database on the mSQL server.

Parameters

database_name

The name of the mSQL database.

link_identifier

The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • msql_drop_db() - Drop (delete) mSQL database


Alias of msql_create_db

  • « msql_create_db
  • msql_data_seek »
  • PHP Manual
  • mSQL Functions
  • Alias of msql_create_db

msql_createdb

(PHP 4, PHP 5, PHP 7)

msql_createdb — Alias of msql_create_db()

Description

This function is an alias of: msql_create_db().


Move internal row pointer

  • « msql_createdb
  • msql_db_query »
  • PHP Manual
  • mSQL Functions
  • Move internal row pointer

msql_data_seek

(PHP 4, PHP 5, PHP 7)

msql_data_seek — Move internal row pointer

Description

msql_data_seek ( resource $result , int $row_number ) : bool

msql_data_seek() moves the internal row pointer of the mSQL result associated with the specified query identifier to point to the specified row number. The next call to msql_fetch_row() would return that row.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

row_number

The seeked row number.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • msql_fetch_array() - Fetch row as array
  • msql_fetch_object() - Fetch row as object
  • msql_fetch_row() - Get row as enumerated array
  • msql_result() - Get result data


Send mSQL query

  • « msql_data_seek
  • msql_dbname »
  • PHP Manual
  • mSQL Functions
  • Send mSQL query

msql_db_query

(PHP 4, PHP 5, PHP 7)

msql_db_query — Send mSQL query

Description

msql_db_query ( string $database , string $query [, resource $link_identifier ] ) : resource

msql_db_query() selects a database and executes a query on it.

Parameters

database

The name of the mSQL database.

query

The SQL query.

link_identifier

The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.

Return Values

Returns a positive mSQL query identifier to the query result, or FALSE on error.

See Also

  • msql_query() - Send mSQL query


Alias of msql_result

  • « msql_db_query
  • msql_drop_db »
  • PHP Manual
  • mSQL Functions
  • Alias of msql_result

msql_dbname

(PHP 4, PHP 5, PHP 7)

msql_dbname — Alias of msql_result()

Description

This function is an alias of: msql_result().


Drop (delete) mSQL database

  • « msql_dbname
  • msql_error »
  • PHP Manual
  • mSQL Functions
  • Drop (delete) mSQL database

msql_drop_db

(PHP 4, PHP 5, PHP 7)

msql_drop_db — Drop (delete) mSQL database

Description

msql_drop_db ( string $database_name [, resource $link_identifier ] ) : bool

msql_drop_db() attempts to drop (remove) a database from the mSQL server.

Parameters

database_name

The name of the database.

link_identifier

The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • msql_create_db() - Create mSQL database


Returns error message of last msql call

  • « msql_drop_db
  • msql_fetch_array »
  • PHP Manual
  • mSQL Functions
  • Returns error message of last msql call

msql_error

(PHP 4, PHP 5, PHP 7)

msql_error — Returns error message of last msql call

Description

msql_error ( void ) : string

msql_error() returns the last issued error by the mSQL server. Note that only the last error message is accessible with msql_error().

Return Values

The last error message or an empty string if no error was issued.


Fetch row as array

  • « msql_error
  • msql_fetch_field »
  • PHP Manual
  • mSQL Functions
  • Fetch row as array

msql_fetch_array

(PHP 4, PHP 5, PHP 7)

msql_fetch_array — Fetch row as array

Description

msql_fetch_array ( resource $result [, int $result_type ] ) : array

msql_fetch_array() is an extended version of msql_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

An important thing to note is that using msql_fetch_array() is NOT significantly slower than using msql_fetch_row(), while it provides a significant added value.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

result_type

A constant that can take the following values: MSQL_ASSOC, MSQL_NUM, and MSQL_BOTH with MSQL_BOTH being the default.

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Examples

Example #1 msql_fetch_array() example

<?php
$con = msql_connect();
if (!$con) {
    die('Server connection problem: ' . msql_error());
}

if (!msql_select_db('test', $con)) {
    die('Database connection problem: ' . msql_error());
}

$result = msql_query('SELECT id, name FROM people', $con);
if (!$result) {
    die('Query execution problem: ' . msql_error());
}

while ($row = msql_fetch_array($result, MSQL_ASSOC)) {
    echo $row['id'] . ': ' . $row['name'] . "\n";
}

msql_free_result($result);
?>

Changelog

Version | Description
5.0.4 | A bug was fixed when retrieving data from columns containing NULL values. Such columns were not placed into the resulting array.

See Also

  • msql_fetch_row() - Get row as enumerated array
  • msql_fetch_object() - Fetch row as object
  • msql_data_seek() - Move internal row pointer
  • msql_result() - Get result data


Get field information

  • « msql_fetch_array
  • msql_fetch_object »
  • PHP Manual
  • mSQL Functions
  • Get field information

msql_fetch_field

(PHP 4, PHP 5, PHP 7)

msql_fetch_field — Get field information

Description

msql_fetch_field ( resource $result [, int $field_offset = 0 ] ) : object

msql_fetch_field() can be used in order to obtain information about fields in a certain query result.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

field_offset

The field offset. If not specified, the next field that wasn't yet retrieved by msql_fetch_field() is retrieved.

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

  • not_null - 1 if the column cannot be NULL

  • unique - 1 if the column is a unique key

  • type - the type of the column

See Also

  • msql_field_seek() - Set field offset


Fetch row as object

  • « msql_fetch_field
  • msql_fetch_row »
  • PHP Manual
  • mSQL Functions
  • Fetch row as object

msql_fetch_object

(PHP 4, PHP 5, PHP 7)

msql_fetch_object — Fetch row as object

Description

msql_fetch_object ( resource $result ) : object

msql_fetch_object() is similar to msql_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).

Speed-wise, the function is identical to msql_fetch_array(), and almost as quick as msql_fetch_row() (the difference is insignificant).

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

Return Values

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

Examples

Example #1 msql_fetch_object() example

<?php
$con = msql_connect();
if (!$con) {
    die('Server connection problem: ' . msql_error());
}

if (!msql_select_db('test', $con)) {
    die('Database connection problem: ' . msql_error());
}

$result = msql_query('SELECT id, name FROM people', $con);
if (!$result) {
    die('Query execution problem: ' . msql_error());
}

while ($row = msql_fetch_object($result, MSQL_ASSOC)) {
    echo $row->id . ': ' . $row->name . "\n";
}

msql_free_result($result);
?>

Changelog

Version | Description
5.0.4 | A bug was fixed when retrieving data from columns containing NULL values. Such columns were not placed into the resulting array.

See Also

  • msql_fetch_array() - Fetch row as array
  • msql_fetch_row() - Get row as enumerated array
  • msql_data_seek() - Move internal row pointer
  • msql_result() - Get result data


Get row as enumerated array

  • « msql_fetch_object
  • msql_field_flags »
  • PHP Manual
  • mSQL Functions
  • Get row as enumerated array

msql_fetch_row

(PHP 4, PHP 5, PHP 7)

msql_fetch_row — Get row as enumerated array

Description

msql_fetch_row ( resource $result ) : array

msql_fetch_row() fetches one row of data from the result associated with the specified query identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

Subsequent call to msql_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Examples

Example #1 msql_fetch_row() example

<?php
$con = msql_connect();
if (!$con) {
    die('Server connection problem: ' . msql_error());
}

if (!msql_select_db('test', $con)) {
    die('Database connection problem: ' . msql_error());
}

$result = msql_query('SELECT id, name FROM people', $con);
if (!$result) {
    die('Query execution problem: ' . msql_error());
}

while ($row = msql_fetch_row($result)) {
    echo $row[0] . ': ' . $row[1] . "\n";
}

msql_free_result($result);
?>

Changelog

Version | Description
5.0.4 | A bug was fixed when retrieving data from columns containing NULL values. Such columns were not placed into the resulting array.

See Also

  • msql_fetch_array() - Fetch row as array
  • msql_fetch_object() - Fetch row as object
  • msql_data_seek() - Move internal row pointer
  • msql_result() - Get result data


Get field flags

  • « msql_fetch_row
  • msql_field_len »
  • PHP Manual
  • mSQL Functions
  • Get field flags

msql_field_flags

(PHP 4, PHP 5, PHP 7)

msql_field_flags — Get field flags

Description

msql_field_flags ( resource $result , int $field_offset ) : string

msql_field_flags() returns the field flags of the specified field.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

field_offset

The numerical field offset. The field_offset starts at 1.

Return Values

Returns a string containing the field flags of the specified key. This can be: primary key not null, not null, primary key, unique not null or unique.


Get field length

  • « msql_field_flags
  • msql_field_name »
  • PHP Manual
  • mSQL Functions
  • Get field length

msql_field_len

(PHP 4, PHP 5, PHP 7)

msql_field_len — Get field length

Description

msql_field_len ( resource $result , int $field_offset ) : int

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

field_offset

The numerical field offset. The field_offset starts at 1.

Return Values

Returns the length of the specified field or FALSE on error.


Get the name of the specified field in a result

  • « msql_field_len
  • msql_field_seek »
  • PHP Manual
  • mSQL Functions
  • Get the name of the specified field in a result

msql_field_name

(PHP 4, PHP 5, PHP 7)

msql_field_name — Get the name of the specified field in a result

Description

msql_field_name ( resource $result , int $field_offset ) : string

msql_field_name() gets the name of the specified field index.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

field_offset

The numerical field offset. The field_offset starts at 1.

Return Values

The name of the field or FALSE on failure.

See Also

  • msql_field_len() - Get field length


Set field offset

  • « msql_field_name
  • msql_field_table »
  • PHP Manual
  • mSQL Functions
  • Set field offset

msql_field_seek

(PHP 4, PHP 5, PHP 7)

msql_field_seek — Set field offset

Description

msql_field_seek ( resource $result , int $field_offset ) : bool

Seeks to the specified field offset. If the next call to msql_fetch_field() won't include a field offset, this field would be returned.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

field_offset

The numerical field offset. The field_offset starts at 1.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • msql_fetch_field() - Get field information


Get table name for field

  • « msql_field_seek
  • msql_field_type »
  • PHP Manual
  • mSQL Functions
  • Get table name for field

msql_field_table

(PHP 4, PHP 5, PHP 7)

msql_field_table — Get table name for field

Description

msql_field_table ( resource $result , int $field_offset ) : int

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

field_offset

The numerical field offset. The field_offset starts at 1.

Return Values

The name of the table on success or FALSE on failure.


Get field type

  • « msql_field_table
  • msql_fieldflags »
  • PHP Manual
  • mSQL Functions
  • Get field type

msql_field_type

(PHP 4, PHP 5, PHP 7)

msql_field_type — Get field type

Description

msql_field_type ( resource $result , int $field_offset ) : string

msql_field_type() gets the type of the specified field index.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

field_offset

The numerical field offset. The field_offset starts at 1.

Return Values

The type of the field. One of int, char, real, ident, null or unknown. This functions will return FALSE on failure.


Alias of msql_field_flags

  • « msql_field_type
  • msql_fieldlen »
  • PHP Manual
  • mSQL Functions
  • Alias of msql_field_flags

msql_fieldflags

(PHP 4, PHP 5, PHP 7)

msql_fieldflags — Alias of msql_field_flags()

Description

This function is an alias of: msql_field_flags().


Alias of msql_field_len

  • « msql_fieldflags
  • msql_fieldname »
  • PHP Manual
  • mSQL Functions
  • Alias of msql_field_len

msql_fieldlen

(PHP 4, PHP 5, PHP 7)

msql_fieldlen — Alias of msql_field_len()

Description

This function is an alias of: msql_field_len().


Alias of msql_field_name

  • « msql_fieldlen
  • msql_fieldtable »
  • PHP Manual
  • mSQL Functions
  • Alias of msql_field_name

msql_fieldname

(PHP 4, PHP 5, PHP 7)

msql_fieldname — Alias of msql_field_name()

Description

This function is an alias of: msql_field_name().


Alias of msql_field_table

  • « msql_fieldname
  • msql_fieldtype »
  • PHP Manual
  • mSQL Functions
  • Alias of msql_field_table

msql_fieldtable

(PHP 4, PHP 5, PHP 7)

msql_fieldtable — Alias of msql_field_table()

Description

This function is an alias of: msql_field_table().


Alias of msql_field_type

  • « msql_fieldtable
  • msql_free_result »
  • PHP Manual
  • mSQL Functions
  • Alias of msql_field_type

msql_fieldtype

(PHP 4, PHP 5, PHP 7)

msql_fieldtype — Alias of msql_field_type()

Description

This function is an alias of: msql_field_type().


Free result memory

  • « msql_fieldtype
  • msql_list_dbs »
  • PHP Manual
  • mSQL Functions
  • Free result memory

msql_free_result

(PHP 4, PHP 5, PHP 7)

msql_free_result — Free result memory

Description

msql_free_result ( resource $result ) : bool

msql_free_result() frees the memory associated with query_identifier. When PHP completes a request, this memory is freed automatically, so you only need to call this function when you want to make sure you don't use too much memory while the script is running.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

Return Values

Returns TRUE on success or FALSE on failure.


List mSQL databases on server

  • « msql_free_result
  • msql_list_fields »
  • PHP Manual
  • mSQL Functions
  • List mSQL databases on server

msql_list_dbs

(PHP 4, PHP 5, PHP 7)

msql_list_dbs — List mSQL databases on server

Description

msql_list_dbs ([ resource $link_identifier ] ) : resource

msql_list_tables() lists the databases available on the specified link_identifier.

Parameters

link_identifier

The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.

Return Values

Returns a result set which may be traversed with any function that fetches result sets, such as msql_fetch_array(). On failure, this function will return FALSE.

See Also

  • msql_list_tables() - List tables in an mSQL database
  • msql_list_fields() - List result fields


List result fields

  • « msql_list_dbs
  • msql_list_tables »
  • PHP Manual
  • mSQL Functions
  • List result fields

msql_list_fields

(PHP 4, PHP 5, PHP 7)

msql_list_fields — List result fields

Description

msql_list_fields ( string $database , string $tablename [, resource $link_identifier ] ) : resource

msql_list_fields() returns information about the given table.

Parameters

database

The name of the database.

tablename

The name of the table.

link_identifier

The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.

Return Values

Returns a result set which may be traversed with any function that fetches result sets, such as msql_fetch_array(). On failure, this function will return FALSE.

See Also

  • msql_list_tables() - List tables in an mSQL database
  • msql_list_dbs() - List mSQL databases on server


List tables in an mSQL database

  • « msql_list_fields
  • msql_num_fields »
  • PHP Manual
  • mSQL Functions
  • List tables in an mSQL database

msql_list_tables

(PHP 4, PHP 5, PHP 7)

msql_list_tables — List tables in an mSQL database

Description

msql_list_tables ( string $database [, resource $link_identifier ] ) : resource

msql_list_tables() lists the tables on the specified database.

Parameters

database

The name of the database.

link_identifier

The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.

Return Values

Returns a result set which may be traversed with any function that fetches result sets, such as msql_fetch_array(). On failure, this function will return FALSE.

See Also

  • msql_list_fields() - List result fields
  • msql_list_dbs() - List mSQL databases on server


Get number of fields in result

  • « msql_list_tables
  • msql_num_rows »
  • PHP Manual
  • mSQL Functions
  • Get number of fields in result

msql_num_fields

(PHP 4, PHP 5, PHP 7)

msql_num_fields — Get number of fields in result

Description

msql_num_fields ( resource $result ) : int

msql_num_fields() returns the number of fields in a result set.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

Return Values

Returns the number of fields in the result set.

See Also

  • msql_query() - Send mSQL query
  • msql_fetch_field() - Get field information
  • msql_num_rows() - Get number of rows in result


Get number of rows in result

  • « msql_num_fields
  • msql_numfields »
  • PHP Manual
  • mSQL Functions
  • Get number of rows in result

msql_num_rows

(PHP 4, PHP 5, PHP 7)

msql_num_rows — Get number of rows in result

Description

msql_num_rows ( resource $query_identifier ) : int

msql_num_rows() returns the number of rows in a result set.

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

Return Values

Returns the number of rows in the result set.

See Also

  • msql_num_fields() - Get number of fields in result


Alias of msql_num_fields

  • « msql_num_rows
  • msql_numrows »
  • PHP Manual
  • mSQL Functions
  • Alias of msql_num_fields

msql_numfields

(PHP 4, PHP 5, PHP 7)

msql_numfields — Alias of msql_num_fields()

Description

This function is an alias of: msql_num_fields().


Alias of msql_num_rows

  • « msql_numfields
  • msql_pconnect »
  • PHP Manual
  • mSQL Functions
  • Alias of msql_num_rows

msql_numrows

(PHP 4, PHP 5, PHP 7)

msql_numrows — Alias of msql_num_rows()

Description

This function is an alias of: msql_num_rows().


Open persistent mSQL connection

  • « msql_numrows
  • msql_query »
  • PHP Manual
  • mSQL Functions
  • Open persistent mSQL connection

msql_pconnect

(PHP 4, PHP 5, PHP 7)

msql_pconnect — Open persistent mSQL connection

Description

msql_pconnect ([ string $hostname ] ) : resource

msql_pconnect() acts very much like msql_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. 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 (msql_close() will not close links established by this function).

Parameters

hostname

The hostname can also include a port number. e.g. hostname,port.

If not specified, the connection is established by the means of a Unix domain socket, being more efficient than a localhost TCP socket connection.

Note: While this function will accept a colon (:) as a host/port separator, a comma (,) is the preferred method.

Return Values

Returns a positive mSQL link identifier on success, or FALSE on error.

See Also

  • msql_connect() - Open mSQL connection
  • msql_close() - Close mSQL connection


Send mSQL query

  • « msql_pconnect
  • msql_regcase »
  • PHP Manual
  • mSQL Functions
  • Send mSQL query

msql_query

(PHP 4, PHP 5, PHP 7)

msql_query — Send mSQL query

Description

msql_query ( string $query [, resource $link_identifier ] ) : resource

msql_query() sends a query to the currently active database on the server that's associated with the specified link identifier.

Parameters

query

The SQL query.

link_identifier

The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.

Return Values

Returns a positive mSQL query identifier on success, or FALSE on error.

Examples

Example #1 msql_query() example

<?php
$link = msql_connect("dbserver")
   or die("unable to connect to msql server: " . msql_error());
msql_select_db("db", $link)
   or die("unable to select database 'db': " . msql_error());

$result = msql_query("SELECT * FROM table WHERE id=1", $link);
if (!$result) {
   die("query failed: " . msql_error());
}

while ($row = msql_fetch_array($result)) {
    echo $row["id"];
}
?>

See Also

  • msql_db_query() - Send mSQL query
  • msql_select_db() - Select mSQL database
  • msql_connect() - Open mSQL connection


Alias of sql_regcase

  • « msql_query
  • msql_result »
  • PHP Manual
  • mSQL Functions
  • Alias of sql_regcase

msql_regcase

(PHP 4, PHP 5, PHP 7)

msql_regcase — Alias of sql_regcase()

Description

This function is an alias of: sql_regcase().


Get result data

  • « msql_regcase
  • msql_select_db »
  • PHP Manual
  • mSQL Functions
  • Get result data

msql_result

(PHP 4, PHP 5, PHP 7)

msql_result — Get result data

Description

msql_result ( resource $result , int $row [, mixed $field ] ) : string

msql_result() returns the contents of one cell from a mSQL 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 are often much quicker than msql_result().

Recommended high-performance alternatives:
msql_fetch_row(),
msql_fetch_array(), and
msql_fetch_object().

Parameters

result

The result resource that is being evaluated. This result comes from a call to msql_query().

row

The row offset.

field

Can be the field's offset, or the field's name, or the field's table dot field's name (tablename.fieldname.). If the column name has been aliased ('select foo as bar from ...'), use the alias instead of the column name.

Note:

Specifying a numeric field offset is much quicker than specifying a fieldname or tablename.fieldname.

Return Values

Returns the contents of the cell at the row and offset in the specified mSQL result set.


Select mSQL database

  • « msql_result
  • msql_tablename »
  • PHP Manual
  • mSQL Functions
  • Select mSQL database

msql_select_db

(PHP 4, PHP 5, PHP 7)

msql_select_db — Select mSQL database

Description

msql_select_db ( string $database_name [, resource $link_identifier ] ) : bool

msql_select_db() sets the current active database on the server that's associated with the specified link_identifier.

Subsequent calls to msql_query() will be made on the active database.

Parameters

database_name

The database name.

link_identifier

The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • msql_connect() - Open mSQL connection
  • msql_pconnect() - Open persistent mSQL connection
  • msql_query() - Send mSQL query


Alias of msql_result

  • « msql_select_db
  • msql »
  • PHP Manual
  • mSQL Functions
  • Alias of msql_result

msql_tablename

(PHP 4, PHP 5, PHP 7)

msql_tablename — Alias of msql_result()

Description

This function is an alias of: msql_result().


Alias of msql_db_query

  • « msql_tablename
  • Mssql »
  • PHP Manual
  • mSQL Functions
  • Alias of msql_db_query

msql

(PHP 4, PHP 5, PHP 7)

msql — Alias of msql_db_query()

Description

This function is an alias of: msql_db_query().


Microsoft SQL Server

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Mssql Functions
    • mssql_bind — Adds a parameter to a stored procedure or a remote stored procedure
    • mssql_close — Close MS SQL Server connection
    • mssql_connect — Open MS SQL server connection
    • mssql_data_seek — Moves internal row pointer
    • mssql_execute — Executes a stored procedure on a MS SQL server database
    • mssql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
    • mssql_fetch_assoc — Returns an associative array of the current row in the result
    • mssql_fetch_batch — Returns the next batch of records
    • mssql_fetch_field — Get field information
    • mssql_fetch_object — Fetch row as object
    • mssql_fetch_row — Get row as enumerated array
    • mssql_field_length — Get the length of a field
    • mssql_field_name — Get the name of a field
    • mssql_field_seek — Seeks to the specified field offset
    • mssql_field_type — Gets the type of a field
    • mssql_free_result — Free result memory
    • mssql_free_statement — Free statement memory
    • mssql_get_last_message — Returns the last message from the server
    • mssql_guid_string — Converts a 16 byte binary GUID to a string
    • mssql_init — Initializes a stored procedure or a remote stored procedure
    • mssql_min_error_severity — Sets the minimum error severity
    • mssql_min_message_severity — Sets the minimum message severity
    • mssql_next_result — Move the internal result pointer to the next result
    • mssql_num_fields — Gets the number of fields in result
    • mssql_num_rows — Gets the number of rows in result
    • mssql_pconnect — Open persistent MS SQL connection
    • mssql_query — Send MS SQL query
    • mssql_result — Get result data
    • mssql_rows_affected — Returns the number of records affected by the query
    • mssql_select_db — Select MS SQL database


Introduction

Warning

This feature was REMOVED in PHP 7.0.0.

Alternatives to this feature include:

  • PDO_SQLSRV
  • PDO_ODBC
  • SQLSRV
  • Unified ODBC API

These functions allow you to access MS SQL Server database.

This extension is not available anymore on Windows with PHP 5.3 or later.

SQLSRV, an alternative extension for MS SQL connectivity is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.


Requirements

Requirements for Win32 platforms.

The extension requires the MS SQL Client Tools to be installed on the system where PHP is installed. The Client Tools can be installed from the MS SQL Server CD or by copying ntwdblib.dll from \winnt\system32 on the server to \winnt\system32 on the PHP box. Copying ntwdblib.dll will only provide access through named pipes. Configuration of the client will require installation of all the tools.

This extension is not available anymore on Windows with PHP 5.3 or later.

SqlSrv, an alternative driver for MS SQL is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.

Requirements for Unix/Linux platforms.

To use the MSSQL extension on Unix/Linux, you first need to build and install the FreeTDS library. Source code and installation instructions are available at the FreeTDS home page: » http://www.freetds.org/

Note:

On Windows, the DBLIB from Microsoft is used. Functions that return a column name are based on the dbcolname() function in DBLIB. DBLIB was developed for SQL Server 6.x where the max identifier length is 30. For this reason, the maximum column length is 30 characters. On platforms where FreeTDS is used (Linux), this is not a problem.

Note:

On Windows, if you're using MSSQL 2005 or greater you must copy the ntwdblib.dll into the directory where you have installed php and overwrite the one thats already in there. This is due to the version distributed is old and outdated. Alternatively you can use the » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx, ODBC, PDO_DBLIB or PDO_ODBC extensions, to talk to MSSQL.


Installation

The MSSQL extension is enabled by adding extension=php_mssql.dll to php.ini.

To get these functions to work, you have to compile PHP with --with-mssql[=DIR] , where DIR is the FreeTDS install prefix. And FreeTDS should be compiled using --enable-msdblib .

Warning

MS SQL functions are aliases to Sybase functions if PHP is compiled with Sybase extension and without MS SQL extension.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

MS SQL Server configuration options
Name | Default | Changeable | Changelog
mssql.allow_persistent | "1" | PHP_INI_SYSTEM |
mssql.max_persistent | "-1" | PHP_INI_SYSTEM |
mssql.max_links | "-1" | PHP_INI_SYSTEM |
mssql.min_error_severity | "10" | PHP_INI_ALL |
mssql.min_message_severity | "10" | PHP_INI_ALL |
mssql.compatibility_mode | "0" | PHP_INI_ALL |
mssql.connect_timeout | "5" | PHP_INI_ALL |
mssql.timeout | "60" | PHP_INI_ALL | Available since PHP 4.1.0.
mssql.textsize | "-1" | PHP_INI_ALL |
mssql.textlimit | "-1" | PHP_INI_ALL |
mssql.batchsize | "0" | PHP_INI_ALL | Available since PHP 4.0.4.
mssql.datetimeconvert | "1" | PHP_INI_ALL | Available since PHP 4.2.0.
mssql.secure_connection | "0" | PHP_INI_SYSTEM | Available since PHP 4.3.0.
mssql.max_procs | "-1" | PHP_INI_ALL | Available since PHP 4.3.0.
mssql.charset | "" | PHP_INI_ALL | Available since PHP 5.1.2 when built with FreeTDS 7.0 or greater.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.


Resource Types

mssql link

A connection link returned by mssql_connect() and mssql_pconnect().

mssql result

A result handle returned by mssql_query() on SELECT queries.

mssql statement

A statement handle returned by mssql_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.

MSSQL_ASSOC (integer)
Return an associative array. Used on mssql_fetch_array()'s result_type parameter.
MSSQL_NUM (integer)
Return an array with numeric keys. Used on mssql_fetch_array()'s result_type parameter.
MSSQL_BOTH (integer)
Return an array with both numeric keys and keys with their field name. This is the default value for mssql_fetch_array()'s result_type parameter.
SQLTEXT (integer)
Indicates the 'TEXT' type in MSSQL, used by mssql_bind()'s type parameter.
SQLVARCHAR (integer)
Indicates the 'VARCHAR' type in MSSQL, used by mssql_bind()'s type parameter.
SQLCHAR (integer)
Indicates the 'CHAR' type in MSSQL, used by mssql_bind()'s type parameter.
SQLINT1 (integer)
Represents one byte, with a range of -128 to 127.
SQLINT2 (integer)
Represents two bytes, with a range of -32768 to 32767.
SQLINT4 (integer)
Represents four bytes, with a range of -2147483648 to 2147483647.
SQLBIT (integer)
Indicates the 'BIT' type in MSSQL, used by mssql_bind()'s type parameter.
SQLFLT4 (integer)
Represents an four byte float.
SQLFLT8 (integer)
Represents an eight byte float.


Mssql Functions

Table of Contents

  • mssql_bind — Adds a parameter to a stored procedure or a remote stored procedure
  • mssql_close — Close MS SQL Server connection
  • mssql_connect — Open MS SQL server connection
  • mssql_data_seek — Moves internal row pointer
  • mssql_execute — Executes a stored procedure on a MS SQL server database
  • mssql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
  • mssql_fetch_assoc — Returns an associative array of the current row in the result
  • mssql_fetch_batch — Returns the next batch of records
  • mssql_fetch_field — Get field information
  • mssql_fetch_object — Fetch row as object
  • mssql_fetch_row — Get row as enumerated array
  • mssql_field_length — Get the length of a field
  • mssql_field_name — Get the name of a field
  • mssql_field_seek — Seeks to the specified field offset
  • mssql_field_type — Gets the type of a field
  • mssql_free_result — Free result memory
  • mssql_free_statement — Free statement memory
  • mssql_get_last_message — Returns the last message from the server
  • mssql_guid_string — Converts a 16 byte binary GUID to a string
  • mssql_init — Initializes a stored procedure or a remote stored procedure
  • mssql_min_error_severity — Sets the minimum error severity
  • mssql_min_message_severity — Sets the minimum message severity
  • mssql_next_result — Move the internal result pointer to the next result
  • mssql_num_fields — Gets the number of fields in result
  • mssql_num_rows — Gets the number of rows in result
  • mssql_pconnect — Open persistent MS SQL connection
  • mssql_query — Send MS SQL query
  • mssql_result — Get result data
  • mssql_rows_affected — Returns the number of records affected by the query
  • mssql_select_db — Select MS SQL database


Adds a parameter to a stored procedure or a remote stored procedure

  • « Mssql Functions
  • mssql_close »
  • PHP Manual
  • Mssql Functions
  • Adds a parameter to a stored procedure or a remote stored procedure

mssql_bind

(PHP 4 >= 4.0.7, PHP 5, PECL odbtp >= 1.1.1)

mssql_bind — Adds a parameter to a stored procedure or a remote stored procedure

Warning

This function was REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • PDOStatement::bindParam()
  • PDOStatement::bindValue()
  • sqlsrv_prepare()
  • odbc_prepare()

Description

mssql_bind ( resource $stmt , string $param_name , mixed &$var , int $type [, bool $is_output = FALSE [, bool $is_null = FALSE [, int $maxlen = -1 ]]] ) : bool

Binds a parameter to a stored procedure or a remote stored procedure.

Parameters

stmt

Statement resource, obtained with mssql_init().

param_name

The parameter name, as a string.

Note:

You have to include the @ character, like in the T-SQL syntax. See the explanation included in mssql_execute().

var

The PHP variable you'll bind the MSSQL parameter to. It is passed by reference, to retrieve OUTPUT and RETVAL values after the procedure execution.

type

One of: SQLTEXT, SQLVARCHAR, SQLCHAR, SQLINT1, SQLINT2, SQLINT4, SQLBIT, SQLFLT4, SQLFLT8, SQLFLTN.

is_output

Whether the value is an OUTPUT parameter or not. If it's an OUTPUT parameter and you don't mention it, it will be treated as a normal input parameter and no error will be thrown.

is_null

Whether the parameter is NULL or not. Passing the NULL value as var will not do the job.

maxlen

Used with char/varchar values. You have to indicate the length of the data so if the parameter is a varchar(50), the type must be SQLVARCHAR and this value 50.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mssql_bind() example

<?php
// Connect to MSSQL and select the database
mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Create a new stored prodecure
$stmt = mssql_init('NewUserRecord');

// Bind the field names
mssql_bind($stmt, '@username',  'Kalle',  SQLVARCHAR,  false,  false,  60);
mssql_bind($stmt, '@name',      'Kalle',  SQLVARCHAR,  false,  false,  60);
mssql_bind($stmt, '@age',       19,       SQLINT1,     false,  false,   3);

// Execute
mssql_execute($stmt);

// Free statement
mssql_free_statement($stmt);
?>

See Also

  • mssql_execute() - Executes a stored procedure on a MS SQL server database
  • mssql_free_statement() - Free statement memory
  • mssql_init() - Initializes a stored procedure or a remote stored procedure


Close MS SQL Server connection

  • « mssql_bind
  • mssql_connect »
  • PHP Manual
  • Mssql Functions
  • Close MS SQL Server connection

mssql_close

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_close — Close MS SQL Server connection

Warning

This function was REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • sqlsrv_close()
  • odbc_close()
  • odbc_close_all()

Description

mssql_close ([ resource $link_identifier ] ) : bool

Closes the link to a MS SQL Server database that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.

Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

Parameters

link_identifier

A MS SQL link identifier, returned by mssql_connect().

This function will not close persistent links generated by mssql_pconnect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mssql_close() example

<?php
// Connect to MSSQL
$link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');

// Do any related operations here

// Close the link to MSSQL
mssql_close($link);
?>

See Also

  • mssql_connect() - Open MS SQL server connection
  • mssql_pconnect() - Open persistent MS SQL connection


Open MS SQL server connection

  • « mssql_close
  • mssql_data_seek »
  • PHP Manual
  • Mssql Functions
  • Open MS SQL server connection

mssql_connect

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_connect — Open MS SQL server connection

Warning

This function was REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • PDO::__construct()
  • sqlsrv_connect()
  • odbc_connect()

Description

mssql_connect ([ string $servername [, string $username [, string $password [, bool $new_link = FALSE ]]]] ) : resource

mssql_connect() establishes a connection to a MS SQL server.

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

Parameters

servername

The MS SQL server. It can also include a port number, e.g. hostname:port (Linux), or hostname,port (Windows).

username

The username.

password

The password.

new_link

If a second call is made to mssql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. This parameter modifies this behavior and makes mssql_connect() always open a new link, even if mssql_connect() was called before with the same parameters.

Return Values

Returns a MS SQL link identifier on success, or FALSE on error.

Changelog

Version | Description
5.1.0 | The new_link parameter was added

Examples

Example #1 mssql_connect() example

<?php
// Server in the this format: <computer>\<instance name> or
// <server>,<port> when using a non default port number
$server = 'KALLESPC\SQLEXPRESS';

// Connect to MSSQL
$link = mssql_connect($server, 'sa', 'phpfi');

if (!$link) {
    die('Something went wrong while connecting to MSSQL');
}
?>

See Also

  • mssql_close() - Close MS SQL Server connection
  • mssql_pconnect() - Open persistent MS SQL connection


Moves internal row pointer

  • « mssql_connect
  • mssql_execute »
  • PHP Manual
  • Mssql Functions
  • Moves internal row pointer

mssql_data_seek

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_data_seek — Moves internal row pointer

Warning

This function was REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • Using an OFFSET clause with a query issued through PDO_SQLSRV, PDO_ODBC, SQLSRV, or the unified ODBC driver.

Description

mssql_data_seek ( resource $result_identifier , int $row_number ) : bool

mssql_data_seek() moves the internal row pointer of the MS SQL result associated with the specified result identifier to point to the specified row number, first row being number 0. The next call to mssql_fetch_row() would return that row.

Parameters

result_identifier

The result resource that is being evaluated.

row_number

The desired row number of the new result pointer.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mssql_data_seek() example

<?php
// Connect to MSSQL and select the database
$link = mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php', $link);

// Select all people
$result = mssql_query('SELECT [name], [age] FROM [persons] WHERE [age] >= 13');

if (!$result) {
    die('Query failed.');
}

// Select every 4th student in the results
for ($i = mssql_num_rows($result) - 1; $i % 4; $i++) {
    if (!mssql_data_seek($result, $i)) {
        continue;
    }

    // Fetch the row ...
}

// Free the query result
mssql_free_result($result);
?>


Executes a stored procedure on a MS SQL server database

  • « mssql_data_seek
  • mssql_fetch_array »
  • PHP Manual
  • Mssql Functions
  • Executes a stored procedure on a MS SQL server database

mssql_execute

(PHP 4 >= 4.0.7, PHP 5, PECL odbtp >= 1.1.1)

mssql_execute — Executes a stored procedure on a MS SQL server database

Warning

This function was REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • Using an EXEC query issued through PDO_SQLSRV, PDO_ODBC, SQLSRV, or the unified ODBC driver.

Description

mssql_execute ( resource $stmt [, bool $skip_results = FALSE ] ) : mixed

Executes a stored procedure on a MS SQL server database

Parameters

stmt

Statement handle obtained with mssql_init().

skip_results

Whenever to skip the results or not.

Examples

Example #1 mssql_execute() example

<?php
// Create a new statement
$stmt = mssql_init('NewBlogEntry');

// Some data strings
$title = 'Test of blogging system';
$content = 'If you can read this, then the new system is compatible with MSSQL';

// Bind values
mssql_bind($stmt, '@author',    'Felipe Pena',  SQLVARCHAR,     false,  false,   60);
mssql_bind($stmt, '@date',      '08/10/2008',   SQLVARCHAR,     false,  false,   20);
mssql_bind($stmt, '@title',     $title,         SQLVARCHAR,     false,  false,   60);
mssql_bind($stmt, '@content',   $content,       SQLTEXT);

// Execute the statement
mssql_execute($stmt);

// And we can free it like so:
mssql_free_statement($stmt);
?>

Notes

Note:

If the stored procedure returns parameters or a return value these will be available after the call to mssql_execute() unless the stored procedure returns more than one result set. In that case use mssql_next_result() to shift through the results. When the last result has been processed the output parameters and return values will be available.

See Also

  • mssql_bind() - Adds a parameter to a stored procedure or a remote stored procedure
  • mssql_free_statement() - Free statement memory
  • mssql_init() - Initializes a stored procedure or a remote stored procedure


Fetch a result row as an associative array, a numeric array, or both

  • « mssql_execute
  • mssql_fetch_assoc »
  • PHP Manual
  • Mssql Functions
  • Fetch a result row as an associative array, a numeric array, or both

mssql_fetch_array

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_fetch_array — Fetch a result row as an associative array, a numeric array, or both

Warning

This function was REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • PDOStatement::fetch()
  • sqlsrv_fetch_array()
  • odbc_fetch_array()

Description

mssql_fetch_array ( resource $result [, int $result_type = MSSQL_BOTH ] ) : array

mssql_fetch_array() is an extended version of mssql_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

An important thing to note is that using mssql_fetch_array() is NOT significantly slower than using mssql_fetch_row(), while it provides a significant added value.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

result_type

The type of array that is to be fetched. It's a constant and can take the following values: MSSQL_ASSOC, MSSQL_NUM, and MSSQL_BOTH.

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Examples

Example #1 mssql_fetch_array() example

<?php
// Send a select query to MSSQL
$query = mssql_query('SELECT [username], [name] FROM [php].[dbo].[userlist]');

// Check if there were any records
if (!mssql_num_rows($query)) {
    echo 'No records found';
} else {
    // The following is equal to the code below:
    //
    // while ($row = mssql_fetch_row($query)) {

    while ($row = mssql_fetch_array($query, MSSQL_NUM)) {
        // ...
    }
}

// Free the query result
mssql_free_result($query);
?>

Notes

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to the PHP NULL value.

See Also

  • mssql_fetch_row() - Get row as enumerated array


Returns an associative array of the current row in the result

  • « mssql_fetch_array
  • mssql_fetch_batch »
  • PHP Manual
  • Mssql Functions
  • Returns an associative array of the current row in the result

mssql_fetch_assoc

(PHP 4 >= 4.2.0, PHP 5, PECL odbtp >= 1.1.1)

mssql_fetch_assoc — Returns an associative array of the current row in the result

Warning

This function was REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • PDOStatement::fetch()
  • sqlsrv_fetch_array()
  • odbc_fetch_array()

Description

mssql_fetch_assoc ( resource $result_id ) : array

Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. mssql_fetch_assoc() is equivalent to calling mssql_fetch_array() with MSSQL_ASSOC for the optional second parameter.

Parameters

result_id

The result resource that is being evaluated. This result comes from a call to mssql_query().

Return Values

Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.

Examples

Example #1 mssql_fetch_assoc() example

<?php
// Send a select query to MSSQL
$query = mssql_query('SELECT [username], [name] FROM [php].[dbo].[userlist]');

// Check if there were any records
if (!mssql_num_rows($query)) {
    echo 'No records found';
}
else
{
    // Print a nice list of users in the format of:
    // * name (username)

    echo '<ul>';

    while ($row = mssql_fetch_assoc($query)) {
        echo '<li>' . $row['name'] . ' (' . $row['username'] . ')</li>';
    }

    echo '</ul>';
}

// Free the query result
mssql_free_result($query);
?>


Returns the next batch of records

  • « mssql_fetch_assoc
  • mssql_fetch_field »
  • PHP Manual
  • Mssql Functions
  • Returns the next batch of records

mssql_fetch_batch

(PHP 4 >= 4.0.4, PHP 5, PECL odbtp >= 1.1.1)

mssql_fetch_batch — Returns the next batch of records

Warning

This function was REMOVED in PHP 7.0.0.

Description

mssql_fetch_batch ( resource $result ) : int

Returns the next batch of records.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

Return Values

Returns the number of rows in the returned batch.

Examples

Example #1 mssql_fetch_batch() example

<?php
// Connect to MSSQL and select the database
$link = mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php', $link);

// Send a query
$result = mssql_query('SELECT * FROM [php].[dbo].[people]', $link, 100);
$records = 10;

while ($records >= 0) {
    while ($row = mssql_fetch_assoc($result)) {
        // Do stuff ...
    }

    --$records;
}

if ($batchsize = mssql_fetch_batch($result)) {
    // $batchsize is the number of records left
    // in the result, but not shown above
}
?>


Get field information

  • « mssql_fetch_batch
  • mssql_fetch_object »
  • PHP Manual
  • Mssql Functions
  • Get field information

mssql_fetch_field

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_fetch_field — Get field information

Warning

This function was REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • PDOStatement::getColumnMeta()
  • sqlsrv_field_metadata()
  • The various odbc_field_* functions in the unified ODBC driver.

Description

mssql_fetch_field ( resource $result [, int $field_offset = -1 ] ) : object

mssql_fetch_field() can be used in order to obtain information about fields in a certain query result.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_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. if the column is a result of a function, this property is set to computed#N, where #N is a serial number.
  • column_source - the table from which the column was taken
  • max_length - maximum length of the column
  • numeric - 1 if the column is numeric
  • type - the column type.

Examples

Example #1 mssql_fetch_field() example

<?php
// Connect to MSSQL and select the database
mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Send a select query to MSSQL
$query = mssql_query('SELECT * FROM [php].[dbo].[persons]');

// Construct table
echo '<h3>Table structure for \'persons\'</h3>';
echo '<table border="1">';

// Table header
echo '<thead>';
echo '<tr>';
echo '<td>Field name</td>';
echo '<td>Data type</td>';
echo '<td>Max length</td>';
echo '</tr>';
echo '</thead>';

// Dump all fields
echo '<tbody>';

for ($i = 0; $i < mssql_num_fields($query); ++$i) {
    // Fetch the field information
    $field = mssql_fetch_field($query, $i);

    // Print the row
    echo '<tr>';
    echo '<td>' . $field->name . '</td>';
    echo '<td>' . strtoupper($field->type) . '</td>';
    echo '<td>' . $field->max_length . '</td>';
    echo '</tr>';
}

echo '</tbody>';
echo '</table>';

// Free the query result
mssql_free_result($query);
?>

See Also

  • mssql_field_seek() - Seeks to the specified field offset


Fetch row as object

  • « mssql_fetch_field
  • mssql_fetch_row »
  • PHP Manual
  • Mssql Functions
  • Fetch row as object

mssql_fetch_object

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_fetch_object — Fetch row as object

Warning

This function was REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • PDOStatement::fetchObject()
  • sqlsrv_fetch_object()
  • odbc_fetch_object()

Description

mssql_fetch_object ( resource $result ) : object

mssql_fetch_object() is similar to mssql_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).

Speed-wise, the function is identical to mssql_fetch_array(), and almost as quick as mssql_fetch_row() (the difference is insignificant).

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

Return Values

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

Examples

Example #1 mssql_fetch_object() example

<?php
// Send a select query to MSSQL
$query = mssql_query('SELECT [username], [name] FROM [php].[dbo].[userlist]');

// Check if there were any records
if (!mssql_num_rows($query)) {
    echo 'No records found';
} else {
    // Print a nice list of users in the format of:
    // * name (username)

    echo '<ul>';

    while ($row = mssql_fetch_object($query)) {
        echo '<li>' . $row->name . ' (' . $row->username . ')</li>';
    }

    echo '</ul>';
}

// Free the query result
mssql_free_result($query);
?>

Notes

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to the PHP NULL value.

See Also

  • mssql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • mssql_fetch_row() - Get row as enumerated array


Get row as enumerated array

  • « mssql_fetch_object
  • mssql_field_length »
  • PHP Manual
  • Mssql Functions
  • Get row as enumerated array

mssql_fetch_row

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_fetch_row — Get row as enumerated array

Warning

This function was REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • PDOStatement::fetch()
  • sqlsrv_fetch_array()
  • odbc_fetch_row()

Description

mssql_fetch_row ( resource $result ) : array

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

Subsequent call to mssql_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Examples

Example #1 mssql_fetch_row() example

<?php
// Connect to MSSQL and select the database
$link = mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php', $link);

// Query to execute
$query = mssql_query('SELECT [id], [quote] FROM [quotes] WHERE [id] = \'42\'', $link);

// Did the query fail?
if (!$query) {
    die('MSSQL error: ' . mssql_get_last_message());
}

// Fetch the row
$row = mssql_fetch_row($query);

// Print the 'quote'
echo 'Quote #' . $row[0] . ': "' . $row[1] . '"';
?>

The above example will output something similar to:

Quote #42: "The answer to everything..."

Notes

Note: This function sets NULL fields to the PHP NULL value.

See Also

  • mssql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • mssql_fetch_object() - Fetch row as object
  • mssql_data_seek() - Moves internal row pointer
  • mssql_result() - Get result data


Get the length of a field

  • « mssql_fetch_row
  • mssql_field_name »
  • PHP Manual
  • Mssql Functions
  • Get the length of a field

mssql_field_length

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_field_length — Get the length of a field

Warning

This function was REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • PDOStatement::getColumnMeta()
  • sqlsrv_field_metadata()
  • odbc_field_len()

Description

mssql_field_length ( resource $result [, int $offset = -1 ] ) : int

Returns the length of field no. offset in result.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

offset

The field offset, starts at 0. If omitted, the current field is used.

Return Values

The length of the specified field index on success or FALSE on failure.

Examples

Example #1 mssql_field_length() example

<?php
// Connect to MSSQL and select the database
mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Send a select query to MSSQL
$query = mssql_query('SELECT [name], [age] FROM [php].[dbo].[persons]');

// Print the field length
echo 'The field \'age\' has a data length of ' . mssql_field_length($query, 1);

// Free the query result
mssql_free_result($query);
?>

The above example will output something similar to:

The field 'age' has a data length of 4

Notes

Note: Note to Windows Users

Due to a limitation in the underlying API used by PHP (MS DBLib C API), the length of VARCHAR fields is limited to 255. If you need to store more data, use a TEXT field instead.

See Also

  • mssql_field_name() - Get the name of a field
  • mssql_field_type() - Gets the type of a field


Get the name of a field

  • « mssql_field_length
  • mssql_field_seek »
  • PHP Manual
  • Mssql Functions
  • Get the name of a field

mssql_field_name

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_field_name — Get the name of a field

Warning

This function was REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • PDOStatement::getColumnMeta()
  • sqlsrv_field_metadata()
  • odbc_field_name()

Description

mssql_field_name ( resource $result [, int $offset = -1 ] ) : string

Returns the name of field no. offset in result.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

offset

The field offset, starts at 0. If omitted, the current field is used.

Return Values

The name of the specified field index on success or FALSE on failure.

Examples

Example #1 mssql_field_name() example

<?php
// Send a select query to MSSQL
$query = mssql_query('SELECT [username], [name], [email] FROM [php].[dbo].[userlist]');

echo 'Result set contains the following field(s):', PHP_EOL;

// Dump all field names in result
for ($i = 0; $i < mssql_num_fields($query); ++$i) {
    echo ' - ' . mssql_field_name($query, $i), PHP_EOL;
}

// Free the query result
mssql_free_result($query);
?>

The above example will output something similar to:

Result set contains the following field(s):
 - username
 - name
 - email

See Also

  • mssql_field_length() - Get the length of a field
  • mssql_field_type() - Gets the type of a field


Seeks to the specified field offset

  • « mssql_field_name
  • mssql_field_type »
  • PHP Manual
  • Mssql Functions
  • Seeks to the specified field offset

mssql_field_seek

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_field_seek — Seeks to the specified field offset

Warning

This function was REMOVED in PHP 7.0.0.

Description

mssql_field_seek ( resource $result , int $field_offset ) : bool

Seeks to the specified field offset. If the next call to mssql_fetch_field() won't include a field offset, this field would be returned.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

field_offset

The field offset, starts at 0.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Using mssql_field_seek() on the example for mssql_fetch_field()

<?php
// Connect to MSSQL and select the database
mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Send a select query to MSSQL
$query = mssql_query('SELECT * FROM [php].[dbo].[persons]');

// Construct table
echo '<h3>Table structure for \'persons\'</h3>';
echo '<table border="1">';

// Table header
echo '<thead>';
echo '<tr>';
echo '<td>Field name</td>';
echo '<td>Data type</td>';
echo '<td>Max length</td>';
echo '</tr>';
echo '</thead>';

// Dump all fields
echo '<tbody>';

for ($i = 0; $i < mssql_num_fields($query); ++$i) {
    // Fetch the field information, notice the
    // field_offset parameter is not set. See
    // the mssql_field_seek call below
    $field = mssql_fetch_field($query);

    // Print the row
    echo '<tr>';
    echo '<td>' . $field->name . '</td>';
    echo '<td>' . strtoupper($field->type) . '</td>';
    echo '<td>' . $field->max_length . '</td>';
    echo '</tr>';

    // Move the internal seek pointer to the next
    // row in the result set
    mssql_field_seek($query, $i + 1);
}

echo '</tbody>';
echo '</table>';

// Free the query result
mssql_free_result($query);
?>

See Also

  • mssql_fetch_field() - Get field information


Gets the type of a field

  • « mssql_field_seek
  • mssql_free_result »
  • PHP Manual
  • Mssql Functions
  • Gets the type of a field

mssql_field_type

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_field_type — Gets the type of a field

Warning

This function was REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • PDOStatement::getColumnMeta()
  • sqlsrv_field_metadata()
  • odbc_field_type()

Description

mssql_field_type ( resource $result [, int $offset = -1 ] ) : string

Returns the type of field no. offset in result.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

offset

The field offset, starts at 0. If omitted, the current field is used.

Return Values

The type of the specified field index on success or FALSE on failure.

Examples

Example #1 mssql_field_type() example

<?php
// Connect to MSSQL and select the database
mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Send a select query to MSSQL
$query = mssql_query('SELECT [name] FROM [php].[dbo].[persons]');

// Print the field type and length
echo '\'' . mssql_field_name($query, 0) . '\' is a type of ' .
     strtoupper(mssql_field_type($query, 0)) .
     '(' . mssql_field_length($query, 0) . ')';

// Free the query result
mssql_free_result($query);
?>

The above example will output something similar to:

'name' is a type of CHAR(50)

See Also

  • mssql_field_length() - Get the length of a field
  • mssql_field_name() - Get the name of a field


Free result memory

  • « mssql_field_type
  • mssql_free_statement »
  • PHP Manual
  • Mssql Functions
  • Free result memory

mssql_free_result

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_free_result — Free result memory

Warning

This function was REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • odbc_free_result()

Description

mssql_free_result ( resource $result ) : bool

mssql_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 ends. You may call mssql_free_result() with the result identifier as an argument and the associated result memory will be freed.

Parameters

result

The result resource that is being freed. This result comes from a call to mssql_query().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mssql_free_result() example

<?php
// Select some data from a table
$query = mssql_query('SELECT * FROM [php].[dbo].[persons]', $link);

// Handle query result here

// When we're done we free the result by calling
// mssql_free_result like so:
mssql_free_result($query);
?>

See Also

  • mssql_free_statement() - Free statement memory


Free statement memory

  • « mssql_free_result
  • mssql_get_last_message »
  • PHP Manual
  • Mssql Functions
  • Free statement memory

mssql_free_statement

(PHP 4 >= 4.3.2, PHP 5, PECL odbtp >= 1.1.1)

mssql_free_statement — Free statement memory

Warning

This function was REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • sqlsrv_free_stmt()

Description

mssql_free_statement ( resource $stmt ) : bool

mssql_free_statement() only needs to be called if you are worried about using too much memory while your script is running. All statement memory will automatically be freed when the script ends. You may call mssql_free_statement() with the statement identifier as an argument and the associated statement memory will be freed.

Parameters

stmt

Statement resource, obtained with mssql_init().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mssql_free_statement() example

<?php
// Create a new statement
$stmt = mssql_init('test');

// Bind values here and execute the statement

// once we're done, we clear it from the memory
// using mssql_free_statement like so:
mssql_free_statement($stmt);
?>

See Also

  • mssql_bind() - Adds a parameter to a stored procedure or a remote stored procedure
  • mssql_execute() - Executes a stored procedure on a MS SQL server database
  • mssql_init() - Initializes a stored procedure or a remote stored procedure
  • mssql_free_result() - Free result memory


Returns the last message from the server

  • « mssql_free_statement
  • mssql_guid_string »
  • PHP Manual
  • Mssql Functions
  • Returns the last message from the server

mssql_get_last_message

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_get_last_message — Returns the last message from the server

Warning

This function was REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • PDOStatement::errorInfo()
  • sqlsrv_errors()
  • odbc_errormsg()

Description

mssql_get_last_message ( void ) : string

Gets the last message from the MS-SQL server

Parameters

This function has no parameters.

Return Values

Returns last error message from server, or an empty string if no error messages are returned from MSSQL.

Examples

Example #1 mssql_get_last_message() example

<?php
// Connect to MSSQL and select the database
mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Make a query that will fail
$query = @mssql_query('SELECT * FROM [php].[dbo].[not-found]');

if (!$query) {
    // The query has failed, print a nice error message
    // using mssql_get_last_message()
    die('MSSQL error: ' . mssql_get_last_message());
}
?>

The above example will output something similar to:

MSSQL error: Invalid object name 'php.dbo.not-found'.

See Also

  • mssql_min_error_severity() - Sets the minimum error severity
  • mssql_min_message_severity() - Sets the minimum message severity


Converts a 16 byte binary GUID to a string

  • « mssql_get_last_message
  • mssql_init »
  • PHP Manual
  • Mssql Functions
  • Converts a 16 byte binary GUID to a string

mssql_guid_string

(PHP 4 >= 4.0.7, PHP 5, PECL odbtp >= 1.1.1)

mssql_guid_string — Converts a 16 byte binary GUID to a string

Warning

This function was REMOVED in PHP 7.0.0.

Description

mssql_guid_string ( string $binary [, bool $short_format = FALSE ] ) : string

Converts a 16 byte binary GUID to a string.

Parameters

binary

A 16 byte binary GUID.

short_format

Whenever to use short format.

Return Values

Returns the converted string on success.

Examples

Example #1 mssql_guid_string() example

<?php
$binary = '19555081977808608437941339997619274330352755554827939936';

var_dump(mssql_guid_string($binary));
var_dump(mssql_guid_string($binary, true));
?>

The above example will output:

string(36) "35353931-3035-3138-3937-373830383630"
string(32) "31393535353038313937373830383630"


Initializes a stored procedure or a remote stored procedure

  • « mssql_guid_string
  • mssql_min_error_severity »
  • PHP Manual
  • Mssql Functions
  • Initializes a stored procedure or a remote stored procedure

mssql_init

(PHP 4 >= 4.0.7, PHP 5, PECL odbtp >= 1.1.1)

mssql_init — Initializes a stored procedure or a remote stored procedure

Warning

This function was REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • Using an EXEC query issued through PDO_SQLSRV, PDO_ODBC, SQLSRV, or the unified ODBC driver.

Description

mssql_init ( string $sp_name [, resource $link_identifier ] ) : resource

Initializes a stored procedure or a remote stored procedure.

Parameters

sp_name

Stored procedure name, like ownew.sp_name or otherdb.owner.sp_name.

link_identifier

A MS SQL link identifier, returned by mssql_connect().

Return Values

Returns a resource identifier "statement", used in subsequent calls to mssql_bind() and mssql_execute(), or FALSE on errors.

Examples

Example #1 mssql_init() example

<?php
// Connect to MSSQL and select the database
$link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php', $link);

// Create a new statement
$stmt = mssql_init('StatementTest', $link);

// Bind values here

// Once values are binded we execute our statement
// using mssql_execute:
mssql_execute($stmt);

// And we can free it like so:
mssql_free_statement($stmt);
?>

See Also

  • mssql_bind() - Adds a parameter to a stored procedure or a remote stored procedure
  • mssql_execute() - Executes a stored procedure on a MS SQL server database
  • mssql_free_statement() - Free statement memory


Sets the minimum error severity

  • « mssql_init
  • mssql_min_message_severity »
  • PHP Manual
  • Mssql Functions
  • Sets the minimum error severity

mssql_min_error_severity

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_min_error_severity — Sets the minimum error severity

Warning

This function was REMOVED in PHP 7.0.0.

Description

mssql_min_error_severity ( int $severity ) : void

Sets the minimum error severity.

Parameters

severity

The new error severity.

Return Values

No value is returned.

Examples

Example #1 mssql_min_error_severity() example

<?php
// Connect to MSSQL and select the database
mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Set the minimum error severity to not include SQL
// syntax errors by setting it to something greater than
// or equal to 1.
mssql_min_error_severity(1);

// Send a query we know that will cause an syntax error, in
// this case we use the MySQL quote signs instead of wrapping
// square brackets around the field and table names.
$query = mssql_query('SELECT `syntax`, `error` FROM `MSSQL`');

if (!$query) {
    // Custom error handler ...
}
?>


Sets the minimum message severity

  • « mssql_min_error_severity
  • mssql_next_result »
  • PHP Manual
  • Mssql Functions
  • Sets the minimum message severity

mssql_min_message_severity

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_min_message_severity — Sets the minimum message severity

Warning

This function was REMOVED in PHP 7.0.0.

Description

mssql_min_message_severity ( int $severity ) : void

Sets the minimum message severity.

Parameters

severity

The new message severity.

Return Values

No value is returned.

Examples

Example #1 mssql_min_message_severity() example

<?php
// Connect to MSSQL
mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');

// Set the minimum message severity to 17, this
// will not show any messages issued by the underlaying
// API when we select a non-existent database below
mssql_min_message_severity(17);

// Select a non-existent database
mssql_select_db('THIS_DATABASE_DOES_NOT_EXISTS');
?>

The above example will output:

mssql_select_db(): Unable to select database:  THIS_DATABASE_DOES_NOT_EXISTS


Move the internal result pointer to the next result

  • « mssql_min_message_severity
  • mssql_num_fields »
  • PHP Manual
  • Mssql Functions
  • Move the internal result pointer to the next result

mssql_next_result

(PHP 4 >= 4.0.5, PHP 5, PECL odbtp >= 1.1.1)

mssql_next_result — Move the internal result pointer to the next result

Warning

This function was REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • PDOStatement::nextRowset()
  • sqlsrv_next_result()
  • odbc_next_result()

Description

mssql_next_result ( resource $result_id ) : bool

When sending more than one SQL statement to the server or executing a stored procedure with multiple results, it will cause the server to return multiple result sets. This function will test for additional results available form the server. If an additional result set exists it will free the existing result set and prepare to fetch the rows from the new result set.

Parameters

result_id

The result resource that is being evaluated. This result comes from a call to mssql_query().

Return Values

Returns TRUE if an additional result set was available or FALSE otherwise.

Examples

Example #1 mssql_next_result() example

<?php
// Connect to MSSQL and select the database
$link = mssql_connect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php', $link);

// Send a query to MSSQL
$sql = 'SELECT [name], [age] FROM [php].[dbo].[persons]';
$query = mssql_query($sql, $link);

// Iterate through returned records
do {
    while ($row = mssql_fetch_row($query)) {
        // Handle record ...
    }
} while (mssql_next_result($query));

// Clean up
mssql_free_result($query);
mssql_close($link);
?>


Gets the number of fields in result

  • « mssql_next_result
  • mssql_num_rows »
  • PHP Manual
  • Mssql Functions
  • Gets the number of fields in result

mssql_num_fields

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_num_fields — Gets the number of fields in result

Warning

This function was REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • PDOStatement::columnCount()
  • sqlsrv_num_fields()
  • odbc_num_fields()

Description

mssql_num_fields ( resource $result ) : int

mssql_num_fields() returns the number of fields in a result set.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

Return Values

Returns the number of fields, as an integer.

Examples

Example #1 mssql_num_fields() example

<?php
// Connect to MSSQL and select the database
$link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php', $link);

// Select some data from our database
$data = mssql_query('SELECT [name], [age] FROM [php].[dbo].[persons]');

// Construct a table
echo '<table border="1">';

$header = false;

// Iterate through returned results
while ($row = mssql_fetch_array($data)) {
    // Build the table header
    if (!$header) {
        echo '<thead>';
        echo '<tr>';

        for ($i = 1; ($i + 1) <= mssql_num_fields($data); ++$i) {
            echo '<td>' . ucfirst($row[$i]) . '</td>';
        }

        echo '</tr>';
        echo '</thead>';
        echo '<tbody>';

        $header = true;
    }

    // Build the row
    echo '<tr>';

    foreach($row as $value) {
        echo '<td>' . $value . '</td>';
    }

    echo '</tr>';
}

// Close table
echo '</tbody>';
echo '</table>';

// Clean up
mssql_free_result($data);
mssql_close($link);
?>

See Also

  • mssql_query() - Send MS SQL query
  • mssql_fetch_field() - Get field information
  • mssql_num_rows() - Gets the number of rows in result


Gets the number of rows in result

  • « mssql_num_fields
  • mssql_pconnect »
  • PHP Manual
  • Mssql Functions
  • Gets the number of rows in result

mssql_num_rows

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_num_rows — Gets the number of rows in result

Warning

This function was REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • PDOStatement::rowCount()
  • sqlsrv_num_rows()
  • odbc_num_rows()

Description

mssql_num_rows ( resource $result ) : int

mssql_num_rows() returns the number of rows in a result set.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

Return Values

Returns the number of rows, as an integer.

Examples

Example #1 mssql_num_rows() example

<?php
// Connect to MSSQL and select the database
$link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php');

// Select all our records from a table
$query = mssql_query('SELECT * FROM [php].[dbo].[persons]');

echo 'Total records in database: ' . mssql_num_rows($query);

// Clean up
mssql_free_result($query);
?>

See Also

  • mssql_query() - Send MS SQL query
  • mssql_fetch_row() - Get row as enumerated array


Open persistent MS SQL connection

  • « mssql_num_rows
  • mssql_query »
  • PHP Manual
  • Mssql Functions
  • Open persistent MS SQL connection

mssql_pconnect

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_pconnect — Open persistent MS SQL connection

Warning

This function was REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • PDO::__construct()
  • sqlsrv_connect()
  • odbc_pconnect()

Description

mssql_pconnect ([ string $servername [, string $username [, string $password [, bool $new_link = FALSE ]]]] ) : resource

mssql_pconnect() acts very much like mssql_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 (mssql_close() will not close links established by mssql_pconnect()).

This type of links is therefore called 'persistent'.

Parameters

servername

The MS SQL server. It can also include a port number. e.g. hostname:port.

username

The username.

password

The password.

new_link

If a second call is made to mssql_pconnect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. This parameter modifies this behavior and makes mssql_pconnect() always open a new link, even if mssql_pconnect() was called before with the same parameters.

Return Values

Returns a positive MS SQL persistent link identifier on success, or FALSE on error.

Examples

Example #1 mssql_pconnect() using the new_link parameter

<?php
// Connect to MSSQL and select the database
$link1 = mssql_pconnect('MANGO\SQLEXPRESS', 'sa', 'phpfi');
mssql_select_db('php', $link1);

// Create a new link
$link2 = mssql_pconnect('MANGO\SQLEXPRESS', 'sa', 'phpfi', true);
mssql_select_db('random', $link2);
?>


Send MS SQL query

  • « mssql_pconnect
  • mssql_result »
  • PHP Manual
  • Mssql Functions
  • Send MS SQL query

mssql_query

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_query — Send MS SQL query

Warning

This function was REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • PDO::query()
  • sqlsrv_query()
  • odbc_exec()

Description

mssql_query ( string $query [, resource $link_identifier [, int $batch_size = 0 ]] ) : mixed

mssql_query() sends a query to the currently active database on the server that's associated with the specified link identifier.

Parameters

query

An SQL query.

link_identifier

A MS SQL link identifier, returned by mssql_connect() or mssql_pconnect().

If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if mssql_connect() was called, and use it.

batch_size

The number of records to batch in the buffer.

Return Values

Returns a MS SQL result resource on success, TRUE if no rows were returned, or FALSE on error.

Examples

Example #1 mssql_query() example

<?php
// Connect to MSSQL
$link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');

if (!$link || !mssql_select_db('php', $link)) {
    die('Unable to connect or select database!');
}

// Do a simple query, select the version of
// MSSQL and print it.
$version = mssql_query('SELECT @@VERSION');
$row = mssql_fetch_array($version);

echo $row[0];

// Clean up
mssql_free_result($version);
?>

Notes

Note:

If the query returns multiple results then it is necessary to fetch all results by mssql_next_result() or free the results by mssql_free_result() before executing next query.

See Also

  • mssql_select_db() - Select MS SQL database
  • mssql_connect() - Open MS SQL server connection


Get result data

  • « mssql_query
  • mssql_rows_affected »
  • PHP Manual
  • Mssql Functions
  • Get result data

mssql_result

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_result — Get result data

Warning

This function was REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • odbc_result()

Description

mssql_result ( resource $result , int $row , mixed $field ) : string

mssql_result() returns the contents of one cell from a MS SQL result set.

Parameters

result

The result resource that is being evaluated. This result comes from a call to mssql_query().

row

The row number.

field

Can be the field's offset, the field's name or the field's table dot field's name (tablename.fieldname). If the column name has been aliased ('select foo as bar from...'), it uses the alias instead of the column name.

Note:

Specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.

Return Values

Returns the contents of the specified cell.

Examples

Example #1 mssql_result() example

<?php
// Send a select query to MSSQL
$query = mssql_query('SELECT [username] FROM [php].[dbo].[userlist]');

// Check if there were any records
if (!mssql_num_rows($query)) {
    echo 'No records found';
} else {
    for ($i = 0; $i < mssql_num_rows($query); ++$i) {
        echo mssql_result($query, $i, 'username'), PHP_EOL;
    }
}

// Free the query result
mssql_free_result($query);
?>

The above example will output something similar to:

Kalle
Felipe
Emil
Ross

Example #2 Faster alternative to above example

<?php
// Send a select query to MSSQL
$query = mssql_query('SELECT [username] FROM [php].[dbo].[userlist]');

// Check if there were any records
if (!mssql_num_rows($query)) {
    echo 'No records found';
} else {
    while ($row = mssql_fetch_array($query)) {
        echo $row['username'], PHP_EOL;
    }
}

// Free the query result
mssql_free_result($query);
?>

Notes

Note:

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

See Also

Recommended high-performance alternatives:

  • mssql_fetch_row() - Get row as enumerated array
  • mssql_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • mssql_fetch_assoc() - Returns an associative array of the current row in the result
  • mssql_fetch_object() - Fetch row as object


Returns the number of records affected by the query

  • « mssql_result
  • mssql_select_db »
  • PHP Manual
  • Mssql Functions
  • Returns the number of records affected by the query

mssql_rows_affected

(PHP 4 >= 4.0.4, PHP 5, PECL odbtp >= 1.1.1)

mssql_rows_affected — Returns the number of records affected by the query

Warning

This function was REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • PDOStatement::rowCount()
  • sqlsrv_rows_affected()

Description

mssql_rows_affected ( resource $link_identifier ) : int

Returns the number of records affected by the last write query.

Parameters

link_identifier

A MS SQL link identifier, returned by mssql_connect() or mssql_pconnect().

Return Values

Returns the number of records affected by last operation.

Examples

Example #1 mssql_rows_affected() example

<?php
// Delete all rows in a table
mssql_query('TRUNCATE TABLE [php].[dbo].[persons]');

echo 'Deleted ' . mssql_rows_affected($link) . ' row(s)';
?>


Select MS SQL database

  • « mssql_rows_affected
  • MySQL »
  • PHP Manual
  • Mssql Functions
  • Select MS SQL database

mssql_select_db

(PHP 4, PHP 5, PECL odbtp >= 1.1.1)

mssql_select_db — Select MS SQL database

Warning

This function was REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • PDO_SQLSRV DSN
  • PDO_ODBC DSN
  • sqlsrv_connect()
  • odbc_connect()

Description

mssql_select_db ( string $database_name [, resource $link_identifier ] ) : bool

mssql_select_db() sets the current active database on the server that's associated with the specified link identifier.

Every subsequent call to mssql_query() will be made on the active database.

Parameters

database_name

The database name.

To escape the name of a database that contains spaces, hyphens ("-"), or any other exceptional characters, the database name must be enclosed in brackets, as is shown in the example, below. This technique must also be applied when selecting a database name that is also a reserved word (such as primary).

link_identifier

A MS SQL link identifier, returned by mssql_connect() or mssql_pconnect().

If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if mssql_connect() was called, and use it.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mssql_select_db() example

<?php
// Create a link to MSSQL
$link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');

// Select the database 'php'
mssql_select_db('php', $link);
?>

Example #2 Escaping the database name with square brackets

<?php
// Create a link to MSSQL
$link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');

// Select the database 'my.database-name'
mssql_select_db('[my.database-name]', $link);
?>

See Also

  • mssql_connect() - Open MS SQL server connection
  • mssql_pconnect() - Open persistent MS SQL connection
  • mssql_query() - Send MS SQL query


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.

  • Overview of the MySQL PHP drivers
    • Terminology overview
    • Choosing an API
    • Choosing a library
    • Concepts
  • MySQLi — MySQL Improved Extension
    • Introduction
    • Overview
    • Quick start guide
    • Installing/Configuring
    • The mysqli Extension and Persistent Connections
    • Predefined Constants
    • Notes
    • The MySQLi Extension Function Summary
    • Examples
    • 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
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • 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
    • Introduction
    • Installing/Configuring
    • Changelog
    • Predefined Constants
    • Examples
    • MySQL Functions
  • Mysqlnd — MySQL Native Driver
    • Introduction
    • Overview
    • Installation
    • Runtime Configuration
    • Incompatibilities
    • Persistent Connections
    • Statistics
    • Notes
    • Memory management
    • MySQL Native Driver Plugin API
  • mysqlnd_ms — Mysqlnd replication and load balancing plugin
    • Introduction
    • Quickstart and Examples
    • Concepts
    • Installing/Configuring
    • Predefined Constants
    • Mysqlnd_ms Functions
    • Change History
  • mysqlnd_qc — Mysqlnd query result cache plugin
    • Introduction
    • Quickstart and Examples
    • Installing/Configuring
    • Predefined Constants
    • mysqlnd_qc Functions
    • Change History
  • mysqlnd_uh — Mysqlnd user handler plugin
    • Introduction
    • Quickstart and Examples
    • Installing/Configuring
    • Predefined Constants
    • MysqlndUhConnection — The MysqlndUhConnection class
    • MysqlndUhPreparedStatement — The MysqlndUhPreparedStatement class
    • Mysqlnd_uh Functions
    • Change History
  • mysqlnd_mux — Mysqlnd connection multiplexing plugin
    • Introduction
    • Concepts
    • Installing/Configuring
    • Predefined Constants
    • Change History
  • mysqlnd_memcache — Mysqlnd Memcache plugin
    • Introduction
    • Quickstart and Examples
    • Installing/Configuring
    • Predefined Constants
    • Mysqlnd_memcache Functions
    • Change History


Overview of the MySQL PHP drivers

Introduction

Depending on the version of PHP, there are either two or three PHP APIs for accessing the MySQL database. PHP 5 users can choose between the deprecated mysql extension, mysqli, or PDO_MySQL. PHP 7 removes the mysql extension, leaving only the latter two options.

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
  • Choosing an API
  • Choosing a library
  • Concepts
    • Buffered and Unbuffered queries
    • Character sets


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 extensions, such as the mysqli extension, and the mysql 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.


Choosing an API

PHP offers three different APIs to connect to MySQL. Below we show the APIs provided by the mysql, 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 three 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']);

// mysql
$c = mysql_connect("example.com", "user", "password");
mysql_select_db("database");
$result = mysql_query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");
$row = mysql_fetch_assoc($result);
echo htmlentities($row['_message']);
?>

Recommended API

It is recommended to use either the mysqli or PDO_MySQL extensions. It is not recommended to use the old mysql extension for new development, as it was deprecated in PHP 5.5.0 and was removed in PHP 7. A detailed feature comparison matrix is provided below. The overall performance of all three 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%.

Feature comparison

 | ext/mysqli | PDO_MySQL | ext/mysql
PHP version introduced | 5.0 | 5.1 | 2.0
Included with PHP 5.x | Yes | Yes | Yes
Included with PHP 7.x | Yes | Yes | No
Development status | Active | Active | Maintenance only in 5.x; removed in 7.x
Lifecycle | Active | Active | Deprecated in 5.x; removed in 7.x
Recommended for new projects | Yes | Yes | No
OOP Interface | Yes | Yes | No
Procedural Interface | Yes | No | Yes
API supports non-blocking, asynchronous queries with mysqlnd | Yes | No | No
Persistent Connections | Yes | Yes | Yes
API supports Charsets | Yes | Yes | Yes
API supports server-side Prepared Statements | Yes | Yes | No
API supports client-side Prepared Statements | No | Yes | No
API supports Stored Procedures | Yes | Yes | No
API supports Multiple Statements | Yes | Most | No
API supports Transactions | Yes | Yes | No
Transactions can be controlled with SQL | Yes | Yes | Yes
Supports all MySQL 5.1+ functionality | Yes | Most | No


Choosing a library

The mysqli, PDO_MySQL and 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 since 5.3.0. 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 --with-mysql=mysqlnd

// Alternatively recommended, compiles with mysqlnd as of PHP 5.4
$ ./configure --with-mysqli --with-pdo-mysql --with-mysql

// Not recommended, compiles with libmysqlclient
$ ./configure --with-mysqli=/path/to/mysql_config --with-pdo-mysql=/path/to/mysql_config --with-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
PHP 5.4 and above; compile default (for all MySQL extensions) | Yes | No
PHP 5.3; compile default (for all MySQL extensions) | No | Yes
Compression protocol support | Yes (5.3.1+) | Yes
SSL support | Yes (5.3.3+) | Yes
Named pipe support | Yes (5.3.4+) | 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
Read/Write splitting for MySQL Replication | Yes, with plugin | No
Load Balancing | Yes, with plugin | No
Fail over | Yes, with plugin | No
Lazy connections | Yes, with plugin | No
Query caching | Yes, with plugin | No
Transparent query manipulations (E.g., auto-EXPLAIN or monitoring) | Yes, with plugin | No
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 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 return a resource while the data is still waiting on the MySQL server for being 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".

Following these characteristics buffered queries should be used in cases where you expect only a limited result set or need to know the amount of returned rows before reading all rows. Unbuffered mode should be used when you expect larger results.

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");
$uresult = $mysqli->query("SELECT Name FROM City", MYSQLI_USE_RESULT);

if ($uresult) {
   while ($row = $uresult->fetch_assoc()) {
       echo $row['Name'] . PHP_EOL;
   }
}
$uresult->close();
?>

Example #2 Unbuffered query example: pdo_mysql

<?php
$pdo = new PDO("mysql:host=localhost;dbname=world", 'my_user', 'my_pass');
$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);

$uresult = $pdo->query("SELECT Name FROM City");
if ($uresult) {
   while ($row = $uresult->fetch(PDO::FETCH_ASSOC)) {
       echo $row['Name'] . PHP_EOL;
   }
}
?>

Example #3 Unbuffered query example: mysql

<?php
$conn = mysql_connect("localhost", "my_user", "my_pass");
$db   = mysql_select_db("world");

$uresult = mysql_unbuffered_query("SELECT Name FROM City");
if ($uresult) {
   while ($row = mysql_fetch_assoc($uresult)) {
       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, mysql_real_escape_string() for mysql, 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 utf8");

// Will NOT affect $mysqli->real_escape_string();
$mysqli->query("SET CHARACTER SET utf8");

// But, this will affect $mysqli->real_escape_string();
$mysqli->set_charset('utf8');

// But, this will NOT affect it (utf-8 vs utf8) -- 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. The string "utf-8" is not valid, as using "utf-8" will fail to change the character set.

Example #2 Setting the character set example: mysqli

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

printf("Initial character set: %s\n", $mysqli->character_set_name());

if (!$mysqli->set_charset('utf8')) {
    printf("Error loading character set utf8: %s\n", $mysqli->error);
    exit;
}

echo "New character set information:\n";
print_r( $mysqli->get_charset() );

?>

Example #3 Setting the character set example: pdo_mysql

Note: This only works as of PHP 5.3.6.

<?php
$pdo = new PDO("mysql:host=localhost;dbname=world;charset=utf8", 'my_user', 'my_pass');
?>

Example #4 Setting the character set example: mysql

<?php
$conn = mysql_connect("localhost", "my_user", "my_pass");
$db   = mysql_select_db("world");

echo 'Initial character set: ' .  mysql_client_encoding($conn) . "\n";

if (!mysql_set_charset('utf8', $conn)) {
    echo "Error: Unable to set the character set.\n";
    exit;
}

echo 'Your current character set is: ' .  mysql_client_encoding($conn);
?>


MySQL Improved Extension

  • Introduction
  • 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
    • Resource Types
  • The mysqli Extension and Persistent Connections
  • Predefined Constants
  • Notes
  • The MySQLi Extension Function Summary
  • Examples
    • MySQLi extension basic examples
  • 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 specified database connection
    • mysqli::character_set_name — Returns the default character set for 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 string description of the last connect 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_list — Returns a list of errors from the last command executed
    • mysqli::$error — Returns a string description of the last error
    • 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 a resource for use with mysqli_real_connect()
    • mysqli::$insert_id — Returns the auto generated id used in the latest 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 a query 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 — Prepare an SQL statement for execution
    • mysqli::query — Performs a query on the database
    • mysqli::real_connect — Opens a connection to a 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::rpl_query_type — Returns RPL query type
    • mysqli::savepoint — Set a named transaction savepoint
    • mysqli::select_db — Selects the default database for database queries
    • mysqli::send_query — Send the query and return
    • mysqli::set_charset — Sets the default client character set
    • mysqli::set_local_infile_default — Unsets user defined handler for load local infile command
    • mysqli::set_local_infile_handler — Set callback function for LOAD DATA LOCAL INFILE command
    • 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 from the last query for the given link
  • mysqli_stmt — The mysqli_stmt class
    • mysqli_stmt::$affected_rows — Returns the total number of rows changed, deleted, or inserted by the last executed statement
    • 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 — Seeks to an arbitrary row in statement result set
    • mysqli_stmt::$errno — Returns the error code for the most recent statement call
    • mysqli_stmt::$error_list — Returns a list of errors from the last statement executed
    • mysqli_stmt::$error — Returns a string description for last statement error
    • mysqli_stmt::execute — Executes a prepared Query
    • mysqli_stmt::fetch — Fetch results from a prepared statement into the bound variables
    • mysqli_stmt::$field_count — Returns the number of field 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
    • 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 — Return the number of rows in statements result set
    • mysqli_stmt::$param_count — Returns the number of parameter for the given statement
    • mysqli_stmt::prepare — Prepare 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 — Transfers a result set from a prepared statement
  • mysqli_result — The mysqli_result class
    • 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 — Fetches all result rows as an associative array, a numeric array, or both
    • mysqli_result::fetch_array — Fetch a result row as an associative, a numeric array, or both
    • mysqli_result::fetch_assoc — Fetch a result row as an associative array
    • mysqli_result::fetch_field_direct — Fetch meta-data for a single field
    • mysqli_result::fetch_field — Returns the next field in the result set
    • mysqli_result::fetch_fields — Returns an array of objects representing the fields in a result set
    • mysqli_result::fetch_object — Returns the current row of a result set as an object
    • mysqli_result::fetch_row — Get a result row as an enumerated array
    • mysqli_result::$field_count — Get the number of fields in a result
    • mysqli_result::field_seek — Set result pointer to a specified field offset
    • mysqli_result::free — Frees the memory associated with a result
    • 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 a result
  • 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 — Enables or disables internal report functions
  • mysqli_warning — The mysqli_warning class
    • mysqli_warning::__construct — The __construct purpose
    • mysqli_warning::next — Fetch next warning
  • mysqli_sql_exception — The mysqli_sql_exception class
  • Aliases and deprecated Mysqli Functions
    • mysqli_bind_param — Alias for mysqli_stmt_bind_param
    • mysqli_bind_result — Alias for mysqli_stmt_bind_result
    • mysqli_client_encoding — Alias of mysqli_character_set_name
    • mysqli_connect — Alias of mysqli::__construct
    • mysqli::disable_reads_from_master — Disable reads from master
    • mysqli_disable_rpl_parse — Disable RPL parse
    • mysqli_enable_reads_from_master — Enable reads from master
    • mysqli_enable_rpl_parse — Enable RPL parse
    • mysqli_escape_string — Alias of mysqli_real_escape_string
    • mysqli_execute — Alias for mysqli_stmt_execute
    • mysqli_fetch — Alias for mysqli_stmt_fetch
    • mysqli_get_cache_stats — Returns client Zval cache statistics
    • mysqli_get_client_stats — Returns client per-process statistics
    • mysqli_get_links_stats — Return information about open and cached links
    • mysqli_get_metadata — Alias for mysqli_stmt_result_metadata
    • mysqli_master_query — Enforce execution of a query on the master in a master/slave setup
    • mysqli_param_count — Alias for mysqli_stmt_param_count
    • mysqli_report — Alias of mysqli_driver->report_mode
    • mysqli_rpl_parse_enabled — Check if RPL parse is enabled
    • mysqli_rpl_probe — RPL probe
    • mysqli_send_long_data — Alias for mysqli_stmt_send_long_data
    • mysqli::set_opt — Alias of mysqli_options
    • mysqli_slave_query — Force execution of a query on a slave in a master/slave setup
  • Changelog


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 mysql 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 three main API options when considering connecting to a MySQL database server:

  • PHP's MySQL Extension

  • 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 MySQL Extension?

This is the original extension designed to allow you to develop PHP applications that interact with a MySQL database. The mysql extension provides a procedural interface and is intended for use only with MySQL versions older than 4.1.3. This extension can be used with versions of MySQL 4.1.3 or newer, but not all of the latest MySQL server features will be available.

Note:

If you are using MySQL versions 4.1.3 or later it is strongly recommended that you use the mysqli extension instead.

The mysql extension source code is located in the PHP extension directory ext/mysql.

For further information on the mysql extension, see MySQL (Original).

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

  • Embedded server support

Note:

If you are using MySQL versions 4.1.3 or later it is strongly recommended that you use this extension.

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

What is PHP's MySQL Native Driver?

In order to communicate with the MySQL database server the mysql extension, 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.

The mysql extension, 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.

Note:

The MySQL Native Driver can only be used with MySQL server versions 4.1.3 and later.

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 three 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's MySQL Extension
PHP version introduced | 5.0 | 5.0 | Prior to 3.0
Included with PHP 5.x | yes | yes | Yes
MySQL development status | Active development | Active development as of PHP 5.3 | Maintenance only
Recommended by MySQL for new projects | Yes - preferred option | Yes | No
API supports Charsets | Yes | Yes | No
API supports server-side Prepared Statements | Yes | Yes | No
API supports client-side Prepared Statements | No | Yes | No
API supports Stored Procedures | Yes | Yes | No
API supports Multiple Statements | Yes | Most | No
Supports all MySQL 4.1+ functionality | Yes | Most | No


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");
$res = mysqli_query($mysqli, "SELECT 'Please, do not use ' AS _msg FROM DUAL");
$row = mysqli_fetch_assoc($res);
echo $row['_msg'];

$mysql = mysql_connect("example.com", "user", "password");
mysql_select_db("test");
$res = mysql_query("SELECT 'the mysql extension for new developments.' AS _msg FROM DUAL", $mysql);
$row = mysql_fetch_assoc($res);
echo $row['_msg'];
?>

The above example will output:

Please, do not use the mysql extension for new developments.

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");
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$res = mysqli_query($mysqli, "SELECT 'A world full of ' AS _msg FROM DUAL");
$row = mysqli_fetch_assoc($res);
echo $row['_msg'];

$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: " . $mysqli->connect_error;
}

$res = $mysqli->query("SELECT 'choices to please everybody.' AS _msg FROM DUAL");
$row = $res->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");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: " . $mysqli->connect_error;
}

$res = mysqli_query($mysqli, "SELECT 'Possible but bad style.' AS _msg FROM DUAL");
if (!$res) {
    echo "Failed to run query: (" . $mysqli->errno . ") " . $mysqli->error;
}

if ($row = $res->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. It is not possible to open a TCP/IP connection using the hostname localhost you must use 127.0.0.1 instead.

Example #1 Special meaning of localhost

<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";

$mysqli = new mysqli("127.0.0.1", "user", "password", "database", 3306);
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

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(), 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 a unused persistent connection for a given combination of host, username, password, socket, port and default database can not 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() function 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() functions.
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 Connecting to MySQL

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT)") ||
    !$mysqli->query("INSERT INTO test(id) VALUES (1)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
?>

Buffered result sets

After statement execution results can be retrieved at once to be buffered by the client or by read row by row. Client-side result set buffering allows the server to free resources associated with the statement 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 = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT)") ||
    !$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

$res = $mysqli->query("SELECT id FROM test ORDER BY id ASC");

echo "Reverse order...\n";
for ($row_no = $res->num_rows - 1; $row_no >= 0; $row_no--) {
    $res->data_seek($row_no);
    $row = $res->fetch_assoc();
    echo " id = " . $row['id'] . "\n";
}

echo "Result set order...\n";
$res->data_seek(0);
while ($row = $res->fetch_assoc()) {
    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");
$res = $mysqli->use_result();

echo "Result set order...\n";
while ($row = $res->fetch_assoc()) {
    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 = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$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')")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

$res = $mysqli->query("SELECT id, label FROM test WHERE id = 1");
$row = $res->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 = mysqli_init();
$mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);
$mysqli->real_connect("example.com", "user", "password", "database");

if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$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')")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

$res = $mysqli->query("SELECT id, label FROM test WHERE id = 1");
$row = $res->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::init()
  • mysqli::options()
  • mysqli::real_connect()
  • mysqli::query()
  • mysqli::multi_query()
  • mysqli::use_result()
  • mysqli::store_result()
  • mysqli_result::free()


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.

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

Example #1 First stage: prepare

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

/* Non-prepared statement */
if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

/* Prepared statement, stage 1: prepare */
if (!($stmt = $mysqli->prepare("INSERT INTO test(id) VALUES (?)"))) {
    echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
?>

Prepare is followed by execute. During execute the client binds parameter values and sends them to the server. The server creates a statement from the statement template and the bound values to execute it using the previously created internal resources.

Example #2 Second stage: bind and execute

<?php
/* Prepared statement, stage 2: bind and execute */
$id = 1;
if (!$stmt->bind_param("i", $id)) {
    echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}

if (!$stmt->execute()) {
    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
?>

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 #3 INSERT prepared once, executed multiple times

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

/* Non-prepared statement */
if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

/* Prepared statement, stage 1: prepare */
if (!($stmt = $mysqli->prepare("INSERT INTO test(id) VALUES (?)"))) {
     echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

/* Prepared statement, stage 2: bind and execute */
$id = 1;
if (!$stmt->bind_param("i", $id)) {
    echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}

if (!$stmt->execute()) {
    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}

/* Prepared statement: repeated execution, only data transferred from client to server */
for ($id = 2; $id < 5; $id++) {
    if (!$stmt->execute()) {
        echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
    }
}

/* explicit close recommended */
$stmt->close();

/* Non-prepared statement */
$res = $mysqli->query("SELECT id FROM test");
var_dump($res->fetch_all());
?>

The above example will output:

array(4) {
  [0]=>
  array(1) {
    [0]=>
    string(1) "1"
  }
  [1]=>
  array(1) {
    [0]=>
    string(1) "2"
  }
  [2]=>
  array(1) {
    [0]=>
    string(1) "3"
  }
  [3]=>
  array(1) {
    [0]=>
    string(1) "4"
  }
}

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 less round-trips between the server and client than the prepared statement shown above.

Example #4 Less round trips using multi-INSERT SQL

<?php
if (!$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3), (4)")) {
    echo "Multi-INSERT failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
?>

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. The client libraries do not receive strings only. Instead, they will 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 #5 Native datatypes

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$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')")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

$stmt = $mysqli->prepare("SELECT id, label FROM test WHERE id = 1");
$stmt->execute();
$res = $stmt->get_result();
$row = $res->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)

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 #6 Output variable binding

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$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')")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!($stmt = $mysqli->prepare("SELECT id, label FROM test"))) {
    echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$stmt->execute()) {
    echo "Execute failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

$out_id    = NULL;
$out_label = NULL;
if (!$stmt->bind_result($out_id, $out_label)) {
    echo "Binding output parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}

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 = a (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 #7 Using mysqli_result to fetch results

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$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')")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!($stmt = $mysqli->prepare("SELECT id, label FROM test ORDER BY id ASC"))) {
    echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$stmt->execute()) {
     echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}

if (!($res = $stmt->get_result())) {
    echo "Getting result set failed: (" . $stmt->errno . ") " . $stmt->error;
}

var_dump($res->fetch_all());
?>

The above example will output:

array(1) {
  [0]=>
  array(2) {
    [0]=>
    int(1)
    [1]=>
    string(1) "a"
  }
}

Using the mysqli_result interface offers the additional benefit of flexible client-side result set navigation.

Example #8 Buffered result set for flexible read out

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$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'), (2, 'b'), (3, 'c')")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!($stmt = $mysqli->prepare("SELECT id, label FROM test"))) {
    echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$stmt->execute()) {
     echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}

if (!($res = $stmt->get_result())) {
    echo "Getting result set failed: (" . $stmt->errno . ") " . $stmt->error;
}

for ($row_no = ($res->num_rows - 1); $row_no >= 0; $row_no--) {
    $res->data_seek($row_no);
    var_dump($res->fetch_assoc());
}
$res->close();
?>

The above example will output:

array(2) {
  ["id"]=>
  int(3)
  ["label"]=>
  string(1) "c"
}
array(2) {
  ["id"]=>
  int(2)
  ["label"]=>
  string(1) "b"
}
array(2) {
  ["id"]=>
  int(1)
  ["label"]=>
  string(1) "a"
}

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 sometimes considered as 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.

Quick prepared - non-prepared statement comparison

The table below compares server-side prepared and non-prepared statements.

Comparison of prepared and non-prepared statements
 | Prepared Statement | Non-prepared statement
Client-server round trips, SELECT, single execution | 2 | 1
Statement string transferred from client to server | 1 | 1
Client-server round trips, SELECT, repeated (n) execution | 1 + n | n
Statement string transferred from client to server | 1 template, n times bound parameter, if any | n times together with parameter, if any
Input parameter binding API | Yes, automatic input escaping | No, manual input escaping
Output variable binding API | Yes | No
Supports use of mysqli_result API | Yes, use mysqli_stmt_get_result() | Yes
Buffered result sets | Yes, use mysqli_stmt_get_result() or binding with mysqli_stmt_store_result() | Yes, default of mysqli_query()
Unbuffered result sets | Yes, use output binding API | Yes, use mysqli_real_query() with mysqli_use_result()
MySQL Client Server protocol data transfer flavor | Binary protocol | Text protocol
Result set values SQL data types | Preserved when fetching | Converted to string or preserved when fetching
Supports all SQL statements | Recent MySQL versions support most but not all | Yes

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 = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$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;")) {
    echo "Stored procedure creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$mysqli->query("CALL p(1)")) {
    echo "CALL failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!($res = $mysqli->query("SELECT id FROM test"))) {
    echo "SELECT failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

var_dump($res->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 = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP PROCEDURE IF EXISTS p") ||
    !$mysqli->query('CREATE PROCEDURE p(OUT msg VARCHAR(50)) BEGIN SELECT "Hi!" INTO msg; END;')) {
    echo "Stored procedure creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$mysqli->query("SET @msg = ''") || !$mysqli->query("CALL p(@msg)")) {
    echo "CALL failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!($res = $mysqli->query("SELECT @msg as _p_out"))) {
    echo "Fetch failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

$row = $res->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 = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT)") ||
    !$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$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;')) {
    echo "Stored procedure creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$mysqli->multi_query("CALL p()")) {
    echo "CALL failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

do {
    if ($res = $mysqli->store_result()) {
        printf("---\n");
        var_dump($res->fetch_all());
        $res->free();
    } else {
        if ($mysqli->errno) {
            echo "Store failed: (" . $mysqli->errno . ") " . $mysqli->error;
        }
    }
} while ($mysqli->more_results() && $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 = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT)") ||
    !$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$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;')) {
    echo "Stored procedure creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!($stmt = $mysqli->prepare("CALL p()"))) {
    echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$stmt->execute()) {
    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}

do {
    if ($res = $stmt->get_result()) {
        printf("---\n");
        var_dump(mysqli_fetch_all($res));
        mysqli_free_result($res);
    } else {
        if ($stmt->errno) {
            echo "Store failed: (" . $stmt->errno . ") " . $stmt->error;
        }
    }
} while ($stmt->more_results() && $stmt->next_result());
?>

Of course, use of the bind API for fetching is supported as well.

Example #5 Stored Procedures and Prepared Statements using bind API

<?php
if (!($stmt = $mysqli->prepare("CALL p()"))) {
    echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

if (!$stmt->execute()) {
    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}

do {

    $id_out = NULL;
    if (!$stmt->bind_result($id_out)) {
        echo "Bind failed: (" . $stmt->errno . ") " . $stmt->error;
    }

    while ($stmt->fetch()) {
        echo "id = $id_out\n";
    }
} while ($stmt->more_results() && $stmt->next_result());
?>

See also

  • mysqli::query()
  • mysqli::multi_query()
  • mysqli_result::next-result()
  • mysqli_result::more-results()


Multiple Statements

MySQL optionally allows having multiple statements in one statement string. Sending multiple statements at once reduces client-server round trips but 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 = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

$sql = "SELECT COUNT(*) AS _num FROM test; ";
$sql.= "INSERT INTO test(id) VALUES (1); ";
$sql.= "SELECT COUNT(*) AS _num FROM test; ";

if (!$mysqli->multi_query($sql)) {
    echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

do {
    if ($res = $mysqli->store_result()) {
        var_dump($res->fetch_all(MYSQLI_ASSOC));
        $res->free();
    }
} while ($mysqli->more_results() && $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 likeliness 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 second, injected and malicious SQL statement.

Example #2 SQL Injection

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
$res    = $mysqli->query("SELECT 1; DROP TABLE mysql.user");
if (!$res) {
    echo "Error executing query: (" . $mysqli->errno . ") " . $mysqli->error;
}
?>

The above example will output:

Error executing query: (1064) 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_result::next-result()
  • mysqli_result::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 auto commit mode and for committing and rolling back transactions.

Example #1 Setting auto commit mode with SQL and through the API

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

/* Recommended: using API to control transactional settings */
$mysqli->autocommit(false);

/* Won't be monitored and recognized by the replication and the load balancing plugin */
if (!$mysqli->query('SET AUTOCOMMIT = 0')) {
    echo "Query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
?>

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 auto commit mode, committing or rolling back a transaction.

Example #2 Commit and rollback

<?php
$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_result::commit()
  • mysqli_result::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 = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

$res = $mysqli->query("SELECT 1 AS _one, 'Hello' AS _two FROM DUAL");
var_dump($res->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
$stmt = $mysqli->prepare("SELECT 1 AS _one, 'Hello' AS _two FROM DUAL");
$stmt->execute();
$res = $stmt->result_metadata();
var_dump($res->fetch_fields());
?>

See also

  • mysqli::query()
  • mysqli_result::fetch_fields()


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 will be supported in a future PHP release. In the meantime, 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 is most commonly installed using the binary installer.

PHP 5.3.0 and newer

On Windows, for PHP versions 5.3 and newer, the mysqli extension is enabled and uses the MySQL Native Driver by default. This means you don't need to worry about configuring access to libmysql.dll.

PHP 5.0, 5.1, 5.2

On these old unsupported PHP versions (PHP 5.2 reached EOL on '6 Jan 2011'), additional configuration procedures are required to enable mysqli and specify the client library you want it to use.

The mysqli extension is not enabled by default, so the php_mysqli.dll DLL must be enabled inside of php.ini. In order to do this you need to find the php.ini file (typically located in c:\php), and make sure you remove the comment (semi-colon) from the start of the line extension=php_mysqli.dll, in the section marked [PHP_MYSQLI].

Also, if you want to use the MySQL Client Library with mysqli, you need to make sure PHP can access the client library file. The MySQL Client Library is included as a file named libmysql.dll in the Windows PHP distribution. This file needs to be available in the Windows system's PATH environment variable, so that it can be successfully loaded. See the FAQ titled "How do I add my PHP directory to the PATH on Windows" for information on how to do this. Copying libmysql.dll to the Windows system directory (typically c:\Windows\system) also works, as the system directory is by default in the system's PATH. However, this practice is strongly discouraged.

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 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_mysqli.dll'", this is because php_mysqli.dll and/or libmysql.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" | PHP_INI_SYSTEM | Available as of PHP 5.2.4. Before PHP 7.2.16 and 7.3.3 the default was "1".
mysqli.allow_persistent | "1" | PHP_INI_SYSTEM | Available as of PHP 5.3.0.
mysqli.max_persistent | "-1" | PHP_INI_SYSTEM | Available as of PHP 5.3.0.
mysqli.max_links | "-1" | PHP_INI_SYSTEM |
mysqli.default_port | "3306" | PHP_INI_ALL |
mysqli.default_socket | NULL | PHP_INI_ALL |
mysqli.default_host | NULL | PHP_INI_ALL |
mysqli.default_user | NULL | PHP_INI_ALL |
mysqli.default_pw | NULL | PHP_INI_ALL |
mysqli.reconnect | "0" | PHP_INI_SYSTEM |
mysqli.rollback_on_cached_plink | TRUE | PHP_INI_SYSTEM | Available as of PHP 5.6.0.

For further details and definitions of the preceding PHP_INI_* constants, see the chapter on configuration changes.

Here's a short explanation of the configuration directives.

mysqli.allow_local_infile integer

Allow accessing, from PHP's perspective, local files with LOAD DATA statements

mysqli.allow_persistent integer

Enable the ability to create persistent connections using mysqli_connect().

mysqli.max_persistent integer

Maximum of persistent connections that can be made. Set to 0 for unlimited.

mysqli.max_links integer

The maximum number of MySQL connections per process.

mysqli.default_port integer

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. Doesn't apply in safe mode.

mysqli.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 safe mode.

mysqli.default_pw string

The default password to use when connecting to the database server if no other password is specified. Doesn't apply in safe mode.

mysqli.reconnect integer

Automatically reconnect if the connection was lost.

Note: This php.ini setting is ignored by the mysqlnd driver.

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.


  • « Runtime Configuration
  • The mysqli Extension and Persistent Connections »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

This extension has no resource types defined.


The mysqli Extension and Persistent Connections

Persistent connection support was introduced in PHP 5.3 for the mysqli extension. Support was already present in PDO MYSQL and ext/mysql. 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

Read options from the named group from my.cnf or the file specified with MYSQLI_READ_DEFAULT_FILE

MYSQLI_READ_DEFAULT_FILE

Read options from the named option file instead of from my.cnf

MYSQLI_OPT_CONNECT_TIMEOUT

Connect timeout in seconds

MYSQLI_OPT_LOCAL_INFILE

Enables command LOAD LOCAL INFILE

MYSQLI_INIT_COMMAND

Command to execute when connecting to MySQL server. Will automatically be re-executed when reconnecting.

MYSQLI_CLIENT_SSL

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

Use compression protocol

MYSQLI_CLIENT_INTERACTIVE

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

Allow spaces after function names. Makes all functions names reserved words.

MYSQLI_CLIENT_NO_SCHEMA

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

For using buffered resultsets

MYSQLI_USE_RESULT

For using unbuffered resultsets

MYSQLI_ASSOC

Columns are returned into the array having the fieldname as the array index.

MYSQLI_NUM

Columns are returned into the array having an enumerated index.

MYSQLI_BOTH

Columns are returned into the array having both a numerical index and the fieldname as the associative index.

MYSQLI_NOT_NULL_FLAG

Indicates that a field is defined as NOT NULL

MYSQLI_PRI_KEY_FLAG

Field is part of a primary index

MYSQLI_UNIQUE_KEY_FLAG

Field is part of a unique index.

MYSQLI_MULTIPLE_KEY_FLAG

Field is part of an index.

MYSQLI_BLOB_FLAG

Field is defined as BLOB

MYSQLI_UNSIGNED_FLAG

Field is defined as UNSIGNED

MYSQLI_ZEROFILL_FLAG

Field is defined as ZEROFILL

MYSQLI_AUTO_INCREMENT_FLAG

Field is defined as AUTO_INCREMENT

MYSQLI_TIMESTAMP_FLAG

Field is defined as TIMESTAMP

MYSQLI_SET_FLAG

Field is defined as SET

MYSQLI_NUM_FLAG

Field is defined as NUMERIC

MYSQLI_PART_KEY_FLAG

Field is part of an multi-index

MYSQLI_GROUP_FLAG

Field is part of GROUP BY

MYSQLI_TYPE_DECIMAL

Field is defined as DECIMAL

MYSQLI_TYPE_NEWDECIMAL

Precision math DECIMAL or NUMERIC field (MySQL 5.0.3 and up)

MYSQLI_TYPE_BIT

Field is defined as BIT (MySQL 5.0.3 and up)

MYSQLI_TYPE_TINY

Field is defined as TINYINT

MYSQLI_TYPE_SHORT

Field is defined as SMALLINT

MYSQLI_TYPE_LONG

Field is defined as INT

MYSQLI_TYPE_FLOAT

Field is defined as FLOAT

MYSQLI_TYPE_DOUBLE

Field is defined as DOUBLE

MYSQLI_TYPE_NULL

Field is defined as DEFAULT NULL

MYSQLI_TYPE_TIMESTAMP

Field is defined as TIMESTAMP

MYSQLI_TYPE_LONGLONG

Field is defined as BIGINT

MYSQLI_TYPE_INT24

Field is defined as MEDIUMINT

MYSQLI_TYPE_DATE

Field is defined as DATE

MYSQLI_TYPE_TIME

Field is defined as TIME

MYSQLI_TYPE_DATETIME

Field is defined as DATETIME

MYSQLI_TYPE_YEAR

Field is defined as YEAR

MYSQLI_TYPE_NEWDATE

Field is defined as DATE

MYSQLI_TYPE_INTERVAL

Field is defined as INTERVAL

MYSQLI_TYPE_ENUM

Field is defined as ENUM

MYSQLI_TYPE_SET

Field is defined as SET

MYSQLI_TYPE_TINY_BLOB

Field is defined as TINYBLOB

MYSQLI_TYPE_MEDIUM_BLOB

Field is defined as MEDIUMBLOB

MYSQLI_TYPE_LONG_BLOB

Field is defined as LONGBLOB

MYSQLI_TYPE_BLOB

Field is defined as BLOB

MYSQLI_TYPE_VAR_STRING

Field is defined as VARCHAR

MYSQLI_TYPE_STRING

Field is defined as CHAR or BINARY

MYSQLI_TYPE_CHAR

Field is defined as TINYINT. For CHAR, see MYSQLI_TYPE_STRING

MYSQLI_TYPE_GEOMETRY

Field is defined as GEOMETRY

MYSQLI_NEED_DATA

More data available for bind variable

MYSQLI_NO_DATA

No more data available for bind variable

MYSQLI_DATA_TRUNCATED

Data truncation occurred. Available since PHP 5.1.0 and MySQL 5.0.5.

MYSQLI_ENUM_FLAG

Field is defined as ENUM. Available since PHP 5.3.0.

MYSQLI_BINARY_FLAG

Field is defined as BINARY. Available since PHP 5.3.0.

MYSQLI_CURSOR_TYPE_FOR_UPDATE

MYSQLI_CURSOR_TYPE_NO_CURSOR

MYSQLI_CURSOR_TYPE_READ_ONLY

MYSQLI_CURSOR_TYPE_SCROLLABLE

MYSQLI_STMT_ATTR_CURSOR_TYPE

MYSQLI_STMT_ATTR_PREFETCH_ROWS

MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH

MYSQLI_SET_CHARSET_NAME

MYSQLI_REPORT_INDEX

Report if no index or bad index was used in a query.

MYSQLI_REPORT_ERROR

Report errors from mysqli function calls.

MYSQLI_REPORT_STRICT

Throw a mysqli_sql_exception for errors instead of warnings.

MYSQLI_REPORT_ALL

Set all options on (report all).

MYSQLI_REPORT_OFF

Turns reporting off.

MYSQLI_DEBUG_TRACE_ENABLED

Is set to 1 if mysqli_debug() functionality is enabled.

MYSQLI_SERVER_QUERY_NO_GOOD_INDEX_USED

MYSQLI_SERVER_QUERY_NO_INDEX_USED

MYSQLI_REFRESH_GRANT

Refreshes the grant tables.

MYSQLI_REFRESH_LOG

Flushes the logs, like executing the FLUSH LOGS SQL statement.

MYSQLI_REFRESH_TABLES

Flushes the table cache, like executing the FLUSH TABLES SQL statement.

MYSQLI_REFRESH_HOSTS

Flushes the host cache, like executing the FLUSH HOSTS SQL statement.

MYSQLI_REFRESH_STATUS

Reset the status variables, like executing the FLUSH STATUS SQL statement.

MYSQLI_REFRESH_THREADS

Flushes the thread cache.

MYSQLI_REFRESH_SLAVE

On a slave replication server: resets the master server information, and restarts the slave. Like executing the RESET SLAVE SQL statement.

MYSQLI_REFRESH_MASTER

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.

MYSQLI_TRANS_COR_AND_CHAIN

Appends "AND CHAIN" to mysqli_commit() or mysqli_rollback().

MYSQLI_TRANS_COR_AND_NO_CHAIN

Appends "AND NO CHAIN" to mysqli_commit() or mysqli_rollback().

MYSQLI_TRANS_COR_RELEASE

Appends "RELEASE" to mysqli_commit() or mysqli_rollback().

MYSQLI_TRANS_COR_NO_RELEASE

Appends "NO RELEASE" to mysqli_commit() or mysqli_rollback().

MYSQLI_TRANS_START_READ_ONLY

Start the transaction as "START TRANSACTION READ ONLY" with mysqli_begin_transaction().

MYSQLI_TRANS_START_READ_WRITE

Start the transaction as "START TRANSACTION READ WRITE" with mysqli_begin_transaction().

MYSQLI_TRANS_START_CONSISTENT_SNAPSHOT

Start the transaction as "START TRANSACTION WITH CONSISTENT SNAPSHOT" with mysqli_begin_transaction().


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::client_encoding | mysqli_character_set_name() | mysqli_client_encoding() | 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
mysqli::get_client_stats() | mysqli_get_client_stats() | N/A | Returns client per-process statistics. Available only with mysqlnd.
mysqli::get_cache_stats() | mysqli_get_cache_stats() | N/A | Returns client Zval cache 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 a resource for use with mysqli_real_connect. [Not called on an object, as it returns a $mysqli object.]
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::set_local_infile_default() | mysqli_set_local_infile_default() | N/A | Unsets user defined handler for load local infile command
mysqli::set_local_infile_handler() | mysqli_set_local_infile_handler() | N/A | Set callback function for LOAD DATA LOCAL INFILE command
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() | mysqli_param_count() | 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() | mysqli_bind_param() | Binds variables to a prepared statement as parameters
mysqli_stmt::bind_result() | mysqli_stmt_bind_result() | mysqli_bind_result() | 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() | mysqli_fetch() | 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() | mysqli_get_metadata() | Returns result set metadata from a prepared statement
mysqli_stmt::send_long_data() | mysqli_stmt_send_long_data() | mysqli_send_long_data() | 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_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
N/A
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 Extension Function Summary
  • MySQLi extension basic examples »
  • PHP Manual
  • MySQLi
  • Examples

Examples

Table of Contents

  • MySQLi extension basic examples


MySQLi extension basic examples

This example shows how to connect, execute a query, use basic error handling, print resulting rows, and disconnect from a MySQL database.

This example uses the freely available Sakila database that can be downloaded from » dev.mysql.com, as described here. To get this example to work, (a) install sakila and (b) modify the connection variables (host, your_user, your_pass).

Example #1 MySQLi extension overview example

<?php
// Let's pass in a $_GET variable to our example, in this case
// it's aid for actor_id in our Sakila database. Let's make it
// default to 1, and cast it to an integer as to avoid SQL injection
// and/or related security problems. Handling all of this goes beyond
// the scope of this simple example. Example:
//   http://example.org/script.php?aid=42
if (isset($_GET['aid']) && is_numeric($_GET['aid'])) {
    $aid = (int) $_GET['aid'];
} else {
    $aid = 1;
}

// Connecting to and selecting a MySQL database named sakila
// Hostname: 127.0.0.1, username: your_user, password: your_pass, db: sakila
$mysqli = new mysqli('127.0.0.1', 'your_user', 'your_pass', 'sakila');

// Oh no! A connect_errno exists so the connection attempt failed!
if ($mysqli->connect_errno) {
    // The connection failed. What do you want to do?
    // You could contact yourself (email?), log the error, show a nice page, etc.
    // You do not want to reveal sensitive information

    // Let's try this:
    echo "Sorry, this website is experiencing problems.";

    // Something you should not do on a public site, but this example will show you
    // anyways, is print out MySQL error related information -- you might log this
    echo "Error: Failed to make a MySQL connection, here is why: \n";
    echo "Errno: " . $mysqli->connect_errno . "\n";
    echo "Error: " . $mysqli->connect_error . "\n";

    // You might want to show them something nice, but we will simply exit
    exit;
}

// Perform an SQL query
$sql = "SELECT actor_id, first_name, last_name FROM actor WHERE actor_id = $aid";
if (!$result = $mysqli->query($sql)) {
    // Oh no! The query failed.
    echo "Sorry, the website is experiencing problems.";

    // Again, do not do this on a public site, but we'll show you how
    // to get the error information
    echo "Error: Our query failed to execute and here is why: \n";
    echo "Query: " . $sql . "\n";
    echo "Errno: " . $mysqli->errno . "\n";
    echo "Error: " . $mysqli->error . "\n";
    exit;
}

// Phew, we made it. We know our MySQL connection and query
// succeeded, but do we have a result?
if ($result->num_rows === 0) {
    // Oh, no rows! Sometimes that's expected and okay, sometimes
    // it is not. You decide. In this case, maybe actor_id was too
    // large?
    echo "We could not find a match for ID $aid, sorry about that. Please try again.";
    exit;
}

// Now, we know only one result will exist in this example so let's
// fetch it into an associated array where the array's keys are the
// table's column names
$actor = $result->fetch_assoc();
echo "Sometimes I see " . $actor['first_name'] . " " . $actor['last_name'] . " on TV.";

// Now, let's fetch five random actors and output their names to a list.
// We'll add less error handling here as you can do that on your own now
$sql = "SELECT actor_id, first_name, last_name FROM actor ORDER BY rand() LIMIT 5";
if (!$result = $mysqli->query($sql)) {
    echo "Sorry, the website is experiencing problems.";
    exit;
}

// Print our 5 random actors in a list, and link to each actor
echo "<ul>\n";
while ($actor = $result->fetch_assoc()) {
    echo "<li><a href='" . $_SERVER['SCRIPT_FILENAME'] . "?aid=" . $actor['actor_id'] . "'>\n";
    echo $actor['first_name'] . ' ' . $actor['last_name'];
    echo "</a></li>\n";
}
echo "</ul>\n";

// The script will automatically free the result and close the MySQL
// connection when it exits, but let's just do it anyways
$result->free();
$mysqli->close();
?>


The mysqli class

(PHP 5, PHP 7)

Introduction

Represents a connection between PHP and a MySQL database.

Class synopsis

mysqli {
/* Properties */
int $affected_rows;
int $connect_errno;
string $connect_error;
int $errno;
array $error_list;
string $error;
int $field_count;
string $client_info;
int $client_version;
string $host_info;
string $protocol_version;
string $server_info;
int $server_version;
string $info;
mixed $insert_id;
string $sqlstate;
int $thread_id;
int $warning_count;
/* Methods */
 __construct
  ([ string $host = ini_get("mysqli.default_host")
 [, string $username = ini_get("mysqli.default_user")
 [, string $passwd = ini_get("mysqli.default_pw")
 [, string $dbname = ""
 [, int $port = ini_get("mysqli.default_port")
 [, string $socket = ini_get("mysqli.default_socket")
]]]]]] )
autocommit ( bool $mode ) : bool
change_user ( string $user , string $password , string $database ) : bool
character_set_name ( void ) : string
close ( void ) : bool
commit ([ int $flags = 0 [, string $name ]] ) : bool
 connect
  ([ string $host = ini_get("mysqli.default_host")
 [, string $username = ini_get("mysqli.default_user")
 [, string $passwd = ini_get("mysqli.default_pw")
 [, string $dbname = ""
 [, int $port = ini_get("mysqli.default_port")
 [, string $socket = ini_get("mysqli.default_socket")
]]]]]] ) : void
debug ( string $message ) : bool
dump_debug_info ( void ) : bool
get_charset ( void ) : object
get_client_info ( void ) : string
get_connection_stats ( void ) : bool
mysqli_stmt::get_server_info ( void ) : string
get_warnings ( void ) : mysqli_warning
init ( void ) : mysqli
kill ( int $processid ) : bool
more_results ( void ) : bool
multi_query ( string $query ) : bool
next_result ( void ) : bool
options ( int $option , mixed $value ) : bool
ping ( void ) : bool
public static poll ( array &$read , array &$error , array &$reject , int $sec [, int $usec = 0 ] ) : int
prepare ( string $query ) : mysqli_stmt
query ( string $query [, int $resultmode = MYSQLI_STORE_RESULT ] ) : mixed
real_connect ([ string $host [, string $username [, string $passwd [, string $dbname [, int $port [, string $socket [, int $flags ]]]]]]] ) : bool
escape_string ( string $escapestr ) : string
real_escape_string ( string $escapestr ) : string
real_query ( string $query ) : bool
public reap_async_query ( void ) : mysqli_result
public refresh ( int $options ) : bool
rollback ([ int $flags = 0 [, string $name ]] ) : bool
rpl_query_type ( string $query ) : int
select_db ( string $dbname ) : bool
send_query ( string $query ) : bool
set_charset ( string $charset ) : bool
set_local_infile_handler ( mysqli $link , callable $read_func ) : bool
ssl_set ( string $key , string $cert , string $ca , string $capath , string $cipher ) : bool
stat ( void ) : string
stmt_init ( void ) : mysqli_stmt
store_result ([ int $option ] ) : mysqli_result
use_result ( void ) : mysqli_result
}

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 specified database connection
  • mysqli::character_set_name — Returns the default character set for 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 string description of the last connect 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_list — Returns a list of errors from the last command executed
  • mysqli::$error — Returns a string description of the last error
  • 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 a resource for use with mysqli_real_connect()
  • mysqli::$insert_id — Returns the auto generated id used in the latest 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 a query 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 — Prepare an SQL statement for execution
  • mysqli::query — Performs a query on the database
  • mysqli::real_connect — Opens a connection to a 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::rpl_query_type — Returns RPL query type
  • mysqli::savepoint — Set a named transaction savepoint
  • mysqli::select_db — Selects the default database for database queries
  • mysqli::send_query — Send the query and return
  • mysqli::set_charset — Sets the default client character set
  • mysqli::set_local_infile_default — Unsets user defined handler for load local infile command
  • mysqli::set_local_infile_handler — Set callback function for LOAD DATA LOCAL INFILE command
  • 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 from the last query for the given link


Gets the number of affected rows in a previous MySQL operation

  • « mysqli
  • mysqli::autocommit »
  • PHP Manual
  • mysqli
  • Gets the number of affected rows in a previous MySQL operation

mysqli::$affected_rows

mysqli_affected_rows

(PHP 5, PHP 7)

mysqli::$affected_rows -- mysqli_affected_rows — Gets the number of affected rows in a previous MySQL operation

Description

Object oriented style

int $mysqli->affected_rows;

Procedural style

mysqli_affected_rows ( mysqli $link ) : int

Returns the number of rows affected by the last INSERT, UPDATE, REPLACE or DELETE query.

For SELECT statements mysqli_affected_rows() works like mysqli_num_rows().

Parameters

link

Procedural style only: A link identifier 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.

Note:

If the number of affected rows is greater than the maximum integer 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 = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* 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);

$result->close();

/* Delete table Language */
$mysqli->query("DROP TABLE Language");

/* close connection */
$mysqli->close();
?>

Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

if (!$link) {
    printf("Can't connect to localhost. Error: %s\n", mysqli_connect_error());
    exit();
}

/* 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));

mysqli_free_result($result);

/* Delete table Language */
mysqli_query($link, "DROP TABLE Language");

/* close connection */
mysqli_close($link);
?>

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 a result
  • mysqli_info() - Retrieves information about the most recently executed query


Turns on or off auto-committing database modifications

  • « mysqli::$affected_rows
  • mysqli::begin_transaction »
  • PHP Manual
  • mysqli
  • Turns on or off auto-committing database modifications

mysqli::autocommit

mysqli_autocommit

(PHP 5, PHP 7)

mysqli::autocommit -- mysqli_autocommit — Turns on or off auto-committing database modifications

Description

Object oriented style

mysqli::autocommit ( bool $mode ) : bool

Procedural style

mysqli_autocommit ( mysqli $link , bool $mode ) : 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

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

mode

Whether to turn on auto-commit or not.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note:

This function doesn't work with non transactional table types (like MyISAM or ISAM).

Examples

Example #1 mysqli::autocommit() example

Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* turn autocommit on */
$mysqli->autocommit(TRUE);

if ($result = $mysqli->query("SELECT @@autocommit")) {
    $row = $result->fetch_row();
    printf("Autocommit is %s\n", $row[0]);
    $result->free();
}

/* close connection */
$mysqli->close();
?>

Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

if (!$link) {
    printf("Can't connect to localhost. Error: %s\n", mysqli_connect_error());
    exit();
}

/* turn autocommit on */
mysqli_autocommit($link, TRUE);

if ($result = mysqli_query($link, "SELECT @@autocommit")) {
    $row = mysqli_fetch_row($result);
    printf("Autocommit is %s\n", $row[0]);
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

The above examples will output:

Autocommit is 1

See Also

  • mysqli_begin_transaction() - Starts a transaction
  • mysqli_commit() - Commits the current transaction
  • mysqli_rollback() - Rolls back current transaction


Starts a transaction

  • « mysqli::autocommit
  • mysqli::change_user »
  • PHP Manual
  • mysqli
  • Starts a transaction

mysqli::begin_transaction

mysqli_begin_transaction

(PHP 5 >= 5.5.0, PHP 7)

mysqli::begin_transaction -- mysqli_begin_transaction — Starts a transaction

Description

Object oriented style (method):

public mysqli::begin_transaction ([ int $flags = 0 [, string $name ]] ) : bool

Procedural style:

mysqli_begin_transaction ( mysqli $link [, int $flags = 0 [, string $name ]] ) : 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

link

Procedural style only: A link identifier 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.

Examples

Example #1 $mysqli->begin_transaction() example

Object oriented style

<?php
$mysqli = new mysqli("127.0.0.1", "my_user", "my_password", "sakila");

if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

$mysqli->begin_transaction(MYSQLI_TRANS_START_READ_ONLY);

$mysqli->query("SELECT first_name, last_name FROM actor");
$mysqli->commit();

$mysqli->close();
?>

Procedural style

<?php
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "sakila");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

mysqli_begin_transaction($link, MYSQLI_TRANS_START_READ_ONLY);

mysqli_query($link, "SELECT first_name, last_name FROM actor LIMIT 1");
mysqli_commit($link);

mysqli_close($link);
?>

See Also

  • mysqli_autocommit() - Turns on or off auto-committing database modifications
  • mysqli_commit() - Commits the current transaction
  • mysqli_rollback() - Rolls back current transaction


Changes the user of the specified database connection

  • « mysqli::begin_transaction
  • mysqli::character_set_name »
  • PHP Manual
  • mysqli
  • Changes the user of the specified database connection

mysqli::change_user

mysqli_change_user

(PHP 5, PHP 7)

mysqli::change_user -- mysqli_change_user — Changes the user of the specified database connection

Description

Object oriented style

mysqli::change_user ( string $user , string $password , string $database ) : bool

Procedural style

mysqli_change_user ( mysqli $link , string $user , string $password , string $database ) : bool

Changes the user of the specified database connection and sets the current database.

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

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

user

The MySQL user name.

password

The MySQL password.

database

The database to change to.

If desired, the NULL value may be passed resulting in only changing the user and not selecting a database. To select a database in this case use the mysqli_select_db() function.

Return Values

Returns TRUE on success or FALSE on failure.

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.

Examples

Example #1 mysqli::change_user() example

Object oriented style

<?php

/* connect database test */
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Set Variable a */
$mysqli->query("SET @a:=1");

/* reset all and select a new database */
$mysqli->change_user("my_user", "my_password", "world");

if ($result = $mysqli->query("SELECT DATABASE()")) {
    $row = $result->fetch_row();
    printf("Default database: %s\n", $row[0]);
    $result->close();
}

if ($result = $mysqli->query("SELECT @a")) {
    $row = $result->fetch_row();
    if ($row[0] === NULL) {
        printf("Value of variable a is NULL\n");
    }
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Procedural style

<?php
/* connect database test */
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Set Variable a */
mysqli_query($link, "SET @a:=1");

/* reset all and select a new database */
mysqli_change_user($link, "my_user", "my_password", "world");

if ($result = mysqli_query($link, "SELECT DATABASE()")) {
    $row = mysqli_fetch_row($result);
    printf("Default database: %s\n", $row[0]);
    mysqli_free_result($result);
}

if ($result = mysqli_query($link, "SELECT @a")) {
    $row = mysqli_fetch_row($result);
    if ($row[0] === NULL) {
        printf("Value of variable a is NULL\n");
    }
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

The above examples will output:

Default database: world
Value of variable a is NULL

See Also

  • mysqli_connect() - Alias of mysqli::__construct
  • mysqli_select_db() - Selects the default database for database queries


Returns the default character set for the database connection

  • « mysqli::change_user
  • mysqli::close »
  • PHP Manual
  • mysqli
  • Returns the default character set for the database connection

mysqli::character_set_name

mysqli_character_set_name

(PHP 5, PHP 7)

mysqli::character_set_name -- mysqli_character_set_name — Returns the default character set for the database connection

Description

Object oriented style

mysqli::character_set_name ( void ) : string

Procedural style

mysqli_character_set_name ( mysqli $link ) : string

Returns the current character set for the database connection.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

The default character set for the current connection

Examples

Example #1 mysqli::character_set_name() example

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();
}

/* Print current character set */
$charset = $mysqli->character_set_name();
printf ("Current character set is %s\n", $charset);

$mysqli->close();
?>

Procedural style

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Print current character set */
$charset = mysqli_character_set_name($link);
printf ("Current character set is %s\n",$charset);

/* close connection */
mysqli_close($link);
?>

The above examples will output:

Current character set is latin1_swedish_ci

See Also

  • mysqli_set_charset() - Sets the default client character set
  • mysqli_client_encoding() - Alias of mysqli_character_set_name
  • 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


Closes a previously opened database connection

  • « mysqli::character_set_name
  • mysqli::commit »
  • PHP Manual
  • mysqli
  • Closes a previously opened database connection

mysqli::close

mysqli_close

(PHP 5, PHP 7)

mysqli::close -- mysqli_close — Closes a previously opened database connection

Description

Object oriented style

mysqli::close ( void ) : bool

Procedural style

mysqli_close ( mysqli $link ) : bool

Closes a previously opened database connection.

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

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

See mysqli_connect().

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 a resource for use with mysqli_real_connect()
  • mysqli_real_connect() - Opens a connection to a mysql server
  • mysqli_free_result() - Frees the memory associated with a result


Commits the current transaction

  • « mysqli::close
  • mysqli::$connect_errno »
  • PHP Manual
  • mysqli
  • Commits the current transaction

mysqli::commit

mysqli_commit

(PHP 5, PHP 7)

mysqli::commit -- mysqli_commit — Commits the current transaction

Description

Object oriented style

mysqli::commit ([ int $flags = 0 [, string $name ]] ) : bool

Procedural style

mysqli_commit ( mysqli $link [, int $flags = 0 [, string $name ]] ) : bool

Commits the current transaction for the database connection.

Parameters

link

Procedural style only: A link identifier 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.

Changelog

Version | Description
5.5.0 | Added flags and name parameters.

Examples

Example #1 mysqli::commit() 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();
}

$mysqli->query("CREATE TABLE Language LIKE CountryLanguage");

/* set autocommit to off */
$mysqli->autocommit(FALSE);

/* Insert some values */
$mysqli->query("INSERT INTO Language VALUES ('DEU', 'Bavarian', 'F', 11.2)");
$mysqli->query("INSERT INTO Language VALUES ('DEU', 'Swabian', 'F', 9.4)");

/* commit transaction */
if (!$mysqli->commit()) {
    print("Transaction commit failed\n");
    exit();
}

/* drop table */
$mysqli->query("DROP TABLE Language");

/* close connection */
$mysqli->close();
?>

Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* set autocommit to off */
mysqli_autocommit($link, FALSE);

mysqli_query($link, "CREATE TABLE Language LIKE CountryLanguage");

/* Insert some values */
mysqli_query($link, "INSERT INTO Language VALUES ('DEU', 'Bavarian', 'F', 11.2)");
mysqli_query($link, "INSERT INTO Language VALUES ('DEU', 'Swabian', 'F', 9.4)");

/* commit transaction */
if (!mysqli_commit($link)) {
    print("Transaction commit failed\n");
    exit();
}

/* close connection */
mysqli_close($link);
?>

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


Returns the error code from last connect call

  • « mysqli::commit
  • mysqli::$connect_error »
  • PHP Manual
  • mysqli
  • Returns the error code from last connect call

mysqli::$connect_errno

mysqli_connect_errno

(PHP 5, PHP 7)

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 ( void ) : int

Returns the last error code number from the last call to mysqli_connect().

Note:

Client error message numbers are listed in the MySQL errmsg.h header file, server error message numbers are listed in mysqld_error.h. In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error.txt.

Return Values

An error code value for the last call to mysqli_connect(), if it failed. zero means no error occurred.

Examples

Example #1 $mysqli->connect_errno example

Object oriented style

<?php
$mysqli = @new mysqli('localhost', 'fake_user', 'my_password', 'my_db');

if ($mysqli->connect_errno) {
    die('Connect Error: ' . $mysqli->connect_errno);
}
?>

Procedural style

<?php
$link = @mysqli_connect('localhost', 'fake_user', 'my_password', 'my_db');

if (!$link) {
    die('Connect Error: ' . mysqli_connect_errno());
}
?>

The above examples will output:

Connect Error: 1045

See Also

  • mysqli_connect() - Alias of mysqli::__construct
  • mysqli_connect_error() - Returns a string description of the last connect 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


Returns a string description of the last connect error

  • « mysqli::$connect_errno
  • mysqli::__construct »
  • PHP Manual
  • mysqli
  • Returns a string description of the last connect error

mysqli::$connect_error

mysqli_connect_error

(PHP 5, PHP 7)

mysqli::$connect_error -- mysqli_connect_error — Returns a string description of the last connect error

Description

Object oriented style

string $mysqli->connect_error;

Procedural style

mysqli_connect_error ( void ) : string

Returns the last error message string from the last call to mysqli_connect().

Return Values

A string that describes the error. NULL is returned if no error occurred.

Examples

Example #1 $mysqli->connect_error example

Object oriented style

<?php
$mysqli = @new mysqli('localhost', 'fake_user', 'my_password', 'my_db');

// Works as of PHP 5.2.9 and 5.3.0.
if ($mysqli->connect_error) {
    die('Connect Error: ' . $mysqli->connect_error);
}
?>

Procedural style

<?php
$link = @mysqli_connect('localhost', 'fake_user', 'my_password', 'my_db');

if (!$link) {
    die('Connect Error: ' . mysqli_connect_error());
}
?>

The above examples will output:

Connect Error: Access denied for user 'fake_user'@'localhost' (using password: YES)

Notes

Warning

The mysqli->connect_error property only works properly as of PHP versions 5.2.9 and 5.3.0. Use the mysqli_connect_error() function if compatibility with earlier PHP versions is required.

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


Open a new connection to the MySQL server

  • « mysqli::$connect_error
  • mysqli::debug »
  • PHP Manual
  • mysqli
  • Open a new connection to the MySQL server

mysqli::__construct

mysqli::connect

mysqli_connect

(PHP 5, PHP 7)

mysqli::__construct -- mysqli::connect -- mysqli_connect — Open a new connection to the MySQL server

Description

Object oriented style

 mysqli::__construct
  ([ string $host = ini_get("mysqli.default_host")
 [, string $username = ini_get("mysqli.default_user")
 [, string $passwd = ini_get("mysqli.default_pw")
 [, string $dbname = ""
 [, int $port = ini_get("mysqli.default_port")
 [, string $socket = ini_get("mysqli.default_socket")
]]]]]] )
 mysqli::connect
  ([ string $host = ini_get("mysqli.default_host")
 [, string $username = ini_get("mysqli.default_user")
 [, string $passwd = ini_get("mysqli.default_pw")
 [, string $dbname = ""
 [, int $port = ini_get("mysqli.default_port")
 [, string $socket = ini_get("mysqli.default_socket")
]]]]]] ) : void

Procedural style

 mysqli_connect
  ([ string $host = ini_get("mysqli.default_host")
 [, string $username = ini_get("mysqli.default_user")
 [, string $passwd = ini_get("mysqli.default_pw")
 [, string $dbname = ""
 [, int $port = ini_get("mysqli.default_port")
 [, string $socket = ini_get("mysqli.default_socket")
]]]]]] ) : mysqli

Opens a connection to the MySQL Server.

Parameters

host

Can be either a host name or an IP address. Passing the NULL value or the string "localhost" to this parameter, the local host is assumed. When possible, pipes will be used instead of the TCP/IP protocol.

Prepending host by p: opens a persistent connection. mysqli_change_user() is automatically called on connections opened from the connection pool.

username

The MySQL user name.

passwd

If not provided or NULL, the MySQL server will attempt to authenticate the user against those user records which have no password only. This allows one username to be used with different permissions (depending on if a password is provided or not).

dbname

If provided will specify the default database to be used when performing queries.

port

Specifies the port number to attempt to connect to the MySQL server.

socket

Specifies the socket or named pipe that should be used.

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 host parameter.

Return Values

Returns an object which represents the connection to a MySQL Server, or FALSE on failure.

Changelog

Version | Description
5.3.0 | Added the ability of persistent connections.

Examples

Example #1 mysqli::__construct() example

Object oriented style

<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');

/*
 * This is the "official" OO way to do it,
 * BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
 */
if ($mysqli->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') '
            . $mysqli->connect_error);
}

/*
 * Use this instead of $connect_error if you need to ensure
 * compatibility with PHP versions prior to 5.2.9 and 5.3.0.
 */
if (mysqli_connect_error()) {
    die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
}

echo 'Success... ' . $mysqli->host_info . "\n";

$mysqli->close();
?>

Object oriented style when extending mysqli class

<?php

class foo_mysqli extends mysqli {
    public function __construct($host, $user, $pass, $db) {
        parent::__construct($host, $user, $pass, $db);

        if (mysqli_connect_error()) {
            die('Connect Error (' . mysqli_connect_errno() . ') '
                    . mysqli_connect_error());
        }
    }
}

$db = new foo_mysqli('localhost', 'my_user', 'my_password', 'my_db');

echo 'Success... ' . $db->host_info . "\n";

$db->close();
?>

Procedural style

<?php
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');

if (!$link) {
    die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
}

echo 'Success... ' . mysqli_get_host_info($link) . "\n";

mysqli_close($link);
?>

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

Note:

OO syntax only: If a connection fails an object is still returned. To check if the connection failed then 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 a mysql server
  • mysqli_options() - Set options
  • mysqli_connect_errno() - Returns the error code from last connect call
  • mysqli_connect_error() - Returns a string description of the last connect error
  • mysqli_close() - Closes a previously opened database connection


Performs debugging operations

  • « mysqli::__construct
  • mysqli::dump_debug_info »
  • PHP Manual
  • mysqli
  • Performs debugging operations

mysqli::debug

mysqli_debug

(PHP 5, PHP 7)

mysqli::debug -- mysqli_debug — Performs debugging operations

Description

Object oriented style

mysqli::debug ( string $message ) : bool

Procedural style

mysqli_debug ( string $message ) : bool

Performs debugging operations using the Fred Fish debugging library.

Parameters

message

A string representing the debugging operation to perform

Return Values

Returns TRUE.

Notes

Note:

To use the mysqli_debug() function you must compile the MySQL client library to support debugging.

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");

?>

See Also

  • mysqli_dump_debug_info() - Dump debugging information into the log
  • mysqli_report() - Alias of mysqli_driver->report_mode


Dump debugging information into the log

  • « mysqli::debug
  • mysqli::$errno »
  • PHP Manual
  • mysqli
  • Dump debugging information into the log

mysqli::dump_debug_info

mysqli_dump_debug_info

(PHP 5, PHP 7)

mysqli::dump_debug_info -- mysqli_dump_debug_info — Dump debugging information into the log

Description

Object oriented style

mysqli::dump_debug_info ( void ) : bool

Procedural style

mysqli_dump_debug_info ( mysqli $link ) : 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

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • mysqli_debug() - Performs debugging operations


Returns the error code for the most recent function call

  • « mysqli::dump_debug_info
  • mysqli::$error_list »
  • PHP Manual
  • mysqli
  • Returns the error code for the most recent function call

mysqli::$errno

mysqli_errno

(PHP 5, PHP 7)

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 $link ) : int

Returns the last error code for the most recent MySQLi function call that can succeed or fail.

Client error message numbers are listed in the MySQL errmsg.h header file, server error message numbers are listed in mysqld_error.h. In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error.txt.

Parameters

link

Procedural style only: A link identifier 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 string description of the last connect error
  • mysqli_error() - Returns a string description of the last error
  • mysqli_sqlstate() - Returns the SQLSTATE error from previous MySQL operation


Returns a list of errors from the last command executed

  • « mysqli::$errno
  • mysqli::$error »
  • PHP Manual
  • mysqli
  • Returns a list of errors from the last command executed

mysqli::$error_list

mysqli_error_list

(PHP 5 >= 5.4.0, PHP 7)

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 $link ) : array

Returns a array of errors for the most recent MySQLi function call that can succeed or fail.

Parameters

link

Procedural style only: A link identifier 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 string description of the last connect error
  • mysqli_error() - Returns a string description of the last error
  • mysqli_sqlstate() - Returns the SQLSTATE error from previous MySQL operation


Returns a string description of the last error

  • « mysqli::$error_list
  • mysqli::$field_count »
  • PHP Manual
  • mysqli
  • Returns a string description of the last error

mysqli::$error

mysqli_error

(PHP 5, PHP 7)

mysqli::$error -- mysqli_error — Returns a string description of the last error

Description

Object oriented style

string $mysqli->error;

Procedural style

mysqli_error ( mysqli $link ) : string

Returns the last error message for the most recent MySQLi function call that can succeed or fail.

Parameters

link

Procedural style only: A link identifier 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 string description of the last connect error
  • mysqli_errno() - Returns the error code for the most recent function call
  • mysqli_sqlstate() - Returns the SQLSTATE error from previous MySQL operation


Returns the number of columns for the most recent query

  • « mysqli::$error
  • mysqli::get_charset »
  • PHP Manual
  • mysqli
  • Returns the number of columns for the most recent query

mysqli::$field_count

mysqli_field_count

(PHP 5, PHP 7)

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 $link ) : int

Returns the number of columns for the most recent query on the connection represented by the link 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

link

Procedural style only: A link identifier 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);
?>


Returns a character set object

  • « mysqli::$field_count
  • mysqli::$client_info »
  • PHP Manual
  • mysqli
  • Returns a character set object

mysqli::get_charset

mysqli_get_charset

(PHP 5 >= 5.1.0, PHP 7)

mysqli::get_charset -- mysqli_get_charset — Returns a character set object

Description

Object oriented style

mysqli::get_charset ( void ) : object

Procedural style

mysqli_get_charset ( mysqli $link ) : object

Returns a character set object providing several properties of the current active character set.

Parameters

link

Procedural style only: A link identifier 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 charset 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

Character set status (?)

Examples

Example #1 mysqli::get_charset() example

Object oriented style

<?php
  $db = mysqli_init();
  $db->real_connect("localhost","root","","test");
  var_dump($db->get_charset());
?>

Procedural style

<?php
  $db = mysqli_init();
  mysqli_real_connect($db, "localhost","root","","test");
  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(801)
}

See Also

  • mysqli_character_set_name() - Returns the default character set for the database connection
  • mysqli_set_charset() - Sets the default client character set


Get MySQL client info

  • « mysqli::get_charset
  • mysqli::$client_version »
  • PHP Manual
  • mysqli
  • Get MySQL client info

mysqli::$client_info

mysqli::get_client_info

mysqli_get_client_info

(PHP 5, PHP 7)

mysqli::$client_info -- mysqli::get_client_info -- mysqli_get_client_info — Get MySQL client info

Description

Object oriented style

string $mysqli->client_info;
mysqli::get_client_info ( void ) : string

Procedural style

mysqli_get_client_info ([ mysqli $link = NULL ] ) : string

Returns a string that represents the MySQL client library version.

Return Values

A string that represents the MySQL client library version

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


Returns the MySQL client version as an integer

  • « mysqli::$client_info
  • mysqli::get_connection_stats »
  • PHP Manual
  • mysqli
  • Returns the MySQL client version as an integer

mysqli::$client_version

mysqli_get_client_version

(PHP 5, PHP 7)

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 ( mysqli $link ) : int

Returns client version number as an integer.

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


Returns statistics about the client connection

  • « mysqli::$client_version
  • mysqli::$host_info »
  • PHP Manual
  • mysqli
  • Returns statistics about the client connection

mysqli::get_connection_stats

mysqli_get_connection_stats

(PHP 5 >= 5.3.0, PHP 7)

mysqli::get_connection_stats -- mysqli_get_connection_stats — Returns statistics about the client connection

Description

Object oriented style

mysqli::get_connection_stats ( void ) : bool

Procedural style

mysqli_get_connection_stats ( mysqli $link ) : array

Returns statistics about the client connection. Available only with mysqlnd.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns an array with connection stats if success, FALSE otherwise.

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


Returns a string representing the type of connection used

  • « mysqli::get_connection_stats
  • mysqli::$protocol_version »
  • PHP Manual
  • mysqli
  • Returns a string representing the type of connection used

mysqli::$host_info

mysqli_get_host_info

(PHP 5, PHP 7)

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 $link ) : string

Returns a string describing the connection represented by the link parameter (including the server host name).

Parameters

link

Procedural style only: A link identifier 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 = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print host information */
printf("Host info: %s\n", $mysqli->host_info);

/* 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();
}

/* print host information */
printf("Host info: %s\n", mysqli_get_host_info($link));

/* close connection */
mysqli_close($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


Returns the version of the MySQL protocol used

  • « mysqli::$host_info
  • mysqli::$server_info »
  • PHP Manual
  • mysqli
  • Returns the version of the MySQL protocol used

mysqli::$protocol_version

mysqli_get_proto_info

(PHP 5, PHP 7)

mysqli::$protocol_version -- mysqli_get_proto_info — Returns the version of the MySQL protocol used

Description

Object oriented style

string $mysqli->protocol_version;

Procedural style

mysqli_get_proto_info ( mysqli $link ) : int

Returns an integer representing the MySQL protocol version used by the connection represented by the link parameter.

Parameters

link

Procedural style only: A link identifier 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 = new mysqli("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print protocol version */
printf("Protocol version: %d\n", $mysqli->protocol_version);

/* close connection */
$mysqli->close();
?>

Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print protocol version */
printf("Protocol version: %d\n", mysqli_get_proto_info($link));

/* close connection */
mysqli_close($link);
?>

The above examples will output:

Protocol version: 10

See Also

  • mysqli_get_host_info() - Returns a string representing the type of connection used


Returns the version of the MySQL server

  • « mysqli::$protocol_version
  • mysqli::$server_version »
  • PHP Manual
  • mysqli
  • Returns the version of the MySQL server

mysqli::$server_info

mysqli::get_server_info

mysqli_get_server_info

(PHP 5, PHP 7)

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;
mysqli_stmt::get_server_info ( void ) : string

Procedural style

mysqli_get_server_info ( mysqli $link ) : string

Returns a string representing the version of the MySQL server that the MySQLi extension is connected to.

Parameters

link

Procedural style only: A link identifier 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 = new mysqli("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print server version */
printf("Server version: %s\n", $mysqli->server_info);

/* close connection */
$mysqli->close();
?>

Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print server version */
printf("Server version: %s\n", mysqli_get_server_info($link));

/* close connection */
mysqli_close($link);
?>

The above examples will output:

Server version: 4.1.2-alpha-debug

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


Returns the version of the MySQL server as an integer

  • « mysqli::$server_info
  • mysqli::get_warnings »
  • PHP Manual
  • mysqli
  • Returns the version of the MySQL server as an integer

mysqli::$server_version

mysqli_get_server_version

(PHP 5, PHP 7)

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 $link ) : int

The mysqli_get_server_version() function returns the version of the server connected to (represented by the link parameter) as an integer.

Parameters

link

Procedural style only: A link identifier 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 = new mysqli("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print server version */
printf("Server version: %d\n", $mysqli->server_version);

/* close connection */
$mysqli->close();
?>

Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* print server version */
printf("Server version: %d\n", mysqli_get_server_version($link));

/* close connection */
mysqli_close($link);
?>

The above examples will output:

Server version: 40102

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


Get result of SHOW WARNINGS

  • « mysqli::$server_version
  • mysqli::$info »
  • PHP Manual
  • mysqli
  • Get result of SHOW WARNINGS

mysqli::get_warnings

mysqli_get_warnings

(PHP 5 >= 5.1.0, PHP 7)

mysqli::get_warnings -- mysqli_get_warnings — Get result of SHOW WARNINGS

Description

Object oriented style

mysqli::get_warnings ( void ) : mysqli_warning

Procedural style

mysqli_get_warnings ( mysqli $link ) : mysqli_warning
Warning

This function is currently not documented; only its argument list is available.


Retrieves information about the most recently executed query

  • « mysqli::get_warnings
  • mysqli::init »
  • PHP Manual
  • mysqli
  • Retrieves information about the most recently executed query

mysqli::$info

mysqli_info

(PHP 5, PHP 7)

mysqli::$info -- mysqli_info — Retrieves information about the most recently executed query

Description

Object oriented style

string $mysqli->info;

Procedural style

mysqli_info ( mysqli $link ) : 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

link

Procedural style only: A link identifier 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 = 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 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);

/* 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();
}

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

/* close connection */
mysqli_close($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 from the last query for the given link
  • mysqli_num_rows() - Gets the number of rows in a result


Initializes MySQLi and returns a resource for use with mysqli_real_connect()

  • « mysqli::$info
  • mysqli::$insert_id »
  • PHP Manual
  • mysqli
  • Initializes MySQLi and returns a resource for use with mysqli_real_connect()

mysqli::init

mysqli_init

(PHP 5, PHP 7)

mysqli::init -- mysqli_init — Initializes MySQLi and returns a resource for use with mysqli_real_connect()

Description

Object oriented style

mysqli::init ( void ) : mysqli

Procedural style

mysqli_init ( void ) : mysqli

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()) will fail until mysqli_real_connect() was called.

Return Values

Returns an object.

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 a mysql server
  • mysqli_connect() - Alias of mysqli::__construct


Returns the auto generated id used in the latest query

  • « mysqli::init
  • mysqli::kill »
  • PHP Manual
  • mysqli
  • Returns the auto generated id used in the latest query

mysqli::$insert_id

mysqli_insert_id

(PHP 5, PHP 7)

mysqli::$insert_id -- mysqli_insert_id — Returns the auto generated id used in the latest query

Description

Object oriented style

mixed $mysqli->insert_id;

Procedural style

mysqli_insert_id ( mysqli $link ) : mixed

The mysqli_insert_id() function returns the ID generated by a query (usually INSERT) on a table with a column having the AUTO_INCREMENT attribute. If no INSERT or UPDATE statements were sent via this connection, or if the modified table does not have a column with the AUTO_INCREMENT attribute, this function will return zero.

Note:

Performing an INSERT or UPDATE statement using the LAST_INSERT_ID() function will also modify the value returned by the mysqli_insert_id() function.

Parameters

link

Procedural style only: A link identifier 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.

Note:

If the number is greater than maximal int value, mysqli_insert_id() will return a string.

Examples

Example #1 $mysqli->insert_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();
}

$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");

/* 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();
}

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");

/* close connection */
mysqli_close($link);
?>

The above examples will output:

New Record has id 1.


Asks the server to kill a MySQL thread

  • « mysqli::$insert_id
  • mysqli::more_results »
  • PHP Manual
  • mysqli
  • Asks the server to kill a MySQL thread

mysqli::kill

mysqli_kill

(PHP 5, PHP 7)

mysqli::kill -- mysqli_kill — Asks the server to kill a MySQL thread

Description

Object oriented style

mysqli::kill ( int $processid ) : bool

Procedural style

mysqli_kill ( mysqli $link , int $processid ) : bool

This function is used to ask the server to kill a MySQL thread specified by the processid 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

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns TRUE on success or FALSE on failure.

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


Check if there are any more query results from a multi query

  • « mysqli::kill
  • mysqli::multi_query »
  • PHP Manual
  • mysqli
  • Check if there are any more query results from a multi query

mysqli::more_results

mysqli_more_results

(PHP 5, PHP 7)

mysqli::more_results -- mysqli_more_results — Check if there are any more query results from a multi query

Description

Object oriented style

mysqli::more_results ( void ) : bool

Procedural style

mysqli_more_results ( mysqli $link ) : bool

Indicates if one or more result sets are available from a previous call to mysqli_multi_query().

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns TRUE if one or more result sets are available from a previous call to mysqli_multi_query(), otherwise FALSE.

Examples

See mysqli_multi_query().

See Also

  • mysqli_multi_query() - Performs a query 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


Performs a query on the database

  • « mysqli::more_results
  • mysqli::next_result »
  • PHP Manual
  • mysqli
  • Performs a query on the database

mysqli::multi_query

mysqli_multi_query

(PHP 5, PHP 7)

mysqli::multi_query -- mysqli_multi_query — Performs a query on the database

Description

Object oriented style

mysqli::multi_query ( string $query ) : bool

Procedural style

mysqli_multi_query ( mysqli $link , string $query ) : bool

Executes one or multiple queries which are concatenated by a semicolon.

To retrieve the resultset from the first query you can use mysqli_use_result() or mysqli_store_result(). All subsequent query results can be processed using mysqli_more_results() and mysqli_next_result().

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

query

The query, as a string.

Data inside the query should be properly escaped.

Return Values

Returns FALSE if the first statement failed. To retrieve subsequent errors from other statements you have to call mysqli_next_result() first.

Examples

Example #1 mysqli::multi_query() 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->store_result()) {
            while ($row = $result->fetch_row()) {
                printf("%s\n", $row[0]);
            }
            $result->free();
        }
        /* 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_store_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 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


Prepare next result from multi_query

  • « mysqli::multi_query
  • mysqli::options »
  • PHP Manual
  • mysqli
  • Prepare next result from multi_query

mysqli::next_result

mysqli_next_result

(PHP 5, PHP 7)

mysqli::next_result -- mysqli_next_result — Prepare next result from multi_query

Description

Object oriented style

mysqli::next_result ( void ) : bool

Procedural style

mysqli_next_result ( mysqli $link ) : 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

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns TRUE on success or FALSE on failure.

Examples

See mysqli_multi_query().

See Also

  • mysqli_multi_query() - Performs a query 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


Set options

  • « mysqli::next_result
  • mysqli::ping »
  • PHP Manual
  • mysqli
  • Set options

mysqli::options

mysqli_options

(PHP 5, PHP 7)

mysqli::options -- mysqli_options — Set options

Description

Object oriented style

mysqli::options ( int $option , mixed $value ) : bool

Procedural style

mysqli_options ( mysqli $link , int $option , mixed $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

link

Procedural style only: A link identifier 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 (supported on Windows with TCP/IP since PHP 5.3.1)
MYSQLI_OPT_LOCAL_INFILE | enable/disable use of LOAD LOCAL INFILE
MYSQLI_INIT_COMMAND | command to execute after when connecting to MySQL server
MYSQLI_READ_DEFAULT_FILE | Read options from named option file instead of my.cnf
MYSQLI_READ_DEFAULT_GROUP | Read options from the named group from my.cnf or the file specified with MYSQL_READ_DEFAULT_FILE.
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. Only valid for mysqlnd.
MYSQLI_OPT_SSL_VERIFY_SERVER_CERT

value

The value for the option.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.5.0 | The MYSQLI_SERVER_PUBLIC_KEY and MYSQLI_SERVER_PUBLIC_KEY options were added.
5.3.0 | The MYSQLI_OPT_INT_AND_FLOAT_NATIVE, MYSQLI_OPT_NET_CMD_BUFFER_SIZE, MYSQLI_OPT_NET_READ_BUFFER_SIZE, and MYSQLI_OPT_SSL_VERIFY_SERVER_CERT options were added.

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 a resource for use with mysqli_real_connect()
  • mysqli_real_connect() - Opens a connection to a mysql server


Pings a server connection, or tries to reconnect if the connection has gone down

  • « mysqli::options
  • mysqli::poll »
  • PHP Manual
  • mysqli
  • Pings a server connection, or tries to reconnect if the connection has gone down

mysqli::ping

mysqli_ping

(PHP 5, PHP 7)

mysqli::ping -- mysqli_ping — Pings a server connection, or tries to reconnect if the connection has gone down

Description

Object oriented style

mysqli::ping ( void ) : bool

Procedural style

mysqli_ping ( mysqli $link ) : 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

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns TRUE on success or FALSE on failure.

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!


Poll connections

  • « mysqli::ping
  • mysqli::prepare »
  • PHP Manual
  • mysqli
  • Poll connections

mysqli::poll

mysqli_poll

(PHP 5 >= 5.3.0, PHP 7)

mysqli::poll -- mysqli_poll — Poll connections

Description

Object oriented style

public static mysqli::poll ( array &$read , array &$error , array &$reject , int $sec [, int $usec = 0 ] ) : int

Procedural style

mysqli_poll ( array &$read , array &$error , array &$reject , int $sec [, int $usec = 0 ] ) : int

Poll connections. Available only with mysqlnd. The method can be used as static.

Parameters

read

List of connections to check for outstanding results that can be read.

error

List of connections on which an error occured, 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.

sec

Maximum number of seconds to wait, must be non-negative.

usec

Maximum number of microseconds to wait, must be non-negative.

Return Values

Returns number of ready connections upon success, FALSE otherwise.

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


Prepare an SQL statement for execution

  • « mysqli::poll
  • mysqli::query »
  • PHP Manual
  • mysqli
  • Prepare an SQL statement for execution

mysqli::prepare

mysqli_prepare

(PHP 5, PHP 7)

mysqli::prepare -- mysqli_prepare — Prepare an SQL statement for execution

Description

Object oriented style

mysqli::prepare ( string $query ) : mysqli_stmt

Procedural style

mysqli_prepare ( mysqli $link , string $query ) : mysqli_stmt

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 parameter markers must be bound to application variables using mysqli_stmt_bind_param() and/or mysqli_stmt_bind_result() before executing the statement or fetching rows.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

query

The query, as a string.

Note:

You should not add a terminating semicolon or \g to the statement.

This parameter can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions.

Note:

The markers are legal only in certain places in SQL statements. For example, they are allowed 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 allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement, or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. It's not allowed to compare marker with NULL by ? IS NULL too. In general, parameters are legal only in Data Manipulation Language (DML) statements, and not in Data Definition Language (DDL) statements.

Return Values

mysqli_prepare() returns a statement object or FALSE if an error occurred.

Examples

Example #1 mysqli::prepare() 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();
}

$city = "Amersfoort";

/* create a prepared statement */
if ($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);

    /* close statement */
    $stmt->close();
}

/* 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();
}

$city = "Amersfoort";

/* create a prepared statement */
if ($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);

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

The above examples will output:

Amersfoort is in district Utrecht

See Also

  • mysqli_stmt_execute() - Executes a prepared Query
  • 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_close() - Closes a prepared statement


Performs a query on the database

  • « mysqli::prepare
  • mysqli::real_connect »
  • PHP Manual
  • mysqli
  • Performs a query on the database

mysqli::query

mysqli_query

(PHP 5, PHP 7)

mysqli::query -- mysqli_query — Performs a query on the database

Description

Object oriented style

mysqli::query ( string $query [, int $resultmode = MYSQLI_STORE_RESULT ] ) : mixed

Procedural style

mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] ) : mixed

Performs a query against the database.

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 you pass a statement 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

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

query

The query string.

Data inside the query should be properly escaped.

resultmode

Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used.

If you use MYSQLI_USE_RESULT all subsequent calls will return error Commands out of sync unless you call mysqli_free_result()

With MYSQLI_ASYNC (available with mysqlnd), it is possible to perform query asynchronously. mysqli_poll() is then used to get results from such queries.

Return Values

Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.

Changelog

Version | Description
5.3.0 | Added the ability of async queries.

Examples

Example #1 mysqli::query() 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();
}

/* Create table doesn't return a resultset */
if ($mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
    printf("Table myCity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT Name FROM City LIMIT 10")) {
    printf("Select returned %d rows.\n", $result->num_rows);

    /* free result set */
    $result->close();
}

/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = $mysqli->query("SELECT * FROM City", MYSQLI_USE_RESULT)) {

    /* Note, that we can't execute any functions which interact with the
       server until result set was closed. All calls will return an
       'out of sync' error */
    if (!$mysqli->query("SET @a:='this will not work'")) {
        printf("Error: %s\n", $mysqli->error);
    }
    $result->close();
}

$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();
}

/* Create table doesn't return a resultset */
if (mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
    printf("Table myCity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = mysqli_query($link, "SELECT Name FROM City LIMIT 10")) {
    printf("Select returned %d rows.\n", mysqli_num_rows($result));

    /* free result set */
    mysqli_free_result($result);
}

/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = mysqli_query($link, "SELECT * FROM City", MYSQLI_USE_RESULT)) {

    /* Note, that we can't execute any functions which interact with the
       server until result set was closed. All calls will return an
       'out of sync' error */
    if (!mysqli_query($link, "SET @a:='this will not work'")) {
        printf("Error: %s\n", mysqli_error($link));
    }
    mysqli_free_result($result);
}

mysqli_close($link);
?>

The above examples will output:

Table myCity successfully created.
Select returned 10 rows.
Error: Commands out of sync;  You can't run this command now

See Also

  • mysqli_real_query() - Execute an SQL query
  • mysqli_multi_query() - Performs a query on the database
  • mysqli_free_result() - Frees the memory associated with a result


Opens a connection to a mysql server

  • « mysqli::query
  • mysqli::real_escape_string »
  • PHP Manual
  • mysqli
  • Opens a connection to a mysql server

mysqli::real_connect

mysqli_real_connect

(PHP 5, PHP 7)

mysqli::real_connect -- mysqli_real_connect — Opens a connection to a mysql server

Description

Object oriented style

mysqli::real_connect ([ string $host [, string $username [, string $passwd [, string $dbname [, int $port [, string $socket [, int $flags ]]]]]]] ) : bool

Procedural style

mysqli_real_connect ( mysqli $link [, string $host [, string $username [, string $passwd [, string $dbname [, int $port [, string $socket [, int $flags ]]]]]]] ) : bool

Establish a connection to a MySQL database engine.

This function differs from mysqli_connect():

  • mysqli_real_connect() needs a valid object which has to be created by function mysqli_init().

  • With the mysqli_options() function you can set various options for connection.

  • There is a flags parameter.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

host

Can be either a host name or an IP address. Passing the NULL value or the string "localhost" to this parameter, the local host is assumed. When possible, pipes will be used instead of the TCP/IP protocol.

username

The MySQL user name.

passwd

If provided or NULL, the MySQL server will attempt to authenticate the user against those user records which have no password only. This allows one username to be used with different permissions (depending on if a password as provided or not).

dbname

If provided will specify the default database to be used when performing queries.

port

Specifies the port number to attempt to connect to the MySQL server.

socket

Specifies the socket or named pipe that should be used.

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

Changelog

Version | Description
5.6.16 | Added the MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT flag for MySQL Native Driver

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mysqli::real_connect() example

Object oriented style

<?php

$mysqli = mysqli_init();
if (!$mysqli) {
    die('mysqli_init failed');
}

if (!$mysqli->options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
    die('Setting MYSQLI_INIT_COMMAND failed');
}

if (!$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
    die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}

if (!$mysqli->real_connect('localhost', 'my_user', 'my_password', 'my_db')) {
    die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
}

echo 'Success... ' . $mysqli->host_info . "\n";

$mysqli->close();
?>

Object oriented style when extending mysqli class

<?php

class foo_mysqli extends mysqli {
    public function __construct($host, $user, $pass, $db) {
        parent::init();

        if (!parent::options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
            die('Setting MYSQLI_INIT_COMMAND failed');
        }

        if (!parent::options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
            die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
        }

        if (!parent::real_connect($host, $user, $pass, $db)) {
            die('Connect Error (' . mysqli_connect_errno() . ') '
                    . mysqli_connect_error());
        }
    }
}

$db = new foo_mysqli('localhost', 'my_user', 'my_password', 'my_db');

echo 'Success... ' . $db->host_info . "\n";

$db->close();
?>

Procedural style

<?php

$link = mysqli_init();
if (!$link) {
    die('mysqli_init failed');
}

if (!mysqli_options($link, MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
    die('Setting MYSQLI_INIT_COMMAND failed');
}

if (!mysqli_options($link, MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
    die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}

if (!mysqli_real_connect($link, 'localhost', 'my_user', 'my_password', 'my_db')) {
    die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
}

echo 'Success... ' . mysqli_get_host_info($link) . "\n";

mysqli_close($link);
?>

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 a resource 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


Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

  • « mysqli::real_connect
  • mysqli::real_query »
  • PHP Manual
  • mysqli
  • Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

mysqli::real_escape_string

mysqli::escape_string

mysqli_real_escape_string

(PHP 5, PHP 7)

mysqli::real_escape_string -- mysqli::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

mysqli::escape_string ( string $escapestr ) : string
mysqli::real_escape_string ( string $escapestr ) : string

Procedural style

mysqli_real_escape_string ( mysqli $link , string $escapestr ) : 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 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

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

escapestr

The string to be escaped.

Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and Control-Z.

Return Values

Returns an escaped string.

Errors/Exceptions

Executing this function without a valid MySQLi connection passed in will return NULL and emit E_WARNING level errors.

Examples

Example #1 mysqli::real_escape_string() 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();
}

$mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City");

$city = "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!$mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) {
    printf("Error: %s\n", $mysqli->sqlstate);
}

$city = $mysqli->real_escape_string($city);

/* this query with escaped $city will work */
if ($mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) {
    printf("%d Row inserted.\n", $mysqli->affected_rows);
}

$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();
}

mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City");

$city = "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
    printf("Error: %s\n", mysqli_sqlstate($link));
}

$city = mysqli_real_escape_string($link, $city);

/* this query with escaped $city will work */
if (mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
    printf("%d Row inserted.\n", mysqli_affected_rows($link));
}

mysqli_close($link);
?>

The above examples will output:

Error: 42000
1 Row inserted.

Notes

Note:

For those accustomed to using mysql_real_escape_string(),
note that the arguments of mysqli_real_escape_string()
differ from what mysql_real_escape_string() expects.
The link identifier comes first in
mysqli_real_escape_string(), whereas the string to be escaped
comes first in mysql_real_escape_string().

See Also

  • mysqli_set_charset() - Sets the default client character set
  • mysqli_character_set_name() - Returns the default character set for the database connection


Execute an SQL query

  • « mysqli::real_escape_string
  • mysqli::reap_async_query »
  • PHP Manual
  • mysqli
  • Execute an SQL query

mysqli::real_query

mysqli_real_query

(PHP 5, PHP 7)

mysqli::real_query -- mysqli_real_query — Execute an SQL query

Description

Object oriented style

mysqli::real_query ( string $query ) : bool

Procedural style

mysqli_real_query ( mysqli $link , 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.

In order to determine if a given query should return a result set or not, see mysqli_field_count().

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

query

The query, as a string.

Data inside the query should be properly escaped.

Return Values

Returns TRUE on success or FALSE on failure.

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


Get result from async query

  • « mysqli::real_query
  • mysqli::refresh »
  • PHP Manual
  • mysqli
  • Get result from async query

mysqli::reap_async_query

mysqli_reap_async_query

(PHP 5 >= 5.3.0, PHP 7)

mysqli::reap_async_query -- mysqli_reap_async_query — Get result from async query

Description

Object oriented style

public mysqli::reap_async_query ( void ) : mysqli_result

Procedural style

mysqli_reap_async_query ( mysqli $link ) : mysqli_result

Get result from async query. Available only with mysqlnd.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns mysqli_result in success, FALSE otherwise.

See Also

  • mysqli_poll() - Poll connections


Refreshes

  • « mysqli::reap_async_query
  • mysqli::release_savepoint »
  • PHP Manual
  • mysqli
  • Refreshes

mysqli::refresh

mysqli_refresh

(PHP 5 >= 5.3.0, PHP 7)

mysqli::refresh -- mysqli_refresh — Refreshes

Description

Object oriented style

public mysqli::refresh ( int $options ) : bool

Procedural style

mysqli_refresh ( resource $link , int $options ) : bool

Flushes tables or caches, or resets the replication server information.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

options

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

See Also

  • mysqli_poll() - Poll connections


Removes the named savepoint from the set of savepoints of the current transaction

  • « mysqli::refresh
  • mysqli::rollback »
  • PHP Manual
  • mysqli
  • Removes the named savepoint from the set of savepoints of the current transaction

mysqli::release_savepoint

mysqli_release_savepoint

(PHP 5 >= 5.5.0, PHP 7)

mysqli::release_savepoint -- mysqli_release_savepoint — Removes the named savepoint from the set of savepoints of the current transaction

Description

Object oriented style (method):

public mysqli::release_savepoint ( string $name ) : bool

Procedural style:

mysqli_release_savepoint ( mysqli $link , string $name ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

name

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • mysqli_rollback() - Rolls back current transaction


Rolls back current transaction

  • « mysqli::release_savepoint
  • mysqli::rpl_query_type »
  • PHP Manual
  • mysqli
  • Rolls back current transaction

mysqli::rollback

mysqli_rollback

(PHP 5, PHP 7)

mysqli::rollback -- mysqli_rollback — Rolls back current transaction

Description

Object oriented style

mysqli::rollback ([ int $flags = 0 [, string $name ]] ) : bool

Procedural style

mysqli_rollback ( mysqli $link [, int $flags = 0 [, string $name ]] ) : bool

Rollbacks the current transaction for the database.

Parameters

link

Procedural style only: A link identifier 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.

Changelog

Version | Description
5.5.0 | Added flags and name parameters.

Examples

Example #1 mysqli::rollback() 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();
}

/* disable autocommit */
$mysqli->autocommit(FALSE);

$mysqli->query("CREATE TABLE myCity LIKE City");
$mysqli->query("ALTER TABLE myCity Type=InnoDB");
$mysqli->query("INSERT INTO myCity SELECT * FROM City LIMIT 50");

/* commit insert */
$mysqli->commit();

/* delete all rows */
$mysqli->query("DELETE FROM myCity");

if ($result = $mysqli->query("SELECT COUNT(*) FROM myCity")) {
    $row = $result->fetch_row();
    printf("%d rows in table myCity.\n", $row[0]);
    /* Free result */
    $result->close();
}

/* Rollback */
$mysqli->rollback();

if ($result = $mysqli->query("SELECT COUNT(*) FROM myCity")) {
    $row = $result->fetch_row();
    printf("%d rows in table myCity (after rollback).\n", $row[0]);
    /* Free result */
    $result->close();
}

/* Drop table myCity */
$mysqli->query("DROP TABLE myCity");

$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();
}

/* disable autocommit */
mysqli_autocommit($link, FALSE);

mysqli_query($link, "CREATE TABLE myCity LIKE City");
mysqli_query($link, "ALTER TABLE myCity Type=InnoDB");
mysqli_query($link, "INSERT INTO myCity SELECT * FROM City LIMIT 50");

/* commit insert */
mysqli_commit($link);

/* delete all rows */
mysqli_query($link, "DELETE FROM myCity");

if ($result = mysqli_query($link, "SELECT COUNT(*) FROM myCity")) {
    $row = mysqli_fetch_row($result);
    printf("%d rows in table myCity.\n", $row[0]);
    /* Free result */
    mysqli_free_result($result);
}

/* Rollback */
mysqli_rollback($link);

if ($result = mysqli_query($link, "SELECT COUNT(*) FROM myCity")) {
    $row = mysqli_fetch_row($result);
    printf("%d rows in table myCity (after rollback).\n", $row[0]);
    /* Free result */
    mysqli_free_result($result);
}

/* Drop table myCity */
mysqli_query($link, "DROP TABLE myCity");

mysqli_close($link);
?>

The above examples will output:

0 rows in table myCity.
50 rows in table myCity (after rollback).

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


Returns RPL query type

  • « mysqli::rollback
  • mysqli::savepoint »
  • PHP Manual
  • mysqli
  • Returns RPL query type

mysqli::rpl_query_type

mysqli_rpl_query_type

(PHP 5, PHP 7)

mysqli::rpl_query_type -- mysqli_rpl_query_type — Returns RPL query type

Description

Object oriented style

mysqli::rpl_query_type ( string $query ) : int

Procedural style

mysqli_rpl_query_type ( mysqli $link , string $query ) : int

Returns MYSQLI_RPL_MASTER, MYSQLI_RPL_SLAVE or MYSQLI_RPL_ADMIN depending on a query type. INSERT, UPDATE and similar are master queries, SELECT is slave, and FLUSH, REPAIR and similar are admin.

Warning

This function is currently not documented; only its argument list is available.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.3.0.


Set a named transaction savepoint

  • « mysqli::rpl_query_type
  • mysqli::select_db »
  • PHP Manual
  • mysqli
  • Set a named transaction savepoint

mysqli::savepoint

mysqli_savepoint

(PHP 5 >= 5.5.0, PHP 7)

mysqli::savepoint -- mysqli_savepoint — Set a named transaction savepoint

Description

Object oriented style (method):

public mysqli::savepoint ( string $name ) : bool

Procedural style:

mysqli_savepoint ( mysqli $link , string $name ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

name

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • mysqli_commit() - Commits the current transaction


Selects the default database for database queries

  • « mysqli::savepoint
  • mysqli::send_query »
  • PHP Manual
  • mysqli
  • Selects the default database for database queries

mysqli::select_db

mysqli_select_db

(PHP 5, PHP 7)

mysqli::select_db -- mysqli_select_db — Selects the default database for database queries

Description

Object oriented style

mysqli::select_db ( string $dbname ) : bool

Procedural style

mysqli_select_db ( mysqli $link , string $dbname ) : 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

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

dbname

The database name.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mysqli::select_db() example

Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
    $row = $result->fetch_row();
    printf("Default database is %s.\n", $row[0]);
    $result->close();
}

/* change db to world db */
$mysqli->select_db("world");

/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
    $row = $result->fetch_row();
    printf("Default database is %s.\n", $row[0]);
    $result->close();
}

$mysqli->close();
?>

Procedural style

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* return name of current default database */
if ($result = mysqli_query($link, "SELECT DATABASE()")) {
    $row = mysqli_fetch_row($result);
    printf("Default database is %s.\n", $row[0]);
    mysqli_free_result($result);
}

/* change db to world db */
mysqli_select_db($link, "world");

/* return name of current default database */
if ($result = mysqli_query($link, "SELECT DATABASE()")) {
    $row = mysqli_fetch_row($result);
    printf("Default database is %s.\n", $row[0]);
    mysqli_free_result($result);
}

mysqli_close($link);
?>

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 a mysql server


Send the query and return

  • « mysqli::select_db
  • mysqli::set_charset »
  • PHP Manual
  • mysqli
  • Send the query and return

mysqli::send_query

mysqli_send_query

(PHP 5, PHP 7)

mysqli::send_query -- mysqli_send_query — Send the query and return

Description

Object oriented style

mysqli::send_query ( string $query ) : bool

Procedural style

mysqli_send_query ( mysqli $link , string $query ) : bool
Warning

This function is currently not documented; only its argument list is available.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.3.0.


Sets the default client character set

  • « mysqli::send_query
  • mysqli::set_local_infile_default »
  • PHP Manual
  • mysqli
  • Sets the default client character set

mysqli::set_charset

mysqli_set_charset

(PHP 5 >= 5.0.5, PHP 7)

mysqli::set_charset -- mysqli_set_charset — Sets the default client character set

Description

Object oriented style

mysqli::set_charset ( string $charset ) : bool

Procedural style

mysqli_set_charset ( mysqli $link , string $charset ) : bool

Sets the default character set to be used when sending data from and to the database server.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

charset

The charset to be set as default.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note:

To use this function on a Windows platform you need MySQL client library version 4.1.11 or above (for MySQL 5.0 you need 5.0.6 or above).

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.

Examples

Example #1 mysqli::set_charset() example

Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

printf("Initial character set: %s\n", $mysqli->character_set_name());

/* change character set to utf8 */
if (!$mysqli->set_charset("utf8")) {
    printf("Error loading character set utf8: %s\n", $mysqli->error);
    exit();
} else {
    printf("Current character set: %s\n", $mysqli->character_set_name());
}

$mysqli->close();
?>

Procedural style

<?php
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'test');

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

printf("Initial character set: %s\n", mysqli_character_set_name($link));

/* change character set to utf8 */
if (!mysqli_set_charset($link, "utf8")) {
    printf("Error loading character set utf8: %s\n", mysqli_error($link));
    exit();
} else {
    printf("Current character set: %s\n", mysqli_character_set_name($link));
}

mysqli_close($link);
?>

The above examples will output something similar to:

Initial character set: latin1
Current character set: utf8

See Also

  • mysqli_character_set_name() - Returns the default character set for 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


Unsets user defined handler for load local infile command

  • « mysqli::set_charset
  • mysqli::set_local_infile_handler »
  • PHP Manual
  • mysqli
  • Unsets user defined handler for load local infile command

mysqli::set_local_infile_default

mysqli_set_local_infile_default

(PHP 5, PHP 7)

mysqli::set_local_infile_default -- mysqli_set_local_infile_default — Unsets user defined handler for load local infile command

Description

mysqli_set_local_infile_default ( mysqli $link ) : void

Deactivates a LOAD DATA INFILE LOCAL handler previously set with mysqli_set_local_infile_handler().

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

No value is returned.

Examples

See mysqli_set_local_infile_handler() examples

See Also

  • mysqli_set_local_infile_handler() - Set callback function for LOAD DATA LOCAL INFILE command


Set callback function for LOAD DATA LOCAL INFILE command

  • « mysqli::set_local_infile_default
  • mysqli::$sqlstate »
  • PHP Manual
  • mysqli
  • Set callback function for LOAD DATA LOCAL INFILE command

mysqli::set_local_infile_handler

mysqli_set_local_infile_handler

(PHP 5, PHP 7)

mysqli::set_local_infile_handler -- mysqli_set_local_infile_handler — Set callback function for LOAD DATA LOCAL INFILE command

Description

Object oriented style

mysqli::set_local_infile_handler ( mysqli $link , callable $read_func ) : bool

Procedural style

mysqli_set_local_infile_handler ( mysqli $link , callable $read_func ) : bool

Set callback function for LOAD DATA LOCAL INFILE command

The callbacks task is to read input from the file specified in the LOAD DATA LOCAL INFILE and to reformat it into the format understood by LOAD DATA INFILE.

The returned data needs to match the format specified in the LOAD DATA

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

read_func

A callback function or object method taking the following parameters:

stream

A PHP stream associated with the SQL commands INFILE

&buffer

A string buffer to store the rewritten input into

buflen

The maximum number of characters to be stored in the buffer

&errormsg

If an error occurs you can store an error message in here

The callback function should return the number of characters stored in the buffer or a negative value if an error occurred.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mysqli::set_local_infile_handler() example

Object oriented style

<?php
  $db = mysqli_init();
  $db->real_connect("localhost","root","","test");

  function callme($stream, &$buffer, $buflen, &$errmsg)
  {
    $buffer = fgets($stream);

    echo $buffer;

    // convert to upper case and replace "," delimiter with [TAB]
    $buffer = strtoupper(str_replace(",", "\t", $buffer));

    return strlen($buffer);
  }

  echo "Input:\n";

  $db->set_local_infile_handler("callme");
  $db->query("LOAD DATA LOCAL INFILE 'input.txt' INTO TABLE t1");
  $db->set_local_infile_default();

  $res = $db->query("SELECT * FROM t1");

  echo "\nResult:\n";
  while ($row = $res->fetch_assoc()) {
    echo join(",", $row)."\n";
  }
?>

Procedural style

<?php
  $db = mysqli_init();
  mysqli_real_connect($db, "localhost","root","","test");

  function callme($stream, &$buffer, $buflen, &$errmsg)
  {
    $buffer = fgets($stream);

    echo $buffer;

    // convert to upper case and replace "," delimiter with [TAB]
    $buffer = strtoupper(str_replace(",", "\t", $buffer));

    return strlen($buffer);
  }

  echo "Input:\n";

  mysqli_set_local_infile_handler($db, "callme");
  mysqli_query($db, "LOAD DATA LOCAL INFILE 'input.txt' INTO TABLE t1");
  mysqli_set_local_infile_default($db);

  $res = mysqli_query($db, "SELECT * FROM t1");

  echo "\nResult:\n";
  while ($row = mysqli_fetch_assoc($res)) {
    echo join(",", $row)."\n";
  }
?>

The above examples will output:

Input:
23,foo
42,bar

Output:
23,FOO
42,BAR

See Also

  • mysqli_set_local_infile_default() - Unsets user defined handler for load local infile command


Returns the SQLSTATE error from previous MySQL operation

  • « mysqli::set_local_infile_handler
  • mysqli::ssl_set »
  • PHP Manual
  • mysqli
  • Returns the SQLSTATE error from previous MySQL operation

mysqli::$sqlstate

mysqli_sqlstate

(PHP 5, PHP 7)

mysqli::$sqlstate -- mysqli_sqlstate — Returns the SQLSTATE error from previous MySQL operation

Description

Object oriented style

string $mysqli->sqlstate;

Procedural style

mysqli_sqlstate ( mysqli $link ) : 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

link

Procedural style only: A link identifier 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 = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Table City already exists, so we should get an error */
if (!$mysqli->query("CREATE TABLE City (ID INT, Name VARCHAR(30))")) {
    printf("Error - SQLSTATE %s.\n", $mysqli->sqlstate);
}

$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();
}

/* Table City already exists, so we should get an error */
if (!mysqli_query($link, "CREATE TABLE City (ID INT, Name VARCHAR(30))")) {
    printf("Error - SQLSTATE %s.\n", mysqli_sqlstate($link));
}

mysqli_close($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


Used for establishing secure connections using SSL

  • « mysqli::$sqlstate
  • mysqli::stat »
  • PHP Manual
  • mysqli
  • Used for establishing secure connections using SSL

mysqli::ssl_set

mysqli_ssl_set

(PHP 5, PHP 7)

mysqli::ssl_set -- mysqli_ssl_set — Used for establishing secure connections using SSL

Description

Object oriented style

mysqli::ssl_set ( string $key , string $cert , string $ca , string $capath , string $cipher ) : bool

Procedural style

mysqli_ssl_set ( mysqli $link , string $key , string $cert , string $ca , string $capath , string $cipher ) : bool

Used for establishing secure connections using SSL. It must be called before mysqli_real_connect(). This function does nothing unless OpenSSL support is enabled.

Note that MySQL Native Driver does not support SSL before PHP 5.3.3, so calling this function when using MySQL Native Driver will result in an error. MySQL Native Driver is enabled by default on Microsoft Windows from PHP version 5.3 onwards.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

key

The path name to the key file.

cert

The path name to the certificate file.

ca

The path name to the certificate authority file.

capath

The pathname to a directory that contains trusted SSL CA certificates in PEM format.

cipher

A list of allowable ciphers to use for SSL encryption.

Return Values

This function always returns TRUE value. 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 a mysql server


Gets the current system status

  • « mysqli::ssl_set
  • mysqli::stmt_init »
  • PHP Manual
  • mysqli
  • Gets the current system status

mysqli::stat

mysqli_stat

(PHP 5, PHP 7)

mysqli::stat -- mysqli_stat — Gets the current system status

Description

Object oriented style

mysqli::stat ( void ) : string

Procedural style

mysqli_stat ( mysqli $link ) : string

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

link

Procedural style only: A link identifier 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 = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

printf ("System status: %s\n", $mysqli->stat());

$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();
}

printf("System status: %s\n", mysqli_stat($link));

mysqli_close($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


Initializes a statement and returns an object for use with mysqli_stmt_prepare

  • « mysqli::stat
  • mysqli::store_result »
  • PHP Manual
  • mysqli
  • Initializes a statement and returns an object for use with mysqli_stmt_prepare

mysqli::stmt_init

mysqli_stmt_init

(PHP 5, PHP 7)

mysqli::stmt_init -- mysqli_stmt_init — Initializes a statement and returns an object for use with mysqli_stmt_prepare

Description

Object oriented style

mysqli::stmt_init ( void ) : mysqli_stmt

Procedural style

mysqli_stmt_init ( mysqli $link ) : mysqli_stmt

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

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

Return Values

Returns an object.

See Also

  • mysqli_stmt_prepare() - Prepare an SQL statement for execution


Transfers a result set from the last query

  • « mysqli::stmt_init
  • mysqli::$thread_id »
  • PHP Manual
  • mysqli
  • Transfers a result set from the last query

mysqli::store_result

mysqli_store_result

(PHP 5, PHP 7)

mysqli::store_result -- mysqli_store_result — Transfers a result set from the last query

Description

Object oriented style

mysqli::store_result ([ int $option ] ) : mysqli_result

Procedural style

mysqli_store_result ( mysqli $link [, int $option ] ) : mysqli_result

Transfers the result set from the last query on the database connection represented by the link parameter to be used with the mysqli_data_seek() function.

Parameters

link

Procedural style only: A link identifier 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_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, since PHP 5.6.0)

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.

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.

Examples

See mysqli_multi_query().

See Also

  • mysqli_real_query() - Execute an SQL query
  • mysqli_use_result() - Initiate a result set retrieval


Returns the thread ID for the current connection

  • « mysqli::store_result
  • mysqli::thread_safe »
  • PHP Manual
  • mysqli
  • Returns the thread ID for the current connection

mysqli::$thread_id

mysqli_thread_id

(PHP 5, PHP 7)

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 $link ) : 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 other. 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

link

Procedural style only: A link identifier 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


Returns whether thread safety is given or not

  • « mysqli::$thread_id
  • mysqli::use_result »
  • PHP Manual
  • mysqli
  • Returns whether thread safety is given or not

mysqli::thread_safe

mysqli_thread_safe

(PHP 5, PHP 7)

mysqli::thread_safe -- mysqli_thread_safe — Returns whether thread safety is given or not

Description

Procedural style

mysqli_thread_safe ( void ) : bool

Tells whether the client library is compiled as thread-safe.

Return Values

TRUE if the client library is thread-safe, otherwise FALSE.


Initiate a result set retrieval

  • « mysqli::thread_safe
  • mysqli::$warning_count »
  • PHP Manual
  • mysqli
  • Initiate a result set retrieval

mysqli::use_result

mysqli_use_result

(PHP 5, PHP 7)

mysqli::use_result -- mysqli_use_result — Initiate a result set retrieval

Description

Object oriented style

mysqli::use_result ( void ) : mysqli_result

Procedural style

mysqli_use_result ( mysqli $link ) : mysqli_result

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.

Return Values

Returns an unbuffered result object or FALSE if an error occurred.

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


Returns the number of warnings from the last query for the given link

  • « mysqli::use_result
  • mysqli_stmt »
  • PHP Manual
  • mysqli
  • Returns the number of warnings from the last query for the given link

mysqli::$warning_count

mysqli_warning_count

(PHP 5, PHP 7)

mysqli::$warning_count -- mysqli_warning_count — Returns the number of warnings from the last query for the given link

Description

Object oriented style

int $mysqli->warning_count;

Procedural style

mysqli_warning_count ( mysqli $link ) : int

Returns the number of warnings from the last query in the connection.

Note:

For retrieving warning messages you can use the SQL command SHOW WARNINGS [limit row_count].

Parameters

link

Procedural style only: A link identifier 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 = 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 myCity LIKE City");

/* a remarkable city in Wales */
$query = "INSERT INTO myCity (CountryCode, Name) VALUES('GBR',
        'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')";

$mysqli->query($query);

if ($mysqli->warning_count) {
    if ($result = $mysqli->query("SHOW WARNINGS")) {
        $row = $result->fetch_row();
        printf("%s (%d): %s\n", $row[0], $row[1], $row[2]);
        $result->close();
    }
}

/* 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();
}

mysqli_query($link, "CREATE TABLE myCity LIKE City");

/* a remarkable long city name in Wales */
$query = "INSERT INTO myCity (CountryCode, Name) VALUES('GBR',
        'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')";

mysqli_query($link, $query);

if (mysqli_warning_count($link)) {
    if ($result = mysqli_query($link, "SHOW WARNINGS")) {
        $row = mysqli_fetch_row($result);
        printf("%s (%d): %s\n", $row[0], $row[1], $row[2]);
        mysqli_free_result($result);
    }
}

/* close connection */
mysqli_close($link);
?>

The above examples will output:

Warning (1264): Data truncated for column 'Name' at row 1

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


The mysqli_stmt class

(PHP 5, PHP 7)

Introduction

Represents a prepared statement.

Class synopsis

mysqli_stmt {
/* Properties */
int $affected_rows;
int $errno;
array $error_list;
string $error;
int $field_count;
int $insert_id;
int $num_rows;
int $param_count;
string $sqlstate;
/* Methods */
__construct ( mysqli $link [, string $query ] )
attr_get ( int $attr ) : int
attr_set ( int $attr , int $mode ) : bool
bind_param ( string $types , mixed &$var1 [, mixed &$... ] ) : bool
bind_result ( mixed &$var1 [, mixed &$... ] ) : bool
close ( void ) : bool
data_seek ( int $offset ) : void
execute ( void ) : bool
fetch ( void ) : bool
free_result ( void ) : void
get_result ( void ) : mysqli_result
get_warnings ( void ) : object
num_rows ( void ) : int
prepare ( string $query ) : mixed
reset ( void ) : bool
result_metadata ( void ) : mysqli_result
send_long_data ( int $param_nr , string $data ) : bool
store_result ( void ) : bool
}

Table of Contents

  • mysqli_stmt::$affected_rows — Returns the total number of rows changed, deleted, or inserted by the last executed statement
  • 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 — Seeks to an arbitrary row in statement result set
  • mysqli_stmt::$errno — Returns the error code for the most recent statement call
  • mysqli_stmt::$error_list — Returns a list of errors from the last statement executed
  • mysqli_stmt::$error — Returns a string description for last statement error
  • mysqli_stmt::execute — Executes a prepared Query
  • mysqli_stmt::fetch — Fetch results from a prepared statement into the bound variables
  • mysqli_stmt::$field_count — Returns the number of field 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
  • 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 — Return the number of rows in statements result set
  • mysqli_stmt::$param_count — Returns the number of parameter for the given statement
  • mysqli_stmt::prepare — Prepare 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 — Transfers a result set from a prepared statement


Returns the total number of rows changed, deleted, or inserted by the last executed statement

  • « mysqli_stmt
  • mysqli_stmt::attr_get »
  • PHP Manual
  • mysqli_stmt
  • Returns the total number of rows changed, deleted, or inserted by the last executed statement

mysqli_stmt::$affected_rows

mysqli_stmt_affected_rows

(PHP 5, PHP 7)

mysqli_stmt::$affected_rows -- mysqli_stmt_affected_rows — Returns the total number of rows changed, deleted, or inserted by the last executed statement

Description

Object oriented style

int $mysqli_stmt->affected_rows;

Procedural style

mysqli_stmt_affected_rows ( mysqli_stmt $stmt ) : int

Returns the number of rows affected by INSERT, UPDATE, or DELETE query.

This function only works with queries which update a table. In order to get the number of rows from a SELECT query, use mysqli_stmt_num_rows() instead.

Parameters

stmt

Procedural style only: A statement identifier 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 where updated for an UPDATE/DELETE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query has returned an error. NULL indicates an invalid argument was supplied to the function.

Note:

If the number of affected rows is greater than maximal PHP int value, the number of affected rows will be returned as a string value.

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();
}

/* create temp table */
$mysqli->query("CREATE TEMPORARY TABLE myCountry LIKE Country");

$query = "INSERT INTO myCountry SELECT * FROM Country WHERE Code LIKE ?";

/* prepare statement */
if ($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);

    /* 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();
}

/* create temp table */
mysqli_query($link, "CREATE TEMPORARY TABLE myCountry LIKE Country");

$query = "INSERT INTO myCountry SELECT * FROM Country WHERE Code LIKE ?";

/* prepare statement */
if ($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));

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

The above examples will output:

rows inserted: 17

See Also

  • mysqli_stmt_num_rows() - Return the number of rows in statements result set
  • mysqli_prepare() - Prepare an SQL statement for execution


Used to get the current value of a statement attribute

  • « mysqli_stmt::$affected_rows
  • mysqli_stmt::attr_set »
  • PHP Manual
  • mysqli_stmt
  • Used to get the current value of a statement attribute

mysqli_stmt::attr_get

mysqli_stmt_attr_get

(PHP 5, PHP 7)

mysqli_stmt::attr_get -- mysqli_stmt_attr_get — Used to get the current value of a statement attribute

Description

Object oriented style

mysqli_stmt::attr_get ( int $attr ) : int

Procedural style

mysqli_stmt_attr_get ( mysqli_stmt $stmt , int $attr ) : int

Gets the current value of a statement attribute.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

attr

The attribute that you want to get.

Return Values

Returns FALSE if the attribute is not found, otherwise returns the value of the attribute.


Used to modify the behavior of a prepared statement

  • « mysqli_stmt::attr_get
  • mysqli_stmt::bind_param »
  • PHP Manual
  • mysqli_stmt
  • Used to modify the behavior of a prepared statement

mysqli_stmt::attr_set

mysqli_stmt_attr_set

(PHP 5, PHP 7)

mysqli_stmt::attr_set -- mysqli_stmt_attr_set — Used to modify the behavior of a prepared statement

Description

Object oriented style

mysqli_stmt::attr_set ( int $attr , int $mode ) : bool

Procedural style

mysqli_stmt_attr_set ( mysqli_stmt $stmt , int $attr , int $mode ) : bool

Used to modify the behavior of a prepared statement. This function may be called multiple times to set several attributes.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

attr

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. mode 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. mode can be in the range from 1 to the maximum value of unsigned long. The default is 1.

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.

mode

The value to assign to the attribute.

See Also

  • » Connector/MySQL mysql_stmt_attr_set()


Binds variables to a prepared statement as parameters

  • « mysqli_stmt::attr_set
  • mysqli_stmt::bind_result »
  • PHP Manual
  • mysqli_stmt
  • Binds variables to a prepared statement as parameters

mysqli_stmt::bind_param

mysqli_stmt_bind_param

(PHP 5, PHP 7)

mysqli_stmt::bind_param -- mysqli_stmt_bind_param — Binds variables to a prepared statement as parameters

Description

Object oriented style

mysqli_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$... ] ) : bool

Procedural style

mysqli_stmt_bind_param ( mysqli_stmt $stmt , string $types , mixed &$var1 [, mixed &$... ] ) : bool

Bind variables for the parameter markers in the SQL statement that was passed to mysqli_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

stmt

Procedural style only: A statement identifier 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 integer
d | corresponding variable has type double
s | corresponding variable has type string
b | corresponding variable is a blob and will be sent in packets

var1

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.

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();
}

$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);

$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;

/* execute prepared statement */
$stmt->execute();

printf("%d Row inserted.\n", $stmt->affected_rows);

/* close statement and connection */
$stmt->close();

/* Clean up table CountryLanguage */
$mysqli->query("DELETE FROM CountryLanguage WHERE Language='Bavarian'");
printf("%d Row deleted.\n", $mysqli->affected_rows);

/* close connection */
$mysqli->close();
?>

Example #2 Procedural style

<?php
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');

/* check connection */
if (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$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;

/* execute prepared statement */
mysqli_stmt_execute($stmt);

printf("%d Row inserted.\n", mysqli_stmt_affected_rows($stmt));

/* close statement and connection */
mysqli_stmt_close($stmt);

/* Clean up table CountryLanguage */
mysqli_query($link, "DELETE FROM CountryLanguage WHERE Language='Bavarian'");
printf("%d Row deleted.\n", mysqli_affected_rows($link));

/* close connection */
mysqli_close($link);
?>

The above examples will output:

1 Row inserted.
1 Row deleted.

See Also

  • mysqli_stmt_bind_result() - Binds variables to a prepared statement for result storage
  • mysqli_stmt_execute() - Executes a prepared Query
  • mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • mysqli_prepare() - Prepare 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


Binds variables to a prepared statement for result storage

  • « mysqli_stmt::bind_param
  • mysqli_stmt::close »
  • PHP Manual
  • mysqli_stmt
  • Binds variables to a prepared statement for result storage

mysqli_stmt::bind_result

mysqli_stmt_bind_result

(PHP 5, PHP 7)

mysqli_stmt::bind_result -- mysqli_stmt_bind_result — Binds variables to a prepared statement for result storage

Description

Object oriented style

mysqli_stmt::bind_result ( mixed &$var1 [, mixed &$... ] ) : bool

Procedural style

mysqli_stmt_bind_result ( mysqli_stmt $stmt , mixed &$var1 [, mixed &$... ] ) : 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 var1, ....

Note:

Note that all columns must be bound after mysqli_stmt_execute() and prior to calling mysqli_stmt_fetch(). Depending on column types bound variables can silently change to the corresponding PHP type.

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.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

var1

The variable to be bound.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* prepare statement */
if ($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);
    }

    /* 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 (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* prepare statement */
if ($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);
    }

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

The above examples will output:

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
  • mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters
  • mysqli_stmt_execute() - Executes a prepared Query
  • mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • mysqli_prepare() - Prepare an SQL statement for execution
  • mysqli_stmt_prepare() - Prepare an SQL statement for execution
  • mysqli_stmt_init() - Initializes a statement and returns an object for use with mysqli_stmt_prepare
  • mysqli_stmt_errno() - Returns the error code for the most recent statement call
  • mysqli_stmt_error() - Returns a string description for last statement error


Closes a prepared statement

  • « mysqli_stmt::bind_result
  • mysqli_stmt::__construct »
  • PHP Manual
  • mysqli_stmt
  • Closes a prepared statement

mysqli_stmt::close

mysqli_stmt_close

(PHP 5, PHP 7)

mysqli_stmt::close -- mysqli_stmt_close — Closes a prepared statement

Description

Object oriented style

mysqli_stmt::close ( void ) : bool

Procedural style

mysqli_stmt_close ( mysqli_stmt $stmt ) : bool

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

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • mysqli_prepare() - Prepare an SQL statement for execution


Constructs a new mysqli_stmt object

  • « mysqli_stmt::close
  • mysqli_stmt::data_seek »
  • PHP Manual
  • mysqli_stmt
  • Constructs a new mysqli_stmt object

mysqli_stmt::__construct

(PHP 5, PHP 7)

mysqli_stmt::__construct — Constructs a new mysqli_stmt object

Description

mysqli_stmt::__construct ( mysqli $link [, string $query ] )

This method constructs a new mysqli_stmt object.

Note:

In general, you should use either mysqli_prepare() or mysqli_stmt_init() to create a mysqli_stmt object, rather than directly instantiating the object with new mysqli_stmt. This method (and the ability to directly instantiate mysqli_stmt objects) may be deprecated and removed in the future.

Parameters

link

Procedural style only: A link identifier returned by mysqli_connect() or mysqli_init()

query

The query, as a string. If this parameter is omitted, then the constructor behaves identically to mysqli_stmt_init(), if provided, then it behaves as per mysqli_prepare().

See Also

  • mysqli_prepare() - Prepare an SQL statement for execution
  • mysqli_stmt_init() - Initializes a statement and returns an object for use with mysqli_stmt_prepare


Seeks to an arbitrary row in statement result set

  • « mysqli_stmt::__construct
  • mysqli_stmt::$errno »
  • PHP Manual
  • mysqli_stmt
  • Seeks to an arbitrary row in statement result set

mysqli_stmt::data_seek

mysqli_stmt_data_seek

(PHP 5, PHP 7)

mysqli_stmt::data_seek -- mysqli_stmt_data_seek — Seeks to an arbitrary row in statement result set

Description

Object oriented style

mysqli_stmt::data_seek ( int $offset ) : void

Procedural style

mysqli_stmt_data_seek ( mysqli_stmt $stmt , int $offset ) : void

Seeks to an arbitrary result pointer in the statement result set.

mysqli_stmt_store_result() must be called prior to mysqli_stmt_data_seek().

Parameters

stmt

Procedural style only: A statement identifier 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
/* 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();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {

    /* execute query */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($name, $code);

    /* store result */
    $stmt->store_result();

    /* seek to row no. 400 */
    $stmt->data_seek(399);

    /* fetch values */
    $stmt->fetch();

    printf ("City: %s  Countrycode: %s\n", $name, $code);

    /* 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();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $name, $code);

    /* store result */
    mysqli_stmt_store_result($stmt);

    /* seek to row no. 400 */
    mysqli_stmt_data_seek($stmt, 399);

    /* fetch values */
    mysqli_stmt_fetch($stmt);

    printf ("City: %s  Countrycode: %s\n", $name, $code);

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

The above examples will output:

City: Benin City  Countrycode: NGA

See Also

  • mysqli_prepare() - Prepare an SQL statement for execution


Returns the error code for the most recent statement call

  • « mysqli_stmt::data_seek
  • mysqli_stmt::$error_list »
  • PHP Manual
  • mysqli_stmt
  • Returns the error code for the most recent statement call

mysqli_stmt::$errno

mysqli_stmt_errno

(PHP 5, PHP 7)

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 $stmt ) : int

Returns the error code for the most recently invoked statement function that can succeed or fail.

Client error message numbers are listed in the MySQL errmsg.h header file, server error message numbers are listed in mysqld_error.h. In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error.txt.

Parameters

stmt

Procedural style only: A statement identifier 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


Returns a list of errors from the last statement executed

  • « mysqli_stmt::$errno
  • mysqli_stmt::$error »
  • PHP Manual
  • mysqli_stmt
  • Returns a list of errors from the last statement executed

mysqli_stmt::$error_list

mysqli_stmt_error_list

(PHP 5 >= 5.4.0, PHP 7)

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 $stmt ) : array

Returns an array of errors for the most recently invoked statement function that can succeed or fail.

Parameters

stmt

Procedural style only: A statement identifier 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:

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


Returns a string description for last statement error

  • « mysqli_stmt::$error_list
  • mysqli_stmt::execute »
  • PHP Manual
  • mysqli_stmt
  • Returns a string description for last statement error

mysqli_stmt::$error

mysqli_stmt_error

(PHP 5, PHP 7)

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 $stmt ) : string

Returns a string containing the error message for the most recently invoked statement function that can succeed or fail.

Parameters

stmt

Procedural style only: A statement identifier 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


Executes a prepared Query

  • « mysqli_stmt::$error
  • mysqli_stmt::fetch »
  • PHP Manual
  • mysqli_stmt
  • Executes a prepared Query

mysqli_stmt::execute

mysqli_stmt_execute

(PHP 5, PHP 7)

mysqli_stmt::execute -- mysqli_stmt_execute — Executes a prepared Query

Description

Object oriented style

mysqli_stmt::execute ( void ) : bool

Procedural style

mysqli_stmt_execute ( mysqli_stmt $stmt ) : bool

Executes a query that has been previously prepared using the mysqli_prepare() function. When executed any parameter markers which exist will automatically be replaced with the appropriate data.

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. Likewise, if the query yields a result set the mysqli_stmt_fetch() function is used.

Note:

When using mysqli_stmt_execute(), the mysqli_stmt_fetch() function must be used to fetch the data prior to performing any additional queries.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

Returns TRUE on success or 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();
}

$mysqli->query("CREATE TABLE myCity LIKE City");

/* Prepare an insert statement */
$query = "INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)";
$stmt = $mysqli->prepare($query);

$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();

/* close statement */
$stmt->close();

/* retrieve all rows from myCity */
$query = "SELECT Name, CountryCode, District FROM myCity";
if ($result = $mysqli->query($query)) {
    while ($row = $result->fetch_row()) {
        printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
    }
    /* free result set */
    $result->close();
}

/* remove table */
$mysqli->query("DROP TABLE myCity");

/* 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();
}

mysqli_query($link, "CREATE TABLE myCity LIKE City");

/* Prepare an insert statement */
$query = "INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)";
$stmt = mysqli_prepare($link, $query);

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

/* close statement */
mysqli_stmt_close($stmt);

/* retrieve all rows from myCity */
$query = "SELECT Name, CountryCode, District FROM myCity";
if ($result = mysqli_query($link, $query)) {
    while ($row = mysqli_fetch_row($result)) {
        printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
    }
    /* free result set */
    mysqli_free_result($result);
}

/* remove table */
mysqli_query($link, "DROP TABLE myCity");

/* close connection */
mysqli_close($link);
?>

The above examples will output:

Stuttgart (DEU,Baden-Wuerttemberg)
Bordeaux (FRA,Aquitaine)

See Also

  • mysqli_prepare() - Prepare 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


Fetch results from a prepared statement into the bound variables

  • « mysqli_stmt::execute
  • mysqli_stmt::$field_count »
  • PHP Manual
  • mysqli_stmt
  • Fetch results from a prepared statement into the bound variables

mysqli_stmt::fetch

mysqli_stmt_fetch

(PHP 5, PHP 7)

mysqli_stmt::fetch -- mysqli_stmt_fetch — Fetch results from a prepared statement into the bound variables

Description

Object oriented style

mysqli_stmt::fetch ( void ) : bool

Procedural style

mysqli_stmt_fetch ( mysqli_stmt $stmt ) : 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 are transferred unbuffered without calling mysqli_stmt_store_result() which can decrease performance (but reduces memory cost).

Parameters

stmt

Procedural style only: A statement identifier 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

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


Returns the number of field in the given statement

  • « mysqli_stmt::fetch
  • mysqli_stmt::free_result »
  • PHP Manual
  • mysqli_stmt
  • Returns the number of field in the given statement

mysqli_stmt::$field_count

mysqli_stmt_field_count

(PHP 5, PHP 7)

mysqli_stmt::$field_count -- mysqli_stmt_field_count — Returns the number of field in the given statement

Description

Object oriented style

int $mysqli_stmt->field_count;

Procedural style

mysqli_stmt_field_count ( mysqli_stmt $stmt ) : int
Warning

This function is currently not documented; only its argument list is available.


Frees stored result memory for the given statement handle

  • « mysqli_stmt::$field_count
  • mysqli_stmt::get_result »
  • PHP Manual
  • mysqli_stmt
  • Frees stored result memory for the given statement handle

mysqli_stmt::free_result

mysqli_stmt_free_result

(PHP 5, PHP 7)

mysqli_stmt::free_result -- mysqli_stmt_free_result — Frees stored result memory for the given statement handle

Description

Object oriented style

mysqli_stmt::free_result ( void ) : void

Procedural style

mysqli_stmt_free_result ( mysqli_stmt $stmt ) : void

Frees the result memory associated with the statement, which was allocated by mysqli_stmt_store_result().

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

No value is returned.

See Also

  • mysqli_stmt_store_result() - Transfers a result set from a prepared statement


Gets a result set from a prepared statement

  • « mysqli_stmt::free_result
  • mysqli_stmt::get_warnings »
  • PHP Manual
  • mysqli_stmt
  • Gets a result set from a prepared statement

mysqli_stmt::get_result

mysqli_stmt_get_result

(PHP 5 >= 5.3.0, PHP 7)

mysqli_stmt::get_result -- mysqli_stmt_get_result — Gets a result set from a prepared statement

Description

Object oriented style

mysqli_stmt::get_result ( void ) : mysqli_result

Procedural style

mysqli_stmt_get_result ( mysqli_stmt $stmt ) : mysqli_result

Call to return a result set from a prepared statement query.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

Returns a resultset for successful SELECT queries, or FALSE for other DML queries or on failure. The mysqli_errno() function can be used to distinguish between the two types of failure.

MySQL Native Driver Only

Available only with mysqlnd.

Examples

Example #1 Object oriented style

<?php

$mysqli = new mysqli("127.0.0.1", "user", "password", "world");

if($mysqli->connect_error)
{
    die("$mysqli->connect_errno: $mysqli->connect_error");
}

$query = "SELECT Name, Population, Continent FROM Country WHERE Continent=? ORDER BY Name LIMIT 1";

$stmt = $mysqli->stmt_init();
if(!$stmt->prepare($query))
{
    print "Failed to prepare statement\n";
}
else
{
    $stmt->bind_param("s", $continent);

    $continent_array = array('Europe','Africa','Asia','North America');

    foreach($continent_array as $continent)
    {
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_array(MYSQLI_NUM))
        {
            foreach ($row as $r)
            {
                print "$r ";
            }
            print "\n";
        }
    }
}

$stmt->close();
$mysqli->close();
?>

Example #2 Procedural style

<?php

$link = mysqli_connect("127.0.0.1", "user", "password", "world");

if (!$link)
{
    $error = mysqli_connect_error();
    $errno = mysqli_connect_errno();
    print "$errno: $error\n";
    exit();
}

$query = "SELECT Name, Population, Continent FROM Country WHERE Continent=? ORDER BY Name LIMIT 1";

$stmt = mysqli_stmt_init($link);
if(!mysqli_stmt_prepare($stmt, $query))
{
    print "Failed to prepare statement\n";
}
else
{
    mysqli_stmt_bind_param($stmt, "s", $continent);

    $continent_array = array('Europe','Africa','Asia','North America');

    foreach($continent_array 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";
        }
    }
}
mysqli_stmt_close($stmt);
mysqli_close($link);
?>

The above examples will output:

Albania 3401200 Europe
Algeria 31471000 Africa
Afghanistan 22720000 Asia
Anguilla 8000 North America

See Also

  • mysqli_prepare() - Prepare 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 a result row as an associative, a numeric array, or both
  • mysqli_stmt_store_result() - Transfers a result set from a prepared statement
  • mysqli_errno() - Returns the error code for the most recent function call


Get result of SHOW WARNINGS

  • « mysqli_stmt::get_result
  • mysqli_stmt::$insert_id »
  • PHP Manual
  • mysqli_stmt
  • Get result of SHOW WARNINGS

mysqli_stmt::get_warnings

mysqli_stmt_get_warnings

(PHP 5 >= 5.1.0, PHP 7)

mysqli_stmt::get_warnings -- mysqli_stmt_get_warnings — Get result of SHOW WARNINGS

Description

Object oriented style

mysqli_stmt::get_warnings ( void ) : object

Procedural style

mysqli_stmt_get_warnings ( mysqli_stmt $stmt ) : object
Warning

This function is currently not documented; only its argument list is available.


Get the ID generated from the previous INSERT operation

  • « mysqli_stmt::get_warnings
  • mysqli_stmt::more_results »
  • PHP Manual
  • mysqli_stmt
  • Get the ID generated from the previous INSERT operation

mysqli_stmt::$insert_id

mysqli_stmt_insert_id

(PHP 5, PHP 7)

mysqli_stmt::$insert_id -- mysqli_stmt_insert_id — Get the ID generated from the previous INSERT operation

Description

Object oriented style

int $mysqli_stmt->insert_id;

Procedural style

mysqli_stmt_insert_id ( mysqli_stmt $stmt ) : mixed
Warning

This function is currently not documented; only its argument list is available.


Check if there are more query results from a multiple query

  • « mysqli_stmt::$insert_id
  • mysqli_stmt::next_result »
  • PHP Manual
  • mysqli_stmt
  • Check if there are more query results from a multiple query

mysqli_stmt::more_results

mysqli_stmt_more_results

(PHP 5 >= 5.3.0, PHP 7)

mysqli_stmt::more_results -- mysqli_stmt_more_results — Check if there are more query results from a multiple query

Description

Object oriented style (method):

public mysqli_stmt::more_results ( void ) : bool

Procedural style:

mysqli_stmt_more_results ( mysql_stmt $stmt ) : bool

Checks if there are more query results from a multiple query.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

Returns TRUE if more results exist, otherwise FALSE.

MySQL Native Driver Only

Available only with mysqlnd.

See Also

  • mysqli_stmt::next_result() - Reads the next result from a multiple query
  • mysqli::multi_query() - Performs a query on the database


Reads the next result from a multiple query

  • « mysqli_stmt::more_results
  • mysqli_stmt::$num_rows »
  • PHP Manual
  • mysqli_stmt
  • Reads the next result from a multiple query

mysqli_stmt::next_result

mysqli_stmt_next_result

(PHP 5 >= 5.3.0, PHP 7)

mysqli_stmt::next_result -- mysqli_stmt_next_result — Reads the next result from a multiple query

Description

Object oriented style (method):

public mysqli_stmt::next_result ( void ) : bool

Procedural style:

mysqli_stmt_next_result ( mysql_stmt $stmt ) : bool

Reads the next result from a multiple query.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Emits an E_STRICT level error if a result set does not exist, and suggests using mysqli_stmt::more_results() in these cases, before calling mysqli_stmt::next_result().

MySQL Native Driver Only

Available only with mysqlnd.

See Also

  • mysqli_stmt::more_results() - Check if there are more query results from a multiple query
  • mysqli::multi_query() - Performs a query on the database


Return the number of rows in statements result set

  • « mysqli_stmt::next_result
  • mysqli_stmt::$param_count »
  • PHP Manual
  • mysqli_stmt
  • Return the number of rows in statements result set

mysqli_stmt::$num_rows

mysqli_stmt::num_rows

mysqli_stmt_num_rows

(PHP 5, PHP 7)

mysqli_stmt::$num_rows -- mysqli_stmt::num_rows -- mysqli_stmt_num_rows — Return the number of rows in statements result set

Description

Object oriented style

int $mysqli_stmt->num_rows;
mysqli_stmt::num_rows ( void ) : int

Procedural style

mysqli_stmt_num_rows ( mysqli_stmt $stmt ) : int

Returns the number of rows in the result set. The use of mysqli_stmt_num_rows() depends on whether or not you used mysqli_stmt_store_result() to buffer the entire result set in the statement handle.

If you use mysqli_stmt_store_result(), mysqli_stmt_num_rows() may be called immediately.

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

An integer representing the number of rows in result set.

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();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
if ($stmt = $mysqli->prepare($query)) {

    /* execute query */
    $stmt->execute();

    /* store result */
    $stmt->store_result();

    printf("Number of rows: %d.\n", $stmt->num_rows);

    /* 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();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
if ($stmt = mysqli_prepare($link, $query)) {

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* store result */
    mysqli_stmt_store_result($stmt);

    printf("Number of rows: %d.\n", mysqli_stmt_num_rows($stmt));

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

The above examples will output:

Number of rows: 20.

See Also

  • mysqli_stmt_affected_rows() - Returns the total number of rows changed, deleted, or inserted by the last executed statement
  • mysqli_prepare() - Prepare an SQL statement for execution
  • mysqli_stmt_store_result() - Transfers a result set from a prepared statement


Returns the number of parameter for the given statement

  • « mysqli_stmt::$num_rows
  • mysqli_stmt::prepare »
  • PHP Manual
  • mysqli_stmt
  • Returns the number of parameter for the given statement

mysqli_stmt::$param_count

mysqli_stmt_param_count

(PHP 5, PHP 7)

mysqli_stmt::$param_count -- mysqli_stmt_param_count — Returns the number of parameter for the given statement

Description

Object oriented style

int $mysqli_stmt->param_count;

Procedural style

mysqli_stmt_param_count ( mysqli_stmt $stmt ) : int

Returns the number of parameter markers present in the prepared statement.

Parameters

stmt

Procedural style only: A statement identifier 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() - Prepare an SQL statement for execution


Prepare an SQL statement for execution

  • « mysqli_stmt::$param_count
  • mysqli_stmt::reset »
  • PHP Manual
  • mysqli_stmt
  • Prepare an SQL statement for execution

mysqli_stmt::prepare

mysqli_stmt_prepare

(PHP 5, PHP 7)

mysqli_stmt::prepare -- mysqli_stmt_prepare — Prepare an SQL statement for execution

Description

Object oriented style

mysqli_stmt::prepare ( string $query ) : mixed

Procedural style

mysqli_stmt_prepare ( mysqli_stmt $stmt , string $query ) : bool

Prepares the SQL query pointed to by the null-terminated string query.

The parameter markers must be bound to application variables using mysqli_stmt_bind_param() and/or mysqli_stmt_bind_result() before executing the statement or fetching rows.

Note:

In the case where you pass a statement 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

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

query

The query, as a string. It must consist of a single SQL statement.

You can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions.

Note:

You should not add a terminating semicolon or \g to the statement.

Note:

The markers are legal only in certain places in SQL statements. For example, they are allowed 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 allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement), or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. In general, parameters are legal only in Data Manipulation Language (DML) statements, and not in Data Definition Language (DDL) statements.

Return Values

Returns TRUE on success or 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();
}

$city = "Amersfoort";

/* create a prepared statement */
$stmt =  $mysqli->stmt_init();
if ($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);

    /* 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();
}

$city = "Amersfoort";

/* create a prepared statement */
$stmt = mysqli_stmt_init($link);
if (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);

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

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 Query
  • 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
  • mysqli_stmt_close() - Closes a prepared statement


Resets a prepared statement

  • « mysqli_stmt::prepare
  • mysqli_stmt::result_metadata »
  • PHP Manual
  • mysqli_stmt
  • Resets a prepared statement

mysqli_stmt::reset

mysqli_stmt_reset

(PHP 5, PHP 7)

mysqli_stmt::reset -- mysqli_stmt_reset — Resets a prepared statement

Description

Object oriented style

mysqli_stmt::reset ( void ) : bool

Procedural style

mysqli_stmt_reset ( mysqli_stmt $stmt ) : 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

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • mysqli_prepare() - Prepare an SQL statement for execution


Returns result set metadata from a prepared statement

  • « mysqli_stmt::reset
  • mysqli_stmt::send_long_data »
  • PHP Manual
  • mysqli_stmt
  • Returns result set metadata from a prepared statement

mysqli_stmt::result_metadata

mysqli_stmt_result_metadata

(PHP 5, PHP 7)

mysqli_stmt::result_metadata -- mysqli_stmt_result_metadata — Returns result set metadata from a prepared statement

Description

Object oriented style

mysqli_stmt::result_metadata ( void ) : mysqli_result

Procedural style

mysqli_stmt_result_metadata ( mysqli_stmt $stmt ) : mysqli_result

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.

Note:

This result set pointer can be passed as an argument to any of 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()

The result set structure should be freed when you are done with it, which you can do by passing it to 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 using the statement handle with mysqli_stmt_fetch().

Parameters

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

Returns a result object or FALSE if an error occurred.

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

/* close resultset */
$result->close();

/* close connection */
$mysqli->close();
?>

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

/* close resultset */
mysqli_free_result($result);

/* close connection */
mysqli_close($link);
?>

See Also

  • mysqli_prepare() - Prepare an SQL statement for execution
  • mysqli_free_result() - Frees the memory associated with a result


Send data in blocks

  • « mysqli_stmt::result_metadata
  • mysqli_stmt::$sqlstate »
  • PHP Manual
  • mysqli_stmt
  • Send data in blocks

mysqli_stmt::send_long_data

mysqli_stmt_send_long_data

(PHP 5, PHP 7)

mysqli_stmt::send_long_data -- mysqli_stmt_send_long_data — Send data in blocks

Description

Object oriented style

mysqli_stmt::send_long_data ( int $param_nr , string $data ) : bool

Procedural style

mysqli_stmt_send_long_data ( mysqli_stmt $stmt , int $param_nr , 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

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

param_nr

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() - Prepare an SQL statement for execution
  • mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters


Returns SQLSTATE error from previous statement operation

  • « mysqli_stmt::send_long_data
  • mysqli_stmt::store_result »
  • PHP Manual
  • mysqli_stmt
  • Returns SQLSTATE error from previous statement operation

mysqli_stmt::$sqlstate

mysqli_stmt_sqlstate

(PHP 5, PHP 7)

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 $stmt ) : 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

stmt

Procedural style only: A statement identifier 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.

Notes

Note:

Note that not all MySQL errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.

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.

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


Transfers a result set from a prepared statement

  • « mysqli_stmt::$sqlstate
  • mysqli_result »
  • PHP Manual
  • mysqli_stmt
  • Transfers a result set from a prepared statement

mysqli_stmt::store_result

mysqli_stmt_store_result

(PHP 5, PHP 7)

mysqli_stmt::store_result -- mysqli_stmt_store_result — Transfers a result set from a prepared statement

Description

Object oriented style

mysqli_stmt::store_result ( void ) : bool

Procedural style

mysqli_stmt_store_result ( mysqli_stmt $stmt ) : bool

You must call mysqli_stmt_store_result() for every query that successfully produces a result set (SELECT, SHOW, DESCRIBE, EXPLAIN), if and only if you want to buffer the complete result set by the client, so that the subsequent mysqli_stmt_fetch() call returns 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

stmt

Procedural style only: A statement identifier returned by mysqli_stmt_init().

Return Values

Returns TRUE on success or FALSE on failure.

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();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
if ($stmt = $mysqli->prepare($query)) {

    /* execute query */
    $stmt->execute();

    /* store result */
    $stmt->store_result();

    printf("Number of rows: %d.\n", $stmt->num_rows);

    /* free result */
    $stmt->free_result();

    /* 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();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
if ($stmt = mysqli_prepare($link, $query)) {

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* store result */
    mysqli_stmt_store_result($stmt);

    printf("Number of rows: %d.\n", mysqli_stmt_num_rows($stmt));

    /* free result */
    mysqli_stmt_free_result($stmt);

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

The above examples will output:

Number of rows: 20.

See Also

  • mysqli_prepare() - Prepare 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


The mysqli_result class

(PHP 5, PHP 7)

Introduction

Represents the result set obtained from a query against the database.

Changelog

Changelog
Version | Description
5.4.0 | Iterator support was added, as mysqli_result now implements Traversable.

Class synopsis

mysqli_result implements Traversable {
/* Properties */
int $current_field ;
int $field_count;
array $lengths;
int $num_rows;
/* Methods */
data_seek ( int $offset ) : bool
fetch_all ([ int $resulttype = MYSQLI_NUM ] ) : mixed
fetch_array ([ int $resulttype = MYSQLI_BOTH ] ) : mixed
fetch_assoc ( void ) : array
fetch_field_direct ( int $fieldnr ) : object
fetch_field ( void ) : object
fetch_fields ( void ) : array
fetch_object ([ string $class_name = "stdClass" [, array $params ]] ) : object
fetch_row ( void ) : mixed
field_seek ( int $fieldnr ) : bool
free ( void ) : void
}

Table of Contents

  • 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 — Fetches all result rows as an associative array, a numeric array, or both
  • mysqli_result::fetch_array — Fetch a result row as an associative, a numeric array, or both
  • mysqli_result::fetch_assoc — Fetch a result row as an associative array
  • mysqli_result::fetch_field_direct — Fetch meta-data for a single field
  • mysqli_result::fetch_field — Returns the next field in the result set
  • mysqli_result::fetch_fields — Returns an array of objects representing the fields in a result set
  • mysqli_result::fetch_object — Returns the current row of a result set as an object
  • mysqli_result::fetch_row — Get a result row as an enumerated array
  • mysqli_result::$field_count — Get the number of fields in a result
  • mysqli_result::field_seek — Set result pointer to a specified field offset
  • mysqli_result::free — Frees the memory associated with a result
  • 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 a result


Get current field offset of a result pointer

  • « mysqli_result
  • mysqli_result::data_seek »
  • PHP Manual
  • mysqli_result
  • Get current field offset of a result pointer

mysqli_result::$current_field

mysqli_field_tell

(PHP 5, PHP 7)

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 result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_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


Adjusts the result pointer to an arbitrary row in the result

  • « mysqli_result::$current_field
  • mysqli_result::fetch_all »
  • PHP Manual
  • mysqli_result
  • Adjusts the result pointer to an arbitrary row in the result

mysqli_result::data_seek

mysqli_data_seek

(PHP 5, PHP 7)

mysqli_result::data_seek -- mysqli_data_seek — Adjusts the result pointer to an arbitrary row in the result

Description

Object oriented style

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 result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

offset

The field 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.

Notes

Note:

This function can only be used with buffered results attained from the use of the mysqli_store_result() or mysqli_query() functions.

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();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
if ($result = $mysqli->query($query)) {

    /* seek to row no. 400 */
    $result->data_seek(399);

    /* fetch row */
    $row = $result->fetch_row();

    printf ("City: %s  Countrycode: %s\n", $row[0], $row[1]);

    /* free result set*/
    $result->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 (!$link) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name";

if ($result = mysqli_query($link, $query)) {

    /* seek to row no. 400 */
    mysqli_data_seek($result, 399);

    /* fetch row */
    $row = mysqli_fetch_row($result);

    printf ("City: %s  Countrycode: %s\n", $row[0], $row[1]);

    /* free result set*/
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

The above examples will output:

City: Benin City  Countrycode: NGA

See Also

  • mysqli_store_result() - Transfers a result set from the last query
  • mysqli_fetch_row() - Get a result row as an enumerated array
  • mysqli_fetch_array() - Fetch a result row as an associative, a numeric array, or both
  • mysqli_fetch_assoc() - Fetch a result row as an associative array
  • mysqli_fetch_object() - Returns the current 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 a result


Fetches all result rows as an associative array, a numeric array, or both

  • « mysqli_result::data_seek
  • mysqli_result::fetch_array »
  • PHP Manual
  • mysqli_result
  • Fetches all result rows as an associative array, a numeric array, or both

mysqli_result::fetch_all

mysqli_fetch_all

(PHP 5 >= 5.3.0, PHP 7)

mysqli_result::fetch_all -- mysqli_fetch_all — Fetches all result rows as an associative array, a numeric array, or both

Description

Object oriented style

mysqli_result::fetch_all ([ int $resulttype = MYSQLI_NUM ] ) : mixed

Procedural style

mysqli_fetch_all ( mysqli_result $result [, int $resulttype = MYSQLI_NUM ] ) : mixed

mysqli_fetch_all() fetches all result rows and returns the result set as an associative array, a numeric array, or both.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

resulttype

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.

MySQL Native Driver Only

Available only with mysqlnd.

As mysqli_fetch_all() returns all the rows as an array in a single step, it may consume more memory than some similar functions such as mysqli_fetch_array(), which only returns one row at a time from the result set. Further, if you need to iterate over the result set, you will need a looping construct that will further impact performance. For these reasons mysqli_fetch_all() should only be used in those situations where the fetched result set will be sent to another layer for processing.

See Also

  • mysqli_fetch_array() - Fetch a result row as an associative, a numeric array, or both
  • mysqli_query() - Performs a query on the database


Fetch a result row as an associative, a numeric array, or both

  • « mysqli_result::fetch_all
  • mysqli_result::fetch_assoc »
  • PHP Manual
  • mysqli_result
  • Fetch a result row as an associative, a numeric array, or both

mysqli_result::fetch_array

mysqli_fetch_array

(PHP 5, PHP 7)

mysqli_result::fetch_array -- mysqli_fetch_array — Fetch a result row as an associative, a numeric array, or both

Description

Object oriented style

mysqli_result::fetch_array ([ int $resulttype = MYSQLI_BOTH ] ) : mixed

Procedural style

mysqli_fetch_array ( mysqli_result $result [, int $resulttype = MYSQLI_BOTH ] ) : mixed

Returns an array that corresponds to the fetched row or NULL if there are no more rows for the resultset represented by the result parameter.

mysqli_fetch_array() is an extended version of the mysqli_fetch_row() function. In addition to storing the data in the numeric indices of the result array, the mysqli_fetch_array() function can also store the data in associative indices, using the field names of the result set as keys.

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to the PHP NULL value.

If two or more columns of the result have the same field names, the last column will take precedence and overwrite the earlier data. In order to access multiple columns with the same name, the numerically indexed version of the row must be used.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

resulttype

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 of strings that corresponds to the fetched row or NULL if there are no more rows in resultset.

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

/* free result set */
$result->free();

/* 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 LIMIT 3";
$result = mysqli_query($link, $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"]);

/* free result set */
mysqli_free_result($result);

/* close connection */
mysqli_close($link);
?>

The above examples will output:

Kabul (AFG)
Qandahar (AFG)
Herat (AFG)

See Also

  • mysqli_fetch_assoc() - Fetch a result row as an associative array
  • mysqli_fetch_row() - Get a result row as an enumerated array
  • mysqli_fetch_object() - Returns the current 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


Fetch a result row as an associative array

  • « mysqli_result::fetch_array
  • mysqli_result::fetch_field_direct »
  • PHP Manual
  • mysqli_result
  • Fetch a result row as an associative array

mysqli_result::fetch_assoc

mysqli_fetch_assoc

(PHP 5, PHP 7)

mysqli_result::fetch_assoc -- mysqli_fetch_assoc — Fetch a result row as an associative array

Description

Object oriented style

mysqli_result::fetch_assoc ( void ) : array

Procedural style

mysqli_fetch_assoc ( mysqli_result $result ) : array

Returns an associative array that corresponds to the fetched row or NULL if there are no more rows.

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 result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

Return Values

Returns an associative array of strings representing the fetched row in the result set, where each key in the array represents the name of one of the result set's columns or NULL if there are no more rows in resultset.

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 mysqli_fetch_row() or add alias names.

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 50,5";

if ($result = $mysqli->query($query)) {

    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {
        printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
    }

    /* free result set */
    $result->free();
}

/* 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 50,5";

if ($result = mysqli_query($link, $query)) {

    /* fetch associative array */
    while ($row = mysqli_fetch_assoc($result)) {
        printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
    }

    /* free result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

The above examples will output:

Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

Example #3 A mysqli_result example comparing iterator usage

<?php
$c = mysqli_connect('127.0.0.1','user', 'pass');

// Using iterators (support was added with PHP 5.4)
foreach ( $c->query('SELECT user,host FROM mysql.user') as $row ) {
    printf("'%s'@'%s'\n", $row['user'], $row['host']);
}

echo "\n==================\n";

// Not using iterators
$result = $c->query('SELECT user,host FROM mysql.user');
while ($row = $result->fetch_assoc()) {
    printf("'%s'@'%s'\n", $row['user'], $row['host']);
}

?>

The above example will output something similar to:

'root'@'192.168.1.1'
'root'@'127.0.0.1'
'dude'@'localhost'
'lebowski'@'localhost'

==================

'root'@'192.168.1.1'
'root'@'127.0.0.1'
'dude'@'localhost'
'lebowski'@'localhost'

See Also

  • mysqli_fetch_array() - Fetch a result row as an associative, a numeric array, or both
  • mysqli_fetch_row() - Get a result row as an enumerated array
  • mysqli_fetch_object() - Returns the current 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


Fetch meta-data for a single field

  • « mysqli_result::fetch_assoc
  • mysqli_result::fetch_field »
  • PHP Manual
  • mysqli_result
  • Fetch meta-data for a single field

mysqli_result::fetch_field_direct

mysqli_fetch_field_direct

(PHP 5, PHP 7)

mysqli_result::fetch_field_direct -- mysqli_fetch_field_direct — Fetch meta-data for a single field

Description

Object oriented style

mysqli_result::fetch_field_direct ( int $fieldnr ) : object

Procedural style

mysqli_fetch_field_direct ( mysqli_result $result , int $fieldnr ) : object

Returns an object which contains field definition information from the specified result set.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

fieldnr

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 fieldnr is available.

Object attributes
Attribute | 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 | The default value for this field, represented as a string
max_length | The maximum width of the field for the result set.
length | The width of the field, as specified in the table definition.
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 used (for numeric 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() - Get the number of fields in a result
  • 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


Returns the next field in the result set

  • « mysqli_result::fetch_field_direct
  • mysqli_result::fetch_fields »
  • PHP Manual
  • mysqli_result
  • Returns the next field in the result set

mysqli_result::fetch_field

mysqli_fetch_field

(PHP 5, PHP 7)

mysqli_result::fetch_field -- mysqli_fetch_field — Returns the next field in the result set

Description

Object oriented style

mysqli_result::fetch_field ( void ) : object

Procedural style

mysqli_fetch_field ( mysqli_result $result ) : object

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 result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_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 | Reserved for default value, currently always ""
db | Database (since PHP 5.3.6)
catalog | The catalog name, always "def" (since PHP 5.3.6)
max_length | The maximum width of the field for the result set.
length | The width of the field, as specified in the table definition.
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 used (for integer 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() - Get the number of fields in a result
  • 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


Returns an array of objects representing the fields in a result set

  • « mysqli_result::fetch_field
  • mysqli_result::fetch_object »
  • PHP Manual
  • mysqli_result
  • Returns an array of objects representing the fields in a result set

mysqli_result::fetch_fields

mysqli_fetch_fields

(PHP 5, PHP 7)

mysqli_result::fetch_fields -- mysqli_fetch_fields — Returns an array of objects representing the fields in a result set

Description

Object oriented style

mysqli_result::fetch_fields ( void ) : 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 result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

Return Values

Returns an array of objects 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
max_length | The maximum width of the field for the result set.
length | The width of the field, in bytes, as specified in the table definition. Note that this number (bytes) might differ from your table definition value (characters), depending on the character set you use. For example, the character set utf8 has 3 bytes per character, so varchar(10) will return a length of 30 for utf8 (10*3), but return 10 for latin1 (10*1).
charsetnr | The character set number (id) 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 used (for integer 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() - Get the number of fields in a result
  • mysqli_fetch_field_direct() - Fetch meta-data for a single field
  • mysqli_fetch_field() - Returns the next field in the result set


Returns the current row of a result set as an object

  • « mysqli_result::fetch_fields
  • mysqli_result::fetch_row »
  • PHP Manual
  • mysqli_result
  • Returns the current row of a result set as an object

mysqli_result::fetch_object

mysqli_fetch_object

(PHP 5, PHP 7)

mysqli_result::fetch_object -- mysqli_fetch_object — Returns the current row of a result set as an object

Description

Object oriented style

mysqli_result::fetch_object ([ string $class_name = "stdClass" [, array $params ]] ) : object

Procedural style

mysqli_fetch_object ( mysqli_result $result [, string $class_name = "stdClass" [, array $params ]] ) : object

The mysqli_fetch_object() will return the current row result set as an object where the attributes of the object represent the names of the fields found within the result set.

Note that mysqli_fetch_object() sets the properties of the object before calling the object constructor.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

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 corresponds to the fetched row or NULL if there are no more rows in resultset.

Note: Field names returned by this function are case-sensitive.

Note: This function sets NULL fields to the PHP NULL value.

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 50,5";

if ($result = $mysqli->query($query)) {

    /* fetch object array */
    while ($obj = $result->fetch_object()) {
        printf ("%s (%s)\n", $obj->Name, $obj->CountryCode);
    }

    /* free result set */
    $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, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = mysqli_query($link, $query)) {

    /* fetch associative array */
    while ($obj = mysqli_fetch_object($result)) {
        printf ("%s (%s)\n", $obj->Name, $obj->CountryCode);
    }

    /* free result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

The above examples will output:

Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

See Also

  • mysqli_fetch_array() - Fetch a result row as an associative, a numeric array, or both
  • mysqli_fetch_assoc() - Fetch a result row as an associative array
  • mysqli_fetch_row() - Get a result row 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


Get a result row as an enumerated array

  • « mysqli_result::fetch_object
  • mysqli_result::$field_count »
  • PHP Manual
  • mysqli_result
  • Get a result row as an enumerated array

mysqli_result::fetch_row

mysqli_fetch_row

(PHP 5, PHP 7)

mysqli_result::fetch_row -- mysqli_fetch_row — Get a result row as an enumerated array

Description

Object oriented style

mysqli_result::fetch_row ( void ) : mixed

Procedural style

mysqli_fetch_row ( mysqli_result $result ) : mixed

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.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

Return Values

mysqli_fetch_row() returns an array of strings that corresponds to the fetched row or NULL if there are no more rows in result set.

Note: This function sets NULL fields to the PHP NULL value.

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 50,5";

if ($result = $mysqli->query($query)) {

    /* fetch object array */
    while ($row = $result->fetch_row()) {
        printf ("%s (%s)\n", $row[0], $row[1]);
    }

    /* free result set */
    $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, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

if ($result = mysqli_query($link, $query)) {

    /* fetch associative array */
    while ($row = mysqli_fetch_row($result)) {
        printf ("%s (%s)\n", $row[0], $row[1]);
    }

    /* free result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

The above examples will output:

Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

See Also

  • mysqli_fetch_array() - Fetch a result row as an associative, a numeric array, or both
  • mysqli_fetch_assoc() - Fetch a result row as an associative array
  • mysqli_fetch_object() - Returns the current 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


Get the number of fields in a result

  • « mysqli_result::fetch_row
  • mysqli_result::field_seek »
  • PHP Manual
  • mysqli_result
  • Get the number of fields in a result

mysqli_result::$field_count

mysqli_num_fields

(PHP 5, PHP 7)

mysqli_result::$field_count -- mysqli_num_fields — Get the number of fields in a result

Description

Object oriented style

int $mysqli_result->field_count;

Procedural style

mysqli_num_fields ( mysqli_result $result ) : int

Returns the number of fields from specified result set.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

Return Values

The number of fields from a result set.

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 ($result = $mysqli->query("SELECT * FROM City ORDER BY ID LIMIT 1")) {

    /* determine number of fields in result set */
    $field_cnt = $result->field_count;

    printf("Result set has %d fields.\n", $field_cnt);

    /* close result set */
    $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();
}

if ($result = mysqli_query($link, "SELECT * FROM City ORDER BY ID LIMIT 1")) {

    /* determine number of fields in result set */
    $field_cnt = mysqli_num_fields($result);

    printf("Result set has %d fields.\n", $field_cnt);

    /* close result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

The above examples will output:

Result set has 5 fields.

See Also

  • mysqli_fetch_field() - Returns the next field in the result set


Set result pointer to a specified field offset

  • « mysqli_result::$field_count
  • mysqli_result::free »
  • PHP Manual
  • mysqli_result
  • Set result pointer to a specified field offset

mysqli_result::field_seek

mysqli_field_seek

(PHP 5, PHP 7)

mysqli_result::field_seek -- mysqli_field_seek — Set result pointer to a specified field offset

Description

Object oriented style

mysqli_result::field_seek ( int $fieldnr ) : bool

Procedural style

mysqli_field_seek ( mysqli_result $result , int $fieldnr ) : bool

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 result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

fieldnr

The field number. This value must be in the range from 0 to number of fields - 1.

Return Values

Returns TRUE on success or 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


Frees the memory associated with a result

  • « mysqli_result::field_seek
  • mysqli_result::$lengths »
  • PHP Manual
  • mysqli_result
  • Frees the memory associated with a result

mysqli_result::free

mysqli_result::close

mysqli_result::free_result

mysqli_free_result

(PHP 5, PHP 7)

mysqli_result::free -- mysqli_result::close -- mysqli_result::free_result -- mysqli_free_result — Frees the memory associated with a result

Description

Object oriented style

mysqli_result::free ( void ) : void
mysqli_result::close ( void ) : void
mysqli_result::free_result ( void ) : void

Procedural style

mysqli_free_result ( mysqli_result $result ) : void

Frees the memory associated with the result.

Note:

You should always free your result with mysqli_free_result(), when your result object is not needed anymore.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

Return Values

No value is returned.

See Also

  • mysqli_query() - Performs a query on the database
  • mysqli_stmt_store_result() - Transfers a result set from a prepared statement
  • mysqli_store_result() - Transfers a result set from the last query
  • mysqli_use_result() - Initiate a result set retrieval


Returns the lengths of the columns of the current row in the result set

  • « mysqli_result::free
  • mysqli_result::$num_rows »
  • PHP Manual
  • mysqli_result
  • Returns the lengths of the columns of the current row in the result set

mysqli_result::$lengths

mysqli_fetch_lengths

(PHP 5, PHP 7)

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

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 result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_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


Gets the number of rows in a result

  • « mysqli_result::$lengths
  • mysqli_driver »
  • PHP Manual
  • mysqli_result
  • Gets the number of rows in a result

mysqli_result::$num_rows

mysqli_num_rows

(PHP 5, PHP 7)

mysqli_result::$num_rows -- mysqli_num_rows — Gets the number of rows in a result

Description

Object oriented style

int $mysqli_result->num_rows;

Procedural style

mysqli_num_rows ( mysqli_result $result ) : int

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. For unbuffered result sets, mysqli_num_rows() will not return the correct number of rows until all the rows in the result have been retrieved.

Parameters

result

Procedural style only: A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result().

Return Values

Returns number of rows in the result set.

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 = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($result = $mysqli->query("SELECT Code, Name FROM Country ORDER BY Name")) {

    /* determine number of rows result set */
    $row_cnt = $result->num_rows;

    printf("Result set has %d rows.\n", $row_cnt);

    /* close result set */
    $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();
}

if ($result = mysqli_query($link, "SELECT Code, Name FROM Country ORDER BY Name")) {

    /* determine number of rows result set */
    $row_cnt = mysqli_num_rows($result);

    printf("Result set has %d rows.\n", $row_cnt);

    /* close result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

The above examples will output:

Result set has 239 rows.

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


The mysqli_driver class

(PHP 5, PHP 7)

Introduction

MySQLi Driver.

Class synopsis

mysqli_driver {
/* Properties */
public readonly string $client_info ;
public readonly string $client_version ;
public readonly string $driver_version ;
public readonly string $embedded ;
public bool $reconnect ;
public int $report_mode ;
/* Methods */
embedded_server_end ( void ) : void
embedded_server_start ( int $start , array $arguments , array $groups ) : bool
}

Properties

client_info

The Client API header version

client_version

The Client version

driver_version

The MySQLi Driver version

embedded

Whether MySQLi Embedded support is enabled

reconnect

Allow or prevent reconnect (see the mysqli.reconnect INI directive)

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

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 — Enables or disables internal report functions


Stop embedded server

  • « mysqli_driver
  • mysqli_driver::embedded_server_start »
  • PHP Manual
  • mysqli_driver
  • Stop embedded server

mysqli_driver::embedded_server_end

mysqli_embedded_server_end

(PHP 5, PHP 7)

mysqli_driver::embedded_server_end -- mysqli_embedded_server_end — Stop embedded server

Description

Object oriented style

mysqli_driver::embedded_server_end ( void ) : void

Procedural style

mysqli_embedded_server_end ( void ) : void
Warning

This function is currently not documented; only its argument list is available.


Initialize and start embedded server

  • « mysqli_driver::embedded_server_end
  • mysqli_driver::$report_mode »
  • PHP Manual
  • mysqli_driver
  • Initialize and start embedded server

mysqli_driver::embedded_server_start

mysqli_embedded_server_start

(PHP 5, PHP 7)

mysqli_driver::embedded_server_start -- mysqli_embedded_server_start — Initialize and start embedded server

Description

Object oriented style

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.


Enables or disables internal report functions

  • « mysqli_driver::embedded_server_start
  • mysqli_warning »
  • PHP Manual
  • mysqli_driver
  • Enables or disables internal report functions

mysqli_driver::$report_mode

mysqli_report

(PHP 5, PHP 7)

mysqli_driver::$report_mode -- mysqli_report — Enables or disables internal report functions

Description

Object oriented style

int $mysqli_driver->report_mode ;

Procedural style

mysqli_report ( int $flags ) : bool

A function helpful in improving queries during code development and testing. Depending on the flags, it reports errors from mysqli function calls or queries that don't use an index (or use a bad index).

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

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.3.4 | Changing the reporting mode is now be per-request, rather than per-process.
5.2.15 | Changing the reporting mode is now be per-request, rather than per-process.

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();
}

/* activate reporting */
$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_ALL;

try {

    /* this query should report an error */
    $result = $mysqli->query("SELECT Name FROM Nonexistingtable WHERE population > 50000");

    /* this query should report a bad index */
    $result = $mysqli->query("SELECT Name FROM City WHERE population > 50000");

    $result->close();

    $mysqli->close();

} catch (mysqli_sql_exception $e) {

    echo $e->__toString();
}
?>

Example #2 Procedural style

<?php
/* activate reporting */
mysqli_report(MYSQLI_REPORT_ALL);

$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* this query should report an error */
$result = mysqli_query("SELECT Name FROM Nonexistingtable WHERE population > 50000");

/* this query should report a bad index */
$result = mysqli_query("SELECT Name FROM City WHERE population > 50000");

mysqli_free_result($result);

mysqli_close($link);
?>

See Also

  • mysqli_debug() - Performs debugging operations
  • mysqli_dump_debug_info() - Dump debugging information into the log
  • mysqli_sql_exception
  • set_exception_handler() - Sets a user-defined exception handler function
  • error_reporting() - Sets which PHP errors are reported


The mysqli_warning class

(PHP 5, PHP 7)

Introduction

Represents a MySQL warning.

Class synopsis

mysqli_warning {
/* Properties */
public $message ;
public $sqlstate ;
public $errno ;
/* Methods */
protected __construct ( void )
public next ( void ) : bool
}

Properties

message

Message string

sqlstate

SQL state

errno

Error number

Table of Contents

  • mysqli_warning::__construct — The __construct purpose
  • mysqli_warning::next — Fetch next warning


The __construct purpose

  • « mysqli_warning
  • mysqli_warning::next »
  • PHP Manual
  • mysqli_warning
  • The __construct purpose

mysqli_warning::__construct

(PHP 5, PHP 7)

mysqli_warning::__construct — The __construct purpose

Description

protected mysqli_warning::__construct ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Fetch next warning

  • « mysqli_warning::__construct
  • mysqli_sql_exception »
  • PHP Manual
  • mysqli_warning
  • Fetch next warning

mysqli_warning::next

(PHP 5, PHP 7)

mysqli_warning::next — Fetch next warning

Description

public mysqli_warning::next ( void ) : 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


The mysqli_sql_exception class

(PHP 5, PHP 7)

Introduction

The mysqli exception handling class.

Class synopsis

mysqli_sql_exception extends RuntimeException {
/* Properties */
protected string $sqlstate ;
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
}

Properties

sqlstate

The sql state with the error.


Aliases and deprecated Mysqli Functions

Table of Contents

  • mysqli_bind_param — Alias for mysqli_stmt_bind_param
  • mysqli_bind_result — Alias for mysqli_stmt_bind_result
  • mysqli_client_encoding — Alias of mysqli_character_set_name
  • mysqli_connect — Alias of mysqli::__construct
  • mysqli::disable_reads_from_master — Disable reads from master
  • mysqli_disable_rpl_parse — Disable RPL parse
  • mysqli_enable_reads_from_master — Enable reads from master
  • mysqli_enable_rpl_parse — Enable RPL parse
  • mysqli_escape_string — Alias of mysqli_real_escape_string
  • mysqli_execute — Alias for mysqli_stmt_execute
  • mysqli_fetch — Alias for mysqli_stmt_fetch
  • mysqli_get_cache_stats — Returns client Zval cache statistics
  • mysqli_get_client_stats — Returns client per-process statistics
  • mysqli_get_links_stats — Return information about open and cached links
  • mysqli_get_metadata — Alias for mysqli_stmt_result_metadata
  • mysqli_master_query — Enforce execution of a query on the master in a master/slave setup
  • mysqli_param_count — Alias for mysqli_stmt_param_count
  • mysqli_report — Alias of mysqli_driver->report_mode
  • mysqli_rpl_parse_enabled — Check if RPL parse is enabled
  • mysqli_rpl_probe — RPL probe
  • mysqli_send_long_data — Alias for mysqli_stmt_send_long_data
  • mysqli::set_opt — Alias of mysqli_options
  • mysqli_slave_query — Force execution of a query on a slave in a master/slave setup


Alias for mysqli_stmt_bind_param

  • « Aliases and deprecated Mysqli Functions
  • mysqli_bind_result »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Alias for mysqli_stmt_bind_param

mysqli_bind_param

(PHP 5 < 5.4.0)

mysqli_bind_param — Alias for mysqli_stmt_bind_param()

Description

This function is an alias of: mysqli_stmt_bind_param().

Warning

This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

See Also

  • mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters


Alias for mysqli_stmt_bind_result

  • « mysqli_bind_param
  • mysqli_client_encoding »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Alias for mysqli_stmt_bind_result

mysqli_bind_result

(PHP 5 < 5.4.0)

mysqli_bind_result — Alias for mysqli_stmt_bind_result()

Description

This function is an alias of: mysqli_stmt_bind_result().

Warning

This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

See Also

  • mysqli_stmt_bind_result() - Binds variables to a prepared statement for result storage


Alias of mysqli_character_set_name

  • « mysqli_bind_result
  • mysqli_connect »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Alias of mysqli_character_set_name

mysqli_client_encoding

(PHP 5 < 5.4.0)

mysqli_client_encoding — Alias of mysqli_character_set_name()

Description

This function is an alias of: mysqli_character_set_name().

Warning

This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

See Also

  • 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


Alias of mysqli::__construct

  • « mysqli_client_encoding
  • mysqli::disable_reads_from_master »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Alias of mysqli::__construct

mysqli_connect

(PHP 5, PHP 7)

mysqli_connect — Alias of mysqli::__construct()

Description

This function is an alias of: mysqli::__construct()

Although the mysqli::__construct() documentation also includes procedural examples that use the mysqli_connect() function, here is a short example:

Examples

Example #1 mysqli_connect() example

<?php
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");

if (!$link) {
    echo "Error: Unable to connect to MySQL." . PHP_EOL;
    echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
    echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
    exit;
}

echo "Success: A proper connection to MySQL was made! The my_db database is great." . PHP_EOL;
echo "Host information: " . mysqli_get_host_info($link) . PHP_EOL;

mysqli_close($link);
?>

The above examples will output something similar to:

Success: A proper connection to MySQL was made! The my_db database is great.
Host information: localhost via TCP/IP


Disable reads from master

  • « mysqli_connect
  • mysqli_disable_rpl_parse »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Disable reads from master

mysqli::disable_reads_from_master

mysqli_disable_reads_from_master

(PHP 5 < 5.3.0)

mysqli::disable_reads_from_master -- mysqli_disable_reads_from_master — Disable reads from master

Description

Object oriented style

mysqli::disable_reads_from_master ( void ) : void

Procedural style

mysqli_disable_reads_from_master ( mysqli $link ) : bool
Warning

This function is currently not documented; only its argument list is available.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.3.0.


Disable RPL parse

  • « mysqli::disable_reads_from_master
  • mysqli_enable_reads_from_master »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Disable RPL parse

mysqli_disable_rpl_parse

(PHP 5 < 5.3.0)

mysqli_disable_rpl_parse — Disable RPL parse

Description

mysqli_disable_rpl_parse ( mysqli $link ) : bool
Warning

This function is currently not documented; only its argument list is available.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.3.0.


Enable reads from master

  • « mysqli_disable_rpl_parse
  • mysqli_enable_rpl_parse »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Enable reads from master

mysqli_enable_reads_from_master

(PHP 5 < 5.3.0)

mysqli_enable_reads_from_master — Enable reads from master

Description

mysqli_enable_reads_from_master ( mysqli $link ) : bool
Warning

This function is currently not documented; only its argument list is available.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.3.0.


Enable RPL parse

  • « mysqli_enable_reads_from_master
  • mysqli_escape_string »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Enable RPL parse

mysqli_enable_rpl_parse

(PHP 5 < 5.3.0)

mysqli_enable_rpl_parse — Enable RPL parse

Description

mysqli_enable_rpl_parse ( mysqli $link ) : bool
Warning

This function is currently not documented; only its argument list is available.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.3.0.


Alias of mysqli_real_escape_string

  • « mysqli_enable_rpl_parse
  • mysqli_execute »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Alias of mysqli_real_escape_string

mysqli_escape_string

(PHP 5, PHP 7)

mysqli_escape_string — Alias of mysqli_real_escape_string()

Description

This function is an alias of: mysqli_real_escape_string().


Alias for mysqli_stmt_execute

  • « mysqli_escape_string
  • mysqli_fetch »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Alias for mysqli_stmt_execute

mysqli_execute

(PHP 5, PHP 7)

mysqli_execute — Alias for 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 Query


Alias for mysqli_stmt_fetch

  • « mysqli_execute
  • mysqli_get_cache_stats »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Alias for mysqli_stmt_fetch

mysqli_fetch

(PHP 5 < 5.4.0)

mysqli_fetch — Alias for mysqli_stmt_fetch()

Description

This function is an alias of: mysqli_stmt_fetch().

Warning

This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

See Also

  • mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables


Returns client Zval cache statistics

  • « mysqli_fetch
  • mysqli_get_client_stats »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Returns client Zval cache statistics

mysqli_get_cache_stats

(PHP 5 >= 5.3.0 and < 5.4.0)

mysqli_get_cache_stats — Returns client Zval cache statistics

Warning

This function has been REMOVED as of PHP 5.4.0.

Description

mysqli_get_cache_stats ( void ) : array

Returns an empty array. Available only with mysqlnd.

Parameters

Return Values

Returns an empty array on success, FALSE otherwise.

Changelog

Version | Description
5.4.0 | The mysqli_get_cache_stats() was removed.
5.3.0 | The mysqli_get_cache_stats() was added as stub.


Returns client per-process statistics

  • « mysqli_get_cache_stats
  • mysqli_get_links_stats »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Returns client per-process statistics

mysqli_get_client_stats

(PHP 5 >= 5.3.0, PHP 7)

mysqli_get_client_stats — Returns client per-process statistics

Description

mysqli_get_client_stats ( void ) : array

Returns client per-process statistics. Available only with mysqlnd.

Parameters

Return Values

Returns an array with client stats if success, FALSE otherwise.

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


Return information about open and cached links

  • « mysqli_get_client_stats
  • mysqli_get_metadata »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Return information about open and cached links

mysqli_get_links_stats

(PHP 5 >= 5.6.0, PHP 7)

mysqli_get_links_stats — Return information about open and cached links

Description

mysqli_get_links_stats ( void ) : 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 integer indicating the total number of open links in any state.

active_plinks

An integer representing the number of active persistent connections.

cached_plinks

An integer representing the number of inactive persistent connections.


Alias for mysqli_stmt_result_metadata

  • « mysqli_get_links_stats
  • mysqli_master_query »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Alias for mysqli_stmt_result_metadata

mysqli_get_metadata

(PHP 5 < 5.4.0)

mysqli_get_metadata — Alias for mysqli_stmt_result_metadata()

Description

This function is an alias of: mysqli_stmt_result_metadata().

Warning

This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

See Also

  • mysqli_stmt_result_metadata() - Returns result set metadata from a prepared statement


Enforce execution of a query on the master in a master/slave setup

  • « mysqli_get_metadata
  • mysqli_param_count »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Enforce execution of a query on the master in a master/slave setup

mysqli_master_query

(PHP 5 < 5.3.0)

mysqli_master_query — Enforce execution of a query on the master in a master/slave setup

Description

mysqli_master_query ( mysqli $link , string $query ) : bool
Warning

This function is currently not documented; only its argument list is available.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.3.0.


Alias for mysqli_stmt_param_count

  • « mysqli_master_query
  • mysqli_report »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Alias for mysqli_stmt_param_count

mysqli_param_count

(PHP 5 < 5.4.0)

mysqli_param_count — Alias for mysqli_stmt_param_count()

Description

This function is an alias of: mysqli_stmt_param_count().

Warning

This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

See Also

  • mysqli_stmt_param_count() - Returns the number of parameter for the given statement


Alias of mysqli_driver->report_mode

  • « mysqli_param_count
  • mysqli_rpl_parse_enabled »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Alias of mysqli_driver->report_mode

mysqli_report

(PHP 5, PHP 7)

mysqli_report — Alias of mysqli_driver->report_mode

Description

This function is an alias of: mysqli_driver->report_mode


Check if RPL parse is enabled

  • « mysqli_report
  • mysqli_rpl_probe »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Check if RPL parse is enabled

mysqli_rpl_parse_enabled

(PHP 5 < 5.3.0)

mysqli_rpl_parse_enabled — Check if RPL parse is enabled

Description

mysqli_rpl_parse_enabled ( mysqli $link ) : int
Warning

This function is currently not documented; only its argument list is available.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.3.0.


RPL probe

  • « mysqli_rpl_parse_enabled
  • mysqli_send_long_data »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • RPL probe

mysqli_rpl_probe

(PHP 5 < 5.3.0)

mysqli_rpl_probe — RPL probe

Description

mysqli_rpl_probe ( mysqli $link ) : bool
Warning

This function is currently not documented; only its argument list is available.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.3.0.


Alias for mysqli_stmt_send_long_data

  • « mysqli_rpl_probe
  • mysqli::set_opt »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Alias for mysqli_stmt_send_long_data

mysqli_send_long_data

(PHP 5 < 5.4.0)

mysqli_send_long_data — Alias for mysqli_stmt_send_long_data()

Description

This function is an alias of: mysqli_stmt_send_long_data().

Warning

This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

See Also

  • mysqli_stmt_send_long_data() - Send data in blocks


Alias of mysqli_options

  • « mysqli_send_long_data
  • mysqli_slave_query »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Alias of mysqli_options

mysqli::set_opt

mysqli_set_opt

(PHP 5, PHP 7)

mysqli::set_opt -- mysqli_set_opt — Alias of mysqli_options()

Description

This function is an alias of: mysqli_options().


Force execution of a query on a slave in a master/slave setup

  • « mysqli::set_opt
  • Changelog »
  • PHP Manual
  • Aliases and deprecated Mysqli Functions
  • Force execution of a query on a slave in a master/slave setup

mysqli_slave_query

(PHP 5 < 5.3.0)

mysqli_slave_query — Force execution of a query on a slave in a master/slave setup

Description

mysqli_slave_query ( mysqli $link , string $query ) : bool
Warning

This function is currently not documented; only its argument list is available.

Warning

This function has been DEPRECATED and REMOVED as of PHP 5.3.0.


Changelog

The following changes have been made to classes/functions/methods of this extension.

Version | Function | Description
5.6.16 | mysqli::real_connect | Added the MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT flag for MySQL Native Driver
5.5.0 | mysqli::commit | Added flags and name parameters.
 | mysqli::options | The MYSQLI_SERVER_PUBLIC_KEY and MYSQLI_SERVER_PUBLIC_KEY options were added.
 | mysqli::rollback | Added flags and name parameters.
5.4.0 | mysqli_get_cache_stats | The mysqli_get_cache_stats was removed.
5.3.4 | mysqli_driver::$report_mode | Changing the reporting mode is now be per-request, rather than per-process.
5.3.0 | mysqli_get_cache_stats | The mysqli_get_cache_stats was added as stub.
 | mysqli::__construct | Added the ability of persistent connections.
 | mysqli::options | The MYSQLI_OPT_INT_AND_FLOAT_NATIVE, MYSQLI_OPT_NET_CMD_BUFFER_SIZE, MYSQLI_OPT_NET_READ_BUFFER_SIZE, and MYSQLI_OPT_SSL_VERIFY_SERVER_CERT options were added.
 | mysqli::query | Added the ability of async queries.
5.2.15 | mysqli_driver::$report_mode | Changing the reporting mode is now be per-request, rather than per-process.


Mysql_xdevapi

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Building / Compiling From Source
  • Predefined Constants
  • 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 — 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 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 — Execute 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


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

// 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 | PHP_INI_SYSTEM |
xmysqlnd.collect_statistics | 1 | PHP_INI_ALL |
xmysqlnd.debug |  | PHP_INI_SYSTEM |
xmysqlnd.mempool_default_size | 16000 | PHP_INI_ALL |
xmysqlnd.net_read_timeout | 31536000 | PHP_INI_SYSTEM |
xmysqlnd.trace_alloc |  | PHP_INI_SYSTEM |

Here's a short explanation of the configuration directives.

xmysqlnd.collect_memory_statistics integer

xmysqlnd.collect_statistics integer

xmysqlnd.debug string

xmysqlnd.mempool_default_size integer

xmysqlnd.net_read_timeout integer

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 either » the original SDK (older, PHP-7.1 only) or » the current SDK (PHP-7.1 or newer).

    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 (integer)
MYSQLX_TYPE_DECIMAL (integer)
MYSQLX_TYPE_TINY (integer)
MYSQLX_TYPE_SHORT (integer)
MYSQLX_TYPE_SMALLINT (integer)
MYSQLX_TYPE_MEDIUMINT (integer)
MYSQLX_TYPE_INT (integer)
MYSQLX_TYPE_BIGINT (integer)
MYSQLX_TYPE_LONG (integer)
MYSQLX_TYPE_FLOAT (integer)
MYSQLX_TYPE_DOUBLE (integer)
MYSQLX_TYPE_NULL (integer)
MYSQLX_TYPE_TIMESTAMP (integer)
MYSQLX_TYPE_LONGLONG (integer)
MYSQLX_TYPE_INT24 (integer)
MYSQLX_TYPE_DATE (integer)
MYSQLX_TYPE_TIME (integer)
MYSQLX_TYPE_DATETIME (integer)
MYSQLX_TYPE_YEAR (integer)
MYSQLX_TYPE_NEWDATE (integer)
MYSQLX_TYPE_ENUM (integer)
MYSQLX_TYPE_SET (integer)
MYSQLX_TYPE_TINY_BLOB (integer)
MYSQLX_TYPE_MEDIUM_BLOB (integer)
MYSQLX_TYPE_LONG_BLOB (integer)
MYSQLX_TYPE_BLOB (integer)
MYSQLX_TYPE_VAR_STRING (integer)
MYSQLX_TYPE_STRING (integer)
MYSQLX_TYPE_CHAR (integer)
MYSQLX_TYPE_BYTES (integer)
MYSQLX_TYPE_INTERVAL (integer)
MYSQLX_TYPE_GEOMETRY (integer)
MYSQLX_TYPE_JSON (integer)
MYSQLX_TYPE_NEWDECIMAL (integer)
MYSQLX_TYPE_BIT (integer)
MYSQLX_LOCK_DEFAULT (integer)
MYSQLX_LOCK_NOWAIT (integer)
MYSQLX_LOCK_SKIP_LOCKED (integer)


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_xdevap\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 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

Table of Contents

  • expression — Bind prepared statement variables as parameters
  • getSession — Connect to a MySQL server


Bind prepared statement variables as parameters

  • « Mysql_xdevapi Functions
  • getSession »
  • PHP Manual
  • Mysql_xdevapi Functions
  • Bind prepared statement variables as parameters

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


Connect to a MySQL server

  • « expression
  • mysql_xdevapi\BaseResult »
  • PHP Manual
  • Mysql_xdevapi Functions
  • Connect to a MySQL server

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.

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

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


BaseResult interface

(PECL mysql-xdevapi >= 8.0.11)

Introduction

Class synopsis

mysql_xdevapi\BaseResult {
/* Methods */
abstract public getWarnings ( void ) : array
abstract public getWarningsCount ( void ) : integer
}

Table of Contents

  • BaseResult::getWarnings — Fetch warnings from last operation
  • BaseResult::getWarningsCount — Fetch warning count from last operation


Fetch warnings from last operation

  • « mysql_xdevapi\BaseResult
  • BaseResult::getWarningsCount »
  • PHP Manual
  • mysql_xdevapi\BaseResult
  • Fetch warnings from last operation

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 ( void ) : 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
        )
)


Fetch warning count from last operation

  • « BaseResult::getWarnings
  • mysql_xdevapi\Client »
  • PHP Manual
  • mysql_xdevapi\BaseResult
  • Fetch warning count from last operation

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 ( void ) : integer

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


Client class

(No version information available, might only be in Git)

Introduction

Provides access to the connection pool.

Class synopsis

mysql_xdevapi\Client {
/* Methods */
public close ( void ) : bool
public getSession ( void ) : mysql_xdevapi\Session
}

Table of Contents

  • mysql_xdevapi\Client::close — Close client
  • Client::__construct — Client constructor
  • Client::getClient — Get client session


Close client

  • « mysql_xdevapi\Client
  • Client::__construct »
  • PHP Manual
  • mysql_xdevapi\Client
  • Close client

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 ( void ) : bool

Close all client connections with the server.

Parameters

This function has no parameters.

Return Values

TRUE if connections are closed.


Client constructor

  • « mysql_xdevapi\Client::close
  • Client::getClient »
  • PHP Manual
  • mysql_xdevapi\Client
  • Client constructor

Client::__construct

(No version information available, might only be in Git)

Client::__construct — Client constructor

Description

private mysql_xdevapi\Client::__construct ( void )

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


Get client session

  • « Client::__construct
  • mysql_xdevapi\Collection »
  • PHP Manual
  • mysql_xdevapi\Client
  • Get client session

Client::getClient

(No version information available, might only be in Git)

Client::getClient — Get client session

Description

public mysql_xdevapi\Client::getSession ( void ) : mysql_xdevapi\Session

Get session associated with the client.

Parameters

This function has no parameters.

Return Values

A Session object.


Collection class

(PECL mysql-xdevapi >= 8.0.11)

Introduction

Class synopsis

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 ( void ) : integer
public createIndex ( string $index_name , string $index_desc_json ) : void
public dropIndex ( string $index_name ) : bool
public existsInDatabase ( void ) : bool
public find ([ string $search_condition ] ) : mysql_xdevapi\CollectionFind
public getName ( void ) : string
public getOne ( string $id ) : Document
public getSchema ( void ) : Schema Object
public getSession ( void ) : 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

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


Add collection document

  • « mysql_xdevapi\Collection
  • Collection::addOrReplaceOne »
  • PHP Manual
  • mysql_xdevapi\Collection
  • Add collection document

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.


Add or replace collection document

  • « Collection::add
  • Collection::__construct »
  • PHP Manual
  • mysql_xdevapi\Collection
  • Add or replace collection document

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 constructor

  • « Collection::addOrReplaceOne
  • Collection::count »
  • PHP Manual
  • mysql_xdevapi\Collection
  • Collection constructor

Collection::__construct

(No version information available, might only be in Git)

Collection::__construct — Collection constructor

Description

private mysql_xdevapi\Collection::__construct ( void )

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
)


Get document count

  • « Collection::__construct
  • Collection::createIndex »
  • PHP Manual
  • mysql_xdevapi\Collection
  • Get document count

Collection::count

(No version information available, might only be in Git)

Collection::count — Get document count

Description

public mysql_xdevapi\Collection::count ( void ) : integer

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)


Create collection index

  • « Collection::count
  • Collection::dropIndex »
  • PHP Manual
  • mysql_xdevapi\Collection
  • Create collection index

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
  }'
);


Drop collection index

  • « Collection::createIndex
  • Collection::existsInDatabase »
  • PHP Manual
  • mysql_xdevapi\Collection
  • Drop collection index

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.


Check if collection exists in database

  • « Collection::dropIndex
  • Collection::find »
  • PHP Manual
  • mysql_xdevapi\Collection
  • Check if collection exists in database

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

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


Search for document

  • « Collection::existsInDatabase
  • Collection::getName »
  • PHP Manual
  • mysql_xdevapi\Collection
  • Search for document

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


Get collection name

  • « Collection::find
  • Collection::getOne »
  • PHP Manual
  • mysql_xdevapi\Collection
  • Get collection name

Collection::getName

(No version information available, might only be in Git)

Collection::getName — Get collection name

Description

public mysql_xdevapi\Collection::getName ( void ) : 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"


Get one document

  • « Collection::getName
  • Collection::getSchema »
  • PHP Manual
  • mysql_xdevapi\Collection
  • Get one document

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
)


Get schema object

  • « Collection::getOne
  • Collection::getSession »
  • PHP Manual
  • mysql_xdevapi\Collection
  • Get schema object

Collection::getSchema

(No version information available, might only be in Git)

Collection::getSchema — Get schema object

Description

public mysql_xdevapi\Collection::getSchema ( void ) : 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"
}


Get session object

  • « Collection::getSchema
  • Collection::modify »
  • PHP Manual
  • mysql_xdevapi\Collection
  • Get session object

Collection::getSession

(No version information available, might only be in Git)

Collection::getSession — Get session object

Description

public mysql_xdevapi\Collection::getSession ( void ) : 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) {
}


Modify collection documents

  • « Collection::getSession
  • Collection::remove »
  • PHP Manual
  • mysql_xdevapi\Collection
  • Modify collection documents

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 collections 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();
?>


Remove collection documents

  • « Collection::modify
  • Collection::removeOne »
  • PHP Manual
  • mysql_xdevapi\Collection
  • Remove collection documents

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

Remove collections 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 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 lowest age
$collection
  ->remove('true')
  ->sort('age desc')
  ->limit(1)
  ->execute();
?>


Remove one collection document

  • « Collection::remove
  • Collection::replaceOne »
  • PHP Manual
  • mysql_xdevapi\Collection
  • Remove one collection document

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


Replace one collection document

  • « Collection::removeOne
  • mysql_xdevapi\CollectionAdd »
  • PHP Manual
  • mysql_xdevapi\Collection
  • Replace one collection document

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

?>


CollectionAdd class

(PECL mysql-xdevapi >= 8.0.11)

Introduction

Class synopsis

mysql_xdevapi\CollectionAdd implements mysql_xdevapi\Executable {
/* Methods */
public execute ( void ) : mysql_xdevapi\Result
}

Table of Contents

  • CollectionAdd::__construct — CollectionAdd constructor
  • CollectionAdd::execute — Execute the statement


CollectionAdd constructor

  • « mysql_xdevapi\CollectionAdd
  • CollectionAdd::execute »
  • PHP Manual
  • mysql_xdevapi\CollectionAdd
  • CollectionAdd constructor

CollectionAdd::__construct

(No version information available, might only be in Git)

CollectionAdd::__construct — CollectionAdd constructor

Description

private mysql_xdevapi\CollectionAdd::__construct ( void )

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.


Execute the statement

  • « CollectionAdd::__construct
  • mysql_xdevapi\CollectionFind »
  • PHP Manual
  • mysql_xdevapi\CollectionAdd
  • Execute the statement

CollectionAdd::execute

(No version information available, might only be in Git)

CollectionAdd::execute — Execute the statement

Description

public mysql_xdevapi\CollectionAdd::execute ( void ) : 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
)


CollectionFind class

(PECL mysql-xdevapi >= 8.0.11)

Introduction

Class synopsis

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 ( void ) : 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 ( integer $rows ) : mysql_xdevapi\CollectionFind
public lockExclusive ([ integer $lock_waiting_option ] ) : mysql_xdevapi\CollectionFind
public lockShared ([ integer $lock_waiting_option ] ) : mysql_xdevapi\CollectionFind
public offset ( integer $position ) : mysql_xdevapi\CollectionFind
public sort ( string $sort_expr ) : mysql_xdevapi\CollectionFind
}

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


Bind value to query placeholder

  • « mysql_xdevapi\CollectionFind
  • CollectionFind::__construct »
  • PHP Manual
  • mysql_xdevapi\CollectionFind
  • Bind value to query placeholder

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 constructor

  • « CollectionFind::bind
  • CollectionFind::execute »
  • PHP Manual
  • mysql_xdevapi\CollectionFind
  • CollectionFind constructor

CollectionFind::__construct

(No version information available, might only be in Git)

CollectionFind::__construct — CollectionFind constructor

Description

private mysql_xdevapi\CollectionFind::__construct ( void )

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


Execute the statement

  • « CollectionFind::__construct
  • CollectionFind::fields »
  • PHP Manual
  • mysql_xdevapi\CollectionFind
  • Execute the statement

CollectionFind::execute

(No version information available, might only be in Git)

CollectionFind::execute — Execute the statement

Description

public mysql_xdevapi\CollectionFind::execute ( void ) : mysql_xdevapi\DocResult

Execute the find operation; this functionality allows for method chaining.

Parameters

This function has no parameters.

Return Values

A DocResult object that 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"
  }
}


Set document field filter

  • « CollectionFind::execute
  • CollectionFind::groupBy »
  • PHP Manual
  • mysql_xdevapi\CollectionFind
  • Set document field filter

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

Defined the columns for the query to return. If not defined then all columns are used.

Parameters

projection

Can either be a single string or an array of string, those strings are identifying the columns that have 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"
  }
}


Set grouping criteria

  • « CollectionFind::fields
  • CollectionFind::having »
  • PHP Manual
  • mysql_xdevapi\CollectionFind
  • Set grouping criteria

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 more columns, frequently this is used with aggregate functions like COUNT,MAX,MIN,SUM etc.

Parameters

sort_expr

The columns 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 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();

?>


Set condition for aggregate functions

  • « CollectionFind::groupBy
  • CollectionFind::limit »
  • PHP Manual
  • mysql_xdevapi\CollectionFind
  • Set condition for aggregate functions

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

?>


Limit number of returned documents

  • « CollectionFind::having
  • CollectionFind::lockExclusive »
  • PHP Manual
  • mysql_xdevapi\CollectionFind
  • Limit number of returned documents

CollectionFind::limit

(No version information available, might only be in Git)

CollectionFind::limit — Limit number of returned documents

Description

public mysql_xdevapi\CollectionFind::limit ( integer $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"
  }
}


Execute operation with EXCLUSIVE LOCK

  • « CollectionFind::limit
  • CollectionFind::lockShared »
  • PHP Manual
  • mysql_xdevapi\CollectionFind
  • Execute operation with EXCLUSIVE LOCK

CollectionFind::lockExclusive

(No version information available, might only be in Git)

CollectionFind::lockExclusive — Execute operation with EXCLUSIVE LOCK

Description

public mysql_xdevapi\CollectionFind::lockExclusive ([ integer $lock_waiting_option ] ) : mysql_xdevapi\CollectionFind

Lock exclusively the document, other transactions are blocked from updating the document until the document is locked While the document is locked, other transactions are blocked from updating those docs, from doing SELECT ... LOCK IN SHARE MODE, or from reading the data in certain transaction isolation levels. Consistent reads ignore any locks set on the records that exist in the read view.

This feature is directly useful with the modify() command, to avoid concurrency problems. Basically, it serializes access to a row through row locking

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();
?>


Execute operation with SHARED LOCK

  • « CollectionFind::lockExclusive
  • CollectionFind::offset »
  • PHP Manual
  • mysql_xdevapi\CollectionFind
  • Execute operation with SHARED LOCK

CollectionFind::lockShared

(No version information available, might only be in Git)

CollectionFind::lockShared — Execute operation with SHARED LOCK

Description

public mysql_xdevapi\CollectionFind::lockShared ([ integer $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 has not yet committed,

your query waits until that transaction ends and then uses 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();
?>


Skip given number of elements to be returned

  • « CollectionFind::lockShared
  • CollectionFind::sort »
  • PHP Manual
  • mysql_xdevapi\CollectionFind
  • Skip given number of elements to be returned

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 ( integer $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"
  }
}


Set the sorting criteria

  • « CollectionFind::offset
  • mysql_xdevapi\CollectionModify »
  • PHP Manual
  • mysql_xdevapi\CollectionFind
  • Set the sorting criteria

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


CollectionModify class

(PECL mysql-xdevapi >= 8.0.11)

Introduction

Class synopsis

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 ( void ) : mysql_xdevapi\Result
public limit ( integer $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 ( integer $position ) : mysql_xdevapi\CollectionModify
public sort ( string $sort_expr ) : mysql_xdevapi\CollectionModify
public unset ( array $fields ) : mysql_xdevapi\CollectionModify
}

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


Append element to an array field

  • « mysql_xdevapi\CollectionModify
  • CollectionModify::arrayInsert »
  • PHP Manual
  • mysql_xdevapi\CollectionModify
  • Append element to an array field

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


Insert element into an array field

  • « CollectionModify::arrayAppend
  • CollectionModify::bind »
  • PHP Manual
  • mysql_xdevapi\CollectionModify
  • Insert element into an array field

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

Add an element to a document's field, as multiple elements of a field are represented as an array. Unlike arrayAppend(), arrayInsert() allows you to specify where the new element is inserted by defining which item it is after, whereas arrayAppend() always appends the new element at the end of the array.

Parameters

collection_field

Identify the item in the array that the new element is inserted after. The format of this parameter is FIELD_NAME[ INDEX ] where FIELD_NAME is the name of the document field to remove the element from, and INDEX is the INDEX of the element within the field.

The INDEX field is zero based, so the leftmost item from 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
                )
        )
)


Bind value to query placeholder

  • « CollectionModify::arrayInsert
  • CollectionModify::__construct »
  • PHP Manual
  • mysql_xdevapi\CollectionModify
  • Bind value to query placeholder

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 constructor

  • « CollectionModify::bind
  • CollectionModify::execute »
  • PHP Manual
  • mysql_xdevapi\CollectionModify
  • CollectionModify constructor

CollectionModify::__construct

(No version information available, might only be in Git)

CollectionModify::__construct — CollectionModify constructor

Description

private mysql_xdevapi\CollectionModify::__construct ( void )

Modify (update) a collection, and is instantiated by the 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
                )
        )
)


Execute modify operation

  • « CollectionModify::__construct
  • CollectionModify::limit »
  • PHP Manual
  • mysql_xdevapi\CollectionModify
  • Execute modify operation

CollectionModify::execute

(No version information available, might only be in Git)

CollectionModify::execute — Execute modify operation

Description

public mysql_xdevapi\CollectionModify::execute ( void ) : 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

/* ... */

?>


Limit number of modified documents

  • « CollectionModify::execute
  • CollectionModify::patch »
  • PHP Manual
  • mysql_xdevapi\CollectionModify
  • Limit number of modified documents

CollectionModify::limit

(No version information available, might only be in Git)

CollectionModify::limit — Limit number of modified documents

Description

public mysql_xdevapi\CollectionModify::limit ( integer $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
        )
)


Patch document

  • « CollectionModify::limit
  • CollectionModify::replace »
  • PHP Manual
  • mysql_xdevapi\CollectionModify
  • Patch document

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.

Warning

This function is currently not documented; only its argument list is available.

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

?>


Replace document field

  • « CollectionModify::patch
  • CollectionModify::set »
  • PHP Manual
  • mysql_xdevapi\CollectionModify
  • Replace document field

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


Set document attribute

  • « CollectionModify::replace
  • CollectionModify::skip »
  • PHP Manual
  • mysql_xdevapi\CollectionModify
  • Set document attribute

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


Skip elements

  • « CollectionModify::set
  • CollectionModify::sort »
  • PHP Manual
  • mysql_xdevapi\CollectionModify
  • Skip elements

CollectionModify::skip

(No version information available, might only be in Git)

CollectionModify::skip — Skip elements

Description

public mysql_xdevapi\CollectionModify::skip ( integer $position ) : mysql_xdevapi\CollectionModify

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

Warning

This function is currently not documented; only its argument list is available.

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

?>


Set the sorting criteria

  • « CollectionModify::skip
  • CollectionModify::unset »
  • PHP Manual
  • mysql_xdevapi\CollectionModify
  • Set the sorting criteria

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

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 expression can be provided, the evaluation of these will be from the leftmost to the rightmost, 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();

?>


Unset the value of document fields

  • « CollectionModify::sort
  • mysql_xdevapi\CollectionRemove »
  • PHP Manual
  • mysql_xdevapi\CollectionModify
  • Unset the value of document fields

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.

Warning

This function is currently not documented; only its argument list is available.

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

?>


CollectionRemove class

(PECL mysql-xdevapi >= 8.0.11)

Introduction

Class synopsis

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 ( void ) : mysql_xdevapi\Result
public limit ( integer $rows ) : mysql_xdevapi\CollectionRemove
public sort ( string $sort_expr ) : mysql_xdevapi\CollectionRemove
}

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


Bind value to placeholder

  • « mysql_xdevapi\CollectionRemove
  • CollectionRemove::__construct »
  • PHP Manual
  • mysql_xdevapi\CollectionRemove
  • Bind value to placeholder

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 constructor

  • « CollectionRemove::bind
  • CollectionRemove::execute »
  • PHP Manual
  • mysql_xdevapi\CollectionRemove
  • CollectionRemove constructor

CollectionRemove::__construct

(No version information available, might only be in Git)

CollectionRemove::__construct — CollectionRemove constructor

Description

private mysql_xdevapi\CollectionRemove::__construct ( void )

Remove collection documents, and is instantiated by the 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();
?>


Execute remove operation

  • « CollectionRemove::__construct
  • CollectionRemove::limit »
  • PHP Manual
  • mysql_xdevapi\CollectionRemove
  • Execute remove operation

CollectionRemove::execute

(No version information available, might only be in Git)

CollectionRemove::execute — Execute remove operation

Description

public mysql_xdevapi\CollectionRemove::execute ( void ) : 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();

?>


Limit number of documents to remove

  • « CollectionRemove::execute
  • CollectionRemove::sort »
  • PHP Manual
  • mysql_xdevapi\CollectionRemove
  • Limit number of documents to remove

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 ( integer $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();

?>


Set the sorting criteria

  • « CollectionRemove::limit
  • mysql_xdevapi\ColumnResult »
  • PHP Manual
  • mysql_xdevapi\CollectionRemove
  • Set the sorting criteria

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

?>


ColumnResult class

(PECL mysql-xdevapi >= 8.0.11)

Introduction

Class synopsis

mysql_xdevapi\ColumnResult {
/* Methods */
public getCharacterSetName ( void ) : string
public getCollationName ( void ) : string
public getColumnLabel ( void ) : string
public getColumnName ( void ) : string
public getFractionalDigits ( void ) : integer
public getLength ( void ) : integer
public getSchemaName ( void ) : string
public getTableLabel ( void ) : string
public getTableName ( void ) : string
public getType ( void ) : integer
public isNumberSigned ( void ) : integer
public isPadded ( void ) : integer
}

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


ColumnResult constructor

  • « mysql_xdevapi\ColumnResult
  • ColumnResult::getCharacterSetName »
  • PHP Manual
  • mysql_xdevapi\ColumnResult
  • ColumnResult constructor

ColumnResult::__construct

(No version information available, might only be in Git)

ColumnResult::__construct — ColumnResult constructor

Description

private mysql_xdevapi\ColumnResult::__construct ( void )

Retrieve column metadata, such as its character set; this is instantiated by the 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
        )
)


Get character set

  • « ColumnResult::__construct
  • ColumnResult::getCollationName »
  • PHP Manual
  • mysql_xdevapi\ColumnResult
  • Get character set

ColumnResult::getCharacterSetName

(No version information available, might only be in Git)

ColumnResult::getCharacterSetName — Get character set

Description

public mysql_xdevapi\ColumnResult::getCharacterSetName ( void ) : 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

/* ... */

?>


Get collation name

  • « ColumnResult::getCharacterSetName
  • ColumnResult::getColumnLabel »
  • PHP Manual
  • mysql_xdevapi\ColumnResult
  • Get collation name

ColumnResult::getCollationName

(No version information available, might only be in Git)

ColumnResult::getCollationName — Get collation name

Description

public mysql_xdevapi\ColumnResult::getCollationName ( void ) : 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

/* ... */

?>


Get column label

  • « ColumnResult::getCollationName
  • ColumnResult::getColumnName »
  • PHP Manual
  • mysql_xdevapi\ColumnResult
  • Get column label

ColumnResult::getColumnLabel

(No version information available, might only be in Git)

ColumnResult::getColumnLabel — Get column label

Description

public mysql_xdevapi\ColumnResult::getColumnLabel ( void ) : 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

/* ... */

?>


Get column name

  • « ColumnResult::getColumnLabel
  • ColumnResult::getFractionalDigits »
  • PHP Manual
  • mysql_xdevapi\ColumnResult
  • Get column name

ColumnResult::getColumnName

(No version information available, might only be in Git)

ColumnResult::getColumnName — Get column name

Description

public mysql_xdevapi\ColumnResult::getColumnName ( void ) : 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

/* ... */

?>


Get fractional digit length

  • « ColumnResult::getColumnName
  • ColumnResult::getLength »
  • PHP Manual
  • mysql_xdevapi\ColumnResult
  • Get fractional digit length

ColumnResult::getFractionalDigits

(No version information available, might only be in Git)

ColumnResult::getFractionalDigits — Get fractional digit length

Description

public mysql_xdevapi\ColumnResult::getFractionalDigits ( void ) : integer

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

/* ... */

?>


Get column field length

  • « ColumnResult::getFractionalDigits
  • ColumnResult::getSchemaName »
  • PHP Manual
  • mysql_xdevapi\ColumnResult
  • Get column field length

ColumnResult::getLength

(No version information available, might only be in Git)

ColumnResult::getLength — Get column field length

Description

public mysql_xdevapi\ColumnResult::getLength ( void ) : integer

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

/* ... */

?>


Get schema name

  • « ColumnResult::getLength
  • ColumnResult::getTableLabel »
  • PHP Manual
  • mysql_xdevapi\ColumnResult
  • Get schema name

ColumnResult::getSchemaName

(No version information available, might only be in Git)

ColumnResult::getSchemaName — Get schema name

Description

public mysql_xdevapi\ColumnResult::getSchemaName ( void ) : 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

/* ... */

?>


Get table label

  • « ColumnResult::getSchemaName
  • ColumnResult::getTableName »
  • PHP Manual
  • mysql_xdevapi\ColumnResult
  • Get table label

ColumnResult::getTableLabel

(No version information available, might only be in Git)

ColumnResult::getTableLabel — Get table label

Description

public mysql_xdevapi\ColumnResult::getTableLabel ( void ) : 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

/* ... */

?>


Get table name

  • « ColumnResult::getTableLabel
  • ColumnResult::getType »
  • PHP Manual
  • mysql_xdevapi\ColumnResult
  • Get table name

ColumnResult::getTableName

(No version information available, might only be in Git)

ColumnResult::getTableName — Get table name

Description

public mysql_xdevapi\ColumnResult::getTableName ( void ) : 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

/* ... */

?>


Get column type

  • « ColumnResult::getTableName
  • ColumnResult::isNumberSigned »
  • PHP Manual
  • mysql_xdevapi\ColumnResult
  • Get column type

ColumnResult::getType

(No version information available, might only be in Git)

ColumnResult::getType — Get column type

Description

public mysql_xdevapi\ColumnResult::getType ( void ) : integer

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

/* ... */

?>


Check if signed type

  • « ColumnResult::getType
  • ColumnResult::isPadded »
  • PHP Manual
  • mysql_xdevapi\ColumnResult
  • Check if signed type

ColumnResult::isNumberSigned

(No version information available, might only be in Git)

ColumnResult::isNumberSigned — Check if signed type

Description

public mysql_xdevapi\ColumnResult::isNumberSigned ( void ) : integer

Retrieve a table's column information, and is instantiated by the 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

/* ... */

?>


Check if padded

  • « ColumnResult::isNumberSigned
  • mysql_xdevapi\CrudOperationBindable »
  • PHP Manual
  • mysql_xdevapi\ColumnResult
  • Check if padded

ColumnResult::isPadded

(No version information available, might only be in Git)

ColumnResult::isPadded — Check if padded

Description

public mysql_xdevapi\ColumnResult::isPadded ( void ) : integer

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

/* ... */

?>


CrudOperationBindable interface

(PECL mysql-xdevapi >= 8.0.11)

Introduction

Class synopsis

mysql_xdevapi\CrudOperationBindable {
/* Methods */
abstract public bind ( array $placeholder_values ) : mysql_xdevapi\CrudOperationBindable
}

Table of Contents

  • CrudOperationBindable::bind — Bind value to placeholder


Bind value to placeholder

  • « mysql_xdevapi\CrudOperationBindable
  • mysql_xdevapi\CrudOperationLimitable »
  • PHP Manual
  • mysql_xdevapi\CrudOperationBindable
  • Bind value to placeholder

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

?>


CrudOperationLimitable interface

(PECL mysql-xdevapi >= 8.0.11)

Introduction

Class synopsis

mysql_xdevapi\CrudOperationLimitable {
/* Methods */
abstract public limit ( integer $rows ) : mysql_xdevapi\CrudOperationLimitable
}

Table of Contents

  • CrudOperationLimitable::limit — Set result limit


Set result limit

  • « mysql_xdevapi\CrudOperationLimitable
  • mysql_xdevapi\CrudOperationSkippable »
  • PHP Manual
  • mysql_xdevapi\CrudOperationLimitable
  • Set result limit

CrudOperationLimitable::limit

(No version information available, might only be in Git)

CrudOperationLimitable::limit — Set result limit

Description

abstract public mysql_xdevapi\CrudOperationLimitable::limit ( integer $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();

?>


CrudOperationSkippable interface

(PECL mysql-xdevapi >= 8.0.11)

Introduction

Class synopsis

mysql_xdevapi\CrudOperationSkippable {
/* Methods */
abstract public skip ( integer $skip ) : mysql_xdevapi\CrudOperationSkippable
}

Table of Contents

  • CrudOperationSkippable::skip — Number of operations to skip


Number of operations to skip

  • « mysql_xdevapi\CrudOperationSkippable
  • mysql_xdevapi\CrudOperationSortable »
  • PHP Manual
  • mysql_xdevapi\CrudOperationSkippable
  • Number of operations to skip

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 ( integer $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();

?>


CrudOperationSortable interface

(PECL mysql-xdevapi >= 8.0.11)

Introduction

Class synopsis

mysql_xdevapi\CrudOperationSortable {
/* Methods */
abstract public sort ( string $sort_expr ) : mysql_xdevapi\CrudOperationSortable
}

Table of Contents

  • CrudOperationSortable::sort — Sort results


Sort results

  • « mysql_xdevapi\CrudOperationSortable
  • mysql_xdevapi\DatabaseObject »
  • PHP Manual
  • mysql_xdevapi\CrudOperationSortable
  • Sort results

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

?>


DatabaseObject interface

(PECL mysql-xdevapi >= 8.0.11)

Introduction

Class synopsis

mysql_xdevapi\DatabaseObject {
/* Methods */
abstract public existsInDatabase ( void ) : bool
abstract public getName ( void ) : string
abstract public getSession ( void ) : mysql_xdevapi\Session
}

Table of Contents

  • DatabaseObject::existsInDatabase — Check if object exists in database
  • DatabaseObject::getName — Get object name
  • DatabaseObject::getSession — Get session name


Check if object exists in database

  • « mysql_xdevapi\DatabaseObject
  • DatabaseObject::getName »
  • PHP Manual
  • mysql_xdevapi\DatabaseObject
  • Check if object exists in database

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 ( void ) : 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();

?>


Get object name

  • « DatabaseObject::existsInDatabase
  • DatabaseObject::getSession »
  • PHP Manual
  • mysql_xdevapi\DatabaseObject
  • Get object name

DatabaseObject::getName

(No version information available, might only be in Git)

DatabaseObject::getName — Get object name

Description

abstract public mysql_xdevapi\DatabaseObject::getName ( void ) : 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();

?>


Get session name

  • « DatabaseObject::getName
  • mysql_xdevapi\DocResult »
  • PHP Manual
  • mysql_xdevapi\DatabaseObject
  • Get session name

DatabaseObject::getSession

(No version information available, might only be in Git)

DatabaseObject::getSession — Get session name

Description

abstract public mysql_xdevapi\DatabaseObject::getSession ( void ) : 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();

?>


DocResult class

(PECL mysql-xdevapi >= 8.0.11)

Introduction

Class synopsis

mysql_xdevapi\DocResult implements mysql_xdevapi\BaseResult , Traversable {
/* Methods */
public fetchAll ( void ) : array
public fetchOne ( void ) : array
public getWarnings ( void ) : Array
public getWarningsCount ( void ) : integer
}

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


DocResult constructor

  • « mysql_xdevapi\DocResult
  • DocResult::fetchAll »
  • PHP Manual
  • mysql_xdevapi\DocResult
  • DocResult constructor

DocResult::__construct

(No version information available, might only be in Git)

DocResult::__construct — DocResult constructor

Description

private mysql_xdevapi\DocResult::__construct ( void )

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


Get all rows

  • « DocResult::__construct
  • DocResult::fetchOne »
  • PHP Manual
  • mysql_xdevapi\DocResult
  • Get all rows

DocResult::fetchAll

(No version information available, might only be in Git)

DocResult::fetchAll — Get all rows

Description

public mysql_xdevapi\DocResult::fetchAll ( void ) : 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"
  }

}


Get one row

  • « DocResult::fetchAll
  • DocResult::getWarnings »
  • PHP Manual
  • mysql_xdevapi\DocResult
  • Get one row

DocResult::fetchOne

(No version information available, might only be in Git)

DocResult::fetchOne — Get one row

Description

public mysql_xdevapi\DocResult::fetchOne ( void ) : 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"
}


Get warnings from last operation

  • « DocResult::fetchOne
  • DocResult::getWarningsCount »
  • PHP Manual
  • mysql_xdevapi\DocResult
  • Get warnings from last operation

DocResult::getWarnings

(No version information available, might only be in Git)

DocResult::getWarnings — Get warnings from last operation

Description

public mysql_xdevapi\DocResult::getWarnings ( void ) : 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
        )
)


Get warning count from last operation

  • « DocResult::getWarnings
  • mysql_xdevapi\Exception »
  • PHP Manual
  • mysql_xdevapi\DocResult
  • Get warning count from last operation

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 ( void ) : integer

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


Exception class

(PECL mysql-xdevapi >= 8.0.11)

Introduction

Class synopsis

mysql_xdevapi\Exception extends RuntimeException implements Throwable {
}


Executable interface

(PECL mysql-xdevapi >= 8.0.11)

Introduction

Class synopsis

mysql_xdevapi\Executable {
/* Methods */
abstract public execute ( void ) : mysql_xdevapi\Result
}

Table of Contents

  • Executable::execute — Execute statement


Execute statement

  • « mysql_xdevapi\Executable
  • mysql_xdevapi\ExecutionStatus »
  • PHP Manual
  • mysql_xdevapi\Executable
  • Execute statement

Executable::execute

(No version information available, might only be in Git)

Executable::execute — Execute statement

Description

abstract public mysql_xdevapi\Executable::execute ( void ) : 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) {
}


ExecutionStatus class

(PECL mysql-xdevapi >= 8.0.11)

Introduction

Class synopsis

mysql_xdevapi\ExecutionStatus {
/* Properties */
public $affectedItems ;
public $matchedItems ;
public $foundItems ;
public $lastInsertId ;
public $lastDocumentId ;
/* Constructor */
private __construct ( void )
}

Properties

affectedItems

matchedItems

foundItems

lastInsertId

lastDocumentId

Table of Contents

  • ExecutionStatus::__construct — ExecutionStatus constructor


ExecutionStatus constructor

  • « mysql_xdevapi\ExecutionStatus
  • mysql_xdevapi\Expression »
  • PHP Manual
  • mysql_xdevapi\ExecutionStatus
  • ExecutionStatus constructor

ExecutionStatus::__construct

(No version information available, might only be in Git)

ExecutionStatus::__construct — ExecutionStatus constructor

Description

private mysql_xdevapi\ExecutionStatus::__construct ( void )

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

/* ... */

?>


Expression class

(PECL mysql-xdevapi >= 8.0.11)

Introduction

Class synopsis

mysql_xdevapi\Expression {
/* Properties */
public $name ;
/* Constructor */
public __construct ( string $expression )
}

Properties

name

Table of Contents

  • Expression::__construct — Expression constructor


Expression constructor

  • « mysql_xdevapi\Expression
  • mysql_xdevapi\Result »
  • PHP Manual
  • mysql_xdevapi\Expression
  • Expression constructor

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

/* ... */

?>


Result class

(PECL mysql-xdevapi >= 8.0.11)

Introduction

Class synopsis

mysql_xdevapi\Result implements mysql_xdevapi\BaseResult , Traversable {
/* Methods */
public getAffectedItemsCount ( void ) : int
public getAutoIncrementValue ( void ) : int
public getGeneratedIds ( void ) : array
public getWarnings ( void ) : array
public getWarningsCount ( void ) : integer
}

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


Result constructor

  • « mysql_xdevapi\Result
  • Result::getAffectedItemsCount »
  • PHP Manual
  • mysql_xdevapi\Result
  • Result constructor

Result::__construct

(No version information available, might only be in Git)

Result::__construct — Result constructor

Description

private mysql_xdevapi\Result::__construct ( void )

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)


Get affected row count

  • « Result::__construct
  • Result::getAutoIncrementValue »
  • PHP Manual
  • mysql_xdevapi\Result
  • Get affected row count

Result::getAffectedItemsCount

(No version information available, might only be in Git)

Result::getAffectedItemsCount — Get affected row count

Description

public mysql_xdevapi\Result::getAffectedItemsCount ( void ) : 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)


Get autoincremented value

  • « Result::getAffectedItemsCount
  • Result::getGeneratedIds »
  • PHP Manual
  • mysql_xdevapi\Result
  • Get autoincremented value

Result::getAutoIncrementValue

(No version information available, might only be in Git)

Result::getAutoIncrementValue — Get autoincremented value

Description

public mysql_xdevapi\Result::getAutoIncrementValue ( void ) : 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)


Get generated ids

  • « Result::getAutoIncrementValue
  • Result::getWarnings »
  • PHP Manual
  • mysql_xdevapi\Result
  • Get generated ids

Result::getGeneratedIds

(No version information available, might only be in Git)

Result::getGeneratedIds — Get generated ids

Description

public mysql_xdevapi\Result::getGeneratedIds ( void ) : 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"
}


Get warnings from last operation

  • « Result::getGeneratedIds
  • Result::getWarningsCount »
  • PHP Manual
  • mysql_xdevapi\Result
  • Get warnings from last operation

Result::getWarnings

(No version information available, might only be in Git)

Result::getWarnings — Get warnings from last operation

Description

public mysql_xdevapi\Result::getWarnings ( void ) : 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
        )
)


Get warning count from last operation

  • « Result::getWarnings
  • mysql_xdevapi\RowResult »
  • PHP Manual
  • mysql_xdevapi\Result
  • Get warning count from last operation

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 ( void ) : integer

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


RowResult class

(PECL mysql-xdevapi >= 8.0.11)

Introduction

Class synopsis

mysql_xdevapi\RowResult implements mysql_xdevapi\BaseResult , Traversable {
/* Methods */
public fetchAll ( void ) : array
public fetchOne ( void ) : array
public getColumnsCount ( void ) : integer
public getColumnNames ( void ) : array
public getColumns ( void ) : array
public getWarnings ( void ) : array
public getWarningsCount ( void ) : integer
}

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


RowResult constructor

  • « mysql_xdevapi\RowResult
  • RowResult::fetchAll »
  • PHP Manual
  • mysql_xdevapi\RowResult
  • RowResult constructor

RowResult::__construct

(No version information available, might only be in Git)

RowResult::__construct — RowResult constructor

Description

private mysql_xdevapi\RowResult::__construct ( void )

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


Get all rows from result

  • « RowResult::__construct
  • RowResult::fetchOne »
  • PHP Manual
  • mysql_xdevapi\RowResult
  • Get all rows from result

RowResult::fetchAll

(No version information available, might only be in Git)

RowResult::fetchAll — Get all rows from result

Description

public mysql_xdevapi\RowResult::fetchAll ( void ) : 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
        )
)


Get row from result

  • « RowResult::fetchAll
  • RowResult::getColumnsCount »
  • PHP Manual
  • mysql_xdevapi\RowResult
  • Get row from result

RowResult::fetchOne

(No version information available, might only be in Git)

RowResult::fetchOne — Get row from result

Description

public mysql_xdevapi\RowResult::fetchOne ( void ) : 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
)


Get column count

  • « RowResult::fetchOne
  • RowResult::getColumnNames »
  • PHP Manual
  • mysql_xdevapi\RowResult
  • Get column count

RowResult::getColumnsCount

(No version information available, might only be in Git)

RowResult::getColumnsCount — Get column count

Description

public mysql_xdevapi\RowResult::getColumnsCount ( void ) : integer

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


Get all column names

  • « RowResult::getColumnsCount
  • RowResult::getColumns »
  • PHP Manual
  • mysql_xdevapi\RowResult
  • Get all column names

RowResult::getColumnNames

(No version information available, might only be in Git)

RowResult::getColumnNames — Get all column names

Description

public mysql_xdevapi\RowResult::getColumnNames ( void ) : 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
)


Get column metadata

  • « RowResult::getColumnNames
  • RowResult::getWarnings »
  • PHP Manual
  • mysql_xdevapi\RowResult
  • Get column metadata

RowResult::getColumns

(No version information available, might only be in Git)

RowResult::getColumns — Get column metadata

Description

public mysql_xdevapi\RowResult::getColumns ( void ) : 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
        )
)


Get warnings from last operation

  • « RowResult::getColumns
  • RowResult::getWarningsCount »
  • PHP Manual
  • mysql_xdevapi\RowResult
  • Get warnings from last operation

RowResult::getWarnings

(No version information available, might only be in Git)

RowResult::getWarnings — Get warnings from last operation

Description

public mysql_xdevapi\RowResult::getWarnings ( void ) : 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
        )
)


Get warning count from last operation

  • « RowResult::getWarnings
  • mysql_xdevapi\Schema »
  • PHP Manual
  • mysql_xdevapi\RowResult
  • Get warning count from last operation

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 ( void ) : integer

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


Schema class

(PECL mysql-xdevapi >= 8.0.11)

Introduction

Class synopsis

mysql_xdevapi\Schema implements mysql_xdevapi\DatabaseObject {
/* Properties */
public $name ;
/* Methods */
public createCollection ( string $name ) : mysql_xdevapi\Collection
public dropCollection ( string $collection_name ) : bool
public existsInDatabase ( void ) : bool
public getCollection ( string $name ) : mysql_xdevapi\Collection
public getCollectionAsTable ( string $name ) : mysql_xdevapi\Table
public getCollections ( void ) : array
public getName ( void ) : string
public getSession ( void ) : mysql_xdevapi\Session
public getTable ( string $name ) : mysql_xdevapi\Table
public getTables ( void ) : array
}

Properties

name

Table of Contents

  • Schema::__construct — 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 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


constructor

  • « mysql_xdevapi\Schema
  • Schema::createCollection »
  • PHP Manual
  • mysql_xdevapi\Schema
  • constructor

Schema::__construct

(No version information available, might only be in Git)

Schema::__construct — constructor

Description

private mysql_xdevapi\Schema::__construct ( void )

The Schema object provides full access to the schema (database).

Parameters

This function has no parameters.

Examples

Example #1 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
        )
)


Add collection to schema

  • « Schema::__construct
  • Schema::dropCollection »
  • PHP Manual
  • mysql_xdevapi\Schema
  • Add collection to schema

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 ) : mysql_xdevapi\Collection

Create a collection within the schema.

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values

Examples

Example #1 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
        )
)


Drop collection from schema

  • « Schema::createCollection
  • Schema::existsInDatabase »
  • PHP Manual
  • mysql_xdevapi\Schema
  • Drop collection from schema

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


Check if exists in database

  • « Schema::dropCollection
  • Schema::getCollection »
  • PHP Manual
  • mysql_xdevapi\Schema
  • Check if exists in database

Schema::existsInDatabase

(No version information available, might only be in Git)

Schema::existsInDatabase — Check if exists in database

Description

public mysql_xdevapi\Schema::existsInDatabase ( void ) : bool

Checks if the current object (schema, table, collection, or view) exists in the schema object.

Warning

This function is currently not documented; only its argument list is available.

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


Get collection from schema

  • « Schema::existsInDatabase
  • Schema::getCollectionAsTable »
  • PHP Manual
  • mysql_xdevapi\Schema
  • Get collection from schema

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


Get collection table object

  • « Schema::getCollection
  • Schema::getCollections »
  • PHP Manual
  • mysql_xdevapi\Schema
  • Get collection table object

Schema::getCollectionAsTable

(No version information available, might only be in Git)

Schema::getCollectionAsTable — Get collection 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 table object for the collection.

Examples

Example #1 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"
}


Get all schema collections

  • « Schema::getCollectionAsTable
  • Schema::getName »
  • PHP Manual
  • mysql_xdevapi\Schema
  • Get all schema collections

Schema::getCollections

(No version information available, might only be in Git)

Schema::getCollections — Get all schema collections

Description

public mysql_xdevapi\Schema::getCollections ( void ) : 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"
  }
}


Get schema name

  • « Schema::getCollections
  • Schema::getSession »
  • PHP Manual
  • mysql_xdevapi\Schema
  • Get schema name

Schema::getName

(No version information available, might only be in Git)

Schema::getName — Get schema name

Description

public mysql_xdevapi\Schema::getName ( void ) : 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"


Get schema session

  • « Schema::getName
  • Schema::getTable »
  • PHP Manual
  • mysql_xdevapi\Schema
  • Get schema session

Schema::getSession

(No version information available, might only be in Git)

Schema::getSession — Get schema session

Description

public mysql_xdevapi\Schema::getSession ( void ) : 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) {
}


Get schema table

  • « Schema::getSession
  • Schema::getTables »
  • PHP Manual
  • mysql_xdevapi\Schema
  • Get schema table

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


Get schema tables

  • « Schema::getTable
  • mysql_xdevapi\SchemaObject »
  • PHP Manual
  • mysql_xdevapi\Schema
  • Get schema tables

Schema::getTables

(No version information available, might only be in Git)

Schema::getTables — Get schema tables

Description

public mysql_xdevapi\Schema::getTables ( void ) : 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"
  }
}


SchemaObject interface

(PECL mysql-xdevapi >= 8.0.11)

Introduction

Class synopsis

mysql_xdevapi\SchemaObject implements mysql_xdevapi\DatabaseObject {
/* Methods */
abstract getSchema ( void ) : mysql_xdevapi\Schema
}

Table of Contents

  • SchemaObject::getSchema — Get schema object


Get schema object

  • « mysql_xdevapi\SchemaObject
  • mysql_xdevapi\Session »
  • PHP Manual
  • mysql_xdevapi\SchemaObject
  • Get schema object

SchemaObject::getSchema

(No version information available, might only be in Git)

SchemaObject::getSchema — Get schema object

Description

abstract mysql_xdevapi\SchemaObject::getSchema ( void ) : 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
)


Session class

(PECL mysql-xdevapi >= 8.0.11)

Introduction

Class synopsis

mysql_xdevapi\Session {
/* Methods */
public close ( void ) : bool
public commit ( void ) : Object
public createSchema ( string $schema_name ) : mysql_xdevapi\Schema
public dropSchema ( string $schema_name ) : bool
public generateUUID ( void ) : string
public getDefaultSchema ( void ) : string
public getSchema ( string $schema_name ) : mysql_xdevapi\Schema
public getSchemas ( void ) : array
public getServerVersion ( void ) : integer
public listClients ( void ) : array
public quoteName ( string $name ) : string
public releaseSavepoint ( string $name ) : void
public rollback ( void ) : void
public rollbackTo ( string $name ) : void
public setSavepoint ([ string $name ] ) : string
public sql ( string $query ) : mysql_xdevapi\SqlStatement
public startTransaction ( void ) : void
}

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 — Execute SQL query
  • Session::startTransaction — Start transaction


Close session

  • « mysql_xdevapi\Session
  • Session::commit »
  • PHP Manual
  • mysql_xdevapi\Session
  • Close session

Session::close

(No version information available, might only be in Git)

Session::close — Close session

Description

public mysql_xdevapi\Session::close ( void ) : 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();


Commit transaction

  • « Session::close
  • Session::__construct »
  • PHP Manual
  • mysql_xdevapi\Session
  • Commit transaction

Session::commit

(PHP 4 >= 4.4.0, PHP 5, PHP 7)

Session::commit — Commit transaction

Description

public mysql_xdevapi\Session::commit ( void ) : 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();


Description constructor

  • « Session::commit
  • Session::createSchema »
  • PHP Manual
  • mysql_xdevapi\Session
  • Description constructor

Session::__construct

(No version information available, might only be in Git)

Session::__construct — Description constructor

Description

private mysql_xdevapi\Session::__construct ( void )

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();
?>


Create new schema

  • « Session::__construct
  • Session::dropSchema »
  • PHP Manual
  • mysql_xdevapi\Session
  • Create new schema

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'


Drop a schema

  • « Session::createSchema
  • Session::generateUUID »
  • PHP Manual
  • mysql_xdevapi\Session
  • Drop a schema

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();
?>


Get new UUID

  • « Session::dropSchema
  • Session::getDefaultSchema »
  • PHP Manual
  • mysql_xdevapi\Session
  • Get new UUID

Session::generateUUID

(No version information available, might only be in Git)

Session::generateUUID — Get new UUID

Description

public mysql_xdevapi\Session::generateUUID ( void ) : 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"


Get default schema name

  • « Session::generateUUID
  • Session::getSchema »
  • PHP Manual
  • mysql_xdevapi\Session
  • Get default schema name

Session::getDefaultSchema

(No version information available, might only be in Git)

Session::getDefaultSchema — Get default schema name

Description

public mysql_xdevapi\Session::getDefaultSchema ( void ) : string

Retrieve name of the default schema that's typically set in the connection URI.

Parameters

This function has no parameters.

Return Values

Name of 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;
?>

The above example will output:

testx


Get a new schema object

  • « Session::getDefaultSchema
  • Session::getSchemas »
  • PHP Manual
  • mysql_xdevapi\Session
  • Get a new schema object

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
)


Get the schemas

  • « Session::getSchema
  • Session::getServerVersion »
  • PHP Manual
  • mysql_xdevapi\Session
  • Get the schemas

Session::getSchemas

(No version information available, might only be in Git)

Session::getSchemas — Get the schemas

Description

public mysql_xdevapi\Session::getSchemas ( void ) : 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
        )
    ...


Get server version

  • « Session::getSchemas
  • Session::listClients »
  • PHP Manual
  • mysql_xdevapi\Session
  • Get server version

Session::getServerVersion

(No version information available, might only be in Git)

Session::getServerVersion — Get server version

Description

public mysql_xdevapi\Session::getServerVersion ( void ) : integer

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)


Get client list

  • « Session::getServerVersion
  • Session::quoteName »
  • PHP Manual
  • mysql_xdevapi\Session
  • Get client list

Session::listClients

(No version information available, might only be in Git)

Session::listClients — Get client list

Description

public mysql_xdevapi\Session::listClients ( void ) : 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)
  }
}


Add quotes

  • « Session::listClients
  • Session::releaseSavepoint »
  • PHP Manual
  • mysql_xdevapi\Session
  • Add quotes

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


Release set savepoint

  • « Session::quoteName
  • Session::rollback »
  • PHP Manual
  • mysql_xdevapi\Session
  • Release set savepoint

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();
?>


Rollback transaction

  • « Session::releaseSavepoint
  • Session::rollbackTo »
  • PHP Manual
  • mysql_xdevapi\Session
  • Rollback transaction

Session::rollback

(No version information available, might only be in Git)

Session::rollback — Rollback transaction

Description

public mysql_xdevapi\Session::rollback ( void ) : 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();
?>


Rollback transaction to savepoint

  • « Session::rollback
  • Session::setSavepoint »
  • PHP Manual
  • mysql_xdevapi\Session
  • Rollback transaction to savepoint

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


Create savepoint

  • « Session::rollbackTo
  • Session::sql »
  • PHP Manual
  • mysql_xdevapi\Session
  • Create savepoint

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();
?>


Execute SQL query

  • « Session::setSavepoint
  • Session::startTransaction »
  • PHP Manual
  • mysql_xdevapi\Session
  • Execute SQL query

Session::sql

(No version information available, might only be in Git)

Session::sql — Execute 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();
?>


Start transaction

  • « Session::sql
  • mysql_xdevapi\SqlStatement »
  • PHP Manual
  • mysql_xdevapi\Session
  • Start transaction

Session::startTransaction

(No version information available, might only be in Git)

Session::startTransaction — Start transaction

Description

public mysql_xdevapi\Session::startTransaction ( void ) : 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();
?>


SqlStatement class

(PECL mysql-xdevapi >= 8.0.11)

Introduction

Class synopsis

mysql_xdevapi\SqlStatement {
/* Constants */
const integer EXECUTE_ASYNC = 1 ;
const integer BUFFERED = 2 ;
/* Properties */
public $statement ;
/* Methods */
public bind ( string $param ) : mysql_xdevapi\SqlStatement
public execute ( void ) : mysql_xdevapi\Result
public getNextResult ( void ) : mysql_xdevapi\Result
public getResult ( void ) : mysql_xdevapi\Result
public hasMoreResults ( void ) : bool
}

Properties

statement

Predefined Constants

mysql_xdevapi\SqlStatement::EXECUTE_ASYNC

mysql_xdevapi\SqlStatement::BUFFERED

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


Bind statement parameters

  • « mysql_xdevapi\SqlStatement
  • SqlStatement::__construct »
  • PHP Manual
  • mysql_xdevapi\SqlStatement
  • Bind statement parameters

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

/* ... */

?>


Description constructor

  • « SqlStatement::bind
  • SqlStatement::execute »
  • PHP Manual
  • mysql_xdevapi\SqlStatement
  • Description constructor

SqlStatement::__construct

(No version information available, might only be in Git)

SqlStatement::__construct — Description constructor

Description

private mysql_xdevapi\SqlStatement::__construct ( void )

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

/* ... */

?>


Execute the operation

  • « SqlStatement::__construct
  • SqlStatement::getNextResult »
  • PHP Manual
  • mysql_xdevapi\SqlStatement
  • Execute the operation

SqlStatement::execute

(No version information available, might only be in Git)

SqlStatement::execute — Execute the operation

Description

public mysql_xdevapi\SqlStatement::execute ( void ) : 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

/* ... */

?>


Get next result

  • « SqlStatement::execute
  • SqlStatement::getResult »
  • PHP Manual
  • mysql_xdevapi\SqlStatement
  • Get next result

SqlStatement::getNextResult

(No version information available, might only be in Git)

SqlStatement::getNextResult — Get next result

Description

public mysql_xdevapi\SqlStatement::getNextResult ( void ) : 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

/* ... */

?>


Get result

  • « SqlStatement::getNextResult
  • SqlStatement::hasMoreResults »
  • PHP Manual
  • mysql_xdevapi\SqlStatement
  • Get result

SqlStatement::getResult

(No version information available, might only be in Git)

SqlStatement::getResult — Get result

Description

public mysql_xdevapi\SqlStatement::getResult ( void ) : 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

/* ... */

?>


Check for more results

  • « SqlStatement::getResult
  • mysql_xdevapi\SqlStatementResult »
  • PHP Manual
  • mysql_xdevapi\SqlStatement
  • Check for more results

SqlStatement::hasMoreResults

(No version information available, might only be in Git)

SqlStatement::hasMoreResults — Check for more results

Description

public mysql_xdevapi\SqlStatement::hasMoreResults ( void ) : 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

/* ... */

?>


SqlStatementResult class

(PECL mysql-xdevapi >= 8.0.11)

Introduction

Class synopsis

mysql_xdevapi\SqlStatementResult implements mysql_xdevapi\BaseResult , Traversable {
/* Methods */
public fetchAll ( void ) : array
public fetchOne ( void ) : array
public getAffectedItemsCount ( void ) : integer
public getColumnsCount ( void ) : integer
public getColumnNames ( void ) : array
public getColumns ( void ) : Array
public getGeneratedIds ( void ) : array
public getLastInsertId ( void ) : String
public getWarnings ( void ) : array
public getWarningCounts ( void ) : integer
public hasData ( void ) : bool
public nextResult ( void ) : mysql_xdevapi\Result
}

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


Description constructor

  • « mysql_xdevapi\SqlStatementResult
  • SqlStatementResult::fetchAll »
  • PHP Manual
  • mysql_xdevapi\SqlStatementResult
  • Description constructor

SqlStatementResult::__construct

(No version information available, might only be in Git)

SqlStatementResult::__construct — Description constructor

Description

private mysql_xdevapi\SqlStatementResult::__construct ( void )

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

/* ... */

?>


Get all rows from result

  • « SqlStatementResult::__construct
  • SqlStatementResult::fetchOne »
  • PHP Manual
  • mysql_xdevapi\SqlStatementResult
  • Get all rows from result

SqlStatementResult::fetchAll

(No version information available, might only be in Git)

SqlStatementResult::fetchAll — Get all rows from result

Description

public mysql_xdevapi\SqlStatementResult::fetchAll ( void ) : 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
        )
)


Get single row

  • « SqlStatementResult::fetchAll
  • SqlStatementResult::getAffectedItemsCount »
  • PHP Manual
  • mysql_xdevapi\SqlStatementResult
  • Get single row

SqlStatementResult::fetchOne

(No version information available, might only be in Git)

SqlStatementResult::fetchOne — Get single row

Description

public mysql_xdevapi\SqlStatementResult::fetchOne ( void ) : 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
)


Get affected row count

  • « SqlStatementResult::fetchOne
  • SqlStatementResult::getColumnsCount »
  • PHP Manual
  • mysql_xdevapi\SqlStatementResult
  • Get affected row count

SqlStatementResult::getAffectedItemsCount

(No version information available, might only be in Git)

SqlStatementResult::getAffectedItemsCount — Get affected row count

Description

public mysql_xdevapi\SqlStatementResult::getAffectedItemsCount ( void ) : integer

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

/* ... */

?>


Get column count

  • « SqlStatementResult::getAffectedItemsCount
  • SqlStatementResult::getColumnNames »
  • PHP Manual
  • mysql_xdevapi\SqlStatementResult
  • Get column count

SqlStatementResult::getColumnsCount

(No version information available, might only be in Git)

SqlStatementResult::getColumnsCount — Get column count

Description

public mysql_xdevapi\SqlStatementResult::getColumnsCount ( void ) : integer

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

/* ... */

?>


Get column names

  • « SqlStatementResult::getColumnsCount
  • SqlStatementResult::getColumns »
  • PHP Manual
  • mysql_xdevapi\SqlStatementResult
  • Get column names

SqlStatementResult::getColumnNames

(No version information available, might only be in Git)

SqlStatementResult::getColumnNames — Get column names

Description

public mysql_xdevapi\SqlStatementResult::getColumnNames ( void ) : 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

/* ... */

?>


Get columns

  • « SqlStatementResult::getColumnNames
  • SqlStatementResult::getGeneratedIds »
  • PHP Manual
  • mysql_xdevapi\SqlStatementResult
  • Get columns

SqlStatementResult::getColumns

(No version information available, might only be in Git)

SqlStatementResult::getColumns — Get columns

Description

public mysql_xdevapi\SqlStatementResult::getColumns ( void ) : 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

/* ... */

?>


Get generated ids

  • « SqlStatementResult::getColumns
  • SqlStatementResult::getLastInsertId »
  • PHP Manual
  • mysql_xdevapi\SqlStatementResult
  • Get generated ids

SqlStatementResult::getGeneratedIds

(No version information available, might only be in Git)

SqlStatementResult::getGeneratedIds — Get generated ids

Description

public mysql_xdevapi\SqlStatementResult::getGeneratedIds ( void ) : 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

/* ... */

?>


Get last insert id

  • « SqlStatementResult::getGeneratedIds
  • SqlStatementResult::getWarnings »
  • PHP Manual
  • mysql_xdevapi\SqlStatementResult
  • Get last insert id

SqlStatementResult::getLastInsertId

(No version information available, might only be in Git)

SqlStatementResult::getLastInsertId — Get last insert id

Description

public mysql_xdevapi\SqlStatementResult::getLastInsertId ( void ) : 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

/* ... */

?>


Get warnings from last operation

  • « SqlStatementResult::getLastInsertId
  • SqlStatementResult::getWarningsCount »
  • PHP Manual
  • mysql_xdevapi\SqlStatementResult
  • Get warnings from last operation

SqlStatementResult::getWarnings

(No version information available, might only be in Git)

SqlStatementResult::getWarnings — Get warnings from last operation

Description

public mysql_xdevapi\SqlStatementResult::getWarnings ( void ) : 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

/* ... */

?>


Get warning count from last operation

  • « SqlStatementResult::getWarnings
  • SqlStatementResult::hasData »
  • PHP Manual
  • mysql_xdevapi\SqlStatementResult
  • Get warning count from last operation

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 ( void ) : integer

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

/* ... */

?>


Check if result has data

  • « SqlStatementResult::getWarningsCount
  • SqlStatementResult::nextResult »
  • PHP Manual
  • mysql_xdevapi\SqlStatementResult
  • Check if result has data

SqlStatementResult::hasData

(No version information available, might only be in Git)

SqlStatementResult::hasData — Check if result has data

Description

public mysql_xdevapi\SqlStatementResult::hasData ( void ) : 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

/* ... */

?>


Get next result

  • « SqlStatementResult::hasData
  • mysql_xdevapi\Statement »
  • PHP Manual
  • mysql_xdevapi\SqlStatementResult
  • Get next result

SqlStatementResult::nextResult

(No version information available, might only be in Git)

SqlStatementResult::nextResult — Get next result

Description

public mysql_xdevapi\SqlStatementResult::nextResult ( void ) : 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

/* ... */

?>


Statement class

(PECL mysql-xdevapi >= 8.0.11)

Introduction

Class synopsis

mysql_xdevapi\Statement {
/* Constants */
const integer EXECUTE_ASYNC = 1 ;
const integer BUFFERED = 2 ;
/* Methods */
public getNextResult ( void ) : mysql_xdevapi\Result
public getResult ( void ) : mysql_xdevapi\Result
public hasMoreResults ( void ) : bool
}

Predefined Constants

mysql_xdevapi\Statement::EXECUTE_ASYNC

mysql_xdevapi\Statement::BUFFERED

Table of Contents

  • Statement::__construct — Description constructor
  • Statement::getNextResult — Get next result
  • Statement::getResult — Get result
  • Statement::hasMoreResults — Check if more results


Description constructor

  • « mysql_xdevapi\Statement
  • Statement::getNextResult »
  • PHP Manual
  • mysql_xdevapi\Statement
  • Description constructor

Statement::__construct

(No version information available, might only be in Git)

Statement::__construct — Description constructor

Description

private mysql_xdevapi\Statement::__construct ( void )

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

/* ... */

?>


Get next result

  • « Statement::__construct
  • Statement::getResult »
  • PHP Manual
  • mysql_xdevapi\Statement
  • Get next result

Statement::getNextResult

(No version information available, might only be in Git)

Statement::getNextResult — Get next result

Description

public mysql_xdevapi\Statement::getNextResult ( void ) : 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

/* ... */

?>


Get result

  • « Statement::getNextResult
  • Statement::hasMoreResults »
  • PHP Manual
  • mysql_xdevapi\Statement
  • Get result

Statement::getResult

(No version information available, might only be in Git)

Statement::getResult — Get result

Description

public mysql_xdevapi\Statement::getResult ( void ) : 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

/* ... */

?>


Check if more results

  • « Statement::getResult
  • mysql_xdevapi\Table »
  • PHP Manual
  • mysql_xdevapi\Statement
  • Check if more results

Statement::hasMoreResults

(No version information available, might only be in Git)

Statement::hasMoreResults — Check if more results

Description

public mysql_xdevapi\Statement::hasMoreResults ( void ) : 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 class

(PECL mysql-xdevapi >= 8.0.11)

Introduction

Provides access to the table through INSERT/SELECT/UPDATE/DELETE statements.

Class synopsis

mysql_xdevapi\Table implements mysql_xdevapi\SchemaObject {
/* Properties */
public $name ;
/* Methods */
public count ( void ) : integer
public delete ( void ) : mysql_xdevapi\TableDelete
public existsInDatabase ( void ) : bool
public getName ( void ) : string
public getSchema ( void ) : mysql_xdevapi\Schema
public getSession ( void ) : mysql_xdevapi\Session
public insert ( mixed $columns [, mixed $... ] ) : mysql_xdevapi\TableInsert
public isView ( void ) : bool
public select ( mixed $columns [, mixed $... ] ) : mysql_xdevapi\TableSelect
public update ( void ) : mysql_xdevapi\TableUpdate
}

Properties

name

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


Table constructor

  • « mysql_xdevapi\Table
  • Table::count »
  • PHP Manual
  • mysql_xdevapi\Table
  • Table constructor

Table::__construct

(No version information available, might only be in Git)

Table::__construct — Table constructor

Description

private mysql_xdevapi\Table::__construct ( void )

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");
?>


Get row count

  • « Table::__construct
  • Table::delete »
  • PHP Manual
  • mysql_xdevapi\Table
  • Get row count

Table::count

(No version information available, might only be in Git)

Table::count — Get row count

Description

public mysql_xdevapi\Table::count ( void ) : integer

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)


Delete rows from table

  • « Table::count
  • Table::existsInDatabase »
  • PHP Manual
  • mysql_xdevapi\Table
  • Delete rows from table

Table::delete

(No version information available, might only be in Git)

Table::delete — Delete rows from table

Description

public mysql_xdevapi\Table::delete ( void ) : 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();
?>


Check if table exists in database

  • « Table::delete
  • Table::getName »
  • PHP Manual
  • mysql_xdevapi\Table
  • Check if table exists in database

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


Get table name

  • « Table::existsInDatabase
  • Table::getSchema »
  • PHP Manual
  • mysql_xdevapi\Table
  • Get table name

Table::getName

(No version information available, might only be in Git)

Table::getName — Get table name

Description

public mysql_xdevapi\Table::getName ( void ) : 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"


Get table schema

  • « Table::getName
  • Table::getSession »
  • PHP Manual
  • mysql_xdevapi\Table
  • Get table schema

Table::getSchema

(No version information available, might only be in Git)

Table::getSchema — Get table schema

Description

public mysql_xdevapi\Table::getSchema ( void ) : 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"
}


Get table session

  • « Table::getSchema
  • Table::insert »
  • PHP Manual
  • mysql_xdevapi\Table
  • Get table session

Table::getSession

(No version information available, might only be in Git)

Table::getSession — Get table session

Description

public mysql_xdevapi\Table::getSession ( void ) : 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) {
}


Insert table rows

  • « Table::getSession
  • Table::isView »
  • PHP Manual
  • mysql_xdevapi\Table
  • Insert table rows

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 $... ] ) : 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.

...

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();
?>


Check if table is view

  • « Table::insert
  • Table::select »
  • PHP Manual
  • mysql_xdevapi\Table
  • Check if table is view

Table::isView

(No version information available, might only be in Git)

Table::isView — Check if table is view

Description

public mysql_xdevapi\Table::isView ( void ) : 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:

int(2)


Select rows from table

  • « Table::isView
  • Table::update »
  • PHP Manual
  • mysql_xdevapi\Table
  • Select rows from table

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 $... ] ) : 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.

...

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


Update rows in table

  • « Table::select
  • mysql_xdevapi\TableDelete »
  • PHP Manual
  • mysql_xdevapi\Table
  • Update rows in table

Table::update

(No version information available, might only be in Git)

Table::update — Update rows in table

Description

public mysql_xdevapi\Table::update ( void ) : 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();
?>


TableDelete class

(PECL mysql-xdevapi >= 8.0.11)

Introduction

A statement for delete operations on Table.

Class synopsis

mysql_xdevapi\TableDelete implements mysql_xdevapi\Executable {
/* Methods */
public bind ( array $placeholder_values ) : mysql_xdevapi\TableDelete
public execute ( void ) : mysql_xdevapi\Result
public limit ( integer $rows ) : mysql_xdevapi\TableDelete
public orderby ( string $orderby_expr ) : mysql_xdevapi\TableDelete
public where ( string $where_expr ) : mysql_xdevapi\TableDelete
}

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


Bind delete query parameters

  • « mysql_xdevapi\TableDelete
  • TableDelete::__construct »
  • PHP Manual
  • mysql_xdevapi\TableDelete
  • Bind delete query parameters

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 constructor

  • « TableDelete::bind
  • TableDelete::execute »
  • PHP Manual
  • mysql_xdevapi\TableDelete
  • TableDelete constructor

TableDelete::__construct

(No version information available, might only be in Git)

TableDelete::__construct — TableDelete constructor

Description

private mysql_xdevapi\TableDelete::__construct ( void )

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

?>


Execute delete query

  • « TableDelete::__construct
  • TableDelete::limit »
  • PHP Manual
  • mysql_xdevapi\TableDelete
  • Execute delete query

TableDelete::execute

(No version information available, might only be in Git)

TableDelete::execute — Execute delete query

Description

public mysql_xdevapi\TableDelete::execute ( void ) : 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();

?>


Limit deleted rows

  • « TableDelete::execute
  • TableDelete::orderby »
  • PHP Manual
  • mysql_xdevapi\TableDelete
  • Limit deleted rows

TableDelete::limit

(No version information available, might only be in Git)

TableDelete::limit — Limit deleted rows

Description

public mysql_xdevapi\TableDelete::limit ( integer $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();

?>


Set delete sort criteria

  • « TableDelete::limit
  • TableDelete::where »
  • PHP Manual
  • mysql_xdevapi\TableDelete
  • Set delete sort criteria

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

?>


Set delete search condition

  • « TableDelete::orderby
  • mysql_xdevapi\TableInsert »
  • PHP Manual
  • mysql_xdevapi\TableDelete
  • Set delete search condition

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

?>


TableInsert class

(PECL mysql-xdevapi >= 8.0.11)

Introduction

A statement for insert operations on Table.

Class synopsis

mysql_xdevapi\TableInsert implements mysql_xdevapi\Executable {
/* Methods */
public execute ( void ) : mysql_xdevapi\Result
public values ( array $row_values ) : mysql_xdevapi\TableInsert
}

Table of Contents

  • TableInsert::__construct — TableInsert constructor
  • TableInsert::execute — Execute insert query
  • TableInsert::values — Add insert row values


TableInsert constructor

  • « mysql_xdevapi\TableInsert
  • TableInsert::execute »
  • PHP Manual
  • mysql_xdevapi\TableInsert
  • TableInsert constructor

TableInsert::__construct

(No version information available, might only be in Git)

TableInsert::__construct — TableInsert constructor

Description

private mysql_xdevapi\TableInsert::__construct ( void )

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();
?>


Execute insert query

  • « TableInsert::__construct
  • TableInsert::values »
  • PHP Manual
  • mysql_xdevapi\TableInsert
  • Execute insert query

TableInsert::execute

(No version information available, might only be in Git)

TableInsert::execute — Execute insert query

Description

public mysql_xdevapi\TableInsert::execute ( void ) : 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();
?>


Add insert row values

  • « TableInsert::execute
  • mysql_xdevapi\TableSelect »
  • PHP Manual
  • mysql_xdevapi\TableInsert
  • Add insert row values

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();
?>


TableSelect class

(PECL mysql-xdevapi >= 8.0.11)

Introduction

A statement for record retrieval operations on a Table.

Class synopsis

mysql_xdevapi\TableSelect implements mysql_xdevapi\Executable {
/* Methods */
public bind ( array $placeholder_values ) : mysql_xdevapi\TableSelect
public execute ( void ) : mysql_xdevapi\RowResult
public groupBy ( mixed $sort_expr ) : mysql_xdevapi\TableSelect
public having ( string $sort_expr ) : mysql_xdevapi\TableSelect
public limit ( integer $rows ) : mysql_xdevapi\TableSelect
public lockExclusive ([ integer $lock_waiting_option ] ) : mysql_xdevapi\TableSelect
public lockShared ([ integer $lock_waiting_option ] ) : mysql_xdevapi\TableSelect
public offset ( integer $position ) : mysql_xdevapi\TableSelect
public orderby ( mixed $sort_expr [, mixed $... ] ) : mysql_xdevapi\TableSelect
public where ( string $where_expr ) : mysql_xdevapi\TableSelect
}

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


Bind select query parameters

  • « mysql_xdevapi\TableSelect
  • TableSelect::__construct »
  • PHP Manual
  • mysql_xdevapi\TableSelect
  • Bind select query parameters

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 constructor

  • « TableSelect::bind
  • TableSelect::execute »
  • PHP Manual
  • mysql_xdevapi\TableSelect
  • TableSelect constructor

TableSelect::__construct

(No version information available, might only be in Git)

TableSelect::__construct — TableSelect constructor

Description

private mysql_xdevapi\TableSelect::__construct ( void )

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


Execute select statement

  • « TableSelect::__construct
  • TableSelect::groupBy »
  • PHP Manual
  • mysql_xdevapi\TableSelect
  • Execute select statement

TableSelect::execute

(No version information available, might only be in Git)

TableSelect::execute — Execute select statement

Description

public mysql_xdevapi\TableSelect::execute ( void ) : 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
        )
)


Set select grouping criteria

  • « TableSelect::execute
  • TableSelect::having »
  • PHP Manual
  • mysql_xdevapi\TableSelect
  • Set select grouping criteria

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


Set select having condition

  • « TableSelect::groupBy
  • TableSelect::limit »
  • PHP Manual
  • mysql_xdevapi\TableSelect
  • Set select having condition

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


Limit selected rows

  • « TableSelect::having
  • TableSelect::lockExclusive »
  • PHP Manual
  • mysql_xdevapi\TableSelect
  • Limit selected rows

TableSelect::limit

(No version information available, might only be in Git)

TableSelect::limit — Limit selected rows

Description

public mysql_xdevapi\TableSelect::limit ( integer $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
        )
)


Execute EXCLUSIVE LOCK

  • « TableSelect::limit
  • TableSelect::lockShared »
  • PHP Manual
  • mysql_xdevapi\TableSelect
  • Execute EXCLUSIVE LOCK

TableSelect::lockExclusive

(No version information available, might only be in Git)

TableSelect::lockExclusive — Execute EXCLUSIVE LOCK

Description

public mysql_xdevapi\TableSelect::lockExclusive ([ integer $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
        )
)


Execute SHARED LOCK

  • « TableSelect::lockExclusive
  • TableSelect::offset »
  • PHP Manual
  • mysql_xdevapi\TableSelect
  • Execute SHARED LOCK

TableSelect::lockShared

(No version information available, might only be in Git)

TableSelect::lockShared — Execute SHARED LOCK

Description

public mysql_xdevapi\TableSelect::lockShared ([ integer $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
        )
)


Set limit offset

  • « TableSelect::lockShared
  • TableSelect::orderby »
  • PHP Manual
  • mysql_xdevapi\TableSelect
  • Set limit offset

TableSelect::offset

(No version information available, might only be in Git)

TableSelect::offset — Set limit offset

Description

public mysql_xdevapi\TableSelect::offset ( integer $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
        )
)


Set select sort criteria

  • « TableSelect::offset
  • TableSelect::where »
  • PHP Manual
  • mysql_xdevapi\TableSelect
  • Set select sort criteria

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 $... ] ) : 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.

...

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


Set select search condition

  • « TableSelect::orderby
  • mysql_xdevapi\TableUpdate »
  • PHP Manual
  • mysql_xdevapi\TableSelect
  • Set select search condition

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


TableUpdate class

(PECL mysql-xdevapi >= 8.0.11)

Introduction

A statement for record update operations on a Table.

Class synopsis

mysql_xdevapi\TableUpdate implements mysql_xdevapi\Executable {
/* Methods */
public bind ( array $placeholder_values ) : mysql_xdevapi\TableUpdate
public execute ( void ) : mysql_xdevapi\TableUpdate
public limit ( integer $rows ) : mysql_xdevapi\TableUpdate
public orderby ( mixed $orderby_expr [, mixed $... ] ) : mysql_xdevapi\TableUpdate
public set ( string $table_field , string $expression_or_literal ) : mysql_xdevapi\TableUpdate
public where ( string $where_expr ) : mysql_xdevapi\TableUpdate
}

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


Bind update query parameters

  • « mysql_xdevapi\TableUpdate
  • TableUpdate::__construct »
  • PHP Manual
  • mysql_xdevapi\TableUpdate
  • Bind update query parameters

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 constructor

  • « TableUpdate::bind
  • TableUpdate::execute »
  • PHP Manual
  • mysql_xdevapi\TableUpdate
  • TableUpdate constructor

TableUpdate::__construct

(No version information available, might only be in Git)

TableUpdate::__construct — TableUpdate constructor

Description

private mysql_xdevapi\TableUpdate::__construct ( void )

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

?>


Execute update query

  • « TableUpdate::__construct
  • TableUpdate::limit »
  • PHP Manual
  • mysql_xdevapi\TableUpdate
  • Execute update query

TableUpdate::execute

(No version information available, might only be in Git)

TableUpdate::execute — Execute update query

Description

public mysql_xdevapi\TableUpdate::execute ( void ) : 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();

?>


Limit update row count

  • « TableUpdate::execute
  • TableUpdate::orderby »
  • PHP Manual
  • mysql_xdevapi\TableUpdate
  • Limit update row count

TableUpdate::limit

(No version information available, might only be in Git)

TableUpdate::limit — Limit update row count

Description

public mysql_xdevapi\TableUpdate::limit ( integer $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();

?>


Set sorting criteria

  • « TableUpdate::limit
  • TableUpdate::set »
  • PHP Manual
  • mysql_xdevapi\TableUpdate
  • Set sorting criteria

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 $... ] ) : 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.

...

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();
?>


Add field to be updated

  • « TableUpdate::orderby
  • TableUpdate::where »
  • PHP Manual
  • mysql_xdevapi\TableUpdate
  • Add field to be updated

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

?>


Set search filter

  • « TableUpdate::set
  • mysql_xdevapi\Warning »
  • PHP Manual
  • mysql_xdevapi\TableUpdate
  • Set search filter

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

?>


Warning class

(PECL mysql-xdevapi >= 8.0.11)

Introduction

Class synopsis

mysql_xdevapi\Warning {
/* Properties */
public $message ;
public $level ;
public $code ;
/* Constructor */
private __construct ( void )
}

Properties

message

level

code

Table of Contents

  • Warning::__construct — Warning constructor


Warning constructor

  • « mysql_xdevapi\Warning
  • MySQL (Original) »
  • PHP Manual
  • mysql_xdevapi\Warning
  • Warning constructor

Warning::__construct

(No version information available, might only be in Git)

Warning::__construct — Warning constructor

Description

private mysql_xdevapi\Warning::__construct ( void )

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

/* ... */

?>


Original MySQL API

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


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


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 and related FAQ for more information. 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 and related FAQ for more information. 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" | PHP_INI_SYSTEM |
mysql.allow_persistent | "1" | PHP_INI_SYSTEM |
mysql.max_persistent | "-1" | PHP_INI_SYSTEM |
mysql.max_links | "-1" | PHP_INI_SYSTEM |
mysql.trace_mode | "0" | PHP_INI_ALL |
mysql.default_port | NULL | PHP_INI_ALL |
mysql.default_socket | NULL | PHP_INI_ALL |
mysql.default_host | NULL | PHP_INI_ALL |
mysql.default_user | NULL | PHP_INI_ALL |
mysql.default_password | NULL | PHP_INI_ALL |
mysql.connect_timeout | "60" | PHP_INI_ALL |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

mysql.allow_local_infile integer

Allow accessing, from PHP's perspective, local files with LOAD DATA statements

mysql.allow_persistent boolean

Whether to allow persistent connections to MySQL.

mysql.max_persistent integer

The maximum number of persistent MySQL connections per process.

mysql.max_links integer

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

mysql.trace_mode boolean

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 integer

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.
5.5.0 | This extension has been deprecated. Connecting to a MySQL database via mysql_connect(), mysql_pconnect() or an implicit connection via any other mysql_* function will generate an E_DEPRECATED error.
5.5.0 | All of the old deprecated functions and aliases now emit E_DEPRECATED errors. These functions are: mysql(), mysql_fieldname(), mysql_fieldtable(), mysql_fieldlen(), mysql_fieldtype(), mysql_fieldflags(), mysql_selectdb(), mysql_createdb(), mysql_dropdb(), mysql_freeresult(), mysql_numfields(), mysql_numrows(), mysql_listdbs(), mysql_listtables(), mysql_listfields(), mysql_db_name(), mysql_dbname(), mysql_tablename(), and mysql_table_name().

Changes to existing functions

The following list is a compilation of changelog entries from the ext/mysql functions.

Version | Function | Description
5.5.0 | mysql_connect | This function will generate an E_DEPRECATED error.
 | mysql_db_name | The mysql_list_dbs function is deprecated, and emits an E_DEPRECATED level error.
 | mysql_pconnect | This function will generate an E_DEPRECATED error.
 | mysql_tablename | The mysql_tablename function is deprecated, and emits an E_DEPRECATED level error.
5.3.0 | mysql_db_query | This function now throws an E_DEPRECATED notice.
 | mysql_escape_string | This function now throws an E_DEPRECATED notice.
4.3.7 | mysql_list_tables | This function became deprecated.
4.3.0 | mysql_escape_string | This function became deprecated, do not use this function. Instead, use mysql_real_escape_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.

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.


  • « Predefined Constants
  • MySQL extension overview example »
  • PHP Manual
  • MySQL (Original)
  • Examples

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.

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


Get number of affected rows in previous MySQL operation

  • « MySQL Functions
  • mysql_client_encoding »
  • PHP Manual
  • MySQL Functions
  • Get number of affected rows in previous MySQL operation

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 and related FAQ for more information. 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


Returns the name of the character set

  • « mysql_affected_rows
  • mysql_close »
  • PHP Manual
  • MySQL Functions
  • Returns the name of the character set

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 and related FAQ for more information. 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


Close MySQL connection

  • « mysql_client_encoding
  • mysql_connect »
  • PHP Manual
  • MySQL Functions
  • Close MySQL connection

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 and related FAQ for more information. 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


Open a connection to a MySQL Server

  • « mysql_close
  • mysql_create_db »
  • PHP Manual
  • MySQL Functions
  • Open a connection to a MySQL Server

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 and related FAQ for more information. 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

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.

Changelog

Version | Description
5.5.0 | This function will generate an E_DEPRECATED error.

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, you should set the correct path as in your PHP configuration and leave the server field 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


Create a MySQL database

  • « mysql_connect
  • mysql_data_seek »
  • PHP Manual
  • MySQL Functions
  • Create a MySQL database

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 and its related FAQ entry for additional information. 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


Move internal result pointer

  • « mysql_create_db
  • mysql_db_name »
  • PHP Manual
  • MySQL Functions
  • Move internal result pointer

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 and related FAQ for more information. 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 a 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


Retrieves database name from the call to mysql_list_dbs

  • « mysql_data_seek
  • mysql_db_query »
  • PHP Manual
  • MySQL Functions
  • Retrieves database name from the call to mysql_list_dbs

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 and related FAQ for more information. 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.

Changelog

Version | Description
5.5.0 | The mysql_list_dbs() function is deprecated, and emits an E_DEPRECATED level 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


Selects a database and executes a query on it

  • « mysql_db_name
  • mysql_drop_db »
  • PHP Manual
  • MySQL Functions
  • Selects a database and executes a query on it

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 and its related FAQ entry for additional information. 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

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.

Changelog

Version | Description
5.3.0 | This function now throws an E_DEPRECATED notice.

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


Drop (delete) a MySQL database

  • « mysql_db_query
  • mysql_errno »
  • PHP Manual
  • MySQL Functions
  • Drop (delete) 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 and its related FAQ entry for additional information. 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


Returns the numerical value of the error message from previous MySQL operation

  • « mysql_drop_db
  • mysql_error »
  • PHP Manual
  • MySQL Functions
  • Returns the numerical value of the error message from previous MySQL operation

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 and related FAQ for more information. 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


Returns the text of the error message from previous MySQL operation

  • « mysql_errno
  • mysql_escape_string »
  • PHP Manual
  • MySQL Functions
  • Returns the text of the error message from previous MySQL operation

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 and related FAQ for more information. 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


Escapes a string for use in a mysql_query

  • « mysql_error
  • mysql_fetch_array »
  • PHP Manual
  • MySQL Functions
  • Escapes a string for use in a mysql_query

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 and its related FAQ entry for additional information. 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.

Changelog

Version | Description
5.3.0 | This function now throws an E_DEPRECATED notice.
4.3.0 | This function became deprecated, do not use this function. Instead, use mysql_real_escape_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
  • addslashes() - Quote string with slashes
  • The magic_quotes_gpc directive.


Fetch a result row as an associative array, a numeric array, or both

  • « mysql_escape_string
  • mysql_fetch_assoc »
  • PHP Manual
  • MySQL Functions
  • Fetch a result row as an associative array, a numeric array, or both

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 and related FAQ for more information. 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


Fetch a result row as an associative array

  • « mysql_fetch_array
  • mysql_fetch_field »
  • PHP Manual
  • MySQL Functions
  • Fetch a result row as an associative array

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 and related FAQ for more information. Alternatives to this function include:

  • mysqli_fetch_assoc()
  • PDOStatement::fetch(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


Get column information from a result and return as an object

  • « mysql_fetch_assoc
  • mysql_fetch_lengths »
  • PHP Manual
  • MySQL Functions
  • Get column information from a result and return as an object

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 and related FAQ for more information. 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


Get the length of each output in a result

  • « mysql_fetch_field
  • mysql_fetch_object »
  • PHP Manual
  • MySQL Functions
  • Get the length of each output in a result

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 and related FAQ for more information. Alternatives to this function include:

  • mysqli_fetch_lengths()
  • PDOStatement::getColumnMeta()

Description

mysql_fetch_lengths ( resource $result ) : array

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


Fetch a result row as an object

  • « mysql_fetch_lengths
  • mysql_fetch_row »
  • PHP Manual
  • MySQL Functions
  • Fetch a result row as an object

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 and related FAQ for more information. Alternatives to this function include:

  • mysqli_fetch_object()
  • PDOStatement::fetch(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


Get a result row as an enumerated array

  • « mysql_fetch_object
  • mysql_field_flags »
  • PHP Manual
  • MySQL Functions
  • Get a result row as an enumerated array

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 and related FAQ for more information. Alternatives to this function include:

  • mysqli_fetch_row()
  • PDOStatement::fetch(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


Get the flags associated with the specified field in a result

  • « mysql_fetch_row
  • mysql_field_len »
  • PHP Manual
  • MySQL Functions
  • Get the flags associated with the specified field in a result

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 and related FAQ for more information. Alternatives to this function include:

  • mysqli_fetch_field_direct() [flags]
  • PDOStatement::getColumnMeta() [flags]

Description

mysql_field_flags ( resource $result , int $field_offset ) : string

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


Returns the length of the specified field

  • « mysql_field_flags
  • mysql_field_name »
  • PHP Manual
  • MySQL Functions
  • 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 and related FAQ for more information. Alternatives to this function include:

  • mysqli_fetch_field_direct() [length]
  • PDOStatement::getColumnMeta() [len]

Description

mysql_field_len ( resource $result , int $field_offset ) : int

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


Get the name of the specified field in a result

  • « mysql_field_len
  • mysql_field_seek »
  • PHP Manual
  • MySQL Functions
  • Get the name of the specified field in a result

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 and related FAQ for more information. 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

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


Set result pointer to a specified field offset

  • « mysql_field_name
  • mysql_field_table »
  • PHP Manual
  • MySQL Functions
  • Set result pointer to a specified field offset

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 and related FAQ for more information. 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


Get name of the table the specified field is in

  • « mysql_field_seek
  • mysql_field_type »
  • PHP Manual
  • MySQL Functions
  • Get name of the table the specified field is in

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 and related FAQ for more information. 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


Get the type of the specified field in a result

  • « mysql_field_table
  • mysql_free_result »
  • PHP Manual
  • MySQL Functions
  • Get the type of the specified field in a result

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 and related FAQ for more information. 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


Free result memory

  • « mysql_field_type
  • mysql_get_client_info »
  • PHP Manual
  • MySQL Functions
  • Free result memory

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 and related FAQ for more information. 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


Get MySQL client info

  • « mysql_free_result
  • mysql_get_host_info »
  • PHP Manual
  • MySQL Functions
  • Get MySQL client info

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 and related FAQ for more information. Alternatives to this function include:

  • mysqli_get_client_info()
  • PDO::getAttribute(PDO::ATTR_CLIENT_VERSION)

Description

mysql_get_client_info ( void ) : string

mysql_get_client_info() returns a string that represents the client library version.

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


Get MySQL host info

  • « mysql_get_client_info
  • mysql_get_proto_info »
  • PHP Manual
  • MySQL Functions
  • Get MySQL host 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 and related FAQ for more information. Alternatives to this function include:

  • mysqli_get_host_info()
  • PDO::getAttribute(PDO::ATTR_CONNECTION_STATUS)

Description

mysql_get_host_info ([ resource $link_identifier = NULL ] ) : string

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


Get MySQL protocol info

  • « mysql_get_host_info
  • mysql_get_server_info »
  • PHP Manual
  • MySQL Functions
  • Get MySQL protocol 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 and related FAQ for more information. Alternatives to this function include:

  • mysqli_get_proto_info()

Description

mysql_get_proto_info ([ resource $link_identifier = NULL ] ) : int

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


Get MySQL server info

  • « mysql_get_proto_info
  • mysql_info »
  • PHP Manual
  • MySQL Functions
  • 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 and related FAQ for more information. Alternatives to this function include:

  • mysqli_get_server_info()
  • PDO::getAttribute(PDO::ATTR_SERVER_VERSION)

Description

mysql_get_server_info ([ resource $link_identifier = NULL ] ) : string

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


Get information about the most recent query

  • « mysql_get_server_info
  • mysql_insert_id »
  • PHP Manual
  • MySQL Functions
  • Get information about the most recent query

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 and related FAQ for more information. 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


Get the ID generated in the last query

  • « mysql_info
  • mysql_list_dbs »
  • PHP Manual
  • MySQL Functions
  • Get the ID generated in the last query

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 and related FAQ for more information. 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


List databases available on a MySQL server

  • « mysql_insert_id
  • mysql_list_fields »
  • PHP Manual
  • MySQL Functions
  • List databases available on a MySQL server

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 and its related FAQ entry for additional information. 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


List MySQL table fields

  • « mysql_list_dbs
  • mysql_list_processes »
  • PHP Manual
  • MySQL Functions
  • List MySQL table fields

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 and its related FAQ entry for additional information. 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


List MySQL processes

  • « mysql_list_fields
  • mysql_list_tables »
  • PHP Manual
  • MySQL Functions
  • List MySQL processes

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 and related FAQ for more information. Alternatives to this function include:

  • mysqli_thread_id()

Description

mysql_list_processes ([ resource $link_identifier = NULL ] ) : resource

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


List tables in a MySQL database

  • « mysql_list_processes
  • mysql_num_fields »
  • PHP Manual
  • MySQL Functions
  • List tables in a MySQL database

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 and its related FAQ entry for additional information. Alternatives to this function include:

  • SQL Query: SHOW TABLES FROM dbname

Description

mysql_list_tables ( string $database [, resource $link_identifier = NULL ] ) : resource

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

Changelog

Version | Description
4.3.7 | This function became deprecated.

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


Get number of fields in result

  • « mysql_list_tables
  • mysql_num_rows »
  • PHP Manual
  • MySQL Functions
  • Get number of fields in result

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 and related FAQ for more information. Alternatives to this function include:

  • mysqli_num_fields()
  • PDOStatement::columnCount()

Description

mysql_num_fields ( resource $result ) : int

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


Get number of rows in result

  • « mysql_num_fields
  • mysql_pconnect »
  • PHP Manual
  • MySQL Functions
  • 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 and related FAQ for more information. Alternatives to this function include:

  • mysqli_num_rows()
  • mysqli_stmt_num_rows()
  • PDOStatement::rowCount()

Description

mysql_num_rows ( resource $result ) : int

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


Open a persistent connection to a MySQL server

  • « mysql_num_rows
  • mysql_ping »
  • PHP Manual
  • MySQL Functions
  • Open a persistent connection to a MySQL server

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 and related FAQ for more information. 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.

Changelog

Version | Description
5.5.0 | This function will generate an E_DEPRECATED error.

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


Ping a server connection or reconnect if there is no connection

  • « mysql_pconnect
  • mysql_query »
  • PHP Manual
  • MySQL Functions
  • Ping a server connection or reconnect if there is no connection

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 and related FAQ for more information. 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


Send a MySQL query

  • « mysql_ping
  • mysql_real_escape_string »
  • PHP Manual
  • MySQL Functions
  • Send a MySQL query

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 and related FAQ for more information. 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


Escapes special characters in a string for use in an SQL statement

  • « mysql_query
  • mysql_result »
  • PHP Manual
  • MySQL Functions
  • Escapes special characters in a string for use in an SQL statement

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 and related FAQ for more information. 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 magic_quotes_gpc is enabled, first apply stripslashes() to the data. Using this function on data which has already been escaped will escape the data twice.

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
  • addslashes() - Quote string with slashes
  • stripslashes() - Un-quotes a quoted string
  • The magic_quotes_gpc directive
  • The magic_quotes_runtime directive


Get result data

  • « mysql_real_escape_string
  • mysql_select_db »
  • PHP Manual
  • MySQL Functions
  • Get result data

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 and related FAQ for more information. 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


Select a MySQL database

  • « mysql_result
  • mysql_set_charset »
  • PHP Manual
  • MySQL Functions
  • Select a MySQL database

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 and related FAQ for more information. 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


Sets the client character set

  • « mysql_select_db
  • mysql_stat »
  • PHP Manual
  • MySQL Functions
  • Sets the client character set

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 and related FAQ for more information. 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


Get current system status

  • « mysql_set_charset
  • mysql_tablename »
  • PHP Manual
  • MySQL Functions
  • Get current system status

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 and related FAQ for more information. Alternatives to this function include:

  • mysqli_stat()
  • PDO::getAttribute(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


Get table name of field

  • « mysql_stat
  • mysql_thread_id »
  • PHP Manual
  • MySQL Functions
  • Get table name of field

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 and related FAQ for more information. Alternatives to this function include:

  • SQL Query: SHOW TABLES

Description

mysql_tablename ( resource $result , int $i ) : string

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

Changelog

Version | Description
5.5.0 | The mysql_tablename() function is deprecated, and emits an E_DEPRECATED level error.

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


Return the current thread ID

  • « mysql_tablename
  • mysql_unbuffered_query »
  • PHP Manual
  • MySQL Functions
  • Return the current thread ID

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 and related FAQ for more information. Alternatives to this function include:

  • mysqli_thread_id()

Description

mysql_thread_id ([ resource $link_identifier = NULL ] ) : int

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


Send an SQL query to MySQL without fetching and buffering the result rows

  • « mysql_thread_id
  • Mysqlnd »
  • PHP Manual
  • MySQL Functions
  • Send an SQL query to MySQL without fetching and buffering the result rows

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 and related FAQ for more information. 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


MySQL Native Driver

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


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_cache_stats(),
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 has supported SSL since PHP version 5.3.3

Compressed Protocol Support

As of PHP 5.3.2 MySQL Native Driver supports the compressed client server protocol. MySQL Native Driver did not support this in 5.3.0 and 5.3.1. Extensions such as ext/mysql, ext/mysqli, that are 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 support for Windows was added in PHP version 5.4.0.


Installation

Changelog

Changelog
Version | Description
5.3.0 | The MySQL Native Driver was added, with support for all MySQL extensions (i.e., mysql, mysqli and PDO_MYSQL). Passing in mysqlnd to the appropriate configure switch enables this support.
5.4.0 | The MySQL Native Driver is now the default for all MySQL extensions (i.e., mysql, mysqli and PDO_MYSQL). Passing in mysqlnd to configure is now optional.
5.5.0 | SHA-256 Authentication Plugin support was added

Installation on Unix

The MySQL database extensions must be configured to use the MySQL Client Library. 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 from 5.3 onwards, 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]


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" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
mysqlnd.collect_memory_statistics | "0" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
mysqlnd.debug | "" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
mysqlnd.log_mask | 0 | PHP_INI_ALL | Available since PHP 5.3.0
mysqlnd.mempool_default_size | 16000 | PHP_INI_ALL | Available since PHP 5.3.3
mysqlnd.net_read_timeout | "86400" | PHP_INI_ALL | Available since PHP 5.3.0. Before PHP 7.2.0 the default value was "31536000" and the changeability was PHP_INI_SYSTEM
mysqlnd.net_cmd_buffer_size | 5.3.0 - "2048", 5.3.1 - "4096" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
mysqlnd.net_read_buffer_size | "32768" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
mysqlnd.sha256_server_public_key | "" | PHP_INI_PERDIR | Available since PHP 5.5.0.
mysqlnd.trace_alloc | "" | PHP_INI_SYSTEM | Available since PHP 5.5.0.
mysqlnd.fetch_data_copy | 0 | PHP_INI_ALL | Available since PHP 5.6.0.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

mysqlnd.collect_statistics boolean

Enables the collection of various client statistics which can be
accessed through mysqli_get_client_stats(),
mysqli_get_connection_stats(),
mysqli_get_cache_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 boolean

Enable the collection of various memory statistics which can be
accessed through mysqli_get_client_stats(),
mysqli_get_connection_stats(),
mysqli_get_cache_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. Works on Microsoft Windows if using a debug build of PHP and PHP was built using Microsoft Visual C version 9 and above.

mysqlnd.log_mask integer

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 integer

Default size of the mysqlnd memory pool, which is used by result sets.

mysqlnd.net_read_timeout integer

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 integer

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 2048 bytes in PHP 5.3.0. In later versions the default is 4096 bytes.

It is recommended that the buffer size be set to no less than 4096 bytes because mysqlnd also uses it when reading certain communication packet from MySQL. In PHP 5.3.0, mysqlnd will not grow the buffer if MySQL sends a packet that is larger than the current size of the buffer. As a consequence, mysqlnd is unable to decode the packet and the client application will get an error. There are only two situations when the packet can be larger than the 2048 bytes default of mysqlnd.net_cmd_buffer_size in PHP 5.3.0: the packet transports a very long error message, or the packet holds column meta data from COM_LIST_FIELD (mysql_list_fields() and the meta data come from a string column with a very long default value (>1900 bytes).

As of PHP 5.3.2 mysqlnd does not allow setting buffers smaller than 4096 bytes.

The value can also be set using mysqli_options(link, MYSQLI_OPT_NET_CMD_BUFFER_SIZE, size).

mysqlnd.net_read_buffer_size integer

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 integer

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.


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

Using Statistical Data

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

If you are 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 MySQL Native Driver. For example, when compiling both ext/mysql and ext/mysqli against MySQL Native Driver, both function calls of ext/mysql and ext/mysqli will change 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. You can configure the PDO MySQL Driver, ext/mysql and ext/mysqli to optionally use the MySQL Native Driver. When doing so, all three extensions will change the statistics.

Accessing Client Statistics

To access client statistics, you need to call mysqli_get_client_stats(). The function call does not require any parameters.

The function returns an associative array that contains the name of the statistic as the key and the statistical data as the value.

Client statistics can also be accessed by calling the phpinfo() function.

Accessing Connection Statistics

To access connection statistics call mysqli_get_connection_stats(). This takes the database connection handle as the parameter.

The function returns an associative array that contains the name of the statistic as the key and the statistical data as the value.

Buffered and Unbuffered Result Sets

Result sets can be buffered or unbuffered. Using default settings, ext/mysql and ext/mysqli work with buffered result sets for normal (non prepared statement) queries. Buffered result sets are cached on the client. After the query execution all results are fetched from the MySQL Server and stored in a cache on the client. The big advantage of buffered result sets is that they allow the server to free all resources allocated to a result set, once the results have been fetched by the client.

Unbuffered result sets on the other hand are kept much longer on the server. If you want to reduce memory consumption on the client, but increase load on the server, use unbuffered results. If you experience a high server load and the figures for unbuffered result sets are high, you should consider moving the load to the clients. Clients typically scale better than servers. Load does not only refer to memory buffers - the server also needs to keep other resources open, for example file handles and threads, before a result set can be freed.

Prepared Statements use unbuffered result sets by default. However, you can use mysqli_stmt_store_result() to enable buffered result sets.

Statistics returned by MySQL Native Driver

The following tables show a list of statistics returned by the mysqli_get_client_stats() and mysqli_get_connection_stats() functions.

Returned mysqlnd statistics: Network
Statistic | Scope | Description | Notes
bytes_sent | Connection | Number of bytes sent from PHP to the MySQL server | Can be used to check the efficiency of the compression protocol
bytes_received | Connection | Number of bytes received from MySQL server | Can be used to check the efficiency of the compression protocol
packets_sent | Connection | Number of MySQL Client Server protocol packets sent | Used for debugging Client Server protocol implementation
packets_received | Connection | Number of MySQL Client Server protocol packets received | Used for debugging Client Server protocol implementation
protocol_overhead_in | Connection | 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 | Used for debugging Client Server protocol implementation
protocol_overhead_out | Connection | 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_sent * 4 | Used for debugging Client Server protocol implementation
bytes_received_ok_packet | Connection | 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. | Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_ok | Connection | Number of MySQL Client Server protocol OK packets received. | Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_eof_packet | Connection | 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. | Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_eof | Connection | 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. | Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_rset_header_packet | Connection | 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). | Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_rset_header | Connection | Number of MySQL Client Server protocol result set header packets. | Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_rset_field_meta_packet | Connection | Total size in bytes of MySQL Client Server protocol result set meta data (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. | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_rset_field_meta | Connection | Number of MySQL Client Server protocol result set meta data (field information) packets. | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_rset_row_packet | Connection | 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. You can reverse engineer 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. | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_rset_row | Connection | Number of MySQL Client Server protocol result set row data packets and their total size in bytes. | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_prepare_response_packet | Connection | 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: 9 bytes with MySQL 4.1 and 12 bytes from MySQL 5.0 on. There is no safe way to know how many errors happened. You may be able to guess that an error has occurred if, for example, you always connect to MySQL 5.0 or newer and, bytes_received_prepare_response_packet != packets_received_prepare_response * 12. See also ps_prepared_never_executed, ps_prepared_once_executed. | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_prepare_response | Connection | Number of MySQL Client Server protocol OK for Prepared Statement Initialization packets (prepared statement init packets). | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_change_user_packet | Connection | Total size in bytes of MySQL Client Server protocol COM_CHANGE_USER packets. The packet may also transport an error or EOF. | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_change_user | Connection | Number of MySQL Client Server protocol COM_CHANGE_USER packets | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_sent_command | Connection | 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. At its best you can use it to check if PHP has sent any commands to MySQL to know if you can consider to disable MySQL support in your PHP binary. There is also no way to reverse engineer the number of errors that may have occurred while sending data to MySQL. The only error that is recorded is command_buffer_too_small (see below). | Only useful for debugging CS protocol implementation.
bytes_received_real_data_normal Connection 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.

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

This statistic is available as of PHP version 5.3.4.

bytes_received_real_data_ps | Connection | 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 has 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. This statistic is available as of PHP version 5.3.4.

Result Set

Returned mysqlnd statistics: Result Set
Statistic | Scope | Description | Notes
result_set_queries | Connection | 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. | You may use it as an indirect measure for the number of queries PHP has sent to MySQL, for example, to identify a client that causes a high database load.
non_result_set_queries | Connection | 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. | You may use it as an indirect measure for the number of queries PHP has sent to MySQL, for example, to identify a client that causes a high database load.
no_index_used | Connection | Number of queries that have generated a result set but did not use an index (see also mysqld start option –log-queries-not-using-indexes). If you want these queries to be reported you can use mysqli_report(MYSQLI_REPORT_INDEX) to make ext/mysqli throw an exception. If you prefer a warning instead of an exception use mysqli_report(MYSQLI_REPORT_INDEX ^ MYSQLI_REPORT_STRICT).
bad_index_used | Connection | Number of queries that have generated a result set and did not use a good index (see also mysqld start option –log-slow-queries). | If you want these queries to be reported you can use mysqli_report(MYSQLI_REPORT_INDEX) to make ext/mysqli throw an exception. If you prefer a warning instead of an exception use mysqli_report(MYSQLI_REPORT_INDEX ^ MYSQLI_REPORT_STRICT)
slow_queries | Connection | SQL statements that took more than long_query_time seconds to execute and required at least min_examined_row_limit rows to be examined. | Not reported through mysqli_report()
buffered_sets | Connection | Number of buffered result sets returned by normal queries. Normal means not prepared statement in the following notes. | Examples of API calls that will buffer result sets on the client: mysql_query(), mysqli_query(), mysqli_store_result(), mysqli_stmt_get_result(). Buffering result sets on the client ensures that server resources are freed as soon as possible and it makes result set scrolling easier. The downside is the additional memory consumption on the client for buffering data. Note that mysqlnd (unlike the MySQL Client Library) respects the PHP memory limit because it uses PHP internal memory management functions to allocate memory. This is also the reason why memory_get_usage() reports a higher memory consumption when using mysqlnd instead of the MySQL Client Library. memory_get_usage() does not measure the memory consumption of the MySQL Client Library at all because the MySQL Client Library does not use PHP internal memory management functions monitored by the function!
unbuffered_sets | Connection | Number of unbuffered result sets returned by normal (non prepared statement) queries. | Examples of API calls that will not buffer result sets on the client: mysqli_use_result()
ps_buffered_sets | Connection | Number of buffered result sets returned by prepared statements. By default prepared statements are unbuffered. | Examples of API calls that will buffer result sets on the client: mysqli_stmt_store_result
ps_unbuffered_sets | Connection | Number of unbuffered result sets returned by prepared statements. | By default prepared statements are unbuffered.
flushed_normal_sets Connection Number of result sets from normal (non prepared statement) queries with unread data which have been flushed silently for you. 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 Connection Number of result sets from prepared statements with unread data which have been flushed silently for you. 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 | Connection | Number of statements prepared but never executed. | Prepared statements occupy server resources. You should not prepare a statement if you do not plan to execute it.
ps_prepared_once_executed | Connection | Number of prepared statements executed only one. | One of the ideas behind prepared statements is that the same query gets executed over and over again (with different parameters) and some parsing and other preparation work can be saved, if statement execution is split up in separate prepare and execute stages. The idea is to prepare once and cache results, for example, the parse tree to be reused during multiple statement executions. If you execute a prepared statement only once the two stage processing can be inefficient compared to normal queries because all the caching means extra work and it takes (limited) server resources to hold the cached information. Consequently, prepared statements that are executed only once may cause performance hurts.
rows_fetched_from_server_normal, rows_fetched_from_server_ps | Connection | Total number of result set rows successfully fetched from MySQL regardless if the client application has consumed them or not. Some of the rows may not have been fetched by the client application but have been flushed implicitly. | See also packets_received_rset_row
rows_buffered_from_client_normal, rows_buffered_from_client_ps | Connection | Total number of successfully buffered rows originating from a "normal" query or a prepared statement. This is the number of rows that have been fetched from MySQL and buffered on client. Note that there are two distinct statistics on rows that have been buffered (MySQL to mysqlnd internal buffer) and buffered rows that have been fetched by the client application (mysqlnd internal buffer to client application). If the number of buffered rows is higher than the number of fetched buffered rows it can mean that the client application runs queries that cause larger result sets than needed resulting in rows not read by the client. | Examples of queries that will buffer results: mysqli_query(), mysqli_store_result()
rows_fetched_from_client_normal_buffered, rows_fetched_from_client_ps_buffered | Connection | Total number of rows fetched by the client from a buffered result set created by a normal query or a prepared statement.
rows_fetched_from_client_normal_unbuffered, rows_fetched_from_client_ps_unbuffered | Connection | Total number of rows fetched by the client from a unbuffered result set created by a "normal" query or a prepared statement.
rows_fetched_from_client_ps_cursor | Connection | Total number of rows fetch by the client from a cursor created by a prepared statement.
rows_skipped_normal, rows_skipped_ps | Connection | Reserved for future use (currently not supported)
copy_on_write_saved, copy_on_write_performed | Process | With mysqlnd, variables returned by the extensions point into mysqlnd internal network result buffers. If you do not change the variables, fetched data will be kept only once in memory. If you change the variables, mysqlnd has to perform a copy-on-write to protect the internal network result buffers from being changed. With the MySQL Client Library you always hold fetched data twice in memory. Once in the internal MySQL Client Library buffers and once in the variables returned by the extensions. In theory mysqlnd can save up to 40% memory. However, note that the memory saving cannot be measured using memory_get_usage().
explicit_free_result, implicit_free_result | Connection, Process (only during prepared statement cleanup) | Total number of freed result sets. | The free is always considered explicit but for result sets created by an init command, for example, mysqli_options(MYSQLI_INIT_COMMAND , ...)
proto_text_fetched_null, proto_text_fetched_bit, proto_text_fetched_tinyint proto_text_fetched_short, proto_text_fetched_int24, proto_text_fetched_int proto_text_fetched_bigint, proto_text_fetched_decimal, proto_text_fetched_float proto_text_fetched_double, proto_text_fetched_date, proto_text_fetched_year proto_text_fetched_time, proto_text_fetched_datetime, proto_text_fetched_timestamp proto_text_fetched_string, proto_text_fetched_blob, proto_text_fetched_enum proto_text_fetched_set, proto_text_fetched_geometry, proto_text_fetched_other Connection Total number of columns of a certain type fetched from a normal query (MySQL text protocol). Mapping from C API / MySQL meta data type to statistics name:

  • MYSQL_TYPE_NULL - proto_text_fetched_null

  • MYSQL_TYPE_BIT - proto_text_fetched_bit

  • MYSQL_TYPE_TINY - proto_text_fetched_tinyint

  • MYSQL_TYPE_SHORT - proto_text_fetched_short

  • MYSQL_TYPE_INT24 - proto_text_fetched_int24

  • MYSQL_TYPE_LONG - proto_text_fetched_int

  • MYSQL_TYPE_LONGLONG - proto_text_fetched_bigint

  • MYSQL_TYPE_DECIMAL, MYSQL_TYPE_NEWDECIMAL - proto_text_fetched_decimal

  • MYSQL_TYPE_FLOAT - proto_text_fetched_float

  • MYSQL_TYPE_DOUBLE - proto_text_fetched_double

  • MYSQL_TYPE_DATE, MYSQL_TYPE_NEWDATE - proto_text_fetched_date

  • MYSQL_TYPE_YEAR - proto_text_fetched_year

  • MYSQL_TYPE_TIME - proto_text_fetched_time

  • MYSQL_TYPE_DATETIME - proto_text_fetched_datetime

  • MYSQL_TYPE_TIMESTAMP - proto_text_fetched_timestamp

  • MYSQL_TYPE_STRING, MYSQL_TYPE_VARSTRING, MYSQL_TYPE_VARCHAR - proto_text_fetched_string

  • MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_BLOB - proto_text_fetched_blob

  • MYSQL_TYPE_ENUM - proto_text_fetched_enum

  • MYSQL_TYPE_SET - proto_text_fetched_set

  • MYSQL_TYPE_GEOMETRY - proto_text_fetched_geometry

  • Any MYSQL_TYPE_* not listed before (there should be none) - proto_text_fetched_other

Note that the MYSQL_*-type constants may not be associated with the very same SQL column types in every version of MySQL.

proto_binary_fetched_null, proto_binary_fetched_bit, proto_binary_fetched_tinyint proto_binary_fetched_short, proto_binary_fetched_int24, proto_binary_fetched_int, proto_binary_fetched_bigint, proto_binary_fetched_decimal, proto_binary_fetched_float, proto_binary_fetched_double, proto_binary_fetched_date, proto_binary_fetched_year, proto_binary_fetched_time, proto_binary_fetched_datetime, proto_binary_fetched_timestamp, proto_binary_fetched_string, proto_binary_fetched_blob, proto_binary_fetched_enum, proto_binary_fetched_set, proto_binary_fetched_geometry, proto_binary_fetched_other | Connection | Total number of columns of a certain type fetched from a prepared statement (MySQL binary protocol). | For type mapping see proto_text_* described in the preceding text.
Returned mysqlnd statistics: Connection
Statistic | Scope | Description | Notes
connect_success, connect_failure | Connection | Total number of successful / failed connection attempt. | Reused connections and all other kinds of connections are included.
reconnect | Process | Total number of (real_)connect attempts made on an already opened connection handle. | The code sequence $link = new mysqli(...); $link->real_connect(...) will cause a reconnect. But $link = new mysqli(...); $link->connect(...) will not because $link->connect(...) will explicitly close the existing connection before a new connection is established.
pconnect_success | Connection | Total number of successful persistent connection attempts. | Note that connect_success holds the sum of successful persistent and non-persistent connection attempts. The number of successful non-persistent connection attempts is connect_success - pconnect_success.
active_connections | Connection | Total number of active persistent and non-persistent connections.
active_persistent_connections | Connection | Total number of active persistent connections. | The total number of active non-persistent connections is active_connections - active_persistent_connections.
explicit_close Connection Total number of explicitly closed connections (ext/mysqli only). Examples of code snippets that cause an explicit close :
$link = new mysqli(...); $link->close(...)
$link = new mysqli(...); $link->connect(...)
implicit_close Connection Total number of implicitly closed connections (ext/mysqli only). 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 | Connection failures indicated by the C API call mysql_real_connect() during an attempt to establish a connection. | It is called disconnect_close because the connection handle passed to the C API call will be closed.
in_middle_of_command_close | Process | 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). | Unless you use asynchronous queries this should only happen if your script stops unexpectedly and PHP shuts down the connections for you.
init_command_executed_count | Connection | Total number of init command executions, for example, mysqli_options(MYSQLI_INIT_COMMAND , ...). | The number of successful executions is init_command_executed_count - init_command_failed_count.
init_command_failed_count | Connection | Total number of failed init commands.
Returned mysqlnd statistics: COM_* Command
Statistic Scope Description Notes
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 Connection 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. 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.

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

Returned mysqlnd statistics: Miscellaneous
Statistic | Scope | Description | Notes
explicit_stmt_close, implicit_stmt_close | Process | Total number of close prepared statements. | A close is always considered explicit but for a failed prepare.
mem_emalloc_count, mem_emalloc_ammount, mem_ecalloc_count, mem_ecalloc_ammount, mem_erealloc_count, mem_erealloc_ammount, mem_efree_count, mem_malloc_count, mem_malloc_ammount, mem_calloc_count, mem_calloc_ammount, mem_realloc_count, mem_realloc_ammount, mem_free_count | Process | Memory management calls. | Development only.
command_buffer_too_small Connection 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 (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 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 (php.ini) bytes for almost every connection, you should consider to increase the default size to avoid re-allocations.

The default buffer size is 2048 bytes in PHP 5.3.0. In future versions the default will be 4kB or larger. The default can changed either through the php.ini setting mysqlnd.net_cmd_buffer_size or using mysqli_options(MYSQLI_OPT_NET_CMD_BUFFER_SIZE, int size).

It is recommended to set the buffer size to no less than 4096 bytes because mysqlnd also uses it when reading certain communication packet from MySQL. In PHP 5.3.0, mysqlnd will not grow the buffer if MySQL sends a packet that is larger than the current size of the buffer. As a consequence mysqlnd is unable to decode the packet and the client application will get an error. There are only two situations when the packet can be larger than the 2048 bytes default of mysqlnd.net_cmd_buffer_size in PHP 5.3.0: the packet transports a very long error message or the packet holds column meta data from COM_LIST_FIELD (mysql_list_fields()) and the meta data comes from a string column with a very long default value (>1900 bytes). No bug report on this exists - it should happen rarely.

As of PHP 5.3.2 mysqlnd does not allow setting buffers smaller than 4096 bytes.

connection_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 noticible 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 is 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.

The copy mode can be enforced by setting mysqlnd.fetch_data_copy=1.

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.

The following table shows PHP versions and the corresponding mysqlnd version contained within.

The bundled mysqlnd version per PHP release
PHP Version | MySQL Native Driver version
5.3.0 | 5.0.5
5.3.1 | 5.0.5
5.3.2 | 5.0.7
5.3.3 | 5.0.7
5.3.4 | 5.0.7

Plugin developers can determine the mysqlnd version through accessing MYSQLND_VERSION, which is a string of the format mysqlnd 5.0.7-dev - 091210 - $Revision: 300535, 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.

Caution

Due to a bug in PHP versions 5.3.0 to 5.3.3, plugins do not associate plugin data with a persistent connection. This is because ext/mysql and ext/mysqli do not trigger all the necessary mysqlnd end_psession() method calls and the plugin may therefore leak memory. This has been fixed in PHP 5.3.4.


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

  1. mysqlnd_cache.query()

  2. mysqlnd.query

ext/mysqlnd_monitor mysqlnd_monitor.query()

  1. mysqlnd_monitor.query()

  2. mysqlnd_cache.query()

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

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


Mysqlnd replication and load balancing plugin

  • Introduction
  • Quickstart and Examples
    • Setup
    • Running statements
    • Connection state
    • SQL Hints
    • Local transactions
    • XA/Distributed Transactions
    • Service level and consistency
    • Global transaction IDs
    • Cache integration
    • Failover
    • Partitioning and Sharding
    • MySQL Fabric
  • Concepts
    • Architecture
    • Connection pooling and switching
    • Local transaction handling
    • Error handling
    • Transient errors
    • Failover
    • Load balancing
    • Read-write splitting
    • Filter
    • Service level and consistency
    • Global transaction IDs
    • Cache integration
    • Supported clusters
    • XA/Distributed transactions
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Plugin configuration file (>=1.1.x)
  • Predefined Constants
  • Mysqlnd_ms Functions
    • mysqlnd_ms_dump_servers — Returns a list of currently configured servers
    • mysqlnd_ms_fabric_select_global — Switch to global sharding server for a given table
    • mysqlnd_ms_fabric_select_shard — Switch to shard
    • mysqlnd_ms_get_last_gtid — Returns the latest global transaction ID
    • mysqlnd_ms_get_last_used_connection — Returns an array which describes the last used connection
    • mysqlnd_ms_get_stats — Returns query distribution and connection statistics
    • mysqlnd_ms_match_wild — Finds whether a table name matches a wildcard pattern or not
    • mysqlnd_ms_query_is_select — Find whether to send the query to the master, the slave or the last used MySQL server
    • mysqlnd_ms_set_qos — Sets the quality of service needed from the cluster
    • mysqlnd_ms_set_user_pick_server — Sets a callback for user-defined read/write splitting
    • mysqlnd_ms_xa_begin — Starts a distributed/XA transaction among MySQL servers
    • mysqlnd_ms_xa_commit — Commits a distributed/XA transaction among MySQL servers
    • mysqlnd_ms_xa_gc — Garbage collects unfinished XA transactions after severe errors
    • mysqlnd_ms_xa_rollback — Rolls back a distributed/XA transaction among MySQL servers
  • Change History
    • PECL/mysqlnd_ms 1.6 series
    • PECL/mysqlnd_ms 1.5 series
    • PECL/mysqlnd_ms 1.4 series
    • PECL/mysqlnd_ms 1.3 series
    • PECL/mysqlnd_ms 1.2 series
    • PECL/mysqlnd_ms 1.1 series
    • PECL/mysqlnd_ms 1.0 series


Introduction

The mysqlnd replication and load balancing plugin (mysqlnd_ms) adds easy to use MySQL replication support to all PHP MySQL extensions that use mysqlnd.

As of version PHP 5.3.3 the MySQL native driver for PHP (mysqlnd) features an internal plugin C API. C plugins, such as the replication and load balancing plugin, can extend the functionality of mysqlnd.

The MySQL native driver for PHP is a C library that ships together with PHP as of PHP 5.3.0. It serves as a drop-in replacement for the MySQL Client Library (libmysqlclient). Using mysqlnd has several advantages: no extra downloads are required because it's bundled with PHP, it's under the PHP license, there is lower memory consumption in certain cases, and it contains new functionality such as asynchronous queries.

Mysqlnd plugins like mysqlnd_ms operate, for the most part, transparently from a user perspective. The replication and load balancing plugin supports all PHP applications, and all MySQL PHP extensions. It does not change existing APIs. Therefore, it can easily be used with existing PHP applications.

Key Features

The key features of PECL/mysqlnd_ms are as follows.

  • Transparent and therefore easy to use.

    • Supports all of the PHP MySQL extensions.

    • SSL support.

    • A consistent API.

    • Little to no application changes required, dependent on the required usage scenario.

    • Lazy connections: connections to master and slave servers are not opened before a SQL statement is executed.

    • Optional: automatic use of master after the first write in a web request, to lower the possible impact of replication lag.

  • Can be used with any MySQL clustering solution.

    • MySQL Replication: Read-write splitting is done by the plugin. Primary focus of the plugin.

    • MySQL Cluster: Read-write splitting can be disabled. Configuration of multiple masters possible

    • Third-party solutions: the plugin is optimized for MySQL Replication but can be used with any other kind of MySQL clustering solution.

  • Featured read-write split strategies

    • Automatic detection of SELECT.

    • Supports SQL hints to overrule automatism.

    • User-defined.

    • Can be disabled for, for example, when using synchronous clusters such as MySQL Cluster.

  • Featured load balancing strategies

    • Round Robin: choose a different slave in round-robin fashion for every slave request.

    • Random: choose a random slave for every slave request.

    • Random once (sticky): choose a random slave once to run all slave requests for the duration of a web request.

    • User-defined. The application can register callbacks with mysqlnd_ms.

    • PHP 5.4.0 or newer: transaction aware when using API calls only to control transactions.

    • Weighted load balancing: servers can be assigned different priorities, for example, to direct more requests to a powerful machine than to another less powerful machine. Or, to prefer nearby machines to reduce latency.

  • Global transaction ID

    • Client-side emulation. Makes manual master server failover and slave promotion easier with asynchronous clusters, such as MySQL Replication.

    • Support for built-in global transaction identifier feature of MySQL 5.6.5 or newer.

    • Supports using transaction ids to identify up-to-date asynchronous slaves for reading when session consistency is required. Please, note the restrictions mentioned in the manual.

    • Throttling: optionally, the plugin can wait for a slave to become "synchronous" before continuing.

  • Service and consistency levels

    • Applications can request eventual, session and strong consistency service levels for connections. Appropriate cluster nodes will be searched automatically.

    • Eventual consistent MySQL Replication slave accesses can be replaced with fast local cache accesses transparently to reduce server load.

  • Partitioning and sharding

    • Servers of a replication cluster can be organized into groups. SQL hints can be used to manually direct queries to a specific group. Grouping can be used to partition (shard) the data, or to cure the issue of hotspots with updates.

    • MySQL Replication filters are supported through the table filter.

  • MySQL Fabric

    • Experimental support for MySQL Fabric is included.

Limitations

The built-in read-write-split mechanism is very basic. Every query which starts with SELECT is considered a read request to be sent to a MySQL slave server. All other queries (such as SHOW statements) are considered as write requests that are sent to the MySQL master server. The build-in behavior can be overruled using SQL hints, or a user-defined callback function.

The read-write splitter is not aware of multi-statements. Multi-statements are considered as one statement. The decision of where to run the statement will be based on the beginning of the statement string. For example, if using mysqli_multi_query() to execute the multi-statement SELECT id FROM test ; INSERT INTO test(id) VALUES (1), the statement will be redirected to a slave server because it begins with SELECT. The INSERT statement, which is also part of the multi-statement, will not be redirected to a master server.

Note:

Applications must be aware of the consequences of connection switches that are performed for load balancing purposes. Please check the documentation on connection pooling and switching, transaction handling, failover load balancing and read-write splitting.

On the name

The shortcut mysqlnd_ms stands for mysqlnd master slave plugin. The name was chosen for a quick-and-dirty proof-of-concept. In the beginning the developers did not expect to continue using the code base.


Quickstart and Examples

Table of Contents

  • Setup
  • Running statements
  • Connection state
  • SQL Hints
  • Local transactions
  • XA/Distributed Transactions
  • Service level and consistency
  • Global transaction IDs
  • Cache integration
  • Failover
  • Partitioning and Sharding
  • MySQL Fabric

The mysqlnd replication load balancing plugin is easy to use. This quickstart will demo typical use-cases, and provide practical advice on getting started.

It is strongly recommended to read the reference sections in addition to the quickstart. The quickstart tries to avoid discussing theoretical concepts and limitations. Instead, it will link to the reference sections. It is safe to begin with the quickstart. However, before using the plugin in mission critical environments we urge you to read additionally the background information from the reference sections.

The focus is on using PECL mysqlnd_ms for work with an asynchronous MySQL cluster, namely MySQL replication. Generally speaking an asynchronous cluster is more difficult to use than a synchronous one. Thus, users of, for example, MySQL Cluster will find more information than needed.


Setup

The plugin is implemented as a PHP extension. See also the installation instructions to install the » PECL/mysqlnd_ms extension.

Compile or configure the PHP MySQL extension (API) (mysqli, PDO_MYSQL, mysql) that you plan to use with support for the mysqlnd library. PECL/mysqlnd_ms is a plugin for the mysqlnd library. To use the plugin with any of the PHP MySQL extensions, the extension has to use the mysqlnd library.

Then, load the extension into PHP and activate the plugin in the PHP configuration file using the PHP configuration directive named mysqlnd_ms.enable.

Example #1 Enabling the plugin (php.ini)

mysqlnd_ms.enable=1
mysqlnd_ms.config_file=/path/to/mysqlnd_ms_plugin.ini

The plugin uses its own configuration file. Use the PHP configuration directive mysqlnd_ms.config_file to set the full file path to the plugin-specific configuration file. This file must be readable by PHP (e.g., the web server user). Please note, the configuration directive mysqlnd_ms.config_file superseeds mysqlnd_ms.ini_file since 1.4.0. It is a common pitfall to use the old, no longer available configuration directive.

Create a plugin-specific configuration file. Save the file to the path set by the PHP configuration directive mysqlnd_ms.config_file.

The plugins configuration file is JSON based. It is divided into one or more sections. Each section has a name, for example, myapp. Every section makes its own set of configuration settings.

A section must, at a minimum, list the MySQL replication master server, and set a list of slaves. The plugin supports using only one master server per section. Multi-master MySQL replication setups are not yet fully supported. Use the configuration setting master to set the hostname, and the port or socket of the MySQL master server. MySQL slave servers are configured using the slave keyword.

Example #2 Minimal plugin-specific configuration file (mysqlnd_ms_plugin.ini)

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": [

        ]
    }
}

Configuring a MySQL slave server list is required, although it may contain an empty list. It is recommended to always configure at least one slave server.

Server lists can use anonymous or non-anonymous syntax. Non-anonymous lists include alias names for the servers, such as master_0 for the master in the above example. The quickstart uses the more verbose non-anonymous syntax.

Example #3 Recommended minimal plugin-specific config (mysqlnd_ms_plugin.ini)

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.2.27",
                "port": "3306"
            }
        }
    }
}

If there are at least two servers in total, the plugin can start to load balance and switch connections. Switching connections is not always transparent and can cause issues in certain cases. The reference sections about connection pooling and switching, transaction handling, fail over load balancing and read-write splitting all provide more details. And potential pitfalls are described later in this guide.

It is the responsibility of the application to handle potential issues caused by connection switches, by configuring a master with at least one slave server, which allows switching to work therefore related problems can be found.

The MySQL master and MySQL slave servers, which you configure, do not need to be part of MySQL replication setup. For testing purpose you can use single MySQL server and make it known to the plugin as a master and slave server as shown below. This could help you to detect many potential issues with connection switches. However, such a setup will not be prone to the issues caused by replication lag.

Example #4 Using one server as a master and as a slave (testing only!)

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "127.0.0.1",
                "port": "3306"
            }
        }
    }
}

The plugin attempts to notify you of invalid configurations. Since 1.5.0 it will throw a warning during PHP startup if the configuration file cannot be read, is empty or parsing the JSON failed. Depending on your PHP settings those errors may appear in some log files only. Further validation is done when a connection is to be established and the configuration file is searched for valid sections. Setting mysqlnd_ms.force_config_usage may help debugging a faulty setup. Please, see also configuration file debugging notes.


Running statements

The plugin can be used with any PHP MySQL extension (mysqli, mysql, and PDO_MYSQL) that is compiled to use the mysqlnd library. PECL/mysqlnd_ms plugs into the mysqlnd library. It does not change the API or behavior of those extensions.

Whenever a connection to MySQL is being opened, the plugin compares the host parameter value of the connect call, with the section names from the plugin specific configuration file. If, for example, the plugin specific configuration file has a section myapp then the section should be referenced by opening a MySQL connection to the host myapp

Example #1 Plugin specific configuration file (mysqlnd_ms_plugin.ini)

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.2.27",
                "port": "3306"
            }
        }
    }
}

Example #2 Opening a load balanced connection

<?php
/* Load balanced following "myapp" section rules from the plugins config file */
$mysqli = new mysqli("myapp", "username", "password", "database");
$pdo = new PDO('mysql:host=myapp;dbname=database', 'username', 'password');
$mysql = mysql_connect("myapp", "username", "password");
?>

The connection examples above will be load balanced. The plugin will send read-only statements to the MySQL slave server with the IP 192.168.2.27 and will listen on port 3306 for the MySQL client connection. All other statements will be directed to the MySQL master server running on the host localhost. If on Unix like operating systems, the master on localhost will be accepting MySQL client connections on the Unix domain socket /tmp/mysql.sock, while TCP/IP is the default port on Windows. The plugin will use the user name username and the password password to connect to any of the MySQL servers listed in the section myapp of the plugins configuration file. Upon connect, the plugin will select database as the current schemata.

The username, password and schema name are taken from the connect API calls and used for all servers. In other words: you must use the same username and password for every MySQL server listed in a plugin configuration file section. The is not a general limitation. As of PECL/mysqlnd_ms 1.1.0, it is possible to set the username and password for any server in the plugins configuration file, to be used instead of the credentials passed to the API call.

The plugin does not change the API for running statements. Read-write splitting works out of the box. The following example assumes that there is no significant replication lag between the master and the slave.

Example #3 Executing statements

<?php
/* Load balanced following "myapp" section rules from the plugins config file */
$mysqli = new mysqli("myapp", "username", "password", "database");
if (mysqli_connect_errno()) {
    /* Of course, your error handling is nicer... */
    die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));
}

/* Statements will be run on the master */
if (!$mysqli->query("DROP TABLE IF EXISTS test")) {
    printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}
if (!$mysqli->query("CREATE TABLE test(id INT)")) {
    printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}
if (!$mysqli->query("INSERT INTO test(id) VALUES (1)")) {
    printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}

/* read-only: statement will be run on a slave */
if (!($res = $mysqli->query("SELECT id FROM test"))) {
    printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
} else {
    $row = $res->fetch_assoc();
    $res->close();
    printf("Slave returns id = '%s'\n", $row['id']);
}
$mysqli->close();
?>

The above example will output something similar to:

Slave returns id = '1'


Connection state

The plugin changes the semantics of a PHP MySQL connection handle. A new connection handle represents a connection pool, instead of a single MySQL client-server network connection. The connection pool consists of a master connection, and optionally any number of slave connections.

Every connection from the connection pool has its own state. For example, SQL user variables, temporary tables and transactions are part of the state. For a complete list of items that belong to the state of a connection, see the connection pooling and switching concepts documentation. If the plugin decides to switch connections for load balancing, the application could be given a connection which has a different state. Applications must be made aware of this.

Example #1 Plugin config with one slave and one master

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.2.27",
                "port": "3306"
            }
        }
    }
}

Example #2 Pitfall: connection state and SQL user variables

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli) {
    /* Of course, your error handling is nicer... */
    die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));
}

/* Connection 1, connection bound SQL user variable, no SELECT thus run on master */
if (!$mysqli->query("SET @myrole='master'")) {
    printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}

/* Connection 2, run on slave because SELECT */
if (!($res = $mysqli->query("SELECT @myrole AS _role"))) {
    printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
} else {
    $row = $res->fetch_assoc();
    $res->close();
    printf("@myrole = '%s'\n", $row['_role']);
}
$mysqli->close();
?>

The above example will output:

@myrole = ''

The example opens a load balanced connection and executes two statements. The first statement SET @myrole='master' does not begin with the string SELECT. Therefore the plugin does not recognize it as a read-only query which shall be run on a slave. The plugin runs the statement on the connection to the master. The statement sets a SQL user variable which is bound to the master connection. The state of the master connection has been changed.

The next statement is SELECT @myrole AS _role. The plugin does recognize it as a read-only query and sends it to the slave. The statement is run on a connection to the slave. This second connection does not have any SQL user variables bound to it. It has a different state than the first connection to the master. The requested SQL user variable is not set. The example script prints @myrole = ''.

It is the responsibility of the application developer to take care of the connection state. The plugin does not monitor all connection state changing activities. Monitoring all possible cases would be a very CPU intensive task, if it could be done at all.

The pitfalls can easily be worked around using SQL hints.


SQL Hints

SQL hints can force a query to choose a specific server from the connection pool. It gives the plugin a hint to use a designated server, which can solve issues caused by connection switches and connection state.

SQL hints are standard compliant SQL comments. Because SQL comments are supposed to be ignored by SQL processing systems, they do not interfere with other programs such as the MySQL Server, the MySQL Proxy, or a firewall.

Three SQL hints are supported by the plugin: The MYSQLND_MS_MASTER_SWITCH hint makes the plugin run a statement on the master, MYSQLND_MS_SLAVE_SWITCH enforces the use of the slave, and MYSQLND_MS_LAST_USED_SWITCH will run a statement on the same server that was used for the previous statement.

The plugin scans the beginning of a statement for the existence of an SQL hint. SQL hints are only recognized if they appear at the beginning of the statement.

Example #1 Plugin config with one slave and one master

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.2.27",
                "port": "3306"
            }
        }
    }
}

Example #2 SQL hints to prevent connection switches

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (mysqli_connect_errno()) {
    /* Of course, your error handling is nicer... */
    die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));
}

/* Connection 1, connection bound SQL user variable, no SELECT thus run on master */
if (!$mysqli->query("SET @myrole='master'")) {
    printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}

/* Connection 1, run on master because of SQL hint */
if (!($res = $mysqli->query(sprintf("/*%s*/SELECT @myrole AS _role", MYSQLND_MS_LAST_USED_SWITCH)))) {
    printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
} else {
    $row = $res->fetch_assoc();
    $res->close();
    printf("@myrole = '%s'\n", $row['_role']);
}
$mysqli->close();
?>

The above example will output:

@myrole = 'master'

In the above example, using MYSQLND_MS_LAST_USED_SWITCH prevents session switching from the master to a slave when running the SELECT statement.

SQL hints can also be used to run SELECT statements on the MySQL master server. This may be desired if the MySQL slave servers are typically behind the master, but you need current data from the cluster.

In version 1.2.0 the concept of a service level has been introduced to address cases when current data is required. Using a service level requires less attention and removes the need of using SQL hints for this use case. Please, find more information below in the service level and consistency section.

Example #3 Fighting replication lag

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli) {
    /* Of course, your error handling is nicer... */
    die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));
}

/* Force use of master, master has always fresh and current data */
if (!$mysqli->query(sprintf("/*%s*/SELECT critical_data FROM important_table", MYSQLND_MS_MASTER_SWITCH))) {
    printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}
?>

A use case may include the creation of tables on a slave. If an SQL hint is not given, then the plugin will send CREATE and INSERT statements to the master. Use the SQL hint MYSQLND_MS_SLAVE_SWITCH if you want to run any such statement on a slave, for example, to build temporary reporting tables.

Example #4 Table creation on a slave

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli) {
    /* Of course, your error handling is nicer... */
    die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));
}

/* Force use of slave */
if (!$mysqli->query(sprintf("/*%s*/CREATE TABLE slave_reporting(id INT)", MYSQLND_MS_SLAVE_SWITCH))) {
    printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}
/* Continue using this particular slave connection */
if (!$mysqli->query(sprintf("/*%s*/INSERT INTO slave_reporting(id) VALUES (1), (2), (3)", MYSQLND_MS_LAST_USED_SWITCH))) {
    printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}
/* Don't use MYSQLND_MS_SLAVE_SWITCH which would allow switching to another slave! */
if ($res = $mysqli->query(sprintf("/*%s*/SELECT COUNT(*) AS _num FROM slave_reporting", MYSQLND_MS_LAST_USED_SWITCH))) {
    $row = $res->fetch_assoc();
    $res->close();
    printf("There are %d rows in the table 'slave_reporting'", $row['_num']);
} else {
    printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}
$mysqli->close();
?>

The SQL hint MYSQLND_MS_LAST_USED forbids switching a connection, and forces use of the previously used connection.


Local transactions

The current version of the plugin is not transaction safe by default, because it is not aware of running transactions in all cases. SQL transactions are units of work to be run on a single server. The plugin does not always know when the unit of work starts and when it ends. Therefore, the plugin may decide to switch connections in the middle of a transaction.

No kind of MySQL load balancer can detect transaction boundaries without any kind of hint from the application.

You can either use SQL hints to work around this limitation. Alternatively, you can activate transaction API call monitoring. In the latter case you must use API calls only to control transactions, see below.

Example #1 Plugin config with one slave and one master

[myapp]
{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.2.27",
                "port": "3306"
            }
        }
    }
}

Example #2 Using SQL hints for transactions

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli) {
    /* Of course, your error handling is nicer... */
    die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));
}

/* Not a SELECT, will use master */
if (!$mysqli->query("START TRANSACTION")) {
    /* Please use better error handling in your code */
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* Prevent connection switch! */
if (!$mysqli->query(sprintf("/*%s*/INSERT INTO test(id) VALUES (1)", MYSQLND_MS_LAST_USED_SWITCH))) {
    /* Please do proper ROLLBACK in your code, don't just die */
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
if ($res = $mysqli->query(sprintf("/*%s*/SELECT COUNT(*) AS _num FROM test", MYSQLND_MS_LAST_USED_SWITCH))) {
    $row = $res->fetch_assoc();
    $res->close();
    if ($row['_num'] > 1000) {
        if (!$mysqli->query(sprintf("/*%s*/INSERT INTO events(task) VALUES ('cleanup')", MYSQLND_MS_LAST_USED_SWITCH))) {
            die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
        }
    }
} else {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
if (!$mysqli->query(sprintf("/*%s*/UPDATE log SET last_update = NOW()", MYSQLND_MS_LAST_USED_SWITCH))) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
if (!$mysqli->query(sprintf("/*%s*/COMMIT", MYSQLND_MS_LAST_USED_SWITCH))) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

$mysqli->close();
?>

Starting with PHP 5.4.0, the mysqlnd library allows the plugin to monitor the status of the autocommit mode, if the mode is set by API calls instead of using SQL statements such as SET AUTOCOMMIT=0. This makes it possible for the plugin to become transaction aware. In this case, you do not need to use SQL hints.

If using PHP 5.4.0 or newer, API calls that enable autocommit mode, and when setting the plugin configuration option trx_stickiness=master, the plugin can automatically disable load balancing and connection switches for SQL transactions. In this configuration, the plugin stops load balancing if autocommit is disabled and directs all statements to the master. This prevents connection switches in the middle of a transaction. Once autocommit is re-enabled, the plugin starts to load balance statements again.

API based transaction boundary detection has been improved with PHP 5.5.0 and PECL/mysqlnd_ms 1.5.0 to cover not only calls to mysqli_autocommit() but also mysqli_begin(), mysqli_commit() and mysqli_rollback().

Example #3 Transaction aware load balancing: trx_stickiness setting

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "127.0.0.1",
                "port": "3306"
            }
        },
        "trx_stickiness": "master"
    }
}

Example #4 Transaction aware

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli) {
    /* Of course, your error handling is nicer... */
    die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));
}

/* Disable autocommit, plugin will run all statements on the master */
$mysqli->autocommit(false);

if (!$mysqli->query("INSERT INTO test(id) VALUES (1)")) {
    /* Please do proper ROLLBACK in your code, don't just die */
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
if ($res = $mysqli->query("SELECT COUNT(*) AS _num FROM test")) {
    $row = $res->fetch_assoc();
    $res->close();
    if ($row['_num'] > 1000) {
        if (!$mysqli->query("INSERT INTO events(task) VALUES ('cleanup')")) {
            die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
        }
    }
} else {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
if (!$mysqli->query("UPDATE log SET last_update = NOW()")) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
if (!$mysqli->commit()) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* Plugin assumes that the transaction has ended and starts load balancing again */
$mysqli->autocommit(true);
$mysqli->close();
?>

Note: Version requirement

The plugin configuration option trx_stickiness=master requires PHP 5.4.0 or newer.

Please note the restrictions outlined in the transaction handling concepts section.


XA/Distributed Transactions

Note: Version requirement

XA related functions have been introduced in PECL mysqlnd_ms version 1.6.0-alpha.

Note: Early adaptors wanted

The feature is currently under development. There may be issues and/or feature limitations. Do not use in production environments, although early lab tests indicate reasonable quality.

Please, contact the development team if you are interested in this feature. We are looking for real life feedback to complement the feature.

XA transactions are a standardized method for executing transactions across multiple resources. Those resources can be databases or other transactional systems. The MySQL server supports XA SQL statements which allows users to carry out a distributed SQL transaction that spawns multiple database servers or any kind as long as they support the SQL statements too. In such a scenario it is in the responsibility of the user to coordinate the participating servers.

PECL/mysqlnd_ms can act as a transaction coordinator for a global (distributed, XA) transaction carried out on MySQL servers only. As a transaction coordinator, the plugin tracks all servers involved in a global transaction and transparently issues appropriate SQL statements on the participants. The global transactions are controlled with mysqlnd_ms_xa_begin(), mysqlnd_ms_xa_commit() and mysqlnd_ms_xa_rollback(). SQL details are mostly hidden from the application as is the need to track and coordinate participants.

Example #1 General pattern for XA transactions

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli) {
    /* Of course, your error handling is nicer... */
    die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));
}

/* start a global transaction */
$gtrid_id = "12345";
if (!mysqlnd_ms_xa_begin($mysqli, $gtrid_id)) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* run queries as usual: XA BEGIN will be injected upon running a query */
if (!$mysqli->query("INSERT INTO orders(order_id, item) VALUES (1, 'christmas tree, 1.8m')")) {
    /* Either INSERT failed or the injected XA BEGIN failed */
    if ('XA' == substr($mysqli->sqlstate, 0, 2)) {
        printf("Global transaction/XA related failure, [%d] %s\n", $mysqli->errno, $mysqli->error);
    } else {
        printf("INSERT failed, [%d] %s\n", $mysqli->errno, $mysqli->error);
    }
    /* rollback global transaction */
    mysqlnd_ms_xa_rollback($mysqli, $xid);
    die("Stopping.");
}

/* continue carrying out queries on other servers, e.g. other shards */

/* commit the global transaction */
if (!mysqlnd_ms_xa_commit($mysqli, $xa_id)) {
    printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}
?>

Unlike with local transactions, which are carried out on a single server, XA transactions have an identifier (xid) associated with them. The XA transaction identifier is composed of a global transaction identifier (gtrid), a branch qualifier (bqual) a format identifier (formatID). Only the global transaction identifier can and must be given when calling any of the plugins XA functions.

Once a global transaction has been started, the plugin begins tracking servers until the global transaction ends. When a server is picked for query execution, the plugin injects the SQL statement XA BEGIN prior to executing the actual SQL statement on the server. XA BEGIN makes the server participate in the global transaction. If the injected SQL statement fails, the plugin will report the issue in reply to the query execution function that was used. In the above example, $mysqli->query("INSERT INTO orders(order_id, item) VALUES (1, 'christmas tree, 1.8m')") would indicate such an error. You may want to check the errors SQL state code to determine whether the actual query (here: INSERT) has failed or the error is related to the global transaction. It is up to you to ignore the failure to start the global transaction on a server and continue execution without having the server participate in the global transaction.

Example #2 Local and global transactions are mutually exclusive

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli) {
    /* Of course, your error handling is nicer... */
    die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));
}

/* start a local transaction */
if (!$mysqli->begin_transaction()) {
    die(sprintf("[%d/%s] %s\n", $mysqli->errno, $mysqli->sqlstate, $mysqli->error));
}

/* cannot start global transaction now - must end local transaction first */
$gtrid_id = "12345";
if (!mysqlnd_ms_xa_begin($mysqli, $gtrid_id)) {
    die(sprintf("[%d/%s] %s\n", $mysqli->errno, $mysqli->sqlstate, $mysqli->error));
}
?>

The above example will output:

Warning: mysqlnd_ms_xa_begin(): (mysqlnd_ms) Some work is done outside global transaction. You must end the active local transaction first in ... on line ...
[1400/XAE09] (mysqlnd_ms) Some work is done outside global transaction. You must end the active local transaction first

A global transaction cannot be started when a local transaction is active. The plugin tries to detect this situation as early as possible, that is when mysqlnd_ms_xa_begin() is called. If using API calls only to control transactions, the plugin will know that a local transaction is open and return an error for mysqlnd_ms_xa_begin(). However, note the plugins limitations on detecting transaction boundaries.. In the worst case, if using direct SQL for local transactions (BEGIN, COMMIT, ...), it may happen that an error is delayed until some SQL is executed on a server.

To end a global transaction invoke mysqlnd_ms_xa_commit() or mysqlnd_ms_xa_rollback(). When a global transaction is ended all participants must be informed of the end. Therefore, PECL/mysqlnd_ms transparently issues appropriate XA related SQL statements on some or all of them. Any failure during this phase will cause an implicit rollback. The XA related API is intentionally kept simple here. A more complex API that gave more control would bare few, if any, advantages over a user implementation that issues all lower level XA SQL statements itself.

XA transactions use the two-phase commit protocol. The two-phase commit protocol is a blocking protocol. There are cases when no progress can be made, not even when using timeouts. Transaction coordinators should survive their own failure, be able to detect blockades and break ties. PECL/mysqlnd_ms takes the role of a transaction coordinator and can be configured to survive its own crash to avoid issues with blocked MySQL servers. Therefore, the plugin can and should be configured to use a persistent and crash-safe state to allow garbage collection of unfinished, aborted global transactions. A global transaction can be aborted in an open state if either the plugin fails (crashes) or a connection from the plugin to a global transaction participant fails.

Example #3 Transaction coordinator state store

{
    "myapp": {
        "xa": {
            "state_store": {
                "participant_localhost_ip": "192.168.2.12",
                "mysql": {
                    "host": "192.168.2.13",
                    "user": "root",
                    "password": "",
                    "db": "test",
                    "port": "3312",
                    "socket": null
                }
            }
        },
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.2.14",
                "port": "3306"
            }
        }
    }
}

Currently, PECL/mysqlnd_ms supports only using MySQL database tables as a state store. The SQL definitions of the tables are given in the plugin configuration section. Please, make sure to use a transactional and crash-safe storage engine for the tables, such as InnoDB. InnoDB is the default table engine in recent versions of the MySQL server. Make also sure the database server itself is highly available.

If a state store has been configured, the plugin can perform a garbage collection. During garbage collection it may be necessary to connect to a participant of a failed global transaction. Thus, the state store holds a list of participants and, among others, their host names. If the garbage collection is run on another host but the one that has written a participant entry with the host name localhost, then localhost resolves to different machines. There are two solutions to the problem. Either you do not configure any servers with the host name localhost but configure an IP address (and port) or, you hint the garbage collection. In the above example, localhost is used for master_0, hence it may not resolve to the correct host during garbage collection. However, participant_localhost_ip is also set to hint the garbage collection that localhost stands for the IP 192.168.2.12.


Service level and consistency

Note: Version requirement

Service levels have been introduced in PECL mysqlnd_ms version 1.2.0-alpha. mysqlnd_ms_set_qos() is available with PHP 5.4.0 or newer.

Different types of MySQL cluster solutions offer different service and data consistency levels to their users. An asynchronous MySQL replication cluster offers eventual consistency by default. A read executed on an asynchronous slave may return current, stale or no data at all, depending on whether the slave has replayed all changesets from the master or not.

Applications using an MySQL replication cluster need to be designed to work correctly with eventual consistent data. In some cases, however, stale data is not acceptable. In those cases only certain slaves or even only master accesses are allowed to achieve the required quality of service from the cluster.

As of PECL mysqlnd_ms 1.2.0 the plugin is capable of selecting MySQL replication nodes automatically that deliver session consistency or strong consistency. Session consistency means that one client can read its writes. Other clients may or may not see the clients' write. Strong consistency means that all clients will see all writes from the client.

Example #1 Session consistency: read your writes

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "127.0.0.1",
                "port": "3306"
            }
        }
    }
}

Example #2 Requesting session consistency

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli) {
    /* Of course, your error handling is nicer... */
    die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));
}

/* read-write splitting: master used */
if (!$mysqli->query("INSERT INTO orders(order_id, item) VALUES (1, 'christmas tree, 1.8m')")) {
    /* Please use better error handling in your code */
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* Request session consistency: read your writes */
if (!mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_SESSION)) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* Plugin picks a node which has the changes, here: master */
if (!$res = $mysqli->query("SELECT item FROM orders WHERE order_id = 1")) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

var_dump($res->fetch_assoc());

/* Back to eventual consistency: stale data allowed */
if (!mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL)) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* Plugin picks any slave, stale data is allowed */
if (!$res = $mysqli->query("SELECT item, price FROM specials")) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
?>

Service levels can be set in the plugins configuration file and at runtime using mysqlnd_ms_set_qos(). In the example the function is used to enforce session consistency (read your writes) for all future statements until further notice. The SELECT statement on the orders table is run on the master to ensure the previous write can be seen by the client. Read-write splitting logic has been adapted to fulfill the service level.

After the application has read its changes from the orders table it returns to the default service level, which is eventual consistency. Eventual consistency puts no restrictions on choosing a node for statement execution. Thus, the SELECT statement on the specials table is executed on a slave.

The new functionality supersedes the use of SQL hints and the master_on_write configuration option. In many cases mysqlnd_ms_set_qos() is easier to use, more powerful improves portability.

Example #3 Maximum age/slave lag

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "127.0.0.1",
                "port": "3306"
            }
        },
        "failover" : "master"
    }
}

Example #4 Limiting slave lag

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli) {
    /* Of course, your error handling is nicer... */
    die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));
}

/* Read from slaves lagging no more than four seconds */
$ret = mysqlnd_ms_set_qos(
    $mysqli,
    MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL,
    MYSQLND_MS_QOS_OPTION_AGE,
    4
);

if (!$ret) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* Plugin picks any slave, which may or may not have the changes */
if (!$res = $mysqli->query("SELECT item, price FROM daytrade")) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* Back to default: use of all slaves and masters permitted */
if (!mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL)) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
?>

The eventual consistency service level can be used with an optional parameter to set a maximum slave lag for choosing slaves. If set, the plugin checks SHOW SLAVE STATUS for all configured slaves. In case of the example, only slaves for which Slave_IO_Running=Yes, Slave_SQL_Running=Yes and Seconds_Behind_Master <= 4 is true are considered for executing the statement SELECT item, price FROM daytrade.

Checking SHOW SLAVE STATUS is done transparently from an applications perspective. Errors, if any, are reported as warnings. No error will be set on the connection handle. Even if all SHOW SLAVE STATUS SQL statements executed by the plugin fail, the execution of the users statement is not stopped, given that master fail over is enabled. Thus, no application changes are required.

Note: Expensive and slow operation

Checking SHOW SLAVE STATUS for all slaves adds overhead to the application. It is an expensive and slow background operation. Try to minimize the use of it. Unfortunately, a MySQL replication cluster does not give clients the possibility to request a list of candidates from a central instance. Thus, a more efficient way of checking the slaves lag is not available.

Please, note the limitations and properties of SHOW SLAVE STATUS as explained in the MySQL reference manual.

To prevent mysqlnd_ms from emitting a warning if no slaves can be found that lag no more than the defined number of seconds behind the master, it is necessary to enable master fail over in the plugins configuration file. If no slaves can be found and fail over is turned on, the plugin picks a master for executing the statement.

If no slave can be found and fail over is turned off, the plugin emits a warning, it does not execute the statement and it sets an error on the connection.

Example #5 Fail over not set

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "127.0.0.1",
                "port": "3306"
            }
        }
    }
}

Example #6 No slave within time limit

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli) {
    /* Of course, your error handling is nicer... */
    die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));
}

/* Read from slaves lagging no more than four seconds */
$ret = mysqlnd_ms_set_qos(
    $mysqli,
    MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL,
    MYSQLND_MS_QOS_OPTION_AGE,
    4
);

if (!$ret) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* Plugin picks any slave, which may or may not have the changes */
if (!$res = $mysqli->query("SELECT item, price FROM daytrade")) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* Back to default: use of all slaves and masters permitted */
if (!mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL)) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
?>

The above example will output:

PHP Warning:  mysqli::query(): (mysqlnd_ms) Couldn't find the appropriate slave connection. 0 slaves to choose from. Something is wrong in %s on line %d
PHP Warning:  mysqli::query(): (mysqlnd_ms) No connection selected by the last filter in %s on line %d
[2000] (mysqlnd_ms) No connection selected by the last filter


Global transaction IDs

Note: Version requirement

A client-side global transaction ID injection has been introduced in mysqlnd_ms version 1.2.0-alpha. The feature is not required for synchronous clusters, such as MySQL Cluster. Use it with asynchronous clusters such as classical MySQL replication.

As of MySQL 5.6.5-m8 release candidate the MySQL server features built-in global transaction identifiers. The MySQL built-in global transaction ID feature is supported by PECL/mysqlnd_ms 1.3.0-alpha or later. However, the final feature set found in MySQL 5.6 production releases to date is not sufficient to support the ideas discussed below in all cases. Please, see also the concepts section.

PECL/mysqlnd_ms can either use its own global transaction ID emulation or the global transaction ID feature built-in to MySQL 5.6.5-m8 or later. From a developer perspective the client-side and server-side approach offer the same features with regards to service levels provided by PECL/mysqlnd_ms. Their differences are discussed in the concepts section.

The quickstart first demonstrates the use of the client-side global transaction ID emulation built-in to PECL/mysqlnd_ms before its show how to use the server-side counterpart. The order ensures that the underlying idea is discussed first.

Idea and client-side emulation

In its most basic form a global transaction ID (GTID) is a counter in a table on the master. The counter is incremented whenever a transaction is committed on the master. Slaves replicate the table. The counter serves two purposes. In case of a master failure, it helps the database administrator to identify the most recent slave for promoting it to the new master. The most recent slave is the one with the highest counter value. Applications can use the global transaction ID to search for slaves which have replicated a certain write (identified by a global transaction ID) already.

PECL/mysqlnd_ms can inject SQL for every committed transaction to increment a GTID counter. The so created GTID is accessible by the application to identify an applications write operation. This enables the plugin to deliver session consistency (read your writes) service level by not only querying masters but also slaves which have replicated the change already. Read load is taken away from the master.

Client-side global transaction ID emulation has some limitations. Please, read the concepts section carefully to fully understand the principles and ideas behind it, before using in production environments. The background knowledge is not required to continue with the quickstart.

First, create a counter table on your master server and insert a record into it. The plugin does not assist creating the table. Database administrators must make sure it exists. Depending on the error reporting mode, the plugin will silently ignore the lack of the table or bail out.

Example #1 Create counter table on master

CREATE TABLE `trx` (
  `trx_id` int(11) DEFAULT NULL,
  `last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1
INSERT INTO `trx`(`trx_id`) VALUES (1);

In the plugins configuration file set the SQL to update the global transaction ID table using on_commit from the global_transaction_id_injection section. Make sure the table name used for the UPDATE statement is fully qualified. In the example, test.trx is used to refer to table trx in the schema (database) test. Use the table that was created in the previous step. It is important to set the fully qualified table name because the connection on which the injection is done may use a different default database. Make sure the user that opens the connection is allowed to execute the UPDATE.

Enable reporting of errors that may occur when mysqlnd_ms does global transaction ID injection.

Example #2 Plugin config: SQL for client-side GTID injection

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "127.0.0.1",
                "port": "3306"
            }
        },
        "global_transaction_id_injection":{
            "on_commit":"UPDATE test.trx SET trx_id = trx_id + 1",
            "report_error":true
        }
    }
}

Example #3 Transparent global transaction ID injection

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli) {
    /* Of course, your error handling is nicer... */
    die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));
}

/* auto commit mode, transaction on master, GTID must be incremented */
if (!$mysqli->query("DROP TABLE IF EXISTS test")) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* auto commit mode, transaction on master, GTID must be incremented */
if (!$mysqli->query("CREATE TABLE test(id INT)")) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* auto commit mode, transaction on master, GTID must be incremented */
if (!$mysqli->query("INSERT INTO test(id) VALUES (1)")) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* auto commit mode, read on slave, no increment */
if (!($res = $mysqli->query("SELECT id FROM test"))) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

var_dump($res->fetch_assoc());
?>

The above example will output:

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

The example runs three statements in auto commit mode on the master, causing three transactions on the master. For every such statement, the plugin will inject the configured UPDATE transparently before executing the users SQL statement. When the script ends the global transaction ID counter on the master has been incremented by three.

The fourth SQL statement executed in the example, a SELECT, does not trigger an increment. Only transactions (writes) executed on a master shall increment the GTID counter.

Note: SQL for global transaction ID: efficient solution wanted!

The SQL used for the client-side global transaction ID emulation is inefficient. It is optimized for clearity not for performance. Do not use it for production environments. Please, help finding an efficient solution for inclusion in the manual. We appreciate your input.

Example #4 Plugin config: SQL for fetching GTID

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "127.0.0.1",
                "port": "3306"
            }
        },
        "global_transaction_id_injection":{
            "on_commit":"UPDATE test.trx SET trx_id = trx_id + 1",
            "fetch_last_gtid" : "SELECT MAX(trx_id) FROM test.trx",
            "report_error":true
        }
    }
}

Example #5 Obtaining GTID after injection

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli) {
    /* Of course, your error handling is nicer... */
    die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));
}

/* auto commit mode, transaction on master, GTID must be incremented */
if (!$mysqli->query("DROP TABLE IF EXISTS test")) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

printf("GTID after transaction %s\n", mysqlnd_ms_get_last_gtid($mysqli));

/* auto commit mode, transaction on master, GTID must be incremented */
if (!$mysqli->query("CREATE TABLE test(id INT)")) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

printf("GTID after transaction %s\n", mysqlnd_ms_get_last_gtid($mysqli));
?>

The above example will output:

GTID after transaction 7
GTID after transaction 8

Applications can ask PECL mysqlnd_ms for a global transaction ID which belongs to the last write operation performed by the application. The function mysqlnd_ms_get_last_gtid() returns the GTID obtained when executing the SQL statement from the fetch_last_gtid entry of the global_transaction_id_injection section from the plugins configuration file. The function may be called after the GTID has been incremented.

Applications are adviced not to run the SQL statement themselves as this bares the risk of accidentally causing an implicit GTID increment. Also, if the function is used, it is easy to migrate an application from one SQL statement for fetching a transaction ID to another, for example, if any MySQL server ever features built-in global transaction ID support.

The quickstart shows a SQL statement which will return a GTID equal or greater to that created for the previous statement. It is exactly the GTID created for the previous statement if no other clients have incremented the GTID in the time span between the statement execution and the SELECT to fetch the GTID. Otherwise, it is greater.

Example #6 Plugin config: Checking for a certain GTID

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "127.0.0.1",
                "port": "3306"
            }
        },
        "global_transaction_id_injection":{
            "on_commit":"UPDATE test.trx SET trx_id = trx_id + 1",
            "fetch_last_gtid" : "SELECT MAX(trx_id) FROM test.trx",
            "check_for_gtid" : "SELECT trx_id FROM test.trx WHERE trx_id >= #GTID",
            "report_error":true
        }
    }
}

Example #7 Session consistency service level and GTID combined

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli) {
    /* Of course, your error handling is nicer... */
    die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));
}

/* auto commit mode, transaction on master, GTID must be incremented */
if (   !$mysqli->query("DROP TABLE IF EXISTS test")
    || !$mysqli->query("CREATE TABLE test(id INT)")
    || !$mysqli->query("INSERT INTO test(id) VALUES (1)")
) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* GTID as an identifier for the last write */
$gtid = mysqlnd_ms_get_last_gtid($mysqli);

/* Session consistency (read your writes): try to read from slaves not only master */
if (false == mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_SESSION, MYSQLND_MS_QOS_OPTION_GTID, $gtid)) {
    die(sprintf("[006] [%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* Either run on master or a slave which has replicated the INSERT */
if (!($res = $mysqli->query("SELECT id FROM test"))) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

var_dump($res->fetch_assoc());
?>

A GTID returned from mysqlnd_ms_get_last_gtid() can be used as an option for the session consistency service level. Session consistency delivers read your writes. Session consistency can be requested by calling mysqlnd_ms_set_qos(). In the example, the plugin will execute the SELECT statement either on the master or on a slave which has replicated the previous INSERT already.

PECL mysqlnd_ms will transparently check every configured slave if it has replicated the INSERT by checking the slaves GTID table. The check is done running the SQL set with the check_for_gtid option from the global_transaction_id_injection section of the plugins configuration file. Please note, that this is a slow and expensive procedure. Applications should try to use it sparsely and only if read load on the master becomes to high otherwise.

Use of the server-side global transaction ID feature

Note: Insufficient server support in MySQL 5.6

The plugin has been developed against a pre-production version of MySQL 5.6. It turns out that all released production versions of MySQL 5.6 do not provide clients with enough information to enforce session consistency based on GTIDs. Please, read the concepts section for details.

Starting with MySQL 5.6.5-m8 the MySQL Replication system features server-side global transaction IDs. Transaction identifiers are automatically generated and maintained by the server. Users do not need to take care of maintaining them. There is no need to setup any tables in advance, or for setting on_commit. A client-side emulation is no longer needed.

Clients can continue to use global transaction identifier to achieve session consistency when reading from MySQL Replication slaves in some cases but not all! The algorithm works as described above. Different SQL statements must be configured for fetch_last_gtid and check_for_gtid. The statements are given below. Please note, MySQL 5.6.5-m8 is a development version. Details of the server implementation may change in the future and require adoption of the SQL statements shown.

Using the following configuration any of the above described functionality can be used together with the server-side global transaction ID feature. mysqlnd_ms_get_last_gtid() and mysqlnd_ms_set_qos() continue to work as described above. The only difference is that the server does not use a simple sequence number but a string containing of a server identifier and a sequence number. Thus, users cannot easily derive an order from GTIDs returned by mysqlnd_ms_get_last_gtid().

Example #8 Plugin config: using MySQL 5.6.5-m8 built-in GTID feature

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "127.0.0.1",
                "port": "3306"
            }
        },
        "global_transaction_id_injection":{
            "fetch_last_gtid" : "SELECT @@GLOBAL.GTID_DONE AS trx_id FROM DUAL",
            "check_for_gtid" : "SELECT GTID_SUBSET('#GTID', @@GLOBAL.GTID_DONE) AS trx_id FROM DUAL",
            "report_error":true
        }
    }
}


Cache integration

Note: Version requirement, dependencies and status

Please, find more about version requirements, extension load order dependencies and the current status in the concepts section!

Databases clusters can deliver different levels of consistency. As of PECL/mysqlnd_ms 1.2.0 it is possible to advice the plugin to consider only cluster nodes that can deliver the consistency level requested. For example, if using asynchronous MySQL Replication with its cluster-wide eventual consistency, it is possible to request session consistency (read your writes) at any time using mysqlnd_ms_set_quos(). Please, see also the service level and consistency introduction.

Example #1 Recap: quality of service to request read your writes

/* Request session consistency: read your writes */
if (!mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_SESSION))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

Assuming PECL/mysqlnd has been explicitly told to deliver no consistency level higher than eventual consistency, it is possible to replace a database node read access with a client-side cache using time-to-live (TTL) as its invalidation strategy. Both the database node and the cache may or may not serve current data as this is what eventual consistency defines.

Replacing a database node read access with a local cache access can improve overall performance and lower the database load. If the cache entry is every reused by other clients than the one creating the cache entry, a database access is saved and thus database load is lowered. Furthermore, system performance can become better if computation and delivery of a database query is slower than a local cache access.

Example #2 Plugin config: no special entries for caching

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "127.0.0.1",
                "port": "3306"
            }
        },
    }
}

Example #3 Caching a slave request

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli) {
    /* Of course, your error handling is nicer... */
    die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));
}

if (   !$mysqli->query("DROP TABLE IF EXISTS test")
    || !$mysqli->query("CREATE TABLE test(id INT)")
    || !$mysqli->query("INSERT INTO test(id) VALUES (1)")
) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* Explicitly allow eventual consistency and caching (TTL <= 60 seconds) */
if (false == mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL, MYSQLND_MS_QOS_OPTION_CACHE, 60)) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* To make this example work, we must wait for a slave to catch up. Brute force style. */
$attempts = 0;
do {
    /* check if slave has the table */
    if ($res = $mysqli->query("SELECT id FROM test")) {
        break;
    } else if ($mysqli->errno) {
        die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
    }
    /* wait for slave to catch up */
    usleep(200000);
} while ($attempts++ < 10);

/* Query has been run on a slave, result is in the cache */
assert($res);
var_dump($res->fetch_assoc());

/* Served from cache */
$res = $mysqli->query("SELECT id FROM test");
?>

The example shows how to use the cache feature. First, you have to set the quality of service to eventual consistency and explicitly allow for caching. This is done by calling mysqlnd_ms_set_qos(). Then, the result set of every read-only statement is cached for upto that many seconds as allowed with mysqlnd_ms_set_qos().

The actual TTL is lower or equal to the value set with mysqlnd_ms_set_qos(). The value passed to the function sets the maximum age (seconds) of the data delivered. To calculate the actual TTL value the replication lag on a slave is checked and subtracted from the given value. If, for example, the maximum age is set to 60 seconds and the slave reports a lag of 10 seconds the resulting TTL is 50 seconds. The TTL is calculated individually for every cached query.

Example #4 Read your writes and caching combined

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli) {
    /* Of course, your error handling is nicer... */
    die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));
}

if (   !$mysqli->query("DROP TABLE IF EXISTS test")
    || !$mysqli->query("CREATE TABLE test(id INT)")
    || !$mysqli->query("INSERT INTO test(id) VALUES (1)")
) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* Explicitly allow eventual consistency and caching (TTL <= 60 seconds) */
if (false == mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL, MYSQLND_MS_QOS_OPTION_CACHE, 60)) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* To make this example work, we must wait for a slave to catch up. Brute force style. */
$attempts = 0;
do {
    /* check if slave has the table */
    if ($res = $mysqli->query("SELECT id FROM test")) {
        break;
    } else if ($mysqli->errno) {
        die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
    }
    /* wait for slave to catch up */
    usleep(200000);
} while ($attempts++ < 10);

assert($res);

/* Query has been run on a slave, result is in the cache */
var_dump($res->fetch_assoc());

/* Served from cache */
if (!($res = $mysqli->query("SELECT id FROM test"))) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
var_dump($res->fetch_assoc());

/* Update on master */
if (!$mysqli->query("UPDATE test SET id = 2")) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* Read your writes */
if (false == mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_SESSION)) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* Fetch latest data */
if (!($res = $mysqli->query("SELECT id FROM test"))) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
var_dump($res->fetch_assoc());
?>

The quality of service can be changed at any time to avoid further cache usage. If needed, you can switch to read your writes (session consistency). In that case, the cache will not be used and fresh data is read.


Failover

By default, the plugin does not attempt to fail over if connecting to a host fails. This prevents pitfalls related to connection state. It is recommended to manually handle connection errors in a way similar to a failed transaction. You should catch the error, rebuild the connection state and rerun your query as shown below.

If connection state is no issue to you, you can alternatively enable automatic and silent failover. Depending on the configuration, the automatic and silent failover will either attempt to fail over to the master before issuing and error or, try to connect to other slaves, given the query allowes for it, before attempting to connect to a master. Because automatic failover is not fool-proof, it is not discussed in the quickstart. Instead, details are given in the concepts section below.

Example #1 Manual failover, automatic optional

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "simulate_slave_failure",
                "port": "0"
            },
            "slave_1": {
                "host": "127.0.0.1",
                "port": 3311
            }
        },
       "filters": { "roundrobin": [] }
    }
 }

Example #2 Manual failover

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli) {
    /* Of course, your error handling is nicer... */
    die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));
}

$sql = "SELECT 1 FROM DUAL";

/* error handling as it should be done regardless of the plugin */
if (!($res = $link->query($sql))) {
    /* plugin specific: check for connection error */
    switch ($link->errno) {
    case 2002:
    case 2003:
    case 2005:
        printf("Connection error - trying next slave!\n");
        /* load balancer will pick next slave */
        $res = $link->query($sql);
        break;
    default:
        /* no connection error, failover is unlikely to help */
        die(sprintf("SQL error: [%d] %s", $link->errno, $link->error));
        break;
    }
}
if ($res) {
    var_dump($res->fetch_assoc());
}
?>


Partitioning and Sharding

Database clustering is done for various reasons. Clusters can improve availability, fault tolerance, and increase performance by applying a divide and conquer approach as work is distributed over many machines. Clustering is sometimes combined with partitioning and sharding to further break up a large complex task into smaller, more manageable units.

The mysqlnd_ms plugin aims to support a wide variety of MySQL database clusters. Some flavors of MySQL database clusters have built-in methods for partitioning and sharding, which could be transparent to use. The plugin supports the two most common approaches: MySQL Replication table filtering, and Sharding (application based partitioning).

MySQL Replication supports partitioning as filters that allow you to create slaves that replicate all or specific databases of the master, or tables. It is then in the responsibility of the application to choose a slave according to the filter rules. You can either use the mysqlnd_ms node_groups filter to manually support this, or use the experimental table filter.

Manual partitioning or sharding is supported through the node grouping filter, and SQL hints as of 1.5.0. The node_groups filter lets you assign a symbolic name to a group of master and slave servers. In the example, the master master_0 and slave_0 form a group with the name Partition_A. It is entirely up to you to decide what makes up a group. For example, you may use node groups for sharding, and use the group names to address shards like Shard_A_Range_0_100.

Example #1 Cluster node groups

{
  "myapp": {
       "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "simulate_slave_failure",
                "port": "0"
            },
            "slave_1": {
                "host": "127.0.0.1",
                "port": 3311
            }
        },
        "filters": {
            "node_groups": {
                "Partition_A" : {
                    "master": ["master_0"],
                    "slave": ["slave_0"]
                }
            },
           "roundrobin": []
        }
    }
}

Example #2 Manual partitioning using SQL hints

<?php
function select($mysqli, $msg, $hint = '')
{
    /* Note: weak test, two connections to two servers may have the same thread id */
    $sql = sprintf("SELECT CONNECTION_ID() AS _thread, '%s' AS _hint FROM DUAL", $msg);
    if ($hint) {
        $sql = $hint . $sql;
    }
    if (!($res = $mysqli->query($sql))) {
        printf("[%d] %s", $mysqli->errno, $mysqli->error);
        return false;
    }
    $row =  $res->fetch_assoc();
    printf("%d - %s - %s\n", $row['_thread'], $row['_hint'], $sql);
    return true;
}

$mysqli = new mysqli("myapp", "user", "password", "database");
if (!$mysqli) {
    /* Of course, your error handling is nicer... */
    die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));
}

/* All slaves allowed */
select($mysqli, "slave_0");
select($mysqli, "slave_1");

/* only servers of node group "Partition_A" allowed */
select($mysqli, "slave_1", "/*Partition_A*/");
select($mysqli, "slave_1", "/*Partition_A*/");
?>
6804 - slave_0 - SELECT CONNECTION_ID() AS _thread, 'slave1' AS _hint FROM DUAL
2442 - slave_1 - SELECT CONNECTION_ID() AS _thread, 'slave2' AS _hint FROM DUAL
6804 - slave_0 - /*Partition_A*/SELECT CONNECTION_ID() AS _thread, 'slave1' AS _hint FROM DUAL
6804 - slave_0 - /*Partition_A*/SELECT CONNECTION_ID() AS _thread, 'slave1' AS _hint FROM DUAL

By default, the plugin will use all configured master and slave servers for query execution. But if a query begins with a SQL hint like /*node_group*/, the plugin will only consider the servers listed in the node_group for query execution. Thus, SELECT queries prefixed with /*Partition_A*/ will only be executed on slave_0.


MySQL Fabric

Note: Version requirement and status

Work on supporting MySQL Fabric started in version 1.6. Please, consider the support to be of pre-alpha quality. The manual may not list all features or feature limitations. This is work in progress.

Sharding is the only use case supported by the plugin to date.

Note: MySQL Fabric concepts

Please, check the MySQL reference manual for more information about MySQL Fabric and how to set it up. The PHP manual assumes that you are familiar with the basic concepts and ideas of MySQL Fabric.

MySQL Fabric is a system for managing farms of MySQL servers to achive High Availability and optionally support sharding. Technically, it is a middleware to manage and monitor MySQL servers.

Clients query MySQL Fabric to obtain lists of MySQL servers, their state and their roles. For example, clients can request a list of slaves for a MySQL Replication group and whether they are ready to handle SQL requests. Another example is a cluster of sharded MySQL servers where the client seeks to know which shard to query for a given table and shard key. If configured to use Fabric, the plugin uses XML RCP over HTTP to obtain the list at runtime from a MySQL Fabric host. The XML remote procedure call itself is done in the background and transparent from a developers point of view.

Instead of listing MySQL servers directly in the plugins configuration file it contains a list of one or more MySQL Fabric hosts

Example #1 Plugin config: Fabric hosts instead of MySQL servers

{
    "myapp": {
        "fabric": {
            "hosts": [
                {
                    "host" : "127.0.0.1",
                    "port" : 8080
                }
            ]
        }
    }
}

Users utilize the new functions mysqlnd_ms_fabric_select_shard() and mysqlnd_ms_fabric_select_global() to switch to the set of servers responsible for a given shard key. Then, the plugin picks an appropriate server for running queries on. When doing so, the plugin takes care of additional load balancing rules set.

The below example assumes that MySQL Fabric has been setup to shard the table test.fabrictest using the id column of the table as a shard key.

Example #2 Manual partitioning using SQL hints

<?php
$mysqli = new mysqli("myapp", "user", "password", "database");
if (!$mysqli) {
    /* Of course, your error handling is nicer... */
    die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));
}

/* Create a global table - a table available on all shards */
mysqlnd_ms_fabric_select_global($mysqli, "test.fabrictest");
if (!$mysqli->query("CREATE TABLE test.fabrictest(id INT NOT NULL PRIMARY KEY)")) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* Switch connection to appropriate shard and insert record */
mysqlnd_ms_fabric_select_shard($mysqli, "test.fabrictest", 10);
if (!($res = $mysqli->query("INSERT INTO fabrictest(id) VALUES (10)"))) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}

/* Try to read newly inserted record */
mysqlnd_ms_fabric_select_shard($mysqli, "test.fabrictest", 10);
if (!($res = $mysqli->query("SELECT id FROM test WHERE id = 10"))) {
    die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
}
?>

The example creates the sharded table, inserts a record and reads the record thereafter. All SQL data definition language (DDL) operations on a sharded table must be applied to the so called global server group. Prior to creating or altering a sharded table, mysqlnd_ms_fabric_select_global() is called to switch the given connection to the corresponding servers of the global group. Data manipulation (DML) SQL statements must be sent to the shards directly. The mysqlnd_ms_fabric_select_shard() switches a connection to shards handling a certain shard key.


Concepts

Table of Contents

  • Architecture
  • Connection pooling and switching
  • Local transaction handling
  • Error handling
  • Transient errors
  • Failover
  • Load balancing
  • Read-write splitting
  • Filter
  • Service level and consistency
  • Global transaction IDs
  • Cache integration
  • Supported clusters
  • XA/Distributed transactions

This explains the architecture and related concepts for this plugin, and describes the impact that MySQL replication and this plugin have on developmental tasks while using a database cluster. Reading and understanding these concepts is required, in order to use this plugin with success.


Architecture

The mysqlnd replication and load balancing plugin is implemented as a PHP extension. It is written in C and operates under the hood of PHP. During the startup of the PHP interpreter, in the module init phase of the PHP engine, it gets registered as a mysqlnd plugin to replace selected mysqlnd C methods.

At PHP runtime, it inspects queries sent from mysqlnd (PHP) to the MySQL server. If a query is recognized as read-only, it will be sent to one of the configured slave servers. Statements are considered read-only if they either start with SELECT, the SQL hint /*ms=slave*/ or a slave had been chosen for running the previous query, and the query started with the SQL hint /*ms=last_used*/. In all other cases, the query will be sent to the MySQL replication master server.

For better portability, applications should use the MYSQLND_MS_MASTER_SWITCH, MYSQLND_MS_SLAVE_SWITCH, and MYSQLND_MS_LAST_USED_SWITCH predefined mysqlnd_ms constants, instead of their literal values, such as /*ms=slave*/.

The plugin handles the opening and closing of database connections to both master and slave servers. From an application point of view, there continues to be only one connection handle. However, internally, this one public connection handle represents a pool of network connections that are managed by the plugin. The plugin proxies queries to the master server, and to the slaves using multiple connections.

Database connections have a state consisting of, for example, transaction status, transaction settings, character set settings, and temporary tables. The plugin will try to maintain the same state among all internal connections, whenever this can be done in an automatic and transparent way. In cases where it is not easily possible to maintain state among all connections, such as when using BEGIN TRANSACTION, the plugin leaves it to the user to handle.


Connection pooling and switching

The replication and load balancing plugin changes the semantics of a PHP MySQL connection handle. The existing API of the PHP MySQL extensions (mysqli, mysql, and PDO_MYSQL) are not changed in a way that functions are added or removed. But their behavior changes when using the plugin. Existing applications do not need to be adapted to a new API, but they may need to be modified because of the behavior changes.

The plugin breaks the one-by-one relationship between a mysqli, mysql, and PDO_MYSQL connection handle and a MySQL network connection. And a mysqli, mysql, and PDO_MYSQL connection handle represents a local pool of connections to the configured MySQL replication master and MySQL replication slave servers. The plugin redirects queries to the master and slave servers. At some point in time one and the same PHP connection handle may point to the MySQL master server. Later on, it may point to one of the slave servers or still the master. Manipulating and replacing the network connection referenced by a PHP MySQL connection handle is not a transparent operation.

Every MySQL connection has a state. The state of the connections in the connection pool of the plugin can differ. Whenever the plugin switches from one wire connection to another, the current state of the user connection may change. The applications must be aware of this.

The following list shows what the connection state consists of. The list may not be complete.

  • Transaction status
  • Temporary tables
  • Table locks
  • Session system variables and session user variables
  • The current database set using USE and other state chaining SQL commands
  • Prepared statements
  • HANDLER variables
  • Locks acquired with GET_LOCK()

Connection switches happen right before queries are executed. The plugin does not switch the current connection until the next statement is executed.

Note: Replication issues

See also the MySQL reference manual chapter about » replication features and related issues. Some restrictions may not be related to the PHP plugin, but are properties of the MySQL replication system.

Broadcasted messages

The plugins philosophy is to align the state of connections in the pool only if the state is under full control of the plugin, or if it is necessary for security reasons. Just a few actions that change the state of the connection fall into this category.

The following is a list of connection client library calls that change state, and are broadcasted to all open connections in the connection pool.

If any of the listed calls below are to be executed, the plugin loops over all open master and slave connections. The loop continues until all servers have been contacted, and the loop does not break if a server indicates a failure. If possible, the failure will propagate to the called user API function, which may be detected depending on which underlying library function was triggered.

Library call | Notes | Version
change_user() | Called by the mysqli_change_user() user API call. Also triggered upon reuse of a persistent mysqli connection. | Since 1.0.0.
select_db | Called by the following user API calls: mysql_select_db(), mysql_list_tables(), mysql_db_query(), mysql_list_fields(), mysqli_select_db(). Note, that SQL USE is not monitored. | Since 1.0.0.
set_charset() | Called by the following user API calls: mysql_set_charset(). mysqli_set_charset(). Note, that SQL SET NAMES is not monitored. | Since 1.0.0.
set_server_option() | Called by the following user API calls: mysqli_multi_query(), mysqli_real_query(), mysqli_query(), mysql_query(). | Since 1.0.0.
set_client_option() | Called by the following user API calls: mysqli_options(), mysqli_ssl_set(), mysqli_connect(), mysql_connect(), mysql_pconnect(). | Since 1.0.0.
set_autocommit() | Called by the following user API calls: mysqli_autocommit(), PDO::setAttribute(PDO::ATTR_AUTOCOMMIT). | Since 1.0.0. PHP >= 5.4.0.
ssl_set() | Called by the following user API calls: mysqli_ssl_set(). | Since 1.1.0.

Broadcasting and lazy connections

The plugin does not proxy or remember all settings to apply them on connections opened in the future. This is important to remember, if using lazy connections. Lazy connections are connections which are not opened before the client sends the first connection. Use of lazy connections is the default plugin action.

The following connection library calls each changed state, and their execution is recorded for later use when lazy connections are opened. This helps ensure that the connection state of all connections in the connection pool are comparable.

Library call | Notes | Version
change_user() | User, password and database recorded for future use. | Since 1.1.0.
select_db | Database recorded for future use. | Since 1.1.0.
set_charset() | Calls set_client_option(MYSQL_SET_CHARSET_NAME, charset) on lazy connection to ensure charset will be used upon opening the lazy connection. | Since 1.1.0.
set_autocommit() | Adds SET AUTOCOMMIT=0|1 to the list of init commands of a lazy connection using set_client_option(MYSQL_INIT_COMMAND, "SET AUTOCOMMIT=...%quot;). | Since 1.1.0. PHP >= 5.4.0.
Caution

Connection state

The connection state is not only changed by API calls. Thus, even if PECL mysqlnd_ms monitors all API calls, the application must still be aware. Ultimately, it is the applications responsibility to maintain the connection state, if needed.

Charsets and string escaping

Due to the use of lazy connections, which are a default, it can happen that an application tries to escape a string for use within SQL statements before a connection has been established. In this case string escaping is not possible. The string escape function does not know what charset to use before a connection has been established.

To overcome the problem a new configuration setting server_charset has been introduced in version 1.4.0.

Attention has to be paid on escaping strings with a certain charset but using the result on a connection that uses a different charset. Please note, that PECL/mysqlnd_ms manipulates connections and one application level connection represents a pool of multiple connections that all may have different default charsets. It is recommended to configure the servers involved to use the same default charsets. The configuration setting server_charset does help with this situation as well. If using server_charset, the plugin will set the given charset on all newly opened connections.


Local transaction handling

Transaction handling is fundamentally changed. An SQL transaction is a unit of work that is run on one database server. The unit of work consists of one or more SQL statements.

By default the plugin is not aware of SQL transactions. The plugin may switch connections for load balancing at any point in time. Connection switches may happen in the middle of a transaction. This is against the nature of an SQL transaction. By default, the plugin is not transaction safe.

Any kind of MySQL load balancer must be hinted about the begin and end of a transaction. Hinting can either be done implicitly by monitoring API calls or using SQL hints. Both options are supported by the plugin, depending on your PHP version. API monitoring requires PHP 5.4.0 or newer. The plugin, like any other MySQL load balancer, cannot detect transaction boundaries based on the MySQL Client Server Protocol. Thus, entirely transparent transaction aware load balancing is not possible. The least intrusive option is API monitoring, which requires little to no application changes, depending on your application.

Please, find examples of using SQL hints or the API monitoring in the examples section. The details behind the API monitoring, which makes the plugin transaction aware, are described below.

Beginning with PHP 5.4.0, the mysqlnd library allows this plugin to subclass the library C API call set_autocommit(), to detect the status of autocommit mode.

The PHP MySQL extensions either issue a query (such as SET AUTOCOMMIT=0|1), or use the mysqlnd library call set_autocommit() to control the autocommit setting. If an extension makes use of set_autocommit(), the plugin can be made transaction aware. Transaction awareness cannot be achieved if using SQL to set the autocommit mode. The library function set_autocommit() is called by the mysqli_autocommit() and PDO::setAttribute(PDO::ATTR_AUTOCOMMIT) user API calls.

The plugin configuration option trx_stickiness=master can be used to make the plugin transactional aware. In this mode, the plugin stops load balancing if autocommit becomes disabled, and directs all statements to the master until autocommit gets enabled.

An application that does not want to set SQL hints for transactions but wants to use the transparent API monitoring to avoid application changes must make sure that the autocommit settings is changed exclusively through the listed API calls.

API based transaction boundary detection has been improved with PHP 5.5.0 and PECL/mysqlnd_ms 1.5.0 to cover not only calls to mysqli_autocommit() but also mysqli_begin(), mysqli_commit() and mysqli_rollback().


Error handling

Applications using PECL/mysqlnd_ms should implement proper error handling for all user API calls. And because the plugin changes the semantics of a connection handle, API calls may return unexpected errors. If using the plugin on a connection handle that no longer represents an individual network connection, but a connection pool, an error code and error message will be set on the connection handle whenever an error occurs on any of the network connections behind.

If using lazy connections, which is the default, connections are not opened until they are needed for query execution. Therefore, an API call for a statement execution may return a connection error. In the example below, an error is provoked when trying to run a statement on a slave. Opening a slave connection fails because the plugin configuration file lists an invalid host name for the slave.

Example #1 Provoking a connection error

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "invalid_host_name",
            }
        },
        "lazy_connections": 1
    }
}

The explicit activation of lazy connections is for demonstration purpose only.

Example #2 Connection error on query execution

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (mysqli_connect_errno())
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* Connection 1, connection bound SQL user variable, no SELECT thus run on master */
if (!$mysqli->query("SET @myrole='master'")) {
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}

/* Connection 2, run on slave because SELECT, provoke connection error */
if (!($res = $mysqli->query("SELECT @myrole AS _role"))) {
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
} else {
 $row = $res->fetch_assoc();
 $res->close();
 printf("@myrole = '%s'\n", $row['_role']);
}
$mysqli->close();
?>

The above example will output something similar to:

PHP Warning:  mysqli::query(): php_network_getaddresses: getaddrinfo failed: Name or service not known in %s on line %d
PHP Warning:  mysqli::query(): [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known (trying to connect via tcp://invalid_host_name:3306) in %s on line %d
[2002] php_network_getaddresses: getaddrinfo failed: Name or service not known

Applications are expected to handle possible connection errors by implementing proper error handling.

Depending on the use case, applications may want to handle connection errors differently from other errors. Typical connection errors are 2002 (CR_CONNECTION_ERROR) - Can't connect to local MySQL server through socket '%s' (%d), 2003 (CR_CONN_HOST_ERROR) - Can't connect to MySQL server on '%s' (%d) and 2005 (CR_UNKNOWN_HOST) - Unknown MySQL server host '%s' (%d). For example, the application may test for the error codes and manually perform a fail over. The plugins philosophy is not to offer automatic fail over, beyond master fail over, because fail over is not a transparent operation.

Example #3 Provoking a connection error

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "invalid_host_name"
            },
            "slave_1": {
                "host": "192.168.78.136"
            }
        },
        "lazy_connections": 1,
        "filters": {
            "roundrobin": [

            ]
        }
    }
}

Explicitly activating lazy connections is done for demonstration purposes, as is round robin load balancing as opposed to the default random once type.

Example #4 Most basic failover

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (mysqli_connect_errno())
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* Connection 1, connection bound SQL user variable, no SELECT thus run on master */
if (!$mysqli->query("SET @myrole='master'")) {
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}

/* Connection 2, first slave */
$res = $mysqli->query("SELECT VERSION() AS _version");
/* Hackish manual fail over */
if (2002 == $mysqli->errno || 2003 == $mysqli->errno || 2004 == $mysqli->errno) {
  /* Connection 3, first slave connection failed, trying next slave */
  $res = $mysqli->query("SELECT VERSION() AS _version");
}

if (!$res) {
  printf("ERROR, [%d] '%s'\n", $mysqli->errno, $mysqli->error);
} else {
 /* Error messages are taken from connection 3, thus no error */
 printf("SUCCESS, [%d] '%s'\n", $mysqli->errno, $mysqli->error);
 $row = $res->fetch_assoc();
 $res->close();
 printf("version = %s\n", $row['_version']);
}
$mysqli->close();
?>

The above example will output something similar to:

[1045] Access denied for user 'username'@'localhost' (using password: YES)
PHP Warning:  mysqli::query(): php_network_getaddresses: getaddrinfo failed: Name or service not known in %s on line %d
PHP Warning:  mysqli::query(): [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known (trying to connect via tcp://invalid_host_name:3306) in %s on line %d
SUCCESS, [0] ''
version = 5.6.2-m5-log

In some cases, it may not be easily possible to retrieve all errors that occur on all network connections through a connection handle. For example, let's assume a connection handle represents a pool of three open connections. One connection to a master and two connections to the slaves. The application changes the current database using the user API call mysqli_select_db(), which then calls the mysqlnd library function to change the schemata. mysqlnd_ms monitors the function, and tries to change the current database on all connections to harmonize their state. Now, assume the master succeeds in changing the database, and both slaves fail. Upon the initial error from the first slave, the plugin will set an appropriate error on the connection handle. The same is done when the second slave fails to change the database. The error message from the first slave is lost.

Such cases can be debugged by either checking for errors of the type E_WARNING (see above) or, if no other option, investigation of the mysqlnd_ms debug and trace log.


Transient errors

Some distributed database clusters make use of transient errors. A transient error is a temporary error that is likely to disappear soon. By definition it is safe for a client to ignore a transient error and retry the failed operation on the same database server. The retry is free of side effects. Clients are not forced to abort their work or to fail over to another database server immediately. They may enter a retry loop before to wait for the error to disappear before giving up on the database server. Transient errors can be seen, for example, when using MySQL Cluster. But they are not bound to any specific clustering solution per se.

PECL/mysqlnd_ms can perform an automatic retry loop in case of a transient error. This increases distribution transparency and thus makes it easier to migrate an application running on a single database server to run on a cluster of database servers without having to change the source of the application.

The automatic retry loop will repeat the requested operation up to a user configurable number of times and pause between the attempts for a configurable amount of time. If the error disappears during the loop, the application will never see it. If not, the error is forwarded to the application for handling.

In the example below a duplicate key error is provoked to make the plugin retry the failing query two times before the error is passed to the application. Between the two attempts the plugin sleeps for 100 milliseconds.

Example #1 Provoking a transient error

mysqlnd_ms.enable=1
mysqlnd_ms.collect_statistics=1
{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
       },
       "transient_error": {
          "mysql_error_codes": [
            1062
          ],
          "max_retries": 2,
          "usleep_retry": 100
       }
    }
}

Example #2 Transient error retry loop

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
if (mysqli_connect_errno())
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
    !$mysqli->query("CREATE TABLE test(id INT PRIMARY KEY)") ||
    !$mysqli->query("INSERT INTO test(id) VALUES (1))")) {
  printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}

/* Retry loop is completely transparent. Checking statistics is
 the only way to know about implicit retries */
$stats = mysqlnd_ms_get_stats();
printf("Transient error retries before error: %d\n", $stats['transient_error_retries']);

/* Provoking duplicate key error to see statistics change */
if (!$mysqli->query("INSERT INTO test(id) VALUES (1))")) {
  printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
}

$stats = mysqlnd_ms_get_stats();
printf("Transient error retries after error: %d\n", $stats['transient_error_retries']);

$mysqli->close();
?>

The above example will output something similar to:

Transient error retries before error: 0
[1062] Duplicate entry '1' for key 'PRIMARY'
Transient error retries before error: 2

Because the execution of the retry loop is transparent from a users point of view, the example checks the statistics provided by the plugin to learn about it.

As the example shows, the plugin can be instructed to consider any error transient regardless of the database servers error semantics. The only error that a stock MySQL server considers temporary has the error code 1297. When configuring other error codes but 1297 make sure your configuration reflects the semantics of your clusters error codes.

The following mysqlnd C API calls are monitored by the plugin to check
for transient errors: query(),
change_user(), select_db(),
set_charset(), set_server_option()
prepare(), execute(),
set_autocommit(),
tx_begin(), tx_commit(),
tx_rollback(), tx_commit_or_rollback().
The corresponding user API calls have similar names.

The maximum time the plugin may sleep during the retry loop depends on the function in question. The a retry loop for query(), prepare() or execute() will sleep for up to max_retries * usleep_retry milliseconds.

However, functions that control connection state are dispatched to all connections. The retry loop settings are applied to every connection on which the command is to be run. Thus, such a function may interrupt program execution for longer than a function that is run on one server only. For example, set_autocommit() is dispatched to connections and may sleep up to (max_retries * usleep_retry) * number_of_open_connections) milliseconds. Please, keep this in mind when setting long sleep times and large retry numbers. Using the default settings of max_retries=1, usleep_retry=100 and lazy_connections=1 it is unlikely that you will ever see a delay of more than 1 second.


Failover

By default, connection failover handling is left to the user. The application is responsible for checking return values of the database functions it calls and reacting to possible errors. If, for example, the plugin recognizes a query as a read-only query to be sent to the slave servers, and the slave server selected by the plugin is not available, the plugin will raise an error after not executing the statement.

Default: manual failover

It is up to the application to handle the error and, if required, re-issue the query to trigger the selection of another slave server for statement execution. The plugin will make no attempts to failover automatically, because the plugin cannot ensure that an automatic failover will not change the state of the connection. For example, the application may have issued a query which depends on SQL user variables which are bound to a specific connection. Such a query might return incorrect results if the plugin would switch the connection implicitly as part of automatic failover. To ensure correct results, the application must take care of the failover, and rebuild the required connection state. Therefore, by default, no automatic failover is performed by the plugin.

A user that does not change the connection state after opening a connection may activate automatic failover. Please note, that automatic failover logic is limited to connection attempts. Automatic failover is not used for already established connections. There is no way to instruct the plugin to attempt failover on a connection that has been connected to MySQL already in the past.

Automatic failover

The failover policy is configured in the plugins configuration file, by using the failover configuration directive.

Automatic and silent failover can be enabled through the failover configuration directive. Automatic failover can either be configured to try exactly one master after a slave failure or, alternatively, loop over slaves and masters before returning an error to the user. The number of connection attempts can be limited and failed hosts can be excluded from future load balancing attempts. Limiting the number of retries and remembering failed hosts are considered experimental features, albeit being reasonable stable. Syntax and semantics may change in future versions.

Please note, since version 1.5.0 automatic failover is disabled for the duration of a transaction if transaction stickiness is enabled and transaction boundaries have been detected. The plugin will not switch connections for the duration of a transaction. It will also not perform automatic and silent failover. Instead an error will be thrown. It is then left to the user to handle the failure of the transaction. Please check, the trx_stickiness documentation how to do this.

A basic manual failover example is provided within the error handling section.

Standby servers

Using weighted load balancing, introduced in PECL/mysqlnd 1.4.0, it is possible to configure standby servers that are sparsely used during normal operations. A standby server that is primarily used as a worst-case standby failover target can be assigned a very low weight/priority in relation to all other servers. As long as all servers are up and running the majority of the workload is assigned to the servers which have hight weight values. Few requests will be directed to the standby system which has a very low weight value.

Upon failure of the servers with a high priority, you can still failover to the standby, which has been given a low load balancing priority by assigning a low weight to it. Failover can be some manually or automatically. If done automatically, you may want to combine it with the remember_failed option.

At this point, it is not possible to instruct the load balancer to direct no requests at all to a standby. This may not be much of a limitation given that the highest weight you can assign to a server is 65535. Given two slaves, of which one shall act as a standby and has been assigned a weight of 1, the standby will have to handle far less than one percent of the overall workload.

Failover and primary copy

Please note, if using a primary copy cluster, such as MySQL Replication, it is difficult to do connection failover in case of a master failure. At any time there is only one master in the cluster for a given dataset. The master is a single point of failure. If the master fails, clients have no target to fail over write requests. In case of a master outage the database administrator must take care of the situation and update the client configurations, if need be.


Load balancing

Four load balancing strategies are supported to distribute statements over the configured MySQL slave servers:

random

Chooses a random server whenever a statement is executed.

random once (default)

Chooses a random server after the first statement is executed, and uses the decision for the rest of the PHP request.

It is the default, and the lowest impact on the connection state.

round robin

Iterates over the list of configured servers.

user-defined via callback

Is used to implement any other strategy.

The load balancing policy is configured in the plugins configuration file using the random, roundrobin, and user filters.

Servers can be prioritized assigning a weight. A server that has been given a weight of two will get twice as many requests as a server that has been given the default weight of one. Prioritization can be handy in heterogenous environments. For example, you may want to assign more requests to a powerful machine than to a less powerful. Or, you may have configured servers that are close or far from the client, thus expose different latencies.


Read-write splitting

The plugin executes read-only statements on the configured MySQL slaves, and all other queries on the MySQL master. Statements are considered read-only if they either start with SELECT, the SQL hint /*ms=slave*/, or if a slave had been chosen for running the previous query and the query starts with the SQL hint /*ms=last_used*/. In all other cases, the query will be sent to the MySQL replication master server. It is recommended to use the constants MYSQLND_MS_SLAVE_SWITCH, MYSQLND_MS_MASTER_SWITCH and MYSQLND_MS_LAST_USED_SWITCH instead of /*ms=slave*/. See also the list of mysqlnd_ms constants.

SQL hints are a special kind of standard compliant SQL comments. The plugin does check every statement for certain SQL hints. The SQL hints are described within the mysqlnd_ms constants documentation, constants that are exported by the extension. Other systems involved with the statement processing, such as the MySQL server, SQL firewalls, and SQL proxies, are unaffected by the SQL hints, because those systems are designed to ignore SQL comments.

The built-in read-write splitter can be replaced by a user-defined filter, see also the user filter documentation.

A user-defined read-write splitter can request the built-in logic to send a statement to a specific location, by invoking mysqlnd_ms_is_select().

Note:

The built-in read-write splitter is not aware of multi-statements. Multi-statements are seen as one statement. The splitter will check the beginning of the statement to decide where to run the statement. If, for example, a multi-statement begins with SELECT 1 FROM DUAL; INSERT INTO test(id) VALUES (1); ... the plugin will run it on a slave although the statement is not read-only.


Filter

Note: Version requirement

Filters exist as of mysqlnd_ms version 1.1.0-beta.

filters. PHP applications that implement a MySQL replication cluster must first identify a group of servers in the cluster which could execute a statement before the statement is executed by one of the candidates. In other words: a defined list of servers must be filtered until only one server is available.

The process of filtering may include using one or more filters, and filters can be chained. And they are executed in the order they are defined in the plugins configuration file.

Note: Explanation: comparing filter chaining to pipes

The concept of chained filters can be compared to using pipes to connect command line utilities on an operating system command shell. For example, an input stream is passed to a processor, filtered, and then transferred to be output. Then, the output is passed as input to the next command, which is connected to the previous using the pipe operator.

Available filters:

  • Load balancing filters: random and roundrobin.
  • Selection filter: user, user_multi, quality_of_service.

The random filter implements the 'random' and 'random once' load balancing policies. The 'round robin' load balancing can be configured through the roundrobin filter. Setting a 'user defined callback' for server selection is possible with the user filter. The quality_of_service filter finds cluster nodes capable of delivering a certain service, for example, read-your-writes or, not lagging more seconds behind the master than allowed.

Filters can accept parameters to change their behavior. The random filter accepts an optional sticky parameter. If set to true, the filter changes load balancing from random to random once. Random picks a random server every time a statement is to be executed. Random once picks a random server when the first statement is to be executed and uses the same server for the rest of the PHP request.

One of the biggest strength of the filter concept is the possibility to chain filters. This strength does not become immediately visible because the random, roundrobin and user filters are supposed to output no more than one server. If a filter reduces the list of candidates for running a statement to only one server, it makes little sense to use that one server as input for another filter for further reduction of the list of candidates.

An example filter sequence that will fail:

  • Statement to be executed: SELECT 1 FROM DUAL. Passed to all filters.
  • All configured nodes are passed as input to the first filter. Master nodes: master_0. Slave nodes:slave_0, slave_1
  • Filter: random, argument sticky=1. Picks a random slave once to be used for the rest of the PHP request. Output: slave_0.
  • Output of slave_0 and the statement to be executed is passed as input to the next filter. Here: roundrobin, server list passed to filter is: slave_0.
  • Filter: roundrobin. Server list consists of one server only, round robin will always return the same server.
If trying to use such a filter sequence, the plugin may emit a warning like (mysqlnd_ms) Error while creating filter '%s' . Non-multi filter '%s' already created. Stopping in %s on line %d. Furthermore, an appropriate error on the connection handle may be set.

A second type of filter exists: multi filter. A multi filter emits zero, one or multiple servers after processing. The quality_of_service filter is an example. If the service quality requested sets an upper limit for the slave lag and more than one slave is lagging behind less than the allowed number of seconds, the filter returns more than one cluster node. A multi filter must be followed by other to further reduce the list of candidates for statement execution until a candidate is found.

A filter sequence with the quality_of_service multi filter followed by a load balancing filter.

  • Statement to be executed: SELECT sum(price) FROM orders WHERE order_id = 1. Passed to all filters.
  • All configured nodes are passed as input to the first filter. Master nodes: master_0. Slave nodes: slave_0, slave_1, slave_2, slave_3
  • Filter: quality_of_service, rule set: session_consistency (read-your-writes) Output: master_0
  • Output of master_0 and the statement to be executed is passed as input to the next filter, which is roundrobin.
  • Filter: roundrobin. Server list consists of one server. Round robin selects master_0.

A filter sequence must not end with a multi filter. If trying to use a filter sequence which ends with a multi filter the plugin may emit a warning like (mysqlnd_ms) Error in configuration. Last filter is multi filter. Needs to be non-multi one. Stopping in %s on line %d. Furthermore, an appropriate error on the connection handle may be set.

Note: Speculation towards the future: MySQL replication filtering

In future versions, there may be additional multi filters. For example, there may be a table filter to support MySQL replication filtering. This would allow you to define rules for which database or table is to be replicated to which node of a replication cluster. Assume your replication cluster consists of four slaves (slave_0, slave_1, slave_2, slave_3) two of which replicate a database named sales (slave_0, slave_1). If the application queries the database slaves, the hypothetical table filter reduces the list of possible servers to slave_0 and slave_1. Because the output and list of candidates consists of more than one server, it is necessary and possible to add additional filters to the candidate list, for example, using a load balancing filter to identify a server for statement execution.


Service level and consistency

Note: Version requirement

Service levels have been introduced in mysqlnd_ms version 1.2.0-alpha. mysqlnd_ms_set_qos() requires PHP 5.4.0 or newer.

The plugin can be used with different kinds of MySQL database clusters. Different clusters can deliver different levels of service to applications. The service levels can be grouped by the data consistency levels that can be achieved. The plugin knows about:

  • eventual consistency
  • session consistency
  • strong consistency

Depending how a cluster is used it may be possible to achieve higher service levels than the default one. For example, a read from an asynchronous MySQL replication slave is eventual consistent. Thus, one may say the default consistency level of a MySQL replication cluster is eventual consistency. However, if the master only is used by a client for reading and writing during a session, session consistency (read your writes) is given. PECL mysqlnd 1.2.0 abstracts the details of choosing an appropriate node for any of the above service levels from the user.

Service levels can be set through the qualify-of-service filter in the plugins configuration file and at runtime using the function mysqlnd_ms_set_qos().

The plugin defines the different service levels as follows.

Eventual consistency is the default service provided by an asynchronous cluster, such as classical MySQL replication. A read operation executed on an arbitrary node may or may not return stale data. The applications view of the data is eventual consistent.

Session consistency is given if a client can always read its own writes. An asynchronous MySQL replication cluster can deliver session consistency if clients always use the master after the first write or never query a slave which has not yet replicated the clients write operation.

The plugins understanding of strong consistency is that all clients always see the committed writes of all other clients. This is the default when using MySQL Cluster or any other cluster offering synchronous data distribution.

Service level parameters

Eventual consistency and session consistency service level accept parameters.

Eventual consistency is the service provided by classical MySQL replication. By default, all nodes qualify for read requests. An optional age parameter can be given to filter out nodes which lag more than a certain number of seconds behind the master. The plugin is using SHOW SLAVE STATUS to measure the lag. Please, see the MySQL reference manual to learn about accuracy and reliability of the SHOW SLAVE STATUS command.

Session consistency (read your writes) accepts an optional GTID parameter to consider reading not only from the master but also from slaves which already have replicated a certain write described by its transaction identifier. This way, when using asynchronous MySQL replication, read requests may be load balanced over slaves while still ensuring session consistency.

The latter requires the use of client-side global transaction id injection.

Advantages of the new approach

The new approach supersedes the use of SQL hints and the configuration option master_on_write in some respects. If an application running on top of an asynchronous MySQL replication cluster cannot accept stale data for certain reads, it is easier to tell the plugin to choose appropriate nodes than prefixing all read statements in question with the SQL hint to enforce the use of the master. Furthermore, the plugin may be able to use selected slaves for reading.

The master_on_write configuration option makes the plugin use the master after the first write (session consistency, read your writes). In some cases, session consistency may not be needed for the rest of the session but only for some, few read operations. Thus, master_on_write may result in more read load on the master than necessary. In those cases it is better to request a higher than default service level only for those reads that actually need it. Once the reads are done, the application can return to default service level. Switching between service levels is only possible using mysqlnd_ms_set_qos().

Performance considerations

A MySQL replication cluster cannot tell clients which slaves are capable of delivering which level of service. Thus, in some cases, clients need to query the slaves to check their status. PECL mysqlnd_ms transparently runs the necessary SQL in the background. However, this is an expensive and slow operation. SQL statements are run if eventual consistency is combined with an age (slave lag) limit and if session consistency is combined with a global transaction ID.

If eventual consistency is combined with an maximum age (slave lag), the plugin selects candidates for statement execution and load balancing for each statement as follows. If the statement is a write all masters are considered as candidates. Slaves are not checked and not considered as candidates. If the statement is a read, the plugin transparently executes SHOW SLAVE STATUS on every slaves connection. It will loop over all connections, send the statement and then start checking for results. Usually, this is slightly faster than a loop over all connections in which for every connection a query is send and the plugin waits for its results. A slave is considered a candidate if SHOW SLAVE STATUS reports Slave_IO_Running=Yes, Slave_SQL_Running=Yes and Seconds_Behind_Master is less or equal than the allowed maximum age. In case of an SQL error, the plugin emits a warning but does not set an error on the connection. The error is not set to make it possible to use the plugin as a drop-in.

If session consistency is combined with a global transaction ID, the plugin executes the SQL statement set with the fetch_last_gtid entry of the global_transaction_id_injection section from the plugins configuration file. Further details are identical to those described above.

In version 1.2.0 no additional optimizations are done for executing background queries. Future versions may contain optimizations, depending on user demand.

If no parameters and options are set, no SQL is needed. In that case, the plugin consider all nodes of the type shown below.

  • eventual consistency, no further options set: all masters, all slaves
  • session consistency, no further options set: all masters
  • strong consistency (no options allowed): all masters

Throttling

The quality of service filter can be combined with Global transaction IDs to throttle clients. Throttling does reduce the write load on the master by slowing down clients. If session consistency is requested and global transactions identifier are used to check the status of a slave, the check can be done in two ways. By default a slave is checked and skipped immediately if it does not match the criteria for session consistency. Alternatively, the plugin can wait for a slave to catch up to the master until session consistency is possible. To enable the throttling, you have to set wait_for_gtid_timeout configuration option.


Global transaction IDs

Note: Version requirement

Client side global transaction ID injection exists as of mysqlnd_ms version 1.2.0-alpha. Transaction boundaries are detected by monitoring API calls. This is possible as of PHP 5.4.0. Please, see also Transaction handling.

As of MySQL 5.6.5-m8 the MySQL server features built-in global transaction identifiers. The MySQL built-in global transaction ID feature is supported by PECL/mysqlnd_ms 1.3.0-alpha or later. Neither are client-side transaction boundary monitoring nor any setup activities required if using the server feature.

Please note, all MySQL 5.6 production versions do not provide clients with enough information to use GTIDs for enforcing session consistency. In the worst case, the plugin will choose the master only.

Idea and client-side emulation

PECL/mysqlnd_ms can do client-side transparent global transaction ID injection. In its most basic form, a global transaction identifier is a counter which is incremented for every transaction executed on the master. The counter is held in a table on the master. Slaves replicate the counter table.

In case of a master failure a database administrator can easily identify the most recent slave for promoting it as a new master. The most recent slave has the highest transaction identifier.

Application developers can ask the plugin for the global transaction identifier (GTID) for their last successful write operation. The plugin will return an identifier that refers to an transaction no older than that of the clients last write operation. Then, the GTID can be passed as a parameter to the quality of service (QoS) filter as an option for session consistency. Session consistency ensures read your writes. The filter ensures that all reads are either directed to a master or a slave which has replicated the write referenced by the GTID.

When injection is done

The plugin transparently maintains the GTID table on the master. In autocommit mode the plugin injects an UPDATE statement before executing the users statement for every master use. In manual transaction mode, the injection is done before the application calls commit() to close a transaction. The configuration option report_error of the GTID section in the plugins configuration file is used to control whether a failed injection shall abort the current operation or be ignored silently (default).

Please note, the PHP version requirements for transaction boundary monitoring and their limits.

Limitations

Client-side global transaction ID injection has shortcomings. The potential issues are not specific to PECL/mysqlnd_ms but are rather of general nature.

  • Global transaction ID tables must be deployed on all masters and replicas.
  • The GTID can have holes. Only PHP clients using the plugin will maintain the table. Other clients will not.
  • Client-side transaction boundary detection is based on API calls only.
  • Client-side transaction boundary detection does not take implicit commit into account. Some MySQL SQL statements cause an implicit commit and cannot be rolled back.

Using server-side global transaction identifier

Starting with PECL/mysqlnd_ms 1.3.0-alpha the MySQL 5.6.5-m8 or newer built-in global transaction identifier feature is supported. Use of the server feature lifts all of the above listed limitations. Please, see the MySQL Reference Manual for limitations and preconditions for using server built-in global transaction identifiers.

Whether to use the client-side emulation or the server built-in functionality is a question not directly related to the plugin, thus it is not discussed in depth. There are no plans to remove the client-side emulation and you can continue to use it, if the server-side solution is no option. This may be the case in heterogenous environments with old MySQL server or, if any of the server-side solution limitations is not acceptable.

From an applications perspective there is hardly a difference in using one or the other approach. The following properties differ.

  • Client-side emulation, as shown in the manual, is using an easy to compare sequence number for global transactions. Multi-master is not handled to keep the manual examples easy. Server-side built-in feature is using a combination of a server identifier and a sequence number as a global transaction identifier. Comparison cannot use numeric algebra. Instead a SQL function must be used. Please, see the MySQL Reference Manual for details. Server-side built-in feature of MySQL 5.6 cannot be used to ensure session consistency under all circumstances. Do not use it for the quality-of-service feature. Here is a simple example why it will not give reliable results. There are more edge cases that cannot be covered with limited functionality exported by the server. Currently, clients can ask a MySQL replication master for a list of all executed global transaction IDs only. If a slave is configured not to replicate all transactions, for example, because replication filters are set, then the slave will never show the same set of executed global transaction IDs. Albeit the slave may have replicated a clients writes and it may be a candidate for a consistent read, it will never be considered by the plugin. Upon write the plugin learns from the master that the servers complete transaction history consists of GTID=1..3. There is no way for the plugin to ask for the GTID of the write transaction itself, say GTID=3. Assume that a slave does not replicate the transactions GTID=1..2 but only GTID=3 because of a replication feature. Then, the slaves transaction history is GTID=3. However, the plugin tries to find a node which has a transaction history of GITD=1...3. Albeit the slave has replicated the clients write and session consistency may be achieved when reading from the slave, it will not be considered by the plugin. This is not a fault of the plugin implementation but a feature gap on the server side. Please note, this is a trivial case to illustrate the issue there are other issues. In sum you are asked not to attempt using MySQL 5.6 built-in GTIDs for enforcing session consistency. Sooner or later the load balancing will stop working properly and the plugin will direct all session consistency requests to the master.
  • Plugin global transaction ID statistics are only available with client-side emulation because they monitor the emulation.

Note: Global transaction identifiers in distributed systems

Global transaction identifiers can serve multiple purposes in the context of distributed systems, such as a database cluster. Global transaction identifiers can be used for, for example, system wide identification of transactions, global ordering of transactions, heartbeat mechanism and for checking the replication status of replicas. PECL/mysqlnd_ms, a clientside driver based software, does focus on using GTIDs for tasks that can be handled at the client, such as checking the replication status of replicas for asynchronous replication setups.


Cache integration

Note: Version requirement

The feature requires use of PECL/mysqlnd_ms 1.3.0-beta or later, and PECL/mysqlnd_qc 1.1.0-alpha or newer. PECL/mysqlnd_ms must be compiled to support the feature. PHP 5.4.0 or newer is required.

Note: Setup: extension load order

PECL/mysqlnd_ms must be loaded before PECL/mysqlnd_qc, when using shared extensions.

Note: Feature stability

The cache integration is of beta quality.

Note: Suitable MySQL clusters

The feature is targeted for use with MySQL Replication (primary copy). Currently, no other kinds of MySQL clusters are supported. Users of such cluster must control PECL/mysqlnd_qc manually if they are interested in client-side query caching.

Support for MySQL replication clusters (asynchronous primary copy) is the main focus of PECL/mysqlnd_ms. The slaves of a MySQL replication cluster may or may not reflect the latest updates from the master. Slaves are asynchronous and can lag behind the master. A read from a slave is eventual consistent from a cluster-wide perspective.

The same level of consistency is offered by a local cache using time-to-live (TTL) invalidation strategy. Current data or stale data may be served. Eventually, data searched for in the cache is not available and the source of the cache needs to be accessed.

Given that both a MySQL Replication slave (asynchronous secondary) and a local TTL-driven cache deliver the same level of service it is possible to transparently replace a remote database access with a local cache access to gain better possibility.

As of PECL/mysqlnd_ms 1.3.0-beta the plugin is capable of transparently controlling PECL/mysqlnd_ms 1.1.0-alpha or newer to cache a read-only query if explicitly allowed by setting an appropriate quality of service through mysqlnd_ms_set_qos(). P lease, see the quickstart for a code example. Both plugins must be installed, PECL/mysqlnd_ms must be compiled to support the cache feature and PHP 5.4.0 or newer has to be used.

Applications have full control of cache usage and can request fresh data at any time, if need be. The cache usage can be enabled and disabled time during the execution of a script. The cache will be used if mysqlnd_ms_set_qos() sets the quality of service to eventual consistency and enables cache usage. Cache usage is disabled by requesting higher consistency levels, for example, session consistency (read your writes). Once the quality of service has been relaxed to eventual consistency the cache can be used again.

If caching is enabled for a read-only statement, PECL/mysqlnd_ms may inject SQL hints to control caching by PECL/mysqlnd_qc. It may modify the SQL statement it got from the application. Subsequent SQL processors are supposed to ignore the SQL hints. A SQL hint is a SQL comment. Comments must not be ignored, for example, by the database server.

The TTL of a cache entry is computed on a per statement basis. Applications set an maximum age for the data they want to retrieve using mysqlnd_ms_set_qos(). The age sets an approximate upper limit of how many seconds the data returned may lag behind the master.

The following logic is used to compute the actual TTL if caching is enabled. The logic takes the estimated slave lag into account for choosing a TTL. If, for example, there are two slaves lagging 5 and 10 seconds behind and the maximum age allowed is 60 seconds, the TTL is set to 50 seconds. Please note, the age setting is no more than an estimated guess.

  • Check whether the statement is read-only. If not, don't cache.
  • If caching is enabled, check the slave lag of all configured slaves. Establish slave connections if none exist so far and lazy connections are used.
  • Send SHOW SLAVE STATUS to all slaves. Do not wait for the first slave to reply before sending to the second slave. Clients often wait long for replies, thus we send out all requests in a burst before fetching in a second stage.
  • Loop over all slaves. For every slave wait for its reply. Do not start checking another slave before the currently waited for slave has replied. Check for Slave_IO_Running=Yes and Slave_SQL_Running=Yes. If both conditions hold true, fetch the value of Seconds_Behind_Master. In case of any errors or if conditions fail, set an error on the slave connection. Skip any such slave connection for the rest of connection filtering.
  • Search for the maximum value of Seconds_Behind_Master from all slaves that passed the previous conditions. Subtract the value from the maximum age provided by the user with mysqlnd_ms_set_qos(). Use the result as a TTL.
  • The filtering may sort out all slaves. If so, the maximum age is used as TTL, because the maximum lag found equals zero. It is perfectly valid to sort out all slaves. In the following it is up to subsequent filter to decide what to do. The built-in load balancing filter will pick the master.
  • Inject the appropriate SQL hints to enable caching by PECL/mysqlnd_qc.
  • Proceed with the connection filtering, e.g. apply load balancing rules to pick a slave.
  • PECL/mysqlnd_qc is loaded after PECL/mysqlnd_ms by PHP. Thus, it will see all query modifications of PECL/mysqlnd_ms and cache the query if instructed to do so.

The algorithm may seem expensive. SHOW SLAVE STATUS is a very fast operation. Given a sufficient number of requests and cache hits per second the cost of checking the slaves lag can easily outweigh the costs of the cache decision.

Suggestions on a better algorithm are always welcome.


Supported clusters

Any application using any kind of MySQL cluster is faced with the same tasks:

  • Identify nodes capable of executing a given statement with the required service level
  • Load balance requests within the list of candidates
  • Automatic fail over within candidates, if needed

The plugin is optimized for fulfilling these tasks in the context of a classical asynchronous MySQL replication cluster consisting of a single master and many slaves (primary copy). When using classical, asynchronous MySQL replication all of the above listed tasks need to be mastered at the client side.

Other types of MySQL cluster may have lower requirements on the application side. For example, if all nodes in the cluster can answer read and write requests, no read-write splitting needs to be done (multi-master, update-all). If all nodes in the cluster are synchronous, they automatically provide the highest possible quality of service which makes choosing a node easier. In this case, the plugin may serve the application after some reconfiguration to disable certain features, such as built-in read-write splitting.

Note: Documentation focus

The documentation focusses describing the use of the plugin with classical asynchronous MySQL replication clusters (primary copy). Support for this kind of cluster has been the original development goal. Use of other clusters is briefly described below. Please note, that this is still work in progress.

Primary copy (MySQL Replication)

This is the primary use case of the plugin. Follow the hints given in the descriptions of each feature.

  • Configure one master and one or more slaves. Server configuration details are given in the setup section.
  • Use random load balancing policy together with the sticky flag.
  • If you do not plan to use the service level API calls, add the master on write flag.
  • Please, make yourself aware of the properties of automatic failover before adding a failover directive.
  • Consider the use of trx_stickiness to execute transactions on the primary only. Please, read carefully how it works before you rely on it.

Example #1 Enabling the plugin (php.ini)

mysqlnd_ms.enable=1
mysqlnd_ms.config_file=/path/to/mysqlnd_ms_plugin.ini

Example #2 Basic plugin configuration (mysqlnd_ms_plugin.ini) for MySQL Replication

{
  "myapp": {
    "master": {
      "master_1": {
        "host": "localhost",
        "socket": "\/tmp\/mysql57.sock"
      }
    },
    "slave": {
      "slave_0": {
        "host": "127.0.0.1",
        "port": 3308
      },
      "slave_1": {
        "host": "192.168.2.28",
        "port": 3306
      }
    },
    "filters": {
      "random": {
        "sticky": "1"
      }
    }
  }
}

Primary copy with multi primaries (MMM - MySQL Multi Master)

MySQL Replication allows you to create cluster topologies with multiple masters (primaries). Write-write conflicts are not handled by the replication system. This is no update anywhere setup. Thus, data must be partitioned manually and clients must redirected in accordance to the partitioning rules. The recommended setup is equal to the sharding setup below.

Manual sharding, possibly combined with primary copy and multiple primaries

Use SQL hints and the node group filter for clusters that use data partitioning but leave query redirection to the client. The example configuration shows a multi master setup with two shards.

Example #3 Multiple primaries - multi master (php.ini)

mysqlnd_ms.enable=1
mysqlnd_ms.config_file=/path/to/mysqlnd_ms_plugin.ini
mysqlnd_ms.multi_master=1

Example #4 Primary copy with multiple primaries and paritioning

{
  "myapp": {
    "master": {
      "master_1": {
        "host": "localhost",
        "socket": "\/tmp\/mysql57.sock"
      }
      "master_2": {
        "host": "192.168.2.27",
        "socket": "3306"
      }
    },
    "slave": {
      "slave_1": {
        "host": "127.0.0.1",
        "port": 3308
      },
      "slave_2": {
        "host": "192.168.2.28",
        "port": 3306
      }
    },
    "filters": {
      "node_groups": {
        "Partition_A" : {
          "master": ["master_1"],
          "slave": ["slave_1"]
        },
        "Partition_B" : {
          "master": ["master_2"],
          "slave": ["slave_2"]
        }
      },
      "roundrobin": []
    }
  }
}

The plugin can also be used with a loose collection of unrelated shards. For such a cluster, configure masters only and disable read write splitting. The nodes of such a cluster are called masters in the plugin configuration as they accept both reads and writes for their partition.

Using synchronous update everywhere clusters such as MySQL Cluster

MySQL Cluster is a synchronous cluster solution. All cluster nodes accept read and write requests. In the context of the plugin, all nodes shall be considered as masters.

Use the load balancing and fail over features only.

  • Disable the plugins built-in read-write splitting.
  • Configure masters only.
  • Consider random once load balancing strategy, which is the plugins default. If random once is used, only masters are configured and no SQL hints are used to force using a certain node, no connection switches will happen for the duration of a web request. Thus, no special handling is required for transactions. The plugin will pick one master at the beginning of the PHP script and use it until the script terminates.
  • Do not set the quality of service. All nodes have all the data. This automatically gives you the highest possible service quality (strong consistency).
  • Do not enable client-side global transaction injection. It is neither required to help with server-side fail over nor to assist the quality of service filter choosing an appropriate node.

Disabling built-in read-write splitting.

  • Set mysqlnd_ms.disable_rw_split=1
  • Do not use SQL hints to enforce the use of slaves

Configure masters only.

  • Set mysqlnd_ms.multi_master=1.
  • Do not configure any slaves.
  • Set failover=loop_before_master in the plugins configuration file to avoid warnings about the empty slave list and to make the failover logic loop over all configured masters before emitting an error. Please, note the warnings about automatic failover given in the previous sections.

Example #5 Multiple primaries - multi master (php.ini)

mysqlnd_ms.enable=1
mysqlnd_ms.config_file=/path/to/mysqlnd_ms_plugin.ini
mysqlnd_ms.multi_master=1
mysqlnd_ms.disable_rw_split=1

Example #6 Synchronous update anywhere cluster

"myapp": {
    "master": {
      "master_1": {
        "host": "localhost",
        "socket": "\/tmp\/mysql57.sock"
      },
      "master_2": {
        "host": "192.168.2.28",
        "port": 3306
      }
    },
    "slave": {
    },
    "filters": {
      "roundrobin": {
      }
    },
    "failover": {
      "strategy": "loop_before_master",
      "remember_failed": true
    }
  }
}

If running an update everywhere cluster that has no built-in partitioning to avoid hot spots and high collision rates, consider using the node groups filter to keep updates on a frequently accessed table on one of the nodes. This may help to reduce collision rates and thus improve performance.


XA/Distributed transactions

Note: Version requirement

XA related functions have been introduced in PECL/mysqlnd_ms version 1.6.0-alpha.

Note: Early adaptors wanted

The feature is currently under development. There may be issues and/or feature limitations. Do not use in production environments, although early lab tests indicate reasonable quality.

Please, contact the development team if you are interested in this feature. We are looking for real life feedback to complement the feature.

Below is a list of some feature restrictions.

  • The feature is not yet compatible with the MySQL Fabric support . This limitation is soon to be lifted.

    XA transaction identifier are currently restricted to numbers. This limitation will be lifted upon request, it is a simplification used during the initial implementation.

Note: MySQL server restrictions

The XA support by the MySQL server has some restrictions. Most noteably, the servers binary log may lack changes made by XA transactions in case of certain errors. Please, see the MySQL manual for details.

XA/Distributed transactions can spawn multiple MySQL servers. Thus, they may seem like a perfect tool for sharded MySQL clusters, for example, clusters managed with MySQL Fabric. PECL/mysqlnd_ms hides most of the SQL commands to control XA transactions and performs automatic administrative tasks in cases of errors, to provide the user with a comprehensive API. Users should setup the plugin carefully and be well aware of server restrictions prior to using the feature.

Example #1 General pattern for XA transactions

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");

/* BEGIN */
mysqlnd_ms_xa_begin($mysqli, 1 /* xa id */);

/* run queries on various servers */
$mysqli->query("UPDATE some_table SET col_a = 1");
...

/* COMMIT */
mysqlnd_ms_xa_commit($link, 1);
?>

XA transactions use the two-phase commit protocol. The two-phase commit protocol is a blocking protocol. During the first phase participating servers begin a transaction and the client carries out its work. This phase is followed by a second voting phase. During voting, the servers first make a firm promise that they are ready to commit the work even in case of their possible unexpected failure. Should a server crash in this phase, it will still recall the aborted transaction after recover and wait for the client to decide on whether it shall be committed or rolled back.

Should a client that has initiated a global transaction crash after all the participating servers gave their promise to be ready to commit, then the servers must wait for a decision. The servers are not allowed to unilaterally decide on the transaction.

A client crash or disconnect from a participant, a server crash or server error during the fist phase of the protocol is uncritical. In most cases, the server will forget about the XA transaction and its work is rolled back. Additionally, the plugin tries to reach out to as many participants as it can to instruct the server to roll back the work immediately. It is not possible to disable this implicit rollback carried out by PECL/mysqlnd_ms in case of errors during the first phase of the protocol. This design decision has been made to keep the implementation simple.

An error during the second phase of the commit protocol can develop into a more severe situation. The servers will not forget about prepared but unfinished transactions in all cases. The plugin will not attempt to solve these cases immediately but waits for optional background garbage collection to ensure progress of the commit protocol. It is assumed that a solution will take significant time as it may include waiting for a participating server to recover from a crash. This time span may be longer than a developer and end user expects when trying to commit a global transaction with mysqlnd_ms_xa_commit(). Thus, the function returns with the unfinished global transaction still requiring attention. Please, be warned that at this point, it is not yet clear whether the global transaction will be committed or rolled back later on.

Errors during the second phase can be ignored, handled by yourself or solved by the build-int garbage collection logic. Ignoring them is not recommended as you may experience unfinished global transactions on your servers that block resources virtually indefinitely. Handling the errors requires knowing the participants, checking their state and issuing appropriate SQL commands on them. There are no user API calls to expose this very information. You will have to configure a state store and make the plugin record its actions in it to receive the desired facts.

Please, see the quickstart and related plugin configuration file settings for an example how to configure a state. In addition to configuring a state store, you have to setup some SQL tables. The table definitions are given in the description of the plugin configuration settings.

Setting up and configuring a state store is also a precondition for using the built-in garbage collection for XA transactions that fail during the second commit phase. Recording information about ongoing XA transactions is an unavoidable extra task. The extra task consists of updating the state store after each and every operation that changes the state of the global transaction itself (started, committed, rolled back, errors and aborts), the addition of participants (host, optionally user and password required to connect) and any changes to a participants state. Please note, depending on configuration and your security policies, these recordings may be considered sensitive. It is therefore recommended to restrict access to the state store. Unless the state store itself becomes overloaded, writing the state information may contribute noteworthy to the runtime but should overall be only a minor factor.

It is possible that the effort it takes to implement your own routines for handling XA transactions that failed during the second commit phase exceeds the benefits of using the XA feature of PECL/mysqlnd_ms in the first place. Thus, the manual focussed on using the built-on garbage collection only.

Garbage collection can be triggered manually or automatically in the background. You may want to call mysqlnd_ms_xa_gc() immediately after a commit failure to attempt to solve any failed but still open global transactions as soon as possible. You may also decide to disable the automatic background garbage collection, implement your own rule set for invoking the built-in garbage collection and trigger it when desired.

By default the plugin will start the garbage collection with a certain probability in the extensions internal RSHUTDOWN method. The request shutdown is called after your script finished. Whether the garbage collection will be triggered is determined by computing a random value between 1...1000 and comparing it with the configuration setting probability (default: 5). If the setting is greater or equal to the random value, the garbage collection will be triggered.

Once started, the garbage collection acts upon up to max_transactions_per_run (default: 100) global transactions recorded. Records include successfully finished but also unfinished XA transactions. Records for successful transactions are removed and unfinished transactions are attempted to be solved. There are no statistics that help you finding the right balance between keeping garbage collection runs short by limiting the number of transactions considered per run and preventing the garbage collection to fall behind, resulting in many records.

For each failed XA transaction the garbage collection makes max_retries (default: 5) attempts to finish it. After that PECL/mysqlnd_ms gives up. There are two possible reasons for this. Either a participating server crashed and has not become accessible again within max_retries invocations of the garbage collection, or there is a situation that the built-in garbage collection cannot cope with. Likely, the latter would be considered a bug. However, you can manually force more garbage collection runs calling mysqlnd_ms_xa_gc() with the appropriate parameter set. Should even those function runs fail to solve the situation, then the problem must be solved by an operator.

The function mysqlnd_ms_get_stats() provides some statistics on how many XA transactions have been started, committed, failed or rolled back.


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Plugin configuration file (>=1.1.x)


Requirements

PHP 5.3.6 or newer. Some advanced functionality requires PHP 5.4.0 or newer.

The mysqlnd_ms replication and load balancing plugin supports all PHP applications and all available PHP MySQL extensions (mysqli, mysql, PDO_MYSQL). The PHP MySQL extension must be configured to use mysqlnd in order to be able to use the mysqlnd_ms plugin for mysqlnd.


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/mysqlnd_ms

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Mysqlnd_ms Configure Options
Name | Default | Changeable | Changelog
mysqlnd_ms.enable | 0 | PHP_INI_SYSTEM |
mysqlnd_ms.force_config_usage | 0 | PHP_INI_SYSTEM |
mysqlnd_ms.ini_file | "" | PHP_INI_SYSTEM |
mysqlnd_ms.config_file | "" | PHP_INI_SYSTEM |
mysqlnd_ms.collect_statistics | 0 | PHP_INI_SYSTEM |
mysqlnd_ms.multi_master | 0 | PHP_INI_SYSTEM |
mysqlnd_ms.disable_rw_split | 0 | PHP_INI_SYSTEM |

Here's a short explanation of the configuration directives.

mysqlnd_ms.enable integer

Enables or disables the plugin. If disabled, the extension will not plug into mysqlnd to proxy internal mysqlnd C API calls.

mysqlnd_ms.force_config_usage integer

If enabled, the plugin checks if the host (server) parameters value of any MySQL connection attempt, matches a section name from the plugin configuration file. If not, the connection attempt is blocked.

This setting is not only useful to restrict PHP to certain servers but also to debug configuration file problems. The configuration file validity is checked at two different stages. The first check is performed when PHP begins to handle a web request. At this point the plugin reads and decodes the configuration file. Errors thrown at this early stage in an extensions life cycle may not be shown properly to the user. Thus, the plugin buffers the errors, if any, and additionally displays them when establishing a connection to MySQL. By default a buffered startup error will emit an error of type E_WARNING. If force_config_usage is set, the error type used is E_RECOVERABLE_ERROR.

Please, see also configuration file debugging notes.

mysqlnd_ms.ini_file string

Plugin specific configuration file. This setting has been renamed to mysqlnd_ms.config_file in version 1.4.0.

mysqlnd_ms.config_file string

Plugin specific configuration file. This setting superseeds mysqlnd_ms.ini_file since 1.4.0.

mysqlnd_ms.collect_statistics integer

Enables or disables the collection of statistics. The collection of statistics is disabled by default for performance reasons. Statistics are returned by the function mysqlnd_ms_get_stats().

mysqlnd_ms.multi_master integer

Enables or disables support of MySQL multi master replication setups. Please, see also supported clusters.

mysqlnd_ms.disable_rw_split integer

Enables or disables built-in read write splitting.

Controls whether load balancing and lazy connection functionality can be used independently of read write splitting. If read write splitting is disabled, only servers from the master list will be used for statement execution. All configured slave servers will be ignored.

The SQL hint MYSQLND_MS_USE_SLAVE will not be recognized. If found, the statement will be redirected to a master.

Disabling read write splitting impacts the return value of mysqlnd_ms_query_is_select(). The function will no longer propose query execution on slave servers.

Note: Multiple master servers

Setting mysqlnd_ms.multi_master=1 allows the plugin to use multiple master servers, instead of only the first master server of the master list.

Please, see also supported clusters.


Plugin configuration file (>=1.1.x)

The following documentation applies to PECL/mysqlnd_ms >= 1.1.0-beta. It is not valid for prior versions. For documentation covering earlier versions, see the configuration documentation for mysqlnd_ms 1.0.x and below.

Introduction

Note: Changelog: Feature was added in PECL/mysqlnd_ms 1.1.0-beta

The below description applies to PECL/mysqlnd_ms >= 1.1.0-beta. It is not valid for prior versions.

The plugin uses its own configuration file. The configuration file holds information about the MySQL replication master server, the MySQL replication slave servers, the server pick (load balancing) policy, the failover strategy, and the use of lazy connections.

The plugin loads its configuration file at the beginning of a web request. It is then cached in memory and used for the duration of the web request. This way, there is no need to restart PHP after deploying the configuration file. Configuration file changes will become active almost instantly.

The PHP configuration directive mysqlnd_ms.config_file is used to set the plugins configuration file. Please note, that the PHP configuration directive may not be evaluated for every web request. Therefore, changing the plugins configuration file name or location may require a PHP restart. However, no restart is required to read changes if an already existing plugin configuration file is updated.

Using and parsing JSON is efficient, and using JSON makes it easier to express hierarchical data structures than the standard php.ini format.

Example #1 Converting a PHP array (hash) into JSON format

Or alternatively, a developer may be more familiar with the PHP array syntax, and prefer it. This example demonstrates how a developer might convert a PHP array to JSON.

<?php
$config = array(
  "myapp" => array(
    "master" => array(
      "master_0" => array(
        "host"   => "localhost",
        "socket" => "/tmp/mysql.sock",
      ),
    ),
    "slave" => array(),
  ),
);

file_put_contents("mysqlnd_ms.ini", json_encode($config, JSON_PRETTY_PRINT));
printf("mysqlnd_ms.ini file created...\n");
printf("Dumping file contents...\n");
printf("%s\n", str_repeat("-", 80));
echo file_get_contents("mysqlnd_ms.ini");
printf("\n%s\n", str_repeat("-", 80));
?>

The above example will output:

mysqlnd_ms.ini file created...
Dumping file contents...
--------------------------------------------------------------------------------
{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": [

        ]
    }
}
--------------------------------------------------------------------------------

A plugin configuration file consists of one or more sections. Sections are represented by the top-level object properties of the object encoded in the JSON file. Sections could also be called configuration names.

Applications reference sections by their name. Applications use section names as the host (server) parameter to the various connect methods of the mysqli, mysql and PDO_MYSQL extensions. Upon connect, the mysqlnd plugin compares the hostname with all of the section names from the plugin configuration file. If the hostname and section name match, then the plugin will load the settings for that section.

Example #2 Using section names example

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.2.27"
            },
            "slave_1": {
                "host": "192.168.2.27",
                "port": 3306
            }
        }
    },
    "localhost": {
        "master": [
            {
                "host": "localhost",
                "socket": "\/path\/to\/mysql.sock"
            }
        ],
        "slave": [
            {
                "host": "192.168.3.24",
                "port": "3305"
            },
            {
                "host": "192.168.3.65",
                "port": "3309"
            }
        ]
    }
}
<?php
/* All of the following connections will be load balanced */
$mysqli = new mysqli("myapp", "username", "password", "database");
$pdo = new PDO('mysql:host=myapp;dbname=database', 'username', 'password');
$mysql = mysql_connect("myapp", "username", "password");

$mysqli = new mysqli("localhost", "username", "password", "database");
?>

Section names are strings. It is valid to use a section name such as 192.168.2.1, 127.0.0.1 or localhost. If, for example, an application connects to localhost and a plugin configuration section localhost exists, the semantics of the connect operation are changed. The application will no longer only use the MySQL server running on the host localhost, but the plugin will start to load balance MySQL queries following the rules from the localhost configuration section. This way you can load balance queries from an application without changing the applications source code. Please keep in mind, that such a configuration may not contribute to overall readability of your applications source code. Using section names that can be mixed up with host names should be seen as a last resort.

Each configuration section contains, at a minimum, a list of master servers and a list of slave servers. The master list is configured with the keyword master, while the slave list is configured with the slave keyword. Failing to provide a slave list will result in a fatal E_ERROR level error, although a slave list may be empty. It is possible to allow no slaves. However, this is only recommended with synchronous clusters, please see also supported clusters. The main part of the documentation focusses on the use of asynchronous MySQL replication clusters.

The master and slave server lists can be optionally indexed by symbolic names for the servers they describe. Alternatively, an array of descriptions for slave and master servers may be used.

Example #3 List of anonymous slaves

"slave": [
    {
        "host": "192.168.3.24",
        "port": "3305"
    },
    {
        "host": "192.168.3.65",
        "port": "3309"
    }
]

An anonymous server list is encoded by the JSON array type. Optionally, symbolic names may be used for indexing the slave or master servers of a server list, and done so using the JSON object type.

Example #4 Master list using symbolic names

"master": {
    "master_0": {
        "host": "localhost"
    }
}

It is recommended to index the server lists with symbolic server names. The alias names will be shown in error messages.

The order of servers is preserved and taken into account by mysqlnd_ms. If, for example, you configure round robin load balancing strategy, the first SELECT statement will be executed on the slave that appears first in the slave server list.

A configured server can be described with the host, port, socket, db, user, password and connect_flags. It is mandatory to set the database server host using the host keyword. All other settings are optional.

Example #5 Keywords to configure a server

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "db_server_host",
                "port": "db_server_port",
                "socket": "db_server_socket",
                "db": "database_resp_schema",
                "user": "user",
                "password": "password",
                "connect_flags": 0
            }
        },
        "slave": {
            "slave_0": {
                "host": "db_server_host",
                "port": "db_server_port",
                "socket": "db_server_socket"
            }
        }
    }
}

If a setting is omitted, the plugin will use the value provided by the user API call used to open a connection. Please, see the using section names example above.

The configuration file format has been changed in version 1.1.0-beta to allow for chained filters. Filters are responsible for filtering the configured list of servers to identify a server for execution of a given statement. Filters are configured with the filter keyword. Filters are executed by mysqlnd_ms in the order of their appearance. Defining filters is optional. A configuration section in the plugins configuration file does not need to have a filters entry.

Filters replace the pick[] setting from prior versions. The new random and roundrobin provide the same functionality.

Example #6 New roundrobin filter, old functionality

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            },
            "slave_1": {
                "host": "192.168.78.137",
                "port": "3306"
            }
        },
        "filters": {
            "roundrobin": [

            ]
        }
    }
}

The function mysqlnd_ms_set_user_pick_server() has been removed. Setting a callback is now done with the user filter. Some filters accept parameters. The user filter requires and accepts a mandatory callback parameter to set the callback previously set through the function mysqlnd_ms_set_user_pick_server().

Example #7 The user filter replaces mysqlnd_ms_set_user_pick_server()

"filters": {
    "user": {
        "callback": "pick_server"
    }
}

The validity of the configuration file is checked both when reading the configuration file and later when establishing a connection. The configuration file is read during PHP request startup. At this early stage a PHP extension may not display error messages properly. In the worst case, no error is shown and a connection attempt fails without an adequate error message. This problem has been cured in version 1.5.0.

Example #8 Common error message in case of configuration file issues (upto version 1.5.0)

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
?>

The above example will output:

Warning: mysqli::mysqli(): (mysqlnd_ms) (mysqlnd_ms) Failed to parse config file [s1.json]. Please, verify the JSON in Command line code

Warning: mysqli::mysqli(): (HY000/2002): php_network_getaddresses: getaddrinfo failed: Name or service not known in Command line code on line 1

Warning: mysqli::query(): Couldn't fetch mysqli in Command line code on line 1

Fatal error: Call to a member function fetch_assoc() on a non-object in Command line code on line 1

Since version 1.5.0 startup errors are additionally buffered and emitted when a connection attempt is made. Use the configuration directive mysqlnd_ms.force_config_usage to set the error type used to display buffered errors. By default an error of type E_WARNING will be emitted.

Example #9 Improved configuration file validation since 1.5.0

<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
?>

The above example will output:

Warning: mysqli::mysqli(): (mysqlnd_ms) (mysqlnd_ms) Failed to parse config file [s1.json]. Please, verify the JSON in Command line code on line 1

It can be useful to set mysqlnd_ms.force_config_usage = 1 when debugging potential configuration file errors. This will not only turn the type of buffered startup errors into E_RECOVERABLE_ERROR but also help detecting misspelled section names.

Example #10 Possibly more precise error due to mysqlnd_ms.force_config_usage=1

mysqlnd_ms.force_config_usage=1
<?php
$mysqli = new mysqli("invalid_section", "username", "password", "database");
?>

The above example will output:

Warning: mysqli::mysqli(): (mysqlnd_ms) Exclusive usage of configuration enforced but did not find the correct INI file section (invalid_section) in Command line code on line 1 line 1

Configuration Directives

Here is a short explanation of the configuration directives that can be used.

master array or object

List of MySQL replication master servers. The list of either of the JSON type array to declare an anonymous list of servers or of the JSON type object. Please, see above for examples.

Setting at least one master server is mandatory. The plugin will issue an error of type E_ERROR if the user has failed to provide a master server list for a configuration section. The fatal error may read (mysqlnd_ms) Section [master] doesn't exist for host [name_of_a_config_section] in %s on line %d.

A server is described with the host, port, socket, db, user, password and connect_flags. It is mandatory to provide at a value for host. If any of the other values is not given, it will be taken from the user API connect call, please, see also: using section names example.

Table of server configuration keywords.

Keyword Description Version
host

Database server host. This is a mandatory setting. Failing to provide, will cause an error of type E_RECOVERABLE_ERROR when the plugin tries to connect to the server. The error message may read (mysqlnd_ms) Cannot find [host] in [%s] section in config in %s on line %d.

Since 1.1.0.
port

Database server TCP/IP port.

Since 1.1.0.
socket

Database server Unix domain socket.

Since 1.1.0.
db

Database (schemata).

Since 1.1.0.
user

MySQL database user.

Since 1.1.0.
password

MySQL database user password.

Since 1.1.0.
connect_flags

Connection flags.

Since 1.1.0.

The plugin supports using only one master server. An experimental setting exists to enable multi-master support. The details are not documented. The setting is meant for development only.

slave array or object

List of one or more MySQL replication slave servers. The syntax is identical to setting master servers, please, see master above for details.

The plugin supports using one or more slave servers.

Setting a list of slave servers is mandatory. The plugin will report an error of the type E_ERROR if slave is not given for a configuration section. The fatal error message may read (mysqlnd_ms) Section [slave] doesn't exist for host [%s] in %s on line %d. Note, that it is valid to use an empty slave server list. The error has been introduced to prevent accidentally setting no slaves by forgetting about the slave setting. A master-only setup is still possible using an empty slave server list.

If an empty slave list is configured and an attempt is made to execute a statement on a slave the plugin may emit a warning like mysqlnd_ms) Couldn't find the appropriate slave connection. 0 slaves to choose from. upon statement execution. It is possible that another warning follows such as (mysqlnd_ms) No connection selected by the last filter.

global_transaction_id_injection array or object

Global transaction identifier configuration related to both the use of the server built-in global transaction ID feature and the client-side emulation.

Keyword Description Version
fetch_last_gtid

SQL statement for accessing the latest global transaction identifier. The SQL statement is run if the plugin needs to know the most recent global transaction identifier. This can be the case, for example, when checking MySQL Replication slave status. Also used with mysqlnd_ms_get_last_gtid().

Since 1.2.0.
check_for_gtid

SQL statement for checking if a replica has replicated all transactions up to and including ones searched for. The SQL statement is run when searching for replicas which can offer a higher level of consistency than eventual consistency. The statement must contain a placeholder #GTID which is to be replaced with the global transaction identifier searched for by the plugin. Please, check the quickstart for examples.

Since 1.2.0.
report_errors

Whether to emit an error of type warning if an issue occurs while executing any of the configured SQL statements.

Since 1.2.0.
on_commit

Client-side global transaction ID emulation only. SQL statement to run when a transaction finished to update the global transaction identifier sequence number on the master. Please, see the quickstart for examples.

Since 1.2.0.
wait_for_gtid_timeout

Instructs the plugin to wait up to wait_for_gtid_timeout seconds for a slave to catch up when searching for slaves that can deliver session consistency. The setting limits the time spend for polling the slave status. If polling the status takes very long, the total clock time spend waiting may exceed wait_for_gtid_timeout. The plugin calls sleep(1) to sleep one second between each two polls.

The setting can be used both with the plugins client-side emulation and the server-side global transaction identifier feature of MySQL 5.6.

Waiting for a slave to replicate a certain GTID needed for session consistency also means throttling the client. By throttling the client the write load on the master is reduced indirectly. A primary copy based replication system, such as MySQL Replication, is given more time to reach a consistent state. This can be desired, for example, to increase the number of data copies for high availability considerations or to prevent the master from being overloaded.

Since 1.4.0.
fabric object

MySQL Fabric related settings. If the plugin is used together with MySQL Fabric, then the plugins configuration file no longer contains lists of MySQL servers. Instead, the plugin will ask MySQL Fabric which list of servers to use to perform a certain task.

A minimum plugin configuration for use with MySQL Fabric contains a list of one or more MySQL Fabric hosts that the plugin can query. If more than one MySQL Fabric host is configured, the plugin will use a roundrobin strategy to choose among them. Other strategies are currently not available.

Example #11 Minimum pluging configuration for use with MySQL Fabric

{
    "myapp": {
        "fabric": {
            "hosts": [
                {
                    "host" : "127.0.0.1",
                    "port" : 8080
                }
            ]
        }
    }
}

Each MySQL Fabric host is described using a JSON object with the following members.

Keyword Description Version
host

Host name of the MySQL Fabric host.

Since 1.6.0.
port

The TCP/IP port on which the MySQL Fabric host listens for remote procedure calls sent by clients such as the plugin.

Since 1.6.0.

The plugin is using PHP streams to communicate with MySQL Fabric through XML RPC over HTTP. By default no timeouts are set for the network communication. Thus, the plugin defaults to PHP stream default timeouts. Those defaults are out of control of the plugin itself.

An optional timeout value can be set to overrule the PHP streams default timeout setting. Setting the timeout in the plugins configuration file has the same effect as setting a timeout for a PHP user space HTTP connection established through PHP streams.

The plugins Fabric timeout value unit is seconds. The allowed value range is from 0 to 65535. The setting exists since version 1.6.

Example #12 Optional timeout for communication with Fabric

{
    "myapp": {
        "fabric": {
            "hosts": [
                {
                    "host" : "127.0.0.1",
                    "port" : 8080
                }
            ],
            "timeout": 2
        }
    }
}

Transaction stickiness and MySQL Fabric logic can collide. The stickiness option disables switching between servers for the duration of a transaction. When using Fabric and sharding the user may (erroneously) start a local transaction on one share and then attempt to switch to a different shard using either mysqlnd_ms_fabric_select_shard() or mysqlnd_ms_fabric_select_global(). In this case, the plugin will not reject the request to switch servers in the middle of a transaction but allow the user to switch to another server regardless of the transaction stickiness setting used. It is clearly a user error to write such code.

If transaction stickiness is enabled and you would like to get an error of type warning when calling mysqlnd_ms_fabric_select_shard() or mysqlnd_ms_fabric_select_global(), set the boolean flag trx_warn_server_list_changes.

Example #13 Warnings about the violation of transaction boundaries

{
    "myapp": {
        "fabric": {
            "hosts": [
                {
                    "host" : "127.0.0.1",
                    "port" : 8080
                }
            ],
            "trx_warn_serverlist_changes": 1
        },
        "trx_stickiness": "on"
    }
}
<?php
$link = new mysqli("myapp", "root", "", "test");
/*
  For the demo the call may fail.
  Failed or not we get into the state
  needed for the example.
*/
@mysqlnd_ms_fabric_select_global($link, 1);
$link->begin_transaction();
@$link->query("DROP TABLE IF EXISTS test");
/*
  Switching servers/shards is a mistake due to open
  local transaction!
*/
mysqlnd_ms_select_global($link, 1);
?>

The above example will output:

PHP Warning: mysqlnd_ms_fabric_select_global(): (mysqlnd_ms) Fabric server exchange in the middle of a transaction in %s on line %d

Please, consider the feature experimental. Changes to syntax and semantics may happen.

filters object

List of filters. A filter is responsible to filter the list of available servers for executing a given statement. Filters can be chained. The random and roundrobin filter replace the pick[] directive used in prior version to select a load balancing policy. The user filter replaces the mysqlnd_ms_set_user_pick_server() function.

Filters may accept parameters to refine their actions.

If no load balancing policy is set, the plugin will default to random_once. The random_once policy picks a random slave server when running the first read-only statement. The slave server will be used for all read-only statements until the PHP script execution ends. No load balancing policy is set and thus, defaulting takes place, if neither the random nor the roundrobin are part of a configuration section.

If a filter chain is configured so that a filter which output no more than once server is used as input for a filter which should be given more than one server as input, the plugin may emit a warning upon opening a connection. The warning may read: (mysqlnd_ms) Error while creating filter '%s' . Non-multi filter '%s' already created. Stopping in %s on line %d. Furthermore, an error of the error code 2000, the sql state HY000 and an error message similar to the warning may be set on the connection handle.

Example #14 Invalid filter sequence

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "filters": [
            "roundrobin",
            "random"
        ]
    }
}
<?php
$link = new mysqli("myapp", "root", "", "test");
printf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error());
$link->query("SELECT 1 FROM DUAL");
?>

The above example will output:

PHP Warning:  mysqli::mysqli(): (HY000/2000): (mysqlnd_ms) Error while creating filter 'random' . Non-multi filter 'roundrobin' already created. Stopping in filter_warning.php on line 1
[2000] (mysqlnd_ms) Error while creating filter 'random' . Non-multi filter 'roundrobin' already created. Stopping
PHP Warning:  mysqli::query(): Couldn't fetch mysqli in filter_warning.php on line 3

Filter: random object

The random filter features the random and random once load balancing policies, set through the pick[] directive in older versions.

The random policy will pick a random server whenever a read-only statement is to be executed. The random once strategy picks a random slave server once and continues using the slave for the rest of the PHP web request. Random once is a default, if load balancing is not configured through a filter.

If the random filter is not given any arguments, it stands for random load balancing policy.

Example #15 Random load balancing with random filter

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            },
            "slave_1": {
                "host": "192.168.78.137",
                "port": "3306"
            }
        },
        "filters": [
            "random"
        ]
    }
}

Optionally, the sticky argument can be passed to the filter. If the parameter sticky is set to the string 1, the filter follows the random once load balancing strategy.

Example #16 Random once load balancing with random filter

{
    "filters": {
        "random": {
            "sticky": "1"
        }
    }
}

Both the random and roundrobin filters support setting a priority, a weight for a server, since PECL/mysqlnd_ms 1.4.0. If the weight argument is passed to the filter, it must assign a weight for all servers. Servers must be given an alias name in the slave respectively master server lists. The alias must be used to reference servers for assigning a priority with weight.

Example #17 Referencing error

[E_RECOVERABLE_ERROR] mysqli_real_connect(): (mysqlnd_ms) Unknown server 'slave3' in 'random' filter configuration. Stopping in %s on line %d

Using a wrong alias name with weight may result in an error similar to the shown above.

If weight is omitted, the default weight of all servers is one.

Example #18 Assigning a weight for load balancing

{
   "myapp": {
       "master": {
           "master1":{
               "host":"localhost",
               "socket":"\/var\/run\/mysql\/mysql.sock"
           }
       },
       "slave": {
           "slave1": {
               "host":"192.168.2.28",
               "port":3306
           },
           "slave2": {
               "host":"192.168.2.29",
               "port":3306
           },
           "slave3": {
               "host":"192.0.43.10",
               "port":3306
           },
       },
       "filters": {
           "random": {
               "weights": {
                   "slave1":8,
                   "slave2":4,
                   "slave3":1,
                   "master1":1
               }
           }
       }
   }
}

At the average a server assigned a weight of two will be selected twice as often as a server assigned a weight of one. Different weights can be assigned to reflect differently sized machines, to prefer co-located slaves which have a low network latency or, to configure a standby failover server. In the latter case, you may want to assign the standby server a very low weight in relation to the other servers. For example, given the configuration above slave3 will get only some eight percent of the requests in the average. As long as slave1 and slave2 are running, it will be used sparsely, similar to a standby failover server. Upon failure of slave1 and slave2, the usage of slave3 increases. Please, check the notes on failover before using weight this way.

Valid weight values range from 1 to 65535.

Unknown arguments are ignored by the filter. No warning or error is given.

The filter expects one or more servers as input. Outputs one server. A filter sequence such as random, roundrobin may cause a warning and an error message to be set on the connection handle when executing a statement.

List of filter arguments.

Keyword Description Version
sticky

Enables or disabled random once load balancing policy. See above.

Since 1.2.0.
weight

Assigns a load balancing weight/priority to a server. Please, see above for a description.

Since 1.4.0.
Filter: roundrobin object

If using the roundrobin filter, the plugin iterates over the list of configured slave servers to pick a server for statement execution. If the plugin reaches the end of the list, it wraps around to the beginning of the list and picks the first configured slave server.

Example #19 roundrobin filter

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "filters": [
            "roundrobin"
        ]
    }
}

Expects one or more servers as input. Outputs one server. A filter sequence such as roundrobin, random may cause a warning and an error message to be set on the connection handle when executing a statement.

List of filter arguments.

Keyword Description Version
weight

Assigns a load balancing weight/priority to a server. Please, find a description above.

Since 1.4.0.
Filter: user object

The user replaces mysqlnd_ms_set_user_pick_server() function, which was removed in 1.1.0-beta. The filter sets a callback for user-defined read/write splitting and server selection.

The plugins built-in read/write query split mechanism decisions can be overwritten in two ways. The easiest way is to prepend a query string with the SQL hints MYSQLND_MS_MASTER_SWITCH, MYSQLND_MS_SLAVE_SWITCH or MYSQLND_MS_LAST_USED_SWITCH. Using SQL hints one can control, for example, whether a query shall be send to the MySQL replication master server or one of the slave servers. By help of SQL hints it is not possible to pick a certain slave server for query execution.

Full control on server selection can be gained using a callback function. Use of a callback is recommended to expert users only because the callback has to cover all cases otherwise handled by the plugin.

The plugin will invoke the callback function for selecting a server from the lists of configured master and slave servers. The callback function inspects the query to run and picks a server for query execution by returning the hosts URI, as found in the master and slave list.

If the lazy connections are enabled and the callback chooses a slave server for which no connection has been established so far and establishing the connection to the slave fails, the plugin will return an error upon the next action on the failed connection, for example, when running a query. It is the responsibility of the application developer to handle the error. For example, the application can re-run the query to trigger a new server selection and callback invocation. If so, the callback must make sure to select a different slave, or check slave availability, before returning to the plugin to prevent an endless loop.

Example #20 Setting a callback

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "filters": {
            "user": {
                "callback": "pick_server"
            }
        }
    }
}

The callback is supposed to return a host to run the query on. The host URI is to be taken from the master and slave connection lists passed to the callback function. If callback returns a value neither found in the master nor in the slave connection lists the plugin will emit an error of the type E_RECOVERABLE_ERROR The error may read like (mysqlnd_ms) User filter callback has returned an unknown server. The server 'server that is not in master or slave list' can neither be found in the master list nor in the slave list. If the application catches the error to ignore it, follow up errors may be set on the connection handle, for example, (mysqlnd_ms) No connection selected by the last filter with the error code 2000 and the sqlstate HY000. Furthermore a warning may be emitted.

Referencing a non-existing function as a callback will result in any error of the type E_RECOVERABLE_ERROR whenever the plugin tries to callback function. The error message may reads like: (mysqlnd_ms) Specified callback (pick_server) is not a valid callback. If the application catches the error to ignore it, follow up errors may be set on the connection handle, for example, (mysqlnd_ms) Specified callback (pick_server) is not a valid callback with the error code 2000 and the sqlstate HY000. Furthermore a warning may be emitted.

The following parameters are passed from the plugin to the callback.

Parameter Description Version
connected_host

URI of the currently connected database server.

Since 1.1.0.
query

Query string of the statement for which a server needs to be picked.

Since 1.1.0.
masters

List of master servers to choose from. Note, that the list of master servers may not be identical to the list of configured master servers if the filter is not the first in the filter chain. Previously run filters may have reduced the master list already.

Since 1.1.0.
slaves

List of slave servers to choose from. Note, that the list of slave servers may not be identical to the list of configured slave servers if the filter is not the first in the filter chain. Previously run filters may have reduced the slave list already.

Since 1.1.0.
last_used_connection

URI of the server of the connection used to execute the previous statement on.

Since 1.1.0.
in_transaction

Boolean flag indicating whether the statement is part of an open transaction. If autocommit mode is turned off, this will be set to TRUE. Otherwise it is set to FALSE.

Transaction detection is based on monitoring the mysqlnd library call set_autocommit. Monitoring is not possible before PHP 5.4.0. Please, see connection pooling and switching concepts discussion for further details.

Since 1.1.0.

Example #21 Using a callback

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.2.27",
                "port": "3306"
            },
            "slave_1": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "filters": {
            "user": {
                "callback": "pick_server"
            }
        }
    }
}
<?php
function pick_server($connected, $query, $masters, $slaves, $last_used_connection, $in_transaction)
{
 static $slave_idx = 0;
 static $num_slaves = NULL;
 if (is_null($num_slaves))
  $num_slaves = count($slaves);

 /* default: fallback to the plugins build-in logic */
 $ret = NULL;

 printf("User has connected to '%s'...\n", $connected);
 printf("... deciding where to run '%s'\n", $query);

 $where = mysqlnd_ms_query_is_select($query);
 switch ($where)
 {
  case MYSQLND_MS_QUERY_USE_MASTER:
   printf("... using master\n");
   $ret = $masters[0];
   break;
  case MYSQLND_MS_QUERY_USE_SLAVE:
   /* SELECT or SQL hint for using slave */
   if (stristr($query, "FROM table_on_slave_a_only"))
   {
    /* a table which is only on the first configured slave  */
    printf("... access to table available only on slave A detected\n");
    $ret = $slaves[0];
   }
   else
   {
    /* round robin */
    printf("... some read-only query for a slave\n");
    $ret = $slaves[$slave_idx++ % $num_slaves];
   }
   break;
  case MYSQLND_MS_QUERY_LAST_USED:
   printf("... using last used server\n");
   $ret = $last_used_connection;
   break;
 }

 printf("... ret = '%s'\n", $ret);
 return $ret;
}

$mysqli = new mysqli("myapp", "root", "", "test");

if (!($res = $mysqli->query("SELECT 1 FROM DUAL")))
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
else
 $res->close();

if (!($res = $mysqli->query("SELECT 2 FROM DUAL")))
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
else
 $res->close();

if (!($res = $mysqli->query("SELECT * FROM table_on_slave_a_only")))
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
else
 $res->close();

$mysqli->close();
?>

The above example will output:

User has connected to 'myapp'...
... deciding where to run 'SELECT 1 FROM DUAL'
... some read-only query for a slave
... ret = 'tcp://192.168.2.27:3306'
User has connected to 'myapp'...
... deciding where to run 'SELECT 2 FROM DUAL'
... some read-only query for a slave
... ret = 'tcp://192.168.78.136:3306'
User has connected to 'myapp'...
... deciding where to run 'SELECT * FROM table_on_slave_a_only'
... access to table available only on slave A detected
... ret = 'tcp://192.168.2.27:3306'

Filter: user_multi object

The user_multi differs from the user only in one aspect. Otherwise, their syntax is identical. The user filter must pick and return exactly one node for statement execution. A filter chain usually ends with a filter that emits only one node. The filter chain shall reduce the list of candidates for statement execution down to one. This, only one node left, is the case after the user filter has been run.

The user_multi filter is a multi filter. It returns a list of slave and a list of master servers. This list needs further filtering to identify exactly one node for statement execution. A multi filter is typically placed at the top of the filter chain. The quality_of_service filter is another example of a multi filter.

The return value of the callback set for user_multi must be an array with two elements. The first element holds a list of selected master servers. The second element contains a list of selected slave servers. The lists shall contain the keys of the slave and master servers as found in the slave and master lists passed to the callback. The below example returns random master and slave lists extracted from the functions input.

Example #22 Returning random masters and slaves

<?php
function pick_server($connected, $query, $masters, $slaves, $last_used_connection, $in_transaction)
{
  $picked_masters = array()
  foreach ($masters as $key => $value) {
    if (mt_rand(0, 2) > 1)
      $picked_masters[] = $key;
  }
  $picked_slaves = array()
  foreach ($slaves as $key => $value) {
    if (mt_rand(0, 2) > 1)
      $picked_slaves[] = $key;
  }
  return array($picked_masters, $picked_slaves);
}
?>

The plugin will issue an error of type E_RECOVERABLE if the callback fails to return a server list. The error may read (mysqlnd_ms) User multi filter callback has not returned a list of servers to use. The callback must return an array in %s on line %d. In case the server list is not empty but has invalid servers key/ids in it, an error of type E_RECOVERABLE will the thrown with an error message like (mysqlnd_ms) User multi filter callback has returned an invalid list of servers to use. Server id is negative in %s on line %d, or similar.

Whether an error is emitted in case of an empty slave or master list depends on the configuration. If an empty master list is returned for a write operation, it is likely that the plugin will emit a warning that may read (mysqlnd_ms) Couldn't find the appropriate master connection. 0 masters to choose from. Something is wrong in %s on line %d. Typically a follow up error of type E_ERROR will happen. In case of a read operation and an empty slave list the behavior depends on the fail over configuration. If fail over to master is enabled, no error should appear. If fail over to master is deactivated the plugin will emit a warning that may read (mysqlnd_ms) Couldn't find the appropriate slave connection. 0 slaves to choose from. Something is wrong in %s on line %d.

Filter: node_groups object

The node_groups filter lets you group cluster nodes and query selected groups, for example, to support data partitioning. Data partitioning can be required for manual sharding, primary copy based clusters running multiple masters, or to avoid hot spots in update everywhere clusters that have no built-in partitioning. The filter is a multi filter which returns zero, one or multiple of its input servers. Thus, it must be followed by other filters to reduce the number of candidates down to one for statement execution.

Keyword Description Version
user defined node group name

One or more node groups must be defined. A node group can have an arbitrary user defined name. The name is used in combination with a SQL hint to restrict query execution to the nodes listed for the node group. To run a query on any of the servers of a node group, the query must begin with the SQL hint /*user defined node group name*/. Please note, no white space is allowed around user defined node group name. Because user defined node group name is used as-is as part of a SQL hint, you should choose the name that is compliant with the SQL language.

Each node group entry must contain a list of master servers. Additional slave servers are allowed. Failing to provide a list of master for a node group name_of_group may cause an error of type E_RECOVERABLE_ERROR like (mysqlnd_ms) No masters configured in node group 'name_of_group' for 'node_groups' filter.

The list of master and slave servers must reference corresponding entries in the global master respectively slave server list. Referencing an unknown server in either of the both server lists may cause an E_RECOVERABLE_ERROR error like (mysqlnd_ms) Unknown master 'server_alias_name' (section 'name_of_group') in 'node_groups' filter configuration.

Example #23 Manual partitioning

{
  "myapp": {
       "master": {
            "master_0": {
                "host": "localhost",
                "socket": "\/tmp\/mysql.sock"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.2.28",
                "port": 3306
            },
            "slave_1": {
                "host": "127.0.0.1",
                "port": 3311
            }
        },
        "filters": {
            "node_groups": {
                "Partition_A" : {
                    "master": ["master_0"],
                    "slave": ["slave_0"]
                }
            },
           "roundrobin": []
        }
    }
}

Please note, if a filter chain generates an empty slave list and the PHP configuration directive mysqlnd_ms.multi_master=0 is used, the plugin may emit a warning.

Since 1.5.0.
Filter: quality_of_service object

The quality_of_service identifies cluster nodes capable of delivering a certain quality of service. It is a multi filter which returns zero, one or multiple of its input servers. Thus, it must be followed by other filters to reduce the number of candidates down to one for statement execution.

The quality_of_service filter has been introduced in 1.2.0-alpha. In the 1.2 series the filters focus is on the consistency aspect of service quality. Different types of clusters offer different default data consistencies. For example, an asynchronous MySQL replication slave offers eventual consistency. The slave may not be able to deliver requested data because it has not replicated the write, it may serve stale database because its lagging behind or it may serve current information. Often, this is acceptable. In some cases higher consistency levels are needed for the application to work correct. In those cases, the quality_of_service can filter out cluster nodes which cannot deliver the necessary quality of service.

The quality_of_service filter can be replaced or created at runtime. A successful call to mysqlnd_ms_set_qos() removes all existing qos filter entries from the filter list and installs a new one at the very beginning. All settings that can be made through mysqlnd_ms_set_qos() can also be in the plugins configuration file. However, use of the function is by far the most common use case. Instead of setting session consistency and strong consistency service levels in the plugins configuration file it is recommended to define only masters and no slaves. Both service levels will force the use of masters only. Using an empty slave list shortens the configuration file, thus improving readability. The only service level for which there is a case of defining in the plugins configuration file is the combination of eventual consistency and maximum slave lag.

Keyword Description Version
eventual_consistency

Request eventual consistency. Allows the use of all master and slave servers. Data returned may or may not be current.

Eventual consistency accepts an optional age parameter. If age is given the plugin considers only slaves for reading for which MySQL replication reports a slave lag less or equal to age. The replication lag is measure using SHOW SLAVE STATUS. If the plugin fails to fetch the replication lag, the slave tested is skipped. Implementation details and tips are given in the quality of service concepts section.

Please note, if a filter chain generates an empty slave list and the PHP configuration directive mysqlnd_ms.multi_master=0 is used, the plugin may emit a warning.

Example #24 Global limit on slave lag

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.2.27",
                "port": "3306"
            },
            "slave_1": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "filters": {
            "quality_of_service": {
                "eventual_consistency": {
                    "age":123
                }
            }
        }
    }
}

 Since 1.2.0.
session_consistency

Request session consistency (read your writes). Allows use of all masters and all slaves which are in sync with the master. If no further parameters are given slaves are filtered out as there is no reliable way to test if a slave has caught up to the master or is lagging behind. Please note, if a filter chain generates an empty slave list and the PHP configuration directive mysqlnd_ms.multi_master=0 is used, the plugin may emit a warning.

Session consistency temporarily requested using mysqlnd_ms_set_qos() is a valuable alternative to using master_on_write. master_on_write is likely to send more statements to the master than needed. The application may be able to continue operation at a lower consistency level after it has done some critical reads.

Since 1.1.0.
strong_consistency

Request strong consistency. Only masters will be used.

Since 1.2.0.
failover Up to and including 1.3.x: string. Since 1.4.0: object.

Failover policy. Supported policies: disabled (default), master, loop_before_master (Since 1.4.0).

If no failover policy is set, the plugin will not do any automatic failover (failover=disabled). Whenever the plugin fails to connect a server it will emit a warning and set the connections error code and message. Thereafter it is up to the application to handle the error and, for example, resent the last statement to trigger the selection of another server.

Please note, the automatic failover logic is applied when opening connections only. Once a connection has been opened no automatic attempts are made to reopen it in case of an error. If, for example, the server a connection is connected to is shut down and the user attempts to run a statement on the connection, no automatic failover will be tried. Instead, an error will be reported.

If using failover=master the plugin will implicitly failover to a master, if available. Please check the concepts documentation to learn about potential pitfalls and risks of using failover=master.

Example #25 Optional master failover when failing to connect to slave (PECL/mysqlnd_ms < 1.4.0)

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "failover": "master"
    }
}

Since PECL/mysqlnd_ms 1.4.0 the failover configuration keyword refers to an object.

Example #26 New syntax since 1.4.0

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "failover": {"strategy": "master" }
    }
}

Keyword Description Version
strategy

Failover policy. Possible values: disabled (default), master, loop_before_master

A value of disabled disables automatic failover.

Setting master instructs the plugin to try to connect to a master in case of a slave connection error. If the master connection attempt fails, the plugin exists the failover loop and returns an error to the user.

If using loop_before_master and a slave request is made, the plugin tries to connect to other slaves before failing over to a master. If multiple master are given and multi master is enabled, the plugin also loops over the list of masters and attempts to connect before returning an error to the user.

Since 1.4.0.
remember_failed

Remember failures for the duration of a web request. Default: false.

If set to true the plugin will remember failed hosts and skip the hosts in all future load balancing made for the duration of the current web request.

Since 1.4.0. The feature is only available together with the random and roundrobin load balancing filter. Use of the setting is recommended.
max_retries

Maximum number of connection attempts before skipping host. Default: 0 (no limit).

The setting is used to prevent hosts from being dropped of the host list upon the first failure. If set to n > 0, the plugin will keep the node in the node list even after a failed connection attempt. The node will not be removed immediately from the slave respectively master lists after the first connection failure but instead be tried to connect to up to n times in future load balancing rounds before being removed.

Since 1.4.0. The feature is only available together with the random and roundrobin load balancing filter.

Setting failover to any other value but disabled, master or loop_before_master will not emit any warning or error.

lazy_connections bool

Controls the use of lazy connections. Lazy connections are connections which are not opened before the client sends the first connection. Lazy connections are a default.

It is strongly recommended to use lazy connections. Lazy connections help to keep the number of open connections low. If you disable lazy connections and, for example, configure one MySQL replication master server and two MySQL replication slaves, the plugin will open three connections upon the first call to a connect function although the application might use the master connection only.

Lazy connections bare a risk if you make heavy use of actions which change the state of a connection. The plugin does not dispatch all state changing actions to all connections from the connection pool. The few dispatched actions are applied to already opened connections only. Lazy connections opened in the future are not affected. Only some settings are "remembered" and applied when lazy connections are opened.

Example #27 Disabling lazy connection

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "lazy_connections": 0
    }
}

Please, see also server_charset to overcome potential problems with string escaping and servers using different default charsets.

server_charset string

The setting has been introduced in 1.4.0. It is recommended to set it if using lazy connections.

The server_charset setting serves two purposes. It acts as a fallback charset to be used for string escaping done before a connection has been established and it helps to avoid escaping pitfalls in heterogeneous environments which servers using different default charsets.

String escaping takes a connections charset into account. String escaping is not possible before a connection has been opened and the connections charset is known. The use of lazy connections delays the actual opening of connections until a statement is send.

An application using lazy connections may attempt to escape a string before sending a statement. In fact, this should be a common case as the statement string may contain the string that is to be escaped. However, due to the lazy connection feature no connection has been opened yet and escaping fails. The plugin may report an error of the type E_WARNING and a message like (mysqlnd_ms) string escaping doesn't work without established connection. Possible solution is to add server_charset to your configuration to inform you of the pitfall.

Setting server_charset makes the plugin use the given charset for string escaping done on lazy connection handles before establishing a network connection to MySQL. Furthermore, the plugin will enforce the use of the charset when the connection is established.

Enforcing the use of the configured charset used for escaping is done to prevent tapping into the pitfall of using a different charset for escaping than used later for the connection. This has the additional benefit of removing the need to align the charset configuration of all servers used. No matter what the default charset on any of the servers is, the plugin will set the configured one as a default.

The plugin does not stop the user from changing the charset at any time using the set_charset() call or corresponding SQL statements. Please, note that the use of SQL is not recommended as it cannot be monitored by the plugin. The user can, for example, change the charset on a lazy connection handle after escaping a string and before the actual connection is opened. The charset set by the user will be used for any subsequent escaping before the connection is established. The connection will be established using the configured charset, no matter what the server charset is or what the user has set before. Once a connection has been opened, set_charset is of no meaning anymore.

Example #28 String escaping on a lazy connection handle

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "lazy_connections": 1,
        "server_charset" : "utf8"
    }
}
<?php
$mysqli = new mysqli("myapp", "username", "password", "database");
$mysqli->real_escape("this will be escaped using the server_charset setting - utf8");
$mysqli->set_charset("latin1");
$mysqli->real_escape("this will be escaped using latin1");
/* server_charset implicitly set - utf8 connection */
$mysqli->query("SELECT 'This connection will be set to server_charset upon establishing' AS _msg FROM DUAL");
/* latin1 used from now on */
$mysqli->set_charset("latin1");
?>

master_on_write bool

If set, the plugin will use the master server only after the first statement has been executed on the master. Applications can still send statements to the slaves using SQL hints to overrule the automatic decision.

The setting may help with replication lag. If an application runs an INSERT the plugin will, by default, use the master to execute all following statements, including SELECT statements. This helps to avoid problems with reads from slaves which have not replicated the INSERT yet.

Example #29 Master on write for consistent reads

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "master_on_write": 1
    }
}

Please, note the quality_of_service filter introduced in version 1.2.0-alpha. It gives finer control, for example, for achieving read-your-writes and, it offers additional functionality introducing service levels.

All transaction stickiness settings, including trx_stickiness=on, are overruled by master_on_write=1.

trx_stickiness string

Transaction stickiness policy. Supported policies: disabled (default), master.

The setting requires 5.4.0 or newer. If used with PHP older than 5.4.0, the plugin will emit a warning like (mysqlnd_ms) trx_stickiness strategy is not supported before PHP 5.3.99.

If no transaction stickiness policy is set or, if setting trx_stickiness=disabled, the plugin is not transaction aware. Thus, the plugin may load balance connections and switch connections in the middle of a transaction. The plugin is not transaction safe. SQL hints must be used avoid connection switches during a transaction.

As of PHP 5.4.0 the mysqlnd library allows the plugin to monitor the autocommit mode set by calls to the libraries set_autocommit() function. If setting set_stickiness=master and autocommit gets disabled by a PHP MySQL extension invoking the mysqlnd library internal function call set_autocommit(), the plugin is made aware of the begin of a transaction. Then, the plugin stops load balancing and directs all statements to the master server until autocommit is enabled. Thus, no SQL hints are required.

An example of a PHP MySQL API function calling the mysqlnd library internal function call set_autocommit() is mysqli_autocommit().

Although setting trx_stickiness=master, the plugin cannot be made aware of autocommit mode changes caused by SQL statements such as SET AUTOCOMMIT=0 or BEGIN.

As of PHP 5.5.0, the mysqlnd library features additional C API calls to control transactions. The level of control matches the one offered by SQL statements. The mysqli API has been modified to use these calls. Since version 1.5.0, PECL/mysqlnd_ms can monitor not only mysqli_autocommit(), but also mysqli_begin(), mysqli_commit() and mysqli_rollback() to detect transaction boundaries and stop load balancing for the duration of a transaction.

Example #30 Using master to execute transactions

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
        },
        "trx_stickiness": "master"
    }
}

Since version 1.5.0 automatic and silent failover is disabled for the duration of a transaction. If the boundaries of a transaction have been properly detected, transaction stickiness is enabled and a server fails, the plugin will not attempt to fail over to the next server, if any, regardless of the failover policy configured. The user must handle the error manually. Depending on the configuration, the plugin may emit an error of type E_WARNING reading like (mysqlnd_ms) Automatic failover is not permitted in the middle of a transaction. This error may then be overwritten by follow up errors such as (mysqlnd_ms) No connection selected by the last filter. Those errors will be generated by the failing query function.

Example #31 No automatic failover, error handling pitfall

<?php
/* assumption: automatic failover configured */
$mysqli = new mysqli("myapp", "username", "password", "database");

/* sets plugin internal state in_trx = 1 */
$mysqli->autocommit(false);

/* assumption: server fails */
if (!($res = $mysqli->query("SELECT 'Assume this query fails' AS _msg FROM DUAL"))) {
 /* handle failure of transaction, plugin internal state is still in_trx = 1 */
 printf("[%d] %s", $mysqli->errno, $mysqli->error);
 /*
  If using autocommit() based transaction detection it is a
  MUST to call autocommit(true). Otherwise the plugin assumes
  the current transaction continues and connection
  changes remain forbidden.
 */
 $mysqli->autocommit(true);
 /* Likewise, you'll want to start a new transaction */
 $mysqli->autocommit(false);
}
/* latin1 used from now on */
$mysqli->set_charset("latin1");
?>

If a server fails in the middle of a transaction the plugin continues to refuse to switch connections until the current transaction has been finished. Recall that the plugin monitors API calls to detect transaction boundaries. Thus, you have to, for example, enable auto commit mode to end the current transaction before the plugin continues load balancing and switches the server. Likewise, you will want to start a new transaction immediately thereafter and disable auto commit mode again.

Not handling failed queries and not ending a failed transaction using API calls may cause all following commands emit errors such as Commands out of sync; you can't run this command now. Thus, it is important to handle all errors.

transient_error object

The setting has been introduced in 1.6.0.

A database cluster node may reply a transient error to a client. The client can then repeat the operation on the same node, fail over to a different node or abort the operation. Per definition is it safe for a client to retry the same operation on the same node before giving up.

PECL/mysqlnd_ms can perform the retry loop on behalf of the application. By configuring transient_error the plugin can be instructed to repeat operations failing with a certain error code for a certain maximum number of times with a pause between the retries. If the transient error disappears during loop execution, it is hidden from the application. Otherwise, the error is forwarded to the application by the end of the loop.

Example #32 Retry loop for transient errors

{
    "myapp": {
        "master": {
            "master_0": {
                "host": "localhost"
            }
        },
        "slave": {
            "slave_0": {
                "host": "192.168.78.136",
                "port": "3306"
            }
       },
       "transient_error": {
          "mysql_error_codes": [
            1297
          ],
          "max_retries": 2,
          "usleep_retry": 100
       }
    }
}

Keyword Description Version
mysql_error_codes

List of transient error codes. You may add any MySQL error code to the list. It is possible to consider any error as transient not only 1297 (HY000 (ER_GET_TEMPORARY_ERRMSG), Message: Got temporary error %d '%s' from %s). Before adding other codes but 1297 to the list, make sure your cluster supports a new attempt without impacting the state of your application.

Since 1.6.0.
max_retries

How often to retry an operation which fails with a transient error before forwarding the failure to the user.

Default: 1

Since 1.6.0.
usleep_retry

Milliseconds to sleep between transient error retries. The value is passed to the C function usleep(), hence the name.

Default: 100

Since 1.6.0.
xa object

The setting has been introduced in 1.6.0.

Note: Experimental

The feature is currently under development. There may be issues and/or feature limitations. Do not use in production environments.

state_store
record_participant_credentials

Whether to store the username and password of a global transaction participant in the participants table. If disabled, the garbage collection will use the default username and password when connecting to the participants. Unless you are using a different username and password for each of your MySQL servers, you can use the default and avoid storing the sensible information in state store.

Please note, username and password are stored in clear text when using the MySQL state store, which is the only one available. It is in your responsibility to protect this sensible information.

Default: false

participant_localhost_ip

During XA garbage collection the plugin may find a participant server for which the host localhost has been recorded. If the garbage collection takes place on another host but the host that has written the participant record to the state store, the host name localhost now resolves to a different host. Therefore, when recording a participant servers host name in the state store, a value of localhost must be replaced with the actual IP address of localhost.

Setting participant_localhost_ip should be considered only if using localhost cannot be avoided. From a garbage collection point of view only, it is preferrable not to configure any socket connection but to provide an IP address and port for a node.

mysql

The MySQL state store is the only state store available.

global_trx_table

Name of the MySQL table used to store the state of an ongoing or aborted global transaction. Use the below SQL statement to create the table. Make sure to edit the table name to match your configuration.

Default: mysqlnd_ms_xa_trx

Example #33 SQL definition for the MySQL state store transaction table

CREATE TABLE mysqlnd_ms_xa_trx (
  store_trx_id int(11) NOT NULL AUTO_INCREMENT,
  gtrid int(11) NOT NULL,
  format_id int(10) unsigned NOT NULL DEFAULT '1',
  state enum('XA_NON_EXISTING','XA_ACTIVE','XA_IDLE','XA_PREPARED','XA_COMMIT','XA_ROLLBACK') NOT NULL DEFAULT 'XA_NON_EXISTING',
  intend enum('XA_NON_EXISTING','XA_ACTIVE','XA_IDLE','XA_PREPARED','XA_COMMIT','XA_ROLLBACK') DEFAULT 'XA_NON_EXISTING',
  finished enum('NO','SUCCESS','FAILURE') NOT NULL DEFAULT 'NO',
  modified timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  started datetime DEFAULT NULL,
  timeout datetime DEFAULT NULL,
  PRIMARY KEY (store_trx_id),
  KEY idx_xa_id (gtrid,format_id,finished),
  KEY idx_state (state)
) ENGINE=InnoDB

participant_table

Name of the MySQL table used to store participants of an ongoing or aborted global transaction. Use the below SQL statement to create the table. Make sure to edit the table name to match your configuration.

Storing credentials can be enabled and disabled using record_participant_credentials

Default: mysqlnd_ms_xa_participants

Example #34 SQL definition for the MySQL state store transaction table

CREATE TABLE mysqlnd_ms_xa_participants (
  fk_store_trx_id int(11) NOT NULL,
  bqual varbinary(64) NOT NULL DEFAULT '',
  participant_id int(10) unsigned NOT NULL AUTO_INCREMENT,
  server_uuid varchar(127) DEFAULT NULL,
  scheme varchar(1024) NOT NULL,
  host varchar(127) DEFAULT NULL,
  port smallint(5) unsigned DEFAULT NULL,
  socket varchar(127) DEFAULT NULL,
  user varchar(127) DEFAULT NULL,
  password varchar(127) DEFAULT NULL,
  state enum('XA_NON_EXISTING','XA_ACTIVE','XA_IDLE','XA_PREPARED','XA_COMMIT','XA_ROLLBACK')
   NOT NULL DEFAULT 'XA_NON_EXISTING',
  health enum('OK','GC_DONE','CLIENT ERROR','SERVER ERROR') NOT NULL DEFAULT 'OK',
  connection_id int(10) unsigned DEFAULT NULL,
  client_errno smallint(5) unsigned DEFAULT NULL,
  client_error varchar(1024) DEFAULT NULL,
  modified timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (participant_id),
  KEY idx_xa_bqual (bqual),
  KEY idx_store_trx (fk_store_trx_id),
  CONSTRAINT mysqlnd_ms_xa_participants_ibfk_1 FOREIGN KEY (fk_store_trx_id)
    REFERENCES mysqlnd_ms_xa_trx (store_trx_id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB
garbage_collection_table

Name of the MySQL table used to track and synchronize garbage collection runs. Use the below SQL statement to create the table. Make sure to edit the table name to match your configuration.

Default: mysqlnd_ms_xa_gc

Example #35 SQL definition for the MySQL state store garbage collection table

CREATE TABLE mysqlnd_ms_xa_gc (
  gc_id int(10) unsigned NOT NULL AUTO_INCREMENT,
  gtrid int(11) NOT NULL,
  format_id int(10) unsigned NOT NULL DEFAULT '1',
  fk_store_trx_id int(11) DEFAULT NULL,
  modified timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  attempts smallint(5) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (gc_id),
  KEY idx_store_trx (gtrid,format_id,fk_store_trx_id)
) ENGINE=InnoDB
host

Host name of the MySQL server.

user

Name of the user used to connect to the MySQL server.

password

Password for the MySQL server user.

db

Database that holds the garbage collection tables. Please note, you have to create the garbage collection tables prior to using the plugin. The tables will not be created implicitly during runtime but garbage collection will fail if the tables to not exist.

port

Port of the MySQL server.

socket

Unix domain socket of the MySQL server. Please note, if you have multiple PHP servers each of them will try to carry out garbage collection and need to be able to connect to the state store. In this case, you may prefer configuring an IP address and a port for the MySQL state store server to ensure all PHP servers can reach it.

rollback_on_close

Whether to automatically rollback an open global transaction when a connection is closed. If enabled, it mimics the default behaviour of local transactions. Should a client disconnect, the server rolls back any open and unfinished transactions.

Default: true

garbage_collection
max_retries

Maximum number of garbage collection runs before giving up. Allowed values are from 0 to 100. A setting of 0 means no limit, unless the state store enforces a limit. Should the state store enforce a limit, it can be supposed to be significantly higher than 100. Available since 1.6.0.

Please note, it is important to end failed XA transactions within reasonable time to make participating servers free resources bound to the transaction. The built-in garbage collection is not expected to fail for a long period as long as crashed servers become available again quickly. Still, a situation may arise where a human is required to act because the built-in garbage collection stopped or failed. In this case, you may first want to check if the transaction still cannot be fixed by forcing mysqlnd_ms_xa_gc() to ignore the setting, prior to handling it manually.

Default: 5

probability

Garbage collection probability. Allowed values are from 0 to 1000. A setting of 0 disables automatic background garbage collection. Despite a setting of 0 it is still possible to trigger garbage collection by calling mysqlnd_ms_gc(). Available since 1.6.0.

The automatic garbage collection of stalled XA transaction is only available if a state store have been configured. The state store is responsible to keep track of XA transactions. Based on its recordings it can find blocked XA transactions where the client has crashed, connect to the participants and rollback the unfinished transactions.

The garbage collection is triggered as part of PHP's request shutdown procedure at the end of a web request. That is after your PHP script has finished working. Do decide whether to run the garbage collection a random value between 0 and 1000 is computed. If the probability value is higher or equal to the random value, the state stores garbage collection routines are invoked.

Default: 5

max_transactions_per_run

Maximum number of unfinished XA transactions considered by the garbage collection during one run. Allowed values are from 1 to 32768. Available since 1.6.0.

Cleaning up an unfinished XA transaction takes considerable amounts of time and resources. The garbage collection routine may have to connect to several participants of a failed global transaction to issue the SQL commands for rolling back the unfinished tranaction.

Default: 100

Plugin configuration file (<= 1.0.x)

Note:

The below description applies to PECL/mysqlnd_ms < 1.1.0-beta. It is not valid for later versions.

The plugin is using its own configuration file. The configuration file holds information on the MySQL replication master server, the MySQL replication slave servers, the server pick (load balancing) policy, the failover strategy and the use of lazy connections.

The PHP configuration directive mysqlnd_ms.ini_file is used to set the plugins configuration file.

The configuration file mimics standard the php.ini format. It consists of one or more sections. Every section defines its own unit of settings. There is no global section for setting defaults.

Applications reference sections by their name. Applications use section names as the host (server) parameter to the various connect methods of the mysqli, mysql and PDO_MYSQL extensions. Upon connect the mysqlnd plugin compares the hostname with all section names from the plugin configuration file. If hostname and section name match, the plugin will load the sections settings.

Example #36 Using section names example

[myapp]
master[] = localhost
slave[] = 192.168.2.27
slave[] = 192.168.2.28:3306
[localhost]
master[] = localhost:/tmp/mysql/mysql.sock
slave[] = 192.168.3.24:3305
slave[] = 192.168.3.65:3309
<?php
/* All of the following connections will be load balanced */
$mysqli = new mysqli("myapp", "username", "password", "database");
$pdo = new PDO('mysql:host=myapp;dbname=database', 'username', 'password');
$mysql = mysql_connect("myapp", "username", "password");

$mysqli = new mysqli("localhost", "username", "password", "database");
?>

Section names are strings. It is valid to use a section name such as 192.168.2.1, 127.0.0.1 or localhost. If, for example, an application connects to localhost and a plugin configuration section [localhost] exists, the semantics of the connect operation are changed. The application will no longer only use the MySQL server running on the host localhost but the plugin will start to load balance MySQL queries following the rules from the [localhost] configuration section. This way you can load balance queries from an application without changing the applications source code.

The master[], slave[] and pick[] configuration directives use a list-like syntax. Configuration directives supporting list-like syntax may appear multiple times in a configuration section. The plugin maintains the order in which entries appear when interpreting them. For example, the below example shows two slave[] configuration directives in the configuration section [myapp]. If doing round-robin load balancing for read-only queries, the plugin will send the first read-only query to the MySQL server mysql_slave_1 because it is the first in the list. The second read-only query will be send to the MySQL server mysql_slave_2 because it is the second in the list. Configuration directives supporting list-like syntax result are ordered from top to bottom in accordance to their appearance within a configuration section.

Example #37 List-like syntax

[myapp]
master[] = mysql_master_server
slave[] = mysql_slave_1
slave[] = mysql_slave_2

Here is a short explanation of the configuration directives that can be used.

master[] string

URI of a MySQL replication master server. The URI follows the syntax hostname[:port|unix_domain_socket].

The plugin supports using only one master server.

Setting a master server is mandatory. The plugin will report a warning upon connect if the user has failed to provide a master server for a configuration section. The warning may read (mysqlnd_ms) Cannot find master section in config. Furthermore the plugin may set an error code for the connection handle such as HY000/2000 (CR_UNKNOWN_ERROR). The corresponding error message depends on your language settings.

slave[] string

URI of one or more MySQL replication slave servers. The URI follows the syntax hostname[:port|unix_domain_socket].

The plugin supports using one or more slave servers.

Setting a slave server is mandatory. The plugin will report a warning upon connect if the user has failed to provide at least one slave server for a configuration section. The warning may read (mysqlnd_ms) Cannot find slaves section in config. Furthermore the plugin may set an error code for the connection handle such as HY000/2000 (CR_UNKNOWN_ERROR). The corresponding error message depends on your language settings.

pick[] string

Load balancing (server picking) policy. Supported policies: random, random_once (default), roundrobin, user.

If no load balancing policy is set, the plugin will default to random_once. The random_once policy picks a random slave server when running the first read-only statement. The slave server will be used for all read-only statements until the PHP script execution ends.

The random policy will pick a random server whenever a read-only statement is to be executed.

If using roundrobin the plugin iterates over the list of configured slave servers to pick a server for statement execution. If the plugin reaches the end of the list, it wraps around to the beginning of the list and picks the first configured slave server.

Setting more than one load balancing policy for a configuration section makes only sense in conjunction with user and mysqlnd_ms_set_user_pick_server(). If the user defined callback fails to pick a server, the plugin falls back to the second configured load balancing policy.

failover string

Failover policy. Supported policies: disabled (default), master.

If no failover policy is set, the plugin will not do any automatic failover (failover=disabled). Whenever the plugin fails to connect a server it will emit a warning and set the connections error code and message. Thereafter it is up to the application to handle the error and, for example, resent the last statement to trigger the selection of another server.

If using failover=master the plugin will implicitly failover to a slave, if available. Please check the concepts documentation to learn about potential pitfalls and risks of using failover=master.

lazy_connections bool

Controls the use of lazy connections. Lazy connections are connections which are not opened before the client sends the first connection.

It is strongly recommended to use lazy connections. Lazy connections help to keep the number of open connections low. If you disable lazy connections and, for example, configure one MySQL replication master server and two MySQL replication slaves, the plugin will open three connections upon the first call to a connect function although the application might use the master connection only.

Lazy connections bare a risk if you make heavy use of actions which change the state of a connection. The plugin does not dispatch all state changing actions to all connections from the connection pool. The few dispatched actions are applied to already opened connections only. Lazy connections opened in the future are not affected. If, for example, the connection character set is changed using a PHP MySQL API call, the plugin will change the character set of all currently opened connection. It will not remember the character set change to apply it on lazy connections opened in the future. As a result the internal connection pool would hold connections using different character sets. This is not desired. Remember that character sets are taken into account for escaping.

master_on_write bool

If set, the plugin will use the master server only after the first statement has been executed on the master. Applications can still send statements to the slaves using SQL hints to overrule the automatic decision.

The setting may help with replication lag. If an application runs an INSERT the plugin will, by default, use the master to execute all following statements, including SELECT statements. This helps to avoid problems with reads from slaves which have not replicated the INSERT yet.

trx_stickiness string

Transaction stickiness policy. Supported policies: disabled (default), master.

Experimental feature.

The setting requires 5.4.0 or newer. If used with PHP older than 5.4.0, the plugin will emit a warning like (mysqlnd_ms) trx_stickiness strategy is not supported before PHP 5.3.99.

If no transaction stickiness policy is set or, if setting trx_stickiness=disabled, the plugin is not transaction aware. Thus, the plugin may load balance connections and switch connections in the middle of a transaction. The plugin is not transaction safe. SQL hints must be used avoid connection switches during a transaction.

As of PHP 5.4.0 the mysqlnd library allows the plugin to monitor the autocommit mode set by calls to the libraries trx_autocommit() function. If setting trx_stickiness=master and autocommit gets disabled by a PHP MySQL extension invoking the mysqlnd library internal function call trx_autocommit(), the plugin is made aware of the begin of a transaction. Then, the plugin stops load balancing and directs all statements to the master server until autocommit is enabled. Thus, no SQL hints are required.

An example of a PHP MySQL API function calling the mysqlnd library internal function call trx_autocommit() is mysqli_autocommit().

Although setting trx_stickiness=master, the plugin cannot be made aware of autocommit mode changes caused by SQL statements such as SET AUTOCOMMIT=0.

Testing

Note:

The section applies to mysqlnd_ms 1.1.0 or newer, not the 1.0 series.

The PECL/mysqlnd_ms test suite is in the tests/ directory of the source distribution. The test suite consists of standard phpt tests, which are described on the PHP Quality Assurance Teams website.

Running the tests requires setting up one to four MySQL servers. Some tests don't connect to MySQL at all. Others require one server for testing. Some require two distinct servers. In some cases two servers are used to emulate a replication setup. In other cases a master and a slave of an existing MySQL replication setup are required for testing. The tests will try to detect how many servers and what kind of servers are given. If the required servers are not found, the test will be skipped automatically.

Before running the tests, edit tests/config.inc to configure the MySQL servers to be used for testing.

The most basic configuration is as follows.

 putenv("MYSQL_TEST_HOST=localhost");
 putenv("MYSQL_TEST_PORT=3306");
 putenv("MYSQL_TEST_USER=root");
 putenv("MYSQL_TEST_PASSWD=");
 putenv("MYSQL_TEST_DB=test");
 putenv("MYSQL_TEST_ENGINE=MyISAM");
 putenv("MYSQL_TEST_SOCKET=");

 putenv("MYSQL_TEST_SKIP_CONNECT_FAILURE=1");
 putenv("MYSQL_TEST_CONNECT_FLAGS=0");
 putenv("MYSQL_TEST_EXPERIMENTAL=0");

 /* replication cluster emulation */
 putenv("MYSQL_TEST_EMULATED_MASTER_HOST=". getenv("MYSQL_TEST_HOST"));
 putenv("MYSQL_TEST_EMULATED_SLAVE_HOST=". getenv("MYSQL_TEST_HOST"));

 /* real replication cluster */
 putenv("MYSQL_TEST_MASTER_HOST=". getenv("MYSQL_TEST_EMULATED_MASTER_HOST"));
 putenv("MYSQL_TEST_SLAVE_HOST=". getenv("MYSQL_TEST_EMULATED_SLAVE_HOST"));

MYSQL_TEST_HOST, MYSQL_TEST_PORT and MYSQL_TEST_SOCKET define the hostname, TCP/IP port and Unix domain socket of the default database server. MYSQL_TEST_USER and MYSQL_TEST_PASSWD contain the user and password needed to connect to the database/schema configured with MYSQL_TEST_DB. All configured servers must have the same database user configured to give access to the test database.

Using host, host:port or host:/path/to/socket syntax one can set an alternate host, host and port or host and socket for any of the servers.

putenv("MYSQL_TEST_SLAVE_HOST=192.168.78.136:3307"));
putenv("MYSQL_TEST_MASTER_HOST=myserver_hostname:/path/to/socket"));

Debugging and Tracing

The mysqlnd debug log can be used to debug and trace the actitivities of PECL/mysqlnd_ms. As a mysqlnd PECL/mysqlnd_ms adds trace information to the mysqlnd library debug file. Please, see the mysqlnd.debug PHP configuration directive documentation for a detailed description on how to configure the debug log.

Configuration setting example to activate the debug log:

mysqlnd.debug=d:t:x:O,/tmp/mysqlnd.trace

Note:

This feature is only available with a debug build of PHP. Works on Microsoft Windows if using a debug build of PHP and PHP was built using Microsoft Visual C version 9 and above.

The debug log shows mysqlnd library and PECL/mysqlnd_ms plugin function calls, similar to a trace log. Mysqlnd library calls are usually prefixed with mysqlnd_. PECL/mysqlnd internal calls begin with mysqlnd_ms.

Example excerpt from the debug log (connect):

[...]
>mysqlnd_connect
| info : host=myapp user=root db=test port=3306 flags=131072
| >mysqlnd_ms::connect
| | >mysqlnd_ms_config_json_section_exists
| | | info : section=[myapp] len=[5]
| | | >mysqlnd_ms_config_json_sub_section_exists
| | | | info : section=[myapp] len=[5]
| | | | info : ret=1
| | | <mysqlnd_ms_config_json_sub_section_exists
| | | info : ret=1
| | <mysqlnd_ms_config_json_section_exists
[...]

The debug log is not only useful for plugin developers but also to find the cause of user errors. For example, if your application does not do proper error handling and fails to record error messages, checking the debug and trace log may help finding the cause. Use of the debug log to debug application issues should be considered only if no other option is available. Writing the debug log to disk is a slow operation and may have negative impact on the application performance.

Example excerpt from the debug log (connection failure):

[...]
| | | | | | | info : adding error [Access denied for user 'root'@'localhost' (using password: YES)] to the list
| | | | | | | info : PACKET_FREE(0)
| | | | | | | info : PACKET_FREE(0x7f3ef6323f50)
| | | | | | | info : PACKET_FREE(0x7f3ef6324080)
| | | | | | <mysqlnd_auth_handshake
| | | | | | info : switch_to_auth_protocol=n/a
| | | | | | info : conn->error_info.error_no = 1045
| | | | | <mysqlnd_connect_run_authentication
| | | | | info : PACKET_FREE(0x7f3ef63236d8)
| | | | | >mysqlnd_conn::free_contents
| | | | | | >mysqlnd_net::free_contents
| | | | | | <mysqlnd_net::free_contents
| | | | | | info : Freeing memory of members
| | | | | | info : scheme=unix:///tmp/mysql.sock
| | | | | | >mysqlnd_error_list_pdtor
| | | | | | <mysqlnd_error_list_pdtor
| | | | | <mysqlnd_conn::free_contents
| | | | <mysqlnd_conn::connect
[...]

The trace log can also be used to verify correct behaviour of PECL/mysqlnd_ms itself, for example, to check which server has been selected for query execution and why.

Example excerpt from the debug log (plugin decision):

[...]
>mysqlnd_ms::query
| info : query=DROP TABLE IF EXISTS test
| >_mysqlnd_plugin_get_plugin_connection_data
| | info : plugin_id=5
| <_mysqlnd_plugin_get_plugin_connection_data
| >mysqlnd_ms_pick_server_ex
| | info : conn_data=0x7fb6a7d3e5a0 *conn_data=0x7fb6a7d410d0
| | >mysqlnd_ms_select_servers_all
| | <mysqlnd_ms_select_servers_all
| | >mysqlnd_ms_choose_connection_rr
| | | >mysqlnd_ms_query_is_select
[...]
| | | <mysqlnd_ms_query_is_select
[...]
| | | info : Init the master context
| | | info : list(0x7fb6a7d3f598) has 1
| | | info : Using master connection
| | | >mysqlnd_ms_advanced_connect
| | | | >mysqlnd_conn::connect
| | | | | info : host=localhost user=root db=test port=3306 flags=131072 persistent=0 state=0

In this case the statement DROP TABLE IF EXISTS test has been executed. Note that the statement string is shown in the log file. You may want to take measures to restrict access to the log for security considerations.

The statement has been load balanced using round robin policy, as you can easily guess from the functions name >mysqlnd_ms_choose_connection_rr. It has been sent to a master server running on host=localhost user=root db=test port=3306 flags=131072 persistent=0 state=0.

Monitoring

Plugin activity can be monitored using the mysqlnd trace log, mysqlnd statistics, mysqlnd_ms plugin statistics and external PHP debugging tools. Use of the trace log should be limited to debugging. It is recommended to use the plugins statistics for monitoring.

Writing a trace log is a slow operation. If using an external PHP debugging tool, please refer to the vendors manual about its performance impact and the type of information collected. In many cases, external debugging tools will provide call stacks. Often, a call stack or a trace log is more difficult to interpret than the statistics provided by the plugin.

Plugin statistics tell how often which kind of cluster node has been used (slave or master), why the node was used, if lazy connections have been used and if global transaction ID injection has been performed. The monitoring information provided enables user to verify plugin decisions and to plan their cluster resources based on usage pattern. The function mysqlnd_ms_get_stats() is used to access the statistics. Please, see the functions description for a list of available statistics.

Statistics are collected on a per PHP process basis. Their scope is a PHP process. Depending on the PHP deployment model a process may serve one or multiple web requests. If using CGI model, a PHP process serves one web request. If using FastCGI or pre-fork web server models, a PHP process usually serves multiple web requests. The same is the case with a threaded web server. Please, note that threads running in parallel can update the statistics in parallel. Thus, if using a threaded PHP deployment model, statistics can be changed by more than one script at a time. A script cannot rely on the fact that it sees only its own changes to statistics.

Example #38 Verify plugin activity in a non-threaded deployment model

mysqlnd_ms.enable=1
mysqlnd_ms.collect_statistics=1
<?php
/* Load balanced following "myapp" section rules from the plugins config file (not shown) */
$mysqli = new mysqli("myapp", "username", "password", "database");
if (mysqli_connect_errno())
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

$stats_before = mysqlnd_ms_get_stats();
if ($res = $mysqli->query("SELECT 'Read request' FROM DUAL")) {
  var_dump($res->fetch_all());
}
$stats_after = mysqlnd_ms_get_stats();
if ($stats_after['use_slave'] <= $stats_before['use_slave']) {
  echo "According to the statistics the read request has not been run on a slave!";
}
?>

Statistics are aggregated for all plugin activities and all connections handled by the plugin. It is not possible to tell how much a certain connection handle has contributed to the overall statistics.

Utilizing PHPs register_shutdown_function() function or the auto_append_file PHP configuration directive it is easily possible to dump statistics into, for example, a log file when a script finishes. Instead of using a log file it is also possible to send the statistics to an external monitoring tool for recording and display.

Example #39 Recording statistics during shutdown

mysqlnd_ms.enable=1
mysqlnd_ms.collect_statistics=1
error_log=/tmp/php_errors.log
<?php
function check_stats() {
  $msg = str_repeat("-", 80) . "\n";
  $msg .= var_export(mysqlnd_ms_get_stats(), true) . "\n";
  $msg .= str_repeat("-", 80) . "\n";
  error_log($msg);
}
register_shutdown_function("check_stats");
?>


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.

SQL hint related

Example #1 Example demonstrating the usage of mysqlnd_ms constants

The mysqlnd replication and load balancing plugin (mysqlnd_ms) performs read/write splitting. This directs write queries to a MySQL master server, and read-only queries to the MySQL slave servers. The plugin has a built-in read/write split logic. All queries which start with SELECT are considered read-only queries, which are then sent to a MySQL slave server that is listed in the plugin configuration file. All other queries are directed to the MySQL master server that is also specified in the plugin configuration file.

User supplied SQL hints can be used to overrule automatic read/write splitting, to gain full control on the process. SQL hints are standards compliant SQL comments. The plugin will scan the beginning of a query string for an SQL comment for certain commands, which then control query redirection. Other systems involved in the query processing are unaffected by the SQL hints because other systems will ignore the SQL comments.

The plugin supports three SQL hints to direct queries to either the MySQL slave servers, the MySQL master server, or the last used MySQL server. SQL hints must be placed at the beginning of a query to be recognized by the plugin.

For better portability, it is recommended to use the string constants MYSQLND_MS_MASTER_SWITCH, MYSQLND_MS_SLAVE_SWITCH and MYSQLND_MS_LAST_USED_SWITCH instead of their literal values.

<?php
/* Use constants for maximum portability */
$master_query = "/*" . MYSQLND_MS_MASTER_SWITCH . "*/SELECT id FROM test";

/* Valid but less portable: using literal instead of constant */
$slave_query = "/*ms=slave*/SHOW TABLES";

printf("master_query = '%s'\n", $master_query);
printf("slave_query = '%s'\n", $slave_query);
?>

The above examples will output:

master_query = /*ms=master*/SELECT id FROM test
slave_query = /*ms=slave*/SHOW TABLES

MYSQLND_MS_MASTER_SWITCH (string)
SQL hint used to send a query to the MySQL replication master server.
MYSQLND_MS_SLAVE_SWITCH (string)
SQL hint used to send a query to one of the MySQL replication slave servers.
MYSQLND_MS_LAST_USED_SWITCH (string)
SQL hint used to send a query to the last used MySQL server. The last used MySQL server can either be a master or a slave server in a MySQL replication setup.

mysqlnd_ms_query_is_select() related

MYSQLND_MS_QUERY_USE_MASTER (integer)
If mysqlnd_ms_is_select() returns MYSQLND_MS_QUERY_USE_MASTER for a given query, the built-in read/write split mechanism recommends sending the query to a MySQL replication master server.
MYSQLND_MS_QUERY_USE_SLAVE (integer)
If mysqlnd_ms_is_select() returns MYSQLND_MS_QUERY_USE_SLAVE for a given query, the built-in read/write split mechanism recommends sending the query to a MySQL replication slave server.
MYSQLND_MS_QUERY_USE_LAST_USED (integer)
If mysqlnd_ms_is_select() returns MYSQLND_MS_QUERY_USE_LAST_USED for a given query, the built-in read/write split mechanism recommends sending the query to the last used server.

mysqlnd_ms_set_qos(), quality of service filter and service level related

MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL (integer)
Use to request the service level eventual consistency from the mysqlnd_ms_set_qos(). Eventual consistency is the default quality of service when reading from an asynchronous MySQL replication slave. Data returned in this service level may or may not be stale, depending on whether the selected slaves happen to have replicated the latest changes from the MySQL replication master or not.
MYSQLND_MS_QOS_CONSISTENCY_SESSION (integer)
Use to request the service level session consistency from the mysqlnd_ms_set_qos(). Session consistency is defined as read your writes. The client is guaranteed to see his latest changes.
MYSQLND_MS_QOS_CONSISTENCY_STRONG (integer)
Use to request the service level strong consistency from the mysqlnd_ms_set_qos(). Strong consistency is used to ensure all clients see each others changes.
MYSQLND_MS_QOS_OPTION_GTID (integer)
Used as a service level option with mysqlnd_ms_set_qos() to parameterize session consistency.
MYSQLND_MS_QOS_OPTION_AGE (integer)
Used as a service level option with mysqlnd_ms_set_qos() to parameterize eventual consistency.

Other

The plugins version number can be obtained using MYSQLND_MS_VERSION or MYSQLND_MS_VERSION_ID. MYSQLND_MS_VERSION is the string representation of the numerical version number MYSQLND_MS_VERSION_ID, which is an integer such as 10000. Developers can calculate the version number as follows.

Version (part) | Example
Major*10000 | 1*10000 = 10000
Minor*100 | 0*100 = 0
Patch | 0 = 0
MYSQLND_MS_VERSION_ID | 10000

MYSQLND_MS_VERSION (string)
Plugin version string, for example, 1.0.0-prototype.
MYSQLND_MS_VERSION_ID (integer)
Plugin version number, for example, 10000.


Mysqlnd_ms Functions

Table of Contents

  • mysqlnd_ms_dump_servers — Returns a list of currently configured servers
  • mysqlnd_ms_fabric_select_global — Switch to global sharding server for a given table
  • mysqlnd_ms_fabric_select_shard — Switch to shard
  • mysqlnd_ms_get_last_gtid — Returns the latest global transaction ID
  • mysqlnd_ms_get_last_used_connection — Returns an array which describes the last used connection
  • mysqlnd_ms_get_stats — Returns query distribution and connection statistics
  • mysqlnd_ms_match_wild — Finds whether a table name matches a wildcard pattern or not
  • mysqlnd_ms_query_is_select — Find whether to send the query to the master, the slave or the last used MySQL server
  • mysqlnd_ms_set_qos — Sets the quality of service needed from the cluster
  • mysqlnd_ms_set_user_pick_server — Sets a callback for user-defined read/write splitting
  • mysqlnd_ms_xa_begin — Starts a distributed/XA transaction among MySQL servers
  • mysqlnd_ms_xa_commit — Commits a distributed/XA transaction among MySQL servers
  • mysqlnd_ms_xa_gc — Garbage collects unfinished XA transactions after severe errors
  • mysqlnd_ms_xa_rollback — Rolls back a distributed/XA transaction among MySQL servers


Returns a list of currently configured servers

  • « Mysqlnd_ms Functions
  • mysqlnd_ms_fabric_select_global »
  • PHP Manual
  • Mysqlnd_ms Functions
  • Returns a list of currently configured servers

mysqlnd_ms_dump_servers

(No version information available, might only be in Git)

mysqlnd_ms_dump_servers — Returns a list of currently configured servers

Description

mysqlnd_ms_dump_servers ( mixed $connection ) : array

Returns a list of currently configured servers.

Parameters

connection

A MySQL connection handle obtained from any of the connect functions of the mysqli, mysql or PDO_MYSQL extensions.

Return Values

FALSE on error. Otherwise, returns an array with two entries masters and slaves each of which contains an array listing all corresponding servers.

The function can be used to check and debug the list of servers currently used by the plugin. It is mostly useful when the list of servers changes at runtime, for example, when using MySQL Fabric.

masters and slaves server entries

Key | Description | Version
name_from_config | Server entry name from config, if appliciable. NULL if no configuration name is available. | Since 1.6.0.
hostname | Host name of the server. | Since 1.6.0.
user | Database user used to authenticate against the server. | Since 1.6.0.
port | TCP/IP port of the server. | Since 1.6.0.
socket | Unix domain socket of the server. | Since 1.6.0.

Notes

Note:

mysqlnd_ms_dump_servers() requires PECL mysqlnd_ms >> 1.6.0.

Examples

Example #1 mysqlnd_ms_dump_servers() example

{
    "myapp": {
        "master": {
            "master1": {
                "host":"master1_host",
                "port":"master1_port",
                "socket":"master1_socket",
                "db":"master1_db",
                "user":"master1_user",
                "password":"master1_pw"
            }
        },
        "slave": {
             "slave_0": {
                 "host":"slave0_host",
                 "port":"slave0_port",
                 "socket":"slave0_socket",
                 "db":"slave0_db",
                 "user":"slave0_user",
                 "password":"slave0_pw"
             },
             "slave_1": {
                 "host":"slave1_host"
             }
        }
    }
}
<?php
$link = mysqli_connect("myapp", "global_user", "global_pass", "global_db", 1234, "global_socket");
var_dump(mysqlnd_ms_dump_servers($link);
?>

The above example will output:

array(2) {
  ["masters"]=>
  array(1) {
    [0]=>
    array(5) {
      ["name_from_config"]=>
      string(7) "master1"
      ["hostname"]=>
      string(12) "master1_host"
      ["user"]=>
      string(12) "master1_user"
      ["port"]=>
      int(3306)
      ["socket"]=>
      string(14) "master1_socket"
    }
  }
  ["slaves"]=>
  array(2) {
    [0]=>
    array(5) {
      ["name_from_config"]=>
      string(7) "slave_0"
      ["hostname"]=>
      string(11) "slave0_host"
      ["user"]=>
      string(11) "slave0_user"
      ["port"]=>
      int(3306)
      ["socket"]=>
      string(13) "slave0_socket"
    }
    [1]=>
    array(5) {
      ["name_from_config"]=>
      string(7) "slave_1"
      ["hostname"]=>
      string(11) "slave1_host"
      ["user"]=>
      string(12) "gloabal_user"
      ["port"]=>
      int(1234)
      ["socket"]=>
      string(13) "global_socket"
    }
  }
}


Switch to global sharding server for a given table

  • « mysqlnd_ms_dump_servers
  • mysqlnd_ms_fabric_select_shard »
  • PHP Manual
  • Mysqlnd_ms Functions
  • Switch to global sharding server for a given table

mysqlnd_ms_fabric_select_global

(No version information available, might only be in Git)

mysqlnd_ms_fabric_select_global — Switch to global sharding server for a given table

Description

mysqlnd_ms_fabric_select_global ( mixed $connection , mixed $table_name ) : array
Warning

This function is currently not documented; only its argument list is available.

MySQL Fabric related.

Switch the connection to the nodes handling global sharding queries for the given table name.

Parameters

connection

A MySQL connection handle obtained from any of the connect functions of the mysqli, mysql or PDO_MYSQL extensions.

table_name

The table name to ask Fabric about.

Return Values

FALSE on error. Otherwise, TRUE

Notes

Note:

mysqlnd_ms_fabric_select_global() requires PECL mysqlnd_ms >> 1.6.0.


Switch to shard

  • « mysqlnd_ms_fabric_select_global
  • mysqlnd_ms_get_last_gtid »
  • PHP Manual
  • Mysqlnd_ms Functions
  • Switch to shard

mysqlnd_ms_fabric_select_shard

(No version information available, might only be in Git)

mysqlnd_ms_fabric_select_shard — Switch to shard

Description

mysqlnd_ms_fabric_select_shard ( mixed $connection , mixed $table_name , mixed $shard_key ) : array
Warning

This function is currently not documented; only its argument list is available.

MySQL Fabric related.

Switch the connection to the shards responsible for the given table name and shard key.

Parameters

connection

A MySQL connection handle obtained from any of the connect functions of the mysqli, mysql or PDO_MYSQL extensions.

table_name

The table name to ask Fabric about.

shard_key

The shard key to ask Fabric about.

Return Values

FALSE on error. Otherwise, TRUE

Notes

Note:

mysqlnd_ms_fabric_select_shard() requires PECL mysqlnd_ms >> 1.6.0.


Returns the latest global transaction ID

  • « mysqlnd_ms_fabric_select_shard
  • mysqlnd_ms_get_last_used_connection »
  • PHP Manual
  • Mysqlnd_ms Functions
  • Returns the latest global transaction ID

mysqlnd_ms_get_last_gtid

(PECL mysqlnd_ms >= 1.2.0)

mysqlnd_ms_get_last_gtid — Returns the latest global transaction ID

Description

mysqlnd_ms_get_last_gtid ( mixed $connection ) : string

Returns a global transaction identifier which belongs to a write operation no older than the last write performed by the client. It is not guaranteed that the global transaction identifier is identical to that one created for the last write transaction performed by the client.

Parameters

connection

A PECL/mysqlnd_ms connection handle to a MySQL server of the type PDO_MYSQL, mysqli> or ext/mysql. The connection handle is obtained when opening a connection with a host name that matches a mysqlnd_ms configuration file entry using any of the above three MySQL driver extensions.

Return Values

Returns a global transaction ID (GTID) on success. Otherwise, returns FALSE.

The function mysqlnd_ms_get_last_gtid() returns the GTID obtained when executing the SQL statement from the fetch_last_gtid entry of the global_transaction_id_injection section from the plugins configuration file.

The function may be called after the GTID has been incremented.

Notes

Note:

mysqlnd_ms_get_last_gtid() requires PHP >= 5.4.0 and PECL mysqlnd_ms >= 1.2.0. Internally, it is using a mysqlnd library C functionality not available with PHP 5.3.

Please note, all MySQL 5.6 production versions do not provide clients with enough information to use GTIDs for enforcing session consistency. In the worst case, the plugin will choose the master only.

Examples

Example #1 mysqlnd_ms_get_last_gtid() example

<?php
/* Open mysqlnd_ms connection using mysqli, PDO_MySQL or mysql extension */
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* auto commit mode, transaction on master, GTID must be incremented */
if (!$mysqli->query("DROP TABLE IF EXISTS test"))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

printf("GTID after transaction %s\n", mysqlnd_ms_get_last_gtid($mysqli));

/* auto commit mode, transaction on master, GTID must be incremented */
if (!$mysqli->query("CREATE TABLE test(id INT)"))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

printf("GTID after transaction %s\n", mysqlnd_ms_get_last_gtid($mysqli));
?>

See Also

  • Global Transaction IDs


Returns an array which describes the last used connection

  • « mysqlnd_ms_get_last_gtid
  • mysqlnd_ms_get_stats »
  • PHP Manual
  • Mysqlnd_ms Functions
  • Returns an array which describes the last used connection

mysqlnd_ms_get_last_used_connection

(PECL mysqlnd_ms >= 1.1.0)

mysqlnd_ms_get_last_used_connection — Returns an array which describes the last used connection

Description

mysqlnd_ms_get_last_used_connection ( mixed $connection ) : array

Returns an array which describes the last used connection from the plugins connection pool currently pointed to by the user connection handle. If using the plugin, a user connection handle represents a pool of database connections. It is not possible to tell from the user connection handles properties to which database server from the pool the user connection handle points.

The function can be used to debug or monitor PECL mysqlnd_ms.

Parameters

connection

A MySQL connection handle obtained from any of the connect functions of the mysqli, mysql or PDO_MYSQL extensions.

Return Values

FALSE on error. Otherwise, an array which describes the connection used to execute the last statement on.

Array which describes the connection.

Property | Description | Version
scheme | Connection scheme. Either tcp://host:port or unix://host:socket. If you want to distinguish connections from each other use a combination of scheme and thread_id as a unique key. Neither scheme nor thread_id alone are sufficient to distinguish two connections from each other. Two servers may assign the same thread_id to two different connections. Thus, connections in the pool may have the same thread_id. Also, do not rely on uniqueness of scheme in a pool. Your QA engineers may use the same MySQL server instance for two distinct logical roles and add it multiple times to the pool. This hack is used, for example, in the test suite. | Since 1.1.0.
host | Database server host used with the connection. The host is only set with TCP/IP connections. It is empty with Unix domain or Windows named pipe connections, | Since 1.1.0.
host_info | A character string representing the server hostname and the connection type. | Since 1.1.2.
port | Database server port used with the connection. | Since 1.1.0.
socket_or_pipe | Unix domain socket or Windows named pipe used with the connection. The value is empty for TCP/IP connections. | Since 1.1.2.
thread_id | Connection thread id. | Since 1.1.0.
last_message | Info message obtained from the MySQL C API function mysql_info(). Please, see mysqli_info() for a description. | Since 1.1.0.
errno | Error code. | Since 1.1.0.
error | Error message. | Since 1.1.0.
sqlstate | Error SQLstate code. | Since 1.1.0.

Notes

Note:

mysqlnd_ms_get_last_used_connection() requires PHP >= 5.4.0 and PECL mysqlnd_ms >> 1.1.0. Internally, it is using a mysqlnd library C call not available with PHP 5.3.

Examples

The example assumes that myapp refers to a plugin configuration file section and represents a connection pool.

Example #1 mysqlnd_ms_get_last_used_connection() example

<?php
$link = new mysqli("myapp", "user", "password", "database");
$res = $link->query("SELECT 1 FROM DUAL");
var_dump(mysqlnd_ms_get_last_used_connection($link));
?>

The above example will output:

array(10) {
  ["scheme"]=>
  string(22) "unix:///tmp/mysql.sock"
  ["host_info"]=>
  string(25) "Localhost via UNIX socket"
  ["host"]=>
  string(0) ""
  ["port"]=>
  int(3306)
  ["socket_or_pipe"]=>
  string(15) "/tmp/mysql.sock"
  ["thread_id"]=>
  int(46253)
  ["last_message"]=>
  string(0) ""
  ["errno"]=>
  int(0)
  ["error"]=>
  string(0) ""
  ["sqlstate"]=>
  string(5) "00000"
}


Returns query distribution and connection statistics

  • « mysqlnd_ms_get_last_used_connection
  • mysqlnd_ms_match_wild »
  • PHP Manual
  • Mysqlnd_ms Functions
  • Returns query distribution and connection statistics

mysqlnd_ms_get_stats

(PECL mysqlnd_ms >= 1.0.0)

mysqlnd_ms_get_stats — Returns query distribution and connection statistics

Description

mysqlnd_ms_get_stats ( void ) : array

Returns an array of statistics collected by the replication and load balancing plugin.

The PHP configuration setting mysqlnd_ms.collect_statistics controls the collection of statistics. The collection of statistics is disabled by default for performance reasons.

The scope of the statistics is the PHP process. Depending on your deployment model a PHP process may handle one or multiple requests.

Statistics are aggregated for all connections and all storage handler. It is not possible to tell how much queries originating from mysqli, PDO_MySQL or mysql API calls have contributed to the aggregated data values.

Parameters

This function has no parameters.

Return Values

Returns NULL if the PHP configuration directive mysqlnd_ms.enable has disabled the plugin. Otherwise, returns array of statistics.

Array of statistics

Statistic | Description | Version
use_slave

The semantics of this statistic has changed between 1.0.1 - 1.1.0.

The meaning for version 1.0.1 is as follows. Number of statements considered as read-only by the built-in query analyzer. Neither statements which begin with a SQL hint to force use of slave nor statements directed to a slave by an user-defined callback are included. The total number of statements sent to the slaves is use_slave + use_slave_sql_hint + use_slave_callback.

PECL/mysqlnd_ms 1.1.0 introduces a new concept of chained filters. The statistics is now set by the internal load balancing filter. With version 1.1.0 the load balancing filter is always the last in the filter chain, if used. In future versions a load balancing filter may be followed by other filters causing another change in the meaning of the statistic. If, in the future, a load balancing filter is followed by another filter it is no longer guaranteed that the statement, which increments use_slave, will be executed on the slaves.

The meaning for version 1.1.0 is as follows. Number of statements sent to the slaves. Statements directed to a slave by the user filter (an user-defined callback) are not included. The latter are counted by use_slave_callback.

Since 1.0.0.
use_master

The semantics of this statistic has changed between 1.0.1 - 1.1.0.

The meaning for version 1.0.1 is as follows. Number of statements not considered as read-only by the built-in query analyzer. Neither statements which begin with a SQL hint to force use of master nor statements directed to a master by an user-defined callback are included. The total number of statements sent to the master is use_master + use_master_sql_hint + use_master_callback.

PECL/mysqlnd_ms 1.1.0 introduces a new concept of chained filters. The statictics is now set by the internal load balancing filter. With version 1.1.0 the load balancing filter is always the last in the filter chain, if used. In future versions a load balancing filter may be followed by other filters causing another change in the meaning of the statistic. If, in the future, a load balancing filter is followed by another filter it is no longer guaranteed that the statement, which increments use_master, will be executed on the slaves.

The meaning for version 1.1.0 is as follows. Number of statements sent to the masters. Statements directed to a master by the user filter (an user-defined callback) are not included. The latter are counted by use_master_callback.

Since 1.0.0.
use_slave_guess | Number of statements the built-in query analyzer recommends sending to a slave because they contain no SQL hint to force use of a certain server. The recommendation may be overruled in the following. It is not guaranteed whether the statement will be executed on a slave or not. This is how often the internal is_select function has guessed that a slave shall be used. Please, see also the user space function mysqlnd_ms_query_is_select(). | Since 1.1.0.
use_master_guess | Number of statements the built-in query analyzer recommends sending to a master because they contain no SQL hint to force use of a certain server. The recommendation may be overruled in the following. It is not guaranteed whether the statement will be executed on a slave or not. This is how often the internal is_select function has guessed that a master shall be used. Please, see also the user space function mysqlnd_ms_query_is_select(). | Since 1.1.0.
use_slave_sql_hint | Number of statements sent to a slave because statement begins with the SQL hint to force use of slave. | Since 1.0.0.
use_master_sql_hint | Number of statements sent to a master because statement begins with the SQL hint to force use of master. | Since 1.0.0.
use_last_used_sql_hint | Number of statements sent to server which has run the previous statement, because statement begins with the SQL hint to force use of previously used server. | Since 1.0.0.
use_slave_callback | Number of statements sent to a slave because an user-defined callback has chosen a slave server for statement execution. | Since 1.0.0.
use_master_callback | Number of statements sent to a master because an user-defined callback has chosen a master server for statement execution. | Since 1.0.0.
non_lazy_connections_slave_success | Number of successfully opened slave connections from configurations not using lazy connections. The total number of successfully opened slave connections is non_lazy_connections_slave_success + lazy_connections_slave_success | Since 1.0.0.
non_lazy_connections_slave_failure | Number of failed slave connection attempts from configurations not using lazy connections. The total number of failed slave connection attempts is non_lazy_connections_slave_failure + lazy_connections_slave_failure | Since 1.0.0.
non_lazy_connections_master_success | Number of successfully opened master connections from configurations not using lazy connections. The total number of successfully opened master connections is non_lazy_connections_master_success + lazy_connections_master_success | Since 1.0.0.
non_lazy_connections_master_failure | Number of failed master connection attempts from configurations not using lazy connections. The total number of failed master connection attempts is non_lazy_connections_master_failure + lazy_connections_master_failure | Since 1.0.0.
lazy_connections_slave_success | Number of successfully opened slave connections from configurations using lazy connections. | Since 1.0.0.
lazy_connections_slave_failure | Number of failed slave connection attempts from configurations using lazy connections. | Since 1.0.0.
lazy_connections_master_success | Number of successfully opened master connections from configurations using lazy connections. | Since 1.0.0.
lazy_connections_master_failure | Number of failed master connection attempts from configurations using lazy connections. | Since 1.0.0.
trx_autocommit_on | Number of autocommit mode activations via API calls. This figure may be used to monitor activity related to the plugin configuration setting trx_stickiness. If, for example, you want to know if a certain API call invokes the mysqlnd library function trx_autocommit(), which is a requirement for trx_stickiness, you may call the user API function in question and check if the statistic has changed. The statistic is modified only by the plugins internal subclassed trx_autocommit() method. | Since 1.0.0.
trx_autocommit_off | Number of autocommit mode deactivations via API calls. | Since 1.0.0.
trx_master_forced | Number of statements redirected to the master while trx_stickiness=master and autocommit mode is disabled. | Since 1.0.0.
gtid_autocommit_injections_success | Number of successful SQL injections in autocommit mode as part of the plugins client-side global transaction id emulation. | Since 1.2.0.
gtid_autocommit_injections_failure | Number of failed SQL injections in autocommit mode as part of the plugins client-side global transaction id emulation. | Since 1.2.0.
gtid_commit_injections_success | Number of successful SQL injections in commit mode as part of the plugins client-side global transaction id emulation. | Since 1.2.0.
gtid_commit_injections_failure | Number of failed SQL injections in commit mode as part of the plugins client-side global transaction id emulation. | Since 1.2.0.
gtid_implicit_commit_injections_success | Number of successful SQL injections when implicit commit is detected as part of the plugins client-side global transaction id emulation. Implicit commit happens, for example, when autocommit has been turned off, a query is executed and autocommit is enabled again. In that case, the statement will be committed by the server and SQL to maintain is injected before the autocommit is re-enabled. Another sequence causing an implicit commit is begin(), query(), begin(). The second call to begin() will implicitly commit the transaction started by the first call to begin(). begin() refers to internal library calls not actual PHP user API calls. | Since 1.2.0.
gtid_implicit_commit_injections_failure | Number of failed SQL injections when implicit commit is detected as part of the plugins client-side global transaction id emulation. Implicit commit happens, for example, when autocommit has been turned off, a query is executed and autocommit is enabled again. In that case, the statement will be committed by the server and SQL to maintain is injected before the autocommit is re-enabled. | Since 1.2.0.
transient_error_retries | How often an operation has been retried when a transient error was detected. See also, transient_error plugin configuration file setting. | Since 1.6.0.
fabric_sharding_lookup_servers_success | Number of successful sharding.lookup_servers remote procedure calls to MySQL Fabric. A call is considered successful if the plugin could reach MySQL Fabric and got any reply. The reply itself may or may not be understood by the plugin. Success refers to the network transport only. If the reply was not understood or indicates a valid error condition, fabric_sharding_lookup_servers_xml_failure gets incremented. | Since 1.6.0.
fabric_sharding_lookup_servers_failure | Number of failed sharding.lookup_servers remote procedure calls to MySQL Fabric. A remote procedure call is considered failed if there was a network error in connecting to, writing to or reading from MySQL Fabric. | Since 1.6.0.
fabric_sharding_lookup_servers_time_total | Time spent connecting to,writing to and reading from MySQL Fabrich during the sharding.lookup_servers remote procedure call. The value is aggregated for all calls. Time is measured in microseconds. | Since 1.6.0.
fabric_sharding_lookup_servers_bytes_total | Total number of bytes received from MySQL Fabric in reply to sharding.lookup_servers calls. | Since 1.6.0.
fabric_sharding_lookup_servers_xml_failure | How often a reply from MySQL Fabric to sharding.lookup_servers calls was not understood. Please note, the current experimental implementation does not distinguish between valid errors returned and malformed replies. | Since 1.6.0.
xa_begin | How many XA/distributed transactions have been started using mysqlnd_ms_xa_begin(). | Since 1.6.0.
xa_commit_success | How many XA/distributed transactions have been successfully committed using mysqlnd_ms_xa_commit(). | Since 1.6.0.
xa_commit_failure | How many XA/distributed transactions failed to commit during mysqlnd_ms_xa_commit(). | Since 1.6.0.
xa_rollback_success | How many XA/distributed transactions have been successfully rolled back using mysqlnd_ms_xa_rollback(). The figure does not include implict rollbacks performed as a result of mysqlnd_ms_xa_commit() failure. | Since 1.6.0.
xa_rollback_failure | How many XA/distributed transactions could not be rolled back. This includes failures of mysqlnd_ms_xa_rollback() but also failured during rollback when closing a connection, if rollback_on_close is set. Please, see also xa_rollback_on_close below. | Since 1.6.0.
xa_participants | Total number of participants in any XA transaction started with mysqlnd_ms_xa_begin(). | Since 1.6.0.
xa_rollback_on_close | How many XA transactions have been rolled back implicitly when a connection was close and rollback_on_close is set. Depending on your coding policies, this may hint a flaw in your code as you may prefer to explicitly clean up resources. | Since 1.6.0.
pool_masters_total | Number of master servers (connections) in the internal connection pool. | Since 1.6.0.
pool_slaves_total | Number of slave servers (connections) in the internal connection pool. | Since 1.6.0.
pool_masters_active | Number of master servers (connections) from the internal connection pool which are currently used for picking a connection. | Since 1.6.0.
pool_slaves_active | Number of slave servers (connections) from the internal connection pool which are currently used for picking a connection. | Since 1.6.0.
pool_updates | How often the active connection list has been replaced and a new set of master and slave servers had been installed. | Since 1.6.0.
pool_master_reactivated | How often a master connection has been reused after being flushed from the active list. | Since 1.6.0.
pool_slave_reactivated | How often a slave connection has been reused after being flushed from the active list. | Since 1.6.0.

Examples

Example #1 mysqlnd_ms_get_stats() example

<?php
printf("mysqlnd_ms.enable = %d\n", ini_get("mysqlnd_ms.enable"));
printf("mysqlnd_ms.collect_statistics = %d\n", ini_get("mysqlnd_ms.collect_statistics"));
var_dump(mysqlnd_ms_get_stats());
?>

The above example will output:

mysqlnd_ms.enable = 1
mysqlnd_ms.collect_statistics = 1
array(26) {
  ["use_slave"]=>
  string(1) "0"
  ["use_master"]=>
  string(1) "0"
  ["use_slave_guess"]=>
  string(1) "0"
  ["use_master_guess"]=>
  string(1) "0"
  ["use_slave_sql_hint"]=>
  string(1) "0"
  ["use_master_sql_hint"]=>
  string(1) "0"
  ["use_last_used_sql_hint"]=>
  string(1) "0"
  ["use_slave_callback"]=>
  string(1) "0"
  ["use_master_callback"]=>
  string(1) "0"
  ["non_lazy_connections_slave_success"]=>
  string(1) "0"
  ["non_lazy_connections_slave_failure"]=>
  string(1) "0"
  ["non_lazy_connections_master_success"]=>
  string(1) "0"
  ["non_lazy_connections_master_failure"]=>
  string(1) "0"
  ["lazy_connections_slave_success"]=>
  string(1) "0"
  ["lazy_connections_slave_failure"]=>
  string(1) "0"
  ["lazy_connections_master_success"]=>
  string(1) "0"
  ["lazy_connections_master_failure"]=>
  string(1) "0"
  ["trx_autocommit_on"]=>
  string(1) "0"
  ["trx_autocommit_off"]=>
  string(1) "0"
  ["trx_master_forced"]=>
  string(1) "0"
  ["gtid_autocommit_injections_success"]=>
  string(1) "0"
  ["gtid_autocommit_injections_failure"]=>
  string(1) "0"
  ["gtid_commit_injections_success"]=>
  string(1) "0"
  ["gtid_commit_injections_failure"]=>
  string(1) "0"
  ["gtid_implicit_commit_injections_success"]=>
  string(1) "0"
  ["gtid_implicit_commit_injections_failure"]=>
  string(1) "0"
  ["transient_error_retries"]=>
  string(1) "0"
}

See Also

  • Runtime configuration
  • mysqlnd_ms.collect_statistics
  • mysqlnd_ms.enable
  • Monitoring


Finds whether a table name matches a wildcard pattern or not

  • « mysqlnd_ms_get_stats
  • mysqlnd_ms_query_is_select »
  • PHP Manual
  • Mysqlnd_ms Functions
  • Finds whether a table name matches a wildcard pattern or not

mysqlnd_ms_match_wild

(PECL mysqlnd_ms >= 1.1.0)

mysqlnd_ms_match_wild — Finds whether a table name matches a wildcard pattern or not

Description

mysqlnd_ms_match_wild ( string $table_name , string $wildcard ) : bool

Finds whether a table name matches a wildcard pattern or not.

This function is not of much practical relevance with PECL mysqlnd_ms 1.1.0 because the plugin does not support MySQL replication table filtering yet.

Parameters

table_name

The table name to check if it is matched by the wildcard.

wildcard

The wildcard pattern to check against the table name. The wildcard pattern supports the same placeholders as MySQL replication filters do.

MySQL replication filters can be configured by using the MySQL Server configuration options --replicate-wild-do-table and --replicate-wild-do-db. Please, consult the MySQL Reference Manual to learn more about this MySQL Server feature.

The supported placeholders are:

  • % - zero or more literals
  • _ - one literal

Placeholders can be escaped using \.

Return Values

Returns TRUE table_name is matched by wildcard. Otherwise, returns FALSE

Examples

Example #1 mysqlnd_ms_match_wild() example

<?php
var_dump(mysqlnd_ms_match_wild("schema_name.table_name", "schema%"));
var_dump(mysqlnd_ms_match_wild("abc", "_"));
var_dump(mysqlnd_ms_match_wild("table1", "table_"));
var_dump(mysqlnd_ms_match_wild("asia_customers", "%customers"));
var_dump(mysqlnd_ms_match_wild("funny%table","funny\%table"));
var_dump(mysqlnd_ms_match_wild("funnytable", "funny%table"));
?>

The above example will output:

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


Find whether to send the query to the master, the slave or the last used MySQL server

  • « mysqlnd_ms_match_wild
  • mysqlnd_ms_set_qos »
  • PHP Manual
  • Mysqlnd_ms Functions
  • Find whether to send the query to the master, the slave or the last used MySQL server

mysqlnd_ms_query_is_select

(PECL mysqlnd_ms >= 1.0.0)

mysqlnd_ms_query_is_select — Find whether to send the query to the master, the slave or the last used MySQL server

Description

mysqlnd_ms_query_is_select ( string $query ) : int

Finds whether to send the query to the master, the slave or the last used MySQL server.

The plugins built-in read/write split mechanism will be used to analyze the query string to make a recommendation where to send the query. The built-in read/write split mechanism is very basic and simple. The plugin will recommend sending all queries to the MySQL replication master server but those which begin with SELECT, or begin with a SQL hint which enforces sending the query to a slave server. Due to the basic but fast algorithm the plugin may propose to run some read-only statements such as SHOW TABLES on the replication master.

Parameters

query

Query string to test.

Return Values

A return value of MYSQLND_MS_QUERY_USE_MASTER indicates that the query should be send to the MySQL replication master server. The function returns a value of MYSQLND_MS_QUERY_USE_SLAVE if the query can be run on a slave because it is considered read-only. A value of MYSQLND_MS_QUERY_USE_LAST_USED is returned to recommend running the query on the last used server. This can either be a MySQL replication master server or a MySQL replication slave server.

If read write splitting has been disabled by setting mysqlnd_ms.disable_rw_split, the function will always return MYSQLND_MS_QUERY_USE_MASTER or MYSQLND_MS_QUERY_USE_LAST_USED.

Examples

Example #1 mysqlnd_ms_query_is_select() example

<?php
function is_select($query)
{
 switch (mysqlnd_ms_query_is_select($query))
 {
  case MYSQLND_MS_QUERY_USE_MASTER:
   printf("'%s' should be run on the master.\n", $query);
   break;
  case MYSQLND_MS_QUERY_USE_SLAVE:
   printf("'%s' should be run on a slave.\n", $query);
   break;
  case MYSQLND_MS_QUERY_USE_LAST_USED:
   printf("'%s' should be run on the server that has run the previous query\n", $query);
   break;
  default:
   printf("No suggestion where to run the '%s', fallback to master recommended\n", $query);
   break;
 }
}

is_select("INSERT INTO test(id) VALUES (1)");
is_select("SELECT 1 FROM DUAL");
is_select("/*" . MYSQLND_MS_LAST_USED_SWITCH . "*/SELECT 2 FROM DUAL");
?>

The above example will output:

INSERT INTO test(id) VALUES (1) should be run on the master.
SELECT 1 FROM DUAL should be run on a slave.
/*ms=last_used*/SELECT 2 FROM DUAL should be run on the server that has run the previous query

See Also

  • Predefined Constants
  • user filter
  • Runtime configuration
  • mysqlnd_ms.disable_rw_split
  • mysqlnd_ms.enable


Sets the quality of service needed from the cluster

  • « mysqlnd_ms_query_is_select
  • mysqlnd_ms_set_user_pick_server »
  • PHP Manual
  • Mysqlnd_ms Functions
  • Sets the quality of service needed from the cluster

mysqlnd_ms_set_qos

(PECL mysqlnd_ms < 1.2.0)

mysqlnd_ms_set_qos — Sets the quality of service needed from the cluster

Description

mysqlnd_ms_set_qos ( mixed $connection , int $service_level [, int $service_level_option [, mixed $option_value ]] ) : bool

Sets the quality of service needed from the cluster. A database cluster delivers a certain quality of service to the user depending on its architecture. A major aspect of the quality of service is the consistency level the cluster can offer. An asynchronous MySQL replication cluster defaults to eventual consistency for slave reads: a slave may serve stale data, current data, or it may have not the requested data at all, because it is not synchronous to the master. In a MySQL replication cluster, only master accesses can give strong consistency, which promises that all clients see each others changes.

PECL/mysqlnd_ms hides the complexity of choosing appropriate nodes to achieve a certain level of service from the cluster. The "Quality of Service" filter implements the necessary logic. The filter can either be configured in the plugins configuration file, or at runtime using mysqlnd_ms_set_qos().

Similar results can be achieved with PECL mysqlnd_ms < 1.2.0, if using SQL hints to force the use of a certain type of node or using the master_on_write plugin configuration option. The first requires more code and causes more work on the application side. The latter is less refined than using the quality of service filter. Settings made through the function call can be reversed, as shown in the example below. The example temporarily switches to a higher service level (session consistency, read your writes) and returns back to the clusters default after it has performed all operations that require the better service. This way, read load on the master can be minimized compared to using master_on_write, which would continue using the master after the first write.

Since 1.5.0 calls will fail when done in the middle of a transaction if transaction stickiness is enabled and transaction boundaries have been detected. properly.

Parameters

connection

A PECL/mysqlnd_ms connection handle to a MySQL server of the type PDO_MYSQL, mysqli or ext/mysql for which a service level is to be set. The connection handle is obtained when opening a connection with a host name that matches a mysqlnd_ms configuration file entry using any of the above three MySQL driver extensions.

service_level

The requested service level: MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL, MYSQLND_MS_QOS_CONSISTENCY_SESSION or MYSQLND_MS_QOS_CONSISTENCY_STRONG.

service_level_option

An option to parameterize the requested service level. The option can either be MYSQLND_MS_QOS_OPTION_GTID or MYSQLND_MS_QOS_OPTION_AGE.

The option MYSQLND_MS_QOS_OPTION_GTID can be used to refine the service level MYSQLND_MS_QOS_CONSISTENCY_SESSION. It must be combined with a fourth function parameter, the option_value. The option_value shall be a global transaction ID obtained from mysqlnd_ms_get_last_gtid(). If set, the plugin considers both master servers and asynchronous slaves for session consistency (read your writes). Otherwise, only masters are used to achieve session consistency. A slave is considered up-to-date and checked if it has already replicated the global transaction ID from option_value. Please note, searching appropriate slaves is an expensive and slow operation. Use the feature sparsely, if the master cannot handle the read load alone.

The MYSQLND_MS_QOS_OPTION_AGE option can be combined with the MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL service level, to filter out asynchronous slaves that lag more seconds behind the master than option_value. If set, the plugin will only consider slaves for reading if SHOW SLAVE STATUS reports Slave_IO_Running=Yes, Slave_SQL_Running=Yes and Seconds_Behind_Master <= option_value. Please note, searching appropriate slaves is an expensive and slow operation. Use the feature sparsely in version 1.2.0. Future versions may improve the algorithm used to identify candidates. Please, see the MySQL reference manual about the precision, accuracy and limitations of the MySQL administrative command SHOW SLAVE STATUS.

option_value

Parameter value for the service level option. See also the service_level_option parameter.

Return Values

Returns TRUE if the connections service level has been switched to the requested. Otherwise, returns FALSE

Notes

Note:

mysqlnd_ms_set_qos() requires PHP >= 5.4.0 and PECL mysqlnd_ms >= 1.2.0. Internally, it is using a mysqlnd library C functionality not available with PHP 5.3.

Please note, all MySQL 5.6 production versions do not provide clients with enough information to use GTIDs for enforcing session consistency. In the worst case, the plugin will choose the master only.

Examples

Example #1 mysqlnd_ms_set_qos() example

<?php
/* Open mysqlnd_ms connection using mysqli, PDO_MySQL or mysql extension */
$mysqli = new mysqli("myapp", "username", "password", "database");
if (!$mysqli)
  /* Of course, your error handling is nicer... */
  die(sprintf("[%d] %s\n", mysqli_connect_errno(), mysqli_connect_error()));

/* Session consistency: read your writes */
$ret = mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_SESSION);
if (!$ret)
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

/* Will use master and return fresh data, client can see his last write */
if (!$res = $mysqli->query("SELECT item, price FROM orders WHERE order_id = 1"))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

/* Back to default: use of all slaves and masters permitted, stale data can happen */
if (!mysqlnd_ms_set_qos($mysqli, MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL))
  die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));
?>

See Also

  • mysqlnd_ms_get_last_gtid() - Returns the latest global transaction ID
  • Service level and consistency concept
  • Filter concept


Sets a callback for user-defined read/write splitting

  • « mysqlnd_ms_set_qos
  • mysqlnd_ms_xa_begin »
  • PHP Manual
  • Mysqlnd_ms Functions
  • Sets a callback for user-defined read/write splitting

mysqlnd_ms_set_user_pick_server

(PECL mysqlnd_ms < 1.1.0)

mysqlnd_ms_set_user_pick_server — Sets a callback for user-defined read/write splitting

Description

mysqlnd_ms_set_user_pick_server ( string $function ) : bool

Sets a callback for user-defined read/write splitting. The plugin will call the callback only if pick[]=user is the default rule for server picking in the relevant section of the plugins configuration file.

The plugins built-in read/write query split mechanism decisions can be overwritten in two ways. The easiest way is to prepend the query string with the SQL hints MYSQLND_MS_MASTER_SWITCH, MYSQLND_MS_SLAVE_SWITCH or MYSQLND_MS_LAST_USED_SWITCH. Using SQL hints one can control, for example, whether a query shall be send to the MySQL replication master server or one of the slave servers. By help of SQL hints it is not possible to pick a certain slave server for query execution.

Full control on server selection can be gained using a callback function. Use of a callback is recommended to expert users only because the callback has to cover all cases otherwise handled by the plugin.

The plugin will invoke the callback function for selecting a server from the lists of configured master and slave servers. The callback function inspects the query to run and picks a server for query execution by returning the hosts URI, as found in the master and slave list.

If the lazy connections are enabled and the callback chooses a slave server for which no connection has been established so far and establishing the connection to the slave fails, the plugin will return an error upon the next action on the failed connection, for example, when running a query. It is the responsibility of the application developer to handle the error. For example, the application can re-run the query to trigger a new server selection and callback invocation. If so, the callback must make sure to select a different slave, or check slave availability, before returning to the plugin to prevent an endless loop.

Parameters

function

The function to be called. Class methods may also be invoked statically using this function by passing array($classname, $methodname) to this parameter. Additionally class methods of an object instance may be called by passing array($objectinstance, $methodname) to this parameter.

Return Values

Host to run the query on. The host URI is to be taken from the master and slave connection lists passed to the callback function. If callback returns a value neither found in the master nor in the slave connection lists the plugin will fallback to the second pick method configured via the pick[] setting in the plugin configuration file. If not second pick method is given, the plugin falls back to the build-in default pick method for server selection.

Notes

Note:

mysqlnd_ms_set_user_pick_server() is available with PECL mysqlnd_ms < 1.1.0. It has been replaced by the user filter. Please, check the Change History for upgrade notes.

Examples

Example #1 mysqlnd_ms_set_user_pick_server() example

[myapp]
master[] = localhost
slave[] = 192.168.2.27:3306
slave[] = 192.168.78.136:3306
pick[] = user
<?php

function pick_server($connected, $query, $master, $slaves, $last_used)
{
 static $slave_idx = 0;
 static $num_slaves = NULL;
 if (is_null($num_slaves))
  $num_slaves = count($slaves);

 /* default: fallback to the plugins build-in logic */
 $ret = NULL;

 printf("User has connected to '%s'...\n", $connected);
 printf("... deciding where to run '%s'\n", $query);

 $where = mysqlnd_ms_query_is_select($query);
 switch ($where)
 {
  case MYSQLND_MS_QUERY_USE_MASTER:
   printf("... using master\n");
   $ret = $master[0];
   break;
  case MYSQLND_MS_QUERY_USE_SLAVE:
   /* SELECT or SQL hint for using slave */
   if (stristr($query, "FROM table_on_slave_a_only"))
   {
    /* a table which is only on the first configured slave  */
    printf("... access to table available only on slave A detected\n");
    $ret = $slaves[0];
   }
   else
   {
    /* round robin */
    printf("... some read-only query for a slave\n");
    $ret = $slaves[$slave_idx++ % $num_slaves];
   }
   break;
  case MYSQLND_MS_QUERY_LAST_USED:
   printf("... using last used server\n");
   $ret = $last_used;
   break;
 }

 printf("... ret = '%s'\n", $ret);
 return $ret;
}

mysqlnd_ms_set_user_pick_server("pick_server");

$mysqli = new mysqli("myapp", "root", "root", "test");

if (!($res = $mysqli->query("SELECT 1 FROM DUAL")))
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
else
 $res->close();

if (!($res = $mysqli->query("SELECT 2 FROM DUAL")))
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
else
 $res->close();

if (!($res = $mysqli->query("SELECT * FROM table_on_slave_a_only")))
 printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
else
 $res->close();

$mysqli->close();
?>

The above example will output:

User has connected to 'myapp'...
... deciding where to run 'SELECT 1 FROM DUAL'
... some read-only query for a slave
... ret = 'tcp://192.168.2.27:3306'
User has connected to 'myapp'...
... deciding where to run 'SELECT 2 FROM DUAL'
... some read-only query for a slave
... ret = 'tcp://192.168.78.136:3306'
User has connected to 'myapp'...
... deciding where to run 'SELECT * FROM table_on_slave_a_only'
... access to table available only on slave A detected
... ret = 'tcp://192.168.2.27:3306'

See Also

  • mysqlnd_ms_query_is_select() - Find whether to send the query to the master, the slave or the last used MySQL server
  • Filter concept
  • user filter


Starts a distributed/XA transaction among MySQL servers

  • « mysqlnd_ms_set_user_pick_server
  • mysqlnd_ms_xa_commit »
  • PHP Manual
  • Mysqlnd_ms Functions
  • Starts a distributed/XA transaction among MySQL servers

mysqlnd_ms_xa_begin

(PECL mysqlnd_ms < 1.6.0)

mysqlnd_ms_xa_begin — Starts a distributed/XA transaction among MySQL servers

Description

mysqlnd_ms_xa_begin ( mixed $connection , string $gtrid [, int $timeout ] ) : int

Starts a XA transaction among MySQL servers. PECL/mysqlnd_ms acts as a transaction coordinator the distributed transaction.

Once a global transaction has been started, the plugin injects appropriate XA BEGIN SQL statements on all MySQL servers used in the following. The global transaction is either ended by calling mysqlnd_ms_xa_commit(), mysqlnd_ms_xa_rollback() or by an implicit rollback in case of an error.

During a global transaction, the plugin tracks all server switches, for example, when switching from one MySQL shard to another MySQL shard. Immediately before a query is run on a server that has not been participating in the global transaction yet, XA BEGIN is executed on the server. From a users perspective the injection happens during a call to a query execution function such as mysqli_query(). Should the injection fail an error is reported to the caller of the query execution function. The failing server does not become a participant in the global transaction. The user may retry executing a query on the server and hereby retry injecting XA BEGIN, abort the global transaction because not all required servers can participate, or ignore and continue the global without the failed server.

Reasons to fail executing XA BEGIN include but are not limited to a server being unreachable or the server having an open, concurrent XA transaction using the same xid.

Please note, global and local transactions are mutually exclusive. You cannot start a XA transaction when you have a local transaction open. The local transaction must be ended first. The plugin tries to detect this conflict as early as possible. It monitors API calls for controlling local transactions to learn about the current state. However, if using SQL statements for local transactions such as BEGIN, the plugin may not know the current state and the conflict is not detected before XA BEGIN is injected and executed.

The use of other XA resources but MySQL servers is not supported by the function. To carry out a global transaction among, for example, a MySQL server and another vendors database system, you should issue the systems SQL commands yourself.

Note: Experimental

The feature is currently under development. There may be issues and/or feature limitations. Do not use in production environments.

Parameters

connection

A MySQL connection handle obtained from any of the connect functions of the mysqli, mysql or PDO_MYSQL extensions.

gtrid

Global transaction identifier (gtrid). The gtrid is a binary string up to 64 bytes long. Please note, depending on your character set settings, 64 characters may require more than 64 bytes to store.

In accordance with the MySQL SQL syntax, XA transactions use identifiers made of three parts. An xid consists of a global transaction identifier (gtrid), a branch qualifier (bqual) and a format identifier (formatID). Only the global transaction identifier can and needs to be set.

The branch qualifier and format identifier are set automatically. The details should be considered implementation dependent, which may change without prior notice. In version 1.6 the branch qualifier is consecutive number which is incremented whenever a participant joins the global transaction.

timeout

Timeout in seconds. The default value is 60 seconds.

The timeout is a hint to the garbage collection. If a transaction is recorded to take longer than expected, the garbage collection begins checking the transactions status.

Setting a low value may make the garbage collection check the progress too often. Please note, checking the status of a global transaction may involve connecting to all recorded participants and possibly issuing queries on the servers.

Return Values

Returns TRUE if there is no open local or global transaction and a new global transaction can be started. Otherwise, returns FALSE

See Also

  • Quickstart XA/Distributed transactions
  • Runtime configuration
  • mysqlnd_ms_get_stats() - Returns query distribution and connection statistics


Commits a distributed/XA transaction among MySQL servers

  • « mysqlnd_ms_xa_begin
  • mysqlnd_ms_xa_gc »
  • PHP Manual
  • Mysqlnd_ms Functions
  • Commits a distributed/XA transaction among MySQL servers

mysqlnd_ms_xa_commit

(PECL mysqlnd_ms < 1.6.0)

mysqlnd_ms_xa_commit — Commits a distributed/XA transaction among MySQL servers

Description

mysqlnd_ms_xa_commit ( mixed $connection , string $gtrid ) : int

Commits a global transaction among MySQL servers started by mysqlnd_ms_xa_begin().

If any of the global transaction participants fails to commit an implicit rollback is performed. It may happen that not all cases can be handled during the rollback. For example, no attempts will be made to reconnect to a participant after the connection to the participant has been lost. Solving cases that cannot easily be rolled back is left to the garbage collection.

Note: Experimental

The feature is currently under development. There may be issues and/or feature limitations. Do not use in production environments.

Parameters

connection

A MySQL connection handle obtained from any of the connect functions of the mysqli, mysql or PDO_MYSQL extensions.

gtrid

Global transaction identifier (gtrid).

Return Values

Returns TRUE if the global transaction has been committed. Otherwise, returns FALSE

See Also

  • Quickstart XA/Distributed transactions
  • Runtime configuration
  • mysqlnd_ms_get_stats() - Returns query distribution and connection statistics


Garbage collects unfinished XA transactions after severe errors

  • « mysqlnd_ms_xa_commit
  • mysqlnd_ms_xa_rollback »
  • PHP Manual
  • Mysqlnd_ms Functions
  • Garbage collects unfinished XA transactions after severe errors

mysqlnd_ms_xa_gc

(PECL mysqlnd_ms < 1.6.0)

mysqlnd_ms_xa_gc — Garbage collects unfinished XA transactions after severe errors

Description

mysqlnd_ms_xa_gc ( mixed $connection [, string $gtrid [, bool $ignore_max_retries ]] ) : int

Garbage collects unfinished XA transactions.

The XA protocol is a blocking protocol. There exist cases when servers participating in a global transaction cannot make progress when the transaction coordinator crashes or disconnects. In such a case, the MySQL servers keep waiting for instructions to finish the XA transaction in question. Because transactions occupy resources, transactions should always be terminated properly.

Garbage collection requires configuring a state store to track global transactions. Should a PHP client crash in the middle of a transaction and a new PHP client be started, then the built-in garbage collection can learn about the aborted global transaction and terminate it. If you do not configure a state store, the garbage collection cannot perform any cleanup tasks.

The state store should be crash-safe and be highly available to survive its own crash. Currently, only MySQL is supported as a state store.

Garbage collection can also be performed automatically in the background. See the plugin configuration directive garbage_collection for details.

Note: Experimental

The feature is currently under development. There may be issues and/or feature limitations. Do not use in production environments.

Parameters

connection

A MySQL connection handle obtained from any of the connect functions of the mysqli, mysql or PDO_MYSQL extensions.

gtrid

Global transaction identifier (gtrid). If given, the garbage collection considers the transaction only. Otherwise, the state store is scanned for any unfinished transaction.

ignore_max_retries

Whether to ignore the plugin configuration max_retries setting. If garbage collection continuously fails and the max_retries limit is reached prior to finishing the failed global transaction, you can attempt further runs prior to investigating the cause and solving the issue manually by issuing appropriate SQL statements on the participants. Setting the parameter has the same effect as temporarily setting max_retries = 0.

Return Values

Returns TRUE if garbage collection was successful. Otherwise, returns FALSE

See Also

  • Quickstart XA/Distributed transactions
  • Runtime configuration
  • State store configuration
  • mysqlnd_ms_get_stats() - Returns query distribution and connection statistics


Rolls back a distributed/XA transaction among MySQL servers

  • « mysqlnd_ms_xa_gc
  • Change History »
  • PHP Manual
  • Mysqlnd_ms Functions
  • Rolls back a distributed/XA transaction among MySQL servers

mysqlnd_ms_xa_rollback

(PECL mysqlnd_ms < 1.6.0)

mysqlnd_ms_xa_rollback — Rolls back a distributed/XA transaction among MySQL servers

Description

mysqlnd_ms_xa_rollback ( mixed $connection , string $gtrid ) : int

Rolls back a global transaction among MySQL servers started by mysqlnd_ms_xa_begin().

If any of the global transaction participants fails to rollback the situation is left to be solved by the garbage collection.

Note: Experimental

The feature is currently under development. There may be issues and/or feature limitations. Do not use in production environments.

Parameters

connection

A MySQL connection handle obtained from any of the connect functions of the mysqli, mysql or PDO_MYSQL extensions.

gtrid

Global transaction identifier (gtrid).

Return Values

Returns TRUE if the global transaction has been rolled back. Otherwise, returns FALSE

See Also

  • Quickstart XA/Distributed transactions
  • Runtime configuration
  • mysqlnd_ms_get_stats() - Returns query distribution and connection statistics


Change History

Table of Contents

  • PECL/mysqlnd_ms 1.6 series
  • PECL/mysqlnd_ms 1.5 series
  • PECL/mysqlnd_ms 1.4 series
  • PECL/mysqlnd_ms 1.3 series
  • PECL/mysqlnd_ms 1.2 series
  • PECL/mysqlnd_ms 1.1 series
  • PECL/mysqlnd_ms 1.0 series

This change history is a high level summary of selected changes that may impact applications and/or break backwards compatibility.

See also the CHANGES file in the source distribution for a complete list of changes.


PECL/mysqlnd_ms 1.6 series

1.6.0-alpha

  • Release date: TBD
  • Motto/theme: Maintenance and initial MySQL Fabric support

Note:

This is the current development series. All features are at an early stage. Changes may happen at any time without prior notice. Please, do not use this version in production environments.

The documentation may not reflect all changes yet.

Bug fixes

  • Won't fix: #66616 R/W split fails: QOS with mysqlnd_get_last_gtid with built-in MySQL GTID

    This is not a bug in the plugins implementation but a server side feature limitation not considered and documented before. MySQL 5.6 built-in GTIDs cannot be used to ensure session consistency when reading from slaves in all cases. In the worst case the plugin will not consider using the slaves and fallback to using the master. There will be no wrong results but no benefit from doing GTID checks either.

  • Fixed #66064 - Random once load balancer ignoring weights

    Due to a config parsing bug random load balancing has ignored node weights if, and only if, the sticky flag was set (random once).

  • Fixed #65496 - Wrong check for slave delay

    The quality of service filter has erroneously ignored slaves that lag for zero (0) seconds if a any maximum lag had been set. Although a slave was not lagging behind, it was excluded from the load balancing list if a maximum age was set by the QoS filter. This was due to using the wrong comparison operator in the source of the filter.

  • Fixed #65408 - Compile failure with -Werror=format-security

Feature changes

  • Introduced an internal connection pool. When using Fabric and switching from shard group A to shard group B, we are replacing the entire list of masters and slaves. This troubles the connections state alignment logic and some filters. Some filters cache information on the master and slave lists. The new internal connection pool abstraction allows us to inform the filters of changes, hence they can update their caches.

    Later on, the pool can also be used to reduce connection overhead. Assume you are switching from a shard group to another and back again. Whenever the switch is done, the pool's active server (and connection) lists are replaced. However, no longer used connections are not necessarily closed immediately but can be kept in the pool for later reuse.

    Please note, the connection pool is internalat this point. There are some new statistics to monitor it. However, you cannot yet configure pool size of behaviour.

  • Added a basic distributed transaction abstraction. XA transactions can are supported ever since using standard SQL calls. This is inconvenient as XA participants must be managed manually. PECL/mysqlnd_ms introduces API calls to control XA transaction among MySQL servers. When using the new functions, PECL/mysqlnd_ms acts as a transaction coordinator. After starting a distributed transaction, the plugin tracks all servers involved until the transaction is ended and issues appropriate SQL statements on the XA participants.

    This is useful, for example, when using Fabric and sharding. When using Fabric the actual shard servers involved in a business transaction may not be known in advance. Thus, manually controlling a transaction that spawns multiple shards becomes difficult. Please, be warned about current limitations.

  • Introduced automatic retry loop for transient errors and corresponding statistic to count the number of implicit retries. Some distributed database clusters use transient errors to hint a client to retry its operation in a bit. Most often, the client is then supposed to halt execution (sleep) for a short moment before retrying the desired operation. Immediately failing over to another node is not necessary in response to the error. Instead, a retry loop can be performed. Common situation when using MySQL Cluster.

  • Introduced automatic retry loop for transient errors and corresponding statistic to count the number of implicit retries. Some distributed database clusters use transient errors to hint a client to retry its operation in a bit. Most often, the client is then supposed to halt execution (sleep) for a short moment before retrying the desired operation. Immediately failing over to another node is not necessary in response to the error. Instead, a retry loop can be performed. Common situation when using MySQL Cluster.

  • Introduced most basic support for the MySQL Fabric High Availability and sharding framework.

    Please, consider this pre-alpha quality. Both the server side framework and the client side code is supposed to work flawless considering the MySQL Fabric quickstart examples only. However, testing has not been performed to the level of prior plugin alpha releases. Either sides are moving targets, API changes may happen at any time without prior warning.

    As this is work in progress, the manual may not yet reflect allow feature limitations and known bugs.

  • New statistics to monitor the Fabric XML RPC call sharding.lookup_servers: fabric_sharding_lookup_servers_success, fabric_sharding_lookup_servers_failure, fabric_sharding_lookup_servers_time_total, fabric_sharding_lookup_servers_bytes_total, fabric_sharding_lookup_servers_xml_failure.

  • New functions related to MySQL Fabric:
mysqlnd_ms_fabric_select_shard(),
mysqlnd_ms_fabric_select_global(),
mysqlnd_ms_dump_servers().


PECL/mysqlnd_ms 1.5 series

1.5.1-stable

  • Release date: 06/2013
  • Motto/theme: Sharding support, improved transaction support

Note:

This is the current stable series. Use this version in production environments.

The documentation is complete.

1.5.0-alpha

  • Release date: 03/2013
  • Motto/theme: Sharding support, improved transaction support

Bug fixes

  • Fixed #60605 PHP segmentation fault when mysqlnd_ms is enabled.

  • Setting transaction stickiness disables all load balancing, including automatic failover, for the duration of a transaction. So far connection switches could have happened in the middle of a transaction in multi-master configurations and during automatic failover although transaction monitoring had detected transaction boundaries properly.

  • BC break and bug fix. SQL hints enforcing the use of a specific kind of server (MYSQLND_MS_MASTER_SWITCH, MYSQLND_MS_SLAVE_SWITCH, MYSQLND_MS_LAST_USED_SWITCH) are ignored for the duration of a transaction of transaction stickiness is enabled and transaction boundaries have been detected properly.

    This is a change in behaviour. However, it is also a bug fix and a step to align behaviour. If, in previous versions, transaction stickiness, one of the above listed SQL hints and the quality of service filtering was combined it could happened that the SQL hints got ignored. In some case the SQL hints did work, in other cases they did not. The new behaviour is more consistent. SQL hints will always be ignore for the duration of a transaction, if transaction stickiness is enabled.

    Please note, transaction boundary detection continues to be based on API call monitoring. SQL commands controlling transactions are not monitored.

  • BC break and bug fix. Calls to mysqlnd_ms_set_qos() will fail when done in the middle of a transaction if transaction stickiness is enabled. Connection switches are not allowed for the duration of a transaction. Changing the quality of service likely results on a different set of servers qualifying for query execution, possibly making it necessary to switch connections. Thus, the call is not allowed in during an active transaction. The quality of server can, however, be changed in between transactions.

Feature changes

  • Introduced the node_group filter. The filter lets you organize servers (master and slaves) into groups. Queries can be directed to a certain group of servers by prefixing the query statement with a SQL hint/comment that contains the groups configured name. Grouping can be used for partitioning and sharding, and also to optimize for local caching. In the case of sharding, a group name can be thought of like a shard key. All queries for a given shard key will be executed on the configured shard. Note: both the client and server must support sharding for sharding to function with mysqlnd_ms.

  • Extended configuration file validation during PHP startup (RINIT). An E_WARNING level error will be thrown if the configuration file can not be read (permissions), is empty, or the file (JSON) could not be parsed. Warnings may appear in log files, which depending on how PHP is configured.

    Distributions that aim to provide a pre-configured setup, including a configuration file stub, are asked to put {} into the configuration file to prevent this warning about an invalid configuration file.

    Further configuration file validation is done when parsing sections upon opening a connection. Please, note that there may still be situations when an invalid plugin configuration file does not lead to proper error messages but a failure to connect.

  • As of PHP 5.5.0, improved support for transaction boundaries detection was added for mysqli. The mysqli extension has been modified to use the new C API calls of the mysqlnd library to begin, commit, and rollback a transaction or savepoint. If trx_stickiness is used to enable transaction aware load balancing, the mysqli_begin(), mysqli_commit() and mysqli_rollback() functions will now be monitered by the plugin, to go along with the mysqli_autocommit() function that was already supported. All SQL features to control transactions are also available through the improved mysqli transaction control related functions. This means that it is not required to issue SQL statements instead of using API calls. Applications using the appropriate API calls can be load balanced by PECL/mysqlnd_ms in a completely transaction-aware way.

    Please note, PDO_MySQL has not been updated yet to utilize the new mysqlnd API calls. Thus, transaction boundary detection with PDO_MySQL continues to be limited to the monitoring by passing in PDO::ATTR_AUTOCOMMIT to PDO::setAttribute().

  • Introduced trx_stickiness=on. This trx_stickiness option differs from trx_stickiness=master as it tries to execute a read-only transaction on a slave, if quality of service (consistency level) allows the use of a slave. Read-only transactions were introduced in MySQL 5.6, and they offer performance gains.

  • Query cache support is considered beta if used with the mysqli API. It should work fine with primary copy based clusters. For all other APIs, this feature continues to be called experimental.

  • The code examples in the mysqlnd_ms source were updated.


PECL/mysqlnd_ms 1.4 series

1.4.2-stable

  • Release date: 08/2012
  • Motto/theme: Tweaking based on user feedback

1.4.1-beta

  • Release date: 08/2012
  • Motto/theme: Tweaking based on user feedback

Bug fixes

  • Fixed build with PHP 5.5

1.4.0-alpha

  • Release date: 07/2012
  • Motto/theme: Tweaking based on user feedback

Feature changes

  • BC break: Renamed plugin configuration setting ini_file to config_file. In early versions the plugin configuration file used ini style. Back then the configuration setting was named accordingly. It has now been renamed to reflect the newer file format and to distinguish it from PHP's own ini file (configuration directives file).

  • Introduced new default charset setting server_charset to allow proper escaping before a connection is opened. This is most useful when using lazy connections, which are a default.

  • Introduced wait_for_gtid_timeout setting to throttle slave reads that need session consistency. If global transaction identifier are used and the service level is set to session consistency, the plugin tries to find up-to-date slaves. The slave status check is done by a SQL statement. If nothing else is set, the slave status is checked only one can the search for more up-to-date slaves continues immediately thereafter. Setting wait_for_gtid_timeout instructs the plugin to poll a slaves status for wait_for_gtid_timeout seconds if the first execution of the SQL statement has shown that the slave is not up-to-date yet. The poll will be done once per second. This way, the plugin will wait for slaves to catch up and throttle the client.

  • New failover strategy loop_before_master. By default the plugin does no failover. It is possible to enable automatic failover if a connection attempt fails. Upto version 1.3 only master strategy existed to failover to a master if a slave connection fails. loop_before_master is similar but tries all other slaves before attempting to connect to the master if a slave connection fails.

    The number of attempts can be limited using the max_retries option. Failed hosts can be remembered and skipped in load balancing for the rest of the web request. max_retries and remember_failed are considered experimental although decent stability is given. Syntax and semantics may change in the future without prior notice.


PECL/mysqlnd_ms 1.3 series

1.3.2-stable

  • Release date: 04/2012
  • Motto/theme: see 1.3.0-alpha

Bug fixes

  • Fixed problem with multi-master where although in a transaction the queries to the master weren't sticky and were spread all over the masters (RR). Still not sticky for Random. Random_once is not affected.

1.3.1-beta

  • Release date: 04/2012
  • Motto/theme: see 1.3.0-alpha

Bug fixes

  • Fixed problem with building together with QC.

1.3.0-alpha

  • Release date: 04/2012
  • Motto/theme: Query caching through quality-of-service concept

The 1.3 series aims to improve the performance of applications and the overall load of an asynchronous MySQL cluster, for example, a MySQL cluster using MySQL Replication. This is done by transparently replacing a slave access with a local cache access, if the application allows it by setting an appropriate quality of service flag. When using MySQL replication a slave can serve stale data. An application using MySQL replication must continue to work correctly with stale data. Given that the application is know to work correctly with stale data, the slave access can transparently be replace with a local cache access.

PECL/mysqlnd_qc serves as a cache backend. PECL/mysqlnd_qc supports use of various storage locations, among others main memory, APC and MEMCACHE.

Feature changes

  • Added cache option to quality-of-service (QoS) filter.

    • New configure option enable-mysqlnd-ms-cache-support
    • New constant MYSQLND_MS_HAVE_CACHE_SUPPORT.
    • New constant MYSQLND_MS_QOS_OPTION_CACHE to be used with mysqlnd_ms_set_qos().

  • Support for built-in global transaction identifier feature of MySQL 5.6.5-m8 or newer.


PECL/mysqlnd_ms 1.2 series

1.2.1-beta

  • Release date: 01/2012
  • Motto/theme: see 1.2.0-alpha

Minor test changes.

1.2.0-alpha

  • Release date: 11/2011
  • Motto/theme: Global Transaction ID injection and quality-of-service concept

In version 1.2 the focus continues to be on supporting MySQL database clusters with asynchronous replication. The plugin tries to make using the cluster introducing a quality-of-service filter which applications can use to define what service quality they need from the cluster. Service levels provided are eventual consistency with optional maximum age/slave slag, session consistency and strong consistency.

Additionally the plugin can do client-side global transaction id injection to make manual master failover easier.

Feature changes

  • Introduced quality-of-service (QoS) filter. Service levels provided by QoS filter:

    • eventual consistency, optional option slave lag
    • session consistency, optional option GTID
    • strong consistency

  • Added the mysqlnd_ms_set_qos() function to set the required connection quality at runtime. The new constants related to mysqlnd_ms_set_qos() are:

    • MYSQLND_MS_QOS_CONSISTENCY_STRONG
    • MYSQLND_MS_QOS_CONSISTENCY_SESSION
    • MYSQLND_MS_QOS_CONSISTENCY_EVENTUAL
    • MYSQLND_MS_QOS_OPTION_GTID
    • MYSQLND_MS_QOS_OPTION_AGE

  • Added client-side global transaction id injection (GTID).

  • New statistics related to GTID:

    • gtid_autocommit_injections_success
    • gtid_autocommit_injections_failure
    • gtid_commit_injections_success
    • gtid_commit_injections_failure
    • gtid_implicit_commit_injections_success
    • gtid_implicit_commit_injections_failure

  • Added mysqlnd_ms_get_last_gtid() to fetch the last global transaction id.

  • Enabled support for multi master without slaves.


PECL/mysqlnd_ms 1.1 series

1.1.0

  • Release date: 09/2011
  • Motto/theme: Cover replication basics with production quality

The 1.1 and 1.0 series expose a similar feature set. Internally, the 1.1 series has been refactored to plan for future feature additions. A new configuration file format has been introduced, and limitations have been lifted. And the code quality and quality assurance has been improved.

Feature changes

  • Added the (chainable) filter concept:

    • BC break: mysqlnd_ms_set_user_pick_server() has been removed. Thehttp://svn.php.net/viewvc/pecl/mysqlnd_ms/trunk/ user filter has been introduced to replace it. The filter offers similar functionality, but see below for an explanation of the differences.

  • New powerful JSON based configuration syntax.
  • Lazy connections improved: security relevant, and state changing commands are covered.
  • Support for (native) prepared statements.

  • New statistics: use_master_guess, use_slave_guess.

    • BC break: Semantics of statistics changed for use_slave, use_master. Future changes are likely. Please see, mysqlnd_ms_get_stats().

  • List of broadcasted messages extended by ssl_set.
  • Library calls now monitored to remember settings for lazy connections: change_user, select_db, set_charset, set_autocommit.
  • Introduced mysqlnd_ms.disable_rw_split. The configuration setting allows using the load balancing and lazy connection functionality independently of read write splitting.

Bug fixes

  • Fixed PECL #22724 - Server switching (mysqlnd_ms_query_is_select() case sensitive)
  • Fixed PECL #22784 - Using mysql_connect and mysql_select_db did not work
  • Fixed PECL #59982 - Unusable extension with --enable-mysqlnd-ms-table-filter. Use of the option is NOT supported. You must not used it. Added note to m4.
  • Fixed Bug #60119 - host="localhost" lost in mysqlnd_ms_get_last_used_connection()

The mysqlnd_ms_set_user_pick_server() function was removed, and replaced in favor of a new user filter. You can no longer set a callback function using mysqlnd_ms_set_user_pick_server() at runtime, but instead have to configure it in the plugins configuration file. The user filter will pass the same arguments to the callback as before. Therefore, you can continue to use the same procedural function as a callback.callback It is no longer possible to use static class methods, or class methods of an object instance, as a callback. Doing so will cause the function executing a statement handled by the plugin to emit an E_RECOVERABLE_ERROR level error, which might look like: "(mysqlnd_ms) Specified callback (picker) is not a valid callback." Note: this may halt your application.


PECL/mysqlnd_ms 1.0 series

1.0.1-alpha

  • Release date: 04/2011
  • Motto/theme: bug fix release

1.0.0-alpha

  • Release date: 04/2011
  • Motto/theme: Cover replication basics to test user feedback

The first release of practical use. It features basic automatic read-write splitting, SQL hints to overrule automatic redirection, load balancing of slave requests, lazy connections, and optional, automatic use of the master after the first write.

The public feature set is close to that of the 1.1 release.

1.0.0-pre-alpha

  • Release date: 09/2010
  • Motto/theme: Proof of concept

Initial check-in. Essentially a demo of the mysqlnd plugin API.


Mysqlnd query result cache plugin

  • Introduction
  • Quickstart and Examples
    • Architecture and Concepts
    • Setup
    • Caching queries
    • Setting the TTL
    • Pattern based caching
    • Slam defense
    • Finding cache candidates
    • Measuring cache efficiency
    • Beyond TTL: user-defined storage
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
  • Predefined Constants
  • mysqlnd_qc Functions
    • mysqlnd_qc_clear_cache — Flush all cache contents
    • mysqlnd_qc_get_available_handlers — Returns a list of available storage handler
    • mysqlnd_qc_get_cache_info — Returns information on the current handler, the number of cache entries and cache entries, if available
    • mysqlnd_qc_get_core_stats — Statistics collected by the core of the query cache
    • mysqlnd_qc_get_normalized_query_trace_log — Returns a normalized query trace log for each query inspected by the query cache
    • mysqlnd_qc_get_query_trace_log — Returns a backtrace for each query inspected by the query cache
    • mysqlnd_qc_set_cache_condition — Set conditions for automatic caching
    • mysqlnd_qc_set_is_select — Installs a callback which decides whether a statement is cached
    • mysqlnd_qc_set_storage_handler — Change current storage handler
    • mysqlnd_qc_set_user_handlers — Sets the callback functions for a user-defined procedural storage handler
  • Change History
    • PECL/mysqlnd_qc 1.2 series
    • PECL/mysqlnd_qc 1.1 series
    • PECL/mysqlnd_qc 1.0 series


Introduction

The mysqlnd query result cache plugin adds easy to use client-side query caching to all PHP MySQL extensions using mysqlnd.

As of version PHP 5.3.3 the MySQL native driver for PHP ( mysqlnd) features an internal plugin C API. C plugins, such as the query cache plugin, can extend the functionality of mysqlnd.

Mysqlnd plugins such as the query cache plugin operate transparent from a user perspective. The cache plugin supports all PHP applications and all PHP MySQL extensions ( mysqli, mysql, PDO_MYSQL). It does not change existing APIs.

No significant application changes are required to cache a query. The cache has two operation modes. It will either cache all queries (not recommended) or only those queries marked with a certain SQL hint (recommended).

Key Features

  • Transparent and therefore easy to use

    • supports all PHP MySQL extensions

    • no API changes

    • very little application changes required

  • Flexible invalidation strategy

    • Time-to-Live (TTL)

    • user-defined

  • Storage with different scope and life-span

    • Default (Hash, process memory)

    • APC

    • MEMCACHE

    • sqlite

    • user-defined

  • Built-in slam defense to prevent cache stampeding.

Limitations

The current 1.0.1 release of PECL mysqlnd_qc does not support PHP 5.4. Version 1.1.0-alpha lifts this limitation.

Prepared statements and unbuffered queries are fully supported. Thus, the plugin is capable of caching all statements issued with mysqli or PDO_MySQL, which are the only two PHP MySQL APIs to offer prepared statement support.

On the name

The shortcut mysqlnd_qc stands for mysqlnd query cache plugin. The name was chosen for a quick-and-dirty proof-of-concept. In the beginning the developers did not expect to continue using the code base. Sometimes PECL/mysqlnd_qc has also been called client-side query result set cache.


Quickstart and Examples

Table of Contents

  • Architecture and Concepts
  • Setup
  • Caching queries
  • Setting the TTL
  • Pattern based caching
  • Slam defense
  • Finding cache candidates
  • Measuring cache efficiency
  • Beyond TTL: user-defined storage

The mysqlnd query cache plugin is easy to use. This quickstart will demo typical use-cases, and provide practical advice on getting started.

It is strongly recommended to read the reference sections in addition to the quickstart. It is safe to begin with the quickstart. However, before using the plugin in mission critical environments we urge you to read additionally the background information from the reference sections.

Most of the examples use the mysqli extension because it is the most feature complete PHP MySQL extension. However, the plugin can be used with any PHP MySQL extension that is using the mysqlnd library.


Architecture and Concepts

The query cache plugin is implemented as a PHP extension. It is written in C and operates under the hood of PHP. During the startup of the PHP interpreter, it gets registered as a mysqlnd plugin to replace selected mysqlnd C methods. Hereby, it can change the behaviour of any PHP MySQL extension (mysqli, PDO_MYSQL, mysql) compiled to use the mysqlnd library without changing the extensions API. This makes the plugin compatible with each and every PHP MySQL application. Because existing APIs are not changed, it is almost transparent to use. Please, see the mysqlnd plugin API description for a discussion of the advantages of the plugin architecture and a comparison with proxy based solutions.

Transparent to use

At PHP run time PECL/mysqlnd_qc can proxy queries send from PHP (mysqlnd) to the MySQL server. It then inspects the statement string to find whether it shall cache its results. If so, result set is cached using a storage handler and further executions of the statement are served from the cache for a user-defined period. The Time to Live (TTL) of the cache entry can either be set globally or on a per statement basis.

A statement is either cached if the plugin is instructed to cache all statements globally using a or, if the query string starts with the SQL hint (/*qc=on*/). The plugin is capable of caching any query issued by calling appropriate API calls of any of the existing PHP MySQL extensions.

Flexible storage: various storage handler

Various storage handler are supported to offer different scopes for cache entries. Different scopes allow for different degrees in sharing cache entries among clients.

  • default (built-in): process memory, scope: process, one or more web requests depending on PHP deployment model used

  • APC: shared memory, scope: single server, multiple web requests

  • SQLite: memory or file, scope: single server, multiple web requests

  • MEMCACHE: main memory, scope: single or multiple server, multiple web requests

  • user (built-in): user-defined - any, scope: user-defined - any

Support for the APC, SQLite and MEMCACHE storage handler has to be enabled at compile time. The default and user handler are built-in. It is possible to switch between compiled-in storage handlers on a per query basis at run time. However, it is recommended to pick one storage handler and use it for all cache entries.

Built-in slam defense to avoid overloading

To avoid overload situations the cache plugin has a built-in slam defense mechanism. If a popular cache entries expires many clients using the cache entries will try to refresh the cache entry. For the duration of the refresh many clients may access the database server concurrently. In the worst case, the database server becomes overloaded and it takes more and more time to refresh the cache entry, which in turn lets more and more clients try to refresh the cache entry. To prevent this from happening the plugin has a slam defense mechanism. If slam defense is enabled and the plugin detects an expired cache entry it extends the life time of the cache entry before it refreshes the cache entry. This way other concurrent accesses to the expired cache entry are still served from the cache for a certain time. The other concurrent accesses to not trigger a concurrent refresh. Ideally, the cache entry gets refreshed by the client which extended the cache entries lifespan before other clients try to refresh the cache and potentially cause an overload situation.

Unique approach to caching

PECL/mysqlnd_qc has a unique approach to caching result sets that is superior to application based cache solutions. Application based solutions first fetch a result set into PHP variables. Then, the PHP variables are serialized for storage in a persistent cache, and then unserialized when fetching. The mysqlnd query cache stores the raw wire protocol data sent from MySQL to PHP in its cache and replays it, if still valid, on a cache hit. This way, it saves an extra serialization step for a cache put that all application based solutions have to do. It can store the raw wire protocol data in the cache without having to serialize into a PHP variable first and deserializing the PHP variable for storing in the cache again.


Setup

The plugin is implemented as a PHP extension. See also the installation instructions to install the » PECL/mysqlnd_qc extension.

Compile or configure the PHP MySQL extension (mysqli, PDO_MYSQL, mysql) that you plan to use with support for the mysqlnd library. PECL/mysqlnd_qc is a plugin for the mysqlnd library. To use the plugin with any of the existing PHP MySQL extensions (APIs), the extension has to use the mysqlnd library.

Then, load the extension into PHP and activate the plugin in the PHP configuration file using the PHP configuration directive named mysqlnd_qc.enable_qc.

Example #1 Enabling the plugin (php.ini)

mysqlnd_qc.enable_qc=1


Caching queries

There are four ways to trigger caching of a query.

  • Use of SQL hints on a per query basis
  • User supplied callbacks to decide on a per query basis, for example, using mysqlnd_qc_is_select()
  • mysqlnd_set_cache_condition() for rule based automatic per query decisions
  • mysqlnd_qc.cache_by_default = 1 to cache all queries blindly

Use of SQL hints and mysqlnd_qc.cache_by_default = 1 are explained below. Please, refer to the function reference on mysqlnd_qc_is_select() for a description of using a callback and, mysqlnd_qc_set_cache_condition() on how to set rules for automatic caching.

A SQL hint is a SQL standards compliant comment. As a SQL comment it is ignored by the database. A statement is considered eligible for caching if it either begins with the SQL hint enabling caching or it is a SELECT statement.

An individual query which shall be cached must begin with the SQL hint /*qc=on*/. It is recommended to use the PHP constant MYSQLND_QC_ENABLE_SWITCH instead of using the string value.

  • not eligible for caching and not cached: INSERT INTO test(id) VALUES (1)

  • not eligible for caching and not cached: SHOW ENGINES

  • eligible for caching but uncached: SELECT id FROM test

  • eligible for caching and cached: /*qc=on*/SELECT id FROM test

The examples SELECT statement string is prefixed with the MYSQLND_QC_ENABLE_SWITCH SQL hint to enable caching of the statement. The SQL hint must be given at the very beginning of the statement string to enable caching.

Example #1 Using the MYSQLND_QC_ENABLE_SWITCH SQL hint

mysqlnd_qc.enable_qc=1
<?php
/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2)");

/* Will be cached because of the SQL hint */
$start = microtime(true);
$res   = $mysqli->query("/*" . MYSQLND_QC_ENABLE_SWITCH . "*/" . "SELECT id FROM test WHERE id = 1");

var_dump($res->fetch_assoc());
$res->free();

printf("Total time uncached query: %.6fs\n", microtime(true) - $start);

/* Cache hit */
$start = microtime(true);
$res   = $mysqli->query("/*" . MYSQLND_QC_ENABLE_SWITCH . "*/" . "SELECT id FROM test WHERE id = 1");

var_dump($res->fetch_assoc());
$res->free();

printf("Total time cached query: %.6fs\n", microtime(true) - $start);
?>

The above examples will output something similar to:

array(1) {
  ["id"]=>
  string(1) "1"
}
Total time uncached query: 0.000740s
array(1) {
  ["id"]=>
  string(1) "1"
}
Total time cached query: 0.000098s

If nothing else is configured, as it is the case in the quickstart example, the plugin will use the built-in default storage handler. The default storage handler uses process memory to hold a cache entry. Depending on the PHP deployment model, a PHP process may serve one or more web requests. Please, consult the web server manual for details. Details make no difference for the examples given in the quickstart.

The query cache plugin will cache all queries regardless if the query string begins with the SQL hint which enables caching or not, if the PHP configuration directive mysqlnd_qc.cache_by_default is set to 1. The setting mysqlnd_qc.cache_by_default is evaluated by the core of the query cache plugins. Neither the built-in nor user-defined storage handler can overrule the setting.

The SQL hint /*qc=off*/ can be used to disable caching of individual queries if mysqlnd_qc.cache_by_default = 1 It is recommended to use the PHP constant MYSQLND_QC_DISABLE_SWITCH instead of using the string value.

Example #2 Using the MYSQLND_QC_DISABLE_SWITCH SQL hint

mysqlnd_qc.enable_qc=1
mysqlnd_qc.cache_by_default=1
<?php
/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2)");

/* Will be cached although no SQL hint is present because of mysqlnd_qc.cache_by_default = 1*/
$res = $mysqli->query("SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();

$mysqli->query("DELETE FROM test WHERE id = 1");

/* Cache hit - no automatic invalidation and still valid! */
$res = $mysqli->query("SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();

/* Cache miss - query must not be cached because of the SQL hint */
$res = $mysqli->query("/*" . MYSQLND_QC_DISABLE_SWITCH . "*/SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();
?>

The above examples will output:

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

PECL/mysqlnd_qc forbids caching of statements for which at least one column from the statements result set shows no table name in its meta data by default. This is usually the case for columns originating from SQL functions such as NOW() or LAST_INSERT_ID(). The policy aims to prevent pitfalls if caching by default is used.

Example #3 Example showing which type of statements are not cached

mysqlnd_qc.enable_qc=1
mysqlnd_qc.cache_by_default=1
<?php
/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1)");

for ($i = 0; $i < 3; $i++) {

    $start = microtime(true);

    /* Note: statement will not be cached because of NOW() use */
    $res = $mysqli->query("SELECT id, NOW() AS _time FROM test");
    $row = $res->fetch_assoc();

    /* dump results */
    var_dump($row);

    printf("Total time: %.6fs\n", microtime(true) - $start);

    /* pause one second */
    sleep(1);
}
?>

The above examples will output something similar to:

array(2) {
  ["id"]=>
  string(1) "1"
  ["_time"]=>
  string(19) "2012-01-11 15:43:10"
}
Total time: 0.000540s
array(2) {
  ["id"]=>
  string(1) "1"
  ["_time"]=>
  string(19) "2012-01-11 15:43:11"
}
Total time: 0.000555s
array(2) {
  ["id"]=>
  string(1) "1"
  ["_time"]=>
  string(19) "2012-01-11 15:43:12"
}
Total time: 0.000549s

It is possible to enable caching for all statements including those which has columns in their result set for which MySQL reports no table, such as the statement from the example. Set mysqlnd_qc.cache_no_table = 1 to enable caching of such statements. Please, note the difference in the measured times for the above and below examples.

Example #4 Enabling caching for all statements using the mysqlnd_qc.cache_no_table ini setting

mysqlnd_qc.enable_qc=1
mysqlnd_qc.cache_by_default=1
mysqlnd_qc.cache_no_table=1
<?php
/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1)");

for ($i = 0; $i < 3; $i++) {

    $start = microtime(true);

    /* Note: statement will not be cached because of NOW() use */
    $res = $mysqli->query("SELECT id, NOW() AS _time FROM test");
    $row = $res->fetch_assoc();

    /* dump results */
    var_dump($row);

    printf("Total time: %.6fs\n", microtime(true) - $start);

    /* pause one second */
    sleep(1);
}
?>

The above examples will output something similar to:

array(2) {
  ["id"]=>
  string(1) "1"
  ["_time"]=>
  string(19) "2012-01-11 15:47:45"
}
Total time: 0.000546s
array(2) {
  ["id"]=>
  string(1) "1"
  ["_time"]=>
  string(19) "2012-01-11 15:47:45"
}
Total time: 0.000187s
array(2) {
  ["id"]=>
  string(1) "1"
  ["_time"]=>
  string(19) "2012-01-11 15:47:45"
}
Total time: 0.000167s

Note:

Although mysqlnd_qc.cache_no_table = 1 has been created for use with mysqlnd_qc.cache_by_default = 1 it is bound it. The plugin will evaluate the mysqlnd_qc.cache_no_table whenever a query is to be cached, no matter whether caching has been enabled using a SQL hint or any other measure.


Setting the TTL

The default invalidation strategy of the query cache plugin is Time to Live (TTL). The built-in storage handlers will use the default TTL defined by the PHP configuration value mysqlnd_qc.ttl unless the query string contains a hint for setting a different TTL. The TTL is specified in seconds. By default cache entries expire after 30 seconds

The example sets mysqlnd_qc.ttl=3 to cache statements for three seconds by default. Every second it updates a database table record to hold the current time and executes a SELECT statement to fetch the record from the database. The SELECT statement is cached for three seconds because it is prefixed with the SQL hint enabling caching. The output verifies that the query results are taken from the cache for the duration of three seconds before they are refreshed.

Example #1 Setting the TTL with the mysqlnd_qc.ttl ini setting

mysqlnd_qc.enable_qc=1
mysqlnd_qc.ttl=3
<?php
/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id VARCHAR(255))");

for ($i = 0; $i < 7; $i++) {

    /* update DB row  */
    if (!$mysqli->query("DELETE FROM test") ||
        !$mysqli->query("INSERT INTO test(id) VALUES (NOW())"))
      /* Of course, a real-life script should do better error handling */
      die(sprintf("[%d] %s\n", $mysqli->errno, $mysqli->error));

    /* select latest row but cache results */
    $query  = "/*" . MYSQLND_QC_ENABLE_SWITCH . "*/";
    $query .= "SELECT id AS _time FROM test";
    if (!($res = $mysqli->query($query)) ||
        !($row = $res->fetch_assoc()))
    {
      printf("[%d] %s\n", $mysqli->errno, $mysqli->error);
    }
    $res->free();
    printf("Wall time %s - DB row time %s\n", date("H:i:s"), $row['_time']);

    /* pause one second */
    sleep(1);
}
?>

The above examples will output something similar to:

Wall time 14:55:59 - DB row time 2012-01-11 14:55:59
Wall time 14:56:00 - DB row time 2012-01-11 14:55:59
Wall time 14:56:01 - DB row time 2012-01-11 14:55:59
Wall time 14:56:02 - DB row time 2012-01-11 14:56:02
Wall time 14:56:03 - DB row time 2012-01-11 14:56:02
Wall time 14:56:04 - DB row time 2012-01-11 14:56:02
Wall time 14:56:05 - DB row time 2012-01-11 14:56:05

As can be seen from the example, any TTL based cache can serve stale data. Cache entries are not automatically invalidated, if underlying data changes. Applications using the default TTL invalidation strategy must be able to work correctly with stale data.

A user-defined cache storage handler can implement any invalidation strategy to work around this limitation.

The default TTL can be overruled using the SQL hint /*qc_tt=seconds*/. The SQL hint must be appear immediately after the SQL hint which enables caching. It is recommended to use the PHP constant MYSQLND_QC_TTL_SWITCH instead of using the string value.

Example #2 Setting TTL with SQL hints

<?php
$start = microtime(true);

/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2)");

printf("Default TTL\t: %d seconds\n", ini_get("mysqlnd_qc.ttl"));

/* Will be cached for 2 seconds */
$sql = sprintf("/*%s*//*%s%d*/SELECT id FROM test WHERE id = 1", MYSQLND_QC_ENABLE_SWITCH, MYSQLND_QC_TTL_SWITCH, 2);
$res = $mysqli->query($sql);

var_dump($res->fetch_assoc());
$res->free();

$mysqli->query("DELETE FROM test WHERE id = 1");
sleep(1);

/* Cache hit - no automatic invalidation and still valid! */
$res = $mysqli->query($sql);
var_dump($res->fetch_assoc());
$res->free();

sleep(2);

/* Cache miss - cache entry has expired */
$res = $mysqli->query($sql);
var_dump($res->fetch_assoc());
$res->free();

printf("Script runtime\t: %d seconds\n", microtime(true) - $start);
?>

The above examples will output something similar to:

Default TTL     : 30 seconds
array(1) {
  ["id"]=>
  string(1) "1"
}
array(1) {
  ["id"]=>
  string(1) "1"
}
NULL
Script runtime  : 3 seconds


Pattern based caching

An application has three options for telling PECL/mysqlnd_qc whether a particular statement shall be used. The most basic approach is to cache all statements by setting mysqlnd_qc.cache_by_default = 1. This approach is often of little practical value. But it enables users to make a quick estimation about the maximum performance gains from caching. An application designed to use a cache may be able to prefix selected statements with the appropriate SQL hints. However, altering an applications source code may not always be possible or desired, for example, to avoid problems with software updates. Therefore, PECL/mysqlnd_qc allows setting a callback which decides if a query is to be cached.

The callback is installed with the mysqlnd_qc_set_is_select() function. The callback is given the statement string of every statement inspected by the plugin. Then, the callback can decide whether to cache the function. The callback is supposed to return FALSE if the statement shall not be cached. A return value of TRUE makes the plugin try to add the statement into the cache. The cache entry will be given the default TTL ( mysqlnd_qc.ttl). If the callback returns a numerical value it is used as the TTL instead of the global default.

Example #1 Setting a callback with mysqlnd_qc_set_is_select()

mysqlnd_qc.enable_qc=1
mysqlnd_qc.collect_statistics=1
<?php
/* callback which decides if query is cached */
function is_select($query) {
    static $patterns = array(
      /* true - use default from mysqlnd_qc.ttl */
      "@SELECT\s+.*\s+FROM\s+test@ismU" => true,
      /* 3 - use TTL = 3 seconds */
      "@SELECT\s+.*\s+FROM\s+news@ismU" => 3
    );

    /* check if query does match pattern */
    foreach ($patterns as $pattern => $ttl) {
        if (preg_match($pattern, $query)) {
            printf("is_select(%45s): cache\n", $query);
            return $ttl;
        }
    }
    printf("is_select(%45s): do not cache\n", $query);
    return false;
}
/* install callback */
mysqlnd_qc_set_is_select("is_select");

/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");

/* cache put */
$mysqli->query("SELECT id FROM test WHERE id = 1");
/* cache hit */
$mysqli->query("SELECT id FROM test WHERE id = 1");
/* cache put */
$mysqli->query("SELECT * FROM test");

$stats = mysqlnd_qc_get_core_stats();
printf("Cache put: %d\n", $stats['cache_put']);
printf("Cache hit: %d\n", $stats['cache_hit']);
?>

The above examples will output something similar to:

is_select(                    DROP TABLE IF EXISTS test): do not cache
is_select(                    CREATE TABLE test(id INT)): do not cache
is_select(    INSERT INTO test(id) VALUES (1), (2), (3)): do not cache
is_select(             SELECT id FROM test WHERE id = 1): cache
is_select(             SELECT id FROM test WHERE id = 1): cache
is_select(                           SELECT * FROM test): cache
Cache put: 2
Cache hit: 1

The examples callback tests if a statement string matches a pattern. If this is the case, it either returns TRUE to cache the statement using the global default TTL or an alternative TTL.

To minimize application changes the callback can put into and registered in an auto prepend file.


Slam defense

A badly designed cache can do more harm than good. In the worst case a cache can increase database server load instead of minimizing it. An overload situation can occur if a highly shared cache entry expires (cache stampeding).

Cache entries are shared and reused to a different degree depending on the storage used. The default storage handler stores cache entries in process memory. Thus, a cache entry can be reused for the life-span of a process. Other PHP processes cannot access it. If Memcache is used, a cache entry can be shared among multiple PHP processes and even among multiple machines, depending on the set up being used.

If a highly shared cache entry stored, for example, in Memcache expires, many clients gets a cache miss. Many client requests can no longer be served from the cache but try to run the underlying query on the database server. Until the cache entry is refreshed, more and more clients contact the database server. In the worst case, a total lost of service is the result.

The overload can be avoided using a storage handler which limits the reuse of cache entries to few clients. Then, at the average, its likely that only a limited number of clients will try to refresh a cache entry concurrently.

Additionally, the built-in slam defense mechanism can and should be used. If slam defense is activated an expired cache entry is given an extended life time. The first client getting a cache miss for the expired cache entry tries to refresh the cache entry within the extended life time. All other clients requesting the cache entry are temporarily served from the cache although the original TTL of the cache entry has expired. The other clients will not experience a cache miss before the extended life time is over.

Example #1 Enabling the slam defense mechanism

mysqlnd_qc.slam_defense=1
mysqlnd_qc.slam_defense_ttl=1

The slam defense mechanism is enabled with the PHP configuration directive mysqlnd_qc.slam_defense. The extended life time of a cache entry is set with mysqlnd_qc.slam_defense_ttl.

The function mysqlnd_qc_get_core_stats() returns an array of statistics. The statistics slam_stale_refresh and slam_stale_hit are incremented if slam defense takes place.

It is not possible to give a one-fits-all recommendation on the slam defense configuration. Users are advised to monitor and test their setup and derive settings accordingly.


Finding cache candidates

A statement should be considered for caching if it is executed often and has a long run time. Cache candidates are found by creating a list of statements sorted by the product of the number of executions multiplied by the statements run time. The function mysqlnd_qc_get_query_trace_log() returns a query log which help with the task.

Collecting a query trace is a slow operation. Thus, it is disabled by default. The PHP configuration directive mysqlnd_qc.collect_query_trace is used to enable it. The functions trace contains one entry for every query issued before the function is called.

Example #1 Collecting a query trace

mysqlnd_qc.enable_qc=1
mysqlnd_qc.collect_query_trace=1
<?php
/* connect to MySQL */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");

/* dummy queries to fill the query trace */
for ($i = 0; $i < 2; $i++) {
    $res = $mysqli->query("SELECT 1 AS _one FROM DUAL");
    $res->free();
}

/* dump trace */
var_dump(mysqlnd_qc_get_query_trace_log());
?>

The above examples will output:

array(2) {
  [0]=>
  array(8) {
    ["query"]=>
    string(26) "SELECT 1 AS _one FROM DUAL"
    ["origin"]=>
    string(102) "#0 qc.php(7): mysqli->query('SELECT 1 AS _on...')
#1 {main}"
    ["run_time"]=>
    int(0)
    ["store_time"]=>
    int(25)
    ["eligible_for_caching"]=>
    bool(false)
    ["no_table"]=>
    bool(false)
    ["was_added"]=>
    bool(false)
    ["was_already_in_cache"]=>
    bool(false)
  }
  [1]=>
  array(8) {
    ["query"]=>
    string(26) "SELECT 1 AS _one FROM DUAL"
    ["origin"]=>
    string(102) "#0 qc.php(7): mysqli->query('SELECT 1 AS _on...')
#1 {main}"
    ["run_time"]=>
    int(0)
    ["store_time"]=>
    int(8)
    ["eligible_for_caching"]=>
    bool(false)
    ["no_table"]=>
    bool(false)
    ["was_added"]=>
    bool(false)
    ["was_already_in_cache"]=>
    bool(false)
  }
}

Assorted information is given in the trace. Among them timings and the origin of the query call. The origin property holds a code backtrace to identify the source of the query. The depth of the backtrace can be limited with the PHP configuration directive mysqlnd_qc.query_trace_bt_depth. The default depth is 3.

Example #2 Setting the backtrace depth with the mysqlnd_qc.query_trace_bt_depth ini setting

mysqlnd_qc.enable_qc=1
mysqlnd_qc.collect_query_trace=1
<?php
/* connect to MySQL */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");

/* dummy queries to fill the query trace */
for ($i = 0; $i < 3; $i++) {
    $res = $mysqli->query("SELECT id FROM test WHERE id = " . $mysqli->real_escape_string($i));
    $res->free();
}

$trace = mysqlnd_qc_get_query_trace_log();
$summary = array();
foreach ($trace as $entry) {
    if (!isset($summary[$entry['query']])) {
        $summary[$entry['query']] = array(
            "executions" => 1,
            "time"       => $entry['run_time'] + $entry['store_time'],
        );
    } else {
        $summary[$entry['query']]['executions']++;
        $summary[$entry['query']]['time'] += $entry['run_time'] + $entry['store_time'];
    }
}

foreach ($summary as $query => $details) {
    printf("%45s: %5dms (%dx)\n",
    $query, $details['time'], $details['executions']);
}
?>

The above examples will output something similar to:

                    DROP TABLE IF EXISTS test:     0ms (1x)
                    CREATE TABLE test(id INT):     0ms (1x)
    INSERT INTO test(id) VALUES (1), (2), (3):     0ms (1x)
             SELECT id FROM test WHERE id = 0:    25ms (1x)
             SELECT id FROM test WHERE id = 1:    10ms (1x)
             SELECT id FROM test WHERE id = 2:     9ms (1x)


Measuring cache efficiency

PECL/mysqlnd_qc offers three ways to measure the cache efficiency. The function mysqlnd_qc_get_normalized_query_trace_log() returns statistics aggregated by the normalized query string, mysqlnd_qc_get_cache_info() gives storage handler specific information which includes a list of all cached items, depending on the storage handler. Additionally, the core of PECL/mysqlnd_qc collects high-level summary statistics aggregated per PHP process. The high-level statistics are returned by mysqlnd_qc_get_core_stats().

The functions mysqlnd_qc_get_normalized_query_trace_log() and mysqlnd_qc_get_core_stats() will not collect data unless data collection has been enabled through their corresponding PHP configuration directives. Data collection is disabled by default for performance considerations. It is configurable with the mysqlnd_qc.time_statistics option, which determines if timing information should be collected. Collection of time statistics is enabled by default but only performed if data collection as such has been enabled. Recording time statistics causes extra system calls. In most cases, the benefit of the monitoring outweighs any potential performance penalty of the additional system calls.

Example #1 Collecting statistics data with the mysqlnd_qc.time_statistics ini setting

mysqlnd_qc.enable_qc=1
mysqlnd_qc.collect_statistics=1
<?php
/* connect to MySQL */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");

/* dummy queries */
for ($i = 1; $i <= 4; $i++) {
    $query = sprintf("/*%s*/SELECT id FROM test WHERE id = %d", MYSQLND_QC_ENABLE_SWITCH, $i % 2);
    $res   = $mysqli->query($query);

    $res->free();
}

var_dump(mysqlnd_qc_get_core_stats());
?>

The above examples will output something similar to:

array(26) {
  ["cache_hit"]=>
  string(1) "2"
  ["cache_miss"]=>
  string(1) "2"
  ["cache_put"]=>
  string(1) "2"
  ["query_should_cache"]=>
  string(1) "4"
  ["query_should_not_cache"]=>
  string(1) "3"
  ["query_not_cached"]=>
  string(1) "3"
  ["query_could_cache"]=>
  string(1) "4"
  ["query_found_in_cache"]=>
  string(1) "2"
  ["query_uncached_other"]=>
  string(1) "0"
  ["query_uncached_no_table"]=>
  string(1) "0"
  ["query_uncached_no_result"]=>
  string(1) "0"
  ["query_uncached_use_result"]=>
  string(1) "0"
  ["query_aggr_run_time_cache_hit"]=>
  string(2) "28"
  ["query_aggr_run_time_cache_put"]=>
  string(3) "900"
  ["query_aggr_run_time_total"]=>
  string(3) "928"
  ["query_aggr_store_time_cache_hit"]=>
  string(2) "14"
  ["query_aggr_store_time_cache_put"]=>
  string(2) "40"
  ["query_aggr_store_time_total"]=>
  string(2) "54"
  ["receive_bytes_recorded"]=>
  string(3) "136"
  ["receive_bytes_replayed"]=>
  string(3) "136"
  ["send_bytes_recorded"]=>
  string(2) "84"
  ["send_bytes_replayed"]=>
  string(2) "84"
  ["slam_stale_refresh"]=>
  string(1) "0"
  ["slam_stale_hit"]=>
  string(1) "0"
  ["request_counter"]=>
  int(1)
  ["process_hash"]=>
  int(1929695233)
}

For a quick overview, call mysqlnd_qc_get_core_stats(). It delivers cache usage, cache timing and traffic related statistics. Values are aggregated on a per process basis for all queries issued by any PHP MySQL API call.

Some storage handler, such as the default handler, can report cache entries, statistics related to the entries and meta data for the underlying query through the mysqlnd_qc_get_cache_info() function. Please note, that the information returned depends on the storage handler. Values are aggregated on a per process basis.

Example #2 Example mysqlnd_qc_get_cache_info() usage

mysqlnd_qc.enable_qc=1
<?php
/* connect to MySQL */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");

/* dummy queries to fill the query trace */
for ($i = 1; $i <= 4; $i++) {
    $query = sprintf("/*%s*/SELECT id FROM test WHERE id = %d", MYSQLND_QC_ENABLE_SWITCH, $i % 2);
    $res   = $mysqli->query($query);

    $res->free();
}

var_dump(mysqlnd_qc_get_cache_info());
?>

The above examples will output something similar to:

array(4) {
  ["num_entries"]=>
  int(2)
  ["handler"]=>
  string(7) "default"
  ["handler_version"]=>
  string(5) "1.0.0"
  ["data"]=>
  array(2) {
    ["Localhost via UNIX socket
3306
root
test|/*qc=on*/SELECT id FROM test WHERE id = 1"]=>
    array(2) {
      ["statistics"]=>
      array(11) {
        ["rows"]=>
        int(1)
        ["stored_size"]=>
        int(71)
        ["cache_hits"]=>
        int(1)
        ["run_time"]=>
        int(391)
        ["store_time"]=>
        int(27)
        ["min_run_time"]=>
        int(16)
        ["max_run_time"]=>
        int(16)
        ["min_store_time"]=>
        int(8)
        ["max_store_time"]=>
        int(8)
        ["avg_run_time"]=>
        int(8)
        ["avg_store_time"]=>
        int(4)
      }
      ["metadata"]=>
      array(1) {
        [0]=>
        array(8) {
          ["name"]=>
          string(2) "id"
          ["orig_name"]=>
          string(2) "id"
          ["table"]=>
          string(4) "test"
          ["orig_table"]=>
          string(4) "test"
          ["db"]=>
          string(4) "test"
          ["max_length"]=>
          int(1)
          ["length"]=>
          int(11)
          ["type"]=>
          int(3)
        }
      }
    }
    ["Localhost via UNIX socket
3306
root
test|/*qc=on*/SELECT id FROM test WHERE id = 0"]=>
    array(2) {
      ["statistics"]=>
      array(11) {
        ["rows"]=>
        int(0)
        ["stored_size"]=>
        int(65)
        ["cache_hits"]=>
        int(1)
        ["run_time"]=>
        int(299)
        ["store_time"]=>
        int(13)
        ["min_run_time"]=>
        int(11)
        ["max_run_time"]=>
        int(11)
        ["min_store_time"]=>
        int(6)
        ["max_store_time"]=>
        int(6)
        ["avg_run_time"]=>
        int(5)
        ["avg_store_time"]=>
        int(3)
      }
      ["metadata"]=>
      array(1) {
        [0]=>
        array(8) {
          ["name"]=>
          string(2) "id"
          ["orig_name"]=>
          string(2) "id"
          ["table"]=>
          string(4) "test"
          ["orig_table"]=>
          string(4) "test"
          ["db"]=>
          string(4) "test"
          ["max_length"]=>
          int(0)
          ["length"]=>
          int(11)
          ["type"]=>
          int(3)
        }
      }
    }
  }
}

It is possible to further break down the granularity of statistics to the level of the normalized statement string. The normalized statement string is the statements string with all parameters replaced with question marks. For example, the two statements SELECT id FROM test WHERE id = 0 and SELECT id FROM test WHERE id = 1 are normalized into SELECT id FROM test WHERE id = ?. Their both statistics are aggregated into one entry for SELECT id FROM test WHERE id = ?.

Example #3 Example mysqlnd_qc_get_normalized_query_trace_log() usage

mysqlnd_qc.enable_qc=1
mysqlnd_qc.collect_normalized_query_trace=1
<?php
/* connect to MySQL */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");

/* dummy queries to fill the query trace */
for ($i = 1; $i <= 4; $i++) {
    $query = sprintf("/*%s*/SELECT id FROM test WHERE id = %d", MYSQLND_QC_ENABLE_SWITCH, $i % 2);
    $res   = $mysqli->query($query);

    $res->free();
}

var_dump(mysqlnd_qc_get_normalized_query_trace_log());
?>

The above examples will output something similar to:

array(4) {
  [0]=>
  array(9) {
    ["query"]=>
    string(25) "DROP TABLE IF EXISTS test"
    ["occurences"]=>
    int(0)
    ["eligible_for_caching"]=>
    bool(false)
    ["avg_run_time"]=>
    int(0)
    ["min_run_time"]=>
    int(0)
    ["max_run_time"]=>
    int(0)
    ["avg_store_time"]=>
    int(0)
    ["min_store_time"]=>
    int(0)
    ["max_store_time"]=>
    int(0)
  }
  [1]=>
  array(9) {
    ["query"]=>
    string(27) "CREATE TABLE test (id INT )"
    ["occurences"]=>
    int(0)
    ["eligible_for_caching"]=>
    bool(false)
    ["avg_run_time"]=>
    int(0)
    ["min_run_time"]=>
    int(0)
    ["max_run_time"]=>
    int(0)
    ["avg_store_time"]=>
    int(0)
    ["min_store_time"]=>
    int(0)
    ["max_store_time"]=>
    int(0)
  }
  [2]=>
  array(9) {
    ["query"]=>
    string(46) "INSERT INTO test (id ) VALUES (? ), (? ), (? )"
    ["occurences"]=>
    int(0)
    ["eligible_for_caching"]=>
    bool(false)
    ["avg_run_time"]=>
    int(0)
    ["min_run_time"]=>
    int(0)
    ["max_run_time"]=>
    int(0)
    ["avg_store_time"]=>
    int(0)
    ["min_store_time"]=>
    int(0)
    ["max_store_time"]=>
    int(0)
  }
  [3]=>
  array(9) {
    ["query"]=>
    string(31) "SELECT id FROM test WHERE id =?"
    ["occurences"]=>
    int(4)
    ["eligible_for_caching"]=>
    bool(true)
    ["avg_run_time"]=>
    int(179)
    ["min_run_time"]=>
    int(11)
    ["max_run_time"]=>
    int(393)
    ["avg_store_time"]=>
    int(12)
    ["min_store_time"]=>
    int(7)
    ["max_store_time"]=>
    int(25)
  }
}

The source distribution of PECL/mysqlnd_qc contains a directory web/ in which web based monitoring scripts can be found which give an example how to write a cache monitor. Please, follow the instructions given in the source.

Since PECL/mysqlnd_qc 1.1.0 it is possible to write statistics into a log file. Please, see mysqlnd_qc.collect_statistics_log_file.


Beyond TTL: user-defined storage

The query cache plugin supports the use of user-defined storage handler. User-defined storage handler can use arbitrarily complex invalidation algorithms and support arbitrary storage media.

All user-defined storage handlers have to provide a certain interface. The functions of the user-defined storage handler will be called by the core of the cache plugin. The necessary interface consists of seven public functions. Both procedural and object oriented user-defined storage handler must implement the same set of functions.

Example #1 Using a user-defined storage handler

<?php
/* Enable default caching of all statements */
ini_set("mysqlnd_qc.cache_by_default", 1);

/* Procedural user defined storage handler functions */

$__cache = array();

function get_hash($host_info, $port, $user, $db, $query) {
    global $__cache;
    printf("\t%s(%d)\n", __FUNCTION__, func_num_args());

    return md5(sprintf("%s%s%s%s%s", $host_info, $port, $user, $db, $query));
}

function find_query_in_cache($key) {
    global $__cache;
    printf("\t%s(%d)\n", __FUNCTION__, func_num_args());

    if (isset($__cache[$key])) {
        $tmp = $__cache[$key];
        if ($tmp["valid_until"] < time()) {
            unset($__cache[$key]);
            $ret = NULL;
        } else {
            $ret = $__cache[$key]["data"];
        }
    } else {
        $ret = NULL;
    }

    return $ret;
}

function return_to_cache($key) {
    /*
     Called on cache hit after cached data has been processed,
     may be used for reference counting
    */
    printf("\t%s(%d)\n", __FUNCTION__, func_num_args());
}

function add_query_to_cache_if_not_exists($key, $data, $ttl, $run_time, $store_time, $row_count) {
    global $__cache;
    printf("\t%s(%d)\n", __FUNCTION__, func_num_args());

    $__cache[$key] = array(
        "data"               => $data,
        "row_count"          => $row_count,
        "valid_until"        => time() + $ttl,
        "hits"               => 0,
        "run_time"           => $run_time,
        "store_time"         => $store_time,
        "cached_run_times"   => array(),
        "cached_store_times" => array(),
    );

    return TRUE;
}

function query_is_select($query) {
    printf("\t%s('%s'): ", __FUNCTION__, $query);

    $ret = FALSE;
    if (stristr($query, "SELECT") !== FALSE) {
        /* cache for 5 seconds */
        $ret = 5;
    }

    printf("%s\n", (FALSE === $ret) ? "FALSE" : $ret);
    return $ret;
}

function update_query_run_time_stats($key, $run_time, $store_time) {
    global $__cache;
    printf("\t%s(%d)\n", __FUNCTION__, func_num_args());

    if (isset($__cache[$key])) {
        $__cache[$key]['hits']++;
        $__cache[$key]["cached_run_times"][] = $run_time;
        $__cache[$key]["cached_store_times"][] = $store_time;
    }
}

function get_stats($key = NULL) {
    global $__cache;
    printf("\t%s(%d)\n", __FUNCTION__, func_num_args());

    if ($key && isset($__cache[$key])) {
        $stats = $__cache[$key];
    } else {
        $stats = array();
        foreach ($__cache as $key => $details) {
            $stats[$key] = array(
               'hits'              => $details['hits'],
               'bytes'             => strlen($details['data']),
               'uncached_run_time' => $details['run_time'],
               'cached_run_time'   => (count($details['cached_run_times']))
                                      ? array_sum($details['cached_run_times']) / count($details['cached_run_times'])
                                      : 0,
            );
        }
    }

    return $stats;
}

function clear_cache() {
    global $__cache;
    printf("\t%s(%d)\n", __FUNCTION__, func_num_args());

    $__cache = array();
    return TRUE;
}

/* Install procedural user-defined storage handler */
if (!mysqlnd_qc_set_user_handlers("get_hash", "find_query_in_cache",
    "return_to_cache", "add_query_to_cache_if_not_exists",
    "query_is_select", "update_query_run_time_stats", "get_stats", "clear_cache")) {

        printf("Failed to install user-defined storage handler\n");
}

/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2)");

printf("\nCache put/cache miss\n");

$res = $mysqli->query("SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();

/* Delete record to verify we get our data from the cache */
$mysqli->query("DELETE FROM test WHERE id = 1");

printf("\nCache hit\n");

$res = $mysqli->query("SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();

printf("\nDisplay cache statistics\n");
var_dump(mysqlnd_qc_get_cache_info());

printf("\nFlushing cache, cache put/cache miss");
var_dump(mysqlnd_qc_clear_cache());

$res = $mysqli->query("SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();
?>

The above examples will output something similar to:

        query_is_select('DROP TABLE IF EXISTS test'): FALSE
        query_is_select('CREATE TABLE test(id INT)'): FALSE
        query_is_select('INSERT INTO test(id) VALUES (1), (2)'): FALSE

Cache put/cache miss
        query_is_select('SELECT id FROM test WHERE id = 1'): 5
        get_hash(5)
        find_query_in_cache(1)
        add_query_to_cache_if_not_exists(6)
array(1) {
  ["id"]=>
  string(1) "1"
}
        query_is_select('DELETE FROM test WHERE id = 1'): FALSE

Cache hit
        query_is_select('SELECT id FROM test WHERE id = 1'): 5
        get_hash(5)
        find_query_in_cache(1)
        return_to_cache(1)
        update_query_run_time_stats(3)
array(1) {
  ["id"]=>
  string(1) "1"
}

Display cache statistics
        get_stats(0)
array(4) {
  ["num_entries"]=>
  int(1)
  ["handler"]=>
  string(4) "user"
  ["handler_version"]=>
  string(5) "1.0.0"
  ["data"]=>
  array(1) {
    ["18683c177dc89bb352b29965d112fdaa"]=>
    array(4) {
      ["hits"]=>
      int(1)
      ["bytes"]=>
      int(71)
      ["uncached_run_time"]=>
      int(398)
      ["cached_run_time"]=>
      int(4)
    }
  }
}

Flushing cache, cache put/cache miss    clear_cache(0)
bool(true)
        query_is_select('SELECT id FROM test WHERE id = 1'): 5
        get_hash(5)
        find_query_in_cache(1)
        add_query_to_cache_if_not_exists(6)
NULL


  • « Beyond TTL: user-defined storage
  • Requirements »
  • PHP Manual
  • mysqlnd_qc
  • Installing/Configuring

Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration


Requirements

PHP 5.3.3 or a newer version of PHP.

PECL/mysqlnd_qc is a mysqlnd plugin. It plugs into the mysqlnd library. To use you this plugin with a PHP MySQL extension, the extension (mysqli, mysql, or PDO_MYSQL) must enable the mysqlnd library.

For using the APC storage handler with PECL/mysqlnd_qc 1.0 APC 3.1.3p1-beta or newer. PECL/mysqlnd_qc 1.2 has been tested with APC 3.1.13-beta. The APC storage handler cannot be used with a shared build. You cannot use the PHP configuration directive extension to load the APC and PECL/mysqlnd_qc extensions if PECL/mysqlnd_qc will use APC as a storage handler. For using the APC storage handler, you have to statically compile PHP with APC and PECL/mysqlnd_qc support into PHP.

For using MEMCACHE storage handler: Use libmemcache 0.38 or newer. PECL/mysqlnd_qc 1.2 has been tested with libmemcache 1.4.0.

For using sqlite storage handler: Use the sqlite3 extension that bundled with PHP.


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/mysqlnd_qc

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

mysqlnd_qc Configure Options
Name | Default | Changeable | Changelog
mysqlnd_qc.enable_qc | 1 | PHP_INI_SYSTEM |
mysqlnd_qc.ttl | 30 | PHP_INI_ALL |
mysqlnd_qc.cache_by_default | 0 | PHP_INI_ALL |
mysqlnd_qc.cache_no_table | 0 | PHP_INI_ALL |
mysqlnd_qc.use_request_time | 0 | PHP_INI_ALL |
mysqlnd_qc.time_statistics | 1 | PHP_INI_ALL |
mysqlnd_qc.collect_statistics | 0 | PHP_INI_ALL |
mysqlnd_qc.collect_statistics_log_file | /tmp/mysqlnd_qc.stats | PHP_INI_SYSTEM |
mysqlnd_qc.collect_query_trace | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.query_trace_bt_depth | 3 | PHP_INI_SYSTEM |
mysqlnd_qc.collect_normalized_query_trace | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.ignore_sql_comments | 1 | PHP_INI_ALL |
mysqlnd_qc.slam_defense | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.slam_defense_ttl | 30 | PHP_INI_SYSTEM |
mysqlnd_qc.std_data_copy | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.apc_prefix | qc_ | PHP_INI_ALL |
mysqlnd_qc.memc_server | 127.0.0.1 | PHP_INI_ALL |
mysqlnd_qc.memc_port | 11211 | PHP_INI_ALL |
mysqlnd_qc.sqlite_data_file | :memory: | PHP_INI_ALL |

Here's a short explanation of the configuration directives.

mysqlnd_qc.enable_qc integer

Enables or disables the plugin. If disabled the extension will not plug into mysqlnd to proxy internal mysqlnd C API calls.

mysqlnd_qc.ttl integer

Default Time-to-Live (TTL) for cache entries in seconds.

mysqlnd_qc.cache_by_default integer

Cache all queries regardless if they begin with the SQL hint that enables caching of a query or not. Storage handler cannot overrule the setting. It is evaluated by the core of the plugin.

mysqlnd_qc.cache_no_table integer

Whether to cache queries with no table name in any of columns meta data of their result set, for example, SELECT SLEEP(1), SELECT NOW(), SELECT SUBSTRING().

mysqlnd_qc.use_request_time integer

Use PHP global request time to avoid gettimeofday() system calls? If using APC storage handler it should be set to the value of apc.use_request_time , if not warnings will be generated.

mysqlnd_qc.time_statistics integer

Collect run time and store time statistics using gettimeofday() system call? Data will be collected only if you also set mysqlnd_qc.collect_statistics = 1,

mysqlnd_qc.collect_statistics integer

Collect statistics for mysqlnd_qc_get_core_stats()? Does not influence storage handler statistics! Handler statistics can be an integral part of the handler internal storage format. Therefore, collection of some handler statistics cannot be disabled.

mysqlnd_qc.collect_statistics-log-file integer

If mysqlnd_qc.collect_statistics and mysqlnd_qc.collect_statistics_log_file are set, the plugin will dump statistics into the specified log file at every 10th web request during PHP request shutdown. The log file needs to be writable by the web server user.

Since 1.1.0.

mysqlnd_qc.collect_query_trace integer

Collect query back traces?

mysqlnd_qc.query_trace_bt_depth integer

Maximum depth/level of a query code backtrace.

mysqlnd_qc.ignore_sql_comments integer

Whether to remove SQL comments from a query string before hashing it to generate a cache key. Disable if you do not want two statemts such as SELECT /*my_source_ip=123*/ id FROM test and SELECT /*my_source_ip=456*/ id FROM test to refer to the same cache entry.

Since 1.1.0.

mysqlnd_qc.slam_defense integer

Activates handler based slam defense (cache stampeding protection) if available. Supported by Default and APC storage handler

mysqlnd_qc.slam_defense_ttl integer

TTL for stale cache entries which are served while another client updates the entries. Supported by APC storage handler.

mysqlnd_qc.collect_normalized_query_trace integer

Collect aggregated normalized query traces? The setting has no effect by default. You compile the extension using the define NORM_QUERY_TRACE_LOG to make use of the setting.

mysqlnd_qc.std_data_copy integer

Default storage handler: copy cached wire data? EXPERIMENTAL – use default setting!

mysqlnd_qc.apc_prefix string

The APC storage handler stores data in the APC user cache. The setting sets a prefix to be used for cache entries.

mysqlnd_qc.memc_server string

MEMCACHE storage handler: memcache server host.

mysqlnd_qc.memc_port integer

MEMCACHE storage handler: memcached server port.

mysqlnd_qc.sqlite_data_file string

sqlite storage handler: data file. Any setting but :memory: may be of little practical value.


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.

SQL hint related

Example #1 Using SQL hint constants

The query cache is controlled by SQL hints. SQL hints are used to enable and disable caching. SQL hints can be used to set the TTL of a query.

The SQL hints recognized by the query cache can be manually changed at compile time. This makes it possible to use mysqlnd_qc in environments in which the default SQL hints are already taken and interpreted by other systems. Therefore it is recommended to use the SQL hint string constants instead of manually adding the default SQL hints to the query string.

<?php
/* Use constants for maximum portability */
$query = "/*" . MYSQLND_QC_ENABLE_SWITCH . "*/SELECT id FROM test";

/* Valid but less portable: default TTL */
$query = "/*qc=on*/SELECT id FROM test";

/* Valid but less portable: per statement TTL */
$query = "/*qc=on*//*qc_ttl=5*/SELECT id FROM test";

printf("MYSQLND_QC_ENABLE_SWITCH: %s\n", MYSQLND_QC_ENABLE_SWITCH);
printf("MYSQLND_QC_DISABLE_SWITCH: %s\n", MYSQLND_QC_DISABLE_SWITCH);
printf("MYSQLND_QC_TTL_SWITCH: %s\n", MYSQLND_QC_TTL_SWITCH);
?>

The above examples will output:

MYSQLND_QC_ENABLE_SWITCH: qc=on
MYSQLND_QC_DISABLE_SWITCH: qc=off
MYSQLND_QC_TTL_SWITCH: qc_ttl=

MYSQLND_QC_ENABLE_SWITCH (string)
SQL hint used to enable caching of a query.
MYSQLND_QC_DISABLE_SWITCH (string)
SQL hint used to disable caching of a query if mysqlnd_qc.cache_by_default = 1.
MYSQLND_QC_TTL_SWITCH (string)
SQL hint used to set the TTL of a result set.
MYSQLND_QC_SERVER_ID_SWITCH (string)
This SQL hint should not be used in general. It is needed by PECL/mysqlnd_ms to group cache entries for one statement but originating from different physical connections. If the hint is used connection settings such as user, hostname and charset are not considered for generating a cache key of a query. Instead the given value and the query string are used as input to the hashing function that generates the key. PECL/mysqlnd_ms may, if instructed, cache results from MySQL Replication slaves. Because it can hold many connections to the slave the cache key shall not be formed from the user, hostname or other settings that may vary for the various slave connections. Instead, PECL/mysqlnd_ms provides an identifier which refers to the group of slave connections that shall be enabled to share cache entries no matter which physical slave connection was to generate the cache entry. Use of this feature outside of PECL/mysqlnd_ms is not recommended.

mysqlnd_qc_set_cache_condition() related

Example #2 Example mysqlnd_qc_set_cache_condition() usage

The function mysqlnd_qc_set_cache_condition() allows setting conditions for automatic caching of statements which don't begin with the SQL hints necessary to manually enable caching.

<?php
/* Cache all accesses to tables with the name "new%" in schema/database "db_example" for 1 second */
if (!mysqlnd_qc_set_cache_condition(MYSQLND_QC_CONDITION_META_SCHEMA_PATTERN, "db_example.new%", 1)) {
  die("Failed to set cache condition!");
}

$mysqli = new mysqli("host", "user", "password", "db_example", "port");
/* cached although no SQL hint given  */
$mysqli->query("SELECT id, title FROM news");

$pdo_mysql = new PDO("mysql:host=host;dbname=db_example;port=port", "user", "password");
/* not cached: no SQL hint, no pattern match */
$pdo_mysql->query("SELECT id, title FROM latest_news");
/* cached: TTL 1 second, pattern match */
$pdo_mysql->query("SELECT id, title FROM news");
?>

MYSQLND_QC_CONDITION_META_SCHEMA_PATTERN (int)
Used as a parameter of mysqlnd_qc_set_cache_condition() to set conditions for schema based automatic caching.

Other

The plugin version number can be obtained using either MYSQLND_QC_VERSION, which is the string representation of the numerical version number, or MYSQLND_QC_VERSION_ID, which is an integer such as 10000. Developers can calculate the version number as follows.

Version (part) | Example
Major*10000 | 1*10000 = 10000
Minor*100 | 0*100 = 0
Patch | 0 = 0
MYSQLND_QC_VERSION_ID | 10000

MYSQLND_QC_VERSION (string)
Plugin version string, for example, 1.0.0-prototype.

MYSQLND_QC_VERSION_ID (int)
Plugin version number, for example, 10000.


mysqlnd_qc Functions

Table of Contents

  • mysqlnd_qc_clear_cache — Flush all cache contents
  • mysqlnd_qc_get_available_handlers — Returns a list of available storage handler
  • mysqlnd_qc_get_cache_info — Returns information on the current handler, the number of cache entries and cache entries, if available
  • mysqlnd_qc_get_core_stats — Statistics collected by the core of the query cache
  • mysqlnd_qc_get_normalized_query_trace_log — Returns a normalized query trace log for each query inspected by the query cache
  • mysqlnd_qc_get_query_trace_log — Returns a backtrace for each query inspected by the query cache
  • mysqlnd_qc_set_cache_condition — Set conditions for automatic caching
  • mysqlnd_qc_set_is_select — Installs a callback which decides whether a statement is cached
  • mysqlnd_qc_set_storage_handler — Change current storage handler
  • mysqlnd_qc_set_user_handlers — Sets the callback functions for a user-defined procedural storage handler


Flush all cache contents

  • « mysqlnd_qc Functions
  • mysqlnd_qc_get_available_handlers »
  • PHP Manual
  • mysqlnd_qc Functions
  • Flush all cache contents

mysqlnd_qc_clear_cache

(PECL mysqlnd_qc >= 1.0.0)

mysqlnd_qc_clear_cache — Flush all cache contents

Description

mysqlnd_qc_clear_cache ( void ) : bool

Flush all cache contents.

Flushing the cache is a storage handler responsibility. All built-in storage handler but the memcache storage handler support flushing the cache. The memcache storage handler cannot flush its cache contents.

User-defined storage handler may or may not support the operation.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

A return value of FALSE indicates that flushing all cache contents has failed or the operation is not supported by the active storage handler. Applications must not expect that calling the function will always flush the cache.


Returns a list of available storage handler

  • « mysqlnd_qc_clear_cache
  • mysqlnd_qc_get_cache_info »
  • PHP Manual
  • mysqlnd_qc Functions
  • Returns a list of available storage handler

mysqlnd_qc_get_available_handlers

(PECL mysqlnd_qc >= 1.0.0)

mysqlnd_qc_get_available_handlers — Returns a list of available storage handler

Description

mysqlnd_qc_get_available_handlers ( void ) : array

Which storage are available depends on the compile time configuration of the query cache plugin. The default storage handler is always available. All other storage handler must be enabled explicitly when building the extension.

Parameters

This function has no parameters.

Return Values

Returns an array of available built-in storage handler. For each storage handler the version number and version string is given.

Examples

Example #1 mysqlnd_qc_get_available_handlers() example

<?php
var_dump(mysqlnd_qc_get_available_handlers());
?>

The above examples will output:

array(5) {
  ["default"]=>
  array(2) {
    ["version"]=>
    string(5) "1.0.0"
    ["version_number"]=>
    int(100000)
  }
  ["user"]=>
  array(2) {
    ["version"]=>
    string(5) "1.0.0"
    ["version_number"]=>
    int(100000)
  }
  ["APC"]=>
  array(2) {
    ["version"]=>
    string(5) "1.0.0"
    ["version_number"]=>
    int(100000)
  }
  ["MEMCACHE"]=>
  array(2) {
    ["version"]=>
    string(5) "1.0.0"
    ["version_number"]=>
    int(100000)
  }
  ["sqlite"]=>
  array(2) {
    ["version"]=>
    string(5) "1.0.0"
    ["version_number"]=>
    int(100000)
  }
}

See Also

  • Installation
  • mysqlnd_qc_set_storage_handler() - Change current storage handler


Returns information on the current handler, the number of cache entries and cache entries, if available

  • « mysqlnd_qc_get_available_handlers
  • mysqlnd_qc_get_core_stats »
  • PHP Manual
  • mysqlnd_qc Functions
  • Returns information on the current handler, the number of cache entries and cache entries, if available

mysqlnd_qc_get_cache_info

(PECL mysqlnd_qc >= 1.0.0)

mysqlnd_qc_get_cache_info — Returns information on the current handler, the number of cache entries and cache entries, if available

Description

mysqlnd_qc_get_cache_info ( void ) : array

Parameters

This function has no parameters.

Return Values

Returns information on the current handler, the number of cache entries and cache entries, if available. If and what data will be returned for the cache entries is subject to the active storage handler. Storage handler are free to return any data. Storage handler are recommended to return at least the data provided by the default handler, if technically possible.

The scope of the information is the PHP process. Depending on the PHP deployment model a process may serve one or more web requests.

Values are aggregated for all cache activities on a per storage handler basis. It is not possible to tell how much queries originating from mysqli, PDO_MySQL or mysql.API calls have contributed to the aggregated data values. Use mysqlnd_qc_get_core_stats() to get timing data aggregated for all storage handlers.

Array of cache information

handler string

The active storage handler.

All storage handler. Since 1.0.0.

handler_version string

The version of the active storage handler.

All storage handler. Since 1.0.0.

num_entries int

The number of cache entries. The value depends on the storage handler in use.

The default, APC and SQLite storage handler provide the actual number of cache entries.

The MEMCACHE storage handler always returns 0. MEMCACHE does not support counting the number of cache entries.

If a user defined handler is used, the number of entries of the data property is reported.

Since 1.0.0.

data array

The version of the active storage handler.

Additional storage handler dependent data on the cache entries. Storage handler are requested to provide similar and comparable information. A user defined storage handler is free to return any data.

Since 1.0.0.

The following information is provided by the default storage handler for the data property.

The data property holds a hash. The hash is indexed by the internal cache entry identifier of the storage handler. The cache entry identifier is human-readable and contains the query string leading to the cache entry. Please, see also the example below. The following data is given for every cache entry.

statistics array

Statistics of the cache entry.

Since 1.0.0.

Property | Description | Version
rows | Number of rows of the cached result set. | Since 1.0.0.
stored_size | The size of the cached result set in bytes. This is the size of the payload. The value is not suited for calculating the total memory consumption of all cache entries including the administrative overhead of the cache entries. | Since 1.0.0.
cache_hits | How often the cached entry has been returned. | Since 1.0.0.
run_time | Run time of the statement to which the cache entry belongs. This is the run time of the uncached statement. It is the time between sending the statement to MySQL receiving a reply from MySQL. Run time saved by using the query cache plugin can be calculated like this: cache_hits * ((run_time - avg_run_time) + (store_time - avg_store_time)). | Since 1.0.0.
store_time | Store time of the statements result set to which the cache entry belongs. This is the time it took to fetch and store the results of the uncached statement. | Since 1.0.0.
min_run_time | Minimum run time of the cached statement. How long it took to find the statement in the cache. | Since 1.0.0.
min_store_time | Minimum store time of the cached statement. The time taken for fetching the cached result set from the storage medium and decoding | Since 1.0.0.
avg_run_time | Average run time of the cached statement. | Since 1.0.0.
avg_store_time | Average store time of the cached statement. | Since 1.0.0.
max_run_time | Average run time of the cached statement. | Since 1.0.0.
max_store_time | Average store time of the cached statement. | Since 1.0.0.
valid_until | Timestamp when the cache entry expires. | Since 1.1.0.
metadata array

Metadata of the cache entry. This is the metadata provided by MySQL together with the result set of the statement in question. Different versions of the MySQL server may return different metadata. Unlike with some of the PHP MySQL extensions no attempt is made to hide MySQL server version dependencies and version details from the caller. Please, refer to the MySQL C API documentation that belongs to the MySQL server in use for further details.

The metadata list contains one entry for every column.

Since 1.0.0.

Property | Description | Version
name | The field name. Depending on the MySQL version this may be the fields alias name. | Since 1.0.0.
org_name | The field name. | Since 1.0.0.
table | The table name. If an alias name was used for the table, this usually holds the alias name. | Since 1.0.0.
org_table | The table name. | Since 1.0.0.
db | The database/schema name. | Since 1.0.0.
max_length | The maximum width of the field. Details may vary by MySQL server version. | Since 1.0.0.
length | The width of the field. Details may vary by MySQL server version. | Since 1.0.0.
type | The data type of the field. Details may vary by the MySQL server in use. This is the MySQL C API type constants value. It is recommended to use type constants provided by the mysqli extension to test for its meaning. You should not test for certain type values by comparing with certain numbers. | Since 1.0.0.

The APC storage handler returns the same information for the data property but no metadata. The metadata of a cache entry is set to NULL.

The MEMCACHE storage handler does not fill the data property. Statistics are not available on a per cache entry basis with the MEMCACHE storage handler.

A user defined storage handler is free to provide any data.

Examples

Example #1 mysqlnd_qc_get_cache_info() example

The example shows the output from the built-in default storage handler. Other storage handler may report different data.

<?php
/* Populate the cache, e.g. using mysqli */
$mysqli = new mysqli("host", "user", "password", "schema");
$mysqli->query("/*" . MYSQLND_QC_ENABLE_SWITCH . "*/SELECT id FROM test");

/* Display cache information */
var_dump(mysqlnd_qc_get_cache_info());
?>

The above examples will output:

array(4) {
 ["num_entries"]=>
 int(1)
 ["handler"]=>
 string(7) "default"
 ["handler_version"]=>
 string(5) "1.0.0"
 ["data"]=>
 array(1) {
   ["Localhost via UNIX socket 3306 user schema|/*qc=on*/SELECT id FROM test"]=>
   array(2) {
     ["statistics"]=>
     array(11) {
       ["rows"]=>
       int(6)
       ["stored_size"]=>
       int(101)
       ["cache_hits"]=>
       int(0)
       ["run_time"]=>
       int(471)
       ["store_time"]=>
       int(27)
       ["min_run_time"]=>
       int(0)
       ["max_run_time"]=>
       int(0)
       ["min_store_time"]=>
       int(0)
       ["max_store_time"]=>
       int(0)
       ["avg_run_time"]=>
       int(0)
       ["avg_store_time"]=>
       int(0)
     }
     ["metadata"]=>
     array(1) {
       [0]=>
       array(8) {
         ["name"]=>
         string(2) "id"
         ["orig_name"]=>
         string(2) "id"
         ["table"]=>
         string(4) "test"
         ["orig_table"]=>
         string(4) "test"
         ["db"]=>
         string(4) "schema"
         ["max_length"]=>
         int(1)
         ["length"]=>
         int(11)
         ["type"]=>
         int(3)
       }
     }
   }
 }
}

See Also

  • mysqlnd_qc_get_core_stats() - Statistics collected by the core of the query cache


Statistics collected by the core of the query cache

  • « mysqlnd_qc_get_cache_info
  • mysqlnd_qc_get_normalized_query_trace_log »
  • PHP Manual
  • mysqlnd_qc Functions
  • Statistics collected by the core of the query cache

mysqlnd_qc_get_core_stats

(PECL mysqlnd_qc >= 1.0.0)

mysqlnd_qc_get_core_stats — Statistics collected by the core of the query cache

Description

mysqlnd_qc_get_core_stats ( void ) : array

Returns an array of statistics collected by the core of the cache plugin. The same data fields will be reported for any storage handler because the data is collected by the core.

The PHP configuration setting mysqlnd_qc.collect_statistics controls the collection of statistics. The collection of statistics is disabled by default for performance reasons. Disabling the collection of statistics will also disable the collection of time related statistics.

The PHP configuration setting mysqlnd_qc.collect_time_statistics controls the collection of time related statistics.

The scope of the core statistics is the PHP process. Depending on your deployment model a PHP process may handle one or multiple requests.

Statistics are aggregated for all cache entries and all storage handler. It is not possible to tell how much queries originating from mysqli, PDO_MySQL or mysql API calls have contributed to the aggregated data values.

Parameters

This function has no parameters.

Return Values

Array of core statistics

Statistic | Description | Version
cache_hit | Statement is considered cacheable and cached data has been reused. Statement is considered cacheable and a cache miss happened but the statement got cached by someone else while we process it and thus we can fetch the result from the refreshed cache. | Since 1.0.0.
cache_miss Statement is considered cacheable...

  • ... and has been added to the cache

  • ... but the PHP configuration directive setting of mysqlnd_qc.cache_no_table = 1 has prevented caching.

  • ... but an unbuffered result set is requested.

  • ... but a buffered result set was empty.

Since 1.0.0.
cache_put | Statement is considered cacheable and has been added to the cache. Take care when calculating derived statistics. Storage handler with a storage life time beyond process scope may report cache_put = 0 together with cache_hit > 0, if another process has filled the cache. You may want to use num_entries from mysqlnd_qc_get_cache_info() if the handler supports it ( default, APC). | Since 1.0.0.
query_should_cache | Statement is considered cacheable based on query string analysis. The statement may or may not be added to the cache. See also cache_put. | Since 1.0.0.
query_should_not_cache | Statement is considered not cacheable based on query string analysis. | Since 1.0.0.
query_not_cached | Statement is considered not cacheable or it is considered cachable but the storage handler has not returned a hash key for it. | Since 1.0.0.
query_could_cache Statement is considered cacheable...

  • ... and statement has been run without errors

  • ... and meta data shows at least one column in the result set

The statement may or may not be in the cache already. It may or may not be added to the cache later on. 		Since 1.0.0.
query_found_in_cache | Statement is considered cacheable and we have found it in the cache but we have not replayed the cached data yet and we have not send the result set to the client yet. This is not considered a cache hit because the client might not fetch the result or the cached data may be faulty. | Since 1.0.0.
query_uncached_other | Statement is considered cacheable and it may or may not be in the cache already but either replaying cached data has failed, no result set is available or some other error has happened.
query_uncached_no_table | Statement has not been cached because the result set has at least one column which has no table name in its meta data. An example of such a query is SELECT SLEEP(1). To cache those statements you have to change default value of the PHP configuration directive mysqlnd_qc.cache_no_table and set mysqlnd_qc.cache_no_table = 1. Often, it is not desired to cache such statements. | Since 1.0.0.
query_uncached_use_result | Statement would have been cached if a buffered result set had been used. The situation is also considered as a cache miss and cache_miss will be incremented as well. | Since 1.0.0.
query_aggr_run_time_cache_hit | Aggregated run time (ms) of all cached queries. Cached queries are those which have incremented cache_hit. | Since 1.0.0.
query_aggr_run_time_cache_put | Aggregated run time (ms) of all uncached queries that have been put into the cache. See also cache_put. | Since 1.0.0.
query_aggr_run_time_total | Aggregated run time (ms) of all uncached and cached queries that have been inspected and executed by the query cache. | Since 1.0.0.
query_aggr_store_time_cache_hit | Aggregated store time (ms) of all cached queries. Cached queries are those which have incremented cache_hit. | Since 1.0.0.
query_aggr_store_time_cache_put | Aggregated store time ( ms) of all uncached queries that have been put into the cache. See also cache_put. | Since 1.0.0.
query_aggr_store_time_total | Aggregated store time (ms) of all uncached and cached queries that have been inspected and executed by the query cache. | Since 1.0.0.
receive_bytes_recorded | Recorded incoming network traffic ( bytes) send from MySQL to PHP. The traffic may or may not have been added to the cache. The traffic is the total for all queries regardless if cached or not. | Since 1.0.0.
receive_bytes_replayed | Network traffic replayed during cache. This is the total amount of incoming traffic saved because of the usage of the query cache plugin. | Since 1.0.0.
send_bytes_recorded | Recorded outgoing network traffic ( bytes) send from MySQL to PHP. The traffic may or may not have been added to the cache. The traffic is the total for all queries regardless if cached or not. | Since 1.0.0.
send_bytes_replayed | Network traffic replayed during cache. This is the total amount of outgoing traffic saved because of the usage of the query cache plugin. | Since 1.0.0.
slam_stale_refresh | Number of cache misses which triggered serving stale data until the client causing the cache miss has refreshed the cache entry. | Since 1.0.0.
slam_stale_hit | Number of cache hits while a stale cache entry gets refreshed. | Since 1.0.0.

Examples

Example #1 mysqlnd_qc_get_core_stats() example

<?php
/* Enable collection of statistics - default: disabled */
ini_set("mysqlnd_qc.collect_statistics", 1);

/* Enable collection of all timing related statistics -
default: enabled but overruled by mysqlnd_qc.collect_statistics = 0 */
ini_set("mysqlnd_qc.collect_time_statistics", 1);

/* Populate the cache, e.g. using mysqli */
$mysqli = new mysqli('host', 'user', 'password', 'schema');

/* Cache miss and cache put */
$mysqli->query("/*qc=on*/SELECT id FROM test");
/* Cache hit */
$mysqli->query("/*qc=on*/SELECT id FROM test");

/* Display core statistics */
var_dump(mysqlnd_qc_get_core_stats());
?>

The above examples will output:

array(26) {
  ["cache_hit"]=>
  string(1) "1"
  ["cache_miss"]=>
  string(1) "1"
  ["cache_put"]=>
  string(1) "1"
  ["query_should_cache"]=>
  string(1) "2"
  ["query_should_not_cache"]=>
  string(1) "0"
  ["query_not_cached"]=>
  string(1) "0"
  ["query_could_cache"]=>
  string(1) "2"
  ["query_found_in_cache"]=>
  string(1) "1"
  ["query_uncached_other"]=>
  string(1) "0"
  ["query_uncached_no_table"]=>
  string(1) "0"
  ["query_uncached_no_result"]=>
  string(1) "0"
  ["query_uncached_use_result"]=>
  string(1) "0"
  ["query_aggr_run_time_cache_hit"]=>
  string(1) "4"
  ["query_aggr_run_time_cache_put"]=>
  string(3) "395"
  ["query_aggr_run_time_total"]=>
  string(3) "399"
  ["query_aggr_store_time_cache_hit"]=>
  string(1) "2"
  ["query_aggr_store_time_cache_put"]=>
  string(1) "8"
  ["query_aggr_store_time_total"]=>
  string(2) "10"
  ["receive_bytes_recorded"]=>
  string(2) "65"
  ["receive_bytes_replayed"]=>
  string(2) "65"
  ["send_bytes_recorded"]=>
  string(2) "29"
  ["send_bytes_replayed"]=>
  string(2) "29"
  ["slam_stale_refresh"]=>
  string(1) "0"
  ["slam_stale_hit"]=>
  string(1) "0"
  ["request_counter"]=>
  int(1)
  ["process_hash"]=>
  int(3547549858)
}

See Also

  • Runtime configuration
  • mysqlnd_qc.collect_statistics
  • mysqlnd_qc.time_statistics
  • mysqlnd_qc_get_cache_info() - Returns information on the current handler, the number of cache entries and cache entries, if available


Returns a normalized query trace log for each query inspected by the query cache

  • « mysqlnd_qc_get_core_stats
  • mysqlnd_qc_get_query_trace_log »
  • PHP Manual
  • mysqlnd_qc Functions
  • Returns a normalized query trace log for each query inspected by the query cache

mysqlnd_qc_get_normalized_query_trace_log

(PECL mysqlnd_qc >= 1.0.0)

mysqlnd_qc_get_normalized_query_trace_log — Returns a normalized query trace log for each query inspected by the query cache

Description

mysqlnd_qc_get_normalized_query_trace_log ( void ) : array

Returns a normalized query trace log for each query inspected by the query cache. The collection of the trace log is disabled by default. To collect the trace log you have to set the PHP configuration directive mysqlnd_qc.collect_normalized_query_trace to 1

Entries in the trace log are grouped by the normalized query statement. The normalized query statement is the query statement with all statement parameter values being replaced with a question mark. For example, the two statements SELECT id FROM test WHERE id = 1 and SELECT id FROM test WHERE id = 2 are normalized as SELECT id FROM test WHERE id = ?. Whenever a statement is inspected by the query cache which matches the normalized statement pattern, its statistics are grouped by the normalized statement string.

Parameters

This function has no parameters.

Return Values

An array of query log. Every list entry contains the normalized query stringand further detail information.

Key | Description
query | Normalized statement string.
occurences | How many statements have matched the normalized statement string in addition to the one which has created the log entry. The value is zero if a statement has been normalized, its normalized representation has been added to the log but no further queries inspected by PECL/mysqlnd_qc have the same normalized statement string.
eligible_for_caching | Whether the statement could be cached. An statement eligible for caching has not necessarily been cached. It not possible to tell for sure if or how many cached statement have contributed to the aggregated normalized statement log entry. However, comparing the minimum and average run time one can make an educated guess.
avg_run_time | The average run time of all queries contributing to the query log entry. The run time is the time between sending the query statement to MySQL and receiving an answer from MySQL.
avg_store_time | The average store time of all queries contributing to the query log entry. The store time is the time needed to fetch a statements result set from the server to the client and, storing it on the client.
min_run_time | The minimum run time of all queries contributing to the query log entry.
min_store_time | The minimum store time of all queries contributing to the query log entry.
max_run_time | The maximum run time of all queries contributing to the query log entry.
max_store_time | The maximum store time of all queries contributing to the query log entry.

Examples

Example #1 mysqlnd_qc_get_normalized_query_trace_log() example

mysqlnd_qc.collect_normalized_query_trace=1
<?php
/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2)");

/* not cached */
$res = $mysqli->query("SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();

/* cache put */
$res = $mysqli->query("/*" . MYSQLND_QC_ENABLE_SWITCH . "*/" . "SELECT id FROM test WHERE id = 2");
var_dump($res->fetch_assoc());
$res->free();

/* cache hit */
$res = $mysqli->query("/*" . MYSQLND_QC_ENABLE_SWITCH . "*/" . "SELECT id FROM test WHERE id = 2");
var_dump($res->fetch_assoc());
$res->free();

var_dump(mysqlnd_qc_get_normalized_query_trace_log());
?>

The above examples will output:

array(1) {
  ["id"]=>
  string(1) "1"
}
array(1) {
  ["id"]=>
  string(1) "2"
}
array(1) {
  ["id"]=>
  string(1) "2"
}
array(4) {
  [0]=>
  array(9) {
    ["query"]=>
    string(25) "DROP TABLE IF EXISTS test"
    ["occurences"]=>
    int(0)
    ["eligible_for_caching"]=>
    bool(false)
    ["avg_run_time"]=>
    int(0)
    ["min_run_time"]=>
    int(0)
    ["max_run_time"]=>
    int(0)
    ["avg_store_time"]=>
    int(0)
    ["min_store_time"]=>
    int(0)
    ["max_store_time"]=>
    int(0)
  }
  [1]=>
  array(9) {
    ["query"]=>
    string(27) "CREATE TABLE test (id INT )"
    ["occurences"]=>
    int(0)
    ["eligible_for_caching"]=>
    bool(false)
    ["avg_run_time"]=>
    int(0)
    ["min_run_time"]=>
    int(0)
    ["max_run_time"]=>
    int(0)
    ["avg_store_time"]=>
    int(0)
    ["min_store_time"]=>
    int(0)
    ["max_store_time"]=>
    int(0)
  }
  [2]=>
  array(9) {
    ["query"]=>
    string(40) "INSERT INTO test (id ) VALUES (? ), (? )"
    ["occurences"]=>
    int(0)
    ["eligible_for_caching"]=>
    bool(false)
    ["avg_run_time"]=>
    int(0)
    ["min_run_time"]=>
    int(0)
    ["max_run_time"]=>
    int(0)
    ["avg_store_time"]=>
    int(0)
    ["min_store_time"]=>
    int(0)
    ["max_store_time"]=>
    int(0)
  }
  [3]=>
  array(9) {
    ["query"]=>
    string(31) "SELECT id FROM test WHERE id =?"
    ["occurences"]=>
    int(2)
    ["eligible_for_caching"]=>
    bool(true)
    ["avg_run_time"]=>
    int(159)
    ["min_run_time"]=>
    int(12)
    ["max_run_time"]=>
    int(307)
    ["avg_store_time"]=>
    int(10)
    ["min_store_time"]=>
    int(8)
    ["max_store_time"]=>
    int(13)
  }
}

See Also

  • Runtime configuration
  • mysqlnd_qc.collect_normalized_query_trace
  • mysqlnd_qc.time_statistics
  • mysqlnd_qc_get_query_trace_log() - Returns a backtrace for each query inspected by the query cache


Returns a backtrace for each query inspected by the query cache

  • « mysqlnd_qc_get_normalized_query_trace_log
  • mysqlnd_qc_set_cache_condition »
  • PHP Manual
  • mysqlnd_qc Functions
  • Returns a backtrace for each query inspected by the query cache

mysqlnd_qc_get_query_trace_log

(PECL mysqlnd_qc >= 1.0.0)

mysqlnd_qc_get_query_trace_log — Returns a backtrace for each query inspected by the query cache

Description

mysqlnd_qc_get_query_trace_log ( void ) : array

Returns a backtrace for each query inspected by the query cache. The collection of the backtrace is disabled by default. To collect the backtrace you have to set the PHP configuration directive mysqlnd_qc.collect_query_trace to 1

The maximum depth of the backtrace is limited to the depth set with the PHP configuration directive mysqlnd_qc.query_trace_bt_depth.

Parameters

This function has no parameters.

Return Values

An array of query backtrace. Every list entry contains the query string, a backtrace and further detail information.

Key | Description
query | Query string.
origin | Code backtrace.
run_time | Query run time in milliseconds. The collection of all times and the necessary gettimeofday system calls can be disabled by setting the PHP configuration directive mysqlnd_qc.time_statistics to 0
store_time | Query result set store time in milliseconds. The collection of all times and the necessary gettimeofday system calls can be disabled by setting the PHP configuration directive mysqlnd_qc.time_statistics to 0
eligible_for_caching | TRUE if query is cacheable otherwise FALSE.
no_table | TRUE if the query has generated a result set and at least one column from the result set has no table name set in its metadata. This is usually the case with queries which one probably do not want to cache such as SELECT SLEEP(1). By default any such query will not be added to the cache. See also PHP configuration directive mysqlnd_qc.cache_no_table.
was_added | TRUE if the query result has been put into the cache, otherwise FALSE.
was_already_in_cache | TRUE if the query result would have been added to the cache if it was not already in the cache (cache hit). Otherwise FALSE.

Examples

Example #1 mysqlnd_qc_get_query_trace_log() example

mysqlnd_qc.collect_query_trace=1
<?php
/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema", "port", "socket");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2)");

/* not cached */
$res = $mysqli->query("SELECT id FROM test WHERE id = 1");
var_dump($res->fetch_assoc());
$res->free();

/* cache put */
$res = $mysqli->query("/*" . MYSQLND_QC_ENABLE_SWITCH . "*/" . "SELECT id FROM test WHERE id = 2");
var_dump($res->fetch_assoc());
$res->free();

/* cache hit */
$res = $mysqli->query("/*" . MYSQLND_QC_ENABLE_SWITCH . "*/" . "SELECT id FROM test WHERE id = 2");
var_dump($res->fetch_assoc());
$res->free();

var_dump(mysqlnd_qc_get_query_trace_log());
?>

The above examples will output:

array(1) {
  ["id"]=>
  string(1) "1"
}
array(1) {
  ["id"]=>
  string(1) "2"
}
array(1) {
  ["id"]=>
  string(1) "2"
}
array(6) {
  [0]=>
  array(8) {
    ["query"]=>
    string(25) "DROP TABLE IF EXISTS test"
    ["origin"]=>
    string(102) "#0 qc.php(4): mysqli->query('DROP TABLE IF E...')
#1 {main}"
    ["run_time"]=>
    int(0)
    ["store_time"]=>
    int(0)
    ["eligible_for_caching"]=>
    bool(false)
    ["no_table"]=>
    bool(false)
    ["was_added"]=>
    bool(false)
    ["was_already_in_cache"]=>
    bool(false)
  }
  [1]=>
  array(8) {
    ["query"]=>
    string(25) "CREATE TABLE test(id INT)"
    ["origin"]=>
    string(102) "#0 qc.php(5): mysqli->query('CREATE TABLE te...')
#1 {main}"
    ["run_time"]=>
    int(0)
    ["store_time"]=>
    int(0)
    ["eligible_for_caching"]=>
    bool(false)
    ["no_table"]=>
    bool(false)
    ["was_added"]=>
    bool(false)
    ["was_already_in_cache"]=>
    bool(false)
  }
  [2]=>
  array(8) {
    ["query"]=>
    string(36) "INSERT INTO test(id) VALUES (1), (2)"
    ["origin"]=>
    string(102) "#0 qc.php(6): mysqli->query('INSERT INTO tes...')
#1 {main}"
    ["run_time"]=>
    int(0)
    ["store_time"]=>
    int(0)
    ["eligible_for_caching"]=>
    bool(false)
    ["no_table"]=>
    bool(false)
    ["was_added"]=>
    bool(false)
    ["was_already_in_cache"]=>
    bool(false)
  }
  [3]=>
  array(8) {
    ["query"]=>
    string(32) "SELECT id FROM test WHERE id = 1"
    ["origin"]=>
    string(102) "#0 qc.php(9): mysqli->query('SELECT id FROM ...')
#1 {main}"
    ["run_time"]=>
    int(0)
    ["store_time"]=>
    int(25)
    ["eligible_for_caching"]=>
    bool(false)
    ["no_table"]=>
    bool(false)
    ["was_added"]=>
    bool(false)
    ["was_already_in_cache"]=>
    bool(false)
  }
  [4]=>
  array(8) {
    ["query"]=>
    string(41) "/*qc=on*/SELECT id FROM test WHERE id = 2"
    ["origin"]=>
    string(103) "#0 qc.php(14): mysqli->query('/*qc=on*/SELECT...')
#1 {main}"
    ["run_time"]=>
    int(311)
    ["store_time"]=>
    int(13)
    ["eligible_for_caching"]=>
    bool(true)
    ["no_table"]=>
    bool(false)
    ["was_added"]=>
    bool(true)
    ["was_already_in_cache"]=>
    bool(false)
  }
  [5]=>
  array(8) {
    ["query"]=>
    string(41) "/*qc=on*/SELECT id FROM test WHERE id = 2"
    ["origin"]=>
    string(103) "#0 qc.php(19): mysqli->query('/*qc=on*/SELECT...')
#1 {main}"
    ["run_time"]=>
    int(13)
    ["store_time"]=>
    int(8)
    ["eligible_for_caching"]=>
    bool(true)
    ["no_table"]=>
    bool(false)
    ["was_added"]=>
    bool(false)
    ["was_already_in_cache"]=>
    bool(true)
  }
}

See Also

  • Runtime configuration
  • mysqlnd_qc.collect_query_trace
  • mysqlnd_qc.query_trace_bt_depth
  • mysqlnd_qc.time_statistics
  • mysqlnd_qc.cache_no_table
  • mysqlnd_qc_get_normalized_query_trace_log() - Returns a normalized query trace log for each query inspected by the query cache


Set conditions for automatic caching

  • « mysqlnd_qc_get_query_trace_log
  • mysqlnd_qc_set_is_select »
  • PHP Manual
  • mysqlnd_qc Functions
  • Set conditions for automatic caching

mysqlnd_qc_set_cache_condition

(PECL mysqlnd_qc >= 1.1.0)

mysqlnd_qc_set_cache_condition — Set conditions for automatic caching

Description

mysqlnd_qc_set_cache_condition ( int $condition_type , mixed $condition , mixed $condition_option ) : bool

Sets a condition for automatic caching of statements which do not contain the necessary SQL hints to enable caching of them.

Parameters

condition_type

Type of the condition. The only allowed value is MYSQLND_QC_CONDITION_META_SCHEMA_PATTERN.

condition

Parameter for the condition set with condition_type. Parameter type and structure depend on condition_type

If condition_type equals MYSQLND_QC_CONDITION_META_SCHEMA_PATTERN condition must be a string. The string sets a pattern. Statements are cached if table and database meta data entry of their result sets match the pattern. The pattern is checked for a match with the db and org_table meta data entries provided by the underlying MySQL client server library. Please, check the MySQL Reference manual for details about the two entries. The db and org_table values are concatenated with a dot (.) before matched against condition. Pattern matching supports the wildcards % and _. The wildcard % will match one or many arbitrary characters. _ will match one arbitrary character. The escape symbol is backslash.

condition_option

Option for condition. Type and structure depend on condition_type.

If condition_type equals MYSQLND_QC_CONDITION_META_SCHEMA_PATTERN condition_options is the TTL to be used.

Examples

Example #1 mysqlnd_qc_set_cache_condition() example

<?php
/* Cache all accesses to tables with the name "new%" in schema/database "db_example" for 1 second */
if (!mysqlnd_qc_set_cache_condition(MYSQLND_QC_CONDITION_META_SCHEMA_PATTERN, "db_example.new%", 1)) {
  die("Failed to set cache condition!");
}

$mysqli = new mysqli("host", "user", "password", "db_example", "port");
/* cached although no SQL hint given  */
$mysqli->query("SELECT id, title FROM news");

$pdo_mysql = new PDO("mysql:host=host;dbname=db_example;port=port", "user", "password");
/* not cached: no SQL hint, no pattern match */
$pdo_mysql->query("SELECT id, title FROM latest_news");
/* cached: TTL 1 second, pattern match */
$pdo_mysql->query("SELECT id, title FROM news");
?>

Return Values

Returns TRUE on success or FALSE on FAILURE.

See Also

  • Quickstart: pattern based caching


Installs a callback which decides whether a statement is cached

  • « mysqlnd_qc_set_cache_condition
  • mysqlnd_qc_set_storage_handler »
  • PHP Manual
  • mysqlnd_qc Functions
  • Installs a callback which decides whether a statement is cached

mysqlnd_qc_set_is_select

(PECL mysqlnd_qc >= 1.0.0)

mysqlnd_qc_set_is_select — Installs a callback which decides whether a statement is cached

Description

mysqlnd_qc_set_is_select ( string $callback ) : mixed

Installs a callback which decides whether a statement is cached.

There are several ways of hinting PELC/mysqlnd_qc to cache a query. By default, PECL/mysqlnd_qc attempts to cache a if caching of all statements is enabled or the query string begins with a certain SQL hint. The plugin internally calls a function named is_select() to find out. This internal function can be replaced with a user-defined callback. Then, the user-defined callback is responsible to decide whether the plugin attempts to cache a statement. Because the internal function is replaced with the callback, the callback gains full control. The callback is free to ignore the configuration setting mysqlnd_qc.cache_by_default and SQL hints.

The callback is invoked for every statement inspected by the plugin. It is given the statements string as a parameter. The callback returns FALSE if the statement shall not be cached. It returns TRUE to make the plugin attempt to cache the statements result set, if any. A so-created cache entry is given the default TTL set with the PHP configuration directive mysqlnd_qc.ttl. If a different TTL shall be used, the callback returns a numeric value to be used as the TTL.

The internal is_select function is part of the internal cache storage handler interface. Thus, a user-defined storage handler offers the same capabilities.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mysqlnd_qc_set_is_select() example

<?php
/* callback which decides if query is cached */
function is_select($query) {
  static $patterns = array(
   /* true - use default from mysqlnd_qc.ttl */
   "@SELECT\s+.*\s+FROM\s+test@ismU" => true,
   /* 3 - use TTL = 3 seconds */
   "@SELECT\s+.*\s+FROM\s+news@ismU" => 3
  );
  /* check if query does match pattern */
  foreach ($patterns as $pattern => $ttl) {
    if (preg_match($pattern, $query)) {
      printf("is_select(%45s): cache\n", $query);
      return $ttl;
    }
  }
  printf("is_select(%45s): do not cache\n", $query);
  return false;
}
mysqlnd_qc_set_is_select("is_select");

/* Connect, create and populate test table */
$mysqli = new mysqli("host", "user", "password", "schema");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");

/* cache put */
$mysqli->query("SELECT id FROM test WHERE id = 1");
/* cache hit */
$mysqli->query("SELECT id FROM test WHERE id = 1");
/* cache put */
$mysqli->query("SELECT * FROM test");
?>

The above examples will output:

is_select(                    DROP TABLE IF EXISTS test): do not cache
is_select(                    CREATE TABLE test(id INT)): do not cache
is_select(    INSERT INTO test(id) VALUES (1), (2), (3)): do not cache
is_select(             SELECT id FROM test WHERE id = 1): cache
is_select(             SELECT id FROM test WHERE id = 1): cache
is_select(                           SELECT * FROM test): cache

See Also

  • Runtime configuration
  • mysqlnd_qc.ttl
  • mysqlnd_qc.cache_by_default
  • mysqlnd_qc_set_user_handlers() - Sets the callback functions for a user-defined procedural storage handler


Change current storage handler

  • « mysqlnd_qc_set_is_select
  • mysqlnd_qc_set_user_handlers »
  • PHP Manual
  • mysqlnd_qc Functions
  • Change current storage handler

mysqlnd_qc_set_storage_handler

(PECL mysqlnd_qc >= 1.0.0)

mysqlnd_qc_set_storage_handler — Change current storage handler

Description

mysqlnd_qc_set_storage_handler ( string $handler ) : bool

Sets the storage handler used by the query cache. A list of available storage handler can be obtained from mysqlnd_qc_get_available_handlers(). Which storage are available depends on the compile time configuration of the query cache plugin. The default storage handler is always available. All other storage handler must be enabled explicitly when building the extension.

Parameters

handler

Handler can be of type string representing the name of a built-in storage handler or an object of type mysqlnd_qc_handler_default. The names of the built-in storage handler are default, APC, MEMCACHE, sqlite.

Return Values

Returns TRUE on success or FALSE on failure.

If changing the storage handler fails a catchable fatal error will be thrown. The query cache cannot operate if the previous storage handler has been shutdown but no new storage handler has been installed.

Examples

Example #1 mysqlnd_qc_set_storage_handler() example

The example shows the output from the built-in default storage handler. Other storage handler may report different data.

<?php
var_dump(mysqlnd_qc_set_storage_handler("memcache"));

if (true === mysqlnd_qc_set_storage_handler("default"))
  printf("Default storage handler activated");

/* Catchable fatal error */
var_dump(mysqlnd_qc_set_storage_handler("unknown"));
?>

The above examples will output:

bool(true)
Default storage handler activated
Catchable fatal error: mysqlnd_qc_set_storage_handler(): Unknown handler 'unknown' in (file) on line (line)

See Also

  • Installation
  • mysqlnd_qc_get_available_handlers() - Returns a list of available storage handler


Sets the callback functions for a user-defined procedural storage handler

  • « mysqlnd_qc_set_storage_handler
  • Change History »
  • PHP Manual
  • mysqlnd_qc Functions
  • Sets the callback functions for a user-defined procedural storage handler

mysqlnd_qc_set_user_handlers

(PECL mysqlnd_qc >= 1.0.0)

mysqlnd_qc_set_user_handlers — Sets the callback functions for a user-defined procedural storage handler

Description

mysqlnd_qc_set_user_handlers ( string $get_hash , string $find_query_in_cache , string $return_to_cache , string $add_query_to_cache_if_not_exists , string $query_is_select , string $update_query_run_time_stats , string $get_stats , string $clear_cache ) : bool

Sets the callback functions for a user-defined procedural storage handler.

Parameters

get_hash

Name of the user function implementing the storage handler get_hash functionality.

find_query_in_cache

Name of the user function implementing the storage handler find_in_cache functionality.

return_to_cache

Name of the user function implementing the storage handler return_to_cache functionality.

add_query_to_cache_if_not_exists

Name of the user function implementing the storage handler add_query_to_cache_if_not_exists functionality.

query_is_select

Name of the user function implementing the storage handler query_is_select functionality.

update_query_run_time_stats

Name of the user function implementing the storage handler update_query_run_time_stats functionality.

get_stats

Name of the user function implementing the storage handler get_stats functionality.

clear_cache

Name of the user function implementing the storage handler clear_cache functionality.

Return Values

Returns TRUE on success or FALSE on FAILURE.

See Also

  • Procedural user-defined storage handler example


Change History

Table of Contents

  • PECL/mysqlnd_qc 1.2 series
  • PECL/mysqlnd_qc 1.1 series
  • PECL/mysqlnd_qc 1.0 series

This change history is a high level summary of selected changes that may impact applications and/or break backwards compatibility.

See also the CHANGES file in the source distribution for a complete list of changes.


PECL/mysqlnd_qc 1.2 series

1.2.0 - alpha

  • Release date: 03/2013
  • Motto/theme: PHP 5.5 compatibility

Feature changes

  • Update build for PHP 5.5 (Credits: Remi Collet)

  • APC storage handler update

    • Fix build for APC 3.1.13-beta and trunk

  • Introduced MYSQLND_QC_VERSION and MYSQLND_QC_VERSION_ID.


PECL/mysqlnd_qc 1.1 series

1.1.0 - stable

  • Release date: 04/2012
  • Motto/theme: PHP 5.4 compatibility, schema pattern based caching and mysqlnd_ms support

1.1.0 - beta

  • Release date: 04/2012
  • Motto/theme: PHP 5.4 compatibility, schema pattern based caching and mysqlnd_ms support

1.1.0 - alpha

  • Release date: 04/2012
  • Motto/theme: PHP 5.4 compatibility, schema pattern based caching and mysqlnd_ms support

Feature changes

  • APC storage handler update

    • Fix build for APC 3.1.9+
    • Note: Use of the APC storage handler is currently not recommended due to stability issues of APC itself.

  • New PHP configuration directives

    • mysqlnd_qc.collect_statistics_log_file. Aggregated cache statistics log file written after every 10th request served by the PHP process.
    • mysqlnd_qc.ignore_sql_comments. Control whether SQL comments are ignored for cache key hash generation.

  • New constants and SQL hints

    • MYSQLND_QC_SERVER_ID_SWITCH allows grouping of cache entries from different physical connections. This is needed by PECL/mysqlnd_ms.
    • MYSQLND_QC_CONDITION_META_SCHEMA_PATTERN to be used with mysqlnd_qc_set_cache_condition().

  • New function mysqlnd_qc_set_cache_condition() for built-in schema pattern based caching. Likely to support a wider range of conditions in the future.

  • Report valid_until timestamp for cache entries of the default handler through mysqlnd_qc_get_cache_info().

  • Include charset number for cache entry hashing. This should prevent serving result sets which have the wrong charset.

    API change: get_hash_key expects new "charsetnr" (int) parameter after "port".

  • API change: changing is_select() signature from bool is_select() to mixed is_select(). Mixed can be either boolean or array(long ttl, string server_id). This is needed by PECL/mysqlnd_ms.

Other

  • Support acting as a cache backend for PECL/mysqlnd_ms 1.3.0-beta or later to transparently replace MySQL Replication slave reads with cache accesses, if the user explicitly allows.

Bug fixes

  • Fixed Bug #59959 (config.m4, wrong library - 64bit memcached handler builds) (Credits: Remi Collet)


PECL/mysqlnd_qc 1.0 series

1.0.1-stable

  • Release date: 12/2010
  • Motto/theme: Prepared statement support

Added support for Prepared statements and unbuffered queries.

1.0.0-beta

  • Release date: 07/2010
  • Motto/theme: TTL-based cache with various storage options (Memcache, APC, SQLite, user-defined)

Initial public release of the transparent TTL-based query result cache. Flexible storage of cached results. Various storage media supported.


Mysqlnd user handler plugin

  • Introduction
  • Quickstart and Examples
    • Setup
    • How it works
    • Installing a proxy
    • Basic query monitoring
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • MysqlndUhConnection — The MysqlndUhConnection class
    • MysqlndUhConnection::changeUser — Changes the user of the specified mysqlnd database connection
    • MysqlndUhConnection::charsetName — Returns the default character set for the database connection
    • MysqlndUhConnection::close — Closes a previously opened database connection
    • MysqlndUhConnection::connect — Open a new connection to the MySQL server
    • MysqlndUhConnection::__construct — The __construct purpose
    • MysqlndUhConnection::endPSession — End a persistent connection
    • MysqlndUhConnection::escapeString — Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
    • MysqlndUhConnection::getAffectedRows — Gets the number of affected rows in a previous MySQL operation
    • MysqlndUhConnection::getErrorNumber — Returns the error code for the most recent function call
    • MysqlndUhConnection::getErrorString — Returns a string description of the last error
    • MysqlndUhConnection::getFieldCount — Returns the number of columns for the most recent query
    • MysqlndUhConnection::getHostInformation — Returns a string representing the type of connection used
    • MysqlndUhConnection::getLastInsertId — Returns the auto generated id used in the last query
    • MysqlndUhConnection::getLastMessage — Retrieves information about the most recently executed query
    • MysqlndUhConnection::getProtocolInformation — Returns the version of the MySQL protocol used
    • MysqlndUhConnection::getServerInformation — Returns the version of the MySQL server
    • MysqlndUhConnection::getServerStatistics — Gets the current system status
    • MysqlndUhConnection::getServerVersion — Returns the version of the MySQL server as an integer
    • MysqlndUhConnection::getSqlstate — Returns the SQLSTATE error from previous MySQL operation
    • MysqlndUhConnection::getStatistics — Returns statistics about the client connection
    • MysqlndUhConnection::getThreadId — Returns the thread ID for the current connection
    • MysqlndUhConnection::getWarningCount — Returns the number of warnings from the last query for the given link
    • MysqlndUhConnection::init — Initialize mysqlnd connection
    • MysqlndUhConnection::killConnection — Asks the server to kill a MySQL thread
    • MysqlndUhConnection::listFields — List MySQL table fields
    • MysqlndUhConnection::listMethod — Wrapper for assorted list commands
    • MysqlndUhConnection::moreResults — Check if there are any more query results from a multi query
    • MysqlndUhConnection::nextResult — Prepare next result from multi_query
    • MysqlndUhConnection::ping — Pings a server connection, or tries to reconnect if the connection has gone down
    • MysqlndUhConnection::query — Performs a query on the database
    • MysqlndUhConnection::queryReadResultsetHeader — Read a result set header
    • MysqlndUhConnection::reapQuery — Get result from async query
    • MysqlndUhConnection::refreshServer — Flush or reset tables and caches
    • MysqlndUhConnection::restartPSession — Restart a persistent mysqlnd connection
    • MysqlndUhConnection::selectDb — Selects the default database for database queries
    • MysqlndUhConnection::sendClose — Sends a close command to MySQL
    • MysqlndUhConnection::sendQuery — Sends a query to MySQL
    • MysqlndUhConnection::serverDumpDebugInformation — Dump debugging information into the log for the MySQL server
    • MysqlndUhConnection::setAutocommit — Turns on or off auto-committing database modifications
    • MysqlndUhConnection::setCharset — Sets the default client character set
    • MysqlndUhConnection::setClientOption — Sets a client option
    • MysqlndUhConnection::setServerOption — Sets a server option
    • MysqlndUhConnection::shutdownServer — The shutdownServer purpose
    • MysqlndUhConnection::simpleCommand — Sends a basic COM_* command
    • MysqlndUhConnection::simpleCommandHandleResponse — Process a response for a basic COM_* command send to the client
    • MysqlndUhConnection::sslSet — Used for establishing secure connections using SSL
    • MysqlndUhConnection::stmtInit — Initializes a statement and returns a resource for use with mysqli_statement::prepare
    • MysqlndUhConnection::storeResult — Transfers a result set from the last query
    • MysqlndUhConnection::txCommit — Commits the current transaction
    • MysqlndUhConnection::txRollback — Rolls back current transaction
    • MysqlndUhConnection::useResult — Initiate a result set retrieval
  • MysqlndUhPreparedStatement — The MysqlndUhPreparedStatement class
    • MysqlndUhPreparedStatement::__construct — The __construct purpose
    • MysqlndUhPreparedStatement::execute — Executes a prepared Query
    • MysqlndUhPreparedStatement::prepare — Prepare an SQL statement for execution
  • Mysqlnd_uh Functions
    • mysqlnd_uh_convert_to_mysqlnd — Converts a MySQL connection handle into a mysqlnd connection handle
    • mysqlnd_uh_set_connection_proxy — Installs a proxy for mysqlnd connections
    • mysqlnd_uh_set_statement_proxy — Installs a proxy for mysqlnd statements
  • Change History
    • PECL/mysqlnd_uh 1.0 series


Introduction

The mysqlnd user handler plugin (mysqlnd_uh) allows users to set hooks for most internal calls of the MySQL native driver for PHP (mysqlnd). Mysqlnd and its plugins, including PECL/mysqlnd_uh, operate on a layer beneath the PHP MySQL extensions. A mysqlnd plugin can be considered as a proxy between the PHP MySQL extensions and the MySQL server as part of the PHP executable on the client-side. Because the plugins operates on their own layer below the PHP MySQL extensions, they can monitor and change application actions without requiring application changes. If the PHP MySQL extensions (mysqli, mysql, PDO_MYSQL) are compiled to use mysqlnd this can be used for:

  • Monitoring

    • Queries executed by any of the PHP MySQL extensions

    • Prepared statements executing by any of the PHP MySQL extensions

  • Auditing

    • Detection of database usage

    • SQL injection protection using black and white lists

  • Assorted

    • Load Balancing connections

The MySQL native driver for PHP (mysqlnd) features an internal plugin C API. C plugins, such as the mysqlnd user handler plugin, can extend the functionality of mysqlnd. PECL/mysqlnd_uh makes parts of the internal plugin C API available to the PHP user for plugin development with PHP.

Note: Status

The mysqlnd user handler plugin is in alpha status. Take appropriate care before using it in production environments.

Security considerations

PECL/mysqlnd_uh gives users access to MySQL user names, MySQL password used by any of the PHP MySQL extensions to connect to MySQL. It allows monitoring of all queries and prepared statements exposing the statement string to the user. Therefore, the extension should be installed with care. The PHP_INI_SYSTEM configuration setting mysqlnd_uh.enable can be used to prevent users from hooking mysqlnd calls.

Code obfuscators and similar technologies are not suitable to prevent monitoring of mysqlnd library activities if PECL/mysqlnd_uh is made available and the user can install a proxy, for example, using auto_prepend_file.

Documentation note

Many of the mysqlnd_uh functions are briefly described because the mysqli extension is a thin abstraction layer on top of the MySQL C API that the mysqlnd library provides. Therefore, the corresponding mysqli documentation (along with the MySQL reference manual) can be consulted to receive more information about a particular function.

On the name

The shortcut mysqlnd_uh stands for mysqlnd user handler, and has been the name since early development.


Quickstart and Examples

Table of Contents

  • Setup
  • How it works
  • Installing a proxy
  • Basic query monitoring

The mysqlnd user handler plugin can be understood as a client-side proxy for all PHP MySQL extensions (mysqli, mysql, PDO_MYSQL), if they are compiled to use the mysqlnd library. The extensions use the mysqlnd library internally, at the C level, to communicate with the MySQL server. PECL/mysqlnd_uh allows it to hook many mysqlnd calls. Therefore, most activities of the PHP MySQL extensions can be monitored.

Because monitoring happens at the level of the library, at a layer below the application, it is possible to monitor applications without changing them.

On the C level, the mysqlnd library is structured in modules or classes. The extension hooks almost all methods of the mysqlnd internal connection class and exposes them through the user space class MysqlndUhConnection. Some few methods of the mysqlnd internal statement class are made available to the PHP user with the class MysqlndUhPreparedStatement. By subclassing the classes MysqlndUhConnection and MysqlndUhPreparedStatement users get access to mysqlnd internal function calls.

Note:

The internal mysqlnd function calls are not designed to be exposed to the PHP user. Manipulating their activities may cause PHP to crash or leak memory. Often, this is not considered a bug. Please, keep in mind that you are accessing C library functions through PHP which are expected to take certain actions, which you may not be able to emulate in user space. Therefore, it is strongly recommended to always call the parent method implementation when subclassing MysqlndUhConnection or MysqlndUhPreparedStatement. To prevent the worst case, the extension performs some sanity checks. Please, see also the Mysqlnd_uh Configure Options.


Setup

The plugin is implemented as a PHP extension. See the installation instructions to install the » PECL/mysqlnd_uh extension. Then, load the extension into PHP and activate the plugin in the PHP configuration file using the PHP configuration directive named mysqlnd_uh.enable. The below example shows the default settings of the extension.

Example #1 Enabling the plugin (php.ini)

mysqlnd_uh.enable=1
mysqlnd_uh.report_wrong_types=1


How it works

This describes the background and inner workings of the mysqlnd_uh extension.

Two classes are provided by the extension: MysqlndUhConnection and MysqlndUhPreparedStatement. MysqlndUhConnection lets you access almost all methods of the mysqlnd internal connection class. The latter exposes some selected methods of the mysqlnd internal statement class. For example, MysqlndUhConnection::connect() maps to the mysqlnd library C function mysqlnd_conn__connect.

As a mysqlnd plugin, the PECL/mysqlnd_uh extension replaces mysqlnd library C functions with its own functions. Whenever a PHP MySQL extension compiled to use mysqlnd calls a mysqlnd function, the functions installed by the plugin are executed instead of the original mysqlnd ones. For example, mysqli_connect() invokes mysqlnd_conn__connect, so the connect function installed by PECL/mysqlnd_uh will be called. The functions installed by PECL/mysqlnd_uh are the methods of the built-in classes.

The built-in PHP classes and their methods do nothing but call their mysqlnd C library counterparts, to behave exactly like the original mysqlnd function they replace. The code below illustrates in pseudo-code what the extension does.

Example #1 Pseudo-code: what a built-in class does

class MysqlndUhConnection {
  public function connect(($conn, $host, $user, $passwd, $db, $port, $socket, $mysql_flags) {
    MYSQLND* c_mysqlnd_connection = convert_from_php_to_c($conn);
    ...
    return call_c_function(mysqlnd_conn__connect(c_mysqlnd_connection, ...));
  }
}

The build-in classes behave like a transparent proxy. It is possible for you to replace the proxy with your own. This is done by subclassing MysqlndUhConnection or MysqlndUhPreparedStatement to extend the functionality of the proxy, followed by registering a new proxy object. Proxy objects are installed by mysqlnd_uh_set_connection_proxy() and mysqlnd_uh_set_statement_proxy().

Example #2 Installing a proxy

<?php
class proxy extends MysqlndUhConnection {
 public function connect($res, $host, $user, $passwd, $db, $port, $socket, $mysql_flags) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::connect($res, $host, $user, $passwd, $db, $port, $socket, $mysql_flags);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
?>

The above example will output:

proxy::connect(array (
  0 => NULL,
  1 => 'localhost',
  2 => 'root',
  3 => '',
  4 => 'test',
  5 => 3306,
  6 => NULL,
  7 => 131072,
))
proxy::connect returns true


Installing a proxy

The extension provides two built-in classes: MysqlndUhConnection and MysqlndUhPreparedStatement. The classes are used for hooking mysqlnd library calls. Their methods correspond to mysqlnd internal functions. By default they act like a transparent proxy and do nothing but call their mysqlnd counterparts. By subclassing the classes you can install your own proxy to monitor mysqlnd.

See also the How it works guide to learn about the inner workings of this extension.

Connection proxies are objects of the type MysqlndUhConnection. Connection proxy objects are installed by mysqlnd_uh_set_connection_proxy(). If you install the built-in class MysqlndUhConnection as a proxy, nothing happens. It behaves like a transparent proxy.

Example #1 Proxy registration, mysqlnd_uh.enable=1

<?php
mysqlnd_uh_set_connection_proxy(new MysqlndUhConnection());
$mysqli = new mysqli("localhost", "root", "", "test");
?>

The PHP_INI_SYSTEM configuration setting mysqlnd_uh.enable controls whether a proxy may be set. If disabled, the extension will throw errors of type E_WARNING

Example #2 Proxy installation disabled

mysqlnd_uh.enable=0
<?php
mysqlnd_uh_set_connection_proxy(new MysqlndUhConnection());
$mysqli = new mysqli("localhost", "root", "", "test");
?>

The above example will output:

PHP Warning:  MysqlndUhConnection::__construct(): (Mysqlnd User Handler) The plugin has been disabled by setting the configuration parameter mysqlnd_uh.enabled = false.  You must not use any of the base classes in %s on line %d
PHP Warning:  mysqlnd_uh_set_connection_proxy(): (Mysqlnd User Handler) The plugin has been disabled by setting the configuration parameter mysqlnd_uh.enable = false. The proxy has not been installed  in %s on line %d

To monitor mysqlnd, you have to write your own proxy object subclassing MysqlndUhConnection. Please, see the function reference for a the list of methods that can be subclassed. Alternatively, you can use reflection to inspect the built-in MysqlndUhConnection.

Create a new class proxy. Derive it from the built-in class MysqlndUhConnection. Replace the MysqlndUhConnection::connect(). method. Print out the host parameter value passed to the method. Make sure that you call the parent implementation of the connect method. Failing to do so may give unexpected and undesired results, including memory leaks and crashes.

Register your proxy and open three connections using the PHP MySQL extensions mysqli, mysql, PDO_MYSQL. If the extensions have been compiled to use the mysqlnd library, the proxy::connect method will be called three times, once for each connection opened.

Example #3 Connection proxy

<?php
class proxy extends MysqlndUhConnection {
  public function connect($res, $host, $user, $passwd, $db, $port, $socket, $mysql_flags) {
   printf("Connection opened to '%s'\n", $host);
   /* Always call the parent implementation! */
   return parent::connect($res, $host, $user, $passwd, $db, $port, $socket, $mysql_flags);
  }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysql = mysql_connect("localhost", "root", "");
$pdo = new PDO("mysql:host=localhost;dbname=test", "root", "");
?>

The above example will output:

Connection opened to 'localhost'
Connection opened to 'localhost'
Connection opened to 'localhost'

The use of prepared statement proxies follows the same pattern: create a proxy object of the type MysqlndUhPreparedStatement and install the proxy using mysqlnd_uh_set_statement_proxy().

Example #4 Prepared statement proxy

<?php
class stmt_proxy extends MysqlndUhPreparedStatement {
 public function prepare($res, $query) {
  printf("%s(%s)\n", __METHOD__, $query);
  return parent::prepare($res, $query);
 }
}
mysqlnd_uh_set_statement_proxy(new stmt_proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$stmt = $mysqli->prepare("SELECT 'mysqlnd hacking made easy' AS _msg FROM DUAL");
?>

The above example will output:

stmt_proxy::prepare(SELECT 'mysqlnd hacking made easy' AS _msg FROM DUAL)


Basic query monitoring

Basic monitoring of a query statement is easy with PECL/mysqlnd_uh. Combined with debug_print_backtrace() it can become a powerful tool, for example, to find the origin of certain statement. This may be desired when searching for slow queries but also after database refactoring to find code still accessing deprecated databases or tables. The latter may be a complicated matter to do otherwise, especially if the application uses auto-generated queries.

Example #1 Basic Monitoring

<?php
class conn_proxy extends MysqlndUhConnection {
 public function query($res, $query) {
  debug_print_backtrace();
  return parent::query($res, $query);
 }
}
class stmt_proxy extends MysqlndUhPreparedStatement {
 public function prepare($res, $query) {
  debug_print_backtrace();
  return parent::prepare($res, $query);
 }
}
mysqlnd_uh_set_connection_proxy(new conn_proxy());
mysqlnd_uh_set_statement_proxy(new stmt_proxy());

printf("Proxies installed...\n");
$pdo = new PDO("mysql:host=localhost;dbname=test", "root", "");
var_dump($pdo->query("SELECT 1 AS _one FROM DUAL")->fetchAll(PDO::FETCH_ASSOC));

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->prepare("SELECT 1 AS _two FROM DUAL");
?>

The above example will output:

#0  conn_proxy->query(Resource id #19, SELECT 1 AS _one FROM DUAL)
#1  PDO->query(SELECT 1 AS _one FROM DUAL) called at [example.php:19]
array(1) {
  [0]=>
  array(1) {
    ["_one"]=>
    string(1) "1"
  }
}
#0  stmt_proxy->prepare(Resource id #753, SELECT 1 AS _two FROM DUAL)
#1  mysqli->prepare(SELECT 1 AS _two FROM DUAL) called at [example.php:22]

For basic query monitoring you should install a connection and a prepared statement proxy. The connection proxy should subclass MysqlndUhConnection::query(). All database queries not using native prepared statements will call this method. In the example the query function is invoked by a PDO call. By default, PDO_MySQL is using prepared statement emulation.

All native prepared statements are prepared with the prepare method of mysqlnd exported through MysqlndUhPreparedStatement::prepare(). Subclass MysqlndUhPreparedStatement and overwrite prepare for native prepared statement monitoring.


Requirements

PHP 5.3.3 or later. It is recommended to use PHP 5.4.0 or later to get access to the latest mysqlnd features.

The mysqlnd_uh user handler plugin supports all PHP applications and all available PHP MySQL extensions (mysqli, mysql, PDO_MYSQL). The PHP MySQL extension must be configured to use mysqlnd in order to be able to use the mysqlnd_uh plugin for mysqlnd.

The alpha versions makes use of some mysqli features. You must enable mysqli to compile the plugin. This requirement may be removed in the future. Note, that this requirement does not restrict you to use the plugin only with mysqli. You can use the plugin to monitor mysql, mysqli and PDO_MYSQL.


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/mysqlnd-uh

PECL/mysqlnd_uh is currently not available on Windows. The source code of the extension makes use of C99 constructs not allowed with PHP Windows builds.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Mysqlnd_uh Configure Options
Name | Default | Changeable | Changelog
mysqlnd_uh.enable | 1 | PHP_INI_SYSTEM |
mysqlnd_uh.report_wrong_types | 1 | PHP_INI_ALL |

Here's a short explanation of the configuration directives.

mysqlnd_uh.enable integer

Enables or disables the plugin. If set to disabled, the extension will not allow users to plug into mysqlnd to hook mysqlnd calls.

mysqlnd_uh.report_wrong_types integer

Whether to report wrong return value types of user hooks as E_WARNING level errors. This is recommended for detecting errors.


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.

Most of the constants refer to details of the MySQL Client Server Protocol. Please, refer to the MySQL reference manual to learn about their meaning. To avoid content duplication, only short descriptions are given.

MysqlndUhConnection::simpleCommand() related

The following constants can be used to detect what command is to be send through MysqlndUhConnection::simpleCommand().

MYSQLND_UH_MYSQLND_COM_SLEEP (integer)
MySQL Client Server protocol command: COM_SLEEP.
MYSQLND_UH_MYSQLND_COM_QUIT (integer)
MySQL Client Server protocol command: COM_QUIT.
MYSQLND_UH_MYSQLND_COM_INIT_DB (integer)
MySQL Client Server protocol command: COM_INIT_DB.
MYSQLND_UH_MYSQLND_COM_QUERY (integer)
MySQL Client Server protocol command: COM_QUERY.
MYSQLND_UH_MYSQLND_COM_FIELD_LIST (integer)
MySQL Client Server protocol command: COM_FIELD_LIST.
MYSQLND_UH_MYSQLND_COM_CREATE_DB (integer)
MySQL Client Server protocol command: COM_CREATE_DB.
MYSQLND_UH_MYSQLND_COM_DROP_DB (integer)
MySQL Client Server protocol command: COM_DROP_DB.
MYSQLND_UH_MYSQLND_COM_REFRESH (integer)
MySQL Client Server protocol command: COM_REFRESH.
MYSQLND_UH_MYSQLND_COM_SHUTDOWN (integer)
MySQL Client Server protocol command: COM_SHUTDOWN.
MYSQLND_UH_MYSQLND_COM_STATISTICS (integer)
MySQL Client Server protocol command: COM_STATISTICS.
MYSQLND_UH_MYSQLND_COM_PROCESS_INFO (integer)
MySQL Client Server protocol command: COM_PROCESS_INFO.
MYSQLND_UH_MYSQLND_COM_CONNECT (integer)
MySQL Client Server protocol command: COM_CONNECT.
MYSQLND_UH_MYSQLND_COM_PROCESS_KILL (integer)
MySQL Client Server protocol command: COM_PROCESS_KILL.
MYSQLND_UH_MYSQLND_COM_DEBUG (integer)
MySQL Client Server protocol command: COM_DEBUG.
MYSQLND_UH_MYSQLND_COM_PING (integer)
MySQL Client Server protocol command: COM_PING.
MYSQLND_UH_MYSQLND_COM_TIME (integer)
MySQL Client Server protocol command: COM_TIME.
MYSQLND_UH_MYSQLND_COM_DELAYED_INSERT (integer)
MySQL Client Server protocol command: COM_DELAYED_INSERT.
MYSQLND_UH_MYSQLND_COM_CHANGE_USER (integer)
MySQL Client Server protocol command: COM_CHANGE_USER.
MYSQLND_UH_MYSQLND_COM_BINLOG_DUMP (integer)
MySQL Client Server protocol command: COM_BINLOG_DUMP.
MYSQLND_UH_MYSQLND_COM_TABLE_DUMP (integer)
MySQL Client Server protocol command: COM_TABLE_DUMP.
MYSQLND_UH_MYSQLND_COM_CONNECT_OUT (integer)
MySQL Client Server protocol command: COM_CONNECT_OUT.
MYSQLND_UH_MYSQLND_COM_REGISTER_SLAVED (integer)
MySQL Client Server protocol command: COM_REGISTER_SLAVED.
MYSQLND_UH_MYSQLND_COM_STMT_PREPARE (integer)
MySQL Client Server protocol command: COM_STMT_PREPARE.
MYSQLND_UH_MYSQLND_COM_STMT_EXECUTE (integer)
MySQL Client Server protocol command: COM_STMT_EXECUTE.
MYSQLND_UH_MYSQLND_COM_STMT_SEND_LONG_DATA (integer)
MySQL Client Server protocol command: COM_STMT_SEND_LONG_DATA.
MYSQLND_UH_MYSQLND_COM_STMT_CLOSE (integer)
MySQL Client Server protocol command: COM_STMT_CLOSE.
MYSQLND_UH_MYSQLND_COM_STMT_RESET (integer)
MySQL Client Server protocol command: COM_STMT_RESET.
MYSQLND_UH_MYSQLND_COM_SET_OPTION (integer)
MySQL Client Server protocol command: COM_SET_OPTION.
MYSQLND_UH_MYSQLND_COM_STMT_FETCH (integer)
MySQL Client Server protocol command: COM_STMT_FETCH.
MYSQLND_UH_MYSQLND_COM_DAEMON (integer)
MySQL Client Server protocol command: COM_DAEMON.
MYSQLND_UH_MYSQLND_COM_END (integer)
MySQL Client Server protocol command: COM_END.

The following constants can be used to analyze the ok_packet argument of MysqlndUhConnection::simpleCommand().

MYSQLND_UH_MYSQLND_PROT_GREET_PACKET (integer)
MySQL Client Server protocol packet: greeting.
MYSQLND_UH_MYSQLND_PROT_AUTH_PACKET (integer)
MySQL Client Server protocol packet: authentication.
MYSQLND_UH_MYSQLND_PROT_OK_PACKET (integer)
MySQL Client Server protocol packet: OK.
MYSQLND_UH_MYSQLND_PROT_EOF_PACKET (integer)
MySQL Client Server protocol packet: EOF.
MYSQLND_UH_MYSQLND_PROT_CMD_PACKET (integer)
MySQL Client Server protocol packet: command.
MYSQLND_UH_MYSQLND_PROT_RSET_HEADER_PACKET (integer)
MySQL Client Server protocol packet: result set header.
MYSQLND_UH_MYSQLND_PROT_RSET_FLD_PACKET (integer)
MySQL Client Server protocol packet: resultset field.
MYSQLND_UH_MYSQLND_PROT_ROW_PACKET (integer)
MySQL Client Server protocol packet: row.
MYSQLND_UH_MYSQLND_PROT_STATS_PACKET (integer)
MySQL Client Server protocol packet: stats.
MYSQLND_UH_MYSQLND_PREPARE_RESP_PACKET (integer)
MySQL Client Server protocol packet: prepare response.
MYSQLND_UH_MYSQLND_CHG_USER_RESP_PACKET (integer)
MySQL Client Server protocol packet: change user response.
MYSQLND_UH_MYSQLND_PROT_LAST (integer)
No practical meaning. Last entry marker of internal C data structure list.

MysqlndUhConnection::close() related

The following constants can be used to detect why a connection has been closed through MysqlndUhConnection::close().

MYSQLND_UH_MYSQLND_CLOSE_EXPLICIT (integer)
User has called mysqlnd to close the connection.
MYSQLND_UH_MYSQLND_CLOSE_IMPLICIT (integer)
Implicitly closed, for example, during garbage connection.
MYSQLND_UH_MYSQLND_CLOSE_DISCONNECTED (integer)
Connection error.
MYSQLND_UH_MYSQLND_CLOSE_LAST (integer)
No practical meaning. Last entry marker of internal C data structure list.

MysqlndUhConnection::setServerOption() related

The following constants can be used to detect which option is set through MysqlndUhConnection::setServerOption().

MYSQLND_UH_SERVER_OPTION_MULTI_STATEMENTS_ON (integer)
Option: enables multi statement support.
MYSQLND_UH_SERVER_OPTION_MULTI_STATEMENTS_OFF (integer)
Option: disables multi statement support.

MysqlndUhConnection::setClientOption() related

The following constants can be used to detect which option is set through MysqlndUhConnection::setClientOption().

MYSQLND_UH_MYSQLND_OPTION_OPT_CONNECT_TIMEOUT (integer)
Option: connection timeout.
MYSQLND_UH_MYSQLND_OPTION_OPT_COMPRESS (integer)
Option: whether the MySQL compressed protocol is to be used.
MYSQLND_UH_MYSQLND_OPTION_OPT_NAMED_PIPE (integer)
Option: named pipe to use for connection (Windows).
MYSQLND_UH_MYSQLND_OPTION_INIT_COMMAND (integer)
Option: init command to execute upon connect.
MYSQLND_UH_MYSQLND_READ_DEFAULT_FILE (integer)
Option: MySQL server default file to read upon connect.
MYSQLND_UH_MYSQLND_READ_DEFAULT_GROUP (integer)
Option: MySQL server default file group to read upon connect.
MYSQLND_UH_MYSQLND_SET_CHARSET_DIR (integer)
Option: charset description files directory.
MYSQLND_UH_MYSQLND_SET_CHARSET_NAME (integer)
Option: charset name.
MYSQLND_UH_MYSQLND_OPT_LOCAL_INFILE (integer)
Option: Whether to allow LOAD DATA LOCAL INFILE use.
MYSQLND_UH_MYSQLND_OPT_PROTOCOL (integer)
Option: supported protocol version.
MYSQLND_UH_MYSQLND_SHARED_MEMORY_BASE_NAME (integer)
Option: shared memory base name for shared memory connections.
MYSQLND_UH_MYSQLND_OPT_READ_TIMEOUT (integer)
Option: connection read timeout.
MYSQLND_UH_MYSQLND_OPT_WRITE_TIMEOUT (integer)
Option: connection write timeout.
MYSQLND_UH_MYSQLND_OPT_USE_RESULT (integer)
Option: unbuffered result sets.
MYSQLND_UH_MYSQLND_OPT_USE_REMOTE_CONNECTION (integer)
Embedded server related.
MYSQLND_UH_MYSQLND_OPT_USE_EMBEDDED_CONNECTION (integer)
Embedded server related.
MYSQLND_UH_MYSQLND_OPT_GUESS_CONNECTION (integer)
TODO
MYSQLND_UH_MYSQLND_SET_CLIENT_IP (integer)
TODO
MYSQLND_UH_MYSQLND_SECURE_AUTH (integer)
TODO
MYSQLND_UH_MYSQLND_REPORT_DATA_TRUNCATION (integer)
Option: Whether to report data truncation.
MYSQLND_UH_MYSQLND_OPT_RECONNECT (integer)
Option: Whether to reconnect automatically.
MYSQLND_UH_MYSQLND_OPT_SSL_VERIFY_SERVER_CERT (integer)
Option: TODO
MYSQLND_UH_MYSQLND_OPT_NET_CMD_BUFFER_SIZE (integer)
Option: mysqlnd network buffer size for commands.
MYSQLND_UH_MYSQLND_OPT_NET_READ_BUFFER_SIZE (integer)
Option: mysqlnd network buffer size for reading from the server.
MYSQLND_UH_MYSQLND_OPT_SSL_KEY (integer)
Option: SSL key.
MYSQLND_UH_MYSQLND_OPT_SSL_CERT (integer)
Option: SSL certificate.
MYSQLND_UH_MYSQLND_OPT_SSL_CA (integer)
Option: SSL CA.
MYSQLND_UH_MYSQLND_OPT_SSL_CAPATH (integer)
Option: Path to SSL CA.
MYSQLND_UH_MYSQLND_OPT_SSL_CIPHER (integer)
Option: SSL cipher.
MYSQLND_UH_MYSQLND_OPT_SSL_PASSPHRASE (integer)
Option: SSL passphrase.
MYSQLND_UH_SERVER_OPTION_PLUGIN_DIR (integer)
Option: server plugin directory.
MYSQLND_UH_SERVER_OPTION_DEFAULT_AUTH (integer)
Option: default authentication method.
MYSQLND_UH_SERVER_OPTION_SET_CLIENT_IP (integer)
TODO
MYSQLND_UH_MYSQLND_OPT_MAX_ALLOWED_PACKET (integer)
Option: maximum allowed packet size. Available as of PHP 5.4.0.
MYSQLND_UH_MYSQLND_OPT_AUTH_PROTOCOL (integer)
Option: TODO. Available as of PHP 5.4.0.
MYSQLND_UH_MYSQLND_OPT_INT_AND_FLOAT_NATIVE (integer)
Option: make mysqlnd return integer and float columns as long even when using the MySQL Client Server text protocol. Only available with a custom build of mysqlnd.

Other

The plugins version number can be obtained using MYSQLND_UH_VERSION or MYSQLND_UH_VERSION_ID. MYSQLND_UH_VERSION is the string representation of the numerical version number MYSQLND_UH_VERSION_ID, which is an integer such as 10000. Developers can calculate the version number as follows.

Version (part) | Example
Major*10000 | 1*10000 = 10000
Minor*100 | 0*100 = 0
Patch | 0 = 0
MYSQLND_UH_VERSION_ID | 10000

MYSQLND_UH_VERSION (string)
Plugin version string, for example, 1.0.0-alpha.
MYSQLND_UH_VERSION_ID (integer)
Plugin version number, for example, 10000.


The MysqlndUhConnection class

(PECL mysqlnd-uh >= 1.0.0-alpha)

Introduction

Class synopsis

MysqlndUhConnection {
/* Methods */
public changeUser ( mysqlnd_connection $connection , string $user , string $password , string $database , bool $silent , int $passwd_len ) : bool
public charsetName ( mysqlnd_connection $connection ) : string
public close ( mysqlnd_connection $connection , int $close_type ) : bool
public connect ( mysqlnd_connection $connection , string $host , string $use" , string $password , string $database , int $port , string $socket , int $mysql_flags ) : bool
public __construct ( void )
public endPSession ( mysqlnd_connection $connection ) : bool
public escapeString ( mysqlnd_connection $connection , string $escape_string ) : string
public getAffectedRows ( mysqlnd_connection $connection ) : int
public getErrorNumber ( mysqlnd_connection $connection ) : int
public getErrorString ( mysqlnd_connection $connection ) : string
public getFieldCount ( mysqlnd_connection $connection ) : int
public getHostInformation ( mysqlnd_connection $connection ) : string
public getLastInsertId ( mysqlnd_connection $connection ) : int
public getLastMessage ( mysqlnd_connection $connection ) : void
public getProtocolInformation ( mysqlnd_connection $connection ) : string
public getServerInformation ( mysqlnd_connection $connection ) : string
public getServerStatistics ( mysqlnd_connection $connection ) : string
public getServerVersion ( mysqlnd_connection $connection ) : int
public getSqlstate ( mysqlnd_connection $connection ) : string
public getStatistics ( mysqlnd_connection $connection ) : array
public getThreadId ( mysqlnd_connection $connection ) : int
public getWarningCount ( mysqlnd_connection $connection ) : int
public init ( mysqlnd_connection $connection ) : bool
public killConnection ( mysqlnd_connection $connection , int $pid ) : bool
public listFields ( mysqlnd_connection $connection , string $table , string $achtung_wild ) : array
public listMethod ( mysqlnd_connection $connection , string $query , string $achtung_wild , string $par1 ) : void
public moreResults ( mysqlnd_connection $connection ) : bool
public nextResult ( mysqlnd_connection $connection ) : bool
public ping ( mysqlnd_connection $connection ) : bool
public query ( mysqlnd_connection $connection , string $query ) : bool
public queryReadResultsetHeader ( mysqlnd_connection $connection , mysqlnd_statement $mysqlnd_stmt ) : bool
public reapQuery ( mysqlnd_connection $connection ) : bool
public refreshServer ( mysqlnd_connection $connection , int $options ) : bool
public restartPSession ( mysqlnd_connection $connection ) : bool
public selectDb ( mysqlnd_connection $connection , string $database ) : bool
public sendClose ( mysqlnd_connection $connection ) : bool
public sendQuery ( mysqlnd_connection $connection , string $query ) : bool
public serverDumpDebugInformation ( mysqlnd_connection $connection ) : bool
public setAutocommit ( mysqlnd_connection $connection , int $mode ) : bool
public setCharset ( mysqlnd_connection $connection , string $charset ) : bool
public setClientOption ( mysqlnd_connection $connection , int $option , int $value ) : bool
public setServerOption ( mysqlnd_connection $connection , int $option ) : void
public shutdownServer ( string $MYSQLND_UH_RES_MYSQLND_NAME , string $level ) : void
public simpleCommand ( mysqlnd_connection $connection , int $command , string $arg , int $ok_packet , bool $silent , bool $ignore_upsert_status ) : bool
public simpleCommandHandleResponse ( mysqlnd_connection $connection , int $ok_packet , bool $silent , int $command , bool $ignore_upsert_status ) : bool
public sslSet ( mysqlnd_connection $connection , string $key , string $cert , string $ca , string $capath , string $cipher ) : bool
public stmtInit ( mysqlnd_connection $connection ) : resource
public storeResult ( mysqlnd_connection $connection ) : resource
public txCommit ( mysqlnd_connection $connection ) : bool
public txRollback ( mysqlnd_connection $connection ) : bool
public useResult ( mysqlnd_connection $connection ) : resource
}

Table of Contents

  • MysqlndUhConnection::changeUser — Changes the user of the specified mysqlnd database connection
  • MysqlndUhConnection::charsetName — Returns the default character set for the database connection
  • MysqlndUhConnection::close — Closes a previously opened database connection
  • MysqlndUhConnection::connect — Open a new connection to the MySQL server
  • MysqlndUhConnection::__construct — The __construct purpose
  • MysqlndUhConnection::endPSession — End a persistent connection
  • MysqlndUhConnection::escapeString — Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
  • MysqlndUhConnection::getAffectedRows — Gets the number of affected rows in a previous MySQL operation
  • MysqlndUhConnection::getErrorNumber — Returns the error code for the most recent function call
  • MysqlndUhConnection::getErrorString — Returns a string description of the last error
  • MysqlndUhConnection::getFieldCount — Returns the number of columns for the most recent query
  • MysqlndUhConnection::getHostInformation — Returns a string representing the type of connection used
  • MysqlndUhConnection::getLastInsertId — Returns the auto generated id used in the last query
  • MysqlndUhConnection::getLastMessage — Retrieves information about the most recently executed query
  • MysqlndUhConnection::getProtocolInformation — Returns the version of the MySQL protocol used
  • MysqlndUhConnection::getServerInformation — Returns the version of the MySQL server
  • MysqlndUhConnection::getServerStatistics — Gets the current system status
  • MysqlndUhConnection::getServerVersion — Returns the version of the MySQL server as an integer
  • MysqlndUhConnection::getSqlstate — Returns the SQLSTATE error from previous MySQL operation
  • MysqlndUhConnection::getStatistics — Returns statistics about the client connection
  • MysqlndUhConnection::getThreadId — Returns the thread ID for the current connection
  • MysqlndUhConnection::getWarningCount — Returns the number of warnings from the last query for the given link
  • MysqlndUhConnection::init — Initialize mysqlnd connection
  • MysqlndUhConnection::killConnection — Asks the server to kill a MySQL thread
  • MysqlndUhConnection::listFields — List MySQL table fields
  • MysqlndUhConnection::listMethod — Wrapper for assorted list commands
  • MysqlndUhConnection::moreResults — Check if there are any more query results from a multi query
  • MysqlndUhConnection::nextResult — Prepare next result from multi_query
  • MysqlndUhConnection::ping — Pings a server connection, or tries to reconnect if the connection has gone down
  • MysqlndUhConnection::query — Performs a query on the database
  • MysqlndUhConnection::queryReadResultsetHeader — Read a result set header
  • MysqlndUhConnection::reapQuery — Get result from async query
  • MysqlndUhConnection::refreshServer — Flush or reset tables and caches
  • MysqlndUhConnection::restartPSession — Restart a persistent mysqlnd connection
  • MysqlndUhConnection::selectDb — Selects the default database for database queries
  • MysqlndUhConnection::sendClose — Sends a close command to MySQL
  • MysqlndUhConnection::sendQuery — Sends a query to MySQL
  • MysqlndUhConnection::serverDumpDebugInformation — Dump debugging information into the log for the MySQL server
  • MysqlndUhConnection::setAutocommit — Turns on or off auto-committing database modifications
  • MysqlndUhConnection::setCharset — Sets the default client character set
  • MysqlndUhConnection::setClientOption — Sets a client option
  • MysqlndUhConnection::setServerOption — Sets a server option
  • MysqlndUhConnection::shutdownServer — The shutdownServer purpose
  • MysqlndUhConnection::simpleCommand — Sends a basic COM_* command
  • MysqlndUhConnection::simpleCommandHandleResponse — Process a response for a basic COM_* command send to the client
  • MysqlndUhConnection::sslSet — Used for establishing secure connections using SSL
  • MysqlndUhConnection::stmtInit — Initializes a statement and returns a resource for use with mysqli_statement::prepare
  • MysqlndUhConnection::storeResult — Transfers a result set from the last query
  • MysqlndUhConnection::txCommit — Commits the current transaction
  • MysqlndUhConnection::txRollback — Rolls back current transaction
  • MysqlndUhConnection::useResult — Initiate a result set retrieval


Changes the user of the specified mysqlnd database connection

  • « MysqlndUhConnection
  • MysqlndUhConnection::charsetName »
  • PHP Manual
  • MysqlndUhConnection
  • Changes the user of the specified mysqlnd database connection

MysqlndUhConnection::changeUser

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::changeUser — Changes the user of the specified mysqlnd database connection

Description

public MysqlndUhConnection::changeUser ( mysqlnd_connection $connection , string $user , string $password , string $database , bool $silent , int $passwd_len ) : bool

Changes the user of the specified mysqlnd database connection

Parameters

connection

Mysqlnd connection handle. Do not modify!

user

The MySQL user name.

password

The MySQL password.

database

The MySQL database to change to.

silent

Controls if mysqlnd is allowed to emit errors or not.

passwd_len

Length of the MySQL password.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::changeUser() example

<?php
class proxy extends MysqlndUhConnection {
 /* Hook mysqlnd's connection::change_user call */
 public function changeUser($res, $user, $passwd, $db, $silent, $passwd_len) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::changeUser($res, $user, $passwd, $db, $silent, $passwd_len);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
/* Install proxy/hooks to be used with all future mysqlnd connection */
mysqlnd_uh_set_connection_proxy(new proxy());

/* Create mysqli connection which is using the mysqlnd library */
$mysqli = new mysqli("localhost", "root", "", "test");

/* Example of a user API call which triggers the hooked mysqlnd call */
var_dump($mysqli->change_user("root", "bar", "test"));
?>

The above example will output:

proxy::changeUser(array (
  0 => NULL,
  1 => 'root',
  2 => 'bar',
  3 => 'test',
  4 => false,
  5 => 3,
))
proxy::changeUser returns false
bool(false)

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_change_user() - Changes the user of the specified database connection


Returns the default character set for the database connection

  • « MysqlndUhConnection::changeUser
  • MysqlndUhConnection::close »
  • PHP Manual
  • MysqlndUhConnection
  • Returns the default character set for the database connection

MysqlndUhConnection::charsetName

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::charsetName — Returns the default character set for the database connection

Description

public MysqlndUhConnection::charsetName ( mysqlnd_connection $connection ) : string

Returns the default character set for the database connection.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

The default character set.

Examples

Example #1 MysqlndUhConnection::charsetName() example

<?php
class proxy extends MysqlndUhConnection {
  public function charsetName($res) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::charsetName($res);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump(mysqli_character_set_name($mysqli));
?>

The above example will output:

proxy::charsetName(array (
  0 => NULL,
))
proxy::charsetName returns 'latin1'
string(6) "latin1"

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_character_set_name() - Returns the default character set for the database connection


Closes a previously opened database connection

  • « MysqlndUhConnection::charsetName
  • MysqlndUhConnection::connect »
  • PHP Manual
  • MysqlndUhConnection
  • Closes a previously opened database connection

MysqlndUhConnection::close

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::close — Closes a previously opened database connection

Description

public MysqlndUhConnection::close ( mysqlnd_connection $connection , int $close_type ) : bool

Closes a previously opened database connection.

Note:

Failing to call the parent implementation may cause memory leaks or crash PHP. This is not considered a bug. Please, keep in mind that the mysqlnd library functions have never been designed to be exposed to the user space.

Parameters

connection

The connection to be closed. Do not modify!

close_type

Why the connection is to be closed. The value of close_type is one of MYSQLND_UH_MYSQLND_CLOSE_EXPLICIT, MYSQLND_UH_MYSQLND_CLOSE_IMPLICIT, MYSQLND_UH_MYSQLND_CLOSE_DISCONNECTED or MYSQLND_UH_MYSQLND_CLOSE_LAST. The latter should never be seen, unless the default behaviour of the mysqlnd library has been changed by a plugin.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::close() example

<?php
function close_type_to_string($close_type) {
 $mapping = array(
  MYSQLND_UH_MYSQLND_CLOSE_DISCONNECTED => "MYSQLND_UH_MYSQLND_CLOSE_DISCONNECTED",
  MYSQLND_UH_MYSQLND_CLOSE_EXPLICIT => "MYSQLND_UH_MYSQLND_CLOSE_EXPLICIT",
  MYSQLND_UH_MYSQLND_CLOSE_IMPLICIT => "MYSQLND_UH_MYSQLND_CLOSE_IMPLICIT",
  MYSQLND_UH_MYSQLND_CLOSE_LAST => "MYSQLND_UH_MYSQLND_CLOSE_IMPLICIT"
 );
 return (isset($mapping[$close_type])) ? $mapping[$close_type] : 'unknown';
}

class proxy extends MysqlndUhConnection {
  public function close($res, $close_type) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   printf("close_type = %s\n", close_type_to_string($close_type));
   /* WARNING: you must call the parent */
   $ret = parent::close($res, $close_type);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->close();
?>

The above example will output:

proxy::close(array (
  0 => NULL,
  1 => 0,
))
close_type = MYSQLND_UH_MYSQLND_CLOSE_EXPLICIT
proxy::close returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_close() - Closes a previously opened database connection
  • mysql_close() - Close MySQL connection


Open a new connection to the MySQL server

  • « MysqlndUhConnection::close
  • MysqlndUhConnection::__construct »
  • PHP Manual
  • MysqlndUhConnection
  • Open a new connection to the MySQL server

MysqlndUhConnection::connect

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::connect — Open a new connection to the MySQL server

Description

public MysqlndUhConnection::connect ( mysqlnd_connection $connection , string $host , string $use" , string $password , string $database , int $port , string $socket , int $mysql_flags ) : bool

Open a new connection to the MySQL server.

Parameters

connection

Mysqlnd connection handle. Do not modify!

host

Can be either a host name or an IP address. Passing the NULL value or the string "localhost" to this parameter, the local host is assumed. When possible, pipes will be used instead of the TCP/IP protocol.

user

The MySQL user name.

password

If not provided or NULL, the MySQL server will attempt to authenticate the user against those user records which have no password only. This allows one username to be used with different permissions (depending on if a password as provided or not).

database

If provided will specify the default database to be used when performing queries.

port

Specifies the port number to attempt to connect to the MySQL server.

socket

Specifies the socket or named pipe that should be used. If NULL, mysqlnd will default to /tmp/mysql.sock.

mysql_flags

Connection options.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::connect() example

<?php
class proxy extends MysqlndUhConnection {
 public function connect($res, $host, $user, $passwd, $db, $port, $socket, $mysql_flags) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::connect($res, $host, $user, $passwd, $db, $port, $socket, $mysql_flags);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
?>

The above example will output:

proxy::connect(array (
  0 => NULL,
  1 => 'localhost',
  2 => 'root',
  3 => '',
  4 => 'test',
  5 => 3306,
  6 => NULL,
  7 => 131072,
))
proxy::connect returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_connect() - Alias of mysqli::__construct
  • mysql_connect() - Open a connection to a MySQL Server


The __construct purpose

  • « MysqlndUhConnection::connect
  • MysqlndUhConnection::endPSession »
  • PHP Manual
  • MysqlndUhConnection
  • The __construct purpose

MysqlndUhConnection::__construct

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::__construct — The __construct purpose

Description

public MysqlndUhConnection::__construct ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


End a persistent connection

  • « MysqlndUhConnection::__construct
  • MysqlndUhConnection::escapeString »
  • PHP Manual
  • MysqlndUhConnection
  • End a persistent connection

MysqlndUhConnection::endPSession

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::endPSession — End a persistent connection

Description

public MysqlndUhConnection::endPSession ( mysqlnd_connection $connection ) : bool

End a persistent connection

Warning

This function is currently not documented; only its argument list is available.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::endPSession() example

<?php
class proxy extends MysqlndUhConnection {
 public function endPSession($conn) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::endPSession($conn);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("p:localhost", "root", "", "test");
$mysqli->close();
?>

The above example will output:

proxy::endPSession(array (
  0 => NULL,
))
proxy::endPSession returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections


Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

  • « MysqlndUhConnection::endPSession
  • MysqlndUhConnection::getAffectedRows »
  • PHP Manual
  • MysqlndUhConnection
  • Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

MysqlndUhConnection::escapeString

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::escapeString — Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection

Description

public MysqlndUhConnection::escapeString ( mysqlnd_connection $connection , string $escape_string ) : string

Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection.

Parameters

MYSQLND_UH_RES_MYSQLND_NAME

Mysqlnd connection handle. Do not modify!

escape_string

The string to be escaped.

Return Values

The escaped string.

Examples

Example #1 MysqlndUhConnection::escapeString() example

<?php
class proxy extends MysqlndUhConnection {
 public function escapeString($res, $string) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::escapeString($res, $string);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->set_charset("latin1");
$mysqli->real_escape_string("test0'test");
?>

The above example will output:

proxy::escapeString(array (
  0 => NULL,
  1 => 'test0\'test',
))
proxy::escapeString returns 'test0\\\'test'

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • 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_real_escape_string() - Escapes special characters in a string for use in an SQL statement


Gets the number of affected rows in a previous MySQL operation

  • « MysqlndUhConnection::escapeString
  • MysqlndUhConnection::getErrorNumber »
  • PHP Manual
  • MysqlndUhConnection
  • Gets the number of affected rows in a previous MySQL operation

MysqlndUhConnection::getAffectedRows

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getAffectedRows — Gets the number of affected rows in a previous MySQL operation

Description

public MysqlndUhConnection::getAffectedRows ( mysqlnd_connection $connection ) : int

Gets the number of affected rows in a previous MySQL operation.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Number of affected rows.

Examples

Example #1 MysqlndUhConnection::getAffectedRows() example

<?php
class proxy extends MysqlndUhConnection {
 public function getAffectedRows($res) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::getAffectedRows($res);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1)");
var_dump($mysqli->affected_rows);
?>

The above example will output:

proxy::getAffectedRows(array (
  0 => NULL,
))
proxy::getAffectedRows returns 1
int(1)

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_affected_rows() - Gets the number of affected rows in a previous MySQL operation
  • mysql_affected_rows() - Get number of affected rows in previous MySQL operation


Returns the error code for the most recent function call

  • « MysqlndUhConnection::getAffectedRows
  • MysqlndUhConnection::getErrorString »
  • PHP Manual
  • MysqlndUhConnection
  • Returns the error code for the most recent function call

MysqlndUhConnection::getErrorNumber

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getErrorNumber — Returns the error code for the most recent function call

Description

public MysqlndUhConnection::getErrorNumber ( mysqlnd_connection $connection ) : int

Returns the error code for the most recent function call.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Error code for the most recent function call.

Examples

MysqlndUhConnection::getErrorNumber() is not only executed after the invocation of a user space API call which maps directly to it but also called internally.

Example #1 MysqlndUhConnection::getErrorNumber() example

<?php
class proxy extends MysqlndUhConnection {
 public function getErrorNumber($res) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::getErrorNumber($res);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

printf("connect...\n");
$mysqli = new mysqli("localhost", "root", "", "test");
printf("query...\n");
$mysqli->query("PLEASE_LET_THIS_BE_INVALID_SQL");
printf("errno...\n");
var_dump($mysqli->errno);
printf("close...\n");
$mysqli->close();
?>

The above example will output:

connect...
proxy::getErrorNumber(array (
  0 => NULL,
))
proxy::getErrorNumber returns 0
query...
errno...
proxy::getErrorNumber(array (
  0 => NULL,
))
proxy::getErrorNumber returns 1064
int(1064)
close...

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • MysqlndUhConnection::getErrorString() - Returns a string description of the last error
  • mysqli_errno() - Returns the error code for the most recent function call
  • mysql_errno() - Returns the numerical value of the error message from previous MySQL operation


Returns a string description of the last error

  • « MysqlndUhConnection::getErrorNumber
  • MysqlndUhConnection::getFieldCount »
  • PHP Manual
  • MysqlndUhConnection
  • Returns a string description of the last error

MysqlndUhConnection::getErrorString

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getErrorString — Returns a string description of the last error

Description

public MysqlndUhConnection::getErrorString ( mysqlnd_connection $connection ) : string

Returns a string description of the last error.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Error string for the most recent function call.

Examples

MysqlndUhConnection::getErrorString() is not only executed after the invocation of a user space API call which maps directly to it but also called internally.

Example #1 MysqlndUhConnection::getErrorString() example

<?php
class proxy extends MysqlndUhConnection {
 public function getErrorString($res) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::getErrorString($res);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

printf("connect...\n");
$mysqli = new mysqli("localhost", "root", "", "test");
printf("query...\n");
$mysqli->query("WILL_I_EVER_LEARN_SQL?");
printf("errno...\n");
var_dump($mysqli->error);
printf("close...\n");
$mysqli->close();
?>

The above example will output:

connect...
proxy::getErrorString(array (
  0 => NULL,
))
proxy::getErrorString returns ''
query...
errno...
proxy::getErrorString(array (
  0 => NULL,
))
proxy::getErrorString returns '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 \'WILL_I_EVER_LEARN_SQL?\' at line 1'
string(168) "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 'WILL_I_EVER_LEARN_SQL?' at line 1"
close...

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • MysqlndUhConnection::getErrorNumber() - Returns the error code for the most recent function call
  • mysqli_error() - Returns a string description of the last error
  • mysql_error() - Returns the text of the error message from previous MySQL operation


Returns the number of columns for the most recent query

  • « MysqlndUhConnection::getErrorString
  • MysqlndUhConnection::getHostInformation »
  • PHP Manual
  • MysqlndUhConnection
  • Returns the number of columns for the most recent query

MysqlndUhConnection::getFieldCount

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getFieldCount — Returns the number of columns for the most recent query

Description

public MysqlndUhConnection::getFieldCount ( mysqlnd_connection $connection ) : int

Returns the number of columns for the most recent query.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Number of columns.

Examples

MysqlndUhConnection::getFieldCount() is not only executed after the invocation of a user space API call which maps directly to it but also called internally.

Example #1 MysqlndUhConnection::getFieldCount() example

<?php
class proxy extends MysqlndUhConnection {
 public function getFieldCount($res) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::getFieldCount($res);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->query("WILL_I_EVER_LEARN_SQL?");
var_dump($mysqli->field_count);
$mysqli->query("SELECT 1, 2, 3 FROM DUAL");
var_dump($mysqli->field_count);
?>

The above example will output:

proxy::getFieldCount(array (
  0 => NULL,
))
proxy::getFieldCount returns 0
int(0)
proxy::getFieldCount(array (
  0 => NULL,
))
proxy::getFieldCount returns 3
proxy::getFieldCount(array (
  0 => NULL,
))
proxy::getFieldCount returns 3
int(3)

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_field_count() - Returns the number of columns for the most recent query


Returns a string representing the type of connection used

  • « MysqlndUhConnection::getFieldCount
  • MysqlndUhConnection::getLastInsertId »
  • PHP Manual
  • MysqlndUhConnection
  • Returns a string representing the type of connection used

MysqlndUhConnection::getHostInformation

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getHostInformation — Returns a string representing the type of connection used

Description

public MysqlndUhConnection::getHostInformation ( mysqlnd_connection $connection ) : string

Returns a string representing the type of connection used.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Connection description.

Examples

Example #1 MysqlndUhConnection::getHostInformation() example

<?php
class proxy extends MysqlndUhConnection {
 public function getHostInformation($res) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::getHostInformation($res);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump($mysqli->host_info);
?>

The above example will output:

proxy::getHostInformation(array (
  0 => NULL,
))
proxy::getHostInformation returns 'Localhost via UNIX socket'
string(25) "Localhost via UNIX socket"

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_get_host_info() - Returns a string representing the type of connection used
  • mysql_get_host_info() - Get MySQL host info


Returns the auto generated id used in the last query

  • « MysqlndUhConnection::getHostInformation
  • MysqlndUhConnection::getLastMessage »
  • PHP Manual
  • MysqlndUhConnection
  • Returns the auto generated id used in the last query

MysqlndUhConnection::getLastInsertId

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getLastInsertId — Returns the auto generated id used in the last query

Description

public MysqlndUhConnection::getLastInsertId ( mysqlnd_connection $connection ) : int

Returns the auto generated id used in the last query.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Last insert id.

Examples

Example #1 MysqlndUhConnection::getLastInsertId() example

<?php
class proxy extends MysqlndUhConnection {
 public function getLastInsertId($res) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::getLastInsertId($res);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT AUTO_INCREMENT PRIMARY KEY, col VARCHAR(255))");
$mysqli->query("INSERT INTO test(col) VALUES ('a')");
var_dump($mysqli->insert_id);
?>

The above example will output:

proxy::getLastInsertId(array (
  0 => NULL,
))
proxy::getLastInsertId returns 1
int(1)

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_insert_id() - Returns the auto generated id used in the latest query
  • mysql_insert_id() - Get the ID generated in the last query


Retrieves information about the most recently executed query

  • « MysqlndUhConnection::getLastInsertId
  • MysqlndUhConnection::getProtocolInformation »
  • PHP Manual
  • MysqlndUhConnection
  • Retrieves information about the most recently executed query

MysqlndUhConnection::getLastMessage

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getLastMessage — Retrieves information about the most recently executed query

Description

public MysqlndUhConnection::getLastMessage ( mysqlnd_connection $connection ) : void

Retrieves information about the most recently executed query.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Last message. Trying to return a string longer than 511 bytes will cause an error of the type E_WARNING and result in the string being truncated.

Examples

Example #1 MysqlndUhConnection::getLastMessage() example

<?php
class proxy extends MysqlndUhConnection {
 public function getLastMessage($res) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::getLastMessage($res);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump($mysqli->info);
$mysqli->query("DROP TABLE IF EXISTS test");
var_dump($mysqli->info);
?>

The above example will output:

proxy::getLastMessage(array (
  0 => NULL,
))
proxy::getLastMessage returns ''
string(0) ""
proxy::getLastMessage(array (
  0 => NULL,
))
proxy::getLastMessage returns ''
string(0) ""

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_info() - Retrieves information about the most recently executed query
  • mysql_info() - Get information about the most recent query


Returns the version of the MySQL protocol used

  • « MysqlndUhConnection::getLastMessage
  • MysqlndUhConnection::getServerInformation »
  • PHP Manual
  • MysqlndUhConnection
  • Returns the version of the MySQL protocol used

MysqlndUhConnection::getProtocolInformation

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getProtocolInformation — Returns the version of the MySQL protocol used

Description

public MysqlndUhConnection::getProtocolInformation ( mysqlnd_connection $connection ) : string

Returns the version of the MySQL protocol used.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

The protocol version.

Examples

Example #1 MysqlndUhConnection::getProtocolInformation() example

<?php
class proxy extends MysqlndUhConnection {
 public function getProtocolInformation($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::getProtocolInformation($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump($mysqli->protocol_version);
?>

The above example will output:

proxy::getProtocolInformation(array (
  0 => NULL,
))
proxy::getProtocolInformation returns 10
int(10)

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_get_proto_info() - Returns the version of the MySQL protocol used
  • mysql_get_proto_info() - Get MySQL protocol info


Returns the version of the MySQL server

  • « MysqlndUhConnection::getProtocolInformation
  • MysqlndUhConnection::getServerStatistics »
  • PHP Manual
  • MysqlndUhConnection
  • Returns the version of the MySQL server

MysqlndUhConnection::getServerInformation

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getServerInformation — Returns the version of the MySQL server

Description

public MysqlndUhConnection::getServerInformation ( mysqlnd_connection $connection ) : string

Returns the version of the MySQL server.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

The server version.

Examples

Example #1 MysqlndUhConnection::getServerInformation() example

<?php
class proxy extends MysqlndUhConnection {
 public function getServerInformation($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::getServerInformation($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump($mysqli->server_info);
?>

The above example will output:

proxy::getServerInformation(array (
  0 => NULL,
))
proxy::getServerInformation returns '5.1.45-debug-log'
string(16) "5.1.45-debug-log"

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_get_server_info() - Returns the version of the MySQL server
  • mysql_get_server_info() - Get MySQL server info


Gets the current system status

  • « MysqlndUhConnection::getServerInformation
  • MysqlndUhConnection::getServerVersion »
  • PHP Manual
  • MysqlndUhConnection
  • Gets the current system status

MysqlndUhConnection::getServerStatistics

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getServerStatistics — Gets the current system status

Description

public MysqlndUhConnection::getServerStatistics ( mysqlnd_connection $connection ) : string

Gets the current system status.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

The system status message.

Examples

Example #1 MysqlndUhConnection::getServerStatistics() example

<?php
class proxy extends MysqlndUhConnection {
 public function getServerStatistics($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::getServerStatistics($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump(mysqli_stat($mysqli));
?>

The above example will output:

proxy::getServerStatistics(array (
  0 => NULL,
))
proxy::getServerStatistics returns 'Uptime: 2059995  Threads: 1  Questions: 126157  Slow queries: 0  Opens: 6377  Flush tables: 1  Open tables: 18  Queries per second avg: 0.61'
string(140) "Uptime: 2059995  Threads: 1  Questions: 126157  Slow queries: 0  Opens: 6377  Flush tables: 1  Open tables: 18  Queries per second avg: 0.61"

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_stat() - Gets the current system status
  • mysql_stat() - Get current system status


Returns the version of the MySQL server as an integer

  • « MysqlndUhConnection::getServerStatistics
  • MysqlndUhConnection::getSqlstate »
  • PHP Manual
  • MysqlndUhConnection
  • Returns the version of the MySQL server as an integer

MysqlndUhConnection::getServerVersion

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getServerVersion — Returns the version of the MySQL server as an integer

Description

public MysqlndUhConnection::getServerVersion ( mysqlnd_connection $connection ) : int

Returns the version of the MySQL server as an integer.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

The MySQL version.

Examples

Example #1 MysqlndUhConnection::getServerVersion() example

<?php
class proxy extends MysqlndUhConnection {
 public function getServerVersion($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::getServerVersion($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump($mysqli->server_version);
?>

The above example will output:

proxy::getServerVersion(array (
  0 => NULL,
))
proxy::getServerVersion returns 50145
int(50145)

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_get_server_version() - Returns the version of the MySQL server as an integer
  • mysql_get_server_version()


Returns the SQLSTATE error from previous MySQL operation

  • « MysqlndUhConnection::getServerVersion
  • MysqlndUhConnection::getStatistics »
  • PHP Manual
  • MysqlndUhConnection
  • Returns the SQLSTATE error from previous MySQL operation

MysqlndUhConnection::getSqlstate

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getSqlstate — Returns the SQLSTATE error from previous MySQL operation

Description

public MysqlndUhConnection::getSqlstate ( mysqlnd_connection $connection ) : string

Returns the SQLSTATE error from previous MySQL operation.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

The SQLSTATE code.

Examples

Example #1 MysqlndUhConnection::getSqlstate() example

<?php
class proxy extends MysqlndUhConnection {
 public function getSqlstate($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::getSqlstate($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump($mysqli->sqlstate);
$mysqli->query("AN_INVALID_REQUEST_TO_PROVOKE_AN_ERROR");
var_dump($mysqli->sqlstate);
?>

The above example will output:

proxy::getSqlstate(array (
  0 => NULL,
))
proxy::getSqlstate returns '00000'
string(5) "00000"
proxy::getSqlstate(array (
  0 => NULL,
))
proxy::getSqlstate returns '42000'
string(5) "42000"

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_sql_state()


Returns statistics about the client connection

  • « MysqlndUhConnection::getSqlstate
  • MysqlndUhConnection::getThreadId »
  • PHP Manual
  • MysqlndUhConnection
  • Returns statistics about the client connection

MysqlndUhConnection::getStatistics

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getStatistics — Returns statistics about the client connection

Description

public MysqlndUhConnection::getStatistics ( mysqlnd_connection $connection ) : array

Returns statistics about the client connection.

Warning

This function is currently not documented; only its argument list is available.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Connection statistics collected by mysqlnd.

Examples

Example #1 MysqlndUhConnection::getStatistics() example

<?php
class proxy extends MysqlndUhConnection {
 public function getStatistics($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::getStatistics($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump($mysqli->get_connection_stats());
?>

The above example will output:

proxy::getStatistics(array (
  0 => NULL,
))
proxy::getStatistics returns array (
  'bytes_sent' => '73',
  'bytes_received' => '77',
  'packets_sent' => '2',
  'packets_received' => '2',
  'protocol_overhead_in' => '8',
  'protocol_overhead_out' => '8',
  'bytes_received_ok_packet' => '0',
  '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' => '0',
  '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_affected_normal' => '0',
  'rows_affected_ps' => '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_amount' => '0',
  'mem_ecalloc_count' => '0',
  'mem_ecalloc_amount' => '0',
  'mem_erealloc_count' => '0',
  'mem_erealloc_amount' => '0',
  'mem_efree_count' => '0',
  'mem_efree_amount' => '0',
  'mem_malloc_count' => '0',
  'mem_malloc_amount' => '0',
  'mem_calloc_count' => '0',
  'mem_calloc_amount' => '0',
  'mem_realloc_count' => '0',
  'mem_realloc_amount' => '0',
  'mem_free_count' => '0',
  'mem_free_amount' => '0',
  'mem_estrndup_count' => '0',
  'mem_strndup_count' => '0',
  'mem_estndup_count' => '0',
  'mem_strdup_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',
  'init_command_executed_count' => '0',
  'init_command_failed_count' => '0',
  'com_quit' => '0',
  'com_init_db' => '0',
  'com_query' => '0',
  'com_field_list' => '0',
  'com_create_db' => '0',
  'com_drop_db' => '0',
  'com_refresh' => '0',
  'com_shutdown' => '0',
  'com_statistics' => '0',
  'com_process_info' => '0',
  'com_connect' => '0',
  'com_process_kill' => '0',
  'com_debug' => '0',
  'com_ping' => '0',
  'com_time' => '0',
  'com_delayed_insert' => '0',
  'com_change_user' => '0',
  'com_binlog_dump' => '0',
  'com_table_dump' => '0',
  'com_connect_out' => '0',
  'com_register_slave' => '0',
  'com_stmt_prepare' => '0',
  'com_stmt_execute' => '0',
  'com_stmt_send_long_data' => '0',
  'com_stmt_close' => '0',
  'com_stmt_reset' => '0',
  'com_stmt_set_option' => '0',
  'com_stmt_fetch' => '0',
  'com_deamon' => '0',
  'bytes_received_real_data_normal' => '0',
  'bytes_received_real_data_ps' => '0',
)
array(160) {
  ["bytes_sent"]=>
  string(2) "73"
  ["bytes_received"]=>
  string(2) "77"
  ["packets_sent"]=>
  string(1) "2"
  ["packets_received"]=>
  string(1) "2"
  ["protocol_overhead_in"]=>
  string(1) "8"
  ["protocol_overhead_out"]=>
  string(1) "8"
  ["bytes_received_ok_packet"]=>
  string(1) "0"
  ["bytes_received_eof_packet"]=>
  string(1) "0"
  ["bytes_received_rset_header_packet"]=>
  string(1) "0"
  ["bytes_received_rset_field_meta_packet"]=>
  string(1) "0"
  ["bytes_received_rset_row_packet"]=>
  string(1) "0"
  ["bytes_received_prepare_response_packet"]=>
  string(1) "0"
  ["bytes_received_change_user_packet"]=>
  string(1) "0"
  ["packets_sent_command"]=>
  string(1) "0"
  ["packets_received_ok"]=>
  string(1) "0"
  ["packets_received_eof"]=>
  string(1) "0"
  ["packets_received_rset_header"]=>
  string(1) "0"
  ["packets_received_rset_field_meta"]=>
  string(1) "0"
  ["packets_received_rset_row"]=>
  string(1) "0"
  ["packets_received_prepare_response"]=>
  string(1) "0"
  ["packets_received_change_user"]=>
  string(1) "0"
  ["result_set_queries"]=>
  string(1) "0"
  ["non_result_set_queries"]=>
  string(1) "0"
  ["no_index_used"]=>
  string(1) "0"
  ["bad_index_used"]=>
  string(1) "0"
  ["slow_queries"]=>
  string(1) "0"
  ["buffered_sets"]=>
  string(1) "0"
  ["unbuffered_sets"]=>
  string(1) "0"
  ["ps_buffered_sets"]=>
  string(1) "0"
  ["ps_unbuffered_sets"]=>
  string(1) "0"
  ["flushed_normal_sets"]=>
  string(1) "0"
  ["flushed_ps_sets"]=>
  string(1) "0"
  ["ps_prepared_never_executed"]=>
  string(1) "0"
  ["ps_prepared_once_executed"]=>
  string(1) "0"
  ["rows_fetched_from_server_normal"]=>
  string(1) "0"
  ["rows_fetched_from_server_ps"]=>
  string(1) "0"
  ["rows_buffered_from_client_normal"]=>
  string(1) "0"
  ["rows_buffered_from_client_ps"]=>
  string(1) "0"
  ["rows_fetched_from_client_normal_buffered"]=>
  string(1) "0"
  ["rows_fetched_from_client_normal_unbuffered"]=>
  string(1) "0"
  ["rows_fetched_from_client_ps_buffered"]=>
  string(1) "0"
  ["rows_fetched_from_client_ps_unbuffered"]=>
  string(1) "0"
  ["rows_fetched_from_client_ps_cursor"]=>
  string(1) "0"
  ["rows_affected_normal"]=>
  string(1) "0"
  ["rows_affected_ps"]=>
  string(1) "0"
  ["rows_skipped_normal"]=>
  string(1) "0"
  ["rows_skipped_ps"]=>
  string(1) "0"
  ["copy_on_write_saved"]=>
  string(1) "0"
  ["copy_on_write_performed"]=>
  string(1) "0"
  ["command_buffer_too_small"]=>
  string(1) "0"
  ["connect_success"]=>
  string(1) "1"
  ["connect_failure"]=>
  string(1) "0"
  ["connection_reused"]=>
  string(1) "0"
  ["reconnect"]=>
  string(1) "0"
  ["pconnect_success"]=>
  string(1) "0"
  ["active_connections"]=>
  string(1) "1"
  ["active_persistent_connections"]=>
  string(1) "0"
  ["explicit_close"]=>
  string(1) "0"
  ["implicit_close"]=>
  string(1) "0"
  ["disconnect_close"]=>
  string(1) "0"
  ["in_middle_of_command_close"]=>
  string(1) "0"
  ["explicit_free_result"]=>
  string(1) "0"
  ["implicit_free_result"]=>
  string(1) "0"
  ["explicit_stmt_close"]=>
  string(1) "0"
  ["implicit_stmt_close"]=>
  string(1) "0"
  ["mem_emalloc_count"]=>
  string(1) "0"
  ["mem_emalloc_amount"]=>
  string(1) "0"
  ["mem_ecalloc_count"]=>
  string(1) "0"
  ["mem_ecalloc_amount"]=>
  string(1) "0"
  ["mem_erealloc_count"]=>
  string(1) "0"
  ["mem_erealloc_amount"]=>
  string(1) "0"
  ["mem_efree_count"]=>
  string(1) "0"
  ["mem_efree_amount"]=>
  string(1) "0"
  ["mem_malloc_count"]=>
  string(1) "0"
  ["mem_malloc_amount"]=>
  string(1) "0"
  ["mem_calloc_count"]=>
  string(1) "0"
  ["mem_calloc_amount"]=>
  string(1) "0"
  ["mem_realloc_count"]=>
  string(1) "0"
  ["mem_realloc_amount"]=>
  string(1) "0"
  ["mem_free_count"]=>
  string(1) "0"
  ["mem_free_amount"]=>
  string(1) "0"
  ["mem_estrndup_count"]=>
  string(1) "0"
  ["mem_strndup_count"]=>
  string(1) "0"
  ["mem_estndup_count"]=>
  string(1) "0"
  ["mem_strdup_count"]=>
  string(1) "0"
  ["proto_text_fetched_null"]=>
  string(1) "0"
  ["proto_text_fetched_bit"]=>
  string(1) "0"
  ["proto_text_fetched_tinyint"]=>
  string(1) "0"
  ["proto_text_fetched_short"]=>
  string(1) "0"
  ["proto_text_fetched_int24"]=>
  string(1) "0"
  ["proto_text_fetched_int"]=>
  string(1) "0"
  ["proto_text_fetched_bigint"]=>
  string(1) "0"
  ["proto_text_fetched_decimal"]=>
  string(1) "0"
  ["proto_text_fetched_float"]=>
  string(1) "0"
  ["proto_text_fetched_double"]=>
  string(1) "0"
  ["proto_text_fetched_date"]=>
  string(1) "0"
  ["proto_text_fetched_year"]=>
  string(1) "0"
  ["proto_text_fetched_time"]=>
  string(1) "0"
  ["proto_text_fetched_datetime"]=>
  string(1) "0"
  ["proto_text_fetched_timestamp"]=>
  string(1) "0"
  ["proto_text_fetched_string"]=>
  string(1) "0"
  ["proto_text_fetched_blob"]=>
  string(1) "0"
  ["proto_text_fetched_enum"]=>
  string(1) "0"
  ["proto_text_fetched_set"]=>
  string(1) "0"
  ["proto_text_fetched_geometry"]=>
  string(1) "0"
  ["proto_text_fetched_other"]=>
  string(1) "0"
  ["proto_binary_fetched_null"]=>
  string(1) "0"
  ["proto_binary_fetched_bit"]=>
  string(1) "0"
  ["proto_binary_fetched_tinyint"]=>
  string(1) "0"
  ["proto_binary_fetched_short"]=>
  string(1) "0"
  ["proto_binary_fetched_int24"]=>
  string(1) "0"
  ["proto_binary_fetched_int"]=>
  string(1) "0"
  ["proto_binary_fetched_bigint"]=>
  string(1) "0"
  ["proto_binary_fetched_decimal"]=>
  string(1) "0"
  ["proto_binary_fetched_float"]=>
  string(1) "0"
  ["proto_binary_fetched_double"]=>
  string(1) "0"
  ["proto_binary_fetched_date"]=>
  string(1) "0"
  ["proto_binary_fetched_year"]=>
  string(1) "0"
  ["proto_binary_fetched_time"]=>
  string(1) "0"
  ["proto_binary_fetched_datetime"]=>
  string(1) "0"
  ["proto_binary_fetched_timestamp"]=>
  string(1) "0"
  ["proto_binary_fetched_string"]=>
  string(1) "0"
  ["proto_binary_fetched_blob"]=>
  string(1) "0"
  ["proto_binary_fetched_enum"]=>
  string(1) "0"
  ["proto_binary_fetched_set"]=>
  string(1) "0"
  ["proto_binary_fetched_geometry"]=>
  string(1) "0"
  ["proto_binary_fetched_other"]=>
  string(1) "0"
  ["init_command_executed_count"]=>
  string(1) "0"
  ["init_command_failed_count"]=>
  string(1) "0"
  ["com_quit"]=>
  string(1) "0"
  ["com_init_db"]=>
  string(1) "0"
  ["com_query"]=>
  string(1) "0"
  ["com_field_list"]=>
  string(1) "0"
  ["com_create_db"]=>
  string(1) "0"
  ["com_drop_db"]=>
  string(1) "0"
  ["com_refresh"]=>
  string(1) "0"
  ["com_shutdown"]=>
  string(1) "0"
  ["com_statistics"]=>
  string(1) "0"
  ["com_process_info"]=>
  string(1) "0"
  ["com_connect"]=>
  string(1) "0"
  ["com_process_kill"]=>
  string(1) "0"
  ["com_debug"]=>
  string(1) "0"
  ["com_ping"]=>
  string(1) "0"
  ["com_time"]=>
  string(1) "0"
  ["com_delayed_insert"]=>
  string(1) "0"
  ["com_change_user"]=>
  string(1) "0"
  ["com_binlog_dump"]=>
  string(1) "0"
  ["com_table_dump"]=>
  string(1) "0"
  ["com_connect_out"]=>
  string(1) "0"
  ["com_register_slave"]=>
  string(1) "0"
  ["com_stmt_prepare"]=>
  string(1) "0"
  ["com_stmt_execute"]=>
  string(1) "0"
  ["com_stmt_send_long_data"]=>
  string(1) "0"
  ["com_stmt_close"]=>
  string(1) "0"
  ["com_stmt_reset"]=>
  string(1) "0"
  ["com_stmt_set_option"]=>
  string(1) "0"
  ["com_stmt_fetch"]=>
  string(1) "0"
  ["com_deamon"]=>
  string(1) "0"
  ["bytes_received_real_data_normal"]=>
  string(1) "0"
  ["bytes_received_real_data_ps"]=>
  string(1) "0"
}

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_get_connection_stats() - Returns statistics about the client connection


Returns the thread ID for the current connection

  • « MysqlndUhConnection::getStatistics
  • MysqlndUhConnection::getWarningCount »
  • PHP Manual
  • MysqlndUhConnection
  • Returns the thread ID for the current connection

MysqlndUhConnection::getThreadId

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getThreadId — Returns the thread ID for the current connection

Description

public MysqlndUhConnection::getThreadId ( mysqlnd_connection $connection ) : int

Returns the thread ID for the current connection.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Connection thread id.

Examples

Example #1 MysqlndUhConnection::getThreadId() example

<?php
class proxy extends MysqlndUhConnection {
 public function getThreadId($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::getThreadId($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump($mysqli->thread_id);
?>

The above example will output:

proxy::getThreadId(array (
  0 => NULL,
))
proxy::getThreadId returns 27646
int(27646)

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_thread_id() - Returns the thread ID for the current connection
  • mysql_thread_id() - Return the current thread ID


Returns the number of warnings from the last query for the given link

  • « MysqlndUhConnection::getThreadId
  • MysqlndUhConnection::init »
  • PHP Manual
  • MysqlndUhConnection
  • Returns the number of warnings from the last query for the given link

MysqlndUhConnection::getWarningCount

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::getWarningCount — Returns the number of warnings from the last query for the given link

Description

public MysqlndUhConnection::getWarningCount ( mysqlnd_connection $connection ) : int

Returns the number of warnings from the last query for the given link.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Number of warnings.

Examples

Example #1 MysqlndUhConnection::getWarningCount() example

<?php
class proxy extends MysqlndUhConnection {
 public function getWarningCount($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::getWarningCount($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
var_dump($mysqli->warning_count);
?>

The above example will output:

proxy::getWarningCount(array (
  0 => NULL,
))
proxy::getWarningCount returns 0
int(0)

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_warning_count() - Returns the number of warnings from the last query for the given link


Initialize mysqlnd connection

  • « MysqlndUhConnection::getWarningCount
  • MysqlndUhConnection::killConnection »
  • PHP Manual
  • MysqlndUhConnection
  • Initialize mysqlnd connection

MysqlndUhConnection::init

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::init — Initialize mysqlnd connection

Description

public MysqlndUhConnection::init ( mysqlnd_connection $connection ) : bool

Initialize mysqlnd connection. This is an mysqlnd internal call to initialize the connection object.

Note:

Failing to call the parent implementation may cause memory leaks or crash PHP. This is not considered a bug. Please, keep in mind that the mysqlnd library functions have never been designed to be exposed to the user space.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::init() example

<?php
class proxy extends MysqlndUhConnection {
 public function init($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::init($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
?>

The above example will output:

proxy::init(array (
  0 => NULL,
))
proxy::init returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections


Asks the server to kill a MySQL thread

  • « MysqlndUhConnection::init
  • MysqlndUhConnection::listFields »
  • PHP Manual
  • MysqlndUhConnection
  • Asks the server to kill a MySQL thread

MysqlndUhConnection::killConnection

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::killConnection — Asks the server to kill a MySQL thread

Description

public MysqlndUhConnection::killConnection ( mysqlnd_connection $connection , int $pid ) : bool

Asks the server to kill a MySQL thread.

Parameters

connection

Mysqlnd connection handle. Do not modify!

pid

Thread Id of the connection to be killed.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::kill() example

<?php
class proxy extends MysqlndUhConnection {
 public function killConnection($res, $pid) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::killConnection($res, $pid);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->kill($mysqli->thread_id);
?>

The above example will output:

proxy::killConnection(array (
  0 => NULL,
  1 => 27650,
))
proxy::killConnection returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_kill() - Asks the server to kill a MySQL thread


List MySQL table fields

  • « MysqlndUhConnection::killConnection
  • MysqlndUhConnection::listMethod »
  • PHP Manual
  • MysqlndUhConnection
  • List MySQL table fields

MysqlndUhConnection::listFields

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::listFields — List MySQL table fields

Description

public MysqlndUhConnection::listFields ( mysqlnd_connection $connection , string $table , string $achtung_wild ) : array

List MySQL table fields.

Warning

This function is currently not documented; only its argument list is available.

Parameters

connection

Mysqlnd connection handle. Do not modify!

table

The name of the table that's being queried.

pattern

Name pattern.

Return Values

Examples

Example #1 MysqlndUhConnection::listFields() example

<?php
class proxy extends MysqlndUhConnection {
 public function listFields($res, $table, $pattern) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::listFields($res, $table, $pattern);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysql = mysql_connect("localhost", "root", "");
mysql_select_db("test", $mysql);
mysql_query("DROP TABLE IF EXISTS test_a", $mysql);
mysql_query("CREATE TABLE test_a(id INT, col1 VARCHAR(255))", $mysql);
$res = mysql_list_fields("test", "test_a", $mysql);
printf("num_rows = %d\n", mysql_num_rows($res));
while ($row = mysql_fetch_assoc($res))
 var_dump($row);
?>

The above example will output:

proxy::listFields(array (
  0 => NULL,
  1 => 'test_a',
  2 => '',
))
proxy::listFields returns NULL
num_rows = 0

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysql_list_fields() - List MySQL table fields


Wrapper for assorted list commands

  • « MysqlndUhConnection::listFields
  • MysqlndUhConnection::moreResults »
  • PHP Manual
  • MysqlndUhConnection
  • Wrapper for assorted list commands

MysqlndUhConnection::listMethod

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::listMethod — Wrapper for assorted list commands

Description

public MysqlndUhConnection::listMethod ( mysqlnd_connection $connection , string $query , string $achtung_wild , string $par1 ) : void

Wrapper for assorted list commands.

Warning

This function is currently not documented; only its argument list is available.

Parameters

connection

Mysqlnd connection handle. Do not modify!

query

SHOW command to be executed.

achtung_wild

par1

Return Values

Return Values

TODO

Examples

Example #1 MysqlndUhConnection::listMethod() example

<?php
class proxy extends MysqlndUhConnection {
 public function listMethod($res, $query, $pattern, $par1) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::listMethod($res, $query, $pattern, $par1);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysql = mysql_connect("localhost", "root", "");
$res = mysql_list_dbs($mysql);
printf("num_rows = %d\n", mysql_num_rows($res));
while ($row = mysql_fetch_assoc($res))
 var_dump($row);
?>

The above example will output:

proxy::listMethod(array (
  0 => NULL,
  1 => 'SHOW DATABASES',
  2 => '',
  3 => '',
))
proxy::listMethod returns NULL
num_rows = 6
array(1) {
  ["Database"]=>
  string(18) "information_schema"
}
array(1) {
  ["Database"]=>
  string(5) "mysql"
}
array(1) {
  ["Database"]=>
  string(8) "oxid_new"
}
array(1) {
  ["Database"]=>
  string(7) "phptest"
}
array(1) {
  ["Database"]=>
  string(7) "pushphp"
}
array(1) {
  ["Database"]=>
  string(4) "test"
}

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysql_list_dbs() - List databases available on a MySQL server


Check if there are any more query results from a multi query

  • « MysqlndUhConnection::listMethod
  • MysqlndUhConnection::nextResult »
  • PHP Manual
  • MysqlndUhConnection
  • Check if there are any more query results from a multi query

MysqlndUhConnection::moreResults

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::moreResults — Check if there are any more query results from a multi query

Description

public MysqlndUhConnection::moreResults ( mysqlnd_connection $connection ) : bool

Check if there are any more query results from a multi query.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::moreResults() example

<?php
class proxy extends MysqlndUhConnection {
 public function moreResults($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::moreResults($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->multi_query("SELECT 1 AS _one; SELECT 2 AS _two");
do {
  $res = $mysqli->store_result();
  var_dump($res->fetch_assoc());
  printf("%s\n", str_repeat("-", 40));
} while ($mysqli->more_results() && $mysqli->next_result());
?>

The above example will output:

array(1) {
  ["_one"]=>
  string(1) "1"
}
----------------------------------------
proxy::moreResults(array (
  0 => NULL,
))
proxy::moreResults returns true
proxy::moreResults(array (
  0 => NULL,
))
proxy::moreResults returns true
array(1) {
  ["_two"]=>
  string(1) "2"
}
----------------------------------------
proxy::moreResults(array (
  0 => NULL,
))
proxy::moreResults returns false

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_more_results() - Check if there are any more query results from a multi query


Prepare next result from multi_query

  • « MysqlndUhConnection::moreResults
  • MysqlndUhConnection::ping »
  • PHP Manual
  • MysqlndUhConnection
  • Prepare next result from multi_query

MysqlndUhConnection::nextResult

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::nextResult — Prepare next result from multi_query

Description

public MysqlndUhConnection::nextResult ( mysqlnd_connection $connection ) : bool

Prepare next result from multi_query.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::nextResult() example

<?php
class proxy extends MysqlndUhConnection {
 public function nextResult($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::nextResult($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->multi_query("SELECT 1 AS _one; SELECT 2 AS _two");
do {
  $res = $mysqli->store_result();
  var_dump($res->fetch_assoc());
  printf("%s\n", str_repeat("-", 40));
} while ($mysqli->more_results() && $mysqli->next_result());
?>

The above example will output:

array(1) {
  ["_one"]=>
  string(1) "1"
}
----------------------------------------
proxy::nextResult(array (
  0 => NULL,
))
proxy::nextResult returns true
array(1) {
  ["_two"]=>
  string(1) "2"
}
----------------------------------------

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_next_result() - Prepare next result from multi_query


Pings a server connection, or tries to reconnect if the connection has gone down

  • « MysqlndUhConnection::nextResult
  • MysqlndUhConnection::query »
  • PHP Manual
  • MysqlndUhConnection
  • Pings a server connection, or tries to reconnect if the connection has gone down

MysqlndUhConnection::ping

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::ping — Pings a server connection, or tries to reconnect if the connection has gone down

Description

public MysqlndUhConnection::ping ( mysqlnd_connection $connection ) : bool

Pings a server connection, or tries to reconnect if the connection has gone down.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::ping() example

<?php
class proxy extends MysqlndUhConnection {
 public function ping($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::ping($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->ping();
?>

The above example will output:

proxy::ping(array (
  0 => NULL,
))
proxy::ping returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_ping() - Pings a server connection, or tries to reconnect if the connection has gone down
  • mysql_ping() - Ping a server connection or reconnect if there is no connection


Performs a query on the database

  • « MysqlndUhConnection::ping
  • MysqlndUhConnection::queryReadResultsetHeader »
  • PHP Manual
  • MysqlndUhConnection
  • Performs a query on the database

MysqlndUhConnection::query

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::query — Performs a query on the database

Description

public MysqlndUhConnection::query ( mysqlnd_connection $connection , string $query ) : bool

Performs a query on the database (COM_QUERY).

Parameters

connection

Mysqlnd connection handle. Do not modify!

query

The query string.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::query() example

<?php
class proxy extends MysqlndUhConnection {
 public function query($res, $query) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $query = "SELECT 'How about query rewriting?'";
  $ret = parent::query($res, $query);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$res = $mysqli->query("SELECT 'Welcome mysqlnd_uh!' FROM DUAL");
var_dump($res->fetch_assoc());
?>

The above example will output:

proxy::query(array (
  0 => NULL,
  1 => 'SELECT \'Welcome mysqlnd_uh!\' FROM DUAL',
))
proxy::query returns true
array(1) {
  ["How about query rewriting?"]=>
  string(26) "How about query rewriting?"
}

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_query() - Performs a query on the database
  • mysql_query() - Send a MySQL query


Read a result set header

  • « MysqlndUhConnection::query
  • MysqlndUhConnection::reapQuery »
  • PHP Manual
  • MysqlndUhConnection
  • Read a result set header

MysqlndUhConnection::queryReadResultsetHeader

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::queryReadResultsetHeader — Read a result set header

Description

public MysqlndUhConnection::queryReadResultsetHeader ( mysqlnd_connection $connection , mysqlnd_statement $mysqlnd_stmt ) : bool

Read a result set header.

Parameters

connection

Mysqlnd connection handle. Do not modify!

mysqlnd_stmt

Mysqlnd statement handle. Do not modify! Set to NULL, if function is not used in the context of a prepared statement.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::queryReadResultsetHeader() example

<?php
class proxy extends MysqlndUhConnection {
 public function queryReadResultsetHeader($res, $stmt) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::queryReadResultsetHeader($res, $stmt);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$res = $mysqli->query("SELECT 'Welcome mysqlnd_uh!' FROM DUAL");
var_dump($res->fetch_assoc());
?>

The above example will output:

proxy::queryReadResultsetHeader(array (
  0 => NULL,
  1 => NULL,
))
proxy::queryReadResultsetHeader returns true
array(1) {
  ["Welcome mysqlnd_uh!"]=>
  string(19) "Welcome mysqlnd_uh!"
}

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections


Get result from async query

  • « MysqlndUhConnection::queryReadResultsetHeader
  • MysqlndUhConnection::refreshServer »
  • PHP Manual
  • MysqlndUhConnection
  • Get result from async query

MysqlndUhConnection::reapQuery

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::reapQuery — Get result from async query

Description

public MysqlndUhConnection::reapQuery ( mysqlnd_connection $connection ) : bool

Get result from async query.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::reapQuery() example

<?php
class proxy extends MysqlndUhConnection {
 public function reapQuery($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::reapQuery($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$conn1 = new mysqli("localhost", "root", "", "test");
$conn2 = new mysqli("localhost", "root", "", "test");

$conn1->query("SELECT 1 as 'one', SLEEP(1) AS _sleep FROM DUAL", MYSQLI_ASYNC |  MYSQLI_USE_RESULT);
$conn2->query("SELECT 1.1 as 'one dot one' FROM DUAL", MYSQLI_ASYNC |  MYSQLI_USE_RESULT);

$links = array(
 $conn1->thread_id => array('link' => $conn1, 'processed' => false),
 $conn2->thread_id => array('link' => $conn2, 'processed' => false)
);

$saved_errors = array();
do {
 $poll_links = $poll_errors = $poll_reject = array();
 foreach ($links as $thread_id => $link) {
  if (!$link['processed']) {
   $poll_links[] = $link['link'];
   $poll_errors[] = $link['link'];
   $poll_reject[] = $link['link'];
  }
 }
 if (0 == count($poll_links))
  break;

 if (0 == ($num_ready = mysqli_poll($poll_links, $poll_errors, $poll_reject, 0, 200000)))
  continue;

 if (!empty($poll_errors)) {
  die(var_dump($poll_errors));
 }

 foreach ($poll_links as $link) {
  $thread_id = mysqli_thread_id($link);
  $links[$thread_id]['processed'] = true;

  if (is_object($res = mysqli_reap_async_query($link))) {
   // result set object
   while ($row = mysqli_fetch_assoc($res)) {
    // eat up all results
    var_dump($row);
   }
   mysqli_free_result($res);
  } else {
   // either there is no result (no SELECT) or there is an error
   if (mysqli_errno($link) > 0) {
    $saved_errors[$thread_id] = mysqli_errno($link);
    printf("'%s' caused %d\n", $links[$thread_id]['query'],     mysqli_errno($link));
   }
  }
 }
} while (true);
?>

The above example will output:

proxy::reapQuery(array (
  0 => NULL,
))
proxy::reapQuery returns true
array(1) {
  ["one dot one"]=>
  string(3) "1.1"
}
proxy::reapQuery(array (
  0 => NULL,
))
proxy::reapQuery returns true
array(2) {
  ["one"]=>
  string(1) "1"
  ["_sleep"]=>
  string(1) "0"
}

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_real_async_query()


Flush or reset tables and caches

  • « MysqlndUhConnection::reapQuery
  • MysqlndUhConnection::restartPSession »
  • PHP Manual
  • MysqlndUhConnection
  • Flush or reset tables and caches

MysqlndUhConnection::refreshServer

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::refreshServer — Flush or reset tables and caches

Description

public MysqlndUhConnection::refreshServer ( mysqlnd_connection $connection , int $options ) : bool

Flush or reset tables and caches.

Warning

This function is currently not documented; only its argument list is available.

Parameters

connection

Mysqlnd connection handle. Do not modify!

options

What to refresh.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::refreshServer() example

<?php
class proxy extends MysqlndUhConnection {
 public function refreshServer($res, $option) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::refreshServer($res, $option);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
mysqli_refresh($mysqli, 1);
?>

The above example will output:

proxy::refreshServer(array (
  0 => NULL,
  1 => 1,
))
proxy::refreshServer returns false

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections


Restart a persistent mysqlnd connection

  • « MysqlndUhConnection::refreshServer
  • MysqlndUhConnection::selectDb »
  • PHP Manual
  • MysqlndUhConnection
  • Restart a persistent mysqlnd connection

MysqlndUhConnection::restartPSession

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::restartPSession — Restart a persistent mysqlnd connection

Description

public MysqlndUhConnection::restartPSession ( mysqlnd_connection $connection ) : bool

Restart a persistent mysqlnd connection.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::restartPSession() example

<?php
class proxy extends MysqlndUhConnection {
 public function ping($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::ping($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->ping();
?>

The above example will output:

proxy::restartPSession(array (
  0 => NULL,
))
proxy::restartPSession returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections


Selects the default database for database queries

  • « MysqlndUhConnection::restartPSession
  • MysqlndUhConnection::sendClose »
  • PHP Manual
  • MysqlndUhConnection
  • Selects the default database for database queries

MysqlndUhConnection::selectDb

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::selectDb — Selects the default database for database queries

Description

public MysqlndUhConnection::selectDb ( mysqlnd_connection $connection , string $database ) : bool

Selects the default database for database queries.

Parameters

connection

Mysqlnd connection handle. Do not modify!

database

The database name.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::selectDb() example

<?php
class proxy extends MysqlndUhConnection {
 public function selectDb($res, $database) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::selectDb($res, $database);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->select_db("mysql");
?>

The above example will output:

proxy::selectDb(array (
  0 => NULL,
  1 => 'mysql',
))
proxy::selectDb returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_select_db() - Selects the default database for database queries
  • mysql_select_db() - Select a MySQL database


Sends a close command to MySQL

  • « MysqlndUhConnection::selectDb
  • MysqlndUhConnection::sendQuery »
  • PHP Manual
  • MysqlndUhConnection
  • Sends a close command to MySQL

MysqlndUhConnection::sendClose

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::sendClose — Sends a close command to MySQL

Description

public MysqlndUhConnection::sendClose ( mysqlnd_connection $connection ) : bool

Sends a close command to MySQL.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::sendClose() example

<?php
class proxy extends MysqlndUhConnection {
 public function sendClose($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::sendClose($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->close();
?>

The above example will output:

proxy::sendClose(array (
  0 => NULL,
))
proxy::sendClose returns true
proxy::sendClose(array (
  0 => NULL,
))
proxy::sendClose returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections


Sends a query to MySQL

  • « MysqlndUhConnection::sendClose
  • MysqlndUhConnection::serverDumpDebugInformation »
  • PHP Manual
  • MysqlndUhConnection
  • Sends a query to MySQL

MysqlndUhConnection::sendQuery

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::sendQuery — Sends a query to MySQL

Description

public MysqlndUhConnection::sendQuery ( mysqlnd_connection $connection , string $query ) : bool

Sends a query to MySQL.

Parameters

connection

Mysqlnd connection handle. Do not modify!

query

The query string.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::sendQuery() example

<?php
class proxy extends MysqlndUhConnection {
 public function sendQuery($res, $query) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::sendQuery($res, $query);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->query("SELECT 1");
?>

The above example will output:

proxy::sendQuery(array (
  0 => NULL,
  1 => 'SELECT 1',
))
proxy::sendQuery returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections


Dump debugging information into the log for the MySQL server

  • « MysqlndUhConnection::sendQuery
  • MysqlndUhConnection::setAutocommit »
  • PHP Manual
  • MysqlndUhConnection
  • Dump debugging information into the log for the MySQL server

MysqlndUhConnection::serverDumpDebugInformation

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::serverDumpDebugInformation — Dump debugging information into the log for the MySQL server

Description

public MysqlndUhConnection::serverDumpDebugInformation ( mysqlnd_connection $connection ) : bool

Dump debugging information into the log for the MySQL server.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::serverDumpDebugInformation() example

<?php
class proxy extends MysqlndUhConnection {
 public function serverDumpDebugInformation($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::serverDumpDebugInformation($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->dump_debug_info();
?>

The above example will output:

proxy::serverDumpDebugInformation(array (
  0 => NULL,
))
proxy::serverDumpDebugInformation returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_dump_debug_info() - Dump debugging information into the log


Turns on or off auto-committing database modifications

  • « MysqlndUhConnection::serverDumpDebugInformation
  • MysqlndUhConnection::setCharset »
  • PHP Manual
  • MysqlndUhConnection
  • Turns on or off auto-committing database modifications

MysqlndUhConnection::setAutocommit

(PECL mysqlnd-uh >= 1.0.1-alpha)

MysqlndUhConnection::setAutocommit — Turns on or off auto-committing database modifications

Description

public MysqlndUhConnection::setAutocommit ( mysqlnd_connection $connection , int $mode ) : bool

Turns on or off auto-committing database modifications

Parameters

connection

Mysqlnd connection handle. Do not modify!

mode

Whether to turn on auto-commit or not.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::setAutocommit() example

<?php
class proxy extends MysqlndUhConnection {
 public function setAutocommit($res, $mode) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::setAutocommit($res, $mode);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->autocommit(false);
$mysqli->autocommit(true);
?>

The above example will output:

proxy::setAutocommit(array (
  0 => NULL,
  1 => 0,
))
proxy::setAutocommit returns true
proxy::setAutocommit(array (
  0 => NULL,
  1 => 1,
))
proxy::setAutocommit returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_autocommit() - Turns on or off auto-committing database modifications


Sets the default client character set

  • « MysqlndUhConnection::setAutocommit
  • MysqlndUhConnection::setClientOption »
  • PHP Manual
  • MysqlndUhConnection
  • Sets the default client character set

MysqlndUhConnection::setCharset

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::setCharset — Sets the default client character set

Description

public MysqlndUhConnection::setCharset ( mysqlnd_connection $connection , string $charset ) : bool

Sets the default client character set.

Parameters

connection

Mysqlnd connection handle. Do not modify!

charset

The charset to be set as default.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::setCharset() example

<?php
class proxy extends MysqlndUhConnection {
 public function setCharset($res, $charset) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::setCharset($res, $charset);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->set_charset("latin1");
?>

The above example will output:

proxy::setCharset(array (
  0 => NULL,
  1 => 'latin1',
))
proxy::setCharset returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_set_charset() - Sets the default client character set


Sets a client option

  • « MysqlndUhConnection::setCharset
  • MysqlndUhConnection::setServerOption »
  • PHP Manual
  • MysqlndUhConnection
  • Sets a client option

MysqlndUhConnection::setClientOption

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::setClientOption — Sets a client option

Description

public MysqlndUhConnection::setClientOption ( mysqlnd_connection $connection , int $option , int $value ) : bool

Sets a client option.

Parameters

connection

Mysqlnd connection handle. Do not modify!

option

The option to be set.

value

Optional option value, if required.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::setClientOption() example

<?php
function client_option_to_string($option) {
 static $mapping = array(
  MYSQLND_UH_MYSQLND_OPTION_OPT_CONNECT_TIMEOUT => "MYSQLND_UH_MYSQLND_OPTION_OPT_CONNECT_TIMEOUT",
  MYSQLND_UH_MYSQLND_OPTION_OPT_COMPRESS => "MYSQLND_UH_MYSQLND_OPTION_OPT_COMPRESS",
  MYSQLND_UH_MYSQLND_OPTION_OPT_NAMED_PIPE => "MYSQLND_UH_MYSQLND_OPTION_OPT_NAMED_PIPE",
  MYSQLND_UH_MYSQLND_OPTION_INIT_COMMAND => "MYSQLND_UH_MYSQLND_OPTION_INIT_COMMAND",
  MYSQLND_UH_MYSQLND_READ_DEFAULT_FILE => "MYSQLND_UH_MYSQLND_READ_DEFAULT_FILE",
  MYSQLND_UH_MYSQLND_READ_DEFAULT_GROUP => "MYSQLND_UH_MYSQLND_READ_DEFAULT_GROUP",
  MYSQLND_UH_MYSQLND_SET_CHARSET_DIR => "MYSQLND_UH_MYSQLND_SET_CHARSET_DIR",
  MYSQLND_UH_MYSQLND_SET_CHARSET_NAME => "MYSQLND_UH_MYSQLND_SET_CHARSET_NAME",
  MYSQLND_UH_MYSQLND_OPT_LOCAL_INFILE => "MYSQLND_UH_MYSQLND_OPT_LOCAL_INFILE",
  MYSQLND_UH_MYSQLND_OPT_PROTOCOL => "MYSQLND_UH_MYSQLND_OPT_PROTOCOL",
  MYSQLND_UH_MYSQLND_SHARED_MEMORY_BASE_NAME => "MYSQLND_UH_MYSQLND_SHARED_MEMORY_BASE_NAME",
  MYSQLND_UH_MYSQLND_OPT_READ_TIMEOUT => "MYSQLND_UH_MYSQLND_OPT_READ_TIMEOUT",
  MYSQLND_UH_MYSQLND_OPT_WRITE_TIMEOUT => "MYSQLND_UH_MYSQLND_OPT_WRITE_TIMEOUT",
  MYSQLND_UH_MYSQLND_OPT_USE_RESULT => "MYSQLND_UH_MYSQLND_OPT_USE_RESULT",
  MYSQLND_UH_MYSQLND_OPT_USE_REMOTE_CONNECTION => "MYSQLND_UH_MYSQLND_OPT_USE_REMOTE_CONNECTION",
  MYSQLND_UH_MYSQLND_OPT_USE_EMBEDDED_CONNECTION => "MYSQLND_UH_MYSQLND_OPT_USE_EMBEDDED_CONNECTION",
  MYSQLND_UH_MYSQLND_OPT_GUESS_CONNECTION => "MYSQLND_UH_MYSQLND_OPT_GUESS_CONNECTION",
  MYSQLND_UH_MYSQLND_SET_CLIENT_IP => "MYSQLND_UH_MYSQLND_SET_CLIENT_IP",
  MYSQLND_UH_MYSQLND_SECURE_AUTH => "MYSQLND_UH_MYSQLND_SECURE_AUTH",
  MYSQLND_UH_MYSQLND_REPORT_DATA_TRUNCATION => "MYSQLND_UH_MYSQLND_REPORT_DATA_TRUNCATION",
  MYSQLND_UH_MYSQLND_OPT_RECONNECT => "MYSQLND_UH_MYSQLND_OPT_RECONNECT",
  MYSQLND_UH_MYSQLND_OPT_SSL_VERIFY_SERVER_CERT => "MYSQLND_UH_MYSQLND_OPT_SSL_VERIFY_SERVER_CERT",
  MYSQLND_UH_MYSQLND_OPT_NET_CMD_BUFFER_SIZE => "MYSQLND_UH_MYSQLND_OPT_NET_CMD_BUFFER_SIZE",
  MYSQLND_UH_MYSQLND_OPT_NET_READ_BUFFER_SIZE => "MYSQLND_UH_MYSQLND_OPT_NET_READ_BUFFER_SIZE",
  MYSQLND_UH_MYSQLND_OPT_SSL_KEY => "MYSQLND_UH_MYSQLND_OPT_SSL_KEY",
  MYSQLND_UH_MYSQLND_OPT_SSL_CERT => "MYSQLND_UH_MYSQLND_OPT_SSL_CERT",
  MYSQLND_UH_MYSQLND_OPT_SSL_CA => "MYSQLND_UH_MYSQLND_OPT_SSL_CA",
  MYSQLND_UH_MYSQLND_OPT_SSL_CAPATH => "MYSQLND_UH_MYSQLND_OPT_SSL_CAPATH",
  MYSQLND_UH_MYSQLND_OPT_SSL_CIPHER => "MYSQLND_UH_MYSQLND_OPT_SSL_CIPHER",
  MYSQLND_UH_MYSQLND_OPT_SSL_PASSPHRASE => "MYSQLND_UH_MYSQLND_OPT_SSL_PASSPHRASE",
  MYSQLND_UH_SERVER_OPTION_PLUGIN_DIR => "MYSQLND_UH_SERVER_OPTION_PLUGIN_DIR",
  MYSQLND_UH_SERVER_OPTION_DEFAULT_AUTH => "MYSQLND_UH_SERVER_OPTION_DEFAULT_AUTH",
  MYSQLND_UH_SERVER_OPTION_SET_CLIENT_IP => "MYSQLND_UH_SERVER_OPTION_SET_CLIENT_IP"
 );
 if (version_compare(PHP_VERSION, '5.3.99-dev', '>')) {
  $mapping[MYSQLND_UH_MYSQLND_OPT_MAX_ALLOWED_PACKET] = "MYSQLND_UH_MYSQLND_OPT_MAX_ALLOWED_PACKET";
  $mapping[MYSQLND_UH_MYSQLND_OPT_AUTH_PROTOCOL] = "MYSQLND_UH_MYSQLND_OPT_AUTH_PROTOCOL";
 }
 if (defined("MYSQLND_UH_MYSQLND_OPT_INT_AND_FLOAT_NATIVE")) {
  /* special mysqlnd build */
  $mapping["MYSQLND_UH_MYSQLND_OPT_INT_AND_FLOAT_NATIVE"] = "MYSQLND_UH_MYSQLND_OPT_INT_AND_FLOAT_NATIVE";
 }
 return (isset($mapping[$option])) ? $mapping[$option] : 'unknown';
}

class proxy extends MysqlndUhConnection {
 public function setClientOption($res, $option, $value) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  printf("Option '%s' set to %s\n", client_option_to_string($option), var_export($value, true));
  $ret = parent::setClientOption($res, $option, $value);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
?>

The above example will output:

proxy::setClientOption(array (
  0 => NULL,
  1 => 210,
  2 => 3221225472,
))
Option 'MYSQLND_UH_MYSQLND_OPT_MAX_ALLOWED_PACKET' set to 3221225472
proxy::setClientOption returns true
proxy::setClientOption(array (
  0 => NULL,
  1 => 211,
  2 => 'mysql_native_password',
))
Option 'MYSQLND_UH_MYSQLND_OPT_AUTH_PROTOCOL' set to 'mysql_native_password'
proxy::setClientOption returns true
proxy::setClientOption(array (
  0 => NULL,
  1 => 8,
  2 => 1,
))
Option 'MYSQLND_UH_MYSQLND_OPT_LOCAL_INFILE' set to 1
proxy::setClientOption returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_real_connect() - Opens a connection to a mysql server
  • mysqli_options() - Set options


Sets a server option

  • « MysqlndUhConnection::setClientOption
  • MysqlndUhConnection::shutdownServer »
  • PHP Manual
  • MysqlndUhConnection
  • Sets a server option

MysqlndUhConnection::setServerOption

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::setServerOption — Sets a server option

Description

public MysqlndUhConnection::setServerOption ( mysqlnd_connection $connection , int $option ) : void

Sets a server option.

Parameters

connection

Mysqlnd connection handle. Do not modify!

option

The option to be set.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::setServerOption() example

<?php
function server_option_to_string($option) {
 $ret = 'unknown';
 switch ($option) {
  case MYSQLND_UH_SERVER_OPTION_MULTI_STATEMENTS_ON:
   $ret = 'MYSQLND_UH_SERVER_OPTION_MULTI_STATEMENTS_ON';
   break;
  case MYSQLND_UH_SERVER_OPTION_MULTI_STATEMENTS_OFF:
   $ret = 'MYSQLND_UH_SERVER_OPTION_MULTI_STATEMENTS_ON';
   break;
 }
 return $ret;
}

class proxy extends MysqlndUhConnection {
 public function setServerOption($res, $option) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  printf("Option '%s' set\n", server_option_to_string($option));
  $ret = parent::setServerOption($res, $option);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->multi_query("SELECT 1; SELECT 2");
?>

The above example will output:

proxy::setServerOption(array (
  0 => NULL,
  1 => 0,
))
Option 'MYSQLND_UH_SERVER_OPTION_MULTI_STATEMENTS_ON' set
proxy::setServerOption returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_real_connect() - Opens a connection to a mysql server
  • mysqli_options() - Set options
  • mysqli_multi_query() - Performs a query on the database


The shutdownServer purpose

  • « MysqlndUhConnection::setServerOption
  • MysqlndUhConnection::simpleCommand »
  • PHP Manual
  • MysqlndUhConnection
  • The shutdownServer purpose

MysqlndUhConnection::shutdownServer

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::shutdownServer — The shutdownServer purpose

Description

public MysqlndUhConnection::shutdownServer ( string $MYSQLND_UH_RES_MYSQLND_NAME , string $level ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

MYSQLND_UH_RES_MYSQLND_NAME

level

Return Values


Sends a basic COM_* command

  • « MysqlndUhConnection::shutdownServer
  • MysqlndUhConnection::simpleCommandHandleResponse »
  • PHP Manual
  • MysqlndUhConnection
  • Sends a basic COM_* command

MysqlndUhConnection::simpleCommand

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::simpleCommand — Sends a basic COM_* command

Description

public MysqlndUhConnection::simpleCommand ( mysqlnd_connection $connection , int $command , string $arg , int $ok_packet , bool $silent , bool $ignore_upsert_status ) : bool

Sends a basic COM_* command to MySQL.

Parameters

connection

Mysqlnd connection handle. Do not modify!

command

The COM command to be send.

arg

Optional COM command arguments.

ok_packet

The OK packet type.

silent

Whether mysqlnd may emit errors.

ignore_upsert_status

Whether to ignore UPDATE/INSERT status.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::simpleCommand() example

<?php
function server_cmd_2_string($command) {
 $mapping = array(
  MYSQLND_UH_MYSQLND_COM_SLEEP => "MYSQLND_UH_MYSQLND_COM_SLEEP",
  MYSQLND_UH_MYSQLND_COM_QUIT => "MYSQLND_UH_MYSQLND_COM_QUIT",
  MYSQLND_UH_MYSQLND_COM_INIT_DB => "MYSQLND_UH_MYSQLND_COM_INIT_DB",
  MYSQLND_UH_MYSQLND_COM_QUERY => "MYSQLND_UH_MYSQLND_COM_QUERY",
  MYSQLND_UH_MYSQLND_COM_FIELD_LIST => "MYSQLND_UH_MYSQLND_COM_FIELD_LIST",
  MYSQLND_UH_MYSQLND_COM_CREATE_DB => "MYSQLND_UH_MYSQLND_COM_CREATE_DB",
  MYSQLND_UH_MYSQLND_COM_DROP_DB => "MYSQLND_UH_MYSQLND_COM_DROP_DB",
  MYSQLND_UH_MYSQLND_COM_REFRESH => "MYSQLND_UH_MYSQLND_COM_REFRESH",
  MYSQLND_UH_MYSQLND_COM_SHUTDOWN => "MYSQLND_UH_MYSQLND_COM_SHUTDOWN",
  MYSQLND_UH_MYSQLND_COM_STATISTICS => "MYSQLND_UH_MYSQLND_COM_STATISTICS",
  MYSQLND_UH_MYSQLND_COM_PROCESS_INFO => "MYSQLND_UH_MYSQLND_COM_PROCESS_INFO",
  MYSQLND_UH_MYSQLND_COM_CONNECT => "MYSQLND_UH_MYSQLND_COM_CONNECT",
  MYSQLND_UH_MYSQLND_COM_PROCESS_KILL => "MYSQLND_UH_MYSQLND_COM_PROCESS_KILL",
  MYSQLND_UH_MYSQLND_COM_DEBUG => "MYSQLND_UH_MYSQLND_COM_DEBUG",
  MYSQLND_UH_MYSQLND_COM_PING => "MYSQLND_UH_MYSQLND_COM_PING",
  MYSQLND_UH_MYSQLND_COM_TIME => "MYSQLND_UH_MYSQLND_COM_TIME",
  MYSQLND_UH_MYSQLND_COM_DELAYED_INSERT => "MYSQLND_UH_MYSQLND_COM_DELAYED_INSERT",
  MYSQLND_UH_MYSQLND_COM_CHANGE_USER => "MYSQLND_UH_MYSQLND_COM_CHANGE_USER",
  MYSQLND_UH_MYSQLND_COM_BINLOG_DUMP => "MYSQLND_UH_MYSQLND_COM_BINLOG_DUMP",
  MYSQLND_UH_MYSQLND_COM_TABLE_DUMP => "MYSQLND_UH_MYSQLND_COM_TABLE_DUMP",
  MYSQLND_UH_MYSQLND_COM_CONNECT_OUT => "MYSQLND_UH_MYSQLND_COM_CONNECT_OUT",
  MYSQLND_UH_MYSQLND_COM_REGISTER_SLAVED => "MYSQLND_UH_MYSQLND_COM_REGISTER_SLAVED",
  MYSQLND_UH_MYSQLND_COM_STMT_PREPARE => "MYSQLND_UH_MYSQLND_COM_STMT_PREPARE",
  MYSQLND_UH_MYSQLND_COM_STMT_EXECUTE => "MYSQLND_UH_MYSQLND_COM_STMT_EXECUTE",
  MYSQLND_UH_MYSQLND_COM_STMT_SEND_LONG_DATA => "MYSQLND_UH_MYSQLND_COM_STMT_SEND_LONG_DATA",
  MYSQLND_UH_MYSQLND_COM_STMT_CLOSE => "MYSQLND_UH_MYSQLND_COM_STMT_CLOSE",
  MYSQLND_UH_MYSQLND_COM_STMT_RESET => "MYSQLND_UH_MYSQLND_COM_STMT_RESET",
  MYSQLND_UH_MYSQLND_COM_SET_OPTION => "MYSQLND_UH_MYSQLND_COM_SET_OPTION",
  MYSQLND_UH_MYSQLND_COM_STMT_FETCH => "MYSQLND_UH_MYSQLND_COM_STMT_FETCH",
  MYSQLND_UH_MYSQLND_COM_DAEMON => "MYSQLND_UH_MYSQLND_COM_DAEMON",
  MYSQLND_UH_MYSQLND_COM_END => "MYSQLND_UH_MYSQLND_COM_END",
 );
 return (isset($mapping[$command])) ? $mapping[$command] : 'unknown';
}

function ok_packet_2_string($ok_packet) {
 $mapping = array(
  MYSQLND_UH_MYSQLND_PROT_GREET_PACKET => "MYSQLND_UH_MYSQLND_PROT_GREET_PACKET",
  MYSQLND_UH_MYSQLND_PROT_AUTH_PACKET => "MYSQLND_UH_MYSQLND_PROT_AUTH_PACKET",
  MYSQLND_UH_MYSQLND_PROT_OK_PACKET => "MYSQLND_UH_MYSQLND_PROT_OK_PACKET",
  MYSQLND_UH_MYSQLND_PROT_EOF_PACKET => "MYSQLND_UH_MYSQLND_PROT_EOF_PACKET",
  MYSQLND_UH_MYSQLND_PROT_CMD_PACKET => "MYSQLND_UH_MYSQLND_PROT_CMD_PACKET",
  MYSQLND_UH_MYSQLND_PROT_RSET_HEADER_PACKET => "MYSQLND_UH_MYSQLND_PROT_RSET_HEADER_PACKET",
  MYSQLND_UH_MYSQLND_PROT_RSET_FLD_PACKET => "MYSQLND_UH_MYSQLND_PROT_RSET_FLD_PACKET",
  MYSQLND_UH_MYSQLND_PROT_ROW_PACKET => "MYSQLND_UH_MYSQLND_PROT_ROW_PACKET",
  MYSQLND_UH_MYSQLND_PROT_STATS_PACKET => "MYSQLND_UH_MYSQLND_PROT_STATS_PACKET",
  MYSQLND_UH_MYSQLND_PREPARE_RESP_PACKET => "MYSQLND_UH_MYSQLND_PREPARE_RESP_PACKET",
  MYSQLND_UH_MYSQLND_CHG_USER_RESP_PACKET => "MYSQLND_UH_MYSQLND_CHG_USER_RESP_PACKET",
  MYSQLND_UH_MYSQLND_PROT_LAST => "MYSQLND_UH_MYSQLND_PROT_LAST",
 );
 return (isset($mapping[$ok_packet])) ? $mapping[$ok_packet] : 'unknown';
}

class proxy extends MysqlndUhConnection {
 public function simpleCommand($conn, $command, $arg, $ok_packet, $silent, $ignore_upsert_status) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  printf("Command '%s'\n", server_cmd_2_string($command));
  printf("OK packet '%s'\n",  ok_packet_2_string($ok_packet));
  $ret = parent::simpleCommand($conn, $command, $arg, $ok_packet, $silent, $ignore_upsert_status);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->query("SELECT 1");
?>

The above example will output:

proxy::simpleCommand(array (
  0 => NULL,
  1 => 3,
  2 => 'SELECT 1',
  3 => 13,
  4 => false,
  5 => false,
))
Command 'MYSQLND_UH_MYSQLND_COM_QUERY'
OK packet 'MYSQLND_UH_MYSQLND_PROT_LAST'
proxy::simpleCommand returns true
:)proxy::simpleCommand(array (
  0 => NULL,
  1 => 1,
  2 => '',
  3 => 13,
  4 => true,
  5 => true,
))
Command 'MYSQLND_UH_MYSQLND_COM_QUIT'
OK packet 'MYSQLND_UH_MYSQLND_PROT_LAST'
proxy::simpleCommand returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections


Process a response for a basic COM_* command send to the client

  • « MysqlndUhConnection::simpleCommand
  • MysqlndUhConnection::sslSet »
  • PHP Manual
  • MysqlndUhConnection
  • Process a response for a basic COM_* command send to the client

MysqlndUhConnection::simpleCommandHandleResponse

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::simpleCommandHandleResponse — Process a response for a basic COM_* command send to the client

Description

public MysqlndUhConnection::simpleCommandHandleResponse ( mysqlnd_connection $connection , int $ok_packet , bool $silent , int $command , bool $ignore_upsert_status ) : bool

Process a response for a basic COM_* command send to the client.

Parameters

connection

Mysqlnd connection handle. Do not modify!

ok_packet

The OK packet type.

silent

Whether mysqlnd may emit errors.

command

The COM command to process results from.

ignore_upsert_status

Whether to ignore UPDATE/INSERT status.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::simpleCommandHandleResponse() example

<?php
function server_cmd_2_string($command) {
 $mapping = array(
  MYSQLND_UH_MYSQLND_COM_SLEEP => "MYSQLND_UH_MYSQLND_COM_SLEEP",
  MYSQLND_UH_MYSQLND_COM_QUIT => "MYSQLND_UH_MYSQLND_COM_QUIT",
  MYSQLND_UH_MYSQLND_COM_INIT_DB => "MYSQLND_UH_MYSQLND_COM_INIT_DB",
  MYSQLND_UH_MYSQLND_COM_QUERY => "MYSQLND_UH_MYSQLND_COM_QUERY",
  MYSQLND_UH_MYSQLND_COM_FIELD_LIST => "MYSQLND_UH_MYSQLND_COM_FIELD_LIST",
  MYSQLND_UH_MYSQLND_COM_CREATE_DB => "MYSQLND_UH_MYSQLND_COM_CREATE_DB",
  MYSQLND_UH_MYSQLND_COM_DROP_DB => "MYSQLND_UH_MYSQLND_COM_DROP_DB",
  MYSQLND_UH_MYSQLND_COM_REFRESH => "MYSQLND_UH_MYSQLND_COM_REFRESH",
  MYSQLND_UH_MYSQLND_COM_SHUTDOWN => "MYSQLND_UH_MYSQLND_COM_SHUTDOWN",
  MYSQLND_UH_MYSQLND_COM_STATISTICS => "MYSQLND_UH_MYSQLND_COM_STATISTICS",
  MYSQLND_UH_MYSQLND_COM_PROCESS_INFO => "MYSQLND_UH_MYSQLND_COM_PROCESS_INFO",
  MYSQLND_UH_MYSQLND_COM_CONNECT => "MYSQLND_UH_MYSQLND_COM_CONNECT",
  MYSQLND_UH_MYSQLND_COM_PROCESS_KILL => "MYSQLND_UH_MYSQLND_COM_PROCESS_KILL",
  MYSQLND_UH_MYSQLND_COM_DEBUG => "MYSQLND_UH_MYSQLND_COM_DEBUG",
  MYSQLND_UH_MYSQLND_COM_PING => "MYSQLND_UH_MYSQLND_COM_PING",
  MYSQLND_UH_MYSQLND_COM_TIME => "MYSQLND_UH_MYSQLND_COM_TIME",
  MYSQLND_UH_MYSQLND_COM_DELAYED_INSERT => "MYSQLND_UH_MYSQLND_COM_DELAYED_INSERT",
  MYSQLND_UH_MYSQLND_COM_CHANGE_USER => "MYSQLND_UH_MYSQLND_COM_CHANGE_USER",
  MYSQLND_UH_MYSQLND_COM_BINLOG_DUMP => "MYSQLND_UH_MYSQLND_COM_BINLOG_DUMP",
  MYSQLND_UH_MYSQLND_COM_TABLE_DUMP => "MYSQLND_UH_MYSQLND_COM_TABLE_DUMP",
  MYSQLND_UH_MYSQLND_COM_CONNECT_OUT => "MYSQLND_UH_MYSQLND_COM_CONNECT_OUT",
  MYSQLND_UH_MYSQLND_COM_REGISTER_SLAVED => "MYSQLND_UH_MYSQLND_COM_REGISTER_SLAVED",
  MYSQLND_UH_MYSQLND_COM_STMT_PREPARE => "MYSQLND_UH_MYSQLND_COM_STMT_PREPARE",
  MYSQLND_UH_MYSQLND_COM_STMT_EXECUTE => "MYSQLND_UH_MYSQLND_COM_STMT_EXECUTE",
  MYSQLND_UH_MYSQLND_COM_STMT_SEND_LONG_DATA => "MYSQLND_UH_MYSQLND_COM_STMT_SEND_LONG_DATA",
  MYSQLND_UH_MYSQLND_COM_STMT_CLOSE => "MYSQLND_UH_MYSQLND_COM_STMT_CLOSE",
  MYSQLND_UH_MYSQLND_COM_STMT_RESET => "MYSQLND_UH_MYSQLND_COM_STMT_RESET",
  MYSQLND_UH_MYSQLND_COM_SET_OPTION => "MYSQLND_UH_MYSQLND_COM_SET_OPTION",
  MYSQLND_UH_MYSQLND_COM_STMT_FETCH => "MYSQLND_UH_MYSQLND_COM_STMT_FETCH",
  MYSQLND_UH_MYSQLND_COM_DAEMON => "MYSQLND_UH_MYSQLND_COM_DAEMON",
  MYSQLND_UH_MYSQLND_COM_END => "MYSQLND_UH_MYSQLND_COM_END",
 );
 return (isset($mapping[$command])) ? $mapping[$command] : 'unknown';
}

function ok_packet_2_string($ok_packet) {
 $mapping = array(
  MYSQLND_UH_MYSQLND_PROT_GREET_PACKET => "MYSQLND_UH_MYSQLND_PROT_GREET_PACKET",
  MYSQLND_UH_MYSQLND_PROT_AUTH_PACKET => "MYSQLND_UH_MYSQLND_PROT_AUTH_PACKET",
  MYSQLND_UH_MYSQLND_PROT_OK_PACKET => "MYSQLND_UH_MYSQLND_PROT_OK_PACKET",
  MYSQLND_UH_MYSQLND_PROT_EOF_PACKET => "MYSQLND_UH_MYSQLND_PROT_EOF_PACKET",
  MYSQLND_UH_MYSQLND_PROT_CMD_PACKET => "MYSQLND_UH_MYSQLND_PROT_CMD_PACKET",
  MYSQLND_UH_MYSQLND_PROT_RSET_HEADER_PACKET => "MYSQLND_UH_MYSQLND_PROT_RSET_HEADER_PACKET",
  MYSQLND_UH_MYSQLND_PROT_RSET_FLD_PACKET => "MYSQLND_UH_MYSQLND_PROT_RSET_FLD_PACKET",
  MYSQLND_UH_MYSQLND_PROT_ROW_PACKET => "MYSQLND_UH_MYSQLND_PROT_ROW_PACKET",
  MYSQLND_UH_MYSQLND_PROT_STATS_PACKET => "MYSQLND_UH_MYSQLND_PROT_STATS_PACKET",
  MYSQLND_UH_MYSQLND_PREPARE_RESP_PACKET => "MYSQLND_UH_MYSQLND_PREPARE_RESP_PACKET",
  MYSQLND_UH_MYSQLND_CHG_USER_RESP_PACKET => "MYSQLND_UH_MYSQLND_CHG_USER_RESP_PACKET",
  MYSQLND_UH_MYSQLND_PROT_LAST => "MYSQLND_UH_MYSQLND_PROT_LAST",
 );
 return (isset($mapping[$ok_packet])) ? $mapping[$ok_packet] : 'unknown';
}

class proxy extends MysqlndUhConnection {
 public function simpleCommandHandleResponse($conn, $ok_packet, $silent, $command, $ignore_upsert_status) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  printf("Command '%s'\n", server_cmd_2_string($command));
  printf("OK packet '%s'\n",  ok_packet_2_string($ok_packet));
  $ret = parent::simpleCommandHandleResponse($conn, $ok_packet, $silent, $command, $ignore_upsert_status);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysql = mysql_connect("localhost", "root", "");
mysql_query("SELECT 1 FROM DUAL", $mysql);
?>

The above example will output:

proxy::simpleCommandHandleResponse(array (
  0 => NULL,
  1 => 5,
  2 => false,
  3 => 27,
  4 => true,
))
Command 'MYSQLND_UH_MYSQLND_COM_SET_OPTION'
OK packet 'MYSQLND_UH_MYSQLND_PROT_EOF_PACKET'
proxy::simpleCommandHandleResponse returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections


Used for establishing secure connections using SSL

  • « MysqlndUhConnection::simpleCommandHandleResponse
  • MysqlndUhConnection::stmtInit »
  • PHP Manual
  • MysqlndUhConnection
  • Used for establishing secure connections using SSL

MysqlndUhConnection::sslSet

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::sslSet — Used for establishing secure connections using SSL

Description

public MysqlndUhConnection::sslSet ( mysqlnd_connection $connection , string $key , string $cert , string $ca , string $capath , string $cipher ) : bool

Used for establishing secure connections using SSL.

Parameters

connection

Mysqlnd connection handle. Do not modify!

key

The path name to the key file.

cert

The path name to the certificate file.

ca

The path name to the certificate authority file.

capath

The pathname to a directory that contains trusted SSL CA certificates in PEM format.

cipher

A list of allowable ciphers to use for SSL encryption.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::sslSet() example

<?php
class proxy extends MysqlndUhConnection {
 public function sslSet($conn, $key, $cert, $ca, $capath, $cipher) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::sslSet($conn, $key, $cert, $ca, $capath, $cipher);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->ssl_set("key", "cert", "ca", "capath", "cipher");
?>

The above example will output:

proxy::sslSet(array (
  0 => NULL,
  1 => 'key',
  2 => 'cert',
  3 => 'ca',
  4 => 'capath',
  5 => 'cipher',
))
proxy::sslSet returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_ssl_set() - Used for establishing secure connections using SSL


Initializes a statement and returns a resource for use with mysqli_statement::prepare

  • « MysqlndUhConnection::sslSet
  • MysqlndUhConnection::storeResult »
  • PHP Manual
  • MysqlndUhConnection
  • Initializes a statement and returns a resource for use with mysqli_statement::prepare

MysqlndUhConnection::stmtInit

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::stmtInit — Initializes a statement and returns a resource for use with mysqli_statement::prepare

Description

public MysqlndUhConnection::stmtInit ( mysqlnd_connection $connection ) : resource

Initializes a statement and returns a resource for use with mysqli_statement::prepare.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Resource of type Mysqlnd Prepared Statement (internal only - you must not modify it!). The documentation may also refer to such resources using the alias name mysqlnd_prepared_statement.

Examples

Example #1 MysqlndUhConnection::stmtInit() example

<?php
class proxy extends MysqlndUhConnection {
 public function stmtInit($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  var_dump($res);
  $ret = parent::stmtInit($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  var_dump($ret);
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());
$mysqli = new mysqli("localhost", "root", "", "test");
$stmt = $mysqli->prepare("SELECT 1 AS _one FROM DUAL");
$stmt->execute();
$one = NULL;
$stmt->bind_result($one);
$stmt->fetch();
var_dump($one);
?>

The above example will output:

proxy::stmtInit(array (
  0 => NULL,
))
resource(19) of type (Mysqlnd Connection)
proxy::stmtInit returns NULL
resource(246) of type (Mysqlnd Prepared Statement (internal only - you must not modify it!))
int(1)

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_stmt_init() - Initializes a statement and returns an object for use with mysqli_stmt_prepare


Transfers a result set from the last query

  • « MysqlndUhConnection::stmtInit
  • MysqlndUhConnection::txCommit »
  • PHP Manual
  • MysqlndUhConnection
  • Transfers a result set from the last query

MysqlndUhConnection::storeResult

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::storeResult — Transfers a result set from the last query

Description

public MysqlndUhConnection::storeResult ( mysqlnd_connection $connection ) : resource

Transfers a result set from the last query.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Resource of type Mysqlnd Resultset (internal only - you must not modify it!). The documentation may also refer to such resources using the alias name mysqlnd_resultset.

Examples

Example #1 MysqlndUhConnection::storeResult() example

<?php
class proxy extends MysqlndUhConnection {
 public function storeResult($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::storeResult($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  var_dump($ret);
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$res = $mysqli->query("SELECT 'Also called buffered result' AS _msg FROM DUAL");
var_dump($res->fetch_assoc());

$mysqli->real_query("SELECT 'Good morning!' AS _msg FROM DUAL");
$res = $mysqli->store_result();
var_dump($res->fetch_assoc());
?>

The above example will output:

proxy::storeResult(array (
  0 => NULL,
))
proxy::storeResult returns NULL
resource(475) of type (Mysqlnd Resultset (internal only - you must not modify it!))
array(1) {
  ["_msg"]=>
  string(27) "Also called buffered result"
}
proxy::storeResult(array (
  0 => NULL,
))
proxy::storeResult returns NULL
resource(730) of type (Mysqlnd Resultset (internal only - you must not modify it!))
array(1) {
  ["_msg"]=>
  string(13) "Good morning!"
}

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_store_result() - Transfers a result set from the last query
  • mysqli_real_query() - Execute an SQL query


Commits the current transaction

  • « MysqlndUhConnection::storeResult
  • MysqlndUhConnection::txRollback »
  • PHP Manual
  • MysqlndUhConnection
  • Commits the current transaction

MysqlndUhConnection::txCommit

(PECL mysqlnd-uh >= 1.0.1-alpha)

MysqlndUhConnection::txCommit — Commits the current transaction

Description

public MysqlndUhConnection::txCommit ( mysqlnd_connection $connection ) : bool

Commits the current transaction.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::txCommit() example

<?php
class proxy extends MysqlndUhConnection {
 public function txCommit($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::txCommit($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->commit();
?>

The above example will output:

proxy::txCommit(array (
  0 => NULL,
))
proxy::txCommit returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_commit() - Commits the current transaction


Rolls back current transaction

  • « MysqlndUhConnection::txCommit
  • MysqlndUhConnection::useResult »
  • PHP Manual
  • MysqlndUhConnection
  • Rolls back current transaction

MysqlndUhConnection::txRollback

(PECL mysqlnd-uh >= 1.0.1-alpha)

MysqlndUhConnection::txRollback — Rolls back current transaction

Description

public MysqlndUhConnection::txRollback ( mysqlnd_connection $connection ) : bool

Rolls back current transaction.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhConnection::txRollback() example

<?php
class proxy extends MysqlndUhConnection {
 public function txRollback($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::txRollback($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->rollback();
?>

The above example will output:

proxy::txRollback(array (
  0 => NULL,
))
proxy::txRollback returns true

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_commit() - Commits the current transaction


Initiate a result set retrieval

  • « MysqlndUhConnection::txRollback
  • MysqlndUhPreparedStatement »
  • PHP Manual
  • MysqlndUhConnection
  • Initiate a result set retrieval

MysqlndUhConnection::useResult

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhConnection::useResult — Initiate a result set retrieval

Description

public MysqlndUhConnection::useResult ( mysqlnd_connection $connection ) : resource

Initiate a result set retrieval.

Parameters

connection

Mysqlnd connection handle. Do not modify!

Return Values

Resource of type Mysqlnd Resultset (internal only - you must not modify it!). The documentation may also refer to such resources using the alias name mysqlnd_resultset.

Examples

Example #1 MysqlndUhConnection::useResult() example

<?php
class proxy extends MysqlndUhConnection {
 public function useResult($res) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $ret = parent::useResult($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  var_dump($ret);
  return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->real_query("SELECT 'Good morning!' AS _msg FROM DUAL");
$res = $mysqli->use_result();
var_dump($res->fetch_assoc());
?>

The above example will output:

proxy::useResult(array (
  0 => NULL,
))
proxy::useResult returns NULL
resource(425) of type (Mysqlnd Resultset (internal only - you must not modify it!))
array(1) {
  ["_msg"]=>
  string(13) "Good morning!"
}

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqli_use_result() - Initiate a result set retrieval
  • mysqli_real_query() - Execute an SQL query


The MysqlndUhPreparedStatement class

(PECL mysqlnd-uh >= 1.0.0-alpha)

Introduction

Class synopsis

MysqlndUhPreparedStatement {
/* Methods */
public __construct ( void )
public execute ( mysqlnd_prepared_statement $statement ) : bool
public prepare ( mysqlnd_prepared_statement $statement , string $query ) : bool
}

Table of Contents

  • MysqlndUhPreparedStatement::__construct — The __construct purpose
  • MysqlndUhPreparedStatement::execute — Executes a prepared Query
  • MysqlndUhPreparedStatement::prepare — Prepare an SQL statement for execution


The __construct purpose

  • « MysqlndUhPreparedStatement
  • MysqlndUhPreparedStatement::execute »
  • PHP Manual
  • MysqlndUhPreparedStatement
  • The __construct purpose

MysqlndUhPreparedStatement::__construct

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhPreparedStatement::__construct — The __construct purpose

Description

public MysqlndUhPreparedStatement::__construct ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Executes a prepared Query

  • « MysqlndUhPreparedStatement::__construct
  • MysqlndUhPreparedStatement::prepare »
  • PHP Manual
  • MysqlndUhPreparedStatement
  • Executes a prepared Query

MysqlndUhPreparedStatement::execute

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhPreparedStatement::execute — Executes a prepared Query

Description

public MysqlndUhPreparedStatement::execute ( mysqlnd_prepared_statement $statement ) : bool

Executes a prepared Query.

Parameters

statement

Mysqlnd prepared statement handle. Do not modify! Resource of type Mysqlnd Prepared Statement (internal only - you must not modify it!).

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhPreparedStatement::execute() example

<?php
class stmt_proxy extends MysqlndUhPreparedStatement {
 public function execute($res) {
  printf("%s(", __METHOD__);
  var_dump($res);
  printf(")\n");
  $ret = parent::execute($res);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  var_dump($ret);
  return $ret;
 }
}
mysqlnd_uh_set_statement_proxy(new stmt_proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$stmt = $mysqli->prepare("SELECT 'Labskaus' AS _msg FROM DUAL");
$stmt->execute();
$msg = NULL;
$stmt->bind_result($msg);
$stmt->fetch();
var_dump($msg);
?>

The above example will output:

stmt_proxy::execute(resource(256) of type (Mysqlnd Prepared Statement (internal only - you must not modify it!))
)
stmt_proxy::execute returns true
bool(true)
string(8) "Labskaus"

See Also

  • mysqlnd_uh_set_statement_proxy() - Installs a proxy for mysqlnd statements
  • mysqli_stmt_execute() - Executes a prepared Query


Prepare an SQL statement for execution

  • « MysqlndUhPreparedStatement::execute
  • Mysqlnd_uh Functions »
  • PHP Manual
  • MysqlndUhPreparedStatement
  • Prepare an SQL statement for execution

MysqlndUhPreparedStatement::prepare

(PECL mysqlnd-uh >= 1.0.0-alpha)

MysqlndUhPreparedStatement::prepare — Prepare an SQL statement for execution

Description

public MysqlndUhPreparedStatement::prepare ( mysqlnd_prepared_statement $statement , string $query ) : bool

Prepare an SQL statement for execution.

Parameters

statement

Mysqlnd prepared statement handle. Do not modify! Resource of type Mysqlnd Prepared Statement (internal only - you must not modify it!).

query

The query to be prepared.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 MysqlndUhPreparedStatement::prepare() example

<?php
class stmt_proxy extends MysqlndUhPreparedStatement {
 public function prepare($res, $query) {
  printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
  $query = "SELECT 'No more you-know-what-I-mean for lunch, please' AS _msg FROM DUAL";
  $ret = parent::prepare($res, $query);
  printf("%s returns %s\n", __METHOD__, var_export($ret, true));
  var_dump($ret);
  return $ret;
 }
}
mysqlnd_uh_set_statement_proxy(new stmt_proxy());

$mysqli = new mysqli("localhost", "root", "", "test");
$stmt = $mysqli->prepare("SELECT 'Labskaus' AS _msg FROM DUAL");
$stmt->execute();
$msg = NULL;
$stmt->bind_result($msg);
$stmt->fetch();
var_dump($msg);
?>

The above example will output:

stmt_proxy::prepare(array (
  0 => NULL,
  1 => 'SELECT \'Labskaus\' AS _msg FROM DUAL',
))
stmt_proxy::prepare returns true
bool(true)
string(46) "No more you-know-what-I-mean for lunch, please"

See Also

  • mysqlnd_uh_set_statement_proxy() - Installs a proxy for mysqlnd statements
  • mysqli_stmt_prepare() - Prepare an SQL statement for execution
  • mysqli_prepare() - Prepare an SQL statement for execution


Mysqlnd_uh Functions

Table of Contents

  • mysqlnd_uh_convert_to_mysqlnd — Converts a MySQL connection handle into a mysqlnd connection handle
  • mysqlnd_uh_set_connection_proxy — Installs a proxy for mysqlnd connections
  • mysqlnd_uh_set_statement_proxy — Installs a proxy for mysqlnd statements


Converts a MySQL connection handle into a mysqlnd connection handle

  • « Mysqlnd_uh Functions
  • mysqlnd_uh_set_connection_proxy »
  • PHP Manual
  • Mysqlnd_uh Functions
  • Converts a MySQL connection handle into a mysqlnd connection handle

mysqlnd_uh_convert_to_mysqlnd

(PECL mysqlnd-uh >= 1.0.0-alpha)

mysqlnd_uh_convert_to_mysqlnd — Converts a MySQL connection handle into a mysqlnd connection handle

Description

mysqlnd_uh_convert_to_mysqlnd ( mysqli &$mysql_connection ) : resource

Converts a MySQL connection handle into a mysqlnd connection handle. After conversion you can execute mysqlnd library calls on the connection handle. This can be used to access mysqlnd functionality not made available through user space API calls.

The function can be disabled with mysqlnd_uh.enable. If mysqlnd_uh.enable is set to FALSE the function will not install the proxy and always return TRUE. Additionally, an error of the type E_WARNING may be emitted. The error message may read like PHP Warning: mysqlnd_uh_convert_to_mysqlnd(): (Mysqlnd User Handler) The plugin has been disabled by setting the configuration parameter mysqlnd_uh.enable = false. You are not allowed to call this function [...].

Parameters

MySQL connection handle

A MySQL connection handle of type mysql, mysqli or PDO_MySQL.

Return Values

A mysqlnd connection handle.

Changelog

Version | Description
5.4.0 | The mysql_connection parameter can now be of type mysql, PDO_MySQL, or mysqli. Before, only the mysqli type was allowed.

Examples

Example #1 mysqlnd_uh_convert_to_mysqlnd() example

<?php
/* PDO user API gives no access to connection thread id */
$mysql_connection = new PDO("mysql:host=localhost;dbname=test", "root", "");

/* Convert PDO MySQL handle to mysqlnd handle */
$mysqlnd = mysqlnd_uh_convert_to_mysqlnd($mysql_connection);

/* Create Proxy to call mysqlnd connection class methods */
$obj = new MySQLndUHConnection();
/* Call mysqlnd_conn::get_thread_id */
var_dump($obj->getThreadId($mysqlnd));

/* Use SQL to fetch connection thread id */
var_dump($mysql_connection->query("SELECT CONNECTION_ID()")->fetchAll());
?>

The above example will output:

int(27054)
array(1) {
  [0]=>
  array(2) {
    ["CONNECTION_ID()"]=>
    string(5) "27054"
    [0]=>
    string(5) "27054"
  }
}

See Also

  • mysqlnd_uh.enable


Installs a proxy for mysqlnd connections

  • « mysqlnd_uh_convert_to_mysqlnd
  • mysqlnd_uh_set_statement_proxy »
  • PHP Manual
  • Mysqlnd_uh Functions
  • Installs a proxy for mysqlnd connections

mysqlnd_uh_set_connection_proxy

(PECL mysqlnd-uh >= 1.0.0-alpha)

mysqlnd_uh_set_connection_proxy — Installs a proxy for mysqlnd connections

Description

mysqlnd_uh_set_connection_proxy ( MysqlndUhConnection &$connection_proxy [, mysqli &$mysqli_connection ] ) : bool

Installs a proxy object to hook mysqlnd's connection objects methods. Once installed, the proxy will be used for all MySQL connections opened with mysqli, mysql or PDO_MYSQL, assuming that the listed extensions are compiled to use the mysqlnd library.

The function can be disabled with mysqlnd_uh.enable. If mysqlnd_uh.enable is set to FALSE the function will not install the proxy and always return TRUE. Additionally, an error of the type E_WARNING may be emitted. The error message may read like PHP Warning: mysqlnd_uh_set_connection_proxy(): (Mysqlnd User Handler) The plugin has been disabled by setting the configuration parameter mysqlnd_uh.enable = false. The proxy has not been installed [...].

Parameters

connection_proxy

A proxy object of type MysqlndUhConnection.

mysqli_connection

Object of type mysqli. If given, the proxy will be set for this particular connection only.

Return Values

Returns TRUE on success. Otherwise, returns FALSE

Examples

Example #1 mysqlnd_uh_set_connection_proxy() example

<?php
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->query("SELECT 'No proxy installed, yet'");

class proxy extends MysqlndUhConnection {
 public function query($res, $query) {
   printf("%s(%s)\n", __METHOD__, var_export(func_get_args(), true));
   $ret = parent::query($res, $query);
   printf("%s returns %s\n", __METHOD__, var_export($ret, true));
   return $ret;
 }
}
mysqlnd_uh_set_connection_proxy(new proxy());

$mysqli->query("SELECT 'mysqlnd rocks!'");

$mysql = mysql_connect("localhost", "root", "", "test");
mysql_query("SELECT 'Ahoy Andrey!'", $mysql);

$pdo = new PDO("mysql:host=localhost;dbname=test", "root", "");
$pdo->query("SELECT 'Moin Johannes!'");
?>

The above example will output:

proxy::query(array (
  0 => NULL,
  1 => 'SELECT \'mysqlnd rocks!\'',
))
proxy::query returns true
proxy::query(array (
  0 => NULL,
  1 => 'SELECT \'Ahoy Andrey!\'',
))
proxy::query returns true
proxy::query(array (
  0 => NULL,
  1 => 'SELECT \'Moin Johannes!\'',
))
proxy::query returns true

See Also

  • mysqlnd_uh_set_statement_proxy() - Installs a proxy for mysqlnd statements
  • mysqlnd_uh.enable


Installs a proxy for mysqlnd statements

  • « mysqlnd_uh_set_connection_proxy
  • Change History »
  • PHP Manual
  • Mysqlnd_uh Functions
  • Installs a proxy for mysqlnd statements

mysqlnd_uh_set_statement_proxy

(PECL mysqlnd-uh >= 1.0.0-alpha)

mysqlnd_uh_set_statement_proxy — Installs a proxy for mysqlnd statements

Description

mysqlnd_uh_set_statement_proxy ( MysqlndUhStatement &$statement_proxy ) : bool

Installs a proxy for mysqlnd statements. The proxy object will be used for all mysqlnd prepared statement objects, regardless which PHP MySQL extension (mysqli, mysql, PDO_MYSQL) has created them as long as the extension is compiled to use the mysqlnd library.

The function can be disabled with mysqlnd_uh.enable. If mysqlnd_uh.enable is set to FALSE the function will not install the proxy and always return TRUE. Additionally, an error of the type E_WARNING may be emitted. The error message may read like PHP Warning: mysqlnd_uh_set_statement_proxy(): (Mysqlnd User Handler) The plugin has been disabled by setting the configuration parameter mysqlnd_uh.enable = false. The proxy has not been installed [...].

Parameters

statement_proxy

The mysqlnd statement proxy object of type MysqlndUhStatement

Return Values

Returns TRUE on success. Otherwise, returns FALSE

See Also

  • mysqlnd_uh_set_connection_proxy() - Installs a proxy for mysqlnd connections
  • mysqlnd_uh.enable


Change History

Table of Contents

  • PECL/mysqlnd_uh 1.0 series

The Change History lists major changes users need to be aware if upgrading from one version to another. It is a high level summary of selected changes that may impact applications or might even break backwards compatibility. See also the CHANGES file contained in the source for additional changelog information. The commit history is also available.


PECL/mysqlnd_uh 1.0 series

1.0.1-alpha

  • Release date: TBD
  • Motto/theme: bug fix release

Feature changes

  • Support of PHP 5.4.0 or later.
  • BC break: MysqlndUhConnection::changeUser() requires additional passwd_len parameter.
  • BC break: MYSQLND_UH_VERSION_STR renamed to MYSQLND_UH_VERSION. MYSQLND_UH_VERSION renamed to MYSQLND_UH_VERSION_ID.
  • BC break: mysqlnd_uh.enabled configuration setting renamed to mysqlnd_uh.enable.

1.0.0-alpha

  • Release date: 08/2010
  • Motto/theme: Initial release


Mysqlnd connection multiplexing plugin

  • Introduction
  • Concepts
    • Architecture
    • Connection pool
    • Sharing connections
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
  • Predefined Constants
  • Change History
    • PECL/mysqlnd_mux 1.0 series


Introduction

The mysqlnd multiplexing plugin (mysqlnd_mux) multiplexes MySQL connections established by all PHP MySQL extensions that use the MySQL native driver (mysqlnd) for PHP.

The MySQL native driver for PHP features an internal C API for plugins, such as the connection multiplexing plugin, which can extend the functionality of mysqlnd. See the mysqlnd for additional details about its benefits over the MySQL Client Library libmysqlclient.

Mysqlnd plugins like mysqlnd_mux operate, for the most part, transparently from a user perspective. The connection multiplexing plugin supports all PHP applications, and all MySQL PHP extensions. It does not change existing APIs. Therefore, it can easily be used with existing PHP applications.

Note:

This is a proof-of-concept. All features are at an early stage. Not all kinds of queries are handled by the plugin yet. Thus, it cannot be used in a drop-in fashion at the moment.

Please, do not use this version in production environments.

Key Features

The key features of mysqlnd_mux are as follows:

  • Transparent and therefore easy to use:

    • Supports all of the PHP MySQL extensions.

    • Little to no application changes are required, dependent on the required usage scenario.

  • Reduces server load and connection establishment latency:

    • Opens less connections to the MySQL server.

    • Less connections to MySQL mean less work for the MySQL server. In a client-server environment scaling the server is often more difficult than scaling the client. Multiplexing helps with horizontal scale-out (scale-by-client).

    • Pooling saves connection time.

    • Multiplexed connection: multiple user handles share the same network connection. Once opened, a network connection is cached and shared among multiple user handles. There is a 1:n relationship between internal network connection and user connection handles.

    • Persistent connection: a network connection is kept open at the end of the web request, if the PHP deployment model allows. Thus, subsequently web requests can reuse a previously opened connection. Like other resources, network connections are bound to the scope of a process. Thus, they can be reused for all web requests served by a process.

Limitations

The proof-of-concept does not support unbuffered queries, prepared statements, and asynchronous queries.

The connection pool is using a combination of the transport method and hostname as keys. As a consequence, two connections to the same host using the same transport method (TCP/IP, Unix socket, Windows named pipe) will be linked to the same pooled connection even if username and password differ. Be aware of the possible security implications.

The proof-of-concept is transaction agnostic. It does not know about SQL transactions.

Note:

Applications must be aware of the consequences of connection sharing connections.

About the name mysqlnd_mux

The shortcut mysqlnd_mux stands for mysqlnd connection multiplexing plugin.


Concepts

Table of Contents

  • Architecture
  • Connection pool
  • Sharing connections

This explains the architecture and related concepts for this plugin. Reading and understanding these concepts is required to successfully use this plugin.


Architecture

The mysqlnd connection multiplexing plugin is implemented as a PHP extension. It is written in C and operates under the hood of PHP. During the startup of the PHP interpreter, in the module initialization phase of the PHP engine, it gets registered as a mysqlnd plugin to replace specific mysqlnd C methods.

The mysqlnd library uses PHP streams to communicate with the MySQL server. PHP streams are accessed by the mysqlnd library through its net module. The mysqlnd connection multiplexing plugin proxies methods of the mysqlnd library net module to control opening and closing of network streams.

Upon opening a user connection to MySQL using the appropriate connection functions of either mysqli, PDO_MYSQL or ext/mysql, the plugin will search its connection pool for an open network connection. If the pool contains a network connection to the host specified by the connect function using the transport method requested (TCP/IP, Unix domain socket, Windows named pipe), the pooled connection is linked to the user handle. Otherwise, a new network connection is opened, put into the poolm and associated with the user connection handle. This way, multiple user handles can be linked to the same network connection.


Connection pool

The plugins connection pool is created when PHP initializes its modules (MINIT) and free'd when PHP shuts down the modules (MSHUTDOWN). This is the same as for persistent MySQL connections.

Depending on the deployment model, the pool is used for the duration of one or multiple web requests. Network connections are bound to the lifespan of an operating system level process. If the PHP process serves multiple web requests as it is the case for Fast-CGI or threaded web server deployments, then the pooled connections can be reused over multiple connections. Because multiplexing means sharing connections, it can even happen with a threaded deployment that two threads or two distinct web requests are linked to one pooled network connections.

A pooled connection is explicitly closed once the last reference to it is released. An implicit close happens when PHP shuts down its modules.


Sharing connections

The PHP mysqlnd connection multiplexing plugin changes the relationship between a users connection handle and the underlying MySQL connection. Without the plugin, every MySQL connection belongs to exactly one user connection at a time. The multiplexing plugin changes. A MySQL connection is shared among multiple user handles. There no one-to-one relation if using the plugin.

Sharing pooled connections has an impact on the connection state. State changing operations from multiple user handles pointing to one MySQL connection are not isolated from each other. If, for example, a session variable is set through one user connection handle, the session variable becomes visible to all other user handles that reference the same underlying MySQL connection.

This is similar in concept to connection state related phenomens described for the PHP mysqlnd replication and load balancing plugin. Please, check the PECL/mysqlnd_ms documentation for more details on the state of a connection.

The proof-of-concept takes no measures to isolate multiplexed connections from each other.


  • « Sharing connections
  • Requirements »
  • PHP Manual
  • mysqlnd_mux
  • Installing/Configuring

Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration


Requirements

PHP 5.5.0 or newer. Some advanced functionality requires PHP 5.5.0 or newer.

The mysqlnd_mux replication and load balancing plugin supports all PHP applications and all available PHP MySQL extensions (mysqli, mysql, PDO_MYSQL). The PHP MySQL extension must be configured to use mysqlnd in order to be able to use the mysqlnd_mux plugin for mysqlnd.


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/mysqlnd_mux


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Mysqlnd_mux Configure Options
Name | Default | Changeable | Changelog
mysqlnd_mux.enable | 0 | PHP_INI_SYSTEM |

Here's a short explanation of the configuration directives.

mysqlnd_mux.enable integer

Enables or disables the plugin. If disabled, the extension will not plug into mysqlnd to proxy internal mysqlnd C API calls.


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.

Other

The plugins version number can be obtained using MYSQLND_MUX_VERSION or MYSQLND_MUX_VERSION_ID. MYSQLND_MUX_VERSION is the string representation of the numerical version number MYSQLND_MUX_VERSION_ID, which is an integer such as 10000. Developers can calculate the version number as follows.

Version (part) | Example
Major*10000 | 1*10000 = 10000
Minor*100 | 0*100 = 0
Patch | 0 = 0
MYSQLND_MUX_VERSION_ID | 10000

MYSQLND_MUX_VERSION (string)
Plugin version string, for example, 1.0.0-prototype.
MYSQLND_MUX_VERSION_ID (integer)
Plugin version number, for example, 10000.


Change History

Table of Contents

  • PECL/mysqlnd_mux 1.0 series

This change history is a high level summary of selected changes that may impact applications and/or break backwards compatibility.

See also the CHANGES file in the source distribution for a complete list of changes.


PECL/mysqlnd_mux 1.0 series

1.0.0-pre-alpha

  • Release date: no package released, initial check-in 09/2012
  • Motto/theme: Proof of concept

Initial check-in. Essentially a demo of the mysqlnd plugin API.

Note:

This is the current development series. All features are at an early stage. Changes may happen at any time without prior notice. Please, do not use this version in production environments.

The documentation may not reflect all changes yet.


Mysqlnd Memcache plugin

  • Introduction
  • Quickstart and Examples
    • Setup
    • Usage
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
  • Predefined Constants
  • Mysqlnd_memcache Functions
    • mysqlnd_memcache_get_config — Returns information about the plugin configuration
    • mysqlnd_memcache_set — Associate a MySQL connection with a Memcache connection
  • Change History
    • PECL/mysqlnd_memcache 1.0 series


Introduction

The mysqlnd memcache plugin (mysqlnd_memcache) is an PHP extension for transparently translating SQL into requests for the MySQL InnoDB Memcached Daemon Plugin (server plugin). It includes experimental support for the MySQL Cluster Memcached Daemon. The server plugin provides access to data stored inside MySQL InnoDB (respectively MySQL Cluster NDB) tables using the Memcache protocol. This PHP extension, which supports all PHP MySQL extensions that use mysqlnd, will identify tables exported in this way and will translate specific SELECT queries into Memcache requests.

mysqlnd_memcache data flow

Note:

This plugin depends on the MySQL InnoDB Memcached Daemon Plugin. It is not provided to be used with a stand-alone Memcached. For a generic query cache using Memcached look at the mysqlnd query cache plugin. For direct Memcache access look at the memcache and memcached extensions.

The MySQL native driver for PHP is a C library that ships together with PHP as of PHP 5.3.0. It serves as a drop-in replacement for the MySQL Client Library (libmysqlclient). Using mysqlnd has several advantages: no extra downloads are required because it's bundled with PHP, it's under the PHP license, there is lower memory consumption in certain cases, and it contains new functionality such as asynchronous queries.

The mysqlnd_mmemcache operates, for the most part, transparently from a user perspective. The mysqlnd memcache plugin supports all PHP applications, and all MySQL PHP extensions. It does not change existing APIs. Therefore, it can easily be used with existing PHP applications.

The MySQL Memcache plugins add key-value style access method for data stored in InnoDB resp. NDB (MySQL Cluster) SQL tables through the Memcache protocol. This type of key-value access if often faster than using SQL.

Key Features

The key features of PECL/mysqlnd_memcache are as follows.

  • Possible performance benefits

    • Client-side: light-weight protocol.

    • Server-side: no SQL parsing, direct access to the storage.

    • Please, run your own benchmarks! Actual performance results are highly dependent on setup and hardware used.

Limitations

The initial version is not binary safe. Due to the way the MySQL Memcache plugins works there are restrictions related to separators.

Prepared statements and asynchronous queries are not supported. Result set meta data support is limited.

The mapping information for tables accessible via Memcache is not cached in the plugin between requests but fetched from the MySQL server each time a MySQL connection is associated with a Memcache connection. See mysqlnd_memcache_set() for details.

On the name

The shortcut mysqlnd_memcache stands for mysqlnd memcache plugin. Memcache refers to support of the MySQL Memcache plugins for InnoDB and NDB (MySQL Cluster). The plugin is not related to the Memcached cache server.


Quickstart and Examples

Table of Contents

  • Setup
  • Usage

The mysqlnd memcache plugin is easy to use. This quickstart will demo typical use-cases, and provide practical advice on getting started.

It is strongly recommended to read the reference sections in addition to the quickstart. The quickstart tries to avoid discussing theoretical concepts and limitations. Instead, it will link to the reference sections. It is safe to begin with the quickstart. However, before using the plugin in mission critical environments we urge you to read additionally the background information from the reference sections.


Setup

The plugin is implemented as a PHP extension. See also the installation instructions to install this extension.

Compile or configure the PHP MySQL extension (API) (mysqli, PDO_MYSQL, mysql). That extension must use the mysqlnd library as because mysqlnd_memcache is a plugin for the mysqlnd library. For additional information, refer to the mysqlnd_memcache installation instructions.

Then, load this extension into PHP and activate the plugin in the PHP configuration file using the PHP configuration directive named mysqlnd_memcache.enable.

Example #1 Enabling the plugin (php.ini)

; On Windows the filename is php_mysqnd_memcache.dll
; Load the extension
extension=mysqlnd_memcache.so
; Enable it
mysqlnd_memcache.enable=1

Follow the instructions given in the » MySQL Reference Manual on installing the Memcache plugins for the MySQL server. Activate the plugins and configure Memcache access for SQL tables.

The examples in this quickguide assume that the following table exists, and that Memcache is configured with access to it.

Example #2 SQL table used for the Quickstart

CREATE TABLE test(
  id CHAR(16),
  f1 VARCHAR(255),
  f2 VARCHAR(255),
  f3 VARCHAR(255),
  flags INT NOT NULL,
  cas_column INT,
  expire_time_column INT,
  PRIMARY KEY(id)
  ) ENGINE=InnoDB;

INSERT INTO test (id, f1, f2, f3) VALUES (1, 'Hello', 'World', '!');
INSERT INTO test (id, f1, f2, f3) VALUES (2, 'Lady', 'and', 'the tramp');

INSERT INTO innodb_memcache.containers(
  name, db_schema, db_table, key_columns, value_columns,
  flags, cas_column, expire_time_column, unique_idx_name_on_key)
VALUES (
  'plugin_test', 'test', 'test', 'id', 'f1,f2,f3',
  'flags', 'cas_column', 'expire_time_column', 'PRIMARY KEY');


Usage

After associating a MySQL connection with a Memcache connection using mysqnd_memcache_set() the plugin attempts to transparently replace SQL SELECT statements by a memcache access. For that purpose the plugin monitors all SQL statements executed and tries to match the statement string against MYSQLND_MEMCACHE_DEFAULT_REGEXP. In case of a match, the mysqlnd memcache plugin checks whether the SELECT is accessing only columns of a mapped table and the WHERE clause is limited to a single key lookup.

In case of the example SQL table, the plugin will use the Memcache interface of the MySQL server to fetch results for a SQL query like SELECT f1, f2, f3 WHERE id = n.

Example #1 Basic example.

<?php
$mysqli = new mysqli("host", "user", "passwd", "database");
$memc = new Memcached();
$memc->addServer("host", 11211);
mysqlnd_memcache_set($mysqli, $memc);

/*
   This is a query which queries table test using id as key in the WHERE part
   and is accessing fields f1, f2 and f3. Therefore, mysqlnd_memcache
   will intercept it and route it via memcache.
*/
$result = $mysqli->query("SELECT f1, f2, f3 FROM test WHERE id = 1");
while ($row = $result->fetch_row()) {
    print_r($row);
}

/*
   This is a query which queries table test but using f1 in the WHERE clause.
   Therefore, mysqlnd_memcache can't intercept it. This will be executed
   using the MySQL protocol
*/
$mysqli->query("SELECT id FROM test WHERE f1 = 'Lady'");
while ($row = $result->fetch_row()) {
    print_r($row);
}
?>

The above example will output:

array(
    [f1] => Hello
    [f2] => World
    [f3] => !
)
array(
    [id] => 2
)


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration


Requirements

PHP: this extension requires PHP 5.4+, version PHP 5.4.4 or never. The required PHP extensions are PCRE (enabled by default), and the memcached extension version 2.0.x.

The mysqlnd_memcache Memcache plugin supports all PHP applications and all available PHP MySQL extensions (mysqli, mysql, PDO_MYSQL). The PHP MySQL extension must be configured with mysqlnd support.

For accessing InnoDB tables, this PHP extension requires MySQL Server 5.6.6 or newer with the InnoDB Memcache Daemon Plugin enabled.

For accessing MySQL Cluster NDB tables, this PHP extension requires MySQL Cluster 7.2 or newer with the NDB Memcache API nodes enabled.


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/mysqlnd_memcache

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Mysqlnd_memcache Configure Options
Name | Default | Changeable | Changelog
mysqlnd_memcache.enable | 1 | PHP_INI_SYSTEM | Available since 1.0.0

Here's a short explanation of the configuration directives.

mysqlnd_memcache.enable integer

Enables or disables the plugin. If disabled, the extension will not plug into mysqlnd to proxy internal mysqlnd C API calls.

Note:

This option is mainly used by developers to build this extension statically into PHP. General users are encouraged to build this extension as a shared object, and to unload it completely when it is not needed.


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.

MySQL Memcache Plugin related

MYSQLND_MEMCACHE_DEFAULT_REGEXP (string)
Default regular expression (PCRE style) used for matching SELECT statements that will be mapped into a MySQL Memcache Plugin access point, if possible. It is also possible to use mysqlnd_memcache_set(), but the default approach is using this regular expression for pattern matching.

Assorted

The version number of this plugin can be obtained by using MYSQLND_MEMCACHE_VERSION or MYSQLND_MEMCACHE_VERSION_ID. MYSQLND_MEMCACHE_VERSION is the string representation of the numerical version number MYSQLND_MEMCACHE_VERSION_ID, which is an integer such as 10000. Developers can calculate the version number as follows.

Version (part) | Example
Major*10000 | 1*10000 = 10000
Minor*100 | 0*100 = 0
Patch | 0 = 0
MYSQLND_MEMCACHE_VERSION_ID | 10000

MYSQLND_MEMCACHE_VERSION (string)
Plugin version string, for example, 1.0.0-alpha.
MYSQLND_MEMCACHE_VERSION_ID (integer)
Plugin version number, for example, 10000.


Mysqlnd_memcache Functions

Table of Contents

  • mysqlnd_memcache_get_config — Returns information about the plugin configuration
  • mysqlnd_memcache_set — Associate a MySQL connection with a Memcache connection


Returns information about the plugin configuration

  • « Mysqlnd_memcache Functions
  • mysqlnd_memcache_set »
  • PHP Manual
  • Mysqlnd_memcache Functions
  • Returns information about the plugin configuration

mysqlnd_memcache_get_config

(PECL mysqlnd_memcache >= 1.0.0)

mysqlnd_memcache_get_config — Returns information about the plugin configuration

Description

mysqlnd_memcache_get_config ( mixed $connection ) : array

This function returns an array of all mysqlnd_memcache related configuration information that is attached to the MySQL connection. This includes MySQL, the Memcache object provided via mysqlnd_memcache_set(), and the table mapping configuration that was automatically collected from the MySQL Server.

Parameters

connection

A handle to a MySQL Server using one of the MySQL API extensions for PHP, which are PDO_MYSQL, mysqli or ext/mysql.

Return Values

An array of mysqlnd_memcache configuration information on success, otherwise FALSE.

The returned array has these elements:

mysqlnd_memcache_get_config() array structure
Array Key | Description
memcached | Instance of Memcached associated to this MySQL connection by mysqlnd_memcache_set(). You can use this to change settings of the memcache connection, or directly by querying the server on this connection.
pattern | The PCRE regular expression used to match the SQL query sent to the server. Queries matching this pattern will be further analyzed to decide whether the query can be intercepted and sent via the memcache interface or whether the query is sent using the general MySQL protocol to the server. The pattern is either the default pattern (MYSQLND_MEMCACHE_DEFAULT_REGEXP) or it is set via mysqlnd_memcache_set().
mappings | An associative array with a list of all configured containers as they were discovered by this plugin. The key for these elements is the name of the container in the MySQL configuration. The value is described below. The contents of this field is created by querying the MySQL Server during association to MySQL and a memcache connection using mysqlnd_memcache_set().
mapping_query | An SQL query used during mysqlnd_memcache_set() to identify the available containers and mappings. The result of that query is provided in the mappings element.
Mapping entry structure
Array Key | Description
prefix | A prefix used while accessing data via memcache. With the MySQL InnoDB Memcache Deamon plugin, this usually begins with @@ and ends with a configurable separator. This prefix is placed in front of the key value while using the memcache protocol.
schema_name | Name of the schema (database) which contains the table being accessed.
table_name | Name of the table which contains the data accessible via memcache protocol.
id_field_name | Name of the database field (column) with the id used as key when accessing the table via memcache. Often this is the database field having a primary key.
separator The separator used to split the different field values. This is needed as memcache only provides access to a single value while MySQL can map multiple columns to this value.

Note:

The separator, which can be set in the MySQL Server configuration, should not be part of any value retrieved via memcache because proper mapping can't be guaranteed.

fields | An array with the name of all fields available for this mapping.

Examples

Example #1 mysqlnd_memcache_get_config() example

<?php
$mysqli = new mysqli("host", "user", "passwd", "database");
$memc = new Memcached();
$memc->addServer("host", 11211);
mysqlnd_memcache_set($mysqli, $memc);

var_dump(mysqlnd_memcache_get_config($mysqli));
?>

The above example will output:

array(4) {
  ["memcached"]=>
  object(Memcached)#2 (0) {
  }
  ["pattern"]=>
  string(125) "/^\s*SELECT\s*(.+?)\s*FROM\s*`?([a-z0-9_]+)`?\s*WHERE\s*`?([a-z0-9_]+)`?\s*=\s*(?(?=["'])["']([^"']*)["']|([0-9e\.]*))\s*$/is"
  ["mappings"]=>
  array(1) {
    ["mymem_test"]=>
    array(6) {
      ["prefix"]=>
      string(13) "@@mymem_test."
      ["schema_name"]=>
      string(4) "test"
      ["table_name"]=>
      string(10) "mymem_test"
      ["id_field_name"]=>
      string(2) "id"
      ["separator"]=>
      string(1) "|"
      ["fields"]=>
      array(3) {
        [0]=>
        string(2) "f1"
        [1]=>
        string(2) "f2"
        [2]=>
        string(2) "f3"
      }
    }
  }
  ["mapping_query"]=>
  string(209) "    SELECT c.name,
                          CONCAT('@@', c.name, (SELECT value FROM innodb_memcache.config_options WHERE name = 'table_map_delimiter')) AS key_prefix,
                          c.db_schema,
                          c.db_table,
                          c.key_columns,
                          c.value_columns,
                          (SELECT value FROM innodb_memcache.config_options WHERE name = 'separator') AS sep
                     FROM innodb_memcache.containers c"
}

See Also

  • mysqlnd_memcache_set() - Associate a MySQL connection with a Memcache connection


Associate a MySQL connection with a Memcache connection

  • « mysqlnd_memcache_get_config
  • Change History »
  • PHP Manual
  • Mysqlnd_memcache Functions
  • Associate a MySQL connection with a Memcache connection

mysqlnd_memcache_set

(PECL mysqlnd_memcache >= 1.0.0)

mysqlnd_memcache_set — Associate a MySQL connection with a Memcache connection

Description

mysqlnd_memcache_set ( mixed $mysql_connection [, Memcached $memcache_connection [, string $pattern [, callback $callback ]]] ) : bool

Associate mysql_connection with memcache_connection using pattern as a PCRE regular expression, and callback as a notification callback or to unset the association of mysql_connection.

While associating a MySQL connection with a Memcache connection, this function will query the MySQL Server for its configuration. It will automatically detect whether the server is configured to use the InnoDB Memcache Daemon Plugin or MySQL Cluster NDB Memcache support. It will also query the server to automatically identify exported tables and other configuration options. The results of this automatic configuration can be retrieved using mysqlnd_memcache_get_config().

Parameters

mysql_connection

A handle to a MySQL Server using one of the MySQL API extensions for PHP, which are PDO_MYSQL, mysqli or ext/mysql.

memcache_connection

A Memcached instance with a connection to the MySQL Memcache Daemon plugin. If this parameter is omitted, then mysql_connection will be unassociated from any memcache connection. And if a previous association exists, then it will be replaced.

pattern

A regular expression in Perl Compatible Regular Expression syntax used to identify potential Memcache-queries. The query should have three sub patterns. The first subpattern contains the requested field list, the second the name of the ID column from the query and the third the requested value. If this parameter is omitted or os set to NULL, then a default pattern will be used.

callback

A callback which will be used whenever a query is being sent to MySQL. The callback will receive a single boolean parameter telling if a query was sent via Memcache.

Return Values

TRUE if the association or disassociation is successful, otherwise FALSE if there is an error.

Examples

Example #1 mysqlnd_memcache_set() example with var_dump() as a simple debugging callback.

<?php
$mysqli = new mysqli("host", "user", "passwd", "database");
$memc = new Memcached();
$memc->addServer("host", 11211);
mysqlnd_memcache_set($mysqli, $memc, NULL, 'var_dump');

/* This query will be intercepted and executed via Memcache protocol */
echo "Sending query for id via Memcache: ";
$mysqli->query("SELECT f1, f2, f3 FROM test WHERE id = 1");

/* f1 is not configured as valid key field, this won't be sent via Memcache */
echo "Sending query for f1 via Memcache: ";
$mysqli->query("SELECT id FROM test WHERE f1 = 1");

mysqlnd_memcache_set($mysqli);

/* Now the regular MySQL protocol will be used */
echo "var_dump won't be invoked: ";
$mysqli->query("SELECT f1, f2, f3 WHERE id = 1");

?>

The above example will output:

Sending query for id via Memcache: bool(true)
Sending query for f1 via Memcache: bool(false)
var_dump won't be invoked:

See Also

  • mysqlnd_memcache_get_config() - Returns information about the plugin configuration


Change History

Table of Contents

  • PECL/mysqlnd_memcache 1.0 series

This change history is a high level summary of selected changes that may impact applications and/or break backwards compatibility.

See also the CHANGES file in the source distribution for a complete list of changes.


PECL/mysqlnd_memcache 1.0 series

1.0.0-alpha

  • Release date: TBD
  • Motto/theme: Basic mapping of SQL SELECT to a MySQL Memcache plugin access.

The initial release does map basic SQL SELECT statements to a MySQL Memcache plugin access. This bares potential performance benefits as the direct key-value access to MySQL storage using the Memcache protocol is usually faster than using SQL access.


Oracle OCI8

  • Introduction
  • 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_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_fetch — Fetches the next row from a query into internal buffers
    • 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_raw — Tell the raw Oracle data type of the field
    • oci_field_type — Returns a field's data type name
    • 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 12c Implicit Result Sets
    • oci_internal_debug — Enables or disables internal debug output
    • 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_statement_type — Returns the type of a statement
    • oci_unregister_taf_callback — Unregister a user-defined callback function for Oracle Database TAF
  • OCI-Collection — The OCI-Collection class
    • OCI-Collection::append — Appends element to the collection
    • OCI-Collection::assign — Assigns a value to the collection from another existing collection
    • OCI-Collection::assignElem — Assigns a value to the element of the collection
    • OCI-Collection::free — Frees the resources associated with the collection object
    • OCI-Collection::getElem — Returns value of the element
    • OCI-Collection::max — Returns the maximum number of elements in the collection
    • OCI-Collection::size — Returns size of the collection
    • OCI-Collection::trim — Trims elements from the end of the collection
  • OCI-Lob — The OCI-Lob class
    • OCI-Lob::append — Appends data from the large object to another large object
    • OCI-Lob::close — Closes LOB descriptor
    • OCI-Lob::eof — Tests for end-of-file on a large object's descriptor
    • OCI-Lob::erase — Erases a specified portion of the internal LOB data
    • OCI-Lob::export — Exports LOB's contents to a file
    • OCI-Lob::flush — Flushes/writes buffer of the LOB to the server
    • OCI-Lob::free — Frees resources associated with the LOB descriptor
    • OCI-Lob::getBuffering — Returns current state of buffering for the large object
    • OCI-Lob::import — Imports file data to the LOB
    • OCI-Lob::load — Returns large object's contents
    • OCI-Lob::read — Reads part of the large object
    • OCI-Lob::rewind — Moves the internal pointer to the beginning of the large object
    • OCI-Lob::save — Saves data to the large object
    • OCI-Lob::saveFile — Alias of OCI-Lob::import
    • OCI-Lob::seek — Sets the internal pointer of the large object
    • OCI-Lob::setBuffering — Changes current state of buffering for the large object
    • OCI-Lob::size — Returns size of large object
    • OCI-Lob::tell — Returns the current position of internal pointer of large object
    • OCI-Lob::truncate — Truncates large object
    • OCI-Lob::write — Writes data to the large object
    • OCI-Lob::writeTemporary — Writes a temporary large object
    • OCI-Lob::writeToFile — Alias of OCI-Lob::export
  • OCI8 Obsolete Aliases and Functions
    • ocibindbyname — Alias of oci_bind_by_name
    • ocicancel — Alias of oci_cancel
    • ocicloselob — Alias of OCI-Lob::close
    • ocicollappend — Alias of OCI-Collection::append
    • ocicollassign — Alias of OCI-Collection::assign
    • ocicollassignelem — Alias of OCI-Collection::assignElem
    • ocicollgetelem — Alias of OCI-Collection::getElem
    • ocicollmax — Alias of OCI-Collection::max
    • ocicollsize — Alias of OCI-Collection::size
    • ocicolltrim — Alias of OCI-Collection::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 OCI-Collection::free
    • ocifreecursor — Alias of oci_free_statement
    • ocifreedesc — Alias of OCI-Lob::free
    • ocifreestatement — Alias of oci_free_statement
    • ociinternaldebug — Alias of oci_internal_debug
    • ociloadlob — Alias of OCI-Lob::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 OCI-Lob::save
    • ocisavelobfile — Alias of OCI-Lob::import
    • ociserverversion — Alias of oci_server_version
    • ocisetprefetch — Alias of oci_set_prefetch
    • ocistatementtype — Alias of oci_statement_type
    • ociwritelobtofile — Alias of OCI-Lob::export
    • ociwritetemporarylob — Alias of OCI-Lob::writeTemporary


Introduction

These functions allow you to access Oracle Database 19c, 18c, 12c, 11g, 10g, 9i and 8i. 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

The OCI8 1.4 extension is included with PHP 5.3, PHP 5.4 and PHP 5.5. It is also available from » PECL. A newer OCI8 2.0 version is available only from » PECL. OCI8 1.4 requires Oracle 12c, 11g, 10g or 9iR2 client libraries and will install on PHP 4.3.9 onwards. OCI8 2.0 requires Oracle 12c, 11g or 10g client libraries and will install on PHP 5.2 onwards.

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.

To use Oracle Instant Client, install the basic or basiclite Oracle Instant Client ZIP file or RPM package. When building PHP from source code, also install the sdk ZIP file or devel RPM package.

You must run PHP with the same, or a more recent, version of the Oracle libraries that OCI8 was built with.

On Windows, the php_oci8 DLL needs Oracle client libraries from version 10gR2 or greater. In PHP 5.3 up to and including PHP 5.3.5, the php_oci8_11g DLL requires Oracle 11gR1 or greater client libraries. From PHP 5.3.6 the php_oci8_11g DLL requires Oracle 11gR2 or greater client libraries. The php_oci8_12c DLL from PECL requires Oracle 12cR1 client libraries. With some versions of Instant Client you may additionally need mfc71.dll and msvcr71.dll libraries.

Note:

If OCI8 uses 9iR2 client libraries, then PHP can connect to Oracle Database 8i, 9iR2, 10g or 11g. If OCI8 uses 10gR2 client libraries, the database can be 9iR2, 10g, 11g or 12c. If OCI8 uses 11g client libraries, the database can be 9iR2, 10g, 11g or 12c. If OCI8 uses 12c client libraries, the database can be 10gR2, 11g or 12c.

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.

To enable the OCI8 extension, configure PHP with the option --with-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 11.2 libraries, then PHP should also be deployed and run with Oracle 11.2 libraries. PHP applications can connect to other versions of Oracle Database, since Oracle has client-server cross-version compatibility.

Installing OCI8 as a Shared Extension

The configuration shared option builds 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 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/12.1/client/lib

    Note that Oracle Instant Client support first appeared in PHP 4.3.11 and 5.0.4 and originally used the option --with-oci8-instant-client to configure PHP.

  • 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

Configure PHP to include OCI8 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 from PECL

The OCI8 extension can be added to an existing PHP installation either automatically or manually from » PECL.

For an automated install follow these steps:

  • 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

    When prompted, enter either the value of $ORACLE_HOME, or instantclient,/path/to/instant/client/lib.

    Note: Do not enter the variable $ORACLE_HOME because it will not be expanded. Instead, enter the actual path of the Oracle home directory.

For a manual install when the pecl command is not available, download the PECL OCI8 package, e.g. oci8-1.4.10.tgz.

  • Extract the package:

    tar -zxf oci8-1.4.10.tgz
cd oci8-1.4.10

  • 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

After either an automatic or manual install, 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 on Windows

When using Oracle 10gR2 client libraries on Windows, uncomment the php.ini line extension=php_oci8.dll. When using Oracle 11gR2 or later client libraries, uncomment extension=php_oci8_11g.dll or extension=php_oci8.dll. With Oracle 12c libraries use 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 DYLD_LIBRARY_PATH, LIBPATH, or SHLIB_PATH) to the location of the Oracle libraries, for example $ORACLE_HOME/lib or /usr/lib/oracle/11.1/client/lib. This variable is not needed if the libraries are located by a different search mechanism, such as with ldconfig or with LD_PRELOAD.
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 $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. With Oracle 10gR2 XE do:

    $ . /usr/lib/oracle/xe/app/oracle/product/10.2.0/server/bin/oracle_env.sh

With Oracle 11gR2 XE do:

    $ . /u01/app/oracle/product/11.2.0/xe/bin/oracle_env.sh

For other versions of the Oracle database do:

    $ . /usr/local/bin/oraenv

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 | "" | PHP_INI_ALL | Available since PHP 5.3 (PECL OCI8 1.3).
oci8.default_prefetch | "100" | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.events | Off | PHP_INI_SYSTEM | Available since PHP 5.3 (PECL OCI8 1.3).
oci8.max_persistent | "-1" | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.old_oci_close_semantics | Off | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.persistent_timeout | "-1" | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.ping_interval | "60" | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.privileged_connect | Off | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).
oci8.statement_cache_size | "20" | PHP_INI_SYSTEM | Available since PHP 5.1.2 (PECL OCI8 1.1).

Here's a short explanation of the configuration directives.

oci8.connection_class string

This user defined text is used by Oracle 11g Database Resident Connection Pooling (DRCP) connections to sub-partition the connection pool. It allows 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 libraries and the database must be Oracle 11g. The 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.

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.

In PHP 5.3 (PECL OCI8 1.3.4) the default value was increased from 10 to 100.

In PHP 5.3.2 (PECL OCI8 1.4) the minimum value settable was reduced from 1 to 0, allowing prefetching to be turned off.

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 boolean

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 boolean

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.

Note: In PHP 5.3 (PECL OCI8 1.3), persistent connections can be closed with oci_close().

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.privileged_connect boolean

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, 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. Introduced in PHP 5.3 and PECL OCI8 1.3.4.
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 OCI-Lob::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. Introduced in PHP 5.3.2 (PECL OCI8 1.4).
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 OCI-Lob::seek to set the seek position.
OCI_SEEK_END | Used with OCI-Lob::seek to set the seek position.
OCI_SEEK_SET | Used with OCI-Lob::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 OCI-Lob::writeTemporary to indicate that a temporary BLOB should be created.
OCI_TEMP_CLOB | Used with OCI-Lob::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. Note: in PHP < 5.0 it was called OCI_B_SQLT_NTY.
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.


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); // use OCI_DEFAULT for PHP <= 5.3.1
$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 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 FCGI, 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.

DRCP Connection Pooling

PHP from 5.3 (PECL OCI8 1.3) 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, build PHP with the OCI8 1.3 (or later) 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 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.

DRCP Recommendations and Known Limitations

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.

From OCI8 1.3, 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.

If the Oracle Database is version 11.1.0.6, then the Oracle database patch for Oracle bug 6474441 must be applied to use DRCP. Without this patch, errors such as ORA-01000: maximum open cursors exceeded, ORA-01001 invalid cursor or ORA-01002 fetch out of sequence may occur. This bug was fixed in Oracle 11.1.0.7 onwards.

If the Oracle 11.1.0.6 database patch cannot be applied, one of the following three workarounds can be used instead:

  • Connect using Oracle Dedicated or Shared servers instead of DRCP.
  • Set PHP's oci8.statement_cache_size to 0.
  • Set an event in the database initialization parameter file: event="56699 trace name context forever, level 128".

Oracle Database 11.1.0.7 and the Oracle Database 11.1.0.6 patch for Oracle bug 6474441 allow PHP applications with DRCP connection to use a database LOGON trigger to set session properties at the time of session creation. Examples of such settings are the NLS language and the date format.

If the Oracle 11.1.0.6 database patch cannot be applied, one of the following workarounds can be used instead of using LOGON triggers:

  • After logon, explicitly set the session properties using PHP application code.
  • Connect using Oracle Dedicated or Shared servers instead of DRCP.

The automatic re-establishment of PHP persistent connections after an Apache or FCGI process respawns means LOGON triggers in PHP are only recommended for setting session attributes and not for per-application user connection requests. This is even more so with DRCP due to the automatic pool sizing and with the way LOGON triggers fire with DRCP authentication.


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

The following example registers 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");
                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;
    }
}

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
$fn_name = 'MyClass::TAFCallback';

oci_register_taf_callback($conn, $fn_name); // Register TAFCallback to Oracle TAF

$sql = "SELECT col1 FROM mytab";
$stmt = oci_parse($conn, $sql);
oci_define_by_name($stmt, 'COL1', $col1);

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

$e = oci_execute($stmt);
if ($e == false)
{
    // do error handling, if oci_execute() fails
    // var_dump(oci_error($stmt));
}
while (oci_fetch($stmt))
{
    echo "COL1 value is $col1<br>\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 2.0 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 ^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

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_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_fetch — Fetches the next row from a query into internal buffers
  • 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_raw — Tell the raw Oracle data type of the field
  • oci_field_type — Returns a field's data type name
  • 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 12c Implicit Result Sets
  • oci_internal_debug — Enables or disables internal debug output
  • 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_statement_type — Returns the type of a statement
  • oci_unregister_taf_callback — Unregister a user-defined callback function for Oracle Database TAF


Binds a PHP array to an Oracle PL/SQL array parameter

  • « OCI8 Functions
  • oci_bind_by_name »
  • PHP Manual
  • OCI8 Functions
  • Binds a PHP array to an Oracle PL/SQL array parameter

oci_bind_array_by_name

(PHP 5 >= 5.1.2, PHP 7, 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 $name , array &$var_array , int $max_table_length [, int $max_item_length = -1 [, int $type = SQLT_AFC ]] ) : bool

Binds the PHP array var_array to the Oracle placeholder name, 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.

name

The Oracle placeholder.

var_array

An array.

max_table_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);

?>


Binds a PHP variable to an Oracle placeholder

  • « oci_bind_array_by_name
  • oci_cancel »
  • PHP Manual
  • OCI8 Functions
  • Binds a PHP variable to an Oracle placeholder

oci_bind_by_name

(PHP 5, PHP 7, 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 $bv_name , mixed &$variable [, int $maxlength = -1 [, int $type = SQLT_CHR ]] ) : bool

Binds a PHP variable variable to the Oracle bind variable placeholder bv_name. 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 maxlength 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 maxlength 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 identifer.

bv_name

The colon-prefixed bind variable placeholder used in the statement. The colon is optional in bv_name. Oracle does not use question marks for placeholders.

variable

The PHP variable to be associated with bv_name

maxlength

Sets the maximum length for the data. If you set it to -1, this function will use the current length of variable to set the maximum length. In this case the variable 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 OCI8 2.0.7 and 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

?>

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Warning

Do not use magic_quotes_gpc or 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 variable 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


Cancels reading from cursor

  • « oci_bind_by_name
  • oci_client_version »
  • PHP Manual
  • OCI8 Functions
  • Cancels reading from cursor

oci_cancel

(PHP 5, PHP 7, 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.


Returns the Oracle client library version

  • « oci_cancel
  • oci_close »
  • PHP Manual
  • OCI8 Functions
  • Returns the Oracle client library version

oci_client_version

(PHP 5 >= 5.3.7, PHP 7, PECL OCI8 >= 1.4.6)

oci_client_version — Returns the Oracle client library version

Description

oci_client_version ( void ) : 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: 11.2.0.2
?>

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


Closes an Oracle connection

  • « oci_client_version
  • oci_commit »
  • PHP Manual
  • OCI8 Functions
  • Closes an Oracle connection

oci_close

(PHP 5, PHP 7, 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 TRUE on success or FALSE on failure.

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:

Prior to version PHP 5.1.2 (PECL OCI8 1.1) oci_close() was a no-op. In more recent versions it correctly closes the Oracle connection. Use oci8.old_oci_close_semantics option to restore old behavior of this function.

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


Commits the outstanding database transaction

  • « oci_close
  • oci_connect »
  • PHP Manual
  • OCI8 Functions
  • Commits the outstanding database transaction

oci_commit

(PHP 5, PHP 7, 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
// Use OCI_DEFAULT as the flag for PHP <= 5.3.1.  The two flags are equivalent
$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


Connect to an Oracle database

  • « oci_commit
  • oci_define_by_name »
  • PHP Manual
  • OCI8 Functions
  • Connect to an Oracle database

oci_connect

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_connect — Connect to an Oracle database

Description

oci_connect ( string $username , string $password [, string $connection_string [, string $character_set [, int $session_mode ]]] ) : resource

Returns a connection identifier needed for most other OCI8 operations.

See Connection Handling for general information on connection management and connection pooling.

From PHP 5.1.2 (PECL OCI8 1.1) oci_close() can be used to close the connection.

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

character_set

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


Associates a PHP variable with a column for query fetches

  • « oci_connect
  • oci_error »
  • PHP Manual
  • OCI8 Functions
  • Associates a PHP variable with a column for query fetches

oci_define_by_name

(PHP 5, PHP 7, 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_name , mixed &$variable [, int $type = SQLT_CHR ] ) : 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_name

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.

variable

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


Returns the last error found

  • « oci_define_by_name
  • oci_execute »
  • PHP Manual
  • OCI8 Functions
  • Returns the last error found

oci_error

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_error — Returns the last error found

Description

oci_error ([ resource $resource ] ) : array

Returns the last error found.

The function should be called immediately after an error occurs. Errors are cleared by a successful statement.

Parameters

resource

For most errors, resource is the
resource handle that was passed to the failing function call.
For connection errors with oci_connect(),
oci_new_connect() or
oci_pconnect() do not pass resource.

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 | integer | The Oracle error number.
message | string | The Oracle error text.
offset | integer | 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.

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


Executes a statement

  • « oci_error
  • oci_fetch_all »
  • PHP Manual
  • OCI8 Functions
  • Executes a statement

oci_execute

(PHP 5, PHP 7, 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. Prior to PHP 5.3.2 (PECL OCI8 1.4) use OCI_DEFAULT which is equivalent to OCI_NO_AUTO_COMMIT.

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);  // use OCI_DEFAULT for PHP <= 5.3.1
}
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


Fetches multiple rows from a query into a two-dimensional array

  • « oci_execute
  • oci_fetch_array »
  • PHP Manual
  • OCI8 Functions
  • Fetches multiple rows from a query into a two-dimensional array

oci_fetch_all

(PHP 5, PHP 7, 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 $skip = 0 [, int $maxrows = -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.

skip

The number of initial rows to discard when fetching the result. The default value is 0, so the first row onwards is returned.

maxrows

The number of rows to return. The default is -1 meaning return all the rows from skip + 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, or FALSE on failure.

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


Returns the next row from a query as an associative or numeric array

  • « oci_fetch_all
  • oci_fetch_assoc »
  • PHP Manual
  • OCI8 Functions
  • Returns the next row from a query as an associative or numeric array

oci_fetch_array

(PHP 5, PHP 7, 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 ] ) : array

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 12c 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 12c 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 and Oracle Database 12c
// 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


Returns the next row from a query as an associative array

  • « oci_fetch_array
  • oci_fetch_object »
  • PHP Manual
  • OCI8 Functions
  • Returns the next row from a query as an associative array

oci_fetch_assoc

(PHP 5, PHP 7, 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

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


Returns the next row from a query as an object

  • « oci_fetch_assoc
  • oci_fetch_row »
  • PHP Manual
  • OCI8 Functions
  • Returns the next row from a query as an object

oci_fetch_object

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_fetch_object — Returns the next row from a query as an object

Description

oci_fetch_object ( resource $statement ) : object

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


Returns the next row from a query as a numeric array

  • « oci_fetch_object
  • oci_fetch »
  • PHP Manual
  • OCI8 Functions
  • Returns the next row from a query as a numeric array

oci_fetch_row

(PHP 5, PHP 7, 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

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


Fetches the next row from a query into internal buffers

  • « oci_fetch_row
  • oci_field_is_null »
  • PHP Manual
  • OCI8 Functions
  • Fetches the next row from a query into internal buffers

oci_fetch

(PHP 5, PHP 7, 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 12c 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


Checks if a field in the currently fetched row is NULL

  • « oci_fetch
  • oci_field_name »
  • PHP Manual
  • OCI8 Functions
  • Checks if a field in the currently fetched row is NULL

oci_field_is_null

(PHP 5, PHP 7, 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 , mixed $field ) : bool

Checks if the given field from the current row of statement is NULL.

Parameters

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Return Values

Returns TRUE if field 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);

?>

Notes

Note:

In PHP versions before 5.0.0 you must use ocicolumnisnull() instead. This name still can be used, it was left as alias of oci_field_is_null() for downwards compatability. This, however, is deprecated and not recommended.


Returns the name of a field from the statement

  • « oci_field_is_null
  • oci_field_precision »
  • PHP Manual
  • OCI8 Functions
  • Returns the name of a field from the statement

oci_field_name

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_field_name — Returns the name of a field from the statement

Description

oci_field_name ( resource $statement , mixed $field ) : string

Returns the name of the field.

Parameters

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Return Values

Returns the name as a string, or FALSE on errors.

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

?>

Notes

Note:

In PHP versions before 5.0.0 you must use ocicolumnname() instead. This name still can be used, it was left as alias of oci_field_name() for downwards compatability. This, however, is deprecated and not recommended.

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


Tell the precision of a field

  • « oci_field_name
  • oci_field_scale »
  • PHP Manual
  • OCI8 Functions
  • Tell the precision of a field

oci_field_precision

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_field_precision — Tell the precision of a field

Description

oci_field_precision ( resource $statement , mixed $field ) : int

Returns precision of the field.

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.

field

Can be the field's index (1-based) or name.

Return Values

Returns the precision as an integer, or FALSE on errors.

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

?>

Notes

Note:

In PHP versions before 5.0.0 you must use ocicolumnprecision() instead. This name still can be used, it was left as alias of oci_field_precision() for downwards compatability. This, however, is deprecated and not recommended.

See Also

  • oci_field_scale() - Tell the scale of the field
  • oci_field_type() - Returns a field's data type name


Tell the scale of the field

  • « oci_field_precision
  • oci_field_size »
  • PHP Manual
  • OCI8 Functions
  • Tell the scale of the field

oci_field_scale

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_field_scale — Tell the scale of the field

Description

oci_field_scale ( resource $statement , mixed $field ) : int

Returns the scale of the column with field 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.

field

Can be the field's index (1-based) or name.

Return Values

Returns the scale as an integer, or FALSE on errors.

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

?>

Notes

Note:

In PHP versions before 5.0.0 you must use ocicolumnscale() instead. This name still can be used, it was left as alias of oci_field_scale() for downwards compatability. This, however, is deprecated and not recommended.

See Also

  • oci_field_precision() - Tell the precision of a field
  • oci_field_type() - Returns a field's data type name


Returns field's size

  • « oci_field_scale
  • oci_field_type_raw »
  • PHP Manual
  • OCI8 Functions
  • Returns field's size

oci_field_size

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_field_size — Returns field's size

Description

oci_field_size ( resource $statement , mixed $field ) : int

Returns the size of a field.

Parameters

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Return Values

Returns the size of a field in bytes, or FALSE on errors.

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

?>

Notes

Note:

In PHP versions before 5.0.0 you must use ocicolumnsize() instead. This name still can be used, it was left as alias of oci_field_size() for downwards compatability. This, however, is deprecated and not recommended.

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


Tell the raw Oracle data type of the field

  • « oci_field_size
  • oci_field_type »
  • PHP Manual
  • OCI8 Functions
  • Tell the raw Oracle data type of the field

oci_field_type_raw

(PHP 5, PHP 7, 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 , mixed $field ) : int

Returns Oracle's raw "SQLT" data type of the field.

If you want a field's type name, then use oci_field_type() instead.

Parameters

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Return Values

Returns Oracle's raw data type as a number, or FALSE on errors.

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

?>

Notes

Note:

In PHP versions before 5.0.0 you must use ocicolumntyperaw() instead. This name still can be used, it was left as alias of oci_field_type_raw() for downwards compatability. This, however, is deprecated and not recommended.


Returns a field's data type name

  • « oci_field_type_raw
  • oci_free_descriptor »
  • PHP Manual
  • OCI8 Functions
  • Returns a field's data type name

oci_field_type

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_field_type — Returns a field's data type name

Description

oci_field_type ( resource $statement , mixed $field ) : mixed

Returns a field's data type name.

Parameters

statement

A valid OCI statement identifier.

field

Can be the field's index (1-based) or name.

Return Values

Returns the field data type as a string, or FALSE on errors.

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

?>

Notes

Note:

In PHP versions before 5.0.0 you must use ocicolumntype() instead. This name still can be used, it was left as alias of oci_field_type() for downwards compatability. This, however, is deprecated and not recommended.

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


Frees a descriptor

  • « oci_field_type
  • oci_free_statement »
  • PHP Manual
  • OCI8 Functions
  • Frees a descriptor

oci_free_descriptor

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_free_descriptor — Frees a descriptor

Description

oci_free_descriptor ( resource $descriptor ) : bool

Frees a 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 OCI-LOB::free.

See Also

  • OCI-LOB::free


Frees all resources associated with statement or cursor

  • « oci_free_descriptor
  • oci_get_implicit_resultset »
  • PHP Manual
  • OCI8 Functions
  • Frees all resources associated with statement or cursor

oci_free_statement

(PHP 5, PHP 7, 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.


Returns the next child statement resource from a parent statement resource that has Oracle Database 12c Implicit Result Sets

  • « oci_free_statement
  • oci_internal_debug »
  • PHP Manual
  • OCI8 Functions
  • Returns the next child statement resource from a parent statement resource that has Oracle Database 12c Implicit Result Sets

oci_get_implicit_resultset

(PHP 5 >= 5.6.0, PHP 7, PECL OCI8 >= 2.0.0)

oci_get_implicit_resultset — Returns the next child statement resource from a parent statement resource that has Oracle Database 12c Implicit Result Sets

Description

oci_get_implicit_resultset ( resource $statement ) : resource

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 Oracle's 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().


Enables or disables internal debug output

  • « oci_get_implicit_resultset
  • oci_lob_copy »
  • PHP Manual
  • OCI8 Functions
  • Enables or disables internal debug output

oci_internal_debug

(PHP 5, PHP 7, PECL OCI8 >= 1.1.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:

In PHP versions before 5.0.0 you must use ociinternaldebug() instead. This name still can be used, it was left as alias of oci_internal_debug() for downwards compatability. This, however, is deprecated and not recommended.


Copies large object

  • « oci_internal_debug
  • oci_lob_is_equal »
  • PHP Manual
  • OCI8 Functions
  • Copies large object

oci_lob_copy

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_lob_copy — Copies large object

Description

oci_lob_copy ( OCI-Lob $lob_to , OCI-Lob $lob_from [, int $length = 0 ] ) : 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 OCI-Lob::seek() to move LOB internal pointers.

Parameters

lob_to

The destination LOB.

lob_from

The copied LOB.

length

Indicates the length of data to be copied.

Return Values

Returns TRUE on success or FALSE on failure.


Compares two LOB/FILE locators for equality

  • « oci_lob_copy
  • oci_new_collection »
  • PHP Manual
  • OCI8 Functions
  • Compares two LOB/FILE locators for equality

oci_lob_is_equal

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_lob_is_equal — Compares two LOB/FILE locators for equality

Description

oci_lob_is_equal ( OCI-Lob $lob1 , OCI-Lob $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.


Allocates new collection object

  • « oci_lob_is_equal
  • oci_new_connect »
  • PHP Manual
  • OCI8 Functions
  • Allocates new collection object

oci_new_collection

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_new_collection — Allocates new collection object

Description

oci_new_collection ( resource $connection , string $tdo [, string $schema = NULL ] ) : OCI-Collection

Allocates a new collection object.

Parameters

connection

An Oracle connection identifier, returned by oci_connect() or oci_pconnect().

tdo

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 the default value.

Return Values

Returns a new OCICollection object or FALSE on error.

Notes

Note:

In PHP versions before 5.0.0 you must use ocinewcollection() instead. This name still can be used, it was left as alias of oci_new_collection() for downwards compatability. This, however, is deprecated and not recommended.


Connect to the Oracle server using a unique connection

  • « oci_new_collection
  • oci_new_cursor »
  • PHP Manual
  • OCI8 Functions
  • Connect to the Oracle server using a unique connection

oci_new_connect

(PHP 5, PHP 7, 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 [, string $character_set [, int $session_mode ]]] ) : resource

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

character_set

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

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


Allocates and returns a new cursor (statement handle)

  • « oci_new_connect
  • oci_new_descriptor »
  • PHP Manual
  • OCI8 Functions
  • Allocates and returns a new cursor (statement handle)

oci_new_cursor

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_new_cursor — Allocates and returns a new cursor (statement handle)

Description

oci_new_cursor ( resource $connection ) : resource

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

?>

Notes

Note:

In PHP versions before 5.0.0 you must use ocinewcursor() instead. This name still can be used, it was left as alias of oci_new_cursor() for downwards compatability. This, however, is deprecated and not recommended.


Initializes a new empty LOB or FILE descriptor

  • « oci_new_cursor
  • oci_num_fields »
  • PHP Manual
  • OCI8 Functions
  • Initializes a new empty LOB or FILE descriptor

oci_new_descriptor

(PHP 5, PHP 7, 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 ] ) : OCI-Lob

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, FALSE on error.

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

Notes

Note:

In PHP versions before 5.0.0 you must use ocinewdescriptor() instead. This name still can be used, it was left as alias of oci_new_descriptor() for downwards compatability. This, however, is deprecated and not recommended.

See Also

  • oci_bind_by_name() - Binds a PHP variable to an Oracle placeholder


Returns the number of result columns in a statement

  • « oci_new_descriptor
  • oci_num_rows »
  • PHP Manual
  • OCI8 Functions
  • Returns the number of result columns in a statement

oci_num_fields

(PHP 5, PHP 7, 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 integer, or FALSE on errors.

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

?>

Notes

Note:

In PHP versions before 5.0.0 you must use ocinumcols() instead. This name still can be used, it was left as alias of oci_num_fields() for downwards compatability. This, however, is deprecated and not recommended.


Returns number of rows affected during statement execution

  • « oci_num_fields
  • oci_parse »
  • PHP Manual
  • OCI8 Functions
  • Returns number of rows affected during statement execution

oci_num_rows

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_num_rows — Returns number of rows affected during statement execution

Description

oci_num_rows ( resource $statement ) : int

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

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.

Note:

In PHP versions before 5.0.0 you must use ocirowcount() instead. This name still can be used, it was left as alias of oci_num_rows() for downwards compatability. This, however, is deprecated and not recommended.


Prepares an Oracle statement for execution

  • « oci_num_rows
  • oci_password_change »
  • PHP Manual
  • OCI8 Functions
  • Prepares an Oracle statement for execution

oci_parse

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_parse — Prepares an Oracle statement for execution

Description

oci_parse ( resource $connection , string $sql_text ) : resource

Prepares sql_text 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_text

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_text. The only way to find out if sql_text 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


Changes password of Oracle's user

  • « oci_parse
  • oci_pconnect »
  • PHP Manual
  • OCI8 Functions
  • Changes password of Oracle's user

oci_password_change

(PHP 5, PHP 7, 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 $dbname , 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.

dbname

The database name.

Return Values

Returns TRUE 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.

Note:

In PHP versions before 5.0.0 you must use ocipasswordchange() instead. This name still can be used, it was left as alias of oci_password_change() for downwards compatability. This, however, is deprecated and not recommended.


Connect to an Oracle database using a persistent connection

  • « oci_password_change
  • oci_register_taf_callback »
  • PHP Manual
  • OCI8 Functions
  • Connect to an Oracle database using a persistent connection

oci_pconnect

(PHP 5, PHP 7, 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 [, string $character_set [, int $session_mode ]]] ) : resource

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 FastCGI/CGI process). See the Persistent Database Connections 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, 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]. 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 $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.

character_set

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: Starting with PHP 5.1.2 and PECL OCI8 1.1, 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


Register a user-defined callback function for Oracle Database TAF

  • « oci_pconnect
  • oci_result »
  • PHP Manual
  • OCI8 Functions
  • Register a user-defined callback function for Oracle Database TAF

oci_register_taf_callback

(PHP 7.0 >= 7.0.21, PHP 7 >= 7.1.7, 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 [, mixed $callbackFn ] ) : 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.

callbackFn

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


Returns field's value from the fetched row

  • « oci_register_taf_callback
  • oci_rollback »
  • PHP Manual
  • OCI8 Functions
  • Returns field's value from the fetched row

oci_result

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_result — Returns field's value from the fetched row

Description

oci_result ( resource $statement , mixed $field ) : mixed

Returns the data from field 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

field

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

?>

Notes

Note:

In PHP versions before 5.0.0 you must use ociresult() instead. This name still can be used, it was left as alias of oci_result() for downwards compatability. This, however, is deprecated and not recommended.

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


Rolls back the outstanding database transaction

  • « oci_result
  • oci_server_version »
  • PHP Manual
  • OCI8 Functions
  • Rolls back the outstanding database transaction

oci_rollback

(PHP 5, PHP 7, 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
// Use OCI_DEFAULT as the flag for PHP <= 5.3.1.  The two flags are equivalent
$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


Returns the Oracle Database version

  • « oci_rollback
  • oci_set_action »
  • PHP Manual
  • OCI8 Functions
  • Returns the Oracle Database version

oci_server_version

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_server_version — Returns the Oracle Database version

Description

oci_server_version ( resource $connection ) : string

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

?>

Notes

Note:

In PHP versions before 5.0.0 you must use ociserverversion() instead. This old name still can be used. However it is deprecated and not recommended.

See Also

  • oci_client_version() - Returns the Oracle client library version


Sets the action name

  • « oci_server_version
  • oci_set_call_timeout »
  • PHP Manual
  • OCI8 Functions
  • Sets the action name

oci_set_action

(PHP 5 >= 5.3.2, PHP 7, PECL OCI8 >= 1.4.0)

oci_set_action — Sets the action name

Description

oci_set_action ( resource $connection , string $action_name ) : 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_name

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


Sets a millisecond timeout for database calls

  • « oci_set_action
  • oci_set_client_identifier »
  • PHP Manual
  • OCI8 Functions
  • Sets a millisecond timeout for database calls

oci_set_call_timeout

(PHP 7 >= 7.2.14, PHP 7.3.1 > 7.3 PECL OCI8 >= 2.2.0)

oci_set_call_timeout — Sets a millisecond timeout for database calls

Description

oci_set_call_timeout ( resource $connection , int $time_out ) : bool

Sets a timeout limiting the maxium 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().

time_out

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

?>


Sets the client identifier

  • « oci_set_call_timeout
  • oci_set_client_info »
  • PHP Manual
  • OCI8 Functions
  • Sets the client identifier

oci_set_client_identifier

(PHP 5 >= 5.3.2, PHP 7, PECL OCI8 >= 1.4.0)

oci_set_client_identifier — Sets the client identifier

Description

oci_set_client_identifier ( resource $connection , string $client_identifier ) : 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_identifier

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


Sets the client information

  • « oci_set_client_identifier
  • oci_set_db_operation »
  • PHP Manual
  • OCI8 Functions
  • Sets the client information

oci_set_client_info

(PHP 5 >= 5.3.2, PHP 7, 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


Sets the database operation

  • « oci_set_client_info
  • oci_set_edition »
  • PHP Manual
  • OCI8 Functions
  • Sets the database operation

oci_set_db_operation

(PHP 7 >= 7.2.14, PHP 7.3.1 > 7.3 PECL OCI8 >= 2.2.0)

oci_set_db_operation — Sets the database operation

Description

oci_set_db_operation ( resource $connection , string $dbop ) : 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().

dbop

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


Sets the database edition

  • « oci_set_db_operation
  • oci_set_module_name »
  • PHP Manual
  • OCI8 Functions
  • Sets the database edition

oci_set_edition

(PHP 5 >= 5.3.2, PHP 7, 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.

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.

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

?>


Sets the module name

  • « oci_set_edition
  • oci_set_prefetch »
  • PHP Manual
  • OCI8 Functions
  • Sets the module name

oci_set_module_name

(PHP 5 >= 5.3.2, PHP 7, PECL OCI8 >= 1.4.0)

oci_set_module_name — Sets the module name

Description

oci_set_module_name ( resource $connection , string $module_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().

module_name

User chosen string up to 48 bytes long.

Return Values

Returns TRUE on success or FALSE on failure.

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.

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;

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


Sets number of rows to be prefetched by queries

  • « oci_set_module_name
  • oci_statement_type »
  • PHP Manual
  • OCI8 Functions
  • Sets number of rows to be prefetched by queries

oci_set_prefetch

(PHP 5, PHP 7, 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.

Changelog

Version | Description
5.3.2 (PECL OCI8 1.4) | Before this release, rows must be >= 1.
5.3.0 (PECL OCI8 1.3.4) | Before this release, prefetching was limited to the lesser of rows rows and 1024 * rows bytes. The byte size restriction has now been removed.

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().
// A prefetch value of 0 is allowed in PHP 5.3.2 and PECL OCI8 1.4
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


Returns the type of a statement

  • « oci_set_prefetch
  • oci_unregister_taf_callback »
  • PHP Manual
  • OCI8 Functions
  • Returns the type of a statement

oci_statement_type

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

oci_statement_type — Returns the type of a statement

Description

oci_statement_type ( resource $statement ) : string

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 | Introduced in PHP 5.2.1 (PECL OCI8 1.2.3)
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);

?>


Unregister a user-defined callback function for Oracle Database TAF

  • « oci_statement_type
  • OCI-Collection »
  • PHP Manual
  • OCI8 Functions
  • Unregister a user-defined callback function for Oracle Database TAF

oci_unregister_taf_callback

(PHP 7.0 >= 7.0.23, PHP 7 >= 7.1.9, PHP 7.2, 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


The OCI-Collection class

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

Introduction

OCI8 Collection functionality.

Class synopsis

OCI-Collection {
/* Methods */
append ( mixed $value ) : bool
assign ( OCI-Collection $from ) : bool
assignElem ( int $index , mixed $value ) : bool
free ( void ) : bool
getElem ( int $index ) : mixed
max ( void ) : int
size ( void ) : int
trim ( int $num ) : bool
}

Table of Contents

  • OCI-Collection::append — Appends element to the collection
  • OCI-Collection::assign — Assigns a value to the collection from another existing collection
  • OCI-Collection::assignElem — Assigns a value to the element of the collection
  • OCI-Collection::free — Frees the resources associated with the collection object
  • OCI-Collection::getElem — Returns value of the element
  • OCI-Collection::max — Returns the maximum number of elements in the collection
  • OCI-Collection::size — Returns size of the collection
  • OCI-Collection::trim — Trims elements from the end of the collection


Appends element to the collection

  • « OCI-Collection
  • OCI-Collection::assign »
  • PHP Manual
  • OCI-Collection
  • Appends element to the collection

OCI-Collection::append

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Collection::append — Appends element to the collection

Description

OCI-Collection::append ( mixed $value ) : bool

Appends element to the end of the collection.

Parameters

value

The value to be added to the collection. Can be a string or a number.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • OCI-Collection::assign


Assigns a value to the collection from another existing collection

  • « OCI-Collection::append
  • OCI-Collection::assignElem »
  • PHP Manual
  • OCI-Collection
  • Assigns a value to the collection from another existing collection

OCI-Collection::assign

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Collection::assign — Assigns a value to the collection from another existing collection

Description

OCI-Collection::assign ( OCI-Collection $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 OCI-Collection.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • OCI-Collection::append


Assigns a value to the element of the collection

  • « OCI-Collection::assign
  • OCI-Collection::free »
  • PHP Manual
  • OCI-Collection
  • Assigns a value to the element of the collection

OCI-Collection::assignElem

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Collection::assignElem — Assigns a value to the element of the collection

Description

OCI-Collection::assignElem ( int $index , mixed $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.

See Also

  • OCI-Collection::getElem


Frees the resources associated with the collection object

  • « OCI-Collection::assignElem
  • OCI-Collection::getElem »
  • PHP Manual
  • OCI-Collection
  • Frees the resources associated with the collection object

OCI-Collection::free

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Collection::free — Frees the resources associated with the collection object

Description

OCI-Collection::free ( void ) : bool

Frees the resources associated with the collection object.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • oci_new_collection


Returns value of the element

  • « OCI-Collection::free
  • OCI-Collection::max »
  • PHP Manual
  • OCI-Collection
  • Returns value of the element

OCI-Collection::getElem

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Collection::getElem — Returns value of the element

Description

OCI-Collection::getElem ( int $index ) : mixed

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.

See Also

  • OCI-Collection::assignElem


Returns the maximum number of elements in the collection

  • « OCI-Collection::getElem
  • OCI-Collection::size »
  • PHP Manual
  • OCI-Collection
  • Returns the maximum number of elements in the collection

OCI-Collection::max

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Collection::max — Returns the maximum number of elements in the collection

Description

OCI-Collection::max ( void ) : int

Returns the maximum number of elements in the collection.

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.

See Also

  • OCI-Collection::size


Returns size of the collection

  • « OCI-Collection::max
  • OCI-Collection::trim »
  • PHP Manual
  • OCI-Collection
  • Returns size of the collection

OCI-Collection::size

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Collection::size — Returns size of the collection

Description

OCI-Collection::size ( void ) : int

Returns the size of the collection.

Return Values

Returns the number of elements in the collection or FALSE on error.

See Also

  • OCI-Collection::max


Trims elements from the end of the collection

  • « OCI-Collection::size
  • OCI-Lob »
  • PHP Manual
  • OCI-Collection
  • Trims elements from the end of the collection

OCI-Collection::trim

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Collection::trim — Trims elements from the end of the collection

Description

OCI-Collection::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.

See Also

  • OCI-Collection::size


The OCI-Lob class

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

Introduction

OCI8 LOB functionality for large binary (BLOB) and character (CLOB) objects.

Class synopsis

OCI-Lob {
/* Methods */
append ( OCI-Lob $lob_from ) : bool
close ( void ) : bool
eof ( void ) : bool
erase ([ int $offset [, int $length ]] ) : int
export ( string $filename [, int $start [, int $length ]] ) : bool
flush ([ int $flag ] ) : bool
free ( void ) : bool
getBuffering ( void ) : bool
import ( string $filename ) : bool
load ( void ) : string
read ( int $length ) : string
rewind ( void ) : bool
save ( string $data [, int $offset ] ) : bool
seek ( int $offset [, int $whence = OCI_SEEK_SET ] ) : bool
setBuffering ( bool $on_off ) : bool
size ( void ) : int
tell ( void ) : int
truncate ([ int $length = 0 ] ) : bool
write ( string $data [, int $length ] ) : int
writeTemporary ( string $data [, int $lob_type = OCI_TEMP_CLOB ] ) : bool
}

Table of Contents

  • OCI-Lob::append — Appends data from the large object to another large object
  • OCI-Lob::close — Closes LOB descriptor
  • OCI-Lob::eof — Tests for end-of-file on a large object's descriptor
  • OCI-Lob::erase — Erases a specified portion of the internal LOB data
  • OCI-Lob::export — Exports LOB's contents to a file
  • OCI-Lob::flush — Flushes/writes buffer of the LOB to the server
  • OCI-Lob::free — Frees resources associated with the LOB descriptor
  • OCI-Lob::getBuffering — Returns current state of buffering for the large object
  • OCI-Lob::import — Imports file data to the LOB
  • OCI-Lob::load — Returns large object's contents
  • OCI-Lob::read — Reads part of the large object
  • OCI-Lob::rewind — Moves the internal pointer to the beginning of the large object
  • OCI-Lob::save — Saves data to the large object
  • OCI-Lob::saveFile — Alias of OCI-Lob::import
  • OCI-Lob::seek — Sets the internal pointer of the large object
  • OCI-Lob::setBuffering — Changes current state of buffering for the large object
  • OCI-Lob::size — Returns size of large object
  • OCI-Lob::tell — Returns the current position of internal pointer of large object
  • OCI-Lob::truncate — Truncates large object
  • OCI-Lob::write — Writes data to the large object
  • OCI-Lob::writeTemporary — Writes a temporary large object
  • OCI-Lob::writeToFile — Alias of OCI-Lob::export


Appends data from the large object to another large object

  • « OCI-Lob
  • OCI-Lob::close »
  • PHP Manual
  • OCI-Lob
  • Appends data from the large object to another large object

OCI-Lob::append

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::append — Appends data from the large object to another large object

Description

OCI-Lob::append ( OCI-Lob $lob_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 OCI-Lob::flush before disabling buffering.

Parameters

lob_from

The copied LOB.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • OCI-Lob::flush
  • OCI-Lob::setBuffering
  • OCI-Lob::getBuffering


Closes LOB descriptor

  • « OCI-Lob::append
  • OCI-Lob::eof »
  • PHP Manual
  • OCI-Lob
  • Closes LOB descriptor

OCI-Lob::close

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::close — Closes LOB descriptor

Description

OCI-Lob::close ( void ) : bool

Closes descriptor of LOB or FILE. This function should be used only with OCI-Lob::writeTemporary.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • OCI-Lob::writeTemporary


Tests for end-of-file on a large object's descriptor

  • « OCI-Lob::close
  • OCI-Lob::erase »
  • PHP Manual
  • OCI-Lob
  • Tests for end-of-file on a large object's descriptor

OCI-Lob::eof

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::eof — Tests for end-of-file on a large object's descriptor

Description

OCI-Lob::eof ( void ) : bool

Tells whether the internal pointer of large object is at the end of LOB.

Return Values

Returns TRUE if internal pointer of large object is at the end of LOB. Otherwise returns FALSE.

Notes

Note:

This function will return an Oracle error if OCI-Lob::setBuffering is enabled on the LOB.

See Also

  • OCI-Lob::size


Erases a specified portion of the internal LOB data

  • « OCI-Lob::eof
  • OCI-Lob::export »
  • PHP Manual
  • OCI-Lob
  • Erases a specified portion of the internal LOB data

OCI-Lob::erase

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::erase — Erases a specified portion of the internal LOB data

Description

OCI-Lob::erase ([ int $offset [, int $length ]] ) : int

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.

See Also

  • OCI-Lob::truncate


Exports LOB's contents to a file

  • « OCI-Lob::erase
  • OCI-Lob::flush »
  • PHP Manual
  • OCI-Lob
  • Exports LOB's contents to a file

OCI-Lob::export

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::export — Exports LOB's contents to a file

Description

OCI-Lob::export ( string $filename [, int $start [, int $length ]] ) : bool

Exports LOB contents to a file.

Parameters

filename

Path to the file.

start

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.

See Also

  • OCI-Lob::import


Flushes/writes buffer of the LOB to the server

  • « OCI-Lob::export
  • OCI-Lob::free »
  • PHP Manual
  • OCI-Lob
  • Flushes/writes buffer of the LOB to the server

OCI-Lob::flush

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::flush — Flushes/writes buffer of the LOB to the server

Description

OCI-Lob::flush ([ int $flag ] ) : bool

OCI-Lob::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.

See Also

  • OCI-Lob::getBuffering
  • OCI-Lob::setBuffering


Frees resources associated with the LOB descriptor

  • « OCI-Lob::flush
  • OCI-Lob::getBuffering »
  • PHP Manual
  • OCI-Lob
  • Frees resources associated with the LOB descriptor

OCI-Lob::free

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::free — Frees resources associated with the LOB descriptor

Description

OCI-Lob::free ( void ) : bool

Frees resources associated with the descriptor, previously allocated with oci_new_descriptor().

Return Values

Returns TRUE on success or FALSE on failure.


Returns current state of buffering for the large object

  • « OCI-Lob::free
  • OCI-Lob::import »
  • PHP Manual
  • OCI-Lob
  • Returns current state of buffering for the large object

OCI-Lob::getBuffering

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::getBuffering — Returns current state of buffering for the large object

Description

OCI-Lob::getBuffering ( void ) : bool

Tells whether the buffering for the large object is on or off.

Return Values

Returns FALSE if buffering for the large object is off and TRUE if buffering is used.

See Also

  • OCI-Lob::setBuffering


Imports file data to the LOB

  • « OCI-Lob::getBuffering
  • OCI-Lob::load »
  • PHP Manual
  • OCI-Lob
  • Imports file data to the LOB

OCI-Lob::import

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::import — Imports file data to the LOB

Description

OCI-Lob::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.

See Also

  • OCI-Lob::export
  • OCI-Lob::write


Returns large object's contents

  • « OCI-Lob::import
  • OCI-Lob::read »
  • PHP Manual
  • OCI-Lob
  • Returns large object's contents

OCI-Lob::load

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::load — Returns large object's contents

Description

OCI-Lob::load ( void ) : string

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 OCI-Lob::read instead.

Return Values

Returns the contents of the object, or FALSE on errors.

See Also

  • OCI-Lob::read


Reads part of the large object

  • « OCI-Lob::load
  • OCI-Lob::rewind »
  • PHP Manual
  • OCI-Lob
  • Reads part of the large object

OCI-Lob::read

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::read — Reads part of the large object

Description

OCI-Lob::read ( int $length ) : string

Reads length bytes from the current position of LOB's internal pointer.

Reading stops when length bytes have been read or end of the large object is reached. Internal pointer of the large object will be shifted on the amount of bytes read.

Parameters

length

The length of data to read, in bytes. Large values will be rounded down to 1 MB.

Return Values

Returns the contents as a string, or FALSE on failure.

See Also

  • OCI-Lob::load
  • OCI-Lob::write


Moves the internal pointer to the beginning of the large object

  • « OCI-Lob::read
  • OCI-Lob::save »
  • PHP Manual
  • OCI-Lob
  • Moves the internal pointer to the beginning of the large object

OCI-Lob::rewind

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::rewind — Moves the internal pointer to the beginning of the large object

Description

OCI-Lob::rewind ( void ) : bool

Sets the internal pointer to the beginning of the large object.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • OCI-Lob::seek
  • OCI-Lob::tell


Saves data to the large object

  • « OCI-Lob::rewind
  • OCI-Lob::saveFile »
  • PHP Manual
  • OCI-Lob
  • Saves data to the large object

OCI-Lob::save

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::save — Saves data to the large object

Description

OCI-Lob::save ( string $data [, int $offset ] ) : 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.

See Also

  • OCI-Lob::write
  • OCI-Lob::import


Alias of OCI-Lob::import

  • « OCI-Lob::save
  • OCI-Lob::seek »
  • PHP Manual
  • OCI-Lob
  • Alias of OCI-Lob::import

OCI-Lob::saveFile

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::saveFile — Alias of OCI-Lob::import()

Description

This function is an alias of: OCI-Lob::import().


Sets the internal pointer of the large object

  • « OCI-Lob::saveFile
  • OCI-Lob::setBuffering »
  • PHP Manual
  • OCI-Lob
  • Sets the internal pointer of the large object

OCI-Lob::seek

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::seek — Sets the internal pointer of the large object

Description

OCI-Lob::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.

See Also

  • OCI-Lob::rewind
  • OCI-Lob::tell
  • OCI-Lob::eof


Changes current state of buffering for the large object

  • « OCI-Lob::seek
  • OCI-Lob::size »
  • PHP Manual
  • OCI-Lob
  • Changes current state of buffering for the large object

OCI-Lob::setBuffering

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::setBuffering — Changes current state of buffering for the large object

Description

OCI-Lob::setBuffering ( bool $on_off ) : bool

Sets the buffering for the large object, depending on the value of the on_off 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. OCI-Lob::flush() should be used to flush buffers, when you have finished working with the large object.

Parameters

on_off

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.

See Also

  • OCI-Lob::getBuffering


Returns size of large object

  • « OCI-Lob::setBuffering
  • OCI-Lob::tell »
  • PHP Manual
  • OCI-Lob
  • Returns size of large object

OCI-Lob::size

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::size — Returns size of large object

Description

OCI-Lob::size ( void ) : int

Gets the size of the large object.

Return Values

Returns length of large object value or FALSE on failure. Empty objects have zero length.


Returns the current position of internal pointer of large object

  • « OCI-Lob::size
  • OCI-Lob::truncate »
  • PHP Manual
  • OCI-Lob
  • Returns the current position of internal pointer of large object

OCI-Lob::tell

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::tell — Returns the current position of internal pointer of large object

Description

OCI-Lob::tell ( void ) : int

Gets the current position of a LOB's internal pointer.

Return Values

Returns current position of a LOB's internal pointer or FALSE if an error occurred.

See Also

  • OCI-Lob::rewind
  • OCI-Lob::size
  • OCI-Lob::eof


Truncates large object

  • « OCI-Lob::tell
  • OCI-Lob::write »
  • PHP Manual
  • OCI-Lob
  • Truncates large object

OCI-Lob::truncate

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::truncate — Truncates large object

Description

OCI-Lob::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.

See Also

  • OCI-Lob::erase


Writes data to the large object

  • « OCI-Lob::truncate
  • OCI-Lob::writeTemporary »
  • PHP Manual
  • OCI-Lob
  • Writes data to the large object

OCI-Lob::write

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::write — Writes data to the large object

Description

OCI-Lob::write ( string $data [, int $length ] ) : int

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 given, 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.

See Also

  • OCI-Lob::read


Writes a temporary large object

  • « OCI-Lob::write
  • OCI-Lob::writeToFile »
  • PHP Manual
  • OCI-Lob
  • Writes a temporary large object

OCI-Lob::writeTemporary

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::writeTemporary — Writes a temporary large object

Description

OCI-Lob::writeTemporary ( string $data [, int $lob_type = OCI_TEMP_CLOB ] ) : bool

Creates a temporary large object and writes data to it.

You should use OCI-Lob::close when you are done with this object.

Parameters

data

The data to write.

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

See Also

  • OCI-Lob::close


Alias of OCI-Lob::export

  • « OCI-Lob::writeTemporary
  • OCI8 Obsolete Aliases and Functions »
  • PHP Manual
  • OCI-Lob
  • Alias of OCI-Lob::export

OCI-Lob::writeToFile

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0)

OCI-Lob::writeToFile — Alias of OCI-Lob::export()

Description

This function is an alias of: OCI-Lob::export().


OCI8 Obsolete Aliases and Functions

Table of Contents

  • ocibindbyname — Alias of oci_bind_by_name
  • ocicancel — Alias of oci_cancel
  • ocicloselob — Alias of OCI-Lob::close
  • ocicollappend — Alias of OCI-Collection::append
  • ocicollassign — Alias of OCI-Collection::assign
  • ocicollassignelem — Alias of OCI-Collection::assignElem
  • ocicollgetelem — Alias of OCI-Collection::getElem
  • ocicollmax — Alias of OCI-Collection::max
  • ocicollsize — Alias of OCI-Collection::size
  • ocicolltrim — Alias of OCI-Collection::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 OCI-Collection::free
  • ocifreecursor — Alias of oci_free_statement
  • ocifreedesc — Alias of OCI-Lob::free
  • ocifreestatement — Alias of oci_free_statement
  • ociinternaldebug — Alias of oci_internal_debug
  • ociloadlob — Alias of OCI-Lob::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 OCI-Lob::save
  • ocisavelobfile — Alias of OCI-Lob::import
  • ociserverversion — Alias of oci_server_version
  • ocisetprefetch — Alias of oci_set_prefetch
  • ocistatementtype — Alias of oci_statement_type
  • ociwritelobtofile — Alias of OCI-Lob::export
  • ociwritetemporarylob — Alias of OCI-Lob::writeTemporary


Alias of oci_bind_by_name

  • « OCI8 Obsolete Aliases and Functions
  • ocicancel »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_bind_by_name

ocibindbyname

(PHP 4, PHP 5, PHP 7, 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.


Alias of oci_cancel

  • « ocibindbyname
  • ocicloselob »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_cancel

ocicancel

(PHP 4, PHP 5, PHP 7, 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.


Alias of OCI-Lob::close

  • « ocicancel
  • ocicollappend »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of OCI-Lob::close

ocicloselob

(PHP 4 >= 4.0.6, PECL OCI8 1.0)

ocicloselob — Alias of OCI-Lob::close()

Description

Alias of OCI-Lob::close()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.


Alias of OCI-Collection::append

  • « ocicloselob
  • ocicollassign »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of OCI-Collection::append

ocicollappend

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicollappend — Alias of OCI-Collection::append()

Description

Alias of OCI-Collection::append()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.


Alias of OCI-Collection::assign

  • « ocicollappend
  • ocicollassignelem »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of OCI-Collection::assign

ocicollassign

(PHP 4 >= 4.0.6, PECL OCI8 1.0)

ocicollassign — Alias of OCI-Collection::assign()

Description

Alias of OCI-Collection::assign()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.


Alias of OCI-Collection::assignElem

  • « ocicollassign
  • ocicollgetelem »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of OCI-Collection::assignElem

ocicollassignelem

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicollassignelem — Alias of OCI-Collection::assignElem()

Description

Alias of OCI-Collection::assignElem()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.


Alias of OCI-Collection::getElem

  • « ocicollassignelem
  • ocicollmax »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of OCI-Collection::getElem

ocicollgetelem

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicollgetelem — Alias of OCI-Collection::getElem()

Description

Alias of OCI-Collection::getElem()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.


Alias of OCI-Collection::max

  • « ocicollgetelem
  • ocicollsize »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of OCI-Collection::max

ocicollmax

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicollmax — Alias of OCI-Collection::max()

Description

Alias of OCI-Collection::max()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.


Alias of OCI-Collection::size

  • « ocicollmax
  • ocicolltrim »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of OCI-Collection::size

ocicollsize

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicollsize — Alias of OCI-Collection::size()

Description

Alias of OCI-Collection::size()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.


Alias of OCI-Collection::trim

  • « ocicollsize
  • ocicolumnisnull »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of OCI-Collection::trim

ocicolltrim

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicolltrim — Alias of OCI-Collection::trim()

Description

Alias of OCI-Collection::trim()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.


Alias of oci_field_is_null

  • « ocicolltrim
  • ocicolumnname »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_field_is_null

ocicolumnisnull

(PHP 4, PHP 5, PHP 7, 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.


Alias of oci_field_name

  • « ocicolumnisnull
  • ocicolumnprecision »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_field_name

ocicolumnname

(PHP 4, PHP 5, PHP 7, 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.


Alias of oci_field_precision

  • « ocicolumnname
  • ocicolumnscale »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_field_precision

ocicolumnprecision

(PHP 4, PHP 5, PHP 7, 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.


Alias of oci_field_scale

  • « ocicolumnprecision
  • ocicolumnsize »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_field_scale

ocicolumnscale

(PHP 4, PHP 5, PHP 7, 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.


Alias of oci_field_size

  • « ocicolumnscale
  • ocicolumntype »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_field_size

ocicolumnsize

(PHP 4, PHP 5, PHP 7, 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.


Alias of oci_field_type

  • « ocicolumnsize
  • ocicolumntyperaw »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_field_type

ocicolumntype

(PHP 4, PHP 5, PHP 7, 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.


Alias of oci_field_type_raw

  • « ocicolumntype
  • ocicommit »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_field_type_raw

ocicolumntyperaw

(PHP 4, PHP 5, PHP 7, 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.


Alias of oci_commit

  • « ocicolumntyperaw
  • ocidefinebyname »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_commit

ocicommit

(PHP 4, PHP 5, PHP 7, 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.


Alias of oci_define_by_name

  • « ocicommit
  • ocierror »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_define_by_name

ocidefinebyname

(PHP 4, PHP 5, PHP 7, 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.


Alias of oci_error

  • « ocidefinebyname
  • ociexecute »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_error

ocierror

(PHP 4, PHP 5, PHP 7, 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.


Alias of oci_execute

  • « ocierror
  • ocifetch »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_execute

ociexecute

(PHP 4, PHP 5, PHP 7, 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.


Alias of oci_fetch

  • « ociexecute
  • ocifetchinto »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_fetch

ocifetch

(PHP 4, PHP 5, PHP 7, 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.


Obsolete variant of oci_fetch_array, oci_fetch_object, oci_fetch_assoc and oci_fetch_row

  • « ocifetch
  • ocifetchstatement »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Obsolete variant of oci_fetch_array, oci_fetch_object, oci_fetch_assoc and oci_fetch_row

ocifetchinto

(PHP 4, PHP 5, PHP 7, 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.


Alias of oci_fetch_all

  • « ocifetchinto
  • ocifreecollection »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_fetch_all

ocifetchstatement

(PHP 4, PHP 5, PHP 7, 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.


Alias of OCI-Collection::free

  • « ocifetchstatement
  • ocifreecursor »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of OCI-Collection::free

ocifreecollection

(PHP 4 >= 4.0.7, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocifreecollection — Alias of OCI-Collection::free()

Description

Alias of OCI-Collection::free()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.


Alias of oci_free_statement

  • « ocifreecollection
  • ocifreedesc »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_free_statement

ocifreecursor

(PHP 4, PHP 5, PHP 7, 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.


Alias of OCI-Lob::free

  • « ocifreecursor
  • ocifreestatement »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of OCI-Lob::free

ocifreedesc

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocifreedesc — Alias of OCI-Lob::free()

Description

Alias of OCI-Lob::free()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.


Alias of oci_free_statement

  • « ocifreedesc
  • ociinternaldebug »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_free_statement

ocifreestatement

(PHP 4, PHP 5, PHP 7, 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.


Alias of oci_internal_debug

  • « ocifreestatement
  • ociloadlob »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_internal_debug

ociinternaldebug

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.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.


Alias of OCI-Lob::load

  • « ociinternaldebug
  • ocilogoff »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of OCI-Lob::load

ociloadlob

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ociloadlob — Alias of OCI-Lob::load()

Description

Alias of OCI-Lob::load()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.


Alias of oci_close

  • « ociloadlob
  • ocilogon »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_close

ocilogoff

(PHP 4, PHP 5, PHP 7, 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.


Alias of oci_connect

  • « ocilogoff
  • ocinewcollection »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_connect

ocilogon

(PHP 4, PHP 5, PHP 7, 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.


Alias of oci_new_collection

  • « ocilogon
  • ocinewcursor »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_new_collection

ocinewcollection

(PHP 4 >= 4.0.6, PHP 5, PHP 7, 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.


Alias of oci_new_cursor

  • « ocinewcollection
  • ocinewdescriptor »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_new_cursor

ocinewcursor

(PHP 4, PHP 5, PHP 7, 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.


Alias of oci_new_descriptor

  • « ocinewcursor
  • ocinlogon »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_new_descriptor

ocinewdescriptor

(PHP 4, PHP 5, PHP 7, 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.


Alias of oci_new_connect

  • « ocinewdescriptor
  • ocinumcols »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_new_connect

ocinlogon

(PHP 4, PHP 5, PHP 7, 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.


Alias of oci_num_fields

  • « ocinlogon
  • ociparse »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_num_fields

ocinumcols

(PHP 4, PHP 5, PHP 7, 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.


Alias of oci_parse

  • « ocinumcols
  • ociplogon »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_parse

ociparse

(PHP 4, PHP 5, PHP 7, 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.


Alias of oci_pconnect

  • « ociparse
  • ociresult »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_pconnect

ociplogon

(PHP 4, PHP 5, PHP 7, 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.


Alias of oci_result

  • « ociplogon
  • ocirollback »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_result

ociresult

(PHP 4, PHP 5, PHP 7, 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.


Alias of oci_rollback

  • « ociresult
  • ocirowcount »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_rollback

ocirollback

(PHP 4, PHP 5, PHP 7, 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.


Alias of oci_num_rows

  • « ocirollback
  • ocisavelob »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_num_rows

ocirowcount

(PHP 4, PHP 5, PHP 7, 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.


Alias of OCI-Lob::save

  • « ocirowcount
  • ocisavelobfile »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of OCI-Lob::save

ocisavelob

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocisavelob — Alias of OCI-Lob::save()

Description

Alias of OCI-Lob::save()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.


Alias of OCI-Lob::import

  • « ocisavelob
  • ociserverversion »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of OCI-Lob::import

ocisavelobfile

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocisavelobfile — Alias of OCI-Lob::import()

Description

Alias of OCI-Lob::import()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.


Alias of oci_server_version

  • « ocisavelobfile
  • ocisetprefetch »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_server_version

ociserverversion

(PHP 4, PHP 5, PHP 7, 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.


Alias of oci_set_prefetch

  • « ociserverversion
  • ocistatementtype »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_set_prefetch

ocisetprefetch

(PHP 4, PHP 5, PHP 7, 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.


Alias of oci_statement_type

  • « ocisetprefetch
  • ociwritelobtofile »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of oci_statement_type

ocistatementtype

(PHP 4, PHP 5, PHP 7, 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.


Alias of OCI-Lob::export

  • « ocistatementtype
  • ociwritetemporarylob »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of OCI-Lob::export

ociwritelobtofile

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ociwritelobtofile — Alias of OCI-Lob::export()

Description

Alias of OCI-Lob::export()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.


Alias of OCI-Lob::writeTemporary

  • « ociwritelobtofile
  • Paradox »
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Alias of OCI-Lob::writeTemporary

ociwritetemporarylob

(PHP 4 >= 4.0.6, PECL OCI8 1.0)

ociwritetemporarylob — Alias of OCI-Lob::writeTemporary()

Description

Alias of OCI-Lob::writeTemporary()

Warning

This alias has been DEPRECATED as of PHP 5.4.0. Relying on this alias is highly discouraged.


Paradox File Access

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Paradox Functions
    • px_close — Closes a paradox database
    • px_create_fp — Create a new paradox database
    • px_date2string — Converts a date into a string
    • px_delete_record — Deletes record from paradox database
    • px_delete — Deletes resource of paradox database
    • px_get_field — Returns the specification of a single field
    • px_get_info — Return lots of information about a paradox file
    • px_get_parameter — Gets a parameter
    • px_get_record — Returns record of paradox database
    • px_get_schema — Returns the database schema
    • px_get_value — Gets a value
    • px_insert_record — Inserts record into paradox database
    • px_new — Create a new paradox object
    • px_numfields — Returns number of fields in a database
    • px_numrecords — Returns number of records in a database
    • px_open_fp — Open paradox database
    • px_put_record — Stores record into paradox database
    • px_retrieve_record — Returns record of paradox database
    • px_set_blob_file — Sets the file where blobs are read from
    • px_set_parameter — Sets a parameter
    • px_set_tablename — Sets the name of a table (deprecated)
    • px_set_targetencoding — Sets the encoding for character fields (deprecated)
    • px_set_value — Sets a value
    • px_timestamp2string — Converts the timestamp into a string
    • px_update_record — Updates record in paradox database


Introduction

This module allows to read and write Paradox databases, primary index files and blob files. Write support has been proven to be quite reliable, though due to lack of documentation the produced files may not in any case be readable by other applications. Encrypted databases can be read without specifying a password if pxlib >= 0.5.0 is used.

Note:

This module is also in development and may change, though major changes to the API are not expected.

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.


Requirements

You need at least PHP 5.0.0 and pxlib >= 0.4.4 for the basic set of functions. Some newer functions are only available with pxlib >= 0.6.0. Reading and writing of encrypted databases requires at least pxlib >= 0.5.0. The paradox library (pxlib) is available at » http://pxlib.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/paradox

Make sure you have pxlib installed before. If you install pxlib from an rpm or debian package, do not forget to install the development package as well.


  • « Runtime Configuration
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

px_new() creates a new Paradox object required by all Paradox 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.

The following two tables lists all constants defined by the paradox extension.

Contants for field types
Name | Meaning
PX_FIELD_ALPHA | Character data with fixed length
PX_FIELD_DATE | Date, number of days since 1.1.0000
PX_FIELD_SHORT | Short integer (2 Bytes)
PX_FIELD_LONG | Long integer (4 Bytes)
PX_FIELD_CURRENCY | same as PX_FIELD_NUMBER
PX_FIELD_NUMBER | Double
PX_FIELD_LOGICAL | Boolean
PX_FIELD_MEMOBLOB | Binary large object
PX_FIELD_BLOB | Binary large object (not supported)
PX_FIELD_FMTMEMOBLOB | Binary large object
PX_FIELD_OLE | OLE object (basically a blob, not supported)
PX_FIELD_GRAPHIC | Graphic (basically a blob, not supported)
PX_FIELD_TIME | time, number of milli seconds since midnight
PX_FIELD_TIMESTAMP | timestamp, number of milli seconds since 1.1.0000
PX_FIELD_AUTOINC | Auto incrementing interger (like PX_FIELD_LONG)
PX_FIELD_BCD | Decimal number stored in bcd format (not supported)
PX_FIELD_BYTES | Array of Bytes with not more than 255 bytes (not supported)
PX_KEYTOLOWER | Turn all field names into lower case
PX_KEYTOUPPER | Turn all field names into upper case
Contants for file types
Name | Meaning
PX_FILE_INDEX_DB | Indexed database
PX_FILE_PRIM_INDEX | Primary index
PX_FILE_NON_INDEX_DB | None indexed database
PX_FILE_NON_INC_SEC_INDEX | None incremental secondary index
PX_FILE_SEC_INDEX | Secondary index
PX_FILE_INC_SEC_INDEX | Incremental secondary index
PX_FILE_NON_INC_SEC_INDEX_G | Non incremental secondary index
PX_FILE_SEC_INDEX_G | Secondary index
PX_FILE_INC_SEC_INDEX_G | Non incremental secondary index


Paradox Functions

Object oriented API

The paradox extension provides also an object oriented API. It consists of only one class called paradox_db. Its methods only differ from the functions in its name and of course the missing first parameter. The following table will list all methods and its equivalent functions.

Methods of class paradox_db
Name of method | Equivalent function
Constructor | px_new()
Destructor | px_delete()
open_fp() | px_open_fp()
create_fp() | px_create_fp()
close() | px_close()
numrecords() | px_numrecords()
numfields() | px_numfields()
get_record() | px_get_record()
put_record() | px_put_record()
retrieve_record() | px_retrieve_record()
delete_record() | px_delete_record()
insert_record() | px_insert_record()
update_record() | px_update_record()
get_field() | px_get_field()
get_schema() | px_get_schema()
get_info() | px_get_info()
set_parameter() | px_set_parameter()
get_parameter() | px_get_parameter()
set_value() | px_set_value()
get_value() | px_get_value()
get_info() | px_get_info()
set_targetencoding() | px_set_targetencoding()
set_tablename() | px_set_tablename()
set_blob_file() | px_set_blob_file()
date2string() | px_date2string()
timestamp2string() | px_timestamp2string()

Table of Contents

  • px_close — Closes a paradox database
  • px_create_fp — Create a new paradox database
  • px_date2string — Converts a date into a string
  • px_delete_record — Deletes record from paradox database
  • px_delete — Deletes resource of paradox database
  • px_get_field — Returns the specification of a single field
  • px_get_info — Return lots of information about a paradox file
  • px_get_parameter — Gets a parameter
  • px_get_record — Returns record of paradox database
  • px_get_schema — Returns the database schema
  • px_get_value — Gets a value
  • px_insert_record — Inserts record into paradox database
  • px_new — Create a new paradox object
  • px_numfields — Returns number of fields in a database
  • px_numrecords — Returns number of records in a database
  • px_open_fp — Open paradox database
  • px_put_record — Stores record into paradox database
  • px_retrieve_record — Returns record of paradox database
  • px_set_blob_file — Sets the file where blobs are read from
  • px_set_parameter — Sets a parameter
  • px_set_tablename — Sets the name of a table (deprecated)
  • px_set_targetencoding — Sets the encoding for character fields (deprecated)
  • px_set_value — Sets a value
  • px_timestamp2string — Converts the timestamp into a string
  • px_update_record — Updates record in paradox database


Closes a paradox database

  • « Paradox Functions
  • px_create_fp »
  • PHP Manual
  • Paradox Functions
  • Closes a paradox database

px_close

(PECL paradox >= 1.0.0)

px_close — Closes a paradox database

Description

px_close ( resource $pxdoc ) : bool

Closes the paradox database. This function will not close the file. You will have to call fclose() afterwards.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • px_open_fp() - Open paradox database
  • The example at px_new() - Create a new paradox object


Create a new paradox database

  • « px_close
  • px_date2string »
  • PHP Manual
  • Paradox Functions
  • Create a new paradox database

px_create_fp

(PECL paradox >= 1.0.0)

px_create_fp — Create a new paradox database

Description

px_create_fp ( resource $pxdoc , resource $file , array $fielddesc ) : bool

Create a new paradox database file. The actual file has to be opened before with fopen(). Make sure the file is writable.

Note:

Calling this functions issues a warning about an empty tablename which can be safely ignored. Just set the tablename afterwards with px_set_parameter().

Note:

This function is highly experimental, due to insufficient documentation of the paradox file format. Database files created with this function can be opened by px_open_fp() and has been successfully opened by the Paradox software, but your milage may vary.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

file

File handle as returned by fopen().

fielddesc

fielddesc is an array containing one element for each field specification. A field specification is an array itself with either two or three elements.The first element is always a string value used as the name of the field. It may not be larger than ten characters. The second element contains the field type which is one of the constants listed in the table Constants for field types. In the case of a character field or bcd field, you will have to provide a third element specifying the length respectively the precesion of the field. If your field specification contains blob fields, you will have to make sure to either make the field large enough for all field values to fit or specify a blob file with px_set_blob_file() for storing the blobs. If this is not done the field data is truncated.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Creating a Paradox database with two fields

<?php
if(!$pxdoc = px_new()) {
  /* Error handling */
}
$fp = fopen("test.db", "w+");
$fields = array(array("col1", "S"), array("col2", "I"));
if(!px_create_fp($pxdoc, $fp, $fields)) {
  /* Error handling */
}
px_set_parameter($pxdoc, "tablename", "testtable");
for($i=-50; $i<50; $i++) {
  $rec = array($i, -$i);
  px_put_record($pxdoc, $rec);
}
px_close($pxdoc);
px_delete($pxdoc);
fclose($fp);
?>

See Also

  • px_new() - Create a new paradox object
  • px_put_record() - Stores record into paradox database
  • fopen() - Opens file or URL


Converts a date into a string

  • « px_create_fp
  • px_delete_record »
  • PHP Manual
  • Paradox Functions
  • Converts a date into a string

px_date2string

(PECL paradox >= 1.4.0)

px_date2string — Converts a date into a string

Description

px_date2string ( resource $pxdoc , int $value , string $format ) : string

Turns a date as it stored in the paradox file into human readable format. Paradox dates are the number of days since 1.1.0000. This function is just for convenience. It can be easily replaced by some math and the calendar functions as demonstrated in the example below.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

value

Value as stored in paradox database field of type PX_FIELD_DATE.

format

String format similar to the format used by date(). The placeholders support by this function is a subset of those supported by date() (Y, y, m, n, d, j, L).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Turn a paradox date into a human readable form

<?php
$px = px_new();

/* make up a date as it could be stored in */
/* a date field of a paradox db. */
/* 700000 days since 1.1.0000. */
$days = 700000;

/* Use the calendar functions to print a */
/* human readable format of the date */
echo jdtogregorian($days+1721425)."\n";
/* px_date2string() outputs the same */
echo px_date2string($px, $days, "n/d/Y")."\n";

px_delete($px);
?>

The above example will output:

7/15/1917
7/15/1917

See Also

  • px_timestamp2string() - Converts the timestamp into a string
  • jdtogregorian() - Converts Julian Day Count to Gregorian date


Deletes record from paradox database

  • « px_date2string
  • px_delete »
  • PHP Manual
  • Paradox Functions
  • Deletes record from paradox database

px_delete_record

(PECL paradox >= 1.4.0)

px_delete_record — Deletes record from paradox database

Description

px_delete_record ( resource $pxdoc , int $num ) : bool

This function deletes a record from the database. It does not free the space in the database file but just marks it as deleted. Inserting a new record afterwards will reuse the space.

Note:

This function is only available if pxlib >= 0.6.0 is used.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

num

The record number is an artificial number counting records in the order as they are stored in the database. The first record has number 0.

Return Values

Returns TRUE on success or FALSE on failure.


Deletes resource of paradox database

  • « px_delete_record
  • px_get_field »
  • PHP Manual
  • Paradox Functions
  • Deletes resource of paradox database

px_delete

(PECL paradox >= 1.0.0)

px_delete — Deletes resource of paradox database

Description

px_delete ( resource $pxdoc ) : bool

Deletes the resource of the paradox file and frees all memory.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

Return Values

Returns TRUE on success or FALSE on failure.


Returns the specification of a single field

  • « px_delete
  • px_get_info »
  • PHP Manual
  • Paradox Functions
  • Returns the specification of a single field

px_get_field

(PECL paradox >= 1.0.0)

px_get_field — Returns the specification of a single field

Description

px_get_field ( resource $pxdoc , int $fieldno ) : array

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

fieldno

Number of the field. The first field has number 0. Specifying a field number less than 0 and greater or equal the number of fields will trigger an error.

Return Values

Returns the specification of the fieldno 'th database field as an associated array. The array contains three fields named name, type, and size.


Return lots of information about a paradox file

  • « px_get_field
  • px_get_parameter »
  • PHP Manual
  • Paradox Functions
  • Return lots of information about a paradox file

px_get_info

(PECL paradox >= 1.0.0)

px_get_info — Return lots of information about a paradox file

Description

px_get_info ( resource $pxdoc ) : array

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

Return Values

Returns an associated array with lots of information about a paradox file. This array is likely to be extended in the future.

fileversion

Version of file multiplied by 10, e.g. 70.

tablename

Name of table as stored in the file. If the database was created by pxlib, then this will be the name of the file without the extension.

numrecords

Number of records in this table.

numfields

Number of fields in this table.

headersize

Number of bytes used for the header. This is usually 0x800.

recordsize

Number of bytes used for each record. This is the sum of all field sizes (available since version 1.4.2).

maxtablesize

This value multiplied by 0x400 is the size of a data block in bytes. The maximum number of records in a datablock is the integer part of (maxtablesize * 0x400 - 8) / recordsize.

numdatablocks

The number of data blocks in the file. Each data block contains a certain number of records which depends on the record size and the data block size (maxtablesize). Data blocks may not necessarily be completely filled.

numindexfields

Number of fields used for the primary index. The fields do always start with field number 1.

codepage

The DOS codepage which was used for encoding fields with character data. If the target encoding is not set with px_set_targetencoding() this will be the encoding for character fields when records are being accessed with px_get_record() or px_retrieve_record().

See Also

  • px_numfields() - Returns number of fields in a database
  • px_numrecords() - Returns number of records in a database


Gets a parameter

  • « px_get_info
  • px_get_record »
  • PHP Manual
  • Paradox Functions
  • Gets a parameter

px_get_parameter

(PECL paradox >= 1.1.0)

px_get_parameter — Gets a parameter

Description

px_get_parameter ( resource $pxdoc , string $name ) : string

Gets various parameters.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

name

The name can be one of the following:

tablename

The name of the table as it will be stored in the database header.

targetencoding

The encoding for the output. Data which is being read from character fields with px_get_record() or px_retrieve_record() is recoded into the targetencoding. If it is not set, then the data will be delivered as stored in the database file.

inputencoding

The encoding of the input data which is to be stored into the database. When storing data of character fields in the database, the data is expected to be delivered in this encoding.

Return Values

Returns the value of the parameter or FALSE on failure.


Returns record of paradox database

  • « px_get_parameter
  • px_get_schema »
  • PHP Manual
  • Paradox Functions
  • Returns record of paradox database

px_get_record

(PECL paradox >= 1.0.0)

px_get_record — Returns record of paradox database

Description

px_get_record ( resource $pxdoc , int $num [, int $mode = 0 ] ) : array

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

num

The record number is an artificial number counting records in the order as they are stored in the database. The first record has number 0.

mode

The optional mode can be PX_KEYTOLOWER or PX_KEYTOUPPER in order to convert the keys of the returned array into lower or upper case. If mode is not passed or is 0, then the key will be exactly like the field name. The element values will contain the field values. NULL values will be retained and are different from 0.0, 0 or the empty string. Fields of type PX_FIELD_TIME will be returned as an integer counting the number of milliseconds starting at midnight. A timestamp (PX_FIELD_TIMESTAMP) and date (PX_FIELD_DATE) are floating point respectively int values counting milliseconds respectively days starting at the beginning of julian calendar. Use the functions px-timestamp2string() and px-date2string() to convert them into a character representation.

Return Values

Returns the num'th record from the paradox database. The record is returned as an associated array with its keys being the field names.

See Also

  • px_retrieve_record() - Returns record of paradox database


Returns the database schema

  • « px_get_record
  • px_get_value »
  • PHP Manual
  • Paradox Functions
  • Returns the database schema

px_get_schema

(PECL paradox >= 1.0.0)

px_get_schema — Returns the database schema

Description

px_get_schema ( resource $pxdoc [, int $mode = 0 ] ) : array

px_get_schema() returns the database schema.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

mode

If the optional mode is PX_KEYTOLOWER or PX_KEYTOUPPER the keys of the returned array will be converted to lower or upper case. If mode is 0 or not passed at all, then the key name will be identical to the field name.

Return Values

Returns the schema of a database file as an associated array. The key name is equal to the field name. Each array element is itself an associated array containing the two fields type and size. type is one of the constants in table Constants for field types. size is the number of bytes this field consumes in the record. The total of all field sizes is equal to the record size as it can be retrieved with px-get-info().


Gets a value

  • « px_get_schema
  • px_insert_record »
  • PHP Manual
  • Paradox Functions
  • Gets a value

px_get_value

(PECL paradox >= 1.1.0)

px_get_value — Gets a value

Description

px_get_value ( resource $pxdoc , string $name ) : float

Gets various values.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

name

name can be one of the following.

numprimkeys

The number of primary keys. Paradox databases always use the first numprimkeys fields for the primary index.

Return Values

Returns the value of the parameter or FALSE on failure.


Inserts record into paradox database

  • « px_get_value
  • px_new »
  • PHP Manual
  • Paradox Functions
  • Inserts record into paradox database

px_insert_record

(PECL paradox >= 1.4.0)

px_insert_record — Inserts record into paradox database

Description

px_insert_record ( resource $pxdoc , array $data ) : int

Inserts a new record into the database. The record is not necessarily inserted at the end of the database, but may be inserted at any position depending on where the first free slot is found.

The record data is passed as an array of field values. The elements in the array must correspond to the fields in the database. If the array has less elements than fields in the database, the remaining fields will be set to null.

Most field values can be passed as its equivalent php type e.g. a long value is used for fields of type PX_FIELD_LONG, PX_FIELD_SHORT and PX_FIELD_AUTOINC, a double values is used for fields of type PX_FIELD_CURRENCY and PX_FIELD_NUMBER. Field values for blob and alpha fields are passed as strings.

Fields of type PX_FIELD_TIME and PX_FIELD_DATE both require a long value. In the first case this is the number of milliseconds since midnight. In the second case this is the number of days since 1.1.0000. Below there are two examples to convert the current date or timestamp into a value suitable for one of paradox's date/time fields.

Note:

This function is only available if pxlib >= 0.6.0 is used.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

data

Associated or indexed array containing the field values as e.g. returned by px_retrieve_record().

Return Values

Returns FALSE on failure or the record number in case of success.

Examples

Example #1 Set the date/time fields in a paradox database to the current date/time

<?php
$px = px_new();
$fp = fopen("test.db", "w+");
px_create_fp($px, $fp, array(array("timestamp", "@"), array("time", "T"), array("date", "D")));

$curdate = getdate();
$jd = gregoriantojd($curdate["mon"], $curdate["mday"], $curdate["year"]);
$days = $jd - 1721425; /* Number of days between 1.1.4714 b.c. and 1.1.0000 */
$secs = $curdate["hours"]*3600 + $curdate["minutes"]*60 + $curdate["seconds"];
px_insert_record($px, array($days*86400000.0 + $secs*1000.0, $secs*1000.0, $days));

$curtimestamp = microtime(true);
$days = (int) ($curtimestamp/86400);
$secs = $curtimestamp - ($days * 86400.0);
$days += 2440588; /* Number of days between 1.1.4714 b.c. and 1.1.1970 */
$days -= 1721425; /* Number of days between 1.1.4714 b.c. and 1.1.0000 */
px_insert_record($px, array($days*86400000.0 + $secs*1000.0, $secs*1000.0, $days));
for($i=0; $i<2; $i++) {
    $rec = px_retrieve_record($px, $i);
    echo px_timestamp2string($px, $rec["timestamp"], "n/d/Y H:i:s")."\n";
    echo px_date2string($px, $rec["date"], "n/d/Y")."\n";
}
px_close($px);
px_delete($px);
?>

The above example will output:

2/21/2006 21:42:30
2/21/2006
2/21/2006 20:42:30
2/21/2006

The Julian day count as passed to jdtogregorian() has a different base of 1.1.4714 b.c. and must therefore be calculated by adding 1721425 to the day count used in the paradox file. Turning the day count into a timestamp is easily done by multiplying with 86400000.0 to obtain milli seconds.

See Also

px_update_record() - Updates record in paradox database


Create a new paradox object

  • « px_insert_record
  • px_numfields »
  • PHP Manual
  • Paradox Functions
  • Create a new paradox object

px_new

(PECL paradox >= 1.0.0)

px_new — Create a new paradox object

Description

px_new ( void ) : resource

Create a new paradox object. You will have to call this function before any further functions. px_new() does not create any file on the disk, it just creates an instance of a paradox object. This function must not be called if the object oriented interface is used. Use new paradox_db() instead.

Return Values

Returns FALSE on failure.

Examples

Example #1 Opening a Paradox database

<?php
if(!$pxdoc = px_new()) {
  /* Error handling */
}
$fp = fopen("test.db", "r");
if(!px_open_fp($pxdoc, $fp)) {
  /* Error handling */
}
// ...
px_close($pxdoc);
px_delete($pxdoc);
fclose($fp);
?>

If you prefer the object oriented API, then the above example will look like the following.

Example #2 Opening a Paradox database

<?php
$fp = fopen("test.db", "r");
$pxdoc = new paradox_db();
if(!$pxdoc->open_fp($fp)) {
  /* Error handling */
}
// ...
$pxdoc->close();
fclose($fp);
?>

See Also

  • px_delete() - Deletes resource of paradox database
  • px_open_fp() - Open paradox database


Returns number of fields in a database

  • « px_new
  • px_numrecords »
  • PHP Manual
  • Paradox Functions
  • Returns number of fields in a database

px_numfields

(PECL paradox >= 1.0.0)

px_numfields — Returns number of fields in a database

Description

px_numfields ( resource $pxdoc ) : int

Get the number of fields in a database file.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

Return Values

Returns the number of fields in a database file. The return value of this function is identical to the element numfields in the array returned by px_get_info().


Returns number of records in a database

  • « px_numfields
  • px_open_fp »
  • PHP Manual
  • Paradox Functions
  • Returns number of records in a database

px_numrecords

(PECL paradox >= 1.0.0)

px_numrecords — Returns number of records in a database

Description

px_numrecords ( resource $pxdoc ) : int

Get the number of records in a database file.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

Return Values

Returns the number of records in a database file. The return value of this function is identical to the element numrecords in the array returned by px_get_info().


Open paradox database

  • « px_numrecords
  • px_put_record »
  • PHP Manual
  • Paradox Functions
  • Open paradox database

px_open_fp

(PECL paradox >= 1.0.0)

px_open_fp — Open paradox database

Description

px_open_fp ( resource $pxdoc , resource $file ) : bool

Open an existing paradox database file. The actual file has to be opened before with fopen(). This function can also be used to open primary index files and tread them like a paradox database. This is supported for those who would like to investigate a primary index. It cannot be used to accelerate access to a database file.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

file

file is the return value from fopen() with the actual database file as parameter. Make sure the database is writable if you plan to update or insert records.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fopen() - Opens file or URL
  • The example at px_new() - Create a new paradox object


Stores record into paradox database

  • « px_open_fp
  • px_retrieve_record »
  • PHP Manual
  • Paradox Functions
  • Stores record into paradox database

px_put_record

(PECL paradox >= 1.0.0)

px_put_record — Stores record into paradox database

Description

px_put_record ( resource $pxdoc , array $record [, int $recpos = -1 ] ) : bool

Stores a record into a paradox database. The record is always added at the end of the database, regardless of any free slots. Use px_insert_record() to add a new record into the first free slot found in the database.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

record

Associated or indexed array containing the field values as e.g. returned by px_retrieve_record().

recpos

This optional parameter may be used to specify a record number greater than the current number of records in the database. The function will add as many empty records as needed. There is hardly any need for this parameter.

Return Values

Returns TRUE on success or FALSE on failure.


Returns record of paradox database

  • « px_put_record
  • px_set_blob_file »
  • PHP Manual
  • Paradox Functions
  • Returns record of paradox database

px_retrieve_record

(PECL paradox >= 1.4.0)

px_retrieve_record — Returns record of paradox database

Description

px_retrieve_record ( resource $pxdoc , int $num [, int $mode = 0 ] ) : array

This function is very similar to px_get_record() but uses internally a different approach to retrieve the data. It relies on pxlib for reading each single field value, which usually results in support for more field types.

Note:

This function is only available if pxlib >= 0.6.0 is used.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

num

The record number is an artificial number counting records in the order as they are stored in the database. The first record has number 0.

mode

The optional mode can be PX_KEYTOLOWER or PX_KEYTOUPPER in order to convert the keys into lower or upper case. If mode is not passed or is 0, then the key will be exactly like the field name. The element values will contain the field values. NULL values will be retained and are different from 0.0, 0 or the empty string. Fields of type PX_FIELD_TIME will be returned as an integer counting the number of milliseconds starting at midnight. A timestamp is a floating point value also counting milliseconds starting at the beginning of julian calendar.

Return Values

Returns the num'th record from the paradox database. The record is returned as an associated array with its keys being the field names.

See Also

  • px_get_record() - Returns record of paradox database


Sets the file where blobs are read from

  • « px_retrieve_record
  • px_set_parameter »
  • PHP Manual
  • Paradox Functions
  • Sets the file where blobs are read from

px_set_blob_file

(PECL paradox >= 1.3.0)

px_set_blob_file — Sets the file where blobs are read from

Description

px_set_blob_file ( resource $pxdoc , string $filename ) : bool

Sets the name of the file where blobs are going to be read from or written into. Without calling this function, px_get_record() or px_retrieve_record() will only return data in blob fields if the data is part of the record and not stored in the blob file. Blob data is stored in the record if it is small enough to fit in the size of the blob field.

Calling px_put_record(),
px_insert_record(), or
px_update_record() without calling
px_set_blob_file() will result in truncated blob fields
unless the data fits into the database file.

Calling this function twice will close the first blob file and open the new one.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

filename

The name of the file. Its extension should be .MB.

Return Values

Returns TRUE on success or FALSE on failure.


Sets a parameter

  • « px_set_blob_file
  • px_set_tablename »
  • PHP Manual
  • Paradox Functions
  • Sets a parameter

px_set_parameter

(PECL paradox >= 1.1.0)

px_set_parameter — Sets a parameter

Description

px_set_parameter ( resource $pxdoc , string $name , string $value ) : bool

Sets various parameters.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

name

Depending on the parameter you want to set, name can be one of the following.

tablename

The name of the table as it will be stored in the database header.

targetencoding

The encoding for the output. Data which is being read from character fields is recoded into the targetencoding.

inputencoding

The encoding of the input data which is to be stored into the database.

value

The value of parameter to set. For inputencoding and targetencoding this must be the name of the encoding as understood by iconv or recode, e.g. iso-8859-1, utf-8, cp850.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • px_get_info() - Return lots of information about a paradox file to determine the DOS code page.


Sets the name of a table (deprecated)

  • « px_set_parameter
  • px_set_targetencoding »
  • PHP Manual
  • Paradox Functions
  • Sets the name of a table (deprecated)

px_set_tablename

(PECL paradox >= 1.0.0)

px_set_tablename — Sets the name of a table (deprecated)

Description

px_set_tablename ( resource $pxdoc , string $name ) : void

Sets the table name of a paradox database, which was created with px_create_fp(). This function is deprecated use px_set_parameter() instead.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

tablename

The name of the table. If it is not set explicitly it will be set to the name of the database file.

Return Values

Returns NULL on success or FALSE on failure.

See Also

px_set_parameter() - Sets a parameter


Sets the encoding for character fields (deprecated)

  • « px_set_tablename
  • px_set_value »
  • PHP Manual
  • Paradox Functions
  • Sets the encoding for character fields (deprecated)

px_set_targetencoding

(PECL paradox >= 1.0.0)

px_set_targetencoding — Sets the encoding for character fields (deprecated)

Description

px_set_targetencoding ( resource $pxdoc , string $encoding ) : bool

Set the encoding for data retrieved from a character field. All character fields will be recoded to the encoding set by this function. If the encoding is not set, the character data will be returned in the DOS code page encoding as specified in the database file. The encoding can be any string identifier known to iconv or recode. On Unix systems run iconv -l for a list of available encodings.

This function is deprecated and should be replaced by calling px_set_parameter().

See also px_get_info() to determine the DOS code page as stored in the database file.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

encoding

The encoding for the output. Data which is being read from character fields is recoded into the targetencoding.

Return Values

Returns FALSE if the encoding could not be set, e.g. the encoding is unknown, or pxlib does not support recoding at all. In the second case a warning will be issued.

See Also

px_set_parameter() - Sets a parameter


Sets a value

  • « px_set_targetencoding
  • px_timestamp2string »
  • PHP Manual
  • Paradox Functions
  • Sets a value

px_set_value

(PECL paradox >= 1.1.0)

px_set_value — Sets a value

Description

px_set_value ( resource $pxdoc , string $name , float $value ) : bool

Sets various values.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

name

name can be one of the following.

numprimkeys

The number of primary keys. Paradox databases always use the first numprimkeys fields for the primary index.

value

Return Values

Returns TRUE on success or FALSE on failure.

See Also

px_set_parameter() - Sets a parameter


Converts the timestamp into a string

  • « px_set_value
  • px_update_record »
  • PHP Manual
  • Paradox Functions
  • Converts the timestamp into a string

px_timestamp2string

(PECL paradox >= 1.4.0)

px_timestamp2string — Converts the timestamp into a string

Description

px_timestamp2string ( resource $pxdoc , float $value , string $format ) : string

Turns a timestamp as it stored in the paradox file into human readable format. Paradox timestamps are the number of miliseconds since 0001-01-02. This function is just for convenience. It can be easily replaced by some math and the calendar functions as demonstrated in the following example.

Parameters

pxdoc

Resource identifier of the paradox database.

value

Value as stored in paradox database field of type PX_FIELD_TIME, or PX_FIELD_TIMESTAMP.

format

String format similar to the format used by date(). The placeholders support by this function is a subset of those supported by date() (Y, y, m, n, d, j, H, h, G, g, i, s, A, a, L).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Turn a paradox timestamp into a human readable form

<?php
$px = px_new();

/* make up a date as it could be stored in */
/* a date field of a paradox db. */
/* 700000 days since 1.1.0000. */
$days = 700000;

/* Use the calendar functions to print a */
/* human readable format of the date */
echo jdtogregorian($days+1721425)."\n";

/* Turn it into a timestamp as it stored in a paradox database */
/* Timestamps are stored in miliseconds since 0001-01-02 */
$stamp = $days * 86400.0 * 1000.0;
/* Add one hour */
$stamp += 3600000.0;
/* The following will output '7/15/1917 01:00:00'. */
echo px_timestamp2string($px, $stamp, "n/d/Y H:i:s")."\n";

px_delete($px);
?>

The above example will output:

7/15/1917
7/15/1917 01:00:00

The Julian day count as passed to jdtogregorian() has a different base of 1.1.4714 b.c. and must therefore be calculated by adding 1721425 to the day count used in the paradox file. Turning the day count into a timestamp is easily done by multiplying with 86400000.0 to obtain miliseconds.

See Also

  • px_date2string() - Converts a date into a string
  • jdtogregorian() - Converts Julian Day Count to Gregorian date


Updates record in paradox database

  • « px_timestamp2string
  • PostgreSQL »
  • PHP Manual
  • Paradox Functions
  • Updates record in paradox database

px_update_record

(PECL paradox >= 1.4.0)

px_update_record — Updates record in paradox database

Description

px_update_record ( resource $pxdoc , array $data , int $num ) : bool

Updates an exiting record in the database. The record starts at 0.

The record data is passed as an array of field values. The elements in the array must correspond to the fields in the database. If the array has less elements than fields in the database, the remaining fields will be set to null.

Note:

This function is only available if pxlib >= 0.6.0 is used.

Parameters

pxdoc

Resource identifier of the paradox database as returned by px_new().

data

Associated array containing the field values as returned by px_retrieve_record().

num

The record number is an artificial number counting records in the order as they are stored in the database. The first record has number 0.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

px_insert_record() - Inserts record into paradox database


PostgreSQL

  • Introduction
  • 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_poll — Poll the status of an in-progress asynchronous PostgreSQL connection attempt
    • pg_connect — Open a PostgreSQL connection
    • 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 a 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_columns — Fetches all rows in a particular result column as an array
    • pg_fetch_all — Fetches all rows from a result 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 resource
    • 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_oid — Returns the type ID (OID) for the corresponding field number
    • pg_field_type — Returns the type name 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_all — Reads an entire large object and send straight to browser
    • pg_lo_read — Read a large object
    • 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 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_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_query — Execute a query
    • pg_result_error_field — Returns an individual field of an error report
    • pg_result_error — Get error message associated with result
    • pg_result_seek — Set internal row offset in result resource
    • 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_params — Submits a command and separate parameters to the server without waiting for the result(s)
    • pg_send_query — Sends asynchronous query
    • pg_set_client_encoding — Set the client encoding
    • 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)


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.


Requirements

To use PostgreSQL support, you need PostgreSQL 6.5 or later, PostgreSQL 8.0 or later to enable all PostgreSQL module features. 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" | PHP_INI_SYSTEM |
pgsql.max_persistent | "-1" | PHP_INI_SYSTEM |
pgsql.max_links | "-1" | PHP_INI_SYSTEM |
pgsql.auto_reset_persistent | "0" | PHP_INI_SYSTEM | Available since PHP 4.2.0.
pgsql.ignore_notice | "0" | PHP_INI_ALL | Available since PHP 4.3.0.
pgsql.log_notice | "0" | PHP_INI_ALL | Available since PHP 4.3.0.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

pgsql.allow_persistent boolean

Whether to allow persistent Postgres connections.

pgsql.max_persistent integer

The maximum number of persistent Postgres connections per process.

pgsql.max_links integer

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

pgsql.auto_reset_persistent integer

Detect broken persistent links with pg_pconnect(). Needs a little overhead.

pgsql.ignore_notice integer

Whether or not to ignore PostgreSQL backend notices.

pgsql.log_notice integer

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

There are 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)
Long libpq version that includes compiler information.
PGSQL_ASSOC (integer)
Passed to pg_fetch_array(). Return an associative array of field names and values.
PGSQL_NUM (integer)
Passed to pg_fetch_array(). Return a numerically indexed array of field numbers and values.
PGSQL_BOTH (integer)
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 (integer)
Passed to pg_connect() to force the creation of a new connection, rather than re-using an existing identical connection.
PGSQL_CONNECT_ASYNC (integer)
Passed to pg_connect() to create an asynchronous connection. Added in PHP 5.6.0.
PGSQL_CONNECTION_BAD (integer)
Returned by pg_connection_status() indicating that the database connection is in an invalid state.
PGSQL_CONNECTION_OK (integer)
Returned by pg_connection_status() indicating that the database connection is in a valid state.
PGSQL_SEEK_SET (integer)
Passed to pg_lo_seek(). Seek operation is to begin from the start of the object.
PGSQL_SEEK_CUR (integer)
Passed to pg_lo_seek(). Seek operation is to begin from the current position.
PGSQL_SEEK_END (integer)
Passed to pg_lo_seek(). Seek operation is to begin from the end of the object.
PGSQL_EMPTY_QUERY (integer)
Returned by pg_result_status(). The string sent to the server was empty.
PGSQL_COMMAND_OK (integer)
Returned by pg_result_status(). Successful completion of a command returning no data.
PGSQL_TUPLES_OK (integer)
Returned by pg_result_status(). Successful completion of a command returning data (such as a SELECT or SHOW).
PGSQL_COPY_OUT (integer)
Returned by pg_result_status(). Copy Out (from server) data transfer started.
PGSQL_COPY_IN (integer)
Returned by pg_result_status(). Copy In (to server) data transfer started.
PGSQL_BAD_RESPONSE (integer)
Returned by pg_result_status(). The server's response was not understood.
PGSQL_NONFATAL_ERROR (integer)
Returned by pg_result_status(). A nonfatal error (a notice or warning) occurred.
PGSQL_FATAL_ERROR (integer)
Returned by pg_result_status(). A fatal error occurred.
PGSQL_TRANSACTION_IDLE (integer)
Returned by pg_transaction_status(). Connection is currently idle, not in a transaction.
PGSQL_TRANSACTION_ACTIVE (integer)
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 (integer)
Returned by pg_transaction_status(). The connection is idle, in a transaction block.
PGSQL_TRANSACTION_INERROR (integer)
Returned by pg_transaction_status(). The connection is idle, in a failed transaction block.
PGSQL_TRANSACTION_UNKNOWN (integer)
Returned by pg_transaction_status(). The connection is bad.
PGSQL_DIAG_SEVERITY (integer)
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 (integer)
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 (integer)
Passed to pg_result_error_field(). The primary human-readable error message (typically one line). Always present.
PGSQL_DIAG_MESSAGE_DETAIL (integer)
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 (integer)
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 (integer)
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 (integer)
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 (integer)
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 (integer)
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 (integer)
Passed to pg_result_error_field(). The file name of the PostgreSQL source-code location where the error was reported.
PGSQL_DIAG_SOURCE_LINE (integer)
Passed to pg_result_error_field(). The line number of the PostgreSQL source-code location where the error was reported.
PGSQL_DIAG_SOURCE_FUNCTION (integer)
Passed to pg_result_error_field(). The name of the PostgreSQL source-code function reporting the error.
PGSQL_ERRORS_TERSE (integer)
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 (integer)
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 (integer)
Passed to pg_set_error_verbosity(). The verbose mode includes all available fields.
PGSQL_NOTICE_LAST (integer)
Used by pg_last_notice(). Available since PHP 7.1.0.
PGSQL_NOTICE_ALL (integer)
Used by pg_last_notice(). Available since PHP 7.1.0.
PGSQL_NOTICE_CLEAR (integer)
Used by pg_last_notice(). Available since PHP 7.1.0.
PGSQL_STATUS_LONG (integer)
Passed to pg_result_status(). Indicates that numerical result code is desired.
PGSQL_STATUS_STRING (integer)
Passed to pg_result_status(). Indicates that textual result command tag is desired.
PGSQL_CONV_IGNORE_DEFAULT (integer)
Passed to pg_convert(). Ignore default values in the table during conversion.
PGSQL_CONV_FORCE_NULL (integer)
Passed to pg_convert(). Use SQL NULL in place of an empty string.
PGSQL_CONV_IGNORE_NOT_NULL (integer)
Passed to pg_convert(). Ignore conversion of NULL into SQL NOT NULL columns.
PGSQL_DML_NO_CONV (integer)
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 (integer)
Passed to pg_insert(), pg_select(), pg_update() and pg_delete(). Execute query by these functions.
PGSQL_DML_ASYNC (integer)
Passed to pg_insert(), pg_select(), pg_update() and pg_delete(). Execute asynchronous query by these functions.
PGSQL_DML_STRING (integer)
Passed to pg_insert(), pg_select(), pg_update() and pg_delete(). Return executed query string.
PGSQL_DML_ESCAPE (integer)
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 (integer)
Returned by pg_connect_poll() to indicate that the connection attempt failed.
PGSQL_POLLING_READING (integer)
Returned by pg_connect_poll() to indicate that the connection is waiting for the PostgreSQL socket to be readable.
PGSQL_POLLING_WRITING (integer)
Returned by pg_connect_poll() to indicate that the connection is waiting for the PostgreSQL socket to be writable.
PGSQL_POLLING_OK (integer)
Returned by pg_connect_poll() to indicate that the connection is ready to be used.
PGSQL_POLLING_ACTIVE (integer)
Returned by pg_connect_poll() to indicate that the connection is currently active.
PGSQL_DIAG_SEVERITY_NONLOCALIZED (integer)
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.


  • « Predefined Constants
  • Basic usage »
  • PHP Manual
  • PostgreSQL
  • Examples

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($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 in PostgreSQL 7.4 and above containing system views with all the necessary information, in an easily queryable form. See the » PostgreSQL Documentation for full details.

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_poll — Poll the status of an in-progress asynchronous PostgreSQL connection attempt
  • pg_connect — Open a PostgreSQL connection
  • 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 a 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_columns — Fetches all rows in a particular result column as an array
  • pg_fetch_all — Fetches all rows from a result 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 resource
  • 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_oid — Returns the type ID (OID) for the corresponding field number
  • pg_field_type — Returns the type name 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_all — Reads an entire large object and send straight to browser
  • pg_lo_read — Read a large object
  • 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 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_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_query — Execute a query
  • pg_result_error_field — Returns an individual field of an error report
  • pg_result_error — Get error message associated with result
  • pg_result_seek — Set internal row offset in result resource
  • 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_params — Submits a command and separate parameters to the server without waiting for the result(s)
  • pg_send_query — Sends asynchronous query
  • pg_set_client_encoding — Set the client encoding
  • 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)


Returns number of affected records (tuples)

  • « PostgreSQL Functions
  • pg_cancel_query »
  • PHP Manual
  • PostgreSQL Functions
  • Returns number of affected records (tuples)

pg_affected_rows

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_affected_rows — Returns number of affected records (tuples)

Description

pg_affected_rows ( resource $result ) : int

pg_affected_rows() returns the number of tuples (instances/records/rows) affected by INSERT, UPDATE, and DELETE queries.

Since PostgreSQL 9.0 and above, the server returns the number of SELECTed rows. Older PostgreSQL return 0 for SELECT.

Note:

This function used to be called pg_cmdtuples().

Parameters

result

PostgreSQL query result resource, 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.

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


Cancel an asynchronous query

  • « pg_affected_rows
  • pg_client_encoding »
  • PHP Manual
  • PostgreSQL Functions
  • Cancel an asynchronous query

pg_cancel_query

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_cancel_query — Cancel an asynchronous query

Description

pg_cancel_query ( resource $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

PostgreSQL database connection resource.

Return Values

Returns TRUE on success or FALSE on failure.

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


Gets the client encoding

  • « pg_cancel_query
  • pg_close »
  • PHP Manual
  • PostgreSQL Functions
  • Gets the client encoding

pg_client_encoding

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

pg_client_encoding — Gets the client encoding

Description

pg_client_encoding ([ resource $connection ] ) : 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:

This function requires PHP 4.0.3 or higher and PostgreSQL 7.0 or higher. 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

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

The client encoding, or FALSE on error.

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


Closes a PostgreSQL connection

  • « pg_client_encoding
  • pg_connect_poll »
  • PHP Manual
  • PostgreSQL Functions
  • Closes a PostgreSQL connection

pg_close

(PHP 4, PHP 5, PHP 7)

pg_close — Closes a PostgreSQL connection

Description

pg_close ([ resource $connection ] ) : bool

pg_close() closes the non-persistent connection to a PostgreSQL database associated with the given connection resource.

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 large object resource on the connection, do not close the connection before closing all large object resources.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

Returns TRUE on success or FALSE on failure.

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


Poll the status of an in-progress asynchronous PostgreSQL connection attempt

  • « pg_close
  • pg_connect »
  • PHP Manual
  • PostgreSQL Functions
  • Poll the status of an in-progress asynchronous PostgreSQL connection attempt

pg_connect_poll

(PHP 5 >= 5.6.0, PHP 7)

pg_connect_poll — Poll the status of an in-progress asynchronous PostgreSQL connection attempt

Description

pg_connect_poll ( resource $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

PostgreSQL database connection resource.

Return Values

Returns PGSQL_POLLING_FAILED, PGSQL_POLLING_READING, PGSQL_POLLING_WRITING, PGSQL_POLLING_OK, or PGSQL_POLLING_ACTIVE.


Open a PostgreSQL connection

  • « pg_connect_poll
  • pg_connection_busy »
  • PHP Manual
  • PostgreSQL Functions
  • Open a PostgreSQL connection

pg_connect

(PHP 4, PHP 5, PHP 7)

pg_connect — Open a PostgreSQL connection

Description

pg_connect ( string $connection_string [, int $connect_type ] ) : resource

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

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.

connect_type

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

PostgreSQL connection resource on success, FALSE on failure.

Changelog

Version | Description
5.6.0 | Support for giving the PGSQL_CONNECT_ASYNC constant as the connect_type was added.

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


Get connection is busy or not

  • « pg_connect
  • pg_connection_reset »
  • PHP Manual
  • PostgreSQL Functions
  • Get connection is busy or not

pg_connection_busy

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_connection_busy — Get connection is busy or not

Description

pg_connection_busy ( resource $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

PostgreSQL database connection resource.

Return Values

Returns TRUE if the connection is busy, FALSE otherwise.

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


Reset connection (reconnect)

  • « pg_connection_busy
  • pg_connection_status »
  • PHP Manual
  • PostgreSQL Functions
  • Reset connection (reconnect)

pg_connection_reset

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_connection_reset — Reset connection (reconnect)

Description

pg_connection_reset ( resource $connection ) : bool

pg_connection_reset() resets the connection. It is useful for error recovery.

Parameters

connection

PostgreSQL database connection resource.

Return Values

Returns TRUE on success or FALSE on failure.

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


Get connection status

  • « pg_connection_reset
  • pg_consume_input »
  • PHP Manual
  • PostgreSQL Functions
  • Get connection status

pg_connection_status

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_connection_status — Get connection status

Description

pg_connection_status ( resource $connection ) : int

pg_connection_status() returns the status of the specified connection.

Parameters

connection

PostgreSQL database connection resource.

Return Values

PGSQL_CONNECTION_OK or PGSQL_CONNECTION_BAD.

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


Reads input on the connection

  • « pg_connection_status
  • pg_convert »
  • PHP Manual
  • PostgreSQL Functions
  • Reads input on the connection

pg_consume_input

(PHP 5 >= 5.6.0, PHP 7)

pg_consume_input — Reads input on the connection

Description

pg_consume_input ( resource $connection ) : bool

pg_consume_input() consumes any input waiting to be read from the database server.

Parameters

connection

PostgreSQL database connection resource.

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.


Convert associative array values into forms suitable for SQL statements

  • « pg_consume_input
  • pg_copy_from »
  • PHP Manual
  • PostgreSQL Functions
  • Convert associative array values into forms suitable for SQL statements

pg_convert

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_convert — Convert associative array values into forms suitable for SQL statements

Description

pg_convert ( resource $connection , string $table_name , array $assoc_array [, int $options = 0 ] ) : array

pg_convert() checks and converts the values in assoc_array 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 assoc_array has elements. The fieldnames in table_name must match the indices in assoc_array and the corresponding datatypes must be compatible. Returns an array with the converted values on success, FALSE otherwise.

Note:

Since PHP 5.6.0, it accepts boolean values, converting them to PostgreSQL booleans. String representations of boolean values are also supported. NULL is converted to PostgreSQL NULL.

Prior to PHP 5.6.0, if there are boolean fields in table_name don't use the constant TRUE in assoc_array. It will be converted to the string 'TRUE' which is not a valid entry for boolean fields in PostgreSQL. Use one of "t", "true", 1, "y", "yes" instead.

Parameters

connection

PostgreSQL database connection resource.

table_name

Name of the table against which to convert types.

assoc_array

Data to be converted.

options

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

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

Changelog

Version | Description
5.6.0 | No longer experimental. Boolean/NULL data types are supported. Unknown/unsupported data types are escaped without validation. pg_convert() can be used with any data types.

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


Insert records into a table from an array

  • « pg_convert
  • pg_copy_to »
  • PHP Manual
  • PostgreSQL Functions
  • Insert records into a table from an array

pg_copy_from

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_copy_from — Insert records into a table from an array

Description

pg_copy_from ( resource $connection , string $table_name , array $rows [, string $delimiter [, string $null_as ]] ) : bool

pg_copy_from() inserts records into a table from rows. It issues a COPY FROM SQL command internally to insert records.

Parameters

connection

PostgreSQL database connection resource.

table_name

Name of the table into which to copy the rows.

rows

An array of 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.

delimiter

The token that separates values for each field in each element of rows. Default is TAB.

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.

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


Copy a table to an array

  • « pg_copy_from
  • pg_dbname »
  • PHP Manual
  • PostgreSQL Functions
  • Copy a table to an array

pg_copy_to

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_copy_to — Copy a table to an array

Description

pg_copy_to ( resource $connection , string $table_name [, string $delimiter [, string $null_as ]] ) : array

pg_copy_to() copies a table to an array. It issues COPY TO SQL command internally to retrieve records.

Parameters

connection

PostgreSQL database connection resource.

table_name

Name of the table from which to copy the data into rows.

delimiter

The token that separates values for each field in each element of rows. Default is TAB.

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. It returns FALSE on failure.

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


Get the database name

  • « pg_copy_to
  • pg_delete »
  • PHP Manual
  • PostgreSQL Functions
  • Get the database name

pg_dbname

(PHP 4, PHP 5, PHP 7)

pg_dbname — Get the database name

Description

pg_dbname ([ resource $connection ] ) : string

pg_dbname() returns the name of the database that the given PostgreSQL connection resource.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

A string containing the name of the database the connection is to, or FALSE on error.

Examples

Example #1 pg_dbname() example

<?php
  error_reporting(E_ALL);

  pg_connect("host=localhost port=5432 dbname=mary");
  echo pg_dbname(); // mary
?>


Deletes records

  • « pg_dbname
  • pg_end_copy »
  • PHP Manual
  • PostgreSQL Functions
  • Deletes records

pg_delete

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_delete — Deletes records

Description

pg_delete ( resource $connection , string $table_name , array $assoc_array [, int $options = PGSQL_DML_EXEC ] ) : mixed

pg_delete() deletes records from a table specified by the keys and values in assoc_array. If options is specified, pg_convert() is applied to assoc_array with the specified options.

If options is specified, pg_convert() is applied to assoc_array with the specified flags.

By default pg_delete() passes raw values. Values must be escaped or PGSQL_DML_ESCAPE option must be specified. PGSQL_DML_ESCAPE quotes and escapes paramters/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

PostgreSQL database connection resource.

table_name

Name of the table from which to delete rows.

assoc_array

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.

options

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

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 nither escape nor prepared query.
  $res = pg_delete($db, 'post_log', $_POST);
  if ($res) {
      echo "POST data is deleted: $res\n";
  } else {
      echo "User must have sent wrong inputs\n";
  }
?>

Changelog

Version | Description
5.6.0 | No longer experimental. Added PGSQL_DML_ESCAPE constant, TRUE/FALSE and NULL data type support.
5.5.3/5.4.19 | Direct SQL injection to table_name and Indirect SQL injection to identifiers are fixed.

See Also

  • pg_convert() - Convert associative array values into forms suitable for SQL statements


Sync with PostgreSQL backend

  • « pg_delete
  • pg_escape_bytea »
  • PHP Manual
  • PostgreSQL Functions
  • Sync with PostgreSQL backend

pg_end_copy

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

pg_end_copy — Sync with PostgreSQL backend

Description

pg_end_copy ([ resource $connection ] ) : 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

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

Returns TRUE on success or FALSE on failure.

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


Escape a string for insertion into a bytea field

  • « pg_end_copy
  • pg_escape_identifier »
  • PHP Manual
  • PostgreSQL Functions
  • Escape a string for insertion into a bytea field

pg_escape_bytea

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_escape_bytea — Escape a string for insertion into a bytea field

Description

pg_escape_bytea ([ resource $connection ], string $data ) : 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

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

data

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
5.2.0 | connection added

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


Escape a identifier for insertion into a text field

  • « pg_escape_bytea
  • pg_escape_literal »
  • PHP Manual
  • PostgreSQL Functions
  • Escape a identifier for insertion into a text field

pg_escape_identifier

(PHP 5 >= 5.4.4, PHP 7)

pg_escape_identifier — Escape a identifier for insertion into a text field

Description

pg_escape_identifier ([ resource $connection ], string $data ) : string

pg_escape_identifier() escapes a identifier (e.g. table, field names) for quering 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.

Note:

This function has internal escape code and can also be used with PostgreSQL 8.4 or less.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

data

A string containing text to be escaped.

Return Values

A string containing the escaped data.

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


Escape a literal for insertion into a text field

  • « pg_escape_identifier
  • pg_escape_string »
  • PHP Manual
  • PostgreSQL Functions
  • Escape a literal for insertion into a text field

pg_escape_literal

(PHP 5 >= 5.4.4, PHP 7)

pg_escape_literal — Escape a literal for insertion into a text field

Description

pg_escape_literal ([ resource $connection ], string $data ) : string

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.

Note:

This function has internal escape code and can also be used with PostgreSQL 8.4 or less.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect(). When there is no default connection, it raises E_WARNING and returns FALSE.

data

A string containing text to be escaped.

Return Values

A string containing the escaped data.

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


Escape a string for query

  • « pg_escape_literal
  • pg_execute »
  • PHP Manual
  • PostgreSQL Functions
  • Escape a string for query

pg_escape_string

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_escape_string — Escape a string for query

Description

pg_escape_string ([ resource $connection ], string $data ) : 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)

Note:

This function requires PostgreSQL 7.2 or later.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

data

A string containing text to be escaped.

Return Values

A string containing the escaped data.

Changelog

Version | Description
5.2.0 | connection added

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


Sends a request to execute a prepared statement with given parameters, and waits for the result

  • « pg_escape_string
  • pg_fetch_all_columns »
  • PHP Manual
  • PostgreSQL Functions
  • Sends a request to execute a prepared statement with given parameters, and waits for the result

pg_execute

(PHP 5 >= 5.1.0, PHP 7)

pg_execute — Sends a request to execute a prepared statement with given parameters, and waits for the result

Description

pg_execute ([ resource $connection ], string $stmtname , array $params ) : resource

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. pg_execute() is supported only against PostgreSQL 7.4 or higher connections; it will fail when using earlier versions.

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

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

stmtname

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

A query result resource on success or FALSE on failure.

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


Fetches all rows in a particular result column as an array

  • « pg_execute
  • pg_fetch_all »
  • PHP Manual
  • PostgreSQL Functions
  • Fetches all rows in a particular result column as an array

pg_fetch_all_columns

(PHP 5 >= 5.1.0, PHP 7)

pg_fetch_all_columns — Fetches all rows in a particular result column as an array

Description

pg_fetch_all_columns ( resource $result [, int $column = 0 ] ) : array

pg_fetch_all_columns() returns an array that contains all rows (records) in a particular column of the result resource.

Note: This function sets NULL fields to the PHP NULL value.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

column

Column number, zero-based, to be retrieved from the result resource. Defaults to the first column if not specified.

Return Values

An array with all values in the result column.

FALSE is returned if column is larger than the number of columns in the result, or on any other error.

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


Fetches all rows from a result as an array

  • « pg_fetch_all_columns
  • pg_fetch_array »
  • PHP Manual
  • PostgreSQL Functions
  • Fetches all rows from a result as an array

pg_fetch_all

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_fetch_all — Fetches all rows from a result as an array

Description

pg_fetch_all ( resource $result [, int $result_type = PGSQL_ASSOC ] ) : array

pg_fetch_all() returns an array that contains all rows (records) in the result resource.

Note: This function sets NULL fields to the PHP NULL value.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Return Values

An array with all rows in the result. Each row is an array of field values indexed by field name.

FALSE is returned if there are no rows in the result, or on any other error.

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
        )

)

Changelog

Version | Description
7.1.0 | The result_type parameter was added.

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 resource


Fetch a row as an array

  • « pg_fetch_all
  • pg_fetch_assoc »
  • PHP Manual
  • PostgreSQL Functions
  • Fetch a row as an array

pg_fetch_array

(PHP 4, PHP 5, PHP 7)

pg_fetch_array — Fetch a row as an array

Description

pg_fetch_array ( resource $result [, int $row [, int $result_type = PGSQL_BOTH ]] ) : array

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

PostgreSQL query result resource, 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.

result_type

An optional parameter that controls how the returned array is indexed. result_type is a constant and can take the following values: PGSQL_ASSOC, PGSQL_NUM and PGSQL_BOTH. Using PGSQL_NUM, pg_fetch_array() will return an array with numerical indices, using PGSQL_ASSOC it will return only associative indices while PGSQL_BOTH, the default, 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.

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 resource


Fetch a row as an associative array

  • « pg_fetch_array
  • pg_fetch_object »
  • PHP Manual
  • PostgreSQL Functions
  • Fetch a row as an associative array

pg_fetch_assoc

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_fetch_assoc — Fetch a row as an associative array

Description

pg_fetch_assoc ( resource $result [, int $row ] ) : array

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

PostgreSQL query result resource, 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.

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 resource


Fetch a row as an object

  • « pg_fetch_assoc
  • pg_fetch_result »
  • PHP Manual
  • PostgreSQL Functions
  • Fetch a row as an object

pg_fetch_object

(PHP 4, PHP 5, PHP 7)

pg_fetch_object — Fetch a row as an object

Description

pg_fetch_object ( resource $result [, int $row [, int $result_type = PGSQL_ASSOC ]] ) : object
pg_fetch_object ( resource $result [, int $row [, string $class_name [, array $params ]]] ) : object

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

PostgreSQL query result resource, 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.

result_type

Ignored and deprecated.

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

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.

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 resource


Returns values from a result resource

  • « pg_fetch_object
  • pg_fetch_row »
  • PHP Manual
  • PostgreSQL Functions
  • Returns values from a result resource

pg_fetch_result

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_fetch_result — Returns values from a result resource

Description

pg_fetch_result ( resource $result , int $row , mixed $field ) : string
pg_fetch_result ( resource $result , mixed $field ) : string

pg_fetch_result() returns the value of a particular row and field (column) in a PostgreSQL result resource.

Note:

This function used to be called pg_result().

Parameters

result

PostgreSQL query result resource, 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.

Examples

Example #1 pg_fetch_result() example

<?php
$db = pg_connect("dbname=users user=me") || die();

$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


Get a row as an enumerated array

  • « pg_fetch_result
  • pg_field_is_null »
  • PHP Manual
  • PostgreSQL Functions
  • Get a row as an enumerated array

pg_fetch_row

(PHP 4, PHP 5, PHP 7)

pg_fetch_row — Get a row as an enumerated array

Description

pg_fetch_row ( resource $result [, int $row ] ) : array

pg_fetch_row() fetches one row of data from the result associated with the specified result resource.

Note: This function sets NULL fields to the PHP NULL value.

Parameters

result

PostgreSQL query result resource, 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 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.

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 resource


Test if a field is SQL NULL

  • « pg_fetch_row
  • pg_field_name »
  • PHP Manual
  • PostgreSQL Functions
  • Test if a field is SQL NULL

pg_field_is_null

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_field_is_null — Test if a field is SQL NULL

Description

pg_field_is_null ( resource $result , int $row , mixed $field ) : int
pg_field_is_null ( resource $result , mixed $field ) : int

pg_field_is_null() tests if a field in a PostgreSQL result resource is SQL NULL or not.

Note:

This function used to be called pg_fieldisnull().

Parameters

result

PostgreSQL query result resource, 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 integer 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.

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


Returns the name of a field

  • « pg_field_is_null
  • pg_field_num »
  • PHP Manual
  • PostgreSQL Functions
  • Returns the name of a field

pg_field_name

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_field_name — Returns the name of a field

Description

pg_field_name ( resource $result , int $field_number ) : string

pg_field_name() returns the name of the field occupying the given field_number in the given PostgreSQL result resource. Field numbering starts from 0.

Note:

This function used to be called pg_fieldname().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_number

Field number, starting from 0.

Return Values

The field name, or FALSE on error.

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


Returns the field number of the named field

  • « pg_field_name
  • pg_field_prtlen »
  • PHP Manual
  • PostgreSQL Functions
  • Returns the field number of the named field

pg_field_num

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_field_num — Returns the field number of the named field

Description

pg_field_num ( resource $result , string $field_name ) : int

pg_field_num() will return the number of the field number that corresponds to the field_name in the given PostgreSQL result resource.

Note:

This function used to be called pg_fieldnum().

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_name

The name of the field.

Return Values

The field number (numbered from 0), or -1 on error.

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


Returns the printed length

  • « pg_field_num
  • pg_field_size »
  • PHP Manual
  • PostgreSQL Functions
  • Returns the printed length

pg_field_prtlen

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_field_prtlen — Returns the printed length

Description

pg_field_prtlen ( resource $result , int $row_number , mixed $field_name_or_number ) : int
pg_field_prtlen ( resource $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 integer or as a string. If it is passed as an integer, 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

PostgreSQL query result resource, 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, or FALSE on error.

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


Returns the internal storage size of the named field

  • « pg_field_prtlen
  • pg_field_table »
  • PHP Manual
  • PostgreSQL Functions
  • Returns the internal storage size of the named field

pg_field_size

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_field_size — Returns the internal storage size of the named field

Description

pg_field_size ( resource $result , int $field_number ) : 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

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_number

Field number, starting from 0.

Return Values

The internal field storage size (in bytes). -1 indicates a variable length field. FALSE is returned on error.

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


Returns the name or oid of the tables field

  • « pg_field_size
  • pg_field_type_oid »
  • PHP Manual
  • PostgreSQL Functions
  • Returns the name or oid of the tables field

pg_field_table

(PHP 5 >= 5.2.0, PHP 7)

pg_field_table — Returns the name or oid of the tables field

Description

pg_field_table ( resource $result , int $field_number [, bool $oid_only = FALSE ] ) : mixed

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

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_number

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.

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


Returns the type ID (OID) for the corresponding field number

  • « pg_field_table
  • pg_field_type »
  • PHP Manual
  • PostgreSQL Functions
  • Returns the type ID (OID) for the corresponding field number

pg_field_type_oid

(PHP 5 >= 5.1.0, PHP 7)

pg_field_type_oid — Returns the type ID (OID) for the corresponding field number

Description

pg_field_type_oid ( resource $result , int $field_number ) : int

pg_field_type_oid() returns an integer containing the OID of the base type of the given field_number in the given PostgreSQL result resource.

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

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_number

Field number, starting from 0.

Return Values

The OID of the field's base type. FALSE is returned on error.

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


Returns the type name for the corresponding field number

  • « pg_field_type_oid
  • pg_flush »
  • PHP Manual
  • PostgreSQL Functions
  • Returns the type name for the corresponding field number

pg_field_type

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_field_type — Returns the type name for the corresponding field number

Description

pg_field_type ( resource $result , int $field_number ) : string

pg_field_type() returns a string containing the base type name of the given field_number in the given PostgreSQL result resource.

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

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

field_number

Field number, starting from 0.

Return Values

A string containing the base name of the field's type, or FALSE on error.

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


Flush outbound query data on the connection

  • « pg_field_type
  • pg_free_result »
  • PHP Manual
  • PostgreSQL Functions
  • Flush outbound query data on the connection

pg_flush

(PHP 5 >= 5.6.0, PHP 7)

pg_flush — Flush outbound query data on the connection

Description

pg_flush ( resource $connection ) : mixed

pg_flush() flushes any outbound query data waiting to be sent on the connection.

Parameters

connection

PostgreSQL database connection resource.

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.


Free result memory

  • « pg_flush
  • pg_get_notify »
  • PHP Manual
  • PostgreSQL Functions
  • Free result memory

pg_free_result

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_free_result — Free result memory

Description

pg_free_result ( resource $result ) : bool

pg_free_result() frees the memory and data associated with the specified PostgreSQL query result resource.

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

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pg_free_result() example

<?php
$db = pg_connect("dbname=users user=me") || die();

$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


Gets SQL NOTIFY message

  • « pg_free_result
  • pg_get_pid »
  • PHP Manual
  • PostgreSQL Functions
  • Gets SQL NOTIFY message

pg_get_notify

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_get_notify — Gets SQL NOTIFY message

Description

pg_get_notify ( resource $connection [, int $result_type ] ) : array

pg_get_notify() gets notifications generated by a NOTIFY SQL command. To receive notifications, the LISTEN SQL command must be issued.

Parameters

connection

PostgreSQL database connection resource.

result_type

An optional parameter that controls how the returned array is indexed. result_type is a constant and can take the following values: PGSQL_ASSOC, PGSQL_NUM and PGSQL_BOTH. Using PGSQL_NUM, pg_get_notify() will return an array with numerical indices, using PGSQL_ASSOC it will return only associative indices while PGSQL_BOTH, the default, will return both numerical and associative indices.

Return Values

An array containing the NOTIFY message name and backend PID. As of PHP 5.4.0 and 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.

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


Gets the backend's process ID

  • « pg_get_notify
  • pg_get_result »
  • PHP Manual
  • PostgreSQL Functions
  • Gets the backend's process ID

pg_get_pid

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_get_pid — Gets the backend's process ID

Description

pg_get_pid ( resource $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

PostgreSQL database connection resource.

Return Values

The backend database process ID.

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


Get asynchronous query result

  • « pg_get_pid
  • pg_host »
  • PHP Manual
  • PostgreSQL Functions
  • Get asynchronous query result

pg_get_result

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_get_result — Get asynchronous query result

Description

pg_get_result ([ resource $connection ] ) : resource

pg_get_result() gets the result resource 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

PostgreSQL database connection resource.

Return Values

The result resource, or FALSE if no more results are available.

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


Returns the host name associated with the connection

  • « pg_get_result
  • pg_insert »
  • PHP Manual
  • PostgreSQL Functions
  • Returns the host name associated with the connection

pg_host

(PHP 4, PHP 5, PHP 7)

pg_host — Returns the host name associated with the connection

Description

pg_host ([ resource $connection ] ) : string

pg_host() returns the host name of the given PostgreSQL connection resource is connected to.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

A string containing the name of the host the connection is to, or FALSE on error.

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


Insert array into table

  • « pg_host
  • pg_last_error »
  • PHP Manual
  • PostgreSQL Functions
  • Insert array into table

pg_insert

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_insert — Insert array into table

Description

pg_insert ( resource $connection , string $table_name , array $assoc_array [, int $options = PGSQL_DML_EXEC ] ) : mixed

pg_insert() inserts the values of assoc_array into the table specified by table_name. If options is specified, pg_convert() is applied to assoc_array with the specified options.

If options is specified, pg_convert() is applied to assoc_array with the specified flags.

By default pg_insert() passes raw values. Values must be escaped or PGSQL_DML_ESCAPE option must be specified. PGSQL_DML_ESCAPE quotes and escapes paramters/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

PostgreSQL database connection resource.

table_name

Name of the table into which to insert rows. The table table_name must at least have as many columns as assoc_array has elements.

assoc_array

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.

options

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 options 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 the connection resource on success, or FALSE on failure. Returns string if PGSQL_DML_STRING is passed via options.

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, PG_DML_ESCAPE);
  if ($res) {
      echo "POST data is successfully logged\n";
  } else {
      echo "User must have sent wrong inputs\n";
  }
?>

Changelog

Version | Description
5.6.0 | Unless PGSQL_DML_STRING is passed, the function now returns the connection resource instead of TRUE on success.
5.6.0 | No longer experimental. Added PGSQL_DML_ESCAPE constant, TRUE/FALSE and NULL data type support.
5.5.3/5.4.19 | Direct SQL injection to table_name and Indirect SQL injection to identifiers are fixed.

See Also

  • pg_convert() - Convert associative array values into forms suitable for SQL statements


Get the last error message string of a connection

  • « pg_insert
  • pg_last_notice »
  • PHP Manual
  • PostgreSQL Functions
  • Get the last error message string of a connection

pg_last_error

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_last_error — Get the last error message string of a connection

Description

pg_last_error ([ resource $connection ] ) : 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

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

A string containing the last error message on the given connection, or FALSE on error.

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


Returns the last notice message from PostgreSQL server

  • « pg_last_error
  • pg_last_oid »
  • PHP Manual
  • PostgreSQL Functions
  • Returns the last notice message from PostgreSQL server

pg_last_notice

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

pg_last_notice — Returns the last notice message from PostgreSQL server

Description

pg_last_notice ( resource $connection [, int $option = PGSQL_NOTICE_LAST ] ) : mixed

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

PostgreSQL database connection resource.

option

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 boolean with PGSQL_NOTICE_CLEAR, or FALSE on error.

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"

Changelog

Version | Description
7.1.0 | The option parameter was added.

See Also

  • pg_query() - Execute a query
  • pg_last_error() - Get the last error message string of a connection


Returns the last row's OID

  • « pg_last_notice
  • pg_lo_close »
  • PHP Manual
  • PostgreSQL Functions
  • Returns the last row's OID

pg_last_oid

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_last_oid — Returns the last row's OID

Description

pg_last_oid ( resource $result ) : string

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

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

Return Values

A string containing the OID assigned to the most recently inserted row in the specified connection, or FALSE on error or no available OID.

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


Close a large object

  • « pg_last_oid
  • pg_lo_create »
  • PHP Manual
  • PostgreSQL Functions
  • Close a large object

pg_lo_close

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_close — Close a large object

Description

pg_lo_close ( resource $large_object ) : bool

pg_lo_close() closes a large object. large_object is a resource for the large object from pg_lo_open().

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

result

PostgreSQL large object (LOB) resource, returned by pg_lo_open().

Return Values

Returns TRUE on success or FALSE on failure.

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


Create a large object

  • « pg_lo_close
  • pg_lo_export »
  • PHP Manual
  • PostgreSQL Functions
  • Create a large object

pg_lo_create

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_create — Create a large object

Description

pg_lo_create ([ resource $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, INV_WRITE, and INV_ARCHIVE are not supported, the object is created always with both read and write access. INV_ARCHIVE has been removed from PostgreSQL itself (version 6.3 and above).

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

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

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. The parameter was added in PHP 5.3 and relies on functionality that first appeared in PostgreSQL 8.1.

Return Values

A large object OID or FALSE on error.

Changelog

Version | Description
5.3.0 | The optional object_id was added.

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");
?>


Export a large object to file

  • « pg_lo_create
  • pg_lo_import »
  • PHP Manual
  • PostgreSQL Functions
  • Export a large object to file

pg_lo_export

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_export — Export a large object to file

Description

pg_lo_export ([ resource $connection ], int $oid , string $pathname ) : 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

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

oid

The OID of the large object in the database.

pathname

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.

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


Import a large object from file

  • « pg_lo_export
  • pg_lo_open »
  • PHP Manual
  • PostgreSQL Functions
  • Import a large object from file

pg_lo_import

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_import — Import a large object from file

Description

pg_lo_import ([ resource $connection ], string $pathname [, mixed $object_id ] ) : int

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: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

Note:

This function used to be called pg_loimport().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

pathname

The full path and file name of the file on the client filesystem from which to read the large object data.

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. The parameter was added in PHP 5.3 and 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
5.3.0 | The optional object_id was added.

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


Open a large object

  • « pg_lo_import
  • pg_lo_read_all »
  • PHP Manual
  • PostgreSQL Functions
  • Open a large object

pg_lo_open

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_open — Open a large object

Description

pg_lo_open ( resource $connection , int $oid , string $mode ) : resource

pg_lo_open() opens a large object in the database and returns large object resource so that it can be manipulated.

Warning

Do not close the database connection before closing the large object resource.

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

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

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

A large object resource or FALSE on error.

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


Reads an entire large object and send straight to browser

  • « pg_lo_open
  • pg_lo_read »
  • PHP Manual
  • PostgreSQL Functions
  • Reads an entire large object and send straight to browser

pg_lo_read_all

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_read_all — Reads an entire large object and send straight to browser

Description

pg_lo_read_all ( resource $large_object ) : 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

large_object

PostgreSQL large object (LOB) resource, returned by pg_lo_open().

Return Values

Number of bytes read or FALSE on error.

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


Read a large object

  • « pg_lo_read_all
  • pg_lo_seek »
  • PHP Manual
  • PostgreSQL Functions
  • Read a large object

pg_lo_read

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_read — Read a large object

Description

pg_lo_read ( resource $large_object [, int $len = 8192 ] ) : string

pg_lo_read() reads at most len 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

large_object

PostgreSQL large object (LOB) resource, returned by pg_lo_open().

len

An optional maximum number of bytes to return.

Return Values

A string containing len bytes from the large object, or FALSE on error.

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


Seeks position within a large object

  • « pg_lo_read
  • pg_lo_tell »
  • PHP Manual
  • PostgreSQL Functions
  • Seeks position within a large object

pg_lo_seek

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_seek — Seeks position within a large object

Description

pg_lo_seek ( resource $large_object , int $offset [, int $whence = PGSQL_SEEK_CUR ] ) : bool

pg_lo_seek() seeks a position within a large object resource.

To use the large object interface, it is necessary to enclose it within a transaction block.

Parameters

large_object

PostgreSQL large object (LOB) resource, 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.

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

Changelog

Version | Description
5.6.0 | Added PostgreSQL 9.3's 64bit large object support. Both client and server must support PostgreSQL 9.3 and PHP must be 64bit build to use 64bit large object.

See Also

  • pg_lo_tell() - Returns current seek position a of large object


Returns current seek position a of large object

  • « pg_lo_seek
  • pg_lo_truncate »
  • PHP Manual
  • PostgreSQL Functions
  • Returns current seek position a of large object

pg_lo_tell

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_tell — Returns current seek position a of large object

Description

pg_lo_tell ( resource $large_object ) : 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

large_object

PostgreSQL large object (LOB) resource, 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.

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

Changelog

Version | Description
5.6.0 | Added PostgreSQL 9.3's 64bit large object support. Both client and server must support PostgreSQL 9.3 and PHP must be 64bit build to use 64bit large object.

See Also

  • pg_lo_seek() - Seeks position within a large object


Truncates a large object

  • « pg_lo_tell
  • pg_lo_unlink »
  • PHP Manual
  • PostgreSQL Functions
  • Truncates a large object

pg_lo_truncate

(PHP 5 >= 5.6.0, PHP 7)

pg_lo_truncate — Truncates a large object

Description

pg_lo_truncate ( resource $large_object , int $size ) : bool

pg_lo_truncate() truncates a large object resource.

To use the large object interface, it is necessary to enclose it within a transaction block.

Parameters

large_object

PostgreSQL large object (LOB) resource, returned by pg_lo_open().

size

The number of bytes to truncate.

Return Values

Returns TRUE on success or FALSE on failure.

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

Changelog

Version | Description
5.6.0 | Added truncate function. It supports PostgreSQL 9.3's 64bit large object. Both client and server must support PostgreSQL 9.3 and PHP must be 64bit build to use 64bit large object.

See Also

  • pg_lo_tell() - Returns current seek position a of large object


Delete a large object

  • « pg_lo_truncate
  • pg_lo_write »
  • PHP Manual
  • PostgreSQL Functions
  • Delete a large object

pg_lo_unlink

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_unlink — Delete a large object

Description

pg_lo_unlink ( resource $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

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

oid

The OID of the large object in the database.

Return Values

Returns TRUE on success or FALSE on failure.

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


Write to a large object

  • « pg_lo_unlink
  • pg_meta_data »
  • PHP Manual
  • PostgreSQL Functions
  • Write to a large object

pg_lo_write

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_lo_write — Write to a large object

Description

pg_lo_write ( resource $large_object , string $data [, int $len ] ) : int

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

large_object

PostgreSQL large object (LOB) resource, returned by pg_lo_open().

data

The data to be written to the large object. If len is specified and is less than the length of data, only len bytes will be written.

len

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.

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


Get meta data for table

  • « pg_lo_write
  • pg_num_fields »
  • PHP Manual
  • PostgreSQL Functions
  • Get meta data for table

pg_meta_data

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_meta_data — Get meta data for table

Description

pg_meta_data ( resource $connection , string $table_name [, bool $extended = FALSE ] ) : array

pg_meta_data() returns table definition for table_name as an array.

Parameters

connection

PostgreSQL database connection resource.

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

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

Changelog

Version | Description
5.6.0 | No longer experimental. Added "is enum" as default attribute. extended flag is added.

See Also

  • pg_convert() - Convert associative array values into forms suitable for SQL statements


Returns the number of fields in a result

  • « pg_meta_data
  • pg_num_rows »
  • PHP Manual
  • PostgreSQL Functions
  • Returns the number of fields in a result

pg_num_fields

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_num_fields — Returns the number of fields in a result

Description

pg_num_fields ( resource $result ) : int

pg_num_fields() returns the number of fields (columns) in a PostgreSQL result resource.

Note:

This function used to be called pg_numfields().

Parameters

result

PostgreSQL query result resource, 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.

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)


Returns the number of rows in a result

  • « pg_num_fields
  • pg_options »
  • PHP Manual
  • PostgreSQL Functions
  • Returns the number of rows in a result

pg_num_rows

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_num_rows — Returns the number of rows in a result

Description

pg_num_rows ( resource $result ) : int

pg_num_rows() will return the number of rows in a PostgreSQL result resource.

Note:

This function used to be called pg_numrows().

Parameters

result

PostgreSQL query result resource, 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.

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)


Get the options associated with the connection

  • « pg_num_rows
  • pg_parameter_status »
  • PHP Manual
  • PostgreSQL Functions
  • Get the options associated with the connection

pg_options

(PHP 4, PHP 5, PHP 7)

pg_options — Get the options associated with the connection

Description

pg_options ([ resource $connection ] ) : string

pg_options() will return a string containing the options specified on the given PostgreSQL connection resource.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

A string containing the connection options, or FALSE on error.

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


Looks up a current parameter setting of the server

  • « pg_options
  • pg_pconnect »
  • PHP Manual
  • PostgreSQL Functions
  • Looks up a current parameter setting of the server

pg_parameter_status

(PHP 5, PHP 7)

pg_parameter_status — Looks up a current parameter setting of the server

Description

pg_parameter_status ([ resource $connection ], string $param_name ) : string

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 as of PostgreSQL 8.0 include server_version, server_encoding, client_encoding, is_superuser, session_authorization, DateStyle, TimeZone, and integer_datetimes. (server_encoding, TimeZone, and integer_datetimes were not reported by releases before 8.0.) Note that server_version, server_encoding and integer_datetimes cannot change after PostgreSQL startup.

PostgreSQL 7.3 or lower servers do not report parameter settings, pg_parameter_status() includes logic to obtain values for server_version and client_encoding anyway. Applications are encouraged to use pg_parameter_status() rather than ad hoc code to determine these values.

Caution

On a pre-7.4 PostgreSQL server, changing client_encoding via SET after connection startup will not be reflected by pg_parameter_status().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

param_name

Possible param_name values include server_version, server_encoding, client_encoding, is_superuser, session_authorization, DateStyle, TimeZone, and integer_datetimes.

Return Values

A string containing the value of the parameter, FALSE on failure or invalid param_name.

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


Open a persistent PostgreSQL connection

  • « pg_parameter_status
  • pg_ping »
  • PHP Manual
  • PostgreSQL Functions
  • Open a persistent PostgreSQL connection

pg_pconnect

(PHP 4, PHP 5, PHP 7)

pg_pconnect — Open a persistent PostgreSQL connection

Description

pg_pconnect ( string $connection_string [, int $connect_type ] ) : resource

pg_pconnect() opens a connection to a PostgreSQL database. It returns a connection resource 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 connect_type.

To enable persistent connection, the pgsql.allow_persistent php.ini directive must be set to "On" (which is the default). The maximum number of persistent connection 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 your PostgreSQL version.

connect_type

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

PostgreSQL connection resource on success, FALSE on failure.

Examples

Example #1 Using pg_pconnect()

<?php
$dbconn = pg_pconnect("dbname=mary");
//connect to a database named "mary"

$dbconn2 = pg_pconnect("host=localhost port=5432 dbname=mary");
// connect to a database named "mary" on "localhost" at port "5432"

$dbconn3 = pg_pconnect("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_pconnect($conn_string);
//connect to a database named "test" on the host "sheep" with a username and password
?>

See Also

  • pg_connect() - Open a PostgreSQL connection
  • Persistent Database Connections


Ping database connection

  • « pg_pconnect
  • pg_port »
  • PHP Manual
  • PostgreSQL Functions
  • Ping database connection

pg_ping

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_ping — Ping database connection

Description

pg_ping ([ resource $connection ] ) : bool

pg_ping() pings a database connection and tries to reconnect it if it is broken.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

Returns TRUE on success or FALSE on failure.

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)


Return the port number associated with the connection

  • « pg_ping
  • pg_prepare »
  • PHP Manual
  • PostgreSQL Functions
  • Return the port number associated with the connection

pg_port

(PHP 4, PHP 5, PHP 7)

pg_port — Return the port number associated with the connection

Description

pg_port ([ resource $connection ] ) : int

pg_port() returns the port number that the given PostgreSQL connection resource is connected to.

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

An int containing the port number of the database server the connection is to, or FALSE on error.

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


Submits a request to create a prepared statement with the given parameters, and waits for completion

  • « pg_port
  • pg_put_line »
  • PHP Manual
  • PostgreSQL Functions
  • Submits a request to create a prepared statement with the given parameters, and waits for completion

pg_prepare

(PHP 5 >= 5.1.0, PHP 7)

pg_prepare — Submits a request to create a prepared statement with the given parameters, and waits for completion

Description

pg_prepare ([ resource $connection ], string $stmtname , string $query ) : resource

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. pg_prepare() is supported only against PostgreSQL 7.4 or higher connections; it will fail when using earlier versions.

The function creates a prepared statement named stmtname from the query string, which must contain a single SQL command. stmtname 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

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

stmtname

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

A query result resource on success or FALSE on failure.

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)


Send a NULL-terminated string to PostgreSQL backend

  • « pg_prepare
  • pg_query_params »
  • PHP Manual
  • PostgreSQL Functions
  • Send a NULL-terminated string to PostgreSQL backend

pg_put_line

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

pg_put_line — Send a NULL-terminated string to PostgreSQL backend

Description

pg_put_line ([ resource $connection ], string $data ) : 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

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

data

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.

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


Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text

  • « pg_put_line
  • pg_query »
  • PHP Manual
  • PostgreSQL Functions
  • 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

(PHP 5 >= 5.1.0, PHP 7)

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 ([ resource $connection ], string $query , array $params ) : resource

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. pg_query_params() is supported only against PostgreSQL 7.4 or higher connections; it will fail when using earlier versions.

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

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

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

A query result resource on success or FALSE on failure.

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


Execute a query

  • « pg_query_params
  • pg_result_error_field »
  • PHP Manual
  • PostgreSQL Functions
  • Execute a query

pg_query

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_query — Execute a query

Description

pg_query ([ resource $connection ], string $query ) : resource

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

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

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

A query result resource on success or FALSE on failure.

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)


Returns an individual field of an error report

  • « pg_query
  • pg_result_error »
  • PHP Manual
  • PostgreSQL Functions
  • Returns an individual field of an error report

pg_result_error_field

(PHP 5 >= 5.1.0, PHP 7)

pg_result_error_field — Returns an individual field of an error report

Description

pg_result_error_field ( resource $result , int $fieldcode ) : string

pg_result_error_field() returns one of the detailed error message fields associated with result resource. It is only available against a PostgreSQL 7.4 or above server. The error field is specified by the fieldcode.

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

A PostgreSQL query result resource from a previously executed statement.

fieldcode

Possible fieldcode 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 (PostgreSQL 8.0+ only), PGSQL_DIAG_INTERNAL_QUERY (PostgreSQL 8.0+ only), 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.

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


Get error message associated with result

  • « pg_result_error_field
  • pg_result_seek »
  • PHP Manual
  • PostgreSQL Functions
  • Get error message associated with result

pg_result_error

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_result_error — Get error message associated with result

Description

pg_result_error ( resource $result ) : string

pg_result_error() returns any error message associated with the result resource. 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

PostgreSQL query result resource, 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.

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


Set internal row offset in result resource

  • « pg_result_error
  • pg_result_status »
  • PHP Manual
  • PostgreSQL Functions
  • Set internal row offset in result resource

pg_result_seek

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_result_seek — Set internal row offset in result resource

Description

pg_result_seek ( resource $result , int $offset ) : bool

pg_result_seek() sets the internal row offset in a result resource.

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

offset

Row to move the internal offset to in the result resource. Rows are numbered starting from zero.

Return Values

Returns TRUE on success or FALSE on failure.

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 resource


Get status of query result

  • « pg_result_seek
  • pg_select »
  • PHP Manual
  • PostgreSQL Functions
  • Get status of query result

pg_result_status

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_result_status — Get status of query result

Description

pg_result_status ( resource $result [, int $type = PGSQL_STATUS_LONG ] ) : mixed

pg_result_status() returns the status of a result resource, or the PostgreSQL command completion tag associated with the result

Parameters

result

PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).

type

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

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


Select records

  • « pg_result_status
  • pg_send_execute »
  • PHP Manual
  • PostgreSQL Functions
  • Select records

pg_select

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_select — Select records

Description

pg_select ( resource $connection , string $table_name , array $assoc_array [, int $options = PGSQL_DML_EXEC [, int $result_type = PGSQL_ASSOC ]] ) : mixed

pg_select() selects records specified by assoc_array which has field=>value. For a successful query, it returns an array containing all records and fields that match the condition specified by assoc_array.

If options is specified, pg_convert() is applied to assoc_array with the specified flags.

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 paramters/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

PostgreSQL database connection resource.

table_name

Name of the table from which to select rows.

assoc_array

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.

options

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

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

Changelog

Version | Description
7.1.0 | The result_type parameter was added.
5.6.0 | No longer experimental. Added PGSQL_DML_ESCAPE constant, TRUE/FALSE and NULL data type support.
5.5.3/5.4.19 | Direct SQL injection to table_name and Indirect SQL injection to identifiers are fixed.

See Also

  • pg_convert() - Convert associative array values into forms suitable for SQL statements


Sends a request to execute a prepared statement with given parameters, without waiting for the result(s)

  • « pg_select
  • pg_send_prepare »
  • PHP Manual
  • PostgreSQL Functions
  • Sends a request to execute a prepared statement with given parameters, without waiting for the result(s)

pg_send_execute

(PHP 5 >= 5.1.0, PHP 7)

pg_send_execute — Sends a request to execute a prepared statement with given parameters, without waiting for the result(s)

Description

pg_send_execute ( resource $connection , string $stmtname , array $params ) : 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

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

stmtname

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 on failure. Use pg_get_result() to determine the query result.

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


Sends a request to create a prepared statement with the given parameters, without waiting for completion

  • « pg_send_execute
  • pg_send_query_params »
  • PHP Manual
  • PostgreSQL Functions
  • Sends a request to create a prepared statement with the given parameters, without waiting for completion

pg_send_prepare

(PHP 5 >= 5.1.0, PHP 7)

pg_send_prepare — Sends a request to create a prepared statement with the given parameters, without waiting for completion

Description

pg_send_prepare ( resource $connection , string $stmtname , string $query ) : 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

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

stmtname

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 on failure. Use pg_get_result() to determine the query result.

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)


Submits a command and separate parameters to the server without waiting for the result(s)

  • « pg_send_prepare
  • pg_send_query »
  • PHP Manual
  • PostgreSQL Functions
  • Submits a command and separate parameters to the server without waiting for the result(s)

pg_send_query_params

(PHP 5 >= 5.1.0, PHP 7)

pg_send_query_params — Submits a command and separate parameters to the server without waiting for the result(s)

Description

pg_send_query_params ( resource $connection , string $query , array $params ) : 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

PostgreSQL database connection resource.

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 or FALSE on failure.

Use pg_get_result() to determine the query result.

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


Sends asynchronous query

  • « pg_send_query_params
  • pg_set_client_encoding »
  • PHP Manual
  • PostgreSQL Functions
  • Sends asynchronous query

pg_send_query

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pg_send_query — Sends asynchronous query

Description

pg_send_query ( resource $connection , string $query ) : 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

PostgreSQL database connection resource.

query

The SQL statement or statements to be executed.

Data inside the query should be properly escaped.

Return Values

Returns TRUE on success or FALSE on failure.

Use pg_get_result() to determine the query result.

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


Set the client encoding

  • « pg_send_query
  • pg_set_error_verbosity »
  • PHP Manual
  • PostgreSQL Functions
  • Set the client encoding

pg_set_client_encoding

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

pg_set_client_encoding — Set the client encoding

Description

pg_set_client_encoding ([ resource $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

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

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.

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


Determines the verbosity of messages returned by pg_last_error and pg_result_error

  • « pg_set_client_encoding
  • pg_socket »
  • PHP Manual
  • PostgreSQL Functions
  • Determines the verbosity of messages returned by pg_last_error and pg_result_error

pg_set_error_verbosity

(PHP 5 >= 5.1.0, PHP 7)

pg_set_error_verbosity — Determines the verbosity of messages returned by pg_last_error() and pg_result_error()

Description

pg_set_error_verbosity ([ resource $connection ], int $verbosity ) : int

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

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

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.

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


Get a read only handle to the socket underlying a PostgreSQL connection

  • « pg_set_error_verbosity
  • pg_trace »
  • PHP Manual
  • PostgreSQL Functions
  • Get a read only handle to the socket underlying a PostgreSQL connection

pg_socket

(PHP 5 >= 5.6.0, PHP 7)

pg_socket — Get a read only handle to the socket underlying a PostgreSQL connection

Description

pg_socket ( resource $connection ) : resource

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

PostgreSQL database connection resource.

Return Values

A socket resource on success or FALSE on failure.


Enable tracing a PostgreSQL connection

  • « pg_socket
  • pg_transaction_status »
  • PHP Manual
  • PostgreSQL Functions
  • Enable tracing a PostgreSQL connection

pg_trace

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

pg_trace — Enable tracing a PostgreSQL connection

Description

pg_trace ( string $pathname [, string $mode = "w" [, resource $connection ]] ) : 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

pathname

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

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

Returns TRUE on success or FALSE on failure.

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


Returns the current in-transaction status of the server

  • « pg_trace
  • pg_tty »
  • PHP Manual
  • PostgreSQL Functions
  • Returns the current in-transaction status of the server

pg_transaction_status

(PHP 5 >= 5.1.0, PHP 7)

pg_transaction_status — Returns the current in-transaction status of the server

Description

pg_transaction_status ( resource $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

PostgreSQL database connection resource.

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.

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


Return the TTY name associated with the connection

  • « pg_transaction_status
  • pg_unescape_bytea »
  • PHP Manual
  • PostgreSQL Functions
  • Return the TTY name associated with the connection

pg_tty

(PHP 4, PHP 5, PHP 7)

pg_tty — Return the TTY name associated with the connection

Description

pg_tty ([ resource $connection ] ) : string

pg_tty() returns the TTY name that server side debugging output is sent to on the given PostgreSQL connection resource.

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

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

A string containing the debug TTY of the connection, or FALSE on error.

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


Unescape binary for bytea type

  • « pg_tty
  • pg_untrace »
  • PHP Manual
  • PostgreSQL Functions
  • Unescape binary for bytea type

pg_unescape_bytea

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_unescape_bytea — Unescape binary for bytea type

Description

pg_unescape_bytea ( string $data ) : 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.

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

data

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

Changelog

Version | Description
5.5.1 | A warning is thrown if the input string is invalid.

See Also

  • pg_escape_bytea() - Escape a string for insertion into a bytea field
  • pg_escape_string() - Escape a string for query


Disable tracing of a PostgreSQL connection

  • « pg_unescape_bytea
  • pg_update »
  • PHP Manual
  • PostgreSQL Functions
  • Disable tracing of a PostgreSQL connection

pg_untrace

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

pg_untrace — Disable tracing of a PostgreSQL connection

Description

pg_untrace ([ resource $connection ] ) : bool

Stop tracing started by pg_trace().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

Always returns TRUE.

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


Update table

  • « pg_untrace
  • pg_version »
  • PHP Manual
  • PostgreSQL Functions
  • Update table

pg_update

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pg_update — Update table

Description

pg_update ( resource $connection , string $table_name , array $data , array $condition [, int $options = PGSQL_DML_EXEC ] ) : mixed

pg_update() updates records that matches condition with data. If options is specified, pg_convert() is applied to data with specified options.

pg_update() updates records specified by assoc_array which has field=>value.

If options is specified, pg_convert() is applied to assoc_array with the specified flags.

By default pg_update() passes raw values. Values must be escaped or PGSQL_DML_ESCAPE option must be specified. PGSQL_DML_ESCAPE quotes and escapes paramters/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

PostgreSQL database connection resource.

table_name

Name of the table into which to update rows.

data

An array whose keys are field names in the table table_name, and whose values are what matched rows are to be updated to.

condition

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.

options

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

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

Changelog

Version | Description
5.6.0 | No longer experimental. Added PGSQL_DML_ESCAPE constant, TRUE/FALSE and NULL data type support.
5.5.3/5.4.19 | Direct SQL injection to table_name and Indirect SQL injection to identifiers are fixed.

See Also

  • pg_convert() - Convert associative array values into forms suitable for SQL statements


Returns an array with client, protocol and server version (when available)

  • « pg_update
  • SQLite »
  • PHP Manual
  • PostgreSQL Functions
  • Returns an array with client, protocol and server version (when available)

pg_version

(PHP 5, PHP 7)

pg_version — Returns an array with client, protocol and server version (when available)

Description

pg_version ([ resource $connection ] ) : array

pg_version() returns an array with the client, protocol and server version. Protocol and server versions are only available if PHP was compiled with PostgreSQL 7.4 or later.

For more detailed server information, use pg_parameter_status().

Parameters

connection

PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Return Values

Returns an array with client, protocol and server keys and values (if available). Returns FALSE on error or invalid connection.

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


SQLite

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • SQLite Functions
    • sqlite_array_query — Execute a query against a given database and returns an array
    • sqlite_busy_timeout — Set busy timeout duration, or disable busy handlers
    • sqlite_changes — Returns the number of rows that were changed by the most recent SQL statement
    • sqlite_close — Closes an open SQLite database
    • sqlite_column — Fetches a column from the current row of a result set
    • sqlite_create_aggregate — Register an aggregating UDF for use in SQL statements
    • sqlite_create_function — Registers a "regular" User Defined Function for use in SQL statements
    • sqlite_current — Fetches the current row from a result set as an array
    • sqlite_error_string — Returns the textual description of an error code
    • sqlite_escape_string — Escapes a string for use as a query parameter
    • sqlite_exec — Executes a result-less query against a given database
    • sqlite_factory — Opens an SQLite database and returns an SQLiteDatabase object
    • sqlite_fetch_all — Fetches all rows from a result set as an array of arrays
    • sqlite_fetch_array — Fetches the next row from a result set as an array
    • sqlite_fetch_column_types — Return an array of column types from a particular table
    • sqlite_fetch_object — Fetches the next row from a result set as an object
    • sqlite_fetch_single — Fetches the first column of a result set as a string
    • sqlite_fetch_string — Alias of sqlite_fetch_single
    • sqlite_field_name — Returns the name of a particular field
    • sqlite_has_more — Finds whether or not more rows are available
    • sqlite_has_prev — Returns whether or not a previous row is available
    • sqlite_key — Returns the current row index
    • sqlite_last_error — Returns the error code of the last error for a database
    • sqlite_last_insert_rowid — Returns the rowid of the most recently inserted row
    • sqlite_libencoding — Returns the encoding of the linked SQLite library
    • sqlite_libversion — Returns the version of the linked SQLite library
    • sqlite_next — Seek to the next row number
    • sqlite_num_fields — Returns the number of fields in a result set
    • sqlite_num_rows — Returns the number of rows in a buffered result set
    • sqlite_open — Opens an SQLite database and create the database if it does not exist
    • sqlite_popen — Opens a persistent handle to an SQLite database and create the database if it does not exist
    • sqlite_prev — Seek to the previous row number of a result set
    • sqlite_query — Executes a query against a given database and returns a result handle
    • sqlite_rewind — Seek to the first row number
    • sqlite_seek — Seek to a particular row number of a buffered result set
    • sqlite_single_query — Executes a query and returns either an array for one single column or the value of the first row
    • sqlite_udf_decode_binary — Decode binary data passed as parameters to an UDF
    • sqlite_udf_encode_binary — Encode binary data before returning it from an UDF
    • sqlite_unbuffered_query — Execute a query that does not prefetch and buffer all data
    • sqlite_valid — Returns whether more rows are available


Introduction

This is an extension for the SQLite Embeddable SQL Database Engine. SQLite is a C library that implements an embeddable SQL database engine. Programs that link with the SQLite library can have SQL database access without running a separate RDBMS process.

SQLite is not a client library used to connect to a big database server. SQLite is the server. The SQLite library reads and writes directly to and from the database files on disk.

Note:

For further information see the SQLite Website (» http://sqlite.org/).

Note: This extension offers support for SQLite 2.x. Sqlite 3.x is supported by the SQLite3 extension.


Requirements

The SQLite extension is enabled by default as of PHP 5.0. Beginning with PHP 5.4, the SQLite extension is available only via PECL.


Installation

Since PHP 5.0 this extension was bundled with PHP. Beginning with PHP 5.4, this extension is available only via PECL.

Windows users must enable php_sqlite.dll inside of php.ini in order to use these functions. A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Windows builds must also enable PDO because as of PHP 5.1.0 it depends on it. So, php.ini will end up with something like this:

extension=php_pdo.dll
extension=php_sqlite.dll
On Linux or Unix operating systems, if you build PDO as a shared extension, you must build SQLite as a shared extension using the --with-sqlite=shared configure option.

The PHP 5.0.x series of Windows builds enabled this extension by default, where no DLL file is necessary.

SQLite 3 is supported through PDO SQLite.

Note: Windows installation for unprivileged accounts

On Windows operating systems, unprivileged accounts don't have the TMP environment variable set by default. This will make sqlite create temporary files in the windows directory, which is not desirable. So, you should set the TMP environment variable for the web server or the user account the web server is running under. If Apache is your web server, you can accomplish this via a SetEnv directive in your httpd.conf file. For example:

SetEnv TMP c:/temp
If you are unable to establish this setting at the server level, you can implement the setting in your script:
<?php
putenv('TMP=C:/temp');
?>
The setting must refer to a directory that the web server has permission to create files in and subsequently write to and delete the files it created. Otherwise, you may receive the following error message: malformed database schema - unable to open a temporary database file for storing temporary tables


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

SQLite Configure Options
Name | Default | Changeable | Changelog
sqlite.assoc_case | "0" | PHP_INI_ALL | Available since PHP 5.0.0.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

sqlite.assoc_case int

Whether to use mixed case (0), upper case (1) or lower case (2) hash indexes.

This option is primarily useful when you need compatibility with other database systems, where the names of the columns are always returned as uppercase or lowercase, regardless of the case of the actual field names in the database schema.

The SQLite library returns the column names in their natural case (that matches the case you used in your schema). When sqlite.assoc_case is set to 0 the natural case will be preserved. When it is set to 1 or 2, PHP will apply case folding on the hash keys to upper- or lower-case the keys, respectively.

Use of this option incurs a slight performance penalty, but is MUCH faster than performing the case folding yourself using PHP script.


Resource Types

There are two resources used in the SQLite Interface. The first one is the database connection, the second one 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 functions sqlite_fetch_array() and sqlite_current() use a constant for the different types of result arrays. The following constants are defined:

SQLite result type constants
SQLITE_ASSOC (int)
Columns are returned into the array having the field name as the array index.
SQLITE_BOTH (int)
Columns are returned into the array having both a numerical index and the field name as the array index.
SQLITE_NUM (int)
Columns are returned into the array having a numerical index to the fields. This index starts with 0, the first field in the result.

A number of functions may return status codes. The following constants are defined:

SQLite status code constants
SQLITE_OK (int)
Successful result.
SQLITE_ERROR (int)
SQL error or missing database.
SQLITE_INTERNAL (int)
An internal logic error in SQLite.
SQLITE_PERM (int)
Access permission denied.
SQLITE_ABORT (int)
Callback routine requested an abort.
SQLITE_BUSY (int)
The database file is locked.
SQLITE_LOCKED (int)
A table in the database is locked.
SQLITE_NOMEM (int)
Memory allocation failed.
SQLITE_READONLY (int)
Attempt to write a readonly database.
SQLITE_INTERRUPT (int)
Operation terminated internally.
SQLITE_IOERR (int)
Disk I/O error occurred.
SQLITE_NOTADB (int)
File opened that is not a database file.
SQLITE_CORRUPT (int)
The database disk image is malformed.
SQLITE_FORMAT (int)
Auxiliary database format error.
SQLITE_NOTFOUND (int)
(Internal) Table or record not found.
SQLITE_FULL (int)
Insertion failed because database is full.
SQLITE_CANTOPEN (int)
Unable to open the database file.
SQLITE_PROTOCOL (int)
Database lock protocol error.
SQLITE_EMPTY (int)
(Internal) Database table is empty.
SQLITE_SCHEMA (int)
The database schema changed.
SQLITE_TOOBIG (int)
Too much data for one row of a table.
SQLITE_CONSTRAINT (int)
Abort due to constraint violation.
SQLITE_MISMATCH (int)
Data type mismatch.
SQLITE_MISUSE (int)
Library used incorrectly.
SQLITE_NOLFS (int)
Uses of OS features not supported on host.
SQLITE_AUTH (int)
Authorized failed.
SQLITE_ROW (int)
Internal process has another row ready.
SQLITE_DONE (int)
Internal process has finished executing.


SQLite Functions

Predefined Classes

SQLiteDatabase

Represents an opened SQLite database.

Constructor

  • __construct - construct a new SQLiteDatabase object

Methods

  • query - Execute a query
  • queryExec - Execute a result-less query
  • arrayQuery - Execute a query and return the result as an array
  • singleQuery - Execute a query and return either an array for one single column or the value of the first row
  • unbufferedQuery - Execute an unbuffered query
  • lastInsertRowid - Returns the rowid of the most recently inserted row
  • changes - Returns the number of rows changed by the most recent statement
  • createAggregate - Register an aggregating UDF for use in SQL statements
  • createFunction - Register a UDF for use in SQL statements
  • busyTimeout - Sets or disables busy timeout duration
  • lastError - Returns the last error code of the most recently encountered error
  • fetchColumnTypes - Return an array of column types from a particular table

SQLiteResult

Represents a buffered SQLite result set.

Methods

  • fetch - Fetches the next row from the result set as an array
  • fetchObject - Fetches the next row from the result set as an object
  • fetchSingle - Fetches the first column from the result set as a string
  • fetchAll - Fetches all rows from the result set as an array of arrays
  • column - Fetches a column from the current row of the result set
  • numFields - Returns the number of fields in the result set
  • fieldName - Returns the name of a particular field in the result set
  • current - Fetches the current row from the result set as an array
  • key - Return the current row index
  • next - Seek to the next row number
  • valid - Returns whether more rows are available
  • rewind - Seek to the first row number of the result set
  • prev - Seek to the previous row number of the result set
  • hasPrev - Returns whether or not a previous row is available
  • numRows - Returns the number of rows in the result set
  • seek - Seek to a particular row number

SQLiteUnbuffered

Represents an unbuffered SQLite result set. Unbuffered results sets are sequential, forward-seeking only.

Methods

  • fetch - Fetches the next row from the result set as an array
  • fetchObject - Fetches the next row from the result set as an object
  • fetchSingle - Fetches the first column from the result set as a string
  • fetchAll - Fetches all rows from the result set as an array of arrays
  • column - Fetches a column from the current row of the result set
  • numFields - Returns the number of fields in the result set
  • fieldName - Returns the name of a particular field in the result set
  • current - Fetches the current row from the result set as an array
  • next - Seek to the next row number
  • valid - Returns whether more rows are available

Table of Contents

  • sqlite_array_query — Execute a query against a given database and returns an array
  • sqlite_busy_timeout — Set busy timeout duration, or disable busy handlers
  • sqlite_changes — Returns the number of rows that were changed by the most recent SQL statement
  • sqlite_close — Closes an open SQLite database
  • sqlite_column — Fetches a column from the current row of a result set
  • sqlite_create_aggregate — Register an aggregating UDF for use in SQL statements
  • sqlite_create_function — Registers a "regular" User Defined Function for use in SQL statements
  • sqlite_current — Fetches the current row from a result set as an array
  • sqlite_error_string — Returns the textual description of an error code
  • sqlite_escape_string — Escapes a string for use as a query parameter
  • sqlite_exec — Executes a result-less query against a given database
  • sqlite_factory — Opens an SQLite database and returns an SQLiteDatabase object
  • sqlite_fetch_all — Fetches all rows from a result set as an array of arrays
  • sqlite_fetch_array — Fetches the next row from a result set as an array
  • sqlite_fetch_column_types — Return an array of column types from a particular table
  • sqlite_fetch_object — Fetches the next row from a result set as an object
  • sqlite_fetch_single — Fetches the first column of a result set as a string
  • sqlite_fetch_string — Alias of sqlite_fetch_single
  • sqlite_field_name — Returns the name of a particular field
  • sqlite_has_more — Finds whether or not more rows are available
  • sqlite_has_prev — Returns whether or not a previous row is available
  • sqlite_key — Returns the current row index
  • sqlite_last_error — Returns the error code of the last error for a database
  • sqlite_last_insert_rowid — Returns the rowid of the most recently inserted row
  • sqlite_libencoding — Returns the encoding of the linked SQLite library
  • sqlite_libversion — Returns the version of the linked SQLite library
  • sqlite_next — Seek to the next row number
  • sqlite_num_fields — Returns the number of fields in a result set
  • sqlite_num_rows — Returns the number of rows in a buffered result set
  • sqlite_open — Opens an SQLite database and create the database if it does not exist
  • sqlite_popen — Opens a persistent handle to an SQLite database and create the database if it does not exist
  • sqlite_prev — Seek to the previous row number of a result set
  • sqlite_query — Executes a query against a given database and returns a result handle
  • sqlite_rewind — Seek to the first row number
  • sqlite_seek — Seek to a particular row number of a buffered result set
  • sqlite_single_query — Executes a query and returns either an array for one single column or the value of the first row
  • sqlite_udf_decode_binary — Decode binary data passed as parameters to an UDF
  • sqlite_udf_encode_binary — Encode binary data before returning it from an UDF
  • sqlite_unbuffered_query — Execute a query that does not prefetch and buffer all data
  • sqlite_valid — Returns whether more rows are available


Execute a query against a given database and returns an array

  • « SQLite Functions
  • sqlite_busy_timeout »
  • PHP Manual
  • SQLite Functions
  • Execute a query against a given database and returns an array

sqlite_array_query

SQLiteDatabase::arrayQuery

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_array_query -- SQLiteDatabase::arrayQuery — Execute a query against a given database and returns an array

Description

sqlite_array_query ( resource $dbhandle , string $query [, int $result_type = SQLITE_BOTH [, bool $decode_binary = TRUE ]] ) : array
sqlite_array_query ( string $query , resource $dbhandle [, int $result_type = SQLITE_BOTH [, bool $decode_binary = TRUE ]] ) : array

Object oriented style (method):

public SQLiteDatabase::arrayQuery ( string $query [, int $result_type = SQLITE_BOTH [, bool $decode_binary = TRUE ]] ) : array

sqlite_array_query() executes the given query and returns an array of the entire result set. It is similar to calling sqlite_query() and then sqlite_fetch_array() for each row in the result set. sqlite_array_query() is significantly faster than the aforementioned.

Tip

sqlite_array_query() is best suited to queries returning 45 rows or less. If you have more data than that, it is recommended that you write your scripts to use sqlite_unbuffered_query() instead for more optimal performance.

Parameters

query

The query to be executed.

Data inside the query should be properly escaped.

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.

decode_binary

When the decode_binary parameter is set to TRUE (the default), PHP will decode the binary encoding it applied to the data if it was encoded using the sqlite_escape_string(). You should normally leave this value at its default, unless you are interoperating with databases created by other sqlite capable applications.

Note: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.

Return Values

Returns an array of the entire result set; FALSE otherwise.

The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be case-folded according to the value of the sqlite.assoc_case configuration option.

Examples

Example #1 Procedural style

<?php
$dbhandle = sqlite_open('sqlitedb');
$result = sqlite_array_query($dbhandle, 'SELECT name, email FROM users LIMIT 25', SQLITE_ASSOC);
foreach ($result as $entry) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?>

Example #2 Object-oriented style

<?php
$dbhandle = new SQLiteDatabase('sqlitedb');
$result = $dbhandle->arrayQuery('SELECT name, email FROM users LIMIT 25', SQLITE_ASSOC);
foreach ($result as $entry) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?>

See Also

  • sqlite_query() - Executes a query against a given database and returns a result handle
  • sqlite_fetch_array() - Fetches the next row from a result set as an array
  • sqlite_fetch_string() - Alias of sqlite_fetch_single


Set busy timeout duration, or disable busy handlers

  • « sqlite_array_query
  • sqlite_changes »
  • PHP Manual
  • SQLite Functions
  • Set busy timeout duration, or disable busy handlers

sqlite_busy_timeout

SQLiteDatabase::busyTimeout

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_busy_timeout -- SQLiteDatabase::busyTimeout — Set busy timeout duration, or disable busy handlers

Description

sqlite_busy_timeout ( resource $dbhandle , int $milliseconds ) : void

Object oriented style (method):

public SQLiteDatabase::busyTimeout ( int $milliseconds ) : void

Set the maximum time, in milliseconds, that SQLite will wait for a dbhandle to become ready for use.

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

milliseconds

The number of milliseconds. When set to 0, busy handlers will be disabled and SQLite will return immediately with a SQLITE_BUSY status code if another process/thread has the database locked for an update.

PHP sets the default busy timeout to be 60 seconds when the database is opened.

Note:

There are one thousand (1000) milliseconds in one second.

Return Values

No value is returned.

Examples

Example #1 Procedural style

<?php
$dbhandle = sqlite_open('sqlitedb');
sqlite_busy_timeout($dbhandle, 10000); // set timeout to 10 seconds
sqlite_busy_timeout($dbhandle, 0); // disable busy handler
?>

Example #2 Object oriented style

<?php
$dbhandle = new SQLiteDatabase('sqlitedb');
$dbhandle->busyTimeout(10000); // 10 seconds
$dbhandle->busyTimeout(0); // disable
?>

See Also

  • sqlite_open() - Opens an SQLite database and create the database if it does not exist


Returns the number of rows that were changed by the most recent SQL statement

  • « sqlite_busy_timeout
  • sqlite_close »
  • PHP Manual
  • SQLite Functions
  • Returns the number of rows that were changed by the most recent SQL statement

sqlite_changes

SQLiteDatabase::changes

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_changes -- SQLiteDatabase::changes — Returns the number of rows that were changed by the most recent SQL statement

Description

sqlite_changes ( resource $dbhandle ) : int

Object oriented style (method):

public SQLiteDatabase::changes ( void ) : int

Returns the numbers of rows that were changed by the most recent SQL statement executed against the dbhandle database handle.

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

Return Values

Returns the number of changed rows.

Examples

Example #1 Procedural style

<?php
$dbhandle = sqlite_open('mysqlitedb');
$query = sqlite_query($dbhandle, "UPDATE users SET email='jDoe@example.com' WHERE username='jDoe'");
if (!$query) {
    exit('Error in query.');
} else {
    echo 'Number of rows modified: ', sqlite_changes($dbhandle);
}
?>

Example #2 Object oriented style

<?php
$dbhandle = new SQLiteDatabase('mysqlitedb');
$query = $dbhandle->query("UPDATE users SET email='jDoe@example.com' WHERE username='jDoe'");
if (!$query) {
    exit('Error in query.');
} else {
    echo 'Number of rows modified: ', $dbhandle->changes();
}
?>

See Also

  • sqlite_open() - Opens an SQLite database and create the database if it does not exist


Closes an open SQLite database

  • « sqlite_changes
  • sqlite_column »
  • PHP Manual
  • SQLite Functions
  • Closes an open SQLite database

sqlite_close

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_close — Closes an open SQLite database

Description

sqlite_close ( resource $dbhandle ) : void

Closes the given db_handle database handle. If the database was persistent, it will be closed and removed from the persistent list.

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally.

Return Values

No value is returned.

Examples

Example #1 sqlite_close() example

<?php
$dbhandle = sqlite_open('sqlitedb');
sqlite_close($dbhandle);
?>

See Also

  • sqlite_open() - Opens an SQLite database and create the database if it does not exist
  • sqlite_popen() - Opens a persistent handle to an SQLite database and create the database if it does not exist


Fetches a column from the current row of a result set

  • « sqlite_close
  • sqlite_create_aggregate »
  • PHP Manual
  • SQLite Functions
  • Fetches a column from the current row of a result set

sqlite_column

SQLiteResult::column

SQLiteUnbuffered::column

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_column -- SQLiteResult::column -- SQLiteUnbuffered::column — Fetches a column from the current row of a result set

Description

sqlite_column ( resource $result , mixed $index_or_name [, bool $decode_binary = TRUE ] ) : mixed
SQLiteResult::column ( mixed $index_or_name [, bool $decode_binary = TRUE ] ) : mixed
SQLiteUnbuffered::column ( mixed $index_or_name [, bool $decode_binary = TRUE ] ) : mixed

Fetches the value of a column named index_or_name (if it is a string), or of the ordinal column numbered index_or_name (if it is an integer) from the current row of the query result handle result.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

index_or_name

The column index or name to fetch.

decode_binary

When the decode_binary parameter is set to TRUE (the default), PHP will decode the binary encoding it applied to the data if it was encoded using the sqlite_escape_string(). You should normally leave this value at its default, unless you are interoperating with databases created by other sqlite capable applications.

Return Values

Returns the column value.

Notes

Note:

Use this function when you are iterating a large result set with many columns, or with columns that contain large amounts of data.

See Also

  • sqlite_fetch_string() - Alias of sqlite_fetch_single


Register an aggregating UDF for use in SQL statements

  • « sqlite_column
  • sqlite_create_function »
  • PHP Manual
  • SQLite Functions
  • Register an aggregating UDF for use in SQL statements

sqlite_create_aggregate

SQLiteDatabase::createAggregate

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_create_aggregate -- SQLiteDatabase::createAggregate — Register an aggregating UDF for use in SQL statements

Description

sqlite_create_aggregate ( resource $dbhandle , string $function_name , callable $step_func , callable $finalize_func [, int $num_args = -1 ] ) : void

Object oriented style (method):

public SQLiteDatabase::createAggregate ( string $function_name , callable $step_func , callable $finalize_func [, int $num_args = -1 ] ) : void

sqlite_create_aggregate() is similar to sqlite_create_function() 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 function and sqlite_create_function() is that two functions are required to manage the aggregate; step_func is called for each row of the result set. Your PHP function should accumulate the result and store it into the aggregation context. Once all the rows have been processed, finalize_func will be called and it should then take the data from the aggregation context and return the result. Callback functions should return a type understood by SQLite (i.e. scalar type).

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

function_name

The name of the function used in SQL statements.

step_func

Callback function called for each row of the result set. Function parameters are &$context, $value, ....

finalize_func

Callback function to aggregate the "stepped" data from each row. Function parameter is &$context and the function should return the final result of aggregation.

num_args

Hint to the SQLite parser if the callback function accepts a predetermined number of arguments.

Return Values

No value is returned.

Examples

Example #1 max_length aggregation function example

<?php
$data = array(
   'one',
   'two',
   'three',
   'four',
   'five',
   'six',
   'seven',
   'eight',
   'nine',
   'ten',
   );
$dbhandle = sqlite_open(':memory:');
sqlite_query($dbhandle, "CREATE TABLE strings(a)");
foreach ($data as $str) {
    $str = sqlite_escape_string($str);
    sqlite_query($dbhandle, "INSERT INTO strings VALUES ('$str')");
}

function max_len_step(&$context, $string)
{
    if (strlen($string) > $context) {
        $context = strlen($string);
    }
}

function max_len_finalize(&$context)
{
    return $context;
}

sqlite_create_aggregate($dbhandle, 'max_len', 'max_len_step', 'max_len_finalize');

var_dump(sqlite_array_query($dbhandle, 'SELECT max_len(a) from strings'));

?>

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.

Note:

The example above will not work correctly if the column contains binary data. Take a look at the manual page for sqlite_udf_decode_binary() for an explanation of why this is so, and an example of how to make it respect the binary encoding.

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 sqlite_create_function() and sqlite_create_aggregate() to override SQLite native SQL functions.

See Also

  • sqlite_create_function() - Registers a "regular" User Defined Function for use in SQL statements
  • sqlite_udf_encode_binary() - Encode binary data before returning it from an UDF
  • sqlite_udf_decode_binary() - Decode binary data passed as parameters to an UDF


Registers a "regular" User Defined Function for use in SQL statements

  • « sqlite_create_aggregate
  • sqlite_current »
  • PHP Manual
  • SQLite Functions
  • Registers a "regular" User Defined Function for use in SQL statements

sqlite_create_function

SQLiteDatabase::createFunction

(PHP 5 < 5.4.0, sqlite >= 1.0.0)

sqlite_create_function -- SQLiteDatabase::createFunction — Registers a "regular" User Defined Function for use in SQL statements

Description

sqlite_create_function ( resource $dbhandle , string $function_name , callable $callback [, int $num_args = -1 ] ) : void

Object oriented style (method):

public SQLiteDatabase::createFunction ( string $function_name , callable $callback [, int $num_args = -1 ] ) : void

sqlite_create_function() allows you to register a PHP function with SQLite as an UDF (User Defined Function), so that it can be called from within your SQL statements.

The UDF can be used in any SQL statement that can call functions, such as SELECT and UPDATE statements and also in triggers.

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

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

num_args

Hint to the SQLite parser if the callback function accepts a predetermined number of arguments.

Note: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.

Return Values

No value is returned.

Examples

Example #1 sqlite_create_function() example

<?php
function md5_and_reverse($string)
{
    return strrev(md5($string));
}

if ($dbhandle = sqlite_open('mysqlitedb', 0666, $sqliteerror)) {

    sqlite_create_function($dbhandle, 'md5rev', 'md5_and_reverse', 1);

    $sql  = 'SELECT md5rev(filename) FROM files';
    $rows = sqlite_array_query($dbhandle, $sql);
} else {
    echo 'Error opening sqlite db: ' . $sqliteerror;
    exit;
}
?>

In this example, we have a function that calculates the md5 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 you do not need to process the result using a foreach loop after you have queried for the data.

PHP registers a special function named php when the database is first opened. The php function can be used to call any PHP function without having to register it first.

Example #2 Example of using the PHP function

<?php
$rows = sqlite_array_query($dbhandle, "SELECT php('md5', filename) from files");
?>

This example will call the md5() on each filename column in the database and return the result into $rows

Note:

For performance reasons, PHP will not automatically encode/decode binary data passed to and from your UDF's. You need to manually encode/decode the parameters and return values if you need to process binary data in this way. Take a look at sqlite_udf_encode_binary() and sqlite_udf_decode_binary() for more details.

Tip

It is not recommended to use UDF's to handle processing of binary data, unless high performance is not a key requirement of your application.

Tip

You can use sqlite_create_function() and sqlite_create_aggregate() to override SQLite native SQL functions.

See Also

  • sqlite_create_aggregate() - Register an aggregating UDF for use in SQL statements


Fetches the current row from a result set as an array

  • « sqlite_create_function
  • sqlite_error_string »
  • PHP Manual
  • SQLite Functions
  • Fetches the current row from a result set as an array

sqlite_current

SQLiteResult::current

SQLiteUnbuffered::current

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_current -- SQLiteResult::current -- SQLiteUnbuffered::current — Fetches the current row from a result set as an array

Description

sqlite_current ( resource $result [, int $result_type = SQLITE_BOTH [, bool $decode_binary = TRUE ]] ) : array

Object oriented style (method):

SQLiteResult::current ([ int $result_type = SQLITE_BOTH [, bool $decode_binary = TRUE ]] ) : array
SQLiteUnbuffered::current ([ int $result_type = SQLITE_BOTH [, bool $decode_binary = TRUE ]] ) : array

sqlite_current() is identical to sqlite_fetch_array() except that it does not advance to the next row prior to returning the data; it returns the data from the current position only.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.

decode_binary

When the decode_binary parameter is set to TRUE (the default), PHP will decode the binary encoding it applied to the data if it was encoded using the sqlite_escape_string(). You should normally leave this value at its default, unless you are interoperating with databases created by other sqlite capable applications.

Return Values

Returns an array of the current row from a result set; FALSE if the current position is beyond the final row.

The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be case-folded according to the value of the sqlite.assoc_case configuration option.

See Also

  • sqlite_seek() - Seek to a particular row number of a buffered result set
  • sqlite_next() - Seek to the next row number
  • sqlite_fetch_array() - Fetches the next row from a result set as an array


Returns the textual description of an error code

  • « sqlite_current
  • sqlite_escape_string »
  • PHP Manual
  • SQLite Functions
  • Returns the textual description of an error code

sqlite_error_string

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_error_string — Returns the textual description of an error code

Description

sqlite_error_string ( int $error_code ) : string

Returns a human readable description of the error_code returned from sqlite_last_error().

Parameters

error_code

The error code being used, which might be passed in from sqlite_last_error().

Return Values

Returns a human readable description of the error_code, as a string.

See Also

  • sqlite_last_error() - Returns the error code of the last error for a database


Escapes a string for use as a query parameter

  • « sqlite_error_string
  • sqlite_exec »
  • PHP Manual
  • SQLite Functions
  • Escapes a string for use as a query parameter

sqlite_escape_string

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_escape_string — Escapes a string for use as a query parameter

Description

sqlite_escape_string ( string $item ) : string

sqlite_escape_string() will correctly quote the string specified by item for use in an SQLite SQL statement. This includes doubling up single-quote characters (') and checking for binary-unsafe characters in the query string.

Although the encoding makes it safe to insert the data, it will render simple text comparisons and LIKE clauses in your queries unusable for the columns that contain the binary data. In practice, this shouldn't be a problem, as your schema should be such that you don't use such things on binary columns (in fact, it might be better to store binary data using other means, such as in files).

Parameters

item

The string being quoted.

If the item contains a NUL character, or if it begins with a character whose ordinal value is 0x01, PHP will apply a binary encoding scheme so that you can safely store and retrieve binary data.

Return Values

Returns an escaped string for use in an SQLite SQL statement.

Notes

Note:

    Do not use this function to encode the return values from UDF's created
    using sqlite_create_function() or
    sqlite_create_aggregate() - use
    sqlite_udf_encode_binary() instead.

Warning

addslashes() should NOT be used to quote your strings for SQLite queries; it will lead to strange results when retrieving your data.

See Also

  • sqlite_udf_encode_binary() - Encode binary data before returning it from an UDF


Executes a result-less query against a given database

  • « sqlite_escape_string
  • sqlite_factory »
  • PHP Manual
  • SQLite Functions
  • Executes a result-less query against a given database

sqlite_exec

SQLiteDatabase::exec

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.3)

sqlite_exec -- SQLiteDatabase::exec — Executes a result-less query against a given database

Description

sqlite_exec ( resource $dbhandle , string $query [, string &$error_msg ] ) : bool
sqlite_exec ( string $query , resource $dbhandle ) : bool

Object oriented style (method):

public SQLiteDatabase::queryExec ( string $query [, string &$error_msg ] ) : bool

Executes an SQL statement given by the query against a given database handle (specified by the dbhandle parameter).

Warning

SQLite will execute multiple queries separated by semicolons, so you can use it to execute a batch of SQL that you have loaded from a file or have embedded in a script.

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

query

The query to be executed.

Data inside the query should be properly escaped.

error_msg

The specified variable will be filled if an error occurs. This is specially important because SQL syntax errors can't be fetched using the sqlite_last_error() function.

Note: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.

Return Values

This function will return a boolean result; TRUE for success or FALSE for failure. If you need to run a query that returns rows, see sqlite_query().

The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be case-folded according to the value of the sqlite.assoc_case configuration option.

Changelog

Version | Description
5.1.0 | Added the error_msg parameter

Examples

Example #1 Procedural example

<?php
$dbhandle = sqlite_open('mysqlitedb');
$query = sqlite_exec($dbhandle, "UPDATE users SET email='jDoe@example.com' WHERE username='jDoe'", $error);
if (!$query) {
    exit("Error in query: '$error'");
} else {
    echo 'Number of rows modified: ', sqlite_changes($dbhandle);
}
?>

Example #2 Object-oriented example

<?php
$dbhandle = new SQLiteDatabase('mysqlitedb');
$query = $dbhandle->queryExec("UPDATE users SET email='jDoe@example.com' WHERE username='jDoe'", $error);
if (!$query) {
    exit("Error in query: '$error'");
} else {
    echo 'Number of rows modified: ', $dbhandle->changes();
}
?>

See Also

  • sqlite_query() - Executes a query against a given database and returns a result handle
  • sqlite_unbuffered_query() - Execute a query that does not prefetch and buffer all data
  • sqlite_array_query() - Execute a query against a given database and returns an array


Opens an SQLite database and returns an SQLiteDatabase object

  • « sqlite_exec
  • sqlite_fetch_all »
  • PHP Manual
  • SQLite Functions
  • Opens an SQLite database and returns an SQLiteDatabase object

sqlite_factory

(PHP 5 < 5.4.0)

sqlite_factory — Opens an SQLite database and returns an SQLiteDatabase object

Description

sqlite_factory ( string $filename [, int $mode = 0666 [, string &$error_message ]] ) : SQLiteDatabase

sqlite_factory() behaves similarly to sqlite_open() in that it opens an SQLite database or attempts to create it if it does not exist. However, a SQLiteDatabase object is returned rather than a resource. Please see the sqlite_open() reference page for further usage and caveats.

Parameters

filename

The filename of the SQLite database.

mode

The mode of the file. Intended to be used to open the database in read-only mode. Presently, this parameter is ignored by the sqlite library. The default value for mode is the octal value 0666 and this is the recommended value.

error_message

Passed by reference and is set to hold a descriptive error message explaining why the database could not be opened if there was an error.

Return Values

Returns an SQLiteDatabase object on success, NULL on error.

Examples

Example #1 sqlite_factory() example

<?php
$dbhandle = sqlite_factory('sqlitedb');
$dbhandle->query('SELECT user_id, username FROM users');

/* functionally equivalent to: */

$dbhandle = new SQLiteDatabase('sqlitedb');
$dbhandle->query('SELECT user_id, username FROM users');

?>

See Also

  • sqlite_open() - Opens an SQLite database and create the database if it does not exist
  • sqlite_popen() - Opens a persistent handle to an SQLite database and create the database if it does not exist


Fetches all rows from a result set as an array of arrays

  • « sqlite_factory
  • sqlite_fetch_array »
  • PHP Manual
  • SQLite Functions
  • Fetches all rows from a result set as an array of arrays

sqlite_fetch_all

SQLiteResult::fetchAll

SQLiteUnbuffered::fetchAll

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_fetch_all -- SQLiteResult::fetchAll -- SQLiteUnbuffered::fetchAll — Fetches all rows from a result set as an array of arrays

Description

sqlite_fetch_all ( resource $result [, int $result_type = SQLITE_BOTH [, bool $decode_binary = TRUE ]] ) : array

Object oriented style (method):

SQLiteResult::fetchAll ([ int $result_type = SQLITE_BOTH [, bool $decode_binary = TRUE ]] ) : array
SQLiteUnbuffered::fetchAll ([ int $result_type = SQLITE_BOTH [, bool $decode_binary = TRUE ]] ) : array

sqlite_fetch_all() returns an array of the entire result set from the result resource. It is similar to calling sqlite_query() (or sqlite_unbuffered_query()) and then sqlite_fetch_array() for each row in the result set.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.

decode_binary

When the decode_binary parameter is set to TRUE (the default), PHP will decode the binary encoding it applied to the data if it was encoded using the sqlite_escape_string(). You should normally leave this value at its default, unless you are interoperating with databases created by other sqlite capable applications.

Return Values

Returns an array of the remaining rows in a result set. If called right after sqlite_query(), it returns all rows. If called after sqlite_fetch_array(), it returns the rest. If there are no rows in a result set, it returns an empty array.

The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be case-folded according to the value of the sqlite.assoc_case configuration option.

Examples

Example #1 Procedural example

<?php
$dbhandle = sqlite_open('sqlitedb');
$query = sqlite_query($dbhandle, 'SELECT name, email FROM users LIMIT 25');
$result = sqlite_fetch_all($query, SQLITE_ASSOC);
foreach ($result as $entry) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?>

Example #2 Object-oriented example

<?php
$dbhandle = new SQLiteDatabase('sqlitedb');

$query = $dbhandle->query('SELECT name, email FROM users LIMIT 25'); // buffered result set
$query = $dbhandle->unbufferedQuery('SELECT name, email FROM users LIMIT 25'); // unbuffered result set

$result = $query->fetchAll(SQLITE_ASSOC);
foreach ($result as $entry) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?>

See Also

  • sqlite_fetch_array() - Fetches the next row from a result set as an array


Fetches the next row from a result set as an array

  • « sqlite_fetch_all
  • sqlite_fetch_column_types »
  • PHP Manual
  • SQLite Functions
  • Fetches the next row from a result set as an array

sqlite_fetch_array

SQLiteResult::fetch

SQLiteUnbuffered::fetch

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_fetch_array -- SQLiteResult::fetch -- SQLiteUnbuffered::fetch — Fetches the next row from a result set as an array

Description

sqlite_fetch_array ( resource $result [, int $result_type = SQLITE_BOTH [, bool $decode_binary = TRUE ]] ) : array

Object oriented style (method):

SQLiteResult::fetch ([ int $result_type = SQLITE_BOTH [, bool $decode_binary = TRUE ]] ) : array
SQLiteUnbuffered::fetch ([ int $result_type = SQLITE_BOTH [, bool $decode_binary = TRUE ]] ) : array

Fetches the next row from the given result handle. If there are no more rows, returns FALSE, otherwise returns an associative array representing the row data.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.

decode_binary

When the decode_binary parameter is set to TRUE (the default), PHP will decode the binary encoding it applied to the data if it was encoded using the sqlite_escape_string(). You should normally leave this value at its default, unless you are interoperating with databases created by other sqlite capable applications.

Return Values

Returns an array of the next row from a result set; FALSE if the next position is beyond the final row.

The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be case-folded according to the value of the sqlite.assoc_case configuration option.

Examples

Example #1 Procedural example

<?php
$dbhandle = sqlite_open('sqlitedb');
$query = sqlite_query($dbhandle, 'SELECT name, email FROM users LIMIT 25');
while ($entry = sqlite_fetch_array($query, SQLITE_ASSOC)) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?>

Example #2 Object-oriented example

<?php
$dbhandle = new SQLiteDatabase('sqlitedb');

$query = $dbhandle->query('SELECT name, email FROM users LIMIT 25'); // buffered result set
$query = $dbhandle->unbufferedQuery('SELECT name, email FROM users LIMIT 25'); // unbuffered result set

while ($entry = $query->fetch(SQLITE_ASSOC)) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?>

See Also

  • sqlite_array_query() - Execute a query against a given database and returns an array
  • sqlite_fetch_string() - Alias of sqlite_fetch_single


Return an array of column types from a particular table

  • « sqlite_fetch_array
  • sqlite_fetch_object »
  • PHP Manual
  • SQLite Functions
  • Return an array of column types from a particular table

sqlite_fetch_column_types

SQLiteDatabase::fetchColumnTypes

(PHP 5 < 5.4.0)

sqlite_fetch_column_types -- SQLiteDatabase::fetchColumnTypes — Return an array of column types from a particular table

Description

sqlite_fetch_column_types ( string $table_name , resource $dbhandle [, int $result_type = SQLITE_ASSOC ] ) : array

Object oriented style (method):

public SQLiteDatabase::fetchColumnTypes ( string $table_name [, int $result_type = SQLITE_ASSOC ] ) : array

sqlite_fetch_column_types() returns an array of column data types from the specified table_name table.

Parameters

table_name

The table name to query.

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_ASSOC is the default for this function.

Return Values

Returns an array of column data types; FALSE on error.

The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be case-folded according to the value of the sqlite.assoc_case configuration option.

Changelog

Version | Description
5.1.0 | Added result_type

Examples

Example #1 Procedural example

<?php
$db = sqlite_open('mysqlitedb');
sqlite_query($db, 'CREATE TABLE foo (bar varchar(10), arf text)');
$cols = sqlite_fetch_column_types('foo', $db, SQLITE_ASSOC);

foreach ($cols as $column => $type) {
    echo "Column: $column  Type: $type\n";
}
?>

Example #2 Object-oriented example

<?php
$db = new SQLiteDatabase('mysqlitedb');
$db->query('CREATE TABLE foo (bar varchar(10), arf text)');
$cols = $db->fetchColumnTypes('foo', SQLITE_ASSOC);

foreach ($cols as $column => $type) {
    echo "Column: $column  Type: $type\n";
}
?>

The above example will output:

Column: bar  Type: VARCHAR
Column: arf  Type: TEXT


Fetches the next row from a result set as an object

  • « sqlite_fetch_column_types
  • sqlite_fetch_single »
  • PHP Manual
  • SQLite Functions
  • Fetches the next row from a result set as an object

sqlite_fetch_object

SQLiteResult::fetchObject

SQLiteUnbuffered::fetchObject

(PHP 5 < 5.4.0)

sqlite_fetch_object -- SQLiteResult::fetchObject -- SQLiteUnbuffered::fetchObject — Fetches the next row from a result set as an object

Description

sqlite_fetch_object ( resource $result [, string $class_name [, array $ctor_params [, bool $decode_binary = TRUE ]]] ) : object

Object oriented style (method):

SQLiteResult::fetchObject ([ string $class_name [, array $ctor_params [, bool $decode_binary = TRUE ]]] ) : object
SQLiteUnbuffered::fetchObject ([ string $class_name [, array $ctor_params [, bool $decode_binary = TRUE ]]] ) : object
Warning

This function is currently not documented; only its argument list is available.


Fetches the first column of a result set as a string

  • « sqlite_fetch_object
  • sqlite_fetch_string »
  • PHP Manual
  • SQLite Functions
  • Fetches the first column of a result set as a string

sqlite_fetch_single

SQLiteResult::fetchSingle

SQLiteUnbuffered::fetchSingle

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.1)

sqlite_fetch_single -- SQLiteResult::fetchSingle -- SQLiteUnbuffered::fetchSingle — Fetches the first column of a result set as a string

Description

sqlite_fetch_single ( resource $result [, bool $decode_binary = TRUE ] ) : string

Object oriented style (method):

SQLiteResult::fetchSingle ([ bool $decode_binary = TRUE ] ) : string
SQLiteUnbuffered::fetchSingle ([ bool $decode_binary = TRUE ] ) : string

sqlite_fetch_single() is identical to sqlite_fetch_array() except that it returns the value of the first column of the rowset.

This is the most optimal way to retrieve data when you are only interested in the values from a single column of data.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

decode_binary

When the decode_binary parameter is set to TRUE (the default), PHP will decode the binary encoding it applied to the data if it was encoded using the sqlite_escape_string(). You should normally leave this value at its default, unless you are interoperating with databases created by other sqlite capable applications.

Return Values

Returns the first column value, as a string.

Examples

Example #1 A sqlite_fetch_single() example

<?php
if ($dbhandle = sqlite_open('mysqlitedb', 0666, $sqliteerror)) {

    $sql = "SELECT id FROM sometable WHERE id = 42";
    $res = sqlite_query($dbhandle, $sql);

    if (sqlite_num_rows($res) > 0) {
        echo sqlite_fetch_single($res); // 42
    }

    sqlite_close($dbhandle);
}
?>

See Also

  • sqlite_fetch_array() - Fetches the next row from a result set as an array


Alias of sqlite_fetch_single

  • « sqlite_fetch_single
  • sqlite_field_name »
  • PHP Manual
  • SQLite Functions
  • Alias of sqlite_fetch_single

sqlite_fetch_string

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_fetch_string — Alias of sqlite_fetch_single()

Description

This function is an alias of: sqlite_fetch_single().


Returns the name of a particular field

  • « sqlite_fetch_string
  • sqlite_has_more »
  • PHP Manual
  • SQLite Functions
  • Returns the name of a particular field

sqlite_field_name

SQLiteResult::fieldName

SQLiteUnbuffered::fieldName

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_field_name -- SQLiteResult::fieldName -- SQLiteUnbuffered::fieldName — Returns the name of a particular field

Description

sqlite_field_name ( resource $result , int $field_index ) : string

Object oriented style (method):

SQLiteResult::fieldName ( int $field_index ) : string
SQLiteUnbuffered::fieldName ( int $field_index ) : string

Given the ordinal column number, field_index, sqlite_field_name() returns the name of that field in the result set result.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

field_index

The ordinal column number in the result set.

Return Values

Returns the name of a field in an SQLite result set, given the ordinal column number; FALSE on error.

The column names returned by SQLITE_ASSOC and SQLITE_BOTH will be case-folded according to the value of the sqlite.assoc_case configuration option.


Finds whether or not more rows are available

  • « sqlite_field_name
  • sqlite_has_prev »
  • PHP Manual
  • SQLite Functions
  • Finds whether or not more rows are available

sqlite_has_more

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_has_more — Finds whether or not more rows are available

Description

sqlite_has_more ( resource $result ) : bool

Finds whether more rows are available from the given result set.

Parameters

result

The SQLite result resource.

Return Values

Returns TRUE if there are more rows available from the result handle, or FALSE otherwise.

See Also

  • sqlite_num_rows() - Returns the number of rows in a buffered result set
  • sqlite_changes() - Returns the number of rows that were changed by the most recent SQL statement


Returns whether or not a previous row is available

  • « sqlite_has_more
  • sqlite_key »
  • PHP Manual
  • SQLite Functions
  • Returns whether or not a previous row is available

sqlite_has_prev

SQLiteResult::hasPrev

(PHP 5 < 5.4.0)

sqlite_has_prev -- SQLiteResult::hasPrev — Returns whether or not a previous row is available

Description

sqlite_has_prev ( resource $result ) : bool

Object oriented style (method):

SQLiteResult::hasPrev ( void ) : bool

Find whether there are more previous rows from the given result handle.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Note:

This function cannot be used with unbuffered result handles.

Return Values

Returns TRUE if there are more previous rows available from the result handle, or FALSE otherwise.

See Also

  • sqlite_prev() - Seek to the previous row number of a result set
  • sqlite_has_more() - Finds whether or not more rows are available
  • sqlite_num_rows() - Returns the number of rows in a buffered result set


Returns the current row index

  • « sqlite_has_prev
  • sqlite_last_error »
  • PHP Manual
  • SQLite Functions
  • Returns the current row index

sqlite_key

SQLiteResult::key

(PHP 5 >= 5.1.0 < 5.4.0)

sqlite_key -- SQLiteResult::key — Returns the current row index

Description

Object oriented style (method):

SQLiteResult::key ( void ) : int

SQLiteResult::key() returns the current row index of the buffered result set result.

Unlike all other SQLite functions, this function does not have a procedural version, and can only be called as a method on a SQLiteResult object.

Return Values

Returns the current row index of the buffered result set result.

See Also

  • sqlite_next() - Seek to the next row number
  • sqlite_current() - Fetches the current row from a result set as an array
  • sqlite_rewind() - Seek to the first row number


Returns the error code of the last error for a database

  • « sqlite_key
  • sqlite_last_insert_rowid »
  • PHP Manual
  • SQLite Functions
  • Returns the error code of the last error for a database

sqlite_last_error

SQLiteDatabase::lastError

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_last_error -- SQLiteDatabase::lastError — Returns the error code of the last error for a database

Description

sqlite_last_error ( resource $dbhandle ) : int

Object oriented style (method):

public SQLiteDatabase::lastError ( void ) : int

Returns the error code from the last operation performed on dbhandle (the database handle), or 0 when no error occurred. A human readable description of the error code can be retrieved using sqlite_error_string().

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

Return Values

Returns an error code, or 0 if no error occurred.

See Also

  • sqlite_error_string() - Returns the textual description of an error code


Returns the rowid of the most recently inserted row

  • « sqlite_last_error
  • sqlite_libencoding »
  • PHP Manual
  • SQLite Functions
  • Returns the rowid of the most recently inserted row

sqlite_last_insert_rowid

SQLiteDatabase::lastInsertRowid

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_last_insert_rowid -- SQLiteDatabase::lastInsertRowid — Returns the rowid of the most recently inserted row

Description

sqlite_last_insert_rowid ( resource $dbhandle ) : int

Object oriented style (method):

public SQLiteDatabase::lastInsertRowid ( void ) : int

Returns the rowid of the row that was most recently inserted into the database dbhandle, if it was created as an auto-increment field.

Tip

You can create auto-increment fields in SQLite by declaring them as INTEGER PRIMARY KEY in your table schema.

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

Return Values

Returns the row id, as an integer.


Returns the encoding of the linked SQLite library

  • « sqlite_last_insert_rowid
  • sqlite_libversion »
  • PHP Manual
  • SQLite Functions
  • Returns the encoding of the linked SQLite library

sqlite_libencoding

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_libencoding — Returns the encoding of the linked SQLite library

Description

sqlite_libencoding ( void ) : string

The SQLite library may be compiled in either ISO-8859-1 or UTF-8 compatible modes. This function allows you to determine which encoding scheme is used by your version of the library.

Warning

The default PHP distribution builds libsqlite in ISO-8859-1 encoding mode. However, this is a misnomer; rather than handling ISO-8859-1, it operates according to your current locale settings for string comparisons and sort ordering. So, rather than ISO-8859-1, you should think of it as being '8-bit' instead.

When compiled with UTF-8 support, sqlite handles encoding and decoding of UTF-8 multi-byte character sequences, but does not yet do a complete job when working with the data (no normalization is performed for example), and some comparison operations may still not be carried out correctly.

Warning

It is not recommended that you use PHP in a web-server configuration with a version of the SQLite library compiled with UTF-8 support, since libsqlite will abort the process if it detects a problem with the UTF-8 encoding.

Return Values

Returns the library encoding.

See Also

  • sqlite_libversion() - Returns the version of the linked SQLite library


Returns the version of the linked SQLite library

  • « sqlite_libencoding
  • sqlite_next »
  • PHP Manual
  • SQLite Functions
  • Returns the version of the linked SQLite library

sqlite_libversion

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_libversion — Returns the version of the linked SQLite library

Description

sqlite_libversion ( void ) : string

Returns the version of the linked SQLite library.

Return Values

Returns the library version, as a string.

See Also

  • sqlite_libencoding() - Returns the encoding of the linked SQLite library


Seek to the next row number

  • « sqlite_libversion
  • sqlite_num_fields »
  • PHP Manual
  • SQLite Functions
  • Seek to the next row number

sqlite_next

SQLiteResult::next

SQLiteUnbuffered::next

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_next -- SQLiteResult::next -- SQLiteUnbuffered::next — Seek to the next row number

Description

sqlite_next ( resource $result ) : bool

Object oriented style (method):

SQLiteResult::next ( void ) : bool
SQLiteUnbuffered::next ( void ) : bool

sqlite_next() advances the result handle result to the next row.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Return Values

Returns TRUE on success, or FALSE if there are no more rows.

See Also

  • sqlite_seek() - Seek to a particular row number of a buffered result set
  • sqlite_current() - Fetches the current row from a result set as an array
  • sqlite_rewind() - Seek to the first row number


Returns the number of fields in a result set

  • « sqlite_next
  • sqlite_num_rows »
  • PHP Manual
  • SQLite Functions
  • Returns the number of fields in a result set

sqlite_num_fields

SQLiteResult::numFields

SQLiteUnbuffered::numFields

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_num_fields -- SQLiteResult::numFields -- SQLiteUnbuffered::numFields — Returns the number of fields in a result set

Description

sqlite_num_fields ( resource $result ) : int

Object oriented style (method):

SQLiteResult::numFields ( void ) : int
SQLiteUnbuffered::numFields ( void ) : int

Returns the number of fields in the result set.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Return Values

Returns the number of fields, as an integer.

See Also

  • sqlite_changes() - Returns the number of rows that were changed by the most recent SQL statement
  • sqlite_num_rows() - Returns the number of rows in a buffered result set


Returns the number of rows in a buffered result set

  • « sqlite_num_fields
  • sqlite_open »
  • PHP Manual
  • SQLite Functions
  • Returns the number of rows in a buffered result set

sqlite_num_rows

SQLiteResult::numRows

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_num_rows -- SQLiteResult::numRows — Returns the number of rows in a buffered result set

Description

sqlite_num_rows ( resource $result ) : int

Object oriented style (method):

SQLiteResult::numRows ( void ) : int

Returns the number of rows in the buffered result set.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Note:

This function cannot be used with unbuffered result handles.

Return Values

Returns the number of rows, as an integer.

Examples

Example #1 Procedural example

<?php
$db = sqlite_open('mysqlitedb');
$result = sqlite_query($db, "SELECT * FROM mytable WHERE name='John Doe'");
$rows = sqlite_num_rows($result);

echo "Number of rows: $rows";
?>

Example #2 Object-oriented example

<?php
$db = new SQLiteDatabase('mysqlitedb');
$result = $db->query("SELECT * FROM mytable WHERE name='John Doe'");
$rows = $result->numRows();

echo "Number of rows: $rows";
?>

See Also

  • sqlite_changes() - Returns the number of rows that were changed by the most recent SQL statement
  • sqlite_query() - Executes a query against a given database and returns a result handle
  • sqlite_num_fields() - Returns the number of fields in a result set


Opens an SQLite database and create the database if it does not exist

  • « sqlite_num_rows
  • sqlite_popen »
  • PHP Manual
  • SQLite Functions
  • Opens an SQLite database and create the database if it does not exist

sqlite_open

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_open — Opens an SQLite database and create the database if it does not exist

Description

sqlite_open ( string $filename [, int $mode = 0666 [, string &$error_message ]] ) : resource

Object oriented style (constructor):

final public SQLiteDatabase::__construct ( string $filename [, int $mode = 0666 [, string &$error_message ]] )

Opens an SQLite database or creates the database if it does not exist.

Parameters

filename

The filename of the SQLite database. If the file does not exist, SQLite will attempt to create it. PHP must have write permissions to the file if data is inserted, the database schema is modified or to create the database if it does not exist.

mode

The mode of the file. Intended to be used to open the database in read-only mode. Presently, this parameter is ignored by the sqlite library. The default value for mode is the octal value 0666 and this is the recommended value.

error_message

Passed by reference and is set to hold a descriptive error message explaining why the database could not be opened if there was an error.

Return Values

Returns a resource (database handle) on success, FALSE on error.

Examples

Example #1 sqlite_open() example

<?php
if ($db = sqlite_open('mysqlitedb', 0666, $sqliteerror)) {
    sqlite_query($db, 'CREATE TABLE foo (bar varchar(10))');
    sqlite_query($db, "INSERT INTO foo VALUES ('fnord')");
    $result = sqlite_query($db, 'select bar from foo');
    var_dump(sqlite_fetch_array($result));
} else {
    die($sqliteerror);
}
?>

Notes

Tip

On Unix platforms, SQLite is sensitive to scripts that use the fork() system call. If you do have such a script, it is recommended that you close the handle prior to forking and then re-open it in the child and/or parent. For more information on this issue, see » The C language interface to the SQLite library in the section entitled Multi-Threading And SQLite.

Tip

It is not recommended to work with SQLite databases mounted on NFS partitions. Since NFS is notoriously bad when it comes to locking you may find that you cannot even open the database at all, and if it succeeds, the locking behaviour may be undefined.

Note: Starting with SQLite library version 2.8.2, you can specify :memory: as the filename to create a database that lives only in the memory of the computer. This is useful mostly for temporary processing, as the in-memory database will be destroyed when the process ends. It can also be useful when coupled with the ATTACH DATABASE SQL statement to load other databases and move and query data between them.

Note: SQLite is safe mode and open_basedir aware.

See Also

  • sqlite_popen() - Opens a persistent handle to an SQLite database and create the database if it does not exist
  • sqlite_close() - Closes an open SQLite database
  • sqlite_factory() - Opens an SQLite database and returns an SQLiteDatabase object


Opens a persistent handle to an SQLite database and create the database if it does not exist

  • « sqlite_open
  • sqlite_prev »
  • PHP Manual
  • SQLite Functions
  • Opens a persistent handle to an SQLite database and create the database if it does not exist

sqlite_popen

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_popen — Opens a persistent handle to an SQLite database and create the database if it does not exist

Description

sqlite_popen ( string $filename [, int $mode = 0666 [, string &$error_message ]] ) : resource

This function behaves identically to sqlite_open() except that is uses the persistent resource mechanism of PHP. For information about the meaning of the parameters, read the sqlite_open() manual page.

sqlite_popen() will first check to see if a persistent handle has already been opened for the given filename. If it finds one, it returns that handle to your script, otherwise it opens a fresh handle to the database.

The benefit of this approach is that you don't incur the performance cost of re-reading the database and index schema on each page hit served by persistent web server SAPI's (any SAPI except for regular CGI or CLI).

Note: If you use persistent handles and have the database updated by a background process (perhaps via a crontab), and that process re-creates the database by overwriting it (either by unlinking and rebuilding, or moving the updated version to replace the current version), you may experience undefined behaviour when a persistent handle on the old version of the database is recycled. To avoid this situation, have your background processes open the same database file and perform their updates in a transaction.

Parameters

filename

The filename of the SQLite database. If the file does not exist, SQLite will attempt to create it. PHP must have write permissions to the file if data is inserted, the database schema is modified or to create the database if it does not exist.

mode

The mode of the file. Intended to be used to open the database in read-only mode. Presently, this parameter is ignored by the sqlite library. The default value for mode is the octal value 0666 and this is the recommended value.

error_message

Passed by reference and is set to hold a descriptive error message explaining why the database could not be opened if there was an error.

Return Values

Returns a resource (database handle) on success, FALSE on error.

See Also

  • sqlite_open() - Opens an SQLite database and create the database if it does not exist
  • sqlite_close() - Closes an open SQLite database
  • sqlite_factory() - Opens an SQLite database and returns an SQLiteDatabase object


Seek to the previous row number of a result set

  • « sqlite_popen
  • sqlite_query »
  • PHP Manual
  • SQLite Functions
  • Seek to the previous row number of a result set

sqlite_prev

SQLiteResult::prev

(PHP 5 < 5.4.0)

sqlite_prev -- SQLiteResult::prev — Seek to the previous row number of a result set

Description

sqlite_prev ( resource $result ) : bool

Object oriented style (method):

SQLiteResult::prev ( void ) : bool

sqlite_prev() seeks back the result handle to the previous row.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Note:

This function cannot be used with unbuffered result handles.

Return Values

Returns TRUE on success, or FALSE if there are no more previous rows.

See Also

  • sqlite_has_prev() - Returns whether or not a previous row is available
  • sqlite_rewind() - Seek to the first row number
  • sqlite_next() - Seek to the next row number


Executes a query against a given database and returns a result handle

  • « sqlite_prev
  • sqlite_rewind »
  • PHP Manual
  • SQLite Functions
  • Executes a query against a given database and returns a result handle

sqlite_query

SQLiteDatabase::query

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_query -- SQLiteDatabase::query — Executes a query against a given database and returns a result handle

Description

sqlite_query ( resource $dbhandle , string $query [, int $result_type = SQLITE_BOTH [, string &$error_msg ]] ) : resource
sqlite_query ( string $query , resource $dbhandle [, int $result_type = SQLITE_BOTH [, string &$error_msg ]] ) : resource

Object oriented style (method):

public SQLiteDatabase::query ( string $query [, int $result_type = SQLITE_BOTH [, string &$error_msg ]] ) : SQLiteResult

Executes an SQL statement given by the query against a given database handle.

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

query

The query to be executed.

Data inside the query should be properly escaped.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.

error_msg

The specified variable will be filled if an error occurs. This is specially important because SQL syntax errors can't be fetched using the sqlite_last_error() function.

Note: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.

Return Values

This function will return a result handle or FALSE on failure. For queries that return rows, the result handle can then be used with functions such as sqlite_fetch_array() and sqlite_seek().

Regardless of the query type, this function will return FALSE if the query failed.

sqlite_query() returns a buffered, seekable result handle. This is useful for reasonably small queries where you need to be able to randomly access the rows. Buffered result handles will allocate memory to hold the entire result and will not return until it has been fetched. If you only need sequential access to the data, it is recommended that you use the much higher performance sqlite_unbuffered_query() instead.

Changelog

Version | Description
5.1.0 | Added the error_msg parameter

Notes

Warning

SQLite will execute multiple queries separated by semicolons, so you can use it to execute a batch of SQL that you have loaded from a file or have embedded in a script. However, this works only when the result of the function is not used - if it is used, only the first SQL statement would be executed. Function sqlite_exec() will always execute multiple SQL statements.

When executing multiple queries, the return value of this function will be FALSE if there was an error, but undefined otherwise (it might be TRUE for success or it might return a result handle).

See Also

  • sqlite_unbuffered_query() - Execute a query that does not prefetch and buffer all data
  • sqlite_array_query() - Execute a query against a given database and returns an array


Seek to the first row number

  • « sqlite_query
  • sqlite_seek »
  • PHP Manual
  • SQLite Functions
  • Seek to the first row number

sqlite_rewind

SQLiteResult::rewind

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_rewind -- SQLiteResult::rewind — Seek to the first row number

Description

sqlite_rewind ( resource $result ) : bool

Object oriented style (method):

SQLiteResult::rewind ( void ) : bool

sqlite_rewind() seeks back to the first row in the given result set.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Note:

This function cannot be used with unbuffered result handles.

Return Values

Returns FALSE if there are no rows in the result set, TRUE otherwise.

See Also

  • sqlite_next() - Seek to the next row number
  • sqlite_current() - Fetches the current row from a result set as an array
  • sqlite_seek() - Seek to a particular row number of a buffered result set


Seek to a particular row number of a buffered result set

  • « sqlite_rewind
  • sqlite_single_query »
  • PHP Manual
  • SQLite Functions
  • Seek to a particular row number of a buffered result set

sqlite_seek

SQLiteResult::seek

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_seek -- SQLiteResult::seek — Seek to a particular row number of a buffered result set

Description

sqlite_seek ( resource $result , int $rownum ) : bool

Object oriented style (method):

SQLiteResult::seek ( int $rownum ) : bool

sqlite_seek() seeks to the row given by the parameter rownum.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Note:

This function cannot be used with unbuffered result handles.

rownum

The ordinal row number to seek to. The row number is zero-based (0 is the first row).

Note:

This function cannot be used with unbuffered result handles.

Return Values

Returns FALSE if the row does not exist, TRUE otherwise.

See Also

  • sqlite_next() - Seek to the next row number
  • sqlite_current() - Fetches the current row from a result set as an array
  • sqlite_rewind() - Seek to the first row number


Executes a query and returns either an array for one single column or the value of the first row

  • « sqlite_seek
  • sqlite_udf_decode_binary »
  • PHP Manual
  • SQLite Functions
  • Executes a query and returns either an array for one single column or the value of the first row

sqlite_single_query

SQLiteDatabase::singleQuery

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.1)

sqlite_single_query -- SQLiteDatabase::singleQuery — Executes a query and returns either an array for one single column or the value of the first row

Description

sqlite_single_query ( resource $db , string $query [, bool $first_row_only [, bool $decode_binary ]] ) : array

Object oriented style (method):

public SQLiteDatabase::singleQuery ( string $query [, bool $first_row_only [, bool $decode_binary ]] ) : array
Warning

This function is currently not documented; only its argument list is available.


Decode binary data passed as parameters to an UDF

  • « sqlite_single_query
  • sqlite_udf_encode_binary »
  • PHP Manual
  • SQLite Functions
  • Decode binary data passed as parameters to an UDF

sqlite_udf_decode_binary

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_udf_decode_binary — Decode binary data passed as parameters to an UDF

Description

sqlite_udf_decode_binary ( string $data ) : string

Decodes binary data passed as parameters to a UDF.

You must call this function on parameters passed to your UDF if you need them to handle binary data, as the binary encoding employed by PHP will obscure the content and of the parameter in its natural, non-coded form.

PHP does not perform this encode/decode operation automatically as it would severely impact performance if it did.

Parameters

data

The encoded data that will be decoded, data that was applied by either sqlite_udf_encode_binary() or sqlite_escape_string().

Return Values

The decoded string.

Examples

Example #1 binary-safe max_length aggregation function example

<?php
$data = array(
   'one',
   'two',
   'three',
   'four',
   'five',
   'six',
   'seven',
   'eight',
   'nine',
   'ten',
   );
$db = sqlite_open(':memory:');
sqlite_query($db, "CREATE TABLE strings(a)");
foreach ($data as $str) {
    $str = sqlite_escape_string($str);
    sqlite_query($db, "INSERT INTO strings VALUES ('$str')");
}

function max_len_step(&$context, $string)
{
    $string = sqlite_udf_decode_binary($string);
    if (strlen($string) > $context) {
        $context = strlen($string);
    }
}

function max_len_finalize(&$context)
{
    return $context;
}

sqlite_create_aggregate($db, 'max_len', 'max_len_step', 'max_len_finalize');

var_dump(sqlite_array_query($db, 'SELECT max_len(a) from strings'));

?>

See Also

  • sqlite_udf_encode_binary() - Encode binary data before returning it from an UDF
  • sqlite_create_function() - Registers a "regular" User Defined Function for use in SQL statements
  • sqlite_create_aggregate() - Register an aggregating UDF for use in SQL statements


Encode binary data before returning it from an UDF

  • « sqlite_udf_decode_binary
  • sqlite_unbuffered_query »
  • PHP Manual
  • SQLite Functions
  • Encode binary data before returning it from an UDF

sqlite_udf_encode_binary

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_udf_encode_binary — Encode binary data before returning it from an UDF

Description

sqlite_udf_encode_binary ( string $data ) : string

sqlite_udf_encode_binary() applies a binary encoding to the data so that it can be safely returned from queries (since the underlying libsqlite API is not binary safe).

If there is a chance that your data might be binary unsafe (e.g.: it contains a NUL byte in the middle rather than at the end, or if it has and 0x01 byte as the first character) then you must call this function to encode the return value from your UDF.

PHP does not perform this encode/decode operation automatically as it would severely impact performance if it did.

Note:

Do not use sqlite_escape_string() to quote strings returned from UDF's as it will lead to double-quoting of the data. Use sqlite_udf_encode_binary() instead!

Parameters

data

The string being encoded.

Return Values

The encoded string.

See Also

  • sqlite_udf_decode_binary() - Decode binary data passed as parameters to an UDF
  • sqlite_escape_string() - Escapes a string for use as a query parameter
  • sqlite_create_function() - Registers a "regular" User Defined Function for use in SQL statements
  • sqlite_create_aggregate() - Register an aggregating UDF for use in SQL statements


Execute a query that does not prefetch and buffer all data

  • « sqlite_udf_encode_binary
  • sqlite_valid »
  • PHP Manual
  • SQLite Functions
  • Execute a query that does not prefetch and buffer all data

sqlite_unbuffered_query

SQLiteDatabase::unbufferedQuery

(PHP 5 < 5.4.0, PECL sqlite >= 1.0.0)

sqlite_unbuffered_query -- SQLiteDatabase::unbufferedQuery — Execute a query that does not prefetch and buffer all data

Description

sqlite_unbuffered_query ( resource $dbhandle , string $query [, int $result_type = SQLITE_BOTH [, string &$error_msg ]] ) : resource
sqlite_unbuffered_query ( string $query , resource $dbhandle [, int $result_type = SQLITE_BOTH [, string &$error_msg ]] ) : resource

Object oriented style (method):

public SQLiteDatabase::unbufferedQuery ( string $query [, int $result_type = SQLITE_BOTH [, string &$error_msg ]] ) : SQLiteUnbuffered

sqlite_unbuffered_query() is identical to sqlite_query() except that the result that is returned is a sequential forward-only result set that can only be used to read each row, one after the other.

This function is ideal for generating things such as HTML tables where you only need to process one row at a time and don't need to randomly access the row data.

Note:

Functions such as sqlite_seek(),
sqlite_rewind(), sqlite_next(),
sqlite_current(), and
sqlite_num_rows() do not work on result handles
returned from sqlite_unbuffered_query().

Parameters

dbhandle

The SQLite Database resource; returned from sqlite_open() when used procedurally. This parameter is not required when using the object-oriented method.

query

The query to be executed.

Data inside the query should be properly escaped.

result_type

The optional result_type parameter accepts a constant and determines how the returned array will be indexed. Using SQLITE_ASSOC will return only associative indices (named fields) while SQLITE_NUM will return only numerical indices (ordinal field numbers). SQLITE_BOTH will return both associative and numerical indices. SQLITE_BOTH is the default for this function.

error_msg

The specified variable will be filled if an error occurs. This is specially important because SQL syntax errors can't be fetched using the sqlite_last_error() function.

Note: Two alternative syntaxes are supported for compatibility with other database extensions (such as MySQL). The preferred form is the first, where the dbhandle parameter is the first parameter to the function.

Return Values

Returns a result handle or FALSE on failure.

sqlite_unbuffered_query() returns a sequential forward-only result set that can only be used to read each row, one after the other.

Changelog

Version | Description
5.1.0 | Added the error_msg parameter

See Also

  • sqlite_query() - Executes a query against a given database and returns a result handle


Returns whether more rows are available

  • « sqlite_unbuffered_query
  • SQLite3 »
  • PHP Manual
  • SQLite Functions
  • Returns whether more rows are available

sqlite_valid

SQLiteResult::valid

SQLiteUnbuffered::valid

(PHP 5 < 5.4.0)

sqlite_valid -- SQLiteResult::valid -- SQLiteUnbuffered::valid — Returns whether more rows are available

Description

sqlite_valid ( resource $result ) : bool

Object oriented style (method):

SQLiteResult::valid ( void ) : bool
SQLiteUnbuffered::valid ( void ) : bool

Finds whether more rows are available from the given result handle.

Parameters

result

The SQLite result resource. This parameter is not required when using the object-oriented method.

Note:

This function cannot be used with unbuffered result handles.

Return Values

Returns TRUE if there are more rows available from the result handle, or FALSE otherwise.

See Also

  • sqlite_num_rows() - Returns the number of rows in a buffered result set
  • sqlite_changes() - Returns the number of rows that were changed by the most recent SQL statement


SQLite3

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • SQLite3 — The SQLite3 class
    • 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::version — Returns the SQLite3 library version as a string constant and as a number
  • 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::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::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


  • « SQLite3
  • Installing/Configuring »
  • PHP Manual
  • SQLite3
  • Introduction

Introduction

Support for SQLite version 3 databases.


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 as of PHP 5.3.0. 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 as of PHP 5.3.0.

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.

Note:

This extension was briefly a PECL extension but that version is only recommended for experimental use.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

SQLite3 Configure Options
Name | Default | Changeable | Changelog
sqlite3.extension_dir | "" | PHP_INI_SYSTEM | Available as of PHP 5.3.11.
sqlite3.defensive | 1 | PHP_INI_SYSTEM | Available as of PHP 7.2.17 and 7.3.4 for libsqlite ≥ 3.26.0.

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 (integer)
Specifies that the Sqlite3Result::fetchArray() method shall return an array indexed by column name as returned in the corresponding result set.
SQLITE3_NUM (integer)
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 (integer)
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 (integer)
Represents the SQLite3 INTEGER storage class.
SQLITE3_FLOAT (integer)
Represents the SQLite3 REAL (FLOAT) storage class.
SQLITE3_TEXT (integer)
Represents the SQLite3 TEXT storage class.
SQLITE3_BLOB (integer)
Represents the SQLite3 BLOB storage class.
SQLITE3_NULL (integer)
Represents the SQLite3 NULL storage class.
SQLITE3_OPEN_READONLY (integer)
Specifies that the SQLite3 database be opened for reading only.
SQLITE3_OPEN_READWRITE (integer)
Specifies that the SQLite3 database be opened for reading and writing.
SQLITE3_OPEN_CREATE (integer)
Specifies that the SQLite3 database be created if it does not already exist.
SQLITE3_DETERMINISTIC (integer)
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)

Introduction

A class that interfaces SQLite 3 databases.

Class synopsis

SQLite3 {
/* Methods */
public busyTimeout ( int $msecs ) : bool
public changes ( void ) : int
public close ( void ) : bool
public __construct ( string $filename [, int $flags = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE [, string $encryption_key = "" ]] )
public createAggregate ( string $name , mixed $step_callback , mixed $final_callback [, int $argument_count = -1 ] ) : bool
public createCollation ( string $name , callable $callback ) : bool
public createFunction ( string $name , mixed $callback [, int $argument_count = -1 [, int $flags = 0 ]] ) : bool
enableExceptions ([ bool $enableExceptions = FALSE ] ) : bool
public static escapeString ( string $value ) : string
public exec ( string $query ) : bool
public lastErrorCode ( void ) : int
public lastErrorMsg ( void ) : string
public lastInsertRowID ( void ) : int
public loadExtension ( string $shared_library ) : bool
public open ( string $filename [, int $flags = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE [, string $encryption_key = "" ]] ) : void
public openBlob ( string $table , string $column , int $rowid [, string $dbname = "main" [, int $flags = SQLITE3_OPEN_READONLY ]] ) : resource
public prepare ( string $query ) : SQLite3Stmt
public query ( string $query ) : SQLite3Result
public querySingle ( string $query [, bool $entire_row = FALSE ] ) : mixed
public static version ( void ) : array
}

Table of Contents

  • 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::version — Returns the SQLite3 library version as a string constant and as a number


Sets the busy connection handler

  • « SQLite3
  • SQLite3::changes »
  • PHP Manual
  • SQLite3
  • Sets the busy connection handler

SQLite3::busyTimeout

(PHP 5 >= 5.3.3, PHP 7)

SQLite3::busyTimeout — Sets the busy connection handler

Description

public SQLite3::busyTimeout ( int $msecs ) : bool

Sets a busy handler that will sleep until the database is not locked or the timeout is reached.

Parameters

msecs

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.


Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement

  • « SQLite3::busyTimeout
  • SQLite3::close »
  • PHP Manual
  • SQLite3
  • Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement

SQLite3::changes

(PHP 5 >= 5.3.0, PHP 7)

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 ( void ) : 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 integer 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();
}
?>


Closes the database connection

  • « SQLite3::changes
  • SQLite3::__construct »
  • PHP Manual
  • SQLite3
  • Closes the database connection

SQLite3::close

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::close — Closes the database connection

Description

public SQLite3::close ( void ) : 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();
?>


Instantiates an SQLite3 object and opens an SQLite 3 database

  • « SQLite3::close
  • SQLite3::createAggregate »
  • PHP Manual
  • SQLite3
  • Instantiates an SQLite3 object and opens an SQLite 3 database

SQLite3::__construct

(PHP 5 >= 5.3.0, PHP 7)

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 $encryption_key = "" ]] )

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.

encryption_key

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

Returns an SQLite3 object on success.

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 STRING)');
$db->exec("INSERT INTO foo (bar) VALUES ('This is a test')");

$result = $db->query('SELECT bar FROM foo');
var_dump($result->fetchArray());
?>


Registers a PHP function for use as an SQL aggregate function

  • « SQLite3::__construct
  • SQLite3::createCollation »
  • PHP Manual
  • SQLite3
  • Registers a PHP function for use as an SQL aggregate function

SQLite3::createAggregate

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::createAggregate — Registers a PHP function for use as an SQL aggregate function

Description

public SQLite3::createAggregate ( string $name , mixed $step_callback , mixed $final_callback [, int $argument_count = -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.

step_callback

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 $value1 [, mixed $... ] ) : 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.

value1

The first argument passed to the aggregate.

...

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.

final_callback

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.

argument_count

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.


Registers a PHP function for use as an SQL collating function

  • « SQLite3::createAggregate
  • SQLite3::createFunction »
  • PHP Manual
  • SQLite3
  • Registers a PHP function for use as an SQL collating function

SQLite3::createCollation

(PHP 5 >= 5.3.11, PHP 7)

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


Registers a PHP function for use as an SQL scalar function

  • « SQLite3::createCollation
  • SQLite3::enableExceptions »
  • PHP Manual
  • SQLite3
  • Registers a PHP function for use as an SQL scalar function

SQLite3::createFunction

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::createFunction — Registers a PHP function for use as an SQL scalar function

Description

public SQLite3::createFunction ( string $name , mixed $callback [, int $argument_count = -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 $value1 [, mixed $... ] ) : mixed
value1

The first argument passed to the SQL function.

...

Further arguments passed to the SQL function.

argument_count

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


Enable throwing exceptions

  • « SQLite3::createFunction
  • SQLite3::escapeString »
  • PHP Manual
  • SQLite3
  • Enable throwing exceptions

SQLite3::enableExceptions

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::enableExceptions — Enable throwing exceptions

Description

SQLite3::enableExceptions ([ bool $enableExceptions = 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.

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


Returns a string that has been properly escaped

  • « SQLite3::enableExceptions
  • SQLite3::exec »
  • PHP Manual
  • SQLite3
  • Returns a string that has been properly escaped

SQLite3::escapeString

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::escapeString — Returns a string that has been properly escaped

Description

public static SQLite3::escapeString ( string $value ) : 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

value

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.


Executes a result-less query against a given database

  • « SQLite3::escapeString
  • SQLite3::lastErrorCode »
  • PHP Manual
  • SQLite3
  • Executes a result-less query against a given database

SQLite3::exec

(PHP 5 >= 5.3.0, PHP 7)

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 STRING)');
?>


Returns the numeric result code of the most recent failed SQLite request

  • « SQLite3::exec
  • SQLite3::lastErrorMsg »
  • PHP Manual
  • SQLite3
  • Returns the numeric result code of the most recent failed SQLite request

SQLite3::lastErrorCode

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::lastErrorCode — Returns the numeric result code of the most recent failed SQLite request

Description

public SQLite3::lastErrorCode ( void ) : 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.


Returns English text describing the most recent failed SQLite request

  • « SQLite3::lastErrorCode
  • SQLite3::lastInsertRowID »
  • PHP Manual
  • SQLite3
  • Returns English text describing the most recent failed SQLite request

SQLite3::lastErrorMsg

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::lastErrorMsg — Returns English text describing the most recent failed SQLite request

Description

public SQLite3::lastErrorMsg ( void ) : 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.


Returns the row ID of the most recent INSERT into the database

  • « SQLite3::lastErrorMsg
  • SQLite3::loadExtension »
  • PHP Manual
  • SQLite3
  • Returns the row ID of the most recent INSERT into the database

SQLite3::lastInsertRowID

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::lastInsertRowID — Returns the row ID of the most recent INSERT into the database

Description

public SQLite3::lastInsertRowID ( void ) : 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


Attempts to load an SQLite extension library

  • « SQLite3::lastInsertRowID
  • SQLite3::open »
  • PHP Manual
  • SQLite3
  • Attempts to load an SQLite extension library

SQLite3::loadExtension

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::loadExtension — Attempts to load an SQLite extension library

Description

public SQLite3::loadExtension ( string $shared_library ) : bool

Attempts to load an SQLite extension library.

Parameters

shared_library

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');
?>


Opens an SQLite database

  • « SQLite3::loadExtension
  • SQLite3::openBlob »
  • PHP Manual
  • SQLite3
  • Opens an SQLite database

SQLite3::open

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::open — Opens an SQLite database

Description

public SQLite3::open ( string $filename [, int $flags = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE [, string $encryption_key = "" ]] ) : 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.

encryption_key

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());
?>


Opens a stream resource to read a BLOB

  • « SQLite3::open
  • SQLite3::prepare »
  • PHP Manual
  • SQLite3
  • Opens a stream resource to read a BLOB

SQLite3::openBlob

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::openBlob — Opens a stream resource to read a BLOB

Description

public SQLite3::openBlob ( string $table , string $column , int $rowid [, string $dbname = "main" [, int $flags = SQLITE3_OPEN_READONLY ]] ) : resource

Opens a stream resource to read or write a BLOB, which would be selected by:

SELECT column FROM dbname.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.

dbname

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


Prepares an SQL statement for execution

  • « SQLite3::openBlob
  • SQLite3::query »
  • PHP Manual
  • SQLite3
  • Prepares an SQL statement for execution

SQLite3::prepare

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::prepare — Prepares an SQL statement for execution

Description

public SQLite3::prepare ( string $query ) : SQLite3Stmt

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


Executes an SQL query

  • « SQLite3::prepare
  • SQLite3::querySingle »
  • PHP Manual
  • SQLite3
  • Executes an SQL query

SQLite3::query

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::query — Executes an SQL query

Description

public SQLite3::query ( string $query ) : SQLite3Result

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


Executes a query and returns a single result

  • « SQLite3::query
  • SQLite3::version »
  • PHP Manual
  • SQLite3
  • Executes a query and returns a single result

SQLite3::querySingle

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::querySingle — Executes a query and returns a single result

Description

public SQLite3::querySingle ( string $query [, bool $entire_row = FALSE ] ) : mixed

Executes a query and returns a single result.

Parameters

query

The SQL query to execute.

entire_row

By default, querySingle() returns the value of the first column returned by the query. If entire_row 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 entire_row is TRUE).

If the query is valid but no results are returned, then NULL will be returned if entire_row 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
)


Returns the SQLite3 library version as a string constant and as a number

  • « SQLite3::querySingle
  • SQLite3Stmt »
  • PHP Manual
  • SQLite3
  • Returns the SQLite3 library version as a string constant and as a number

SQLite3::version

(PHP 5 >= 5.3.0, PHP 7)

SQLite3::version — Returns the SQLite3 library version as a string constant and as a number

Description

public static SQLite3::version ( void ) : 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
)


The SQLite3Stmt class

(PHP 5 >= 5.3.0, PHP 7)

Introduction

A class that handles prepared statements for the SQLite 3 extension.

Class synopsis

SQLite3Stmt {
/* Methods */
public bindParam ( mixed $sql_param , mixed &$param [, int $type ] ) : bool
public bindValue ( mixed $sql_param , mixed $value [, int $type ] ) : bool
public clear ( void ) : bool
public close ( void ) : bool
public execute ( void ) : SQLite3Result
public getSQL ([ bool $expanded = FALSE ] ) : string
public paramCount ( void ) : int
public readOnly ( void ) : bool
public reset ( void ) : bool
}

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


Binds a parameter to a statement variable

  • « SQLite3Stmt
  • SQLite3Stmt::bindValue »
  • PHP Manual
  • SQLite3Stmt
  • Binds a parameter to a statement variable

SQLite3Stmt::bindParam

(PHP 5 >= 5.3.0, PHP 7)

SQLite3Stmt::bindParam — Binds a parameter to a statement variable

Description

public SQLite3Stmt::bindParam ( mixed $sql_param , mixed &$param [, int $type ] ) : 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

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

param

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 param: boolean and integer 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 param 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 | sql_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


Binds the value of a parameter to a statement variable

  • « SQLite3Stmt::bindParam
  • SQLite3Stmt::clear »
  • PHP Manual
  • SQLite3Stmt
  • Binds the value of a parameter to a statement variable

SQLite3Stmt::bindValue

(PHP 5 >= 5.3.0, PHP 7)

SQLite3Stmt::bindValue — Binds the value of a parameter to a statement variable

Description

public SQLite3Stmt::bindValue ( mixed $sql_param , mixed $value [, int $type ] ) : 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

sql_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: boolean and integer 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 | sql_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


Clears all current bound parameters

  • « SQLite3Stmt::bindValue
  • SQLite3Stmt::close »
  • PHP Manual
  • SQLite3Stmt
  • Clears all current bound parameters

SQLite3Stmt::clear

(PHP 5 >= 5.3.0, PHP 7)

SQLite3Stmt::clear — Clears all current bound parameters

Description

public SQLite3Stmt::clear ( void ) : 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.


Closes the prepared statement

  • « SQLite3Stmt::clear
  • SQLite3Stmt::execute »
  • PHP Manual
  • SQLite3Stmt
  • Closes the prepared statement

SQLite3Stmt::close

(PHP 5 >= 5.3.0, PHP 7)

SQLite3Stmt::close — Closes the prepared statement

Description

public SQLite3Stmt::close ( void ) : bool

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

Returns TRUE


Executes a prepared statement and returns a result set object

  • « SQLite3Stmt::close
  • SQLite3Stmt::getSQL »
  • PHP Manual
  • SQLite3Stmt
  • Executes a prepared statement and returns a result set object

SQLite3Stmt::execute

(PHP 5 >= 5.3.0, PHP 7)

SQLite3Stmt::execute — Executes a prepared statement and returns a result set object

Description

public SQLite3Stmt::execute ( void ) : SQLite3Result

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


Get the SQL of the statement

  • « SQLite3Stmt::execute
  • SQLite3Stmt::paramCount »
  • PHP Manual
  • SQLite3Stmt
  • Get the SQL of the statement

SQLite3Stmt::getSQL

(PHP 7 >= 7.4.0)

SQLite3Stmt::getSQL — Get the SQL of the statement

Description

public SQLite3Stmt::getSQL ([ bool $expanded = FALSE ] ) : string

Retrieves the SQL of the prepared statement. If expanded is FALSE, the unmodified SQL is retrieved. If expanded is TRUE, all query parameters are replaced with their bound values, or with an SQL NULL, if not already bound.

Parameters

expanded

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


Returns the number of parameters within the prepared statement

  • « SQLite3Stmt::getSQL
  • SQLite3Stmt::readOnly »
  • PHP Manual
  • SQLite3Stmt
  • Returns the number of parameters within the prepared statement

SQLite3Stmt::paramCount

(PHP 5 >= 5.3.0, PHP 7)

SQLite3Stmt::paramCount — Returns the number of parameters within the prepared statement

Description

public SQLite3Stmt::paramCount ( void ) : 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


Returns whether a statement is definitely read only

  • « SQLite3Stmt::paramCount
  • SQLite3Stmt::reset »
  • PHP Manual
  • SQLite3Stmt
  • Returns whether a statement is definitely read only

SQLite3Stmt::readOnly

(PHP 5 >= 5.3.6, PHP 7)

SQLite3Stmt::readOnly — Returns whether a statement is definitely read only

Description

public SQLite3Stmt::readOnly ( void ) : 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.


Resets the prepared statement

  • « SQLite3Stmt::readOnly
  • SQLite3Result »
  • PHP Manual
  • SQLite3Stmt
  • Resets the prepared statement

SQLite3Stmt::reset

(PHP 5 >= 5.3.0, PHP 7)

SQLite3Stmt::reset — Resets the prepared statement

Description

public SQLite3Stmt::reset ( void ) : 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.


The SQLite3Result class

(PHP 5 >= 5.3.0, PHP 7)

Introduction

A class that handles result sets for the SQLite 3 extension.

Class synopsis

SQLite3Result {
/* Methods */
public columnName ( int $column_number ) : string
public columnType ( int $column_number ) : int
public fetchArray ([ int $mode = SQLITE3_BOTH ] ) : array
public finalize ( void ) : bool
public numColumns ( void ) : int
public reset ( void ) : bool
}

Table of Contents

  • SQLite3Result::columnName — Returns the name of the nth column
  • SQLite3Result::columnType — Returns the type of the nth column
  • 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


Returns the name of the nth column

  • « SQLite3Result
  • SQLite3Result::columnType »
  • PHP Manual
  • SQLite3Result
  • Returns the name of the nth column

SQLite3Result::columnName

(PHP 5 >= 5.3.0, PHP 7)

SQLite3Result::columnName — Returns the name of the nth column

Description

public SQLite3Result::columnName ( int $column_number ) : string

Returns the name of the column specified by the column_number.

Parameters

column_number

The numeric zero-based index of the column.

Return Values

Returns the string name of the column identified by column_number.


Returns the type of the nth column

  • « SQLite3Result::columnName
  • SQLite3Result::fetchArray »
  • PHP Manual
  • SQLite3Result
  • Returns the type of the nth column

SQLite3Result::columnType

(PHP 5 >= 5.3.0, PHP 7)

SQLite3Result::columnType — Returns the type of the nth column

Description

public SQLite3Result::columnType ( int $column_number ) : int

Returns the type of the column identified by column_number.

Parameters

column_number

The numeric zero-based index of the column.

Return Values

Returns the data type index of the column identified by column_number (one of SQLITE3_INTEGER, SQLITE3_FLOAT, SQLITE3_TEXT, SQLITE3_BLOB, or SQLITE3_NULL).


Fetches a result row as an associative or numerically indexed array or both

  • « SQLite3Result::columnType
  • SQLite3Result::finalize »
  • PHP Manual
  • SQLite3Result
  • Fetches a result row as an associative or numerically indexed array or both

SQLite3Result::fetchArray

(PHP 5 >= 5.3.0, PHP 7)

SQLite3Result::fetchArray — Fetches a result row as an associative or numerically indexed array or both

Description

public SQLite3Result::fetchArray ([ int $mode = SQLITE3_BOTH ] ) : array

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


Closes the result set

  • « SQLite3Result::fetchArray
  • SQLite3Result::numColumns »
  • PHP Manual
  • SQLite3Result
  • Closes the result set

SQLite3Result::finalize

(PHP 5 >= 5.3.0, PHP 7)

SQLite3Result::finalize — Closes the result set

Description

public SQLite3Result::finalize ( void ) : bool

Closes the result set.

Parameters

This function has no parameters.

Return Values

Returns TRUE.


Returns the number of columns in the result set

  • « SQLite3Result::finalize
  • SQLite3Result::reset »
  • PHP Manual
  • SQLite3Result
  • Returns the number of columns in the result set

SQLite3Result::numColumns

(PHP 5 >= 5.3.0, PHP 7)

SQLite3Result::numColumns — Returns the number of columns in the result set

Description

public SQLite3Result::numColumns ( void ) : 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.


Resets the result set back to the first row

  • « SQLite3Result::numColumns
  • SQLSRV »
  • PHP Manual
  • SQLite3Result
  • Resets the result set back to the first row

SQLite3Result::reset

(PHP 5 >= 5.3.0, PHP 7)

SQLite3Result::reset — Resets the result set back to the first row

Description

public SQLite3Result::reset ( void ) : 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.


Microsoft SQL Server Driver for PHP

  • Introduction
  • 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_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 — Makes the next row in a result set available for reading
    • 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


Introduction

The SQLSRV extension allows you to access Microsoft SQL Server and SQL Azure databases when running PHP on Windows. 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.


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. If you are running non-thread-safe PHP (PHP 5.3), use the php_sqlsrv_53_nts.dll file. (You should use a non-thread-safe version if you are using IIS as your web server). If you are running thread-safe PHP, use the php_sqlsrv_53_ts.dll file. Similarly for PHP 5.4, use the php_sqlsrv_54_nts.dll or php_sqlsrv_54_ts.dll depending on whether your PHP installation is non-thread-safe or thread-safe.

The most recent version of the driver is available for download here: » SQLSRV 4.0 download. If you need support for PHP 5.2 and/or PHP compiled with VC6, use the 2.0 release of the driver: » SQLSRV 2.0 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 8 driver files, four of which are for PDO support. If you are running non-thread-safe PHP (PHP 5.3), use the php_sqlsrv_53_nts.dll file. (You should use a non-thread-safe version if you are using IIS as your web server). If you are running thread-safe PHP, use the php_sqlsrv_53_ts.dll file. Similarly for PHP 5.4, use the php_sqlsrv_54_nts.dll or php_sqlsrv_54_ts.dll depending on whether your PHP installation is non-thread-safe or thread-safe.

The most recent version of the driver is available for download here: » SQLSRV 4.0 download. If you need support for PHP 5.2 and/or PHP compiled with VC6, use the 2.0 release of the driver: » SQLSRV 2.0 download.

For more information about SQLSRV requirements, see » SQLSRV System Requirements.

The SQLSRV extension is only compatible with PHP 5 running on Windows. Since version 4.0 the SQLSRV extension is compatilbe 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) | PHP_INI_ALL | Available since SQLSRV 1.0
sqlsrv.LogSubsystems | 0 | PHP_INI_ALL | Available since SQLSRV 1.0
sqlsrv.LogSeverity | 1 | PHP_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 (integer)
Forces sqlsrv_fetch_array() to return an associative array when passed as a parameter.
SQLSRV_FETCH_NUMERIC (integer)
Forces sqlsrv_fetch_array() to return an array with numeric when passed as a parameter.
SQLSRV_FETCH_BOTH (integer)
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 (integer)
Forces sqlsrv_errors() to return both errors and warings when passed as a parameter (the default behavior).
SQLSRV_ERR_ERRORS (integer)
Forces sqlsrv_errors() to return errors only (no warnings) when passed as a parameter.
SQLSRV_ERR_WARNINGS (integer)
Forces sqlsrv_errors() to return warnings only (no errors) when passed as a parameter.
SQLSRV_LOG_SYSTEM_ALL (integer)
Turns on logging of all subsystems when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SYSTEM_CONN (integer)
Turns on logging of connection activity when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SYSTEM_INIT (integer)
Turns on logging of initialization activity when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SYSTEM_OFF (integer)
Turns off logging of all subsystems when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SYSTEM_STMT (integer)
Turns on logging of statement activity when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SYSTEM_UTIL (integer)
Turns on logging of error function activity when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SEVERITY_ALL (integer)
Specifies that errors, warnings, and notices will be logged when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SEVERITY_ERROR (integer)
Specifies that errors will be logged when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SEVERITY_NOTICE (integer)
Specifies that notices will be logged when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SEVERITY_WARNING (integer)
Specifies that warnings will be logged when passed to sqlsrv_configure() as a parameter.
SQLSRV_NULLABLE_YES (integer)
Indicates that a column is nullable.
SQLSRV_NULLABLE_NO (integer)
Indicates that a column is not nullable.
SQLSRV_NULLABLE_UNKNOWN (integer)
Indicates that it is not known if a column is nullable.
SQLSRV_PARAM_IN (integer)
Indicates an input parameter when passed to sqlsrv_query() or sqlsrv_prepare().
SQLSRV_PARAM_INOUT (integer)
Indicates a bidirectional parameter when passed to sqlsrv_query() or sqlsrv_prepare().
SQLSRV_PARAM_OUT (integer)
Indicates an output parameter when passed to sqlsrv_query() or sqlsrv_prepare().
SQLSRV_PHPTYPE_INT (integer)
Specifies an integer PHP data type. For usage information, see » How to: Specify PHP Types.
SQLSRV_PHPTYPE_DATETIME (integer)
Specifies a datetime PHP data type. For usage information, see » How to: Specify PHP Types.
SQLSRV_PHPTYPE_FLOAT (integer)
Specifies a float PHP data type. For usage information, see » How to: Specify PHP Types.
SQLSRV_PHPTYPE_STREAM (integer)
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 (integer)
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 (integer)
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 (integer)
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.
UTF-8 (integer)
Specifies that data is returned with UTF-8 encoding. For usage information, see » How to: Specify PHP Types.
SQLSRV_SQLTYPE_BIGINT (integer)
Describes the bigint SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_BINARY (integer)
Describes the binary SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_BIT (integer)
Describes the bit SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_CHAR (integer)
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 (integer)
Describes the date SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_DATETIME (integer)
Describes the datetime SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_DATETIME2 (integer)
Describes the datetime2 SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_DATETIMEOFFSET (integer)
Describes the datetimeoffset SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_DECIMAL (integer)
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 (integer)
Describes the float SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_IMAGE (integer)
Describes the image SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_INT (integer)
Describes the int SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_MONEY (integer)
Describes the money SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_NCHAR (integer)
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 (integer)
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 (integer)
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') (integer)
Describes the nvarchar(MAX) SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_NTEXT (integer)
Describes the ntext SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_REAL (integer)
Describes the real SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_SMALLDATETIME (integer)
Describes the smalldatetime SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_SMALLINT (integer)
Describes the smallint SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_SMALLMONEY (integer)
Describes the smallmoney SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_TEXT (integer)
Describes the text SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_TIME (integer)
Describes the time SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_TIMESTAMP (integer)
Describes the timestamp SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_TINYINT (integer)
Describes the tinyint SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_UNIQUEIDENTIFIER (integer)
Describes the uniqueidentifier SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_UDT (integer)
Describes the UDT SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_VARBINARY (integer)
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') (integer)
Describes the varbinary(MAX) SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_VARCHAR (integer)
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') (integer)
Describes the varchar(MAX) SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_XML (integer)
Describes the XML SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_TXN_READ_UNCOMMITTED (integer)
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 (integer)
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 (integer)
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 (integer)
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 (integer)
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 (integer)
Indicates a forward-only cursor. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_CURSOR_STATIC (integer)
Indicates a static cursor. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_CURSOR_DYNAMIC (integer)
Indicates a dynamic cursor. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_CURSOR_KEYSET (integer)
Indicates a keyset cursor. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_CURSOR_BUFFERED (integer)
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 (integer)
Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_SCROLL_PRIOR (integer)
Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_SCROLL_FIRST (integer)
Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_SCROLL_LAST (integer)
Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_SCROLL_ABSOLUTE (integer)
Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_SCROLL_RELATIVE (integer)
Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.


SQLSRV Functions

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_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 — Makes the next row in a result set available for reading
  • 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


Begins a database transaction

  • « SQLSRV Functions
  • sqlsrv_cancel »
  • PHP Manual
  • SQLSRV Functions
  • Begins a database transaction

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


Cancels a statement

  • « sqlsrv_begin_transaction
  • sqlsrv_client_info »
  • PHP Manual
  • SQLSRV Functions
  • Cancels a statement

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


Returns information about the client and specified connection

  • « sqlsrv_cancel
  • sqlsrv_close »
  • PHP Manual
  • SQLSRV Functions
  • Returns information about the client and specified connection

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


Closes an open connection and releases resourses associated with the connection

  • « sqlsrv_client_info
  • sqlsrv_commit »
  • PHP Manual
  • SQLSRV Functions
  • Closes an open connection and releases resourses associated with the connection

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


Commits a transaction that was begun with sqlsrv_begin_transaction

  • « sqlsrv_close
  • sqlsrv_configure »
  • PHP Manual
  • SQLSRV Functions
  • Commits a transaction that was begun with sqlsrv_begin_transaction

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


Changes the driver error handling and logging configurations

  • « sqlsrv_commit
  • sqlsrv_connect »
  • PHP Manual
  • SQLSRV Functions
  • Changes the driver error handling and logging configurations

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.


Opens a connection to a Microsoft SQL Server database

  • « sqlsrv_configure
  • sqlsrv_errors »
  • PHP Manual
  • SQLSRV Functions
  • Opens a connection to a Microsoft SQL Server database

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


Returns error and warning information about the last SQLSRV operation performed

  • « sqlsrv_connect
  • sqlsrv_execute »
  • PHP Manual
  • SQLSRV Functions
  • Returns error and warning information about the last SQLSRV operation performed

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


Executes a statement prepared with sqlsrv_prepare

  • « sqlsrv_errors
  • sqlsrv_fetch_array »
  • PHP Manual
  • SQLSRV Functions
  • Executes a statement prepared with sqlsrv_prepare

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


Returns a row as an array

  • « sqlsrv_execute
  • sqlsrv_fetch_object »
  • PHP Manual
  • SQLSRV Functions
  • Returns a row as an array

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


Retrieves the next row of data in a result set as an object

  • « sqlsrv_fetch_array
  • sqlsrv_fetch »
  • PHP Manual
  • SQLSRV Functions
  • Retrieves the next row of data in a result set as an object

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


Makes the next row in a result set available for reading

  • « sqlsrv_fetch_object
  • sqlsrv_field_metadata »
  • PHP Manual
  • SQLSRV Functions
  • Makes the next row in a result set available for reading

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


Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare or sqlsrv_query

  • « sqlsrv_fetch
  • sqlsrv_free_stmt »
  • PHP Manual
  • SQLSRV Functions
  • Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare or sqlsrv_query

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


Frees all resources for the specified statement

  • « sqlsrv_field_metadata
  • sqlsrv_get_config »
  • PHP Manual
  • SQLSRV Functions
  • Frees all resources for the specified statement

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


Returns the value of the specified configuration setting

  • « sqlsrv_free_stmt
  • sqlsrv_get_field »
  • PHP Manual
  • SQLSRV Functions
  • Returns the value of the specified configuration setting

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


Gets field data from the currently selected row

  • « sqlsrv_get_config
  • sqlsrv_has_rows »
  • PHP Manual
  • SQLSRV Functions
  • Gets field data from the currently selected row

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


Indicates whether the specified statement has rows

  • « sqlsrv_get_field
  • sqlsrv_next_result »
  • PHP Manual
  • SQLSRV Functions
  • Indicates whether the specified statement has rows

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


Makes the next result of the specified statement active

  • « sqlsrv_has_rows
  • sqlsrv_num_fields »
  • PHP Manual
  • SQLSRV Functions
  • Makes the next result of the specified statement active

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


Retrieves the number of fields (columns) on a statement

  • « sqlsrv_next_result
  • sqlsrv_num_rows »
  • PHP Manual
  • SQLSRV Functions
  • Retrieves the number of fields (columns) on a statement

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


Retrieves the number of rows in a result set

  • « sqlsrv_num_fields
  • sqlsrv_prepare »
  • PHP Manual
  • SQLSRV Functions
  • Retrieves the number of rows in a result set

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


Prepares a query for execution

  • « sqlsrv_num_rows
  • sqlsrv_query »
  • PHP Manual
  • SQLSRV Functions
  • Prepares a query for execution

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


Prepares and executes a query

  • « sqlsrv_prepare
  • sqlsrv_rollback »
  • PHP Manual
  • SQLSRV Functions
  • 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


Rolls back a transaction that was begun with sqlsrv_begin_transaction

  • « sqlsrv_query
  • sqlsrv_rows_affected »
  • PHP Manual
  • SQLSRV Functions
  • Rolls back a transaction that was begun with sqlsrv_begin_transaction

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


Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed

  • « sqlsrv_rollback
  • sqlsrv_send_stream_data »
  • PHP Manual
  • SQLSRV Functions
  • Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed

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

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


Sends data from parameter streams to the server

  • « sqlsrv_rows_affected
  • sqlsrv_server_info »
  • PHP Manual
  • SQLSRV Functions
  • Sends data from parameter streams to the server

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


Returns information about the server

  • « sqlsrv_send_stream_data
  • Sybase »
  • PHP Manual
  • SQLSRV Functions
  • Returns information about the server

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


Sybase

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Sybase Functions
    • sybase_affected_rows — Gets number of affected rows in last query
    • sybase_close — Closes a Sybase connection
    • sybase_connect — Opens a Sybase server connection
    • sybase_data_seek — Moves internal row pointer
    • sybase_deadlock_retry_count — Sets the deadlock retry count
    • sybase_fetch_array — Fetch row as array
    • sybase_fetch_assoc — Fetch a result row as an associative array
    • sybase_fetch_field — Get field information from a result
    • sybase_fetch_object — Fetch a row as an object
    • sybase_fetch_row — Get a result row as an enumerated array
    • sybase_field_seek — Sets field offset
    • sybase_free_result — Frees result memory
    • sybase_get_last_message — Returns the last message from the server
    • sybase_min_client_severity — Sets minimum client severity
    • sybase_min_error_severity — Sets minimum error severity
    • sybase_min_message_severity — Sets minimum message severity
    • sybase_min_server_severity — Sets minimum server severity
    • sybase_num_fields — Gets the number of fields in a result set
    • sybase_num_rows — Get number of rows in a result set
    • sybase_pconnect — Open persistent Sybase connection
    • sybase_query — Sends a Sybase query
    • sybase_result — Get result data
    • sybase_select_db — Selects a Sybase database
    • sybase_set_message_handler — Sets the handler called when a server message is raised
    • sybase_unbuffered_query — Send a Sybase query and do not block


  • « Sybase
  • Installing/Configuring »
  • PHP Manual
  • Sybase
  • Introduction

Introduction

Warning

As of PHP 7.0.0, the sybase_ct extension has been removed.


Installation

To enable Sybase-DB support configure PHP --with-sybase[=DIR] . DIR is the Sybase home directory, defaults to /home/sybase. To enable Sybase-CT support configure PHP --with-sybase-ct[=DIR] . DIR is the Sybase home directory, defaults to /home/sybase.

Note:

As of PHP 5.3.0, the Sybase extension has been superseded by the sybase_ct extension and is no longer maintained. To continue using sybase you must use the sybase_ct extension.

As of PHP 7.0.0, the sybase_ct extension has been removed.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Sybase configuration options
Name | Default | Changeable | Changelog
sybase.allow_persistent | "1" | PHP_INI_ALL | PHP_INI_ALL in PHP <= 4.0.2. PHP_INI_SYSTEM in PHP <= 4.0.3.
sybase.max_persistent | "-1" | PHP_INI_ALL | PHP_INI_ALL in PHP <= 4.0.2. PHP_INI_SYSTEM in PHP <= 4.0.3.
sybase.max_links | "-1" | PHP_INI_ALL | PHP_INI_ALL in PHP <= 4.0.2. PHP_INI_SYSTEM in PHP <= 4.0.3.
sybase.interface_file | "/usr/sybase/interfaces" | PHP_INI_SYSTEM |
sybase.min_error_severity | "10" | PHP_INI_ALL |
sybase.min_message_severity | "10" | PHP_INI_ALL |
sybase.compatability_mode | "0" | PHP_INI_ALL |
magic_quotes_sybase | "0" | PHP_INI_ALL | Deprecated in PHP 5.3.0. Removed in PHP 5.4.0.

Here's a short explanation of the configuration directives.

sybase.allow_persistent boolean

Whether to allow persistent Sybase connections.

sybase.max_persistent integer

The maximum number of persistent Sybase connections per process. -1 means no limit.

sybase.max_links integer

The maximum number of Sybase connections per process, including persistent connections. -1 means no limit.

sybase.min_error_severity integer

Minimum error severity to display.

sybase.min_message_severity integer

Minimum message severity to display.

magic_quotes_sybase boolean

If magic_quotes_sybase is on, a single-quote is escaped with a single-quote instead of a backslash if magic_quotes_gpc or magic_quotes_runtime are enabled. This setting is also respected by addslashes() and stripslashes().

Note:

Note that when magic_quotes_sybase is ON it completely overrides magic_quotes_gpc . In this case even when magic_quotes_gpc is enabled neither double quotes, backslashes or NUL's will be escaped.

Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

Sybase-CT configuration options
Name | Default | Changeable | Changelog
sybct.deadlock_retry_count | "0" | PHP_INI_ALL | Available since PHP 4.3.0.

Here's a short explanation of the configuration directives.

sybct.login_timeout integer

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

sybct.timeout integer

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

sybct.deadlock_retry_count int

Allows you to define how often deadlocks are to be retried. The default is 0, value -1 means "forever".

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.


  • « Resource Types
  • Sybase Functions »
  • PHP Manual
  • Sybase
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


Sybase Functions

Table of Contents

  • sybase_affected_rows — Gets number of affected rows in last query
  • sybase_close — Closes a Sybase connection
  • sybase_connect — Opens a Sybase server connection
  • sybase_data_seek — Moves internal row pointer
  • sybase_deadlock_retry_count — Sets the deadlock retry count
  • sybase_fetch_array — Fetch row as array
  • sybase_fetch_assoc — Fetch a result row as an associative array
  • sybase_fetch_field — Get field information from a result
  • sybase_fetch_object — Fetch a row as an object
  • sybase_fetch_row — Get a result row as an enumerated array
  • sybase_field_seek — Sets field offset
  • sybase_free_result — Frees result memory
  • sybase_get_last_message — Returns the last message from the server
  • sybase_min_client_severity — Sets minimum client severity
  • sybase_min_error_severity — Sets minimum error severity
  • sybase_min_message_severity — Sets minimum message severity
  • sybase_min_server_severity — Sets minimum server severity
  • sybase_num_fields — Gets the number of fields in a result set
  • sybase_num_rows — Get number of rows in a result set
  • sybase_pconnect — Open persistent Sybase connection
  • sybase_query — Sends a Sybase query
  • sybase_result — Get result data
  • sybase_select_db — Selects a Sybase database
  • sybase_set_message_handler — Sets the handler called when a server message is raised
  • sybase_unbuffered_query — Send a Sybase query and do not block


Gets number of affected rows in last query

  • « Sybase Functions
  • sybase_close »
  • PHP Manual
  • Sybase Functions
  • Gets number of affected rows in last query

sybase_affected_rows

(PHP 4, PHP 5)

sybase_affected_rows — Gets number of affected rows in last query

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_affected_rows ([ resource $link_identifier ] ) : int

sybase_affected_rows() returns the number of rows affected by the last INSERT, UPDATE or DELETE query on the server associated with the specified link identifier.

This command is not effective for SELECT statements, only on statements which modify records. To retrieve the number of rows returned from a SELECT, use sybase_num_rows().

Parameters

link_identifier

If the link identifier isn't specified, the last opened link is assumed.

Return Values

Returns the number of affected rows, as an integer.

Examples

Example #1 Delete-Query

<?php
/* connect to database */
sybase_connect('SYBASE', '', '') or
die("Could not connect");
sybase_select_db("db");

sybase_query("DELETE FROM sometable WHERE id < 10");
printf("Records deleted: %d\n", sybase_affected_rows());
?>

The above example will output:

Records deleted: 10

See Also

  • sybase_num_rows() - Get number of rows in a result set


Closes a Sybase connection

  • « sybase_affected_rows
  • sybase_connect »
  • PHP Manual
  • Sybase Functions
  • Closes a Sybase connection

sybase_close

(PHP 4, PHP 5)

sybase_close — Closes a Sybase connection

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_close ([ resource $link_identifier ] ) : bool

sybase_close() closes the link to a Sybase database that's associated with the specified link link_identifier.

Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

sybase_close() will not close persistent links generated by sybase_pconnect().

Parameters

link_identifier

If the link identifier isn't specified, the last opened link is assumed.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • sybase_connect() - Opens a Sybase server connection
  • sybase_pconnect() - Open persistent Sybase connection


Opens a Sybase server connection

  • « sybase_close
  • sybase_data_seek »
  • PHP Manual
  • Sybase Functions
  • Opens a Sybase server connection

sybase_connect

(PHP 4, PHP 5)

sybase_connect — Opens a Sybase server connection

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_connect ([ string $servername [, string $username [, string $password [, string $charset [, string $appname [, bool $new = FALSE ]]]]]] ) : resource

sybase_connect() establishes a connection to a Sybase server.

In case a second call is made to sybase_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 sybase_close().

Parameters

servername

The servername argument has to be a valid servername that is defined in the 'interfaces' file.

username

Sybase user name

password

Password associated with username.

charset

Specifies the charset for the connection

appname

Specifies an appname for the Sybase connection. This allow you to make separate connections in the same script to the same database. This may come handy when you have started a transaction in your current connection, and you need to be able to do a separate query which cannot be performed inside this transaction.

new

Whether to open a new connection or use the existing one.

Return Values

Returns a positive Sybase link identifier on success, or FALSE on failure.

Changelog

Version | Description
5.3.0 | The new parameter was added.

Examples

Example #1 sybase_connect() example

<?php
$link = sybase_connect('SYBASE', '', '')
        or die("Could not connect !");
echo "Connected successfully";
sybase_close($link);
?>

See Also

  • sybase_pconnect() - Open persistent Sybase connection
  • sybase_close() - Closes a Sybase connection


Moves internal row pointer

  • « sybase_connect
  • sybase_deadlock_retry_count »
  • PHP Manual
  • Sybase Functions
  • Moves internal row pointer

sybase_data_seek

(PHP 4, PHP 5)

sybase_data_seek — Moves internal row pointer

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_data_seek ( resource $result_identifier , int $row_number ) : bool

sybase_data_seek() moves the internal row pointer of the Sybase result associated with the specified result identifier to pointer to the specified row number. The next call to sybase_fetch_row() would return that row.

Parameters

result_identifier

row_number

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • sybase_fetch_row() - Get a result row as an enumerated array


Sets the deadlock retry count

  • « sybase_data_seek
  • sybase_fetch_array »
  • PHP Manual
  • Sybase Functions
  • Sets the deadlock retry count

sybase_deadlock_retry_count

(PHP 4 >= 4.3.0, PHP 5)

sybase_deadlock_retry_count — Sets the deadlock retry count

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_deadlock_retry_count ( int $retry_count ) : void

Using sybase_deadlock_retry_count(), the number of retries can be defined in cases of deadlocks. By default, every deadlock is retried an infinite number of times or until the process is killed by Sybase, the executing script is killed (for instance, by set_time_limit()) or the query succeeds.

Parameters

retry_count

Values for retry_count
-1 | Retry forever (default)
0 | Do not retry
n | Retry n times

Return Values

No value is returned.

Notes

Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.


Fetch row as array

  • « sybase_deadlock_retry_count
  • sybase_fetch_assoc »
  • PHP Manual
  • Sybase Functions
  • Fetch row as array

sybase_fetch_array

(PHP 4, PHP 5)

sybase_fetch_array — Fetch row as array

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_fetch_array ( resource $result ) : array

sybase_fetch_array() is an extended version of sybase_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

An important thing to note is that using sybase_fetch_array() is NOT significantly slower than using sybase_fetch_row(), while it provides a significant added value.

Parameters

result

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Note:

When selecting fields with identical names (for instance, in a join), the associative indices will have a sequential number prepended. See the example for details.

Examples

Example #1 Identical fieldnames

<?php

$dbh = sybase_connect('SYBASE', '', '');
$q = sybase_query('SELECT * FROM p, a WHERE p.person_id= a.person_id');
var_dump(sybase_fetch_array($q));
sybase_close($dbh);
?>

The above example would produce the following output (assuming the two tables only have each one column called "person_id"):

array(4) {
  [0]=>
  int(1)
  ["person_id"]=>
  int(1)
  [1]=>
  int(1)
  ["person_id1"]=>
  int(1)
}

See Also

  • sybase_fetch_row() - Get a result row as an enumerated array
  • sybase_fetch_assoc() - Fetch a result row as an associative array
  • sybase_fetch_object() - Fetch a row as an object


Fetch a result row as an associative array

  • « sybase_fetch_array
  • sybase_fetch_field »
  • PHP Manual
  • Sybase Functions
  • Fetch a result row as an associative array

sybase_fetch_assoc

(PHP 4 >= 4.3.0, PHP 5)

sybase_fetch_assoc — Fetch a result row as an associative array

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_fetch_assoc ( resource $result ) : array

sybase_fetch_assoc() is a version of sybase_fetch_row() that uses column names instead of integers for indices in the result array. Columns from different tables with the same names are returned as name, name1, name2, ..., nameN.

An important thing to note is that using sybase_fetch_assoc() is NOT significantly slower than using sybase_fetch_row(), while it provides a significant added value.

Parameters

result

Return Values

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Notes

Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.

See Also

  • sybase_fetch_row() - Get a result row as an enumerated array
  • sybase_fetch_array() - Fetch row as array
  • sybase_fetch_object() - Fetch a row as an object


Get field information from a result

  • « sybase_fetch_assoc
  • sybase_fetch_object »
  • PHP Manual
  • Sybase Functions
  • Get field information from a result

sybase_fetch_field

(PHP 4, PHP 5)

sybase_fetch_field — Get field information from a result

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_fetch_field ( resource $result [, int $field_offset = -1 ] ) : object

sybase_fetch_field() can be used in order to obtain information about fields in a certain query result.

Parameters

result

field_offset

If the field offset isn't specified, the next field that wasn't yet retrieved by sybase_fetch_field() is retrieved.

Return Values

Returns an object containing field information.

The properties of the object are:

  • name - column name. if the column is a result of a function, this property is set to computed#N, where #N is a serial number.
  • column_source - the table from which the column was taken
  • max_length - maximum length of the column
  • numeric - 1 if the column is numeric
  • type - datatype of the column

See Also

  • sybase_field_seek() - Sets field offset


Fetch a row as an object

  • « sybase_fetch_field
  • sybase_fetch_row »
  • PHP Manual
  • Sybase Functions
  • Fetch a row as an object

sybase_fetch_object

(PHP 4, PHP 5)

sybase_fetch_object — Fetch a row as an object

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_fetch_object ( resource $result [, mixed $object ] ) : object

sybase_fetch_object() is similar to sybase_fetch_assoc(), with one difference - an object is returned, instead of an array.

Speed-wise, the function is identical to sybase_fetch_array(), and almost as quick as sybase_fetch_row() (the difference is insignificant).

Parameters

result

object

Use the second object to specify the type of object you want to return. If this parameter is omitted, the object will be of type stdClass.

Return Values

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

Examples

Example #1 sybase_fetch_object() return as Foo

<?php
    class Foo {
        var $foo, $bar, $baz;
    }

    // {...]
    $qrh= sybase_query('SELECT foo, bar, baz FROM example');
    $foo= sybase_fetch_object($qrh, 'Foo');
    $bar= sybase_fetch_object($qrh, new Foo());
    // {...]
?>

See Also

  • sybase_fetch_array() - Fetch row as array
  • sybase_fetch_row() - Get a result row as an enumerated array


Get a result row as an enumerated array

  • « sybase_fetch_object
  • sybase_field_seek »
  • PHP Manual
  • Sybase Functions
  • Get a result row as an enumerated array

sybase_fetch_row

(PHP 4, PHP 5)

sybase_fetch_row — Get a result row as an enumerated array

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_fetch_row ( resource $result ) : array

sybase_fetch_row() fetches one row of data from the result associated with the specified result identifier.

Subsequent call to sybase_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Parameters

result

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.

Data types
PHP | Sybase
string | VARCHAR, TEXT, CHAR, IMAGE, BINARY, VARBINARY, DATETIME
int | NUMERIC (w/o precision), DECIMAL (w/o precision), INT, BIT, TINYINT, SMALLINT
float | NUMERIC (w/ precision), DECIMAL (w/ precision), REAL, FLOAT, MONEY
NULL | NULL

See Also

  • sybase_fetch_array() - Fetch row as array
  • sybase_fetch_assoc() - Fetch a result row as an associative array
  • sybase_fetch_object() - Fetch a row as an object
  • sybase_data_seek() - Moves internal row pointer
  • sybase_result() - Get result data


Sets field offset

  • « sybase_fetch_row
  • sybase_free_result »
  • PHP Manual
  • Sybase Functions
  • Sets field offset

sybase_field_seek

(PHP 4, PHP 5)

sybase_field_seek — Sets field offset

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_field_seek ( resource $result , int $field_offset ) : bool

Seeks to the specified field offset. If the next call to sybase_fetch_field() won't include a field offset, this field would be returned.

Parameters

result

field_offset

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • sybase_fetch_field() - Get field information from a result


Frees result memory

  • « sybase_field_seek
  • sybase_get_last_message »
  • PHP Manual
  • Sybase Functions
  • Frees result memory

sybase_free_result

(PHP 4, PHP 5)

sybase_free_result — Frees result memory

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_free_result ( resource $result ) : bool

sybase_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 ends. You may call sybase_free_result() with the result identifier as an argument and the associated result memory will be freed.

Parameters

result

Return Values

Returns TRUE on success or FALSE on failure.


Returns the last message from the server

  • « sybase_free_result
  • sybase_min_client_severity »
  • PHP Manual
  • Sybase Functions
  • Returns the last message from the server

sybase_get_last_message

(PHP 4, PHP 5)

sybase_get_last_message — Returns the last message from the server

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_get_last_message ( void ) : string

sybase_get_last_message() returns the last message reported by the server.

Return Values

Returns the message as a string.

See Also

  • sybase_min_message_severity() - Sets minimum message severity


Sets minimum client severity

  • « sybase_get_last_message
  • sybase_min_error_severity »
  • PHP Manual
  • Sybase Functions
  • Sets minimum client severity

sybase_min_client_severity

(PHP 4, PHP 5)

sybase_min_client_severity — Sets minimum client severity

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_min_client_severity ( int $severity ) : void

sybase_min_client_severity() sets the minimum client severity level.

Parameters

severity

Return Values

No value is returned.

Notes

Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.

See Also

  • sybase_min_server_severity() - Sets minimum server severity


Sets minimum error severity

  • « sybase_min_client_severity
  • sybase_min_message_severity »
  • PHP Manual
  • Sybase Functions
  • Sets minimum error severity

sybase_min_error_severity

(PHP 4, PHP 5)

sybase_min_error_severity — Sets minimum error severity

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_min_error_severity ( int $severity ) : void

sybase_min_error_severity() sets the minimum error severity level.

Parameters

severity

Return Values

No value is returned.

Notes

Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.

See Also

  • sybase_min_message_severity() - Sets minimum message severity


Sets minimum message severity

  • « sybase_min_error_severity
  • sybase_min_server_severity »
  • PHP Manual
  • Sybase Functions
  • Sets minimum message severity

sybase_min_message_severity

(PHP 4, PHP 5)

sybase_min_message_severity — Sets minimum message severity

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_min_message_severity ( int $severity ) : void

sybase_min_message_severity() sets the minimum message severity level.

Parameters

severity

Return Values

No value is returned.

Notes

Note: This function is only available when using the DB library interface to Sybase, and not with the CT library.

See Also

  • sybase_min_error_severity() - Sets minimum error severity


Sets minimum server severity

  • « sybase_min_message_severity
  • sybase_num_fields »
  • PHP Manual
  • Sybase Functions
  • Sets minimum server severity

sybase_min_server_severity

(PHP 4, PHP 5)

sybase_min_server_severity — Sets minimum server severity

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_min_server_severity ( int $severity ) : void

sybase_min_server_severity() sets the minimum server severity level.

Parameters

severity

Return Values

No value is returned.

Notes

Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.

See Also

  • sybase_min_client_severity() - Sets minimum client severity


Gets the number of fields in a result set

  • « sybase_min_server_severity
  • sybase_num_rows »
  • PHP Manual
  • Sybase Functions
  • Gets the number of fields in a result set

sybase_num_fields

(PHP 4, PHP 5)

sybase_num_fields — Gets the number of fields in a result set

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_num_fields ( resource $result ) : int

sybase_num_fields() returns the number of fields in a result set.

Parameters

result

Return Values

Returns the number of fields as an integer.

See Also

  • sybase_query() - Sends a Sybase query
  • sybase_fetch_field() - Get field information from a result
  • sybase_num_rows() - Get number of rows in a result set


Get number of rows in a result set

  • « sybase_num_fields
  • sybase_pconnect »
  • PHP Manual
  • Sybase Functions
  • Get number of rows in a result set

sybase_num_rows

(PHP 4, PHP 5)

sybase_num_rows — Get number of rows in a result set

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_num_rows ( resource $result ) : int

sybase_num_rows() returns the number of rows in a result set.

Parameters

result

Return Values

Returns the number of rows as an integer.

See Also

  • sybase_num_fields() - Gets the number of fields in a result set
  • sybase_query() - Sends a Sybase query
  • sybase_fetch_row() - Get a result row as an enumerated array


Open persistent Sybase connection

  • « sybase_num_rows
  • sybase_query »
  • PHP Manual
  • Sybase Functions
  • Open persistent Sybase connection

sybase_pconnect

(PHP 4, PHP 5)

sybase_pconnect — Open persistent Sybase connection

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_pconnect ([ string $servername [, string $username [, string $password [, string $charset [, string $appname ]]]]] ) : resource

sybase_pconnect() acts very much like sybase_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 (sybase_close() will not close links established by sybase_pconnect()).

This type of links is therefore called 'persistent'.

Parameters

servername

The servername argument has to be a valid servername that is defined in the 'interfaces' file.

username

Sybase user name

password

Password associated with username.

charset

Specifies the charset for the connection

appname

Specifies an appname for the Sybase connection. This allow you to make separate connections in the same script to the same database. This may come handy when you have started a transaction in your current connection, and you need to be able to do a separate query which cannot be performed inside this transaction.

Return Values

Returns a positive Sybase persistent link identifier on success, or FALSE on error.

See Also

  • sybase_connect() - Opens a Sybase server connection


Sends a Sybase query

  • « sybase_pconnect
  • sybase_result »
  • PHP Manual
  • Sybase Functions
  • Sends a Sybase query

sybase_query

(PHP 4, PHP 5)

sybase_query — Sends a Sybase query

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_query ( string $query [, resource $link_identifier ] ) : mixed

sybase_query() sends a query to the currently active database on the server that's associated with the specified link identifier.

Parameters

query

link_identifier

If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if sybase_connect() was called, and use it.

Return Values

Returns a positive Sybase result identifier on success, FALSE on error, or TRUE if the query was successful but didn't return any columns.

See Also

  • sybase_select_db() - Selects a Sybase database
  • sybase_connect() - Opens a Sybase server connection


Get result data

  • « sybase_query
  • sybase_select_db »
  • PHP Manual
  • Sybase Functions
  • Get result data

sybase_result

(PHP 4, PHP 5)

sybase_result — Get result data

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_result ( resource $result , int $row , mixed $field ) : string

Returns the contents of the cell at the row and offset in the specified Sybase 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 sybase_result(). Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.

Recommended high-performance alternatives:
sybase_fetch_row(),
sybase_fetch_array() and
sybase_fetch_object().

Parameters

result

row

field

The field argument can be the field's offset, or the field's name, or the field's table dot field's name (tablename.fieldname). If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name.

Return Values

sybase_result() returns the contents of one cell from a Sybase result set.


Selects a Sybase database

  • « sybase_result
  • sybase_set_message_handler »
  • PHP Manual
  • Sybase Functions
  • Selects a Sybase database

sybase_select_db

(PHP 4, PHP 5)

sybase_select_db — Selects a Sybase database

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_select_db ( string $database_name [, resource $link_identifier ] ) : bool

sybase_select_db() sets the current active database on the server that's associated with the specified link identifier.

Every subsequent call to sybase_query() will be made on the active database.

Parameters

database_name

link_identifier

If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if sybase_connect() was called, and use it.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • sybase_connect() - Opens a Sybase server connection
  • sybase_pconnect() - Open persistent Sybase connection
  • sybase_query() - Sends a Sybase query


Sets the handler called when a server message is raised

  • « sybase_select_db
  • sybase_unbuffered_query »
  • PHP Manual
  • Sybase Functions
  • Sets the handler called when a server message is raised

sybase_set_message_handler

(PHP 4 >= 4.3.0, PHP 5)

sybase_set_message_handler — Sets the handler called when a server message is raised

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_set_message_handler ( callable $handler [, resource $link_identifier ] ) : bool

sybase_set_message_handler() sets a user function to handle messages generated by the server. You may specify the name of a global function, or use an array to specify an object reference and a method name.

Parameters

handler

The handler expects five arguments in the following order: message number, severity, state, line number and description. The first four are integers. The last is a string. If the function returns FALSE, PHP generates an ordinary error message.

link_identifier

If the link identifier isn't specified, the last opened link is assumed.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 sybase_set_message_handler() callback function

<?php
    function msg_handler($msgnumber, $severity, $state, $line, $text)
    {
        var_dump($msgnumber, $severity, $state, $line, $text);
    }

    sybase_set_message_handler('msg_handler');
?>

Example #2 sybase_set_message_handler() callback to a class

<?php
    class Sybase {
        function handler($msgnumber, $severity, $state, $line, $text)
        {
            var_dump($msgnumber, $severity, $state, $line, $text);
        }
    }

    $sybase= new Sybase();
    sybase_set_message_handler(array($sybase, 'handler'));
?>

Example #3 sybase_set_message_handler() unhandled messages

<?php
    // Return FALSE from this function to indicate you can't handle
    // this. The error is printed out as a warning, the way you're used
    // to it if there is no handler installed.
    function msg_handler($msgnumber, $severity, $state, $line, $text)
    {
        if (257 == $msgnumber) {
            return false;
        }
        var_dump($msgnumber, $severity, $state, $line, $text);
    }

    sybase_set_message_handler('msg_handler');
?>

Notes

Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.


Send a Sybase query and do not block

  • « sybase_set_message_handler
  • tokyo_tyrant »
  • PHP Manual
  • Sybase Functions
  • Send a Sybase query and do not block

sybase_unbuffered_query

(PHP 4 >= 4.3.0, PHP 5)

sybase_unbuffered_query — Send a Sybase query and do not block

Warning

This function was REMOVED in PHP 7.0.0.

Description

sybase_unbuffered_query ( string $query , resource $link_identifier [, bool $store_result ] ) : resource

sybase_unbuffered_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if sybase_connect() was called, and use it.

Unlike sybase_query(), sybase_unbuffered_query() reads only the first row of the result set. sybase_fetch_array() and similar function read more rows as needed. sybase_data_seek() reads up to the target row. The behavior may produce better performance for large result sets.

sybase_num_rows() will only return the correct number of rows if all result sets have been read. To Sybase, the number of rows is not known and is therefore computed by the client implementation.

Note:

If you don't read all of the resultsets prior to executing the next query, PHP will raise a warning and cancel all of the pending results. To get rid of this, use sybase_free_result() which will cancel pending results of an unbuffered query.

Parameters

query

link_identifier

store_result

The optional store_result can be FALSE to indicate the resultsets shouldn't be fetched into memory, thus minimizing memory usage which is particularly interesting with very large resultsets.

Return Values

Returns a positive Sybase result identifier on success, or FALSE on error.

Examples

Example #1 sybase_unbuffered_query() example

<?php

$dbh = sybase_connect('SYBASE', '', '');
$q = sybase_unbuffered_query('select firstname, lastname from huge_table', $dbh, false);
sybase_data_seek($q, 10000);
$i = 0;

while ($row = sybase_fetch_row($q)) {
    echo $row[0], ' ', $row[1], '<br />';
    if ($i++ > 40000) {
        break;
    }
}

sybase_free_result($q);
sybase_close($dbh);

?>

Notes

Note: This function is only available when using the CT library interface to Sybase, and not with the DB library.

See Also

  • sybase_query() - Sends a Sybase query


tokyo_tyrant

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • TokyoTyrant — The TokyoTyrant class
    • TokyoTyrant::add — Adds to a numeric key
    • TokyoTyrant::connect — Connect to a database
    • TokyoTyrant::connectUri — Connects to a database
    • TokyoTyrant::__construct — Construct a new TokyoTyrant object
    • TokyoTyrant::copy — Copies the database
    • TokyoTyrant::ext — Execute a remote script
    • TokyoTyrant::fwmKeys — Returns the forward matching keys
    • TokyoTyrant::get — The get purpose
    • TokyoTyrant::getIterator — Get an iterator
    • TokyoTyrant::num — Number of records in the database
    • TokyoTyrant::out — Removes records
    • TokyoTyrant::put — Puts values
    • TokyoTyrant::putCat — Concatenates to a record
    • TokyoTyrant::putKeep — Puts a record
    • TokyoTyrant::putNr — Puts value
    • TokyoTyrant::putShl — Concatenates to a record
    • TokyoTyrant::restore — Restore the database
    • TokyoTyrant::setMaster — Set the replication master
    • TokyoTyrant::size — Returns the size of the value
    • TokyoTyrant::stat — Get statistics
    • TokyoTyrant::sync — Synchronize the database
    • TokyoTyrant::tune — Tunes connection values
    • TokyoTyrant::vanish — Empties the database
  • TokyoTyrantTable — The TokyoTyrantTable class
    • TokyoTyrantTable::add — Adds a record
    • TokyoTyrantTable::genUid — Generate unique id
    • TokyoTyrantTable::get — Get a row
    • TokyoTyrantTable::getIterator — Get an iterator
    • TokyoTyrantTable::getQuery — Get a query object
    • TokyoTyrantTable::out — Remove records
    • TokyoTyrantTable::put — Store a row
    • TokyoTyrantTable::putCat — Concatenates to a row
    • TokyoTyrantTable::putKeep — Put a new record
    • TokyoTyrantTable::putNr — Puts value
    • TokyoTyrantTable::putShl — Concatenates to a record
    • TokyoTyrantTable::setIndex — Sets index
  • TokyoTyrantQuery — The TokyoTyrantQuery class
    • TokyoTyrantQuery::addCond — Adds a condition to the query
    • TokyoTyrantQuery::__construct — Construct a new query
    • TokyoTyrantQuery::count — Counts records
    • TokyoTyrantQuery::current — Returns the current element
    • TokyoTyrantQuery::hint — Get the hint string of the query
    • TokyoTyrantQuery::key — Returns the current key
    • TokyoTyrantQuery::metaSearch — Retrieve records with multiple queries
    • TokyoTyrantQuery::next — Moves the iterator to next entry
    • TokyoTyrantQuery::out — Removes records based on query
    • TokyoTyrantQuery::rewind — Rewinds the iterator
    • TokyoTyrantQuery::search — Searches records
    • TokyoTyrantQuery::setLimit — Limit results
    • TokyoTyrantQuery::setOrder — Orders results
    • TokyoTyrantQuery::valid — Checks the validity of current item
  • TokyoTyrantIterator — The TokyoTyrantIterator class
    • TokyoTyrantIterator::__construct — Construct an iterator
    • TokyoTyrantIterator::current — Get the current value
    • TokyoTyrantIterator::key — Returns the current key
    • TokyoTyrantIterator::next — Move to next key
    • TokyoTyrantIterator::rewind — Rewinds the iterator
    • TokyoTyrantIterator::valid — Rewinds the iterator
  • TokyoTyrantException — The TokyoTyrantException class


Introduction

tokyo_tyrant extension provides a wrapper for Tokyo Tyrant client libraries. The extension contains the normal key-value API and the table API.

"Tokyo Tyrant is a package of network interface to the DBM called Tokyo Cabinet. Though the DBM has high performance, you might bother in case that multiple processes share the same database, or remote processes access the database. Thus, Tokyo Tyrant is provided for concurrent and remote connections to Tokyo Cabinet. It is composed of the server process managing a database and its access library for client applications." --Tokyo Tyrant documentation

Tokyo Tyrant is written by Mikio Hirabayashi and is licensed under GNU Lesser General Public License.


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

Before using this extension Tokyo Cabinet and Tokyo Tyrant must be installed.


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/tokyo_tyrant

Configure options

  • --with-tokyo-tyrant[=DIR] DIR is the prefix to the Tokyo Tyrant installation
  • --with-tokyo-cabinet-dir[=DIR] DIR is the prefix to the Tokyo Cabinet installation
  • --disable-tokyo-tyrant-session Disable Tokyo Tyrant session handler support

Enabling the extension

The extension can be enabled by adding extension=tokyo_tyrant.so to the INI-configuration

Running Tokyo Tyrant for the session handler

ttserver -port 2000 -ext /path/to/expire.lua -extpc expire 30.0 '/tmp/sessions.tct#idx=ts:dec'

Note: expire.lua is included in the tokyo_tyrant extension source distribution

Configuring session handler

  • tokyo_tyrant.session_salt="randomlongstring"
  • session.save_handler=tokyo_tyrant
  • session.save_path="tcp://hostname1:2000,tcp://hostname2:2000"

Note: It is important to make sure that tokyo_tyrant.session_salt matches on all servers.

How it works?

The session handler creates a session id like the following: 8b0e27a823fa4a6cf7246945b82c1d51-a5eadbbed1f2075952900628456bfd6830541629-0-5460

The parts from left to right:

  • Session id - Generated session id
  • Checksum - Checksum of session salt, session id, node id and primary key
  • Node id - The id of the node where the session maps to
  • Primary key - The primary key of the row where the session is stored

The checksum contains SHA1 sum of the node id, primary key, session id and the salt which is known only on the server side. This allows quick mapping of session id to node and primary key since there is no need to do an additional search. During session id regeneration only the parts 1 and 2 change but the mapping to the node and primary key stays constant.

In case some of the nodes fail tokyo_tyrant.allow_failover, tokyo_tyrant.fail_threshold and tokyo_tyrant.health_check_divisor INI-settings control the behavior during failover. If failover is allowed the session handler will map the session to a healthy node and creates a new empty session.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

tokyo_tyrant Configure Options
Name | Default | Changeable | Changelog
tokyo_tyrant.default_timeout | 2.0 | PHP_INI_ALL |
tokyo_tyrant.session_salt | NULL | PHP_INI_ALL |
tokyo_tyrant.key_prefix | NULL | PHP_INI_ALL |
tokyo_tyrant.allow_failover | 1 | PHP_INI_ALL |
tokyo_tyrant.fail_threshold | 5 | PHP_INI_ALL |
tokyo_tyrant.health_check_divisor | 1000 | PHP_INI_ALL |
tokyo_tyrant.php_expiration | 0 | PHP_INI_ALL |

Here's a short explanation of the configuration directives.

tokyo_tyrant.default_timeout integer

Default timeout when connecting to databases

tokyo_tyrant.session_salt string

The secret that is used to salt session id

tokyo_tyrant.key_prefix string

Prefix all keys with this string. The prefix is transparent to the developer but helps making sure that keys won't collide if multiple applications are using the same database.

tokyo_tyrant.allow_failover integer

Whether to allow session failover in case a server dies.

tokyo_tyrant.fail_threshold integer

How many read/write or connection failures is allowed before server is marked as failed.

tokyo_tyrant.health_check_divisor integer

Defines the divisor for the health check probability. If there are failed servers and the probability matches, the servers are health checked and in case the server seems healthy, it will be added back to the pool.

tokyo_tyrant.php_expiration integer

Whether to use built in session expiration mechanism or delegate the expiration to a lua-script on the server-side.


  • « Resource Types
  • Examples »
  • PHP Manual
  • tokyo_tyrant
  • Predefined Constants

Predefined Constants

TokyoTyrant constants


Examples

Basic usage

Example #1 Putting and getting a key-value pair

<?php
$tt = new TokyoTyrant("localhost");
$tt->put("key", "value");
echo $tt->get("key");
?>

The above example will output:

value


The TokyoTyrant class

(PECL tokyo_tyrant >= 0.1.0)

Introduction

The main Tokyo Tyrant class

Class synopsis

TokyoTyrant {
/* Constants */
const integer RDBDEF_PORT = 1978 ;
const integer RDBQC_STREQ = 0 ;
const integer RDBQC_STRINC = 1 ;
const integer RDBQC_STRBW = 2 ;
const integer RDBQC_STREW = 3 ;
const integer RDBQC_STRAND = 4 ;
const integer RDBQC_STROR = 5 ;
const integer RDBQC_STROREQ = 6 ;
const integer RDBQC_STRRX = 7 ;
const integer RDBQC_NUMEQ = 8 ;
const integer RDBQC_NUMGT = 9 ;
const integer RDBQC_NUMGE = 10 ;
const integer RDBQC_NUMLT = 11 ;
const integer RDBQC_NUMLE = 12 ;
const integer RDBQC_NUMBT = 13 ;
const integer RDBQC_NUMOREQ = 14 ;
const integer RDBQC_NEGATE = 16777216 ;
const integer RDBQC_NOIDX = 33554432 ;
const integer RDBQO_STRASC = 0 ;
const integer RDBQO_STRDESC = 1 ;
const integer RDBQO_NUMASC = 2 ;
const integer RDBQO_NUMDESC = 3 ;
const integer RDBIT_LEXICAL = 0 ;
const integer RDBIT_DECIMAL = 1 ;
const integer RDBIT_TOKEN = 2 ;
const integer RDBIT_QGRAM = 3 ;
const integer RDBIT_OPT = 9998 ;
const integer RDBIT_VOID = 9999 ;
const integer RDBIT_KEEP = 16777216 ;
const integer RDBQCFTS_PH = 15 ;
const integer RDBQCFTS_AND = 16 ;
const integer RDBQCFTS_OR = 17 ;
const integer RDBQCFTS_EX = 18 ;
const integer RDBXO_LCKREC = 1 ;
const integer RDBXOLCK_GLB = 2 ;
const integer RDBREC_INT = 1 ;
const integer RDBREC_DBL = 2 ;
const integer RDBMS_UNION = 0 ;
const integer RDBMS_ISECT = 1 ;
const integer RDBMS_DIFF = 2 ;
const integer RDBT_RECON = 1 ;
/* Methods */
public add ( string $key , number $increment [, int $type = 0 ] ) : number
public connect ( string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]] ) : TokyoTyrant
public connectUri ( string $uri ) : TokyoTyrant
public __construct ([ string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]]] )
public copy ( string $path ) : TokyoTyrant
public ext ( string $name , int $options , string $key , string $value ) : string
public fwmKeys ( string $prefix , int $max_recs ) : array
public get ( mixed $keys ) : mixed
public getIterator ( void ) : TokyoTyrantIterator
public num ( void ) : int
public out ( mixed $keys ) : TokyoTyrant
public put ( mixed $keys [, string $value = NULL ] ) : TokyoTyrant
public putCat ( mixed $keys [, string $value ] ) : TokyoTyrant
public putKeep ( mixed $keys [, string $value ] ) : TokyoTyrant
public putNr ( mixed $keys [, string $value = NULL ] ) : TokyoTyrant
public putShl ( string $key , string $value , int $width ) : mixed
public restore ( string $log_dir , int $timestamp [, bool $check_consistency = TRUE ] ) : mixed
public setMaster ( string $host , int $port , int $timestamp [, bool $check_consistency = TRUE ] ) : mixed
public size ( string $key ) : int
public stat ( void ) : array
public sync ( void ) : mixed
public tune ( float $timeout [, int $options = TokyoTyrant::RDBT_RECON ] ) : TokyoTyrant
public vanish ( void ) : mixed
}

Predefined Constants

TokyoTyrant Constants

TokyoTyrant::RDBDEF_PORT

The default port of the Tokyo Tyrant database

TokyoTyrant::RDBQC_STREQ

string is equal to

TokyoTyrant::RDBQC_STRINC

string is included in

TokyoTyrant::RDBQC_STRBW

string begins with

TokyoTyrant::RDBQC_STREW

string ends with

TokyoTyrant::RDBQC_STRAND

string includes all tokens in

TokyoTyrant::RDBQC_STROR

string includes at least one token in

TokyoTyrant::RDBQC_STROREQ

string is equal to at least one token in

TokyoTyrant::RDBQC_STRRX

string matches regular expressions of

TokyoTyrant::RDBQC_NUMEQ

number is equal to

TokyoTyrant::RDBQC_NUMGT

number is greater than

TokyoTyrant::RDBQC_NUMGE

number is greater than or equal to

TokyoTyrant::RDBQC_NUMLT

number is less than

TokyoTyrant::RDBQC_NUMLE

number is less than or equal to

TokyoTyrant::RDBQC_NUMBT

number is between two tokens of

TokyoTyrant::RDBQC_NUMOREQ

number is equal to at least one token in

TokyoTyrant::RDBQC_NEGATE

negation flag

TokyoTyrant::RDBQC_NOIDX

no index flag

TokyoTyrant::RDBQO_STRASC

string ascending

TokyoTyrant::RDBQO_STRDESC

string descending

TokyoTyrant::RDBQO_NUMASC

number ascending

TokyoTyrant::RDBQO_NUMDESC

number descending

TokyoTyrant::RDBIT_LEXICAL

lexical string

TokyoTyrant::RDBIT_DECIMAL

decimal string

TokyoTyrant::RDBIT_TOKEN

token inverted index (Tokyo Tyrant >= 1.1.29)

TokyoTyrant::RDBIT_QGRAM

QGRAM inverted index (Tokyo Tyrant >= 1.1.29)

TokyoTyrant::RDBIT_OPT

optimize

TokyoTyrant::RDBIT_VOID

void

TokyoTyrant::RDBIT_KEEP

keep existing index

TokyoTyrant::RDBQCFTS_PH

full-text search with the phrase of (Tokyo Tyrant >= 1.1.29)

TokyoTyrant::RDBQCFTS_AND

full-text search with all tokens in (Tokyo Tyrant >= 1.1.29)

TokyoTyrant::RDBQCFTS_OR

full-text search with at least one token in (Tokyo Tyrant >= 1.1.29)

TokyoTyrant::RDBQCFTS_EX

full-text search with the compound expression of (Tokyo Tyrant >= 1.1.29)

TokyoTyrant::RDBQCFTS_AND

Metasearch union between records (Tokyo Tyrant >= 1.1.33)

TokyoTyrant::RDBQCFTS_OR

Metasearch intersection between records (Tokyo Tyrant >= 1.1.33)

TokyoTyrant::RDBQCFTS_EX

Metasearch difference between records (Tokyo Tyrant >= 1.1.33)

TokyoTyrant::RDBT_RECON

Whether to reconnect on connection failure. It is recommended to have this parameter on for persistent connections

TokyoTyrant::RDBXOLCK_REC

record locking

TokyoTyrant::RDBXOLCK_GLB

global locking

TokyoTyrant::RDBREC_INT

record type int

TokyoTyrant::RDBREC_DBL

record type float (double)

TokyoTyrant::TTE_SUCCESS

success

TokyoTyrant::TTE_INVALID

invalid operation

TokyoTyrant::TTE_NOHOST

host not found

TokyoTyrant::TTE_REFUSED

connection refused

TokyoTyrant::TTE_SEND

send error

TokyoTyrant::TTE_RECV

recv error

TokyoTyrant::TTE_KEEP

record exist

TokyoTyrant::TTE_NOREC

no record found

TokyoTyrant::TTE_MISC

miscellaneous error

Table of Contents

  • TokyoTyrant::add — Adds to a numeric key
  • TokyoTyrant::connect — Connect to a database
  • TokyoTyrant::connectUri — Connects to a database
  • TokyoTyrant::__construct — Construct a new TokyoTyrant object
  • TokyoTyrant::copy — Copies the database
  • TokyoTyrant::ext — Execute a remote script
  • TokyoTyrant::fwmKeys — Returns the forward matching keys
  • TokyoTyrant::get — The get purpose
  • TokyoTyrant::getIterator — Get an iterator
  • TokyoTyrant::num — Number of records in the database
  • TokyoTyrant::out — Removes records
  • TokyoTyrant::put — Puts values
  • TokyoTyrant::putCat — Concatenates to a record
  • TokyoTyrant::putKeep — Puts a record
  • TokyoTyrant::putNr — Puts value
  • TokyoTyrant::putShl — Concatenates to a record
  • TokyoTyrant::restore — Restore the database
  • TokyoTyrant::setMaster — Set the replication master
  • TokyoTyrant::size — Returns the size of the value
  • TokyoTyrant::stat — Get statistics
  • TokyoTyrant::sync — Synchronize the database
  • TokyoTyrant::tune — Tunes connection values
  • TokyoTyrant::vanish — Empties the database


Adds to a numeric key

  • « TokyoTyrant
  • TokyoTyrant::connect »
  • PHP Manual
  • TokyoTyrant
  • Adds to a numeric key

TokyoTyrant::add

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::add — Adds to a numeric key

Description

public TokyoTyrant::add ( string $key , number $increment [, int $type = 0 ] ) : number

Adds to an int or double value. This increments the value by the given amount and returns the new value. If the key does not exist a new key is created with initial value of the increment parameter.

Parameters

key

The string key

increment

The amount to increment

type

TokyoTyrant::RDBREC_INT or TokyoTyrant::RDBREC_DBL constant. If this parameter is omitted the type is guessed from the increment parameters type.

Return Values

Returns the new value on success

Examples

Example #1 TokyoTyrant::add() example

<?php
$tt = new TokyoTyrant("localhost", TokyoTyrant::RDBDEF_PORT);
/* Adds integer 3 to key and creates a new key */
$tt->add("test", 3);

/* String value is converted to double */
echo $tt->add("test", "3.5", TokyoTyrant::RDBREC_DBL);
?>

The above example will output something similar to:

6.5

See Also

  • TokyoTyrant::put() - Puts values
  • TokyoTyrant::putcat() - Concatenates to a record
  • TokyoTyrant::putkeep() - Puts a record


Connect to a database

  • « TokyoTyrant::add
  • TokyoTyrant::connectUri »
  • PHP Manual
  • TokyoTyrant
  • Connect to a database

TokyoTyrant::connect

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::connect — Connect to a database

Description

public TokyoTyrant::connect ( string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]] ) : TokyoTyrant

Connects to a remote database

Parameters

host

The hostname

port

The port. Default: 1978

options

Connection options: timeout (default: 5.0), reconnect (default: TRUE) and persistent (default: TRUE)

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::connect() example

<?php
$tt = new TokyoTyrant();
$tt->connect("localhost", TokyoTyrant::RDBDEF_PORT)->put("test", "value");
?>

See Also

  • TokyoTyrant::connectUri() - Connects to a database


Connects to a database

  • « TokyoTyrant::connect
  • TokyoTyrant::__construct »
  • PHP Manual
  • TokyoTyrant
  • Connects to a database

TokyoTyrant::connectUri

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::connectUri — Connects to a database

Description

public TokyoTyrant::connectUri ( string $uri ) : TokyoTyrant

Connects to a database using an uri

Parameters

uri

An URI to the database. For example tcp://localhost:1979/

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::connectUri() example

<?php
$tt = new TokyoTyrant();
$tt->connectUri("tcp://localhost:1978/")->put("test", "hi");
?>

See Also

  • TokyoTyrant::connect() - Connect to a database


Construct a new TokyoTyrant object

  • « TokyoTyrant::connectUri
  • TokyoTyrant::copy »
  • PHP Manual
  • TokyoTyrant
  • Construct a new TokyoTyrant object

TokyoTyrant::__construct

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::__construct — Construct a new TokyoTyrant object

Description

public TokyoTyrant::__construct ([ string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]]] )

Constructs a new TokyoTyrant object and optionally connects to the database

Parameters

host

The hostname. Default: NULL

port

port number. Default: 1978

options

Connection options: timeout (default: 5.0), reconnect (default: TRUE) and persistent (default: TRUE)

Return Values

Throws TokyoTyrantException if connection to database fails

See Also

  • TokyoTyrant::connect() - Connect to a database
  • TokyoTyrant::connectUri() - Connects to a database


Copies the database

  • « TokyoTyrant::__construct
  • TokyoTyrant::ext »
  • PHP Manual
  • TokyoTyrant
  • Copies the database

TokyoTyrant::copy

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::copy — Copies the database

Description

public TokyoTyrant::copy ( string $path ) : TokyoTyrant

Makes a copy of the current database

Parameters

path

Path to where to copy the database. The user running the remote database must have a write access to the directory.

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::copy() example

<?php
$tt = new TokyoTyrant("localhost", 1978);
$tt->copy("/tmp/foobar.tct");
?>

See Also

  • TokyoTyrant::restore() - Restore the database


Execute a remote script

  • « TokyoTyrant::copy
  • TokyoTyrant::fwmKeys »
  • PHP Manual
  • TokyoTyrant
  • Execute a remote script

TokyoTyrant::ext

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::ext — Execute a remote script

Description

public TokyoTyrant::ext ( string $name , int $options , string $key , string $value ) : string

Executes a remote script extension.

Parameters

name

Name of the function to execute

options

Either TokyoTyrant::RDBXO_LCKREC for record locking and TokyoTyrant::RDBXO_LCKGLB for global locking.

key

The key to pass to the function

value

The value to pass to the function

Return Values

Returns the result of the script function

Examples

Example #1 TokyoTyrant::ext() example

<?php
$tt = new TokyoTyrant("localhost", 1978);
echo $tt->ext("somefunc", TokyoTyrant::RDBXO_LCKREC, "some_key", "some_value");
?>


Returns the forward matching keys

  • « TokyoTyrant::ext
  • TokyoTyrant::get »
  • PHP Manual
  • TokyoTyrant
  • Returns the forward matching keys

TokyoTyrant::fwmKeys

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::fwmKeys — Returns the forward matching keys

Description

public TokyoTyrant::fwmKeys ( string $prefix , int $max_recs ) : array

Returns the forward matching keys from the database

Parameters

prefix

Prefix of the keys

max_recs

Maximum records to return

Return Values

Returns an array of matching keys. The values are not returned

Examples

Example #1 TokyoTyrant::fwmKeys() example

<?php

$tt = new TokyoTyrant("localhost");

/* Create 20 macthing keys */
for ($i = 0; $i < 20; $i++) {
    $tt->put("key_" . $i, "value_" . $i);
}

/* Create 20 non-macthing keys */
for ($i = 0; $i < 20; $i++) {
    $tt->put("something_" . $i, "data_" . $i);
}

/* Get five matching keys */
var_dump($tt->fwmKeys("key_", 5));
?>

The above example will output something similar to:

array(5) {
  [0]=>
  string(5) "key_5"
  [1]=>
  string(6) "key_14"
  [2]=>
  string(5) "key_6"
  [3]=>
  string(6) "key_15"
  [4]=>
  string(5) "key_7"
}


The get purpose

  • « TokyoTyrant::fwmKeys
  • TokyoTyrant::getIterator »
  • PHP Manual
  • TokyoTyrant
  • The get purpose

TokyoTyrant::get

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::get — The get purpose

Description

public TokyoTyrant::get ( mixed $keys ) : mixed

This method is used to return a value or multiple values. This method accepts a string or an array as a value.

Parameters

keys

A string key or an array of string keys

Return Values

Returns a string or an array based on the given parameters. Throws a TokyoTyrantException on error. If string is passed null is returned if the key is not found. In case an array is given as an parameter only existing keys will be returned. It is not an error to pass a key that does not exist.

Examples

Example #1 TokyoTyrant::get() example

<?php
$tt = new TokyoTyrant("localhost", 1978);
$tt->put("key1", "value1");
$tt->put("key2", "value2");
var_dump($tt->get(array("key1", "key2")));
var_dump($tt->get("key1"));
?>

The above example will output:

array(2) {
  ["key1"]=>
  string(6) "value1"
  ["key2"]=>
  string(6) "value2"
}
string(6) "value1"

See Also

  • TokyoTyrant::put() - Puts values


Get an iterator

  • « TokyoTyrant::get
  • TokyoTyrant::num »
  • PHP Manual
  • TokyoTyrant
  • Get an iterator

TokyoTyrant::getIterator

(No version information available, might only be in Git)

TokyoTyrant::getIterator — Get an iterator

Description

public TokyoTyrant::getIterator ( void ) : TokyoTyrantIterator

Gets an iterator for iterating all keys / values in the database.

Parameters

This function has no parameters.

Return Values

This method returns TokyoTyrantIterator object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::getIterator() example

<?php
$tt = new TokyoTyrant("localhost");
$it = $tt->getIterator();

foreach ($it as $k => $v) {

}
?>

See Also

  • TokyoTyrantTable::getQuery() - Get a query object
  • TokyoTyrantTable::getIterator() - Get an iterator


Number of records in the database

  • « TokyoTyrant::getIterator
  • TokyoTyrant::out »
  • PHP Manual
  • TokyoTyrant
  • Number of records in the database

TokyoTyrant::num

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::num — Number of records in the database

Description

public TokyoTyrant::num ( void ) : int

Returns the number of records in the database

Parameters

This function has no parameters.

Return Values

Returns number of records in the database

Examples

Example #1 TokyoTyrant::num() example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

/* Echo the number of records */
echo $tt->num();
?>

The above example will output something similar to:

1234

See Also

  • TokyoTyrant::stat() - Get statistics


Removes records

  • « TokyoTyrant::num
  • TokyoTyrant::put »
  • PHP Manual
  • TokyoTyrant
  • Removes records

TokyoTyrant::out

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::out — Removes records

Description

public TokyoTyrant::out ( mixed $keys ) : TokyoTyrant

Removes a record or multiple records. This method accepts a string for a single key or an array of keys for multiple records.

Parameters

keys

A string key or an array of string keys

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::out() example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

$tt->put("test1", "value1");
$tt->put("test2", "value2");

$tt->out(array("test1", "test2"));
?>

See Also

  • TokyoTyrant::put() - Puts values


Puts values

  • « TokyoTyrant::out
  • TokyoTyrant::putCat »
  • PHP Manual
  • TokyoTyrant
  • Puts values

TokyoTyrant::put

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::put — Puts values

Description

public TokyoTyrant::put ( mixed $keys [, string $value = NULL ] ) : TokyoTyrant

Puts a key-value pair into the database or multiple key-value pairs. If keys is string then the second parameter value defines the value. The second parameter is mandatory if keys is a string. If the key exists the value will be replaced with new value.

Parameters

keys

A string key or an array of key-value pairs

value

The value in case a string key is used

Return Values

This method returns a reference to the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::put() example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

/* Put single key-value pair */
$tt->put("key", "value");

/* Put key-value pairs, new value overwrites the old */
$tt->put(array("key1" => "value1", "key" => "value2"));

/* Get back one key */
echo $tt->get("key");
?>

The above example will output:

value2

See Also

  • TokyoTyrant::putKeep() - Puts a record
  • TokyoTyrant::putCat() - Concatenates to a record


Concatenates to a record

  • « TokyoTyrant::put
  • TokyoTyrant::putKeep »
  • PHP Manual
  • TokyoTyrant
  • Concatenates to a record

TokyoTyrant::putCat

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::putCat — Concatenates to a record

Description

public TokyoTyrant::putCat ( mixed $keys [, string $value ] ) : TokyoTyrant

Appends a value into existing key or multiple values if keys is an array. The second parameter is mandatory if keys is a string. If the record does not exist a new record is created.

Parameters

keys

A string key or an array of key-value pairs

value

The value in case a string key is used

Return Values

This method returns a reference to the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::putCat() example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

/* Create a new key */
$tt->put("key", "value");

/* Concatenate single key-value pair */
$tt->putCat("key", " has more data");

/* Echo the key */
echo $tt->get("key");
?>

The above example will output:

value has more data

See Also

  • TokyoTyrant::put() - Puts values
  • TokyoTyrant::putKeep() - Puts a record


Puts a record

  • « TokyoTyrant::putCat
  • TokyoTyrant::putNr »
  • PHP Manual
  • TokyoTyrant
  • Puts a record

TokyoTyrant::putKeep

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::putKeep — Puts a record

Description

public TokyoTyrant::putKeep ( mixed $keys [, string $value ] ) : TokyoTyrant

Puts a key-value pair into the database or multiple key-value pairs. If keys is string then the second parameter value defines the value. The second parameter is mandatory if keys is a string. If the key already exists this method throws an exception indicating that the records exists.

Parameters

keys

A string key or an array of key-value pairs

value

The string value

Return Values

This method returns a reference to the current object and throws TokyoTyrantException on failure.

Examples

Example #1 tokyotyrant::putKeep() example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

/* Create a new key */
$tt->put("key", "value");

try {
    $tt->putKeep("key", "new value");
} catch (TokyoTyrantException $e) {
    if ($e->getCode() === TokyoTyrant::TTE_KEEP) {
        echo "Existing record! Not modified\n";
    } else {
        echo "Error: " , $e->getMessage() , "\n";
    }
}
echo $tt->get("key");
?>

The above example will output:

Existing record! Not modified
value

See Also

  • TokyoTyrant::put() - Puts values
  • TokyoTyrant::putCat() - Concatenates to a record


Puts value

  • « TokyoTyrant::putKeep
  • TokyoTyrant::putShl »
  • PHP Manual
  • TokyoTyrant
  • Puts value

TokyoTyrant::putNr

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::putNr — Puts value

Description

public TokyoTyrant::putNr ( mixed $keys [, string $value = NULL ] ) : TokyoTyrant

Puts a key-value pair into the database or multiple key-value pairs. If keys is string then the second parameter value defines the value. The second parameter is mandatory if keys is a string. This method does not wait for the response from the server.

Parameters

keys

A string key or an array of key-value pairs

value

The value in case a string key is used

Return Values

This method returns a reference to the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::putNr() example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

/* Put single key-value pair */
$tt->putNr("key", "value");

/* Put key-value pairs */
$tt->putNr(array("key1" => "value1", "key2" => "value2"));

/* Get back one key */
echo $tt->get("key1");
?>

The above example will output:

value1

See Also

  • TokyoTyrant::putNr()
  • TokyoTyrant::putKeep() - Puts a record
  • TokyoTyrant::putCat() - Concatenates to a record


Concatenates to a record

  • « TokyoTyrant::putNr
  • TokyoTyrant::restore »
  • PHP Manual
  • TokyoTyrant
  • Concatenates to a record

TokyoTyrant::putShl

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::putShl — Concatenates to a record

Description

public TokyoTyrant::putShl ( string $key , string $value , int $width ) : mixed

Concatenate to a record and shift to left.

Parameters

key

A string key

value

The value to concatenate

width

The width of the record

Return Values

This method returns a reference to the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::putShl() example

<?php
/* Connect to a database on default port */
$tt = new TokyoTyrant("localhost");

/* Create a new key */
$tt->put("key", "just a long piece of data");

/* Concatenate and shift to left */
$tt->putShl("key", " and string", 15);

/* Echo the key */
echo $tt->get("key");
?>

The above example will output:

data and string

See Also

  • TokyoTyrant::put() - Puts values
  • TokyoTyrant::putKeep() - Puts a record
  • TokyoTyrant::putCat() - Concatenates to a record


Restore the database

  • « TokyoTyrant::putShl
  • TokyoTyrant::setMaster »
  • PHP Manual
  • TokyoTyrant
  • Restore the database

TokyoTyrant::restore

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::restore — Restore the database

Description

public TokyoTyrant::restore ( string $log_dir , int $timestamp [, bool $check_consistency = TRUE ] ) : mixed

Restore the database from the update log.

Warning

This method is not supported on 32bit platforms.

Parameters

log_dir

Directory where the log is

timestamp

Beginning timestamp with microseconds

check_consistency

Whether to check consistency: Default: TRUE

Return Values

This method returns the current object and throws TokyoTyrantException on failure.


Set the replication master

  • « TokyoTyrant::restore
  • TokyoTyrant::size »
  • PHP Manual
  • TokyoTyrant
  • Set the replication master

TokyoTyrant::setMaster

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::setMaster — Set the replication master

Description

public TokyoTyrant::setMaster ( string $host , int $port , int $timestamp [, bool $check_consistency = TRUE ] ) : mixed

Sets the replication master of the database

Warning

This method is not supported on 32bit platforms.

Parameters

host

Hostname of the replication master. If NULL the replication is disabled.

port

Port of the replication master

timestamp

Beginning timestamp with microseconds

check_consistency

Whether to check consistency.

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::setMaster() example

<?php
/* Connect to a database */
$tt = new TokyoTyrant("tokyotyrant.example.com");

/* Disable the replication */
$tt->setMaster(NULL, 0, 0);
?>

See Also

  • Classname::Method()


Returns the size of the value

  • « TokyoTyrant::setMaster
  • TokyoTyrant::stat »
  • PHP Manual
  • TokyoTyrant
  • Returns the size of the value

TokyoTyrant::size

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::size — Returns the size of the value

Description

public TokyoTyrant::size ( string $key ) : int

Returns the size of a value by key

Parameters

key

The key of which size to fetch

Return Values

Returns the size of the key or throw TokyoTyrantException on error

Examples

Example #1 TokyoTyrant::size() example

<?php
$tt = new TokyoTyrant("localhost");

$tt->put("test_key", "12345");

echo $tt->size("test_key");
?>

The above example will output:

5


Get statistics

  • « TokyoTyrant::size
  • TokyoTyrant::sync »
  • PHP Manual
  • TokyoTyrant
  • Get statistics

TokyoTyrant::stat

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::stat — Get statistics

Description

public TokyoTyrant::stat ( void ) : array

Returns statistics of the remote database

Parameters

This function has no parameters.

Return Values

Returns an array of key value pairs describing the statistics

Examples

Example #1 TokyoTyrant::stat() example

<?php
$tt = new TokyoTyrant("localhost");

var_dump($tt->stat());
?>

The above example will output something similar to:

array(19) {
  ["version"]=>
  string(6) "1.1.28"
  ["libver"]=>
  string(3) "311"
  ["protver"]=>
  string(4) "0.91"
  ["os"]=>
  string(5) "Linux"
  ["time"]=>
  string(17) "1247358357.665630"
  ["pid"]=>
  string(5) "14348"
  ["sid"]=>
  string(8) "59025947"
  ["type"]=>
  string(9) "on-memory"
  ["path"]=>
  string(1) "*"
  ["rnum"]=>
  string(1) "4"
  ["size"]=>
  string(6) "262856"
  ["bigend"]=>
  string(1) "0"
  ["fd"]=>
  string(1) "5"
  ["loadavg"]=>
  string(8) "0.000000"
  ["memsize"]=>
  string(8) "77328384"
  ["memrss"]=>
  string(7) "1183744"
  ["ru_real"]=>
  string(13) "162776.042152"
  ["ru_user"]=>
  string(8) "0.476029"
  ["ru_sys"]=>
  string(8) "8.652540"
}

See Also

  • Classname::Method()


Synchronize the database

  • « TokyoTyrant::stat
  • TokyoTyrant::tune »
  • PHP Manual
  • TokyoTyrant
  • Synchronize the database

TokyoTyrant::sync

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::sync — Synchronize the database

Description

public TokyoTyrant::sync ( void ) : mixed

Synchronizes the database on to the physical device

Parameters

This function has no parameters.

Return Values

This method returns the current object and throws TokyoTyrantException on failure.


Tunes connection values

  • « TokyoTyrant::sync
  • TokyoTyrant::vanish »
  • PHP Manual
  • TokyoTyrant
  • Tunes connection values

TokyoTyrant::tune

(PECL tokyo_tyrant >= 0.2.0)

TokyoTyrant::tune — Tunes connection values

Description

public TokyoTyrant::tune ( float $timeout [, int $options = TokyoTyrant::RDBT_RECON ] ) : TokyoTyrant

Tunes database connection options.

Parameters

timeout

The objects timeout value (default: 5.0)

options

Bitmask of options to tune. This can be either 0 or TokyoTyrant::RDBT_RECON. It is recommended not to change the second parameter.

Return Values

This method returns a reference to the current object and throws TokyoTyrantException on failure.


Empties the database

  • « TokyoTyrant::tune
  • TokyoTyrantTable »
  • PHP Manual
  • TokyoTyrant
  • Empties the database

TokyoTyrant::vanish

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrant::vanish — Empties the database

Description

public TokyoTyrant::vanish ( void ) : mixed

Empties a remote database

Parameters

This function has no parameters.

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrant::vanish() example

<?php
$tt = new TokyoTyrant("localhost");
$tt->vanish();
?>

See Also

  • TokyoTyrant::out() - Removes records


The TokyoTyrantTable class

(PECL tokyo_tyrant >= 0.1.0)

Introduction

Provides an API to the table databases. A table database can be create using the following command: ttserver -port 1979 /tmp/tt_table.tct. In Tokyo Tyrant the table API is a schemaless database which can store arbitrary amount of key-value pairs under a single primary key.

Class synopsis

TokyoTyrantTable extends TokyoTyrant {
/* Methods */
public add ( string $key , mixed $increment [, string $type ] ) : void
public genUid ( void ) : int
public get ( mixed $keys ) : array
public getIterator ( void ) : TokyoTyrantIterator
public getQuery ( void ) : TokyoTyrantQuery
public out ( mixed $keys ) : void
public put ( string $key , array $columns ) : int
public putCat ( string $key , array $columns ) : void
public putKeep ( string $key , array $columns ) : void
public putNr ( mixed $keys [, string $value ] ) : void
public putShl ( string $key , string $value , int $width ) : void
public setIndex ( string $column , int $type ) : mixed
/* Inherited methods */
public TokyoTyrant::add ( string $key , number $increment [, int $type = 0 ] ) : number
public TokyoTyrant::connect ( string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]] ) : TokyoTyrant
public TokyoTyrant::connectUri ( string $uri ) : TokyoTyrant
public TokyoTyrant::__construct ([ string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]]] )
public TokyoTyrant::copy ( string $path ) : TokyoTyrant
public TokyoTyrant::ext ( string $name , int $options , string $key , string $value ) : string
public TokyoTyrant::fwmKeys ( string $prefix , int $max_recs ) : array
public TokyoTyrant::get ( mixed $keys ) : mixed
public TokyoTyrant::getIterator ( void ) : TokyoTyrantIterator
public TokyoTyrant::num ( void ) : int
public TokyoTyrant::out ( mixed $keys ) : TokyoTyrant
public TokyoTyrant::put ( mixed $keys [, string $value = NULL ] ) : TokyoTyrant
public TokyoTyrant::putCat ( mixed $keys [, string $value ] ) : TokyoTyrant
public TokyoTyrant::putKeep ( mixed $keys [, string $value ] ) : TokyoTyrant
public TokyoTyrant::putNr ( mixed $keys [, string $value = NULL ] ) : TokyoTyrant
public TokyoTyrant::putShl ( string $key , string $value , int $width ) : mixed
public TokyoTyrant::restore ( string $log_dir , int $timestamp [, bool $check_consistency = TRUE ] ) : mixed
public TokyoTyrant::setMaster ( string $host , int $port , int $timestamp [, bool $check_consistency = TRUE ] ) : mixed
public TokyoTyrant::size ( string $key ) : int
public TokyoTyrant::stat ( void ) : array
public TokyoTyrant::sync ( void ) : mixed
public TokyoTyrant::tune ( float $timeout [, int $options = TokyoTyrant::RDBT_RECON ] ) : TokyoTyrant
public TokyoTyrant::vanish ( void ) : mixed
}

Table of Contents

  • TokyoTyrantTable::add — Adds a record
  • TokyoTyrantTable::genUid — Generate unique id
  • TokyoTyrantTable::get — Get a row
  • TokyoTyrantTable::getIterator — Get an iterator
  • TokyoTyrantTable::getQuery — Get a query object
  • TokyoTyrantTable::out — Remove records
  • TokyoTyrantTable::put — Store a row
  • TokyoTyrantTable::putCat — Concatenates to a row
  • TokyoTyrantTable::putKeep — Put a new record
  • TokyoTyrantTable::putNr — Puts value
  • TokyoTyrantTable::putShl — Concatenates to a record
  • TokyoTyrantTable::setIndex — Sets index


Adds a record

  • « TokyoTyrantTable
  • TokyoTyrantTable::genUid »
  • PHP Manual
  • TokyoTyrantTable
  • Adds a record

TokyoTyrantTable::add

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::add — Adds a record

Description

public TokyoTyrantTable::add ( string $key , mixed $increment [, string $type ] ) : void

This method is not supported with table databases.

Parameters

key

The string key

increment

The amount to increment

type

TokyoTyrant::RDB_RECINT or TokyoTyrant::RDB_RECDBL constant. If this parameter is omitted the type is guessed from the increment parameters type.

Return Values

This method throws an TokyoTyrantException if used through this class.

See Also

  • TokyoTyrant::add() - Adds to a numeric key


Generate unique id

  • « TokyoTyrantTable::add
  • TokyoTyrantTable::get »
  • PHP Manual
  • TokyoTyrantTable
  • Generate unique id

TokyoTyrantTable::genUid

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::genUid — Generate unique id

Description

public TokyoTyrantTable::genUid ( void ) : int

Generates an unique id inside the table database. In table databases rows are referenced using a numeric primary key.

Parameters

This function has no parameters.

Return Values

Returns an unique id or throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantTable::genUid() example

<?php
$tt = new TokyoTyrantTable("localhost", 1122);

echo $tt->genUid();
?>

The above example will output something similar to:

4

See Also

  • TokyoTyrantTable::put() - Store a row


Get a row

  • « TokyoTyrantTable::genUid
  • TokyoTyrantTable::getIterator »
  • PHP Manual
  • TokyoTyrantTable
  • Get a row

TokyoTyrantTable::get

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::get — Get a row

Description

public TokyoTyrantTable::get ( mixed $keys ) : array

Gets a row from table database. keys is a single integer for the primary key of the row or an array of integers for multiple rows.

Parameters

keys

The primary key, can be a string or an integer

Return Values

Returns the row as an array

Examples

Example #1 TokyoTyrantTable::get() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Passing null to put generates a new uid */
$index = $tt->put(null, array("column1" => "some data", "column2" => "more data"));

/* Get the row back */
var_dump($tt->get($index));
?>

The above example will output:

array(2) {
  ["column1"]=>
  string(9) "some data"
  ["column2"]=>
  string(9) "more data"
}

Notes

Note:

Starting from version 0.3.0 this method accepts array as parameter. Please note that multi-get on tables is not binary-safe.

See Also

  • TokyoTyrantTable::put() - Store a row


Get an iterator

  • « TokyoTyrantTable::get
  • TokyoTyrantTable::getQuery »
  • PHP Manual
  • TokyoTyrantTable
  • Get an iterator

TokyoTyrantTable::getIterator

(No version information available, might only be in Git)

TokyoTyrantTable::getIterator — Get an iterator

Description

public TokyoTyrantTable::getIterator ( void ) : TokyoTyrantIterator

Gets an iterator for iterating all keys / values in the database.

Parameters

This function has no parameters.

Return Values

This method returns TokyoTyrantIterator object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrantTable::getIterator() example

<?php
$tt = new TokyoTyrantTable("localhost");
$it = $tt->getIterator();

foreach ($it as $k => $v) {
  var_dump($k, $v);
}
?>

See Also

  • TokyoTyrantTable::getQuery() - Get a query object
  • TokyoTyrant::getIterator() - Get an iterator


Get a query object

  • « TokyoTyrantTable::getIterator
  • TokyoTyrantTable::out »
  • PHP Manual
  • TokyoTyrantTable
  • Get a query object

TokyoTyrantTable::getQuery

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::getQuery — Get a query object

Description

public TokyoTyrantTable::getQuery ( void ) : TokyoTyrantQuery

Get a query object to execute searches on the database

Parameters

This function has no parameters.

Return Values

Returns TokyoTyrantQuery on success and throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantTable::getQuery() example

<?php
/* Connect to a table database */
$table = new TokyoTyrantTable("localhost", 1979);

/* Put a few rows */
$table->put(null, array("column1" => "some data", "column2" => "more data"));
$table->put(null, array("something" => "value", "data" => "good data"));

/* Get query object */
$query = $table->getQuery();

/* Add condition to query */
$query->addCond('data', TokyoTyrant::RDBQC_STREQ, 'good data');

/* Get matching rows */
var_dump($query->search());
?>

The above example will output something similar to:

array(1) {
  [11]=>
  array(2) {
    ["something"]=>
    string(5) "value"
    ["data"]=>
    string(9) "good data"
  }
}

See Also

  • TokyoTyrantQuery::search() - Searches records
  • TokyoTyrantQuery::out() - Removes records based on query


Remove records

  • « TokyoTyrantTable::getQuery
  • TokyoTyrantTable::put »
  • PHP Manual
  • TokyoTyrantTable
  • Remove records

TokyoTyrantTable::out

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::out — Remove records

Description

public TokyoTyrantTable::out ( mixed $keys ) : void

Removes records from a table database.

Parameters

keys

A single integer key or an array of integers

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrantTable::out() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Passing null to put generates a new uid */
$index = $tt->put(null, array("column1" => "some data", "column2" => "more data"));

/* Delete the row */
$tt->out($index);
?>

See Also

  • TokyoTyrantTable::put() - Store a row


Store a row

  • « TokyoTyrantTable::out
  • TokyoTyrantTable::putCat »
  • PHP Manual
  • TokyoTyrantTable
  • Store a row

TokyoTyrantTable::put

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::put — Store a row

Description

public TokyoTyrantTable::put ( string $key , array $columns ) : int

Puts a new row into the database. This method parameters are key which is the primary key of the row, passing NULL will generate a new unique id. value is an array containing the row contents which is usually key value pairs.

Parameters

key

The primary key of the row

columns

The row contents

Return Values

Returns the primary key on success and throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantTable::put() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Passing null to put generates a new uid */
$index = $tt->put(null, array("column1" => "some data", "column2" => "more data"));

/* Get the row back */
var_dump($tt->get($index));

/* Modify an existing row */
$tt->put($index, array("column1" => "other data", "column2" => "better data"));

/* Get the row back */
var_dump($tt->get($index));
?>

The above example will output:

array(2) {
  ["column1"]=>
  string(9) "some data"
  ["column2"]=>
  string(9) "more data"
}
array(2) {
  ["column1"]=>
  string(10) "other data"
  ["column2"]=>
  string(11) "better data"
}

See Also

  • TokyoTyrantTable::get() - Get a row


Concatenates to a row

  • « TokyoTyrantTable::put
  • TokyoTyrantTable::putKeep »
  • PHP Manual
  • TokyoTyrantTable
  • Concatenates to a row

TokyoTyrantTable::putCat

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::putCat — Concatenates to a row

Description

public TokyoTyrantTable::putCat ( string $key , array $columns ) : void

This method can be used to add new columns to existing records. Existing keys will be left unmodified but any new columns will be appended to the row. Passing null as key will generate a new row.

Parameters

key

The primary key of the row or NULL

columns

Array of row contents

Return Values

Returns the primary key and throws TokyoTyrantException on error.

Examples

Example #1 TokyoTyrantTable::putCat() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Passing null to put generates a new uid */
$index = $tt->put(null, array("column1" => "some data", "column2" => "more data"));

/* Get the row back */
var_dump($tt->get($index));

/* Modify an existing row */
$tt->putcat($index, array("column1" => "something new", "new_column" => "other data"));

/* Get the row back */
var_dump($tt->get($index));
?>

The above example will output:

array(2) {
  ["column1"]=>
  string(9) "some data"
  ["column2"]=>
  string(9) "more data"
}
array(3) {
  ["column1"]=>
  string(9) "some data"
  ["column2"]=>
  string(9) "more data"
  ["new_column"]=>
  string(10) "other data"
}

See Also

  • TokyoTyrantTable::put() - Store a row


Put a new record

  • « TokyoTyrantTable::putCat
  • TokyoTyrantTable::putNr »
  • PHP Manual
  • TokyoTyrantTable
  • Put a new record

TokyoTyrantTable::putKeep

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::putKeep — Put a new record

Description

public TokyoTyrantTable::putKeep ( string $key , array $columns ) : void

Puts a new record into the database. If the key already exists this method throws an exception indicating that the records exists.

Parameters

key

The primary key of the row or NULL

columns

Array of the row contents

Return Values

Returns the primary key and throws TokyoTyrantException on error.

Examples

Example #1 TokyoTyrantTable::putKeep() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Passing null to put generates a new uid */
$index = $tt->put(null, array("column1" => "some data", "column2" => "more data"));

/* Get the row back */
var_dump($tt->get($index));

try {
    $tt->putKeep($index, array("column1" => "something new", "new_column" => "other data"));
} catch (TokyoTyrantException $e) {
    if ($e->getCode() === TokyoTyrant::TTE_KEEP) {
        echo "Existing record! Not modified\n";
    } else {
        echo "Error: " , $e->getMessage() , "\n";
    }
}

/* Get the row back */
var_dump($tt->get($index));
?>

The above example will output something similar to:

array(2) {
  ["column1"]=>
  string(9) "some data"
  ["column2"]=>
  string(9) "more data"
}
Existing record! Not modified
array(2) {
  ["column1"]=>
  string(9) "some data"
  ["column2"]=>
  string(9) "more data"
}

See Also

  • TokyoTyrantTable::put() - Store a row


Puts value

  • « TokyoTyrantTable::putKeep
  • TokyoTyrantTable::putShl »
  • PHP Manual
  • TokyoTyrantTable
  • Puts value

TokyoTyrantTable::putNr

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::putNr — Puts value

Description

public TokyoTyrantTable::putNr ( mixed $keys [, string $value ] ) : void

This method is not supported on table databases. Calling this method through TokyoTyrantTable is considered an error and an TokyoTyrantException will be thrown.

Parameters

keys

A string key or an array of key-value pairs

value

The value in case a string key is used

Return Values

This method is not supported on table databases. Calling this method through TokyoTyrantTable is considered an error and an TokyoTyrantException will be thrown.

See Also

  • TokyoTyrant::putNr() - Puts value
  • TokyoTyrant::putKeep() - Puts a record
  • TokyoTyrant::putCat() - Concatenates to a record


Concatenates to a record

  • « TokyoTyrantTable::putNr
  • TokyoTyrantTable::setIndex »
  • PHP Manual
  • TokyoTyrantTable
  • Concatenates to a record

TokyoTyrantTable::putShl

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::putShl — Concatenates to a record

Description

public TokyoTyrantTable::putShl ( string $key , string $value , int $width ) : void

This method is not supported on table databases. Calling this method through TokyoTyrantTable is considered an error and an TokyoTyrantException will be thrown.

Parameters

key

A string key

value

The value to concatenate

width

The width of the record

Return Values

This method is not supported on table databases.

See Also

  • TokyoTyrant::put() - Puts values
  • TokyoTyrant::putKeep() - Puts a record
  • TokyoTyrant::putCat() - Concatenates to a record
  • TokyoTyrantTable::put() - Store a row
  • TokyoTyrantTable::putKeep() - Put a new record
  • TokyoTyrantTable::putCat() - Concatenates to a row


Sets index

  • « TokyoTyrantTable::putShl
  • TokyoTyrantQuery »
  • PHP Manual
  • TokyoTyrantTable
  • Sets index

TokyoTyrantTable::setIndex

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantTable::setIndex — Sets index

Description

public TokyoTyrantTable::setIndex ( string $column , int $type ) : mixed

Sets an index on a specified column. The index type is one of the TokyoTyrant::RDBIT_* constants. Passing TokyoTyrant::RDBIT_VOID removes the index.

Parameters

column

The name of the column

type

The index type

Return Values

This method returns the current object and throws TokyoTyrantException on failure.


The TokyoTyrantQuery class

(PECL tokyo_tyrant >= 0.1.0)

Introduction

This class is used to query the table databases

Class synopsis

TokyoTyrantQuery implements Iterator {
/* Methods */
public addCond ( string $name , int $op , string $expr ) : mixed
public __construct ( TokyoTyrantTable $table )
public count ( void ) : int
public current ( void ) : array
public hint ( void ) : string
public key ( void ) : string
public metaSearch ( array $queries , int $type ) : array
public next ( void ) : array
public out ( void ) : TokyoTyrantQuery
public rewind ( void ) : bool
public search ( void ) : array
public setLimit ([ int $max [, int $skip ]] ) : mixed
public setOrder ( string $name , int $type ) : mixed
public valid ( void ) : bool
}

Table of Contents

  • TokyoTyrantQuery::addCond — Adds a condition to the query
  • TokyoTyrantQuery::__construct — Construct a new query
  • TokyoTyrantQuery::count — Counts records
  • TokyoTyrantQuery::current — Returns the current element
  • TokyoTyrantQuery::hint — Get the hint string of the query
  • TokyoTyrantQuery::key — Returns the current key
  • TokyoTyrantQuery::metaSearch — Retrieve records with multiple queries
  • TokyoTyrantQuery::next — Moves the iterator to next entry
  • TokyoTyrantQuery::out — Removes records based on query
  • TokyoTyrantQuery::rewind — Rewinds the iterator
  • TokyoTyrantQuery::search — Searches records
  • TokyoTyrantQuery::setLimit — Limit results
  • TokyoTyrantQuery::setOrder — Orders results
  • TokyoTyrantQuery::valid — Checks the validity of current item


Adds a condition to the query

  • « TokyoTyrantQuery
  • TokyoTyrantQuery::__construct »
  • PHP Manual
  • TokyoTyrantQuery
  • Adds a condition to the query

TokyoTyrantQuery::addCond

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::addCond — Adds a condition to the query

Description

public TokyoTyrantQuery::addCond ( string $name , int $op , string $expr ) : mixed

Adds a condition to the query. Condition can be something like: get all keys which value matches expr.

Parameters

name

Name of the column in the condition

op

The operator. One of the TokyoTyrant::RDBQC_* constants

expr

The expression

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrantQuery::addCond() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "not here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Dump the search results */
var_dump($query->search());
?>

The above example will output:

array(2) {
  [1]=>
  array(2) {
    ["column1"]=>
    string(9) "some data"
    ["column2"]=>
    string(14) "something here"
  }
  [4]=>
  array(2) {
    ["column45"]=>
    string(11) "random data"
    ["column2"]=>
    string(25) "something along the lines"
  }
}

See Also

  • Classname::Method()


Construct a new query

  • « TokyoTyrantQuery::addCond
  • TokyoTyrantQuery::count »
  • PHP Manual
  • TokyoTyrantQuery
  • Construct a new query

TokyoTyrantQuery::__construct

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::__construct — Construct a new query

Description

public TokyoTyrantQuery::__construct ( TokyoTyrantTable $table )

Construct a new query object

Parameters

table

TokyoTyrantTable object with active database connection

Return Values

Returns a new TokyoTyrantQuery object and throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantQuery::__construct() example

<?php
$tt = new TokyoTyrantTable("localhost", 1979);

$query = new TokyoTyrantQuery($tt);

/* Work with $query */
?>

See Also

  • TokyoTyrantTable::getQuery() - Get a query object


Counts records

  • « TokyoTyrantQuery::__construct
  • TokyoTyrantQuery::current »
  • PHP Manual
  • TokyoTyrantQuery
  • Counts records

TokyoTyrantQuery::count

(No version information available, might only be in Git)

TokyoTyrantQuery::count — Counts records

Description

public TokyoTyrantQuery::count ( void ) : int

Returns a count of how many records a query returns.

Parameters

This function has no parameters.

Return Values

Returns a count of matching rows and throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantQuery::count() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "not here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Count the results */
var_dump($query->count());
?>

The above example will output:

int(2)

See Also

  • TokyoTyrantQuery::out() - Removes records based on query
  • TokyoTyrantQuery::search() - Searches records
  • TokyoTyrantQuery::metaSearch() - Retrieve records with multiple queries


Returns the current element

  • « TokyoTyrantQuery::count
  • TokyoTyrantQuery::hint »
  • PHP Manual
  • TokyoTyrantQuery
  • Returns the current element

TokyoTyrantQuery::current

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::current — Returns the current element

Description

public TokyoTyrantQuery::current ( void ) : array

Returns the current element. Part of Iterator interface

Parameters

This function has no parameters.

Return Values

Returns the current row

Examples

Example #1 TokyoTyrantQuery iterator example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Iterate the results */
foreach ($query as $key => $value) {
    echo "pk: $key, columns: ", count($value) ,"\n";
}
?>

The above example will output something similar to:

pk: 1, columns: 2
pk: 4, columns: 2

See Also

  • TokyoTyrantQuery::addCond() - Adds a condition to the query


Get the hint string of the query

  • « TokyoTyrantQuery::current
  • TokyoTyrantQuery::key »
  • PHP Manual
  • TokyoTyrantQuery
  • Get the hint string of the query

TokyoTyrantQuery::hint

(No version information available, might only be in Git)

TokyoTyrantQuery::hint — Get the hint string of the query

Description

public TokyoTyrantQuery::hint ( void ) : string

Get the hint string of the query. The hint string contains information about an executed query and it could be compared to for example MySQL EXPLAIN statement.

Parameters

This function has no parameters.

Return Values

This method always returns a string

Examples

Example #1 TokyoTyrantQuery::hint example

<?php
$tt = new TokyoTyrantTable("localhost", 1979);
$tt->vanish();

for ($i = 0; $i < 11; $i++) {
     $tt->put(null, array('a_col' => 'a' . $i, 'b_col' => 'b' . $i));
}

$query = $tt->getQuery();
$query->addCond('a_col', TokyoTyrant::RDBQC_STRBW, 'a');

$query->search();
var_dump($query->hint());
?>

The above example will output something similar to:

string(72) "
scanning the whole table
result set size: 11
leaving the natural order
"

See Also

  • TokyoTyrantQuery::addCond() - Adds a condition to the query


Returns the current key

  • « TokyoTyrantQuery::hint
  • TokyoTyrantQuery::metaSearch »
  • PHP Manual
  • TokyoTyrantQuery
  • Returns the current key

TokyoTyrantQuery::key

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::key — Returns the current key

Description

public TokyoTyrantQuery::key ( void ) : string

Returns the current key. Part of the Iterator interface

Parameters

This function has no parameters.

Return Values

Returns the current key and throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantQuery iterator example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Iterate the results */
foreach ($query as $key => $value) {
    echo "pk: $key, columns: ", count($value) ,"\n";
}
?>

The above example will output something similar to:

pk: 1, columns: 2
pk: 4, columns: 2

See Also

  • TokyoTyrantQuery::addCond() - Adds a condition to the query


Retrieve records with multiple queries

  • « TokyoTyrantQuery::key
  • TokyoTyrantQuery::next »
  • PHP Manual
  • TokyoTyrantQuery
  • Retrieve records with multiple queries

TokyoTyrantQuery::metaSearch

(No version information available, might only be in Git)

TokyoTyrantQuery::metaSearch — Retrieve records with multiple queries

Description

public TokyoTyrantQuery::metaSearch ( array $queries , int $type ) : array

Executes multiple queries on a database and returns matching records. The current object is always the left most object in the search.

Parameters

queries

Array of TokyoTyrantQuery objects

type

One of the TokyoTyrant::RDBMS_* constants

Return Values

Returns the matching rows and throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantQuery::metaSearch() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add test data */
$tt->put('cherry',     array('color' => 'red'));
$tt->put('strawberry', array('color' => 'red'));
$tt->put('apple',      array('color' => 'green'));
$tt->put('lemon',      array('color' => 'yellow'));

/* First query */
$query = $tt->getQuery();
$query->addCond('color', TokyoTyrant::RDBQC_STREQ, 'red')->setOrder('color', TokyoTyrant::RDBQO_STRASC);

/* Second query */
$query1 = $tt->getQuery();
$query1->addCond('color', TokyoTyrant::RDBQC_STREQ, 'yellow');

/* Get union between the queries */
var_dump($query->metaSearch(array($query1), TokyoTyrant::RDBMS_UNION));
?>

The above example will output:

array(3) {
  ["cherry"]=>
  array(1) {
    ["color"]=>
    string(3) "red"
  }
  ["strawberry"]=>
  array(1) {
    ["color"]=>
    string(3) "red"
  }
  ["lemon"]=>
  array(1) {
    ["color"]=>
    string(6) "yellow"
  }
}

See Also

  • TokyoTyrantQuery::search() - Searches records


Moves the iterator to next entry

  • « TokyoTyrantQuery::metaSearch
  • TokyoTyrantQuery::out »
  • PHP Manual
  • TokyoTyrantQuery
  • Moves the iterator to next entry

TokyoTyrantQuery::next

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::next — Moves the iterator to next entry

Description

public TokyoTyrantQuery::next ( void ) : array

Returns the next result in the resultset. Part of the Iterator interface.

Parameters

This function has no parameters.

Return Values

Returns the next row and throws TokyoTyrantException on error.

Examples

Example #1 TokyoTyrantQuery iterator example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Iterate the results */
foreach ($query as $key => $value) {
    echo "pk: $key, columns: ", count($value) ,"\n";
}
?>

The above example will output something similar to:

pk: 1, columns: 2
pk: 4, columns: 2

See Also

  • TokyoTyrantQuery::addCond() - Adds a condition to the query


Removes records based on query

  • « TokyoTyrantQuery::next
  • TokyoTyrantQuery::rewind »
  • PHP Manual
  • TokyoTyrantQuery
  • Removes records based on query

TokyoTyrantQuery::out

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::out — Removes records based on query

Description

public TokyoTyrantQuery::out ( void ) : TokyoTyrantQuery

Removes all records that match the query. Works exactly like search but removes the records instead of returning them.

Parameters

This function has no parameters.

Return Values

This method returns the current object and throws TokyoTyrantException on failure.

Examples

Example #1 TokyoTyrantQuery::out() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Remove matching records */
$query->out();
?>

See Also

  • TokyoTyrantQuery::addCond() - Adds a condition to the query


Rewinds the iterator

  • « TokyoTyrantQuery::out
  • TokyoTyrantQuery::search »
  • PHP Manual
  • TokyoTyrantQuery
  • Rewinds the iterator

TokyoTyrantQuery::rewind

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::rewind — Rewinds the iterator

Description

public TokyoTyrantQuery::rewind ( void ) : bool

Rewind the resultset and executes the query if it has not been executed. Part of the Iterator interface.

Parameters

This function has no parameters.

Return Values

Returns TRUE

Examples

Example #1 TokyoTyrantQuery iterator example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Iterate the results */
foreach ($query as $key => $value) {
    echo "pk: $key, columns: ", count($value) ,"\n";
}
?>

The above example will output something similar to:

pk: 1, columns: 2
pk: 4, columns: 2

See Also

  • TokyoTyrantQuery::addCond() - Adds a condition to the query


Searches records

  • « TokyoTyrantQuery::rewind
  • TokyoTyrantQuery::setLimit »
  • PHP Manual
  • TokyoTyrantQuery
  • Searches records

TokyoTyrantQuery::search

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::search — Searches records

Description

public TokyoTyrantQuery::search ( void ) : array

Executes a search on the table database. Returns an array of arrays containing the matching records. In the returned array the first level is the primary key of the data and the second level is the row data.

Parameters

This function has no parameters.

Return Values

Returns the matching rows and throws TokyoTyrantException on error

Examples

Example #1 TokyoTyrantQuery::search() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "not here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Dump the search results */
var_dump($query->search());
?>

The above example will output:

array(2) {
  [1]=>
  array(2) {
    ["column1"]=>
    string(9) "some data"
    ["column2"]=>
    string(14) "something here"
  }
  [4]=>
  array(2) {
    ["column45"]=>
    string(11) "random data"
    ["column2"]=>
    string(25) "something along the lines"
  }
}

See Also

  • TokyoTyrantQuery::out() - Removes records based on query
  • TokyoTyrantQuery::metaSearch() - Retrieve records with multiple queries


Limit results

  • « TokyoTyrantQuery::search
  • TokyoTyrantQuery::setOrder »
  • PHP Manual
  • TokyoTyrantQuery
  • Limit results

TokyoTyrantQuery::setLimit

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::setLimit — Limit results

Description

public TokyoTyrantQuery::setLimit ([ int $max [, int $skip ]] ) : mixed

Set the maximum amount of records to return on a query.

Parameters

max

Maximum amount of records. Default: -1

skip

How many records to skip from the start. Default: -1

Return Values

This method returns the current object and throws TokyoTyrantException on failure.


Orders results

  • « TokyoTyrantQuery::setLimit
  • TokyoTyrantQuery::valid »
  • PHP Manual
  • TokyoTyrantQuery
  • Orders results

TokyoTyrantQuery::setOrder

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::setOrder — Orders results

Description

public TokyoTyrantQuery::setOrder ( string $name , int $type ) : mixed

Sets the order of a query

Parameters

name

The column name to apply the ordering on.

type

The type can be one of the following constants:

  • TokyoTyrant::RDBQO_STRASC - String ascending
  • TokyoTyrant::RDBQO_STRDESC - String descending
  • TokyoTyrant::RDBQO_NUMASC - Numberic ascending
  • TokyoTyrant::RDBQO_NUMDESC - String descending

Return Values

This method returns the current object.


Checks the validity of current item

  • « TokyoTyrantQuery::setOrder
  • TokyoTyrantIterator »
  • PHP Manual
  • TokyoTyrantQuery
  • Checks the validity of current item

TokyoTyrantQuery::valid

(PECL tokyo_tyrant >= 0.1.0)

TokyoTyrantQuery::valid — Checks the validity of current item

Description

public TokyoTyrantQuery::valid ( void ) : bool

Checks if the current item is valid. Part of the Iterator interface

Parameters

This function has no parameters.

Return Values

Returns TRUE if the current item is valid and FALSE if not.

Examples

Example #1 TokyoTyrantQuery iterator example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Add rows */
$tt->put(null, array("column1" => "some data", "column2" => "something here"));
$tt->put(null, array("column1" => "more data", "column2" => "best data this far"));
$tt->put(null, array("column1" => "again data", "column3" => "foobar here"));
$tt->put(null, array("column45" => "random data", "column2" => "something along the lines"));
$tt->put(null, array("column21" => "test data", "column2" => "generating.."));
$tt->put(null, array("column1" => "foobar data", "column2" => "value here"));

/* Get a new query object */
$query = $tt->getQuery();

/* Add a search condition */
$query->addCond("column2", TokyoTyrant::RDBQC_STROR, "something");

/* Iterate the results */
foreach ($query as $key => $value) {
    echo "pk: $key, columns: ", count($value) ,"\n";
}
?>

The above example will output something similar to:

pk: 1, columns: 2
pk: 4, columns: 2

See Also

  • TokyoTyrantQuery::addCond() - Adds a condition to the query


The TokyoTyrantIterator class

(PECL tokyo_tyrant >= 0.2.0)

Introduction

Provides an iterator for TokyoTyrant and TokyoTyrantTable objects. The iterator iterates over all keys and values in the database. TokyoTyrantIterator was added in version 0.2.0.

Class synopsis

TokyoTyrantIterator implements Iterator {
/* Methods */
public __construct ( mixed $object )
public current ( void ) : mixed
public key ( void ) : mixed
public next ( void ) : mixed
public rewind ( void ) : void
public valid ( void ) : bool
/* Inherited methods */
public TokyoTyrant::add ( string $key , number $increment [, int $type = 0 ] ) : number
public TokyoTyrant::connect ( string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]] ) : TokyoTyrant
public TokyoTyrant::connectUri ( string $uri ) : TokyoTyrant
public TokyoTyrant::__construct ([ string $host [, int $port = TokyoTyrant::RDBDEF_PORT [, array $options ]]] )
public TokyoTyrant::copy ( string $path ) : TokyoTyrant
public TokyoTyrant::ext ( string $name , int $options , string $key , string $value ) : string
public TokyoTyrant::fwmKeys ( string $prefix , int $max_recs ) : array
public TokyoTyrant::get ( mixed $keys ) : mixed
public TokyoTyrant::getIterator ( void ) : TokyoTyrantIterator
public TokyoTyrant::num ( void ) : int
public TokyoTyrant::out ( mixed $keys ) : TokyoTyrant
public TokyoTyrant::put ( mixed $keys [, string $value = NULL ] ) : TokyoTyrant
public TokyoTyrant::putCat ( mixed $keys [, string $value ] ) : TokyoTyrant
public TokyoTyrant::putKeep ( mixed $keys [, string $value ] ) : TokyoTyrant
public TokyoTyrant::putNr ( mixed $keys [, string $value = NULL ] ) : TokyoTyrant
public TokyoTyrant::putShl ( string $key , string $value , int $width ) : mixed
public TokyoTyrant::restore ( string $log_dir , int $timestamp [, bool $check_consistency = TRUE ] ) : mixed
public TokyoTyrant::setMaster ( string $host , int $port , int $timestamp [, bool $check_consistency = TRUE ] ) : mixed
public TokyoTyrant::size ( string $key ) : int
public TokyoTyrant::stat ( void ) : array
public TokyoTyrant::sync ( void ) : mixed
public TokyoTyrant::tune ( float $timeout [, int $options = TokyoTyrant::RDBT_RECON ] ) : TokyoTyrant
public TokyoTyrant::vanish ( void ) : mixed
}

Table of Contents

  • TokyoTyrantIterator::__construct — Construct an iterator
  • TokyoTyrantIterator::current — Get the current value
  • TokyoTyrantIterator::key — Returns the current key
  • TokyoTyrantIterator::next — Move to next key
  • TokyoTyrantIterator::rewind — Rewinds the iterator
  • TokyoTyrantIterator::valid — Rewinds the iterator


Construct an iterator

  • « TokyoTyrantIterator
  • TokyoTyrantIterator::current »
  • PHP Manual
  • TokyoTyrantIterator
  • Construct an iterator

TokyoTyrantIterator::__construct

(PECL tokyo_tyrant >= 0.2.0)

TokyoTyrantIterator::__construct — Construct an iterator

Description

public TokyoTyrantIterator::__construct ( mixed $object )

Construct a new TokyoTyrantIterator object. One connection can have multiple iterators but it is not quaranteed that all items are traversed in that case. object parameter can be either an of instance TokyoTyrant or TokyoTyrantTable.

Parameters

This function has no parameters.

Return Values

Throws an exception if iterator initialization fails.

Examples

Example #1 TokyoTyrantIterator::__construct() example

<?php
/* Connect to a table database */
$tt = new TokyoTyrantTable("localhost", 1979);

/* Passing null to put generates a new uid */
$index = $tt->put(null, array("column1" => "some data", "column2" => "more data"));

/* Construct an iterator */
$it = new TokyoTyrantIterator($tt);

foreach ($it as $value) {
    var_dump($value);
}
?>

The above example will output:

array(2) {
  ["column1"]=>
  string(9) "some data"
  ["column2"]=>
  string(9) "more data"
}

See Also

  • TokyoTyrantIterator::key() - Returns the current key
  • TokyoTyrantIterator::current() - Get the current value
  • TokyoTyrantIterator::next() - Move to next key
  • TokyoTyrantIterator::rewind() - Rewinds the iterator
  • TokyoTyrantIterator::key() - Returns the current key


Get the current value

  • « TokyoTyrantIterator::__construct
  • TokyoTyrantIterator::key »
  • PHP Manual
  • TokyoTyrantIterator
  • Get the current value

TokyoTyrantIterator::current

(PECL tokyo_tyrant >= 0.2.0)

TokyoTyrantIterator::current — Get the current value

Description

public TokyoTyrantIterator::current ( void ) : mixed

Returns the current value during iteration.

Parameters

This function has no parameters.

Return Values

Returns the current value on success and false on failure.

See Also

  • TokyoTyrantIterator::valid() - Rewinds the iterator
  • TokyoTyrantIterator::key() - Returns the current key
  • TokyoTyrantIterator::next() - Move to next key
  • TokyoTyrantIterator::rewind() - Rewinds the iterator


Returns the current key

  • « TokyoTyrantIterator::current
  • TokyoTyrantIterator::next »
  • PHP Manual
  • TokyoTyrantIterator
  • Returns the current key

TokyoTyrantIterator::key

(PECL tokyo_tyrant >= 0.2.0)

TokyoTyrantIterator::key — Returns the current key

Description

public TokyoTyrantIterator::key ( void ) : mixed

Returns the current key.

Parameters

This function has no parameters.

Return Values

Returns the current key on success and false on failure.

See Also

  • TokyoTyrantIterator::valid() - Rewinds the iterator
  • TokyoTyrantIterator::current() - Get the current value
  • TokyoTyrantIterator::next() - Move to next key
  • TokyoTyrantIterator::rewind() - Rewinds the iterator


Move to next key

  • « TokyoTyrantIterator::key
  • TokyoTyrantIterator::rewind »
  • PHP Manual
  • TokyoTyrantIterator
  • Move to next key

TokyoTyrantIterator::next

(PECL tokyo_tyrant >= 0.2.0)

TokyoTyrantIterator::next — Move to next key

Description

public TokyoTyrantIterator::next ( void ) : mixed

Move to next key during iteration and return it's value.

Parameters

This function has no parameters.

Return Values

Returns the next value on success and false on failure.

See Also

  • TokyoTyrantIterator::valid() - Rewinds the iterator
  • TokyoTyrantIterator::key() - Returns the current key
  • TokyoTyrantIterator::current() - Get the current value
  • TokyoTyrantIterator::rewind() - Rewinds the iterator


Rewinds the iterator

  • « TokyoTyrantIterator::next
  • TokyoTyrantIterator::valid »
  • PHP Manual
  • TokyoTyrantIterator
  • Rewinds the iterator

TokyoTyrantIterator::rewind

(PECL tokyo_tyrant >= 0.2.0)

TokyoTyrantIterator::rewind — Rewinds the iterator

Description

public TokyoTyrantIterator::rewind ( void ) : void

Rewinds the iterator for new iteration. Called automatically at the beginning of foreach.

Parameters

This function has no parameters.

Return Values

Throws TokyoTyrantException if iterator initialization fails.

See Also

  • TokyoTyrantIterator::valid() - Rewinds the iterator
  • TokyoTyrantIterator::current() - Get the current value
  • TokyoTyrantIterator::next() - Move to next key
  • TokyoTyrantIterator::rewind()


Rewinds the iterator

  • « TokyoTyrantIterator::rewind
  • TokyoTyrantException »
  • PHP Manual
  • TokyoTyrantIterator
  • Rewinds the iterator

TokyoTyrantIterator::valid

(PECL tokyo_tyrant >= 0.2.0)

TokyoTyrantIterator::valid — Rewinds the iterator

Description

public TokyoTyrantIterator::valid ( void ) : bool

Checks whether the internal pointer points to valid element.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the current item is valid and FALSE if not.

See Also

  • TokyoTyrantIterator::key() - Returns the current key
  • TokyoTyrantIterator::current() - Get the current value
  • TokyoTyrantIterator::next() - Move to next key
  • TokyoTyrantIterator::rewind() - Rewinds the iterator


The TokyoTyrantException class

(PECL tokyo_tyrant >= 0.1.0)

Introduction

TokyoTyrantException

Class synopsis

tokyotyrantexception extends Exception {
/* Properties */
protected int $code ;
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}

Properties

code

The exception code. This can be compared to TokyoTyrant::TTE_* constants


Date and Time Related Extensions

  • Calendar
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Calendar Functions
  • Date/Time — Date and Time
    • Introduction
    • 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
    • Supported Date and Time Formats
    • List of Supported Timezones
  • HRTime — High resolution timing
    • Introduction
    • Installing/Configuring
    • Examples
    • HRTime\PerformanceCounter — The HRTime\PerformanceCounter class
    • HRTime\StopWatch — The HRTime\StopWatch class
    • HRTime\Unit — The HRTime\Unit class


Calendar

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • 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 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


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.


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 (integer)
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 (integer)
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 (integer)
For easter_days(): calculate Easter according to the proleptic Gregorian calendar.
CAL_EASTER_ALWAYS_JULIAN (integer)
For easter_days(): calculate Easter according to the Julian calendar.
CAL_GREGORIAN (integer)
For cal_days_in_month(),
cal_from_jd(), cal_info() and
cal_to_jd(): use the proleptic Gregorian calendar.
CAL_JULIAN (integer)
For cal_days_in_month(),
cal_from_jd(), cal_info() and
cal_to_jd(): use the Julian calendar.
CAL_JEWISH (integer)
For cal_days_in_month(),
cal_from_jd(), cal_info() and
cal_to_jd(): use the Jewish calendar.
CAL_FRENCH (integer)
For cal_days_in_month(),
cal_from_jd(), cal_info() and
cal_to_jd(): use the French Repuclican calendar.
CAL_NUM_CALS (integer)
The number of available calendars.
CAL_JEWISH_ADD_ALAFIM_GERESH (integer)
For jdtojewish(): adds a geresh symbol (which resembles a single-quote mark) as thousands separator to the year number.
CAL_JEWISH_ADD_ALAFIM (integer)
For jdtojewish(): adds the word alafim as thousands separator to the year number.
CAL_JEWISH_ADD_GERESHAYIM (integer)
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 (integer)
For jddayofweek(): the day of the week as integer, where 0 means Sunday and 6 means Saturday.
CAL_DOW_SHORT (integer)
For jddayofweek(): the abbreviated English name of the day of the week.
CAL_DOW_LONG (integer)
For jddayofweek(): the English name of the day of the week.
CAL_MONTH_GREGORIAN_SHORT (integer)
For jdmonthname(): the abbreviated Gregorian month name.
CAL_MONTH_GREGORIAN_LONG (integer)
For jdmonthname(): the Gregorian month name.
CAL_MONTH_JULIAN_SHORT (integer)
For jdmonthname(): the abbreviated Julian month name.
CAL_MONTH_JULIAN_LONG (integer)
For jdmonthname(): the Julian month name.
CAL_MONTH_JEWISH (integer)
For jdmonthname(): the Jewish month name.
CAL_MONTH_FRENCH (integer)
For jdmonthname(): the French Republican month name.


Calendar Functions

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


Return the number of days in a month for a given year and calendar

  • « Calendar Functions
  • cal_from_jd »
  • PHP Manual
  • Calendar Functions
  • Return the number of days in a month for a given year and calendar

cal_days_in_month

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

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


Converts from Julian Day Count to a supported calendar

  • « cal_days_in_month
  • cal_info »
  • PHP Manual
  • Calendar Functions
  • Converts from Julian Day Count to a supported calendar

cal_from_jd

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

cal_from_jd — Converts from Julian Day Count to a supported calendar

Description

cal_from_jd ( int $jd , int $calendar ) : array

cal_from_jd() converts the Julian day given in jd into a date of the specified calendar. Supported calendar values are CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH and CAL_FRENCH.

Parameters

jd

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


Returns information about a particular calendar

  • « cal_from_jd
  • cal_to_jd »
  • PHP Manual
  • Calendar Functions
  • Returns information about a particular calendar

cal_info

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

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
)


Converts from a supported calendar to Julian Day Count

  • « cal_info
  • easter_date »
  • PHP Manual
  • Calendar Functions
  • Converts from a supported calendar to Julian Day Count

cal_to_jd

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

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


Get Unix timestamp for midnight on Easter of a given year

  • « cal_to_jd
  • easter_days »
  • PHP Manual
  • Calendar Functions
  • Get Unix timestamp for midnight on Easter of a given year

easter_date

(PHP 4, PHP 5, PHP 7)

easter_date — Get Unix timestamp for midnight on Easter of a given year

Description

easter_date ([ int $year = date("Y") [, int $method = CAL_EASTER_DEFAULT ]] ) : int

Returns the Unix timestamp corresponding to midnight on Easter of the given year.

Warning

This function will generate a warning if the year is outside of the range for Unix timestamps (i.e. typically before 1970 or after 2037 on 32bit systems).

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 number between 1970 an 2037. If omitted, defaults to the current year according to the local time.

method

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.

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

?>

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


Get number of days after March 21 on which Easter falls for a given year

  • « easter_date
  • frenchtojd »
  • PHP Manual
  • Calendar Functions
  • Get number of days after March 21 on which Easter falls for a given year

easter_days

(PHP 4, PHP 5, PHP 7)

easter_days — Get number of days after March 21 on which Easter falls for a given year

Description

easter_days ([ int $year = date("Y") [, int $method = 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, defaults to the current year according to the local time.

method

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.

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 midnight on Easter of a given year


Converts a date from the French Republican Calendar to a Julian Day Count

  • « easter_days
  • gregoriantojd »
  • PHP Manual
  • Calendar Functions
  • Converts a date from the French Republican Calendar to a Julian Day Count

frenchtojd

(PHP 4, PHP 5, PHP 7)

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


Converts a Gregorian date to Julian Day Count

  • « frenchtojd
  • jddayofweek »
  • PHP Manual
  • Calendar Functions
  • Converts a Gregorian date to Julian Day Count

gregoriantojd

(PHP 4, PHP 5, PHP 7)

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


Returns the day of the week

  • « gregoriantojd
  • jdmonthname »
  • PHP Manual
  • Calendar Functions
  • Returns the day of the week

jddayofweek

(PHP 4, PHP 5, PHP 7)

jddayofweek — Returns the day of the week

Description

jddayofweek ( int $julianday [, int $mode = CAL_DOW_DAYNO ] ) : mixed

Returns the day of the week. Can return a string or an integer depending on the mode.

Parameters

julianday

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.


Returns a month name

  • « jddayofweek
  • jdtofrench »
  • PHP Manual
  • Calendar Functions
  • Returns a month name

jdmonthname

(PHP 4, PHP 5, PHP 7)

jdmonthname — Returns a month name

Description

jdmonthname ( int $julianday , 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, AdarI, AdarII, 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

jday

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.


Converts a Julian Day Count to the French Republican Calendar

  • « jdmonthname
  • jdtogregorian »
  • PHP Manual
  • Calendar Functions
  • Converts a Julian Day Count to the French Republican Calendar

jdtofrench

(PHP 4, PHP 5, PHP 7)

jdtofrench — Converts a Julian Day Count to the French Republican Calendar

Description

jdtofrench ( int $juliandaycount ) : string

Converts a Julian Day Count to the French Republican Calendar.

Parameters

julianday

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


Converts Julian Day Count to Gregorian date

  • « jdtofrench
  • jdtojewish »
  • PHP Manual
  • Calendar Functions
  • Converts Julian Day Count to Gregorian date

jdtogregorian

(PHP 4, PHP 5, PHP 7)

jdtogregorian — Converts Julian Day Count to Gregorian date

Description

jdtogregorian ( int $julianday ) : string

Converts Julian Day Count to a string containing the Gregorian date in the format of "month/day/year".

Parameters

julianday

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


Converts a Julian day count to a Jewish calendar date

  • « jdtogregorian
  • jdtojulian »
  • PHP Manual
  • Calendar Functions
  • Converts a Julian day count to a Jewish calendar date

jdtojewish

(PHP 4, PHP 5, PHP 7)

jdtojewish — Converts a Julian day count to a Jewish calendar date

Description

jdtojewish ( int $juliandaycount [, bool $hebrew = FALSE [, int $fl = 0 ]] ) : string

Converts a Julian Day Count to the Jewish Calendar.

Parameters

julianday

A julian day number as integer

hebrew

If the hebrew parameter is set to TRUE, the fl parameter is used for Hebrew, ISO-8859-8 encoded string based, output format.

fl

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


Converts a Julian Day Count to a Julian Calendar Date

  • « jdtojewish
  • jdtounix »
  • PHP Manual
  • Calendar Functions
  • Converts a Julian Day Count to a Julian Calendar Date

jdtojulian

(PHP 4, PHP 5, PHP 7)

jdtojulian — Converts a Julian Day Count to a Julian Calendar Date

Description

jdtojulian ( int $julianday ) : string

Converts Julian Day Count to a string containing the Julian Calendar Date in the format of "month/day/year".

Parameters

julianday

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


Convert Julian Day to Unix timestamp

  • « jdtojulian
  • jewishtojd »
  • PHP Manual
  • Calendar Functions
  • Convert Julian Day to Unix timestamp

jdtounix

(PHP 4, PHP 5, PHP 7)

jdtounix — Convert Julian Day to Unix timestamp

Description

jdtounix ( int $jday ) : int

This function will return a Unix timestamp corresponding to the Julian Day given in jday or FALSE if jday is not inside the Unix epoch (Gregorian years between 1970 and 2037 or 2440588 <= jday <= 2465342 ). The time returned is UTC.

Parameters

jday

A julian day number between 2440588 and 2465342.

Return Values

The unix timestamp for the start (midnight, not noon) of the given Julian day.

See Also

  • unixtojd() - Convert Unix timestamp to Julian Day


Converts a date in the Jewish Calendar to Julian Day Count

  • « jdtounix
  • juliantojd »
  • PHP Manual
  • Calendar Functions
  • Converts a date in the Jewish Calendar to Julian Day Count

jewishtojd

(PHP 4, PHP 5, PHP 7)

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


Converts a Julian Calendar date to Julian Day Count

  • « jewishtojd
  • unixtojd »
  • PHP Manual
  • Calendar Functions
  • Converts a Julian Calendar date to Julian Day Count

juliantojd

(PHP 4, PHP 5, PHP 7)

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


Convert Unix timestamp to Julian Day

  • « juliantojd
  • Date/Time »
  • PHP Manual
  • Calendar Functions
  • Convert Unix timestamp to Julian Day

unixtojd

(PHP 4, PHP 5, PHP 7)

unixtojd — Convert Unix timestamp to Julian Day

Description

unixtojd ([ int $timestamp = time() ] ) : int

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.

See Also

  • jdtounix() - Convert Julian Day to Unix timestamp


Date and Time

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • DateTime Arithmetic
  • DateTime — The DateTime class
    • DateTime::add — Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
    • DateTime::__construct — Returns new DateTime object
    • DateTime::createFromFormat — Parses a time string according to a specified format
    • DateTime::createFromImmutable — Returns new DateTime object encapsulating the given DateTimeImmutable object
    • DateTime::getLastErrors — Returns the warnings and errors
    • 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 — Adds an 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::createFromMutable — Returns new DateTimeImmutable object 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
    • DateTime::diff — Returns the difference between two DateTime objects
    • DateTime::format — Returns date formatted according to given format
    • DateTime::getOffset — Returns the timezone offset
    • DateTime::getTimestamp — Gets the Unix timestamp
    • DateTime::getTimezone — Return time zone relative to given 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::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_add — Alias of DateTime::add
    • date_create_from_format — Alias of DateTime::createFromFormat
    • date_create_immutable_from_format — Alias of DateTimeImmutable::createFromFormat
    • date_create_immutable — Alias of DateTimeImmutable::__construct
    • date_create — Alias of DateTime::__construct
    • 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 DateTime::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_from_format — Get info about given date formatted according to the specified format
    • date_parse — Returns associative array with detailed info about given date
    • 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
    • date — Format a local time/date
    • 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 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 the timezone name from abbreviation
    • 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
  • Supported Date and Time Formats
    • Time Formats
    • Date Formats
    • Compound Formats
    • Relative Formats
  • List of Supported Timezones
    • Africa
    • America
    • Antarctica
    • Arctic
    • Asia
    • Atlantic
    • Australia
    • Europe
    • Indian
    • Pacific
    • Others


Introduction

These functions allow you to get the date and time from the server where your PHP scripts are running. You can use these functions to format the date and time in many different ways.

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: Please keep in mind that these functions are dependent on the locale settings of your server. Make sure to take daylight saving time (use e.g. $date = strtotime('+7 days', $date) and not $date += 7*24*60*60) and leap years into consideration when working with these functions.

Note: The timezones referenced in this section can be found in the List of Supported Timezones.


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.

Note: Experimental DateTime support in PHP 5.1.x

Although the DateTime class (and related functions) are enabled by default since PHP 5.2.0, it is possible to add experimental support into PHP 5.1.x by using the following flag before configure/compile: CFLAGS=-DEXPERIMENTAL_DATE_SUPPORT=1


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" | PHP_INI_ALL |
date.default_longitude | "35.2333" | PHP_INI_ALL |
date.sunrise_zenith | "90.583333" | PHP_INI_ALL |
date.sunset_zenith | "90.583333" | PHP_INI_ALL |
date.timezone | "" | PHP_INI_ALL | Available as of PHP 5.1.0.
For further details and definitions of the PHP_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.

date.default_longitude float

The default longitude.

date.sunrise_zenith float

The default sunrise zenith.

date.sunset_zenith float

The default sunset zenith.

date.timezone string

The default timezone used by all date/time functions. Prior to PHP 5.4.0, this would only work if the TZ environment variable was not set. 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 since PHP 5.1.1 and they offer standard date representations, which can be used along with the date format functions (like date()).

Following constants exists since PHP 5.1.2 and specify a format returned by functions date_sunrise() and date_sunset().

SUNFUNCS_RET_TIMESTAMP (integer)
Timestamp
SUNFUNCS_RET_STRING (integer)
Hours:minutes (example: 08:02)
SUNFUNCS_RET_DOUBLE (integer)
Hours as floating point number (example 8.75)


  • « Predefined Constants
  • DateTime Arithmetic »
  • PHP Manual
  • Date/Time
  • Examples

Examples

Table of Contents

  • DateTime Arithmetic


DateTime Arithmetic

The following examples show some pitfalls of DateTime arithmetic with regard to DST transitions and months having different numbers of days.

Example #1 DateTime::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 DateTime("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->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 DateTime::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 DateTime("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->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 DateTime("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->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 DateTime("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->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 as of PHP 5.3.0.

<?php
echo "Normal year:\n"; // February has 28 days
$dt = new DateTime("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->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 DateTime("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->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)

Introduction

Representation of date and time.

Class synopsis

DateTime implements DateTimeInterface {
/* Inherited constants */
const string DateTimeInterface::ATOM = "Y-m-d\TH:i:sP" ;
const string DateTimeInterface::COOKIE = "l, d-M-Y H:i:s T" ;
const string DateTimeInterface::ISO8601 = "Y-m-d\TH:i:sO" ;
const string DateTimeInterface::RFC822 = "D, d M y H:i:s O" ;
const string DateTimeInterface::RFC850 = "l, d-M-y H:i:s T" ;
const string DateTimeInterface::RFC1036 = "D, d M y H:i:s O" ;
const string DateTimeInterface::RFC1123 = "D, d M Y H:i:s O" ;
const string DateTimeInterface::RFC2822 = "D, d M Y H:i:s O" ;
const string DateTimeInterface::RFC3339 = "Y-m-d\TH:i:sP" ;
const string DateTimeInterface::RFC3339_EXTENDED = "Y-m-d\TH:i:s.vP" ;
const string DateTimeInterface::RSS = "D, d M Y H:i:s O" ;
const string DateTimeInterface::W3C = "Y-m-d\TH:i:sP" ;
/* Methods */
public __construct ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )
public add ( DateInterval $interval ) : DateTime
public static createFromFormat ( string $format , string $time [, DateTimeZone $timezone ] ) : DateTime
public static createFromImmutable ( DateTimeImmutable $datetime ) : DateTime
public static getLastErrors ( void ) : array
public modify ( string $modify ) : DateTime
public static __set_state ( array $array ) : DateTime
public setDate ( int $year , int $month , int $day ) : DateTime
public setISODate ( int $year , int $week [, int $day = 1 ] ) : DateTime
public setTime ( int $hour , int $minute [, int $second = 0 [, int $microseconds = 0 ]] ) : DateTime
public setTimestamp ( int $unixtimestamp ) : DateTime
public setTimezone ( DateTimeZone $timezone ) : DateTime
public sub ( DateInterval $interval ) : DateTime
public diff ( DateTimeInterface $datetime2 [, bool $absolute = FALSE ] ) : DateInterval
public format ( string $format ) : string
public getOffset ( void ) : int
public getTimestamp ( void ) : int
public getTimezone ( void ) : DateTimeZone
public __wakeup ( void )
}

Changelog

Version | Description
7.2.0 | The class constants of DateTime are now defined on DateTimeInterface.
7.0.0 | Added constants: DATE_RFC3339_EXTENDED and DateTime::RFC3339_EXTENDED.
5.5.0 | The class now implements DateTimeInterface.
5.4.24 | The COOKIE constant was changed to reflect RFC 1036 using a four digit year rather than a two digit year (RFC 850) as prior versions.
5.2.2 | DateTime object comparison with the comparison operators changed to work as expected. Previously, all DateTime objects were considered equal (using ==).

Table of Contents

  • DateTime::add — Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
  • DateTime::__construct — Returns new DateTime object
  • DateTime::createFromFormat — Parses a time string according to a specified format
  • DateTime::createFromImmutable — Returns new DateTime object encapsulating the given DateTimeImmutable object
  • DateTime::getLastErrors — Returns the warnings and errors
  • 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


Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object

  • « DateTime
  • DateTime::__construct »
  • PHP Manual
  • DateTime
  • Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object

DateTime::add

date_add

(PHP 5 >= 5.3.0, PHP 7)

DateTime::add -- date_add — Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object

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.

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 DateTime object for method chaining or FALSE on failure.

Examples

Example #1 DateTime::add() example

Object oriented style

<?php
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('P10D'));
echo $date->format('Y-m-d') . "\n";
?>

Procedural style

<?php
$date = date_create('2000-01-01');
date_add($date, date_interval_create_from_date_string('10 days'));
echo date_format($date, 'Y-m-d');
?>

The above examples will output:

2000-01-11

Example #2 Further DateTime::add() examples

<?php
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('PT10H30S'));
echo $date->format('Y-m-d H:i:s') . "\n";

$date = new DateTime('2000-01-01');
$date->add(new DateInterval('P7Y5M4DT4H3M2S'));
echo $date->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 DateTime('2000-12-31');
$interval = new DateInterval('P1M');

$date->add($interval);
echo $date->format('Y-m-d') . "\n";

$date->add($interval);
echo $date->format('Y-m-d') . "\n";
?>

The above example will output:

2001-01-31
2001-03-03

Notes

DateTime::modify() is an alternative when using PHP 5.2.

See Also

  • 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
  • DateTime::modify() - Alters the timestamp


Returns new DateTime object

  • « DateTime::add
  • DateTime::createFromFormat »
  • PHP Manual
  • DateTime
  • Returns new DateTime object

DateTime::__construct

date_create

(PHP 5 >= 5.2.0, PHP 7)

DateTime::__construct -- date_create — Returns new DateTime object

Description

Object oriented style

public DateTime::__construct ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )

Procedural style

date_create ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] ) : DateTime

Returns new DateTime object.

Parameters

time

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 $time.

If $timezone is omitted, the current timezone will be used.

Note:

The $timezone parameter and the current timezone are ignored when the $time 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. Procedural style returns FALSE on failure.

Errors/Exceptions

Emits Exception in case of an error.

Changelog

Version | Description
7.1 | From now on microseconds are filled with actual value. Not with '00000'.
5.3.0 | If time contains an invalid date/time format, then an exception is now thrown. Previously an error was emitted.

Examples

Example #1 DateTime::__construct() example

Object oriented style

<?php
try {
    $date = new DateTime('2000-01-01');
} catch (Exception $e) {
    echo $e->getMessage();
    exit(1);
}

echo $date->format('Y-m-d');
?>

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 examples will output:

2000-01-01

Example #2 Intricacies of DateTime::__construct()

<?php
// Specified date/time in your computer's time zone.
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:sP') . "\n";

// Specified date/time in the specified time zone.
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";

// Current date/time in your computer's time zone.
$date = new DateTime();
echo $date->format('Y-m-d H:i:sP') . "\n";

// Current date/time in the specified time zone.
$date = new DateTime(null, 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 DateTime('@946684800');
echo $date->format('Y-m-d H:i:sP') . "\n";

// Non-existent values roll over.
$date = new DateTime('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

See Also

  • DateTime::createFromFormat() - Parses a time string according to a specified format
  • DateTimeZone::__construct() - Creates new DateTimeZone object
  • Date and Time Formats
  • date.timezone ini setting
  • date_default_timezone_set() - Sets the default timezone used by all date/time functions in a script
  • DateTime::getLastErrors() - Returns the warnings and errors
  • checkdate() - Validate a Gregorian date


Parses a time string according to a specified format

  • « DateTime::__construct
  • DateTime::createFromImmutable »
  • PHP Manual
  • DateTime
  • Parses a time string according to a specified format

DateTime::createFromFormat

date_create_from_format

(PHP 5 >= 5.3.0, PHP 7)

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 $time [, DateTimeZone $timezone ] ) : DateTime

Procedural style

date_create_from_format ( string $format , string $time [, DateTimeZone $timezone ] ) : DateTime

Returns a new DateTime object representing the date and time specified by the time 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.

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
D and l | A textual representation of a day | Mon through Sun or Sunday through Saturday
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) | 0 through 365
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
Year --- ---
Y | A full numeric representation of a year, 4 digits | Examples: 1999 or 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
G and H | 24-hour format of an hour with or without leading zeros | 0 through 23 or 00 through 23
i | Minutes with leading zeros | 00 to 59
s | Seconds, with leading zeros | 00 through 59
v | Milliseconds (up to three digits) | Example: 12, 345
u | Microseconds (up to six digits) | Example: 45, 654321
Timezone --- ---
e, O, 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) | One space or one tab | Example:
# 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 the Unix Epoch 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 the Unix Epoch 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 DateTime::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 DateTime::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 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 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.

The Unix epoch is 1970-01-01 00:00:00 UTC.

time

String representing the time.

timezone

A DateTimeZone object representing the desired time zone.

If timezone is omitted and time contains no timezone, the current timezone will be used.

Note:

The timezone parameter and the current timezone are ignored when the time 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 DateTime instance or FALSE on failure.

Changelog

Version | Description
7.3.0 | The v format specifier has been added.
5.3.9 | The + format specifier has been added.

Examples

Example #1 DateTime::createFromFormat() example

Object oriented style

<?php
$date = DateTime::createFromFormat('j-M-Y', '15-Feb-2009');
echo $date->format('Y-m-d');
?>

Procedural style

<?php
$date = date_create_from_format('j-M-Y', '15-Feb-2009');
echo date_format($date, 'Y-m-d');
?>

The above examples will output:

2009-02-15

Example #2 Intricacies of DateTime::createFromFormat()

<?php
echo 'Current time: ' . date('Y-m-d H:i:s') . "\n";

$format = 'Y-m-d';
$date = DateTime::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 = DateTime::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 = DateTime::createFromFormat($format, '2009-02-15 15:16:17');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";

$format = '!d';
$date = DateTime::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: 2010-04-23 10:29:35
Format: Y-m-d; 2009-02-15 10:29:35
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

Example #3 Format string with literal characters

<?php
echo DateTime::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

See Also

  • DateTime::__construct() - Returns new DateTime object
  • DateTime::getLastErrors() - Returns the warnings and errors
  • checkdate() - Validate a Gregorian date
  • strptime() - Parse a time/date generated with strftime


Returns new DateTime object encapsulating the given DateTimeImmutable object

  • « DateTime::createFromFormat
  • DateTime::getLastErrors »
  • PHP Manual
  • DateTime
  • Returns new DateTime object encapsulating the given DateTimeImmutable object

DateTime::createFromImmutable

(PHP 7 >= 7.3.0)

DateTime::createFromImmutable — Returns new DateTime object encapsulating the given DateTimeImmutable object

Description

public static DateTime::createFromImmutable ( DateTimeImmutable $datetime ) : DateTime

Parameters

datetime

The immutable DateTimeImmutable 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.

Examples

Example #1 Creating a mutable date time object

<?php
$date = new DateTimeImmutable("2014-06-20 11:45 Europe/London");

$mutable = DateTime::createFromImmutable( $date );
?>

Return Values

Returns a new DateTime instance.


Returns the warnings and errors

  • « DateTime::createFromImmutable
  • DateTime::modify »
  • PHP Manual
  • DateTime
  • Returns the warnings and errors

DateTime::getLastErrors

date_get_last_errors

(PHP 5 >= 5.3.0, PHP 7)

DateTime::getLastErrors -- date_get_last_errors — Returns the warnings and errors

Description

Object oriented style

public static DateTime::getLastErrors ( void ) : array

Procedural style

date_get_last_errors ( void ) : array

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.

Examples

Example #1 DateTime::getLastErrors() example

Object oriented style

<?php
try {
    $date = new DateTime('asdfasdf');
} catch (Exception $e) {
    // For demonstration purposes only...
    print_r(DateTime::getLastErrors());

    // The real object oriented way to do this is
    // echo $e->getMessage();
}
?>

Procedural style

<?php
$date = date_create('asdfasdf');
print_r(date_get_last_errors());
?>

The above examples 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
       )

)

The indexes 6, and 0 in the example output refer to the character index in the string where the error occurred.


Alters the timestamp

  • « DateTime::getLastErrors
  • DateTime::__set_state »
  • PHP Manual
  • DateTime
  • Alters the timestamp

DateTime::modify

date_modify

(PHP 5 >= 5.2.0, PHP 7)

DateTime::modify -- date_modify — Alters the timestamp

Description

Object oriented style

public DateTime::modify ( string $modify ) : DateTime

Procedural style

date_modify ( DateTime $object , string $modify ) : DateTime

Alter the timestamp of a DateTime object by incrementing or decrementing in a format accepted by strtotime().

Parameters

object

Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

modify

A date/time string. Valid formats are explained in Date and Time Formats.

Return Values

Returns the DateTime object for method chaining or FALSE on failure.

Changelog

Version | Description
5.3.6 | Absolute date/time statements now take effect. Previously, only relative parts were used.
5.3.0 | Changed the return value on success from NULL to DateTime.

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');
?>

Procedural style

<?php
$date = date_create('2006-12-12');
date_modify($date, '+1 day');
echo date_format($date, 'Y-m-d');
?>

The above examples 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

See Also

  • strtotime() - Parse about any English textual datetime description into a Unix timestamp
  • DateTime::add() - Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
  • 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


The __set_state handler

  • « DateTime::modify
  • DateTime::setDate »
  • PHP Manual
  • DateTime
  • The __set_state handler

DateTime::__set_state

(PHP 5 >= 5.3.0, PHP 7)

DateTime::__set_state — The __set_state handler

Description

public static DateTime::__set_state ( array $array ) : DateTime

The __set_state() handler.

Parameters

array

Initialization array.

Return Values

Returns a new instance of a DateTime object.


Sets the date

  • « DateTime::__set_state
  • DateTime::setISODate »
  • PHP Manual
  • DateTime
  • Sets the date

DateTime::setDate

date_date_set

(PHP 5 >= 5.2.0, PHP 7)

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.

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 DateTime object for method chaining or FALSE on failure.

Changelog

Version | Description
5.3.0 | Changed the return value on success from NULL to DateTime.

Examples

Example #1 DateTime::setDate() example

Object oriented style

<?php
$date = new DateTime();
$date->setDate(2001, 2, 3);
echo $date->format('Y-m-d');
?>

Procedural style

<?php
$date = date_create();
date_date_set($date, 2001, 2, 3);
echo date_format($date, 'Y-m-d');
?>

The above examples will output:

2001-02-03

Example #2 Values exceeding ranges are added to their parent values

<?php
$date = new DateTime();

$date->setDate(2001, 2, 28);
echo $date->format('Y-m-d') . "\n";

$date->setDate(2001, 2, 29);
echo $date->format('Y-m-d') . "\n";

$date->setDate(2001, 14, 3);
echo $date->format('Y-m-d') . "\n";
?>

The above example will output:

2001-02-28
2001-03-01
2002-02-03

See Also

  • DateTime::setISODate() - Sets the ISO date
  • DateTime::setTime() - Sets the time


Sets the ISO date

  • « DateTime::setDate
  • DateTime::setTime »
  • PHP Manual
  • DateTime
  • Sets the ISO date

DateTime::setISODate

date_isodate_set

(PHP 5 >= 5.2.0, PHP 7)

DateTime::setISODate -- date_isodate_set — Sets the ISO date

Description

Object oriented style

public DateTime::setISODate ( int $year , int $week [, int $day = 1 ] ) : DateTime

Procedural style

date_isodate_set ( DateTime $object , int $year , int $week [, int $day = 1 ] ) : DateTime

Set a date according to the ISO 8601 standard - using weeks and day offsets rather than specific dates.

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.

day

Offset from the first day of the week.

Return Values

Returns the DateTime object for method chaining or FALSE on failure.

Changelog

Version | Description
5.3.0 | Changed the return value on success from NULL to DateTime.

Examples

Example #1 DateTime::setISODate() example

Object oriented style

<?php
$date = new DateTime();

$date->setISODate(2008, 2);
echo $date->format('Y-m-d') . "\n";

$date->setISODate(2008, 2, 7);
echo $date->format('Y-m-d') . "\n";
?>

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 examples will output:

2008-01-07
2008-01-13

Example #2 Values exceeding ranges are added to their parent values

<?php
$date = new DateTime();

$date->setISODate(2008, 2, 7);
echo $date->format('Y-m-d') . "\n";

$date->setISODate(2008, 2, 8);
echo $date->format('Y-m-d') . "\n";

$date->setISODate(2008, 53, 7);
echo $date->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 DateTime();
$date->setISODate(2008, 14);
echo $date->format('n');
?>

The above examples will output:

3

See Also

  • DateTime::setDate() - Sets the date
  • DateTime::setTime() - Sets the time


Sets the time

  • « DateTime::setISODate
  • DateTime::setTimestamp »
  • PHP Manual
  • DateTime
  • Sets the time

DateTime::setTime

date_time_set

(PHP 5 >= 5.2.0, PHP 7)

DateTime::setTime -- date_time_set — Sets the time

Description

Object oriented style

public DateTime::setTime ( int $hour , int $minute [, int $second = 0 [, int $microseconds = 0 ]] ) : DateTime

Procedural style

date_time_set ( DateTime $object , int $hour , int $minute [, int $second = 0 [, int $microseconds = 0 ]] ) : DateTime

Resets the current time of the DateTime object to a different time.

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.

microseconds

Microsecond of the time.

Return Values

Returns the DateTime object for method chaining or FALSE on failure.

Changelog

Version | Description
7.1.0 | The microseconds parameter was added.
5.3.0 | Changed the return value on success from NULL to DateTime.

Examples

Example #1 DateTime::setTime() example

Object oriented style

<?php
$date = new DateTime('2001-01-01');

$date->setTime(14, 55);
echo $date->format('Y-m-d H:i:s') . "\n";

$date->setTime(14, 55, 24);
echo $date->format('Y-m-d H:i:s') . "\n";
?>

Procedural style

<?php
$date = date_create('2001-01-01');

date_time_set($date, 14, 55);
echo date_format($date, 'Y-m-d H:i:s') . "\n";

date_time_set($date, 14, 55, 24);
echo date_format($date, 'Y-m-d H:i:s') . "\n";
?>

The above examples 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 DateTime('2001-01-01');

$date->setTime(14, 55, 24);
echo $date->format('Y-m-d H:i:s') . "\n";

$date->setTime(14, 55, 65);
echo $date->format('Y-m-d H:i:s') . "\n";

$date->setTime(14, 65, 24);
echo $date->format('Y-m-d H:i:s') . "\n";

$date->setTime(25, 55, 24);
echo $date->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

  • DateTime::setDate() - Sets the date
  • DateTime::setISODate() - Sets the ISO date


Sets the date and time based on an Unix timestamp

  • « DateTime::setTime
  • DateTime::setTimezone »
  • PHP Manual
  • DateTime
  • Sets the date and time based on an Unix timestamp

DateTime::setTimestamp

date_timestamp_set

(PHP 5 >= 5.3.0, PHP 7)

DateTime::setTimestamp -- date_timestamp_set — Sets the date and time based on an Unix timestamp

Description

Object oriented style

public DateTime::setTimestamp ( int $unixtimestamp ) : DateTime

Procedural style

date_timestamp_set ( DateTime $object , int $unixtimestamp ) : DateTime

Sets the date and time based on an Unix timestamp.

Parameters

object

Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

unixtimestamp

Unix timestamp representing the date.

Return Values

Returns the DateTime object for method chaining or FALSE on failure.

Examples

Example #1 DateTime::setTimestamp() example

Object oriented style

<?php
$date = new DateTime();
echo $date->format('U = Y-m-d H:i:s') . "\n";

$date->setTimestamp(1171502725);
echo $date->format('U = Y-m-d H:i:s') . "\n";
?>

Procedural style

<?php
$date = date_create();
echo date_format($date, 'U = Y-m-d H:i:s') . "\n";

date_timestamp_set($date, 1171502725);
echo date_format($date, 'U = Y-m-d H:i:s') . "\n";
?>

The above examples will output something similar to:

1272508903 = 2010-04-28 22:41:43
1171502725 = 2007-02-14 20:25:25

Notes

Using the Unix timestamp format to construct a new DateTime object is an alternative when using PHP 5.2, as shown in the example below.

Example #2 DateTime::setTimestamp() alternative in PHP 5.2

<?php
$ts = 1171502725;
$date = new DateTime("@$ts");
echo $date->format('U = Y-m-d H:i:s') . "\n";
?>

The above example will output something similar to:

1171502725 = 2007-02-14 20:25:25

See Also

  • DateTime::getTimestamp() - Gets the Unix timestamp


Sets the time zone for the DateTime object

  • « DateTime::setTimestamp
  • DateTime::sub »
  • PHP Manual
  • DateTime
  • Sets the time zone for the DateTime object

DateTime::setTimezone

date_timezone_set

(PHP 5 >= 5.2.0, PHP 7)

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.

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 or FALSE on failure.

Changelog

Version | Description
5.3.0 | Changed the return value on success from NULL to DateTime.

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

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 examples will output:

2000-01-01 00:00:00+12:00
2000-01-01 01:45:00+13:45

See Also

  • DateTime::getTimezone() - Return time zone relative to given DateTime
  • DateTimeZone::__construct() - Creates new DateTimeZone object


Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object

  • « DateTime::setTimezone
  • DateTimeImmutable »
  • PHP Manual
  • DateTime
  • Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object

DateTime::sub

date_sub

(PHP 5 >= 5.3.0, PHP 7)

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

Subtracts the specified DateInterval object from the specified DateTime object.

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 DateTime object for method chaining or FALSE on failure.

Examples

Example #1 DateTime::sub() example

Object oriented style

<?php
$date = new DateTime('2000-01-20');
$date->sub(new DateInterval('P10D'));
echo $date->format('Y-m-d') . "\n";
?>

Procedural style

<?php
$date = date_create('2000-01-20');
date_sub($date, date_interval_create_from_date_string('10 days'));
echo date_format($date, 'Y-m-d');
?>

The above examples will output:

2000-01-10

Example #2 Further DateTime::sub() examples

<?php
$date = new DateTime('2000-01-20');
$date->sub(new DateInterval('PT10H30S'));
echo $date->format('Y-m-d H:i:s') . "\n";

$date = new DateTime('2000-01-20');
$date->sub(new DateInterval('P7Y5M4DT4H3M2S'));
echo $date->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 DateTime('2001-04-30');
$interval = new DateInterval('P1M');

$date->sub($interval);
echo $date->format('Y-m-d') . "\n";

$date->sub($interval);
echo $date->format('Y-m-d') . "\n";
?>

The above example will output:

2001-03-30
2001-03-02

Notes

DateTime::modify() is an alternative when using PHP 5.2.

See Also

  • DateTime::add() - Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
  • DateTime::diff() - Returns the difference between two DateTime objects
  • DateTime::modify() - Alters the timestamp


The DateTimeImmutable class

(PHP 5 >= 5.5.0, PHP 7)

Introduction

This class behaves the same as DateTime except it never modifies itself but returns a new object instead.

Class synopsis

DateTimeImmutable implements DateTimeInterface {
/* Inherited constants */
const string DateTimeInterface::ATOM = "Y-m-d\TH:i:sP" ;
const string DateTimeInterface::COOKIE = "l, d-M-Y H:i:s T" ;
const string DateTimeInterface::ISO8601 = "Y-m-d\TH:i:sO" ;
const string DateTimeInterface::RFC822 = "D, d M y H:i:s O" ;
const string DateTimeInterface::RFC850 = "l, d-M-y H:i:s T" ;
const string DateTimeInterface::RFC1036 = "D, d M y H:i:s O" ;
const string DateTimeInterface::RFC1123 = "D, d M Y H:i:s O" ;
const string DateTimeInterface::RFC2822 = "D, d M Y H:i:s O" ;
const string DateTimeInterface::RFC3339 = "Y-m-d\TH:i:sP" ;
const string DateTimeInterface::RFC3339_EXTENDED = "Y-m-d\TH:i:s.vP" ;
const string DateTimeInterface::RSS = "D, d M Y H:i:s O" ;
const string DateTimeInterface::W3C = "Y-m-d\TH:i:sP" ;
/* Methods */
public __construct ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )
public add ( DateInterval $interval ) : DateTimeImmutable
public static createFromFormat ( string $format , string $time [, DateTimeZone $timezone ] ) : DateTimeImmutable
public static createFromMutable ( DateTime $datetime ) : DateTimeImmutable
public static getLastErrors ( void ) : array
public modify ( string $modify ) : DateTimeImmutable
public static __set_state ( array $array ) : DateTimeImmutable
public setDate ( int $year , int $month , int $day ) : DateTimeImmutable
public setISODate ( int $year , int $week [, int $day = 1 ] ) : DateTimeImmutable
public setTime ( int $hour , int $minute [, int $second = 0 [, int $microseconds = 0 ]] ) : DateTimeImmutable
public setTimestamp ( int $unixtimestamp ) : DateTimeImmutable
public setTimezone ( DateTimeZone $timezone ) : DateTimeImmutable
public sub ( DateInterval $interval ) : DateTimeImmutable
public diff ( DateTimeInterface $datetime2 [, bool $absolute = FALSE ] ) : DateInterval
public format ( string $format ) : string
public getOffset ( void ) : int
public getTimestamp ( void ) : int
public getTimezone ( void ) : DateTimeZone
public __wakeup ( void )
}

Table of Contents

  • DateTimeImmutable::add — Adds an 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::createFromMutable — Returns new DateTimeImmutable object 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


Adds an amount of days, months, years, hours, minutes and seconds

  • « DateTimeImmutable
  • DateTimeImmutable::__construct »
  • PHP Manual
  • DateTimeImmutable
  • Adds an amount of days, months, years, hours, minutes and seconds

DateTimeImmutable::add

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::add — Adds an amount of days, months, years, hours, minutes and seconds

Description

public DateTimeImmutable::add ( DateInterval $interval ) : DateTimeImmutable

Like DateTime::add() but works with DateTimeImmutable.


Returns new DateTimeImmutable object

  • « DateTimeImmutable::add
  • DateTimeImmutable::createFromFormat »
  • PHP Manual
  • DateTimeImmutable
  • Returns new DateTimeImmutable object

DateTimeImmutable::__construct

date_create_immutable

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::__construct -- date_create_immutable — Returns new DateTimeImmutable object

Description

Object oriented style

public DateTimeImmutable::__construct ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )

Procedural style

date_create_immutable ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] ) : DateTimeImmutable

Like DateTime::__construct() but works with DateTimeImmutable.


Parses a time string according to a specified format

  • « DateTimeImmutable::__construct
  • DateTimeImmutable::createFromMutable »
  • PHP Manual
  • DateTimeImmutable
  • Parses a time string according to a specified format

DateTimeImmutable::createFromFormat

date_create_immutable_from_format

(PHP 5 >= 5.5.0, PHP 7)

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 $time [, DateTimeZone $timezone ] ) : DateTimeImmutable

Procedural style

date_create_immutable_from_format ( string $format , string $time [, DateTimeZone $timezone ] ) : DateTimeImmutable

Like DateTime::createFromFormat() but works with DateTimeImmutable.


Returns new DateTimeImmutable object encapsulating the given DateTime object

  • « DateTimeImmutable::createFromFormat
  • DateTimeImmutable::getLastErrors »
  • PHP Manual
  • DateTimeImmutable
  • Returns new DateTimeImmutable object encapsulating the given DateTime object

DateTimeImmutable::createFromMutable

(PHP 5 >= 5.6.0, PHP 7)

DateTimeImmutable::createFromMutable — Returns new DateTimeImmutable object encapsulating the given DateTime object

Description

public static DateTimeImmutable::createFromMutable ( DateTime $datetime ) : DateTimeImmutable

Parameters

datetime

The mutable DateTime object that you want to convert 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.

Examples

Example #1 Creating an immutable date time object

<?php
$date = new DateTime("2014-06-20 11:45 Europe/London");

$immutable = DateTimeImmutable::createFromMutable( $date );
?>

Return Values

Returns a new DateTimeImmutable instance.


Returns the warnings and errors

  • « DateTimeImmutable::createFromMutable
  • DateTimeImmutable::modify »
  • PHP Manual
  • DateTimeImmutable
  • Returns the warnings and errors

DateTimeImmutable::getLastErrors

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::getLastErrors — Returns the warnings and errors

Description

public static DateTimeImmutable::getLastErrors ( void ) : array

Like DateTime::getLastErrors() but works with DateTimeImmutable.


Creates a new object with modified timestamp

  • « DateTimeImmutable::getLastErrors
  • DateTimeImmutable::__set_state »
  • PHP Manual
  • DateTimeImmutable
  • Creates a new object with modified timestamp

DateTimeImmutable::modify

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::modify — Creates a new object with modified timestamp

Description

public DateTimeImmutable::modify ( string $modify ) : DateTimeImmutable

Creates a new DateTimeImmutable object with modified timestamp. The original object is not modified.

Parameters

object

Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

modify

A date/time string. Valid formats are explained in Date and Time Formats.

Return Values

Returns the newly created object or FALSE on failure.


The __set_state handler

  • « DateTimeImmutable::modify
  • DateTimeImmutable::setDate »
  • PHP Manual
  • DateTimeImmutable
  • The __set_state handler

DateTimeImmutable::__set_state

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::__set_state — The __set_state handler

Description

public static DateTimeImmutable::__set_state ( array $array ) : DateTimeImmutable

Like DateTime::__set_state() but works with DateTimeImmutable.


Sets the date

  • « DateTimeImmutable::__set_state
  • DateTimeImmutable::setISODate »
  • PHP Manual
  • DateTimeImmutable
  • Sets the date

DateTimeImmutable::setDate

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::setDate — Sets the date

Description

public DateTimeImmutable::setDate ( int $year , int $month , int $day ) : DateTimeImmutable

Like DateTime::setDate() but works with DateTimeImmutable.


Sets the ISO date

  • « DateTimeImmutable::setDate
  • DateTimeImmutable::setTime »
  • PHP Manual
  • DateTimeImmutable
  • Sets the ISO date

DateTimeImmutable::setISODate

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::setISODate — Sets the ISO date

Description

public DateTimeImmutable::setISODate ( int $year , int $week [, int $day = 1 ] ) : DateTimeImmutable

Like DateTime::setISODate() but works with DateTimeImmutable.


Sets the time

  • « DateTimeImmutable::setISODate
  • DateTimeImmutable::setTimestamp »
  • PHP Manual
  • DateTimeImmutable
  • Sets the time

DateTimeImmutable::setTime

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::setTime — Sets the time

Description

public DateTimeImmutable::setTime ( int $hour , int $minute [, int $second = 0 [, int $microseconds = 0 ]] ) : DateTimeImmutable

Like DateTime::setTime() but works with DateTimeImmutable.


Sets the date and time based on a Unix timestamp

  • « DateTimeImmutable::setTime
  • DateTimeImmutable::setTimezone »
  • PHP Manual
  • DateTimeImmutable
  • Sets the date and time based on a Unix timestamp

DateTimeImmutable::setTimestamp

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::setTimestamp — Sets the date and time based on a Unix timestamp

Description

public DateTimeImmutable::setTimestamp ( int $unixtimestamp ) : DateTimeImmutable

Like DateTime::setTimestamp() but works with DateTimeImmutable.


Sets the time zone

  • « DateTimeImmutable::setTimestamp
  • DateTimeImmutable::sub »
  • PHP Manual
  • DateTimeImmutable
  • Sets the time zone

DateTimeImmutable::setTimezone

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::setTimezone — Sets the time zone

Description

public DateTimeImmutable::setTimezone ( DateTimeZone $timezone ) : DateTimeImmutable

Like DateTime::setTimezone() but works with DateTimeImmutable.


Subtracts an amount of days, months, years, hours, minutes and seconds

  • « DateTimeImmutable::setTimezone
  • DateTimeInterface »
  • PHP Manual
  • DateTimeImmutable
  • Subtracts an amount of days, months, years, hours, minutes and seconds

DateTimeImmutable::sub

(PHP 5 >= 5.5.0, PHP 7)

DateTimeImmutable::sub — Subtracts an amount of days, months, years, hours, minutes and seconds

Description

public DateTimeImmutable::sub ( DateInterval $interval ) : DateTimeImmutable

Like DateTime::sub() but works with DateTimeImmutable.


The DateTimeInterface interface

(PHP 5 >= 5.5.0, PHP 7)

Introduction

DateTimeInterface is meant so that both DateTime and DateTimeImmutable can be type hinted for. It is not possible to implement this interface with userland classes.

Class synopsis

DateTimeInterface {
/* Constants */
const string ATOM = "Y-m-d\TH:i:sP" ;
const string COOKIE = "l, d-M-Y H:i:s T" ;
const string ISO8601 = "Y-m-d\TH:i:sO" ;
const string RFC822 = "D, d M y H:i:s O" ;
const string RFC850 = "l, d-M-y H:i:s T" ;
const string RFC1036 = "D, d M y H:i:s O" ;
const string RFC1123 = "D, d M Y H:i:s O" ;
const string RFC2822 = "D, d M Y H:i:s O" ;
const string RFC3339 = "Y-m-d\TH:i:sP" ;
const string RFC3339_EXTENDED = "Y-m-d\TH:i:s.vP" ;
const string RSS = "D, d M Y H:i:s O" ;
const string W3C = "Y-m-d\TH:i:sP" ;
/* Methods */
public diff ( DateTimeInterface $datetime2 [, bool $absolute = FALSE ] ) : DateInterval
public format ( string $format ) : string
public getOffset ( void ) : int
public getTimestamp ( void ) : int
public getTimezone ( void ) : DateTimeZone
public __wakeup ( void )
}

Predefined Constants

DateTimeInterface::ATOM
DATE_ATOM
Atom (example: 2005-08-15T15:52:01+00:00)
DateTimeInterface::COOKIE
DATE_COOKIE
HTTP Cookies (example: Monday, 15-Aug-2005 15:52:01 UTC)
DateTimeInterface::ISO8601
DATE_ISO8601
ISO-8601 (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 DateTime::ATOM or DATE_ATOM for compatibility with ISO-8601 instead.

DateTimeInterface::RFC822
DATE_RFC822
RFC 822 (example: Mon, 15 Aug 05 15:52:01 +0000)
DateTimeInterface::RFC850
DATE_RFC850
RFC 850 (example: Monday, 15-Aug-05 15:52:01 UTC)
DateTimeInterface::RFC1036
DATE_RFC1036
RFC 1036 (example: Mon, 15 Aug 05 15:52:01 +0000)
DateTimeInterface::RFC1123
DATE_RFC1123
RFC 1123 (example: Mon, 15 Aug 2005 15:52:01 +0000)
DateTimeInterface::RFC2822
DATE_RFC2822
RFC 2822 (example: Mon, 15 Aug 2005 15:52:01 +0000)
DateTimeInterface::RFC3339
DATE_RFC3339
Same as DATE_ATOM (since PHP 5.1.3)
DateTimeInterface::RFC3339_EXTENDED
DATE_RFC3339_EXTENDED
RFC 3339 EXTENDED format (since PHP 7.0.0) (example: 2005-08-15T15:52:01.000+00:00)
DateTimeInterface::RSS
DATE_RSS
RSS (example: Mon, 15 Aug 2005 15:52:01 +0000)
DateTimeInterface::W3C
DATE_W3C
World Wide Web Consortium (example: 2005-08-15T15:52:01+00:00)

Changelog

Version | Description
7.2.0 | The class constants of DateTime are now defined on DateTimeInterface.
5.5.8 | Trying to implement DateTimeInterface raises a fatal error now. Formerly implementing the interface didn't raise an error, but the behavior was erroneous.

Table of Contents

  • DateTime::diff — Returns the difference between two DateTime objects
  • DateTime::format — Returns date formatted according to given format
  • DateTime::getOffset — Returns the timezone offset
  • DateTime::getTimestamp — Gets the Unix timestamp
  • DateTime::getTimezone — Return time zone relative to given DateTime
  • DateTime::__wakeup — The __wakeup handler


Returns the difference between two DateTime objects

  • « DateTimeInterface
  • DateTime::format »
  • PHP Manual
  • DateTimeInterface
  • Returns the difference between two DateTime objects

DateTime::diff

DateTimeImmutable::diff

DateTimeInterface::diff

date_diff

(PHP 5 >= 5.3.0, PHP 7)

DateTime::diff -- DateTimeImmutable::diff -- DateTimeInterface::diff -- date_diff — Returns the difference between two DateTime objects

Description

Object oriented style

public DateTime::diff ( DateTimeInterface $datetime2 [, bool $absolute = FALSE ] ) : DateInterval
public DateTimeImmutable::diff ( DateTimeInterface $datetime2 [, bool $absolute = FALSE ] ) : DateInterval
public DateTimeInterface::diff ( DateTimeInterface $datetime2 [, bool $absolute = FALSE ] ) : DateInterval

Procedural style

date_diff ( DateTimeInterface $datetime1 , DateTimeInterface $datetime2 [, 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 representing the difference between the two dates or FALSE on failure.

Examples

Example #1 DateTime::diff() example

Object oriented style

<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>

Procedural style

<?php
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days');
?>

The above examples will output:

+2 days

Example #2 DateTime object comparison

Note:

As of PHP 5.2.2, 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() - Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
  • DateTime::sub() - Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object


Returns date formatted according to given format

  • « DateTime::diff
  • DateTime::getOffset »
  • PHP Manual
  • DateTimeInterface
  • Returns date formatted according to given format

DateTime::format

DateTimeImmutable::format

DateTimeInterface::format

date_format

(PHP 5 >= 5.2.1, PHP 7)

DateTime::format -- DateTimeImmutable::format -- DateTimeInterface::format -- date_format — Returns date formatted according to given format

Description

Object oriented style

public DateTime::format ( string $format ) : string
public DateTimeImmutable::format ( string $format ) : string
public DateTimeInterface::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

Format accepted by date().

Return Values

Returns the formatted date string on success or FALSE on failure.

Examples

Example #1 DateTime::format() example

Object oriented style

<?php
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:s');
?>

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

Notes

This method does not use locales. All output is in English.

See Also

  • date() - Format a local time/date


Returns the timezone offset

  • « DateTime::format
  • DateTime::getTimestamp »
  • PHP Manual
  • DateTimeInterface
  • Returns the timezone offset

DateTime::getOffset

DateTimeImmutable::getOffset

DateTimeInterface::getOffset

date_offset_get

(PHP 5 >= 5.2.1, PHP 7)

DateTime::getOffset -- DateTimeImmutable::getOffset -- DateTimeInterface::getOffset -- date_offset_get — Returns the timezone offset

Description

Object oriented style

public DateTime::getOffset ( void ) : int
public DateTimeImmutable::getOffset ( void ) : int
public DateTimeInterface::getOffset ( void ) : 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 or FALSE on failure.

Examples

Example #1 DateTime::getOffset() example

Object oriented style

<?php
$winter = new DateTime('2010-12-21', new DateTimeZone('America/New_York'));
$summer = new DateTime('2008-06-21', new DateTimeZone('America/New_York'));

echo $winter->getOffset() . "\n";
echo $summer->getOffset() . "\n";
?>

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 examples will output:

-18000
-14400

Note: -18000 = -5 hours, -14400 = -4 hours.


Gets the Unix timestamp

  • « DateTime::getOffset
  • DateTime::getTimezone »
  • PHP Manual
  • DateTimeInterface
  • Gets the Unix timestamp

DateTime::getTimestamp

DateTimeImmutable::getTimestamp

DateTimeInterface::getTimestamp

date_timestamp_get

(PHP 5 >= 5.3.0, PHP 7)

DateTime::getTimestamp -- DateTimeImmutable::getTimestamp -- DateTimeInterface::getTimestamp -- date_timestamp_get — Gets the Unix timestamp

Description

Object oriented style

public DateTime::getTimestamp ( void ) : int
public DateTimeImmutable::getTimestamp ( void ) : int
public DateTimeInterface::getTimestamp ( void ) : 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.

Examples

Example #1 DateTime::getTimestamp() example

Object oriented style

<?php
$date = new DateTime();
echo $date->getTimestamp();
?>

Procedural style

<?php
$date = date_create();
echo date_timestamp_get($date);
?>

The above examples will output something similar to:

1272509157

Notes

Using U as the parameter to DateTime::format() is an alternative when using PHP 5.2.

See Also

  • DateTime::setTimestamp() - Sets the date and time based on an Unix timestamp
  • DateTime::format() - Returns date formatted according to given format


Return time zone relative to given DateTime

  • « DateTime::getTimestamp
  • DateTime::__wakeup »
  • PHP Manual
  • DateTimeInterface
  • Return time zone relative to given DateTime

DateTime::getTimezone

DateTimeImmutable::getTimezone

DateTimeInterface::getTimezone

date_timezone_get

(PHP 5 >= 5.2.1, PHP 7)

DateTime::getTimezone -- DateTimeImmutable::getTimezone -- DateTimeInterface::getTimezone -- date_timezone_get — Return time zone relative to given DateTime

Description

Object oriented style

public DateTime::getTimezone ( void ) : DateTimeZone
public DateTimeImmutable::getTimezone ( void ) : DateTimeZone
public DateTimeInterface::getTimezone ( void ) : DateTimeZone

Procedural style

date_timezone_get ( DateTimeInterface $object ) : DateTimeZone

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 DateTime(null, new DateTimeZone('Europe/London'));
$tz = $date->getTimezone();
echo $tz->getName();
?>

Procedural style

<?php
$date = date_create(null, timezone_open('Europe/London'));
$tz = date_timezone_get($date);
echo timezone_name_get($tz);
?>

The above examples will output:

Europe/London

See Also

  • DateTime::setTimezone() - Sets the time zone for the DateTime object


The __wakeup handler

  • « DateTime::getTimezone
  • DateTimeZone »
  • PHP Manual
  • DateTimeInterface
  • The __wakeup handler

DateTime::__wakeup

DateTimeImmutable::__wakeup

DateTimeInterface::__wakeup

(PHP 5 >= 5.3.0, PHP 7)

DateTime::__wakeup -- DateTimeImmutable::__wakeup -- DateTimeInterface::__wakeup — The __wakeup handler

Description

public DateTime::__wakeup ( void )
public DateTimeImmutable::__wakeup ( void )
public DateTimeInterface::__wakeup ( void )

The __wakeup() handler.

Parameters

This function has no parameters.

Return Values

Initializes a DateTime object.


The DateTimeZone class

(PHP 5 >= 5.2.0, PHP 7)

Introduction

Representation of time zone.

Class synopsis

DateTimeZone {
/* Constants */
const integer AFRICA = 1 ;
const integer AMERICA = 2 ;
const integer ANTARCTICA = 4 ;
const integer ARCTIC = 8 ;
const integer ASIA = 16 ;
const integer ATLANTIC = 32 ;
const integer AUSTRALIA = 64 ;
const integer EUROPE = 128 ;
const integer INDIAN = 256 ;
const integer PACIFIC = 512 ;
const integer UTC = 1024 ;
const integer ALL = 2047 ;
const integer ALL_WITH_BC = 4095 ;
const integer PER_COUNTRY = 4096 ;
/* Methods */
public __construct ( string $timezone )
public getLocation ( void ) : array
public getName ( void ) : string
public getOffset ( DateTimeInterface $datetime ) : int
public getTransitions ([ int $timestamp_begin = PHP_INT_MIN [, int $timestamp_end = PHP_INT_MAX ]] ) : array
public static listAbbreviations ( void ) : array
public static listIdentifiers ([ int $what = DateTimeZone::ALL [, string $country = NULL ]] ) : array
}

Predefined Constants

DateTimeZone::AFRICA

Africa time zones.

DateTimeZone::AMERICA

America time zones.

DateTimeZone::ANTARCTICA

Antarctica time zones.

DateTimeZone::ARCTIC

Arctic time zones.

DateTimeZone::ASIA

Asia time zones.

DateTimeZone::ATLANTIC

Atlantic time zones.

DateTimeZone::AUSTRALIA

Australia time zones.

DateTimeZone::EUROPE

Europe time zones.

DateTimeZone::INDIAN

Indian time zones.

DateTimeZone::PACIFIC

Pacific time zones.

DateTimeZone::UTC

UTC time zones.

DateTimeZone::ALL

All time zones.

DateTimeZone::ALL_WITH_BC

All time zones including backwards compatible.

DateTimeZone::PER_COUNTRY

Time zones per country.

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


Creates new DateTimeZone object

  • « DateTimeZone
  • DateTimeZone::getLocation »
  • PHP Manual
  • DateTimeZone
  • Creates new DateTimeZone object

DateTimeZone::__construct

timezone_open

(PHP 5 >= 5.2.0, PHP 7)

DateTimeZone::__construct -- timezone_open — Creates new DateTimeZone object

Description

Object oriented style

public DateTimeZone::__construct ( string $timezone )

Procedural style

timezone_open ( string $timezone ) : DateTimeZone

Creates new DateTimeZone object.

Parameters

timezone

One of the supported timezone names or an offset value (+0200).

Return Values

Returns DateTimeZone on success. Procedural style returns FALSE on failure.

Errors/Exceptions

This method throws Exception if the timezone supplied is not recognised as a valid timezone.

Changelog

Version | Description
5.5.10 | The timezone parameter accepts offset values.

Examples

Example #1 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);
    } catch(Exception $e) {
        echo $e->getMessage() . '<br />';
    }
}
?>

The above example will output:

DateTimeZone::__construct() [datetimezone.--construct]: Unknown or bad timezone (Mars/Phobos)
DateTimeZone::__construct() [datetimezone.--construct]: Unknown or bad timezone (Jupiter/Europa)


Returns location information for a timezone

  • « DateTimeZone::__construct
  • DateTimeZone::getName »
  • PHP Manual
  • DateTimeZone
  • Returns location information for a timezone

DateTimeZone::getLocation

timezone_location_get

(PHP 5 >= 5.3.0, PHP 7)

DateTimeZone::getLocation -- timezone_location_get — Returns location information for a timezone

Description

Object oriented style

public DateTimeZone::getLocation ( void ) : array

Procedural style

timezone_location_get ( DateTimeZone $object ) : array

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("Europe/Prague");
print_r($tz->getLocation());
print_r(timezone_location_get($tz));
?>

The above example will output:

Array
(
    [country_code] => CZ
    [latitude] => 50.08333
    [longitude] => 14.43333
    [comments] =>
)
Array
(
    [country_code] => CZ
    [latitude] => 50.08333
    [longitude] => 14.43333
    [comments] =>
)


Returns the name of the timezone

  • « DateTimeZone::getLocation
  • DateTimeZone::getOffset »
  • PHP Manual
  • DateTimeZone
  • Returns the name of the timezone

DateTimeZone::getName

timezone_name_get

(PHP 5 >= 5.2.0, PHP 7)

DateTimeZone::getName -- timezone_name_get — Returns the name of the timezone

Description

Object oriented style

public DateTimeZone::getName ( void ) : 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

One of the timezone names in the list of timezones.


Returns the timezone offset from GMT

  • « DateTimeZone::getName
  • DateTimeZone::getTransitions »
  • PHP Manual
  • DateTimeZone
  • Returns the timezone offset from GMT

DateTimeZone::getOffset

timezone_offset_get

(PHP 5 >= 5.2.0, PHP 7)

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 on success or FALSE on failure.

Changelog

Version | Description
5.5.19, 5.6.3 | datetime type changed to DateTimeInterface. Previously, DateTime.

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


Returns all transitions for the timezone

  • « DateTimeZone::getOffset
  • DateTimeZone::listAbbreviations »
  • PHP Manual
  • DateTimeZone
  • Returns all transitions for the timezone

DateTimeZone::getTransitions

timezone_transitions_get

(PHP 5 >= 5.2.0, PHP 7)

DateTimeZone::getTransitions -- timezone_transitions_get — Returns all transitions for the timezone

Description

Object oriented style

public DateTimeZone::getTransitions ([ int $timestamp_begin = PHP_INT_MIN [, int $timestamp_end = PHP_INT_MAX ]] ) : array

Procedural style

timezone_transitions_get ( DateTimeZone $object [, int $timestamp_begin = PHP_INT_MIN [, int $timestamp_end = PHP_INT_MAX ]] ) : array

Parameters

object

Procedural style only: A DateTimeZone object returned by timezone_open()

timestamp_begin

Begin timestamp.

timestamp_end

End timestamp.

Return Values

Returns numerically indexed array containing associative array with all transitions on success or FALSE on failure.

Changelog

Version | Description
5.3.0 | The optional timestamp_begin and timestamp_end were added.

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] => -9223372036854775808
            [time] => -292277022657-01-27T08:29:52+0000
            [offset] => 3600
            [isdst] => 1
            [abbr] => BST
        )

    [1] => Array
        (
            [ts] => -1691964000
            [time] => 1916-05-21T02:00:00+0000
            [offset] => 3600
            [isdst] => 1
            [abbr] => BST
        )

    [2] => Array
        (
            [ts] => -1680472800
            [time] => 1916-10-01T02:00:00+0000
            [offset] => 0
            [isdst] =>
            [abbr] => GMT
        )

)


Returns associative array containing dst, offset and the timezone name

  • « DateTimeZone::getTransitions
  • DateTimeZone::listIdentifiers »
  • PHP Manual
  • DateTimeZone
  • Returns associative array containing dst, offset and the timezone name

DateTimeZone::listAbbreviations

timezone_abbreviations_list

(PHP 5 >= 5.2.0, PHP 7)

DateTimeZone::listAbbreviations -- timezone_abbreviations_list — Returns associative array containing dst, offset and the timezone name

Description

Object oriented style

public static DateTimeZone::listAbbreviations ( void ) : array

Procedural style

timezone_abbreviations_list ( void ) : array

Note:

The data for this function are precompiled for performance reasons, and are not updated when using a newer » timezonedb.

Return Values

Returns array on success or FALSE on failure.

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] => 1
            [offset] => -14400
            [timezone_id] => America/Porto_Acre
        )

    [1] => Array
        (
            [dst] => 1
            [offset] => -14400
            [timezone_id] => America/Eirunepe
        )

    [2] => Array
        (
            [dst] => 1
            [offset] => -14400
            [timezone_id] => America/Rio_Branco
        )

    [3] => Array
        (
            [dst] => 1
            [offset] => -14400
            [timezone_id] => Brazil/Acre
        )

)

See Also

  • timezone_identifiers_list() - Alias of DateTimeZone::listIdentifiers


Returns a numerically indexed array containing all defined timezone identifiers

  • « DateTimeZone::listAbbreviations
  • DateInterval »
  • PHP Manual
  • DateTimeZone
  • Returns a numerically indexed array containing all defined timezone identifiers

DateTimeZone::listIdentifiers

timezone_identifiers_list

(PHP 5 >= 5.2.0, PHP 7)

DateTimeZone::listIdentifiers -- timezone_identifiers_list — Returns a numerically indexed array containing all defined timezone identifiers

Description

Object oriented style

public static DateTimeZone::listIdentifiers ([ int $what = DateTimeZone::ALL [, string $country = NULL ]] ) : array

Procedural style

timezone_identifiers_list ([ int $what = DateTimeZone::ALL [, string $country = NULL ]] ) : array

Parameters

what

One of the DateTimeZone class constants (or a combination).

country

A two-letter ISO 3166-1 compatible country code.

Note: This option is only used when what is set to DateTimeZone::PER_COUNTRY.

Return Values

Returns array on success or FALSE on failure.

Changelog

Version | Description
5.3.0 | Added the optional what and country parameters.

Examples

Example #1 A timezone_identifiers_list() example

<?php
$timezone_identifiers = DateTimeZone::listIdentifiers();
for ($i=0; $i < 5; $i++) {
    echo "$timezone_identifiers[$i]\n";
}
?>

The above example will output something similar to:

Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
Africa/Asmara

See Also

  • timezone_abbreviations_list() - Alias of DateTimeZone::listAbbreviations


The DateInterval class

(PHP 5 >= 5.3.0, PHP 7)

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 DateTime's constructor supports.

Class synopsis

DateInterval {
/* Properties */
public integer $y ;
public integer $m ;
public integer $d ;
public integer $h ;
public integer $i ;
public integer $s ;
public float $f ;
public integer $invert ;
public mixed $days ;
/* Methods */
public __construct ( string $interval_spec )
public static createFromDateString ( string $time ) : DateInterval
public format ( string $format ) : string
}

Properties

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 DateTime::diff(), then this is the total number of days between the start and end dates. Otherwise, days will be FALSE.

Before PHP 5.4.20/5.5.4 instead of FALSE you will receive -99999 upon accessing the property.

Changelog

Version | Description
7.1.0 | The f property was added.

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


Creates a new DateInterval object

  • « DateInterval
  • DateInterval::createFromDateString »
  • PHP Manual
  • DateInterval
  • Creates a new DateInterval object

DateInterval::__construct

(PHP 5 >= 5.3.0, PHP 7)

DateInterval::__construct — Creates a new DateInterval object

Description

public DateInterval::__construct ( string $interval_spec )

Creates a new DateInterval object.

Parameters

interval_spec

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.

interval_spec Period Designators
Period Designator | Description
Y | years
M | months
D | days
W | weeks. These get converted into days, so 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 Exception when the interval_spec cannot be parsed as an interval.

Examples

Example #1 DateInterval example

<?php

$interval = new DateInterval('P2Y4DT6H8M');
var_dump($interval);

?>

The above example will output:

object(DateInterval)#1 (8) {
  ["y"]=>
  int(2)
  ["m"]=>
  int(0)
  ["d"]=>
  int(4)
  ["h"]=>
  int(6)
  ["i"]=>
  int(8)
  ["s"]=>
  int(0)
  ["invert"]=>
  int(0)
  ["days"]=>
  bool(false)
}

See Also

  • DateInterval::format() - Formats the interval
  • DateTime::add() - Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
  • 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


Sets up a DateInterval from the relative parts of the string

  • « DateInterval::__construct
  • DateInterval::format »
  • PHP Manual
  • DateInterval
  • Sets up a DateInterval from the relative parts of the string

DateInterval::createFromDateString

(PHP 5 >= 5.3.0, PHP 7)

DateInterval::createFromDateString — Sets up a DateInterval from the relative parts of the string

Description

public static DateInterval::createFromDateString ( string $time ) : DateInterval

Uses the normal date parsers and sets up a DateInterval from the relative parts of the parsed string.

Parameters

time

A date with relative parts. Specifically, the relative formats supported by the parser used for strtotime() and DateTime will be used to construct the DateInterval.

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');
?>

Return Values

Returns a new DateInterval instance.


Formats the interval

  • « DateInterval::createFromDateString
  • DatePeriod »
  • PHP Manual
  • DateInterval
  • Formats the interval

DateInterval::format

(PHP 5 >= 5.3.0, PHP 7)

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.

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

Changelog

Version | Description
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

See Also

  • DateTime::diff() - Returns the difference between two DateTime objects


The DatePeriod class

(PHP 5 >= 5.3.0, PHP 7)

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

DatePeriod implements Traversable {
/* Constants */
const integer EXCLUDE_START_DATE = 1 ;
/* Properties */
public integer $recurrences ;
public boolean $include_start_date ;
public DateTimeInterface $start ;
public DateTimeInterface $current ;
public DateTimeInterface $end ;
public DateInterval $interval ;
/* Methods */
public __construct ( DateTimeInterface $start , DateInterval $interval , int $recurrences [, int $options ] )
public __construct ( DateTimeInterface $start , DateInterval $interval , DateTimeInterface $end [, int $options ] )
public __construct ( string $isostr [, int $options ] )
public getDateInterval ( void ) : DateInterval
public getEndDate ( void ) : DateTimeInterface
getRecurrences ( void ) : int
public getStartDate ( void ) : DateTimeInterface
}

Predefined Constants

DatePeriod::EXCLUDE_START_DATE

Exclude start date, used in DatePeriod::__construct().

Properties

recurrences

The number of recurrences, if the DatePeriod instance had been created by explicitly passing $recurrences. See also DatePeriod::getRecurrences().

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
5.3.27, 5.4.17 | The public properties recurrences, include_start_date, start, current, end and interval have been exposed.

Table of Contents

  • DatePeriod::__construct — Creates a new DatePeriod object
  • DatePeriod::getDateInterval — Gets the interval
  • DatePeriod::getEndDate — Gets the end date
  • DatePeriod::getRecurrences — Gets the number of recurrences
  • DatePeriod::getStartDate — Gets the start date


Creates a new DatePeriod object

  • « DatePeriod
  • DatePeriod::getDateInterval »
  • PHP Manual
  • DatePeriod
  • Creates a new DatePeriod object

DatePeriod::__construct

(PHP 5 >= 5.3.0, PHP 7)

DatePeriod::__construct — Creates a new DatePeriod object

Description

public DatePeriod::__construct ( DateTimeInterface $start , DateInterval $interval , int $recurrences [, int $options ] )
public DatePeriod::__construct ( DateTimeInterface $start , DateInterval $interval , DateTimeInterface $end [, int $options ] )
public DatePeriod::__construct ( string $isostr [, int $options ] )

Creates a new DatePeriod object.

Parameters

start

The start date of the period.

interval

The interval between recurrences within the period.

recurrences

The number of recurrences.

end

The end date of the period.

isostr

An ISO 8601 repeating interval specification.

options

Can be set to DatePeriod::EXCLUDE_START_DATE to exclude the start date from the set of recurring dates within the period.

Changelog

Version | Description
5.5.8 | end type changed to DateTimeInterface. Previously, DateTime.
5.5.0 | start type changed to DateTimeInterface. Previously, DateTime.

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:

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

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.


Gets the interval

  • « DatePeriod::__construct
  • DatePeriod::getEndDate »
  • PHP Manual
  • DatePeriod
  • Gets the interval

DatePeriod::getDateInterval

(PHP 5 >= 5.6.5, PHP 7)

DatePeriod::getDateInterval — Gets the interval

Description

Object oriented style

public DatePeriod::getDateInterval ( void ) : 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 = new DatePeriod('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


Gets the end date

  • « DatePeriod::getDateInterval
  • DatePeriod::getRecurrences »
  • PHP Manual
  • DatePeriod
  • Gets the end date

DatePeriod::getEndDate

(PHP 5 >= 5.6.5, PHP 7)

DatePeriod::getEndDate — Gets the end date

Description

Object oriented style

public DatePeriod::getEndDate ( void ) : 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 DateTime object 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


Gets the number of recurrences

  • « DatePeriod::getEndDate
  • DatePeriod::getStartDate »
  • PHP Manual
  • DatePeriod
  • Gets the number of recurrences

DatePeriod::getRecurrences

(PHP 7 >= 7.2.17/7.3.4)

DatePeriod::getRecurrences — Gets the number of recurrences

Description

Object oriented style

DatePeriod::getRecurrences ( void ) : int

Get the number of recurrences.

Parameters

This function has no parameters.

Return Values

Returns the number of recurrences.

See Also

  • DatePeriod::$recurrences


Gets the start date

  • « DatePeriod::getRecurrences
  • Date/Time Functions »
  • PHP Manual
  • DatePeriod
  • Gets the start date

DatePeriod::getStartDate

(PHP 5 >= 5.6.5, PHP 7)

DatePeriod::getStartDate — Gets the start date

Description

Object oriented style

public DatePeriod::getStartDate ( void ) : 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 = new DatePeriod('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


Date/Time Functions

Table of Contents

  • checkdate — Validate a Gregorian date
  • date_add — Alias of DateTime::add
  • date_create_from_format — Alias of DateTime::createFromFormat
  • date_create_immutable_from_format — Alias of DateTimeImmutable::createFromFormat
  • date_create_immutable — Alias of DateTimeImmutable::__construct
  • date_create — Alias of DateTime::__construct
  • 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 DateTime::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_from_format — Get info about given date formatted according to the specified format
  • date_parse — Returns associative array with detailed info about given date
  • 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
  • date — Format a local time/date
  • 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 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 the timezone name from abbreviation
  • 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


Validate a Gregorian date

  • « Date/Time Functions
  • date_add »
  • PHP Manual
  • Date/Time Functions
  • Validate a Gregorian date

checkdate

(PHP 4, PHP 5, PHP 7)

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


Alias of DateTime::add

  • « checkdate
  • date_create_from_format »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::add

date_add

(PHP 5 >= 5.3.0, PHP 7)

date_add — Alias of DateTime::add()

Description

This function is an alias of: DateTime::add()


Alias of DateTime::createFromFormat

  • « date_add
  • date_create_immutable_from_format »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::createFromFormat

date_create_from_format

(PHP 5 >= 5.3.0, PHP 7)

date_create_from_format — Alias of DateTime::createFromFormat()

Description

This function is an alias of: DateTime::createFromFormat()


Alias of DateTimeImmutable::createFromFormat

  • « date_create_from_format
  • date_create_immutable »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTimeImmutable::createFromFormat

date_create_immutable_from_format

(PHP 5 >= 5.5.0, PHP 7)

date_create_immutable_from_format — Alias of DateTimeImmutable::createFromFormat()

Description

This function is an alias of: DateTimeImmutable::createFromFormat()


Alias of DateTimeImmutable::__construct

  • « date_create_immutable_from_format
  • date_create »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTimeImmutable::__construct

date_create_immutable

(PHP 5 >= 5.5.0, PHP 7)

date_create_immutable — Alias of DateTimeImmutable::__construct()

Description

This function is an alias of: DateTimeImmutable::__construct()


Alias of DateTime::__construct

  • « date_create_immutable
  • date_date_set »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::__construct

date_create

(PHP 5 >= 5.2.0, PHP 7)

date_create — Alias of DateTime::__construct()

Description

This function is an alias of: DateTime::__construct()


Alias of DateTime::setDate

  • « date_create
  • date_default_timezone_get »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::setDate

date_date_set

(PHP 5 >= 5.2.0, PHP 7)

date_date_set — Alias of DateTime::setDate()

Description

This function is an alias of: DateTime::setDate()


Gets the default timezone used by all date/time functions in a script

  • « date_date_set
  • date_default_timezone_set »
  • PHP Manual
  • Date/Time Functions
  • Gets the default timezone used by all date/time functions in a script

date_default_timezone_get

(PHP 5 >= 5.1.0, PHP 7)

date_default_timezone_get — Gets the default timezone used by all date/time functions in a script

Description

date_default_timezone_get ( void ) : 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)

  • Prior to PHP 5.4.0 only: Reading the TZ environment variable (if non empty)

  • Reading the value of the date.timezone ini option (if set)

  • Prior to PHP 5.4.0 only: Querying the host operating system (if supported and allowed by the OS). This uses an algorithm that has to guess the timezone. This is by no means going to work correctly for every situation. A warning is shown when this stage is reached. Do not rely on it to be guessed correctly, and set date.timezone to the correct timezone instead.

If none of the above succeed, date_default_timezone_get() will return a default timezone of UTC.

Return Values

Returns a string.

Changelog

Version | Description
5.4.0 | The TZ environment variable is no longer used to guess the timezone.
5.4.0 | The timezone is no longer guessed from information available through the operating system as the guessed timezone can not be relied on.

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() . '<br />';
}

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


Sets the default timezone used by all date/time functions in a script

  • « date_default_timezone_get
  • date_diff »
  • PHP Manual
  • Date/Time Functions
  • Sets the default timezone used by all date/time functions in a script

date_default_timezone_set

(PHP 5 >= 5.1.0, PHP 7)

date_default_timezone_set — Sets the default timezone used by all date/time functions in a script

Description

date_default_timezone_set ( string $timezone_identifier ) : bool

date_default_timezone_set() sets the default timezone used by all date/time functions.

Note:

Since PHP 5.1.0 (when the date/time functions were rewritten), every call to a date/time function will generate a E_NOTICE if the timezone isn't valid, and/or a E_WARNING message if using the system settings or the TZ environment variable.

Instead of using this function to set the default timezone in your script, you can also use the INI setting date.timezone to set the default timezone.

Parameters

timezone_identifier

The timezone identifier, like UTC or Europe/Lisbon. The list of valid identifiers is available in the List of Supported Timezones.

Return Values

This function returns FALSE if the timezone_identifier 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();

if (strcmp($script_tz, ini_get('date.timezone'))){
    echo 'Script timezone differs from ini-set timezone.';
} else {
    echo 'Script timezone and ini-set timezone match.';
}
?>

Changelog

Version | Description
5.3.0 | Now throws E_WARNING rather than E_STRICT.
5.1.2 | The function started to validate the timezone_identifier parameter.

See Also

  • date_default_timezone_get() - Gets the default timezone used by all date/time functions in a script
  • List of Supported Timezones


Alias of DateTime::diff

  • « date_default_timezone_set
  • date_format »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::diff

date_diff

(PHP 5 >= 5.3.0, PHP 7)

date_diff — Alias of DateTime::diff()

Description

This function is an alias of: DateTime::diff()


Alias of DateTime::format

  • « date_diff
  • date_get_last_errors »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::format

date_format

(PHP 5 >= 5.2.0, PHP 7)

date_format — Alias of DateTime::format()

Description

This function is an alias of: DateTime::format()


Alias of DateTime::getLastErrors

  • « date_format
  • date_interval_create_from_date_string »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::getLastErrors

date_get_last_errors

(PHP 5 >= 5.3.0, PHP 7)

date_get_last_errors — Alias of DateTime::getLastErrors()

Description

This function is an alias of: DateTime::getLastErrors()


Alias of DateInterval::createFromDateString

  • « date_get_last_errors
  • date_interval_format »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateInterval::createFromDateString

date_interval_create_from_date_string

(PHP 5 >= 5.3.0, PHP 7)

date_interval_create_from_date_string — Alias of DateInterval::createFromDateString()

Description

This function is an alias of: DateInterval::createFromDateString()


Alias of DateInterval::format

  • « date_interval_create_from_date_string
  • date_isodate_set »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateInterval::format

date_interval_format

(PHP 5 >= 5.3.0, PHP 7)

date_interval_format — Alias of DateInterval::format()

Description

This function is an alias of: DateInterval::format()


Alias of DateTime::setISODate

  • « date_interval_format
  • date_modify »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::setISODate

date_isodate_set

(PHP 5 >= 5.2.0, PHP 7)

date_isodate_set — Alias of DateTime::setISODate()

Description

This function is an alias of: DateTime::setISODate()


Alias of DateTime::modify

  • « date_isodate_set
  • date_offset_get »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::modify

date_modify

(PHP 5 >= 5.2.0, PHP 7)

date_modify — Alias of DateTime::modify()

Description

This function is an alias of: DateTime::modify()


Alias of DateTime::getOffset

  • « date_modify
  • date_parse_from_format »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::getOffset

date_offset_get

(PHP 5 >= 5.2.0, PHP 7)

date_offset_get — Alias of DateTime::getOffset()

Description

This function is an alias of: DateTime::getOffset()


Get info about given date formatted according to the specified format

  • « date_offset_get
  • date_parse »
  • PHP Manual
  • Date/Time Functions
  • Get info about given date formatted according to the specified format

date_parse_from_format

(PHP 5 >= 5.3.0, PHP 7)

date_parse_from_format — Get info about given date formatted according to the specified format

Description

date_parse_from_format ( string $format , string $date ) : array

Returns associative array with detailed info about given date.

Parameters

format

Format accepted by DateTime::createFromFormat().

date

String representing the date.

Return Values

Returns associative array with detailed info about given date.

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 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] =>
    [warning_count] => 0
    [warnings] => Array
        (
        )

    [error_count] => 0
    [errors] => Array
        (
        )

    [is_localtime] => 1
    [zone_type] => 1
    [zone] => 3600
    [is_dst] =>
)

See Also

  • DateTime::createFromFormat() - Parses a time string according to a specified format
  • checkdate() - Validate a Gregorian date


Returns associative array with detailed info about given date

  • « date_parse_from_format
  • date_sub »
  • PHP Manual
  • Date/Time Functions
  • Returns associative array with detailed info about given date

date_parse

(PHP 5 >= 5.2.0, PHP 7)

date_parse — Returns associative array with detailed info about given date

Description

date_parse ( string $date ) : array

Parameters

date

Date in format accepted by strtotime().

Return Values

Returns array with information about the parsed date on success or FALSE on failure.

Errors/Exceptions

In case the date format has an error, the element 'errors' will contains 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

<?php
print_r(date_parse("2006-12-12 10:00:00.5"));
?>

The above example will output:

Array
(
    [year] => 2006
    [month] => 12
    [day] => 12
    [hour] => 10
    [minute] => 0
    [second] => 0
    [fraction] => 0.5
    [warning_count] => 0
    [warnings] => Array()
    [error_count] => 0
    [errors] => Array()
    [is_localtime] =>
)

Relative formats do not influence the values parsed from absolute formats, but are parsed into the "relative" element.

Example #2 date_parse() with relative formats

<?php
print_r(date_parse("2006-12-12 10:00:00.5 +1 week +1 hour"));
?>

The above example will output:

Array
(
    [year] => 2006
    [month] => 12
    [day] => 12
    [hour] => 10
    [minute] => 0
    [second] => 0
    [fraction] => 0.5
    [warning_count] => 0
    [warnings] => Array
        (
        )

    [error_count] => 0
    [errors] => Array
        (
        )

    [is_localtime] =>
    [relative] => Array
        (
            [year] => 0
            [month] => 0
            [day] => 7
            [hour] => 1
            [minute] => 0
            [second] => 0
        )

)

See Also

  • checkdate() - Validate a Gregorian date
  • getdate() - Get date/time information


Alias of DateTime::sub

  • « date_parse
  • date_sun_info »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::sub

date_sub

(PHP 5 >= 5.3.0, PHP 7)

date_sub — Alias of DateTime::sub()

Description

This function is an alias of: DateTime::sub()


Returns an array with information about sunset/sunrise and twilight begin/end

  • « date_sub
  • date_sunrise »
  • PHP Manual
  • Date/Time Functions
  • Returns an array with information about sunset/sunrise and twilight begin/end

date_sun_info

(PHP 5 >= 5.1.2, PHP 7)

date_sun_info — Returns an array with information about sunset/sunrise and twilight begin/end

Description

date_sun_info ( int $time , float $latitude , float $longitude ) : array

Parameters

time

Timestamp.

latitude

Latitude in degrees.

longitude

Longitude in degrees.

Return Values

Returns array on success or FALSE on failure. The structure of the array is detailed in the following list:

sunrise
The time of the sunrise (zenith angle = 90°35').
sunset
The time of the sunset (zenith angle = 90°35').
transit
The time 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
5.2.2 | The order of latitude and longitude has been swapped.

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

<?php
var_dump(date_sun_info(strtotime("2017-12-21"), 90, 0));
?>

The above example will output:

array(9) {
  ["sunrise"]=>
  bool(false)
  ["sunset"]=>
  bool(false)
  ["transit"]=>
  int(1513857490)
  ["civil_twilight_begin"]=>
  bool(false)
  ["civil_twilight_end"]=>
  bool(false)
  ["nautical_twilight_begin"]=>
  bool(false)
  ["nautical_twilight_end"]=>
  bool(false)
  ["astronomical_twilight_begin"]=>
  bool(false)
  ["astronomical_twilight_end"]=>
  bool(false)
}

Example #3 Midnight sun

<?php
var_dump(date_sun_info(strtotime("2017-06-21"), 90, 0));
?>

The above example will output:

array(9) {
  ["sunrise"]=>
  bool(true)
  ["sunset"]=>
  bool(true)
  ["transit"]=>
  int(1498046510)
  ["civil_twilight_begin"]=>
  bool(true)
  ["civil_twilight_end"]=>
  bool(true)
  ["nautical_twilight_begin"]=>
  bool(true)
  ["nautical_twilight_end"]=>
  bool(true)
  ["astronomical_twilight_begin"]=>
  bool(true)
  ["astronomical_twilight_end"]=>
  bool(true)
}

See Also

  • date_sunrise() - Returns time of sunrise for a given day and location
  • date_sunset() - Returns time of sunset for a given day and location


Returns time of sunrise for a given day and location

  • « date_sun_info
  • date_sunset »
  • PHP Manual
  • Date/Time Functions
  • Returns time of sunrise for a given day and location

date_sunrise

(PHP 5, PHP 7)

date_sunrise — Returns time of sunrise for a given day and location

Description

date_sunrise ( int $timestamp [, int $format = SUNFUNCS_RET_STRING [, float $latitude = ini_get("date.default_latitude") [, float $longitude = ini_get("date.default_longitude") [, float $zenith = ini_get("date.sunrise_zenith") [, float $gmt_offset = 0 ]]]]] ) : mixed

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.

format

format 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 integer (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.

gmtoffset

Specified in hours. The gmtoffset is ignored, if format is SUNFUNCS_RET_TIMESTAMP.

Return Values

Returns the sunrise time in a specified format 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_NOTICE if the time zone is not valid, and/or a E_STRICT or E_WARNING message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

Changelog

Version | Description
5.1.0 | Now issues the E_STRICT and E_NOTICE time zone errors.

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:

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:

bool(false)

See Also

  • date_sunset() - Returns time of sunset for a given day and location
  • date_sun_info() - Returns an array with information about sunset/sunrise and twilight begin/end


Returns time of sunset for a given day and location

  • « date_sunrise
  • date_time_set »
  • PHP Manual
  • Date/Time Functions
  • Returns time of sunset for a given day and location

date_sunset

(PHP 5, PHP 7)

date_sunset — Returns time of sunset for a given day and location

Description

date_sunset ( int $timestamp [, int $format = SUNFUNCS_RET_STRING [, float $latitude = ini_get("date.default_latitude") [, float $longitude = ini_get("date.default_longitude") [, float $zenith = ini_get("date.sunset_zenith") [, float $gmt_offset = 0 ]]]]] ) : mixed

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.

format

format 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 integer (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.

gmtoffset

Specified in hours. The gmtoffset is ignored, if format is SUNFUNCS_RET_TIMESTAMP.

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT or E_WARNING message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

Changelog

Version | Description
5.1.0 | Now issues the E_STRICT and E_NOTICE time zone errors.

Return Values

Returns the sunset time in a specified format 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.

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:

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:

bool(false)

See Also

  • date_sunrise() - Returns time of sunrise for a given day and location
  • date_sun_info() - Returns an array with information about sunset/sunrise and twilight begin/end


Alias of DateTime::setTime

  • « date_sunset
  • date_timestamp_get »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::setTime

date_time_set

(PHP 5 >= 5.2.0, PHP 7)

date_time_set — Alias of DateTime::setTime()

Description

This function is an alias of: DateTime::setTime()


Alias of DateTime::getTimestamp

  • « date_time_set
  • date_timestamp_set »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::getTimestamp

date_timestamp_get

(PHP 5 >= 5.3.0, PHP 7)

date_timestamp_get — Alias of DateTime::getTimestamp()

Description

This function is an alias of: DateTime::getTimestamp()


Alias of DateTime::setTimestamp

  • « date_timestamp_get
  • date_timezone_get »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::setTimestamp

date_timestamp_set

(PHP 5 >= 5.3.0, PHP 7)

date_timestamp_set — Alias of DateTime::setTimestamp()

Description

This function is an alias of: DateTime::setTimestamp()


Alias of DateTime::getTimezone

  • « date_timestamp_set
  • date_timezone_set »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::getTimezone

date_timezone_get

(PHP 5 >= 5.2.0, PHP 7)

date_timezone_get — Alias of DateTime::getTimezone()

Description

This function is an alias of: DateTime::getTimezone()


Alias of DateTime::setTimezone

  • « date_timezone_get
  • date »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTime::setTimezone

date_timezone_set

(PHP 5 >= 5.2.0, PHP 7)

date_timezone_set — Alias of DateTime::setTimezone()

Description

This function is an alias of: DateTime::setTimezone()


Format a local time/date

  • « date_timezone_set
  • getdate »
  • PHP Manual
  • Date/Time Functions
  • Format a local time/date

date

(PHP 4, PHP 5, PHP 7)

date — Format a local time/date

Description

date ( string $format [, int $timestamp = time() ] ) : string

Returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given. In other words, timestamp is optional and defaults to the value of time().

Parameters

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 (added in PHP 5.1.0) | 1 (for Monday) through 7 (for Sunday)
S | English ordinal suffix for the day of the month, 2 characters | st, nd, rd or th. Works well with j
w | Numeric representation of the day of the week | 0 (for Sunday) through 6 (for Saturday)
z | The day of the year (starting from 0) | 0 through 365
Week --- ---
W | ISO-8601 week number of year, weeks starting on Monday | 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. (added in PHP 5.1.0) | Examples: 1999 or 2003
Y | A full numeric representation of a year, 4 digits | Examples: 1999 or 2003
y | A two digit representation of a year | Examples: 99 or 03
Time --- ---
a | Lowercase Ante meridiem and Post meridiem | am or pm
A | Uppercase Ante meridiem and Post meridiem | AM or PM
B | Swatch Internet time | 000 through 999
g | 12-hour format of an hour without leading zeros | 1 through 12
G | 24-hour format of an hour without leading zeros | 0 through 23
h | 12-hour format of an hour with leading zeros | 01 through 12
H | 24-hour format of an hour with leading zeros | 00 through 23
i | Minutes with leading zeros | 00 to 59
s | Seconds with leading zeros | 00 through 59
u | Microseconds (added in PHP 5.2.2). Note that date() will always generate 000000 since it takes an integer parameter, whereas DateTime::format() does support microseconds if DateTime was created with microseconds. | Example: 654321
v | Milliseconds (added in PHP 7.0.0). Same note applies as for u. | Example: 654
Timezone --- ---
e | Timezone identifier (added in PHP 5.1.0) | Examples: UTC, GMT, Atlantic/Azores
I (capital i) | Whether or not the date is in daylight saving time | 1 if Daylight Saving Time, 0 otherwise.
O | Difference to Greenwich time (GMT) without colon between hours and minutes | Example: +0200
P | Difference to Greenwich time (GMT) with colon between hours and minutes (added in PHP 5.1.3) | Example: +02:00
T | Timezone abbreviation | Examples: EST, MDT ...
Z | Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. | -43200 through 50400
Full Date/Time --- ---
c | ISO 8601 date (added in PHP 5) | 2004-02-12T15:19:21+00:00
r | » RFC 2822 formatted date | Example: Thu, 21 Dec 2000 16:01:07 +0200
U | Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) | See also time()

Unrecognized characters in the format string will be printed as-is. The Z format will always return 0 when using gmdate().

Note:

Since this function only accepts integer timestamps the u format character is only useful when using the date_format() function with user based timestamps created with date_create().

timestamp

The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().

Return Values

Returns a formatted date string. If a non-numeric value is used for timestamp, FALSE is returned and an E_WARNING level error is emitted.

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT or E_WARNING message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

Changelog

Version | Description
5.1.1 | There are useful constants of standard date/time formats that can be used to specify the format parameter.
5.1.0 | The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer). However, before PHP 5.1.0 this range was limited from 01-01-1970 to 19-01-2038 on some systems (e.g. Windows).
5.1.0 | Now issues the E_STRICT and E_NOTICE time zone errors.

Examples

Example #1 date() examples

<?php
// set the default timezone to use. Available since PHP 5.1
date_default_timezone_set('UTC');

// Prints something like: Monday
echo date("l");

// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');

// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));

/* use the constants in the format parameter */
// prints something like: Wed, 25 Sep 2013 15:28:57 -0700
echo date(DATE_RFC2822);

// 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');
?>

It is possible to use date() and mktime() together to find dates in the future or the past.

Example #3 date() and mktime() example

<?php
$tomorrow  = mktime(0, 0, 0, date("m")  , date("d")+1, date("Y"));
$lastmonth = mktime(0, 0, 0, date("m")-1, date("d"),   date("Y"));
$nextyear  = mktime(0, 0, 0, date("m"),   date("d"),   date("Y")+1);
?>

Note:

This can be more reliable than simply adding or subtracting the number of seconds in a day or month to a timestamp because of daylight saving time.

Some examples of date() formatting. Note that you should escape any other characters, as any which currently have a special meaning will produce undesirable results, and other characters may be assigned meaning in future PHP versions. When escaping, be sure to use single quotes to prevent characters like \n from becoming newlines.

Example #4 date() Formatting

<?php
// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the
// Mountain Standard Time (MST) Time Zone

$today = date("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm
$today = date("m.d.y");                         // 03.10.01
$today = date("j, n, Y");                       // 10, 3, 2001
$today = date("Ymd");                           // 20010310
$today = date('h-i-s, j-m-y, it is w Day');     // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.');   // it is the 10th day.
$today = date("D M j G:i:s T Y");               // Sat Mar 10 17:16:18 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:18 m is month
$today = date("H:i:s");                         // 17:16:18
$today = date("Y-m-d H:i:s");                   // 2001-03-10 17:16:18 (the MySQL DATETIME format)
?>

To format dates in other languages, you should use the setlocale() and strftime() functions 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'] since PHP 5.1.

See Also

  • gmdate() - Format a GMT/UTC date/time
  • idate() - Format a local time/date as integer
  • getdate() - Get date/time information
  • getlastmod() - Gets time of last page modification
  • mktime() - Get Unix timestamp for a date
  • strftime() - Format a local time/date according to locale settings
  • time() - Return current Unix timestamp
  • strtotime() - Parse about any English textual datetime description into a Unix timestamp
  • Predefined DateTime Constants


Get date/time information

  • « date
  • gettimeofday »
  • PHP Manual
  • Date/Time Functions
  • Get date/time information

getdate

(PHP 4, PHP 5, PHP 7)

getdate — Get date/time information

Description

getdate ([ int $timestamp = time() ] ) : array

Returns an associative array containing the date information of the timestamp, or the current local time if no timestamp is given.

Parameters

timestamp

The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().

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.

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 local time/date
  • idate() - Format a local time/date as integer
  • localtime() - Get the local time
  • time() - Return current Unix timestamp
  • setlocale() - Set locale information


Get current time

  • « getdate
  • gmdate »
  • PHP Manual
  • Date/Time Functions
  • Get current time

gettimeofday

(PHP 4, PHP 5, PHP 7)

gettimeofday — Get current time

Description

gettimeofday ([ bool $return_float = FALSE ] ) : mixed

This is an interface to gettimeofday(2). It returns an associative array containing the data returned from the system call.

Parameters

return_float

When set to TRUE, a float instead of an array is returned.

Return Values

By default an array is returned. If return_float is set, then a float is returned.

Array keys:

  • "sec" - seconds since the Unix Epoch
  • "usec" - microseconds
  • "minuteswest" - minutes west of Greenwich
  • "dsttime" - type of dst correction

Changelog

Version | Description
5.1.0 | The return_float parameter was added.

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


Format a GMT/UTC date/time

  • « gettimeofday
  • gmmktime »
  • PHP Manual
  • Date/Time Functions
  • Format a GMT/UTC date/time

gmdate

(PHP 4, PHP 5, PHP 7)

gmdate — Format a GMT/UTC date/time

Description

gmdate ( string $format [, int $timestamp = time() ] ) : 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 integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().

Return Values

Returns a formatted date string. If a non-numeric value is used for timestamp, FALSE is returned and an E_WARNING level error is emitted.

Changelog

Version | Description
5.1.1 | There are useful constants of standard date/time formats that can be used to specify the format parameter.
5.1.0 | The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer). However, before PHP 5.1.0 this range was limited from 01-01-1970 to 19-01-2038 on some systems (e.g. Windows).

Examples

Example #1 gmdate() example

When run in Finland (GMT +0200), the first line below prints "Jan 01 1998 00:00:00", while the second prints "Dec 31 1997 22:00:00".

<?php
echo date("M d Y H:i:s", mktime(0, 0, 0, 1, 1, 1998));
echo gmdate("M d Y H:i:s", mktime(0, 0, 0, 1, 1, 1998));
?>

See Also

  • date() - Format a local time/date
  • mktime() - Get Unix timestamp for a date
  • gmmktime() - Get Unix timestamp for a GMT date
  • strftime() - Format a local time/date according to locale settings


Get Unix timestamp for a GMT date

  • « gmdate
  • gmstrftime »
  • PHP Manual
  • Date/Time Functions
  • Get Unix timestamp for a GMT date

gmmktime

(PHP 4, PHP 5, PHP 7)

gmmktime — Get Unix timestamp for a GMT date

Description

 gmmktime
  ([ int $hour = gmdate("H")
 [, int $minute = gmdate("i")
 [, int $second = gmdate("s")
 [, int $month = gmdate("n")
 [, int $day = gmdate("j")
 [, int $year = gmdate("Y")
 [, int $is_dst = -1
]]]]]]] ) : int

Identical to mktime() except the passed parameters represents a GMT date. gmmktime() internally uses mktime() so only times valid in derived local time can be used.

Like mktime(), arguments may be left out in order from right to left, with any omitted arguments being set to the current corresponding GMT value.

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

is_dst

Parameters always represent a GMT date so is_dst doesn't influence the result.

Note:

This parameter has been removed in PHP 7.0.0.

Return Values

Returns a integer Unix timestamp.

Changelog

Version | Description
7.0.0 | is_dst parameter has been removed.
5.1.0 | As of PHP 5.1.0, the is_dst parameter became deprecated. As a result, the new timezone handling features should be used instead.

Examples

Example #1 gmmktime() basic example

<?php
// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", gmmktime(0, 0, 0, 7, 1, 2000));
?>

See Also

  • mktime() - Get Unix timestamp for a date
  • date() - Format a local time/date
  • time() - Return current Unix timestamp


Format a GMT/UTC time/date according to locale settings

  • « gmmktime
  • idate »
  • PHP Manual
  • Date/Time Functions
  • Format a GMT/UTC time/date according to locale settings

gmstrftime

(PHP 4, PHP 5, PHP 7)

gmstrftime — Format a GMT/UTC time/date according to locale settings

Description

gmstrftime ( string $format [, int $timestamp = time() ] ) : string

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

Parameters

format

See description in strftime().

timestamp

The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().

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

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

  • strftime() - Format a local time/date according to locale settings


Format a local time/date as integer

  • « gmstrftime
  • localtime »
  • PHP Manual
  • Date/Time Functions
  • Format a local time/date as integer

idate

(PHP 5, PHP 7)

idate — Format a local time/date as integer

Description

idate ( string $format [, int $timestamp = time() ] ) : int

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
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 integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().

Return Values

Returns an integer.

As idate() always returns an integer and as they can't start with a "0", idate() may return fewer digits than you would expect. See the example below.

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT or E_WARNING message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

Changelog

Version | Description
5.1.0 | Now issues the E_STRICT and E_NOTICE time zone errors.

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

See Also

  • date() - Format a local time/date
  • getdate() - Get date/time information
  • time() - Return current Unix timestamp


Get the local time

  • « idate
  • microtime »
  • PHP Manual
  • Date/Time Functions
  • Get the local time

localtime

(PHP 4, PHP 5, PHP 7)

localtime — Get the local time

Description

localtime ([ int $timestamp = time() [, bool $is_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 integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().

is_associative

If set to FALSE or not supplied then the array is returned as a regular, numerically indexed array. If the argument is set to TRUE then localtime() returns an associative array containing all the different elements of the structure returned by the C function call to localtime. The names of the different keys of the associative array are as follows:

  • "tm_sec" - seconds, 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_NOTICE if the time zone is not valid, and/or a E_STRICT or E_WARNING message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

Changelog

Version | Description
5.1.0 | Now issues the E_STRICT and E_NOTICE time zone errors.

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


Return current Unix timestamp with microseconds

  • « localtime
  • mktime »
  • PHP Manual
  • Date/Time Functions
  • Return current Unix timestamp with microseconds

microtime

(PHP 4, PHP 5, PHP 7)

microtime — Return current Unix timestamp with microseconds

Description

microtime ([ bool $get_as_float = FALSE ] ) : mixed

microtime() returns the current Unix timestamp with microseconds. This function is only available on operating systems that support the gettimeofday() system call.

Parameters

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

If get_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 with microtime()

<?php
/**
 * Simple function to replicate PHP 5 behaviour
 */
function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

$time_start = microtime_float();

// Sleep for a while
usleep(100);

$time_end = microtime_float();
$time = $time_end - $time_start;

echo "Did nothing in $time seconds\n";
?>

Example #2 Timing script execution in PHP 5

<?php
$time_start = microtime(true);

// Sleep for a while
usleep(100);

$time_end = microtime(true);
$time = $time_end - $time_start;

echo "Did nothing in $time seconds\n";
?>

Example #3 microtime() and REQUEST_TIME_FLOAT (as of PHP 5.4.0)

<?php
// Randomize sleeping time
usleep(mt_rand(100, 10000));

// As of PHP 5.4.0, 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


Get Unix timestamp for a date

  • « microtime
  • strftime »
  • PHP Manual
  • Date/Time Functions
  • Get Unix timestamp for a date

mktime

(PHP 4, PHP 5, PHP 7)

mktime — Get Unix timestamp for a date

Description

 mktime
  ([ int $hour = date("H")
 [, int $minute = date("i")
 [, int $second = date("s")
 [, int $month = date("n")
 [, int $day = date("j")
 [, int $year = date("Y")
 [, int $is_dst = -1
]]]]]]] ) : int

Returns the Unix timestamp corresponding to the arguments given. This timestamp is a long integer containing the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified.

Arguments may be left out in order from right to left; any arguments thus omitted will be set to the current value according to the local date and time.

Notes

Note:

As of PHP 5.1, when called with no arguments, mktime() throws an E_STRICT notice: use the time() function instead.

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. However, before PHP 5.1.0 this range was limited from 1970 to 2038 on some systems (e.g. Windows).

is_dst

This parameter can be set to 1 if the time is during daylight savings time (DST), 0 if it is not, or -1 (the default) if it is unknown whether the time is within daylight savings time or not. If it's unknown, PHP tries to figure it out itself. This can cause unexpected (but not incorrect) results. Some times are invalid if DST is enabled on the system PHP is running on or is_dst is set to 1. If DST is enabled in e.g. 2:00, all times between 2:00 and 3:00 are invalid and mktime() returns an undefined (usually negative) value. Some systems (e.g. Solaris 8) enable DST at midnight so time 0:30 of the day when DST is enabled is evaluated as 23:30 of the previous day.

Note:

As of PHP 5.1.0, this parameter became deprecated. As a result, the new timezone handling features should be used instead.

Note:

This parameter has been removed in PHP 7.0.0.

Return Values

mktime() returns the Unix timestamp of the arguments given. If the arguments are invalid, the function returns FALSE (before PHP 5.1 it returned -1).

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT or E_WARNING message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

Changelog

Version | Description
7.0.0 | is_dst parameter has been removed.
5.3.0 | mktime() now throws E_DEPRECATED notice if the is_dst parameter is used.
5.1.0 | The is_dst parameter became deprecated. Made the function return FALSE on error, instead of -1. Fixed the function to accept the year, month and day to be all passed as zero.
5.1.0 | When called with no arguments, mktime() throws E_STRICT notice. Use the time() function instead.
5.1.0 | Now issues the E_STRICT and E_NOTICE time zone errors.

Examples

Example #1 mktime() basic example

<?php
// Set the default timezone to use. Available as of PHP 5.1
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));

// Prints something like: 2006-04-05T01:02:03+00:00
echo date('c', mktime(1, 2, 3, 4, 5, 2006));
?>

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
echo date("M-d-Y", mktime(0, 0, 0, 12, 32, 1997));
echo date("M-d-Y", mktime(0, 0, 0, 13, 1, 1997));
echo date("M-d-Y", mktime(0, 0, 0, 1, 1, 1998));
echo date("M-d-Y", mktime(0, 0, 0, 1, 1, 98));
?>

Example #3 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 strftime("Last day in Feb 2000 is: %d", $lastday);
$lastday = mktime(0, 0, 0, 4, -31, 2000);
echo strftime("Last day in Feb 2000 is: %d", $lastday);
?>

Notes

Caution

Before PHP 5.1.0, negative timestamps were not supported under any known version of Windows and some other systems as well. Therefore the range of valid years was limited to 1970 through 2038.

See Also

  • checkdate() - Validate a Gregorian date
  • gmmktime() - Get Unix timestamp for a GMT date
  • date() - Format a local time/date
  • time() - Return current Unix timestamp


Format a local time/date according to locale settings

  • « mktime
  • strptime »
  • PHP Manual
  • Date/Time Functions
  • Format a local time/date according to locale settings

strftime

(PHP 4, PHP 5, PHP 7)

strftime — Format a local time/date according to locale settings

Description

strftime ( string $format [, int $timestamp = time() ] ) : string

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

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.

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
%P | lower-case 'am' or 'pm' based on the given time | Example: am for 00:31, pm for 22:23
%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 ("%") ---

Maximum length of this parameter is 1023 characters.

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 only: The %P modifier is not supported in the macOS implementation of this function.

timestamp

The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().

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

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT or E_WARNING message if using the system settings or the TZ environment variable. 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
5.1.0 | Now issues the E_STRICT and E_NOTICE time zone errors.

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

  • » 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()


Parse a time/date generated with strftime

  • « strftime
  • strtotime »
  • PHP Manual
  • Date/Time Functions
  • Parse a time/date generated with strftime

strptime

(PHP 5 >= 5.1.0, PHP 7)

strptime — Parse a time/date generated with strftime()

Description

strptime ( string $date , string $format ) : array

strptime() returns an array with the date parsed, or FALSE on error.

Month and weekday names and other language dependent strings respect the current locale set with setlocale() (LC_TIME).

Parameters

date (string)

The string to parse (e.g. returned from strftime()).

format (string)

The format used in date (e.g. the same as used in strftime()). 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 date part which was not recognized using the specified format

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 on PHP 5.3.0 and later.

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.

Note:

Prior to PHP 5.2.0, this function could return undefined behaviour. Notably, the "tm_sec", "tm_min" and "tm_hour" entries would return undefined values.

See Also

  • 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
  • DateTime::createFromFormat() - Parses a time string according to a specified format


Parse about any English textual datetime description into a Unix timestamp

  • « strptime
  • time »
  • PHP Manual
  • Date/Time Functions
  • Parse about any English textual datetime description into a Unix timestamp

strtotime

(PHP 4, PHP 5, PHP 7)

strtotime — Parse about any English textual datetime description into a Unix timestamp

Description

strtotime ( string $time [, int $now = time() ] ) : int

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 now, or the current time if now is not supplied.

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

time

A date/time string. Valid formats are explained in Date and Time Formats.

now

The timestamp which is used as a base for the calculation of relative dates.

Return Values

Returns a timestamp on success, FALSE otherwise. Previous to PHP 5.1.0, this function would return -1 on failure.

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT or E_WARNING message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

Changelog

Version | Description
5.3.0 | Prior to PHP 5.3.0, relative time formats supplied to the time argument of strtotime() such as this week, previous week, last week, and next week were interpreted to mean a 7 day period relative to the current date/time, rather than a week period of Monday through Sunday.
5.3.0 | Prior to PHP 5.3.0, 24:00 was not a valid format and strtotime() returned FALSE.
5.2.7 | In PHP 5 prior to 5.2.7, requesting a given occurrence of a given weekday in a month where that weekday was the first day of the month would incorrectly add one week to the returned timestamp. This has been corrected in 5.2.7 and later versions.
5.1.0 | Now returns FALSE on failure, instead of -1.
5.1.0 | Now issues the E_STRICT and E_NOTICE time zone errors.
5.0.2 | In PHP 5 up to 5.0.2, "now" and other relative times are wrongly computed from today's midnight. This differs from other versions where it is correctly computed from current time.
5.0.0 | Microseconds began to be allowed, but they are ignored.

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';

// previous to PHP 5.1.0 you would compare with -1, instead of false
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:

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

Prior to PHP 5.1.0, not all platforms support negative timestamps, therefore your date range may be limited to no earlier than the Unix epoch. This means that e.g. dates prior to Jan 1, 1970 will not work on Windows, some Linux distributions, and a few other operating systems.

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:

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. If, however, the year is given in a two digit format and the separator is a dash (-), the date string is parsed as y-m-d.

To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.

Note:

Using this function for mathematical operations is not advisable. It is better to use DateTime::add() and DateTime::sub() in PHP 5.3 and later, or DateTime::modify() in PHP 5.2.

See Also

  • Date and Time Formats
  • DateTime::createFromFormat() - Parses a time string according to a specified format
  • checkdate() - Validate a Gregorian date
  • strptime() - Parse a time/date generated with strftime


Return current Unix timestamp

  • « strtotime
  • timezone_abbreviations_list »
  • PHP Manual
  • Date/Time Functions
  • Return current Unix timestamp

time

(PHP 4, PHP 5, PHP 7)

time — Return current Unix timestamp

Description

time ( void ) : int

Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

Examples

Example #1 time() example

<?php
$nextWeek = time() + (7 * 24 * 60 * 60);
                   // 7 days; 24 hours; 60 mins; 60 secs
echo 'Now:       '. date('Y-m-d') ."\n";
echo 'Next Week: '. date('Y-m-d', $nextWeek) ."\n";
// or using strtotime():
echo 'Next Week: '. date('Y-m-d', strtotime('+1 week')) ."\n";
?>

The above example will output something similar to:

Now:       2005-03-30
Next Week: 2005-04-06
Next Week: 2005-04-06

Notes

Tip

Timestamp of the start of the request is available in $_SERVER['REQUEST_TIME'] since PHP 5.1.

See Also

  • date() - Format a local time/date
  • microtime() - Return current Unix timestamp with microseconds


Alias of DateTimeZone::listAbbreviations

  • « time
  • timezone_identifiers_list »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTimeZone::listAbbreviations

timezone_abbreviations_list

(PHP 5 >= 5.2.0, PHP 7)

timezone_abbreviations_list — Alias of DateTimeZone::listAbbreviations()

Description

This function is an alias of: DateTimeZone::listAbbreviations()


Alias of DateTimeZone::listIdentifiers

  • « timezone_abbreviations_list
  • timezone_location_get »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTimeZone::listIdentifiers

timezone_identifiers_list

(PHP 5 >= 5.2.0, PHP 7)

timezone_identifiers_list — Alias of DateTimeZone::listIdentifiers()

Description

This function is an alias of: DateTimeZone::listIdentifiers()


Alias of DateTimeZone::getLocation

  • « timezone_identifiers_list
  • timezone_name_from_abbr »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTimeZone::getLocation

timezone_location_get

(PHP 5 >= 5.3.0, PHP 7)

timezone_location_get — Alias of DateTimeZone::getLocation()

Description

This function is an alias of: DateTimeZone::getLocation()


Returns the timezone name from abbreviation

  • « timezone_location_get
  • timezone_name_get »
  • PHP Manual
  • Date/Time Functions
  • Returns the timezone name from abbreviation

timezone_name_from_abbr

(PHP 5 >= 5.1.3, PHP 7)

timezone_name_from_abbr — Returns the timezone name from abbreviation

Description

timezone_name_from_abbr ( string $abbr [, int $gmtOffset = -1 [, int $isdst = -1 ]] ) : string

Parameters

abbr

Time zone abbreviation.

gmtOffset

Offset from GMT in seconds. Defaults to -1 which means that first found time zone corresponding to abbr is returned. Otherwise exact offset is searched and only if not found then the first time zone with any offset is returned.

isdst

Daylight saving time indicator. 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 gmtOffset is assumed to be an offset with daylight saving in effect; if 0, then gmtOffset 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 gmtOffset 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


Alias of DateTimeZone::getName

  • « timezone_name_from_abbr
  • timezone_offset_get »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTimeZone::getName

timezone_name_get

(PHP 5 >= 5.2.0, PHP 7)

timezone_name_get — Alias of DateTimeZone::getName()

Description

This function is an alias of: DateTimeZone::getName()


Alias of DateTimeZone::getOffset

  • « timezone_name_get
  • timezone_open »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTimeZone::getOffset

timezone_offset_get

(PHP 5 >= 5.2.0, PHP 7)

timezone_offset_get — Alias of DateTimeZone::getOffset()

Description

This function is an alias of: DateTimeZone::getOffset()


Alias of DateTimeZone::__construct

  • « timezone_offset_get
  • timezone_transitions_get »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTimeZone::__construct

timezone_open

(PHP 5 >= 5.2.0, PHP 7)

timezone_open — Alias of DateTimeZone::__construct()

Description

This function is an alias of: DateTimeZone::__construct()


Alias of DateTimeZone::getTransitions

  • « timezone_open
  • timezone_version_get »
  • PHP Manual
  • Date/Time Functions
  • Alias of DateTimeZone::getTransitions

timezone_transitions_get

(PHP 5 >= 5.2.0, PHP 7)

timezone_transitions_get — Alias of DateTimeZone::getTransitions()

Description

This function is an alias of: DateTimeZone::getTransitions()


Gets the version of the timezonedb

  • « timezone_transitions_get
  • Supported Date and Time Formats »
  • PHP Manual
  • Date/Time Functions
  • Gets the version of the timezonedb

timezone_version_get

(PHP 5 >= 5.3.0, PHP 7)

timezone_version_get — Gets the version of the timezonedb

Description

timezone_version_get ( void ) : string

Returns the current version of the timezonedb.

Return Values

Returns a string.

Examples

Example #1 Getting the timezonedb version

<?php
echo timezone_version_get();
?>

The above example will output something similar to:

2009.7

See Also

  • List of Supported Timezones


Supported Date and Time Formats

Table of Contents

  • Time Formats
  • Date Formats
  • Compound Formats
  • Relative Formats

This section describes all the different formats that the strtotime(), DateTime and date_create() 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).


Time Formats

This page describes the different time formats that the strtotime(), DateTime and date_create() parser understands.

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), PHP 5.3 and later only | 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 that the strtotime(), DateTime and date_create() parser understands.

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"
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 | d ([ .\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"
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"

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 works if a time string has already been found -- otherwise this format is recognised as HH MM.

Note:

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 as of PHP 5.1.0 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 that the strtotime(), DateTime and date_create() parser understands.

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] | "04", "8", "59"
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"
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"
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, XMRPC 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 that the strtotime(), DateTime and date_create() parser understands.

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 | (('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 best used together with a month name following it. | "first day of January 2008"
'last day of' | Sets the day to the last day of the current month. This phrase is best used together with a month name following it. | "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 space unit | Handles relative time items where the value is text. | "fifth day", "second month"
'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. | "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.

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
5.6.23, 7.0.8 | Weeks always start on monday. Formerly, sunday would also be considered to start a week.
5.3.3 | "first day" and "last day" changed to behave has "+1 day" and "-1 day", respectively. Previously, the behaviour was as "first day of" and "last day of".


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


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/Costa_Rica | 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/Godthab | 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/Nipigon | America/Nome | America/Noronha
America/North_Dakota/Beulah | America/North_Dakota/Center | America/North_Dakota/New_Salem | America/Ojinaga
America/Panama | America/Pangnirtung | America/Paramaribo | America/Phoenix
America/Port-au-Prince | America/Port_of_Spain | America/Porto_Velho | America/Puerto_Rico
America/Punta_Arenas | America/Rainy_River | 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/Thunder_Bay | America/Tijuana
America/Toronto | America/Tortola | America/Vancouver | America/Whitehorse
America/Winnipeg | America/Yakutat | America/Yellowknife |


Antarctica

Antarctica
Antarctica/Casey | Antarctica/Davis | Antarctica/DumontDUrville | Antarctica/Macquarie
Antarctica/Mawson | Antarctica/McMurdo | Antarctica/Palmer | Antarctica/Rothera
Antarctica/Syowa | Antarctica/Troll | Antarctica/Vostok |


  • « Antarctica
  • Asia »
  • PHP Manual
  • List of Supported Timezones
  • Arctic

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


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/Currie
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/Kiev | Europe/Kirov | 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/Uzhgorod | Europe/Vaduz
Europe/Vatican | Europe/Vienna | Europe/Vilnius | Europe/Volgograd
Europe/Warsaw | Europe/Zagreb | Europe/Zaporozhye | 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/Enderbury
Pacific/Fakaofo | Pacific/Fiji | Pacific/Funafuti | Pacific/Galapagos
Pacific/Gambier | Pacific/Guadalcanal | Pacific/Guam | Pacific/Honolulu
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.

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/Indianapolis | America/Jujuy
America/Knox_IN | America/Louisville | America/Mendoza | America/Montreal
America/Porto_Acre | America/Rosario | America/Santa_Isabel | America/Shiprock
America/Virgin | Antarctica/South_Pole | Asia/Ashkhabad | Asia/Calcutta
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/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/Nicosia | Europe/Tiraspol | 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/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/Pacific-New
US/Samoa | UTC | W-SU | WET
Zulu |  |  |


High resolution timing

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


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 underlaying APIs.

Note: As of PHP 7.3.0 the related function hrtime() is part of the core.


  • « Introduction
  • Installation »
  • PHP Manual
  • HRTime
  • Installing/Configuring

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.

A DLL for this PECL extension is available under » http://windows.php.net/downloads/pecl/releases/hrtime/.


  • « Installation
  • Basic usage »
  • PHP Manual
  • HRTime
  • Examples

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

HRTime\PerformanceCounter {
/* Methods */
public static getFrequency ( void ) : int
public static getTicks ( void ) : int
public static getTicksSince ( int $start ) : int
}

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


Timer frequency in ticks per second

  • « HRTime\PerformanceCounter
  • HRTime\PerformanceCounter::getTicks »
  • PHP Manual
  • HRTime\PerformanceCounter
  • Timer frequency in ticks per second

HRTime\PerformanceCounter::getFrequency

(PECL hrtime >= 0.4.3)

HRTime\PerformanceCounter::getFrequency — Timer frequency in ticks per second

Description

public static HRTime\PerformanceCounter::getFrequency ( void ) : 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 integer indicating the timer frequency.


Current ticks from the system

  • « HRTime\PerformanceCounter::getFrequency
  • HRTime\PerformanceCounter::getTicksSince »
  • PHP Manual
  • HRTime\PerformanceCounter
  • Current ticks from the system

HRTime\PerformanceCounter::getTicks

(PECL hrtime >= 0.6.0)

HRTime\PerformanceCounter::getTicks — Current ticks from the system

Description

public static HRTime\PerformanceCounter::getTicks ( void ) : int

Returns the ticks count.

Parameters

This function has no parameters.

Return Values

Returns integer indicating the ticks count.


Ticks elapsed since the given value

  • « HRTime\PerformanceCounter::getTicks
  • HRTime\StopWatch »
  • PHP Manual
  • HRTime\PerformanceCounter
  • Ticks elapsed since the given value

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 integer indicating the ticks count.


The HRTime\StopWatch class

(PECL hrtime >= 0.4.3)

Introduction

Class synopsis

HRTime\StopWatch extends HRTime\PerformanceCounter {
/* Methods */
public getElapsedTicks ( void ) : int
public getElapsedTime ([ int $unit ] ) : float
public getLastElapsedTicks ( void ) : int
public getLastElapsedTime ([ int $unit ] ) : float
public isRunning ( void ) : bool
public start ( void ) : void
public stop ( void ) : void
/* Inherited methods */
public static HRTime\PerformanceCounter::getFrequency ( void ) : int
public static HRTime\PerformanceCounter::getTicks ( void ) : int
public static HRTime\PerformanceCounter::getTicksSince ( int $start ) : int
}

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


Get elapsed ticks for all intervals

  • « HRTime\StopWatch
  • HRTime\StopWatch::getElapsedTime »
  • PHP Manual
  • HRTime\StopWatch
  • Get elapsed ticks for all intervals

HRTime\StopWatch::getElapsedTicks

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::getElapsedTicks — Get elapsed ticks for all intervals

Description

public HRTime\StopWatch::getElapsedTicks ( void ) : int

Get elapsed ticks for all the previously closed intervals.

Parameters

This function has no parameters.

Return Values

Returns integer indicating elapsed ticks.


Get elapsed time for all intervals

  • « HRTime\StopWatch::getElapsedTicks
  • HRTime\StopWatch::getLastElapsedTicks »
  • PHP Manual
  • HRTime\StopWatch
  • Get elapsed time for all intervals

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.


Get elapsed ticks for the last interval

  • « HRTime\StopWatch::getElapsedTime
  • HRTime\StopWatch::getLastElapsedTime »
  • PHP Manual
  • HRTime\StopWatch
  • Get elapsed ticks for the last interval

HRTime\StopWatch::getLastElapsedTicks

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::getLastElapsedTicks — Get elapsed ticks for the last interval

Description

public HRTime\StopWatch::getLastElapsedTicks ( void ) : int

Get elapsed ticks for the previously closed interval.

Parameters

This function has no parameters.

Return Values

Returns integer indicating elapsed ticks.


Get elapsed time for the last interval

  • « HRTime\StopWatch::getLastElapsedTicks
  • HRTime\StopWatch::isRunning »
  • PHP Manual
  • HRTime\StopWatch
  • Get elapsed time for the last interval

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.


Whether the measurement is running

  • « HRTime\StopWatch::getLastElapsedTime
  • HRTime\StopWatch::start »
  • PHP Manual
  • HRTime\StopWatch
  • Whether the measurement is running

HRTime\StopWatch::isRunning

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::isRunning — Whether the measurement is running

Description

public HRTime\StopWatch::isRunning ( void ) : bool

Reveals whether the measurement was started.

Parameters

This function has no parameters.

Return Values

Returns boolean indicating whetehr the measurement is running.


Start time measurement

  • « HRTime\StopWatch::isRunning
  • HRTime\StopWatch::stop »
  • PHP Manual
  • HRTime\StopWatch
  • Start time measurement

HRTime\StopWatch::start

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::start — Start time measurement

Description

public HRTime\StopWatch::start ( void ) : 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.


Stop time measurement

  • « HRTime\StopWatch::start
  • HRTime\Unit »
  • PHP Manual
  • HRTime\StopWatch
  • Stop time measurement

HRTime\StopWatch::stop

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::stop — Stop time measurement

Description

public HRTime\StopWatch::stop ( void ) : void

Stop the time measurement for the previously started interval.

Parameters

This function has no parameters.

Return Values

Returns void.


The HRTime\Unit class

(PECL hrtime >= 0.4.3)

Introduction

Class synopsis

HRTime\Unit {
/* Constants */
const integer SECOND = 0 ;
const integer MILLISECOND = 1 ;
const integer MICROSECOND = 2 ;
const integer NANOSECOND = 3 ;
/* Methods */
}

Predefined Constants

HRTime\Unit::SECOND

HRTime\Unit::MILLISECOND

HRTime\Unit::MICROSECOND

HRTime\Unit::NANOSECOND


File System Related Extensions

  • Direct IO
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Direct IO Functions
  • Directories
    • Installing/Configuring
    • Predefined Constants
    • Directory — The Directory class
    • Directory Functions
  • Fileinfo — File Information
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Fileinfo Functions
    • finfo — The finfo class
  • Filesystem
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Filesystem Functions
  • Inotify
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Inotify Functions
  • Mimetype
    • Introduction
    • Installing/Configuring
    • Predefined Constants
  • Phdfs
    • Installing/Configuring
    • Predefined Constants
    • phdfs — The phdfs class
  • Proctitle
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Proctitle Functions
  • xattr
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • xattr Functions
  • xdiff
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • xdiff Functions


Direct IO

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • 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/ouput 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


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.

Note:

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.1.0.


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.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.


  • « Runtime Configuration
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

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

F_GETFD (integer)

F_GETFL (integer)

F_GETLK (integer)

F_GETOWN (integer)

F_RDLCK (integer)

F_SETFL (integer)

F_SETLK (integer)

F_SETLKW (integer)

F_SETOWN (integer)

F_UNLCK (integer)

F_WRLCK (integer)

O_APPEND (integer)

O_ASYNC (integer)

O_CREAT (integer)

O_EXCL (integer)

O_NDELAY (integer)

O_NOCTTY (integer)

O_NONBLOCK (integer)

O_RDONLY (integer)

O_RDWR (integer)

O_SYNC (integer)

O_TRUNC (integer)

O_WRONLY (integer)

S_IRGRP (integer)

S_IROTH (integer)

S_IRUSR (integer)

S_IRWXG (integer)

S_IRWXO (integer)

S_IRWXU (integer)

S_IWGRP (integer)

S_IWOTH (integer)

S_IWUSR (integer)

S_IXGRP (integer)

S_IXOTH (integer)

S_IXUSR (integer)


Direct IO Functions

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/ouput 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


Closes the file descriptor given by fd

  • « Direct IO Functions
  • dio_fcntl »
  • PHP Manual
  • Direct IO Functions
  • Closes the file descriptor given by fd

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/ouput stream functions allow


Performs a c library fcntl on fd

  • « dio_close
  • dio_open »
  • PHP Manual
  • Direct IO Functions
  • Performs a c library fcntl on fd

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.


Opens a file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow

  • « dio_fcntl
  • dio_read »
  • PHP Manual
  • Direct IO Functions
  • Opens a file (creating it if necessary) at a lower level than the C library input/ouput stream functions allow

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/ouput 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


Reads bytes from a file descriptor

  • « dio_open
  • dio_seek »
  • PHP Manual
  • Direct IO Functions
  • Reads bytes from a file descriptor

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


Seeks to pos on fd from whence

  • « dio_read
  • dio_stat »
  • PHP Manual
  • Direct IO Functions
  • Seeks to pos on fd from whence

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


Gets stat information about the file descriptor fd

  • « dio_seek
  • dio_tcsetattr »
  • PHP Manual
  • Direct IO Functions
  • Gets stat information about the file descriptor 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.


Sets terminal attributes and baud rate for a serial port

  • « dio_stat
  • dio_truncate »
  • PHP Manual
  • Direct IO Functions
  • Sets terminal attributes and baud rate for a serial port

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 (1) {

  $data = dio_read($fd, 256);

  if ($data) {
      echo $data;
  }
}

?>

Notes

Note: This function is not implemented on Windows platforms.


Truncates file descriptor fd to offset bytes

  • « dio_tcsetattr
  • dio_write »
  • PHP Manual
  • Direct IO Functions
  • Truncates file descriptor fd to offset bytes

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.


Writes data to fd with optional truncation at length

  • « dio_truncate
  • Directories »
  • PHP Manual
  • Direct IO Functions
  • Writes data to fd with optional truncation at length

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


Directories

  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • 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


Predefined Constants

DIRECTORY_SEPARATOR (string)
PATH_SEPARATOR (string)
Semicolon on Windows, colon otherwise.
SCANDIR_SORT_ASCENDING (integer)
Available since PHP 5.4.0.
SCANDIR_SORT_DESCENDING (integer)
Available since PHP 5.4.0.
SCANDIR_SORT_NONE (integer)
Available since PHP 5.4.0.


The Directory class

(PHP 4, PHP 5, PHP 7)

Introduction

Instances of Directory are created by calling the dir() function, not by the new operator.

Class synopsis

Directory {
/* Properties */
public string $path ;
public resource $handle ;
/* Methods */
public close ([ resource $dir_handle ] ) : void
public read ([ resource $dir_handle ] ) : string
public rewind ([ resource $dir_handle ] ) : void
}

Properties

path

The directory that was opened.

handle

Can be used with other directory functions such as readdir(), rewinddir() and closedir().

Table of Contents

  • Directory::close — Close directory handle
  • Directory::read — Read entry from directory handle
  • Directory::rewind — Rewind directory handle


Close directory handle

  • « Directory
  • Directory::read »
  • PHP Manual
  • Directory
  • Close directory handle

Directory::close

(PHP 4, PHP 5, PHP 7)

Directory::close — Close directory handle

Description

public Directory::close ([ resource $dir_handle ] ) : void

Same as closedir(), only dir_handle defaults to $this->handle.


Read entry from directory handle

  • « Directory::close
  • Directory::rewind »
  • PHP Manual
  • Directory
  • Read entry from directory handle

Directory::read

(PHP 4, PHP 5, PHP 7)

Directory::read — Read entry from directory handle

Description

public Directory::read ([ resource $dir_handle ] ) : string

Same as readdir(), only dir_handle defaults to $this->handle.


Rewind directory handle

  • « Directory::read
  • Directory Functions »
  • PHP Manual
  • Directory
  • Rewind directory handle

Directory::rewind

(PHP 4, PHP 5, PHP 7)

Directory::rewind — Rewind directory handle

Description

public Directory::rewind ([ resource $dir_handle ] ) : void

Same as rewinddir(), only dir_handle defaults to $this->handle.


Directory Functions

See Also

For related functions such as dirname(),
is_dir(), mkdir(), and
rmdir(), see the
Filesystem section.

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


Change directory

  • « Directory Functions
  • chroot »
  • PHP Manual
  • Directory Functions
  • Change directory

chdir

(PHP 4, PHP 5, PHP 7)

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

Note: When safe mode is enabled, PHP checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.

See Also

  • getcwd() - Gets the current working directory


Change the root directory

  • « chdir
  • closedir »
  • PHP Manual
  • Directory Functions
  • Change the root directory

chroot

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

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.

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.


Close directory handle

  • « chroot
  • dir »
  • PHP Manual
  • Directory Functions
  • Close directory handle

closedir

(PHP 4, PHP 5, PHP 7)

closedir — Close directory handle

Description

closedir ([ resource $dir_handle ] ) : void

Closes the directory stream indicated by dir_handle. The stream must have previously been opened by opendir().

Parameters

dir_handle

The directory handle resource previously opened with opendir(). If the directory handle is not specified, the last link opened by opendir() is assumed.

Examples

Example #1 closedir() example

<?php
$dir = "/etc/php5/";

// Open a known directory, read directory into variable and then close
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        $directory = readdir($dh);
        closedir($dh);
    }
}
?>


Return an instance of the Directory class

  • « closedir
  • getcwd »
  • PHP Manual
  • Directory Functions
  • Return an instance of the Directory class

dir

(PHP 4, PHP 5, PHP 7)

dir — Return an instance of the Directory class

Description

dir ( string $directory [, resource $context ] ) : Directory

A pseudo-object oriented mechanism for reading a directory. The given directory is opened.

Parameters

directory

Directory to open

context

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams.

Return Values

Returns an instance of Directory, or NULL with wrong parameters, or FALSE in case of another error.

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.


Gets the current working directory

  • « dir
  • opendir »
  • PHP Manual
  • Directory Functions
  • Gets the current working directory

getcwd

(PHP 4, PHP 5, PHP 7)

getcwd — Gets the current working directory

Description

getcwd ( void ) : string

Gets the current working directory.

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

See Also

  • chdir() - Change directory
  • chmod() - Changes file mode


Open directory handle

  • « getcwd
  • readdir »
  • PHP Manual
  • Directory Functions
  • Open directory handle

opendir

(PHP 4, PHP 5, PHP 7)

opendir — Open directory handle

Description

opendir ( string $path [, resource $context ] ) : resource

Opens up a directory handle to be used in subsequent closedir(), readdir(), and rewinddir() calls.

Parameters

path

The directory path that is to be opened

context

For a description of the context parameter, refer to the streams section of the manual.

Return Values

Returns a directory handle resource on success, or FALSE on failure

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

This may happen if path is not a valid directory, the directory can not be opened due to permission restrictions, or due to filesystem errors.

Examples

Example #1 opendir() example

<?php
$dir = "/etc/php5/";

// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
        }
        closedir($dh);
    }
}
?>

The above example will output something similar to:

filename: . : filetype: dir
filename: .. : filetype: dir
filename: apache : filetype: dir
filename: cgi : filetype: dir
filename: cli : filetype: dir

See Also

  • is_dir() - Tells whether the filename is a directory
  • readdir() - Read entry from directory handle
  • dir() - Return an instance of the Directory class


Read entry from directory handle

  • « opendir
  • rewinddir »
  • PHP Manual
  • Directory Functions
  • Read entry from directory handle

readdir

(PHP 4, PHP 5, PHP 7)

readdir — Read entry from directory handle

Description

readdir ([ resource $dir_handle ] ) : string

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

The directory handle resource previously opened with opendir(). If the directory handle is not specified, the last link opened by opendir() is assumed.

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.

Examples

Example #1 List all entries in a directory

Please note the fashion in which readdir()'s return value is checked in the examples below. We are explicitly testing whether the return value is identical to (equal to and of the same type as--see Comparison Operators for more information) FALSE since otherwise, any directory entry whose name evaluates to FALSE will stop the loop (e.g. a directory named "0").

<?php

if ($handle = opendir('/path/to/files')) {
    echo "Directory handle: $handle\n";
    echo "Entries:\n";

    /* This is the correct way to loop over the directory. */
    while (false !== ($entry = readdir($handle))) {
        echo "$entry\n";
    }

    /* This is the WRONG way to loop over the directory. */
    while ($entry = readdir($handle)) {
        echo "$entry\n";
    }

    closedir($handle);
}
?>

Example #2 List all entries in the current directory and strip out . and ..

<?php
if ($handle = opendir('.')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            echo "$entry\n";
        }
    }
    closedir($handle);
}
?>

See Also

  • is_dir() - Tells whether the filename is a directory
  • glob() - Find pathnames matching a pattern
  • opendir() - Open directory handle
  • scandir() - List files and directories inside the specified path


Rewind directory handle

  • « readdir
  • scandir »
  • PHP Manual
  • Directory Functions
  • Rewind directory handle

rewinddir

(PHP 4, PHP 5, PHP 7)

rewinddir — Rewind directory handle

Description

rewinddir ([ resource $dir_handle ] ) : void

Resets the directory stream indicated by dir_handle to the beginning of the directory.

Parameters

dir_handle

The directory handle resource previously opened with opendir(). If the directory handle is not specified, the last link opened by opendir() is assumed.

Return Values

Returns NULL on success or FALSE on failure.


List files and directories inside the specified path

  • « rewinddir
  • Fileinfo »
  • PHP Manual
  • Directory Functions
  • List files and directories inside the specified path

scandir

(PHP 5, PHP 7)

scandir — List files and directories inside the specified path

Description

scandir ( string $directory [, int $sorting_order = SCANDIR_SORT_ASCENDING [, resource $context ]] ) : array

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
5.4.0 | sorting_order constants were added. Any nonzero value caused descending order in previous versions. So for all PHP versions, use 0 for ascending order, and 1 for descending order. An option for SCANDIR_SORT_NONE behavior did not exist prior to PHP 5.4.0.

Examples

Example #1 A simple scandir() example

<?php
$dir    = '/tmp';
$files1 = scandir($dir);
$files2 = scandir($dir, 1);

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


File Information

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Fileinfo Functions
    • finfo_buffer — Return information about a string buffer
    • finfo_close — Close fileinfo resource
    • finfo_file — Return information about a file
    • finfo_open — Create a new fileinfo resource
    • 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()


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
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

Before PHP 5.3.0, the magic_open library is needed to build this extension.


Installation

This extension is enabled by default as of PHP 5.3.0. Before this time, fileinfo was a PECL extension but is no longer maintained there. However, versions prior to 5.3+ may use the » discontinued PECL extension.

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.

Upgrade history of the bundled libmagic library
PHP Version | Updated libmagic Version | Notes
5.3.2 | 5.03 |
5.3.0 | 5.02 |


Resource Types

There is one resource used in 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 (integer)
No special handling.
FILEINFO_SYMLINK (integer)
Follow symlinks.
FILEINFO_MIME_TYPE (integer)
Return the mime type. Available since PHP 5.3.0.
FILEINFO_MIME_ENCODING (integer)
Return the mime encoding of the file. Available since PHP 5.3.0.
FILEINFO_MIME (integer)
Return the mime type and mime encoding as defined by RFC 2045.
FILEINFO_COMPRESS (integer)
Decompress compressed files. Disabled since PHP 5.3.0 due to thread safety issues.
FILEINFO_DEVICES (integer)
Look at the contents of blocks or character special devices.
FILEINFO_CONTINUE (integer)
Return all matches, not just the first.
FILEINFO_PRESERVE_ATIME (integer)
If possible preserve the original access time.
FILEINFO_RAW (integer)
Don't translate unprintable characters to a \ooo octal representation.
FILEINFO_EXTENSION (integer)
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 Functions

Table of Contents

  • finfo_buffer — Return information about a string buffer
  • finfo_close — Close fileinfo resource
  • finfo_file — Return information about a file
  • finfo_open — Create a new fileinfo resource
  • finfo_set_flags — Set libmagic configuration options
  • mime_content_type — Detect MIME Content-type for a file


Return information about a string buffer

  • « Fileinfo Functions
  • finfo_close »
  • PHP Manual
  • Fileinfo Functions
  • Return information about a string buffer

finfo_buffer

finfo::buffer

(PHP 5 >= 5.3.0, PHP 7, PECL fileinfo >= 0.1.0)

finfo_buffer -- finfo::buffer — Return information about a string buffer

Description

Procedural style

finfo_buffer ( resource $finfo , string $string [, int $options = FILEINFO_NONE [, resource $context ]] ) : string

Object oriented style

public finfo::buffer ( string $string [, int $options = FILEINFO_NONE [, resource $context ]] ) : string

This function is used to get information about binary data in a string.

Parameters

finfo

Fileinfo resource returned by finfo_open().

string

Content of a file to be checked.

options

One or disjunction of more Fileinfo constants.

context

Return Values

Returns a textual description of the string argument, or FALSE if an error occurred.

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() - Alias of finfo_file()


Close fileinfo resource

  • « finfo_buffer
  • finfo_file »
  • PHP Manual
  • Fileinfo Functions
  • Close fileinfo resource

finfo_close

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo_close — Close fileinfo resource

Description

finfo_close ( resource $finfo ) : bool

This function closes the resource opened by finfo_open().

Parameters

finfo

Fileinfo resource returned by finfo_open().

Return Values

Returns TRUE on success or FALSE on failure.


Return information about a file

  • « finfo_close
  • finfo_open »
  • PHP Manual
  • Fileinfo Functions
  • Return information about a file

finfo_file

finfo::file

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo_file -- finfo::file — Return information about a file

Description

Procedural style

finfo_file ( resource $finfo , string $file_name [, int $options = FILEINFO_NONE [, resource $context ]] ) : string

Object oriented style

public finfo::file ( string $file_name [, int $options = FILEINFO_NONE [, resource $context ]] ) : string

This function is used to get information about a file.

Parameters

finfo

Fileinfo resource returned by finfo_open().

file_name

Name of a file to be checked.

options

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 file_name argument, or FALSE if an error occurred.

Examples

Example #1 A finfo_file() example

<?php
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala 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() - Alias of finfo_buffer()


Create a new fileinfo resource

  • « finfo_file
  • finfo_set_flags »
  • PHP Manual
  • Fileinfo Functions
  • Create a new fileinfo resource

finfo_open

finfo::__construct

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo_open -- finfo::__construct — Create a new fileinfo resource

Description

Procedural style

finfo_open ([ int $options = FILEINFO_NONE [, string $magic_file = "" ]] ) : resource

Object oriented style (constructor):

public finfo::__construct ([ int $options = FILEINFO_NONE [, string $magic_file = "" ]] )

This function opens a magic database and returns its resource.

Parameters

options

One or disjunction of more Fileinfo constants.

magic_file

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 a magic database resource on success or FALSE on failure.

Notes

Warning

The expected magic database format changed in PHP 5.3.11 and 5.4.1. Due to this, the internal magic database was upgraded. This mostly effects code where an external magic database is used: reading an older magic file will now fail. Also, some textual representations of the mime types has changed, for instance for PHP would be "PHP script, ASCII text" instead of "PHP script text" returned.

Note:

Generally, using the bundled magic database (by leaving magic_file and the MAGIC environment variables unset) is the best course of action unless you specifically need a custom magic database.

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

See Also

  • finfo_close() - Close fileinfo resource


Set libmagic configuration options

  • « finfo_open
  • mime_content_type »
  • PHP Manual
  • Fileinfo Functions
  • Set libmagic configuration options

finfo_set_flags

finfo::set_flags

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo_set_flags -- finfo::set_flags — Set libmagic configuration options

Description

Procedural style

finfo_set_flags ( resource $finfo , int $options ) : bool

Object oriented style

public finfo::set_flags ( int $options ) : bool

This function sets various Fileinfo options. Options can be set also directly in finfo_open() or other Fileinfo functions.

Parameters

finfo

Fileinfo resource returned by finfo_open().

options

One or disjunction of more Fileinfo constants.

Return Values

Returns TRUE on success or FALSE on failure.


Detect MIME Content-type for a file

  • « finfo_set_flags
  • finfo »
  • PHP Manual
  • Fileinfo Functions
  • Detect MIME Content-type for a file

mime_content_type

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

mime_content_type — Detect MIME Content-type for a file

Description

mime_content_type ( string $filename ) : string

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() - Alias of finfo_file()
  • finfo_buffer() - Alias of finfo_buffer()


The finfo class

(PHP 5 >= 5.3.0, PHP 7, PECL fileinfo >= 0.1.0)

Introduction

This class provides an object oriented interface into the fileinfo functions.

Class synopsis

finfo {
public __construct ([ int $options = FILEINFO_NONE [, string $magic_file = "" ]] )
public buffer ( string $string [, int $options = FILEINFO_NONE [, resource $context ]] ) : string
public file ( string $file_name [, int $options = FILEINFO_NONE [, resource $context ]] ) : string
public set_flags ( int $options ) : bool
}

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


Alias of finfo_buffer()

  • « finfo
  • finfo::__construct »
  • PHP Manual
  • finfo
  • Alias of finfo_buffer()

finfo::buffer

(PHP 5 >= 5.3.0, PHP 7, PECL fileinfo >= 0.1.0)

finfo::buffer — Alias of finfo_buffer()

Description

public finfo::buffer ( string $string [, int $options = FILEINFO_NONE [, resource $context ]] ) : string

This function is an alias of: finfo_buffer()


Alias of finfo_open

  • « finfo::buffer
  • finfo::file »
  • PHP Manual
  • finfo
  • Alias of finfo_open

finfo::__construct

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo::__construct — Alias of finfo_open()

Description

public finfo::__construct ([ int $options = FILEINFO_NONE [, string $magic_file = "" ]] )

This function is an alias of: finfo_open()


Alias of finfo_file()

  • « finfo::__construct
  • finfo::set_flags »
  • PHP Manual
  • finfo
  • Alias of finfo_file()

finfo::file

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo::file — Alias of finfo_file()

Description

public finfo::file ( string $file_name [, int $options = FILEINFO_NONE [, resource $context ]] ) : string

This function is an alias of: finfo_file()


Alias of finfo_set_flags()

  • « finfo::file
  • Filesystem »
  • PHP Manual
  • finfo
  • Alias of finfo_set_flags()

finfo::set_flags

(PHP >= 5.3.0, PECL fileinfo >= 0.1.0)

finfo::set_flags — Alias of finfo_set_flags()

Description

public finfo::set_flags ( int $options ) : bool

This function is an alias of: finfo_set_flags()


Filesystem

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • 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
    • 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_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
    • file — Reads entire file into an array
    • 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
    • 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_cache_get — Get realpath cache entries
    • realpath_cache_size — Get realpath cache size
    • realpath — Returns canonicalized absolute pathname
    • 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


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.


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" | PHP_INI_SYSTEM |
allow_url_include | "0" | PHP_INI_SYSTEM | Available since PHP 5.2.0. Deprecated as of PHP 7.4.0.
user_agent | NULL | PHP_INI_ALL |
default_socket_timeout | "60" | PHP_INI_ALL |
from | "" | PHP_INI_ALL |
auto_detect_line_endings | "0" | PHP_INI_ALL |
sys_temp_dir | "" | PHP_INI_SYSTEM | Available since PHP 5.5.0.

Here's a short explanation of the configuration directives.

allow_url_fopen boolean

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 boolean

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 integer

Default timeout (in seconds) for socket based streams.

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 boolean

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 (integer)
SEEK_CUR (integer)
SEEK_END (integer)
LOCK_SH (integer)
LOCK_EX (integer)
LOCK_UN (integer)
LOCK_NB (integer)
GLOB_BRACE (integer)
GLOB_ONLYDIR (integer)
GLOB_MARK (integer)
GLOB_NOSORT (integer)
GLOB_NOCHECK (integer)
GLOB_NOESCAPE (integer)
GLOB_AVAILABLE_FLAGS (integer)
PATHINFO_DIRNAME (integer)
PATHINFO_BASENAME (integer)
PATHINFO_EXTENSION (integer)
PATHINFO_FILENAME (integer)
Since PHP 5.2.0.
FILE_USE_INCLUDE_PATH (integer)
Search for filename in include_path.
FILE_NO_DEFAULT_CONTEXT (integer)
FILE_APPEND (integer)
Append content to existing file.
FILE_IGNORE_NEW_LINES (integer)
Strip EOL characters.
FILE_SKIP_EMPTY_LINES (integer)
Skip empty lines.
FILE_BINARY (integer)

Binary mode (since PHP 5.2.7).

Note:

This constant has no effect, and is only available for forward compatibility.

FILE_TEXT (integer)

Text mode (since PHP 5.2.7).

Note:

This constant has no effect, and is only available for forward compatibility.

INI_SCANNER_NORMAL (integer)
Normal INI scanner mode (since PHP 5.3).
INI_SCANNER_RAW (integer)
Raw INI scanner mode (since PHP 5.3).
INI_SCANNER_TYPED (integer)
Typed INI scanner mode (since PHP 5.6.1).
FNM_NOESCAPE (integer)
Disable backslash escaping.
FNM_PATHNAME (integer)
Slash in string only matches slash in the given pattern.
FNM_PERIOD (integer)
Leading period in string must be exactly matched by period in the given pattern.
FNM_CASEFOLD (integer)
Caseless match. Part of the GNU extension.


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.

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
  • 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_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
  • file — Reads entire file into an array
  • 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
  • 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_cache_get — Get realpath cache entries
  • realpath_cache_size — Get realpath cache size
  • realpath — Returns canonicalized absolute pathname
  • 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


Returns trailing name component of path

  • « Filesystem Functions
  • chgrp »
  • PHP Manual
  • Filesystem Functions
  • Returns trailing name component of path

basename

(PHP 4, PHP 5, PHP 7)

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.

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


Changes file group

  • « basename
  • chmod »
  • PHP Manual
  • Filesystem Functions
  • Changes file group

chgrp

(PHP 4, PHP 5, PHP 7)

chgrp — Changes file group

Description

chgrp ( string $filename , mixed $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: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

See Also

  • chown() - Changes file owner
  • chmod() - Changes file mode


Changes file mode

  • « chgrp
  • chown »
  • PHP Manual
  • Filesystem Functions
  • Changes file mode

chmod

(PHP 4, PHP 5, PHP 7)

chmod — Changes file mode

Description

chmod ( string $filename , int $mode ) : bool

Attempts to change the mode of the specified file to that given in mode.

Parameters

filename

Path to the file.

mode

Note that mode is not automatically assumed to be an octal value, so to ensure the expected operation, you need to prefix mode 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 mode parameter consists of three octal number components specifying access restrictions for the owner, the user group in which the owner is in, and to everybody else in this order. One component can be computed by adding up the needed permissions for that target user base. Number 1 means that you grant execute rights, number 2 means that you make the file writeable, number 4 means that you make the file readable. Add up these numbers to specify needed rights. You can also read more about modes on Unix systems with 'man 1 chmod' and 'man 2 chmod'.

<?php
// Read and write for owner, nothing for everybody else
chmod("/somedir/somefile", 0600);

// Read and write for owner, read for everybody else
chmod("/somedir/somefile", 0644);

// Everything for owner, read and execute for others
chmod("/somedir/somefile", 0755);

// Everything for owner, read and execute for owner's group
chmod("/somedir/somefile", 0750);
?>

Return Values

Returns TRUE on success or FALSE on failure.

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.

Note:

When safe mode is enabled, PHP checks whether the files or directories you are about to operate on have the same UID (owner) as the script that is being executed. In addition, you cannot set the SUID, SGID and sticky bits.

See Also

  • chown() - Changes file owner
  • chgrp() - Changes file group
  • fileperms() - Gets file permissions
  • stat() - Gives information about a file


Changes file owner

  • « chmod
  • clearstatcache »
  • PHP Manual
  • Filesystem Functions
  • Changes file owner

chown

(PHP 4, PHP 5, PHP 7)

chown — Changes file owner

Description

chown ( string $filename , mixed $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: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

See Also

  • chmod() - Changes file mode
  • chgrp() - Changes file group


Clears file status cache

  • « chown
  • copy »
  • PHP Manual
  • Filesystem Functions
  • Clears file status cache

clearstatcache

(PHP 4, PHP 5, PHP 7)

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 clear the realpath cache or not.

filename

Clear the realpath and the stat cache for a specific filename only; only used if clear_realpath_cache is TRUE.

Return Values

No value is returned.

Changelog

Version | Description
5.3.0 | Added optional clear_realpath_cache and filename parameters.

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


Copies file

  • « clearstatcache
  • delete »
  • PHP Manual
  • Filesystem Functions
  • Copies file

copy

(PHP 4, PHP 5, PHP 7)

copy — Copies file

Description

copy ( string $source , string $dest [, resource $context ] ) : bool

Makes a copy of the file source to dest.

If you wish to move a file, use the rename() function.

Parameters

source

Path to the source file.

dest

The destination path. If dest 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.

Changelog

Version | Description
5.3.4 | Changed the context parameter to actually have an effect. Previously, any context was ignored.
5.3.0 | Added context support.

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


See unlink or unset

  • « copy
  • dirname »
  • PHP Manual
  • Filesystem Functions
  • See unlink or unset

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


Returns a parent directory's path

  • « delete
  • disk_free_space »
  • PHP Manual
  • Filesystem Functions
  • Returns a parent directory's path

dirname

(PHP 4, PHP 5, PHP 7)

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

dirname() is locale aware, so for it to see the correct directory name with multibyte character paths, the matching locale must be set using the setlocale() function.

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.

Changelog

Version | Description
7.0.0 | Added the optional levels parameter.

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


Returns available space on filesystem or disk partition

  • « dirname
  • disk_total_space »
  • PHP Manual
  • Filesystem Functions
  • Returns available space on filesystem or disk partition

disk_free_space

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

disk_free_space — Returns available space on filesystem or disk partition

Description

disk_free_space ( string $directory ) : float

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


Returns the total size of a filesystem or disk partition

  • « disk_free_space
  • diskfreespace »
  • PHP Manual
  • Filesystem Functions
  • Returns the total size of a filesystem or disk partition

disk_total_space

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

disk_total_space — Returns the total size of a filesystem or disk partition

Description

disk_total_space ( string $directory ) : float

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


Alias of disk_free_space

  • « disk_total_space
  • fclose »
  • PHP Manual
  • Filesystem Functions
  • Alias of disk_free_space

diskfreespace

(PHP 4, PHP 5, PHP 7)

diskfreespace — Alias of disk_free_space()

Description

This function is an alias of: disk_free_space().


Closes an open file pointer

  • « diskfreespace
  • feof »
  • PHP Manual
  • Filesystem Functions
  • Closes an open file pointer

fclose

(PHP 4, PHP 5, PHP 7)

fclose — Closes an open file pointer

Description

fclose ( resource $handle ) : bool

The file pointed to by handle is closed.

Parameters

handle

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


Tests for end-of-file on a file pointer

  • « fclose
  • fflush »
  • PHP Manual
  • Filesystem Functions
  • Tests for end-of-file on a file pointer

feof

(PHP 4, PHP 5, PHP 7)

feof — Tests for end-of-file on a file pointer

Description

feof ( resource $handle ) : bool

Tests for end-of-file on a file pointer.

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

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


Flushes the output to a file

  • « feof
  • fgetc »
  • PHP Manual
  • Filesystem Functions
  • Flushes the output to a file

fflush

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

fflush — Flushes the output to a file

Description

fflush ( resource $handle ) : bool

This function forces a write of all buffered output to the resource pointed to by the file handle.

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

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


Gets character from file pointer

  • « fflush
  • fgetcsv »
  • PHP Manual
  • Filesystem Functions
  • Gets character from file pointer

fgetc

(PHP 4, PHP 5, PHP 7)

fgetc — Gets character from file pointer

Description

fgetc ( resource $handle ) : string

Gets a character from the given file pointer.

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

Return Values

Returns a string containing a single character read from the file pointed to by handle. 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


Gets line from file pointer and parse for CSV fields

  • « fgetc
  • fgets »
  • PHP Manual
  • Filesystem Functions
  • Gets line from file pointer and parse for CSV fields

fgetcsv

(PHP 4, PHP 5, PHP 7)

fgetcsv — Gets line from file pointer and parse for CSV fields

Description

fgetcsv ( resource $handle [, int $length = 0 [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\\" ]]]] ) : array

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. If LC_CTYPE is e.g. en_US.UTF-8, files in one-byte encodings may be read wrongly by this function.

Parameters

handle

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 in PHP 5.1.0 and later) the maximum line length is not limited, which is slightly slower.

delimiter

The optional delimiter parameter sets the field delimiter (one character only).

enclosure

The optional enclosure parameter sets the field enclosure character (one character only).

escape

The optional escape parameter sets the escape character (at most one character). An empty string ("") disables the proprietary escape mechanism.

Note: Usually an enclosure character is escaped inside a field by doubling it; however, the escape character can be used as an alternative. So for the default parameter values "" and \" have the same meaning. Other than allowing to escape the enclosure character the escape character has no special meaning; it isn't even meant to escape itself.

Return Values

Returns an indexed array containing the fields read.

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.

fgetcsv() returns NULL if an invalid handle is supplied or FALSE on other errors, including end of file.

Changelog

Version | Description
7.4.0 | The escape parameter now also accepts an empty string to disable the proprietary escape mechanism.
5.3.0 | The escape parameter was added
5.1.0 | The length is now optional. Default is 0, meaning no length limit.

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

  • str_getcsv() - Parse a CSV string into an array
  • explode() - Split a string by a string
  • file() - Reads entire file into an array
  • pack() - Pack data into binary string
  • fputcsv() - Format line as CSV and write to file pointer


Gets line from file pointer

  • « fgetcsv
  • fgetss »
  • PHP Manual
  • Filesystem Functions
  • Gets line from file pointer

fgets

(PHP 4, PHP 5, PHP 7)

fgets — Gets line from file pointer

Description

fgets ( resource $handle [, int $length ] ) : string

Gets a line from file pointer.

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

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 handle. 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
$handle = @fopen("/tmp/inputfile.txt", "r");
if ($handle) {
    while (($buffer = fgets($handle, 4096)) !== false) {
        echo $buffer;
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}
?>

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


Gets line from file pointer and strip HTML tags

  • « fgets
  • file_exists »
  • PHP Manual
  • Filesystem Functions
  • Gets line from file pointer and strip HTML tags

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


Checks whether a file or directory exists

  • « fgetss
  • file_get_contents »
  • PHP Manual
  • Filesystem Functions
  • Checks whether a file or directory exists

file_exists

(PHP 4, PHP 5, PHP 7)

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.

Warning

This function returns FALSE for files inaccessible due to safe mode restrictions. However these files still can be included if they are located in safe_mode_include_dir.

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.

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

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

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


Reads entire file into a string

  • « file_exists
  • file_put_contents »
  • PHP Manual
  • Filesystem Functions
  • Reads entire file into a string

file_get_contents

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

file_get_contents — Reads entire file into a string

Description

file_get_contents ( string $filename [, bool $use_include_path = FALSE [, resource $context [, int $offset = 0 [, int $maxlen ]]]] ) : string

This function is similar to file(), except that file_get_contents() returns the file in a string, starting at the specified offset up to maxlen 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.

maxlen

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, maxlength is less than zero, or if seeking to the specified offset in the stream fails.

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 = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n"
  )
);

$context = stream_context_create($opts);

// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);
?>

Changelog

Version | Description
7.1.0 | Support for negative offsets has been added.
5.1.0 | Added the offset and maxlen parameters.

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


Write data to a file

  • « file_get_contents
  • file »
  • PHP Manual
  • Filesystem Functions
  • Write data to a file

file_put_contents

(PHP 5, PHP 7)

file_put_contents — Write data to a file

Description

file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] ) : int

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

Changelog

Version | Description
5.1.0 | Added support for LOCK_EX and the ability to pass a stream resource to the data parameter

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


Reads entire file into an array

  • « file_put_contents
  • fileatime »
  • PHP Manual
  • Filesystem Functions
  • Reads entire file into an array

file

(PHP 4, PHP 5, PHP 7)

file — Reads entire file into an array

Description

file ( string $filename [, int $flags = 0 [, resource $context ]] ) : array

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

context

A context resource created with the stream_context_create() function.

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams.

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

Emits an E_WARNING level error if the file does not exist.

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

// Another example, let's get a web page into a string.  See also file_get_contents().
$html = implode('', file('http://www.example.com/'));

// Using the optional flags parameter since PHP 5
$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

  • readfile() - Outputs a file
  • 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
  • include - include
  • stream_context_create() - Creates a stream context


Gets last access time of file

  • « file
  • filectime »
  • PHP Manual
  • Filesystem Functions
  • Gets last access time of file

fileatime

(PHP 4, PHP 5, PHP 7)

fileatime — Gets last access time of file

Description

fileatime ( string $filename ) : int

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.

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

?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

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 local time/date


Gets inode change time of file

  • « fileatime
  • filegroup »
  • PHP Manual
  • Filesystem Functions
  • Gets inode change time of file

filectime

(PHP 4, PHP 5, PHP 7)

filectime — Gets inode change time of file

Description

filectime ( string $filename ) : int

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.

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

?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

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


Gets file group

  • « filectime
  • fileinode »
  • PHP Manual
  • Filesystem Functions
  • Gets file group

filegroup

(PHP 4, PHP 5, PHP 7)

filegroup — Gets file group

Description

filegroup ( string $filename ) : int

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.

Examples

Example #1 Finding the group of a file

<?php
$filename = 'index.php';
print_r(posix_getgrgid(filegroup($filename)));
?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

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


Gets file inode

  • « filegroup
  • filemtime »
  • PHP Manual
  • Filesystem Functions
  • Gets file inode

fileinode

(PHP 4, PHP 5, PHP 7)

fileinode — Gets file inode

Description

fileinode ( string $filename ) : int

Gets the file inode.

Parameters

filename

Path to the file.

Return Values

Returns the inode number of the file, or FALSE on failure.

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

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

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


Gets file modification time

  • « fileinode
  • fileowner »
  • PHP Manual
  • Filesystem Functions
  • Gets file modification time

filemtime

(PHP 4, PHP 5, PHP 7)

filemtime — Gets file modification time

Description

filemtime ( string $filename ) : int

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.

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

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

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


Gets file owner

  • « filemtime
  • fileperms »
  • PHP Manual
  • Filesystem Functions
  • Gets file owner

fileowner

(PHP 4, PHP 5, PHP 7)

fileowner — Gets file owner

Description

fileowner ( string $filename ) : int

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.

Examples

Example #1 Finding the owner of a file

<?php
$filename = 'index.php';
print_r(posix_getpwuid(fileowner($filename)));
?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

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


Gets file permissions

  • « fileowner
  • filesize »
  • PHP Manual
  • Filesystem Functions
  • Gets file permissions

fileperms

(PHP 4, PHP 5, PHP 7)

fileperms — Gets file permissions

Description

fileperms ( string $filename ) : int

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.

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

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

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


Gets file size

  • « fileperms
  • filetype »
  • PHP Manual
  • Filesystem Functions
  • Gets file size

filesize

(PHP 4, PHP 5, PHP 7)

filesize — Gets file size

Description

filesize ( string $filename ) : int

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.

Examples

Example #1 filesize() example

<?php

// outputs e.g.  somefile.txt: 1024 bytes

$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename) . ' bytes';

?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

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


Gets file type

  • « filesize
  • flock »
  • PHP Manual
  • Filesystem Functions
  • Gets file type

filetype

(PHP 4, PHP 5, PHP 7)

filetype — Gets file type

Description

filetype ( string $filename ) : string

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.

Examples

Example #1 filetype() example

<?php

echo filetype('/etc/passwd');  // file
echo filetype('/etc/');        // dir

?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

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


Portable advisory file locking

  • « filetype
  • fnmatch »
  • PHP Manual
  • Filesystem Functions
  • Portable advisory file locking

flock

(PHP 4, PHP 5, PHP 7)

flock — Portable advisory file locking

Description

flock ( resource $handle , int $operation [, int &$wouldblock ] ) : 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).

On versions of PHP before 5.3.2, the lock is released also by fclose() (which is also called automatically when script finished).

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

handle

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 you don't want flock() to block while locking.

wouldblock

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.

Changelog

Version | Description
5.5.22, 5.6.6 | Added support for the wouldblock parameter on Windows.
5.3.2 | The automatic unlocking when the file's resource handle is closed was removed. Unlocking now always has to be done manually.

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 handle 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 like ISAPI 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.


Match filename against a pattern

  • « flock
  • fopen »
  • PHP Manual
  • Filesystem Functions
  • Match filename against a pattern

fnmatch

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

fnmatch — Match filename against a pattern

Description

fnmatch ( string $pattern , string $string [, int $flags = 0 ] ) : bool

fnmatch() checks if the passed string would match the given shell wildcard pattern.

Parameters

pattern

The shell wildcard pattern.

string

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.

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms.

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


Opens file or URL

  • « fnmatch
  • fpassthru »
  • PHP Manual
  • Filesystem Functions
  • Opens file or URL

fopen

(PHP 4, PHP 5, PHP 7)

fopen — Opens file or URL

Description

fopen ( string $filename , string $mode [, bool $use_include_path = FALSE [, resource $context ]] ) : resource

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 safe mode or 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; 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.
'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 conform 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 use \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 depends on the SAPI and version of PHP that you are using, so you are encouraged to always specify the appropriate flag for portability reasons. You should 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 notepad. You should use the 'b' in all other cases.

If you do not specify the 'b' 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 strongly recommended that you always use the 'b' flag when opening files with fopen().

Note:

Again, 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.

use_include_path

The optional third use_include_path parameter can be set to '1' or TRUE if you want to search for the file in the include_path, too.

context

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams.

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.
5.2.6 | The 'c' and 'c+' options were 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: When safe mode is enabled, PHP checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.

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


Output all remaining data on a file pointer

  • « fopen
  • fputcsv »
  • PHP Manual
  • Filesystem Functions
  • Output all remaining data on a file pointer

fpassthru

(PHP 4, PHP 5, PHP 7)

fpassthru — Output all remaining data on a file pointer

Description

fpassthru ( resource $handle ) : 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

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

Return Values

If an error occurs, fpassthru() returns FALSE. Otherwise, fpassthru() returns the number of characters read from handle 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


Format line as CSV and write to file pointer

  • « fpassthru
  • fputs »
  • PHP Manual
  • Filesystem Functions
  • Format line as CSV and write to file pointer

fputcsv

(PHP 5 >= 5.1.0, PHP 7)

fputcsv — Format line as CSV and write to file pointer

Description

fputcsv ( resource $handle , array $fields [, string $delimiter = "," [, string $enclosure = '"' [, string $escape_char = "\\" ]]] ) : int

fputcsv() formats a line (passed as a fields array) as CSV and writes it (terminated by a newline) to the specified file handle.

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

fields

An array of strings.

delimiter

The optional delimiter parameter sets the field delimiter (one character only).

enclosure

The optional enclosure parameter sets the field enclosure (one character only).

escape_char

The optional escape_char parameter sets the escape character (at most one character). An empty string ("") disables the proprietary escape mechanism.

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

Return Values

Returns the length of the written string or FALSE on failure.

Changelog

Version | Description
7.4.0 | The escape_char parameter now also accepts an empty string to disable the proprietary escape mechanism.
5.5.4 | The escape_char parameter was added

Examples

Example #1 fputcsv() example

<?php

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"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"""

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

  • fgetcsv() - Gets line from file pointer and parse for CSV fields


Alias of fwrite

  • « fputcsv
  • fread »
  • PHP Manual
  • Filesystem Functions
  • Alias of fwrite

fputs

(PHP 4, PHP 5, PHP 7)

fputs — Alias of fwrite()

Description

This function is an alias of: fwrite().


Binary-safe file read

  • « fputs
  • fscanf »
  • PHP Manual
  • Filesystem Functions
  • Binary-safe file read

fread

(PHP 4, PHP 5, PHP 7)

fread — Binary-safe file read

Description

fread ( resource $handle , int $length ) : string

fread() reads up to length bytes from the file pointer referenced by handle. 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

handle

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
// For PHP 5 and up
$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
  • 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


Parses input from a file according to a format

  • « fread
  • fseek »
  • PHP Manual
  • Filesystem Functions
  • Parses input from a file according to a format

fscanf

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

fscanf — Parses input from a file according to a format

Description

fscanf ( resource $handle , string $format [, mixed &$... ] ) : mixed

The function fscanf() is similar to sscanf(), but it takes its input from a file associated with handle and interprets the input according to the specified format, which is described in the documentation for sprintf().

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

handle

A file system pointer resource that is typically created using fopen().

format

The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result and conversion specifications, each of which results in fetching its own parameter.

A conversion specification follows this prototype: %[argnum$][flags][width][.precision]specifier.

Argnum

An integer followed by a dollar sign $, to specify which number argument to treat in the conversion.

Flags
Flag | Description
- Left-justify within the given field width; Right justification is the default
+ Prefix positive numbers with a plus sign +; Default only negative are prefixed with a negative sign.
(space) | Pads the result with spaces. This is the default.
0 | Only left-pads numbers with zeros. With s specifiers this can also right-pad with zeros.
'(char) | Pads the result with the character (char).

Width

An integer that says how many characters (minimum) this conversion should result in.

Precision

A period . followed by an integer who's meaning depends on the specifier:

  • For e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
  • For g and G specifiers: this is the maximum number of significant digits to be printed.
  • For s specifier: it acts as a cutoff point, setting a maximum character limit to the string.

Note: If the period is specified without an explicit value for precision, 0 is assumed.

Note: Attempting to use a position specifier greater than PHP_INT_MAX will generate warnings.

Specifiers
Specifier | Description
% A literal percent character. No argument is required.
b | The argument is treated as an integer and presented as a binary number.
c | The argument is treated as an integer and presented as the character with that ASCII.
d | The argument is treated as an integer and presented as a (signed) decimal number.
e | The argument is treated as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point since PHP 5.2.1. In earlier versions, it was taken as number of significant digits (one less).
E | Like the e specifier but uses uppercase letter (e.g. 1.2E+2).
f | The argument is treated as a float and presented as a floating-point number (locale aware).
F | The argument is treated as a float and presented as a floating-point number (non-locale aware). Available as of PHP 5.0.3.
g

General format.

Let P equal the precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero. Then, if a conversion with style E would have an exponent of X:

If P > X ≥ −4, the conversion is with style f and precision P − (X + 1). Otherwise, the conversion is with style e and precision P − 1.

G | Like the g specifier but uses E and F.
o | The argument is treated as an integer and presented as an octal number.
s | The argument is treated and presented as a string.
u | The argument is treated as an integer and presented as an unsigned decimal number.
x | The argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).
X | The argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).

Warning

The c type specifier ignores padding and width

Warning

Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results

Variables will be co-erced to a suitable type for the specifier:

Type Handling
Type | Specifiers
string | s
integer | d, u, c, o, x, X, b
double | g, G, e, E, f, F

...

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.

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


Seeks on a file pointer

  • « fscanf
  • fstat »
  • PHP Manual
  • Filesystem Functions
  • Seeks on a file pointer

fseek

(PHP 4, PHP 5, PHP 7)

fseek — Seeks on a file pointer

Description

fseek ( resource $handle , int $offset [, int $whence = SEEK_SET ] ) : int

Sets the file position indicator for the file referenced by handle. 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

handle

A file system pointer resource that is typically created using fopen().

offset

The offset.

To move to a position before the end-of-file, you need to pass a negative value in offset and set whence to SEEK_END.

whence

whence values are:

  • SEEK_SET - Set position equal to offset bytes.
  • SEEK_CUR - Set position to current location plus offset.
  • SEEK_END - Set position to end-of-file plus offset.

Return Values

Upon success, returns 0; otherwise, returns -1.

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


Gets information about a file using an open file pointer

  • « fseek
  • ftell »
  • PHP Manual
  • Filesystem Functions
  • Gets information about a file using an open file pointer

fstat

(PHP 4, PHP 5, PHP 7)

fstat — Gets information about a file using an open file pointer

Description

fstat ( resource $handle ) : array

Gathers the statistics of the file opened by the file pointer handle. This function is similar to the stat() function except that it operates on an open file pointer instead of a filename.

Parameters

handle

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.

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.


Returns the current position of the file read/write pointer

  • « fstat
  • ftruncate »
  • PHP Manual
  • Filesystem Functions
  • Returns the current position of the file read/write pointer

ftell

(PHP 4, PHP 5, PHP 7)

ftell — Returns the current position of the file read/write pointer

Description

ftell ( resource $handle ) : int

Returns the position of the file pointer referenced by handle.

Parameters

handle

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


Truncates a file to a given length

  • « ftell
  • fwrite »
  • PHP Manual
  • Filesystem Functions
  • Truncates a file to a given length

ftruncate

(PHP 4, PHP 5, PHP 7)

ftruncate — Truncates a file to a given length

Description

ftruncate ( resource $handle , int $size ) : bool

Takes the filepointer, handle, and truncates the file to length, size.

Parameters

handle

The file pointer.

Note:

The handle 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


Binary-safe file write

  • « ftruncate
  • glob »
  • PHP Manual
  • Filesystem Functions
  • Binary-safe file write

fwrite

(PHP 4, PHP 5, PHP 7)

fwrite — Binary-safe file write

Description

fwrite ( resource $handle , string $string [, int $length ] ) : int

fwrite() writes the contents of string to the file stream pointed to by handle.

Parameters

handle

A file system pointer resource that is typically created using fopen().

string

The string that is to be written.

length

If the length argument is given, writing will stop after length bytes have been written or the end of string is reached, whichever comes first.

Note that if the length argument is given, then the magic_quotes_runtime configuration option will be ignored and no slashes will be stripped from string.

Return Values

fwrite() returns the number of bytes written, or FALSE on error.

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 handle was fopen()ed in append mode, fwrite()s are atomic (unless the size of string 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!
?>

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 (!$handle = fopen($filename, 'a')) {
         echo "Cannot open file ($filename)";
         exit;
    }

    // Write $somecontent to our opened file.
    if (fwrite($handle, $somecontent) === FALSE) {
        echo "Cannot write to file ($filename)";
        exit;
    }

    echo "Success, wrote ($somecontent) to file ($filename)";

    fclose($handle);

} else {
    echo "The file $filename is not writable";
}
?>

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


Find pathnames matching a pattern

  • « fwrite
  • is_dir »
  • PHP Manual
  • Filesystem Functions
  • Find pathnames matching a pattern

glob

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

glob — Find pathnames matching a pattern

Description

glob ( string $pattern [, int $flags = 0 ] ) : array

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.

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.
  • \ - Escapes the following character, except when the GLOB_NOESCAPE flag is used.

flags

Valid flags:

  • GLOB_MARK - Adds a slash to each directory returned
  • GLOB_NOSORT - Return files as they appear in the directory (no sorting). When this flag is not used, the pathnames are sorted alphabetically
  • GLOB_NOCHECK - Return the search pattern if no files matching it were found
  • GLOB_NOESCAPE - Backslashes do not quote metacharacters
  • GLOB_BRACE - Expands {a,b,c} to match 'a', 'b', or 'c'
  • GLOB_ONLYDIR - Return only directory entries which match the pattern
  • GLOB_ERR - Stop on read errors (like unreadable directories), by default errors are ignored.

Return Values

Returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.

Note:

On some systems it is impossible to distinguish between empty match and an error.

Changelog

Version | Description
5.1.0 | GLOB_ERR was added

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

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

Note: The GLOB_BRACE flag is not available on some non GNU systems, like Solaris.

See Also

  • opendir() - Open directory handle
  • readdir() - Read entry from directory handle
  • closedir() - Close directory handle
  • fnmatch() - Match filename against a pattern


Tells whether the filename is a directory

  • « glob
  • is_executable »
  • PHP Manual
  • Filesystem Functions
  • Tells whether the filename is a directory

is_dir

(PHP 4, PHP 5, PHP 7)

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 safe mode, or open_basedir further restrictions may apply.

Return Values

Returns TRUE if the filename exists and is a directory, FALSE otherwise.

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)

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

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


Tells whether the filename is executable

  • « is_dir
  • is_file »
  • PHP Manual
  • Filesystem Functions
  • Tells whether the filename is executable

is_executable

(PHP 4, PHP 5, PHP 7)

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.

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

?>

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

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_file() - Tells whether the filename is a regular file
  • is_link() - Tells whether the filename is a symbolic link


Tells whether the filename is a regular file

  • « is_executable
  • is_link »
  • PHP Manual
  • Filesystem Functions
  • Tells whether the filename is a regular file

is_file

(PHP 4, PHP 5, PHP 7)

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.

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.

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)

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

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


Tells whether the filename is a symbolic link

  • « is_file
  • is_readable »
  • PHP Manual
  • Filesystem Functions
  • Tells whether the filename is a symbolic link

is_link

(PHP 4, PHP 5, PHP 7)

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.

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

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

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


Tells whether a file exists and is readable

  • « is_link
  • is_uploaded_file »
  • PHP Manual
  • Filesystem Functions
  • Tells whether a file exists and is readable

is_readable

(PHP 4, PHP 5, PHP 7)

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.

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

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

Notes

Keep in mind that PHP may be accessing the file as the user id that the web server runs as (often 'nobody'). Safe mode limitations are not taken into account before PHP 5.1.5.

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


Tells whether the file was uploaded via HTTP POST

  • « is_readable
  • is_writable »
  • PHP Manual
  • Filesystem Functions
  • Tells whether the file was uploaded via HTTP POST

is_uploaded_file

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

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.


Tells whether the filename is writable

  • « is_uploaded_file
  • is_writeable »
  • PHP Manual
  • Filesystem Functions
  • Tells whether the filename is writable

is_writable

(PHP 4, PHP 5, PHP 7)

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'). Safe mode limitations are not taken into account.

Parameters

filename

The filename being checked.

Return Values

Returns TRUE if the filename exists and is writable.

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

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

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


Alias of is_writable

  • « is_writable
  • lchgrp »
  • PHP Manual
  • Filesystem Functions
  • Alias of is_writable

is_writeable

(PHP 4, PHP 5, PHP 7)

is_writeable — Alias of is_writable()

Description

This function is an alias of: is_writable().


Changes group ownership of symlink

  • « is_writeable
  • lchown »
  • PHP Manual
  • Filesystem Functions
  • Changes group ownership of symlink

lchgrp

(PHP 5 >= 5.1.3, PHP 7)

lchgrp — Changes group ownership of symlink

Description

lchgrp ( string $filename , mixed $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: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

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


Changes user ownership of symlink

  • « lchgrp
  • link »
  • PHP Manual
  • Filesystem Functions
  • Changes user ownership of symlink

lchown

(PHP 5 >= 5.1.3, PHP 7)

lchown — Changes user ownership of symlink

Description

lchown ( string $filename , mixed $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: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

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


Create a hard link

  • « lchown
  • linkinfo »
  • PHP Manual
  • Filesystem Functions
  • Create a hard link

link

(PHP 4, PHP 5, PHP 7)

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.

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms (Vista, Server 2008 or greater).

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


Gets information about a link

  • « link
  • lstat »
  • PHP Manual
  • Filesystem Functions
  • Gets information about a link

linkinfo

(PHP 4, PHP 5, PHP 7)

linkinfo — Gets information about a link

Description

linkinfo ( string $path ) : int

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 0 or FALSE in case of error.

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms (Vista, Server 2008 or greater).

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


Gives information about a file or symbolic link

  • « linkinfo
  • mkdir »
  • PHP Manual
  • Filesystem Functions
  • Gives information about a file or symbolic link

lstat

(PHP 4, PHP 5, PHP 7)

lstat — Gives information about a file or symbolic link

Description

lstat ( string $filename ) : array

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.

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
)

Errors/Exceptions

Upon failure, an E_WARNING is emitted.

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


Makes directory

  • « lstat
  • move_uploaded_file »
  • PHP Manual
  • Filesystem Functions
  • Makes directory

mkdir

(PHP 4, PHP 5, PHP 7)

mkdir — Makes directory

Description

mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive = FALSE [, resource $context ]]] ) : bool

Attempts to create the directory specified by pathname.

Parameters

pathname

The directory path.

mode

The mode is 0777 by default, which means the widest possible access. For more information on modes, read the details on the chmod() page.

Note:

mode is ignored on Windows.

Note that you probably want to specify the mode as an octal number, which means it should have a leading zero. The mode is also modified by the current umask, which you can change using umask().

recursive

Allows the creation of nested directories specified in the pathname.

context

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 mkdir() example

<?php
mkdir("/path/to/my/dir", 0700);
?>

Example #2 mkdir() using the recursive parameter

<?php
// Desired folder 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 folders...');
}

// ...
?>

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.

Notes

Note: When safe mode is enabled, PHP checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.

See Also

  • is_dir() - Tells whether the filename is a directory
  • rmdir() - Removes directory


Moves an uploaded file to a new location

  • « mkdir
  • parse_ini_file »
  • PHP Manual
  • Filesystem Functions
  • Moves an uploaded file to a new location

move_uploaded_file

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

move_uploaded_file — Moves an uploaded file to a new location

Description

move_uploaded_file ( string $filename , string $destination ) : bool

This function checks to ensure that the file designated by filename 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 destination.

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

filename

The filename of the uploaded file.

destination

The destination of the moved file.

Return Values

Returns TRUE on success.

If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.

If filename 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 both safe mode and open_basedir aware. However, restrictions are placed only on the destination path as to allow the moving of uploaded files in which filename 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 a configuration file

  • « move_uploaded_file
  • parse_ini_string »
  • PHP Manual
  • Filesystem Functions
  • Parse a configuration file

parse_ini_file

(PHP 4, PHP 5, PHP 7)

parse_ini_file — Parse a configuration file

Description

parse_ini_file ( string $filename [, bool $process_sections = FALSE [, int $scanner_mode = INI_SCANNER_NORMAL ]] ) : array

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.

Parameters

filename

The filename 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.

Changelog

Version | Description
7.0.0 | Hash marks (#) are no longer recognized as comments.
5.6.1 | Added new INI_SCANNER_TYPED mode.
5.3.0 | Added optional scanner_mode parameter. Single quotes may now be used around variable assignments. Hash marks (#) should no longer be used as comments and will throw a deprecation warning if used.
5.2.7 | On syntax error this function will return FALSE rather than an empty array.
5.2.4 | Keys and section names consisting of numbers are now evaluated as PHP integers thus numbers starting by 0 are evaluated as octals and numbers starting by 0x are evaluated as hexadecimals.

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 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. 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 available as of PHP 5.2.4
$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

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 (as of PHP 5.6.1). 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.

See Also

  • parse_ini_string() - Parse a configuration string


Parse a configuration string

  • « parse_ini_file
  • pathinfo »
  • PHP Manual
  • Filesystem Functions
  • Parse a configuration string

parse_ini_string

(PHP 5 >= 5.3.0, PHP 7)

parse_ini_string — Parse a configuration string

Description

parse_ini_string ( string $ini [, bool $process_sections = FALSE [, int $scanner_mode = INI_SCANNER_NORMAL ]] ) : array

parse_ini_string() returns the settings in string ini in an associative array.

The structure of the ini string is the same as the php.ini's.

Parameters

ini

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


Returns information about a file path

  • « parse_ini_string
  • pclose »
  • PHP Manual
  • Filesystem Functions
  • Returns information about a file path

pathinfo

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

pathinfo — Returns information about a file path

Description

pathinfo ( string $path [, int $options = PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME ] ) : mixed

pathinfo() returns information about path: either an associative array or a string, depending on options.

Note:

For information on retrieving the current path info, read the section on predefined reserved variables.

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.

options

If present, specifies a specific element to be returned; one of PATHINFO_DIRNAME, PATHINFO_BASENAME, PATHINFO_EXTENSION or PATHINFO_FILENAME.

If options is not specified, returns all available elements.

Return Values

If the options 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 options is present, returns a string containing the requested element.

Changelog

Version | Description
5.2.0 | The PATHINFO_FILENAME constant was added.

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"; // since PHP 5.2.0
?>

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] =>
)

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


Closes process file pointer

  • « pathinfo
  • popen »
  • PHP Manual
  • Filesystem Functions
  • Closes process file pointer

pclose

(PHP 4, PHP 5, PHP 7)

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


Opens process file pointer

  • « pclose
  • readfile »
  • PHP Manual
  • Filesystem Functions
  • Opens process file pointer

popen

(PHP 4, PHP 5, PHP 7)

popen — Opens process file pointer

Description

popen ( string $command , string $mode ) : resource

Opens a pipe to a process executed by forking the command given by command.

Parameters

command

The command

mode

The mode

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

Note: When safe mode is enabled, you can only execute files within the safe_mode_exec_dir. For practical reasons, it is currently not allowed to have .. components in the path to the executable.

Warning

With safe mode enabled, the command string is escaped with escapeshellcmd(). Thus, echo y | echo x becomes echo y \| echo x.

See Also

  • pclose() - Closes process file pointer
  • fopen() - Opens file or URL
  • proc_open() - Execute a command and open file pointers for input/output


Outputs a file

  • « popen
  • readlink »
  • PHP Manual
  • Filesystem Functions
  • Outputs a file

readfile

(PHP 4, PHP 5, PHP 7)

readfile — Outputs a file

Description

readfile ( string $filename [, bool $use_include_path = FALSE [, resource $context ]] ) : int

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:

Open / Save dialogue

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.

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams.

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


Returns the target of a symbolic link

  • « readfile
  • realpath_cache_get »
  • PHP Manual
  • Filesystem Functions
  • Returns the target of a symbolic link

readlink

(PHP 4, PHP 5, PHP 7)

readlink — Returns the target of a symbolic link

Description

readlink ( string $path ) : string

readlink() does the same as the readlink C function.

Parameters

path

The symbolic link path.

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms (Vista, Server 2008 or greater).

Return Values

Returns the contents of the symbolic link path or FALSE on error.

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


Get realpath cache entries

  • « readlink
  • realpath_cache_size »
  • PHP Manual
  • Filesystem Functions
  • Get realpath cache entries

realpath_cache_get

(PHP 5 >= 5.3.2, PHP 7)

realpath_cache_get — Get realpath cache entries

Description

realpath_cache_get ( void ) : array

Get the contents of the realpath cache.

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


Get realpath cache size

  • « realpath_cache_get
  • realpath »
  • PHP Manual
  • Filesystem Functions
  • Get realpath cache size

realpath_cache_size

(PHP 5 >= 5.3.2, PHP 7)

realpath_cache_size — Get realpath cache size

Description

realpath_cache_size ( void ) : int

Get the amount of memory used by the realpath cache.

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


Returns canonicalized absolute pathname

  • « realpath_cache_size
  • rename »
  • PHP Manual
  • Filesystem Functions
  • Returns canonicalized absolute pathname

realpath

(PHP 4, PHP 5, PHP 7)

realpath — Returns canonicalized absolute pathname

Description

realpath ( string $path ) : string

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

Changelog

Version | Description
5.3.0 | Prior to this release, if only the last path component did not exist, realpath() would not fail on *BSD systems. realpath() now fails in this case.
5.2.1 | Prior to this version, realpath() returned FALSE if path is an empty string or NULL.

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


Renames a file or directory

  • « realpath
  • rewind »
  • PHP Manual
  • Filesystem Functions
  • Renames a file or directory

rename

(PHP 4, PHP 5, PHP 7)

rename — Renames a file or directory

Description

rename ( string $oldname , string $newname [, resource $context ] ) : bool

Attempts to rename oldname to newname, moving it between directories if necessary. If renaming a file and newname exists, it will be overwritten. If renaming a directory and newname exists, this function will emit a warning.

Parameters

oldname

The old name.

Note:

The wrapper used in oldname must match the wrapper used in newname.

newname

The new name.

context

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.3.1 | rename() can now rename files across drives in Windows.

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 the position of a file pointer

  • « rename
  • rmdir »
  • PHP Manual
  • Filesystem Functions
  • Rewind the position of a file pointer

rewind

(PHP 4, PHP 5, PHP 7)

rewind — Rewind the position of a file pointer

Description

rewind ( resource $handle ) : bool

Sets the file position indicator for handle 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

handle

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


Removes directory

  • « rewind
  • set_file_buffer »
  • PHP Manual
  • Filesystem Functions
  • Removes directory

rmdir

(PHP 4, PHP 5, PHP 7)

rmdir — Removes directory

Description

rmdir ( string $dirname [, resource $context ] ) : bool

Attempts to remove the directory named by dirname. The directory must be empty, and the relevant permissions must permit this. A E_WARNING level error will be generated on failure.

Parameters

dirname

Path to the directory.

context

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 rmdir() example

<?php
if (!is_dir('examples')) {
    mkdir('examples');
}

rmdir('examples');
?>

Notes

Note: When safe mode is enabled, PHP checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.

See Also

  • is_dir() - Tells whether the filename is a directory
  • mkdir() - Makes directory
  • unlink() - Deletes a file


Alias of stream_set_write_buffer

  • « rmdir
  • stat »
  • PHP Manual
  • Filesystem Functions
  • Alias of stream_set_write_buffer

set_file_buffer

(PHP 4, PHP 5, PHP 7)

set_file_buffer — Alias of stream_set_write_buffer()

Description

This function is an alias of: stream_set_write_buffer().


Gives information about a file

  • « set_file_buffer
  • symlink »
  • PHP Manual
  • Filesystem Functions
  • Gives information about a file

stat

(PHP 4, PHP 5, PHP 7)

stat — Gives information about a file

Description

stat ( string $filename ) : array

Gathers the statistics of the file named by filename. If filename is a symbolic link, statistics are from the file itself, not the symlink.

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.

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
0120000 | link
0100000 | regular file
0060000 | block device
0040000 | directory
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.

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


Creates a symbolic link

  • « stat
  • tempnam »
  • PHP Manual
  • Filesystem Functions
  • Creates a symbolic link

symlink

(PHP 4, PHP 5, PHP 7)

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.

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms (Vista, Server 2008 or greater).

Examples

Example #1 Create a symbolic link

<?php
$target = 'uploads.php';
$link = 'uploads';
symlink($target, $link);

echo readlink($link);
?>

Notes

Note: Windows users should note that this function will only work if the system you run PHP from is Windows Vista/Windows Server 2008 or newer. Windows versions prior to that do not support symbolic links.

See Also

  • link() - Create a hard link
  • readlink() - Returns the target of a symbolic link
  • linkinfo() - Gets information about a link


Create file with unique file name

  • « symlink
  • tmpfile »
  • PHP Manual
  • Filesystem Functions
  • Create file with unique file name

tempnam

(PHP 4, PHP 5, PHP 7)

tempnam — Create file with unique file name

Description

tempnam ( string $dir , string $prefix ) : string

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

dir

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. Windows even uses only the first three characters of the prefix.

Return Values

Returns the new temporary filename (with path), or FALSE on failure.

Examples

Example #1 tempnam() example

<?php
$tmpfname = tempnam("/tmp", "FOO");

$handle = fopen($tmpfname, "w");
fwrite($handle, "writing to tempfile");
fclose($handle);

// do here something

unlink($tmpfname);
?>

Notes

Note: If PHP cannot create a file in the specified dir parameter, it falls back on the system default. On NTFS this also happens if the specified dir 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


Creates a temporary file

  • « tempnam
  • touch »
  • PHP Manual
  • Filesystem Functions
  • Creates a temporary file

tmpfile

(PHP 4, PHP 5, PHP 7)

tmpfile — Creates a temporary file

Description

tmpfile ( void ) : resource

Creates a temporary file with a unique name in read-write (w+) 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.

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


Sets access and modification time of file

  • « tmpfile
  • umask »
  • PHP Manual
  • Filesystem Functions
  • Sets access and modification time of file

touch

(PHP 4, PHP 5, PHP 7)

touch — Sets access and modification time of file

Description

touch ( string $filename [, int $time = time() [, int $atime ]] ) : bool

Attempts to set the access and modification times of the file named in the filename parameter to the value given in time. 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.

time

The touch time. If time is not supplied, the current system time is used.

atime

If present, the access time of the given filename is set to the value of atime. Otherwise, it is set to the value passed to the time parameter. If neither are present, the current system time is used.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.3.0 | It became possible to change the modification time of a directory under Windows.

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

Warning

Prior to PHP 5.3.0 it was not possible to change the modification time of a directory with this function under Windows.


Changes the current umask

  • « touch
  • unlink »
  • PHP Manual
  • Filesystem Functions
  • Changes the current umask

umask

(PHP 4, PHP 5, PHP 7)

umask — Changes the current umask

Description

umask ([ int $mask ] ) : 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

umask() without arguments simply returns the current umask otherwise the old umask is returned.

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.


Deletes a file

  • « umask
  • Inotify »
  • PHP Manual
  • Filesystem Functions
  • Deletes a file

unlink

(PHP 4, PHP 5, PHP 7)

unlink — Deletes a file

Description

unlink ( string $filename [, resource $context ] ) : 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.

context

Note: Context support was added with PHP 5.0.0. For a description of contexts, refer to Streams.

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


Inotify

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installing/Configuring
    • Runtime Configuration
    • 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


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

  • Requirements
  • Installing/Configuring
  • Runtime Configuration
  • Resource Types


  • « Installing/Configuring
  • Installing/Configuring »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

This extension requires Linux 2.6.13 or newer, and a recent libC.


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.


  • « Installing/Configuring
  • Resource Types »
  • PHP Manual
  • Installing/Configuring
  • Runtime Configuration

Runtime Configuration

This extension has no configuration directives defined in php.ini.


  • « Runtime Configuration
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

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 (integer)
File was accessed (read) (*)
IN_MODIFY (integer)
File was modified (*)
IN_ATTRIB (integer)
Metadata changed (e.g. permissions, mtime, etc.) (*)
IN_CLOSE_WRITE (integer)
File opened for writing was closed (*)
IN_CLOSE_NOWRITE (integer)
File not opened for writing was closed (*)
IN_OPEN (integer)
File was opened (*)
IN_MOVED_TO (integer)
File moved into watched directory (*)
IN_MOVED_FROM (integer)
File moved out of watched directory (*)
IN_CREATE (integer)
File or directory created in watched directory (*)
IN_DELETE (integer)
File or directory deleted in watched directory (*)
IN_DELETE_SELF (integer)
Watched file or directory was deleted
IN_MOVE_SELF (integer)
Watch file or directory was moved
IN_CLOSE (integer)
Equals to IN_CLOSE_WRITE | IN_CLOSE_NOWRITE
IN_MOVE (integer)
Equals to IN_MOVED_FROM | IN_MOVED_TO
IN_ALL_EVENTS (integer)
Bitmask of all the above constants
IN_UNMOUNT (integer)
File system containing watched object was unmounted
IN_Q_OVERFLOW (integer)
Event queue overflowed (wd is -1 for this event)
IN_IGNORED (integer)
Watch was removed (explicitly by inotify_rm_watch() or because file was removed or filesystem unmounted
IN_ISDIR (integer)
Subject of this event is a directory
IN_ONLYDIR (integer)
Only watch pathname if it is a directory (Since Linux 2.6.15)
IN_DONT_FOLLOW (integer)
Do not dereference pathname if it is a symlink (Since Linux 2.6.15)
IN_MASK_ADD (integer)
Add events to watch mask for this pathname if it already exists (instead of replacing mask).
IN_ONESHOT (integer)
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

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


Add a watch to an initialized inotify instance

  • « Inotify Functions
  • inotify_init »
  • PHP Manual
  • Inotify Functions
  • Add a watch to an initialized inotify instance

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

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.

See Also

  • inotify_init() - Initialize an inotify instance


Initialize an inotify instance

  • « inotify_add_watch
  • inotify_queue_len »
  • PHP Manual
  • Inotify Functions
  • Initialize an inotify instance

inotify_init

(PECL inotify >= 0.1.2)

inotify_init — Initialize an inotify instance

Description

inotify_init ( void ) : resource

Initialize an inotify instance for use with inotify_add_watch()

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


Return a number upper than zero if there are pending events

  • « inotify_init
  • inotify_read »
  • PHP Manual
  • Inotify Functions
  • Return a number upper than zero if there are pending events

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 tv_sec and tv_usec
  • stream_set_blocking() - Set blocking/non-blocking mode on a stream


Read events from an inotify instance

  • « inotify_queue_len
  • inotify_rm_watch »
  • PHP Manual
  • Inotify Functions
  • Read events from an inotify instance

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 tv_sec and tv_usec
  • 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


Remove an existing watch from an inotify instance

  • « inotify_read
  • Mimetype »
  • PHP Manual
  • Inotify Functions
  • Remove an existing watch from an inotify instance

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


Mimetype

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants


Introduction

Warning

This extension has been deprecated as the PECL extension Fileinfo provides the same functionality (and more) in a much cleaner way.

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.

This extension is derived from Apache mod_mime_magic, which is itself based on the file command maintained by Ian F. Darwin. See the source code for further historic and copyright information.


Installation

Warning

Mimetype extensions has been removed from PHP 5.3.0 in favor of Fileinfo.

You must compile PHP with the configure switch --with-mime-magic to get support for mime-type functions. The extension needs a copy of the simplified magic file that is distributed with the Apache httpd.

Note:

This extension is not capable of handling the fully decorated magic file that generally comes with standard Linux distro's and is supposed to be used with recent versions of file command.

Note: Note to Win32 Users

In order to use this module on a Windows environment, you must set the path to the bundled magic.mime file in your php.ini.

Example #1 Setting the path to magic.mime

mime_magic.magicfile = "$PHP_INSTALL_DIR\magic.mime"

Remember to substitute the $PHP_INSTALL_DIR for your actual path to PHP in the above example. e.g. c:\php


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Mimetype configuration options
Name | Default | Changeable | Changelog
mime_magic.debug | "0" | PHP_INI_SYSTEM | Available since PHP 5.0.0.
mime_magic.magicfile | "/path/to/php/magic.mime" | PHP_INI_SYSTEM | Available since PHP 4.3.0.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

mime_magic.debug bool

Enable/disable debugging.

mime_magic.magicfile string

The path to the magic.mime file.


  • « Resource Types
  • Phdfs »
  • PHP Manual
  • Mimetype
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


Phdfs

  • Installing/Configuring
    • Requirements
    • Installation
    • Resource Types
  • Predefined Constants
  • phdfs — The phdfs class
    • phdfs::connect — Description
    • phdfs::__construct — Description
    • phdfs::copy — Description
    • phdfs::create_directory — Description
    • phdfs::delete — Description
    • phdfs::__destruct — Description
    • phdfs::disconnect — Description
    • phdfs::exists — Description
    • phdfs::file_info — Description
    • phdfs::list_directory — Description
    • phdfs::read — Description
    • phdfs::rename — Description
    • phdfs::tell — Description
    • phdfs::write — Description


  • « Phdfs
  • Installing/Configuring »
  • PHP Manual
  • Phdfs

The phdfs extensions is using PHP to manipulate Hadoop HDFS phdfs requires PHP 5.3 or greater. Earlier versions may not work. For a quick start guide, please refer to the Tutorials section.


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

PHP Version: PHP 5.3+

ZTS Enabled ( Thread Safety )

need to install hadoop


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


  • « Installation
  • Resource Types »
  • PHP Manual
  • Installing/Configuring

This extension has no configuration directives defined in php.ini.


  • «
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

This extension has no resource types 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.

O_WRONLY (integer)
O_CREAT (integer)
O_APPEND (integer)


The phdfs class

(phdfs >= 0.1.0)

Introduction

Class synopsis

phdfs {
/* Properties */
static $host ;
static $port ;
/* Methods */
public connect ( void ) : bool
public __construct ( string $ip , string $port )
public copy ( string $source_file , string $destination_file ) : bool
public create_directory ( string $path ) : bool
public delete ( string $path ) : bool
public __destruct ( void ) : void
public disconnect ( void ) : bool
public exists ( string $path ) : bool
public file_info ( string $path ) : array
public list_directory ( string $path [, int $level = 0 ] ) : array
public read ( string $path [, int $length = 0 ] ) : string
public rename ( string $old_path , string $new_path ) : bool
public tell ( string $path [, int $read_length = 1024 ] ) : int
public write ( string $path , string $buffer [, int $mode = 0 ] ) : bool
}

Properties

host

port

Table of Contents

  • phdfs::connect — Description
  • phdfs::__construct — Description
  • phdfs::copy — Description
  • phdfs::create_directory — Description
  • phdfs::delete — Description
  • phdfs::__destruct — Description
  • phdfs::disconnect — Description
  • phdfs::exists — Description
  • phdfs::file_info — Description
  • phdfs::list_directory — Description
  • phdfs::read — Description
  • phdfs::rename — Description
  • phdfs::tell — Description
  • phdfs::write — Description


Description

  • « phdfs
  • phdfs::__construct »
  • PHP Manual
  • phdfs
  • Description

phdfs::connect

(phdfs >= 0.1.0)

phdfs::connect — Description

Description

public phdfs::connect ( void ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.


Description

  • « phdfs::connect
  • phdfs::copy »
  • PHP Manual
  • phdfs
  • Description

phdfs::__construct

(phdfs >= 0.1.0)

phdfs::__construct — Description

Description

public phdfs::__construct ( string $ip , string $port )

Warning

This function is currently not documented; only its argument list is available.

Parameters

ip

port

Return Values


Description

  • « phdfs::__construct
  • phdfs::create_directory »
  • PHP Manual
  • phdfs
  • Description

phdfs::copy

(phdfs >= 0.1.0)

phdfs::copy — Description

Description

public phdfs::copy ( string $source_file , string $destination_file ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

source_file

destination_file

Return Values

Returns TRUE on success or FALSE on failure.


Description

  • « phdfs::copy
  • phdfs::delete »
  • PHP Manual
  • phdfs
  • Description

phdfs::create_directory

(phdfs >= 0.1.0)

phdfs::create_directory — Description

Description

public phdfs::create_directory ( string $path ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

path

Return Values

Returns TRUE on success or FALSE on failure.


Description

  • « phdfs::create_directory
  • phdfs::__destruct »
  • PHP Manual
  • phdfs
  • Description

phdfs::delete

(phdfs >= 0.1.0)

phdfs::delete — Description

Description

public phdfs::delete ( string $path ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

path

Return Values

Returns TRUE on success or FALSE on failure.


Description

  • « phdfs::delete
  • phdfs::disconnect »
  • PHP Manual
  • phdfs
  • Description

phdfs::__destruct

(phdfs >= 0.1.0)

phdfs::__destruct — Description

Description

public phdfs::__destruct ( void ) : 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.


Description

  • « phdfs::__destruct
  • phdfs::exists »
  • PHP Manual
  • phdfs
  • Description

phdfs::disconnect

(phdfs >= 0.1.0)

phdfs::disconnect — Description

Description

public phdfs::disconnect ( void ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.


Description

  • « phdfs::disconnect
  • phdfs::file_info »
  • PHP Manual
  • phdfs
  • Description

phdfs::exists

(phdfs>= 0.1.0)

phdfs::exists — Description

Description

public phdfs::exists ( string $path ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

path

Return Values

Returns TRUE on success or FALSE on failure.


Description

  • « phdfs::exists
  • phdfs::list_directory »
  • PHP Manual
  • phdfs
  • Description

phdfs::file_info

(phdfs >= 0.1.0)

phdfs::file_info — Description

Description

public phdfs::file_info ( string $path ) : array

Warning

This function is currently not documented; only its argument list is available.

Parameters

path

Return Values

Returns array on success or FALSE on failure.


Description

  • « phdfs::file_info
  • phdfs::read »
  • PHP Manual
  • phdfs
  • Description

phdfs::list_directory

(phdfs >= 0.1.0)

phdfs::list_directory — Description

Description

public phdfs::list_directory ( string $path [, int $level = 0 ] ) : array

Warning

This function is currently not documented; only its argument list is available.

Parameters

path

level

Return Values

Returns array on success or FALSE on failure.


Description

  • « phdfs::list_directory
  • phdfs::rename »
  • PHP Manual
  • phdfs
  • Description

phdfs::read

(phdfs >= 0.1.0)

phdfs::read — Description

Description

public phdfs::read ( string $path [, int $length = 0 ] ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

path

length

Return Values


Description

  • « phdfs::read
  • phdfs::tell »
  • PHP Manual
  • phdfs
  • Description

phdfs::rename

(phdfs >= 0.1.0)

phdfs::rename — Description

Description

public phdfs::rename ( string $old_path , string $new_path ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

old_path

new_path

Return Values

Returns TRUE on success or FALSE on failure.


Description

  • « phdfs::rename
  • phdfs::write »
  • PHP Manual
  • phdfs
  • Description

phdfs::tell

(phdfs >= 0.1.0)

phdfs::tell — Description

Description

public phdfs::tell ( string $path [, int $read_length = 1024 ] ) : int

Warning

This function is currently not documented; only its argument list is available.

Parameters

path

read_length

Return Values


Description

  • « phdfs::tell
  • Proctitle »
  • PHP Manual
  • phdfs
  • Description

phdfs::write

(phdfs >= 0.1.0)

phdfs::write — Description

Description

public phdfs::write ( string $path , string $buffer [, int $mode = 0 ] ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

path

buffer

mode

Return Values

Returns TRUE on success or FALSE on failure.


Proctitle

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Proctitle Functions
    • setproctitle — Set the process title
    • setthreadtitle — Set the thread title


Introduction

This extension allows changing the current process', and thread, name on Linux and *BSD systems. This is useful when using pcntl_fork() to identify running processes in process list


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

Nothing special.


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


  • « Resource Types
  • Proctitle Functions »
  • PHP Manual
  • Proctitle
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


Proctitle Functions

Table of Contents

  • setproctitle — Set the process title
  • setthreadtitle — Set the thread title


Set the process title

  • « Proctitle Functions
  • setthreadtitle »
  • PHP Manual
  • Proctitle Functions
  • Set the process title

setproctitle

(PECL proctitle >= 0.1.0)

setproctitle — Set the process title

Description

setproctitle ( string $title ) : void

Sets the process title of the current process.

Parameters

title

The title to use as the process title.

Return Values

No value is returned.

Examples

Example #1 setproctitle() example

Running the example below will change the process title (visible with ps a for example).

<?php
setproctitle("myscript");
?>

The above example will output something similar to:

$ ps a
  PID TTY      STAT   TIME COMMAND
 1168 pts/3    S      0:00 myscript

See Also

  • cli_set_process_title() - Sets the process title
  • pcntl_fork() - Forks the currently running process
  • setthreadtitle() - Set the thread title


Set the thread title

  • « setproctitle
  • xattr »
  • PHP Manual
  • Proctitle Functions
  • Set the thread title

setthreadtitle

(PECL proctitle >= 0.1.2)

setthreadtitle — Set the thread title

Description

setthreadtitle ( string $title ) : bool

Sets the thread title.

Parameters

title

The title to use as the thread title.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 setthreadtitle() example

Running the example below will change the thread title (visible with ps c for example).

<?php
setthreadtitle("myscript");
?>

The above example will output something similar to:

$ ps c
  PID TTY      STAT   TIME COMMAND
 1178 pts/3    S      0:00 myscript

See Also

  • pcntl_fork() - Forks the currently running process
  • setproctitle() - Set the process title


xattr

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • 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


Introduction

The xattr extension allows for the manipulation of extended attributes on a filesystem.


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 (integer)
Set attribute in root (trusted) namespace. Requires root privileges.
XATTR_DONTFOLLOW (integer)
Do not follow the symbolic link but operate on symbolic link itself.
XATTR_CREATE (integer)
Function will fail if extended attribute already exists.
XATTR_REPLACE (integer)
Function will fail if extended attribute doesn't exist.


xattr Functions

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


Get an extended attribute

  • « xattr Functions
  • xattr_list »
  • PHP Manual
  • xattr Functions
  • Get an extended attribute

xattr_get

(PECL xattr >= 0.9.0)

xattr_get — Get an extended attribute

Description

xattr_get ( string $filename , string $name [, int $flags = 0 ] ) : string

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


Get a list of extended attributes

  • « xattr_get
  • xattr_remove »
  • PHP Manual
  • xattr Functions
  • Get a list of extended attributes

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


Remove an extended attribute

  • « xattr_list
  • xattr_set »
  • PHP Manual
  • xattr Functions
  • Remove 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


Set an extended attribute

  • « xattr_remove
  • xattr_supported »
  • PHP Manual
  • xattr Functions
  • Set 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


Check if filesystem supports extended attributes

  • « xattr_set
  • xdiff »
  • PHP Manual
  • xattr Functions
  • Check if filesystem supports extended attributes

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


xdiff

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • xdiff Functions
    • xdiff_file_bdiff_size — Read a size of file created by applying a binary diff
    • xdiff_file_bdiff — Make binary diff of two files
    • xdiff_file_bpatch — Patch a file with a binary diff
    • xdiff_file_diff_binary — Alias of xdiff_file_bdiff
    • xdiff_file_diff — Make unified diff of two files
    • xdiff_file_merge3 — Merge 3 files into one
    • xdiff_file_patch_binary — Alias of xdiff_file_bpatch
    • xdiff_file_patch — Patch a file with an unified diff
    • xdiff_file_rabdiff — Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm
    • xdiff_string_bdiff_size — Read a size of file created by applying a binary diff
    • xdiff_string_bdiff — Make binary diff of two strings
    • xdiff_string_bpatch — Patch a string with a binary diff
    • xdiff_string_diff_binary — Alias of xdiff_string_bdiff
    • xdiff_string_diff — Make unified diff of two strings
    • xdiff_string_merge3 — Merge 3 strings into one
    • xdiff_string_patch_binary — Alias of xdiff_string_bpatch
    • xdiff_string_patch — Patch a string with an unified diff
    • xdiff_string_rabdiff — Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm


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.


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.

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.

XDIFF_PATCH_NORMAL (integer)
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 (integer)
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

Table of Contents

  • xdiff_file_bdiff_size — Read a size of file created by applying a binary diff
  • xdiff_file_bdiff — Make binary diff of two files
  • xdiff_file_bpatch — Patch a file with a binary diff
  • xdiff_file_diff_binary — Alias of xdiff_file_bdiff
  • xdiff_file_diff — Make unified diff of two files
  • xdiff_file_merge3 — Merge 3 files into one
  • xdiff_file_patch_binary — Alias of xdiff_file_bpatch
  • xdiff_file_patch — Patch a file with an unified diff
  • xdiff_file_rabdiff — Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm
  • xdiff_string_bdiff_size — Read a size of file created by applying a binary diff
  • xdiff_string_bdiff — Make binary diff of two strings
  • xdiff_string_bpatch — Patch a string with a binary diff
  • xdiff_string_diff_binary — Alias of xdiff_string_bdiff
  • xdiff_string_diff — Make unified diff of two strings
  • xdiff_string_merge3 — Merge 3 strings into one
  • xdiff_string_patch_binary — Alias of xdiff_string_bpatch
  • xdiff_string_patch — Patch a string with an unified diff
  • xdiff_string_rabdiff — Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm


Read a size of file created by applying a binary diff

  • « xdiff Functions
  • xdiff_file_bdiff »
  • PHP Manual
  • xdiff Functions
  • Read a size of file created by applying 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


Make binary diff of two files

  • « xdiff_file_bdiff_size
  • xdiff_file_bpatch »
  • PHP Manual
  • xdiff Functions
  • Make binary diff of two files

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


Patch a file with a binary diff

  • « xdiff_file_bdiff
  • xdiff_file_diff_binary »
  • PHP Manual
  • xdiff Functions
  • 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


Alias of xdiff_file_bdiff

  • « xdiff_file_bpatch
  • xdiff_file_diff »
  • PHP Manual
  • xdiff Functions
  • Alias of xdiff_file_bdiff

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


Make unified diff of two files

  • « xdiff_file_diff_binary
  • xdiff_file_merge3 »
  • PHP Manual
  • xdiff Functions
  • Make unified diff of two files

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


Merge 3 files into one

  • « xdiff_file_diff
  • xdiff_file_patch_binary »
  • PHP Manual
  • xdiff Functions
  • Merge 3 files into one

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


Alias of xdiff_file_bpatch

  • « xdiff_file_merge3
  • xdiff_file_patch »
  • PHP Manual
  • xdiff Functions
  • Alias of xdiff_file_bpatch

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


Patch a file with an unified diff

  • « xdiff_file_patch_binary
  • xdiff_file_rabdiff »
  • PHP Manual
  • xdiff Functions
  • Patch a file with an unified diff

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


Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm

  • « xdiff_file_patch
  • xdiff_string_bdiff_size »
  • PHP Manual
  • xdiff Functions
  • Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm

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


Read a size of file created by applying a binary diff

  • « xdiff_file_rabdiff
  • xdiff_string_bdiff »
  • PHP Manual
  • xdiff Functions
  • Read a size of file created by applying 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 binary diff of two strings using the Rabin's polynomial fingerprinting algorithm
  • xdiff_string_bpatch() - Patch a string with a binary diff


Make binary diff of two strings

  • « xdiff_string_bdiff_size
  • xdiff_string_bpatch »
  • PHP Manual
  • xdiff Functions
  • Make binary diff of two strings

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


Patch a string with a binary diff

  • « xdiff_string_bdiff
  • xdiff_string_diff_binary »
  • PHP Manual
  • xdiff Functions
  • 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 binary diff of two strings using the Rabin's polynomial fingerprinting algorithm


Alias of xdiff_string_bdiff

  • « xdiff_string_bpatch
  • xdiff_string_diff »
  • PHP Manual
  • xdiff Functions
  • Alias of xdiff_string_bdiff

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


Make unified diff of two strings

  • « xdiff_string_diff_binary
  • xdiff_string_merge3 »
  • PHP Manual
  • xdiff Functions
  • Make unified diff of two strings

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


Merge 3 strings into one

  • « xdiff_string_diff
  • xdiff_string_patch_binary »
  • PHP Manual
  • xdiff Functions
  • Merge 3 strings into one

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


Alias of xdiff_string_bpatch

  • « xdiff_string_merge3
  • xdiff_string_patch »
  • PHP Manual
  • xdiff Functions
  • Alias of xdiff_string_bpatch

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 binary diff of two strings using the Rabin's polynomial fingerprinting algorithm


Patch a string with an unified diff

  • « xdiff_string_patch_binary
  • xdiff_string_rabdiff »
  • PHP Manual
  • xdiff Functions
  • Patch a string with an unified diff

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


Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

  • « xdiff_string_patch
  • Human Language and Character Encoding Support »
  • PHP Manual
  • xdiff Functions
  • Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

xdiff_string_rabdiff

(PECL xdiff >= 1.5.0)

xdiff_string_rabdiff — Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

Description

xdiff_string_bdiff ( string $old_data , string $new_data ) : string

Makes a binary diff of two strings and returns the result. The difference between this function and xdiff_string_bdiff() is different algorithm used which should result in faster execution and smaller diff produced. This function works with both text and binary data. Resulting patch can be later applied using xdiff_string_bpatch()/xdiff_file_bpatch().

For more details about differences between algorithm used please check » libxdiff website.

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


Human Language and Character Encoding Support

  • Enchant — Enchant spelling library
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Enchant Functions
  • FriBiDi
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • FriBiDi Functions
  • Gender — Determine gender of firstnames
    • Introduction
    • Installing/Configuring
    • Examples
    • Gender\Gender — The Gender\Gender class
  • Gettext
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Gettext Functions
  • iconv
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • iconv Functions
  • intl — Internationalization Functions
    • Introduction
    • 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
    • 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
    • Introduction
    • 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
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Pspell Functions
  • Recode — GNU Recode
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Recode Functions


Enchant spelling library

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • 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_dict — Free a dictionary resource
    • enchant_broker_free — Free the broker resource and its dictionnaries
    • 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_to_personal — Add a word to personal word list
    • 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_in_session — Whether or not 'word' exists in this spelling-session
    • 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


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)


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 not yet supported.

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

This extension is bundled with PHP as of PHP 5.3.0. Before this time, enchant was a PECL extension. Users of versions prior to 5.3.0 may use the » PECL extension.

Provided the required libraries are installed, users of PHP 5.3.0 or later may enable enchant by adding the --with-enchant[=dir] option when compiling PHP.


Resource Types

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

ENCHANT_MYSPELL (integer)
Dictionary type for MySpell. Used with enchant_broker_get_dict_path() and enchant_broker_set_dict_path().
ENCHANT_ISPELL (integer)
Dictionary type for Ispell. Used with enchant_broker_get_dict_path() and enchant_broker_set_dict_path().


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

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_dict — Free a dictionary resource
  • enchant_broker_free — Free the broker resource and its dictionnaries
  • 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_to_personal — Add a word to personal word list
  • 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_in_session — Whether or not 'word' exists in this spelling-session
  • 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


Enumerates the Enchant providers

  • « Enchant Functions
  • enchant_broker_dict_exists »
  • PHP Manual
  • Enchant Functions
  • Enumerates the Enchant providers

enchant_broker_describe

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0)

enchant_broker_describe — Enumerates the Enchant providers

Description

enchant_broker_describe ( resource $broker ) : array

Enumerates the Enchant providers and tells you some rudimentary information about them. The same info is provided through phpinfo().

Parameters

broker

Broker resource

Return Values

Returns TRUE on success or 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
        )

)


Whether a dictionary exists or not. Using non-empty tag

  • « enchant_broker_describe
  • enchant_broker_free_dict »
  • PHP Manual
  • Enchant Functions
  • Whether a dictionary exists or not. Using non-empty tag

enchant_broker_dict_exists

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_broker_dict_exists — Whether a dictionary exists or not. Using non-empty tag

Description

enchant_broker_dict_exists ( resource $broker , string $tag ) : bool

Tells if a dictionary exists or not, using a non-empty tags

Parameters

broker

Broker resource

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.

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


Free a dictionary resource

  • « enchant_broker_dict_exists
  • enchant_broker_free »
  • PHP Manual
  • Enchant Functions
  • Free a dictionary resource

enchant_broker_free_dict

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_broker_free_dict — Free a dictionary resource

Description

enchant_broker_free_dict ( resource $dict ) : bool

Free a dictionary resource.

Parameters

dict

Dictionary resource.

Return Values

Returns TRUE on success or FALSE on failure.

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


Free the broker resource and its dictionnaries

  • « enchant_broker_free_dict
  • enchant_broker_get_dict_path »
  • PHP Manual
  • Enchant Functions
  • Free the broker resource and its dictionnaries

enchant_broker_free

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_broker_free — Free the broker resource and its dictionnaries

Description

enchant_broker_free ( resource $broker ) : bool

Free a broker resource with all its dictionaries.

Parameters

broker

Broker resource

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • enchant_broker_init() - Create a new broker object capable of requesting


Get the directory path for a given backend

  • « enchant_broker_free
  • enchant_broker_get_error »
  • PHP Manual
  • Enchant Functions
  • Get the directory path for a given backend

enchant_broker_get_dict_path

(PHP 5 >= 5.3.1, PHP 7, PECL enchant >= 1.0.1)

enchant_broker_get_dict_path — Get the directory path for a given backend

Description

enchant_broker_get_dict_path ( resource $broker , int $dict_type ) : bool

Get the directory path for a given backend.

Parameters

broker

Broker resource.

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

See Also

  • enchant_broker_set_dict_path() - Set the directory path for a given backend


Returns the last error of the broker

  • « enchant_broker_get_dict_path
  • enchant_broker_init »
  • PHP Manual
  • Enchant Functions
  • Returns the last error of the broker

enchant_broker_get_error

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_broker_get_error — Returns the last error of the broker

Description

enchant_broker_get_error ( resource $broker ) : string

Returns the last error which occurred in this broker.

Parameters

broker

Broker resource.

Return Values

Return the msg string if an error was found or FALSE


Create a new broker object capable of requesting

  • « enchant_broker_get_error
  • enchant_broker_list_dicts »
  • PHP Manual
  • Enchant Functions
  • Create a new broker object capable of requesting

enchant_broker_init

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_broker_init — Create a new broker object capable of requesting

Description

enchant_broker_init ( void ) : resource

Parameters

Return Values

Returns a broker resource on success or FALSE.

See Also

  • enchant_broker_free() - Free the broker resource and its dictionnaries


Returns a list of available dictionaries

  • « enchant_broker_init
  • enchant_broker_request_dict »
  • PHP Manual
  • Enchant Functions
  • Returns a list of available dictionaries

enchant_broker_list_dicts

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 1.0.1)

enchant_broker_list_dicts — Returns a list of available dictionaries

Description

enchant_broker_list_dicts ( resource $broker ) : mixed

Returns a list of available dictionaries with their details.

Parameters

broker

Broker resource

Return Values

Returns TRUE on success or 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


Create a new dictionary using a tag

  • « enchant_broker_list_dicts
  • enchant_broker_request_pwl_dict »
  • PHP Manual
  • Enchant Functions
  • Create a new dictionary using a tag

enchant_broker_request_dict

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_broker_request_dict — Create a new dictionary using a tag

Description

enchant_broker_request_dict ( resource $broker , string $tag ) : resource

create a new dictionary using tag, the non-empty language tag you wish to request a dictionary for ("en_US", "de_DE", ...)

Parameters

broker

Broker resource

tag

A tag describing the locale, for example en_US, de_DE

Return Values

Returns a dictionary resource on success or FALSE on failure.

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($r, $tag);
}
?>

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


Creates a dictionary using a PWL file

  • « enchant_broker_request_dict
  • enchant_broker_set_dict_path »
  • PHP Manual
  • Enchant Functions
  • Creates a dictionary using a PWL file

enchant_broker_request_pwl_dict

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_broker_request_pwl_dict — Creates a dictionary using a PWL file

Description

enchant_broker_request_pwl_dict ( resource $broker , string $filename ) : resource

Creates a dictionary using a PWL file. A PWL file is personal word file one word per line.

Parameters

broker

Broker resource

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.

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


Set the directory path for a given backend

  • « enchant_broker_request_pwl_dict
  • enchant_broker_set_ordering »
  • PHP Manual
  • Enchant Functions
  • Set the directory path for a given backend

enchant_broker_set_dict_path

(PHP 5 >= 5.3.1, PHP 7, PECL enchant >= 1.0.1)

enchant_broker_set_dict_path — Set the directory path for a given backend

Description

enchant_broker_set_dict_path ( resource $broker , int $dict_type , string $value ) : bool

Set the directory path for a given backend.

Parameters

broker

Broker resource.

dict_type

The type of the dictionaries, i.e. ENCHANT_MYSPELL or ENCHANT_ISPELL.

value

The path of the dictionary directory.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • enchant_broker_get_dict_path() - Get the directory path for a given backend


Declares a preference of dictionaries to use for the language

  • « enchant_broker_set_dict_path
  • enchant_dict_add_to_personal »
  • PHP Manual
  • Enchant Functions
  • Declares a preference of dictionaries to use for the language

enchant_broker_set_ordering

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_broker_set_ordering — Declares a preference of dictionaries to use for the language

Description

enchant_broker_set_ordering ( resource $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

Broker resource

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.


Add a word to personal word list

  • « enchant_broker_set_ordering
  • enchant_dict_add_to_session »
  • PHP Manual
  • Enchant Functions
  • Add a word to personal word list

enchant_dict_add_to_personal

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_dict_add_to_personal — Add a word to personal word list

Description

enchant_dict_add_to_personal ( resource $dict , string $word ) : void

Add a word to personal word list of the given dictionary.

Parameters

dict

Dictionary resource

word

The word to add

Return Values

Returns TRUE on success or FALSE on failure.

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_to_personal($dict, $word);

enchant_broker_free($broker);

?>

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


Add 'word' to this spell-checking session

  • « enchant_dict_add_to_personal
  • enchant_dict_check »
  • PHP Manual
  • Enchant Functions
  • Add 'word' to this spell-checking session

enchant_dict_add_to_session

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_dict_add_to_session — Add 'word' to this spell-checking session

Description

enchant_dict_add_to_session ( resource $dict , string $word ) : void

Add a word to the given dictionary. It will be added only for the active spell-checking session.

Parameters

dict

Dictionary resource

word

The word to add

Return Values

No value is returned.

See Also

  • enchant_broker_request_dict() - Create a new dictionary using a tag


Check whether a word is correctly spelled or not

  • « enchant_dict_add_to_session
  • enchant_dict_describe »
  • PHP Manual
  • Enchant Functions
  • Check whether a word is correctly spelled or not

enchant_dict_check

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_dict_check — Check whether a word is correctly spelled or not

Description

enchant_dict_check ( resource $dict , string $word ) : bool

If the word is correctly spelled return TRUE, otherwise return FALSE

Parameters

dict

Dictionary resource

word

The word to check

Return Values

Returns TRUE if the word is spelled correctly, FALSE if not.


Describes an individual dictionary

  • « enchant_dict_check
  • enchant_dict_get_error »
  • PHP Manual
  • Enchant Functions
  • Describes an individual dictionary

enchant_dict_describe

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_dict_describe — Describes an individual dictionary

Description

enchant_dict_describe ( resource $dict ) : mixed

Returns the details of the dictionary.

Parameters

dict

Dictionary resource

Return Values

Returns TRUE on success or 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($r, $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
)


Returns the last error of the current spelling-session

  • « enchant_dict_describe
  • enchant_dict_is_in_session »
  • PHP Manual
  • Enchant Functions
  • Returns the last error of the current spelling-session

enchant_dict_get_error

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_dict_get_error — Returns the last error of the current spelling-session

Description

enchant_dict_get_error ( resource $dict ) : string

Returns the last error of the current spelling-session

Parameters

dict

Dictinaray resource

Return Values

Returns the error message as string or FALSE if no error occurred.


Whether or not 'word' exists in this spelling-session

  • « enchant_dict_get_error
  • enchant_dict_quick_check »
  • PHP Manual
  • Enchant Functions
  • Whether or not 'word' exists in this spelling-session

enchant_dict_is_in_session

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_dict_is_in_session — Whether or not 'word' exists in this spelling-session

Description

enchant_dict_is_in_session ( resource $dict , string $word ) : bool

Tells whether or not a word already exists in the current session.

Parameters

dict

Dictionary resource

word

The word to lookup

Return Values

Returns TRUE if the word exists or FALSE

See Also

  • enchant_dict_add_to_session() - Add 'word' to this spell-checking session


Check the word is correctly spelled and provide suggestions

  • « enchant_dict_is_in_session
  • enchant_dict_store_replacement »
  • PHP Manual
  • Enchant Functions
  • Check the word is correctly spelled and provide suggestions

enchant_dict_quick_check

(PHP 5 >= 5.3.0, PHP 7, 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 ( resource $dict , string $word [, array &$suggestions ] ) : bool

If the word is correctly spelled return TRUE, otherwise return FALSE, if suggestions variable is provided, fill it with spelling alternatives.

Parameters

dict

Dictionary resource

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

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


Add a correction for a word

  • « enchant_dict_quick_check
  • enchant_dict_suggest »
  • PHP Manual
  • Enchant Functions
  • Add a correction for a word

enchant_dict_store_replacement

(PHP 5 >= 5.3.0, PHP 7, PECL enchant >= 0.1.0 )

enchant_dict_store_replacement — Add a correction for a word

Description

enchant_dict_store_replacement ( resource $dict , string $mis , string $cor ) : 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

dict

Dictionary resource

mis

The work to fix

cor

The correct word

Return Values

Returns TRUE on success or FALSE on failure.


Will return a list of values if any of those pre-conditions are not met

  • « enchant_dict_store_replacement
  • FriBiDi »
  • PHP Manual
  • Enchant Functions
  • Will return a list of values if any of those pre-conditions are not met

enchant_dict_suggest

(PHP 5 >= 5.3.0, PHP 7, 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 ( resource $dict , string $word ) : array

Parameters

dict

Dictionary resource

word

Word to use for the suggestions.

Return Values

Will returns an array of suggestions if the word is bad spelled.

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);
    }
    enchant_broker_free_dict($d);
}
enchant_broker_free($r);
?>

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


FriBiDi

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • FriBiDi Functions
    • fribidi_log2vis — Convert a logical string to a visual one


Introduction

FriBiDi is a free implementation of the » Unicode Bidirectional Algorithm.


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

You must download and install the » FriBiDi package.


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/fribidi.

In order to use these functions you must compile PHP with Fribidi support by using the --with-fribidi[=DIR] configure option.

Windows users will enable php_fribidi.dll inside of php.ini in order to use these functions. A DLL for this PECL extension is currently unavailable. See also the building on Windows section.


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.

FRIBIDI_CHARSET_UTF8 (integer)
Unicode
FRIBIDI_CHARSET_8859_6 (integer)
Arabic
FRIBIDI_CHARSET_8859_8 (integer)
Hebrew
FRIBIDI_CHARSET_CP1255 (integer)
Hebrew/Yiddish
FRIBIDI_CHARSET_CP1256 (integer)
Arabic
FRIBIDI_CHARSET_ISIRI_3342 (integer)
Persian
FRIBIDI_CHARSET_CAP_RTL (integer)
Used for test purposes, will treat CAPS as non-English letters
FRIBIDI_RTL (integer)
Right to left
FRIBIDI_LTR (integer)
Left to right
FRIBIDI_AUTO (integer)
Autodetect the base direction


FriBiDi Functions

Table of Contents

  • fribidi_log2vis — Convert a logical string to a visual one


Convert a logical string to a visual one

  • « FriBiDi Functions
  • Gender »
  • PHP Manual
  • FriBiDi Functions
  • Convert a logical string to a visual one

fribidi_log2vis

(PHP 4 >= 4.0.4 and PHP 4 <= 4.1.0, PECL fribidi >= 1.0)

fribidi_log2vis — Convert a logical string to a visual one

Description

fribidi_log2vis ( string $str , string $direction , int $charset ) : string

Converts a logical string to a visual one.

Parameters

str

The logical string.

direction

One of FRIBIDI_RTL, FRIBIDI_LTR or FRIBIDI_AUTO.

charset

One of the FRIBIDI_CHARSET_XXX constants.

Return Values

Returns the visual string on success or FALSE on failure.


Determine gender of firstnames

  • Introduction
  • 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


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.


  • « Introduction
  • Installation »
  • PHP Manual
  • Gender
  • Installing/Configuring

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.

A DLL for this PECL extension is available under » http://windows.php.net/downloads/pecl/releases/gender/.


  • « Installation
  • Usage example. »
  • PHP Manual
  • Gender
  • Examples

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

Gender\Gender {
/* Constants */
const integer IS_FEMALE = 70 ;
const integer IS_MOSTLY_FEMALE = 102 ;
const integer IS_MALE = 77 ;
const integer IS_MOSTLY_MALE = 109 ;
const integer IS_UNISEX_NAME = 63 ;
const integer IS_A_COUPLE = 67 ;
const integer NAME_NOT_FOUND = 32 ;
const integer ERROR_IN_NAME = 69 ;
const integer ANY_COUNTRY = 0 ;
const integer BRITAIN = 1 ;
const integer IRELAND = 2 ;
const integer USA = 3 ;
const integer SPAIN = 4 ;
const integer PORTUGAL = 5 ;
const integer ITALY = 6 ;
const integer MALTA = 7 ;
const integer FRANCE = 8 ;
const integer BELGIUM = 9 ;
const integer LUXEMBOURG = 10 ;
const integer NETHERLANDS = 11 ;
const integer GERMANY = 12 ;
const integer EAST_FRISIA = 13 ;
const integer AUSTRIA = 14 ;
const integer SWISS = 15 ;
const integer ICELAND = 16 ;
const integer DENMARK = 17 ;
const integer NORWAY = 18 ;
const integer SWEDEN = 19 ;
const integer FINLAND = 20 ;
const integer ESTONIA = 21 ;
const integer LATVIA = 22 ;
const integer LITHUANIA = 23 ;
const integer POLAND = 24 ;
const integer CZECH_REP = 25 ;
const integer SLOVAKIA = 26 ;
const integer HUNGARY = 27 ;
const integer ROMANIA = 28 ;
const integer BULGARIA = 29 ;
const integer BOSNIA = 30 ;
const integer CROATIA = 31 ;
const integer KOSOVO = 32 ;
const integer MACEDONIA = 33 ;
const integer MONTENEGRO = 34 ;
const integer SERBIA = 35 ;
const integer SLOVENIA = 36 ;
const integer ALBANIA = 37 ;
const integer GREECE = 38 ;
const integer RUSSIA = 39 ;
const integer BELARUS = 40 ;
const integer MOLDOVA = 41 ;
const integer UKRAINE = 42 ;
const integer ARMENIA = 43 ;
const integer AZERBAIJAN = 44 ;
const integer GEORGIA = 45 ;
const integer KAZAKH_UZBEK = 46 ;
const integer TURKEY = 47 ;
const integer ARABIA = 48 ;
const integer ISRAEL = 49 ;
const integer CHINA = 50 ;
const integer INDIA = 51 ;
const integer JAPAN = 52 ;
const integer KOREA = 53 ;
/* Methods */
public connect ( string $dsn ) : bool
public __construct ([ string $dsn ] )
public country ( int $country ) : array
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

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


Connect to an external name dictionary

  • « Gender\Gender
  • Gender\Gender::__construct »
  • PHP Manual
  • Gender\Gender
  • Connect to an external name dictionary

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.


Construct the Gender object

  • « Gender\Gender::connect
  • Gender\Gender::country »
  • PHP Manual
  • Gender\Gender
  • Construct the Gender object

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.

Return Values


Get textual country representation

  • « Gender\Gender::__construct
  • Gender\Gender::get »
  • PHP Manual
  • Gender\Gender
  • Get textual country representation

Gender\Gender::country

(PECL gender >= 0.8.0)

Gender\Gender::country — Get textual country representation

Description

public Gender\Gender::country ( int $country ) : array

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"
}


Get gender of a name

  • « Gender\Gender::country
  • Gender\Gender::isNick »
  • PHP Manual
  • Gender\Gender
  • Get gender of a name

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.


Check if the name0 is an alias of the name1

  • « Gender\Gender::get
  • Gender\Gender::similarNames »
  • PHP Manual
  • Gender\Gender
  • Check if the name0 is an alias of the name1

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.


Get similar names

  • « Gender\Gender::isNick
  • Gettext »
  • PHP Manual
  • Gender\Gender
  • Get similar names

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.


Gettext

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Gettext Functions
    • bind_textdomain_codeset — Specify the character encoding in which the messages from the DOMAIN message catalog will be returned
    • bindtextdomain — Sets 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


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.


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.


  • « Resource Types
  • Gettext Functions »
  • PHP Manual
  • Gettext
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


Gettext Functions

Table of Contents

  • bind_textdomain_codeset — Specify the character encoding in which the messages from the DOMAIN message catalog will be returned
  • bindtextdomain — Sets 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


Specify the character encoding in which the messages from the DOMAIN message catalog will be returned

  • « Gettext Functions
  • bindtextdomain »
  • PHP Manual
  • Gettext Functions
  • Specify the character encoding in which the messages from the DOMAIN message catalog will be returned

bind_textdomain_codeset

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

bind_textdomain_codeset — Specify the character encoding in which the messages from the DOMAIN message catalog will be returned

Description

bind_textdomain_codeset ( string $domain , string $codeset ) : string

With bind_textdomain_codeset(), you can set in which encoding will be messages from domain returned by gettext() and similar functions.

Parameters

domain

The domain

codeset

The code set

Return Values

A string on success.


Sets the path for a domain

  • « bind_textdomain_codeset
  • dcgettext »
  • PHP Manual
  • Gettext Functions
  • Sets the path for a domain

bindtextdomain

(PHP 4, PHP 5, PHP 7)

bindtextdomain — Sets the path for a domain

Description

bindtextdomain ( string $domain , string $directory ) : string

The bindtextdomain() function sets the path for a domain.

Parameters

domain

The domain

directory

The directory path

Return Values

The full pathname for the domain currently being set.

Examples

Example #1 bindtextdomain() example

<?php

$domain = 'myapp';
echo bindtextdomain($domain, '/usr/share/myapp/locale');

?>

The above example will output:

/usr/share/myapp/locale


Overrides the domain for a single lookup

  • « bindtextdomain
  • dcngettext »
  • PHP Manual
  • Gettext Functions
  • Overrides the domain for a single lookup

dcgettext

(PHP 4, PHP 5, PHP 7)

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


Plural version of dcgettext

  • « dcgettext
  • dgettext »
  • PHP Manual
  • Gettext Functions
  • Plural version of dcgettext

dcngettext

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

dcngettext — Plural version of dcgettext

Description

dcngettext ( string $domain , string $msgid1 , string $msgid2 , int $n , int $category ) : string

This function allows you to override the current domain for a single plural message lookup.

Parameters

domain

The domain

msgid1

msgid2

n

category

Return Values

A string on success.

See Also

  • ngettext() - Plural version of gettext


Override the current domain

  • « dcngettext
  • dngettext »
  • PHP Manual
  • Gettext Functions
  • Override the current domain

dgettext

(PHP 4, PHP 5, PHP 7)

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.

See Also

  • gettext() - Lookup a message in the current domain


Plural version of dgettext

  • « dgettext
  • gettext »
  • PHP Manual
  • Gettext Functions
  • Plural version of dgettext

dngettext

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

dngettext — Plural version of dgettext

Description

dngettext ( string $domain , string $msgid1 , string $msgid2 , int $n ) : string

The dngettext() function allows you to override the current domain for a single plural message lookup.

Parameters

domain

The domain

msgid1

msgid2

n

Return Values

A string on success.

See Also

  • ngettext() - Plural version of gettext


Lookup a message in the current domain

  • « dngettext
  • ngettext »
  • PHP Manual
  • Gettext Functions
  • Lookup a message in the current domain

gettext

(PHP 4, PHP 5, PHP 7)

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

  • setlocale() - Set locale information


Plural version of gettext

  • « gettext
  • textdomain »
  • PHP Manual
  • Gettext Functions
  • Plural version of gettext

ngettext

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

ngettext — Plural version of gettext

Description

ngettext ( string $msgid1 , string $msgid2 , int $n ) : string

The plural version of gettext(). Some languages have more than one form for plural messages dependent on the count.

Parameters

msgid1

The singular message ID.

msgid2

The plural message ID.

n

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 msgid1 and msgid2 for count n.

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

?>


Sets the default domain

  • « ngettext
  • iconv »
  • PHP Manual
  • Gettext Functions
  • Sets the default domain

textdomain

(PHP 4, PHP 5, PHP 7)

textdomain — Sets the default domain

Description

textdomain ( string $text_domain = NULL ) : string

This function sets the domain to search within when calls are made to gettext(), usually the named after an application.

Parameters

text_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.


iconv

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • iconv Functions
    • iconv_get_encoding — Retrieve internal configuration variables of iconv extension
    • iconv_mime_decode_headers — Decodes multiple MIME header fields at once
    • iconv_mime_decode — Decodes a MIME header field
    • 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
    • iconv — Convert string to requested character encoding
    • ob_iconv_handler — Convert character encoding as output buffer handler


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.


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 | "" | PHP_INI_ALL | Deprecated in PHP 5.6.0.
iconv.output_encoding | "" | PHP_INI_ALL | Deprecated in PHP 5.6.0.
iconv.internal_encoding | "" | PHP_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 default_charset 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 default_charset 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 | The implementation name
ICONV_VERSION | 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 | integer | A bitmask used for iconv_mime_decode()
ICONV_MIME_DECODE_CONTINUE_ON_ERROR | integer | A bitmask used for iconv_mime_decode()


iconv Functions

See Also

See also GNU Recode functions.

Table of Contents

  • iconv_get_encoding — Retrieve internal configuration variables of iconv extension
  • iconv_mime_decode_headers — Decodes multiple MIME header fields at once
  • iconv_mime_decode — Decodes a MIME header field
  • 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
  • iconv — Convert string to requested character encoding
  • ob_iconv_handler — Convert character encoding as output buffer handler


Retrieve internal configuration variables of iconv extension

  • « iconv Functions
  • iconv_mime_decode_headers »
  • PHP Manual
  • iconv Functions
  • Retrieve internal configuration variables of iconv extension

iconv_get_encoding

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

iconv_get_encoding — Retrieve internal configuration variables of iconv extension

Description

iconv_get_encoding ([ string $type = "all" ] ) : mixed

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


Decodes multiple MIME header fields at once

  • « iconv_get_encoding
  • iconv_mime_decode »
  • PHP Manual
  • iconv Functions
  • Decodes multiple MIME header fields at once

iconv_mime_decode_headers

(PHP 5, PHP 7)

iconv_mime_decode_headers — Decodes multiple MIME header fields at once

Description

iconv_mime_decode_headers ( string $encoded_headers [, int $mode = 0 [, string $charset = ini_get("iconv.internal_encoding") ]] ) : array

Decodes multiple MIME header fields at once.

Parameters

encoded_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.

charset

The optional charset parameter specifies the character set to represent the result by. If omitted, iconv.internal_encoding will be used.

Return Values

Returns an associative array that holds a whole set of MIME header fields specified by encoded_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.

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


Decodes a MIME header field

  • « iconv_mime_decode_headers
  • iconv_mime_encode »
  • PHP Manual
  • iconv Functions
  • Decodes a MIME header field

iconv_mime_decode

(PHP 5, PHP 7)

iconv_mime_decode — Decodes a MIME header field

Description

iconv_mime_decode ( string $encoded_header [, int $mode = 0 [, string $charset = ini_get("iconv.internal_encoding") ]] ) : string

Decodes a MIME header field.

Parameters

encoded_header

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.

charset

The optional charset parameter specifies the character set to represent the result by. If omitted, iconv.internal_encoding will be used.

Return Values

Returns a decoded MIME field on success, or FALSE if an error occurs during the decoding.

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


Composes a MIME header field

  • « iconv_mime_decode
  • iconv_set_encoding »
  • PHP Manual
  • iconv Functions
  • Composes a MIME header field

iconv_mime_encode

(PHP 5, PHP 7)

iconv_mime_encode — Composes a MIME header field

Description

iconv_mime_encode ( string $field_name , string $field_value [, array $preferences = NULL ] ) : string

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.

preferences

You can control the behaviour of iconv_mime_encode() by specifying an associative array that contains configuration items to the optional third parameter preferences. 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 | integer | 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


Set current setting for character encoding conversion

  • « iconv_mime_encode
  • iconv_strlen »
  • PHP Manual
  • iconv Functions
  • Set current setting for character encoding conversion

iconv_set_encoding

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

iconv_set_encoding — Set current setting for character encoding conversion

Description

iconv_set_encoding ( string $type , string $charset ) : bool

Changes the value of the internal configuration variable specified by type to charset.

Parameters

type

The value of type can be any one of these:

  • input_encoding
  • output_encoding
  • internal_encoding

charset

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


Returns the character count of string

  • « iconv_set_encoding
  • iconv_strpos »
  • PHP Manual
  • iconv Functions
  • Returns the character count of string

iconv_strlen

(PHP 5, PHP 7)

iconv_strlen — Returns the character count of string

Description

iconv_strlen ( string $str [, string $charset = ini_get("iconv.internal_encoding") ] ) : int

In contrast to strlen(), iconv_strlen() counts the occurrences of characters in the given byte sequence str on the basis of the specified character set, the result of which is not necessarily identical to the length of the string in byte.

Parameters

str

The string.

charset

If charset parameter is omitted, str is assumed to be encoded in iconv.internal_encoding.

Return Values

Returns the character count of str, as an integer.

See Also

  • grapheme_strlen() - Get string length in grapheme units
  • mb_strlen() - Get string length
  • strlen() - Get string length


Finds position of first occurrence of a needle within a haystack

  • « iconv_strlen
  • iconv_strrpos »
  • PHP Manual
  • iconv Functions
  • Finds position of first occurrence of a needle within a haystack

iconv_strpos

(PHP 5, PHP 7)

iconv_strpos — Finds position of first occurrence of a needle within a haystack

Description

iconv_strpos ( string $haystack , string $needle [, int $offset = 0 [, string $charset = ini_get("iconv.internal_encoding") ]] ) : int

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 charset.

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.

charset

If charset parameter is omitted, 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
7.1.0 | Support for negative offsets 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


Finds the last occurrence of a needle within a haystack

  • « iconv_strpos
  • iconv_substr »
  • PHP Manual
  • iconv Functions
  • Finds the last occurrence of a needle within a haystack

iconv_strrpos

(PHP 5, PHP 7)

iconv_strrpos — Finds the last occurrence of a needle within a haystack

Description

iconv_strrpos ( string $haystack , string $needle [, string $charset = ini_get("iconv.internal_encoding") ] ) : int

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 charset.

Parameters

haystack

The entire string.

needle

The searched substring.

charset

If charset parameter is omitted, 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.

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


Cut out part of a string

  • « iconv_strrpos
  • iconv »
  • PHP Manual
  • iconv Functions
  • Cut out part of a string

iconv_substr

(PHP 5, PHP 7)

iconv_substr — Cut out part of a string

Description

iconv_substr ( string $str , int $offset [, int $length = iconv_strlen($str, $charset) [, string $charset = ini_get("iconv.internal_encoding") ]] ) : string

Cuts a portion of str specified by the offset and length parameters.

Parameters

str

The original string.

offset

If offset is non-negative, iconv_substr() cuts the portion out of str 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 str.

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 str 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.

charset

If charset parameter is omitted, 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 charset, whilst the counterpart substr() always takes these for byte offsets.

Return Values

Returns the portion of str specified by the offset and length parameters.

If str is shorter than offset characters long, FALSE will be returned. If str is exactly offset characters long, an empty string will be returned.

Changelog

Version | Description
7.0.11 | If str 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


Convert string to requested character encoding

  • « iconv_substr
  • ob_iconv_handler »
  • PHP Manual
  • iconv Functions
  • Convert string to requested character encoding

iconv

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

iconv — Convert string to requested character encoding

Description

iconv ( string $in_charset , string $out_charset , string $str ) : string

Performs a character set conversion on the string str from in_charset to out_charset.

Parameters

in_charset

The input charset.

out_charset

The output charset.

If you append the string //TRANSLIT to out_charset transliteration is activated. This means that when a character can't be represented in the target charset, it can be approximated through one or several similarly looking characters. If you append the string //IGNORE, 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 out_charset.

str

The string to be converted.

Return Values

Returns the converted string or FALSE on failure.

Changelog

Version | Description
5.4.0 | Since this version, the function returns FALSE on illegal characters, unless //IGNORE is specified in output charset. Before, it returned partial output string.

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


Convert character encoding as output buffer handler

  • « iconv
  • intl »
  • PHP Manual
  • iconv Functions
  • Convert character encoding as output buffer handler

ob_iconv_handler

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

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


Internationalization Functions

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • 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::sortWithSortKeys — Sort array using specified collator and sort keys
    • Collator::sort — Sort array using specified collator
  • NumberFormatter — The NumberFormatter class
    • NumberFormatter::create — Create a number formatter
    • NumberFormatter::formatCurrency — Format a currency value
    • NumberFormatter::format — Format a number
    • 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::parseCurrency — Parse a currency number
    • NumberFormatter::parse — Parse a 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::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::formatMessage — Quick format message
    • MessageFormatter::format — Format the 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::parseMessage — Quick parse input string
    • MessageFormatter::parse — Parse input string according to pattern
    • 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::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::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::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::setTimeZoneId — Sets the time zone to use
    • 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::getErrorCode — Get bundle's last error code
    • ResourceBundle::getErrorMessage — Get bundle's last error message
    • ResourceBundle::get — Get data from the bundle
    • 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
  • 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
  • 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 convertor 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 string from one charset 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_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


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


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.

This extension is bundled with PHP as of PHP version 5.3.0. Alternatively, the PECL version of this extension may be used with all PHP versions greater than 5.2.0 (5.2.4+ recommended).


Installation

This extension may be installed using the bundled version as of PHP 5.3.0, or as a PECL extension as of PHP 5.2.0. In other words, there are two methods to install the intl extension.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: » https://pecl.php.net/package/intl.

Alternatively, --enable-intl will enable the bundled version 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 |  | PHP_INI_ALL |
intl.error_level | 0 | PHP_INI_ALL |
intl.use_exceptions | 0 | PHP_INI_ALL | Available since PHP 5.5 and 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 » http://demo.icu-project.org/icu-bin/locexp.

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 integer

The level 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. Choosing E_ERROR will terminate the script whenever an error condition is found on intl classes.

The default value is 0.

intl.use_exceptions integer

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_MAX_LOCALE_LEN (integer)
Limit on locale length, set to 80 in PHP code. Locale names longer than this limit will not be accepted.
IDNA_DEFAULT (integer)
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 (integer)
Allow processing of unassigned codepoints in the input for IDN functions.
IDNA_USE_STD3_RULES (integer)
Check if the input for IDN functions conforms to domain name ASCII rules.
IDNA_CHECK_BIDI (integer)
Check whether the input conforms to the BiDi rules. Ignored by the IDNA2003 implementation, which always performs this check.
IDNA_CHECK_CONTEXTJ (integer)
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 (integer)
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 (integer)
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 (integer)
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 (integer)
Use UTS #46 algorithm in idn_to_utf8() and idn_to_ascii(). Available as of ICU 4.6.
IDNA_ERROR_EMPTY_LABEL (integer)
IDNA_ERROR_LABEL_TOO_LONG (integer)
IDNA_ERROR_DOMAIN_NAME_TOO_LONG (integer)
IDNA_ERROR_LEADING_HYPHEN (integer)
IDNA_ERROR_TRAILING_HYPHEN (integer)
IDNA_ERROR_HYPHEN_3_4 (integer)
IDNA_ERROR_LEADING_COMBINING_MARK (integer)
IDNA_ERROR_DISALLOWED (integer)
IDNA_ERROR_PUNYCODE (integer)
IDNA_ERROR_LABEL_HAS_DOT (integer)
IDNA_ERROR_INVALID_ACE_LABEL (integer)
IDNA_ERROR_BIDI (integer)
IDNA_ERROR_CONTEXTJ (integer)
Errors reported in a bitset returned by the UTS #46 algorithm in idn_to_utf8() and idn_to_ascii().


  • « Predefined Constants
  • Basic usage of this extension »
  • PHP Manual
  • intl
  • Examples

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, PECL intl >= 1.0.0)

Introduction

Provides string comparison capability with support for appropriate locale-sensitive sort orderings.

Class synopsis

Collator {
/* Methods */
public __construct ( string $locale )
public asort ( array &$arr [, int $sort_flag ] ) : bool
public compare ( string $str1 , string $str2 ) : int
public static create ( string $locale ) : Collator
public getAttribute ( int $attr ) : int
public getErrorCode ( void ) : int
public getErrorMessage ( void ) : string
public getLocale ( int $type ) : string
public getSortKey ( string $str ) : string
public getStrength ( void ) : int
public setAttribute ( int $attr , int $val ) : bool
public setStrength ( int $strength ) : bool
public sortWithSortKeys ( array &$arr ) : bool
public sort ( array &$arr [, int $sort_flag ] ) : bool
}

Predefined Constants

Collator::FRENCH_COLLATION (integer)

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 (integer)

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 (integer)

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 (integer)

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 (integer)

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 (integer)

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 (integer)

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 (integer)

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 (integer)
Collator::PRIMARY (integer)
Collator::SECONDARY (integer)
Collator::TERTIARY (integer)
Collator::DEFAULT_STRENGTH (integer)
Collator::QUATERNARY (integer)
Collator::IDENTICAL (integer)
Collator::OFF (integer)
Collator::ON (integer)
Collator::SHIFTED (integer)
Collator::NON_IGNORABLE (integer)
Collator::LOWER_FIRST (integer)
Collator::UPPER_FIRST (integer)

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::sortWithSortKeys — Sort array using specified collator and sort keys
  • Collator::sort — Sort array using specified collator


Sort array maintaining index association

  • « Collator
  • Collator::compare »
  • PHP Manual
  • Collator
  • Sort array maintaining index association

Collator::asort

collator_asort

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

Collator::asort -- collator_asort — Sort array maintaining index association

Description

Object oriented style

public Collator::asort ( array &$arr [, int $sort_flag ] ) : bool

Procedural style

collator_asort ( Collator $coll , array &$arr [, int $sort_flag ] ) : 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

coll

Collator object.

arr

Array of strings to sort.

sort_flag

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 $sort_flag value is Collator::SORT_REGULAR. It is also used if an invalid $sort_flag 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


Compare two Unicode strings

  • « Collator::asort
  • Collator::__construct »
  • PHP Manual
  • Collator
  • Compare two Unicode strings

Collator::compare

collator_compare

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

Collator::compare -- collator_compare — Compare two Unicode strings

Description

Object oriented style

public Collator::compare ( string $str1 , string $str2 ) : int

Procedural style

collator_compare ( Collator $coll , string $str1 , string $str2 ) : int

Compare two Unicode strings according to collation rules.

Parameters

coll

Collator object.

str1

The first string to compare.

str2

The second string to compare.

Return Values

Return comparison result:

  • 1 if str1 is greater than str2 ;

  • 0 if str1 is equal to str2;

  • -1 if str1 is less than str2 .

On error boolean FALSE is returned.

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

See Also

  • collator_sort() - Sort array using specified collator


Create a collator

  • « Collator::compare
  • Collator::create »
  • PHP Manual
  • Collator
  • Create a collator

Collator::__construct

(PHP 5 >= 5.3.0, PHP 7, 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 null 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.

Return Values

Returns Collator instance.

Errors/Exceptions

Returns an "empty" object on error. You can 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


Create a collator

  • « Collator::__construct
  • Collator::getAttribute »
  • PHP Manual
  • Collator
  • Create a collator

Collator::create

collator_create

(PHP 5 >= 5.3.0, PHP 7, 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 null is passed for the locale, the default locale collation rules will be used. If empty string ("") or "root" are 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


Get collation attribute value

  • « Collator::create
  • Collator::getErrorCode »
  • PHP Manual
  • Collator
  • Get collation attribute value

Collator::getAttribute

collator_get_attribute

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

Collator::getAttribute -- collator_get_attribute — Get collation attribute value

Description

Object oriented style

public Collator::getAttribute ( int $attr ) : int

Procedural style

collator_get_attribute ( Collator $coll , int $attr ) : int

Get a value of an integer collator attribute.

Parameters

coll

Collator object.

attr

Attribute to get value for.

Return Values

Attribute value, or boolean FALSE on error.

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


Get collator's last error code

  • « Collator::getAttribute
  • Collator::getErrorMessage »
  • PHP Manual
  • Collator
  • Get collator's last error code

Collator::getErrorCode

collator_get_error_code

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

Collator::getErrorCode -- collator_get_error_code — Get collator's last error code

Description

Object oriented style

public Collator::getErrorCode ( void ) : int

Procedural style

collator_get_error_code ( Collator $coll ) : int

Parameters

coll

Collator object.

Return Values

Error code returned by the last Collator API function call.

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


Get text for collator's last error code

  • « Collator::getErrorCode
  • Collator::getLocale »
  • PHP Manual
  • Collator
  • Get text for collator's last error code

Collator::getErrorMessage

collator_get_error_message

(PHP 5 >= 5.3.0, PHP 7, 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 ( void ) : string

Procedural style

collator_get_error_message ( Collator $coll ) : string

Retrieves the message for the last error.

Parameters

coll

Collator object.

Return Values

Description of an error occurred in the last Collator API function call.

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


Get the locale name of the collator

  • « Collator::getErrorMessage
  • Collator::getSortKey »
  • PHP Manual
  • Collator
  • Get the locale name of the collator

Collator::getLocale

collator_get_locale

(PHP 5 >= 5.3.0, PHP 7, 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

Procedural style

collator_get_locale ( Collator $coll , int $type ) : string

Get collector locale name.

Parameters

coll

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 boolean 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


Get sorting key for a string

  • « Collator::getLocale
  • Collator::getStrength »
  • PHP Manual
  • Collator
  • Get sorting key for a string

Collator::getSortKey

collator_get_sort_key

(PHP 5 >= 5.3.11, PHP 7, 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 $str ) : string

Procedural style

collator_get_sort_key ( Collator $coll , string $str ) : string

Return collation key for a string.

Parameters

coll

Collator object.

str

The string to produce the key from.

Return Values

Returns the collation key for the string. Collation keys can be compared directly instead of strings.

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 urlencode($res);
?>

The above example will output:

71%3F%3FE%01%09%01%8F%08%00

See Also

  • collator_sort() - Sort array using specified collator
  • collator_sort_with_sort_keys() - Sort array using specified collator and sort keys


Get current collation strength

  • « Collator::getSortKey
  • Collator::setAttribute »
  • PHP Manual
  • Collator
  • Get current collation strength

Collator::getStrength

collator_get_strength

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

Collator::getStrength -- collator_get_strength — Get current collation strength

Description

Object oriented style

public Collator::getStrength ( void ) : int

Procedural style

collator_get_strength ( Collator $coll ) : int

Parameters

coll

Collator object.

Return Values

Returns current collation strength, or boolean FALSE on error.

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


Set collation attribute

  • « Collator::getStrength
  • Collator::setStrength »
  • PHP Manual
  • Collator
  • Set collation attribute

Collator::setAttribute

collator_set_attribute

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

Collator::setAttribute -- collator_set_attribute — Set collation attribute

Description

Object oriented style

public Collator::setAttribute ( int $attr , int $val ) : bool

Procedural style

collator_set_attribute ( Collator $coll , int $attr , int $val ) : bool

Parameters

coll

Collator object.

attr

Attribute.

val

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' );
$val  = collator_get_attribute( $coll, Collator::NUMERIC_COLLATION );
if ($val === false) {
    // Handle error.
} elseif ($val === Collator::ON) {
    // Do something useful.
}
?>

See Also

  • Collator constants
  • collator_get_attribute() - Get collation attribute value
  • collator_set_strength() - Set collation strength


Set collation strength

  • « Collator::setAttribute
  • Collator::sortWithSortKeys »
  • PHP Manual
  • Collator
  • Set collation strength

Collator::setStrength

collator_set_strength

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

Collator::setStrength -- collator_set_strength — Set collation strength

Description

Object oriented style

public Collator::setStrength ( int $strength ) : bool

Procedural style

collator_set_strength ( Collator $coll , int $strength ) : bool

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 level1 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 level2 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 level3 strength.

  4. Quaternary Level: When punctuation is ignored (see Ignoring Punctuations ) at level 13, 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 level4 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 14. 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

coll

Collator object.

strength

Strength to set.

Possible values are:

  • Collator::PRIMARY

  • Collator::SECONDARY

  • Collator::TERTIARY

  • Collator::QUATERNARY

  • Collator::IDENTICAL

  • Collator::DEFAULT_STRENGTH

Return Values

Returns TRUE on success or FALSE on failure.

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


Sort array using specified collator and sort keys

  • « Collator::setStrength
  • Collator::sort »
  • PHP Manual
  • Collator
  • Sort array using specified collator and sort keys

Collator::sortWithSortKeys

collator_sort_with_sort_keys

(PHP 5 >= 5.3.0, PHP 7, 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 &$arr ) : bool

Procedural style

collator_sort_with_sort_keys ( Collator $coll , array &$arr ) : bool

Similar to collator_sort() but uses ICU sorting keys produced by ucol_getSortKey() to gain more speed on large arrays.

Parameters

coll

Collator object.

arr

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


Sort array using specified collator

  • « Collator::sortWithSortKeys
  • NumberFormatter »
  • PHP Manual
  • Collator
  • Sort array using specified collator

Collator::sort

collator_sort

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

Collator::sort -- collator_sort — Sort array using specified collator

Description

Object oriented style

public Collator::sort ( array &$arr [, int $sort_flag ] ) : bool

Procedural style

collator_sort ( Collator $coll , array &$arr [, int $sort_flag ] ) : bool

This function sorts an array according to current locale rules.

Equivalent to standard PHP sort() .

Parameters

coll

Collator object.

arr

Array of strings to sort.

sort_flag

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 sort_flag 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


The NumberFormatter class

(PHP 5 >= 5.3.0, PHP 7, 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

NumberFormatter {
/* Methods */
public __construct ( string $locale , int $style [, string $pattern ] )
public static create ( string $locale , int $style [, string $pattern ] ) : NumberFormatter
public formatCurrency ( float $value , string $currency ) : string
public format ( number $value [, int $type ] ) : string
public getAttribute ( int $attr ) : int
public getErrorCode ( void ) : int
public getErrorMessage ( void ) : string
public getLocale ([ int $type ] ) : string
public getPattern ( void ) : string
public getSymbol ( int $attr ) : string
public getTextAttribute ( int $attr ) : string
public parseCurrency ( string $value , string &$currency [, int &$position ] ) : float
public parse ( string $value [, int $type [, int &$position ]] ) : mixed
public setAttribute ( int $attr , int $value ) : bool
public setPattern ( string $pattern ) : bool
public setSymbol ( int $attr , string $value ) : bool
public setTextAttribute ( int $attr , string $value ) : bool
}

Predefined Constants

These styles are used by the numfmt_create() to define the type of the formatter.

NumberFormatter::PATTERN_DECIMAL (integer)
Decimal format defined by pattern
NumberFormatter::DECIMAL (integer)
Decimal format
NumberFormatter::CURRENCY (integer)
Currency format
NumberFormatter::PERCENT (integer)
Percent format
NumberFormatter::SCIENTIFIC (integer)
Scientific format
NumberFormatter::SPELLOUT (integer)
Spellout rule-based format
NumberFormatter::ORDINAL (integer)
Ordinal rule-based format
NumberFormatter::DURATION (integer)
Duration rule-based format
NumberFormatter::PATTERN_RULEBASED (integer)
Rule-based format defined by pattern
NumberFormatter::CURRENCY_ACCOUNTING (integer)
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 (integer)
Default format for the locale
NumberFormatter::IGNORE (integer)
Alias for PATTERN_DECIMAL

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 (integer)
Derive the type from variable type
NumberFormatter::TYPE_INT32 (integer)
Format/parse as 32-bit integer
NumberFormatter::TYPE_INT64 (integer)
Format/parse as 64-bit integer
NumberFormatter::TYPE_DOUBLE (integer)
Format/parse as floating point value
NumberFormatter::TYPE_CURRENCY (integer)
Format/parse as currency value

Number format attribute used by numfmt_get_attribute() and numfmt_set_attribute().

NumberFormatter::PARSE_INT_ONLY (integer)
Parse integers only.
NumberFormatter::GROUPING_USED (integer)
Use grouping separator.
NumberFormatter::DECIMAL_ALWAYS_SHOWN (integer)
Always show decimal point.
NumberFormatter::MAX_INTEGER_DIGITS (integer)
Maximum integer digits.
NumberFormatter::MIN_INTEGER_DIGITS (integer)
Minimum integer digits.
NumberFormatter::INTEGER_DIGITS (integer)
Integer digits.
NumberFormatter::MAX_FRACTION_DIGITS (integer)
Maximum fraction digits.
NumberFormatter::MIN_FRACTION_DIGITS (integer)
Minimum fraction digits.
NumberFormatter::FRACTION_DIGITS (integer)
Fraction digits.
NumberFormatter::MULTIPLIER (integer)
Multiplier.
NumberFormatter::GROUPING_SIZE (integer)
Grouping size.
NumberFormatter::ROUNDING_MODE (integer)
Rounding Mode.
NumberFormatter::ROUNDING_INCREMENT (integer)
Rounding increment.
NumberFormatter::FORMAT_WIDTH (integer)
The width to which the output of format() is padded.
NumberFormatter::PADDING_POSITION (integer)
The position at which padding will take place. See pad position constants for possible argument values.
NumberFormatter::SECONDARY_GROUPING_SIZE (integer)
Secondary grouping size.
NumberFormatter::SIGNIFICANT_DIGITS_USED (integer)
Use significant digits.
NumberFormatter::MIN_SIGNIFICANT_DIGITS (integer)
Minimum significant digits.
NumberFormatter::MAX_SIGNIFICANT_DIGITS (integer)
Maximum significant digits.
NumberFormatter::LENIENT_PARSE (integer)
Lenient parse mode used by rule-based formats.

Number format text attribute used by numfmt_get_text_attribute() and numfmt_set_text_attribute().

NumberFormatter::POSITIVE_PREFIX (integer)
Positive prefix.
NumberFormatter::POSITIVE_SUFFIX (integer)
Positive suffix.
NumberFormatter::NEGATIVE_PREFIX (integer)
Negative prefix.
NumberFormatter::NEGATIVE_SUFFIX (integer)
Negative suffix.
NumberFormatter::PADDING_CHARACTER (integer)
The character used to pad to the format width.
NumberFormatter::CURRENCY_CODE (integer)
The ISO currency code.
NumberFormatter::DEFAULT_RULESET (integer)
The default rule set. This is only available with rule-based formatters.
NumberFormatter::PUBLIC_RULESETS (integer)
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).

Number format symbols used by numfmt_get_symbol() and numfmt_set_symbol().

NumberFormatter::DECIMAL_SEPARATOR_SYMBOL (integer)
The decimal separator.
NumberFormatter::GROUPING_SEPARATOR_SYMBOL (integer)
The grouping separator.
NumberFormatter::PATTERN_SEPARATOR_SYMBOL (integer)
The pattern separator.
NumberFormatter::PERCENT_SYMBOL (integer)
The percent sign.
NumberFormatter::ZERO_DIGIT_SYMBOL (integer)
Zero.
NumberFormatter::DIGIT_SYMBOL (integer)
Character representing a digit in the pattern.
NumberFormatter::MINUS_SIGN_SYMBOL (integer)
The minus sign.
NumberFormatter::PLUS_SIGN_SYMBOL (integer)
The plus sign.
NumberFormatter::CURRENCY_SYMBOL (integer)
The currency symbol.
NumberFormatter::INTL_CURRENCY_SYMBOL (integer)
The international currency symbol.
NumberFormatter::MONETARY_SEPARATOR_SYMBOL (integer)
The monetary separator.
NumberFormatter::EXPONENTIAL_SYMBOL (integer)
The exponential symbol.
NumberFormatter::PERMILL_SYMBOL (integer)
Per mill symbol.
NumberFormatter::PAD_ESCAPE_SYMBOL (integer)
Escape padding character.
NumberFormatter::INFINITY_SYMBOL (integer)
Infinity symbol.
NumberFormatter::NAN_SYMBOL (integer)
Not-a-number symbol.
NumberFormatter::SIGNIFICANT_DIGIT_SYMBOL (integer)
Significant digit symbol.
NumberFormatter::MONETARY_GROUPING_SEPARATOR_SYMBOL (integer)
The monetary grouping separator.

Rounding mode values used by numfmt_get_attribute()
and numfmt_set_attribute() with
NumberFormatter::ROUNDING_MODE attribute.

NumberFormatter::ROUND_CEILING (integer)
Rounding mode to round towards positive infinity.
NumberFormatter::ROUND_DOWN (integer)
Rounding mode to round towards zero.
NumberFormatter::ROUND_FLOOR (integer)
Rounding mode to round towards negative infinity.
NumberFormatter::ROUND_HALFDOWN (integer)
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round down.
NumberFormatter::ROUND_HALFEVEN (integer)
Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.
NumberFormatter::ROUND_HALFUP (integer)
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.
NumberFormatter::ROUND_UP (integer)
Rounding mode to round away from zero.

Pad position values used by numfmt_get_attribute()
and numfmt_set_attribute() with
NumberFormatter::PADDING_POSITION attribute.

NumberFormatter::PAD_AFTER_PREFIX (integer)
Pad characters inserted after the prefix.
NumberFormatter::PAD_AFTER_SUFFIX (integer)
Pad characters inserted after the suffix.
NumberFormatter::PAD_BEFORE_PREFIX (integer)
Pad characters inserted before the prefix.
NumberFormatter::PAD_BEFORE_SUFFIX (integer)
Pad characters inserted before the suffix.

See Also

  • » ICU formatting documentation
  • » ICU number formatters
  • » ICU decimal formatters
  • » ICU rule-based number formatters

Table of Contents

  • NumberFormatter::create — Create a number formatter
  • NumberFormatter::formatCurrency — Format a currency value
  • NumberFormatter::format — Format a number
  • 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::parseCurrency — Parse a currency number
  • NumberFormatter::parse — Parse a number
  • NumberFormatter::setAttribute — Set an attribute
  • NumberFormatter::setPattern — Set formatter pattern
  • NumberFormatter::setSymbol — Set a symbol value
  • NumberFormatter::setTextAttribute — Set a text attribute


Create a number formatter

  • « NumberFormatter
  • NumberFormatter::formatCurrency »
  • PHP Manual
  • NumberFormatter
  • Create a number formatter

NumberFormatter::create

numfmt_create

NumberFormatter::__construct

(PHP 5 >= 5.3.0, PHP 7, 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 ] ) : NumberFormatter

Procedural style

numfmt_create ( string $locale , int $style [, string $pattern ] ) : NumberFormatter

Object oriented style (constructor):

public NumberFormatter::__construct ( string $locale , int $style [, string $pattern ] )

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 FALSE on error.

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


Format a currency value

  • « NumberFormatter::create
  • NumberFormatter::format »
  • PHP Manual
  • NumberFormatter
  • Format a currency value

NumberFormatter::formatCurrency

numfmt_format_currency

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

NumberFormatter::formatCurrency -- numfmt_format_currency — Format a currency value

Description

Object oriented style

public NumberFormatter::formatCurrency ( float $value , string $currency ) : string

Procedural style

numfmt_format_currency ( NumberFormatter $fmt , float $value , string $currency ) : string

Format the currency value according to the formatter rules.

Parameters

fmt

NumberFormatter object.

value

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р.

See Also

  • numfmt_get_error_code() - Get formatter's last error code
  • numfmt_format() - Format a number
  • numfmt_parse_currency() - Parse a currency number


Format a number

  • « NumberFormatter::formatCurrency
  • NumberFormatter::getAttribute »
  • PHP Manual
  • NumberFormatter
  • Format a number

NumberFormatter::format

numfmt_format

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

NumberFormatter::format -- numfmt_format — Format a number

Description

Object oriented style

public NumberFormatter::format ( number $value [, int $type ] ) : string

Procedural style

numfmt_format ( NumberFormatter $fmt , number $value [, int $type ] ) : string

Format a numeric value according to the formatter rules.

Parameters

fmt

NumberFormatter object.

value

The value to format. Can be integer or float, other values will be converted to a numeric value.

type

The formatting type to use.

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);
if(intl_is_failure(numfmt_format($fmt))) {
    report_error("Formatter error");
}
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
$fmt->format(1234567.891234567890000);
if(intl_is_failure($fmt->getErrorCode())) {
    report_error("Formatter error");
}
?>

The above example will output:

1.234.567,891

See Also

  • numfmt_get_error_code() - Get formatter's last error code
  • numfmt_format_currency() - Format a currency value
  • numfmt_parse() - Parse a number


Get an attribute

  • « NumberFormatter::format
  • NumberFormatter::getErrorCode »
  • PHP Manual
  • NumberFormatter
  • Get an attribute

NumberFormatter::getAttribute

numfmt_get_attribute

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

NumberFormatter::getAttribute -- numfmt_get_attribute — Get an attribute

Description

Object oriented style

public NumberFormatter::getAttribute ( int $attr ) : int

Procedural style

numfmt_get_attribute ( NumberFormatter $fmt , int $attr ) : int

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

fmt

NumberFormatter object.

attr

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


Get formatter's last error code

  • « NumberFormatter::getAttribute
  • NumberFormatter::getErrorMessage »
  • PHP Manual
  • NumberFormatter
  • Get formatter's last error code

NumberFormatter::getErrorCode

numfmt_get_error_code

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

NumberFormatter::getErrorCode -- numfmt_get_error_code — Get formatter's last error code

Description

Object oriented style

public NumberFormatter::getErrorCode ( void ) : int

Procedural style

numfmt_get_error_code ( NumberFormatter $fmt ) : int

Get error code from the last function performed by the formatter.

Parameters

fmt

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))) {
    report_error("Formatter error");
}
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
$fmt->format(1234567.891234567890000);
if(intl_is_failure($fmt->getErrorCode())) {
    report_error("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


Get formatter's last error message

  • « NumberFormatter::getErrorCode
  • NumberFormatter::getLocale »
  • PHP Manual
  • NumberFormatter
  • Get formatter's last error message

NumberFormatter::getErrorMessage

numfmt_get_error_message

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

NumberFormatter::getErrorMessage -- numfmt_get_error_message — Get formatter's last error message

Description

Object oriented style

public NumberFormatter::getErrorMessage ( void ) : string

Procedural style

numfmt_get_error_message ( NumberFormatter $fmt ) : string

Get error message from the last function performed by the formatter.

Parameters

fmt

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


Get formatter locale

  • « NumberFormatter::getErrorMessage
  • NumberFormatter::getPattern »
  • PHP Manual
  • NumberFormatter
  • Get formatter locale

NumberFormatter::getLocale

numfmt_get_locale

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

NumberFormatter::getLocale -- numfmt_get_locale — Get formatter locale

Description

Object oriented style

public NumberFormatter::getLocale ([ int $type ] ) : string

Procedural style

numfmt_get_locale ( NumberFormatter $fmt [, int $type ] ) : string

Get formatter locale name.

Parameters

fmt

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.

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


Get formatter pattern

  • « NumberFormatter::getLocale
  • NumberFormatter::getSymbol »
  • PHP Manual
  • NumberFormatter
  • Get formatter pattern

NumberFormatter::getPattern

numfmt_get_pattern

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

NumberFormatter::getPattern -- numfmt_get_pattern — Get formatter pattern

Description

Object oriented style

public NumberFormatter::getPattern ( void ) : string

Procedural style

numfmt_get_pattern ( NumberFormatter $fmt ) : string

Extract pattern used by the formatter.

Parameters

fmt

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


Get a symbol value

  • « NumberFormatter::getPattern
  • NumberFormatter::getTextAttribute »
  • PHP Manual
  • NumberFormatter
  • Get a symbol value

NumberFormatter::getSymbol

numfmt_get_symbol

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

NumberFormatter::getSymbol -- numfmt_get_symbol — Get a symbol value

Description

Object oriented style

public NumberFormatter::getSymbol ( int $attr ) : string

Procedural style

numfmt_get_symbol ( NumberFormatter $fmt , int $attr ) : string

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

fmt

NumberFormatter object.

attr

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


Get a text attribute

  • « NumberFormatter::getSymbol
  • NumberFormatter::parseCurrency »
  • PHP Manual
  • NumberFormatter
  • Get a text attribute

NumberFormatter::getTextAttribute

numfmt_get_text_attribute

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

NumberFormatter::getTextAttribute -- numfmt_get_text_attribute — Get a text attribute

Description

Object oriented style

public NumberFormatter::getTextAttribute ( int $attr ) : string

Procedural style

numfmt_get_text_attribute ( NumberFormatter $fmt , int $attr ) : string

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

fmt

NumberFormatter object.

attr

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


Parse a currency number

  • « NumberFormatter::getTextAttribute
  • NumberFormatter::parse »
  • PHP Manual
  • NumberFormatter
  • Parse a currency number

NumberFormatter::parseCurrency

numfmt_parse_currency

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

NumberFormatter::parseCurrency -- numfmt_parse_currency — Parse a currency number

Description

Object oriented style

public NumberFormatter::parseCurrency ( string $value , string &$currency [, int &$position ] ) : float

Procedural style

numfmt_parse_currency ( NumberFormatter $fmt , string $value , string &$currency [, int &$position ] ) : float

Parse a string into a double and a currency using the current formatter.

Parameters

fmt

NumberFormatter object.

currency

Parameter to receive the currency name (3-letter ISO 4217 currency code).

position

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


Parse a number

  • « NumberFormatter::parseCurrency
  • NumberFormatter::setAttribute »
  • PHP Manual
  • NumberFormatter
  • Parse a number

NumberFormatter::parse

numfmt_parse

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

NumberFormatter::parse -- numfmt_parse — Parse a number

Description

Object oriented style

public NumberFormatter::parse ( string $value [, int $type [, int &$position ]] ) : mixed

Procedural style

numfmt_parse ( NumberFormatter $fmt , string $value [, int $type [, int &$position ]] ) : mixed

Parse a string into a number using the current formatter rules.

Parameters

fmt

NumberFormatter object.

type

The formatting type to use. By default, NumberFormatter::TYPE_DOUBLE is used.

position

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


Set an attribute

  • « NumberFormatter::parse
  • NumberFormatter::setPattern »
  • PHP Manual
  • NumberFormatter
  • Set an attribute

NumberFormatter::setAttribute

numfmt_set_attribute

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

NumberFormatter::setAttribute -- numfmt_set_attribute — Set an attribute

Description

Object oriented style

public NumberFormatter::setAttribute ( int $attr , int $value ) : bool

Procedural style

numfmt_set_attribute ( NumberFormatter $fmt , int $attr , int $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

fmt

NumberFormatter object.

attr

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

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


Set formatter pattern

  • « NumberFormatter::setAttribute
  • NumberFormatter::setSymbol »
  • PHP Manual
  • NumberFormatter
  • Set formatter pattern

NumberFormatter::setPattern

numfmt_set_pattern

(PHP 5 >= 5.3.0, PHP 7, 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 $fmt , string $pattern ) : bool

Set the pattern used by the formatter. Can not be used on a rule-based formatter.

Parameters

fmt

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


Set a symbol value

  • « NumberFormatter::setPattern
  • NumberFormatter::setTextAttribute »
  • PHP Manual
  • NumberFormatter
  • Set a symbol value

NumberFormatter::setSymbol

numfmt_set_symbol

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

NumberFormatter::setSymbol -- numfmt_set_symbol — Set a symbol value

Description

Object oriented style

public NumberFormatter::setSymbol ( int $attr , string $value ) : bool

Procedural style

numfmt_set_symbol ( NumberFormatter $fmt , int $attr , 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

fmt

NumberFormatter object.

attr

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


Set a text attribute

  • « NumberFormatter::setSymbol
  • Locale »
  • PHP Manual
  • NumberFormatter
  • Set a text attribute

NumberFormatter::setTextAttribute

numfmt_set_text_attribute

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

NumberFormatter::setTextAttribute -- numfmt_set_text_attribute — Set a text attribute

Description

Object oriented style

public NumberFormatter::setTextAttribute ( int $attr , string $value ) : bool

Procedural style

numfmt_set_text_attribute ( NumberFormatter $fmt , int $attr , 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

fmt

NumberFormatter object.

attr

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


The Locale class

(PHP 5 >= 5.3.0, PHP 7, 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

Locale {
/* Methods */
public static acceptFromHttp ( string $header ) : string
public static canonicalize ( string $locale ) : string
public static composeLocale ( array $subtags ) : string
public static filterMatches ( string $langtag , string $locale [, bool $canonicalize = FALSE ] ) : bool
public static getAllVariants ( string $locale ) : array
public static getDefault ( void ) : string
public static getDisplayLanguage ( string $locale [, string $in_locale ] ) : string
public static getDisplayName ( string $locale [, string $in_locale ] ) : string
public static getDisplayRegion ( string $locale [, string $in_locale ] ) : string
public static getDisplayScript ( string $locale [, string $in_locale ] ) : string
public static getDisplayVariant ( string $locale [, string $in_locale ] ) : string
public static getKeywords ( string $locale ) : array
public static getPrimaryLanguage ( string $locale ) : string
public static getRegion ( string $locale ) : string
public static getScript ( string $locale ) : string
public static lookup ( array $langtag , string $locale [, bool $canonicalize = FALSE [, string $default ]] ) : string
public static parseLocale ( string $locale ) : array
public static setDefault ( string $locale ) : bool
}

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 (string)
This is locale the data actually comes from.
Locale::VALID_LOCALE (string)
This is the most specific locale supported by ICU.

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

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::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


Tries to find out best available locale based on HTTP "Accept-Language" header

  • « Locale
  • Locale::canonicalize »
  • PHP Manual
  • Locale
  • Tries to find out best available locale based on HTTP "Accept-Language" header

Locale::acceptFromHttp

locale_accept_from_http

(PHP 5 >= 5.3.0, PHP 7, 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

Procedural style

locale_accept_from_http ( string $header ) : string

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.

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


Canonicalize the locale string

  • « Locale::acceptFromHttp
  • Locale::composeLocale »
  • PHP Manual
  • Locale
  • Canonicalize the locale string

Locale::canonicalize

locale_canonicalize

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

Locale::canonicalize -- locale_canonicalize — Canonicalize the locale string

Description

public static Locale::canonicalize ( string $locale ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

locale

Return Values


Returns a correctly ordered and delimited locale ID

  • « Locale::canonicalize
  • Locale::filterMatches »
  • PHP Manual
  • Locale
  • Returns a correctly ordered and delimited locale ID

Locale::composeLocale

locale_compose

(PHP 5 >= 5.3.0, PHP 7, 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

Procedural style

locale_compose ( array $subtags ) : string

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.e.g. 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.

The 'variant', 'private' and 'extlang' multiple values can be specified both as array under specific key (e.g. 'variant') and as multiple numbered keys (e.g. 'variant0', 'variant1', etc.).

Return Values

The corresponding locale identifier.

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

See Also

  • locale_parse() - Returns a key-value array of locale ID subtag elements


Checks if a language tag filter matches with locale

  • « Locale::composeLocale
  • Locale::getAllVariants »
  • PHP Manual
  • Locale
  • Checks if a language tag filter matches with locale

Locale::filterMatches

locale_filter_matches

(PHP 5 >= 5.3.0, PHP 7, 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 $langtag , string $locale [, bool $canonicalize = FALSE ] ) : bool

Procedural style

locale_filter_matches ( string $langtag , string $locale [, bool $canonicalize = FALSE ] ) : bool

Checks if a $langtag filter matches with $locale according to RFC 4647's basic filtering algorithm

Parameters

langtag

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 $langtag FALSE otherwise.

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


Gets the variants for the input locale

  • « Locale::filterMatches
  • Locale::getDefault »
  • PHP Manual
  • Locale
  • Gets the variants for the input locale

Locale::getAllVariants

locale_get_all_variants

(PHP 5 >= 5.3.0, PHP 7, 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

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


Gets the default locale value from the INTL global 'default_locale'

  • « Locale::getAllVariants
  • Locale::getDisplayLanguage »
  • PHP Manual
  • Locale
  • Gets the default locale value from the INTL global 'default_locale'

Locale::getDefault

locale_get_default

(PHP 5 >= 5.3.0, PHP 7, 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 ( void ) : string

Procedural style

locale_get_default ( void ) : 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


Returns an appropriately localized display name for language of the inputlocale

  • « Locale::getDefault
  • Locale::getDisplayName »
  • PHP Manual
  • Locale
  • Returns an appropriately localized display name for language of the inputlocale

Locale::getDisplayLanguage

locale_get_display_language

(PHP 5 >= 5.3.0, PHP 7, 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 $in_locale ] ) : string

Procedural style

locale_get_display_language ( string $locale [, string $in_locale ] ) : string

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

in_locale

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 $in_locale.

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


Returns an appropriately localized display name for the input locale

  • « Locale::getDisplayLanguage
  • Locale::getDisplayRegion »
  • PHP Manual
  • Locale
  • Returns an appropriately localized display name for the input locale

Locale::getDisplayName

locale_get_display_name

(PHP 5 >= 5.3.0, PHP 7, 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 $in_locale ] ) : string

Procedural style

locale_get_display_name ( string $locale [, string $in_locale ] ) : string

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.

in_locale

optional format locale

Return Values

Display name of the locale in the format appropriate for $in_locale.

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


Returns an appropriately localized display name for region of the input locale

  • « Locale::getDisplayName
  • Locale::getDisplayScript »
  • PHP Manual
  • Locale
  • Returns an appropriately localized display name for region of the input locale

Locale::getDisplayRegion

locale_get_display_region

(PHP 5 >= 5.3.0, PHP 7, 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 $in_locale ] ) : string

Procedural style

locale_get_display_region ( string $locale [, string $in_locale ] ) : string

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.

in_locale

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 $in_locale.

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


Returns an appropriately localized display name for script of the input locale

  • « Locale::getDisplayRegion
  • Locale::getDisplayVariant »
  • PHP Manual
  • Locale
  • Returns an appropriately localized display name for script of the input locale

Locale::getDisplayScript

locale_get_display_script

(PHP 5 >= 5.3.0, PHP 7, 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 $in_locale ] ) : string

Procedural style

locale_get_display_script ( string $locale [, string $in_locale ] ) : string

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

in_locale

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 $in_locale.

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


Returns an appropriately localized display name for variants of the input locale

  • « Locale::getDisplayScript
  • Locale::getKeywords »
  • PHP Manual
  • Locale
  • 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, 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 $in_locale ] ) : string

Procedural style

locale_get_display_variant ( string $locale [, string $in_locale ] ) : string

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

in_locale

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 $in_locale.

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


Gets the keywords for the input locale

  • « Locale::getDisplayVariant
  • Locale::getPrimaryLanguage »
  • PHP Manual
  • Locale
  • Gets the keywords for the input locale

Locale::getKeywords

locale_get_keywords

(PHP 5 >= 5.3.0, PHP 7, 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

Procedural style

locale_get_keywords ( string $locale ) : array

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

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


Gets the primary language for the input locale

  • « Locale::getKeywords
  • Locale::getRegion »
  • PHP Manual
  • Locale
  • Gets the primary language for the input locale

Locale::getPrimaryLanguage

locale_get_primary_language

(PHP 5 >= 5.3.0, PHP 7, 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 or NULL in case of error.

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


Gets the region for the input locale

  • « Locale::getPrimaryLanguage
  • Locale::getScript »
  • PHP Manual
  • Locale
  • Gets the region for the input locale

Locale::getRegion

locale_get_region

(PHP 5 >= 5.3.0, PHP 7, 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

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


Gets the script for the input locale

  • « Locale::getRegion
  • Locale::lookup »
  • PHP Manual
  • Locale
  • Gets the script for the input locale

Locale::getScript

locale_get_script

(PHP 5 >= 5.3.0, PHP 7, 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


Searches the language tag list for the best match to the language

  • « Locale::getScript
  • Locale::parseLocale »
  • PHP Manual
  • Locale
  • Searches the language tag list for the best match to the language

Locale::lookup

locale_lookup

(PHP 5 >= 5.3.0, PHP 7, 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 $langtag , string $locale [, bool $canonicalize = FALSE [, string $default ]] ) : string

Procedural style

locale_lookup ( array $langtag , string $locale [, bool $canonicalize = FALSE [, string $default ]] ) : string

Searches the items in langtag for the best match to the language range specified in locale according to RFC 4647's lookup algorithm.

Parameters

langtag

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.

default

The locale to use if no match is found.

Return Values

The closest matching language tag or default value.

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


Returns a key-value array of locale ID subtag elements

  • « Locale::lookup
  • Locale::setDefault »
  • PHP Manual
  • Locale
  • Returns a key-value array of locale ID subtag elements

Locale::parseLocale

locale_parse

(PHP 5 >= 5.3.0, PHP 7, 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


Sets the default runtime locale

  • « Locale::parseLocale
  • Normalizer »
  • PHP Manual
  • Locale
  • Sets the default runtime locale

Locale::setDefault

locale_set_default

(PHP 5 >= 5.3.0, PHP 7, 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 ) : bool

Procedural style

locale_set_default ( string $locale ) : bool

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 on success or FALSE on failure.

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'


The Normalizer class

(PHP 5 >= 5.3.0, PHP 7, 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

Normalizer {
/* Methods */
public static getRawDecomposition ( string $input ) : string
public static isNormalized ( string $input [, int $form = Normalizer::FORM_C ] ) : bool
public static normalize ( string $input [, int $form = Normalizer::FORM_C ] ) : string
}

Predefined Constants

The following constants define the normalization form used by the normalizer:

Normalizer::FORM_C (integer)
Normalization Form C (NFC) - Canonical Decomposition followed by Canonical Composition
Normalizer::FORM_D (integer)
Normalization Form D (NFD) - Canonical Decomposition
Normalizer::FORM_KC (integer)
Normalization Form KC (NFKC) - Compatibility Decomposition, followed by Canonical Composition
Normalizer::FORM_KD (integer)
Normalization Form KD (NFKD) - Compatibility Decomposition
Normalizer::NONE (integer)
No decomposition/composition
Normalizer::OPTION_DEFAULT (integer)
Default normalization options

See Also

  • » Unicode Normalization
  • » Unicode Normalization FAQ
  • » ICU User Guide - Normalization
  • » ICU API Reference - Normalization

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


Gets the Decomposition_Mapping property for the given UTF-8 encoded code point

  • « Normalizer
  • Normalizer::isNormalized »
  • PHP Manual
  • Normalizer
  • Gets the Decomposition_Mapping property for the given UTF-8 encoded code point

Normalizer::getRawDecomposition

normalizer_get_raw_decomposition

(PHP 7 >= 7.3)

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 $input ) : string

Procedural style

normalizer_get_raw_decomposition ( string $input ) : string

Gets the Decomposition_Mapping property, as specified in the Unicode Character Database (UCD), for the given UTF-8 encoded code point.

Parameters

input

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


Checks if the provided string is already in the specified normalization form

  • « Normalizer::getRawDecomposition
  • Normalizer::normalize »
  • PHP Manual
  • Normalizer
  • Checks if the provided string is already in the specified normalization form

Normalizer::isNormalized

normalizer_is_normalized

(PHP 5 >= 5.3.0, PHP 7, 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 $input [, int $form = Normalizer::FORM_C ] ) : bool

Procedural style

normalizer_is_normalized ( string $input [, int $form = Normalizer::FORM_C ] ) : bool

Checks if the provided string is already in the specified normalization form.

Parameters

input

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


Normalizes the input provided and returns the normalized string

  • « Normalizer::isNormalized
  • MessageFormatter »
  • PHP Manual
  • Normalizer
  • Normalizes the input provided and returns the normalized string

Normalizer::normalize

normalizer_normalize

(PHP 5 >= 5.3.0, PHP 7, 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 $input [, int $form = Normalizer::FORM_C ] ) : string

Procedural style

normalizer_normalize ( string $input [, int $form = Normalizer::FORM_C ] ) : string

Normalizes the input provided and returns the normalized string

Parameters

input

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


The MessageFormatter class

(PHP 5 >= 5.3.0, PHP 7, 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

MessageFormatter {
/* Methods */
public __construct ( string $locale , string $pattern )
public static create ( string $locale , string $pattern ) : MessageFormatter
public static formatMessage ( string $locale , string $pattern , array $args ) : string
public format ( array $args ) : string
public getErrorCode ( void ) : int
public getErrorMessage ( void ) : string
public getLocale ( void ) : string
public getPattern ( void ) : string
public static parseMessage ( string $locale , string $pattern , string $source ) : array
public parse ( string $value ) : array
public setPattern ( string $pattern ) : bool
}

See Also

  • » ICU formatting documentation
  • » ICU message formatting description
  • » ICU message formatters
  • » ICU choice formatters

Table of Contents

  • MessageFormatter::create — Constructs a new Message Formatter
  • MessageFormatter::formatMessage — Quick format message
  • MessageFormatter::format — Format the 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::parseMessage — Quick parse input string
  • MessageFormatter::parse — Parse input string according to pattern
  • MessageFormatter::setPattern — Set the pattern used by the formatter


Constructs a new Message Formatter

  • « MessageFormatter
  • MessageFormatter::formatMessage »
  • PHP Manual
  • MessageFormatter
  • Constructs a new Message Formatter

MessageFormatter::create

MessageFormatter::__construct

msgfmt_create

(PHP 5 >= 5.3.0, PHP 7, 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; it is run through » umsg_autoQuoteApostrophe before being interpreted.

Return Values

The formatter object

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


Quick format message

  • « MessageFormatter::create
  • MessageFormatter::format »
  • PHP Manual
  • MessageFormatter
  • Quick format message

MessageFormatter::formatMessage

msgfmt_format_message

(PHP 5 >= 5.3.0, PHP 7, 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 $args ) : string

Procedural style

msgfmt_format_message ( string $locale , string $pattern , array $args ) : string

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 and parameters or state to be kept.

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; it is run through » umsg_autoQuoteApostrophe before being interpreted.

args

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));
?>

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));
?>

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_get_error_code() - Get the error code from last operation
  • msgfmt_get_error_message() - Get the error text from the last operation


Format the message

  • « MessageFormatter::formatMessage
  • MessageFormatter::getErrorCode »
  • PHP Manual
  • MessageFormatter
  • Format the message

MessageFormatter::format

msgfmt_format

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

MessageFormatter::format -- msgfmt_format — Format the message

Description

Object oriented style

public MessageFormatter::format ( array $args ) : string

Procedural style

msgfmt_format ( MessageFormatter $fmt , array $args ) : string

Format the message by substituting the data into the format string according to the locale rules

Parameters

fmt

The message formatter

args

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


Get the error code from last operation

  • « MessageFormatter::format
  • MessageFormatter::getErrorMessage »
  • PHP Manual
  • MessageFormatter
  • Get the error code from last operation

MessageFormatter::getErrorCode

msgfmt_get_error_code

(PHP 5 >= 5.3.0, PHP 7, 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 ( void ) : int

Procedural style

msgfmt_get_error_code ( MessageFormatter $fmt ) : int

Get the error code from last operation.

Parameters

fmt

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


Get the error text from the last operation

  • « MessageFormatter::getErrorCode
  • MessageFormatter::getLocale »
  • PHP Manual
  • MessageFormatter
  • Get the error text from the last operation

MessageFormatter::getErrorMessage

msgfmt_get_error_message

(PHP 5 >= 5.3.0, PHP 7, 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 ( void ) : string

Procedural style

msgfmt_get_error_message ( MessageFormatter $fmt ) : string

Get the error text from the last operation.

Parameters

fmt

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


Get the locale for which the formatter was created

  • « MessageFormatter::getErrorMessage
  • MessageFormatter::getPattern »
  • PHP Manual
  • MessageFormatter
  • Get the locale for which the formatter was created

MessageFormatter::getLocale

msgfmt_get_locale

(PHP 5 >= 5.3.0, PHP 7, 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 ( void ) : string

Procedural style

msgfmt_get_locale ( NumberFormatter $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


Get the pattern used by the formatter

  • « MessageFormatter::getLocale
  • MessageFormatter::parseMessage »
  • PHP Manual
  • MessageFormatter
  • Get the pattern used by the formatter

MessageFormatter::getPattern

msgfmt_get_pattern

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

MessageFormatter::getPattern -- msgfmt_get_pattern — Get the pattern used by the formatter

Description

Object oriented style

public MessageFormatter::getPattern ( void ) : string

Procedural style

msgfmt_get_pattern ( MessageFormatter $fmt ) : string

Get the pattern used by the formatter

Parameters

fmt

The message formatter

Return Values

The pattern string for this message formatter

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


Quick parse input string

  • « MessageFormatter::getPattern
  • MessageFormatter::parse »
  • PHP Manual
  • MessageFormatter
  • Quick parse input string

MessageFormatter::parseMessage

msgfmt_parse_message

(PHP 5 >= 5.3.0, PHP 7, 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 $source ) : array

Procedural style

msgfmt_parse_message ( string $locale , string $pattern , string $value ) : array

Parses input string without explicitly creating the formatter object. Use this function when the format operation is done only once and does not need and 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 value.

source

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


Parse input string according to pattern

  • « MessageFormatter::parseMessage
  • MessageFormatter::setPattern »
  • PHP Manual
  • MessageFormatter
  • Parse input string according to pattern

MessageFormatter::parse

msgfmt_parse

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

MessageFormatter::parse -- msgfmt_parse — Parse input string according to pattern

Description

Object oriented style

public MessageFormatter::parse ( string $value ) : array

Procedural style

msgfmt_parse ( MessageFormatter $fmt , string $value ) : array

Parses input string and return any extracted items as an array.

Parameters

fmt

The message formatter

value

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


Set the pattern used by the formatter

  • « MessageFormatter::parse
  • IntlCalendar »
  • PHP Manual
  • MessageFormatter
  • Set the pattern used by the formatter

MessageFormatter::setPattern

msgfmt_set_pattern

(PHP 5 >= 5.3.0, PHP 7, 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 $fmt , string $pattern ) : bool

Set the pattern used by the formatter

Parameters

fmt

The message formatter

pattern

The pattern string to use in this message formatter. The pattern uses an 'apostrophe-friendly' syntax; it is run through » umsg_autoQuoteApostrophe before being interpreted.

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


The IntlCalendar class

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

Introduction

Class synopsis

IntlCalendar {
/* Constants */
const integer FIELD_ERA = 0 ;
const integer FIELD_YEAR = 1 ;
const integer FIELD_MONTH = 2 ;
const integer FIELD_WEEK_OF_YEAR = 3 ;
const integer FIELD_WEEK_OF_MONTH = 4 ;
const integer FIELD_DATE = 5 ;
const integer FIELD_DAY_OF_YEAR = 6 ;
const integer FIELD_DAY_OF_WEEK = 7 ;
const integer FIELD_DAY_OF_WEEK_IN_MONTH = 8 ;
const integer FIELD_AM_PM = 9 ;
const integer FIELD_HOUR = 10 ;
const integer FIELD_HOUR_OF_DAY = 11 ;
const integer FIELD_MINUTE = 12 ;
const integer FIELD_SECOND = 13 ;
const integer FIELD_MILLISECOND = 14 ;
const integer FIELD_ZONE_OFFSET = 15 ;
const integer FIELD_DST_OFFSET = 16 ;
const integer FIELD_YEAR_WOY = 17 ;
const integer FIELD_DOW_LOCAL = 18 ;
const integer FIELD_EXTENDED_YEAR = 19 ;
const integer FIELD_JULIAN_DAY = 20 ;
const integer FIELD_MILLISECONDS_IN_DAY = 21 ;
const integer FIELD_IS_LEAP_MONTH = 22 ;
const integer FIELD_FIELD_COUNT = 23 ;
const integer FIELD_DAY_OF_MONTH = 5 ;
const integer DOW_SUNDAY = 1 ;
const integer DOW_MONDAY = 2 ;
const integer DOW_TUESDAY = 3 ;
const integer DOW_WEDNESDAY = 4 ;
const integer DOW_THURSDAY = 5 ;
const integer DOW_FRIDAY = 6 ;
const integer DOW_SATURDAY = 7 ;
const integer DOW_TYPE_WEEKDAY = 0 ;
const integer DOW_TYPE_WEEKEND = 1 ;
const integer DOW_TYPE_WEEKEND_OFFSET = 2 ;
const integer DOW_TYPE_WEEKEND_CEASE = 3 ;
const integer WALLTIME_FIRST = 1 ;
const integer WALLTIME_LAST = 0 ;
const integer WALLTIME_NEXT_VALID = 2 ;
/* Methods */
public add ( int $field , int $amount ) : bool
intlcal_add ( IntlCalendar $cal , int $field , int $amount ) : bool
public after ( IntlCalendar $other ) : bool
intlcal_after ( IntlCalendar $cal , IntlCalendar $other ) : bool
public before ( IntlCalendar $other ) : bool
intlcal_before ( IntlCalendar $cal , IntlCalendar $other ) : bool
public clear ([ int $field = NULL ] ) : bool
intlcal_clear ( IntlCalendar $cal [, int $field = NULL ] ) : bool
private __construct ( void )
public static createInstance ([ mixed $timeZone = NULL [, string $locale = "" ]] ) : IntlCalendar
intlcal_create_instance ([ mixed $timeZone = NULL [, string $locale = "" ]] ) : IntlCalendar
public equals ( IntlCalendar $other ) : bool
intlcal_equals ( IntlCalendar $cal , IntlCalendar $other ) : bool
public fieldDifference ( float $when , int $field ) : int
intlcal_field_difference ( IntlCalendar $cal , float $when , int $field ) : int
public static fromDateTime ( mixed $dateTime ) : IntlCalendar
intlcal_from_date_time ( mixed $dateTime ) : IntlCalendar
public get ( int $field ) : int
intlcal_get ( IntlCalendar $cal , int $field ) : int
public getActualMaximum ( int $field ) : int
intlcal_get_actual_maximum ( IntlCalendar $cal , int $field ) : int
public getActualMinimum ( int $field ) : int
intlcal_get_actual_minimum ( IntlCalendar $cal , int $field ) : int
public static getAvailableLocales ( void ) : array
intlcal_get_available_locales ( void ) : array
public getDayOfWeekType ( int $dayOfWeek ) : int
intlcal_get_day_of_week_type ( IntlCalendar $cal , int $dayOfWeek ) : int
public getErrorCode ( void ) : int
public getErrorMessage ( void ) : string
public getFirstDayOfWeek ( void ) : int
intlcal_get_first_day_of_week ( IntlCalendar $cal ) : int
public getGreatestMinimum ( int $field ) : int
intlcal_get_greatest_minimum ( IntlCalendar $cal , int $field ) : int
public static getKeywordValuesForLocale ( string $key , string $locale , bool $commonlyUsed ) : Iterator
intlcal_get_keyword_values_for_locale ( string $key , string $locale , bool $commonlyUsed ) : Iterator
public getLeastMaximum ( int $field ) : int
intlcal_get_least_maximum ( IntlCalendar $cal , int $field ) : int
public getLocale ( int $localeType ) : string
intlcal_get_locale ( IntlCalendar $cal , int $localeType ) : string
public getMaximum ( int $field ) : int
intlcal_get_maximum ( IntlCalendar $cal , int $field ) : int
public getMinimalDaysInFirstWeek ( void ) : int
intlcal_get_minimal_days_in_first_week ( IntlCalendar $cal ) : int
public getMinimum ( int $field ) : int
intlcal_get_minimum ( IntlCalendar $cal , int $field ) : int
public static getNow ( void ) : float
intlcal_get_now ( void ) : float
public getRepeatedWallTimeOption ( void ) : int
intlcal_get_repeated_wall_time_option ( IntlCalendar $cal ) : int
public getSkippedWallTimeOption ( void ) : int
intlcal_get_skipped_wall_time_option ( IntlCalendar $cal ) : int
public getTime ( void ) : float
intlcal_get_time ( IntlCalendar $cal ) : float
public getTimeZone ( void ) : IntlTimeZone
intlcal_get_time_zone ( IntlCalendar $cal ) : IntlTimeZone
public getType ( void ) : string
intlcal_get_type ( IntlCalendar $cal ) : string
public getWeekendTransition ( string $dayOfWeek ) : int
intlcal_get_weekend_transition ( IntlCalendar $cal , string $dayOfWeek ) : int
public inDaylightTime ( void ) : bool
intlcal_in_daylight_time ( IntlCalendar $cal ) : bool
public isEquivalentTo ( IntlCalendar $other ) : bool
intlcal_is_equivalent_to ( IntlCalendar $cal , IntlCalendar $other ) : bool
public isLenient ( void ) : bool
intlcal_is_lenient ( IntlCalendar $cal ) : bool
public isSet ( int $field ) : bool
intlcal_is_set ( IntlCalendar $cal , int $field ) : bool
public isWeekend ([ float $date = NULL ] ) : bool
intlcal_is_weekend ( IntlCalendar $cal [, float $date = NULL ] ) : bool
public roll ( int $field , mixed $amountOrUpOrDown ) : bool
intlcal_roll ( IntlCalendar $cal , int $field , mixed $amountOrUpOrDown ) : bool
public set ( int $field , int $value ) : bool
public set ( int $year , int $month [, int $dayOfMonth = NULL [, int $hour = NULL [, int $minute = NULL [, int $second = NULL ]]]] ) : bool
intlcal_set ( IntlCalendar $cal , int $field , int $value ) : bool
intlcal_set ( IntlCalendar $cal , int $year , int $month [, int $dayOfMonth = NULL [, int $hour = NULL [, int $minute = NULL [, int $second = NULL ]]]] ) : bool
public setFirstDayOfWeek ( int $dayOfWeek ) : bool
intlcal_set_first_day_of_week ( IntlCalendar $cal , int $dayOfWeek ) : bool
public setLenient ( bool $isLenient ) : bool
intlcal_set_lenient ( IntlCalendar $cal , bool $isLenient ) : bool
public setMinimalDaysInFirstWeek ( int $minimalDays ) : bool
intlcal_get_minimal_days_in_first_week ( IntlCalendar $cal , int $minimalDays ) : bool
public setRepeatedWallTimeOption ( int $wallTimeOption ) : bool
intlcal_set_repeated_wall_time_option ( IntlCalendar $cal , int $wallTimeOption ) : bool
public setSkippedWallTimeOption ( int $wallTimeOption ) : bool
intlcal_set_skipped_wall_time_option ( IntlCalendar $cal , int $wallTimeOption ) : bool
public setTime ( float $date ) : bool
intlcal_set_time ( IntlCalendar $cal , float $date ) : bool
public setTimeZone ( mixed $timeZone ) : bool
intlcal_set_time_zone ( IntlCalendar $cal , mixed $timeZone ) : bool
public toDateTime ( void ) : DateTime
intlcal_to_date_time ( IntlCalendar $cal ) : DateTime
}

Predefined Constants

IntlCalendar::FIELD_ERA

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

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

Calendar field for the month. The month sequence is zero-based, so Janurary (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

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

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

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

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

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

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

Calendar field indicating whether a time is before noon (value 0, AM) or after (1). Midnight is AM, noon is PM.

IntlCalendar::FIELD_HOUR

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

Calendar field for the full (24h) hour of the day. Valid values are 0 to 23.

IntlCalendar::FIELD_MINUTE

Calendar field for the minutes component of the time.

IntlCalendar::FIELD_SECOND

Calendar field for the seconds component of the time.

IntlCalendar::FIELD_MILLISECOND

Calendar field the milliseconds component of the time.

IntlCalendar::FIELD_ZONE_OFFSET

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

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

Calendar field representing the year for week of year purposes.

IntlCalendar::FIELD_DOW_LOCAL

Calendar field for the localized day of the week. This is a value betwen 1 and 7, 1 being used for the day of the week that matches the value returned by IntlCalendar::getFirstDayOfWeek().

IntlCalendar::FIELD_EXTENDED_YEAR

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

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

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 ellapsed in the day since on DST transitions it will have discontinuities analog to those of the wall time.

IntlCalendar::FIELD_IS_LEAP_MONTH

Calendar field whose value is 1 for indicating a leap month and 0 otherwise.

IntlCalendar::FIELD_FIELD_COUNT

The total number of fields.

IntlCalendar::FIELD_DAY_OF_MONTH

Alias for IntlCalendar::FIELD_DATE.

IntlCalendar::DOW_SUNDAY

Sunday.

IntlCalendar::DOW_MONDAY

Monday.

IntlCalendar::DOW_TUESDAY

Tuesday.

IntlCalendar::DOW_WEDNESDAY

Wednesday.

IntlCalendar::DOW_THURSDAY

Thursday.

IntlCalendar::DOW_FRIDAY

Friday.

IntlCalendar::DOW_SATURDAY

Saturday.

IntlCalendar::DOW_TYPE_WEEKDAY

Output of IntlCalendar::getDayOfWeekType() indicating a day of week is a weekday.

IntlCalendar::DOW_TYPE_WEEKEND

Output of IntlCalendar::getDayOfWeekType() indicating a day of week belongs to the weekend.

IntlCalendar::DOW_TYPE_WEEKEND_OFFSET

Output of IntlCalendar::getDayOfWeekType() indicating the weekend begins during the given day of week.

IntlCalendar::DOW_TYPE_WEEKEND_CEASE

Output of IntlCalendar::getDayOfWeekType() indicating the weekend ends during the given day of week.

IntlCalendar::WALLTIME_FIRST

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

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

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).

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::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


Add a (signed) amount of time to a field

  • « IntlCalendar
  • IntlCalendar::after »
  • PHP Manual
  • IntlCalendar
  • Add a (signed) amount of time to a field

IntlCalendar::add

(PHP 5 >= 5.5.0, PHP 7, 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 $amount ) : bool

Procedural style

intlcal_add ( IntlCalendar $cal , int $field , int $amount ) : 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 Janurary.

Parameters

cal

The IntlCalendar resource.

field

One of the IntlCalendar date/time field constants. These are integer values between 0 and IntlCalendar::FIELD_COUNT.

amount

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 wil 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


Whether this objectʼs time is after that of the passed object

  • « IntlCalendar::add
  • IntlCalendar::before »
  • PHP Manual
  • IntlCalendar
  • Whether this objectʼs time is after that of the passed object

IntlCalendar::after

(PHP 5 >= 5.5.0, PHP 7, 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 $cal , IntlCalendar $other ) : bool

Returns whether this objectʼs time succeeds the argumentʼs time.

Parameters

cal

The IntlCalendar resource.

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. Also returns FALSE on failure. You can use exceptions or intl_get_error_code() to detect error conditions.

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


Whether this objectʼs time is before that of the passed object

  • « IntlCalendar::after
  • IntlCalendar::clear »
  • PHP Manual
  • IntlCalendar
  • Whether this objectʼs time is before that of the passed object

IntlCalendar::before

(PHP 5 >= 5.5.0, PHP 7, 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 $cal , IntlCalendar $other ) : bool

Returns whether this objectʼs time precedes the argumentʼs time.

Parameters

cal

The IntlCalendar resource.

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. Also returns FALSE on failure. You can use exceptions or intl_get_error_code() to detect error conditions.


Clear a field or all fields

  • « IntlCalendar::before
  • IntlCalendar::__construct »
  • PHP Manual
  • IntlCalendar
  • Clear a field or all fields

IntlCalendar::clear

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::clear — Clear a field or all fields

Description

Object oriented style

public IntlCalendar::clear ([ int $field = NULL ] ) : bool

Procedural style

intlcal_clear ( IntlCalendar $cal [, int $field = NULL ] ) : bool

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

cal

The IntlCalendar resource.

field

One of the IntlCalendar date/time field constants. These are integer values between 0 and IntlCalendar::FIELD_COUNT.

Return Values

Returns TRUE on success or FALSE on failure. Failure can only occur is invalid arguments are provided.

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


Private constructor for disallowing instantiation

  • « IntlCalendar::clear
  • IntlCalendar::createInstance »
  • PHP Manual
  • IntlCalendar
  • Private constructor for disallowing instantiation

IntlCalendar::__construct

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::__construct — Private constructor for disallowing instantiation

Description

private IntlCalendar::__construct ( void )

A private constructor for disallowing instantiation with the new operator.

Call IntlCalendar::createInstance() instead.

Parameters

This function has no parameters.

Return Values

No value is returned.


Create a new IntlCalendar

  • « IntlCalendar::__construct
  • IntlCalendar::equals »
  • PHP Manual
  • IntlCalendar
  • Create a new IntlCalendar

IntlCalendar::createInstance

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::createInstance — Create a new IntlCalendar

Description

Object oriented style

public static IntlCalendar::createInstance ([ mixed $timeZone = NULL [, string $locale = "" ]] ) : IntlCalendar

Procedural style

intlcal_create_instance ([ mixed $timeZone = NULL [, string $locale = "" ]] ) : 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


Compare time of two IntlCalendar objects for equality

  • « IntlCalendar::createInstance
  • IntlCalendar::fieldDifference »
  • PHP Manual
  • IntlCalendar
  • Compare time of two IntlCalendar objects for equality

IntlCalendar::equals

(PHP 5 >= 5.5.0, PHP 7, 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 $cal , 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

cal

The IntlCalendar resource.

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. The value FALSE can also be returned on failure. This can only happen if bad arguments are passed in. In any case, the two cases can be distinguished by calling intl_get_error_code().

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


Calculate difference between given time and this objectʼs time

  • « IntlCalendar::equals
  • IntlCalendar::fromDateTime »
  • PHP Manual
  • IntlCalendar
  • Calculate difference between given time and this objectʼs time

IntlCalendar::fieldDifference

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::fieldDifference — Calculate difference between given time and this objectʼs time

Description

Object oriented style

public IntlCalendar::fieldDifference ( float $when , int $field ) : int

Procedural style

intlcal_field_difference ( IntlCalendar $cal , float $when , int $field ) : int

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

cal

The IntlCalendar resource.

when

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


Create an IntlCalendar from a DateTime object or string

  • « IntlCalendar::fieldDifference
  • IntlCalendar::get »
  • PHP Manual
  • IntlCalendar
  • Create an IntlCalendar from a DateTime object or string

IntlCalendar::fromDateTime

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a2)

IntlCalendar::fromDateTime — Create an IntlCalendar from a DateTime object or string

Description

Object oriented style

public static IntlCalendar::fromDateTime ( mixed $dateTime ) : IntlCalendar

Procedural style

intlcal_from_date_time ( mixed $dateTime ) : 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');

//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


Get the value for a field

  • « IntlCalendar::fromDateTime
  • IntlCalendar::getActualMaximum »
  • PHP Manual
  • IntlCalendar
  • Get the value for a field

IntlCalendar::get

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::get — Get the value for a field

Description

Object oriented style

public IntlCalendar::get ( int $field ) : int

Procedural style

intlcal_get ( IntlCalendar $cal , int $field ) : int

Gets the value for a specific field.

Parameters

cal

The IntlCalendar resource.

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


The maximum value for a field, considering the objectʼs current time

  • « IntlCalendar::get
  • IntlCalendar::getActualMinimum »
  • PHP Manual
  • IntlCalendar
  • The maximum value for a field, considering the objectʼs current time

IntlCalendar::getActualMaximum

(PHP 5 >= 5.5.0, PHP 7, 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

Procedural style

intlcal_get_actual_maximum ( IntlCalendar $cal , int $field ) : int

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

cal

The IntlCalendar resource.

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


The minimum value for a field, considering the objectʼs current time

  • « IntlCalendar::getActualMaximum
  • IntlCalendar::getAvailableLocales »
  • PHP Manual
  • IntlCalendar
  • The minimum value for a field, considering the objectʼs current time

IntlCalendar::getActualMinimum

(PHP 5 >= 5.5.0, PHP 7, 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

Procedural style

intlcal_get_actual_minimum ( IntlCalendar $cal , int $field ) : int

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

cal

The IntlCalendar resource.

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


Get array of locales for which there is data

  • « IntlCalendar::getActualMinimum
  • IntlCalendar::getDayOfWeekType »
  • PHP Manual
  • IntlCalendar
  • Get array of locales for which there is data

IntlCalendar::getAvailableLocales

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getAvailableLocales — Get array of locales for which there is data

Description

Object oriented style

public static IntlCalendar::getAvailableLocales ( void ) : array

Procedural style

intlcal_get_available_locales ( void ) : 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
)


Tell whether a day is a weekday, weekend or a day that has a transition between the two

  • « IntlCalendar::getAvailableLocales
  • IntlCalendar::getErrorCode »
  • PHP Manual
  • IntlCalendar
  • Tell whether a day is a weekday, weekend or a day that has a transition between the two

IntlCalendar::getDayOfWeekType

(PHP 5 >= 5.5.0, PHP 7, 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

Procedural style

intlcal_get_day_of_week_type ( IntlCalendar $cal , int $dayOfWeek ) : int

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

cal

The IntlCalendar resource.

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++) {
        echo $i, " ", $cal->getDayOfWeekType($i), " ",
                $cal->getDayOfWeekType($i) >= IntlCalendar::DOW_TYPE_WEEKEND_OFFSET
                        ? $cal->getWeekendTransition($i)
                        : '',
                "\n";
    }
    echo "\n";
}

The above example will output:

Locale: English (United States)
1 3 86400000
2 0
3 0
4 0
5 0
6 0
7 1

Locale: Arabic (Saudi Arabia)
1 0
2 0
3 0
4 0
5 1
6 3 86400000
7 0


Get last error code on the object

  • « IntlCalendar::getDayOfWeekType
  • IntlCalendar::getErrorMessage »
  • PHP Manual
  • IntlCalendar
  • Get last error code on the object

IntlCalendar::getErrorCode

intlcal_get_error_code

(PHP 5 >= 5.5.0, PHP 7, 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 ( void ) : int

Procedural style:

intlcal_get_error_code ( IntlCalendar $calendar ) : int

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.

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


Get last error message on the object

  • « IntlCalendar::getErrorCode
  • IntlCalendar::getFirstDayOfWeek »
  • PHP Manual
  • IntlCalendar
  • Get last error message on the object

IntlCalendar::getErrorMessage

intlcal_get_error_message

(PHP 5 >= 5.5.0, PHP 7, 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 ( void ) : string

Procedural style:

intlcal_get_error_message ( IntlCalendar $calendar ) : string

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-existance of an error.

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"


Get the first day of the week for the calendarʼs locale

  • « IntlCalendar::getErrorMessage
  • IntlCalendar::getGreatestMinimum »
  • PHP Manual
  • IntlCalendar
  • Get the first day of the week for the calendarʼs locale

IntlCalendar::getFirstDayOfWeek

(PHP 5 >= 5.5.0, PHP 7, 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 ( void ) : int

Procedural style

intlcal_get_first_day_of_week ( IntlCalendar $cal ) : int

The week day deemed to start a week, either the default value for this locale or the value set with IntlCalendar::setFirstDayOfWeek().

Parameters

cal

The IntlCalendar resource.

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


Get the largest local minimum value for a field

  • « IntlCalendar::getFirstDayOfWeek
  • IntlCalendar::getKeywordValuesForLocale »
  • PHP Manual
  • IntlCalendar
  • Get the largest local minimum value for a field

IntlCalendar::getGreatestMinimum

(PHP 5 >= 5.5.0, PHP 7, 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

Procedural style

intlcal_get_greatest_minimum ( IntlCalendar $cal , int $field ) : int

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

cal

The IntlCalendar resource.

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.


Get set of locale keyword values

  • « IntlCalendar::getGreatestMinimum
  • IntlCalendar::getLeastMaximum »
  • PHP Manual
  • IntlCalendar
  • Get set of locale keyword values

IntlCalendar::getKeywordValuesForLocale

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getKeywordValuesForLocale — Get set of locale keyword values

Description

Object oriented style

public static IntlCalendar::getKeywordValuesForLocale ( string $key , string $locale , bool $commonlyUsed ) : Iterator

Procedural style

intlcal_get_keyword_values_for_locale ( string $key , string $locale , bool $commonlyUsed ) : Iterator

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

key

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.

commonlyUsed

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
)


Get the smallest local maximum for a field

  • « IntlCalendar::getKeywordValuesForLocale
  • IntlCalendar::getLocale »
  • PHP Manual
  • IntlCalendar
  • Get the smallest local maximum for a field

IntlCalendar::getLeastMaximum

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getLeastMaximum — Get the smallest local maximum for a field

Description

Object oriented style

public IntlCalendar::getLeastMaximum ( int $field ) : int

Procedural style

intlcal_get_least_maximum ( IntlCalendar $cal , int $field ) : int

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

cal

The IntlCalendar resource.

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


Get the locale associated with the object

  • « IntlCalendar::getLeastMaximum
  • IntlCalendar::getMaximum »
  • PHP Manual
  • IntlCalendar
  • Get the locale associated with the object

IntlCalendar::getLocale

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getLocale — Get the locale associated with the object

Description

Object oriented style

public IntlCalendar::getLocale ( int $localeType ) : string

Procedural style

intlcal_get_locale ( IntlCalendar $cal , int $localeType ) : string

Returns the locale used by this calendar object.

Parameters

cal

The IntlCalendar resource.

localeType

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"


Get the global maximum value for a field

  • « IntlCalendar::getLocale
  • IntlCalendar::getMinimalDaysInFirstWeek »
  • PHP Manual
  • IntlCalendar
  • Get the global maximum value for a field

IntlCalendar::getMaximum

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getMaximum — Get the global maximum value for a field

Description

Object oriented style

public IntlCalendar::getMaximum ( int $field ) : int

Procedural style

intlcal_get_maximum ( IntlCalendar $cal , int $field ) : int

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

cal

The IntlCalendar resource.

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


Get minimal number of days the first week in a year or month can have

  • « IntlCalendar::getMaximum
  • IntlCalendar::getMinimum »
  • PHP Manual
  • IntlCalendar
  • Get minimal number of days the first week in a year or month can have

IntlCalendar::getMinimalDaysInFirstWeek

(PHP 5 >= 5.5.0, PHP 7, 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 ( void ) : int

Procedural style

intlcal_get_minimal_days_in_first_week ( IntlCalendar $cal ) : int

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

cal

The IntlCalendar resource.

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"


Get the global minimum value for a field

  • « IntlCalendar::getMinimalDaysInFirstWeek
  • IntlCalendar::getNow »
  • PHP Manual
  • IntlCalendar
  • Get the global minimum value for a field

IntlCalendar::getMinimum

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getMinimum — Get the global minimum value for a field

Description

Object oriented style

public IntlCalendar::getMinimum ( int $field ) : int

Procedural style

intlcal_get_minimum ( IntlCalendar $cal , int $field ) : int

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

cal

The IntlCalendar resource.

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.


Get number representing the current time

  • « IntlCalendar::getMinimum
  • IntlCalendar::getRepeatedWallTimeOption »
  • PHP Manual
  • IntlCalendar
  • Get number representing the current time

IntlCalendar::getNow

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getNow — Get number representing the current time

Description

Object oriented style

public static IntlCalendar::getNow ( void ) : float

Procedural style

intlcal_get_now ( void ) : 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


Get behavior for handling repeating wall time

  • « IntlCalendar::getNow
  • IntlCalendar::getSkippedWallTimeOption »
  • PHP Manual
  • IntlCalendar
  • Get behavior for handling repeating wall time

IntlCalendar::getRepeatedWallTimeOption

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getRepeatedWallTimeOption — Get behavior for handling repeating wall time

Description

Object oriented style

public IntlCalendar::getRepeatedWallTimeOption ( void ) : int

Procedural style

intlcal_get_repeated_wall_time_option ( IntlCalendar $cal ) : 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

cal

The IntlCalendar resource.

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


Get behavior for handling skipped wall time

  • « IntlCalendar::getRepeatedWallTimeOption
  • IntlCalendar::getTime »
  • PHP Manual
  • IntlCalendar
  • Get behavior for handling skipped wall time

IntlCalendar::getSkippedWallTimeOption

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getSkippedWallTimeOption — Get behavior for handling skipped wall time

Description

Object oriented style

public IntlCalendar::getSkippedWallTimeOption ( void ) : int

Procedural style

intlcal_get_skipped_wall_time_option ( IntlCalendar $cal ) : 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

cal

The IntlCalendar resource.

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


Get time currently represented by the object

  • « IntlCalendar::getSkippedWallTimeOption
  • IntlCalendar::getTimeZone »
  • PHP Manual
  • IntlCalendar
  • Get time currently represented by the object

IntlCalendar::getTime

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getTime — Get time currently represented by the object

Description

Object oriented style

public IntlCalendar::getTime ( void ) : float

Procedural style

intlcal_get_time ( IntlCalendar $cal ) : float

Returns the time associated with this object, expressed as the number of milliseconds since the epoch.

Parameters

cal

The IntlCalendar resource.

Return Values

A float representing the number of milliseconds elapsed since the reference time (1 Jan 1970 00:00:00 UTC).

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


Get the objectʼs timezone

  • « IntlCalendar::getTime
  • IntlCalendar::getType »
  • PHP Manual
  • IntlCalendar
  • Get the objectʼs timezone

IntlCalendar::getTimeZone

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getTimeZone — Get the objectʼs timezone

Description

Object oriented style

public IntlCalendar::getTimeZone ( void ) : IntlTimeZone

Procedural style

intlcal_get_time_zone ( IntlCalendar $cal ) : IntlTimeZone

Returns the IntlTimeZone object associated with this calendar.

Parameters

cal

The IntlCalendar resource.

Return Values

An IntlTimeZone object corresponding to the one used internally in this object.

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


Get the calendar type

  • « IntlCalendar::getTimeZone
  • IntlCalendar::getWeekendTransition »
  • PHP Manual
  • IntlCalendar
  • Get the calendar type

IntlCalendar::getType

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getType — Get the calendar type

Description

Object oriented style

public IntlCalendar::getType ( void ) : string

Procedural style

intlcal_get_type ( IntlCalendar $cal ) : string

A string describing the type of this calendar. This is one of the valid values for the calendar keyword value 'calendar'.

Parameters

cal

The IntlCalendar resource.

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"


Get time of the day at which weekend begins or ends

  • « IntlCalendar::getType
  • IntlCalendar::inDaylightTime »
  • PHP Manual
  • IntlCalendar
  • Get time of the day at which weekend begins or ends

IntlCalendar::getWeekendTransition

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::getWeekendTransition — Get time of the day at which weekend begins or ends

Description

Object oriented style

public IntlCalendar::getWeekendTransition ( string $dayOfWeek ) : int

Procedural style

intlcal_get_weekend_transition ( IntlCalendar $cal , string $dayOfWeek ) : int

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

cal

The IntlCalendar resource.

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().


Whether the objectʼs time is in Daylight Savings Time

  • « IntlCalendar::getWeekendTransition
  • IntlCalendar::isEquivalentTo »
  • PHP Manual
  • IntlCalendar
  • Whether the objectʼs time is in Daylight Savings Time

IntlCalendar::inDaylightTime

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::inDaylightTime — Whether the objectʼs time is in Daylight Savings Time

Description

Object oriented style

public IntlCalendar::inDaylightTime ( void ) : bool

Procedural style

intlcal_in_daylight_time ( IntlCalendar $cal ) : bool

Whether, for the instant represented by this object and for this objectʼs timezone, daylight saving time is in place.

Parameters

cal

The IntlCalendar resource.

Return Values

Returns TRUE if the date is in Daylight Savings Time, FALSE otherwise. The value FALSE may also be returned on failure, for instance after specifying invalid field values on non-lenient mode; use exceptions or query intl_get_error_code() to disambiguate.

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


Whether another calendar is equal but for a different time

  • « IntlCalendar::inDaylightTime
  • IntlCalendar::isLenient »
  • PHP Manual
  • IntlCalendar
  • Whether another calendar is equal but for a different time

IntlCalendar::isEquivalentTo

(PHP 5 >= 5.5.0, PHP 7, 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 $cal , 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

cal

The IntlCalendar resource.

other

The other calendar against which the comparison is to be made.

Return Values

Assuming there are no argument errors, returns TRUE iif 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


Whether date/time interpretation is in lenient mode

  • « IntlCalendar::isEquivalentTo
  • IntlCalendar::isSet »
  • PHP Manual
  • IntlCalendar
  • Whether date/time interpretation is in lenient mode

IntlCalendar::isLenient

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::isLenient — Whether date/time interpretation is in lenient mode

Description

Object oriented style

public IntlCalendar::isLenient ( void ) : bool

Procedural style

intlcal_is_lenient ( IntlCalendar $cal ) : 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

cal

The IntlCalendar resource.

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


Whether a field is set

  • « IntlCalendar::isLenient
  • IntlCalendar::isWeekend »
  • PHP Manual
  • IntlCalendar
  • Whether a field is set

IntlCalendar::isSet

(PHP 5 >= 5.5.0, PHP 7, 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 $cal , 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

cal

The IntlCalendar resource.

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 iif 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


Whether a certain date/time is in the weekend

  • « IntlCalendar::isSet
  • IntlCalendar::roll »
  • PHP Manual
  • IntlCalendar
  • Whether a certain date/time is in the weekend

IntlCalendar::isWeekend

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::isWeekend — Whether a certain date/time is in the weekend

Description

Object oriented style

public IntlCalendar::isWeekend ([ float $date = NULL ] ) : bool

Procedural style

intlcal_is_weekend ( IntlCalendar $cal [, float $date = 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

cal

The IntlCalendar resource.

date

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.

The value FALSE may also be returned on failure, for instance after giving a date out of bounds on non-lenient mode; use exceptions or query intl_get_error_code() to disambiguate.

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


Add value to field without carrying into more significant fields

  • « IntlCalendar::isWeekend
  • IntlCalendar::set »
  • PHP Manual
  • IntlCalendar
  • Add value to field without carrying into more significant fields

IntlCalendar::roll

(PHP 5 >= 5.5.0, PHP 7, 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 , mixed $amountOrUpOrDown ) : bool

Procedural style

intlcal_roll ( IntlCalendar $cal , int $field , mixed $amountOrUpOrDown ) : 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

cal

The IntlCalendar resource.

field

One of the IntlCalendar date/time field constants. These are integer values between 0 and IntlCalendar::FIELD_COUNT.

amountOrUpOrDown

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


Set a time field or several common fields at once

  • « IntlCalendar::roll
  • IntlCalendar::setFirstDayOfWeek »
  • PHP Manual
  • IntlCalendar
  • Set a time field or several common fields at once

IntlCalendar::set

(PHP 5 >= 5.5.0, PHP 7, 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 ) : bool
public IntlCalendar::set ( int $year , int $month [, int $dayOfMonth = NULL [, int $hour = NULL [, int $minute = NULL [, int $second = NULL ]]]] ) : bool

Procedural style

intlcal_set ( IntlCalendar $cal , int $field , int $value ) : bool
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

The IntlCalendar resource.

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.

dayOfMonth

The new value for IntlCalendar::FIELD_DAY_OF_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.

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

Returns TRUE on success and FALSE on failure.

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


Set the day on which the week is deemed to start

  • « IntlCalendar::set
  • IntlCalendar::setLenient »
  • PHP Manual
  • IntlCalendar
  • Set the day on which the week is deemed to start

IntlCalendar::setFirstDayOfWeek

(PHP 5 >= 5.5.0, PHP 7, 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 ) : bool

Procedural style

intlcal_set_first_day_of_week ( IntlCalendar $cal , int $dayOfWeek ) : bool

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

cal

The IntlCalendar resource.

dayOfWeek

One of the constants IntlCalendar::DOW_SUNDAY,
IntlCalendar::DOW_MONDAY, …,
IntlCalendar::DOW_SATURDAY.

Return Values

Returns TRUE on success. Failure can only happen due to invalid parameters.

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


Set whether date/time interpretation is to be lenient

  • « IntlCalendar::setFirstDayOfWeek
  • IntlCalendar::setMinimalDaysInFirstWeek »
  • PHP Manual
  • IntlCalendar
  • Set whether date/time interpretation is to be lenient

IntlCalendar::setLenient

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::setLenient — Set whether date/time interpretation is to be lenient

Description

Object oriented style

public IntlCalendar::setLenient ( bool $isLenient ) : bool

Procedural style

intlcal_set_lenient ( IntlCalendar $cal , bool $isLenient ) : bool

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

cal

The IntlCalendar resource.

isLenient

Use TRUE to activate the lenient mode; FALSE otherwise.

Return Values

Returns TRUE on success. Failure can only happen due to invalid parameters.

Examples

See the example in IntlCalendar::isLenient().


Set minimal number of days the first week in a year or month can have

  • « IntlCalendar::setLenient
  • IntlCalendar::setRepeatedWallTimeOption »
  • PHP Manual
  • IntlCalendar
  • Set minimal number of days the first week in a year or month can have

IntlCalendar::setMinimalDaysInFirstWeek

(PHP 5 >= 5.5.1, PHP 7)

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 $minimalDays ) : bool

Procedural style

intlcal_get_minimal_days_in_first_week ( IntlCalendar $cal , int $minimalDays ) : bool

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

cal

The IntlCalendar resource.

minimalDays

The number of minimal days to set.

Return Values

TRUE on success, FALSE on failure.


Set behavior for handling repeating wall times at negative timezone offset transitions

  • « IntlCalendar::setMinimalDaysInFirstWeek
  • IntlCalendar::setSkippedWallTimeOption »
  • PHP Manual
  • IntlCalendar
  • Set behavior for handling repeating wall times at negative timezone offset transitions

IntlCalendar::setRepeatedWallTimeOption

(PHP 5 >= 5.5.0, PHP 7, 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 $wallTimeOption ) : bool

Procedural style

intlcal_set_repeated_wall_time_option ( IntlCalendar $cal , int $wallTimeOption ) : bool

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

cal

The IntlCalendar resource.

wallTimeOption

One of the constants IntlCalendar::WALLTIME_FIRST or IntlCalendar::WALLTIME_LAST.

Return Values

Returns TRUE on success. Failure can only happen due to invalid parameters.

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


Set behavior for handling skipped wall times at positive timezone offset transitions

  • « IntlCalendar::setRepeatedWallTimeOption
  • IntlCalendar::setTime »
  • PHP Manual
  • IntlCalendar
  • Set behavior for handling skipped wall times at positive timezone offset transitions

IntlCalendar::setSkippedWallTimeOption

(PHP 5 >= 5.5.0, PHP 7, 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 $wallTimeOption ) : bool

Procedural style

intlcal_set_skipped_wall_time_option ( IntlCalendar $cal , int $wallTimeOption ) : bool

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

cal

The IntlCalendar resource.

wallTimeOption

One of the constants IntlCalendar::WALLTIME_FIRST,
IntlCalendar::WALLTIME_LAST or
IntlCalendar::WALLTIME_NEXT_VALID.

Return Values

Returns TRUE on success. Failure can only happen due to invalid parameters.

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


Set the calendar time in milliseconds since the epoch

  • « IntlCalendar::setSkippedWallTimeOption
  • IntlCalendar::setTimeZone »
  • PHP Manual
  • IntlCalendar
  • Set the calendar time in milliseconds since the epoch

IntlCalendar::setTime

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::setTime — Set the calendar time in milliseconds since the epoch

Description

Object oriented style

public IntlCalendar::setTime ( float $date ) : bool

Procedural style

intlcal_set_time ( IntlCalendar $cal , float $date ) : 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

cal

The IntlCalendar resource.

date

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


Set the timezone used by this calendar

  • « IntlCalendar::setTime
  • IntlCalendar::toDateTime »
  • PHP Manual
  • IntlCalendar
  • Set the timezone used by this calendar

IntlCalendar::setTimeZone

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlCalendar::setTimeZone — Set the timezone used by this calendar

Description

Object oriented style

public IntlCalendar::setTimeZone ( mixed $timeZone ) : bool

Procedural style

intlcal_set_time_zone ( IntlCalendar $cal , mixed $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

cal

The IntlCalendar resource.

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)


Convert an IntlCalendar into a DateTime object

  • « IntlCalendar::setTimeZone
  • IntlGregorianCalendar »
  • PHP Manual
  • IntlCalendar
  • Convert an IntlCalendar into a DateTime object

IntlCalendar::toDateTime

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a2)

IntlCalendar::toDateTime — Convert an IntlCalendar into a DateTime object

Description

Object oriented style

public IntlCalendar::toDateTime ( void ) : DateTime

Procedural style

intlcal_to_date_time ( IntlCalendar $cal ) : DateTime

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

cal

The IntlCalendar resource.

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()


The IntlGregorianCalendar class

(PHP 5 >= 5.5.0, PHP 7)

Introduction

Class synopsis

IntlGregorianCalendar extends IntlCalendar {
/* Inherited constants */
const integer IntlCalendar::FIELD_ERA = 0 ;
const integer IntlCalendar::FIELD_YEAR = 1 ;
const integer IntlCalendar::FIELD_MONTH = 2 ;
const integer IntlCalendar::FIELD_WEEK_OF_YEAR = 3 ;
const integer IntlCalendar::FIELD_WEEK_OF_MONTH = 4 ;
const integer IntlCalendar::FIELD_DATE = 5 ;
const integer IntlCalendar::FIELD_DAY_OF_YEAR = 6 ;
const integer IntlCalendar::FIELD_DAY_OF_WEEK = 7 ;
const integer IntlCalendar::FIELD_DAY_OF_WEEK_IN_MONTH = 8 ;
const integer IntlCalendar::FIELD_AM_PM = 9 ;
const integer IntlCalendar::FIELD_HOUR = 10 ;
const integer IntlCalendar::FIELD_HOUR_OF_DAY = 11 ;
const integer IntlCalendar::FIELD_MINUTE = 12 ;
const integer IntlCalendar::FIELD_SECOND = 13 ;
const integer IntlCalendar::FIELD_MILLISECOND = 14 ;
const integer IntlCalendar::FIELD_ZONE_OFFSET = 15 ;
const integer IntlCalendar::FIELD_DST_OFFSET = 16 ;
const integer IntlCalendar::FIELD_YEAR_WOY = 17 ;
const integer IntlCalendar::FIELD_DOW_LOCAL = 18 ;
const integer IntlCalendar::FIELD_EXTENDED_YEAR = 19 ;
const integer IntlCalendar::FIELD_JULIAN_DAY = 20 ;
const integer IntlCalendar::FIELD_MILLISECONDS_IN_DAY = 21 ;
const integer IntlCalendar::FIELD_IS_LEAP_MONTH = 22 ;
const integer IntlCalendar::FIELD_FIELD_COUNT = 23 ;
const integer IntlCalendar::FIELD_DAY_OF_MONTH = 5 ;
const integer IntlCalendar::DOW_SUNDAY = 1 ;
const integer IntlCalendar::DOW_MONDAY = 2 ;
const integer IntlCalendar::DOW_TUESDAY = 3 ;
const integer IntlCalendar::DOW_WEDNESDAY = 4 ;
const integer IntlCalendar::DOW_THURSDAY = 5 ;
const integer IntlCalendar::DOW_FRIDAY = 6 ;
const integer IntlCalendar::DOW_SATURDAY = 7 ;
const integer IntlCalendar::DOW_TYPE_WEEKDAY = 0 ;
const integer IntlCalendar::DOW_TYPE_WEEKEND = 1 ;
const integer IntlCalendar::DOW_TYPE_WEEKEND_OFFSET = 2 ;
const integer IntlCalendar::DOW_TYPE_WEEKEND_CEASE = 3 ;
const integer IntlCalendar::WALLTIME_FIRST = 1 ;
const integer IntlCalendar::WALLTIME_LAST = 0 ;
const integer IntlCalendar::WALLTIME_NEXT_VALID = 2 ;
/* Methods */
public __construct ([ IntlTimeZone $tz [, string $locale ]] )
public getGregorianChange ( void ) : float
public isLeapYear ( int $year ) : bool
public setGregorianChange ( float $date ) : bool
/* Inherited methods */
public IntlCalendar::add ( int $field , int $amount ) : bool
intlcal_add ( IntlCalendar $cal , int $field , int $amount ) : bool
public IntlCalendar::after ( IntlCalendar $other ) : bool
intlcal_after ( IntlCalendar $cal , IntlCalendar $other ) : bool
public IntlCalendar::before ( IntlCalendar $other ) : bool
intlcal_before ( IntlCalendar $cal , IntlCalendar $other ) : bool
public IntlCalendar::clear ([ int $field = NULL ] ) : bool
intlcal_clear ( IntlCalendar $cal [, int $field = NULL ] ) : bool
private IntlCalendar::__construct ( void )
public static IntlCalendar::createInstance ([ mixed $timeZone = NULL [, string $locale = "" ]] ) : IntlCalendar
intlcal_create_instance ([ mixed $timeZone = NULL [, string $locale = "" ]] ) : IntlCalendar
public IntlCalendar::equals ( IntlCalendar $other ) : bool
intlcal_equals ( IntlCalendar $cal , IntlCalendar $other ) : bool
public IntlCalendar::fieldDifference ( float $when , int $field ) : int
intlcal_field_difference ( IntlCalendar $cal , float $when , int $field ) : int
public static IntlCalendar::fromDateTime ( mixed $dateTime ) : IntlCalendar
intlcal_from_date_time ( mixed $dateTime ) : IntlCalendar
public IntlCalendar::get ( int $field ) : int
intlcal_get ( IntlCalendar $cal , int $field ) : int
public IntlCalendar::getActualMaximum ( int $field ) : int
intlcal_get_actual_maximum ( IntlCalendar $cal , int $field ) : int
public IntlCalendar::getActualMinimum ( int $field ) : int
intlcal_get_actual_minimum ( IntlCalendar $cal , int $field ) : int
public static IntlCalendar::getAvailableLocales ( void ) : array
intlcal_get_available_locales ( void ) : array
public IntlCalendar::getDayOfWeekType ( int $dayOfWeek ) : int
intlcal_get_day_of_week_type ( IntlCalendar $cal , int $dayOfWeek ) : int
public IntlCalendar::getErrorCode ( void ) : int
public IntlCalendar::getErrorMessage ( void ) : string
public IntlCalendar::getFirstDayOfWeek ( void ) : int
intlcal_get_first_day_of_week ( IntlCalendar $cal ) : int
public IntlCalendar::getGreatestMinimum ( int $field ) : int
intlcal_get_greatest_minimum ( IntlCalendar $cal , int $field ) : int
public static IntlCalendar::getKeywordValuesForLocale ( string $key , string $locale , bool $commonlyUsed ) : Iterator
intlcal_get_keyword_values_for_locale ( string $key , string $locale , bool $commonlyUsed ) : Iterator
public IntlCalendar::getLeastMaximum ( int $field ) : int
intlcal_get_least_maximum ( IntlCalendar $cal , int $field ) : int
public IntlCalendar::getLocale ( int $localeType ) : string
intlcal_get_locale ( IntlCalendar $cal , int $localeType ) : string
public IntlCalendar::getMaximum ( int $field ) : int
intlcal_get_maximum ( IntlCalendar $cal , int $field ) : int
public IntlCalendar::getMinimalDaysInFirstWeek ( void ) : int
intlcal_get_minimal_days_in_first_week ( IntlCalendar $cal ) : int
public IntlCalendar::getMinimum ( int $field ) : int
intlcal_get_minimum ( IntlCalendar $cal , int $field ) : int
public static IntlCalendar::getNow ( void ) : float
intlcal_get_now ( void ) : float
public IntlCalendar::getRepeatedWallTimeOption ( void ) : int
intlcal_get_repeated_wall_time_option ( IntlCalendar $cal ) : int
public IntlCalendar::getSkippedWallTimeOption ( void ) : int
intlcal_get_skipped_wall_time_option ( IntlCalendar $cal ) : int
public IntlCalendar::getTime ( void ) : float
intlcal_get_time ( IntlCalendar $cal ) : float
public IntlCalendar::getTimeZone ( void ) : IntlTimeZone
intlcal_get_time_zone ( IntlCalendar $cal ) : IntlTimeZone
public IntlCalendar::getType ( void ) : string
intlcal_get_type ( IntlCalendar $cal ) : string
public IntlCalendar::getWeekendTransition ( string $dayOfWeek ) : int
intlcal_get_weekend_transition ( IntlCalendar $cal , string $dayOfWeek ) : int
public IntlCalendar::inDaylightTime ( void ) : bool
intlcal_in_daylight_time ( IntlCalendar $cal ) : bool
public IntlCalendar::isEquivalentTo ( IntlCalendar $other ) : bool
intlcal_is_equivalent_to ( IntlCalendar $cal , IntlCalendar $other ) : bool
public IntlCalendar::isLenient ( void ) : bool
intlcal_is_lenient ( IntlCalendar $cal ) : bool
public IntlCalendar::isSet ( int $field ) : bool
intlcal_is_set ( IntlCalendar $cal , int $field ) : bool
public IntlCalendar::isWeekend ([ float $date = NULL ] ) : bool
intlcal_is_weekend ( IntlCalendar $cal [, float $date = NULL ] ) : bool
public IntlCalendar::roll ( int $field , mixed $amountOrUpOrDown ) : bool
intlcal_roll ( IntlCalendar $cal , int $field , mixed $amountOrUpOrDown ) : bool
public IntlCalendar::set ( int $field , int $value ) : bool
public IntlCalendar::set ( int $year , int $month [, int $dayOfMonth = NULL [, int $hour = NULL [, int $minute = NULL [, int $second = NULL ]]]] ) : bool
intlcal_set ( IntlCalendar $cal , int $field , int $value ) : bool
intlcal_set ( IntlCalendar $cal , int $year , int $month [, int $dayOfMonth = NULL [, int $hour = NULL [, int $minute = NULL [, int $second = NULL ]]]] ) : bool
public IntlCalendar::setFirstDayOfWeek ( int $dayOfWeek ) : bool
intlcal_set_first_day_of_week ( IntlCalendar $cal , int $dayOfWeek ) : bool
public IntlCalendar::setLenient ( bool $isLenient ) : bool
intlcal_set_lenient ( IntlCalendar $cal , bool $isLenient ) : bool
public IntlCalendar::setMinimalDaysInFirstWeek ( int $minimalDays ) : bool
intlcal_get_minimal_days_in_first_week ( IntlCalendar $cal , int $minimalDays ) : bool
public IntlCalendar::setRepeatedWallTimeOption ( int $wallTimeOption ) : bool
intlcal_set_repeated_wall_time_option ( IntlCalendar $cal , int $wallTimeOption ) : bool
public IntlCalendar::setSkippedWallTimeOption ( int $wallTimeOption ) : bool
intlcal_set_skipped_wall_time_option ( IntlCalendar $cal , int $wallTimeOption ) : bool
public IntlCalendar::setTime ( float $date ) : bool
intlcal_set_time ( IntlCalendar $cal , float $date ) : bool
public IntlCalendar::setTimeZone ( mixed $timeZone ) : bool
intlcal_set_time_zone ( IntlCalendar $cal , mixed $timeZone ) : bool
public IntlCalendar::toDateTime ( void ) : DateTime
intlcal_to_date_time ( IntlCalendar $cal ) : DateTime
}

Table of Contents

  • IntlGregorianCalendar::__construct — Create the Gregorian Calendar class
  • 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


Create the Gregorian Calendar class

  • « IntlGregorianCalendar
  • IntlGregorianCalendar::getGregorianChange »
  • PHP Manual
  • IntlGregorianCalendar
  • Create the Gregorian Calendar class

IntlGregorianCalendar::__construct

(PHP 5 >= 5.5.0, PHP 7)

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


Get the Gregorian Calendar change date

  • « IntlGregorianCalendar::__construct
  • IntlGregorianCalendar::isLeapYear »
  • PHP Manual
  • IntlGregorianCalendar
  • Get the Gregorian Calendar change date

IntlGregorianCalendar::getGregorianChange

(PHP 5 >= 5.5.0, PHP 7)

IntlGregorianCalendar::getGregorianChange — Get the Gregorian Calendar change date

Description

public IntlGregorianCalendar::getGregorianChange ( void ) : 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 or FALSE on failure.


Determine if the given year is a leap year

  • « IntlGregorianCalendar::getGregorianChange
  • IntlGregorianCalendar::setGregorianChange »
  • PHP Manual
  • IntlGregorianCalendar
  • Determine if the given year is a leap year

IntlGregorianCalendar::isLeapYear

(PHP 5 >= 5.5.0, PHP 7)

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.


Set the Gregorian Calendar the change date

  • « IntlGregorianCalendar::isLeapYear
  • IntlTimeZone »
  • PHP Manual
  • IntlGregorianCalendar
  • Set the Gregorian Calendar the change date

IntlGregorianCalendar::setGregorianChange

(PHP 5 >= 5.5.0, PHP 7)

IntlGregorianCalendar::setGregorianChange — Set the Gregorian Calendar the change date

Description

public IntlGregorianCalendar::setGregorianChange ( float $date ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

date

Return Values

Returns TRUE on success or FALSE on failure.


The IntlTimeZone class

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

Introduction

Class synopsis

IntlTimeZone {
/* Constants */
const integer DISPLAY_SHORT = 1 ;
const integer DISPLAY_LONG = 2 ;
/* Methods */
public static countEquivalentIDs ( string $zoneId ) : int
public static createDefault ( void ) : IntlTimeZone
public static createEnumeration ([ mixed $countryOrRawOffset ] ) : IntlIterator
public static createTimeZone ( string $zoneId ) : IntlTimeZone
public static createTimeZoneIDEnumeration ( int $zoneType [, string $region [, int $rawOffset ]] ) : IntlIterator
public static fromDateTimeZone ( DateTimeZone $zoneId ) : IntlTimeZone
public static getCanonicalID ( string $zoneId [, bool &$isSystemID ] ) : string
public getDisplayName ([ bool $isDaylight [, int $style [, string $locale ]]] ) : string
public getDSTSavings ( void ) : int
public static getEquivalentID ( string $zoneId , int $index ) : string
public getErrorCode ( void ) : int
public getErrorMessage ( void ) : string
public static getGMT ( void ) : IntlTimeZone
public getID ( void ) : string
public static getIDForWindowsID ( string $timezone [, string $region ] ) : string
public getOffset ( float $date , bool $local , int &$rawOffset , int &$dstOffset ) : int
public getRawOffset ( void ) : int
public static getRegion ( string $zoneId ) : string
public static getTZDataVersion ( void ) : string
public static getUnknown ( void ) : IntlTimeZone
public static getWindowsID ( string $timezone ) : string
public hasSameRules ( IntlTimeZone $otherTimeZone ) : bool
public toDateTimeZone ( void ) : DateTimeZone
public useDaylightTime ( void ) : bool
}

Predefined Constants

IntlTimeZone::DISPLAY_SHORT

IntlTimeZone::DISPLAY_LONG

Table of Contents

  • 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


Get the number of IDs in the equivalency group that includes the given ID

  • « IntlTimeZone
  • IntlTimeZone::createDefault »
  • PHP Manual
  • IntlTimeZone
  • Get the number of IDs in the equivalency group that includes the given ID

IntlTimeZone::countEquivalentIDs

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::countEquivalentIDs — Get the number of IDs in the equivalency group that includes the given ID

Description

public static IntlTimeZone::countEquivalentIDs ( string $zoneId ) : int

Warning

This function is currently not documented; only its argument list is available.

Parameters

zoneId

Return Values


Create a new copy of the default timezone for this host

  • « IntlTimeZone::countEquivalentIDs
  • IntlTimeZone::createEnumeration »
  • PHP Manual
  • IntlTimeZone
  • Create a new copy of the default timezone for this host

IntlTimeZone::createDefault

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::createDefault — Create a new copy of the default timezone for this host

Description

public static IntlTimeZone::createDefault ( void ) : IntlTimeZone

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Get an enumeration over time zone IDs associated with the given country or offset

  • « IntlTimeZone::createDefault
  • IntlTimeZone::createTimeZone »
  • PHP Manual
  • IntlTimeZone
  • Get an enumeration over time zone IDs associated with the given country or offset

IntlTimeZone::createEnumeration

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::createEnumeration — Get an enumeration over time zone IDs associated with the given country or offset

Description

public static IntlTimeZone::createEnumeration ([ mixed $countryOrRawOffset ] ) : IntlIterator

Warning

This function is currently not documented; only its argument list is available.

Parameters

countryOrRawOffset

Return Values


Create a timezone object for the given ID

  • « IntlTimeZone::createEnumeration
  • IntlTimeZone::createTimeZoneIDEnumeration »
  • PHP Manual
  • IntlTimeZone
  • Create a timezone object for the given ID

IntlTimeZone::createTimeZone

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::createTimeZone — Create a timezone object for the given ID

Description

public static IntlTimeZone::createTimeZone ( string $zoneId ) : IntlTimeZone

Warning

This function is currently not documented; only its argument list is available.

Parameters

zoneId

Return Values


Get an enumeration over system time zone IDs with the given filter conditions

  • « IntlTimeZone::createTimeZone
  • IntlTimeZone::fromDateTimeZone »
  • PHP Manual
  • IntlTimeZone
  • Get an enumeration over system time zone IDs with the given filter conditions

IntlTimeZone::createTimeZoneIDEnumeration

(PHP 5 >= 5.5.0, PHP 7)

IntlTimeZone::createTimeZoneIDEnumeration — Get an enumeration over system time zone IDs with the given filter conditions

Description

public static IntlTimeZone::createTimeZoneIDEnumeration ( int $zoneType [, string $region [, int $rawOffset ]] ) : IntlIterator

Warning

This function is currently not documented; only its argument list is available.

Parameters

zoneType

region

rawOffset

Return Values

Returns IntlIterator or FALSE on failure.


Create a timezone object from DateTimeZone

  • « IntlTimeZone::createTimeZoneIDEnumeration
  • IntlTimeZone::getCanonicalID »
  • PHP Manual
  • IntlTimeZone
  • Create a timezone object from DateTimeZone

IntlTimeZone::fromDateTimeZone

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::fromDateTimeZone — Create a timezone object from DateTimeZone

Description

public static IntlTimeZone::fromDateTimeZone ( DateTimeZone $zoneId ) : IntlTimeZone

Warning

This function is currently not documented; only its argument list is available.

Parameters

zoneId

Return Values


Get the canonical system timezone ID or the normalized custom time zone ID for the given time zone ID

  • « IntlTimeZone::fromDateTimeZone
  • IntlTimeZone::getDisplayName »
  • PHP Manual
  • IntlTimeZone
  • Get the canonical system timezone ID or the normalized custom time zone ID for the given time zone ID

IntlTimeZone::getCanonicalID

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::getCanonicalID — Get the canonical system timezone ID or the normalized custom time zone ID for the given time zone ID

Description

public static IntlTimeZone::getCanonicalID ( string $zoneId [, bool &$isSystemID ] ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

zoneId

isSystemID

Return Values


Get a name of this time zone suitable for presentation to the user

  • « IntlTimeZone::getCanonicalID
  • IntlTimeZone::getDSTSavings »
  • PHP Manual
  • IntlTimeZone
  • Get a name of this time zone suitable for presentation to the user

IntlTimeZone::getDisplayName

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::getDisplayName — Get a name of this time zone suitable for presentation to the user

Description

public IntlTimeZone::getDisplayName ([ bool $isDaylight [, int $style [, string $locale ]]] ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

isDaylight

style

locale

Return Values


Get the amount of time to be added to local standard time to get local wall clock time

  • « IntlTimeZone::getDisplayName
  • IntlTimeZone::getEquivalentID »
  • PHP Manual
  • IntlTimeZone
  • Get the amount of time to be added to local standard time to get local wall clock time

IntlTimeZone::getDSTSavings

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::getDSTSavings — Get the amount of time to be added to local standard time to get local wall clock time

Description

public IntlTimeZone::getDSTSavings ( void ) : int

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Get an ID in the equivalency group that includes the given ID

  • « IntlTimeZone::getDSTSavings
  • IntlTimeZone::getErrorCode »
  • PHP Manual
  • IntlTimeZone
  • Get an ID in the equivalency group that includes the given ID

IntlTimeZone::getEquivalentID

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::getEquivalentID — Get an ID in the equivalency group that includes the given ID

Description

public static IntlTimeZone::getEquivalentID ( string $zoneId , int $index ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

zoneId

index

Return Values


Get last error code on the object

  • « IntlTimeZone::getEquivalentID
  • IntlTimeZone::getErrorMessage »
  • PHP Manual
  • IntlTimeZone
  • Get last error code on the object

IntlTimeZone::getErrorCode

intltz_get_error_code

(PHP 5 >= 5.5.0, PHP 7, 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 ( void ) : int

Procedural style:

intltz_get_error_code ( void ) : int

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Get last error message on the object

  • « IntlTimeZone::getErrorCode
  • IntlTimeZone::getGMT »
  • PHP Manual
  • IntlTimeZone
  • Get last error message on the object

IntlTimeZone::getErrorMessage

intltz_get_error_message

(PHP 5 >= 5.5.0, PHP 7, 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 ( void ) : string

Procedural style:

intltz_get_error_message ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Create GMT (UTC) timezone

  • « IntlTimeZone::getErrorMessage
  • IntlTimeZone::getID »
  • PHP Manual
  • IntlTimeZone
  • Create GMT (UTC) timezone

IntlTimeZone::getGMT

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::getGMT — Create GMT (UTC) timezone

Description

public static IntlTimeZone::getGMT ( void ) : IntlTimeZone

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Get timezone ID

  • « IntlTimeZone::getGMT
  • IntlTimeZone::getIDForWindowsID »
  • PHP Manual
  • IntlTimeZone
  • Get timezone ID

IntlTimeZone::getID

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::getID — Get timezone ID

Description

public IntlTimeZone::getID ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Translate a Windows timezone into a system timezone

  • « IntlTimeZone::getID
  • IntlTimeZone::getOffset »
  • PHP Manual
  • IntlTimeZone
  • Translate a Windows timezone into a system timezone

IntlTimeZone::getIDForWindowsID

(PHP 7 >= 7.1.0)

IntlTimeZone::getIDForWindowsID — Translate a Windows timezone into a system timezone

Description

public static IntlTimeZone::getIDForWindowsID ( string $timezone [, string $region ] ) : string

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

timezone

region

Return Values

Returns the system timezone or FALSE on failure.

See Also

  • IntlTimeZone::getWindowsID() - Translate a system timezone into a Windows timezone


Get the time zone raw and GMT offset for the given moment in time

  • « IntlTimeZone::getIDForWindowsID
  • IntlTimeZone::getRawOffset »
  • PHP Manual
  • IntlTimeZone
  • Get the time zone raw and GMT offset for the given moment in time

IntlTimeZone::getOffset

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::getOffset — Get the time zone raw and GMT offset for the given moment in time

Description

public IntlTimeZone::getOffset ( float $date , bool $local , int &$rawOffset , int &$dstOffset ) : int

Warning

This function is currently not documented; only its argument list is available.

Parameters

date

local

rawOffset

dstOffset

Return Values


Get the raw GMT offset (before taking daylight savings time into account

  • « IntlTimeZone::getOffset
  • IntlTimeZone::getRegion »
  • PHP Manual
  • IntlTimeZone
  • Get the raw GMT offset (before taking daylight savings time into account

IntlTimeZone::getRawOffset

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::getRawOffset — Get the raw GMT offset (before taking daylight savings time into account

Description

public IntlTimeZone::getRawOffset ( void ) : int

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Get the region code associated with the given system time zone ID

  • « IntlTimeZone::getRawOffset
  • IntlTimeZone::getTZDataVersion »
  • PHP Manual
  • IntlTimeZone
  • Get the region code associated with the given system time zone ID

IntlTimeZone::getRegion

(PHP 5 >= 5.5.0, PHP 7)

IntlTimeZone::getRegion — Get the region code associated with the given system time zone ID

Description

public static IntlTimeZone::getRegion ( string $zoneId ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

zoneId

Return Values

Return region or FALSE on failure.


Get the timezone data version currently used by ICU

  • « IntlTimeZone::getRegion
  • IntlTimeZone::getUnknown »
  • PHP Manual
  • IntlTimeZone
  • Get the timezone data version currently used by ICU

IntlTimeZone::getTZDataVersion

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::getTZDataVersion — Get the timezone data version currently used by ICU

Description

public static IntlTimeZone::getTZDataVersion ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Get the "unknown" time zone

  • « IntlTimeZone::getTZDataVersion
  • IntlTimeZone::getWindowsID »
  • PHP Manual
  • IntlTimeZone
  • Get the "unknown" time zone

IntlTimeZone::getUnknown

(PHP 5 >= 5.5.0, PHP 7)

IntlTimeZone::getUnknown — Get the "unknown" time zone

Description

public static IntlTimeZone::getUnknown ( void ) : 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.


Translate a system timezone into a Windows timezone

  • « IntlTimeZone::getUnknown
  • IntlTimeZone::hasSameRules »
  • PHP Manual
  • IntlTimeZone
  • Translate a system timezone into a Windows timezone

IntlTimeZone::getWindowsID

(PHP 7 >= 7.1.0)

IntlTimeZone::getWindowsID — Translate a system timezone into a Windows timezone

Description

public static IntlTimeZone::getWindowsID ( string $timezone ) : string

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

timezone

Return Values

Returns the Windows timezone or FALSE on failure.

See Also

  • IntlTimeZone::getIDForWindowsID() - Translate a Windows timezone into a system timezone


Check if this zone has the same rules and offset as another zone

  • « IntlTimeZone::getWindowsID
  • IntlTimeZone::toDateTimeZone »
  • PHP Manual
  • IntlTimeZone
  • Check if this zone has the same rules and offset as another zone

IntlTimeZone::hasSameRules

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::hasSameRules — Check if this zone has the same rules and offset as another zone

Description

public IntlTimeZone::hasSameRules ( IntlTimeZone $otherTimeZone ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

otherTimeZone

Return Values


Convert to DateTimeZone object

  • « IntlTimeZone::hasSameRules
  • IntlTimeZone::useDaylightTime »
  • PHP Manual
  • IntlTimeZone
  • Convert to DateTimeZone object

IntlTimeZone::toDateTimeZone

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::toDateTimeZone — Convert to DateTimeZone object

Description

public IntlTimeZone::toDateTimeZone ( void ) : DateTimeZone

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Check if this time zone uses daylight savings time

  • « IntlTimeZone::toDateTimeZone
  • IntlDateFormatter »
  • PHP Manual
  • IntlTimeZone
  • Check if this time zone uses daylight savings time

IntlTimeZone::useDaylightTime

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

IntlTimeZone::useDaylightTime — Check if this time zone uses daylight savings time

Description

public IntlTimeZone::useDaylightTime ( void ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The IntlDateFormatter class

(PHP 5 >= 5.3.0, PHP 7, 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

IntlDateFormatter {
/* Methods */
public __construct ( string $locale , int $datetype , int $timetype [, mixed $timezone = NULL [, mixed $calendar = NULL [, string $pattern = "" ]]] )
public static create ( string $locale , int $datetype , int $timetype [, mixed $timezone = NULL [, mixed $calendar = NULL [, string $pattern = "" ]]] ) : IntlDateFormatter
public format ( mixed $value ) : string
public static formatObject ( object $object [, mixed $format = NULL [, string $locale = NULL ]] ) : string
getCalendar ( void ) : int
public getDateType ( void ) : int
public getErrorCode ( void ) : int
public getErrorMessage ( void ) : string
public getLocale ([ int $which ] ) : string
public getPattern ( void ) : string
public getTimeType ( void ) : int
public getTimeZoneId ( void ) : string
public getCalendarObject ( void ) : IntlCalendar
public getTimeZone ( void ) : IntlTimeZone
public isLenient ( void ) : bool
public localtime ( string $value [, int &$position ] ) : array
public parse ( string $value [, int &$position ] ) : int
setCalendar ( mixed $which ) : bool
public setLenient ( bool $lenient ) : bool
public setPattern ( string $pattern ) : bool
public setTimeZoneId ( string $zone ) : bool
public setTimeZone ( mixed $zone ) : bool
}

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 (integer)
Do not include this element
IntlDateFormatter::FULL (integer)
Completely specified style (Tuesday, April 12, 1952 AD or 3:30:42pm PST)
IntlDateFormatter::LONG (integer)
Long style (January 12, 1952 or 3:30:32pm)
IntlDateFormatter::MEDIUM (integer)
Medium style (Jan 12, 1952)
IntlDateFormatter::SHORT (integer)
Most abbreviated style, only essential data (12/13/52 or 3:30pm)

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 (integer)
Non-Gregorian Calendar
IntlDateFormatter::GREGORIAN (integer)
Gregorian Calendar

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::setTimeZoneId — Sets the time zone to use
  • IntlDateFormatter::setTimeZone — Sets formatterʼs timezone


Create a date formatter

  • « IntlDateFormatter
  • IntlDateFormatter::format »
  • PHP Manual
  • IntlDateFormatter
  • Create a date formatter

IntlDateFormatter::create

datefmt_create

IntlDateFormatter::__construct

(PHP 5 >= 5.3.0, PHP 7, 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 , int $timetype [, mixed $timezone = NULL [, mixed $calendar = NULL [, string $pattern = "" ]]] ) : IntlDateFormatter

Object oriented style (constructor)

public IntlDateFormatter::__construct ( string $locale , int $datetype , int $timetype [, mixed $timezone = NULL [, mixed $calendar = NULL [, string $pattern = "" ]]] )

Procedural style

datefmt_create ( string $locale , int $datetype , int $timetype [, mixed $timezone = NULL [, mixed $calendar = NULL [, string $pattern = "" ]]] ) : 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

Date type to use (none, short, medium, long, full). This is one of the IntlDateFormatter constants. It can also be NULL, in which case ICUʼs default date type will be used.

timetype

Time type to use (none, short, medium, long, full). This is one of the IntlDateFormatter constants. It can also be NULL, in which case ICUʼs default time type will be used.

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 » http://userguide.icu-project.org/formatparse/datetime.

Return Values

The created IntlDateFormatter or FALSE in case of failure.

Changelog

Version | Description
5.5.0/PECL 3.0.0 | An IntlCalendar object is allowed for calendar. Objects of type IntlTimeZone and DateTimeZone are allowed for timezone. Invalid timezone identifiers (including empty strings) are no longer allowed for timezone. If NULL is given for timezone, the timezone identifier given by date_default_timezone_get() will be used instead of ICUʼs default.

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);
?>

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


Format the date/time value as a string

  • « IntlDateFormatter::create
  • IntlDateFormatter::formatObject »
  • PHP Manual
  • IntlDateFormatter
  • Format the date/time value as a string

IntlDateFormatter::format

datefmt_format

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

IntlDateFormatter::format -- datefmt_format — Format the date/time value as a string

Description

Object oriented style

public IntlDateFormatter::format ( mixed $value ) : string

Procedural style

datefmt_format ( IntlDateFormatter $fmt , mixed $value ) : string

Formats the time value as a string.

Parameters

fmt

The date formatter resource.

value

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 value parameter was added. Formerly, only proper DateTime objects were supported.
5.5.0/PECL 3.0.0 | Support for providing IntlCalendar objects to the value parameter was added.
5.3.4 | Support for providing DateTime objects to the value 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


Formats an object

  • « IntlDateFormatter::format
  • IntlDateFormatter::getCalendar »
  • PHP Manual
  • IntlDateFormatter
  • Formats an object

IntlDateFormatter::formatObject

datefmt_format_object

(PHP 5 >= 5.5.0, PHP 7, PECL intl >= 3.0.0)

IntlDateFormatter::formatObject -- datefmt_format_object — Formats an object

Description

Object oriented style

public static IntlDateFormatter::formatObject ( object $object [, mixed $format = NULL [, string $locale = NULL ]] ) : string

Procedural style

public static datefmt_format_object ( object $object [, mixed $format = NULL [, string $locale = NULL ]] ) : string

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

object

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 integer 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


Get the calendar type used for the IntlDateFormatter

  • « IntlDateFormatter::formatObject
  • IntlDateFormatter::getDateType »
  • PHP Manual
  • IntlDateFormatter
  • Get the calendar type used for the IntlDateFormatter

IntlDateFormatter::getCalendar

datefmt_get_calendar

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

IntlDateFormatter::getCalendar -- datefmt_get_calendar — Get the calendar type used for the IntlDateFormatter

Description

Object oriented style

IntlDateFormatter::getCalendar ( void ) : int

Procedural style

datefmt_get_calendar ( IntlDateFormatter $fmt ) : int

Parameters

fmt

The formatter resource

Return Values

The calendar type being used by the formatter. Either IntlDateFormatter::TRADITIONAL or IntlDateFormatter::GREGORIAN.

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();

?>

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


Get the datetype used for the IntlDateFormatter

  • « IntlDateFormatter::getCalendar
  • IntlDateFormatter::getErrorCode »
  • PHP Manual
  • IntlDateFormatter
  • Get the datetype used for the IntlDateFormatter

IntlDateFormatter::getDateType

datefmt_get_datetype

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

IntlDateFormatter::getDateType -- datefmt_get_datetype — Get the datetype used for the IntlDateFormatter

Description

Object oriented style

public IntlDateFormatter::getDateType ( void ) : int

Procedural style

datefmt_get_datetype ( IntlDateFormatter $fmt ) : int

Returns date type used by the formatter.

Parameters

fmt

The formatter resource.

Return Values

The current date type value of the formatter.

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


Get the error code from last operation

  • « IntlDateFormatter::getDateType
  • IntlDateFormatter::getErrorMessage »
  • PHP Manual
  • IntlDateFormatter
  • Get the error code from last operation

IntlDateFormatter::getErrorCode

datefmt_get_error_code

(PHP 5 >= 5.3.0, PHP 7, 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 ( void ) : int

Procedural style

datefmt_get_error_code ( IntlDateFormatter $fmt ) : int

Get the error code from last operation. Returns error code from the last number formatting operation.

Parameters

fmt

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);
if (!$str) {
    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();
if (!$str) {
    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


Get the error text from the last operation

  • « IntlDateFormatter::getErrorCode
  • IntlDateFormatter::getLocale »
  • PHP Manual
  • IntlDateFormatter
  • Get the error text from the last operation

IntlDateFormatter::getErrorMessage

datefmt_get_error_message

(PHP 5 >= 5.3.0, PHP 7, 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 ( void ) : string

Procedural style

datefmt_get_error_message ( IntlDateFormatter $fmt ) : string

Get the error text from the last operation.

Parameters

fmt

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);
if (!$str) {
    prtinf(
        "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();
if(!$str) {
    prtinf(
        "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


Get the locale used by formatter

  • « IntlDateFormatter::getErrorMessage
  • IntlDateFormatter::getPattern »
  • PHP Manual
  • IntlDateFormatter
  • Get the locale used by formatter

IntlDateFormatter::getLocale

datefmt_get_locale

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

IntlDateFormatter::getLocale -- datefmt_get_locale — Get the locale used by formatter

Description

Object oriented style

public IntlDateFormatter::getLocale ([ int $which ] ) : string

Procedural style

datefmt_get_locale ( IntlDateFormatter $fmt [, int $which ] ) : string

Get locale used by the formatter.

Parameters

fmt

The formatter resource

hich

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' if error

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


Get the pattern used for the IntlDateFormatter

  • « IntlDateFormatter::getLocale
  • IntlDateFormatter::getTimeType »
  • PHP Manual
  • IntlDateFormatter
  • Get the pattern used for the IntlDateFormatter

IntlDateFormatter::getPattern

datefmt_get_pattern

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

IntlDateFormatter::getPattern -- datefmt_get_pattern — Get the pattern used for the IntlDateFormatter

Description

Object oriented style

public IntlDateFormatter::getPattern ( void ) : string

Procedural style

datefmt_get_pattern ( IntlDateFormatter $fmt ) : string

Get pattern used by the formatter.

Parameters

fmt

The formatter resource.

Return Values

The pattern string being used to format/parse.

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


Get the timetype used for the IntlDateFormatter

  • « IntlDateFormatter::getPattern
  • IntlDateFormatter::getTimeZoneId »
  • PHP Manual
  • IntlDateFormatter
  • Get the timetype used for the IntlDateFormatter

IntlDateFormatter::getTimeType

datefmt_get_timetype

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

IntlDateFormatter::getTimeType -- datefmt_get_timetype — Get the timetype used for the IntlDateFormatter

Description

Object oriented style

public IntlDateFormatter::getTimeType ( void ) : int

Procedural style

datefmt_get_timetype ( IntlDateFormatter $fmt ) : int

Return time type used by the formatter.

Parameters

fmt

The formatter resource.

Return Values

The current date type value of the formatter.

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


Get the timezone-id used for the IntlDateFormatter

  • « IntlDateFormatter::getTimeType
  • IntlDateFormatter::getCalendarObject »
  • PHP Manual
  • IntlDateFormatter
  • Get the timezone-id used for the IntlDateFormatter

IntlDateFormatter::getTimeZoneId

datefmt_get_timezone_id

(PHP 5 >= 5.3.0, PHP 7, 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 ( void ) : string

Procedural style

datefmt_get_timezone_id ( IntlDateFormatter $fmt ) : string

Get the timezone-id used for the IntlDateFormatter.

Parameters

fmt

The formatter resource.

Return Values

ID string for the time zone used by this formatter.

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);
datefmt_set_timezone_id($fmt, 'CN');
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();
$fmt->setTimezoneId('CN');
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 : CN

See Also

  • datefmt_set_timezone_id() - Sets the time zone to use
  • datefmt_create() - Create a date formatter


Get copy of formatterʼs calendar object

  • « IntlDateFormatter::getTimeZoneId
  • IntlDateFormatter::getTimeZone »
  • PHP Manual
  • IntlDateFormatter
  • Get copy of formatterʼs calendar object

IntlDateFormatter::getCalendarObject

datefmt_get_calendar_object

(PHP 5 >= 5.5.0, PHP 7, 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 ( void ) : IntlCalendar

Procedural style

datefmt_get_calendar_object ( void ) : IntlCalendar

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.

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


Get formatterʼs timezone

  • « IntlDateFormatter::getCalendarObject
  • IntlDateFormatter::isLenient »
  • PHP Manual
  • IntlDateFormatter
  • Get formatterʼs timezone

IntlDateFormatter::getTimeZone

datefmt_get_timezone

(PHP 5 >= 5.5.0, PHP 7, PECL intl >= 3.0.0)

IntlDateFormatter::getTimeZone -- datefmt_get_timezone — Get formatterʼs timezone

Description

Object oriented style

public IntlDateFormatter::getTimeZone ( void ) : IntlTimeZone

Procedural style

datefmt_get_timezone ( void ) : IntlTimeZone

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


Get the lenient used for the IntlDateFormatter

  • « IntlDateFormatter::getTimeZone
  • IntlDateFormatter::localtime »
  • PHP Manual
  • IntlDateFormatter
  • Get the lenient used for the IntlDateFormatter

IntlDateFormatter::isLenient

datefmt_is_lenient

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

IntlDateFormatter::isLenient -- datefmt_is_lenient — Get the lenient used for the IntlDateFormatter

Description

Object oriented style

public IntlDateFormatter::isLenient ( void ) : bool

Procedural style

datefmt_is_lenient ( IntlDateFormatter $fmt ) : bool

Check if the parser is strict or lenient in interpreting inputs that do not match the pattern exactly.

Parameters

fmt

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


Parse string to a field-based time value

  • « IntlDateFormatter::isLenient
  • IntlDateFormatter::parse »
  • PHP Manual
  • IntlDateFormatter
  • Parse string to a field-based time value

IntlDateFormatter::localtime

datefmt_localtime

(PHP 5 >= 5.3.0, PHP 7, 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 $value [, int &$position ] ) : array

Procedural style

datefmt_localtime ( IntlDateFormatter $fmt , string $value [, int &$position ] ) : array

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

fmt

The formatter resource

value

string to convert to a time

position

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

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 4:00:00 PM PT', 0);
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 4:00:00 PM PT', 0);
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 : 1969 ,
tm_mday : 31 , tm_wday : 4 , 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


Parse string to a timestamp value

  • « IntlDateFormatter::localtime
  • IntlDateFormatter::setCalendar »
  • PHP Manual
  • IntlDateFormatter
  • Parse string to a timestamp value

IntlDateFormatter::parse

datefmt_parse

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

IntlDateFormatter::parse -- datefmt_parse — Parse string to a timestamp value

Description

Object oriented style

public IntlDateFormatter::parse ( string $value [, int &$position ] ) : int

Procedural style

datefmt_parse ( IntlDateFormatter $fmt , string $value [, int &$position ] ) : int

Converts string $value to an incremental time value, starting at $parse_pos and consuming as much of the input value as possible.

Parameters

fmt

The formatter resource

value

string to convert to a time

position

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 (and the error occurred). This variable will contain the end position if the parse fails. If $parse_pos > strlen($value), the parse fails immediately.

Return Values

timestamp parsed value, or FALSE if value can't 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


Sets the calendar type used by the formatter

  • « IntlDateFormatter::parse
  • IntlDateFormatter::setLenient »
  • PHP Manual
  • IntlDateFormatter
  • Sets the calendar type used by the formatter

IntlDateFormatter::setCalendar

datefmt_set_calendar

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

IntlDateFormatter::setCalendar -- datefmt_set_calendar — Sets the calendar type used by the formatter

Description

Object oriented style

IntlDateFormatter::setCalendar ( mixed $which ) : bool

Procedural style

datefmt_set_calendar ( IntlDateFormatter $fmt , mixed $which ) : bool

Sets the calendar or calendar type used by the formatter.

Parameters

fmt

The formatter resource.

which

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
5.5.0/PECL 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


Set the leniency of the parser

  • « IntlDateFormatter::setCalendar
  • IntlDateFormatter::setPattern »
  • PHP Manual
  • IntlDateFormatter
  • Set the leniency of the parser

IntlDateFormatter::setLenient

datefmt_set_lenient

(PHP 5 >= 5.3.0, PHP 7, 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 ) : bool

Procedural style

datefmt_set_lenient ( IntlDateFormatter $fmt , bool $lenient ) : bool

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

fmt

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


Set the pattern used for the IntlDateFormatter

  • « IntlDateFormatter::setLenient
  • IntlDateFormatter::setTimeZoneId »
  • PHP Manual
  • IntlDateFormatter
  • Set the pattern used for the IntlDateFormatter

IntlDateFormatter::setPattern

datefmt_set_pattern

(PHP 5 >= 5.3.0, PHP 7, 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 $fmt , string $pattern ) : bool

Set the pattern used for the IntlDateFormatter.

Parameters

fmt

The formatter resource.

pattern

New pattern string to use. Possible patterns are documented at » http://userguide.icu-project.org/formatparse/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);
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 with pattern is 12/31/1969
Now pattern of the formatter is : yyyymmdd hh:mm:ss z
Second Formatted output with pattern is 19690031 04:00:00 PST

See Also

  • datefmt_get_pattern() - Get the pattern used for the IntlDateFormatter
  • datefmt_create() - Create a date formatter


Sets the time zone to use

  • « IntlDateFormatter::setPattern
  • IntlDateFormatter::setTimeZone »
  • PHP Manual
  • IntlDateFormatter
  • Sets the time zone to use

IntlDateFormatter::setTimeZoneId

datefmt_set_timezone_id

(PHP 5 >= 5.3.0, PECL intl >= 1.0.0)

IntlDateFormatter::setTimeZoneId -- datefmt_set_timezone_id — Sets the time zone to use

Warning

This function was DEPRECATED in PHP 5.5.0, and REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • IntlDateFormatter::setTimeZone()

Description

Object oriented style

public IntlDateFormatter::setTimeZoneId ( string $zone ) : bool

Procedural style

datefmt_set_timezone_id ( IntlDateFormatter $fmt , string $zone ) : bool

Sets the time zone to use.

Parameters

fmt

The formatter resource.

zone

The time zone ID string of the time zone to use. If NULL or the empty string, the default time zone for the runtime is used.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.0.0 | This function has been removed.
5.5.0 | This function has been deprecated.

Examples

Example #1 datefmt_set_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);
datefmt_set_timezone_id($fmt, 'CN');
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();
$fmt->setTimezoneId('CN');
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 : CN

See Also

  • datefmt_get_timezone_id() - Get the timezone-id used for the IntlDateFormatter
  • datefmt_create() - Create a date formatter


Sets formatterʼs timezone

  • « IntlDateFormatter::setTimeZoneId
  • ResourceBundle »
  • PHP Manual
  • IntlDateFormatter
  • Sets formatterʼs timezone

IntlDateFormatter::setTimeZone

datefmt_set_timezone

(PHP 5 >= 5.5.0, PHP 7, PECL intl >= 3.0.0)

IntlDateFormatter::setTimeZone -- datefmt_set_timezone — Sets formatterʼs timezone

Description

Object oriented style

public IntlDateFormatter::setTimeZone ( mixed $zone ) : bool

Procedural style

datefmt_set_timezone ( IntlDateFormatter $fmt , mixed $zone ) : bool

Sets the timezone used for the IntlDateFormatter. object.

Parameters

fmt

The formatter resource.

zone

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 and FALSE on failure.

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


The ResourceBundle class

(PHP 5 >= 5.3.2, PHP 7, 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

ResourceBundle {
/* Methods */
public __construct ( string $locale , string $bundlename [, bool $fallback ] )
public count ( void ) : int
public static create ( string $locale , string $bundlename [, bool $fallback ] ) : ResourceBundle
public getErrorCode ( void ) : int
public getErrorMessage ( void ) : string
public get ( string|int $index [, bool $fallback = TRUE ] ) : mixed
public getLocales ( string $bundlename ) : array
}

See Also

  • » ICU Resource Management
  • » ICU Data

Table of Contents

  • ResourceBundle::count — Get number of elements in the bundle
  • ResourceBundle::create — Create a resource bundle
  • ResourceBundle::getErrorCode — Get bundle's last error code
  • ResourceBundle::getErrorMessage — Get bundle's last error message
  • ResourceBundle::get — Get data from the bundle
  • ResourceBundle::getLocales — Get supported locales


Get number of elements in the bundle

  • « ResourceBundle
  • ResourceBundle::create »
  • PHP Manual
  • ResourceBundle
  • Get number of elements in the bundle

ResourceBundle::count

resourcebundle_count

(PHP 5 >= 5.3.2, PHP 7, PECL intl >= 2.0.0)

ResourceBundle::count -- resourcebundle_count — Get number of elements in the bundle

Description

Object oriented style

public ResourceBundle::count ( void ) : int

Procedural style

resourcebundle_count ( ResourceBundle $r ) : int

Get the number of elements in the bundle.

Parameters

r

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


Create a resource bundle

  • « ResourceBundle::count
  • ResourceBundle::getErrorCode »
  • PHP Manual
  • ResourceBundle
  • Create a resource bundle

ResourceBundle::create

resourcebundle_create

ResourceBundle::__construct

(PHP 5 >= 5.3.2, PHP 7, 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 $bundlename [, bool $fallback ] ) : ResourceBundle

Procedural style

resourcebundle_create ( string $locale , string $bundlename [, bool $fallback ] ) : ResourceBundle

Object oriented style (constructor):

public ResourceBundle::__construct ( string $locale , string $bundlename [, bool $fallback ] )

Creates a resource bundle.

Parameters

locale

Locale for which the resources should be loaded (locale name, e.g. en_CA).

bundlename

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


Get bundle's last error code

  • « ResourceBundle::create
  • ResourceBundle::getErrorMessage »
  • PHP Manual
  • ResourceBundle
  • Get bundle's last error code

ResourceBundle::getErrorCode

resourcebundle_get_error_code

(PHP 5 >= 5.3.2, PHP 7, PECL intl >= 2.0.0)

ResourceBundle::getErrorCode -- resourcebundle_get_error_code — Get bundle's last error code

Description

Object oriented style

public ResourceBundle::getErrorCode ( void ) : int

Procedural style

resourcebundle_get_error_code ( ResourceBundle $r ) : int

Get error code from the last function performed by the bundle object.

Parameters

r

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


Get bundle's last error message

  • « ResourceBundle::getErrorCode
  • ResourceBundle::get »
  • PHP Manual
  • ResourceBundle
  • Get bundle's last error message

ResourceBundle::getErrorMessage

resourcebundle_get_error_message

(PHP 5 >= 5.3.2, PHP 7, PECL intl >= 2.0.0)

ResourceBundle::getErrorMessage -- resourcebundle_get_error_message — Get bundle's last error message

Description

Object oriented style

public ResourceBundle::getErrorMessage ( void ) : string

Procedural style

resourcebundle_get_error_message ( ResourceBundle $r ) : string

Get error message from the last function performed by the bundle object.

Parameters

r

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


Get data from the bundle

  • « ResourceBundle::getErrorMessage
  • ResourceBundle::getLocales »
  • PHP Manual
  • ResourceBundle
  • Get data from the bundle

ResourceBundle::get

resourcebundle_get

(PHP 5 >= 5.3.2, PHP 7, 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 ] ) : mixed

Procedural style

resourcebundle_get ( ResourceBundle $r , string|int $index [, bool $fallback = TRUE ] ) : mixed

Get the data from the bundle by index or string key.

Parameters

r

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.

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


Get supported locales

  • « ResourceBundle::get
  • Spoofchecker »
  • PHP Manual
  • ResourceBundle
  • Get supported locales

ResourceBundle::getLocales

resourcebundle_locales

(PHP 5 >= 5.3.2, PHP 7, PECL intl >= 2.0.0)

ResourceBundle::getLocales -- resourcebundle_locales — Get supported locales

Description

Object oriented style

public ResourceBundle::getLocales ( string $bundlename ) : array

Procedural style

resourcebundle_locales ( string $bundlename ) : array

Get available locales from ResourceBundle name.

Parameters

bundlename

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.

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


The Spoofchecker class

(PHP 5 >= 5.4.0, PHP 7, 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

Spoofchecker {
/* Constants */
const number ASCII = 0x10000000 ;
const number HIGHLY_RESTRICTIVE = 0x30000000 ;
const number MODERATELY_RESTRICTIVE = 0x40000000 ;
const number MINIMALLY_RESTRICTIVE = 0x50000000 ;
const number UNRESTRICTIVE = 0x60000000 ;
const number SINGLE_SCRIPT_RESTRICTIVE = 0x20000000 ;
const integer SINGLE_SCRIPT_CONFUSABLE = 1 ;
const integer MIXED_SCRIPT_CONFUSABLE = 2 ;
const integer WHOLE_SCRIPT_CONFUSABLE = 4 ;
const integer ANY_CASE = 8 ;
const integer SINGLE_SCRIPT = 16 ;
const integer INVISIBLE = 32 ;
const integer CHAR_LIMIT = 64 ;
/* Methods */
public areConfusable ( string $str1 , string $str2 [, string &$error ] ) : bool
public __construct ( void )
public isSuspicious ( string $text [, string &$error ] ) : bool
public setAllowedLocales ( string $locale_list ) : void
public setChecks ( int $checks ) : void
}

Predefined Constants

Spoofchecker::ASCII

Spoofchecker::HIGHLY_RESTRICTIVE

Spoofchecker::MODERATELY_RESTRICTIVE

Spoofchecker::MINIMALLY_RESTRICTIVE

Spoofchecker::UNRESTRICTIVE

Spoofchecker::SINGLE_SCRIPT_RESTRICTIVE

Spoofchecker::SINGLE_SCRIPT_CONFUSABLE

Spoofchecker::MIXED_SCRIPT_CONFUSABLE

Spoofchecker::WHOLE_SCRIPT_CONFUSABLE

Spoofchecker::ANY_CASE

Spoofchecker::SINGLE_SCRIPT

Spoofchecker::INVISIBLE

Spoofchecker::CHAR_LIMIT

Changelog

Version | Description
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.

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


Checks if given strings can be confused

  • « Spoofchecker
  • Spoofchecker::__construct »
  • PHP Manual
  • Spoofchecker
  • Checks if given strings can be confused

Spoofchecker::areConfusable

(PHP 5 >= 5.4.0, PHP 7, PECL intl >= 2.0.0)

Spoofchecker::areConfusable — Checks if given strings can be confused

Description

public Spoofchecker::areConfusable ( string $str1 , string $str2 [, string &$error ] ) : bool

Checks whether two given strings can easily be mistaken.

Parameters

str1

First string to check.

str2

Second string to check.

error

This variable is set by-reference to string containing an error, if there were 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


Constructor

  • « Spoofchecker::areConfusable
  • Spoofchecker::isSuspicious »
  • PHP Manual
  • Spoofchecker
  • Constructor

Spoofchecker::__construct

(PHP 5 >= 5.4.0, PHP 7, PECL intl >= 2.0.0)

Spoofchecker::__construct — Constructor

Description

public Spoofchecker::__construct ( void )

Creates new instance of Spoofchecker.

Parameters

This function has no parameters.

Return Values

Returns Spoofchecker instance.


Checks if a given text contains any suspicious characters

  • « Spoofchecker::__construct
  • Spoofchecker::setAllowedLocales »
  • PHP Manual
  • Spoofchecker
  • Checks if a given text contains any suspicious characters

Spoofchecker::isSuspicious

(PHP 5 >= 5.4.0, PHP 7, PECL intl >= 2.0.0)

Spoofchecker::isSuspicious — Checks if a given text contains any suspicious characters

Description

public Spoofchecker::isSuspicious ( string $text [, string &$error ] ) : bool

Checks if given string contains any suspicious characters like letters which are almost identical visually, but are Unicode characters from different sets.

Parameters

text

String to test.

error

This variable is set by-reference to string containing an error, if there were 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"


Locales to use when running checks

  • « Spoofchecker::isSuspicious
  • Spoofchecker::setChecks »
  • PHP Manual
  • Spoofchecker
  • Locales to use when running checks

Spoofchecker::setAllowedLocales

(PHP 5 >= 5.4.0, PHP 7, PECL intl >= 2.0.0)

Spoofchecker::setAllowedLocales — Locales to use when running checks

Description

public Spoofchecker::setAllowedLocales ( string $locale_list ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

locale_list

Return Values


Set the checks to run

  • « Spoofchecker::setAllowedLocales
  • Transliterator »
  • PHP Manual
  • Spoofchecker
  • Set the checks to run

Spoofchecker::setChecks

(PHP 5 >= 5.4.0, PHP 7, PECL intl >= 2.0.0)

Spoofchecker::setChecks — Set the checks to run

Description

public Spoofchecker::setChecks ( int $checks ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

checks

Return Values


The Transliterator class

(PHP 5 >= 5.4.0, PHP 7, PECL intl >= 2.0.0)

Introduction

Transliterator provides transliteration of strings.

Class synopsis

Transliterator {
/* Constants */
const integer FORWARD = 0 ;
const integer REVERSE = 1 ;
/* Properties */
public $id ;
/* Methods */
__construct ( void )
public static create ( string $id [, int $direction ] ) : Transliterator
public static createFromRules ( string $rules [, string $direction ] ) : Transliterator
public createInverse ( void ) : Transliterator
public getErrorCode ( void ) : int
public getErrorMessage ( void ) : string
public static listIDs ( void ) : array
public transliterate ( string $subject [, int $start [, int $end ]] ) : string
}

Properties

id

Predefined Constants

Transliterator::FORWARD

Transliterator::REVERSE

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


Private constructor to deny instantiation

  • « Transliterator
  • Transliterator::create »
  • PHP Manual
  • Transliterator
  • Private constructor to deny instantiation

Transliterator::__construct

(PHP 5 >= 5.4.0, PHP 7, PECL intl >= 2.0.0)

Transliterator::__construct — Private constructor to deny instantiation

Description

Transliterator::__construct ( void )

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.

Return Values

This method should not be executed. If it is (e.g. through reflection), then its return value is unspecified.

See Also

  • Transliterator::create() - Create a transliterator
  • Transliterator::createFromRules() - Create transliterator from rules


Create a transliterator

  • « Transliterator::__construct
  • Transliterator::createFromRules »
  • PHP Manual
  • Transliterator
  • Create a transliterator

Transliterator::create

transliterator_create

(PHP 5 >= 5.4.0, PHP 7, 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

Procedural style

transliterator_create ( string $id [, int $direction ] ) : Transliterator

Opens a Transliterator by id.

Warning

This function is currently not documented; only its argument list is available.

Parameters

id

The id.

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


Create transliterator from rules

  • « Transliterator::create
  • Transliterator::createInverse »
  • PHP Manual
  • Transliterator
  • Create transliterator from rules

Transliterator::createFromRules

transliterator_create_from_rules

(PHP 5 >= 5.4.0, PHP 7, 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 [, string $direction ] ) : Transliterator

Procedural style

transliterator_create_from_rules ( string $id [, int $direction ] ) : Transliterator

Creates a Transliterator from rules.

Warning

This function is currently not documented; only its argument list is available.

Parameters

rules

The rules.

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


Create an inverse transliterator

  • « Transliterator::createFromRules
  • Transliterator::getErrorCode »
  • PHP Manual
  • Transliterator
  • Create an inverse transliterator

Transliterator::createInverse

transliterator_create_inverse

(PHP 5 >= 5.4.0, PHP 7, PECL intl >= 2.0.0)

Transliterator::createInverse -- transliterator_create_inverse — Create an inverse transliterator

Description

Object oriented style

public Transliterator::createInverse ( void ) : Transliterator

Procedural style

transliterator_create_inverse ( void ) : 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


Get last error code

  • « Transliterator::createInverse
  • Transliterator::getErrorMessage »
  • PHP Manual
  • Transliterator
  • Get last error code

Transliterator::getErrorCode

transliterator_get_error_code

(PHP 5 >= 5.4.0, PHP 7, PECL intl >= 2.0.0)

Transliterator::getErrorCode -- transliterator_get_error_code — Get last error code

Description

Object oriented style

public Transliterator::getErrorCode ( void ) : int

Procedural style

transliterator_get_error_code ( void ) : int

Gets the last error code for this transliterator.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

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


Get last error message

  • « Transliterator::getErrorCode
  • Transliterator::listIDs »
  • PHP Manual
  • Transliterator
  • Get last error message

Transliterator::getErrorMessage

transliterator_get_error_message

(PHP 5 >= 5.4.0, PHP 7, PECL intl >= 2.0.0)

Transliterator::getErrorMessage -- transliterator_get_error_message — Get last error message

Description

Object oriented style

public Transliterator::getErrorMessage ( void ) : string

Procedural style

transliterator_get_error_message ( void ) : string

Gets the last error message for this transliterator.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

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


Get transliterator IDs

  • « Transliterator::getErrorMessage
  • Transliterator::transliterate »
  • PHP Manual
  • Transliterator
  • Get transliterator IDs

Transliterator::listIDs

transliterator_list_ids

(PHP 5 >= 5.4.0, PHP 7, PECL intl >= 2.0.0)

Transliterator::listIDs -- transliterator_list_ids — Get transliterator IDs

Description

Object oriented style

public static Transliterator::listIDs ( void ) : array

Procedural style

transliterator_list_ids ( void ) : array

Returns an array with the registered transliterator IDs.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

An array of registered transliterator IDs on success, or FALSE on failure.

See Also

  • Transliterator::getErrorMessage() - Get last error message
  • Transliterator::transliterate() - Transliterate a string


Transliterate a string

  • « Transliterator::listIDs
  • IntlBreakIterator »
  • PHP Manual
  • Transliterator
  • Transliterate a string

Transliterator::transliterate

transliterator_transliterate

(PHP 5 >= 5.4.0, PHP 7, PECL intl >= 2.0.0)

Transliterator::transliterate -- transliterator_transliterate — Transliterate a string

Description

Object oriented style

public Transliterator::transliterate ( string $subject [, int $start [, int $end ]] ) : string

Procedural style

transliterator_transliterate ( mixed $transliterator , string $subject [, int $start [, int $end ]] )

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.

subject

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 transfomed 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


The IntlBreakIterator class

(PHP 5 >= 5.5.0, PHP 7)

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 Traversable. 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

IntlBreakIterator implements Traversable {
/* Constants */
const integer DONE = -1 ;
const integer WORD_NONE = 0 ;
const integer WORD_NONE_LIMIT = 100 ;
const integer WORD_NUMBER = 100 ;
const integer WORD_NUMBER_LIMIT = 200 ;
const integer WORD_LETTER = 200 ;
const integer WORD_LETTER_LIMIT = 300 ;
const integer WORD_KANA = 300 ;
const integer WORD_KANA_LIMIT = 400 ;
const integer WORD_IDEO = 400 ;
const integer WORD_IDEO_LIMIT = 500 ;
const integer LINE_SOFT = 0 ;
const integer LINE_SOFT_LIMIT = 100 ;
const integer LINE_HARD = 100 ;
const integer LINE_HARD_LIMIT = 200 ;
const integer SENTENCE_TERM = 0 ;
const integer SENTENCE_TERM_LIMIT = 100 ;
const integer SENTENCE_SEP = 100 ;
const integer SENTENCE_SEP_LIMIT = 200 ;
/* Methods */
private __construct ( void )
public static createCharacterInstance ([ string $locale ] ) : IntlBreakIterator
public static createCodePointInstance ( void ) : IntlBreakIterator
public static createLineInstance ([ string $locale ] ) : IntlBreakIterator
public static createSentenceInstance ([ string $locale ] ) : IntlBreakIterator
public static createTitleInstance ([ string $locale ] ) : IntlBreakIterator
public static createWordInstance ([ string $locale ] ) : IntlBreakIterator
public current ( void ) : int
public first ( void ) : int
public following ( int $offset ) : int
public getErrorCode ( void ) : int
intl_get_error_code ( void ) : int
public getErrorMessage ( void ) : string
intl_get_error_message ( void ) : string
public getLocale ( string $locale_type ) : string
public getPartsIterator ([ int $key_type = IntlPartsIterator::KEY_SEQUENTIAL ] ) : IntlPartsIterator
public getText ( void ) : string
public isBoundary ( int $offset ) : bool
public last ( void ) : int
public next ([ int $offset ] ) : int
public preceding ( int $offset ) : int
public previous ( void ) : int
public setText ( string $text ) : bool
}

Predefined Constants

IntlBreakIterator::DONE

IntlBreakIterator::WORD_NONE

IntlBreakIterator::WORD_NONE_LIMIT

IntlBreakIterator::WORD_NUMBER

IntlBreakIterator::WORD_NUMBER_LIMIT

IntlBreakIterator::WORD_LETTER

IntlBreakIterator::WORD_LETTER_LIMIT

IntlBreakIterator::WORD_KANA

IntlBreakIterator::WORD_KANA_LIMIT

IntlBreakIterator::WORD_IDEO

IntlBreakIterator::WORD_IDEO_LIMIT

IntlBreakIterator::LINE_SOFT

IntlBreakIterator::LINE_SOFT_LIMIT

IntlBreakIterator::LINE_HARD

IntlBreakIterator::LINE_HARD_LIMIT

IntlBreakIterator::SENTENCE_TERM

IntlBreakIterator::SENTENCE_TERM_LIMIT

IntlBreakIterator::SENTENCE_SEP

IntlBreakIterator::SENTENCE_SEP_LIMIT

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


Private constructor for disallowing instantiation

  • « IntlBreakIterator
  • IntlBreakIterator::createCharacterInstance »
  • PHP Manual
  • IntlBreakIterator
  • Private constructor for disallowing instantiation

IntlBreakIterator::__construct

(PHP 5 >= 5.5.0, PHP 7)

IntlBreakIterator::__construct — Private constructor for disallowing instantiation

Description

private IntlBreakIterator::__construct ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Create break iterator for boundaries of combining character sequences

  • « IntlBreakIterator::__construct
  • IntlBreakIterator::createCodePointInstance »
  • PHP Manual
  • IntlBreakIterator
  • Create break iterator for boundaries of combining character sequences

IntlBreakIterator::createCharacterInstance

(PHP 5 >= 5.5.0, PHP 7)

IntlBreakIterator::createCharacterInstance — Create break iterator for boundaries of combining character sequences

Description

public static IntlBreakIterator::createCharacterInstance ([ string $locale ] ) : IntlBreakIterator

Warning

This function is currently not documented; only its argument list is available.

Parameters

locale

Return Values


Create break iterator for boundaries of code points

  • « IntlBreakIterator::createCharacterInstance
  • IntlBreakIterator::createLineInstance »
  • PHP Manual
  • IntlBreakIterator
  • Create break iterator for boundaries of code points

IntlBreakIterator::createCodePointInstance

(PHP 5 >= 5.5.0, PHP 7)

IntlBreakIterator::createCodePointInstance — Create break iterator for boundaries of code points

Description

public static IntlBreakIterator::createCodePointInstance ( void ) : IntlBreakIterator

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Create break iterator for logically possible line breaks

  • « IntlBreakIterator::createCodePointInstance
  • IntlBreakIterator::createSentenceInstance »
  • PHP Manual
  • IntlBreakIterator
  • Create break iterator for logically possible line breaks

IntlBreakIterator::createLineInstance

(PHP 5 >= 5.5.0, PHP 7)

IntlBreakIterator::createLineInstance — Create break iterator for logically possible line breaks

Description

public static IntlBreakIterator::createLineInstance ([ string $locale ] ) : IntlBreakIterator

Warning

This function is currently not documented; only its argument list is available.

Parameters

locale

Return Values


Create break iterator for sentence breaks

  • « IntlBreakIterator::createLineInstance
  • IntlBreakIterator::createTitleInstance »
  • PHP Manual
  • IntlBreakIterator
  • Create break iterator for sentence breaks

IntlBreakIterator::createSentenceInstance

(PHP 5 >= 5.5.0, PHP 7)

IntlBreakIterator::createSentenceInstance — Create break iterator for sentence breaks

Description

public static IntlBreakIterator::createSentenceInstance ([ string $locale ] ) : IntlBreakIterator

Warning

This function is currently not documented; only its argument list is available.

Parameters

locale

Return Values


Create break iterator for title-casing breaks

  • « IntlBreakIterator::createSentenceInstance
  • IntlBreakIterator::createWordInstance »
  • PHP Manual
  • IntlBreakIterator
  • Create break iterator for title-casing breaks

IntlBreakIterator::createTitleInstance

(PHP 5 >= 5.5.0, PHP 7)

IntlBreakIterator::createTitleInstance — Create break iterator for title-casing breaks

Description

public static IntlBreakIterator::createTitleInstance ([ string $locale ] ) : IntlBreakIterator

Warning

This function is currently not documented; only its argument list is available.

Parameters

locale

Return Values


Create break iterator for word breaks

  • « IntlBreakIterator::createTitleInstance
  • IntlBreakIterator::current »
  • PHP Manual
  • IntlBreakIterator
  • Create break iterator for word breaks

IntlBreakIterator::createWordInstance

(PHP 5 >= 5.5.0, PHP 7)

IntlBreakIterator::createWordInstance — Create break iterator for word breaks

Description

public static IntlBreakIterator::createWordInstance ([ string $locale ] ) : IntlBreakIterator

Warning

This function is currently not documented; only its argument list is available.

Parameters

locale

Return Values


Get index of current position

  • « IntlBreakIterator::createWordInstance
  • IntlBreakIterator::first »
  • PHP Manual
  • IntlBreakIterator
  • Get index of current position

IntlBreakIterator::current

(PHP 5 >= 5.5.0, PHP 7)

IntlBreakIterator::current — Get index of current position

Description

public IntlBreakIterator::current ( void ) : int

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Set position to the first character in the text

  • « IntlBreakIterator::current
  • IntlBreakIterator::following »
  • PHP Manual
  • IntlBreakIterator
  • Set position to the first character in the text

IntlBreakIterator::first

(PHP 5 >= 5.5.0, PHP 7)

IntlBreakIterator::first — Set position to the first character in the text

Description

public IntlBreakIterator::first ( void ) : int

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Advance the iterator to the first boundary following specified offset

  • « IntlBreakIterator::first
  • IntlBreakIterator::getErrorCode »
  • PHP Manual
  • IntlBreakIterator
  • Advance the iterator to the first boundary following specified offset

IntlBreakIterator::following

(PHP 5 >= 5.5.0, PHP 7)

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


Get last error code on the object

  • « IntlBreakIterator::following
  • IntlBreakIterator::getErrorMessage »
  • PHP Manual
  • IntlBreakIterator
  • Get last error code on the object

IntlBreakIterator::getErrorCode

intl_get_error_code

(PHP 5 >= 5.5.0, PHP 7)

IntlBreakIterator::getErrorCode -- intl_get_error_code — Get last error code on the object

Description

Object oriented style (method):

public IntlBreakIterator::getErrorCode ( void ) : int

Procedural style:

intl_get_error_code ( void ) : int

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Get last error message on the object

  • « IntlBreakIterator::getErrorCode
  • IntlBreakIterator::getLocale »
  • PHP Manual
  • IntlBreakIterator
  • Get last error message on the object

IntlBreakIterator::getErrorMessage

intl_get_error_message

(PHP 5 >= 5.5.0, PHP 7)

IntlBreakIterator::getErrorMessage -- intl_get_error_message — Get last error message on the object

Description

Object oriented style (method):

public IntlBreakIterator::getErrorMessage ( void ) : string

Procedural style:

intl_get_error_message ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Get the locale associated with the object

  • « IntlBreakIterator::getErrorMessage
  • IntlBreakIterator::getPartsIterator »
  • PHP Manual
  • IntlBreakIterator
  • Get the locale associated with the object

IntlBreakIterator::getLocale

(PHP 5 >= 5.5.0, PHP 7)

IntlBreakIterator::getLocale — Get the locale associated with the object

Description

public IntlBreakIterator::getLocale ( string $locale_type ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

locale_type

Return Values


Create iterator for navigating fragments between boundaries

  • « IntlBreakIterator::getLocale
  • IntlBreakIterator::getText »
  • PHP Manual
  • IntlBreakIterator
  • Create iterator for navigating fragments between boundaries

IntlBreakIterator::getPartsIterator

(PHP 5 >= 5.5.0, PHP 7)

IntlBreakIterator::getPartsIterator — Create iterator for navigating fragments between boundaries

Description

public IntlBreakIterator::getPartsIterator ([ int $key_type = IntlPartsIterator::KEY_SEQUENTIAL ] ) : IntlPartsIterator

Warning

This function is currently not documented; only its argument list is available.

Parameters

key_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


Get the text being scanned

  • « IntlBreakIterator::getPartsIterator
  • IntlBreakIterator::isBoundary »
  • PHP Manual
  • IntlBreakIterator
  • Get the text being scanned

IntlBreakIterator::getText

(PHP 5 >= 5.5.0, PHP 7)

IntlBreakIterator::getText — Get the text being scanned

Description

public IntlBreakIterator::getText ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Tell whether an offset is a boundaryʼs offset

  • « IntlBreakIterator::getText
  • IntlBreakIterator::last »
  • PHP Manual
  • IntlBreakIterator
  • Tell whether an offset is a boundaryʼs offset

IntlBreakIterator::isBoundary

(PHP 5 >= 5.5.0, PHP 7)

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


Set the iterator position to index beyond the last character

  • « IntlBreakIterator::isBoundary
  • IntlBreakIterator::next »
  • PHP Manual
  • IntlBreakIterator
  • Set the iterator position to index beyond the last character

IntlBreakIterator::last

(PHP 5 >= 5.5.0, PHP 7)

IntlBreakIterator::last — Set the iterator position to index beyond the last character

Description

public IntlBreakIterator::last ( void ) : int

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Advance the iterator the next boundary

  • « IntlBreakIterator::last
  • IntlBreakIterator::preceding »
  • PHP Manual
  • IntlBreakIterator
  • Advance the iterator the next boundary

IntlBreakIterator::next

(PHP 5 >= 5.5.0, PHP 7)

IntlBreakIterator::next — Advance the iterator the next boundary

Description

public IntlBreakIterator::next ([ int $offset ] ) : int

Warning

This function is currently not documented; only its argument list is available.

Parameters

offset

Return Values


Set the iterator position to the first boundary before an offset

  • « IntlBreakIterator::next
  • IntlBreakIterator::previous »
  • PHP Manual
  • IntlBreakIterator
  • Set the iterator position to the first boundary before an offset

IntlBreakIterator::preceding

(PHP 5 >= 5.5.0, PHP 7)

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


Set the iterator position to the boundary immediately before the current

  • « IntlBreakIterator::preceding
  • IntlBreakIterator::setText »
  • PHP Manual
  • IntlBreakIterator
  • Set the iterator position to the boundary immediately before the current

IntlBreakIterator::previous

(PHP 5 >= 5.5.0, PHP 7)

IntlBreakIterator::previous — Set the iterator position to the boundary immediately before the current

Description

public IntlBreakIterator::previous ( void ) : int

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Set the text being scanned

  • « IntlBreakIterator::previous
  • IntlRuleBasedBreakIterator »
  • PHP Manual
  • IntlBreakIterator
  • Set the text being scanned

IntlBreakIterator::setText

(PHP 5 >= 5.5.0, PHP 7)

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


The IntlRuleBasedBreakIterator class

(PHP 5 >= 5.5.0, PHP 7)

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

IntlRuleBasedBreakIterator extends IntlBreakIterator implements Traversable {
/* Inherited constants */
const integer IntlBreakIterator::DONE = -1 ;
const integer IntlBreakIterator::WORD_NONE = 0 ;
const integer IntlBreakIterator::WORD_NONE_LIMIT = 100 ;
const integer IntlBreakIterator::WORD_NUMBER = 100 ;
const integer IntlBreakIterator::WORD_NUMBER_LIMIT = 200 ;
const integer IntlBreakIterator::WORD_LETTER = 200 ;
const integer IntlBreakIterator::WORD_LETTER_LIMIT = 300 ;
const integer IntlBreakIterator::WORD_KANA = 300 ;
const integer IntlBreakIterator::WORD_KANA_LIMIT = 400 ;
const integer IntlBreakIterator::WORD_IDEO = 400 ;
const integer IntlBreakIterator::WORD_IDEO_LIMIT = 500 ;
const integer IntlBreakIterator::LINE_SOFT = 0 ;
const integer IntlBreakIterator::LINE_SOFT_LIMIT = 100 ;
const integer IntlBreakIterator::LINE_HARD = 100 ;
const integer IntlBreakIterator::LINE_HARD_LIMIT = 200 ;
const integer IntlBreakIterator::SENTENCE_TERM = 0 ;
const integer IntlBreakIterator::SENTENCE_TERM_LIMIT = 100 ;
const integer IntlBreakIterator::SENTENCE_SEP = 100 ;
const integer IntlBreakIterator::SENTENCE_SEP_LIMIT = 200 ;
/* Methods */
public __construct ( string $rules [, string $areCompiled ] )
public getBinaryRules ( void ) : string
public getRules ( void ) : string
public getRuleStatus ( void ) : int
public getRuleStatusVec ( void ) : array
/* Inherited methods */
private IntlBreakIterator::__construct ( void )
public static IntlBreakIterator::createCharacterInstance ([ string $locale ] ) : IntlBreakIterator
public static IntlBreakIterator::createCodePointInstance ( void ) : IntlBreakIterator
public static IntlBreakIterator::createLineInstance ([ string $locale ] ) : IntlBreakIterator
public static IntlBreakIterator::createSentenceInstance ([ string $locale ] ) : IntlBreakIterator
public static IntlBreakIterator::createTitleInstance ([ string $locale ] ) : IntlBreakIterator
public static IntlBreakIterator::createWordInstance ([ string $locale ] ) : IntlBreakIterator
public IntlBreakIterator::current ( void ) : int
public IntlBreakIterator::first ( void ) : int
public IntlBreakIterator::following ( int $offset ) : int
public IntlBreakIterator::getErrorCode ( void ) : int
intl_get_error_code ( void ) : int
public IntlBreakIterator::getErrorMessage ( void ) : string
intl_get_error_message ( void ) : string
public IntlBreakIterator::getLocale ( string $locale_type ) : string
public IntlBreakIterator::getPartsIterator ([ int $key_type = IntlPartsIterator::KEY_SEQUENTIAL ] ) : IntlPartsIterator
public IntlBreakIterator::getText ( void ) : string
public IntlBreakIterator::isBoundary ( int $offset ) : bool
public IntlBreakIterator::last ( void ) : int
public IntlBreakIterator::next ([ int $offset ] ) : int
public IntlBreakIterator::preceding ( int $offset ) : int
public IntlBreakIterator::previous ( void ) : int
public IntlBreakIterator::setText ( string $text ) : bool
}

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


Create iterator from ruleset

  • « IntlRuleBasedBreakIterator
  • IntlRuleBasedBreakIterator::getBinaryRules »
  • PHP Manual
  • IntlRuleBasedBreakIterator
  • Create iterator from ruleset

IntlRuleBasedBreakIterator::__construct

(PHP 5 >= 5.5.0, PHP 7)

IntlRuleBasedBreakIterator::__construct — Create iterator from ruleset

Description

public IntlRuleBasedBreakIterator::__construct ( string $rules [, string $areCompiled ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

rules

areCompiled

Return Values


Get the binary form of compiled rules

  • « IntlRuleBasedBreakIterator::__construct
  • IntlRuleBasedBreakIterator::getRules »
  • PHP Manual
  • IntlRuleBasedBreakIterator
  • Get the binary form of compiled rules

IntlRuleBasedBreakIterator::getBinaryRules

(PHP 5 >= 5.5.0, PHP 7)

IntlRuleBasedBreakIterator::getBinaryRules — Get the binary form of compiled rules

Description

public IntlRuleBasedBreakIterator::getBinaryRules ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Get the rule set used to create this object

  • « IntlRuleBasedBreakIterator::getBinaryRules
  • IntlRuleBasedBreakIterator::getRuleStatus »
  • PHP Manual
  • IntlRuleBasedBreakIterator
  • Get the rule set used to create this object

IntlRuleBasedBreakIterator::getRules

(PHP 5 >= 5.5.0, PHP 7)

IntlRuleBasedBreakIterator::getRules — Get the rule set used to create this object

Description

public IntlRuleBasedBreakIterator::getRules ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Get the largest status value from the break rules that determined the current break position

  • « IntlRuleBasedBreakIterator::getRules
  • IntlRuleBasedBreakIterator::getRuleStatusVec »
  • PHP Manual
  • IntlRuleBasedBreakIterator
  • Get the largest status value from the break rules that determined the current break position

IntlRuleBasedBreakIterator::getRuleStatus

(PHP 5 >= 5.5.0, PHP 7)

IntlRuleBasedBreakIterator::getRuleStatus — Get the largest status value from the break rules that determined the current break position

Description

public IntlRuleBasedBreakIterator::getRuleStatus ( void ) : int

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Get the status values from the break rules that determined the current break position

  • « IntlRuleBasedBreakIterator::getRuleStatus
  • IntlCodePointBreakIterator »
  • PHP Manual
  • IntlRuleBasedBreakIterator
  • Get the status values from the break rules that determined the current break position

IntlRuleBasedBreakIterator::getRuleStatusVec

(PHP 5 >= 5.5.0, PHP 7)

IntlRuleBasedBreakIterator::getRuleStatusVec — Get the status values from the break rules that determined the current break position

Description

public IntlRuleBasedBreakIterator::getRuleStatusVec ( void ) : array

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The IntlCodePointBreakIterator class

(PHP 5 >= 5.5.0, PHP 7)

Introduction

This break iterator identifies the boundaries between UTF-8 code points.

Class synopsis

IntlCodePointBreakIterator extends IntlBreakIterator implements Traversable {
/* Inherited constants */
const integer IntlBreakIterator::DONE = -1 ;
const integer IntlBreakIterator::WORD_NONE = 0 ;
const integer IntlBreakIterator::WORD_NONE_LIMIT = 100 ;
const integer IntlBreakIterator::WORD_NUMBER = 100 ;
const integer IntlBreakIterator::WORD_NUMBER_LIMIT = 200 ;
const integer IntlBreakIterator::WORD_LETTER = 200 ;
const integer IntlBreakIterator::WORD_LETTER_LIMIT = 300 ;
const integer IntlBreakIterator::WORD_KANA = 300 ;
const integer IntlBreakIterator::WORD_KANA_LIMIT = 400 ;
const integer IntlBreakIterator::WORD_IDEO = 400 ;
const integer IntlBreakIterator::WORD_IDEO_LIMIT = 500 ;
const integer IntlBreakIterator::LINE_SOFT = 0 ;
const integer IntlBreakIterator::LINE_SOFT_LIMIT = 100 ;
const integer IntlBreakIterator::LINE_HARD = 100 ;
const integer IntlBreakIterator::LINE_HARD_LIMIT = 200 ;
const integer IntlBreakIterator::SENTENCE_TERM = 0 ;
const integer IntlBreakIterator::SENTENCE_TERM_LIMIT = 100 ;
const integer IntlBreakIterator::SENTENCE_SEP = 100 ;
const integer IntlBreakIterator::SENTENCE_SEP_LIMIT = 200 ;
/* Methods */
public getLastCodePoint ( void ) : int
/* Inherited methods */
private IntlBreakIterator::__construct ( void )
public static IntlBreakIterator::createCharacterInstance ([ string $locale ] ) : IntlBreakIterator
public static IntlBreakIterator::createCodePointInstance ( void ) : IntlBreakIterator
public static IntlBreakIterator::createLineInstance ([ string $locale ] ) : IntlBreakIterator
public static IntlBreakIterator::createSentenceInstance ([ string $locale ] ) : IntlBreakIterator
public static IntlBreakIterator::createTitleInstance ([ string $locale ] ) : IntlBreakIterator
public static IntlBreakIterator::createWordInstance ([ string $locale ] ) : IntlBreakIterator
public IntlBreakIterator::current ( void ) : int
public IntlBreakIterator::first ( void ) : int
public IntlBreakIterator::following ( int $offset ) : int
public IntlBreakIterator::getErrorCode ( void ) : int
intl_get_error_code ( void ) : int
public IntlBreakIterator::getErrorMessage ( void ) : string
intl_get_error_message ( void ) : string
public IntlBreakIterator::getLocale ( string $locale_type ) : string
public IntlBreakIterator::getPartsIterator ([ int $key_type = IntlPartsIterator::KEY_SEQUENTIAL ] ) : IntlPartsIterator
public IntlBreakIterator::getText ( void ) : string
public IntlBreakIterator::isBoundary ( int $offset ) : bool
public IntlBreakIterator::last ( void ) : int
public IntlBreakIterator::next ([ int $offset ] ) : int
public IntlBreakIterator::preceding ( int $offset ) : int
public IntlBreakIterator::previous ( void ) : int
public IntlBreakIterator::setText ( string $text ) : bool
}

Table of Contents

  • IntlCodePointBreakIterator::getLastCodePoint — Get last code point passed over after advancing or receding the iterator


Get last code point passed over after advancing or receding the iterator

  • « IntlCodePointBreakIterator
  • IntlPartsIterator »
  • PHP Manual
  • IntlCodePointBreakIterator
  • Get last code point passed over after advancing or receding the iterator

IntlCodePointBreakIterator::getLastCodePoint

(PHP 5 >= 5.5.0, PHP 7)

IntlCodePointBreakIterator::getLastCodePoint — Get last code point passed over after advancing or receding the iterator

Description

public IntlCodePointBreakIterator::getLastCodePoint ( void ) : int

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The IntlPartsIterator class

(PHP 5 >= 5.5.0, PHP 7)

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

IntlPartsIterator extends IntlIterator implements Iterator {
/* Constants */
const integer KEY_SEQUENTIAL = 0 ;
const integer KEY_LEFT = 1 ;
const integer KEY_RIGHT = 2 ;
/* Methods */
public getBreakIterator ( void ) : IntlBreakIterator
/* Inherited methods */
public IntlIterator::current ( void ) : mixed
public IntlIterator::key ( void ) : string
public IntlIterator::next ( void ) : void
public IntlIterator::rewind ( void ) : void
public IntlIterator::valid ( void ) : bool
}

Predefined Constants

IntlPartsIterator::KEY_SEQUENTIAL

IntlPartsIterator::KEY_LEFT

IntlPartsIterator::KEY_RIGHT

Table of Contents

  • IntlPartsIterator::getBreakIterator — Get IntlBreakIterator backing this parts iterator


Get IntlBreakIterator backing this parts iterator

  • « IntlPartsIterator
  • UConverter »
  • PHP Manual
  • IntlPartsIterator
  • Get IntlBreakIterator backing this parts iterator

IntlPartsIterator::getBreakIterator

(PHP 5 >= 5.5.0, PHP 7)

IntlPartsIterator::getBreakIterator — Get IntlBreakIterator backing this parts iterator

Description

public IntlPartsIterator::getBreakIterator ( void ) : IntlBreakIterator

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The UConverter class

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

Introduction

Class synopsis

UConverter {
/* Constants */
const integer REASON_UNASSIGNED = 0 ;
const integer REASON_ILLEGAL = 1 ;
const integer REASON_IRREGULAR = 2 ;
const integer REASON_RESET = 3 ;
const integer REASON_CLOSE = 4 ;
const integer REASON_CLONE = 5 ;
const integer UNSUPPORTED_CONVERTER = -1 ;
const integer SBCS = 0 ;
const integer DBCS = 1 ;
const integer MBCS = 2 ;
const integer LATIN_1 = 3 ;
const integer UTF8 = 4 ;
const integer UTF16_BigEndian = 5 ;
const integer UTF16_LittleEndian = 6 ;
const integer UTF32_BigEndian = 7 ;
const integer UTF32_LittleEndian = 8 ;
const integer EBCDIC_STATEFUL = 9 ;
const integer ISO_2022 = 10 ;
const integer LMBCS_1 = 11 ;
const integer LMBCS_2 = 12 ;
const integer LMBCS_3 = 13 ;
const integer LMBCS_4 = 14 ;
const integer LMBCS_5 = 15 ;
const integer LMBCS_6 = 16 ;
const integer LMBCS_8 = 17 ;
const integer LMBCS_11 = 18 ;
const integer LMBCS_16 = 19 ;
const integer LMBCS_17 = 20 ;
const integer LMBCS_18 = 21 ;
const integer LMBCS_19 = 22 ;
const integer LMBCS_LAST = 22 ;
const integer HZ = 23 ;
const integer SCSU = 24 ;
const integer ISCII = 25 ;
const integer US_ASCII = 26 ;
const integer UTF7 = 27 ;
const integer BOCU1 = 28 ;
const integer UTF16 = 29 ;
const integer UTF32 = 30 ;
const integer CESU8 = 31 ;
const integer IMAP_MAILBOX = 32 ;
/* Methods */
public __construct ([ string $destination_encoding [, string $source_encoding ]] )
public convert ( string $str [, bool $reverse ] ) : string
public fromUCallback ( int $reason , string $source , string $codePoint , int &$error ) : mixed
public static getAliases ( string $name ) : array
public static getAvailable ( void ) : array
public getDestinationEncoding ( void ) : string
public getDestinationType ( void ) : int
public getErrorCode ( void ) : int
public getErrorMessage ( void ) : string
public getSourceEncoding ( void ) : string
public getSourceType ( void ) : int
public static getStandards ( void ) : array
public getSubstChars ( void ) : string
public static reasonText ([ int $reason ] ) : string
public setDestinationEncoding ( string $encoding ) : void
public setSourceEncoding ( string $encoding ) : void
public setSubstChars ( string $chars ) : void
public toUCallback ( int $reason , string $source , string $codeUnits , int &$error ) : mixed
public static transcode ( string $str , string $toEncoding , string $fromEncoding [, array $options ] ) : string
}

Predefined Constants

UConverter::REASON_UNASSIGNED

UConverter::REASON_ILLEGAL

UConverter::REASON_IRREGULAR

UConverter::REASON_RESET

UConverter::REASON_CLOSE

UConverter::REASON_CLONE

UConverter::UNSUPPORTED_CONVERTER

UConverter::SBCS

UConverter::DBCS

UConverter::MBCS

UConverter::LATIN_1

UConverter::UTF8

UConverter::UTF16_BigEndian

UConverter::UTF16_LittleEndian

UConverter::UTF32_BigEndian

UConverter::UTF32_LittleEndian

UConverter::EBCDIC_STATEFUL

UConverter::ISO_2022

UConverter::LMBCS_1

UConverter::LMBCS_2

UConverter::LMBCS_3

UConverter::LMBCS_4

UConverter::LMBCS_5

UConverter::LMBCS_6

UConverter::LMBCS_8

UConverter::LMBCS_11

UConverter::LMBCS_16

UConverter::LMBCS_17

UConverter::LMBCS_18

UConverter::LMBCS_19

UConverter::LMBCS_LAST

UConverter::HZ

UConverter::SCSU

UConverter::ISCII

UConverter::US_ASCII

UConverter::UTF7

UConverter::BOCU1

UConverter::UTF16

UConverter::UTF32

UConverter::CESU8

UConverter::IMAP_MAILBOX

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 convertor 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 string from one charset to another


Create UConverter object

  • « UConverter
  • UConverter::convert »
  • PHP Manual
  • UConverter
  • Create UConverter object

UConverter::__construct

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::__construct — Create UConverter object

Description

public UConverter::__construct ([ string $destination_encoding [, string $source_encoding ]] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

destination_encoding

source_encoding

Return Values


Convert string from one charset to another

  • « UConverter::__construct
  • UConverter::fromUCallback »
  • PHP Manual
  • UConverter
  • Convert string from one charset to another

UConverter::convert

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::convert — Convert string from one charset to another

Description

public UConverter::convert ( string $str [, bool $reverse ] ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

str

reverse

Return Values


Default "from" callback function

  • « UConverter::convert
  • UConverter::getAliases »
  • PHP Manual
  • UConverter
  • Default "from" callback function

UConverter::fromUCallback

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::fromUCallback — Default "from" callback function

Description

public UConverter::fromUCallback ( int $reason , string $source , string $codePoint , int &$error ) : mixed

Warning

This function is currently not documented; only its argument list is available.

Parameters

reason

source

codePoint

error

Return Values


Get the aliases of the given name

  • « UConverter::fromUCallback
  • UConverter::getAvailable »
  • PHP Manual
  • UConverter
  • Get the aliases of the given name

UConverter::getAliases

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::getAliases — Get the aliases of the given name

Description

public static UConverter::getAliases ( string $name ) : array

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values


Get the available canonical converter names

  • « UConverter::getAliases
  • UConverter::getDestinationEncoding »
  • PHP Manual
  • UConverter
  • Get the available canonical converter names

UConverter::getAvailable

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::getAvailable — Get the available canonical converter names

Description

public static UConverter::getAvailable ( void ) : array

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Get the destination encoding

  • « UConverter::getAvailable
  • UConverter::getDestinationType »
  • PHP Manual
  • UConverter
  • Get the destination encoding

UConverter::getDestinationEncoding

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::getDestinationEncoding — Get the destination encoding

Description

public UConverter::getDestinationEncoding ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Get the destination converter type

  • « UConverter::getDestinationEncoding
  • UConverter::getErrorCode »
  • PHP Manual
  • UConverter
  • Get the destination converter type

UConverter::getDestinationType

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::getDestinationType — Get the destination converter type

Description

public UConverter::getDestinationType ( void ) : int

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Get last error code on the object

  • « UConverter::getDestinationType
  • UConverter::getErrorMessage »
  • PHP Manual
  • UConverter
  • Get last error code on the object

UConverter::getErrorCode

intl_get_error_code

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::getErrorCode -- intl_get_error_code — Get last error code on the object

Description

public UConverter::getErrorCode ( void ) : int

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Get last error message on the object

  • « UConverter::getErrorCode
  • UConverter::getSourceEncoding »
  • PHP Manual
  • UConverter
  • Get last error message on the object

UConverter::getErrorMessage

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::getErrorMessage — Get last error message on the object

Description

public UConverter::getErrorMessage ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Get the source encoding

  • « UConverter::getErrorMessage
  • UConverter::getSourceType »
  • PHP Manual
  • UConverter
  • Get the source encoding

UConverter::getSourceEncoding

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::getSourceEncoding — Get the source encoding

Description

public UConverter::getSourceEncoding ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Get the source convertor type

  • « UConverter::getSourceEncoding
  • UConverter::getStandards »
  • PHP Manual
  • UConverter
  • Get the source convertor type

UConverter::getSourceType

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::getSourceType — Get the source convertor type

Description

public UConverter::getSourceType ( void ) : int

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Get standards associated to converter names

  • « UConverter::getSourceType
  • UConverter::getSubstChars »
  • PHP Manual
  • UConverter
  • Get standards associated to converter names

UConverter::getStandards

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::getStandards — Get standards associated to converter names

Description

public static UConverter::getStandards ( void ) : array

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Get substitution chars

  • « UConverter::getStandards
  • UConverter::reasonText »
  • PHP Manual
  • UConverter
  • Get substitution chars

UConverter::getSubstChars

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::getSubstChars — Get substitution chars

Description

public UConverter::getSubstChars ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Get string representation of the callback reason

  • « UConverter::getSubstChars
  • UConverter::setDestinationEncoding »
  • PHP Manual
  • UConverter
  • Get string representation of the callback reason

UConverter::reasonText

(PHP 5 >= 5.5.0, PHP 7, 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


Set the destination encoding

  • « UConverter::reasonText
  • UConverter::setSourceEncoding »
  • PHP Manual
  • UConverter
  • Set the destination encoding

UConverter::setDestinationEncoding

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::setDestinationEncoding — Set the destination encoding

Description

public UConverter::setDestinationEncoding ( string $encoding ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

encoding

Return Values


Set the source encoding

  • « UConverter::setDestinationEncoding
  • UConverter::setSubstChars »
  • PHP Manual
  • UConverter
  • Set the source encoding

UConverter::setSourceEncoding

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::setSourceEncoding — Set the source encoding

Description

public UConverter::setSourceEncoding ( string $encoding ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

encoding

Return Values


Set the substitution chars

  • « UConverter::setSourceEncoding
  • UConverter::toUCallback »
  • PHP Manual
  • UConverter
  • Set the substitution chars

UConverter::setSubstChars

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::setSubstChars — Set the substitution chars

Description

public UConverter::setSubstChars ( string $chars ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

chars

Return Values


Default "to" callback function

  • « UConverter::setSubstChars
  • UConverter::transcode »
  • PHP Manual
  • UConverter
  • Default "to" callback function

UConverter::toUCallback

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::toUCallback — Default "to" callback function

Description

public UConverter::toUCallback ( int $reason , string $source , string $codeUnits , int &$error ) : mixed

Warning

This function is currently not documented; only its argument list is available.

Parameters

reason

source

codeUnits

error

Return Values


Convert string from one charset to another

  • « UConverter::toUCallback
  • Grapheme Functions »
  • PHP Manual
  • UConverter
  • Convert string from one charset to another

UConverter::transcode

(PHP 5 >= 5.5.0, PHP 7, PECL >= 3.0.0a1)

UConverter::transcode — Convert string from one charset to another

Description

public static UConverter::transcode ( string $str , string $toEncoding , string $fromEncoding [, array $options ] ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

str

toEncoding

fromEncoding

options

Return Values


Grapheme Functions

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_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


Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8

  • « Grapheme Functions
  • grapheme_stripos »
  • PHP Manual
  • Grapheme Functions
  • Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8

grapheme_extract

(PHP 5 >= 5.3.0, PHP 7, 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 $extract_type [, int $start = 0 [, int &$next ]]] ) : string

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 $extract_type - to return.

extract_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.

start

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 $start 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 $start and ending on a default grapheme cluster boundary that conforms to the $size and $extract_type specified.

Changelog

Version | Description
7.1.0 | Support for negative starts 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


Find position (in grapheme units) of first occurrence of a case-insensitive string

  • « grapheme_extract
  • grapheme_stristr »
  • PHP Manual
  • Grapheme Functions
  • Find position (in grapheme units) of first occurrence of a case-insensitive string

grapheme_stripos

(PHP 5 >= 5.3.0, PHP 7, 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 ] ) : int

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.

Return Values

Returns the position as an integer. If needle is not found, grapheme_stripos() will return boolean FALSE.

Changelog

Version | Description
7.1.0 | Support for negative offsets 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


Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack

  • « grapheme_stripos
  • grapheme_strlen »
  • PHP Manual
  • Grapheme Functions
  • Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack

grapheme_stristr

(PHP 5 >= 5.3.0, PHP 7, 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 $before_needle = FALSE ] ) : string

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.

before_needle

If TRUE, grapheme_strstr() returns the part of the haystack before the first occurrence of the needle (excluding needle).

Return Values

Returns the portion of $haystack, or FALSE if $needle is not found.

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


Get string length in grapheme units

  • « grapheme_stristr
  • grapheme_strpos »
  • PHP Manual
  • Grapheme Functions
  • Get string length in grapheme units

grapheme_strlen

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

grapheme_strlen — Get string length in grapheme units

Description

Procedural style

grapheme_strlen ( string $input ) : int

Get string length in grapheme units (not bytes or characters)

Parameters

input

The string being measured for length. It must be a valid UTF-8 string.

Return Values

The length of the string on success, and 0 if the string is empty.

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


Find position (in grapheme units) of first occurrence of a string

  • « grapheme_strlen
  • grapheme_strripos »
  • PHP Manual
  • Grapheme Functions
  • Find position (in grapheme units) of first occurrence of a string

grapheme_strpos

(PHP 5 >= 5.3.0, PHP 7, 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 ] ) : int

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.

Return Values

Returns the position as an integer. If needle is not found, grapheme_strpos() will return boolean FALSE.

Changelog

Version | Description
7.1.0 | Support for negative offsets 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


Find position (in grapheme units) of last occurrence of a case-insensitive string

  • « grapheme_strpos
  • grapheme_strrpos »
  • PHP Manual
  • Grapheme Functions
  • Find position (in grapheme units) of last occurrence of a case-insensitive string

grapheme_strripos

(PHP 5 >= 5.3.0, PHP 7, 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 ] ) : int

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.

Return Values

Returns the position as an integer. If needle is not found, grapheme_strripos() will return boolean FALSE.

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


Find position (in grapheme units) of last occurrence of a string

  • « grapheme_strripos
  • grapheme_strstr »
  • PHP Manual
  • Grapheme Functions
  • Find position (in grapheme units) of last occurrence of a string

grapheme_strrpos

(PHP 5 >= 5.3.0, PHP 7, 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 ] ) : int

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.

Return Values

Returns the position as an integer. If needle is not found, grapheme_strrpos() will return boolean FALSE.

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


Returns part of haystack string from the first occurrence of needle to the end of haystack

  • « grapheme_strrpos
  • grapheme_substr »
  • PHP Manual
  • Grapheme Functions
  • Returns part of haystack string from the first occurrence of needle to the end of haystack

grapheme_strstr

(PHP 5 >= 5.3.0, PHP 7, 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 $before_needle = FALSE ] ) : string

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.

before_needle

If TRUE, grapheme_strstr() returns the part of the haystack before the first occurrence of the needle (excluding the needle).

Return Values

Returns the portion of string, or FALSE if needle is not found.

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


Return part of a string

  • « grapheme_strstr
  • IDN Functions »
  • PHP Manual
  • Grapheme Functions
  • Return part of a string

grapheme_substr

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

grapheme_substr — Return part of a string

Description

Procedural style

grapheme_substr ( string $string , int $start [, int $length ] ) : string

Return part of a string

Parameters

string

The input string. Must be valid UTF-8.

start

Start position in default grapheme units. If $start is non-negative, the returned string will start at the $start'th position in $string, counting from zero. If $start is negative, the returned string will start at the $start'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 $start (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 a start is negative). If $start denotes a position beyond this truncation, FALSE will be returned.

Return Values

Returns the extracted part of $string.

Changelog

Version | Description
5.4 | If length is given and positive and the argument string is shorter than the specified length, all the rest of the string according to start parameter is returned. Previously, FALSE was returned.

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


IDN Functions

Table of Contents

  • idn_to_ascii — Convert domain name to IDNA ASCII form
  • idn_to_utf8 — Convert domain name from IDNA ASCII to Unicode


Convert domain name to IDNA ASCII form

  • « IDN Functions
  • idn_to_utf8 »
  • PHP Manual
  • IDN Functions
  • Convert domain name to IDNA ASCII form

idn_to_ascii

(PHP 5 >= 5.3.0, PHP 7, 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 $options = IDNA_DEFAULT [, int $variant = INTL_IDNA_VARIANT_UTS46 [, array &$idna_info ]]] ) : string

This function converts a Unicode domain name to an IDNA ASCII-compatible format.

Parameters

domain

The domain to convert, which must be UTF-8 encoded.

options

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.
5.4.0/PECL 2.0.0b1 | Added the parameters variant and idna_info; UTS #46 support (requires ICU ≥ 4.6).

Examples

Example #1 idn_to_ascii() example

<?php

echo idn_to_ascii('täst.de');

?>

The above example will output:

xn--tst-qla.de

See Also

  • idn_to_utf8() - Convert domain name from IDNA ASCII to Unicode


Convert domain name from IDNA ASCII to Unicode

  • « idn_to_ascii
  • IntlChar »
  • PHP Manual
  • IDN Functions
  • Convert domain name from IDNA ASCII to Unicode

idn_to_utf8

(PHP 5 >= 5.3.0, PHP 7, 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 $options = IDNA_DEFAULT [, int $variant = INTL_IDNA_VARIANT_UTS46 [, array &$idna_info ]]] ) : string

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.

options

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.
5.4.0/PECL 2.0.0b1 | Added the parameters variant and idna_info; UTS #46 support (requires ICU ≥ 4.6).

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


IntlChar

(PHP 7)

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

IntlChar {
/* Constants */
const string UNICODE_VERSION = 6.3 ;
const integer CODEPOINT_MIN = 0 ;
const integer CODEPOINT_MAX = 1114111 ;
const float NO_NUMERIC_VALUE = -123456789 ;
const integer PROPERTY_ALPHABETIC = 0 ;
const integer PROPERTY_BINARY_START = 0 ;
const integer PROPERTY_ASCII_HEX_DIGIT = 1 ;
const integer PROPERTY_BIDI_CONTROL = 2 ;
const integer PROPERTY_BIDI_MIRRORED = 3 ;
const integer PROPERTY_DASH = 4 ;
const integer PROPERTY_DEFAULT_IGNORABLE_CODE_POINT = 5 ;
const integer PROPERTY_DEPRECATED = 6 ;
const integer PROPERTY_DIACRITIC = 7 ;
const integer PROPERTY_EXTENDER = 8 ;
const integer PROPERTY_FULL_COMPOSITION_EXCLUSION = 9 ;
const integer PROPERTY_GRAPHEME_BASE = 10 ;
const integer PROPERTY_GRAPHEME_EXTEND = 11 ;
const integer PROPERTY_GRAPHEME_LINK = 12 ;
const integer PROPERTY_HEX_DIGIT = 13 ;
const integer PROPERTY_HYPHEN = 14 ;
const integer PROPERTY_ID_CONTINUE = 15 ;
const integer PROPERTY_ID_START = 16 ;
const integer PROPERTY_IDEOGRAPHIC = 17 ;
const integer PROPERTY_IDS_BINARY_OPERATOR = 18 ;
const integer PROPERTY_IDS_TRINARY_OPERATOR = 19 ;
const integer PROPERTY_JOIN_CONTROL = 20 ;
const integer PROPERTY_LOGICAL_ORDER_EXCEPTION = 21 ;
const integer PROPERTY_LOWERCASE = 22 ;
const integer PROPERTY_MATH = 23 ;
const integer PROPERTY_NONCHARACTER_CODE_POINT = 24 ;
const integer PROPERTY_QUOTATION_MARK = 25 ;
const integer PROPERTY_RADICAL = 26 ;
const integer PROPERTY_SOFT_DOTTED = 27 ;
const integer PROPERTY_TERMINAL_PUNCTUATION = 28 ;
const integer PROPERTY_UNIFIED_IDEOGRAPH = 29 ;
const integer PROPERTY_UPPERCASE = 30 ;
const integer PROPERTY_WHITE_SPACE = 31 ;
const integer PROPERTY_XID_CONTINUE = 32 ;
const integer PROPERTY_XID_START = 33 ;
const integer PROPERTY_CASE_SENSITIVE = 34 ;
const integer PROPERTY_S_TERM = 35 ;
const integer PROPERTY_VARIATION_SELECTOR = 36 ;
const integer PROPERTY_NFD_INERT = 37 ;
const integer PROPERTY_NFKD_INERT = 38 ;
const integer PROPERTY_NFC_INERT = 39 ;
const integer PROPERTY_NFKC_INERT = 40 ;
const integer PROPERTY_SEGMENT_STARTER = 41 ;
const integer PROPERTY_PATTERN_SYNTAX = 42 ;
const integer PROPERTY_PATTERN_WHITE_SPACE = 43 ;
const integer PROPERTY_POSIX_ALNUM = 44 ;
const integer PROPERTY_POSIX_BLANK = 45 ;
const integer PROPERTY_POSIX_GRAPH = 46 ;
const integer PROPERTY_POSIX_PRINT = 47 ;
const integer PROPERTY_POSIX_XDIGIT = 48 ;
const integer PROPERTY_CASED = 49 ;
const integer PROPERTY_CASE_IGNORABLE = 50 ;
const integer PROPERTY_CHANGES_WHEN_LOWERCASED = 51 ;
const integer PROPERTY_CHANGES_WHEN_UPPERCASED = 52 ;
const integer PROPERTY_CHANGES_WHEN_TITLECASED = 53 ;
const integer PROPERTY_CHANGES_WHEN_CASEFOLDED = 54 ;
const integer PROPERTY_CHANGES_WHEN_CASEMAPPED = 55 ;
const integer PROPERTY_CHANGES_WHEN_NFKC_CASEFOLDED = 56 ;
const integer PROPERTY_BINARY_LIMIT = 57 ;
const integer PROPERTY_BIDI_CLASS = 4096 ;
const integer PROPERTY_INT_START = 4096 ;
const integer PROPERTY_BLOCK = 4097 ;
const integer PROPERTY_CANONICAL_COMBINING_CLASS = 4098 ;
const integer PROPERTY_DECOMPOSITION_TYPE = 4099 ;
const integer PROPERTY_EAST_ASIAN_WIDTH = 4100 ;
const integer PROPERTY_GENERAL_CATEGORY = 4101 ;
const integer PROPERTY_JOINING_GROUP = 4102 ;
const integer PROPERTY_JOINING_TYPE = 4103 ;
const integer PROPERTY_LINE_BREAK = 4104 ;
const integer PROPERTY_NUMERIC_TYPE = 4105 ;
const integer PROPERTY_SCRIPT = 4106 ;
const integer PROPERTY_HANGUL_SYLLABLE_TYPE = 4107 ;
const integer PROPERTY_NFD_QUICK_CHECK = 4108 ;
const integer PROPERTY_NFKD_QUICK_CHECK = 4109 ;
const integer PROPERTY_NFC_QUICK_CHECK = 4110 ;
const integer PROPERTY_NFKC_QUICK_CHECK = 4111 ;
const integer PROPERTY_LEAD_CANONICAL_COMBINING_CLASS = 4112 ;
const integer PROPERTY_TRAIL_CANONICAL_COMBINING_CLASS = 4113 ;
const integer PROPERTY_GRAPHEME_CLUSTER_BREAK = 4114 ;
const integer PROPERTY_SENTENCE_BREAK = 4115 ;
const integer PROPERTY_WORD_BREAK = 4116 ;
const integer PROPERTY_BIDI_PAIRED_BRACKET_TYPE = 4117 ;
const integer PROPERTY_INT_LIMIT = 4118 ;
const integer PROPERTY_GENERAL_CATEGORY_MASK = 8192 ;
const integer PROPERTY_MASK_START = 8192 ;
const integer PROPERTY_MASK_LIMIT = 8193 ;
const integer PROPERTY_NUMERIC_VALUE = 12288 ;
const integer PROPERTY_DOUBLE_START = 12288 ;
const integer PROPERTY_DOUBLE_LIMIT = 12289 ;
const integer PROPERTY_AGE = 16384 ;
const integer PROPERTY_STRING_START = 16384 ;
const integer PROPERTY_BIDI_MIRRORING_GLYPH = 16385 ;
const integer PROPERTY_CASE_FOLDING = 16386 ;
const integer PROPERTY_ISO_COMMENT = 16387 ;
const integer PROPERTY_LOWERCASE_MAPPING = 16388 ;
const integer PROPERTY_NAME = 16389 ;
const integer PROPERTY_SIMPLE_CASE_FOLDING = 16390 ;
const integer PROPERTY_SIMPLE_LOWERCASE_MAPPING = 16391 ;
const integer PROPERTY_SIMPLE_TITLECASE_MAPPING = 16392 ;
const integer PROPERTY_SIMPLE_UPPERCASE_MAPPING = 16393 ;
const integer PROPERTY_TITLECASE_MAPPING = 16394 ;
const integer PROPERTY_UNICODE_1_NAME = 16395 ;
const integer PROPERTY_UPPERCASE_MAPPING = 16396 ;
const integer PROPERTY_BIDI_PAIRED_BRACKET = 16397 ;
const integer PROPERTY_STRING_LIMIT = 16398 ;
const integer PROPERTY_SCRIPT_EXTENSIONS = 28672 ;
const integer PROPERTY_OTHER_PROPERTY_START = 28672 ;
const integer PROPERTY_OTHER_PROPERTY_LIMIT = 28673 ;
const integer PROPERTY_INVALID_CODE = -1 ;
const integer CHAR_CATEGORY_UNASSIGNED = 0 ;
const integer CHAR_CATEGORY_GENERAL_OTHER_TYPES = 0 ;
const integer CHAR_CATEGORY_UPPERCASE_LETTER = 1 ;
const integer CHAR_CATEGORY_LOWERCASE_LETTER = 2 ;
const integer CHAR_CATEGORY_TITLECASE_LETTER = 3 ;
const integer CHAR_CATEGORY_MODIFIER_LETTER = 4 ;
const integer CHAR_CATEGORY_OTHER_LETTER = 5 ;
const integer CHAR_CATEGORY_NON_SPACING_MARK = 6 ;
const integer CHAR_CATEGORY_ENCLOSING_MARK = 7 ;
const integer CHAR_CATEGORY_COMBINING_SPACING_MARK = 8 ;
const integer CHAR_CATEGORY_DECIMAL_DIGIT_NUMBER = 9 ;
const integer CHAR_CATEGORY_LETTER_NUMBER = 10 ;
const integer CHAR_CATEGORY_OTHER_NUMBER = 11 ;
const integer CHAR_CATEGORY_SPACE_SEPARATOR = 12 ;
const integer CHAR_CATEGORY_LINE_SEPARATOR = 13 ;
const integer CHAR_CATEGORY_PARAGRAPH_SEPARATOR = 14 ;
const integer CHAR_CATEGORY_CONTROL_CHAR = 15 ;
const integer CHAR_CATEGORY_FORMAT_CHAR = 16 ;
const integer CHAR_CATEGORY_PRIVATE_USE_CHAR = 17 ;
const integer CHAR_CATEGORY_SURROGATE = 18 ;
const integer CHAR_CATEGORY_DASH_PUNCTUATION = 19 ;
const integer CHAR_CATEGORY_START_PUNCTUATION = 20 ;
const integer CHAR_CATEGORY_END_PUNCTUATION = 21 ;
const integer CHAR_CATEGORY_CONNECTOR_PUNCTUATION = 22 ;
const integer CHAR_CATEGORY_OTHER_PUNCTUATION = 23 ;
const integer CHAR_CATEGORY_MATH_SYMBOL = 24 ;
const integer CHAR_CATEGORY_CURRENCY_SYMBOL = 25 ;
const integer CHAR_CATEGORY_MODIFIER_SYMBOL = 26 ;
const integer CHAR_CATEGORY_OTHER_SYMBOL = 27 ;
const integer CHAR_CATEGORY_INITIAL_PUNCTUATION = 28 ;
const integer CHAR_CATEGORY_FINAL_PUNCTUATION = 29 ;
const integer CHAR_CATEGORY_CHAR_CATEGORY_COUNT = 30 ;
const integer CHAR_DIRECTION_LEFT_TO_RIGHT = 0 ;
const integer CHAR_DIRECTION_RIGHT_TO_LEFT = 1 ;
const integer CHAR_DIRECTION_EUROPEAN_NUMBER = 2 ;
const integer CHAR_DIRECTION_EUROPEAN_NUMBER_SEPARATOR = 3 ;
const integer CHAR_DIRECTION_EUROPEAN_NUMBER_TERMINATOR = 4 ;
const integer CHAR_DIRECTION_ARABIC_NUMBER = 5 ;
const integer CHAR_DIRECTION_COMMON_NUMBER_SEPARATOR = 6 ;
const integer CHAR_DIRECTION_BLOCK_SEPARATOR = 7 ;
const integer CHAR_DIRECTION_SEGMENT_SEPARATOR = 8 ;
const integer CHAR_DIRECTION_WHITE_SPACE_NEUTRAL = 9 ;
const integer CHAR_DIRECTION_OTHER_NEUTRAL = 10 ;
const integer CHAR_DIRECTION_LEFT_TO_RIGHT_EMBEDDING = 11 ;
const integer CHAR_DIRECTION_LEFT_TO_RIGHT_OVERRIDE = 12 ;
const integer CHAR_DIRECTION_RIGHT_TO_LEFT_ARABIC = 13 ;
const integer CHAR_DIRECTION_RIGHT_TO_LEFT_EMBEDDING = 14 ;
const integer CHAR_DIRECTION_RIGHT_TO_LEFT_OVERRIDE = 15 ;
const integer CHAR_DIRECTION_POP_DIRECTIONAL_FORMAT = 16 ;
const integer CHAR_DIRECTION_DIR_NON_SPACING_MARK = 17 ;
const integer CHAR_DIRECTION_BOUNDARY_NEUTRAL = 18 ;
const integer CHAR_DIRECTION_FIRST_STRONG_ISOLATE = 19 ;
const integer CHAR_DIRECTION_LEFT_TO_RIGHT_ISOLATE = 20 ;
const integer CHAR_DIRECTION_RIGHT_TO_LEFT_ISOLATE = 21 ;
const integer CHAR_DIRECTION_POP_DIRECTIONAL_ISOLATE = 22 ;
const integer CHAR_DIRECTION_CHAR_DIRECTION_COUNT = 23 ;
const integer BLOCK_CODE_NO_BLOCK = 0 ;
const integer BLOCK_CODE_BASIC_LATIN = 1 ;
const integer BLOCK_CODE_LATIN_1_SUPPLEMENT = 2 ;
const integer BLOCK_CODE_LATIN_EXTENDED_A = 3 ;
const integer BLOCK_CODE_LATIN_EXTENDED_B = 4 ;
const integer BLOCK_CODE_IPA_EXTENSIONS = 5 ;
const integer BLOCK_CODE_SPACING_MODIFIER_LETTERS = 6 ;
const integer BLOCK_CODE_COMBINING_DIACRITICAL_MARKS = 7 ;
const integer BLOCK_CODE_GREEK = 8 ;
const integer BLOCK_CODE_CYRILLIC = 9 ;
const integer BLOCK_CODE_ARMENIAN = 10 ;
const integer BLOCK_CODE_HEBREW = 11 ;
const integer BLOCK_CODE_ARABIC = 12 ;
const integer BLOCK_CODE_SYRIAC = 13 ;
const integer BLOCK_CODE_THAANA = 14 ;
const integer BLOCK_CODE_DEVANAGARI = 15 ;
const integer BLOCK_CODE_BENGALI = 16 ;
const integer BLOCK_CODE_GURMUKHI = 17 ;
const integer BLOCK_CODE_GUJARATI = 18 ;
const integer BLOCK_CODE_ORIYA = 19 ;
const integer BLOCK_CODE_TAMIL = 20 ;
const integer BLOCK_CODE_TELUGU = 21 ;
const integer BLOCK_CODE_KANNADA = 22 ;
const integer BLOCK_CODE_MALAYALAM = 23 ;
const integer BLOCK_CODE_SINHALA = 24 ;
const integer BLOCK_CODE_THAI = 25 ;
const integer BLOCK_CODE_LAO = 26 ;
const integer BLOCK_CODE_TIBETAN = 27 ;
const integer BLOCK_CODE_MYANMAR = 28 ;
const integer BLOCK_CODE_GEORGIAN = 29 ;
const integer BLOCK_CODE_HANGUL_JAMO = 30 ;
const integer BLOCK_CODE_ETHIOPIC = 31 ;
const integer BLOCK_CODE_CHEROKEE = 32 ;
const integer BLOCK_CODE_UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS = 33 ;
const integer BLOCK_CODE_OGHAM = 34 ;
const integer BLOCK_CODE_RUNIC = 35 ;
const integer BLOCK_CODE_KHMER = 36 ;
const integer BLOCK_CODE_MONGOLIAN = 37 ;
const integer BLOCK_CODE_LATIN_EXTENDED_ADDITIONAL = 38 ;
const integer BLOCK_CODE_GREEK_EXTENDED = 39 ;
const integer BLOCK_CODE_GENERAL_PUNCTUATION = 40 ;
const integer BLOCK_CODE_SUPERSCRIPTS_AND_SUBSCRIPTS = 41 ;
const integer BLOCK_CODE_CURRENCY_SYMBOLS = 42 ;
const integer BLOCK_CODE_COMBINING_MARKS_FOR_SYMBOLS = 43 ;
const integer BLOCK_CODE_LETTERLIKE_SYMBOLS = 44 ;
const integer BLOCK_CODE_NUMBER_FORMS = 45 ;
const integer BLOCK_CODE_ARROWS = 46 ;
const integer BLOCK_CODE_MATHEMATICAL_OPERATORS = 47 ;
const integer BLOCK_CODE_MISCELLANEOUS_TECHNICAL = 48 ;
const integer BLOCK_CODE_CONTROL_PICTURES = 49 ;
const integer BLOCK_CODE_OPTICAL_CHARACTER_RECOGNITION = 50 ;
const integer BLOCK_CODE_ENCLOSED_ALPHANUMERICS = 51 ;
const integer BLOCK_CODE_BOX_DRAWING = 52 ;
const integer BLOCK_CODE_BLOCK_ELEMENTS = 53 ;
const integer BLOCK_CODE_GEOMETRIC_SHAPES = 54 ;
const integer BLOCK_CODE_MISCELLANEOUS_SYMBOLS = 55 ;
const integer BLOCK_CODE_DINGBATS = 56 ;
const integer BLOCK_CODE_BRAILLE_PATTERNS = 57 ;
const integer BLOCK_CODE_CJK_RADICALS_SUPPLEMENT = 58 ;
const integer BLOCK_CODE_KANGXI_RADICALS = 59 ;
const integer BLOCK_CODE_IDEOGRAPHIC_DESCRIPTION_CHARACTERS = 60 ;
const integer BLOCK_CODE_CJK_SYMBOLS_AND_PUNCTUATION = 61 ;
const integer BLOCK_CODE_HIRAGANA = 62 ;
const integer BLOCK_CODE_KATAKANA = 63 ;
const integer BLOCK_CODE_BOPOMOFO = 64 ;
const integer BLOCK_CODE_HANGUL_COMPATIBILITY_JAMO = 65 ;
const integer BLOCK_CODE_KANBUN = 66 ;
const integer BLOCK_CODE_BOPOMOFO_EXTENDED = 67 ;
const integer BLOCK_CODE_ENCLOSED_CJK_LETTERS_AND_MONTHS = 68 ;
const integer BLOCK_CODE_CJK_COMPATIBILITY = 69 ;
const integer BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A = 70 ;
const integer BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS = 71 ;
const integer BLOCK_CODE_YI_SYLLABLES = 72 ;
const integer BLOCK_CODE_YI_RADICALS = 73 ;
const integer BLOCK_CODE_HANGUL_SYLLABLES = 74 ;
const integer BLOCK_CODE_HIGH_SURROGATES = 75 ;
const integer BLOCK_CODE_HIGH_PRIVATE_USE_SURROGATES = 76 ;
const integer BLOCK_CODE_LOW_SURROGATES = 77 ;
const integer BLOCK_CODE_PRIVATE_USE_AREA = 78 ;
const integer BLOCK_CODE_PRIVATE_USE = 78 ;
const integer BLOCK_CODE_CJK_COMPATIBILITY_IDEOGRAPHS = 79 ;
const integer BLOCK_CODE_ALPHABETIC_PRESENTATION_FORMS = 80 ;
const integer BLOCK_CODE_ARABIC_PRESENTATION_FORMS_A = 81 ;
const integer BLOCK_CODE_COMBINING_HALF_MARKS = 82 ;
const integer BLOCK_CODE_CJK_COMPATIBILITY_FORMS = 83 ;
const integer BLOCK_CODE_SMALL_FORM_VARIANTS = 84 ;
const integer BLOCK_CODE_ARABIC_PRESENTATION_FORMS_B = 85 ;
const integer BLOCK_CODE_SPECIALS = 86 ;
const integer BLOCK_CODE_HALFWIDTH_AND_FULLWIDTH_FORMS = 87 ;
const integer BLOCK_CODE_OLD_ITALIC = 88 ;
const integer BLOCK_CODE_GOTHIC = 89 ;
const integer BLOCK_CODE_DESERET = 90 ;
const integer BLOCK_CODE_BYZANTINE_MUSICAL_SYMBOLS = 91 ;
const integer BLOCK_CODE_MUSICAL_SYMBOLS = 92 ;
const integer BLOCK_CODE_MATHEMATICAL_ALPHANUMERIC_SYMBOLS = 93 ;
const integer BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B = 94 ;
const integer BLOCK_CODE_CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT = 95 ;
const integer BLOCK_CODE_TAGS = 96 ;
const integer BLOCK_CODE_CYRILLIC_SUPPLEMENT = 97 ;
const integer BLOCK_CODE_CYRILLIC_SUPPLEMENTARY = 97 ;
const integer BLOCK_CODE_TAGALOG = 98 ;
const integer BLOCK_CODE_HANUNOO = 99 ;
const integer BLOCK_CODE_BUHID = 100 ;
const integer BLOCK_CODE_TAGBANWA = 101 ;
const integer BLOCK_CODE_MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A = 102 ;
const integer BLOCK_CODE_SUPPLEMENTAL_ARROWS_A = 103 ;
const integer BLOCK_CODE_SUPPLEMENTAL_ARROWS_B = 104 ;
const integer BLOCK_CODE_MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B = 105 ;
const integer BLOCK_CODE_SUPPLEMENTAL_MATHEMATICAL_OPERATORS = 106 ;
const integer BLOCK_CODE_KATAKANA_PHONETIC_EXTENSIONS = 107 ;
const integer BLOCK_CODE_VARIATION_SELECTORS = 108 ;
const integer BLOCK_CODE_SUPPLEMENTARY_PRIVATE_USE_AREA_A = 109 ;
const integer BLOCK_CODE_SUPPLEMENTARY_PRIVATE_USE_AREA_B = 110 ;
const integer BLOCK_CODE_LIMBU = 111 ;
const integer BLOCK_CODE_TAI_LE = 112 ;
const integer BLOCK_CODE_KHMER_SYMBOLS = 113 ;
const integer BLOCK_CODE_PHONETIC_EXTENSIONS = 114 ;
const integer BLOCK_CODE_MISCELLANEOUS_SYMBOLS_AND_ARROWS = 115 ;
const integer BLOCK_CODE_YIJING_HEXAGRAM_SYMBOLS = 116 ;
const integer BLOCK_CODE_LINEAR_B_SYLLABARY = 117 ;
const integer BLOCK_CODE_LINEAR_B_IDEOGRAMS = 118 ;
const integer BLOCK_CODE_AEGEAN_NUMBERS = 119 ;
const integer BLOCK_CODE_UGARITIC = 120 ;
const integer BLOCK_CODE_SHAVIAN = 121 ;
const integer BLOCK_CODE_OSMANYA = 122 ;
const integer BLOCK_CODE_CYPRIOT_SYLLABARY = 123 ;
const integer BLOCK_CODE_TAI_XUAN_JING_SYMBOLS = 124 ;
const integer BLOCK_CODE_VARIATION_SELECTORS_SUPPLEMENT = 125 ;
const integer BLOCK_CODE_ANCIENT_GREEK_MUSICAL_NOTATION = 126 ;
const integer BLOCK_CODE_ANCIENT_GREEK_NUMBERS = 127 ;
const integer BLOCK_CODE_ARABIC_SUPPLEMENT = 128 ;
const integer BLOCK_CODE_BUGINESE = 129 ;
const integer BLOCK_CODE_CJK_STROKES = 130 ;
const integer BLOCK_CODE_COMBINING_DIACRITICAL_MARKS_SUPPLEMENT = 131 ;
const integer BLOCK_CODE_COPTIC = 132 ;
const integer BLOCK_CODE_ETHIOPIC_EXTENDED = 133 ;
const integer BLOCK_CODE_ETHIOPIC_SUPPLEMENT = 134 ;
const integer BLOCK_CODE_GEORGIAN_SUPPLEMENT = 135 ;
const integer BLOCK_CODE_GLAGOLITIC = 136 ;
const integer BLOCK_CODE_KHAROSHTHI = 137 ;
const integer BLOCK_CODE_MODIFIER_TONE_LETTERS = 138 ;
const integer BLOCK_CODE_NEW_TAI_LUE = 139 ;
const integer BLOCK_CODE_OLD_PERSIAN = 140 ;
const integer BLOCK_CODE_PHONETIC_EXTENSIONS_SUPPLEMENT = 141 ;
const integer BLOCK_CODE_SUPPLEMENTAL_PUNCTUATION = 142 ;
const integer BLOCK_CODE_SYLOTI_NAGRI = 143 ;
const integer BLOCK_CODE_TIFINAGH = 144 ;
const integer BLOCK_CODE_VERTICAL_FORMS = 145 ;
const integer BLOCK_CODE_NKO = 146 ;
const integer BLOCK_CODE_BALINESE = 147 ;
const integer BLOCK_CODE_LATIN_EXTENDED_C = 148 ;
const integer BLOCK_CODE_LATIN_EXTENDED_D = 149 ;
const integer BLOCK_CODE_PHAGS_PA = 150 ;
const integer BLOCK_CODE_PHOENICIAN = 151 ;
const integer BLOCK_CODE_CUNEIFORM = 152 ;
const integer BLOCK_CODE_CUNEIFORM_NUMBERS_AND_PUNCTUATION = 153 ;
const integer BLOCK_CODE_COUNTING_ROD_NUMERALS = 154 ;
const integer BLOCK_CODE_SUNDANESE = 155 ;
const integer BLOCK_CODE_LEPCHA = 156 ;
const integer BLOCK_CODE_OL_CHIKI = 157 ;
const integer BLOCK_CODE_CYRILLIC_EXTENDED_A = 158 ;
const integer BLOCK_CODE_VAI = 159 ;
const integer BLOCK_CODE_CYRILLIC_EXTENDED_B = 160 ;
const integer BLOCK_CODE_SAURASHTRA = 161 ;
const integer BLOCK_CODE_KAYAH_LI = 162 ;
const integer BLOCK_CODE_REJANG = 163 ;
const integer BLOCK_CODE_CHAM = 164 ;
const integer BLOCK_CODE_ANCIENT_SYMBOLS = 165 ;
const integer BLOCK_CODE_PHAISTOS_DISC = 166 ;
const integer BLOCK_CODE_LYCIAN = 167 ;
const integer BLOCK_CODE_CARIAN = 168 ;
const integer BLOCK_CODE_LYDIAN = 169 ;
const integer BLOCK_CODE_MAHJONG_TILES = 170 ;
const integer BLOCK_CODE_DOMINO_TILES = 171 ;
const integer BLOCK_CODE_SAMARITAN = 172 ;
const integer BLOCK_CODE_UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS_EXTENDED = 173 ;
const integer BLOCK_CODE_TAI_THAM = 174 ;
const integer BLOCK_CODE_VEDIC_EXTENSIONS = 175 ;
const integer BLOCK_CODE_LISU = 176 ;
const integer BLOCK_CODE_BAMUM = 177 ;
const integer BLOCK_CODE_COMMON_INDIC_NUMBER_FORMS = 178 ;
const integer BLOCK_CODE_DEVANAGARI_EXTENDED = 179 ;
const integer BLOCK_CODE_HANGUL_JAMO_EXTENDED_A = 180 ;
const integer BLOCK_CODE_JAVANESE = 181 ;
const integer BLOCK_CODE_MYANMAR_EXTENDED_A = 182 ;
const integer BLOCK_CODE_TAI_VIET = 183 ;
const integer BLOCK_CODE_MEETEI_MAYEK = 184 ;
const integer BLOCK_CODE_HANGUL_JAMO_EXTENDED_B = 185 ;
const integer BLOCK_CODE_IMPERIAL_ARAMAIC = 186 ;
const integer BLOCK_CODE_OLD_SOUTH_ARABIAN = 187 ;
const integer BLOCK_CODE_AVESTAN = 188 ;
const integer BLOCK_CODE_INSCRIPTIONAL_PARTHIAN = 189 ;
const integer BLOCK_CODE_INSCRIPTIONAL_PAHLAVI = 190 ;
const integer BLOCK_CODE_OLD_TURKIC = 191 ;
const integer BLOCK_CODE_RUMI_NUMERAL_SYMBOLS = 192 ;
const integer BLOCK_CODE_KAITHI = 193 ;
const integer BLOCK_CODE_EGYPTIAN_HIEROGLYPHS = 194 ;
const integer BLOCK_CODE_ENCLOSED_ALPHANUMERIC_SUPPLEMENT = 195 ;
const integer BLOCK_CODE_ENCLOSED_IDEOGRAPHIC_SUPPLEMENT = 196 ;
const integer BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_C = 197 ;
const integer BLOCK_CODE_MANDAIC = 198 ;
const integer BLOCK_CODE_BATAK = 199 ;
const integer BLOCK_CODE_ETHIOPIC_EXTENDED_A = 200 ;
const integer BLOCK_CODE_BRAHMI = 201 ;
const integer BLOCK_CODE_BAMUM_SUPPLEMENT = 202 ;
const integer BLOCK_CODE_KANA_SUPPLEMENT = 203 ;
const integer BLOCK_CODE_PLAYING_CARDS = 204 ;
const integer BLOCK_CODE_MISCELLANEOUS_SYMBOLS_AND_PICTOGRAPHS = 205 ;
const integer BLOCK_CODE_EMOTICONS = 206 ;
const integer BLOCK_CODE_TRANSPORT_AND_MAP_SYMBOLS = 207 ;
const integer BLOCK_CODE_ALCHEMICAL_SYMBOLS = 208 ;
const integer BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_D = 209 ;
const integer BLOCK_CODE_ARABIC_EXTENDED_A = 210 ;
const integer BLOCK_CODE_ARABIC_MATHEMATICAL_ALPHABETIC_SYMBOLS = 211 ;
const integer BLOCK_CODE_CHAKMA = 212 ;
const integer BLOCK_CODE_MEETEI_MAYEK_EXTENSIONS = 213 ;
const integer BLOCK_CODE_MEROITIC_CURSIVE = 214 ;
const integer BLOCK_CODE_MEROITIC_HIEROGLYPHS = 215 ;
const integer BLOCK_CODE_MIAO = 216 ;
const integer BLOCK_CODE_SHARADA = 217 ;
const integer BLOCK_CODE_SORA_SOMPENG = 218 ;
const integer BLOCK_CODE_SUNDANESE_SUPPLEMENT = 219 ;
const integer BLOCK_CODE_TAKRI = 220 ;
const integer BLOCK_CODE_COUNT = 221 ;
const integer BLOCK_CODE_INVALID_CODE = -1 ;
const integer BPT_NONE = 0 ;
const integer BPT_OPEN = 1 ;
const integer BPT_CLOSE = 2 ;
const integer BPT_COUNT = 3 ;
const integer EA_NEUTRAL = 0 ;
const integer EA_AMBIGUOUS = 1 ;
const integer EA_HALFWIDTH = 2 ;
const integer EA_FULLWIDTH = 3 ;
const integer EA_NARROW = 4 ;
const integer EA_WIDE = 5 ;
const integer EA_COUNT = 6 ;
const integer UNICODE_CHAR_NAME = 0 ;
const integer UNICODE_10_CHAR_NAME = 1 ;
const integer EXTENDED_CHAR_NAME = 2 ;
const integer CHAR_NAME_ALIAS = 3 ;
const integer CHAR_NAME_CHOICE_COUNT = 4 ;
const integer SHORT_PROPERTY_NAME = 0 ;
const integer LONG_PROPERTY_NAME = 1 ;
const integer PROPERTY_NAME_CHOICE_COUNT = 2 ;
const integer DT_NONE = 0 ;
const integer DT_CANONICAL = 1 ;
const integer DT_COMPAT = 2 ;
const integer DT_CIRCLE = 3 ;
const integer DT_FINAL = 4 ;
const integer DT_FONT = 5 ;
const integer DT_FRACTION = 6 ;
const integer DT_INITIAL = 7 ;
const integer DT_ISOLATED = 8 ;
const integer DT_MEDIAL = 9 ;
const integer DT_NARROW = 10 ;
const integer DT_NOBREAK = 11 ;
const integer DT_SMALL = 12 ;
const integer DT_SQUARE = 13 ;
const integer DT_SUB = 14 ;
const integer DT_SUPER = 15 ;
const integer DT_VERTICAL = 16 ;
const integer DT_WIDE = 17 ;
const integer DT_COUNT = 18 ;
const integer JT_NON_JOINING = 0 ;
const integer JT_JOIN_CAUSING = 1 ;
const integer JT_DUAL_JOINING = 2 ;
const integer JT_LEFT_JOINING = 3 ;
const integer JT_RIGHT_JOINING = 4 ;
const integer JT_TRANSPARENT = 5 ;
const integer JT_COUNT = 6 ;
const integer JG_NO_JOINING_GROUP = 0 ;
const integer JG_AIN = 1 ;
const integer JG_ALAPH = 2 ;
const integer JG_ALEF = 3 ;
const integer JG_BEH = 4 ;
const integer JG_BETH = 5 ;
const integer JG_DAL = 6 ;
const integer JG_DALATH_RISH = 7 ;
const integer JG_E = 8 ;
const integer JG_FEH = 9 ;
const integer JG_FINAL_SEMKATH = 10 ;
const integer JG_GAF = 11 ;
const integer JG_GAMAL = 12 ;
const integer JG_HAH = 13 ;
const integer JG_TEH_MARBUTA_GOAL = 14 ;
const integer JG_HAMZA_ON_HEH_GOAL = 14 ;
const integer JG_HE = 15 ;
const integer JG_HEH = 16 ;
const integer JG_HEH_GOAL = 17 ;
const integer JG_HETH = 18 ;
const integer JG_KAF = 19 ;
const integer JG_KAPH = 20 ;
const integer JG_KNOTTED_HEH = 21 ;
const integer JG_LAM = 22 ;
const integer JG_LAMADH = 23 ;
const integer JG_MEEM = 24 ;
const integer JG_MIM = 25 ;
const integer JG_NOON = 26 ;
const integer JG_NUN = 27 ;
const integer JG_PE = 28 ;
const integer JG_QAF = 29 ;
const integer JG_QAPH = 30 ;
const integer JG_REH = 31 ;
const integer JG_REVERSED_PE = 32 ;
const integer JG_SAD = 33 ;
const integer JG_SADHE = 34 ;
const integer JG_SEEN = 35 ;
const integer JG_SEMKATH = 36 ;
const integer JG_SHIN = 37 ;
const integer JG_SWASH_KAF = 38 ;
const integer JG_SYRIAC_WAW = 39 ;
const integer JG_TAH = 40 ;
const integer JG_TAW = 41 ;
const integer JG_TEH_MARBUTA = 42 ;
const integer JG_TETH = 43 ;
const integer JG_WAW = 44 ;
const integer JG_YEH = 45 ;
const integer JG_YEH_BARREE = 46 ;
const integer JG_YEH_WITH_TAIL = 47 ;
const integer JG_YUDH = 48 ;
const integer JG_YUDH_HE = 49 ;
const integer JG_ZAIN = 50 ;
const integer JG_FE = 51 ;
const integer JG_KHAPH = 52 ;
const integer JG_ZHAIN = 53 ;
const integer JG_BURUSHASKI_YEH_BARREE = 54 ;
const integer JG_FARSI_YEH = 55 ;
const integer JG_NYA = 56 ;
const integer JG_ROHINGYA_YEH = 57 ;
const integer JG_COUNT = 58 ;
const integer GCB_OTHER = 0 ;
const integer GCB_CONTROL = 1 ;
const integer GCB_CR = 2 ;
const integer GCB_EXTEND = 3 ;
const integer GCB_L = 4 ;
const integer GCB_LF = 5 ;
const integer GCB_LV = 6 ;
const integer GCB_LVT = 7 ;
const integer GCB_T = 8 ;
const integer GCB_V = 9 ;
const integer GCB_SPACING_MARK = 10 ;
const integer GCB_PREPEND = 11 ;
const integer GCB_REGIONAL_INDICATOR = 12 ;
const integer GCB_COUNT = 13 ;
const integer WB_OTHER = 0 ;
const integer WB_ALETTER = 1 ;
const integer WB_FORMAT = 2 ;
const integer WB_KATAKANA = 3 ;
const integer WB_MIDLETTER = 4 ;
const integer WB_MIDNUM = 5 ;
const integer WB_NUMERIC = 6 ;
const integer WB_EXTENDNUMLET = 7 ;
const integer WB_CR = 8 ;
const integer WB_EXTEND = 9 ;
const integer WB_LF = 10 ;
const integer WB_MIDNUMLET = 11 ;
const integer WB_NEWLINE = 12 ;
const integer WB_REGIONAL_INDICATOR = 13 ;
const integer WB_HEBREW_LETTER = 14 ;
const integer WB_SINGLE_QUOTE = 15 ;
const integer WB_DOUBLE_QUOTE = 16 ;
const integer WB_COUNT = 17 ;
const integer SB_OTHER = 0 ;
const integer SB_ATERM = 1 ;
const integer SB_CLOSE = 2 ;
const integer SB_FORMAT = 3 ;
const integer SB_LOWER = 4 ;
const integer SB_NUMERIC = 5 ;
const integer SB_OLETTER = 6 ;
const integer SB_SEP = 7 ;
const integer SB_SP = 8 ;
const integer SB_STERM = 9 ;
const integer SB_UPPER = 10 ;
const integer SB_CR = 11 ;
const integer SB_EXTEND = 12 ;
const integer SB_LF = 13 ;
const integer SB_SCONTINUE = 14 ;
const integer SB_COUNT = 15 ;
const integer LB_UNKNOWN = 0 ;
const integer LB_AMBIGUOUS = 1 ;
const integer LB_ALPHABETIC = 2 ;
const integer LB_BREAK_BOTH = 3 ;
const integer LB_BREAK_AFTER = 4 ;
const integer LB_BREAK_BEFORE = 5 ;
const integer LB_MANDATORY_BREAK = 6 ;
const integer LB_CONTINGENT_BREAK = 7 ;
const integer LB_CLOSE_PUNCTUATION = 8 ;
const integer LB_COMBINING_MARK = 9 ;
const integer LB_CARRIAGE_RETURN = 10 ;
const integer LB_EXCLAMATION = 11 ;
const integer LB_GLUE = 12 ;
const integer LB_HYPHEN = 13 ;
const integer LB_IDEOGRAPHIC = 14 ;
const integer LB_INSEPARABLE = 15 ;
const integer LB_INSEPERABLE = 15 ;
const integer LB_INFIX_NUMERIC = 16 ;
const integer LB_LINE_FEED = 17 ;
const integer LB_NONSTARTER = 18 ;
const integer LB_NUMERIC = 19 ;
const integer LB_OPEN_PUNCTUATION = 20 ;
const integer LB_POSTFIX_NUMERIC = 21 ;
const integer LB_PREFIX_NUMERIC = 22 ;
const integer LB_QUOTATION = 23 ;
const integer LB_COMPLEX_CONTEXT = 24 ;
const integer LB_SURROGATE = 25 ;
const integer LB_SPACE = 26 ;
const integer LB_BREAK_SYMBOLS = 27 ;
const integer LB_ZWSPACE = 28 ;
const integer LB_NEXT_LINE = 29 ;
const integer LB_WORD_JOINER = 30 ;
const integer LB_H2 = 31 ;
const integer LB_H3 = 32 ;
const integer LB_JL = 33 ;
const integer LB_JT = 34 ;
const integer LB_JV = 35 ;
const integer LB_CLOSE_PARENTHESIS = 36 ;
const integer LB_CONDITIONAL_JAPANESE_STARTER = 37 ;
const integer LB_HEBREW_LETTER = 38 ;
const integer LB_REGIONAL_INDICATOR = 39 ;
const integer LB_COUNT = 40 ;
const integer NT_NONE = 0 ;
const integer NT_DECIMAL = 1 ;
const integer NT_DIGIT = 2 ;
const integer NT_NUMERIC = 3 ;
const integer NT_COUNT = 4 ;
const integer HST_NOT_APPLICABLE = 0 ;
const integer HST_LEADING_JAMO = 1 ;
const integer HST_VOWEL_JAMO = 2 ;
const integer HST_TRAILING_JAMO = 3 ;
const integer HST_LV_SYLLABLE = 4 ;
const integer HST_LVT_SYLLABLE = 5 ;
const integer HST_COUNT = 6 ;
/* Methods */
public static charAge ( mixed $codepoint ) : array
public static charDigitValue ( mixed $codepoint ) : int
public static charDirection ( mixed $codepoint ) : int
public static charFromName ( string $characterName [, int $nameChoice = IntlChar::UNICODE_CHAR_NAME ] ) : int
public static charMirror ( mixed $codepoint ) : mixed
public static charName ( mixed $codepoint [, int $nameChoice = IntlChar::UNICODE_CHAR_NAME ] ) : string
public static charType ( mixed $codepoint ) : int
public static chr ( mixed $codepoint ) : string
public static digit ( string $codepoint [, int $radix = 10 ] ) : int
public static enumCharNames ( mixed $start , mixed $limit , callable $callback [, int $nameChoice = IntlChar::UNICODE_CHAR_NAME ] ) : void
public static enumCharTypes ( callable $callback ) : void
public static foldCase ( mixed $codepoint [, int $options = IntlChar::FOLD_CASE_DEFAULT ] ) : mixed
public static forDigit ( int $digit [, int $radix = 10 ] ) : int
public static getBidiPairedBracket ( mixed $codepoint ) : mixed
public static getBlockCode ( mixed $codepoint ) : int
public static getCombiningClass ( mixed $codepoint ) : int
public static getFC_NFKC_Closure ( mixed $codepoint ) : string
public static getIntPropertyMaxValue ( int $property ) : int
public static getIntPropertyMinValue ( int $property ) : int
public static getIntPropertyValue ( mixed $codepoint , int $property ) : int
public static getNumericValue ( mixed $codepoint ) : float
public static getPropertyEnum ( string $alias ) : int
public static getPropertyName ( int $property [, int $nameChoice = IntlChar::LONG_PROPERTY_NAME ] ) : string
public static getPropertyValueEnum ( int $property , string $name ) : int
public static getPropertyValueName ( int $property , int $value [, int $nameChoice = IntlChar::LONG_PROPERTY_NAME ] ) : string
public static getUnicodeVersion ( void ) : array
public static hasBinaryProperty ( mixed $codepoint , int $property ) : bool
public static isalnum ( mixed $codepoint ) : bool
public static isalpha ( mixed $codepoint ) : bool
public static isbase ( mixed $codepoint ) : bool
public static isblank ( mixed $codepoint ) : bool
public static iscntrl ( mixed $codepoint ) : bool
public static isdefined ( mixed $codepoint ) : bool
public static isdigit ( mixed $codepoint ) : bool
public static isgraph ( mixed $codepoint ) : bool
public static isIDIgnorable ( mixed $codepoint ) : bool
public static isIDPart ( mixed $codepoint ) : bool
public static isIDStart ( mixed $codepoint ) : bool
public static isISOControl ( mixed $codepoint ) : bool
public static isJavaIDPart ( mixed $codepoint ) : bool
public static isJavaIDStart ( mixed $codepoint ) : bool
public static isJavaSpaceChar ( mixed $codepoint ) : bool
public static islower ( mixed $codepoint ) : bool
public static isMirrored ( mixed $codepoint ) : bool
public static isprint ( mixed $codepoint ) : bool
public static ispunct ( mixed $codepoint ) : bool
public static isspace ( mixed $codepoint ) : bool
public static istitle ( mixed $codepoint ) : bool
public static isUAlphabetic ( mixed $codepoint ) : bool
public static isULowercase ( mixed $codepoint ) : bool
public static isupper ( mixed $codepoint ) : bool
public static isUUppercase ( mixed $codepoint ) : bool
public static isUWhiteSpace ( mixed $codepoint ) : bool
public static isWhitespace ( mixed $codepoint ) : bool
public static isxdigit ( mixed $codepoint ) : bool
public static ord ( mixed $character ) : int
public static tolower ( mixed $codepoint ) : mixed
public static totitle ( mixed $codepoint ) : mixed
public static toupper ( mixed $codepoint ) : mixed
}

Predefined Constants

IntlChar::UNICODE_VERSION

IntlChar::CODEPOINT_MIN

IntlChar::CODEPOINT_MAX

IntlChar::NO_NUMERIC_VALUE

Special value that is returned by IntlChar::getNumericValue() when no numeric value is defined for a code point.

IntlChar::PROPERTY_ALPHABETIC

IntlChar::PROPERTY_BINARY_START

IntlChar::PROPERTY_ASCII_HEX_DIGIT

IntlChar::PROPERTY_BIDI_CONTROL

IntlChar::PROPERTY_BIDI_MIRRORED

IntlChar::PROPERTY_DASH

IntlChar::PROPERTY_DEFAULT_IGNORABLE_CODE_POINT

IntlChar::PROPERTY_DEPRECATED

IntlChar::PROPERTY_DIACRITIC

IntlChar::PROPERTY_EXTENDER

IntlChar::PROPERTY_FULL_COMPOSITION_EXCLUSION

IntlChar::PROPERTY_GRAPHEME_BASE

IntlChar::PROPERTY_GRAPHEME_EXTEND

IntlChar::PROPERTY_GRAPHEME_LINK

IntlChar::PROPERTY_HEX_DIGIT

IntlChar::PROPERTY_HYPHEN

IntlChar::PROPERTY_ID_CONTINUE

IntlChar::PROPERTY_ID_START

IntlChar::PROPERTY_IDEOGRAPHIC

IntlChar::PROPERTY_IDS_BINARY_OPERATOR

IntlChar::PROPERTY_IDS_TRINARY_OPERATOR

IntlChar::PROPERTY_JOIN_CONTROL

IntlChar::PROPERTY_LOGICAL_ORDER_EXCEPTION

IntlChar::PROPERTY_LOWERCASE

IntlChar::PROPERTY_MATH

IntlChar::PROPERTY_NONCHARACTER_CODE_POINT

IntlChar::PROPERTY_QUOTATION_MARK

IntlChar::PROPERTY_RADICAL

IntlChar::PROPERTY_SOFT_DOTTED

IntlChar::PROPERTY_TERMINAL_PUNCTUATION

IntlChar::PROPERTY_UNIFIED_IDEOGRAPH

IntlChar::PROPERTY_UPPERCASE

IntlChar::PROPERTY_WHITE_SPACE

IntlChar::PROPERTY_XID_CONTINUE

IntlChar::PROPERTY_XID_START

IntlChar::PROPERTY_CASE_SENSITIVE

IntlChar::PROPERTY_S_TERM

IntlChar::PROPERTY_VARIATION_SELECTOR

IntlChar::PROPERTY_NFD_INERT

IntlChar::PROPERTY_NFKD_INERT

IntlChar::PROPERTY_NFC_INERT

IntlChar::PROPERTY_NFKC_INERT

IntlChar::PROPERTY_SEGMENT_STARTER

IntlChar::PROPERTY_PATTERN_SYNTAX

IntlChar::PROPERTY_PATTERN_WHITE_SPACE

IntlChar::PROPERTY_POSIX_ALNUM

IntlChar::PROPERTY_POSIX_BLANK

IntlChar::PROPERTY_POSIX_GRAPH

IntlChar::PROPERTY_POSIX_PRINT

IntlChar::PROPERTY_POSIX_XDIGIT

IntlChar::PROPERTY_CASED

IntlChar::PROPERTY_CASE_IGNORABLE

IntlChar::PROPERTY_CHANGES_WHEN_LOWERCASED

IntlChar::PROPERTY_CHANGES_WHEN_UPPERCASED

IntlChar::PROPERTY_CHANGES_WHEN_TITLECASED

IntlChar::PROPERTY_CHANGES_WHEN_CASEFOLDED

IntlChar::PROPERTY_CHANGES_WHEN_CASEMAPPED

IntlChar::PROPERTY_CHANGES_WHEN_NFKC_CASEFOLDED

IntlChar::PROPERTY_BINARY_LIMIT

IntlChar::PROPERTY_BIDI_CLASS

IntlChar::PROPERTY_INT_START

IntlChar::PROPERTY_BLOCK

IntlChar::PROPERTY_CANONICAL_COMBINING_CLASS

IntlChar::PROPERTY_DECOMPOSITION_TYPE

IntlChar::PROPERTY_EAST_ASIAN_WIDTH

IntlChar::PROPERTY_GENERAL_CATEGORY

IntlChar::PROPERTY_JOINING_GROUP

IntlChar::PROPERTY_JOINING_TYPE

IntlChar::PROPERTY_LINE_BREAK

IntlChar::PROPERTY_NUMERIC_TYPE

IntlChar::PROPERTY_SCRIPT

IntlChar::PROPERTY_HANGUL_SYLLABLE_TYPE

IntlChar::PROPERTY_NFD_QUICK_CHECK

IntlChar::PROPERTY_NFKD_QUICK_CHECK

IntlChar::PROPERTY_NFC_QUICK_CHECK

IntlChar::PROPERTY_NFKC_QUICK_CHECK

IntlChar::PROPERTY_LEAD_CANONICAL_COMBINING_CLASS

IntlChar::PROPERTY_TRAIL_CANONICAL_COMBINING_CLASS

IntlChar::PROPERTY_GRAPHEME_CLUSTER_BREAK

IntlChar::PROPERTY_SENTENCE_BREAK

IntlChar::PROPERTY_WORD_BREAK

IntlChar::PROPERTY_BIDI_PAIRED_BRACKET_TYPE

IntlChar::PROPERTY_INT_LIMIT

IntlChar::PROPERTY_GENERAL_CATEGORY_MASK

IntlChar::PROPERTY_MASK_START

IntlChar::PROPERTY_MASK_LIMIT

IntlChar::PROPERTY_NUMERIC_VALUE

IntlChar::PROPERTY_DOUBLE_START

IntlChar::PROPERTY_DOUBLE_LIMIT

IntlChar::PROPERTY_AGE

IntlChar::PROPERTY_STRING_START

IntlChar::PROPERTY_BIDI_MIRRORING_GLYPH

IntlChar::PROPERTY_CASE_FOLDING

IntlChar::PROPERTY_ISO_COMMENT

IntlChar::PROPERTY_LOWERCASE_MAPPING

IntlChar::PROPERTY_NAME

IntlChar::PROPERTY_SIMPLE_CASE_FOLDING

IntlChar::PROPERTY_SIMPLE_LOWERCASE_MAPPING

IntlChar::PROPERTY_SIMPLE_TITLECASE_MAPPING

IntlChar::PROPERTY_SIMPLE_UPPERCASE_MAPPING

IntlChar::PROPERTY_TITLECASE_MAPPING

IntlChar::PROPERTY_UNICODE_1_NAME

IntlChar::PROPERTY_UPPERCASE_MAPPING

IntlChar::PROPERTY_BIDI_PAIRED_BRACKET

IntlChar::PROPERTY_STRING_LIMIT

IntlChar::PROPERTY_SCRIPT_EXTENSIONS

IntlChar::PROPERTY_OTHER_PROPERTY_START

IntlChar::PROPERTY_OTHER_PROPERTY_LIMIT

IntlChar::PROPERTY_INVALID_CODE

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

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

IntlChar::BLOCK_CODE_NO_BLOCK

IntlChar::BLOCK_CODE_BASIC_LATIN

IntlChar::BLOCK_CODE_LATIN_1_SUPPLEMENT

IntlChar::BLOCK_CODE_LATIN_EXTENDED_A

IntlChar::BLOCK_CODE_LATIN_EXTENDED_B

IntlChar::BLOCK_CODE_IPA_EXTENSIONS

IntlChar::BLOCK_CODE_SPACING_MODIFIER_LETTERS

IntlChar::BLOCK_CODE_COMBINING_DIACRITICAL_MARKS

IntlChar::BLOCK_CODE_GREEK

IntlChar::BLOCK_CODE_CYRILLIC

IntlChar::BLOCK_CODE_ARMENIAN

IntlChar::BLOCK_CODE_HEBREW

IntlChar::BLOCK_CODE_ARABIC

IntlChar::BLOCK_CODE_SYRIAC

IntlChar::BLOCK_CODE_THAANA

IntlChar::BLOCK_CODE_DEVANAGARI

IntlChar::BLOCK_CODE_BENGALI

IntlChar::BLOCK_CODE_GURMUKHI

IntlChar::BLOCK_CODE_GUJARATI

IntlChar::BLOCK_CODE_ORIYA

IntlChar::BLOCK_CODE_TAMIL

IntlChar::BLOCK_CODE_TELUGU

IntlChar::BLOCK_CODE_KANNADA

IntlChar::BLOCK_CODE_MALAYALAM

IntlChar::BLOCK_CODE_SINHALA

IntlChar::BLOCK_CODE_THAI

IntlChar::BLOCK_CODE_LAO

IntlChar::BLOCK_CODE_TIBETAN

IntlChar::BLOCK_CODE_MYANMAR

IntlChar::BLOCK_CODE_GEORGIAN

IntlChar::BLOCK_CODE_HANGUL_JAMO

IntlChar::BLOCK_CODE_ETHIOPIC

IntlChar::BLOCK_CODE_CHEROKEE

IntlChar::BLOCK_CODE_UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS

IntlChar::BLOCK_CODE_OGHAM

IntlChar::BLOCK_CODE_RUNIC

IntlChar::BLOCK_CODE_KHMER

IntlChar::BLOCK_CODE_MONGOLIAN

IntlChar::BLOCK_CODE_LATIN_EXTENDED_ADDITIONAL

IntlChar::BLOCK_CODE_GREEK_EXTENDED

IntlChar::BLOCK_CODE_GENERAL_PUNCTUATION

IntlChar::BLOCK_CODE_SUPERSCRIPTS_AND_SUBSCRIPTS

IntlChar::BLOCK_CODE_CURRENCY_SYMBOLS

IntlChar::BLOCK_CODE_COMBINING_MARKS_FOR_SYMBOLS

IntlChar::BLOCK_CODE_LETTERLIKE_SYMBOLS

IntlChar::BLOCK_CODE_NUMBER_FORMS

IntlChar::BLOCK_CODE_ARROWS

IntlChar::BLOCK_CODE_MATHEMATICAL_OPERATORS

IntlChar::BLOCK_CODE_MISCELLANEOUS_TECHNICAL

IntlChar::BLOCK_CODE_CONTROL_PICTURES

IntlChar::BLOCK_CODE_OPTICAL_CHARACTER_RECOGNITION

IntlChar::BLOCK_CODE_ENCLOSED_ALPHANUMERICS

IntlChar::BLOCK_CODE_BOX_DRAWING

IntlChar::BLOCK_CODE_BLOCK_ELEMENTS

IntlChar::BLOCK_CODE_GEOMETRIC_SHAPES

IntlChar::BLOCK_CODE_MISCELLANEOUS_SYMBOLS

IntlChar::BLOCK_CODE_DINGBATS

IntlChar::BLOCK_CODE_BRAILLE_PATTERNS

IntlChar::BLOCK_CODE_CJK_RADICALS_SUPPLEMENT

IntlChar::BLOCK_CODE_KANGXI_RADICALS

IntlChar::BLOCK_CODE_IDEOGRAPHIC_DESCRIPTION_CHARACTERS

IntlChar::BLOCK_CODE_CJK_SYMBOLS_AND_PUNCTUATION

IntlChar::BLOCK_CODE_HIRAGANA

IntlChar::BLOCK_CODE_KATAKANA

IntlChar::BLOCK_CODE_BOPOMOFO

IntlChar::BLOCK_CODE_HANGUL_COMPATIBILITY_JAMO

IntlChar::BLOCK_CODE_KANBUN

IntlChar::BLOCK_CODE_BOPOMOFO_EXTENDED

IntlChar::BLOCK_CODE_ENCLOSED_CJK_LETTERS_AND_MONTHS

IntlChar::BLOCK_CODE_CJK_COMPATIBILITY

IntlChar::BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A

IntlChar::BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS

IntlChar::BLOCK_CODE_YI_SYLLABLES

IntlChar::BLOCK_CODE_YI_RADICALS

IntlChar::BLOCK_CODE_HANGUL_SYLLABLES

IntlChar::BLOCK_CODE_HIGH_SURROGATES

IntlChar::BLOCK_CODE_HIGH_PRIVATE_USE_SURROGATES

IntlChar::BLOCK_CODE_LOW_SURROGATES

IntlChar::BLOCK_CODE_PRIVATE_USE_AREA

IntlChar::BLOCK_CODE_PRIVATE_USE

IntlChar::BLOCK_CODE_CJK_COMPATIBILITY_IDEOGRAPHS

IntlChar::BLOCK_CODE_ALPHABETIC_PRESENTATION_FORMS

IntlChar::BLOCK_CODE_ARABIC_PRESENTATION_FORMS_A

IntlChar::BLOCK_CODE_COMBINING_HALF_MARKS

IntlChar::BLOCK_CODE_CJK_COMPATIBILITY_FORMS

IntlChar::BLOCK_CODE_SMALL_FORM_VARIANTS

IntlChar::BLOCK_CODE_ARABIC_PRESENTATION_FORMS_B

IntlChar::BLOCK_CODE_SPECIALS

IntlChar::BLOCK_CODE_HALFWIDTH_AND_FULLWIDTH_FORMS

IntlChar::BLOCK_CODE_OLD_ITALIC

IntlChar::BLOCK_CODE_GOTHIC

IntlChar::BLOCK_CODE_DESERET

IntlChar::BLOCK_CODE_BYZANTINE_MUSICAL_SYMBOLS

IntlChar::BLOCK_CODE_MUSICAL_SYMBOLS

IntlChar::BLOCK_CODE_MATHEMATICAL_ALPHANUMERIC_SYMBOLS

IntlChar::BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B

IntlChar::BLOCK_CODE_CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT

IntlChar::BLOCK_CODE_TAGS

IntlChar::BLOCK_CODE_CYRILLIC_SUPPLEMENT

IntlChar::BLOCK_CODE_CYRILLIC_SUPPLEMENTARY

IntlChar::BLOCK_CODE_TAGALOG

IntlChar::BLOCK_CODE_HANUNOO

IntlChar::BLOCK_CODE_BUHID

IntlChar::BLOCK_CODE_TAGBANWA

IntlChar::BLOCK_CODE_MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A

IntlChar::BLOCK_CODE_SUPPLEMENTAL_ARROWS_A

IntlChar::BLOCK_CODE_SUPPLEMENTAL_ARROWS_B

IntlChar::BLOCK_CODE_MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B

IntlChar::BLOCK_CODE_SUPPLEMENTAL_MATHEMATICAL_OPERATORS

IntlChar::BLOCK_CODE_KATAKANA_PHONETIC_EXTENSIONS

IntlChar::BLOCK_CODE_VARIATION_SELECTORS

IntlChar::BLOCK_CODE_SUPPLEMENTARY_PRIVATE_USE_AREA_A

IntlChar::BLOCK_CODE_SUPPLEMENTARY_PRIVATE_USE_AREA_B

IntlChar::BLOCK_CODE_LIMBU

IntlChar::BLOCK_CODE_TAI_LE

IntlChar::BLOCK_CODE_KHMER_SYMBOLS

IntlChar::BLOCK_CODE_PHONETIC_EXTENSIONS

IntlChar::BLOCK_CODE_MISCELLANEOUS_SYMBOLS_AND_ARROWS

IntlChar::BLOCK_CODE_YIJING_HEXAGRAM_SYMBOLS

IntlChar::BLOCK_CODE_LINEAR_B_SYLLABARY

IntlChar::BLOCK_CODE_LINEAR_B_IDEOGRAMS

IntlChar::BLOCK_CODE_AEGEAN_NUMBERS

IntlChar::BLOCK_CODE_UGARITIC

IntlChar::BLOCK_CODE_SHAVIAN

IntlChar::BLOCK_CODE_OSMANYA

IntlChar::BLOCK_CODE_CYPRIOT_SYLLABARY

IntlChar::BLOCK_CODE_TAI_XUAN_JING_SYMBOLS

IntlChar::BLOCK_CODE_VARIATION_SELECTORS_SUPPLEMENT

IntlChar::BLOCK_CODE_ANCIENT_GREEK_MUSICAL_NOTATION

IntlChar::BLOCK_CODE_ANCIENT_GREEK_NUMBERS

IntlChar::BLOCK_CODE_ARABIC_SUPPLEMENT

IntlChar::BLOCK_CODE_BUGINESE

IntlChar::BLOCK_CODE_CJK_STROKES

IntlChar::BLOCK_CODE_COMBINING_DIACRITICAL_MARKS_SUPPLEMENT

IntlChar::BLOCK_CODE_COPTIC

IntlChar::BLOCK_CODE_ETHIOPIC_EXTENDED

IntlChar::BLOCK_CODE_ETHIOPIC_SUPPLEMENT

IntlChar::BLOCK_CODE_GEORGIAN_SUPPLEMENT

IntlChar::BLOCK_CODE_GLAGOLITIC

IntlChar::BLOCK_CODE_KHAROSHTHI

IntlChar::BLOCK_CODE_MODIFIER_TONE_LETTERS

IntlChar::BLOCK_CODE_NEW_TAI_LUE

IntlChar::BLOCK_CODE_OLD_PERSIAN

IntlChar::BLOCK_CODE_PHONETIC_EXTENSIONS_SUPPLEMENT

IntlChar::BLOCK_CODE_SUPPLEMENTAL_PUNCTUATION

IntlChar::BLOCK_CODE_SYLOTI_NAGRI

IntlChar::BLOCK_CODE_TIFINAGH

IntlChar::BLOCK_CODE_VERTICAL_FORMS

IntlChar::BLOCK_CODE_NKO

IntlChar::BLOCK_CODE_BALINESE

IntlChar::BLOCK_CODE_LATIN_EXTENDED_C

IntlChar::BLOCK_CODE_LATIN_EXTENDED_D

IntlChar::BLOCK_CODE_PHAGS_PA

IntlChar::BLOCK_CODE_PHOENICIAN

IntlChar::BLOCK_CODE_CUNEIFORM

IntlChar::BLOCK_CODE_CUNEIFORM_NUMBERS_AND_PUNCTUATION

IntlChar::BLOCK_CODE_COUNTING_ROD_NUMERALS

IntlChar::BLOCK_CODE_SUNDANESE

IntlChar::BLOCK_CODE_LEPCHA

IntlChar::BLOCK_CODE_OL_CHIKI

IntlChar::BLOCK_CODE_CYRILLIC_EXTENDED_A

IntlChar::BLOCK_CODE_VAI

IntlChar::BLOCK_CODE_CYRILLIC_EXTENDED_B

IntlChar::BLOCK_CODE_SAURASHTRA

IntlChar::BLOCK_CODE_KAYAH_LI

IntlChar::BLOCK_CODE_REJANG

IntlChar::BLOCK_CODE_CHAM

IntlChar::BLOCK_CODE_ANCIENT_SYMBOLS

IntlChar::BLOCK_CODE_PHAISTOS_DISC

IntlChar::BLOCK_CODE_LYCIAN

IntlChar::BLOCK_CODE_CARIAN

IntlChar::BLOCK_CODE_LYDIAN

IntlChar::BLOCK_CODE_MAHJONG_TILES

IntlChar::BLOCK_CODE_DOMINO_TILES

IntlChar::BLOCK_CODE_SAMARITAN

IntlChar::BLOCK_CODE_UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS_EXTENDED

IntlChar::BLOCK_CODE_TAI_THAM

IntlChar::BLOCK_CODE_VEDIC_EXTENSIONS

IntlChar::BLOCK_CODE_LISU

IntlChar::BLOCK_CODE_BAMUM

IntlChar::BLOCK_CODE_COMMON_INDIC_NUMBER_FORMS

IntlChar::BLOCK_CODE_DEVANAGARI_EXTENDED

IntlChar::BLOCK_CODE_HANGUL_JAMO_EXTENDED_A

IntlChar::BLOCK_CODE_JAVANESE

IntlChar::BLOCK_CODE_MYANMAR_EXTENDED_A

IntlChar::BLOCK_CODE_TAI_VIET

IntlChar::BLOCK_CODE_MEETEI_MAYEK

IntlChar::BLOCK_CODE_HANGUL_JAMO_EXTENDED_B

IntlChar::BLOCK_CODE_IMPERIAL_ARAMAIC

IntlChar::BLOCK_CODE_OLD_SOUTH_ARABIAN

IntlChar::BLOCK_CODE_AVESTAN

IntlChar::BLOCK_CODE_INSCRIPTIONAL_PARTHIAN

IntlChar::BLOCK_CODE_INSCRIPTIONAL_PAHLAVI

IntlChar::BLOCK_CODE_OLD_TURKIC

IntlChar::BLOCK_CODE_RUMI_NUMERAL_SYMBOLS

IntlChar::BLOCK_CODE_KAITHI

IntlChar::BLOCK_CODE_EGYPTIAN_HIEROGLYPHS

IntlChar::BLOCK_CODE_ENCLOSED_ALPHANUMERIC_SUPPLEMENT

IntlChar::BLOCK_CODE_ENCLOSED_IDEOGRAPHIC_SUPPLEMENT

IntlChar::BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_C

IntlChar::BLOCK_CODE_MANDAIC

IntlChar::BLOCK_CODE_BATAK

IntlChar::BLOCK_CODE_ETHIOPIC_EXTENDED_A

IntlChar::BLOCK_CODE_BRAHMI

IntlChar::BLOCK_CODE_BAMUM_SUPPLEMENT

IntlChar::BLOCK_CODE_KANA_SUPPLEMENT

IntlChar::BLOCK_CODE_PLAYING_CARDS

IntlChar::BLOCK_CODE_MISCELLANEOUS_SYMBOLS_AND_PICTOGRAPHS

IntlChar::BLOCK_CODE_EMOTICONS

IntlChar::BLOCK_CODE_TRANSPORT_AND_MAP_SYMBOLS

IntlChar::BLOCK_CODE_ALCHEMICAL_SYMBOLS

IntlChar::BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_D

IntlChar::BLOCK_CODE_ARABIC_EXTENDED_A

IntlChar::BLOCK_CODE_ARABIC_MATHEMATICAL_ALPHABETIC_SYMBOLS

IntlChar::BLOCK_CODE_CHAKMA

IntlChar::BLOCK_CODE_MEETEI_MAYEK_EXTENSIONS

IntlChar::BLOCK_CODE_MEROITIC_CURSIVE

IntlChar::BLOCK_CODE_MEROITIC_HIEROGLYPHS

IntlChar::BLOCK_CODE_MIAO

IntlChar::BLOCK_CODE_SHARADA

IntlChar::BLOCK_CODE_SORA_SOMPENG

IntlChar::BLOCK_CODE_SUNDANESE_SUPPLEMENT

IntlChar::BLOCK_CODE_TAKRI

IntlChar::BLOCK_CODE_COUNT

IntlChar::BLOCK_CODE_INVALID_CODE

IntlChar::BPT_NONE

IntlChar::BPT_OPEN

IntlChar::BPT_CLOSE

IntlChar::BPT_COUNT

IntlChar::EA_NEUTRAL

IntlChar::EA_AMBIGUOUS

IntlChar::EA_HALFWIDTH

IntlChar::EA_FULLWIDTH

IntlChar::EA_NARROW

IntlChar::EA_WIDE

IntlChar::EA_COUNT

IntlChar::UNICODE_CHAR_NAME

IntlChar::UNICODE_10_CHAR_NAME

IntlChar::EXTENDED_CHAR_NAME

IntlChar::CHAR_NAME_ALIAS

IntlChar::CHAR_NAME_CHOICE_COUNT

IntlChar::SHORT_PROPERTY_NAME

IntlChar::LONG_PROPERTY_NAME

IntlChar::PROPERTY_NAME_CHOICE_COUNT

IntlChar::DT_NONE

IntlChar::DT_CANONICAL

IntlChar::DT_COMPAT

IntlChar::DT_CIRCLE

IntlChar::DT_FINAL

IntlChar::DT_FONT

IntlChar::DT_FRACTION

IntlChar::DT_INITIAL

IntlChar::DT_ISOLATED

IntlChar::DT_MEDIAL

IntlChar::DT_NARROW

IntlChar::DT_NOBREAK

IntlChar::DT_SMALL

IntlChar::DT_SQUARE

IntlChar::DT_SUB

IntlChar::DT_SUPER

IntlChar::DT_VERTICAL

IntlChar::DT_WIDE

IntlChar::DT_COUNT

IntlChar::JT_NON_JOINING

IntlChar::JT_JOIN_CAUSING

IntlChar::JT_DUAL_JOINING

IntlChar::JT_LEFT_JOINING

IntlChar::JT_RIGHT_JOINING

IntlChar::JT_TRANSPARENT

IntlChar::JT_COUNT

IntlChar::JG_NO_JOINING_GROUP

IntlChar::JG_AIN

IntlChar::JG_ALAPH

IntlChar::JG_ALEF

IntlChar::JG_BEH

IntlChar::JG_BETH

IntlChar::JG_DAL

IntlChar::JG_DALATH_RISH

IntlChar::JG_E

IntlChar::JG_FEH

IntlChar::JG_FINAL_SEMKATH

IntlChar::JG_GAF

IntlChar::JG_GAMAL

IntlChar::JG_HAH

IntlChar::JG_TEH_MARBUTA_GOAL

IntlChar::JG_HAMZA_ON_HEH_GOAL

IntlChar::JG_HE

IntlChar::JG_HEH

IntlChar::JG_HEH_GOAL

IntlChar::JG_HETH

IntlChar::JG_KAF

IntlChar::JG_KAPH

IntlChar::JG_KNOTTED_HEH

IntlChar::JG_LAM

IntlChar::JG_LAMADH

IntlChar::JG_MEEM

IntlChar::JG_MIM

IntlChar::JG_NOON

IntlChar::JG_NUN

IntlChar::JG_PE

IntlChar::JG_QAF

IntlChar::JG_QAPH

IntlChar::JG_REH

IntlChar::JG_REVERSED_PE

IntlChar::JG_SAD

IntlChar::JG_SADHE

IntlChar::JG_SEEN

IntlChar::JG_SEMKATH

IntlChar::JG_SHIN

IntlChar::JG_SWASH_KAF

IntlChar::JG_SYRIAC_WAW

IntlChar::JG_TAH

IntlChar::JG_TAW

IntlChar::JG_TEH_MARBUTA

IntlChar::JG_TETH

IntlChar::JG_WAW

IntlChar::JG_YEH

IntlChar::JG_YEH_BARREE

IntlChar::JG_YEH_WITH_TAIL

IntlChar::JG_YUDH

IntlChar::JG_YUDH_HE

IntlChar::JG_ZAIN

IntlChar::JG_FE

IntlChar::JG_KHAPH

IntlChar::JG_ZHAIN

IntlChar::JG_BURUSHASKI_YEH_BARREE

IntlChar::JG_FARSI_YEH

IntlChar::JG_NYA

IntlChar::JG_ROHINGYA_YEH

IntlChar::JG_COUNT

IntlChar::GCB_OTHER

IntlChar::GCB_CONTROL

IntlChar::GCB_CR

IntlChar::GCB_EXTEND

IntlChar::GCB_L

IntlChar::GCB_LF

IntlChar::GCB_LV

IntlChar::GCB_LVT

IntlChar::GCB_T

IntlChar::GCB_V

IntlChar::GCB_SPACING_MARK

IntlChar::GCB_PREPEND

IntlChar::GCB_REGIONAL_INDICATOR

IntlChar::GCB_COUNT

IntlChar::WB_OTHER

IntlChar::WB_ALETTER

IntlChar::WB_FORMAT

IntlChar::WB_KATAKANA

IntlChar::WB_MIDLETTER

IntlChar::WB_MIDNUM

IntlChar::WB_NUMERIC

IntlChar::WB_EXTENDNUMLET

IntlChar::WB_CR

IntlChar::WB_EXTEND

IntlChar::WB_LF

IntlChar::WB_MIDNUMLET

IntlChar::WB_NEWLINE

IntlChar::WB_REGIONAL_INDICATOR

IntlChar::WB_HEBREW_LETTER

IntlChar::WB_SINGLE_QUOTE

IntlChar::WB_DOUBLE_QUOTE

IntlChar::WB_COUNT

IntlChar::SB_OTHER

IntlChar::SB_ATERM

IntlChar::SB_CLOSE

IntlChar::SB_FORMAT

IntlChar::SB_LOWER

IntlChar::SB_NUMERIC

IntlChar::SB_OLETTER

IntlChar::SB_SEP

IntlChar::SB_SP

IntlChar::SB_STERM

IntlChar::SB_UPPER

IntlChar::SB_CR

IntlChar::SB_EXTEND

IntlChar::SB_LF

IntlChar::SB_SCONTINUE

IntlChar::SB_COUNT

IntlChar::LB_UNKNOWN

IntlChar::LB_AMBIGUOUS

IntlChar::LB_ALPHABETIC

IntlChar::LB_BREAK_BOTH

IntlChar::LB_BREAK_AFTER

IntlChar::LB_BREAK_BEFORE

IntlChar::LB_MANDATORY_BREAK

IntlChar::LB_CONTINGENT_BREAK

IntlChar::LB_CLOSE_PUNCTUATION

IntlChar::LB_COMBINING_MARK

IntlChar::LB_CARRIAGE_RETURN

IntlChar::LB_EXCLAMATION

IntlChar::LB_GLUE

IntlChar::LB_HYPHEN

IntlChar::LB_IDEOGRAPHIC

IntlChar::LB_INSEPARABLE

IntlChar::LB_INSEPERABLE

IntlChar::LB_INFIX_NUMERIC

IntlChar::LB_LINE_FEED

IntlChar::LB_NONSTARTER

IntlChar::LB_NUMERIC

IntlChar::LB_OPEN_PUNCTUATION

IntlChar::LB_POSTFIX_NUMERIC

IntlChar::LB_PREFIX_NUMERIC

IntlChar::LB_QUOTATION

IntlChar::LB_COMPLEX_CONTEXT

IntlChar::LB_SURROGATE

IntlChar::LB_SPACE

IntlChar::LB_BREAK_SYMBOLS

IntlChar::LB_ZWSPACE

IntlChar::LB_NEXT_LINE

IntlChar::LB_WORD_JOINER

IntlChar::LB_H2

IntlChar::LB_H3

IntlChar::LB_JL

IntlChar::LB_JT

IntlChar::LB_JV

IntlChar::LB_CLOSE_PARENTHESIS

IntlChar::LB_CONDITIONAL_JAPANESE_STARTER

IntlChar::LB_HEBREW_LETTER

IntlChar::LB_REGIONAL_INDICATOR

IntlChar::LB_COUNT

IntlChar::NT_NONE

IntlChar::NT_DECIMAL

IntlChar::NT_DIGIT

IntlChar::NT_NUMERIC

IntlChar::NT_COUNT

IntlChar::HST_NOT_APPLICABLE

IntlChar::HST_LEADING_JAMO

IntlChar::HST_VOWEL_JAMO

IntlChar::HST_TRAILING_JAMO

IntlChar::HST_LV_SYLLABLE

IntlChar::HST_LVT_SYLLABLE

IntlChar::HST_COUNT

IntlChar::FOLD_CASE_DEFAULT

IntlChar::FOLD_CASE_EXCLUDE_SPECIAL_I

Changelog

Version | Description
7.0.6 | The IntlChar::NO_NUMERIC_VALUE constant was added.

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


Get the "age" of the code point

  • « IntlChar
  • IntlChar::charDigitValue »
  • PHP Manual
  • IntlChar
  • Get the "age" of the code point

IntlChar::charAge

(PHP 7)

IntlChar::charAge — Get the "age" of the code point

Description

public static IntlChar::charAge ( mixed $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 integer 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].

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


Get the decimal digit value of a decimal digit character

  • « IntlChar::charAge
  • IntlChar::charDirection »
  • PHP Manual
  • IntlChar
  • Get the decimal digit value of a decimal digit character

IntlChar::charDigitValue

(PHP 7)

IntlChar::charDigitValue — Get the decimal digit value of a decimal digit character

Description

public static IntlChar::charDigitValue ( mixed $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 integer 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.

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


Get bidirectional category value for a code point

  • « IntlChar::charDigitValue
  • IntlChar::charFromName »
  • PHP Manual
  • IntlChar
  • Get bidirectional category value for a code point

IntlChar::charDirection

(PHP 7)

IntlChar::charDirection — Get bidirectional category value for a code point

Description

public static IntlChar::charDirection ( mixed $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 integer 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

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)


Find Unicode character by name and return its code point value

  • « IntlChar::charDirection
  • IntlChar::charMirror »
  • PHP Manual
  • IntlChar
  • Find Unicode character by name and return its code point value

IntlChar::charFromName

(PHP 7)

IntlChar::charFromName — Find Unicode character by name and return its code point value

Description

public static IntlChar::charFromName ( string $characterName [, int $nameChoice = 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

characterName

Full name of the Unicode character.

nameChoice

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 integer), 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)
bool(false)

See Also

  • IntlChar::charName() - Retrieve the name of a Unicode character
  • IntlChar::enumCharNames() - Enumerate all assigned Unicode characters within a range


Get the "mirror-image" character for a code point

  • « IntlChar::charFromName
  • IntlChar::charName »
  • PHP Manual
  • IntlChar
  • Get the "mirror-image" character for a code point

IntlChar::charMirror

(PHP 7)

IntlChar::charMirror — Get the "mirror-image" character for a code point

Description

public static IntlChar::charMirror ( mixed $codepoint ) : mixed

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 integer 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 will be integer unless the code point was passed as a UTF-8 string, in which case a string will be returned.

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


Retrieve the name of a Unicode character

  • « IntlChar::charMirror
  • IntlChar::charType »
  • PHP Manual
  • IntlChar
  • Retrieve the name of a Unicode character

IntlChar::charName

(PHP 7)

IntlChar::charName — Retrieve the name of a Unicode character

Description

public static IntlChar::charName ( mixed $codepoint [, int $nameChoice = IntlChar::UNICODE_CHAR_NAME ] ) : string

Retrieves the name of a Unicode character.

Depending on nameChoice, 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 integer codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

nameChoice

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


Get the general category value for a code point

  • « IntlChar::charName
  • IntlChar::chr »
  • PHP Manual
  • IntlChar
  • Get the general category value for a code point

IntlChar::charType

(PHP 7)

IntlChar::charType — Get the general category value for a code point

Description

public static IntlChar::charType ( mixed $codepoint ) : int

Returns the general category value for the code point.

Parameters

codepoint

The integer 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);
?>

The above example will output:

bool(true)
bool(true)
bool(true)
bool(true)


Return Unicode character by code point value

  • « IntlChar::charType
  • IntlChar::digit »
  • PHP Manual
  • IntlChar
  • Return Unicode character by code point value

IntlChar::chr

(PHP 7)

IntlChar::chr — Return Unicode character by code point value

Description

public static IntlChar::chr ( mixed $codepoint ) : string

Returns a string containing the character specified by the Unicode code point value.

This function compliments IntlChar::ord().

Parameters

codepoint

The integer 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.

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
  • chr() - Generate a single-byte string from a number


Get the decimal digit value of a code point for a given radix

  • « IntlChar::chr
  • IntlChar::enumCharNames »
  • PHP Manual
  • IntlChar
  • Get the decimal digit value of a code point for a given radix

IntlChar::digit

(PHP 7)

IntlChar::digit — Get the decimal digit value of a code point for a given radix

Description

public static IntlChar::digit ( string $codepoint [, int $radix = 10 ] ) : int

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 integer codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

radix

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.

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


Enumerate all assigned Unicode characters within a range

  • « IntlChar::digit
  • IntlChar::enumCharTypes »
  • PHP Manual
  • IntlChar
  • Enumerate all assigned Unicode characters within a range

IntlChar::enumCharNames

(PHP 7)

IntlChar::enumCharNames — Enumerate all assigned Unicode characters within a range

Description

public static IntlChar::enumCharNames ( mixed $start , mixed $limit , callable $callback [, int $nameChoice = IntlChar::UNICODE_CHAR_NAME ] ) : void

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.

limit

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:

  • integer $codepoint - The numeric code point value
  • integer $nameChoice - The same value as the nameChoice parameter below
  • string $name - The name of the character

nameChoice

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

No value is returned.

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


Enumerate all code points with their Unicode general categories

  • « IntlChar::enumCharNames
  • IntlChar::foldCase »
  • PHP Manual
  • IntlChar
  • Enumerate all code points with their Unicode general categories

IntlChar::enumCharTypes

(PHP 7)

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:

  • integer $start - The starting code point of the range
  • integer $end - The ending code point of the range
  • integer $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
...


Perform case folding on a code point

  • « IntlChar::enumCharTypes
  • IntlChar::forDigit »
  • PHP Manual
  • IntlChar
  • Perform case folding on a code point

IntlChar::foldCase

(PHP 7)

IntlChar::foldCase — Perform case folding on a code point

Description

public static IntlChar::foldCase ( mixed $codepoint [, int $options = IntlChar::FOLD_CASE_DEFAULT ] ) : mixed

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 integer 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.


Get character representation for a given digit and radix

  • « IntlChar::foldCase
  • IntlChar::getBidiPairedBracket »
  • PHP Manual
  • IntlChar
  • Get character representation for a given digit and radix

IntlChar::forDigit

(PHP 7)

IntlChar::forDigit — Get character representation for a given digit and radix

Description

public static IntlChar::forDigit ( int $digit [, int $radix = 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.

radix

The radix (defaults to 10).

Return Values

The character representation (as a string) 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


Get the paired bracket character for a code point

  • « IntlChar::forDigit
  • IntlChar::getBlockCode »
  • PHP Manual
  • IntlChar
  • Get the paired bracket character for a code point

IntlChar::getBidiPairedBracket

(PHP 7)

IntlChar::getBidiPairedBracket — Get the paired bracket character for a code point

Description

public static IntlChar::getBidiPairedBracket ( mixed $codepoint ) : mixed

Maps the specified character to its paired bracket character.

For Bidi_Paired_Bracket_Type!=None, this is the same as IntlChar::charMirror(). Otherwise codepoint itself is returned.

Parameters

codepoint

The integer 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.

The return type will be integer unless the code point was passed as a UTF-8 string, in which case a string will be returned.

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) "]"

See Also

  • IntlChar::charMirror() - Get the "mirror-image" character for a code point
  • IntlChar::PROPERTY_BIDI_PAIRED_BRACKET
  • IntlChar::PROPERTY_BIDI_PAIRED_BRACKET_TYPE


Get the Unicode allocation block containing a code point

  • « IntlChar::getBidiPairedBracket
  • IntlChar::getCombiningClass »
  • PHP Manual
  • IntlChar
  • Get the Unicode allocation block containing a code point

IntlChar::getBlockCode

(PHP 7)

IntlChar::getBlockCode — Get the Unicode allocation block containing a code point

Description

public static IntlChar::getBlockCode ( mixed $codepoint ) : int

Returns the Unicode allocation block that contains the character.

Parameters

codepoint

The integer 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.

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)


Get the combining class of a code point

  • « IntlChar::getBlockCode
  • IntlChar::getFC_NFKC_Closure »
  • PHP Manual
  • IntlChar
  • Get the combining class of a code point

IntlChar::getCombiningClass

(PHP 7)

IntlChar::getCombiningClass — Get the combining class of a code point

Description

public static IntlChar::getCombiningClass ( mixed $codepoint ) : int

Returns the combining class of the code point.

Parameters

codepoint

The integer 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.

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)


Get the FC_NFKC_Closure property for a code point

  • « IntlChar::getCombiningClass
  • IntlChar::getIntPropertyMaxValue »
  • PHP Manual
  • IntlChar
  • Get the FC_NFKC_Closure property for a code point

IntlChar::getFC_NFKC_Closure

(PHP 7)

IntlChar::getFC_NFKC_Closure — Get the FC_NFKC_Closure property for a code point

Description

public static IntlChar::getFC_NFKC_Closure ( mixed $codepoint ) : string

Gets the FC_NFKC_Closure property string for a character.

Parameters

codepoint

The integer 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.

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) "æ"


Get the max value for a Unicode property

  • « IntlChar::getFC_NFKC_Closure
  • IntlChar::getIntPropertyMinValue »
  • PHP Manual
  • IntlChar
  • Get the max value for a Unicode property

IntlChar::getIntPropertyMaxValue

(PHP 7)

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


Get the min value for a Unicode property

  • « IntlChar::getIntPropertyMaxValue
  • IntlChar::getIntPropertyValue »
  • PHP Manual
  • IntlChar
  • Get the min value for a Unicode property

IntlChar::getIntPropertyMinValue

(PHP 7)

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


Get the value for a Unicode property for a code point

  • « IntlChar::getIntPropertyMinValue
  • IntlChar::getNumericValue »
  • PHP Manual
  • IntlChar
  • Get the value for a Unicode property for a code point

IntlChar::getIntPropertyValue

(PHP 7)

IntlChar::getIntPropertyValue — Get the value for a Unicode property for a code point

Description

public static IntlChar::getIntPropertyValue ( mixed $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 integer 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 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


Get the numeric value for a Unicode code point

  • « IntlChar::getIntPropertyValue
  • IntlChar::getPropertyEnum »
  • PHP Manual
  • IntlChar
  • Get the numeric value for a Unicode code point

IntlChar::getNumericValue

(PHP 7)

IntlChar::getNumericValue — Get the numeric value for a Unicode code point

Description

public static IntlChar::getNumericValue ( mixed $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 integer 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.

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)


Get the property constant value for a given property name

  • « IntlChar::getNumericValue
  • IntlChar::getPropertyName »
  • PHP Manual
  • IntlChar
  • Get the property constant value for a given property name

IntlChar::getPropertyEnum

(PHP 7)

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 compliments 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


Get the Unicode name for a property

  • « IntlChar::getPropertyEnum
  • IntlChar::getPropertyValueEnum »
  • PHP Manual
  • IntlChar
  • Get the Unicode name for a property

IntlChar::getPropertyName

(PHP 7)

IntlChar::getPropertyName — Get the Unicode name for a property

Description

public static IntlChar::getPropertyName ( int $property [, int $nameChoice = IntlChar::LONG_PROPERTY_NAME ] ) : string

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 compliments 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.

nameChoice

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 nameChoice is out of range.

If a given nameChoice returns FALSE, then all larger values of nameChoice 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


Get the property value for a given value name

  • « IntlChar::getPropertyName
  • IntlChar::getPropertyValueName »
  • PHP Manual
  • IntlChar
  • Get the property value for a given value name

IntlChar::getPropertyValueEnum

(PHP 7)

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)


Get the Unicode name for a property value

  • « IntlChar::getPropertyValueEnum
  • IntlChar::getUnicodeVersion »
  • PHP Manual
  • IntlChar
  • Get the Unicode name for a property value

IntlChar::getPropertyValueName

(PHP 7)

IntlChar::getPropertyValueName — Get the Unicode name for a property value

Description

public static IntlChar::getPropertyValueName ( int $property , int $value [, int $nameChoice = IntlChar::LONG_PROPERTY_NAME ] ) : string

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.

nameChoice

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 nameChoice is out of range.

If a given nameChoice returns FALSE, then all larger values of nameChoice 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)


Get the Unicode version

  • « IntlChar::getPropertyValueName
  • IntlChar::hasBinaryProperty »
  • PHP Manual
  • IntlChar
  • Get the Unicode version

IntlChar::getUnicodeVersion

(PHP 7)

IntlChar::getUnicodeVersion — Get the Unicode version

Description

public static IntlChar::getUnicodeVersion ( void ) : 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


Check a binary Unicode property for a code point

  • « IntlChar::getUnicodeVersion
  • IntlChar::isalnum »
  • PHP Manual
  • IntlChar
  • Check a binary Unicode property for a code point

IntlChar::hasBinaryProperty

(PHP 7)

IntlChar::hasBinaryProperty — Check a binary Unicode property for a code point

Description

public static IntlChar::hasBinaryProperty ( mixed $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 integer 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.

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


Check if code point is an alphanumeric character

  • « IntlChar::hasBinaryProperty
  • IntlChar::isalpha »
  • PHP Manual
  • IntlChar
  • Check if code point is an alphanumeric character

IntlChar::isalnum

(PHP 7)

IntlChar::isalnum — Check if code point is an alphanumeric character

Description

public static IntlChar::isalnum ( mixed $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 integer 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.

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


Check if code point is a letter character

  • « IntlChar::isalnum
  • IntlChar::isbase »
  • PHP Manual
  • IntlChar
  • Check if code point is a letter character

IntlChar::isalpha

(PHP 7)

IntlChar::isalpha — Check if code point is a letter character

Description

public static IntlChar::isalpha ( mixed $codepoint ) : bool

Determines whether the specified code point is a letter character. TRUE for general categories "L" (letters).

Parameters

codepoint

The integer 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.

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


Check if code point is a base character

  • « IntlChar::isalpha
  • IntlChar::isblank »
  • PHP Manual
  • IntlChar
  • Check if code point is a base character

IntlChar::isbase

(PHP 7)

IntlChar::isbase — Check if code point is a base character

Description

public static IntlChar::isbase ( mixed $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 integer 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.

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


Check if code point is a "blank" or "horizontal space" character

  • « IntlChar::isbase
  • IntlChar::iscntrl »
  • PHP Manual
  • IntlChar
  • Check if code point is a "blank" or "horizontal space" character

IntlChar::isblank

(PHP 7)

IntlChar::isblank — Check if code point is a "blank" or "horizontal space" character

Description

public static IntlChar::isblank ( mixed $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 integer 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.

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


Check if code point is a control character

  • « IntlChar::isblank
  • IntlChar::isdefined »
  • PHP Manual
  • IntlChar
  • Check if code point is a control character

IntlChar::iscntrl

(PHP 7)

IntlChar::iscntrl — Check if code point is a control character

Description

public static IntlChar::iscntrl ( mixed $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 integer 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.

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


Check whether the code point is defined

  • « IntlChar::iscntrl
  • IntlChar::isdigit »
  • PHP Manual
  • IntlChar
  • Check whether the code point is defined

IntlChar::isdefined

(PHP 7)

IntlChar::isdefined — Check whether the code point is defined

Description

public static IntlChar::isdefined ( mixed $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 integer 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.

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


Check if code point is a digit character

  • « IntlChar::isdefined
  • IntlChar::isgraph »
  • PHP Manual
  • IntlChar
  • Check if code point is a digit character

IntlChar::isdigit

(PHP 7)

IntlChar::isdigit — Check if code point is a digit character

Description

public static IntlChar::isdigit ( mixed $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 integer 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.

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


Check if code point is a graphic character

  • « IntlChar::isdigit
  • IntlChar::isIDIgnorable »
  • PHP Manual
  • IntlChar
  • Check if code point is a graphic character

IntlChar::isgraph

(PHP 7)

IntlChar::isgraph — Check if code point is a graphic character

Description

public static IntlChar::isgraph ( mixed $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 integer 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.

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)


Check if code point is an ignorable character

  • « IntlChar::isgraph
  • IntlChar::isIDPart »
  • PHP Manual
  • IntlChar
  • Check if code point is an ignorable character

IntlChar::isIDIgnorable

(PHP 7)

IntlChar::isIDIgnorable — Check if code point is an ignorable character

Description

public static IntlChar::isIDIgnorable ( mixed $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 integer 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.

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


Check if code point is permissible in an identifier

  • « IntlChar::isIDIgnorable
  • IntlChar::isIDStart »
  • PHP Manual
  • IntlChar
  • Check if code point is permissible in an identifier

IntlChar::isIDPart

(PHP 7)

IntlChar::isIDPart — Check if code point is permissible in an identifier

Description

public static IntlChar::isIDPart ( mixed $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 integer 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.

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


Check if code point is permissible as the first character in an identifier

  • « IntlChar::isIDPart
  • IntlChar::isISOControl »
  • PHP Manual
  • IntlChar
  • Check if code point is permissible as the first character in an identifier

IntlChar::isIDStart

(PHP 7)

IntlChar::isIDStart — Check if code point is permissible as the first character in an identifier

Description

public static IntlChar::isIDStart ( mixed $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 integer 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.

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


Check if code point is an ISO control code

  • « IntlChar::isIDStart
  • IntlChar::isJavaIDPart »
  • PHP Manual
  • IntlChar
  • Check if code point is an ISO control code

IntlChar::isISOControl

(PHP 7)

IntlChar::isISOControl — Check if code point is an ISO control code

Description

public static IntlChar::isISOControl ( mixed $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 integer 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.

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


Check if code point is permissible in a Java identifier

  • « IntlChar::isISOControl
  • IntlChar::isJavaIDStart »
  • PHP Manual
  • IntlChar
  • Check if code point is permissible in a Java identifier

IntlChar::isJavaIDPart

(PHP 7)

IntlChar::isJavaIDPart — Check if code point is permissible in a Java identifier

Description

public static IntlChar::isJavaIDPart ( mixed $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 integer 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.

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


Check if code point is permissible as the first character in a Java identifier

  • « IntlChar::isJavaIDPart
  • IntlChar::isJavaSpaceChar »
  • PHP Manual
  • IntlChar
  • Check if code point is permissible as the first character in a Java identifier

IntlChar::isJavaIDStart

(PHP 7)

IntlChar::isJavaIDStart — Check if code point is permissible as the first character in a Java identifier

Description

public static IntlChar::isJavaIDStart ( mixed $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 integer 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.

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


Check if code point is a space character according to Java

  • « IntlChar::isJavaIDStart
  • IntlChar::islower »
  • PHP Manual
  • IntlChar
  • Check if code point is a space character according to Java

IntlChar::isJavaSpaceChar

(PHP 7)

IntlChar::isJavaSpaceChar — Check if code point is a space character according to Java

Description

public static IntlChar::isJavaSpaceChar ( mixed $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 integer 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.

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


Check if code point is a lowercase letter

  • « IntlChar::isJavaSpaceChar
  • IntlChar::isMirrored »
  • PHP Manual
  • IntlChar
  • Check if code point is a lowercase letter

IntlChar::islower

(PHP 7)

IntlChar::islower — Check if code point is a lowercase letter

Description

public static IntlChar::islower ( mixed $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 integer 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.

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


Check if code point has the Bidi_Mirrored property

  • « IntlChar::islower
  • IntlChar::isprint »
  • PHP Manual
  • IntlChar
  • Check if code point has the Bidi_Mirrored property

IntlChar::isMirrored

(PHP 7)

IntlChar::isMirrored — Check if code point has the Bidi_Mirrored property

Description

public static IntlChar::isMirrored ( mixed $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 integer 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.

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


Check if code point is a printable character

  • « IntlChar::isMirrored
  • IntlChar::ispunct »
  • PHP Manual
  • IntlChar
  • Check if code point is a printable character

IntlChar::isprint

(PHP 7)

IntlChar::isprint — Check if code point is a printable character

Description

public static IntlChar::isprint ( mixed $codepoint ) : bool

Determines whether the specified code point is a printable character.

TRUE for general categories other than "C" (controls).

Parameters

codepoint

The integer 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.

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


Check if code point is punctuation character

  • « IntlChar::isprint
  • IntlChar::isspace »
  • PHP Manual
  • IntlChar
  • Check if code point is punctuation character

IntlChar::ispunct

(PHP 7)

IntlChar::ispunct — Check if code point is punctuation character

Description

public static IntlChar::ispunct ( mixed $codepoint ) : bool

Determines whether the specified code point is a punctuation character.

TRUE for characters with general categories "P" (punctuation).

Parameters

codepoint

The integer 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.

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)


Check if code point is a space character

  • « IntlChar::ispunct
  • IntlChar::istitle »
  • PHP Manual
  • IntlChar
  • Check if code point is a space character

IntlChar::isspace

(PHP 7)

IntlChar::isspace — Check if code point is a space character

Description

public static IntlChar::isspace ( mixed $codepoint ) : bool

Determines if the specified character is a space character or not.

Parameters

codepoint

The integer 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.

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


Check if code point is a titlecase letter

  • « IntlChar::isspace
  • IntlChar::isUAlphabetic »
  • PHP Manual
  • IntlChar
  • Check if code point is a titlecase letter

IntlChar::istitle

(PHP 7)

IntlChar::istitle — Check if code point is a titlecase letter

Description

public static IntlChar::istitle ( mixed $codepoint ) : bool

Determines whether the specified code point is a titlecase letter.

TRUE for general category "Lt" (titlecase letter).

Parameters

codepoint

The integer 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.

Examples

Example #1 Testing different code points

<?php
var_dump(IntlChar::istitle("A"));
var_dump(IntlChar::istitle("a"));
var_dump(IntlChar::istitle("Φ"));
var_dump(IntlChar::istitle("φ"));
var_dump(IntlChar::istitle("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::islower() - Check if code point is a lowercase letter
  • IntlChar::totitle() - Make Unicode character titlecase


Check if code point has the Alphabetic Unicode property

  • « IntlChar::istitle
  • IntlChar::isULowercase »
  • PHP Manual
  • IntlChar
  • Check if code point has the Alphabetic Unicode property

IntlChar::isUAlphabetic

(PHP 7)

IntlChar::isUAlphabetic — Check if code point has the Alphabetic Unicode property

Description

public static IntlChar::isUAlphabetic ( mixed $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 integer 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.

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


Check if code point has the Lowercase Unicode property

  • « IntlChar::isUAlphabetic
  • IntlChar::isupper »
  • PHP Manual
  • IntlChar
  • Check if code point has the Lowercase Unicode property

IntlChar::isULowercase

(PHP 7)

IntlChar::isULowercase — Check if code point has the Lowercase Unicode property

Description

public static IntlChar::isULowercase ( mixed $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 integer 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.

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


Check if code point has the general category "Lu" (uppercase letter)

  • « IntlChar::isULowercase
  • IntlChar::isUUppercase »
  • PHP Manual
  • IntlChar
  • Check if code point has the general category "Lu" (uppercase letter)

IntlChar::isupper

(PHP 7)

IntlChar::isupper — Check if code point has the general category "Lu" (uppercase letter)

Description

public static IntlChar::isupper ( mixed $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 integer 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.

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


Check if code point has the Uppercase Unicode property

  • « IntlChar::isupper
  • IntlChar::isUWhiteSpace »
  • PHP Manual
  • IntlChar
  • Check if code point has the Uppercase Unicode property

IntlChar::isUUppercase

(PHP 7)

IntlChar::isUUppercase — Check if code point has the Uppercase Unicode property

Description

public static IntlChar::isUUppercase ( mixed $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 integer 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.

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


Check if code point has the White_Space Unicode property

  • « IntlChar::isUUppercase
  • IntlChar::isWhitespace »
  • PHP Manual
  • IntlChar
  • Check if code point has the White_Space Unicode property

IntlChar::isUWhiteSpace

(PHP 7)

IntlChar::isUWhiteSpace — Check if code point has the White_Space Unicode property

Description

public static IntlChar::isUWhiteSpace ( mixed $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 integer 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.

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


Check if code point is a whitespace character according to ICU

  • « IntlChar::isUWhiteSpace
  • IntlChar::isxdigit »
  • PHP Manual
  • IntlChar
  • Check if code point is a whitespace character according to ICU

IntlChar::isWhitespace

(PHP 7)

IntlChar::isWhitespace — Check if code point is a whitespace character according to ICU

Description

public static IntlChar::isWhitespace ( mixed $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 integer 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.

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


Check if code point is a hexadecimal digit

  • « IntlChar::isWhitespace
  • IntlChar::ord »
  • PHP Manual
  • IntlChar
  • Check if code point is a hexadecimal digit

IntlChar::isxdigit

(PHP 7)

IntlChar::isxdigit — Check if code point is a hexadecimal digit

Description

public static IntlChar::isxdigit ( mixed $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 integer 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.

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);
?>

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)

See Also

  • IntlChar::isdigit() - Check if code point is a digit character


Return Unicode code point value of character

  • « IntlChar::isxdigit
  • IntlChar::tolower »
  • PHP Manual
  • IntlChar
  • Return Unicode code point value of character

IntlChar::ord

(PHP 7)

IntlChar::ord — Return Unicode code point value of character

Description

public static IntlChar::ord ( mixed $character ) : int

Returns the Unicode code point value of the given character.

This function compliments IntlChar::chr().

Parameters

character

A Unicode character.

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::isalnum() - Check if code point is an alphanumeric character
  • IntlChar::isdigit() - Check if code point is a digit character
  • IntlChar::chr() - Return Unicode character by code point value
  • ord() - Convert the first byte of a string to a value between 0 and 255


Make Unicode character lowercase

  • « IntlChar::ord
  • IntlChar::totitle »
  • PHP Manual
  • IntlChar
  • Make Unicode character lowercase

IntlChar::tolower

(PHP 7)

IntlChar::tolower — Make Unicode character lowercase

Description

public static IntlChar::tolower ( mixed $codepoint ) : mixed

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 integer 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.

The return type will be integer unless the code point was passed as a UTF-8 string, in which case a string will be returned.

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


Make Unicode character titlecase

  • « IntlChar::tolower
  • IntlChar::toupper »
  • PHP Manual
  • IntlChar
  • Make Unicode character titlecase

IntlChar::totitle

(PHP 7)

IntlChar::totitle — Make Unicode character titlecase

Description

public static IntlChar::totitle ( mixed $codepoint ) : mixed

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 integer 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.

The return type will be integer unless the code point was passed as a UTF-8 string, in which case a string will be returned.

Examples

Example #1 Testing different code points

<?php
var_dump(IntlChar::totitle("A"));
var_dump(IntlChar::totitle("a"));
var_dump(IntlChar::totitle("Φ"));
var_dump(IntlChar::totitle("φ"));
var_dump(IntlChar::totitle("1"));
var_dump(IntlChar::totitle(ord("A")));
var_dump(IntlChar::totitle(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::toupper() - Make Unicode character uppercase
  • mb_convert_case() - Perform case folding on a string


Make Unicode character uppercase

  • « IntlChar::totitle
  • IntlException »
  • PHP Manual
  • IntlChar
  • Make Unicode character uppercase

IntlChar::toupper

(PHP 7)

IntlChar::toupper — Make Unicode character uppercase

Description

public static IntlChar::toupper ( mixed $codepoint ) : mixed

The given character is mapped to its uppercase equivalent. If the character has no uppercase equivalent, the character itself is returned.

Parameters

codepoint

The integer 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 will be integer unless the code point was passed as a UTF-8 string, in which case a string will be returned.

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


Exception class for intl errors

(PHP 5 > 5.5.0, PHP 7, 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

IntlException extends Exception {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The IntlIterator class

(PHP 5 >= 5.5.0, PHP 7)

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

IntlIterator implements Iterator {
/* Methods */
public current ( void ) : mixed
public key ( void ) : string
public next ( void ) : void
public rewind ( void ) : void
public valid ( void ) : bool
}

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


Get the current element

  • « IntlIterator
  • IntlIterator::key »
  • PHP Manual
  • IntlIterator
  • Get the current element

IntlIterator::current

(PHP 5 >= 5.5.0, PHP 7)

IntlIterator::current — Get the current element

Description

public IntlIterator::current ( void ) : mixed

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Get the current key

  • « IntlIterator::current
  • IntlIterator::next »
  • PHP Manual
  • IntlIterator
  • Get the current key

IntlIterator::key

(PHP 5 >= 5.5.0, PHP 7)

IntlIterator::key — Get the current key

Description

public IntlIterator::key ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Move forward to the next element

  • « IntlIterator::key
  • IntlIterator::rewind »
  • PHP Manual
  • IntlIterator
  • Move forward to the next element

IntlIterator::next

(PHP 5 >= 5.5.0, PHP 7)

IntlIterator::next — Move forward to the next element

Description

public IntlIterator::next ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Rewind the iterator to the first element

  • « IntlIterator::next
  • IntlIterator::valid »
  • PHP Manual
  • IntlIterator
  • Rewind the iterator to the first element

IntlIterator::rewind

(PHP 5 >= 5.5.0, PHP 7)

IntlIterator::rewind — Rewind the iterator to the first element

Description

public IntlIterator::rewind ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Check if current position is valid

  • « IntlIterator::rewind
  • intl Functions »
  • PHP Manual
  • IntlIterator
  • Check if current position is valid

IntlIterator::valid

(PHP 5 >= 5.5.0, PHP 7)

IntlIterator::valid — Check if current position is valid

Description

public IntlIterator::valid ( void ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


intl Functions

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


Get symbolic name for a given error code

  • « intl Functions
  • intl_get_error_code »
  • PHP Manual
  • intl Functions
  • Get symbolic name for a given error code

intl_error_name

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

intl_error_name — Get symbolic name for a given error code

Description

intl_error_name ( int $error_code ) : string

Return ICU error code name.

Parameters

error_code

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


Get the last error code

  • « intl_error_name
  • intl_get_error_message »
  • PHP Manual
  • intl Functions
  • Get the last error code

intl_get_error_code

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

intl_get_error_code — Get the last error code

Description

intl_get_error_code ( void ) : int

Useful to handle errors occurred in static methods when there's no object to get error code from.

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


Get description of the last error

  • « intl_get_error_code
  • intl_is_failure »
  • PHP Manual
  • intl Functions
  • Get description of the last error

intl_get_error_message

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

intl_get_error_message — Get description of the last error

Description

intl_get_error_message ( void ) : string

Get error message from last internationalization function called.

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


Check whether the given error code indicates failure

  • « intl_get_error_message
  • Multibyte String »
  • PHP Manual
  • intl Functions
  • Check whether the given error code indicates failure

intl_is_failure

(PHP 5 >= 5.3.0, PHP 7, PECL intl >= 1.0.0)

intl_is_failure — Check whether the given error code indicates failure

Description

intl_is_failure ( int $error_code ) : bool

Parameters

error_code

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() - Get collator's last error code


Multibyte String

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • 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 — Get a specific character
    • mb_convert_case — Perform case folding on a string
    • mb_convert_encoding — Convert character encoding
    • 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_match — Regular expression match for multibyte string
    • mb_ereg_replace_callback — Perform a regular expression search and replace with multibyte support using a callback
    • mb_ereg_replace — Replace regular expression with multibyte support
    • 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_ereg_search — Multibyte regular expression match for predefined multibyte string
    • mb_ereg — Regular expression match with multibyte support
    • mb_eregi_replace — Replace regular expression with multibyte support ignoring case
    • mb_eregi — Regular expression match ignoring case with multibyte support
    • 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_list_encodings — Returns an array of all supported encodings
    • mb_ord — Get 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_scrub — Description
    • mb_send_mail — Send encoded mail
    • mb_split — Split multibyte string using regular expression
    • 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_count — Count the number of substring occurrences
    • mb_substr — Get part of 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 below).


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. Before 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. Oniguruma is bundled with mbstring. As of PHP 5.4.0, if Oniguruma is already installed on the system, --with-onig[=DIR] can be specified to use the installed library.

    As of PHP 5.4.0 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" | PHP_INI_ALL | PHP_INI_PERDIR in PHP <= 5.2.6.
mbstring.detect_order | NULL | PHP_INI_ALL |
mbstring.http_input | "pass" | PHP_INI_ALL | Deprecated in PHP 5.6.0.
mbstring.http_output | "pass" | PHP_INI_ALL | Deprecated in PHP 5.6.0.
mbstring.internal_encoding | NULL | PHP_INI_ALL | Deprecated in PHP 5.6.0.
mbstring.script_encoding | NULL | PHP_INI_ALL | Removed in PHP 5.4.0. Use zend.script_encoding instead.
mbstring.substitute_character | NULL | PHP_INI_ALL |
mbstring.func_overload | "0" | PHP_INI_SYSTEM | PHP_INI_PERDIR in PHP <= 5.2.6. Deprecated in PHP 7.2.0.
mbstring.encoding_translation | "0" | PHP_INI_PERDIR |
mbstring.http_output_conv_mimetypes | "^(text/|application/xhtml\+xml)" | PHP_INI_ALL | Available as of PHP 5.3.0.
mbstring.strict_detection | "0" | PHP_INI_ALL | Available as of PHP 5.1.2.
For further details and definitions of the PHP_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 boolean

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 feature has been DEPRECATED as of PHP 5.6.0. Relying on this feature is highly discouraged.

Defines the default internal character encoding.

PHP 5.6 and later users should leave this empty and set default_charset instead.

mbstring.http_input string
Warning

This feature has been DEPRECATED as of PHP 5.6.0. Relying on this feature is highly discouraged.

Defines the default HTTP input character encoding.

PHP 5.6 and later users should leave this empty and set default_charset instead.

mbstring.http_output string
Warning

This feature has been DEPRECATED as of PHP 5.6.0. Relying on this feature is highly discouraged.

Defines the default HTTP output character encoding (output will be converted from the internal encoding to the HTTP output encoding upon output).

PHP 5.6 and later 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. 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 boolean

Enables the strict encoding detection.

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 (integer)
MB_OVERLOAD_STRING (integer)
MB_OVERLOAD_REGEX (integer)
MB_CASE_UPPER (integer)
MB_CASE_LOWER (integer)
MB_CASE_TITLE (integer)
MB_CASE_FOLD (integer)
Available since PHP 7.3.
MB_CASE_LOWER_SIMPLE (integer)
Available since PHP 7.3.
MB_CASE_UPPER_SIMPLE (integer)
Available since PHP 7.3.
MB_CASE_TITLE_SIMPLE (integer)
Available since PHP 7.3.
MB_CASE_FOLD_SIMPLE (integer)
Used by case-insensitive operations. Available since PHP 7.3.
MB_ONIGURUMA_VERSION (string)
The Oniguruma version, e.g. 6.9.4. Available since 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.
  • As of PHP 5.4.0, the pictogram characters 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.

** denotes encodings available since PHP 5.4.0.

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. 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()
4 | ereg() | mb_ereg()
4 | eregi() | mb_eregi()
4 | ereg_replace() | mb_ereg_replace()
4 | eregi_replace() | mb_eregi_replace()
4 | split() | mb_split()

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

    » http://examples.oreilly.com/cjkvinfo/doc/cjk.inf

Table of Contents

  • mb_check_encoding — Check if strings are valid for the specified encoding
  • mb_chr — Get a specific character
  • mb_convert_case — Perform case folding on a string
  • mb_convert_encoding — Convert character encoding
  • 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_match — Regular expression match for multibyte string
  • mb_ereg_replace_callback — Perform a regular expression search and replace with multibyte support using a callback
  • mb_ereg_replace — Replace regular expression with multibyte support
  • 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_ereg_search — Multibyte regular expression match for predefined multibyte string
  • mb_ereg — Regular expression match with multibyte support
  • mb_eregi_replace — Replace regular expression with multibyte support ignoring case
  • mb_eregi — Regular expression match ignoring case with multibyte support
  • 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_list_encodings — Returns an array of all supported encodings
  • mb_ord — Get 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_scrub — Description
  • mb_send_mail — Send encoded mail
  • mb_split — Split multibyte string using regular expression
  • 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_count — Count the number of substring occurrences
  • mb_substr — Get part of string


Check if strings are valid for the specified encoding

  • « Multibyte String Functions
  • mb_chr »
  • PHP Manual
  • Multibyte String Functions
  • Check if strings are valid for the specified encoding

mb_check_encoding

(PHP 4 >= 4.4.3, PHP 5 >= 5.1.3, PHP 7)

mb_check_encoding — Check if strings are valid for the specified encoding

Description

mb_check_encoding ([ mixed $var = NULL [, string $encoding = mb_internal_encoding() ]] ) : bool

Checks if the specified byte stream is valid for the specified encoding. If var is of type array, all keys and values are validated recursively. It is useful to prevent so-called "Invalid Encoding Attack".

Parameters

var

The byte stream or array to check. If it is omitted, this function checks all the input from the beginning of the request.

encoding

The expected encoding.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.2.0 | This function now also accepts an array as var. Formerly, only strings have been supported.


Get a specific character

  • « mb_check_encoding
  • mb_convert_case »
  • PHP Manual
  • Multibyte String Functions
  • Get a specific character

mb_chr

(PHP 7 >= 7.2.0)

mb_chr — Get a specific character

Description

mb_chr ( int $cp [, string $encoding ] ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

cp

encoding

Return Values

Returns a specific character or FALSE on failure.

See Also

  • mb_ord() - Get code point of character
  • chr() - Generate a single-byte string from a number


Perform case folding on a string

  • « mb_chr
  • mb_convert_encoding »
  • PHP Manual
  • Multibyte String Functions
  • Perform case folding on a string

mb_convert_case

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

mb_convert_case — Perform case folding on a string

Description

mb_convert_case ( string $str , int $mode [, string $encoding = mb_internal_encoding() ] ) : string

Performs case folding on a string, converted in the way specified by mode.

Parameters

str

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_LOWER_SIMPLE, MB_CASE_UPPER_SIMPLE, MB_CASE_TITLE_SIMPLE, MB_CASE_FOLD_SIMPLE.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

A case folded version of string converted in the way specified by mode.

Unicode

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 as A-umlaut (Ä).

For more information about the Unicode properties, please see » http://www.unicode.org/unicode/reports/tr21/.

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; // Prints MARY HAD A LITTLE LAMB AND SHE LOVED IT SO
$str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
echo $str; // Prints Mary Had A Little Lamb And She Loved It So
?>

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; // Prints ΤΆΧΙΣΤΗ ΑΛΏΠΗΞ ΒΑΦΉΣ ΨΗΜΈΝΗ ΓΗ, ΔΡΑΣΚΕΛΊΖΕΙ ΥΠΈΡ ΝΩΘΡΟΎ ΚΥΝΌΣ
$str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
echo $str; // Prints Τάχιστη Αλώπηξ Βαφήσ Ψημένη Γη, Δρασκελίζει Υπέρ Νωθρού Κυνόσ
?>

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


Convert character encoding

  • « mb_convert_case
  • mb_convert_kana »
  • PHP Manual
  • Multibyte String Functions
  • Convert character encoding

mb_convert_encoding

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_convert_encoding — Convert character encoding

Description

mb_convert_encoding ( mixed $val , string $to_encoding [, mixed $from_encoding = mb_internal_encoding() ] ) : mixed

Converts the character encoding of val to to_encoding from optionally from_encoding. If val is an array, all its string values will be converted recursively.

Parameters

val

The string or array being encoded.

to_encoding

The type of encoding that val is being converted to.

from_encoding

Is specified by character code names before conversion. It is either an array, or a comma separated enumerated list. If from_encoding is not specified, the internal encoding will be used.

See supported encodings.

Return Values

The encoded string or array.

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");

/* "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

Changelog

Version | Description
7.2.0 | This function now also accepts an array as val. Formerly, only strings have been supported.


Convert "kana" one from another ("zen-kaku", "han-kaku" and more)

  • « mb_convert_encoding
  • mb_convert_variables »
  • PHP Manual
  • Multibyte String Functions
  • Convert "kana" one from another ("zen-kaku", "han-kaku" and more)

mb_convert_kana

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_convert_kana — Convert "kana" one from another ("zen-kaku", "han-kaku" and more)

Description

mb_convert_kana ( string $str [, string $option = "KV" [, string $encoding = mb_internal_encoding() ]] ) : string

Performs a "han-kaku" - "zen-kaku" conversion for string str. This function is only useful for Japanese.

Parameters

str

The string being converted.

option

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, the internal character encoding value will be used.

Return Values

The converted string.

Examples

Example #1 mb_convert_kana() example

<?php
/* Convert all "kana" to "zen-kaku" "kata-kana" */
$str = mb_convert_kana($str, "KVC");

/* Convert "han-kaku" "kata-kana" to "zen-kaku" "kata-kana"
   and "zen-kaku" alpha-numeric to "han-kaku" */
$str = mb_convert_kana($str, "KVa");
?>


Convert character code in variable(s)

  • « mb_convert_kana
  • mb_decode_mimeheader »
  • PHP Manual
  • Multibyte String Functions
  • Convert character code in variable(s)

mb_convert_variables

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_convert_variables — Convert character code in variable(s)

Description

mb_convert_variables ( string $to_encoding , mixed $from_encoding , mixed &$vars [, mixed &$... ] ) : string

Converts character encoding of variables 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.

vars

vars is the reference to the variable being converted. String, Array and Object are accepted. mb_convert_variables() assumes all parameters have the same encoding.

...

Additional vars.

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);
?>


Decode string in MIME header field

  • « mb_convert_variables
  • mb_decode_numericentity »
  • PHP Manual
  • Multibyte String Functions
  • Decode string in MIME header field

mb_decode_mimeheader

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_decode_mimeheader — Decode string in MIME header field

Description

mb_decode_mimeheader ( string $str ) : string

Decodes encoded-word string str in MIME header.

Parameters

str

The string being decoded.

Return Values

The decoded string in internal character encoding.

See Also

  • mb_encode_mimeheader() - Encode string for MIME header


Decode HTML numeric string reference to character

  • « mb_decode_mimeheader
  • mb_detect_encoding »
  • PHP Manual
  • Multibyte String Functions
  • Decode HTML numeric string reference to character

mb_decode_numericentity

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_decode_numericentity — Decode HTML numeric string reference to character

Description

mb_decode_numericentity ( string $str , array $convmap [, string $encoding = mb_internal_encoding() [, bool $is_hex = FALSE ]] ) : string

Convert numeric string reference of string str in a specified block to character.

Parameters

str

The string being decoded.

convmap

convmap is an array that specifies the code area to convert.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

is_hex

This parameter is not used.

Return Values

The converted string.

Changelog

Version | Description
5.4.0 | Added is_hex parameter.

Examples

Example #1 convmap 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 convmap 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


Detect character encoding

  • « mb_decode_numericentity
  • mb_detect_order »
  • PHP Manual
  • Multibyte String Functions
  • Detect character encoding

mb_detect_encoding

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_detect_encoding — Detect character encoding

Description

mb_detect_encoding ( string $str [, mixed $encoding_list = mb_detect_order() [, bool $strict = FALSE ]] ) : string

Detects character encoding in string str.

Parameters

str

The string being detected.

encoding_list

encoding_list is list of character encoding. Encoding order may be specified by array or comma separated list string.

If encoding_list is omitted, detect_order is used.

strict

strict specifies whether to use the strict encoding detection or not. Default is FALSE.

Return Values

The detected character encoding or FALSE if the encoding cannot be detected from the given string.

Examples

Example #1 mb_detect_encoding() example

<?php
/* Detect character encoding with current detect_order */
echo mb_detect_encoding($str);

/* "auto" is expanded according to mbstring.language */
echo mb_detect_encoding($str, "auto");

/* Specify encoding_list character encoding by comma separated list */
echo mb_detect_encoding($str, "JIS, eucjp-win, sjis-win");

/* Use array to specify encoding_list  */
$ary[] = "ASCII";
$ary[] = "JIS";
$ary[] = "EUC-JP";
echo mb_detect_encoding($str, $ary);
?>

See Also

  • mb_detect_order() - Set/Get character encoding detection order


Set/Get character encoding detection order

  • « mb_detect_encoding
  • mb_encode_mimeheader »
  • PHP Manual
  • Multibyte String Functions
  • Set/Get character encoding detection order

mb_detect_order

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_detect_order — Set/Get character encoding detection order

Description

mb_detect_order ([ mixed $encoding_list = mb_detect_order() ] ) : mixed

Sets the automatic character encoding detection order to encoding_list.

Parameters

encoding_list

encoding_list is an array or comma separated list of character encoding. See supported encodings.

If encoding_list is omitted, 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.

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


Encode string for MIME header

  • « mb_detect_order
  • mb_encode_numericentity »
  • PHP Manual
  • Multibyte String Functions
  • Encode string for MIME header

mb_encode_mimeheader

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_encode_mimeheader — Encode string for MIME header

Description

mb_encode_mimeheader ( string $str [, string $charset = mb_language() [, string $transfer_encoding = "B" [, string $linefeed = "\r\n" [, int $indent = 0 ]]]] ) : string

Encodes a given string str by the MIME header encoding scheme.

Parameters

str

The string being encoded. Its encoding should be same as mb_internal_encoding().

charset

charset specifies the name of the character set in which str 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.

linefeed

linefeed 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 str).

Return Values

A converted version of the string represented in ASCII.

Examples

Example #1 mb_encode_mimeheader() example

<?php
$name = ""; // kanji
$mbox = "kru";
$doma = "gtinn.mon";
$addr = mb_encode_mimeheader($name, "UTF-7", "Q") . " <" . $mbox . "@" . $doma . ">";
echo $addr;
?>

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


Encode character to HTML numeric string reference

  • « mb_encode_mimeheader
  • mb_encoding_aliases »
  • PHP Manual
  • Multibyte String Functions
  • Encode character to HTML numeric string reference

mb_encode_numericentity

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_encode_numericentity — Encode character to HTML numeric string reference

Description

mb_encode_numericentity ( string $str , array $convmap [, string $encoding = mb_internal_encoding() [, bool $is_hex = FALSE ]] ) : string

Converts specified character codes in string str from character code to HTML numeric character reference.

Parameters

str

The string being encoded.

convmap

convmap is array specifies code area to convert.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

is_hex

Whether the returned entity reference should be in hexadecimal notation (otherwise it is in decimal notation).

Return Values

The converted string.

Changelog

Version | Description
5.4.0 | Added is_hex parameter.

Examples

Example #1 convmap 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.
?>

Examples

Example #2 mb_encode_numericentity() example

<?php
/* Convert Left side of ISO-8859-1 to HTML numeric character reference */
$convmap = array(0x80, 0xff, 0, 0xff);
$str = mb_encode_numericentity($str, $convmap, "ISO-8859-1");

/* Convert user defined SJIS-win code in block 95-104 to numeric
   string reference */
$convmap = array(
       0xe000, 0xe03e, 0x1040, 0xffff,
       0xe03f, 0xe0bb, 0x1041, 0xffff,
       0xe0bc, 0xe0fa, 0x1084, 0xffff,
       0xe0fb, 0xe177, 0x1085, 0xffff,
       0xe178, 0xe1b6, 0x10c8, 0xffff,
       0xe1b7, 0xe233, 0x10c9, 0xffff,
       0xe234, 0xe272, 0x110c, 0xffff,
       0xe273, 0xe2ef, 0x110d, 0xffff,
       0xe2f0, 0xe32e, 0x1150, 0xffff,
       0xe32f, 0xe3ab, 0x1151, 0xffff );
$str = mb_encode_numericentity($str, $convmap, "sjis-win");
?>

See Also

  • mb_decode_numericentity() - Decode HTML numeric string reference to character


Get aliases of a known encoding type

  • « mb_encode_numericentity
  • mb_ereg_match »
  • PHP Manual
  • Multibyte String Functions
  • Get aliases of a known encoding type

mb_encoding_aliases

(PHP 5 >= 5.3.0, PHP 7)

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 on success, or FALSE on failure

Errors/Exceptions

Emits an E_WARNING level error if encoding is unknown.

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


Regular expression match for multibyte string

  • « mb_encoding_aliases
  • mb_ereg_replace_callback »
  • PHP Manual
  • Multibyte String Functions
  • Regular expression match for multibyte string

mb_ereg_match

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

mb_ereg_match — Regular expression match for multibyte string

Description

mb_ereg_match ( string $pattern , string $string [, string $option = "msr" ] ) : bool

A regular expression match for a multibyte string

Parameters

pattern

The regular expression pattern.

string

The string being evaluated.

option

The search option. See mb_regex_set_options() for explanation.

Return Values

Returns TRUE if string matches the regular expression pattern, FALSE if not.

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


Perform a regular expression search and replace with multibyte support using a callback

  • « mb_ereg_match
  • mb_ereg_replace »
  • PHP Manual
  • Multibyte String Functions
  • Perform a regular expression search and replace with multibyte support using a callback

mb_ereg_replace_callback

(PHP 5 >= 5.4.1, PHP 7)

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 $option = "msr" ] ) : string

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 subject 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.

option

The search option. See mb_regex_set_options() for explanation.

Return Values

The resultant string on success, or 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.

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 supported in PHP 5.3.0 or later

<?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);
?>

See Also

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg_replace() - Replace regular expression with multibyte support
  • Anonymous functions
  • information about the callback type


Replace regular expression with multibyte support

  • « mb_ereg_replace_callback
  • mb_ereg_search_getpos »
  • PHP Manual
  • Multibyte String Functions
  • Replace regular expression with multibyte support

mb_ereg_replace

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

mb_ereg_replace — Replace regular expression with multibyte support

Description

mb_ereg_replace ( string $pattern , string $replacement , string $string [, string $option = "msr" ] ) : string

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.

option
The search option. See mb_regex_set_options() for explanation.

Return Values

The resultant string on success, or FALSE on error.

Changelog

Version | Description
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


Returns start point for next regular expression match

  • « mb_ereg_replace
  • mb_ereg_search_getregs »
  • PHP Manual
  • Multibyte String Functions
  • Returns start point for next regular expression match

mb_ereg_search_getpos

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

mb_ereg_search_getpos — Returns start point for next regular expression match

Description

mb_ereg_search_getpos ( void ) : 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


Retrieve the result from the last multibyte regular expression match

  • « mb_ereg_search_getpos
  • mb_ereg_search_init »
  • PHP Manual
  • Multibyte String Functions
  • Retrieve the result from the last multibyte regular expression match

mb_ereg_search_getregs

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

mb_ereg_search_getregs — Retrieve the result from the last multibyte regular expression match

Description

mb_ereg_search_getregs ( void ) : array

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


Setup string and regular expression for a multibyte regular expression match

  • « mb_ereg_search_getregs
  • mb_ereg_search_pos »
  • PHP Manual
  • Multibyte String Functions
  • Setup string and regular expression for a multibyte regular expression match

mb_ereg_search_init

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

mb_ereg_search_init — Setup string and regular expression for a multibyte regular expression match

Description

mb_ereg_search_init ( string $string [, string $pattern [, string $option = "msr" ]] ) : 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.

option

The search option. See mb_regex_set_options() for explanation.

Return Values

Returns TRUE on success or FALSE on failure.

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


Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string

  • « mb_ereg_search_init
  • mb_ereg_search_regs »
  • PHP Manual
  • Multibyte String Functions
  • Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string

mb_ereg_search_pos

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

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 [, string $option = "ms" ]] ) : array

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.

option

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.

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


Returns the matched part of a multibyte regular expression

  • « mb_ereg_search_pos
  • mb_ereg_search_setpos »
  • PHP Manual
  • Multibyte String Functions
  • Returns the matched part of a multibyte regular expression

mb_ereg_search_regs

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

mb_ereg_search_regs — Returns the matched part of a multibyte regular expression

Description

mb_ereg_search_regs ([ string $pattern [, string $option = "ms" ]] ) : array

Returns the matched part of a multibyte regular expression.

Parameters

pattern

The search pattern.

option

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.

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


Set start point of next regular expression match

  • « mb_ereg_search_regs
  • mb_ereg_search »
  • PHP Manual
  • Multibyte String Functions
  • Set start point of next regular expression match

mb_ereg_search_setpos

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

mb_ereg_search_setpos — Set start point of next regular expression match

Description

mb_ereg_search_setpos ( int $position ) : bool

mb_ereg_search_setpos() sets the starting point of a match for mb_ereg_search().

Parameters

position

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 positions 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


Multibyte regular expression match for predefined multibyte string

  • « mb_ereg_search_setpos
  • mb_ereg »
  • PHP Manual
  • Multibyte String Functions
  • Multibyte regular expression match for predefined multibyte string

mb_ereg_search

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

mb_ereg_search — Multibyte regular expression match for predefined multibyte string

Description

mb_ereg_search ([ string $pattern [, string $option = "ms" ]] ) : bool

Performs a multibyte regular expression match for a predefined multibyte string.

Parameters

pattern

The search pattern.

option

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.

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


Regular expression match with multibyte support

  • « mb_ereg_search
  • mb_eregi_replace »
  • PHP Manual
  • Multibyte String Functions
  • Regular expression match with multibyte support

mb_ereg

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

mb_ereg — Regular expression match with multibyte support

Description

mb_ereg ( string $pattern , string $string [, array &$regs ] ) : int

Executes the regular expression match with multibyte support.

Parameters

pattern

The search pattern.

string

The search string.

regs

If matches are found for parenthesized substrings of pattern and the function is called with the third argument regs, the matches will be stored in the elements of the array regs. If no matches are found, regs is set to an empty array.

$regs[1] will contain the substring which starts at the first left parenthesis; $regs[2] will contain the substring starting at the second, and so on. $regs[0] will contain a copy of the complete string matched.

Return Values

Returns the byte length of the matched string if a match for pattern was found in string, or FALSE if no matches were found or an error occurred.

If the optional parameter regs was not passed or the length of the matched string is 0, this function returns 1.

Changelog

Version | Description
7.1.0 | mb_ereg() will now set regs to an empty array, if nothing matched. Formerly, regs 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


Replace regular expression with multibyte support ignoring case

  • « mb_ereg
  • mb_eregi »
  • PHP Manual
  • Multibyte String Functions
  • Replace regular expression with multibyte support ignoring case

mb_eregi_replace

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

mb_eregi_replace — Replace regular expression with multibyte support ignoring case

Description

mb_eregi_replace ( string $pattern , string $replace , string $string [, string $option = "msri" ] ) : string

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.

replace

The replacement text.

string

The searched string.

option
The search option. See mb_regex_set_options() for explanation.

Return Values

The resultant string or FALSE on error.

Changelog

Version | Description
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


Regular expression match ignoring case with multibyte support

  • « mb_eregi_replace
  • mb_get_info »
  • PHP Manual
  • Multibyte String Functions
  • Regular expression match ignoring case with multibyte support

mb_eregi

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

mb_eregi — Regular expression match ignoring case with multibyte support

Description

mb_eregi ( string $pattern , string $string [, array &$regs ] ) : int

Executes the case insensitive regular expression match with multibyte support.

Parameters

pattern

The regular expression pattern.

string

The string being searched.

regs

If matches are found for parenthesized substrings of pattern and the function is called with the third argument regs, the matches will be stored in the elements of the array regs. If no matches are found, regs is set to an empty array.

$regs[1] will contain the substring which starts at the first left parenthesis; $regs[2] will contain the substring starting at the second, and so on. $regs[0] will contain a copy of the complete string matched.

Return Values

Returns the byte length of the matched string if a match for pattern was found in string, or FALSE if no matches were found or an error occurred.

If the optional parameter regs was not passed or the length of the matched string is 0, this function returns 1.

Changelog

Version | Description
7.1.0 | mb_eregi() will now set regs to an empty array, if nothing matched. Formerly, regs 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


Get internal settings of mbstring

  • « mb_eregi
  • mb_http_input »
  • PHP Manual
  • Multibyte String Functions
  • Get internal settings of mbstring

mb_get_info

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

mb_get_info — Get internal settings of mbstring

Description

mb_get_info ([ string $type = "all" ] ) : mixed

mb_get_info() returns the internal setting parameters of mbstring.

Parameters

type

If type isn't specified or is specified to "all", an array having the elements "internal_encoding", "http_output", "http_input", "func_overload", "mail_charset", "mail_header_encoding", "mail_body_encoding" will be returned.

If type is specified as "http_output", "http_input", "internal_encoding", "func_overload", the specified setting parameter will be returned.

Return Values

An array of type information if type is not specified, otherwise a specific type.

Changelog

Version | Description
5.3.0 | The entry "http_output_conv_mimetypes" was made available.
5.1.3 | The entries "mail_charset", "mail_header_encoding", and "mail_body_encoding" were made available.

See Also

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_http_output() - Set/Get HTTP output character encoding


Detect HTTP input character encoding

  • « mb_get_info
  • mb_http_output »
  • PHP Manual
  • Multibyte String Functions
  • Detect HTTP input character encoding

mb_http_input

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_http_input — Detect HTTP input character encoding

Description

mb_http_input ([ string $type = "" ] ) : mixed

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. If mb_http_input() does not process specified HTTP input, it returns FALSE.

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


Set/Get HTTP output character encoding

  • « mb_http_input
  • mb_internal_encoding »
  • PHP Manual
  • Multibyte String Functions
  • Set/Get HTTP output character encoding

mb_http_output

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_http_output — Set/Get HTTP output character encoding

Description

mb_http_output ([ string $encoding = mb_http_output() ] ) : mixed

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.

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


Set/Get internal character encoding

  • « mb_http_output
  • mb_language »
  • PHP Manual
  • Multibyte String Functions
  • Set/Get internal character encoding

mb_internal_encoding

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_internal_encoding — Set/Get internal character encoding

Description

mb_internal_encoding ([ string $encoding = mb_internal_encoding() ] ) : mixed

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.

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


Set/Get current language

  • « mb_internal_encoding
  • mb_list_encodings »
  • PHP Manual
  • Multibyte String Functions
  • Set/Get current language

mb_language

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_language — Set/Get current language

Description

mb_language ( string $language ) : bool
mb_language ( void ) : string

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 | Notes
German/de | ISO-8859-15 | Quoted-Printable
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 | Available as of PHP 5.2.0
Ukrainian/ua | KOI8-U | Quoted-Printable | Available as of PHP 5.3.0
uni | UTF-8 | BASE64
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, it returns the language name as a string.

See Also

  • mb_send_mail() - Send encoded mail


Returns an array of all supported encodings

  • « mb_language
  • mb_ord »
  • PHP Manual
  • Multibyte String Functions
  • Returns an array of all supported encodings

mb_list_encodings

(PHP 5, PHP 7)

mb_list_encodings — Returns an array of all supported encodings

Description

mb_list_encodings ( void ) : 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
)


Get code point of character

  • « mb_list_encodings
  • mb_output_handler »
  • PHP Manual
  • Multibyte String Functions
  • Get code point of character

mb_ord

(PHP 7 >= 7.2.0)

mb_ord — Get code point of character

Description

mb_ord ( string $str [, string $encoding ] ) : int

Warning

This function is currently not documented; only its argument list is available.

Parameters

str

encoding

Return Values

Returns a code point of character or FALSE on failure.

See Also

  • mb_chr() - Get a specific character
  • ord() - Convert the first byte of a string to a value between 0 and 255


Callback function converts character encoding in output buffer

  • « mb_ord
  • mb_parse_str »
  • PHP Manual
  • Multibyte String Functions
  • Callback function converts character encoding in output buffer

mb_output_handler

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_output_handler — Callback function converts character encoding in output buffer

Description

mb_output_handler ( string $contents , 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

contents

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


Parse GET/POST/COOKIE data and set global variable

  • « mb_output_handler
  • mb_preferred_mime_name »
  • PHP Manual
  • Multibyte String Functions
  • Parse GET/POST/COOKIE data and set global variable

mb_parse_str

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_parse_str — Parse GET/POST/COOKIE data and set global variable

Description

mb_parse_str ( string $encoded_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

encoded_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.

See Also

  • mb_detect_order() - Set/Get character encoding detection order
  • mb_internal_encoding() - Set/Get internal character encoding


Get MIME charset string

  • « mb_parse_str
  • mb_regex_encoding »
  • PHP Manual
  • Multibyte String Functions
  • Get MIME charset string

mb_preferred_mime_name

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_preferred_mime_name — Get MIME charset string

Description

mb_preferred_mime_name ( string $encoding ) : string

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.

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));
?>


Set/Get character encoding for multibyte regex

  • « mb_preferred_mime_name
  • mb_regex_set_options »
  • PHP Manual
  • Multibyte String Functions
  • Set/Get character encoding for multibyte regex

mb_regex_encoding

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

mb_regex_encoding — Set/Get character encoding for multibyte regex

Description

mb_regex_encoding ([ string $encoding = mb_regex_encoding() ] ) : mixed

Set/Get character encoding for a multibyte regex.

Parameters

encoding

The encoding parameter is the character encoding. If it is omitted, 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
5.6.0 | Default encoding is changed to UTF-8. It was EUC-JP Previously.

See Also

  • mb_internal_encoding() - Set/Get internal character encoding
  • mb_ereg() - Regular expression match with multibyte support


Set/Get the default options for mbregex functions

  • « mb_regex_encoding
  • mb_scrub »
  • PHP Manual
  • Multibyte String Functions
  • Set/Get the default options for mbregex functions

mb_regex_set_options

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

mb_regex_set_options — Set/Get the default options for mbregex functions

Description

mb_regex_set_options ([ string $options = mb_regex_set_options() ] ) : 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
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
Regex syntax modes
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, it returns the string that describes the current options.

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


Description

  • « mb_regex_set_options
  • mb_send_mail »
  • PHP Manual
  • Multibyte String Functions
  • Description

mb_scrub

(PHP 7 >= 7.2.0)

mb_scrub — Description

Description

mb_scrub ( string $str [, string $encoding ] ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

str

encoding

Return Values


Send encoded mail

  • « mb_scrub
  • mb_split »
  • PHP Manual
  • Multibyte String Functions
  • Send encoded mail

mb_send_mail

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_send_mail — Send encoded mail

Description

mb_send_mail ( string $to , string $subject , string $message [, mixed $additional_headers = NULL [, string $additional_parameter = 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_parameter

additional_parameter 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
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


Split multibyte string using regular expression

  • « mb_send_mail
  • mb_strcut »
  • PHP Manual
  • Multibyte String Functions
  • Split multibyte string using regular expression

mb_split

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

mb_split — Split multibyte string using regular expression

Description

mb_split ( string $pattern , string $string [, int $limit = -1 ] ) : array

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


Get part of string

  • « mb_split
  • mb_strimwidth »
  • PHP Manual
  • Multibyte String Functions
  • Get part of string

mb_strcut

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_strcut — Get part of string

Description

mb_strcut ( string $str , int $start [, int $length = NULL [, string $encoding = mb_internal_encoding() ]] ) : 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

str

The string being cut.

start

If start is non-negative, the returned string will start at the start'th byte position in str, 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 from the end of str.

length

Length in bytes. If omitted or NULL is passed, extract all bytes to the end of the string.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

mb_strcut() returns the portion of str specified by the start and length parameters.

Changelog

Version | Description
5.4.8 | Passing NULL as length extracts all bytes to the end of the string. Prior to this version NULL was treated the same as 0.

See Also

  • mb_substr() - Get part of string
  • mb_internal_encoding() - Set/Get internal character encoding


Get truncated string with specified width

  • « mb_strcut
  • mb_stripos »
  • PHP Manual
  • Multibyte String Functions
  • Get truncated string with specified width

mb_strimwidth

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_strimwidth — Get truncated string with specified width

Description

mb_strimwidth ( string $str , int $start , int $width [, string $trimmarker = "" [, string $encoding = mb_internal_encoding() ]] ) : string

Truncates string str to specified width.

Parameters

str

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. Negative widths count from the end of the string.

trimmarker

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, the internal character encoding value will be used.

Return Values

The truncated string. If trimmarker is set, trimmarker replaces the last chars to match the width.

Changelog

Version | Description
7.1.0 | Support for negative starts and widths 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


Finds position of first occurrence of a string within another, case insensitive

  • « mb_strimwidth
  • mb_stristr »
  • PHP Manual
  • Multibyte String Functions
  • Finds position of first occurrence of a string within another, case insensitive

mb_stripos

(PHP 5 >= 5.2.0, PHP 7)

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 = mb_internal_encoding() ]] ) : int

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

Character encoding name to use. If it is omitted, internal character encoding is used.

Return Values

Return the numeric position of the first occurrence of needle in the haystack string, or FALSE if needle is not found.

Changelog

Version | Description
7.1.0 | Support for negative offsets 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


Finds first occurrence of a string within another, case insensitive

  • « mb_stripos
  • mb_strlen »
  • PHP Manual
  • Multibyte String Functions
  • Finds first occurrence of a string within another, case insensitive

mb_stristr

(PHP 5 >= 5.2.0, PHP 7)

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 = mb_internal_encoding() ]] ) : string

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

Character encoding name to use. If it is omitted, internal character encoding is used.

Return Values

Returns the portion of haystack, or FALSE if needle is not found.

See Also

  • stristr() - Case-insensitive strstr
  • strstr() - Find the first occurrence of a string
  • mb_strstr() - Finds first occurrence of a string within another


Get string length

  • « mb_stristr
  • mb_strpos »
  • PHP Manual
  • Multibyte String Functions
  • Get string length

mb_strlen

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_strlen — Get string length

Description

mb_strlen ( string $str [, string $encoding = mb_internal_encoding() ] ) : int

Gets the length of a string.

Parameters

str

The string being checked for length.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

Returns the number of characters in string str 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.

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


Find position of first occurrence of string in a string

  • « mb_strlen
  • mb_strrchr »
  • PHP Manual
  • Multibyte String Functions
  • Find position of first occurrence of string in a string

mb_strpos

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_strpos — Find position of first occurrence of string in a string

Description

mb_strpos ( string $haystack , string $needle [, int $offset = 0 [, string $encoding = mb_internal_encoding() ]] ) : int

Finds position of the first occurrence of a string in a 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 being checked.

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, 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.

Changelog

Version | Description
7.1.0 | Support for negative offsets 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


Finds the last occurrence of a character in a string within another

  • « mb_strpos
  • mb_strrichr »
  • PHP Manual
  • Multibyte String Functions
  • Finds the last occurrence of a character in a string within another

mb_strrchr

(PHP 5 >= 5.2.0, PHP 7)

mb_strrchr — Finds the last occurrence of a character in a string within another

Description

mb_strrchr ( string $haystack , string $needle [, bool $part = FALSE [, string $encoding = mb_internal_encoding() ]] ) : string

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

part

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

Character encoding name to use. If it is omitted, internal character encoding is used.

Return Values

Returns the portion of haystack. or FALSE if needle is not found.

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


Finds the last occurrence of a character in a string within another, case insensitive

  • « mb_strrchr
  • mb_strripos »
  • PHP Manual
  • Multibyte String Functions
  • Finds the last occurrence of a character in a string within another, case insensitive

mb_strrichr

(PHP 5 >= 5.2.0, PHP 7)

mb_strrichr — Finds the last occurrence of a character in a string within another, case insensitive

Description

mb_strrichr ( string $haystack , string $needle [, bool $part = FALSE [, string $encoding = mb_internal_encoding() ]] ) : string

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

part

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

Character encoding name to use. If it is omitted, internal character encoding is used.

Return Values

Returns the portion of haystack. or FALSE if needle is not found.

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


Finds position of last occurrence of a string within another, case insensitive

  • « mb_strrichr
  • mb_strrpos »
  • PHP Manual
  • Multibyte String Functions
  • Finds position of last occurrence of a string within another, case insensitive

mb_strripos

(PHP 5 >= 5.2.0, PHP 7)

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 = mb_internal_encoding() ]] ) : int

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

The position in haystack to start searching

encoding

Character encoding name to use. If it is omitted, internal character encoding is used.

Return Values

Return the numeric position of the last occurrence of needle in the haystack string, or FALSE if needle is not found.

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


Find position of last occurrence of a string in a string

  • « mb_strripos
  • mb_strstr »
  • PHP Manual
  • Multibyte String Functions
  • Find position of last occurrence of a string in a string

mb_strrpos

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

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 = mb_internal_encoding() ]] ) : int

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 string. Negative values will stop searching at an arbitrary point prior to the end of the string.
encoding

The encoding parameter is the character encoding. If it is omitted, 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.

Changelog

Version | Description
5.2.0 | Added the optional parameter offset.

Notes

Note: The encoding parameter was moved from the third position to the fourth in PHP 5.2.0. For backward compatibility, encoding can be specified as the third parameter, but doing so is deprecated and will be removed in the future.

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


Finds first occurrence of a string within another

  • « mb_strrpos
  • mb_strtolower »
  • PHP Manual
  • Multibyte String Functions
  • Finds first occurrence of a string within another

mb_strstr

(PHP 5 >= 5.2.0, PHP 7)

mb_strstr — Finds first occurrence of a string within another

Description

mb_strstr ( string $haystack , string $needle [, bool $before_needle = FALSE [, string $encoding = mb_internal_encoding() ]] ) : string

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

Character encoding name to use. If it is omitted, internal character encoding is used.

Return Values

Returns the portion of haystack, or FALSE if needle is not found.

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


Make a string lowercase

  • « mb_strstr
  • mb_strtoupper »
  • PHP Manual
  • Multibyte String Functions
  • Make a string lowercase

mb_strtolower

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

mb_strtolower — Make a string lowercase

Description

mb_strtolower ( string $str [, string $encoding = mb_internal_encoding() ] ) : string

Returns str with all alphabetic characters converted to lowercase.

Parameters

str

The string being lowercased.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

str with all alphabetic characters converted to lowercase.

Unicode

For more information about the Unicode properties, please see » http://www.unicode.org/unicode/reports/tr21/.

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 (Ä).

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 τάχιστη αλώπηξ βαφής ψημένη γη, δρασκελίζει υπέρ νωθρού κυνός
?>

See Also

  • mb_strtoupper() - Make a string uppercase
  • mb_convert_case() - Perform case folding on a string
  • strtolower() - Make a string lowercase


Make a string uppercase

  • « mb_strtolower
  • mb_strwidth »
  • PHP Manual
  • Multibyte String Functions
  • Make a string uppercase

mb_strtoupper

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

mb_strtoupper — Make a string uppercase

Description

mb_strtoupper ( string $str [, string $encoding = mb_internal_encoding() ] ) : string

Returns str with all alphabetic characters converted to uppercase.

Parameters

str

The string being uppercased.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

str with all alphabetic characters converted to uppercase.

Unicode

For more information about the Unicode properties, please see » http://www.unicode.org/unicode/reports/tr21/.

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 (ä).

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 ΤΆΧΙΣΤΗ ΑΛΏΠΗΞ ΒΑΦΉΣ ΨΗΜΈΝΗ ΓΗ, ΔΡΑΣΚΕΛΊΖΕΙ ΥΠΈΡ ΝΩΘΡΟΎ ΚΥΝΌΣ
?>

See Also

  • mb_strtolower() - Make a string lowercase
  • mb_convert_case() - Perform case folding on a string
  • strtoupper() - Make a string uppercase


Return width of string

  • « mb_strtoupper
  • mb_substitute_character »
  • PHP Manual
  • Multibyte String Functions
  • Return width of string

mb_strwidth

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_strwidth — Return width of string

Description

mb_strwidth ( string $str [, string $encoding = mb_internal_encoding() ] ) : int

Returns the width of string str, where halfwidth characters count as 1, and fullwidth characters count as 2.

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

str

The string being decoded.

encoding

The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

Return Values

The width of string str.

See Also

  • mb_strimwidth() - Get truncated string with specified width
  • mb_internal_encoding() - Set/Get internal character encoding


Set/Get substitution character

  • « mb_strwidth
  • mb_substr_count »
  • PHP Manual
  • Multibyte String Functions
  • Set/Get substitution character

mb_substitute_character

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_substitute_character — Set/Get substitution character

Description

mb_substitute_character ([ mixed $substchar = mb_substitute_character() ] ) : mixed

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 NULL (no output), string or integer value (Unicode character code value).

This setting affects mb_convert_encoding(),
mb_convert_variables(),
mb_output_handler(),
and mb_send_mail().

Parameters

substchar

Specify the Unicode value as an integer, 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 substchar is set, it returns TRUE for success, otherwise returns FALSE. If substchar is not set, it returns the current setting.

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();
?>


Count the number of substring occurrences

  • « mb_substitute_character
  • mb_substr »
  • PHP Manual
  • Multibyte String Functions
  • Count the number of substring occurrences

mb_substr_count

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

mb_substr_count — Count the number of substring occurrences

Description

mb_substr_count ( string $haystack , string $needle [, string $encoding = mb_internal_encoding() ] ) : 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, the internal character encoding value will be used.

Return Values

The number of times the needle substring occurs in the haystack string.

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


Get part of string

  • « mb_substr_count
  • Pspell »
  • PHP Manual
  • Multibyte String Functions
  • Get part of string

mb_substr

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

mb_substr — Get part of string

Description

mb_substr ( string $str , int $start [, int $length = NULL [, string $encoding = mb_internal_encoding() ]] ) : string

Performs a multi-byte safe substr() operation based on number of characters. Position is counted from the beginning of str. First character's position is 0. Second character position is 1, and so on.

Parameters

str

The string to extract the substring from.

start

If start is non-negative, the returned string will start at the start'th position in str, 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 str.

length

Maximum number of characters to use from str. 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, the internal character encoding value will be used.

Return Values

mb_substr() returns the portion of str specified by the start and length parameters.

Changelog

Version | Description
5.4.8 | Passing NULL as length extracts all characters to the end of the string. Prior to this version NULL was treated the same as 0.

See Also

  • mb_strcut() - Get part of string
  • mb_internal_encoding() - Set/Get internal character encoding


Pspell

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • 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_config — Load a new dictionary with settings based on a given config
    • pspell_new_personal — Load a new dictionary with personal wordlist
    • pspell_new — Load a new dictionary
    • 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


Introduction

These functions allow you to check the spelling of a word and offer suggestions.


Requirements

To compile PHP with pspell support, you need the aspell library, available from » http://aspell.net/.


Installation

If you have the libraries needed add the --with-pspell[=dir] option when compiling PHP.

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.


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 (integer)
PSPELL_NORMAL (integer)
PSPELL_BAD_SPELLERS (integer)
PSPELL_RUN_TOGETHER (integer)


Pspell Functions

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_config — Load a new dictionary with settings based on a given config
  • pspell_new_personal — Load a new dictionary with personal wordlist
  • pspell_new — Load a new dictionary
  • 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


Add the word to a personal wordlist

  • « Pspell Functions
  • pspell_add_to_session »
  • PHP Manual
  • Pspell Functions
  • Add the word to a personal wordlist

pspell_add_to_personal

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_add_to_personal — Add the word to a personal wordlist

Description

pspell_add_to_personal ( int $dictionary_link , 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_link

word

The added word.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pspell_add_to_personal()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
$pspell_link = pspell_new_config($pspell_config);

pspell_add_to_personal($pspell_link, "Vlad");
pspell_save_wordlist($pspell_link);
?>

Notes

Note:

This function will not work unless you have pspell .11.2 and aspell .32.5 or later.


Add the word to the wordlist in the current session

  • « pspell_add_to_personal
  • pspell_check »
  • PHP Manual
  • Pspell Functions
  • Add the word to the wordlist in the current session

pspell_add_to_session

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_add_to_session — Add the word to the wordlist in the current session

Description

pspell_add_to_session ( int $dictionary_link , 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_link

word

The added word.

Return Values

Returns TRUE on success or FALSE on failure.


Check a word

  • « pspell_add_to_session
  • pspell_clear_session »
  • PHP Manual
  • Pspell Functions
  • Check a word

pspell_check

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_check — Check a word

Description

pspell_check ( int $dictionary_link , string $word ) : bool

pspell_check() checks the spelling of a word.

Parameters

dictionary_link

word

The tested word.

Return Values

Returns TRUE if the spelling is correct, FALSE if not.

Examples

Example #1 pspell_check() Example

<?php
$pspell_link = pspell_new("en");

if (pspell_check($pspell_link, "testt")) {
    echo "This is a valid spelling";
} else {
    echo "Sorry, wrong spelling";
}
?>


Clear the current session

  • « pspell_check
  • pspell_config_create »
  • PHP Manual
  • Pspell Functions
  • Clear the current session

pspell_clear_session

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_clear_session — Clear the current session

Description

pspell_clear_session ( int $dictionary_link ) : 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_link

Return Values

Returns TRUE on success or FALSE on failure.

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_link = pspell_new_config($pspell_config);

pspell_add_to_personal($pspell_link, "Vlad");
pspell_clear_session($pspell_link);
pspell_save_wordlist($pspell_link);    //"Vlad" will not be saved
?>


Create a config used to open a dictionary

  • « pspell_clear_session
  • pspell_config_data_dir »
  • PHP Manual
  • Pspell Functions
  • Create a config used to open a dictionary

pspell_config_create

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_config_create — Create a config used to open a dictionary

Description

pspell_config_create ( string $language [, string $spelling [, string $jargon [, string $encoding ]]] ) : int

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

Retuns a pspell config identifier, or FALSE on error.

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_link = pspell_new_personal($pspell_config, "en");
?>


Location of language data files

  • « pspell_config_create
  • pspell_config_dict_dir »
  • PHP Manual
  • Pspell Functions
  • Location of language data files

pspell_config_data_dir

(PHP 5, PHP 7)

pspell_config_data_dir — Location of language data files

Description

pspell_config_data_dir ( int $conf , 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.


Location of the main word list

  • « pspell_config_data_dir
  • pspell_config_ignore »
  • PHP Manual
  • Pspell Functions
  • Location of the main word list

pspell_config_dict_dir

(PHP 5, PHP 7)

pspell_config_dict_dir — Location of the main word list

Description

pspell_config_dict_dir ( int $conf , 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.


Ignore words less than N characters long

  • « pspell_config_dict_dir
  • pspell_config_mode »
  • PHP Manual
  • Pspell Functions
  • Ignore words less than N characters long

pspell_config_ignore

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_config_ignore — Ignore words less than N characters long

Description

pspell_config_ignore ( int $dictionary_link , int $n ) : 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

dictionary_link

n

Words less than n characters will be skipped.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pspell_config_ignore()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_ignore($pspell_config, 5);
$pspell_link = pspell_new_config($pspell_config);
pspell_check($pspell_link, "abcd");    //will not result in an error
?>


Change the mode number of suggestions returned

  • « pspell_config_ignore
  • pspell_config_personal »
  • PHP Manual
  • Pspell Functions
  • Change the mode number of suggestions returned

pspell_config_mode

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_config_mode — Change the mode number of suggestions returned

Description

pspell_config_mode ( int $dictionary_link , 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

dictionary_link

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.

Examples

Example #1 pspell_config_mode() Example

<?php
$pspell_config = pspell_config_create("en");
pspell_config_mode($pspell_config, PSPELL_FAST);
$pspell_link = pspell_new_config($pspell_config);
pspell_check($pspell_link, "thecat");
?>


Set a file that contains personal wordlist

  • « pspell_config_mode
  • pspell_config_repl »
  • PHP Manual
  • Pspell Functions
  • Set a file that contains personal wordlist

pspell_config_personal

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_config_personal — Set a file that contains personal wordlist

Description

pspell_config_personal ( int $dictionary_link , string $file ) : 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

dictionary_link

file

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.

Examples

Example #1 pspell_config_personal()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
$pspell_link = pspell_new_config($pspell_config);
pspell_check($pspell_link, "thecat");
?>

Notes

Note:

This function will not work unless you have pspell .11.2 and aspell .32.5 or later.


Set a file that contains replacement pairs

  • « pspell_config_personal
  • pspell_config_runtogether »
  • PHP Manual
  • Pspell Functions
  • Set a file that contains replacement pairs

pspell_config_repl

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_config_repl — Set a file that contains replacement pairs

Description

pspell_config_repl ( int $dictionary_link , string $file ) : 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

dictionary_link

file

The file should be writable by whoever PHP runs as (e.g. nobody).

Return Values

Returns TRUE on success or FALSE on failure.

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_link = pspell_new_config($pspell_config);
pspell_check($pspell_link, "thecat");
?>

Notes

Note:

This function will not work unless you have pspell .11.2 and aspell .32.5 or later.


Consider run-together words as valid compounds

  • « pspell_config_repl
  • pspell_config_save_repl »
  • PHP Manual
  • Pspell Functions
  • Consider run-together words as valid compounds

pspell_config_runtogether

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_config_runtogether — Consider run-together words as valid compounds

Description

pspell_config_runtogether ( int $dictionary_link , bool $flag ) : 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

dictionary_link

flag

TRUE if run-together words should be treated as legal compounds, FALSE otherwise.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pspell_config_runtogether()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_runtogether($pspell_config, true);
$pspell_link = pspell_new_config($pspell_config);
pspell_check($pspell_link, "thecat");
?>


Determine whether to save a replacement pairs list along with the wordlist

  • « pspell_config_runtogether
  • pspell_new_config »
  • PHP Manual
  • Pspell Functions
  • Determine whether to save a replacement pairs list along with the wordlist

pspell_config_save_repl

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_config_save_repl — Determine whether to save a replacement pairs list along with the wordlist

Description

pspell_config_save_repl ( int $dictionary_link , bool $flag ) : 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

dictionary_link

flag

TRUE if replacement pairs should be saved, FALSE otherwise.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note:

This function will not work unless you have pspell .11.2 and aspell .32.5 or later.


Load a new dictionary with settings based on a given config

  • « pspell_config_save_repl
  • pspell_new_personal »
  • PHP Manual
  • Pspell Functions
  • Load a new dictionary with settings based on a given config

pspell_new_config

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_new_config — Load a new dictionary with settings based on a given config

Description

pspell_new_config ( int $config ) : int

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 a dictionary link identifier on success, or FALSE on failure.

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_link = pspell_new_config($pspell_config);
?>


Load a new dictionary with personal wordlist

  • « pspell_new_config
  • pspell_new »
  • PHP Manual
  • Pspell Functions
  • Load a new dictionary with personal wordlist

pspell_new_personal

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_new_personal — Load a new dictionary with personal wordlist

Description

pspell_new_personal ( string $personal , string $language [, string $spelling [, string $jargon [, string $encoding [, int $mode = 0 ]]]] ) : int

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

personal

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 the dictionary link identifier for use in other pspell functions.

Examples

Example #1 pspell_new_personal()

<?php
$pspell_link = pspell_new_personal ("/var/dictionaries/custom.pws",
        "en", "", "", "", PSPELL_FAST|PSPELL_RUN_TOGETHER);
?>


Load a new dictionary

  • « pspell_new_personal
  • pspell_save_wordlist »
  • PHP Manual
  • Pspell Functions
  • Load a new dictionary

pspell_new

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_new — Load a new dictionary

Description

pspell_new ( string $language [, string $spelling [, string $jargon [, string $encoding [, int $mode = 0 ]]]] ) : int

pspell_new() opens up a new dictionary and returns the dictionary link identifier 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 the dictionary link identifier on success or FALSE on failure.

Examples

Example #1 pspell_new()

<?php
$pspell_link = pspell_new("en", "", "", "",
                           (PSPELL_FAST|PSPELL_RUN_TOGETHER));
?>


Save the personal wordlist to a file

  • « pspell_new
  • pspell_store_replacement »
  • PHP Manual
  • Pspell Functions
  • Save the personal wordlist to a file

pspell_save_wordlist

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_save_wordlist — Save the personal wordlist to a file

Description

pspell_save_wordlist ( int $dictionary_link ) : 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_link

A dictionary link identifier opened with pspell_new_personal().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pspell_add_to_personal()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/tmp/dicts/newdict");
$pspell_link = pspell_new_config($pspell_config);

pspell_add_to_personal($pspell_link, "Vlad");
pspell_save_wordlist($pspell_link);
?>

Notes

Note:

This function will not work unless you have pspell .11.2 and aspell .32.5 or later.


Store a replacement pair for a word

  • « pspell_save_wordlist
  • pspell_suggest »
  • PHP Manual
  • Pspell Functions
  • Store a replacement pair for a word

pspell_store_replacement

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_store_replacement — Store a replacement pair for a word

Description

pspell_store_replacement ( int $dictionary_link , 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_link

A dictionary link identifier, opened with pspell_new_personal()

misspelled

The misspelled word.

correct

The fixed spelling for the misspelled word.

Return Values

Returns TRUE on success or FALSE on failure.

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_link = pspell_new_config($pspell_config);

pspell_store_replacement($pspell_link, $misspelled, $correct);
pspell_save_wordlist($pspell_link);
?>

Notes

Note:

This function will not work unless you have pspell .11.2 and aspell .32.5 or later.


Suggest spellings of a word

  • « pspell_store_replacement
  • Recode »
  • PHP Manual
  • Pspell Functions
  • Suggest spellings of a word

pspell_suggest

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

pspell_suggest — Suggest spellings of a word

Description

pspell_suggest ( int $dictionary_link , string $word ) : array

pspell_suggest() returns an array of possible spellings for the given word.

Parameters

dictionary_link

word

The tested word.

Return Values

Returns an array of possible spellings.

Examples

Example #1 pspell_suggest() example

<?php
$pspell_link = pspell_new("en");

if (!pspell_check($pspell_link, "testt")) {
    $suggestions = pspell_suggest($pspell_link, "testt");

    foreach ($suggestions as $suggestion) {
        echo "Possible spelling: $suggestion<br />";
    }
}
?>


GNU Recode

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Recode Functions
    • recode_file — Recode from file to file according to recode request
    • recode_string — Recode a string according to a recode request
    • recode — Alias of recode_string


Introduction

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.


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

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, YAZ and Cyrus 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.


  • « Resource Types
  • Recode Functions »
  • PHP Manual
  • Recode
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


Recode Functions

Table of Contents

  • recode_file — Recode from file to file according to recode request
  • recode_string — Recode a string according to a recode request
  • recode — Alias of recode_string


Recode from file to file according to recode request

  • « Recode Functions
  • recode_string »
  • PHP Manual
  • Recode Functions
  • Recode from file to file according to recode request

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 a string according to a recode request

  • « recode_file
  • recode »
  • PHP Manual
  • Recode Functions
  • Recode a string according to a recode request

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.


Alias of recode_string

  • « recode_string
  • Image Processing and Generation »
  • PHP Manual
  • Recode Functions
  • Alias of recode_string

recode

(PHP 4, PHP 5, PHP 7 < 7.4.0)

recode — Alias of recode_string()

Description

This function is an alias of: recode_string().


Image Processing and Generation

  • Cairo
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Cairo Functions
    • Cairo — The Cairo class
    • CairoContext — The CairoContext class
    • CairoException — The CairoException class
    • CairoStatus — The CairoStatus class
    • CairoSurface — The CairoSurface class
    • CairoSvgSurface — Svg Surface Backend
    • CairoImageSurface — The CairoImageSurface class
    • CairoPdfSurface — The CairoPdfSurface class
    • CairoPsSurface — The CairoPsSurface class
    • CairoSurfaceType — The CairoSurfaceType class
    • CairoFontFace — The CairoFontFace class
    • CairoFontOptions — The CairoFontOptions class
    • CairoFontSlant — The CairoFontSlant class
    • CairoFontType — The CairoFontType class
    • CairoFontWeight — The CairoFontWeight class
    • CairoScaledFont — The CairoScaledFont class
    • CairoToyFontFace — The CairoToyFontFace class
    • CairoPatternType — The CairoPatternType class
    • CairoPattern — The CairoPattern class
    • CairoGradientPattern — The CairoGradientPattern class
    • CairoSolidPattern — The CairoSolidPattern class
    • CairoSurfacePattern — The CairoSurfacePattern class
    • CairoLinearGradient — The CairoLinearGradient class
    • CairoRadialGradient — The CairoRadialGradient class
    • CairoAntialias — The CairoAntialias class
    • CairoContent — The CairoContent class
    • CairoExtend — The CairoExtend class
    • CairoFormat — The CairoFormat class
    • CairoFillRule — The CairoFillRule class
    • CairoFilter — The CairoFilter class
    • CairoHintMetrics — The CairoHintMetrics class
    • CairoHintStyle — The CairoHintStyle class
    • CairoLineCap — The CairoLineCap class
    • CairoLineJoin — The CairoLineJoin class
    • CairoMatrix — The CairoMatrix class
    • CairoOperator — The CairoOperator class
    • CairoPath — The CairoPath class
    • CairoPsLevel — The CairoPsLevel class
    • CairoSubpixelOrder — The CairoSubpixelOrder class
    • CairoSvgVersion — The CairoSvgVersion class
  • Exif — Exchangeable image information
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Exif Functions
  • GD — Image Processing and GD
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • GD and Image Functions
  • Gmagick
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Gmagick — The Gmagick class
    • GmagickDraw — The GmagickDraw class
    • GmagickPixel — The GmagickPixel class
  • ImageMagick — Image Processing (ImageMagick)
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Imagick — The Imagick class
    • ImagickDraw — The ImagickDraw class
    • ImagickPixel — The ImagickPixel class
    • ImagickPixelIterator — The ImagickPixelIterator class
    • ImagickKernel — The ImagickKernel class


Cairo

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Cairo Functions
    • cairo_create — Returns a new CairoContext object on the requested surface
    • cairo_font_options_create — Description
    • cairo_font_options_equal — Description
    • cairo_font_options_get_antialias — Description
    • cairo_font_options_get_hint_metrics — Description
    • cairo_font_options_get_hint_style — Description
    • cairo_font_options_get_subpixel_order — Description
    • cairo_font_options_hash — Description
    • cairo_font_options_merge — Description
    • cairo_font_options_set_antialias — Description
    • cairo_font_options_set_hint_metrics — Description
    • cairo_font_options_set_hint_style — Description
    • cairo_font_options_set_subpixel_order — Description
    • cairo_font_options_status — Description
    • cairo_format_stride_for_width — Description
    • cairo_image_surface_create_for_data — Description
    • cairo_image_surface_create_from_png — Description
    • cairo_image_surface_create — Description
    • cairo_image_surface_get_data — Description
    • cairo_image_surface_get_format — Description
    • cairo_image_surface_get_height — Description
    • cairo_image_surface_get_stride — Description
    • cairo_image_surface_get_width — Description
    • cairo_matrix_create_scale — Alias of CairoMatrix::initScale
    • cairo_matrix_create_translate — Alias of CairoMatrix::initTranslate
    • cairo_matrix_invert — Description
    • cairo_matrix_multiply — Description
    • cairo_matrix_transform_distance — Description
    • cairo_matrix_transform_point — Description
    • cairo_matrix_translate — Description
    • cairo_pattern_add_color_stop_rgb — Description
    • cairo_pattern_add_color_stop_rgba — Description
    • cairo_pattern_create_for_surface — Description
    • cairo_pattern_create_linear — Description
    • cairo_pattern_create_radial — Description
    • cairo_pattern_create_rgb — Description
    • cairo_pattern_create_rgba — Description
    • cairo_pattern_get_color_stop_count — Description
    • cairo_pattern_get_color_stop_rgba — Description
    • cairo_pattern_get_extend — Description
    • cairo_pattern_get_filter — Description
    • cairo_pattern_get_linear_points — Description
    • cairo_pattern_get_matrix — Description
    • cairo_pattern_get_radial_circles — Description
    • cairo_pattern_get_rgba — Description
    • cairo_pattern_get_surface — Description
    • cairo_pattern_get_type — Description
    • cairo_pattern_set_extend — Description
    • cairo_pattern_set_filter — Description
    • cairo_pattern_set_matrix — Description
    • cairo_pattern_status — Description
    • cairo_pdf_surface_create — Description
    • cairo_pdf_surface_set_size — Description
    • cairo_ps_get_levels — Description
    • cairo_ps_level_to_string — Description
    • cairo_ps_surface_create — Description
    • cairo_ps_surface_dsc_begin_page_setup — Description
    • cairo_ps_surface_dsc_begin_setup — Description
    • cairo_ps_surface_dsc_comment — Description
    • cairo_ps_surface_get_eps — Description
    • cairo_ps_surface_restrict_to_level — Description
    • cairo_ps_surface_set_eps — Description
    • cairo_ps_surface_set_size — Description
    • cairo_scaled_font_create — Description
    • cairo_scaled_font_extents — Description
    • cairo_scaled_font_get_ctm — Description
    • cairo_scaled_font_get_font_face — Description
    • cairo_scaled_font_get_font_matrix — Description
    • cairo_scaled_font_get_font_options — Description
    • cairo_scaled_font_get_scale_matrix — Description
    • cairo_scaled_font_get_type — Description
    • cairo_scaled_font_glyph_extents — Description
    • cairo_scaled_font_status — Description
    • cairo_scaled_font_text_extents — Description
    • cairo_surface_copy_page — Description
    • cairo_surface_create_similar — Description
    • cairo_surface_finish — Description
    • cairo_surface_flush — Description
    • cairo_surface_get_content — Description
    • cairo_surface_get_device_offset — Description
    • cairo_surface_get_font_options — Description
    • cairo_surface_get_type — Description
    • cairo_surface_mark_dirty_rectangle — Description
    • cairo_surface_mark_dirty — Description
    • cairo_surface_set_device_offset — Description
    • cairo_surface_set_fallback_resolution — Description
    • cairo_surface_show_page — Description
    • cairo_surface_status — Description
    • cairo_surface_write_to_png — Description
    • cairo_svg_surface_create — Description
    • cairo_svg_surface_restrict_to_version — Description
    • cairo_svg_version_to_string — Description
  • Cairo — The Cairo class
    • Cairo::availableFonts — Retrieves the availables font types
    • Cairo::availableSurfaces — Retrieves all available surfaces
    • Cairo::statusToString — Retrieves the current status as string
    • Cairo::version — Retrieves cairo's library version
    • Cairo::versionString — Retrieves cairo version as string
  • CairoContext — The CairoContext class
    • CairoContext::appendPath — Appends a path to current path
    • CairoContext::arc — Adds a circular arc
    • CairoContext::arcNegative — Adds a negative arc
    • CairoContext::clip — Establishes a new clip region
    • CairoContext::clipExtents — Computes the area inside the current clip
    • CairoContext::clipPreserve — Establishes a new clip region from the current clip
    • CairoContext::clipRectangleList — Retrieves the current clip as a list of rectangles
    • CairoContext::closePath — Closes the current path
    • CairoContext::__construct — Creates a new CairoContext
    • CairoContext::copyPage — Emits the current page
    • CairoContext::copyPath — Creates a copy of the current path
    • CairoContext::copyPathFlat — Gets a flattened copy of the current path
    • CairoContext::curveTo — Adds a curve
    • CairoContext::deviceToUser — Transform a coordinate
    • CairoContext::deviceToUserDistance — Transform a distance
    • CairoContext::fill — Fills the current path
    • CairoContext::fillExtents — Computes the filled area
    • CairoContext::fillPreserve — Fills and preserve the current path
    • CairoContext::fontExtents — Get the font extents
    • CairoContext::getAntialias — Retrieves the current antialias mode
    • CairoContext::getCurrentPoint — The getCurrentPoint purpose
    • CairoContext::getDash — The getDash purpose
    • CairoContext::getDashCount — The getDashCount purpose
    • CairoContext::getFillRule — The getFillRule purpose
    • CairoContext::getFontFace — The getFontFace purpose
    • CairoContext::getFontMatrix — The getFontMatrix purpose
    • CairoContext::getFontOptions — The getFontOptions purpose
    • CairoContext::getGroupTarget — The getGroupTarget purpose
    • CairoContext::getLineCap — The getLineCap purpose
    • CairoContext::getLineJoin — The getLineJoin purpose
    • CairoContext::getLineWidth — The getLineWidth purpose
    • CairoContext::getMatrix — The getMatrix purpose
    • CairoContext::getMiterLimit — The getMiterLimit purpose
    • CairoContext::getOperator — The getOperator purpose
    • CairoContext::getScaledFont — The getScaledFont purpose
    • CairoContext::getSource — The getSource purpose
    • CairoContext::getTarget — The getTarget purpose
    • CairoContext::getTolerance — The getTolerance purpose
    • CairoContext::glyphPath — The glyphPath purpose
    • CairoContext::hasCurrentPoint — The hasCurrentPoint purpose
    • CairoContext::identityMatrix — The identityMatrix purpose
    • CairoContext::inFill — The inFill purpose
    • CairoContext::inStroke — The inStroke purpose
    • CairoContext::lineTo — The lineTo purpose
    • CairoContext::mask — The mask purpose
    • CairoContext::maskSurface — The maskSurface purpose
    • CairoContext::moveTo — The moveTo purpose
    • CairoContext::newPath — The newPath purpose
    • CairoContext::newSubPath — The newSubPath purpose
    • CairoContext::paint — The paint purpose
    • CairoContext::paintWithAlpha — The paintWithAlpha purpose
    • CairoContext::pathExtents — The pathExtents purpose
    • CairoContext::popGroup — The popGroup purpose
    • CairoContext::popGroupToSource — The popGroupToSource purpose
    • CairoContext::pushGroup — The pushGroup purpose
    • CairoContext::pushGroupWithContent — The pushGroupWithContent purpose
    • CairoContext::rectangle — The rectangle purpose
    • CairoContext::relCurveTo — The relCurveTo purpose
    • CairoContext::relLineTo — The relLineTo purpose
    • CairoContext::relMoveTo — The relMoveTo purpose
    • CairoContext::resetClip — The resetClip purpose
    • CairoContext::restore — The restore purpose
    • CairoContext::rotate — The rotate purpose
    • CairoContext::save — The save purpose
    • CairoContext::scale — The scale purpose
    • CairoContext::selectFontFace — The selectFontFace purpose
    • CairoContext::setAntialias — The setAntialias purpose
    • CairoContext::setDash — The setDash purpose
    • CairoContext::setFillRule — The setFillRule purpose
    • CairoContext::setFontFace — The setFontFace purpose
    • CairoContext::setFontMatrix — The setFontMatrix purpose
    • CairoContext::setFontOptions — The setFontOptions purpose
    • CairoContext::setFontSize — The setFontSize purpose
    • CairoContext::setLineCap — The setLineCap purpose
    • CairoContext::setLineJoin — The setLineJoin purpose
    • CairoContext::setLineWidth — The setLineWidth purpose
    • CairoContext::setMatrix — The setMatrix purpose
    • CairoContext::setMiterLimit — The setMiterLimit purpose
    • CairoContext::setOperator — The setOperator purpose
    • CairoContext::setScaledFont — The setScaledFont purpose
    • CairoContext::setSource — The setSource purpose
    • CairoContext::setSourceRGB — The setSourceRGB purpose
    • CairoContext::setSourceRGBA — The setSourceRGBA purpose
    • CairoContext::setSourceSurface — The setSourceSurface purpose
    • CairoContext::setTolerance — The setTolerance purpose
    • CairoContext::showPage — The showPage purpose
    • CairoContext::showText — The showText purpose
    • CairoContext::status — The status purpose
    • CairoContext::stroke — The stroke purpose
    • CairoContext::strokeExtents — The strokeExtents purpose
    • CairoContext::strokePreserve — The strokePreserve purpose
    • CairoContext::textExtents — The textExtents purpose
    • CairoContext::textPath — The textPath purpose
    • CairoContext::transform — The transform purpose
    • CairoContext::translate — The translate purpose
    • CairoContext::userToDevice — The userToDevice purpose
    • CairoContext::userToDeviceDistance — The userToDeviceDistance purpose
  • CairoException — The CairoException class
  • CairoStatus — The CairoStatus class
  • CairoSurface — The CairoSurface class
    • CairoSurface::__construct — The __construct purpose
    • CairoSurface::copyPage — The copyPage purpose
    • CairoSurface::createSimilar — The createSimilar purpose
    • CairoSurface::finish — The finish purpose
    • CairoSurface::flush — The flush purpose
    • CairoSurface::getContent — The getContent purpose
    • CairoSurface::getDeviceOffset — The getDeviceOffset purpose
    • CairoSurface::getFontOptions — The getFontOptions purpose
    • CairoSurface::getType — The getType purpose
    • CairoSurface::markDirty — The markDirty purpose
    • CairoSurface::markDirtyRectangle — The markDirtyRectangle purpose
    • CairoSurface::setDeviceOffset — The setDeviceOffset purpose
    • CairoSurface::setFallbackResolution — The setFallbackResolution purpose
    • CairoSurface::showPage — The showPage purpose
    • CairoSurface::status — The status purpose
    • CairoSurface::writeToPng — The writeToPng purpose
  • CairoSvgSurface — Svg Surface Backend
    • CairoSvgSurface::__construct — The __construct purpose
    • CairoSvgSurface::getVersions — Used to retrieve a list of supported SVG versions
    • CairoSvgSurface::restrictToVersion — The restrictToVersion purpose
    • CairoSvgSurface::versionToString — The versionToString purpose
  • CairoImageSurface — The CairoImageSurface class
    • CairoImageSurface::__construct — Creates a new CairoImageSurface
    • CairoImageSurface::createForData — The createForData purpose
    • CairoImageSurface::createFromPng — Creates a new CairoImageSurface form a png image file
    • CairoImageSurface::getData — Gets the image data as string
    • CairoImageSurface::getFormat — Get the image format
    • CairoImageSurface::getHeight — Retrieves the height of the CairoImageSurface
    • CairoImageSurface::getStride — The getStride purpose
    • CairoImageSurface::getWidth — Retrieves the width of the CairoImageSurface
  • CairoPdfSurface — The CairoPdfSurface class
    • CairoPdfSurface::__construct — The __construct purpose
    • CairoPdfSurface::setSize — The setSize purpose
  • CairoPsSurface — The CairoPsSurface class
    • CairoPsSurface::__construct — The __construct purpose
    • CairoPsSurface::dscBeginPageSetup — The dscBeginPageSetup purpose
    • CairoPsSurface::dscBeginSetup — The dscBeginSetup purpose
    • CairoPsSurface::dscComment — The dscComment purpose
    • CairoPsSurface::getEps — The getEps purpose
    • CairoPsSurface::getLevels — The getLevels purpose
    • CairoPsSurface::levelToString — The levelToString purpose
    • CairoPsSurface::restrictToLevel — The restrictToLevel purpose
    • CairoPsSurface::setEps — The setEps purpose
    • CairoPsSurface::setSize — The setSize purpose
  • CairoSurfaceType — The CairoSurfaceType class
  • CairoFontFace — The CairoFontFace class
    • CairoFontFace::__construct — Creates a new CairoFontFace object
    • CairoFontFace::getType — Retrieves the font face type
    • CairoFontFace::status — Check for CairoFontFace errors
  • CairoFontOptions — The CairoFontOptions class
    • CairoFontOptions::__construct — The __construct purpose
    • CairoFontOptions::equal — The equal purpose
    • CairoFontOptions::getAntialias — The getAntialias purpose
    • CairoFontOptions::getHintMetrics — The getHintMetrics purpose
    • CairoFontOptions::getHintStyle — The getHintStyle purpose
    • CairoFontOptions::getSubpixelOrder — The getSubpixelOrder purpose
    • CairoFontOptions::hash — The hash purpose
    • CairoFontOptions::merge — The merge purpose
    • CairoFontOptions::setAntialias — The setAntialias purpose
    • CairoFontOptions::setHintMetrics — The setHintMetrics purpose
    • CairoFontOptions::setHintStyle — The setHintStyle purpose
    • CairoFontOptions::setSubpixelOrder — The setSubpixelOrder purpose
    • CairoFontOptions::status — The status purpose
  • CairoFontSlant — The CairoFontSlant class
  • CairoFontType — The CairoFontType class
  • CairoFontWeight — The CairoFontWeight class
  • CairoScaledFont — The CairoScaledFont class
    • CairoScaledFont::__construct — The __construct purpose
    • CairoScaledFont::extents — The extents purpose
    • CairoScaledFont::getCtm — The getCtm purpose
    • CairoScaledFont::getFontFace — The getFontFace purpose
    • CairoScaledFont::getFontMatrix — The getFontMatrix purpose
    • CairoScaledFont::getFontOptions — The getFontOptions purpose
    • CairoScaledFont::getScaleMatrix — The getScaleMatrix purpose
    • CairoScaledFont::getType — The getType purpose
    • CairoScaledFont::glyphExtents — The glyphExtents purpose
    • CairoScaledFont::status — The status purpose
    • CairoScaledFont::textExtents — The textExtents purpose
  • CairoToyFontFace — The CairoToyFontFace class
  • CairoPatternType — The CairoPatternType class
  • CairoPattern — The CairoPattern class
    • CairoPattern::__construct — The __construct purpose
    • CairoPattern::getMatrix — The getMatrix purpose
    • CairoPattern::getType — The getType purpose
    • CairoPattern::setMatrix — The setMatrix purpose
    • CairoPattern::status — The status purpose
  • CairoGradientPattern — The CairoGradientPattern class
    • CairoGradientPattern::addColorStopRgb — The addColorStopRgb purpose
    • CairoGradientPattern::addColorStopRgba — The addColorStopRgba purpose
    • CairoGradientPattern::getColorStopCount — The getColorStopCount purpose
    • CairoGradientPattern::getColorStopRgba — The getColorStopRgba purpose
    • CairoGradientPattern::getExtend — The getExtend purpose
    • CairoGradientPattern::setExtend — The setExtend purpose
  • CairoSolidPattern — The CairoSolidPattern class
    • CairoSolidPattern::__construct — The __construct purpose
    • CairoSolidPattern::getRgba — The getRgba purpose
  • CairoSurfacePattern — The CairoSurfacePattern class
    • CairoSurfacePattern::__construct — The __construct purpose
    • CairoSurfacePattern::getExtend — The getExtend purpose
    • CairoSurfacePattern::getFilter — The getFilter purpose
    • CairoSurfacePattern::getSurface — The getSurface purpose
    • CairoSurfacePattern::setExtend — The setExtend purpose
    • CairoSurfacePattern::setFilter — The setFilter purpose
  • CairoLinearGradient — The CairoLinearGradient class
    • CairoLinearGradient::__construct — The __construct purpose
    • CairoLinearGradient::getPoints — The getPoints purpose
  • CairoRadialGradient — The CairoRadialGradient class
    • CairoRadialGradient::__construct — The __construct purpose
    • CairoRadialGradient::getCircles — The getCircles purpose
  • CairoAntialias — The CairoAntialias class
  • CairoContent — The CairoContent class
  • CairoExtend — The CairoExtend class
  • CairoFormat — The CairoFormat class
    • CairoFormat::strideForWidth — Provides an appropriate stride to use
  • CairoFillRule — The CairoFillRule class
  • CairoFilter — The CairoFilter class
  • CairoHintMetrics — The CairoHintMetrics class
  • CairoHintStyle — The CairoHintStyle class
  • CairoLineCap — The CairoLineCap class
  • CairoLineJoin — The CairoLineJoin class
  • CairoMatrix — The CairoMatrix class
    • CairoMatrix::__construct — Creates a new CairoMatrix object
    • CairoMatrix::initIdentity — Creates a new identity matrix
    • CairoMatrix::initRotate — Creates a new rotated matrix
    • CairoMatrix::initScale — Creates a new scaling matrix
    • CairoMatrix::initTranslate — Creates a new translation matrix
    • CairoMatrix::invert — The invert purpose
    • CairoMatrix::multiply — The multiply purpose
    • CairoMatrix::rotate — The rotate purpose
    • CairoMatrix::scale — Applies scaling to a matrix
    • CairoMatrix::transformDistance — The transformDistance purpose
    • CairoMatrix::transformPoint — The transformPoint purpose
    • CairoMatrix::translate — The translate purpose
  • CairoOperator — The CairoOperator class
  • CairoPath — The CairoPath class
  • CairoPsLevel — The CairoPsLevel class
  • CairoSubpixelOrder — The CairoSubpixelOrder class
  • CairoSvgVersion — The CairoSvgVersion class


Introduction

Cairo is a native PHP extension to create and modify graphics using the Cairo Graphics Library.

The Cairo Graphics Library is a 2D library written in C with support for multiple output devices. Currently supported output targets include the X Window System, Quartz, Win32, image buffers, PostScript, PDF, and SVG file output. Experimental backends include OpenGL (through glitz), XCB, BeOS, OS/2, and DirectFB. The library also has support for two types of text manipulation and layout. The "toy" API provides demo quality support, and the glyphs API, although full-featured, works best with a helper library such as pango. Font backend support includes FreeType, Quartz, Win32, and User fonts.

There are two types of computer graphics, vector and raster. Raster graphics are the representation of images as an array of pixels. Vector graphics use geometrical primitives such as points, lines, curves or polygons to represent images. The primitives are created using mathematical equations. The Cairo Graphics Library takes a vector approach to graphics, allowing smaller size, infinite zooming, and moving, scaling and rotating without degrading image quality.

Operations in the cairo graphics library including stroking and filling cubic Bézier splines, transforming and compositing translucent images, and antialiased text rendering. All drawing operations can be transformed by any affine transformation (scale, rotation, shear, and others) This is very similar to drawing operations for PostScript and PDF drawing.

The Cairo PHP Extension aims to provide support for all officially supported font backends and surface backends, as well as expose all available functionality in cairo to PHP users.


Requirements

Cairo is only available for PHP 5.2+ and PHP 5.3+ The extension also requires the cairo graphics library version 1.4 or higher. The cairo graphics library uses an even and odd numbering scheme to denote stable and unstable library versions. Both unstable and stable versions can be used with the extension, but conditional support for new features is determined by the stable version below the unstable version in use. The latest cairo release can be found at » http://cairographics.org/.

The binary files used for the windows compiles can be found at » http://cairographics.org/download/ along with the project files used to create them.


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/cairo.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Notes specific to installation on Windows

Binary builds of the extension can be found at » http://cairographics.org/download/. Download the correct zip file, place php_cairo.dll in the extensions directory, and enable it via the php.ini file in use. Please be sure the PHP minor version (5.2, 5.3) match, the thread safety (Thread Safe TS or Non-Thread Safe NTS), the architecture (x86 or x64), and the compiler version (VC6 or VC9) match or the extension will not load.


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.

CAIRO_STATUS_SUCCESS (integer)
CAIRO_STATUS_NO_MEMORY (integer)
CAIRO_STATUS_INVALID_RESTORE (integer)
CAIRO_STATUS_INVALID_POP_GROUP (integer)
CAIRO_STATUS_NO_CURRENT_POINT (integer)
CAIRO_STATUS_INVALID_MATRIX (integer)
CAIRO_STATUS_INVALID_STATUS (integer)
CAIRO_STATUS_NULL_POINTER (integer)
CAIRO_STATUS_INVALID_STRING (integer)
CAIRO_STATUS_INVALID_PATH_DATA (integer)
CAIRO_STATUS_READ_ERROR (integer)
CAIRO_STATUS_WRITE_ERROR (integer)
CAIRO_STATUS_SURFACE_FINISHED (integer)
CAIRO_STATUS_SURFACE_TYPE_MISMATCH (integer)
CAIRO_STATUS_PATTERN_TYPE_MISMATCH (integer)
CAIRO_STATUS_INVALID_CONTENT (integer)
CAIRO_STATUS_INVALID_FORMAT (integer)
CAIRO_STATUS_INVALID_VISUAL (integer)
CAIRO_STATUS_FILE_NOT_FOUND (integer)
CAIRO_STATUS_INVALID_DASH (integer)
CAIRO_STATUS_INVALID_DSC_COMMENT (integer)
CAIRO_STATUS_INVALID_INDEX (integer)
CAIRO_STATUS_CLIP_NOT_REPRESENTABLE (integer)
CAIRO_STATUS_TEMP_FILE_ERROR (integer)
CAIRO_STATUS_INVALID_STRIDE (integer)
CAIRO_ANTIALIAS_DEFAULT (integer)
CAIRO_ANTIALIAS_NONE (integer)
CAIRO_ANTIALIAS_GRAY (integer)
CAIRO_ANTIALIAS_SUBPIXEL (integer)
CAIRO_SUBPIXEL_ORDER_DEFAULT (integer)
CAIRO_SUBPIXEL_ORDER_RGB (integer)
CAIRO_SUBPIXEL_ORDER_BGR (integer)
CAIRO_SUBPIXEL_ORDER_VRGB (integer)
CAIRO_SUBPIXEL_ORDER_VBGR (integer)
CAIRO_FILL_RULE_WINDING (integer)
CAIRO_FILL_RULE_EVEN_ODD (integer)
CAIRO_LINE_CAP_BUTT (integer)
CAIRO_LINE_CAP_ROUND (integer)
CAIRO_LINE_CAP_SQUARE (integer)
CAIRO_LINE_JOIN_MITER (integer)
CAIRO_LINE_JOIN_ROUND (integer)
CAIRO_LINE_JOIN_BEVEL (integer)
CAIRO_OPERATOR_CLEAR (integer)
CAIRO_OPERATOR_SOURCE (integer)
CAIRO_OPERATOR_OVER (integer)
CAIRO_OPERATOR_IN (integer)
CAIRO_OPERATOR_OUT (integer)
CAIRO_OPERATOR_ATOP (integer)
CAIRO_OPERATOR_DEST (integer)
CAIRO_OPERATOR_DEST_OVER (integer)
CAIRO_OPERATOR_DEST_IN (integer)
CAIRO_OPERATOR_DEST_OUT (integer)
CAIRO_OPERATOR_DEST_ATOP (integer)
CAIRO_OPERATOR_XOR (integer)
CAIRO_OPERATOR_ADD (integer)
CAIRO_OPERATOR_SATURATE (integer)
CAIRO_PATTERN_TYPE_SOLID (integer)
CAIRO_PATTERN_TYPE_SURFACE (integer)
CAIRO_PATTERN_TYPE_LINEAR (integer)
CAIRO_PATTERN_TYPE_RADIAL (integer)
CAIRO_EXTEND_NONE (integer)
CAIRO_EXTEND_REPEAT (integer)
CAIRO_EXTEND_REFLECT (integer)
CAIRO_EXTEND_PAD (integer)
CAIRO_FILTER_FAST (integer)
CAIRO_FILTER_GOOD (integer)
CAIRO_FILTER_BEST (integer)
CAIRO_FILTER_NEAREST (integer)
CAIRO_FILTER_BILINEAR (integer)
CAIRO_FILTER_GAUSSIAN (integer)
CAIRO_HINT_STYLE_DEFAULT (integer)
CAIRO_HINT_STYLE_NONE (integer)
CAIRO_HINT_STYLE_SLIGHT (integer)
CAIRO_HINT_STYLE_MEDIUM (integer)
CAIRO_HINT_STYLE_FULL (integer)
CAIRO_HINT_METRICS_DEFAULT (integer)
CAIRO_HINT_METRICS_OFF (integer)
CAIRO_HINT_METRICS_ON (integer)
CAIRO_FONT_TYPE_TOY (integer)
CAIRO_FONT_TYPE_FT (integer)
CAIRO_FONT_TYPE_WIN32 (integer)
CAIRO_FONT_TYPE_QUARTZ (integer)
CAIRO_FONT_SLANT_NORMAL (integer)
CAIRO_FONT_SLANT_ITALIC (integer)
CAIRO_FONT_SLANT_OBLIQUE (integer)
CAIRO_FONT_WEIGHT_NORMAL (integer)
CAIRO_FONT_WEIGHT_BOLD (integer)
CAIRO_CONTENT_COLOR (integer)
CAIRO_CONTENT_ALPHA (integer)
CAIRO_CONTENT_COLOR_ALPHA (integer)
CAIRO_SURFACE_TYPE_IMAGE (integer)
CAIRO_SURFACE_TYPE_PDF (integer)
CAIRO_SURFACE_TYPE_PS (integer)
CAIRO_SURFACE_TYPE_XLIB (integer)
CAIRO_SURFACE_TYPE_XCB (integer)
CAIRO_SURFACE_TYPE_GLITZ (integer)
CAIRO_SURFACE_TYPE_QUARTZ (integer)
CAIRO_SURFACE_TYPE_WIN32 (integer)
CAIRO_SURFACE_TYPE_BEOS (integer)
CAIRO_SURFACE_TYPE_DIRECTFB (integer)
CAIRO_SURFACE_TYPE_SVG (integer)
CAIRO_SURFACE_TYPE_OS2 (integer)
CAIRO_SURFACE_TYPE_WIN32_PRINTING (integer)
CAIRO_SURFACE_TYPE_QUARTZ_IMAGE (integer)
CAIRO_FORMAT_ARGB32 (integer)
CAIRO_FORMAT_RGB24 (integer)
CAIRO_FORMAT_A8 (integer)
CAIRO_FORMAT_A1 (integer)
CAIRO_PS_LEVEL_2 (integer)
CAIRO_PS_LEVEL_3 (integer)
CAIRO_SVG_VERSION_1_1 (integer)
CAIRO_SVG_VERSION_1_2 (integer)


Examples

Description here...

Example #1 Cairo Example

<?php

/* ... */

?>

The above example will output something similar to:

...


Cairo Functions

Table of Contents

  • cairo_create — Returns a new CairoContext object on the requested surface
  • cairo_font_options_create — Description
  • cairo_font_options_equal — Description
  • cairo_font_options_get_antialias — Description
  • cairo_font_options_get_hint_metrics — Description
  • cairo_font_options_get_hint_style — Description
  • cairo_font_options_get_subpixel_order — Description
  • cairo_font_options_hash — Description
  • cairo_font_options_merge — Description
  • cairo_font_options_set_antialias — Description
  • cairo_font_options_set_hint_metrics — Description
  • cairo_font_options_set_hint_style — Description
  • cairo_font_options_set_subpixel_order — Description
  • cairo_font_options_status — Description
  • cairo_format_stride_for_width — Description
  • cairo_image_surface_create_for_data — Description
  • cairo_image_surface_create_from_png — Description
  • cairo_image_surface_create — Description
  • cairo_image_surface_get_data — Description
  • cairo_image_surface_get_format — Description
  • cairo_image_surface_get_height — Description
  • cairo_image_surface_get_stride — Description
  • cairo_image_surface_get_width — Description
  • cairo_matrix_create_scale — Alias of CairoMatrix::initScale
  • cairo_matrix_create_translate — Alias of CairoMatrix::initTranslate
  • cairo_matrix_invert — Description
  • cairo_matrix_multiply — Description
  • cairo_matrix_transform_distance — Description
  • cairo_matrix_transform_point — Description
  • cairo_matrix_translate — Description
  • cairo_pattern_add_color_stop_rgb — Description
  • cairo_pattern_add_color_stop_rgba — Description
  • cairo_pattern_create_for_surface — Description
  • cairo_pattern_create_linear — Description
  • cairo_pattern_create_radial — Description
  • cairo_pattern_create_rgb — Description
  • cairo_pattern_create_rgba — Description
  • cairo_pattern_get_color_stop_count — Description
  • cairo_pattern_get_color_stop_rgba — Description
  • cairo_pattern_get_extend — Description
  • cairo_pattern_get_filter — Description
  • cairo_pattern_get_linear_points — Description
  • cairo_pattern_get_matrix — Description
  • cairo_pattern_get_radial_circles — Description
  • cairo_pattern_get_rgba — Description
  • cairo_pattern_get_surface — Description
  • cairo_pattern_get_type — Description
  • cairo_pattern_set_extend — Description
  • cairo_pattern_set_filter — Description
  • cairo_pattern_set_matrix — Description
  • cairo_pattern_status — Description
  • cairo_pdf_surface_create — Description
  • cairo_pdf_surface_set_size — Description
  • cairo_ps_get_levels — Description
  • cairo_ps_level_to_string — Description
  • cairo_ps_surface_create — Description
  • cairo_ps_surface_dsc_begin_page_setup — Description
  • cairo_ps_surface_dsc_begin_setup — Description
  • cairo_ps_surface_dsc_comment — Description
  • cairo_ps_surface_get_eps — Description
  • cairo_ps_surface_restrict_to_level — Description
  • cairo_ps_surface_set_eps — Description
  • cairo_ps_surface_set_size — Description
  • cairo_scaled_font_create — Description
  • cairo_scaled_font_extents — Description
  • cairo_scaled_font_get_ctm — Description
  • cairo_scaled_font_get_font_face — Description
  • cairo_scaled_font_get_font_matrix — Description
  • cairo_scaled_font_get_font_options — Description
  • cairo_scaled_font_get_scale_matrix — Description
  • cairo_scaled_font_get_type — Description
  • cairo_scaled_font_glyph_extents — Description
  • cairo_scaled_font_status — Description
  • cairo_scaled_font_text_extents — Description
  • cairo_surface_copy_page — Description
  • cairo_surface_create_similar — Description
  • cairo_surface_finish — Description
  • cairo_surface_flush — Description
  • cairo_surface_get_content — Description
  • cairo_surface_get_device_offset — Description
  • cairo_surface_get_font_options — Description
  • cairo_surface_get_type — Description
  • cairo_surface_mark_dirty_rectangle — Description
  • cairo_surface_mark_dirty — Description
  • cairo_surface_set_device_offset — Description
  • cairo_surface_set_fallback_resolution — Description
  • cairo_surface_show_page — Description
  • cairo_surface_status — Description
  • cairo_surface_write_to_png — Description
  • cairo_svg_surface_create — Description
  • cairo_svg_surface_restrict_to_version — Description
  • cairo_svg_version_to_string — Description


Returns a new CairoContext object on the requested surface

  • « Cairo Functions
  • cairo_font_options_create »
  • PHP Manual
  • Cairo Functions
  • Returns a new CairoContext object on the requested surface

cairo_create

(PECL cairo >= 0.1.0)

cairo_create — Returns a new CairoContext object on the requested surface

Description

cairo_create ( CairoSurface $surface ) : CairoContext

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_create() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_create
  • cairo_font_options_equal »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_font_options_create

(PECL cairo >= 0.1.0)

cairo_font_options_create — Description

Description

cairo_font_options_create ( void ) : CairoFontOptions

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_create() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_font_options_create
  • cairo_font_options_get_antialias »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_font_options_equal

(PECL cairo >= 0.1.0)

cairo_font_options_equal — Description

Description

cairo_font_options_equal ( CairoFontOptions $options , CairoFontOptions $other ) : bool

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

other

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_equal() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_font_options_equal
  • cairo_font_options_get_hint_metrics »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_font_options_get_antialias

(PECL cairo >= 0.1.0)

cairo_font_options_get_antialias — Description

Description

cairo_font_options_get_antialias ( CairoFontOptions $options ) : int

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_get_antialias() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_font_options_get_antialias
  • cairo_font_options_get_hint_style »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_font_options_get_hint_metrics

(PECL cairo >= 0.1.0)

cairo_font_options_get_hint_metrics — Description

Description

cairo_font_options_get_hint_metrics ( CairoFontOptions $options ) : int

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_get_hint_metrics() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_font_options_get_hint_metrics
  • cairo_font_options_get_subpixel_order »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_font_options_get_hint_style

(PECL cairo >= 0.1.0)

cairo_font_options_get_hint_style — Description

Description

cairo_font_options_get_hint_style ( CairoFontOptions $options ) : int

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_get_hint_style() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_font_options_get_hint_style
  • cairo_font_options_hash »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_font_options_get_subpixel_order

(PECL cairo >= 0.1.0)

cairo_font_options_get_subpixel_order — Description

Description

cairo_font_options_get_subpixel_order ( CairoFontOptions $options ) : int

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_get_subpixel_order() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_font_options_get_subpixel_order
  • cairo_font_options_merge »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_font_options_hash

(PECL cairo >= 0.1.0)

cairo_font_options_hash — Description

Description

cairo_font_options_hash ( CairoFontOptions $options ) : int

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_hash() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_font_options_hash
  • cairo_font_options_set_antialias »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_font_options_merge

(PECL cairo >= 0.1.0)

cairo_font_options_merge — Description

Description

cairo_font_options_merge ( CairoFontOptions $options , CairoFontOptions $other ) : void

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

other

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_merge() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_font_options_merge
  • cairo_font_options_set_hint_metrics »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_font_options_set_antialias

(PECL cairo >= 0.1.0)

cairo_font_options_set_antialias — Description

Description

cairo_font_options_set_antialias ( CairoFontOptions $options , int $antialias ) : void

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

antialias

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_set_antialias() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_font_options_set_antialias
  • cairo_font_options_set_hint_style »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_font_options_set_hint_metrics

(PECL cairo >= 0.1.0)

cairo_font_options_set_hint_metrics — Description

Description

cairo_font_options_set_hint_metrics ( CairoFontOptions $options , int $hint_metrics ) : void

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

hint_metrics

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_set_hint_metrics() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_font_options_set_hint_metrics
  • cairo_font_options_set_subpixel_order »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_font_options_set_hint_style

(PECL cairo >= 0.1.0)

cairo_font_options_set_hint_style — Description

Description

cairo_font_options_set_hint_style ( CairoFontOptions $options , int $hint_style ) : void

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

hint_style

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_set_hint_style() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_font_options_set_hint_style
  • cairo_font_options_status »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_font_options_set_subpixel_order

(PECL cairo >= 0.1.0)

cairo_font_options_set_subpixel_order — Description

Description

cairo_font_options_set_subpixel_order ( CairoFontOptions $options , int $subpixel_order ) : void

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

subpixel_order

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_set_subpixel_order() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_font_options_set_subpixel_order
  • cairo_format_stride_for_width »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_font_options_status

(PECL cairo >= 0.1.0)

cairo_font_options_status — Description

Description

cairo_font_options_status ( CairoFontOptions $options ) : int

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_font_options_status() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_font_options_status
  • cairo_image_surface_create_for_data »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_format_stride_for_width

(PECL cairo >= 0.1.0)

cairo_format_stride_for_width — Description

Description

cairo_format_stride_for_width ( int $format , int $width ) : int

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

format

Description...

width

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_format_stride_for_width() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_format_stride_for_width
  • cairo_image_surface_create_from_png »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_image_surface_create_for_data

(PECL cairo >= 0.1.0)

cairo_image_surface_create_for_data — Description

Description

cairo_image_surface_create_for_data ( string $data , int $format , int $width , int $height [, int $stride = -1 ] ) : CairoImageSurface

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

data

Description...

format

Description...

width

Description...

height

Description...

stride

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_image_surface_create_for_data() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_image_surface_create_for_data
  • cairo_image_surface_create »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_image_surface_create_from_png

(PECL cairo >= 0.1.0)

cairo_image_surface_create_from_png — Description

Description

cairo_image_surface_create_from_png ( mixed $file ) : CairoImageSurface

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

file

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_image_surface_create_from_png() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_image_surface_create_from_png
  • cairo_image_surface_get_data »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_image_surface_create

(PECL cairo >= 0.1.0)

cairo_image_surface_create — Description

Description

cairo_image_surface_create ( int $format , int $width , int $height ) : CairoImageSurface

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

format

Description...

width

Description...

height

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_image_surface_create() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_image_surface_create
  • cairo_image_surface_get_format »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_image_surface_get_data

(PECL cairo >= 0.1.0)

cairo_image_surface_get_data — Description

Description

cairo_image_surface_get_data ( CairoImageSurface $surface ) : string

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_image_surface_get_data() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_image_surface_get_data
  • cairo_image_surface_get_height »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_image_surface_get_format

(PECL cairo >= 0.1.0)

cairo_image_surface_get_format — Description

Description

cairo_image_surface_get_format ( CairoImageSurface $surface ) : int

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_image_surface_get_format() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_image_surface_get_format
  • cairo_image_surface_get_stride »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_image_surface_get_height

(PECL cairo >= 0.1.0)

cairo_image_surface_get_height — Description

Description

cairo_image_surface_get_height ( CairoImageSurface $surface ) : int

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_image_surface_get_height() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_image_surface_get_height
  • cairo_image_surface_get_width »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_image_surface_get_stride

(PECL cairo >= 0.1.0)

cairo_image_surface_get_stride — Description

Description

cairo_image_surface_get_stride ( CairoImageSurface $surface ) : int

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_image_surface_get_stride() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_image_surface_get_stride
  • cairo_matrix_create_scale »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_image_surface_get_width

(PECL cairo >= 0.1.0)

cairo_image_surface_get_width — Description

Description

cairo_image_surface_get_width ( CairoImageSurface $surface ) : int

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_image_surface_get_width() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Alias of CairoMatrix::initScale

  • « cairo_image_surface_get_width
  • cairo_matrix_create_translate »
  • PHP Manual
  • Cairo Functions
  • Alias of CairoMatrix::initScale

cairo_matrix_create_scale

(PECL cairo >= 0.1.0)

cairo_matrix_create_scale — Alias of CairoMatrix::initScale()

Description

This function is an alias of: CairoMatrix::initScale().

This function alias is deprecated and only exists for backwards compatibility reasons. The use of this function is not recommended, as it may be removed from PHP in the future.


Alias of CairoMatrix::initTranslate

  • « cairo_matrix_create_scale
  • cairo_matrix_invert »
  • PHP Manual
  • Cairo Functions
  • Alias of CairoMatrix::initTranslate

cairo_matrix_create_translate

(PECL cairo >= 0.1.0)

cairo_matrix_create_translate — Alias of CairoMatrix::initTranslate()

Description

This function is an alias of: CairoMatrix::initTranslate().

This function alias is deprecated and only exists for backwards compatibility reasons. The use of this function is not recommended, as it may be removed from PHP in the future.


Description

  • « cairo_matrix_create_translate
  • cairo_matrix_multiply »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_matrix_invert

(PECL cairo >= 0.1.0)

cairo_matrix_invert — Description

Description

cairo_matrix_invert ( CairoMatrix $matrix ) : void

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

matrix

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_matrix_invert() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_matrix_invert
  • cairo_matrix_transform_distance »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_matrix_multiply

(PECL cairo >= 0.1.0)

cairo_matrix_multiply — Description

Description

cairo_matrix_multiply ( CairoMatrix $matrix1 , CairoMatrix $matrix2 ) : CairoMatrix

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

matrix1

Description...

matrix2

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_matrix_multiply() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_matrix_multiply
  • cairo_matrix_transform_point »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_matrix_transform_distance

(PECL cairo >= 0.1.0)

cairo_matrix_transform_distance — Description

Description

cairo_matrix_transform_distance ( CairoMatrix $matrix , float $dx , float $dy ) : array

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

matrix

Description...

dx

Description...

dy

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_matrix_transform_distance() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_matrix_transform_distance
  • cairo_matrix_translate »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_matrix_transform_point

(PECL cairo >= 0.1.0)

cairo_matrix_transform_point — Description

Description

cairo_matrix_transform_point ( CairoMatrix $matrix , float $dx , float $dy ) : array

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

matrix

Description...

dx

Description...

dy

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_matrix_transform_point() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_matrix_transform_point
  • cairo_pattern_add_color_stop_rgb »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_matrix_translate

(PECL cairo >= 0.1.0)

cairo_matrix_translate — Description

Description

cairo_matrix_translate ( CairoMatrix $matrix , float $tx , float $ty ) : void

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

matrix

Description...

tx

Description...

ty

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_matrix_translate() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_matrix_translate
  • cairo_pattern_add_color_stop_rgba »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_add_color_stop_rgb

(PECL cairo >= 0.1.0)

cairo_pattern_add_color_stop_rgb — Description

Description

cairo_pattern_add_color_stop_rgb ( CairoGradientPattern $pattern , float $offset , float $red , float $green , float $blue ) : void

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

offset

Description...

red

Description...

green

Description...

blue

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_add_color_stop_rgb() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_pattern_add_color_stop_rgb
  • cairo_pattern_create_for_surface »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_add_color_stop_rgba

(PECL cairo >= 0.1.0)

cairo_pattern_add_color_stop_rgba — Description

Description

cairo_pattern_add_color_stop_rgba ( CairoGradientPattern $pattern , float $offset , float $red , float $green , float $blue , float $alpha ) : void

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

offset

Description...

red

Description...

green

Description...

blue

Description...

alpha

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_add_color_stop_rgba() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_pattern_add_color_stop_rgba
  • cairo_pattern_create_linear »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_create_for_surface

(PECL cairo >= 0.1.0)

cairo_pattern_create_for_surface — Description

Description

cairo_pattern_create_for_surface ( CairoSurface $surface ) : CairoPattern

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_create_for_surface() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_pattern_create_for_surface
  • cairo_pattern_create_radial »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_create_linear

(PECL cairo >= 0.1.0)

cairo_pattern_create_linear — Description

Description

cairo_pattern_create_linear ( float $x0 , float $y0 , float $x1 , float $y1 ) : CairoPattern

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

x0

Description...

y0

Description...

x1

Description...

y1

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_create_linear() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_pattern_create_linear
  • cairo_pattern_create_rgb »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_create_radial

(PECL cairo >= 0.1.0)

cairo_pattern_create_radial — Description

Description

cairo_pattern_create_radial ( float $x0 , float $y0 , float $r0 , float $x1 , float $y1 , float $r1 ) : CairoPattern

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

x0

Description...

y0

Description...

r0

Description...

x1

Description...

y1

Description...

r1

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_create_radial() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_pattern_create_radial
  • cairo_pattern_create_rgba »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_create_rgb

(PECL cairo >= 0.1.0)

cairo_pattern_create_rgb — Description

Description

cairo_pattern_create_rgb ( float $red , float $green , float $blue ) : CairoPattern

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

red

Description...

green

Description...

blue

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_create_rgb() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_pattern_create_rgb
  • cairo_pattern_get_color_stop_count »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_create_rgba

(PECL cairo >= 0.1.0)

cairo_pattern_create_rgba — Description

Description

cairo_pattern_create_rgba ( float $red , float $green , float $blue , float $alpha ) : CairoPattern

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

red

Description...

green

Description...

blue

Description...

alpha

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_create_rgba() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_pattern_create_rgba
  • cairo_pattern_get_color_stop_rgba »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_get_color_stop_count

(PECL cairo >= 0.1.0)

cairo_pattern_get_color_stop_count — Description

Description

cairo_pattern_get_color_stop_count ( CairoGradientPattern $pattern ) : int

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_get_color_stop_count() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_pattern_get_color_stop_count
  • cairo_pattern_get_extend »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_get_color_stop_rgba

(PECL cairo >= 0.1.0)

cairo_pattern_get_color_stop_rgba — Description

Description

cairo_pattern_get_color_stop_rgba ( CairoGradientPattern $pattern , int $index ) : array

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

index

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_get_color_stop_rgba() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_pattern_get_color_stop_rgba
  • cairo_pattern_get_filter »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_get_extend

(PECL cairo >= 0.1.0)

cairo_pattern_get_extend — Description

Description

cairo_pattern_get_extend ( string $pattern ) : int

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_get_extend() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_pattern_get_extend
  • cairo_pattern_get_linear_points »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_get_filter

(PECL cairo >= 0.1.0)

cairo_pattern_get_filter — Description

Description

cairo_pattern_get_filter ( CairoSurfacePattern $pattern ) : int

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_get_filter() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_pattern_get_filter
  • cairo_pattern_get_matrix »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_get_linear_points

(PECL cairo >= 0.1.0)

cairo_pattern_get_linear_points — Description

Description

cairo_pattern_get_linear_points ( CairoLinearGradient $pattern ) : array

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_get_linear_points() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_pattern_get_linear_points
  • cairo_pattern_get_radial_circles »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_get_matrix

(PECL cairo >= 0.1.0)

cairo_pattern_get_matrix — Description

Description

cairo_pattern_get_matrix ( CairoPattern $pattern ) : CairoMatrix

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_get_matrix() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_pattern_get_matrix
  • cairo_pattern_get_rgba »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_get_radial_circles

(PECL cairo >= 0.1.0)

cairo_pattern_get_radial_circles — Description

Description

cairo_pattern_get_radial_circles ( CairoRadialGradient $pattern ) : array

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_get_radial_circles() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_pattern_get_radial_circles
  • cairo_pattern_get_surface »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_get_rgba

(PECL cairo >= 0.1.0)

cairo_pattern_get_rgba — Description

Description

cairo_pattern_get_rgba ( CairoSolidPattern $pattern ) : array

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_get_rgba() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_pattern_get_rgba
  • cairo_pattern_get_type »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_get_surface

(PECL cairo >= 0.1.0)

cairo_pattern_get_surface — Description

Description

cairo_pattern_get_surface ( CairoSurfacePattern $pattern ) : CairoSurface

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_get_surface() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_pattern_get_surface
  • cairo_pattern_set_extend »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_get_type

(PECL cairo >= 0.1.0)

cairo_pattern_get_type — Description

Description

cairo_pattern_get_type ( CairoPattern $pattern ) : int

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_get_type() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_pattern_get_type
  • cairo_pattern_set_filter »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_set_extend

(PECL cairo >= 0.1.0)

cairo_pattern_set_extend — Description

Description

cairo_pattern_set_extend ( string $pattern , string $extend ) : void

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

extend

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_set_extend() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_pattern_set_extend
  • cairo_pattern_set_matrix »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_set_filter

(PECL cairo >= 0.1.0)

cairo_pattern_set_filter — Description

Description

cairo_pattern_set_filter ( CairoSurfacePattern $pattern , int $filter ) : void

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

filter

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_set_filter() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_pattern_set_filter
  • cairo_pattern_status »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_set_matrix

(PECL cairo >= 0.1.0)

cairo_pattern_set_matrix — Description

Description

cairo_pattern_set_matrix ( CairoPattern $pattern , CairoMatrix $matrix ) : void

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

matrix

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_set_matrix() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_pattern_set_matrix
  • cairo_pdf_surface_create »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pattern_status

(PECL cairo >= 0.1.0)

cairo_pattern_status — Description

Description

cairo_pattern_status ( CairoPattern $pattern ) : int

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

pattern

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pattern_status() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_pattern_status
  • cairo_pdf_surface_set_size »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pdf_surface_create

(PECL cairo >= 0.1.0)

cairo_pdf_surface_create — Description

Description

cairo_pdf_surface_create ( string $file , float $width , float $height ) : CairoPdfSurface

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

file

Description...

width

Description...

height

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pdf_surface_create() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_pdf_surface_create
  • cairo_ps_get_levels »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_pdf_surface_set_size

(PECL cairo >= 0.1.0)

cairo_pdf_surface_set_size — Description

Description

cairo_pdf_surface_set_size ( CairoPdfSurface $surface , float $width , float $height ) : void

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

width

Description...

height

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_pdf_surface_set_size() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_pdf_surface_set_size
  • cairo_ps_level_to_string »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_ps_get_levels

(PECL cairo >= 0.1.0)

cairo_ps_get_levels — Description

Description

cairo_ps_get_levels ( void ) : array

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_ps_get_levels() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_ps_get_levels
  • cairo_ps_surface_create »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_ps_level_to_string

(PECL cairo >= 0.1.0)

cairo_ps_level_to_string — Description

Description

cairo_ps_level_to_string ( int $level ) : string

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

level

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_ps_level_to_string() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_ps_level_to_string
  • cairo_ps_surface_dsc_begin_page_setup »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_ps_surface_create

(PECL cairo >= 0.1.0)

cairo_ps_surface_create — Description

Description

cairo_ps_surface_create ( string $file , float $width , float $height ) : CairoPsSurface

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

file

Description...

width

Description...

height

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_ps_surface_create() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_ps_surface_create
  • cairo_ps_surface_dsc_begin_setup »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_ps_surface_dsc_begin_page_setup

(PECL cairo >= 0.1.0)

cairo_ps_surface_dsc_begin_page_setup — Description

Description

cairo_ps_surface_dsc_begin_page_setup ( CairoPsSurface $surface ) : void

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_ps_surface_dsc_begin_page_setup() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_ps_surface_dsc_begin_page_setup
  • cairo_ps_surface_dsc_comment »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_ps_surface_dsc_begin_setup

(PECL cairo >= 0.1.0)

cairo_ps_surface_dsc_begin_setup — Description

Description

cairo_ps_surface_dsc_begin_setup ( CairoPsSurface $surface ) : void

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_ps_surface_dsc_begin_setup() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_ps_surface_dsc_begin_setup
  • cairo_ps_surface_get_eps »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_ps_surface_dsc_comment

(PECL cairo >= 0.1.0)

cairo_ps_surface_dsc_comment — Description

Description

cairo_ps_surface_dsc_comment ( CairoPsSurface $surface , string $comment ) : void

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

comment

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_ps_surface_dsc_comment() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_ps_surface_dsc_comment
  • cairo_ps_surface_restrict_to_level »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_ps_surface_get_eps

(PECL cairo >= 0.1.0)

cairo_ps_surface_get_eps — Description

Description

cairo_ps_surface_get_eps ( CairoPsSurface $surface ) : bool

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_ps_surface_get_eps() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_ps_surface_get_eps
  • cairo_ps_surface_set_eps »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_ps_surface_restrict_to_level

(PECL cairo >= 0.1.0)

cairo_ps_surface_restrict_to_level — Description

Description

cairo_ps_surface_restrict_to_level ( CairoPsSurface $surface , int $level ) : void

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

level

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_ps_surface_restrict_to_level() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_ps_surface_restrict_to_level
  • cairo_ps_surface_set_size »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_ps_surface_set_eps

(PECL cairo >= 0.1.0)

cairo_ps_surface_set_eps — Description

Description

cairo_ps_surface_set_eps ( CairoPsSurface $surface , bool $level ) : void

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

level

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_ps_surface_set_eps() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_ps_surface_set_eps
  • cairo_scaled_font_create »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_ps_surface_set_size

(PECL cairo >= 0.1.0)

cairo_ps_surface_set_size — Description

Description

cairo_ps_surface_set_size ( CairoPsSurface $surface , float $width , float $height ) : void

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

width

Description...

height

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_ps_surface_set_size() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_ps_surface_set_size
  • cairo_scaled_font_extents »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_scaled_font_create

(PECL cairo >= 0.1.0)

cairo_scaled_font_create — Description

Description

cairo_scaled_font_create ( CairoFontFace $fontface , CairoMatrix $matrix , CairoMatrix $ctm , CairoFontOptions $fontoptions ) : CairoScaledFont

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

fontface

Description...

matrix

Description...

ctm

Description...

fontoptions

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_create() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_scaled_font_create
  • cairo_scaled_font_get_ctm »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_scaled_font_extents

(PECL cairo >= 0.1.0)

cairo_scaled_font_extents — Description

Description

cairo_scaled_font_extents ( CairoScaledFont $scaledfont ) : array

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

scaledfont

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_extents() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_scaled_font_extents
  • cairo_scaled_font_get_font_face »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_scaled_font_get_ctm

(PECL cairo >= 0.1.0)

cairo_scaled_font_get_ctm — Description

Description

cairo_scaled_font_get_ctm ( CairoScaledFont $scaledfont ) : CairoMatrix

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

scaledfont

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_get_ctm() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_scaled_font_get_ctm
  • cairo_scaled_font_get_font_matrix »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_scaled_font_get_font_face

(PECL cairo >= 0.1.0)

cairo_scaled_font_get_font_face — Description

Description

cairo_scaled_font_get_font_face ( CairoScaledFont $scaledfont ) : CairoFontFace

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

scaledfont

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_get_font_face() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_scaled_font_get_font_face
  • cairo_scaled_font_get_font_options »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_scaled_font_get_font_matrix

(PECL cairo >= 0.1.0)

cairo_scaled_font_get_font_matrix — Description

Description

cairo_scaled_font_get_font_matrix ( CairoScaledFont $scaledfont ) : CairoFontOptions

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

scaledfont

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_get_font_matrix() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_scaled_font_get_font_matrix
  • cairo_scaled_font_get_scale_matrix »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_scaled_font_get_font_options

(PECL cairo >= 0.1.0)

cairo_scaled_font_get_font_options — Description

Description

cairo_scaled_font_get_font_options ( CairoScaledFont $scaledfont ) : CairoFontOptions

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

scaledfont

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_get_font_options() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_scaled_font_get_font_options
  • cairo_scaled_font_get_type »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_scaled_font_get_scale_matrix

(PECL cairo >= 0.1.0)

cairo_scaled_font_get_scale_matrix — Description

Description

cairo_scaled_font_get_scale_matrix ( CairoScaledFont $scaledfont ) : CairoMatrix

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

scaledfont

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_get_scale_matrix() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_scaled_font_get_scale_matrix
  • cairo_scaled_font_glyph_extents »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_scaled_font_get_type

(PECL cairo >= 0.1.0)

cairo_scaled_font_get_type — Description

Description

cairo_scaled_font_get_type ( CairoScaledFont $scaledfont ) : int

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

scaledfont

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_get_type() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_scaled_font_get_type
  • cairo_scaled_font_status »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_scaled_font_glyph_extents

(PECL cairo >= 0.1.0)

cairo_scaled_font_glyph_extents — Description

Description

cairo_scaled_font_glyph_extents ( CairoScaledFont $scaledfont , array $glyphs ) : array

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

scaledfont

Description...

glyphs

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_glyph_extents() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_scaled_font_glyph_extents
  • cairo_scaled_font_text_extents »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_scaled_font_status

(PECL cairo >= 0.1.0)

cairo_scaled_font_status — Description

Description

cairo_scaled_font_status ( CairoScaledFont $scaledfont ) : int

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

scaledfont

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_status() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_scaled_font_status
  • cairo_surface_copy_page »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_scaled_font_text_extents

(PECL cairo >= 0.1.0)

cairo_scaled_font_text_extents — Description

Description

cairo_scaled_font_text_extents ( CairoScaledFont $scaledfont , string $text ) : array

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

scaledfont

Description...

text

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_scaled_font_text_extents() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_scaled_font_text_extents
  • cairo_surface_create_similar »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_surface_copy_page

(PECL cairo >= 0.1.0)

cairo_surface_copy_page — Description

Description

cairo_surface_copy_page ( CairoSurface $surface ) : void

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_copy_page() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_surface_copy_page
  • cairo_surface_finish »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_surface_create_similar

(PECL cairo >= 0.1.0)

cairo_surface_create_similar — Description

Description

cairo_surface_create_similar ( CairoSurface $surface , int $content , float $width , float $height ) : CairoSurface

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

content

Description...

width

Description...

height

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_create_similar() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_surface_create_similar
  • cairo_surface_flush »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_surface_finish

(PECL cairo >= 0.1.0)

cairo_surface_finish — Description

Description

cairo_surface_finish ( CairoSurface $surface ) : void

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_finish() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_surface_finish
  • cairo_surface_get_content »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_surface_flush

(PECL cairo >= 0.1.0)

cairo_surface_flush — Description

Description

cairo_surface_flush ( CairoSurface $surface ) : void

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_flush() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_surface_flush
  • cairo_surface_get_device_offset »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_surface_get_content

(PECL cairo >= 0.1.0)

cairo_surface_get_content — Description

Description

cairo_surface_get_content ( CairoSurface $surface ) : int

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_get_content() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_surface_get_content
  • cairo_surface_get_font_options »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_surface_get_device_offset

(PECL cairo >= 0.1.0)

cairo_surface_get_device_offset — Description

Description

cairo_surface_get_device_offset ( CairoSurface $surface ) : array

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_get_device_offset() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_surface_get_device_offset
  • cairo_surface_get_type »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_surface_get_font_options

(PECL cairo >= 0.1.0)

cairo_surface_get_font_options — Description

Description

cairo_surface_get_font_options ( CairoSurface $surface ) : CairoFontOptions

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_get_font_options() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_surface_get_font_options
  • cairo_surface_mark_dirty_rectangle »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_surface_get_type

(PECL cairo >= 0.1.0)

cairo_surface_get_type — Description

Description

cairo_surface_get_type ( CairoSurface $surface ) : int

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_get_type() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_surface_get_type
  • cairo_surface_mark_dirty »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_surface_mark_dirty_rectangle

(PECL cairo >= 0.1.0)

cairo_surface_mark_dirty_rectangle — Description

Description

cairo_surface_mark_dirty_rectangle ( CairoSurface $surface , float $x , float $y , float $width , float $height ) : void

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

x

Description...

y

Description...

width

Description...

height

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_mark_dirty_rectangle() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_surface_mark_dirty_rectangle
  • cairo_surface_set_device_offset »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_surface_mark_dirty

(PECL cairo >= 0.1.0)

cairo_surface_mark_dirty — Description

Description

cairo_surface_mark_dirty ( CairoSurface $surface ) : void

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_mark_dirty() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_surface_mark_dirty
  • cairo_surface_set_fallback_resolution »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_surface_set_device_offset

(PECL cairo >= 0.1.0)

cairo_surface_set_device_offset — Description

Description

cairo_surface_set_device_offset ( CairoSurface $surface , float $x , float $y ) : void

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

x

Description...

y

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_set_device_offset() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_surface_set_device_offset
  • cairo_surface_show_page »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_surface_set_fallback_resolution

(PECL cairo >= 0.1.0)

cairo_surface_set_fallback_resolution — Description

Description

cairo_surface_set_fallback_resolution ( CairoSurface $surface , float $x , float $y ) : void

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

x

Description...

y

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_set_fallback_resolution() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_surface_set_fallback_resolution
  • cairo_surface_status »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_surface_show_page

(PECL cairo >= 0.1.0)

cairo_surface_show_page — Description

Description

cairo_surface_show_page ( CairoSurface $surface ) : void

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_show_page() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_surface_show_page
  • cairo_surface_write_to_png »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_surface_status

(PECL cairo >= 0.1.0)

cairo_surface_status — Description

Description

cairo_surface_status ( CairoSurface $surface ) : int

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_status() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_surface_status
  • cairo_svg_surface_create »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_surface_write_to_png

(PECL cairo >= 0.1.0)

cairo_surface_write_to_png — Description

Description

cairo_surface_write_to_png ( CairoSurface $surface , resource $stream ) : void

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

stream

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_surface_write_to_png() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_surface_write_to_png
  • cairo_svg_surface_restrict_to_version »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_svg_surface_create

(PECL cairo >= 0.1.0)

cairo_svg_surface_create — Description

Description

cairo_svg_surface_create ( string $file , float $width , float $height ) : CairoSvgSurface

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

file

Description...

width

Description...

height

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_svg_surface_create() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_svg_surface_create
  • cairo_svg_version_to_string »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_svg_surface_restrict_to_version

(PECL cairo >= 0.1.0)

cairo_svg_surface_restrict_to_version — Description

Description

cairo_svg_surface_restrict_to_version ( CairoSvgSurface $surface , int $version ) : void

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

version

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_svg_surface_restrict_to_version() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


Description

  • « cairo_svg_surface_restrict_to_version
  • Cairo »
  • PHP Manual
  • Cairo Functions
  • Description

cairo_svg_version_to_string

(PECL cairo >= 0.1.0)

cairo_svg_version_to_string — Description

Description

cairo_svg_version_to_string ( int $version ) : string

The function description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

version

Description...

Return Values

What is returned on success and failure

Errors/Exceptions

When does this function issue E_* level errors, and/or throw exceptions.

Examples

Example #1 cairo_svg_version_to_string() example

Any text that describes the purpose of the example, or what goes on in the example should be here.

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • related function name here()


The Cairo class

(PECL cairo >= 0.1.0)

Introduction

Simple class with some static helper methods.

Class synopsis

Cairo {
/* Methods */
public static availableFonts ( void ) : array
public static availableSurfaces ( void ) : array
public static statusToString ( int $status ) : string
public static version ( void ) : int
public static versionString ( void ) : string
}

Table of Contents

  • Cairo::availableFonts — Retrieves the availables font types
  • Cairo::availableSurfaces — Retrieves all available surfaces
  • Cairo::statusToString — Retrieves the current status as string
  • Cairo::version — Retrieves cairo's library version
  • Cairo::versionString — Retrieves cairo version as string


Retrieves the availables font types

  • « Cairo
  • Cairo::availableSurfaces »
  • PHP Manual
  • Cairo
  • Retrieves the availables font types

Cairo::availableFonts

cairo_available_fonts

(PECL cairo >= 0.1.0)

Cairo::availableFonts -- cairo_available_fonts — Retrieves the availables font types

Description

Object oriented style:

public static Cairo::availableFonts ( void ) : array

Procedural style:

cairo_available_fonts ( void ) : array

Returns an array with the available font backends

Parameters

This function has no parameters.

Return Values

A list-type array with all available font backends.

Examples

Example #1 Object oriented style

<?php

/* Object Oriented Style */
var_dump(Cairo::availableFonts());

?>

The above example will output something similar to:

array(2) {
  [0]=>
  string(5) "WIN32"
  [1]=>
  string(4) "USER"
}

Example #2 Procedural style

<?php

/* Procedural style */
var_dump(cairo_available_fonts());

?>

The above example will output something similar to:

array(2) {
  [0]=>
  string(5) "WIN32"
  [1]=>
  string(4) "USER"
}

See Also

  • Cairo::availableSurfaces() - Retrieves all available surfaces


Retrieves all available surfaces

  • « Cairo::availableFonts
  • Cairo::statusToString »
  • PHP Manual
  • Cairo
  • Retrieves all available surfaces

Cairo::availableSurfaces

cairo_available_surfaces

(PECL cairo >= 0.1.0)

Cairo::availableSurfaces -- cairo_available_surfaces — Retrieves all available surfaces

Description

Object oriented style (method):

public static Cairo::availableSurfaces ( void ) : array

Procedural style:

cairo_available_surfaces ( void ) : array

Returns an array with the available surface backends

Parameters

This function has no parameters.

Return Values

A list-type array with all available surface backends.

Examples

Example #1 Object oriented style

<?php

/* Object Oriented style */
var_dump(Cairo::availableSurfaces());

?>

The above example will output something similar to:

array(6) {
  [0]=>
  string(5) "IMAGE"
  [1]=>
  string(3) "PNG"
  [2]=>
  string(3) "PDF"
  [3]=>
  string(2) "PS"
  [4]=>
  string(3) "SVG"
  [5]=>
  string(5) "WIN32"
}

Example #2 Procedural style

<?php

/* Procedural style */
var_dump(cairo_available_surfaces());

?>

The above example will output something similar to:

array(6) {
  [0]=>
  string(5) "IMAGE"
  [1]=>
  string(3) "PNG"
  [2]=>
  string(3) "PDF"
  [3]=>
  string(2) "PS"
  [4]=>
  string(3) "SVG"
  [5]=>
  string(5) "WIN32"
}

See Also

  • Cairo::availableFonts() - Retrieves the availables font types


Retrieves the current status as string

  • « Cairo::availableSurfaces
  • Cairo::version »
  • PHP Manual
  • Cairo
  • Retrieves the current status as string

Cairo::statusToString

cairo_status_to_string

(PECL cairo >= 0.1.0)

Cairo::statusToString -- cairo_status_to_string — Retrieves the current status as string

Description

Object oriented style (method):

public static Cairo::statusToString ( int $status ) : string

Procedural style:

cairo_status_to_string ( int $status ) : string

Retrieves the current status as a readable string

Parameters

status

A valid status code given by cairo_status() or CairoContext::status()

Return Values

A string containing the current status of a CairoContext object

Examples

Example #1 Object oriented style

<?php
$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);
$context = new CairoContext($surface);

var_dump(Cairo::statusToString($context->status()));
?>

The above example will output something similar to:

string(7) "success"

Example #2 Procedural style

<?php
$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);
$context = cairo_create($surface);

var_dump(cairo_status_to_string(cairo_status($context)));
?>

The above example will output something similar to:

string(7) "success"

See Also

  • CairoContext::status() - The status purpose


Retrieves cairo's library version

  • « Cairo::statusToString
  • Cairo::versionString »
  • PHP Manual
  • Cairo
  • Retrieves cairo's library version

Cairo::version

cairo_version

(PECL cairo >= 0.1.0)

Cairo::version -- cairo_version — Retrieves cairo's library version

Description

Object oriented style (method):

public static Cairo::version ( void ) : int

Procedural style:

cairo_version ( void ) : int

Retrieves the current version of the cairo library as an integer value

Parameters

This function has no parameters.

Return Values

Current Cairo library version integer

Examples

Example #1 Object oriented style

<?php
var_dump(Cairo::version());
?>

The above example will output something similar to:

int(10808)

Example #2 Procedural style

<?php
var_dump(cairo_version());
?>

The above example will output something similar to:

int(10808)

See Also

  • Cairo::versionString() - Retrieves cairo version as string


Retrieves cairo version as string

  • « Cairo::version
  • CairoContext »
  • PHP Manual
  • Cairo
  • Retrieves cairo version as string

Cairo::versionString

cairo_version_string

(PECL cairo >= 0.1.0)

Cairo::versionString -- cairo_version_string — Retrieves cairo version as string

Description

Object oriented style (method):

public static Cairo::versionString ( void ) : string

Procedural style:

cairo_version_string ( void ) : string

Retrieves the current cairo library version as a string.

Parameters

This function has no parameters.

Return Values

Current Cairo library version string

Examples

Example #1 Object oriented style

<?php

var_dump(Cairo::versionString());

?>

The above example will output something similar to:

string(5) "1.8.8"

Example #2 Procedural style

<?php

var_dump(cairo_version_string());

?>

The above example will output something similar to:

string(5) "1.8.8"

See Also

  • Cairo::version() - Retrieves cairo's library version


The CairoContext class

(PECL cairo >= 0.1.0)

Introduction

Context is the main object used when drawing with cairo. To draw with cairo, you create a CairoContext, set the target CairoSurface, and drawing options for the CairoContext, create shapes with functions . like CairoContext::moveTo() and CairoContext::lineTo(), and then draw shapes with CairoContext::stroke() or CairoContext::fill(). Contexts can be pushed to a stack via CairoContext::save(). They may then safely be changed, without losing the current state. Use CairoContext::restore() to restore to the saved state.

Class synopsis

CairoContext {
/* Methods */
public appendPath ( CairoPath $path ) : void
public arc ( float $x , float $y , float $radius , float $angle1 , float $angle2 ) : void
public arcNegative ( float $x , float $y , float $radius , float $angle1 , float $angle2 ) : void
public clip ( void ) : void
public clipExtents ( void ) : array
public clipPreserve ( void ) : void
public clipRectangleList ( void ) : array
public closePath ( void ) : void
public __construct ( CairoSurface $surface )
public copyPage ( void ) : void
public copyPath ( void ) : CairoPath
public copyPathFlat ( void ) : CairoPath
public curveTo ( float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 ) : void
public deviceToUser ( float $x , float $y ) : array
public deviceToUserDistance ( float $x , float $y ) : array
public fill ( void ) : void
public fillExtents ( void ) : array
public fillPreserve ( void ) : void
public fontExtents ( void ) : array
public getAntialias ( void ) : int
public getCurrentPoint ( void ) : array
public getDash ( void ) : array
public getDashCount ( void ) : int
public getFillRule ( void ) : int
public getFontFace ( void ) : void
public getFontMatrix ( void ) : void
public getFontOptions ( void ) : void
public getGroupTarget ( void ) : void
public getLineCap ( void ) : int
public getLineJoin ( void ) : int
public getLineWidth ( void ) : float
public getMatrix ( void ) : void
public getMiterLimit ( void ) : float
public getOperator ( void ) : int
public getScaledFont ( void ) : void
public getSource ( void ) : void
public getTarget ( void ) : void
public getTolerance ( void ) : float
public glyphPath ( array $glyphs ) : void
public hasCurrentPoint ( void ) : bool
public identityMatrix ( void ) : void
public inFill ( float $x , float $y ) : bool
public inStroke ( float $x , float $y ) : bool
public lineTo ( float $x , float $y ) : void
public mask ( CairoPattern $pattern ) : void
public maskSurface ( CairoSurface $surface [, float $x [, float $y ]] ) : void
public moveTo ( float $x , float $y ) : void
public newPath ( void ) : void
public newSubPath ( void ) : void
public paint ( void ) : void
public paintWithAlpha ( float $alpha ) : void
public pathExtents ( void ) : array
public popGroup ( void ) : void
public popGroupToSource ( void ) : void
public pushGroup ( void ) : void
public pushGroupWithContent ( int $content ) : void
public rectangle ( float $x , float $y , float $width , float $height ) : void
public relCurveTo ( float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 ) : void
public relLineTo ( float $x , float $y ) : void
public relMoveTo ( float $x , float $y ) : void
public resetClip ( void ) : void
public restore ( void ) : void
public rotate ( float $angle ) : void
public save ( void ) : void
public scale ( float $x , float $y ) : void
public selectFontFace ( string $family [, int $slant [, int $weight ]] ) : void
public setAntialias ([ int $antialias ] ) : void
public setDash ( array $dashes [, float $offset ] ) : void
public setFillRule ( int $setting ) : void
public setFontFace ( CairoFontFace $fontface ) : void
public setFontMatrix ( CairoMatrix $matrix ) : void
public setFontOptions ( CairoFontOptions $fontoptions ) : void
public setFontSize ( float $size ) : void
public setLineCap ( int $setting ) : void
public setLineJoin ( int $setting ) : void
public setLineWidth ( float $width ) : void
public setMatrix ( CairoMatrix $matrix ) : void
public setMiterLimit ( float $limit ) : void
public setOperator ( int $setting ) : void
public setScaledFont ( CairoScaledFont $scaledfont ) : void
public setSource ( CairoPattern $pattern ) : void
public setSourceRGB ( float $red , float $green , float $blue ) : void
public setSourceRGBA ( float $red , float $green , float $blue , float $alpha ) : void
public setSourceSurface ( CairoSurface $surface [, float $x [, float $y ]] ) : void
public setTolerance ( float $tolerance ) : void
public showPage ( void ) : void
public showText ( string $text ) : void
public status ( void ) : int
public stroke ( void ) : void
public strokeExtents ( void ) : array
public strokePreserve ( void ) : void
public textExtents ( string $text ) : array
public textPath ( string $string ) : void
public transform ( CairoMatrix $matrix ) : void
public translate ( float $x , float $y ) : void
public userToDevice ( float $x , float $y ) : array
public userToDeviceDistance ( float $x , float $y ) : array
}

Table of Contents

  • CairoContext::appendPath — Appends a path to current path
  • CairoContext::arc — Adds a circular arc
  • CairoContext::arcNegative — Adds a negative arc
  • CairoContext::clip — Establishes a new clip region
  • CairoContext::clipExtents — Computes the area inside the current clip
  • CairoContext::clipPreserve — Establishes a new clip region from the current clip
  • CairoContext::clipRectangleList — Retrieves the current clip as a list of rectangles
  • CairoContext::closePath — Closes the current path
  • CairoContext::__construct — Creates a new CairoContext
  • CairoContext::copyPage — Emits the current page
  • CairoContext::copyPath — Creates a copy of the current path
  • CairoContext::copyPathFlat — Gets a flattened copy of the current path
  • CairoContext::curveTo — Adds a curve
  • CairoContext::deviceToUser — Transform a coordinate
  • CairoContext::deviceToUserDistance — Transform a distance
  • CairoContext::fill — Fills the current path
  • CairoContext::fillExtents — Computes the filled area
  • CairoContext::fillPreserve — Fills and preserve the current path
  • CairoContext::fontExtents — Get the font extents
  • CairoContext::getAntialias — Retrieves the current antialias mode
  • CairoContext::getCurrentPoint — The getCurrentPoint purpose
  • CairoContext::getDash — The getDash purpose
  • CairoContext::getDashCount — The getDashCount purpose
  • CairoContext::getFillRule — The getFillRule purpose
  • CairoContext::getFontFace — The getFontFace purpose
  • CairoContext::getFontMatrix — The getFontMatrix purpose
  • CairoContext::getFontOptions — The getFontOptions purpose
  • CairoContext::getGroupTarget — The getGroupTarget purpose
  • CairoContext::getLineCap — The getLineCap purpose
  • CairoContext::getLineJoin — The getLineJoin purpose
  • CairoContext::getLineWidth — The getLineWidth purpose
  • CairoContext::getMatrix — The getMatrix purpose
  • CairoContext::getMiterLimit — The getMiterLimit purpose
  • CairoContext::getOperator — The getOperator purpose
  • CairoContext::getScaledFont — The getScaledFont purpose
  • CairoContext::getSource — The getSource purpose
  • CairoContext::getTarget — The getTarget purpose
  • CairoContext::getTolerance — The getTolerance purpose
  • CairoContext::glyphPath — The glyphPath purpose
  • CairoContext::hasCurrentPoint — The hasCurrentPoint purpose
  • CairoContext::identityMatrix — The identityMatrix purpose
  • CairoContext::inFill — The inFill purpose
  • CairoContext::inStroke — The inStroke purpose
  • CairoContext::lineTo — The lineTo purpose
  • CairoContext::mask — The mask purpose
  • CairoContext::maskSurface — The maskSurface purpose
  • CairoContext::moveTo — The moveTo purpose
  • CairoContext::newPath — The newPath purpose
  • CairoContext::newSubPath — The newSubPath purpose
  • CairoContext::paint — The paint purpose
  • CairoContext::paintWithAlpha — The paintWithAlpha purpose
  • CairoContext::pathExtents — The pathExtents purpose
  • CairoContext::popGroup — The popGroup purpose
  • CairoContext::popGroupToSource — The popGroupToSource purpose
  • CairoContext::pushGroup — The pushGroup purpose
  • CairoContext::pushGroupWithContent — The pushGroupWithContent purpose
  • CairoContext::rectangle — The rectangle purpose
  • CairoContext::relCurveTo — The relCurveTo purpose
  • CairoContext::relLineTo — The relLineTo purpose
  • CairoContext::relMoveTo — The relMoveTo purpose
  • CairoContext::resetClip — The resetClip purpose
  • CairoContext::restore — The restore purpose
  • CairoContext::rotate — The rotate purpose
  • CairoContext::save — The save purpose
  • CairoContext::scale — The scale purpose
  • CairoContext::selectFontFace — The selectFontFace purpose
  • CairoContext::setAntialias — The setAntialias purpose
  • CairoContext::setDash — The setDash purpose
  • CairoContext::setFillRule — The setFillRule purpose
  • CairoContext::setFontFace — The setFontFace purpose
  • CairoContext::setFontMatrix — The setFontMatrix purpose
  • CairoContext::setFontOptions — The setFontOptions purpose
  • CairoContext::setFontSize — The setFontSize purpose
  • CairoContext::setLineCap — The setLineCap purpose
  • CairoContext::setLineJoin — The setLineJoin purpose
  • CairoContext::setLineWidth — The setLineWidth purpose
  • CairoContext::setMatrix — The setMatrix purpose
  • CairoContext::setMiterLimit — The setMiterLimit purpose
  • CairoContext::setOperator — The setOperator purpose
  • CairoContext::setScaledFont — The setScaledFont purpose
  • CairoContext::setSource — The setSource purpose
  • CairoContext::setSourceRGB — The setSourceRGB purpose
  • CairoContext::setSourceRGBA — The setSourceRGBA purpose
  • CairoContext::setSourceSurface — The setSourceSurface purpose
  • CairoContext::setTolerance — The setTolerance purpose
  • CairoContext::showPage — The showPage purpose
  • CairoContext::showText — The showText purpose
  • CairoContext::status — The status purpose
  • CairoContext::stroke — The stroke purpose
  • CairoContext::strokeExtents — The strokeExtents purpose
  • CairoContext::strokePreserve — The strokePreserve purpose
  • CairoContext::textExtents — The textExtents purpose
  • CairoContext::textPath — The textPath purpose
  • CairoContext::transform — The transform purpose
  • CairoContext::translate — The translate purpose
  • CairoContext::userToDevice — The userToDevice purpose
  • CairoContext::userToDeviceDistance — The userToDeviceDistance purpose


Appends a path to current path

  • « CairoContext
  • CairoContext::arc »
  • PHP Manual
  • CairoContext
  • Appends a path to current path

CairoContext::appendPath

cairo_append_path

(PECL cairo >= 0.1.0)

CairoContext::appendPath -- cairo_append_path — Appends a path to current path

Description

Object oriented style (method):

public CairoContext::appendPath ( CairoPath $path ) : void

Procedural style:

cairo_append_path ( CairoContext $context , CairoPath $path ) : void

Appends the path onto the current path. The path may be either the return value from one of CairoContext::copyPath() or CairoContext::copyPathFlat();

if path is not a valid CairoPath instance a CairoException will be thrown

Parameters

context

CairoContext object

path

CairoPath object

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

$path = $context->copyPath();

$context->appendPath($path);

?>

Example #2 Procedural style

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

$path = cairo_copy_path($context);

cairo_append_path($context, $path);

?>

See Also

  • CairoPath
  • CairoContext::copyPath() - Creates a copy of the current path
  • CairoContext::copyPathFlat() - Gets a flattened copy of the current path


Adds a circular arc

  • « CairoContext::appendPath
  • CairoContext::arcNegative »
  • PHP Manual
  • CairoContext
  • Adds a circular arc

CairoContext::arc

cairo_arc

(PECL cairo >= 0.1.0)

CairoContext::arc -- cairo_arc — Adds a circular arc

Description

Object oriented style (method):

public CairoContext::arc ( float $x , float $y , float $radius , float $angle1 , float $angle2 ) : void

Procedural style:

cairo_arc ( CairoContext $context , float $x , float $y , float $radius , float $angle1 , float $angle2 ) : void

Adds a circular arc of the given radius to the current path. The arc is centered at (x, y), begins at angle1 and proceeds in the direction of increasing angles to end at angle2. If angle2 is less than angle1 it will be progressively increased by 2*M_PI until it is greater than angle1. If there is a current point, an initial line segment will be added to the path to connect the current point to the beginning of the arc. If this initial line is undesired, it can be avoided by calling CairoContext::newSubPath() or procedural cairo_new_sub_path() before calling CairoContext::arc() or cairo_arc(). Angles are measured in radians. An angle of 0.0 is in the direction of the positive X axis (in user space). An angle of M_PI/2.0 radians (90 degrees) is in the direction of the positive Y axis (in user space). Angles increase in the direction from the positive X axis toward the positive Y axis. So with the default transformation matrix, angles increase in a clockwise direction. (To convert from degrees to radians, use degrees * (M_PI / 180.).) This function gives the arc in the direction of increasing angles; see CairoContext::arcNegative() or cairo_arc_negative() to get the arc in the direction of decreasing angles.

Parameters

context

A valid CairoContext object

x

x position

y

y position

radius

Radius of the arc

angle1

start angle

angle2

end angle

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php

$s = new CairoImageSurface(CairoFormat::ARGB32, 100, 100);
$c = new CairoContext($s);

$c->setSourceRgb(0, 0, 0);
$c->paint();

$c->setLineWidth(1);
$c->setSourceRgb(1, 1, 1);

for ($r = 50; $r > 0; $r -= 10) {
 $c->arc(50, 50, $r, 0, 2 * M_PI);
 $c->stroke();
 $c->fill();
}

$s->writeToPng(dirname(__FILE__) . '/CairoContext__arc.png');
?>

Example #2 Procedural style

<?php

$s = cairo_image_surface_create(CAIRO_SURFACE_TYPE_IMAGE, 100, 100);
$c = cairo_create($s);

cairo_set_source_rgb($c, 0, 0, 0);
cairo_paint($c);

cairo_set_source_rgb($c, 1, 1, 1);
cairo_set_line_width($c, 1);

for ($r = 50; $r > 0; $r -= 10) {
 cairo_arc($c, 50, 50, $r, 0, 2 * M_PI);
 cairo_stroke($c);
 cairo_fill($c);
}

cairo_surface_write_to_png($s, dirname(__FILE__) . '/cairo_arc.png');
?>

See Also

  • CairoContext::arcNegative() - Adds a negative arc


Adds a negative arc

  • « CairoContext::arc
  • CairoContext::clip »
  • PHP Manual
  • CairoContext
  • Adds a negative arc

CairoContext::arcNegative

cairo_arc_negative

(PECL cairo >= 0.1.0)

CairoContext::arcNegative -- cairo_arc_negative — Adds a negative arc

Description

Object oriented style (method):

public CairoContext::arcNegative ( float $x , float $y , float $radius , float $angle1 , float $angle2 ) : void

Procedural style:

cairo_arc_negative ( CairoContext $context , float $x , float $y , float $radius , float $angle1 , float $angle2 ) : void

Adds a circular arc of the given radius to the current path. The arc is centered at (x, y), begins at angle1 and proceeds in the direction of decreasing angles to end at angle2. If angle2 is greater than angle1 it will be progressively decreased by 2*M_PI until it is less than angle1. See CairoContext::arc() or cairo_arc() for more details. This function differs only in the direction of the arc between the two angles.

Parameters

context

A valid CairoContext object

x

double x position

y

double y position

radius

The radius of the desired negative arc

angle1

Start angle of the arc

angle2

End angle of the arc

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php

$s = new CairoImageSurface(CairoFormat::ARGB32, 100, 100);
$c = new CairoContext($s);

$c->setSourceRgb(0, 0, 0);
$c->paint();

$c->setLineWidth(1);
$c->setSourceRgb(1, 1, 1);

for ($r = 50; $r > 0; $r -= 10) {
 $c->arcNegative(50, 50, $r, 2 * M_PI, 0);
 $c->stroke();
 $c->fill();
}

$s->writeToPng(dirname(__FILE__) . '/CairoContext__arcNegative.png');
?>

Example #2 Procedural style

<?php

$s = cairo_image_surface_create(CAIRO_SURFACE_TYPE_IMAGE, 100, 100);
$c = cairo_create($s);

cairo_set_source_rgb($c, 0, 0, 0);
cairo_paint($c);

cairo_set_source_rgb($c, 1, 1, 1);
cairo_set_line_width($c, 1);

for ($r = 50; $r > 0; $r -= 10) {
 cairo_arc_negative($c, 50, 50, $r, 2 * M_PI, 0);
 cairo_stroke($c);
 cairo_fill($c);
}

cairo_surface_write_to_png($s, dirname(__FILE__) . '/cairo_arc_negative.png');
?>

See Also

  • CairoContext::arc() - Adds a circular arc


Establishes a new clip region

  • « CairoContext::arcNegative
  • CairoContext::clipExtents »
  • PHP Manual
  • CairoContext
  • Establishes a new clip region

CairoContext::clip

cairo_clip

(PECL cairo >= 0.1.0)

CairoContext::clip -- cairo_clip — Establishes a new clip region

Description

Object oriented style (method):

public CairoContext::clip ( void ) : void

Procedural style:

cairo_clip ( CairoContext $context ) : void

Establishes a new clip region by intersecting the current clip region with the current path as it would be filled by CairoContext::fill() or cairo_fill() and according to the current fill rule (see CairoContext::setFillRule() or cairo_set_fill_rule()).

After CairoContext::clip() or cairo_clip(), the current path will be cleared from the cairo context.

The current clip region affects all drawing operations by effectively masking out any changes to the surface that are outside the current clip region.

Calling CairoContext::clip() or cairo_clip()
can only make the clip region smaller, never larger. But the current clip is part of the
graphics state, so a temporary restriction of the clip region can be achieved by calling
CairoContext::clip() or cairo_clip() within a
CairoContext::save()/CairoContext::restore() or
cairo_save()/cairo_restore() pair.
The only other means of increasing the size of the clip region is
CairoContext::resetClip() or procedural cairo_reset_clip().

Parameters

context

A valid CairoContext object

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

$context->clip();

?>

Example #2 Procedural style

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

cairo_clip($context);

?>

See Also

  • CairoContext::resetClip() - The resetClip purpose
  • cairo_reset_clip() - The resetClip purpose


Computes the area inside the current clip

  • « CairoContext::clip
  • CairoContext::clipPreserve »
  • PHP Manual
  • CairoContext
  • Computes the area inside the current clip

CairoContext::clipExtents

cairo_clip_extents

(PECL cairo >= 0.1.0)

CairoContext::clipExtents -- cairo_clip_extents — Computes the area inside the current clip

Description

Object oriented style (method):

public CairoContext::clipExtents ( void ) : array

Procedural style:

cairo_clip_extents ( CairoContext $context ) : array

Computes a bounding box in user coordinates covering the area inside the current clip.

Parameters

context

A valid CairoContext object

Return Values

An array containing the (float)x1, (float)y1, (float)x2, (float)y2, coordinates covering the area inside the current clip

Examples

Example #1 Object oriented style

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

var_dump($context->clipExtents());
?>

The above example will output something similar to:

array(4) {
  [0]=>
  float(0)
  [1]=>
  float(0)
  [2]=>
  float(50)
  [3]=>
  float(50)
}

Example #2 Procedural style

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

var_dump(cairo_clip_extents($context));

?>

The above example will output something similar to:

array(4) {
  [0]=>
  float(0)
  [1]=>
  float(0)
  [2]=>
  float(50)
  [3]=>
  float(50)
}

See Also

  • CairoContext::clip() - Establishes a new clip region


Establishes a new clip region from the current clip

  • « CairoContext::clipExtents
  • CairoContext::clipRectangleList »
  • PHP Manual
  • CairoContext
  • Establishes a new clip region from the current clip

CairoContext::clipPreserve

cairo_clip_preserve

(PECL cairo >= 0.1.0)

CairoContext::clipPreserve -- cairo_clip_preserve — Establishes a new clip region from the current clip

Description

Object oriented style (method):

public CairoContext::clipPreserve ( void ) : void

Procedural style:

cairo_clip_preserve ( CairoContext $context ) : void

Establishes a new clip region by intersecting the current clip region with the current path as it would be filled by Context.fill() and according to the current FILL RULE (see CairoContext::setFillRule() or cairo_set_fill_rule()).

Unlike CairoContext::clip(), CairoContext::clipPreserve() preserves the path within the Context. The current clip region affects all drawing operations by effectively masking out any changes to the surface that are outside the current clip region.

Calling CairoContext::clipPreserve() can only make the clip region smaller, never larger. But the current clip is part of the graphics state, so a temporary restriction of the clip region can be achieved by calling CairoContext::clipPreserve() within a CairoContext::save()/CairoContext::restore() pair. The only other means of increasing the size of the clip region is CairoContext::resetClip().

Parameters

context

A valid CairoContext object

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

$context->clipPreserve();

?>

Example #2 Procedural style

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

cairo_clip_preserve($context);

?>

See Also

  • CairoContext::save() - The save purpose
  • CairoContext::restore() - The restore purpose
  • CairoContext::resetClip() - The resetClip purpose


Retrieves the current clip as a list of rectangles

  • « CairoContext::clipPreserve
  • CairoContext::closePath »
  • PHP Manual
  • CairoContext
  • Retrieves the current clip as a list of rectangles

CairoContext::clipRectangleList

cairo_clip_rectangle_list

(PECL cairo >= 0.1.0)

CairoContext::clipRectangleList -- cairo_clip_rectangle_list — Retrieves the current clip as a list of rectangles

Description

Object oriented style (method):

public CairoContext::clipRectangleList ( void ) : array

Procedural style:

cairo_clip_rectangle_list ( CairoContext $context ) : array

Returns a list-type array with the current clip region as a list of rectangles in user coordinates

Parameters

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Return Values

An array of user-space represented rectangles for the current clip

(The status in the list may be CAIRO_STATUS_CLIP_NOT_REPRESENTABLE to indicate that the clip region cannot be represented as a list of user-space rectangles. The status may have other values to indicate other errors.)

Examples

Example #1 Object oriented style

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

var_dump($context->clipRectangleList());

?>

The above example will output something similar to:

array(1) {
  [0]=>
  array(4) {
    ["x"]=>
    float(0)
    ["y"]=>
    float(0)
    ["width"]=>
    float(50)
    ["height"]=>
    float(50)
  }
}

Example #2 Procedural style

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

var_dump(cairo_clip_rectangle_list($context));

?>

The above example will output something similar to:

array(1) {
  [0]=>
  array(4) {
    ["x"]=>
    float(0)
    ["y"]=>
    float(0)
    ["width"]=>
    float(50)
    ["height"]=>
    float(50)
  }
}

See Also

  • Classname::Method()


Closes the current path

  • « CairoContext::clipRectangleList
  • CairoContext::__construct »
  • PHP Manual
  • CairoContext
  • Closes the current path

CairoContext::closePath

cairo_close_path

(PECL cairo >= 0.1.0)

CairoContext::closePath -- cairo_close_path — Closes the current path

Description

Object oriented style (method):

public CairoContext::closePath ( void ) : void

Procedural style:

cairo_close_path ( CairoContext $context ) : void

Adds a line segment to the path from the current point to the beginning of the current sub-path, (the most recent point passed to CairoContext::moveTo()), and closes this sub-path. After this call the current point will be at the joined endpoint of the sub-path.

The behavior of close_path() is distinct from simply calling CairoContext::lineTo() with the equivalent coordinate in the case of stroking. When a closed sub-path is stroked, there are no caps on the ends of the sub-path. Instead, there is a line join connecting the final and initial segments of the sub-path.

If there is no current point before the call to CairoContext::closePath(), this function will have no effect.

Parameters

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

$context->closePath();

?>

Example #2 Procedural style

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

cairo_close_path($context);

?>

See Also

  • CairoContext::copyPath() - Creates a copy of the current path


Creates a new CairoContext

  • « CairoContext::closePath
  • CairoContext::copyPage »
  • PHP Manual
  • CairoContext
  • Creates a new CairoContext

CairoContext::__construct

(PECL cairo >= 0.1.0)

CairoContext::__construct — Creates a new CairoContext

Description

public CairoContext::__construct ( CairoSurface $surface )

Creates a new CairoContext object to draw

Parameters

surface

A valid CairoSurface like CairoImageSurface or CairoPdfSurface

Return Values

A CairoContext

Examples

Example #1 CairoContext::__construct() example

<?php
// The surface to work on
$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

// Create a new CairoContext for the CairoSurface
$context = new CairoContext($surface);

?>

See Also

  • Cairo::Method()


Emits the current page

  • « CairoContext::__construct
  • CairoContext::copyPath »
  • PHP Manual
  • CairoContext
  • Emits the current page

CairoContext::copyPage

cairo_copy_page

(PECL cairo >= 0.1.0)

CairoContext::copyPage -- cairo_copy_page — Emits the current page

Description

Object oriented style (method):

public CairoContext::copyPage ( void ) : void

Procedural style:

cairo_copy_page ( CairoContext $context ) : void

Emits the current page for backends that support multiple pages, but doesn’t clear it, so, the contents of the current page will be retained for the next page too. Use CairoContext::showPage() if you want to get an empty page after the emission.

This is a convenience function that simply calls CairoSurface::copyPage() on CairoContext’s target.

Parameters

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

$context->copyPage();

?>

Example #2 Procedural style

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

cairo_copy_page($context);

?>

See Also

  • CairoContext::showPage() - The showPage purpose
  • CairoSurface::copyPage() - The copyPage purpose


Creates a copy of the current path

  • « CairoContext::copyPage
  • CairoContext::copyPathFlat »
  • PHP Manual
  • CairoContext
  • Creates a copy of the current path

CairoContext::copyPath

cairo_copy_path

(PECL cairo >= 0.1.0)

CairoContext::copyPath -- cairo_copy_path — Creates a copy of the current path

Description

Object oriented style (method):

public CairoContext::copyPath ( void ) : CairoPath

Procedural style:

cairo_copy_path ( CairoContext $context ) : CairoPath

Creates a copy of the current path and returns it to the user as a CairoPath. See CairoPath for hints on how to iterate over the returned data structure.

This function will always return a valid CairoPath object, but the result will have no data, if either of the following conditions hold:

  • 1. If there is insufficient memory to copy the path. In this case CairoPath->status will be set to CAIRO_STATUS_NO_MEMORY.
  • 2. If context is already in an error state. In this case CairoPath->status will contain the same status that would be returned by cairo_status().
In either case, CairoPath->status will be set to CAIRO_STATUS_NO_MEMORY (regardless of what the error status in cr might have been).

Parameters

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Return Values

A copy of the current CairoPath in the context

Examples

Example #1 Object oriented style

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

var_dump($context->copyPath())

?>

The above example will output something similar to:

object(CairoPath)#3 (0) {
}

Example #2 Procedural style

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

var_dump(cairo_copy_path($context));

?>

The above example will output something similar to:

object(CairoPath)#3 (0) {
}

See Also

  • CairoContext::closePath() - Closes the current path


Gets a flattened copy of the current path

  • « CairoContext::copyPath
  • CairoContext::curveTo »
  • PHP Manual
  • CairoContext
  • Gets a flattened copy of the current path

CairoContext::copyPathFlat

cairo_copy_path_flat

(PECL cairo >= 0.1.0)

CairoContext::copyPathFlat -- cairo_copy_path_flat — Gets a flattened copy of the current path

Description

Object oriented style (method):

public CairoContext::copyPathFlat ( void ) : CairoPath

Procedural style:

cairo_copy_path_flat ( CairoContext $context ) : CairoPath

Gets a flattened copy of the current path and returns it to the user as a CairoPath.

This function is like CairoContext::copyPath() except that any curves in the path will be approximated with piecewise-linear approximations, (accurate to within the current tolerance value). That is, the result is guaranteed to not have any elements of type CAIRO_PATH_CURVE_TO which will instead be replaced by a series of CAIRO_PATH_LINE_TO elements.

Parameters

context

A CairoContext object

Return Values

A copy of the current path

Examples

Example #1 Object oriented style

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

$context = new CairoContext($surface);

var_dump($context->copyPathFlat());

?>

The above example will output something similar to:

object(CairoPath)#3 (0) {
}

Example #2 Procedural style

<?php

$surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);

$context = cairo_create($surface);

var_dump(cairo_copy_path_flat($context));

?>

The above example will output something similar to:

object(CairoPath)#3 (0) {
}

See Also

  • CairoContext::copyPath() - Creates a copy of the current path
  • CairoContext::closePath() - Closes the current path


Adds a curve

  • « CairoContext::copyPathFlat
  • CairoContext::deviceToUser »
  • PHP Manual
  • CairoContext
  • Adds a curve

CairoContext::curveTo

cairo_curve_to

(PECL cairo >= 0.1.0)

CairoContext::curveTo -- cairo_curve_to — Adds a curve

Description

Object oriented style (method):

public CairoContext::curveTo ( float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 ) : void

Procedural style:

cairo_curve_to ( CairoContext $context , float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 ) : void

Adds a cubic Bezier spline to the path from the current point to position x3 ,y3 in user-space coordinates, using x1, y1 and x2, y2 as the control points. After this call the current point will be x3, y3.

If there is no current point before the call to CairoContext::curveTo() this function will behave as if preceded by a call to CairoContext::moveTo() (x1, y1).

Parameters

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

x1

First control point in the x axis for the curve

y1

First control point in the y axis for the curve

x2

Second control point in x axis for the curve

y2

Second control point in y axis for the curve

x3

Final point in the x axis for the curve

y3

Final point in the y axis for the curve

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php
$s = new CairoImageSurface(CairoFormat::ARGB32, 100, 100);
$c = new CairoContext($s);

$c->setSourceRgb(0, 0, 0);

$c->paint();

$c->moveTo(10, 50);
$c->setLineWidth(5);
$c->setSourceRgb(.1, 0, 1);
$c->curveTo(20, 80, 80, 20, 90, 50);
$c->stroke();

$s->writeToPng(dirname(__FILE__) . '/curveTo.png');
?>

Example #2 Procedural style

<?php

$s = cairo_image_surface_create(CAIRO_SURFACE_TYPE_IMAGE, 100, 100);
$c = cairo_create($s);

cairo_set_source_rgb($c, 0, 0, 0);

cairo_paint($c);

cairo_move_to($c, 10, 50);
cairo_set_line_width($c, 5);
cairo_set_source_rgb($c, .1, 0, 1);
cairo_curve_to($c, 20, 80, 80, 20, 90, 50);
cairo_stroke($c);

cairo_surface_write_to_png($s, dirname(__FILE__) . '/curve_to.png');
?>

See Also

  • CairoContext::moveTo() - The moveTo purpose


Transform a coordinate

  • « CairoContext::curveTo
  • CairoContext::deviceToUserDistance »
  • PHP Manual
  • CairoContext
  • Transform a coordinate

CairoContext::deviceToUser

cairo_device_to_user

(PECL cairo >= 0.1.0)

CairoContext::deviceToUser -- cairo_device_to_user — Transform a coordinate

Description

Object oriented style (method):

public CairoContext::deviceToUser ( float $x , float $y ) : array

Procedural style:

cairo_device_to_user ( CairoContext $context , float $x , float $y ) : array

Transform a coordinate from device space to user space by multiplying the given point by the inverse of the current transformation matrix (CTM).

Parameters

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

x

x value of the coordinate

y

y value of the coordinate

Return Values

An array containing the x and y coordinates in the user-space

See Also

  • CairoContext::deviceToUserDistance() - Transform a distance


Transform a distance

  • « CairoContext::deviceToUser
  • CairoContext::fill »
  • PHP Manual
  • CairoContext
  • Transform a distance

CairoContext::deviceToUserDistance

cairo_device_to_user_distance

(PECL cairo >= 0.1.0)

CairoContext::deviceToUserDistance -- cairo_device_to_user_distance — Transform a distance

Description

Object oriented style (method):

public CairoContext::deviceToUserDistance ( float $x , float $y ) : array

Procedural style:

cairo_device_to_user_distance ( CairoContext $context , float $x , float $y ) : array

Transform a distance vector from device space to user space. This function is similar to CairoContext::deviceToUser() or cairo_device_to_user() except that the translation components of the inverse Cairo Transformation Matrix will be ignored when transforming (x,y).

Parameters

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

x

X component of a distance vector

y

Y component of a distance vector

Return Values

Returns an array with the x and y values of a distance vector in the user-space

See Also

  • CairoContext::deviceToUser() - Transform a coordinate


Fills the current path

  • « CairoContext::deviceToUserDistance
  • CairoContext::fillExtents »
  • PHP Manual
  • CairoContext
  • Fills the current path

CairoContext::fill

cairo_fill

(PECL cairo >= 0.1.0)

CairoContext::fill -- cairo_fill — Fills the current path

Description

Object oriented style (method):

public CairoContext::fill ( void ) : void

Procedural style:

cairo_fill ( CairoContext $context ) : void

A drawing operator that fills the current path according to the current CairoFillRule, (each sub-path is implicitly closed before being filled). After CairoContext::fill() or cairo_fill(), the current path will be cleared from the CairoContext.

Parameters

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php

$s = new CairoImageSurface(CairoFormat::ARGB32, 100, 100);
$c = new CairoContext($s);

$c->setSourceRgb(0, 0, 0);
$c->paint();

$c->setSourceRgb(1, 1, 1);
$c->rectangle(0, 0, 50, 50);
$c->fill();
$c->setSourceRgb(0, 1, 0);
$c->rectangle(50, 50, 50, 50);
$c->fill();

$s->writeToPng(dirname(__FILE__) . '/CairoContext_fill.png');

?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php

$s = cairo_image_surface_create(CAIRO_SURFACE_TYPE_IMAGE, 100, 100);
$c = cairo_create($s);

cairo_set_source_rgb($c, 0, 0, 0);
cairo_paint($c);

cairo_set_source_rgb($c, 1, 1, 1);
cairo_rectangle($c, 0, 0, 50, 50);
cairo_fill($c);
cairo_set_source_rgb($c, 0, 1, 0);
cairo_rectangle($c, 50, 50, 50, 50);
cairo_fill($c);

cairo_surface_write_to_png($s, dirname(__FILE__) . '/cairo_fill.png');

?>

The above example will output something similar to:

...

See Also

  • CairoContext::setFillRule() - The setFillRule purpose
  • ContextContext::fillPreserve()
  • CairoFillRule


Computes the filled area

  • « CairoContext::fill
  • CairoContext::fillPreserve »
  • PHP Manual
  • CairoContext
  • Computes the filled area

CairoContext::fillExtents

cairo_fill_extents

(PECL cairo >= 0.1.0)

CairoContext::fillExtents -- cairo_fill_extents — Computes the filled area

Description

Object oriented style (method):

public CairoContext::fillExtents ( void ) : array

Procedural style:

cairo_fill_extents ( CairoContext $context ) : array

Computes a bounding box in user coordinates covering the area that would be affected, (the “inked” area), by a CairoContext::fill() operation given the current path and fill parameters. If the current path is empty, returns an empty rectangle (0,0,0,0). Surface dimensions and clipping are not taken into account.

Contrast with CairoContext::pathExtents(), which is similar, but returns non-zero extents for some paths with no inked area, (such as a simple line segment).

Note that CairoContext::fillExtents() must necessarily do more work to compute the precise inked areas in light of the fill rule, so CairoContext::pathExtents() may be more desirable for sake of performance if the non-inked path extents are desired.

Parameters

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Return Values

An array with the coordinates of the afected area

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • CairoContext::fill() - Fills the current path
  • CairoContext::setFillRule() - The setFillRule purpose
  • CairoContext::fillPreserve() - Fills and preserve the current path


Fills and preserve the current path

  • « CairoContext::fillExtents
  • CairoContext::fontExtents »
  • PHP Manual
  • CairoContext
  • Fills and preserve the current path

CairoContext::fillPreserve

cairo_fill_preserve

(PECL cairo >= 0.1.0)

CairoContext::fillPreserve -- cairo_fill_preserve — Fills and preserve the current path

Description

Object oriented style (method):

public CairoContext::fillPreserve ( void ) : void

Procedural style:

cairo_fill_preserve ( CairoContext $context ) : void

A drawing operator that fills the current path according to the current CairoFillRule, (each sub-path is implicitly closed before being filled). Unlike CairoContext::fill(), CairoContext::fillPreserve() (Procedural cairo_fill(), cairo_fill_preserve(), respectively) preserves the path within the Context.

Parameters

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • CairoContext::setFillRule() - The setFillRule purpose
  • CairoContext::fill() - Fills the current path


Get the font extents

  • « CairoContext::fillPreserve
  • CairoContext::getAntialias »
  • PHP Manual
  • CairoContext
  • Get the font extents

CairoContext::fontExtents

cairo_font_extents

(PECL cairo >= 0.1.0)

CairoContext::fontExtents -- cairo_font_extents — Get the font extents

Description

Object oriented style (method):

public CairoContext::fontExtents ( void ) : array

Procedural style:

cairo_font_extents ( CairoContext $context ) : array

Gets the font extents for the currently selected font.

Parameters

context

Description...

Return Values

An array containing the font extents for the current font.

Examples

Example #1 Object oriented style

<?php

$sur = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);
$con = new CairoContext($sur);

var_dump($con->fontExtents());

?>

The above example will output something similar to:

array(5) {
  ["ascent"]=>
  float(10)
  ["descent"]=>
  float(3)
  ["height"]=>
  float(13.3125)
  ["max_x_advance"]=>
  float(26.65625)
  ["max_y_advance"]=>
  float(0)
}

Example #2 Procedural style

<?php

$sur = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);
$con = cairo_create($sur);

var_dump(cairo_font_extents($con));

?>

The above example will output something similar to:

array(5) {
  ["ascent"]=>
  float(10)
  ["descent"]=>
  float(3)
  ["height"]=>
  float(13.3125)
  ["max_x_advance"]=>
  float(26.65625)
  ["max_y_advance"]=>
  float(0)
}

See Also

  • Classname::Method()


Retrieves the current antialias mode

  • « CairoContext::fontExtents
  • CairoContext::getCurrentPoint »
  • PHP Manual
  • CairoContext
  • Retrieves the current antialias mode

CairoContext::getAntialias

cairo_get_antialias

(PECL cairo >= 0.1.0)

CairoContext::getAntialias -- cairo_get_antialias — Retrieves the current antialias mode

Description

Object oriented style (method):

public CairoContext::getAntialias ( void ) : int

Procedural style:

cairo_get_antialias ( CairoContext $context ) : int

Returns the current CairoAntialias mode, as set by CairoContext::setAntialias().

Parameters

context

A valid CairoContext object created with CairoContext::__construct() or cairo_create()

Return Values

The current CairoAntialias mode.

Examples

Example #1 Object oriented style

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);
$context = new CairoContext($surface);

$context->setAntialias(CairoAntialias::MODE_SUBPIXEL);

var_dump($context->getAntialias());

?>

The above example will output something similar to:

int(3)

Example #2 Procedural style

<?php

$sur = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 50, 50);
$con = cairo_create($sur);

cairo_set_antialias($con, CAIRO_ANTIALIAS_SUBPIXEL);

var_dump(cairo_get_antialias($con));

?>

The above example will output something similar to:

int(3)

See Also

  • CairoContext::setAntialias() - The setAntialias purpose
  • CairoAntialias


The getCurrentPoint purpose

  • « CairoContext::getAntialias
  • CairoContext::getDash »
  • PHP Manual
  • CairoContext
  • The getCurrentPoint purpose

CairoContext::getCurrentPoint

cairo_get_current_point

(PECL cairo >= 0.1.0)

CairoContext::getCurrentPoint -- cairo_get_current_point — The getCurrentPoint purpose

Description

Object oriented style

public CairoContext::getCurrentPoint ( void ) : array

Procedural style

cairo_get_current_point ( CairoContext $context ) : array

Gets the current point of the current path, which is conceptually the final point reached by the path so far.

The current point is returned in the user-space coordinate system. If there is no defined current point or if cr is in an error status, x and y will both be set to 0.0. It is possible to check this in advance with CairoContext::hasCurrentPoint().

Most path construction functions alter the current point. See the following for details on how they affect the current point: CairoContext::newPath(),
CairoContext::newSubPath(), CairoContext::appendPath(), CairoContext::closePath(), CairoContext::moveTo(),
CairoContext::lineTo(), CairoContext::curveTo(), CairoContext::relMoveTo(),
CairoContext::relLineTo(), CairoContext::relCurveTo(),
CairoContext::arc(), CairoContext::arcNegative(), CairoContext::rectangle(),
CairoContext::textPath(), CairoContext::glyphPath().

Some functions use and alter the current point but do not otherwise change current path: CairoContext::showText().

Some functions unset the current path and as a result, current point: CairoContext::fill(), CairoContext::stroke().

Parameters

context

A valid CairoContext object.

Return Values

An array containing the x (index 0) and y (index 1) coordinates of the current point.

Examples

Example #1 Object oriented style

<?php

$s = new CairoImageSurface(CairoFormat::ARGB32, 100, 100);
$c = new CairoContext($s);

$c->moveTo(10, 10);

var_dump($c->getCurrentPoint());

?>

The above example will output something similar to:

array(2) {
  [0]=>
  float(10)
  [1]=>
  float(10)
}

Example #2 Procedural style

<?php

$s = cairo_image_surface_create(CAIRO_SURFACE_TYPE_IMAGE, 100, 100);
$c = cairo_create($s);

cairo_move_to($c, 10, 10);

var_dump(cairo_get_current_point($c));

?>

The above example will output something similar to:

array(2) {
  [0]=>
  float(10)
  [1]=>
  float(10)
}

See Also

  • CairoContext::moveTo() - The moveTo purpose
  • CairoContext::hasCurrentPoint() - The hasCurrentPoint purpose


The getDash purpose

  • « CairoContext::getCurrentPoint
  • CairoContext::getDashCount »
  • PHP Manual
  • CairoContext
  • The getDash purpose

CairoContext::getDash

cairo_get_dash

(PECL cairo >= 0.1.0)

CairoContext::getDash -- cairo_get_dash — The getDash purpose

Description

Object oriented style (method):

public CairoContext::getDash ( void ) : array

Procedural style:

cairo_get_dash ( CairoContext $context ) : array

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getDashCount purpose

  • « CairoContext::getDash
  • CairoContext::getFillRule »
  • PHP Manual
  • CairoContext
  • The getDashCount purpose

CairoContext::getDashCount

cairo_get_dash_count

(PECL cairo >= 0.1.0)

CairoContext::getDashCount -- cairo_get_dash_count — The getDashCount purpose

Description

Object oriented style (method):

public CairoContext::getDashCount ( void ) : int

Procedural style:

cairo_get_dash_count ( CairoContext $context ) : int

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getFillRule purpose

  • « CairoContext::getDashCount
  • CairoContext::getFontFace »
  • PHP Manual
  • CairoContext
  • The getFillRule purpose

CairoContext::getFillRule

cairo_get_fill_rule

(PECL cairo >= 0.1.0)

CairoContext::getFillRule -- cairo_get_fill_rule — The getFillRule purpose

Description

Object oriented style (method):

public CairoContext::getFillRule ( void ) : int

Procedural style:

cairo_get_fill_rule ( CairoContext $context ) : int

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getFontFace purpose

  • « CairoContext::getFillRule
  • CairoContext::getFontMatrix »
  • PHP Manual
  • CairoContext
  • The getFontFace purpose

CairoContext::getFontFace

cairo_get_font_face

(PECL cairo >= 0.1.0)

CairoContext::getFontFace -- cairo_get_font_face — The getFontFace purpose

Description

Object oriented style (method):

public CairoContext::getFontFace ( void ) : void

Procedural style:

cairo_get_font_face ( CairoContext $context ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getFontMatrix purpose

  • « CairoContext::getFontFace
  • CairoContext::getFontOptions »
  • PHP Manual
  • CairoContext
  • The getFontMatrix purpose

CairoContext::getFontMatrix

cairo_get_font_matrix

(PECL cairo >= 0.1.0)

CairoContext::getFontMatrix -- cairo_get_font_matrix — The getFontMatrix purpose

Description

Object oriented style (method):

public CairoContext::getFontMatrix ( void ) : void

Procedural style:

cairo_get_font_matrix ( CairoContext $context ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getFontOptions purpose

  • « CairoContext::getFontMatrix
  • CairoContext::getGroupTarget »
  • PHP Manual
  • CairoContext
  • The getFontOptions purpose

CairoContext::getFontOptions

cairo_get_font_options

(PECL cairo >= 0.1.0)

CairoContext::getFontOptions -- cairo_get_font_options — The getFontOptions purpose

Description

Object oriented style (method):

public CairoContext::getFontOptions ( void ) : void

Procedural style:

cairo_get_font_options ( CairoContext $context ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getGroupTarget purpose

  • « CairoContext::getFontOptions
  • CairoContext::getLineCap »
  • PHP Manual
  • CairoContext
  • The getGroupTarget purpose

CairoContext::getGroupTarget

cairo_get_group_target

(PECL cairo >= 0.1.0)

CairoContext::getGroupTarget -- cairo_get_group_target — The getGroupTarget purpose

Description

Object oriented style (method):

public CairoContext::getGroupTarget ( void ) : void

Procedural style:

cairo_get_group_target ( CairoContext $context ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getLineCap purpose

  • « CairoContext::getGroupTarget
  • CairoContext::getLineJoin »
  • PHP Manual
  • CairoContext
  • The getLineCap purpose

CairoContext::getLineCap

cairo_get_line_cap

(PECL cairo >= 0.1.0)

CairoContext::getLineCap -- cairo_get_line_cap — The getLineCap purpose

Description

Object oriented style (method):

public CairoContext::getLineCap ( void ) : int

Procedural style:

cairo_get_line_cap ( CairoContext $context ) : int

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getLineJoin purpose

  • « CairoContext::getLineCap
  • CairoContext::getLineWidth »
  • PHP Manual
  • CairoContext
  • The getLineJoin purpose

CairoContext::getLineJoin

cairo_get_line_join

(PECL cairo >= 0.1.0)

CairoContext::getLineJoin -- cairo_get_line_join — The getLineJoin purpose

Description

Object oriented style (method):

public CairoContext::getLineJoin ( void ) : int

Procedural style:

cairo_get_line_join ( CairoContext $context ) : int

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getLineWidth purpose

  • « CairoContext::getLineJoin
  • CairoContext::getMatrix »
  • PHP Manual
  • CairoContext
  • The getLineWidth purpose

CairoContext::getLineWidth

cairo_get_line_width

(PECL cairo >= 0.1.0)

CairoContext::getLineWidth -- cairo_get_line_width — The getLineWidth purpose

Description

Object oriented style (method):

public CairoContext::getLineWidth ( void ) : float

Procedural style:

cairo_get_line_width ( CairoContext $context ) : float

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getMatrix purpose

  • « CairoContext::getLineWidth
  • CairoContext::getMiterLimit »
  • PHP Manual
  • CairoContext
  • The getMatrix purpose

CairoContext::getMatrix

cairo_get_matrix

(PECL cairo >= 0.1.0)

CairoContext::getMatrix -- cairo_get_matrix — The getMatrix purpose

Description

Object oriented style (method):

public CairoContext::getMatrix ( void ) : void

Procedural style:

cairo_get_matrix ( CairoContext $context ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getMiterLimit purpose

  • « CairoContext::getMatrix
  • CairoContext::getOperator »
  • PHP Manual
  • CairoContext
  • The getMiterLimit purpose

CairoContext::getMiterLimit

cairo_get_miter_limit

(PECL cairo >= 0.1.0)

CairoContext::getMiterLimit -- cairo_get_miter_limit — The getMiterLimit purpose

Description

Object oriented style (method):

public CairoContext::getMiterLimit ( void ) : float

Procedural style:

cairo_get_miter_limit ( CairoContext $context ) : float

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getOperator purpose

  • « CairoContext::getMiterLimit
  • CairoContext::getScaledFont »
  • PHP Manual
  • CairoContext
  • The getOperator purpose

CairoContext::getOperator

cairo_get_operator

(PECL cairo >= 0.1.0)

CairoContext::getOperator -- cairo_get_operator — The getOperator purpose

Description

Object oriented style (method):

public CairoContext::getOperator ( void ) : int

Procedural style:

cairo_get_operator ( CairoContext $context ) : int

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getScaledFont purpose

  • « CairoContext::getOperator
  • CairoContext::getSource »
  • PHP Manual
  • CairoContext
  • The getScaledFont purpose

CairoContext::getScaledFont

cairo_get_scaled_font

(PECL cairo >= 0.1.0)

CairoContext::getScaledFont -- cairo_get_scaled_font — The getScaledFont purpose

Description

Object oriented style (method):

public CairoContext::getScaledFont ( void ) : void

Procedural style:

cairo_get_scaled_font ( CairoContext $context ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getSource purpose

  • « CairoContext::getScaledFont
  • CairoContext::getTarget »
  • PHP Manual
  • CairoContext
  • The getSource purpose

CairoContext::getSource

cairo_get_source

(PECL cairo >= 0.1.0)

CairoContext::getSource -- cairo_get_source — The getSource purpose

Description

Object oriented style (method):

public CairoContext::getSource ( void ) : void

Procedural style:

cairo_get_source ( CairoContext $context ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getTarget purpose

  • « CairoContext::getSource
  • CairoContext::getTolerance »
  • PHP Manual
  • CairoContext
  • The getTarget purpose

CairoContext::getTarget

cairo_get_target

(PECL cairo >= 0.1.0)

CairoContext::getTarget -- cairo_get_target — The getTarget purpose

Description

Object oriented style (method):

public CairoContext::getTarget ( void ) : void

Procedural style:

cairo_get_target ( CairoContext $context ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getTolerance purpose

  • « CairoContext::getTarget
  • CairoContext::glyphPath »
  • PHP Manual
  • CairoContext
  • The getTolerance purpose

CairoContext::getTolerance

cairo_get_tolerance

(PECL cairo >= 0.1.0)

CairoContext::getTolerance -- cairo_get_tolerance — The getTolerance purpose

Description

Object oriented style (method):

public CairoContext::getTolerance ( void ) : float

Procedural style:

cairo_get_tolerance ( CairoContext $context ) : float

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The glyphPath purpose

  • « CairoContext::getTolerance
  • CairoContext::hasCurrentPoint »
  • PHP Manual
  • CairoContext
  • The glyphPath purpose

CairoContext::glyphPath

cairo_glyph_path

(PECL cairo >= 0.1.0)

CairoContext::glyphPath -- cairo_glyph_path — The glyphPath purpose

Description

Object oriented style

public CairoContext::glyphPath ( array $glyphs ) : void

Procedural style

cairo_glyph_path ( CairoContext $context , array $glyphs ) : void

Adds closed paths for the glyphs to the current path. The generated path if filled, achieves an effect similar to that of CairoContext::showGlyphs().

Parameters

context

A CairoContext object

glyphs

Array of glyphs

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...


The hasCurrentPoint purpose

  • « CairoContext::glyphPath
  • CairoContext::identityMatrix »
  • PHP Manual
  • CairoContext
  • The hasCurrentPoint purpose

CairoContext::hasCurrentPoint

cairo_has_current_point

(PECL cairo >= 0.1.0)

CairoContext::hasCurrentPoint -- cairo_has_current_point — The hasCurrentPoint purpose

Description

Object oriented style (method):

public CairoContext::hasCurrentPoint ( void ) : bool

Procedural style:

cairo_has_current_point ( CairoContext $context ) : bool

Returns whether a current point is defined on the current path. See CairoContext::getCurrentPoint() for details on the current point.

Parameters

context

A valid CairoContext object.

Return Values

Whether a current point is defined

Examples

Example #1 Object oriented style

<?php

$s = new CairoImageSurface(CairoFormat::ARGB32, 100, 100);
$c = new CairoContext($s);

var_dump($c->hasCurrentPoint());

$c->moveTo(10, 10);

var_dump($c->hasCurrentPoint());

?>

The above example will output:

bool(false)
bool(true)

Example #2 Procedural style

<?php

$s = cairo_image_surface_create(CAIRO_SURFACE_TYPE_IMAGE, 100, 100);
$c = cairo_create($s);

var_dump(cairo_has_current_point($c));

cairo_move_to($c, 10, 10);

var_dump(cairo_has_current_point($c));

?>

The above example will output:

bool(false)
bool(true)

See Also

  • CairoContext::getCurrentPoint() - The getCurrentPoint purpose


The identityMatrix purpose

  • « CairoContext::hasCurrentPoint
  • CairoContext::inFill »
  • PHP Manual
  • CairoContext
  • The identityMatrix purpose

CairoContext::identityMatrix

cairo_identity_matrix

(PECL cairo >= 0.1.0)

CairoContext::identityMatrix -- cairo_identity_matrix — The identityMatrix purpose

Description

Object oriented style (method):

public CairoContext::identityMatrix ( void ) : void

Procedural style:

cairo_identity_matrix ( CairoContext $context ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The inFill purpose

  • « CairoContext::identityMatrix
  • CairoContext::inStroke »
  • PHP Manual
  • CairoContext
  • The inFill purpose

CairoContext::inFill

cairo_in_fill

(PECL cairo >= 0.1.0)

CairoContext::inFill -- cairo_in_fill — The inFill purpose

Description

Object oriented style (method):

public CairoContext::inFill ( float $x , float $y ) : bool

Procedural style:

cairo_in_fill ( CairoContext $context , float $x , float $y ) : bool

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The inStroke purpose

  • « CairoContext::inFill
  • CairoContext::lineTo »
  • PHP Manual
  • CairoContext
  • The inStroke purpose

CairoContext::inStroke

cairo_in_stroke

(PECL cairo >= 0.1.0)

CairoContext::inStroke -- cairo_in_stroke — The inStroke purpose

Description

Object oriented style (method):

public CairoContext::inStroke ( float $x , float $y ) : bool

Procedural style:

cairo_in_stroke ( CairoContext $context , float $x , float $y ) : bool

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The lineTo purpose

  • « CairoContext::inStroke
  • CairoContext::mask »
  • PHP Manual
  • CairoContext
  • The lineTo purpose

CairoContext::lineTo

cairo_line_to

(PECL cairo >= 0.1.0)

CairoContext::lineTo -- cairo_line_to — The lineTo purpose

Description

Object oriented style (method):

public CairoContext::lineTo ( float $x , float $y ) : void

Procedural style:

cairo_line_to ( CairoContext $context , float $x , float $y ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The mask purpose

  • « CairoContext::lineTo
  • CairoContext::maskSurface »
  • PHP Manual
  • CairoContext
  • The mask purpose

CairoContext::mask

cairo_mask

(PECL cairo >= 0.1.0)

CairoContext::mask -- cairo_mask — The mask purpose

Description

Object oriented style (method):

public CairoContext::mask ( CairoPattern $pattern ) : void

Procedural style:

cairo_mask ( CairoContext $context , CairoPattern $pattern ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

pattern

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The maskSurface purpose

  • « CairoContext::mask
  • CairoContext::moveTo »
  • PHP Manual
  • CairoContext
  • The maskSurface purpose

CairoContext::maskSurface

cairo_mask_surface

(PECL cairo >= 0.1.0)

CairoContext::maskSurface -- cairo_mask_surface — The maskSurface purpose

Description

Object oriented style (method):

public CairoContext::maskSurface ( CairoSurface $surface [, float $x [, float $y ]] ) : void

Procedural style:

cairo_mask_surface ( CairoContext $context , CairoSurface $surface [, float $x [, float $y ]] ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

surface

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The moveTo purpose

  • « CairoContext::maskSurface
  • CairoContext::newPath »
  • PHP Manual
  • CairoContext
  • The moveTo purpose

CairoContext::moveTo

cairo_move_to

(PECL cairo >= 0.1.0)

CairoContext::moveTo -- cairo_move_to — The moveTo purpose

Description

Object oriented style (method):

public CairoContext::moveTo ( float $x , float $y ) : void

Procedural style:

cairo_move_to ( CairoContext $context , float $x , float $y ) : void

Begin a new sub-path. After this call the current point will be (x, y).

Parameters

context

A valid CairoContext object.

x

The x coordinate of the new position.

y

The y coordinate of the new position

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php

$s = new CairoImageSurface(CairoFormat::ARGB32, 100, 100);
$c = new CairoContext($s);

$c->setSourceRgb(0, 0, 0);
$c->paint();

// Move 10 pixels across, and 10 pixels down
$c->moveTo(10, 10);
$c->lineTo(90, 90);
$c->setLineWidth(2);
$c->setSourceRgb(1, 1, 1);
$c->stroke();

// Move 90 pixels across, and 10 pixels down
$c->moveTo(90, 10);
$c->lineTo(10, 90);
$c->setLineWidth(2);
$c->setSourceRgb(1, 1, 1);
$c->stroke();

$s->writeToPng(dirname(__FILE__) . '/CairoContext_moveTo.png');
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php

$s = cairo_image_surface_create(CAIRO_SURFACE_TYPE_IMAGE, 100, 100);
$c = cairo_create($s);

cairo_set_source_rgb($c, 0, 0, 0);
cairo_paint($c);

// Move 10 pixels across, and 10 pixels down
cairo_move_to($c, 10, 10);
cairo_line_to($c, 90, 90);
cairo_set_line_width($c, 2);
cairo_set_source_rgb($c, 1, 1, 1);
cairo_stroke($c);

// Move 90 pixels across, and 10 pixels down
cairo_move_to($c, 90, 10);
cairo_line_to($c, 10, 90);
cairo_set_line_width($c, 2);
cairo_set_source_rgb($c, 1, 1, 1);
cairo_stroke($c);

cairo_surface_write_to_png($s, dirname(__FILE__) . '/cairo_move_to.png');
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The newPath purpose

  • « CairoContext::moveTo
  • CairoContext::newSubPath »
  • PHP Manual
  • CairoContext
  • The newPath purpose

CairoContext::newPath

cairo_new_path

(PECL cairo >= 0.1.0)

CairoContext::newPath -- cairo_new_path — The newPath purpose

Description

Object oriented style (method):

public CairoContext::newPath ( void ) : void

Procedural style:

cairo_new_path ( CairoContext $context ) : void

Clears the current path. After this call there will be no path and no current point.

Parameters

context

A valid CairoContext object.

Return Values

No value is returned.

Examples

Example #1 Object oriented style

<?php
// [...]
CairoContext::newPath();
?>

Example #2 Procedural style

<?php
// [...]
cairo_new_path($context);
?>

See Also

  • CairoContext::appendPath() - Appends a path to current path
  • CairoContext::closePath() - Closes the current path


The newSubPath purpose

  • « CairoContext::newPath
  • CairoContext::paint »
  • PHP Manual
  • CairoContext
  • The newSubPath purpose

CairoContext::newSubPath

cairo_new_sub_path

(PECL cairo >= 0.1.0)

CairoContext::newSubPath -- cairo_new_sub_path — The newSubPath purpose

Description

Object oriented style (method):

public CairoContext::newSubPath ( void ) : void

Procedural style:

cairo_new_sub_path ( CairoContext $context ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The paint purpose

  • « CairoContext::newSubPath
  • CairoContext::paintWithAlpha »
  • PHP Manual
  • CairoContext
  • The paint purpose

CairoContext::paint

cairo_paint

(PECL cairo >= 0.1.0)

CairoContext::paint -- cairo_paint — The paint purpose

Description

Object oriented style (method):

public CairoContext::paint ( void ) : void

Procedural style:

cairo_paint ( CairoContext $context ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The paintWithAlpha purpose

  • « CairoContext::paint
  • CairoContext::pathExtents »
  • PHP Manual
  • CairoContext
  • The paintWithAlpha purpose

CairoContext::paintWithAlpha

cairo_paint_with_alpha

(PECL cairo >= 0.1.0)

CairoContext::paintWithAlpha -- cairo_paint_with_alpha — The paintWithAlpha purpose

Description

Object oriented style (method):

public CairoContext::paintWithAlpha ( float $alpha ) : void

Procedural style:

cairo_paint_with_alpha ( CairoContext $context , float $alpha ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

alpha

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The pathExtents purpose

  • « CairoContext::paintWithAlpha
  • CairoContext::popGroup »
  • PHP Manual
  • CairoContext
  • The pathExtents purpose

CairoContext::pathExtents

cairo_path_extents

(PECL cairo >= 0.1.0)

CairoContext::pathExtents -- cairo_path_extents — The pathExtents purpose

Description

Object oriented style (method):

public CairoContext::pathExtents ( void ) : array

Procedural style:

cairo_path_extents ( CairoContext $context ) : array

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The popGroup purpose

  • « CairoContext::pathExtents
  • CairoContext::popGroupToSource »
  • PHP Manual
  • CairoContext
  • The popGroup purpose

CairoContext::popGroup

cairo_pop_group

(PECL cairo >= 0.1.0)

CairoContext::popGroup -- cairo_pop_group — The popGroup purpose

Description

Object oriented style (method):

public CairoContext::popGroup ( void ) : void

Procedural style:

cairo_pop_group ( CairoContext $context ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The popGroupToSource purpose

  • « CairoContext::popGroup
  • CairoContext::pushGroup »
  • PHP Manual
  • CairoContext
  • The popGroupToSource purpose

CairoContext::popGroupToSource

cairo_pop_group_to_source

(PECL cairo >= 0.1.0)

CairoContext::popGroupToSource -- cairo_pop_group_to_source — The popGroupToSource purpose

Description

Object oriented style (method):

public CairoContext::popGroupToSource ( void ) : void

Procedural style:

cairo_pop_group_to_source ( CairoContext $context ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The pushGroup purpose

  • « CairoContext::popGroupToSource
  • CairoContext::pushGroupWithContent »
  • PHP Manual
  • CairoContext
  • The pushGroup purpose

CairoContext::pushGroup

cairo_push_group

(PECL cairo >= 0.1.0)

CairoContext::pushGroup -- cairo_push_group — The pushGroup purpose

Description

Object oriented style (method):

public CairoContext::pushGroup ( void ) : void

Procedural style:

cairo_push_group ( CairoContext $context ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The pushGroupWithContent purpose

  • « CairoContext::pushGroup
  • CairoContext::rectangle »
  • PHP Manual
  • CairoContext
  • The pushGroupWithContent purpose

CairoContext::pushGroupWithContent

cairo_push_group_with_content

(PECL cairo >= 0.1.0)

CairoContext::pushGroupWithContent -- cairo_push_group_with_content — The pushGroupWithContent purpose

Description

Object oriented style (method):

public CairoContext::pushGroupWithContent ( int $content ) : void

Procedural style:

cairo_push_group_with_content ( CairoContext $context , int $content ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

content

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The rectangle purpose

  • « CairoContext::pushGroupWithContent
  • CairoContext::relCurveTo »
  • PHP Manual
  • CairoContext
  • The rectangle purpose

CairoContext::rectangle

cairo_rectangle

(PECL cairo >= 0.1.0)

CairoContext::rectangle -- cairo_rectangle — The rectangle purpose

Description

Object oriented style (method):

public CairoContext::rectangle ( float $x , float $y , float $width , float $height ) : void

Procedural style:

cairo_rectangle ( CairoContext $context , float $x , float $y , float $width , float $height ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

width

Description...

height

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The relCurveTo purpose

  • « CairoContext::rectangle
  • CairoContext::relLineTo »
  • PHP Manual
  • CairoContext
  • The relCurveTo purpose

CairoContext::relCurveTo

cairo_rel_curve_to

(PECL cairo >= 0.1.0)

CairoContext::relCurveTo -- cairo_rel_curve_to — The relCurveTo purpose

Description

Object oriented style (method):

public CairoContext::relCurveTo ( float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 ) : void

Procedural style:

cairo_rel_curve_to ( CairoContext $context , float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x1

Description...

y1

Description...

x2

Description...

y2

Description...

x3

Description...

y3

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The relLineTo purpose

  • « CairoContext::relCurveTo
  • CairoContext::relMoveTo »
  • PHP Manual
  • CairoContext
  • The relLineTo purpose

CairoContext::relLineTo

cairo_rel_line_to

(PECL cairo >= 0.1.0)

CairoContext::relLineTo -- cairo_rel_line_to — The relLineTo purpose

Description

Object oriented style (method):

public CairoContext::relLineTo ( float $x , float $y ) : void

Procedural style:

cairo_rel_line_to ( CairoContext $context , float $x , float $y ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The relMoveTo purpose

  • « CairoContext::relLineTo
  • CairoContext::resetClip »
  • PHP Manual
  • CairoContext
  • The relMoveTo purpose

CairoContext::relMoveTo

cairo_rel_move_to

(PECL cairo >= 0.1.0)

CairoContext::relMoveTo -- cairo_rel_move_to — The relMoveTo purpose

Description

Object oriented style (method):

public CairoContext::relMoveTo ( float $x , float $y ) : void

Procedural style:

cairo_rel_move_to ( CairoContext $context , float $x , float $y ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The resetClip purpose

  • « CairoContext::relMoveTo
  • CairoContext::restore »
  • PHP Manual
  • CairoContext
  • The resetClip purpose

CairoContext::resetClip

cairo_reset_clip

(PECL cairo >= 0.1.0)

CairoContext::resetClip -- cairo_reset_clip — The resetClip purpose

Description

Object oriented style (method):

public CairoContext::resetClip ( void ) : void

Procedural style:

cairo_reset_clip ( CairoContext $context ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The restore purpose

  • « CairoContext::resetClip
  • CairoContext::rotate »
  • PHP Manual
  • CairoContext
  • The restore purpose

CairoContext::restore

cairo_restore

(PECL cairo >= 0.1.0)

CairoContext::restore -- cairo_restore — The restore purpose

Description

Object oriented style (method):

public CairoContext::restore ( void ) : void

Procedural style:

cairo_restore ( CairoContext $context ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The rotate purpose

  • « CairoContext::restore
  • CairoContext::save »
  • PHP Manual
  • CairoContext
  • The rotate purpose

CairoContext::rotate

cairo_rotate

(PECL cairo >= 0.1.0)

CairoContext::rotate -- cairo_rotate — The rotate purpose

Description

Object oriented style (method):

public CairoContext::rotate ( float $angle ) : void

Procedural style:

cairo_rotate ( CairoContext $context , float $angle ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

angle

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The save purpose

  • « CairoContext::rotate
  • CairoContext::scale »
  • PHP Manual
  • CairoContext
  • The save purpose

CairoContext::save

cairo_save

(PECL cairo >= 0.1.0)

CairoContext::save -- cairo_save — The save purpose

Description

Object oriented style (method):

public CairoContext::save ( void ) : void

Procedural style:

cairo_save ( CairoContext $context ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The scale purpose

  • « CairoContext::save
  • CairoContext::selectFontFace »
  • PHP Manual
  • CairoContext
  • The scale purpose

CairoContext::scale

cairo_scale

(PECL cairo >= 0.1.0)

CairoContext::scale -- cairo_scale — The scale purpose

Description

Object oriented style (method):

public CairoContext::scale ( float $x , float $y ) : void

Procedural style:

cairo_scale ( CairoContext $context , float $x , float $y ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The selectFontFace purpose

  • « CairoContext::scale
  • CairoContext::setAntialias »
  • PHP Manual
  • CairoContext
  • The selectFontFace purpose

CairoContext::selectFontFace

cairo_select_font_face

(PECL cairo >= 0.1.0)

CairoContext::selectFontFace -- cairo_select_font_face — The selectFontFace purpose

Description

Object oriented style (method):

public CairoContext::selectFontFace ( string $family [, int $slant [, int $weight ]] ) : void

Procedural style:

cairo_select_font_face ( CairoContext $context , string $family [, int $slant [, int $weight ]] ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

family

Description...

slant

Description...

weight

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The setAntialias purpose

  • « CairoContext::selectFontFace
  • CairoContext::setDash »
  • PHP Manual
  • CairoContext
  • The setAntialias purpose

CairoContext::setAntialias

cairo_set_antialias

(PECL cairo >= 0.1.0)

CairoContext::setAntialias -- cairo_set_antialias — The setAntialias purpose

Description

Object oriented style (method):

public CairoContext::setAntialias ([ int $antialias ] ) : void

Procedural style:

cairo_set_antialias ( CairoContext $context [, int $antialias ] ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

antialias

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The setDash purpose

  • « CairoContext::setAntialias
  • CairoContext::setFillRule »
  • PHP Manual
  • CairoContext
  • The setDash purpose

CairoContext::setDash

cairo_set_dash

(PECL cairo >= 0.1.0)

CairoContext::setDash -- cairo_set_dash — The setDash purpose

Description

Object oriented style (method):

public CairoContext::setDash ( array $dashes [, float $offset ] ) : void

Procedural style:

cairo_set_dash ( CairoContext $context , array $dashes [, float $offset ] ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

dashes

Description...

offset

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The setFillRule purpose

  • « CairoContext::setDash
  • CairoContext::setFontFace »
  • PHP Manual
  • CairoContext
  • The setFillRule purpose

CairoContext::setFillRule

cairo_set_fill_rule

(PECL cairo >= 0.1.0)

CairoContext::setFillRule -- cairo_set_fill_rule — The setFillRule purpose

Description

Object oriented style (method):

public CairoContext::setFillRule ( int $setting ) : void

Procedural style:

cairo_set_fill_rule ( CairoContext $context , int $setting ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

setting

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The setFontFace purpose

  • « CairoContext::setFillRule
  • CairoContext::setFontMatrix »
  • PHP Manual
  • CairoContext
  • The setFontFace purpose

CairoContext::setFontFace

cairo_set_font_face

(PECL cairo >= 0.1.0)

CairoContext::setFontFace -- cairo_set_font_face — The setFontFace purpose

Description

Object oriented style (method):

public CairoContext::setFontFace ( CairoFontFace $fontface ) : void

Procedural style:

cairo_set_font_face ( CairoContext $context , CairoFontFace $fontface ) : void

Sets the font-face for a given context.

Parameters

context

A CairoContext object to change the font-face for.

fontface

A CairoFontFace object

Return Values

No value is returned

Examples

Example #1 Object oriented style

<?php
// New surface with white background
$s = new CairoImageSurface(CairoFormat::ARGB32, 300, 100);
$c = new CairoContext($s);
$c->setSourceRgb(1, 1, 1);
$c->paint();

// Draw some text
$c->setSourceRgb(0, 0, 0);
$c->moveTo(10, 60);
// Create a new font face
$f = new CairoToyFontFace("sans-serif", CairoFontSlant::NORMAL, CairoFontWeight::NORMAL);
$c->setFontFace($f);
$c->setFontSize(30);
$c->showText('Hello, World!');
$s->writeToPng(dirname(__FILE__) . '/setFontFace.png');
?>

Example #2 Procedural style

<?php
/* ... */
?>

See Also

  • CairoContext::setFontSize() - The setFontSize purpose
  • CairoContext::showText() - The showText purpose


The setFontMatrix purpose

  • « CairoContext::setFontFace
  • CairoContext::setFontOptions »
  • PHP Manual
  • CairoContext
  • The setFontMatrix purpose

CairoContext::setFontMatrix

cairo_set_font_matrix

(PECL cairo >= 0.1.0)

CairoContext::setFontMatrix -- cairo_set_font_matrix — The setFontMatrix purpose

Description

Object oriented style (method):

public CairoContext::setFontMatrix ( CairoMatrix $matrix ) : void

Procedural style:

cairo_set_font_matrix ( CairoContext $context , CairoMatrix $matrix ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

matrix

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The setFontOptions purpose

  • « CairoContext::setFontMatrix
  • CairoContext::setFontSize »
  • PHP Manual
  • CairoContext
  • The setFontOptions purpose

CairoContext::setFontOptions

cairo_set_font_options

(PECL cairo >= 0.1.0)

CairoContext::setFontOptions -- cairo_set_font_options — The setFontOptions purpose

Description

Object oriented style (method):

public CairoContext::setFontOptions ( CairoFontOptions $fontoptions ) : void

Procedural style:

cairo_set_font_options ( CairoContext $context , CairoFontOptions $fontoptions ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

fontoptions

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The setFontSize purpose

  • « CairoContext::setFontOptions
  • CairoContext::setLineCap »
  • PHP Manual
  • CairoContext
  • The setFontSize purpose

CairoContext::setFontSize

cairo_set_font_size

(PECL cairo >= 0.1.0)

CairoContext::setFontSize -- cairo_set_font_size — The setFontSize purpose

Description

Object oriented style (method):

public CairoContext::setFontSize ( float $size ) : void

Procedural style:

cairo_set_font_size ( CairoContext $context , float $size ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

size

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The setLineCap purpose

  • « CairoContext::setFontSize
  • CairoContext::setLineJoin »
  • PHP Manual
  • CairoContext
  • The setLineCap purpose

CairoContext::setLineCap

cairo_set_line_cap

(PECL cairo >= 0.1.0)

CairoContext::setLineCap -- cairo_set_line_cap — The setLineCap purpose

Description

Object oriented style (method):

public CairoContext::setLineCap ( int $setting ) : void

Procedural style:

cairo_set_line_cap ( CairoContext $context , int $setting ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

setting

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The setLineJoin purpose

  • « CairoContext::setLineCap
  • CairoContext::setLineWidth »
  • PHP Manual
  • CairoContext
  • The setLineJoin purpose

CairoContext::setLineJoin

cairo_set_line_join

(PECL cairo >= 0.1.0)

CairoContext::setLineJoin -- cairo_set_line_join — The setLineJoin purpose

Description

Object oriented style (method):

public CairoContext::setLineJoin ( int $setting ) : void

Procedural style:

cairo_set_line_join ( CairoContext $context , int $setting ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

setting

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The setLineWidth purpose

  • « CairoContext::setLineJoin
  • CairoContext::setMatrix »
  • PHP Manual
  • CairoContext
  • The setLineWidth purpose

CairoContext::setLineWidth

cairo_set_line_width

(PECL cairo >= 0.1.0)

CairoContext::setLineWidth -- cairo_set_line_width — The setLineWidth purpose

Description

Object oriented style (method):

public CairoContext::setLineWidth ( float $width ) : void

Procedural style:

cairo_set_line_width ( CairoContext $context , float $width ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

width

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The setMatrix purpose

  • « CairoContext::setLineWidth
  • CairoContext::setMiterLimit »
  • PHP Manual
  • CairoContext
  • The setMatrix purpose

CairoContext::setMatrix

cairo_set_matrix

(PECL cairo >= 0.1.0)

CairoContext::setMatrix -- cairo_set_matrix — The setMatrix purpose

Description

Object oriented style (method):

public CairoContext::setMatrix ( CairoMatrix $matrix ) : void

Procedural style:

cairo_set_matrix ( CairoContext $context , CairoMatrix $matrix ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

matrix

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The setMiterLimit purpose

  • « CairoContext::setMatrix
  • CairoContext::setOperator »
  • PHP Manual
  • CairoContext
  • The setMiterLimit purpose

CairoContext::setMiterLimit

cairo_set_miter_limit

(PECL cairo >= 0.1.0)

CairoContext::setMiterLimit -- cairo_set_miter_limit — The setMiterLimit purpose

Description

Object oriented style (method):

public CairoContext::setMiterLimit ( float $limit ) : void

Procedural style:

cairo_set_miter_limit ( CairoContext $context , float $limit ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

limit

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The setOperator purpose

  • « CairoContext::setMiterLimit
  • CairoContext::setScaledFont »
  • PHP Manual
  • CairoContext
  • The setOperator purpose

CairoContext::setOperator

cairo_set_operator

(PECL cairo >= 0.1.0)

CairoContext::setOperator -- cairo_set_operator — The setOperator purpose

Description

Object oriented style (method):

public CairoContext::setOperator ( int $setting ) : void

Procedural style:

cairo_set_operator ( CairoContext $context , int $setting ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

setting

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The setScaledFont purpose

  • « CairoContext::setOperator
  • CairoContext::setSource »
  • PHP Manual
  • CairoContext
  • The setScaledFont purpose

CairoContext::setScaledFont

cairo_set_scaled_font

(PECL cairo >= 0.1.0)

CairoContext::setScaledFont -- cairo_set_scaled_font — The setScaledFont purpose

Description

Object oriented style (method):

public CairoContext::setScaledFont ( CairoScaledFont $scaledfont ) : void

Procedural style:

cairo_set_scaled_font ( CairoContext $context , CairoScaledFont $scaledfont ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

scaledfont

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The setSource purpose

  • « CairoContext::setScaledFont
  • CairoContext::setSourceRGB »
  • PHP Manual
  • CairoContext
  • The setSource purpose

CairoContext::setSource

cairo_set_source

(PECL cairo >= 0.1.0)

CairoContext::setSource -- cairo_set_source — The setSource purpose

Description

Object oriented style (method):

public CairoContext::setSource ( CairoPattern $pattern ) : void

Procedural style:

cairo_set_source ( CairoContext $context , CairoPattern $pattern ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

pattern

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The setSourceRGB purpose

  • « CairoContext::setSource
  • CairoContext::setSourceRGBA »
  • PHP Manual
  • CairoContext
  • The setSourceRGB purpose

CairoContext::setSourceRGB

cairo_set_source

(PECL cairo >= 0.1.0)

CairoContext::setSourceRGB -- cairo_set_source — The setSourceRGB purpose

Description

Object oriented style (method):

public CairoContext::setSourceRGB ( float $red , float $green , float $blue ) : void

Procedural style:

cairo_set_source ( CairoContext $context , float $red , float $green , float $blue ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

red

Description...

green

Description...

blue

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The setSourceRGBA purpose

  • « CairoContext::setSourceRGB
  • CairoContext::setSourceSurface »
  • PHP Manual
  • CairoContext
  • The setSourceRGBA purpose

CairoContext::setSourceRGBA

cairo_set_source

(PECL cairo >= 0.1.0)

CairoContext::setSourceRGBA -- cairo_set_source — The setSourceRGBA purpose

Description

Object oriented style (method):

public CairoContext::setSourceRGBA ( float $red , float $green , float $blue , float $alpha ) : void

Procedural style:

cairo_set_source ( CairoContext $context , float $red , float $green , float $blue , float $alpha ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

red

Description...

green

Description...

blue

Description...

alpha

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The setSourceSurface purpose

  • « CairoContext::setSourceRGBA
  • CairoContext::setTolerance »
  • PHP Manual
  • CairoContext
  • The setSourceSurface purpose

CairoContext::setSourceSurface

cairo_set_source_surface

(PECL cairo >= 0.1.0)

CairoContext::setSourceSurface -- cairo_set_source_surface — The setSourceSurface purpose

Description

Object oriented style (method):

public CairoContext::setSourceSurface ( CairoSurface $surface [, float $x [, float $y ]] ) : void

Procedural style:

cairo_set_source_surface ( CairoContext $context , CairoSurface $surface [, float $x [, float $y ]] ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

surface

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The setTolerance purpose

  • « CairoContext::setSourceSurface
  • CairoContext::showPage »
  • PHP Manual
  • CairoContext
  • The setTolerance purpose

CairoContext::setTolerance

cairo_set_tolerance

(PECL cairo >= 0.1.0)

CairoContext::setTolerance -- cairo_set_tolerance — The setTolerance purpose

Description

Object oriented style (method):

public CairoContext::setTolerance ( float $tolerance ) : void

Procedural style:

cairo_set_tolerance ( CairoContext $context , float $tolerance ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

tolerance

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The showPage purpose

  • « CairoContext::setTolerance
  • CairoContext::showText »
  • PHP Manual
  • CairoContext
  • The showPage purpose

CairoContext::showPage

cairo_show_page

(PECL cairo >= 0.1.0)

CairoContext::showPage -- cairo_show_page — The showPage purpose

Description

Object oriented style (method):

public CairoContext::showPage ( void ) : void

Procedural style:

cairo_show_page ( CairoContext $context ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The showText purpose

  • « CairoContext::showPage
  • CairoContext::status »
  • PHP Manual
  • CairoContext
  • The showText purpose

CairoContext::showText

cairo_show_text

(PECL cairo >= 0.1.0)

CairoContext::showText -- cairo_show_text — The showText purpose

Description

Object oriented style (method):

public CairoContext::showText ( string $text ) : void

Procedural style:

cairo_show_text ( CairoContext $context , string $text ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

text

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The status purpose

  • « CairoContext::showText
  • CairoContext::stroke »
  • PHP Manual
  • CairoContext
  • The status purpose

CairoContext::status

cairo_status

(PECL cairo >= 0.1.0)

CairoContext::status -- cairo_status — The status purpose

Description

Object oriented style (method):

public CairoContext::status ( void ) : int

Procedural style:

cairo_status ( CairoContext $context ) : int

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The stroke purpose

  • « CairoContext::status
  • CairoContext::strokeExtents »
  • PHP Manual
  • CairoContext
  • The stroke purpose

CairoContext::stroke

cairo_stroke

(PECL cairo >= 0.1.0)

CairoContext::stroke -- cairo_stroke — The stroke purpose

Description

Object oriented style (method):

public CairoContext::stroke ( void ) : void

Procedural style:

cairo_stroke ( CairoContext $context ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The strokeExtents purpose

  • « CairoContext::stroke
  • CairoContext::strokePreserve »
  • PHP Manual
  • CairoContext
  • The strokeExtents purpose

CairoContext::strokeExtents

cairo_stroke_extents

(PECL cairo >= 0.1.0)

CairoContext::strokeExtents -- cairo_stroke_extents — The strokeExtents purpose

Description

Object oriented style (method):

public CairoContext::strokeExtents ( void ) : array

Procedural style:

cairo_stroke_extents ( CairoContext $context ) : array

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The strokePreserve purpose

  • « CairoContext::strokeExtents
  • CairoContext::textExtents »
  • PHP Manual
  • CairoContext
  • The strokePreserve purpose

CairoContext::strokePreserve

cairo_stroke_preserve

(PECL cairo >= 0.1.0)

CairoContext::strokePreserve -- cairo_stroke_preserve — The strokePreserve purpose

Description

Object oriented style (method):

public CairoContext::strokePreserve ( void ) : void

Procedural style:

cairo_stroke_preserve ( CairoContext $context ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The textExtents purpose

  • « CairoContext::strokePreserve
  • CairoContext::textPath »
  • PHP Manual
  • CairoContext
  • The textExtents purpose

CairoContext::textExtents

cairo_text_extents

(PECL cairo >= 0.1.0)

CairoContext::textExtents -- cairo_text_extents — The textExtents purpose

Description

Object oriented style (method):

public CairoContext::textExtents ( string $text ) : array

Procedural style:

cairo_text_extents ( CairoContext $context ) : array

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

text

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The textPath purpose

  • « CairoContext::textExtents
  • CairoContext::transform »
  • PHP Manual
  • CairoContext
  • The textPath purpose

CairoContext::textPath

cairo_text_path

(PECL cairo >= 0.1.0)

CairoContext::textPath -- cairo_text_path — The textPath purpose

Description

Object oriented style

public CairoContext::textPath ( string $string ) : void

Procedural style

cairo_text_path ( CairoContext $context , string $text ) : void

Adds closed paths for text to the current path. The generated path, if filled, achieves an effect similar to that of CairoContext::showText().

Text conversion and positioning is done similar to CairoContext::showText().

Like CairoContext::showText(), after this call the current point is moved to the origin of where the next glyph would be placed in this same progression. That is, the current point will be at the origin of the final glyph offset by its advance values. This allows for chaining multiple calls to CairoContext::showText() without having to set current point in between.

Note: The CairoContext::textPath() function call is part of what the cairo designers call the "toy" text API. It is convenient for short demos and simple programs, but it is not expected to be adequate for serious text-using applications. See CairoContext::glyphPath() for the "real" text path API in cairo.

Parameters

context

A CairoContext object

text

Description...

string

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The transform purpose

  • « CairoContext::textPath
  • CairoContext::translate »
  • PHP Manual
  • CairoContext
  • The transform purpose

CairoContext::transform

cairo_transform

(PECL cairo >= 0.1.0)

CairoContext::transform -- cairo_transform — The transform purpose

Description

Object oriented style (method):

public CairoContext::transform ( CairoMatrix $matrix ) : void

Procedural style:

cairo_transform ( CairoContext $context , CairoMatrix $matrix ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

matrix

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The translate purpose

  • « CairoContext::transform
  • CairoContext::userToDevice »
  • PHP Manual
  • CairoContext
  • The translate purpose

CairoContext::translate

cairo_translate

(PECL cairo >= 0.1.0)

CairoContext::translate -- cairo_translate — The translate purpose

Description

Object oriented style (method):

public CairoContext::translate ( float $x , float $y ) : void

Procedural style:

cairo_translate ( CairoContext $context , float $x , float $y ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The userToDevice purpose

  • « CairoContext::translate
  • CairoContext::userToDeviceDistance »
  • PHP Manual
  • CairoContext
  • The userToDevice purpose

CairoContext::userToDevice

cairo_user_to_device

(PECL cairo >= 0.1.0)

CairoContext::userToDevice -- cairo_user_to_device — The userToDevice purpose

Description

Object oriented style (method):

public CairoContext::userToDevice ( float $x , float $y ) : array

Procedural style:

cairo_user_to_device ( CairoContext $context , float $x , float $y ) : array

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The userToDeviceDistance purpose

  • « CairoContext::userToDevice
  • CairoException »
  • PHP Manual
  • CairoContext
  • The userToDeviceDistance purpose

CairoContext::userToDeviceDistance

cairo_user_to_device_distance

(PECL cairo >= 0.1.0)

CairoContext::userToDeviceDistance -- cairo_user_to_device_distance — The userToDeviceDistance purpose

Description

Object oriented style (method):

public CairoContext::userToDeviceDistance ( float $x , float $y ) : array

Procedural style:

cairo_user_to_device_distance ( CairoContext $context , float $x , float $y ) : array

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The CairoException class

(PECL cairo >= 0.1.0)

Introduction

Exception class thrown by Cairo functions and methods

Class synopsis

CairoException extends Exception {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The CairoStatus class

(No version information available, might only be in Git)

Introduction

CairoStatus is used to indicate errors that can occur when using Cairo. In some cases it is returned directly by functions. but when using CairoContext, the last error, if any, is stored in the object and can be retrieved with CairoContext::status() or cairo_status(). New entries may be added in future versions.

Use Cairo::statusToString() or cairo_status_to_string() to get a human-readable representation of an error message.

Class synopsis

CairoStatus {
/* Constants */
const integer SUCCESS = 0 ;
const integer NO_MEMORY = 1 ;
const integer INVALID_RESTORE = 2 ;
const integer INVALID_POP_GROUP = 3 ;
const integer NO_CURRENT_POINT = 4 ;
const integer INVALID_MATRIX = 5 ;
const integer INVALID_STATUS = 6 ;
const integer NULL_POINTER = 7 ;
const integer INVALID_STRING = 8 ;
const integer INVALID_PATH_DATA = 9 ;
const integer READ_ERROR = 10 ;
const integer WRITE_ERROR = 11 ;
const integer SURFACE_FINISHED = 12 ;
const integer SURFACE_TYPE_MISMATCH = 13 ;
const integer PATTERN_TYPE_MISMATCH = 14 ;
const integer INVALID_CONTENT = 15 ;
const integer INVALID_FORMAT = 16 ;
const integer INVALID_VISUAL = 17 ;
const integer FILE_NOT_FOUND = 18 ;
const integer INVALID_DASH = 19 ;
const integer INVALID_DSC_COMMENT = 20 ;
const integer INVALID_INDEX = 21 ;
const integer CLIP_NOT_REPRESENTABLE = 22 ;
const integer TEMP_FILE_ERROR = 23 ;
const integer INVALID_STRIDE = 24 ;
}

Predefined Constants

CairoStatus::SUCCESS

No error has occurred

CairoStatus::NO_MEMORY

Out of memory

CairoStatus::INVALID_RESTORE

cairo_restore() called without matching cairo_save()

CairoStatus::INVALID_POP_GROUP

No saved group to pop

CairoStatus::NO_CURRENT_POINT

No current point defined

CairoStatus::INVALID_MATRIX

Invalid matrix (not invertible)

CairoStatus::INVALID_STATUS

Invalid value for an input CairoStatus>

CairoStatus::NULL_POINTER

Null pointer

CairoStatus::INVALID_STRING

Input string not valid UTF-8 string

CairoStatus::INVALID_PATH_DATA

Input path data not valid

CairoStatus::READ_ERROR

Error while reading from input stream

CairoStatus::WRITE_ERROR

Error while writing to output stream

CairoStatus::SURFACE_FINISHED

Target surface has been finished

CairoStatus::SURFACE_TYPE_MISMATCH

The surface type is not appropriate for the operation

CairoStatus::PATTERN_TYPE_MISMATCH

The pattern type is not appropriate for the operation

CairoStatus::INVALID_CONTENT

Invalid value for an input CairoContent

CairoStatus::INVALID_FORMAT

Invalid value for an input CairoFormat

CairoStatus::INVALID_VISUAL

Invalid value for an input Visual

CairoStatus::FILE_NOT_FOUND

File not found

CairoStatus::INVALID_DASH

Invalid value for a dash setting

CairoStatus::INVALID_DSC_COMMENT

Invalid value for a DSC comment

CairoStatus::INVALID_INDEX

Invalid index passed to getter

CairoStatus::CLIP_NOT_REPRESENTABLE

Clip region not representable in desired format

CairoStatus::TEMP_FILE_ERROR

Error creating or writing to a temporary file

CairoStatus::INVALID_STRIDE

Invalid value for CairoStride


The CairoSurface class

(PECL cairo >= 0.1.0)

Introduction

This is the base-class for all other Surface types. CairoSurface is the abstract type representing all different drawing targets that cairo can render to. The actual drawings are performed using a CairoContext.

Class synopsis

CairoSurface {
/* Methods */
public __construct ( void )
public copyPage ( void ) : void
public createSimilar ( CairoSurface $other , int $content , string $width , string $height ) : void
public finish ( void ) : void
public flush ( void ) : void
public getContent ( void ) : int
public getDeviceOffset ( void ) : array
public getFontOptions ( void ) : void
public getType ( void ) : int
public markDirty ( void ) : void
public markDirtyRectangle ( float $x , float $y , float $width , float $height ) : void
public setDeviceOffset ( float $x , float $y ) : void
public setFallbackResolution ( float $x , float $y ) : void
public showPage ( void ) : void
public status ( void ) : int
public writeToPng ( string $file ) : void
}

Table of Contents

  • CairoSurface::__construct — The __construct purpose
  • CairoSurface::copyPage — The copyPage purpose
  • CairoSurface::createSimilar — The createSimilar purpose
  • CairoSurface::finish — The finish purpose
  • CairoSurface::flush — The flush purpose
  • CairoSurface::getContent — The getContent purpose
  • CairoSurface::getDeviceOffset — The getDeviceOffset purpose
  • CairoSurface::getFontOptions — The getFontOptions purpose
  • CairoSurface::getType — The getType purpose
  • CairoSurface::markDirty — The markDirty purpose
  • CairoSurface::markDirtyRectangle — The markDirtyRectangle purpose
  • CairoSurface::setDeviceOffset — The setDeviceOffset purpose
  • CairoSurface::setFallbackResolution — The setFallbackResolution purpose
  • CairoSurface::showPage — The showPage purpose
  • CairoSurface::status — The status purpose
  • CairoSurface::writeToPng — The writeToPng purpose


The __construct purpose

  • « CairoSurface
  • CairoSurface::copyPage »
  • PHP Manual
  • CairoSurface
  • The __construct purpose

CairoSurface::__construct

(PECL cairo >= 0.1.0)

CairoSurface::__construct — The __construct purpose

Description

public CairoSurface::__construct ( void )

CairoSurface is an abstract type and, as such, should not be instantiated in your PHP scripts.

Parameters

This function has no parameters.

Return Values

No return value

Notes

Note:

If you're using a PHP version before 5.3, you must destroy the CairoContext associated with a CairoSurface after you destroy the CairoSurface. Otherwise, you're left with a Circular-reference memory leak.

See Also

  • CairoImageSurface::__construct() - Creates a new CairoImageSurface


The copyPage purpose

  • « CairoSurface::__construct
  • CairoSurface::createSimilar »
  • PHP Manual
  • CairoSurface
  • The copyPage purpose

CairoSurface::copyPage

cairo_copy_page

(PECL cairo >= 0.1.0)

CairoSurface::copyPage -- cairo_copy_page — The copyPage purpose

Description

Object oriented style (method):

public CairoSurface::copyPage ( void ) : void

Procedural style:

cairo_copy_page ( CairoContext $context ) : void

Emits the current page for backends that support multiple pages, but doesn't clear it, so that the contents of the current page will be retained for the next page. Use CairoSurface::showPage() if you want to get an empty page after the emission.

Parameters

context

A CairoContext object

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The createSimilar purpose

  • « CairoSurface::copyPage
  • CairoSurface::finish »
  • PHP Manual
  • CairoSurface
  • The createSimilar purpose

CairoSurface::createSimilar

(PECL cairo >= 0.1.0)

CairoSurface::createSimilar — The createSimilar purpose

Description

public CairoSurface::createSimilar ( CairoSurface $other , int $content , string $width , string $height ) : void

Create a new surface that is as compatible as possible with an existing surface. For example the new surface will have the same fallback resolution and font options as other. Generally, the new surface will also use the same backend as other, unless that is not possible for some reason. The type of the returned surface may be examined with CairoSurface::getType(). Initially the surface contents are all 0 (transparent if contents have transparency, black otherwise.)

Parameters

other

An existing surface used to select the backend of the new surface

content

The content for the new surface. See the CairoContent class for possible values.

width

Width of the new surface, (in device-space units).

height

Height of the new surface, (in device-space units).

Return Values

A new CairoSurface

Examples

Example #1 CairoSurface::createSimilar() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • CairoContent()


The finish purpose

  • « CairoSurface::createSimilar
  • CairoSurface::flush »
  • PHP Manual
  • CairoSurface
  • The finish purpose

CairoSurface::finish

(PECL cairo >= 0.1.0)

CairoSurface::finish — The finish purpose

Description

public CairoSurface::finish ( void ) : void

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoSurface::finish() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The flush purpose

  • « CairoSurface::finish
  • CairoSurface::getContent »
  • PHP Manual
  • CairoSurface
  • The flush purpose

CairoSurface::flush

(PECL cairo >= 0.1.0)

CairoSurface::flush — The flush purpose

Description

public CairoSurface::flush ( void ) : void

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoSurface::flush() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getContent purpose

  • « CairoSurface::flush
  • CairoSurface::getDeviceOffset »
  • PHP Manual
  • CairoSurface
  • The getContent purpose

CairoSurface::getContent

(PECL cairo >= 0.1.0)

CairoSurface::getContent — The getContent purpose

Description

public CairoSurface::getContent ( void ) : int

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoSurface::getContent() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getDeviceOffset purpose

  • « CairoSurface::getContent
  • CairoSurface::getFontOptions »
  • PHP Manual
  • CairoSurface
  • The getDeviceOffset purpose

CairoSurface::getDeviceOffset

(PECL cairo >= 0.1.0)

CairoSurface::getDeviceOffset — The getDeviceOffset purpose

Description

public CairoSurface::getDeviceOffset ( void ) : array

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoSurface::getDeviceOffset() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getFontOptions purpose

  • « CairoSurface::getDeviceOffset
  • CairoSurface::getType »
  • PHP Manual
  • CairoSurface
  • The getFontOptions purpose

CairoSurface::getFontOptions

cairo_get_font_options

(PECL cairo >= 0.1.0)

CairoSurface::getFontOptions -- cairo_get_font_options — The getFontOptions purpose

Description

Object oriented style (method):

public CairoSurface::getFontOptions ( void ) : void

Procedural style:

cairo_get_font_options ( CairoContext $context ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getType purpose

  • « CairoSurface::getFontOptions
  • CairoSurface::markDirty »
  • PHP Manual
  • CairoSurface
  • The getType purpose

CairoSurface::getType

(PECL cairo >= 0.1.0)

CairoSurface::getType — The getType purpose

Description

public CairoSurface::getType ( void ) : int

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoSurface::getType() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The markDirty purpose

  • « CairoSurface::getType
  • CairoSurface::markDirtyRectangle »
  • PHP Manual
  • CairoSurface
  • The markDirty purpose

CairoSurface::markDirty

(PECL cairo >= 0.1.0)

CairoSurface::markDirty — The markDirty purpose

Description

public CairoSurface::markDirty ( void ) : void

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoSurface::markDirty() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The markDirtyRectangle purpose

  • « CairoSurface::markDirty
  • CairoSurface::setDeviceOffset »
  • PHP Manual
  • CairoSurface
  • The markDirtyRectangle purpose

CairoSurface::markDirtyRectangle

(PECL cairo >= 0.1.0)

CairoSurface::markDirtyRectangle — The markDirtyRectangle purpose

Description

public CairoSurface::markDirtyRectangle ( float $x , float $y , float $width , float $height ) : void

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

x

Description...

y

Description...

width

Description...

height

Description...

Return Values

Description...

Examples

Example #1 CairoSurface::markDirtyRectangle() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The setDeviceOffset purpose

  • « CairoSurface::markDirtyRectangle
  • CairoSurface::setFallbackResolution »
  • PHP Manual
  • CairoSurface
  • The setDeviceOffset purpose

CairoSurface::setDeviceOffset

(PECL cairo >= 0.1.0)

CairoSurface::setDeviceOffset — The setDeviceOffset purpose

Description

public CairoSurface::setDeviceOffset ( float $x , float $y ) : void

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 CairoSurface::setDeviceOffset() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The setFallbackResolution purpose

  • « CairoSurface::setDeviceOffset
  • CairoSurface::showPage »
  • PHP Manual
  • CairoSurface
  • The setFallbackResolution purpose

CairoSurface::setFallbackResolution

(PECL cairo >= 0.1.0)

CairoSurface::setFallbackResolution — The setFallbackResolution purpose

Description

public CairoSurface::setFallbackResolution ( float $x , float $y ) : void

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

x

Description...

y

Description...

Return Values

Description...

Examples

Example #1 CairoSurface::setFallbackResolution() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The showPage purpose

  • « CairoSurface::setFallbackResolution
  • CairoSurface::status »
  • PHP Manual
  • CairoSurface
  • The showPage purpose

CairoSurface::showPage

cairo_show_page

(PECL cairo >= 0.1.0)

CairoSurface::showPage -- cairo_show_page — The showPage purpose

Description

Object oriented style (method):

public CairoSurface::showPage ( void ) : void

Procedural style:

cairo_show_page ( CairoContext $context ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The status purpose

  • « CairoSurface::showPage
  • CairoSurface::writeToPng »
  • PHP Manual
  • CairoSurface
  • The status purpose

CairoSurface::status

cairo_status

(PECL cairo >= 0.1.0)

CairoSurface::status -- cairo_status — The status purpose

Description

Object oriented style (method):

public CairoSurface::status ( void ) : int

Procedural style:

cairo_status ( CairoContext $context ) : int

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The writeToPng purpose

  • « CairoSurface::status
  • CairoSvgSurface »
  • PHP Manual
  • CairoSurface
  • The writeToPng purpose

CairoSurface::writeToPng

(PECL cairo >= 0.1.0)

CairoSurface::writeToPng — The writeToPng purpose

Description

public CairoSurface::writeToPng ( string $file ) : void

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

file

Description...

Return Values

Description...

Examples

Example #1 CairoSurface::writeToPng() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


Svg Surface Backend

(PECL cairo >= 0.1.0)

Introduction

Svg specific surface class, uses the SVG (standard vector graphics) surface backend.

Class synopsis

CairoSvgSurface extends CairoSurface {
/* Methods */
public __construct ( string $file , float $width , float $height )
public static getVersions ( void ) : array
public restrictToVersion ( int $version ) : void
public static versionToString ( int $version ) : string
/* Inherited methods */
public CairoSurface::__construct ( void )
public CairoSurface::copyPage ( void ) : void
public CairoSurface::createSimilar ( CairoSurface $other , int $content , string $width , string $height ) : void
public CairoSurface::finish ( void ) : void
public CairoSurface::flush ( void ) : void
public CairoSurface::getContent ( void ) : int
public CairoSurface::getDeviceOffset ( void ) : array
public CairoSurface::getFontOptions ( void ) : void
public CairoSurface::getType ( void ) : int
public CairoSurface::markDirty ( void ) : void
public CairoSurface::markDirtyRectangle ( float $x , float $y , float $width , float $height ) : void
public CairoSurface::setDeviceOffset ( float $x , float $y ) : void
public CairoSurface::setFallbackResolution ( float $x , float $y ) : void
public CairoSurface::showPage ( void ) : void
public CairoSurface::status ( void ) : int
public CairoSurface::writeToPng ( string $file ) : void
}

Table of Contents

  • CairoSvgSurface::__construct — The __construct purpose
  • CairoSvgSurface::getVersions — Used to retrieve a list of supported SVG versions
  • CairoSvgSurface::restrictToVersion — The restrictToVersion purpose
  • CairoSvgSurface::versionToString — The versionToString purpose


The __construct purpose

  • « CairoSvgSurface
  • CairoSvgSurface::getVersions »
  • PHP Manual
  • CairoSvgSurface
  • The __construct purpose

CairoSvgSurface::__construct

(PECL cairo >= 0.1.0)

CairoSvgSurface::__construct — The __construct purpose

Description

public CairoSvgSurface::__construct ( string $file , float $width , float $height )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

file

Description...

width

Description...

height

Description...

Return Values

Description...

Examples

Example #1 CairoSvgSurface::__construct() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


Used to retrieve a list of supported SVG versions

  • « CairoSvgSurface::__construct
  • CairoSvgSurface::restrictToVersion »
  • PHP Manual
  • CairoSvgSurface
  • Used to retrieve a list of supported SVG versions

CairoSvgSurface::getVersions

cairo_svg_surface_get_versions

(PECL cairo >= 0.1.0)

CairoSvgSurface::getVersions -- cairo_svg_surface_get_versions — Used to retrieve a list of supported SVG versions

Description

Object oriented style (method):

public static CairoSvgSurface::getVersions ( void ) : array

Procedural style:

cairo_svg_get_versions ( void ) : array

Returns a numerically indexed array of currently available CairoSvgVersion constants. In order to retrieve the string values for each item, use CairoSvgSurface::versionToString().

Parameters

This function has no parameters.

Return Values

Returns a numerically indexed array of integer values.

Examples

Example #1 CairoSvgSurface::getVersions() example

<?php
/* Grab our list of versions */
$versions = CairoSvgSurface::getVersions();
var_dump($versions);

/* echo the string name of each version */
foreach($versions as $id) {
    echo CairoSvgSurface::versionToString($id), PHP_EOL;
}
?>

The above example will output something similar to:

array(2) {
  [0]=>
  int(0)
  [1]=>
  int(1)
}
SVG 1.1
SVG 1.2

Example #2 Procedural style

<?php
/* Grab our list of versions */
$versions = cairo_svg_surface_get_versions();
var_dump($versions);

/* echo the string name of each version */
foreach($versions as $id) {
    echo cairo_svg_surface_version_to_string($id), PHP_EOL;
}
?>

The above example will output something similar to:

array(2) {
  [0]=>
  int(0)
  [1]=>
  int(1)
}
SVG 1.1
SVG 1.2

See Also

  • CairoSvgSurface::versionToString() - The versionToString purpose


The restrictToVersion purpose

  • « CairoSvgSurface::getVersions
  • CairoSvgSurface::versionToString »
  • PHP Manual
  • CairoSvgSurface
  • The restrictToVersion purpose

CairoSvgSurface::restrictToVersion

(PECL cairo >= 0.1.0)

CairoSvgSurface::restrictToVersion — The restrictToVersion purpose

Description

public CairoSvgSurface::restrictToVersion ( int $version ) : void

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

version

Description...

Return Values

Description...

Examples

Example #1 CairoSvgSurface::restrictToVersion() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The versionToString purpose

  • « CairoSvgSurface::restrictToVersion
  • CairoImageSurface »
  • PHP Manual
  • CairoSvgSurface
  • The versionToString purpose

CairoSvgSurface::versionToString

(PECL cairo >= 0.1.0)

CairoSvgSurface::versionToString — The versionToString purpose

Description

public static CairoSvgSurface::versionToString ( int $version ) : string

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

version

Description...

Return Values

Description...

Examples

Example #1 CairoSvgSurface::versionToString() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The CairoImageSurface class

(PECL cairo >= 0.1.0)

Introduction

CairoImageSurface provide the ability to render to memory buffers either allocated by cairo or by the calling code. The supported image formats are those defined in CairoFormat.

Class synopsis

CairoImageSurface extends CairoSurface {
/* Methods */
public __construct ( int $format , int $width , int $height )
public static createForData ( string $data , int $format , int $width , int $height ) : void
public static createFromPng ( string $file ) : CairoImageSurface
public getData ( void ) : string
public getFormat ( void ) : int
public getHeight ( void ) : int
public getStride ( void ) : int
public getWidth ( void ) : int
/* Inherited methods */
public CairoSurface::__construct ( void )
public CairoSurface::copyPage ( void ) : void
public CairoSurface::createSimilar ( CairoSurface $other , int $content , string $width , string $height ) : void
public CairoSurface::finish ( void ) : void
public CairoSurface::flush ( void ) : void
public CairoSurface::getContent ( void ) : int
public CairoSurface::getDeviceOffset ( void ) : array
public CairoSurface::getFontOptions ( void ) : void
public CairoSurface::getType ( void ) : int
public CairoSurface::markDirty ( void ) : void
public CairoSurface::markDirtyRectangle ( float $x , float $y , float $width , float $height ) : void
public CairoSurface::setDeviceOffset ( float $x , float $y ) : void
public CairoSurface::setFallbackResolution ( float $x , float $y ) : void
public CairoSurface::showPage ( void ) : void
public CairoSurface::status ( void ) : int
public CairoSurface::writeToPng ( string $file ) : void
}

Table of Contents

  • CairoImageSurface::__construct — Creates a new CairoImageSurface
  • CairoImageSurface::createForData — The createForData purpose
  • CairoImageSurface::createFromPng — Creates a new CairoImageSurface form a png image file
  • CairoImageSurface::getData — Gets the image data as string
  • CairoImageSurface::getFormat — Get the image format
  • CairoImageSurface::getHeight — Retrieves the height of the CairoImageSurface
  • CairoImageSurface::getStride — The getStride purpose
  • CairoImageSurface::getWidth — Retrieves the width of the CairoImageSurface


Creates a new CairoImageSurface

  • « CairoImageSurface
  • CairoImageSurface::createForData »
  • PHP Manual
  • CairoImageSurface
  • Creates a new CairoImageSurface

CairoImageSurface::__construct

(PECL cairo >= 0.1.0)

CairoImageSurface::__construct — Creates a new CairoImageSurface

Description

public CairoImageSurface::__construct ( int $format , int $width , int $height )

Creates a new CairoImageSuface object of type format

Parameters

format

Can be any defined in CairoFormat

width

The width of the image surface

height

The height of the image surface

Return Values

A new CairoImageSurface

Examples

Example #1 CairoImageSurface::__construct() example

<?php

// Creates a image with ARGB32 format of 50 width and 50 height
$surface = new CairoImageSurface(CairoFormat::ARGB32, 50,50);

?>

See Also

  • CairoContext::__construct() - Creates a new CairoContext


The createForData purpose

  • « CairoImageSurface::__construct
  • CairoImageSurface::createFromPng »
  • PHP Manual
  • CairoImageSurface
  • The createForData purpose

CairoImageSurface::createForData

(PECL cairo >= 0.1.0)

CairoImageSurface::createForData — The createForData purpose

Description

public static CairoImageSurface::createForData ( string $data , int $format , int $width , int $height ) : void

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

data

Description...

format

Description...

width

Description...

height

Description...

Return Values

Description...

Examples

Example #1 CairoImageSurface::createForData() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


Creates a new CairoImageSurface form a png image file

  • « CairoImageSurface::createForData
  • CairoImageSurface::getData »
  • PHP Manual
  • CairoImageSurface
  • Creates a new CairoImageSurface form a png image file

CairoImageSurface::createFromPng

(PECL cairo >= 0.1.0)

CairoImageSurface::createFromPng — Creates a new CairoImageSurface form a png image file

Description

public static CairoImageSurface::createFromPng ( string $file ) : CairoImageSurface

Creates a new CairoImageSurface form a png image file

This method should be called static

Parameters

file

Path to PNG image file

Return Values

CairoImageSurface object

Examples

Example #1 CairoImageSurface::createFromPng() example

<?php

$surface = CairoImageSurface::createFromPng('/path/to/image/file.png');

?>

The above example will output something similar to:

...

See Also

  • CairoImageSurface::__construct() - Creates a new CairoImageSurface


Gets the image data as string

  • « CairoImageSurface::createFromPng
  • CairoImageSurface::getFormat »
  • PHP Manual
  • CairoImageSurface
  • Gets the image data as string

CairoImageSurface::getData

(PECL cairo >= 0.1.0)

CairoImageSurface::getData — Gets the image data as string

Description

public CairoImageSurface::getData ( void ) : string

Returns the image data of this surface or NULL if surface is not an image surface, or if CairoContext::finish(), procedural : cairo_surface_finish(), has been called.

Parameters

This function has no parameters.

Return Values

The image data as string

Examples

Example #1 CairoImageSurface::getData() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • CairoImageSurface::getStride() - The getStride purpose


Get the image format

  • « CairoImageSurface::getData
  • CairoImageSurface::getHeight »
  • PHP Manual
  • CairoImageSurface
  • Get the image format

CairoImageSurface::getFormat

(PECL cairo >= 0.1.0)

CairoImageSurface::getFormat — Get the image format

Description

public CairoImageSurface::getFormat ( void ) : int

Retrieves the image format, as one of the CairoFormat defined

Parameters

This function has no parameters.

Return Values

One of the CairoFormat enums

Examples

Example #1 CairoImageSurface::getFormat() example

<?php

$surface = new CairoImageSurface(CairoFormat::ARGB32, 50, 50);

var_dump($surface->getFormat()); // 0

$surface2 = new CairoImageSurface(CairoFormat::A8, 50, 50);

var_dump($surface2->getFormat()); // 2

?>

The above example will output something similar to:

int(0)
int(2)

See Also

  • CairoImageSurface::getHeight() - Retrieves the height of the CairoImageSurface
  • CairoImageSurface::getWidth() - Retrieves the width of the CairoImageSurface


Retrieves the height of the CairoImageSurface

  • « CairoImageSurface::getFormat
  • CairoImageSurface::getStride »
  • PHP Manual
  • CairoImageSurface
  • Retrieves the height of the CairoImageSurface

CairoImageSurface::getHeight

(PECL cairo >= 0.1.0)

CairoImageSurface::getHeight — Retrieves the height of the CairoImageSurface

Description

public CairoImageSurface::getHeight ( void ) : int

This methods returns the CairoImageSurface height.

Parameters

This function has no parameters.

Return Values

CairoImageSurface object height

Examples

Example #1 CairoImageSurface::getHeight() example

<?php
// creates a new image surface
$surface = new CairoImageSurface(CairoFormat::ARGB32, 80, 50);

//gets the height
var_dump($surface->getHeight());

?>

The above example will output something similar to:

int(50)

See Also

  • CairoImageSurface::getWidth() - Retrieves the width of the CairoImageSurface


The getStride purpose

  • « CairoImageSurface::getHeight
  • CairoImageSurface::getWidth »
  • PHP Manual
  • CairoImageSurface
  • The getStride purpose

CairoImageSurface::getStride

(PECL cairo >= 0.1.0)

CairoImageSurface::getStride — The getStride purpose

Description

public CairoImageSurface::getStride ( void ) : int

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoImageSurface::getStride() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


Retrieves the width of the CairoImageSurface

  • « CairoImageSurface::getStride
  • CairoPdfSurface »
  • PHP Manual
  • CairoImageSurface
  • Retrieves the width of the CairoImageSurface

CairoImageSurface::getWidth

(PECL cairo >= 0.1.0)

CairoImageSurface::getWidth — Retrieves the width of the CairoImageSurface

Description

public CairoImageSurface::getWidth ( void ) : int

Gets the width of the CairoImageSurface

Parameters

This function has no parameters.

Return Values

Returns the width of the CairoImageSurface object

Examples

Example #1 CairoImageSurface::getWidth() example

<?php
// creates a new image surface
$surface = new CairoImageSurface(CairoFormat::ARGB32, 80, 50);

//gets the width
var_dump($surface->getWidth());

?>

The above example will output something similar to:

int(80)

See Also

  • CairoImageSurface::getHeight() - Retrieves the height of the CairoImageSurface


The CairoPdfSurface class

(PECL cairo >= 0.1.0)

Introduction

Class synopsis

CairoPdfSurface extends CairoSurface {
/* Methods */
public __construct ( string $file , float $width , float $height )
public setSize ( float $width , float $height ) : void
/* Inherited methods */
public CairoSurface::__construct ( void )
public CairoSurface::copyPage ( void ) : void
public CairoSurface::createSimilar ( CairoSurface $other , int $content , string $width , string $height ) : void
public CairoSurface::finish ( void ) : void
public CairoSurface::flush ( void ) : void
public CairoSurface::getContent ( void ) : int
public CairoSurface::getDeviceOffset ( void ) : array
public CairoSurface::getFontOptions ( void ) : void
public CairoSurface::getType ( void ) : int
public CairoSurface::markDirty ( void ) : void
public CairoSurface::markDirtyRectangle ( float $x , float $y , float $width , float $height ) : void
public CairoSurface::setDeviceOffset ( float $x , float $y ) : void
public CairoSurface::setFallbackResolution ( float $x , float $y ) : void
public CairoSurface::showPage ( void ) : void
public CairoSurface::status ( void ) : int
public CairoSurface::writeToPng ( string $file ) : void
}

Table of Contents

  • CairoPdfSurface::__construct — The __construct purpose
  • CairoPdfSurface::setSize — The setSize purpose


The __construct purpose

  • « CairoPdfSurface
  • CairoPdfSurface::setSize »
  • PHP Manual
  • CairoPdfSurface
  • The __construct purpose

CairoPdfSurface::__construct

(PECL cairo >= 0.1.0)

CairoPdfSurface::__construct — The __construct purpose

Description

public CairoPdfSurface::__construct ( string $file , float $width , float $height )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

file

Description...

width

Description...

height

Description...

Return Values

Description...

Examples

Example #1 CairoPdfSurface::__construct() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The setSize purpose

  • « CairoPdfSurface::__construct
  • CairoPsSurface »
  • PHP Manual
  • CairoPdfSurface
  • The setSize purpose

CairoPdfSurface::setSize

(PECL cairo >= 0.1.0)

CairoPdfSurface::setSize — The setSize purpose

Description

public CairoPdfSurface::setSize ( float $width , float $height ) : void

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

width

Description...

height

Description...

Return Values

Description...

Examples

Example #1 CairoPdfSurface::setSize() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The CairoPsSurface class

(PECL cairo >= 0.1.0)

Introduction

Class synopsis

CairoPsSurface extends CairoSurface {
/* Methods */
public __construct ( string $file , float $width , float $height )
public dscBeginPageSetup ( void ) : void
public dscBeginSetup ( void ) : void
public dscComment ( string $comment ) : void
public getEps ( void ) : bool
public static getLevels ( void ) : array
public static levelToString ( int $level ) : string
public restrictToLevel ( int $level ) : void
public setEps ( bool $level ) : void
public setSize ( float $width , float $height ) : void
/* Inherited methods */
public CairoSurface::__construct ( void )
public CairoSurface::copyPage ( void ) : void
public CairoSurface::createSimilar ( CairoSurface $other , int $content , string $width , string $height ) : void
public CairoSurface::finish ( void ) : void
public CairoSurface::flush ( void ) : void
public CairoSurface::getContent ( void ) : int
public CairoSurface::getDeviceOffset ( void ) : array
public CairoSurface::getFontOptions ( void ) : void
public CairoSurface::getType ( void ) : int
public CairoSurface::markDirty ( void ) : void
public CairoSurface::markDirtyRectangle ( float $x , float $y , float $width , float $height ) : void
public CairoSurface::setDeviceOffset ( float $x , float $y ) : void
public CairoSurface::setFallbackResolution ( float $x , float $y ) : void
public CairoSurface::showPage ( void ) : void
public CairoSurface::status ( void ) : int
public CairoSurface::writeToPng ( string $file ) : void
}

Table of Contents

  • CairoPsSurface::__construct — The __construct purpose
  • CairoPsSurface::dscBeginPageSetup — The dscBeginPageSetup purpose
  • CairoPsSurface::dscBeginSetup — The dscBeginSetup purpose
  • CairoPsSurface::dscComment — The dscComment purpose
  • CairoPsSurface::getEps — The getEps purpose
  • CairoPsSurface::getLevels — The getLevels purpose
  • CairoPsSurface::levelToString — The levelToString purpose
  • CairoPsSurface::restrictToLevel — The restrictToLevel purpose
  • CairoPsSurface::setEps — The setEps purpose
  • CairoPsSurface::setSize — The setSize purpose


The __construct purpose

  • « CairoPsSurface
  • CairoPsSurface::dscBeginPageSetup »
  • PHP Manual
  • CairoPsSurface
  • The __construct purpose

CairoPsSurface::__construct

(PECL cairo >= 0.1.0)

CairoPsSurface::__construct — The __construct purpose

Description

public CairoPsSurface::__construct ( string $file , float $width , float $height )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

file

Description...

width

Description...

height

Description...

Return Values

Description...

Examples

Example #1 CairoPsSurface::__construct() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The dscBeginPageSetup purpose

  • « CairoPsSurface::__construct
  • CairoPsSurface::dscBeginSetup »
  • PHP Manual
  • CairoPsSurface
  • The dscBeginPageSetup purpose

CairoPsSurface::dscBeginPageSetup

(PECL cairo >= 0.1.0)

CairoPsSurface::dscBeginPageSetup — The dscBeginPageSetup purpose

Description

public CairoPsSurface::dscBeginPageSetup ( void ) : void

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoPsSurface::dscBeginPageSetup() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The dscBeginSetup purpose

  • « CairoPsSurface::dscBeginPageSetup
  • CairoPsSurface::dscComment »
  • PHP Manual
  • CairoPsSurface
  • The dscBeginSetup purpose

CairoPsSurface::dscBeginSetup

(PECL cairo >= 0.1.0)

CairoPsSurface::dscBeginSetup — The dscBeginSetup purpose

Description

public CairoPsSurface::dscBeginSetup ( void ) : void

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoPsSurface::dscBeginSetup() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The dscComment purpose

  • « CairoPsSurface::dscBeginSetup
  • CairoPsSurface::getEps »
  • PHP Manual
  • CairoPsSurface
  • The dscComment purpose

CairoPsSurface::dscComment

(PECL cairo >= 0.1.0)

CairoPsSurface::dscComment — The dscComment purpose

Description

public CairoPsSurface::dscComment ( string $comment ) : void

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

comment

Description...

Return Values

Description...

Examples

Example #1 CairoPsSurface::dscComment() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getEps purpose

  • « CairoPsSurface::dscComment
  • CairoPsSurface::getLevels »
  • PHP Manual
  • CairoPsSurface
  • The getEps purpose

CairoPsSurface::getEps

(PECL cairo >= 0.1.0)

CairoPsSurface::getEps — The getEps purpose

Description

public CairoPsSurface::getEps ( void ) : bool

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoPsSurface::getEps() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getLevels purpose

  • « CairoPsSurface::getEps
  • CairoPsSurface::levelToString »
  • PHP Manual
  • CairoPsSurface
  • The getLevels purpose

CairoPsSurface::getLevels

(PECL cairo >= 0.1.0)

CairoPsSurface::getLevels — The getLevels purpose

Description

public static CairoPsSurface::getLevels ( void ) : array

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoPsSurface::getLevels() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The levelToString purpose

  • « CairoPsSurface::getLevels
  • CairoPsSurface::restrictToLevel »
  • PHP Manual
  • CairoPsSurface
  • The levelToString purpose

CairoPsSurface::levelToString

(PECL cairo >= 0.1.0)

CairoPsSurface::levelToString — The levelToString purpose

Description

public static CairoPsSurface::levelToString ( int $level ) : string

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

level

Description...

Return Values

Description...

Examples

Example #1 CairoPsSurface::levelToString() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The restrictToLevel purpose

  • « CairoPsSurface::levelToString
  • CairoPsSurface::setEps »
  • PHP Manual
  • CairoPsSurface
  • The restrictToLevel purpose

CairoPsSurface::restrictToLevel

(PECL cairo >= 0.1.0)

CairoPsSurface::restrictToLevel — The restrictToLevel purpose

Description

public CairoPsSurface::restrictToLevel ( int $level ) : void

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

level

Description...

Return Values

Description...

Examples

Example #1 CairoPsSurface::restrictToLevel() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The setEps purpose

  • « CairoPsSurface::restrictToLevel
  • CairoPsSurface::setSize »
  • PHP Manual
  • CairoPsSurface
  • The setEps purpose

CairoPsSurface::setEps

(PECL cairo >= 0.1.0)

CairoPsSurface::setEps — The setEps purpose

Description

public CairoPsSurface::setEps ( bool $level ) : void

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

level

Description...

Return Values

Description...

Examples

Example #1 CairoPsSurface::setEps() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The setSize purpose

  • « CairoPsSurface::setEps
  • CairoSurfaceType »
  • PHP Manual
  • CairoPsSurface
  • The setSize purpose

CairoPsSurface::setSize

(PECL cairo >= 0.1.0)

CairoPsSurface::setSize — The setSize purpose

Description

public CairoPsSurface::setSize ( float $width , float $height ) : void

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

width

Description...

height

Description...

Return Values

Description...

Examples

Example #1 CairoPsSurface::setSize() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The CairoSurfaceType class

(No version information available, might only be in Git)

Introduction

Class synopsis

CairoSurfaceType {
/* Constants */
const integer IMAGE = 0 ;
const integer PDF = 1 ;
const integer PS = 2 ;
const integer XLIB = 3 ;
const integer XCB = 4 ;
const integer GLITZ = 5 ;
const integer QUARTZ = 6 ;
const integer WIN32 = 7 ;
const integer BEOS = 8 ;
const integer DIRECTFB = 9 ;
const integer SVG = 10 ;
const integer OS2 = 11 ;
const integer WIN32_PRINTING = 12 ;
const integer QUARTZ_IMAGE = 13 ;
}

Predefined Constants

CairoSurfaceType::IMAGE

Description here...

CairoSurfaceType::PDF

Description here...

CairoSurfaceType::PS

Description here...

CairoSurfaceType::XLIB

Description here...

CairoSurfaceType::XCB

Description here...

CairoSurfaceType::GLITZ

Description here...

CairoSurfaceType::QUARTZ

Description here...

CairoSurfaceType::WIN32

Description here...

CairoSurfaceType::BEOS

Description here...

CairoSurfaceType::DIRECTFB

Description here...

CairoSurfaceType::SVG

Description here...

CairoSurfaceType::OS2

Description here...

CairoSurfaceType::WIN32_PRINTING

Description here...

CairoSurfaceType::QUARTZ_IMAGE

Description here...


The CairoFontFace class

(PECL cairo >= 0.1.0)

Introduction

CairoFontFace abstract class represents a particular font at a particular weight, slant, and other characteristic but no transformation or size.

Note: This class can not be instantiated directly, it is created by CairoContext::getFontFace() or cairo_scaled_font_get_font_face().

Class synopsis

CairoFontFace {
/* Methods */
public __construct ( void )
public getType ( void ) : int
public status ( void ) : int
}

Table of Contents

  • CairoFontFace::__construct — Creates a new CairoFontFace object
  • CairoFontFace::getType — Retrieves the font face type
  • CairoFontFace::status — Check for CairoFontFace errors


Creates a new CairoFontFace object

  • « CairoFontFace
  • CairoFontFace::getType »
  • PHP Manual
  • CairoFontFace
  • Creates a new CairoFontFace object

CairoFontFace::__construct

(PECL cairo >= 0.1.0)

CairoFontFace::__construct — Creates a new CairoFontFace object

Description

public CairoFontFace::__construct ( void )

CairoFontFace class represents a particular font at a particular weight, slant, and other characteristic but no transformation or size.

Note: This class can't be instantiated directly it is created by CairoContext::getFontFace() or cairo_scaled_font_get_font_face()

Parameters

This function has no parameters.

Return Values

CairoFontFace

Examples

Example #1 CairoFontFace::__construct() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Class::Method()


Retrieves the font face type

  • « CairoFontFace::__construct
  • CairoFontFace::status »
  • PHP Manual
  • CairoFontFace
  • Retrieves the font face type

CairoFontFace::getType

cairo_font_face_get_type

(PECL cairo >= 0.1.0)

CairoFontFace::getType -- cairo_font_face_get_type — Retrieves the font face type

Description

Object oriented style (method):

public CairoFontFace::getType ( void ) : int

Procedural style:

cairo_font_face_get_type ( CairoFontFace $fontface ) : int

This function returns the type of the backend used to create a font face. See CairoFontType class constants for available types.

Parameters

This function has no parameters.

Return Values

A font type that can be any one defined in CairoFontType

Examples

Example #1 CairoFontFace::getType() example

<?php

// Creates the font face
$fontface = new CairoToyFontFace('sans-serif');

// Get the font face type
var_dump($fontface->getType());

?>

The above example will output something similar to:

int(0)

See Also

  • Classname::Method()


Check for CairoFontFace errors

  • « CairoFontFace::getType
  • CairoFontOptions »
  • PHP Manual
  • CairoFontFace
  • Check for CairoFontFace errors

CairoFontFace::status

cairo_font_face_status

(PECL cairo >= 0.1.0)

CairoFontFace::status -- cairo_font_face_status — Check for CairoFontFace errors

Description

Object oriented style (method):

public CairoFontFace::status ( void ) : int

Procedural style:

cairo_font_face_status ( CairoFontFace $fontface ) : int

Checks whether an error has previously occurred for this font face

Parameters

fontface

A valid CairoFontFace object

Return Values

CAIRO_STATUS_SUCCESS or another error such as CAIRO_STATUS_NO_MEMORY.

Examples

Example #1 Object oriented style

<?php

// Creates the font face
$fontface = new CairoToyFontFace('sans-serif');

// Get the font face status
var_dump($fontface->status()); // should be the value of CAIRO_STATUS_SUCCESS

?>

The above example will output something similar to:

int(0)

Example #2 Procedural style

<?php

// Creates the font face
$fontface = new CairoToyFontFace('sans-serif');

// Get the font face status
var_dump(cairo_font_face_status($fontface)); // should be the value of CAIRO_STATUS_SUCCESS

?>

The above example will output something similar to:

int(0)

See Also

  • Classname::Method()


The CairoFontOptions class

(PECL cairo >= 0.1.0)

Introduction

An opaque structure holding all options that are used when rendering fonts.

Individual features of a cairo_font_options_t can be set or accessed using functions named cairo_font_options_set_feature_name and cairo_font_options_get_feature_name, like cairo_font_options_set_antialias() and cairo_font_options_get_antialias().

New features may be added to CairoFontOptions in the future. For this reason CairoFontOptions::copy(), CairoFontOptions::equal(), CairoFontOptions::merge(), CairoFontOptions::hash() (cairo_font_options_copy(), cairo_font_options_equal(), cairo_font_options_merge(), and cairo_font_options_hash() in procedural way) should be used to copy, check for equality, merge, or compute a hash value of CairoFontOptions objects.

Class synopsis

CairoFontOptions {
/* Methods */
public __construct ( void )
public equal ( CairoFontOptions $other ) : bool
public getAntialias ( void ) : int
public getHintMetrics ( void ) : int
public getHintStyle ( void ) : int
public getSubpixelOrder ( void ) : int
public hash ( void ) : int
public merge ( CairoFontOptions $other ) : void
public setAntialias ( int $antialias ) : void
public setHintMetrics ( int $hint_metrics ) : void
public setHintStyle ( int $hint_style ) : void
public setSubpixelOrder ( int $subpixel_order ) : void
public status ( void ) : int
}

Table of Contents

  • CairoFontOptions::__construct — The __construct purpose
  • CairoFontOptions::equal — The equal purpose
  • CairoFontOptions::getAntialias — The getAntialias purpose
  • CairoFontOptions::getHintMetrics — The getHintMetrics purpose
  • CairoFontOptions::getHintStyle — The getHintStyle purpose
  • CairoFontOptions::getSubpixelOrder — The getSubpixelOrder purpose
  • CairoFontOptions::hash — The hash purpose
  • CairoFontOptions::merge — The merge purpose
  • CairoFontOptions::setAntialias — The setAntialias purpose
  • CairoFontOptions::setHintMetrics — The setHintMetrics purpose
  • CairoFontOptions::setHintStyle — The setHintStyle purpose
  • CairoFontOptions::setSubpixelOrder — The setSubpixelOrder purpose
  • CairoFontOptions::status — The status purpose


The __construct purpose

  • « CairoFontOptions
  • CairoFontOptions::equal »
  • PHP Manual
  • CairoFontOptions
  • The __construct purpose

CairoFontOptions::__construct

(PECL cairo >= 0.1.0)

CairoFontOptions::__construct — The __construct purpose

Description

public CairoFontOptions::__construct ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoFontOptions::__construct() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The equal purpose

  • « CairoFontOptions::__construct
  • CairoFontOptions::getAntialias »
  • PHP Manual
  • CairoFontOptions
  • The equal purpose

CairoFontOptions::equal

(PECL cairo >= 0.1.0)

CairoFontOptions::equal — The equal purpose

Description

public CairoFontOptions::equal ( CairoFontOptions $other ) : bool

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

other

Description...

Return Values

Description...

Examples

Example #1 CairoFontOptions::equal() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getAntialias purpose

  • « CairoFontOptions::equal
  • CairoFontOptions::getHintMetrics »
  • PHP Manual
  • CairoFontOptions
  • The getAntialias purpose

CairoFontOptions::getAntialias

cairo_get_antialias

(PECL cairo >= 0.1.0)

CairoFontOptions::getAntialias -- cairo_get_antialias — The getAntialias purpose

Description

Object oriented style (method):

public CairoFontOptions::getAntialias ( void ) : int

Procedural style:

cairo_get_antialias ( CairoContext $context ) : int

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getHintMetrics purpose

  • « CairoFontOptions::getAntialias
  • CairoFontOptions::getHintStyle »
  • PHP Manual
  • CairoFontOptions
  • The getHintMetrics purpose

CairoFontOptions::getHintMetrics

(PECL cairo >= 0.1.0)

CairoFontOptions::getHintMetrics — The getHintMetrics purpose

Description

public CairoFontOptions::getHintMetrics ( void ) : int

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoFontOptions::getHintMetrics() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getHintStyle purpose

  • « CairoFontOptions::getHintMetrics
  • CairoFontOptions::getSubpixelOrder »
  • PHP Manual
  • CairoFontOptions
  • The getHintStyle purpose

CairoFontOptions::getHintStyle

(PECL cairo >= 0.1.0)

CairoFontOptions::getHintStyle — The getHintStyle purpose

Description

public CairoFontOptions::getHintStyle ( void ) : int

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoFontOptions::getHintStyle() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getSubpixelOrder purpose

  • « CairoFontOptions::getHintStyle
  • CairoFontOptions::hash »
  • PHP Manual
  • CairoFontOptions
  • The getSubpixelOrder purpose

CairoFontOptions::getSubpixelOrder

(PECL cairo >= 0.1.0)

CairoFontOptions::getSubpixelOrder — The getSubpixelOrder purpose

Description

public CairoFontOptions::getSubpixelOrder ( void ) : int

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoFontOptions::getSubpixelOrder() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The hash purpose

  • « CairoFontOptions::getSubpixelOrder
  • CairoFontOptions::merge »
  • PHP Manual
  • CairoFontOptions
  • The hash purpose

CairoFontOptions::hash

(PECL cairo >= 0.1.0)

CairoFontOptions::hash — The hash purpose

Description

public CairoFontOptions::hash ( void ) : int

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoFontOptions::hash() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The merge purpose

  • « CairoFontOptions::hash
  • CairoFontOptions::setAntialias »
  • PHP Manual
  • CairoFontOptions
  • The merge purpose

CairoFontOptions::merge

(PECL cairo >= 0.1.0)

CairoFontOptions::merge — The merge purpose

Description

public CairoFontOptions::merge ( CairoFontOptions $other ) : void

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

other

Description...

Return Values

Description...

Examples

Example #1 CairoFontOptions::merge() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The setAntialias purpose

  • « CairoFontOptions::merge
  • CairoFontOptions::setHintMetrics »
  • PHP Manual
  • CairoFontOptions
  • The setAntialias purpose

CairoFontOptions::setAntialias

cairo_set_antialias

(PECL cairo >= 0.1.0)

CairoFontOptions::setAntialias -- cairo_set_antialias — The setAntialias purpose

Description

Object oriented style (method):

public CairoFontOptions::setAntialias ( int $antialias ) : void

Procedural style:

cairo_set_antialias ( CairoContext $context [, int $antialias ] ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

antialias

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The setHintMetrics purpose

  • « CairoFontOptions::setAntialias
  • CairoFontOptions::setHintStyle »
  • PHP Manual
  • CairoFontOptions
  • The setHintMetrics purpose

CairoFontOptions::setHintMetrics

(PECL cairo >= 0.1.0)

CairoFontOptions::setHintMetrics — The setHintMetrics purpose

Description

public CairoFontOptions::setHintMetrics ( int $hint_metrics ) : void

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

hint_metrics

Description...

Return Values

Description...

Examples

Example #1 CairoFontOptions::setHintMetrics() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The setHintStyle purpose

  • « CairoFontOptions::setHintMetrics
  • CairoFontOptions::setSubpixelOrder »
  • PHP Manual
  • CairoFontOptions
  • The setHintStyle purpose

CairoFontOptions::setHintStyle

(PECL cairo >= 0.1.0)

CairoFontOptions::setHintStyle — The setHintStyle purpose

Description

public CairoFontOptions::setHintStyle ( int $hint_style ) : void

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

hint_style

Description...

Return Values

Description...

Examples

Example #1 CairoFontOptions::setHintStyle() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The setSubpixelOrder purpose

  • « CairoFontOptions::setHintStyle
  • CairoFontOptions::status »
  • PHP Manual
  • CairoFontOptions
  • The setSubpixelOrder purpose

CairoFontOptions::setSubpixelOrder

(PECL cairo >= 0.1.0)

CairoFontOptions::setSubpixelOrder — The setSubpixelOrder purpose

Description

public CairoFontOptions::setSubpixelOrder ( int $subpixel_order ) : void

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

subpixel_order

Description...

Return Values

Description...

Examples

Example #1 CairoFontOptions::setSubpixelOrder() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The status purpose

  • « CairoFontOptions::setSubpixelOrder
  • CairoFontSlant »
  • PHP Manual
  • CairoFontOptions
  • The status purpose

CairoFontOptions::status

cairo_status

(PECL cairo >= 0.1.0)

CairoFontOptions::status -- cairo_status — The status purpose

Description

Object oriented style (method):

public CairoFontOptions::status ( void ) : int

Procedural style:

cairo_status ( CairoContext $context ) : int

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The CairoFontSlant class

(No version information available, might only be in Git)

Introduction

Specifies variants of a font face based on their slant.

Class synopsis

CairoFontSlant {
/* Constants */
const integer NORMAL = 0 ;
const integer ITALIC = 1 ;
const integer OBLIQUE = 2 ;
}

Predefined Constants

CairoFontSlant::NORMAL

Upright font style

CairoFontSlant::ITALIC

Italic font style

CairoFontSlant::OBLIQUE

Oblique font style


The CairoFontType class

(No version information available, might only be in Git)

Introduction

CairoFontType class is an abstract final class that contains constants used to describe the type of a given CairoFontFace or CairoScaledFont. The font types are also known as "font backends" within cairo.

The type of a CairoFontFace is determined by the how it is created, an example would be the CairoToyFontFace::__construct(). The CairoFontFace type can be queried with CairoFontFace::getType() or cairo_font_face_get_type()

The various CairoFontFace functions can be used with a font face of any type.

The type of a CairoScaledFont is determined by the type of the CairoFontFace passed to CairoScaledFont::__construct() or cairo_scaled_font_create(). The scaled font type can be queried with CairoScaledFont::getType() or cairo_scaled_font_get_type().

Class synopsis

CairoFontType {
/* Constants */
const integer TOY = 0 ;
const integer FT = 1 ;
const integer WIN32 = 2 ;
const integer QUARTZ = 3 ;
}

Predefined Constants

CairoFontType::TOY

The font was created using CairoToyFont api

CairoFontType::FT

The font is of type CairoFreeType

CairoFontType::WIN32

The font is of type Win32

CairoFontType::QUARTZ

The font is of type Quartz

CairoFontType::USER

The font was create using cairo's user font api


The CairoFontWeight class

(No version information available, might only be in Git)

Introduction

Specifies variants of a font face based on their weight.

Class synopsis

CairoFontWeight {
/* Constants */
const integer NORMAL = 0 ;
const integer BOLD = 1 ;
}

Predefined Constants

CairoFontWeight::NORMAL

Normal font weight

CairoFontWeight::BOLD

Bold font weight


The CairoScaledFont class

(PECL cairo >= 0.1.0)

Introduction

Class synopsis

CairoScaledFont {
/* Methods */
public __construct ( CairoFontFace $font_face , CairoMatrix $matrix , CairoMatrix $ctm , CairoFontOptions $options )
public extents ( void ) : array
public getCtm ( void ) : CairoMatrix
public getFontFace ( void ) : void
public getFontMatrix ( void ) : void
public getFontOptions ( void ) : void
public getScaleMatrix ( void ) : void
public getType ( void ) : int
public glyphExtents ( array $glyphs ) : array
public status ( void ) : int
public textExtents ( string $text ) : array
}

Table of Contents

  • CairoScaledFont::__construct — The __construct purpose
  • CairoScaledFont::extents — The extents purpose
  • CairoScaledFont::getCtm — The getCtm purpose
  • CairoScaledFont::getFontFace — The getFontFace purpose
  • CairoScaledFont::getFontMatrix — The getFontMatrix purpose
  • CairoScaledFont::getFontOptions — The getFontOptions purpose
  • CairoScaledFont::getScaleMatrix — The getScaleMatrix purpose
  • CairoScaledFont::getType — The getType purpose
  • CairoScaledFont::glyphExtents — The glyphExtents purpose
  • CairoScaledFont::status — The status purpose
  • CairoScaledFont::textExtents — The textExtents purpose


The __construct purpose

  • « CairoScaledFont
  • CairoScaledFont::extents »
  • PHP Manual
  • CairoScaledFont
  • The __construct purpose

CairoScaledFont::__construct

(PECL cairo >= 0.1.0)

CairoScaledFont::__construct — The __construct purpose

Description

public CairoScaledFont::__construct ( CairoFontFace $font_face , CairoMatrix $matrix , CairoMatrix $ctm , CairoFontOptions $options )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

font_face

Description...

matrix

Description...

ctm

Description...

options

Description...

Return Values

Description...

Examples

Example #1 CairoScaledFont::__construct() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The extents purpose

  • « CairoScaledFont::__construct
  • CairoScaledFont::getCtm »
  • PHP Manual
  • CairoScaledFont
  • The extents purpose

CairoScaledFont::extents

(PECL cairo >= 0.1.0)

CairoScaledFont::extents — The extents purpose

Description

public CairoScaledFont::extents ( void ) : array

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoScaledFont::extents() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getCtm purpose

  • « CairoScaledFont::extents
  • CairoScaledFont::getFontFace »
  • PHP Manual
  • CairoScaledFont
  • The getCtm purpose

CairoScaledFont::getCtm

(PECL cairo >= 0.1.0)

CairoScaledFont::getCtm — The getCtm purpose

Description

public CairoScaledFont::getCtm ( void ) : CairoMatrix

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoScaledFont::getCtm() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getFontFace purpose

  • « CairoScaledFont::getCtm
  • CairoScaledFont::getFontMatrix »
  • PHP Manual
  • CairoScaledFont
  • The getFontFace purpose

CairoScaledFont::getFontFace

cairo_get_font_face

(PECL cairo >= 0.1.0)

CairoScaledFont::getFontFace -- cairo_get_font_face — The getFontFace purpose

Description

Object oriented style (method):

public CairoScaledFont::getFontFace ( void ) : void

Procedural style:

cairo_get_font_face ( CairoContext $context ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getFontMatrix purpose

  • « CairoScaledFont::getFontFace
  • CairoScaledFont::getFontOptions »
  • PHP Manual
  • CairoScaledFont
  • The getFontMatrix purpose

CairoScaledFont::getFontMatrix

cairo_get_font_matrix

(PECL cairo >= 0.1.0)

CairoScaledFont::getFontMatrix -- cairo_get_font_matrix — The getFontMatrix purpose

Description

Object oriented style (method):

public CairoScaledFont::getFontMatrix ( void ) : void

Procedural style:

cairo_get_font_matrix ( CairoContext $context ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getFontOptions purpose

  • « CairoScaledFont::getFontMatrix
  • CairoScaledFont::getScaleMatrix »
  • PHP Manual
  • CairoScaledFont
  • The getFontOptions purpose

CairoScaledFont::getFontOptions

cairo_get_font_options

(PECL cairo >= 0.1.0)

CairoScaledFont::getFontOptions -- cairo_get_font_options — The getFontOptions purpose

Description

Object oriented style (method):

public CairoScaledFont::getFontOptions ( void ) : void

Procedural style:

cairo_get_font_options ( CairoContext $context ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getScaleMatrix purpose

  • « CairoScaledFont::getFontOptions
  • CairoScaledFont::getType »
  • PHP Manual
  • CairoScaledFont
  • The getScaleMatrix purpose

CairoScaledFont::getScaleMatrix

(PECL cairo >= 0.1.0)

CairoScaledFont::getScaleMatrix — The getScaleMatrix purpose

Description

public CairoScaledFont::getScaleMatrix ( void ) : void

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoScaledFont::getScaleMatrix() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getType purpose

  • « CairoScaledFont::getScaleMatrix
  • CairoScaledFont::glyphExtents »
  • PHP Manual
  • CairoScaledFont
  • The getType purpose

CairoScaledFont::getType

(PECL cairo >= 0.1.0)

CairoScaledFont::getType — The getType purpose

Description

public CairoScaledFont::getType ( void ) : int

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoScaledFont::getType() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The glyphExtents purpose

  • « CairoScaledFont::getType
  • CairoScaledFont::status »
  • PHP Manual
  • CairoScaledFont
  • The glyphExtents purpose

CairoScaledFont::glyphExtents

(PECL cairo >= 0.1.0)

CairoScaledFont::glyphExtents — The glyphExtents purpose

Description

public CairoScaledFont::glyphExtents ( array $glyphs ) : array

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

glyphs

Description...

Return Values

Description...

Examples

Example #1 CairoScaledFont::glyphExtents() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The status purpose

  • « CairoScaledFont::glyphExtents
  • CairoScaledFont::textExtents »
  • PHP Manual
  • CairoScaledFont
  • The status purpose

CairoScaledFont::status

cairo_status

(PECL cairo >= 0.1.0)

CairoScaledFont::status -- cairo_status — The status purpose

Description

Object oriented style (method):

public CairoScaledFont::status ( void ) : int

Procedural style:

cairo_status ( CairoContext $context ) : int

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The textExtents purpose

  • « CairoScaledFont::status
  • CairoToyFontFace »
  • PHP Manual
  • CairoScaledFont
  • The textExtents purpose

CairoScaledFont::textExtents

cairo_text_extents

(PECL cairo >= 0.1.0)

CairoScaledFont::textExtents -- cairo_text_extents — The textExtents purpose

Description

Object oriented style (method):

public CairoScaledFont::textExtents ( string $text ) : array

Procedural style:

cairo_text_extents ( CairoContext $context ) : array

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

text

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The CairoToyFontFace class

(PECL cairo >= 0.1.0)

Introduction

The CairoToyFontFace class can be used instead of CairoContext::selectFontFace() to create a toy font independently of a context.

Class synopsis

CairoToyFontFace extends CairoFontFace {
/* Inherited methods */
}


The CairoPatternType class

(No version information available, might only be in Git)

Introduction

CairoPatternType is used to describe the type of a given pattern.

The type of a pattern is determined by the function used to create it. The cairo_pattern_create_rgb() and cairo_pattern_create_rgba() functions create CairoPatternType::SOLID patterns. The remaining cairo_pattern_create_* functions map to pattern types in obvious ways.

Class synopsis

CairoPatternType {
/* Constants */
const integer SOLID = 0 ;
const integer SURFACE = 1 ;
const integer LINEAR = 2 ;
const integer RADIAL = 3 ;
}

Predefined Constants

CairoPatternType::SOLID

The pattern is a solid (uniform) color. It may be opaque or translucent.

CairoPatternType::SURFACE

The pattern is a based on a surface (an image).

CairoPatternType::LINEAR

The pattern is a linear gradient.

CairoPatternType::RADIAL

The pattern is a radial gradient.


The CairoPattern class

(PECL cairo >= 0.1.0)

Introduction

CairoPattern is the abstract base class from which all the other pattern classes derive. It cannot be instantiated directly

Class synopsis

CairoPattern {
/* Methods */
public __construct ( void )
public getMatrix ( void ) : void
public getType ( void ) : int
public setMatrix ( CairoMatrix $matrix ) : void
public status ( void ) : int
}

Table of Contents

  • CairoPattern::__construct — The __construct purpose
  • CairoPattern::getMatrix — The getMatrix purpose
  • CairoPattern::getType — The getType purpose
  • CairoPattern::setMatrix — The setMatrix purpose
  • CairoPattern::status — The status purpose


The __construct purpose

  • « CairoPattern
  • CairoPattern::getMatrix »
  • PHP Manual
  • CairoPattern
  • The __construct purpose

CairoPattern::__construct

(PECL cairo >= 0.1.0)

CairoPattern::__construct — The __construct purpose

Description

public CairoPattern::__construct ( void )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoPattern::__construct() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getMatrix purpose

  • « CairoPattern::__construct
  • CairoPattern::getType »
  • PHP Manual
  • CairoPattern
  • The getMatrix purpose

CairoPattern::getMatrix

cairo_get_matrix

(PECL cairo >= 0.1.0)

CairoPattern::getMatrix -- cairo_get_matrix — The getMatrix purpose

Description

Object oriented style (method):

public CairoPattern::getMatrix ( void ) : void

Procedural style:

cairo_get_matrix ( CairoContext $context ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getType purpose

  • « CairoPattern::getMatrix
  • CairoPattern::setMatrix »
  • PHP Manual
  • CairoPattern
  • The getType purpose

CairoPattern::getType

(PECL cairo >= 0.1.0)

CairoPattern::getType — The getType purpose

Description

public CairoPattern::getType ( void ) : int

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoPattern::getType() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The setMatrix purpose

  • « CairoPattern::getType
  • CairoPattern::status »
  • PHP Manual
  • CairoPattern
  • The setMatrix purpose

CairoPattern::setMatrix

cairo_set_matrix

(PECL cairo >= 0.1.0)

CairoPattern::setMatrix -- cairo_set_matrix — The setMatrix purpose

Description

Object oriented style (method):

public CairoPattern::setMatrix ( CairoMatrix $matrix ) : void

Procedural style:

cairo_set_matrix ( CairoContext $context , CairoMatrix $matrix ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

matrix

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The status purpose

  • « CairoPattern::setMatrix
  • CairoGradientPattern »
  • PHP Manual
  • CairoPattern
  • The status purpose

CairoPattern::status

cairo_status

(PECL cairo >= 0.1.0)

CairoPattern::status -- cairo_status — The status purpose

Description

Object oriented style (method):

public CairoPattern::status ( void ) : int

Procedural style:

cairo_status ( CairoContext $context ) : int

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The CairoGradientPattern class

(PECL cairo >= 0.1.0)

Introduction

CairoGradientPattern is an abstract base class from which other Pattern classes derive. It cannot be instantiated directly.

Class synopsis

CairoGradientPattern extends CairoPattern {
/* Methods */
public addColorStopRgb ( float $offset , float $red , float $green , float $blue ) : void
public addColorStopRgba ( float $offset , float $red , float $green , float $blue , float $alpha ) : void
public getColorStopCount ( void ) : int
public getColorStopRgba ( int $index ) : array
public getExtend ( void ) : int
public setExtend ( int $extend ) : void
/* Inherited methods */
public CairoPattern::__construct ( void )
public CairoPattern::getMatrix ( void ) : void
public CairoPattern::getType ( void ) : int
public CairoPattern::setMatrix ( CairoMatrix $matrix ) : void
public CairoPattern::status ( void ) : int
}

Table of Contents

  • CairoGradientPattern::addColorStopRgb — The addColorStopRgb purpose
  • CairoGradientPattern::addColorStopRgba — The addColorStopRgba purpose
  • CairoGradientPattern::getColorStopCount — The getColorStopCount purpose
  • CairoGradientPattern::getColorStopRgba — The getColorStopRgba purpose
  • CairoGradientPattern::getExtend — The getExtend purpose
  • CairoGradientPattern::setExtend — The setExtend purpose


The addColorStopRgb purpose

  • « CairoGradientPattern
  • CairoGradientPattern::addColorStopRgba »
  • PHP Manual
  • CairoGradientPattern
  • The addColorStopRgb purpose

CairoGradientPattern::addColorStopRgb

(PECL cairo >= 0.1.0)

CairoGradientPattern::addColorStopRgb — The addColorStopRgb purpose

Description

public CairoGradientPattern::addColorStopRgb ( float $offset , float $red , float $green , float $blue ) : void

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

offset

Description...

red

Description...

green

Description...

blue

Description...

Return Values

Description...

Examples

Example #1 CairoGradientPattern::addColorStopRgb() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The addColorStopRgba purpose

  • « CairoGradientPattern::addColorStopRgb
  • CairoGradientPattern::getColorStopCount »
  • PHP Manual
  • CairoGradientPattern
  • The addColorStopRgba purpose

CairoGradientPattern::addColorStopRgba

(PECL cairo >= 0.1.0)

CairoGradientPattern::addColorStopRgba — The addColorStopRgba purpose

Description

public CairoGradientPattern::addColorStopRgba ( float $offset , float $red , float $green , float $blue , float $alpha ) : void

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

offset

Description...

red

Description...

green

Description...

blue

Description...

alpha

Description...

Return Values

Description...

Examples

Example #1 CairoGradientPattern::addColorStopRgba() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getColorStopCount purpose

  • « CairoGradientPattern::addColorStopRgba
  • CairoGradientPattern::getColorStopRgba »
  • PHP Manual
  • CairoGradientPattern
  • The getColorStopCount purpose

CairoGradientPattern::getColorStopCount

(PECL cairo >= 0.1.0)

CairoGradientPattern::getColorStopCount — The getColorStopCount purpose

Description

public CairoGradientPattern::getColorStopCount ( void ) : int

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoGradientPattern::getColorStopCount() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getColorStopRgba purpose

  • « CairoGradientPattern::getColorStopCount
  • CairoGradientPattern::getExtend »
  • PHP Manual
  • CairoGradientPattern
  • The getColorStopRgba purpose

CairoGradientPattern::getColorStopRgba

(PECL cairo >= 0.1.0)

CairoGradientPattern::getColorStopRgba — The getColorStopRgba purpose

Description

public CairoGradientPattern::getColorStopRgba ( int $index ) : array

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

index

Description...

Return Values

Description...

Examples

Example #1 CairoGradientPattern::getColorStopRgba() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getExtend purpose

  • « CairoGradientPattern::getColorStopRgba
  • CairoGradientPattern::setExtend »
  • PHP Manual
  • CairoGradientPattern
  • The getExtend purpose

CairoGradientPattern::getExtend

(PECL cairo >= 0.1.0)

CairoGradientPattern::getExtend — The getExtend purpose

Description

public CairoGradientPattern::getExtend ( void ) : int

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoGradientPattern::getExtend() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The setExtend purpose

  • « CairoGradientPattern::getExtend
  • CairoSolidPattern »
  • PHP Manual
  • CairoGradientPattern
  • The setExtend purpose

CairoGradientPattern::setExtend

(PECL cairo >= 0.1.0)

CairoGradientPattern::setExtend — The setExtend purpose

Description

public CairoGradientPattern::setExtend ( int $extend ) : void

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

extend

Description...

Return Values

Description...

Examples

Example #1 CairoGradientPattern::setExtend() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The CairoSolidPattern class

(PECL cairo >= 0.1.0)

Introduction

Class synopsis

CairoSolidPattern extends CairoPattern {
/* Methods */
public __construct ( float $red , float $green , float $blue [, float $alpha = 0 ] )
public getRgba ( void ) : array
/* Inherited methods */
public CairoPattern::__construct ( void )
public CairoPattern::getMatrix ( void ) : void
public CairoPattern::getType ( void ) : int
public CairoPattern::setMatrix ( CairoMatrix $matrix ) : void
public CairoPattern::status ( void ) : int
}

Table of Contents

  • CairoSolidPattern::__construct — The __construct purpose
  • CairoSolidPattern::getRgba — The getRgba purpose


The __construct purpose

  • « CairoSolidPattern
  • CairoSolidPattern::getRgba »
  • PHP Manual
  • CairoSolidPattern
  • The __construct purpose

CairoSolidPattern::__construct

(PECL cairo >= 0.1.0)

CairoSolidPattern::__construct — The __construct purpose

Description

public CairoSolidPattern::__construct ( float $red , float $green , float $blue [, float $alpha = 0 ] )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

red

Description...

green

Description...

blue

Description...

alpha

Description...

Return Values

Description...

Examples

Example #1 CairoSolidPattern::__construct() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getRgba purpose

  • « CairoSolidPattern::__construct
  • CairoSurfacePattern »
  • PHP Manual
  • CairoSolidPattern
  • The getRgba purpose

CairoSolidPattern::getRgba

(PECL cairo >= 0.1.0)

CairoSolidPattern::getRgba — The getRgba purpose

Description

public CairoSolidPattern::getRgba ( void ) : array

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoSolidPattern::getRgba() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The CairoSurfacePattern class

(PECL cairo >= 0.1.0)

Introduction

Class synopsis

CairoSurfacePattern extends CairoPattern {
/* Methods */
public __construct ( CairoSurface $surface )
public getExtend ( void ) : int
public getFilter ( void ) : int
public getSurface ( void ) : void
public setExtend ( int $extend ) : void
public setFilter ( int $filter ) : void
/* Inherited methods */
public CairoPattern::__construct ( void )
public CairoPattern::getMatrix ( void ) : void
public CairoPattern::getType ( void ) : int
public CairoPattern::setMatrix ( CairoMatrix $matrix ) : void
public CairoPattern::status ( void ) : int
}

Table of Contents

  • CairoSurfacePattern::__construct — The __construct purpose
  • CairoSurfacePattern::getExtend — The getExtend purpose
  • CairoSurfacePattern::getFilter — The getFilter purpose
  • CairoSurfacePattern::getSurface — The getSurface purpose
  • CairoSurfacePattern::setExtend — The setExtend purpose
  • CairoSurfacePattern::setFilter — The setFilter purpose


The __construct purpose

  • « CairoSurfacePattern
  • CairoSurfacePattern::getExtend »
  • PHP Manual
  • CairoSurfacePattern
  • The __construct purpose

CairoSurfacePattern::__construct

(PECL cairo >= 0.1.0)

CairoSurfacePattern::__construct — The __construct purpose

Description

public CairoSurfacePattern::__construct ( CairoSurface $surface )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

surface

Description...

Return Values

Description...

Examples

Example #1 CairoSurfacePattern::__construct() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getExtend purpose

  • « CairoSurfacePattern::__construct
  • CairoSurfacePattern::getFilter »
  • PHP Manual
  • CairoSurfacePattern
  • The getExtend purpose

CairoSurfacePattern::getExtend

(PECL cairo >= 0.1.0)

CairoSurfacePattern::getExtend — The getExtend purpose

Description

public CairoSurfacePattern::getExtend ( void ) : int

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoSurfacePattern::getExtend() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getFilter purpose

  • « CairoSurfacePattern::getExtend
  • CairoSurfacePattern::getSurface »
  • PHP Manual
  • CairoSurfacePattern
  • The getFilter purpose

CairoSurfacePattern::getFilter

(PECL cairo >= 0.1.0)

CairoSurfacePattern::getFilter — The getFilter purpose

Description

public CairoSurfacePattern::getFilter ( void ) : int

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoSurfacePattern::getFilter() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getSurface purpose

  • « CairoSurfacePattern::getFilter
  • CairoSurfacePattern::setExtend »
  • PHP Manual
  • CairoSurfacePattern
  • The getSurface purpose

CairoSurfacePattern::getSurface

(PECL cairo >= 0.1.0)

CairoSurfacePattern::getSurface — The getSurface purpose

Description

public CairoSurfacePattern::getSurface ( void ) : void

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoSurfacePattern::getSurface() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The setExtend purpose

  • « CairoSurfacePattern::getSurface
  • CairoSurfacePattern::setFilter »
  • PHP Manual
  • CairoSurfacePattern
  • The setExtend purpose

CairoSurfacePattern::setExtend

(PECL cairo >= 0.1.0)

CairoSurfacePattern::setExtend — The setExtend purpose

Description

public CairoSurfacePattern::setExtend ( int $extend ) : void

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

extend

Description...

Return Values

Description...

Examples

Example #1 CairoSurfacePattern::setExtend() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The setFilter purpose

  • « CairoSurfacePattern::setExtend
  • CairoLinearGradient »
  • PHP Manual
  • CairoSurfacePattern
  • The setFilter purpose

CairoSurfacePattern::setFilter

(PECL cairo >= 0.1.0)

CairoSurfacePattern::setFilter — The setFilter purpose

Description

public CairoSurfacePattern::setFilter ( int $filter ) : void

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

filter

Description...

Return Values

Description...

Examples

Example #1 CairoSurfacePattern::setFilter() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The CairoLinearGradient class

(PECL cairo >= 0.1.0)

Introduction

Create a new CairoLinearGradient along the line defined

Class synopsis

CairoLinearGradient extends CairoGradientPattern {
/* Methods */
public __construct ( float $x0 , float $y0 , float $x1 , float $y1 )
public getPoints ( void ) : array
/* Inherited methods */
public CairoGradientPattern::addColorStopRgb ( float $offset , float $red , float $green , float $blue ) : void
public CairoGradientPattern::addColorStopRgba ( float $offset , float $red , float $green , float $blue , float $alpha ) : void
public CairoGradientPattern::getColorStopCount ( void ) : int
public CairoGradientPattern::getColorStopRgba ( int $index ) : array
public CairoGradientPattern::getExtend ( void ) : int
public CairoGradientPattern::setExtend ( int $extend ) : void
}

Table of Contents

  • CairoLinearGradient::__construct — The __construct purpose
  • CairoLinearGradient::getPoints — The getPoints purpose


The __construct purpose

  • « CairoLinearGradient
  • CairoLinearGradient::getPoints »
  • PHP Manual
  • CairoLinearGradient
  • The __construct purpose

CairoLinearGradient::__construct

(PECL cairo >= 0.1.0)

CairoLinearGradient::__construct — The __construct purpose

Description

public CairoLinearGradient::__construct ( float $x0 , float $y0 , float $x1 , float $y1 )

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

x0

Description...

y0

Description...

x1

Description...

y1

Description...

Return Values

Description...

Examples

Example #1 CairoLinearGradient::__construct() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getPoints purpose

  • « CairoLinearGradient::__construct
  • CairoRadialGradient »
  • PHP Manual
  • CairoLinearGradient
  • The getPoints purpose

CairoLinearGradient::getPoints

(PECL cairo >= 0.1.0)

CairoLinearGradient::getPoints — The getPoints purpose

Description

public CairoLinearGradient::getPoints ( void ) : array

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoLinearGradient::getPoints() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The CairoRadialGradient class

(PECL cairo >= 0.1.0)

Introduction

Class synopsis

CairoRadialGradient extends CairoGradientPattern {
/* Methods */
public __construct ( float $x0 , float $y0 , float $r0 , float $x1 , float $y1 , float $r1 )
public getCircles ( void ) : array
/* Inherited methods */
public CairoGradientPattern::addColorStopRgb ( float $offset , float $red , float $green , float $blue ) : void
public CairoGradientPattern::addColorStopRgba ( float $offset , float $red , float $green , float $blue , float $alpha ) : void
public CairoGradientPattern::getColorStopCount ( void ) : int
public CairoGradientPattern::getColorStopRgba ( int $index ) : array
public CairoGradientPattern::getExtend ( void ) : int
public CairoGradientPattern::setExtend ( int $extend ) : void
}

Table of Contents

  • CairoRadialGradient::__construct — The __construct purpose
  • CairoRadialGradient::getCircles — The getCircles purpose


The __construct purpose

  • « CairoRadialGradient
  • CairoRadialGradient::getCircles »
  • PHP Manual
  • CairoRadialGradient
  • The __construct purpose

CairoRadialGradient::__construct

(PECL cairo >= 0.1.0)

CairoRadialGradient::__construct — The __construct purpose

Description

Object oriented style:

public CairoRadialGradient::__construct ( float $x0 , float $y0 , float $r0 , float $x1 , float $y1 , float $r1 )

Procedural style:

Creates a new radial gradient CairoPattern between the two circles defined by (x0, y0, r0) and (x1, y1, r1). Before using the gradient pattern, a number of color stops should be defined using CairoRadialGradient::addColorStopRgb() or CairoRadialGradient::addColorStopRgba().

Note: The coordinates here are in pattern space. For a new pattern, pattern space is identical to user space, but the relationship between the spaces can be changed with CairoRadialGradient::setMatrix().

Parameters

x0

x coordinate for the center of the start circle.

y0

y coordinate for the center of the start circle.

r0

radius of the start circle.

x1

x coordinate for the center of the end circle.

y1

y coordinate for the center of the end circle.

r1

radius of the end circle.

Return Values

Description...

Examples

Example #1 CairoRadialGradient::__construct() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The getCircles purpose

  • « CairoRadialGradient::__construct
  • CairoAntialias »
  • PHP Manual
  • CairoRadialGradient
  • The getCircles purpose

CairoRadialGradient::getCircles

(PECL cairo >= 0.1.0)

CairoRadialGradient::getCircles — The getCircles purpose

Description

public CairoRadialGradient::getCircles ( void ) : array

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoRadialGradient::getCircles() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The CairoAntialias class

(No version information available, might only be in Git)

Introduction

Enum class that specifies the type of antialiasing to do when rendering text or shapes.

Class synopsis

CairoAntialias {
/* Constants */
const integer MODE_DEFAULT = 0 ;
const integer MODE_NONE = 1 ;
const integer MODE_GRAY = 2 ;
const integer MODE_SUBPIXEL = 3 ;
}

Predefined Constants

CairoAntialias::MODE_DEFAULT

Use the default antialiasing for the subsystem and target device

CairoAntialias::MODE_NONE

Use a bilevel alpha mask

CairoAntialias::MODE_GRAY

Perform single-color antialiasing (using shades of gray for black text on a white background, for example).

CairoAntialias::MODE_SUBPIXEL

Perform antialiasing by taking advantage of the order of subpixel elements on devices such as LCD panels.


The CairoContent class

(No version information available, might only be in Git)

Introduction

CairoContent is used to describe the content that a surface will contain, whether color information, alpha information (translucence vs. opacity), or both.

Note: The large values here are designed to keep CairoContent values distinct from CairoContent values so that the implementation can detect the error if users confuse the two types.

Class synopsis

CairoContent {
/* Constants */
const integer COLOR = 4096 ;
const integer ALPHA = 8192 ;
const integer COLOR_ALPHA = 12288 ;
}

Predefined Constants

CairoContent::COLOR

The surface will hold color content only.

CairoContent::ALPHA

The surface will hold alpha content only.

CairoContent::COLOR_ALPHA

The surface will hold color and alpha content.


The CairoExtend class

(No version information available, might only be in Git)

Introduction

Class synopsis

CairoExtend {
/* Constants */
const integer NONE = 0 ;
const integer REPEAT = 1 ;
const integer REFLECT = 2 ;
const integer PAD = 3 ;
}

Predefined Constants

CairoExtend::NONE

Description here...

CairoExtend::REPEAT

Description here...

CairoExtend::REFLECT

Description here...

CairoExtend::PAD

Description here...


The CairoFormat class

(PECL cairo >= 0.1.0)

Introduction

CairoFormat enums are used to identify the memory format of the image data.

Class synopsis

CairoFormat {
/* Constants */
const integer ARGB32 = 0 ;
const integer RGB24 = 1 ;
const integer A8 = 2 ;
const integer A1 = 3 ;
/* Methods */
public static strideForWidth ( int $format , int $width ) : int
}

Predefined Constants

CairoFormat::ARGB32

Each pixel is a 32-bit quantity, with alpha in the upper 8 bits, then red, then green, then blue. The 32-bit quantities are stored native-endian. Pre-multiplied alpha is used. (That is, 50% transparent red is 0x80800000, not 0x80ff0000.)

CairoFormat::RGB24

Each pixel is a 32-bit quantity, with the upper 8 bits unused. Red, Green, and Blue are stored in the remaining 24 bits in that order.

CairoFormat::A8

Each pixel is a 8-bit quantity holding an alpha value.

CairoFormat::A1

Each pixel is a 1-bit quantity holding an alpha value. Pixels are packed together into 32-bit quantities. The ordering of the bits matches the endianness of the platform. On a big-endian machine, the first pixel is in the uppermost bit, on a little-endian machine the first pixel is in the least-significant bit.

Table of Contents

  • CairoFormat::strideForWidth — Provides an appropriate stride to use


Provides an appropriate stride to use

  • « CairoFormat
  • CairoFillRule »
  • PHP Manual
  • CairoFormat
  • Provides an appropriate stride to use

CairoFormat::strideForWidth

(PECL cairo >= 0.1.0)

CairoFormat::strideForWidth — Provides an appropriate stride to use

Description

public static CairoFormat::strideForWidth ( int $format , int $width ) : int

This method provides a stride value that will respect all alignment requirements of the accelerated image-rendering code within cairo.

Parameters

format

The desired CairoFormat to use

width

The width of the image

Return Values

The appropriate stride to use given the desired format and width, or -1 if either the format is invalid or the width too large.

Examples

Example #1 CairoFormat::strideForWidth() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The CairoFillRule class

(No version information available, might only be in Git)

Introduction

A CairoFillRule is used to select how paths are filled. For both fill rules, whether or not a point is included in the fill is determined by taking a ray from that point to infinity and looking at intersections with the path. The ray can be in any direction, as long as it doesn't pass through the end point of a segment or have a tricky intersection such as intersecting tangent to the path. (Note that filling is not actually implemented in this way. This is just a description of the rule that is applied.)

The default fill rule is CairoFillRule::WINDING.

Class synopsis

CairoFillRule {
/* Constants */
const integer WINDING = 0 ;
const integer EVEN_ODD = 1 ;
}

Predefined Constants

CairoFillRule::WINDING

If the path crosses the ray from left-to-right, counts +1. If the path crosses the ray from right to left, counts -1. (Left and right are determined from the perspective of looking along the ray from the starting point.) If the total count is non-zero, the point will be filled.

CairoFillRule::EVEN_ODD

Counts the total number of intersections, without regard to the orientation of the contour. If the total number of intersections is odd, the point will be filled.


The CairoFilter class

(No version information available, might only be in Git)

Introduction

A CairoFilter is used to indicate what filtering should be applied when reading pixel values from patterns. See CairoPattern::setSource() or cairo_pattern_set_source() for indicating the desired filter to be used with a particular pattern.

Class synopsis

CairoFilter {
/* Constants */
const integer FAST = 0 ;
const integer GOOD = 1 ;
const integer BEST = 2 ;
const integer NEAREST = 3 ;
const integer BILINEAR = 4 ;
const integer GAUSSIAN = 5 ;
}

Predefined Constants

CairoFilter::FAST

A high-performance filter, with quality similar to CairoFilter::NEAREST

CairoFilter::GOOD

A reasonable-performance filter, with quality similar to CairoFilter::BILINEAR

CairoFilter::BEST

The highest-quality available, performance may not be suitable for interactive use.

CairoFilter::NEAREST

Nearest-neighbor filtering

CairoFilter::BILINEAR

Linear interpolation in two dimensions

CairoFilter::GAUSSIAN

This filter value is currently unimplemented, and should not be used in current code.


The CairoHintMetrics class

(No version information available, might only be in Git)

Introduction

Specifies whether to hint font metrics; hinting font metrics means quantizing them so that they are integer values in device space. Doing this improves the consistency of letter and line spacing, however it also means that text will be laid out differently at different zoom factors.

Class synopsis

CairoHintMetrics {
/* Constants */
const integer METRICS_DEFAULT = 0 ;
const integer METRICS_OFF = 1 ;
const integer METRICS_ON = 2 ;
}

Predefined Constants

CairoHintMetrics::METRICS_DEFAULT

Hint metrics in the default manner for the font backend and target device

CairoHintMetrics::METRICS_OFF

Do not hint font metrics

CairoHintMetrics::METRICS_ON

Hint font metrics


The CairoHintStyle class

(No version information available, might only be in Git)

Introduction

Specifies the type of hinting to do on font outlines. Hinting is the process of fitting outlines to the pixel grid in order to improve the appearance of the result. Since hinting outlines involves distorting them, it also reduces the faithfulness to the original outline shapes. Not all of the outline hinting styles are supported by all font backends.

Class synopsis

CairoHintStyle {
/* Constants */
const integer STYLE_DEFAULT = 0 ;
const integer STYLE_NONE = 1 ;
const integer STYLE_SLIGHT = 2 ;
const integer STYLE_MEDIUM = 3 ;
const integer STYLE_FULL = 4 ;
}

Predefined Constants

CairoHintStyle::STYLE_DEFAULT

Use the default hint style for font backend and target device

CairoHintStyle::STYLE_NONE

Do not hint outlines

CairoHintStyle::STYLE_SLIGHT

Hint outlines slightly to improve contrast while retaining good fidelity to the original shapes.

CairoHintStyle::STYLE_MEDIUM

Hint outlines with medium strength giving a compromise between fidelity to the original shapes and contrast

CairoHintStyle::STYLE_FULL

Hint outlines to maximize contrast


The CairoLineCap class

(No version information available, might only be in Git)

Introduction

Specifies how to render the endpoints of the path when stroking.

The default line cap style is CairoLineCap::BUTT.

Class synopsis

CairoLineCap {
/* Constants */
const integer BUTT = 0 ;
const integer ROUND = 1 ;
const integer SQUARE = 2 ;
}

Predefined Constants

CairoLineCap::BUTT

Start(stop) the line exactly at the start(end) point

CairoLineCap::ROUND

Use a round ending, the center of the circle is the end point

CairoLineCap::SQUARE

Use squared ending, the center of the square is the end point


The CairoLineJoin class

(No version information available, might only be in Git)

Introduction

Class synopsis

CairoLineJoin {
/* Constants */
const integer MITER = 0 ;
const integer ROUND = 1 ;
const integer BEVEL = 2 ;
}

Predefined Constants

CairoLineJoin::MITER

Description here...

CairoLineJoin::ROUND

Description here...

CairoLineJoin::BEVEL

Description here...


The CairoMatrix class

(PECL cairo >= 0.1.0)

Introduction

Matrices are used throughout cairo to convert between different coordinate spaces.

Class synopsis

CairoMatrix {
/* Methods */
public __construct ([ float $xx = 1.0 [, float $yx = 0.0 [, float $xy = 0.0 [, float $yy = 1.0 [, float $x0 = 0.0 [, float $y0 = 0.0 ]]]]]] )
public static initIdentity ( void ) : void
public static initRotate ( float $radians ) : void
public static initScale ( float $sx , float $sy ) : void
public static initTranslate ( float $tx , float $ty ) : void
public invert ( void ) : void
public static multiply ( CairoMatrix $matrix1 , CairoMatrix $matrix2 ) : CairoMatrix
public rotate ( float $radians ) : void
public scale ( float $sx , float $sy ) : void
public transformDistance ( float $dx , float $dy ) : array
public transformPoint ( float $dx , float $dy ) : array
public translate ( float $tx , float $ty ) : void
}

Table of Contents

  • CairoMatrix::__construct — Creates a new CairoMatrix object
  • CairoMatrix::initIdentity — Creates a new identity matrix
  • CairoMatrix::initRotate — Creates a new rotated matrix
  • CairoMatrix::initScale — Creates a new scaling matrix
  • CairoMatrix::initTranslate — Creates a new translation matrix
  • CairoMatrix::invert — The invert purpose
  • CairoMatrix::multiply — The multiply purpose
  • CairoMatrix::rotate — The rotate purpose
  • CairoMatrix::scale — Applies scaling to a matrix
  • CairoMatrix::transformDistance — The transformDistance purpose
  • CairoMatrix::transformPoint — The transformPoint purpose
  • CairoMatrix::translate — The translate purpose


Creates a new CairoMatrix object

  • « CairoMatrix
  • CairoMatrix::initIdentity »
  • PHP Manual
  • CairoMatrix
  • Creates a new CairoMatrix object

CairoMatrix::__construct

cairo_matrix_init

(PECL cairo >= 0.1.0)

CairoMatrix::__construct -- cairo_matrix_init — Creates a new CairoMatrix object

Description

Object oriented style (method):

public CairoMatrix::__construct ([ float $xx = 1.0 [, float $yx = 0.0 [, float $xy = 0.0 [, float $yy = 1.0 [, float $x0 = 0.0 [, float $y0 = 0.0 ]]]]]] )

Procedural style:

cairo_matrix_init ([ float $xx = 1.0 [, float $yx = 0.0 [, float $xy = 0.0 [, float $yy = 1.0 [, float $x0 = 0.0 [, float $y0 = 0.0 ]]]]]] ) : object

Returns new CairoMatrix object. Matrices are used throughout cairo to convert between different coordinate spaces. Sets matrix to be the affine transformation given by xx, yx, xy, yy, x0, y0. The transformation is given by: x_new = xx * x + xy * y + x0; and y_new = yx * x + yy * y + y0;

Parameters

xx

xx component of the affine transformation

yx

yx component of the affine transformation

xy

xy component of the affine transformation

yy

yy component of the affine transformation

x0

X translation component of the affine transformation

y0

Y translation component of the affine transformation

Return Values

Returns a new CairoMatrix object that can be used with surfaces, contexts, and patterns.

Examples

Example #1 Object oriented style

<?php
/* Create a new Matrix */
$matrix = new CairoMatrix(1.0, 0.5, 0.0, 1.0, 0.0, 0.0);
?>

Example #2 Procedural style

<?php
/* Create a new Matrix */
$matrix = cairo_matrix_init(1.0, 0.5, 0.0, 1.0, 0.0, 0.0);
?>

See Also

  • CairoMatrix::initIdentity() - Creates a new identity matrix
  • CairoMatrix::initRotate() - Creates a new rotated matrix
  • CairoMatrix::initScale() - Creates a new scaling matrix
  • CairoMatrix::initTranslate() - Creates a new translation matrix


Creates a new identity matrix

  • « CairoMatrix::__construct
  • CairoMatrix::initRotate »
  • PHP Manual
  • CairoMatrix
  • Creates a new identity matrix

CairoMatrix::initIdentity

cairo_matrix_init_identity

(PECL cairo >= 0.1.0)

CairoMatrix::initIdentity -- cairo_matrix_init_identity — Creates a new identity matrix

Description

Object oriented style (method):

public static CairoMatrix::initIdentity ( void ) : void

Procedural style:

cairo_matrix_init_identity ( void ) : object

Creates a new matrix that is an identity transformation. An identity transformation means the source data is copied into the destination data without change

Parameters

This function has no parameters.

Return Values

Returns a new CairoMatrix object that can be used with surfaces, contexts, and patterns.

Examples

Example #1 Object oriented style

<?php
/* Create a new Matrix */
$matrix = CairoMatrix::initIdentity();
?>

Example #2 Procedural style

<?php
/* Create a new Matrix */
$matrix = cairo_matrix_init_identity();
?>

See Also

  • CairoMatrix::__construct() - Creates a new CairoMatrix object
  • CairoMatrix::initRotate() - Creates a new rotated matrix
  • CairoMatrix::initScale() - Creates a new scaling matrix
  • CairoMatrix::initTranslate() - Creates a new translation matrix


Creates a new rotated matrix

  • « CairoMatrix::initIdentity
  • CairoMatrix::initScale »
  • PHP Manual
  • CairoMatrix
  • Creates a new rotated matrix

CairoMatrix::initRotate

cairo_matrix_init_rotate

(PECL cairo >= 0.1.0)

CairoMatrix::initRotate -- cairo_matrix_init_rotate — Creates a new rotated matrix

Description

Object oriented style (method):

public static CairoMatrix::initRotate ( float $radians ) : void

Procedural style:

cairo_matrix_init_rotate ( float $radians ) : object

Creates a new matrix to a transformation that rotates by radians provided

Parameters

radians

angle of rotation, in radians. The direction of rotation is defined such that positive angles rotate in the direction from the positive X axis toward the positive Y axis. With the default axis orientation of cairo, positive angles rotate in a clockwise direction.

Return Values

Returns a new CairoMatrix object that can be used with surfaces, contexts, and patterns.

Examples

Example #1 Object oriented style

<?php
/* Create a new Matrix */
$matrix = CairoMatrix::initRotate(0.3);
?>

Example #2 Procedural style

<?php
/* Create a new Matrix */
$matrix = cairo_matrix_init_rotate(0.3);
?>

See Also

  • CairoMatrix::__construct() - Creates a new CairoMatrix object
  • CairoMatrix::initIdentity() - Creates a new identity matrix
  • CairoMatrix::initScale() - Creates a new scaling matrix
  • CairoMatrix::initTranslate() - Creates a new translation matrix


Creates a new scaling matrix

  • « CairoMatrix::initRotate
  • CairoMatrix::initTranslate »
  • PHP Manual
  • CairoMatrix
  • Creates a new scaling matrix

CairoMatrix::initScale

cairo_matrix_init_scale

(PECL cairo >= 0.1.0)

CairoMatrix::initScale -- cairo_matrix_init_scale — Creates a new scaling matrix

Description

Object oriented style (method):

public static CairoMatrix::initScale ( float $sx , float $sy ) : void

Procedural style:

cairo_matrix_init_scale ( float $sx , float $sy ) : object

Creates a new matrix to a transformation that scales by sx and sy in the X and Y dimensions, respectively.

Parameters

sx

scale factor in the X direction

sy

scale factor in the Y direction

Return Values

Returns a new CairoMatrix object that can be used with surfaces, contexts, and patterns.

Examples

Example #1 Object oriented style

<?php
/* Create a new Matrix */
$matrix = CairoMatrix::initScale(1.0, 2.0);
?>

Example #2 Procedural style

<?php
/* Create a new Matrix */
$matrix = cairo_matrix_init_scale(1.0, 2.0);
?>

See Also

  • CairoMatrix::__construct() - Creates a new CairoMatrix object
  • CairoMatrix::initIdentity() - Creates a new identity matrix
  • CairoMatrix::initRotate() - Creates a new rotated matrix
  • CairoMatrix::initTranslate() - Creates a new translation matrix


Creates a new translation matrix

  • « CairoMatrix::initScale
  • CairoMatrix::invert »
  • PHP Manual
  • CairoMatrix
  • Creates a new translation matrix

CairoMatrix::initTranslate

cairo_matrix_init_translate

(PECL cairo >= 0.1.0)

CairoMatrix::initTranslate -- cairo_matrix_init_translate — Creates a new translation matrix

Description

Object oriented style (method):

public static CairoMatrix::initTranslate ( float $tx , float $ty ) : void

Procedural style:

cairo_matrix_init_translate ( float $tx , float $ty ) : object

Creates a new matrix to a transformation that translates by tx and ty in the X and Y dimensions, respectively.

Parameters

tx

amount to translate in the X direction

ty

amount to translate in the Y direction

Return Values

Returns a new CairoMatrix object that can be used with surfaces, contexts, and patterns.

Examples

Example #1 Object oriented style

<?php
/* Create a new Matrix */
$matrix = CairoMatrix::initTranslate(1.0, 2.0);
?>

Example #2 Procedural style

<?php
/* Create a new Matrix */
$matrix = cairo_matrix_init_translate(1.0, 2.0);
?>

See Also

  • CairoMatrix::__construct() - Creates a new CairoMatrix object
  • CairoMatrix::initIdentity() - Creates a new identity matrix
  • CairoMatrix::initRotate() - Creates a new rotated matrix
  • CairoMatrix::initScale() - Creates a new scaling matrix


The invert purpose

  • « CairoMatrix::initTranslate
  • CairoMatrix::multiply »
  • PHP Manual
  • CairoMatrix
  • The invert purpose

CairoMatrix::invert

(PECL cairo >= 0.1.0)

CairoMatrix::invert — The invert purpose

Description

public CairoMatrix::invert ( void ) : void

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Description...

Examples

Example #1 CairoMatrix::invert() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The multiply purpose

  • « CairoMatrix::invert
  • CairoMatrix::rotate »
  • PHP Manual
  • CairoMatrix
  • The multiply purpose

CairoMatrix::multiply

(PECL cairo >= 0.1.0)

CairoMatrix::multiply — The multiply purpose

Description

public static CairoMatrix::multiply ( CairoMatrix $matrix1 , CairoMatrix $matrix2 ) : CairoMatrix

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

matrix1

Description...

matrix2

Description...

Return Values

Description...

Examples

Example #1 CairoMatrix::multiply() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The rotate purpose

  • « CairoMatrix::multiply
  • CairoMatrix::scale »
  • PHP Manual
  • CairoMatrix
  • The rotate purpose

CairoMatrix::rotate

cairo_matrix_rotate

(PECL cairo >= 0.1.0)

CairoMatrix::rotate -- cairo_matrix_rotate — The rotate purpose

Description

Object oriented style (method):

public CairoMatrix::rotate ( float $radians ) : void

Procedural style:

cairo_matrix_rotate ( CairoContext $context , string $radians ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

radians

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


Applies scaling to a matrix

  • « CairoMatrix::rotate
  • CairoMatrix::transformDistance »
  • PHP Manual
  • CairoMatrix
  • Applies scaling to a matrix

CairoMatrix::scale

cairo_matrix_scale

(PECL cairo >= 0.1.0)

CairoMatrix::scale -- cairo_matrix_scale — Applies scaling to a matrix

Description

Object oriented style (method):

public CairoMatrix::scale ( float $sx , float $sy ) : void

Procedural style:

cairo_matrix_scale ( CairoContext $context , float $sx , float $sy ) : void

Applies scaling by sx, sy to the transformation in the matrix. The effect of the new transformation is to first scale the coordinates by sx and sy, then apply the original transformation to the coordinates.

Parameters

matrix

Procedural only - CairoMatrix instance

sx

scale factor in the X direction

sy

scale factor in the Y direction

Examples

Example #1 Object oriented style

<?php
/* Apply scaling to a matrix */
$matrix = new CairoMatrix(1.0, 0.5, 0.0, 1.0, 0.0, 0.0);
$matrix->scale(0.2, 2.0);
?>

Example #2 Procedural style

<?php
/* Apply scaling to a matrix */
$matrix = cairo_matrix_init(1.0, 0.5, 0.0, 1.0, 0.0, 0.0);
cairo_matrix_scale($matrix, 0.2, 2.0);
?>

See Also

  • CairoMatrix::initScale() - Creates a new scaling matrix


The transformDistance purpose

  • « CairoMatrix::scale
  • CairoMatrix::transformPoint »
  • PHP Manual
  • CairoMatrix
  • The transformDistance purpose

CairoMatrix::transformDistance

(PECL cairo >= 0.1.0)

CairoMatrix::transformDistance — The transformDistance purpose

Description

public CairoMatrix::transformDistance ( float $dx , float $dy ) : array

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

dx

Description...

dy

Description...

Return Values

Description...

Examples

Example #1 CairoMatrix::transformDistance() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The transformPoint purpose

  • « CairoMatrix::transformDistance
  • CairoMatrix::translate »
  • PHP Manual
  • CairoMatrix
  • The transformPoint purpose

CairoMatrix::transformPoint

(PECL cairo >= 0.1.0)

CairoMatrix::transformPoint — The transformPoint purpose

Description

public CairoMatrix::transformPoint ( float $dx , float $dy ) : array

The method description goes here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

dx

Description...

dy

Description...

Return Values

Description...

Examples

Example #1 CairoMatrix::transformPoint() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The translate purpose

  • « CairoMatrix::transformPoint
  • CairoOperator »
  • PHP Manual
  • CairoMatrix
  • The translate purpose

CairoMatrix::translate

cairo_translate

(PECL cairo >= 0.1.0)

CairoMatrix::translate -- cairo_translate — The translate purpose

Description

Object oriented style (method):

public CairoMatrix::translate ( float $tx , float $ty ) : void

Procedural style:

cairo_translate ( CairoContext $context , float $x , float $y ) : void

Description here.

Warning

This function is currently not documented; only its argument list is available.

Parameters

context

Description...

x

Description...

y

Description...

tx

Description...

ty

Description...

Return Values

Description...

Examples

Example #1 Object oriented style

<?php
/* ... */
?>

The above example will output something similar to:

...

Example #2 Procedural style

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The CairoOperator class

(No version information available, might only be in Git)

Introduction

This is used to set the compositing operator for all cairo drawing operations.

The default operator is CairoOperator::OVER

The operators marked as unbounded modify their destination even outside of the mask layer (that is, their effect is not bound by the mask layer). However, their effect can still be limited by way of clipping.

To keep things simple, the operator descriptions here document the behavior for when both source and destination are either fully transparent or fully opaque. The actual implementation works for translucent layers too. For a more detailed explanation of the effects of each operator, including the mathematical definitions, see http://cairographics.org/operators/.

Class synopsis

CairoOperator {
/* Constants */
const integer CLEAR = 0 ;
const integer SOURCE = 1 ;
const integer OVER = 2 ;
const integer IN = 3 ;
const integer OUT = 4 ;
const integer ATOP = 5 ;
const integer DEST = 6 ;
const integer DEST_OVER = 7 ;
const integer DEST_IN = 8 ;
const integer DEST_OUT = 9 ;
const integer DEST_ATOP = 10 ;
const integer XOR = 11 ;
const integer ADD = 12 ;
const integer SATURATE = 13 ;
}

Predefined Constants

CairoOperator::CLEAR

Clear destination layer (bounded)

CairoOperator::SOURCE

Replace destination layer (bounded)

CairoOperator::OVER

Draw source layer on top of destination layer (bounded)

CairoOperator::IN

Draw source where there was destination content (unbounded)

CairoOperator::OUT

Draw source where there was no destination content (unbounded)

CairoOperator::ATOP

Draw source on top of destination content and only there

CairoOperator::DEST

Ignore the source

CairoOperator::DEST_OVER

Draw destination on top of source

CairoOperator::DEST_IN

Leave destination only where there was source content (unbounded)

CairoOperator::DEST_OUT

Leave destination only where there was no source content

CairoOperator::DEST_ATOP

Leave destination on top of source content and only there (unbounded)

CairoOperator::XOR

Source and destination are shown where there is only one of them

CairoOperator::ADD

Source and destination layers are accumulated

CairoOperator::SATURATE

Like CairoOperator::OVER, but assuming source and dest are disjoint geometries


The CairoPath class

(No version information available, might only be in Git)

Introduction

Note: CairoPath class cannot be instantiated directly, doing so will result in Fatal Error if used or passed

Class synopsis

CairoPath {
}


The CairoPsLevel class

(No version information available, might only be in Git)

Introduction

Class synopsis

CairoPsLevel {
/* Constants */
const integer LEVEL_2 = 0 ;
const integer LEVEL_3 = 1 ;
}

Predefined Constants

CairoPsLevel::LEVEL_2

Description here...

CairoPsLevel::LEVEL_3

Description here...


The CairoSubpixelOrder class

(No version information available, might only be in Git)

Introduction

Class synopsis

CairoSubpixelOrder {
/* Constants */
const integer ORDER_DEFAULT = 0 ;
const integer ORDER_RGB = 1 ;
const integer ORDER_BGR = 2 ;
const integer ORDER_VRGB = 3 ;
const integer ORDER_VBGR = 4 ;
}

Predefined Constants

CairoSubpixelOrder::ORDER_DEFAULT

Description here...

CairoSubpixelOrder::ORDER_RGB

Description here...

CairoSubpixelOrder::ORDER_BGR

Description here...

CairoSubpixelOrder::ORDER_VRGB

Description here...

CairoSubpixelOrder::ORDER_VBGR

Description here...


The CairoSvgVersion class

(No version information available, might only be in Git)

Introduction

Class synopsis

CairoSvgVersion {
/* Constants */
const integer VERSION_1_1 = 0 ;
const integer VERSION_1_2 = 1 ;
}

Predefined Constants

CairoSvgVersion::VERSION_1_1

Description here...

CairoSvgVersion::VERSION_1_2

Description here...


Exchangeable image information

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • 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


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.


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.

Windows only: The mbstring extension must always be enabled. Note that mbstring extension must be loaded prior to EXIF in php.ini.


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" | PHP_INI_ALL |
exif.decode_unicode_motorola | "UCS-2BE" | PHP_INI_ALL |
exif.decode_unicode_intel | "UCS-2LE" | PHP_INI_ALL |
exif.encode_jis | "" | PHP_INI_ALL |
exif.decode_jis_motorola | "JIS" | PHP_INI_ALL |
exif.decode_jis_intel | "JIS" | PHP_INI_ALL |
For further details and definitions of the PHP_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 (integer)
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

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


Determine the type of an image

  • « Exif Functions
  • exif_read_data »
  • PHP Manual
  • Exif Functions
  • Determine the type of an image

exif_imagetype

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

exif_imagetype — Determine the type of an image

Description

exif_imagetype ( string $filename ) : int

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.

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.
5.3.0 | Added icon support.

Predefined Constants

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

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


Reads the EXIF headers from an image file

  • « exif_imagetype
  • exif_tagname »
  • PHP Manual
  • Exif Functions
  • Reads the EXIF headers from an image file

exif_read_data

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

exif_read_data — Reads the EXIF headers from an image file

Description

exif_read_data ( mixed $stream [, string $sections = NULL [, bool $arrays = FALSE [, bool $thumbnail = FALSE ]]] ) : array

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).

Note:

Windows Me/XP can both wipe the Exif headers when connecting to a camera.

Parameters

stream

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.

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.

arrays

Specifies whether or not each section becomes an array. The sections COMPUTED, THUMBNAIL, and COMMENT always become arrays as they may contain values whose names conflict with other sections.

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.

Changelog

Version | Description
7.2.0 | The filename parameter was renamed to stream and now supports both local files or 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 stream 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


Get the header name for an index

  • « exif_read_data
  • exif_thumbnail »
  • PHP Manual
  • Exif Functions
  • Get the header name for an index

exif_tagname

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

exif_tagname — Get the header name for an index

Description

exif_tagname ( int $index ) : string

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


Retrieve the embedded thumbnail of an image

  • « exif_tagname
  • read_exif_data »
  • PHP Manual
  • Exif Functions
  • Retrieve the embedded thumbnail of an image

exif_thumbnail

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

exif_thumbnail — Retrieve the embedded thumbnail of an image

Description

exif_thumbnail ( mixed $stream [, int &$width [, int &$height [, int &$imagetype ]]] ) : string

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

stream

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.

imagetype

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.

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';
}
?>

Changelog

Version | Description
7.2.0 | The filename parameter was renamed to stream and now supports both local files or stream resources.

Notes

Note:

If the stream 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


Alias of exif_read_data

  • « exif_thumbnail
  • GD »
  • PHP Manual
  • Exif Functions
  • Alias of exif_read_data

read_exif_data

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

read_exif_data — Alias of exif_read_data()

Description

This function is an alias of: exif_read_data().

Changelog

Version | Description
7.2.0 | This function alias was deprecated.


Image Processing and GD

  • Introduction
  • 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
    • 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
    • imagecreatefrombmp — Create a new image from 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
    • imagecreatefromgd — Create a new image from GD 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
    • 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
    • imagegd2 — Output GD2 image to browser or file
    • imagegd — Output GD image to browser or file
    • imagegetclip — Get the clipping rectangle
    • 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
    • imagepsbbox — Give the bounding box of a text rectangle using PostScript Type1 fonts
    • imagepsencodefont — Change the character encoding vector of a font
    • imagepsextendfont — Extend or condense a font
    • imagepsfreefont — Free memory used by a PostScript Type 1 font
    • imagepsloadfont — Load a PostScript Type 1 font from file
    • imagepsslantfont — Slant a font
    • imagepstext — Draws a text over an image using PostScript Type1 fonts
    • 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 PNG 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


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 | Available as of GD 2.0.28 and PHP 5.0.1
XBM | TRUE | TRUE |
XPM | TRUE | FALSE | Read support available on Windows as of PHP 5.3.19.
WBMP | TRUE | TRUE |
WebP | TRUE | TRUE | PHP 5.4+
BMP | TRUE | TRUE | Available as of GD 2.1.0 and 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.


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. GIF support is available as of gd-2.0.28.

Note: libgd-2.0.4 or higher is required. As of PHP 5.5 libgd-2.1.0 or higher is required. Alternatively, use the bundled GD library that ships with PHP.

You may wish to enhance GD to handle more image formats.

Supported image formats
Image format | Library to download | Notes
gif |  | Only supported in GD versions newer than gd-2.0.28. Write support is available as of PHP 5.0.1.
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 | » ftp://metalab.unc.edu/pub/Linux/libs/X/!INDEX.html | It's likely you have this library already available, if your system has an installed X-Environment.

You may wish to enhance GD to deal with different fonts. The following font libraries are supported:

Supported font libraries
Font library | Download | Notes
FreeType 1.x | » http://www.freetype.org/ | Support for FreeType 1.x has been removed as of PHP 5.3.0.
FreeType 2 | » http://www.freetype.org/ |
T1lib | » ftp://sunsite.unc.edu/pub/Linux/libs/graphics/) | Support for Postscript Type 1 fonts (Removed as of PHP 7.0.0).


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.

In Windows, you'll include the GD2 DLL php_gd2.dll as an extension in php.ini.

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
jpeg | To enable support for jpeg add --with-jpeg-dir=DIR . Jpeg 6b, 7 or 8 are supported.
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.
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.
webp | To enable support for webp add --with-vpx-dir=DIR . Available as of PHP 5.4.0. As of PHP 7.0.0 --with-webp-dir=DIR has to be added, i.e. support for libvpx has been removed in favor of libwebp.

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.
T1lib | To enable support for T1lib (Postscript Type 1 fonts) add --with-t1lib[=DIR] (Removed as of PHP 7.0.0).
Native TrueType string function | To enable support for native TrueType string function add --enable-gd-native-ttf . (Effectless as of PHP 5.5.0; 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" | PHP_INI_ALL | Available since PHP 5.1.3.
For further details and definitions of the PHP_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() |
gd font | Font resource internally created by imageloadfont() |
gd PS font | PostScript Type 1 font resource, returned by imagepsloadfont() | Removed as of PHP 7.0.0.
gd PS encoding | PostScript Type 1 encoding resource, returned by imagepsencodefont() | Removed as of PHP 7.0.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. (Available as of PHP 5.2.4)
GD_MAJOR_VERSION (integer)
The GD major version PHP was compiled against. (Available as of PHP 5.2.4)
GD_MINOR_VERSION (integer)
The GD minor version PHP was compiled against. (Available as of PHP 5.2.4)
GD_RELEASE_VERSION (integer)
The GD release version PHP was compiled against. (Available as of PHP 5.2.4)
GD_EXTRA_VERSION (string)
The GD "extra" version (beta/rc..) PHP was compiled against. (Available as of PHP 5.2.4)
GD_BUNDLED (integer)
When the bundled version of GD is used this is 1 otherwise its set to 0.
IMG_BMP (integer)
Used as a return value by imagetypes()
IMG_GIF (integer)
Used as a return value by imagetypes()
IMG_JPG (integer)
Used as a return value by imagetypes()
IMG_JPEG (integer)
Used as a return value by imagetypes()

Note:

This constant has the same value as IMG_JPG

IMG_PNG (integer)
Used as a return value by imagetypes()
IMG_WBMP (integer)
Used as a return value by imagetypes()
IMG_XPM (integer)
Used as a return value by imagetypes()
IMG_WEBP (integer)
Used as a return value by imagetypes() Available as of PHP 5.6.25 and PHP 7.0.10, respectively.
IMG_COLOR_TILED (integer)
Special color option which can be used instead of a color allocated with imagecolorallocate() or imagecolorallocatealpha().
IMG_COLOR_STYLED (integer)
Special color option which can be used instead of a color allocated with imagecolorallocate() or imagecolorallocatealpha().
IMG_COLOR_BRUSHED (integer)
Special color option which can be used instead of a color allocated with imagecolorallocate() or imagecolorallocatealpha().
IMG_COLOR_STYLEDBRUSHED (integer)
Special color option which can be used instead of a color allocated with imagecolorallocate() or imagecolorallocatealpha().
IMG_COLOR_TRANSPARENT (integer)
Special color option which can be used instead of a color allocated with imagecolorallocate() or imagecolorallocatealpha().
IMG_AFFINE_TRANSLATE (integer)
An affine transformation type constant used by the imageaffinematrixget() function.
IMG_AFFINE_SCALE (integer)
An affine transformation type constant used by the imageaffinematrixget() function.
IMG_AFFINE_ROTATE (integer)
An affine transformation type constant used by the imageaffinematrixget() function.
IMG_AFFINE_SHEAR_HORIZONTAL (integer)
An affine transformation type constant used by the imageaffinematrixget() function.
IMG_AFFINE_SHEAR_VERTICAL (integer)
An affine transformation type constant used by the imageaffinematrixget() function.
IMG_ARC_ROUNDED (integer)
A style constant used by the imagefilledarc() function.

Note:

This constant has the same value as IMG_ARC_PIE

IMG_ARC_PIE (integer)
A style constant used by the imagefilledarc() function.
IMG_ARC_CHORD (integer)
A style constant used by the imagefilledarc() function.
IMG_ARC_NOFILL (integer)
A style constant used by the imagefilledarc() function.
IMG_ARC_EDGED (integer)
A style constant used by the imagefilledarc() function.
IMG_GD2_RAW (integer)
A type constant used by the imagegd2() function.
IMG_GD2_COMPRESSED (integer)
A type constant used by the imagegd2() function.
IMG_EFFECT_REPLACE (integer)
Alpha blending effect used by the imagelayereffect() function.
IMG_EFFECT_ALPHABLEND (integer)
Alpha blending effect used by the imagelayereffect() function.
IMG_EFFECT_NORMAL (integer)
Alpha blending effect used by the imagelayereffect() function.
IMG_EFFECT_OVERLAY (integer)
Alpha blending effect used by the imagelayereffect() function.
IMG_EFFECT_MULTIPLY (integer)
Alpha blending effect used by the imagelayereffect() function.
IMG_FILTER_NEGATE (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_GRAYSCALE (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_BRIGHTNESS (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_CONTRAST (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_COLORIZE (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_EDGEDETECT (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_GAUSSIAN_BLUR (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_SELECTIVE_BLUR (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_EMBOSS (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_MEAN_REMOVAL (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_SMOOTH (integer)
Special GD filter used by the imagefilter() function.
IMG_FILTER_PIXELATE (integer)
Special GD filter used by the imagefilter() function. (Available as of PHP 5.3.0)
IMG_FILTER_SCATTER (integer)
Special GD filter used by the imagefilter() function. (Available as of PHP 7.4.0)
IMAGETYPE_GIF (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JPEG (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JPEG2000 (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_PNG (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_SWF (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_PSD (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_BMP (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_WBMP (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_XBM (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_TIFF_II (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_TIFF_MM (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_IFF (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JB2 (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JPC (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JP2 (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JPX (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_SWC (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_ICO (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions. (Available as of PHP 5.3.0)
IMAGETYPE_WEBP (integer)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions. (Available as of PHP 7.1.0)
PNG_NO_FILTER (integer)
A special PNG filter, used by the imagepng() function.
PNG_FILTER_NONE (integer)
A special PNG filter, used by the imagepng() function.
PNG_FILTER_SUB (integer)
A special PNG filter, used by the imagepng() function.
PNG_FILTER_UP (integer)
A special PNG filter, used by the imagepng() function.
PNG_FILTER_AVG (integer)
A special PNG filter, used by the imagepng() function.
PNG_FILTER_PAETH (integer)
A special PNG filter, used by the imagepng() function.
PNG_ALL_FILTERS (integer)
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.


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);
imagedestroy($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 and free memory
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
Adding watermarks to images using alpha channels
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

  • « Adding watermarks to images using alpha channels
  • GD and Image Functions »
  • PHP Manual
  • Examples
  • Using imagecopymerge to create a translucent watermark

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 and free memory
imagepng($im, 'photo_stamp.png');
imagedestroy($im);

?>
Using imagecopymerge() to create a translucent watermark
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

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
  • 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
  • imagecreatefrombmp — Create a new image from 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
  • imagecreatefromgd — Create a new image from GD 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
  • 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
  • imagegd2 — Output GD2 image to browser or file
  • imagegd — Output GD image to browser or file
  • imagegetclip — Get the clipping rectangle
  • 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
  • imagepsbbox — Give the bounding box of a text rectangle using PostScript Type1 fonts
  • imagepsencodefont — Change the character encoding vector of a font
  • imagepsextendfont — Extend or condense a font
  • imagepsfreefont — Free memory used by a PostScript Type 1 font
  • imagepsloadfont — Load a PostScript Type 1 font from file
  • imagepsslantfont — Slant a font
  • imagepstext — Draws a text over an image using PostScript Type1 fonts
  • 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 PNG 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


Retrieve information about the currently installed GD library

  • « GD and Image Functions
  • getimagesize »
  • PHP Manual
  • GD and Image Functions
  • Retrieve information about the currently installed GD library

gd_info

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

gd_info — Retrieve information about the currently installed GD library

Description

gd_info ( void ) : array

Gets information about the version and capabilities of the installed GD library.

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 | boolean 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.
T1Lib Support | boolean value. TRUE if T1Lib support is included.
GIF Read Support | boolean value. TRUE if support for reading GIF images is included.
GIF Create Support | boolean value. TRUE if support for creating GIF images is included.
JPEG Support | boolean value. TRUE if JPEG support is included.
PNG Support | boolean value. TRUE if PNG support is included.
WBMP Support | boolean value. TRUE if WBMP support is included.
XBM Support | boolean value. TRUE if XBM support is included.
WebP Support | boolean value. TRUE if WebP support is included.

Note:

Previous to PHP 5.3.0, the JPEG Support attribute was named JPG Support.

Changelog

Version | Description
5.6.12 | WebP Support added.
5.3.0 | JPG Support attribute renamed to JPEG Support.

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)
  ["T1Lib 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)
}

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
  • imagetypes() - Return the image types supported by this PHP build


Get the size of an image

  • « gd_info
  • getimagesizefromstring »
  • PHP Manual
  • GD and Image Functions
  • Get the size of an image

getimagesize

(PHP 4, PHP 5, PHP 7)

getimagesize — Get the size of an image

Description

getimagesize ( string $filename [, array &$imageinfo ] ) : array

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 imageinfo 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.

imageinfo

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 imageinfo 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.

Index 2 is one of the IMAGETYPE_XXX 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.

Changelog

Version | Description
7.1.0 | Added WebP support.
5.3.0 | Added icon support.
5.2.3 | Read errors generated by this function downgraded to E_NOTICE from E_WARNING.

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


Get the size of an image from a string

  • « getimagesize
  • image_type_to_extension »
  • PHP Manual
  • GD and Image Functions
  • Get the size of an image from a string

getimagesizefromstring

(PHP 5 >= 5.4.0, PHP 7)

getimagesizefromstring — Get the size of an image from a string

Description

getimagesizefromstring ( string $imagedata [, array &$imageinfo ] ) : array

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

imagedata

The image data, as a string.

imageinfo

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


Get file extension for image type

  • « getimagesizefromstring
  • image_type_to_mime_type »
  • PHP Manual
  • GD and Image Functions
  • Get file extension for image type

image_type_to_extension

(PHP 5 >= 5.2.0, PHP 7)

image_type_to_extension — Get file extension for image type

Description

image_type_to_extension ( int $imagetype [, bool $include_dot = TRUE ] ) : string

Returns the extension for the given IMAGETYPE_XXX constant.

Parameters

imagetype

One of the IMAGETYPE_XXX 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.

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));
imagedestroy($im);
?>

Notes

Note:

This function does not require the GD image library.


Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype

  • « image_type_to_extension
  • image2wbmp »
  • PHP Manual
  • GD and Image Functions
  • Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype

image_type_to_mime_type

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

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 $imagetype ) : string

The image_type_to_mime_type() function will determine the Mime-Type for an IMAGETYPE constant.

Parameters

imagetype

One of the IMAGETYPE_XXX constants.

Return Values

The returned values are as follows

Returned values Constants
imagetype | 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

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


Output image to browser or file

  • « image_type_to_mime_type
  • imageaffine »
  • PHP Manual
  • GD and Image Functions
  • Output image to browser or file

image2wbmp

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

image2wbmp — Output image to browser or file

Warning

image2wbmp() is deprecated as of PHP 7.3.0, and will be removed in the next major version. Use imagewbmp() instead.

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
imagedestroy($image);
?>

See Also

  • imagewbmp() - Output image to browser or file


Return an image containing the affine transformed src image, using an optional clipping area

  • « image2wbmp
  • imageaffinematrixconcat »
  • PHP Manual
  • GD and Image Functions
  • Return an image containing the affine transformed src image, using an optional clipping area

imageaffine

(PHP 5 >= 5.5.0, PHP 7)

imageaffine — Return an image containing the affine transformed src image, using an optional clipping area

Description

imageaffine ( resource $image , array $affine [, array $clip ] ) : resource

Warning

This function is currently not documented; only its argument list is available.

Parameters

image

An image resource, 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".

Return Values

Return affined image resource on success or FALSE on failure.


Concatenate two affine transformation matrices

  • « imageaffine
  • imageaffinematrixget »
  • PHP Manual
  • GD and Image Functions
  • Concatenate two affine transformation matrices

imageaffinematrixconcat

(PHP 5 >= 5.5.0, PHP 7)

imageaffinematrixconcat — Concatenate two affine transformation matrices

Description

imageaffinematrixconcat ( array $m1 , array $m2 ) : array

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

m1

An affine transformation matrix (an array with keys 0 to 5 and float values).

m2

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


Get an affine transformation matrix

  • « imageaffinematrixconcat
  • imagealphablending »
  • PHP Manual
  • GD and Image Functions
  • Get an affine transformation matrix

imageaffinematrixget

(PHP 5 >= 5.5.0, PHP 7)

imageaffinematrixget — Get an affine transformation matrix

Description

imageaffinematrixget ( int $type [, mixed $options ] ) : array

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


Set the blending mode for an image

  • « imageaffinematrixget
  • imageantialias »
  • PHP Manual
  • GD and Image Functions
  • Set the blending mode for an image

imagealphablending

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

imagealphablending — Set the blending mode for an image

Description

imagealphablending ( resource $image , bool $blendmode ) : bool

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

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

blendmode

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

Returns TRUE on success or FALSE on failure.

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);
imagedestroy($im);
?>


Should antialias functions be used or not

  • « imagealphablending
  • imagearc »
  • PHP Manual
  • GD and Image Functions
  • Should antialias functions be used or not

imageantialias

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

imageantialias — Should antialias functions be used or not

Description

imageantialias ( resource $image , bool $enabled ) : bool

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

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

enabled

Whether to enable antialiasing or not.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
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);
imagedestroy($aa);
imagedestroy($normal);
?>

The above example will output something similar to:

Output of example : A comparison of two lines, one with anti-aliasing switched on

See Also

  • imagecreatetruecolor() - Create a new true color image


Draws an arc

  • « imageantialias
  • imagebmp »
  • PHP Manual
  • GD and Image Functions
  • Draws an arc

imagearc

(PHP 4, PHP 5, PHP 7)

imagearc — Draws an arc

Description

imagearc ( resource $image , int $cx , int $cy , int $width , int $height , int $start , int $end , int $color ) : bool

imagearc() draws an arc of circle centered at the given coordinates.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

cx

x-coordinate of the center.

cy

y-coordinate of the center.

width

The arc width.

height

The arc height.

start

The arc start angle, in degrees.

end

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

Returns TRUE on success or FALSE on failure.

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);

// free memory
imagedestroy($img);

?>

The above example will output something similar to:

Output of example : Drawing a circle with imagearc()

See Also

  • imagefilledarc() - Draw a partial arc and fill it
  • imageellipse() - Draw an ellipse
  • imagefilledellipse() - Draw a filled ellipse


Output a BMP image to browser or file

  • « imagearc
  • imagechar »
  • PHP Manual
  • GD and Image Functions
  • Output a BMP image to browser or file

imagebmp

(PHP 7 >= 7.2.0)

imagebmp — Output a BMP image to browser or file

Description

imagebmp ( resource $image [, mixed $to = NULL [, bool $compressed = TRUE ]] ) : bool

Outputs or saves a BMP version of the given image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

to

The path or an open stream resource (which is automatically being closed after this function returns) to save the file to. If not set or NULL, the raw image stream will be outputted 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.

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');

// Free up memory
imagedestroy($im);
?>


Draw a character horizontally

  • « imagebmp
  • imagecharup »
  • PHP Manual
  • GD and Image Functions
  • Draw a character horizontally

imagechar

(PHP 4, PHP 5, PHP 7)

imagechar — Draw a character horizontally

Description

imagechar ( resource $image , int $font , int $x , int $y , string $c , int $color ) : bool

imagechar() draws the first character of c in the image identified by image with its upper-left at x,y (top left is 0, 0) with the color color.

Parameters

image

An image resource, 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 any of your own font identifiers registered with imageloadfont().

x

x-coordinate of the start.

y

y-coordinate of the start.

c

The character to draw.

color

A color identifier created with imagecolorallocate().

Return Values

Returns TRUE on success or FALSE on failure.

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:

Output of example : imagechar()

See Also

  • imagecharup() - Draw a character vertically
  • imageloadfont() - Load a new font


Draw a character vertically

  • « imagechar
  • imagecolorallocate »
  • PHP Manual
  • GD and Image Functions
  • Draw a character vertically

imagecharup

(PHP 4, PHP 5, PHP 7)

imagecharup — Draw a character vertically

Description

imagecharup ( resource $image , int $font , int $x , int $y , string $c , int $color ) : bool

Draws the character c vertically at the specified coordinate on the given image.

Parameters

image

An image resource, 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 any of your own font identifiers registered with imageloadfont().

x

x-coordinate of the start.

y

y-coordinate of the start.

c

The character to draw.

color

A color identifier created with imagecolorallocate().

Return Values

Returns TRUE on success or FALSE on failure.

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:

Output of example : imagecharup()

See Also

  • imagechar() - Draw a character horizontally
  • imageloadfont() - Load a new font


Allocate a color for an image

  • « imagecharup
  • imagecolorallocatealpha »
  • PHP Manual
  • GD and Image Functions
  • Allocate a color for an image

imagecolorallocate

(PHP 4, PHP 5, PHP 7)

imagecolorallocate — Allocate a color for an image

Description

imagecolorallocate ( resource $image , int $red , int $green , int $blue ) : int

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

An image resource, 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
5.1.3 | Returns FALSE if the allocation failed. Previously -1 was returned.

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


Allocate a color for an image

  • « imagecolorallocate
  • imagecolorat »
  • PHP Manual
  • GD and Image Functions
  • Allocate a color for an image

imagecolorallocatealpha

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

imagecolorallocatealpha — Allocate a color for an image

Description

imagecolorallocatealpha ( resource $image , int $red , int $green , int $blue , int $alpha ) : int

imagecolorallocatealpha() behaves identically to imagecolorallocate() with the addition of the transparency parameter alpha.

Parameters

image

An image resource, 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
5.1.3 | Returns FALSE if the allocation failed. Previously -1 was returned.

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);
imagedestroy($image);
?>

The above example will output something similar to:

Output of example : Example of using imagecolorallocatealpha()

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


Get the index of the color of a pixel

  • « imagecolorallocatealpha
  • imagecolorclosest »
  • PHP Manual
  • GD and Image Functions
  • Get the index of the color of a pixel

imagecolorat

(PHP 4, PHP 5, PHP 7)

imagecolorat — Get the index of the color of a pixel

Description

imagecolorat ( resource $image , int $x , int $y ) : int

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

An image resource, 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.

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


Get the index of the closest color to the specified color

  • « imagecolorat
  • imagecolorclosestalpha »
  • PHP Manual
  • GD and Image Functions
  • Get the index of the closest color to the specified color

imagecolorclosest

(PHP 4, PHP 5, PHP 7)

imagecolorclosest — Get the index of the closest color to the specified color

Description

imagecolorclosest ( resource $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

An image resource, 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

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";
}

imagedestroy($im);
?>

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


Get the index of the closest color to the specified color + alpha

  • « imagecolorclosest
  • imagecolorclosesthwb »
  • PHP Manual
  • GD and Image Functions
  • Get the index of the closest color to the specified color + alpha

imagecolorclosestalpha

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

imagecolorclosestalpha — Get the index of the closest color to the specified color + alpha

Description

imagecolorclosestalpha ( resource $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

An image resource, 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";
}

imagedestroy($im);
?>

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


Get the index of the color which has the hue, white and blackness

  • « imagecolorclosestalpha
  • imagecolordeallocate »
  • PHP Manual
  • GD and Image Functions
  • Get the index of the color which has the hue, white and blackness

imagecolorclosesthwb

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

imagecolorclosesthwb — Get the index of the color which has the hue, white and blackness

Description

imagecolorclosesthwb ( resource $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

An image resource, 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
5.3.0 | This function is now available on Windows

Examples

Example #1 Example of using imagecolorclosesthwb()

<?php
$im = imagecreatefromgif('php.gif');

echo 'HWB: ' . imagecolorclosesthwb($im, 116, 115, 152);

imagedestroy($im);
?>

The above example will output something similar to:

HWB: 33

See Also

  • imagecolorclosest() - Get the index of the closest color to the specified color


De-allocate a color for an image

  • « imagecolorclosesthwb
  • imagecolorexact »
  • PHP Manual
  • GD and Image Functions
  • De-allocate a color for an image

imagecolordeallocate

(PHP 4, PHP 5, PHP 7)

imagecolordeallocate — De-allocate a color for an image

Description

imagecolordeallocate ( resource $image , int $color ) : bool

De-allocates a color previously allocated with imagecolorallocate() or imagecolorallocatealpha().

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

color

The color identifier.

Return Values

Returns TRUE on success or FALSE on failure.

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


Get the index of the specified color

  • « imagecolordeallocate
  • imagecolorexactalpha »
  • PHP Manual
  • GD and Image Functions
  • Get the index of the specified color

imagecolorexact

(PHP 4, PHP 5, PHP 7)

imagecolorexact — Get the index of the specified color

Description

imagecolorexact ( resource $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

An image resource, 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.

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);

// Free from memory
imagedestroy($im);
?>

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


Get the index of the specified color + alpha

  • « imagecolorexact
  • imagecolormatch »
  • PHP Manual
  • GD and Image Functions
  • Get the index of the specified color + alpha

imagecolorexactalpha

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

imagecolorexactalpha — Get the index of the specified color + alpha

Description

imagecolorexactalpha ( resource $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

An image resource, 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.

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);

// Free from memory
imagedestroy($im);
?>

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


Makes the colors of the palette version of an image more closely match the true color version

  • « imagecolorexactalpha
  • imagecolorresolve »
  • PHP Manual
  • GD and Image Functions
  • Makes the colors of the palette version of an image more closely match the true color version

imagecolormatch

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

imagecolormatch — Makes the colors of the palette version of an image more closely match the true color version

Description

imagecolormatch ( resource $image1 , resource $image2 ) : bool

Makes the colors of the palette version of an image more closely match the true color version.

Parameters

image1

A truecolor image link resource.

image2

A palette image link resource pointing to an image that has the same size as image1.

Return Values

Returns TRUE on success or FALSE on failure.

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);

// Free from memory
imagedestroy($im1);
imagedestroy($im2);
?>

See Also

  • imagecreatetruecolor() - Create a new true color image


Get the index of the specified color or its closest possible alternative

  • « imagecolormatch
  • imagecolorresolvealpha »
  • PHP Manual
  • GD and Image Functions
  • Get the index of the specified color or its closest possible alternative

imagecolorresolve

(PHP 4, PHP 5, PHP 7)

imagecolorresolve — Get the index of the specified color or its closest possible alternative

Description

imagecolorresolve ( resource $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

An image resource, 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.

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);

imagedestroy($im);
?>

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


Get the index of the specified color + alpha or its closest possible alternative

  • « imagecolorresolve
  • imagecolorset »
  • PHP Manual
  • GD and Image Functions
  • Get the index of the specified color + alpha or its closest possible alternative

imagecolorresolvealpha

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

imagecolorresolvealpha — Get the index of the specified color + alpha or its closest possible alternative

Description

imagecolorresolvealpha ( resource $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

An image resource, 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.

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);

imagedestroy($im);
?>

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


Set the color for the specified palette index

  • « imagecolorresolvealpha
  • imagecolorsforindex »
  • PHP Manual
  • GD and Image Functions
  • Set the color for the specified palette index

imagecolorset

(PHP 4, PHP 5, PHP 7)

imagecolorset — Set the color for the specified palette index

Description

imagecolorset ( resource $image , int $index , int $red , int $green , int $blue [, int $alpha = 0 ] ) : void

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

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

index

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

No value is returned.

Changelog

Version | Description
5.4.0 | The alpha parameter was added.

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 backgrund to be blue
imagecolorset($im, $bg, 0, 0, 255);

// Output the image to the browser
header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);
?>

See Also

  • imagecolorat() - Get the index of the color of a pixel


Get the colors for an index

  • « imagecolorset
  • imagecolorstotal »
  • PHP Manual
  • GD and Image Functions
  • Get the colors for an index

imagecolorsforindex

(PHP 4, PHP 5, PHP 7)

imagecolorsforindex — Get the colors for an index

Description

imagecolorsforindex ( resource $image , int $index ) : array

Gets the color for a specified index.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

index

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.

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


Find out the number of colors in an image's palette

  • « imagecolorsforindex
  • imagecolortransparent »
  • PHP Manual
  • GD and Image Functions
  • Find out the number of colors in an image's palette

imagecolorstotal

(PHP 4, PHP 5, PHP 7)

imagecolorstotal — Find out the number of colors in an image's palette

Description

imagecolorstotal ( resource $image ) : int

Returns the number of colors in an image palette.

Parameters

image

An image resource, 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.

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);

// Free image
imagedestroy($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


Define a color as transparent

  • « imagecolorstotal
  • imageconvolution »
  • PHP Manual
  • GD and Image Functions
  • Define a color as transparent

imagecolortransparent

(PHP 4, PHP 5, PHP 7)

imagecolortransparent — Define a color as transparent

Description

imagecolortransparent ( resource $image ) : int
imagecolortransparent ( resource $image , int $color ) : int

Gets or sets the transparent color in the given image.

Parameters

image

An image resource, 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 not specified, and the image has no transparent color, the returned identifier will be -1.

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');
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : imagecolortransparent()

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.


Apply a 3x3 convolution matrix, using coefficient and offset

  • « imagecolortransparent
  • imagecopy »
  • PHP Manual
  • GD and Image Functions
  • Apply a 3x3 convolution matrix, using coefficient and offset

imageconvolution

(PHP 5 >= 5.1.0, PHP 7)

imageconvolution — Apply a 3x3 convolution matrix, using coefficient and offset

Description

imageconvolution ( resource $image , array $matrix , float $div , float $offset ) : bool

Applies a convolution matrix on the image, using the given coefficient and offset.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

matrix

A 3x3 matrix: an array of three arrays of three floats.

div

The divisor of the result of the convolution, used for normalization.

offset

Color offset.

Return Values

Returns TRUE on success or FALSE on failure.

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:

Output of example : Embossing the PHP.net logo

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:

Output of example : Gaussian blur

Notes

This function requires GD 2.1.0 or higher.

See Also

  • imagefilter() - Applies a filter to an image


Copy part of an image

  • « imageconvolution
  • imagecopymerge »
  • PHP Manual
  • GD and Image Functions
  • Copy part of an image

imagecopy

(PHP 4, PHP 5, PHP 7)

imagecopy — Copy part of an image

Description

imagecopy ( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x , int $src_y , int $src_w , int $src_h ) : bool

Copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the x,y coordinates, dst_x and dst_y.

Parameters

dst_im

Destination image link resource.

src_im

Source image link 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_w

Source width.

src_h

Source height.

Return Values

Returns TRUE on success or FALSE on failure.

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);

imagedestroy($dest);
imagedestroy($src);
?>

The above example will output something similar to:

Output of example : Cropping the PHP.net logo


Copy and merge part of an image

  • « imagecopy
  • imagecopymergegray »
  • PHP Manual
  • GD and Image Functions
  • Copy and merge part of an image

imagecopymerge

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

imagecopymerge — Copy and merge part of an image

Description

imagecopymerge ( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x , int $src_y , int $src_w , int $src_h , int $pct ) : bool

Copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the x,y coordinates, dst_x and dst_y.

Parameters

dst_im

Destination image link resource.

src_im

Source image link 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_w

Source width.

src_h

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

Returns TRUE on success or FALSE on failure.

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 and free from memory
header('Content-Type: image/gif');
imagegif($dest);

imagedestroy($dest);
imagedestroy($src);
?>


Copy and merge part of an image with gray scale

  • « imagecopymerge
  • imagecopyresampled »
  • PHP Manual
  • GD and Image Functions
  • Copy and merge part of an image with gray scale

imagecopymergegray

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

imagecopymergegray — Copy and merge part of an image with gray scale

Description

imagecopymergegray ( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x , int $src_y , int $src_w , int $src_h , int $pct ) : bool

imagecopymergegray() copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. 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_im

Destination image link resource.

src_im

Source image link 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_w

Source width.

src_h

Source height.

pct

The src_im 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

Returns TRUE on success or FALSE on failure.

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 and free from memory
header('Content-Type: image/gif');
imagegif($dest);

imagedestroy($dest);
imagedestroy($src);
?>


Copy and resize part of an image with resampling

  • « imagecopymergegray
  • imagecopyresized »
  • PHP Manual
  • GD and Image Functions
  • Copy and resize part of an image with resampling

imagecopyresampled

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

imagecopyresampled — Copy and resize part of an image with resampling

Description

imagecopyresampled ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h ) : bool

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_w and height src_h at position (src_x,src_y) and place it in a rectangular area of dst_image of width dst_w and height dst_h 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 link resource.

src_image

Source image link 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_w

Destination width.

dst_h

Destination height.

src_w

Source width.

src_h

Source height.

Return Values

Returns TRUE on success or FALSE on failure.

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:

Output of example : Simple example

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:

Output of example : Resampling an image proportionally

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


Copy and resize part of an image

  • « imagecopyresampled
  • imagecreate »
  • PHP Manual
  • GD and Image Functions
  • Copy and resize part of an image

imagecopyresized

(PHP 4, PHP 5, PHP 7)

imagecopyresized — Copy and resize part of an image

Description

imagecopyresized ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h ) : bool

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_w and height src_h at position (src_x,src_y) and place it in a rectangular area of dst_image of width dst_w and height dst_h 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 link resource.

src_image

Source image link 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_w

Destination width.

dst_h

Destination height.

src_w

Source width.

src_h

Source height.

Return Values

Returns TRUE on success or FALSE on failure.

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:

Output of example : Resizing an image

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


Create a new palette based image

  • « imagecopyresized
  • imagecreatefrombmp »
  • PHP Manual
  • GD and Image Functions
  • Create a new palette based image

imagecreate

(PHP 4, PHP 5, PHP 7)

imagecreate — Create a new palette based image

Description

imagecreate ( int $width , int $height ) : resource

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 resource identifier on success, FALSE on errors.

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);
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : Creating a new GD image stream and outputting an image.

See Also

  • imagedestroy() - Destroy an image
  • imagecreatetruecolor() - Create a new true color image


Create a new image from file or URL

  • « imagecreate
  • imagecreatefromgd2 »
  • PHP Manual
  • GD and Image Functions
  • Create a new image from file or URL

imagecreatefrombmp

(PHP 7 >= 7.2.0)

imagecreatefrombmp — Create a new image from file or URL

Description

imagecreatefrombmp ( string $filename ) : resource

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 resource identifier on success, FALSE on errors.

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');
imagedestroy($im);
?>


Create a new image from GD2 file or URL

  • « imagecreatefrombmp
  • imagecreatefromgd2part »
  • PHP Manual
  • GD and Image Functions
  • Create a new image from GD2 file or URL

imagecreatefromgd2

(PHP 4 >= 4.0.7, PHP 5, PHP 7)

imagecreatefromgd2 — Create a new image from GD2 file or URL

Description

imagecreatefromgd2 ( string $filename ) : resource

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 resource identifier on success, FALSE on errors.

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 PHP 5+
if(function_exists('imagefilter'))
{
    imagefilter($im, IMG_FILTER_NEGATE);
}

// Save the image
imagegd2($im, './test_updated.gd2');
imagedestroy($im);
?>


Create a new image from a given part of GD2 file or URL

  • « imagecreatefromgd2
  • imagecreatefromgd »
  • PHP Manual
  • GD and Image Functions
  • Create a new image from a given part of GD2 file or URL

imagecreatefromgd2part

(PHP 4 >= 4.0.7, PHP 5, PHP 7)

imagecreatefromgd2part — Create a new image from a given part of GD2 file or URL

Description

imagecreatefromgd2part ( string $filename , int $srcX , int $srcY , int $width , int $height ) : resource

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.

srcX

x-coordinate of source point.

srcY

y-coordinate of source point.

width

Source width.

height

Source height.

Return Values

Returns an image resource identifier on success, FALSE on errors.

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 PHP 5+
if(function_exists('imagefilter'))
{
    imagefilter($im, IMG_FILTER_EMBOSS);
}

// Save optimized image
imagegd2($im, './test_emboss.gd2');
imagedestroy($im);
?>


Create a new image from GD file or URL

  • « imagecreatefromgd2part
  • imagecreatefromgif »
  • PHP Manual
  • GD and Image Functions
  • Create a new image from GD file or URL

imagecreatefromgd

(PHP 4 >= 4.0.7, PHP 5, PHP 7)

imagecreatefromgd — Create a new image from GD file or URL

Description

imagecreatefromgd ( string $filename ) : resource

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 resource identifier on success, FALSE on errors.

Examples

Example #1 imagecreatefromgd() example

<?php
// Load the gd image
$im = @imagecreatefromgd('./test.gd');

// Test if the image was loaded
if(!is_resource($im))
{
     die('Unable to load gd image!');
}

// Do image operations here

// Save the image
imagegd($im, './test_updated.gd');
imagedestroy($im);
?>


Create a new image from file or URL

  • « imagecreatefromgd
  • imagecreatefromjpeg »
  • PHP Manual
  • GD and Image Functions
  • Create a new image from file or URL

imagecreatefromgif

(PHP 4, PHP 5, PHP 7)

imagecreatefromgif — Create a new image from file or URL

Description

imagecreatefromgif ( string $filename ) : resource

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 resource pointer. 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 resource identifier on success, FALSE on errors.

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);
imagedestroy($img);
?>

The above example will output something similar to:

Output of example : Example to handle an error during loading of a GIF

Notes

Note:

GIF support was removed from the GD library in Version 1.6, and added back in Version 2.0.28. This function is not available between these versions.


Create a new image from file or URL

  • « imagecreatefromgif
  • imagecreatefrompng »
  • PHP Manual
  • GD and Image Functions
  • Create a new image from file or URL

imagecreatefromjpeg

(PHP 4, PHP 5, PHP 7)

imagecreatefromjpeg — Create a new image from file or URL

Description

imagecreatefromjpeg ( string $filename ) : resource

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 resource identifier on success, FALSE on errors.

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);
imagedestroy($img);
?>

The above example will output something similar to:

Output of example : Example to handle an error during loading of a JPEG


Create a new image from file or URL

  • « imagecreatefromjpeg
  • imagecreatefromstring »
  • PHP Manual
  • GD and Image Functions
  • Create a new image from file or URL

imagecreatefrompng

(PHP 4, PHP 5, PHP 7)

imagecreatefrompng — Create a new image from file or URL

Description

imagecreatefrompng ( string $filename ) : resource

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 resource identifier on success, FALSE on errors.

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);
imagedestroy($img);
?>

The above example will output something similar to:


Create a new image from the image stream in the string

  • « imagecreatefrompng
  • imagecreatefromwbmp »
  • PHP Manual
  • GD and Image Functions
  • Create a new image from the image stream in the string

imagecreatefromstring

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

imagecreatefromstring — Create a new image from the image stream in the string

Description

imagecreatefromstring ( string $image ) : resource

imagecreatefromstring() returns an image identifier representing the image obtained from the given image. These types will be automatically detected if your build of PHP supports them: JPEG, PNG, GIF, BMP, WBMP, and GD2.

Parameters

image

A string containing the image data.

Return Values

An image resource 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.

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);
    imagedestroy($im);
}
else {
    echo 'An error occurred.';
}
?>

The above example will output something similar to:

Output of example : imagecreatefromstring()

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


Create a new image from file or URL

  • « imagecreatefromstring
  • imagecreatefromwebp »
  • PHP Manual
  • GD and Image Functions
  • Create a new image from file or URL

imagecreatefromwbmp

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

imagecreatefromwbmp — Create a new image from file or URL

Description

imagecreatefromwbmp ( string $filename ) : resource

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 resource identifier on success, FALSE on errors.

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);
imagedestroy($img);
?>


Create a new image from file or URL

  • « imagecreatefromwbmp
  • imagecreatefromxbm »
  • PHP Manual
  • GD and Image Functions
  • Create a new image from file or URL

imagecreatefromwebp

(PHP 5 >= 5.4.0, PHP 7)

imagecreatefromwebp — Create a new image from file or URL

Description

imagecreatefromwebp ( string $filename ) : resource

imagecreatefromwebp() 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 WebP image.

Return Values

Returns an image resource identifier on success, FALSE on errors.

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);
imagedestroy($im);
?>


Create a new image from file or URL

  • « imagecreatefromwebp
  • imagecreatefromxpm »
  • PHP Manual
  • GD and Image Functions
  • Create a new image from file or URL

imagecreatefromxbm

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

imagecreatefromxbm — Create a new image from file or URL

Description

imagecreatefromxbm ( string $filename ) : resource

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 resource identifier on success, FALSE on errors.

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');
imagedestroy($xbm);
?>


Create a new image from file or URL

  • « imagecreatefromxbm
  • imagecreatetruecolor »
  • PHP Manual
  • GD and Image Functions
  • Create a new image from file or URL

imagecreatefromxpm

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

imagecreatefromxpm — Create a new image from file or URL

Description

imagecreatefromxpm ( string $filename ) : resource

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 resource identifier on success, FALSE on errors.

Changelog

Version | Description
5.3.19 | imagecreatefromxpm() is available on Windows.

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);
imagedestroy($xpm);
?>


Create a new true color image

  • « imagecreatefromxpm
  • imagecrop »
  • PHP Manual
  • GD and Image Functions
  • Create a new true color image

imagecreatetruecolor

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

imagecreatetruecolor — Create a new true color image

Description

imagecreatetruecolor ( int $width , int $height ) : resource

imagecreatetruecolor() returns an image identifier representing a black image of the specified size.

Parameters

width

Image width.

height

Image height.

Return Values

Returns an image resource identifier on success, FALSE on errors.

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);
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : Creating a new GD image stream and outputting an image.

See Also

  • imagedestroy() - Destroy an image
  • imagecreate() - Create a new palette based image


Crop an image to the given rectangle

  • « imagecreatetruecolor
  • imagecropauto »
  • PHP Manual
  • GD and Image Functions
  • Crop an image to the given rectangle

imagecrop

(PHP 5 >= 5.5.0, PHP 7)

imagecrop — Crop an image to the given rectangle

Description

imagecrop ( resource $image , array $rect ) : resource

Crops an image to the given rectangular area and returns the resulting image. The given image is not modified.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

rect

The cropping rectangle as array with keys x, y, width and height.

Return Values

Return cropped image resource on success or FALSE on failure.

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');
    imagedestroy($im2);
}
imagedestroy($im);
?>

See Also

  • imagecropauto() - Crop an image automatically using one of the available modes


Crop an image automatically using one of the available modes

  • « imagecrop
  • imagedashedline »
  • PHP Manual
  • GD and Image Functions
  • Crop an image automatically using one of the available modes

imagecropauto

(PHP 5 >= 5.5.0, PHP 7)

imagecropauto — Crop an image automatically using one of the available modes

Description

imagecropauto ( resource $image [, int $mode = IMG_CROP_DEFAULT [, float $threshold = .5 [, int $color = -1 ]]] ) : resource

Automatically crops an image according to the given mode.

Parameters

image

An image resource, 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 resource on success or FALSE on failure. If the complete image was cropped, imagecrop() returns FALSE.

Changelog

Version | Description
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 resource $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 resource was returned
    imagedestroy($im);    // we destroy the original image
    $im = $cropped;       // and assign the cropped image to $im
}
?>

See Also

  • imagecrop() - Crop an image to the given rectangle


Draw a dashed line

  • « imagecropauto
  • imagedestroy »
  • PHP Manual
  • GD and Image Functions
  • Draw a dashed line

imagedashedline

(PHP 4, PHP 5, PHP 7)

imagedashedline — Draw a dashed line

Description

imagedashedline ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color ) : bool

This function is deprecated. Use combination of imagesetstyle() and imageline() instead.

Parameters

image

An image resource, 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

Returns TRUE on success or FALSE on failure.

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');
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : imagedashedline()

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');
imagedestroy($im);
?>

See Also

  • imagesetstyle() - Set the style for line drawing
  • imageline() - Draw a line


Destroy an image

  • « imagedashedline
  • imageellipse »
  • PHP Manual
  • GD and Image Functions
  • Destroy an image

imagedestroy

(PHP 4, PHP 5, PHP 7)

imagedestroy — Destroy an image

Description

imagedestroy ( resource $image ) : bool

imagedestroy() frees any memory associated with image image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Using imagedestroy() example

<?php
// create a 100 x 100 image
$im = imagecreatetruecolor(100, 100);

// alter or save the image

// frees image from memory
imagedestroy($im);
?>


Draw an ellipse

  • « imagedestroy
  • imagefill »
  • PHP Manual
  • GD and Image Functions
  • Draw an ellipse

imageellipse

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

imageellipse — Draw an ellipse

Description

imageellipse ( resource $image , int $cx , int $cy , int $width , int $height , int $color ) : bool

Draws an ellipse centered at the specified coordinates.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

cx

x-coordinate of the center.

cy

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

Returns TRUE on success or FALSE on failure.

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:

Output of example : imageellipse()

Notes

Note:

imageellipse() ignores imagesetthickness().

See Also

  • imagefilledellipse() - Draw a filled ellipse
  • imagearc() - Draws an arc


Flood fill

  • « imageellipse
  • imagefilledarc »
  • PHP Manual
  • GD and Image Functions
  • Flood fill

imagefill

(PHP 4, PHP 5, PHP 7)

imagefill — Flood fill

Description

imagefill ( resource $image , int $x , int $y , int $color ) : bool

Performs a flood fill starting at the given coordinate (top left is 0, 0) with the given color in the image.

Parameters

image

An image resource, 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

Returns TRUE on success or FALSE on failure.

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);
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : imagefill()

See Also

  • imagecolorallocate() - Allocate a color for an image


Draw a partial arc and fill it

  • « imagefill
  • imagefilledellipse »
  • PHP Manual
  • GD and Image Functions
  • Draw a partial arc and fill it

imagefilledarc

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

imagefilledarc — Draw a partial arc and fill it

Description

imagefilledarc ( resource $image , int $cx , int $cy , int $width , int $height , int $start , int $end , int $color , int $style ) : bool

Draws a partial arc centered at the specified coordinate in the given image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

cx

x-coordinate of the center.

cy

y-coordinate of the center.

width

The arc width.

height

The arc height.

start

The arc start angle, in degrees.

end

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

Returns TRUE on success or FALSE on failure.

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);
imagedestroy($image);
?>

The above example will output something similar to:

Output of example : Creating a 3D looking pie


Draw a filled ellipse

  • « imagefilledarc
  • imagefilledpolygon »
  • PHP Manual
  • GD and Image Functions
  • Draw a filled ellipse

imagefilledellipse

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

imagefilledellipse — Draw a filled ellipse

Description

imagefilledellipse ( resource $image , int $cx , int $cy , int $width , int $height , int $color ) : bool

Draws an ellipse centered at the specified coordinate on the given image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

cx

x-coordinate of the center.

cy

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

Returns TRUE on success or FALSE on failure.

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:

Output of example : imagefilledellipse()

Notes

Note:

imagefilledellipse() ignores imagesetthickness().

See Also

  • imageellipse() - Draw an ellipse
  • imagefilledarc() - Draw a partial arc and fill it


Draw a filled polygon

  • « imagefilledellipse
  • imagefilledrectangle »
  • PHP Manual
  • GD and Image Functions
  • Draw a filled polygon

imagefilledpolygon

(PHP 4, PHP 5, PHP 7)

imagefilledpolygon — Draw a filled polygon

Description

imagefilledpolygon ( resource $image , array $points , int $num_points , int $color ) : bool

imagefilledpolygon() creates a filled polygon in the given image.

Parameters

image

An image resource, 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.

color

A color identifier created with imagecolorallocate().

Return Values

Returns TRUE on success or FALSE on failure.

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, 6, $blue);

// flush image
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>

The above example will output something similar to:

Output of example : imagefilledpolygon()

See Also

  • imagepolygon() - Draws a polygon


Draw a filled rectangle

  • « imagefilledpolygon
  • imagefilltoborder »
  • PHP Manual
  • GD and Image Functions
  • Draw a filled rectangle

imagefilledrectangle

(PHP 4, PHP 5, PHP 7)

imagefilledrectangle — Draw a filled rectangle

Description

imagefilledrectangle ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color ) : bool

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

An image resource, 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

Returns TRUE on success or FALSE on failure.

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');
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : imagefilledrectangle()


Flood fill to specific color

  • « imagefilledrectangle
  • imagefilter »
  • PHP Manual
  • GD and Image Functions
  • Flood fill to specific color

imagefilltoborder

(PHP 4, PHP 5, PHP 7)

imagefilltoborder — Flood fill to specific color

Description

imagefilltoborder ( resource $image , int $x , int $y , int $border , int $color ) : bool

imagefilltoborder() performs a flood fill whose border color is defined by border. The starting point for the fill is x, y (top left is 0, 0) and the region is filled with color color.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

x

x-coordinate of start.

y

y-coordinate of start.

border

The border color. A color identifier created with imagecolorallocate().

color

The fill color. A color identifier created with imagecolorallocate().

Return Values

Returns TRUE on success or FALSE on failure.

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 and free memory
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : Filling an ellipse with a color


Applies a filter to an image

  • « imagefilltoborder
  • imageflip »
  • PHP Manual
  • GD and Image Functions
  • Applies a filter to an image

imagefilter

(PHP 5, PHP 7)

imagefilter — Applies a filter to an image

Description

imagefilter ( resource $image , int $filtertype [, int $arg1 [, int $arg2 [, int $arg3 [, int $arg4 ]]]] ) : bool

imagefilter() applies the given filter filtertype on the image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

filtertype

filtertype 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 arg1 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 arg1 to set the level of contrast.
  • IMG_FILTER_COLORIZE: Like IMG_FILTER_GRAYSCALE, except you can specify the color. Use arg1, 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 arg1 to set the level of smoothness.
  • IMG_FILTER_PIXELATE: Applies pixelation effect to the image, use arg1 to set the block size and arg2 to set the pixelation effect mode.
  • IMG_FILTER_SCATTER: Applies scatter effect to the image, use arg1 and arg2 to define the effect strength and additionally arg3 to only apply the on select pixel colors.

arg1

  • 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.

Changelog

Version | Description
7.4.0 | Scatter support (IMG_FILTER_SCATTER) was added.
5.3.0 | Pixelation support (IMG_FILTER_PIXELATE) was added.
5.2.5 | Alpha support for IMG_FILTER_COLORIZE 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.';
}

imagedestroy($im);
?>

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');
    imagedestroy($im);
}
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');
    imagedestroy($im);
}
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);
    imagedestroy($im);
}
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);
imagedestroy($logo1);
imagedestroy($logo2);

// Output the differences
header('Content-Type: image/png');
imagepng($output);
imagedestroy($output);
?>

The above example will output something similar to:

Output of example : imagefilter() pixelate

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);
imagedestroy($logo);
?>

The above example will output something similar to:

Output of example : imagefilter() scatter

Notes

Note: The result of IMG_FILTER_SCATTER is always random.

See Also

  • imageconvolution() - Apply a 3x3 convolution matrix, using coefficient and offset


Flips an image using a given mode

  • « imagefilter
  • imagefontheight »
  • PHP Manual
  • GD and Image Functions
  • Flips an image using a given mode

imageflip

(PHP 5 >= 5.5.0, PHP 7)

imageflip — Flips an image using a given mode

Description

imageflip ( resource $image , int $mode ) : bool

Flips the image image using the given mode.

Parameters

image

An image resource, 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

Returns TRUE on success or FALSE on failure.

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);
imagedestroy($im);
?>

The above example will output something similar to:

Output of example: Vertically flipped image

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);
imagedestroy($im);
?>

The above example will output something similar to:

Output of example: Horizontally flipped image


Get font height

  • « imageflip
  • imagefontwidth »
  • PHP Manual
  • GD and Image Functions
  • Get font height

imagefontheight

(PHP 4, PHP 5, PHP 7)

imagefontheight — Get font height

Description

imagefontheight ( 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 any of your own font identifiers registered with imageloadfont().

Return Values

Returns the pixel height of the font.

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


Get font width

  • « imagefontheight
  • imageftbbox »
  • PHP Manual
  • GD and Image Functions
  • Get font width

imagefontwidth

(PHP 4, PHP 5, PHP 7)

imagefontwidth — Get font width

Description

imagefontwidth ( 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 any of your own font identifiers registered with imageloadfont().

Return Values

Returns the pixel width of the font.

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


Give the bounding box of a text using fonts via freetype2

  • « imagefontwidth
  • imagefttext »
  • PHP Manual
  • GD and Image Functions
  • Give the bounding box of a text using fonts via freetype2

imageftbbox

(PHP 4 >= 4.0.7, PHP 5, PHP 7)

imageftbbox — Give the bounding box of a text using fonts via freetype2

Description

imageftbbox ( float $size , float $angle , string $fontfile , string $text [, array $extrainfo ] ) : array

This function calculates and returns the bounding box in pixels for a FreeType text.

Note:

imageftbbox() is an extended variant of imagettfbbox() which additionally supports the extrainfo.

Parameters

size

The font size in points.

angle

Angle in degrees in which text will be measured.

fontfile

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.

text

The string to be measured.

extrainfo

Possible array indexes for extrainfo
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.

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);
imagedestroy($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


Write text to the image using fonts using FreeType 2

  • « imageftbbox
  • imagegammacorrect »
  • PHP Manual
  • GD and Image Functions
  • Write text to the image using fonts using FreeType 2

imagefttext

(PHP 4 >= 4.0.7, PHP 5, PHP 7)

imagefttext — Write text to the image using fonts using FreeType 2

Description

imagefttext ( resource $image , float $size , float $angle , int $x , int $y , int $color , string $fontfile , string $text [, array $extrainfo ] ) : array

Note:

imagefttext() is an extended variant of imagettftext() which additionally supports the extrainfo.

Parameters

image

An image resource, 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().

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 enviroment 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.

extrainfo

Possible array indexes for extrainfo
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

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);
imagedestroy($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


Apply a gamma correction to a GD image

  • « imagefttext
  • imagegd2 »
  • PHP Manual
  • GD and Image Functions
  • Apply a gamma correction to a GD image

imagegammacorrect

(PHP 4, PHP 5, PHP 7)

imagegammacorrect — Apply a gamma correction to a GD image

Description

imagegammacorrect ( resource $image , float $inputgamma , float $outputgamma ) : bool

Applies gamma correction to the given gd image given an input and an output gamma.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

inputgamma

The input gamma.

outputgamma

The output gamma.

Return Values

Returns TRUE on success or FALSE on failure.

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 and free image
imagegif($im, './php_gamma_corrected.gif');
imagedestroy($im);
?>


Output GD2 image to browser or file

  • « imagegammacorrect
  • imagegd »
  • PHP Manual
  • GD and Image Functions
  • Output GD2 image to browser or file

imagegd2

(PHP 4 >= 4.0.7, PHP 5, PHP 7)

imagegd2 — Output GD2 image to browser or file

Description

imagegd2 ( resource $image [, mixed $to = NULL [, int $chunk_size = 128 [, int $type = IMG_GD2_RAW ]]] ) : bool

Outputs a GD2 image to the given to.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

to

The path or an open stream resource (which is automatically being closed after this function returns) to save the file to. If not set or NULL, the raw image stream will be outputted directly.

chunk_size

Chunk size.

type

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
5.4.0 | Added support for passing a stream resource to to.

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);

// Free up memory
imagedestroy($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');

// Free up memory
imagedestroy($im);
?>

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.

See Also

  • imagegd() - Output GD image to browser or file


Output GD image to browser or file

  • « imagegd2
  • imagegetclip »
  • PHP Manual
  • GD and Image Functions
  • Output GD image to browser or file

imagegd

(PHP 4 >= 4.0.7, PHP 5, PHP 7)

imagegd — Output GD image to browser or file

Description

imagegd ( resource $image [, mixed $to = NULL ] ) : bool

Outputs a GD image to the given to.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

to

The path or an open stream resource (which is automatically being closed after this function returns) to save the file to. If not set or NULL, the raw image stream will be outputted 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
7.2.0 | imagegd() now allows to output truecolor images. Formerly, these have been implicitly converted to palette.
5.4.0 | Added support for passing a stream resource to to.

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);

// Free up memory
imagedestroy($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');

// Free up memory
imagedestroy($im);
?>

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.

See Also

  • imagegd2() - Output GD2 image to browser or file


Get the clipping rectangle

  • « imagegd
  • imagegif »
  • PHP Manual
  • GD and Image Functions
  • Get the clipping rectangle

imagegetclip

(PHP 7 >= 7.2.0)

imagegetclip — Get the clipping rectangle

Description

imagegetclip ( resource $im ) : array

imagegetclip() retrieves the current clipping rectangle, i.e. the area beyond which no pixels will be drawn.

Parameters

image

An image resource, 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

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


Output image to browser or file

  • « imagegetclip
  • imagegrabscreen »
  • PHP Manual
  • GD and Image Functions
  • Output image to browser or file

imagegif

(PHP 4, PHP 5, PHP 7)

imagegif — Output image to browser or file

Description

imagegif ( resource $image [, mixed $to = NULL ] ) : bool

imagegif() creates the GIF file in to 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

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

to

The path or an open stream resource (which is automatically being closed after this function returns) to save the file to. If not set or NULL, the raw image stream will be outputted 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
5.4.0 | Added support for passing a stream resource to to.

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);
imagedestroy($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');

// Free from memory
imagedestroy($png);

// We're done
echo 'Converted PNG image to GIF with success!';
?>

Notes

Note:

GIF support was removed from the GD library in Version 1.6, and added back in Version 2.0.28. This function is not available between these versions. For more information, see the » GD Project site.

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
{
    imagedestroy($im);

    die('No image support in this PHP server');
}

// If image support was found for one of these
// formats, then free it from memory
if($im)
{
    imagedestroy($im);
}
?>

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


Captures the whole screen

  • « imagegif
  • imagegrabwindow »
  • PHP Manual
  • GD and Image Functions
  • Captures the whole screen

imagegrabscreen

(PHP 5 >= 5.2.2, PHP 7)

imagegrabscreen — Captures the whole screen

Description

imagegrabscreen ( void ) : resource

Grabs a screenshot of the whole screen.

Note:

This function is only available on Windows.

Return Values

Returns an image resource identifier on success, FALSE on failure.

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");
imagedestroy($im);
?>

See Also

  • imagegrabwindow() - Captures a window


Captures a window

  • « imagegrabscreen
  • imageinterlace »
  • PHP Manual
  • GD and Image Functions
  • Captures a window

imagegrabwindow

(PHP 5 >= 5.2.2, PHP 7)

imagegrabwindow — Captures a window

Description

imagegrabwindow ( int $window_handle [, int $client_area = 0 ] ) : resource

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

window_handle

The HWND window ID.

client_area

Include the client area of the application window.

Return Values

Returns an image resource identifier on success, FALSE on failure.

Errors/Exceptions

E_NOTICE is issued if window_handle is invalid window handle. E_WARNING is issued if the Windows API is too old.

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");
imagedestroy($im);
?>

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");
imagedestroy($im);
?>

See Also

  • imagegrabscreen() - Captures the whole screen


Enable or disable interlace

  • « imagegrabwindow
  • imageistruecolor »
  • PHP Manual
  • GD and Image Functions
  • Enable or disable interlace

imageinterlace

(PHP 4, PHP 5, PHP 7)

imageinterlace — Enable or disable interlace

Description

imageinterlace ( resource $image [, int $interlace = 0 ] ) : int

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

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

interlace

If non-zero, the image will be interlaced, else the interlace bit is turned off.

Return Values

Returns 1 if the interlace bit is set for the image, 0 otherwise.

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');
imagedestroy($im);
?>


Finds whether an image is a truecolor image

  • « imageinterlace
  • imagejpeg »
  • PHP Manual
  • GD and Image Functions
  • Finds whether an image is a truecolor image

imageistruecolor

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

imageistruecolor — Finds whether an image is a truecolor image

Description

imageistruecolor ( resource $image ) : bool

imageistruecolor() finds whether the image image is a truecolor image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

Return Values

Returns TRUE if the image is truecolor, FALSE otherwise.

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));
    imagedestroy($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


Output image to browser or file

  • « imageistruecolor
  • imagelayereffect »
  • PHP Manual
  • GD and Image Functions
  • Output image to browser or file

imagejpeg

(PHP 4, PHP 5, PHP 7)

imagejpeg — Output image to browser or file

Description

imagejpeg ( resource $image [, mixed $to = NULL [, int $quality = -1 ]] ) : bool

imagejpeg() creates a JPEG file from the given image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

to

The path or an open stream resource (which is automatically being closed after this function returns) to save the file to. If not set or NULL, the raw image stream will be outputted 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.

Changelog

Version | Description
5.4.0 | Added support for passing a stream resource to to.
5.4.0 | Disallowed passing an empty string to to to skip this argument.

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);

// Free up memory
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : Outputting a JPEG image

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');

// Free up memory
imagedestroy($im);
?>

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 to parameter using NULL, then set the quality to 75%
imagejpeg($im, NULL, 75);

// Free up memory
imagedestroy($im);
?>

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


Set the alpha blending flag to use layering effects

  • « imagejpeg
  • imageline »
  • PHP Manual
  • GD and Image Functions
  • Set the alpha blending flag to use layering effects

imagelayereffect

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

imagelayereffect — Set the alpha blending flag to use layering effects

Description

imagelayereffect ( resource $image , int $effect ) : bool

Set the alpha blending flag to use layering effects.

Parameters

image

An image resource, 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

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
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);
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : imagelayereffect()

Notes

Before PHP 5.5.0, this function is only available if PHP is compiled with the bundled version of the GD library.


Draw a line

  • « imagelayereffect
  • imageloadfont »
  • PHP Manual
  • GD and Image Functions
  • Draw a line

imageline

(PHP 4, PHP 5, PHP 7)

imageline — Draw a line

Description

imageline ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color ) : bool

Draws a line between the two given points.

Parameters

image

An image resource, 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

Returns TRUE on success or FALSE on failure.

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


Load a new font

  • « imageline
  • imageopenpolygon »
  • PHP Manual
  • GD and Image Functions
  • Load a new font

imageloadfont

(PHP 4, PHP 5, PHP 7)

imageloadfont — Load a new font

Description

imageloadfont ( string $file ) : int

imageloadfont() loads a user-defined bitmap and returns its identifier.

Parameters

file

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

The font identifier which is always bigger than 5 to avoid conflicts with built-in fonts or FALSE on errors.

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);
imagedestroy($im);
?>

See Also

  • imagefontwidth() - Get font width
  • imagefontheight() - Get font height


Draws an open polygon

  • « imageloadfont
  • imagepalettecopy »
  • PHP Manual
  • GD and Image Functions
  • Draws an open polygon

imageopenpolygon

(PHP 7 >= 7.2.0)

imageopenpolygon — Draws an open polygon

Description

imageopenpolygon ( resource $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

An image resource, 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.

color

A color identifier created with imagecolorallocate().

Return Values

Returns TRUE on success or FALSE on failure.

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
    ),
    3,
    $col_poly);

// Output the picture to the browser
header('Content-type: image/png');

imagepng($image);
imagedestroy($image);
?>

The above example will output something similar to:

Output of example : imageopenpolygon()

See Also

  • imagepolygon() - Draws a polygon


Copy the palette from one image to another

  • « imageopenpolygon
  • imagepalettetotruecolor »
  • PHP Manual
  • GD and Image Functions
  • Copy the palette from one image to another

imagepalettecopy

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

imagepalettecopy — Copy the palette from one image to another

Description

imagepalettecopy ( resource $destination , resource $source ) : void

imagepalettecopy() copies the palette from the source image to the destination image.

Parameters

destination

The destination image resource.

source

The source image resource.

Return Values

No value is returned.

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);
imagedestroy($palette1);
imagedestroy($palette2);
?>


Converts a palette based image to true color

  • « imagepalettecopy
  • imagepng »
  • PHP Manual
  • GD and Image Functions
  • Converts a palette based image to true color

imagepalettetotruecolor

(PHP 5 >= 5.5.0, PHP 7)

imagepalettetotruecolor — Converts a palette based image to true color

Description

imagepalettetotruecolor ( resource $src ) : bool

Converts a palette based image, created by functions like imagecreate() to a true color image, like imagecreatetruecolor().

Parameters

image

An image resource, 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.

Examples

Example #1 Converts any image resource 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));
        imagedestroy($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();

// Free the memory
imagedestroy($im);
?>

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


Output a PNG image to either the browser or a file

  • « imagepalettetotruecolor
  • imagepolygon »
  • PHP Manual
  • GD and Image Functions
  • Output a PNG image to either the browser or a file

imagepng

(PHP 4, PHP 5, PHP 7)

imagepng — Output a PNG image to either the browser or a file

Description

imagepng ( resource $image [, mixed $to = NULL [, int $quality = -1 [, int $filters = -1 ]]] ) : bool

Outputs or saves a PNG image from the given image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

to

The path or an open stream resource (which is automatically being closed after this function returns) to save the file to. If not set or NULL, the raw image stream will be outputted 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_XXX 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.

Changelog

Version | Description
5.4.0 | Added support for passing a stream resource to to.
5.1.3 | Added the filters parameter.
5.1.2 | Added the quality parameter.

Examples

<?php
$im = imagecreatefrompng("test.png");

header('Content-Type: image/png');

imagepng($im);
imagedestroy($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 PNG images


Draws a polygon

  • « imagepng
  • imagepsbbox »
  • PHP Manual
  • GD and Image Functions
  • Draws a polygon

imagepolygon

(PHP 4, PHP 5, PHP 7)

imagepolygon — Draws a polygon

Description

imagepolygon ( resource $image , array $points , int $num_points , int $color ) : bool

imagepolygon() creates a polygon in the given image.

Parameters

image

An image resource, 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.

color

A color identifier created with imagecolorallocate().

Return Values

Returns TRUE on success or FALSE on failure.

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
    ),
    3,
    $col_poly);

// Output the picture to the browser
header('Content-type: image/png');

imagepng($image);
imagedestroy($image);
?>

The above example will output something similar to:

Output of example : imagepolygon()

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


Give the bounding box of a text rectangle using PostScript Type1 fonts

  • « imagepolygon
  • imagepsencodefont »
  • PHP Manual
  • GD and Image Functions
  • Give the bounding box of a text rectangle using PostScript Type1 fonts

imagepsbbox

(PHP 4, PHP 5)

imagepsbbox — Give the bounding box of a text rectangle using PostScript Type1 fonts

Warning

This function was REMOVED in PHP 7.0.0.

Description

imagepsbbox ( string $text , resource $font , int $size ) : array
imagepsbbox ( string $text , resource $font , int $size , int $space , int $tightness , float $angle ) : array

Gives the bounding box of a text rectangle using PostScript Type1 fonts.

The bounding box is calculated using information available from character metrics, and unfortunately tends to differ slightly from the results achieved by actually rasterizing the text. If the angle is 0 degrees, you can expect the text to need 1 pixel more to every direction.

Parameters

text

The text to be written.

font_index

A font resource, returned by imagepsloadfont().

size

size is expressed in pixels.

space

Allows you to change the default value of a space in a font. This amount is added to the normal value and can also be negative. Expressed in character space units, where 1 unit is 1/1000th of an em-square.

tightness

tightness allows you to control the amount of white space between characters. This amount is added to the normal character width and can also be negative. Expressed in character space units, where 1 unit is 1/1000th of an em-square.

angle

angle is in degrees.

Return Values

Returns an array containing the following elements:

0 | left x-coordinate
1 | upper y-coordinate
2 | right x-coordinate
3 | lower y-coordinate

Changelog

Version | Description
7.0.0 | T1Lib support was removed from PHP, thus this function was removed.

Examples

Example #1 imagepsbbox() usage

<?php
// Create image handle
$im = imagecreatetruecolor(200, 200);

// Allocate colors
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);

// Load the PostScript Font
$font = imagepsloadfont('font.pfm');

// Make a bounding box for the font
$bbox = imagepsbbox('Sample text is simple', $font, 12);

// Define our X and Y cordinates
$x = ($bbox[2] / 2) - 10;
$y = ($bbox[3] / 2) - 10;

// Write the font to the image
imagepstext($im, 'Sample text is simple', $font, 12, $black, $white, $x, $y);

// Output and free memory
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

Notes

Note: This function is only available if PHP is compiled using --with-t1lib[=DIR] .

See Also

  • imagepstext() - Draws a text over an image using PostScript Type1 fonts


Change the character encoding vector of a font

  • « imagepsbbox
  • imagepsextendfont »
  • PHP Manual
  • GD and Image Functions
  • Change the character encoding vector of a font

imagepsencodefont

(PHP 4, PHP 5)

imagepsencodefont — Change the character encoding vector of a font

Warning

This function was REMOVED in PHP 7.0.0.

Description

imagepsencodefont ( resource $font_index , string $encodingfile ) : bool

Loads a character encoding vector from a file and changes the fonts encoding vector to it. As a PostScript fonts default vector lacks most of the character positions above 127, you'll definitely want to change this if you use a language other than English.

If you find yourself using this function all the time, a much better way to define the encoding is to set ps.default_encoding in the configuration file to point to the right encoding file and all fonts you load will automatically have the right encoding.

Parameters

font_index

A font resource, returned by imagepsloadfont().

encodingfile

The exact format of this file is described in T1libs documentation. T1lib comes with two ready-to-use files, IsoLatin1.enc and IsoLatin2.enc.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.0.0 | T1Lib support was removed from PHP, thus this function was removed.

Examples

Example #1 imagepsencodefont() example

<?php
// Load a .pfb font file
$font = imagepsloadfont('./px3l.pfb');

// Tell T1lib to use ISO Latin 1 encoding
imagepsencode($font, './IsoLatin1.enc');

// Do any operations with the font here

// Free the font from memory
imagepsfreefont($font);
?>

Notes

Note: This function is only available if PHP is compiled using --with-t1lib[=DIR] .


Extend or condense a font

  • « imagepsencodefont
  • imagepsfreefont »
  • PHP Manual
  • GD and Image Functions
  • Extend or condense a font

imagepsextendfont

(PHP 4, PHP 5)

imagepsextendfont — Extend or condense a font

Warning

This function was REMOVED in PHP 7.0.0.

Description

imagepsextendfont ( resource $font_index , float $extend ) : bool

Extend or condense a font (font_index), if the value of the extend parameter is less than one you will be condensing the font.

Parameters

font_index

A font resource, returned by imagepsloadfont().

extend

Extension value, must be greater than 0.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.0.0 | T1Lib support was removed from PHP, thus this function was removed.

Examples

Example #1 imagepsextendfont() example

<?php
// Load a .pfb font file
$font = imagepsloadfont('./px3l.pfb');

// Extend the font by 2.5
imagepsextendfont($font, 2.5);

// Do any operations with the font here

// Free the font from memory
imagepsfreefont($font);
?>

Notes

Note: This function is only available if PHP is compiled using --with-t1lib[=DIR] .


Free memory used by a PostScript Type 1 font

  • « imagepsextendfont
  • imagepsloadfont »
  • PHP Manual
  • GD and Image Functions
  • Free memory used by a PostScript Type 1 font

imagepsfreefont

(PHP 4, PHP 5)

imagepsfreefont — Free memory used by a PostScript Type 1 font

Warning

This function was REMOVED in PHP 7.0.0.

Description

imagepsfreefont ( resource $font_index ) : bool

imagepsfreefont() frees memory used by a PostScript Type 1 font.

Parameters

font_index

A font resource, returned by imagepsloadfont().

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.0.0 | T1Lib support was removed from PHP, thus this function was removed.

Examples

Example #1 imagepsfreefont() example

<?php
// Load a .pfb font file
$font = imagepsloadfont('./bchbi.pfb');

// Do any operations with the font here

// Free the font from memory
imagepsfreefont($font);
?>

Notes

Note: This function is only available if PHP is compiled using --with-t1lib[=DIR] .

See Also

  • imagepsloadfont() - Load a PostScript Type 1 font from file


Load a PostScript Type 1 font from file

  • « imagepsfreefont
  • imagepsslantfont »
  • PHP Manual
  • GD and Image Functions
  • Load a PostScript Type 1 font from file

imagepsloadfont

(PHP 4, PHP 5)

imagepsloadfont — Load a PostScript Type 1 font from file

Warning

This function was REMOVED in PHP 7.0.0.

Description

imagepsloadfont ( string $filename ) : resource

Load a PostScript Type 1 font from the given filename.

Parameters

filename

Path to the Postscript font file.

Return Values

In the case everything went right, a valid font index will be returned and can be used for further purposes. Otherwise the function returns FALSE.

Changelog

Version | Description
7.0.0 | T1Lib support was removed from PHP, thus this function was removed.

Examples

Example #1 imagepsloadfont() example

<?php
// Create a new image instance
$im = imagecreatetruecolor(350, 45);

// Allocate colors and fill the background
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);
imagefilledrectangle($im, 0, 0, 349, 44, $white);

// Load a font, write to the image and free the font from memory
$font = imagepsloadfont("bchbi.pfb");
imagepstext($im, "Testing... It worked!", $font, 32, $white, $black, 32, 32);
imagepsfreefont($font);

// Output the image
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

Notes

Note: This function is only available if PHP is compiled using --with-t1lib[=DIR] .

See Also

  • imagepsfreefont() - Free memory used by a PostScript Type 1 font


Slant a font

  • « imagepsloadfont
  • imagepstext »
  • PHP Manual
  • GD and Image Functions
  • Slant a font

imagepsslantfont

(PHP 4, PHP 5)

imagepsslantfont — Slant a font

Warning

This function was REMOVED in PHP 7.0.0.

Description

imagepsslantfont ( resource $font_index , float $slant ) : bool

Slant a given font.

Parameters

font_index

A font resource, returned by imagepsloadfont().

slant

Slant level.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.0.0 | T1Lib support was removed from PHP, thus this function was removed.

Examples

Example #1 imagepsslantfont() example

<?php
// Load a .pfb font file
$font = imagepsloadfont('./px3l.pfb');

// Slant the font by 22.5
imagepsslantfont($font, 22.5);

// Do any operations with the font here

// Free the font from memory
imagepsfreefont($font);
?>

Notes

Note: This function is only available if PHP is compiled using --with-t1lib[=DIR] .


Draws a text over an image using PostScript Type1 fonts

  • « imagepsslantfont
  • imagerectangle »
  • PHP Manual
  • GD and Image Functions
  • Draws a text over an image using PostScript Type1 fonts

imagepstext

(PHP 4, PHP 5)

imagepstext — Draws a text over an image using PostScript Type1 fonts

Warning

This function was REMOVED in PHP 7.0.0.

Description

imagepstext ( resource $image , string $text , resource $font_index , int $size , int $foreground , int $background , int $x , int $y [, int $space = 0 [, int $tightness = 0 [, float $angle = 0.0 [, int $antialias_steps = 4 ]]]] ) : array

Draws a text on an image using PostScript Type1 fonts.

Refer to PostScript documentation about fonts and their measuring system if you have trouble understanding how this works.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

text

The text to be written.

font_index

A font resource, returned by imagepsloadfont().

size

size is expressed in pixels.

foreground

The color in which the text will be painted.

background

The color to which the text will try to fade in with antialiasing. No pixels with the color background are actually painted, so the background image does not need to be of solid color.

x

x-coordinate for the lower-left corner of the first character.

y

y-coordinate for the lower-left corner of the first character.

space

Allows you to change the default value of a space in a font. This amount is added to the normal value and can also be negative. Expressed in character space units, where 1 unit is 1/1000th of an em-square.

tightness

tightness allows you to control the amount of white space between characters. This amount is added to the normal character width and can also be negative. Expressed in character space units, where 1 unit is 1/1000th of an em-square.

angle

angle is in degrees.

antialias_steps

Allows you to control the number of colours used for antialiasing text. Allowed values are 4 and 16. The higher value is recommended for text sizes lower than 20, where the effect in text quality is quite visible. With bigger sizes, use 4. It's less computationally intensive.

Return Values

This function returns an array containing the following elements:

0 | lower left x-coordinate
1 | lower left y-coordinate
2 | upper right x-coordinate
3 | upper right y-coordinate

Changelog

Version | Description
7.0.0 | T1Lib support was removed from PHP, thus this function was removed.

Examples

Example #1 imagepstext() usage

<?php
// Create image handle
$im = imagecreatetruecolor(200, 200);

// Allocate colors
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);

// Load the PostScript Font
$font = imagepsloadfont('font.pfm');

// Write the font to the image
imagepstext($im, 'Sample text is simple', $font, 12, $black, $white, 50, 50);

// Output and free memory
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

Notes

Note: This function is only available if PHP is compiled using --with-t1lib[=DIR] .

See Also

  • imagepsbbox() - Give the bounding box of a text rectangle using PostScript Type1 fonts


Draw a rectangle

  • « imagepstext
  • imageresolution »
  • PHP Manual
  • GD and Image Functions
  • Draw a rectangle

imagerectangle

(PHP 4, PHP 5, PHP 7)

imagerectangle — Draw a rectangle

Description

imagerectangle ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color ) : bool

imagerectangle() creates a rectangle starting at the specified coordinates.

Parameters

image

An image resource, 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

Returns TRUE on success or FALSE on failure.

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 and free from memory
header('Content-Type: image/jpeg');

imagejpeg($canvas);
imagedestroy($canvas);
?>

The above example will output something similar to:

Output of example : Simple imagerectangle() example


Get or set the resolution of the image

  • « imagerectangle
  • imagerotate »
  • PHP Manual
  • GD and Image Functions
  • Get or set the resolution of the image

imageresolution

(PHP 7 >= 7.2.0)

imageresolution — Get or set the resolution of the image

Description

imageresolution ( resource $image ) : mixed
imageresolution ( resource $image , int $res_x [, int $res_y = $res_x ] ) : mixed

imageresolution() allows to set and get the resolution of an image in DPI (dots per inch). If none of the optional parameters is given, the current resolution is returned as indexed array. If only res_x is given, the horizontal and vertical resolution are set to this value. If both optional parameters are given, 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

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

res_x

The horizontal resolution in DPI.

res_y

The vertical resolution in DPI.

Return Values

When used as getter (first signature), it returns an indexed array of the horizontal and vertical resolution on success, or FALSE on failure. When used as setter (second signature), it returns TRUE on success, or FALSE on failure.

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
)


Rotate an image with a given angle

  • « imageresolution
  • imagesavealpha »
  • PHP Manual
  • GD and Image Functions
  • Rotate an image with a given angle

imagerotate

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

imagerotate — Rotate an image with a given angle

Description

imagerotate ( resource $image , float $angle , int $bgd_color [, int $ignore_transparent = 0 ] ) : resource

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

An image resource, 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.

bgd_color

Specifies the color of the uncovered zone after the rotation

ignore_transparent

If set and non-zero, transparent colors are ignored (otherwise kept).

Return Values

Returns an image resource for the rotated image, or FALSE on failure.

Changelog

Version | Description
5.5.0 | The ignore_transparent is now silently ignored.
5.5.0 | This function is now affected by the interpolation method set by the imagesetinterpolation() function.
5.1.0 | ignore_transparent was added.

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);

// Free the memory
imagedestroy($source);
imagedestroy($rotate);
?>

The above example will output something similar to:

Output of example : Rotate an image 180 degrees

Notes

Note:

This function is affected by the interpolation method set by imagesetinterpolation().

See Also

  • imagesetinterpolation() - Set the interpolation method


Whether to retain full alpha channel information when saving PNG images

  • « imagerotate
  • imagescale »
  • PHP Manual
  • GD and Image Functions
  • Whether to retain full alpha channel information when saving PNG images

imagesavealpha

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

imagesavealpha — Whether to retain full alpha channel information when saving PNG images

Description

imagesavealpha ( resource $image , bool $saveflag ) : bool

imagesavealpha() sets the flag which determines whether to retain full alpha channel information (as opposed to single-color transparency) when saving PNG images.

Alphablending has to be disabled (imagealphablending($im, false)) to retain the alpha-channel in the first place.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

saveflag

Whether to save the alpha channel or not. Defaults to FALSE.

Return Values

Returns TRUE on success or FALSE on failure.

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);
imagedestroy($png);
?>

See Also

  • imagealphablending() - Set the blending mode for an image


Scale an image using the given new width and height

  • « imagesavealpha
  • imagesetbrush »
  • PHP Manual
  • GD and Image Functions
  • Scale an image using the given new width and height

imagescale

(PHP 5 >= 5.5.0, PHP 7)

imagescale — Scale an image using the given new width and height

Description

imagescale ( resource $image , int $new_width [, int $new_height = -1 [, int $mode = IMG_BILINEAR_FIXED ]] ) : resource

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

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

new_width

The width to scale the image to.

new_height

The height to scale the image to. If omitted or negative, the aspect ratio will be preserved.

Caution

You should always provide the height if using PHP 5.5.18 or earlier, or PHP 5.6.2 or earlier, as the aspect ratio calculation was incorrect.

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 resource on success or FALSE on failure.

Changelog

Version | Description
5.5.19/5.6.3 | The calculation of the height if new_height was negative or omitted was fixed; prior to these versions, the aspect ratio was not maintained correctly.

See Also

imagecopyresized() - Copy and resize part of an image imagecopyresampled() - Copy and resize part of an image with resampling


Set the brush image for line drawing

  • « imagescale
  • imagesetclip »
  • PHP Manual
  • GD and Image Functions
  • Set the brush image for line drawing

imagesetbrush

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

imagesetbrush — Set the brush image for line drawing

Description

imagesetbrush ( resource $image , resource $brush ) : bool

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

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

brush

An image resource.

Return Values

Returns TRUE on success or FALSE on failure.

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);
imagedestroy($im);
imagedestroy($php);
?>

The above example will output something similar to:

Output of example : imagesetbrush()


Set the clipping rectangle

  • « imagesetbrush
  • imagesetinterpolation »
  • PHP Manual
  • GD and Image Functions
  • Set the clipping rectangle

imagesetclip

(PHP 7 >= 7.2.0)

imagesetclip — Set the clipping rectangle

Description

imagesetclip ( resource $im , int $x1 , int $y1 , int $x2 , int $y2 ) : bool

imagesetclip() sets the current clipping rectangle, i.e. the area beyond which no pixels will be drawn.

Parameters

image

An image resource, 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

Returns TRUE on success or FALSE on failure.

See Also

  • imagegetclip() - Get the clipping rectangle


Set the interpolation method

  • « imagesetclip
  • imagesetpixel »
  • PHP Manual
  • GD and Image Functions
  • Set the interpolation method

imagesetinterpolation

(PHP 5 >= 5.5.0, PHP 7)

imagesetinterpolation — Set the interpolation method

Description

imagesetinterpolation ( resource $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

An image resource, 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.

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()


Set a single pixel

  • « imagesetinterpolation
  • imagesetstyle »
  • PHP Manual
  • GD and Image Functions
  • Set a single pixel

imagesetpixel

(PHP 4, PHP 5, PHP 7)

imagesetpixel — Set a single pixel

Description

imagesetpixel ( resource $image , int $x , int $y , int $color ) : bool

imagesetpixel() draws a pixel at the specified coordinate.

Parameters

image

An image resource, 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

Returns TRUE on success or FALSE on failure.

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:

Output of example : imagesetpixel()

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


Set the style for line drawing

  • « imagesetpixel
  • imagesetthickness »
  • PHP Manual
  • GD and Image Functions
  • Set the style for line drawing

imagesetstyle

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

imagesetstyle — Set the style for line drawing

Description

imagesetstyle ( resource $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

An image resource, 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);
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : imagesetstyle()

See Also

  • imagesetbrush() - Set the brush image for line drawing
  • imageline() - Draw a line


Set the thickness for line drawing

  • « imagesetstyle
  • imagesettile »
  • PHP Manual
  • GD and Image Functions
  • Set the thickness for line drawing

imagesetthickness

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

imagesetthickness — Set the thickness for line drawing

Description

imagesetthickness ( resource $image , int $thickness ) : bool

imagesetthickness() sets the thickness of the lines drawn when drawing rectangles, polygons, arcs etc. to thickness pixels.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

thickness

Thickness, in pixels.

Return Values

Returns TRUE on success or FALSE on failure.

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);
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : imagesetthickness()


Set the tile image for filling

  • « imagesetthickness
  • imagestring »
  • PHP Manual
  • GD and Image Functions
  • Set the tile image for filling

imagesettile

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

imagesettile — Set the tile image for filling

Description

imagesettile ( resource $image , resource $tile ) : bool

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

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

tile

The image resource to be used as a tile.

Return Values

Returns TRUE on success or FALSE on failure.

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);
imagedestroy($im);
imagedestroy($zend);
?>

The above example will output something similar to:

Output of example : imagesettile()


Draw a string horizontally

  • « imagesettile
  • imagestringup »
  • PHP Manual
  • GD and Image Functions
  • Draw a string horizontally

imagestring

(PHP 4, PHP 5, PHP 7)

imagestring — Draw a string horizontally

Description

imagestring ( resource $image , int $font , int $x , int $y , string $string , int $color ) : bool

Draws a string at the given coordinates.

Parameters

image

An image resource, 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 any of your own font identifiers registered with 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

Returns TRUE on success or FALSE on failure.

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);
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : imagestring()

See Also

  • imagestringup() - Draw a string vertically
  • imageloadfont() - Load a new font
  • imagettftext() - Write text to the image using TrueType fonts


Draw a string vertically

  • « imagestring
  • imagesx »
  • PHP Manual
  • GD and Image Functions
  • Draw a string vertically

imagestringup

(PHP 4, PHP 5, PHP 7)

imagestringup — Draw a string vertically

Description

imagestringup ( resource $image , int $font , int $x , int $y , string $string , int $color ) : bool

Draws a string vertically at the given coordinates.

Parameters

image

An image resource, 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 any of your own font identifiers registered with 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

Returns TRUE on success or FALSE on failure.

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');
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : imagestringup()

See Also

  • imagestring() - Draw a string horizontally
  • imageloadfont() - Load a new font


Get image width

  • « imagestringup
  • imagesy »
  • PHP Manual
  • GD and Image Functions
  • Get image width

imagesx

(PHP 4, PHP 5, PHP 7)

imagesx — Get image width

Description

imagesx ( resource $image ) : int

Returns the width of the given image resource.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

Return Values

Return the width of the image or FALSE on errors.

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


Get image height

  • « imagesx
  • imagetruecolortopalette »
  • PHP Manual
  • GD and Image Functions
  • Get image height

imagesy

(PHP 4, PHP 5, PHP 7)

imagesy — Get image height

Description

imagesy ( resource $image ) : int

Returns the height of the given image resource.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

Return Values

Return the height of the image or FALSE on errors.

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


Convert a true color image to a palette image

  • « imagesy
  • imagettfbbox »
  • PHP Manual
  • GD and Image Functions
  • Convert a true color image to a palette image

imagetruecolortopalette

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

imagetruecolortopalette — Convert a true color image to a palette image

Description

imagetruecolortopalette ( resource $image , bool $dither , int $ncolors ) : 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

An image resource, 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.

ncolors

Sets the maximum number of colors that should be retained in the palette.

Return Values

Returns TRUE on success or FALSE on failure.

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');
imagedestroy($im);
?>


Give the bounding box of a text using TrueType fonts

  • « imagetruecolortopalette
  • imagettftext »
  • PHP Manual
  • GD and Image Functions
  • Give the bounding box of a text using TrueType fonts

imagettfbbox

(PHP 4, PHP 5, PHP 7)

imagettfbbox — Give the bounding box of a text using TrueType fonts

Description

imagettfbbox ( float $size , float $angle , string $fontfile , string $text ) : array

This function calculates and returns the bounding box in pixels for a TrueType text.

Note:

imageftbbox() is an extended variant of imagettfbbox() which additionally supports the extrainfo.

Parameters

size

The font size in points.

angle

Angle in degrees in which text 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 enviroment 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 string to be measured.

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.

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);
imagedestroy($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


Write text to the image using TrueType fonts

  • « imagettfbbox
  • imagetypes »
  • PHP Manual
  • GD and Image Functions
  • Write text to the image using TrueType fonts

imagettftext

(PHP 4, PHP 5, PHP 7)

imagettftext — Write text to the image using TrueType fonts

Description

imagettftext ( resource $image , float $size , float $angle , int $x , int $y , int $color , string $fontfile , string $text ) : array

Writes the given text into the image using TrueType fonts.

Note:

imagefttext() is an extended variant of imagettftext() which additionally supports the extrainfo.

Parameters

image

An image resource, 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 enviroment 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.

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
5.2.0 | It is now possible to specify an hexadecimal entity in text.

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);
imagedestroy($im);
?>

The above example will output something similar to:

Output of example : imagettftext()

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


Return the image types supported by this PHP build

  • « imagettftext
  • imagewbmp »
  • PHP Manual
  • GD and Image Functions
  • Return the image types supported by this PHP build

imagetypes

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

imagetypes — Return the image types supported by this PHP build

Description

imagetypes ( void ) : int

Returns the image types supported by the current PHP installation.

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_BMP | IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP | IMG_XPM | IMG_WEBP.

Examples

Example #1 Checking for PNG support

<?php
if (imagetypes() & IMG_PNG) {
    echo "PNG Support is enabled";
}
?>

Changelog

Version | Description
7.2.0 | IMG_BMP added.
5.6.25, 7.0.10 | IMG_WEBP added.

See Also

  • gd_info() - Retrieve information about the currently installed GD library


Output image to browser or file

  • « imagetypes
  • imagewebp »
  • PHP Manual
  • GD and Image Functions
  • Output image to browser or file

imagewbmp

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

imagewbmp — Output image to browser or file

Description

imagewbmp ( resource $image [, mixed $to = NULL [, int $foreground ]] ) : bool

imagewbmp() 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().

to

The path or an open stream resource (which is automatically being closed after this function returns) to save the file to. If not set or NULL, the raw image stream will be outputted 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.

Changelog

Version | Description
5.4.0 | Added support for passing a stream resource to to.

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);

// Free up memory
imagedestroy($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');

// Free up memory
imagedestroy($im);
?>

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);

// Free up memory
imagedestroy($im);
?>

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


Output a WebP image to browser or file

  • « imagewbmp
  • imagexbm »
  • PHP Manual
  • GD and Image Functions
  • Output a WebP image to browser or file

imagewebp

(PHP 5 >= 5.4.0, PHP 7)

imagewebp — Output a WebP image to browser or file

Description

imagewebp ( resource $image [, mixed $to = NULL [, int $quality = 80 ]] ) : bool

Outputs or saves a WebP version of the given image.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

to

The path or an open stream resource (which is automatically being closed after this function returns) to save the file to. If not set or NULL, the raw image stream will be outputted directly.

quality

quality ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file).

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 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');

// Free up memory
imagedestroy($im);
?>


Output an XBM image to browser or file

  • « imagewebp
  • iptcembed »
  • PHP Manual
  • GD and Image Functions
  • Output an XBM image to browser or file

imagexbm

(PHP 5, PHP 7)

imagexbm — Output an XBM image to browser or file

Description

imagexbm ( resource $image [, string $filename = NULL [, int $foreground ]] ) : 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 5.6.24 and 7.0.9, respectively.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

filename

The path to save the file to. If not set or NULL, the raw image stream will be outputted 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

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.

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');

// Free up memory
imagedestroy($im);
?>

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);

// Free up memory
imagedestroy($im);
?>

Notes


Embeds binary IPTC data into a JPEG image

  • « imagexbm
  • iptcparse »
  • PHP Manual
  • GD and Image Functions
  • Embeds binary IPTC data into a JPEG image

iptcembed

(PHP 4, PHP 5, PHP 7)

iptcembed — Embeds binary IPTC data into a JPEG image

Description

iptcembed ( string $iptcdata , string $jpeg_file_name [, int $spool = 0 ] ) : mixed

Embeds binary IPTC data into a JPEG image.

Parameters

iptcdata

The data to be written.

jpeg_file_name

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.


Parse a binary IPTC block into single tags

  • « iptcembed
  • jpeg2wbmp »
  • PHP Manual
  • GD and Image Functions
  • Parse a binary IPTC block into single tags

iptcparse

(PHP 4, PHP 5, PHP 7)

iptcparse — Parse a binary IPTC block into single tags

Description

iptcparse ( string $iptcblock ) : array

Parses an » IPTC block into its single tags.

Parameters

iptcblock

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.


Convert JPEG image file to WBMP image file

  • « iptcparse
  • png2wbmp »
  • PHP Manual
  • GD and Image Functions
  • Convert JPEG image file to WBMP image file

jpeg2wbmp

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

jpeg2wbmp — Convert JPEG image file to WBMP image file

Warning

jpeg2wbmp() has been deprecated as of PHP 7.2.0, and will be removed as of PHP 8.0.0. Use imagecreatefromjpeg() and imagewbmp() instead.

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


Convert PNG image file to WBMP image file

  • « jpeg2wbmp
  • Gmagick »
  • PHP Manual
  • GD and Image Functions
  • 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

png2wbmp() has been deprecated as of PHP 7.2.0, and will be removed as of PHP 8.0.0. Use imagecreatefrompng() and imagewbmp() instead.

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


Gmagick

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
  • 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 — The flopimage purpose
    • 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 — The line purpose
    • 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


Introduction

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).


Requirements

This extension works best with GraphicsMagick version 1.4+ and PHP 5.1.3+. 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 this out: » 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.

For Windows, the build of the Gmagick extension is available » here


  • « Installation
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Runtime Configuration

Runtime Configuration

This extension has no configuration directives defined in php.ini.


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 (integer)
Black
Gmagick::COLOR_BLUE (integer)
Blue
Gmagick::COLOR_CYAN (integer)
Cyan
Gmagick::COLOR_GREEN (integer)
Green
Gmagick::COLOR_RED (integer)
Red
Gmagick::COLOR_YELLOW (integer)
Yellow
Gmagick::COLOR_MAGENTA (integer)
Magenta
Gmagick::COLOR_OPACITY (integer)
Opacity
Gmagick::COLOR_ALPHA (integer)
Alpha
Gmagick::COLOR_FUZZ (integer)
Fuzz
Composite Operator Constants
Gmagick::COMPOSITE_DEFAULT (integer)
The default composite operator
Gmagick::COMPOSITE_UNDEFINED (integer)
Undefined composite operator
Gmagick::COMPOSITE_NO (integer)
No composite operator defined
Gmagick::COMPOSITE_ADD (integer)
The result of image + image
Gmagick::COMPOSITE_ATOP (integer)
The result is the same shape as image, with composite image obscuring image where the image shapes overlap
Gmagick::COMPOSITE_BLEND (integer)
Blends the image
Gmagick::COMPOSITE_BUMPMAP (integer)
The same as COMPOSITE_MULTIPLY, except the source is converted to grayscale first.
Gmagick::COMPOSITE_CLEAR (integer)
Makes the target image transparent
Gmagick::COMPOSITE_COLORBURN (integer)
Darkens the destination image to reflect the source image
Gmagick::COMPOSITE_COLORDODGE (integer)
Brightens the destination image to reflect the source image
Gmagick::COMPOSITE_COLORIZE (integer)
Colorizes the target image using the composite image
Gmagick::COMPOSITE_COPYBLACK (integer)
Copies black from the source to target
Gmagick::COMPOSITE_COPYBLUE (integer)
Copies blue from the source to target
Gmagick::COMPOSITE_COPY (integer)
Copies the source image on the target image
Gmagick::COMPOSITE_COPYCYAN (integer)
Copies cyan from the source to target
Gmagick::COMPOSITE_COPYGREEN (integer)
Copies green from the source to target
Gmagick::COMPOSITE_COPYMAGENTA (integer)
Copies magenta from the source to target
Gmagick::COMPOSITE_COPYOPACITY (integer)
Copies opacity from the source to target
Gmagick::COMPOSITE_COPYRED (integer)
Copies red from the source to target
Gmagick::COMPOSITE_COPYYELLOW (integer)
Copies yellow from the source to target
Gmagick::COMPOSITE_DARKEN (integer)
Darkens the target image
Gmagick::COMPOSITE_DSTATOP (integer)
The part of the destination lying inside of the source is composited over the source and replaces the destination
Gmagick::COMPOSITE_DST (integer)
The target is left untouched
Gmagick::COMPOSITE_DSTIN (integer)
The parts inside the source replace the target
Gmagick::COMPOSITE_DSTOUT (integer)
The parts outside the source replace the target
Gmagick::COMPOSITE_DSTOVER (integer)
Target replaces the source
Gmagick::COMPOSITE_DIFFERENCE (integer)
Subtracts the darker of the two constituent colors from the lighter
Gmagick::COMPOSITE_DISPLACE (integer)
Shifts target image pixels as defined by the source
Gmagick::COMPOSITE_DISSOLVE (integer)
Dissolves the source in to the target
Gmagick::COMPOSITE_EXCLUSION (integer)
Produces an effect similar to that of Gmagick::COMPOSITE_DIFFERENCE, but appears as lower contrast
Gmagick::COMPOSITE_HARDLIGHT (integer)
Multiplies or screens the colors, dependent on the source color value
Gmagick::COMPOSITE_HUE (integer)
Modifies the hue of the target as defined by source
Gmagick::COMPOSITE_IN (integer)
Composites source into the target
Gmagick::COMPOSITE_LIGHTEN (integer)
Lightens the target as defined by source
Gmagick::COMPOSITE_LUMINIZE (integer)
Luminizes the target as defined by source
Gmagick::COMPOSITE_MINUS (integer)
Subtracts the source from the target
Gmagick::COMPOSITE_MODULATE (integer)
Modulates the target brightness, saturation and hue as defined by source
Gmagick::COMPOSITE_MULTIPLY (integer)
Multiplies the target to the source
Gmagick::COMPOSITE_OUT (integer)
Composites outer parts of the source on the target
Gmagick::COMPOSITE_OVER (integer)
Composites source over the target
Gmagick::COMPOSITE_OVERLAY (integer)
Overlays the source on the target
Gmagick::COMPOSITE_PLUS (integer)
Adds the source to the target
Gmagick::COMPOSITE_REPLACE (integer)
Replaces the target with the source
Gmagick::COMPOSITE_SATURATE (integer)
Saturates the target as defined by the source
Gmagick::COMPOSITE_SCREEN (integer)
The source and destination are complemented and then multiplied and then replace the destination
Gmagick::COMPOSITE_SOFTLIGHT (integer)
Darkens or lightens the colors, dependent on the source
Gmagick::COMPOSITE_SRCATOP (integer)
The part of the source lying inside of the destination is composited onto the destination
Gmagick::COMPOSITE_SRC (integer)
The source is copied to the destination
Gmagick::COMPOSITE_SRCIN (integer)
The part of the source lying inside of the destination replaces the destination
Gmagick::COMPOSITE_SRCOUT (integer)
The part of the source lying outside of the destination replaces the destination
Gmagick::COMPOSITE_SRCOVER (integer)
The source replaces the destination
Gmagick::COMPOSITE_SUBTRACT (integer)
Subtract the colors in the source image from the destination image
Gmagick::COMPOSITE_THRESHOLD (integer)
The source is composited on the target as defined by source threshold
Gmagick::COMPOSITE_XOR (integer)
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 (integer)
Gmagick::MONTAGEMODE_UNFRAME (integer)
Gmagick::MONTAGEMODE_CONCATENATE (integer)
Style constants
Gmagick::STYLE_NORMAL (integer)
Gmagick::STYLE_ITALIC (integer)
Gmagick::STYLE_OBLIQUE (integer)
Gmagick::STYLE_ANY (integer)
Filter constants
Gmagick::FILTER_UNDEFINED (integer)
Gmagick::FILTER_POINT (integer)
Gmagick::FILTER_BOX (integer)
Gmagick::FILTER_TRIANGLE (integer)
Gmagick::FILTER_HERMITE (integer)
Gmagick::FILTER_HANNING (integer)
Gmagick::FILTER_HAMMING (integer)
Gmagick::FILTER_BLACKMAN (integer)
Gmagick::FILTER_GAUSSIAN (integer)
Gmagick::FILTER_QUADRATIC (integer)
Gmagick::FILTER_CUBIC (integer)
Gmagick::FILTER_CATROM (integer)
Gmagick::FILTER_MITCHELL (integer)
Gmagick::FILTER_LANCZOS (integer)
Gmagick::FILTER_BESSEL (integer)
Gmagick::FILTER_SINC (integer)
Image type constants
Gmagick::IMGTYPE_UNDEFINED (integer)
Gmagick::IMGTYPE_BILEVEL (integer)
Gmagick::IMGTYPE_GRAYSCALE (integer)
Gmagick::IMGTYPE_GRAYSCALEMATTE (integer)
Gmagick::IMGTYPE_PALETTE (integer)
Gmagick::IMGTYPE_PALETTEMATTE (integer)
Gmagick::IMGTYPE_TRUECOLOR (integer)
Gmagick::IMGTYPE_TRUECOLORMATTE (integer)
Gmagick::IMGTYPE_COLORSEPARATION (integer)
Gmagick::IMGTYPE_COLORSEPARATIONMATTE (integer)
Gmagick::IMGTYPE_OPTIMIZE (integer)
Resolution constants
Gmagick::RESOLUTION_UNDEFINED (integer)
Gmagick::RESOLUTION_PIXELSPERINCH (integer)
Gmagick::RESOLUTION_PIXELSPERCENTIMETER (integer)
Compression constants
Gmagick::COMPRESSION_UNDEFINED (integer)
Gmagick::COMPRESSION_NO (integer)
Gmagick::COMPRESSION_BZIP (integer)
Gmagick::COMPRESSION_FAX (integer)
Gmagick::COMPRESSION_GROUP4 (integer)
Gmagick::COMPRESSION_JPEG (integer)
Gmagick::COMPRESSION_JPEG2000 (integer)
Gmagick::COMPRESSION_LOSSLESSJPEG (integer)
Gmagick::COMPRESSION_LZW (integer)
Gmagick::COMPRESSION_RLE (integer)
Gmagick::COMPRESSION_ZIP (integer)
Paint constants
Gmagick::PAINT_POINT (integer)
Gmagick::PAINT_REPLACE (integer)
Gmagick::PAINT_FLOODFILL (integer)
Gmagick::PAINT_FILLTOBORDER (integer)
Gmagick::PAINT_RESET (integer)
Gravity constants
Gmagick::GRAVITY_NORTHWEST (integer)
Gmagick::GRAVITY_NORTH (integer)
Gmagick::GRAVITY_NORTHEAST (integer)
Gmagick::GRAVITY_WEST (integer)
Gmagick::GRAVITY_CENTER (integer)
Gmagick::GRAVITY_EAST (integer)
Gmagick::GRAVITY_SOUTHWEST (integer)
Gmagick::GRAVITY_SOUTH (integer)
Gmagick::GRAVITY_SOUTHEAST (integer)
Stretch constants
Gmagick::STRETCH_NORMAL (integer)
Gmagick::STRETCH_ULTRACONDENSED (integer)
Gmagick::STRETCH_CONDENSED (integer)
Gmagick::STRETCH_SEMICONDENSED (integer)
Gmagick::STRETCH_SEMIEXPANDED (integer)
Gmagick::STRETCH_EXPANDED (integer)
Gmagick::STRETCH_EXTRAEXPANDED (integer)
Gmagick::STRETCH_ULTRAEXPANDED (integer)
Gmagick::STRETCH_ANY (integer)
Align constants
Gmagick::ALIGN_UNDEFINED (integer)
Gmagick::ALIGN_LEFT (integer)
Gmagick::ALIGN_CENTER (integer)
Gmagick::ALIGN_RIGHT (integer)
Decoration constants
Gmagick::DECORATION_NO (integer)
Gmagick::DECORATION_UNDERLINE (integer)
Gmagick::DECORATION_OVERLINE (integer)
Gmagick::DECORATION_LINETROUGH (integer)
Noise constants
Gmagick::NOISE_UNIFORM (integer)
Gmagick::NOISE_GAUSSIAN (integer)
Gmagick::NOISE_MULTIPLICATIVEGAUSSIAN (integer)
Gmagick::NOISE_IMPULSE (integer)
Gmagick::NOISE_LAPLACIAN (integer)
Gmagick::NOISE_POISSON (integer)
Channel constants
Gmagick::CHANNEL_UNDEFINED (integer)
Gmagick::CHANNEL_RED (integer)
Gmagick::CHANNEL_GRAY (integer)
Gmagick::CHANNEL_CYAN (integer)
Gmagick::CHANNEL_GREEN (integer)
Gmagick::CHANNEL_MAGENTA (integer)
Gmagick::CHANNEL_BLUE (integer)
Gmagick::CHANNEL_YELLOW (integer)
Gmagick::CHANNEL_ALPHA (integer)
Gmagick::CHANNEL_OPACITY (integer)
Gmagick::CHANNEL_MATTE (integer)
Gmagick::CHANNEL_BLACK (integer)
Gmagick::CHANNEL_INDEX (integer)
Gmagick::CHANNEL_ALL (integer)
Metric constants
Gmagick::METRIC_UNDEFINED (integer)
Gmagick::METRIC_MEANABSOLUTEERROR (integer)
Gmagick::METRIC_MEANSQUAREERROR (integer)
Gmagick::METRIC_PEAKABSOLUTEERROR (integer)
Gmagick::METRIC_PEAKSIGNALTONOISERATIO (integer)
Gmagick::METRIC_ROOTMEANSQUAREDERROR (integer)
Pixel constants
Gmagick::PIXEL_CHAR (integer)
Gmagick::PIXEL_DOUBLE (integer)
Gmagick::PIXEL_FLOAT (integer)
Gmagick::PIXEL_INTEGER (integer)
Gmagick::PIXEL_LONG (integer)
Gmagick::PIXEL_QUANTUM (integer)
Gmagick::PIXEL_SHORT (integer)
Colorspace constants
Gmagick::COLORSPACE_UNDEFINED (integer)
Gmagick::COLORSPACE_RGB (integer)
Gmagick::COLORSPACE_GRAY (integer)
Gmagick::COLORSPACE_TRANSPARENT (integer)
Gmagick::COLORSPACE_OHTA (integer)
Gmagick::COLORSPACE_LAB (integer)
Gmagick::COLORSPACE_XYZ (integer)
Gmagick::COLORSPACE_YCBCR (integer)
Gmagick::COLORSPACE_YCC (integer)
Gmagick::COLORSPACE_YIQ (integer)
Gmagick::COLORSPACE_YPBPR (integer)
Gmagick::COLORSPACE_YUV (integer)
Gmagick::COLORSPACE_CMYK (integer)
Gmagick::COLORSPACE_SRGB (integer)
Gmagick::COLORSPACE_HSB (integer)
Gmagick::COLORSPACE_HSL (integer)
Gmagick::COLORSPACE_HWB (integer)
Gmagick::COLORSPACE_REC601LUMA (integer)
Gmagick::COLORSPACE_REC709LUMA (integer)
Gmagick::COLORSPACE_LOG (integer)
Virtual Pixel Method constants
Gmagick::VIRTUALPIXELMETHOD_UNDEFINED (integer)
Gmagick::VIRTUALPIXELMETHOD_BACKGROUND (integer)
Gmagick::VIRTUALPIXELMETHOD_CONSTANT (integer)
Gmagick::VIRTUALPIXELMETHOD_EDGE (integer)
Gmagick::VIRTUALPIXELMETHOD_MIRROR (integer)
Gmagick::VIRTUALPIXELMETHOD_TILE (integer)
Gmagick::VIRTUALPIXELMETHOD_TRANSPARENT (integer)
Preview constants
Gmagick::PREVIEW_UNDEFINED (integer)
Gmagick::PREVIEW_ROTATE (integer)
Gmagick::PREVIEW_SHEAR (integer)
Gmagick::PREVIEW_ROLL (integer)
Gmagick::PREVIEW_HUE (integer)
Gmagick::PREVIEW_SATURATION (integer)
Gmagick::PREVIEW_BRIGHTNESS (integer)
Gmagick::PREVIEW_GAMMA (integer)
Gmagick::PREVIEW_SPIFF (integer)
Gmagick::PREVIEW_DULL (integer)
Gmagick::PREVIEW_GRAYSCALE (integer)
Gmagick::PREVIEW_QUANTIZE (integer)
Gmagick::PREVIEW_DESPECKLE (integer)
Gmagick::PREVIEW_REDUCENOISE (integer)
Gmagick::PREVIEW_ADDNOISE (integer)
Gmagick::PREVIEW_SHARPEN (integer)
Gmagick::PREVIEW_BLUR (integer)
Gmagick::PREVIEW_THRESHOLD (integer)
Gmagick::PREVIEW_EDGEDETECT (integer)
Gmagick::PREVIEW_SPREAD (integer)
Gmagick::PREVIEW_SOLARIZE (integer)
Gmagick::PREVIEW_SHADE (integer)
Gmagick::PREVIEW_RAISE (integer)
Gmagick::PREVIEW_SEGMENT (integer)
Gmagick::PREVIEW_SWIRL (integer)
Gmagick::PREVIEW_IMPLODE (integer)
Gmagick::PREVIEW_WAVE (integer)
Gmagick::PREVIEW_OILPAINT (integer)
Gmagick::PREVIEW_CHARCOALDRAWING (integer)
Gmagick::PREVIEW_JPEG (integer)
Rendering Intent constants
Gmagick::RENDERINGINTENT_UNDEFINED (integer)
Gmagick::RENDERINGINTENT_SATURATION (integer)
Gmagick::RENDERINGINTENT_PERCEPTUAL (integer)
Gmagick::RENDERINGINTENT_ABSOLUTE (integer)
Gmagick::RENDERINGINTENT_RELATIVE (integer)
Fillrule constants
Gmagick::FILLRULE_UNDEFINED (integer)
Gmagick::FILLRULE_EVENODD (integer)
Gmagick::FILLRULE_NONZERO (integer)
Pathunit constants
Gmagick::PATHUNITS_UNDEFINED (integer)
Gmagick::PATHUNITS_USERSPACE (integer)
Gmagick::PATHUNITS_USERSPACEONUSE (integer)
Gmagick::PATHUNITS_OBJECTBOUNDINGBOX (integer)
Linecap constants
Gmagick::LINECAP_UNDEFINED (integer)
Gmagick::LINECAP_BUTT (integer)
Gmagick::LINECAP_ROUND (integer)
Gmagick::LINECAP_SQUARE (integer)
Line Join constants
Gmagick::LINEJOIN_UNDEFINED (integer)
Gmagick::LINEJOIN_MITER (integer)
Gmagick::LINEJOIN_ROUND (integer)
Gmagick::LINEJOIN_BEVEL (integer)
Resourcetype constants
Gmagick::RESOURCETYPE_UNDEFINED (integer)
Gmagick::RESOURCETYPE_AREA (integer)
Gmagick::RESOURCETYPE_DISK (integer)
Gmagick::RESOURCETYPE_FILE (integer)
Gmagick::RESOURCETYPE_MAP (integer)
Gmagick::RESOURCETYPE_MEMORY (integer)
Orientation constants
Gmagick::ORIENTATION_UNDEFINED (integer)
Gmagick::ORIENTATION_TOPLEFT (integer)
Gmagick::ORIENTATION_TOPRIGHT (integer)
Gmagick::ORIENTATION_BOTTOMRIGHT (integer)
Gmagick::ORIENTATION_BOTTOMLEFT (integer)
Gmagick::ORIENTATION_LEFTTOP (integer)
Gmagick::ORIENTATION_RIGHTTOP (integer)
Gmagick::ORIENTATION_RIGHTBOTTOM (integer)
Gmagick::ORIENTATION_LEFTBOTTOM (integer)


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

Gmagick {
/* Methods */
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 ( void ) : Gmagick
public commentimage ( string $comment ) : Gmagick
public compositeimage ( Gmagick $source , int $COMPOSE , int $x , int $y ) : Gmagick
public __construct ([ string $filename ] )
public cropimage ( int $width , int $height , int $x , int $y ) : Gmagick
public cropthumbnailimage ( int $width , int $height ) : Gmagick
public current ( void ) : Gmagick
public cyclecolormapimage ( int $displace ) : Gmagick
public deconstructimages ( void ) : Gmagick
public despeckleimage ( void ) : Gmagick
public destroy ( void ) : bool
public drawimage ( GmagickDraw $GmagickDraw ) : Gmagick
public edgeimage ( float $radius ) : Gmagick
public embossimage ( float $radius , float $sigma ) : Gmagick
public enhanceimage ( void ) : Gmagick
public equalizeimage ( void ) : Gmagick
public flipimage ( void ) : Gmagick
public flopimage ( void ) : Gmagick
public frameimage ( GmagickPixel $color , int $width , int $height , int $inner_bevel , int $outer_bevel ) : Gmagick
public gammaimage ( float $gamma ) : Gmagick
public getcopyright ( void ) : string
public getfilename ( void ) : string
public getimagebackgroundcolor ( void ) : GmagickPixel
public getimageblueprimary ( void ) : array
public getimagebordercolor ( void ) : GmagickPixel
public getimagechanneldepth ( int $channel_type ) : int
public getimagecolors ( void ) : int
public getimagecolorspace ( void ) : int
public getimagecompose ( void ) : int
public getimagedelay ( void ) : int
public getimagedepth ( void ) : int
public getimagedispose ( void ) : int
public getimageextrema ( void ) : array
public getimagefilename ( void ) : string
public getimageformat ( void ) : string
public getimagegamma ( void ) : float
public getimagegreenprimary ( void ) : array
public getimageheight ( void ) : int
public getimagehistogram ( void ) : array
public getimageindex ( void ) : int
public getimageinterlacescheme ( void ) : int
public getimageiterations ( void ) : int
public getimagematte ( void ) : int
public getimagemattecolor ( void ) : GmagickPixel
public getimageprofile ( string $name ) : string
public getimageredprimary ( void ) : array
public getimagerenderingintent ( void ) : int
public getimageresolution ( void ) : array
public getimagescene ( void ) : int
public getimagesignature ( void ) : string
public getimagetype ( void ) : int
public getimageunits ( void ) : int
public getimagewhitepoint ( void ) : array
public getimagewidth ( void ) : int
public getpackagename ( void ) : string
public getquantumdepth ( void ) : array
public getreleasedate ( void ) : string
public getsamplingfactors ( void ) : array
public getsize ( void ) : array
public getversion ( void ) : array
public hasnextimage ( void ) : mixed
public haspreviousimage ( void ) : 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 ( void ) : mixed
public mapimage ( gmagick $gmagick , bool $dither ) : Gmagick
public medianfilterimage ( float $radius ) : void
public minifyimage ( void ) : 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 ( void ) : bool
public normalizeimage ([ int $channel ] ) : Gmagick
public oilpaintimage ( float $radius ) : Gmagick
public previousimage ( void ) : 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 ( void ) : 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 = 75 ) : 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 ( void ) : 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
}

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 — The flopimage purpose
  • 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


Adds new image to Gmagick object image list

  • « Gmagick
  • Gmagick::addnoiseimage »
  • PHP Manual
  • Gmagick
  • Adds new image to Gmagick object image list

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.


Adds random noise to the image

  • « Gmagick::addimage
  • Gmagick::annotateimage »
  • PHP Manual
  • Gmagick
  • Adds random noise to the image

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.


Annotates an image with text

  • « Gmagick::addnoiseimage
  • Gmagick::blurimage »
  • PHP Manual
  • Gmagick
  • Annotates an image with text

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.


Adds blur filter to image

  • « Gmagick::annotateimage
  • Gmagick::borderimage »
  • PHP Manual
  • Gmagick
  • Adds blur filter to image

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.


Surrounds the image with a border

  • « Gmagick::blurimage
  • Gmagick::charcoalimage »
  • PHP Manual
  • Gmagick
  • Surrounds the image with a border

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.


Simulates a charcoal drawing

  • « Gmagick::borderimage
  • Gmagick::chopimage »
  • PHP Manual
  • Gmagick
  • Simulates a charcoal drawing

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.


Removes a region of an image and trims

  • « Gmagick::charcoalimage
  • Gmagick::clear »
  • PHP Manual
  • Gmagick
  • Removes a region of an image and trims

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.


Clears all resources associated to Gmagick object

  • « Gmagick::chopimage
  • Gmagick::commentimage »
  • PHP Manual
  • Gmagick
  • Clears all resources associated to Gmagick object

Gmagick::clear

(PECL gmagick >= Unknown)

Gmagick::clear — Clears all resources associated to Gmagick object

Description

public Gmagick::clear ( void ) : 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.


Adds a comment to your image

  • « Gmagick::clear
  • Gmagick::compositeimage »
  • PHP Manual
  • Gmagick
  • Adds a comment to your image

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.


Composite one image onto another

  • « Gmagick::commentimage
  • Gmagick::__construct »
  • PHP Manual
  • Gmagick
  • Composite one image onto another

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.


The Gmagick constructor

  • « Gmagick::compositeimage
  • Gmagick::cropimage »
  • PHP Manual
  • Gmagick
  • The Gmagick constructor

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

Return Values

Returns a new Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.


Extracts a region of the image

  • « Gmagick::__construct
  • Gmagick::cropthumbnailimage »
  • PHP Manual
  • Gmagick
  • Extracts a region of the image

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.


Creates a crop thumbnail

  • « Gmagick::cropimage
  • Gmagick::current »
  • PHP Manual
  • Gmagick
  • Creates a crop thumbnail

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.


The current purpose

  • « Gmagick::cropthumbnailimage
  • Gmagick::cyclecolormapimage »
  • PHP Manual
  • Gmagick
  • The current purpose

Gmagick::current

(PECL gmagick >= Unknown)

Gmagick::current — The current purpose

Description

public Gmagick::current ( void ) : 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.


Displaces an image's colormap

  • « Gmagick::current
  • Gmagick::deconstructimages »
  • PHP Manual
  • Gmagick
  • Displaces an image's colormap

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.


Returns certain pixel differences between images

  • « Gmagick::cyclecolormapimage
  • Gmagick::despeckleimage »
  • PHP Manual
  • Gmagick
  • Returns certain pixel differences between images

Gmagick::deconstructimages

(PECL gmagick >= Unknown)

Gmagick::deconstructimages — Returns certain pixel differences between images

Description

public Gmagick::deconstructimages ( void ) : 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 on success.

Errors/Exceptions

Throws an GmagickException on error.


The despeckleimage purpose

  • « Gmagick::deconstructimages
  • Gmagick::destroy »
  • PHP Manual
  • Gmagick
  • The despeckleimage purpose

Gmagick::despeckleimage

(PECL gmagick >= Unknown)

Gmagick::despeckleimage — The despeckleimage purpose

Description

public Gmagick::despeckleimage ( void ) : 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 on success.

Errors/Exceptions

Throws an GmagickException on error.

Examples

Example #1 Gmagick::despeckleimage() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The destroy purpose

  • « Gmagick::despeckleimage
  • Gmagick::drawimage »
  • PHP Manual
  • Gmagick
  • The destroy purpose

Gmagick::destroy

(PECL gmagick >= Unknown)

Gmagick::destroy — The destroy purpose

Description

public Gmagick::destroy ( void ) : bool

Destroys the Gmagick object and frees all resources associated with it

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws an GmagickException on error.


Renders the GmagickDraw object on the current image

  • « Gmagick::destroy
  • Gmagick::edgeimage »
  • PHP Manual
  • Gmagick
  • Renders the GmagickDraw object on the current image

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.


Enhance edges within the image

  • « Gmagick::drawimage
  • Gmagick::embossimage »
  • PHP Manual
  • Gmagick
  • Enhance edges within the image

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.


Returns a grayscale image with a three-dimensional effect

  • « Gmagick::edgeimage
  • Gmagick::enhanceimage »
  • PHP Manual
  • Gmagick
  • Returns a grayscale image with a three-dimensional effect

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.


Improves the quality of a noisy image

  • « Gmagick::embossimage
  • Gmagick::equalizeimage »
  • PHP Manual
  • Gmagick
  • Improves the quality of a noisy image

Gmagick::enhanceimage

(PECL gmagick >= Unknown)

Gmagick::enhanceimage — Improves the quality of a noisy image

Description

public Gmagick::enhanceimage ( void ) : Gmagick

Applies a digital filter that improves the quality of a noisy image.

Return Values

The enhanced Gmagick object.

Errors/Exceptions

Throws an GmagickException on error.


Equalizes the image histogram

  • « Gmagick::enhanceimage
  • Gmagick::flipimage »
  • PHP Manual
  • Gmagick
  • Equalizes the image histogram

Gmagick::equalizeimage

(PECL gmagick >= Unknown)

Gmagick::equalizeimage — Equalizes the image histogram

Description

public Gmagick::equalizeimage ( void ) : Gmagick

Equalizes the image histogram.

Return Values

The equalized Gmagick object.

Errors/Exceptions

Throws an GmagickException on error.


Creates a vertical mirror image

  • « Gmagick::equalizeimage
  • Gmagick::flopimage »
  • PHP Manual
  • Gmagick
  • Creates a vertical mirror image

Gmagick::flipimage

(PECL gmagick >= Unknown)

Gmagick::flipimage — Creates a vertical mirror image

Description

public Gmagick::flipimage ( void ) : Gmagick

Creates a vertical mirror image by reflecting the pixels around the central x-axis.

Return Values

The flipped Gmagick object.

Errors/Exceptions

Throws an GmagickException on error.


The flopimage purpose

  • « Gmagick::flipimage
  • Gmagick::frameimage »
  • PHP Manual
  • Gmagick
  • The flopimage purpose

Gmagick::flopimage

(PECL gmagick >= Unknown)

Gmagick::flopimage — The flopimage purpose

Description

public Gmagick::flopimage ( void ) : Gmagick

Creates a horizontal mirror image by reflecting the pixels around the central y-axis.

Return Values

The flopped Gmagick object.

Errors/Exceptions

Throws an GmagickException on error.


Adds a simulated three-dimensional border

  • « Gmagick::flopimage
  • Gmagick::gammaimage »
  • PHP Manual
  • Gmagick
  • Adds a simulated three-dimensional border

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.


Gamma-corrects an image

  • « Gmagick::frameimage
  • Gmagick::getcopyright »
  • PHP Manual
  • Gmagick
  • Gamma-corrects an image

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.


Returns the GraphicsMagick API copyright as a string

  • « Gmagick::gammaimage
  • Gmagick::getfilename »
  • PHP Manual
  • Gmagick
  • Returns the GraphicsMagick API copyright as a string

Gmagick::getcopyright

(PECL gmagick >= Unknown)

Gmagick::getcopyright — Returns the GraphicsMagick API copyright as a string

Description

public Gmagick::getcopyright ( void ) : string

Returns the GraphicsMagick API copyright as a string.

Return Values

Returns a string containing the copyright notice of GraphicsMagick and Magickwand C API.

Errors/Exceptions

Throws an GmagickException on error.


The filename associated with an image sequence

  • « Gmagick::getcopyright
  • Gmagick::getimagebackgroundcolor »
  • PHP Manual
  • Gmagick
  • The filename associated with an image sequence

Gmagick::getfilename

(PECL gmagick >= Unknown)

Gmagick::getfilename — The filename associated with an image sequence

Description

public Gmagick::getfilename ( void ) : string

Returns the filename associated with an image sequence.

Return Values

Returns a string on success.

Errors/Exceptions

Throws an GmagickException on error.


Returns the image background color

  • « Gmagick::getfilename
  • Gmagick::getimageblueprimary »
  • PHP Manual
  • Gmagick
  • Returns the image background color

Gmagick::getimagebackgroundcolor

(PECL gmagick >= Unknown)

Gmagick::getimagebackgroundcolor — Returns the image background color

Description

public Gmagick::getimagebackgroundcolor ( void ) : 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.


Returns the chromaticy blue primary point

  • « Gmagick::getimagebackgroundcolor
  • Gmagick::getimagebordercolor »
  • PHP Manual
  • Gmagick
  • Returns the chromaticy blue primary point

Gmagick::getimageblueprimary

(PECL gmagick >= Unknown)

Gmagick::getimageblueprimary — Returns the chromaticy blue primary point

Description

public Gmagick::getimageblueprimary ( void ) : 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.


Returns the image border color

  • « Gmagick::getimageblueprimary
  • Gmagick::getimagechanneldepth »
  • PHP Manual
  • Gmagick
  • Returns the image border color

Gmagick::getimagebordercolor

(PECL gmagick >= Unknown)

Gmagick::getimagebordercolor — Returns the image border color

Description

public Gmagick::getimagebordercolor ( void ) : 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.


Gets the depth for a particular image channel

  • « Gmagick::getimagebordercolor
  • Gmagick::getimagecolors »
  • PHP Manual
  • Gmagick
  • Gets the depth for a particular image channel

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.


Returns the color of the specified colormap index

  • « Gmagick::getimagechanneldepth
  • Gmagick::getimagecolorspace »
  • PHP Manual
  • Gmagick
  • Returns the color of the specified colormap index

Gmagick::getimagecolors

(PECL gmagick >= Unknown)

Gmagick::getimagecolors — Returns the color of the specified colormap index

Description

public Gmagick::getimagecolors ( void ) : 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.


Gets the image colorspace

  • « Gmagick::getimagecolors
  • Gmagick::getimagecompose »
  • PHP Manual
  • Gmagick
  • Gets the image colorspace

Gmagick::getimagecolorspace

(PECL gmagick >= Unknown)

Gmagick::getimagecolorspace — Gets the image colorspace

Description

public Gmagick::getimagecolorspace ( void ) : int

Gets the image colorspace.

Parameters

This function has no parameters.

Return Values

Colorspace

Errors/Exceptions

Throws an GmagickException on error.


Returns the composite operator associated with the image

  • « Gmagick::getimagecolorspace
  • Gmagick::getimagedelay »
  • PHP Manual
  • Gmagick
  • Returns the composite operator associated with the image

Gmagick::getimagecompose

(PECL gmagick >= Unknown)

Gmagick::getimagecompose — Returns the composite operator associated with the image

Description

public Gmagick::getimagecompose ( void ) : 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.


Gets the image delay

  • « Gmagick::getimagecompose
  • Gmagick::getimagedepth »
  • PHP Manual
  • Gmagick
  • Gets the image delay

Gmagick::getimagedelay

(PECL gmagick >= Unknown)

Gmagick::getimagedelay — Gets the image delay

Description

public Gmagick::getimagedelay ( void ) : 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.


Gets the depth of the image

  • « Gmagick::getimagedelay
  • Gmagick::getimagedispose »
  • PHP Manual
  • Gmagick
  • Gets the depth of the image

Gmagick::getimagedepth

(PECL gmagick >= Unknown)

Gmagick::getimagedepth — Gets the depth of the image

Description

public Gmagick::getimagedepth ( void ) : int

Gets the depth of the image.

Parameters

This function has no parameters.

Return Values

Image depth

Errors/Exceptions

Throws an GmagickException on error.


Gets the image disposal method

  • « Gmagick::getimagedepth
  • Gmagick::getimageextrema »
  • PHP Manual
  • Gmagick
  • Gets the image disposal method

Gmagick::getimagedispose

(PECL gmagick >= Unknown)

Gmagick::getimagedispose — Gets the image disposal method

Description

public Gmagick::getimagedispose ( void ) : 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.


Gets the extrema for the image

  • « Gmagick::getimagedispose
  • Gmagick::getimagefilename »
  • PHP Manual
  • Gmagick
  • Gets the extrema for the image

Gmagick::getimageextrema

(PECL gmagick >= Unknown)

Gmagick::getimageextrema — Gets the extrema for the image

Description

public Gmagick::getimageextrema ( void ) : 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.


Returns the filename of a particular image in a sequence

  • « Gmagick::getimageextrema
  • Gmagick::getimageformat »
  • PHP Manual
  • Gmagick
  • Returns the filename of a particular image in a sequence

Gmagick::getimagefilename

(PECL gmagick >= Unknown)

Gmagick::getimagefilename — Returns the filename of a particular image in a sequence

Description

public Gmagick::getimagefilename ( void ) : 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.


Returns the format of a particular image in a sequence

  • « Gmagick::getimagefilename
  • Gmagick::getimagegamma »
  • PHP Manual
  • Gmagick
  • Returns the format of a particular image in a sequence

Gmagick::getimageformat

(PECL gmagick >= Unknown)

Gmagick::getimageformat — Returns the format of a particular image in a sequence

Description

public Gmagick::getimageformat ( void ) : 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.


Gets the image gamma

  • « Gmagick::getimageformat
  • Gmagick::getimagegreenprimary »
  • PHP Manual
  • Gmagick
  • Gets the image gamma

Gmagick::getimagegamma

(PECL gmagick >= Unknown)

Gmagick::getimagegamma — Gets the image gamma

Description

public Gmagick::getimagegamma ( void ) : 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.


Returns the chromaticy green primary point

  • « Gmagick::getimagegamma
  • Gmagick::getimageheight »
  • PHP Manual
  • Gmagick
  • Returns the chromaticy green primary point

Gmagick::getimagegreenprimary

(PECL gmagick >= Unknown)

Gmagick::getimagegreenprimary — Returns the chromaticy green primary point

Description

public Gmagick::getimagegreenprimary ( void ) : 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.


Returns the image height

  • « Gmagick::getimagegreenprimary
  • Gmagick::getimagehistogram »
  • PHP Manual
  • Gmagick
  • Returns the image height

Gmagick::getimageheight

(PECL gmagick >= Unknown)

Gmagick::getimageheight — Returns the image height

Description

public Gmagick::getimageheight ( void ) : 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.


Gets the image histogram

  • « Gmagick::getimageheight
  • Gmagick::getimageindex »
  • PHP Manual
  • Gmagick
  • Gets the image histogram

Gmagick::getimagehistogram

(PECL gmagick >= Unknown)

Gmagick::getimagehistogram — Gets the image histogram

Description

public Gmagick::getimagehistogram ( void ) : 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.


Gets the index of the current active image

  • « Gmagick::getimagehistogram
  • Gmagick::getimageinterlacescheme »
  • PHP Manual
  • Gmagick
  • Gets the index of the current active image

Gmagick::getimageindex

(PECL gmagick >= Unknown)

Gmagick::getimageindex — Gets the index of the current active image

Description

public Gmagick::getimageindex ( void ) : 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.


Gets the image interlace scheme

  • « Gmagick::getimageindex
  • Gmagick::getimageiterations »
  • PHP Manual
  • Gmagick
  • Gets the image interlace scheme

Gmagick::getimageinterlacescheme

(PECL gmagick >= Unknown)

Gmagick::getimageinterlacescheme — Gets the image interlace scheme

Description

public Gmagick::getimageinterlacescheme ( void ) : 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.


Gets the image iterations

  • « Gmagick::getimageinterlacescheme
  • Gmagick::getimagematte »
  • PHP Manual
  • Gmagick
  • Gets the image iterations

Gmagick::getimageiterations

(PECL gmagick >= Unknown)

Gmagick::getimageiterations — Gets the image iterations

Description

public Gmagick::getimageiterations ( void ) : 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.


Check if the image has a matte channel

  • « Gmagick::getimageiterations
  • Gmagick::getimagemattecolor »
  • PHP Manual
  • Gmagick
  • Check if the image has a matte channel

Gmagick::getimagematte

(PECL gmagick >= Unknown)

Gmagick::getimagematte — Check if the image has a matte channel

Description

public Gmagick::getimagematte ( void ) : 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.


Returns the image matte color

  • « Gmagick::getimagematte
  • Gmagick::getimageprofile »
  • PHP Manual
  • Gmagick
  • Returns the image matte color

Gmagick::getimagemattecolor

(PECL gmagick >= Unknown)

Gmagick::getimagemattecolor — Returns the image matte color

Description

public Gmagick::getimagemattecolor ( void ) : 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.


Returns the named image profile

  • « Gmagick::getimagemattecolor
  • Gmagick::getimageredprimary »
  • PHP Manual
  • Gmagick
  • Returns the named image profile

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.


Returns the chromaticity red primary point

  • « Gmagick::getimageprofile
  • Gmagick::getimagerenderingintent »
  • PHP Manual
  • Gmagick
  • Returns the chromaticity red primary point

Gmagick::getimageredprimary

(PECL gmagick >= Unknown)

Gmagick::getimageredprimary — Returns the chromaticity red primary point

Description

public Gmagick::getimageredprimary ( void ) : 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.


Gets the image rendering intent

  • « Gmagick::getimageredprimary
  • Gmagick::getimageresolution »
  • PHP Manual
  • Gmagick
  • Gets the image rendering intent

Gmagick::getimagerenderingintent

(PECL gmagick >= Unknown)

Gmagick::getimagerenderingintent — Gets the image rendering intent

Description

public Gmagick::getimagerenderingintent ( void ) : 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.


Gets the image X and Y resolution

  • « Gmagick::getimagerenderingintent
  • Gmagick::getimagescene »
  • PHP Manual
  • Gmagick
  • Gets the image X and Y resolution

Gmagick::getimageresolution

(PECL gmagick >= Unknown)

Gmagick::getimageresolution — Gets the image X and Y resolution

Description

public Gmagick::getimageresolution ( void ) : 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.


Gets the image scene

  • « Gmagick::getimageresolution
  • Gmagick::getimagesignature »
  • PHP Manual
  • Gmagick
  • Gets the image scene

Gmagick::getimagescene

(PECL gmagick >= Unknown)

Gmagick::getimagescene — Gets the image scene

Description

public Gmagick::getimagescene ( void ) : int

Gets the image scene.

Parameters

This function has no parameters.

Return Values

Returns the image scene.

Errors/Exceptions

Throws an GmagickException on error.


Generates an SHA-256 message digest

  • « Gmagick::getimagescene
  • Gmagick::getimagetype »
  • PHP Manual
  • Gmagick
  • Generates an SHA-256 message digest

Gmagick::getimagesignature

(PECL gmagick >= Unknown)

Gmagick::getimagesignature — Generates an SHA-256 message digest

Description

public Gmagick::getimagesignature ( void ) : 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.


Gets the potential image type

  • « Gmagick::getimagesignature
  • Gmagick::getimageunits »
  • PHP Manual
  • Gmagick
  • Gets the potential image type

Gmagick::getimagetype

(PECL gmagick >= Unknown)

Gmagick::getimagetype — Gets the potential image type

Description

public Gmagick::getimagetype ( void ) : 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.


Gets the image units of resolution

  • « Gmagick::getimagetype
  • Gmagick::getimagewhitepoint »
  • PHP Manual
  • Gmagick
  • Gets the image units of resolution

Gmagick::getimageunits

(PECL gmagick >= Unknown)

Gmagick::getimageunits — Gets the image units of resolution

Description

public Gmagick::getimageunits ( void ) : int

Gets the image units of resolution.

Parameters

This function has no parameters.

Return Values

Returns the image units of resolution.


Returns the chromaticity white point

  • « Gmagick::getimageunits
  • Gmagick::getimagewidth »
  • PHP Manual
  • Gmagick
  • Returns the chromaticity white point

Gmagick::getimagewhitepoint

(PECL gmagick >= Unknown)

Gmagick::getimagewhitepoint — Returns the chromaticity white point

Description

public Gmagick::getimagewhitepoint ( void ) : 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.


Returns the width of the image

  • « Gmagick::getimagewhitepoint
  • Gmagick::getpackagename »
  • PHP Manual
  • Gmagick
  • Returns the width of the image

Gmagick::getimagewidth

(PECL gmagick >= Unknown)

Gmagick::getimagewidth — Returns the width of the image

Description

public Gmagick::getimagewidth ( void ) : 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.


Returns the GraphicsMagick package name

  • « Gmagick::getimagewidth
  • Gmagick::getquantumdepth »
  • PHP Manual
  • Gmagick
  • Returns the GraphicsMagick package name

Gmagick::getpackagename

(PECL gmagick >= Unknown)

Gmagick::getpackagename — Returns the GraphicsMagick package name

Description

public Gmagick::getpackagename ( void ) : 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.


Returns the Gmagick quantum depth as a string

  • « Gmagick::getpackagename
  • Gmagick::getreleasedate »
  • PHP Manual
  • Gmagick
  • Returns the Gmagick quantum depth as a string

Gmagick::getquantumdepth

(PECL gmagick >= Unknown)

Gmagick::getquantumdepth — Returns the Gmagick quantum depth as a string

Description

public Gmagick::getquantumdepth ( void ) : 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.


Returns the GraphicsMagick release date as a string

  • « Gmagick::getquantumdepth
  • Gmagick::getsamplingfactors »
  • PHP Manual
  • Gmagick
  • Returns the GraphicsMagick release date as a string

Gmagick::getreleasedate

(PECL gmagick >= Unknown)

Gmagick::getreleasedate — Returns the GraphicsMagick release date as a string

Description

public Gmagick::getreleasedate ( void ) : 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.


Gets the horizontal and vertical sampling factor

  • « Gmagick::getreleasedate
  • Gmagick::getsize »
  • PHP Manual
  • Gmagick
  • Gets the horizontal and vertical sampling factor

Gmagick::getsamplingfactors

(PECL gmagick >= Unknown)

Gmagick::getsamplingfactors — Gets the horizontal and vertical sampling factor

Description

public Gmagick::getsamplingfactors ( void ) : 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.


Returns the size associated with the Gmagick object

  • « Gmagick::getsamplingfactors
  • Gmagick::getversion »
  • PHP Manual
  • Gmagick
  • Returns the size associated with the Gmagick object

Gmagick::getsize

(PECL gmagick >= Unknown)

Gmagick::getsize — Returns the size associated with the Gmagick object

Description

public Gmagick::getsize ( void ) : 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.


Returns the GraphicsMagick API version

  • « Gmagick::getsize
  • Gmagick::hasnextimage »
  • PHP Manual
  • Gmagick
  • Returns the GraphicsMagick API version

Gmagick::getversion

(PECL gmagick >= Unknown)

Gmagick::getversion — Returns the GraphicsMagick API version

Description

public Gmagick::getversion ( void ) : 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.


Checks if the object has more images

  • « Gmagick::getversion
  • Gmagick::haspreviousimage »
  • PHP Manual
  • Gmagick
  • Checks if the object has more images

Gmagick::hasnextimage

(PECL gmagick >= Unknown)

Gmagick::hasnextimage — Checks if the object has more images

Description

public Gmagick::hasnextimage ( void ) : 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.


Checks if the object has a previous image

  • « Gmagick::hasnextimage
  • Gmagick::implodeimage »
  • PHP Manual
  • Gmagick
  • Checks if the object has a previous image

Gmagick::haspreviousimage

(PECL gmagick >= Unknown)

Gmagick::haspreviousimage — Checks if the object has a previous image

Description

public Gmagick::haspreviousimage ( void ) : 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.


Creates a new image as a copy

  • « Gmagick::haspreviousimage
  • Gmagick::labelimage »
  • PHP Manual
  • Gmagick
  • Creates a new image as a copy

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.


Adds a label to an image

  • « Gmagick::implodeimage
  • Gmagick::levelimage »
  • PHP Manual
  • Gmagick
  • Adds a label to an image

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.


Adjusts the levels of an image

  • « Gmagick::labelimage
  • Gmagick::magnifyimage »
  • PHP Manual
  • Gmagick
  • Adjusts the levels of an image

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 levelled.

Errors/Exceptions

Throws an GmagickException on error.


Scales an image proportionally 2x

  • « Gmagick::levelimage
  • Gmagick::mapimage »
  • PHP Manual
  • Gmagick
  • Scales an image proportionally 2x

Gmagick::magnifyimage

(PECL gmagick >= Unknown)

Gmagick::magnifyimage — Scales an image proportionally 2x

Description

public Gmagick::magnifyimage ( void ) : 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.


Replaces the colors of an image with the closest color from a reference image

  • « Gmagick::magnifyimage
  • Gmagick::medianfilterimage »
  • PHP Manual
  • Gmagick
  • Replaces the colors of an image with the closest color from a reference image

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

Gmagick object

Errors/Exceptions

Throws an GmagickException on error.


Applies a digital filter

  • « Gmagick::mapimage
  • Gmagick::minifyimage »
  • PHP Manual
  • Gmagick
  • Applies a digital filter

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.


Scales an image proportionally to half its size

  • « Gmagick::medianfilterimage
  • Gmagick::modulateimage »
  • PHP Manual
  • Gmagick
  • Scales an image proportionally to half its size

Gmagick::minifyimage

(PECL gmagick >= Unknown)

Gmagick::minifyimage — Scales an image proportionally to half its size

Description

public Gmagick::minifyimage ( void ) : 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 on success

Errors/Exceptions

Throws an GmagickException on error.


Control the brightness, saturation, and hue

  • « Gmagick::minifyimage
  • Gmagick::motionblurimage »
  • PHP Manual
  • Gmagick
  • Control the brightness, saturation, and hue

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 on success

Errors/Exceptions

Throws an GmagickException on error.


Simulates motion blur

  • « Gmagick::modulateimage
  • Gmagick::newimage »
  • PHP Manual
  • Gmagick
  • Simulates motion blur

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 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 on success

Errors/Exceptions

Throws an GmagickException on error.


Creates a new image

  • « Gmagick::motionblurimage
  • Gmagick::nextimage »
  • PHP Manual
  • Gmagick
  • Creates a new image

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 on success

Errors/Exceptions

Throws an GmagickException on error.


Moves to the next image

  • « Gmagick::newimage
  • Gmagick::normalizeimage »
  • PHP Manual
  • Gmagick
  • Moves to the next image

Gmagick::nextimage

(PECL gmagick >= Unknown)

Gmagick::nextimage — Moves to the next image

Description

public Gmagick::nextimage ( void ) : 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.


Enhances the contrast of a color image

  • « Gmagick::nextimage
  • Gmagick::oilpaintimage »
  • PHP Manual
  • Gmagick
  • Enhances the contrast of a color image

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 on success

Errors/Exceptions

Throws an GmagickException on error.


Simulates an oil painting

  • « Gmagick::normalizeimage
  • Gmagick::previousimage »
  • PHP Manual
  • Gmagick
  • Simulates an oil painting

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.


Move to the previous image in the object

  • « Gmagick::oilpaintimage
  • Gmagick::profileimage »
  • PHP Manual
  • Gmagick
  • Move to the previous image in the object

Gmagick::previousimage

(PECL gmagick >= Unknown)

Gmagick::previousimage — Move to the previous image in the object

Description

public Gmagick::previousimage ( void ) : 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.


Adds or removes a profile from an image

  • « Gmagick::previousimage
  • Gmagick::quantizeimage »
  • PHP Manual
  • Gmagick
  • Adds or removes a profile from an image

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 on success

Errors/Exceptions

Throws an GmagickException on error.


Analyzes the colors within a reference image

  • « Gmagick::profileimage
  • Gmagick::quantizeimages »
  • PHP Manual
  • Gmagick
  • Analyzes the colors within a reference image

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.


The quantizeimages purpose

  • « Gmagick::quantizeimage
  • Gmagick::queryfontmetrics »
  • PHP Manual
  • Gmagick
  • The quantizeimages purpose

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.


Returns an array representing the font metrics

  • « Gmagick::quantizeimages
  • Gmagick::queryfonts »
  • PHP Manual
  • Gmagick
  • Returns an array representing the font metrics

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.


Returns the configured fonts

  • « Gmagick::queryfontmetrics
  • Gmagick::queryformats »
  • PHP Manual
  • Gmagick
  • Returns the configured fonts

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.


Returns formats supported by Gmagick

  • « Gmagick::queryfonts
  • Gmagick::radialblurimage »
  • PHP Manual
  • Gmagick
  • Returns formats supported by Gmagick

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 on success

Errors/Exceptions

Throws an GmagickException on error.


Radial blurs an image

  • « Gmagick::queryformats
  • Gmagick::raiseimage »
  • PHP Manual
  • Gmagick
  • Radial blurs an image

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 on success

Errors/Exceptions

Throws an GmagickException on error.


Creates a simulated 3d button-like effect

  • « Gmagick::radialblurimage
  • Gmagick::read »
  • PHP Manual
  • Gmagick
  • Creates a simulated 3d button-like effect

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 on success

Errors/Exceptions

Throws an GmagickException on error.


Reads image from filename

  • « Gmagick::raiseimage
  • Gmagick::readimage »
  • PHP Manual
  • Gmagick
  • Reads image from filename

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 on success

Errors/Exceptions

Throws an GmagickException on error.


Reads image from filename

  • « Gmagick::read
  • Gmagick::readimageblob »
  • PHP Manual
  • Gmagick
  • Reads image from filename

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 on success

Errors/Exceptions

Throws an GmagickException on error.


Reads image from a binary string

  • « Gmagick::readimage
  • Gmagick::readimagefile »
  • PHP Manual
  • Gmagick
  • Reads image from a binary string

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 on success

Errors/Exceptions

Throws an GmagickException on error.


The readimagefile purpose

  • « Gmagick::readimageblob
  • Gmagick::reducenoiseimage »
  • PHP Manual
  • Gmagick
  • The readimagefile purpose

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 on success

Errors/Exceptions

Throws an GmagickException on error.


Smooths the contours of an image

  • « Gmagick::readimagefile
  • Gmagick::removeimage »
  • PHP Manual
  • Gmagick
  • Smooths the contours of an image

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 on success

Errors/Exceptions

Throws an GmagickException on error.


Removes an image from the image list

  • « Gmagick::reducenoiseimage
  • Gmagick::removeimageprofile »
  • PHP Manual
  • Gmagick
  • Removes an image from the image list

Gmagick::removeimage

(PECL gmagick >= Unknown)

Gmagick::removeimage — Removes an image from the image list

Description

public Gmagick::removeimage ( void ) : Gmagick

Removes an image from the image list.

Parameters

This function has no parameters.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.


Removes the named image profile and returns it

  • « Gmagick::removeimage
  • Gmagick::resampleimage »
  • PHP Manual
  • Gmagick
  • Removes the named image profile and returns it

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.


Resample image to desired resolution

  • « Gmagick::removeimageprofile
  • Gmagick::resizeimage »
  • PHP Manual
  • Gmagick
  • Resample image to desired resolution

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.


Scales an image

  • « Gmagick::resampleimage
  • Gmagick::rollimage »
  • PHP Manual
  • Gmagick
  • Scales an image

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 on success

Errors/Exceptions

Throws an GmagickException on error.


Offsets an image

  • « Gmagick::resizeimage
  • Gmagick::rotateimage »
  • PHP Manual
  • Gmagick
  • Offsets an image

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.


Rotates an image

  • « Gmagick::rollimage
  • Gmagick::scaleimage »
  • PHP Manual
  • Gmagick
  • Rotates an image

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.


Scales the size of an image

  • « Gmagick::rotateimage
  • Gmagick::separateimagechannel »
  • PHP Manual
  • Gmagick
  • Scales the size of an image

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 on success.

Errors/Exceptions

Throws an GmagickException on error.


Separates a channel from the image

  • « Gmagick::scaleimage
  • Gmagick::setCompressionQuality »
  • PHP Manual
  • Gmagick
  • Separates a channel from the image

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

Identify which channel to extract: RedChannel, GreenChannel, BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel, BlackChannel.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.


Sets the object's default compression quality

  • « Gmagick::separateimagechannel
  • Gmagick::setfilename »
  • PHP Manual
  • Gmagick
  • Sets the object's default compression quality

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 = 75 ) : Gmagick

Sets the object's default compression quality.

Parameters

quality

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.

Examples

Example #1 Gmagick::setCompressionQuality()

<?php
$gm = new Gmagick();
$gm->read("magick:rose");
$gm->setCompressionQuality(2);
?>


Sets the filename before you read or write the image

  • « Gmagick::setCompressionQuality
  • Gmagick::setimagebackgroundcolor »
  • PHP Manual
  • Gmagick
  • Sets the filename before you read or write the image

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 on success

Errors/Exceptions

Throws an GmagickException on error.


Sets the image background color

  • « Gmagick::setfilename
  • Gmagick::setimageblueprimary »
  • PHP Manual
  • Gmagick
  • Sets the image background color

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 on success

Errors/Exceptions

Throws an GmagickException on error.


Sets the image chromaticity blue primary point

  • « Gmagick::setimagebackgroundcolor
  • Gmagick::setimagebordercolor »
  • PHP Manual
  • Gmagick
  • Sets the image chromaticity blue primary point

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 on success

Errors/Exceptions

Throws an GmagickException on error.


Sets the image border color

  • « Gmagick::setimageblueprimary
  • Gmagick::setimagechanneldepth »
  • PHP Manual
  • Gmagick
  • Sets the image border color

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 on success

Errors/Exceptions

Throws an GmagickException on error.


Sets the depth of a particular image channel

  • « Gmagick::setimagebordercolor
  • Gmagick::setimagecolorspace »
  • PHP Manual
  • Gmagick
  • Sets the depth of a particular image channel

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

Identify which channel to extract: RedChannel, GreenChannel, BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel, BlackChannel.

depth

The image depth in bits.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.


Sets the image colorspace

  • « Gmagick::setimagechanneldepth
  • Gmagick::setimagecompose »
  • PHP Manual
  • Gmagick
  • Sets the image colorspace

Gmagick::setimagecolorspace

(PECL gmagick >= Unknown)

Gmagick::setimagecolorspace — Sets the image colorspace

Description

public Gmagick::setimagecolorspace ( int $colorspace ) : Gmagick

Sets the image colorspace.

Parameters

colorspace

The image colorspace: UndefinedColorspace, RGBColorspace, GRAYColorspace, TransparentColorspace, OHTAColorspace, XYZColorspace, YCbCrColorspace, YCCColorspace, YIQColorspace, YPbPrColorspace, YPbPrColorspace, YUVColorspace, CMYKColorspace, sRGBColorspace, HSLColorspace, or HWBColorspace.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.


Sets the image composite operator

  • « Gmagick::setimagecolorspace
  • Gmagick::setimagedelay »
  • PHP Manual
  • Gmagick
  • Sets the image composite operator

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.


Sets the image delay

  • « Gmagick::setimagecompose
  • Gmagick::setimagedepth »
  • PHP Manual
  • Gmagick
  • Sets the image delay

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 on success.

Errors/Exceptions

Throws an GmagickException on error.


Sets the image depth

  • « Gmagick::setimagedelay
  • Gmagick::setimagedispose »
  • PHP Manual
  • Gmagick
  • Sets the image depth

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 on success.

Errors/Exceptions

Throws an GmagickException on error.


Sets the image disposal method

  • « Gmagick::setimagedepth
  • Gmagick::setimagefilename »
  • PHP Manual
  • Gmagick
  • Sets the image disposal method

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 on success

Errors/Exceptions

Throws an GmagickException on error.


Sets the filename of a particular image in a sequence

  • « Gmagick::setimagedispose
  • Gmagick::setimageformat »
  • PHP Manual
  • Gmagick
  • Sets the filename of a particular image in a sequence

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 on success.

Errors/Exceptions

Throws an GmagickException on error.


Sets the format of a particular image

  • « Gmagick::setimagefilename
  • Gmagick::setimagegamma »
  • PHP Manual
  • Gmagick
  • Sets the format of a particular image

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 on success.

Errors/Exceptions

Throws an GmagickException on error.


Sets the image gamma

  • « Gmagick::setimageformat
  • Gmagick::setimagegreenprimary »
  • PHP Manual
  • Gmagick
  • Sets the image gamma

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 on success

Errors/Exceptions

Throws an GmagickException on error.


Sets the image chromaticity green primary point

  • « Gmagick::setimagegamma
  • Gmagick::setimageindex »
  • PHP Manual
  • Gmagick
  • Sets the image chromaticity green primary point

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 on success.

Errors/Exceptions

Throws an GmagickException on error.


Set the iterator to the position in the image list specified with the index parameter

  • « Gmagick::setimagegreenprimary
  • Gmagick::setimageinterlacescheme »
  • PHP Manual
  • Gmagick
  • Set the iterator to the position in the image list specified with the index parameter

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 on success.

Errors/Exceptions

Throws an GmagickException on error.


Sets the interlace scheme of the image

  • « Gmagick::setimageindex
  • Gmagick::setimageiterations »
  • PHP Manual
  • Gmagick
  • Sets the interlace scheme of the image

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

The image interlace scheme: NoInterlace, LineInterlace, PlaneInterlace, PartitionInterlace.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.


Sets the image iterations

  • « Gmagick::setimageinterlacescheme
  • Gmagick::setimageprofile »
  • PHP Manual
  • Gmagick
  • Sets the image iterations

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 on success.

Errors/Exceptions

Throws an GmagickException on error.


Adds a named profile to the Gmagick object

  • « Gmagick::setimageiterations
  • Gmagick::setimageredprimary »
  • PHP Manual
  • Gmagick
  • Adds a named profile to the Gmagick object

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.


Sets the image chromaticity red primary point

  • « Gmagick::setimageprofile
  • Gmagick::setimagerenderingintent »
  • PHP Manual
  • Gmagick
  • Sets the image chromaticity red primary point

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.


Sets the image rendering intent

  • « Gmagick::setimageredprimary
  • Gmagick::setimageresolution »
  • PHP Manual
  • Gmagick
  • Sets the image rendering intent

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

The image rendering intent: UndefinedIntent, SaturationIntent, PerceptualIntent, AbsoluteIntent, or RelativeIntent.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.


Sets the image resolution

  • « Gmagick::setimagerenderingintent
  • Gmagick::setimagescene »
  • PHP Manual
  • Gmagick
  • Sets the image resolution

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.


Sets the image scene

  • « Gmagick::setimageresolution
  • Gmagick::setimagetype »
  • PHP Manual
  • Gmagick
  • Sets the image scene

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 on success.

Errors/Exceptions

Throws an GmagickException on error.


Sets the image type

  • « Gmagick::setimagescene
  • Gmagick::setimageunits »
  • PHP Manual
  • Gmagick
  • Sets the image type

Gmagick::setimagetype

(PECL gmagick >= Unknown)

Gmagick::setimagetype — Sets the image type

Description

public Gmagick::setimagetype ( int $imgType ) : Gmagick

Sets the image type.

Parameters

imgType

The image type: UndefinedType, BilevelType, GrayscaleType, GrayscaleMatteType, PaletteType, PaletteMatteType, TrueColorType, TrueColorMatteType, ColorSeparationType, ColorSeparationMatteType, or OptimizeType.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.


Sets the image units of resolution

  • « Gmagick::setimagetype
  • Gmagick::setimagewhitepoint »
  • PHP Manual
  • Gmagick
  • Sets the image units of resolution

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

The image units of resolution : Undefinedresolution, PixelsPerInchResolution, or PixelsPerCentimeterResolution.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.


Sets the image chromaticity white point

  • « Gmagick::setimageunits
  • Gmagick::setsamplingfactors »
  • PHP Manual
  • Gmagick
  • Sets the image chromaticity white point

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 on success.

Errors/Exceptions

Throws an GmagickException on error.


Sets the image sampling factors

  • « Gmagick::setimagewhitepoint
  • Gmagick::setsize »
  • PHP Manual
  • Gmagick
  • Sets the image sampling factors

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 doubles representing the sampling factor for each color component (in RGB order).

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.


Sets the size of the Gmagick object

  • « Gmagick::setsamplingfactors
  • Gmagick::shearimage »
  • PHP Manual
  • Gmagick
  • Sets the size of the Gmagick object

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 RGB, GRAY, or CMYK.

Parameters

columns

The width in pixels.

rows

The height in pixels.

Return Values

The Gmagick object on success.

Errors/Exceptions

Throws an GmagickException on error.


Creating a parallelogram

  • « Gmagick::setsize
  • Gmagick::solarizeimage »
  • PHP Manual
  • Gmagick
  • Creating a parallelogram

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 on success

Errors/Exceptions

Throws an GmagickException on error.


Applies a solarizing effect to the image

  • « Gmagick::shearimage
  • Gmagick::spreadimage »
  • PHP Manual
  • Gmagick
  • Applies a solarizing effect to the image

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 on success.

Errors/Exceptions

Throws an GmagickException on error.


Randomly displaces each pixel in a block

  • « Gmagick::solarizeimage
  • Gmagick::stripimage »
  • PHP Manual
  • Gmagick
  • Randomly displaces each pixel in a block

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 on success

Errors/Exceptions

Throws an GmagickException on error.


Strips an image of all profiles and comments

  • « Gmagick::spreadimage
  • Gmagick::swirlimage »
  • PHP Manual
  • Gmagick
  • Strips an image of all profiles and comments

Gmagick::stripimage

(PECL gmagick >= Unknown)

Gmagick::stripimage — Strips an image of all profiles and comments

Description

public Gmagick::stripimage ( void ) : Gmagick

Strips an image of all profiles and comments.

Parameters

This function has no parameters.

Return Values

The Gmagick object on success

Errors/Exceptions

Throws an GmagickException on error.


Swirls the pixels about the center of the image

  • « Gmagick::stripimage
  • Gmagick::thumbnailimage »
  • PHP Manual
  • Gmagick
  • Swirls the pixels about the center of the image

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 on success

Errors/Exceptions

Throws an GmagickException on error.


Changes the size of an image

  • « Gmagick::swirlimage
  • Gmagick::trimimage »
  • PHP Manual
  • Gmagick
  • Changes the size of an image

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 on success.

Errors/Exceptions

Throws an GmagickException on error.


Remove edges from the image

  • « Gmagick::thumbnailimage
  • Gmagick::write »
  • PHP Manual
  • Gmagick
  • Remove edges from the image

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.


Alias of Gmagick::writeimage

  • « Gmagick::trimimage
  • Gmagick::writeimage »
  • PHP Manual
  • Gmagick
  • Alias of Gmagick::writeimage

Gmagick::write

(PECL gmagick >= Unknown)

Gmagick::write — Alias of Gmagick::writeimage()

Description

This method is an alias of: Gmagick::writeimage().


Writes an image to the specified filename

  • « Gmagick::write
  • GmagickDraw »
  • PHP Manual
  • Gmagick
  • Writes an image to the specified filename

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.


The GmagickDraw class

(PECL gmagick >= Unknown)

Introduction

Class synopsis

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 ( void ) : GmagickPixel
public getfillopacity ( void ) : float
public getfont ( void ) : mixed
public getfontsize ( void ) : float
public getfontstyle ( void ) : int
public getfontweight ( void ) : int
public getstrokecolor ( void ) : GmagickPixel
public getstrokeopacity ( void ) : float
public getstrokewidth ( void ) : float
public gettextdecoration ( void ) : int
public gettextencoding ( void ) : 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
}

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 — The line purpose
  • 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


Draws text on the image

  • « GmagickDraw
  • GmagickDraw::arc »
  • PHP Manual
  • GmagickDraw
  • Draws text on the image

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 on success.


Draws an arc

  • « GmagickDraw::annotate
  • GmagickDraw::bezier »
  • PHP Manual
  • GmagickDraw
  • Draws an arc

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 on success.


Draws a bezier curve

  • « GmagickDraw::arc
  • GmagickDraw::ellipse »
  • PHP Manual
  • GmagickDraw
  • Draws a bezier curve

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 on success


Draws an ellipse on the image

  • « GmagickDraw::bezier
  • GmagickDraw::getfillcolor »
  • PHP Manual
  • GmagickDraw
  • Draws an ellipse on the image

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 on success


Returns the fill color

  • « GmagickDraw::ellipse
  • GmagickDraw::getfillopacity »
  • PHP Manual
  • GmagickDraw
  • Returns the fill color

GmagickDraw::getfillcolor

(PECL gmagick >= Unknown)

GmagickDraw::getfillcolor — Returns the fill color

Description

public GmagickDraw::getfillcolor ( void ) : 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.


Returns the opacity used when drawing

  • « GmagickDraw::getfillcolor
  • GmagickDraw::getfont »
  • PHP Manual
  • GmagickDraw
  • Returns the opacity used when drawing

GmagickDraw::getfillopacity

(PECL gmagick >= Unknown)

GmagickDraw::getfillopacity — Returns the opacity used when drawing

Description

public GmagickDraw::getfillopacity ( void ) : 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.


Returns the font

  • « GmagickDraw::getfillopacity
  • GmagickDraw::getfontsize »
  • PHP Manual
  • GmagickDraw
  • Returns the font

GmagickDraw::getfont

(PECL gmagick >= Unknown)

GmagickDraw::getfont — Returns the font

Description

public GmagickDraw::getfont ( void ) : 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.


Returns the font pointsize

  • « GmagickDraw::getfont
  • GmagickDraw::getfontstyle »
  • PHP Manual
  • GmagickDraw
  • Returns the font pointsize

GmagickDraw::getfontsize

(PECL gmagick >= Unknown)

GmagickDraw::getfontsize — Returns the font pointsize

Description

public GmagickDraw::getfontsize ( void ) : 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.


Returns the font style

  • « GmagickDraw::getfontsize
  • GmagickDraw::getfontweight »
  • PHP Manual
  • GmagickDraw
  • Returns the font style

GmagickDraw::getfontstyle

(PECL gmagick >= Unknown)

GmagickDraw::getfontstyle — Returns the font style

Description

public GmagickDraw::getfontstyle ( void ) : 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.


Returns the font weight

  • « GmagickDraw::getfontstyle
  • GmagickDraw::getstrokecolor »
  • PHP Manual
  • GmagickDraw
  • Returns the font weight

GmagickDraw::getfontweight

(PECL gmagick >= Unknown)

GmagickDraw::getfontweight — Returns the font weight

Description

public GmagickDraw::getfontweight ( void ) : 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.


Returns the color used for stroking object outlines

  • « GmagickDraw::getfontweight
  • GmagickDraw::getstrokeopacity »
  • PHP Manual
  • GmagickDraw
  • Returns the color used for stroking object outlines

GmagickDraw::getstrokecolor

(PECL gmagick >= Unknown)

GmagickDraw::getstrokecolor — Returns the color used for stroking object outlines

Description

public GmagickDraw::getstrokecolor ( void ) : 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.


Returns the opacity of stroked object outlines

  • « GmagickDraw::getstrokecolor
  • GmagickDraw::getstrokewidth »
  • PHP Manual
  • GmagickDraw
  • Returns the opacity of stroked object outlines

GmagickDraw::getstrokeopacity

(PECL gmagick >= Unknown)

GmagickDraw::getstrokeopacity — Returns the opacity of stroked object outlines

Description

public GmagickDraw::getstrokeopacity ( void ) : float

Returns the opacity of stroked object outlines.

Parameters

This function has no parameters.

Return Values

Returns a double describing the opacity.


Returns the width of the stroke used to draw object outlines

  • « GmagickDraw::getstrokeopacity
  • GmagickDraw::gettextdecoration »
  • PHP Manual
  • GmagickDraw
  • Returns the width of the stroke used to draw object outlines

GmagickDraw::getstrokewidth

(PECL gmagick >= Unknown)

GmagickDraw::getstrokewidth — Returns the width of the stroke used to draw object outlines

Description

public GmagickDraw::getstrokewidth ( void ) : float

Returns the width of the stroke used to draw object outlines.

Parameters

This function has no parameters.

Return Values

Returns a double describing the stroke width.


Returns the text decoration

  • « GmagickDraw::getstrokewidth
  • GmagickDraw::gettextencoding »
  • PHP Manual
  • GmagickDraw
  • Returns the text decoration

GmagickDraw::gettextdecoration

(PECL gmagick >= Unknown)

GmagickDraw::gettextdecoration — Returns the text decoration

Description

public GmagickDraw::gettextdecoration ( void ) : 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.


Returns the code set used for text annotations

  • « GmagickDraw::gettextdecoration
  • GmagickDraw::line »
  • PHP Manual
  • GmagickDraw
  • Returns the code set used for text annotations

GmagickDraw::gettextencoding

(PECL gmagick >= Unknown)

GmagickDraw::gettextencoding — Returns the code set used for text annotations

Description

public GmagickDraw::gettextencoding ( void ) : 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.


The line purpose

  • « GmagickDraw::gettextencoding
  • GmagickDraw::point »
  • PHP Manual
  • GmagickDraw
  • The line purpose

GmagickDraw::line

(PECL gmagick >= Unknown)

GmagickDraw::line — The line purpose

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 on success


Draws a point

  • « GmagickDraw::line
  • GmagickDraw::polygon »
  • PHP Manual
  • GmagickDraw
  • Draws a point

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 on success


Draws a polygon

  • « GmagickDraw::point
  • GmagickDraw::polyline »
  • PHP Manual
  • GmagickDraw
  • Draws a polygon

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 on success


Draws a polyline

  • « GmagickDraw::polygon
  • GmagickDraw::rectangle »
  • PHP Manual
  • GmagickDraw
  • Draws a polyline

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 on success


Draws a rectangle

  • « GmagickDraw::polyline
  • GmagickDraw::rotate »
  • PHP Manual
  • GmagickDraw
  • Draws a rectangle

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 on success


Applies the specified rotation to the current coordinate space

  • « GmagickDraw::rectangle
  • GmagickDraw::roundrectangle »
  • PHP Manual
  • GmagickDraw
  • Applies the specified rotation to the current coordinate space

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 on success


Draws a rounded rectangle

  • « GmagickDraw::rotate
  • GmagickDraw::scale »
  • PHP Manual
  • GmagickDraw
  • Draws a rounded rectangle

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 on success


Adjusts the scaling factor

  • « GmagickDraw::roundrectangle
  • GmagickDraw::setfillcolor »
  • PHP Manual
  • GmagickDraw
  • Adjusts the scaling factor

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 on success


Sets the fill color to be used for drawing filled objects

  • « GmagickDraw::scale
  • GmagickDraw::setfillopacity »
  • PHP Manual
  • GmagickDraw
  • Sets the fill color to be used for drawing filled objects

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.


The setfillopacity purpose

  • « GmagickDraw::setfillcolor
  • GmagickDraw::setfont »
  • PHP Manual
  • GmagickDraw
  • The setfillopacity purpose

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 on success


Sets the fully-specified font to use when annotating with text

  • « GmagickDraw::setfillopacity
  • GmagickDraw::setfontsize »
  • PHP Manual
  • GmagickDraw
  • Sets the fully-specified font to use when annotating with text

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 on success


Sets the font pointsize to use when annotating with text

  • « GmagickDraw::setfont
  • GmagickDraw::setfontstyle »
  • PHP Manual
  • GmagickDraw
  • Sets the font pointsize to use when annotating with text

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 on success


Sets the font style to use when annotating with text

  • « GmagickDraw::setfontsize
  • GmagickDraw::setfontweight »
  • PHP Manual
  • GmagickDraw
  • Sets the font style to use when annotating with text

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 on success


Sets the font weight

  • « GmagickDraw::setfontstyle
  • GmagickDraw::setstrokecolor »
  • PHP Manual
  • GmagickDraw
  • Sets the font weight

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 on success


Sets the color used for stroking object outlines

  • « GmagickDraw::setfontweight
  • GmagickDraw::setstrokeopacity »
  • PHP Manual
  • GmagickDraw
  • Sets the color used for stroking object outlines

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.


Specifies the opacity of stroked object outlines

  • « GmagickDraw::setstrokecolor
  • GmagickDraw::setstrokewidth »
  • PHP Manual
  • GmagickDraw
  • Specifies the opacity of stroked object outlines

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 on success


Sets the width of the stroke used to draw object outlines

  • « GmagickDraw::setstrokeopacity
  • GmagickDraw::settextdecoration »
  • PHP Manual
  • GmagickDraw
  • Sets the width of the stroke used to draw object outlines

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 on success


Specifies a decoration

  • « GmagickDraw::setstrokewidth
  • GmagickDraw::settextencoding »
  • PHP Manual
  • GmagickDraw
  • Specifies a decoration

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 on success


Specifies the text code set

  • « GmagickDraw::settextdecoration
  • GmagickPixel »
  • PHP Manual
  • GmagickDraw
  • Specifies the text code set

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 on success


The GmagickPixel class

(PECL gmagick >= Unknown)

Introduction

Class synopsis

GmagickPixel {
/* Methods */
public __construct ([ string $color ] )
public getcolor ([ bool $as_array = FALSE [, bool $normalize_array = FALSE ]] ) : mixed
public getcolorcount ( void ) : int
public getcolorvalue ( int $color ) : float
public setcolor ( string $color ) : GmagickPixel
public setcolorvalue ( int $color , float $value ) : GmagickPixel
}

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


The GmagickPixel constructor

  • « GmagickPixel
  • GmagickPixel::getcolor »
  • PHP Manual
  • GmagickPixel
  • The GmagickPixel constructor

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.

Return Values

The GmagickPixel object on success.


Returns the color

  • « GmagickPixel::__construct
  • GmagickPixel::getcolorcount »
  • PHP Manual
  • GmagickPixel
  • Returns the color

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.


Returns the color count associated with this color

  • « GmagickPixel::getcolor
  • GmagickPixel::getcolorvalue »
  • PHP Manual
  • GmagickPixel
  • Returns the color count associated with this color

GmagickPixel::getcolorcount

(PECL gmagick >= Unknown)

GmagickPixel::getcolorcount — Returns the color count associated with this color

Description

public GmagickPixel::getcolorcount ( void ) : 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.


Gets the normalized value of the provided color channel

  • « GmagickPixel::getcolorcount
  • GmagickPixel::setcolor »
  • PHP Manual
  • GmagickPixel
  • Gets the normalized value of the provided color channel

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.


Sets the color

  • « GmagickPixel::getcolorvalue
  • GmagickPixel::setcolorvalue »
  • PHP Manual
  • GmagickPixel
  • Sets the color

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 on success.


Sets the normalized value of one of the channels

  • « GmagickPixel::setcolor
  • ImageMagick »
  • PHP Manual
  • GmagickPixel
  • Sets the normalized value of one of the channels

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 on success.


Image Processing (ImageMagick)

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • 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 — Description
    • Imagick::averageImages — Average a set of images
    • Imagick::blackThresholdImage — Forces all pixels below the threshold into black
    • Imagick::blueShiftImage — Description
    • Imagick::blurImage — Adds blur filter to image
    • Imagick::borderImage — Surrounds the image with a border
    • Imagick::brightnessContrastImage — Description
    • Imagick::charcoalImage — Simulates a charcoal drawing
    • Imagick::chopImage — Removes a region of an image and trims
    • Imagick::clampImage — Description
    • Imagick::clear — Clears all resources associated to Imagick object
    • Imagick::clipImage — Clips along the first path from the 8BIM profile
    • Imagick::clipImagePath — Description
    • 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 — Description
    • 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 — Description
    • 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 — Description
    • 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 vertical mirror image
    • Imagick::forwardFourierTransformImage — Description
    • 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 — Gets the image alpha channel
    • Imagick::getImageArtifact — Get image artifact
    • Imagick::getImageAttribute — Description
    • 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::getImageMagickLicense — Returns a string containing the ImageMagick license
    • Imagick::getImageMatte — Return if the image has a matte channel
    • Imagick::getImageMatteColor — Returns the image matte color
    • Imagick::getImageMimeType — Description
    • 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 — Description
    • Imagick::getQuantumDepth — Gets the quantum depth
    • Imagick::getQuantumRange — Returns the Imagick quantum range
    • Imagick::getRegistry — Description
    • 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 — Description
    • Imagick::identifyImage — Identifies an image and fetches attributes
    • Imagick::implodeImage — Creates a new image as a copy
    • Imagick::importImagePixels — Imports image pixels
    • Imagick::inverseFourierTransformImage — Description
    • 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 — Description
    • 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 — Description
    • 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 — Description
    • 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 — Description
    • 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 — Description
    • 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 — Description
    • Imagick::setImageBackgroundColor — Sets the image background color
    • Imagick::setImageBias — Sets the image bias for any method that convolves an image
    • Imagick::setImageBiasQuantum — Description
    • 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 — Description
    • Imagick::setRegistry — Description
    • 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 — Description
    • 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 — Description
    • 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 — Description
    • 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 — Description
    • 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 — Description
    • ImagickDraw::getTextInterwordSpacing — Description
    • ImagickDraw::getTextKerning — Description
    • 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 — Description
    • 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 — Description
    • 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 — Description
    • ImagickDraw::setTextInterwordSpacing — Description
    • ImagickDraw::setTextKerning — Description
    • 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
  • 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 — Description
    • ImagickPixel::getColorValue — Gets the normalized value of the provided color channel
    • ImagickPixel::getColorValueQuantum — Description
    • ImagickPixel::getHSL — Returns the normalized HSL color of the ImagickPixel object
    • ImagickPixel::getIndex — Description
    • ImagickPixel::isPixelSimilar — Check the distance between this color and another
    • ImagickPixel::isPixelSimilarQuantum — Description
    • ImagickPixel::isSimilar — Check the distance between this color and another
    • ImagickPixel::setColor — Sets the color
    • ImagickPixel::setColorCount — Description
    • ImagickPixel::setColorValue — Sets the normalized value of one of the channels
    • ImagickPixel::setColorValueQuantum — Description
    • ImagickPixel::setHSL — Sets the normalized HSL color
    • ImagickPixel::setIndex — Description
  • 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
  • ImagickKernel — The ImagickKernel class
    • ImagickKernel::addKernel — Description
    • ImagickKernel::addUnityKernel — Description
    • ImagickKernel::fromBuiltIn — Description
    • ImagickKernel::fromMatrix — Description
    • ImagickKernel::getMatrix — Description
    • ImagickKernel::scale — Description
    • ImagickKernel::separate — Description


Introduction

Imagick is a native php extension to create and modify images using the ImageMagick API.

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.


Requirements

Installation requirements on Windows

Version information does not differ from that above. There are binaries available from http://www.imagemagick.org/ so that you can load this extension on Windows without need for a compiler.

Installation requirements on other platforms

PHP >= 5.1.3 and 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.


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 | PHP_INI_ALL | Available since Imagick 2.1.0
imagick.progress_monitor | FALSE | PHP_INI_SYSTEM | Available since Imagick 2.2.2
imagick.skip_version_check | FALSE | PHP_INI_SYSTEM | Available since Imagick 3.3.0
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

imagick.locale_fix boolean

Fixes a drawing bug with locales that use ',' as float separators.

imagick.progress_monitor boolean

Used to enable the image progress monitor.

imagick.skip_version_check boolean

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 (integer)
Black color
imagick::COLOR_BLUE (integer)
Blue color
imagick::COLOR_CYAN (integer)
Cyan color
imagick::COLOR_GREEN (integer)
Green color
imagick::COLOR_RED (integer)
Red color
imagick::COLOR_YELLOW (integer)
Yellow color
imagick::COLOR_MAGENTA (integer)
Magenta color
imagick::COLOR_OPACITY (integer)
Color's opacity
imagick::COLOR_ALPHA (integer)
Color's alpha
imagick::COLOR_FUZZ (integer)
Color's fuzz
DISPOSE constants

Dispose type constants

imagick::DISPOSE_UNRECOGNIZED (integer)
Unrecognized dispose type
imagick::DISPOSE_UNDEFINED (integer)
Undefined dispose type
imagick::DISPOSE_NONE (integer)
No dispose type defined
imagick::DISPOSE_BACKGROUND (integer)
Dispose background
imagick::DISPOSE_PREVIOUS (integer)
Dispose previous
Composite Operator Constants
imagick::COMPOSITE_DEFAULT (integer)
The default composite operator
imagick::COMPOSITE_UNDEFINED (integer)
Undefined composite operator
imagick::COMPOSITE_NO (integer)
No composite operator defined
imagick::COMPOSITE_ADD (integer)
The result of image + image
imagick::COMPOSITE_ATOP (integer)
The result is the same shape as image, with composite image obscuring image where the image shapes overlap
imagick::COMPOSITE_BLEND (integer)
Blends the image
imagick::COMPOSITE_BUMPMAP (integer)
The same as COMPOSITE_MULTIPLY, except the source is converted to grayscale first.
imagick::COMPOSITE_CLEAR (integer)
Makes the target image transparent
imagick::COMPOSITE_COLORBURN (integer)
Darkens the destination image to reflect the source image
imagick::COMPOSITE_COLORDODGE (integer)
Brightens the destination image to reflect the source image
imagick::COMPOSITE_COLORIZE (integer)
Colorizes the target image using the composite image
imagick::COMPOSITE_COPYBLACK (integer)
Copies black from the source to target
imagick::COMPOSITE_COPYBLUE (integer)
Copies blue from the source to target
imagick::COMPOSITE_COPY (integer)
Copies the source image on the target image
imagick::COMPOSITE_COPYCYAN (integer)
Copies cyan from the source to target
imagick::COMPOSITE_COPYGREEN (integer)
Copies green from the source to target
imagick::COMPOSITE_COPYMAGENTA (integer)
Copies magenta from the source to target
imagick::COMPOSITE_COPYOPACITY (integer)
Copies opacity from the source to target
imagick::COMPOSITE_COPYRED (integer)
Copies red from the source to target
imagick::COMPOSITE_COPYYELLOW (integer)
Copies yellow from the source to target
imagick::COMPOSITE_DARKEN (integer)
Darkens the target image
imagick::COMPOSITE_DSTATOP (integer)
The part of the destination lying inside of the source is composited over the source and replaces the destination
imagick::COMPOSITE_DST (integer)
The target is left untouched
imagick::COMPOSITE_DSTIN (integer)
The parts inside the source replace the target
imagick::COMPOSITE_DSTOUT (integer)
The parts outside the source replace the target
imagick::COMPOSITE_DSTOVER (integer)
Target replaces the source
imagick::COMPOSITE_DIFFERENCE (integer)
Subtracts the darker of the two constituent colors from the lighter
imagick::COMPOSITE_DISPLACE (integer)
Shifts target image pixels as defined by the source
imagick::COMPOSITE_DISSOLVE (integer)
Dissolves the source in to the target
imagick::COMPOSITE_EXCLUSION (integer)
Produces an effect similar to that of imagick::COMPOSITE_DIFFERENCE, but appears as lower contrast
imagick::COMPOSITE_HARDLIGHT (integer)
Multiplies or screens the colors, dependent on the source color value
imagick::COMPOSITE_HUE (integer)
Modifies the hue of the target as defined by source
imagick::COMPOSITE_IN (integer)
Composites source into the target
imagick::COMPOSITE_LIGHTEN (integer)
Lightens the target as defined by source
imagick::COMPOSITE_LUMINIZE (integer)
Luminizes the target as defined by source
imagick::COMPOSITE_MINUS (integer)
Subtracts the source from the target
imagick::COMPOSITE_MODULATE (integer)
Modulates the target brightness, saturation and hue as defined by source
imagick::COMPOSITE_MULTIPLY (integer)
Multiplies the target to the source
imagick::COMPOSITE_OUT (integer)
Composites outer parts of the source on the target
imagick::COMPOSITE_OVER (integer)
Composites source over the target
imagick::COMPOSITE_OVERLAY (integer)
Overlays the source on the target
imagick::COMPOSITE_PLUS (integer)
Adds the source to the target
imagick::COMPOSITE_REPLACE (integer)
Replaces the target with the source
imagick::COMPOSITE_SATURATE (integer)
Saturates the target as defined by the source
imagick::COMPOSITE_SCREEN (integer)
The source and destination are complemented and then multiplied and then replace the destination
imagick::COMPOSITE_SOFTLIGHT (integer)
Darkens or lightens the colors, dependent on the source
imagick::COMPOSITE_SRCATOP (integer)
The part of the source lying inside of the destination is composited onto the destination
imagick::COMPOSITE_SRC (integer)
The source is copied to the destination
imagick::COMPOSITE_SRCIN (integer)
The part of the source lying inside of the destination replaces the destination
imagick::COMPOSITE_SRCOUT (integer)
The part of the source lying outside of the destination replaces the destination
imagick::COMPOSITE_SRCOVER (integer)
The source replaces the destination
imagick::COMPOSITE_SUBTRACT (integer)
Subtract the colors in the source image from the destination image
imagick::COMPOSITE_THRESHOLD (integer)
The source is composited on the target as defined by source threshold
imagick::COMPOSITE_XOR (integer)
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 (integer)
imagick::MONTAGEMODE_UNFRAME (integer)
imagick::MONTAGEMODE_CONCATENATE (integer)
STYLE constants

imagick::STYLE_NORMAL (integer)
imagick::STYLE_ITALIC (integer)
imagick::STYLE_OBLIQUE (integer)
imagick::STYLE_ANY (integer)
FILTER constants

imagick::FILTER_UNDEFINED (integer)
imagick::FILTER_POINT (integer)
imagick::FILTER_BOX (integer)
imagick::FILTER_TRIANGLE (integer)
imagick::FILTER_HERMITE (integer)
imagick::FILTER_HANNING (integer)
imagick::FILTER_HAMMING (integer)
imagick::FILTER_BLACKMAN (integer)
imagick::FILTER_GAUSSIAN (integer)
imagick::FILTER_QUADRATIC (integer)
imagick::FILTER_CUBIC (integer)
imagick::FILTER_CATROM (integer)
imagick::FILTER_MITCHELL (integer)
imagick::FILTER_LANCZOS (integer)
imagick::FILTER_BESSEL (integer)
imagick::FILTER_SINC (integer)
IMGTYPE constants

imagick::IMGTYPE_UNDEFINED (integer)
imagick::IMGTYPE_BILEVEL (integer)
imagick::IMGTYPE_GRAYSCALE (integer)
imagick::IMGTYPE_GRAYSCALEMATTE (integer)
imagick::IMGTYPE_PALETTE (integer)
imagick::IMGTYPE_PALETTEMATTE (integer)
imagick::IMGTYPE_TRUECOLOR (integer)
imagick::IMGTYPE_TRUECOLORMATTE (integer)
imagick::IMGTYPE_COLORSEPARATION (integer)
imagick::IMGTYPE_COLORSEPARATIONMATTE (integer)
imagick::IMGTYPE_OPTIMIZE (integer)
RESOLUTION constants

imagick::RESOLUTION_UNDEFINED (integer)
imagick::RESOLUTION_PIXELSPERINCH (integer)
imagick::RESOLUTION_PIXELSPERCENTIMETER (integer)
COMPRESSION constants

imagick::COMPRESSION_UNDEFINED (integer)
imagick::COMPRESSION_NO (integer)
imagick::COMPRESSION_BZIP (integer)
imagick::COMPRESSION_FAX (integer)
imagick::COMPRESSION_GROUP4 (integer)
imagick::COMPRESSION_JPEG (integer)
imagick::COMPRESSION_JPEG2000 (integer)
imagick::COMPRESSION_LOSSLESSJPEG (integer)
imagick::COMPRESSION_LZW (integer)
imagick::COMPRESSION_RLE (integer)
imagick::COMPRESSION_ZIP (integer)
imagick::COMPRESSION_DXT1 (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.0 or higher.
imagick::COMPRESSION_DXT3 (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.0 or higher.
imagick::COMPRESSION_DXT5 (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.0 or higher.
PAINT constants

imagick::PAINT_POINT (integer)
imagick::PAINT_REPLACE (integer)
imagick::PAINT_FLOODFILL (integer)
imagick::PAINT_FILLTOBORDER (integer)
imagick::PAINT_RESET (integer)
GRAVITY constants

imagick::GRAVITY_NORTHWEST (integer)
imagick::GRAVITY_NORTH (integer)
imagick::GRAVITY_NORTHEAST (integer)
imagick::GRAVITY_WEST (integer)
imagick::GRAVITY_CENTER (integer)
imagick::GRAVITY_EAST (integer)
imagick::GRAVITY_SOUTHWEST (integer)
imagick::GRAVITY_SOUTH (integer)
imagick::GRAVITY_SOUTHEAST (integer)
STRETCH constants

imagick::STRETCH_NORMAL (integer)
imagick::STRETCH_ULTRACONDENSED (integer)
imagick::STRETCH_CONDENSED (integer)
imagick::STRETCH_SEMICONDENSED (integer)
imagick::STRETCH_SEMIEXPANDED (integer)
imagick::STRETCH_EXPANDED (integer)
imagick::STRETCH_EXTRAEXPANDED (integer)
imagick::STRETCH_ULTRAEXPANDED (integer)
imagick::STRETCH_ANY (integer)
ALIGN constants

imagick::ALIGN_UNDEFINED (integer)
imagick::ALIGN_LEFT (integer)
imagick::ALIGN_CENTER (integer)
imagick::ALIGN_RIGHT (integer)
DECORATION constants

imagick::DECORATION_NO (integer)
imagick::DECORATION_UNDERLINE (integer)
imagick::DECORATION_OVERLINE (integer)
imagick::DECORATION_LINETROUGH (integer)
NOISE constants

imagick::NOISE_UNIFORM (integer)
imagick::NOISE_GAUSSIAN (integer)
imagick::NOISE_MULTIPLICATIVEGAUSSIAN (integer)
imagick::NOISE_IMPULSE (integer)
imagick::NOISE_LAPLACIAN (integer)
imagick::NOISE_POISSON (integer)
imagick::NOISE_RANDOM (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
CHANNEL constants

imagick::CHANNEL_UNDEFINED (integer)
imagick::CHANNEL_RED (integer)
imagick::CHANNEL_GRAY (integer)
imagick::CHANNEL_CYAN (integer)
imagick::CHANNEL_GREEN (integer)
imagick::CHANNEL_MAGENTA (integer)
imagick::CHANNEL_BLUE (integer)
imagick::CHANNEL_YELLOW (integer)
imagick::CHANNEL_ALPHA (integer)
imagick::CHANNEL_OPACITY (integer)
imagick::CHANNEL_MATTE (integer)
imagick::CHANNEL_BLACK (integer)
imagick::CHANNEL_INDEX (integer)
imagick::CHANNEL_ALL (integer)
imagick::CHANNEL_DEFAULT (integer)
METRIC constants

imagick::METRIC_UNDEFINED (integer)
imagick::METRIC_MEANABSOLUTEERROR (integer)
imagick::METRIC_MEANSQUAREERROR (integer)
imagick::METRIC_PEAKABSOLUTEERROR (integer)
imagick::METRIC_PEAKSIGNALTONOISERATIO (integer)
imagick::METRIC_ROOTMEANSQUAREDERROR (integer)
PIXEL constants

imagick::PIXEL_CHAR (integer)
imagick::PIXEL_DOUBLE (integer)
imagick::PIXEL_FLOAT (integer)
imagick::PIXEL_INTEGER (integer)
Only available for ImageMagick < 7.
imagick::PIXEL_LONG (integer)
imagick::PIXEL_QUANTUM (integer)
imagick::PIXEL_SHORT (integer)
EVALUATE constants

imagick::EVALUATE_UNDEFINED (integer)
imagick::EVALUATE_ADD (integer)
imagick::EVALUATE_AND (integer)
imagick::EVALUATE_DIVIDE (integer)
imagick::EVALUATE_LEFTSHIFT (integer)
imagick::EVALUATE_MAX (integer)
imagick::EVALUATE_MIN (integer)
imagick::EVALUATE_MULTIPLY (integer)
imagick::EVALUATE_OR (integer)
imagick::EVALUATE_RIGHTSHIFT (integer)
imagick::EVALUATE_SET (integer)
imagick::EVALUATE_SUBTRACT (integer)
imagick::EVALUATE_XOR (integer)
imagick::EVALUATE_POW (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_LOG (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_THRESHOLD (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_THRESHOLDBLACK (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_THRESHOLDWHITE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_GAUSSIANNOISE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_IMPULSENOISE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_LAPLACIANNOISE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_MULTIPLICATIVENOISE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_POISSONNOISE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_UNIFORMNOISE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_COSINE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_SINE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
imagick::EVALUATE_ADDMODULUS (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.4 or higher.
COLORSPACE constants

imagick::COLORSPACE_UNDEFINED (integer)
imagick::COLORSPACE_RGB (integer)
imagick::COLORSPACE_GRAY (integer)
imagick::COLORSPACE_TRANSPARENT (integer)
imagick::COLORSPACE_OHTA (integer)
imagick::COLORSPACE_LAB (integer)
imagick::COLORSPACE_XYZ (integer)
imagick::COLORSPACE_YCBCR (integer)
imagick::COLORSPACE_YCC (integer)
imagick::COLORSPACE_YIQ (integer)
imagick::COLORSPACE_YPBPR (integer)
imagick::COLORSPACE_YUV (integer)
imagick::COLORSPACE_CMYK (integer)
imagick::COLORSPACE_SRGB (integer)
imagick::COLORSPACE_HSB (integer)
imagick::COLORSPACE_HSL (integer)
imagick::COLORSPACE_HWB (integer)
imagick::COLORSPACE_REC601LUMA (integer)
imagick::COLORSPACE_REC709LUMA (integer)
imagick::COLORSPACE_LOG (integer)
imagick::COLORSPACE_CMY (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.2 or higher.
VIRTUALPIXELMETHOD constants

imagick::VIRTUALPIXELMETHOD_UNDEFINED (integer)
imagick::VIRTUALPIXELMETHOD_BACKGROUND (integer)
imagick::VIRTUALPIXELMETHOD_CONSTANT (integer)
imagick::VIRTUALPIXELMETHOD_EDGE (integer)
imagick::VIRTUALPIXELMETHOD_MIRROR (integer)
imagick::VIRTUALPIXELMETHOD_TILE (integer)
imagick::VIRTUALPIXELMETHOD_TRANSPARENT (integer)
imagick::VIRTUALPIXELMETHOD_MASK (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.2 or higher.
imagick::VIRTUALPIXELMETHOD_BLACK (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.2 or higher.
imagick::VIRTUALPIXELMETHOD_GRAY (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.2 or higher.
imagick::VIRTUALPIXELMETHOD_WHITE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.2 or higher.
imagick::VIRTUALPIXELMETHOD_HORIZONTALTILE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.3 or higher.
imagick::VIRTUALPIXELMETHOD_VERTICALTILE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.3 or higher.
PREVIEW constants

imagick::PREVIEW_UNDEFINED (integer)
imagick::PREVIEW_ROTATE (integer)
imagick::PREVIEW_SHEAR (integer)
imagick::PREVIEW_ROLL (integer)
imagick::PREVIEW_HUE (integer)
imagick::PREVIEW_SATURATION (integer)
imagick::PREVIEW_BRIGHTNESS (integer)
imagick::PREVIEW_GAMMA (integer)
imagick::PREVIEW_SPIFF (integer)
imagick::PREVIEW_DULL (integer)
imagick::PREVIEW_GRAYSCALE (integer)
imagick::PREVIEW_QUANTIZE (integer)
imagick::PREVIEW_DESPECKLE (integer)
imagick::PREVIEW_REDUCENOISE (integer)
imagick::PREVIEW_ADDNOISE (integer)
imagick::PREVIEW_SHARPEN (integer)
imagick::PREVIEW_BLUR (integer)
imagick::PREVIEW_THRESHOLD (integer)
imagick::PREVIEW_EDGEDETECT (integer)
imagick::PREVIEW_SPREAD (integer)
imagick::PREVIEW_SOLARIZE (integer)
imagick::PREVIEW_SHADE (integer)
imagick::PREVIEW_RAISE (integer)
imagick::PREVIEW_SEGMENT (integer)
imagick::PREVIEW_SWIRL (integer)
imagick::PREVIEW_IMPLODE (integer)
imagick::PREVIEW_WAVE (integer)
imagick::PREVIEW_OILPAINT (integer)
imagick::PREVIEW_CHARCOALDRAWING (integer)
imagick::PREVIEW_JPEG (integer)
RENDERINGINTENT constants

imagick::RENDERINGINTENT_UNDEFINED (integer)
imagick::RENDERINGINTENT_SATURATION (integer)
imagick::RENDERINGINTENT_PERCEPTUAL (integer)
imagick::RENDERINGINTENT_ABSOLUTE (integer)
imagick::RENDERINGINTENT_RELATIVE (integer)
INTERLACE constants

imagick::INTERLACE_UNDEFINED (integer)
imagick::INTERLACE_NO (integer)
imagick::INTERLACE_LINE (integer)
imagick::INTERLACE_PLANE (integer)
imagick::INTERLACE_PARTITION (integer)
imagick::INTERLACE_GIF (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.4 or higher.
imagick::INTERLACE_JPEG (integer)
imagick::INTERLACE_PNG (integer)
FILLRULE constants

imagick::FILLRULE_UNDEFINED (integer)
imagick::FILLRULE_EVENODD (integer)
imagick::FILLRULE_NONZERO (integer)
PATHUNITS constants

imagick::PATHUNITS_UNDEFINED (integer)
imagick::PATHUNITS_USERSPACE (integer)
imagick::PATHUNITS_USERSPACEONUSE (integer)
imagick::PATHUNITS_OBJECTBOUNDINGBOX (integer)
LINECAP constants

imagick::LINECAP_UNDEFINED (integer)
imagick::LINECAP_BUTT (integer)
imagick::LINECAP_ROUND (integer)
imagick::LINECAP_SQUARE (integer)
LINEJOIN constants

imagick::LINEJOIN_UNDEFINED (integer)
imagick::LINEJOIN_MITER (integer)
imagick::LINEJOIN_ROUND (integer)
imagick::LINEJOIN_BEVEL (integer)
RESOURCETYPE constants

imagick::RESOURCETYPE_UNDEFINED (integer)
imagick::RESOURCETYPE_AREA (integer)
Set the maximum width * height of an image that can reside in the pixel cache memory.
imagick::RESOURCETYPE_DISK (integer)
Set maximum amount of disk space in bytes permitted for use by the pixel cache.
imagick::RESOURCETYPE_FILE (integer)
Set maximum number of open pixel cache files.
imagick::RESOURCETYPE_MAP (integer)
Set maximum amount of memory map in bytes to allocate for the pixel cache.
imagick::RESOURCETYPE_MEMORY (integer)
Set maximum amount of memory in bytes to allocate for the pixel cache from the heap.
imagick::RESOURCETYPE_THREAD (integer)
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 (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_COALESCE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_COMPAREANY (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_COMPARECLEAR (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_COMPAREOVERLAY (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_DISPOSE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_OPTIMIZE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_OPTIMIZEPLUS (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.2.9 or higher.
imagick::LAYERMETHOD_OPTIMIZEIMAGE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::LAYERMETHOD_OPTIMIZETRANS (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::LAYERMETHOD_REMOVEDUPS (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::LAYERMETHOD_REMOVEZERO (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::LAYERMETHOD_COMPOSITE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::LAYERMETHOD_MERGE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.7 or higher.
imagick::LAYERMETHOD_FLATTEN (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.7 or higher.
imagick::LAYERMETHOD_MOSAIC (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.7 or higher.
ORIENTATION constants

imagick::ORIENTATION_UNDEFINED (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_TOPLEFT (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_TOPRIGHT (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_BOTTOMRIGHT (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_BOTTOMLEFT (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_LEFTTOP (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_RIGHTTOP (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_RIGHTBOTTOM (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
imagick::ORIENTATION_LEFTBOTTOM (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.0 or higher.
DISTORTION constants

imagick::DISTORTION_UNDEFINED (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_AFFINE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_AFFINEPROJECTION (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_ARC (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_BILINEAR (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_PERSPECTIVE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_PERSPECTIVEPROJECTION (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_SCALEROTATETRANSLATE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.6 or higher.
imagick::DISTORTION_POLYNOMIAL (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DISTORTION_POLAR (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DISTORTION_DEPOLAR (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DISTORTION_BARREL (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DISTORTION_BARRELINVERSE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DISTORTION_SHEPARDS (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DISTORTION_SENTINEL (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
ALPHACHANNEL constants

imagick::ALPHACHANNEL_ACTIVATE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.8 or higher.
imagick::ALPHACHANNEL_DEACTIVATE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.8 or higher.
imagick::ALPHACHANNEL_RESET (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.8 or higher.
imagick::ALPHACHANNEL_SET (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.8 or higher.
imagick::ALPHACHANNEL_UNDEFINED (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::ALPHACHANNEL_COPY (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::ALPHACHANNEL_EXTRACT (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::ALPHACHANNEL_OPAQUE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::ALPHACHANNEL_SHAPE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::ALPHACHANNEL_TRANSPARENT (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
SPARSECOLORMETHOD constants

imagick::SPARSECOLORMETHOD_UNDEFINED (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::SPARSECOLORMETHOD_BARYCENTRIC (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::SPARSECOLORMETHOD_BILINEAR (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::SPARSECOLORMETHOD_POLYNOMIAL (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::SPARSECOLORMETHOD_SPEPARDS (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::SPARSECOLORMETHOD_VORONOI (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
FUNCTION constants

imagick::FUNCTION_UNDEFINED (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.9 or higher.
imagick::FUNCTION_POLYNOMIAL (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.9 or higher.
imagick::FUNCTION_SINUSOID (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.9 or higher.
INTERPOLATE constants

imagick::INTERPOLATE_UNDEFINED (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_AVERAGE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_BICUBIC (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_BILINEAR (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_FILTER (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_INTEGER (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_MESH (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_NEARESTNEIGHBOR (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.2 or higher.
imagick::INTERPOLATE_SPLINE (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.3.4 or higher.
DITHERMETHOD constants

imagick::DITHERMETHOD_UNDEFINED (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DITHERMETHOD_NO (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DITHERMETHOD_RIEMERSMA (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.
imagick::DITHERMETHOD_FLOYDSTEINBERG (integer)
This constant is available if Imagick has been compiled against ImageMagick version 6.4.6 or higher.


  • « Predefined Constants
  • Basic usage »
  • PHP Manual
  • ImageMagick
  • Examples

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:

Output of example : Creating a reflection of an image

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:

Output of example : Filling text with gradient

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:

Output of example : Creating PHP logo with Imagick


The Imagick class

(PECL imagick 2.0.0)

Class synopsis

Imagick implements Iterator {
adaptiveBlurImage ( float $radius , float $sigma [, int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
adaptiveResizeImage ( int $columns , int $rows [, bool $bestfit = FALSE [, bool $legacy = FALSE ]] ) : bool
adaptiveSharpenImage ( float $radius , float $sigma [, int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
adaptiveThresholdImage ( int $width , int $height , int $offset ) : bool
addImage ( Imagick $source ) : bool
addNoiseImage ( int $noise_type [, int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
affineTransformImage ( ImagickDraw $matrix ) : bool
animateImages ( string $x_server ) : bool
annotateImage ( ImagickDraw $draw_settings , float $x , float $y , float $angle , string $text ) : bool
appendImages ( bool $stack ) : Imagick
public autoLevelImage ([ int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
averageImages ( void ) : Imagick
blackThresholdImage ( mixed $threshold ) : bool
public blueShiftImage ([ float $factor = 1.5 ] ) : bool
blurImage ( float $radius , float $sigma [, int $channel ] ) : bool
borderImage ( mixed $bordercolor , int $width , int $height ) : bool
public brightnessContrastImage ( float $brightness , float $contrast [, int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
charcoalImage ( float $radius , float $sigma ) : bool
chopImage ( int $width , int $height , int $x , int $y ) : bool
public clampImage ([ int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
clear ( void ) : bool
clipImage ( void ) : bool
public clipImagePath ( string $pathname , string $inside ) : void
clipPathImage ( string $pathname , bool $inside ) : bool
clone ( void ) : Imagick
clutImage ( Imagick $lookup_table [, int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
coalesceImages ( void ) : Imagick
colorFloodfillImage ( mixed $fill , float $fuzz , mixed $bordercolor , int $x , int $y ) : bool
colorizeImage ( mixed $colorize , mixed $opacity [, bool $legacy = FALSE ] ) : bool
public colorMatrixImage ( array $color_matrix = Imagick::CHANNEL_DEFAULT ) : bool
combineImages ( int $channelType ) : Imagick
commentImage ( string $comment ) : bool
compareImageChannels ( Imagick $image , int $channelType , int $metricType ) : array
compareImageLayers ( int $method ) : Imagick
compareImages ( Imagick $compare , int $metric ) : array
compositeImage ( Imagick $composite_object , int $composite , int $x , int $y [, int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
__construct ([ mixed $files ] )
contrastImage ( bool $sharpen ) : bool
contrastStretchImage ( float $black_point , float $white_point [, int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
convolveImage ( array $kernel [, int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
public count ([ int $mode = 0 ] ) : int
cropImage ( int $width , int $height , int $x , int $y ) : bool
cropThumbnailImage ( int $width , int $height [, bool $legacy = FALSE ] ) : bool
current ( void ) : Imagick
cycleColormapImage ( int $displace ) : bool
decipherImage ( string $passphrase ) : bool
deconstructImages ( void ) : Imagick
deleteImageArtifact ( string $artifact ) : bool
public deleteImageProperty ( string $name ) : bool
public deskewImage ( float $threshold ) : bool
despeckleImage ( void ) : bool
destroy ( void ) : bool
displayImage ( string $servername ) : bool
displayImages ( string $servername ) : bool
distortImage ( int $method , array $arguments , bool $bestfit ) : bool
drawImage ( ImagickDraw $draw ) : bool
edgeImage ( float $radius ) : bool
embossImage ( float $radius , float $sigma ) : bool
encipherImage ( string $passphrase ) : bool
enhanceImage ( void ) : bool
equalizeImage ( void ) : bool
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
extentImage ( int $width , int $height , int $x , int $y ) : bool
public filter ( ImagickKernel $ImagickKernel [, int $channel = Imagick::CHANNEL_UNDEFINED ] ) : bool
flattenImages ( void ) : Imagick
flipImage ( void ) : bool
floodFillPaintImage ( mixed $fill , float $fuzz , mixed $target , int $x , int $y , bool $invert [, int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
flopImage ( void ) : bool
public forwardFourierTransformimage ( bool $magnitude ) : bool
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
fxImage ( string $expression [, int $channel = Imagick::CHANNEL_DEFAULT ] ) : Imagick
gammaImage ( float $gamma [, int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
gaussianBlurImage ( float $radius , float $sigma [, int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
getColorspace ( void ) : int
getCompression ( void ) : int
getCompressionQuality ( void ) : int
getCopyright ( void ) : string
getFilename ( void ) : string
getFont ( void ) : string
getFormat ( void ) : string
getGravity ( void ) : int
getHomeURL ( void ) : string
getImage ( void ) : Imagick
getImageAlphaChannel ( void ) : int
getImageArtifact ( string $artifact ) : string
public getImageAttribute ( string $key ) : string
getImageBackgroundColor ( void ) : ImagickPixel
getImageBlob ( void ) : string
getImageBluePrimary ( void ) : array
getImageBorderColor ( void ) : ImagickPixel
getImageChannelDepth ( int $channel ) : int
getImageChannelDistortion ( Imagick $reference , int $channel , int $metric ) : float
getImageChannelDistortions ( Imagick $reference , int $metric [, int $channel = Imagick::CHANNEL_DEFAULT ] ) : float
getImageChannelExtrema ( int $channel ) : array
public getImageChannelKurtosis ([ int $channel = Imagick::CHANNEL_DEFAULT ] ) : array
getImageChannelMean ( int $channel ) : array
getImageChannelRange ( int $channel ) : array
getImageChannelStatistics ( void ) : array
getImageClipMask ( void ) : Imagick
getImageColormapColor ( int $index ) : ImagickPixel
getImageColors ( void ) : int
getImageColorspace ( void ) : int
getImageCompose ( void ) : int
getImageCompression ( void ) : int
getImageCompressionQuality ( void ) : int
getImageDelay ( void ) : int
getImageDepth ( void ) : int
getImageDispose ( void ) : int
getImageDistortion ( MagickWand $reference , int $metric ) : float
getImageExtrema ( void ) : array
getImageFilename ( void ) : string
getImageFormat ( void ) : string
getImageGamma ( void ) : float
getImageGeometry ( void ) : array
getImageGravity ( void ) : int
getImageGreenPrimary ( void ) : array
getImageHeight ( void ) : int
getImageHistogram ( void ) : array
getImageIndex ( void ) : int
getImageInterlaceScheme ( void ) : int
getImageInterpolateMethod ( void ) : int
getImageIterations ( void ) : int
getImageLength ( void ) : int
getImageMagickLicense ( void ) : string
getImageMatte ( void ) : bool
getImageMatteColor ( void ) : ImagickPixel
public getImageMimeType ( void ) : string
getImageOrientation ( void ) : int
getImagePage ( void ) : array
getImagePixelColor ( int $x , int $y ) : ImagickPixel
getImageProfile ( string $name ) : string
getImageProfiles ([ string $pattern = "*" [, bool $include_values = TRUE ]] ) : array
getImageProperties ([ string $pattern = "*" [, bool $include_values = TRUE ]] ) : array
getImageProperty ( string $name ) : string
getImageRedPrimary ( void ) : array
getImageRegion ( int $width , int $height , int $x , int $y ) : Imagick
getImageRenderingIntent ( void ) : int
getImageResolution ( void ) : array
getImagesBlob ( void ) : string
getImageScene ( void ) : int
getImageSignature ( void ) : string
getImageSize ( void ) : int
getImageTicksPerSecond ( void ) : int
getImageTotalInkDensity ( void ) : float
getImageType ( void ) : int
getImageUnits ( void ) : int
getImageVirtualPixelMethod ( void ) : int
getImageWhitePoint ( void ) : array
getImageWidth ( void ) : int
getInterlaceScheme ( void ) : int
getIteratorIndex ( void ) : int
getNumberImages ( void ) : int
getOption ( string $key ) : string
getPackageName ( void ) : string
getPage ( void ) : array
getPixelIterator ( void ) : ImagickPixelIterator
getPixelRegionIterator ( int $x , int $y , int $columns , int $rows ) : ImagickPixelIterator
getPointSize ( void ) : float
public static getQuantum ( void ) : int
getQuantumDepth ( void ) : array
getQuantumRange ( void ) : array
public static getRegistry ( string $key ) : string
getReleaseDate ( void ) : string
getResource ( int $type ) : int
getResourceLimit ( int $type ) : int
getSamplingFactors ( void ) : array
getSize ( void ) : array
getSizeOffset ( void ) : int
getVersion ( void ) : array
public haldClutImage ( Imagick $clut [, int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
hasNextImage ( void ) : bool
hasPreviousImage ( void ) : bool
public identifyFormat ( string $embedText ) : string
identifyImage ([ bool $appendRawOutput = FALSE ] ) : array
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
labelImage ( string $label ) : bool
levelImage ( float $blackPoint , float $gamma , float $whitePoint [, int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
linearStretchImage ( float $blackPoint , float $whitePoint ) : bool
liquidRescaleImage ( int $width , int $height , float $delta_x , float $rigidity ) : bool
public static listRegistry ( void ) : array
magnifyImage ( void ) : bool
mapImage ( Imagick $map , bool $dither ) : bool
matteFloodfillImage ( float $alpha , float $fuzz , mixed $bordercolor , int $x , int $y ) : bool
medianFilterImage ( float $radius ) : bool
mergeImageLayers ( int $layer_method ) : Imagick
minifyImage ( void ) : bool
modulateImage ( float $brightness , float $saturation , float $hue ) : bool
montageImage ( ImagickDraw $draw , string $tile_geometry , string $thumbnail_geometry , int $mode , string $frame ) : Imagick
morphImages ( int $number_frames ) : Imagick
public morphology ( int $morphologyMethod , int $iterations , ImagickKernel $ImagickKernel [, int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
mosaicImages ( void ) : Imagick
motionBlurImage ( float $radius , float $sigma , float $angle [, int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
negateImage ( bool $gray [, int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
newImage ( int $cols , int $rows , mixed $background [, string $format ] ) : bool
newPseudoImage ( int $columns , int $rows , string $pseudoString ) : bool
nextImage ( void ) : bool
normalizeImage ([ int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
oilPaintImage ( float $radius ) : bool
opaquePaintImage ( mixed $target , mixed $fill , float $fuzz , bool $invert [, int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
optimizeImageLayers ( void ) : bool
orderedPosterizeImage ( string $threshold_map [, int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
paintFloodfillImage ( mixed $fill , float $fuzz , mixed $bordercolor , int $x , int $y [, int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
paintOpaqueImage ( mixed $target , mixed $fill , float $fuzz [, int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
paintTransparentImage ( mixed $target , float $alpha , float $fuzz ) : bool
pingImage ( string $filename ) : bool
pingImageBlob ( string $image ) : bool
pingImageFile ( resource $filehandle [, string $fileName ] ) : bool
polaroidImage ( ImagickDraw $properties , float $angle ) : bool
posterizeImage ( int $levels , bool $dither ) : bool
previewImages ( int $preview ) : bool
previousImage ( void ) : bool
profileImage ( string $name , string $profile ) : bool
quantizeImage ( int $numberColors , int $colorspace , int $treedepth , bool $dither , bool $measureError ) : bool
quantizeImages ( int $numberColors , int $colorspace , int $treedepth , bool $dither , bool $measureError ) : bool
queryFontMetrics ( ImagickDraw $properties , string $text [, bool $multiline ] ) : array
queryFonts ([ string $pattern = "*" ] ) : array
queryFormats ([ string $pattern = "*" ] ) : array
radialBlurImage ( float $angle [, int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
raiseImage ( int $width , int $height , int $x , int $y , bool $raise ) : bool
randomThresholdImage ( float $low , float $high [, int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
readImage ( string $filename ) : bool
readImageBlob ( string $image [, string $filename ] ) : bool
readImageFile ( resource $filehandle [, string $fileName = NULL ] ) : bool
public readImages ( array $filenames ) : bool
recolorImage ( array $matrix ) : bool
reduceNoiseImage ( float $radius ) : bool
public remapImage ( Imagick $replacement , int $DITHER ) : bool
removeImage ( void ) : bool
removeImageProfile ( string $name ) : string
render ( void ) : bool
resampleImage ( float $x_resolution , float $y_resolution , int $filter , float $blur ) : bool
resetImagePage ( string $page ) : bool
resizeImage ( int $columns , int $rows , int $filter , float $blur [, bool $bestfit = FALSE [, bool $legacy = FALSE ]] ) : bool
rollImage ( int $x , int $y ) : bool
rotateImage ( mixed $background , float $degrees ) : bool
public rotationalBlurImage ( float $angle [, int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
roundCorners ( float $x_rounding , float $y_rounding [, float $stroke_width = 10 [, float $displace = 5 [, float $size_correction = -6 ]]] ) : bool
sampleImage ( int $columns , int $rows ) : bool
scaleImage ( int $cols , 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
separateImageChannel ( int $channel ) : bool
sepiaToneImage ( float $threshold ) : bool
setBackgroundColor ( mixed $background ) : bool
setColorspace ( int $COLORSPACE ) : bool
setCompression ( int $compression ) : bool
setCompressionQuality ( int $quality ) : bool
setFilename ( string $filename ) : bool
setFirstIterator ( void ) : bool
setFont ( string $font ) : bool
setFormat ( string $format ) : bool
setGravity ( int $gravity ) : bool
setImage ( Imagick $replace ) : bool
setImageAlphaChannel ( int $mode ) : bool
setImageArtifact ( string $artifact , string $value ) : bool
public setImageAttribute ( string $key , string $value ) : bool
setImageBackgroundColor ( mixed $background ) : bool
setImageBias ( float $bias ) : bool
public setImageBiasQuantum ( string $bias ) : void
setImageBluePrimary ( float $x , float $y ) : bool
setImageBorderColor ( mixed $border ) : bool
setImageChannelDepth ( int $channel , int $depth ) : bool
setImageClipMask ( Imagick $clip_mask ) : bool
setImageColormapColor ( int $index , ImagickPixel $color ) : bool
setImageColorspace ( int $colorspace ) : bool
setImageCompose ( int $compose ) : bool
setImageCompression ( int $compression ) : bool
setImageCompressionQuality ( int $quality ) : bool
setImageDelay ( int $delay ) : bool
setImageDepth ( int $depth ) : bool
setImageDispose ( int $dispose ) : bool
setImageExtent ( int $columns , int $rows ) : bool
setImageFilename ( string $filename ) : bool
setImageFormat ( string $format ) : bool
setImageGamma ( float $gamma ) : bool
setImageGravity ( int $gravity ) : bool
setImageGreenPrimary ( float $x , float $y ) : bool
setImageIndex ( int $index ) : bool
setImageInterlaceScheme ( int $interlace_scheme ) : bool
setImageInterpolateMethod ( int $method ) : bool
setImageIterations ( int $iterations ) : bool
setImageMatte ( bool $matte ) : bool
setImageMatteColor ( mixed $matte ) : bool
setImageOpacity ( float $opacity ) : bool
setImageOrientation ( int $orientation ) : bool
setImagePage ( int $width , int $height , int $x , int $y ) : bool
setImageProfile ( string $name , string $profile ) : bool
setImageProperty ( string $name , string $value ) : bool
setImageRedPrimary ( float $x , float $y ) : bool
setImageRenderingIntent ( int $rendering_intent ) : bool
setImageResolution ( float $x_resolution , float $y_resolution ) : bool
setImageScene ( int $scene ) : bool
setImageTicksPerSecond ( int $ticks_per_second ) : bool
setImageType ( int $image_type ) : bool
setImageUnits ( int $units ) : bool
setImageVirtualPixelMethod ( int $method ) : bool
setImageWhitePoint ( float $x , float $y ) : bool
setInterlaceScheme ( int $interlace_scheme ) : bool
setIteratorIndex ( int $index ) : bool
setLastIterator ( void ) : bool
setOption ( string $key , string $value ) : bool
setPage ( int $width , int $height , int $x , int $y ) : bool
setPointSize ( float $point_size ) : bool
public setProgressMonitor ( callable $callback ) : bool
public static setRegistry ( string $key , string $value ) : bool
setResolution ( float $x_resolution , float $y_resolution ) : bool
setResourceLimit ( int $type , int $limit ) : bool
setSamplingFactors ( array $factors ) : bool
setSize ( int $columns , int $rows ) : bool
setSizeOffset ( int $columns , int $rows , int $offset ) : bool
setType ( int $image_type ) : bool
shadeImage ( bool $gray , float $azimuth , float $elevation ) : bool
shadowImage ( float $opacity , float $sigma , int $x , int $y ) : bool
sharpenImage ( float $radius , float $sigma [, int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
shaveImage ( int $columns , int $rows ) : bool
shearImage ( mixed $background , float $x_shear , float $y_shear ) : bool
sigmoidalContrastImage ( bool $sharpen , float $alpha , float $beta [, int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
sketchImage ( float $radius , float $sigma , float $angle ) : bool
public smushImages ( bool $stack , int $offset ) : Imagick
solarizeImage ( int $threshold ) : bool
public sparseColorImage ( int $SPARSE_METHOD , array $arguments [, int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
spliceImage ( int $width , int $height , int $x , int $y ) : bool
spreadImage ( float $radius ) : bool
public statisticImage ( int $type , int $width , int $height [, int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
steganoImage ( Imagick $watermark_wand , int $offset ) : Imagick
stereoImage ( Imagick $offset_wand ) : bool
stripImage ( void ) : bool
public subImageMatch ( Imagick $Imagick [, array &$offset [, float &$similarity ]] ) : Imagick
swirlImage ( float $degrees ) : bool
textureImage ( Imagick $texture_wand ) : Imagick
thresholdImage ( float $threshold [, int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
thumbnailImage ( int $columns , int $rows [, bool $bestfit = FALSE [, bool $fill = FALSE [, bool $legacy = FALSE ]]] ) : bool
tintImage ( mixed $tint , mixed $opacity [, bool $legacy = FALSE ] ) : bool
__toString ( void ) : string
transformImage ( string $crop , string $geometry ) : Imagick
transformImageColorspace ( int $colorspace ) : bool
transparentPaintImage ( mixed $target , float $alpha , float $fuzz , bool $invert ) : bool
transposeImage ( void ) : bool
transverseImage ( void ) : bool
trimImage ( float $fuzz ) : bool
uniqueImageColors ( void ) : bool
unsharpMaskImage ( float $radius , float $sigma , float $amount , float $threshold [, int $channel = Imagick::CHANNEL_DEFAULT ] ) : bool
valid ( void ) : bool
vignetteImage ( float $blackPoint , float $whitePoint , int $x , int $y ) : bool
waveImage ( float $amplitude , float $length ) : bool
whiteThresholdImage ( mixed $threshold ) : bool
writeImage ([ string $filename = NULL ] ) : bool
writeImageFile ( resource $filehandle [, string $format ] ) : bool
writeImages ( string $filename , bool $adjoin ) : bool
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() |  |  |  |

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 — Description
  • Imagick::averageImages — Average a set of images
  • Imagick::blackThresholdImage — Forces all pixels below the threshold into black
  • Imagick::blueShiftImage — Description
  • Imagick::blurImage — Adds blur filter to image
  • Imagick::borderImage — Surrounds the image with a border
  • Imagick::brightnessContrastImage — Description
  • Imagick::charcoalImage — Simulates a charcoal drawing
  • Imagick::chopImage — Removes a region of an image and trims
  • Imagick::clampImage — Description
  • Imagick::clear — Clears all resources associated to Imagick object
  • Imagick::clipImage — Clips along the first path from the 8BIM profile
  • Imagick::clipImagePath — Description
  • 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 — Description
  • 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 — Description
  • 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 — Description
  • 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 vertical mirror image
  • Imagick::forwardFourierTransformImage — Description
  • 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 — Gets the image alpha channel
  • Imagick::getImageArtifact — Get image artifact
  • Imagick::getImageAttribute — Description
  • 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::getImageMagickLicense — Returns a string containing the ImageMagick license
  • Imagick::getImageMatte — Return if the image has a matte channel
  • Imagick::getImageMatteColor — Returns the image matte color
  • Imagick::getImageMimeType — Description
  • 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 — Description
  • Imagick::getQuantumDepth — Gets the quantum depth
  • Imagick::getQuantumRange — Returns the Imagick quantum range
  • Imagick::getRegistry — Description
  • 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 — Description
  • Imagick::identifyImage — Identifies an image and fetches attributes
  • Imagick::implodeImage — Creates a new image as a copy
  • Imagick::importImagePixels — Imports image pixels
  • Imagick::inverseFourierTransformImage — Description
  • 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 — Description
  • 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 — Description
  • 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 — Description
  • 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 — Description
  • 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 — Description
  • 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 — Description
  • Imagick::setImageBackgroundColor — Sets the image background color
  • Imagick::setImageBias — Sets the image bias for any method that convolves an image
  • Imagick::setImageBiasQuantum — Description
  • 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 — Description
  • Imagick::setRegistry — Description
  • 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 — Description
  • 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 — Description
  • 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 — Description
  • 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


Adds adaptive blur filter to image

  • « Imagick
  • Imagick::adaptiveResizeImage »
  • PHP Manual
  • Imagick
  • Adds adaptive blur filter to image

Imagick::adaptiveBlurImage

(PECL imagick 2.0.0)

Imagick::adaptiveBlurImage — Adds adaptive blur filter to image

Description

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:

Output of example : Using Imagick::adaptiveBlurImage()

See Also

  • Imagick::blurImage() - Adds blur filter to image
  • Imagick::motionBlurImage() - Simulates motion blur
  • Imagick::radialBlurImage() - Radial blurs an image


Adaptively resize image with data dependent triangulation

  • « Imagick::adaptiveBlurImage
  • Imagick::adaptiveSharpenImage »
  • PHP Manual
  • Imagick
  • Adaptively resize image with data dependent triangulation

Imagick::adaptiveResizeImage

(PECL imagick 2.0.0)

Imagick::adaptiveResizeImage — Adaptively resize image with data dependent triangulation

Description

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
2.1.0 | Added optional fit parameter.
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


Adaptively sharpen the image

  • « Imagick::adaptiveResizeImage
  • Imagick::adaptiveThresholdImage »
  • PHP Manual
  • Imagick
  • Adaptively sharpen the image

Imagick::adaptiveSharpenImage

(PECL imagick 2.0.0)

Imagick::adaptiveSharpenImage — Adaptively sharpen the image

Description

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


Selects a threshold for each pixel based on a range of intensity

  • « Imagick::adaptiveSharpenImage
  • Imagick::addImage »
  • PHP Manual
  • Imagick
  • Selects a threshold for each pixel based on a range of intensity

Imagick::adaptiveThresholdImage

(PECL imagick 2.0.0)

Imagick::adaptiveThresholdImage — Selects a threshold for each pixel based on a range of intensity

Description

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();
}

?>


Adds new image to Imagick object image list

  • « Imagick::adaptiveThresholdImage
  • Imagick::addNoiseImage »
  • PHP Manual
  • Imagick
  • Adds new image to Imagick object image list

Imagick::addImage

(PECL imagick 2.0.0)

Imagick::addImage — Adds new image to Imagick object image list

Description

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.


Adds random noise to the image

  • « Imagick::addImage
  • Imagick::affineTransformImage »
  • PHP Manual
  • Imagick
  • Adds random noise to the image

Imagick::addNoiseImage

(PECL imagick 2.0.0)

Imagick::addNoiseImage — Adds random noise to the image

Description

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();
}

?>


Transforms an image

  • « Imagick::addNoiseImage
  • Imagick::animateImages »
  • PHP Manual
  • Imagick
  • Transforms an image

Imagick::affineTransformImage

(PECL imagick 2.0.0)

Imagick::affineTransformImage — Transforms an image

Description

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 = 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();
}

?>


Animates an image or images

  • « Imagick::affineTransformImage
  • Imagick::annotateImage »
  • PHP Manual
  • Imagick
  • Animates an image or images

Imagick::animateImages

(No version information available, might only be in Git)

Imagick::animateImages — Animates an image or images

Description

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


Annotates an image with text

  • « Imagick::animateImages
  • Imagick::appendImages »
  • PHP Manual
  • Imagick
  • Annotates an image with text

Imagick::annotateImage

(PECL imagick 2.0.0)

Imagick::annotateImage — Annotates an image with text

Description

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


Append a set of images

  • « Imagick::annotateImage
  • Imagick::autoLevelImage »
  • PHP Manual
  • Imagick
  • Append a set of images

Imagick::appendImages

(PECL imagick 2.0.0)

Imagick::appendImages — Append a set of images

Description

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:

Output of example : Imagick::appendImages()


Description

  • « Imagick::appendImages
  • Imagick::averageImages »
  • PHP Manual
  • Imagick
  • Description

Imagick::autoLevelImage

(No version information available, might only be in Git)

Imagick::autoLevelImage — Description

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();
}

?>


Average a set of images

  • « Imagick::autoLevelImage
  • Imagick::blackThresholdImage »
  • PHP Manual
  • Imagick
  • Average a set of images

Imagick::averageImages

(PECL imagick 2.0.0)

Imagick::averageImages — Average a set of images

Description

Imagick::averageImages ( void ) : Imagick

Average a set of images.

Return Values

Returns a new Imagick object on success.

Errors/Exceptions

Throws ImagickException on error.


Forces all pixels below the threshold into black

  • « Imagick::averageImages
  • Imagick::blueShiftImage »
  • PHP Manual
  • Imagick
  • Forces all pixels below the threshold into black

Imagick::blackThresholdImage

(PECL imagick 2.0.0)

Imagick::blackThresholdImage — Forces all pixels below the threshold into black

Description

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
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();
}

?>


Description

  • « Imagick::blackThresholdImage
  • Imagick::blurImage »
  • PHP Manual
  • Imagick
  • Description

Imagick::blueShiftImage

(No version information available, might only be in Git)

Imagick::blueShiftImage — Description

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();
}

?>


Adds blur filter to image

  • « Imagick::blueShiftImage
  • Imagick::borderImage »
  • PHP Manual
  • Imagick
  • Adds blur filter to image

Imagick::blurImage

(PECL imagick 2.0.0)

Imagick::blurImage — Adds blur filter to image

Description

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


Surrounds the image with a border

  • « Imagick::blurImage
  • Imagick::brightnessContrastImage »
  • PHP Manual
  • Imagick
  • Surrounds the image with a border

Imagick::borderImage

(PECL imagick 2.0.0)

Imagick::borderImage — Surrounds the image with a border

Description

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
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();
}

?>


Description

  • « Imagick::borderImage
  • Imagick::charcoalImage »
  • PHP Manual
  • Imagick
  • Description

Imagick::brightnessContrastImage

(No version information available, might only be in Git)

Imagick::brightnessContrastImage — Description

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();
}

?>


Simulates a charcoal drawing

  • « Imagick::brightnessContrastImage
  • Imagick::chopImage »
  • PHP Manual
  • Imagick
  • Simulates a charcoal drawing

Imagick::charcoalImage

(PECL imagick 2.0.0)

Imagick::charcoalImage — Simulates a charcoal drawing

Description

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();
}

?>


Removes a region of an image and trims

  • « Imagick::charcoalImage
  • Imagick::clampImage »
  • PHP Manual
  • Imagick
  • Removes a region of an image and trims

Imagick::chopImage

(PECL imagick 2.0.0)

Imagick::chopImage — Removes a region of an image and trims

Description

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


Description

  • « Imagick::chopImage
  • Imagick::clear »
  • PHP Manual
  • Imagick
  • Description

Imagick::clampImage

(No version information available, might only be in Git)

Imagick::clampImage — Description

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.


Clears all resources associated to Imagick object

  • « Imagick::clampImage
  • Imagick::clipImage »
  • PHP Manual
  • Imagick
  • Clears all resources associated to Imagick object

Imagick::clear

(PECL imagick 2.0.0)

Imagick::clear — Clears all resources associated to Imagick object

Description

Imagick::clear ( void ) : bool

Clears all resources associated to Imagick object

Return Values

Returns TRUE on success.


Clips along the first path from the 8BIM profile

  • « Imagick::clear
  • Imagick::clipImagePath »
  • PHP Manual
  • Imagick
  • Clips along the first path from the 8BIM profile

Imagick::clipImage

(PECL imagick 2.0.0)

Imagick::clipImage — Clips along the first path from the 8BIM profile

Description

Imagick::clipImage ( void ) : bool

Clips along the first path from the 8BIM profile, if present.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.


Description

  • « Imagick::clipImage
  • Imagick::clipPathImage »
  • PHP Manual
  • Imagick
  • Description

Imagick::clipImagePath

(No version information available, might only be in Git)

Imagick::clipImagePath — Description

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


Clips along the named paths from the 8BIM profile

  • « Imagick::clipImagePath
  • Imagick::clone »
  • PHP Manual
  • Imagick
  • Clips along the named paths from the 8BIM profile

Imagick::clipPathImage

(PECL imagick 2.0.0)

Imagick::clipPathImage — Clips along the named paths from the 8BIM profile

Description

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.


Makes an exact copy of the Imagick object

  • « Imagick::clipPathImage
  • Imagick::clutImage »
  • PHP Manual
  • Imagick
  • Makes an exact copy of the Imagick object

Imagick::clone

(PECL imagick 2.0.0)

Imagick::clone — Makes an exact copy of the Imagick object

Description

Imagick::clone ( void ) : 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.

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;
?>

Return Values

A copy of the Imagick object is returned.

Changelog

Version | Description
3.1.0 | The method was deprecated in favour of the clone keyword.


Replaces colors in the image

  • « Imagick::clone
  • Imagick::coalesceImages »
  • PHP Manual
  • Imagick
  • Replaces colors in the image

Imagick::clutImage

(PECL imagick 2.0.0)

Imagick::clutImage — Replaces colors in the image

Description

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


Composites a set of images

  • « Imagick::clutImage
  • Imagick::colorFloodfillImage »
  • PHP Manual
  • Imagick
  • Composites a set of images

Imagick::coalesceImages

(PECL imagick 2.0.0)

Imagick::coalesceImages — Composites a set of images

Description

Imagick::coalesceImages ( void ) : 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.

Return Values

Returns a new Imagick object on success.

Errors/Exceptions

Throws ImagickException on error.


Changes the color value of any pixel that matches target

  • « Imagick::coalesceImages
  • Imagick::colorizeImage »
  • PHP Manual
  • Imagick
  • Changes the color value of any pixel that matches target

Imagick::colorFloodfillImage

(PECL imagick 2.0.0)

Imagick::colorFloodfillImage — Changes the color value of any pixel that matches target

Description

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
2.1.0 | Now allows a string representing the color as first and third parameter. Previous versions allow only an ImagickPixel object.


Blends the fill color with the image

  • « Imagick::colorFloodfillImage
  • Imagick::colorMatrixImage »
  • PHP Manual
  • Imagick
  • Blends the fill color with the image

Imagick::colorizeImage

(PECL imagick 2.0.0)

Imagick::colorizeImage — Blends the fill color with the image

Description

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
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();
}

?>


Description

  • « Imagick::colorizeImage
  • Imagick::combineImages »
  • PHP Manual
  • Imagick
  • Description

Imagick::colorMatrixImage

(No version information available, might only be in Git)

Imagick::colorMatrixImage — Description

Description

public Imagick::colorMatrixImage ( array $color_matrix = Imagick::CHANNEL_DEFAULT ) : 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();
}

?>


Combines one or more images into a single image

  • « Imagick::colorMatrixImage
  • Imagick::commentImage »
  • PHP Manual
  • Imagick
  • Combines one or more images into a single image

Imagick::combineImages

(PECL imagick 2.0.0)

Imagick::combineImages — Combines one or more images into a single image

Description

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.


Adds a comment to your image

  • « Imagick::combineImages
  • Imagick::compareImageChannels »
  • PHP Manual
  • Imagick
  • Adds a comment to your image

Imagick::commentImage

(PECL imagick 2.0.0)

Imagick::commentImage — Adds a comment to your image

Description

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");

?>


Returns the difference in one or more images

  • « Imagick::commentImage
  • Imagick::compareImageLayers »
  • PHP Manual
  • Imagick
  • Returns the difference in one or more images

Imagick::compareImageChannels

(PECL imagick 2.0.0)

Imagick::compareImageChannels — Returns the difference in one or more images

Description

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.


Returns the maximum bounding region between images

  • « Imagick::compareImageChannels
  • Imagick::compareImages »
  • PHP Manual
  • Imagick
  • Returns the maximum bounding region between images

Imagick::compareImageLayers

(PECL imagick 2.0.0)

Imagick::compareImageLayers — Returns the maximum bounding region between images

Description

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


Compares an image to a reconstructed image

  • « Imagick::compareImageLayers
  • Imagick::compositeImage »
  • PHP Manual
  • Imagick
  • Compares an image to a reconstructed image

Imagick::compareImages

(PECL imagick 2.0.0)

Imagick::compareImages — Compares an image to a reconstructed image

Description

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];

?>


Composite one image onto another

  • « Imagick::compareImages
  • Imagick::__construct »
  • PHP Manual
  • Imagick
  • Composite one image onto another

Imagick::compositeImage

(PECL imagick 2.0.0)

Imagick::compositeImage — Composite one image onto another

Description

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


The Imagick constructor

  • « Imagick::compositeImage
  • Imagick::contrastImage »
  • PHP Manual
  • Imagick
  • The Imagick constructor

Imagick::__construct

(PECL imagick 2.0.0)

Imagick::__construct — The Imagick constructor

Description

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.

Return Values

Returns a new Imagick object on success.

Errors/Exceptions

Throws ImagickException on error.


Change the contrast of the image

  • « Imagick::__construct
  • Imagick::contrastStretchImage »
  • PHP Manual
  • Imagick
  • Change the contrast of the image

Imagick::contrastImage

(PECL imagick 2.0.0)

Imagick::contrastImage — Change the contrast of the image

Description

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();
}

?>


Enhances the contrast of a color image

  • « Imagick::contrastImage
  • Imagick::convolveImage »
  • PHP Manual
  • Imagick
  • Enhances the contrast of a color image

Imagick::contrastStretchImage

(PECL imagick 2.0.0)

Imagick::contrastStretchImage — Enhances the contrast of a color image

Description

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.


Applies a custom convolution kernel to the image

  • « Imagick::contrastStretchImage
  • Imagick::count »
  • PHP Manual
  • Imagick
  • Applies a custom convolution kernel to the image

Imagick::convolveImage

(PECL imagick 2.0.0)

Imagick::convolveImage — Applies a custom convolution kernel to the image

Description

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();
}

?>


Get the number of images

  • « Imagick::convolveImage
  • Imagick::cropImage »
  • PHP Manual
  • Imagick
  • Get the number of images

Imagick::count

(No version information available, might only be in Git)

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.


Extracts a region of the image

  • « Imagick::count
  • Imagick::cropThumbnailImage »
  • PHP Manual
  • Imagick
  • Extracts a region of the image

Imagick::cropImage

(PECL imagick 2.0.0)

Imagick::cropImage — Extracts a region of the image

Description

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();
}

?>


Creates a crop thumbnail

  • « Imagick::cropImage
  • Imagick::current »
  • PHP Manual
  • Imagick
  • Creates a crop thumbnail

Imagick::cropThumbnailImage

(PECL imagick 2.0.0)

Imagick::cropThumbnailImage — Creates a crop thumbnail

Description

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.


Returns a reference to the current Imagick object

  • « Imagick::cropThumbnailImage
  • Imagick::cycleColormapImage »
  • PHP Manual
  • Imagick
  • Returns a reference to the current Imagick object

Imagick::current

(PECL imagick 2.0.0)

Imagick::current — Returns a reference to the current Imagick object

Description

Imagick::current ( void ) : Imagick

Returns reference to the current imagick object with image pointer at the correct sequence.

Return Values

Returns self on success.

Errors/Exceptions

Throws ImagickException on error.


Displaces an image's colormap

  • « Imagick::current
  • Imagick::decipherImage »
  • PHP Manual
  • Imagick
  • Displaces an image's colormap

Imagick::cycleColormapImage

(PECL imagick 2.0.0)

Imagick::cycleColormapImage — Displaces an image's colormap

Description

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.


Deciphers an image

  • « Imagick::cycleColormapImage
  • Imagick::deconstructImages »
  • PHP Manual
  • Imagick
  • Deciphers an image

Imagick::decipherImage

(No version information available, might only be in Git)

Imagick::decipherImage — Deciphers an image

Description

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


Returns certain pixel differences between images

  • « Imagick::decipherImage
  • Imagick::deleteImageArtifact »
  • PHP Manual
  • Imagick
  • Returns certain pixel differences between images

Imagick::deconstructImages

(PECL imagick 2.0.0)

Imagick::deconstructImages — Returns certain pixel differences between images

Description

Imagick::deconstructImages ( void ) : Imagick

Compares each image with the next in a sequence and returns the maximum bounding region of any pixel differences it discovers.

Return Values

Returns a new Imagick object on success.

Errors/Exceptions

Throws ImagickException on error.


Delete image artifact

  • « Imagick::deconstructImages
  • Imagick::deleteImageProperty »
  • PHP Manual
  • Imagick
  • Delete image artifact

Imagick::deleteImageArtifact

(No version information available, might only be in Git)

Imagick::deleteImageArtifact — Delete image artifact

Description

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


Description

  • « Imagick::deleteImageArtifact
  • Imagick::deskewImage »
  • PHP Manual
  • Imagick
  • Description

Imagick::deleteImageProperty

(No version information available, might only be in Git)

Imagick::deleteImageProperty — Description

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.


Removes skew from the image

  • « Imagick::deleteImageProperty
  • Imagick::despeckleImage »
  • PHP Manual
  • Imagick
  • Removes skew from the image

Imagick::deskewImage

(No version information available, might only be in Git)

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();
}

?>


Reduces the speckle noise in an image

  • « Imagick::deskewImage
  • Imagick::destroy »
  • PHP Manual
  • Imagick
  • Reduces the speckle noise in an image

Imagick::despeckleImage

(PECL imagick 2.0.0)

Imagick::despeckleImage — Reduces the speckle noise in an image

Description

Imagick::despeckleImage ( void ) : bool

Reduces the speckle noise in an image while preserving the edges of the original image.

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();
}

?>


Destroys the Imagick object

  • « Imagick::despeckleImage
  • Imagick::displayImage »
  • PHP Manual
  • Imagick
  • Destroys the Imagick object

Imagick::destroy

(PECL imagick 2.0.0)

Imagick::destroy — Destroys the Imagick object

Description

Imagick::destroy ( void ) : bool

Destroys the Imagick object and frees all resources associated with it. This method is deprecated in favour of Imagick::clear.

Return Values

Returns TRUE on success.


Displays an image

  • « Imagick::destroy
  • Imagick::displayImages »
  • PHP Manual
  • Imagick
  • Displays an image

Imagick::displayImage

(PECL imagick 2.0.0)

Imagick::displayImage — Displays an image

Description

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.


Displays an image or image sequence

  • « Imagick::displayImage
  • Imagick::distortImage »
  • PHP Manual
  • Imagick
  • Displays an image or image sequence

Imagick::displayImages

(PECL imagick 2.0.0)

Imagick::displayImages — Displays an image or image sequence

Description

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.


Distorts an image using various distortion methods

  • « Imagick::displayImages
  • Imagick::drawImage »
  • PHP Manual
  • Imagick
  • Distorts an image using various distortion methods

Imagick::distortImage

(PECL imagick 2.0.1)

Imagick::distortImage — Distorts an image using various distortion methods

Description

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:

Output of example : Using Imagick::distortImage()

See Also

  • Imagick::blurImage() - Adds blur filter to image
  • Imagick::motionBlurImage() - Simulates motion blur
  • Imagick::radialBlurImage() - Radial blurs an image


Renders the ImagickDraw object on the current image

  • « Imagick::distortImage
  • Imagick::edgeImage »
  • PHP Manual
  • Imagick
  • Renders the ImagickDraw object on the current image

Imagick::drawImage

(PECL imagick 2.0.0)

Imagick::drawImage — Renders the ImagickDraw object on the current image

Description

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.


Enhance edges within the image

  • « Imagick::drawImage
  • Imagick::embossImage »
  • PHP Manual
  • Imagick
  • Enhance edges within the image

Imagick::edgeImage

(PECL imagick 2.0.0)

Imagick::edgeImage — Enhance edges within the image

Description

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();
}

?>


Returns a grayscale image with a three-dimensional effect

  • « Imagick::edgeImage
  • Imagick::encipherImage »
  • PHP Manual
  • Imagick
  • Returns a grayscale image with a three-dimensional effect

Imagick::embossImage

(PECL imagick 2.0.0)

Imagick::embossImage — Returns a grayscale image with a three-dimensional effect

Description

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();
}

?>


Enciphers an image

  • « Imagick::embossImage
  • Imagick::enhanceImage »
  • PHP Manual
  • Imagick
  • Enciphers an image

Imagick::encipherImage

(No version information available, might only be in Git)

Imagick::encipherImage — Enciphers an image

Description

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


Improves the quality of a noisy image

  • « Imagick::encipherImage
  • Imagick::equalizeImage »
  • PHP Manual
  • Imagick
  • Improves the quality of a noisy image

Imagick::enhanceImage

(PECL imagick 2.0.0)

Imagick::enhanceImage — Improves the quality of a noisy image

Description

Imagick::enhanceImage ( void ) : bool

Applies a digital filter that improves the quality of a noisy image.

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();
}

?>


Equalizes the image histogram

  • « Imagick::enhanceImage
  • Imagick::evaluateImage »
  • PHP Manual
  • Imagick
  • Equalizes the image histogram

Imagick::equalizeImage

(PECL imagick 2.0.0)

Imagick::equalizeImage — Equalizes the image histogram

Description

Imagick::equalizeImage ( void ) : bool

Equalizes the image histogram.

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();
}

?>


Applies an expression to an image

  • « Imagick::equalizeImage
  • Imagick::exportImagePixels »
  • PHP Manual
  • Imagick
  • Applies an expression to an image

Imagick::evaluateImage

(PECL imagick 2.0.0)

Imagick::evaluateImage — Applies an expression to an image

Description

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.

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;
?>

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.


Exports raw image pixels

  • « Imagick::evaluateImage
  • Imagick::extentImage »
  • PHP Manual
  • Imagick
  • Exports raw image pixels

Imagick::exportImagePixels

(No version information available, might only be in Git)

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

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)
}

Return Values

Returns an array containing the pixels values.

Errors/Exceptions

Throws ImagickException on error.


Set image size

  • « Imagick::exportImagePixels
  • Imagick::filter »
  • PHP Manual
  • Imagick
  • Set image size

Imagick::extentImage

(No version information available, might only be in Git)

Imagick::extentImage — Set image size

Description

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


Description

  • « Imagick::extentImage
  • Imagick::flattenImages »
  • PHP Manual
  • Imagick
  • Description

Imagick::filter

(No version information available, might only be in Git)

Imagick::filter — Description

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();
}

?>


Merges a sequence of images

  • « Imagick::filter
  • Imagick::flipImage »
  • PHP Manual
  • Imagick
  • Merges a sequence of images

Imagick::flattenImages

(PECL imagick 2.0.0)

Imagick::flattenImages — Merges a sequence of images

Description

Imagick::flattenImages ( void ) : Imagick

Merges a sequence of images. This is useful for combining Photoshop layers into a single image.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.


Creates a vertical mirror image

  • « Imagick::flattenImages
  • Imagick::floodFillPaintImage »
  • PHP Manual
  • Imagick
  • Creates a vertical mirror image

Imagick::flipImage

(PECL imagick 2.0.0)

Imagick::flipImage — Creates a vertical mirror image

Description

Imagick::flipImage ( void ) : bool

Creates a vertical mirror image by reflecting the pixels around the central x-axis.

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();
}

?>


Changes the color value of any pixel that matches target

  • « Imagick::flipImage
  • Imagick::flopImage »
  • PHP Manual
  • Imagick
  • Changes the color value of any pixel that matches target

Imagick::floodFillPaintImage

(No version information available, might only be in Git)

Imagick::floodFillPaintImage — Changes the color value of any pixel that matches target

Description

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:

Output of example : Imagick::floodfillPaintImage()
Output of example : Imagick::floodfillPaintImage()


Creates a vertical mirror image

  • « Imagick::floodFillPaintImage
  • Imagick::forwardFourierTransformImage »
  • PHP Manual
  • Imagick
  • Creates a vertical mirror image

Imagick::flopImage

(PECL imagick 2.0.0)

Imagick::flopImage — Creates a vertical mirror image

Description

Imagick::flopImage ( void ) : bool

Creates a vertical mirror image by reflecting the pixels around the central y-axis.

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();
}

?>


Description

  • « Imagick::flopImage
  • Imagick::frameImage »
  • PHP Manual
  • Imagick
  • Description

Imagick::forwardFourierTransformImage

(No version information available, might only be in Git)

Imagick::forwardFourierTransformImage — Description

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();
}

?>


Adds a simulated three-dimensional border

  • « Imagick::forwardFourierTransformImage
  • Imagick::functionImage »
  • PHP Manual
  • Imagick
  • Adds a simulated three-dimensional border

Imagick::frameImage

(PECL imagick 2.0.0)

Imagick::frameImage — Adds a simulated three-dimensional border

Description

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
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();
}

?>


Applies a function on the image

  • « Imagick::frameImage
  • Imagick::fxImage »
  • PHP Manual
  • Imagick
  • Applies a function on the image

Imagick::functionImage

(No version information available, might only be in Git)

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:

Output of create a sinusoidal gradient

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:

Output of create a polynomial gradient

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:

Output of create complex gradient


Evaluate expression for each pixel in the image

  • « Imagick::functionImage
  • Imagick::gammaImage »
  • PHP Manual
  • Imagick
  • Evaluate expression for each pixel in the image

Imagick::fxImage

(PECL imagick 2.0.0)

Imagick::fxImage — Evaluate expression for each pixel in the image

Description

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();
}

?>


Gamma-corrects an image

  • « Imagick::fxImage
  • Imagick::gaussianBlurImage »
  • PHP Manual
  • Imagick
  • Gamma-corrects an image

Imagick::gammaImage

(PECL imagick 2.0.0)

Imagick::gammaImage — Gamma-corrects an image

Description

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();
}

?>


Blurs an image

  • « Imagick::gammaImage
  • Imagick::getColorspace »
  • PHP Manual
  • Imagick
  • Blurs an image

Imagick::gaussianBlurImage

(PECL imagick 2.0.0)

Imagick::gaussianBlurImage — Blurs an image

Description

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();
}

?>


Gets the colorspace

  • « Imagick::gaussianBlurImage
  • Imagick::getCompression »
  • PHP Manual
  • Imagick
  • Gets the colorspace

Imagick::getColorspace

(PECL imagick 0.9.10-0.9.9)

Imagick::getColorspace — Gets the colorspace

Description

Imagick::getColorspace ( void ) : int

Gets the global colorspace value. This method is available if Imagick has been compiled against ImageMagick version 6.5.7 or newer.

Return Values

Returns an integer which can be compared against COLORSPACE constants.


Gets the object compression type

  • « Imagick::getColorspace
  • Imagick::getCompressionQuality »
  • PHP Manual
  • Imagick
  • Gets the object compression type

Imagick::getCompression

(PECL imagick 2.0.0)

Imagick::getCompression — Gets the object compression type

Description

Imagick::getCompression ( void ) : int

Gets the object compression type.

Return Values

Returns the compression constant


Gets the object compression quality

  • « Imagick::getCompression
  • Imagick::getCopyright »
  • PHP Manual
  • Imagick
  • Gets the object compression quality

Imagick::getCompressionQuality

(PECL imagick 2.0.0)

Imagick::getCompressionQuality — Gets the object compression quality

Description

Imagick::getCompressionQuality ( void ) : int

Gets the object compression quality.

Return Values

Returns integer describing the compression quality


Returns the ImageMagick API copyright as a string

  • « Imagick::getCompressionQuality
  • Imagick::getFilename »
  • PHP Manual
  • Imagick
  • Returns the ImageMagick API copyright as a string

Imagick::getCopyright

(PECL imagick 2.0.0)

Imagick::getCopyright — Returns the ImageMagick API copyright as a string

Description

Imagick::getCopyright ( void ) : string

Returns the ImageMagick API copyright as a string.

Return Values

Returns a string containing the copyright notice of Imagemagick and Magickwand C API.


The filename associated with an image sequence

  • « Imagick::getCopyright
  • Imagick::getFont »
  • PHP Manual
  • Imagick
  • The filename associated with an image sequence

Imagick::getFilename

(PECL imagick 2.0.0)

Imagick::getFilename — The filename associated with an image sequence

Description

Imagick::getFilename ( void ) : string

Returns the filename associated with an image sequence.

Return Values

Returns a string on success.

Errors/Exceptions

Throws ImagickException on error.


Gets font

  • « Imagick::getFilename
  • Imagick::getFormat »
  • PHP Manual
  • Imagick
  • Gets font

Imagick::getFont

(PECL imagick 2.1.0)

Imagick::getFont — Gets font

Description

Imagick::getFont ( void ) : string

Returns the objects font property. This method is available if Imagick has been compiled against ImageMagick version 6.3.7 or newer.

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


Returns the format of the Imagick object

  • « Imagick::getFont
  • Imagick::getGravity »
  • PHP Manual
  • Imagick
  • Returns the format of the Imagick object

Imagick::getFormat

(PECL imagick 2.0.0)

Imagick::getFormat — Returns the format of the Imagick object

Description

Imagick::getFormat ( void ) : string

Returns the format of the Imagick object.

Return Values

Returns the format of the image.

Errors/Exceptions

Throws ImagickException on error.


Gets the gravity

  • « Imagick::getFormat
  • Imagick::getHomeURL »
  • PHP Manual
  • Imagick
  • Gets the gravity

Imagick::getGravity

(No version information available, might only be in Git)

Imagick::getGravity — Gets the gravity

Description

Imagick::getGravity ( void ) : 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.

Return Values

Returns the gravity property. Refer to the list of gravity constants.


Returns the ImageMagick home URL

  • « Imagick::getGravity
  • Imagick::getImage »
  • PHP Manual
  • Imagick
  • Returns the ImageMagick home URL

Imagick::getHomeURL

(PECL imagick 2.0.0)

Imagick::getHomeURL — Returns the ImageMagick home URL

Description

Imagick::getHomeURL ( void ) : string

Returns the ImageMagick home URL.

Return Values

Returns a link to the imagemagick homepage.


Returns a new Imagick object

  • « Imagick::getHomeURL
  • Imagick::getImageAlphaChannel »
  • PHP Manual
  • Imagick
  • Returns a new Imagick object

Imagick::getImage

(PECL imagick 2.0.0)

Imagick::getImage — Returns a new Imagick object

Description

Imagick::getImage ( void ) : Imagick

Returns a new Imagick object with the current image sequence.

Return Values

Returns a new Imagick object with the current image sequence.

Errors/Exceptions

Throws ImagickException on error.


Gets the image alpha channel

  • « Imagick::getImage
  • Imagick::getImageArtifact »
  • PHP Manual
  • Imagick
  • Gets the image alpha channel

Imagick::getImageAlphaChannel

(No version information available, might only be in Git)

Imagick::getImageAlphaChannel — Gets the image alpha channel

Description

Imagick::getImageAlphaChannel ( void ) : int

Gets the image alpha channel value. The returned value is one of the alpha channel constants. This method is available if Imagick has been compiled against ImageMagick version 6.4.0 or newer.

Return Values

Returns a constant defining the current alpha channel value. Refer to this list of alpha channel constants.

Errors/Exceptions

Throws ImagickException on error.


Get image artifact

  • « Imagick::getImageAlphaChannel
  • Imagick::getImageAttribute »
  • PHP Manual
  • Imagick
  • Get image artifact

Imagick::getImageArtifact

(No version information available, might only be in Git)

Imagick::getImageArtifact — Get image artifact

Description

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


Description

  • « Imagick::getImageArtifact
  • Imagick::getImageBackgroundColor »
  • PHP Manual
  • Imagick
  • Description

Imagick::getImageAttribute

(No version information available, might only be in Git)

Imagick::getImageAttribute — Description

Description

public Imagick::getImageAttribute ( string $key ) : string

Returns a named attribute.

Parameters

key

The key of the attribute to get.

Return Values


Returns the image background color

  • « Imagick::getImageAttribute
  • Imagick::getImageBlob »
  • PHP Manual
  • Imagick
  • Returns the image background color

Imagick::getImageBackgroundColor

(PECL imagick 2.0.0)

Imagick::getImageBackgroundColor — Returns the image background color

Description

Imagick::getImageBackgroundColor ( void ) : ImagickPixel

Returns the image background color.

Return Values

Returns an ImagickPixel set to the background color of the image.

Errors/Exceptions

Throws ImagickException on error.


Returns the image sequence as a blob

  • « Imagick::getImageBackgroundColor
  • Imagick::getImageBluePrimary »
  • PHP Manual
  • Imagick
  • Returns the image sequence as a blob

Imagick::getImageBlob

(PECL imagick 2.0.0)

Imagick::getImageBlob — Returns the image sequence as a blob

Description

Imagick::getImageBlob ( void ) : 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().

Return Values

Returns a string containing the image.

Errors/Exceptions

Throws ImagickException on error.


Returns the chromaticy blue primary point

  • « Imagick::getImageBlob
  • Imagick::getImageBorderColor »
  • PHP Manual
  • Imagick
  • Returns the chromaticy blue primary point

Imagick::getImageBluePrimary

(PECL imagick 2.0.0)

Imagick::getImageBluePrimary — Returns the chromaticy blue primary point

Description

Imagick::getImageBluePrimary ( void ) : 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.


Returns the image border color

  • « Imagick::getImageBluePrimary
  • Imagick::getImageChannelDepth »
  • PHP Manual
  • Imagick
  • Returns the image border color

Imagick::getImageBorderColor

(PECL imagick 2.0.0)

Imagick::getImageBorderColor — Returns the image border color

Description

Imagick::getImageBorderColor ( void ) : ImagickPixel

Returns the image border color.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.


Gets the depth for a particular image channel

  • « Imagick::getImageBorderColor
  • Imagick::getImageChannelDistortion »
  • PHP Manual
  • Imagick
  • Gets the depth for a particular image channel

Imagick::getImageChannelDepth

(PECL imagick 2.0.0)

Imagick::getImageChannelDepth — Gets the depth for a particular image channel

Description

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.


Compares image channels of an image to a reconstructed image

  • « Imagick::getImageChannelDepth
  • Imagick::getImageChannelDistortions »
  • PHP Manual
  • Imagick
  • Compares image channels of an image to a reconstructed image

Imagick::getImageChannelDistortion

(PECL imagick 2.0.0)

Imagick::getImageChannelDistortion — Compares image channels of an image to a reconstructed image

Description

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.


Gets channel distortions

  • « Imagick::getImageChannelDistortion
  • Imagick::getImageChannelExtrema »
  • PHP Manual
  • Imagick
  • Gets channel distortions

Imagick::getImageChannelDistortions

(No version information available, might only be in Git)

Imagick::getImageChannelDistortions — Gets channel distortions

Description

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 double describing the channel distortion.

Errors/Exceptions

Throws ImagickException on error.


Gets the extrema for one or more image channels

  • « Imagick::getImageChannelDistortions
  • Imagick::getImageChannelKurtosis »
  • PHP Manual
  • Imagick
  • Gets the extrema for one or more image channels

Imagick::getImageChannelExtrema

(PECL imagick 2.0.0)

Imagick::getImageChannelExtrema — Gets the extrema for one or more image channels

Description

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.


The getImageChannelKurtosis purpose

  • « Imagick::getImageChannelExtrema
  • Imagick::getImageChannelMean »
  • PHP Manual
  • Imagick
  • The getImageChannelKurtosis purpose

Imagick::getImageChannelKurtosis

(No version information available, might only be in Git)

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.


Gets the mean and standard deviation

  • « Imagick::getImageChannelKurtosis
  • Imagick::getImageChannelRange »
  • PHP Manual
  • Imagick
  • Gets the mean and standard deviation

Imagick::getImageChannelMean

(PECL imagick 2.0.0)

Imagick::getImageChannelMean — Gets the mean and standard deviation

Description

Imagick::getImageChannelMean ( int $channel ) : array

Gets the mean and standard deviation of one or more image channels. Return value is an associative array with the keys "mean" and "standardDeviation".

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.


Gets channel range

  • « Imagick::getImageChannelMean
  • Imagick::getImageChannelStatistics »
  • PHP Manual
  • Imagick
  • Gets channel range

Imagick::getImageChannelRange

(PECL imagick 2.2.1)

Imagick::getImageChannelRange — Gets channel range

Description

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.


Returns statistics for each channel in the image

  • « Imagick::getImageChannelRange
  • Imagick::getImageClipMask »
  • PHP Manual
  • Imagick
  • Returns statistics for each channel in the image

Imagick::getImageChannelStatistics

(PECL imagick 2.0.0)

Imagick::getImageChannelStatistics — Returns statistics for each channel in the image

Description

Imagick::getImageChannelStatistics ( void ) : 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. You can access the red channel mean, for example, like this:

Return Values

Returns TRUE on success.


Gets image clip mask

  • « Imagick::getImageChannelStatistics
  • Imagick::getImageColormapColor »
  • PHP Manual
  • Imagick
  • Gets image clip mask

Imagick::getImageClipMask

(No version information available, might only be in Git)

Imagick::getImageClipMask — Gets image clip mask

Description

Imagick::getImageClipMask ( void ) : 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.

Return Values

Returns an Imagick object containing the clip mask.

Errors/Exceptions

Throws ImagickException on error.


Returns the color of the specified colormap index

  • « Imagick::getImageClipMask
  • Imagick::getImageColors »
  • PHP Manual
  • Imagick
  • Returns the color of the specified colormap index

Imagick::getImageColormapColor

(PECL imagick 2.0.0)

Imagick::getImageColormapColor — Returns the color of the specified colormap index

Description

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.


Gets the number of unique colors in the image

  • « Imagick::getImageColormapColor
  • Imagick::getImageColorspace »
  • PHP Manual
  • Imagick
  • Gets the number of unique colors in the image

Imagick::getImageColors

(PECL imagick 2.0.0)

Imagick::getImageColors — Gets the number of unique colors in the image

Description

Imagick::getImageColors ( void ) : int

Gets the number of unique colors in the image.

Return Values

Returns an integer, the number of unique colors in the image.


Gets the image colorspace

  • « Imagick::getImageColors
  • Imagick::getImageCompose »
  • PHP Manual
  • Imagick
  • Gets the image colorspace

Imagick::getImageColorspace

(PECL imagick 2.0.0)

Imagick::getImageColorspace — Gets the image colorspace

Description

Imagick::getImageColorspace ( void ) : int

Gets the image colorspace.

Return Values

Returns an integer which can be compared against COLORSPACE constants.


Returns the composite operator associated with the image

  • « Imagick::getImageColorspace
  • Imagick::getImageCompression »
  • PHP Manual
  • Imagick
  • Returns the composite operator associated with the image

Imagick::getImageCompose

(PECL imagick 2.0.0)

Imagick::getImageCompose — Returns the composite operator associated with the image

Description

Imagick::getImageCompose ( void ) : int

Returns the composite operator associated with the image.

Return Values

Returns TRUE on success.


Gets the current image's compression type

  • « Imagick::getImageCompose
  • Imagick::getImageCompressionQuality »
  • PHP Manual
  • Imagick
  • Gets the current image's compression type

Imagick::getImageCompression

(PECL imagick 2.2.2)

Imagick::getImageCompression — Gets the current image's compression type

Description

Imagick::getImageCompression ( void ) : int

Gets the current image's compression type.

Return Values

Returns the compression constant


Gets the current image's compression quality

  • « Imagick::getImageCompression
  • Imagick::getImageDelay »
  • PHP Manual
  • Imagick
  • Gets the current image's compression quality

Imagick::getImageCompressionQuality

(PECL imagick 2.2.2)

Imagick::getImageCompressionQuality — Gets the current image's compression quality

Description

Imagick::getImageCompressionQuality ( void ) : int

Gets the current image's compression quality

Return Values

Returns integer describing the images compression quality


Gets the image delay

  • « Imagick::getImageCompressionQuality
  • Imagick::getImageDepth »
  • PHP Manual
  • Imagick
  • Gets the image delay

Imagick::getImageDelay

(PECL imagick 2.0.0)

Imagick::getImageDelay — Gets the image delay

Description

Imagick::getImageDelay ( void ) : int

Gets the image delay.

Return Values

Returns the image delay.

Errors/Exceptions

Throws ImagickException on error.


Gets the image depth

  • « Imagick::getImageDelay
  • Imagick::getImageDispose »
  • PHP Manual
  • Imagick
  • Gets the image depth

Imagick::getImageDepth

(PECL imagick 0.9.1-0.9.9)

Imagick::getImageDepth — Gets the image depth

Description

Imagick::getImageDepth ( void ) : int

Gets the image depth.

Return Values

The image depth.


Gets the image disposal method

  • « Imagick::getImageDepth
  • Imagick::getImageDistortion »
  • PHP Manual
  • Imagick
  • Gets the image disposal method

Imagick::getImageDispose

(PECL imagick 2.0.0)

Imagick::getImageDispose — Gets the image disposal method

Description

Imagick::getImageDispose ( void ) : int

Gets the image disposal method.

Return Values

Returns the dispose method on success.

Errors/Exceptions

Throws ImagickException on error.


Compares an image to a reconstructed image

  • « Imagick::getImageDispose
  • Imagick::getImageExtrema »
  • PHP Manual
  • Imagick
  • Compares an image to a reconstructed image

Imagick::getImageDistortion

(PECL imagick 2.0.0)

Imagick::getImageDistortion — Compares an image to a reconstructed image

Description

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.


Gets the extrema for the image

  • « Imagick::getImageDistortion
  • Imagick::getImageFilename »
  • PHP Manual
  • Imagick
  • Gets the extrema for the image

Imagick::getImageExtrema

(PECL imagick 2.0.0)

Imagick::getImageExtrema — Gets the extrema for the image

Description

Imagick::getImageExtrema ( void ) : array

Gets the extrema for the image. Returns an associative array with the keys "min" and "max".

Return Values

Returns an associative array with the keys "min" and "max".

Errors/Exceptions

Throws ImagickException on error.


Returns the filename of a particular image in a sequence

  • « Imagick::getImageExtrema
  • Imagick::getImageFormat »
  • PHP Manual
  • Imagick
  • Returns the filename of a particular image in a sequence

Imagick::getImageFilename

(PECL imagick 2.0.0)

Imagick::getImageFilename — Returns the filename of a particular image in a sequence

Description

Imagick::getImageFilename ( void ) : string

Returns the filename of a particular image in a sequence.

Return Values

Returns a string with the filename of the image.

Errors/Exceptions

Throws ImagickException on error.


Returns the format of a particular image in a sequence

  • « Imagick::getImageFilename
  • Imagick::getImageGamma »
  • PHP Manual
  • Imagick
  • Returns the format of a particular image in a sequence

Imagick::getImageFormat

(PECL imagick 2.0.0)

Imagick::getImageFormat — Returns the format of a particular image in a sequence

Description

Imagick::getImageFormat ( void ) : string

Returns the format of a particular image in a sequence.

Return Values

Returns a string containing the image format on success.

Errors/Exceptions

Throws ImagickException on error.


Gets the image gamma

  • « Imagick::getImageFormat
  • Imagick::getImageGeometry »
  • PHP Manual
  • Imagick
  • Gets the image gamma

Imagick::getImageGamma

(PECL imagick 2.0.0)

Imagick::getImageGamma — Gets the image gamma

Description

Imagick::getImageGamma ( void ) : float

Gets the image gamma.

Return Values

Returns the image gamma on success.

Errors/Exceptions

Throws ImagickException on error.


Gets the width and height as an associative array

  • « Imagick::getImageGamma
  • Imagick::getImageGravity »
  • PHP Manual
  • Imagick
  • Gets the width and height as an associative array

Imagick::getImageGeometry

(PECL imagick 2.0.0)

Imagick::getImageGeometry — Gets the width and height as an associative array

Description

Imagick::getImageGeometry ( void ) : array

Returns the width and height as an associative array.

Return Values

Returns an array with the width/height of the image.

Errors/Exceptions

Throws ImagickException on error.

Examples

Example #1 Imagick::getImageGeometry()

<?php
function getImageGeometry($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>


Gets the image gravity

  • « Imagick::getImageGeometry
  • Imagick::getImageGreenPrimary »
  • PHP Manual
  • Imagick
  • Gets the image gravity

Imagick::getImageGravity

(No version information available, might only be in Git)

Imagick::getImageGravity — Gets the image gravity

Description

Imagick::getImageGravity ( void ) : 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.

Return Values

Returns the images gravity property. Refer to the list of gravity constants.


Returns the chromaticy green primary point

  • « Imagick::getImageGravity
  • Imagick::getImageHeight »
  • PHP Manual
  • Imagick
  • Returns the chromaticy green primary point

Imagick::getImageGreenPrimary

(PECL imagick 2.0.0)

Imagick::getImageGreenPrimary — Returns the chromaticy green primary point

Description

Imagick::getImageGreenPrimary ( void ) : array

Returns the chromaticity green primary point. Returns an array with the keys "x" and "y".

Return Values

Returns an array with the keys "x" and "y" on success, throws an ImagickException on failure.

Errors/Exceptions

Throws ImagickException on error.


Returns the image height

  • « Imagick::getImageGreenPrimary
  • Imagick::getImageHistogram »
  • PHP Manual
  • Imagick
  • Returns the image height

Imagick::getImageHeight

(PECL imagick 2.0.0)

Imagick::getImageHeight — Returns the image height

Description

Imagick::getImageHeight ( void ) : int

Returns the image height.

Return Values

Returns the image height in pixels.

Errors/Exceptions

Throws ImagickException on error.


Gets the image histogram

  • « Imagick::getImageHeight
  • Imagick::getImageIndex »
  • PHP Manual
  • Imagick
  • Gets the image histogram

Imagick::getImageHistogram

(PECL imagick 2.0.0)

Imagick::getImageHistogram — Gets the image histogram

Description

Imagick::getImageHistogram ( void ) : array

Returns the image histogram as an array of ImagickPixel objects.

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;
}

?>


Gets the index of the current active image

  • « Imagick::getImageHistogram
  • Imagick::getImageInterlaceScheme »
  • PHP Manual
  • Imagick
  • Gets the index of the current active image

Imagick::getImageIndex

(PECL imagick 2.0.0)

Imagick::getImageIndex — Gets the index of the current active image

Description

Imagick::getImageIndex ( void ) : int

Returns the index of the current active image within the Imagick object. This method has been deprecated. See Imagick::getIteratorIndex().

Return Values

Returns an integer containing the index of the image in the stack.

Errors/Exceptions

Throws ImagickException on error.


Gets the image interlace scheme

  • « Imagick::getImageIndex
  • Imagick::getImageInterpolateMethod »
  • PHP Manual
  • Imagick
  • Gets the image interlace scheme

Imagick::getImageInterlaceScheme

(PECL imagick 2.0.0)

Imagick::getImageInterlaceScheme — Gets the image interlace scheme

Description

Imagick::getImageInterlaceScheme ( void ) : int

Gets the image interlace scheme.

Return Values

Returns the interlace scheme as an integer on success. Throw an ImagickException on error.


Returns the interpolation method

  • « Imagick::getImageInterlaceScheme
  • Imagick::getImageIterations »
  • PHP Manual
  • Imagick
  • Returns the interpolation method

Imagick::getImageInterpolateMethod

(PECL imagick 2.0.0)

Imagick::getImageInterpolateMethod — Returns the interpolation method

Description

Imagick::getImageInterpolateMethod ( void ) : int

Returns the interpolation method for the specified image. The method is one of the Imagick::INTERPOLATE_* constants.

Return Values

Returns the interpolate method on success.

Errors/Exceptions

Throws ImagickException on error.


Gets the image iterations

  • « Imagick::getImageInterpolateMethod
  • Imagick::getImageLength »
  • PHP Manual
  • Imagick
  • Gets the image iterations

Imagick::getImageIterations

(PECL imagick 2.0.0)

Imagick::getImageIterations — Gets the image iterations

Description

Imagick::getImageIterations ( void ) : int

Gets the image iterations.

Return Values

Returns the image iterations as an integer.

Errors/Exceptions

Throws ImagickException on error.


Returns the image length in bytes

  • « Imagick::getImageIterations
  • Imagick::getImageMagickLicense »
  • PHP Manual
  • Imagick
  • Returns the image length in bytes

Imagick::getImageLength

(PECL imagick 2.0.0)

Imagick::getImageLength — Returns the image length in bytes

Description

Imagick::getImageLength ( void ) : int

Returns the image length in bytes

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';
?>


Returns a string containing the ImageMagick license

  • « Imagick::getImageLength
  • Imagick::getImageMatte »
  • PHP Manual
  • Imagick
  • Returns a string containing the ImageMagick license

Imagick::getImageMagickLicense

(PECL imagick 2.0.0)

Imagick::getImageMagickLicense — Returns a string containing the ImageMagick license

Description

Imagick::getImageMagickLicense ( void ) : string

Returns a string containing the ImageMagick license

Return Values

Returns a string containing the ImageMagick license.


Return if the image has a matte channel

  • « Imagick::getImageMagickLicense
  • Imagick::getImageMatteColor »
  • PHP Manual
  • Imagick
  • Return if the image has a matte channel

Imagick::getImageMatte

(PECL imagick 2.0.0)

Imagick::getImageMatte — Return if the image has a matte channel

Description

Imagick::getImageMatte ( void ) : 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.

Return Values

Returns TRUE on success.


Returns the image matte color

  • « Imagick::getImageMatte
  • Imagick::getImageMimeType »
  • PHP Manual
  • Imagick
  • Returns the image matte color

Imagick::getImageMatteColor

(PECL imagick 2.0.0)

Imagick::getImageMatteColor — Returns the image matte color

Description

Imagick::getImageMatteColor ( void ) : ImagickPixel

Returns the image matte color.

Return Values

Returns ImagickPixel object on success.

Errors/Exceptions

Throws ImagickException on error.


Description

  • « Imagick::getImageMatteColor
  • Imagick::getImageOrientation »
  • PHP Manual
  • Imagick
  • Description

Imagick::getImageMimeType

(No version information available, might only be in Git)

Imagick::getImageMimeType — Description

Description

public Imagick::getImageMimeType ( void ) : string

Returns the image mime-type.

Parameters

This function has no parameters.

Return Values


Gets the image orientation

  • « Imagick::getImageMimeType
  • Imagick::getImagePage »
  • PHP Manual
  • Imagick
  • Gets the image orientation

Imagick::getImageOrientation

(PECL imagick 2.0.0)

Imagick::getImageOrientation — Gets the image orientation

Description

Imagick::getImageOrientation ( void ) : int

Gets the image orientation. The return value is one of the orientation constants.

Return Values

Returns an int on success.

Errors/Exceptions

Throws ImagickException on error.


Returns the page geometry

  • « Imagick::getImageOrientation
  • Imagick::getImagePixelColor »
  • PHP Manual
  • Imagick
  • Returns the page geometry

Imagick::getImagePage

(PECL imagick 2.0.0)

Imagick::getImagePage — Returns the page geometry

Description

Imagick::getImagePage ( void ) : array

Returns the page geometry associated with the image in an array with the keys "width", "height", "x", and "y".

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.


Returns the color of the specified pixel

  • « Imagick::getImagePage
  • Imagick::getImageProfile »
  • PHP Manual
  • Imagick
  • Returns the color of the specified pixel

Imagick::getImagePixelColor

(PECL imagick 2.0.0)

Imagick::getImagePixelColor — Returns the color of the specified pixel

Description

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.


Returns the named image profile

  • « Imagick::getImagePixelColor
  • Imagick::getImageProfiles »
  • PHP Manual
  • Imagick
  • Returns the named image profile

Imagick::getImageProfile

(PECL imagick 2.0.0)

Imagick::getImageProfile — Returns the named image profile

Description

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.


Returns the image profiles

  • « Imagick::getImageProfile
  • Imagick::getImageProperties »
  • PHP Manual
  • Imagick
  • Returns the image profiles

Imagick::getImageProfiles

(PECL imagick 2.0.0)

Imagick::getImageProfiles — Returns the image profiles

Description

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.


Returns the image properties

  • « Imagick::getImageProfiles
  • Imagick::getImageProperty »
  • PHP Manual
  • Imagick
  • Returns the image properties

Imagick::getImageProperties

(PECL imagick 2.0.0)

Imagick::getImageProperties — Returns the image properties

Description

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";
}

?>


Returns the named image property

  • « Imagick::getImageProperties
  • Imagick::getImageRedPrimary »
  • PHP Manual
  • Imagick
  • Returns the named image property

Imagick::getImageProperty

(PECL imagick 2.0.0)

Imagick::getImageProperty — Returns the named image property

Description

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)

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

Return Values

Returns a string containing the image property, false if a property with the given name does not exist.


Returns the chromaticity red primary point

  • « Imagick::getImageProperty
  • Imagick::getImageRegion »
  • PHP Manual
  • Imagick
  • Returns the chromaticity red primary point

Imagick::getImageRedPrimary

(PECL imagick 2.0.0)

Imagick::getImageRedPrimary — Returns the chromaticity red primary point

Description

Imagick::getImageRedPrimary ( void ) : array

Returns the chromaticity red primary point as an array with the keys "x" and "y".

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.


Extracts a region of the image

  • « Imagick::getImageRedPrimary
  • Imagick::getImageRenderingIntent »
  • PHP Manual
  • Imagick
  • Extracts a region of the image

Imagick::getImageRegion

(PECL imagick 2.0.0)

Imagick::getImageRegion — Extracts a region of the image

Description

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.


Gets the image rendering intent

  • « Imagick::getImageRegion
  • Imagick::getImageResolution »
  • PHP Manual
  • Imagick
  • Gets the image rendering intent

Imagick::getImageRenderingIntent

(PECL imagick 2.0.0)

Imagick::getImageRenderingIntent — Gets the image rendering intent

Description

Imagick::getImageRenderingIntent ( void ) : int

Gets the image rendering intent.

Return Values

Returns the image rendering intent.

Errors/Exceptions

Throws ImagickException on error.


Gets the image X and Y resolution

  • « Imagick::getImageRenderingIntent
  • Imagick::getImagesBlob »
  • PHP Manual
  • Imagick
  • Gets the image X and Y resolution

Imagick::getImageResolution

(PECL imagick 2.0.0)

Imagick::getImageResolution — Gets the image X and Y resolution

Description

Imagick::getImageResolution ( void ) : array

Gets the image X and Y resolution.

Return Values

Returns the resolution as an array.

Errors/Exceptions

Throws ImagickException on error.


Returns all image sequences as a blob

  • « Imagick::getImageResolution
  • Imagick::getImageScene »
  • PHP Manual
  • Imagick
  • Returns all image sequences as a blob

Imagick::getImagesBlob

(PECL imagick 2.0.0)

Imagick::getImagesBlob — Returns all image sequences as a blob

Description

Imagick::getImagesBlob ( void ) : 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().

Return Values

Returns a string containing the images. On failure, throws ImagickException.


Gets the image scene

  • « Imagick::getImagesBlob
  • Imagick::getImageSignature »
  • PHP Manual
  • Imagick
  • Gets the image scene

Imagick::getImageScene

(PECL imagick 2.0.0)

Imagick::getImageScene — Gets the image scene

Description

Imagick::getImageScene ( void ) : int

Gets the image scene.

Return Values

Returns the image scene.

Errors/Exceptions

Throws ImagickException on error.


Generates an SHA-256 message digest

  • « Imagick::getImageScene
  • Imagick::getImageSize »
  • PHP Manual
  • Imagick
  • Generates an SHA-256 message digest

Imagick::getImageSignature

(PECL imagick 2.0.0)

Imagick::getImageSignature — Generates an SHA-256 message digest

Description

Imagick::getImageSignature ( void ) : string

Generates an SHA-256 message digest for the image pixel stream.

Return Values

Returns a string containing the SHA-256 hash of the file.

Errors/Exceptions

Throws ImagickException on error.


Returns the image length in bytes

  • « Imagick::getImageSignature
  • Imagick::getImageTicksPerSecond »
  • PHP Manual
  • Imagick
  • Returns the image length in bytes

Imagick::getImageSize

(PECL imagick 2.0.0)

Imagick::getImageSize — Returns the image length in bytes

Description

Imagick::getImageSize ( void ) : int

Returns the image length in bytes. Deprecated in favour of Imagick::getImageLength()

Return Values

Returns an int containing the current image size.


Gets the image ticks-per-second

  • « Imagick::getImageSize
  • Imagick::getImageTotalInkDensity »
  • PHP Manual
  • Imagick
  • Gets the image ticks-per-second

Imagick::getImageTicksPerSecond

(PECL imagick 2.0.0)

Imagick::getImageTicksPerSecond — Gets the image ticks-per-second

Description

Imagick::getImageTicksPerSecond ( void ) : int

Gets the image ticks-per-second.

Return Values

Returns the image ticks-per-second.

Errors/Exceptions

Throws ImagickException on error.


Gets the image total ink density

  • « Imagick::getImageTicksPerSecond
  • Imagick::getImageType »
  • PHP Manual
  • Imagick
  • Gets the image total ink density

Imagick::getImageTotalInkDensity

(PECL imagick 2.0.0)

Imagick::getImageTotalInkDensity — Gets the image total ink density

Description

Imagick::getImageTotalInkDensity ( void ) : float

Gets the image total ink density.

Return Values

Returns the image total ink density of the image. Throw an ImagickException on error.


Gets the potential image type

  • « Imagick::getImageTotalInkDensity
  • Imagick::getImageUnits »
  • PHP Manual
  • Imagick
  • Gets the potential image type

Imagick::getImageType

(PECL imagick 0.9.10-0.9.9)

Imagick::getImageType — Gets the potential image type

Description

Imagick::getImageType ( void ) : int

Gets the potential image type.

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.


Gets the image units of resolution

  • « Imagick::getImageType
  • Imagick::getImageVirtualPixelMethod »
  • PHP Manual
  • Imagick
  • Gets the image units of resolution

Imagick::getImageUnits

(PECL imagick 2.0.0)

Imagick::getImageUnits — Gets the image units of resolution

Description

Imagick::getImageUnits ( void ) : int

Gets the image units of resolution.

Return Values

Returns the image units of resolution.

Errors/Exceptions

Throws ImagickException on error.


Returns the virtual pixel method

  • « Imagick::getImageUnits
  • Imagick::getImageWhitePoint »
  • PHP Manual
  • Imagick
  • Returns the virtual pixel method

Imagick::getImageVirtualPixelMethod

(PECL imagick 2.0.0)

Imagick::getImageVirtualPixelMethod — Returns the virtual pixel method

Description

Imagick::getImageVirtualPixelMethod ( void ) : int

Returns the virtual pixel method for the specified image.

Return Values

Returns the virtual pixel method on success.

Errors/Exceptions

Throws ImagickException on error.


Returns the chromaticity white point

  • « Imagick::getImageVirtualPixelMethod
  • Imagick::getImageWidth »
  • PHP Manual
  • Imagick
  • Returns the chromaticity white point

Imagick::getImageWhitePoint

(PECL imagick 2.0.0)

Imagick::getImageWhitePoint — Returns the chromaticity white point

Description

Imagick::getImageWhitePoint ( void ) : array

Returns the chromaticity white point as an associative array with the keys "x" and "y".

Return Values

Returns the chromaticity white point as an associative array with the keys "x" and "y".

Errors/Exceptions

Throws ImagickException on error.


Returns the image width

  • « Imagick::getImageWhitePoint
  • Imagick::getInterlaceScheme »
  • PHP Manual
  • Imagick
  • Returns the image width

Imagick::getImageWidth

(PECL imagick 2.0.0)

Imagick::getImageWidth — Returns the image width

Description

Imagick::getImageWidth ( void ) : int

Returns the image width.

Return Values

Returns the image width.

Errors/Exceptions

Throws ImagickException on error.


Gets the object interlace scheme

  • « Imagick::getImageWidth
  • Imagick::getIteratorIndex »
  • PHP Manual
  • Imagick
  • Gets the object interlace scheme

Imagick::getInterlaceScheme

(PECL imagick 2.0.0)

Imagick::getInterlaceScheme — Gets the object interlace scheme

Description

Imagick::getInterlaceScheme ( void ) : int

Gets the object interlace scheme.

Return Values

Gets the wand interlace scheme.

Errors/Exceptions

Throws ImagickException on error.


Gets the index of the current active image

  • « Imagick::getInterlaceScheme
  • Imagick::getNumberImages »
  • PHP Manual
  • Imagick
  • Gets the index of the current active image

Imagick::getIteratorIndex

(PECL imagick 2.0.0)

Imagick::getIteratorIndex — Gets the index of the current active image

Description

Imagick::getIteratorIndex ( void ) : 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.

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


Returns the number of images in the object

  • « Imagick::getIteratorIndex
  • Imagick::getOption »
  • PHP Manual
  • Imagick
  • Returns the number of images in the object

Imagick::getNumberImages

(PECL imagick 2.0.0)

Imagick::getNumberImages — Returns the number of images in the object

Description

Imagick::getNumberImages ( void ) : int

Returns the number of images associated with Imagick object.

Return Values

Returns the number of images associated with Imagick object.

Errors/Exceptions

Throws ImagickException on error.


Returns a value associated with the specified key

  • « Imagick::getNumberImages
  • Imagick::getPackageName »
  • PHP Manual
  • Imagick
  • Returns a value associated with the specified key

Imagick::getOption

(PECL imagick 2.0.0)

Imagick::getOption — Returns a value associated with the specified key

Description

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.


Returns the ImageMagick package name

  • « Imagick::getOption
  • Imagick::getPage »
  • PHP Manual
  • Imagick
  • Returns the ImageMagick package name

Imagick::getPackageName

(PECL imagick 2.0.0)

Imagick::getPackageName — Returns the ImageMagick package name

Description

Imagick::getPackageName ( void ) : string

Returns the ImageMagick package name.

Return Values

Returns the ImageMagick package name as a string.

Errors/Exceptions

Throws ImagickException on error.


Returns the page geometry

  • « Imagick::getPackageName
  • Imagick::getPixelIterator »
  • PHP Manual
  • Imagick
  • Returns the page geometry

Imagick::getPage

(PECL imagick 2.0.0)

Imagick::getPage — Returns the page geometry

Description

Imagick::getPage ( void ) : array

Returns the page geometry associated with the Imagick object in an associative array with the keys "width", "height", "x", and "y".

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.


Returns a MagickPixelIterator

  • « Imagick::getPage
  • Imagick::getPixelRegionIterator »
  • PHP Manual
  • Imagick
  • Returns a MagickPixelIterator

Imagick::getPixelIterator

(PECL imagick 2.0.0)

Imagick::getPixelIterator — Returns a MagickPixelIterator

Description

Imagick::getPixelIterator ( void ) : ImagickPixelIterator

Returns a MagickPixelIterator.

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;
}

?>


Get an ImagickPixelIterator for an image section

  • « Imagick::getPixelIterator
  • Imagick::getPointSize »
  • PHP Manual
  • Imagick
  • Get an ImagickPixelIterator for an image section

Imagick::getPixelRegionIterator

(PECL imagick 2.0.0)

Imagick::getPixelRegionIterator — Get an ImagickPixelIterator for an image section

Description

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");
?>


Gets point size

  • « Imagick::getPixelRegionIterator
  • Imagick::getQuantum »
  • PHP Manual
  • Imagick
  • Gets point size

Imagick::getPointSize

(No version information available, might only be in Git)

Imagick::getPointSize — Gets point size

Description

Imagick::getPointSize ( void ) : float

Returns the objects point size property. This method is available if Imagick has been compiled against ImageMagick version 6.3.7 or newer.

Return Values

Returns a float containing the point size.

See Also

  • Imagick::setPointSize() - Sets point size


Description

  • « Imagick::getPointSize
  • Imagick::getQuantumDepth »
  • PHP Manual
  • Imagick
  • Description

Imagick::getQuantum

(No version information available, might only be in Git)

Imagick::getQuantum — Description

Description

public static Imagick::getQuantum ( void ) : int

Returns the ImageMagick quantum range as an integer.

Parameters

This function has no parameters.

Return Values


Gets the quantum depth

  • « Imagick::getQuantum
  • Imagick::getQuantumRange »
  • PHP Manual
  • Imagick
  • Gets the quantum depth

Imagick::getQuantumDepth

(PECL imagick 2.0.0)

Imagick::getQuantumDepth — Gets the quantum depth

Description

Imagick::getQuantumDepth ( void ) : array

Returns the Imagick quantum depth as a string.

Return Values

Returns the Imagick quantum depth as a string.

Errors/Exceptions

Throws ImagickException on error.


Returns the Imagick quantum range

  • « Imagick::getQuantumDepth
  • Imagick::getRegistry »
  • PHP Manual
  • Imagick
  • Returns the Imagick quantum range

Imagick::getQuantumRange

(PECL imagick 2.0.0)

Imagick::getQuantumRange — Returns the Imagick quantum range

Description

Imagick::getQuantumRange ( void ) : array

Returns the quantum range for the Imagick instance.

Return Values

Returns an associative array containing the quantum range as an integer ("quantumRangeLong") and as a string ("quantumRangeString").

Errors/Exceptions

Throws ImagickException on error.


Description

  • « Imagick::getQuantumRange
  • Imagick::getReleaseDate »
  • PHP Manual
  • Imagick
  • Description

Imagick::getRegistry

(No version information available, might only be in Git)

Imagick::getRegistry — Description

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


Returns the ImageMagick release date

  • « Imagick::getRegistry
  • Imagick::getResource »
  • PHP Manual
  • Imagick
  • Returns the ImageMagick release date

Imagick::getReleaseDate

(PECL imagick 2.0.0)

Imagick::getReleaseDate — Returns the ImageMagick release date

Description

Imagick::getReleaseDate ( void ) : string

Returns the ImageMagick release date as a string.

Return Values

Returns the ImageMagick release date as a string.

Errors/Exceptions

Throws ImagickException on error.


Returns the specified resource's memory usage

  • « Imagick::getReleaseDate
  • Imagick::getResourceLimit »
  • PHP Manual
  • Imagick
  • Returns the specified resource's memory usage

Imagick::getResource

(PECL imagick 2.0.0)

Imagick::getResource — Returns the specified resource's memory usage

Description

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.


Returns the specified resource limit

  • « Imagick::getResource
  • Imagick::getSamplingFactors »
  • PHP Manual
  • Imagick
  • Returns the specified resource limit

Imagick::getResourceLimit

(PECL imagick 2.0.0)

Imagick::getResourceLimit — Returns the specified resource limit

Description

Imagick::getResourceLimit ( int $type ) : int

Returns the specified resource limit.

Parameters

type

One of the resourcetype constants. The unit depends on the type of the resource being limited.

Return Values

Returns the specified resource limit in megabytes.

Errors/Exceptions

Throws ImagickException on error.

See Also

  • Imagick::setResourceLimit() - Sets the limit for a particular resource


Gets the horizontal and vertical sampling factor

  • « Imagick::getResourceLimit
  • Imagick::getSize »
  • PHP Manual
  • Imagick
  • Gets the horizontal and vertical sampling factor

Imagick::getSamplingFactors

(PECL imagick 2.0.0)

Imagick::getSamplingFactors — Gets the horizontal and vertical sampling factor

Description

Imagick::getSamplingFactors ( void ) : array

Gets the horizontal and vertical sampling factor.

Return Values

Returns an associative array with the horizontal and vertical sampling factors of the image.

Errors/Exceptions

Throws ImagickException on error.


Returns the size associated with the Imagick object

  • « Imagick::getSamplingFactors
  • Imagick::getSizeOffset »
  • PHP Manual
  • Imagick
  • Returns the size associated with the Imagick object

Imagick::getSize

(PECL imagick 2.0.0)

Imagick::getSize — Returns the size associated with the Imagick object

Description

Imagick::getSize ( void ) : 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().

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


Returns the size offset

  • « Imagick::getSize
  • Imagick::getVersion »
  • PHP Manual
  • Imagick
  • Returns the size offset

Imagick::getSizeOffset

(PECL imagick 2.0.0)

Imagick::getSizeOffset — Returns the size offset

Description

Imagick::getSizeOffset ( void ) : 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.

Return Values

Returns the size offset associated with the Imagick object.

Errors/Exceptions

Throws ImagickException on error.


Returns the ImageMagick API version

  • « Imagick::getSizeOffset
  • Imagick::haldClutImage »
  • PHP Manual
  • Imagick
  • Returns the ImageMagick API version

Imagick::getVersion

(PECL imagick 2.0.0)

Imagick::getVersion — Returns the ImageMagick API version

Description

Imagick::getVersion ( void ) : array

Returns the ImageMagick API version as a string and as a number.

Return Values

Returns the ImageMagick API version as a string and as a number.

Errors/Exceptions

Throws ImagickException on error.


Replaces colors in the image

  • « Imagick::getVersion
  • Imagick::hasNextImage »
  • PHP Manual
  • Imagick
  • Replaces colors in the image

Imagick::haldClutImage

(No version information available, might only be in Git)

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();
}

?>


Checks if the object has more images

  • « Imagick::haldClutImage
  • Imagick::hasPreviousImage »
  • PHP Manual
  • Imagick
  • Checks if the object has more images

Imagick::hasNextImage

(PECL imagick 2.0.0)

Imagick::hasNextImage — Checks if the object has more images

Description

Imagick::hasNextImage ( void ) : bool

Returns TRUE if the object has more images when traversing the list in the forward direction.

Return Values

Returns TRUE if the object has more images when traversing the list in the forward direction, returns FALSE if there are none.


Checks if the object has a previous image

  • « Imagick::hasNextImage
  • Imagick::identifyFormat »
  • PHP Manual
  • Imagick
  • Checks if the object has a previous image

Imagick::hasPreviousImage

(PECL imagick 2.0.0)

Imagick::hasPreviousImage — Checks if the object has a previous image

Description

Imagick::hasPreviousImage ( void ) : bool

Returns TRUE if the object has more images when traversing the list in the reverse direction

Return Values

Returns TRUE if the object has more images when traversing the list in the reverse direction, returns FALSE if there are none.


Description

  • « Imagick::hasPreviousImage
  • Imagick::identifyImage »
  • PHP Manual
  • Imagick
  • Description

Imagick::identifyFormat

(No version information available, might only be in Git)

Imagick::identifyFormat — Description

Description

public Imagick::identifyFormat ( string $embedText ) : string

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");

?>


Identifies an image and fetches attributes

  • « Imagick::identifyFormat
  • Imagick::implodeImage »
  • PHP Manual
  • Imagick
  • Identifies an image and fetches attributes

Imagick::identifyImage

(PECL imagick 2.0.0)

Imagick::identifyImage — Identifies an image and fetches attributes

Description

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.

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
)

Errors/Exceptions

Throws ImagickException on error.


Creates a new image as a copy

  • « Imagick::identifyImage
  • Imagick::importImagePixels »
  • PHP Manual
  • Imagick
  • Creates a new image as a copy

Imagick::implodeImage

(PECL imagick 2.0.0)

Imagick::implodeImage — Creates a new image as a copy

Description

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();

}

?>


Imports image pixels

  • « Imagick::implodeImage
  • Imagick::inverseFourierTransformImage »
  • PHP Manual
  • Imagick
  • Imports image pixels

Imagick::importImagePixels

(No version information available, might only be in Git)

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:

Output of example : Imagick::importImagePixels()


Description

  • « Imagick::importImagePixels
  • Imagick::labelImage »
  • PHP Manual
  • Imagick
  • Description

Imagick::inverseFourierTransformImage

(No version information available, might only be in Git)

Imagick::inverseFourierTransformImage — Description

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.


Adds a label to an image

  • « Imagick::inverseFourierTransformImage
  • Imagick::levelImage »
  • PHP Manual
  • Imagick
  • Adds a label to an image

Imagick::labelImage

(PECL imagick 2.0.0)

Imagick::labelImage — Adds a label to an image

Description

Imagick::labelImage ( string $label ) : bool

Adds a label to an image.

Parameters

label

The label to add

Return Values

Returns TRUE on success.


Adjusts the levels of an image

  • « Imagick::labelImage
  • Imagick::linearStretchImage »
  • PHP Manual
  • Imagick
  • Adjusts the levels of an image

Imagick::levelImage

(PECL imagick 2.0.0)

Imagick::levelImage — Adjusts the levels of an image

Description

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();
}

?>


Stretches with saturation the image intensity

  • « Imagick::levelImage
  • Imagick::liquidRescaleImage »
  • PHP Manual
  • Imagick
  • Stretches with saturation the image intensity

Imagick::linearStretchImage

(PECL imagick 2.0.0)

Imagick::linearStretchImage — Stretches with saturation the image intensity

Description

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();
}

?>


Animates an image or images

  • « Imagick::linearStretchImage
  • Imagick::listRegistry »
  • PHP Manual
  • Imagick
  • Animates an image or images

Imagick::liquidRescaleImage

(No version information available, might only be in Git)

Imagick::liquidRescaleImage — Animates an image or images

Description

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


Description

  • « Imagick::liquidRescaleImage
  • Imagick::magnifyImage »
  • PHP Manual
  • Imagick
  • Description

Imagick::listRegistry

(No version information available, might only be in Git)

Imagick::listRegistry — Description

Description

public static Imagick::listRegistry ( void ) : 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.


Scales an image proportionally 2x

  • « Imagick::listRegistry
  • Imagick::mapImage »
  • PHP Manual
  • Imagick
  • Scales an image proportionally 2x

Imagick::magnifyImage

(PECL imagick 2.0.0)

Imagick::magnifyImage — Scales an image proportionally 2x

Description

Imagick::magnifyImage ( void ) : bool

Is a convenience method that scales an image proportionally to twice its original size.

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();
}

?>


Replaces the colors of an image with the closest color from a reference image

  • « Imagick::magnifyImage
  • Imagick::matteFloodfillImage »
  • PHP Manual
  • Imagick
  • Replaces the colors of an image with the closest color from a reference image

Imagick::mapImage

(PECL imagick 2.0.0)

Imagick::mapImage — Replaces the colors of an image with the closest color from a reference image

Description

Imagick::mapImage ( Imagick $map , bool $dither ) : bool

Parameters

map

dither

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.


Changes the transparency value of a color

  • « Imagick::mapImage
  • Imagick::medianFilterImage »
  • PHP Manual
  • Imagick
  • Changes the transparency value of a color

Imagick::matteFloodfillImage

(PECL imagick 2.0.0)

Imagick::matteFloodfillImage — Changes the transparency value of a color

Description

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
2.1.0 | Now allows a string representing the color as the third parameter. Previous versions allow only an ImagickPixel object.


Applies a digital filter

  • « Imagick::matteFloodfillImage
  • Imagick::mergeImageLayers »
  • PHP Manual
  • Imagick
  • Applies a digital filter

Imagick::medianFilterImage

(PECL imagick 2.0.0)

Imagick::medianFilterImage — Applies a digital filter

Description

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();
}

?>


Merges image layers

  • « Imagick::medianFilterImage
  • Imagick::minifyImage »
  • PHP Manual
  • Imagick
  • Merges image layers

Imagick::mergeImageLayers

(PECL imagick 2.1.0)

Imagick::mergeImageLayers — Merges image layers

Description

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.

See Also

  • Imagick::flattenImages() - Merges a sequence of images

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();
}

?>


Scales an image proportionally to half its size

  • « Imagick::mergeImageLayers
  • Imagick::modulateImage »
  • PHP Manual
  • Imagick
  • Scales an image proportionally to half its size

Imagick::minifyImage

(PECL imagick 2.0.0)

Imagick::minifyImage — Scales an image proportionally to half its size

Description

Imagick::minifyImage ( void ) : bool

Is a convenience method that scales an image proportionally to one-half its original size

Return Values

Returns TRUE on success.


Control the brightness, saturation, and hue

  • « Imagick::minifyImage
  • Imagick::montageImage »
  • PHP Manual
  • Imagick
  • Control the brightness, saturation, and hue

Imagick::modulateImage

(PECL imagick 2.0.0)

Imagick::modulateImage — Control the brightness, saturation, and hue

Description

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();
}

?>


Creates a composite image

  • « Imagick::modulateImage
  • Imagick::morphImages »
  • PHP Manual
  • Imagick
  • Creates a composite image

Imagick::montageImage

(PECL imagick 2.0.0)

Imagick::montageImage — Creates a composite image

Description

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

Returns TRUE on success.


Method morphs a set of images

  • « Imagick::montageImage
  • Imagick::morphology »
  • PHP Manual
  • Imagick
  • Method morphs a set of images

Imagick::morphImages

(PECL imagick 2.0.0)

Imagick::morphImages — Method morphs a set of images

Description

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.


Description

  • « Imagick::morphImages
  • Imagick::mosaicImages »
  • PHP Manual
  • Imagick
  • Description

Imagick::morphology

(No version information available, might only be in Git)

Imagick::morphology — Description

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 functon to get an image silhouette Imagick::morphology()

<?php
    private 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;
    }

?>


Forms a mosaic from images

  • « Imagick::morphology
  • Imagick::motionBlurImage »
  • PHP Manual
  • Imagick
  • Forms a mosaic from images

Imagick::mosaicImages

(PECL imagick 2.0.0)

Imagick::mosaicImages — Forms a mosaic from images

Description

Imagick::mosaicImages ( void ) : 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.

Return Values

Returns TRUE on success.


Simulates motion blur

  • « Imagick::mosaicImages
  • Imagick::negateImage »
  • PHP Manual
  • Imagick
  • Simulates motion blur

Imagick::motionBlurImage

(PECL imagick 2.0.0)

Imagick::motionBlurImage — Simulates motion blur

Description

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();
}

?>


Negates the colors in the reference image

  • « Imagick::motionBlurImage
  • Imagick::newImage »
  • PHP Manual
  • Imagick
  • Negates the colors in the reference image

Imagick::negateImage

(PECL imagick 2.0.0)

Imagick::negateImage — Negates the colors in the reference image

Description

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();
}

?>


Creates a new image

  • « Imagick::negateImage
  • Imagick::newPseudoImage »
  • PHP Manual
  • Imagick
  • Creates a new image

Imagick::newImage

(PECL imagick 2.0.0)

Imagick::newImage — Creates a new image

Description

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
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;

?>


Creates a new image

  • « Imagick::newImage
  • Imagick::nextImage »
  • PHP Manual
  • Imagick
  • Creates a new image

Imagick::newPseudoImage

(PECL imagick 2.0.0)

Imagick::newPseudoImage — Creates a new image

Description

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");

?>


Moves to the next image

  • « Imagick::newPseudoImage
  • Imagick::normalizeImage »
  • PHP Manual
  • Imagick
  • Moves to the next image

Imagick::nextImage

(PECL imagick 2.0.0)

Imagick::nextImage — Moves to the next image

Description

Imagick::nextImage ( void ) : bool

Associates the next image in the image list with an Imagick object.

Return Values

Returns TRUE on success.


Enhances the contrast of a color image

  • « Imagick::nextImage
  • Imagick::oilPaintImage »
  • PHP Manual
  • Imagick
  • Enhances the contrast of a color image

Imagick::normalizeImage

(PECL imagick 2.0.0)

Imagick::normalizeImage — Enhances the contrast of a color image

Description

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();
}

?>


Simulates an oil painting

  • « Imagick::normalizeImage
  • Imagick::opaquePaintImage »
  • PHP Manual
  • Imagick
  • Simulates an oil painting

Imagick::oilPaintImage

(PECL imagick 2.0.0)

Imagick::oilPaintImage — Simulates an oil painting

Description

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();
}

?>


Changes the color value of any pixel that matches target

  • « Imagick::oilPaintImage
  • Imagick::optimizeImageLayers »
  • PHP Manual
  • Imagick
  • Changes the color value of any pixel that matches target

Imagick::opaquePaintImage

(No version information available, might only be in Git)

Imagick::opaquePaintImage — Changes the color value of any pixel that matches target

Description

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.


Removes repeated portions of images to optimize

  • « Imagick::opaquePaintImage
  • Imagick::orderedPosterizeImage »
  • PHP Manual
  • Imagick
  • Removes repeated portions of images to optimize

Imagick::optimizeImageLayers

(PECL imagick 2.0.0)

Imagick::optimizeImageLayers — Removes repeated portions of images to optimize

Description

Imagick::optimizeImageLayers ( void ) : 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.

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


Performs an ordered dither

  • « Imagick::optimizeImageLayers
  • Imagick::paintFloodfillImage »
  • PHP Manual
  • Imagick
  • Performs an ordered dither

Imagick::orderedPosterizeImage

(PECL imagick 2.2.2)

Imagick::orderedPosterizeImage — Performs an ordered dither

Description

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');

?>


Changes the color value of any pixel that matches target

  • « Imagick::orderedPosterizeImage
  • Imagick::paintOpaqueImage »
  • PHP Manual
  • Imagick
  • Changes the color value of any pixel that matches target

Imagick::paintFloodfillImage

(PECL imagick 2.1.0)

Imagick::paintFloodfillImage — Changes the color value of any pixel that matches target

Description

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.


Change any pixel that matches color

  • « Imagick::paintFloodfillImage
  • Imagick::paintTransparentImage »
  • PHP Manual
  • Imagick
  • Change any pixel that matches color

Imagick::paintOpaqueImage

(PECL imagick 2.0.0)

Imagick::paintOpaqueImage — Change any pixel that matches color

Description

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
2.1.0 | Now allows a string representing the color as first and second parameter. Previous versions allow only an ImagickPixel object.


Changes any pixel that matches color with the color defined by fill

  • « Imagick::paintOpaqueImage
  • Imagick::pingImage »
  • PHP Manual
  • Imagick
  • Changes any pixel that matches color with the color defined by fill

Imagick::paintTransparentImage

(PECL imagick 2.0.0)

Imagick::paintTransparentImage — Changes any pixel that matches color with the color defined by fill

Description

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
2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object.


Fetch basic attributes about the image

  • « Imagick::paintTransparentImage
  • Imagick::pingImageBlob »
  • PHP Manual
  • Imagick
  • Fetch basic attributes about the image

Imagick::pingImage

(PECL imagick 2.0.0)

Imagick::pingImage — Fetch basic attributes about the image

Description

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.


Quickly fetch attributes

  • « Imagick::pingImage
  • Imagick::pingImageFile »
  • PHP Manual
  • Imagick
  • Quickly fetch attributes

Imagick::pingImageBlob

(PECL imagick 2.0.0)

Imagick::pingImageBlob — Quickly fetch attributes

Description

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


Get basic image attributes in a lightweight manner

  • « Imagick::pingImageBlob
  • Imagick::polaroidImage »
  • PHP Manual
  • Imagick
  • Get basic image attributes in a lightweight manner

Imagick::pingImageFile

(PECL imagick 2.0.0)

Imagick::pingImageFile — Get basic image attributes in a lightweight manner

Description

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


Simulates a Polaroid picture

  • « Imagick::pingImageFile
  • Imagick::posterizeImage »
  • PHP Manual
  • Imagick
  • Simulates a Polaroid picture

Imagick::polaroidImage

(PECL imagick 2.0.0)

Imagick::polaroidImage — Simulates a Polaroid picture

Description

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;

?>


Reduces the image to a limited number of color level

  • « Imagick::polaroidImage
  • Imagick::previewImages »
  • PHP Manual
  • Imagick
  • Reduces the image to a limited number of color level

Imagick::posterizeImage

(PECL imagick 2.0.0)

Imagick::posterizeImage — Reduces the image to a limited number of color level

Description

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);

?>


Quickly pin-point appropriate parameters for image processing

  • « Imagick::posterizeImage
  • Imagick::previousImage »
  • PHP Manual
  • Imagick
  • Quickly pin-point appropriate parameters for image processing

Imagick::previewImages

(PECL imagick 2.0.0)

Imagick::previewImages — Quickly pin-point appropriate parameters for image processing

Description

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.


Move to the previous image in the object

  • « Imagick::previewImages
  • Imagick::profileImage »
  • PHP Manual
  • Imagick
  • Move to the previous image in the object

Imagick::previousImage

(PECL imagick 2.0.0)

Imagick::previousImage — Move to the previous image in the object

Description

Imagick::previousImage ( void ) : bool

Assocates the previous image in an image list with the Imagick object.

Return Values

Returns TRUE on success.


Adds or removes a profile from an image

  • « Imagick::previousImage
  • Imagick::quantizeImage »
  • PHP Manual
  • Imagick
  • Adds or removes a profile from an image

Imagick::profileImage

(PECL imagick 2.0.0)

Imagick::profileImage — Adds or removes a profile from an image

Description

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 otherwise added. Use a name of '*' and a profile of NULL to remove all profiles from the image.

Parameters

name

profile

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.


Analyzes the colors within a reference image

  • « Imagick::profileImage
  • Imagick::quantizeImages »
  • PHP Manual
  • Imagick
  • Analyzes the colors within a reference image

Imagick::quantizeImage

(PECL imagick 2.0.0)

Imagick::quantizeImage — Analyzes the colors within a reference image

Description

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();
}

?>


Analyzes the colors within a sequence of images

  • « Imagick::quantizeImage
  • Imagick::queryFontMetrics »
  • PHP Manual
  • Imagick
  • Analyzes the colors within a sequence of images

Imagick::quantizeImages

(PECL imagick 2.0.0)

Imagick::quantizeImages — Analyzes the colors within a sequence of images

Description

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.


Returns an array representing the font metrics

  • « Imagick::quantizeImages
  • Imagick::queryFonts »
  • PHP Manual
  • Imagick
  • Returns an array representing the font metrics

Imagick::queryFontMetrics

(PECL imagick 2.0.0)

Imagick::queryFontMetrics — Returns an array representing the font metrics

Description

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!"));
?>


Returns the configured fonts

  • « Imagick::queryFontMetrics
  • Imagick::queryFormats »
  • PHP Manual
  • Imagick
  • Returns the configured fonts

Imagick::queryFonts

(PECL imagick 2.0.0)

Imagick::queryFonts — Returns the configured fonts

Description

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;

?>


Returns formats supported by Imagick

  • « Imagick::queryFonts
  • Imagick::radialBlurImage »
  • PHP Manual
  • Imagick
  • Returns formats supported by Imagick

Imagick::queryFormats

(PECL imagick 2.0.0)

Imagick::queryFormats — Returns formats supported by Imagick

Description

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;
    }

?>


Radial blurs an image

  • « Imagick::queryFormats
  • Imagick::raiseImage »
  • PHP Manual
  • Imagick
  • Radial blurs an image

Imagick::radialBlurImage

(PECL imagick 2.0.0)

Imagick::radialBlurImage — Radial blurs an image

Description

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();
}

?>


Creates a simulated 3d button-like effect

  • « Imagick::radialBlurImage
  • Imagick::randomThresholdImage »
  • PHP Manual
  • Imagick
  • Creates a simulated 3d button-like effect

Imagick::raiseImage

(PECL imagick 2.0.0)

Imagick::raiseImage — Creates a simulated 3d button-like effect

Description

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();
}

?>


Creates a high-contrast, two-color image

  • « Imagick::raiseImage
  • Imagick::readImage »
  • PHP Manual
  • Imagick
  • Creates a high-contrast, two-color image

Imagick::randomThresholdImage

(PECL imagick 2.0.0)

Imagick::randomThresholdImage — Creates a high-contrast, two-color image

Description

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();
}

?>


Reads image from filename

  • « Imagick::randomThresholdImage
  • Imagick::readImageBlob »
  • PHP Manual
  • Imagick
  • Reads image from filename

Imagick::readImage

(PECL imagick 0.9.0-0.9.9)

Imagick::readImage — Reads image from filename

Description

Imagick::readImage ( string $filename ) : bool

Reads image from filename

Parameters

filename

Return Values

Returns TRUE on success.


Reads image from a binary string

  • « Imagick::readImage
  • Imagick::readImageFile »
  • PHP Manual
  • Imagick
  • Reads image from a binary string

Imagick::readImageBlob

(PECL imagick 2.0.0)

Imagick::readImageBlob — Reads image from a binary string

Description

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;
}

?>


Reads image from open filehandle

  • « Imagick::readImageBlob
  • Imagick::readimages »
  • PHP Manual
  • Imagick
  • Reads image from open filehandle

Imagick::readImageFile

(PECL imagick 2.0.0)

Imagick::readImageFile — Reads image from open filehandle

Description

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.


Description

  • « Imagick::readImageFile
  • Imagick::recolorImage »
  • PHP Manual
  • Imagick
  • Description

Imagick::readimages

(No version information available, might only be in Git)

Imagick::readimages — Description

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.


Recolors image

  • « Imagick::readimages
  • Imagick::reduceNoiseImage »
  • PHP Manual
  • Imagick
  • Recolors image

Imagick::recolorImage

(No version information available, might only be in Git)

Imagick::recolorImage — Recolors image

Description

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.

See Also

  • Imagick::displayImage() - Displays an image

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();
}

?>


Smooths the contours of an image

  • « Imagick::recolorImage
  • Imagick::remapImage »
  • PHP Manual
  • Imagick
  • Smooths the contours of an image

Imagick::reduceNoiseImage

(PECL imagick 2.0.0)

Imagick::reduceNoiseImage — Smooths the contours of an image

Description

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();
}

?>


Remaps image colors

  • « Imagick::reduceNoiseImage
  • Imagick::removeImage »
  • PHP Manual
  • Imagick
  • Remaps image colors

Imagick::remapImage

(No version information available, might only be in Git)

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.


Removes an image from the image list

  • « Imagick::remapImage
  • Imagick::removeImageProfile »
  • PHP Manual
  • Imagick
  • Removes an image from the image list

Imagick::removeImage

(PECL imagick 2.0.0)

Imagick::removeImage — Removes an image from the image list

Description

Imagick::removeImage ( void ) : bool

Removes an image from the image list.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.


Removes the named image profile and returns it

  • « Imagick::removeImage
  • Imagick::render »
  • PHP Manual
  • Imagick
  • Removes the named image profile and returns it

Imagick::removeImageProfile

(PECL imagick 2.0.0)

Imagick::removeImageProfile — Removes the named image profile and returns it

Description

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.


Renders all preceding drawing commands

  • « Imagick::removeImageProfile
  • Imagick::resampleImage »
  • PHP Manual
  • Imagick
  • Renders all preceding drawing commands

Imagick::render

(PECL imagick 2.0.0)

Imagick::render — Renders all preceding drawing commands

Description

Imagick::render ( void ) : bool

Renders all preceding drawing commands.

Return Values

Returns TRUE on success.


Resample image to desired resolution

  • « Imagick::render
  • Imagick::resetImagePage »
  • PHP Manual
  • Imagick
  • Resample image to desired resolution

Imagick::resampleImage

(PECL imagick 2.0.0)

Imagick::resampleImage — Resample image to desired resolution

Description

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();
}

?>


Reset image page

  • « Imagick::resampleImage
  • Imagick::resizeImage »
  • PHP Manual
  • Imagick
  • Reset image page

Imagick::resetImagePage

(No version information available, might only be in Git)

Imagick::resetImagePage — Reset image page

Description

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.


Scales an image

  • « Imagick::resetImagePage
  • Imagick::rollImage »
  • PHP Manual
  • Imagick
  • Scales an image

Imagick::resizeImage

(PECL imagick 2.0.0)

Imagick::resizeImage — Scales an image

Description

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
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 &gt; 1 is blurry, &lt; 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();
}

?>


Offsets an image

  • « Imagick::resizeImage
  • Imagick::rotateImage »
  • PHP Manual
  • Imagick
  • Offsets an image

Imagick::rollImage

(PECL imagick 2.0.0)

Imagick::rollImage — Offsets an image

Description

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();
}

?>


Rotates an image

  • « Imagick::rollImage
  • Imagick::rotationalBlurImage »
  • PHP Manual
  • Imagick
  • Rotates an image

Imagick::rotateImage

(PECL imagick 2.0.0)

Imagick::rotateImage — Rotates an image

Description

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
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();
}

?>


Description

  • « Imagick::rotateImage
  • Imagick::roundCorners »
  • PHP Manual
  • Imagick
  • Description

Imagick::rotationalBlurImage

(No version information available, might only be in Git)

Imagick::rotationalBlurImage — Description

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();
}

?>


Rounds image corners

  • « Imagick::rotationalBlurImage
  • Imagick::sampleImage »
  • PHP Manual
  • Imagick
  • Rounds image corners

Imagick::roundCorners

(PECL imagick 2.0.0)

Imagick::roundCorners — Rounds image corners

Description

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.

Parameters

x_rounding

x rounding

y_rounding

y rounding

stroke_width

stroke width

displace

image displace

size_correction

size correction

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");
?>

Return Values

Returns TRUE on success.


Scales an image with pixel sampling

  • « Imagick::roundCorners
  • Imagick::scaleImage »
  • PHP Manual
  • Imagick
  • Scales an image with pixel sampling

Imagick::sampleImage

(PECL imagick 2.0.0)

Imagick::sampleImage — Scales an image with pixel sampling

Description

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.


Scales the size of an image

  • « Imagick::sampleImage
  • Imagick::segmentImage »
  • PHP Manual
  • Imagick
  • Scales the size of an image

Imagick::scaleImage

(PECL imagick 2.0.0)

Imagick::scaleImage — Scales the size of an image

Description

Imagick::scaleImage ( int $cols , 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

cols

rows

bestfit

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.

Changelog

Version | Description
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();
}

?>


Segments an image

  • « Imagick::scaleImage
  • Imagick::selectiveBlurImage »
  • PHP Manual
  • Imagick
  • Segments an image

Imagick::segmentImage

(No version information available, might only be in Git)

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);

?>


Description

  • « Imagick::segmentImage
  • Imagick::separateImageChannel »
  • PHP Manual
  • Imagick
  • Description

Imagick::selectiveBlurImage

(No version information available, might only be in Git)

Imagick::selectiveBlurImage — Description

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();
}

?>


Separates a channel from the image

  • « Imagick::selectiveBlurImage
  • Imagick::sepiaToneImage »
  • PHP Manual
  • Imagick
  • Separates a channel from the image

Imagick::separateImageChannel

(PECL imagick 2.0.0)

Imagick::separateImageChannel — Separates a channel from the image

Description

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);

?>


Sepia tones an image

  • « Imagick::separateImageChannel
  • Imagick::setBackgroundColor »
  • PHP Manual
  • Imagick
  • Sepia tones an image

Imagick::sepiaToneImage

(PECL imagick 2.0.0)

Imagick::sepiaToneImage — Sepia tones an image

Description

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();
}

?>


Sets the object's default background color

  • « Imagick::sepiaToneImage
  • Imagick::setColorspace »
  • PHP Manual
  • Imagick
  • Sets the object's default background color

Imagick::setBackgroundColor

(PECL imagick 2.0.0)

Imagick::setBackgroundColor — Sets the object's default background color

Description

Imagick::setBackgroundColor ( mixed $background ) : bool

Sets the object's default background color.

Parameters

background

Return Values

Returns TRUE on success.

Changelog

Version | Description
2.1.0 | Now allows a string representing the color as a parameter. Previous versions allow only an ImagickPixel object.


Set colorspace

  • « Imagick::setBackgroundColor
  • Imagick::setCompression »
  • PHP Manual
  • Imagick
  • Set colorspace

Imagick::setColorspace

(No version information available, might only be in Git)

Imagick::setColorspace — Set colorspace

Description

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.


Sets the object's default compression type

  • « Imagick::setColorspace
  • Imagick::setCompressionQuality »
  • PHP Manual
  • Imagick
  • Sets the object's default compression type

Imagick::setCompression

(PECL imagick 2.0.0)

Imagick::setCompression — Sets the object's default compression type

Description

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.


Sets the object's default compression quality

  • « Imagick::setCompression
  • Imagick::setFilename »
  • PHP Manual
  • Imagick
  • Sets the object's default compression quality

Imagick::setCompressionQuality

(PECL imagick 0.9.10-0.9.9)

Imagick::setCompressionQuality — Sets the object's default compression quality

Description

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 integer 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();
}

?>


Sets the filename before you read or write the image

  • « Imagick::setCompressionQuality
  • Imagick::setFirstIterator »
  • PHP Manual
  • Imagick
  • Sets the filename before you read or write the image

Imagick::setFilename

(PECL imagick 2.0.0)

Imagick::setFilename — Sets the filename before you read or write the image

Description

Imagick::setFilename ( string $filename ) : bool

Sets the filename before you read or write an image file.

Parameters

filename

Return Values

Returns TRUE on success.


Sets the Imagick iterator to the first image

  • « Imagick::setFilename
  • Imagick::setFont »
  • PHP Manual
  • Imagick
  • Sets the Imagick iterator to the first image

Imagick::setFirstIterator

(PECL imagick 2.0.0)

Imagick::setFirstIterator — Sets the Imagick iterator to the first image

Description

Imagick::setFirstIterator ( void ) : bool

Sets the Imagick iterator to the first image.

Return Values

Returns TRUE on success.


Sets font

  • « Imagick::setFirstIterator
  • Imagick::setFormat »
  • PHP Manual
  • Imagick
  • Sets font

Imagick::setFont

(PECL imagick 2.1.0)

Imagick::setFont — Sets font

Description

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.

See Also

  • Imagick::getFont() - Gets font
  • ImagickDraw::setFont() - Sets the fully-specified font to use when annotating with text
  • ImagickDraw::getFont() - Returns the font

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 */
?>


Sets the format of the Imagick object

  • « Imagick::setFont
  • Imagick::setGravity »
  • PHP Manual
  • Imagick
  • Sets the format of the Imagick object

Imagick::setFormat

(PECL imagick 2.0.0)

Imagick::setFormat — Sets the format of the Imagick object

Description

Imagick::setFormat ( string $format ) : bool

Sets the format of the Imagick object.

Parameters

format

Return Values

Returns TRUE on success.


Sets the gravity

  • « Imagick::setFormat
  • Imagick::setImage »
  • PHP Manual
  • Imagick
  • Sets the gravity

Imagick::setGravity

(No version information available, might only be in Git)

Imagick::setGravity — Sets the gravity

Description

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.


Replaces image in the object

  • « Imagick::setGravity
  • Imagick::setImageAlphaChannel »
  • PHP Manual
  • Imagick
  • Replaces image in the object

Imagick::setImage

(PECL imagick 2.0.0)

Imagick::setImage — Replaces image in the object

Description

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;

?>


Sets image alpha channel

  • « Imagick::setImage
  • Imagick::setImageArtifact »
  • PHP Manual
  • Imagick
  • Sets image alpha channel

Imagick::setImageAlphaChannel

(No version information available, might only be in Git)

Imagick::setImageAlphaChannel — Sets image alpha channel

Description

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


Set image artifact

  • « Imagick::setImageAlphaChannel
  • Imagick::setImageAttribute »
  • PHP Manual
  • Imagick
  • Set image artifact

Imagick::setImageArtifact

(No version information available, might only be in Git)

Imagick::setImageArtifact — Set image artifact

Description

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.

See Also

  • Imagick::getImageArtifact() - Get image artifact
  • Imagick::deleteImageArtifact() - Delete image artifact

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();
}

?>


Description

  • « Imagick::setImageArtifact
  • Imagick::setImageBackgroundColor »
  • PHP Manual
  • Imagick
  • Description

Imagick::setImageAttribute

(No version information available, might only be in Git)

Imagick::setImageAttribute — Description

Description

public Imagick::setImageAttribute ( string $key , string $value ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

key

value

Return Values

Returns TRUE on success.


Sets the image background color

  • « Imagick::setImageAttribute
  • Imagick::setImageBias »
  • PHP Manual
  • Imagick
  • Sets the image background color

Imagick::setImageBackgroundColor

(PECL imagick 2.0.0)

Imagick::setImageBackgroundColor — Sets the image background color

Description

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
2.1.0 | Now allows a string representing the color as the parameter. Previous versions allow only an ImagickPixel object.


Sets the image bias for any method that convolves an image

  • « Imagick::setImageBackgroundColor
  • Imagick::setImageBiasQuantum »
  • PHP Manual
  • Imagick
  • Sets the image bias for any method that convolves an image

Imagick::setImageBias

(PECL imagick 2.0.0)

Imagick::setImageBias — Sets the image bias for any method that convolves an image

Description

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();
}

?>


Description

  • « Imagick::setImageBias
  • Imagick::setImageBluePrimary »
  • PHP Manual
  • Imagick
  • Description

Imagick::setImageBiasQuantum

(No version information available, might only be in Git)

Imagick::setImageBiasQuantum — Description

Description

public Imagick::setImageBiasQuantum ( string $bias ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

bias

Return Values


Sets the image chromaticity blue primary point

  • « Imagick::setImageBiasQuantum
  • Imagick::setImageBorderColor »
  • PHP Manual
  • Imagick
  • Sets the image chromaticity blue primary point

Imagick::setImageBluePrimary

(PECL imagick 2.0.0)

Imagick::setImageBluePrimary — Sets the image chromaticity blue primary point

Description

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.


Sets the image border color

  • « Imagick::setImageBluePrimary
  • Imagick::setImageChannelDepth »
  • PHP Manual
  • Imagick
  • Sets the image border color

Imagick::setImageBorderColor

(PECL imagick 2.0.0)

Imagick::setImageBorderColor — Sets the image border color

Description

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
2.1.0 | Now allows a string representing the color as a parameter. Previous versions allow only an ImagickPixel object.


Sets the depth of a particular image channel

  • « Imagick::setImageBorderColor
  • Imagick::setImageClipMask »
  • PHP Manual
  • Imagick
  • Sets the depth of a particular image channel

Imagick::setImageChannelDepth

(PECL imagick 2.0.0)

Imagick::setImageChannelDepth — Sets the depth of a particular image channel

Description

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.


Sets image clip mask

  • « Imagick::setImageChannelDepth
  • Imagick::setImageColormapColor »
  • PHP Manual
  • Imagick
  • Sets image clip mask

Imagick::setImageClipMask

(No version information available, might only be in Git)

Imagick::setImageClipMask — Sets image clip mask

Description

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();

}

?>


Sets the color of the specified colormap index

  • « Imagick::setImageClipMask
  • Imagick::setImageColorspace »
  • PHP Manual
  • Imagick
  • Sets the color of the specified colormap index

Imagick::setImageColormapColor

(PECL imagick 2.0.0)

Imagick::setImageColormapColor — Sets the color of the specified colormap index

Description

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.


Sets the image colorspace

  • « Imagick::setImageColormapColor
  • Imagick::setImageCompose »
  • PHP Manual
  • Imagick
  • Sets the image colorspace

Imagick::setImageColorspace

(PECL imagick 2.0.0)

Imagick::setImageColorspace — Sets the image colorspace

Description

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.


Sets the image composite operator

  • « Imagick::setImageColorspace
  • Imagick::setImageCompression »
  • PHP Manual
  • Imagick
  • Sets the image composite operator

Imagick::setImageCompose

(PECL imagick 2.0.0)

Imagick::setImageCompose — Sets the image composite operator

Description

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.


Sets the image compression

  • « Imagick::setImageCompose
  • Imagick::setImageCompressionQuality »
  • PHP Manual
  • Imagick
  • Sets the image compression

Imagick::setImageCompression

(PECL imagick 2.0.0)

Imagick::setImageCompression — Sets the image compression

Description

Imagick::setImageCompression ( int $compression ) : bool

Parameters

compression

One of the COMPRESSION constants

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.


Sets the image compression quality

  • « Imagick::setImageCompression
  • Imagick::setImageDelay »
  • PHP Manual
  • Imagick
  • Sets the image compression quality

Imagick::setImageCompressionQuality

(No version information available, might only be in Git)

Imagick::setImageCompressionQuality — Sets the image compression quality

Description

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();
}

?>


Sets the image delay

  • « Imagick::setImageCompressionQuality
  • Imagick::setImageDepth »
  • PHP Manual
  • Imagick
  • Sets the image delay

Imagick::setImageDelay

(PECL imagick 2.0.0)

Imagick::setImageDelay — Sets the image delay

Description

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);

?>


Sets the image depth

  • « Imagick::setImageDelay
  • Imagick::setImageDispose »
  • PHP Manual
  • Imagick
  • Sets the image depth

Imagick::setImageDepth

(PECL imagick 2.0.0)

Imagick::setImageDepth — Sets the image depth

Description

Imagick::setImageDepth ( int $depth ) : bool

Sets the image depth.

Parameters

depth

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.


Sets the image disposal method

  • « Imagick::setImageDepth
  • Imagick::setImageExtent »
  • PHP Manual
  • Imagick
  • Sets the image disposal method

Imagick::setImageDispose

(PECL imagick 2.0.0)

Imagick::setImageDispose — Sets the image disposal method

Description

Imagick::setImageDispose ( int $dispose ) : bool

Sets the image disposal method.

Parameters

dispose

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.


Sets the image size

  • « Imagick::setImageDispose
  • Imagick::setImageFilename »
  • PHP Manual
  • Imagick
  • Sets the image size

Imagick::setImageExtent

(PECL imagick 2.0.0)

Imagick::setImageExtent — Sets the image size

Description

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.


Sets the filename of a particular image

  • « Imagick::setImageExtent
  • Imagick::setImageFormat »
  • PHP Manual
  • Imagick
  • Sets the filename of a particular image

Imagick::setImageFilename

(PECL imagick 2.0.0)

Imagick::setImageFilename — Sets the filename of a particular image

Description

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.


Sets the format of a particular image

  • « Imagick::setImageFilename
  • Imagick::setImageGamma »
  • PHP Manual
  • Imagick
  • Sets the format of a particular image

Imagick::setImageFormat

(PECL imagick 2.0.0)

Imagick::setImageFormat — Sets the format of a particular image

Description

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.


Sets the image gamma

  • « Imagick::setImageFormat
  • Imagick::setImageGravity »
  • PHP Manual
  • Imagick
  • Sets the image gamma

Imagick::setImageGamma

(PECL imagick 2.0.0)

Imagick::setImageGamma — Sets the image gamma

Description

Imagick::setImageGamma ( float $gamma ) : bool

Sets the image gamma.

Parameters

gamma

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.


Sets the image gravity

  • « Imagick::setImageGamma
  • Imagick::setImageGreenPrimary »
  • PHP Manual
  • Imagick
  • Sets the image gravity

Imagick::setImageGravity

(No version information available, might only be in Git)

Imagick::setImageGravity — Sets the image gravity

Description

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.


Sets the image chromaticity green primary point

  • « Imagick::setImageGravity
  • Imagick::setImageIndex »
  • PHP Manual
  • Imagick
  • Sets the image chromaticity green primary point

Imagick::setImageGreenPrimary

(PECL imagick 2.0.0)

Imagick::setImageGreenPrimary — Sets the image chromaticity green primary point

Description

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.


Set the iterator position

  • « Imagick::setImageGreenPrimary
  • Imagick::setImageInterlaceScheme »
  • PHP Manual
  • Imagick
  • Set the iterator position

Imagick::setImageIndex

(PECL imagick 2.0.0)

Imagick::setImageIndex — Set the iterator position

Description

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.


Sets the image compression

  • « Imagick::setImageIndex
  • Imagick::setImageInterpolateMethod »
  • PHP Manual
  • Imagick
  • Sets the image compression

Imagick::setImageInterlaceScheme

(PECL imagick 2.0.0)

Imagick::setImageInterlaceScheme — Sets the image compression

Description

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.


Sets the image interpolate pixel method

  • « Imagick::setImageInterlaceScheme
  • Imagick::setImageIterations »
  • PHP Manual
  • Imagick
  • Sets the image interpolate pixel method

Imagick::setImageInterpolateMethod

(PECL imagick 2.0.0)

Imagick::setImageInterpolateMethod — Sets the image interpolate pixel method

Description

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.


Sets the image iterations

  • « Imagick::setImageInterpolateMethod
  • Imagick::setImageMatte »
  • PHP Manual
  • Imagick
  • Sets the image iterations

Imagick::setImageIterations

(PECL imagick 2.0.0)

Imagick::setImageIterations — Sets the image iterations

Description

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);

?>


Sets the image matte channel

  • « Imagick::setImageIterations
  • Imagick::setImageMatteColor »
  • PHP Manual
  • Imagick
  • Sets the image matte channel

Imagick::setImageMatte

(PECL imagick 2.0.0)

Imagick::setImageMatte — Sets the image matte channel

Description

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.


Sets the image matte color

  • « Imagick::setImageMatte
  • Imagick::setImageOpacity »
  • PHP Manual
  • Imagick
  • Sets the image matte color

Imagick::setImageMatteColor

(PECL imagick 2.0.0)

Imagick::setImageMatteColor — Sets the image matte color

Description

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
2.1.0 | Now allows a string representing the color as the parameter. Previous versions allow only an ImagickPixel object.


Sets the image opacity level

  • « Imagick::setImageMatteColor
  • Imagick::setImageOrientation »
  • PHP Manual
  • Imagick
  • Sets the image opacity level

Imagick::setImageOpacity

(PECL imagick 2.0.0)

Imagick::setImageOpacity — Sets the image opacity level

Description

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;

?>


Sets the image orientation

  • « Imagick::setImageOpacity
  • Imagick::setImagePage »
  • PHP Manual
  • Imagick
  • Sets the image orientation

Imagick::setImageOrientation

(PECL imagick 2.0.0)

Imagick::setImageOrientation — Sets the image orientation

Description

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();
}

?>


Sets the page geometry of the image

  • « Imagick::setImageOrientation
  • Imagick::setImageProfile »
  • PHP Manual
  • Imagick
  • Sets the page geometry of the image

Imagick::setImagePage

(PECL imagick 2.0.0)

Imagick::setImagePage — Sets the page geometry of the image

Description

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.


Adds a named profile to the Imagick object

  • « Imagick::setImagePage
  • Imagick::setImageProperty »
  • PHP Manual
  • Imagick
  • Adds a named profile to the Imagick object

Imagick::setImageProfile

(PECL imagick 2.0.0)

Imagick::setImageProfile — Adds a named profile to the Imagick object

Description

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.


Sets an image property

  • « Imagick::setImageProfile
  • Imagick::setImageRedPrimary »
  • PHP Manual
  • Imagick
  • Sets an image property

Imagick::setImageProperty

(PECL imagick 2.0.0)

Imagick::setImageProperty — Sets an image property

Description

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

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

Return Values

Returns TRUE on success.


Sets the image chromaticity red primary point

  • « Imagick::setImageProperty
  • Imagick::setImageRenderingIntent »
  • PHP Manual
  • Imagick
  • Sets the image chromaticity red primary point

Imagick::setImageRedPrimary

(PECL imagick 2.0.0)

Imagick::setImageRedPrimary — Sets the image chromaticity red primary point

Description

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.


Sets the image rendering intent

  • « Imagick::setImageRedPrimary
  • Imagick::setImageResolution »
  • PHP Manual
  • Imagick
  • Sets the image rendering intent

Imagick::setImageRenderingIntent

(PECL imagick 2.0.0)

Imagick::setImageRenderingIntent — Sets the image rendering intent

Description

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.


Sets the image resolution

  • « Imagick::setImageRenderingIntent
  • Imagick::setImageScene »
  • PHP Manual
  • Imagick
  • Sets the image resolution

Imagick::setImageResolution

(PECL imagick 2.0.0)

Imagick::setImageResolution — Sets the image resolution

Description

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();
}

?>


Sets the image scene

  • « Imagick::setImageResolution
  • Imagick::setImageTicksPerSecond »
  • PHP Manual
  • Imagick
  • Sets the image scene

Imagick::setImageScene

(PECL imagick 2.0.0)

Imagick::setImageScene — Sets the image scene

Description

Imagick::setImageScene ( int $scene ) : bool

Sets the image scene.

Parameters

scene

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.


Sets the image ticks-per-second

  • « Imagick::setImageScene
  • Imagick::setImageType »
  • PHP Manual
  • Imagick
  • Sets the image ticks-per-second

Imagick::setImageTicksPerSecond

(PECL imagick 2.0.0)

Imagick::setImageTicksPerSecond — Sets the image ticks-per-second

Description

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);

?>


Sets the image type

  • « Imagick::setImageTicksPerSecond
  • Imagick::setImageUnits »
  • PHP Manual
  • Imagick
  • Sets the image type

Imagick::setImageType

(PECL imagick 2.0.0)

Imagick::setImageType — Sets the image type

Description

Imagick::setImageType ( int $image_type ) : bool

Sets the image type.

Parameters

image_type

Return Values

Returns TRUE on success.


Sets the image units of resolution

  • « Imagick::setImageType
  • Imagick::setImageVirtualPixelMethod »
  • PHP Manual
  • Imagick
  • Sets the image units of resolution

Imagick::setImageUnits

(PECL imagick 2.0.0)

Imagick::setImageUnits — Sets the image units of resolution

Description

Imagick::setImageUnits ( int $units ) : bool

Sets the image units of resolution.

Parameters

units

Return Values

Returns TRUE on success.


Sets the image virtual pixel method

  • « Imagick::setImageUnits
  • Imagick::setImageWhitePoint »
  • PHP Manual
  • Imagick
  • Sets the image virtual pixel method

Imagick::setImageVirtualPixelMethod

(PECL imagick 2.0.0)

Imagick::setImageVirtualPixelMethod — Sets the image virtual pixel method

Description

Imagick::setImageVirtualPixelMethod ( int $method ) : bool

Sets the image virtual pixel method.

Parameters

method

Return Values

Returns TRUE on success.


Sets the image chromaticity white point

  • « Imagick::setImageVirtualPixelMethod
  • Imagick::setInterlaceScheme »
  • PHP Manual
  • Imagick
  • Sets the image chromaticity white point

Imagick::setImageWhitePoint

(PECL imagick 2.0.0)

Imagick::setImageWhitePoint — Sets the image chromaticity white point

Description

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.


Sets the image compression

  • « Imagick::setImageWhitePoint
  • Imagick::setIteratorIndex »
  • PHP Manual
  • Imagick
  • Sets the image compression

Imagick::setInterlaceScheme

(PECL imagick 2.0.0)

Imagick::setInterlaceScheme — Sets the image compression

Description

Imagick::setInterlaceScheme ( int $interlace_scheme ) : bool

Sets the image compression.

Parameters

interlace_scheme

Return Values

Returns TRUE on success.


Set the iterator position

  • « Imagick::setInterlaceScheme
  • Imagick::setLastIterator »
  • PHP Manual
  • Imagick
  • Set the iterator position

Imagick::setIteratorIndex

(PECL imagick 2.0.0)

Imagick::setIteratorIndex — Set the iterator position

Description

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


Sets the Imagick iterator to the last image

  • « Imagick::setIteratorIndex
  • Imagick::setOption »
  • PHP Manual
  • Imagick
  • Sets the Imagick iterator to the last image

Imagick::setLastIterator

(PECL imagick 2.0.1)

Imagick::setLastIterator — Sets the Imagick iterator to the last image

Description

Imagick::setLastIterator ( void ) : bool

Sets the Imagick iterator to the last image.

Return Values

Returns TRUE on success.


Set an option

  • « Imagick::setLastIterator
  • Imagick::setPage »
  • PHP Manual
  • Imagick
  • Set an option

Imagick::setOption

(PECL imagick 2.0.0)

Imagick::setOption — Set an option

Description

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);
        }
    }

?>


Sets the page geometry of the Imagick object

  • « Imagick::setOption
  • Imagick::setPointSize »
  • PHP Manual
  • Imagick
  • Sets the page geometry of the Imagick object

Imagick::setPage

(PECL imagick 2.0.0)

Imagick::setPage — Sets the page geometry of the Imagick object

Description

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.


Sets point size

  • « Imagick::setPage
  • Imagick::setProgressMonitor »
  • PHP Manual
  • Imagick
  • Sets point size

Imagick::setPointSize

(PECL imagick 2.1.0)

Imagick::setPointSize — Sets point size

Description

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.

See Also

  • Imagick::getPointSize() - Gets point size

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 */
?>


Description

  • « Imagick::setPointSize
  • Imagick::setRegistry »
  • PHP Manual
  • Imagick
  • Description

Imagick::setProgressMonitor

(No version information available, might only be in Git)

Imagick::setProgressMonitor — Description

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);
            }
        }

?>


Description

  • « Imagick::setProgressMonitor
  • Imagick::setResolution »
  • PHP Manual
  • Imagick
  • Description

Imagick::setRegistry

(No version information available, might only be in Git)

Imagick::setRegistry — Description

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.


Sets the image resolution

  • « Imagick::setRegistry
  • Imagick::setResourceLimit »
  • PHP Manual
  • Imagick
  • Sets the image resolution

Imagick::setResolution

(PECL imagick 2.0.0)

Imagick::setResolution — Sets the image resolution

Description

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


Sets the limit for a particular resource

  • « Imagick::setResolution
  • Imagick::setSamplingFactors »
  • PHP Manual
  • Imagick
  • Sets the limit for a particular resource

Imagick::setResourceLimit

(PECL imagick 2.0.0)

Imagick::setResourceLimit — Sets the limit for a particular resource

Description

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


Sets the image sampling factors

  • « Imagick::setResourceLimit
  • Imagick::setSize »
  • PHP Manual
  • Imagick
  • Sets the image sampling factors

Imagick::setSamplingFactors

(PECL imagick 2.0.0)

Imagick::setSamplingFactors — Sets the image sampling factors

Description

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();
}

?>


Sets the size of the Imagick object

  • « Imagick::setSamplingFactors
  • Imagick::setSizeOffset »
  • PHP Manual
  • Imagick
  • Sets the size of the Imagick object

Imagick::setSize

(PECL imagick 2.0.0)

Imagick::setSize — Sets the size of the Imagick object

Description

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.


Sets the size and offset of the Imagick object

  • « Imagick::setSize
  • Imagick::setType »
  • PHP Manual
  • Imagick
  • Sets the size and offset of the Imagick object

Imagick::setSizeOffset

(PECL imagick 2.0.0)

Imagick::setSizeOffset — Sets the size and offset of the Imagick object

Description

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.


Sets the image type attribute

  • « Imagick::setSizeOffset
  • Imagick::shadeImage »
  • PHP Manual
  • Imagick
  • Sets the image type attribute

Imagick::setType

(PECL imagick 2.0.0)

Imagick::setType — Sets the image type attribute

Description

Imagick::setType ( int $image_type ) : bool

Sets the image type attribute.

Parameters

image_type

Return Values

Returns TRUE on success.


Creates a 3D effect

  • « Imagick::setType
  • Imagick::shadowImage »
  • PHP Manual
  • Imagick
  • Creates a 3D effect

Imagick::shadeImage

(PECL imagick 2.0.0)

Imagick::shadeImage — Creates a 3D effect

Description

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();
}

?>


Simulates an image shadow

  • « Imagick::shadeImage
  • Imagick::sharpenImage »
  • PHP Manual
  • Imagick
  • Simulates an image shadow

Imagick::shadowImage

(PECL imagick 2.0.0)

Imagick::shadowImage — Simulates an image shadow

Description

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();
}

?>


Sharpens an image

  • « Imagick::shadowImage
  • Imagick::shaveImage »
  • PHP Manual
  • Imagick
  • Sharpens an image

Imagick::sharpenImage

(PECL imagick 2.0.0)

Imagick::sharpenImage — Sharpens an image

Description

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();
}

?>


Shaves pixels from the image edges

  • « Imagick::sharpenImage
  • Imagick::shearImage »
  • PHP Manual
  • Imagick
  • Shaves pixels from the image edges

Imagick::shaveImage

(PECL imagick 2.0.0)

Imagick::shaveImage — Shaves pixels from the image edges

Description

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();
}

?>


Creating a parallelogram

  • « Imagick::shaveImage
  • Imagick::sigmoidalContrastImage »
  • PHP Manual
  • Imagick
  • Creating a parallelogram

Imagick::shearImage

(PECL imagick 2.0.0)

Imagick::shearImage — Creating a parallelogram

Description

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
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();
}

?>


Adjusts the contrast of an image

  • « Imagick::shearImage
  • Imagick::sketchImage »
  • PHP Manual
  • Imagick
  • Adjusts the contrast of an image

Imagick::sigmoidalContrastImage

(PECL imagick 2.0.0)

Imagick::sigmoidalContrastImage — Adjusts the contrast of an image

Description

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.

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;
}

?>

Errors/Exceptions

Throws ImagickException on error.


Simulates a pencil sketch

  • « Imagick::sigmoidalContrastImage
  • Imagick::smushImages »
  • PHP Manual
  • Imagick
  • Simulates a pencil sketch

Imagick::sketchImage

(PECL imagick 2.0.0)

Imagick::sketchImage — Simulates a pencil sketch

Description

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();
}

?>


Description

  • « Imagick::sketchImage
  • Imagick::solarizeImage »
  • PHP Manual
  • Imagick
  • Description

Imagick::smushImages

(No version information available, might only be in Git)

Imagick::smushImages — Description

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();
}

?>


Applies a solarizing effect to the image

  • « Imagick::smushImages
  • Imagick::sparseColorImage »
  • PHP Manual
  • Imagick
  • Applies a solarizing effect to the image

Imagick::solarizeImage

(PECL imagick 2.0.0)

Imagick::solarizeImage — Applies a solarizing effect to the image

Description

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();
}

?>


Interpolates colors

  • « Imagick::solarizeImage
  • Imagick::spliceImage »
  • PHP Manual
  • Imagick
  • Interpolates colors

Imagick::sparseColorImage

(No version information available, might only be in Git)

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;
}

?>


Splices a solid color into the image

  • « Imagick::sparseColorImage
  • Imagick::spreadImage »
  • PHP Manual
  • Imagick
  • Splices a solid color into the image

Imagick::spliceImage

(PECL imagick 2.0.0)

Imagick::spliceImage — Splices a solid color into the image

Description

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();
}

?>


Randomly displaces each pixel in a block

  • « Imagick::spliceImage
  • Imagick::statisticImage »
  • PHP Manual
  • Imagick
  • Randomly displaces each pixel in a block

Imagick::spreadImage

(PECL imagick 2.0.0)

Imagick::spreadImage — Randomly displaces each pixel in a block

Description

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();
}

?>


Description

  • « Imagick::spreadImage
  • Imagick::steganoImage »
  • PHP Manual
  • Imagick
  • Description

Imagick::statisticImage

(No version information available, might only be in Git)

Imagick::statisticImage — Description

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);

?>


Hides a digital watermark within the image

  • « Imagick::statisticImage
  • Imagick::stereoImage »
  • PHP Manual
  • Imagick
  • Hides a digital watermark within the image

Imagick::steganoImage

(PECL imagick 2.0.0)

Imagick::steganoImage — Hides a digital watermark within the image

Description

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.


Composites two images

  • « Imagick::steganoImage
  • Imagick::stripImage »
  • PHP Manual
  • Imagick
  • Composites two images

Imagick::stereoImage

(PECL imagick 2.0.0)

Imagick::stereoImage — Composites two images

Description

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.


Strips an image of all profiles and comments

  • « Imagick::stereoImage
  • Imagick::subImageMatch »
  • PHP Manual
  • Imagick
  • Strips an image of all profiles and comments

Imagick::stripImage

(PECL imagick 2.0.0)

Imagick::stripImage — Strips an image of all profiles and comments

Description

Imagick::stripImage ( void ) : bool

Strips an image of all profiles and comments.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws ImagickException on error.


Description

  • « Imagick::stripImage
  • Imagick::swirlImage »
  • PHP Manual
  • Imagick
  • Description

Imagick::subImageMatch

(No version information available, might only be in Git)

Imagick::subImageMatch — Description

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();
}

?>


Swirls the pixels about the center of the image

  • « Imagick::subImageMatch
  • Imagick::textureImage »
  • PHP Manual
  • Imagick
  • Swirls the pixels about the center of the image

Imagick::swirlImage

(PECL imagick 2.0.0)

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();
}

?>


Repeatedly tiles the texture image

  • « Imagick::swirlImage
  • Imagick::thresholdImage »
  • PHP Manual
  • Imagick
  • Repeatedly tiles the texture image

Imagick::textureImage

(PECL imagick 2.0.0)

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;
}

?>


Changes the value of individual pixels based on a threshold

  • « Imagick::textureImage
  • Imagick::thumbnailImage »
  • PHP Manual
  • Imagick
  • Changes the value of individual pixels based on a threshold

Imagick::thresholdImage

(PECL imagick 2.0.0)

Imagick::thresholdImage — Changes the value of individual pixels based on a threshold

Description

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();
}

?>


Changes the size of an image

  • « Imagick::thresholdImage
  • Imagick::tintImage »
  • PHP Manual
  • Imagick
  • Changes the size of an image

Imagick::thumbnailImage

(PECL imagick 2.0.0)

Imagick::thumbnailImage — Changes the size of an image

Description

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

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();
}

?>


Applies a color vector to each pixel in the image

  • « Imagick::thumbnailImage
  • Imagick::__toString »
  • PHP Manual
  • Imagick
  • Applies a color vector to each pixel in the image

Imagick::tintImage

(PECL imagick 2.0.0)

Imagick::tintImage — Applies a color vector to each pixel in the image

Description

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
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();
}

?>


Returns the image as a string

  • « Imagick::tintImage
  • Imagick::transformImage »
  • PHP Manual
  • Imagick
  • Returns the image as a string

Imagick::__toString

(No version information available, might only be in Git)

Imagick::__toString — Returns the image as a string

Description

Imagick::__toString ( void ) : 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


Convenience method for setting crop size and the image geometry

  • « Imagick::__toString
  • Imagick::transformImageColorspace »
  • PHP Manual
  • Imagick
  • Convenience method for setting crop size and the image geometry

Imagick::transformImage

(PECL imagick 2.0.0)

Imagick::transformImage — Convenience method for setting crop size and the image geometry

Description

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


Transforms an image to a new colorspace

  • « Imagick::transformImage
  • Imagick::transparentPaintImage »
  • PHP Manual
  • Imagick
  • Transforms an image to a new colorspace

Imagick::transformImageColorspace

(No version information available, might only be in Git)

Imagick::transformImageColorspace — Transforms an image to a new colorspace

Description

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

Examples

Example #2 Imagick::transformImageColorspace()

<?php
function transformImageColorspace($imagePath, $colorSpace, $channel) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->transformimagecolorspace($colorSpace);
    $imagick->separateImageChannel($channel);
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>


Paints pixels transparent

  • « Imagick::transformImageColorspace
  • Imagick::transposeImage »
  • PHP Manual
  • Imagick
  • Paints pixels transparent

Imagick::transparentPaintImage

(No version information available, might only be in Git)

Imagick::transparentPaintImage — Paints pixels transparent

Description

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();
}

?>


Creates a vertical mirror image

  • « Imagick::transparentPaintImage
  • Imagick::transverseImage »
  • PHP Manual
  • Imagick
  • Creates a vertical mirror image

Imagick::transposeImage

(PECL imagick 2.0.0)

Imagick::transposeImage — Creates a vertical mirror image

Description

Imagick::transposeImage ( void ) : 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.

Return Values

Returns TRUE on success.

See Also

  • Imagick::transverseImage() - Creates a horizontal mirror image

Examples

Example #1 Imagick::transposeImage()

<?php
function transposeImage($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->transposeImage();
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>


Creates a horizontal mirror image

  • « Imagick::transposeImage
  • Imagick::trimImage »
  • PHP Manual
  • Imagick
  • Creates a horizontal mirror image

Imagick::transverseImage

(PECL imagick 2.0.0)

Imagick::transverseImage — Creates a horizontal mirror image

Description

Imagick::transverseImage ( void ) : 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.

Return Values

Returns TRUE on success.

See Also

  • Imagick::transposeImage() - Creates a vertical mirror image

Examples

Example #1 Imagick::transverseImage()

<?php
function transverseImage($imagePath) {
    $imagick = new \Imagick(realpath($imagePath));
    $imagick->transverseImage();
    header("Content-Type: image/jpg");
    echo $imagick->getImageBlob();
}

?>


Remove edges from the image

  • « Imagick::transverseImage
  • Imagick::uniqueImageColors »
  • PHP Manual
  • Imagick
  • Remove edges from the image

Imagick::trimImage

(PECL imagick 2.0.0)

Imagick::trimImage — Remove edges from the image

Description

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


Discards all but one of any pixel color

  • « Imagick::trimImage
  • Imagick::unsharpMaskImage »
  • PHP Manual
  • Imagick
  • Discards all but one of any pixel color

Imagick::uniqueImageColors

(PECL imagick 2.0.0)

Imagick::uniqueImageColors — Discards all but one of any pixel color

Description

Imagick::uniqueImageColors ( void ) : 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.

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();
}

?>


Sharpens an image

  • « Imagick::uniqueImageColors
  • Imagick::valid »
  • PHP Manual
  • Imagick
  • Sharpens an image

Imagick::unsharpMaskImage

(PECL imagick 2.0.0)

Imagick::unsharpMaskImage — Sharpens an image

Description

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();
}

?>


Checks if the current item is valid

  • « Imagick::unsharpMaskImage
  • Imagick::vignetteImage »
  • PHP Manual
  • Imagick
  • Checks if the current item is valid

Imagick::valid

(PECL imagick 2.0.0)

Imagick::valid — Checks if the current item is valid

Description

Imagick::valid ( void ) : bool

Checks if the current item is valid.

Return Values

Returns TRUE on success.


Adds vignette filter to the image

  • « Imagick::valid
  • Imagick::waveImage »
  • PHP Manual
  • Imagick
  • Adds vignette filter to the image

Imagick::vignetteImage

(PECL imagick 2.0.0)

Imagick::vignetteImage — Adds vignette filter to the image

Description

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.

See Also

  • Imagick::waveImage() - Applies wave filter to the image
  • Imagick::swirlImage() - Swirls the pixels about the center of the image

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();
}

?>


Applies wave filter to the image

  • « Imagick::vignetteImage
  • Imagick::whiteThresholdImage »
  • PHP Manual
  • Imagick
  • Applies wave filter to the image

Imagick::waveImage

(PECL imagick 2.0.0)

Imagick::waveImage — Applies wave filter to the image

Description

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.

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

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();
}

?>


Force all pixels above the threshold into white

  • « Imagick::waveImage
  • Imagick::writeImage »
  • PHP Manual
  • Imagick
  • Force all pixels above the threshold into white

Imagick::whiteThresholdImage

(PECL imagick 2.0.0)

Imagick::whiteThresholdImage — Force all pixels above the threshold into white

Description

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
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();
}

?>


Writes an image to the specified filename

  • « Imagick::whiteThresholdImage
  • Imagick::writeImageFile »
  • PHP Manual
  • Imagick
  • Writes an image to the specified filename

Imagick::writeImage

(PECL imagick 0.9.0-0.9.9)

Imagick::writeImage — Writes an image to the specified filename

Description

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.


Writes an image to a filehandle

  • « Imagick::writeImage
  • Imagick::writeImages »
  • PHP Manual
  • Imagick
  • Writes an image to a filehandle

Imagick::writeImageFile

(No version information available, might only be in Git)

Imagick::writeImageFile — Writes an image to a filehandle

Description

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

Return Values

Returns TRUE on success.


Writes an image or image sequence

  • « Imagick::writeImageFile
  • Imagick::writeImagesFile »
  • PHP Manual
  • Imagick
  • Writes an image or image sequence

Imagick::writeImages

(PECL imagick 0.9.0-0.9.9)

Imagick::writeImages — Writes an image or image sequence

Description

Imagick::writeImages ( string $filename , bool $adjoin ) : bool

Writes an image or image sequence.

Parameters

filename

adjoin

Return Values

Returns TRUE on success.


Writes frames to a filehandle

  • « Imagick::writeImages
  • ImagickDraw »
  • PHP Manual
  • Imagick
  • Writes frames to a filehandle

Imagick::writeImagesFile

(No version information available, might only be in Git)

Imagick::writeImagesFile — Writes frames to a filehandle

Description

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

Return Values

Returns TRUE on success.


The ImagickDraw class

(PECL imagick 2.0.0)

Class synopsis

ImagickDraw {
affine ( array $affine ) : bool
annotation ( float $x , float $y , string $text ) : bool
arc ( float $sx , float $sy , float $ex , float $ey , float $sd , float $ed ) : bool
bezier ( array $coordinates ) : bool
circle ( float $ox , float $oy , float $px , float $py ) : bool
clear ( void ) : bool
clone ( void ) : ImagickDraw
color ( float $x , float $y , int $paintMethod ) : bool
comment ( string $comment ) : bool
composite ( int $compose , float $x , float $y , float $width , float $height , Imagick $compositeWand ) : bool
__construct ( void )
destroy ( void ) : bool
ellipse ( float $ox , float $oy , float $rx , float $ry , float $start , float $end ) : bool
getClipPath ( void ) : string
getClipRule ( void ) : int
getClipUnits ( void ) : int
getFillColor ( void ) : ImagickPixel
getFillOpacity ( void ) : float
getFillRule ( void ) : int
getFont ( void ) : string
getFontFamily ( void ) : string
getFontSize ( void ) : float
public getFontStretch ( void ) : int
getFontStyle ( void ) : int
getFontWeight ( void ) : int
getGravity ( void ) : int
getStrokeAntialias ( void ) : bool
getStrokeColor ( void ) : ImagickPixel
getStrokeDashArray ( void ) : array
getStrokeDashOffset ( void ) : float
getStrokeLineCap ( void ) : int
getStrokeLineJoin ( void ) : int
getStrokeMiterLimit ( void ) : int
getStrokeOpacity ( void ) : float
getStrokeWidth ( void ) : float
getTextAlignment ( void ) : int
getTextAntialias ( void ) : bool
getTextDecoration ( void ) : int
getTextEncoding ( void ) : string
public getTextInterlineSpacing ( void ) : float
public getTextInterwordSpacing ( void ) : float
public getTextKerning ( void ) : float
getTextUnderColor ( void ) : ImagickPixel
getVectorGraphics ( void ) : string
line ( float $sx , float $sy , float $ex , float $ey ) : bool
matte ( float $x , float $y , int $paintMethod ) : bool
pathClose ( void ) : bool
pathCurveToAbsolute ( float $x1 , float $y1 , float $x2 , float $y2 , float $x , float $y ) : bool
pathCurveToQuadraticBezierAbsolute ( float $x1 , float $y1 , float $x , float $y ) : bool
pathCurveToQuadraticBezierRelative ( float $x1 , float $y1 , float $x , float $y ) : bool
pathCurveToQuadraticBezierSmoothAbsolute ( float $x , float $y ) : bool
pathCurveToQuadraticBezierSmoothRelative ( float $x , float $y ) : bool
pathCurveToRelative ( float $x1 , float $y1 , float $x2 , float $y2 , float $x , float $y ) : bool
pathCurveToSmoothAbsolute ( float $x2 , float $y2 , float $x , float $y ) : bool
pathCurveToSmoothRelative ( float $x2 , float $y2 , float $x , float $y ) : bool
pathEllipticArcAbsolute ( float $rx , float $ry , float $x_axis_rotation , bool $large_arc_flag , bool $sweep_flag , float $x , float $y ) : bool
pathEllipticArcRelative ( float $rx , float $ry , float $x_axis_rotation , bool $large_arc_flag , bool $sweep_flag , float $x , float $y ) : bool
pathFinish ( void ) : bool
pathLineToAbsolute ( float $x , float $y ) : bool
pathLineToHorizontalAbsolute ( float $x ) : bool
pathLineToHorizontalRelative ( float $x ) : bool
pathLineToRelative ( float $x , float $y ) : bool
pathLineToVerticalAbsolute ( float $y ) : bool
pathLineToVerticalRelative ( float $y ) : bool
pathMoveToAbsolute ( float $x , float $y ) : bool
pathMoveToRelative ( float $x , float $y ) : bool
pathStart ( void ) : bool
point ( float $x , float $y ) : bool
polygon ( array $coordinates ) : bool
polyline ( array $coordinates ) : bool
pop ( void ) : bool
popClipPath ( void ) : bool
popDefs ( void ) : bool
popPattern ( void ) : bool
push ( void ) : bool
pushClipPath ( string $clip_mask_id ) : bool
pushDefs ( void ) : bool
pushPattern ( string $pattern_id , float $x , float $y , float $width , float $height ) : bool
rectangle ( float $x1 , float $y1 , float $x2 , float $y2 ) : bool
render ( void ) : bool
public resetVectorGraphics ( void ) : bool
rotate ( float $degrees ) : bool
roundRectangle ( float $x1 , float $y1 , float $x2 , float $y2 , float $rx , float $ry ) : bool
scale ( float $x , float $y ) : bool
setClipPath ( string $clip_mask ) : bool
setClipRule ( int $fill_rule ) : bool
setClipUnits ( int $clip_units ) : bool
setFillAlpha ( float $opacity ) : bool
setFillColor ( ImagickPixel $fill_pixel ) : bool
setFillOpacity ( float $fillOpacity ) : bool
setFillPatternURL ( string $fill_url ) : bool
setFillRule ( int $fill_rule ) : bool
setFont ( string $font_name ) : bool
setFontFamily ( string $font_family ) : bool
setFontSize ( float $pointsize ) : bool
setFontStretch ( int $fontStretch ) : bool
setFontStyle ( int $style ) : bool
setFontWeight ( int $font_weight ) : bool
setGravity ( int $gravity ) : bool
public setResolution ( float $x_resolution , float $y_resolution ) : bool
setStrokeAlpha ( float $opacity ) : bool
setStrokeAntialias ( bool $stroke_antialias ) : bool
setStrokeColor ( ImagickPixel $stroke_pixel ) : bool
setStrokeDashArray ( array $dashArray ) : bool
setStrokeDashOffset ( float $dash_offset ) : bool
setStrokeLineCap ( int $linecap ) : bool
setStrokeLineJoin ( int $linejoin ) : bool
setStrokeMiterLimit ( int $miterlimit ) : bool
setStrokeOpacity ( float $stroke_opacity ) : bool
setStrokePatternURL ( string $stroke_url ) : bool
setStrokeWidth ( float $stroke_width ) : bool
setTextAlignment ( int $alignment ) : bool
setTextAntialias ( bool $antiAlias ) : bool
setTextDecoration ( int $decoration ) : bool
setTextEncoding ( string $encoding ) : bool
public setTextInterlineSpacing ( float $spacing ) : bool
public setTextInterwordSpacing ( float $spacing ) : bool
public setTextKerning ( float $kerning ) : bool
setTextUnderColor ( ImagickPixel $under_color ) : bool
setVectorGraphics ( string $xml ) : bool
setViewbox ( int $x1 , int $y1 , int $x2 , int $y2 ) : bool
skewX ( float $degrees ) : bool
skewY ( float $degrees ) : bool
translate ( float $x , float $y ) : bool
}

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 — Description
  • 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 — Description
  • ImagickDraw::getTextInterwordSpacing — Description
  • ImagickDraw::getTextKerning — Description
  • 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 — Description
  • 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 — Description
  • 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 — Description
  • ImagickDraw::setTextInterwordSpacing — Description
  • ImagickDraw::setTextKerning — Description
  • 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


Adjusts the current affine transformation matrix

  • « ImagickDraw
  • ImagickDraw::annotation »
  • PHP Manual
  • ImagickDraw
  • Adjusts the current affine transformation matrix

ImagickDraw::affine

(PECL imagick 2.0.0)

ImagickDraw::affine — Adjusts the current affine transformation matrix

Description

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()

<?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();
}

?>


Draws text on the image

  • « ImagickDraw::affine
  • ImagickDraw::arc »
  • PHP Manual
  • ImagickDraw
  • Draws text on the image

ImagickDraw::annotation

(PECL imagick 2.0.0)

ImagickDraw::annotation — Draws text on the image

Description

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.


Draws an arc

  • « ImagickDraw::annotation
  • ImagickDraw::bezier »
  • PHP Manual
  • ImagickDraw
  • Draws an arc

ImagickDraw::arc

(PECL imagick 2.0.0)

ImagickDraw::arc — Draws an arc

Description

ImagickDraw::arc ( float $sx , float $sy , float $ex , float $ey , float $sd , float $ed ) : 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

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

No value is returned.

Examples

Example #1 ImagickDraw::arc()

<?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();
}

?>


Draws a bezier curve

  • « ImagickDraw::arc
  • ImagickDraw::circle »
  • PHP Manual
  • ImagickDraw
  • Draws a bezier curve

ImagickDraw::bezier

(PECL imagick 2.0.0)

ImagickDraw::bezier — Draws a bezier curve

Description

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()

<?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();
}

?>


Draws a circle

  • « ImagickDraw::bezier
  • ImagickDraw::clear »
  • PHP Manual
  • ImagickDraw
  • Draws a circle

ImagickDraw::circle

(PECL imagick 2.0.0)

ImagickDraw::circle — Draws a circle

Description

ImagickDraw::circle ( float $ox , float $oy , float $px , float $py ) : bool
Warning

This function is currently not documented; only its argument list is available.

Draws a circle on the image.

Parameters

ox

origin x coordinate

oy

origin y coordinate

px

perimeter x coordinate

py

perimeter y coordinate

Return Values

No value is returned.

Examples

Example #1 ImagickDraw::circle()

<?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();
}

?>


Clears the ImagickDraw

  • « ImagickDraw::circle
  • ImagickDraw::clone »
  • PHP Manual
  • ImagickDraw
  • Clears the ImagickDraw

ImagickDraw::clear

(PECL imagick 2.0.0)

ImagickDraw::clear — Clears the ImagickDraw

Description

ImagickDraw::clear ( void ) : 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.


Makes an exact copy of the specified ImagickDraw object

  • « ImagickDraw::clear
  • ImagickDraw::color »
  • PHP Manual
  • ImagickDraw
  • Makes an exact copy of the specified ImagickDraw object

ImagickDraw::clone

(PECL imagick 2.0.0)

ImagickDraw::clone — Makes an exact copy of the specified ImagickDraw object

Description

ImagickDraw::clone ( void ) : 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

What the function returns, first on success, then on failure. See also the &return.success; entity


Draws color on image

  • « ImagickDraw::clone
  • ImagickDraw::comment »
  • PHP Manual
  • ImagickDraw
  • Draws color on image

ImagickDraw::color

(PECL imagick 2.0.0)

ImagickDraw::color — Draws color on image

Description

ImagickDraw::color ( float $x , float $y , int $paintMethod ) : 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

paintMethod

one of the PAINT_ constants

Return Values

No value is returned.


Adds a comment

  • « ImagickDraw::color
  • ImagickDraw::composite »
  • PHP Manual
  • ImagickDraw
  • Adds a comment

ImagickDraw::comment

(PECL imagick 2.0.0)

ImagickDraw::comment — Adds a comment

Description

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.


Composites an image onto the current image

  • « ImagickDraw::comment
  • ImagickDraw::__construct »
  • PHP Manual
  • ImagickDraw
  • Composites an image onto the current image

ImagickDraw::composite

(PECL imagick 2.0.0)

ImagickDraw::composite — Composites an image onto the current image

Description

ImagickDraw::composite ( int $compose , float $x , float $y , float $width , float $height , Imagick $compositeWand ) : 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

compose

composition operator. One of COMPOSITE_ constants

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

compositeWand

the Imagick object where composition image is taken from

Return Values

Returns TRUE on success.

Examples

Example #1 ImagickDraw::composite()

<?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();
}

?>


The ImagickDraw constructor

  • « ImagickDraw::composite
  • ImagickDraw::destroy »
  • PHP Manual
  • ImagickDraw
  • The ImagickDraw constructor

ImagickDraw::__construct

(PECL imagick 2.0.0)

ImagickDraw::__construct — The ImagickDraw constructor

Description

ImagickDraw::__construct ( void )
Warning

This function is currently not documented; only its argument list is available.

The ImagickDraw constructor

Return Values

No value is returned.


Frees all associated resources

  • « ImagickDraw::__construct
  • ImagickDraw::ellipse »
  • PHP Manual
  • ImagickDraw
  • Frees all associated resources

ImagickDraw::destroy

(PECL imagick 2.0.0)

ImagickDraw::destroy — Frees all associated resources

Description

ImagickDraw::destroy ( void ) : 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.


Draws an ellipse on the image

  • « ImagickDraw::destroy
  • ImagickDraw::getClipPath »
  • PHP Manual
  • ImagickDraw
  • Draws an ellipse on the image

ImagickDraw::ellipse

(PECL imagick 2.0.0)

ImagickDraw::ellipse — Draws an ellipse on the image

Description

ImagickDraw::ellipse ( float $ox , float $oy , float $rx , float $ry , float $start , float $end ) : bool
Warning

This function is currently not documented; only its argument list is available.

Draws an ellipse on the image.

Parameters

ox

oy

rx

ry

start

end

Return Values

No value is returned.

Examples

Example #1 ImagickDraw::ellipse()

<?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();
}

?>


Obtains the current clipping path ID

  • « ImagickDraw::ellipse
  • ImagickDraw::getClipRule »
  • PHP Manual
  • ImagickDraw
  • Obtains the current clipping path ID

ImagickDraw::getClipPath

(PECL imagick 2.0.0)

ImagickDraw::getClipPath — Obtains the current clipping path ID

Description

ImagickDraw::getClipPath ( void ) : 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.


Returns the current polygon fill rule

  • « ImagickDraw::getClipPath
  • ImagickDraw::getClipUnits »
  • PHP Manual
  • ImagickDraw
  • Returns the current polygon fill rule

ImagickDraw::getClipRule

(PECL imagick 2.0.0)

ImagickDraw::getClipRule — Returns the current polygon fill rule

Description

ImagickDraw::getClipRule ( void ) : 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 one of the FILLRULE_ constants.


Returns the interpretation of clip path units

  • « ImagickDraw::getClipRule
  • ImagickDraw::getFillColor »
  • PHP Manual
  • ImagickDraw
  • Returns the interpretation of clip path units

ImagickDraw::getClipUnits

(PECL imagick 2.0.0)

ImagickDraw::getClipUnits — Returns the interpretation of clip path units

Description

ImagickDraw::getClipUnits ( void ) : 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.


Returns the fill color

  • « ImagickDraw::getClipUnits
  • ImagickDraw::getFillOpacity »
  • PHP Manual
  • ImagickDraw
  • Returns the fill color

ImagickDraw::getFillColor

(PECL imagick 2.0.0)

ImagickDraw::getFillColor — Returns the fill color

Description

ImagickDraw::getFillColor ( void ) : 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.


Returns the opacity used when drawing

  • « ImagickDraw::getFillColor
  • ImagickDraw::getFillRule »
  • PHP Manual
  • ImagickDraw
  • Returns the opacity used when drawing

ImagickDraw::getFillOpacity

(PECL imagick 2.0.0)

ImagickDraw::getFillOpacity — Returns the opacity used when drawing

Description

ImagickDraw::getFillOpacity ( void ) : 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.


Returns the fill rule

  • « ImagickDraw::getFillOpacity
  • ImagickDraw::getFont »
  • PHP Manual
  • ImagickDraw
  • Returns the fill rule

ImagickDraw::getFillRule

(PECL imagick 2.0.0)

ImagickDraw::getFillRule — Returns the fill rule

Description

ImagickDraw::getFillRule ( void ) : 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


Returns the font

  • « ImagickDraw::getFillRule
  • ImagickDraw::getFontFamily »
  • PHP Manual
  • ImagickDraw
  • Returns the font

ImagickDraw::getFont

(PECL imagick 2.0.0)

ImagickDraw::getFont — Returns the font

Description

ImagickDraw::getFont ( void ) : 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.


Returns the font family

  • « ImagickDraw::getFont
  • ImagickDraw::getFontSize »
  • PHP Manual
  • ImagickDraw
  • Returns the font family

ImagickDraw::getFontFamily

(PECL imagick 2.0.0)

ImagickDraw::getFontFamily — Returns the font family

Description

ImagickDraw::getFontFamily ( void ) : 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.


Returns the font pointsize

  • « ImagickDraw::getFontFamily
  • ImagickDraw::getFontStretch »
  • PHP Manual
  • ImagickDraw
  • Returns the font pointsize

ImagickDraw::getFontSize

(PECL imagick 2.0.0)

ImagickDraw::getFontSize — Returns the font pointsize

Description

ImagickDraw::getFontSize ( void ) : 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.


Description

  • « ImagickDraw::getFontSize
  • ImagickDraw::getFontStyle »
  • PHP Manual
  • ImagickDraw
  • Description

ImagickDraw::getFontStretch

(No version information available, might only be in Git)

ImagickDraw::getFontStretch — Description

Description

public ImagickDraw::getFontStretch ( void ) : int

Gets the font stretch to use when annotating with text. Returns a StretchType.

Parameters

This function has no parameters.

Return Values


Returns the font style

  • « ImagickDraw::getFontStretch
  • ImagickDraw::getFontWeight »
  • PHP Manual
  • ImagickDraw
  • Returns the font style

ImagickDraw::getFontStyle

(PECL imagick 2.0.0)

ImagickDraw::getFontStyle — Returns the font style

Description

ImagickDraw::getFontStyle ( void ) : 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 the font style constant (STYLE_) associated with the ImagickDraw object or 0 if no style is set.


Returns the font weight

  • « ImagickDraw::getFontStyle
  • ImagickDraw::getGravity »
  • PHP Manual
  • ImagickDraw
  • Returns the font weight

ImagickDraw::getFontWeight

(PECL imagick 2.0.0)

ImagickDraw::getFontWeight — Returns the font weight

Description

ImagickDraw::getFontWeight ( void ) : 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.


Returns the text placement gravity

  • « ImagickDraw::getFontWeight
  • ImagickDraw::getStrokeAntialias »
  • PHP Manual
  • ImagickDraw
  • Returns the text placement gravity

ImagickDraw::getGravity

(PECL imagick 2.0.0)

ImagickDraw::getGravity — Returns the text placement gravity

Description

ImagickDraw::getGravity ( void ) : 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 on success and 0 if no gravity is set.


Returns the current stroke antialias setting

  • « ImagickDraw::getGravity
  • ImagickDraw::getStrokeColor »
  • PHP Manual
  • ImagickDraw
  • Returns the current stroke antialias setting

ImagickDraw::getStrokeAntialias

(PECL imagick 2.0.0)

ImagickDraw::getStrokeAntialias — Returns the current stroke antialias setting

Description

ImagickDraw::getStrokeAntialias ( void ) : 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.


Returns the color used for stroking object outlines

  • « ImagickDraw::getStrokeAntialias
  • ImagickDraw::getStrokeDashArray »
  • PHP Manual
  • ImagickDraw
  • Returns the color used for stroking object outlines

ImagickDraw::getStrokeColor

(PECL imagick 2.0.0)

ImagickDraw::getStrokeColor — Returns the color used for stroking object outlines

Description

ImagickDraw::getStrokeColor ( void ) : 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.


Returns an array representing the pattern of dashes and gaps used to stroke paths

  • « ImagickDraw::getStrokeColor
  • ImagickDraw::getStrokeDashOffset »
  • PHP Manual
  • ImagickDraw
  • Returns an array representing the pattern of dashes and gaps used to stroke paths

ImagickDraw::getStrokeDashArray

(PECL imagick 2.0.0)

ImagickDraw::getStrokeDashArray — Returns an array representing the pattern of dashes and gaps used to stroke paths

Description

ImagickDraw::getStrokeDashArray ( void ) : 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.


Returns the offset into the dash pattern to start the dash

  • « ImagickDraw::getStrokeDashArray
  • ImagickDraw::getStrokeLineCap »
  • PHP Manual
  • ImagickDraw
  • Returns the offset into the dash pattern to start the dash

ImagickDraw::getStrokeDashOffset

(PECL imagick 2.0.0)

ImagickDraw::getStrokeDashOffset — Returns the offset into the dash pattern to start the dash

Description

ImagickDraw::getStrokeDashOffset ( void ) : 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.


Returns the shape to be used at the end of open subpaths when they are stroked

  • « ImagickDraw::getStrokeDashOffset
  • ImagickDraw::getStrokeLineJoin »
  • PHP Manual
  • ImagickDraw
  • Returns the shape to be used at the end of open subpaths when they are stroked

ImagickDraw::getStrokeLineCap

(PECL imagick 2.0.0)

ImagickDraw::getStrokeLineCap — Returns the shape to be used at the end of open subpaths when they are stroked

Description

ImagickDraw::getStrokeLineCap ( void ) : 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 one of the LINECAP_ constants or 0 if stroke linecap is not set.


Returns the shape to be used at the corners of paths when they are stroked

  • « ImagickDraw::getStrokeLineCap
  • ImagickDraw::getStrokeMiterLimit »
  • PHP Manual
  • ImagickDraw
  • Returns the shape to be used at the corners of paths when they are stroked

ImagickDraw::getStrokeLineJoin

(PECL imagick 2.0.0)

ImagickDraw::getStrokeLineJoin — Returns the shape to be used at the corners of paths when they are stroked

Description

ImagickDraw::getStrokeLineJoin ( void ) : 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 one of the LINEJOIN_ constants or 0 if stroke line join is not set.


Returns the stroke miter limit

  • « ImagickDraw::getStrokeLineJoin
  • ImagickDraw::getStrokeOpacity »
  • PHP Manual
  • ImagickDraw
  • Returns the stroke miter limit

ImagickDraw::getStrokeMiterLimit

(PECL imagick 2.0.0)

ImagickDraw::getStrokeMiterLimit — Returns the stroke miter limit

Description

ImagickDraw::getStrokeMiterLimit ( void ) : 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.


Returns the opacity of stroked object outlines

  • « ImagickDraw::getStrokeMiterLimit
  • ImagickDraw::getStrokeWidth »
  • PHP Manual
  • ImagickDraw
  • Returns the opacity of stroked object outlines

ImagickDraw::getStrokeOpacity

(PECL imagick 2.0.0)

ImagickDraw::getStrokeOpacity — Returns the opacity of stroked object outlines

Description

ImagickDraw::getStrokeOpacity ( void ) : 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 double describing the opacity.


Returns the width of the stroke used to draw object outlines

  • « ImagickDraw::getStrokeOpacity
  • ImagickDraw::getTextAlignment »
  • PHP Manual
  • ImagickDraw
  • Returns the width of the stroke used to draw object outlines

ImagickDraw::getStrokeWidth

(PECL imagick 2.0.0)

ImagickDraw::getStrokeWidth — Returns the width of the stroke used to draw object outlines

Description

ImagickDraw::getStrokeWidth ( void ) : 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 double describing the stroke width.


Returns the text alignment

  • « ImagickDraw::getStrokeWidth
  • ImagickDraw::getTextAntialias »
  • PHP Manual
  • ImagickDraw
  • Returns the text alignment

ImagickDraw::getTextAlignment

(PECL imagick 2.0.0)

ImagickDraw::getTextAlignment — Returns the text alignment

Description

ImagickDraw::getTextAlignment ( void ) : 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 one of the ALIGN_ constants and 0 if no align is set.


Returns the current text antialias setting

  • « ImagickDraw::getTextAlignment
  • ImagickDraw::getTextDecoration »
  • PHP Manual
  • ImagickDraw
  • Returns the current text antialias setting

ImagickDraw::getTextAntialias

(PECL imagick 2.0.0)

ImagickDraw::getTextAntialias — Returns the current text antialias setting

Description

ImagickDraw::getTextAntialias ( void ) : 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.


Returns the text decoration

  • « ImagickDraw::getTextAntialias
  • ImagickDraw::getTextEncoding »
  • PHP Manual
  • ImagickDraw
  • Returns the text decoration

ImagickDraw::getTextDecoration

(PECL imagick 2.0.0)

ImagickDraw::getTextDecoration — Returns the text decoration

Description

ImagickDraw::getTextDecoration ( void ) : 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 one of the DECORATION_ constants and 0 if no decoration is set.


Returns the code set used for text annotations

  • « ImagickDraw::getTextDecoration
  • ImagickDraw::getTextInterlineSpacing »
  • PHP Manual
  • ImagickDraw
  • Returns the code set used for text annotations

ImagickDraw::getTextEncoding

(PECL imagick 2.0.0)

ImagickDraw::getTextEncoding — Returns the code set used for text annotations

Description

ImagickDraw::getTextEncoding ( void ) : 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.


Description

  • « ImagickDraw::getTextEncoding
  • ImagickDraw::getTextInterwordSpacing »
  • PHP Manual
  • ImagickDraw
  • Description

ImagickDraw::getTextInterlineSpacing

(No version information available, might only be in Git)

ImagickDraw::getTextInterlineSpacing — Description

Description

public ImagickDraw::getTextInterlineSpacing ( void ) : float

Gets the text interword spacing.

Parameters

This function has no parameters.

Return Values


Description

  • « ImagickDraw::getTextInterlineSpacing
  • ImagickDraw::getTextKerning »
  • PHP Manual
  • ImagickDraw
  • Description

ImagickDraw::getTextInterwordSpacing

(No version information available, might only be in Git)

ImagickDraw::getTextInterwordSpacing — Description

Description

public ImagickDraw::getTextInterwordSpacing ( void ) : float

Gets the text interword spacing.

Parameters

This function has no parameters.

Return Values


Description

  • « ImagickDraw::getTextInterwordSpacing
  • ImagickDraw::getTextUnderColor »
  • PHP Manual
  • ImagickDraw
  • Description

ImagickDraw::getTextKerning

(No version information available, might only be in Git)

ImagickDraw::getTextKerning — Description

Description

public ImagickDraw::getTextKerning ( void ) : float

Gets the text kerning.

Parameters

This function has no parameters.

Return Values


Returns the text under color

  • « ImagickDraw::getTextKerning
  • ImagickDraw::getVectorGraphics »
  • PHP Manual
  • ImagickDraw
  • Returns the text under color

ImagickDraw::getTextUnderColor

(PECL imagick 2.0.0)

ImagickDraw::getTextUnderColor — Returns the text under color

Description

ImagickDraw::getTextUnderColor ( void ) : 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.


Returns a string containing vector graphics

  • « ImagickDraw::getTextUnderColor
  • ImagickDraw::line »
  • PHP Manual
  • ImagickDraw
  • Returns a string containing vector graphics

ImagickDraw::getVectorGraphics

(PECL imagick 2.0.0)

ImagickDraw::getVectorGraphics — Returns a string containing vector graphics

Description

ImagickDraw::getVectorGraphics ( void ) : 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.


Draws a line

  • « ImagickDraw::getVectorGraphics
  • ImagickDraw::matte »
  • PHP Manual
  • ImagickDraw
  • Draws a line

ImagickDraw::line

(PECL imagick 2.0.0)

ImagickDraw::line — Draws a line

Description

ImagickDraw::line ( float $sx , float $sy , float $ex , float $ey ) : 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

sx

starting x coordinate

sy

starting y coordinate

ex

ending x coordinate

ey

ending y coordinate

Return Values

No value is returned.

Examples

Example #1 ImagickDraw::line()

<?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();
}

?>


Paints on the image's opacity channel

  • « ImagickDraw::line
  • ImagickDraw::pathClose »
  • PHP Manual
  • ImagickDraw
  • Paints on the image's opacity channel

ImagickDraw::matte

(PECL imagick 2.0.0)

ImagickDraw::matte — Paints on the image's opacity channel

Description

ImagickDraw::matte ( float $x , float $y , int $paintMethod ) : 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

paintMethod

PAINT_ constant

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ImagickDraw::matte()

<?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();
}

?>


Adds a path element to the current path

  • « ImagickDraw::matte
  • ImagickDraw::pathCurveToAbsolute »
  • PHP Manual
  • ImagickDraw
  • Adds a path element to the current path

ImagickDraw::pathClose

(PECL imagick 2.0.0)

ImagickDraw::pathClose — Adds a path element to the current path

Description

ImagickDraw::pathClose ( void ) : 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.


Draws a cubic Bezier curve

  • « ImagickDraw::pathClose
  • ImagickDraw::pathCurveToQuadraticBezierAbsolute »
  • PHP Manual
  • ImagickDraw
  • Draws a cubic Bezier curve

ImagickDraw::pathCurveToAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToAbsolute — Draws a cubic Bezier curve

Description

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.


Draws a quadratic Bezier curve

  • « ImagickDraw::pathCurveToAbsolute
  • ImagickDraw::pathCurveToQuadraticBezierRelative »
  • PHP Manual
  • ImagickDraw
  • Draws a quadratic Bezier curve

ImagickDraw::pathCurveToQuadraticBezierAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToQuadraticBezierAbsolute — Draws a quadratic Bezier curve

Description

ImagickDraw::pathCurveToQuadraticBezierAbsolute ( float $x1 , float $y1 , float $x , 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

x coordinate of the end point

y

y coordinate of the end point

Return Values

No value is returned.

Examples

Example #1 ImagickDraw::pathCurveToQuadraticBezierAbsolute()

<?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();

}

?>


Draws a quadratic Bezier curve

  • « ImagickDraw::pathCurveToQuadraticBezierAbsolute
  • ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute »
  • PHP Manual
  • ImagickDraw
  • Draws a quadratic Bezier curve

ImagickDraw::pathCurveToQuadraticBezierRelative

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToQuadraticBezierRelative — Draws a quadratic Bezier curve

Description

ImagickDraw::pathCurveToQuadraticBezierRelative ( float $x1 , float $y1 , float $x , 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

ending x coordinate

y

ending y coordinate

Return Values

No value is returned.


Draws a quadratic Bezier curve

  • « ImagickDraw::pathCurveToQuadraticBezierRelative
  • ImagickDraw::pathCurveToQuadraticBezierSmoothRelative »
  • PHP Manual
  • ImagickDraw
  • Draws a quadratic Bezier curve

ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute — Draws a quadratic Bezier curve

Description

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()

<?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();
?>


Draws a quadratic Bezier curve

  • « ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute
  • ImagickDraw::pathCurveToRelative »
  • PHP Manual
  • ImagickDraw
  • Draws a quadratic Bezier curve

ImagickDraw::pathCurveToQuadraticBezierSmoothRelative

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToQuadraticBezierSmoothRelative — Draws a quadratic Bezier curve

Description

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()

<?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();
?>


Draws a cubic Bezier curve

  • « ImagickDraw::pathCurveToQuadraticBezierSmoothRelative
  • ImagickDraw::pathCurveToSmoothAbsolute »
  • PHP Manual
  • ImagickDraw
  • Draws a cubic Bezier curve

ImagickDraw::pathCurveToRelative

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToRelative — Draws a cubic Bezier curve

Description

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.


Draws a cubic Bezier curve

  • « ImagickDraw::pathCurveToRelative
  • ImagickDraw::pathCurveToSmoothRelative »
  • PHP Manual
  • ImagickDraw
  • Draws a cubic Bezier curve

ImagickDraw::pathCurveToSmoothAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToSmoothAbsolute — Draws a cubic Bezier curve

Description

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.


Draws a cubic Bezier curve

  • « ImagickDraw::pathCurveToSmoothAbsolute
  • ImagickDraw::pathEllipticArcAbsolute »
  • PHP Manual
  • ImagickDraw
  • Draws a cubic Bezier curve

ImagickDraw::pathCurveToSmoothRelative

(PECL imagick 2.0.0)

ImagickDraw::pathCurveToSmoothRelative — Draws a cubic Bezier curve

Description

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.


Draws an elliptical arc

  • « ImagickDraw::pathCurveToSmoothRelative
  • ImagickDraw::pathEllipticArcRelative »
  • PHP Manual
  • ImagickDraw
  • Draws an elliptical arc

ImagickDraw::pathEllipticArcAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathEllipticArcAbsolute — Draws an elliptical arc

Description

ImagickDraw::pathEllipticArcAbsolute ( float $rx , float $ry , float $x_axis_rotation , bool $large_arc_flag , bool $sweep_flag , 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 largeArcFlag is TRUE then draw the larger of the available arcs. If sweepFlag 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_flag

large arc flag

sweep_flag

sweep flag

x

x coordinate

y

y coordinate

Return Values

No value is returned.


Draws an elliptical arc

  • « ImagickDraw::pathEllipticArcAbsolute
  • ImagickDraw::pathFinish »
  • PHP Manual
  • ImagickDraw
  • Draws an elliptical arc

ImagickDraw::pathEllipticArcRelative

(PECL imagick 2.0.0)

ImagickDraw::pathEllipticArcRelative — Draws an elliptical arc

Description

ImagickDraw::pathEllipticArcRelative ( float $rx , float $ry , float $x_axis_rotation , bool $large_arc_flag , bool $sweep_flag , 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 largeArcFlag is TRUE then draw the larger of the available arcs. If sweepFlag 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_flag

large arc flag

sweep_flag

sweep flag

x

x coordinate

y

y coordinate

Return Values

No value is returned.


Terminates the current path

  • « ImagickDraw::pathEllipticArcRelative
  • ImagickDraw::pathLineToAbsolute »
  • PHP Manual
  • ImagickDraw
  • Terminates the current path

ImagickDraw::pathFinish

(PECL imagick 2.0.0)

ImagickDraw::pathFinish — Terminates the current path

Description

ImagickDraw::pathFinish ( void ) : bool
Warning

This function is currently not documented; only its argument list is available.

Terminates the current path.

Return Values

No value is returned.


Draws a line path

  • « ImagickDraw::pathFinish
  • ImagickDraw::pathLineToHorizontalAbsolute »
  • PHP Manual
  • ImagickDraw
  • Draws a line path

ImagickDraw::pathLineToAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathLineToAbsolute — Draws a line path

Description

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.


Draws a horizontal line path

  • « ImagickDraw::pathLineToAbsolute
  • ImagickDraw::pathLineToHorizontalRelative »
  • PHP Manual
  • ImagickDraw
  • Draws a horizontal line path

ImagickDraw::pathLineToHorizontalAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathLineToHorizontalAbsolute — Draws a horizontal line path

Description

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.


Draws a horizontal line

  • « ImagickDraw::pathLineToHorizontalAbsolute
  • ImagickDraw::pathLineToRelative »
  • PHP Manual
  • ImagickDraw
  • Draws a horizontal line

ImagickDraw::pathLineToHorizontalRelative

(PECL imagick 2.0.0)

ImagickDraw::pathLineToHorizontalRelative — Draws a horizontal line

Description

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.


Draws a line path

  • « ImagickDraw::pathLineToHorizontalRelative
  • ImagickDraw::pathLineToVerticalAbsolute »
  • PHP Manual
  • ImagickDraw
  • Draws a line path

ImagickDraw::pathLineToRelative

(PECL imagick 2.0.0)

ImagickDraw::pathLineToRelative — Draws a line path

Description

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.


Draws a vertical line

  • « ImagickDraw::pathLineToRelative
  • ImagickDraw::pathLineToVerticalRelative »
  • PHP Manual
  • ImagickDraw
  • Draws a vertical line

ImagickDraw::pathLineToVerticalAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathLineToVerticalAbsolute — Draws a vertical line

Description

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.


Draws a vertical line path

  • « ImagickDraw::pathLineToVerticalAbsolute
  • ImagickDraw::pathMoveToAbsolute »
  • PHP Manual
  • ImagickDraw
  • Draws a vertical line path

ImagickDraw::pathLineToVerticalRelative

(PECL imagick 2.0.0)

ImagickDraw::pathLineToVerticalRelative — Draws a vertical line path

Description

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.


Starts a new sub-path

  • « ImagickDraw::pathLineToVerticalRelative
  • ImagickDraw::pathMoveToRelative »
  • PHP Manual
  • ImagickDraw
  • Starts a new sub-path

ImagickDraw::pathMoveToAbsolute

(PECL imagick 2.0.0)

ImagickDraw::pathMoveToAbsolute — Starts a new sub-path

Description

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.


Starts a new sub-path

  • « ImagickDraw::pathMoveToAbsolute
  • ImagickDraw::pathStart »
  • PHP Manual
  • ImagickDraw
  • Starts a new sub-path

ImagickDraw::pathMoveToRelative

(PECL imagick 2.0.0)

ImagickDraw::pathMoveToRelative — Starts a new sub-path

Description

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.


Declares the start of a path drawing list

  • « ImagickDraw::pathMoveToRelative
  • ImagickDraw::point »
  • PHP Manual
  • ImagickDraw
  • Declares the start of a path drawing list

ImagickDraw::pathStart

(PECL imagick 2.0.0)

ImagickDraw::pathStart — Declares the start of a path drawing list

Description

ImagickDraw::pathStart ( void ) : 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()

<?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();
}

?>


Draws a point

  • « ImagickDraw::pathStart
  • ImagickDraw::polygon »
  • PHP Manual
  • ImagickDraw
  • Draws a point

ImagickDraw::point

(PECL imagick 2.0.0)

ImagickDraw::point — Draws a point

Description

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()

<?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();
}

?>


Draws a polygon

  • « ImagickDraw::point
  • ImagickDraw::polyline »
  • PHP Manual
  • ImagickDraw
  • Draws a polygon

ImagickDraw::polygon

(PECL imagick 2.0.0)

ImagickDraw::polygon — Draws a polygon

Description

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()

<?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();
}

?>


Draws a polyline

  • « ImagickDraw::polygon
  • ImagickDraw::pop »
  • PHP Manual
  • ImagickDraw
  • Draws a polyline

ImagickDraw::polyline

(PECL imagick 2.0.0)

ImagickDraw::polyline — Draws a polyline

Description

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()

<?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();
}

?>


Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw

  • « ImagickDraw::polyline
  • ImagickDraw::popClipPath »
  • PHP Manual
  • ImagickDraw
  • Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw

ImagickDraw::pop

(PECL imagick 2.0.0)

ImagickDraw::pop — Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw

Description

ImagickDraw::pop ( void ) : 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 and false on failure.


Terminates a clip path definition

  • « ImagickDraw::pop
  • ImagickDraw::popDefs »
  • PHP Manual
  • ImagickDraw
  • Terminates a clip path definition

ImagickDraw::popClipPath

(PECL imagick 2.0.0)

ImagickDraw::popClipPath — Terminates a clip path definition

Description

ImagickDraw::popClipPath ( void ) : 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.


Terminates a definition list

  • « ImagickDraw::popClipPath
  • ImagickDraw::popPattern »
  • PHP Manual
  • ImagickDraw
  • Terminates a definition list

ImagickDraw::popDefs

(PECL imagick 2.0.0)

ImagickDraw::popDefs — Terminates a definition list

Description

ImagickDraw::popDefs ( void ) : 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()

<?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();
}

?>


Terminates a pattern definition

  • « ImagickDraw::popDefs
  • ImagickDraw::push »
  • PHP Manual
  • ImagickDraw
  • Terminates a pattern definition

ImagickDraw::popPattern

(PECL imagick 2.0.0)

ImagickDraw::popPattern — Terminates a pattern definition

Description

ImagickDraw::popPattern ( void ) : 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.


Clones the current ImagickDraw and pushes it to the stack

  • « ImagickDraw::popPattern
  • ImagickDraw::pushClipPath »
  • PHP Manual
  • ImagickDraw
  • Clones the current ImagickDraw and pushes it to the stack

ImagickDraw::push

(PECL imagick 2.0.0)

ImagickDraw::push — Clones the current ImagickDraw and pushes it to the stack

Description

ImagickDraw::push ( void ) : 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 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()

<?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();
}

?>


Starts a clip path definition

  • « ImagickDraw::push
  • ImagickDraw::pushDefs »
  • PHP Manual
  • ImagickDraw
  • Starts a clip path definition

ImagickDraw::pushClipPath

(PECL imagick 2.0.0)

ImagickDraw::pushClipPath — Starts a clip path definition

Description

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.


Indicates that following commands create named elements for early processing

  • « ImagickDraw::pushClipPath
  • ImagickDraw::pushPattern »
  • PHP Manual
  • ImagickDraw
  • Indicates that following commands create named elements for early processing

ImagickDraw::pushDefs

(PECL imagick 2.0.0)

ImagickDraw::pushDefs — Indicates that following commands create named elements for early processing

Description

ImagickDraw::pushDefs ( void ) : 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.


Indicates that subsequent commands up to a ImagickDraw::opPattern() command comprise the definition of a named pattern

  • « ImagickDraw::pushDefs
  • ImagickDraw::rectangle »
  • PHP Manual
  • ImagickDraw
  • Indicates that subsequent commands up to a ImagickDraw::opPattern() command comprise the definition of a named pattern

ImagickDraw::pushPattern

(PECL imagick 2.0.0)

ImagickDraw::pushPattern — Indicates that subsequent commands up to a ImagickDraw::opPattern() command comprise the definition of a named pattern

Description

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()

<?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();
}

?>


Draws a rectangle

  • « ImagickDraw::pushPattern
  • ImagickDraw::render »
  • PHP Manual
  • ImagickDraw
  • Draws a rectangle

ImagickDraw::rectangle

(PECL imagick 2.0.0)

ImagickDraw::rectangle — Draws a rectangle

Description

ImagickDraw::rectangle ( float $x1 , float $y1 , float $x2 , float $y2 ) : 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

x1

x coordinate of the top left corner

y1

y coordinate of the top left corner

x2

x coordinate of the bottom right corner

y2

y coordinate of the bottom right corner

Return Values

No value is returned.

Examples

Example #1 ImagickDraw::rectangle()

<?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();
}

?>


Renders all preceding drawing commands onto the image

  • « ImagickDraw::rectangle
  • ImagickDraw::resetVectorGraphics »
  • PHP Manual
  • ImagickDraw
  • Renders all preceding drawing commands onto the image

ImagickDraw::render

(PECL imagick 2.0.0)

ImagickDraw::render — Renders all preceding drawing commands onto the image

Description

ImagickDraw::render ( void ) : 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.


Description

  • « ImagickDraw::render
  • ImagickDraw::rotate »
  • PHP Manual
  • ImagickDraw
  • Description

ImagickDraw::resetVectorGraphics

(No version information available, might only be in Git)

ImagickDraw::resetVectorGraphics — Description

Description

public ImagickDraw::resetVectorGraphics ( void ) : bool

Resets the vector graphics.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.


Applies the specified rotation to the current coordinate space

  • « ImagickDraw::resetVectorGraphics
  • ImagickDraw::roundRectangle »
  • PHP Manual
  • ImagickDraw
  • Applies the specified rotation to the current coordinate space

ImagickDraw::rotate

(PECL imagick 2.0.0)

ImagickDraw::rotate — Applies the specified rotation to the current coordinate space

Description

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()

<?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();
}

?>


Draws a rounded rectangle

  • « ImagickDraw::rotate
  • ImagickDraw::scale »
  • PHP Manual
  • ImagickDraw
  • Draws a rounded rectangle

ImagickDraw::roundRectangle

(PECL imagick 2.0.0)

ImagickDraw::roundRectangle — Draws a rounded rectangle

Description

ImagickDraw::roundRectangle ( float $x1 , float $y1 , float $x2 , float $y2 , float $rx , float $ry ) : 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

x1

x coordinate of the top left corner

y1

y coordinate of the top left corner

x2

x coordinate of the bottom right

y2

y coordinate of the bottom right

rx

x rounding

ry

y rounding

Return Values

No value is returned.

Examples

Example #1 ImagickDraw::roundRectangle()

<?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();
}

?>


Adjusts the scaling factor

  • « ImagickDraw::roundRectangle
  • ImagickDraw::setClipPath »
  • PHP Manual
  • ImagickDraw
  • Adjusts the scaling factor

ImagickDraw::scale

(PECL imagick 2.0.0)

ImagickDraw::scale — Adjusts the scaling factor

Description

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()

<?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();
}

?>


Associates a named clipping path with the image

  • « ImagickDraw::scale
  • ImagickDraw::setClipRule »
  • PHP Manual
  • ImagickDraw
  • Associates a named clipping path with the image

ImagickDraw::setClipPath

(PECL imagick 2.0.0)

ImagickDraw::setClipPath — Associates a named clipping path with the image

Description

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()

<?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();
}

?>


Set the polygon fill rule to be used by the clipping path

  • « ImagickDraw::setClipPath
  • ImagickDraw::setClipUnits »
  • PHP Manual
  • ImagickDraw
  • Set the polygon fill rule to be used by the clipping path

ImagickDraw::setClipRule

(PECL imagick 2.0.0)

ImagickDraw::setClipRule — Set the polygon fill rule to be used by the clipping path

Description

ImagickDraw::setClipRule ( int $fill_rule ) : 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

fill_rule

FILLRULE_ constant

Return Values

No value is returned.

Examples

Example #1 ImagickDraw::setClipRule()

<?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();
}

?>


Sets the interpretation of clip path units

  • « ImagickDraw::setClipRule
  • ImagickDraw::setFillAlpha »
  • PHP Manual
  • ImagickDraw
  • Sets the interpretation of clip path units

ImagickDraw::setClipUnits

(PECL imagick 2.0.0)

ImagickDraw::setClipUnits — Sets the interpretation of clip path units

Description

ImagickDraw::setClipUnits ( int $clip_units ) : bool
Warning

This function is currently not documented; only its argument list is available.

Sets the interpretation of clip path units.

Parameters

clip_units

the number of clip units

Return Values

No value is returned.

Examples

Example #1 ImagickDraw::setClipUnits()

<?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();
}

?>


Sets the opacity to use when drawing using the fill color or fill texture

  • « ImagickDraw::setClipUnits
  • ImagickDraw::setFillColor »
  • PHP Manual
  • ImagickDraw
  • Sets the opacity to use when drawing using the fill color or fill texture

ImagickDraw::setFillAlpha

(PECL imagick 2.0.0)

ImagickDraw::setFillAlpha — Sets the opacity to use when drawing using the fill color or fill texture

Description

ImagickDraw::setFillAlpha ( 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

fill alpha

Return Values

No value is returned.

Examples

Example #1 ImagickDraw::setFillAlpha()

<?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();
}

?>


Sets the fill color to be used for drawing filled objects

  • « ImagickDraw::setFillAlpha
  • ImagickDraw::setFillOpacity »
  • PHP Manual
  • ImagickDraw
  • Sets the fill color to be used for drawing filled objects

ImagickDraw::setFillColor

(PECL imagick 2.0.0)

ImagickDraw::setFillColor — Sets the fill color to be used for drawing filled objects

Description

ImagickDraw::setFillColor ( ImagickPixel $fill_pixel ) : 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_pixel

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();
}

?>


Sets the opacity to use when drawing using the fill color or fill texture

  • « ImagickDraw::setFillColor
  • ImagickDraw::setFillPatternURL »
  • PHP Manual
  • ImagickDraw
  • Sets the opacity to use when drawing using the fill color or fill texture

ImagickDraw::setFillOpacity

(PECL imagick 2.0.0)

ImagickDraw::setFillOpacity — Sets the opacity to use when drawing using the fill color or fill texture

Description

ImagickDraw::setFillOpacity ( float $fillOpacity ) : 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

fillOpacity

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();
}

?>


Sets the URL to use as a fill pattern for filling objects

  • « ImagickDraw::setFillOpacity
  • ImagickDraw::setFillRule »
  • PHP Manual
  • ImagickDraw
  • Sets the URL to use as a fill pattern for filling objects

ImagickDraw::setFillPatternURL

(PECL imagick 2.0.0)

ImagickDraw::setFillPatternURL — Sets the URL to use as a fill pattern for filling objects

Description

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.


Sets the fill rule to use while drawing polygons

  • « ImagickDraw::setFillPatternURL
  • ImagickDraw::setFont »
  • PHP Manual
  • ImagickDraw
  • Sets the fill rule to use while drawing polygons

ImagickDraw::setFillRule

(PECL imagick 2.0.0)

ImagickDraw::setFillRule — Sets the fill rule to use while drawing polygons

Description

ImagickDraw::setFillRule ( int $fill_rule ) : bool
Warning

This function is currently not documented; only its argument list is available.

Sets the fill rule to use while drawing polygons.

Parameters

fill_rule

FILLRULE_ constant

Return Values

No value is returned.

Examples

Example #1 ImagickDraw::setFillRule()

<?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();
}

?>


Sets the fully-specified font to use when annotating with text

  • « ImagickDraw::setFillRule
  • ImagickDraw::setFontFamily »
  • PHP Manual
  • ImagickDraw
  • Sets the fully-specified font to use when annotating with text

ImagickDraw::setFont

(PECL imagick 2.0.0)

ImagickDraw::setFont — Sets the fully-specified font to use when annotating with text

Description

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()

<?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();
}

?>


Sets the font family to use when annotating with text

  • « ImagickDraw::setFont
  • ImagickDraw::setFontSize »
  • PHP Manual
  • ImagickDraw
  • Sets the font family to use when annotating with text

ImagickDraw::setFontFamily

(PECL imagick 2.0.0)

ImagickDraw::setFontFamily — Sets the font family to use when annotating with text

Description

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()

<?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();
}

?>


Sets the font pointsize to use when annotating with text

  • « ImagickDraw::setFontFamily
  • ImagickDraw::setFontStretch »
  • PHP Manual
  • ImagickDraw
  • Sets the font pointsize to use when annotating with text

ImagickDraw::setFontSize

(PECL imagick 2.0.0)

ImagickDraw::setFontSize — Sets the font pointsize to use when annotating with text

Description

ImagickDraw::setFontSize ( float $pointsize ) : 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

pointsize

the point size

Return Values

No value is returned.

Examples

Example #1 ImagickDraw::setFontSize()

<?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();
}

?>


Sets the font stretch to use when annotating with text

  • « ImagickDraw::setFontSize
  • ImagickDraw::setFontStyle »
  • PHP Manual
  • ImagickDraw
  • Sets the font stretch to use when annotating with text

ImagickDraw::setFontStretch

(PECL imagick 2.0.0)

ImagickDraw::setFontStretch — Sets the font stretch to use when annotating with text

Description

ImagickDraw::setFontStretch ( int $fontStretch ) : 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

fontStretch

STRETCH_ constant

Return Values

No value is returned.

Examples

Example #1 ImagickDraw::setFontStretch()

<?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();
}

?>


Sets the font style to use when annotating with text

  • « ImagickDraw::setFontStretch
  • ImagickDraw::setFontWeight »
  • PHP Manual
  • ImagickDraw
  • Sets the font style to use when annotating with text

ImagickDraw::setFontStyle

(PECL imagick 2.0.0)

ImagickDraw::setFontStyle — Sets the font style to use when annotating with text

Description

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

STYLETYPE_ constant

Return Values

No value is returned.

Examples

Example #1 ImagickDraw::setFontStyle()

<?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();
}

?>


Sets the font weight

  • « ImagickDraw::setFontStyle
  • ImagickDraw::setGravity »
  • PHP Manual
  • ImagickDraw
  • Sets the font weight

ImagickDraw::setFontWeight

(PECL imagick 2.0.0)

ImagickDraw::setFontWeight — Sets the font weight

Description

ImagickDraw::setFontWeight ( int $font_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

font_weight

Return Values

Examples

Example #1 ImagickDraw::setFontWeight()

<?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();
}

?>


Sets the text placement gravity

  • « ImagickDraw::setFontWeight
  • ImagickDraw::setResolution »
  • PHP Manual
  • ImagickDraw
  • Sets the text placement gravity

ImagickDraw::setGravity

(PECL imagick 2.0.0)

ImagickDraw::setGravity — Sets the text placement gravity

Description

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

GRAVITY_ constant

Return Values

No value is returned.

Examples

Example #1 ImagickDraw::setGravity()

<?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();
}

?>


Description

  • « ImagickDraw::setGravity
  • ImagickDraw::setStrokeAlpha »
  • PHP Manual
  • ImagickDraw
  • Description

ImagickDraw::setResolution

(No version information available, might only be in Git)

ImagickDraw::setResolution — Description

Description

public ImagickDraw::setResolution ( float $x_resolution , float $y_resolution ) : bool

Sets the resolution.

Parameters

x_resolution

y_resolution

Return Values

Returns TRUE on success.


Specifies the opacity of stroked object outlines

  • « ImagickDraw::setResolution
  • ImagickDraw::setStrokeAntialias »
  • PHP Manual
  • ImagickDraw
  • Specifies the opacity of stroked object outlines

ImagickDraw::setStrokeAlpha

(PECL imagick 2.0.0)

ImagickDraw::setStrokeAlpha — Specifies the opacity of stroked object outlines

Description

ImagickDraw::setStrokeAlpha ( 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

opacity

Return Values

No value is returned.

Examples

Example #1 ImagickDraw::setStrokeAlpha()

<?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();
}

?>


Controls whether stroked outlines are antialiased

  • « ImagickDraw::setStrokeAlpha
  • ImagickDraw::setStrokeColor »
  • PHP Manual
  • ImagickDraw
  • Controls whether stroked outlines are antialiased

ImagickDraw::setStrokeAntialias

(PECL imagick 2.0.0)

ImagickDraw::setStrokeAntialias — Controls whether stroked outlines are antialiased

Description

ImagickDraw::setStrokeAntialias ( bool $stroke_antialias ) : 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

stroke_antialias

the antialias setting

Return Values

No value is returned.

Examples

Example #1 ImagickDraw::setStrokeAntialias()

<?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();
}

?>


Sets the color used for stroking object outlines

  • « ImagickDraw::setStrokeAntialias
  • ImagickDraw::setStrokeDashArray »
  • PHP Manual
  • ImagickDraw
  • Sets the color used for stroking object outlines

ImagickDraw::setStrokeColor

(PECL imagick 2.0.0)

ImagickDraw::setStrokeColor — Sets the color used for stroking object outlines

Description

ImagickDraw::setStrokeColor ( ImagickPixel $stroke_pixel ) : bool
Warning

This function is currently not documented; only its argument list is available.

Sets the color used for stroking object outlines.

Parameters

stroke_pixel

the stroke color

Return Values

No value is returned.

Examples

Example #1 ImagickDraw::setStrokeColor()

<?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();
}

?>


Specifies the pattern of dashes and gaps used to stroke paths

  • « ImagickDraw::setStrokeColor
  • ImagickDraw::setStrokeDashOffset »
  • PHP Manual
  • ImagickDraw
  • Specifies the pattern of dashes and gaps used to stroke paths

ImagickDraw::setStrokeDashArray

(PECL imagick 2.0.0)

ImagickDraw::setStrokeDashArray — Specifies the pattern of dashes and gaps used to stroke paths

Description

ImagickDraw::setStrokeDashArray ( array $dashArray ) : 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

dashArray

array of floats

Return Values

Returns TRUE on success.

Examples

Example #1 ImagickDraw::setStrokeDashArray()

<?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();
}

?>


Specifies the offset into the dash pattern to start the dash

  • « ImagickDraw::setStrokeDashArray
  • ImagickDraw::setStrokeLineCap »
  • PHP Manual
  • ImagickDraw
  • Specifies the offset into the dash pattern to start the dash

ImagickDraw::setStrokeDashOffset

(PECL imagick 2.0.0)

ImagickDraw::setStrokeDashOffset — Specifies the offset into the dash pattern to start the dash

Description

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()

<?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();
}

?>


Specifies the shape to be used at the end of open subpaths when they are stroked

  • « ImagickDraw::setStrokeDashOffset
  • ImagickDraw::setStrokeLineJoin »
  • PHP Manual
  • ImagickDraw
  • Specifies the shape to be used at the end of open subpaths when they are stroked

ImagickDraw::setStrokeLineCap

(PECL imagick 2.0.0)

ImagickDraw::setStrokeLineCap — Specifies the shape to be used at the end of open subpaths when they are stroked

Description

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

LINECAP_ constant

Return Values

No value is returned.

Examples

Example #1 ImagickDraw::setStrokeLineCap()

<?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();
}

?>


Specifies the shape to be used at the corners of paths when they are stroked

  • « ImagickDraw::setStrokeLineCap
  • ImagickDraw::setStrokeMiterLimit »
  • PHP Manual
  • ImagickDraw
  • Specifies the shape to be used at the corners of paths when they are stroked

ImagickDraw::setStrokeLineJoin

(PECL imagick 2.0.0)

ImagickDraw::setStrokeLineJoin — Specifies the shape to be used at the corners of paths when they are stroked

Description

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

LINEJOIN_ constant

Return Values

No value is returned.

Examples

Example #1 ImagickDraw::setStrokeLineJoin()

<?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();
}

?>


Specifies the miter limit

  • « ImagickDraw::setStrokeLineJoin
  • ImagickDraw::setStrokeOpacity »
  • PHP Manual
  • ImagickDraw
  • Specifies the miter limit

ImagickDraw::setStrokeMiterLimit

(PECL imagick 2.0.0)

ImagickDraw::setStrokeMiterLimit — Specifies the miter limit

Description

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()

<?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();
}

?>


Specifies the opacity of stroked object outlines

  • « ImagickDraw::setStrokeMiterLimit
  • ImagickDraw::setStrokePatternURL »
  • PHP Manual
  • ImagickDraw
  • Specifies the opacity of stroked object outlines

ImagickDraw::setStrokeOpacity

(PECL imagick 2.0.0)

ImagickDraw::setStrokeOpacity — Specifies the opacity of stroked object outlines

Description

ImagickDraw::setStrokeOpacity ( float $stroke_opacity ) : bool
Warning

This function is currently not documented; only its argument list is available.

Specifies the opacity of stroked object outlines.

Parameters

stroke_opacity

stroke opacity. 1.0 is fully opaque

Return Values

No value is returned.

Examples

Example #1 ImagickDraw::setStrokeOpacity()

<?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();
}

?>


Sets the pattern used for stroking object outlines

  • « ImagickDraw::setStrokeOpacity
  • ImagickDraw::setStrokeWidth »
  • PHP Manual
  • ImagickDraw
  • Sets the pattern used for stroking object outlines

ImagickDraw::setStrokePatternURL

(PECL imagick 2.0.0)

ImagickDraw::setStrokePatternURL — Sets the pattern used for stroking object outlines

Description

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

imagick.imagickdraw.return.success;


Sets the width of the stroke used to draw object outlines

  • « ImagickDraw::setStrokePatternURL
  • ImagickDraw::setTextAlignment »
  • PHP Manual
  • ImagickDraw
  • Sets the width of the stroke used to draw object outlines

ImagickDraw::setStrokeWidth

(PECL imagick 2.0.0)

ImagickDraw::setStrokeWidth — Sets the width of the stroke used to draw object outlines

Description

ImagickDraw::setStrokeWidth ( float $stroke_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

stroke_width

stroke width

Return Values

No value is returned.

Examples

Example #1 ImagickDraw::setStrokeWidth()

<?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();
}

?>


Specifies a text alignment

  • « ImagickDraw::setStrokeWidth
  • ImagickDraw::setTextAntialias »
  • PHP Manual
  • ImagickDraw
  • Specifies a text alignment

ImagickDraw::setTextAlignment

(PECL imagick 2.0.0)

ImagickDraw::setTextAlignment — Specifies a text alignment

Description

ImagickDraw::setTextAlignment ( int $alignment ) : 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

alignment

ALIGN_ constant

Return Values

No value is returned.

Examples

Example #1 ImagickDraw::setTextAlignment()

<?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();
}

?>


Controls whether text is antialiased

  • « ImagickDraw::setTextAlignment
  • ImagickDraw::setTextDecoration »
  • PHP Manual
  • ImagickDraw
  • Controls whether text is antialiased

ImagickDraw::setTextAntialias

(PECL imagick 2.0.0)

ImagickDraw::setTextAntialias — Controls whether text is antialiased

Description

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()

<?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();
}

?>


Specifies a decoration

  • « ImagickDraw::setTextAntialias
  • ImagickDraw::setTextEncoding »
  • PHP Manual
  • ImagickDraw
  • Specifies a decoration

ImagickDraw::setTextDecoration

(PECL imagick 2.0.0)

ImagickDraw::setTextDecoration — Specifies a decoration

Description

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

DECORATION_ constant

Return Values

No value is returned.

Examples

Example #1 ImagickDraw::setTextDecoration()

<?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();
}

?>


Specifies the text code set

  • « ImagickDraw::setTextDecoration
  • ImagickDraw::setTextInterlineSpacing »
  • PHP Manual
  • ImagickDraw
  • Specifies the text code set

ImagickDraw::setTextEncoding

(PECL imagick 2.0.0)

ImagickDraw::setTextEncoding — Specifies the text code set

Description

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.


Description

  • « ImagickDraw::setTextEncoding
  • ImagickDraw::setTextInterwordSpacing »
  • PHP Manual
  • ImagickDraw
  • Description

ImagickDraw::setTextInterlineSpacing

(No version information available, might only be in Git)

ImagickDraw::setTextInterlineSpacing — Description

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.


Description

  • « ImagickDraw::setTextInterlineSpacing
  • ImagickDraw::setTextKerning »
  • PHP Manual
  • ImagickDraw
  • Description

ImagickDraw::setTextInterwordSpacing

(No version information available, might only be in Git)

ImagickDraw::setTextInterwordSpacing — Description

Description

public ImagickDraw::setTextInterwordSpacing ( float $spacing ) : bool

Sets the text interword spacing.

Parameters

spacing

Return Values

Returns TRUE on success.


Description

  • « ImagickDraw::setTextInterwordSpacing
  • ImagickDraw::setTextUnderColor »
  • PHP Manual
  • ImagickDraw
  • Description

ImagickDraw::setTextKerning

(No version information available, might only be in Git)

ImagickDraw::setTextKerning — Description

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.


Specifies the color of a background rectangle

  • « ImagickDraw::setTextKerning
  • ImagickDraw::setVectorGraphics »
  • PHP Manual
  • ImagickDraw
  • Specifies the color of a background rectangle

ImagickDraw::setTextUnderColor

(PECL imagick 2.0.0)

ImagickDraw::setTextUnderColor — Specifies the color of a background rectangle

Description

ImagickDraw::setTextUnderColor ( ImagickPixel $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()

<?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();
}

?>


Sets the vector graphics

  • « ImagickDraw::setTextUnderColor
  • ImagickDraw::setViewbox »
  • PHP Manual
  • ImagickDraw
  • Sets the vector graphics

ImagickDraw::setVectorGraphics

(PECL imagick 2.0.0)

ImagickDraw::setVectorGraphics — Sets the vector graphics

Description

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()

<?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();
}

?>


Sets the overall canvas size

  • « ImagickDraw::setVectorGraphics
  • ImagickDraw::skewX »
  • PHP Manual
  • ImagickDraw
  • Sets the overall canvas size

ImagickDraw::setViewbox

(PECL imagick 2.0.0)

ImagickDraw::setViewbox — Sets the overall canvas size

Description

ImagickDraw::setViewbox ( int $x1 , int $y1 , int $x2 , int $y2 ) : 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

x1

left x coordinate

y1

left y coordinate

x2

right x coordinate

y2

right y coordinate

Return Values

No value is returned.

Examples

Example #1 ImagickDraw::setViewBox()

<?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();
}

?>


Skews the current coordinate system in the horizontal direction

  • « ImagickDraw::setViewbox
  • ImagickDraw::skewY »
  • PHP Manual
  • ImagickDraw
  • Skews the current coordinate system in the horizontal direction

ImagickDraw::skewX

(PECL imagick 2.0.0)

ImagickDraw::skewX — Skews the current coordinate system in the horizontal direction

Description

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()

<?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();
}

?>


Skews the current coordinate system in the vertical direction

  • « ImagickDraw::skewX
  • ImagickDraw::translate »
  • PHP Manual
  • ImagickDraw
  • Skews the current coordinate system in the vertical direction

ImagickDraw::skewY

(PECL imagick 2.0.0)

ImagickDraw::skewY — Skews the current coordinate system in the vertical direction

Description

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()

<?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();
}

?>


Applies a translation to the current coordinate system

  • « ImagickDraw::skewY
  • ImagickPixel »
  • PHP Manual
  • ImagickDraw
  • Applies a translation to the current coordinate system

ImagickDraw::translate

(PECL imagick 2.0.0)

ImagickDraw::translate — Applies a translation to the current coordinate system

Description

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()

<?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();
}

?>


The ImagickPixel class

(PECL imagick 2.0.0)

Class synopsis

ImagickPixel {
clear ( void ) : bool
__construct ([ string $color ] )
destroy ( void ) : bool
getColor ([ int $normalized = 0 ] ) : array
getColorAsString ( void ) : string
getColorCount ( void ) : int
public getColorQuantum ( void ) : array
getColorValue ( int $color ) : float
public getColorValueQuantum ( int $color ) : number
getHSL ( void ) : array
public getIndex ( void ) : int
isPixelSimilar ( ImagickPixel $color , float $fuzz ) : bool
public isPixelSimilarQuantum ( string $color [, string $fuzz ] ) : bool
isSimilar ( ImagickPixel $color , float $fuzz ) : bool
setColor ( string $color ) : bool
public setcolorcount ( int $colorCount ) : bool
setColorValue ( int $color , float $value ) : bool
public setColorValueQuantum ( int $color , number $value ) : bool
setHSL ( float $hue , float $saturation , float $luminosity ) : bool
public setIndex ( int $index ) : bool
}

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 — Description
  • ImagickPixel::getColorValue — Gets the normalized value of the provided color channel
  • ImagickPixel::getColorValueQuantum — Description
  • ImagickPixel::getHSL — Returns the normalized HSL color of the ImagickPixel object
  • ImagickPixel::getIndex — Description
  • ImagickPixel::isPixelSimilar — Check the distance between this color and another
  • ImagickPixel::isPixelSimilarQuantum — Description
  • ImagickPixel::isSimilar — Check the distance between this color and another
  • ImagickPixel::setColor — Sets the color
  • ImagickPixel::setColorCount — Description
  • ImagickPixel::setColorValue — Sets the normalized value of one of the channels
  • ImagickPixel::setColorValueQuantum — Description
  • ImagickPixel::setHSL — Sets the normalized HSL color
  • ImagickPixel::setIndex — Description


Clears resources associated with this object

  • « ImagickPixel
  • ImagickPixel::__construct »
  • PHP Manual
  • ImagickPixel
  • Clears resources associated with this object

ImagickPixel::clear

(PECL imagick 2.0.0)

ImagickPixel::clear — Clears resources associated with this object

Description

ImagickPixel::clear ( void ) : 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.


The ImagickPixel constructor

  • « ImagickPixel::clear
  • ImagickPixel::destroy »
  • PHP Manual
  • ImagickPixel
  • The ImagickPixel constructor

ImagickPixel::__construct

(PECL imagick 2.0.0)

ImagickPixel::__construct — The ImagickPixel constructor

Description

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();
}

?>


Deallocates resources associated with this object

  • « ImagickPixel::__construct
  • ImagickPixel::getColor »
  • PHP Manual
  • ImagickPixel
  • Deallocates resources associated with this object

ImagickPixel::destroy

(PECL imagick 2.0.0)

ImagickPixel::destroy — Deallocates resources associated with this object

Description

ImagickPixel::destroy ( void ) : 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.


Returns the color

  • « ImagickPixel::destroy
  • ImagickPixel::getColorAsString »
  • PHP Manual
  • ImagickPixel
  • Returns the color

ImagickPixel::getColor

(PECL imagick 2.0.0)

ImagickPixel::getColor — Returns the color

Description

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

Return Values

An array of channel values, each normalized if TRUE is given as param. 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(true);

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
)


Returns the color as a string

  • « ImagickPixel::getColor
  • ImagickPixel::getColorCount »
  • PHP Manual
  • ImagickPixel
  • Returns the color as a string

ImagickPixel::getColorAsString

(PECL imagick 2.1.0)

ImagickPixel::getColorAsString — Returns the color as a string

Description

ImagickPixel::getColorAsString ( void ) : 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.


Returns the color count associated with this color

  • « ImagickPixel::getColorAsString
  • ImagickPixel::getColorQuantum »
  • PHP Manual
  • ImagickPixel
  • Returns the color count associated with this color

ImagickPixel::getColorCount

(PECL imagick 2.0.0)

ImagickPixel::getColorCount — Returns the color count associated with this color

Description

ImagickPixel::getColorCount ( void ) : 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()

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


Description

  • « ImagickPixel::getColorCount
  • ImagickPixel::getColorValue »
  • PHP Manual
  • ImagickPixel
  • Description

ImagickPixel::getColorQuantum

(No version information available, might only be in Git)

ImagickPixel::getColorQuantum — Description

Description

public ImagickPixel::getColorQuantum ( void ) : 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".


Gets the normalized value of the provided color channel

  • « ImagickPixel::getColorQuantum
  • ImagickPixel::getColorValueQuantum »
  • PHP Manual
  • ImagickPixel
  • Gets the normalized value of the provided color channel

ImagickPixel::getColorValue

(PECL imagick 2.0.0)

ImagickPixel::getColorValue — Gets the normalized value of the provided color channel

Description

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


Description

  • « ImagickPixel::getColorValue
  • ImagickPixel::getHSL »
  • PHP Manual
  • ImagickPixel
  • Description

ImagickPixel::getColorValueQuantum

(No version information available, might only be in Git)

ImagickPixel::getColorValueQuantum — Description

Description

public ImagickPixel::getColorValueQuantum ( int $color ) : number

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
        );

?>


Returns the normalized HSL color of the ImagickPixel object

  • « ImagickPixel::getColorValueQuantum
  • ImagickPixel::getIndex »
  • PHP Manual
  • ImagickPixel
  • Returns the normalized HSL color of the ImagickPixel object

ImagickPixel::getHSL

(PECL imagick 2.0.0)

ImagickPixel::getHSL — Returns the normalized HSL color of the ImagickPixel object

Description

ImagickPixel::getHSL ( void ) : 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.

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.


Description

  • « ImagickPixel::getHSL
  • ImagickPixel::isPixelSimilar »
  • PHP Manual
  • ImagickPixel
  • Description

ImagickPixel::getIndex

(No version information available, might only be in Git)

ImagickPixel::getIndex — Description

Description

public ImagickPixel::getIndex ( void ) : int

Gets the colormap index of the pixel wand.

Parameters

This function has no parameters.

Return Values


Check the distance between this color and another

  • « ImagickPixel::getIndex
  • ImagickPixel::isPixelSimilarQuantum »
  • PHP Manual
  • ImagickPixel
  • Check the distance between this color and another

ImagickPixel::isPixelSimilar

(No version information available, might only be in Git)

ImagickPixel::isPixelSimilar — Check the distance between this color and another

Description

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.


Description

  • « ImagickPixel::isPixelSimilar
  • ImagickPixel::isSimilar »
  • PHP Manual
  • ImagickPixel
  • Description

ImagickPixel::isPixelSimilarQuantum

(No version information available, might only be in Git)

ImagickPixel::isPixelSimilarQuantum — Description

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


Check the distance between this color and another

  • « ImagickPixel::isPixelSimilarQuantum
  • ImagickPixel::setColor »
  • PHP Manual
  • ImagickPixel
  • Check the distance between this color and another

ImagickPixel::isSimilar

(PECL imagick 2.0.0)

ImagickPixel::isSimilar — Check the distance between this color and another

Description

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;

?>


Sets the color

  • « ImagickPixel::isSimilar
  • ImagickPixel::setColorCount »
  • PHP Manual
  • ImagickPixel
  • Sets the color

ImagickPixel::setColor

(PECL imagick 2.0.0)

ImagickPixel::setColor — Sets the color

Description

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();
}

?>


Description

  • « ImagickPixel::setColor
  • ImagickPixel::setColorValue »
  • PHP Manual
  • ImagickPixel
  • Description

ImagickPixel::setColorCount

(No version information available, might only be in Git)

ImagickPixel::setColorCount — Description

Description

public ImagickPixel::setcolorcount ( int $colorCount ) : bool

Sets the color count associated with this color.

Parameters

colorCount

Return Values

Returns TRUE on success.


Sets the normalized value of one of the channels

  • « ImagickPixel::setColorCount
  • ImagickPixel::setColorValueQuantum »
  • PHP Manual
  • ImagickPixel
  • Sets the normalized value of one of the channels

ImagickPixel::setColorValue

(PECL imagick 2.0.0)

ImagickPixel::setColorValue — Sets the normalized value of one of the channels

Description

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
)


Description

  • « ImagickPixel::setColorValue
  • ImagickPixel::setHSL »
  • PHP Manual
  • ImagickPixel
  • Description

ImagickPixel::setColorValueQuantum

(No version information available, might only be in Git)

ImagickPixel::setColorValueQuantum — Description

Description

public ImagickPixel::setColorValueQuantum ( int $color , number $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();
}

?>


Sets the normalized HSL color

  • « ImagickPixel::setColorValueQuantum
  • ImagickPixel::setIndex »
  • PHP Manual
  • ImagickPixel
  • Sets the normalized HSL color

ImagickPixel::setHSL

(PECL imagick 2.0.0)

ImagickPixel::setHSL — Sets the normalized HSL color

Description

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.


Description

  • « ImagickPixel::setHSL
  • ImagickPixelIterator »
  • PHP Manual
  • ImagickPixel
  • Description

ImagickPixel::setIndex

(No version information available, might only be in Git)

ImagickPixel::setIndex — Description

Description

public ImagickPixel::setIndex ( int $index ) : bool

Sets the colormap index of the pixel wand.

Parameters

index

Return Values

Returns TRUE on success.


The ImagickPixelIterator class

(PECL imagick 2.0.0)

Class synopsis

ImagickPixelIterator {
clear ( void ) : bool
__construct ( Imagick $wand )
destroy ( void ) : bool
getCurrentIteratorRow ( void ) : array
getIteratorRow ( void ) : int
getNextIteratorRow ( void ) : array
getPreviousIteratorRow ( void ) : array
newPixelIterator ( Imagick $wand ) : bool
newPixelRegionIterator ( Imagick $wand , int $x , int $y , int $columns , int $rows ) : bool
resetIterator ( void ) : bool
setIteratorFirstRow ( void ) : bool
setIteratorLastRow ( void ) : bool
setIteratorRow ( int $row ) : bool
syncIterator ( void ) : bool
}

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


Clear resources associated with a PixelIterator

  • « ImagickPixelIterator
  • ImagickPixelIterator::__construct »
  • PHP Manual
  • ImagickPixelIterator
  • Clear resources associated with a PixelIterator

ImagickPixelIterator::clear

(PECL imagick 2.0.0)

ImagickPixelIterator::clear — Clear resources associated with a PixelIterator

Description

ImagickPixelIterator::clear ( void ) : 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;
}

?>


The ImagickPixelIterator constructor

  • « ImagickPixelIterator::clear
  • ImagickPixelIterator::destroy »
  • PHP Manual
  • ImagickPixelIterator
  • The ImagickPixelIterator constructor

ImagickPixelIterator::__construct

(PECL imagick 2.0.0)

ImagickPixelIterator::__construct — The ImagickPixelIterator constructor

Description

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;
}

?>


Deallocates resources associated with a PixelIterator

  • « ImagickPixelIterator::__construct
  • ImagickPixelIterator::getCurrentIteratorRow »
  • PHP Manual
  • ImagickPixelIterator
  • Deallocates resources associated with a PixelIterator

ImagickPixelIterator::destroy

(PECL imagick 2.0.0)

ImagickPixelIterator::destroy — Deallocates resources associated with a PixelIterator

Description

ImagickPixelIterator::destroy ( void ) : 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.


Returns the current row of ImagickPixel objects

  • « ImagickPixelIterator::destroy
  • ImagickPixelIterator::getIteratorRow »
  • PHP Manual
  • ImagickPixelIterator
  • Returns the current row of ImagickPixel objects

ImagickPixelIterator::getCurrentIteratorRow

(PECL imagick 2.0.0)

ImagickPixelIterator::getCurrentIteratorRow — Returns the current row of ImagickPixel objects

Description

ImagickPixelIterator::getCurrentIteratorRow ( void ) : 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.


Returns the current pixel iterator row

  • « ImagickPixelIterator::getCurrentIteratorRow
  • ImagickPixelIterator::getNextIteratorRow »
  • PHP Manual
  • ImagickPixelIterator
  • Returns the current pixel iterator row

ImagickPixelIterator::getIteratorRow

(PECL imagick 2.0.0)

ImagickPixelIterator::getIteratorRow — Returns the current pixel iterator row

Description

ImagickPixelIterator::getIteratorRow ( void ) : 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.


Returns the next row of the pixel iterator

  • « ImagickPixelIterator::getIteratorRow
  • ImagickPixelIterator::getPreviousIteratorRow »
  • PHP Manual
  • ImagickPixelIterator
  • Returns the next row of the pixel iterator

ImagickPixelIterator::getNextIteratorRow

(PECL imagick 2.0.0)

ImagickPixelIterator::getNextIteratorRow — Returns the next row of the pixel iterator

Description

ImagickPixelIterator::getNextIteratorRow ( void ) : 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;
}

?>


Returns the previous row

  • « ImagickPixelIterator::getNextIteratorRow
  • ImagickPixelIterator::newPixelIterator »
  • PHP Manual
  • ImagickPixelIterator
  • Returns the previous row

ImagickPixelIterator::getPreviousIteratorRow

(PECL imagick 2.0.0)

ImagickPixelIterator::getPreviousIteratorRow — Returns the previous row

Description

ImagickPixelIterator::getPreviousIteratorRow ( void ) : 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.


Returns a new pixel iterator

  • « ImagickPixelIterator::getPreviousIteratorRow
  • ImagickPixelIterator::newPixelRegionIterator »
  • PHP Manual
  • ImagickPixelIterator
  • Returns a new pixel iterator

ImagickPixelIterator::newPixelIterator

(PECL imagick 2.0.0)

ImagickPixelIterator::newPixelIterator — Returns a new pixel iterator

Description

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.


Returns a new pixel iterator

  • « ImagickPixelIterator::newPixelIterator
  • ImagickPixelIterator::resetIterator »
  • PHP Manual
  • ImagickPixelIterator
  • Returns a new pixel iterator

ImagickPixelIterator::newPixelRegionIterator

(PECL imagick 2.0.0)

ImagickPixelIterator::newPixelRegionIterator — Returns a new pixel iterator

Description

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.


Resets the pixel iterator

  • « ImagickPixelIterator::newPixelRegionIterator
  • ImagickPixelIterator::setIteratorFirstRow »
  • PHP Manual
  • ImagickPixelIterator
  • Resets the pixel iterator

ImagickPixelIterator::resetIterator

(PECL imagick 2.0.0)

ImagickPixelIterator::resetIterator — Resets the pixel iterator

Description

ImagickPixelIterator::resetIterator ( void ) : 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;
}

?>


Sets the pixel iterator to the first pixel row

  • « ImagickPixelIterator::resetIterator
  • ImagickPixelIterator::setIteratorLastRow »
  • PHP Manual
  • ImagickPixelIterator
  • Sets the pixel iterator to the first pixel row

ImagickPixelIterator::setIteratorFirstRow

(PECL imagick 2.0.0)

ImagickPixelIterator::setIteratorFirstRow — Sets the pixel iterator to the first pixel row

Description

ImagickPixelIterator::setIteratorFirstRow ( void ) : 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.


Sets the pixel iterator to the last pixel row

  • « ImagickPixelIterator::setIteratorFirstRow
  • ImagickPixelIterator::setIteratorRow »
  • PHP Manual
  • ImagickPixelIterator
  • Sets the pixel iterator to the last pixel row

ImagickPixelIterator::setIteratorLastRow

(PECL imagick 2.0.0)

ImagickPixelIterator::setIteratorLastRow — Sets the pixel iterator to the last pixel row

Description

ImagickPixelIterator::setIteratorLastRow ( void ) : 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.


Set the pixel iterator row

  • « ImagickPixelIterator::setIteratorLastRow
  • ImagickPixelIterator::syncIterator »
  • PHP Manual
  • ImagickPixelIterator
  • Set the pixel iterator row

ImagickPixelIterator::setIteratorRow

(PECL imagick 2.0.0)

ImagickPixelIterator::setIteratorRow — Set the pixel iterator row

Description

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;
}

?>


Syncs the pixel iterator

  • « ImagickPixelIterator::setIteratorRow
  • ImagickKernel »
  • PHP Manual
  • ImagickPixelIterator
  • Syncs the pixel iterator

ImagickPixelIterator::syncIterator

(PECL imagick 2.0.0)

ImagickPixelIterator::syncIterator — Syncs the pixel iterator

Description

ImagickPixelIterator::syncIterator ( void ) : bool
Warning

This function is currently not documented; only its argument list is available.

Syncs the pixel iterator.

Return Values

Returns TRUE on success.


The ImagickKernel class

(PECL imagick >= 3.3.0)

Introduction

Class synopsis

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 ( void ) : array
public scale ( float $scale [, int $normalizeFlag ] ) : void
public separate ( void ) : array
}

Table of Contents

  • ImagickKernel::addKernel — Description
  • ImagickKernel::addUnityKernel — Description
  • ImagickKernel::fromBuiltIn — Description
  • ImagickKernel::fromMatrix — Description
  • ImagickKernel::getMatrix — Description
  • ImagickKernel::scale — Description
  • ImagickKernel::separate — Description


Description

  • « ImagickKernel
  • ImagickKernel::addUnityKernel »
  • PHP Manual
  • ImagickKernel
  • Description

ImagickKernel::addKernel

(PECL imagick >= 3.3.0)

ImagickKernel::addKernel — Description

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();

}

?>


Description

  • « ImagickKernel::addKernel
  • ImagickKernel::fromBuiltIn »
  • PHP Manual
  • ImagickKernel
  • Description

ImagickKernel::addUnityKernel

(PECL imagick >= 3.3.0)

ImagickKernel::addUnityKernel — Description

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();

}

?>


Description

  • « ImagickKernel::addUnityKernel
  • ImagickKernel::fromMatrix »
  • PHP Manual
  • ImagickKernel
  • Description

ImagickKernel::fromBuiltIn

(PECL imagick >= 3.3.0)

ImagickKernel::fromBuiltIn — Description

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);

?>


Description

  • « ImagickKernel::fromBuiltIn
  • ImagickKernel::getMatrix »
  • PHP Manual
  • ImagickKernel
  • Description

ImagickKernel::fromMatrix

(PECL imagick >= 3.3.0)

ImagickKernel::fromMatrix — Description

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();
}

?>


Description

  • « ImagickKernel::fromMatrix
  • ImagickKernel::scale »
  • PHP Manual
  • ImagickKernel
  • Description

ImagickKernel::getMatrix

(PECL imagick >= 3.3.0)

ImagickKernel::getMatrix — Description

Description

public ImagickKernel::getMatrix ( void ) : 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;

?>


Description

  • « ImagickKernel::getMatrix
  • ImagickKernel::separate »
  • PHP Manual
  • ImagickKernel
  • Description

ImagickKernel::scale

(PECL imagick >= 3.3.0)

ImagickKernel::scale — Description

Description

public ImagickKernel::scale ( float $scale [, int $normalizeFlag ] ) : void

ScaleKernelInfo() 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. Flag should be one of Imagick::NORMALIZE_KERNEL_VALUE, Imagick::NORMALIZE_KERNEL_CORRELATE, Imagick::NORMALIZE_KERNEL_PERCENT or not set.

Parameters

This function has no parameters.

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;
?>


Description

  • « ImagickKernel::scale
  • Mail Related Extensions »
  • PHP Manual
  • ImagickKernel
  • Description

ImagickKernel::separate

(PECL imagick >= 3.3.0)

ImagickKernel::separate — Description

Description

public ImagickKernel::separate ( void ) : 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;

?>


Mail Related Extensions

  • Cyrus — Cyrus IMAP administration
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Cyrus Functions
  • IMAP — IMAP, POP3 and NNTP
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • IMAP Functions
  • Mail
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Mail Functions
  • Mailparse
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Mailparse Functions
  • vpopmail
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • vpopmail Functions


Cyrus IMAP administration

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Cyrus Functions
    • cyrus_authenticate — Authenticate against a Cyrus IMAP server
    • cyrus_bind — Bind callbacks to a Cyrus IMAP connection
    • cyrus_close — Close connection to a Cyrus IMAP server
    • cyrus_connect — Connect to a Cyrus IMAP server
    • cyrus_query — Send a query to a Cyrus IMAP server
    • cyrus_unbind — Unbind ...


Introduction

Note: This extension is not available on Windows platforms.

Note:

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.0.0.


Installation

To enable Cyrus IMAP support and to use these functions you have to compile PHP with the --with-cyrus option.

Warning

The IMAP, recode, YAZ and Cyrus 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
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

This extension defines a Cyrus IMAP connection identifier returned by cyrus_connect().


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.

CYRUS_CONN_NONSYNCLITERAL (integer)
CYRUS_CONN_INITIALRESPONSE (integer)
CYRUS_CALLBACK_NUMBERED (integer)
CYRUS_CALLBACK_NOLITERAL (integer)


Cyrus Functions

Table of Contents

  • cyrus_authenticate — Authenticate against a Cyrus IMAP server
  • cyrus_bind — Bind callbacks to a Cyrus IMAP connection
  • cyrus_close — Close connection to a Cyrus IMAP server
  • cyrus_connect — Connect to a Cyrus IMAP server
  • cyrus_query — Send a query to a Cyrus IMAP server
  • cyrus_unbind — Unbind ...


Authenticate against a Cyrus IMAP server

  • « Cyrus Functions
  • cyrus_bind »
  • PHP Manual
  • Cyrus Functions
  • Authenticate against a Cyrus IMAP server

cyrus_authenticate

(PHP 4 >= 4.1.0, PECL cyrus 1.0)

cyrus_authenticate — Authenticate against a Cyrus IMAP server

Description

cyrus_authenticate ( resource $connection [, string $mechlist [, string $service [, string $user [, int $minssf [, int $maxssf [, string $authname [, string $password ]]]]]]] ) : void
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.


Bind callbacks to a Cyrus IMAP connection

  • « cyrus_authenticate
  • cyrus_close »
  • PHP Manual
  • Cyrus Functions
  • Bind callbacks to a Cyrus IMAP connection

cyrus_bind

(PHP 4 >= 4.1.0, PECL cyrus 1.0)

cyrus_bind — Bind callbacks to a Cyrus IMAP connection

Description

cyrus_bind ( resource $connection , array $callbacks ) : bool

Binds callbacks to a Cyrus IMAP connection.

Parameters

connection

The connection handle.

callbacks

An array of callbacks.

Return Values

Returns TRUE on success or FALSE on failure.


Close connection to a Cyrus IMAP server

  • « cyrus_bind
  • cyrus_connect »
  • PHP Manual
  • Cyrus Functions
  • Close connection to a Cyrus IMAP server

cyrus_close

(PHP 4 >= 4.1.0, PECL cyrus 1.0)

cyrus_close — Close connection to a Cyrus IMAP server

Description

cyrus_close ( resource $connection ) : bool

Closes the connection to a Cyrus IMAP server.

Parameters

connection

The connection handle.

Return Values

Returns TRUE on success or FALSE on failure.


Connect to a Cyrus IMAP server

  • « cyrus_close
  • cyrus_query »
  • PHP Manual
  • Cyrus Functions
  • Connect to a Cyrus IMAP server

cyrus_connect

(PHP 4 >= 4.1.0, PECL cyrus 1.0)

cyrus_connect — Connect to a Cyrus IMAP server

Description

cyrus_connect ([ string $host [, string $port [, int $flags ]]] ) : resource

Connects to a Cyrus IMAP server.

Parameters

host

The Cyrus IMAP host name.

port

The port number.

flags

Return Values

Returns a connection handler on success or FALSE on failure.


Send a query to a Cyrus IMAP server

  • « cyrus_connect
  • cyrus_unbind »
  • PHP Manual
  • Cyrus Functions
  • Send a query to a Cyrus IMAP server

cyrus_query

(PHP 4 >= 4.1.0, PECL cyrus 1.0)

cyrus_query — Send a query to a Cyrus IMAP server

Description

cyrus_query ( resource $connection , string $query ) : array

Sends a query to a Cyrus IMAP server.

Parameters

connection

The connection handle.

query

The query string.

Return Values

Returns an associative array with the following keys: text, msgno, and keyword.


Unbind ...

  • « cyrus_query
  • IMAP »
  • PHP Manual
  • Cyrus Functions
  • Unbind ...

cyrus_unbind

(PHP 4 >= 4.1.0, PECL cyrus 1.0)

cyrus_unbind — Unbind ...

Description

cyrus_unbind ( resource $connection , string $trigger_name ) : bool
Warning

This function is currently not documented; only its argument list is available.

Parameters

connection

The connection handle.

trigger_name

The trigger name.

Return Values

Returns TRUE on success or FALSE on failure.


IMAP, POP3 and NNTP

  • Introduction
  • 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_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_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_mail — Send an email message
    • 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_to_mutf7 — Encode a UTF-8 string to modified UTF-7
    • imap_utf8 — Converts MIME-encoded text to UTF-8


Introduction

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.


Requirements

This extension requires the c-client library to be installed. Grab the latest version from » https://www.washington.edu/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

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.

IMAP is not supported on systems earlier than Windows 2000. This is because it uses encryption functions in order to enable SSL connections to the mail servers.

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, recode, YAZ and Cyrus 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" | PHP_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 PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

imap.enable_insecure_rsh boolean

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.


  • « Runtime Configuration
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

The imap resource 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 (integer)
OP_DEBUG (integer)
OP_READONLY (integer)
Open mailbox read-only
OP_ANONYMOUS (integer)
Don't use or update a .newsrc for news (NNTP only)
OP_SHORTCACHE (integer)
OP_SILENT (integer)
OP_PROTOTYPE (integer)
OP_HALFOPEN (integer)
For IMAP and NNTP names, open a connection but don't open a mailbox.
OP_EXPUNGE (integer)
OP_SECURE (integer)
CL_EXPUNGE (integer)
silently expunge the mailbox before closing when calling imap_close()
FT_UID (integer)
The parameter is a UID
FT_PEEK (integer)
Do not set the \Seen flag if not already set
FT_NOT (integer)
FT_INTERNAL (integer)
The return string is in internal format, will not canonicalize to CRLF.
FT_PREFETCHTEXT (integer)
ST_UID (integer)
The sequence argument contains UIDs instead of sequence numbers
ST_SILENT (integer)
ST_SET (integer)
CP_UID (integer)
the sequence numbers contain UIDS
CP_MOVE (integer)
Delete the messages from the current mailbox after copying with imap_mail_copy()
SE_UID (integer)
Return UIDs instead of sequence numbers
SE_FREE (integer)
SE_NOPREFETCH (integer)
Don't prefetch searched messages
SO_FREE (integer)
SO_NOSERVER (integer)
SA_MESSAGES (integer)
SA_RECENT (integer)
SA_UNSEEN (integer)
SA_UIDNEXT (integer)
SA_UIDVALIDITY (integer)
SA_ALL (integer)
LATT_NOINFERIORS (integer)
This mailbox has no "children" (there are no mailboxes below this one).
LATT_NOSELECT (integer)
This is only a container, not a mailbox - you cannot open it.
LATT_MARKED (integer)
This mailbox is marked. Only used by UW-IMAPD.
LATT_UNMARKED (integer)
This mailbox is not marked. Only used by UW-IMAPD.
LATT_REFERRAL (integer)
This container has a referral to a remote mailbox.
LATT_HASCHILDREN (integer)
This mailbox has selectable inferiors.
LATT_HASNOCHILDREN (integer)
This mailbox has no selectable inferiors.
SORTDATE (integer)
Sort criteria for imap_sort(): message Date
SORTARRIVAL (integer)
Sort criteria for imap_sort(): arrival date
SORTFROM (integer)
Sort criteria for imap_sort(): mailbox in first From address
SORTSUBJECT (integer)
Sort criteria for imap_sort(): message subject
SORTTO (integer)
Sort criteria for imap_sort(): mailbox in first To address
SORTCC (integer)
Sort criteria for imap_sort(): mailbox in first cc address
SORTSIZE (integer)
Sort criteria for imap_sort(): size of message in octets
TYPETEXT (integer)
Primary body type: unformatted text
TYPEMULTIPART (integer)
Primary body type: multiple part
TYPEMESSAGE (integer)
Primary body type: encapsulated message
TYPEAPPLICATION (integer)
Primary body type: application data
TYPEAUDIO (integer)
Primary body type: audio
TYPEIMAGE (integer)
Primary body type: static image
TYPEVIDEO (integer)
Primary body type: video
TYPEMODEL (integer)
Primary body type: model
TYPEOTHER (integer)
Primary body type: unknown
ENC7BIT (integer)
Body encoding: 7 bit SMTP semantic data
ENC8BIT (integer)
Body encoding: 8 bit SMTP semantic data
ENCBINARY (integer)
Body encoding: 8 bit binary data
ENCBASE64 (integer)
Body encoding: base-64 encoded data
ENCQUOTEDPRINTABLE (integer)
Body encoding: human-readable 8-as-7 bit data
ENCOTHER (integer)
Body encoding: unknown
IMAP_OPENTIMEOUT (integer)
IMAP_READTIMEOUT (integer)
IMAP_WRITETIMEOUT (integer)
IMAP_CLOSETIMEOUT (integer)
IMAP_GC_ELT (integer)
Garbage collector, clear message cache elements.
IMAP_GC_ENV (integer)
Garbage collector, clear envelopes and bodies.
IMAP_GC_TEXTS (integer)
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.

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_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_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_mail — Send an email message
  • 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_to_mutf7 — Encode a UTF-8 string to modified UTF-7
  • imap_utf8 — Converts MIME-encoded text to UTF-8


Convert an 8bit string to a quoted-printable string

  • « IMAP Functions
  • imap_alerts »
  • PHP Manual
  • IMAP Functions
  • Convert an 8bit string to a quoted-printable string

imap_8bit

(PHP 4, PHP 5, PHP 7)

imap_8bit — Convert an 8bit string to a quoted-printable string

Description

imap_8bit ( string $string ) : string

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.

See Also

  • imap_qprint() - Convert a quoted-printable string to an 8 bit string


Returns all IMAP alert messages that have occurred

  • « imap_8bit
  • imap_append »
  • PHP Manual
  • IMAP Functions
  • Returns all IMAP alert messages that have occurred

imap_alerts

(PHP 4, PHP 5, PHP 7)

imap_alerts — Returns all IMAP alert messages that have occurred

Description

imap_alerts ( void ) : array

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.

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


Append a string message to a specified mailbox

  • « imap_alerts
  • imap_base64 »
  • PHP Manual
  • IMAP Functions
  • Append a string message to a specified mailbox

imap_append

(PHP 4, PHP 5, PHP 7)

imap_append — Append a string message to a specified mailbox

Description

imap_append ( resource $imap_stream , string $mailbox , string $message [, string $options = NULL [, string $internal_date = NULL ]] ) : bool

Appends a string message to the specified mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

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.

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 mailbox

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
5.3.2 | Added INTERNALDATE support to imap_append.

Examples

Example #1 imap_append() example

<?php
$stream = imap_open("{imap.example.org}INBOX.Drafts", "username", "password");

$check = imap_check($stream);
echo "Msg Count before append: ". $check->Nmsgs . "\n";

imap_append($stream, "{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($stream);
echo "Msg Count after append : ". $check->Nmsgs . "\n";

imap_close($stream);
?>


Decode BASE64 encoded text

  • « imap_append
  • imap_binary »
  • PHP Manual
  • IMAP Functions
  • Decode BASE64 encoded text

imap_base64

(PHP 4, PHP 5, PHP 7)

imap_base64 — Decode BASE64 encoded text

Description

imap_base64 ( string $text ) : string

Decodes the given BASE-64 encoded text.

Parameters

text

The encoded text

Return Values

Returns the decoded message as a string.

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


Convert an 8bit string to a base64 string

  • « imap_base64
  • imap_body »
  • PHP Manual
  • IMAP Functions
  • Convert an 8bit string to a base64 string

imap_binary

(PHP 4, PHP 5, PHP 7)

imap_binary — Convert an 8bit string to a base64 string

Description

imap_binary ( string $string ) : string

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.

See Also

  • imap_base64() - Decode BASE64 encoded text


Read the message body

  • « imap_binary
  • imap_bodystruct »
  • PHP Manual
  • IMAP Functions
  • Read the message body

imap_body

(PHP 4, PHP 5, PHP 7)

imap_body — Read the message body

Description

imap_body ( resource $imap_stream , int $msg_number [, int $options = 0 ] ) : string

imap_body() returns the body of the message, numbered msg_number 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_stream

An IMAP stream returned by imap_open().

msg_number

The message number

options

The optional options are a bit mask with one or more of the following:

  • FT_UID - The msg_number 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.


Read the structure of a specified body section of a specific message

  • « imap_body
  • imap_check »
  • PHP Manual
  • IMAP Functions
  • Read the structure of a specified body section of a specific message

imap_bodystruct

(PHP 4, PHP 5, PHP 7)

imap_bodystruct — Read the structure of a specified body section of a specific message

Description

imap_bodystruct ( resource $imap_stream , int $msg_number , string $section ) : object

Read the structure of a specified body section of a specific message.

Parameters

imap_stream

An IMAP stream returned by imap_open().

msg_number

The message number

section

The body section to read

Return Values

Returns the information in an object, for a detailed description of the object structure and properties see imap_fetchstructure().

See Also

  • imap_fetchstructure() - Read the structure of a particular message


Check current mailbox

  • « imap_bodystruct
  • imap_clearflag_full »
  • PHP Manual
  • IMAP Functions
  • Check current mailbox

imap_check

(PHP 4, PHP 5, PHP 7)

imap_check — Check current mailbox

Description

imap_check ( resource $imap_stream ) : object

Checks information about the current mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

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.

Examples

Example #1 imap_check() example

<?php

$imap_obj = imap_check($imap_stream);
var_dump($imap_obj);

?>

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)
}


Clears flags on messages

  • « imap_check
  • imap_close »
  • PHP Manual
  • IMAP Functions
  • Clears flags on messages

imap_clearflag_full

(PHP 4, PHP 5, PHP 7)

imap_clearflag_full — Clears flags on messages

Description

imap_clearflag_full ( resource $imap_stream , string $sequence , string $flag [, int $options = 0 ] ) : bool

This function causes a store to delete the specified flag to the flags set for the messages in the specified sequence.

Parameters

imap_stream

An IMAP stream returned by imap_open().

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

Returns TRUE on success or FALSE on failure.

See Also

  • imap_setflag_full() - Sets flags on messages


Close an IMAP stream

  • « imap_clearflag_full
  • imap_create »
  • PHP Manual
  • IMAP Functions
  • Close an IMAP stream

imap_close

(PHP 4, PHP 5, PHP 7)

imap_close — Close an IMAP stream

Description

imap_close ( resource $imap_stream [, int $flag = 0 ] ) : bool

Closes the imap stream.

Parameters

imap_stream

An IMAP stream returned by imap_open().

flag

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

Returns TRUE on success or FALSE on failure.

See Also

  • imap_open() - Open an IMAP stream to a mailbox


Alias of imap_createmailbox

  • « imap_close
  • imap_createmailbox »
  • PHP Manual
  • IMAP Functions
  • Alias of imap_createmailbox

imap_create

(PHP 4, PHP 5, PHP 7)

imap_create — Alias of imap_createmailbox()

Description

This function is an alias of: imap_createmailbox().


Create a new mailbox

  • « imap_create
  • imap_delete »
  • PHP Manual
  • IMAP Functions
  • Create a new mailbox

imap_createmailbox

(PHP 4, PHP 5, PHP 7)

imap_createmailbox — Create a new mailbox

Description

imap_createmailbox ( resource $imap_stream , string $mailbox ) : bool

Creates a new mailbox specified by mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

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.

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


Mark a message for deletion from current mailbox

  • « imap_createmailbox
  • imap_deletemailbox »
  • PHP Manual
  • IMAP Functions
  • Mark a message for deletion from current mailbox

imap_delete

(PHP 4, PHP 5, PHP 7)

imap_delete — Mark a message for deletion from current mailbox

Description

imap_delete ( resource $imap_stream , int $msg_number [, int $options = 0 ] ) : bool

Marks messages listed in msg_number 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_stream

An IMAP stream returned by imap_open().

msg_number

The message number

options

You can set the FT_UID which tells the function to treat the msg_number argument as a UID.

Return Values

Returns TRUE.

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


Delete a mailbox

  • « imap_delete
  • imap_errors »
  • PHP Manual
  • IMAP Functions
  • Delete a mailbox

imap_deletemailbox

(PHP 4, PHP 5, PHP 7)

imap_deletemailbox — Delete a mailbox

Description

imap_deletemailbox ( resource $imap_stream , string $mailbox ) : bool

Deletes the specified mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

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.

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


Returns all of the IMAP errors that have occurred

  • « imap_deletemailbox
  • imap_expunge »
  • PHP Manual
  • IMAP Functions
  • Returns all of the IMAP errors that have occurred

imap_errors

(PHP 4, PHP 5, PHP 7)

imap_errors — Returns all of the IMAP errors that have occurred

Description

imap_errors ( void ) : array

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.

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


Delete all messages marked for deletion

  • « imap_errors
  • imap_fetch_overview »
  • PHP Manual
  • IMAP Functions
  • Delete all messages marked for deletion

imap_expunge

(PHP 4, PHP 5, PHP 7)

imap_expunge — Delete all messages marked for deletion

Description

imap_expunge ( resource $imap_stream ) : bool

Deletes all the messages marked for deletion by imap_delete(), imap_mail_move(), or imap_setflag_full().

Parameters

imap_stream

An IMAP stream returned by imap_open().

Return Values

Returns TRUE.


Read an overview of the information in the headers of the given message

  • « imap_expunge
  • imap_fetchbody »
  • PHP Manual
  • IMAP Functions
  • Read an overview of the information in the headers of the given message

imap_fetch_overview

(PHP 4, PHP 5, PHP 7)

imap_fetch_overview — Read an overview of the information in the headers of the given message

Description

imap_fetch_overview ( resource $imap_stream , string $sequence [, int $options = 0 ] ) : array

This function fetches mail headers for the given sequence and returns an overview of their contents.

Parameters

imap_stream

An IMAP stream returned by imap_open().

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

options

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

Changelog

Version | Description
5.3.3 | Add the udate property.

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


Fetch a particular section of the body of the message

  • « imap_fetch_overview
  • imap_fetchheader »
  • PHP Manual
  • IMAP Functions
  • Fetch a particular section of the body of the message

imap_fetchbody

(PHP 4, PHP 5, PHP 7)

imap_fetchbody — Fetch a particular section of the body of the message

Description

imap_fetchbody ( resource $imap_stream , int $msg_number , string $section [, int $options = 0 ] ) : string

Fetch of a particular section of the body of the specified messages. Body parts are not decoded by this function.

Parameters

imap_stream

An IMAP stream returned by imap_open().

msg_number

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

options

A bitmask with one or more of the following:

  • FT_UID - The msg_number 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.

See Also

  • imap_savebody() - Save a specific body section to a file
  • imap_fetchstructure() - Read the structure of a particular message


Returns header for a message

  • « imap_fetchbody
  • imap_fetchmime »
  • PHP Manual
  • IMAP Functions
  • Returns header for a message

imap_fetchheader

(PHP 4, PHP 5, PHP 7)

imap_fetchheader — Returns header for a message

Description

imap_fetchheader ( resource $imap_stream , int $msg_number [, int $options = 0 ] ) : string

This function causes a fetch of the complete, unfiltered » RFC2822 format header of the specified message.

Parameters

imap_stream

An IMAP stream returned by imap_open().

msg_number

The message number

options

The possible options are:

  • FT_UID - The msgno 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.

See Also

  • imap_fetch_overview() - Read an overview of the information in the headers of the given message


Fetch MIME headers for a particular section of the message

  • « imap_fetchheader
  • imap_fetchstructure »
  • PHP Manual
  • IMAP Functions
  • Fetch MIME headers for a particular section of the message

imap_fetchmime

(PHP 5 >= 5.3.6, PHP 7)

imap_fetchmime — Fetch MIME headers for a particular section of the message

Description

imap_fetchmime ( resource $imap_stream , int $msg_number , string $section [, int $options = 0 ] ) : string

Fetch the MIME headers of a particular section of the body of the specified messages.

Parameters

imap_stream

An IMAP stream returned by imap_open().

msg_number

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

options

A bitmask with one or more of the following:

  • FT_UID - The msg_number 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.

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


Read the structure of a particular message

  • « imap_fetchmime
  • imap_fetchtext »
  • PHP Manual
  • IMAP Functions
  • Read the structure of a particular message

imap_fetchstructure

(PHP 4, PHP 5, PHP 7)

imap_fetchstructure — Read the structure of a particular message

Description

imap_fetchstructure ( resource $imap_stream , int $msg_number [, int $options = 0 ] ) : object

Fetches all the structured information for a given message.

Parameters

imap_stream

An IMAP stream returned by imap_open().

msg_number

The message number

options

This optional parameter only has a single option, FT_UID, which tells the function to treat the msg_number argument as a UID.

Return Values

Returns an object includes the envelope, internal date, size, flags and body structure along with a similar object for each mime attachment. The structure of the returned objects is as follows:

Returned Objects 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

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


Alias of imap_body

  • « imap_fetchstructure
  • imap_gc »
  • PHP Manual
  • IMAP Functions
  • Alias of imap_body

imap_fetchtext

(PHP 4, PHP 5, PHP 7)

imap_fetchtext — Alias of imap_body()

Description

This function is an alias of: imap_body().


Clears IMAP cache

  • « imap_fetchtext
  • imap_get_quota »
  • PHP Manual
  • IMAP Functions
  • Clears IMAP cache

imap_gc

(PHP 5 >= 5.3.0, PHP 7)

imap_gc — Clears IMAP cache

Description

imap_gc ( resource $imap_stream , int $caches ) : bool

Purges the cache of entries of a specific type.

Parameters

imap_stream

An IMAP stream returned by imap_open().

caches

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

Returns TRUE on success or FALSE on failure.

Examples

Example #1 imap_gc() example

<?php

$mbox = imap_open("{imap.example.org:143}", "username", "password");

imap_gc($mbox, IMAP_GC_ELT);

?>


Retrieve the quota level settings, and usage statics per mailbox

  • « imap_gc
  • imap_get_quotaroot »
  • PHP Manual
  • IMAP Functions
  • Retrieve the quota level settings, and usage statics per mailbox

imap_get_quota

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

imap_get_quota — Retrieve the quota level settings, and usage statics per mailbox

Description

imap_get_quota ( resource $imap_stream , string $quota_root ) : array

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_stream

An IMAP stream returned by imap_open().

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.

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_stream 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


Retrieve the quota settings per user

  • « imap_get_quota
  • imap_getacl »
  • PHP Manual
  • IMAP Functions
  • Retrieve the quota settings per user

imap_get_quotaroot

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

imap_get_quotaroot — Retrieve the quota settings per user

Description

imap_get_quotaroot ( resource $imap_stream , string $quota_root ) : array

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_stream

An IMAP stream returned by imap_open().

quota_root

quota_root 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.

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_stream 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


Gets the ACL for a given mailbox

  • « imap_get_quotaroot
  • imap_getmailboxes »
  • PHP Manual
  • IMAP Functions
  • Gets the ACL for a given mailbox

imap_getacl

(PHP 5, PHP 7)

imap_getacl — Gets the ACL for a given mailbox

Description

imap_getacl ( resource $imap_stream , string $mailbox ) : array

Gets the ACL for a given mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

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.

Examples

Example #1 imap_getacl() example

<?php

print_r(imap_getacl($conn_id, '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


Read the list of mailboxes, returning detailed information on each one

  • « imap_getacl
  • imap_getsubscribed »
  • PHP Manual
  • IMAP Functions
  • Read the list of mailboxes, returning detailed information on each one

imap_getmailboxes

(PHP 4, PHP 5, PHP 7)

imap_getmailboxes — Read the list of mailboxes, returning detailed information on each one

Description

imap_getmailboxes ( resource $imap_stream , string $ref , string $pattern ) : array

Gets information on the mailboxes.

Parameters

imap_stream

An IMAP stream returned by imap_open().

ref

ref 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.

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


List all the subscribed mailboxes

  • « imap_getmailboxes
  • imap_header »
  • PHP Manual
  • IMAP Functions
  • List all the subscribed mailboxes

imap_getsubscribed

(PHP 4, PHP 5, PHP 7)

imap_getsubscribed — List all the subscribed mailboxes

Description

imap_getsubscribed ( resource $imap_stream , string $ref , string $pattern ) : array

Gets information about the subscribed mailboxes.

Identical to imap_getmailboxes(), except that it only returns mailboxes that the user is subscribed to.

Parameters

imap_stream

An IMAP stream returned by imap_open().

ref

ref 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.


Alias of imap_headerinfo

  • « imap_getsubscribed
  • imap_headerinfo »
  • PHP Manual
  • IMAP Functions
  • Alias of imap_headerinfo

imap_header

(PHP 4, PHP 5, PHP 7)

imap_header — Alias of imap_headerinfo()

Description

This function is an alias of: imap_headerinfo().


Read the header of the message

  • « imap_header
  • imap_headers »
  • PHP Manual
  • IMAP Functions
  • Read the header of the message

imap_headerinfo

(PHP 4, PHP 5, PHP 7)

imap_headerinfo — Read the header of the message

Description

imap_headerinfo ( resource $imap_stream , int $msg_number [, int $fromlength = 0 [, int $subjectlength = 0 [, string $defaulthost = NULL ]]] ) : object

Gets information about the given message number by reading its headers.

Parameters

imap_stream

An IMAP stream returned by imap_open().

msg_number

The message number

fromlength

Number of characters for the fetchfrom property. Must be greater than or equal to zero.

subjectlength

Number of characters for the fetchsubject property Must be greater than or equal to zero.

defaulthost

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 fromlength characters
  • fetchsubject - subject line formatted to fit subjectlength characters

See Also

  • imap_fetch_overview() - Read an overview of the information in the headers of the given message


Returns headers for all messages in a mailbox

  • « imap_headerinfo
  • imap_last_error »
  • PHP Manual
  • IMAP Functions
  • Returns headers for all messages in a mailbox

imap_headers

(PHP 4, PHP 5, PHP 7)

imap_headers — Returns headers for all messages in a mailbox

Description

imap_headers ( resource $imap_stream ) : array

Returns headers for all messages in a mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

Return Values

Returns an array of string formatted with header info. One element per mail message.


Gets the last IMAP error that occurred during this page request

  • « imap_headers
  • imap_list »
  • PHP Manual
  • IMAP Functions
  • Gets the last IMAP error that occurred during this page request

imap_last_error

(PHP 4, PHP 5, PHP 7)

imap_last_error — Gets the last IMAP error that occurred during this page request

Description

imap_last_error ( void ) : string

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.

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


Read the list of mailboxes

  • « imap_last_error
  • imap_listmailbox »
  • PHP Manual
  • IMAP Functions
  • Read the list of mailboxes

imap_list

(PHP 4, PHP 5, PHP 7)

imap_list — Read the list of mailboxes

Description

imap_list ( resource $imap_stream , string $ref , string $pattern ) : array

Read the list of mailboxes.

Parameters

imap_stream

An IMAP stream returned by imap_open().

ref

ref 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.

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


Alias of imap_list

  • « imap_list
  • imap_listscan »
  • PHP Manual
  • IMAP Functions
  • Alias of imap_list

imap_listmailbox

(PHP 4, PHP 5, PHP 7)

imap_listmailbox — Alias of imap_list()

Description

This function is an alias of: imap_list().


Returns the list of mailboxes that matches the given text

  • « imap_listmailbox
  • imap_listsubscribed »
  • PHP Manual
  • IMAP Functions
  • Returns the list of mailboxes that matches the given text

imap_listscan

(PHP 4, PHP 5, PHP 7)

imap_listscan — Returns the list of mailboxes that matches the given text

Description

imap_listscan ( resource $imap_stream , string $ref , string $pattern , string $content ) : array

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_stream

An IMAP stream returned by imap_open().

ref

ref 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.

See Also

  • imap_listmailbox() - Alias of imap_list
  • imap_search() - This function returns an array of messages matching the given search criteria


Alias of imap_lsub

  • « imap_listscan
  • imap_lsub »
  • PHP Manual
  • IMAP Functions
  • Alias of imap_lsub

imap_listsubscribed

(PHP 4, PHP 5, PHP 7)

imap_listsubscribed — Alias of imap_lsub()

Description

This function is an alias of: imap_lsub().


List all the subscribed mailboxes

  • « imap_listsubscribed
  • imap_mail_compose »
  • PHP Manual
  • IMAP Functions
  • List all the subscribed mailboxes

imap_lsub

(PHP 4, PHP 5, PHP 7)

imap_lsub — List all the subscribed mailboxes

Description

imap_lsub ( resource $imap_stream , string $ref , string $pattern ) : array

Gets an array of all the mailboxes that you have subscribed.

Parameters

imap_stream

An IMAP stream returned by imap_open().

ref

ref 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.

See Also

  • imap_list() - Read the list of mailboxes
  • imap_getmailboxes() - Read the list of mailboxes, returning detailed information on each one


Create a MIME message based on given envelope and body sections

  • « imap_lsub
  • imap_mail_copy »
  • PHP Manual
  • IMAP Functions
  • Create a MIME message based on given envelope and body sections

imap_mail_compose

(PHP 4, PHP 5, PHP 7)

imap_mail_compose — Create a MIME message based on given envelope and body sections

Description

imap_mail_compose ( array $envelope , array $body ) : string

Create a MIME message based on the given envelope and body sections.

Parameters

envelope

An associative array of headers fields. Valid keys are: "remail", "return_path", "date", "from", "reply_to", "in_reply_to", "subject", "to", "cc", "bcc", "message_id" and "custom_headers" (which contains associative array of other headers).

body

An indexed array of bodies

A body is an associative array which can consist of the following keys: "type", "encoding", "charset", "type.parameters", "subtype", "id", "description", "disposition.type", "disposition", "contents.data", "lines", "bytes" and "md5".

Return Values

Returns the MIME message.

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));

?>


Copy specified messages to a mailbox

  • « imap_mail_compose
  • imap_mail_move »
  • PHP Manual
  • IMAP Functions
  • Copy specified messages to a mailbox

imap_mail_copy

(PHP 4, PHP 5, PHP 7)

imap_mail_copy — Copy specified messages to a mailbox

Description

imap_mail_copy ( resource $imap_stream , string $msglist , string $mailbox [, int $options = 0 ] ) : bool

Copies mail messages specified by msglist to specified mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

msglist

msglist 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.

options

options 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

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • imap_mail_move() - Move specified messages to a mailbox


Move specified messages to a mailbox

  • « imap_mail_copy
  • imap_mail »
  • PHP Manual
  • IMAP Functions
  • Move specified messages to a mailbox

imap_mail_move

(PHP 4, PHP 5, PHP 7)

imap_mail_move — Move specified messages to a mailbox

Description

imap_mail_move ( resource $imap_stream , string $msglist , string $mailbox [, int $options = 0 ] ) : bool

Moves mail messages specified by msglist to the specified mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

msglist

msglist 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.

options

options 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.

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


Send an email message

  • « imap_mail_move
  • imap_mailboxmsginfo »
  • PHP Manual
  • IMAP Functions
  • Send an email message

imap_mail

(PHP 4, PHP 5, PHP 7)

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 $rpath = 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.

rpath

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.

See Also

  • mail() - Send mail
  • imap_mail_compose() - Create a MIME message based on given envelope and body sections


Get information about the current mailbox

  • « imap_mail
  • imap_mime_header_decode »
  • PHP Manual
  • IMAP Functions
  • Get information about the current mailbox

imap_mailboxmsginfo

(PHP 4, PHP 5, PHP 7)

imap_mailboxmsginfo — Get information about the current mailbox

Description

imap_mailboxmsginfo ( resource $imap_stream ) : object

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_stream

An IMAP stream returned by imap_open().

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

Returns FALSE on failure.

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);

?>


Decode MIME header elements

  • « imap_mailboxmsginfo
  • imap_msgno »
  • PHP Manual
  • IMAP Functions
  • Decode MIME header elements

imap_mime_header_decode

(PHP 4, PHP 5, PHP 7)

imap_mime_header_decode — Decode MIME header elements

Description

imap_mime_header_decode ( string $text ) : array

Decodes MIME message header extensions that are non ASCII text (see » RFC2047).

Parameters

text

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.

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


Gets the message sequence number for the given UID

  • « imap_mime_header_decode
  • imap_mutf7_to_utf8 »
  • PHP Manual
  • IMAP Functions
  • Gets the message sequence number for the given UID

imap_msgno

(PHP 4, PHP 5, PHP 7)

imap_msgno — Gets the message sequence number for the given UID

Description

imap_msgno ( resource $imap_stream , int $uid ) : int

Returns the message sequence number for the given uid.

This function is the inverse of imap_uid().

Parameters

imap_stream

An IMAP stream returned by imap_open().

uid

The message UID

Return Values

Returns the message sequence number for the given uid.

See Also

  • imap_uid() - This function returns the UID for the given message sequence number


Decode a modified UTF-7 string to UTF-8

  • « imap_msgno
  • imap_num_msg »
  • PHP Manual
  • IMAP Functions
  • Decode a modified UTF-7 string to UTF-8

imap_mutf7_to_utf8

(PHP 5 >= 5.3.0, PHP 7)

imap_mutf7_to_utf8 — Decode a modified UTF-7 string to UTF-8

Description

imap_mutf7_to_utf8 ( string $in ) : string

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

in

A string encoded in modified UTF-7.

Return Values

Returns in converted to UTF-8, or FALSE on failure.

See Also

  • imap_utf8_to_mutf7() - Encode a UTF-8 string to modified UTF-7


Gets the number of messages in the current mailbox

  • « imap_mutf7_to_utf8
  • imap_num_recent »
  • PHP Manual
  • IMAP Functions
  • Gets the number of messages in the current mailbox

imap_num_msg

(PHP 4, PHP 5, PHP 7)

imap_num_msg — Gets the number of messages in the current mailbox

Description

imap_num_msg ( resource $imap_stream ) : int

Gets the number of messages in the current mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

Return Values

Return the number of messages in the current mailbox, as an integer, or FALSE on error.

See Also

  • imap_num_recent() - Gets the number of recent messages in current mailbox
  • imap_status() - Returns status information on a mailbox


Gets the number of recent messages in current mailbox

  • « imap_num_msg
  • imap_open »
  • PHP Manual
  • IMAP Functions
  • Gets the number of recent messages in current mailbox

imap_num_recent

(PHP 4, PHP 5, PHP 7)

imap_num_recent — Gets the number of recent messages in current mailbox

Description

imap_num_recent ( resource $imap_stream ) : int

Gets the number of recent messages in the current mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

Return Values

Returns the number of recent messages in the current mailbox, as an integer.

See Also

  • imap_num_msg() - Gets the number of messages in the current mailbox
  • imap_status() - Returns status information on a mailbox


Open an IMAP stream to a mailbox

  • « imap_num_recent
  • imap_ping »
  • PHP Manual
  • IMAP Functions
  • Open an IMAP stream to a mailbox

imap_open

(PHP 4, PHP 5, PHP 7)

imap_open — Open an IMAP stream to a mailbox

Description

imap_open ( string $mailbox , string $username , string $password [, int $options = 0 [, int $n_retries = 0 [, array $params = array() ]]] ) : resource

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)

username

The user name

password

The password associated with the username

options

The options 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

n_retries

Number of maximum connect attempts

params

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 stream on success or FALSE on error.

Changelog

Version | Description
5.3.2 | params added
5.2.0 | n_retries added

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


Check if the IMAP stream is still active

  • « imap_open
  • imap_qprint »
  • PHP Manual
  • IMAP Functions
  • Check if the IMAP stream is still active

imap_ping

(PHP 4, PHP 5, PHP 7)

imap_ping — Check if the IMAP stream is still active

Description

imap_ping ( resource $imap_stream ) : 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_stream

An IMAP stream returned by imap_open().

Return Values

Returns TRUE if the stream is still alive, FALSE otherwise.

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
}

?>


Convert a quoted-printable string to an 8 bit string

  • « imap_ping
  • imap_rename »
  • PHP Manual
  • IMAP Functions
  • Convert a quoted-printable string to an 8 bit string

imap_qprint

(PHP 4, PHP 5, PHP 7)

imap_qprint — Convert a quoted-printable string to an 8 bit string

Description

imap_qprint ( string $string ) : string

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.

See Also

  • imap_8bit() - Convert an 8bit string to a quoted-printable string


Alias of imap_renamemailbox

  • « imap_qprint
  • imap_renamemailbox »
  • PHP Manual
  • IMAP Functions
  • Alias of imap_renamemailbox

imap_rename

(PHP 4, PHP 5, PHP 7)

imap_rename — Alias of imap_renamemailbox()

Description

This function is an alias of: imap_renamemailbox().


Rename an old mailbox to new mailbox

  • « imap_rename
  • imap_reopen »
  • PHP Manual
  • IMAP Functions
  • Rename an old mailbox to new mailbox

imap_renamemailbox

(PHP 4, PHP 5, PHP 7)

imap_renamemailbox — Rename an old mailbox to new mailbox

Description

imap_renamemailbox ( resource $imap_stream , string $old_mbox , string $new_mbox ) : bool

This function renames on old mailbox to new mailbox (see imap_open() for the format of mbox names).

Parameters

imap_stream

An IMAP stream returned by imap_open().

old_mbox

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.

new_mbox

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.

See Also

  • imap_createmailbox() - Create a new mailbox
  • imap_deletemailbox() - Delete a mailbox


Reopen IMAP stream to new mailbox

  • « imap_renamemailbox
  • imap_rfc822_parse_adrlist »
  • PHP Manual
  • IMAP Functions
  • Reopen IMAP stream to new mailbox

imap_reopen

(PHP 4, PHP 5, PHP 7)

imap_reopen — Reopen IMAP stream to new mailbox

Description

imap_reopen ( resource $imap_stream , string $mailbox [, int $options = 0 [, int $n_retries = 0 ]] ) : bool

Reopens the specified stream to a new mailbox on an IMAP or NNTP server.

Parameters

imap_stream

An IMAP stream returned by imap_open().

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.

options

The options 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())

n_retries

Number of maximum connect attempts

Return Values

Returns TRUE if the stream is reopened, FALSE otherwise.

Changelog

Version | Description
5.2.0 | n_retries added

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()));
// ..
?>


Parses an address string

  • « imap_reopen
  • imap_rfc822_parse_headers »
  • PHP Manual
  • IMAP Functions
  • Parses an address string

imap_rfc822_parse_adrlist

(PHP 4, PHP 5, PHP 7)

imap_rfc822_parse_adrlist — Parses an address string

Description

imap_rfc822_parse_adrlist ( string $address , string $default_host ) : array

Parses the address string as defined in » RFC2822 and for each address.

Parameters

address

A string containing addresses

default_host

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


Parse mail headers from a string

  • « imap_rfc822_parse_adrlist
  • imap_rfc822_write_address »
  • PHP Manual
  • IMAP Functions
  • Parse mail headers from a string

imap_rfc822_parse_headers

(PHP 4, PHP 5, PHP 7)

imap_rfc822_parse_headers — Parse mail headers from a string

Description

imap_rfc822_parse_headers ( string $headers [, string $defaulthost = "UNKNOWN" ] ) : object

Gets an object of various header elements, similar to imap_header().

Parameters

headers

The parsed headers data

defaulthost

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


Returns a properly formatted email address given the mailbox, host, and personal info

  • « imap_rfc822_parse_headers
  • imap_savebody »
  • PHP Manual
  • IMAP Functions
  • Returns a properly formatted email address given the mailbox, host, and personal info

imap_rfc822_write_address

(PHP 4, PHP 5, PHP 7)

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 $host , string $personal ) : string

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.

host

The email host part

personal

The name of the account owner

Return Values

Returns a string properly formatted email address as defined in » RFC2822.

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>


Save a specific body section to a file

  • « imap_rfc822_write_address
  • imap_scan »
  • PHP Manual
  • IMAP Functions
  • Save a specific body section to a file

imap_savebody

(PHP 5 >= 5.1.3, PHP 7)

imap_savebody — Save a specific body section to a file

Description

imap_savebody ( resource $imap_stream , mixed $file , int $msg_number [, string $part_number = "" [, int $options = 0 ]] ) : bool

Saves a part or the whole body of the specified message.

Parameters

imap_stream

An IMAP stream returned by imap_open().

file

The path to the saved file as a string, or a valid file descriptor returned by fopen().

msg_number

The message number

part_number

The part number. It is a string of integers delimited by period which index into a body part list as per the IMAP4 specification

options

A bitmask with one or more of the following:

  • FT_UID - The msg_number 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.

See Also

  • imap_fetchbody() - Fetch a particular section of the body of the message


Alias of imap_listscan

  • « imap_savebody
  • imap_scanmailbox »
  • PHP Manual
  • IMAP Functions
  • Alias of imap_listscan

imap_scan

(PHP 4, PHP 5, PHP 7)

imap_scan — Alias of imap_listscan()

Description

This function is an alias of: imap_listscan().


Alias of imap_listscan

  • « imap_scan
  • imap_search »
  • PHP Manual
  • IMAP Functions
  • Alias of imap_listscan

imap_scanmailbox

(PHP 4, PHP 5, PHP 7)

imap_scanmailbox — Alias of imap_listscan()

Description

This function is an alias of: imap_listscan().


This function returns an array of messages matching the given search criteria

  • « imap_scanmailbox
  • imap_set_quota »
  • PHP Manual
  • IMAP Functions
  • This function returns an array of messages matching the given search criteria

imap_search

(PHP 4, PHP 5, PHP 7)

imap_search — This function returns an array of messages matching the given search criteria

Description

imap_search ( resource $imap_stream , string $criteria [, int $options = SE_FREE [, string $charset = NULL ]] ) : array

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 » RFC2060, section 6.4.4).

Parameters

imap_stream

An IMAP stream returned by imap_open().

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

options

Valid values for options 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.

Examples

Example #1 imap_search() example

<?php
$conn   = imap_open('{imap.example.com:993/imap/ssl}INBOX', 'foo@example.com', 'pass123', OP_READONLY);

$some   = imap_search($conn, 'SUBJECT "HOWTO be Awesome" SINCE "8 August 2008"', SE_UID);
$msgnos = imap_search($conn, 'ALL');
$uids   = imap_search($conn, '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


Sets a quota for a given mailbox

  • « imap_search
  • imap_setacl »
  • PHP Manual
  • IMAP Functions
  • Sets a quota for a given mailbox

imap_set_quota

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

imap_set_quota — Sets a quota for a given mailbox

Description

imap_set_quota ( resource $imap_stream , string $quota_root , int $quota_limit ) : bool

Sets an upper limit quota on a per mailbox basis.

Parameters

imap_stream

An IMAP stream returned by imap_open().

quota_root

The mailbox to have a quota set. This should follow the IMAP standard format for a mailbox: user.name.

quota_limit

The maximum size (in KB) for the quota_root

Return Values

Returns TRUE on success or FALSE on failure.

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_stream 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


Sets the ACL for a given mailbox

  • « imap_set_quota
  • imap_setflag_full »
  • PHP Manual
  • IMAP Functions
  • Sets the ACL for a given mailbox

imap_setacl

(PHP 4 >= 4.0.7, PHP 5, PHP 7)

imap_setacl — Sets the ACL for a given mailbox

Description

imap_setacl ( resource $imap_stream , string $mailbox , string $id , string $rights ) : bool

Sets the ACL for a giving mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

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.

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.

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


Sets flags on messages

  • « imap_setacl
  • imap_sort »
  • PHP Manual
  • IMAP Functions
  • Sets flags on messages

imap_setflag_full

(PHP 4, PHP 5, PHP 7)

imap_setflag_full — Sets flags on messages

Description

imap_setflag_full ( resource $imap_stream , string $sequence , string $flag [, int $options = NIL ] ) : bool

Causes a store to add the specified flag to the flags set for the messages in the specified sequence.

Parameters

imap_stream

An IMAP stream returned by imap_open().

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

Returns TRUE on success or FALSE on failure.

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


Gets and sort messages

  • « imap_setflag_full
  • imap_status »
  • PHP Manual
  • IMAP Functions
  • Gets and sort messages

imap_sort

(PHP 4, PHP 5, PHP 7)

imap_sort — Gets and sort messages

Description

imap_sort ( resource $imap_stream , int $criteria , int $reverse [, int $options = 0 [, string $search_criteria = NULL [, string $charset = NULL ]]] ) : array

Gets and sorts message numbers by the given parameters.

Parameters

imap_stream

An IMAP stream returned by imap_open().

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

Set this to 1 for reverse sorting

options

The options 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.


Returns status information on a mailbox

  • « imap_sort
  • imap_subscribe »
  • PHP Manual
  • IMAP Functions
  • Returns status information on a mailbox

imap_status

(PHP 4, PHP 5, PHP 7)

imap_status — Returns status information on a mailbox

Description

imap_status ( resource $imap_stream , string $mailbox , int $options ) : object

Gets status information about the given mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

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.

options

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. 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.

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);
?>


Subscribe to a mailbox

  • « imap_status
  • imap_thread »
  • PHP Manual
  • IMAP Functions
  • Subscribe to a mailbox

imap_subscribe

(PHP 4, PHP 5, PHP 7)

imap_subscribe — Subscribe to a mailbox

Description

imap_subscribe ( resource $imap_stream , string $mailbox ) : bool

Subscribe to a new mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

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.

See Also

  • imap_unsubscribe() - Unsubscribe from a mailbox


Returns a tree of threaded message

  • « imap_subscribe
  • imap_timeout »
  • PHP Manual
  • IMAP Functions
  • Returns a tree of threaded message

imap_thread

(PHP 4 >= 4.0.7, PHP 5, PHP 7)

imap_thread — Returns a tree of threaded message

Description

imap_thread ( resource $imap_stream [, int $options = SE_FREE ] ) : array

Gets a tree of a threaded message.

Parameters

imap_stream

An IMAP stream returned by imap_open().

options

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"]

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);

?>


Set or fetch imap timeout

  • « imap_thread
  • imap_uid »
  • PHP Manual
  • IMAP Functions
  • Set or fetch imap timeout

imap_timeout

(PHP 4 >= 4.3.3, PHP 5, PHP 7)

imap_timeout — Set or fetch imap timeout

Description

imap_timeout ( int $timeout_type [, int $timeout = -1 ] ) : mixed

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";

?>


This function returns the UID for the given message sequence number

  • « imap_timeout
  • imap_undelete »
  • PHP Manual
  • IMAP Functions
  • This function returns the UID for the given message sequence number

imap_uid

(PHP 4, PHP 5, PHP 7)

imap_uid — This function returns the UID for the given message sequence number

Description

imap_uid ( resource $imap_stream , int $msg_number ) : int

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_stream

An IMAP stream returned by imap_open().

msg_number

The message number.

Return Values

The UID of the given message.

Notes

Note:

This function is not supported by POP3 mailboxes.

See Also

  • imap_msgno() - Gets the message sequence number for the given UID


Unmark the message which is marked deleted

  • « imap_uid
  • imap_unsubscribe »
  • PHP Manual
  • IMAP Functions
  • Unmark the message which is marked deleted

imap_undelete

(PHP 4, PHP 5, PHP 7)

imap_undelete — Unmark the message which is marked deleted

Description

imap_undelete ( resource $imap_stream , int $msg_number [, int $flags = 0 ] ) : bool

Removes the deletion flag for a specified message, which is set by imap_delete() or imap_mail_move().

Parameters

imap_stream

An IMAP stream returned by imap_open().

msg_number

The message number

flags

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • imap_delete() - Mark a message for deletion from current mailbox
  • imap_mail_move() - Move specified messages to a mailbox


Unsubscribe from a mailbox

  • « imap_undelete
  • imap_utf7_decode »
  • PHP Manual
  • IMAP Functions
  • Unsubscribe from a mailbox

imap_unsubscribe

(PHP 4, PHP 5, PHP 7)

imap_unsubscribe — Unsubscribe from a mailbox

Description

imap_unsubscribe ( resource $imap_stream , string $mailbox ) : bool

Unsubscribe from the specified mailbox.

Parameters

imap_stream

An IMAP stream returned by imap_open().

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.

See Also

  • imap_subscribe() - Subscribe to a mailbox


Decodes a modified UTF-7 encoded string

  • « imap_unsubscribe
  • imap_utf7_encode »
  • PHP Manual
  • IMAP Functions
  • Decodes a modified UTF-7 encoded string

imap_utf7_decode

(PHP 4, PHP 5, PHP 7)

imap_utf7_decode — Decodes a modified UTF-7 encoded string

Description

imap_utf7_decode ( string $text ) : string

Decodes modified UTF-7 text 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

text

A modified UTF-7 encoding string, as defined in » RFC 2060, section 5.1.3 (original UTF-7 was defined in » RFC1642).

Return Values

Returns a string that is encoded in ISO-8859-1 and consists of the same sequence of characters in text, or FALSE if text contains invalid modified UTF-7 sequence or text 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


Converts ISO-8859-1 string to modified UTF-7 text

  • « imap_utf7_decode
  • imap_utf8_to_mutf7 »
  • PHP Manual
  • IMAP Functions
  • Converts ISO-8859-1 string to modified UTF-7 text

imap_utf7_encode

(PHP 4, PHP 5, PHP 7)

imap_utf7_encode — Converts ISO-8859-1 string to modified UTF-7 text

Description

imap_utf7_encode ( string $data ) : string

Converts data 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

data

An ISO-8859-1 string.

Return Values

Returns data encoded with the modified UTF-7 encoding as defined in » RFC 2060, section 5.1.3 (original UTF-7 was defined in » RFC1642).

See Also

  • imap_utf7_decode() - Decodes a modified UTF-7 encoded string


Encode a UTF-8 string to modified UTF-7

  • « imap_utf7_encode
  • imap_utf8 »
  • PHP Manual
  • IMAP Functions
  • Encode a UTF-8 string to modified UTF-7

imap_utf8_to_mutf7

(PHP 5 >= 5.3.0, PHP 7)

imap_utf8_to_mutf7 — Encode a UTF-8 string to modified UTF-7

Description

imap_utf8_to_mutf7 ( string $in ) : string

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

in

A UTF-8 encoded string.

Return Values

Returns in converted to modified UTF-7, or FALSE on failure.

See Also

  • imap_mutf7_to_utf8() - Decode a modified UTF-7 string to UTF-8


Converts MIME-encoded text to UTF-8

  • « imap_utf8_to_mutf7
  • Mail »
  • PHP Manual
  • IMAP Functions
  • Converts MIME-encoded text to UTF-8

imap_utf8

(PHP 4, PHP 5, PHP 7)

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.

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 an UTF-8 encoded string.

See Also

  • imap_mime_header_decode() - Decode MIME header elements


Mail

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Mail Functions
    • ezmlm_hash — Calculate the hash value needed by EZMLM
    • mail — Send mail


  • « Mail
  • Installing/Configuring »
  • PHP Manual
  • Mail
  • Introduction

Introduction

The mail() function allows you to send mail.


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" | PHP_INI_PERDIR | Available since PHP 5.3.0.
mail.log | NULL | PHP_INI_PERDIR | Available since PHP 5.3.0. (PHP_INI_SYSTEM|PHP_INI_PERDIR)
mail.force_extra_parameters | NULL | PHP_INI_PERDIR | Available since PHP 5.0.0. (PHP_INI_SYSTEM|PHP_INI_PERDIR)
SMTP | "localhost" | PHP_INI_ALL |
smtp_port | "25" | PHP_INI_ALL |
sendmail_from | NULL | PHP_INI_ALL |
sendmail_path | "/usr/sbin/sendmail -t -i" | PHP_INI_SYSTEM |
For further details and definitions of the PHP_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.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(), even in safe mode.

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 from PHP under Windows. 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.


  • « Resource Types
  • Mail Functions »
  • PHP Manual
  • Mail
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


Mail Functions

Table of Contents

  • ezmlm_hash — Calculate the hash value needed by EZMLM
  • mail — Send mail


Calculate the hash value needed by EZMLM

  • « Mail Functions
  • mail »
  • PHP Manual
  • Mail Functions
  • Calculate the hash value needed by EZMLM

ezmlm_hash

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

ezmlm_hash — Calculate the hash value needed by EZMLM

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.

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

?>


Send mail

  • « ezmlm_hash
  • Mailparse »
  • PHP Manual
  • Mail Functions
  • Send mail

mail

(PHP 4, PHP 5, PHP 7)

mail — Send mail

Description

mail ( string $to , string $subject , string $message [, mixed $additional_headers [, string $additional_parameters ]] ) : 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@example.com>
  • User <user@example.com>, Another User <anotheruser@example.com>

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:

Before PHP 5.4.42 and 5.5.27, repectively, additional_headers did not have mail header injection protection. Therefore, users must make sure specified headers are safe and contains headers only. i.e. Never start mail body by putting multiple newlines.

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_parameters (optional)

The additional_parameters 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.
5.4.42, 5.5.27 | Header injection protection has been added for the additional_headers parameter. This means that multiple consecutive newlines are no longer allowed.

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_parameters 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 Windows implementation of mail() differs in many ways from the Unix 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


Mailparse

  • Introduction
  • Installing/Configuring
    • Requirements
    • 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_file — Extracts/decodes a message section
    • 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_free — Frees a MIME resource
    • mailparse_msg_get_part_data — Returns an associative array of info about the message
    • mailparse_msg_get_part — Returns a handle on a given section in a mimemessage
    • mailparse_msg_get_structure — Returns an array of mime section names in the supplied message
    • mailparse_msg_parse_file — Parses a file
    • mailparse_msg_parse — Incrementally parse data into buffer
    • 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


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.


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. A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

It is necessary that the mbstring extension is loaded before mailparse.


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 (integer)
MAILPARSE_EXTRACT_STREAM (integer)
MAILPARSE_EXTRACT_RETURN (integer)


Mailparse Functions

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_file — Extracts/decodes a message section
  • 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_free — Frees a MIME resource
  • mailparse_msg_get_part_data — Returns an associative array of info about the message
  • mailparse_msg_get_part — Returns a handle on a given section in a mimemessage
  • mailparse_msg_get_structure — Returns an array of mime section names in the supplied message
  • mailparse_msg_parse_file — Parses a file
  • mailparse_msg_parse — Incrementally parse data into buffer
  • 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


Gets the best way of encoding

  • « Mailparse Functions
  • mailparse_msg_create »
  • PHP Manual
  • Mailparse Functions
  • Gets the best way of encoding

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


Create a mime mail resource

  • « mailparse_determine_best_xfer_encoding
  • mailparse_msg_extract_part_file »
  • PHP Manual
  • Mailparse Functions
  • Create a mime mail resource

mailparse_msg_create

(PECL mailparse >= 0.9.0)

mailparse_msg_create — Create a mime mail resource

Description

mailparse_msg_create ( void ) : resource

Create a MIME mail resource.

Return Values

Returns a handle that can be used to parse a message.

See Also

  • mailparse_msg_free() - Frees a MIME resource
  • mailparse_msg_parse_file() - Parses a file


Extracts/decodes a message section

  • « mailparse_msg_create
  • mailparse_msg_extract_part »
  • PHP Manual
  • Mailparse Functions
  • Extracts/decodes a message section

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


Extracts/decodes a message section

  • « mailparse_msg_extract_part_file
  • mailparse_msg_extract_whole_part_file »
  • PHP Manual
  • Mailparse Functions
  • Extracts/decodes a message section

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


Extracts a message section including headers without decoding the transfer encoding

  • « mailparse_msg_extract_part
  • mailparse_msg_free »
  • PHP Manual
  • Mailparse Functions
  • 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


Frees a MIME resource

  • « mailparse_msg_extract_whole_part_file
  • mailparse_msg_get_part_data »
  • PHP Manual
  • Mailparse Functions
  • Frees a MIME resource

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


Returns an associative array of info about the message

  • « mailparse_msg_free
  • mailparse_msg_get_part »
  • PHP Manual
  • Mailparse Functions
  • Returns an associative array of info about the message

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.


Returns a handle on a given section in a mimemessage

  • « mailparse_msg_get_part_data
  • mailparse_msg_get_structure »
  • PHP Manual
  • Mailparse Functions
  • Returns a handle on a given section in a mimemessage

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


Returns an array of mime section names in the supplied message

  • « mailparse_msg_get_part
  • mailparse_msg_parse_file »
  • PHP Manual
  • Mailparse Functions
  • Returns an array of mime section names in the supplied message

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.


Parses a file

  • « mailparse_msg_get_structure
  • mailparse_msg_parse »
  • PHP Manual
  • Mailparse Functions
  • Parses a file

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.

Return Values

Returns a MIME resource representing the structure, or FALSE on error.

See Also

  • mailparse_msg_free() - Frees a MIME resource
  • mailparse_msg_create() - Create a mime mail resource


Incrementally parse data into buffer

  • « mailparse_msg_parse_file
  • mailparse_rfc822_parse_addresses »
  • PHP Manual
  • Mailparse Functions
  • Incrementally parse data into buffer

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

Return Values

Returns TRUE on success or FALSE on failure.


Parse RFC 822 compliant addresses

  • « mailparse_msg_parse
  • mailparse_stream_encode »
  • PHP Manual
  • Mailparse Functions
  • Parse RFC 822 compliant addresses

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)
  }
}


Streams data from source file pointer, apply encoding and write to destfp

  • « mailparse_rfc822_parse_addresses
  • mailparse_uudecode_all »
  • PHP Manual
  • Mailparse Functions
  • Streams data from source file pointer, apply encoding and write to destfp

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.


Scans the data from fp and extract each embedded uuencoded file

  • « mailparse_stream_encode
  • vpopmail »
  • PHP Manual
  • Mailparse Functions
  • Scans the data from fp and extract each embedded uuencoded file

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


vpopmail

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • vpopmail Functions
    • vpopmail_add_alias_domain_ex — Add alias to an existing virtual domain
    • vpopmail_add_alias_domain — Add an alias for a virtual domain
    • vpopmail_add_domain_ex — Add a new virtual domain
    • vpopmail_add_domain — Add a new virtual domain
    • vpopmail_add_user — Add a new user to the specified virtual domain
    • vpopmail_alias_add — Insert a virtual alias
    • vpopmail_alias_del_domain — Deletes all virtual aliases of a domain
    • vpopmail_alias_del — Deletes all virtual aliases of a user
    • vpopmail_alias_get_all — Get all lines of an alias for a domain
    • vpopmail_alias_get — Get all lines of an alias for a domain
    • vpopmail_auth_user — Attempt to validate a username/domain/password
    • vpopmail_del_domain_ex — Delete a virtual domain
    • vpopmail_del_domain — Delete a virtual domain
    • vpopmail_del_user — Delete a user from a virtual domain
    • vpopmail_error — Get text message for last vpopmail error
    • vpopmail_passwd — Change a virtual user's password
    • vpopmail_set_user_quota — Sets a virtual user's quota


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.


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/vpopmail.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.


  • « Resource Types
  • vpopmail Functions »
  • PHP Manual
  • vpopmail
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


vpopmail Functions

Table of Contents

  • vpopmail_add_alias_domain_ex — Add alias to an existing virtual domain
  • vpopmail_add_alias_domain — Add an alias for a virtual domain
  • vpopmail_add_domain_ex — Add a new virtual domain
  • vpopmail_add_domain — Add a new virtual domain
  • vpopmail_add_user — Add a new user to the specified virtual domain
  • vpopmail_alias_add — Insert a virtual alias
  • vpopmail_alias_del_domain — Deletes all virtual aliases of a domain
  • vpopmail_alias_del — Deletes all virtual aliases of a user
  • vpopmail_alias_get_all — Get all lines of an alias for a domain
  • vpopmail_alias_get — Get all lines of an alias for a domain
  • vpopmail_auth_user — Attempt to validate a username/domain/password
  • vpopmail_del_domain_ex — Delete a virtual domain
  • vpopmail_del_domain — Delete a virtual domain
  • vpopmail_del_user — Delete a user from a virtual domain
  • vpopmail_error — Get text message for last vpopmail error
  • vpopmail_passwd — Change a virtual user's password
  • vpopmail_set_user_quota — Sets a virtual user's quota


Add alias to an existing virtual domain

  • « vpopmail Functions
  • vpopmail_add_alias_domain »
  • PHP Manual
  • vpopmail Functions
  • Add alias to an existing virtual domain

vpopmail_add_alias_domain_ex

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_add_alias_domain_ex — Add alias to an existing virtual domain

Description

vpopmail_add_alias_domain_ex ( string $olddomain , string $newdomain ) : bool
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.

Warning

This function is currently not documented; only its argument list is available.


Add an alias for a virtual domain

  • « vpopmail_add_alias_domain_ex
  • vpopmail_add_domain_ex »
  • PHP Manual
  • vpopmail Functions
  • Add an alias for a virtual domain

vpopmail_add_alias_domain

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_add_alias_domain — Add an alias for a virtual domain

Description

vpopmail_add_alias_domain ( string $domain , string $aliasdomain ) : bool
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.

Warning

This function is currently not documented; only its argument list is available.


Add a new virtual domain

  • « vpopmail_add_alias_domain
  • vpopmail_add_domain »
  • PHP Manual
  • vpopmail Functions
  • Add a new virtual domain

vpopmail_add_domain_ex

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_add_domain_ex — Add a new virtual domain

Description

vpopmail_add_domain_ex ( string $domain , string $passwd [, string $quota [, string $bounce [, bool $apop ]]] ) : bool
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.

Warning

This function is currently not documented; only its argument list is available.


Add a new virtual domain

  • « vpopmail_add_domain_ex
  • vpopmail_add_user »
  • PHP Manual
  • vpopmail Functions
  • Add a new virtual domain

vpopmail_add_domain

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_add_domain — Add a new virtual domain

Description

vpopmail_add_domain ( string $domain , string $dir , int $uid , int $gid ) : bool
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.

Warning

This function is currently not documented; only its argument list is available.


Add a new user to the specified virtual domain

  • « vpopmail_add_domain
  • vpopmail_alias_add »
  • PHP Manual
  • vpopmail Functions
  • Add a new user to the specified virtual domain

vpopmail_add_user

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_add_user — Add a new user to the specified virtual domain

Description

vpopmail_add_user ( string $user , string $domain , string $password [, string $gecos [, bool $apop ]] ) : bool
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.

Warning

This function is currently not documented; only its argument list is available.


Insert a virtual alias

  • « vpopmail_add_user
  • vpopmail_alias_del_domain »
  • PHP Manual
  • vpopmail Functions
  • Insert a virtual alias

vpopmail_alias_add

(PHP 4 >= 4.0.7, PECL vpopmail >= 0.2)

vpopmail_alias_add — Insert a virtual alias

Description

vpopmail_alias_add ( string $user , string $domain , string $alias ) : bool
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.

Warning

This function is currently not documented; only its argument list is available.


Deletes all virtual aliases of a domain

  • « vpopmail_alias_add
  • vpopmail_alias_del »
  • PHP Manual
  • vpopmail Functions
  • Deletes all virtual aliases of a domain

vpopmail_alias_del_domain

(PHP 4 >= 4.0.7, PECL vpopmail >= 0.2)

vpopmail_alias_del_domain — Deletes all virtual aliases of a domain

Description

vpopmail_alias_del_domain ( string $domain ) : bool
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.

Warning

This function is currently not documented; only its argument list is available.


Deletes all virtual aliases of a user

  • « vpopmail_alias_del_domain
  • vpopmail_alias_get_all »
  • PHP Manual
  • vpopmail Functions
  • Deletes all virtual aliases of a user

vpopmail_alias_del

(PHP 4 >= 4.0.7, PECL vpopmail >= 0.2)

vpopmail_alias_del — Deletes all virtual aliases of a user

Description

vpopmail_alias_del ( string $user , string $domain ) : bool
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.

Warning

This function is currently not documented; only its argument list is available.


Get all lines of an alias for a domain

  • « vpopmail_alias_del
  • vpopmail_alias_get »
  • PHP Manual
  • vpopmail Functions
  • Get all lines of an alias for a domain

vpopmail_alias_get_all

(PHP 4 >= 4.0.7, PECL vpopmail >= 0.2)

vpopmail_alias_get_all — Get all lines of an alias for a domain

Description

vpopmail_alias_get_all ( string $domain ) : array
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.

Warning

This function is currently not documented; only its argument list is available.


Get all lines of an alias for a domain

  • « vpopmail_alias_get_all
  • vpopmail_auth_user »
  • PHP Manual
  • vpopmail Functions
  • Get all lines of an alias for a domain

vpopmail_alias_get

(PHP 4 >= 4.0.7, PECL vpopmail >= 0.2)

vpopmail_alias_get — Get all lines of an alias for a domain

Description

vpopmail_alias_get ( string $alias , string $domain ) : array
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.

Warning

This function is currently not documented; only its argument list is available.


Attempt to validate a username/domain/password

  • « vpopmail_alias_get
  • vpopmail_del_domain_ex »
  • PHP Manual
  • vpopmail Functions
  • Attempt to validate a username/domain/password

vpopmail_auth_user

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_auth_user — Attempt to validate a username/domain/password

Description

vpopmail_auth_user ( string $user , string $domain , string $password [, string $apop ] ) : bool
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.

Warning

This function is currently not documented; only its argument list is available.


Delete a virtual domain

  • « vpopmail_auth_user
  • vpopmail_del_domain »
  • PHP Manual
  • vpopmail Functions
  • Delete a virtual domain

vpopmail_del_domain_ex

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_del_domain_ex — Delete a virtual domain

Description

vpopmail_del_domain_ex ( string $domain ) : bool
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.

Warning

This function is currently not documented; only its argument list is available.


Delete a virtual domain

  • « vpopmail_del_domain_ex
  • vpopmail_del_user »
  • PHP Manual
  • vpopmail Functions
  • Delete a virtual domain

vpopmail_del_domain

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_del_domain — Delete a virtual domain

Description

vpopmail_del_domain ( string $domain ) : bool
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.

Warning

This function is currently not documented; only its argument list is available.


Delete a user from a virtual domain

  • « vpopmail_del_domain
  • vpopmail_error »
  • PHP Manual
  • vpopmail Functions
  • Delete a user from a virtual domain

vpopmail_del_user

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_del_user — Delete a user from a virtual domain

Description

vpopmail_del_user ( string $user , string $domain ) : bool
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.

Warning

This function is currently not documented; only its argument list is available.


Get text message for last vpopmail error

  • « vpopmail_del_user
  • vpopmail_passwd »
  • PHP Manual
  • vpopmail Functions
  • Get text message for last vpopmail error

vpopmail_error

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_error — Get text message for last vpopmail error

Description

vpopmail_error ( void ) : string
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.

Warning

This function is currently not documented; only its argument list is available.


Change a virtual user's password

  • « vpopmail_error
  • vpopmail_set_user_quota »
  • PHP Manual
  • vpopmail Functions
  • Change a virtual user's password

vpopmail_passwd

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_passwd — Change a virtual user's password

Description

vpopmail_passwd ( string $user , string $domain , string $password [, bool $apop ] ) : bool
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.

Warning

This function is currently not documented; only its argument list is available.


Sets a virtual user's quota

  • « vpopmail_passwd
  • Mathematical Extensions »
  • PHP Manual
  • vpopmail Functions
  • Sets a virtual user's quota

vpopmail_set_user_quota

(PHP 4 >= 4.0.5, PECL vpopmail >= 0.2)

vpopmail_set_user_quota — Sets a virtual user's quota

Description

vpopmail_set_user_quota ( string $user , string $domain , string $quota ) : bool
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.

Warning

This function is currently not documented; only its argument list is available.


Mathematical Extensions

  • BC Math — BCMath Arbitrary Precision Mathematics
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • BC Math Functions
  • GMP — GNU Multiple Precision
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • GMP Functions
    • GMP — The GMP class
  • Lapack
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Lapack — The Lapack class
    • LapackException — The LapackException class
  • Math — Mathematical Functions
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Math Functions
  • Statistics
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Statistic Functions
  • Trader — Technical Analysis for Traders
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Trader Functions


BCMath Arbitrary Precision Mathematics

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • BC Math Functions
    • bcadd — Add two arbitrary precision numbers
    • bccomp — Compare two arbitrary precision numbers
    • bcdiv — Divide two arbitrary precision numbers
    • 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
    • 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


Introduction

For arbitrary precision mathematics PHP offers the Binary Calculator which supports numbers of any size and precision up to 2147483647 (or 0x7FFFFFFF) decimals, if there is sufficient memory, represented as strings.

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 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'
?>


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" | PHP_INI_ALL |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

bcmath.scale integer

Number of decimal digits for all bcmath functions. See also bcscale().


  • « Resource Types
  • BC Math Functions »
  • PHP Manual
  • BC Math
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


BC Math Functions

Table of Contents

  • bcadd — Add two arbitrary precision numbers
  • bccomp — Compare two arbitrary precision numbers
  • bcdiv — Divide two arbitrary precision numbers
  • 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
  • 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


Add two arbitrary precision numbers

  • « BC Math Functions
  • bccomp »
  • PHP Manual
  • BC Math Functions
  • Add two arbitrary precision numbers

bcadd

(PHP 4, PHP 5, PHP 7)

bcadd — Add two arbitrary precision numbers

Description

bcadd ( string $left_operand , string $right_operand [, int $scale = 0 ] ) : string

Sums left_operand and right_operand.

Parameters

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

scale

This optional parameter is used to set the number of digits after the decimal place in the result. If omitted, it will default to the scale set globally with the bcscale() function, or fallback to 0 if this has not been set.

Return Values

The sum of the two operands, as a string.

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


Compare two arbitrary precision numbers

  • « bcadd
  • bcdiv »
  • PHP Manual
  • BC Math Functions
  • Compare two arbitrary precision numbers

bccomp

(PHP 4, PHP 5, PHP 7)

bccomp — Compare two arbitrary precision numbers

Description

bccomp ( string $left_operand , string $right_operand [, int $scale = 0 ] ) : int

Compares the left_operand to the right_operand and returns the result as an integer.

Parameters

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

scale

The optional scale parameter is used to set the number of digits after the decimal place which will be used in the comparison.

Return Values

Returns 0 if the two operands are equal, 1 if the left_operand is larger than the right_operand, -1 otherwise.

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

?>


Divide two arbitrary precision numbers

  • « bccomp
  • bcmod »
  • PHP Manual
  • BC Math Functions
  • Divide two arbitrary precision numbers

bcdiv

(PHP 4, PHP 5, PHP 7)

bcdiv — Divide two arbitrary precision numbers

Description

bcdiv ( string $dividend , string $divisor [, int $scale = 0 ] ) : string

Divides the dividend by the divisor.

Parameters

dividend

The dividend, as a string.

divisor

The divisor, as a string.

scale

This optional parameter is used to set the number of digits after the decimal place in the result. If omitted, it will default to the scale set globally with the bcscale() function, or fallback to 0 if this has not been set.

Return Values

Returns the result of the division as a string, or NULL if divisor is 0.

Examples

Example #1 bcdiv() example

<?php

echo bcdiv('105', '6.55957', 3);  // 16.007

?>

See Also

  • bcmul() - Multiply two arbitrary precision numbers


Get modulus of an arbitrary precision number

  • « bcdiv
  • bcmul »
  • PHP Manual
  • BC Math Functions
  • Get modulus of an arbitrary precision number

bcmod

(PHP 4, PHP 5, PHP 7)

bcmod — Get modulus of an arbitrary precision number

Description

bcmod ( string $dividend , string $divisor [, int $scale = 0 ] ) : string

Get the remainder of dividing dividend by divisor. Unless divisor is zero, the result has the same sign as dividend.

Parameters

dividend

The dividend, as a string.

divisor

The divisor, as a string.

Return Values

Returns the modulus as a string, or NULL if divisor is 0.

Changelog

Version | Description
7.2.0 | dividend and divisor 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


Multiply two arbitrary precision numbers

  • « bcmod
  • bcpow »
  • PHP Manual
  • BC Math Functions
  • Multiply two arbitrary precision numbers

bcmul

(PHP 4, PHP 5, PHP 7)

bcmul — Multiply two arbitrary precision numbers

Description

bcmul ( string $left_operand , string $right_operand [, int $scale = 0 ] ) : string

Multiply the left_operand by the right_operand.

Parameters

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

scale

This optional parameter is used to set the number of digits after the decimal place in the result. If omitted, it will default to the scale set globally with the bcscale() function, or fallback to 0 if this has not been set.

Return Values

Returns the result as a string.

Changelog

Version | Description
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:

Before 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


Raise an arbitrary precision number to another

  • « bcmul
  • bcpowmod »
  • PHP Manual
  • BC Math Functions
  • Raise an arbitrary precision number to another

bcpow

(PHP 4, PHP 5, PHP 7)

bcpow — Raise an arbitrary precision number to another

Description

bcpow ( string $base , string $exponent [, int $scale = 0 ] ) : string

Raise base to the power exponent.

Parameters

base

The base, as a string.

exponent

The exponent, as a string. If the exponent is non-integral, it is truncated. The valid range of the exponent is platform specific, but is at least -2147483648 to 2147483647.

scale

This optional parameter is used to set the number of digits after the decimal place in the result. If omitted, it will default to the scale set globally with the bcscale() function, or fallback to 0 if this has not been set.

Return Values

Returns the result as a string.

Changelog

Version | Description
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


Raise an arbitrary precision number to another, reduced by a specified modulus

  • « bcpow
  • bcscale »
  • PHP Manual
  • BC Math Functions
  • Raise an arbitrary precision number to another, reduced by a specified modulus

bcpowmod

(PHP 5, PHP 7)

bcpowmod — Raise an arbitrary precision number to another, reduced by a specified modulus

Description

bcpowmod ( string $base , string $exponent , string $modulus [, int $scale = 0 ] ) : string

Use the fast-exponentiation method to raise base to the power exponent with respect to the modulus modulus.

Parameters

base

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 optional parameter is used to set the number of digits after the decimal place in the result. If omitted, it will default to the scale set globally with the bcscale() function, or fallback to 0 if this has not been set.

Return Values

Returns the result as a string, or NULL if modulus is 0 or exponent is negative.

Notes

Note:

Because this method uses the modulus operation, numbers which are not positive integers may give unexpected results.

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.

?>

See Also

  • bcpow() - Raise an arbitrary precision number to another
  • bcmod() - Get modulus of an arbitrary precision number


Set or get default scale parameter for all bc math functions

  • « bcpowmod
  • bcsqrt »
  • PHP Manual
  • BC Math Functions
  • Set or get default scale parameter for all bc math functions

bcscale

(PHP 4, PHP 5, PHP 7)

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 ( void ) : 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.

Changelog

Version | Description
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

?>


Get the square root of an arbitrary precision number

  • « bcscale
  • bcsub »
  • PHP Manual
  • BC Math Functions
  • Get the square root of an arbitrary precision number

bcsqrt

(PHP 4, PHP 5, PHP 7)

bcsqrt — Get the square root of an arbitrary precision number

Description

bcsqrt ( string $operand [, int $scale = 0 ] ) : string

Return the square root of the operand.

Parameters

operand

The operand, as a string.

scale

This optional parameter is used to set the number of digits after the decimal place in the result. If omitted, it will default to the scale set globally with the bcscale() function, or fallback to 0 if this has not been set.

Return Values

Returns the square root as a string, or NULL if operand is negative.

Examples

Example #1 bcsqrt() example

<?php

echo bcsqrt('2', 3); // 1.414

?>

See Also

  • bcpow() - Raise an arbitrary precision number to another


Subtract one arbitrary precision number from another

  • « bcsqrt
  • GMP »
  • PHP Manual
  • BC Math Functions
  • Subtract one arbitrary precision number from another

bcsub

(PHP 4, PHP 5, PHP 7)

bcsub — Subtract one arbitrary precision number from another

Description

bcsub ( string $left_operand , string $right_operand [, int $scale = 0 ] ) : string

Subtracts the right_operand from the left_operand.

Parameters

left_operand

The left operand, as a string.

right_operand

The right operand, as a string.

scale

This optional parameter is used to set the number of digits after the decimal place in the result. If omitted, it will default to the scale set globally with the bcscale() function, or fallback to 0 if this has not been set.

Return Values

The result of the subtraction, as a string.

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


GNU Multiple Precision

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • 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_q — Divide numbers
    • gmp_div_qr — Divide numbers and get quotient and remainder
    • gmp_div_r — Remainder of the division of numbers
    • gmp_div — Alias of gmp_div_q
    • 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_bits — Random number
    • gmp_random_range — Random number
    • gmp_random_seed — Sets the RNG seed
    • gmp_random — Random number
    • 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


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. However, note that PHP 5.5 and earlier represented GMP numbers as resources. 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:

From PHP 5.6 onwards, 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.

Note: This extension is available on Windows platforms since PHP 5.1.0.


Requirements

The GMP library can be downloaded from » http://gmplib.org/#DOWNLOAD. This site also has the GMP manual available.

At least GMP version 2 is required, with some functions requiring a more recent version of the GMP library.


Installation

In order to have these functions available, PHP must be compiled with GMP support by using the --with-gmp option.


Resource Types

Prior to PHP 5.6, most GMP functions operate on or return GMP number resources. PHP 5.6 onwards uses GMP objects in place of GMP number 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.

GMP_ROUND_ZERO (integer)
GMP_ROUND_PLUSINF (integer)
GMP_ROUND_MINUSINF (integer)
GMP_MSW_FIRST (integer)
GMP_LSW_FIRST (integer)
GMP_LITTLE_ENDIAN (integer)
GMP_BIG_ENDIAN (integer)
GMP_NATIVE_ENDIAN (integer)
GMP_VERSION (string)
The GMP 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

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_q — Divide numbers
  • gmp_div_qr — Divide numbers and get quotient and remainder
  • gmp_div_r — Remainder of the division of numbers
  • gmp_div — Alias of gmp_div_q
  • 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_bits — Random number
  • gmp_random_range — Random number
  • gmp_random_seed — Sets the RNG seed
  • gmp_random — Random number
  • 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


Absolute value

  • « GMP Functions
  • gmp_add »
  • PHP Manual
  • GMP Functions
  • Absolute value

gmp_abs

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_abs — Absolute value

Description

gmp_abs ( GMP $a ) : GMP

Get the absolute value of a number.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

Returns the absolute value of a, 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


Add numbers

  • « gmp_abs
  • gmp_and »
  • PHP Manual
  • GMP Functions
  • Add numbers

gmp_add

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_add — Add numbers

Description

gmp_add ( GMP $a , GMP $b ) : GMP

Add two numbers.

Parameters

a

The first summand (augent).

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

b

The second summand (addend).

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

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


Bitwise AND

  • « gmp_add
  • gmp_binomial »
  • PHP Manual
  • GMP Functions
  • Bitwise AND

gmp_and

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_and — Bitwise AND

Description

gmp_and ( GMP $a , GMP $b ) : GMP

Calculates bitwise AND of two GMP numbers.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

b

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

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


Calculates binomial coefficient

  • « gmp_and
  • gmp_clrbit »
  • PHP Manual
  • GMP Functions
  • Calculates binomial coefficient

gmp_binomial

(PHP 7 >= 7.3.0)

gmp_binomial — Calculates binomial coefficient

Description

gmp_binomial ( mixed $n , int $k ) : GMP

Calculates the binomial coefficient C(n, k).

Parameters

n

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

k

Return Values

Returns the binomial coefficient C(n, k), or FALSE on failure.

Errors/Exceptions

Issues E_WARNING if k is negative.


Clear bit

  • « gmp_binomial
  • gmp_cmp »
  • PHP Manual
  • GMP Functions
  • Clear bit

gmp_clrbit

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_clrbit — Clear bit

Description

gmp_clrbit ( GMP $a , int $index ) : void

Clears (sets to 0) bit index in a. The index starts at 0.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

index

The index of the bit to clear. Index 0 represents the least significant bit.

Return Values

A GMP number resource in PHP 5.5 and earlier, or a GMP object in PHP 5.6 and later.

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 resource 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


Compare numbers

  • « gmp_clrbit
  • gmp_com »
  • PHP Manual
  • GMP Functions
  • Compare numbers

gmp_cmp

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_cmp — Compare numbers

Description

gmp_cmp ( GMP $a , GMP $b ) : int

Compares two numbers.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

b

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

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


Calculates one's complement

  • « gmp_cmp
  • gmp_div_q »
  • PHP Manual
  • GMP Functions
  • Calculates one's complement

gmp_com

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_com — Calculates one's complement

Description

gmp_com ( GMP $a ) : GMP

Returns the one's complement of a.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

Returns the one's complement of a, 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


Divide numbers

  • « gmp_com
  • gmp_div_qr »
  • PHP Manual
  • GMP Functions
  • Divide numbers

gmp_div_q

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_div_q — Divide numbers

Description

gmp_div_q ( GMP $a , GMP $b [, int $round = GMP_ROUND_ZERO ] ) : GMP

Divides a by b and returns the integer result.

Parameters

a

The number being divided.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

b

The number that a is being divided by.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

round

The result rounding is defined by the round, 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.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

A GMP number resource in PHP 5.5 and earlier, or a GMP object in PHP 5.6 and later.

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


Divide numbers and get quotient and remainder

  • « gmp_div_q
  • gmp_div_r »
  • PHP Manual
  • GMP Functions
  • Divide numbers and get quotient and remainder

gmp_div_qr

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_div_qr — Divide numbers and get quotient and remainder

Description

gmp_div_qr ( GMP $n , GMP $d [, int $round = GMP_ROUND_ZERO ] ) : array

The function divides n by d.

Parameters

n

The number being divided.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

d

The number that n is being divided by.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

round

See the gmp_div_q() function for description of the round 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


Remainder of the division of numbers

  • « gmp_div_qr
  • gmp_div »
  • PHP Manual
  • GMP Functions
  • Remainder of the division of numbers

gmp_div_r

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_div_r — Remainder of the division of numbers

Description

gmp_div_r ( GMP $n , GMP $d [, int $round = GMP_ROUND_ZERO ] ) : GMP

Calculates remainder of the integer division of n by d. The remainder has the sign of the n argument, if not zero.

Parameters

n

The number being divided.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

d

The number that n is being divided by.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

round

See the gmp_div_q() function for description of the round 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


Alias of gmp_div_q

  • « gmp_div_r
  • gmp_divexact »
  • PHP Manual
  • GMP Functions
  • Alias of gmp_div_q

gmp_div

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_div — Alias of gmp_div_q()

Description

This function is an alias of: gmp_div_q().


Exact division of numbers

  • « gmp_div
  • gmp_export »
  • PHP Manual
  • GMP Functions
  • Exact division of numbers

gmp_divexact

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_divexact — Exact division of numbers

Description

gmp_divexact ( GMP $n , GMP $d ) : GMP

Divides n by d, using fast "exact division" algorithm. This function produces correct results only when it is known in advance that d divides n.

Parameters

n

The number being divided.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

d

The number that a is being divided by.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

A GMP number resource in PHP 5.5 and earlier, or a GMP object in PHP 5.6 and later.

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


Export to a binary string

  • « gmp_divexact
  • gmp_fact »
  • PHP Manual
  • GMP Functions
  • Export to a binary string

gmp_export

(PHP 5 >= 5.6.1, PHP 7)

gmp_export — Export to a binary string

Description

gmp_export ( GMP $gmpnumber [, int $word_size = 1 [, int $options = GMP_MSW_FIRST | GMP_NATIVE_ENDIAN ]] ) : string

Export a GMP number to a binary string

Parameters

gmpnumber

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.

options

Default value is GMP_MSW_FIRST | GMP_NATIVE_ENDIAN.

Return Values

Returns a string or 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


Factorial

  • « gmp_export
  • gmp_gcd »
  • PHP Manual
  • GMP Functions
  • Factorial

gmp_fact

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_fact — Factorial

Description

gmp_fact ( mixed $a ) : GMP

Calculates factorial (a!) of a.

Parameters

a

The factorial number.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

A GMP number resource in PHP 5.5 and earlier, or a GMP object in PHP 5.6 and later.

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


Calculate GCD

  • « gmp_fact
  • gmp_gcdext »
  • PHP Manual
  • GMP Functions
  • Calculate GCD

gmp_gcd

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_gcd — Calculate GCD

Description

gmp_gcd ( GMP $a , GMP $b ) : GMP

Calculate greatest common divisor of a and b. The result is always positive even if either of, or both, input operands are negative.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

b

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

A positive GMP number that divides into both a and b.

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


Calculate GCD and multipliers

  • « gmp_gcd
  • gmp_hamdist »
  • PHP Manual
  • GMP Functions
  • Calculate GCD and multipliers

gmp_gcdext

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_gcdext — Calculate GCD and multipliers

Description

gmp_gcdext ( GMP $a , GMP $b ) : 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

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

b

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

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
?>


Hamming distance

  • « gmp_gcdext
  • gmp_import »
  • PHP Manual
  • GMP Functions
  • Hamming distance

gmp_hamdist

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_hamdist — Hamming distance

Description

gmp_hamdist ( GMP $a , GMP $b ) : int

Returns the hamming distance between a and b. Both operands should be non-negative.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

It should be positive.

b

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

It should be positive.

Return Values

A GMP number resource in PHP 5.5 and earlier, or a GMP object in PHP 5.6 and later.

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


Import from a binary string

  • « gmp_hamdist
  • gmp_init »
  • PHP Manual
  • GMP Functions
  • Import from a binary string

gmp_import

(PHP 5 >= 5.6.1, PHP 7)

gmp_import — Import from a binary string

Description

gmp_import ( string $data [, int $word_size = 1 [, int $options = 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.

options

Default value is GMP_MSW_FIRST | GMP_NATIVE_ENDIAN.

Return Values

Returns a GMP number or 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


Create GMP number

  • « gmp_import
  • gmp_intval »
  • PHP Manual
  • GMP Functions
  • Create GMP number

gmp_init

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_init — Create GMP number

Description

gmp_init ( mixed $number [, int $base = 0 ] ) : GMP

Creates a GMP number from an integer or string.

Parameters

number

An integer or a string. The string representation can be decimal, hexadecimal or octal.

base

The base.

The base may vary from 2 to 36. If base is 0 (default value), the actual base is determined from the leading characters: if the first two characters are 0x or 0X, hexadecimal is assumed, otherwise if the first character is "0", octal is assumed, otherwise decimal is assumed.

Return Values

A GMP number resource in PHP 5.5 and earlier, or a GMP object in PHP 5.6 and later.

Changelog

Version | Description
5.3.2 | The base was extended from 2 to 36, to 2 to 62 and -2 to -36.

Notes

Note:

To use the extended base introduced in PHP 5.3.2, then PHP must be compiled against GMP 4.2.0 or greater.

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().


Convert GMP number to integer

  • « gmp_init
  • gmp_invert »
  • PHP Manual
  • GMP Functions
  • Convert GMP number to integer

gmp_intval

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_intval — Convert GMP number to integer

Description

gmp_intval ( GMP $gmpnumber ) : int

This function converts GMP number into native PHP integers.

Parameters

gmpnumber

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

The integer value of gmpnumber.

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().


Inverse by modulo

  • « gmp_intval
  • gmp_jacobi »
  • PHP Manual
  • GMP Functions
  • Inverse by modulo

gmp_invert

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_invert — Inverse by modulo

Description

gmp_invert ( GMP $a , GMP $b ) : GMP

Computes the inverse of a modulo b.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

b

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

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


Jacobi symbol

  • « gmp_invert
  • gmp_kronecker »
  • PHP Manual
  • GMP Functions
  • Jacobi symbol

gmp_jacobi

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_jacobi — Jacobi symbol

Description

gmp_jacobi ( GMP $a , GMP $p ) : int

Computes » Jacobi symbol of a and p. p should be odd and must be positive.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

p

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Should be odd and must be positive.

Return Values

A GMP number resource in PHP 5.5 and earlier, or a GMP object in PHP 5.6 and later.

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


Kronecker symbol

  • « gmp_jacobi
  • gmp_lcm »
  • PHP Manual
  • GMP Functions
  • Kronecker symbol

gmp_kronecker

(PHP 7 >= 7.3.0)

gmp_kronecker — Kronecker symbol

Description

gmp_kronecker ( mixed $a , mixed $b ) : int

This function computes the Kronecker symbol of a and b.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

b

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

Returns the Kronecker symbol of a and b

See Also

  • gmp_jacobi() - Jacobi symbol
  • gmp_legendre() - Legendre symbol


Calculate LCM

  • « gmp_kronecker
  • gmp_legendre »
  • PHP Manual
  • GMP Functions
  • Calculate LCM

gmp_lcm

(PHP 7 >= 7.3.0)

gmp_lcm — Calculate LCM

Description

gmp_lcm ( mixed $a , mixed $b ) : GMP

This function computes the least common multiple (lcm) of a and b.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

b

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

A GMP number resource in PHP 5.5 and earlier, or a GMP object in PHP 5.6 and later.

See Also

  • gmp_gcd() - Calculate GCD


Legendre symbol

  • « gmp_lcm
  • gmp_mod »
  • PHP Manual
  • GMP Functions
  • Legendre symbol

gmp_legendre

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_legendre — Legendre symbol

Description

gmp_legendre ( GMP $a , GMP $p ) : int

Compute the » Legendre symbol of a and p. p should be odd and must be positive.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

p

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Should be odd and must be positive.

Return Values

A GMP number resource in PHP 5.5 and earlier, or a GMP object in PHP 5.6 and later.

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


Modulo operation

  • « gmp_legendre
  • gmp_mul »
  • PHP Manual
  • GMP Functions
  • Modulo operation

gmp_mod

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_mod — Modulo operation

Description

gmp_mod ( GMP $n , GMP $d ) : GMP

Calculates n modulo d. The result is always non-negative, the sign of d is ignored.

Parameters

n

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

d

The modulo that is being evaluated.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

A GMP number resource in PHP 5.5 and earlier, or a GMP object in PHP 5.6 and later.

Examples

Example #1 gmp_mod() example

<?php
$mod = gmp_mod("8", "3");
echo gmp_strval($mod) . "\n";
?>

The above example will output:

2


Multiply numbers

  • « gmp_mod
  • gmp_neg »
  • PHP Manual
  • GMP Functions
  • Multiply numbers

gmp_mul

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_mul — Multiply numbers

Description

gmp_mul ( GMP $a , GMP $b ) : GMP

Multiplies a by b and returns the result.

Parameters

a

A number that will be multiplied by b.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

b

A number that will be multiplied by a.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

A GMP number resource in PHP 5.5 and earlier, or a GMP object in PHP 5.6 and later.

Examples

Example #1 gmp_mul() example

<?php
$mul = gmp_mul("12345678", "2000");
echo gmp_strval($mul) . "\n";
?>

The above example will output:

24691356000


Negate number

  • « gmp_mul
  • gmp_nextprime »
  • PHP Manual
  • GMP Functions
  • Negate number

gmp_neg

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_neg — Negate number

Description

gmp_neg ( GMP $a ) : GMP

Returns the negative value of a number.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

Returns -a, 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


Find next prime number

  • « gmp_neg
  • gmp_or »
  • PHP Manual
  • GMP Functions
  • Find next prime number

gmp_nextprime

(PHP 5 >= 5.2.0, PHP 7)

gmp_nextprime — Find next prime number

Description

gmp_nextprime ( int $a ) : GMP

Find next prime number

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

Return the next prime number greater than a, 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.


Bitwise OR

  • « gmp_nextprime
  • gmp_perfect_power »
  • PHP Manual
  • GMP Functions
  • Bitwise OR

gmp_or

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_or — Bitwise OR

Description

gmp_or ( GMP $a , GMP $b ) : GMP

Calculates bitwise inclusive OR of two GMP numbers.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

b

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

A GMP number resource in PHP 5.5 and earlier, or a GMP object in PHP 5.6 and later.

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


Perfect power check

  • « gmp_or
  • gmp_perfect_square »
  • PHP Manual
  • GMP Functions
  • Perfect power check

gmp_perfect_power

(PHP 7 >= 7.3.0)

gmp_perfect_power — Perfect power check

Description

gmp_perfect_power ( mixed $a ) : bool

Checks whether a is a perfect power.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

Returns TRUE if a is a perfect power, FALSE otherwise.

See Also

  • gmp_perfect_square() - Perfect square check


Perfect square check

  • « gmp_perfect_power
  • gmp_popcount »
  • PHP Manual
  • GMP Functions
  • Perfect square check

gmp_perfect_square

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_perfect_square — Perfect square check

Description

gmp_perfect_square ( GMP $a ) : bool

Check if a number is a perfect square.

Parameters

a

The number being checked as a perfect square.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

Returns TRUE if a 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


Population count

  • « gmp_perfect_square
  • gmp_pow »
  • PHP Manual
  • GMP Functions
  • Population count

gmp_popcount

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_popcount — Population count

Description

gmp_popcount ( GMP $a ) : int

Get the population count.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

The population count of a, as an integer.

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


Raise number into power

  • « gmp_popcount
  • gmp_powm »
  • PHP Manual
  • GMP Functions
  • Raise number into power

gmp_pow

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_pow — Raise number into power

Description

gmp_pow ( GMP $base , int $exp ) : GMP

Raise base into power exp.

Parameters

base

The base number.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

exp

The positive power to raise the base.

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


Raise number into power with modulo

  • « gmp_pow
  • gmp_prob_prime »
  • PHP Manual
  • GMP Functions
  • Raise number into power with modulo

gmp_powm

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_powm — Raise number into power with modulo

Description

gmp_powm ( GMP $base , GMP $exp , GMP $mod ) : GMP

Calculate (base raised into power exp) modulo mod. If exp is negative, result is undefined.

Parameters

base

The base number.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

exp

The positive power to raise the base.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

mod

The modulo.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

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


Check if number is "probably prime"

  • « gmp_powm
  • gmp_random_bits »
  • PHP Manual
  • GMP Functions
  • Check if number is "probably prime"

gmp_prob_prime

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_prob_prime — Check if number is "probably prime"

Description

gmp_prob_prime ( GMP $a [, int $reps = 10 ] ) : int

The function uses Miller-Rabin's probabilistic test to check if a number is a prime.

Parameters

a

The number being checked as a prime.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

reps

Reasonable values of reps vary from 5 to 10 (default being 10); a higher value lowers the probability for a non-prime to pass as a "probable" prime.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

If this function returns 0, a is definitely not prime. If it returns 1, then a is "probably" prime. If it returns 2, then a 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


Random number

  • « gmp_prob_prime
  • gmp_random_range »
  • PHP Manual
  • GMP Functions
  • Random number

gmp_random_bits

(PHP 5 >= 5.6.3, PHP 7)

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.

Parameters

bits

The number of bits.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

A random GMP number.

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


Random number

  • « gmp_random_bits
  • gmp_random_seed »
  • PHP Manual
  • GMP Functions
  • Random number

gmp_random_range

(PHP 5 >= 5.6.3, PHP 7)

gmp_random_range — Random number

Description

gmp_random_range ( GMP $min , GMP $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.

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

A random GMP number.

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


Sets the RNG seed

  • « gmp_random_range
  • gmp_random »
  • PHP Manual
  • GMP Functions
  • Sets the RNG seed

gmp_random_seed

(PHP 7)

gmp_random_seed — Sets the RNG seed

Description

gmp_random_seed ( mixed $seed ) : void

Parameters

seed

The seed to be set for the gmp_random(), gmp_random_bits(), and gmp_random_range() functions.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

Returns NULL on success or FALSE on failure.

Errors/Exceptions

Issues an E_WARNING and returns FALSE if seed is not valid.

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() - Random number


Random number

  • « gmp_random_seed
  • gmp_root »
  • PHP Manual
  • GMP Functions
  • Random number

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. 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.

Parameters

limiter

The limiter.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

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


Take the integer part of nth root

  • « gmp_random
  • gmp_rootrem »
  • PHP Manual
  • GMP Functions
  • Take the integer part of nth root

gmp_root

(PHP 5 >= 5.6.0, PHP 7)

gmp_root — Take the integer part of nth root

Description

gmp_root ( GMP $a , int $nth ) : GMP

Takes the nth root of a and returns the integer component of the result.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

nth

The positive root to take of a.

Return Values

The integer component of the resultant root, as a GMP number.


Take the integer part and remainder of nth root

  • « gmp_root
  • gmp_scan0 »
  • PHP Manual
  • GMP Functions
  • Take the integer part and remainder of nth root

gmp_rootrem

(PHP 5 >= 5.6.0, PHP 7)

gmp_rootrem — Take the integer part and remainder of nth root

Description

gmp_rootrem ( GMP $a , int $nth ) : array

Takes the nth root of a and returns the integer component and remainder of the result.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

nth

The positive root to take of a.

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.


Scan for 0

  • « gmp_rootrem
  • gmp_scan1 »
  • PHP Manual
  • GMP Functions
  • Scan for 0

gmp_scan0

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_scan0 — Scan for 0

Description

gmp_scan0 ( GMP $a , int $start ) : int

Scans a, starting with bit start, towards more significant bits, until the first clear bit is found.

Parameters

a

The number to scan.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

start

The starting bit.

Return Values

Returns the index of the found bit, as an integer. 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


Scan for 1

  • « gmp_scan0
  • gmp_setbit »
  • PHP Manual
  • GMP Functions
  • Scan for 1

gmp_scan1

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_scan1 — Scan for 1

Description

gmp_scan1 ( GMP $a , int $start ) : int

Scans a, starting with bit start, towards more significant bits, until the first set bit is found.

Parameters

a

The number to scan.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

start

The starting bit.

Return Values

Returns the index of the found bit, as an integer. 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


Set bit

  • « gmp_scan1
  • gmp_sign »
  • PHP Manual
  • GMP Functions
  • Set bit

gmp_setbit

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_setbit — Set bit

Description

gmp_setbit ( GMP $a , int $index [, bool $bit_on = TRUE ] ) : void

Sets bit index in a.

Parameters

a

The value to modify.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

index

The index of the bit to set. Index 0 represents the least significant bit.

bit_on

True to set the bit (set it to 1/on); false to clear the bit (set it to 0/off).

Return Values

A GMP number resource in PHP 5.5 and earlier, or a GMP object in PHP 5.6 and later.

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 resource 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


Sign of number

  • « gmp_setbit
  • gmp_sqrt »
  • PHP Manual
  • GMP Functions
  • Sign of number

gmp_sign

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_sign — Sign of number

Description

gmp_sign ( GMP $a ) : int

Checks the sign of a number.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to an integer.

Return Values

Returns 1 if a is positive, -1 if a is negative, and 0 if a 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


Calculate square root

  • « gmp_sign
  • gmp_sqrtrem »
  • PHP Manual
  • GMP Functions
  • Calculate square root

gmp_sqrt

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_sqrt — Calculate square root

Description

gmp_sqrt ( GMP $a ) : GMP

Calculates square root of a.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

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


Square root with remainder

  • « gmp_sqrt
  • gmp_strval »
  • PHP Manual
  • GMP Functions
  • Square root with remainder

gmp_sqrtrem

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_sqrtrem — Square root with remainder

Description

gmp_sqrtrem ( GMP $a ) : array

Calculate the square root of a number, with remainder.

Parameters

a

The number being square rooted.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

Returns array where first element is the integer square root of a and the second is the remainder (i.e., the difference between a 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


Convert GMP number to string

  • « gmp_sqrtrem
  • gmp_sub »
  • PHP Manual
  • GMP Functions
  • Convert GMP number to string

gmp_strval

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_strval — Convert GMP number to string

Description

gmp_strval ( GMP $gmpnumber [, int $base = 10 ] ) : string

Convert GMP number to string representation in base base. The default base is 10.

Parameters

gmpnumber

The GMP number that will be converted to a string.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

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.

Changelog

Version | Description
5.3.2 | The base was extended from 2 to 36, to 2 to 62 and -2 to -36.

Notes

Note:

To use the extended base introduced in PHP 5.3.2, then PHP must be compiled against GMP 4.2.0 or greater.

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));
?>


Subtract numbers

  • « gmp_strval
  • gmp_testbit »
  • PHP Manual
  • GMP Functions
  • Subtract numbers

gmp_sub

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_sub — Subtract numbers

Description

gmp_sub ( GMP $a , GMP $b ) : GMP

Subtracts b from a and returns the result.

Parameters

a

The number being subtracted from.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

b

The number subtracted from a.

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

A GMP number resource in PHP 5.5 and earlier, or a GMP object in PHP 5.6 and later.

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


Tests if a bit is set

  • « gmp_sub
  • gmp_xor »
  • PHP Manual
  • GMP Functions
  • Tests if a bit is set

gmp_testbit

(PHP 5 >= 5.3.0, PHP 7)

gmp_testbit — Tests if a bit is set

Description

gmp_testbit ( GMP $a , int $index ) : bool

Tests if the specified bit is set.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

index

The bit to test

Return Values

Returns TRUE if the bit is set in resource $a, 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


Bitwise XOR

  • « gmp_testbit
  • GMP »
  • PHP Manual
  • GMP Functions
  • Bitwise XOR

gmp_xor

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_xor — Bitwise XOR

Description

gmp_xor ( GMP $a , GMP $b ) : GMP

Calculates bitwise exclusive OR (XOR) of two GMP numbers.

Parameters

a

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

b

Either a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or a numeric string provided that it is possible to convert the latter to a number.

Return Values

A GMP number resource in PHP 5.5 and earlier, or a GMP object in PHP 5.6 and later.

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


The GMP class

(PHP 5 >= 5.6.0, PHP 7)

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.

GMP implements Serializable {
}


Lapack

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Lapack — The Lapack class
    • Lapack::eigenValues — This function returns the eigenvalues for a given square matrix
    • Lapack::identity — Return an identity matrix
    • Lapack::leastSquaresByFactorisation — Calculate the linear least squares solution of a matrix using QR factorisation
    • Lapack::leastSquaresBySVD — Solve the linear least squares problem, using SVD
    • Lapack::pseudoInverse — Calculate the inverse of a matrix
    • Lapack::singularValues — Calculated the singular values of a matrix
    • Lapack::solveLinearEquation — Solve a system of linear equations
  • LapackException — The LapackException class


Introduction

LAPACK is written in Fortran 90 and provides routines for solving systems of simultaneous linear equations, least-squares solutions of linear systems of equations, eigenvalue problems, and singular value problems. This extension wraps the LAPACKE C bindings to allow access to several processes exposed by the library. Most functions work with arrays of arrays, representing rectangular matrices in row major order - so a two by two matrix [1 2; 3 4] would be array(array(1, 2), array(3, 4))


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

Lapack requires the LAPACK and LAPACKE libraries.


Installation

Most distribution LAPACK packages do not include lapacke, so the easiest method is to build from source:

  svn co https://icl.cs.utk.edu/svn/lapack-dev/lapack/trunk lapack
  cd lapack
  mkdir build
  cd build
  cmake -D BUILD_SHARED_LIBS=ON -D LAPACKE=ON ../
  make
  sudo make install


  • « Resource Types
  • Lapack »
  • PHP Manual
  • Lapack
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


The Lapack class

(PECL lapack >= 0.1.0)

Introduction

LAPACK is written in Fortran 90 and provides routines for solving systems of simultaneous linear equations, least-squares solutions of linear systems of equations, eigenvalue problems, and singular value problems. This extension wraps the LAPACKE C bindings to allow access to several processes exposed by the library. Most functions work with arrays of arrays, representing rectangular matrices in row major order - so a two by two matrix [1 2; 3 4] would be array(array(1, 2), array(3, 4)).

All of the functions are called statically, for example $eig = Lapack::eigenvalues($a);

Class synopsis

Lapack {
/* Methods */
public static eigenValues ( array $a [, array $left [, array $right ]] ) : array
public static identity ( int $n ) : array
public static leastSquaresByFactorisation ( array $a , array $b ) : array
public static leastSquaresBySVD ( array $a , array $b ) : array
public static pseudoInverse ( array $a ) : array
public static singularValues ( array $a ) : array
public static solveLinearEquation ( array $a , array $b ) : array
}

Table of Contents

  • Lapack::eigenValues — This function returns the eigenvalues for a given square matrix
  • Lapack::identity — Return an identity matrix
  • Lapack::leastSquaresByFactorisation — Calculate the linear least squares solution of a matrix using QR factorisation
  • Lapack::leastSquaresBySVD — Solve the linear least squares problem, using SVD
  • Lapack::pseudoInverse — Calculate the inverse of a matrix
  • Lapack::singularValues — Calculated the singular values of a matrix
  • Lapack::solveLinearEquation — Solve a system of linear equations


This function returns the eigenvalues for a given square matrix

  • « Lapack
  • Lapack::identity »
  • PHP Manual
  • Lapack
  • This function returns the eigenvalues for a given square matrix

Lapack::eigenValues

(PECL lapack >= 0.1.0)

Lapack::eigenValues — This function returns the eigenvalues for a given square matrix

Description

public static Lapack::eigenValues ( array $a [, array $left [, array $right ]] ) : array

Calculate the eigenvalues for a square matrix, and optionally calculate the left and right eigenvectors.

Parameters

a

The matrix to calculate the eigenvalues for.

left

Optional parameter - if an array is passed here, it will be filled with the left eigenvectors

right

Optional parameter - if an array is passed here, it will be filled with the right eigenvectors

Return Values

Returns an array of arrays representing the eigenvalues for the array.

Examples

Example #1 Using Lapack::eigenValues():

<?php

 $a = array(
     array(-1.01,   0.86,  -4.60,  3.31,  -4.81  ),
     array( 3.98,   0.53,  -7.04,  5.29,   3.55  ),
     array( 3.30,   8.26,  -3.89,  8.20,  -1.51  ),
     array( 4.43,   4.96,  -7.66, -7.33,   6.18  ),
     array( 7.31,  -6.43,  -6.16,  2.47,   5.58  ),
 );

 $result = Lapack::eigenValues($a);

 ?>


Return an identity matrix

  • « Lapack::eigenValues
  • Lapack::leastSquaresByFactorisation »
  • PHP Manual
  • Lapack
  • Return an identity matrix

Lapack::identity

(PECL lapack >= 0.1.0)

Lapack::identity — Return an identity matrix

Description

public static Lapack::identity ( int $n ) : array

Return a size n identity matrix

Parameters

n

The height and width of the identity matrix.

Return Values

Will return a an array of n arrays, each containing n entries. The diagonals of the matrix will be 1s, the other positions 0.


Calculate the linear least squares solution of a matrix using QR factorisation

  • « Lapack::identity
  • Lapack::leastSquaresBySVD »
  • PHP Manual
  • Lapack
  • Calculate the linear least squares solution of a matrix using QR factorisation

Lapack::leastSquaresByFactorisation

(PECL lapack >= 0.1.0)

Lapack::leastSquaresByFactorisation — Calculate the linear least squares solution of a matrix using QR factorisation

Description

public static Lapack::leastSquaresByFactorisation ( array $a , array $b ) : array

Solve the linear least squares problem, find min x in || B - Ax || Returns an array representing x. Expects arrays of arrays, and will return an array of arrays in the dimension B num cols x A num cols. Uses QR or LQ factorisation on matrix A.

Parameters

a

Matrix A

b

Matrix B

Return Values

Array of the solution matrix

Examples

Example #1 Using Lapack::leastSquaresByFactorisation():

<?php

 $a = array(
     array( 1.44,  -7.84,  -4.39,   4.53),
     array(-9.96,  -0.28,  -3.24,   3.83),
     array(-7.55,   3.24,   6.27,  -6.64),
     array( 8.34,   8.09,   5.28,   2.06),
     array( 7.08,   2.52,   0.74,  -2.47),
     array(-5.45,  -5.70,  -1.19,   4.70),
 );

 $b = array(
     array( 8.58,   9.35),
     array( 8.26,  -4.43),
     array( 8.48,  -0.70),
     array(-5.28,  -0.26),
     array( 5.72,  -7.36),
     array( 8.93,  -2.52),
 );

 $result = Lapack::leastSquaresByFactorisation($a, $b);
 ?>


Solve the linear least squares problem, using SVD

  • « Lapack::leastSquaresByFactorisation
  • Lapack::pseudoInverse »
  • PHP Manual
  • Lapack
  • Solve the linear least squares problem, using SVD

Lapack::leastSquaresBySVD

(PECL lapack >= 0.1.0)

Lapack::leastSquaresBySVD — Solve the linear least squares problem, using SVD

Description

public static Lapack::leastSquaresBySVD ( array $a , array $b ) : array

Solve the linear least squares problem, find min x in || B - Ax || Returns an array representing x. Expects arrays of arrays, and will return an array of arrays in the dimension B num cols x A num cols. Uses SVD with a divide and conquer algorithm.

Parameters

a

Matrix A

b

Matrix B

Return Values

Returns the solution as an array of arrays.

Examples

Example #1 Using Lapack::leastSquaresBySVD():

<?php

  $a = array(
      array( 1.44,  -7.84,  -4.39,   4.53),
      array(-9.96,  -0.28,  -3.24,   3.83),
      array(-7.55,   3.24,   6.27,  -6.64),
      array( 8.34,   8.09,   5.28,   2.06),
      array( 7.08,   2.52,   0.74,  -2.47),
      array(-5.45,  -5.70,  -1.19,   4.70),
  );

  $b = array(
      array( 8.58,   9.35),
      array( 8.26,  -4.43),
      array( 8.48,  -0.70),
      array(-5.28,  -0.26),
      array( 5.72,  -7.36),
      array( 8.93,  -2.52),
  );

  $result = Lapack::leastSquaresBySVD($a, $b);

  ?>


Calculate the inverse of a matrix

  • « Lapack::leastSquaresBySVD
  • Lapack::singularValues »
  • PHP Manual
  • Lapack
  • Calculate the inverse of a matrix

Lapack::pseudoInverse

(PECL lapack >= 0.1.0)

Lapack::pseudoInverse — Calculate the inverse of a matrix

Description

public static Lapack::pseudoInverse ( array $a ) : array

Find the pseudoinverse of a matrix A.

Parameters

a

Matrix to invert

Return Values

Inverted matrix (array of arrays).

Examples

Example #1 Using Lapack::pseudoInverse():

<?php

   $a = array(
       array( 8, 1, 6 ),
       array( 3, 5, 7 ),
       array( 4, 9, 2 ),
   );

   $result = Lapack::pseudoInverse($a);

   ?>


Calculated the singular values of a matrix

  • « Lapack::pseudoInverse
  • Lapack::solveLinearEquation »
  • PHP Manual
  • Lapack
  • Calculated the singular values of a matrix

Lapack::singularValues

(PECL lapack >= 0.1.0)

Lapack::singularValues — Calculated the singular values of a matrix

Description

public static Lapack::singularValues ( array $a ) : array

Calculate the singular values of the matrix A.

Parameters

a

The matrix to calculate the singular values for

Return Values

The singular values

Examples

Example #1 Using Lapack::singularValues():

<?php

    $a = array(
        array( 7.52,  -1.10,  -7.95,  1.08  ),
        array(-0.76,   0.62,   9.34, -7.10  ),
        array( 5.13,   6.62,  -5.66,  0.87  ),
        array(-4.75,   8.52,   5.75,  5.30  ),
        array( 1.33,   4.91,  -5.49, -3.52  ),
        array(-2.40,  -6.77,   2.34,  3.95  ),
    );

    $result = Lapack::singularValues($a);

    ?>


Solve a system of linear equations

  • « Lapack::singularValues
  • LapackException »
  • PHP Manual
  • Lapack
  • Solve a system of linear equations

Lapack::solveLinearEquation

(PECL lapack >= 0.1.0)

Lapack::solveLinearEquation — Solve a system of linear equations

Description

public static Lapack::solveLinearEquation ( array $a , array $b ) : array

This function computes the solution to the system of linear equations with a square matrix A and multiple right-hand sides B. Solves A * X = B for multiple B.

Parameters

a

Square matrix of linear equations

b

Right hand side to be solved for

Return Values

Matrix X

Examples

Example #1 Using Lapack::singularValues():

<?php

    $a = array(
        array( 6.80,  -6.05,  -0.45,   8.32,  -9.67   ),
        array(-2.11,  -3.30,   2.58,   2.71,  -5.14   ),
        array( 5.66,   5.36,  -2.70,   4.35,  -7.26   ),
        array( 5.97,  -4.44,   0.27,  -7.17,   6.08   ),
        array( 8.23,   1.08,   9.04,   2.14,  -6.87   ),
    );

    $b = array(
       array(  4.02,  -1.56,   9.81   ),
       array(  6.19,   4.00,  -4.09   ),
       array( -8.22,  -8.67,  -4.57   ),
       array( -7.57,   1.75,  -8.61   ),
       array( -3.03,   2.86,   8.99   ),
    );

    $result = Lapack::solveLinearEquation($a, $b);

    ?>


The LapackException class

(PECL lapack >= 0.1.0)

Introduction

Exception thrown when an error is caught in the LAPACK functions

Class synopsis

lapackexception extends Exception {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


Mathematical Functions

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Math Functions
    • abs — Absolute value
    • acos — Arc cosine
    • acosh — Inverse hyperbolic cosine
    • asin — Arc sine
    • asinh — Inverse hyperbolic sine
    • atan2 — Arc tangent of two variables
    • atan — Arc tangent
    • 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(number) - 1, computed in a way that is accurate even when the value of number is close to zero
    • floor — Round fractions down
    • fmod — Returns the floating point remainder (modulo) of the division of the arguments
    • getrandmax — Show largest possible random value
    • hexdec — Hexadecimal to decimal
    • hypot — Calculate the length of the hypotenuse of a right-angle triangle
    • intdiv — Integer division
    • is_finite — Finds whether a value is a legal finite number
    • is_infinite — Finds whether a value is infinite
    • is_nan — Finds whether a value is not a number
    • lcg_value — Combined linear congruential generator
    • 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
    • log — Natural logarithm
    • max — Find highest value
    • min — Find lowest value
    • mt_getrandmax — Show largest possible random value
    • mt_rand — Generate a random value via the Mersenne Twister Random Number Generator
    • mt_srand — Seeds the Mersenne Twister Random Number Generator
    • octdec — Octal to decimal
    • pi — Get value of pi
    • pow — Exponential expression
    • rad2deg — Converts the radian number to the equivalent number in degrees
    • rand — Generate a random integer
    • round — Rounds a float
    • sin — Sine
    • sinh — Hyperbolic sine
    • sqrt — Square root
    • srand — Seed the random number generator
    • tan — Tangent
    • tanh — Hyperbolic tangent


Introduction

These math functions will only handle values within the range of the integer and float types on your computer (this corresponds currently to the C types long resp. double). If you need to handle bigger numbers, take a look at the arbitrary precision math functions.

See also the manual page on arithmetic operators.


Predefined Constants

The constants below are always available as part of the PHP core.

Math constants
Constant | Value | Description | Availability
M_PI | 3.14159265358979323846 | Pi |
M_E | 2.7182818284590452354 | e |
M_LOG2E | 1.4426950408889634074 | log_2 e |
M_LOG10E | 0.43429448190325182765 | log_10 e |
M_LN2 | 0.69314718055994530942 | log_e 2 |
M_LN10 | 2.30258509299404568402 | log_e 10 |
M_PI_2 | 1.57079632679489661923 | pi/2 |
M_PI_4 | 0.78539816339744830962 | pi/4 |
M_1_PI | 0.31830988618379067154 | 1/pi |
M_2_PI | 0.63661977236758134308 | 2/pi |
M_SQRTPI | 1.77245385090551602729 | sqrt(pi) | PHP 5.2.0
M_2_SQRTPI | 1.12837916709551257390 | 2/sqrt(pi) |
M_SQRT2 | 1.41421356237309504880 | sqrt(2) |
M_SQRT3 | 1.73205080756887729352 | sqrt(3) | PHP 5.2.0
M_SQRT1_2 | 0.70710678118654752440 | 1/sqrt(2) |
M_LNPI | 1.14472988584940017414 | log_e(pi) | PHP 5.2.0
M_EULER | 0.57721566490153286061 | Euler constant | PHP 5.2.0
PHP_ROUND_HALF_UP | 1 | Round halves up | PHP 5.3.0
PHP_ROUND_HALF_DOWN | 2 | Round halves down | PHP 5.3.0
PHP_ROUND_HALF_EVEN | 3 | Round halves to even numbers | PHP 5.3.0
PHP_ROUND_HALF_ODD | 4 | Round halves to odd numbers | PHP 5.3.0
NAN | NAN (as a float) | Not A Number |
INF | INF (as a float) | The infinite |

All constants without a labeled PHP version above are available starting with PHP 5.0.0.


Math Functions

Table of Contents

  • abs — Absolute value
  • acos — Arc cosine
  • acosh — Inverse hyperbolic cosine
  • asin — Arc sine
  • asinh — Inverse hyperbolic sine
  • atan2 — Arc tangent of two variables
  • atan — Arc tangent
  • 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(number) - 1, computed in a way that is accurate even when the value of number is close to zero
  • floor — Round fractions down
  • fmod — Returns the floating point remainder (modulo) of the division of the arguments
  • getrandmax — Show largest possible random value
  • hexdec — Hexadecimal to decimal
  • hypot — Calculate the length of the hypotenuse of a right-angle triangle
  • intdiv — Integer division
  • is_finite — Finds whether a value is a legal finite number
  • is_infinite — Finds whether a value is infinite
  • is_nan — Finds whether a value is not a number
  • lcg_value — Combined linear congruential generator
  • 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
  • log — Natural logarithm
  • max — Find highest value
  • min — Find lowest value
  • mt_getrandmax — Show largest possible random value
  • mt_rand — Generate a random value via the Mersenne Twister Random Number Generator
  • mt_srand — Seeds the Mersenne Twister Random Number Generator
  • octdec — Octal to decimal
  • pi — Get value of pi
  • pow — Exponential expression
  • rad2deg — Converts the radian number to the equivalent number in degrees
  • rand — Generate a random integer
  • round — Rounds a float
  • sin — Sine
  • sinh — Hyperbolic sine
  • sqrt — Square root
  • srand — Seed the random number generator
  • tan — Tangent
  • tanh — Hyperbolic tangent


Absolute value

  • « Math Functions
  • acos »
  • PHP Manual
  • Math Functions
  • Absolute value

abs

(PHP 4, PHP 5, PHP 7)

abs — Absolute value

Description

abs ( mixed $number ) : number

Returns the absolute value of number.

Parameters

number

The numeric value to process

Return Values

The absolute value of number. If the argument number is of type float, the return type is also float, otherwise it is integer (as float usually has a bigger value range than integer).

Examples

Example #1 abs() example

<?php
echo abs(-4.2); // 4.2 (double/float)
echo abs(5);    // 5 (integer)
echo abs(-5);   // 5 (integer)
?>

See Also

  • gmp_abs() - Absolute value
  • gmp_sign() - Sign of number


Arc cosine

  • « abs
  • acosh »
  • PHP Manual
  • Math Functions
  • Arc cosine

acos

(PHP 4, PHP 5, PHP 7)

acos — Arc cosine

Description

acos ( float $arg ) : float

Returns the arc cosine of arg in radians. acos() is the inverse function of cos(), which means that a==cos(acos(a)) for every value of a that is within acos()' range.

Parameters

arg

The argument to process

Return Values

The arc cosine of arg in radians.

See Also

  • cos() - Cosine
  • acosh() - Inverse hyperbolic cosine
  • asin() - Arc sine
  • atan() - Arc tangent


Inverse hyperbolic cosine

  • « acos
  • asin »
  • PHP Manual
  • Math Functions
  • Inverse hyperbolic cosine

acosh

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

acosh — Inverse hyperbolic cosine

Description

acosh ( float $arg ) : float

Returns the inverse hyperbolic cosine of arg, i.e. the value whose hyperbolic cosine is arg.

Parameters

arg

The value to process

Return Values

The inverse hyperbolic cosine of arg

Changelog

Version | Description
5.3.0 | This function is now available on all platforms

See Also

  • cosh() - Hyperbolic cosine
  • acos() - Arc cosine
  • asinh() - Inverse hyperbolic sine
  • atanh() - Inverse hyperbolic tangent


Arc sine

  • « acosh
  • asinh »
  • PHP Manual
  • Math Functions
  • Arc sine

asin

(PHP 4, PHP 5, PHP 7)

asin — Arc sine

Description

asin ( float $arg ) : float

Returns the arc sine of arg in radians. asin() is the inverse function of sin(), which means that a==sin(asin(a)) for every value of a that is within asin()'s range.

Parameters

arg

The argument to process

Return Values

The arc sine of arg in radians

See Also

  • sin() - Sine
  • asinh() - Inverse hyperbolic sine
  • acos() - Arc cosine
  • atan() - Arc tangent


Inverse hyperbolic sine

  • « asin
  • atan2 »
  • PHP Manual
  • Math Functions
  • Inverse hyperbolic sine

asinh

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

asinh — Inverse hyperbolic sine

Description

asinh ( float $arg ) : float

Returns the inverse hyperbolic sine of arg, i.e. the value whose hyperbolic sine is arg.

Parameters

arg

The argument to process

Return Values

The inverse hyperbolic sine of arg

Changelog

Version | Description
5.3.0 | This function is now available on all platforms

See Also

  • sinh() - Hyperbolic sine
  • asin() - Arc sine
  • acosh() - Inverse hyperbolic cosine
  • atanh() - Inverse hyperbolic tangent


Arc tangent of two variables

  • « asinh
  • atan »
  • PHP Manual
  • Math Functions
  • Arc tangent of two variables

atan2

(PHP 4, PHP 5, PHP 7)

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


Arc tangent

  • « atan2
  • atanh »
  • PHP Manual
  • Math Functions
  • Arc tangent

atan

(PHP 4, PHP 5, PHP 7)

atan — Arc tangent

Description

atan ( float $arg ) : float

Returns the arc tangent of arg in radians. atan() is the inverse function of tan(), which means that a==tan(atan(a)) for every value of a that is within atan()'s range.

Parameters

arg

The argument to process

Return Values

The arc tangent of arg in radians.

See Also

  • tan() - Tangent
  • atanh() - Inverse hyperbolic tangent
  • asin() - Arc sine
  • acos() - Arc cosine


Inverse hyperbolic tangent

  • « atan
  • base_convert »
  • PHP Manual
  • Math Functions
  • Inverse hyperbolic tangent

atanh

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

atanh — Inverse hyperbolic tangent

Description

atanh ( float $arg ) : float

Returns the inverse hyperbolic tangent of arg, i.e. the value whose hyperbolic tangent is arg.

Parameters

arg

The argument to process

Return Values

Inverse hyperbolic tangent of arg

Changelog

Version | Description
5.3.0 | This function is now available on all platforms

See Also

  • tanh() - Hyperbolic tangent
  • atan() - Arc tangent
  • asinh() - Inverse hyperbolic sine
  • acosh() - Inverse hyperbolic cosine


Convert a number between arbitrary bases

  • « atanh
  • bindec »
  • PHP Manual
  • Math Functions
  • Convert a number between arbitrary bases

base_convert

(PHP 4, PHP 5, PHP 7)

base_convert — Convert a number between arbitrary bases

Description

base_convert ( string $number , int $frombase , int $tobase ) : string

Returns a string containing number represented in base tobase. The base in which number is given is specified in frombase. Both frombase and tobase 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. number is interpreted case-insensitively.

Warning

base_convert() may lose precision on large numbers due to properties related to the internal "double" or "float" type used. Please see the Floating point numbers section in the manual for more specific information and limitations.

Parameters

number

The number to convert. Any invalid characters in number are silently ignored. As of PHP 7.4.0 supplying any invalid characters is deprecated.

frombase

The base number is in

tobase

The base to convert number to

Return Values

number converted to base tobase

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


Binary to decimal

  • « base_convert
  • ceil »
  • PHP Manual
  • Math Functions
  • Binary to decimal

bindec

(PHP 4, PHP 5, PHP 7)

bindec — Binary to decimal

Description

bindec ( string $binary_string ) : number

Returns the decimal equivalent of the binary number represented by the binary_string argument.

bindec() converts a binary number to an integer 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 integer 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


Round fractions up

  • « bindec
  • cos »
  • PHP Manual
  • Math Functions
  • Round fractions up

ceil

(PHP 4, PHP 5, PHP 7)

ceil — Round fractions up

Description

ceil ( float $value ) : float

Returns the next highest integer value by rounding up value if necessary.

Parameters

value

The value to round

Return Values

value 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 integer.

Examples

Example #1 ceil() example

<?php
echo ceil(4.3);    // 5
echo ceil(9.999);  // 10
echo ceil(-3.14);  // -3
?>

See Also

  • floor() - Round fractions down
  • round() - Rounds a float


Cosine

  • « ceil
  • cosh »
  • PHP Manual
  • Math Functions
  • Cosine

cos

(PHP 4, PHP 5, PHP 7)

cos — Cosine

Description

cos ( float $arg ) : float

cos() returns the cosine of the arg parameter. The arg parameter is in radians.

Parameters

arg

An angle in radians

Return Values

The cosine of arg

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


Hyperbolic cosine

  • « cos
  • decbin »
  • PHP Manual
  • Math Functions
  • Hyperbolic cosine

cosh

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

cosh — Hyperbolic cosine

Description

cosh ( float $arg ) : float

Returns the hyperbolic cosine of arg, defined as (exp(arg) + exp(-arg))/2.

Parameters

arg

The argument to process

Return Values

The hyperbolic cosine of arg

See Also

  • cos() - Cosine
  • acosh() - Inverse hyperbolic cosine
  • sinh() - Hyperbolic sine
  • tanh() - Hyperbolic tangent


Decimal to binary

  • « cosh
  • dechex »
  • PHP Manual
  • Math Functions
  • Decimal to binary

decbin

(PHP 4, PHP 5, PHP 7)

decbin — Decimal to binary

Description

decbin ( int $number ) : string

Returns a string containing a binary representation of the given number argument.

Parameters

number

Decimal value to convert

Range of inputs on 32-bit machines
positive number | negative number | 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 number | negative number | 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 number

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(), using %b, %032b or %064b as the format


Decimal to hexadecimal

  • « decbin
  • decoct »
  • PHP Manual
  • Math Functions
  • Decimal to hexadecimal

dechex

(PHP 4, PHP 5, PHP 7)

dechex — Decimal to hexadecimal

Description

dechex ( int $number ) : string

Returns a string containing a hexadecimal representation of the given unsigned number 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

number

The decimal value to convert.

As PHP's integer 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 number.

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


Decimal to octal

  • « dechex
  • deg2rad »
  • PHP Manual
  • Math Functions
  • Decimal to octal

decoct

(PHP 4, PHP 5, PHP 7)

decoct — Decimal to octal

Description

decoct ( int $number ) : string

Returns a string containing an octal representation of the given number 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

number

Decimal value to convert

Return Values

Octal string representation of number

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


Converts the number in degrees to the radian equivalent

  • « decoct
  • exp »
  • PHP Manual
  • Math Functions
  • Converts the number in degrees to the radian equivalent

deg2rad

(PHP 4, PHP 5, PHP 7)

deg2rad — Converts the number in degrees to the radian equivalent

Description

deg2rad ( float $number ) : float

This function converts number from degrees to the radian equivalent.

Parameters

number

Angular value in degrees

Return Values

The radian equivalent of number

Examples

Example #1 deg2rad() example

<?php

echo deg2rad(45); // 0.785398163397
var_dump(deg2rad(45) === M_PI_4); // bool(true)

?>

See Also

  • rad2deg() - Converts the radian number to the equivalent number in degrees


Calculates the exponent of e

  • « deg2rad
  • expm1 »
  • PHP Manual
  • Math Functions
  • Calculates the exponent of e

exp

(PHP 4, PHP 5, PHP 7)

exp — Calculates the exponent of e

Description

exp ( float $arg ) : float

Returns e raised to the power of arg.

Note:

'e' is the base of the natural system of logarithms, or approximately 2.718282.

Parameters

arg

The argument to process

Return Values

'e' raised to the power of arg

Examples

Example #1 exp() example

<?php
echo exp(12) . "\n";
echo exp(5.7);
?>

The above example will output:

1.6275E+005
298.87

See Also

  • log() - Natural logarithm
  • pow() - Exponential expression


Returns exp(number) - 1, computed in a way that is accurate even when the value of number is close to zero

  • « exp
  • floor »
  • PHP Manual
  • Math Functions
  • Returns exp(number) - 1, computed in a way that is accurate even when the value of number is close to zero

expm1

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

expm1 — Returns exp(number) - 1, computed in a way that is accurate even when the value of number is close to zero

Description

expm1 ( float $arg ) : float

expm1() returns the equivalent to 'exp(arg) - 1' computed in a way that is accurate even if the value of arg is near zero, a case where 'exp (arg) - 1' would be inaccurate due to subtraction of two numbers that are nearly equal.

Parameters

arg

The argument to process

Return Values

'e' to the power of arg minus one

Changelog

Version | Description
5.3.0 | This function is now available on all platforms

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


Round fractions down

  • « expm1
  • fmod »
  • PHP Manual
  • Math Functions
  • Round fractions down

floor

(PHP 4, PHP 5, PHP 7)

floor — Round fractions down

Description

floor ( float $value ) : float

Returns the next lowest integer value (as float) by rounding down value if necessary.

Parameters

value

The numeric value to round

Return Values

value rounded to the next lowest integer. The return value of floor() is still of type float because the value range of float is usually bigger than that of integer. This function returns FALSE in case of an error (e.g. passing an array).

Examples

Example #1 floor() example

<?php
echo floor(4.3);   // 4
echo floor(9.999); // 9
echo floor(-3.14); // -4
?>

See Also

  • ceil() - Round fractions up
  • round() - Rounds a float


Returns the floating point remainder (modulo) of the division of the arguments

  • « floor
  • getrandmax »
  • PHP Manual
  • Math Functions
  • Returns the floating point remainder (modulo) of the division of the arguments

fmod

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

fmod — Returns the floating point remainder (modulo) of the division of the arguments

Description

fmod ( float $x , float $y ) : float

Returns the floating point remainder of dividing the dividend (x) by the divisor (y). The remainder (r) is defined as: x = i * y + r, for some integer i. If y is non-zero, r has the same sign as x and a magnitude less than the magnitude of y.

Parameters

x

The dividend

y

The divisor

Return Values

The floating point remainder of x/y

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
?>

See Also

  • / - Floating-point division
  • % - Integer modulus
  • intdiv() - Integer division


Show largest possible random value

  • « fmod
  • hexdec »
  • PHP Manual
  • Math Functions
  • Show largest possible random value

getrandmax

(PHP 4, PHP 5, PHP 7)

getrandmax — Show largest possible random value

Description

getrandmax ( void ) : int

Returns the maximum value that can be returned by a call to rand().

Return Values

The largest possible random value returned by rand()

See Also

  • rand() - Generate a random integer
  • srand() - Seed the random number generator
  • mt_getrandmax() - Show largest possible random value


Hexadecimal to decimal

  • « getrandmax
  • hypot »
  • PHP Manual
  • Math Functions
  • Hexadecimal to decimal

hexdec

(PHP 4, PHP 5, PHP 7)

hexdec — Hexadecimal to decimal

Description

hexdec ( string $hex_string ) : number

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("See"));
var_dump(hexdec("ee"));
// both print "int(238)"

var_dump(hexdec("that")); // print "int(10)"
var_dump(hexdec("a0")); // print "int(160)"
?>

Notes

Note:

The function can convert numbers that are too large to fit into the platforms integer 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


Calculate the length of the hypotenuse of a right-angle triangle

  • « hexdec
  • intdiv »
  • PHP Manual
  • Math Functions
  • Calculate the length of the hypotenuse of a right-angle triangle

hypot

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

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


Integer division

  • « hypot
  • is_finite »
  • PHP Manual
  • Math Functions
  • Integer division

intdiv

(PHP 7)

intdiv — Integer division

Description

intdiv ( int $dividend , int $divisor ) : int

Returns the integer quotient of the division of dividend by divisor.

Parameters

dividend

Number to be divided.

divisor

Number which divides the dividend.

Return Values

The integer quotient of the division of dividend by divisor.

Errors/Exceptions

If divisor is 0, a DivisionByZeroError exception is thrown. If the dividend is PHP_INT_MIN and the divisor 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));
var_dump(intdiv(PHP_INT_MIN, -1));
var_dump(intdiv(1, 0));
?>
int(1)
int(-1)
int(-1)
int(1)
int(1)
int(1)

Fatal error: Uncaught ArithmeticError: Division of PHP_INT_MIN by -1 is not an integer in %s on line 8
Fatal error: Uncaught DivisionByZeroError: Division by zero in %s on line 9

See Also

  • / - Floating-point division
  • % - Integer modulus
  • fmod() - Floating-point modulo


Finds whether a value is a legal finite number

  • « intdiv
  • is_infinite »
  • PHP Manual
  • Math Functions
  • Finds whether a value is a legal finite number

is_finite

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

is_finite — Finds whether a value is a legal finite number

Description

is_finite ( float $val ) : bool

Checks whether val is a legal finite on this platform.

Parameters

val

The value to check

Return Values

TRUE if val is a legal finite number within the allowed range for a PHP float on this platform, else FALSE.

See Also

  • is_infinite() - Finds whether a value is infinite
  • is_nan() - Finds whether a value is not a number


Finds whether a value is infinite

  • « is_finite
  • is_nan »
  • PHP Manual
  • Math Functions
  • Finds whether a value is infinite

is_infinite

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

is_infinite — Finds whether a value is infinite

Description

is_infinite ( float $val ) : bool

Returns TRUE if val is infinite (positive or negative), like the result of log(0) or any value too big to fit into a float on this platform.

Parameters

val

The value to check

Return Values

TRUE if val is infinite, else FALSE.

See Also

  • is_finite() - Finds whether a value is a legal finite number
  • is_nan() - Finds whether a value is not a number


Finds whether a value is not a number

  • « is_infinite
  • lcg_value »
  • PHP Manual
  • Math Functions
  • Finds whether a value is not a number

is_nan

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

is_nan — Finds whether a value is not a number

Description

is_nan ( float $val ) : bool

Checks whether val is 'not a number', like the result of acos(1.01).

Parameters

val

The value to check

Return Values

Returns TRUE if val is 'not a number', else FALSE.

Examples

Example #1 is_nan() example

<?php
// Invalid calculation, will return a
// NaN value
$nan = acos(8);

var_dump($nan, is_nan($nan));
?>

The above example will output:

float(NAN)
bool(true)

See Also

  • is_finite() - Finds whether a value is a legal finite number
  • is_infinite() - Finds whether a value is infinite


Combined linear congruential generator

  • « is_nan
  • log10 »
  • PHP Manual
  • Math Functions
  • Combined linear congruential generator

lcg_value

(PHP 4, PHP 5, PHP 7)

lcg_value — Combined linear congruential generator

Description

lcg_value ( void ) : float

lcg_value() returns a pseudo random number in the range of (0, 1). The function combines two CGs with periods of 2^31 - 85 and 2^31 - 249. The period of this function is equal to the product of both primes.

Caution

This function does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using random_int(), random_bytes(), or openssl_random_pseudo_bytes() instead.

Return Values

A pseudo random float value between 0.0 and 1.0, inclusive.

See Also

  • rand() - Generate a random integer
  • mt_rand() - Generate a random value via the Mersenne Twister Random Number Generator


Base-10 logarithm

  • « lcg_value
  • log1p »
  • PHP Manual
  • Math Functions
  • Base-10 logarithm

log10

(PHP 4, PHP 5, PHP 7)

log10 — Base-10 logarithm

Description

log10 ( float $arg ) : float

Returns the base-10 logarithm of arg.

Parameters

arg

The argument to process

Return Values

The base-10 logarithm of arg

See Also

  • log() - Natural logarithm


Returns log(1 + number), computed in a way that is accurate even when the value of number is close to zero

  • « log10
  • log »
  • PHP Manual
  • Math Functions
  • Returns log(1 + number), computed in a way that is accurate even when the value of number is close to zero

log1p

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

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 $number ) : float

log1p() returns log(1 + number) computed in a way that is accurate even when the value of number is close to zero. log() might only return log(1) in this case due to lack of precision.

Parameters

number

The argument to process

Return Values

log(1 + number)

Changelog

Version | Description
5.3.0 | This function is now available on all platforms

See Also

  • expm1() - Returns exp(number) - 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


Natural logarithm

  • « log1p
  • max »
  • PHP Manual
  • Math Functions
  • Natural logarithm

log

(PHP 4, PHP 5, PHP 7)

log — Natural logarithm

Description

log ( float $arg [, float $base = M_E ] ) : float

If the optional base parameter is specified, log() returns logbase arg, otherwise log() returns the natural logarithm of arg.

Parameters

arg

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 arg to base, if given, or the natural logarithm.

See Also

  • log10() - Base-10 logarithm
  • exp() - Calculates the exponent of e
  • pow() - Exponential expression


Find highest value

  • « log
  • min »
  • PHP Manual
  • Math Functions
  • Find highest value

max

(PHP 4, PHP 5, PHP 7)

max — Find highest value

Description

max ( array $values ) : mixed
max ( mixed $value1 [, mixed $... ] ) : 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 integer 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 with mixed types values because max() can produce unpredictable results.

Parameters

values

An array containing the values.

value1

Any comparable value.

...

Any comparable value.

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.

If an empty array is passed, then FALSE will be returned and an E_WARNING error will be emitted.

Examples

Example #1 Example uses of max()

<?php
echo max(2, 3, 1, 6, 7);  // 7
echo max(array(2, 4, 5)); // 5

// The string 'hello' when compared to an int is treated as 0
// Since the two values are equal, the order they are provided determines the result
echo max(0, 'hello');     // 0
echo max('hello', 0);     // hello

// Here we are comparing -1 < 0, so 'hello' is the highest value
echo max('hello', -1);    // 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)

// 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)

// 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)

// 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

// 0, on the other hand, is treated as FALSE, so is "lower than" TRUE
$val = max(0, TRUE); // TRUE
?>

See Also

  • min() - Find lowest value
  • count() - Count all elements in an array, or something in an object


Find lowest value

  • « max
  • mt_getrandmax »
  • PHP Manual
  • Math Functions
  • Find lowest value

min

(PHP 4, PHP 5, PHP 7)

min — Find lowest value

Description

min ( array $values ) : mixed
min ( mixed $value1 [, mixed $... ] ) : 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 integer 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 with mixed types values because min() can produce unpredictable results.

Parameters

values

An array containing the values.

value1

Any comparable value.

...

Any comparable value.

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.

If an empty array is passed, then FALSE will be returned and an E_WARNING error will be emitted.

Examples

Example #1 Example uses of min()

<?php
echo min(2, 3, 1, 6, 7);  // 1
echo min(array(2, 4, 5)); // 2

// The string 'hello' when compared to an int is treated as 0
// Since the two values are equal, the order they are provided determines the result
echo min(0, 'hello');     // 0
echo min('hello', 0);     // hello

// Here we are comparing -1 < 0, so -1 is the lowest value
echo min('hello', -1);    // -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)

// 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)

// 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

// 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
$val = min(-10, NULL, 10);  // NULL

// 0, on the other hand, is treated as FALSE, so is "lower than" TRUE
$val = min(0, TRUE); // 0
?>

See Also

  • max() - Find highest value
  • count() - Count all elements in an array, or something in an object


Show largest possible random value

  • « min
  • mt_rand »
  • PHP Manual
  • Math Functions
  • Show largest possible random value

mt_getrandmax

(PHP 4, PHP 5, PHP 7)

mt_getrandmax — Show largest possible random value

Description

mt_getrandmax ( void ) : int

Returns the maximum value that can be returned by a call to mt_rand().

Return Values

Returns the maximum random value returned by a call to mt_rand() without arguments, which is the maximum value that can be used for its max parameter without the result being scaled up (and therefore less random).

Examples

Example #1 Calculate a random floating-point number

<?php
function randomFloat($min = 0, $max = 1) {
    return $min + mt_rand() / mt_getrandmax() * ($max - $min);
}

var_dump(randomFloat());
var_dump(randomFloat(2, 20));
?>

The above example will output something similar to:

float(0.91601131712832)
float(16.511210331931)

See Also

  • mt_rand() - Generate a random value via the Mersenne Twister Random Number Generator
  • mt_srand() - Seeds the Mersenne Twister Random Number Generator
  • getrandmax() - Show largest possible random value


Generate a random value via the Mersenne Twister Random Number Generator

  • « mt_getrandmax
  • mt_srand »
  • PHP Manual
  • Math Functions
  • Generate a random value via the Mersenne Twister Random Number Generator

mt_rand

(PHP 4, PHP 5, PHP 7)

mt_rand — Generate a random value via the Mersenne Twister Random Number Generator

Description

mt_rand ( void ) : int
mt_rand ( int $min , int $max ) : int
Caution

This function does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using random_int(), random_bytes(), or openssl_random_pseudo_bytes() instead.

Many random number generators of older libcs have dubious or unknown characteristics and are slow. The mt_rand() function is a drop-in replacement for the older rand(). It uses a random number generator with known characteristics using the » Mersenne Twister, which will produce random numbers four times faster than what the average libc rand() provides.

If called without the optional min, max arguments mt_rand() returns a pseudo-random value between 0 and mt_getrandmax(). If you want a random number between 5 and 15 (inclusive), for example, use mt_rand(5, 15).

Parameters

min

Optional lowest value to be returned (default: 0)

max

Optional highest value to be returned (default: mt_getrandmax())

Return Values

A random integer value between min (or 0) and max (or mt_getrandmax(), inclusive), or FALSE if max is less than min.

Changelog

Version | Description
7.2.0 | mt_rand() has received a bug fix for a modulo bias bug. This means that sequences generated with a specific seed may differ from PHP 7.1 on 64-bit machines.
7.1.0 | rand() has been made an alias of mt_rand().
7.1.0 | mt_rand() has been updated to use the fixed, correct, version of the Mersenne Twister algorithm. To fall back to the old behaviour, use mt_srand() with MT_RAND_PHP as the second parameter.
5.3.4 | Issues an E_WARNING and returns FALSE if max < min.

Examples

Example #1 mt_rand() example

<?php
echo mt_rand() . "\n";
echo mt_rand() . "\n";

echo mt_rand(5, 15);
?>

The above example will output something similar to:

1604716014
1478613278
6

Notes

Warning

min max range must be within the range mt_getrandmax(). i.e. (max - min) <= mt_getrandmax() Otherwise, mt_rand() may return poorer random numbers than it should.

See Also

  • mt_srand() - Seeds the Mersenne Twister Random Number Generator
  • mt_getrandmax() - Show largest possible random value
  • random_int() - Generates cryptographically secure pseudo-random integers
  • random_bytes() - Generates cryptographically secure pseudo-random bytes
  • openssl_random_pseudo_bytes() - Generate a pseudo-random string of bytes
  • rand() - Generate a random integer


Seeds the Mersenne Twister Random Number Generator

  • « mt_rand
  • octdec »
  • PHP Manual
  • Math Functions
  • Seeds the Mersenne Twister Random Number Generator

mt_srand

(PHP 4, PHP 5, PHP 7)

mt_srand — Seeds the Mersenne Twister Random Number Generator

Description

mt_srand ([ int $seed [, int $mode = MT_RAND_MT19937 ]] ) : void

Seeds the random number generator with seed or with a random value if no seed is given.

Note: There is no need to seed the random number generator with srand() or mt_srand() as this is done automatically.

Parameters

seed

An arbitrary integer seed value.

mode

Use one of the following constants to specify the implementation of the algorithm to use.

Constant | Description
MT_RAND_MT19937 | Uses the fixed, correct, Mersenne Twister implementation, available as of PHP 7.1.0.
MT_RAND_PHP | Uses an incorrect Mersenne Twister implementation which was used as the default up till PHP 7.1.0. This mode is available for backward compatibility.

Return Values

No value is returned.

Changelog

Version | Description
7.1.0 | srand() has been made an alias of mt_srand().
7.1.0 | mt_rand() has been updated to use the fixed, correct, version of the Mersenne Twister algorithm. To fall back to the old behaviour, use mt_srand() with MT_RAND_PHP as the second parameter.
5.2.1 | The Mersenne Twister implementation in PHP now uses a new seeding algorithm by Richard Wagner. Identical seeds no longer produce the same sequence of values they did in previous versions. This behavior is not expected to change again, but it is considered unsafe to rely upon it nonetheless.

Examples

Example #1 mt_srand() example

<?php
// seed with microseconds
function make_seed()
{
  list($usec, $sec) = explode(' ', microtime());
  return $sec + $usec * 1000000;
}
mt_srand(make_seed());
$randval = mt_rand();
?>

See Also

  • mt_rand() - Generate a random value via the Mersenne Twister Random Number Generator
  • mt_getrandmax() - Show largest possible random value
  • srand() - Seed the random number generator


Octal to decimal

  • « mt_srand
  • pi »
  • PHP Manual
  • Math Functions
  • Octal to decimal

octdec

(PHP 4, PHP 5, PHP 7)

octdec — Octal to decimal

Description

octdec ( string $octal_string ) : number

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 integer 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


Get value of pi

  • « octdec
  • pow »
  • PHP Manual
  • Math Functions
  • Get value of pi

pi

(PHP 4, PHP 5, PHP 7)

pi — Get value of pi

Description

pi ( void ) : float

Returns an approximation of pi. The returned float has a precision based on the precision directive in php.ini, which defaults to 14. Also, you can use the M_PI constant which yields identical results to pi().

Return Values

The value of pi as float.

Examples

Example #1 pi() example

<?php
echo pi(); // 3.1415926535898
echo M_PI; // 3.1415926535898
?>


Exponential expression

  • « pi
  • rad2deg »
  • PHP Manual
  • Math Functions
  • Exponential expression

pow

(PHP 4, PHP 5, PHP 7)

pow — Exponential expression

Description

pow ( number $base , number $exp ) : number

Returns base raised to the power of exp.

Note:

In PHP 5.6 onwards, you may prefer to use the ** operator.

Parameters

base

The base to use

exp

The exponent

Return Values

base raised to the power of exp. If both arguments are non-negative integers and the result can be represented as an integer, the result will be returned with integer type, otherwise it will be returned as a float.

Examples

Example #1 Some examples of pow()

<?php

var_dump(pow(2, 8)); // int(256)
echo pow(-1, 20); // 1
echo pow(0, 0); // 1
echo pow(10, -1); // 0.1

echo pow(-1, 5.5); // PHP >=5.2.2: NAN
echo pow(-1, 5.5); // PHP <5.2.2: -NAN
?>

Notes

Note:

This function will convert all input to a number, even non-scalar values, which could lead to weird results.

See Also

  • exp() - Calculates the exponent of e
  • sqrt() - Square root
  • bcpow() - Raise an arbitrary precision number to another
  • gmp_pow() - Raise number into power


Converts the radian number to the equivalent number in degrees

  • « pow
  • rand »
  • PHP Manual
  • Math Functions
  • Converts the radian number to the equivalent number in degrees

rad2deg

(PHP 4, PHP 5, PHP 7)

rad2deg — Converts the radian number to the equivalent number in degrees

Description

rad2deg ( float $number ) : float

This function converts number from radian to degrees.

Parameters

number

A radian value

Return Values

The equivalent of number 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


Generate a random integer

  • « rad2deg
  • round »
  • PHP Manual
  • Math Functions
  • Generate a random integer

rand

(PHP 4, PHP 5, PHP 7)

rand — Generate a random integer

Description

rand ( void ) : int
rand ( int $min , int $max ) : int

If called without the optional min, max arguments rand() returns a pseudo-random integer between 0 and getrandmax(). If you want a random number between 5 and 15 (inclusive), for example, use rand(5, 15).

Caution

This function does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using random_int(), random_bytes(), or openssl_random_pseudo_bytes() instead.

Note: On some platforms (such as Windows), getrandmax() is only 32767. If you require a range larger than 32767, specifying min and max will allow you to create a range larger than this, or consider using mt_rand() instead.

Note: As of PHP 7.1.0, rand() uses the same random number generator as mt_rand(). To preserve backwards compatibility rand() allows max to be smaller than min as opposed to returning FALSE as mt_rand().

Parameters

min

The lowest value to return (default: 0)

max

The highest value to return (default: getrandmax())

Return Values

A pseudo random value between min (or 0) and max (or getrandmax(), inclusive).

Changelog

Version | Description
7.2.0 | rand() has received a bug fix for a modulo bias bug. This means that sequences generated with a specific seed may differ from PHP 7.1 on 64-bit machines.
7.1.0 | rand() has been made an alias of mt_rand().

Examples

Example #1 rand() example

<?php
echo rand() . "\n";
echo rand() . "\n";

echo rand(5, 15);
?>

The above example will output something similar to:

7771
22264
11

Notes

Warning

min max range must be within the range getrandmax(). i.e. (max - min) <= getrandmax() Otherwise, rand() may return poor-quality random numbers.

See Also

  • srand() - Seed the random number generator
  • getrandmax() - Show largest possible random value
  • mt_rand() - Generate a random value via the Mersenne Twister Random Number Generator
  • random_int() - Generates cryptographically secure pseudo-random integers
  • random_bytes() - Generates cryptographically secure pseudo-random bytes
  • openssl_random_pseudo_bytes() - Generate a pseudo-random string of bytes


Rounds a float

  • « rand
  • sin »
  • PHP Manual
  • Math Functions
  • Rounds a float

round

(PHP 4, PHP 5, PHP 7)

round — Rounds a float

Description

round ( float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]] ) : float

Returns the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default).

Note: PHP doesn't handle strings like "12,300.2" correctly by default. See converting from strings.

Parameters

val

The value to round.

precision

The optional number of decimal digits to round to.

If the precision is positive, the rounding will occur after the decimal point.

If the precision is negative, the rounding will occur before the decimal point. If the absolute value of the precision is greater than or equal to the number of digits, the result of the rounding is equal to 0

mode

Use one of the following constants to specify the mode in which rounding occurs.

Constants | Description
PHP_ROUND_HALF_UP | Round val up to precision decimal places away from zero, when it is half way there. Making 1.5 into 2 and -1.5 into -2.
PHP_ROUND_HALF_DOWN | Round val down to precision decimal places towards zero, when it is half way there. Making 1.5 into 1 and -1.5 into -1.
PHP_ROUND_HALF_EVEN | Round val to precision decimal places towards the nearest even value.
PHP_ROUND_HALF_ODD | Round val to precision decimal places towards the nearest odd value.

Return Values

The value rounded to the given precision as a float.

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(1.95583, 2));
var_dump(round(1241757, -3));
var_dump(round(5.045, 2));
var_dump(round(5.055, 2));
?>

The above example will output:

float(3)
float(4)
float(4)
float(4)
float(1.96)
float(1242000)
float(5.05)
float(5.06)

Example #2 How precision affects a float

<?php
$number = 1346.21;

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));
var_dump(round($number, -4));
?>

The above example will output:

float(1346.21)
float(1346.2)
float(1346)
float(1350)
float(1300)
float(1000)
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 '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.54, 1, PHP_ROUND_HALF_UP));
var_dump(round(-1.55, 1, PHP_ROUND_HALF_UP));
var_dump(round(-1.54, 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.54, 1, PHP_ROUND_HALF_DOWN));
var_dump(round(-1.55, 1, PHP_ROUND_HALF_DOWN));
var_dump(round(-1.54, 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.54, 1, PHP_ROUND_HALF_EVEN));
var_dump(round(-1.55, 1, PHP_ROUND_HALF_EVEN));
var_dump(round(-1.54, 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.54, 1, PHP_ROUND_HALF_ODD));
var_dump(round(-1.55, 1, PHP_ROUND_HALF_ODD));
var_dump(round(-1.54, 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.5)
float(-1.6)
float(-1.5)

Using PHP_ROUND_HALF_DOWN with 1 decimal digit precision
float(1.5)
float(1.5)
float(-1.5)
float(-1.5)

Using PHP_ROUND_HALF_EVEN with 1 decimal digit precision
float(1.6)
float(1.5)
float(-1.6)
float(-1.5)

Using PHP_ROUND_HALF_ODD with 1 decimal digit precision
float(1.5)
float(1.5)
float(-1.5)
float(-1.5)

Changelog

Version | Description
5.3.0 | The mode parameter was introduced.
5.2.7 | The inner workings of round() was changed to conform to the C99 standard.

See Also

  • ceil() - Round fractions up
  • floor() - Round fractions down
  • number_format() - Format a number with grouped thousands


Sine

  • « round
  • sinh »
  • PHP Manual
  • Math Functions
  • Sine

sin

(PHP 4, PHP 5, PHP 7)

sin — Sine

Description

sin ( float $arg ) : float

sin() returns the sine of the arg parameter. The arg parameter is in radians.

Parameters

arg

A value in radians

Return Values

The sine of arg

Examples

Example #1 sin() example

<?php

// Precision depends on your precision directive
echo sin(deg2rad(60));  //  0.866025403 ...
echo sin(60);           // -0.304810621 ...

?>

See Also

  • asin() - Arc sine
  • sinh() - Hyperbolic sine
  • cos() - Cosine
  • tan() - Tangent
  • deg2rad() - Converts the number in degrees to the radian equivalent


Hyperbolic sine

  • « sin
  • sqrt »
  • PHP Manual
  • Math Functions
  • Hyperbolic sine

sinh

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

sinh — Hyperbolic sine

Description

sinh ( float $arg ) : float

Returns the hyperbolic sine of arg, defined as (exp(arg) - exp(-arg))/2.

Parameters

arg

The argument to process

Return Values

The hyperbolic sine of arg

See Also

  • sin() - Sine
  • asinh() - Inverse hyperbolic sine
  • cosh() - Hyperbolic cosine
  • tanh() - Hyperbolic tangent


Square root

  • « sinh
  • srand »
  • PHP Manual
  • Math Functions
  • Square root

sqrt

(PHP 4, PHP 5, PHP 7)

sqrt — Square root

Description

sqrt ( float $arg ) : float

Returns the square root of arg.

Parameters

arg

The argument to process

Return Values

The square root of arg or the special value NAN for negative numbers.

Examples

Example #1 sqrt() example

<?php
// Precision depends on your precision directive
echo sqrt(9); // 3
echo sqrt(10); // 3.16227766 ...
?>

See Also

  • pow() - Exponential expression


Seed the random number generator

  • « sqrt
  • tan »
  • PHP Manual
  • Math Functions
  • Seed the random number generator

srand

(PHP 4, PHP 5, PHP 7)

srand — Seed the random number generator

Description

srand ([ int $seed ] ) : void

Seeds the random number generator with seed or with a random value if no seed is given.

Note: There is no need to seed the random number generator with srand() or mt_srand() as this is done automatically.

Note: As of PHP 7.1.0, srand() has been made an alias of mt_srand().

Parameters

seed

An arbitrary integer seed value.

Return Values

No value is returned.

Changelog

Version | Description
7.1.0 | srand() has been made an alias of mt_srand().

Examples

Example #1 srand() example

<?php
// seed with microseconds
function make_seed()
{
  list($usec, $sec) = explode(' ', microtime());
  return $sec + $usec * 1000000;
}
srand(make_seed());
$randval = rand();
?>

See Also

  • rand() - Generate a random integer
  • getrandmax() - Show largest possible random value
  • mt_srand() - Seeds the Mersenne Twister Random Number Generator


Tangent

  • « srand
  • tanh »
  • PHP Manual
  • Math Functions
  • Tangent

tan

(PHP 4, PHP 5, PHP 7)

tan — Tangent

Description

tan ( float $arg ) : float

tan() returns the tangent of the arg parameter. The arg parameter is in radians.

Parameters

arg

The argument to process in radians

Return Values

The tangent of arg

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


Hyperbolic tangent

  • « tan
  • Statistics »
  • PHP Manual
  • Math Functions
  • Hyperbolic tangent

tanh

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

tanh — Hyperbolic tangent

Description

tanh ( float $arg ) : float

Returns the hyperbolic tangent of arg, defined as sinh(arg)/cosh(arg).

Parameters

arg

The argument to process

Return Values

The hyperbolic tangent of arg

See Also

  • tan() - Tangent
  • atanh() - Inverse hyperbolic tangent
  • sinh() - Hyperbolic sine
  • cosh() - Hyperbolic cosine


Statistics

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • 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_negative — Generates a random deviate from the negative binomial distribution
    • stats_rand_gen_ibinomial — Generates a random deviate from the 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


Introduction

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
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

No external libraries are needed. The extension comes bundled with the libraries used.


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/stats.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.


  • « Resource Types
  • Statistic Functions »
  • PHP Manual
  • Statistics
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


Statistic Functions

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_negative — Generates a random deviate from the negative binomial distribution
  • stats_rand_gen_ibinomial — Generates a random deviate from the 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


Returns the absolute deviation of an array of values

  • « Statistic Functions
  • stats_cdf_beta »
  • PHP Manual
  • Statistic Functions
  • Returns the absolute deviation of an array of values

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.


Calculates any one parameter of the beta distribution given values for the others

  • « stats_absolute_deviation
  • stats_cdf_binomial »
  • PHP Manual
  • Statistic Functions
  • Calculates any one parameter of the beta distribution given values for the others

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.


Calculates any one parameter of the binomial distribution given values for the others

  • « stats_cdf_beta
  • stats_cdf_cauchy »
  • PHP Manual
  • Statistic Functions
  • Calculates any one parameter of the binomial distribution given values for the others

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.


Calculates any one parameter of the Cauchy distribution given values for the others

  • « stats_cdf_binomial
  • stats_cdf_chisquare »
  • PHP Manual
  • Statistic Functions
  • Calculates any one parameter of the Cauchy distribution given values for the others

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.


Calculates any one parameter of the chi-square distribution given values for the others

  • « stats_cdf_cauchy
  • stats_cdf_exponential »
  • PHP Manual
  • Statistic Functions
  • Calculates any one parameter of the chi-square distribution given values for the others

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.


Calculates any one parameter of the exponential distribution given values for the others

  • « stats_cdf_chisquare
  • stats_cdf_f »
  • PHP Manual
  • Statistic Functions
  • Calculates any one parameter of the exponential distribution given values for the others

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.


Calculates any one parameter of the F distribution given values for the others

  • « stats_cdf_exponential
  • stats_cdf_gamma »
  • PHP Manual
  • Statistic Functions
  • Calculates any one parameter of the F distribution given values for the others

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.


Calculates any one parameter of the gamma distribution given values for the others

  • « stats_cdf_f
  • stats_cdf_laplace »
  • PHP Manual
  • Statistic Functions
  • Calculates any one parameter of the gamma distribution given values for the others

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.


Calculates any one parameter of the Laplace distribution given values for the others

  • « stats_cdf_gamma
  • stats_cdf_logistic »
  • PHP Manual
  • Statistic Functions
  • Calculates any one parameter of the Laplace distribution given values for the others

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.


Calculates any one parameter of the logistic distribution given values for the others

  • « stats_cdf_laplace
  • stats_cdf_negative_binomial »
  • PHP Manual
  • Statistic Functions
  • Calculates any one parameter of the logistic distribution given values for the others

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.


Calculates any one parameter of the negative binomial distribution given values for the others

  • « stats_cdf_logistic
  • stats_cdf_noncentral_chisquare »
  • PHP Manual
  • Statistic Functions
  • Calculates any one parameter of the negative binomial distribution given values for the others

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.


Calculates any one parameter of the non-central chi-square distribution given values for the others

  • « stats_cdf_negative_binomial
  • stats_cdf_noncentral_f »
  • PHP Manual
  • Statistic Functions
  • Calculates any one parameter of the non-central chi-square distribution given values for the others

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.


Calculates any one parameter of the non-central F distribution given values for the others

  • « stats_cdf_noncentral_chisquare
  • stats_cdf_noncentral_t »
  • PHP Manual
  • Statistic Functions
  • Calculates any one parameter of the non-central F distribution given values for the others

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.


Calculates any one parameter of the non-central t-distribution give values for the others

  • « stats_cdf_noncentral_f
  • stats_cdf_normal »
  • PHP Manual
  • Statistic Functions
  • Calculates any one parameter of the non-central t-distribution give values for the others

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.


Calculates any one parameter of the normal distribution given values for the others

  • « stats_cdf_noncentral_t
  • stats_cdf_poisson »
  • PHP Manual
  • Statistic Functions
  • Calculates any one parameter of the normal distribution given values for the others

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.


Calculates any one parameter of the Poisson distribution given values for the others

  • « stats_cdf_normal
  • stats_cdf_t »
  • PHP Manual
  • Statistic Functions
  • Calculates any one parameter of the Poisson distribution given values for the others

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.


Calculates any one parameter of the t-distribution given values for the others

  • « stats_cdf_poisson
  • stats_cdf_uniform »
  • PHP Manual
  • Statistic Functions
  • Calculates any one parameter of the t-distribution given values for the others

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.


Calculates any one parameter of the uniform distribution given values for the others

  • « stats_cdf_t
  • stats_cdf_weibull »
  • PHP Manual
  • Statistic Functions
  • Calculates any one parameter of the uniform distribution given values for the others

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.


Calculates any one parameter of the Weibull distribution given values for the others

  • « stats_cdf_uniform
  • stats_covariance »
  • PHP Manual
  • Statistic Functions
  • Calculates any one parameter of the Weibull distribution given values for the others

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.


Computes the covariance of two data sets

  • « stats_cdf_weibull
  • stats_dens_beta »
  • PHP Manual
  • Statistic Functions
  • Computes the covariance of two data sets

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.


Probability density function of the beta distribution

  • « stats_covariance
  • stats_dens_cauchy »
  • PHP Manual
  • Statistic Functions
  • Probability density function of the beta distribution

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.


Probability density function of the Cauchy distribution

  • « stats_dens_beta
  • stats_dens_chisquare »
  • PHP Manual
  • Statistic Functions
  • Probability density function of the Cauchy distribution

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.


Probability density function of the chi-square distribution

  • « stats_dens_cauchy
  • stats_dens_exponential »
  • PHP Manual
  • Statistic Functions
  • Probability density function of the chi-square distribution

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.


Probability density function of the exponential distribution

  • « stats_dens_chisquare
  • stats_dens_f »
  • PHP Manual
  • Statistic Functions
  • Probability density function of the exponential distribution

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.


Probability density function of the F distribution

  • « stats_dens_exponential
  • stats_dens_gamma »
  • PHP Manual
  • Statistic Functions
  • Probability density function of the F distribution

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.


Probability density function of the gamma distribution

  • « stats_dens_f
  • stats_dens_laplace »
  • PHP Manual
  • Statistic Functions
  • Probability density function of the gamma distribution

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.


Probability density function of the Laplace distribution

  • « stats_dens_gamma
  • stats_dens_logistic »
  • PHP Manual
  • Statistic Functions
  • Probability density function of the Laplace distribution

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.


Probability density function of the logistic distribution

  • « stats_dens_laplace
  • stats_dens_normal »
  • PHP Manual
  • Statistic Functions
  • Probability density function of the logistic distribution

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.


Probability density function of the normal distribution

  • « stats_dens_logistic
  • stats_dens_pmf_binomial »
  • PHP Manual
  • Statistic Functions
  • Probability density function of the normal distribution

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.


Probability mass function of the binomial distribution

  • « stats_dens_normal
  • stats_dens_pmf_hypergeometric »
  • PHP Manual
  • Statistic Functions
  • Probability mass function of the binomial distribution

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.


Probability mass function of the hypergeometric distribution

  • « stats_dens_pmf_binomial
  • stats_dens_pmf_negative_binomial »
  • PHP Manual
  • Statistic Functions
  • Probability mass function of the hypergeometric distribution

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.


Probability mass function of the negative binomial distribution

  • « stats_dens_pmf_hypergeometric
  • stats_dens_pmf_poisson »
  • PHP Manual
  • Statistic Functions
  • Probability mass function of the negative binomial distribution

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.


Probability mass function of the Poisson distribution

  • « stats_dens_pmf_negative_binomial
  • stats_dens_t »
  • PHP Manual
  • Statistic Functions
  • Probability mass function of the Poisson distribution

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.


Probability density function of the t-distribution

  • « stats_dens_pmf_poisson
  • stats_dens_uniform »
  • PHP Manual
  • Statistic Functions
  • Probability density function of the t-distribution

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.


Probability density function of the uniform distribution

  • « stats_dens_t
  • stats_dens_weibull »
  • PHP Manual
  • Statistic Functions
  • Probability density function of the uniform distribution

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.


Probability density function of the Weibull distribution

  • « stats_dens_uniform
  • stats_harmonic_mean »
  • PHP Manual
  • Statistic Functions
  • Probability density function of the Weibull distribution

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.


Returns the harmonic mean of an array of values

  • « stats_dens_weibull
  • stats_kurtosis »
  • PHP Manual
  • Statistic Functions
  • Returns the harmonic mean of an array of values

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.


Computes the kurtosis of the data in the array

  • « stats_harmonic_mean
  • stats_rand_gen_beta »
  • PHP Manual
  • Statistic Functions
  • Computes the kurtosis of the data in the 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.


Generates a random deviate from the beta distribution

  • « stats_kurtosis
  • stats_rand_gen_chisquare »
  • PHP Manual
  • Statistic Functions
  • Generates a random deviate from the beta distribution

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


Generates a random deviate from the chi-square distribution

  • « stats_rand_gen_beta
  • stats_rand_gen_exponential »
  • PHP Manual
  • Statistic Functions
  • Generates a random deviate from the chi-square distribution

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


Generates a random deviate from the exponential distribution

  • « stats_rand_gen_chisquare
  • stats_rand_gen_f »
  • PHP Manual
  • Statistic Functions
  • Generates a random deviate from the exponential distribution

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


Generates a random deviate from the F distribution

  • « stats_rand_gen_exponential
  • stats_rand_gen_funiform »
  • PHP Manual
  • Statistic Functions
  • Generates a random deviate from the F distribution

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


Generates uniform float between low (exclusive) and high (exclusive)

  • « stats_rand_gen_f
  • stats_rand_gen_gamma »
  • PHP Manual
  • Statistic Functions
  • Generates uniform float between low (exclusive) and high (exclusive)

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 (inclusive)

high

The upper bound (exclusive)

Return Values

A random deviate


Generates a random deviate from the gamma distribution

  • « stats_rand_gen_funiform
  • stats_rand_gen_ibinomial_negative »
  • PHP Manual
  • Statistic Functions
  • Generates a random deviate from the gamma distribution

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


Generates a random deviate from the negative binomial distribution

  • « stats_rand_gen_gamma
  • stats_rand_gen_ibinomial »
  • PHP Manual
  • Statistic Functions
  • Generates a random deviate from the negative binomial distribution

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.


Generates a random deviate from the binomial distribution

  • « stats_rand_gen_ibinomial_negative
  • stats_rand_gen_int »
  • PHP Manual
  • Statistic Functions
  • Generates a random deviate from the binomial distribution

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


Generates random integer between 1 and 2147483562

  • « stats_rand_gen_ibinomial
  • stats_rand_gen_ipoisson »
  • PHP Manual
  • Statistic Functions
  • Generates random integer between 1 and 2147483562

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 ( void ) : int

Returns a random integer between 1 and 2147483562

Return Values

A random integer


Generates a single random deviate from a Poisson distribution

  • « stats_rand_gen_int
  • stats_rand_gen_iuniform »
  • PHP Manual
  • Statistic Functions
  • Generates a single random deviate from a Poisson distribution

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


Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive)

  • « stats_rand_gen_ipoisson
  • stats_rand_gen_noncentral_chisquare »
  • PHP Manual
  • Statistic Functions
  • Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive)

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


Generates a random deviate from the non-central chi-square distribution

  • « stats_rand_gen_iuniform
  • stats_rand_gen_noncentral_f »
  • PHP Manual
  • Statistic Functions
  • Generates a random deviate from the non-central chi-square distribution

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


Generates a random deviate from the noncentral F distribution

  • « stats_rand_gen_noncentral_chisquare
  • stats_rand_gen_noncentral_t »
  • PHP Manual
  • Statistic Functions
  • Generates a random deviate from the noncentral F distribution

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


Generates a single random deviate from a non-central t-distribution

  • « stats_rand_gen_noncentral_f
  • stats_rand_gen_normal »
  • PHP Manual
  • Statistic Functions
  • Generates a single random deviate from a non-central t-distribution

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


Generates a single random deviate from a normal distribution

  • « stats_rand_gen_noncentral_t
  • stats_rand_gen_t »
  • PHP Manual
  • Statistic Functions
  • Generates a single random deviate from a normal distribution

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


Generates a single random deviate from a t-distribution

  • « stats_rand_gen_normal
  • stats_rand_get_seeds »
  • PHP Manual
  • Statistic Functions
  • Generates a single random deviate from a t-distribution

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


Get the seed values of the random number generator

  • « stats_rand_gen_t
  • stats_rand_phrase_to_seeds »
  • PHP Manual
  • Statistic Functions
  • Get the seed values of the random number generator

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 ( void ) : array

Returns the current seed values of the random number generator

Return Values

Returns an array of two integers.


Generate two seeds for the RGN random number generator

  • « stats_rand_get_seeds
  • stats_rand_ranf »
  • PHP Manual
  • Statistic Functions
  • Generate two seeds for the RGN random number generator

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.


Generates a random floating point number between 0 and 1

  • « stats_rand_phrase_to_seeds
  • stats_rand_setall »
  • PHP Manual
  • Statistic Functions
  • Generates a random floating point number between 0 and 1

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 ( void ) : float

Returns a random floating point number from a uniform distribution between 0 (exclusive) and 1 (exclusive).

Return Values

A random floating point number


Set seed values to the random generator

  • « stats_rand_ranf
  • stats_skew »
  • PHP Manual
  • Statistic Functions
  • Set seed values to the random generator

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.


Computes the skewness of the data in the array

  • « stats_rand_setall
  • stats_standard_deviation »
  • PHP Manual
  • Statistic Functions
  • Computes the skewness of the data in the array

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.


Returns the standard deviation

  • « stats_skew
  • stats_stat_binomial_coef »
  • PHP Manual
  • Statistic Functions
  • Returns the standard deviation

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.


Returns a binomial coefficient

  • « stats_standard_deviation
  • stats_stat_correlation »
  • PHP Manual
  • Statistic Functions
  • Returns a binomial coefficient

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


Returns the Pearson correlation coefficient of two data sets

  • « stats_stat_binomial_coef
  • stats_stat_factorial »
  • PHP Manual
  • Statistic Functions
  • Returns the Pearson correlation coefficient of two data sets

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.


Returns the factorial of an integer

  • « stats_stat_correlation
  • stats_stat_independent_t »
  • PHP Manual
  • Statistic Functions
  • Returns the factorial of an integer

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.


Returns the t-value from the independent two-sample t-test

  • « stats_stat_factorial
  • stats_stat_innerproduct »
  • PHP Manual
  • Statistic Functions
  • Returns the t-value from the independent two-sample t-test

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.


Returns the inner product of two vectors

  • « stats_stat_independent_t
  • stats_stat_paired_t »
  • PHP Manual
  • Statistic Functions
  • Returns the inner product of two vectors

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.


Returns the t-value of the dependent t-test for paired samples

  • « stats_stat_innerproduct
  • stats_stat_percentile »
  • PHP Manual
  • Statistic Functions
  • Returns the t-value of the dependent t-test for paired samples

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.


Returns the percentile value

  • « stats_stat_paired_t
  • stats_stat_powersum »
  • PHP Manual
  • Statistic Functions
  • Returns the percentile value

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.


Returns the power sum of a vector

  • « stats_stat_percentile
  • stats_variance »
  • PHP Manual
  • Statistic Functions
  • Returns the power sum of a vector

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.


Returns the variance

  • « stats_stat_powersum
  • Trader »
  • PHP Manual
  • Statistic Functions
  • Returns the variance

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.


Technical Analysis for Traders

  • Introduction
  • 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_angle — Linear Regression Angle
    • trader_linearreg_intercept — Linear Regression Intercept
    • trader_linearreg_slope — Linear Regression Slope
    • trader_linearreg — Linear Regression
    • 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_rocr100 — Rate of change ratio 100 scale: (price/prevPrice)*100
    • trader_rocr — Rate of change ratio: (price/prevPrice)
    • 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


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 » tadoc.org.


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.

A DLL for this PECL extension is available under » http://windows.php.net/downloads/pecl/releases/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 | PHP_INI_ALL | Since trader 0.2.1
trader.real_round_mode | HALF_DOWN | PHP_INI_ALL | Since trader 0.3.0

Here's a short explanation of the configuration directives.

trader.real_precision integer

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 (integer)
TRADER_MA_TYPE_EMA (integer)
TRADER_MA_TYPE_WMA (integer)
TRADER_MA_TYPE_DEMA (integer)
TRADER_MA_TYPE_TEMA (integer)
TRADER_MA_TYPE_TRIMA (integer)
TRADER_MA_TYPE_KAMA (integer)
TRADER_MA_TYPE_MAMA (integer)
TRADER_MA_TYPE_T3 (integer)
TRADER_REAL_MIN (float)
TRADER_REAL_MAX (float)
TRADER_FUNC_UNST_ADX (integer)
TRADER_FUNC_UNST_ADXR (integer)
TRADER_FUNC_UNST_ATR (integer)
TRADER_FUNC_UNST_CMO (integer)
TRADER_FUNC_UNST_DX (integer)
TRADER_FUNC_UNST_EMA (integer)
TRADER_FUNC_UNST_HT_DCPERIOD (integer)
TRADER_FUNC_UNST_HT_DCPHASE (integer)
TRADER_FUNC_UNST_HT_PHASOR (integer)
TRADER_FUNC_UNST_HT_SINE (integer)
TRADER_FUNC_UNST_HT_TRENDLINE (integer)
TRADER_FUNC_UNST_HT_TRENDMODE (integer)
TRADER_FUNC_UNST_KAMA (integer)
TRADER_FUNC_UNST_MAMA (integer)
TRADER_FUNC_UNST_MFI (integer)
TRADER_FUNC_UNST_MINUS_DI (integer)
TRADER_FUNC_UNST_MINUS_DM (integer)
TRADER_FUNC_UNST_NATR (integer)
TRADER_FUNC_UNST_PLUS_DI (integer)
TRADER_FUNC_UNST_PLUS_DM (integer)
TRADER_FUNC_UNST_RSI (integer)
TRADER_FUNC_UNST_STOCHRSI (integer)
TRADER_FUNC_UNST_T3 (integer)
TRADER_FUNC_UNST_ALL (integer)
TRADER_FUNC_UNST_NONE (integer)
TRADER_COMPATIBILITY_DEFAULT (integer)
TRADER_COMPATIBILITY_METASTOCK (integer)
TRADER_ERR_SUCCESS (integer)
TRADER_ERR_LIB_NOT_INITIALIZE (integer)
TRADER_ERR_BAD_PARAM (integer)
TRADER_ERR_ALLOC_ERR (integer)
TRADER_ERR_GROUP_NOT_FOUND (integer)
TRADER_ERR_FUNC_NOT_FOUND (integer)
TRADER_ERR_INVALID_HANDLE (integer)
TRADER_ERR_INVALID_PARAM_HOLDER (integer)
TRADER_ERR_INVALID_PARAM_HOLDER_TYPE (integer)
TRADER_ERR_INVALID_PARAM_FUNCTION (integer)
TRADER_ERR_INPUT_NOT_ALL_INITIALIZE (integer)
TRADER_ERR_OUTPUT_NOT_ALL_INITIALIZE (integer)
TRADER_ERR_OUT_OF_RANGE_START_INDEX (integer)
TRADER_ERR_OUT_OF_RANGE_END_INDEX (integer)
TRADER_ERR_INVALID_LIST_TYPE (integer)
TRADER_ERR_BAD_OBJECT (integer)
TRADER_ERR_NOT_SUPPORTED (integer)
TRADER_ERR_INTERNAL_ERROR (integer)
TRADER_ERR_UNKNOWN_ERROR (integer)


Trader Functions

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_angle — Linear Regression Angle
  • trader_linearreg_intercept — Linear Regression Intercept
  • trader_linearreg_slope — Linear Regression Slope
  • trader_linearreg — Linear Regression
  • 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_rocr100 — Rate of change ratio 100 scale: (price/prevPrice)*100
  • trader_rocr — Rate of change ratio: (price/prevPrice)
  • 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


Vector Trigonometric ACos

  • « Trader Functions
  • trader_ad »
  • PHP Manual
  • Trader Functions
  • Vector Trigonometric ACos

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.


Chaikin A/D Line

  • « trader_acos
  • trader_add »
  • PHP Manual
  • Trader Functions
  • Chaikin A/D Line

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.


Vector Arithmetic Add

  • « trader_ad
  • trader_adosc »
  • PHP Manual
  • Trader Functions
  • Vector Arithmetic Add

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.


Chaikin A/D Oscillator

  • « trader_add
  • trader_adx »
  • PHP Manual
  • Trader Functions
  • Chaikin A/D Oscillator

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.


Average Directional Movement Index

  • « trader_adosc
  • trader_adxr »
  • PHP Manual
  • Trader Functions
  • Average Directional Movement Index

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.


Average Directional Movement Index Rating

  • « trader_adx
  • trader_apo »
  • PHP Manual
  • Trader Functions
  • Average Directional Movement Index Rating

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.


Absolute Price Oscillator

  • « trader_adxr
  • trader_aroon »
  • PHP Manual
  • Trader Functions
  • Absolute Price Oscillator

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.


Aroon

  • « trader_apo
  • trader_aroonosc »
  • PHP Manual
  • Trader Functions
  • Aroon

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.


Aroon Oscillator

  • « trader_aroon
  • trader_asin »
  • PHP Manual
  • Trader Functions
  • Aroon Oscillator

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.


Vector Trigonometric ASin

  • « trader_aroonosc
  • trader_atan »
  • PHP Manual
  • Trader Functions
  • Vector Trigonometric ASin

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.


Vector Trigonometric ATan

  • « trader_asin
  • trader_atr »
  • PHP Manual
  • Trader Functions
  • Vector Trigonometric ATan

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.


Average True Range

  • « trader_atan
  • trader_avgprice »
  • PHP Manual
  • Trader Functions
  • Average True Range

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.


Average Price

  • « trader_atr
  • trader_bbands »
  • PHP Manual
  • Trader Functions
  • Average Price

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.


Bollinger Bands

  • « trader_avgprice
  • trader_beta »
  • PHP Manual
  • Trader Functions
  • Bollinger Bands

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.


Beta

  • « trader_bbands
  • trader_bop »
  • PHP Manual
  • Trader Functions
  • Beta

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.


Balance Of Power

  • « trader_beta
  • trader_cci »
  • PHP Manual
  • Trader Functions
  • Balance Of Power

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.


Commodity Channel Index

  • « trader_bop
  • trader_cdl2crows »
  • PHP Manual
  • Trader Functions
  • Commodity Channel Index

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.


Two Crows

  • « trader_cci
  • trader_cdl3blackcrows »
  • PHP Manual
  • Trader Functions
  • Two Crows

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.


Three Black Crows

  • « trader_cdl2crows
  • trader_cdl3inside »
  • PHP Manual
  • Trader Functions
  • Three Black Crows

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.


Three Inside Up/Down

  • « trader_cdl3blackcrows
  • trader_cdl3linestrike »
  • PHP Manual
  • Trader Functions
  • Three Inside Up/Down

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.


Three-Line Strike

  • « trader_cdl3inside
  • trader_cdl3outside »
  • PHP Manual
  • Trader Functions
  • Three-Line Strike

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.


Three Outside Up/Down

  • « trader_cdl3linestrike
  • trader_cdl3starsinsouth »
  • PHP Manual
  • Trader Functions
  • Three Outside Up/Down

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.


Three Stars In The South

  • « trader_cdl3outside
  • trader_cdl3whitesoldiers »
  • PHP Manual
  • Trader Functions
  • Three Stars In The South

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.


Three Advancing White Soldiers

  • « trader_cdl3starsinsouth
  • trader_cdlabandonedbaby »
  • PHP Manual
  • Trader Functions
  • Three Advancing White Soldiers

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.


Abandoned Baby

  • « trader_cdl3whitesoldiers
  • trader_cdladvanceblock »
  • PHP Manual
  • Trader Functions
  • Abandoned Baby

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.


Advance Block

  • « trader_cdlabandonedbaby
  • trader_cdlbelthold »
  • PHP Manual
  • Trader Functions
  • Advance Block

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.


Belt-hold

  • « trader_cdladvanceblock
  • trader_cdlbreakaway »
  • PHP Manual
  • Trader Functions
  • Belt-hold

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.


Breakaway

  • « trader_cdlbelthold
  • trader_cdlclosingmarubozu »
  • PHP Manual
  • Trader Functions
  • Breakaway

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.


Closing Marubozu

  • « trader_cdlbreakaway
  • trader_cdlconcealbabyswall »
  • PHP Manual
  • Trader Functions
  • Closing Marubozu

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.


Concealing Baby Swallow

  • « trader_cdlclosingmarubozu
  • trader_cdlcounterattack »
  • PHP Manual
  • Trader Functions
  • Concealing Baby Swallow

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.


Counterattack

  • « trader_cdlconcealbabyswall
  • trader_cdldarkcloudcover »
  • PHP Manual
  • Trader Functions
  • Counterattack

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.


Dark Cloud Cover

  • « trader_cdlcounterattack
  • trader_cdldoji »
  • PHP Manual
  • Trader Functions
  • Dark Cloud Cover

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.


Doji

  • « trader_cdldarkcloudcover
  • trader_cdldojistar »
  • PHP Manual
  • Trader Functions
  • Doji

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.


Doji Star

  • « trader_cdldoji
  • trader_cdldragonflydoji »
  • PHP Manual
  • Trader Functions
  • Doji Star

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.


Dragonfly Doji

  • « trader_cdldojistar
  • trader_cdlengulfing »
  • PHP Manual
  • Trader Functions
  • Dragonfly Doji

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.


Engulfing Pattern

  • « trader_cdldragonflydoji
  • trader_cdleveningdojistar »
  • PHP Manual
  • Trader Functions
  • Engulfing Pattern

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.


Evening Doji Star

  • « trader_cdlengulfing
  • trader_cdleveningstar »
  • PHP Manual
  • Trader Functions
  • Evening Doji Star

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.


Evening Star

  • « trader_cdleveningdojistar
  • trader_cdlgapsidesidewhite »
  • PHP Manual
  • Trader Functions
  • Evening Star

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.


Up/Down-gap side-by-side white lines

  • « trader_cdleveningstar
  • trader_cdlgravestonedoji »
  • PHP Manual
  • Trader Functions
  • Up/Down-gap side-by-side white lines

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.


Gravestone Doji

  • « trader_cdlgapsidesidewhite
  • trader_cdlhammer »
  • PHP Manual
  • Trader Functions
  • Gravestone Doji

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.


Hammer

  • « trader_cdlgravestonedoji
  • trader_cdlhangingman »
  • PHP Manual
  • Trader Functions
  • Hammer

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.


Hanging Man

  • « trader_cdlhammer
  • trader_cdlharami »
  • PHP Manual
  • Trader Functions
  • Hanging Man

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.


Harami Pattern

  • « trader_cdlhangingman
  • trader_cdlharamicross »
  • PHP Manual
  • Trader Functions
  • Harami Pattern

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.


Harami Cross Pattern

  • « trader_cdlharami
  • trader_cdlhighwave »
  • PHP Manual
  • Trader Functions
  • Harami Cross Pattern

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.


High-Wave Candle

  • « trader_cdlharamicross
  • trader_cdlhikkake »
  • PHP Manual
  • Trader Functions
  • High-Wave Candle

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.


Hikkake Pattern

  • « trader_cdlhighwave
  • trader_cdlhikkakemod »
  • PHP Manual
  • Trader Functions
  • Hikkake Pattern

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.


Modified Hikkake Pattern

  • « trader_cdlhikkake
  • trader_cdlhomingpigeon »
  • PHP Manual
  • Trader Functions
  • Modified Hikkake Pattern

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.


Homing Pigeon

  • « trader_cdlhikkakemod
  • trader_cdlidentical3crows »
  • PHP Manual
  • Trader Functions
  • Homing Pigeon

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.


Identical Three Crows

  • « trader_cdlhomingpigeon
  • trader_cdlinneck »
  • PHP Manual
  • Trader Functions
  • Identical Three Crows

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.


In-Neck Pattern

  • « trader_cdlidentical3crows
  • trader_cdlinvertedhammer »
  • PHP Manual
  • Trader Functions
  • In-Neck Pattern

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.


Inverted Hammer

  • « trader_cdlinneck
  • trader_cdlkicking »
  • PHP Manual
  • Trader Functions
  • Inverted Hammer

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.


Kicking

  • « trader_cdlinvertedhammer
  • trader_cdlkickingbylength »
  • PHP Manual
  • Trader Functions
  • Kicking

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.


Kicking - bull/bear determined by the longer marubozu

  • « trader_cdlkicking
  • trader_cdlladderbottom »
  • PHP Manual
  • Trader Functions
  • Kicking - bull/bear determined by the longer marubozu

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.


Ladder Bottom

  • « trader_cdlkickingbylength
  • trader_cdllongleggeddoji »
  • PHP Manual
  • Trader Functions
  • Ladder Bottom

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.


Long Legged Doji

  • « trader_cdlladderbottom
  • trader_cdllongline »
  • PHP Manual
  • Trader Functions
  • Long Legged Doji

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.


Long Line Candle

  • « trader_cdllongleggeddoji
  • trader_cdlmarubozu »
  • PHP Manual
  • Trader Functions
  • Long Line Candle

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.


Marubozu

  • « trader_cdllongline
  • trader_cdlmatchinglow »
  • PHP Manual
  • Trader Functions
  • Marubozu

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.


Matching Low

  • « trader_cdlmarubozu
  • trader_cdlmathold »
  • PHP Manual
  • Trader Functions
  • Matching Low

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.


Mat Hold

  • « trader_cdlmatchinglow
  • trader_cdlmorningdojistar »
  • PHP Manual
  • Trader Functions
  • Mat Hold

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.


Morning Doji Star

  • « trader_cdlmathold
  • trader_cdlmorningstar »
  • PHP Manual
  • Trader Functions
  • Morning Doji Star

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.


Morning Star

  • « trader_cdlmorningdojistar
  • trader_cdlonneck »
  • PHP Manual
  • Trader Functions
  • Morning Star

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.


On-Neck Pattern

  • « trader_cdlmorningstar
  • trader_cdlpiercing »
  • PHP Manual
  • Trader Functions
  • On-Neck Pattern

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.


Piercing Pattern

  • « trader_cdlonneck
  • trader_cdlrickshawman »
  • PHP Manual
  • Trader Functions
  • Piercing Pattern

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.


Rickshaw Man

  • « trader_cdlpiercing
  • trader_cdlrisefall3methods »
  • PHP Manual
  • Trader Functions
  • Rickshaw Man

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.


Rising/Falling Three Methods

  • « trader_cdlrickshawman
  • trader_cdlseparatinglines »
  • PHP Manual
  • Trader Functions
  • Rising/Falling Three Methods

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.


Separating Lines

  • « trader_cdlrisefall3methods
  • trader_cdlshootingstar »
  • PHP Manual
  • Trader Functions
  • Separating Lines

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.


Shooting Star

  • « trader_cdlseparatinglines
  • trader_cdlshortline »
  • PHP Manual
  • Trader Functions
  • Shooting Star

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.


Short Line Candle

  • « trader_cdlshootingstar
  • trader_cdlspinningtop »
  • PHP Manual
  • Trader Functions
  • Short Line Candle

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.


Spinning Top

  • « trader_cdlshortline
  • trader_cdlstalledpattern »
  • PHP Manual
  • Trader Functions
  • Spinning Top

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.


Stalled Pattern

  • « trader_cdlspinningtop
  • trader_cdlsticksandwich »
  • PHP Manual
  • Trader Functions
  • Stalled Pattern

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.


Stick Sandwich

  • « trader_cdlstalledpattern
  • trader_cdltakuri »
  • PHP Manual
  • Trader Functions
  • Stick Sandwich

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.


Takuri (Dragonfly Doji with very long lower shadow)

  • « trader_cdlsticksandwich
  • trader_cdltasukigap »
  • PHP Manual
  • Trader Functions
  • Takuri (Dragonfly Doji with very long lower shadow)

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.


Tasuki Gap

  • « trader_cdltakuri
  • trader_cdlthrusting »
  • PHP Manual
  • Trader Functions
  • Tasuki Gap

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.


Thrusting Pattern

  • « trader_cdltasukigap
  • trader_cdltristar »
  • PHP Manual
  • Trader Functions
  • Thrusting Pattern

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.


Tristar Pattern

  • « trader_cdlthrusting
  • trader_cdlunique3river »
  • PHP Manual
  • Trader Functions
  • Tristar Pattern

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.


Unique 3 River

  • « trader_cdltristar
  • trader_cdlupsidegap2crows »
  • PHP Manual
  • Trader Functions
  • Unique 3 River

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.


Upside Gap Two Crows

  • « trader_cdlunique3river
  • trader_cdlxsidegap3methods »
  • PHP Manual
  • Trader Functions
  • Upside Gap Two Crows

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.


Upside/Downside Gap Three Methods

  • « trader_cdlupsidegap2crows
  • trader_ceil »
  • PHP Manual
  • Trader Functions
  • Upside/Downside Gap Three Methods

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.


Vector Ceil

  • « trader_cdlxsidegap3methods
  • trader_cmo »
  • PHP Manual
  • Trader Functions
  • Vector Ceil

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.


Chande Momentum Oscillator

  • « trader_ceil
  • trader_correl »
  • PHP Manual
  • Trader Functions
  • Chande Momentum Oscillator

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.


Pearson's Correlation Coefficient (r)

  • « trader_cmo
  • trader_cos »
  • PHP Manual
  • Trader Functions
  • Pearson's Correlation Coefficient (r)

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.


Vector Trigonometric Cos

  • « trader_correl
  • trader_cosh »
  • PHP Manual
  • Trader Functions
  • Vector Trigonometric Cos

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.


Vector Trigonometric Cosh

  • « trader_cos
  • trader_dema »
  • PHP Manual
  • Trader Functions
  • Vector Trigonometric Cosh

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.


Double Exponential Moving Average

  • « trader_cosh
  • trader_div »
  • PHP Manual
  • Trader Functions
  • Double Exponential Moving Average

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.


Vector Arithmetic Div

  • « trader_dema
  • trader_dx »
  • PHP Manual
  • Trader Functions
  • Vector Arithmetic Div

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.


Directional Movement Index

  • « trader_div
  • trader_ema »
  • PHP Manual
  • Trader Functions
  • Directional Movement Index

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.


Exponential Moving Average

  • « trader_dx
  • trader_errno »
  • PHP Manual
  • Trader Functions
  • Exponential Moving Average

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.


Get error code

  • « trader_ema
  • trader_exp »
  • PHP Manual
  • Trader Functions
  • Get error code

trader_errno

(PECL trader >= 0.3.0)

trader_errno — Get error code

Description

trader_errno ( void ) : int

Get error code of the last operation.

Return Values

Returns the error code identified by one of the TRADER_ERR_* constants.


Vector Arithmetic Exp

  • « trader_errno
  • trader_floor »
  • PHP Manual
  • Trader Functions
  • Vector Arithmetic Exp

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.


Vector Floor

  • « trader_exp
  • trader_get_compat »
  • PHP Manual
  • Trader Functions
  • Vector Floor

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.


Get compatibility mode

  • « trader_floor
  • trader_get_unstable_period »
  • PHP Manual
  • Trader Functions
  • Get compatibility mode

trader_get_compat

(PECL trader >= 0.2.2)

trader_get_compat — Get compatibility mode

Description

trader_get_compat ( void ) : int

Get compatibility mode which affects the way calculations are done by all the extension functions.

Return Values

Returns the compatibility mode id which can be identified by TRADER_COMPATIBILITY_* series of constants.


Get unstable period

  • « trader_get_compat
  • trader_ht_dcperiod »
  • PHP Manual
  • Trader Functions
  • Get unstable period

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.


Hilbert Transform - Dominant Cycle Period

  • « trader_get_unstable_period
  • trader_ht_dcphase »
  • PHP Manual
  • Trader Functions
  • Hilbert Transform - Dominant Cycle Period

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.


Hilbert Transform - Dominant Cycle Phase

  • « trader_ht_dcperiod
  • trader_ht_phasor »
  • PHP Manual
  • Trader Functions
  • Hilbert Transform - Dominant Cycle Phase

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.


Hilbert Transform - Phasor Components

  • « trader_ht_dcphase
  • trader_ht_sine »
  • PHP Manual
  • Trader Functions
  • Hilbert Transform - Phasor Components

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.


Hilbert Transform - SineWave

  • « trader_ht_phasor
  • trader_ht_trendline »
  • PHP Manual
  • Trader Functions
  • Hilbert Transform - SineWave

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.


Hilbert Transform - Instantaneous Trendline

  • « trader_ht_sine
  • trader_ht_trendmode »
  • PHP Manual
  • Trader Functions
  • Hilbert Transform - Instantaneous Trendline

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.


Hilbert Transform - Trend vs Cycle Mode

  • « trader_ht_trendline
  • trader_kama »
  • PHP Manual
  • Trader Functions
  • Hilbert Transform - Trend vs Cycle Mode

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.


Kaufman Adaptive Moving Average

  • « trader_ht_trendmode
  • trader_linearreg_angle »
  • PHP Manual
  • Trader Functions
  • Kaufman Adaptive Moving Average

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.


Linear Regression Angle

  • « trader_kama
  • trader_linearreg_intercept »
  • PHP Manual
  • Trader Functions
  • Linear Regression Angle

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.


Linear Regression Intercept

  • « trader_linearreg_angle
  • trader_linearreg_slope »
  • PHP Manual
  • Trader Functions
  • Linear Regression Intercept

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.


Linear Regression Slope

  • « trader_linearreg_intercept
  • trader_linearreg »
  • PHP Manual
  • Trader Functions
  • Linear Regression Slope

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.


Linear Regression

  • « trader_linearreg_slope
  • trader_ln »
  • PHP Manual
  • Trader Functions
  • Linear Regression

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.


Vector Log Natural

  • « trader_linearreg
  • trader_log10 »
  • PHP Manual
  • Trader Functions
  • Vector Log Natural

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.


Vector Log10

  • « trader_ln
  • trader_ma »
  • PHP Manual
  • Trader Functions
  • Vector Log10

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.


Moving average

  • « trader_log10
  • trader_macd »
  • PHP Manual
  • Trader Functions
  • Moving average

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.


Moving Average Convergence/Divergence

  • « trader_ma
  • trader_macdext »
  • PHP Manual
  • Trader Functions
  • Moving Average Convergence/Divergence

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.


MACD with controllable MA type

  • « trader_macd
  • trader_macdfix »
  • PHP Manual
  • Trader Functions
  • MACD with controllable MA type

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.


Moving Average Convergence/Divergence Fix 12/26

  • « trader_macdext
  • trader_mama »
  • PHP Manual
  • Trader Functions
  • Moving Average Convergence/Divergence Fix 12/26

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.


MESA Adaptive Moving Average

  • « trader_macdfix
  • trader_mavp »
  • PHP Manual
  • Trader Functions
  • MESA Adaptive Moving Average

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.


Moving average with variable period

  • « trader_mama
  • trader_max »
  • PHP Manual
  • Trader Functions
  • Moving average with variable period

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.


Highest value over a specified period

  • « trader_mavp
  • trader_maxindex »
  • PHP Manual
  • Trader Functions
  • Highest value over a specified period

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.


Index of highest value over a specified period

  • « trader_max
  • trader_medprice »
  • PHP Manual
  • Trader Functions
  • Index of highest value over a specified period

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.


Median Price

  • « trader_maxindex
  • trader_mfi »
  • PHP Manual
  • Trader Functions
  • Median Price

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.


Money Flow Index

  • « trader_medprice
  • trader_midpoint »
  • PHP Manual
  • Trader Functions
  • Money Flow Index

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.


MidPoint over period

  • « trader_mfi
  • trader_midprice »
  • PHP Manual
  • Trader Functions
  • MidPoint over period

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.


Midpoint Price over period

  • « trader_midpoint
  • trader_min »
  • PHP Manual
  • Trader Functions
  • Midpoint Price over period

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.


Lowest value over a specified period

  • « trader_midprice
  • trader_minindex »
  • PHP Manual
  • Trader Functions
  • Lowest value over a specified period

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.


Index of lowest value over a specified period

  • « trader_min
  • trader_minmax »
  • PHP Manual
  • Trader Functions
  • Index of lowest value over a specified period

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.


Lowest and highest values over a specified period

  • « trader_minindex
  • trader_minmaxindex »
  • PHP Manual
  • Trader Functions
  • Lowest and highest values over a specified period

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.


Indexes of lowest and highest values over a specified period

  • « trader_minmax
  • trader_minus_di »
  • PHP Manual
  • Trader Functions
  • Indexes of lowest and highest values over a specified period

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.


Minus Directional Indicator

  • « trader_minmaxindex
  • trader_minus_dm »
  • PHP Manual
  • Trader Functions
  • Minus Directional Indicator

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.


Minus Directional Movement

  • « trader_minus_di
  • trader_mom »
  • PHP Manual
  • Trader Functions
  • Minus Directional Movement

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.


Momentum

  • « trader_minus_dm
  • trader_mult »
  • PHP Manual
  • Trader Functions
  • Momentum

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.


Vector Arithmetic Mult

  • « trader_mom
  • trader_natr »
  • PHP Manual
  • Trader Functions
  • Vector Arithmetic Mult

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.


Normalized Average True Range

  • « trader_mult
  • trader_obv »
  • PHP Manual
  • Trader Functions
  • Normalized Average True Range

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.


On Balance Volume

  • « trader_natr
  • trader_plus_di »
  • PHP Manual
  • Trader Functions
  • On Balance Volume

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.


Plus Directional Indicator

  • « trader_obv
  • trader_plus_dm »
  • PHP Manual
  • Trader Functions
  • Plus Directional Indicator

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.


Plus Directional Movement

  • « trader_plus_di
  • trader_ppo »
  • PHP Manual
  • Trader Functions
  • Plus Directional Movement

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.


Percentage Price Oscillator

  • « trader_plus_dm
  • trader_roc »
  • PHP Manual
  • Trader Functions
  • Percentage Price Oscillator

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.


Rate of change : ((price/prevPrice)-1)*100

  • « trader_ppo
  • trader_rocp »
  • PHP Manual
  • Trader Functions
  • Rate of change : ((price/prevPrice)-1)*100

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.


Rate of change Percentage: (price-prevPrice)/prevPrice

  • « trader_roc
  • trader_rocr100 »
  • PHP Manual
  • Trader Functions
  • Rate of change Percentage: (price-prevPrice)/prevPrice

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.


Rate of change ratio 100 scale: (price/prevPrice)*100

  • « trader_rocp
  • trader_rocr »
  • PHP Manual
  • Trader Functions
  • Rate of change ratio 100 scale: (price/prevPrice)*100

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.


Rate of change ratio: (price/prevPrice)

  • « trader_rocr100
  • trader_rsi »
  • PHP Manual
  • Trader Functions
  • Rate of change ratio: (price/prevPrice)

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.


Relative Strength Index

  • « trader_rocr
  • trader_sar »
  • PHP Manual
  • Trader Functions
  • Relative Strength Index

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.


Parabolic SAR

  • « trader_rsi
  • trader_sarext »
  • PHP Manual
  • Trader Functions
  • Parabolic SAR

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.


Parabolic SAR - Extended

  • « trader_sar
  • trader_set_compat »
  • PHP Manual
  • Trader Functions
  • Parabolic SAR - Extended

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.


Set compatibility mode

  • « trader_sarext
  • trader_set_unstable_period »
  • PHP Manual
  • Trader Functions
  • Set compatibility mode

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.


Set unstable period

  • « trader_set_compat
  • trader_sin »
  • PHP Manual
  • Trader Functions
  • Set unstable period

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.


Vector Trigonometric Sin

  • « trader_set_unstable_period
  • trader_sinh »
  • PHP Manual
  • Trader Functions
  • Vector Trigonometric Sin

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.


Vector Trigonometric Sinh

  • « trader_sin
  • trader_sma »
  • PHP Manual
  • Trader Functions
  • Vector Trigonometric Sinh

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.


Simple Moving Average

  • « trader_sinh
  • trader_sqrt »
  • PHP Manual
  • Trader Functions
  • Simple Moving Average

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.


Vector Square Root

  • « trader_sma
  • trader_stddev »
  • PHP Manual
  • Trader Functions
  • Vector Square Root

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.


Standard Deviation

  • « trader_sqrt
  • trader_stoch »
  • PHP Manual
  • Trader Functions
  • Standard Deviation

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.


Stochastic

  • « trader_stddev
  • trader_stochf »
  • PHP Manual
  • Trader Functions
  • Stochastic

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.


Stochastic Fast

  • « trader_stoch
  • trader_stochrsi »
  • PHP Manual
  • Trader Functions
  • Stochastic Fast

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.


Stochastic Relative Strength Index

  • « trader_stochf
  • trader_sub »
  • PHP Manual
  • Trader Functions
  • Stochastic Relative Strength Index

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.


Vector Arithmetic Subtraction

  • « trader_stochrsi
  • trader_sum »
  • PHP Manual
  • Trader Functions
  • Vector Arithmetic Subtraction

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.


Summation

  • « trader_sub
  • trader_t3 »
  • PHP Manual
  • Trader Functions
  • Summation

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.


Triple Exponential Moving Average (T3)

  • « trader_sum
  • trader_tan »
  • PHP Manual
  • Trader Functions
  • Triple Exponential Moving Average (T3)

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.


Vector Trigonometric Tan

  • « trader_t3
  • trader_tanh »
  • PHP Manual
  • Trader Functions
  • Vector Trigonometric Tan

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.


Vector Trigonometric Tanh

  • « trader_tan
  • trader_tema »
  • PHP Manual
  • Trader Functions
  • Vector Trigonometric Tanh

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.


Triple Exponential Moving Average

  • « trader_tanh
  • trader_trange »
  • PHP Manual
  • Trader Functions
  • Triple Exponential Moving Average

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.


True Range

  • « trader_tema
  • trader_trima »
  • PHP Manual
  • Trader Functions
  • True Range

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.


Triangular Moving Average

  • « trader_trange
  • trader_trix »
  • PHP Manual
  • Trader Functions
  • Triangular Moving Average

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.


1-day Rate-Of-Change (ROC) of a Triple Smooth EMA

  • « trader_trima
  • trader_tsf »
  • PHP Manual
  • Trader Functions
  • 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA

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.


Time Series Forecast

  • « trader_trix
  • trader_typprice »
  • PHP Manual
  • Trader Functions
  • Time Series Forecast

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.


Typical Price

  • « trader_tsf
  • trader_ultosc »
  • PHP Manual
  • Trader Functions
  • Typical Price

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.


Ultimate Oscillator

  • « trader_typprice
  • trader_var »
  • PHP Manual
  • Trader Functions
  • Ultimate Oscillator

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.


Variance

  • « trader_ultosc
  • trader_wclprice »
  • PHP Manual
  • Trader Functions
  • Variance

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.


Weighted Close Price

  • « trader_var
  • trader_willr »
  • PHP Manual
  • Trader Functions
  • Weighted Close Price

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.


Williams' %R

  • « trader_wclprice
  • trader_wma »
  • PHP Manual
  • Trader Functions
  • Williams' %R

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.


Weighted Moving Average

  • « trader_willr
  • Non-Text MIME Output »
  • PHP Manual
  • Trader Functions
  • Weighted Moving Average

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.


Non-Text MIME Output

  • FDF — Forms Data Format
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • FDF Functions
  • GnuPG — GNU Privacy Guard
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • GnuPG Functions
  • haru — Haru PDF
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Builtin Fonts And Encodings
    • HaruException — The HaruException class
    • HaruDoc — The HaruDoc class
    • HaruPage — The HaruPage class
    • HaruFont — The HaruFont class
    • HaruImage — The HaruImage class
    • HaruEncoder — The HaruEncoder class
    • HaruOutline — The HaruOutline class
    • HaruAnnotation — The HaruAnnotation class
    • HaruDestination — The HaruDestination class
  • Ming — Ming (flash)
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Ming Functions
    • SWFAction — The SWFAction class
    • SWFBitmap — The SWFBitmap class
    • SWFButton — The SWFButton class
    • SWFDisplayItem — The SWFDisplayItem class
    • SWFFill — The SWFFill class
    • SWFFont — The SWFFont class
    • SWFFontChar — The SWFFontChar class
    • SWFGradient — The SWFGradient class
    • SWFMorph — The SWFMorph class
    • SWFMovie — The SWFMovie class
    • SWFPrebuiltClip — The SWFPrebuiltClip class
    • SWFShape — The SWFShape class
    • SWFSound — The SWFSound class
    • SWFSoundInstance — The SWFSoundInstance class
    • SWFSprite — The SWFSprite class
    • SWFText — The SWFText class
    • SWFTextField — The SWFTextField class
    • SWFVideoStream — The SWFVideoStream class
  • PDF
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • PDF Functions
  • wkhtmltox
    • Introduction
    • 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
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • PS Functions
  • RPM Reader — RPM Header Reading
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • RPM Reader Functions
  • XLSWriter
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Vtiful\Kernel\Excel — The Vtiful\Kernel\Excel class
    • Vtiful\Kernel\Format — The Vtiful\Kernel\Format class


Forms Data Format

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • 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_string — Read a FDF document from a string
    • fdf_open — Open a FDF document
    • fdf_remove_item — Sets target frame for form
    • fdf_save_string — Returns the FDF document as a string
    • fdf_save — Save a FDF document
    • 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


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..


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 as of PHP 5.3.0.

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 (integer)
FDFStatus (integer)
FDFFile (integer)
FDFID (integer)
FDFFf (integer)
FDFSetFf (integer)
FDFClearFf (integer)
FDFFlags (integer)
FDFSetF (integer)
FDFClrF (integer)
FDFAP (integer)
FDFAS (integer)
FDFAction (integer)
FDFAA (integer)
FDFAPRef (integer)
FDFIF (integer)
FDFEnter (integer)
FDFExit (integer)
FDFDown (integer)
FDFUp (integer)
FDFFormat (integer)
FDFValidate (integer)
FDFKeystroke (integer)
FDFCalculate (integer)
FDFNormalAP (integer)
FDFRolloverAP (integer)
FDFDownAP (integer)


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

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_string — Read a FDF document from a string
  • fdf_open — Open a FDF document
  • fdf_remove_item — Sets target frame for form
  • fdf_save_string — Returns the FDF document as a string
  • fdf_save — Save a FDF document
  • 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


Adds javascript code to the FDF document

  • « FDF Functions
  • fdf_add_template »
  • PHP Manual
  • FDF Functions
  • Adds javascript code to the FDF document

fdf_add_doc_javascript

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

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


Adds a template into the FDF document

  • « fdf_add_doc_javascript
  • fdf_close »
  • PHP Manual
  • FDF Functions
  • Adds a template into the FDF document

fdf_add_template

(PHP 4, PHP 5, PHP 7)

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.


Close an FDF document

  • « fdf_add_template
  • fdf_create »
  • PHP Manual
  • FDF Functions
  • Close an FDF document

fdf_close

(PHP 4, PHP 5, PHP 7)

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


Create a new FDF document

  • « fdf_close
  • fdf_enum_values »
  • PHP Manual
  • FDF Functions
  • Create a new FDF document

fdf_create

(PHP 4, PHP 5, PHP 7)

fdf_create — Create a new FDF document

Description

fdf_create ( void ) : resource

Creates a new FDF document.

This function is needed if one would like to populate input fields in a PDF document with data.

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


Call a user defined function for each document value

  • « fdf_create
  • fdf_errno »
  • PHP Manual
  • FDF Functions
  • Call a user defined function for each document value

fdf_enum_values

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

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.


Return error code for last fdf operation

  • « fdf_enum_values
  • fdf_error »
  • PHP Manual
  • FDF Functions
  • Return error code for last fdf operation

fdf_errno

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

fdf_errno — Return error code for last fdf operation

Description

fdf_errno ( void ) : 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().

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


Return error description for FDF error code

  • « fdf_errno
  • fdf_get_ap »
  • PHP Manual
  • FDF Functions
  • Return error description for FDF error code

fdf_error

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

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


Get the appearance of a field

  • « fdf_error
  • fdf_get_attachment »
  • PHP Manual
  • FDF Functions
  • Get the appearance of a field

fdf_get_ap

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

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.


Extracts uploaded file embedded in the FDF

  • « fdf_get_ap
  • fdf_get_encoding »
  • PHP Manual
  • FDF Functions
  • Extracts uploaded file embedded in the FDF

fdf_get_attachment

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

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]";
?>


Get the value of the /Encoding key

  • « fdf_get_attachment
  • fdf_get_file »
  • PHP Manual
  • FDF Functions
  • Get the value of the /Encoding key

fdf_get_encoding

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

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


Get the value of the /F key

  • « fdf_get_encoding
  • fdf_get_flags »
  • PHP Manual
  • FDF Functions
  • Get the value of the /F key

fdf_get_file

(PHP 4, PHP 5, PHP 7)

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


Gets the flags of a field

  • « fdf_get_file
  • fdf_get_opt »
  • PHP Manual
  • FDF Functions
  • Gets the flags of a field

fdf_get_flags

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

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.


Gets a value from the opt array of a field

  • « fdf_get_flags
  • fdf_get_status »
  • PHP Manual
  • FDF Functions
  • Gets a value from the opt array of a field

fdf_get_opt

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

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.


Get the value of the /STATUS key

  • « fdf_get_opt
  • fdf_get_value »
  • PHP Manual
  • FDF Functions
  • Get the value of the /STATUS key

fdf_get_status

(PHP 4, PHP 5, PHP 7)

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


Get the value of a field

  • « fdf_get_status
  • fdf_get_version »
  • PHP Manual
  • FDF Functions
  • Get the value of a field

fdf_get_value

(PHP 4, PHP 5, PHP 7)

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.

Changelog

Version | Description
4.3.0 | Support for arrays and the which parameter were added.

See Also

  • fdf_set_value() - Set the value of a field


Gets version number for FDF API or file

  • « fdf_get_value
  • fdf_header »
  • PHP Manual
  • FDF Functions
  • Gets version number for FDF API or file

fdf_get_version

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

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


Sets FDF-specific output headers

  • « fdf_get_version
  • fdf_next_field_name »
  • PHP Manual
  • FDF Functions
  • Sets FDF-specific output headers

fdf_header

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

fdf_header — Sets FDF-specific output headers

Description

fdf_header ( void ) : void

This is a convenience function to set appropriate HTTP headers for FDF output. It sets the Content-type: to application/vnd.fdf.

Return Values

No value is returned.


Get the next field name

  • « fdf_header
  • fdf_open_string »
  • PHP Manual
  • FDF Functions
  • Get the next field name

fdf_next_field_name

(PHP 4, PHP 5, PHP 7)

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


Read a FDF document from a string

  • « fdf_next_field_name
  • fdf_open »
  • PHP Manual
  • FDF Functions
  • Read a FDF document from a string

fdf_open_string

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

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


Open a FDF document

  • « fdf_open_string
  • fdf_remove_item »
  • PHP Manual
  • FDF Functions
  • Open a FDF document

fdf_open

(PHP 4, PHP 5, PHP 7)

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


Sets target frame for form

  • « fdf_open
  • fdf_save_string »
  • PHP Manual
  • FDF Functions
  • Sets target frame for form

fdf_remove_item

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

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.


Returns the FDF document as a string

  • « fdf_remove_item
  • fdf_save »
  • PHP Manual
  • FDF Functions
  • Returns the FDF document as a string

fdf_save_string

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

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


Save a FDF document

  • « fdf_save_string
  • fdf_set_ap »
  • PHP Manual
  • FDF Functions
  • Save a FDF document

fdf_save

(PHP 4, PHP 5, PHP 7)

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


Set the appearance of a field

  • « fdf_save
  • fdf_set_encoding »
  • PHP Manual
  • FDF Functions
  • Set the appearance of a field

fdf_set_ap

(PHP 4, PHP 5, PHP 7)

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.


Sets FDF character encoding

  • « fdf_set_ap
  • fdf_set_file »
  • PHP Manual
  • FDF Functions
  • Sets FDF character encoding

fdf_set_encoding

(PHP 4 >= 4.0.7, PHP 5, PHP 7)

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.


Set PDF document to display FDF data in

  • « fdf_set_encoding
  • fdf_set_flags »
  • PHP Manual
  • FDF Functions
  • Set PDF document to display FDF data in

fdf_set_file

(PHP 4, PHP 5, PHP 7)

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


Sets a flag of a field

  • « fdf_set_file
  • fdf_set_javascript_action »
  • PHP Manual
  • FDF Functions
  • Sets a flag of a field

fdf_set_flags

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

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


Sets an javascript action of a field

  • « fdf_set_flags
  • fdf_set_on_import_javascript »
  • PHP Manual
  • FDF Functions
  • Sets an javascript action of a field

fdf_set_javascript_action

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

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


Adds javascript code to be executed when Acrobat opens the FDF

  • « fdf_set_javascript_action
  • fdf_set_opt »
  • PHP Manual
  • FDF Functions
  • Adds javascript code to be executed when Acrobat opens the FDF

fdf_set_on_import_javascript

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

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


Sets an option of a field

  • « fdf_set_on_import_javascript
  • fdf_set_status »
  • PHP Manual
  • FDF Functions
  • Sets an option of a field

fdf_set_opt

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

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


Set the value of the /STATUS key

  • « fdf_set_opt
  • fdf_set_submit_form_action »
  • PHP Manual
  • FDF Functions
  • Set the value of the /STATUS key

fdf_set_status

(PHP 4, PHP 5, PHP 7)

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


Sets a submit form action of a field

  • « fdf_set_status
  • fdf_set_target_frame »
  • PHP Manual
  • FDF Functions
  • Sets a submit form action of a field

fdf_set_submit_form_action

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

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


Set target frame for form display

  • « fdf_set_submit_form_action
  • fdf_set_value »
  • PHP Manual
  • FDF Functions
  • Set target frame for form display

fdf_set_target_frame

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

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()


Set the value of a field

  • « fdf_set_target_frame
  • fdf_set_version »
  • PHP Manual
  • FDF Functions
  • Set the value of a field

fdf_set_value

(PHP 4, PHP 5, PHP 7)

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 beginning with PHP 4.3, but ignored internally.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
4.3.0 | Support for arrays in the value parameter was added.

See Also

  • fdf_get_value() - Get the value of a field
  • fdf_remove_item() - Sets target frame for form


Sets version number for a FDF file

  • « fdf_set_value
  • GnuPG »
  • PHP Manual
  • FDF Functions
  • Sets version number for a FDF file

fdf_set_version

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

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


GNU Privacy Guard

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • 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_encrypt — Encrypts a given text
    • gnupg_encryptsign — Encrypts and signs a given text
    • gnupg_export — Exports a key
    • gnupg_geterror — Returns the errortext, if a function fails
    • gnupg_getprotocol — Returns the currently active protocol for all operations
    • 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_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


  • « GnuPG
  • Installing/Configuring »
  • PHP Manual
  • GnuPG
  • Introduction

Introduction

This module allows you to interact with » gnupg.


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

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 (integer)
GNUPG_SIG_MODE_DETACH (integer)
GNUPG_SIG_MODE_CLEAR (integer)
GNUPG_VALIDITY_UNKNOWN (integer)
GNUPG_VALIDITY_UNDEFINED (integer)
GNUPG_VALIDITY_NEVER (integer)
GNUPG_VALIDITY_MARGINAL (integer)
GNUPG_VALIDITY_FULL (integer)
GNUPG_VALIDITY_ULTIMATE (integer)
GNUPG_PROTOCOL_OpenPGP (integer)
GNUPG_PROTOCOL_CMS (integer)
GNUPG_SIGSUM_VALID (integer)
GNUPG_SIGSUM_GREEN (integer)
GNUPG_SIGSUM_RED (integer)
GNUPG_SIGSUM_KEY_REVOKED (integer)
GNUPG_SIGSUM_KEY_EXPIRED (integer)
GNUPG_SIGSUM_KEY_MISSING (integer)
GNUPG_SIGSUM_SIG_EXPIRED (integer)
GNUPG_SIGSUM_CRL_MISSING (integer)
GNUPG_SIGSUM_CRL_TOO_OLD (integer)
GNUPG_SIGSUM_BAD_POLICY (integer)
GNUPG_SIGSUM_SYS_ERROR (integer)
GNUPG_ERROR_WARNING (integer)
GNUPG_ERROR_EXCEPTION (integer)
GNUPG_ERROR_SILENT (integer)


  • « Predefined Constants
  • Clearsign text »
  • PHP Manual
  • GnuPG
  • Examples

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.

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_encrypt — Encrypts a given text
  • gnupg_encryptsign — Encrypts and signs a given text
  • gnupg_export — Exports a key
  • gnupg_geterror — Returns the errortext, if a function fails
  • gnupg_getprotocol — Returns the currently active protocol for all operations
  • 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_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


Add a key for decryption

  • « GnuPG Functions
  • gnupg_addencryptkey »
  • PHP Manual
  • GnuPG Functions
  • Add a key for decryption

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");
?>


Add a key for encryption

  • « gnupg_adddecryptkey
  • gnupg_addsignkey »
  • PHP Manual
  • GnuPG Functions
  • Add a key for encryption

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");
?>


Add a key for signing

  • « gnupg_addencryptkey
  • gnupg_cleardecryptkeys »
  • PHP Manual
  • GnuPG Functions
  • Add a key for signing

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");
?>


Removes all keys which were set for decryption before

  • « gnupg_addsignkey
  • gnupg_clearencryptkeys »
  • PHP Manual
  • GnuPG Functions
  • Removes all keys which were set for decryption before

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();
?>


Removes all keys which were set for encryption before

  • « gnupg_cleardecryptkeys
  • gnupg_clearsignkeys »
  • PHP Manual
  • GnuPG Functions
  • Removes all keys which were set for encryption before

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();
?>


Removes all keys which were set for signing before

  • « gnupg_clearencryptkeys
  • gnupg_decrypt »
  • PHP Manual
  • GnuPG Functions
  • Removes all keys which were set for signing before

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();
?>


Decrypts a given text

  • « gnupg_clearsignkeys
  • gnupg_decryptverify »
  • PHP Manual
  • GnuPG Functions
  • Decrypts a given text

gnupg_decrypt

(PECL gnupg >= 0.1)

gnupg_decrypt — Decrypts a given text

Description

gnupg_decrypt ( resource $identifier , string $text ) : string

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_encrypt() example

<?php
$gpg = new gnupg();
$gpg -> adddecryptkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
$plain = $gpg -> decrypt($encrypted_text);
echo $plain;
?>


Decrypts and verifies a given text

  • « gnupg_decrypt
  • gnupg_encrypt »
  • PHP Manual
  • GnuPG Functions
  • Decrypts and verifies a given text

gnupg_decryptverify

(PECL gnupg >= 0.2)

gnupg_decryptverify — Decrypts and verifies a given text

Description

gnupg_decryptverify ( resource $identifier , string $text , string &$plaintext ) : array

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);
?>


Encrypts a given text

  • « gnupg_decryptverify
  • gnupg_encryptsign »
  • PHP Manual
  • GnuPG Functions
  • Encrypts a given text

gnupg_encrypt

(PECL gnupg >= 0.1)

gnupg_encrypt — Encrypts a given text

Description

gnupg_encrypt ( resource $identifier , string $plaintext ) : string

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;
?>


Encrypts and signs a given text

  • « gnupg_encrypt
  • gnupg_export »
  • PHP Manual
  • GnuPG Functions
  • Encrypts and signs a given text

gnupg_encryptsign

(PECL gnupg >= 0.2)

gnupg_encryptsign — Encrypts and signs a given text

Description

gnupg_encryptsign ( resource $identifier , string $plaintext ) : string

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;
?>


Exports a key

  • « gnupg_encryptsign
  • gnupg_geterror »
  • PHP Manual
  • GnuPG Functions
  • Exports a key

gnupg_export

(PECL gnupg >= 0.1)

gnupg_export — Exports a key

Description

gnupg_export ( resource $identifier , string $fingerprint ) : string

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");
?>


Returns the errortext, if a function fails

  • « gnupg_export
  • gnupg_getprotocol »
  • PHP Manual
  • GnuPG Functions
  • Returns the errortext, if a function fails

gnupg_geterror

(PECL gnupg >= 0.1)

gnupg_geterror — Returns the errortext, if a function fails

Description

gnupg_geterror ( resource $identifier ) : string

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();
?>


Returns the currently active protocol for all operations

  • « gnupg_geterror
  • gnupg_import »
  • PHP Manual
  • GnuPG Functions
  • Returns the currently active protocol for all operations

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();
?>


Imports a key

  • « gnupg_getprotocol
  • gnupg_init »
  • PHP Manual
  • GnuPG Functions
  • Imports a key

gnupg_import

(PECL gnupg >= 0.3)

gnupg_import — Imports a key

Description

gnupg_import ( resource $identifier , string $keydata ) : array

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);
?>


Initialize a connection

  • « gnupg_import
  • gnupg_keyinfo »
  • PHP Manual
  • GnuPG Functions
  • Initialize a connection

gnupg_init

(PECL gnupg >= 0.4)

gnupg_init — Initialize a connection

Description

gnupg_init ( void ) : resource

Parameters

This function has no parameters.

Return Values

A GnuPG resource connection used by other GnuPG functions.

Examples

Example #1 Procedural gnupg_init() example

<?php
$res = gnupg_init();
?>

Example #2 OO gnupg initializer example

<?php
$gpg = new gnupg();
?>


Returns an array with information about all keys that matches the given pattern

  • « gnupg_init
  • gnupg_setarmor »
  • PHP Manual
  • GnuPG Functions
  • Returns an array with information about all keys that matches the given pattern

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

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);
?>


Toggle armored output

  • « gnupg_keyinfo
  • gnupg_seterrormode »
  • PHP Manual
  • GnuPG Functions
  • Toggle armored output

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;
?>


Sets the mode for error_reporting

  • « gnupg_setarmor
  • gnupg_setsignmode »
  • PHP Manual
  • GnuPG Functions
  • Sets the mode for error_reporting

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
?>


Sets the mode for signing

  • « gnupg_seterrormode
  • gnupg_sign »
  • PHP Manual
  • GnuPG Functions
  • Sets the mode for signing

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
?>


Signs a given text

  • « gnupg_setsignmode
  • gnupg_verify »
  • PHP Manual
  • GnuPG Functions
  • Signs a given text

gnupg_sign

(PECL gnupg >= 0.1)

gnupg_sign — Signs a given text

Description

gnupg_sign ( resource $identifier , string $plaintext ) : string

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;
?>


Verifies a signed text

  • « gnupg_sign
  • haru »
  • PHP Manual
  • GnuPG Functions
  • Verifies a signed text

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

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);
?>


Haru PDF

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic PECL/haru example
  • Builtin Fonts And Encodings
    • Builtin Fonts
    • Builtin Encodings
  • HaruException — The HaruException class
  • HaruDoc — The HaruDoc class
    • HaruDoc::addPage — Add new page to the document
    • HaruDoc::addPageLabel — Set the numbering style for the specified range of pages
    • HaruDoc::__construct — Construct new HaruDoc instance
    • HaruDoc::createOutline — Create a HaruOutline instance
    • HaruDoc::getCurrentEncoder — Get HaruEncoder currently used in the document
    • HaruDoc::getCurrentPage — Return current page of the document
    • HaruDoc::getEncoder — Get HaruEncoder instance for the specified encoding
    • HaruDoc::getFont — Get HaruFont instance
    • HaruDoc::getInfoAttr — Get current value of the specified document attribute
    • HaruDoc::getPageLayout — Get current page layout
    • HaruDoc::getPageMode — Get current page mode
    • HaruDoc::getStreamSize — Get the size of the temporary stream
    • HaruDoc::insertPage — Insert new page just before the specified page
    • HaruDoc::loadJPEG — Load a JPEG image
    • HaruDoc::loadPNG — Load PNG image and return HaruImage instance
    • HaruDoc::loadRaw — Load a RAW image
    • HaruDoc::loadTTC — Load the font with the specified index from TTC file
    • HaruDoc::loadTTF — Load TTF font file
    • HaruDoc::loadType1 — Load Type1 font
    • HaruDoc::output — Write the document data to the output buffer
    • HaruDoc::readFromStream — Read data from the temporary stream
    • HaruDoc::resetError — Reset error state of the document handle
    • HaruDoc::resetStream — Rewind the temporary stream
    • HaruDoc::save — Save the document into the specified file
    • HaruDoc::saveToStream — Save the document into a temporary stream
    • HaruDoc::setCompressionMode — Set compression mode for the document
    • HaruDoc::setCurrentEncoder — Set the current encoder for the document
    • HaruDoc::setEncryptionMode — Set encryption mode for the document
    • HaruDoc::setInfoAttr — Set the info attribute of the document
    • HaruDoc::setInfoDateAttr — Set the datetime info attributes of the document
    • HaruDoc::setOpenAction — Define which page is shown when the document is opened
    • HaruDoc::setPageLayout — Set how pages should be displayed
    • HaruDoc::setPageMode — Set how the document should be displayed
    • HaruDoc::setPagesConfiguration — Set the number of pages per set of pages
    • HaruDoc::setPassword — Set owner and user passwords for the document
    • HaruDoc::setPermission — Set permissions for the document
    • HaruDoc::useCNSEncodings — Enable Chinese simplified encodings
    • HaruDoc::useCNSFonts — Enable builtin Chinese simplified fonts
    • HaruDoc::useCNTEncodings — Enable Chinese traditional encodings
    • HaruDoc::useCNTFonts — Enable builtin Chinese traditional fonts
    • HaruDoc::useJPEncodings — Enable Japanese encodings
    • HaruDoc::useJPFonts — Enable builtin Japanese fonts
    • HaruDoc::useKREncodings — Enable Korean encodings
    • HaruDoc::useKRFonts — Enable builtin Korean fonts
  • HaruPage — The HaruPage class
    • HaruPage::arc — Append an arc to the current path
    • HaruPage::beginText — Begin a text object and set the current text position to (0,0)
    • HaruPage::circle — Append a circle to the current path
    • HaruPage::closePath — Append a straight line from the current point to the start point of the path
    • HaruPage::concat — Concatenate current transformation matrix of the page and the specified matrix
    • HaruPage::createDestination — Create new HaruDestination instance
    • HaruPage::createLinkAnnotation — Create new HaruAnnotation instance
    • HaruPage::createTextAnnotation — Create new HaruAnnotation instance
    • HaruPage::createURLAnnotation — Create and return new HaruAnnotation instance
    • HaruPage::curveTo2 — Append a Bezier curve to the current path
    • HaruPage::curveTo3 — Append a Bezier curve to the current path
    • HaruPage::curveTo — Append a Bezier curve to the current path
    • HaruPage::drawImage — Show image at the page
    • HaruPage::ellipse — Append an ellipse to the current path
    • HaruPage::endPath — End current path object without filling and painting operations
    • HaruPage::endText — End current text object
    • HaruPage::eofill — Fill current path using even-odd rule
    • HaruPage::eoFillStroke — Fill current path using even-odd rule, then paint the path
    • HaruPage::fill — Fill current path using nonzero winding number rule
    • HaruPage::fillStroke — Fill current path using nonzero winding number rule, then paint the path
    • HaruPage::getCharSpace — Get the current value of character spacing
    • HaruPage::getCMYKFill — Get the current filling color
    • HaruPage::getCMYKStroke — Get the current stroking color
    • HaruPage::getCurrentFont — Get the currently used font
    • HaruPage::getCurrentFontSize — Get the current font size
    • HaruPage::getCurrentPos — Get the current position for path painting
    • HaruPage::getCurrentTextPos — Get the current position for text printing
    • HaruPage::getDash — Get the current dash pattern
    • HaruPage::getFillingColorSpace — Get the current filling color space
    • HaruPage::getFlatness — Get the flatness of the page
    • HaruPage::getGMode — Get the current graphics mode
    • HaruPage::getGrayFill — Get the current filling color
    • HaruPage::getGrayStroke — Get the current stroking color
    • HaruPage::getHeight — Get the height of the page
    • HaruPage::getHorizontalScaling — Get the current value of horizontal scaling
    • HaruPage::getLineCap — Get the current line cap style
    • HaruPage::getLineJoin — Get the current line join style
    • HaruPage::getLineWidth — Get the current line width
    • HaruPage::getMiterLimit — Get the value of miter limit
    • HaruPage::getRGBFill — Get the current filling color
    • HaruPage::getRGBStroke — Get the current stroking color
    • HaruPage::getStrokingColorSpace — Get the current stroking color space
    • HaruPage::getTextLeading — Get the current value of line spacing
    • HaruPage::getTextMatrix — Get the current text transformation matrix of the page
    • HaruPage::getTextRenderingMode — Get the current text rendering mode
    • HaruPage::getTextRise — Get the current value of text rising
    • HaruPage::getTextWidth — Get the width of the text using current fontsize, character spacing and word spacing
    • HaruPage::getTransMatrix — Get the current transformation matrix of the page
    • HaruPage::getWidth — Get the width of the page
    • HaruPage::getWordSpace — Get the current value of word spacing
    • HaruPage::lineTo — Draw a line from the current point to the specified point
    • HaruPage::measureText — Calculate the byte length of characters which can be included on one line of the specified width
    • HaruPage::moveTextPos — Move text position to the specified offset
    • HaruPage::moveTo — Set starting point for new drawing path
    • HaruPage::moveToNextLine — Move text position to the start of the next line
    • HaruPage::rectangle — Append a rectangle to the current path
    • HaruPage::setCharSpace — Set character spacing for the page
    • HaruPage::setCMYKFill — Set filling color for the page
    • HaruPage::setCMYKStroke — Set stroking color for the page
    • HaruPage::setDash — Set the dash pattern for the page
    • HaruPage::setFlatness — Set flatness for the page
    • HaruPage::setFontAndSize — Set font and fontsize for the page
    • HaruPage::setGrayFill — Set filling color for the page
    • HaruPage::setGrayStroke — Sets stroking color for the page
    • HaruPage::setHeight — Set height of the page
    • HaruPage::setHorizontalScaling — Set horizontal scaling for the page
    • HaruPage::setLineCap — Set the shape to be used at the ends of lines
    • HaruPage::setLineJoin — Set line join style for the page
    • HaruPage::setLineWidth — Set line width for the page
    • HaruPage::setMiterLimit — Set the current value of the miter limit of the page
    • HaruPage::setRGBFill — Set filling color for the page
    • HaruPage::setRGBStroke — Set stroking color for the page
    • HaruPage::setRotate — Set rotation angle of the page
    • HaruPage::setSize — Set size and direction of the page
    • HaruPage::setSlideShow — Set transition style for the page
    • HaruPage::setTextLeading — Set text leading (line spacing) for the page
    • HaruPage::setTextMatrix — Set the current text transformation matrix of the page
    • HaruPage::setTextRenderingMode — Set text rendering mode for the page
    • HaruPage::setTextRise — Set the current value of text rising
    • HaruPage::setWidth — Set width of the page
    • HaruPage::setWordSpace — Set word spacing for the page
    • HaruPage::showText — Print text at the current position of the page
    • HaruPage::showTextNextLine — Move the current position to the start of the next line and print the text
    • HaruPage::stroke — Paint current path
    • HaruPage::textOut — Print the text on the specified position
    • HaruPage::textRect — Print the text inside the specified region
  • HaruFont — The HaruFont class
    • HaruFont::getAscent — Get the vertical ascent of the font
    • HaruFont::getCapHeight — Get the distance from the baseline of uppercase letters
    • HaruFont::getDescent — Get the vertical descent of the font
    • HaruFont::getEncodingName — Get the name of the encoding
    • HaruFont::getFontName — Get the name of the font
    • HaruFont::getTextWidth — Get the total width of the text, number of characters, number of words and number of spaces
    • HaruFont::getUnicodeWidth — Get the width of the character in the font
    • HaruFont::getXHeight — Get the distance from the baseline of lowercase letters
    • HaruFont::measureText — Calculate the number of characters which can be included within the specified width
  • HaruImage — The HaruImage class
    • HaruImage::getBitsPerComponent — Get the number of bits used to describe each color component of the image
    • HaruImage::getColorSpace — Get the name of the color space
    • HaruImage::getHeight — Get the height of the image
    • HaruImage::getSize — Get size of the image
    • HaruImage::getWidth — Get the width of the image
    • HaruImage::setColorMask — Set the color mask of the image
    • HaruImage::setMaskImage — Set the image mask
  • HaruEncoder — The HaruEncoder class
    • HaruEncoder::getByteType — Get the type of the byte in the text
    • HaruEncoder::getType — Get the type of the encoder
    • HaruEncoder::getUnicode — Convert the specified character to unicode
    • HaruEncoder::getWritingMode — Get the writing mode of the encoder
  • HaruOutline — The HaruOutline class
    • HaruOutline::setDestination — Set the destination for the outline
    • HaruOutline::setOpened — Set the initial state of the outline
  • HaruAnnotation — The HaruAnnotation class
    • HaruAnnotation::setBorderStyle — Set the border style of the annotation
    • HaruAnnotation::setHighlightMode — Set the highlighting mode of the annotation
    • HaruAnnotation::setIcon — Set the icon style of the annotation
    • HaruAnnotation::setOpened — Set the initial state of the annotation
  • HaruDestination — The HaruDestination class
    • HaruDestination::setFit — Set the appearance of the page to fit the window
    • HaruDestination::setFitB — Set the appearance of the page to fit the bounding box of the page within the window
    • HaruDestination::setFitBH — Set the appearance of the page to fit the width of the bounding box
    • HaruDestination::setFitBV — Set the appearance of the page to fit the height of the boudning box
    • HaruDestination::setFitH — Set the appearance of the page to fit the window width
    • HaruDestination::setFitR — Set the appearance of the page to fit the specified rectangle
    • HaruDestination::setFitV — Set the appearance of the page to fit the window height
    • HaruDestination::setXYZ — Set the appearance of the page


Introduction

The PECL/haru extension provides bindings to the libHaru library. libHaru is a free, cross platform, and Open Source library for generating PDF files.

The Haru library (libHaru) may be found here: » http://libharu.org.

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.


Requirements

You need to install libharu first to be able to use PECL/haru. PECL/haru is tested with libharu 2.0.8, older versions might or might not work for you. PECL/haru also requires PHP 5.1.3 or newer.


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/haru.


  • « Resource Types
  • Examples »
  • PHP Manual
  • haru
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


  • « Predefined Constants
  • Basic PECL/haru example »
  • PHP Manual
  • haru
  • Examples

Examples

Table of Contents

  • Basic PECL/haru example


Basic PECL/haru example

Example #1 Fancy "Hello world"

<?php

$doc = new HaruDoc;

$doc->setPageMode(HaruDoc::PAGE_MODE_USE_THUMBS); /* show thumbnails */

$page = $doc->addPage(); /* add page to the document */
$page->setSize(HaruPage::SIZE_A4, HaruPage::LANDSCAPE); /* set the page to use A4 landscape format */

$courier = $doc->getFont("Courier-Bold"); /* we'll use the bundled font a few lines below */

$page->setRGBStroke(0, 0, 0); /* set colors */
$page->setRGBFill(0.7, 0.8, 0.9);
$page->rectangle(150, 150, 550, 250); /* draw a rectangle */

$page->fillStroke(); /* fill and stroke it */

$page->setDash(array(3, 3), 0); /* set dash style for lines at this page */
$page->setFontAndSize($courier, 60); /* set font and size */

$page->setRGBStroke(0.5, 0.5, 0.1); /* set line color */
$page->setRGBFill(1, 1, 1); /* set filling color */

$page->setTextRenderingMode(HaruPage::FILL_THEN_STROKE); /* fill and stroke text */

/* print the text */
$page->beginText();
$page->textOut(210, 270, "Hello World!");
$page->endText();

$doc->save("/tmp/test.pdf"); /* save the document into a file */

?>

Open the result document in your favourite PDF viewer and you should see a light-blue rectangle and white "Hello World!" on it.


  • « Basic PECL/haru example
  • Builtin Fonts »
  • PHP Manual
  • haru
  • Builtin Fonts And Encodings

Builtin Fonts And Encodings

Table of Contents

  • Builtin Fonts
  • Builtin Encodings


Builtin Fonts

These Base14 fonts are built-in into PDF and all viewers can display them. Using these fonts may decrease the size of the result file and make the processing faster, avoiding loading external fonts. However the fonts support only latin1 character set and you have to load external fonts if you need to use an other character set.

The Base14 fonts:

  • Courier

  • Courier-Bold

  • Courier-Oblique

  • Courier-BoldOblique

  • Helvetica

  • Helvetica-Bold

  • Helvetica-Oblique

  • Helvetica-BoldOblique

  • Times-Roman

  • Times-Bold

  • Times-Italic

  • Times-BoldItalic

  • Symbol

  • ZapfDingbats


Builtin Encodings

Single-byte character set encodings
Name | Description
StandardEncoding | The default encoding of PDF.
MacRomanEncoding | The standard encoding of Mac OS.
WinAnsiEncoding | The standard encoding of Windows.
FontSpecific | The font built-in encoding.
ISO8859-2 | Latin2 (East European)
ISO8859-3 | Latin3 (South European)
ISO8859-4 | Latin4 (North European)
ISO8859-5 | Cyrillic
ISO8859-6 | Arabic
ISO8859-7 | Greek
ISO8859-8 | Hebrew
ISO8859-9 | Latin5 (Turkish)
ISO8859-10 | Latin6 (Nordic)
ISO8859-11 | Thai
ISO8859-13 | Latin7 (Baltic Rim)
ISO8859-14 | Latin8 (Celtic)
ISO8859-15 | Latin9
ISO8859-16 | Latin10
CP1250 | MS Windows Codepage 1250.
CP1251 | MS Windows Codepage 1251.
CP1252 | MS Windows Codepage 1252.
CP1253 | MS Windows Codepage 1253.
CP1254 | MS Windows Codepage 1254.
CP1255 | MS Windows Codepage 1255.
CP1256 | MS Windows Codepage 1256.
CP1257 | MS Windows Codepage 1257.
CP1258 | MS Windows Codepage 1258.
KOI8-R | Cyrillic character set.
Multi-byte character set encodings
Name | Description
GB-EUC-H | EUC-CN encoding.
GB-EUC-V | Vertical writing version of GB-EUC-H.
GBK-EUC-H | Microsoft Code Page 936 (lfCharSet 0x86) GBK encoding.
GBK-EUC-V | Vertical writing version of GBK-EUC-H.
ETen-B5-H | Microsoft Code Page 950 (lfCharSet 0x88) Big Five character set with ETen extensions.
ETen-B5-V | Vertical writing version of ETen-B5-H.
90ms-RKSJ-H | Microsoft Code Page 932, JIS X 0208 character.
90ms-RKSJ-V | Vertical writing version of 90ms-RKSJ-V.
90msp-RKSJ-H | Microsoft Code Page 932, JIS X 0208 character (proportional).
EUC-H | JIS X 0208 character set, EUC-JP encoding.
EUC-V | Vertical writing version of EUC-H.
KSC-EUC-H | KS X 1001:1992 character set, EUC-KR encoding.
KSC-EUC-V | Vertical writing version of KSC-EUC-V.
KSCms-UHC-H | Microsoft Code Page 949 (lfCharSet 0x81), KS X 1001:1992 character set plus 8822 additional hangul, Unified Hangul Code (UHC) encoding (proportional).
KSCms-UHC-HW-H | Microsoft Code Page 949 (lfCharSet 0x81), KS X 1001:1992 character set plus 8822 additional hangul, Unified Hangul Code (UHC) encoding (fixed width).
KSCms-UHC-HW-V | Vertical writing version of KSCms-UHC-HW-H.


The HaruException class

(PECL haru >= 0.0.1)

Introduction

Haru PDF Exception Class.

Class synopsis

HaruException extends Exception {
/* Inherits */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The HaruDoc class

(PECL haru >= 0.0.1)

Introduction

Haru PDF Document Class.

Class synopsis

HaruDoc {
/* Methods */
addPage ( void ) : object
addPageLabel ( int $first_page , int $style , int $first_num [, string $prefix = "" ] ) : bool
__construct ( void )
createOutline ( string $title [, object $parent_outline [, object $encoder ]] ) : object
getCurrentEncoder ( void ) : object
getCurrentPage ( void ) : object
getEncoder ( string $encoding ) : object
getFont ( string $fontname [, string $encoding ] ) : object
getInfoAttr ( int $type ) : string
getPageLayout ( void ) : int
getPageMode ( void ) : int
getStreamSize ( void ) : int
insertPage ( object $page ) : object
loadJPEG ( string $filename ) : object
loadPNG ( string $filename [, bool $deferred = FALSE ] ) : object
loadRaw ( string $filename , int $width , int $height , int $color_space ) : object
loadTTC ( string $fontfile , int $index [, bool $embed = FALSE ] ) : string
loadTTF ( string $fontfile [, bool $embed = FALSE ] ) : string
loadType1 ( string $afmfile [, string $pfmfile ] ) : string
output ( void ) : bool
readFromStream ( int $bytes ) : string
resetError ( void ) : bool
resetStream ( void ) : bool
save ( string $file ) : bool
saveToStream ( void ) : bool
setCompressionMode ( int $mode ) : bool
setCurrentEncoder ( string $encoding ) : bool
setEncryptionMode ( int $mode [, int $key_len = 5 ] ) : bool
setInfoAttr ( int $type , string $info ) : bool
setInfoDateAttr ( int $type , int $year , int $month , int $day , int $hour , int $min , int $sec , string $ind , int $off_hour , int $off_min ) : bool
setOpenAction ( object $destination ) : bool
setPageLayout ( int $layout ) : bool
setPageMode ( int $mode ) : bool
setPagesConfiguration ( int $page_per_pages ) : bool
setPassword ( string $owner_password , string $user_password ) : bool
setPermission ( int $permission ) : bool
useCNSEncodings ( void ) : bool
useCNSFonts ( void ) : bool
useCNTEncodings ( void ) : bool
useCNTFonts ( void ) : bool
useJPEncodings ( void ) : bool
useJPFonts ( void ) : bool
useKREncodings ( void ) : bool
useKRFonts ( void ) : bool
}

Predefined Constants

Type | Name | Description
int | HaruDoc::CS_DEVICE_GRAY |
int | HaruDoc::CS_DEVICE_RGB |
int | HaruDoc::CS_DEVICE_CMYK |
int | HaruDoc::CS_CAL_GRAY |
int | HaruDoc::CS_CAL_RGB |
int | HaruDoc::CS_LAB |
int | HaruDoc::CS_ICC_BASED |
int | HaruDoc::CS_SEPARATION |
int | HaruDoc::CS_DEVICE_N |
int | HaruDoc::CS_INDEXED |
int | HaruDoc::CS_PATTERN |
int | HaruDoc::ENABLE_READ |
int | HaruDoc::ENABLE_PRINT |
int | HaruDoc::ENABLE_EDIT_ALL |
int | HaruDoc::ENABLE_COPY |
int | HaruDoc::ENABLE_EDIT |
int | HaruDoc::ENCRYPT_R2 |
int | HaruDoc::ENCRYPT_R3 |
int | HaruDoc::INFO_AUTHOR |
int | HaruDoc::INFO_CREATOR |
int | HaruDoc::INFO_TITLE |
int | HaruDoc::INFO_SUBJECT |
int | HaruDoc::INFO_KEYWORDS |
int | HaruDoc::INFO_CREATION_DATE |
int | HaruDoc::INFO_MOD_DATE |
int | HaruDoc::COMP_NONE |
int | HaruDoc::COMP_TEXT |
int | HaruDoc::COMP_IMAGE |
int | HaruDoc::COMP_METADATA |
int | HaruDoc::COMP_ALL |
int | HaruDoc::PAGE_LAYOUT_SINGLE |
int | HaruDoc::PAGE_LAYOUT_ONE_COLUMN |
int | HaruDoc::PAGE_LAYOUT_TWO_COLUMN_LEFT |
int | HaruDoc::PAGE_LAYOUT_TWO_COLUMN_RIGHT |
int | HaruDoc::PAGE_MODE_USE_NONE |
int | HaruDoc::PAGE_MODE_USE_OUTLINE |
int | HaruDoc::PAGE_MODE_USE_THUMBS |
int | HaruDoc::PAGE_MODE_FULL_SCREEN |

Table of Contents

  • HaruDoc::addPage — Add new page to the document
  • HaruDoc::addPageLabel — Set the numbering style for the specified range of pages
  • HaruDoc::__construct — Construct new HaruDoc instance
  • HaruDoc::createOutline — Create a HaruOutline instance
  • HaruDoc::getCurrentEncoder — Get HaruEncoder currently used in the document
  • HaruDoc::getCurrentPage — Return current page of the document
  • HaruDoc::getEncoder — Get HaruEncoder instance for the specified encoding
  • HaruDoc::getFont — Get HaruFont instance
  • HaruDoc::getInfoAttr — Get current value of the specified document attribute
  • HaruDoc::getPageLayout — Get current page layout
  • HaruDoc::getPageMode — Get current page mode
  • HaruDoc::getStreamSize — Get the size of the temporary stream
  • HaruDoc::insertPage — Insert new page just before the specified page
  • HaruDoc::loadJPEG — Load a JPEG image
  • HaruDoc::loadPNG — Load PNG image and return HaruImage instance
  • HaruDoc::loadRaw — Load a RAW image
  • HaruDoc::loadTTC — Load the font with the specified index from TTC file
  • HaruDoc::loadTTF — Load TTF font file
  • HaruDoc::loadType1 — Load Type1 font
  • HaruDoc::output — Write the document data to the output buffer
  • HaruDoc::readFromStream — Read data from the temporary stream
  • HaruDoc::resetError — Reset error state of the document handle
  • HaruDoc::resetStream — Rewind the temporary stream
  • HaruDoc::save — Save the document into the specified file
  • HaruDoc::saveToStream — Save the document into a temporary stream
  • HaruDoc::setCompressionMode — Set compression mode for the document
  • HaruDoc::setCurrentEncoder — Set the current encoder for the document
  • HaruDoc::setEncryptionMode — Set encryption mode for the document
  • HaruDoc::setInfoAttr — Set the info attribute of the document
  • HaruDoc::setInfoDateAttr — Set the datetime info attributes of the document
  • HaruDoc::setOpenAction — Define which page is shown when the document is opened
  • HaruDoc::setPageLayout — Set how pages should be displayed
  • HaruDoc::setPageMode — Set how the document should be displayed
  • HaruDoc::setPagesConfiguration — Set the number of pages per set of pages
  • HaruDoc::setPassword — Set owner and user passwords for the document
  • HaruDoc::setPermission — Set permissions for the document
  • HaruDoc::useCNSEncodings — Enable Chinese simplified encodings
  • HaruDoc::useCNSFonts — Enable builtin Chinese simplified fonts
  • HaruDoc::useCNTEncodings — Enable Chinese traditional encodings
  • HaruDoc::useCNTFonts — Enable builtin Chinese traditional fonts
  • HaruDoc::useJPEncodings — Enable Japanese encodings
  • HaruDoc::useJPFonts — Enable builtin Japanese fonts
  • HaruDoc::useKREncodings — Enable Korean encodings
  • HaruDoc::useKRFonts — Enable builtin Korean fonts


Add new page to the document

  • « HaruDoc
  • HaruDoc::addPageLabel »
  • PHP Manual
  • HaruDoc
  • Add new page to the document

HaruDoc::addPage

(PECL haru >= 0.0.1)

HaruDoc::addPage — Add new page to the document

Description

HaruDoc::addPage ( void ) : object

Adds a new page to the document.

Parameters

This function has no parameters.

Return Values

Returns a new HaruPage instance.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::insertPage() - Insert new page just before the specified page


Set the numbering style for the specified range of pages

  • « HaruDoc::addPage
  • HaruDoc::__construct »
  • PHP Manual
  • HaruDoc
  • Set the numbering style for the specified range of pages

HaruDoc::addPageLabel

(PECL haru >= 0.0.1)

HaruDoc::addPageLabel — Set the numbering style for the specified range of pages

Description

HaruDoc::addPageLabel ( int $first_page , int $style , int $first_num [, string $prefix = "" ] ) : bool

Set the numbering style for the specified range of pages.

Parameters

first_page

The first page included into the labeling range.

style

The numbering style. The following values are allowed:

  • HaruPage::NUM_STYLE_DECIMAL - page label is displayed using decimal numerals.
  • HaruPage::NUM_STYLE_UPPER_ROMAN - page label is displayed using uppercase Roman numerals.
  • HaruPage::NUM_STYLE_LOWER_ROMAN - page label is displayed using lowercase Roman numerals.
  • HaruPage::NUM_STYLE_UPPER_LETTER - page label is displayed using uppercase letters (from A to Z).
  • HaruPage::NUM_STYLE_LOWER_LETTERS - page label is displayed using lowercase letters (from a to z).

first_num

The first page number in this range.

prefix

The prefix for the page label.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Construct new HaruDoc instance

  • « HaruDoc::addPageLabel
  • HaruDoc::createOutline »
  • PHP Manual
  • HaruDoc
  • Construct new HaruDoc instance

HaruDoc::__construct

(PECL haru >= 0.0.1)

HaruDoc::__construct — Construct new HaruDoc instance

Description

HaruDoc::__construct ( void )

Constructs new HaruDoc instance.

Parameters

This function has no parameters.

Return Values

No value is returned.

Errors/Exceptions

Throws a HaruException on error.


Create a HaruOutline instance

  • « HaruDoc::__construct
  • HaruDoc::getCurrentEncoder »
  • PHP Manual
  • HaruDoc
  • Create a HaruOutline instance

HaruDoc::createOutline

(PECL haru >= 0.0.1)

HaruDoc::createOutline — Create a HaruOutline instance

Description

HaruDoc::createOutline ( string $title [, object $parent_outline [, object $encoder ]] ) : object

Create a HaruOutline instance.

Parameters

title

The caption of new outline object.

parent_outline

A valid HaruOutline instance or NULL.

encoder

A valid HaruEncoder instance or NULL.

Return Values

Returns a new HaruOutline instance.

Errors/Exceptions

Throws a HaruException on error.


Get HaruEncoder currently used in the document

  • « HaruDoc::createOutline
  • HaruDoc::getCurrentPage »
  • PHP Manual
  • HaruDoc
  • Get HaruEncoder currently used in the document

HaruDoc::getCurrentEncoder

(PECL haru >= 0.0.1)

HaruDoc::getCurrentEncoder — Get HaruEncoder currently used in the document

Description

HaruDoc::getCurrentEncoder ( void ) : object

Get the HaruEncoder currently used in the document.

Parameters

This function has no parameters.

Return Values

Returns HaruEncoder currently used in the document or FALSE if encoder is not set.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::setCurrentEncoder() - Set the current encoder for the document


Return current page of the document

  • « HaruDoc::getCurrentEncoder
  • HaruDoc::getEncoder »
  • PHP Manual
  • HaruDoc
  • Return current page of the document

HaruDoc::getCurrentPage

(PECL haru >= 0.0.1)

HaruDoc::getCurrentPage — Return current page of the document

Description

HaruDoc::getCurrentPage ( void ) : object

Get current page of the document.

Parameters

This function has no parameters.

Return Values

Returns HaruPage instance on success or FALSE if there is no current page at the moment.

Errors/Exceptions

Throws a HaruException on error.


Get HaruEncoder instance for the specified encoding

  • « HaruDoc::getCurrentPage
  • HaruDoc::getFont »
  • PHP Manual
  • HaruDoc
  • Get HaruEncoder instance for the specified encoding

HaruDoc::getEncoder

(PECL haru >= 0.0.1)

HaruDoc::getEncoder — Get HaruEncoder instance for the specified encoding

Description

HaruDoc::getEncoder ( string $encoding ) : object

Get the HaruEncoder instance for the specified encoding.

Parameters

encoding

The encoding name. See Builtin Encodings for the list of allowed values.

Return Values

Returns a HaruEncoder instance for the specified encoding.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::setCurrentEncoder() - Set the current encoder for the document
  • HaruDoc::getCurrentEncoder() - Get HaruEncoder currently used in the document


Get HaruFont instance

  • « HaruDoc::getEncoder
  • HaruDoc::getInfoAttr »
  • PHP Manual
  • HaruDoc
  • Get HaruFont instance

HaruDoc::getFont

(PECL haru >= 0.0.1)

HaruDoc::getFont — Get HaruFont instance

Description

HaruDoc::getFont ( string $fontname [, string $encoding ] ) : object

Get a HaruFont instance.

Parameters

fontname

The name of the font. See Builtin Fonts for the list of builtin fonts. You can also use the name of a font loaded via HaruDoc::loadTTF(), HaruDoc::loadTTC() and HaruDoc::loadType1().

encoding

The encoding to use. See Builtin Encodings for the list of supported encodings.

Return Values

Returns a HaruFont instance with the specified fontname and encoding.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setFontAndSize() - Set font and fontsize for the page
  • HaruPage::setCurrentFont()


Get current value of the specified document attribute

  • « HaruDoc::getFont
  • HaruDoc::getPageLayout »
  • PHP Manual
  • HaruDoc
  • Get current value of the specified document attribute

HaruDoc::getInfoAttr

(PECL haru >= 0.0.1)

HaruDoc::getInfoAttr — Get current value of the specified document attribute

Description

HaruDoc::getInfoAttr ( int $type ) : string

Get the current value of the specified document attribute.

Parameters

type

The type of the attribute. The following values are available:

  • HaruDoc::INFO_AUTHOR
  • HaruDoc::INFO_CREATOR
  • HaruDoc::INFO_TITLE
  • HaruDoc::INFO_SUBJECT
  • HaruDoc::INFO_KEYWORDS
  • HaruDoc::INFO_CREATION_DATE
  • HaruDoc::INFO_MOD_DATE

Return Values

Returns the string value of the specified document attribute.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::setInfoAttr() - Set the info attribute of the document
  • HaruDoc::setInfoDateAttr() - Set the datetime info attributes of the document


Get current page layout

  • « HaruDoc::getInfoAttr
  • HaruDoc::getPageMode »
  • PHP Manual
  • HaruDoc
  • Get current page layout

HaruDoc::getPageLayout

(PECL haru >= 0.0.1)

HaruDoc::getPageLayout — Get current page layout

Description

HaruDoc::getPageLayout ( void ) : int

Get the current page layout. See HaruDoc::setPageLayout() for the list of possible values.

Parameters

This function has no parameters.

Return Values

Returns the page layout currently set in the document or FALSE if page layout was not set. See HaruDoc::setPageLayout() for the list of possible values.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::setPageLayout() - Set how pages should be displayed


Get current page mode

  • « HaruDoc::getPageLayout
  • HaruDoc::getStreamSize »
  • PHP Manual
  • HaruDoc
  • Get current page mode

HaruDoc::getPageMode

(PECL haru >= 0.0.1)

HaruDoc::getPageMode — Get current page mode

Description

HaruDoc::getPageMode ( void ) : int

Get the current page mode. See HaruDoc::setPageMode() for the list of possible values.

Parameters

This function has no parameters.

Return Values

Returns the page mode currently set in the document. See HaruDoc::setPageMode() for the list of possible values.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::setPageMode() - Set how the document should be displayed


Get the size of the temporary stream

  • « HaruDoc::getPageMode
  • HaruDoc::insertPage »
  • PHP Manual
  • HaruDoc
  • Get the size of the temporary stream

HaruDoc::getStreamSize

(PECL haru >= 0.0.1)

HaruDoc::getStreamSize — Get the size of the temporary stream

Description

HaruDoc::getStreamSize ( void ) : int

Get the size of the temporary stream.

Parameters

This function has no parameters.

Return Values

Returns the size of the data in the temporary stream of the document. The size is zero if the document was not saved to the temporary stream.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::saveToStream() - Save the document into a temporary stream
  • HaruDoc::resetStream() - Rewind the temporary stream
  • HaruDoc::readFromStream() - Read data from the temporary stream


Insert new page just before the specified page

  • « HaruDoc::getStreamSize
  • HaruDoc::loadJPEG »
  • PHP Manual
  • HaruDoc
  • Insert new page just before the specified page

HaruDoc::insertPage

(PECL haru >= 0.0.1)

HaruDoc::insertPage — Insert new page just before the specified page

Description

HaruDoc::insertPage ( object $page ) : object

Creates a new page and inserts just before the specified page.

Parameters

page

A valid HaruPage instance.

Return Values

Returns a new HaruPage instance.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::addPage() - Add new page to the document


Load a JPEG image

  • « HaruDoc::insertPage
  • HaruDoc::loadPNG »
  • PHP Manual
  • HaruDoc
  • Load a JPEG image

HaruDoc::loadJPEG

(PECL haru >= 0.0.1)

HaruDoc::loadJPEG — Load a JPEG image

Description

HaruDoc::loadJPEG ( string $filename ) : object

Loads the specified JPEG image.

Parameters

filename

A valid JPEG image file.

Return Values

Returns a new HaruImage instance.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::loadPNG() - Load PNG image and return HaruImage instance
  • HaruDoc::loadRAW() - Load a RAW image


Load PNG image and return HaruImage instance

  • « HaruDoc::loadJPEG
  • HaruDoc::loadRaw »
  • PHP Manual
  • HaruDoc
  • Load PNG image and return HaruImage instance

HaruDoc::loadPNG

(PECL haru >= 0.0.1)

HaruDoc::loadPNG — Load PNG image and return HaruImage instance

Description

HaruDoc::loadPNG ( string $filename [, bool $deferred = FALSE ] ) : object

Loads a PNG image.

Libharu might be built without libpng support, in this case each call to this function would result in exception.

Parameters

filename

The name of a PNG image file.

deferred

Do not load data immediately. You can set deferred parameter to TRUE for deferred data loading, in this case only size and color are loaded immediately.

Return Values

Returns a HaruImage instance.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::loadJPEG() - Load a JPEG image
  • HaruDoc::loadRAW() - Load a RAW image


Load a RAW image

  • « HaruDoc::loadPNG
  • HaruDoc::loadTTC »
  • PHP Manual
  • HaruDoc
  • Load a RAW image

HaruDoc::loadRaw

(PECL haru >= 0.0.1)

HaruDoc::loadRaw — Load a RAW image

Description

HaruDoc::loadRaw ( string $filename , int $width , int $height , int $color_space ) : object

Loads a RAW image.

Parameters

filename

The name of a RAW image file.

width

The width of the image.

height

The height of the image.

color_space

The color space of the image. Can be one of the following values:

  • HaruDoc::CS_DEVICE_GRAY
  • HaruDoc::CS_DEVICE_RGB
  • HaruDoc::CS_DEVICE_CMYK

Return Values

Returns a HaruImage instance.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::loadJPEG() - Load a JPEG image
  • HaruDoc::loadPNG() - Load PNG image and return HaruImage instance


Load the font with the specified index from TTC file

  • « HaruDoc::loadRaw
  • HaruDoc::loadTTF »
  • PHP Manual
  • HaruDoc
  • Load the font with the specified index from TTC file

HaruDoc::loadTTC

(PECL haru >= 0.0.1)

HaruDoc::loadTTC — Load the font with the specified index from TTC file

Description

HaruDoc::loadTTC ( string $fontfile , int $index [, bool $embed = FALSE ] ) : string

Loads the TrueType font with the specified index from a TrueType collection file.

Parameters

fontfile

The TrueType collection file.

index

The index of the font in the collection file.

embed

When set to TRUE, the glyph data of the font is embedded into the PDF file, otherwise only the matrix data is included.

Return Values

Returns the name of the loaded font on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::loadTTF() - Load TTF font file
  • HaruDoc::loadType1() - Load Type1 font


Load TTF font file

  • « HaruDoc::loadTTC
  • HaruDoc::loadType1 »
  • PHP Manual
  • HaruDoc
  • Load TTF font file

HaruDoc::loadTTF

(PECL haru >= 0.0.1)

HaruDoc::loadTTF — Load TTF font file

Description

HaruDoc::loadTTF ( string $fontfile [, bool $embed = FALSE ] ) : string

Loads the given TTF file and (optionally) embed its data into the document.

Parameters

fontfile

The TTF file to load.

embed

When set to TRUE, the glyph data of the font is embedded into the PDF file, otherwise only the matrix data is included.

Return Values

Returns the name of the loaded font on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::loadTTC() - Load the font with the specified index from TTC file
  • HaruDoc::loadType1() - Load Type1 font


Load Type1 font

  • « HaruDoc::loadTTF
  • HaruDoc::output »
  • PHP Manual
  • HaruDoc
  • Load Type1 font

HaruDoc::loadType1

(PECL haru >= 0.0.1)

HaruDoc::loadType1 — Load Type1 font

Description

HaruDoc::loadType1 ( string $afmfile [, string $pfmfile ] ) : string

Loads Type1 font from the given file and registers it in the PDF document.

Parameters

afmfile

Path to an AFM file.

pfmfile

Path to a PFA/PFB file, optional. If it's not set only the glyph data of the font is embedded into the PDF document.

Return Values

Returns the name of the loaded font on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::loadTTC() - Load the font with the specified index from TTC file
  • HaruDoc::loadTTF() - Load TTF font file


Write the document data to the output buffer

  • « HaruDoc::loadType1
  • HaruDoc::readFromStream »
  • PHP Manual
  • HaruDoc
  • Write the document data to the output buffer

HaruDoc::output

(PECL haru >= 0.0.1)

HaruDoc::output — Write the document data to the output buffer

Description

HaruDoc::output ( void ) : bool

Writes the document data into standard output.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::save() - Save the document into the specified file


Read data from the temporary stream

  • « HaruDoc::output
  • HaruDoc::resetError »
  • PHP Manual
  • HaruDoc
  • Read data from the temporary stream

HaruDoc::readFromStream

(PECL haru >= 0.0.1)

HaruDoc::readFromStream — Read data from the temporary stream

Description

HaruDoc::readFromStream ( int $bytes ) : string

Read data from the temporary stream.

Parameters

bytes

The bytes parameter specifies how many bytes to read, though the stream may contain less bytes than requested.

Return Values

Returns data from the temporary stream.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::saveToStream() - Save the document into a temporary stream
  • HaruDoc::resetStream() - Rewind the temporary stream
  • HaruDoc::getStreamSize() - Get the size of the temporary stream


Reset error state of the document handle

  • « HaruDoc::readFromStream
  • HaruDoc::resetStream »
  • PHP Manual
  • HaruDoc
  • Reset error state of the document handle

HaruDoc::resetError

(PECL haru >= 0.0.1)

HaruDoc::resetError — Reset error state of the document handle

Description

HaruDoc::resetError ( void ) : bool

Once an error code is set, most of the operations, including I/O processing functions cannot be performed. In case if you want to continue after the cause of the error has been fixed, you have to invoke this function in order to reset the document error state.

Parameters

This function has no parameters.

Return Values

Always succeeds and returns TRUE.


Rewind the temporary stream

  • « HaruDoc::resetError
  • HaruDoc::save »
  • PHP Manual
  • HaruDoc
  • Rewind the temporary stream

HaruDoc::resetStream

(PECL haru >= 0.0.1)

HaruDoc::resetStream — Rewind the temporary stream

Description

HaruDoc::resetStream ( void ) : bool

Rewinds the temporary stream of the document.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::saveToStream() - Save the document into a temporary stream
  • HaruDoc::getStreamSize() - Get the size of the temporary stream
  • HaruDoc::readFromStream() - Read data from the temporary stream


Save the document into the specified file

  • « HaruDoc::resetStream
  • HaruDoc::saveToStream »
  • PHP Manual
  • HaruDoc
  • Save the document into the specified file

HaruDoc::save

(PECL haru >= 0.0.1)

HaruDoc::save — Save the document into the specified file

Description

HaruDoc::save ( string $file ) : bool

Saves the document into the specified file.

Parameters

file

The file to save the document to.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::output() - Write the document data to the output buffer


Save the document into a temporary stream

  • « HaruDoc::save
  • HaruDoc::setCompressionMode »
  • PHP Manual
  • HaruDoc
  • Save the document into a temporary stream

HaruDoc::saveToStream

(PECL haru >= 0.0.1)

HaruDoc::saveToStream — Save the document into a temporary stream

Description

HaruDoc::saveToStream ( void ) : bool

Saves the document data into a temporary stream.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::resetStream() - Rewind the temporary stream
  • HaruDoc::getStreamSize() - Get the size of the temporary stream
  • HaruDoc::readFromStream() - Read data from the temporary stream


Set compression mode for the document

  • « HaruDoc::saveToStream
  • HaruDoc::setCurrentEncoder »
  • PHP Manual
  • HaruDoc
  • Set compression mode for the document

HaruDoc::setCompressionMode

(PECL haru >= 0.0.1)

HaruDoc::setCompressionMode — Set compression mode for the document

Description

HaruDoc::setCompressionMode ( int $mode ) : bool

Defines compression mode for the document. In case when libharu was compiled without Zlib support this function will always throw HaruException.

Parameters

mode

The compression mode to use. The value is a combination of the following flags:

  • HaruDoc::COMP_NONE - all contents is not compressed.
  • HaruDoc::COMP_TEXT - compress the text data.
  • HaruDoc::COMP_IMAGE - compress the image data.
  • HaruDoc::COMP_METADATA - compress other data (fonts, cmaps).
  • HaruDoc::COMP_ALL - compress all data.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Set the current encoder for the document

  • « HaruDoc::setCompressionMode
  • HaruDoc::setEncryptionMode »
  • PHP Manual
  • HaruDoc
  • Set the current encoder for the document

HaruDoc::setCurrentEncoder

(PECL haru >= 0.0.1)

HaruDoc::setCurrentEncoder — Set the current encoder for the document

Description

HaruDoc::setCurrentEncoder ( string $encoding ) : bool

Defines the encoder currently used in the document.

Parameters

encoding

The name of the encoding to use. See Builtin Encodings for the list of allowed values.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Set encryption mode for the document

  • « HaruDoc::setCurrentEncoder
  • HaruDoc::setInfoAttr »
  • PHP Manual
  • HaruDoc
  • Set encryption mode for the document

HaruDoc::setEncryptionMode

(PECL haru >= 0.0.1)

HaruDoc::setEncryptionMode — Set encryption mode for the document

Description

HaruDoc::setEncryptionMode ( int $mode [, int $key_len = 5 ] ) : bool

Defines encryption mode for the document. The encryption mode cannot be set before setting the password.

Parameters

mode

The encryption mode to use. Can be one of the following:

  • HaruDoc::ENCRYPT_R2 - use "revision2" algorithm.
  • HaruDoc::ENCRYPT_R3 - use "revision3" algorithm. Using this value bumps the version of PDF to 1.4.

key_len

The encryption key length in bytes. This parameter is optional and used only when mode is HaruDoc::ENCRYPT_R3. The default value is 5 (40bit).

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::setPassword() - Set owner and user passwords for the document
  • HaruDoc::setPermission() - Set permissions for the document


Set the info attribute of the document

  • « HaruDoc::setEncryptionMode
  • HaruDoc::setInfoDateAttr »
  • PHP Manual
  • HaruDoc
  • Set the info attribute of the document

HaruDoc::setInfoAttr

(PECL haru >= 0.0.1)

HaruDoc::setInfoAttr — Set the info attribute of the document

Description

HaruDoc::setInfoAttr ( int $type , string $info ) : bool

Defines an info attribute. Uses the current encoding of the document.

Parameters

type

The type of the attribute. Can be one of the following:

  • HaruDoc::INFO_AUTHOR
  • HaruDoc::INFO_CREATOR
  • HaruDoc::INFO_TITLE
  • HaruDoc::INFO_SUBJECT
  • HaruDoc::INFO_KEYWORDS

info

The value of the attribute.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::setInfoDateAttr() - Set the datetime info attributes of the document


Set the datetime info attributes of the document

  • « HaruDoc::setInfoAttr
  • HaruDoc::setOpenAction »
  • PHP Manual
  • HaruDoc
  • Set the datetime info attributes of the document

HaruDoc::setInfoDateAttr

(PECL haru >= 0.0.1)

HaruDoc::setInfoDateAttr — Set the datetime info attributes of the document

Description

HaruDoc::setInfoDateAttr ( int $type , int $year , int $month , int $day , int $hour , int $min , int $sec , string $ind , int $off_hour , int $off_min ) : bool

Sets the datetime info attributes of the document.

Parameters

type

The type of the attribute. Can be one of the following:

  • HaruDoc::INFO_CREATION_DATE
  • HaruDoc::INFO_MOD_DATE

year

month

Between 1 and 12.

day

Between 1 and 31, 30, 29 or 28 (different for each month).

hour

Between 0 and 23.

min

Between 0 and 59.

sec

Between 0 and 59.

ind

The timezone relation to UTC, can be "", " ", "+", "-" and "Z".

off_hour

If ind is not " " or "", values between 0 and 23 are valid. Otherwise, this parameter is ignored.

off_min

If ind is not " " or "", values between 0 and 59 are valid. Otherwise, this parameter is ignored.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::setInfoAttr() - Set the info attribute of the document


Define which page is shown when the document is opened

  • « HaruDoc::setInfoDateAttr
  • HaruDoc::setPageLayout »
  • PHP Manual
  • HaruDoc
  • Define which page is shown when the document is opened

HaruDoc::setOpenAction

(PECL haru >= 0.0.1)

HaruDoc::setOpenAction — Define which page is shown when the document is opened

Description

HaruDoc::setOpenAction ( object $destination ) : bool

Defines which page should be shown when the document is opened.

Parameters

destination

A valid HaruDestination instance.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Set how pages should be displayed

  • « HaruDoc::setOpenAction
  • HaruDoc::setPageMode »
  • PHP Manual
  • HaruDoc
  • Set how pages should be displayed

HaruDoc::setPageLayout

(PECL haru >= 0.0.1)

HaruDoc::setPageLayout — Set how pages should be displayed

Description

HaruDoc::setPageLayout ( int $layout ) : bool

Defines how pages should be displayed.

Parameters

layout

The following values are accepted:

  • HaruDoc::PAGE_LAYOUT_SINGLE - only one page is displayed.
  • HaruDoc::PAGE_LAYOUT_ONE_COLUMN - display the pages in one column.
  • HaruDoc::PAGE_LAYOUT_TWO_COLUMN_LEFT - display pages in two columns, first page left.
  • HaruDoc::PAGE_LAYOUT_TWO_COLUMN_RIGHT - display pages in two columns, first page right.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::getPageLayout() - Get current page layout


Set how the document should be displayed

  • « HaruDoc::setPageLayout
  • HaruDoc::setPagesConfiguration »
  • PHP Manual
  • HaruDoc
  • Set how the document should be displayed

HaruDoc::setPageMode

(PECL haru >= 0.0.1)

HaruDoc::setPageMode — Set how the document should be displayed

Description

HaruDoc::setPageMode ( int $mode ) : bool

Defines how the document should be displayed.

Parameters

mode

The following values are accepted:

  • HaruDoc::PAGE_MODE_USE_NONE - display the document with neither outline nor thumbnail.
  • HaruDoc::PAGE_MODE_USE_OUTLINE - display the document with outline pane.
  • HaruDoc::PAGE_MODE_USE_THUMBS - display the document with thumbnail pane.
  • HaruDoc::PAGE_MODE_FULL_SCREEN - display the document with full screen mode.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::getPageMode() - Get current page mode


Set the number of pages per set of pages

  • « HaruDoc::setPageMode
  • HaruDoc::setPassword »
  • PHP Manual
  • HaruDoc
  • Set the number of pages per set of pages

HaruDoc::setPagesConfiguration

(PECL haru >= 0.0.1)

HaruDoc::setPagesConfiguration — Set the number of pages per set of pages

Description

HaruDoc::setPagesConfiguration ( int $page_per_pages ) : bool

By default the document has one pages object as a root for all pages. All page objects are create as branches of this object. One pages object can contain only 8191, therefore the maximum number of pages per document is 8191. But you can change that fact by setting page_per_pages parameter, so that the root pages object contains 8191 more pages (not page) objects, which in turn contain 8191 pages each. So the maximum number of pages in the document becomes 8191*page_per_pages.

Parameters

page_per_pages

The numbers of pages that a pages object can contain.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Set owner and user passwords for the document

  • « HaruDoc::setPagesConfiguration
  • HaruDoc::setPermission »
  • PHP Manual
  • HaruDoc
  • Set owner and user passwords for the document

HaruDoc::setPassword

(PECL haru >= 0.0.1)

HaruDoc::setPassword — Set owner and user passwords for the document

Description

HaruDoc::setPassword ( string $owner_password , string $user_password ) : bool

Defines owner and user passwords for the document. Setting the passwords makes the document contents encrypted.

Parameters

owner_password

The password of the owner, which can change permissions of the document. Empty password is not accepted. Owner's password cannot be the same as the user's password.

user_password

The password of the user. Can be empty.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::setEncryptionMode() - Set encryption mode for the document
  • HaruDoc::setPermission() - Set permissions for the document


Set permissions for the document

  • « HaruDoc::setPassword
  • HaruDoc::useCNSEncodings »
  • PHP Manual
  • HaruDoc
  • Set permissions for the document

HaruDoc::setPermission

(PECL haru >= 0.0.1)

HaruDoc::setPermission — Set permissions for the document

Description

HaruDoc::setPermission ( int $permission ) : bool

Defines permissions for the document.

Parameters

permission

The values is a combination of these flags:

  • HaruDoc::ENABLE_READ - user can read the document.
  • HaruDoc::ENABLE_PRINT - user can print the document.
  • HaruDoc::ENABLE_EDIT_ALL - user can edit the contents of the document other than annotations and form fields.
  • HaruDoc::ENABLE_COPY - user can copy the text and the graphics of the document.
  • HaruDoc::ENABLE_EDIT - user can add or modify the annotations and form fields of the document.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::setPassword() - Set owner and user passwords for the document
  • HaruDoc::setEncryptionMode() - Set encryption mode for the document


Enable Chinese simplified encodings

  • « HaruDoc::setPermission
  • HaruDoc::useCNSFonts »
  • PHP Manual
  • HaruDoc
  • Enable Chinese simplified encodings

HaruDoc::useCNSEncodings

(PECL haru >= 0.0.1)

HaruDoc::useCNSEncodings — Enable Chinese simplified encodings

Description

HaruDoc::useCNSEncodings ( void ) : bool

Enables Chinese simplified encodings.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::useCNSFonts() - Enable builtin Chinese simplified fonts


Enable builtin Chinese simplified fonts

  • « HaruDoc::useCNSEncodings
  • HaruDoc::useCNTEncodings »
  • PHP Manual
  • HaruDoc
  • Enable builtin Chinese simplified fonts

HaruDoc::useCNSFonts

(PECL haru >= 0.0.1)

HaruDoc::useCNSFonts — Enable builtin Chinese simplified fonts

Description

HaruDoc::useCNSFonts ( void ) : bool

Enables builtin Chinese simplified fonts.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::useCNSEncodings() - Enable Chinese simplified encodings


Enable Chinese traditional encodings

  • « HaruDoc::useCNSFonts
  • HaruDoc::useCNTFonts »
  • PHP Manual
  • HaruDoc
  • Enable Chinese traditional encodings

HaruDoc::useCNTEncodings

(PECL haru >= 0.0.1)

HaruDoc::useCNTEncodings — Enable Chinese traditional encodings

Description

HaruDoc::useCNTEncodings ( void ) : bool

Enables Chinese traditional encodings.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::useCNTFonts() - Enable builtin Chinese traditional fonts


Enable builtin Chinese traditional fonts

  • « HaruDoc::useCNTEncodings
  • HaruDoc::useJPEncodings »
  • PHP Manual
  • HaruDoc
  • Enable builtin Chinese traditional fonts

HaruDoc::useCNTFonts

(PECL haru >= 0.0.1)

HaruDoc::useCNTFonts — Enable builtin Chinese traditional fonts

Description

HaruDoc::useCNTFonts ( void ) : bool

Enables builtin Chinese traditional fonts.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::useCNTEncodings() - Enable Chinese traditional encodings


Enable Japanese encodings

  • « HaruDoc::useCNTFonts
  • HaruDoc::useJPFonts »
  • PHP Manual
  • HaruDoc
  • Enable Japanese encodings

HaruDoc::useJPEncodings

(PECL haru >= 0.0.1)

HaruDoc::useJPEncodings — Enable Japanese encodings

Description

HaruDoc::useJPEncodings ( void ) : bool

Enables Japanese encodings.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::useJPFonts() - Enable builtin Japanese fonts


Enable builtin Japanese fonts

  • « HaruDoc::useJPEncodings
  • HaruDoc::useKREncodings »
  • PHP Manual
  • HaruDoc
  • Enable builtin Japanese fonts

HaruDoc::useJPFonts

(PECL haru >= 0.0.1)

HaruDoc::useJPFonts — Enable builtin Japanese fonts

Description

HaruDoc::useJPFonts ( void ) : bool

Enables builtin Japanese fonts.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::useJPEncodings() - Enable Japanese encodings


Enable Korean encodings

  • « HaruDoc::useJPFonts
  • HaruDoc::useKRFonts »
  • PHP Manual
  • HaruDoc
  • Enable Korean encodings

HaruDoc::useKREncodings

(PECL haru >= 0.0.1)

HaruDoc::useKREncodings — Enable Korean encodings

Description

HaruDoc::useKREncodings ( void ) : bool

Enables Korean encodings.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::useKRFonts() - Enable builtin Korean fonts


Enable builtin Korean fonts

  • « HaruDoc::useKREncodings
  • HaruPage »
  • PHP Manual
  • HaruDoc
  • Enable builtin Korean fonts

HaruDoc::useKRFonts

(PECL haru >= 0.0.1)

HaruDoc::useKRFonts — Enable builtin Korean fonts

Description

HaruDoc::useKRFonts ( void ) : bool

Enables builtin Korean fonts.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::useKREncodings() - Enable Korean encodings


The HaruPage class

(PECL haru >= 0.0.1)

Introduction

Haru PDF Page Class.

Class synopsis

HaruPage {
/* Methods */
arc ( float $x , float $y , float $ray , float $ang1 , float $ang2 ) : bool
beginText ( void ) : bool
circle ( float $x , float $y , float $ray ) : bool
closePath ( void ) : bool
concat ( float $a , float $b , float $c , float $d , float $x , float $y ) : bool
createDestination ( void ) : object
createLinkAnnotation ( array $rectangle , object $destination ) : object
createTextAnnotation ( array $rectangle , string $text [, object $encoder ] ) : object
createURLAnnotation ( array $rectangle , string $url ) : object
curveTo2 ( float $x2 , float $y2 , float $x3 , float $y3 ) : bool
curveTo3 ( float $x1 , float $y1 , float $x3 , float $y3 ) : bool
curveTo ( float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 ) : bool
drawImage ( object $image , float $x , float $y , float $width , float $height ) : bool
ellipse ( float $x , float $y , float $xray , float $yray ) : bool
endPath ( void ) : bool
endText ( void ) : bool
eofill ( void ) : bool
eoFillStroke ([ bool $close_path = FALSE ] ) : bool
fill ( void ) : bool
fillStroke ([ bool $close_path = FALSE ] ) : bool
getCharSpace ( void ) : float
getCMYKFill ( void ) : array
getCMYKStroke ( void ) : array
getCurrentFont ( void ) : object
getCurrentFontSize ( void ) : float
getCurrentPos ( void ) : array
getCurrentTextPos ( void ) : array
getDash ( void ) : array
getFillingColorSpace ( void ) : int
getFlatness ( void ) : float
getGMode ( void ) : int
getGrayFill ( void ) : float
getGrayStroke ( void ) : float
getHeight ( void ) : float
getHorizontalScaling ( void ) : float
getLineCap ( void ) : int
getLineJoin ( void ) : int
getLineWidth ( void ) : float
getMiterLimit ( void ) : float
getRGBFill ( void ) : array
getRGBStroke ( void ) : array
getStrokingColorSpace ( void ) : int
getTextLeading ( void ) : float
getTextMatrix ( void ) : array
getTextRenderingMode ( void ) : int
getTextRise ( void ) : float
getTextWidth ( string $text ) : float
getTransMatrix ( void ) : array
getWidth ( void ) : float
getWordSpace ( void ) : float
lineTo ( float $x , float $y ) : bool
measureText ( string $text , float $width [, bool $wordwrap = FALSE ] ) : int
moveTextPos ( float $x , float $y [, bool $set_leading = FALSE ] ) : bool
moveTo ( float $x , float $y ) : bool
moveToNextLine ( void ) : bool
rectangle ( float $x , float $y , float $width , float $height ) : bool
setCharSpace ( float $char_space ) : bool
setCMYKFill ( float $c , float $m , float $y , float $k ) : bool
setCMYKStroke ( float $c , float $m , float $y , float $k ) : bool
setDash ( array $pattern , int $phase ) : bool
setFlatness ( float $flatness ) : bool
setFontAndSize ( object $font , float $size ) : bool
setGrayFill ( float $value ) : bool
setGrayStroke ( float $value ) : bool
setHeight ( float $height ) : bool
setHorizontalScaling ( float $scaling ) : bool
setLineCap ( int $cap ) : bool
setLineJoin ( int $join ) : bool
setLineWidth ( float $width ) : bool
setMiterLimit ( float $limit ) : bool
setRGBFill ( float $r , float $g , float $b ) : bool
setRGBStroke ( float $r , float $g , float $b ) : bool
setRotate ( int $angle ) : bool
setSize ( int $size , int $direction ) : bool
setSlideShow ( int $type , float $disp_time , float $trans_time ) : bool
setTextLeading ( float $text_leading ) : bool
setTextMatrix ( float $a , float $b , float $c , float $d , float $x , float $y ) : bool
setTextRenderingMode ( int $mode ) : bool
setTextRise ( float $rise ) : bool
setWidth ( float $width ) : bool
setWordSpace ( float $word_space ) : bool
showText ( string $text ) : bool
showTextNextLine ( string $text [, float $word_space = 0 [, float $char_space = 0 ]] ) : bool
stroke ([ bool $close_path = FALSE ] ) : bool
textOut ( float $x , float $y , string $text ) : bool
textRect ( float $left , float $top , float $right , float $bottom , string $text [, int $align = HaruPage::TALIGN_LEFT ] ) : bool
}

Predefined Constants

Type | Name | Description
int | HaruPage::GMODE_PAGE_DESCRIPTION |
int | HaruPage::GMODE_TEXT_OBJECT |
int | HaruPage::GMODE_PATH_OBJECT |
int | HaruPage::GMODE_CLIPPING_PATH |
int | HaruPage::GMODE_SHADING |
int | HaruPage::GMODE_INLINE_IMAGE |
int | HaruPage::GMODE_EXTERNAL_OBJECT |
int | HaruPage::BUTT_END |
int | HaruPage::ROUND_END |
int | HaruPage::PROJECTING_SCUARE_END |
int | HaruPage::MITER_JOIN |
int | HaruPage::ROUND_JOIN |
int | HaruPage::BEVEL_JOIN |
int | HaruPage::FILL |
int | HaruPage::STROKE |
int | HaruPage::FILL_THEN_STROKE |
int | HaruPage::INVISIBLE |
int | HaruPage::FILL_CLIPPING |
int | HaruPage::STROKE_CLIPPING |
int | HaruPage::FILL_STROKE_CLIPPING |
int | HaruPage::CLIPPING |
int | HaruPage::TALIGN_LEFT |
int | HaruPage::TALIGN_RIGHT |
int | HaruPage::TALIGN_CENTER |
int | HaruPage::TALIGN_JUSTIFY |
int | HaruPage::SIZE_LETTER |
int | HaruPage::SIZE_LEGAL |
int | HaruPage::SIZE_A3 |
int | HaruPage::SIZE_A4 |
int | HaruPage::SIZE_A5 |
int | HaruPage::SIZE_B4 |
int | HaruPage::SIZE_B5 |
int | HaruPage::SIZE_EXECUTIVE |
int | HaruPage::SIZE_US4x6 |
int | HaruPage::SIZE_US4x8 |
int | HaruPage::SIZE_US5x7 |
int | HaruPage::SIZE_COMM10 |
int | HaruPage::PORTRAIT |
int | HaruPage::LANDSCAPE |
int | HaruPage::TS_WIPE_LIGHT |
int | HaruPage::TS_WIPE_UP |
int | HaruPage::TS_WIPE_LEFT |
int | HaruPage::TS_WIPE_DOWN |
int | HaruPage::TS_BARN_DOORS_HORIZONTAL_OUT |
int | HaruPage::TS_BARN_DOORS_HORIZONTAL_IN |
int | HaruPage::TS_BARN_DOORS_VERTICAL_OUT |
int | HaruPage::TS_BARN_DOORS_VERTICAL_IN |
int | HaruPage::TS_BOX_OUT |
int | HaruPage::TS_BOX_IN |
int | HaruPage::TS_BLINDS_HORIZONTAL |
int | HaruPage::TS_BLINDS_VERTICAL |
int | HaruPage::TS_DISSOLVE |
int | HaruPage::TS_GLITTER_RIGHT |
int | HaruPage::TS_GLITTER_DOWN |
int | HaruPage::TS_GLITTER_TOP_LEFT_TO_BOTTOM_RIGHT |
int | HaruPage::TS_REPLACE |
int | HaruPage::NUM_STYLE_DECIMAL |
int | HaruPage::NUM_STYLE_UPPER_ROMAN |
int | HaruPage::NUM_STYLE_LOWER_ROMAN |
int | HaruPage::NUM_STYLE_UPPER_LETTERS |
int | HaruPage::NUM_STYLE_LOWER_LETTERS |

Table of Contents

  • HaruPage::arc — Append an arc to the current path
  • HaruPage::beginText — Begin a text object and set the current text position to (0,0)
  • HaruPage::circle — Append a circle to the current path
  • HaruPage::closePath — Append a straight line from the current point to the start point of the path
  • HaruPage::concat — Concatenate current transformation matrix of the page and the specified matrix
  • HaruPage::createDestination — Create new HaruDestination instance
  • HaruPage::createLinkAnnotation — Create new HaruAnnotation instance
  • HaruPage::createTextAnnotation — Create new HaruAnnotation instance
  • HaruPage::createURLAnnotation — Create and return new HaruAnnotation instance
  • HaruPage::curveTo2 — Append a Bezier curve to the current path
  • HaruPage::curveTo3 — Append a Bezier curve to the current path
  • HaruPage::curveTo — Append a Bezier curve to the current path
  • HaruPage::drawImage — Show image at the page
  • HaruPage::ellipse — Append an ellipse to the current path
  • HaruPage::endPath — End current path object without filling and painting operations
  • HaruPage::endText — End current text object
  • HaruPage::eofill — Fill current path using even-odd rule
  • HaruPage::eoFillStroke — Fill current path using even-odd rule, then paint the path
  • HaruPage::fill — Fill current path using nonzero winding number rule
  • HaruPage::fillStroke — Fill current path using nonzero winding number rule, then paint the path
  • HaruPage::getCharSpace — Get the current value of character spacing
  • HaruPage::getCMYKFill — Get the current filling color
  • HaruPage::getCMYKStroke — Get the current stroking color
  • HaruPage::getCurrentFont — Get the currently used font
  • HaruPage::getCurrentFontSize — Get the current font size
  • HaruPage::getCurrentPos — Get the current position for path painting
  • HaruPage::getCurrentTextPos — Get the current position for text printing
  • HaruPage::getDash — Get the current dash pattern
  • HaruPage::getFillingColorSpace — Get the current filling color space
  • HaruPage::getFlatness — Get the flatness of the page
  • HaruPage::getGMode — Get the current graphics mode
  • HaruPage::getGrayFill — Get the current filling color
  • HaruPage::getGrayStroke — Get the current stroking color
  • HaruPage::getHeight — Get the height of the page
  • HaruPage::getHorizontalScaling — Get the current value of horizontal scaling
  • HaruPage::getLineCap — Get the current line cap style
  • HaruPage::getLineJoin — Get the current line join style
  • HaruPage::getLineWidth — Get the current line width
  • HaruPage::getMiterLimit — Get the value of miter limit
  • HaruPage::getRGBFill — Get the current filling color
  • HaruPage::getRGBStroke — Get the current stroking color
  • HaruPage::getStrokingColorSpace — Get the current stroking color space
  • HaruPage::getTextLeading — Get the current value of line spacing
  • HaruPage::getTextMatrix — Get the current text transformation matrix of the page
  • HaruPage::getTextRenderingMode — Get the current text rendering mode
  • HaruPage::getTextRise — Get the current value of text rising
  • HaruPage::getTextWidth — Get the width of the text using current fontsize, character spacing and word spacing
  • HaruPage::getTransMatrix — Get the current transformation matrix of the page
  • HaruPage::getWidth — Get the width of the page
  • HaruPage::getWordSpace — Get the current value of word spacing
  • HaruPage::lineTo — Draw a line from the current point to the specified point
  • HaruPage::measureText — Calculate the byte length of characters which can be included on one line of the specified width
  • HaruPage::moveTextPos — Move text position to the specified offset
  • HaruPage::moveTo — Set starting point for new drawing path
  • HaruPage::moveToNextLine — Move text position to the start of the next line
  • HaruPage::rectangle — Append a rectangle to the current path
  • HaruPage::setCharSpace — Set character spacing for the page
  • HaruPage::setCMYKFill — Set filling color for the page
  • HaruPage::setCMYKStroke — Set stroking color for the page
  • HaruPage::setDash — Set the dash pattern for the page
  • HaruPage::setFlatness — Set flatness for the page
  • HaruPage::setFontAndSize — Set font and fontsize for the page
  • HaruPage::setGrayFill — Set filling color for the page
  • HaruPage::setGrayStroke — Sets stroking color for the page
  • HaruPage::setHeight — Set height of the page
  • HaruPage::setHorizontalScaling — Set horizontal scaling for the page
  • HaruPage::setLineCap — Set the shape to be used at the ends of lines
  • HaruPage::setLineJoin — Set line join style for the page
  • HaruPage::setLineWidth — Set line width for the page
  • HaruPage::setMiterLimit — Set the current value of the miter limit of the page
  • HaruPage::setRGBFill — Set filling color for the page
  • HaruPage::setRGBStroke — Set stroking color for the page
  • HaruPage::setRotate — Set rotation angle of the page
  • HaruPage::setSize — Set size and direction of the page
  • HaruPage::setSlideShow — Set transition style for the page
  • HaruPage::setTextLeading — Set text leading (line spacing) for the page
  • HaruPage::setTextMatrix — Set the current text transformation matrix of the page
  • HaruPage::setTextRenderingMode — Set text rendering mode for the page
  • HaruPage::setTextRise — Set the current value of text rising
  • HaruPage::setWidth — Set width of the page
  • HaruPage::setWordSpace — Set word spacing for the page
  • HaruPage::showText — Print text at the current position of the page
  • HaruPage::showTextNextLine — Move the current position to the start of the next line and print the text
  • HaruPage::stroke — Paint current path
  • HaruPage::textOut — Print the text on the specified position
  • HaruPage::textRect — Print the text inside the specified region


Append an arc to the current path

  • « HaruPage
  • HaruPage::beginText »
  • PHP Manual
  • HaruPage
  • Append an arc to the current path

HaruPage::arc

(PECL haru >= 0.0.1)

HaruPage::arc — Append an arc to the current path

Description

HaruPage::arc ( float $x , float $y , float $ray , float $ang1 , float $ang2 ) : bool

Appends an arc to the current path.

Parameters

x

Horizontal coordinate of the center.

y

Vertical coordinate of the center.

ray

The ray of the arc.

ang1

The angle of the beginning.

ang2

The angle of the end. Must be greater than ang1.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Begin a text object and set the current text position to (0,0)

  • « HaruPage::arc
  • HaruPage::circle »
  • PHP Manual
  • HaruPage
  • Begin a text object and set the current text position to (0,0)

HaruPage::beginText

(PECL haru >= 0.0.1)

HaruPage::beginText — Begin a text object and set the current text position to (0,0)

Description

HaruPage::beginText ( void ) : bool

Begins new text object and sets the current text position to (0,0).

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Append a circle to the current path

  • « HaruPage::beginText
  • HaruPage::closePath »
  • PHP Manual
  • HaruPage
  • Append a circle to the current path

HaruPage::circle

(PECL haru >= 0.0.1)

HaruPage::circle — Append a circle to the current path

Description

HaruPage::circle ( float $x , float $y , float $ray ) : bool

Appends a circle to the current path.

Parameters

x

Horizontal coordinate of the center point.

y

Vertical coordinate of the center point.

ray

The ray of the circle.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Append a straight line from the current point to the start point of the path

  • « HaruPage::circle
  • HaruPage::concat »
  • PHP Manual
  • HaruPage
  • Append a straight line from the current point to the start point of the path

HaruPage::closePath

(PECL haru >= 0.0.1)

HaruPage::closePath — Append a straight line from the current point to the start point of the path

Description

HaruPage::closePath ( void ) : bool

Appends a straight line from the current point to the start point of the path.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Concatenate current transformation matrix of the page and the specified matrix

  • « HaruPage::closePath
  • HaruPage::createDestination »
  • PHP Manual
  • HaruPage
  • Concatenate current transformation matrix of the page and the specified matrix

HaruPage::concat

(PECL haru >= 0.0.1)

HaruPage::concat — Concatenate current transformation matrix of the page and the specified matrix

Description

HaruPage::concat ( float $a , float $b , float $c , float $d , float $x , float $y ) : bool

Concatenates current transformation matrix of the page and the specified matrix.

Parameters

a

b

c

d

x

y

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Create new HaruDestination instance

  • « HaruPage::concat
  • HaruPage::createLinkAnnotation »
  • PHP Manual
  • HaruPage
  • Create new HaruDestination instance

HaruPage::createDestination

(PECL haru >= 0.0.1)

HaruPage::createDestination — Create new HaruDestination instance

Description

HaruPage::createDestination ( void ) : object

Create a new HaruDestination instance.

Parameters

This function has no parameters.

Return Values

Returns a new HaruDestination instance.

Errors/Exceptions

Throws a HaruException on error.


Create new HaruAnnotation instance

  • « HaruPage::createDestination
  • HaruPage::createTextAnnotation »
  • PHP Manual
  • HaruPage
  • Create new HaruAnnotation instance

HaruPage::createLinkAnnotation

(PECL haru >= 0.0.1)

HaruPage::createLinkAnnotation — Create new HaruAnnotation instance

Description

HaruPage::createLinkAnnotation ( array $rectangle , object $destination ) : object

Creates a new HaruAnnotation instance.

Parameters

rectangle

An array with 4 coordinates of the clickable area.

destination

Valid HaruDestination instance.

Return Values

Returns a new HaruAnnotation instance.

Errors/Exceptions

Throws a HaruException on error.


Create new HaruAnnotation instance

  • « HaruPage::createLinkAnnotation
  • HaruPage::createURLAnnotation »
  • PHP Manual
  • HaruPage
  • Create new HaruAnnotation instance

HaruPage::createTextAnnotation

(PECL haru >= 0.0.1)

HaruPage::createTextAnnotation — Create new HaruAnnotation instance

Description

HaruPage::createTextAnnotation ( array $rectangle , string $text [, object $encoder ] ) : object

Creates a new HaruAnnotation instance.

Parameters

rectangle

An array with 4 coordinates of the annotation area.

text

The text to be displayed.

encoder

Optional HaruEncoder instance.

Return Values

Returns a new HaruAnnotation instance.

Errors/Exceptions

Throws a HaruException on error.


Create and return new HaruAnnotation instance

  • « HaruPage::createTextAnnotation
  • HaruPage::curveTo2 »
  • PHP Manual
  • HaruPage
  • Create and return new HaruAnnotation instance

HaruPage::createURLAnnotation

(PECL haru >= 0.0.1)

HaruPage::createURLAnnotation — Create and return new HaruAnnotation instance

Description

HaruPage::createURLAnnotation ( array $rectangle , string $url ) : object

Creates a new HaruAnnotation instance.

Parameters

rectangle

An array with 4 coordinates of the clickable area.

url

The URL to open.

Return Values

Returns a new HaruAnnotation instance.

Errors/Exceptions

Throws a HaruException on error.


Append a Bezier curve to the current path

  • « HaruPage::createURLAnnotation
  • HaruPage::curveTo3 »
  • PHP Manual
  • HaruPage
  • Append a Bezier curve to the current path

HaruPage::curveTo2

(PECL haru >= 0.0.1)

HaruPage::curveTo2 — Append a Bezier curve to the current path

Description

HaruPage::curveTo2 ( float $x2 , float $y2 , float $x3 , float $y3 ) : bool

Appends a Bezier curve to the current path. The current point and the point (x2, y2) are used as the control points for the Bezier curve and current point is moved to the point (x3, y3).

Parameters

x2

A Bezier curve control point.

y2

A Bezier curve control point.

x3

The current point moves here.

x3

The current point moves here.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Append a Bezier curve to the current path

  • « HaruPage::curveTo2
  • HaruPage::curveTo »
  • PHP Manual
  • HaruPage
  • Append a Bezier curve to the current path

HaruPage::curveTo3

(PECL haru >= 0.0.1)

HaruPage::curveTo3 — Append a Bezier curve to the current path

Description

HaruPage::curveTo3 ( float $x1 , float $y1 , float $x3 , float $y3 ) : bool

Appends a Bezier curve to the current path. The point (x1, y1) and the point (x3, y3) are used as the control points for a Bezier curve and current point is moved to the point (x3, y3).

Parameters

x1

A Bezier curve control point.

y1

A Bezier curve control point.

x3

The current point moves here.

x3

The current point moves here.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Append a Bezier curve to the current path

  • « HaruPage::curveTo3
  • HaruPage::drawImage »
  • PHP Manual
  • HaruPage
  • Append a Bezier curve to the current path

HaruPage::curveTo

(PECL haru >= 0.0.1)

HaruPage::curveTo — Append a Bezier curve to the current path

Description

HaruPage::curveTo ( float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 ) : bool

Append a Bezier curve to the current path. The point (x1, y1) and the point (x2, y2) are used as the control points for a Bezier curve and current point is moved to the point (x3, y3).

Parameters

x1

A Bezier curve control point.

y1

A Bezier curve control point.

x2

A Bezier curve control point.

y2

A Bezier curve control point.

x3

The current point moves here.

x3

The current point moves here.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Show image at the page

  • « HaruPage::curveTo
  • HaruPage::ellipse »
  • PHP Manual
  • HaruPage
  • Show image at the page

HaruPage::drawImage

(PECL haru >= 0.0.1)

HaruPage::drawImage — Show image at the page

Description

HaruPage::drawImage ( object $image , float $x , float $y , float $width , float $height ) : bool

Show image at the page.

Parameters

image

Valid HaruImage instance.

x

The left border of the area where the image is displayed.

y

The lower border of the area where the image is displayed.

width

The width of the image area.

height

The height of the image area.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Append an ellipse to the current path

  • « HaruPage::drawImage
  • HaruPage::endPath »
  • PHP Manual
  • HaruPage
  • Append an ellipse to the current path

HaruPage::ellipse

(PECL haru >= 0.0.1)

HaruPage::ellipse — Append an ellipse to the current path

Description

HaruPage::ellipse ( float $x , float $y , float $xray , float $yray ) : bool

Appends an ellipse to the current path.

Parameters

x

Horizontal coordinate of the center.

y

Vertical coordinate of the center.

xray

The ray of the ellipse in the x direction.

yray

The ray of the ellipse in the y direction.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


End current path object without filling and painting operations

  • « HaruPage::ellipse
  • HaruPage::endText »
  • PHP Manual
  • HaruPage
  • End current path object without filling and painting operations

HaruPage::endPath

(PECL haru >= 0.0.1)

HaruPage::endPath — End current path object without filling and painting operations

Description

HaruPage::endPath ( void ) : bool

Ends current path object without performing filling and painting operations.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


End current text object

  • « HaruPage::endPath
  • HaruPage::eofill »
  • PHP Manual
  • HaruPage
  • End current text object

HaruPage::endText

(PECL haru >= 0.0.1)

HaruPage::endText — End current text object

Description

HaruPage::endText ( void ) : bool

Finalizes current text object.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Fill current path using even-odd rule

  • « HaruPage::endText
  • HaruPage::eoFillStroke »
  • PHP Manual
  • HaruPage
  • Fill current path using even-odd rule

HaruPage::eofill

(PECL haru >= 0.0.1)

HaruPage::eofill — Fill current path using even-odd rule

Description

HaruPage::eofill ( void ) : bool

Fills current path using even-odd rule.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Fill current path using even-odd rule, then paint the path

  • « HaruPage::eofill
  • HaruPage::fill »
  • PHP Manual
  • HaruPage
  • Fill current path using even-odd rule, then paint the path

HaruPage::eoFillStroke

(PECL haru >= 0.0.1)

HaruPage::eoFillStroke — Fill current path using even-odd rule, then paint the path

Description

HaruPage::eoFillStroke ([ bool $close_path = FALSE ] ) : bool

Fills current path using even-odd rule, then paints the path.

Parameters

close_path

Optional parameter. When set to TRUE, the function closes the current path. Default to FALSE.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Fill current path using nonzero winding number rule

  • « HaruPage::eoFillStroke
  • HaruPage::fillStroke »
  • PHP Manual
  • HaruPage
  • Fill current path using nonzero winding number rule

HaruPage::fill

(PECL haru >= 0.0.1)

HaruPage::fill — Fill current path using nonzero winding number rule

Description

HaruPage::fill ( void ) : bool

Fills current path using nonzero winding number rule.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Fill current path using nonzero winding number rule, then paint the path

  • « HaruPage::fill
  • HaruPage::getCharSpace »
  • PHP Manual
  • HaruPage
  • Fill current path using nonzero winding number rule, then paint the path

HaruPage::fillStroke

(PECL haru >= 0.0.1)

HaruPage::fillStroke — Fill current path using nonzero winding number rule, then paint the path

Description

HaruPage::fillStroke ([ bool $close_path = FALSE ] ) : bool

Fills current path using nonzero winding number rule, then paints the path.

Parameters

close_path

Optional parameter. When set to TRUE, the function closes the current path. Default to FALSE.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Get the current value of character spacing

  • « HaruPage::fillStroke
  • HaruPage::getCMYKFill »
  • PHP Manual
  • HaruPage
  • Get the current value of character spacing

HaruPage::getCharSpace

(PECL haru >= 0.0.1)

HaruPage::getCharSpace — Get the current value of character spacing

Description

HaruPage::getCharSpace ( void ) : float

Get the current value of character spacing.

Parameters

This function has no parameters.

Return Values

Returns the current value of character spacing.

Errors/Exceptions

Throws a HaruException on error.


Get the current filling color

  • « HaruPage::getCharSpace
  • HaruPage::getCMYKStroke »
  • PHP Manual
  • HaruPage
  • Get the current filling color

HaruPage::getCMYKFill

(PECL haru >= 0.0.1)

HaruPage::getCMYKFill — Get the current filling color

Description

HaruPage::getCMYKFill ( void ) : array

Returns the current filling color.

Parameters

This function has no parameters.

Return Values

Returns the current filling color as an array with 4 elements ("c", "m", "y" and "k").

Errors/Exceptions

Throws a HaruException on error.


Get the current stroking color

  • « HaruPage::getCMYKFill
  • HaruPage::getCurrentFont »
  • PHP Manual
  • HaruPage
  • Get the current stroking color

HaruPage::getCMYKStroke

(PECL haru >= 0.0.1)

HaruPage::getCMYKStroke — Get the current stroking color

Description

HaruPage::getCMYKStroke ( void ) : array

Get the current stroking color.

Parameters

This function has no parameters.

Return Values

Returns the current stroking color as an array with 4 elements ("c", "m", "y" and "k").

Errors/Exceptions

Throws a HaruException on error.


Get the currently used font

  • « HaruPage::getCMYKStroke
  • HaruPage::getCurrentFontSize »
  • PHP Manual
  • HaruPage
  • Get the currently used font

HaruPage::getCurrentFont

(PECL haru >= 0.0.1)

HaruPage::getCurrentFont — Get the currently used font

Description

HaruPage::getCurrentFont ( void ) : object

Get the currently used font.

Parameters

This function has no parameters.

Return Values

Returns the currently used font as an instance of HaruFont.

Errors/Exceptions

Throws a HaruException on error.


Get the current font size

  • « HaruPage::getCurrentFont
  • HaruPage::getCurrentPos »
  • PHP Manual
  • HaruPage
  • Get the current font size

HaruPage::getCurrentFontSize

(PECL haru >= 0.0.1)

HaruPage::getCurrentFontSize — Get the current font size

Description

HaruPage::getCurrentFontSize ( void ) : float

Get the current font size.

Parameters

This function has no parameters.

Return Values

Returns the current font size.

Errors/Exceptions

Throws a HaruException on error.


Get the current position for path painting

  • « HaruPage::getCurrentFontSize
  • HaruPage::getCurrentTextPos »
  • PHP Manual
  • HaruPage
  • Get the current position for path painting

HaruPage::getCurrentPos

(PECL haru >= 0.0.1)

HaruPage::getCurrentPos — Get the current position for path painting

Description

HaruPage::getCurrentPos ( void ) : array

Get the current position for path painting.

Parameters

This function has no parameters.

Return Values

Returns the current position for path painting as an array of with two elements - "x" and "y".

Errors/Exceptions

Throws a HaruException on error.


Get the current position for text printing

  • « HaruPage::getCurrentPos
  • HaruPage::getDash »
  • PHP Manual
  • HaruPage
  • Get the current position for text printing

HaruPage::getCurrentTextPos

(PECL haru >= 0.0.1)

HaruPage::getCurrentTextPos — Get the current position for text printing

Description

HaruPage::getCurrentTextPos ( void ) : array

Get the current position for text printing.

Parameters

This function has no parameters.

Return Values

Returns the current position for text printing as an array with 2 elements - "x" and "y".

Errors/Exceptions

Throws a HaruException on error.


Get the current dash pattern

  • « HaruPage::getCurrentTextPos
  • HaruPage::getFillingColorSpace »
  • PHP Manual
  • HaruPage
  • Get the current dash pattern

HaruPage::getDash

(PECL haru >= 0.0.1)

HaruPage::getDash — Get the current dash pattern

Description

HaruPage::getDash ( void ) : array

Get the current dash pattern. See HaruPage::setDash() for more information on dash patterns.

Parameters

This function has no parameters.

Return Values

Returns the current dash pattern as an array of two elements - "pattern" and "phase" or FALSE if dash pattern was not set.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setDash() - Set the dash pattern for the page


Get the current filling color space

  • « HaruPage::getDash
  • HaruPage::getFlatness »
  • PHP Manual
  • HaruPage
  • Get the current filling color space

HaruPage::getFillingColorSpace

(PECL haru >= 0.0.1)

HaruPage::getFillingColorSpace — Get the current filling color space

Description

HaruPage::getFillingColorSpace ( void ) : int

Get the current filling color space.

Parameters

This function has no parameters.

Return Values

Returns the current filling color space. The result value is one of the following:

  • HaruDoc::CS_DEVICE_GRAY
  • HaruDoc::CS_DEVICE_RGB
  • HaruDoc::CS_DEVICE_CMYK
  • HaruDoc::CS_CAL_GRAY
  • HaruDoc::CS_CAL_RGB
  • HaruDoc::CS_LAB
  • HaruDoc::CS_ICC_BASED
  • HaruDoc::CS_SEPARATION
  • HaruDoc::CS_DEVICE_N
  • HaruDoc::CS_INDEXED
  • HaruDoc::CS_PATTERN

Errors/Exceptions

Throws a HaruException on error.


Get the flatness of the page

  • « HaruPage::getFillingColorSpace
  • HaruPage::getGMode »
  • PHP Manual
  • HaruPage
  • Get the flatness of the page

HaruPage::getFlatness

(PECL haru >= 0.0.1)

HaruPage::getFlatness — Get the flatness of the page

Description

HaruPage::getFlatness ( void ) : float

Get the flatness of the page.

Parameters

This function has no parameters.

Return Values

Returns the flatness of the page.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setFlatness() - Set flatness for the page


Get the current graphics mode

  • « HaruPage::getFlatness
  • HaruPage::getGrayFill »
  • PHP Manual
  • HaruPage
  • Get the current graphics mode

HaruPage::getGMode

(PECL haru >= 0.0.1)

HaruPage::getGMode — Get the current graphics mode

Description

HaruPage::getGMode ( void ) : int

Get the current graphics mode.

Parameters

This function has no parameters.

Return Values

Returns the current graphics mode. The result value is one of the following:

  • HaruPage::GMODE_PAGE_DESCRIPTION
  • HaruPage::GMODE_TEXT_OBJECT
  • HaruPage::GMODE_PATH_OBJECT
  • HaruPage::GMODE_CLIPPING_PATH
  • HaruPage::GMODE_SHADING
  • HaruPage::GMODE_INLINE_IMAGE
  • HaruPage::GMODE_EXTERNAL_OBJECT

Errors/Exceptions

Throws a HaruException on error.


Get the current filling color

  • « HaruPage::getGMode
  • HaruPage::getGrayStroke »
  • PHP Manual
  • HaruPage
  • Get the current filling color

HaruPage::getGrayFill

(PECL haru >= 0.0.1)

HaruPage::getGrayFill — Get the current filling color

Description

HaruPage::getGrayFill ( void ) : float

Get the current filling color.

Parameters

This function has no parameters.

Return Values

Returns the current filling color.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setGrayFill() - Set filling color for the page


Get the current stroking color

  • « HaruPage::getGrayFill
  • HaruPage::getHeight »
  • PHP Manual
  • HaruPage
  • Get the current stroking color

HaruPage::getGrayStroke

(PECL haru >= 0.0.1)

HaruPage::getGrayStroke — Get the current stroking color

Description

HaruPage::getGrayStroke ( void ) : float

Get the current stroking color.

Parameters

This function has no parameters.

Return Values

Returns the current stroking color.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setGrayStroke() - Sets stroking color for the page


Get the height of the page

  • « HaruPage::getGrayStroke
  • HaruPage::getHorizontalScaling »
  • PHP Manual
  • HaruPage
  • Get the height of the page

HaruPage::getHeight

(PECL haru >= 0.0.1)

HaruPage::getHeight — Get the height of the page

Description

HaruPage::getHeight ( void ) : float

Get the height of the page.

Parameters

This function has no parameters.

Return Values

Returns the height of the page.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setHeight() - Set height of the page


Get the current value of horizontal scaling

  • « HaruPage::getHeight
  • HaruPage::getLineCap »
  • PHP Manual
  • HaruPage
  • Get the current value of horizontal scaling

HaruPage::getHorizontalScaling

(PECL haru >= 0.0.1)

HaruPage::getHorizontalScaling — Get the current value of horizontal scaling

Description

HaruPage::getHorizontalScaling ( void ) : float

Get the current value of the horizontal scaling.

Parameters

This function has no parameters.

Return Values

Returns the current value of horizontal scaling.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setHorizontalScaling() - Set horizontal scaling for the page


Get the current line cap style

  • « HaruPage::getHorizontalScaling
  • HaruPage::getLineJoin »
  • PHP Manual
  • HaruPage
  • Get the current line cap style

HaruPage::getLineCap

(PECL haru >= 0.0.1)

HaruPage::getLineCap — Get the current line cap style

Description

HaruPage::getLineCap ( void ) : int

Get the current line cap style.

Parameters

This function has no parameters.

Return Values

Returns the current line cap style. The result value is one of the following:

  • HaruPage::BUTT_END - the line is squared off at the endpoint of the path.
  • HaruPage::ROUND_END - the end of the line becomes a semicircle with center in the end point of the path.
  • HaruPage::PROJECTING_SCUARE_END - the line continues to the point that exceeds half of the stroke width the end point.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setLineCap() - Set the shape to be used at the ends of lines


Get the current line join style

  • « HaruPage::getLineCap
  • HaruPage::getLineWidth »
  • PHP Manual
  • HaruPage
  • Get the current line join style

HaruPage::getLineJoin

(PECL haru >= 0.0.1)

HaruPage::getLineJoin — Get the current line join style

Description

HaruPage::getLineJoin ( void ) : int

Get the current line join style.

Parameters

This function has no parameters.

Return Values

Returns the current line join style. The result value is one of the following:

  • HaruPage::MITER_JOIN
  • HaruPage::ROUND_JOIN
  • HaruPage::BEVEL_JOIN

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setLineJoin() - Set line join style for the page


Get the current line width

  • « HaruPage::getLineJoin
  • HaruPage::getMiterLimit »
  • PHP Manual
  • HaruPage
  • Get the current line width

HaruPage::getLineWidth

(PECL haru >= 0.0.1)

HaruPage::getLineWidth — Get the current line width

Description

HaruPage::getLineWidth ( void ) : float

Get the current line width.

Parameters

This function has no parameters.

Return Values

Returns the current line width.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setLineWidth() - Set line width for the page


Get the value of miter limit

  • « HaruPage::getLineWidth
  • HaruPage::getRGBFill »
  • PHP Manual
  • HaruPage
  • Get the value of miter limit

HaruPage::getMiterLimit

(PECL haru >= 0.0.1)

HaruPage::getMiterLimit — Get the value of miter limit

Description

HaruPage::getMiterLimit ( void ) : float

Get the value of the miter limit.

Parameters

This function has no parameters.

Return Values

Returns the value of the miter limit.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setMiterLimit() - Set the current value of the miter limit of the page


Get the current filling color

  • « HaruPage::getMiterLimit
  • HaruPage::getRGBStroke »
  • PHP Manual
  • HaruPage
  • Get the current filling color

HaruPage::getRGBFill

(PECL haru >= 0.0.1)

HaruPage::getRGBFill — Get the current filling color

Description

HaruPage::getRGBFill ( void ) : array

Get the current filling color.

Parameters

This function has no parameters.

Return Values

Returns the current filling color as an array with 3 elements: "r", "g" and "b".

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setRGBFill() - Set filling color for the page


Get the current stroking color

  • « HaruPage::getRGBFill
  • HaruPage::getStrokingColorSpace »
  • PHP Manual
  • HaruPage
  • Get the current stroking color

HaruPage::getRGBStroke

(PECL haru >= 0.0.1)

HaruPage::getRGBStroke — Get the current stroking color

Description

HaruPage::getRGBStroke ( void ) : array

Get the current stroking color.

Parameters

This function has no parameters.

Return Values

Returns the current stroking color.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setRGBStroke() - Set stroking color for the page


Get the current stroking color space

  • « HaruPage::getRGBStroke
  • HaruPage::getTextLeading »
  • PHP Manual
  • HaruPage
  • Get the current stroking color space

HaruPage::getStrokingColorSpace

(PECL haru >= 0.0.1)

HaruPage::getStrokingColorSpace — Get the current stroking color space

Description

HaruPage::getStrokingColorSpace ( void ) : int

Get the current stroking color space.

Parameters

This function has no parameters.

Return Values

Returns the current stroking color space. The list of return values is the same as for HaruPage::getFillingColorSpace()

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getFillingColorSpace() - Get the current filling color space


Get the current value of line spacing

  • « HaruPage::getStrokingColorSpace
  • HaruPage::getTextMatrix »
  • PHP Manual
  • HaruPage
  • Get the current value of line spacing

HaruPage::getTextLeading

(PECL haru >= 0.0.1)

HaruPage::getTextLeading — Get the current value of line spacing

Description

HaruPage::getTextLeading ( void ) : float

Get the current value of line spacing.

Parameters

This function has no parameters.

Return Values

Returns the current value of line spacing.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setTextLeading() - Set text leading (line spacing) for the page


Get the current text transformation matrix of the page

  • « HaruPage::getTextLeading
  • HaruPage::getTextRenderingMode »
  • PHP Manual
  • HaruPage
  • Get the current text transformation matrix of the page

HaruPage::getTextMatrix

(PECL haru >= 0.0.1)

HaruPage::getTextMatrix — Get the current text transformation matrix of the page

Description

HaruPage::getTextMatrix ( void ) : array

Get the current text transformation matrix of the page.

Return Values

Returns the current text transformation matrix of the page as an array of 6 elements: "a", "b", "c", "d", "x" and "y".

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setTextMatrix() - Set the current text transformation matrix of the page


Get the current text rendering mode

  • « HaruPage::getTextMatrix
  • HaruPage::getTextRise »
  • PHP Manual
  • HaruPage
  • Get the current text rendering mode

HaruPage::getTextRenderingMode

(PECL haru >= 0.0.1)

HaruPage::getTextRenderingMode — Get the current text rendering mode

Description

HaruPage::getTextRenderingMode ( void ) : int

Get the current text rendering mode.

Parameters

This function has no parameters.

Return Values

Returns the current text rendering mode. The result value is one of the following:

  • HaruPage::FILL
  • HaruPage::STROKE
  • HaruPage::FILL_THEN_STROKE
  • HaruPage::INVISIBLE
  • HaruPage::FILL_CLIPPING
  • HaruPage::STROKE_CLIPPING
  • HaruPage::FILL_STROKE_CLIPPING
  • HaruPage::CLIPPING

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setTextRenderingMode() - Set text rendering mode for the page


Get the current value of text rising

  • « HaruPage::getTextRenderingMode
  • HaruPage::getTextWidth »
  • PHP Manual
  • HaruPage
  • Get the current value of text rising

HaruPage::getTextRise

(PECL haru >= 0.0.1)

HaruPage::getTextRise — Get the current value of text rising

Description

HaruPage::getTextRise ( void ) : float

Get the current value of text rising.

Parameters

This function has no parameters.

Return Values

Returns the current value of text rising.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setTextRise() - Set the current value of text rising


Get the width of the text using current fontsize, character spacing and word spacing

  • « HaruPage::getTextRise
  • HaruPage::getTransMatrix »
  • PHP Manual
  • HaruPage
  • Get the width of the text using current fontsize, character spacing and word spacing

HaruPage::getTextWidth

(PECL haru >= 0.0.1)

HaruPage::getTextWidth — Get the width of the text using current fontsize, character spacing and word spacing

Description

HaruPage::getTextWidth ( string $text ) : float

Get the width of the text using current fontsize, character spacing and word spacing

Parameters

text

The text to measure.

Return Values

Returns the width of the text using current fontsize, character spacing and word spacing.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::measureText() - Calculate the byte length of characters which can be included on one line of the specified width


Get the current transformation matrix of the page

  • « HaruPage::getTextWidth
  • HaruPage::getWidth »
  • PHP Manual
  • HaruPage
  • Get the current transformation matrix of the page

HaruPage::getTransMatrix

(PECL haru >= 0.0.1)

HaruPage::getTransMatrix — Get the current transformation matrix of the page

Description

HaruPage::getTransMatrix ( void ) : array

Get the current transformation matrix of the page.

Parameters

This function has no parameters.

Return Values

Returns the current transformation matrix of the page as an array of 6 elements: "a", "b", "c", "d", "x" and "y".

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::concat() - Concatenate current transformation matrix of the page and the specified matrix


Get the width of the page

  • « HaruPage::getTransMatrix
  • HaruPage::getWordSpace »
  • PHP Manual
  • HaruPage
  • Get the width of the page

HaruPage::getWidth

(PECL haru >= 0.0.1)

HaruPage::getWidth — Get the width of the page

Description

HaruPage::getWidth ( void ) : float

Get the width of the page.

Parameters

This function has no parameters.

Return Values

Returns the width of the page.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setWidth() - Set width of the page


Get the current value of word spacing

  • « HaruPage::getWidth
  • HaruPage::lineTo »
  • PHP Manual
  • HaruPage
  • Get the current value of word spacing

HaruPage::getWordSpace

(PECL haru >= 0.0.1)

HaruPage::getWordSpace — Get the current value of word spacing

Description

HaruPage::getWordSpace ( void ) : float

Get the current value of word spacing.

Parameters

This function has no parameters.

Return Values

Returns the current value of word spacing.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setWordSpace() - Set word spacing for the page


Draw a line from the current point to the specified point

  • « HaruPage::getWordSpace
  • HaruPage::measureText »
  • PHP Manual
  • HaruPage
  • Draw a line from the current point to the specified point

HaruPage::lineTo

(PECL haru >= 0.0.1)

HaruPage::lineTo — Draw a line from the current point to the specified point

Description

HaruPage::lineTo ( float $x , float $y ) : bool

Draws a line from the current point to the specified point.

Parameters

x

y

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::curveTo() - Append a Bezier curve to the current path
  • HaruPage::curveTo2() - Append a Bezier curve to the current path
  • HaruPage::curveTo3() - Append a Bezier curve to the current path


Calculate the byte length of characters which can be included on one line of the specified width

  • « HaruPage::lineTo
  • HaruPage::moveTextPos »
  • PHP Manual
  • HaruPage
  • Calculate the byte length of characters which can be included on one line of the specified width

HaruPage::measureText

(PECL haru >= 0.0.1)

HaruPage::measureText — Calculate the byte length of characters which can be included on one line of the specified width

Description

HaruPage::measureText ( string $text , float $width [, bool $wordwrap = FALSE ] ) : int

Get the byte length of characters which can be included on one line of the specified width.

Parameters

text

The text to measure.

width

The width of the line.

wordwrap

When this parameter is set to TRUE the function "emulates" word wrapping by stopping after the last full word (delimited by whitespace) that can fit on the line.

Return Values

Returns the byte length of characters which can be included within the specified width. For single-byte encodings, this is equal to the number of characters. For multi-byte encodings, this is not necessarily the case.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruFont::measureText() - Calculate the number of characters which can be included within the specified width


Move text position to the specified offset

  • « HaruPage::measureText
  • HaruPage::moveTo »
  • PHP Manual
  • HaruPage
  • Move text position to the specified offset

HaruPage::moveTextPos

(PECL haru >= 0.0.1)

HaruPage::moveTextPos — Move text position to the specified offset

Description

HaruPage::moveTextPos ( float $x , float $y [, bool $set_leading = FALSE ] ) : bool

Moves text position to the specified offset. If the start position of the current line is (x1, y1), the start of the next line is (x1 + x, y1 + y).

Parameters

x

The specified text position offset.

y

The specified text position offset.

set_leading

If set to TRUE, the function sets the text leading to -y.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::moveToNextLine() - Move text position to the start of the next line


Set starting point for new drawing path

  • « HaruPage::moveTextPos
  • HaruPage::moveToNextLine »
  • PHP Manual
  • HaruPage
  • Set starting point for new drawing path

HaruPage::moveTo

(PECL haru >= 0.0.1)

HaruPage::moveTo — Set starting point for new drawing path

Description

HaruPage::moveTo ( float $x , float $y ) : bool

Defines starting point for new drawing path.

Parameters

x

A new starting point coordinate.

y

A new starting point coordinate.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Move text position to the start of the next line

  • « HaruPage::moveTo
  • HaruPage::rectangle »
  • PHP Manual
  • HaruPage
  • Move text position to the start of the next line

HaruPage::moveToNextLine

(PECL haru >= 0.0.1)

HaruPage::moveToNextLine — Move text position to the start of the next line

Description

HaruPage::moveToNextLine ( void ) : bool

Moves text position to the start of the next line.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::moveTextPos() - Move text position to the specified offset


Append a rectangle to the current path

  • « HaruPage::moveToNextLine
  • HaruPage::setCharSpace »
  • PHP Manual
  • HaruPage
  • Append a rectangle to the current path

HaruPage::rectangle

(PECL haru >= 0.0.1)

HaruPage::rectangle — Append a rectangle to the current path

Description

HaruPage::rectangle ( float $x , float $y , float $width , float $height ) : bool

Appends a rectangle to the current drawing path.

Parameters

x

The left border of the rectangle.

y

The lower border of the rectangle.

width

The width of the rectangle.

height

The height of the rectangle.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Set character spacing for the page

  • « HaruPage::rectangle
  • HaruPage::setCMYKFill »
  • PHP Manual
  • HaruPage
  • Set character spacing for the page

HaruPage::setCharSpace

(PECL haru >= 0.0.1)

HaruPage::setCharSpace — Set character spacing for the page

Description

HaruPage::setCharSpace ( float $char_space ) : bool

Defines character spacing for the page.

Parameters

char_space

The new character spacing for the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getCharSpace() - Get the current value of character spacing


Set filling color for the page

  • « HaruPage::setCharSpace
  • HaruPage::setCMYKStroke »
  • PHP Manual
  • HaruPage
  • Set filling color for the page

HaruPage::setCMYKFill

(PECL haru >= 0.0.1)

HaruPage::setCMYKFill — Set filling color for the page

Description

HaruPage::setCMYKFill ( float $c , float $m , float $y , float $k ) : bool

Defines filling color for the page.

Parameters

c

m

y

k

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getCMYKFill() - Get the current filling color


Set stroking color for the page

  • « HaruPage::setCMYKFill
  • HaruPage::setDash »
  • PHP Manual
  • HaruPage
  • Set stroking color for the page

HaruPage::setCMYKStroke

(PECL haru >= 0.0.1)

HaruPage::setCMYKStroke — Set stroking color for the page

Description

HaruPage::setCMYKStroke ( float $c , float $m , float $y , float $k ) : bool

Defines stroking color for the page.

Parameters

c

m

y

k

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getCMYKStroke() - Get the current stroking color


Set the dash pattern for the page

  • « HaruPage::setCMYKStroke
  • HaruPage::setFlatness »
  • PHP Manual
  • HaruPage
  • Set the dash pattern for the page

HaruPage::setDash

(PECL haru >= 0.0.1)

HaruPage::setDash — Set the dash pattern for the page

Description

HaruPage::setDash ( array $pattern , int $phase ) : bool

Defines the dash pattern for the page.

Parameters

pattern

An array (8 elements max) which contains a pattern of dashes and gaps used for lines on the page.

phase

The phase on which the pattern begins.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getDash() - Get the current dash pattern


Set flatness for the page

  • « HaruPage::setDash
  • HaruPage::setFontAndSize »
  • PHP Manual
  • HaruPage
  • Set flatness for the page

HaruPage::setFlatness

(PECL haru >= 0.0.1)

HaruPage::setFlatness — Set flatness for the page

Description

HaruPage::setFlatness ( float $flatness ) : bool

Defines flatness for the page.

Parameters

flatness

The defined flatness for the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getFlatness() - Get the flatness of the page


Set font and fontsize for the page

  • « HaruPage::setFlatness
  • HaruPage::setGrayFill »
  • PHP Manual
  • HaruPage
  • Set font and fontsize for the page

HaruPage::setFontAndSize

(PECL haru >= 0.0.1)

HaruPage::setFontAndSize — Set font and fontsize for the page

Description

HaruPage::setFontAndSize ( object $font , float $size ) : bool

Defines current font and its size for the page.

Parameters

font

A valid HaruFont instance.

size

The size of the font.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruDoc::getFont() - Get HaruFont instance


Set filling color for the page

  • « HaruPage::setFontAndSize
  • HaruPage::setGrayStroke »
  • PHP Manual
  • HaruPage
  • Set filling color for the page

HaruPage::setGrayFill

(PECL haru >= 0.0.1)

HaruPage::setGrayFill — Set filling color for the page

Description

HaruPage::setGrayFill ( float $value ) : bool

Defines filling color for the page.

Parameters

value

The value of gray level between 0 and 1.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getGrayFill() - Get the current filling color


Sets stroking color for the page

  • « HaruPage::setGrayFill
  • HaruPage::setHeight »
  • PHP Manual
  • HaruPage
  • Sets stroking color for the page

HaruPage::setGrayStroke

(PECL haru >= 0.0.1)

HaruPage::setGrayStroke — Sets stroking color for the page

Description

HaruPage::setGrayStroke ( float $value ) : bool

Defines stroking color for the page.

Parameters

value

The value of gray level between 0 and 1.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getGrayStroke() - Get the current stroking color


Set height of the page

  • « HaruPage::setGrayStroke
  • HaruPage::setHorizontalScaling »
  • PHP Manual
  • HaruPage
  • Set height of the page

HaruPage::setHeight

(PECL haru >= 0.0.1)

HaruPage::setHeight — Set height of the page

Description

HaruPage::setHeight ( float $height ) : bool

Defines height of the page.

Parameters

height

The defined height for the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getHeight() - Get the height of the page


Set horizontal scaling for the page

  • « HaruPage::setHeight
  • HaruPage::setLineCap »
  • PHP Manual
  • HaruPage
  • Set horizontal scaling for the page

HaruPage::setHorizontalScaling

(PECL haru >= 0.0.1)

HaruPage::setHorizontalScaling — Set horizontal scaling for the page

Description

HaruPage::setHorizontalScaling ( float $scaling ) : bool

Set the horizontal scaling for the page.

Parameters

scaling

The horizontal scaling for text showing on the page. The initial value is 100.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getHorizontalScaling() - Get the current value of horizontal scaling


Set the shape to be used at the ends of lines

  • « HaruPage::setHorizontalScaling
  • HaruPage::setLineJoin »
  • PHP Manual
  • HaruPage
  • Set the shape to be used at the ends of lines

HaruPage::setLineCap

(PECL haru >= 0.0.1)

HaruPage::setLineCap — Set the shape to be used at the ends of lines

Description

HaruPage::setLineCap ( int $cap ) : bool

Defines the shape to be used at the ends of lines.

Parameters

cap

Must be one of the following values:

  • HaruPage::BUTT_END - the line is squared off at the endpoint of the path.
  • HaruPage::ROUND_END - the end of the line becomes a semicircle with center in the end point of the path.
  • HaruPage::PROJECTING_SCUARE_END - the line continues to the point that exceeds half of the stroke width the end point.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getLineCap() - Get the current line cap style


Set line join style for the page

  • « HaruPage::setLineCap
  • HaruPage::setLineWidth »
  • PHP Manual
  • HaruPage
  • Set line join style for the page

HaruPage::setLineJoin

(PECL haru >= 0.0.1)

HaruPage::setLineJoin — Set line join style for the page

Description

HaruPage::setLineJoin ( int $join ) : bool

Defines line join style for the page.

Parameters

join

Must be one of the following values:

  • HaruPage::MITER_JOIN
  • HaruPage::ROUND_JOIN
  • HaruPage::BEVEL_JOIN

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getLineJoin() - Get the current line join style


Set line width for the page

  • « HaruPage::setLineJoin
  • HaruPage::setMiterLimit »
  • PHP Manual
  • HaruPage
  • Set line width for the page

HaruPage::setLineWidth

(PECL haru >= 0.0.1)

HaruPage::setLineWidth — Set line width for the page

Description

HaruPage::setLineWidth ( float $width ) : bool

Defines line width for the page.

Parameters

width

The defined line width for the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getLineWidth() - Get the current line width


Set the current value of the miter limit of the page

  • « HaruPage::setLineWidth
  • HaruPage::setRGBFill »
  • PHP Manual
  • HaruPage
  • Set the current value of the miter limit of the page

HaruPage::setMiterLimit

(PECL haru >= 0.0.1)

HaruPage::setMiterLimit — Set the current value of the miter limit of the page

Description

HaruPage::setMiterLimit ( float $limit ) : bool

Set the current value of the miter limit of the page.

Parameters

limit

Defines the current value of the miter limit of the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getMiterLimit() - Get the value of miter limit


Set filling color for the page

  • « HaruPage::setMiterLimit
  • HaruPage::setRGBStroke »
  • PHP Manual
  • HaruPage
  • Set filling color for the page

HaruPage::setRGBFill

(PECL haru >= 0.0.1)

HaruPage::setRGBFill — Set filling color for the page

Description

HaruPage::setRGBFill ( float $r , float $g , float $b ) : bool

Defines filling color for the page. All values must be between 0 and 1.

Parameters

r

g

b

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getRGBFill() - Get the current filling color


Set stroking color for the page

  • « HaruPage::setRGBFill
  • HaruPage::setRotate »
  • PHP Manual
  • HaruPage
  • Set stroking color for the page

HaruPage::setRGBStroke

(PECL haru >= 0.0.1)

HaruPage::setRGBStroke — Set stroking color for the page

Description

HaruPage::setRGBStroke ( float $r , float $g , float $b ) : bool

Defines stroking color for the page. All values must be between 0 and 1.

Parameters

r

g

b

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getRGBStroke() - Get the current stroking color


Set rotation angle of the page

  • « HaruPage::setRGBStroke
  • HaruPage::setSize »
  • PHP Manual
  • HaruPage
  • Set rotation angle of the page

HaruPage::setRotate

(PECL haru >= 0.0.1)

HaruPage::setRotate — Set rotation angle of the page

Description

HaruPage::setRotate ( int $angle ) : bool

Defines rotation angle of the page.

Parameters

angle

Must be a multiple of 90 degrees.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Set size and direction of the page

  • « HaruPage::setRotate
  • HaruPage::setSlideShow »
  • PHP Manual
  • HaruPage
  • Set size and direction of the page

HaruPage::setSize

(PECL haru >= 0.0.1)

HaruPage::setSize — Set size and direction of the page

Description

HaruPage::setSize ( int $size , int $direction ) : bool

Changes size and direction of the page to a predefined format.

Parameters

size

Must be one of the following values:

  • HaruPage::SIZE_LETTER
  • HaruPage::SIZE_LEGAL
  • HaruPage::SIZE_A3
  • HaruPage::SIZE_A4
  • HaruPage::SIZE_A5
  • HaruPage::SIZE_B4
  • HaruPage::SIZE_B5
  • HaruPage::SIZE_EXECUTIVE
  • HaruPage::SIZE_US4x6
  • HaruPage::SIZE_US4x8
  • HaruPage::SIZE_US5x7
  • HaruPage::SIZE_COMM10

direction

Must be one of the following values:

  • HaruPage::PORTRAIT
  • HaruPage::LANDSCAPE

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::setWidth() - Set width of the page
  • HaruPage::setHeight() - Set height of the page


Set transition style for the page

  • « HaruPage::setSize
  • HaruPage::setTextLeading »
  • PHP Manual
  • HaruPage
  • Set transition style for the page

HaruPage::setSlideShow

(PECL haru >= 0.0.1)

HaruPage::setSlideShow — Set transition style for the page

Description

HaruPage::setSlideShow ( int $type , float $disp_time , float $trans_time ) : bool

Defines transition style for the page.

Parameters

type

Must be one of the following values:

  • HaruPage::TS_WIPE_RIGHT
  • HaruPage::TS_WIPE_LEFT
  • HaruPage::TS_WIPE_UP
  • HaruPage::TS_WIPE_DOWN
  • HaruPage::TS_BARN_DOORS_HORIZONTAL_OUT
  • HaruPage::TS_BARN_DOORS_HORIZONTAL_IN
  • HaruPage::TS_BARN_DOORS_VERTICAL_OUT
  • HaruPage::TS_BARN_DOORS_VERTICAL_IN
  • HaruPage::TS_BOX_OUT
  • HaruPage::TS_BOX_IN
  • HaruPage::TS_BLINDS_HORIZONTAL
  • HaruPage::TS_BLINDS_VERTICAL
  • HaruPage::TS_DISSOLVE
  • HaruPage::TS_GLITTER_RIGHT
  • HaruPage::TS_GLITTER_DOWN
  • HaruPage::TS_GLITTER_TOP_LEFT_TO_BOTTOM_RIGHT
  • HaruPage::TS_REPLACE

disp_time

The display duration of the page in seconds.

trans_time

The duration of the transition effect in seconds.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Set text leading (line spacing) for the page

  • « HaruPage::setSlideShow
  • HaruPage::setTextMatrix »
  • PHP Manual
  • HaruPage
  • Set text leading (line spacing) for the page

HaruPage::setTextLeading

(PECL haru >= 0.0.1)

HaruPage::setTextLeading — Set text leading (line spacing) for the page

Description

HaruPage::setTextLeading ( float $text_leading ) : bool

Set the text leading (line spacing) for the page.

Parameters

text_leading

Defines line spacing for the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getTextLeading() - Get the current value of line spacing


Set the current text transformation matrix of the page

  • « HaruPage::setTextLeading
  • HaruPage::setTextRenderingMode »
  • PHP Manual
  • HaruPage
  • Set the current text transformation matrix of the page

HaruPage::setTextMatrix

(PECL haru >= 0.0.1)

HaruPage::setTextMatrix — Set the current text transformation matrix of the page

Description

HaruPage::setTextMatrix ( float $a , float $b , float $c , float $d , float $x , float $y ) : bool

Defines the text transformation matrix of the page.

Parameters

a

Width multiplier.

b

Vertical skew in radians.

c

Horizontal skew in radians.

d

Height multiplier.

x

Horizontal position for text.

y

Vertical position for text.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getTextMatrix() - Get the current text transformation matrix of the page


Set text rendering mode for the page

  • « HaruPage::setTextMatrix
  • HaruPage::setTextRise »
  • PHP Manual
  • HaruPage
  • Set text rendering mode for the page

HaruPage::setTextRenderingMode

(PECL haru >= 0.0.1)

HaruPage::setTextRenderingMode — Set text rendering mode for the page

Description

HaruPage::setTextRenderingMode ( int $mode ) : bool

Defines text rendering mode for the page.

Parameters

mode

Must be one of the following values:

  • HaruPage::FILL
  • HaruPage::STROKE
  • HaruPage::FILL_THEN_STROKE
  • HaruPage::INVISIBLE
  • HaruPage::FILL_CLIPPING
  • HaruPage::STROKE_CLIPPING
  • HaruPage::FILL_STROKE_CLIPPING
  • HaruPage::CLIPPING

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getTextRenderingMode() - Get the current text rendering mode


Set the current value of text rising

  • « HaruPage::setTextRenderingMode
  • HaruPage::setWidth »
  • PHP Manual
  • HaruPage
  • Set the current value of text rising

HaruPage::setTextRise

(PECL haru >= 0.0.1)

HaruPage::setTextRise — Set the current value of text rising

Description

HaruPage::setTextRise ( float $rise ) : bool

Set the current value of text rising.

Parameters

rise

Defines the current value of text rising.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getTextRise() - Get the current value of text rising


Set width of the page

  • « HaruPage::setTextRise
  • HaruPage::setWordSpace »
  • PHP Manual
  • HaruPage
  • Set width of the page

HaruPage::setWidth

(PECL haru >= 0.0.1)

HaruPage::setWidth — Set width of the page

Description

HaruPage::setWidth ( float $width ) : bool

Set the width of the page.

Parameters

width

Defines width of the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getWidth() - Get the width of the page


Set word spacing for the page

  • « HaruPage::setWidth
  • HaruPage::showText »
  • PHP Manual
  • HaruPage
  • Set word spacing for the page

HaruPage::setWordSpace

(PECL haru >= 0.0.1)

HaruPage::setWordSpace — Set word spacing for the page

Description

HaruPage::setWordSpace ( float $word_space ) : bool

Set the word spacing for the page.

Parameters

word_space

Defines word spacing for the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::getWordSpace() - Get the current value of word spacing


Print text at the current position of the page

  • « HaruPage::setWordSpace
  • HaruPage::showTextNextLine »
  • PHP Manual
  • HaruPage
  • Print text at the current position of the page

HaruPage::showText

(PECL haru >= 0.0.1)

HaruPage::showText — Print text at the current position of the page

Description

HaruPage::showText ( string $text ) : bool

Prints out the text at the current position of the page.

Parameters

text

The text to show.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::showTextNextLine() - Move the current position to the start of the next line and print the text
  • HaruPage::textOut() - Print the text on the specified position


Move the current position to the start of the next line and print the text

  • « HaruPage::showText
  • HaruPage::stroke »
  • PHP Manual
  • HaruPage
  • Move the current position to the start of the next line and print the text

HaruPage::showTextNextLine

(PECL haru >= 0.0.1)

HaruPage::showTextNextLine — Move the current position to the start of the next line and print the text

Description

HaruPage::showTextNextLine ( string $text [, float $word_space = 0 [, float $char_space = 0 ]] ) : bool

Moves the current position to the start of the next line and print out the text.

Parameters

text

The text to show.

word_space

The word spacing.

char_space

The character spacing.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::showText() - Print text at the current position of the page
  • HaruPage::textOut() - Print the text on the specified position


Paint current path

  • « HaruPage::showTextNextLine
  • HaruPage::textOut »
  • PHP Manual
  • HaruPage
  • Paint current path

HaruPage::stroke

(PECL haru >= 0.0.1)

HaruPage::stroke — Paint current path

Description

HaruPage::stroke ([ bool $close_path = FALSE ] ) : bool

Paints the current path.

Parameters

close_path

Closes the current path if set to TRUE.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Print the text on the specified position

  • « HaruPage::stroke
  • HaruPage::textRect »
  • PHP Manual
  • HaruPage
  • Print the text on the specified position

HaruPage::textOut

(PECL haru >= 0.0.1)

HaruPage::textOut — Print the text on the specified position

Description

HaruPage::textOut ( float $x , float $y , string $text ) : bool

Prints the text on the specified position.

Parameters

x

y

text

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::showTextNextLine() - Move the current position to the start of the next line and print the text
  • HaruPage::showText() - Print text at the current position of the page


Print the text inside the specified region

  • « HaruPage::textOut
  • HaruFont »
  • PHP Manual
  • HaruPage
  • Print the text inside the specified region

HaruPage::textRect

(PECL haru >= 0.0.1)

HaruPage::textRect — Print the text inside the specified region

Description

HaruPage::textRect ( float $left , float $top , float $right , float $bottom , string $text [, int $align = HaruPage::TALIGN_LEFT ] ) : bool

Prints the text inside the specified region.

Parameters

left

Left border of the text area.

top

Top border of the text area.

right

Right border of the text area.

bottom

Lower border of the text area.

text

The text to print.

align

Text alignment. Must be one of the following values:

  • HaruPage::TALIGN_LEFT
  • HaruPage::TALIGN_RIGHT
  • HaruPage::TALIGN_CENTER
  • HaruPage::TALIGN_JUSTIFY

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.

See Also

  • HaruPage::showTextNextLine() - Move the current position to the start of the next line and print the text
  • HaruPage::showText() - Print text at the current position of the page
  • HaruPage::textOut() - Print the text on the specified position


The HaruFont class

(PECL haru >= 0.0.1)

Introduction

Haru PDF Font Class.

Class synopsis

HaruFont {
/* Methods */
getAscent ( void ) : int
getCapHeight ( void ) : int
getDescent ( void ) : int
getEncodingName ( void ) : string
getFontName ( void ) : string
getTextWidth ( string $text ) : array
getUnicodeWidth ( int $character ) : int
getXHeight ( void ) : int
measureText ( string $text , float $width , float $font_size , float $char_space , float $word_space [, bool $word_wrap = FALSE ] ) : int
}

Table of Contents

  • HaruFont::getAscent — Get the vertical ascent of the font
  • HaruFont::getCapHeight — Get the distance from the baseline of uppercase letters
  • HaruFont::getDescent — Get the vertical descent of the font
  • HaruFont::getEncodingName — Get the name of the encoding
  • HaruFont::getFontName — Get the name of the font
  • HaruFont::getTextWidth — Get the total width of the text, number of characters, number of words and number of spaces
  • HaruFont::getUnicodeWidth — Get the width of the character in the font
  • HaruFont::getXHeight — Get the distance from the baseline of lowercase letters
  • HaruFont::measureText — Calculate the number of characters which can be included within the specified width


Get the vertical ascent of the font

  • « HaruFont
  • HaruFont::getCapHeight »
  • PHP Manual
  • HaruFont
  • Get the vertical ascent of the font

HaruFont::getAscent

(PECL haru >= 0.0.1)

HaruFont::getAscent — Get the vertical ascent of the font

Description

HaruFont::getAscent ( void ) : int

Get the vertical ascent of the font.

Parameters

This function has no parameters.

Return Values

Returns the vertical ascent of the font.

Errors/Exceptions

Throws a HaruException on error.


Get the distance from the baseline of uppercase letters

  • « HaruFont::getAscent
  • HaruFont::getDescent »
  • PHP Manual
  • HaruFont
  • Get the distance from the baseline of uppercase letters

HaruFont::getCapHeight

(PECL haru >= 0.0.1)

HaruFont::getCapHeight — Get the distance from the baseline of uppercase letters

Description

HaruFont::getCapHeight ( void ) : int

Get the distance from the baseline of uppercase letters.

Parameters

This function has no parameters.

Return Values

Returns the distance from the baseline of uppercase letters.

Errors/Exceptions

Throws a HaruException on error.


Get the vertical descent of the font

  • « HaruFont::getCapHeight
  • HaruFont::getEncodingName »
  • PHP Manual
  • HaruFont
  • Get the vertical descent of the font

HaruFont::getDescent

(PECL haru >= 0.0.1)

HaruFont::getDescent — Get the vertical descent of the font

Description

HaruFont::getDescent ( void ) : int

Get the vertical descent of the font.

Parameters

This function has no parameters.

Return Values

Return the vertical descent of the font.

Errors/Exceptions

Throws a HaruException on error.


Get the name of the encoding

  • « HaruFont::getDescent
  • HaruFont::getFontName »
  • PHP Manual
  • HaruFont
  • Get the name of the encoding

HaruFont::getEncodingName

(PECL haru >= 0.0.1)

HaruFont::getEncodingName — Get the name of the encoding

Description

HaruFont::getEncodingName ( void ) : string

Get the name of the font encoding.

Parameters

This function has no parameters.

Return Values

Returns the name of the font encoding.

Errors/Exceptions

Throws a HaruException on error.


Get the name of the font

  • « HaruFont::getEncodingName
  • HaruFont::getTextWidth »
  • PHP Manual
  • HaruFont
  • Get the name of the font

HaruFont::getFontName

(PECL haru >= 0.0.1)

HaruFont::getFontName — Get the name of the font

Description

HaruFont::getFontName ( void ) : string

Get the name of the font.

Parameters

This function has no parameters.

Return Values

Returns the name of the font.

Errors/Exceptions

Throws a HaruException on error.


Get the total width of the text, number of characters, number of words and number of spaces

  • « HaruFont::getFontName
  • HaruFont::getUnicodeWidth »
  • PHP Manual
  • HaruFont
  • Get the total width of the text, number of characters, number of words and number of spaces

HaruFont::getTextWidth

(PECL haru >= 0.0.1)

HaruFont::getTextWidth — Get the total width of the text, number of characters, number of words and number of spaces

Description

HaruFont::getTextWidth ( string $text ) : array

Get the total width of the text, number of characters, number of words and number of spaces.

Parameters

text

The text to measure.

Return Values

Returns the total width of the text, number of characters, number of words and number of spaces in the given text.

Errors/Exceptions

Throws a HaruException on error.


Get the width of the character in the font

  • « HaruFont::getTextWidth
  • HaruFont::getXHeight »
  • PHP Manual
  • HaruFont
  • Get the width of the character in the font

HaruFont::getUnicodeWidth

(PECL haru >= 0.0.1)

HaruFont::getUnicodeWidth — Get the width of the character in the font

Description

HaruFont::getUnicodeWidth ( int $character ) : int

Get the width of the character in the font.

Parameters

character

The code of the character.

Return Values

Returns the width of the character in the font.

Errors/Exceptions

Throws a HaruException on error.


Get the distance from the baseline of lowercase letters

  • « HaruFont::getUnicodeWidth
  • HaruFont::measureText »
  • PHP Manual
  • HaruFont
  • Get the distance from the baseline of lowercase letters

HaruFont::getXHeight

(PECL haru >= 0.0.1)

HaruFont::getXHeight — Get the distance from the baseline of lowercase letters

Description

HaruFont::getXHeight ( void ) : int

Gets the distance from the baseline of lowercase letters.

Parameters

This function has no parameters.

Return Values

Returns the distance from the baseline of lowercase letters.

Errors/Exceptions

Throws a HaruException on error.


Calculate the number of characters which can be included within the specified width

  • « HaruFont::getXHeight
  • HaruImage »
  • PHP Manual
  • HaruFont
  • Calculate the number of characters which can be included within the specified width

HaruFont::measureText

(PECL haru >= 0.0.1)

HaruFont::measureText — Calculate the number of characters which can be included within the specified width

Description

HaruFont::measureText ( string $text , float $width , float $font_size , float $char_space , float $word_space [, bool $word_wrap = FALSE ] ) : int

Calculate the number of characters which can be included within the specified width.

Parameters

text

The text to fit the width.

width

The width of the area to put the text to.

font_size

The size of the font.

char_space

The character spacing.

word_space

The word spacing.

word_wrap

When this parameter is set to TRUE the function "emulates" word wrapping and doesn't include the part of the current word if reached the end of the area.

Return Values

Returns the number of characters which can be included within the specified width.

Errors/Exceptions

Throws a HaruException on error.


The HaruImage class

(PECL haru >= 0.0.1)

Introduction

Haru PDF Image Class.

Class synopsis

HaruImage {
/* Methods */
getBitsPerComponent ( void ) : int
getColorSpace ( void ) : string
getHeight ( void ) : int
getSize ( void ) : array
getWidth ( void ) : int
setColorMask ( int $rmin , int $rmax , int $gmin , int $gmax , int $bmin , int $bmax ) : bool
setMaskImage ( object $mask_image ) : bool
}

Table of Contents

  • HaruImage::getBitsPerComponent — Get the number of bits used to describe each color component of the image
  • HaruImage::getColorSpace — Get the name of the color space
  • HaruImage::getHeight — Get the height of the image
  • HaruImage::getSize — Get size of the image
  • HaruImage::getWidth — Get the width of the image
  • HaruImage::setColorMask — Set the color mask of the image
  • HaruImage::setMaskImage — Set the image mask


Get the number of bits used to describe each color component of the image

  • « HaruImage
  • HaruImage::getColorSpace »
  • PHP Manual
  • HaruImage
  • Get the number of bits used to describe each color component of the image

HaruImage::getBitsPerComponent

(PECL haru >= 0.0.1)

HaruImage::getBitsPerComponent — Get the number of bits used to describe each color component of the image

Description

HaruImage::getBitsPerComponent ( void ) : int

Gets the number of bits used to describe each color component of the image.

Parameters

This function has no parameters.

Return Values

Returns the number of bits used to describe each color component of the image.

Errors/Exceptions

Throws a HaruException on error.


Get the name of the color space

  • « HaruImage::getBitsPerComponent
  • HaruImage::getHeight »
  • PHP Manual
  • HaruImage
  • Get the name of the color space

HaruImage::getColorSpace

(PECL haru >= 0.0.1)

HaruImage::getColorSpace — Get the name of the color space

Description

HaruImage::getColorSpace ( void ) : string

Get the name of the color space.

Parameters

This function has no parameters.

Return Values

Returns the name of the color space of the image. The name is one of the following values:

  • "DeviceGray"
  • "DeviceRGB"
  • "DeviceCMYK"
  • "Indexed"

Errors/Exceptions

Throws a HaruException on error.


Get the height of the image

  • « HaruImage::getColorSpace
  • HaruImage::getSize »
  • PHP Manual
  • HaruImage
  • Get the height of the image

HaruImage::getHeight

(PECL haru >= 0.0.1)

HaruImage::getHeight — Get the height of the image

Description

HaruImage::getHeight ( void ) : int

Get the height of the image.

Parameters

This function has no parameters.

Return Values

Returns the height of the image.

Errors/Exceptions

Throws a HaruException on error.


Get size of the image

  • « HaruImage::getHeight
  • HaruImage::getWidth »
  • PHP Manual
  • HaruImage
  • Get size of the image

HaruImage::getSize

(PECL haru >= 0.0.1)

HaruImage::getSize — Get size of the image

Description

HaruImage::getSize ( void ) : array

Get the size of the image.

Parameters

This function has no parameters.

Return Values

Returns an array with two elements: width and height, which contain appropriate dimensions of the image.

Errors/Exceptions

Throws a HaruException on error.


Get the width of the image

  • « HaruImage::getSize
  • HaruImage::setColorMask »
  • PHP Manual
  • HaruImage
  • Get the width of the image

HaruImage::getWidth

(PECL haru >= 0.0.1)

HaruImage::getWidth — Get the width of the image

Description

HaruImage::getWidth ( void ) : int

Get the width of the image.

Parameters

This function has no parameters.

Return Values

Returns the width of the image.

Errors/Exceptions

Throws a HaruException on error.


Set the color mask of the image

  • « HaruImage::getWidth
  • HaruImage::setMaskImage »
  • PHP Manual
  • HaruImage
  • Set the color mask of the image

HaruImage::setColorMask

(PECL haru >= 0.0.1)

HaruImage::setColorMask — Set the color mask of the image

Description

HaruImage::setColorMask ( int $rmin , int $rmax , int $gmin , int $gmax , int $bmin , int $bmax ) : bool

Defines the transparent color of the image using the RGB range values. The color within the range is displayed as a transparent color. The color space of the image must be RGB.

Parameters

rmin

The lower limit of red. Must be between 0 and 255.

rmax

The upper limit of red. Must be between 0 and 255.

gmin

The lower limit of green. Must be between 0 and 255.

gmax

The upper limit of green. Must be between 0 and 255.

bmin

The lower limit of blue. Must be between 0 and 255.

bmax

The upper limit of blue. Must be between 0 and 255.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Set the image mask

  • « HaruImage::setColorMask
  • HaruEncoder »
  • PHP Manual
  • HaruImage
  • Set the image mask

HaruImage::setMaskImage

(PECL haru >= 0.0.1)

HaruImage::setMaskImage — Set the image mask

Description

HaruImage::setMaskImage ( object $mask_image ) : bool

Sets the image used as image-mask. It must be 1bit gray-scale color image.

Parameters

mask_image

A valid HaruImage instance.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


The HaruEncoder class

(PECL haru >= 0.0.1)

Introduction

Haru PDF Encoder Class.

Class synopsis

HaruEncoder {
/* Methods */
getByteType ( string $text , int $index ) : int
getType ( void ) : int
getUnicode ( int $character ) : int
getWritingMode ( void ) : int
}

Predefined Constants

Type | Name | Description
int | HaruEncoder::TYPE_SINGLE_BYTE |
int | HaruEncoder::TYPE_DOUBLE_BYTE |
int | HaruEncoder::TYPE_UNINITIALIZED |
int | HaruEncoder::UNKNOWN |
int | HaruEncoder::WMODE_HORIZONTAL |
int | HaruEncoder::WMODE_VERTICAL |
int | HaruEncoder::BYTE_TYPE_SINGLE |
int | HaruEncoder::BYTE_TYPE_LEAD |
int | HaruEncoder::BYTE_TYPE_TRAIL |
int | HaruEncoder::BYTE_TYPE_UNKNOWN |

Table of Contents

  • HaruEncoder::getByteType — Get the type of the byte in the text
  • HaruEncoder::getType — Get the type of the encoder
  • HaruEncoder::getUnicode — Convert the specified character to unicode
  • HaruEncoder::getWritingMode — Get the writing mode of the encoder


Get the type of the byte in the text

  • « HaruEncoder
  • HaruEncoder::getType »
  • PHP Manual
  • HaruEncoder
  • Get the type of the byte in the text

HaruEncoder::getByteType

(PECL haru >= 0.0.1)

HaruEncoder::getByteType — Get the type of the byte in the text

Description

HaruEncoder::getByteType ( string $text , int $index ) : int

Get the type of the byte in the text.

Parameters

text

The text.

index

The position in the text.

Return Values

Returns the type of the byte in the text on the specified position. The result is one of the following values:

  • HaruEncoder::BYTE_TYPE_SINGLE - single byte character.
  • HaruEncoder::BYTE_TYPE_LEAD - lead byte of a double-byte character.
  • HaruEncoder::BYTE_TYPE_TRAIL - trailing byte of a double-byte character.
  • HaruEncoder::BYTE_TYPE_UNKNOWN - invalid encoder or cannot detect the byte type.

Errors/Exceptions

Throws a HaruException on error.


Get the type of the encoder

  • « HaruEncoder::getByteType
  • HaruEncoder::getUnicode »
  • PHP Manual
  • HaruEncoder
  • Get the type of the encoder

HaruEncoder::getType

(PECL haru >= 0.0.1)

HaruEncoder::getType — Get the type of the encoder

Description

HaruEncoder::getType ( void ) : int

Get the type of the encoder.

Parameters

This function has no parameters.

Return Values

Returns the type of the encoder. The result is one of the following values:

  • HaruEncoder::TYPE_SINGLE_BYTE - the encoder is for single byte characters.
  • HaruEncoder::TYPE_DOUBLE_BYTE - the encoder is for multibyte characters.
  • HaruEncoder::TYPE_UNINITIALIZED - the encoder is not initialized.
  • HaruEncoder::UNKNOWN - the encoder is invalid.

Errors/Exceptions

Throws a HaruException on error.


Convert the specified character to unicode

  • « HaruEncoder::getType
  • HaruEncoder::getWritingMode »
  • PHP Manual
  • HaruEncoder
  • Convert the specified character to unicode

HaruEncoder::getUnicode

(PECL haru >= 0.0.1)

HaruEncoder::getUnicode — Convert the specified character to unicode

Description

HaruEncoder::getUnicode ( int $character ) : int

Converts the specified character to unicode.

Parameters

character

The character code to convert.

Return Values

Errors/Exceptions

Throws a HaruException on error.


Get the writing mode of the encoder

  • « HaruEncoder::getUnicode
  • HaruOutline »
  • PHP Manual
  • HaruEncoder
  • Get the writing mode of the encoder

HaruEncoder::getWritingMode

(PECL haru >= 0.0.1)

HaruEncoder::getWritingMode — Get the writing mode of the encoder

Description

HaruEncoder::getWritingMode ( void ) : int

Get the writing mode of the encoder.

Parameters

This function has no parameters.

Return Values

Returns the writing mode of the encoder. The result value is on of the following:

  • HaruEncoder::WMODE_HORIZONTAL - horizontal writing mode.
  • HaruEncoder::WMODE_VERTICAL - vertical writing mode.

Errors/Exceptions

Throws a HaruException on error.


The HaruOutline class

(PECL haru >= 0.0.1)

Introduction

Haru PDF Outline Class.

Class synopsis

HaruOutline {
/* Methods */
setDestination ( object $destination ) : bool
setOpened ( bool $opened ) : bool
}

Table of Contents

  • HaruOutline::setDestination — Set the destination for the outline
  • HaruOutline::setOpened — Set the initial state of the outline


Set the destination for the outline

  • « HaruOutline
  • HaruOutline::setOpened »
  • PHP Manual
  • HaruOutline
  • Set the destination for the outline

HaruOutline::setDestination

(PECL haru >= 0.0.1)

HaruOutline::setDestination — Set the destination for the outline

Description

HaruOutline::setDestination ( object $destination ) : bool

Sets a destination object which becomes a target to jump to when the outline is clicked.

Parameters

destination

A valid HaruDestination instance.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Set the initial state of the outline

  • « HaruOutline::setDestination
  • HaruAnnotation »
  • PHP Manual
  • HaruOutline
  • Set the initial state of the outline

HaruOutline::setOpened

(PECL haru >= 0.0.1)

HaruOutline::setOpened — Set the initial state of the outline

Description

HaruOutline::setOpened ( bool $opened ) : bool

Defines whether this node is opened or not when the outline is displayed for the first time.

Parameters

opened

TRUE means open, FALSE - closed.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


The HaruAnnotation class

(PECL haru >= 0.0.1)

Introduction

Haru PDF Annotation Class.

Class synopsis

HaruAnnotation {
/* Methods */
setBorderStyle ( float $width , int $dash_on , int $dash_off ) : bool
setHighlightMode ( int $mode ) : bool
setIcon ( int $icon ) : bool
setOpened ( bool $opened ) : bool
}

Predefined Constants

Type | Name | Description
int | HaruAnnotation::NO_HIGHLIGHT |
int | HaruAnnotation::INVERT_BOX |
int | HaruAnnotation::INVERT_BORDER |
int | HaruAnnotation::DOWN_APPEARANCE |
int | HaruAnnotation::ICON_COMMENT |
int | HaruAnnotation::ICON_KEY |
int | HaruAnnotation::ICON_NOTE |
int | HaruAnnotation::ICON_HELP |
int | HaruAnnotation::ICON_NEW_PARAGRAPH |
int | HaruAnnotation::ICON_PARAGRAPH |
int | HaruAnnotation::ICON_INSERT |

Table of Contents

  • HaruAnnotation::setBorderStyle — Set the border style of the annotation
  • HaruAnnotation::setHighlightMode — Set the highlighting mode of the annotation
  • HaruAnnotation::setIcon — Set the icon style of the annotation
  • HaruAnnotation::setOpened — Set the initial state of the annotation


Set the border style of the annotation

  • « HaruAnnotation
  • HaruAnnotation::setHighlightMode »
  • PHP Manual
  • HaruAnnotation
  • Set the border style of the annotation

HaruAnnotation::setBorderStyle

(PECL haru >= 0.0.1)

HaruAnnotation::setBorderStyle — Set the border style of the annotation

Description

HaruAnnotation::setBorderStyle ( float $width , int $dash_on , int $dash_off ) : bool

Defines the style of the border of the annotation. This function may be used with link annotations only.

Parameters

width

The width of the border line.

dash_on

The dash style.

dash_off

The dash style.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Set the highlighting mode of the annotation

  • « HaruAnnotation::setBorderStyle
  • HaruAnnotation::setIcon »
  • PHP Manual
  • HaruAnnotation
  • Set the highlighting mode of the annotation

HaruAnnotation::setHighlightMode

(PECL haru >= 0.0.1)

HaruAnnotation::setHighlightMode — Set the highlighting mode of the annotation

Description

HaruAnnotation::setHighlightMode ( int $mode ) : bool

Defines the appearance of the annotation when clicked. This function may be used with link annotations only.

Parameters

mode

The highlighting mode of the annotation. Can take only these values:

  • HaruAnnotation::NO_HIGHLIGHT - no highlighting.
  • HaruAnnotation::INVERT_BOX - invert the contents of the annotation.
  • HaruAnnotation::INVERT_BORDER - invert the border of the annotation.
  • HaruAnnotation::DOWN_APPEARANCE - dent the annotation.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Set the icon style of the annotation

  • « HaruAnnotation::setHighlightMode
  • HaruAnnotation::setOpened »
  • PHP Manual
  • HaruAnnotation
  • Set the icon style of the annotation

HaruAnnotation::setIcon

(PECL haru >= 0.0.1)

HaruAnnotation::setIcon — Set the icon style of the annotation

Description

HaruAnnotation::setIcon ( int $icon ) : bool

Defines the style of the annotation icon. This function may be used with text annotations only.

Parameters

icon

The style of the icon. Can take only these values:

  • HaruAnnotation::ICON_COMMENT
  • HaruAnnotation::ICON_KEY
  • HaruAnnotation::ICON_NOTE
  • HaruAnnotation::ICON_HELP
  • HaruAnnotation::ICON_NEW_PARAGRAPH
  • HaruAnnotation::ICON_PARAGRAPH
  • HaruAnnotation::ICON_INSERT

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Set the initial state of the annotation

  • « HaruAnnotation::setIcon
  • HaruDestination »
  • PHP Manual
  • HaruAnnotation
  • Set the initial state of the annotation

HaruAnnotation::setOpened

(PECL haru >= 0.0.1)

HaruAnnotation::setOpened — Set the initial state of the annotation

Description

HaruAnnotation::setOpened ( bool $opened ) : bool

Defines whether the annotation is initially displayed open. This function may be used with text annotations only.

Parameters

opened

TRUE means the annotation is initially displayed open, FALSE - means it's closed.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


The HaruDestination class

(PECL haru >= 0.0.1)

Introduction

Haru PDF Destination Class.

Class synopsis

HaruDestination {
/* Methods */
setFit ( void ) : bool
setFitB ( void ) : bool
setFitBH ( float $top ) : bool
setFitBV ( float $left ) : bool
setFitH ( float $top ) : bool
setFitR ( float $left , float $bottom , float $right , float $top ) : bool
setFitV ( float $left ) : bool
setXYZ ( float $left , float $top , float $zoom ) : bool
}

Table of Contents

  • HaruDestination::setFit — Set the appearance of the page to fit the window
  • HaruDestination::setFitB — Set the appearance of the page to fit the bounding box of the page within the window
  • HaruDestination::setFitBH — Set the appearance of the page to fit the width of the bounding box
  • HaruDestination::setFitBV — Set the appearance of the page to fit the height of the boudning box
  • HaruDestination::setFitH — Set the appearance of the page to fit the window width
  • HaruDestination::setFitR — Set the appearance of the page to fit the specified rectangle
  • HaruDestination::setFitV — Set the appearance of the page to fit the window height
  • HaruDestination::setXYZ — Set the appearance of the page


Set the appearance of the page to fit the window

  • « HaruDestination
  • HaruDestination::setFitB »
  • PHP Manual
  • HaruDestination
  • Set the appearance of the page to fit the window

HaruDestination::setFit

(PECL haru >= 0.0.1)

HaruDestination::setFit — Set the appearance of the page to fit the window

Description

HaruDestination::setFit ( void ) : bool

Defines the appearance of the page to fit the window.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Set the appearance of the page to fit the bounding box of the page within the window

  • « HaruDestination::setFit
  • HaruDestination::setFitBH »
  • PHP Manual
  • HaruDestination
  • Set the appearance of the page to fit the bounding box of the page within the window

HaruDestination::setFitB

(PECL haru >= 0.0.1)

HaruDestination::setFitB — Set the appearance of the page to fit the bounding box of the page within the window

Description

HaruDestination::setFitB ( void ) : bool

Defines the appearance of the page to fit the bounding box of the page within the window.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Set the appearance of the page to fit the width of the bounding box

  • « HaruDestination::setFitB
  • HaruDestination::setFitBV »
  • PHP Manual
  • HaruDestination
  • Set the appearance of the page to fit the width of the bounding box

HaruDestination::setFitBH

(PECL haru >= 0.0.1)

HaruDestination::setFitBH — Set the appearance of the page to fit the width of the bounding box

Description

HaruDestination::setFitBH ( float $top ) : bool

Defines the appearance of the page to magnifying to fit the width of the bounding box and setting the top position of the page to the value of top.

Parameters

top

The top coordinates of the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Set the appearance of the page to fit the height of the boudning box

  • « HaruDestination::setFitBH
  • HaruDestination::setFitH »
  • PHP Manual
  • HaruDestination
  • Set the appearance of the page to fit the height of the boudning box

HaruDestination::setFitBV

(PECL haru >= 0.0.1)

HaruDestination::setFitBV — Set the appearance of the page to fit the height of the boudning box

Description

HaruDestination::setFitBV ( float $left ) : bool

Defines the appearance of the page to magnifying to fit the height of the bounding box and setting the left position of the page to the value of left.

Parameters

left

The left coordinates of the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Set the appearance of the page to fit the window width

  • « HaruDestination::setFitBV
  • HaruDestination::setFitR »
  • PHP Manual
  • HaruDestination
  • Set the appearance of the page to fit the window width

HaruDestination::setFitH

(PECL haru >= 0.0.1)

HaruDestination::setFitH — Set the appearance of the page to fit the window width

Description

HaruDestination::setFitH ( float $top ) : bool

Defines the appearance of the page to fit the window width and sets the top position of the page to the value of top.

Parameters

top

The top position of the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Set the appearance of the page to fit the specified rectangle

  • « HaruDestination::setFitH
  • HaruDestination::setFitV »
  • PHP Manual
  • HaruDestination
  • Set the appearance of the page to fit the specified rectangle

HaruDestination::setFitR

(PECL haru >= 0.0.1)

HaruDestination::setFitR — Set the appearance of the page to fit the specified rectangle

Description

HaruDestination::setFitR ( float $left , float $bottom , float $right , float $top ) : bool

Defines the appearance of the page to fit the rectangle by the parameters.

Parameters

left

The left coordinates of the page.

bottom

The bottom coordinates of the page.

right

The right coordinates of the page.

top

The top coordinates of the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Set the appearance of the page to fit the window height

  • « HaruDestination::setFitR
  • HaruDestination::setXYZ »
  • PHP Manual
  • HaruDestination
  • Set the appearance of the page to fit the window height

HaruDestination::setFitV

(PECL haru >= 0.0.1)

HaruDestination::setFitV — Set the appearance of the page to fit the window height

Description

HaruDestination::setFitV ( float $left ) : bool

Defines the appearance of the page to fit the window height.

Parameters

left

The left position of the page.

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Set the appearance of the page

  • « HaruDestination::setFitV
  • Ming »
  • PHP Manual
  • HaruDestination
  • Set the appearance of the page

HaruDestination::setXYZ

(PECL haru >= 0.0.1)

HaruDestination::setXYZ — Set the appearance of the page

Description

HaruDestination::setXYZ ( float $left , float $top , float $zoom ) : bool

Defines the appearance of the page using three parameters: left, top and zoom.

Parameters

left

The left position of the page.

top

The top position of the page.

zoom

The magnification factor. The value must be between 0.08 (8%) and 32 (3200%).

Return Values

Returns TRUE on success.

Errors/Exceptions

Throws a HaruException on error.


Ming (flash)

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • SWFAction Examples
    • SWFSPrite basic examples
  • Ming Functions
    • ming_keypress — Returns the action flag for keyPress(char)
    • ming_setcubicthreshold — Set cubic threshold
    • ming_setscale — Set the global scaling factor
    • ming_setswfcompression — Sets the SWF output compression
    • ming_useconstants — Use constant pool
    • ming_useswfversion — Sets the SWF version
  • SWFAction — The SWFAction class
    • SWFAction::__construct — Creates a new SWFAction
  • SWFBitmap — The SWFBitmap class
    • SWFBitmap::__construct — Loads Bitmap object
    • SWFBitmap::getHeight — Returns the bitmap's height
    • SWFBitmap::getWidth — Returns the bitmap's width
  • SWFButton — The SWFButton class
    • SWFButton::addAction — Adds an action
    • SWFButton::addASound — Associates a sound with a button transition
    • SWFButton::addShape — Adds a shape to a button
    • SWFButton::__construct — Creates a new Button
    • SWFButton::setAction — Sets the action
    • SWFButton::setDown — Alias for addShape(shape, SWFBUTTON_DOWN)
    • SWFButton::setHit — Alias for addShape(shape, SWFBUTTON_HIT)
    • SWFButton::setMenu — Enable track as menu button behaviour
    • SWFButton::setOver — Alias for addShape(shape, SWFBUTTON_OVER)
    • SWFButton::setUp — Alias for addShape(shape, SWFBUTTON_UP)
  • SWFDisplayItem — The SWFDisplayItem class
    • SWFDisplayItem::addAction — Adds this SWFAction to the given SWFSprite instance
    • SWFDisplayItem::addColor — Adds the given color to this item's color transform
    • SWFDisplayItem::endMask — Another way of defining a MASK layer
    • SWFDisplayItem::getRot — Description
    • SWFDisplayItem::getX — Description
    • SWFDisplayItem::getXScale — Description
    • SWFDisplayItem::getXSkew — Description
    • SWFDisplayItem::getY — Description
    • SWFDisplayItem::getYScale — Description
    • SWFDisplayItem::getYSkew — Description
    • SWFDisplayItem::move — Moves object in relative coordinates
    • SWFDisplayItem::moveTo — Moves object in global coordinates
    • SWFDisplayItem::multColor — Multiplies the item's color transform
    • SWFDisplayItem::remove — Removes the object from the movie
    • SWFDisplayItem::rotate — Rotates in relative coordinates
    • SWFDisplayItem::rotateTo — Rotates the object in global coordinates
    • SWFDisplayItem::scale — Scales the object in relative coordinates
    • SWFDisplayItem::scaleTo — Scales the object in global coordinates
    • SWFDisplayItem::setDepth — Sets z-order
    • SWFDisplayItem::setMaskLevel — Defines a MASK layer at level
    • SWFDisplayItem::setMatrix — Sets the item's transform matrix
    • SWFDisplayItem::setName — Sets the object's name
    • SWFDisplayItem::setRatio — Sets the object's ratio
    • SWFDisplayItem::skewX — Sets the X-skew
    • SWFDisplayItem::skewXTo — Sets the X-skew
    • SWFDisplayItem::skewY — Sets the Y-skew
    • SWFDisplayItem::skewYTo — Sets the Y-skew
  • SWFFill — The SWFFill class
    • SWFFill::moveTo — Moves fill origin
    • SWFFill::rotateTo — Sets fill's rotation
    • SWFFill::scaleTo — Sets fill's scale
    • SWFFill::skewXTo — Sets fill x-skew
    • SWFFill::skewYTo — Sets fill y-skew
  • SWFFont — The SWFFont class
    • SWFFont::__construct — Loads a font definition
    • SWFFont::getAscent — Returns the ascent of the font, or 0 if not available
    • SWFFont::getDescent — Returns the descent of the font, or 0 if not available
    • SWFFont::getLeading — Returns the leading of the font, or 0 if not available
    • SWFFont::getShape — Returns the glyph shape of a char as a text string
    • SWFFont::getUTF8Width — Calculates the width of the given string in this font at full height
    • SWFFont::getWidth — Returns the string's width
  • SWFFontChar — The SWFFontChar class
    • SWFFontChar::addChars — Adds characters to a font for exporting font
    • SWFFontChar::addUTF8Chars — Adds characters to a font for exporting font
  • SWFGradient — The SWFGradient class
    • SWFGradient::addEntry — Adds an entry to the gradient list
    • SWFGradient::__construct — Creates a gradient object
  • SWFMorph — The SWFMorph class
    • SWFMorph::__construct — Creates a new SWFMorph object
    • SWFMorph::getShape1 — Gets a handle to the starting shape
    • SWFMorph::getShape2 — Gets a handle to the ending shape
  • SWFMovie — The SWFMovie class
    • SWFMovie::add — Adds any type of data to a movie
    • SWFMovie::addExport — Description
    • SWFMovie::addFont — Description
    • SWFMovie::__construct — Creates a new movie object, representing an SWF version 4 movie
    • SWFMovie::importChar — Description
    • SWFMovie::importFont — Description
    • SWFMovie::labelFrame — Labels a frame
    • SWFMovie::nextFrame — Moves to the next frame of the animation
    • SWFMovie::output — Dumps your lovingly prepared movie out
    • SWFMovie::remove — Removes the object instance from the display list
    • SWFMovie::save — Saves the SWF movie in a file
    • SWFMovie::saveToFile — Description
    • SWFMovie::setbackground — Sets the background color
    • SWFMovie::setDimension — Sets the movie's width and height
    • SWFMovie::setFrames — Sets the total number of frames in the animation
    • SWFMovie::setRate — Sets the animation's frame rate
    • SWFMovie::startSound — Description
    • SWFMovie::stopSound — Description
    • SWFMovie::streamMP3 — Streams a MP3 file
    • SWFMovie::writeExports — Description
  • SWFPrebuiltClip — The SWFPrebuiltClip class
    • SWFPrebuiltClip::__construct — Returns a SWFPrebuiltClip object
  • SWFShape — The SWFShape class
    • SWFShape::addFill — Adds a solid fill to the shape
    • SWFShape::__construct — Creates a new shape object
    • SWFShape::drawArc — Draws an arc of radius r centered at the current location, from angle startAngle to angle endAngle measured clockwise from 12 o'clock
    • SWFShape::drawCircle — Draws a circle of radius r centered at the current location, in a counter-clockwise fashion
    • SWFShape::drawCubic — Draws a cubic bezier curve using the current position and the three given points as control points
    • SWFShape::drawCubicTo — Draws a cubic bezier curve using the current position and the three given points as control points
    • SWFShape::drawCurve — Draws a curve (relative)
    • SWFShape::drawCurveTo — Draws a curve
    • SWFShape::drawGlyph — Draws the first character in the given string into the shape using the glyph definition from the given font
    • SWFShape::drawLine — Draws a line (relative)
    • SWFShape::drawLineTo — Draws a line
    • SWFShape::movePen — Moves the shape's pen (relative)
    • SWFShape::movePenTo — Moves the shape's pen
    • SWFShape::setLeftFill — Sets left rasterizing color
    • SWFShape::setLine — Sets the shape's line style
    • SWFShape::setRightFill — Sets right rasterizing color
  • SWFSound — The SWFSound class
    • SWFSound::__construct — Returns a new SWFSound object from given file
  • SWFSoundInstance — The SWFSoundInstance class
    • SWFSoundInstance::loopCount — Description
    • SWFSoundInstance::loopInPoint — Description
    • SWFSoundInstance::loopOutPoint — Description
    • SWFSoundInstance::noMultiple — Description
  • SWFSprite — The SWFSprite class
    • SWFSprite::add — Adds an object to a sprite
    • SWFSprite::__construct — Creates a movie clip (a sprite)
    • SWFSprite::labelFrame — Labels frame
    • SWFSprite::nextFrame — Moves to the next frame of the animation
    • SWFSprite::remove — Removes an object to a sprite
    • SWFSprite::setFrames — Sets the total number of frames in the animation
    • SWFSprite::startSound — Description
    • SWFSprite::stopSound — Description
  • SWFText — The SWFText class
    • SWFText::addString — Draws a string
    • SWFText::addUTF8String — Writes the given text into this SWFText object at the current pen position, using the current font, height, spacing, and color
    • SWFText::__construct — Creates a new SWFText object
    • SWFText::getAscent — Returns the ascent of the current font at its current size, or 0 if not available
    • SWFText::getDescent — Returns the descent of the current font at its current size, or 0 if not available
    • SWFText::getLeading — Returns the leading of the current font at its current size, or 0 if not available
    • SWFText::getUTF8Width — Calculates the width of the given string in this text objects current font and size
    • SWFText::getWidth — Computes string's width
    • SWFText::moveTo — Moves the pen
    • SWFText::setColor — Sets the current text color
    • SWFText::setFont — Sets the current font
    • SWFText::setHeight — Sets the current font height
    • SWFText::setSpacing — Sets the current font spacing
  • SWFTextField — The SWFTextField class
    • SWFTextField::addChars — Adds characters to a font that will be available within a textfield
    • SWFTextField::addString — Concatenates the given string to the text field
    • SWFTextField::align — Sets the text field alignment
    • SWFTextField::__construct — Creates a text field object
    • SWFTextField::setBounds — Sets the text field width and height
    • SWFTextField::setColor — Sets the color of the text field
    • SWFTextField::setFont — Sets the text field font
    • SWFTextField::setHeight — Sets the font height of this text field font
    • SWFTextField::setIndentation — Sets the indentation of the first line
    • SWFTextField::setLeftMargin — Sets the left margin width of the text field
    • SWFTextField::setLineSpacing — Sets the line spacing of the text field
    • SWFTextField::setMargins — Sets the margins width of the text field
    • SWFTextField::setName — Sets the variable name
    • SWFTextField::setPadding — Sets the padding of this textfield
    • SWFTextField::setRightMargin — Sets the right margin width of the text field
  • SWFVideoStream — The SWFVideoStream class
    • SWFVideoStream::__construct — Returns a SWFVideoStream object
    • SWFVideoStream::getNumFrames — Returns the number of frames in the video
    • SWFVideoStream::setDimension — Sets video dimension


Introduction

First of all: Ming is not an acronym. Ming is an open-source (LGPL) library which allows you to create SWF ("Flash") format movies. Ming supports almost all of Flash 4's features, including: shapes, gradients, bitmaps (pngs and jpegs), morphs ("shape tweens"), text, buttons, actions, sprites ("movie clips"), streaming mp3, and color transforms --the only thing that's missing is sound events.

Note that all values specifying length, distance, size, etc. are in "twips", twenty units per pixel. That's pretty much arbitrary, though, since the player scales the movie to whatever pixel size is specified in the embed/object tag, or the entire frame if not embedded.

Ming offers a number of advantages over the existing PHP/libswf module. You can use Ming anywhere you can compile the code, whereas libswf is closed-source and only available for a few platforms, Windows not one of them. Ming provides some insulation from the mundane details of the SWF file format, wrapping the movie elements in PHP objects. Also, Ming is still being maintained; if there's a feature that you want to see, just let us know at » http://www.libming.org/.

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.

Note:

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.3.0.


Requirements

To use Ming with PHP, you first need to build and install the Ming library. Source code and installation instructions are available at the Ming home page: » http://www.libming.org/ along with examples, a small tutorial, and the latest news.

Download the ming archive. Unpack the archive. Go in the Ming directory. make. make install.

This will build libming.so and install it into /usr/lib/, and copy ming.h into /usr/include/. Edit the PREFIX= line in the Makefile to change the installation directory.


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/ming.

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.3.0

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.

MING_NEW (integer)
MING_ZLIB (integer)
SWFBUTTON_HIT (integer)
SWFBUTTON_DOWN (integer)
SWFBUTTON_OVER (integer)
SWFBUTTON_UP (integer)
SWFBUTTON_MOUSEUPOUTSIDE (integer)
SWFBUTTON_DRAGOVER (integer)
SWFBUTTON_DRAGOUT (integer)
SWFBUTTON_MOUSEUP (integer)
SWFBUTTON_MOUSEDOWN (integer)
SWFBUTTON_MOUSEOUT (integer)
SWFBUTTON_MOUSEOVER (integer)
SWFFILL_RADIAL_GRADIENT (integer)
SWFFILL_LINEAR_GRADIENT (integer)
SWFFILL_TILED_BITMAP (integer)
SWFFILL_CLIPPED_BITMAP (integer)
SWFTEXTFIELD_HASLENGTH (integer)
SWFTEXTFIELD_NOEDIT (integer)
SWFTEXTFIELD_PASSWORD (integer)
SWFTEXTFIELD_MULTILINE (integer)
SWFTEXTFIELD_WORDWRAP (integer)
SWFTEXTFIELD_DRAWBOX (integer)
SWFTEXTFIELD_NOSELECT (integer)
SWFTEXTFIELD_HTML (integer)
SWFTEXTFIELD_ALIGN_LEFT (integer)
SWFTEXTFIELD_ALIGN_RIGHT (integer)
SWFTEXTFIELD_ALIGN_CENTER (integer)
SWFTEXTFIELD_ALIGN_JUSTIFY (integer)
SWFACTION_ONLOAD (integer)
SWFACTION_ENTERFRAME (integer)
SWFACTION_UNLOAD (integer)
SWFACTION_MOUSEMOVE (integer)
SWFACTION_MOUSEDOWN (integer)
SWFACTION_MOUSEUP (integer)
SWFACTION_KEYDOWN (integer)
SWFACTION_KEYUP (integer)
SWFACTION_DATA (integer)


  • « Predefined Constants
  • SWFAction Examples »
  • PHP Manual
  • Ming
  • Examples

Examples

Table of Contents

  • SWFAction Examples
  • SWFSPrite basic examples


SWFAction Examples

This simple example will move the red square across the window.

Example #1 swfaction() example

<?php
  $s = new SWFShape();
  $f = $s->addFill(0xff, 0, 0);
  $s->setRightFill($f);

  $s->movePenTo(-500, -500);
  $s->drawLineTo(500, -500);
  $s->drawLineTo(500, 500);
  $s->drawLineTo(-500, 500);
  $s->drawLineTo(-500, -500);

  $p = new SWFSprite();
  $i = $p->add($s);
  $i->setDepth(1);
  $p->nextFrame();

  for ($n=0; $n<5; ++$n) {
    $i->rotate(-15);
    $p->nextFrame();
  }

  $m = new SWFMovie();
  $m->setBackground(0xff, 0xff, 0xff);
  $m->setDimension(6000, 4000);

  $i = $m->add($p);
  $i->setDepth(1);
  $i->moveTo(-500,2000);
  $i->setName("box");

  $m->add(new SWFAction("/box.x += 3;"));
  $m->nextFrame();
  $m->add(new SWFAction("gotoFrame(0); play();"));
  $m->nextFrame();

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

This simple example tracks down your mouse on the screen.

Example #2 swfaction() example

<?php

  $m = new SWFMovie();
  $m->setRate(36.0);
  $m->setDimension(1200, 800);
  $m->setBackground(0, 0, 0);

  /* mouse tracking sprite - empty, but follows mouse so we can
     get its x and y coordinates */

  $i = $m->add(new SWFSprite());
  $i->setName('mouse');

  $m->add(new SWFAction("
    startDrag('/mouse', 1); /* '1' means lock sprite to the mouse */
  "));

  /* might as well turn off antialiasing, since these are just squares. */

  $m->add(new SWFAction("
    this.quality = 0;
  "));

  /* morphing box */
  $r = new SWFMorph();
  $s = $r->getShape1();

  /* Note this is backwards from normal shapes.  No idea why. */
  $s->setLeftFill($s->addFill(0xff, 0xff, 0xff));
  $s->movePenTo(-40, -40);
  $s->drawLine(80, 0);
  $s->drawLine(0, 80);
  $s->drawLine(-80, 0);
  $s->drawLine(0, -80);

  $s = $r->getShape2();

  $s->setLeftFill($s->addFill(0x00, 0x00, 0x00));
  $s->movePenTo(-1, -1);
  $s->drawLine(2, 0);
  $s->drawLine(0, 2);
  $s->drawLine(-2, 0);
  $s->drawLine(0, -2);

  /* sprite container for morphing box -
     this is just a timeline w/ the box morphing */

  $box = new SWFSprite();
  $box->add(new SWFAction("
    stop();
  "));
  $i = $box->add($r);

  for ($n=0; $n<=20; ++$n) {
    $i->setRatio($n/20);
    $box->nextFrame();
  }

  /* this container sprite allows us to use the same action code many times */

  $cell = new SWFSprite();
  $i = $cell->add($box);
  $i->setName('box');

  $cell->add(new SWFAction("

    setTarget('box');

    /* ...x means the x coordinate of the parent, i.e. (..).x */
    dx = (/mouse.x + random(6)-3 - ...x)/5;
    dy = (/mouse.y + random(6)-3 - ...y)/5;
    gotoFrame(int(dx*dx + dy*dy));

  "));

  $cell->nextFrame();
  $cell->add(new SWFAction("

    gotoFrame(0);
    play();

  "));

  $cell->nextFrame();

  /* finally, add a bunch of the cells to the movie */

  for ($x=0; $x<12; ++$x) {
    for ($y=0; $y<8; ++$y) {
      $i = $m->add($cell);
      $i->moveTo(100*$x+50, 100*$y+50);
    }
  }

  $m->nextFrame();

  $m->add(new SWFAction("

    gotoFrame(1);
    play();

  "));

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

Same as above, but with nice colored balls...

Example #3 swfaction() example

<?php

  $m = new SWFMovie();
  $m->setDimension(11000, 8000);
  $m->setBackground(0x00, 0x00, 0x00);

  $m->add(new SWFAction("

this.quality = 0;
/frames.visible = 0;
startDrag('/mouse', 1);

  "));

  // mouse tracking sprite
  $t = new SWFSprite();
  $i = $m->add($t);
  $i->setName('mouse');

  $g = new SWFGradient();
  $g->addEntry(0, 0xff, 0xff, 0xff, 0xff);
  $g->addEntry(0.1, 0xff, 0xff, 0xff, 0xff);
  $g->addEntry(0.5, 0xff, 0xff, 0xff, 0x5f);
  $g->addEntry(1.0, 0xff, 0xff, 0xff, 0);

  // gradient shape thing
  $s = new SWFShape();
  $f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
  $f->scaleTo(0.03);
  $s->setRightFill($f);
  $s->movePenTo(-600, -600);
  $s->drawLine(1200, 0);
  $s->drawLine(0, 1200);
  $s->drawLine(-1200, 0);
  $s->drawLine(0, -1200);

  // need to make this a sprite so we can multColor it
  $p = new SWFSprite();
  $p->add($s);
  $p->nextFrame();

  // put the shape in here, each frame a different color
  $q = new SWFSprite();
  $q->add(new SWFAction("gotoFrame(random(7)+1); stop();"));
  $i = $q->add($p);

  $i->multColor(1.0, 1.0, 1.0);
  $q->nextFrame();
  $i->multColor(1.0, 0.5, 0.5);
  $q->nextFrame();
  $i->multColor(1.0, 0.75, 0.5);
  $q->nextFrame();
  $i->multColor(1.0, 1.0, 0.5);
  $q->nextFrame();
  $i->multColor(0.5, 1.0, 0.5);
  $q->nextFrame();
  $i->multColor(0.5, 0.5, 1.0);
  $q->nextFrame();
  $i->multColor(1.0, 0.5, 1.0);
  $q->nextFrame();

  // finally, this one contains the action code
  $p = new SWFSprite();
  $i = $p->add($q);
  $i->setName('frames');
  $p->add(new SWFAction("

dx = (/:mousex-/:lastx)/3 + random(10)-5;
dy = (/:mousey-/:lasty)/3;
x = /:mousex;
y = /:mousey;
alpha = 100;

  "));
  $p->nextFrame();

  $p->add(new SWFAction("

this.x = x;
this.y = y;
this.alpha = alpha;
x += dx;
y += dy;
dy += 3;
alpha -= 8;

  "));
  $p->nextFrame();

  $p->add(new SWFAction("prevFrame(); play();"));
  $p->nextFrame();

  $i = $m->add($p);
  $i->setName('frames');
  $m->nextFrame();

  $m->add(new SWFAction("

lastx = mousex;
lasty = mousey;
mousex = /mouse.x;
mousey = /mouse.y;

++num;

if (num == 11)
  num = 1;

removeClip('char' & num);
duplicateClip(/frames, 'char' & num, num);

  "));

  $m->nextFrame();
  $m->add(new SWFAction("prevFrame(); play();"));

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>


SWFSPrite basic examples

This simple example will spin gracefully a big red square.

Example #1 swfsprite() example

<?php
$s = new SWFShape();
$s->setRightFill($s->addFill(0xff, 0, 0));
$s->movePenTo(-500, -500);
$s->drawLineTo(500, -500);
$s->drawLineTo(500, 500);
$s->drawLineTo(-500, 500);
$s->drawLineTo(-500, -500);

$p = new SWFSprite();
$i = $p->add($s);
$p->nextFrame();
$i->rotate(15);
$p->nextFrame();
$i->rotate(15);
$p->nextFrame();
$i->rotate(15);
$p->nextFrame();
$i->rotate(15);
$p->nextFrame();
$i->rotate(15);
$p->nextFrame();

$m = new SWFMovie();
$i = $m->add($p);
$i->moveTo(1500, 1000);
$i->setName("blah");

$m->setBackground(0xff, 0xff, 0xff);
$m->setDimension(3000, 2000);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>


Ming Functions

Table of Contents

  • ming_keypress — Returns the action flag for keyPress(char)
  • ming_setcubicthreshold — Set cubic threshold
  • ming_setscale — Set the global scaling factor
  • ming_setswfcompression — Sets the SWF output compression
  • ming_useconstants — Use constant pool
  • ming_useswfversion — Sets the SWF version


Returns the action flag for keyPress(char)

  • « Ming Functions
  • ming_setcubicthreshold »
  • PHP Manual
  • Ming Functions
  • Returns the action flag for keyPress(char)

ming_keypress

(PHP 5 < 5.3.0, PECL ming SVN)

ming_keypress — Returns the action flag for keyPress(char)

Description

ming_keypress ( string $char ) : int
Warning

This function is currently not documented; only its argument list is available.


Set cubic threshold

  • « ming_keypress
  • ming_setscale »
  • PHP Manual
  • Ming Functions
  • Set cubic threshold

ming_setcubicthreshold

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PECL ming SVN)

ming_setcubicthreshold — Set cubic threshold

Description

ming_setcubicthreshold ( int $threshold ) : void

Sets the threshold error for drawing cubic beziers.

Parameters

threshold

The Threshold. Lower is more accurate, hence larger file size.

Return Values

No value is returned.


Set the global scaling factor

  • « ming_setcubicthreshold
  • ming_setswfcompression »
  • PHP Manual
  • Ming Functions
  • Set the global scaling factor

ming_setscale

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PECL ming SVN)

ming_setscale — Set the global scaling factor

Description

ming_setscale ( float $scale ) : void

Sets the scale of the output SWF. Inside the SWF file, coordinates are measured in TWIPS, rather than PIXELS. There are 20 TWIPS in 1 pixel.

Parameters

scale

The scale to be set.

Return Values

No value is returned.


Sets the SWF output compression

  • « ming_setscale
  • ming_useconstants »
  • PHP Manual
  • Ming Functions
  • Sets the SWF output compression

ming_setswfcompression

(PHP 5.2.1-5.3.0, PHP 7, PECL ming SVN)

ming_setswfcompression — Sets the SWF output compression

Description

ming_setswfcompression ( int $level ) : void

Sets the SWF output compression level.

Parameters

level

The new compression level. Should be a value between 1 and 9 inclusive.

Return Values

No value is returned.


Use constant pool

  • « ming_setswfcompression
  • ming_useswfversion »
  • PHP Manual
  • Ming Functions
  • Use constant pool

ming_useconstants

(PHP 5 < 5.3.0, PECL ming SVN)

ming_useconstants — Use constant pool

Description

ming_useconstants ( int $use ) : void
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.


Sets the SWF version

  • « ming_useconstants
  • SWFAction »
  • PHP Manual
  • Ming Functions
  • Sets the SWF version

ming_useswfversion

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ming SVN)

ming_useswfversion — Sets the SWF version

Description

ming_useswfversion ( int $version ) : void

Sets the SWF version to be used in the movie. This affect the bahaviour of Action Script.

Parameters

version

SWF version to use.

Return Values

No value is returned.

Examples

Example #1 ming_useswfversion() example

<?php

$movie = new SWFMovie();
ming_useswfversion(4); // Flash 4

?>


The SWFAction class

(PHP 5 < 5.3.0, PECL ming SVN)

Introduction

SWFAction.

Class synopsis

SWFAction {
/* Methods */
__construct ( string $script )
}

Description

The script syntax is based on the C language, but with a lot taken out- the SWF bytecode machine is just too simpleminded to do a lot of things we might like. For instance, we can't implement function calls without a tremendous amount of hackery because the jump bytecode has a hardcoded offset value. No pushing your calling address to the stack and returning- every function would have to know exactly where to return to.

So what's left? The compiler recognises the following tokens:

  • break
  • for
  • continue
  • if
  • else
  • do
  • while

There is no typed data; all values in the SWF action machine are stored as strings. The following functions can be used in expressions:

time()
Returns the number of milliseconds (?) elapsed since the movie started.
random(seed)
Returns a pseudo-random number in the range 0-seed.
length(expr)
Returns the length of the given expression.
int(number)
Returns the given number rounded down to the nearest integer.
concat(expr, expr)
Returns the concatenation of the given expressions.
ord(expr)
Returns the ASCII code for the given character
chr(num)
Returns the character for the given ASCII code
substr(string, location, length)
Returns the substring of length length at location location of the given string string.

Additionally, the following commands may be used:

duplicateClip(clip, name, depth)
Duplicate the named movie clip (aka sprite). The new movie clip has name name and is at depth depth.
removeClip(expr)
Removes the named movie clip.
trace(expr)
Write the given expression to the trace log. Doubtful that the browser plugin does anything with this.
startDrag(target, lock, [left, top, right, bottom])
Start dragging the movie clip target. The lock argument indicates whether to lock the mouse (?)- use 0 (FALSE) or 1 (TRUE). Optional parameters define a bounding area for the dragging.
stopDrag()
Stop dragging my heart around. And this movie clip, too.
callFrame(expr)
Call the named frame as a function.
getURL(url, target, [method])
Load the given URL into the named target. The target argument corresponds to HTML document targets (such as "_top" or "_blank"). The optional method argument can be POST or GET if you want to submit variables back to the server.
loadMovie(url, target)
Load the given URL into the named target. The target argument can be a frame name (I think), or one of the magical values "_level0" (replaces current movie) or "_level1" (loads new movie on top of current movie).
nextFrame()
Go to the next frame.
prevFrame()
Go to the last (or, rather, previous) frame.
play()
Start playing the movie.
stop()
Stop playing the movie.
toggleQuality()
Toggle between high and low quality.
stopSounds()
Stop playing all sounds.
gotoFrame(num)
Go to frame number num. Frame numbers start at 0.
gotoFrame(name)
Go to the frame named name. Which does a lot of good, since I haven't added frame labels yet.
setTarget(expr)
Sets the context for action. Or so they say- I really have no idea what this does.
And there's one weird extra thing. The expression frameLoaded(num) can be used in if statements and while loops to check if the given frame number has been loaded yet. Well, it's supposed to, anyway, but I've never tested it and I seriously doubt it actually works. You can just use /:framesLoaded instead.

Movie clips (all together now- aka sprites) have properties. You can read all of them (or can you?), you can set some of them, and here they are:

  • x
  • y
  • xScale
  • yScale
  • currentFrame - (read-only)
  • totalFrames - (read-only)
  • alpha - transparency level
  • visible - 1=on, 0=off (?)
  • width - (read-only)
  • height - (read-only)
  • rotation
  • target - (read-only) (???)
  • framesLoaded - (read-only)
  • name
  • dropTarget - (read-only) (???)
  • url - (read-only) (???)
  • highQuality - 1=high, 0=low (?)
  • focusRect - (???)
  • soundBufTime - (???)
So, setting a sprite's x position is as simple as /box.x = 100;. Why the slash in front of the box, though? That's how flash keeps track of the sprites in the movie, just like a Unix filesystem- here it shows that box is at the top level. If the sprite named box had another sprite named biff inside of it, you'd set its x position with /box/biff.x = 100;. At least, I think so; correct me if I'm wrong here.

Table of Contents

  • SWFAction::__construct — Creates a new SWFAction


Creates a new SWFAction

  • « SWFAction
  • SWFBitmap »
  • PHP Manual
  • SWFAction
  • Creates a new SWFAction

SWFAction::__construct

(PHP 5 < 5.3.0, PECL ming SVN)

SWFAction::__construct — Creates a new SWFAction

Description

SWFAction::__construct ( string $script )
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.

Creates a new SWFAction and compiles the given script in it.

Parameters

script

An ActionScript snippet to associate with the SWFAction. See SWFAction for more details.


The SWFBitmap class

(PHP 5 < 5.3.0, PECL ming SVN)

Introduction

SWFBitmap.

Class synopsis

SWFBitmap {
/* Methods */
__construct ( mixed $file [, mixed $alphafile ] )
getHeight ( void ) : float
getWidth ( void ) : float
}

Table of Contents

  • SWFBitmap::__construct — Loads Bitmap object
  • SWFBitmap::getHeight — Returns the bitmap's height
  • SWFBitmap::getWidth — Returns the bitmap's width


Loads Bitmap object

  • « SWFBitmap
  • SWFBitmap::getHeight »
  • PHP Manual
  • SWFBitmap
  • Loads Bitmap object

SWFBitmap::__construct

(PHP 5 < 5.3.0, PECL ming SVN)

SWFBitmap::__construct — Loads Bitmap object

Description

SWFBitmap::__construct ( mixed $file [, mixed $alphafile ] )
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.

Creates the new SWFBitmap object from the given file.

Parameters

For both parameters you can provide a file pointer returned by fopen() or the image data, as a binary string.

file

Note:

We can only deal with baseline (frame 0) jpegs, no baseline optimized or progressive scan jpegs!

You can't import png images directly, though- have to use the png2dbl utility to make a dbl ("define bits lossless") file from the png. The reason for this is that I don't want a dependency on the png library in ming- autoconf should solve this, but that's not set up yet.

alphafile

An MSK file to be used as an alpha mask for a JPEG image.

Examples

Example #1 Importing a DBL file

<?php
$s = new SWFShape();
$f = $s->addFill(new SWFBitmap(file_get_contents("image.dbl")));
$s->setRightFill($f);

$s->drawLine(32, 0);
$s->drawLine(0, 32);
$s->drawLine(-32, 0);
$s->drawLine(0, -32);

$m = new SWFMovie();
$m->setDimension(32, 32);
$m->add($s);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

Example #2 Using an alpha mask

<?php

$s = new SWFShape();

// .msk file generated with "gif2mask" utility
$f = $s->addFill(new SWFBitmap(file_get_contents("alphafill.jpg"), file_get_contents("alphafill.msk")));
$s->setRightFill($f);

$s->drawLine(640, 0);
$s->drawLine(0, 480);
$s->drawLine(-640, 0);
$s->drawLine(0, -480);

$c = new SWFShape();
$c->setRightFill($c->addFill(0x99, 0x99, 0x99));
$c->drawLine(40, 0);
$c->drawLine(0, 40);
$c->drawLine(-40, 0);
$c->drawLine(0, -40);

$m = new SWFMovie();
$m->setDimension(640, 480);
$m->setBackground(0xcc, 0xcc, 0xcc);

// draw checkerboard background
for ($y=0; $y<480; $y+=40) {
  for ($x=0; $x<640; $x+=80) {
    $i = $m->add($c);
    $i->moveTo($x, $y);
  }

  $y+=40;

  for ($x=40; $x<640; $x+=80) {
    $i = $m->add($c);
    $i->moveTo($x, $y);
  }
}

$m->add($s);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>


Returns the bitmap's height

  • « SWFBitmap::__construct
  • SWFBitmap::getWidth »
  • PHP Manual
  • SWFBitmap
  • Returns the bitmap's height

SWFBitmap::getHeight

(PHP 5 < 5.3.0, PECL ming SVN)

SWFBitmap::getHeight — Returns the bitmap's height

Description

SWFBitmap::getHeight ( void ) : float
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.

Returns the bitmap's height.

Return Values

Returns the bitmap height in pixels.

See Also

  • SWFBitmap::getWidth() - Returns the bitmap's width


Returns the bitmap's width

  • « SWFBitmap::getHeight
  • SWFButton »
  • PHP Manual
  • SWFBitmap
  • Returns the bitmap's width

SWFBitmap::getWidth

(PHP 5 < 5.3.0, PECL ming SVN)

SWFBitmap::getWidth — Returns the bitmap's width

Description

SWFBitmap::getWidth ( void ) : float
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.

Returns the bitmap's width.

Return Values

Returns the bitmap width in pixels.

See Also

  • SWFBitmap::getHeight() - Returns the bitmap's height


The SWFButton class

(PHP 5 < 5.3.0, PECL ming SVN)

Introduction

SWFButton.

Class synopsis

SWFButton {
/* Methods */
addAction ( SWFAction $action , int $flags ) : void
addASound ( SWFSound $sound , int $flags ) : SWFSoundInstance
addShape ( SWFShape $shape , int $flags ) : void
__construct ( void )
setAction ( SWFAction $action ) : void
setDown ( SWFShape $shape ) : void
setHit ( SWFShape $shape ) : void
setMenu ( int $flag ) : void
setOver ( SWFShape $shape ) : void
setUp ( SWFShape $shape ) : void
}

Table of Contents

  • SWFButton::addAction — Adds an action
  • SWFButton::addASound — Associates a sound with a button transition
  • SWFButton::addShape — Adds a shape to a button
  • SWFButton::__construct — Creates a new Button
  • SWFButton::setAction — Sets the action
  • SWFButton::setDown — Alias for addShape(shape, SWFBUTTON_DOWN)
  • SWFButton::setHit — Alias for addShape(shape, SWFBUTTON_HIT)
  • SWFButton::setMenu — Enable track as menu button behaviour
  • SWFButton::setOver — Alias for addShape(shape, SWFBUTTON_OVER)
  • SWFButton::setUp — Alias for addShape(shape, SWFBUTTON_UP)


Adds an action

  • « SWFButton
  • SWFButton::addASound »
  • PHP Manual
  • SWFButton
  • Adds an action

SWFButton::addAction

(PHP 5 < 5.3.0, PECL ming SVN)

SWFButton::addAction — Adds an action

Description

SWFButton::addAction ( SWFAction $action , int $flags ) : void
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.

Adds the given action to the button for the given conditions.

Parameters

action

An SWFAction, returned by SWFAction::__construct().

flags

The following flags are valid: SWFBUTTON_MOUSEOVER, SWFBUTTON_MOUSEOUT, SWFBUTTON_MOUSEUP, SWFBUTTON_MOUSEUPOUTSIDE, SWFBUTTON_MOUSEDOWN, SWFBUTTON_DRAGOUT and SWFBUTTON_DRAGOVER.

Return Values

No value is returned.

See Also

  • SWFButton::addShape() - Adds a shape to a button
  • SWFAction


Associates a sound with a button transition

  • « SWFButton::addAction
  • SWFButton::addShape »
  • PHP Manual
  • SWFButton
  • Associates a sound with a button transition

SWFButton::addASound

(PHP 5 < 5.3.0, PECL ming SVN)

SWFButton::addASound — Associates a sound with a button transition

Description

SWFButton::addASound ( SWFSound $sound , int $flags ) : SWFSoundInstance
Warning

This function is currently not documented; only its argument list is available.


Adds a shape to a button

  • « SWFButton::addASound
  • SWFButton::__construct »
  • PHP Manual
  • SWFButton
  • Adds a shape to a button

SWFButton::addShape

(PHP 5 < 5.3.0, PECL ming SVN)

SWFButton::addShape — Adds a shape to a button

Description

SWFButton::addShape ( SWFShape $shape , int $flags ) : void
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.

Adds the given shape to the button.

Parameters

shape

An SWFShape instance

flags

The following flags are valid: SWFBUTTON_UP, SWFBUTTON_OVER, SWFBUTTON_DOWN and SWFBUTTON_HIT.

SWFBUTTON_HIT isn't ever displayed, it defines the hit region for the button. That is, everywhere the hit shape would be drawn is considered a "touchable" part of the button.

Return Values

No value is returned.


Creates a new Button

  • « SWFButton::addShape
  • SWFButton::setAction »
  • PHP Manual
  • SWFButton
  • Creates a new Button

SWFButton::__construct

(PHP 5 < 5.3.0, PECL ming SVN)

SWFButton::__construct — Creates a new Button

Description

SWFButton::__construct ( void )
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.

Creates a new Button.

Examples

This simple example will show your usual interactions with buttons : rollover, rollon, mouseup, mousedown, noaction.

Example #1 Usual interactions with buttons

<?php

$f = new SWFFont("_serif");

$p = new SWFSprite();

function label($string)
{
  global $f;

  $t = new SWFTextField();
  $t->setFont($f);
  $t->addString($string);
  $t->setHeight(200);
  $t->setBounds(3200, 200);
  return $t;
}

function addLabel($string)
{
  global $p;

  $i = $p->add(label($string));
  $p->nextFrame();
  $p->remove($i);
}

$p->add(new SWFAction("stop();"));
addLabel("NO ACTION");
addLabel("SWFBUTTON_MOUSEUP");
addLabel("SWFBUTTON_MOUSEDOWN");
addLabel("SWFBUTTON_MOUSEOVER");
addLabel("SWFBUTTON_MOUSEOUT");
addLabel("SWFBUTTON_MOUSEUPOUTSIDE");
addLabel("SWFBUTTON_DRAGOVER");
addLabel("SWFBUTTON_DRAGOUT");

function rect($r, $g, $b)
{
  $s = new SWFShape();
  $s->setRightFill($s->addFill($r, $g, $b));
  $s->drawLine(600, 0);
  $s->drawLine(0, 600);
  $s->drawLine(-600, 0);
  $s->drawLine(0, -600);

  return $s;
}

$b = new SWFButton();
$b->addShape(rect(0xff, 0, 0), SWFBUTTON_UP | SWFBUTTON_HIT);
$b->addShape(rect(0, 0xff, 0), SWFBUTTON_OVER);
$b->addShape(rect(0, 0, 0xff), SWFBUTTON_DOWN);

$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(1);"),
          SWFBUTTON_MOUSEUP);

$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(2);"),
      SWFBUTTON_MOUSEDOWN);

$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(3);"),
      SWFBUTTON_MOUSEOVER);

$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(4);"),
      SWFBUTTON_MOUSEOUT);

$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(5);"),
      SWFBUTTON_MOUSEUPOUTSIDE);

$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(6);"),
      SWFBUTTON_DRAGOVER);

$b->addAction(new SWFAction("setTarget('/label'); gotoFrame(7);"),
      SWFBUTTON_DRAGOUT);

$m = new SWFMovie();
$m->setDimension(4000, 3000);

$i = $m->add($p);
$i->setName("label");
$i->moveTo(400, 1900);

$i = $m->add($b);
$i->moveTo(400, 900);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

This simple example will enables you to drag draw a big red button on the windows. No drag-and-drop, just moving around.

Example #2 Drag example

<?php

$s = new SWFShape();
$s->setRightFill($s->addFill(0xff, 0, 0));
$s->drawLine(1000,0);
$s->drawLine(0,1000);
$s->drawLine(-1000,0);
$s->drawLine(0,-1000);

$b = new SWFButton();
$b->addShape($s, SWFBUTTON_HIT | SWFBUTTON_UP | SWFBUTTON_DOWN | SWFBUTTON_OVER);

$b->addAction(new SWFAction("startDrag('/test', 0);"), // '0' means don't lock to mouse
      SWFBUTTON_MOUSEDOWN);

$b->addAction(new SWFAction("stopDrag();"),
      SWFBUTTON_MOUSEUP | SWFBUTTON_MOUSEUPOUTSIDE);

$p = new SWFSprite();
$p->add($b);
$p->nextFrame();

$m = new SWFMovie();
$i = $m->add($p);
$i->setName('test');
$i->moveTo(1000,1000);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>


Sets the action

  • « SWFButton::__construct
  • SWFButton::setDown »
  • PHP Manual
  • SWFButton
  • Sets the action

SWFButton::setAction

(PHP 5 < 5.3.0, PECL ming SVN)

SWFButton::setAction — Sets the action

Description

SWFButton::setAction ( SWFAction $action ) : void
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.

Sets the action to be performed when the button is clicked.

This is a shortcut for SWFButton::addAction() called with the SWFBUTTON_MOUSEUP flag.

Parameters

action

An SWFAction, returned by SWFAction::__construct().

Return Values

No value is returned.

See Also

  • SWFButton::addAction() - Adds an action
  • SWFAction


Alias for addShape(shape, SWFBUTTON_DOWN)

  • « SWFButton::setAction
  • SWFButton::setHit »
  • PHP Manual
  • SWFButton
  • Alias for addShape(shape, SWFBUTTON_DOWN)

SWFButton::setDown

(PHP 5 < 5.3.0, PECL ming SVN)

SWFButton::setDown — Alias for addShape(shape, SWFBUTTON_DOWN)

Description

SWFButton::setDown ( SWFShape $shape ) : void
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.

swfbutton::setdown() alias for addShape(shape, SWFBUTTON_DOWN).

Return Values

No value is returned.

See Also

  • SWFButton::addShape() - Adds a shape to a button
  • SWFAction


Alias for addShape(shape, SWFBUTTON_HIT)

  • « SWFButton::setDown
  • SWFButton::setMenu »
  • PHP Manual
  • SWFButton
  • Alias for addShape(shape, SWFBUTTON_HIT)

SWFButton::setHit

(PHP 5 < 5.3.0, PECL ming SVN)

SWFButton::setHit — Alias for addShape(shape, SWFBUTTON_HIT)

Description

SWFButton::setHit ( SWFShape $shape ) : void
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.

swfbutton::sethit() alias for addShape(shape, SWFBUTTON_HIT).

Return Values

No value is returned.

See Also

  • SWFButton::addShape() - Adds a shape to a button
  • SWFAction


Enable track as menu button behaviour

  • « SWFButton::setHit
  • SWFButton::setOver »
  • PHP Manual
  • SWFButton
  • Enable track as menu button behaviour

SWFButton::setMenu

(PHP 5 < 5.3.0, PECL ming SVN)

SWFButton::setMenu — Enable track as menu button behaviour

Description

SWFButton::setMenu ( int $flag ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

flag

This parameter can be used for a slight different behavior of buttons. You can set it to 0 (off) or 1 (on).

Return Values

No value is returned.


Alias for addShape(shape, SWFBUTTON_OVER)

  • « SWFButton::setMenu
  • SWFButton::setUp »
  • PHP Manual
  • SWFButton
  • Alias for addShape(shape, SWFBUTTON_OVER)

SWFButton::setOver

(PHP 5 < 5.3.0, PECL ming SVN)

SWFButton::setOver — Alias for addShape(shape, SWFBUTTON_OVER)

Description

SWFButton::setOver ( SWFShape $shape ) : void
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.

swfbutton::setover() alias for addShape(shape, SWFBUTTON_OVER).

Return Values

No value is returned.

See Also

  • SWFButton::addShape() - Adds a shape to a button
  • SWFAction


Alias for addShape(shape, SWFBUTTON_UP)

  • « SWFButton::setOver
  • SWFDisplayItem »
  • PHP Manual
  • SWFButton
  • Alias for addShape(shape, SWFBUTTON_UP)

SWFButton::setUp

(PHP 5 < 5.3.0, PECL ming SVN)

SWFButton::setUp — Alias for addShape(shape, SWFBUTTON_UP)

Description

SWFButton::setUp ( SWFShape $shape ) : void
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.

swfbutton::setup() alias for addShape(shape, SWFBUTTON_UP).

Return Values

No value is returned.

See Also

  • SWFButton::addShape() - Adds a shape to a button
  • SWFAction


The SWFDisplayItem class

(PHP 5 < 5.3.0, PECL ming SVN)

Introduction

SWFDisplayItem.

Class synopsis

SWFDisplayItem {
/* Methods */
addAction ( SWFAction $action , int $flags ) : void
addColor ( int $red , int $green , int $blue [, int $a ] ) : void
endMask ( void ) : void
getRot ( void ) : float
getX ( void ) : float
getXScale ( void ) : float
getXSkew ( void ) : float
getY ( void ) : float
getYScale ( void ) : float
getYSkew ( void ) : float
move ( float $dx , float $dy ) : void
moveTo ( float $x , float $y ) : void
multColor ( float $red , float $green , float $blue [, float $a ] ) : void
remove ( void ) : void
rotate ( float $angle ) : void
rotateTo ( float $angle ) : void
scale ( float $dx , float $dy ) : void
scaleTo ( float $x [, float $y ] ) : void
setDepth ( int $depth ) : void
setMaskLevel ( int $level ) : void
setMatrix ( float $a , float $b , float $c , float $d , float $x , float $y ) : void
setName ( string $name ) : void
setRatio ( float $ratio ) : void
skewX ( float $ddegrees ) : void
skewXTo ( float $degrees ) : void
skewY ( float $ddegrees ) : void
skewYTo ( float $degrees ) : void
}

Table of Contents

  • SWFDisplayItem::addAction — Adds this SWFAction to the given SWFSprite instance
  • SWFDisplayItem::addColor — Adds the given color to this item's color transform
  • SWFDisplayItem::endMask — Another way of defining a MASK layer
  • SWFDisplayItem::getRot — Description
  • SWFDisplayItem::getX — Description
  • SWFDisplayItem::getXScale — Description
  • SWFDisplayItem::getXSkew — Description
  • SWFDisplayItem::getY — Description
  • SWFDisplayItem::getYScale — Description
  • SWFDisplayItem::getYSkew — Description
  • SWFDisplayItem::move — Moves object in relative coordinates
  • SWFDisplayItem::moveTo — Moves object in global coordinates
  • SWFDisplayItem::multColor — Multiplies the item's color transform
  • SWFDisplayItem::remove — Removes the object from the movie
  • SWFDisplayItem::rotate — Rotates in relative coordinates
  • SWFDisplayItem::rotateTo — Rotates the object in global coordinates
  • SWFDisplayItem::scale — Scales the object in relative coordinates
  • SWFDisplayItem::scaleTo — Scales the object in global coordinates
  • SWFDisplayItem::setDepth — Sets z-order
  • SWFDisplayItem::setMaskLevel — Defines a MASK layer at level
  • SWFDisplayItem::setMatrix — Sets the item's transform matrix
  • SWFDisplayItem::setName — Sets the object's name
  • SWFDisplayItem::setRatio — Sets the object's ratio
  • SWFDisplayItem::skewX — Sets the X-skew
  • SWFDisplayItem::skewXTo — Sets the X-skew
  • SWFDisplayItem::skewY — Sets the Y-skew
  • SWFDisplayItem::skewYTo — Sets the Y-skew


Adds this SWFAction to the given SWFSprite instance

  • « SWFDisplayItem
  • SWFDisplayItem::addColor »
  • PHP Manual
  • SWFDisplayItem
  • Adds this SWFAction to the given SWFSprite instance

SWFDisplayItem::addAction

(PHP 5 < 5.3.0, PECL ming SVN)

SWFDisplayItem::addAction — Adds this SWFAction to the given SWFSprite instance

Description

SWFDisplayItem::addAction ( SWFAction $action , int $flags ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

action

An SWFAction, returned by SWFAction::__construct().

flags

Return Values

No value is returned.

See Also

  • SWFAction


Adds the given color to this item's color transform

  • « SWFDisplayItem::addAction
  • SWFDisplayItem::endMask »
  • PHP Manual
  • SWFDisplayItem
  • Adds the given color to this item's color transform

SWFDisplayItem::addColor

(PHP 5 < 5.3.0, PECL ming SVN)

SWFDisplayItem::addColor — Adds the given color to this item's color transform

Description

SWFDisplayItem::addColor ( int $red , int $green , int $blue [, int $a ] ) : void
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.

swfdisplayitem::addcolor() adds the color to this item's color transform. The color is given in its RGB form.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Return Values

No value is returned.

Return Values

No value is returned.


Another way of defining a MASK layer

  • « SWFDisplayItem::addColor
  • SWFDisplayItem::getRot »
  • PHP Manual
  • SWFDisplayItem
  • Another way of defining a MASK layer

SWFDisplayItem::endMask

(PHP 5 < 5.3.0, PECL ming SVN)

SWFDisplayItem::endMask — Another way of defining a MASK layer

Description

SWFDisplayItem::endMask ( void ) : void
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.


Description

  • « SWFDisplayItem::endMask
  • SWFDisplayItem::getX »
  • PHP Manual
  • SWFDisplayItem
  • Description

SWFDisplayItem::getRot

(PHP 5 < 5.3.0, PECL ming SVN)

SWFDisplayItem::getRot —

Description

SWFDisplayItem::getRot ( void ) : float
Warning

This function is currently not documented; only its argument list is available.


Description

  • « SWFDisplayItem::getRot
  • SWFDisplayItem::getXScale »
  • PHP Manual
  • SWFDisplayItem
  • Description

SWFDisplayItem::getX

(PHP 5 < 5.3.0, PECL ming SVN)

SWFDisplayItem::getX —

Description

SWFDisplayItem::getX ( void ) : float
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFDisplayItem::getY() - Description


Description

  • « SWFDisplayItem::getX
  • SWFDisplayItem::getXSkew »
  • PHP Manual
  • SWFDisplayItem
  • Description

SWFDisplayItem::getXScale

(PHP 5 < 5.3.0, PECL ming SVN)

SWFDisplayItem::getXScale —

Description

SWFDisplayItem::getXScale ( void ) : float
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFDisplayItem::getYScale() - Description


Description

  • « SWFDisplayItem::getXScale
  • SWFDisplayItem::getY »
  • PHP Manual
  • SWFDisplayItem
  • Description

SWFDisplayItem::getXSkew

(PHP 5 < 5.3.0, PECL ming SVN)

SWFDisplayItem::getXSkew —

Description

SWFDisplayItem::getXSkew ( void ) : float
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFDisplayItem::getYSkew() - Description


Description

  • « SWFDisplayItem::getXSkew
  • SWFDisplayItem::getYScale »
  • PHP Manual
  • SWFDisplayItem
  • Description

SWFDisplayItem::getY

(PHP 5 < 5.3.0, PECL ming SVN)

SWFDisplayItem::getY —

Description

SWFDisplayItem::getY ( void ) : float
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFDisplayItem::getX() - Description


Description

  • « SWFDisplayItem::getY
  • SWFDisplayItem::getYSkew »
  • PHP Manual
  • SWFDisplayItem
  • Description

SWFDisplayItem::getYScale

(PHP 5 < 5.3.0, PECL ming SVN)

SWFDisplayItem::getYScale —

Description

SWFDisplayItem::getYScale ( void ) : float
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFDisplayItem::getXScale() - Description


Description

  • « SWFDisplayItem::getYScale
  • SWFDisplayItem::move »
  • PHP Manual
  • SWFDisplayItem
  • Description

SWFDisplayItem::getYSkew

(PHP 5 < 5.3.0, PECL ming SVN)

SWFDisplayItem::getYSkew —

Description

SWFDisplayItem::getYSkew ( void ) : float
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFDisplayItem::getXSkew() - Description


Moves object in relative coordinates

  • « SWFDisplayItem::getYSkew
  • SWFDisplayItem::moveTo »
  • PHP Manual
  • SWFDisplayItem
  • Moves object in relative coordinates

SWFDisplayItem::move

(PHP 5 < 5.3.0, PECL ming SVN)

SWFDisplayItem::move — Moves object in relative coordinates

Description

SWFDisplayItem::move ( float $dx , float $dy ) : void
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.

swfdisplayitem::move() moves the current object by (dx,dy) from its current position.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Return Values

No value is returned.

See Also

  • SWFDisplayItem::moveTo() - Moves object in global coordinates


Moves object in global coordinates

  • « SWFDisplayItem::move
  • SWFDisplayItem::multColor »
  • PHP Manual
  • SWFDisplayItem
  • Moves object in global coordinates

SWFDisplayItem::moveTo

(PHP 5 < 5.3.0, PECL ming SVN)

SWFDisplayItem::moveTo — Moves object in global coordinates

Description

SWFDisplayItem::moveTo ( float $x , float $y ) : void
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.

swfdisplayitem::moveto() moves the current object to (x,y) in global coordinates.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Return Values

No value is returned.

See Also

  • SWFDisplayItem::move() - Moves object in relative coordinates


Multiplies the item's color transform

  • « SWFDisplayItem::moveTo
  • SWFDisplayItem::remove »
  • PHP Manual
  • SWFDisplayItem
  • Multiplies the item's color transform

SWFDisplayItem::multColor

(PHP 5 < 5.3.0, PECL ming SVN)

SWFDisplayItem::multColor — Multiplies the item's color transform

Description

SWFDisplayItem::multColor ( float $red , float $green , float $blue [, float $a ] ) : void
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.

swfdisplayitem::multcolor() multiplies the item's color transform by the given values.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Parameters

These parameters are floats between 0.0 and 1.0:

red

Value of red component

green

Value of green component

blue

Value of blue component

a

Value of alpha component

Return Values

No value is returned.

Examples

This simple example will modify your picture's atmosphere to Halloween (use a landscape or bright picture).

Example #1 swfdisplayitem::multcolor() example

<?php

$b = new SWFBitmap(file_get_contents("backyard.jpg"));
// note use your own picture :-)
$s = new SWFShape();
$s->setRightFill($s->addFill($b));
$s->drawLine($b->getWidth(), 0);
$s->drawLine(0, $b->getHeight());
$s->drawLine(-$b->getWidth(), 0);
$s->drawLine(0, -$b->getHeight());

$m = new SWFMovie();
$m->setDimension($b->getWidth(), $b->getHeight());

$i = $m->add($s);

for ($n=0; $n<=20; ++$n) {
  $i->multColor(1.0-$n/10, 1.0, 1.0);
  $i->addColor(0xff*$n/20, 0, 0);
  $m->nextFrame();
}

header('Content-type: application/x-shockwave-flash');
$m->output();
?>


Removes the object from the movie

  • « SWFDisplayItem::multColor
  • SWFDisplayItem::rotate »
  • PHP Manual
  • SWFDisplayItem
  • Removes the object from the movie

SWFDisplayItem::remove

(PHP 5 < 5.3.0, PECL ming SVN)

SWFDisplayItem::remove — Removes the object from the movie

Description

SWFDisplayItem::remove ( void ) : void
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.

swfdisplayitem::remove() removes this object from the movie's display list.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Return Values

No value is returned.

See Also

  • SWFMovie::add() - Adds any type of data to a movie


Rotates in relative coordinates

  • « SWFDisplayItem::remove
  • SWFDisplayItem::rotateTo »
  • PHP Manual
  • SWFDisplayItem
  • Rotates in relative coordinates

SWFDisplayItem::rotate

(PHP 5 < 5.3.0, PECL ming SVN)

SWFDisplayItem::rotate — Rotates in relative coordinates

Description

SWFDisplayItem::rotate ( float $angle ) : void
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.

swfdisplayitem::rotate() rotates the current object by angle degrees from its current rotation.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Return Values

No value is returned.

See Also

  • SWFDisplayItem::rotateTo() - Rotates the object in global coordinates


Rotates the object in global coordinates

  • « SWFDisplayItem::rotate
  • SWFDisplayItem::scale »
  • PHP Manual
  • SWFDisplayItem
  • Rotates the object in global coordinates

SWFDisplayItem::rotateTo

(PHP 5 < 5.3.0, PECL ming SVN)

SWFDisplayItem::rotateTo — Rotates the object in global coordinates

Description

SWFDisplayItem::rotateTo ( float $angle ) : void
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.

swfdisplayitem::rotateto() set the current object rotation to angle degrees in global coordinates.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Return Values

No value is returned.

Examples

This example bring three rotating string from the background to the foreground. Pretty nice.

Example #1 swfdisplayitem::rotateto() example

<?php
$thetext =  "ming!";

$f = new SWFFont("Bauhaus 93.fdb");

$m = new SWFMovie();
$m->setRate(24.0);
$m->setDimension(2400, 1600);
$m->setBackground(0xff, 0xff, 0xff);

// functions with huge numbers of arbitrary
// arguments are always a good idea!  Really!

function text($r, $g, $b, $a, $rot, $x, $y, $scale, $string)
{
  global $f, $m;

  $t = new SWFText();
  $t->setFont($f);
  $t->setColor($r, $g, $b, $a);
  $t->setHeight(960);
  $t->moveTo(-($f->getWidth($string))/2, $f->getAscent()/2);
  $t->addString($string);

  // we can add properties just like a normal PHP var,
  // as long as the names aren't already used.
  // e.g., we can't set $i->scale, because that's a function

  $i = $m->add($t);
  $i->x = $x;
  $i->y = $y;
  $i->rot = $rot;
  $i->s = $scale;
  $i->rotateTo($rot);
  $i->scale($scale, $scale);

  // but the changes are local to the function, so we have to
  // return the changed object.  kinda weird..

  return $i;
}

function step($i)
{
  $oldrot = $i->rot;
  $i->rot = 19*$i->rot/20;
  $i->x = (19*$i->x + 1200)/20;
  $i->y = (19*$i->y + 800)/20;
  $i->s = (19*$i->s + 1.0)/20;

  $i->rotateTo($i->rot);
  $i->scaleTo($i->s, $i->s);
  $i->moveTo($i->x, $i->y);

  return $i;
}

// see?  it sure paid off in legibility:

$i1 = text(0xff, 0x33, 0x33, 0xff, 900, 1200, 800, 0.03, $thetext);
$i2 = text(0x00, 0x33, 0xff, 0x7f, -560, 1200, 800, 0.04, $thetext);
$i3 = text(0xff, 0xff, 0xff, 0x9f, 180, 1200, 800, 0.001, $thetext);

for ($i=1; $i<=100; ++$i) {
  $i1 = step($i1);
  $i2 = step($i2);
  $i3 = step($i3);

  $m->nextFrame();
}

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

See Also

  • SWFDisplayItem::rotate() - Rotates in relative coordinates


Scales the object in relative coordinates

  • « SWFDisplayItem::rotateTo
  • SWFDisplayItem::scaleTo »
  • PHP Manual
  • SWFDisplayItem
  • Scales the object in relative coordinates

SWFDisplayItem::scale

(PHP 5 < 5.3.0, PECL ming SVN)

SWFDisplayItem::scale — Scales the object in relative coordinates

Description

SWFDisplayItem::scale ( float $dx , float $dy ) : void
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.

swfdisplayitem::scale() scales the current object by (dx,dy) from its current size.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Return Values

No value is returned.

See Also

  • SWFDisplayItem::scaleTo() - Scales the object in global coordinates


Scales the object in global coordinates

  • « SWFDisplayItem::scale
  • SWFDisplayItem::setDepth »
  • PHP Manual
  • SWFDisplayItem
  • Scales the object in global coordinates

SWFDisplayItem::scaleTo

(PHP 5 < 5.3.0, PECL ming SVN)

SWFDisplayItem::scaleTo — Scales the object in global coordinates

Description

SWFDisplayItem::scaleTo ( float $x [, float $y ] ) : void
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.

swfdisplayitem::scaleto() scales the current object to (x,y) in global coordinates.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Return Values

No value is returned.

See Also

  • SWFDisplayItem::scale() - Scales the object in relative coordinates


Sets z-order

  • « SWFDisplayItem::scaleTo
  • SWFDisplayItem::setMaskLevel »
  • PHP Manual
  • SWFDisplayItem
  • Sets z-order

SWFDisplayItem::setDepth

(PHP 5 < 5.3.0, PECL ming SVN)

SWFDisplayItem::setDepth — Sets z-order

Description

SWFDisplayItem::setDepth ( int $depth ) : void
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.

swfdisplayitem::setdepth() sets the object's z-order to depth. Depth defaults to the order in which instances are created (by adding a shape/text to a movie)- newer ones are on top of older ones. If two objects are given the same depth, only the later-defined one can be moved.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Return Values

No value is returned.


Defines a MASK layer at level

  • « SWFDisplayItem::setDepth
  • SWFDisplayItem::setMatrix »
  • PHP Manual
  • SWFDisplayItem
  • Defines a MASK layer at level

SWFDisplayItem::setMaskLevel

(PHP 5 < 5.3.0, PECL ming SVN)

SWFDisplayItem::setMaskLevel — Defines a MASK layer at level

Description

SWFDisplayItem::setMaskLevel ( int $level ) : void
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.


Sets the item's transform matrix

  • « SWFDisplayItem::setMaskLevel
  • SWFDisplayItem::setName »
  • PHP Manual
  • SWFDisplayItem
  • Sets the item's transform matrix

SWFDisplayItem::setMatrix

(PHP 5 < 5.3.0, PECL ming SVN)

SWFDisplayItem::setMatrix — Sets the item's transform matrix

Description

SWFDisplayItem::setMatrix ( float $a , float $b , float $c , float $d , float $x , float $y ) : void
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.


Sets the object's name

  • « SWFDisplayItem::setMatrix
  • SWFDisplayItem::setRatio »
  • PHP Manual
  • SWFDisplayItem
  • Sets the object's name

SWFDisplayItem::setName

(PHP 5 < 5.3.0, PECL ming SVN)

SWFDisplayItem::setName — Sets the object's name

Description

SWFDisplayItem::setName ( string $name ) : void
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.

swfdisplayitem::setname() sets the object's name to name, for targetting with action script. Only useful on sprites.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Return Values

No value is returned.


Sets the object's ratio

  • « SWFDisplayItem::setName
  • SWFDisplayItem::skewX »
  • PHP Manual
  • SWFDisplayItem
  • Sets the object's ratio

SWFDisplayItem::setRatio

(PHP 5 < 5.3.0, PECL ming SVN)

SWFDisplayItem::setRatio — Sets the object's ratio

Description

SWFDisplayItem::setRatio ( float $ratio ) : void
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.

swfdisplayitem::setratio() sets the object's ratio to ratio. Obviously only useful for morphs.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Return Values

No value is returned.

Examples

This simple example will morph nicely three concentric circles.

Example #1 swfdisplayitem::setname() example

<?php

$p = new SWFMorph();

$g = new SWFGradient();
$g->addEntry(0.0, 0, 0, 0);
$g->addEntry(0.16, 0xff, 0xff, 0xff);
$g->addEntry(0.32, 0, 0, 0);
$g->addEntry(0.48, 0xff, 0xff, 0xff);
$g->addEntry(0.64, 0, 0, 0);
$g->addEntry(0.80, 0xff, 0xff, 0xff);
$g->addEntry(1.00, 0, 0, 0);

$s = $p->getShape1();
$f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
$f->scaleTo(0.05);
$s->setLeftFill($f);
$s->movePenTo(-160, -120);
$s->drawLine(320, 0);
$s->drawLine(0, 240);
$s->drawLine(-320, 0);
$s->drawLine(0, -240);

$g = new SWFGradient();
$g->addEntry(0.0, 0, 0, 0);
$g->addEntry(0.16, 0xff, 0, 0);
$g->addEntry(0.32, 0, 0, 0);
$g->addEntry(0.48, 0, 0xff, 0);
$g->addEntry(0.64, 0, 0, 0);
$g->addEntry(0.80, 0, 0, 0xff);
$g->addEntry(1.00, 0, 0, 0);

$s = $p->getShape2();
$f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
$f->scaleTo(0.05);
$f->skewXTo(1.0);
$s->setLeftFill($f);
$s->movePenTo(-160, -120);
$s->drawLine(320, 0);
$s->drawLine(0, 240);
$s->drawLine(-320, 0);
$s->drawLine(0, -240);

$m = new SWFMovie();
$m->setDimension(320, 240);
$i = $m->add($p);
$i->moveTo(160, 120);

for ($n=0; $n<=1.001; $n+=0.01) {
    $i->setRatio($n);
    $m->nextFrame();
}

header('Content-type: application/x-shockwave-flash');
$m->output();
?>


Sets the X-skew

  • « SWFDisplayItem::setRatio
  • SWFDisplayItem::skewXTo »
  • PHP Manual
  • SWFDisplayItem
  • Sets the X-skew

SWFDisplayItem::skewX

(PHP 5 < 5.3.0, PECL ming SVN)

SWFDisplayItem::skewX — Sets the X-skew

Description

SWFDisplayItem::skewX ( float $ddegrees ) : void
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.

swfdisplayitem::skewx() adds ddegrees to current x-skew.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Return Values

No value is returned.

See Also

  • SWFDisplayItem::skewXTo() - Sets the X-skew
  • SWFDisplayItem::skewY() - Sets the Y-skew
  • SWFDisplayItem::skewYTo() - Sets the Y-skew


Sets the X-skew

  • « SWFDisplayItem::skewX
  • SWFDisplayItem::skewY »
  • PHP Manual
  • SWFDisplayItem
  • Sets the X-skew

SWFDisplayItem::skewXTo

(PHP 5 < 5.3.0, PECL ming SVN)

SWFDisplayItem::skewXTo — Sets the X-skew

Description

SWFDisplayItem::skewXTo ( float $degrees ) : void
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.

swfdisplayitem::skewxto() sets the x-skew to degrees. For degrees is 1.0, it means a 45-degree forward slant. More is more forward, less is more backward.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Return Values

No value is returned.

See Also

  • SWFDisplayItem::skewX() - Sets the X-skew
  • SWFDisplayItem::skewY() - Sets the Y-skew
  • SWFDisplayItem::skewYTo() - Sets the Y-skew


Sets the Y-skew

  • « SWFDisplayItem::skewXTo
  • SWFDisplayItem::skewYTo »
  • PHP Manual
  • SWFDisplayItem
  • Sets the Y-skew

SWFDisplayItem::skewY

(PHP 5 < 5.3.0, PECL ming SVN)

SWFDisplayItem::skewY — Sets the Y-skew

Description

SWFDisplayItem::skewY ( float $ddegrees ) : void
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.

swfdisplayitem::skewy() adds ddegrees to current y-skew.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Return Values

No value is returned.

See Also

  • SWFDisplayItem::skewYTo() - Sets the Y-skew
  • SWFDisplayItem::skewX() - Sets the X-skew
  • SWFDisplayItem::skewXTo() - Sets the X-skew


Sets the Y-skew

  • « SWFDisplayItem::skewY
  • SWFFill »
  • PHP Manual
  • SWFDisplayItem
  • Sets the Y-skew

SWFDisplayItem::skewYTo

(PHP 5 < 5.3.0, PECL ming SVN)

SWFDisplayItem::skewYTo — Sets the Y-skew

Description

SWFDisplayItem::skewYTo ( float $degrees ) : void
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.

swfdisplayitem::skewyto() sets the y-skew to degrees. For degrees is 1.0, it means a 45-degree forward slant. More is more upward, less is more downward.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie::add().

Return Values

No value is returned.

See Also

  • SWFDisplayItem::skewY() - Sets the Y-skew
  • SWFDisplayItem::skewX() - Sets the X-skew
  • SWFDisplayItem::skewXTo() - Sets the X-skew


The SWFFill class

(PHP 5 < 5.3.0, PECL ming SVN)

Introduction

The SWFFill object allows you to transform (scale, skew, rotate) bitmap and gradient fills.

swffill objects are created by the SWFShape::addFill() method.

Class synopsis

SWFFill {
/* Methods */
moveTo ( float $x , float $y ) : void
rotateTo ( float $angle ) : void
scaleTo ( float $x [, float $y ] ) : void
skewXTo ( float $x ) : void
skewYTo ( float $y ) : void
}

Table of Contents

  • SWFFill::moveTo — Moves fill origin
  • SWFFill::rotateTo — Sets fill's rotation
  • SWFFill::scaleTo — Sets fill's scale
  • SWFFill::skewXTo — Sets fill x-skew
  • SWFFill::skewYTo — Sets fill y-skew


Moves fill origin

  • « SWFFill
  • SWFFill::rotateTo »
  • PHP Manual
  • SWFFill
  • Moves fill origin

SWFFill::moveTo

(PHP 5 < 5.3.0, PECL ming SVN)

SWFFill::moveTo — Moves fill origin

Description

SWFFill::moveTo ( float $x , float $y ) : void
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.

Moves the fill origin to the given global coordinates.

Parameters

x

X-coordinate

y

Y-coordinate

Return Values

No value is returned.


Sets fill's rotation

  • « SWFFill::moveTo
  • SWFFill::scaleTo »
  • PHP Manual
  • SWFFill
  • Sets fill's rotation

SWFFill::rotateTo

(PHP 5 < 5.3.0, PECL ming SVN)

SWFFill::rotateTo — Sets fill's rotation

Description

SWFFill::rotateTo ( float $angle ) : void
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.

Sets the fill rotation to the given angle.

Parameters

angle

The rotation angle, in degrees.

Return Values

No value is returned.


Sets fill's scale

  • « SWFFill::rotateTo
  • SWFFill::skewXTo »
  • PHP Manual
  • SWFFill
  • Sets fill's scale

SWFFill::scaleTo

(PHP 5 < 5.3.0, PECL ming SVN)

SWFFill::scaleTo — Sets fill's scale

Description

SWFFill::scaleTo ( float $x [, float $y ] ) : void
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.

Sets the fill scale to the given coordinates.

Parameters

x

X-coordinate

y

Y-coordinate

Return Values

No value is returned.


Sets fill x-skew

  • « SWFFill::scaleTo
  • SWFFill::skewYTo »
  • PHP Manual
  • SWFFill
  • Sets fill x-skew

SWFFill::skewXTo

(PHP 5 < 5.3.0, PECL ming SVN)

SWFFill::skewXTo — Sets fill x-skew

Description

SWFFill::skewXTo ( float $x ) : void
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.

Sets the fill x-skew to x.

Parameters

x

When x is 1.0, it is a 45-degree forward slant. More is more forward, less is more backward.

Return Values

No value is returned.

See Also

  • SWFFill::skewYTo() - Sets fill y-skew


Sets fill y-skew

  • « SWFFill::skewXTo
  • SWFFont »
  • PHP Manual
  • SWFFill
  • Sets fill y-skew

SWFFill::skewYTo

(PHP 5 < 5.3.0, PECL ming SVN)

SWFFill::skewYTo — Sets fill y-skew

Description

SWFFill::skewYTo ( float $y ) : void
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.

Sets the fill y-skew to y.

Parameters

y

When y is 1.0, it is a 45-degree upward slant. More is more upward, less is more downward.

Return Values

No value is returned.

See Also

  • SWFFill::skewXTo() - Sets fill x-skew


The SWFFont class

(PHP 5 < 5.3.0, PECL ming SVN)

Introduction

The SWFFont object represent a reference to the font definition, for us with SWFText::setFont() and SWFTextField::setFont().

Class synopsis

SWFFont {
/* Methods */
__construct ( string $filename )
getAscent ( void ) : float
getDescent ( void ) : float
getLeading ( void ) : float
getShape ( int $code ) : string
getUTF8Width ( string $string ) : float
getWidth ( string $string ) : float
}

Table of Contents

  • SWFFont::__construct — Loads a font definition
  • SWFFont::getAscent — Returns the ascent of the font, or 0 if not available
  • SWFFont::getDescent — Returns the descent of the font, or 0 if not available
  • SWFFont::getLeading — Returns the leading of the font, or 0 if not available
  • SWFFont::getShape — Returns the glyph shape of a char as a text string
  • SWFFont::getUTF8Width — Calculates the width of the given string in this font at full height
  • SWFFont::getWidth — Returns the string's width


Loads a font definition

  • « SWFFont
  • SWFFont::getAscent »
  • PHP Manual
  • SWFFont
  • Loads a font definition

SWFFont::__construct

(PHP 5 < 5.3.0, PECL ming SVN)

SWFFont::__construct — Loads a font definition

Description

SWFFont::__construct ( string $filename )
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.

If filename is the name of an FDB file (i.e., it ends in ".fdb"), load the font definition found in said file. Otherwise, create a browser-defined font reference.

FDB ("font definition block") is a very simple wrapper for the SWF DefineFont2 block which contains a full description of a font. One may create FDB files from SWT Generator template files with the included makefdb utility- look in the util directory off the main ming distribution directory.

Browser-defined fonts don't contain any information about the font other than its name. It is assumed that the font definition will be provided by the movie player. The fonts _serif, _sans, and _typewriter should always be available. For example:

<?php
$f = newSWFFont("_sans");
?>
will give you the standard sans-serif font, probably the same as what you'd get with <font name="sans-serif"> in HTML.


Returns the ascent of the font, or 0 if not available

  • « SWFFont::__construct
  • SWFFont::getDescent »
  • PHP Manual
  • SWFFont
  • Returns the ascent of the font, or 0 if not available

SWFFont::getAscent

(PHP 5 < 5.3.0, PECL ming SVN)

SWFFont::getAscent — Returns the ascent of the font, or 0 if not available

Description

SWFFont::getAscent ( void ) : float
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFFont::getDescent() - Returns the descent of the font, or 0 if not available


Returns the descent of the font, or 0 if not available

  • « SWFFont::getAscent
  • SWFFont::getLeading »
  • PHP Manual
  • SWFFont
  • Returns the descent of the font, or 0 if not available

SWFFont::getDescent

(PHP 5 < 5.3.0, PECL ming SVN)

SWFFont::getDescent — Returns the descent of the font, or 0 if not available

Description

SWFFont::getDescent ( void ) : float
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFFont::getAscent() - Returns the ascent of the font, or 0 if not available


Returns the leading of the font, or 0 if not available

  • « SWFFont::getDescent
  • SWFFont::getShape »
  • PHP Manual
  • SWFFont
  • Returns the leading of the font, or 0 if not available

SWFFont::getLeading

(PHP 5 < 5.3.0, PECL ming SVN)

SWFFont::getLeading — Returns the leading of the font, or 0 if not available

Description

SWFFont::getLeading ( void ) : float
Warning

This function is currently not documented; only its argument list is available.


Returns the glyph shape of a char as a text string

  • « SWFFont::getLeading
  • SWFFont::getUTF8Width »
  • PHP Manual
  • SWFFont
  • Returns the glyph shape of a char as a text string

SWFFont::getShape

(PHP 5 < 5.3.0, PECL ming SVN)

SWFFont::getShape — Returns the glyph shape of a char as a text string

Description

SWFFont::getShape ( int $code ) : string
Warning

This function is currently not documented; only its argument list is available.


Calculates the width of the given string in this font at full height

  • « SWFFont::getShape
  • SWFFont::getWidth »
  • PHP Manual
  • SWFFont
  • Calculates the width of the given string in this font at full height

SWFFont::getUTF8Width

(PHP 5 < 5.3.0, PECL ming SVN)

SWFFont::getUTF8Width — Calculates the width of the given string in this font at full height

Description

SWFFont::getUTF8Width ( string $string ) : float
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFFont::getWidth() - Returns the string's width


Returns the string's width

  • « SWFFont::getUTF8Width
  • SWFFontChar »
  • PHP Manual
  • SWFFont
  • Returns the string's width

SWFFont::getWidth

(PHP 5 < 5.3.0, PECL ming SVN)

SWFFont::getWidth — Returns the string's width

Description

SWFFont::getWidth ( string $string ) : float
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.

swffont::getwidth() returns the string string's width, using font's default scaling. You'll probably want to use the swftext() version of this method which uses the text object's scale.

See Also

  • SWFFont::getUTF8Width() - Calculates the width of the given string in this font at full height


The SWFFontChar class

(PHP 5 < 5.3.0, PECL ming SVN)

Introduction

SWFFontChar.

Class synopsis

SWFFontChar {
/* Methods */
addChars ( string $char ) : void
addUTF8Chars ( string $char ) : void
}

Table of Contents

  • SWFFontChar::addChars — Adds characters to a font for exporting font
  • SWFFontChar::addUTF8Chars — Adds characters to a font for exporting font


Adds characters to a font for exporting font

  • « SWFFontChar
  • SWFFontChar::addUTF8Chars »
  • PHP Manual
  • SWFFontChar
  • Adds characters to a font for exporting font

SWFFontChar::addChars

(PHP 5 < 5.3.0, PECL ming SVN)

SWFFontChar::addChars — Adds characters to a font for exporting font

Description

SWFFontChar::addChars ( string $char ) : void
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

See Also

  • SWFFontChar::addUTF8Chars() - Adds characters to a font for exporting font


Adds characters to a font for exporting font

  • « SWFFontChar::addChars
  • SWFGradient »
  • PHP Manual
  • SWFFontChar
  • Adds characters to a font for exporting font

SWFFontChar::addUTF8Chars

(PHP 5 < 5.3.0, PECL ming SVN)

SWFFontChar::addUTF8Chars — Adds characters to a font for exporting font

Description

SWFFontChar::addUTF8Chars ( string $char ) : void
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

See Also

  • SWFFontChar::addChars() - Adds characters to a font for exporting font


The SWFGradient class

(PHP 5 < 5.3.0, PECL ming SVN)

Introduction

SWFGradient.

Class synopsis

SWFGradient {
/* Methods */
addEntry ( float $ratio , int $red , int $green , int $blue [, int $alpha = 255 ] ) : void
__construct ( void )
}

Table of Contents

  • SWFGradient::addEntry — Adds an entry to the gradient list
  • SWFGradient::__construct — Creates a gradient object


Adds an entry to the gradient list

  • « SWFGradient
  • SWFGradient::__construct »
  • PHP Manual
  • SWFGradient
  • Adds an entry to the gradient list

SWFGradient::addEntry

(PHP 5 < 5.3.0, PECL ming SVN)

SWFGradient::addEntry — Adds an entry to the gradient list

Description

SWFGradient::addEntry ( float $ratio , int $red , int $green , int $blue [, int $alpha = 255 ] ) : void
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.

swfgradient::addentry() adds an entry to the gradient list. ratio is a number between 0 and 1 indicating where in the gradient this color appears. Thou shalt add entries in order of increasing ratio.

red, green, blue is a color (RGB mode).

Return Values

No value is returned.


Creates a gradient object

  • « SWFGradient::addEntry
  • SWFMorph »
  • PHP Manual
  • SWFGradient
  • Creates a gradient object

SWFGradient::__construct

(PHP 5 < 5.3.0, PECL ming SVN)

SWFGradient::__construct — Creates a gradient object

Description

SWFGradient::__construct ( void )
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.

swfgradient() creates a new SWFGradient object.

After you've added the entries to your gradient, you can use the gradient in a shape fill with the swfshape::addfill() method.

SWFGradient has the following methods : swfgradient::addentry().

This simple example will draw a big black-to-white gradient as background, and a reddish disc in its center.

Example #1 swfgradient() example

<?php

  $m = new SWFMovie();
  $m->setDimension(320, 240);

  $s = new SWFShape();

  // first gradient- black to white
  $g = new SWFGradient();
  $g->addEntry(0.0, 0, 0, 0);
  $g->addEntry(1.0, 0xff, 0xff, 0xff);

  $f = $s->addFill($g, SWFFILL_LINEAR_GRADIENT);
  $f->scaleTo(0.01);
  $f->moveTo(160, 120);
  $s->setRightFill($f);
  $s->drawLine(320, 0);
  $s->drawLine(0, 240);
  $s->drawLine(-320, 0);
  $s->drawLine(0, -240);

  $m->add($s);

  $s = new SWFShape();

  // second gradient- radial gradient from red to transparent
  $g = new SWFGradient();
  $g->addEntry(0.0, 0xff, 0, 0, 0xff);
  $g->addEntry(1.0, 0xff, 0, 0, 0);

  $f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
  $f->scaleTo(0.005);
  $f->moveTo(160, 120);
  $s->setRightFill($f);
  $s->drawLine(320, 0);
  $s->drawLine(0, 240);
  $s->drawLine(-320, 0);
  $s->drawLine(0, -240);

  $m->add($s);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>


The SWFMorph class

(PHP 5 < 5.3.0, PECL ming SVN)

Introduction

The methods here are sort of weird. It would make more sense to just have newSWFMorph(shape1, shape2);, but as things are now, shape2 needs to know that it's the second part of a morph. (This, because it starts writing its output as soon as it gets drawing commands- if it kept its own description of its shapes and wrote on completion this and some other things would be much easier.)

Class synopsis

SWFMorph {
/* Methods */
__construct ( void )
getShape1 ( void ) : SWFShape
getShape2 ( void ) : SWFShape
}

Table of Contents

  • SWFMorph::__construct — Creates a new SWFMorph object
  • SWFMorph::getShape1 — Gets a handle to the starting shape
  • SWFMorph::getShape2 — Gets a handle to the ending shape


Creates a new SWFMorph object

  • « SWFMorph
  • SWFMorph::getShape1 »
  • PHP Manual
  • SWFMorph
  • Creates a new SWFMorph object

SWFMorph::__construct

(PHP 5 < 5.3.0, PECL ming SVN)

SWFMorph::__construct — Creates a new SWFMorph object

Description

SWFMorph::__construct ( void )
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.

Creates a new SWFMorph object.

Also called a "shape tween". This thing lets you make those tacky twisting things that make your computer choke. Oh, joy!

Examples

This simple example will morph a big red square into a smaller blue black-bordered square.

Example #1 swfmorph() example

<?php
  $p = new SWFMorph();

  $s = $p->getShape1();
  $s->setLine(0, 0, 0, 0);

  /* Note that this is backwards from normal shapes (left instead of right).
     I have no idea why, but this seems to work.. */

  $s->setLeftFill($s->addFill(0xff, 0, 0));
  $s->movePenTo(-1000,-1000);
  $s->drawLine(2000,0);
  $s->drawLine(0,2000);
  $s->drawLine(-2000,0);
  $s->drawLine(0,-2000);

  $s = $p->getShape2();
  $s->setLine(60,0,0,0);
  $s->setLeftFill($s->addFill(0, 0, 0xff));
  $s->movePenTo(0,-1000);
  $s->drawLine(1000,1000);
  $s->drawLine(-1000,1000);
  $s->drawLine(-1000,-1000);
  $s->drawLine(1000,-1000);

  $m = new SWFMovie();
  $m->setDimension(3000,2000);
  $m->setBackground(0xff, 0xff, 0xff);

  $i = $m->add($p);
  $i->moveTo(1500,1000);

  for ($r=0.0; $r<=1.0; $r+=0.1) {
    $i->setRatio($r);
    $m->nextFrame();
  }

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>


Gets a handle to the starting shape

  • « SWFMorph::__construct
  • SWFMorph::getShape2 »
  • PHP Manual
  • SWFMorph
  • Gets a handle to the starting shape

SWFMorph::getShape1

(PHP 5 < 5.3.0, PECL ming SVN)

SWFMorph::getShape1 — Gets a handle to the starting shape

Description

SWFMorph::getShape1 ( void ) : SWFShape
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.

Gets the morph's starting shape.

Return Values

Returns a SWFShape object.

See Also

  • SWFMorph::getShape2() - Gets a handle to the ending shape


Gets a handle to the ending shape

  • « SWFMorph::getShape1
  • SWFMovie »
  • PHP Manual
  • SWFMorph
  • Gets a handle to the ending shape

SWFMorph::getShape2

(PHP 5 < 5.3.0, PECL ming SVN)

SWFMorph::getShape2 — Gets a handle to the ending shape

Description

SWFMorph::getShape2 ( void ) : SWFShape
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.

Gets the morph's ending shape.

Return Values

Returns a SWFShape object.

See Also

  • SWFMorph::getShape1() - Gets a handle to the starting shape


The SWFMovie class

(PHP 5 < 5.3.0, PECL ming SVN)

Introduction

SWFMovie is a movie object representing an SWF movie.

Class synopsis

SWFMovie {
/* Methods */
add ( object $instance ) : mixed
addExport ( SWFCharacter $char , string $name ) : void
addFont ( SWFFont $font ) : mixed
__construct ([ int $version ] )
importChar ( string $libswf , string $name ) : SWFSprite
importFont ( string $libswf , string $name ) : SWFFontChar
labelFrame ( string $label ) : void
nextFrame ( void ) : void
output ([ int $compression ] ) : int
remove ( object $instance ) : void
save ( string $filename [, int $compression = -1 ] ) : int
saveToFile ( resource $x [, int $compression = -1 ] ) : int
setbackground ( int $red , int $green , int $blue ) : void
setDimension ( float $width , float $height ) : void
setFrames ( int $number ) : void
setRate ( float $rate ) : void
startSound ( SWFSound $sound ) : SWFSoundInstance
stopSound ( SWFSound $sound ) : void
streamMP3 ( mixed $mp3file [, float $skip = 0 ] ) : int
writeExports ( void ) : void
}

Table of Contents

  • SWFMovie::add — Adds any type of data to a movie
  • SWFMovie::addExport — Description
  • SWFMovie::addFont — Description
  • SWFMovie::__construct — Creates a new movie object, representing an SWF version 4 movie
  • SWFMovie::importChar — Description
  • SWFMovie::importFont — Description
  • SWFMovie::labelFrame — Labels a frame
  • SWFMovie::nextFrame — Moves to the next frame of the animation
  • SWFMovie::output — Dumps your lovingly prepared movie out
  • SWFMovie::remove — Removes the object instance from the display list
  • SWFMovie::save — Saves the SWF movie in a file
  • SWFMovie::saveToFile — Description
  • SWFMovie::setbackground — Sets the background color
  • SWFMovie::setDimension — Sets the movie's width and height
  • SWFMovie::setFrames — Sets the total number of frames in the animation
  • SWFMovie::setRate — Sets the animation's frame rate
  • SWFMovie::startSound — Description
  • SWFMovie::stopSound — Description
  • SWFMovie::streamMP3 — Streams a MP3 file
  • SWFMovie::writeExports — Description


Adds any type of data to a movie

  • « SWFMovie
  • SWFMovie::addExport »
  • PHP Manual
  • SWFMovie
  • Adds any type of data to a movie

SWFMovie::add

(PHP 5 < 5.3.0, PECL ming SVN)

SWFMovie::add — Adds any type of data to a movie

Description

SWFMovie::add ( object $instance ) : mixed
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.

Adds an SWF object instance to the current movie.

Parameters

instance

Any type of object instance, like SWFShape, SWFText, SWFFont.

Return Values

For displayable types (shape, text, button, sprite), this returns an SWFDisplayItem, a handle to the object in a display list. Thus, you can add the same shape to a movie multiple times and get separate handles back for each separate instance.

See Also

  • SWFMovie::remove() - Removes the object instance from the display list


Description

  • « SWFMovie::add
  • SWFMovie::addFont »
  • PHP Manual
  • SWFMovie
  • Description

SWFMovie::addExport

(PHP 5 < 5.3.0, PECL ming SVN)

SWFMovie::addExport —

Description

SWFMovie::addExport ( SWFCharacter $char , string $name ) : void
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.


Description

  • « SWFMovie::addExport
  • SWFMovie::__construct »
  • PHP Manual
  • SWFMovie
  • Description

SWFMovie::addFont

(PHP 5 < 5.3.0, PECL ming SVN)

SWFMovie::addFont —

Description

SWFMovie::addFont ( SWFFont $font ) : mixed
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.


Creates a new movie object, representing an SWF version 4 movie

  • « SWFMovie::addFont
  • SWFMovie::importChar »
  • PHP Manual
  • SWFMovie
  • Creates a new movie object, representing an SWF version 4 movie

SWFMovie::__construct

(PHP 5 < 5.3.0, PECL ming SVN)

SWFMovie::__construct — Creates a new movie object, representing an SWF version 4 movie

Description

SWFMovie::__construct ([ int $version ] )
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.

Creates a new movie object, representing an SWF movie.

Parameters

version

The desired SWF version. Default is 4.


Description

  • « SWFMovie::__construct
  • SWFMovie::importFont »
  • PHP Manual
  • SWFMovie
  • Description

SWFMovie::importChar

(PHP 5 < 5.3.0, PECL ming SVN)

SWFMovie::importChar —

Description

SWFMovie::importChar ( string $libswf , string $name ) : SWFSprite
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFMovie::importFont() - Description


Description

  • « SWFMovie::importChar
  • SWFMovie::labelFrame »
  • PHP Manual
  • SWFMovie
  • Description

SWFMovie::importFont

(PHP 5 < 5.3.0, PECL ming SVN)

SWFMovie::importFont —

Description

SWFMovie::importFont ( string $libswf , string $name ) : SWFFontChar
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFMovie::importChar() - Description


Labels a frame

  • « SWFMovie::importFont
  • SWFMovie::nextFrame »
  • PHP Manual
  • SWFMovie
  • Labels a frame

SWFMovie::labelFrame

(PHP 5 < 5.3.0, PECL ming SVN)

SWFMovie::labelFrame — Labels a frame

Description

SWFMovie::labelFrame ( string $label ) : void
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.


Moves to the next frame of the animation

  • « SWFMovie::labelFrame
  • SWFMovie::output »
  • PHP Manual
  • SWFMovie
  • Moves to the next frame of the animation

SWFMovie::nextFrame

(PHP 5 < 5.3.0, PECL ming SVN)

SWFMovie::nextFrame — Moves to the next frame of the animation

Description

SWFMovie::nextFrame ( void ) : void
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.

Moves to the next frame of the animation.

Return Values

No value is returned.


Dumps your lovingly prepared movie out

  • « SWFMovie::nextFrame
  • SWFMovie::remove »
  • PHP Manual
  • SWFMovie
  • Dumps your lovingly prepared movie out

SWFMovie::output

(PHP 5 < 5.3.0, PECL ming SVN)

SWFMovie::output — Dumps your lovingly prepared movie out

Description

SWFMovie::output ([ int $compression ] ) : int
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.

Dumps the SWFMovie.

Don't forget to send the Content-Type HTTP header file before using this function, in order to display the movie in a browser.

Parameters

compression

The compression level can be a value between 0 and 9, defining the SWF compression similar to gzip compression.

This parameter is only available as of Flash MX (6).

Return Values

Return the number of bytes written or FALSE on error.

Examples

Example #1 Displaying your $movie in a browser

<?php
header('Content-type: application/x-shockwave-flash');
$movie->output();
?>

See Also

  • SWFMovie::save() - Saves the SWF movie in a file
  • SWFMovie::saveToFile() - Description


Removes the object instance from the display list

  • « SWFMovie::output
  • SWFMovie::save »
  • PHP Manual
  • SWFMovie
  • Removes the object instance from the display list

SWFMovie::remove

(PHP 5.2.1-5.3.0, PHP 7, PECL ming SVN)

SWFMovie::remove — Removes the object instance from the display list

Description

SWFMovie::remove ( object $instance ) : void
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.

Removes the given object instance from the display list.

Return Values

No value is returned.

See Also

  • SWFMovie::add() - Adds any type of data to a movie


Saves the SWF movie in a file

  • « SWFMovie::remove
  • SWFMovie::saveToFile »
  • PHP Manual
  • SWFMovie
  • Saves the SWF movie in a file

SWFMovie::save

(PHP 5 < 5.3.0, PECL ming SVN)

SWFMovie::save — Saves the SWF movie in a file

Description

SWFMovie::save ( string $filename [, int $compression = -1 ] ) : int
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.

Saves the SWF movie to the specified filename.

Parameters

filename

The path to the saved SWF document.

compression

The compression level can be a value between 0 and 9, defining the SWF compression similar to gzip compression.

This parameter is only available as of Flash MX (6).

Return Values

Return the number of bytes written or FALSE on error.

See Also

  • SWFMovie::output() - Dumps your lovingly prepared movie out
  • SWFMovie::saveToFile() - Description


Description

  • « SWFMovie::save
  • SWFMovie::setbackground »
  • PHP Manual
  • SWFMovie
  • Description

SWFMovie::saveToFile

(PHP 5 < 5.3.0, PECL ming SVN)

SWFMovie::saveToFile —

Description

SWFMovie::saveToFile ( resource $x [, int $compression = -1 ] ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

X

compression

The compression level can be a value between 0 and 9, defining the SWF compression similar to gzip compression.

This parameter is only available as of Flash MX (6).

Return Values

Return the number of bytes written or FALSE on error.

See Also

  • SWFMovie::output() - Dumps your lovingly prepared movie out
  • SWFMovie::save() - Saves the SWF movie in a file


Sets the background color

  • « SWFMovie::saveToFile
  • SWFMovie::setDimension »
  • PHP Manual
  • SWFMovie
  • Sets the background color

SWFMovie::setbackground

(PHP 5 < 5.3.0, PECL ming SVN)

SWFMovie::setbackground — Sets the background color

Description

SWFMovie::setbackground ( int $red , int $green , int $blue ) : void
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.

Sets the background color.

Why is there no rgba version? Think about it, you might want to let the HTML background show through. There's a way to do that, but it only works on IE4. Search the » http://www.macromedia.com/ site for details.

Parameters

These parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF:

red

Value of red component

green

Value of green component

blue

Value of blue component

Return Values

No value is returned.


Sets the movie's width and height

  • « SWFMovie::setbackground
  • SWFMovie::setFrames »
  • PHP Manual
  • SWFMovie
  • Sets the movie's width and height

SWFMovie::setDimension

(PHP 5 < 5.3.0, PECL ming SVN)

SWFMovie::setDimension — Sets the movie's width and height

Description

SWFMovie::setDimension ( float $width , float $height ) : void
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.

Sets the movie's dimension to the specified width and height.

Parameters

width

The movie width.

height

The movie height.

Return Values

No value is returned.


Sets the total number of frames in the animation

  • « SWFMovie::setDimension
  • SWFMovie::setRate »
  • PHP Manual
  • SWFMovie
  • Sets the total number of frames in the animation

SWFMovie::setFrames

(PHP 5 < 5.3.0, PECL ming SVN)

SWFMovie::setFrames — Sets the total number of frames in the animation

Description

SWFMovie::setFrames ( int $number ) : void
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.

Sets the total number of frames in the animation to the given number.

Parameters

number

The number of frames.

Return Values

No value is returned.


Sets the animation's frame rate

  • « SWFMovie::setFrames
  • SWFMovie::startSound »
  • PHP Manual
  • SWFMovie
  • Sets the animation's frame rate

SWFMovie::setRate

(PHP 5 < 5.3.0, PECL ming SVN)

SWFMovie::setRate — Sets the animation's frame rate

Description

SWFMovie::setRate ( float $rate ) : void
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.

Sets the frame rate to the specified rate.

Animation will slow down if the player can't render frames fast enough- unless there's a streaming sound, in which case display frames are sacrificed to keep sound from skipping.

Parameters

rate

The frame rate, in frame per seconds.

Return Values

No value is returned.


Description

  • « SWFMovie::setRate
  • SWFMovie::stopSound »
  • PHP Manual
  • SWFMovie
  • Description

SWFMovie::startSound

(PHP 5 < 5.3.0, PECL ming SVN)

SWFMovie::startSound —

Description

SWFMovie::startSound ( SWFSound $sound ) : SWFSoundInstance
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFMovie::stopSound() - Description


Description

  • « SWFMovie::startSound
  • SWFMovie::streamMP3 »
  • PHP Manual
  • SWFMovie
  • Description

SWFMovie::stopSound

(PHP 5 < 5.3.0, PECL ming SVN)

SWFMovie::stopSound —

Description

SWFMovie::stopSound ( SWFSound $sound ) : void
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

See Also

  • SWFMovie::startSound() - Description


Streams a MP3 file

  • « SWFMovie::stopSound
  • SWFMovie::writeExports »
  • PHP Manual
  • SWFMovie
  • Streams a MP3 file

SWFMovie::streamMP3

(PHP 5 < 5.3.0, PECL ming SVN)

SWFMovie::streamMP3 — Streams a MP3 file

Description

SWFMovie::streamMP3 ( mixed $mp3file [, float $skip = 0 ] ) : int
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.

Streams the given MP3 file mp3file.

This method is not very robust in dealing with oddities (can skip over an initial ID3 tag, but that's about it).

Note that the movie isn't smart enough to put enough frames in to contain the entire mp3 stream- you'll have to add (length of song * frames per second) frames to get the entire stream in.

Parameters

mp3file

Can be a file pointer returned by fopen() or the MP3 data, as a binary string.

skip

Number of seconds to skip.

Return Values

Return number of frames.

Changelog

Version | Description
5.2.0 | skip added

Examples

Example #1 Streaming example

<?php
$m = new SWFMovie();
$m->setRate(12.0);
$m->streamMp3(file_get_contents("distortobass.mp3"));
// use your own MP3

// The file is 11.85 seconds at 12.0 fps = 142 frames
$m->setFrames(142);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>


Description

  • « SWFMovie::streamMP3
  • SWFPrebuiltClip »
  • PHP Manual
  • SWFMovie
  • Description

SWFMovie::writeExports

(PHP 5 < 5.3.0, PECL ming SVN)

SWFMovie::writeExports —

Description

SWFMovie::writeExports ( void ) : void
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.


The SWFPrebuiltClip class

(PHP 5.0.5-5.3.0, PHP 7, PECL ming SVN)

Introduction

SWFPrebuiltClip.

Class synopsis

SWFPrebuiltClip {
/* Methods */
__construct ( mixed $file )
}

Table of Contents

  • SWFPrebuiltClip::__construct — Returns a SWFPrebuiltClip object


Returns a SWFPrebuiltClip object

  • « SWFPrebuiltClip
  • SWFShape »
  • PHP Manual
  • SWFPrebuiltClip
  • Returns a SWFPrebuiltClip object

SWFPrebuiltClip::__construct

(PHP 5.0.5-5.3.0, PHP 7, PECL ming SVN)

SWFPrebuiltClip::__construct — Returns a SWFPrebuiltClip object

Description

SWFPrebuiltClip::__construct ( mixed $file )
Warning

This function is currently not documented; only its argument list is available.


The SWFShape class

(PHP 5 < 5.3.0, PECL ming SVN)

Introduction

SWFShape.

Class synopsis

SWFShape {
/* Methods */
addFill ( int $red , int $green , int $blue [, int $alpha = 255 ] ) : SWFFill
__construct ( void )
drawArc ( float $r , float $startAngle , float $endAngle ) : void
drawCircle ( float $r ) : void
drawCubic ( float $bx , float $by , float $cx , float $cy , float $dx , float $dy ) : int
drawCubicTo ( float $bx , float $by , float $cx , float $cy , float $dx , float $dy ) : int
drawCurve ( float $controldx , float $controldy , float $anchordx , float $anchordy [, float $targetdx ], float $targetdy ) : int
drawCurveTo ( float $controlx , float $controly , float $anchorx , float $anchory [, float $targetx ], float $targety ) : int
drawGlyph ( SWFFont $font , string $character [, int $size ] ) : void
drawLine ( float $dx , float $dy ) : void
drawLineTo ( float $x , float $y ) : void
movePen ( float $dx , float $dy ) : void
movePenTo ( float $x , float $y ) : void
setLeftFill ( SWFGradient $fill ) : void
setLine ( SWFShape $shape ) : void
setRightFill ( SWFGradient $fill ) : void
}

Table of Contents

  • SWFShape::addFill — Adds a solid fill to the shape
  • SWFShape::__construct — Creates a new shape object
  • SWFShape::drawArc — Draws an arc of radius r centered at the current location, from angle startAngle to angle endAngle measured clockwise from 12 o'clock
  • SWFShape::drawCircle — Draws a circle of radius r centered at the current location, in a counter-clockwise fashion
  • SWFShape::drawCubic — Draws a cubic bezier curve using the current position and the three given points as control points
  • SWFShape::drawCubicTo — Draws a cubic bezier curve using the current position and the three given points as control points
  • SWFShape::drawCurve — Draws a curve (relative)
  • SWFShape::drawCurveTo — Draws a curve
  • SWFShape::drawGlyph — Draws the first character in the given string into the shape using the glyph definition from the given font
  • SWFShape::drawLine — Draws a line (relative)
  • SWFShape::drawLineTo — Draws a line
  • SWFShape::movePen — Moves the shape's pen (relative)
  • SWFShape::movePenTo — Moves the shape's pen
  • SWFShape::setLeftFill — Sets left rasterizing color
  • SWFShape::setLine — Sets the shape's line style
  • SWFShape::setRightFill — Sets right rasterizing color


Adds a solid fill to the shape

  • « SWFShape
  • SWFShape::__construct »
  • PHP Manual
  • SWFShape
  • Adds a solid fill to the shape

SWFShape::addFill

(PHP 5 < 5.3.0, PECL ming SVN)

SWFShape::addFill — Adds a solid fill to the shape

Description

SWFShape::addFill ( int $red , int $green , int $blue [, int $alpha = 255 ] ) : SWFFill
addFill ( SWFBitmap $bitmap [, int $flags ] ) : SWFFill
addFill ( SWFGradient $gradient [, int $flags ] ) : SWFFill
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.

SWFShape::addFill() adds a solid fill to the shape's list of fill styles. SWFShape::addFill() accepts three different types of arguments.

red, green, blue is a color (RGB mode).

The bitmap argument is an SWFBitmap() object. The flags argument can be one of the following values: SWFFILL_CLIPPED_BITMAP, SWFFILL_TILED_BITMAP, SWFFILL_LINEAR_GRADIENT or SWFFILL_RADIAL_GRADIENT. Default is SWFFILL_TILED_BITMAP for SWFBitmap and SWFFILL_LINEAR_GRADIENT for SWFGradient.

The gradient argument is an SWFGradient() object. The flags argument can be one of the following values : SWFFILL_RADIAL_GRADIENT or SWFFILL_LINEAR_GRADIENT. Default is SWFFILL_LINEAR_GRADIENT. I'm sure about this one. Really.

SWFShape::addFill() returns an SWFFill()
object for use with the SWFShape::setLeftFill()
and SWFShape::setRightFill() functions
described below.

Examples

This simple example will draw a frame on a bitmap. Ah, here's another buglet in the flash player- it doesn't seem to care about the second shape's bitmap's transformation in a morph. According to spec, the bitmap should stretch along with the shape in this example..

Example #1 SWFShape::addFill() example

<?php

$p = new SWFMorph();

$b = new SWFBitmap(file_get_contents("alphafill.jpg"));
// use your own bitmap
$width = $b->getWidth();
$height = $b->getHeight();

$s = $p->getShape1();
$f = $s->addFill($b, SWFFILL_TILED_BITMAP);
$f->moveTo(-$width/2, -$height/4);
$f->scaleTo(1.0, 0.5);
$s->setLeftFill($f);
$s->movePenTo(-$width/2, -$height/4);
$s->drawLine($width, 0);
$s->drawLine(0, $height/2);
$s->drawLine(-$width, 0);
$s->drawLine(0, -$height/2);

$s = $p->getShape2();
$f = $s->addFill($b, SWFFILL_TILED_BITMAP);

// these two have no effect!
$f->moveTo(-$width/4, -$height/2);
$f->scaleTo(0.5, 1.0);

$s->setLeftFill($f);
$s->movePenTo(-$width/4, -$height/2);
$s->drawLine($width/2, 0);
$s->drawLine(0, $height);
$s->drawLine(-$width/2, 0);
$s->drawLine(0, -$height);

$m = new SWFMovie();
$m->setDimension($width, $height);
$i = $m->add($p);
$i->moveTo($width/2, $height/2);

for ($n=0; $n<1.001; $n+=0.03) {
    $i->setRatio($n);
    $m->nextFrame();
}

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

See Also

  • SWFShape::setLeftFill() - Sets left rasterizing color
  • SWFShape::setRightFill() - Sets right rasterizing color


Creates a new shape object

  • « SWFShape::addFill
  • SWFShape::drawArc »
  • PHP Manual
  • SWFShape
  • Creates a new shape object

SWFShape::__construct

(PHP 5 < 5.3.0, PECL ming SVN)

SWFShape::__construct — Creates a new shape object

Description

SWFShape::__construct ( void )
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.

Created a new SWFShape object.

Examples

This simple example will draw a big red elliptic quadrant.

Example #1 swfshape() example

<?php
$s = new SWFShape();
$s->setLine(40, 0x7f, 0, 0);
$s->setRightFill($s->addFill(0xff, 0, 0));
$s->movePenTo(200, 200);
$s->drawLineTo(6200, 200);
$s->drawLineTo(6200, 4600);
$s->drawCurveTo(200, 4600, 200, 200);

$m = new SWFMovie();
$m->setDimension(6400, 4800);
$m->setRate(12.0);
$m->add($s);
$m->nextFrame();

header('Content-type: application/x-shockwave-flash');
$m->output();
?>


Draws an arc of radius r centered at the current location, from angle startAngle to angle endAngle measured clockwise from 12 o'clock

  • « SWFShape::__construct
  • SWFShape::drawCircle »
  • PHP Manual
  • SWFShape
  • Draws an arc of radius r centered at the current location, from angle startAngle to angle endAngle measured clockwise from 12 o'clock

SWFShape::drawArc

(PHP 5 < 5.3.0, PECL ming SVN)

SWFShape::drawArc — Draws an arc of radius r centered at the current location, from angle startAngle to angle endAngle measured clockwise from 12 o'clock

Description

SWFShape::drawArc ( float $r , float $startAngle , float $endAngle ) : void
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

See Also

  • SWFShape::drawCircle() - Draws a circle of radius r centered at the current location, in a counter-clockwise fashion


Draws a circle of radius r centered at the current location, in a counter-clockwise fashion

  • « SWFShape::drawArc
  • SWFShape::drawCubic »
  • PHP Manual
  • SWFShape
  • Draws a circle of radius r centered at the current location, in a counter-clockwise fashion

SWFShape::drawCircle

(PHP 5 < 5.3.0, PECL ming SVN)

SWFShape::drawCircle — Draws a circle of radius r centered at the current location, in a counter-clockwise fashion

Description

SWFShape::drawCircle ( float $r ) : void
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.


Draws a cubic bezier curve using the current position and the three given points as control points

  • « SWFShape::drawCircle
  • SWFShape::drawCubicTo »
  • PHP Manual
  • SWFShape
  • Draws a cubic bezier curve using the current position and the three given points as control points

SWFShape::drawCubic

(PHP 5 < 5.3.0, PECL ming SVN)

SWFShape::drawCubic — Draws a cubic bezier curve using the current position and the three given points as control points

Description

SWFShape::drawCubic ( float $bx , float $by , float $cx , float $cy , float $dx , float $dy ) : int
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFShape::drawCubicTo() - Draws a cubic bezier curve using the current position and the three given points as control points


Draws a cubic bezier curve using the current position and the three given points as control points

  • « SWFShape::drawCubic
  • SWFShape::drawCurve »
  • PHP Manual
  • SWFShape
  • Draws a cubic bezier curve using the current position and the three given points as control points

SWFShape::drawCubicTo

(PHP 5 < 5.3.0, PECL ming SVN)

SWFShape::drawCubicTo — Draws a cubic bezier curve using the current position and the three given points as control points

Description

SWFShape::drawCubicTo ( float $bx , float $by , float $cx , float $cy , float $dx , float $dy ) : int
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFShape::drawCubic() - Draws a cubic bezier curve using the current position and the three given points as control points


Draws a curve (relative)

  • « SWFShape::drawCubicTo
  • SWFShape::drawCurveTo »
  • PHP Manual
  • SWFShape
  • Draws a curve (relative)

SWFShape::drawCurve

(PHP 5 < 5.3.0, PECL ming SVN)

SWFShape::drawCurve — Draws a curve (relative)

Description

SWFShape::drawCurve ( float $controldx , float $controldy , float $anchordx , float $anchordy [, float $targetdx ], float $targetdy ) : int
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.

swfshape::drawcurve() draws a quadratic curve (using the current line style,set by swfshape::setline()) from the current pen position to the relative position (anchorx,anchory) using relative control point (controlx,controly). That is, head towards the control point, then smoothly turn to the anchor point.

With 6 parameters, it draws a cubic bezier to point (x+targetdx, x+targetdy) with control points (x+controldx, y+controldy) and (x+anchordx, y+anchordy).

See Also

  • SWFShape::drawCurve()


Draws a curve

  • « SWFShape::drawCurve
  • SWFShape::drawGlyph »
  • PHP Manual
  • SWFShape
  • Draws a curve

SWFShape::drawCurveTo

(PHP 5 < 5.3.0, PECL ming SVN)

SWFShape::drawCurveTo — Draws a curve

Description

SWFShape::drawCurveTo ( float $controlx , float $controly , float $anchorx , float $anchory [, float $targetx ], float $targety ) : int
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.

swfshape::drawcurveto() draws a quadratic curve (using the current line style, set by swfshape::setline()) from the current pen position to (anchorx,anchory) using (controlx,controly) as a control point. That is, head towards the control point, then smoothly turn to the anchor point.

With 6 parameters, it draws a cubic bezier to point (targetx, targety) with control points (controlx, controly) and (anchorx, anchory).

See Also

  • SWFShape::drawCurveTo()


Draws the first character in the given string into the shape using the glyph definition from the given font

  • « SWFShape::drawCurveTo
  • SWFShape::drawLine »
  • PHP Manual
  • SWFShape
  • Draws the first character in the given string into the shape using the glyph definition from the given font

SWFShape::drawGlyph

(PHP 5 < 5.3.0, PECL ming SVN)

SWFShape::drawGlyph — Draws the first character in the given string into the shape using the glyph definition from the given font

Description

SWFShape::drawGlyph ( SWFFont $font , string $character [, int $size ] ) : void
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.


Draws a line (relative)

  • « SWFShape::drawGlyph
  • SWFShape::drawLineTo »
  • PHP Manual
  • SWFShape
  • Draws a line (relative)

SWFShape::drawLine

(PHP 5 < 5.3.0, PECL ming SVN)

SWFShape::drawLine — Draws a line (relative)

Description

SWFShape::drawLine ( float $dx , float $dy ) : void
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.

swfshape::drawline() draws a line (using the current line style set by swfshape::setline()) from the current pen position to displacement (dx,dy).

Return Values

No value is returned.

See Also

  • SWFShape::drawLineTo() - Draws a line


Draws a line

  • « SWFShape::drawLine
  • SWFShape::movePen »
  • PHP Manual
  • SWFShape
  • Draws a line

SWFShape::drawLineTo

(PHP 5 < 5.3.0, PECL ming SVN)

SWFShape::drawLineTo — Draws a line

Description

SWFShape::drawLineTo ( float $x , float $y ) : void
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.

swfshape::setrightfill() draws a line (using the current line style, set by swfshape::setline()) from the current pen position to point (x,y) in the shape's coordinate space.

Return Values

No value is returned.

See Also

  • SWFShape::drawLine() - Draws a line (relative)


Moves the shape's pen (relative)

  • « SWFShape::drawLineTo
  • SWFShape::movePenTo »
  • PHP Manual
  • SWFShape
  • Moves the shape's pen (relative)

SWFShape::movePen

(PHP 5 < 5.3.0, PECL ming SVN)

SWFShape::movePen — Moves the shape's pen (relative)

Description

SWFShape::movePen ( float $dx , float $dy ) : void
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.

swfshape::setrightfill() move the shape's pen from coordinates (current x,current y) to (current x + dx, current y + dy) in the shape's coordinate space.

Return Values

No value is returned.

See Also

  • SWFShape::movePenTo() - Moves the shape's pen


Moves the shape's pen

  • « SWFShape::movePen
  • SWFShape::setLeftFill »
  • PHP Manual
  • SWFShape
  • Moves the shape's pen

SWFShape::movePenTo

(PHP 5 < 5.3.0, PECL ming SVN)

SWFShape::movePenTo — Moves the shape's pen

Description

SWFShape::movePenTo ( float $x , float $y ) : void
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.

swfshape::setrightfill() move the shape's pen to (x,y) in the shape's coordinate space.

Return Values

No value is returned.

See Also

  • SWFShape::movePen() - Moves the shape's pen (relative)


Sets left rasterizing color

  • « SWFShape::movePenTo
  • SWFShape::setLine »
  • PHP Manual
  • SWFShape
  • Sets left rasterizing color

SWFShape::setLeftFill

(PHP 5 < 5.3.0, PECL ming SVN)

SWFShape::setLeftFill — Sets left rasterizing color

Description

SWFShape::setLeftFill ( SWFGradient $fill ) : void
setLeftFill ( int $red , int $green , int $blue [, int $a ] ) : void
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.

What this nonsense is about is, every edge segment borders at most two fills. When rasterizing the object, it's pretty handy to know what those fills are ahead of time, so the swf format requires these to be specified.

swfshape::setleftfill() sets the fill on the left side of the edge- that is, on the interior if you're defining the outline of the shape in a counter-clockwise fashion. The fill object is an SWFFill object returned from one of the addFill functions above.

This seems to be reversed when you're defining a shape in a morph, though. If your browser crashes, just try setting the fill on the other side.

Shortcut for $swfshape->setleftfill($s->addfill($r, $g, $b [, $a]));.

Return Values

No value is returned.

See Also

  • SWFShape::setRightFill() - Sets right rasterizing color


Sets the shape's line style

  • « SWFShape::setLeftFill
  • SWFShape::setRightFill »
  • PHP Manual
  • SWFShape
  • Sets the shape's line style

SWFShape::setLine

(PHP 5 < 5.3.0, PECL ming SVN)

SWFShape::setLine — Sets the shape's line style

Description

SWFShape::setLine ( SWFShape $shape ) : void
setLine ( int $width , int $red , int $green , int $blue [, int $a ] ) : void
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.

swfshape::setline() sets the shape's line style. width is the line's width. If width is 0, the line's style is removed (then, all other arguments are ignored). If width > 0, then line's color is set to red, green, blue. Last parameter a is optional.

You must declare all line styles before you use them (see example).

Return Values

No value is returned.

Examples

This simple example will draw a big "!#%*@", in funny colors and gracious style.

Example #1 swfshape::setline() example

<?php
$s = new SWFShape();
$f1 = $s->addFill(0xff, 0, 0);
$f2 = $s->addFill(0xff, 0x7f, 0);
$f3 = $s->addFill(0xff, 0xff, 0);
$f4 = $s->addFill(0, 0xff, 0);
$f5 = $s->addFill(0, 0, 0xff);

// bug: have to declare all line styles before you use them
$s->setLine(40, 0x7f, 0, 0);
$s->setLine(40, 0x7f, 0x3f, 0);
$s->setLine(40, 0x7f, 0x7f, 0);
$s->setLine(40, 0, 0x7f, 0);
$s->setLine(40, 0, 0, 0x7f);

$f = new SWFFont('Techno.fdb');

$s->setRightFill($f1);
$s->setLine(40, 0x7f, 0, 0);
$s->drawGlyph($f, '!');
$s->movePen($f->getWidth('!'), 0);

$s->setRightFill($f2);
$s->setLine(40, 0x7f, 0x3f, 0);
$s->drawGlyph($f, '#');
$s->movePen($f->getWidth('#'), 0);

$s->setRightFill($f3);
$s->setLine(40, 0x7f, 0x7f, 0);
$s->drawGlyph($f, '%');
$s->movePen($f->getWidth('%'), 0);

$s->setRightFill($f4);
$s->setLine(40, 0, 0x7f, 0);
$s->drawGlyph($f, '*');
$s->movePen($f->getWidth('*'), 0);

$s->setRightFill($f5);
$s->setLine(40, 0, 0, 0x7f);
$s->drawGlyph($f, '@');

$m = new SWFMovie();
$m->setDimension(3000,2000);
$m->setRate(12.0);
$i = $m->add($s);
$i->moveTo(1500-$f->getWidth("!#%*@")/2, 1000+$f->getAscent()/2);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>

Return Values

No value is returned.


Sets right rasterizing color

  • « SWFShape::setLine
  • SWFSound »
  • PHP Manual
  • SWFShape
  • Sets right rasterizing color

SWFShape::setRightFill

(PHP 5 < 5.3.0, PECL ming SVN)

SWFShape::setRightFill — Sets right rasterizing color

Description

SWFShape::setRightFill ( SWFGradient $fill ) : void
setRightFill ( int $red , int $green , int $blue [, int $a ] ) : void
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.

Shortcut for $swfshape->setrightfill($s->addfill($r, $g, $b [, $a]));.

Return Values

No value is returned.

See Also

  • SWFShape::setLeftFill() - Sets left rasterizing color


The SWFSound class

(PHP 5 < 5.3.0, PECL ming SVN)

Introduction

SWFSound.

Class synopsis

SWFSound {
/* Methods */
__construct ( string $filename [, int $flags = 0 ] )
}

Table of Contents

  • SWFSound::__construct — Returns a new SWFSound object from given file


Returns a new SWFSound object from given file

  • « SWFSound
  • SWFSoundInstance »
  • PHP Manual
  • SWFSound
  • Returns a new SWFSound object from given file

SWFSound::__construct

(PHP 5 < 5.3.0, PECL ming SVN)

SWFSound::__construct — Returns a new SWFSound object from given file

Description

SWFSound::__construct ( string $filename [, int $flags = 0 ] )
Warning

This function is currently not documented; only its argument list is available.


The SWFSoundInstance class

(PHP 5 < 5.3.0, PECL ming SVN)

Introduction

SWFSoundInstance objects are returned by the SWFSprite::startSound() and SWFMovie::startSound() methods.

Class synopsis

SWFSoundInstance {
/* Methods */
loopCount ( int $point ) : void
loopInPoint ( int $point ) : void
loopOutPoint ( int $point ) : void
noMultiple ( void ) : void
}

Table of Contents

  • SWFSoundInstance::loopCount — Description
  • SWFSoundInstance::loopInPoint — Description
  • SWFSoundInstance::loopOutPoint — Description
  • SWFSoundInstance::noMultiple — Description


Description

  • « SWFSoundInstance
  • SWFSoundInstance::loopInPoint »
  • PHP Manual
  • SWFSoundInstance
  • Description

SWFSoundInstance::loopCount

(PHP 5 < 5.3.0, PECL ming SVN)

SWFSoundInstance::loopCount —

Description

SWFSoundInstance::loopCount ( int $point ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

point

Return Values

No value is returned.

See Also

  • SWFSoundInstance::loopOutPoint() - Description


Description

  • « SWFSoundInstance::loopCount
  • SWFSoundInstance::loopOutPoint »
  • PHP Manual
  • SWFSoundInstance
  • Description

SWFSoundInstance::loopInPoint

(PHP 5 < 5.3.0, PECL ming SVN)

SWFSoundInstance::loopInPoint —

Description

SWFSoundInstance::loopInPoint ( int $point ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

point

Return Values

No value is returned.

See Also

  • SWFSoundInstance::loopOutPoint() - Description


Description

  • « SWFSoundInstance::loopInPoint
  • SWFSoundInstance::noMultiple »
  • PHP Manual
  • SWFSoundInstance
  • Description

SWFSoundInstance::loopOutPoint

(PHP 5 < 5.3.0, PECL ming SVN)

SWFSoundInstance::loopOutPoint —

Description

SWFSoundInstance::loopOutPoint ( int $point ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

point

Return Values

No value is returned.

See Also

  • SWFSoundInstance::loopInPoint() - Description


Description

  • « SWFSoundInstance::loopOutPoint
  • SWFSprite »
  • PHP Manual
  • SWFSoundInstance
  • Description

SWFSoundInstance::noMultiple

(PHP 5 < 5.3.0, PECL ming SVN)

SWFSoundInstance::noMultiple —

Description

SWFSoundInstance::noMultiple ( void ) : void
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.


The SWFSprite class

(PHP 5 < 5.3.0, PECL ming SVN)

Introduction

An SWFSprite is also known as a "movie clip", this allows one to create objects which are animated in their own timelines. Hence, the sprite has most of the same methods as the movie.

Class synopsis

SWFSprite {
/* Methods */
add ( object $object ) : void
__construct ( void )
labelFrame ( string $label ) : void
nextFrame ( void ) : void
remove ( object $object ) : void
setFrames ( int $number ) : void
startSound ( SWFSound $sount ) : SWFSoundInstance
stopSound ( SWFSound $sount ) : void
}

Table of Contents

  • SWFSprite::add — Adds an object to a sprite
  • SWFSprite::__construct — Creates a movie clip (a sprite)
  • SWFSprite::labelFrame — Labels frame
  • SWFSprite::nextFrame — Moves to the next frame of the animation
  • SWFSprite::remove — Removes an object to a sprite
  • SWFSprite::setFrames — Sets the total number of frames in the animation
  • SWFSprite::startSound — Description
  • SWFSprite::stopSound — Description


Adds an object to a sprite

  • « SWFSprite
  • SWFSprite::__construct »
  • PHP Manual
  • SWFSprite
  • Adds an object to a sprite

SWFSprite::add

(PHP 5 < 5.3.0, PECL ming SVN)

SWFSprite::add — Adds an object to a sprite

Description

SWFSprite::add ( object $object ) : void
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.

swfsprite::add() adds a swfshape(), a
swfbutton(), a swftext(),
a swfaction() or a swfsprite() object.

For displayable types (swfshape(),
swfbutton(), swftext(),
swfaction() or swfsprite()),
this returns a handle  to the object in a display list.

Return Values

No value is returned.


Creates a movie clip (a sprite)

  • « SWFSprite::add
  • SWFSprite::labelFrame »
  • PHP Manual
  • SWFSprite
  • Creates a movie clip (a sprite)

SWFSprite::__construct

(PHP 5 < 5.3.0, PECL ming SVN)

SWFSprite::__construct — Creates a movie clip (a sprite)

Description

SWFSprite::__construct ( void )
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.

Creates a new SWFSprite object.


Labels frame

  • « SWFSprite::__construct
  • SWFSprite::nextFrame »
  • PHP Manual
  • SWFSprite
  • Labels frame

SWFSprite::labelFrame

(PHP 5 < 5.3.0, PECL ming SVN)

SWFSprite::labelFrame — Labels frame

Description

SWFSprite::labelFrame ( string $label ) : void
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.


Moves to the next frame of the animation

  • « SWFSprite::labelFrame
  • SWFSprite::remove »
  • PHP Manual
  • SWFSprite
  • Moves to the next frame of the animation

SWFSprite::nextFrame

(PHP 5 < 5.3.0, PECL ming SVN)

SWFSprite::nextFrame — Moves to the next frame of the animation

Description

SWFSprite::nextFrame ( void ) : void
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.

swfsprite::setframes() moves to the next frame of the animation.

Return Values

No value is returned.


Removes an object to a sprite

  • « SWFSprite::nextFrame
  • SWFSprite::setFrames »
  • PHP Manual
  • SWFSprite
  • Removes an object to a sprite

SWFSprite::remove

(PHP 5 < 5.3.0, PECL ming SVN)

SWFSprite::remove — Removes an object to a sprite

Description

SWFSprite::remove ( object $object ) : void
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.

swfsprite::remove() remove a swfshape(), a
swfbutton(), a swftext(),
a swfaction() or a swfsprite() object
from the sprite.

Return Values

No value is returned.


Sets the total number of frames in the animation

  • « SWFSprite::remove
  • SWFSprite::startSound »
  • PHP Manual
  • SWFSprite
  • Sets the total number of frames in the animation

SWFSprite::setFrames

(PHP 5 < 5.3.0, PECL ming SVN)

SWFSprite::setFrames — Sets the total number of frames in the animation

Description

SWFSprite::setFrames ( int $number ) : void
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.

swfsprite::setframes() sets the total number of frames in the animation to numberofframes.

Return Values

No value is returned.


Description

  • « SWFSprite::setFrames
  • SWFSprite::stopSound »
  • PHP Manual
  • SWFSprite
  • Description

SWFSprite::startSound

(PHP 5 < 5.3.0, PECL ming SVN)

SWFSprite::startSound —

Description

SWFSprite::startSound ( SWFSound $sount ) : SWFSoundInstance
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFSprite::stopSound() - Description


Description

  • « SWFSprite::startSound
  • SWFText »
  • PHP Manual
  • SWFSprite
  • Description

SWFSprite::stopSound

(PHP 5 < 5.3.0, PECL ming SVN)

SWFSprite::stopSound —

Description

SWFSprite::stopSound ( SWFSound $sount ) : void
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

See Also

  • SWFSprite::startSound() - Description


The SWFText class

(PHP 5 < 5.3.0, PECL ming SVN)

Introduction

SWFText.

Class synopsis

SWFText {
/* Methods */
addString ( string $string ) : void
addUTF8String ( string $text ) : void
__construct ( void )
getAscent ( void ) : float
getDescent ( void ) : float
getLeading ( void ) : float
getUTF8Width ( string $string ) : float
getWidth ( string $string ) : float
moveTo ( float $x , float $y ) : void
setColor ( int $red , int $green , int $blue [, int $a = 255 ] ) : void
setFont ( SWFFont $font ) : void
setHeight ( float $height ) : void
setSpacing ( float $spacing ) : void
}

Table of Contents

  • SWFText::addString — Draws a string
  • SWFText::addUTF8String — Writes the given text into this SWFText object at the current pen position, using the current font, height, spacing, and color
  • SWFText::__construct — Creates a new SWFText object
  • SWFText::getAscent — Returns the ascent of the current font at its current size, or 0 if not available
  • SWFText::getDescent — Returns the descent of the current font at its current size, or 0 if not available
  • SWFText::getLeading — Returns the leading of the current font at its current size, or 0 if not available
  • SWFText::getUTF8Width — Calculates the width of the given string in this text objects current font and size
  • SWFText::getWidth — Computes string's width
  • SWFText::moveTo — Moves the pen
  • SWFText::setColor — Sets the current text color
  • SWFText::setFont — Sets the current font
  • SWFText::setHeight — Sets the current font height
  • SWFText::setSpacing — Sets the current font spacing


Draws a string

  • « SWFText
  • SWFText::addUTF8String »
  • PHP Manual
  • SWFText
  • Draws a string

SWFText::addString

(PHP 5 < 5.3.0, PECL ming SVN)

SWFText::addString — Draws a string

Description

SWFText::addString ( string $string ) : void
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.

swftext::addstring() draws the string string at the current pen (cursor) location. Pen is at the baseline of the text; i.e., ascending text is in the -y direction.

Return Values

No value is returned.

See Also

  • SWFText::addUTF8String() - Writes the given text into this SWFText object at the current pen position, using the current font, height, spacing, and color


Writes the given text into this SWFText object at the current pen position, using the current font, height, spacing, and color

  • « SWFText::addString
  • SWFText::__construct »
  • PHP Manual
  • SWFText
  • Writes the given text into this SWFText object at the current pen position, using the current font, height, spacing, and color

SWFText::addUTF8String

(PHP 5 < 5.3.0, PECL ming SVN)

SWFText::addUTF8String — Writes the given text into this SWFText object at the current pen position, using the current font, height, spacing, and color

Description

SWFText::addUTF8String ( string $text ) : void
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

See Also

  • SWFText::addString() - Draws a string


Creates a new SWFText object

  • « SWFText::addUTF8String
  • SWFText::getAscent »
  • PHP Manual
  • SWFText
  • Creates a new SWFText object

SWFText::__construct

(PHP 5 < 5.3.0, PECL ming SVN)

SWFText::__construct — Creates a new SWFText object

Description

SWFText::__construct ( void )
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.

Creates a new SWFText object, fresh for manipulating.

Examples

This simple example will draw a big yellow "PHP generates Flash with Ming" text, on white background.

Example #1 swftext() example

<?php
$f = new SWFFont("Techno.fdb");
$t = new SWFText();
$t->setFont($f);
$t->moveTo(200, 2400);
$t->setColor(0xff, 0xff, 0);
$t->setHeight(1200);
$t->addString("PHP generates Flash with Ming!!");

$m = new SWFMovie();
$m->setDimension(5400, 3600);

$m->add($t);

header('Content-type: application/x-shockwave-flash');
$m->output();
?>


Returns the ascent of the current font at its current size, or 0 if not available

  • « SWFText::__construct
  • SWFText::getDescent »
  • PHP Manual
  • SWFText
  • Returns the ascent of the current font at its current size, or 0 if not available

SWFText::getAscent

(PHP 5 < 5.3.0, PECL ming SVN)

SWFText::getAscent — Returns the ascent of the current font at its current size, or 0 if not available

Description

SWFText::getAscent ( void ) : float
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFText::getDescent() - Returns the descent of the current font at its current size, or 0 if not available


Returns the descent of the current font at its current size, or 0 if not available

  • « SWFText::getAscent
  • SWFText::getLeading »
  • PHP Manual
  • SWFText
  • Returns the descent of the current font at its current size, or 0 if not available

SWFText::getDescent

(PHP 5 < 5.3.0, PECL ming SVN)

SWFText::getDescent — Returns the descent of the current font at its current size, or 0 if not available

Description

SWFText::getDescent ( void ) : float
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFText::getAscent() - Returns the ascent of the current font at its current size, or 0 if not available


Returns the leading of the current font at its current size, or 0 if not available

  • « SWFText::getDescent
  • SWFText::getUTF8Width »
  • PHP Manual
  • SWFText
  • Returns the leading of the current font at its current size, or 0 if not available

SWFText::getLeading

(PHP 5 < 5.3.0, PECL ming SVN)

SWFText::getLeading — Returns the leading of the current font at its current size, or 0 if not available

Description

SWFText::getLeading ( void ) : float
Warning

This function is currently not documented; only its argument list is available.


Calculates the width of the given string in this text objects current font and size

  • « SWFText::getLeading
  • SWFText::getWidth »
  • PHP Manual
  • SWFText
  • Calculates the width of the given string in this text objects current font and size

SWFText::getUTF8Width

(PHP 5 < 5.3.0, PECL ming SVN)

SWFText::getUTF8Width — Calculates the width of the given string in this text objects current font and size

Description

SWFText::getUTF8Width ( string $string ) : float
Warning

This function is currently not documented; only its argument list is available.

See Also

  • SWFText::getWidth() - Computes string's width


Computes string's width

  • « SWFText::getUTF8Width
  • SWFText::moveTo »
  • PHP Manual
  • SWFText
  • Computes string's width

SWFText::getWidth

(PHP 5 < 5.3.0, PECL ming SVN)

SWFText::getWidth — Computes string's width

Description

SWFText::getWidth ( string $string ) : float
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.

Returns the rendered width of the string at the text object's current font, scale, and spacing settings.

See Also

  • SWFText::getUTF8Width() - Calculates the width of the given string in this text objects current font and size


Moves the pen

  • « SWFText::getWidth
  • SWFText::setColor »
  • PHP Manual
  • SWFText
  • Moves the pen

SWFText::moveTo

(PHP 5 < 5.3.0, PECL ming SVN)

SWFText::moveTo — Moves the pen

Description

SWFText::moveTo ( float $x , float $y ) : void
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.

swftext::moveto() moves the pen (or cursor, if that makes more sense) to (x,y) in text object's coordinate space. If either is zero, though, value in that dimension stays the same. Annoying, should be fixed.

Return Values

No value is returned.


Sets the current text color

  • « SWFText::moveTo
  • SWFText::setFont »
  • PHP Manual
  • SWFText
  • Sets the current text color

SWFText::setColor

(PHP 5 < 5.3.0, PECL ming SVN)

SWFText::setColor — Sets the current text color

Description

SWFText::setColor ( int $red , int $green , int $blue [, int $a = 255 ] ) : void
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.

Changes the current text color.

Parameters

These parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF:

red

Value of red component

green

Value of green component

blue

Value of blue component

a

Value of alpha component

Return Values

No value is returned.


Sets the current font

  • « SWFText::setColor
  • SWFText::setHeight »
  • PHP Manual
  • SWFText
  • Sets the current font

SWFText::setFont

(PHP 5 < 5.3.0, PECL ming SVN)

SWFText::setFont — Sets the current font

Description

SWFText::setFont ( SWFFont $font ) : void
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.

swftext::setfont() sets the current font to font.

Return Values

No value is returned.


Sets the current font height

  • « SWFText::setFont
  • SWFText::setSpacing »
  • PHP Manual
  • SWFText
  • Sets the current font height

SWFText::setHeight

(PHP 5 < 5.3.0, PECL ming SVN)

SWFText::setHeight — Sets the current font height

Description

SWFText::setHeight ( float $height ) : void
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.

swftext::setheight() sets the current font height to height. Default is 240.

Return Values

No value is returned.


Sets the current font spacing

  • « SWFText::setHeight
  • SWFTextField »
  • PHP Manual
  • SWFText
  • Sets the current font spacing

SWFText::setSpacing

(PHP 5 < 5.3.0, PECL ming SVN)

SWFText::setSpacing — Sets the current font spacing

Description

SWFText::setSpacing ( float $spacing ) : void
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.

swftext::setspacing() sets the current font spacing to spacing. Default is 1.0. 0 is all of the letters written at the same point. This doesn't really work that well because it inflates the advance across the letter, doesn't add the same amount of spacing between the letters. I should try and explain that better, prolly. Or just fix the damn thing to do constant spacing. This was really just a way to figure out how letter advances work, anyway.. So nyah.

Return Values

No value is returned.


The SWFTextField class

(PHP 5 < 5.3.0, PECL ming SVN)

Introduction

SWFTextField.

Class synopsis

SWFTextField {
/* Methods */
addChars ( string $chars ) : void
addString ( string $string ) : void
align ( int $alignement ) : void
__construct ([ int $flags ] )
setBounds ( float $width , float $height ) : void
setColor ( int $red , int $green , int $blue [, int $a = 255 ] ) : void
setFont ( SWFFont $font ) : void
setHeight ( float $height ) : void
setIndentation ( float $width ) : void
setLeftMargin ( float $width ) : void
setLineSpacing ( float $height ) : void
setMargins ( float $left , float $right ) : void
setName ( string $name ) : void
setPadding ( float $padding ) : void
setRightMargin ( float $width ) : void
}

Table of Contents

  • SWFTextField::addChars — Adds characters to a font that will be available within a textfield
  • SWFTextField::addString — Concatenates the given string to the text field
  • SWFTextField::align — Sets the text field alignment
  • SWFTextField::__construct — Creates a text field object
  • SWFTextField::setBounds — Sets the text field width and height
  • SWFTextField::setColor — Sets the color of the text field
  • SWFTextField::setFont — Sets the text field font
  • SWFTextField::setHeight — Sets the font height of this text field font
  • SWFTextField::setIndentation — Sets the indentation of the first line
  • SWFTextField::setLeftMargin — Sets the left margin width of the text field
  • SWFTextField::setLineSpacing — Sets the line spacing of the text field
  • SWFTextField::setMargins — Sets the margins width of the text field
  • SWFTextField::setName — Sets the variable name
  • SWFTextField::setPadding — Sets the padding of this textfield
  • SWFTextField::setRightMargin — Sets the right margin width of the text field


Adds characters to a font that will be available within a textfield

  • « SWFTextField
  • SWFTextField::addString »
  • PHP Manual
  • SWFTextField
  • Adds characters to a font that will be available within a textfield

SWFTextField::addChars

(PHP 5 < 5.3.0, PECL ming SVN)

SWFTextField::addChars — Adds characters to a font that will be available within a textfield

Description

SWFTextField::addChars ( string $chars ) : void
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.

See Also

  • SWFTextField::addString() - Concatenates the given string to the text field


Concatenates the given string to the text field

  • « SWFTextField::addChars
  • SWFTextField::align »
  • PHP Manual
  • SWFTextField
  • Concatenates the given string to the text field

SWFTextField::addString

(PHP 5 < 5.3.0, PECL ming SVN)

SWFTextField::addString — Concatenates the given string to the text field

Description

SWFTextField::addString ( string $string ) : void
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.

swftextfield::setname() concatenates the string string to the text field.

Return Values

No value is returned.


Sets the text field alignment

  • « SWFTextField::addString
  • SWFTextField::__construct »
  • PHP Manual
  • SWFTextField
  • Sets the text field alignment

SWFTextField::align

(PHP 5 < 5.3.0, PECL ming SVN)

SWFTextField::align — Sets the text field alignment

Description

SWFTextField::align ( int $alignement ) : void
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.

swftextfield::align() sets the text field alignment to alignement. Valid values for alignement are : SWFTEXTFIELD_ALIGN_LEFT, SWFTEXTFIELD_ALIGN_RIGHT, SWFTEXTFIELD_ALIGN_CENTER and SWFTEXTFIELD_ALIGN_JUSTIFY.

Return Values

No value is returned.


Creates a text field object

  • « SWFTextField::align
  • SWFTextField::setBounds »
  • PHP Manual
  • SWFTextField
  • Creates a text field object

SWFTextField::__construct

(PHP 5 < 5.3.0, PECL ming SVN)

SWFTextField::__construct — Creates a text field object

Description

SWFTextField::__construct ([ int $flags ] )
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.

swftextfield() creates a new text field object. Text Fields are less flexible than swftext() objects- they can't be rotated, scaled non-proportionally, or skewed, but they can be used as form entries, and they can use browser-defined fonts.

The optional flags change the text field's behavior. It has the following possibles values :

  • SWFTEXTFIELD_DRAWBOX draws the outline of the textfield
  • SWFTEXTFIELD_HASLENGTH
  • SWFTEXTFIELD_HTML allows text markup using HTML-tags
  • SWFTEXTFIELD_MULTILINE allows multiple lines
  • SWFTEXTFIELD_NOEDIT indicates that the field shouldn't be user-editable
  • SWFTEXTFIELD_NOSELECT makes the field non-selectable
  • SWFTEXTFIELD_PASSWORD obscures the data entry
  • SWFTEXTFIELD_WORDWRAP allows text to wrap
Flags are combined with the bitwise OR operation. For example,
<?php
$t = newSWFTextField(SWFTEXTFIELD_PASSWORD | SWFTEXTFIELD_NOEDIT);
?>
creates a totally useless non-editable password field.

SWFTextField has the following methods : swftextfield::setfont(),
swftextfield::setbounds(), swftextfield::align(),
swftextfield::setheight(), swftextfield::setleftmargin(),
swftextfield::setrightmargin(), swftextfield::setmargins(),
swftextfield::setindentation(), swftextfield::setlinespacing(),
swftextfield::setcolor(), swftextfield::setname() and
swftextfield::addstring().


Sets the text field width and height

  • « SWFTextField::__construct
  • SWFTextField::setColor »
  • PHP Manual
  • SWFTextField
  • Sets the text field width and height

SWFTextField::setBounds

(PHP 5 < 5.3.0, PECL ming SVN)

SWFTextField::setBounds — Sets the text field width and height

Description

SWFTextField::setBounds ( float $width , float $height ) : void
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.

swftextfield::setbounds() sets the text field width to width and height to height. If you don't set the bounds yourself, Ming makes a poor guess at what the bounds are.

Return Values

No value is returned.


Sets the color of the text field

  • « SWFTextField::setBounds
  • SWFTextField::setFont »
  • PHP Manual
  • SWFTextField
  • Sets the color of the text field

SWFTextField::setColor

(PHP 5 < 5.3.0, PECL ming SVN)

SWFTextField::setColor — Sets the color of the text field

Description

SWFTextField::setColor ( int $red , int $green , int $blue [, int $a = 255 ] ) : void
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.

swftextfield::setcolor() sets the color of the text field. Default is fully opaque black. Color is represented using RGB system.

Parameters

These parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF:

red

Value of red component

green

Value of green component

blue

Value of blue component

a

Value of alpha component

Return Values

No value is returned.


Sets the text field font

  • « SWFTextField::setColor
  • SWFTextField::setHeight »
  • PHP Manual
  • SWFTextField
  • Sets the text field font

SWFTextField::setFont

(PHP 5 < 5.3.0, PECL ming SVN)

SWFTextField::setFont — Sets the text field font

Description

SWFTextField::setFont ( SWFFont $font ) : void
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.

swftextfield::setfont() sets the text field font to the [browser-defined?] font font.

Return Values

No value is returned.


Sets the font height of this text field font

  • « SWFTextField::setFont
  • SWFTextField::setIndentation »
  • PHP Manual
  • SWFTextField
  • Sets the font height of this text field font

SWFTextField::setHeight

(PHP 5 < 5.3.0, PECL ming SVN)

SWFTextField::setHeight — Sets the font height of this text field font

Description

SWFTextField::setHeight ( float $height ) : void
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.

swftextfield::setheight() sets the font height of this text field font to the given height height. Default is 240.

Return Values

No value is returned.


Sets the indentation of the first line

  • « SWFTextField::setHeight
  • SWFTextField::setLeftMargin »
  • PHP Manual
  • SWFTextField
  • Sets the indentation of the first line

SWFTextField::setIndentation

(PHP 5 < 5.3.0, PECL ming SVN)

SWFTextField::setIndentation — Sets the indentation of the first line

Description

SWFTextField::setIndentation ( float $width ) : void
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.

swftextfield::setindentation() sets the indentation of the first line in the text field, to width.

Return Values

No value is returned.


Sets the left margin width of the text field

  • « SWFTextField::setIndentation
  • SWFTextField::setLineSpacing »
  • PHP Manual
  • SWFTextField
  • Sets the left margin width of the text field

SWFTextField::setLeftMargin

(PHP 5 < 5.3.0, PECL ming SVN)

SWFTextField::setLeftMargin — Sets the left margin width of the text field

Description

SWFTextField::setLeftMargin ( float $width ) : void
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.

swftextfield::setleftmargin() sets the left margin width of the text field to width. Default is 0.

Return Values

No value is returned.


Sets the line spacing of the text field

  • « SWFTextField::setLeftMargin
  • SWFTextField::setMargins »
  • PHP Manual
  • SWFTextField
  • Sets the line spacing of the text field

SWFTextField::setLineSpacing

(PHP 5 < 5.3.0, PECL ming SVN)

SWFTextField::setLineSpacing — Sets the line spacing of the text field

Description

SWFTextField::setLineSpacing ( float $height ) : void
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.

swftextfield::setlinespacing() sets the line spacing of the text field to the height of height. Default is 40.

Return Values

No value is returned.


Sets the margins width of the text field

  • « SWFTextField::setLineSpacing
  • SWFTextField::setName »
  • PHP Manual
  • SWFTextField
  • Sets the margins width of the text field

SWFTextField::setMargins

(PHP 5 < 5.3.0, PECL ming SVN)

SWFTextField::setMargins — Sets the margins width of the text field

Description

SWFTextField::setMargins ( float $left , float $right ) : void
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.

swftextfield::setmargins() set both margins at once, for the man on the go.

Return Values

No value is returned.


Sets the variable name

  • « SWFTextField::setMargins
  • SWFTextField::setPadding »
  • PHP Manual
  • SWFTextField
  • Sets the variable name

SWFTextField::setName

(PHP 5 < 5.3.0, PECL ming SVN)

SWFTextField::setName — Sets the variable name

Description

SWFTextField::setName ( string $name ) : void
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.

swftextfield::setname() sets the variable name of this text field to name, for form posting and action scripting purposes.

Return Values

No value is returned.


Sets the padding of this textfield

  • « SWFTextField::setName
  • SWFTextField::setRightMargin »
  • PHP Manual
  • SWFTextField
  • Sets the padding of this textfield

SWFTextField::setPadding

(PHP 5 < 5.3.0, PECL ming SVN)

SWFTextField::setPadding — Sets the padding of this textfield

Description

SWFTextField::setPadding ( float $padding ) : void
Warning

This function is currently not documented; only its argument list is available.

Return Values

No value is returned.


Sets the right margin width of the text field

  • « SWFTextField::setPadding
  • SWFVideoStream »
  • PHP Manual
  • SWFTextField
  • Sets the right margin width of the text field

SWFTextField::setRightMargin

(PHP 5 < 5.3.0, PECL ming SVN)

SWFTextField::setRightMargin — Sets the right margin width of the text field

Description

SWFTextField::setRightMargin ( float $width ) : void
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.

swftextfield::setrightmargin() sets the right margin width of the text field to width. Default is 0.

Return Values

No value is returned.


The SWFVideoStream class

(PHP 5.0.5-5.3.0, PHP 7, PECL ming SVN)

Introduction

SWFVideoStream.

Class synopsis

SWFVideoStream {
/* Methods */
__construct ([ string $file ] )
getNumFrames ( void ) : int
setDimension ( int $x , int $y ) : void
}

Table of Contents

  • SWFVideoStream::__construct — Returns a SWFVideoStream object
  • SWFVideoStream::getNumFrames — Returns the number of frames in the video
  • SWFVideoStream::setDimension — Sets video dimension


Returns a SWFVideoStream object

  • « SWFVideoStream
  • SWFVideoStream::getNumFrames »
  • PHP Manual
  • SWFVideoStream
  • Returns a SWFVideoStream object

SWFVideoStream::__construct

(PHP 5.0.5-5.3.0, PHP 7, PECL ming SVN)

SWFVideoStream::__construct — Returns a SWFVideoStream object

Description

SWFVideoStream::__construct ([ string $file ] )
Warning

This function is currently not documented; only its argument list is available.


Returns the number of frames in the video

  • « SWFVideoStream::__construct
  • SWFVideoStream::setDimension »
  • PHP Manual
  • SWFVideoStream
  • Returns the number of frames in the video

SWFVideoStream::getNumFrames

(PHP 5.0.5-5.3.0, PHP 7, PECL ming SVN)

SWFVideoStream::getNumFrames — Returns the number of frames in the video

Description

SWFVideoStream::getNumFrames ( void ) : int

This function returns the number of video-frames of a SWFVideoStream.

Return Values

Returns the number of frames, as an integer


Sets video dimension

  • « SWFVideoStream::getNumFrames
  • PDF »
  • PHP Manual
  • SWFVideoStream
  • Sets video dimension

SWFVideoStream::setDimension

(PHP 5.0.5-5.3.0, PHP 7, PECL ming SVN)

SWFVideoStream::setDimension — Sets video dimension

Description

SWFVideoStream::setDimension ( int $x , int $y ) : void

Sets the width and height for streamed videos.

Parameters

x

Width in pixels.

y

Height in pixels.

Return Values

No value is returned.


PDF

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic Usage Examples
  • PDF Functions
    • PDF_activate_item — Activate structure element or other content item
    • PDF_add_annotation — Add annotation [deprecated]
    • PDF_add_bookmark — Add bookmark for current page [deprecated]
    • PDF_add_launchlink — Add launch annotation for current page [deprecated]
    • PDF_add_locallink — Add link annotation for current page [deprecated]
    • PDF_add_nameddest — Create named destination
    • PDF_add_note — Set annotation for current page [deprecated]
    • PDF_add_outline — Add bookmark for current page [deprecated]
    • PDF_add_pdflink — Add file link annotation for current page [deprecated]
    • PDF_add_table_cell — Add a cell to a new or existing table
    • PDF_add_textflow — Create Textflow or add text to existing Textflow
    • PDF_add_thumbnail — Add thumbnail for current page
    • PDF_add_weblink — Add weblink for current page [deprecated]
    • PDF_arc — Draw a counterclockwise circular arc segment
    • PDF_arcn — Draw a clockwise circular arc segment
    • PDF_attach_file — Add file attachment for current page [deprecated]
    • PDF_begin_document — Create new PDF file
    • PDF_begin_font — Start a Type 3 font definition
    • PDF_begin_glyph — Start glyph definition for Type 3 font
    • PDF_begin_item — Open structure element or other content item
    • PDF_begin_layer — Start layer
    • PDF_begin_page_ext — Start new page
    • PDF_begin_page — Start new page [deprecated]
    • PDF_begin_pattern — Start pattern definition
    • PDF_begin_template_ext — Start template definition
    • PDF_begin_template — Start template definition [deprecated]
    • PDF_circle — Draw a circle
    • PDF_clip — Clip to current path
    • PDF_close_image — Close image
    • PDF_close_pdi_page — Close the page handle
    • PDF_close_pdi — Close the input PDF document [deprecated]
    • PDF_close — Close pdf resource [deprecated]
    • PDF_closepath_fill_stroke — Close, fill and stroke current path
    • PDF_closepath_stroke — Close and stroke path
    • PDF_closepath — Close current path
    • PDF_concat — Concatenate a matrix to the CTM
    • PDF_continue_text — Output text in next line
    • PDF_create_3dview — Create 3D view
    • PDF_create_action — Create action for objects or events
    • PDF_create_annotation — Create rectangular annotation
    • PDF_create_bookmark — Create bookmark
    • PDF_create_field — Create form field
    • PDF_create_fieldgroup — Create form field group
    • PDF_create_gstate — Create graphics state object
    • PDF_create_pvf — Create PDFlib virtual file
    • PDF_create_textflow — Create textflow object
    • PDF_curveto — Draw Bezier curve
    • PDF_define_layer — Create layer definition
    • PDF_delete_pvf — Delete PDFlib virtual file
    • PDF_delete_table — Delete table object
    • PDF_delete_textflow — Delete textflow object
    • PDF_delete — Delete PDFlib object
    • PDF_encoding_set_char — Add glyph name and/or Unicode value
    • PDF_end_document — Close PDF file
    • PDF_end_font — Terminate Type 3 font definition
    • PDF_end_glyph — Terminate glyph definition for Type 3 font
    • PDF_end_item — Close structure element or other content item
    • PDF_end_layer — Deactivate all active layers
    • PDF_end_page_ext — Finish page
    • PDF_end_page — Finish page
    • PDF_end_pattern — Finish pattern
    • PDF_end_template — Finish template
    • PDF_endpath — End current path
    • PDF_fill_imageblock — Fill image block with variable data
    • PDF_fill_pdfblock — Fill PDF block with variable data
    • PDF_fill_stroke — Fill and stroke path
    • PDF_fill_textblock — Fill text block with variable data
    • PDF_fill — Fill current path
    • PDF_findfont — Prepare font for later use [deprecated]
    • PDF_fit_image — Place image or template
    • PDF_fit_pdi_page — Place imported PDF page
    • PDF_fit_table — Place table on page
    • PDF_fit_textflow — Format textflow in rectangular area
    • PDF_fit_textline — Place single line of text
    • PDF_get_apiname — Get name of unsuccessfull API function
    • PDF_get_buffer — Get PDF output buffer
    • PDF_get_errmsg — Get error text
    • PDF_get_errnum — Get error number
    • PDF_get_font — Get font [deprecated]
    • PDF_get_fontname — Get font name [deprecated]
    • PDF_get_fontsize — Font handling [deprecated]
    • PDF_get_image_height — Get image height [deprecated]
    • PDF_get_image_width — Get image width [deprecated]
    • PDF_get_majorversion — Get major version number [deprecated]
    • PDF_get_minorversion — Get minor version number [deprecated]
    • PDF_get_parameter — Get string parameter
    • PDF_get_pdi_parameter — Get PDI string parameter [deprecated]
    • PDF_get_pdi_value — Get PDI numerical parameter [deprecated]
    • PDF_get_value — Get numerical parameter
    • PDF_info_font — Query detailed information about a loaded font
    • PDF_info_matchbox — Query matchbox information
    • PDF_info_table — Retrieve table information
    • PDF_info_textflow — Query textflow state
    • PDF_info_textline — Perform textline formatting and query metrics
    • PDF_initgraphics — Reset graphic state
    • PDF_lineto — Draw a line
    • PDF_load_3ddata — Load 3D model
    • PDF_load_font — Search and prepare font
    • PDF_load_iccprofile — Search and prepare ICC profile
    • PDF_load_image — Open image file
    • PDF_makespotcolor — Make spot color
    • PDF_moveto — Set current point
    • PDF_new — Create PDFlib object
    • PDF_open_ccitt — Open raw CCITT image [deprecated]
    • PDF_open_file — Create PDF file [deprecated]
    • PDF_open_gif — Open GIF image [deprecated]
    • PDF_open_image_file — Read image from file [deprecated]
    • PDF_open_image — Use image data [deprecated]
    • PDF_open_jpeg — Open JPEG image [deprecated]
    • PDF_open_memory_image — Open image created with PHP's image functions [not supported]
    • PDF_open_pdi_document — Prepare a pdi document
    • PDF_open_pdi_page — Prepare a page
    • PDF_open_pdi — Open PDF file [deprecated]
    • PDF_open_tiff — Open TIFF image [deprecated]
    • PDF_pcos_get_number — Get value of pCOS path with type number or boolean
    • PDF_pcos_get_stream — Get contents of pCOS path with type stream, fstream, or string
    • PDF_pcos_get_string — Get value of pCOS path with type name, string, or boolean
    • PDF_place_image — Place image on the page [deprecated]
    • PDF_place_pdi_page — Place PDF page [deprecated]
    • PDF_process_pdi — Process imported PDF document
    • PDF_rect — Draw rectangle
    • PDF_restore — Restore graphics state
    • PDF_resume_page — Resume page
    • PDF_rotate — Rotate coordinate system
    • PDF_save — Save graphics state
    • PDF_scale — Scale coordinate system
    • PDF_set_border_color — Set border color of annotations [deprecated]
    • PDF_set_border_dash — Set border dash style of annotations [deprecated]
    • PDF_set_border_style — Set border style of annotations [deprecated]
    • PDF_set_char_spacing — Set character spacing [deprecated]
    • PDF_set_duration — Set duration between pages [deprecated]
    • PDF_set_gstate — Activate graphics state object
    • PDF_set_horiz_scaling — Set horizontal text scaling [deprecated]
    • PDF_set_info_author — Fill the author document info field [deprecated]
    • PDF_set_info_creator — Fill the creator document info field [deprecated]
    • PDF_set_info_keywords — Fill the keywords document info field [deprecated]
    • PDF_set_info_subject — Fill the subject document info field [deprecated]
    • PDF_set_info_title — Fill the title document info field [deprecated]
    • PDF_set_info — Fill document info field
    • PDF_set_layer_dependency — Define relationships among layers
    • PDF_set_leading — Set distance between text lines [deprecated]
    • PDF_set_parameter — Set string parameter
    • PDF_set_text_matrix — Set text matrix [deprecated]
    • PDF_set_text_pos — Set text position
    • PDF_set_text_rendering — Determine text rendering [deprecated]
    • PDF_set_text_rise — Set text rise [deprecated]
    • PDF_set_value — Set numerical parameter
    • PDF_set_word_spacing — Set spacing between words [deprecated]
    • PDF_setcolor — Set fill and stroke color
    • PDF_setdash — Set simple dash pattern
    • PDF_setdashpattern — Set dash pattern
    • PDF_setflat — Set flatness
    • PDF_setfont — Set font
    • PDF_setgray_fill — Set fill color to gray [deprecated]
    • PDF_setgray_stroke — Set stroke color to gray [deprecated]
    • PDF_setgray — Set color to gray [deprecated]
    • PDF_setlinecap — Set linecap parameter
    • PDF_setlinejoin — Set linejoin parameter
    • PDF_setlinewidth — Set line width
    • PDF_setmatrix — Set current transformation matrix
    • PDF_setmiterlimit — Set miter limit
    • PDF_setpolydash — Set complicated dash pattern [deprecated]
    • PDF_setrgbcolor_fill — Set fill rgb color values [deprecated]
    • PDF_setrgbcolor_stroke — Set stroke rgb color values [deprecated]
    • PDF_setrgbcolor — Set fill and stroke rgb color values [deprecated]
    • PDF_shading_pattern — Define shading pattern
    • PDF_shading — Define blend
    • PDF_shfill — Fill area with shading
    • PDF_show_boxed — Output text in a box [deprecated]
    • PDF_show_xy — Output text at given position
    • PDF_show — Output text at current position
    • PDF_skew — Skew the coordinate system
    • PDF_stringwidth — Return width of text
    • PDF_stroke — Stroke path
    • PDF_suspend_page — Suspend page
    • PDF_translate — Set origin of coordinate system
    • PDF_utf16_to_utf8 — Convert string from UTF-16 to UTF-8
    • PDF_utf32_to_utf16 — Convert string from UTF-32 to UTF-16
    • PDF_utf8_to_utf16 — Convert string from UTF-8 to UTF-16


Introduction

The PDF functions in PHP can create PDF files using the PDFlib library from PDFlib GmbH (» www.pdflib.com). A restricted version called PDFlib Lite 7 is available for free, but it is no longer maintained since 2010. PDFlib integration for PHP is still actively maintained by PDFlib GmbH. It is mainly targeted at the commercial PDFlib versions, but can also be used for the old PDFlib Lite.

If you want to use PDFlib we urge you start with the examples which are included in all PDFlib packages, and refer to the extensive manuals in PDF format which are also included. At a minimum you should take a look at the hello.php sample to learn basic setup for PDFlib usage.

Note:

If you're interested in alternative free PDF generators that do not utilize external PDF libraries, see this related FAQ.


Requirements

PDFlib Lite is available as open source. However, the PDFlib Lite license allows free use only under certain conditions. PDFlib Lite supports a subset of PDFlib's functionality; please see the PDFlib web site for details. The full version of PDFlib is available for download at » http://www.pdflib.com/products/pdflib-family/, but requires that you purchase a license for commercial use.

Issues with older versions of PDFlib

Any version of PHP 4 after March 9, 2000 does not support versions of PDFlib older than 3.0.

PDFlib 4.0 or greater is supported by PHP 4.3.0 and later.


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/pdflib.

To get these functions to work in PHP < 4.3.9, you have to compile PHP with --with-pdflib[=DIR] . DIR is the PDFlib base install directory, defaults to /usr/local.


  • « Runtime Configuration
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

PDF_new() creates a new PDFlib object required by most PDF functions.


  • « Resource Types
  • Examples »
  • PHP Manual
  • PDF
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


  • « Predefined Constants
  • Basic Usage Examples »
  • PHP Manual
  • PDF
  • Examples

Examples

Table of Contents

  • Basic Usage Examples


Basic Usage Examples

Most of the functions are fairly easy to use. The most difficult part is probably creating your first PDF document. The following example should help to get you started. It is developed for PHP 4 and creates the file hello.pdf with one page. It defines some document info field contents, loads the Helvetica-Bold font and outputs the text "Hello world! (says PHP)".

Example #1 Hello World example from PDFlib distribution for PHP 4

<?php
$p = PDF_new();

/*  open new PDF file; insert a file name to create the PDF on disk */
if (PDF_begin_document($p, "", "") == 0) {
    die("Error: " . PDF_get_errmsg($p));
}

PDF_set_info($p, "Creator", "hello.php");
PDF_set_info($p, "Author", "Rainer Schaaf");
PDF_set_info($p, "Title", "Hello world (PHP)!");

PDF_begin_page_ext($p, 595, 842, "");

$font = PDF_load_font($p, "Helvetica-Bold", "winansi", "");

PDF_setfont($p, $font, 24.0);
PDF_set_text_pos($p, 50, 700);
PDF_show($p, "Hello world!");
PDF_continue_text($p, "(says PHP)");
PDF_end_page_ext($p, "");

PDF_end_document($p, "");

$buf = PDF_get_buffer($p);
$len = strlen($buf);

header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=hello.pdf");
print $buf;

PDF_delete($p);
?>

The following example comes with the PDFlib distribution for PHP 5. It uses the new exception handling and object encapsulation features available in PHP 5. It creates the file hello.pdf with one page. It defines some document info field contents, loads the Helvetica-Bold font and outputs the text "Hello world! (says PHP)".

Example #2 Hello World example from PDFlib distribution for PHP 5

<?php

try {
    $p = new PDFlib();

    /*  open new PDF file; insert a file name to create the PDF on disk */
    if ($p->begin_document("", "") == 0) {
        die("Error: " . $p->get_errmsg());
    }

    $p->set_info("Creator", "hello.php");
    $p->set_info("Author", "Rainer Schaaf");
    $p->set_info("Title", "Hello world (PHP)!");

    $p->begin_page_ext(595, 842, "");

    $font = $p->load_font("Helvetica-Bold", "winansi", "");

    $p->setfont($font, 24.0);
    $p->set_text_pos(50, 700);
    $p->show("Hello world!");
    $p->continue_text("(says PHP)");
    $p->end_page_ext("");

    $p->end_document("");

    $buf = $p->get_buffer();
    $len = strlen($buf);

    header("Content-type: application/pdf");
    header("Content-Length: $len");
    header("Content-Disposition: inline; filename=hello.pdf");
    print $buf;
}
catch (PDFlibException $e) {
    die("PDFlib exception occurred in hello sample:\n" .
    "[" . $e->get_errnum() . "] " . $e->get_apiname() . ": " .
    $e->get_errmsg() . "\n");
}
catch (Exception $e) {
    die($e);
}
$p = 0;
?>


PDF Functions

Remarks about Deprecated PDFlib Functions

Starting with PHP 4.0.5, the PHP extension for PDFlib is officially supported by PDFlib GmbH. This means that all the functions described in the PDFlib Reference Manual are supported by PHP 4 with exactly the same meaning and the same parameters. However, with PDFlib Version 5.0.4 or higher all parameters have to be specified. For compatibility reasons, this binding for PDFlib still supports most of the deprecated functions, but they should be replaced by their new versions. PDFlib GmbH will not support any problems arising from the use of these deprecated functions. The documentation in this section indicates old functions as "Deprecated" and gives the replacement function to be used instead.

Table of Contents

  • PDF_activate_item — Activate structure element or other content item
  • PDF_add_annotation — Add annotation [deprecated]
  • PDF_add_bookmark — Add bookmark for current page [deprecated]
  • PDF_add_launchlink — Add launch annotation for current page [deprecated]
  • PDF_add_locallink — Add link annotation for current page [deprecated]
  • PDF_add_nameddest — Create named destination
  • PDF_add_note — Set annotation for current page [deprecated]
  • PDF_add_outline — Add bookmark for current page [deprecated]
  • PDF_add_pdflink — Add file link annotation for current page [deprecated]
  • PDF_add_table_cell — Add a cell to a new or existing table
  • PDF_add_textflow — Create Textflow or add text to existing Textflow
  • PDF_add_thumbnail — Add thumbnail for current page
  • PDF_add_weblink — Add weblink for current page [deprecated]
  • PDF_arc — Draw a counterclockwise circular arc segment
  • PDF_arcn — Draw a clockwise circular arc segment
  • PDF_attach_file — Add file attachment for current page [deprecated]
  • PDF_begin_document — Create new PDF file
  • PDF_begin_font — Start a Type 3 font definition
  • PDF_begin_glyph — Start glyph definition for Type 3 font
  • PDF_begin_item — Open structure element or other content item
  • PDF_begin_layer — Start layer
  • PDF_begin_page_ext — Start new page
  • PDF_begin_page — Start new page [deprecated]
  • PDF_begin_pattern — Start pattern definition
  • PDF_begin_template_ext — Start template definition
  • PDF_begin_template — Start template definition [deprecated]
  • PDF_circle — Draw a circle
  • PDF_clip — Clip to current path
  • PDF_close_image — Close image
  • PDF_close_pdi_page — Close the page handle
  • PDF_close_pdi — Close the input PDF document [deprecated]
  • PDF_close — Close pdf resource [deprecated]
  • PDF_closepath_fill_stroke — Close, fill and stroke current path
  • PDF_closepath_stroke — Close and stroke path
  • PDF_closepath — Close current path
  • PDF_concat — Concatenate a matrix to the CTM
  • PDF_continue_text — Output text in next line
  • PDF_create_3dview — Create 3D view
  • PDF_create_action — Create action for objects or events
  • PDF_create_annotation — Create rectangular annotation
  • PDF_create_bookmark — Create bookmark
  • PDF_create_field — Create form field
  • PDF_create_fieldgroup — Create form field group
  • PDF_create_gstate — Create graphics state object
  • PDF_create_pvf — Create PDFlib virtual file
  • PDF_create_textflow — Create textflow object
  • PDF_curveto — Draw Bezier curve
  • PDF_define_layer — Create layer definition
  • PDF_delete_pvf — Delete PDFlib virtual file
  • PDF_delete_table — Delete table object
  • PDF_delete_textflow — Delete textflow object
  • PDF_delete — Delete PDFlib object
  • PDF_encoding_set_char — Add glyph name and/or Unicode value
  • PDF_end_document — Close PDF file
  • PDF_end_font — Terminate Type 3 font definition
  • PDF_end_glyph — Terminate glyph definition for Type 3 font
  • PDF_end_item — Close structure element or other content item
  • PDF_end_layer — Deactivate all active layers
  • PDF_end_page_ext — Finish page
  • PDF_end_page — Finish page
  • PDF_end_pattern — Finish pattern
  • PDF_end_template — Finish template
  • PDF_endpath — End current path
  • PDF_fill_imageblock — Fill image block with variable data
  • PDF_fill_pdfblock — Fill PDF block with variable data
  • PDF_fill_stroke — Fill and stroke path
  • PDF_fill_textblock — Fill text block with variable data
  • PDF_fill — Fill current path
  • PDF_findfont — Prepare font for later use [deprecated]
  • PDF_fit_image — Place image or template
  • PDF_fit_pdi_page — Place imported PDF page
  • PDF_fit_table — Place table on page
  • PDF_fit_textflow — Format textflow in rectangular area
  • PDF_fit_textline — Place single line of text
  • PDF_get_apiname — Get name of unsuccessfull API function
  • PDF_get_buffer — Get PDF output buffer
  • PDF_get_errmsg — Get error text
  • PDF_get_errnum — Get error number
  • PDF_get_font — Get font [deprecated]
  • PDF_get_fontname — Get font name [deprecated]
  • PDF_get_fontsize — Font handling [deprecated]
  • PDF_get_image_height — Get image height [deprecated]
  • PDF_get_image_width — Get image width [deprecated]
  • PDF_get_majorversion — Get major version number [deprecated]
  • PDF_get_minorversion — Get minor version number [deprecated]
  • PDF_get_parameter — Get string parameter
  • PDF_get_pdi_parameter — Get PDI string parameter [deprecated]
  • PDF_get_pdi_value — Get PDI numerical parameter [deprecated]
  • PDF_get_value — Get numerical parameter
  • PDF_info_font — Query detailed information about a loaded font
  • PDF_info_matchbox — Query matchbox information
  • PDF_info_table — Retrieve table information
  • PDF_info_textflow — Query textflow state
  • PDF_info_textline — Perform textline formatting and query metrics
  • PDF_initgraphics — Reset graphic state
  • PDF_lineto — Draw a line
  • PDF_load_3ddata — Load 3D model
  • PDF_load_font — Search and prepare font
  • PDF_load_iccprofile — Search and prepare ICC profile
  • PDF_load_image — Open image file
  • PDF_makespotcolor — Make spot color
  • PDF_moveto — Set current point
  • PDF_new — Create PDFlib object
  • PDF_open_ccitt — Open raw CCITT image [deprecated]
  • PDF_open_file — Create PDF file [deprecated]
  • PDF_open_gif — Open GIF image [deprecated]
  • PDF_open_image_file — Read image from file [deprecated]
  • PDF_open_image — Use image data [deprecated]
  • PDF_open_jpeg — Open JPEG image [deprecated]
  • PDF_open_memory_image — Open image created with PHP's image functions [not supported]
  • PDF_open_pdi_document — Prepare a pdi document
  • PDF_open_pdi_page — Prepare a page
  • PDF_open_pdi — Open PDF file [deprecated]
  • PDF_open_tiff — Open TIFF image [deprecated]
  • PDF_pcos_get_number — Get value of pCOS path with type number or boolean
  • PDF_pcos_get_stream — Get contents of pCOS path with type stream, fstream, or string
  • PDF_pcos_get_string — Get value of pCOS path with type name, string, or boolean
  • PDF_place_image — Place image on the page [deprecated]
  • PDF_place_pdi_page — Place PDF page [deprecated]
  • PDF_process_pdi — Process imported PDF document
  • PDF_rect — Draw rectangle
  • PDF_restore — Restore graphics state
  • PDF_resume_page — Resume page
  • PDF_rotate — Rotate coordinate system
  • PDF_save — Save graphics state
  • PDF_scale — Scale coordinate system
  • PDF_set_border_color — Set border color of annotations [deprecated]
  • PDF_set_border_dash — Set border dash style of annotations [deprecated]
  • PDF_set_border_style — Set border style of annotations [deprecated]
  • PDF_set_char_spacing — Set character spacing [deprecated]
  • PDF_set_duration — Set duration between pages [deprecated]
  • PDF_set_gstate — Activate graphics state object
  • PDF_set_horiz_scaling — Set horizontal text scaling [deprecated]
  • PDF_set_info_author — Fill the author document info field [deprecated]
  • PDF_set_info_creator — Fill the creator document info field [deprecated]
  • PDF_set_info_keywords — Fill the keywords document info field [deprecated]
  • PDF_set_info_subject — Fill the subject document info field [deprecated]
  • PDF_set_info_title — Fill the title document info field [deprecated]
  • PDF_set_info — Fill document info field
  • PDF_set_layer_dependency — Define relationships among layers
  • PDF_set_leading — Set distance between text lines [deprecated]
  • PDF_set_parameter — Set string parameter
  • PDF_set_text_matrix — Set text matrix [deprecated]
  • PDF_set_text_pos — Set text position
  • PDF_set_text_rendering — Determine text rendering [deprecated]
  • PDF_set_text_rise — Set text rise [deprecated]
  • PDF_set_value — Set numerical parameter
  • PDF_set_word_spacing — Set spacing between words [deprecated]
  • PDF_setcolor — Set fill and stroke color
  • PDF_setdash — Set simple dash pattern
  • PDF_setdashpattern — Set dash pattern
  • PDF_setflat — Set flatness
  • PDF_setfont — Set font
  • PDF_setgray_fill — Set fill color to gray [deprecated]
  • PDF_setgray_stroke — Set stroke color to gray [deprecated]
  • PDF_setgray — Set color to gray [deprecated]
  • PDF_setlinecap — Set linecap parameter
  • PDF_setlinejoin — Set linejoin parameter
  • PDF_setlinewidth — Set line width
  • PDF_setmatrix — Set current transformation matrix
  • PDF_setmiterlimit — Set miter limit
  • PDF_setpolydash — Set complicated dash pattern [deprecated]
  • PDF_setrgbcolor_fill — Set fill rgb color values [deprecated]
  • PDF_setrgbcolor_stroke — Set stroke rgb color values [deprecated]
  • PDF_setrgbcolor — Set fill and stroke rgb color values [deprecated]
  • PDF_shading_pattern — Define shading pattern
  • PDF_shading — Define blend
  • PDF_shfill — Fill area with shading
  • PDF_show_boxed — Output text in a box [deprecated]
  • PDF_show_xy — Output text at given position
  • PDF_show — Output text at current position
  • PDF_skew — Skew the coordinate system
  • PDF_stringwidth — Return width of text
  • PDF_stroke — Stroke path
  • PDF_suspend_page — Suspend page
  • PDF_translate — Set origin of coordinate system
  • PDF_utf16_to_utf8 — Convert string from UTF-16 to UTF-8
  • PDF_utf32_to_utf16 — Convert string from UTF-32 to UTF-16
  • PDF_utf8_to_utf16 — Convert string from UTF-8 to UTF-16


Activate structure element or other content item

  • « PDF Functions
  • PDF_add_annotation »
  • PHP Manual
  • PDF Functions
  • Activate structure element or other content item

PDF_activate_item

(PECL pdflib >= 2.0.0)

PDF_activate_item — Activate structure element or other content item

Description

PDF_activate_item ( resource $pdfdoc , int $id ) : bool

Activates a previously created structure element or other content item. Returns TRUE on success or FALSE on failure.


Add annotation [deprecated]

  • « PDF_activate_item
  • PDF_add_bookmark »
  • PHP Manual
  • PDF Functions
  • Add annotation [deprecated]

PDF_add_annotation

(PHP 4, PECL pdflib >= 1.0.0)

PDF_add_annotation — Add annotation [deprecated]

Description

This function is deprecated, use PDF_create_annotation() with type=Text instead.


Add bookmark for current page [deprecated]

  • « PDF_add_annotation
  • PDF_add_launchlink »
  • PHP Manual
  • PDF Functions
  • Add bookmark for current page [deprecated]

PDF_add_bookmark

(PHP 4 >= 4.0.1, PECL pdflib >= 1.0.0)

PDF_add_bookmark — Add bookmark for current page [deprecated]

Description

This function is deprecated since PDFlib version 6, use PDF_create_bookmark() instead.


Add launch annotation for current page [deprecated]

  • « PDF_add_bookmark
  • PDF_add_locallink »
  • PHP Manual
  • PDF Functions
  • Add launch annotation for current page [deprecated]

PDF_add_launchlink

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_add_launchlink — Add launch annotation for current page [deprecated]

Description

PDF_add_launchlink ( resource $pdfdoc , float $llx , float $lly , float $urx , float $ury , string $filename ) : bool

Adds a link to a web resource.

This function is deprecated since PDFlib version 6,
use PDF_create_action() with
type=Launch and
PDF_create_annotation() with
type=Link instead.


Add link annotation for current page [deprecated]

  • « PDF_add_launchlink
  • PDF_add_nameddest »
  • PHP Manual
  • PDF Functions
  • Add link annotation for current page [deprecated]

PDF_add_locallink

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_add_locallink — Add link annotation for current page [deprecated]

Description

PDF_add_locallink ( resource $pdfdoc , float $lowerleftx , float $lowerlefty , float $upperrightx , float $upperrighty , int $page , string $dest ) : bool

Add a link annotation to a target within the current PDF file. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 6, use
PDF_create_action() with type=GoTo
and PDF_create_annotation() with
type=Link instead.


Create named destination

  • « PDF_add_locallink
  • PDF_add_note »
  • PHP Manual
  • PDF Functions
  • Create named destination

PDF_add_nameddest

(PECL pdflib >= 2.0.0)

PDF_add_nameddest — Create named destination

Description

PDF_add_nameddest ( resource $pdfdoc , string $name , string $optlist ) : bool

Creates a named destination on an arbitrary page in the current document. Returns TRUE on success or FALSE on failure.


Set annotation for current page [deprecated]

  • « PDF_add_nameddest
  • PDF_add_outline »
  • PHP Manual
  • PDF Functions
  • Set annotation for current page [deprecated]

PDF_add_note

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_add_note — Set annotation for current page [deprecated]

Description

PDF_add_note ( resource $pdfdoc , float $llx , float $lly , float $urx , float $ury , string $contents , string $title , string $icon , int $open ) : bool

Sets an annotation for the current page. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 6, use PDF_create_annotation() with type=Text instead.


Add bookmark for current page [deprecated]

  • « PDF_add_note
  • PDF_add_pdflink »
  • PHP Manual
  • PDF Functions
  • Add bookmark for current page [deprecated]

PDF_add_outline

(PHP 4, PECL pdflib >= 1.0.0)

PDF_add_outline — Add bookmark for current page [deprecated]

Description

This function is deprecated, use PDF_create_bookmark() instead.


Add file link annotation for current page [deprecated]

  • « PDF_add_outline
  • PDF_add_table_cell »
  • PHP Manual
  • PDF Functions
  • Add file link annotation for current page [deprecated]

PDF_add_pdflink

(PHP 4, PECL pdflib >= 1.0.0)

PDF_add_pdflink — Add file link annotation for current page [deprecated]

Description

PDF_add_pdflink ( resource $pdfdoc , float $bottom_left_x , float $bottom_left_y , float $up_right_x , float $up_right_y , string $filename , int $page , string $dest ) : bool

Add a file link annotation to a PDF target. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 6, use
PDF_create_action() with
type=GoToR and
PDF_create_annotation() with
type=Link instead.


Add a cell to a new or existing table

  • « PDF_add_pdflink
  • PDF_add_textflow »
  • PHP Manual
  • PDF Functions
  • Add a cell to a new or existing table

PDF_add_table_cell

(PECL pdflib >= 2.1.0)

PDF_add_table_cell — Add a cell to a new or existing table

Description

PDF_add_table_cell ( resource $pdfdoc , int $table , int $column , int $row , string $text , string $optlist ) : int

Adds a cell to a new or existing table.


Create Textflow or add text to existing Textflow

  • « PDF_add_table_cell
  • PDF_add_thumbnail »
  • PHP Manual
  • PDF Functions
  • Create Textflow or add text to existing Textflow

PDF_add_textflow

(PECL pdflib >= 2.1.0)

PDF_add_textflow — Create Textflow or add text to existing Textflow

Description

PDF_add_textflow ( resource $pdfdoc , int $textflow , string $text , string $optlist ) : int

Creates a Textflow object, or adds text and explicit options to an existing Textflow.


Add thumbnail for current page

  • « PDF_add_textflow
  • PDF_add_weblink »
  • PHP Manual
  • PDF Functions
  • Add thumbnail for current page

PDF_add_thumbnail

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_add_thumbnail — Add thumbnail for current page

Description

PDF_add_thumbnail ( resource $pdfdoc , int $image ) : bool

Adds an existing image as thumbnail for the current page. Returns TRUE on success or FALSE on failure.


Add weblink for current page [deprecated]

  • « PDF_add_thumbnail
  • PDF_arc »
  • PHP Manual
  • PDF Functions
  • Add weblink for current page [deprecated]

PDF_add_weblink

(PHP 4, PECL pdflib >= 1.0.0)

PDF_add_weblink — Add weblink for current page [deprecated]

Description

PDF_add_weblink ( resource $pdfdoc , float $lowerleftx , float $lowerlefty , float $upperrightx , float $upperrighty , string $url ) : bool

Adds a weblink annotation to a target url on the Web. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 6, use
PDF_create_action() with type=URI
and PDF_create_annotation() with
type=Link instead.


Draw a counterclockwise circular arc segment

  • « PDF_add_weblink
  • PDF_arcn »
  • PHP Manual
  • PDF Functions
  • Draw a counterclockwise circular arc segment

PDF_arc

(PHP 4, PECL pdflib >= 1.0.0)

PDF_arc — Draw a counterclockwise circular arc segment

Description

PDF_arc ( resource $p , float $x , float $y , float $r , float $alpha , float $beta ) : bool

Adds a counterclockwise circular arc.


Draw a clockwise circular arc segment

  • « PDF_arc
  • PDF_attach_file »
  • PHP Manual
  • PDF Functions
  • Draw a clockwise circular arc segment

PDF_arcn

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_arcn — Draw a clockwise circular arc segment

Description

PDF_arcn ( resource $p , float $x , float $y , float $r , float $alpha , float $beta ) : bool

Except for the drawing direction, this function behaves exactly like PDF_arc().


Add file attachment for current page [deprecated]

  • « PDF_arcn
  • PDF_begin_document »
  • PHP Manual
  • PDF Functions
  • Add file attachment for current page [deprecated]

PDF_attach_file

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_attach_file — Add file attachment for current page [deprecated]

Description

PDF_attach_file ( resource $pdfdoc , float $llx , float $lly , float $urx , float $ury , string $filename , string $description , string $author , string $mimetype , string $icon ) : bool

Adds a file attachment annotation. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 6, use PDF_create_annotation() with type=FileAttachment instead.


Create new PDF file

  • « PDF_attach_file
  • PDF_begin_font »
  • PHP Manual
  • PDF Functions
  • Create new PDF file

PDF_begin_document

(PECL pdflib >= 2.0.0)

PDF_begin_document — Create new PDF file

Description

PDF_begin_document ( resource $pdfdoc , string $filename , string $optlist ) : int

Creates a new PDF file subject to various options.


Start a Type 3 font definition

  • « PDF_begin_document
  • PDF_begin_glyph »
  • PHP Manual
  • PDF Functions
  • Start a Type 3 font definition

PDF_begin_font

(PECL pdflib >= 2.0.0)

PDF_begin_font — Start a Type 3 font definition

Description

PDF_begin_font ( resource $pdfdoc , string $filename , float $a , float $b , float $c , float $d , float $e , float $f , string $optlist ) : bool

Starts a Type 3 font definition.


Start glyph definition for Type 3 font

  • « PDF_begin_font
  • PDF_begin_item »
  • PHP Manual
  • PDF Functions
  • Start glyph definition for Type 3 font

PDF_begin_glyph

(PECL pdflib >= 2.0.0)

PDF_begin_glyph — Start glyph definition for Type 3 font

Description

PDF_begin_glyph ( resource $pdfdoc , string $glyphname , float $wx , float $llx , float $lly , float $urx , float $ury ) : bool

Starts a glyph definition for a Type 3 font.


Open structure element or other content item

  • « PDF_begin_glyph
  • PDF_begin_layer »
  • PHP Manual
  • PDF Functions
  • Open structure element or other content item

PDF_begin_item

(PECL pdflib >= 2.0.0)

PDF_begin_item — Open structure element or other content item

Description

PDF_begin_item ( resource $pdfdoc , string $tag , string $optlist ) : int

Opens a structure element or other content item with attributes supplied as options.


Start layer

  • « PDF_begin_item
  • PDF_begin_page_ext »
  • PHP Manual
  • PDF Functions
  • Start layer

PDF_begin_layer

(PECL pdflib >= 2.0.0)

PDF_begin_layer — Start layer

Description

PDF_begin_layer ( resource $pdfdoc , int $layer ) : bool

Starts a layer for subsequent output on the page. Returns TRUE on success or FALSE on failure.

This function requires PDF 1.5.


Start new page

  • « PDF_begin_layer
  • PDF_begin_page »
  • PHP Manual
  • PDF Functions
  • Start new page

PDF_begin_page_ext

(PECL pdflib >= 2.0.0)

PDF_begin_page_ext — Start new page

Description

PDF_begin_page_ext ( resource $pdfdoc , float $width , float $height , string $optlist ) : bool

Adds a new page to the document, and specifies various options. The parameters width and height are the dimensions of the new page in points. Returns TRUE on success or FALSE on failure.

Common Page Sizes in Points
name | size
A0 | 2380 x 3368
A1 | 1684 x 2380
A2 | 1190 x 1684
A3 | 842 x 1190
A4 | 595 x 842
A5 | 421 x 595
A6 | 297 x 421
B5 | 501 x 709
letter (8.5" x 11") | 612 x 792
legal (8.5" x 14") | 612 x 1008
ledger (17" x 11") | 1224 x 792
11" x 17" | 792 x 1224


Start new page [deprecated]

  • « PDF_begin_page_ext
  • PDF_begin_pattern »
  • PHP Manual
  • PDF Functions
  • Start new page [deprecated]

PDF_begin_page

(PHP 4, PECL pdflib >= 1.0.0)

PDF_begin_page — Start new page [deprecated]

Description

PDF_begin_page ( resource $pdfdoc , float $width , float $height ) : bool

Adds a new page to the document. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 6, use PDF_begin_page_ext() instead.


Start pattern definition

  • « PDF_begin_page
  • PDF_begin_template_ext »
  • PHP Manual
  • PDF Functions
  • Start pattern definition

PDF_begin_pattern

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_begin_pattern — Start pattern definition

Description

PDF_begin_pattern ( resource $pdfdoc , float $width , float $height , float $xstep , float $ystep , int $painttype ) : int

Starts a new pattern definition.


Start template definition

  • « PDF_begin_pattern
  • PDF_begin_template »
  • PHP Manual
  • PDF Functions
  • Start template definition

PDF_begin_template_ext

(PECL pdflib >= 2.1.0)

PDF_begin_template_ext — Start template definition

Description

PDF_begin_template_ext ( resource $pdfdoc , float $width , float $height , string $optlist ) : int

Starts a new template definition.


Start template definition [deprecated]

  • « PDF_begin_template_ext
  • PDF_circle »
  • PHP Manual
  • PDF Functions
  • Start template definition [deprecated]

PDF_begin_template

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_begin_template — Start template definition [deprecated]

Description

PDF_begin_template ( resource $pdfdoc , float $width , float $height ) : int

Starts a new template definition.

This function is deprecated since PDFlib version 7, use PDF_begin_template_ext() instead.


Draw a circle

  • « PDF_begin_template
  • PDF_clip »
  • PHP Manual
  • PDF Functions
  • Draw a circle

PDF_circle

(PHP 4, PECL pdflib >= 1.0.0)

PDF_circle — Draw a circle

Description

PDF_circle ( resource $pdfdoc , float $x , float $y , float $r ) : bool

Adds a circle. Returns TRUE on success or FALSE on failure.


Clip to current path

  • « PDF_circle
  • PDF_close_image »
  • PHP Manual
  • PDF Functions
  • Clip to current path

PDF_clip

(PHP 4, PECL pdflib >= 1.0.0)

PDF_clip — Clip to current path

Description

PDF_clip ( resource $p ) : bool

Uses the current path as clipping path, and terminate the path. Returns TRUE on success or FALSE on failure.


Close image

  • « PDF_clip
  • PDF_close_pdi_page »
  • PHP Manual
  • PDF Functions
  • Close image

PDF_close_image

(PHP 4, PECL pdflib >= 1.0.0)

PDF_close_image — Close image

Description

PDF_close_image ( resource $p , int $image ) : bool

Closes an image retrieved with the PDF_open_image() function.


Close the page handle

  • « PDF_close_image
  • PDF_close_pdi »
  • PHP Manual
  • PDF Functions
  • Close the page handle

PDF_close_pdi_page

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_close_pdi_page — Close the page handle

Description

PDF_close_pdi_page ( resource $p , int $page ) : bool

Closes the page handle, and frees all page-related resources. Returns TRUE on success or FALSE on failure.


Close the input PDF document [deprecated]

  • « PDF_close_pdi_page
  • PDF_close »
  • PHP Manual
  • PDF Functions
  • Close the input PDF document [deprecated]

PDF_close_pdi

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_close_pdi — Close the input PDF document [deprecated]

Description

PDF_close_pdi ( resource $p , int $doc ) : bool

Closes all open page handles, and closes the input PDF document. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 7, use PDF_close_pdi_document() instead.


Close pdf resource [deprecated]

  • « PDF_close_pdi
  • PDF_closepath_fill_stroke »
  • PHP Manual
  • PDF Functions
  • Close pdf resource [deprecated]

PDF_close

(PHP 4, PECL pdflib >= 1.0.0)

PDF_close — Close pdf resource [deprecated]

Description

PDF_close ( resource $p ) : bool

Closes the generated PDF file, and frees all document-related resources. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 6, use PDF_end_document() instead.


Close, fill and stroke current path

  • « PDF_close
  • PDF_closepath_stroke »
  • PHP Manual
  • PDF Functions
  • Close, fill and stroke current path

PDF_closepath_fill_stroke

(PHP 4, PECL pdflib >= 1.0.0)

PDF_closepath_fill_stroke — Close, fill and stroke current path

Description

PDF_closepath_fill_stroke ( resource $p ) : bool

Closes the path, fills, and strokes it. Returns TRUE on success or FALSE on failure.


Close and stroke path

  • « PDF_closepath_fill_stroke
  • PDF_closepath »
  • PHP Manual
  • PDF Functions
  • Close and stroke path

PDF_closepath_stroke

(PHP 4, PECL pdflib >= 1.0.0)

PDF_closepath_stroke — Close and stroke path

Description

PDF_closepath_stroke ( resource $p ) : bool

Closes the path, and strokes it. Returns TRUE on success or FALSE on failure.


Close current path

  • « PDF_closepath_stroke
  • PDF_concat »
  • PHP Manual
  • PDF Functions
  • Close current path

PDF_closepath

(PHP 4, PECL pdflib >= 1.0.0)

PDF_closepath — Close current path

Description

PDF_closepath ( resource $p ) : bool

Closes the current path. Returns TRUE on success or FALSE on failure.


Concatenate a matrix to the CTM

  • « PDF_closepath
  • PDF_continue_text »
  • PHP Manual
  • PDF Functions
  • Concatenate a matrix to the CTM

PDF_concat

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_concat — Concatenate a matrix to the CTM

Description

PDF_concat ( resource $p , float $a , float $b , float $c , float $d , float $e , float $f ) : bool

Concatenates a matrix to the current transformation matrix (CTM). Returns TRUE on success or FALSE on failure.


Output text in next line

  • « PDF_concat
  • PDF_create_3dview »
  • PHP Manual
  • PDF Functions
  • Output text in next line

PDF_continue_text

(PHP 4, PECL pdflib >= 1.0.0)

PDF_continue_text — Output text in next line

Description

PDF_continue_text ( resource $p , string $text ) : bool

Prints text at the next line. Returns TRUE on success or FALSE on failure.


Create 3D view

  • « PDF_continue_text
  • PDF_create_action »
  • PHP Manual
  • PDF Functions
  • Create 3D view

PDF_create_3dview

(PECL pdflib >= 2.1.0)

PDF_create_3dview — Create 3D view

Description

PDF_create_3dview ( resource $pdfdoc , string $username , string $optlist ) : int

Creates a 3D view.

This function requires PDF 1.6.


Create action for objects or events

  • « PDF_create_3dview
  • PDF_create_annotation »
  • PHP Manual
  • PDF Functions
  • Create action for objects or events

PDF_create_action

(PECL pdflib >= 2.0.0)

PDF_create_action — Create action for objects or events

Description

PDF_create_action ( resource $pdfdoc , string $type , string $optlist ) : int

Creates an action which can be applied to various objects and events.


Create rectangular annotation

  • « PDF_create_action
  • PDF_create_bookmark »
  • PHP Manual
  • PDF Functions
  • Create rectangular annotation

PDF_create_annotation

(PECL pdflib >= 2.0.0)

PDF_create_annotation — Create rectangular annotation

Description

PDF_create_annotation ( resource $pdfdoc , float $llx , float $lly , float $urx , float $ury , string $type , string $optlist ) : bool

Creates a rectangular annotation on the current page.


Create bookmark

  • « PDF_create_annotation
  • PDF_create_field »
  • PHP Manual
  • PDF Functions
  • Create bookmark

PDF_create_bookmark

(PECL pdflib >= 2.0.0)

PDF_create_bookmark — Create bookmark

Description

PDF_create_bookmark ( resource $pdfdoc , string $text , string $optlist ) : int

Creates a bookmark subject to various options.


Create form field

  • « PDF_create_bookmark
  • PDF_create_fieldgroup »
  • PHP Manual
  • PDF Functions
  • Create form field

PDF_create_field

(PECL pdflib >= 2.0.0)

PDF_create_field — Create form field

Description

PDF_create_field ( resource $pdfdoc , float $llx , float $lly , float $urx , float $ury , string $name , string $type , string $optlist ) : bool

Creates a form field on the current page subject to various options.


Create form field group

  • « PDF_create_field
  • PDF_create_gstate »
  • PHP Manual
  • PDF Functions
  • Create form field group

PDF_create_fieldgroup

(PECL pdflib >= 2.0.0)

PDF_create_fieldgroup — Create form field group

Description

PDF_create_fieldgroup ( resource $pdfdoc , string $name , string $optlist ) : bool

Creates a form field group subject to various options.


Create graphics state object

  • « PDF_create_fieldgroup
  • PDF_create_pvf »
  • PHP Manual
  • PDF Functions
  • Create graphics state object

PDF_create_gstate

(PECL pdflib >= 2.0.0)

PDF_create_gstate — Create graphics state object

Description

PDF_create_gstate ( resource $pdfdoc , string $optlist ) : int

Creates a graphics state object subject to various options.


Create PDFlib virtual file

  • « PDF_create_gstate
  • PDF_create_textflow »
  • PHP Manual
  • PDF Functions
  • Create PDFlib virtual file

PDF_create_pvf

(PECL pdflib >= 2.0.0)

PDF_create_pvf — Create PDFlib virtual file

Description

PDF_create_pvf ( resource $pdfdoc , string $filename , string $data , string $optlist ) : bool

Creates a named virtual read-only file from data provided in memory.


Create textflow object

  • « PDF_create_pvf
  • PDF_curveto »
  • PHP Manual
  • PDF Functions
  • Create textflow object

PDF_create_textflow

(PECL pdflib >= 2.0.0)

PDF_create_textflow — Create textflow object

Description

PDF_create_textflow ( resource $pdfdoc , string $text , string $optlist ) : int

Preprocesses text for later formatting and creates a textflow object.


Draw Bezier curve

  • « PDF_create_textflow
  • PDF_define_layer »
  • PHP Manual
  • PDF Functions
  • Draw Bezier curve

PDF_curveto

(PHP 4, PECL pdflib >= 1.0.0)

PDF_curveto — Draw Bezier curve

Description

PDF_curveto ( resource $p , float $x1 , float $y1 , float $x2 , float $y2 , float $x3 , float $y3 ) : bool

Draws a Bezier curve from the current point, using 3 more control points. Returns TRUE on success or FALSE on failure.


Create layer definition

  • « PDF_curveto
  • PDF_delete_pvf »
  • PHP Manual
  • PDF Functions
  • Create layer definition

PDF_define_layer

(PECL pdflib >= 2.0.0)

PDF_define_layer — Create layer definition

Description

PDF_define_layer ( resource $pdfdoc , string $name , string $optlist ) : int

Creates a new layer definition.

This function requires PDF 1.5.


Delete PDFlib virtual file

  • « PDF_define_layer
  • PDF_delete_table »
  • PHP Manual
  • PDF Functions
  • Delete PDFlib virtual file

PDF_delete_pvf

(PECL pdflib >= 2.0.0)

PDF_delete_pvf — Delete PDFlib virtual file

Description

PDF_delete_pvf ( resource $pdfdoc , string $filename ) : int

Deletes a named virtual file and frees its data structures (but not the contents).


Delete table object

  • « PDF_delete_pvf
  • PDF_delete_textflow »
  • PHP Manual
  • PDF Functions
  • Delete table object

PDF_delete_table

(PECL pdflib >= 2.1.0)

PDF_delete_table — Delete table object

Description

PDF_delete_table ( resource $pdfdoc , int $table , string $optlist ) : bool

Deletes a table and all associated data structures.


Delete textflow object

  • « PDF_delete_table
  • PDF_delete »
  • PHP Manual
  • PDF Functions
  • Delete textflow object

PDF_delete_textflow

(PECL pdflib >= 2.0.0)

PDF_delete_textflow — Delete textflow object

Description

PDF_delete_textflow ( resource $pdfdoc , int $textflow ) : bool

Deletes a textflow and the associated data structures.


Delete PDFlib object

  • « PDF_delete_textflow
  • PDF_encoding_set_char »
  • PHP Manual
  • PDF Functions
  • Delete PDFlib object

PDF_delete

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_delete — Delete PDFlib object

Description

PDF_delete ( resource $pdfdoc ) : bool

Deletes a PDFlib object, and frees all internal resources. Returns TRUE on success or FALSE on failure.


Add glyph name and/or Unicode value

  • « PDF_delete
  • PDF_end_document »
  • PHP Manual
  • PDF Functions
  • Add glyph name and/or Unicode value

PDF_encoding_set_char

(PECL pdflib >= 2.0.0)

PDF_encoding_set_char — Add glyph name and/or Unicode value

Description

PDF_encoding_set_char ( resource $pdfdoc , string $encoding , int $slot , string $glyphname , int $uv ) : bool

Adds a glyph name and/or Unicode value to a custom encoding.


Close PDF file

  • « PDF_encoding_set_char
  • PDF_end_font »
  • PHP Manual
  • PDF Functions
  • Close PDF file

PDF_end_document

(PECL pdflib >= 2.0.0)

PDF_end_document — Close PDF file

Description

PDF_end_document ( resource $pdfdoc , string $optlist ) : bool

Closes the generated PDF file and applies various options.


Terminate Type 3 font definition

  • « PDF_end_document
  • PDF_end_glyph »
  • PHP Manual
  • PDF Functions
  • Terminate Type 3 font definition

PDF_end_font

(PECL pdflib >= 2.0.0)

PDF_end_font — Terminate Type 3 font definition

Description

PDF_end_font ( resource $pdfdoc ) : bool

Terminates a Type 3 font definition.


Terminate glyph definition for Type 3 font

  • « PDF_end_font
  • PDF_end_item »
  • PHP Manual
  • PDF Functions
  • Terminate glyph definition for Type 3 font

PDF_end_glyph

(PECL pdflib >= 2.0.0)

PDF_end_glyph — Terminate glyph definition for Type 3 font

Description

PDF_end_glyph ( resource $pdfdoc ) : bool

Terminates a glyph definition for a Type 3 font.


Close structure element or other content item

  • « PDF_end_glyph
  • PDF_end_layer »
  • PHP Manual
  • PDF Functions
  • Close structure element or other content item

PDF_end_item

(PECL pdflib >= 2.0.0)

PDF_end_item — Close structure element or other content item

Description

PDF_end_item ( resource $pdfdoc , int $id ) : bool

Closes a structure element or other content item.


Deactivate all active layers

  • « PDF_end_item
  • PDF_end_page_ext »
  • PHP Manual
  • PDF Functions
  • Deactivate all active layers

PDF_end_layer

(PECL pdflib >= 2.0.0)

PDF_end_layer — Deactivate all active layers

Description

PDF_end_layer ( resource $pdfdoc ) : bool

Deactivates all active layers. Returns TRUE on success or FALSE on failure.

This function requires PDF 1.5.


Finish page

  • « PDF_end_layer
  • PDF_end_page »
  • PHP Manual
  • PDF Functions
  • Finish page

PDF_end_page_ext

(PECL pdflib >= 2.0.0)

PDF_end_page_ext — Finish page

Description

PDF_end_page_ext ( resource $pdfdoc , string $optlist ) : bool

Finishes a page, and applies various options. Returns TRUE on success or FALSE on failure.


Finish page

  • « PDF_end_page_ext
  • PDF_end_pattern »
  • PHP Manual
  • PDF Functions
  • Finish page

PDF_end_page

(PHP 4, PECL pdflib >= 1.0.0)

PDF_end_page — Finish page

Description

PDF_end_page ( resource $p ) : bool

Finishes the page. Returns TRUE on success or FALSE on failure.


Finish pattern

  • « PDF_end_page
  • PDF_end_template »
  • PHP Manual
  • PDF Functions
  • Finish pattern

PDF_end_pattern

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_end_pattern — Finish pattern

Description

PDF_end_pattern ( resource $p ) : bool

Finishes the pattern definition. Returns TRUE on success or FALSE on failure.


Finish template

  • « PDF_end_pattern
  • PDF_endpath »
  • PHP Manual
  • PDF Functions
  • Finish template

PDF_end_template

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_end_template — Finish template

Description

PDF_end_template ( resource $p ) : bool

Finishes a template definition. Returns TRUE on success or FALSE on failure.


End current path

  • « PDF_end_template
  • PDF_fill_imageblock »
  • PHP Manual
  • PDF Functions
  • End current path

PDF_endpath

(PHP 4, PECL pdflib >= 1.0.0)

PDF_endpath — End current path

Description

PDF_endpath ( resource $p ) : bool

Ends the current path without filling or stroking it.


Fill image block with variable data

  • « PDF_endpath
  • PDF_fill_pdfblock »
  • PHP Manual
  • PDF Functions
  • Fill image block with variable data

PDF_fill_imageblock

(PECL pdflib >= 2.0.0)

PDF_fill_imageblock — Fill image block with variable data

Description

PDF_fill_imageblock ( resource $pdfdoc , int $page , string $blockname , int $image , string $optlist ) : int

Fills an image block with variable data according to its properties.

This function is only available in the PDFlib Personalization Server (PPS).


Fill PDF block with variable data

  • « PDF_fill_imageblock
  • PDF_fill_stroke »
  • PHP Manual
  • PDF Functions
  • Fill PDF block with variable data

PDF_fill_pdfblock

(PECL pdflib >= 2.0.0)

PDF_fill_pdfblock — Fill PDF block with variable data

Description

PDF_fill_pdfblock ( resource $pdfdoc , int $page , string $blockname , int $contents , string $optlist ) : int

Fills a PDF block with variable data according to its properties.

This function is only available in the PDFlib Personalization Server (PPS).


Fill and stroke path

  • « PDF_fill_pdfblock
  • PDF_fill_textblock »
  • PHP Manual
  • PDF Functions
  • Fill and stroke path

PDF_fill_stroke

(PHP 4, PECL pdflib >= 1.0.0)

PDF_fill_stroke — Fill and stroke path

Description

PDF_fill_stroke ( resource $p ) : bool

Fills and strokes the current path with the current fill and stroke color. Returns TRUE on success or FALSE on failure.


Fill text block with variable data

  • « PDF_fill_stroke
  • PDF_fill »
  • PHP Manual
  • PDF Functions
  • Fill text block with variable data

PDF_fill_textblock

(PECL pdflib >= 2.0.0)

PDF_fill_textblock — Fill text block with variable data

Description

PDF_fill_textblock ( resource $pdfdoc , int $page , string $blockname , string $text , string $optlist ) : int

Fills a text block with variable data according to its properties.

This function is only available in the PDFlib Personalization Server (PPS).


Fill current path

  • « PDF_fill_textblock
  • PDF_findfont »
  • PHP Manual
  • PDF Functions
  • Fill current path

PDF_fill

(PHP 4, PECL pdflib >= 1.0.0)

PDF_fill — Fill current path

Description

PDF_fill ( resource $p ) : bool

Fills the interior of the current path with the current fill color. Returns TRUE on success or FALSE on failure.


Prepare font for later use [deprecated]

  • « PDF_fill
  • PDF_fit_image »
  • PHP Manual
  • PDF Functions
  • Prepare font for later use [deprecated]

PDF_findfont

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_findfont — Prepare font for later use [deprecated]

Description

PDF_findfont ( resource $p , string $fontname , string $encoding , int $embed ) : int

Search for a font and prepare it for later use with PDF_setfont(). The metrics will be loaded, and if embed is nonzero, the font file will be checked, but not yet used. encoding is one of builtin, macroman, winansi, host, a user-defined encoding name or the name of a CMap. Parameter embed is optional before PHP 4.3.5 or with PDFlib less than 5.

This function is deprecated since PDFlib version 5, use PDF_load_font() instead.


Place image or template

  • « PDF_findfont
  • PDF_fit_pdi_page »
  • PHP Manual
  • PDF Functions
  • Place image or template

PDF_fit_image

(PECL pdflib >= 2.0.0)

PDF_fit_image — Place image or template

Description

PDF_fit_image ( resource $pdfdoc , int $image , float $x , float $y , string $optlist ) : bool

Places an image or template on the page, subject to various options. Returns TRUE on success or FALSE on failure.


Place imported PDF page

  • « PDF_fit_image
  • PDF_fit_table »
  • PHP Manual
  • PDF Functions
  • Place imported PDF page

PDF_fit_pdi_page

(PECL pdflib >= 2.0.0)

PDF_fit_pdi_page — Place imported PDF page

Description

PDF_fit_pdi_page ( resource $pdfdoc , int $page , float $x , float $y , string $optlist ) : bool

Places an imported PDF page on the page, subject to various options. Returns TRUE on success or FALSE on failure.


Place table on page

  • « PDF_fit_pdi_page
  • PDF_fit_textflow »
  • PHP Manual
  • PDF Functions
  • Place table on page

PDF_fit_table

(PECL pdflib >= 2.1.0)

PDF_fit_table — Place table on page

Description

PDF_fit_table ( resource $pdfdoc , int $table , float $llx , float $lly , float $urx , float $ury , string $optlist ) : string

Places a table on the page fully or partially.


Format textflow in rectangular area

  • « PDF_fit_table
  • PDF_fit_textline »
  • PHP Manual
  • PDF Functions
  • Format textflow in rectangular area

PDF_fit_textflow

(PECL pdflib >= 2.0.0)

PDF_fit_textflow — Format textflow in rectangular area

Description

PDF_fit_textflow ( resource $pdfdoc , int $textflow , float $llx , float $lly , float $urx , float $ury , string $optlist ) : string

Formats the next portion of a textflow into a rectangular area.


Place single line of text

  • « PDF_fit_textflow
  • PDF_get_apiname »
  • PHP Manual
  • PDF Functions
  • Place single line of text

PDF_fit_textline

(PECL pdflib >= 2.0.0)

PDF_fit_textline — Place single line of text

Description

PDF_fit_textline ( resource $pdfdoc , string $text , float $x , float $y , string $optlist ) : bool

Places a single line of text on the page, subject to various options. Returns TRUE on success or FALSE on failure.


Get name of unsuccessfull API function

  • « PDF_fit_textline
  • PDF_get_buffer »
  • PHP Manual
  • PDF Functions
  • Get name of unsuccessfull API function

PDF_get_apiname

(PECL pdflib >= 2.0.0)

PDF_get_apiname — Get name of unsuccessfull API function

Description

PDF_get_apiname ( resource $pdfdoc ) : string

Gets the name of the API function which threw the last exception or failed.


Get PDF output buffer

  • « PDF_get_apiname
  • PDF_get_errmsg »
  • PHP Manual
  • PDF Functions
  • Get PDF output buffer

PDF_get_buffer

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_get_buffer — Get PDF output buffer

Description

PDF_get_buffer ( resource $p ) : string

Fetches the buffer containing the generated PDF data.


Get error text

  • « PDF_get_buffer
  • PDF_get_errnum »
  • PHP Manual
  • PDF Functions
  • Get error text

PDF_get_errmsg

(PECL pdflib >= 2.0.0)

PDF_get_errmsg — Get error text

Description

PDF_get_errmsg ( resource $pdfdoc ) : string

Gets the text of the last thrown exception or the reason for a failed function call.


Get error number

  • « PDF_get_errmsg
  • PDF_get_font »
  • PHP Manual
  • PDF Functions
  • Get error number

PDF_get_errnum

(PECL pdflib >= 2.0.0)

PDF_get_errnum — Get error number

Description

PDF_get_errnum ( resource $pdfdoc ) : int

Gets the number of the last thrown exception or the reason for a failed function call.


Get font [deprecated]

  • « PDF_get_errnum
  • PDF_get_fontname »
  • PHP Manual
  • PDF Functions
  • Get font [deprecated]

PDF_get_font

(PHP 4, PECL pdflib >= 1.0.0)

PDF_get_font — Get font [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_get_value() with the parameter font instead.


Get font name [deprecated]

  • « PDF_get_font
  • PDF_get_fontsize »
  • PHP Manual
  • PDF Functions
  • Get font name [deprecated]

PDF_get_fontname

(PHP 4, PECL pdflib >= 1.0.0)

PDF_get_fontname — Get font name [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_get_parameter() with the parameter fontname instead.


Font handling [deprecated]

  • « PDF_get_fontname
  • PDF_get_image_height »
  • PHP Manual
  • PDF Functions
  • Font handling [deprecated]

PDF_get_fontsize

(PHP 4, PECL pdflib >= 1.0.0)

PDF_get_fontsize — Font handling [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_get_value() with the parameter fontsizeinstead.


Get image height [deprecated]

  • « PDF_get_fontsize
  • PDF_get_image_width »
  • PHP Manual
  • PDF Functions
  • Get image height [deprecated]

PDF_get_image_height

(PHP 4, PECL pdflib >= 1.0.0)

PDF_get_image_height — Get image height [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_get_value() with the parameter imageheight instead.


Get image width [deprecated]

  • « PDF_get_image_height
  • PDF_get_majorversion »
  • PHP Manual
  • PDF Functions
  • Get image width [deprecated]

PDF_get_image_width

(PHP 4, PECL pdflib >= 1.0.0)

PDF_get_image_width — Get image width [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_get_value() with the parameter imagewidth instead.


Get major version number [deprecated]

  • « PDF_get_image_width
  • PDF_get_minorversion »
  • PHP Manual
  • PDF Functions
  • Get major version number [deprecated]

PDF_get_majorversion

(PHP 4 >= 4.2.0, PECL pdflib >= 1.0.0)

PDF_get_majorversion — Get major version number [deprecated]

Description

PDF_get_majorversion ( void ) : int

This function is deprecated since PDFlib version 5, use PDF_get_value() with the parameter major instead.


Get minor version number [deprecated]

  • « PDF_get_majorversion
  • PDF_get_parameter »
  • PHP Manual
  • PDF Functions
  • Get minor version number [deprecated]

PDF_get_minorversion

(PHP 4 >= 4.2.0, PECL pdflib >= 1.0.0)

PDF_get_minorversion — Get minor version number [deprecated]

Description

PDF_get_minorversion ( void ) : int

Returns the minor version number of the PDFlib version.

This function is deprecated since PDFlib version 5, use PDF_get_value() with the parameter minor instead.


Get string parameter

  • « PDF_get_minorversion
  • PDF_get_pdi_parameter »
  • PHP Manual
  • PDF Functions
  • Get string parameter

PDF_get_parameter

(PHP 4 >= 4.0.1, PECL pdflib >= 1.0.0)

PDF_get_parameter — Get string parameter

Description

PDF_get_parameter ( resource $p , string $key , float $modifier ) : string

Gets the contents of some PDFlib parameter with string type.


Get PDI string parameter [deprecated]

  • « PDF_get_parameter
  • PDF_get_pdi_value »
  • PHP Manual
  • PDF Functions
  • Get PDI string parameter [deprecated]

PDF_get_pdi_parameter

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_get_pdi_parameter — Get PDI string parameter [deprecated]

Description

PDF_get_pdi_parameter ( resource $p , string $key , int $doc , int $page , int $reserved ) : string

Gets the contents of a PDI document parameter with string type.

This function is deprecated since PDFlib version 7, use PDF_pcos_get_string() instead.


Get PDI numerical parameter [deprecated]

  • « PDF_get_pdi_parameter
  • PDF_get_value »
  • PHP Manual
  • PDF Functions
  • Get PDI numerical parameter [deprecated]

PDF_get_pdi_value

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_get_pdi_value — Get PDI numerical parameter [deprecated]

Description

PDF_get_pdi_value ( resource $p , string $key , int $doc , int $page , int $reserved ) : float

Gets the contents of a PDI document parameter with numerical type.

This function is deprecated since PDFlib version 7, use PDF_pcos_get_number() instead.


Get numerical parameter

  • « PDF_get_pdi_value
  • PDF_info_font »
  • PHP Manual
  • PDF Functions
  • Get numerical parameter

PDF_get_value

(PHP 4 >= 4.0.1, PECL pdflib >= 1.0.0)

PDF_get_value — Get numerical parameter

Description

PDF_get_value ( resource $p , string $key , float $modifier ) : float

Gets the value of some PDFlib parameter with numerical type.


Query detailed information about a loaded font

  • « PDF_get_value
  • PDF_info_matchbox »
  • PHP Manual
  • PDF Functions
  • Query detailed information about a loaded font

PDF_info_font

(PECL pdflib >= 2.1.0)

PDF_info_font — Query detailed information about a loaded font

Description

PDF_info_font ( resource $pdfdoc , int $font , string $keyword , string $optlist ) : float

Queries detailed information about a loaded font.


Query matchbox information

  • « PDF_info_font
  • PDF_info_table »
  • PHP Manual
  • PDF Functions
  • Query matchbox information

PDF_info_matchbox

(PECL pdflib >= 2.1.0)

PDF_info_matchbox — Query matchbox information

Description

PDF_info_matchbox ( resource $pdfdoc , string $boxname , int $num , string $keyword ) : float

Queries information about a matchbox on the current page.


Retrieve table information

  • « PDF_info_matchbox
  • PDF_info_textflow »
  • PHP Manual
  • PDF Functions
  • Retrieve table information

PDF_info_table

(PECL pdflib >= 2.1.0)

PDF_info_table — Retrieve table information

Description

PDF_info_table ( resource $pdfdoc , int $table , string $keyword ) : float

Retrieves table information related to the most recently placed table instance.


Query textflow state

  • « PDF_info_table
  • PDF_info_textline »
  • PHP Manual
  • PDF Functions
  • Query textflow state

PDF_info_textflow

(PECL pdflib >= 2.0.0)

PDF_info_textflow — Query textflow state

Description

PDF_info_textflow ( resource $pdfdoc , int $textflow , string $keyword ) : float

Queries the current state of a textflow.


Perform textline formatting and query metrics

  • « PDF_info_textflow
  • PDF_initgraphics »
  • PHP Manual
  • PDF Functions
  • Perform textline formatting and query metrics

PDF_info_textline

(PECL pdflib >= 2.1.0)

PDF_info_textline — Perform textline formatting and query metrics

Description

PDF_info_textline ( resource $pdfdoc , string $text , string $keyword , string $optlist ) : float

Performs textline formatting and queries the resulting metrics.


Reset graphic state

  • « PDF_info_textline
  • PDF_lineto »
  • PHP Manual
  • PDF Functions
  • Reset graphic state

PDF_initgraphics

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_initgraphics — Reset graphic state

Description

PDF_initgraphics ( resource $p ) : bool

Reset all color and graphics state parameters to their defaults. Returns TRUE on success or FALSE on failure.


Draw a line

  • « PDF_initgraphics
  • PDF_load_3ddata »
  • PHP Manual
  • PDF Functions
  • Draw a line

PDF_lineto

(PHP 4, PECL pdflib >= 1.0.0)

PDF_lineto — Draw a line

Description

PDF_lineto ( resource $p , float $x , float $y ) : bool

Draws a line from the current point to another point. Returns TRUE on success or FALSE on failure.


Load 3D model

  • « PDF_lineto
  • PDF_load_font »
  • PHP Manual
  • PDF Functions
  • Load 3D model

PDF_load_3ddata

(PECL pdflib >= 2.1.0)

PDF_load_3ddata — Load 3D model

Description

PDF_load_3ddata ( resource $pdfdoc , string $filename , string $optlist ) : int

Loads a 3D model from a disk-based or virtual file.

This function requires PDF 1.6.


Search and prepare font

  • « PDF_load_3ddata
  • PDF_load_iccprofile »
  • PHP Manual
  • PDF Functions
  • Search and prepare font

PDF_load_font

(PECL pdflib >= 2.0.0)

PDF_load_font — Search and prepare font

Description

PDF_load_font ( resource $pdfdoc , string $fontname , string $encoding , string $optlist ) : int

Searches for a font and prepares it for later use.


Search and prepare ICC profile

  • « PDF_load_font
  • PDF_load_image »
  • PHP Manual
  • PDF Functions
  • Search and prepare ICC profile

PDF_load_iccprofile

(PECL pdflib >= 2.0.0)

PDF_load_iccprofile — Search and prepare ICC profile

Description

PDF_load_iccprofile ( resource $pdfdoc , string $profilename , string $optlist ) : int

Searches for an ICC profile, and prepares it for later use.


Open image file

  • « PDF_load_iccprofile
  • PDF_makespotcolor »
  • PHP Manual
  • PDF Functions
  • Open image file

PDF_load_image

(PECL pdflib >= 2.0.0)

PDF_load_image — Open image file

Description

PDF_load_image ( resource $pdfdoc , string $imagetype , string $filename , string $optlist ) : int

Opens a disk-based or virtual image file subject to various options.


Make spot color

  • « PDF_load_image
  • PDF_moveto »
  • PHP Manual
  • PDF Functions
  • Make spot color

PDF_makespotcolor

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_makespotcolor — Make spot color

Description

PDF_makespotcolor ( resource $p , string $spotname ) : int

Finds a built-in spot color name, or makes a named spot color from the current fill color. Returns TRUE on success or FALSE on failure.


Set current point

  • « PDF_makespotcolor
  • PDF_new »
  • PHP Manual
  • PDF Functions
  • Set current point

PDF_moveto

(PHP 4, PECL pdflib >= 1.0.0)

PDF_moveto — Set current point

Description

PDF_moveto ( resource $p , float $x , float $y ) : bool

Sets the current point for graphics output. Returns TRUE on success or FALSE on failure.


Create PDFlib object

  • « PDF_moveto
  • PDF_open_ccitt »
  • PHP Manual
  • PDF Functions
  • Create PDFlib object

PDF_new

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_new — Create PDFlib object

Description

PDF_new ( void ) : resource

Creates a new PDFlib object with default settings.


Open raw CCITT image [deprecated]

  • « PDF_new
  • PDF_open_file »
  • PHP Manual
  • PDF Functions
  • Open raw CCITT image [deprecated]

PDF_open_ccitt

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_open_ccitt — Open raw CCITT image [deprecated]

Description

PDF_open_ccitt ( resource $pdfdoc , string $filename , int $width , int $height , int $BitReverse , int $k , int $Blackls1 ) : int

Opens a raw CCITT image.

This function is deprecated since PDFlib version 5, use PDF_load_image() instead.


Create PDF file [deprecated]

  • « PDF_open_ccitt
  • PDF_open_gif »
  • PHP Manual
  • PDF Functions
  • Create PDF file [deprecated]

PDF_open_file

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_open_file — Create PDF file [deprecated]

Description

PDF_open_file ( resource $p , string $filename ) : bool

Creates a new PDF file using the supplied file name. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 6, use PDF_begin_document() instead.


Open GIF image [deprecated]

  • « PDF_open_file
  • PDF_open_image_file »
  • PHP Manual
  • PDF Functions
  • Open GIF image [deprecated]

PDF_open_gif

(PHP 4, PECL pdflib >= 1.0.0)

PDF_open_gif — Open GIF image [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_load_image() instead.


Read image from file [deprecated]

  • « PDF_open_gif
  • PDF_open_image »
  • PHP Manual
  • PDF Functions
  • Read image from file [deprecated]

PDF_open_image_file

(PHP 4, PECL pdflib >= 1.0.0)

PDF_open_image_file — Read image from file [deprecated]

Description

PDF_open_image_file ( resource $p , string $imagetype , string $filename , string $stringparam , int $intparam ) : int

Opens an image file.

This function is deprecated since PDFlib version 5, use PDF_load_image() with the colorize, ignoremask, invert, mask, masked, and page options instead.


Use image data [deprecated]

  • « PDF_open_image_file
  • PDF_open_jpeg »
  • PHP Manual
  • PDF Functions
  • Use image data [deprecated]

PDF_open_image

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_open_image — Use image data [deprecated]

Description

PDF_open_image ( resource $p , string $imagetype , string $source , string $data , int $length , int $width , int $height , int $components , int $bpc , string $params ) : int

Uses image data from a variety of data sources.

This function is deprecated since PDFlib version 5, use virtual files and PDF_load_image() instead.


Open JPEG image [deprecated]

  • « PDF_open_image
  • PDF_open_memory_image »
  • PHP Manual
  • PDF Functions
  • Open JPEG image [deprecated]

PDF_open_jpeg

(PHP 4, PECL pdflib >= 1.0.0)

PDF_open_jpeg — Open JPEG image [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_load_image() instead.


Open image created with PHP's image functions [not supported]

  • « PDF_open_jpeg
  • PDF_open_pdi_document »
  • PHP Manual
  • PDF Functions
  • Open image created with PHP's image functions [not supported]

PDF_open_memory_image

(PHP 4, PECL pdflib >= 1.0.0)

PDF_open_memory_image — Open image created with PHP's image functions [not supported]

Description

PDF_open_memory_image ( resource $p , resource $image ) : int

This function is not supported by PDFlib GmbH.


Prepare a pdi document

  • « PDF_open_memory_image
  • PDF_open_pdi_page »
  • PHP Manual
  • PDF Functions
  • Prepare a pdi document

PDF_open_pdi_document

(PECL pdflib >= 2.1.0)

PDF_open_pdi_document — Prepare a pdi document

Description

PDF_open_pdi_document ( resource $p , string $filename , string $optlist ) : int

Open a disk-based or virtual PDF document and prepare it for later use.


Prepare a page

  • « PDF_open_pdi_document
  • PDF_open_pdi »
  • PHP Manual
  • PDF Functions
  • Prepare a page

PDF_open_pdi_page

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_open_pdi_page — Prepare a page

Description

PDF_open_pdi_page ( resource $p , int $doc , int $pagenumber , string $optlist ) : int

Prepares a page for later use with PDF_fit_pdi_page().


Open PDF file [deprecated]

  • « PDF_open_pdi_page
  • PDF_open_tiff »
  • PHP Manual
  • PDF Functions
  • Open PDF file [deprecated]

PDF_open_pdi

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_open_pdi — Open PDF file [deprecated]

Description

PDF_open_pdi ( resource $pdfdoc , string $filename , string $optlist , int $len ) : int

Opens a disk-based or virtual PDF document and prepares it for later use.

This function is deprecated since PDFlib version 7, use PDF_open_pdi_document() instead.


Open TIFF image [deprecated]

  • « PDF_open_pdi
  • PDF_pcos_get_number »
  • PHP Manual
  • PDF Functions
  • Open TIFF image [deprecated]

PDF_open_tiff

(PHP 4, PECL pdflib >= 1.0.0)

PDF_open_tiff — Open TIFF image [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_load_image() instead.


Get value of pCOS path with type number or boolean

  • « PDF_open_tiff
  • PDF_pcos_get_stream »
  • PHP Manual
  • PDF Functions
  • Get value of pCOS path with type number or boolean

PDF_pcos_get_number

(PECL pdflib >= 2.1.0)

PDF_pcos_get_number — Get value of pCOS path with type number or boolean

Description

PDF_pcos_get_number ( resource $p , int $doc , string $path ) : float

Gets the value of a pCOS path with type number or boolean.


Get contents of pCOS path with type stream, fstream, or string

  • « PDF_pcos_get_number
  • PDF_pcos_get_string »
  • PHP Manual
  • PDF Functions
  • Get contents of pCOS path with type stream, fstream, or string

PDF_pcos_get_stream

(PECL pdflib >= 2.1.0)

PDF_pcos_get_stream — Get contents of pCOS path with type stream, fstream, or string

Description

PDF_pcos_get_stream ( resource $p , int $doc , string $optlist , string $path ) : string

Gets the contents of a pCOS path with type stream, fstream, or string.


Get value of pCOS path with type name, string, or boolean

  • « PDF_pcos_get_stream
  • PDF_place_image »
  • PHP Manual
  • PDF Functions
  • Get value of pCOS path with type name, string, or boolean

PDF_pcos_get_string

(PECL pdflib >= 2.1.0)

PDF_pcos_get_string — Get value of pCOS path with type name, string, or boolean

Description

PDF_pcos_get_string ( resource $p , int $doc , string $path ) : string

Gets the value of a pCOS path with type name, string, or boolean.


Place image on the page [deprecated]

  • « PDF_pcos_get_string
  • PDF_place_pdi_page »
  • PHP Manual
  • PDF Functions
  • Place image on the page [deprecated]

PDF_place_image

(PHP 4, PECL pdflib >= 1.0.0)

PDF_place_image — Place image on the page [deprecated]

Description

PDF_place_image ( resource $pdfdoc , int $image , float $x , float $y , float $scale ) : bool

Places an image and scales it. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 5, use PDF_fit_image() instead.


Place PDF page [deprecated]

  • « PDF_place_image
  • PDF_process_pdi »
  • PHP Manual
  • PDF Functions
  • Place PDF page [deprecated]

PDF_place_pdi_page

(PHP 4 >= 4.0.6, PECL pdflib >= 1.0.0)

PDF_place_pdi_page — Place PDF page [deprecated]

Description

PDF_place_pdi_page ( resource $pdfdoc , int $page , float $x , float $y , float $sx , float $sy ) : bool

Places a PDF page and scales it. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 5, use PDF_fit_pdi_page() instead.


Process imported PDF document

  • « PDF_place_pdi_page
  • PDF_rect »
  • PHP Manual
  • PDF Functions
  • Process imported PDF document

PDF_process_pdi

(PECL pdflib >= 2.0.0)

PDF_process_pdi — Process imported PDF document

Description

PDF_process_pdi ( resource $pdfdoc , int $doc , int $page , string $optlist ) : int

Processes certain elements of an imported PDF document.


Draw rectangle

  • « PDF_process_pdi
  • PDF_restore »
  • PHP Manual
  • PDF Functions
  • Draw rectangle

PDF_rect

(PHP 4, PECL pdflib >= 1.0.0)

PDF_rect — Draw rectangle

Description

PDF_rect ( resource $p , float $x , float $y , float $width , float $height ) : bool

Draws a rectangle. Returns TRUE on success or FALSE on failure.


Restore graphics state

  • « PDF_rect
  • PDF_resume_page »
  • PHP Manual
  • PDF Functions
  • Restore graphics state

PDF_restore

(PHP 4, PECL pdflib >= 1.0.0)

PDF_restore — Restore graphics state

Description

PDF_restore ( resource $p ) : bool

Restores the most recently saved graphics state. Returns TRUE on success or FALSE on failure.


Resume page

  • « PDF_restore
  • PDF_rotate »
  • PHP Manual
  • PDF Functions
  • Resume page

PDF_resume_page

(PECL pdflib >= 2.0.0)

PDF_resume_page — Resume page

Description

PDF_resume_page ( resource $pdfdoc , string $optlist ) : bool

Resumes a page to add more content to it.


Rotate coordinate system

  • « PDF_resume_page
  • PDF_save »
  • PHP Manual
  • PDF Functions
  • Rotate coordinate system

PDF_rotate

(PHP 4, PECL pdflib >= 1.0.0)

PDF_rotate — Rotate coordinate system

Description

PDF_rotate ( resource $p , float $phi ) : bool

Rotates the coordinate system. Returns TRUE on success or FALSE on failure.


Save graphics state

  • « PDF_rotate
  • PDF_scale »
  • PHP Manual
  • PDF Functions
  • Save graphics state

PDF_save

(PHP 4, PECL pdflib >= 1.0.0)

PDF_save — Save graphics state

Description

PDF_save ( resource $p ) : bool

Saves the current graphics state. Returns TRUE on success or FALSE on failure.


Scale coordinate system

  • « PDF_save
  • PDF_set_border_color »
  • PHP Manual
  • PDF Functions
  • Scale coordinate system

PDF_scale

(PHP 4, PECL pdflib >= 1.0.0)

PDF_scale — Scale coordinate system

Description

PDF_scale ( resource $p , float $sx , float $sy ) : bool

Scales the coordinate system. Returns TRUE on success or FALSE on failure.


Set border color of annotations [deprecated]

  • « PDF_scale
  • PDF_set_border_dash »
  • PHP Manual
  • PDF Functions
  • Set border color of annotations [deprecated]

PDF_set_border_color

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_border_color — Set border color of annotations [deprecated]

Description

PDF_set_border_color ( resource $p , float $red , float $green , float $blue ) : bool

Sets the border color for all kinds of annotations. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 6, use the option annotcolor in PDF_create_annotation() instead.


Set border dash style of annotations [deprecated]

  • « PDF_set_border_color
  • PDF_set_border_style »
  • PHP Manual
  • PDF Functions
  • Set border dash style of annotations [deprecated]

PDF_set_border_dash

(PHP 4 >= 4.0.1, PECL pdflib >= 1.0.0)

PDF_set_border_dash — Set border dash style of annotations [deprecated]

Description

PDF_set_border_dash ( resource $pdfdoc , float $black , float $white ) : bool

Sets the border dash style for all kinds of annotations. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 6, use the option dasharray in PDF_create_annotation() instead.


Set border style of annotations [deprecated]

  • « PDF_set_border_dash
  • PDF_set_char_spacing »
  • PHP Manual
  • PDF Functions
  • Set border style of annotations [deprecated]

PDF_set_border_style

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_border_style — Set border style of annotations [deprecated]

Description

PDF_set_border_style ( resource $pdfdoc , string $style , float $width ) : bool

Sets the border style for all kinds of annotations. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 6, use the options borderstyle and linewidth in PDF_create_annotation() instead.


Set character spacing [deprecated]

  • « PDF_set_border_style
  • PDF_set_duration »
  • PHP Manual
  • PDF Functions
  • Set character spacing [deprecated]

PDF_set_char_spacing

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_char_spacing — Set character spacing [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_value() with parameter charspacing instead.


Set duration between pages [deprecated]

  • « PDF_set_char_spacing
  • PDF_set_gstate »
  • PHP Manual
  • PDF Functions
  • Set duration between pages [deprecated]

PDF_set_duration

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_duration — Set duration between pages [deprecated]

Description

This function is deprecated since PDFlib version 3, use the duration option in PDF_begin_page_ext() or PDF_end_page_ext() instead.


Activate graphics state object

  • « PDF_set_duration
  • PDF_set_horiz_scaling »
  • PHP Manual
  • PDF Functions
  • Activate graphics state object

PDF_set_gstate

(PECL pdflib >= 2.0.0)

PDF_set_gstate — Activate graphics state object

Description

PDF_set_gstate ( resource $pdfdoc , int $gstate ) : bool

Activates a graphics state object.


Set horizontal text scaling [deprecated]

  • « PDF_set_gstate
  • PDF_set_info_author »
  • PHP Manual
  • PDF Functions
  • Set horizontal text scaling [deprecated]

PDF_set_horiz_scaling

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_horiz_scaling — Set horizontal text scaling [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_value() with parameter horizscaling instead.


Fill the author document info field [deprecated]

  • « PDF_set_horiz_scaling
  • PDF_set_info_creator »
  • PHP Manual
  • PDF Functions
  • Fill the author document info field [deprecated]

PDF_set_info_author

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_info_author — Fill the author document info field [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_info() instead.


Fill the creator document info field [deprecated]

  • « PDF_set_info_author
  • PDF_set_info_keywords »
  • PHP Manual
  • PDF Functions
  • Fill the creator document info field [deprecated]

PDF_set_info_creator

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_info_creator — Fill the creator document info field [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_info() instead.


Fill the keywords document info field [deprecated]

  • « PDF_set_info_creator
  • PDF_set_info_subject »
  • PHP Manual
  • PDF Functions
  • Fill the keywords document info field [deprecated]

PDF_set_info_keywords

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_info_keywords — Fill the keywords document info field [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_info() instead.


Fill the subject document info field [deprecated]

  • « PDF_set_info_keywords
  • PDF_set_info_title »
  • PHP Manual
  • PDF Functions
  • Fill the subject document info field [deprecated]

PDF_set_info_subject

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_info_subject — Fill the subject document info field [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_info() instead.


Fill the title document info field [deprecated]

  • « PDF_set_info_subject
  • PDF_set_info »
  • PHP Manual
  • PDF Functions
  • Fill the title document info field [deprecated]

PDF_set_info_title

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_info_title — Fill the title document info field [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_info() instead.


Fill document info field

  • « PDF_set_info_title
  • PDF_set_layer_dependency »
  • PHP Manual
  • PDF Functions
  • Fill document info field

PDF_set_info

(PHP 4 >= 4.0.1, PECL pdflib >= 1.0.0)

PDF_set_info — Fill document info field

Description

PDF_set_info ( resource $p , string $key , string $value ) : bool

Fill document information field key with value. Returns TRUE on success or FALSE on failure.


Define relationships among layers

  • « PDF_set_info
  • PDF_set_leading »
  • PHP Manual
  • PDF Functions
  • Define relationships among layers

PDF_set_layer_dependency

(PECL pdflib >= 2.0.0)

PDF_set_layer_dependency — Define relationships among layers

Description

PDF_set_layer_dependency ( resource $pdfdoc , string $type , string $optlist ) : bool

Defines hierarchical and group relationships among layers. Returns TRUE on success or FALSE on failure.

This function requires PDF 1.5.


Set distance between text lines [deprecated]

  • « PDF_set_layer_dependency
  • PDF_set_parameter »
  • PHP Manual
  • PDF Functions
  • Set distance between text lines [deprecated]

PDF_set_leading

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_leading — Set distance between text lines [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_value() with the parameter leading instead.


Set string parameter

  • « PDF_set_leading
  • PDF_set_text_matrix »
  • PHP Manual
  • PDF Functions
  • Set string parameter

PDF_set_parameter

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_parameter — Set string parameter

Description

PDF_set_parameter ( resource $p , string $key , string $value ) : bool

Sets some PDFlib parameter with string type. Returns TRUE on success or FALSE on failure.


Set text matrix [deprecated]

  • « PDF_set_parameter
  • PDF_set_text_pos »
  • PHP Manual
  • PDF Functions
  • Set text matrix [deprecated]

PDF_set_text_matrix

(PHP 4 <= 4.0.4)

PDF_set_text_matrix — Set text matrix [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_scale(), PDF_translate(), PDF_rotate(), or PDF_skew() instead.


Set text position

  • « PDF_set_text_matrix
  • PDF_set_text_rendering »
  • PHP Manual
  • PDF Functions
  • Set text position

PDF_set_text_pos

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_text_pos — Set text position

Description

PDF_set_text_pos ( resource $p , float $x , float $y ) : bool

Sets the position for text output on the page. Returns TRUE on success or FALSE on failure.


Determine text rendering [deprecated]

  • « PDF_set_text_pos
  • PDF_set_text_rise »
  • PHP Manual
  • PDF Functions
  • Determine text rendering [deprecated]

PDF_set_text_rendering

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_text_rendering — Determine text rendering [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_value() with the textrendering parameter instead.


Set text rise [deprecated]

  • « PDF_set_text_rendering
  • PDF_set_value »
  • PHP Manual
  • PDF Functions
  • Set text rise [deprecated]

PDF_set_text_rise

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_text_rise — Set text rise [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_value() with the textrise parameter instead.


Set numerical parameter

  • « PDF_set_text_rise
  • PDF_set_word_spacing »
  • PHP Manual
  • PDF Functions
  • Set numerical parameter

PDF_set_value

(PHP 4 >= 4.0.1, PECL pdflib >= 1.0.0)

PDF_set_value — Set numerical parameter

Description

PDF_set_value ( resource $p , string $key , float $value ) : bool

Sets the value of some PDFlib parameter with numerical type. Returns TRUE on success or FALSE on failure.


Set spacing between words [deprecated]

  • « PDF_set_value
  • PDF_setcolor »
  • PHP Manual
  • PDF Functions
  • Set spacing between words [deprecated]

PDF_set_word_spacing

(PHP 4, PECL pdflib >= 1.0.0)

PDF_set_word_spacing — Set spacing between words [deprecated]

Description

This function is deprecated since PDFlib version 3, use PDF_set_value() with the wordspacing parameter instead.


Set fill and stroke color

  • « PDF_set_word_spacing
  • PDF_setdash »
  • PHP Manual
  • PDF Functions
  • Set fill and stroke color

PDF_setcolor

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_setcolor — Set fill and stroke color

Description

PDF_setcolor ( resource $p , string $fstype , string $colorspace , float $c1 , float $c2 , float $c3 , float $c4 ) : bool

Sets the current color space and color. Returns TRUE on success or FALSE on failure.


Set simple dash pattern

  • « PDF_setcolor
  • PDF_setdashpattern »
  • PHP Manual
  • PDF Functions
  • Set simple dash pattern

PDF_setdash

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setdash — Set simple dash pattern

Description

PDF_setdash ( resource $pdfdoc , float $b , float $w ) : bool

Sets the current dash pattern to b black and w white units. Returns TRUE on success or FALSE on failure.


Set dash pattern

  • « PDF_setdash
  • PDF_setflat »
  • PHP Manual
  • PDF Functions
  • Set dash pattern

PDF_setdashpattern

(PECL pdflib >= 2.0.0)

PDF_setdashpattern — Set dash pattern

Description

PDF_setdashpattern ( resource $pdfdoc , string $optlist ) : bool

Sets a dash pattern defined by an option list. Returns TRUE on success or FALSE on failure.


Set flatness

  • « PDF_setdashpattern
  • PDF_setfont »
  • PHP Manual
  • PDF Functions
  • Set flatness

PDF_setflat

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setflat — Set flatness

Description

PDF_setflat ( resource $pdfdoc , float $flatness ) : bool

Sets the flatness parameter. Returns TRUE on success or FALSE on failure.


Set font

  • « PDF_setflat
  • PDF_setgray_fill »
  • PHP Manual
  • PDF Functions
  • Set font

PDF_setfont

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_setfont — Set font

Description

PDF_setfont ( resource $pdfdoc , int $font , float $fontsize ) : bool

Sets the current font in the specified fontsize, using a font handle returned by PDF_load_font(). Returns TRUE on success or FALSE on failure.


Set fill color to gray [deprecated]

  • « PDF_setfont
  • PDF_setgray_stroke »
  • PHP Manual
  • PDF Functions
  • Set fill color to gray [deprecated]

PDF_setgray_fill

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setgray_fill — Set fill color to gray [deprecated]

Description

PDF_setgray_fill ( resource $p , float $g ) : bool

Sets the current fill color to a gray value between 0 and 1 inclusive. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 4, use PDF_setcolor() instead.


Set stroke color to gray [deprecated]

  • « PDF_setgray_fill
  • PDF_setgray »
  • PHP Manual
  • PDF Functions
  • Set stroke color to gray [deprecated]

PDF_setgray_stroke

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setgray_stroke — Set stroke color to gray [deprecated]

Description

PDF_setgray_stroke ( resource $p , float $g ) : bool

Sets the current stroke color to a gray value between 0 and 1 inclusive. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 4, use PDF_setcolor() instead.


Set color to gray [deprecated]

  • « PDF_setgray_stroke
  • PDF_setlinecap »
  • PHP Manual
  • PDF Functions
  • Set color to gray [deprecated]

PDF_setgray

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setgray — Set color to gray [deprecated]

Description

PDF_setgray ( resource $p , float $g ) : bool

Sets the current fill and stroke color to a gray value between 0 and 1 inclusive. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 4, use PDF_setcolor() instead.


Set linecap parameter

  • « PDF_setgray
  • PDF_setlinejoin »
  • PHP Manual
  • PDF Functions
  • Set linecap parameter

PDF_setlinecap

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setlinecap — Set linecap parameter

Description

PDF_setlinecap ( resource $p , int $linecap ) : bool

Sets the linecap parameter to control the shape at the end of a path with respect to stroking.


Set linejoin parameter

  • « PDF_setlinecap
  • PDF_setlinewidth »
  • PHP Manual
  • PDF Functions
  • Set linejoin parameter

PDF_setlinejoin

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setlinejoin — Set linejoin parameter

Description

PDF_setlinejoin ( resource $p , int $value ) : bool

Sets the linejoin parameter to specify the shape at the corners of paths that are stroked. Returns TRUE on success or FALSE on failure.


Set line width

  • « PDF_setlinejoin
  • PDF_setmatrix »
  • PHP Manual
  • PDF Functions
  • Set line width

PDF_setlinewidth

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setlinewidth — Set line width

Description

PDF_setlinewidth ( resource $p , float $width ) : bool

Sets the current line width. Returns TRUE on success or FALSE on failure.


Set current transformation matrix

  • « PDF_setlinewidth
  • PDF_setmiterlimit »
  • PHP Manual
  • PDF Functions
  • Set current transformation matrix

PDF_setmatrix

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_setmatrix — Set current transformation matrix

Description

PDF_setmatrix ( resource $p , float $a , float $b , float $c , float $d , float $e , float $f ) : bool

Explicitly sets the current transformation matrix. Returns TRUE on success or FALSE on failure.


Set miter limit

  • « PDF_setmatrix
  • PDF_setpolydash »
  • PHP Manual
  • PDF Functions
  • Set miter limit

PDF_setmiterlimit

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setmiterlimit — Set miter limit

Description

PDF_setmiterlimit ( resource $pdfdoc , float $miter ) : bool

Sets the miter limit.Returns TRUE on success or FALSE on failure.


Set complicated dash pattern [deprecated]

  • « PDF_setmiterlimit
  • PDF_setrgbcolor_fill »
  • PHP Manual
  • PDF Functions
  • Set complicated dash pattern [deprecated]

PDF_setpolydash

(PHP 4 >= 4.0.5, PECL pdflib >= 1.0.0)

PDF_setpolydash — Set complicated dash pattern [deprecated]

Description

This function is deprecated since PDFlib version 5, use PDF_setdashpattern() instead.


Set fill rgb color values [deprecated]

  • « PDF_setpolydash
  • PDF_setrgbcolor_stroke »
  • PHP Manual
  • PDF Functions
  • Set fill rgb color values [deprecated]

PDF_setrgbcolor_fill

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setrgbcolor_fill — Set fill rgb color values [deprecated]

Description

PDF_setrgbcolor_fill ( resource $p , float $red , float $green , float $blue ) : bool

Sets the current fill color to the supplied RGB values. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 4, use PDF_setcolor() instead.


Set stroke rgb color values [deprecated]

  • « PDF_setrgbcolor_fill
  • PDF_setrgbcolor »
  • PHP Manual
  • PDF Functions
  • Set stroke rgb color values [deprecated]

PDF_setrgbcolor_stroke

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setrgbcolor_stroke — Set stroke rgb color values [deprecated]

Description

PDF_setrgbcolor_stroke ( resource $p , float $red , float $green , float $blue ) : bool

Sets the current stroke color to the supplied RGB values. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 4, use PDF_setcolor() instead.


Set fill and stroke rgb color values [deprecated]

  • « PDF_setrgbcolor_stroke
  • PDF_shading_pattern »
  • PHP Manual
  • PDF Functions
  • Set fill and stroke rgb color values [deprecated]

PDF_setrgbcolor

(PHP 4, PECL pdflib >= 1.0.0)

PDF_setrgbcolor — Set fill and stroke rgb color values [deprecated]

Description

PDF_setrgbcolor ( resource $p , float $red , float $green , float $blue ) : bool

Sets the current fill and stroke color to the supplied RGB values. Returns TRUE on success or FALSE on failure.

This function is deprecated since PDFlib version 4, use PDF_setcolor() instead.


Define shading pattern

  • « PDF_setrgbcolor
  • PDF_shading »
  • PHP Manual
  • PDF Functions
  • Define shading pattern

PDF_shading_pattern

(PECL pdflib >= 2.0.0)

PDF_shading_pattern — Define shading pattern

Description

PDF_shading_pattern ( resource $pdfdoc , int $shading , string $optlist ) : int

Defines a shading pattern using a shading object.

This function requires PDF 1.4 or above.


Define blend

  • « PDF_shading_pattern
  • PDF_shfill »
  • PHP Manual
  • PDF Functions
  • Define blend

PDF_shading

(PECL pdflib >= 2.0.0)

PDF_shading — Define blend

Description

PDF_shading ( resource $pdfdoc , string $shtype , float $x0 , float $y0 , float $x1 , float $y1 , float $c1 , float $c2 , float $c3 , float $c4 , string $optlist ) : int

Defines a blend from the current fill color to another color.

This function requires PDF 1.4 or above.


Fill area with shading

  • « PDF_shading
  • PDF_show_boxed »
  • PHP Manual
  • PDF Functions
  • Fill area with shading

PDF_shfill

(PECL pdflib >= 2.0.0)

PDF_shfill — Fill area with shading

Description

PDF_shfill ( resource $pdfdoc , int $shading ) : bool

Fills an area with a shading, based on a shading object.

This function requires PDF 1.4 or above.


Output text in a box [deprecated]

  • « PDF_shfill
  • PDF_show_xy »
  • PHP Manual
  • PDF Functions
  • Output text in a box [deprecated]

PDF_show_boxed

(PHP 4, PECL pdflib >= 1.0.0)

PDF_show_boxed — Output text in a box [deprecated]

Description

PDF_show_boxed ( resource $p , string $text , float $left , float $top , float $width , float $height , string $mode , string $feature ) : int

This function is deprecated since PDFlib version 6, use PDF_fit_textline() for single lines, or the PDF_*_textflow() functions for multi-line formatting instead.


Output text at given position

  • « PDF_show_boxed
  • PDF_show »
  • PHP Manual
  • PDF Functions
  • Output text at given position

PDF_show_xy

(PHP 4, PECL pdflib >= 1.0.0)

PDF_show_xy — Output text at given position

Description

PDF_show_xy ( resource $p , string $text , float $x , float $y ) : bool

Prints text in the current font. Returns TRUE on success or FALSE on failure.


Output text at current position

  • « PDF_show_xy
  • PDF_skew »
  • PHP Manual
  • PDF Functions
  • Output text at current position

PDF_show

(PHP 4, PECL pdflib >= 1.0.0)

PDF_show — Output text at current position

Description

PDF_show ( resource $pdfdoc , string $text ) : bool

Prints text in the current font and size at the current position. Returns TRUE on success or FALSE on failure.


Skew the coordinate system

  • « PDF_show
  • PDF_stringwidth »
  • PHP Manual
  • PDF Functions
  • Skew the coordinate system

PDF_skew

(PHP 4, PECL pdflib >= 1.0.0)

PDF_skew — Skew the coordinate system

Description

PDF_skew ( resource $p , float $alpha , float $beta ) : bool

Skews the coordinate system in x and y direction by alpha and beta degrees, respectively. Returns TRUE on success or FALSE on failure.


Return width of text

  • « PDF_skew
  • PDF_stroke »
  • PHP Manual
  • PDF Functions
  • Return width of text

PDF_stringwidth

(PHP 4, PECL pdflib >= 1.0.0)

PDF_stringwidth — Return width of text

Description

PDF_stringwidth ( resource $p , string $text , int $font , float $fontsize ) : float

Returns the width of text in an arbitrary font.


Stroke path

  • « PDF_stringwidth
  • PDF_suspend_page »
  • PHP Manual
  • PDF Functions
  • Stroke path

PDF_stroke

(PHP 4, PECL pdflib >= 1.0.0)

PDF_stroke — Stroke path

Description

PDF_stroke ( resource $p ) : bool

Strokes the path with the current color and line width, and clear it. Returns TRUE on success or FALSE on failure.


Suspend page

  • « PDF_stroke
  • PDF_translate »
  • PHP Manual
  • PDF Functions
  • Suspend page

PDF_suspend_page

(PECL pdflib >= 2.0.0)

PDF_suspend_page — Suspend page

Description

PDF_suspend_page ( resource $pdfdoc , string $optlist ) : bool

Suspends the current page so that it can later be resumed with PDF_resume_page().


Set origin of coordinate system

  • « PDF_suspend_page
  • PDF_utf16_to_utf8 »
  • PHP Manual
  • PDF Functions
  • Set origin of coordinate system

PDF_translate

(PHP 4, PECL pdflib >= 1.0.0)

PDF_translate — Set origin of coordinate system

Description

PDF_translate ( resource $p , float $tx , float $ty ) : bool

Translates the origin of the coordinate system.


Convert string from UTF-16 to UTF-8

  • « PDF_translate
  • PDF_utf32_to_utf16 »
  • PHP Manual
  • PDF Functions
  • Convert string from UTF-16 to UTF-8

PDF_utf16_to_utf8

(PECL pdflib >= 2.0.3)

PDF_utf16_to_utf8 — Convert string from UTF-16 to UTF-8

Description

PDF_utf16_to_utf8 ( resource $pdfdoc , string $utf16string ) : string

Converts a string from UTF-16 format to UTF-8.


Convert string from UTF-32 to UTF-16

  • « PDF_utf16_to_utf8
  • PDF_utf8_to_utf16 »
  • PHP Manual
  • PDF Functions
  • Convert string from UTF-32 to UTF-16

PDF_utf32_to_utf16

(PECL pdflib >= Unknown future)

PDF_utf32_to_utf16 — Convert string from UTF-32 to UTF-16

Description

PDF_utf32_to_utf16 ( resource $pdfdoc , string $utf32string , string $ordering ) : string

Converts a string from UTF-32 format to UTF-16.


Convert string from UTF-8 to UTF-16

  • « PDF_utf32_to_utf16
  • wkhtmltox »
  • PHP Manual
  • PDF Functions
  • Convert string from UTF-8 to UTF-16

PDF_utf8_to_utf16

(PECL pdflib >= 2.0.3)

PDF_utf8_to_utf16 — Convert string from UTF-8 to UTF-16

Description

PDF_utf8_to_utf16 ( resource $pdfdoc , string $utf8string , string $ordering ) : string

Converts a string from UTF-8 format to UTF-16.


wkhtmltox

  • Introduction
  • 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


Introduction

libwkhtmltox is an open source LGPLv3 library for rendering HTML into PDF and various image formats using the QtWebKit rendering engine.


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

Name | Description | Default | Stage | Changelog
wkhtmltox.graphics | allow libwkhtmltox to use graphics | Off | PHP_INI_SYSTEM | PHP_INI_PERDIR | >= 0.3.2


The wkhtmltox\PDF\Converter class

(wkhtmltox >= 0.1.0)

Introduction

Converts an HTML input, or set of HTML inputs, into PDF output

Class synopsis

wkhtmltox\PDF\Converter {
/* Constructor */
public __construct ([ array $settings ] )
/* Methods */
public add ( wkhtmltox\PDF\Object $object ) : void
public convert ( void ) : ?string
public getVersion ( void ) : 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


Add an object for conversion

  • « wkhtmltox\PDF\Converter
  • wkhtmltox\PDF\Converter::__construct »
  • PHP Manual
  • wkhtmltox\PDF\Converter
  • Add an object for conversion

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


Create a new PDF converter

  • « wkhtmltox\PDF\Converter::add
  • wkhtmltox\PDF\Converter::convert »
  • PHP Manual
  • wkhtmltox\PDF\Converter
  • Create a new PDF converter

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 | resoluition 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


Perform PDF conversion

  • « wkhtmltox\PDF\Converter::__construct
  • wkhtmltox\PDF\Converter::getVersion »
  • PHP Manual
  • wkhtmltox\PDF\Converter
  • Perform PDF conversion

wkhtmltox\PDF\Converter::convert

(wkhtmltox >= 0.1.0)

wkhtmltox\PDF\Converter::convert — Perform PDF conversion

Description

public wkhtmltox\PDF\Converter::convert ( void ) : ?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


Determine version of Converter

  • « wkhtmltox\PDF\Converter::convert
  • wkhtmltox\PDF\Object »
  • PHP Manual
  • wkhtmltox\PDF\Converter
  • Determine version of Converter

wkhtmltox\PDF\Converter::getVersion

(wkhtmltox >= 0.3.2)

wkhtmltox\PDF\Converter::getVersion — Determine version of Converter

Description

public wkhtmltox\PDF\Converter::getVersion ( void ) : string

Determines the version of Converter as reported by libwkhtmltox

Parameters

This function has no parameters.

Return Values

Returns a version string


The wkhtmltox\PDF\Object class

(wkhtmltox >= 0.1.0)

Introduction

Represents an HTML document, input to PDF converter

Class synopsis

wkhtmltox\PDF\Object {
/* Constructor */
public __construct ( string $buffer [, array $settings ] )
}

Table of Contents

  • wkhtmltox\PDF\Object::__construct — Create a new PDF Object


Create a new PDF Object

  • « wkhtmltox\PDF\Object
  • wkhtmltox\Image\Converter »
  • PHP Manual
  • wkhtmltox\PDF\Object
  • Create a new PDF Object

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


The wkhtmltox\Image\Converter class

(wkhtmltox >= 0.1.0)

Introduction

Converts an HTML input into various image formats

Class synopsis

wkhtmltox\Image\Converter {
/* Constructor */
public __construct ([ string $buffer [, array $settings ]] )
/* Methods */
public convert ( void ) : ?string
public getVersion ( void ) : string
}

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


Create a new Image converter

  • « wkhtmltox\Image\Converter
  • wkhtmltox\Image\Converter::convert »
  • PHP Manual
  • wkhtmltox\Image\Converter
  • Create a new Image converter

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


Perform Image conversion

  • « wkhtmltox\Image\Converter::__construct
  • wkhtmltox\Image\Converter::getVersion »
  • PHP Manual
  • wkhtmltox\Image\Converter
  • Perform Image conversion

wkhtmltox\Image\Converter::convert

(wkhtmltox >= 0.1.0)

wkhtmltox\Image\Converter::convert — Perform Image conversion

Description

public wkhtmltox\Image\Converter::convert ( void ) : ?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


Determine version of Converter

  • « wkhtmltox\Image\Converter::convert
  • PS »
  • PHP Manual
  • wkhtmltox\Image\Converter
  • Determine version of Converter

wkhtmltox\Image\Converter::getVersion

(wkhtmltox >= 0.3.2)

wkhtmltox\Image\Converter::getVersion — Determine version of Converter

Description

public wkhtmltox\Image\Converter::getVersion ( void ) : 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


PostScript document creation

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • 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_image — Closes image and frees memory
    • ps_close — Closes a PostScript document
    • ps_closepath_stroke — Closes and strokes path
    • ps_closepath — Closes 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_stroke — Fills and strokes the current path
    • ps_fill — Fills 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_file — Opens image from file
    • ps_open_image — Reads an image for later placement
    • 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_pattern — Creates a pattern based on a shading
    • ps_shading — Creates a shading for later use
    • ps_shfill — Fills an area with a shading
    • ps_show_boxed — Output text in a box
    • ps_show_xy2 — Output text at position
    • ps_show_xy — Output text at given position
    • ps_show2 — Output a text at current position
    • ps_show — Output text
    • ps_string_geometry — Gets geometry of a string
    • ps_stringwidth — Gets width of a string
    • ps_stroke — Draws the current path
    • ps_symbol_name — Gets name of a glyph
    • ps_symbol_width — Gets width of a glyph
    • ps_symbol — Output a glyph
    • ps_translate — Sets translation


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.


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.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.


  • « Runtime Configuration
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

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.

Contants for line caps
Name | Meaning
ps_LINECAP_BUTT |
ps_LINECAP_ROUND |
ps_LINECAP_SQUARED |
Contants 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.

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_image — Closes image and frees memory
  • ps_close — Closes a PostScript document
  • ps_closepath_stroke — Closes and strokes path
  • ps_closepath — Closes 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_stroke — Fills and strokes the current path
  • ps_fill — Fills 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_file — Opens image from file
  • ps_open_image — Reads an image for later placement
  • 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_pattern — Creates a pattern based on a shading
  • ps_shading — Creates a shading for later use
  • ps_shfill — Fills an area with a shading
  • ps_show_boxed — Output text in a box
  • ps_show_xy2 — Output text at position
  • ps_show_xy — Output text at given position
  • ps_show2 — Output a text at current position
  • ps_show — Output text
  • ps_string_geometry — Gets geometry of a string
  • ps_stringwidth — Gets width of a string
  • ps_stroke — Draws the current path
  • ps_symbol_name — Gets name of a glyph
  • ps_symbol_width — Gets width of a glyph
  • ps_symbol — Output a glyph
  • ps_translate — Sets translation


Add bookmark to current page

  • « PS Functions
  • ps_add_launchlink »
  • PHP Manual
  • PS Functions
  • Add bookmark to current page

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


Adds link which launches file

  • « ps_add_bookmark
  • ps_add_locallink »
  • PHP Manual
  • PS Functions
  • Adds link which launches file

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


Adds link to a page in the same document

  • « ps_add_launchlink
  • ps_add_note »
  • PHP Manual
  • PS Functions
  • Adds link to a page in the same document

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


Adds note to current page

  • « ps_add_locallink
  • ps_add_pdflink »
  • PHP Manual
  • PS Functions
  • Adds note to current page

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


Adds link to a page in a second pdf document

  • « ps_add_note
  • ps_add_weblink »
  • PHP Manual
  • PS Functions
  • Adds link to a page in a second pdf document

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


Adds link to a web location

  • « ps_add_pdflink
  • ps_arc »
  • PHP Manual
  • PS Functions
  • 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


Draws an arc counterclockwise

  • « ps_add_weblink
  • ps_arcn »
  • PHP Manual
  • PS Functions
  • Draws an arc counterclockwise

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


Draws an arc clockwise

  • « ps_arc
  • ps_begin_page »
  • PHP Manual
  • PS Functions
  • 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


Start a new page

  • « ps_arcn
  • ps_begin_pattern »
  • PHP Manual
  • PS Functions
  • Start a new page

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


Start a new pattern

  • « ps_begin_page
  • ps_begin_template »
  • PHP Manual
  • PS Functions
  • Start a new pattern

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

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.

x-step

The distance in pixel of placements of the pattern in horizontal direction.

y-step

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


Start a new template

  • « ps_begin_pattern
  • ps_circle »
  • PHP Manual
  • PS Functions
  • Start a new template

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


Draws a circle

  • « ps_begin_template
  • ps_clip »
  • PHP Manual
  • PS Functions
  • Draws a circle

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


Clips drawing to current path

  • « ps_circle
  • ps_close_image »
  • PHP Manual
  • PS Functions
  • Clips drawing to current path

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


Closes image and frees memory

  • « ps_clip
  • ps_close »
  • PHP Manual
  • PS Functions
  • Closes image and frees memory

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

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


Closes a PostScript document

  • « ps_close_image
  • ps_closepath_stroke »
  • PHP Manual
  • PS Functions
  • Closes a PostScript document

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


Closes and strokes path

  • « ps_close
  • ps_closepath »
  • PHP Manual
  • PS Functions
  • 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


Closes path

  • « ps_closepath_stroke
  • ps_continue_text »
  • PHP Manual
  • PS Functions
  • Closes path

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


Continue text in next line

  • « ps_closepath
  • ps_curveto »
  • PHP Manual
  • PS Functions
  • Continue text in next line

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


Draws a curve

  • « ps_continue_text
  • ps_delete »
  • PHP Manual
  • PS Functions
  • Draws a curve

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


Deletes all resources of a PostScript document

  • « ps_curveto
  • ps_end_page »
  • PHP Manual
  • PS Functions
  • Deletes all resources of a PostScript document

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


End a page

  • « ps_delete
  • ps_end_pattern »
  • PHP Manual
  • PS Functions
  • End a page

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


End a pattern

  • « ps_end_page
  • ps_end_template »
  • PHP Manual
  • PS Functions
  • End a pattern

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


End a template

  • « ps_end_pattern
  • ps_fill_stroke »
  • PHP Manual
  • PS Functions
  • End a template

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


Fills and strokes the current path

  • « ps_end_template
  • ps_fill »
  • PHP Manual
  • PS Functions
  • Fills and strokes 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


Fills the current path

  • « ps_fill_stroke
  • ps_findfont »
  • PHP Manual
  • PS Functions
  • Fills the current path

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


Loads a font

  • « ps_fill
  • ps_get_buffer »
  • PHP Manual
  • PS Functions
  • Loads a font

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


Fetches the full buffer containig the generated PS data

  • « ps_findfont
  • ps_get_parameter »
  • PHP Manual
  • PS Functions
  • Fetches the full buffer containig the generated PS data

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


Gets certain parameters

  • « ps_get_buffer
  • ps_get_value »
  • PHP Manual
  • PS Functions
  • Gets certain parameters

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

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


Gets certain values

  • « ps_get_parameter
  • ps_hyphenate »
  • PHP Manual
  • PS Functions
  • Gets certain values

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


Hyphenates a word

  • « ps_get_value
  • ps_include_file »
  • PHP Manual
  • PS Functions
  • Hyphenates a word

ps_hyphenate

(PECL ps >= 1.1.1)

ps_hyphenate — Hyphenates a word

Description

ps_hyphenate ( resource $psdoc , string $text ) : array

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)


Reads an external file with raw PostScript code

  • « ps_hyphenate
  • ps_lineto »
  • PHP Manual
  • PS Functions
  • Reads an external file with raw PostScript code

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

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().

file

Return Values

Returns TRUE on success or FALSE on failure.


Draws a line

  • « ps_include_file
  • ps_makespotcolor »
  • PHP Manual
  • PS Functions
  • Draws a line

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


Create spot color

  • « ps_lineto
  • ps_moveto »
  • PHP Manual
  • PS Functions
  • Create spot color

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


Sets current point

  • « ps_makespotcolor
  • ps_new »
  • PHP Manual
  • PS Functions
  • Sets current point

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


Creates a new PostScript document object

  • « ps_moveto
  • ps_open_file »
  • PHP Manual
  • PS Functions
  • Creates a new PostScript document object

ps_new

(PECL ps >= 1.1.0)

ps_new — Creates a new PostScript document object

Description

ps_new ( void ) : resource

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.

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


Opens a file for output

  • « ps_new
  • ps_open_image_file »
  • PHP Manual
  • PS Functions
  • Opens a file for output

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


Opens image from file

  • « ps_open_file
  • ps_open_image »
  • PHP Manual
  • PS Functions
  • Opens image from file

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


Reads an image for later placement

  • « ps_open_image_file
  • ps_open_memory_image »
  • PHP Manual
  • PS Functions
  • Reads an image for later placement

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 $lenght , 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


Takes an GD image and returns an image for placement in a PS document

  • « ps_open_image
  • ps_place_image »
  • PHP Manual
  • PS Functions
  • Takes an GD image and returns an image for placement in a PS document

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


Places image on the page

  • « ps_open_memory_image
  • ps_rect »
  • PHP Manual
  • PS Functions
  • Places image on the page

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


Draws a rectangle

  • « ps_place_image
  • ps_restore »
  • PHP Manual
  • PS Functions
  • Draws a rectangle

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


Restore previously save context

  • « ps_rect
  • ps_rotate »
  • PHP Manual
  • PS Functions
  • Restore previously save context

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


Sets rotation factor

  • « ps_restore
  • ps_save »
  • PHP Manual
  • PS Functions
  • Sets rotation factor

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


Save current context

  • « ps_rotate
  • ps_scale »
  • PHP Manual
  • PS Functions
  • Save current context

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


Sets scaling factor

  • « ps_save
  • ps_set_border_color »
  • PHP Manual
  • PS Functions
  • Sets scaling factor

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


Sets color of border for annotations

  • « ps_scale
  • ps_set_border_dash »
  • PHP Manual
  • PS Functions
  • Sets color of border for annotations

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


Sets length of dashes for border of annotations

  • « ps_set_border_color
  • ps_set_border_style »
  • PHP Manual
  • PS Functions
  • Sets length of dashes for border 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


Sets border style of annotations

  • « ps_set_border_dash
  • ps_set_info »
  • PHP Manual
  • PS Functions
  • 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


Sets information fields of document

  • « ps_set_border_style
  • ps_set_parameter »
  • PHP Manual
  • PS Functions
  • Sets information fields of document

ps_set_info

(PECL ps >= 1.1.0)

ps_set_info — Sets information fields of document

Description

ps_set_info ( resource $p , string $key , string $val ) : 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


Sets certain parameters

  • « ps_set_info
  • ps_set_text_pos »
  • PHP Manual
  • PS Functions
  • Sets certain parameters

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


Sets position for text output

  • « ps_set_parameter
  • ps_set_value »
  • PHP Manual
  • PS Functions
  • Sets position for text output

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


Sets certain values

  • « ps_set_text_pos
  • ps_setcolor »
  • PHP Manual
  • PS Functions
  • Sets certain values

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


Sets current color

  • « ps_set_value
  • ps_setdash »
  • PHP Manual
  • PS Functions
  • Sets current color

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.

Bugs

The second parameter is currently not always evaluated. The color is sometimes set for filling and drawing just as if fillstroke were passed.

Return Values

Returns TRUE on success or FALSE on failure.


Sets appearance of a dashed line

  • « ps_setcolor
  • ps_setflat »
  • PHP Manual
  • PS Functions
  • Sets appearance of a dashed line

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


Sets flatness

  • « ps_setdash
  • ps_setfont »
  • PHP Manual
  • PS Functions
  • Sets flatness

ps_setflat

(PECL ps >= 1.1.0)

ps_setflat — Sets flatness

Description

ps_setflat ( resource $psdoc , float $value ) : bool

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().

value

The value must be between 0.2 and 1.

Return Values

Returns TRUE on success or FALSE on failure.


Sets font to use for following output

  • « ps_setflat
  • ps_setgray »
  • PHP Manual
  • PS Functions
  • Sets font to use for following output

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.


Sets gray value

  • « ps_setfont
  • ps_setlinecap »
  • PHP Manual
  • PS Functions
  • Sets gray value

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


Sets appearance of line ends

  • « ps_setgray
  • ps_setlinejoin »
  • PHP Manual
  • PS Functions
  • Sets appearance of line ends

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


Sets how contected lines are joined

  • « ps_setlinecap
  • ps_setlinewidth »
  • PHP Manual
  • PS Functions
  • Sets how contected lines are joined

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


Sets width of a line

  • « ps_setlinejoin
  • ps_setmiterlimit »
  • PHP Manual
  • PS Functions
  • Sets width of a line

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


Sets the miter limit

  • « ps_setlinewidth
  • ps_setoverprintmode »
  • PHP Manual
  • PS Functions
  • 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


Sets overprint mode

  • « ps_setmiterlimit
  • ps_setpolydash »
  • PHP Manual
  • PS Functions
  • Sets overprint mode

ps_setoverprintmode

(PECL ps >= 1.3.0)

ps_setoverprintmode — Sets overprint mode

Description

ps_setoverprintmode ( resource $psdoc , int $mode ) : bool

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().

mode

Return Values

Returns TRUE on success or FALSE on failure.


Sets appearance of a dashed line

  • « ps_setoverprintmode
  • ps_shading_pattern »
  • PHP Manual
  • PS Functions
  • Sets appearance of a dashed line

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


Creates a pattern based on a shading

  • « ps_setpolydash
  • ps_shading »
  • PHP Manual
  • PS Functions
  • Creates a pattern based on 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

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


Creates a shading for later use

  • « ps_shading_pattern
  • ps_shfill »
  • PHP Manual
  • PS Functions
  • Creates a shading for later use

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

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


Fills an area with a shading

  • « ps_shading
  • ps_show_boxed »
  • PHP Manual
  • PS Functions
  • 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


Output text in a box

  • « ps_shfill
  • ps_show_xy2 »
  • PHP Manual
  • PS Functions
  • Output text in a box

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


Output text at position

  • « ps_show_boxed
  • ps_show_xy »
  • PHP Manual
  • PS Functions
  • Output text at position

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.


Output text at given position

  • « ps_show_xy2
  • ps_show2 »
  • PHP Manual
  • PS Functions
  • Output text at given position

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


Output a text at current position

  • « ps_show_xy
  • ps_show »
  • PHP Manual
  • PS Functions
  • Output a text at current position

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.


Output text

  • « ps_show2
  • ps_string_geometry »
  • PHP Manual
  • PS Functions
  • Output text

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


Gets geometry of a string

  • « ps_show
  • ps_stringwidth »
  • PHP Manual
  • PS Functions
  • Gets geometry of a string

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


Gets width of a string

  • « ps_string_geometry
  • ps_stroke »
  • PHP Manual
  • PS Functions
  • 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


Draws the current path

  • « ps_stringwidth
  • ps_symbol_name »
  • PHP Manual
  • PS Functions
  • Draws the current path

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


Gets name of a glyph

  • « ps_stroke
  • ps_symbol_width »
  • PHP Manual
  • PS Functions
  • Gets name 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


Gets width of a glyph

  • « ps_symbol_name
  • ps_symbol »
  • PHP Manual
  • PS Functions
  • 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


Output a glyph

  • « ps_symbol_width
  • ps_translate »
  • PHP Manual
  • PS Functions
  • Output a glyph

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


Sets translation

  • « ps_symbol
  • RPM Reader »
  • PHP Manual
  • PS Functions
  • Sets translation

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


RPM Header Reading

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
  • RPM Reader Functions
    • rpm_close — Closes an RPM file
    • rpm_get_tag — Retrieves a header tag from an RPM file
    • rpm_is_valid — Tests a filename for validity as an RPM file
    • rpm_open — Opens an RPM file
    • rpm_version — Returns a string representing the current version of the rpmreader extension


Introduction

This module allows you to read the meta information stored in the headers of a » RedHat Package Manager (» RPM) file.


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

The RPMReader extension requires PHP 5.


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/rpmreader.


Resource Types

There is one resource type used by the RPMReader module. The resource is a file pointer which identifies the RPM file with which to work.


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 list of constants are used to obtain information using the rpm_get_tag() function. These constants represent the tag number to be retrieved from the RPM file's header section. Descriptions are given below as to what data the tag number constants reference.

RPMREADER_MINIMUM (integer)
The minimum valid value of any RPM tag number.
RPMREADER_NAME (integer)
The name of the RPM package.
RPMREADER_VERSION (integer)
The version of the RPM package.
RPMREADER_RELEASE (integer)
The release of the RPM package.
RPMREADER_EPOCH (integer)
RPMREADER_SERIAL (integer)
RPMREADER_SUMMARY (integer)
The summary text of the RPM package.
RPMREADER_DESCRIPTION (integer)
The full description text of the RPM package.
RPMREADER_BUILDTIME (integer)
The date and time when the RPM package was built.
RPMREADER_BUILDHOST (integer)
The name of the host on which the RPM package was built.
RPMREADER_INSTALLTIME (integer)
RPMREADER_SIZE (integer)
The size of the RPM package.
RPMREADER_DISTRIBUTION (integer)
RPMREADER_VENDOR (integer)
RPMREADER_GIF (integer)
RPMREADER_XPM (integer)
RPMREADER_LICENSE (integer)
RPMREADER_COPYRIGHT (integer)
RPMREADER_PACKAGER (integer)
RPMREADER_GROUP (integer)
RPMREADER_SOURCE (integer)
RPMREADER_PATCH (integer)
RPMREADER_URL (integer)
RPMREADER_OS (integer)
RPMREADER_ARCH (integer)
RPMREADER_PREIN (integer)
RPMREADER_POSTIN (integer)
RPMREADER_PREUN (integer)
RPMREADER_POSTUN (integer)
RPMREADER_OLDFILENAMES (integer)
The list of files in an RPM package (deprecated format). The correct way is now to use a combination of 3 tags (RPMREADER_BASENAMES, RPMREADER_DIRINDEXES, RPMREADER_DIRNAMES) in what RPM now calls "CompressedFileNames". This tag is still used in older RPM files that did not use the "CompressedFileNames" method and is maintained for backward compatibility.
RPMREADER_FILESIZES (integer)
RPMREADER_FILESTATES (integer)
RPMREADER_FILEMODES (integer)
RPMREADER_FILERDEVS (integer)
RPMREADER_FILEMTIMES (integer)
RPMREADER_FILEMD5S (integer)
RPMREADER_FILELINKTOS (integer)
RPMREADER_FILEFLAGS (integer)
RPMREADER_FILEUSERNAME (integer)
RPMREADER_FILEGROUPNAME (integer)
RPMREADER_ICON (integer)
RPMREADER_SOURCERPM (integer)
RPMREADER_FILEVERIFYFLAGS (integer)
RPMREADER_ARCHIVESIZE (integer)
RPMREADER_PROVIDENAME (integer)
RPMREADER_PROVIDES (integer)
RPMREADER_REQUIREFLAGS (integer)
RPMREADER_REQUIRENAME (integer)
RPMREADER_REQUIREVERSION (integer)
RPMREADER_CONFLICTFLAGS (integer)
RPMREADER_CONFLICTNAME (integer)
RPMREADER_CONFLICTVERSION (integer)
RPMREADER_EXCLUDEARCH (integer)
RPMREADER_EXCLUDEOS (integer)
RPMREADER_EXCLUSIVEARCH (integer)
RPMREADER_EXCLUSIVEOS (integer)
RPMREADER_RPMVERSION (integer)
RPMREADER_TRIGGERSCRIPTS (integer)
RPMREADER_TRIGGERNAME (integer)
RPMREADER_TRIGGERVERSION (integer)
RPMREADER_TRIGGERFLAGS (integer)
RPMREADER_TRIGGERINDEX (integer)
RPMREADER_VERIFYSCRIPT (integer)
RPMREADER_CHANGELOGTIME (integer)
The list of dates from changelog entries.
RPMREADER_CHANGELOGNAME (integer)
The list of changelog entry names.
RPMREADER_CHANGELOGTEXT (integer)
The list of the text from changelog entries.
RPMREADER_PREINPROG (integer)
RPMREADER_POSTINPROG (integer)
RPMREADER_PREUNPROG (integer)
RPMREADER_POSTUNPROG (integer)
RPMREADER_BUILDARCHS (integer)
RPMREADER_OBSOLETENAME (integer)
RPMREADER_OBSOLETES (integer)
RPMREADER_VERIFYSCRIPTPROG (integer)
RPMREADER_TRIGGERSCRIPTPROG (integer)
RPMREADER_COOKIE (integer)
RPMREADER_FILEDEVICES (integer)
RPMREADER_FILEINODES (integer)
RPMREADER_FILELANGS (integer)
RPMREADER_PREFIXES (integer)
RPMREADER_INSTPREFIXES (integer)
RPMREADER_PROVIDEFLAGS (integer)
RPMREADER_PROVIDEVERSION (integer)
RPMREADER_OBSOLETEFLAGS (integer)
RPMREADER_OBSOLETEVERSION (integer)
RPMREADER_DIRINDEXES (integer)
The list of indices that relate directory names to files in the RPM package. This tag is used in conjunction with RPMREADER_BASENAMES and RPMREADER_DIRNAMES to reconstruct filenames in the RPM package stored with the new "CompressedFileNames" method in RPM.
RPMREADER_BASENAMES (integer)
The list of the names of files in the RPM package without path information. This tag is used in conjunction with RPMREADER_DIRINDEXES and RPMREADER_DIRNAMES to reconstruct filenames in the RPM package stored with the new "CompressedFileNames" method in RPM.
RPMREADER_DIRNAMES (integer)
The list of directory names used by files in the RPM package. This tag is used in conjunction with RPMREADER_BASENAMES and RPMREADER_DIRINDEXES to reconstruct filenames in the RPM package stored with the new "CompressedFileNames" method in RPM.
RPMREADER_OPTFLAGS (integer)
RPMREADER_DISTURL (integer)
RPMREADER_PAYLOADFORMAT (integer)
RPMREADER_PAYLOADCOMPRESSOR (integer)
RPMREADER_PAYLOADFLAGS (integer)
RPMREADER_INSTALLCOLOR (integer)
RPMREADER_INSTALLTID (integer)
RPMREADER_REMOVETID (integer)
RPMREADER_RHNPLATFORM (integer)
RPMREADER_PLATFORM (integer)
RPMREADER_PATCHESNAME (integer)
RPMREADER_PATCHESFLAGS (integer)
RPMREADER_PATCHESVERSION (integer)
RPMREADER_CACHECTIME (integer)
RPMREADER_CACHEPKGPATH (integer)
RPMREADER_CACHEPKGSIZE (integer)
RPMREADER_CACHEPKGMTIME (integer)
RPMREADER_FILECOLORS (integer)
RPMREADER_FILECLASS (integer)
RPMREADER_CLASSDICT (integer)
RPMREADER_FILEDEPENDSX (integer)
RPMREADER_FILEDEPENDSN (integer)
RPMREADER_DEPENDSDICT (integer)
RPMREADER_SOURCEPKGID (integer)
RPMREADER_FILECONTEXTS (integer)
RPMREADER_FSCONTEXTS (integer)
RPMREADER_RECONTEXTS (integer)
RPMREADER_POLICIES (integer)
RPMREADER_MAXIMUM (integer)
The maximum valid value of any RPM tag number.


  • « Predefined Constants
  • Basic usage »
  • PHP Manual
  • RPM Reader
  • Examples

Examples

Table of Contents

  • Basic usage


Basic usage

This example will open an RPM file and read the name, version, and release from the RPM file, echo the results, and close the RPM file.

Example #1 Basic RPMReader Example

<?php

$filename = "/path/to/file.rpm";

// open file
$rpmr = rpm_open($filename);

// get "Name" tag
$name = rpm_get_tag($rpmr, RPMREADER_NAME);

// get "Version" tag
$ver = rpm_get_tag($rpmr, RPMREADER_VERSION);

// get "Release" tag
$rel = rpm_get_tag($rpmr, RPMREADER_RELEASE);

echo "$name-$ver-$rel<br>\n";

// close file
rpm_close($rpmr);

?>


RPM Reader Functions

Table of Contents

  • rpm_close — Closes an RPM file
  • rpm_get_tag — Retrieves a header tag from an RPM file
  • rpm_is_valid — Tests a filename for validity as an RPM file
  • rpm_open — Opens an RPM file
  • rpm_version — Returns a string representing the current version of the rpmreader extension


Closes an RPM file

  • « RPM Reader Functions
  • rpm_get_tag »
  • PHP Manual
  • RPM Reader Functions
  • Closes an RPM file

rpm_close

(PECL rpmreader >= 0.1.0)

rpm_close — Closes an RPM file

Description

rpm_close ( resource $rpmr ) : bool

rpm_close() will close an RPM file pointer.

Parameters

rpmr

A file pointer resource successfully opened by rpm_open().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 rpm_close() example

<?php

$file = "/path/to/file.rpm";
$rpmr = rpm_open($file);

rpm_close($rpmr);

?>

See Also

  • rpm_open() - Opens an RPM file


Retrieves a header tag from an RPM file

  • « rpm_close
  • rpm_is_valid »
  • PHP Manual
  • RPM Reader Functions
  • Retrieves a header tag from an RPM file

rpm_get_tag

(PECL rpmreader >= 0.1.0)

rpm_get_tag — Retrieves a header tag from an RPM file

Description

rpm_get_tag ( resource $rpmr , int $tagnum ) : mixed

rpm_get_tag() will retrieve a given tag from the RPM file's header and return it.

Parameters

rpmr

A file pointer resource successfully opened by rpm_open().

tagnum

The tag number to retrieve from the RPM header. This value can be specified using the list of constants defined by this module.

Return Values

The return value can be of various types depending on the tagnum supplied to the function.

Examples

Example #1 rpm_get_tag() example

<?php

$file = "/path/to/file.rpm";
$rpmr = rpm_open($file);

$name = rpm_get_tag($rpmr, RPMREADER_NAME);
echo "$name<br>\n";

rpm_close($rpmr);

?>

See Also

  • rpm_open() - Opens an RPM file
  • rpm_close() - Closes an RPM file


Tests a filename for validity as an RPM file

  • « rpm_get_tag
  • rpm_open »
  • PHP Manual
  • RPM Reader Functions
  • Tests a filename for validity as an RPM file

rpm_is_valid

(PECL rpmreader >= 0.1.0)

rpm_is_valid — Tests a filename for validity as an RPM file

Description

rpm_is_valid ( string $filename ) : bool

rpm_is_valid() will test an RPM file for validity as an RPM file. This is not the same as rpm_open() as it only checks the file for validity but does not return a file pointer to be used by further functions.

Parameters

filename

The filename of the RPM file you wish to check for validity.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 rpm_is_valid() example

<?php

$file = "/path/to/file.rpm";

if (rpm_is_valid($file)) {
    echo "File is recognized as an RPM file.<br>\n";
}
else {
    echo "File is not recognized as an RPM file.<br>\n";
}

?>


Opens an RPM file

  • « rpm_is_valid
  • rpm_version »
  • PHP Manual
  • RPM Reader Functions
  • Opens an RPM file

rpm_open

(PECL rpmreader >= 0.1.0)

rpm_open — Opens an RPM file

Description

rpm_open ( string $filename ) : resource

rpm_open() will open an RPM file and will determine if the file is a valid RPM file.

Parameters

filename

The filename of the RPM file you wish to open.

Return Values

If the open succeeds, then rpm_open() will return a file pointer resource to the newly opened file. On error, the function will return FALSE.

Examples

Example #1 rpm_open() example

<?php

$file = "/path/to/file.rpm";
$rpmr = rpm_open($file);

rpm_close($rpmr);

?>

See Also

  • rpm_close() - Closes an RPM file


Returns a string representing the current version of the rpmreader extension

  • « rpm_open
  • XLSWriter »
  • PHP Manual
  • RPM Reader Functions
  • Returns a string representing the current version of the rpmreader extension

rpm_version

(PECL rpmreader >= 0.3.0)

rpm_version — Returns a string representing the current version of the rpmreader extension

Description

rpm_version ( void ) : string

rpm_version() will return the current version of the rpmreader extension.

Return Values

rpm_version() will return a string representing the rpmreader version currently loaded in PHP.

Examples

Example #1 rpm_version() example

<?php

$rpmr_ver = rpm_version();

echo "$rpmr_ver<br />\n";

?>


XLSWriter

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Resource Types
  • Predefined Constants
  • 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


  • « XLSWriter
  • Installing/Configuring »
  • PHP Manual
  • XLSWriter
  • Introduction

Introduction

An efficient and fast xlsx file export extension.


  • « Introduction
  • Requirements »
  • PHP Manual
  • XLSWriter
  • Installing/Configuring

Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Resource Types


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

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.


  • « Resource Types
  • Vtiful\Kernel\Excel »
  • PHP Manual
  • XLSWriter
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


The Vtiful\Kernel\Excel class

(PHP 7 >= 7.0.0, PECL xlswriter >= 1.2.1)

Introduction

Create xlsx files and set cells and output xlsx files

Class synopsis

Vtiful\Kernel\Excel {
/* Methods */
public addSheet ( string $sheetName )
public autoFilter ( string $scope )
public constMemory ( string $fileName [, string $sheetName ] )
public __construct ( array $config )
public data ( array $data )
public fileName ( string $fileName [, string $sheetName ] )
public getHandle ( void )
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 , stringintdouble $data [, string $format ] )
public mergeCells ( string $scope , string $data )
public output ( void )
public setColumn ( string $range , float $width [, resource $format ] )
public setRow ( string $range , float $height [, resource $format ] )
}

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


Vtiful\Kernel\Excel addSheet

  • « Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel::autoFilter »
  • PHP Manual
  • Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel addSheet

Vtiful\Kernel\Excel::addSheet

(PHP 7 >= 7.0.0, 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

  • « Vtiful\Kernel\Excel::addSheet
  • Vtiful\Kernel\Excel::constMemory »
  • PHP Manual
  • Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel autoFilter

Vtiful\Kernel\Excel::autoFilter

(PHP 7 >= 7.0.0, 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

  • « Vtiful\Kernel\Excel::autoFilter
  • Vtiful\Kernel\Excel::__construct »
  • PHP Manual
  • Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel constMemory

Vtiful\Kernel\Excel::constMemory

(PHP 7 >= 7.0.0, 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 constructor

  • « Vtiful\Kernel\Excel::constMemory
  • Vtiful\Kernel\Excel::data »
  • PHP Manual
  • Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel constructor

Vtiful\Kernel\Excel::__construct

(PHP 7 >= 7.0.0, 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

Return Values

Vtiful\Kernel\Excel instance

Examples

Example #1 example

<?php
$config = [
  'path' => '/home/viest'
];

$excelObject = new \Vtiful\Kernel\Excel($config);
?>


Vtiful\Kernel\Excel data

  • « Vtiful\Kernel\Excel::__construct
  • Vtiful\Kernel\Excel::fileName »
  • PHP Manual
  • Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel data

Vtiful\Kernel\Excel::data

(PHP 7 >= 7.0.0, 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

  • « Vtiful\Kernel\Excel::data
  • Vtiful\Kernel\Excel::getHandle »
  • PHP Manual
  • Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel fileName

Vtiful\Kernel\Excel::fileName

(PHP 7 >= 7.0.0, 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

  • « Vtiful\Kernel\Excel::fileName
  • Vtiful\Kernel\Excel::header »
  • PHP Manual
  • Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel getHandle

Vtiful\Kernel\Excel::getHandle

(PHP 7 >= 7.0.0, PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::getHandle — Vtiful\Kernel\Excel getHandle

Description

public Vtiful\Kernel\Excel::getHandle ( void )

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

  • « Vtiful\Kernel\Excel::getHandle
  • Vtiful\Kernel\Excel::insertFormula »
  • PHP Manual
  • Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel header

Vtiful\Kernel\Excel::header

(PHP 7 >= 7.0.0, 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

  • « Vtiful\Kernel\Excel::header
  • Vtiful\Kernel\Excel::insertImage »
  • PHP Manual
  • Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel insertFormula

Vtiful\Kernel\Excel::insertFormula

(PHP 7 >= 7.0.0, 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

  • « Vtiful\Kernel\Excel::insertFormula
  • Vtiful\Kernel\Excel::insertText »
  • PHP Manual
  • Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel insertImage

Vtiful\Kernel\Excel::insertImage

(PHP 7 >= 7.0.0, 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

  • « Vtiful\Kernel\Excel::insertImage
  • Vtiful\Kernel\Excel::mergeCells »
  • PHP Manual
  • Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel insertText

Vtiful\Kernel\Excel::insertText

(PHP 7 >= 7.0.0, PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::insertText — Vtiful\Kernel\Excel insertText

Description

public Vtiful\Kernel\Excel::insertText ( int $row , int $column , stringintdouble $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

  • « Vtiful\Kernel\Excel::insertText
  • Vtiful\Kernel\Excel::output »
  • PHP Manual
  • Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel mergeCells

Vtiful\Kernel\Excel::mergeCells

(PHP 7 >= 7.0.0, 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

  • « Vtiful\Kernel\Excel::mergeCells
  • Vtiful\Kernel\Excel::setColumn »
  • PHP Manual
  • Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel output

Vtiful\Kernel\Excel::output

(PHP 7 >= 7.0.0, PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::output — Vtiful\Kernel\Excel output

Description

public Vtiful\Kernel\Excel::output ( void )

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

  • « Vtiful\Kernel\Excel::output
  • Vtiful\Kernel\Excel::setRow »
  • PHP Manual
  • Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel setColumn

Vtiful\Kernel\Excel::setColumn

(PHP 7 >= 7.0.0, 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 example

<?php
$config = [
    'path' => './tests'
];

$excel  = new \Vtiful\Kernel\Excel($config);

$fileObject = $excel->fileName('tutorial01.xlsx');
$fileHandle = $fileObject->getHandle();

$boldStyle = \Vtiful\Kernel\Format::bold($fileHandle);

$fileObject->header(['name', 'age'])
    ->data([['viest', 21]])
    ->setColumn('A:A', 200, $boldStyle)
    ->output();


Vtiful\Kernel\Excel setRow

  • « Vtiful\Kernel\Excel::setColumn
  • Vtiful\Kernel\Format »
  • PHP Manual
  • Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel setRow

Vtiful\Kernel\Excel::setRow

(PHP 7 >= 7.0.0, 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 column.

Parameters

range

cell start and end coordinate strings

height

row height

format

cell format resource

Return Values

Vtiful\Kernel\Excel instance

Examples

Example #1 example

<?php
$config = [
    'path' => './tests'
];

$excel  = new \Vtiful\Kernel\Excel($config);

$fileObject = $excel->fileName('tutorial01.xlsx');
$fileHandle = $fileObject->getHandle();

$boldStyle = \Vtiful\Kernel\Format::bold($fileHandle);

$fileObject->header(['name', 'age'])
    ->data([['viest', 21]])
    ->setRow('A1', 20, $boldStyle,)
    ->output();


The Vtiful\Kernel\Format class

(PHP 7 >= 7.0.0, PECL xlswriter >= 1.2.1)

Introduction

Create a cell format object

Class synopsis

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

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


Vtiful\Kernel\Format align

  • « Vtiful\Kernel\Format
  • Vtiful\Kernel\Format::bold »
  • PHP Manual
  • Vtiful\Kernel\Format
  • Vtiful\Kernel\Format align

Vtiful\Kernel\Format::align

(PHP 7 >= 7.0.0, 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 example

<?php
$config = [
    'path' => './tests'
];

$excel  = new \Vtiful\Kernel\Excel($config);

$fileObject = $excel->fileName('tutorial01.xlsx');
$fileHandle = $fileObject->getHandle();

$alignStyle = \Vtiful\Kernel\Format::align($fileHandle, \Vtiful\Kernel\Format::FORMAT_ALIGN_LEFT);

$fileObject->header(['name', 'age'])
    ->data([['viest', 21]])
    ->setColumn('A:A', 200, $align)
    ->output();
?>


Vtiful\Kernel\Format bold

  • « Vtiful\Kernel\Format::align
  • Vtiful\Kernel\Format::italic »
  • PHP Manual
  • Vtiful\Kernel\Format
  • Vtiful\Kernel\Format bold

Vtiful\Kernel\Format::bold

(PHP 7 >= 7.0.0, 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 example

<?php
$config = [
    'path' => './tests'
];

$excel  = new \Vtiful\Kernel\Excel($config);

$fileObject = $excel->fileName('tutorial01.xlsx');
$fileHandle = $fileObject->getHandle();

$boldStyle = \Vtiful\Kernel\Format::bold($fileHandle);

$fileObject->header(['name', 'age'])
    ->data([['viest', 21]])
    ->setColumn('A:A', 200, $boldStyle)
    ->output();
?>


Vtiful\Kernel\Format italic

  • « Vtiful\Kernel\Format::bold
  • Vtiful\Kernel\Format::underline »
  • PHP Manual
  • Vtiful\Kernel\Format
  • Vtiful\Kernel\Format italic

Vtiful\Kernel\Format::italic

(PHP 7 >= 7.0.0, 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 example

<?php
$config = [
    'path' => './tests'
];

$excel  = new \Vtiful\Kernel\Excel($config);

$fileObject = $excel->fileName('tutorial01.xlsx');
$fileHandle = $fileObject->getHandle();

$italicStyle = \Vtiful\Kernel\Format::italic($fileHandle);

$fileObject->header(['name', 'age'])
    ->data([['viest', 21]])
    ->setColumn('A:A', 200, $italicStyle)
    ->output();
?>


Vtiful\Kernel\Format underline

  • « Vtiful\Kernel\Format::italic
  • Process Control Extensions »
  • PHP Manual
  • Vtiful\Kernel\Format
  • Vtiful\Kernel\Format underline

Vtiful\Kernel\Format::underline

(PHP 7 >= 7.0.0, 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 example

<?php
$config = [
    'path' => './tests'
];

$excel  = new \Vtiful\Kernel\Excel($config);

$fileObject = $excel->fileName('tutorial01.xlsx');
$fileHandle = $fileObject->getHandle();

$underlineStyle = \Vtiful\Kernel\Format::underline($fileHandle, \Vtiful\Kernel\Format::UNDERLINE_SINGLE);

$fileObject->header(['name', 'age'])
    ->data([['viest', 21]])
    ->setColumn('A:A', 200, $underlineStyle)
    ->output();
?>


Process Control Extensions

  • Eio
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Eio Functions
  • Ev
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Watchers
    • Watcher callbacks
    • Periodic watcher operation modes
    • Ev — The Ev class
    • EvCheck — The EvCheck class
    • EvChild — The EvChild class
    • EvEmbed — The EvEmbed class
    • EvFork — The EvFork class
    • EvIdle — The EvIdle class
    • EvIo — The EvIo class
    • EvLoop — The EvLoop class
    • EvPeriodic — The EvPeriodic class
    • EvPrepare — The EvPrepare class
    • EvSignal — The EvSignal class
    • EvStat — The EvStat class
    • EvTimer — The EvTimer class
    • EvWatcher — The EvWatcher class
  • Expect
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Expect Functions
  • Libevent
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Libevent Functions
  • PCNTL — Process Control
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • PCNTL Functions
  • POSIX
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • POSIX Functions
  • Program execution — System program execution
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Program execution Functions
  • parallel
    • Introduction
    • Installation
    • Philosophy
    • Functional API
    • parallel\Runtime — The parallel\Runtime class
    • parallel\Future — The parallel\Future class
    • parallel\Channel — The parallel\Channel class
    • parallel\Events — The parallel\Events class
    • parallel\Events\Input — The parallel\Events\Input class
    • parallel\Events\Event — The parallel\Events\Event class
    • parallel\Events\Event\Type — The parallel\Events\Event\Type class
    • parallel\Sync — The parallel\Sync class
  • pthreads
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Threaded — The Threaded class
    • Thread — The Thread class
    • Worker — The Worker class
    • Collectable — The Collectable interface
    • Modifiers — Method Modifiers
    • Pool — The Pool class
    • Mutex — The Mutex class
    • Cond — The Cond class
    • Volatile — The Volatile class
  • pht
    • Introduction
    • Installing/Configuring
    • pht\Thread — The Thread class
    • pht\Runnable — The Runnable interface
    • pht\HashTable — The HashTable class
    • pht\Vector — The Vector class
    • pht\Queue — The Queue class
    • pht\AtomicInteger — The AtomicInteger class
    • pht\Threaded — The Threaded interface
  • Semaphore — Semaphore, Shared Memory and IPC
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Semaphore Functions
  • Shared Memory
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Shared Memory Functions
  • Sync
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • SyncMutex — The SyncMutex class
    • SyncSemaphore — The SyncSemaphore class
    • SyncEvent — The SyncEvent class
    • SyncReaderWriter — The SyncReaderWriter class
    • SyncSharedMemory — The SyncSharedMemory class


Eio

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • 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_add — Adds a request to the request group
    • eio_grp_cancel — Cancels a request group
    • eio_grp_limit — Set group limit
    • eio_grp — Creates a request group
    • 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 — Repositions the offset of the open file associated with the fd argument to the argument offset according to the directive whence
    • 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_file_range — Sync a file segment with disk
    • eio_sync — Commit buffer cache to 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


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 */
?>


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.


  • « Runtime Configuration
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

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 (integer)
Request minimal prioriry
EIO_PRI_DEFAULT (integer)
Request default prioriry
EIO_PRI_MAX (integer)
Request maximal prioriry

eio_seek() whence argument:

EIO_SEEK_SET (integer)
The offset is set to specified number of bytes(offset).
EIO_SEEK_CUR (integer)
The offset is set to its current location plus offset bytes.
EIO_SEEK_END (integer)
The offset is set to the size of the file plus offset bytes.

Flags used with eio_readdir():

EIO_READDIR_DENTS (integer)
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 (integer)
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 (integer)
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 (integer)
EIO_DT_UNKNOWN (integer)
Unknown node type(very common). Further stat() needed.
EIO_DT_FIFO (integer)
FIFO node type
EIO_DT_CHR (integer)
Node type
EIO_DT_MPC (integer)
Multiplexed char device (v7+coherent) node type
EIO_DT_DIR (integer)
Directory node type
EIO_DT_NAM (integer)
Xenix special named file node type
EIO_DT_BLK (integer)
Node type
EIO_DT_MPB (integer)
Multiplexed block device (v7+coherent)
EIO_DT_REG (integer)
Node type
EIO_DT_NWK (integer)
EIO_DT_CMP (integer)
HP-UX network special node type
EIO_DT_LNK (integer)
Link node type
EIO_DT_SOCK (integer)
Socket node type
EIO_DT_DOOR (integer)
Solaris door node type
EIO_DT_WHT (integer)
Node type
EIO_DT_MAX (integer)
Highest node type value

Access modes for eio_open() flags argument:

EIO_O_RDONLY (integer)
EIO_O_WRONLY (integer)
EIO_O_RDWR (integer)
EIO_O_NONBLOCK (integer)
EIO_O_APPEND (integer)
EIO_O_CREAT (integer)
EIO_O_TRUNC (integer)
EIO_O_EXCL (integer)
EIO_O_FSYNC (integer)

mode argument flags for eio_open():

EIO_S_IRUSR (integer)
EIO_S_IWUSR (integer)
EIO_S_IXUSR (integer)
EIO_S_IRGRP (integer)
EIO_S_IWGRP (integer)
EIO_S_IXGRP (integer)
EIO_S_IROTH (integer)
EIO_S_IWOTH (integer)
EIO_S_IXOTH (integer)
EIO_S_IFREG (integer)
EIO_S_IFCHR (integer)
EIO_S_IFBLK (integer)
EIO_S_IFIFO (integer)
EIO_S_IFSOCK (integer)

eio_sync_file_range() flags:

EIO_SYNC_FILE_RANGE_WAIT_BEFORE (integer)
EIO_SYNC_FILE_RANGE_WRITE (integer)
EIO_SYNC_FILE_RANGE_WAIT_AFTER (integer)

eio_fallocate() flags:

EIO_FALLOC_FL_KEEP_SIZE (integer)

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

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_add — Adds a request to the request group
  • eio_grp_cancel — Cancels a request group
  • eio_grp_limit — Set group limit
  • eio_grp — Creates a request group
  • 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 — Repositions the offset of the open file associated with the fd argument to the argument offset according to the directive whence
  • 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_file_range — Sync a file segment with disk
  • eio_sync — Commit buffer cache to 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


Artificially increase load. Could be useful in tests, benchmarking

  • « Eio Functions
  • eio_cancel »
  • PHP Manual
  • Eio Functions
  • Artificially increase load. Could be useful in tests, benchmarking

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 error.

See Also

  • eio_nop() - Does nothing, except go through the whole request cycle


Cancels a request

  • « eio_busy
  • eio_chmod »
  • PHP Manual
  • Eio Functions
  • Cancels a request

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


Change file/directory permissions

  • « eio_cancel
  • eio_chown »
  • PHP Manual
  • Eio Functions
  • Change file/directory permissions

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 error.

See Also

  • eio_chown() - Change file/directory permissions


Change file/directory permissions

  • « eio_chmod
  • eio_close »
  • PHP Manual
  • Eio Functions
  • 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 error.

See Also

  • eio_chmod() - Change file/directory permissions


Close file

  • « eio_chown
  • eio_custom »
  • PHP Manual
  • Eio Functions
  • Close file

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 error.

See Also

  • eio_open() - Opens a file


Execute custom request like any other eio_* call

  • « eio_close
  • eio_dup2 »
  • PHP Manual
  • Eio Functions
  • Execute custom request like any other eio_* call

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 error.

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)


Duplicate a file descriptor

  • « eio_custom
  • eio_event_loop »
  • PHP Manual
  • Eio Functions
  • Duplicate a file descriptor

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 error.


Polls libeio until all requests proceeded

  • « eio_dup2
  • eio_fallocate »
  • PHP Manual
  • Eio Functions
  • Polls libeio until all requests proceeded

eio_event_loop

(PECL eio >= 0.0.1dev)

eio_event_loop — Polls libeio until all requests proceeded

Description

eio_event_loop ( void ) : 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 error.

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


Allows the caller to directly manipulate the allocated disk space for a file

  • « eio_event_loop
  • eio_fchmod »
  • PHP Manual
  • Eio Functions
  • Allows the caller to directly manipulate the allocated disk space for a file

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 error.


Change file permissions

  • « eio_fallocate
  • eio_fchown »
  • PHP Manual
  • Eio Functions
  • Change file permissions

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 error.

See Also

  • eio_fchown() - Change file ownership


Change file ownership

  • « eio_fchmod
  • eio_fdatasync »
  • PHP Manual
  • Eio Functions
  • 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.

See Also

  • eio_fchmod() - Change file permissions


Synchronize a file's in-core state with storage device

  • « eio_fchown
  • eio_fstat »
  • PHP Manual
  • Eio Functions
  • Synchronize a file's in-core state with storage device

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 error.


Get file status

  • « eio_fdatasync
  • eio_fstatvfs »
  • PHP Manual
  • Eio Functions
  • Get file status

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 error.

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


Get file system statistics

  • « eio_fstat
  • eio_fsync »
  • PHP Manual
  • Eio Functions
  • Get file system statistics

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 error.

See Also

  • eio_statvfs() - Get file system statistics


Synchronize a file's in-core state with storage device

  • « eio_fstatvfs
  • eio_ftruncate »
  • PHP Manual
  • Eio Functions
  • Synchronize a file's in-core state with storage device

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 error.

See Also

  • eio_sync() - Commit buffer cache to disk


Truncate a file

  • « eio_fsync
  • eio_futime »
  • PHP Manual
  • Eio Functions
  • Truncate a file

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 error.

See Also

  • eio_truncate() - Truncate a file


Change file last access and modification times

  • « eio_ftruncate
  • eio_get_event_stream »
  • PHP Manual
  • Eio Functions
  • Change file last access and modification times

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 error.

See Also

  • eio_utime() - Change file last access and modification times


Get stream representing a variable used in internal communications with libeio

  • « eio_futime
  • eio_get_last_error »
  • PHP Manual
  • Eio Functions
  • Get stream representing a variable used in internal communications with libeio

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 ( void ) : 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"


Returns string describing the last error associated with a request resource

  • « eio_get_event_stream
  • eio_grp_add »
  • PHP Manual
  • Eio Functions
  • Returns string describing the last error associated with a request resource

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.


Adds a request to the request group

  • « eio_get_last_error
  • eio_grp_cancel »
  • PHP Manual
  • Eio Functions
  • 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

eio_grp_add() doesn't return a value.

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


Cancels a request group

  • « eio_grp_add
  • eio_grp_limit »
  • PHP Manual
  • Eio Functions
  • Cancels a request group

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


Set group limit

  • « eio_grp_cancel
  • eio_grp »
  • PHP Manual
  • Eio Functions
  • Set group limit

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


Creates a request group

  • « eio_grp_limit
  • eio_init »
  • PHP Manual
  • Eio Functions
  • Creates a request group

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 error.

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


(Re-)initialize Eio

  • « eio_grp
  • eio_link »
  • PHP Manual
  • Eio Functions
  • (Re-)initialize Eio

eio_init

(PECL eio = 1.0.0)

eio_init — (Re-)initialize Eio

Description

eio_init ( void ) : 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.

Warning

This deprecated feature will certainly be removed in the future. Since Eio 1.1.0 eio_init() is deprecated. In Eio 1.0.0 because of » libeio's restrictions you must call eio_init() in child process, if you fork one by any means. You have to avoid using Eio in parent process, if you use it in childs.

Parameters

This function has no parameters.

Return Values

No value is returned.


Create a hardlink for file

  • « eio_init
  • eio_lstat »
  • PHP Manual
  • Eio Functions
  • Create a hardlink for file

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


Get file status

  • « eio_link
  • eio_mkdir »
  • PHP Manual
  • Eio Functions
  • Get file status

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


Create directory

  • « eio_lstat
  • eio_mknod »
  • PHP Manual
  • Eio Functions
  • Create directory

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 error.

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


Create a special or ordinary file

  • « eio_mkdir
  • eio_nop »
  • PHP Manual
  • Eio Functions
  • Create a special or ordinary file

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 error.

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


Does nothing, except go through the whole request cycle

  • « eio_mknod
  • eio_npending »
  • PHP Manual
  • Eio Functions
  • Does nothing, except go through the whole request cycle

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 error.

See Also

  • eio_busy() - Artificially increase load. Could be useful in tests, benchmarking


Returns number of finished, but unhandled requests

  • « eio_nop
  • eio_nready »
  • PHP Manual
  • Eio Functions
  • Returns number of finished, but unhandled requests

eio_npending

(PECL eio >= 0.0.1dev)

eio_npending — Returns number of finished, but unhandled requests

Description

eio_npending ( void ) : 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


Returns number of not-yet handled requests

  • « eio_npending
  • eio_nreqs »
  • PHP Manual
  • Eio Functions
  • Returns number of not-yet handled requests

eio_nready

(PECL eio >= 0.0.1dev)

eio_nready — Returns number of not-yet handled requests

Description

eio_nready ( void ) : 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


Returns number of requests to be processed

  • « eio_nready
  • eio_nthreads »
  • PHP Manual
  • Eio Functions
  • Returns number of requests to be processed

eio_nreqs

(PECL eio >= 0.0.1dev)

eio_nreqs — Returns number of requests to be processed

Description

eio_nreqs ( void ) : 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


Returns number of threads currently in use

  • « eio_nreqs
  • eio_open »
  • PHP Manual
  • Eio Functions
  • Returns number of threads currently in use

eio_nthreads

(PECL eio >= 0.0.1dev)

eio_nthreads — Returns number of threads currently in use

Description

eio_nthreads ( void ) : 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


Opens a file

  • « eio_nthreads
  • eio_poll »
  • PHP Manual
  • Eio Functions
  • Opens a file

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


Can be to be called whenever there are pending requests that need finishing

  • « eio_open
  • eio_read »
  • PHP Manual
  • Eio Functions
  • Can be to be called whenever there are pending requests that need finishing

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 ( void ) : 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


Read from a file descriptor at given offset

  • « eio_poll
  • eio_readahead »
  • PHP Manual
  • Eio Functions
  • Read from a file descriptor at given offset

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


Perform file readahead into page cache

  • « eio_read
  • eio_readdir »
  • PHP Manual
  • Eio Functions
  • Perform file readahead into page cache

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 error.


Reads through a whole directory

  • « eio_readahead
  • eio_readlink »
  • PHP Manual
  • Eio Functions
  • Reads through a whole directory

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 error. Sets result argument of callback function according to flags:

EIO_READDIR_DENTS (integer)
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 (integer)
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 (integer)
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 (integer)

Node types:

EIO_DT_UNKNOWN (integer)
Unknown node type(very common). Further stat() needed.
EIO_DT_FIFO (integer)
FIFO node type
EIO_DT_CHR (integer)
Node type
EIO_DT_MPC (integer)
Multiplexed char device (v7+coherent) node type
EIO_DT_DIR (integer)
Directory node type
EIO_DT_NAM (integer)
Xenix special named file node type
EIO_DT_BLK (integer)
Node type
EIO_DT_MPB (integer)
Multiplexed block device (v7+coherent)
EIO_DT_REG (integer)
Node type
EIO_DT_NWK (integer)
EIO_DT_CMP (integer)
HP-UX network special node type
EIO_DT_LNK (integer)
Link node type
EIO_DT_SOCK (integer)
Socket node type
EIO_DT_DOOR (integer)
Solaris door node type
EIO_DT_WHT (integer)
Node type
EIO_DT_MAX (integer)
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)
    }
  }
}


Read value of a symbolic link

  • « eio_readdir
  • eio_realpath »
  • PHP Manual
  • Eio Functions
  • Read value of a symbolic link

eio_readlink

(PECL eio >= 0.0.1dev)

eio_readlink — Read value of a symbolic link

Description

eio_readlink ( string $path , int $pri , callable $callback [, string $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 error.

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


Get the canonicalized absolute pathname

  • « eio_readlink
  • eio_rename »
  • PHP Manual
  • Eio Functions
  • Get the canonicalized absolute pathname

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"


Change the name or location of a file

  • « eio_realpath
  • eio_rmdir »
  • PHP Manual
  • Eio Functions
  • Change the name or location of a file

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 error.

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


Remove a directory

  • « eio_rename
  • eio_seek »
  • PHP Manual
  • Eio Functions
  • Remove a directory

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 error.

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


Repositions the offset of the open file associated with the fd argument to the argument offset according to the directive whence

  • « eio_rmdir
  • eio_sendfile »
  • PHP Manual
  • Eio Functions
  • Repositions the offset of the open file associated with the fd argument to the argument offset according to the directive whence

eio_seek

(PECL eio >= 0.5.0b)

eio_seek — Repositions the offset of the open file associated with the fd argument to the argument offset according to the directive whence

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 resource, or file descriptor specified by fd to the argument offset according to the directive whence as follows:

  • 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.

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_seek() returns request resource on success or FALSE on error.


Transfer data between file descriptors

  • « eio_seek
  • eio_set_max_idle »
  • PHP Manual
  • Eio Functions
  • Transfer data between file descriptors

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 error.


Set maximum number of idle threads

  • « eio_sendfile
  • eio_set_max_parallel »
  • PHP Manual
  • Eio Functions
  • Set maximum number of idle threads

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


Set maximum parallel threads

  • « eio_set_max_idle
  • eio_set_max_poll_reqs »
  • PHP Manual
  • Eio Functions
  • 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


Set maximum number of requests processed in a poll

  • « eio_set_max_parallel
  • eio_set_max_poll_time »
  • PHP Manual
  • Eio Functions
  • Set maximum number of requests processed in a poll

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.


Set maximum poll time

  • « eio_set_max_poll_reqs
  • eio_set_min_parallel »
  • PHP Manual
  • Eio Functions
  • Set maximum poll time

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.


Set minimum parallel thread number

  • « eio_set_max_poll_time
  • eio_stat »
  • PHP Manual
  • Eio Functions
  • Set minimum parallel thread number

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


Get file status

  • « eio_set_min_parallel
  • eio_statvfs »
  • PHP Manual
  • Eio Functions
  • Get file status

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


Get file system statistics

  • « eio_stat
  • eio_symlink »
  • PHP Manual
  • Eio Functions
  • Get file system statistics

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 error. 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)
}


Create a symbolic link

  • « eio_statvfs
  • eio_sync_file_range »
  • PHP Manual
  • Eio Functions
  • Create a symbolic link

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 error.

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


Sync a file segment with disk

  • « eio_symlink
  • eio_sync »
  • PHP Manual
  • Eio Functions
  • Sync a file segment with disk

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 error.


Commit buffer cache to disk

  • « eio_sync_file_range
  • eio_syncfs »
  • PHP Manual
  • Eio Functions
  • Commit buffer cache to disk

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 error.


Calls Linux' syncfs syscall, if available

  • « eio_sync
  • eio_truncate »
  • PHP Manual
  • Eio Functions
  • Calls Linux' syncfs syscall, if available

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 error.


Truncate a file

  • « eio_syncfs
  • eio_unlink »
  • PHP Manual
  • Eio Functions
  • Truncate a file

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 error.

See Also

  • eio_ftruncate() - Truncate a file


Delete a name and possibly the file it refers to

  • « eio_truncate
  • eio_utime »
  • PHP Manual
  • Eio Functions
  • Delete a name and possibly the file it refers to

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 error.


Change file last access and modification times

  • « eio_unlink
  • eio_write »
  • PHP Manual
  • Eio Functions
  • Change file last access and modification times

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 error.

See Also

  • eio_futime() - Change file last access and modification times


Write to file

  • « eio_utime
  • Ev »
  • PHP Manual
  • Eio Functions
  • Write to file

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 error.

See Also

  • eio_open() - Opens a file


Ev

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Watchers
  • Watcher callbacks
  • Periodic watcher operation modes
  • Ev — The Ev class
    • 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)
  • EvCheck — The EvCheck class
    • EvCheck::__construct — Constructs the EvCheck watcher object
    • EvCheck::createStopped — Create instance of a stopped EvCheck watcher
  • EvChild — The EvChild class
    • EvChild::__construct — Constructs the EvChild watcher object
    • EvChild::createStopped — Create instance of a stopped EvCheck watcher
    • EvChild::set — Configures the watcher
  • EvEmbed — The EvEmbed class
    • 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
  • EvFork — The EvFork class
    • EvFork::__construct — Constructs the EvFork watcher object
    • EvFork::createStopped — Creates a stopped instance of EvFork watcher class
  • EvIdle — The EvIdle class
    • EvIdle::__construct — Constructs the EvIdle watcher object
    • EvIdle::createStopped — Creates instance of a stopped EvIdle watcher object
  • EvIo — The EvIo class
    • EvIo::__construct — Constructs EvIo watcher object
    • EvIo::createStopped — Create stopped EvIo watcher object
    • EvIo::set — Configures the watcher
  • EvLoop — The EvLoop class
    • 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)
  • EvPeriodic — The EvPeriodic class
    • 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
  • EvPrepare — The EvPrepare class
    • EvPrepare::__construct — Constructs EvPrepare watcher object
    • EvPrepare::createStopped — Creates a stopped instance of EvPrepare watcher
  • EvSignal — The EvSignal class
    • EvSignal::__construct — Constructs EvSignal watcher object
    • EvSignal::createStopped — Create stopped EvSignal watcher object
    • EvSignal::set — Configures the watcher
  • EvStat — The EvStat class
    • EvStat::attr — Returns the values most recently detected by Ev
    • EvStat::__construct — Constructs EvStat watcher object
    • EvStat::createStopped — Create a stopped EvStat watcher object
    • EvStat::prev — Returns the previous set of values returned by EvStat::attr
    • EvStat::set — Configures the watcher
    • EvStat::stat — Initiates the stat call
  • EvTimer — The EvTimer class
    • EvTimer::again — Restarts the timer watcher
    • EvTimer::__construct — Constructs an EvTimer watcher object
    • EvTimer::createStopped — Creates EvTimer stopped watcher object
    • EvTimer::set — Configures the watcher
  • EvWatcher — The EvWatcher class
    • EvWatcher::clear — Clear watcher pending status
    • EvWatcher::__construct — Abstract constructor of a watcher object
    • EvWatcher::feed — Feeds the given revents set into the event loop
    • EvWatcher::getLoop — Returns the loop responsible for the watcher
    • EvWatcher::invoke — Invokes the watcher callback with the given received events bit mask
    • EvWatcher::keepalive — Configures whether to keep the loop from returning
    • EvWatcher::setCallback — Sets new callback for the watcher
    • EvWatcher::start — Starts the watcher
    • EvWatcher::stop — Stops the watcher


Introduction

This extension provides inteface 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
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

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 .


Predefined Constants

This extension has no constants defined.

Most constants are moved to Ev singleton class.


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 Ev {
/* Constants */
const integer FLAG_AUTO = 0 ;
const integer FLAG_NOENV = 16777216 ;
const integer FLAG_FORKCHECK = 33554432 ;
const integer FLAG_NOINOTIFY = 1048576 ;
const integer FLAG_SIGNALFD = 2097152 ;
const integer FLAG_NOSIGMASK = 4194304 ;
const integer RUN_NOWAIT = 1 ;
const integer RUN_ONCE = 2 ;
const integer BREAK_CANCEL = 0 ;
const integer BREAK_ONE = 1 ;
const integer BREAK_ALL = 2 ;
const integer MINPRI = -2 ;
const integer MAXPRI = 2 ;
const integer READ = 1 ;
const integer WRITE = 2 ;
const integer TIMER = 256 ;
const integer PERIODIC = 512 ;
const integer SIGNAL = 1024 ;
const integer CHILD = 2048 ;
const integer STAT = 4096 ;
const integer IDLE = 8192 ;
const integer PREPARE = 16384 ;
const integer CHECK = 32768 ;
const integer EMBED = 65536 ;
const integer CUSTOM = 16777216 ;
const integer ERROR = 2147483648 ;
const integer BACKEND_SELECT = 1 ;
const integer BACKEND_POLL = 2 ;
const integer BACKEND_EPOLL = 4 ;
const integer BACKEND_KQUEUE = 8 ;
const integer BACKEND_DEVPOLL = 16 ;
const integer BACKEND_PORT = 32 ;
const integer BACKEND_ALL = 63 ;
const integer BACKEND_MASK = 65535 ;
/* Methods */
final public static backend ( void ) : int
final public static depth ( void ) : int
final public static embeddableBackends ( void ) : int
final public static feedSignal ( int $signum ) : void
final public static feedSignalEvent ( int $signum ) : void
final public static iteration ( void ) : int
final public static now ( void ) : float
final public static nowUpdate ( void ) : void
final public static recommendedBackends ( void ) : int
final public static resume ( void ) : 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 ( void ) : int
final public static suspend ( void ) : void
final public static time ( void ) : float
final public static verify ( void ) : 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.

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)


Returns an integer describing the backend used by libev

  • « Ev
  • Ev::depth »
  • PHP Manual
  • Ev
  • Returns an integer describing the backend used by libev

Ev::backend

(PECL ev >= 0.2.0)

Ev::backend — Returns an integer describing the backend used by libev

Description

final public static Ev::backend ( void ) : 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


Returns recursion depth

  • « Ev::backend
  • Ev::embeddableBackends »
  • PHP Manual
  • Ev
  • Returns recursion depth

Ev::depth

(PECL ev >= 0.2.0)

Ev::depth — Returns recursion depth

Description

final public static Ev::depth ( void ) : 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


Returns the set of backends that are embeddable in other event loops

  • « Ev::depth
  • Ev::feedSignal »
  • PHP Manual
  • Ev
  • Returns the set of backends that are embeddable in other event loops

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 ( void ) : 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


Feed a signal event info Ev

  • « Ev::embeddableBackends
  • Ev::feedSignalEvent »
  • PHP Manual
  • Ev
  • Feed a signal event info Ev

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


Feed signal event into the default loop

  • « Ev::feedSignal
  • Ev::iteration »
  • PHP Manual
  • Ev
  • 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


Return the number of times the default event loop has polled for new events

  • « Ev::feedSignalEvent
  • Ev::now »
  • PHP Manual
  • Ev
  • Return the number of times the default event loop has polled for new events

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 ( void ) : 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


Returns the time when the last iteration of the default event loop has started

  • « Ev::iteration
  • Ev::nowUpdate »
  • PHP Manual
  • Ev
  • Returns the time when the last iteration of the default event loop has started

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 ( void ) : 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


Establishes the current time by querying the kernel, updating the time returned by Ev::now in the progress

  • « Ev::now
  • Ev::recommendedBackends »
  • PHP Manual
  • Ev
  • 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 ) : 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


Returns a bit mask of recommended backends for current platform

  • « Ev::nowUpdate
  • Ev::resume »
  • PHP Manual
  • Ev
  • Returns a bit mask of recommended backends for current platform

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 ( void ) : 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


Resume previously suspended default event loop

  • « Ev::recommendedBackends
  • Ev::run »
  • PHP Manual
  • Ev
  • Resume previously suspended default event loop

Ev::resume

(PECL ev >= 0.2.0)

Ev::resume — Resume previously suspended default event loop

Description

final public static Ev::resume ( void ) : 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


Begin checking for events and calling callbacks for the default loop

  • « Ev::resume
  • Ev::sleep »
  • PHP Manual
  • Ev
  • Begin checking for events and calling callbacks for the default 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


Block the process for the given number of seconds

  • « Ev::run
  • Ev::stop »
  • PHP Manual
  • Ev
  • Block the process for the given number of seconds

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.


Stops the default event loop

  • « Ev::sleep
  • Ev::supportedBackends »
  • PHP Manual
  • Ev
  • Stops the default event loop

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


Returns the set of backends supported by current libev configuration

  • « Ev::stop
  • Ev::suspend »
  • PHP Manual
  • Ev
  • Returns the set of backends supported by current libev configuration

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 ( void ) : 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


Suspend the default event loop

  • « Ev::supportedBackends
  • Ev::time »
  • PHP Manual
  • Ev
  • Suspend the default event loop

Ev::suspend

(PECL ev >= 0.2.0)

Ev::suspend — Suspend the default event loop

Description

final public static Ev::suspend ( void ) : 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


Returns the current time in fractional seconds since the epoch

  • « Ev::suspend
  • Ev::verify »
  • PHP Manual
  • Ev
  • Returns the current time in fractional seconds since the epoch

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 ( void ) : 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


Performs internal consistency checks(for debugging)

  • « Ev::time
  • EvCheck »
  • PHP Manual
  • Ev
  • Performs internal consistency checks(for debugging)

Ev::verify

(PECL ev >= 0.2.0)

Ev::verify — Performs internal consistency checks(for debugging)

Description

final public static Ev::verify ( void ) : 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.


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

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 ( void ) : int
abstract public EvWatcher::__construct ( void )
public EvWatcher::feed ( int $revents ) : void
public EvWatcher::getLoop ( void ) : EvLoop
public EvWatcher::invoke ( int $revents ) : void
public EvWatcher::keepalive ([ bool $value ] ) : bool
public EvWatcher::setCallback ( callable $callback ) : void
public EvWatcher::start ( void ) : void
public EvWatcher::stop ( void ) : void
}

Table of Contents

  • EvCheck::__construct — Constructs the EvCheck watcher object
  • EvCheck::createStopped — Create instance of a stopped EvCheck watcher


Constructs the EvCheck watcher object

  • « EvCheck
  • EvCheck::createStopped »
  • PHP Manual
  • EvCheck
  • Constructs the EvCheck watcher object

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

Return Values

Returns EvCheck object on success.

See Also

  • EvPrepare
  • EvLoop::check() - Creates EvCheck object associated with the current event loop instance


Create instance of a stopped EvCheck watcher

  • « EvCheck::__construct
  • EvChild »
  • PHP Manual
  • EvCheck
  • Create instance of a stopped EvCheck watcher

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


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

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 ( void ) : int
abstract public EvWatcher::__construct ( void )
public EvWatcher::feed ( int $revents ) : void
public EvWatcher::getLoop ( void ) : EvLoop
public EvWatcher::invoke ( int $revents ) : void
public EvWatcher::keepalive ([ bool $value ] ) : bool
public EvWatcher::setCallback ( callable $callback ) : void
public EvWatcher::start ( void ) : void
public EvWatcher::stop ( void ) : 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 .

Table of Contents

  • EvChild::__construct — Constructs the EvChild watcher object
  • EvChild::createStopped — Create instance of a stopped EvCheck watcher
  • EvChild::set — Configures the watcher


Constructs the EvChild watcher object

  • « EvChild
  • EvChild::createStopped »
  • PHP Manual
  • EvChild
  • Constructs the EvChild watcher object

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

Return Values

Returns EvChild object on success.

See Also

  • EvLoop::child() - Creates EvChild object associated with the current event loop


Create instance of a stopped EvCheck watcher

  • « EvChild::__construct
  • EvChild::set »
  • PHP Manual
  • EvChild
  • Create instance of a stopped EvCheck watcher

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


Configures the watcher

  • « EvChild::createStopped
  • EvEmbed »
  • PHP Manual
  • EvChild
  • Configures the watcher

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


The EvEmbed class

(PECL ev >= 0.2.0)

Introduction

Used to embed one event loop into another.

Class synopsis

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 ) : void
/* Inherited methods */
public EvWatcher::clear ( void ) : int
abstract public EvWatcher::__construct ( void )
public EvWatcher::feed ( int $revents ) : void
public EvWatcher::getLoop ( void ) : EvLoop
public EvWatcher::invoke ( int $revents ) : void
public EvWatcher::keepalive ([ bool $value ] ) : bool
public EvWatcher::setCallback ( callable $callback ) : void
public EvWatcher::start ( void ) : void
public EvWatcher::stop ( void ) : void
}

Properties

is_active

data

is_pending

priority

embed

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


Constructs the EvEmbed object

  • « EvEmbed
  • EvEmbed::createStopped »
  • PHP Manual
  • EvEmbed
  • Constructs the EvEmbed object

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

Return Values

Returns EvEmbed object on success.

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


Create stopped EvEmbed watcher object

  • « EvEmbed::__construct
  • EvEmbed::set »
  • PHP Manual
  • EvEmbed
  • Create stopped EvEmbed watcher object

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


Configures the watcher

  • « EvEmbed::createStopped
  • EvEmbed::sweep »
  • PHP Manual
  • EvEmbed
  • Configures the watcher

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.


Make a single, non-blocking sweep over the embedded loop

  • « EvEmbed::set
  • EvFork »
  • PHP Manual
  • EvEmbed
  • Make a single, non-blocking sweep over the embedded loop

EvEmbed::sweep

(PECL ev >= 0.2.0)

EvEmbed::sweep — Make a single, non-blocking sweep over the embedded loop

Description

public EvEmbed::sweep ( void ) : 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


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

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 ( void ) : int
abstract public EvWatcher::__construct ( void )
public EvWatcher::feed ( int $revents ) : void
public EvWatcher::getLoop ( void ) : EvLoop
public EvWatcher::invoke ( int $revents ) : void
public EvWatcher::keepalive ([ bool $value ] ) : bool
public EvWatcher::setCallback ( callable $callback ) : void
public EvWatcher::start ( void ) : void
public EvWatcher::stop ( void ) : void
}

Table of Contents

  • EvFork::__construct — Constructs the EvFork watcher object
  • EvFork::createStopped — Creates a stopped instance of EvFork watcher class


Constructs the EvFork watcher object

  • « EvFork
  • EvFork::createStopped »
  • PHP Manual
  • EvFork
  • Constructs the EvFork watcher object

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

Return Values

Returns EvFork object on success.

See Also

  • EvLoop::fork() - Creates EvFork watcher object associated with the current event loop instance
  • EvCheck


Creates a stopped instance of EvFork watcher class

  • « EvFork::__construct
  • EvIdle »
  • PHP Manual
  • EvFork
  • Creates a stopped instance of EvFork watcher class

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


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

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 ( void ) : int
abstract public EvWatcher::__construct ( void )
public EvWatcher::feed ( int $revents ) : void
public EvWatcher::getLoop ( void ) : EvLoop
public EvWatcher::invoke ( int $revents ) : void
public EvWatcher::keepalive ([ bool $value ] ) : bool
public EvWatcher::setCallback ( callable $callback ) : void
public EvWatcher::start ( void ) : void
public EvWatcher::stop ( void ) : void
}

Table of Contents

  • EvIdle::__construct — Constructs the EvIdle watcher object
  • EvIdle::createStopped — Creates instance of a stopped EvIdle watcher object


Constructs the EvIdle watcher object

  • « EvIdle
  • EvIdle::createStopped »
  • PHP Manual
  • EvIdle
  • Constructs the EvIdle watcher object

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

Return Values

Returns EvIdle object on success.

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


Creates instance of a stopped EvIdle watcher object

  • « EvIdle::__construct
  • EvIo »
  • PHP Manual
  • EvIdle
  • Creates instance of a stopped EvIdle watcher object

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


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

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 ( void ) : int
abstract public EvWatcher::__construct ( void )
public EvWatcher::feed ( int $revents ) : void
public EvWatcher::getLoop ( void ) : EvLoop
public EvWatcher::invoke ( int $revents ) : void
public EvWatcher::keepalive ([ bool $value ] ) : bool
public EvWatcher::setCallback ( callable $callback ) : void
public EvWatcher::start ( void ) : void
public EvWatcher::stop ( void ) : void
}

Properties

fd

events

Table of Contents

  • EvIo::__construct — Constructs EvIo watcher object
  • EvIo::createStopped — Create stopped EvIo watcher object
  • EvIo::set — Configures the watcher


Constructs EvIo watcher object

  • « EvIo
  • EvIo::createStopped »
  • PHP Manual
  • EvIo
  • Constructs EvIo watcher object

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

Return Values

Returns EvIo object on success.

See Also

  • EvIo::createStopped() - Create stopped EvIo watcher object
  • EvLoop::io() - Create EvIo watcher object associated with the current event loop instance


Create stopped EvIo watcher object

  • « EvIo::__construct
  • EvIo::set »
  • PHP Manual
  • EvIo
  • Create stopped EvIo watcher object

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


Configures the watcher

  • « EvIo::createStopped
  • EvLoop »
  • PHP Manual
  • EvIo
  • Configures the watcher

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.


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 EvLoop {
/* Properties */
public $data ;
public $backend ;
public $is_default_loop ;
public $iteration ;
public $pending ;
public $io_interval ;
public $timeout_interval ;
public $depth ;
/* Methods */
public backend ( void ) : 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 __construct ([ int $flags [, mixed $data = NULL [, float $io_interval = 0.0 [, float $timeout_interval = 0.0 ]]]] )
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 ) : void
final public io ( mixed $fd , int $events , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] ) : EvIo
public loopFork ( void ) : void
public now ( void ) : float
public nowUpdate ( void ) : 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 ) : 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 ) : void
final public timer ( float $after , float $repeat , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] ) : EvTimer
public verify ( void ) : 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() .

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)


Returns an integer describing the backend used by libev

  • « EvLoop
  • EvLoop::check »
  • PHP Manual
  • EvLoop
  • Returns an integer describing the backend used by libev

EvLoop::backend

(PECL ev >= 0.2.0)

EvLoop::backend — Returns an integer describing the backend used by libev

Description

public EvLoop::backend ( void ) : 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


Creates EvCheck object associated with the current event loop instance

  • « EvLoop::backend
  • EvLoop::child »
  • PHP Manual
  • EvLoop
  • Creates EvCheck object associated with the current event loop instance

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


Creates EvChild object associated with the current event loop

  • « EvLoop::check
  • EvLoop::__construct »
  • PHP Manual
  • EvLoop
  • Creates EvChild object associated with the current event loop

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


Constructs the event loop object

  • « EvLoop::child
  • EvLoop::defaultLoop »
  • PHP Manual
  • EvLoop
  • Constructs the event loop 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

Return Values

Returns new EvLoop object.

See Also

  • EvLoop::defaultLoop() - Returns or creates the default event loop


Returns or creates the default event loop

  • « EvLoop::__construct
  • EvLoop::embed »
  • PHP Manual
  • EvLoop
  • 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


Creates an instance of EvEmbed watcher associated with the current EvLoop object

  • « EvLoop::defaultLoop
  • EvLoop::fork »
  • PHP Manual
  • EvLoop
  • Creates an instance of EvEmbed watcher associated with the current EvLoop 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


Creates EvFork watcher object associated with the current event loop instance

  • « EvLoop::embed
  • EvLoop::idle »
  • PHP Manual
  • EvLoop
  • Creates EvFork watcher object associated with the current event loop instance

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


Creates EvIdle watcher object associated with the current event loop instance

  • « EvLoop::fork
  • EvLoop::invokePending »
  • PHP Manual
  • EvLoop
  • Creates EvIdle watcher object associated with the current event loop instance

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


Invoke all pending watchers while resetting their pending state

  • « EvLoop::idle
  • EvLoop::io »
  • PHP Manual
  • EvLoop
  • Invoke all pending watchers while resetting their pending state

EvLoop::invokePending

(PECL ev >= 0.2.0)

EvLoop::invokePending — Invoke all pending watchers while resetting their pending state

Description

public EvLoop::invokePending ( void ) : void

Invoke all pending watchers while resetting their pending state.

Parameters

This function has no parameters.

Return Values

No value is returned.


Create EvIo watcher object associated with the current event loop instance

  • « EvLoop::invokePending
  • EvLoop::loopFork »
  • PHP Manual
  • EvLoop
  • Create EvIo watcher object associated with the current event loop instance

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


Must be called after a fork

  • « EvLoop::io
  • EvLoop::now »
  • PHP Manual
  • EvLoop
  • Must be called after a fork

EvLoop::loopFork

(PECL ev >= 0.2.0)

EvLoop::loopFork — Must be called after a fork

Description

public EvLoop::loopFork ( void ) : 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.


Returns the current "event loop time"

  • « EvLoop::loopFork
  • EvLoop::nowUpdate »
  • PHP Manual
  • EvLoop
  • Returns the current "event loop time"

EvLoop::now

(PECL ev >= 0.2.0)

EvLoop::now — Returns the current "event loop time"

Description

public EvLoop::now ( void ) : 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


Establishes the current time by querying the kernel, updating the time returned by EvLoop::now in the progress

  • « EvLoop::now
  • EvLoop::periodic »
  • PHP Manual
  • EvLoop
  • Establishes the current time by querying the kernel, updating the time returned by EvLoop::now in the progress

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 ) : 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


Creates EvPeriodic watcher object associated with the current event loop instance

  • « EvLoop::nowUpdate
  • EvLoop::prepare »
  • PHP Manual
  • EvLoop
  • Creates EvPeriodic watcher object associated with the current event loop instance

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


Creates EvPrepare watcher object associated with the current event loop instance

  • « EvLoop::periodic
  • EvLoop::resume »
  • PHP Manual
  • EvLoop
  • Creates EvPrepare watcher object associated with the current event loop instance

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


Resume previously suspended default event loop

  • « EvLoop::prepare
  • EvLoop::run »
  • PHP Manual
  • EvLoop
  • Resume previously suspended default event loop

EvLoop::resume

(PECL ev >= 0.2.0)

EvLoop::resume — Resume previously suspended default event loop

Description

public EvLoop::resume ( void ) : 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


Begin checking for events and calling callbacks for the loop

  • « EvLoop::resume
  • EvLoop::signal »
  • PHP Manual
  • EvLoop
  • Begin checking for events and calling callbacks for the 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


Creates EvSignal watcher object associated with the current event loop instance

  • « EvLoop::run
  • EvLoop::stat »
  • PHP Manual
  • EvLoop
  • Creates EvSignal watcher object associated with the current event loop instance

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


Creates EvStat watcher object associated with the current event loop instance

  • « EvLoop::signal
  • EvLoop::stop »
  • PHP Manual
  • EvLoop
  • Creates EvStat watcher object associated with the current event loop instance

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


Stops the event loop

  • « EvLoop::stat
  • EvLoop::suspend »
  • PHP Manual
  • EvLoop
  • Stops the event loop

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


Suspend the loop

  • « EvLoop::stop
  • EvLoop::timer »
  • PHP Manual
  • EvLoop
  • Suspend the loop

EvLoop::suspend

(PECL ev >= 0.2.0)

EvLoop::suspend — Suspend the loop

Description

public EvLoop::suspend ( void ) : 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


Creates EvTimer watcher object associated with the current event loop instance

  • « EvLoop::suspend
  • EvLoop::verify »
  • PHP Manual
  • EvLoop
  • Creates EvTimer watcher object associated with the current event loop instance

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


Performs internal consistency checks(for debugging)

  • « EvLoop::timer
  • EvPeriodic »
  • PHP Manual
  • EvLoop
  • Performs internal consistency checks(for debugging)

EvLoop::verify

(PECL ev >= 0.2.0)

EvLoop::verify — Performs internal consistency checks(for debugging)

Description

public EvLoop::verify ( void ) : 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)


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

EvPeriodic extends EvWatcher {
/* Properties */
public $offset ;
public $interval ;
/* Inherited properties */
public $is_active ;
public $data ;
public $is_pending ;
public $priority ;
/* Methods */
public again ( void ) : void
public at ( void ) : float
public __construct ( float $offset , string $interval , callable $reschedule_cb , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
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 ( void ) : int
abstract public EvWatcher::__construct ( void )
public EvWatcher::feed ( int $revents ) : void
public EvWatcher::getLoop ( void ) : EvLoop
public EvWatcher::invoke ( int $revents ) : void
public EvWatcher::keepalive ([ bool $value ] ) : bool
public EvWatcher::setCallback ( callable $callback ) : void
public EvWatcher::start ( void ) : void
public EvWatcher::stop ( void ) : 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.

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


Simply stops and restarts the periodic watcher again

  • « EvPeriodic
  • EvPeriodic::at »
  • PHP Manual
  • EvPeriodic
  • Simply stops and restarts the periodic watcher again

EvPeriodic::again

(PECL ev >= 0.2.0)

EvPeriodic::again — Simply stops and restarts the periodic watcher again

Description

public EvPeriodic::again ( void ) : 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


Returns the absolute time that this watcher is supposed to trigger next

  • « EvPeriodic::again
  • EvPeriodic::__construct »
  • PHP Manual
  • EvPeriodic
  • Returns the absolute time that this watcher is supposed to trigger next

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 ( void ) : 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.


Constructs EvPeriodic watcher object

  • « EvPeriodic::at
  • EvPeriodic::createStopped »
  • PHP Manual
  • EvPeriodic
  • Constructs EvPeriodic watcher object

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

Return Values

Returns EvPeriodic object on success.

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


Create a stopped EvPeriodic watcher

  • « EvPeriodic::__construct
  • EvPeriodic::set »
  • PHP Manual
  • EvPeriodic
  • 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


Configures the watcher

  • « EvPeriodic::createStopped
  • EvPrepare »
  • PHP Manual
  • EvPeriodic
  • Configures the watcher

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.


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

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 ( void ) : int
abstract public EvWatcher::__construct ( void )
public EvWatcher::feed ( int $revents ) : void
public EvWatcher::getLoop ( void ) : EvLoop
public EvWatcher::invoke ( int $revents ) : void
public EvWatcher::keepalive ([ bool $value ] ) : bool
public EvWatcher::setCallback ( callable $callback ) : void
public EvWatcher::start ( void ) : void
public EvWatcher::stop ( void ) : void
}

Table of Contents

  • EvPrepare::__construct — Constructs EvPrepare watcher object
  • EvPrepare::createStopped — Creates a stopped instance of EvPrepare watcher


Constructs EvPrepare watcher object

  • « EvPrepare
  • EvPrepare::createStopped »
  • PHP Manual
  • EvPrepare
  • Constructs EvPrepare watcher object

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

Return Values

Returns EvPrepare object on success.

See Also

  • EvCheck


Creates a stopped instance of EvPrepare watcher

  • « EvPrepare::__construct
  • EvSignal »
  • PHP Manual
  • EvPrepare
  • Creates a stopped instance of EvPrepare watcher

EvPrepare::createStopped

(PECL ev >= 0.2.0)

EvPrepare::createStopped — Creates a stopped instance of EvPrepare watcher

Description

final public static EvPrepare::createStopped ( callable $callback [, mixed $data = NULL [, int $priority = 0 ]] ) : EvPrepare

Creates a stopped instance of EvPrepare watcher. Unlike EvPrepare::__construct() , this method doesn' start the watcher automatically.

Parameters

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Return Values

Return EvPrepare object on success.

See Also

  • EvPrepare::__construct() - Constructs EvPrepare watcher object
  • EvWatcher::start() - Starts the watcher


The EvSignal class

(PECL ev >= 0.2.0)

Introduction

EvSignal watchers will trigger an event when the process receives a specific signal one or more times. Even though signals are very asynchronous, libev will try its best to deliver signals synchronously, i.e. as part of the normal event processing, like any other event.

There is no limit for the number of watchers for the same signal, but only within the same loop, i.e. one can watch for SIGINT in the default loop and for SIGIO in another loop, but it is not allowed to watch for SIGINT in both the default loop and another loop at the same time. At the moment, SIGCHLD is permanently tied to the default loop.

If possible and supported, libev will install its handlers with SA_RESTART (or equivalent) behaviour enabled, so system calls should not be unduly interrupted. In case of a problem with system calls getting interrupted by signals, all the signals can be blocked in an EvCheck watcher and unblocked in a EvPrepare watcher.

Class synopsis

EvSignal extends EvWatcher {
/* Properties */
public $signum ;
/* Inherited properties */
public $is_active ;
public $data ;
public $is_pending ;
public $priority ;
/* Methods */
public __construct ( int $signum , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
final public static createStopped ( int $signum , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] ) : EvSignal
public set ( int $signum ) : void
/* Inherited methods */
public EvWatcher::clear ( void ) : int
abstract public EvWatcher::__construct ( void )
public EvWatcher::feed ( int $revents ) : void
public EvWatcher::getLoop ( void ) : EvLoop
public EvWatcher::invoke ( int $revents ) : void
public EvWatcher::keepalive ([ bool $value ] ) : bool
public EvWatcher::setCallback ( callable $callback ) : void
public EvWatcher::start ( void ) : void
public EvWatcher::stop ( void ) : void
}

Properties

signum

Signal number. See the constants exported by pcntl extension. See also signal(7) man page.

Table of Contents

  • EvSignal::__construct — Constructs EvSignal watcher object
  • EvSignal::createStopped — Create stopped EvSignal watcher object
  • EvSignal::set — Configures the watcher


Constructs EvSignal watcher object

  • « EvSignal
  • EvSignal::createStopped »
  • PHP Manual
  • EvSignal
  • Constructs EvSignal watcher object

EvSignal::__construct

(PECL ev >= 0.2.0)

EvSignal::__construct — Constructs EvSignal watcher object

Description

public EvSignal::__construct ( int $signum , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Constructs EvSignal watcher object and starts it automatically. For a stopped periodic watcher consider using EvSignal::createStopped() method.

Parameters

signum

Signal number. See constants exported by pcntl extension. See also signal(7) man page.

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Return Values

Returns EvSignal object on success.

Examples

Example #1 Handle SIGTERM signal

<?php
$w = new EvSignal(SIGTERM, function ($watcher) {
    echo "SIGTERM received\n";
    $watcher->stop();
});

Ev::run();
?>

See Also

  • EvSignal::createStopped() - Create stopped EvSignal watcher object


Create stopped EvSignal watcher object

  • « EvSignal::__construct
  • EvSignal::set »
  • PHP Manual
  • EvSignal
  • Create stopped EvSignal watcher object

EvSignal::createStopped

(PECL ev >= 0.2.0)

EvSignal::createStopped — Create stopped EvSignal watcher object

Description

final public static EvSignal::createStopped ( int $signum , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] ) : EvSignal

Create stopped EvSignal watcher object. Unlike EvSignal::__construct() , this method does't start the watcher automatically.

Parameters

signum

Signal number. See constants exported by pcntl extension. See also signal(7) man page.

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Return Values

Returns EvSignal object on success.

See Also

  • EvWatcher::start() - Starts the watcher
  • EvSignal::__construct() - Constructs EvSignal watcher object


Configures the watcher

  • « EvSignal::createStopped
  • EvStat »
  • PHP Manual
  • EvSignal
  • Configures the watcher

EvSignal::set

(PECL ev >= 0.2.0)

EvSignal::set — Configures the watcher

Description

public EvSignal::set ( int $signum ) : void

Configures the watcher.

Parameters

signum

Signal number. The same as for EvSignal::__construct()

Return Values

No value is returned.


The EvStat class

(PECL ev >= 0.2.0)

Introduction

EvStat monitors a file system path for attribute changes. It calls stat() on that path in regular intervals(or when the OS signals it changed) and sees if it changed compared to the last time, invoking the callback if it did.

The path does not need to exist: changing from "path exists" to "path does not exist" is a status change like any other. The condition "path does not exist" is signified by the 'nlink' item being 0(returned by EvStat::attr() method).

The path must not end in a slash or contain special components such as '.' or .. . The path should be absolute: if it is relative and the working directory changes, then the behaviour is undefined.

Since there is no portable change notification interface available, the portable implementation simply calls stat() regularly on the path to see if it changed somehow. For this case a recommended polling interval can be specified. If one specifies a polling interval of 0.0 (highly recommended) then a suitable, unspecified default value will be used(which could be expected to be around 5 seconds, although this might change dynamically). libev will also impose a minimum interval which is currently around 0.1 , but that’s usually overkill.

This watcher type is not meant for massive numbers of EvStat watchers, as even with OS-supported change notifications, this can be resource-intensive.

Class synopsis

EvStat extends EvWatcher {
/* Properties */
public $path ;
public $interval ;
/* Inherited properties */
public $is_active ;
public $data ;
public $is_pending ;
public $priority ;
/* Methods */
public attr ( void ) : array
public __construct ( string $path , float $interval , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
final public static createStopped ( string $path , float $interval , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] ) : void
public prev ( void ) : void
public set ( string $path , float $interval ) : void
public stat ( void ) : bool
/* Inherited methods */
public EvWatcher::clear ( void ) : int
abstract public EvWatcher::__construct ( void )
public EvWatcher::feed ( int $revents ) : void
public EvWatcher::getLoop ( void ) : EvLoop
public EvWatcher::invoke ( int $revents ) : void
public EvWatcher::keepalive ([ bool $value ] ) : bool
public EvWatcher::setCallback ( callable $callback ) : void
public EvWatcher::start ( void ) : void
public EvWatcher::stop ( void ) : void
}

Properties

interval

Readonly . Hint on how quickly a change is expected to be detected and should normally be specified as 0.0 to let libev choose a suitable value.

path

Readonly . The path to wait for status changes on.

Table of Contents

  • EvStat::attr — Returns the values most recently detected by Ev
  • EvStat::__construct — Constructs EvStat watcher object
  • EvStat::createStopped — Create a stopped EvStat watcher object
  • EvStat::prev — Returns the previous set of values returned by EvStat::attr
  • EvStat::set — Configures the watcher
  • EvStat::stat — Initiates the stat call


Returns the values most recently detected by Ev

  • « EvStat
  • EvStat::__construct »
  • PHP Manual
  • EvStat
  • Returns the values most recently detected by Ev

EvStat::attr

(PECL ev >= 0.2.0)

EvStat::attr — Returns the values most recently detected by Ev

Description

public EvStat::attr ( void ) : array

Returns array of the values most recently detected by Ev

Parameters

This function has no parameters.

Return Values

Returns array with the values most recently detect by Ev(without actual stat 'ing):

List for item keys of the array returned by EvStat::attr()
Key | Description
'dev' | ID of device containing file
'ino' | inode number
'mode' | protection
'nlink' | number of hard links
'uid' | user ID of owner
'size' | total size, in bytes
'gid' | group ID of owner
'rdev' | device ID (if special file)
'blksize' | blocksize for file system I/O
'blocks' | number of 512B blocks allocated
'atime' | time of last access
'ctime' | time of last status change
'mtime' | time of last modification

See stat(2) man page for details.

Examples

Example #1 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();
?>

See Also

  • EvStat::prev() - Returns the previous set of values returned by EvStat::attr
  • EvStat::stat() - Initiates the stat call


Constructs EvStat watcher object

  • « EvStat::attr
  • EvStat::createStopped »
  • PHP Manual
  • EvStat
  • Constructs EvStat watcher object

EvStat::__construct

(PECL ev >= 0.2.0)

EvStat::__construct — Constructs EvStat watcher object

Description

public EvStat::__construct ( string $path , float $interval , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Constructs EvStat watcher object and starts the watcher automatically.

Parameters

path

The path to wait for status changes on.

interval

Hint on how quickly a change is expected to be detected and should normally be specified as 0.0 to let libev choose a suitable value.

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Return Values

Returns EvStat watcher object on succes.

Examples

Example #1 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();
?>


Create a stopped EvStat watcher object

  • « EvStat::__construct
  • EvStat::prev »
  • PHP Manual
  • EvStat
  • Create a stopped EvStat watcher object

EvStat::createStopped

(PECL ev >= 0.2.0)

EvStat::createStopped — Create a stopped EvStat watcher object

Description

final public static EvStat::createStopped ( string $path , float $interval , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] ) : void

Creates EvStat watcher object, but doesn't start it automatically(unlike EvStat::__construct() ).

Parameters

path

The path to wait for status changes on.

interval

Hint on how quickly a change is expected to be detected and should normally be specified as 0.0 to let libev choose a suitable value.

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Return Values

Returns a stopped EvStat watcher object on success.

See Also

  • EvStat::__construct() - Constructs EvStat watcher object
  • EvWatcher::start() - Starts the watcher


Returns the previous set of values returned by EvStat::attr

  • « EvStat::createStopped
  • EvStat::set »
  • PHP Manual
  • EvStat
  • Returns the previous set of values returned by EvStat::attr

EvStat::prev

(PECL ev >= 0.2.0)

EvStat::prev — Returns the previous set of values returned by EvStat::attr

Description

public EvStat::prev ( void ) : void

Just like EvStat::attr() , but returns the previous set of values.

Parameters

This function has no parameters.

Return Values

Returns an array with the same structure as the array returned by EvStat::attr() . The array contains previously detected values.

See Also

  • EvStat::attr() - Returns the values most recently detected by Ev
  • EvStat::stat() - Initiates the stat call


Configures the watcher

  • « EvStat::prev
  • EvStat::stat »
  • PHP Manual
  • EvStat
  • Configures the watcher

EvStat::set

(PECL ev >= 0.2.0)

EvStat::set — Configures the watcher

Description

public EvStat::set ( string $path , float $interval ) : void

Configures the watcher.

Parameters

path

The path to wait for status changes on.

interval

Hint on how quickly a change is expected to be detected and should normally be specified as 0.0 to let libev choose a suitable value.

Return Values

No value is returned.


Initiates the stat call

  • « EvStat::set
  • EvTimer »
  • PHP Manual
  • EvStat
  • Initiates the stat call

EvStat::stat

(PECL ev >= 0.2.0)

EvStat::stat — Initiates the stat call

Description

public EvStat::stat ( void ) : bool

Initiates the stat call(updates internal cache). It stats(using lstat ) the path specified in the watcher and sets to the values found.

Parameters

This function has no parameters.

Return Values

Returns TRUE if path exists. Otherwise FALSE.

See Also

  • EvStat::attr() - Returns the values most recently detected by Ev
  • EvStat::prev() - Returns the previous set of values returned by EvStat::attr


The EvTimer class

(PECL ev >= 0.2.0)

Introduction

EvTimer watchers are simple relative timers that generate an event after a given time, and optionally repeating in regular intervals after that.

The timers are based on real time, that is, if one registers an event that times out after an hour and resets the system clock to January last year , it will still time out after(roughly) one hour. "Roughly" because detecting time jumps is hard, and some inaccuracies are unavoidable.

The callback is guaranteed to be invoked only after its timeout has passed (not at, so on systems with very low-resolution clocks this might introduce a small delay). If multiple timers become ready during the same loop iteration then the ones with earlier time-out values are invoked before ones of the same priority with later time-out values (but this is no longer true when a callback calls EvLoop::run() recursively).

The timer itself will do a best-effort at avoiding drift, that is, if a timer is configured to trigger every 10 seconds, then it will normally trigger at exactly 10 second intervals. If, however, the script cannot keep up with the timer because it takes longer than those 10 seconds to do) the timer will not fire more than once per event loop iteration.

Class synopsis

EvTimer extends EvWatcher {
/* Properties */
public $repeat ;
public $remaining ;
/* Inherited properties */
public $is_active ;
public $data ;
public $is_pending ;
public $priority ;
/* Methods */
public again ( void ) : void
public __construct ( float $after , float $repeat , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )
final public static createStopped ( float $after , float $repeat , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] ) : EvTimer
public set ( float $after , float $repeat ) : void
/* Inherited methods */
public EvWatcher::clear ( void ) : int
abstract public EvWatcher::__construct ( void )
public EvWatcher::feed ( int $revents ) : void
public EvWatcher::getLoop ( void ) : EvLoop
public EvWatcher::invoke ( int $revents ) : void
public EvWatcher::keepalive ([ bool $value ] ) : bool
public EvWatcher::setCallback ( callable $callback ) : void
public EvWatcher::start ( void ) : void
public EvWatcher::stop ( void ) : void
}

Properties

repeat

If repeat is 0.0 , then it will automatically be stopped once the timeout is reached. If it is positive, then the timer will automatically be configured to trigger again every repeat seconds later, until stopped manually.

remaining

Returns the remaining time until a timer fires. If the timer is active, then this time is relative to the current event loop time, otherwise it's the timeout value currently configured.

That is, after instanciating an EvTimer with an after value of 5.0 and repeat value of 7.0 , remaining returns 5.0 . When the timer is started and one second passes, remaining will return 4.0 . When the timer expires and is restarted, it will return roughly 7.0 (likely slightly less as callback invocation takes some time too), and so on.

Table of Contents

  • EvTimer::again — Restarts the timer watcher
  • EvTimer::__construct — Constructs an EvTimer watcher object
  • EvTimer::createStopped — Creates EvTimer stopped watcher object
  • EvTimer::set — Configures the watcher


Restarts the timer watcher

  • « EvTimer
  • EvTimer::__construct »
  • PHP Manual
  • EvTimer
  • Restarts the timer watcher

EvTimer::again

(PECL ev >= 0.2.0)

EvTimer::again — Restarts the timer watcher

Description

public EvTimer::again ( void ) : void

This will act as if the timer timed out and restart it again if it is repeating. The exact semantics are:

  1. if the timer is pending, its pending status is cleared.

  2. if the timer is started but non-repeating, stop it (as if it timed out).

  3. if the timer is repeating, either start it if necessary (with the repeat value), or reset the running timer to the repeat value.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • EvWatcher::stop() - Stops the watcher


Constructs an EvTimer watcher object

  • « EvTimer::again
  • EvTimer::createStopped »
  • PHP Manual
  • EvTimer
  • Constructs an EvTimer watcher object

EvTimer::__construct

(PECL ev >= 0.2.0)

EvTimer::__construct — Constructs an EvTimer watcher object

Description

public EvTimer::__construct ( float $after , float $repeat , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] )

Constructs an EvTimer watcher object.

Parameters

after

Configures the timer to trigger after after seconds.

repeat

If repeat is 0.0 , then it will automatically be stopped once the timeout is reached. If it is positive, then the timer will automatically be configured to trigger again every repeat seconds later, until stopped manually.

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Return Values

Returns EvTimer object on success.

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

See Also

  • EvTimer::createStopped() - Creates EvTimer stopped watcher object
  • EvPeriodic
  • » ev_timer - relative and optionally repeating timeouts
  • » Be smart about timeouts


Creates EvTimer stopped watcher object

  • « EvTimer::__construct
  • EvTimer::set »
  • PHP Manual
  • EvTimer
  • Creates EvTimer stopped watcher object

EvTimer::createStopped

(PECL ev >= 0.2.0)

EvTimer::createStopped — Creates EvTimer stopped watcher object

Description

final public static EvTimer::createStopped ( float $after , float $repeat , callable $callback [, mixed $data = NULL [, int $priority = 0 ]] ) : EvTimer

Creates EvTimer stopped watcher object. Unlike EvTimer::__construct() , this method doesn't start the watcher automatically.

Parameters

after

Configures the timer to trigger after after seconds.

repeat

If repeat is 0.0 , then it will automatically be stopped once the timeout is reached. If it is positive, then the timer will automatically be configured to trigger again every repeat seconds later, until stopped manually.

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

Return Values

Returns EvTimer watcher object on success.

Examples

Example #1 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();
?>

See Also

  • EvTimer::__construct() - Constructs an EvTimer watcher object
  • EvPeriodic


Configures the watcher

  • « EvTimer::createStopped
  • EvWatcher »
  • PHP Manual
  • EvTimer
  • Configures the watcher

EvTimer::set

(PECL ev >= 0.2.0)

EvTimer::set — Configures the watcher

Description

public EvTimer::set ( float $after , float $repeat ) : void

Configures the watcher

Parameters

after

Configures the timer to trigger after after seconds.

repeat

If repeat is 0.0 , then it will automatically be stopped once the timeout is reached. If it is positive, then the timer will automatically be configured to trigger again every repeat seconds later, until stopped manually.

Return Values

No value is returned.


The EvWatcher class

(PECL ev >= 0.2.0)

Introduction

EvWatcher is a base class for all watchers( EvCheck , EvChild etc.). Since EvWatcher 's constructor is abstract , one can't(and don't need to) create EvWatcher objects directly.

Class synopsis

abstract EvWatcher {
/* Properties */
public $is_active ;
public $data ;
public $is_pending ;
public $priority ;
/* Methods */
public clear ( void ) : int
abstract public __construct ( void )
public feed ( int $revents ) : void
public getLoop ( void ) : EvLoop
public invoke ( int $revents ) : void
public keepalive ([ bool $value ] ) : bool
public setCallback ( callable $callback ) : void
public start ( void ) : void
public stop ( void ) : void
}

Properties

is_active

Readonly . TRUE if the watcher is active. FALSE otherwise.

data

User custom data associated with the watcher

is_pending

Readonly .TRUE if the watcher is pending, i.e. it has outstanding events, but its callback has not yet been invoked. FALSE otherwise. As long, as a watcher is pending(but not active), one must not change its priority.

priority

Integer between Ev::MINPRI and Ev::MAXPRI . Pending watchers with higher priority will be invoked before watchers with lower priority, but priority will not keep watchers from being executed(except for EvIdle watchers). EvIdle watchers provide functionality to suppress invocation when higher priority events are pending.

Table of Contents

  • EvWatcher::clear — Clear watcher pending status
  • EvWatcher::__construct — Abstract constructor of a watcher object
  • EvWatcher::feed — Feeds the given revents set into the event loop
  • EvWatcher::getLoop — Returns the loop responsible for the watcher
  • EvWatcher::invoke — Invokes the watcher callback with the given received events bit mask
  • EvWatcher::keepalive — Configures whether to keep the loop from returning
  • EvWatcher::setCallback — Sets new callback for the watcher
  • EvWatcher::start — Starts the watcher
  • EvWatcher::stop — Stops the watcher


Clear watcher pending status

  • « EvWatcher
  • EvWatcher::__construct »
  • PHP Manual
  • EvWatcher
  • Clear watcher pending status

EvWatcher::clear

(PECL ev >= 0.2.0)

EvWatcher::clear — Clear watcher pending status

Description

public EvWatcher::clear ( void ) : int

If the watcher is pending, this method clears its pending status and returns its revents bitset(as if its callback was invoked). If the watcher isn't pending it does nothing and returns 0 .

Sometimes it can be useful to "poll" a watcher instead of waiting for its callback to be invoked, which can be accomplished with this function.

Parameters

This function has no parameters.

Return Values

In case if the watcher is pending, returns revents bitset as if the watcher callback had been invoked. Otherwise returns 0 .


Abstract constructor of a watcher object

  • « EvWatcher::clear
  • EvWatcher::feed »
  • PHP Manual
  • EvWatcher
  • Abstract constructor of a watcher object

EvWatcher::__construct

(PECL ev >= 0.2.0)

EvWatcher::__construct — Abstract constructor of a watcher object

Description

abstract public EvWatcher::__construct ( void )

EvWatcher::__construct() is an abstract constructor of a watcher object implemented in the derived classes.


Feeds the given revents set into the event loop

  • « EvWatcher::__construct
  • EvWatcher::getLoop »
  • PHP Manual
  • EvWatcher
  • Feeds the given revents set into the event loop

EvWatcher::feed

(PECL ev >= 0.2.0)

EvWatcher::feed — Feeds the given revents set into the event loop

Description

public EvWatcher::feed ( int $revents ) : void

Feeds the given revents set into the event loop, as if the specified event had happened for the watcher.

Parameters

revents

Bit mask of watcher received events .

Return Values

No value is returned.


Returns the loop responsible for the watcher

  • « EvWatcher::feed
  • EvWatcher::invoke »
  • PHP Manual
  • EvWatcher
  • Returns the loop responsible for the watcher

EvWatcher::getLoop

(PECL ev >= 0.2.0)

EvWatcher::getLoop — Returns the loop responsible for the watcher

Description

public EvWatcher::getLoop ( void ) : EvLoop

Returns the loop responsible for the watcher

Parameters

This function has no parameters.

Return Values

Returns EvLoop event loop object responsible for the watcher.


Invokes the watcher callback with the given received events bit mask

  • « EvWatcher::getLoop
  • EvWatcher::keepalive »
  • PHP Manual
  • EvWatcher
  • Invokes the watcher callback with the given received events bit mask

EvWatcher::invoke

(PECL ev >= 0.2.0)

EvWatcher::invoke — Invokes the watcher callback with the given received events bit mask

Description

public EvWatcher::invoke ( int $revents ) : void

Invokes the watcher callback with the given received events bit mask.

Parameters

revents

Bit mask of watcher received events .

Return Values

No value is returned.


Configures whether to keep the loop from returning

  • « EvWatcher::invoke
  • EvWatcher::setCallback »
  • PHP Manual
  • EvWatcher
  • Configures whether to keep the loop from returning

EvWatcher::keepalive

(PECL ev >= 0.2.0)

EvWatcher::keepalive — Configures whether to keep the loop from returning

Description

public EvWatcher::keepalive ([ bool $value ] ) : bool

Configures whether to keep the loop from returning. With keepalive value set to FALSE the watcher won't keep Ev::run() / EvLoop::run() from returning even though the watcher is active.

Watchers have keepalive value TRUE by default.

Clearing keepalive status is useful when returning from Ev::run() / EvLoop::run() just because of the watcher is undesirable. It could be a long running UDP socket watcher or so.

Parameters

value

With keepalive value set to FALSE the watcher won't keep Ev::run() / EvLoop::run() from returning even though the watcher is active.

Return Values

Returns the previous state.

Examples

Example #1 Register an I/O watcher for some UDP socket but do not keep the event loop from running just because of that watcher.

<?php
$udp_socket = ...
$udp_watcher = new EvIo($udp_socket, Ev::READ, function () { /* ... */ });
$udp_watcher->keepalive(FALSE);
?>


Sets new callback for the watcher

  • « EvWatcher::keepalive
  • EvWatcher::start »
  • PHP Manual
  • EvWatcher
  • Sets new callback for the watcher

EvWatcher::setCallback

(PECL ev >= 0.2.0)

EvWatcher::setCallback — Sets new callback for the watcher

Description

public EvWatcher::setCallback ( callable $callback ) : void

Sets new callback for the watcher

Parameters

callback

See Watcher callbacks .

Return Values

No value is returned.


Starts the watcher

  • « EvWatcher::setCallback
  • EvWatcher::stop »
  • PHP Manual
  • EvWatcher
  • Starts the watcher

EvWatcher::start

(PECL ev >= 0.2.0)

EvWatcher::start — Starts the watcher

Description

public EvWatcher::start ( void ) : void

Marks the watcher as active. Note that only active watchers will receive events.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • EvWatcher::stop() - Stops the watcher


Stops the watcher

  • « EvWatcher::start
  • Expect »
  • PHP Manual
  • EvWatcher
  • Stops the watcher

EvWatcher::stop

(PECL ev >= 0.2.0)

EvWatcher::stop — Stops the watcher

Description

public EvWatcher::stop ( void ) : void

Marks the watcher as inactive. Note that only active watchers will receive events.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • EvWatcher::start() - Starts the watcher


Expect

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Expect Usage Examples
  • Expect Functions
    • expect_expectl — Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen
    • expect_popen — Execute command via Bourne shell, and open the PTY stream to the process


Introduction

This extension allows to interact with processes through PTY. You may consider using the expect:// wrapper with the filesystem functions which provide a simpler and more intuitive interface.


Requirements

This module uses the functions of the » expect library. You need libexpect version >= 5.43.0.


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/expect.

In order to use these functions you must compile PHP with expect support by using the --with-expect[=DIR] configure option.

Windows users will enable php_expect.dll inside of php.ini in order to use these functions. A DLL for this PECL extension is currently unavailable. See also the building on Windows section.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

In order to configure expect extension, there are configuration options in the configuration file php.ini.

Expect Configure Options
Name | Default | Changeable | Changelog
expect.timeout | "10" | PHP_INI_ALL |
expect.loguser | "1" | PHP_INI_ALL |
expect.logfile | "" | PHP_INI_ALL |
expect.match_max | "" | PHP_INI_ALL |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

expect.timeout integer

The timeout period for waiting for the data, when using the expect_expectl() function.

A value of "-1" disables a timeout from occurring.

Note:

A value of "0" causes the expect_expectl() function to return immediately.

expect.loguser boolean

Whether expect should send any output from the spawned process to stdout. Since interactive programs typically echo their input, this usually suffices to show both sides of the conversation.

expect.logfile string

Name of the file, where the output from the spawned process will be written. If this file doesn't exist, it will be created.

Note:

If this configuration is not empty, the output is written regardless of the value of expect.loguser.

expect.match_max integer

Changes default size (2000 bytes) of the buffer used to match asterisks in patterns.


  • « Runtime Configuration
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

expect_popen() returns an open PTY stream used by expect_expectl().


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.

EXP_GLOB (integer)
Indicates that the pattern is a glob-style string pattern.
EXP_EXACT (integer)
Indicates that the pattern is an exact string.
EXP_REGEXP (integer)
Indicates that the pattern is a regexp-style string pattern.
EXP_EOF (integer)
Value, returned by expect_expectl(), when EOF is reached.
EXP_TIMEOUT (integer)
Value, returned by expect_expectl() upon timeout of seconds, specified in value of expect.timeout
EXP_FULLBUFFER (integer)
Value, returned by expect_expectl() if no pattern have been matched.


  • « Predefined Constants
  • Expect Usage Examples »
  • PHP Manual
  • Expect
  • Examples

Examples

Table of Contents

  • Expect Usage Examples


Expect Usage Examples

Example #1 Expect Usage Example

This example connects to the remote host via SSH, and prints the remote uptime.

<?php
ini_set("expect.loguser", "Off");

$stream = fopen("expect://ssh root@remotehost uptime", "r");

$cases = array (
    array (0 => "password:", 1 => PASSWORD)
);

switch (expect_expectl ($stream, $cases)) {
    case PASSWORD:
        fwrite ($stream, "password\n");
        break;

    default:
        die ("Error was occurred while connecting to the remote host!\n");
}

while ($line = fgets($stream)) {
      print $line;
}
fclose ($stream);
?>

The following example connects to the remote host, determines whether installed OS is for 32 or 64 bit, then runs update for specific package.

Example #2 Another Expect Usage Example

<?php
ini_set("expect.timeout", -1);
ini_set("expect.loguser", "Off");

$stream = expect_popen("ssh root@remotehost");

while (true) {
    switch (expect_expectl ($stream, array (
            array ("password:", PASSWORD), // SSH is asking for password
            array ("yes/no)?", YESNO), // SSH is asking whether to store the host entry
            array ("~$ ", SHELL, EXP_EXACT), // We've got the shell!
    ))) {
        case PASSWORD:
            fwrite ($stream, "secret\n");
            break;

        case YESNO:
            fwrite ($stream, "yes\n");
            break;

        case SHELL:
            fwrite ($stream, "uname -a\n");
            while (true) {
                    switch (expect_expectl ($stream, array (
                            array ("~$ ", SHELL, EXP_EXACT), // We've got the shell!
                            array ("^Linux.*$", UNAME, EXP_REGEXP), // uname -a output
                    ), $match)) {
                        case UNAME:
                            $uname .= $match[0];
                            break;

                        case SHELL:
                            // Run update:
                            if (strstr ($uname, "x86_64")) {
                                    fwrite ($stream, "rpm -Uhv http://mirrorsite/somepath/some_64bit.rpm\n");
                            } else {
                                    fwrite ($stream, "rpm -Uhv http://mirrorsite/somepath/some_32bit.rpm\n");
                            }
                            fwrite ($stream, "exit\n");
                            break 2;

                        case EXP_TIMEOUT:
                        case EXP_EOF:
                            break 2;

                        default:
                            die ("Error has occurred!\n");
                    }
            }
            break 2;

        case EXP_TIMEOUT:
        case EXP_EOF:
            break 2;

        default:
            die ("Error has occurred!\n");
    }
}

fclose ($stream);
?>


Expect Functions

Table of Contents

  • expect_expectl — Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen
  • expect_popen — Execute command via Bourne shell, and open the PTY stream to the process


Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen

  • « Expect Functions
  • expect_popen »
  • PHP Manual
  • Expect Functions
  • Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen

expect_expectl

(PECL expect >= 0.1.0)

expect_expectl — Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen

Description

expect_expectl ( resource $expect , array $cases [, array &$match ] ) : int

Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen.

If match is provided, then it is filled with the result of search. The matched string can be found in match[0]. The match substrings (according to the parentheses) in the original pattern can be found in match[1], match[2], and so on, up to match[9] (the limitation of libexpect).

Parameters

expect

An Expect stream, previously opened with expect_popen().

cases

An array of expect cases. Each expect case is an indexed array, as described in the following table:

Expect Case Array
Index Key | Value Type | Description | Is Mandatory | Default Value
0 | string | pattern, that will be matched against the output from the stream | yes
1 | mixed | value, that will be returned by this function, if the pattern matches | yes
2 | integer | pattern type, one of: EXP_GLOB, EXP_EXACT or EXP_REGEXP | no | EXP_GLOB

Return Values

Returns value associated with the pattern that was matched.

On failure this function returns: EXP_EOF, EXP_TIMEOUT or EXP_FULLBUFFER

Changelog

Version | Description
0.2.1 | Prior to version 0.2.1, in match parameter a match string was returned, not an array of match substrings.

Examples

Example #1 expect_expectl() example

<?php
// Copies file from remote host:
ini_set("expect.timeout", 30);

$stream = fopen("expect://scp user@remotehost:/var/log/messages /home/user/messages.txt", "r");

$cases = array(
    // array(pattern, value to return if pattern matched)
    array("password:", "asked for password"),
    array("yes/no)?",  "asked for yes/no")
);

while (true) {
    switch (expect_expectl($stream, $cases)) {
        case "asked for password":
            fwrite($stream, "my password\n");
            break;
        case "asked for yes/no":
            fwrite($stream, "yes\n");
            break;
        case EXP_TIMEOUT:
        case EXP_EOF:
            break 2; // break both the switch statement and the while loop
        default:
            die "Error has occurred!";
    }
}

fclose($stream);
?>

See Also

  • expect_popen() - Execute command via Bourne shell, and open the PTY stream to the process


Execute command via Bourne shell, and open the PTY stream to the process

  • « expect_expectl
  • Libevent »
  • PHP Manual
  • Expect Functions
  • Execute command via Bourne shell, and open the PTY stream to the process

expect_popen

(PECL expect >= 0.1.0)

expect_popen — Execute command via Bourne shell, and open the PTY stream to the process

Description

expect_popen ( string $command ) : resource

Execute command via Bourne shell, and open the PTY stream to the process.

Parameters

command

Command to execute.

Return Values

Returns an open PTY stream to the processes stdio, stdout, and stderr.

On failure this function returns FALSE.

Examples

Example #1 expect_popen() example

<?php
// Login to the PHP.net CVS repository:
$stream = expect_popen ("cvs -d :pserver:anonymous@cvs.php.net:/repository login");
sleep (3);
fwrite ($stream, "phpfi\n");
fclose ($stream);
?>

See Also

  • popen() - Opens process file pointer


Libevent

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Libevent Functions
    • event_add — Add an event to the set of monitored events
    • event_base_free — Destroy event base
    • event_base_loop — Handle events
    • event_base_loopbreak — Abort event loop
    • event_base_loopexit — Exit loop after a time
    • event_base_new — Create and initialize new event base
    • event_base_priority_init — Set the number of event priority levels
    • event_base_reinit — Reinitialize the event base after a fork
    • event_base_set — Associate event base with an event
    • event_buffer_base_set — Associate buffered event with an event base
    • event_buffer_disable — Disable a buffered event
    • event_buffer_enable — Enable a buffered event
    • event_buffer_fd_set — Change a buffered event file descriptor
    • event_buffer_free — Destroy buffered event
    • event_buffer_new — Create new buffered event
    • event_buffer_priority_set — Assign a priority to a buffered event
    • event_buffer_read — Read data from a buffered event
    • event_buffer_set_callback — Set or reset callbacks for a buffered event
    • event_buffer_timeout_set — Set read and write timeouts for a buffered event
    • event_buffer_watermark_set — Set the watermarks for read and write events
    • event_buffer_write — Write data to a buffered event
    • event_del — Remove an event from the set of monitored events
    • event_free — Free event resource
    • event_new — Create new event
    • event_priority_set — Assign a priority to an event
    • event_set — Prepare an event
    • event_timer_add — Alias of event_add
    • event_timer_del — Alias of event_del
    • event_timer_new — Alias of event_new
    • event_timer_set — Prepare a timer event


Introduction

Libevent is a library that provides a mechanism to execute a callback function when a specific event occurs on a file descriptor or after a timeout has been reached.

More information about Libevent can be found at » http://libevent.org/.

Note: The libevent extension is unmaintained; consider to use the event extension instead.


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

This extension requires » libevent library. Minimal required version is 1.4.0.


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/libevent.


Resource Types

There are several resource types used in the extension. These resources are event, event base and buffered event.


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.

EV_TIMEOUT (integer)
EV_READ (integer)
EV_WRITE (integer)
EV_SIGNAL (integer)
EV_PERSIST (integer)
EVLOOP_NONBLOCK (integer)
EVLOOP_ONCE (integer)


Examples

Example #1 polling STDIN using basic API

<?php

function print_line($fd, $events, $arg)
{
    static $max_requests = 0;

    $max_requests++;

    if ($max_requests == 10) {
        // exit loop after 10 writes
        event_base_loopexit($arg[1]);
    }

    // print the line
    echo  fgets($fd);
}

// create base and event
$base = event_base_new();
$event = event_new();

$fd = STDIN;

// set event flags
event_set($event, $fd, EV_READ | EV_PERSIST, "print_line", array($event, $base));
// set event base
event_base_set($event, $base);

// enable event
event_add($event);
// start event loop
event_base_loop($base);

?>

Example #2 polling STDIN using buffered event API

<?php

function print_line($buf, $arg)
{
    static $max_requests;

    $max_requests++;

    if ($max_requests == 10) {
        event_base_loopexit($arg);
    }

    // print the line
    echo event_buffer_read($buf, 4096);
}

function error_func($buf, $what, $arg)
{
    // handle errors
}

$base = event_base_new();
$eb = event_buffer_new(STDIN, "print_line", NULL, "error_func", $base);

event_buffer_base_set($eb, $base);
event_buffer_enable($eb, EV_READ);

event_base_loop($base);

?>


Libevent Functions

Table of Contents

  • event_add — Add an event to the set of monitored events
  • event_base_free — Destroy event base
  • event_base_loop — Handle events
  • event_base_loopbreak — Abort event loop
  • event_base_loopexit — Exit loop after a time
  • event_base_new — Create and initialize new event base
  • event_base_priority_init — Set the number of event priority levels
  • event_base_reinit — Reinitialize the event base after a fork
  • event_base_set — Associate event base with an event
  • event_buffer_base_set — Associate buffered event with an event base
  • event_buffer_disable — Disable a buffered event
  • event_buffer_enable — Enable a buffered event
  • event_buffer_fd_set — Change a buffered event file descriptor
  • event_buffer_free — Destroy buffered event
  • event_buffer_new — Create new buffered event
  • event_buffer_priority_set — Assign a priority to a buffered event
  • event_buffer_read — Read data from a buffered event
  • event_buffer_set_callback — Set or reset callbacks for a buffered event
  • event_buffer_timeout_set — Set read and write timeouts for a buffered event
  • event_buffer_watermark_set — Set the watermarks for read and write events
  • event_buffer_write — Write data to a buffered event
  • event_del — Remove an event from the set of monitored events
  • event_free — Free event resource
  • event_new — Create new event
  • event_priority_set — Assign a priority to an event
  • event_set — Prepare an event
  • event_timer_add — Alias of event_add
  • event_timer_del — Alias of event_del
  • event_timer_new — Alias of event_new
  • event_timer_set — Prepare a timer event


Add an event to the set of monitored events

  • « Libevent Functions
  • event_base_free »
  • PHP Manual
  • Libevent Functions
  • Add an event to the set of monitored events

event_add

(PECL libevent >= 0.0.1)

event_add — Add an event to the set of monitored events

Description

event_add ( resource $event [, int $timeout = -1 ] ) : bool

event_add() schedules the execution of the event when the event specified in event_set() occurs or in at least the time specified by the timeout argument. If timeout was not specified, not timeout is set. The event must be already initalized by event_set() and event_base_set() functions. If the event already has a timeout set, it is replaced by the new one.

Parameters

event

Valid event resource.

timeout

Optional timeout (in microseconds).

Return Values

event_add() returns TRUE on success or FALSE on error.


Destroy event base

  • « event_add
  • event_base_loop »
  • PHP Manual
  • Libevent Functions
  • Destroy event base

event_base_free

(PECL libevent >= 0.0.1)

event_base_free — Destroy event base

Description

event_base_free ( resource $event_base ) : void

Destroys the specified event_base and frees all the resources associated. Note that it's not possible to destroy an event base with events attached to it.

Parameters

event_base

Valid event base resource.


Handle events

  • « event_base_free
  • event_base_loopbreak »
  • PHP Manual
  • Libevent Functions
  • Handle events

event_base_loop

(PECL libevent >= 0.0.1)

event_base_loop — Handle events

Description

event_base_loop ( resource $event_base [, int $flags = 0 ] ) : int

Starts event loop for the specified event base.

Parameters

event_base

Valid event base resource.

flags

Optional parameter, which can take any combination of EVLOOP_ONCE and EVLOOP_NONBLOCK.

Return Values

event_base_loop() returns 0 on success, -1 on error and 1 if no events were registered.


Abort event loop

  • « event_base_loop
  • event_base_loopexit »
  • PHP Manual
  • Libevent Functions
  • Abort event loop

event_base_loopbreak

(PECL libevent >= 0.0.1)

event_base_loopbreak — Abort event loop

Description

event_base_loopbreak ( resource $event_base ) : bool

Abort the active event loop immediately. The behaviour is similar to break statement.

Parameters

event_base

Valid event base resource.

Return Values

event_base_loopbreak() returns TRUE on success or FALSE on error.


Exit loop after a time

  • « event_base_loopbreak
  • event_base_new »
  • PHP Manual
  • Libevent Functions
  • Exit loop after a time

event_base_loopexit

(PECL libevent >= 0.0.1)

event_base_loopexit — Exit loop after a time

Description

event_base_loopexit ( resource $event_base [, int $timeout = -1 ] ) : bool

The next event loop iteration after the given timer expires will complete normally, then exit without blocking for events again.

Parameters

event_base

Valid event base resource.

timeout

Optional timeout parameter (in microseconds).

Return Values

event_base_loopexit() returns TRUE on success or FALSE on error.


Create and initialize new event base

  • « event_base_loopexit
  • event_base_priority_init »
  • PHP Manual
  • Libevent Functions
  • Create and initialize new event base

event_base_new

(PECL libevent >= 0.0.1)

event_base_new — Create and initialize new event base

Description

event_base_new ( void ) : resource

Returns new event base, which can be used later in event_base_set(), event_base_loop() and other functions.

Parameters

This function has no parameters.

Return Values

event_base_new() returns valid event base resource on success or FALSE on error.


Set the number of event priority levels

  • « event_base_new
  • event_base_reinit »
  • PHP Manual
  • Libevent Functions
  • Set the number of event priority levels

event_base_priority_init

(PECL libevent >= 0.0.2)

event_base_priority_init — Set the number of event priority levels

Description

event_base_priority_init ( resource $event_base , int $npriorities ) : bool

Sets the number of different event priority levels.

By default all events are scheduled with the same priority (npriorities/2). Using event_base_priority_init() you can change the number of event priority levels and then set a desired priority for each event.

Parameters

event_base

Valid event base resource.

npriorities

The number of event priority levels.

Return Values

event_base_priority_init() returns TRUE on success or FALSE on error.


Reinitialize the event base after a fork

  • « event_base_priority_init
  • event_base_set »
  • PHP Manual
  • Libevent Functions
  • Reinitialize the event base after a fork

event_base_reinit

(PECL libevent >= 0.1.0)

event_base_reinit — Reinitialize the event base after a fork

Description

event_base_reinit ( resource $event_base ) : bool

Some event mechanisms do not survive across fork. The event_base needs to be reinitialized with this function.

Parameters

event_base

Valid event base resource that needs to be re-initialized.

Return Values

Returns TRUE on success or FALSE on failure.


Associate event base with an event

  • « event_base_reinit
  • event_buffer_base_set »
  • PHP Manual
  • Libevent Functions
  • Associate event base with an event

event_base_set

(PECL libevent >= 0.0.1)

event_base_set — Associate event base with an event

Description

event_base_set ( resource $event , resource $event_base ) : bool

Associates the event_base with the event.

Parameters

event

Valid event resource.

event_base

Valid event base resource.

Return Values

event_base_set() returns TRUE on success or FALSE on error.


Associate buffered event with an event base

  • « event_base_set
  • event_buffer_disable »
  • PHP Manual
  • Libevent Functions
  • Associate buffered event with an event base

event_buffer_base_set

(PECL libevent >= 0.0.1)

event_buffer_base_set — Associate buffered event with an event base

Description

event_buffer_base_set ( resource $bevent , resource $event_base ) : bool

Assign the specified bevent to the event_base.

Parameters

bevent

Valid buffered event resource.

event_base

Valid event base resource.

Return Values

event_buffer_base_set() returns TRUE on success or FALSE on error.


Disable a buffered event

  • « event_buffer_base_set
  • event_buffer_enable »
  • PHP Manual
  • Libevent Functions
  • Disable a buffered event

event_buffer_disable

(PECL libevent >= 0.0.1)

event_buffer_disable — Disable a buffered event

Description

event_buffer_disable ( resource $bevent , int $events ) : bool

Disables the specified buffered event.

Parameters

bevent

Valid buffered event resource.

events

Any combination of EV_READ and EV_WRITE.

Return Values

event_buffer_disable() returns TRUE on success or FALSE on error.


Enable a buffered event

  • « event_buffer_disable
  • event_buffer_fd_set »
  • PHP Manual
  • Libevent Functions
  • Enable a buffered event

event_buffer_enable

(PECL libevent >= 0.0.1)

event_buffer_enable — Enable a buffered event

Description

event_buffer_enable ( resource $bevent , int $events ) : bool

Enables the specified buffered event.

Parameters

bevent

Valid buffered event resource.

events

Any combination of EV_READ and EV_WRITE.

Return Values

event_buffer_enable() returns TRUE on success or FALSE on error.


Change a buffered event file descriptor

  • « event_buffer_enable
  • event_buffer_free »
  • PHP Manual
  • Libevent Functions
  • Change a buffered event file descriptor

event_buffer_fd_set

(PECL libevent >= 0.0.1)

event_buffer_fd_set — Change a buffered event file descriptor

Description

event_buffer_fd_set ( resource $bevent , resource $fd ) : void

Changes the file descriptor on which the buffered event operates.

Parameters

bevent

Valid buffered event resource.

fd

Valid PHP stream, must be castable to file descriptor.


Destroy buffered event

  • « event_buffer_fd_set
  • event_buffer_new »
  • PHP Manual
  • Libevent Functions
  • Destroy buffered event

event_buffer_free

(PECL libevent >= 0.0.1)

event_buffer_free — Destroy buffered event

Description

event_buffer_free ( resource $bevent ) : void

Destroys the specified buffered event and frees all the resources associated.

Parameters

bevent

Valid buffered event resource.


Create new buffered event

  • « event_buffer_free
  • event_buffer_priority_set »
  • PHP Manual
  • Libevent Functions
  • Create new buffered event

event_buffer_new

(PECL libevent >= 0.0.1)

event_buffer_new — Create new buffered event

Description

event_buffer_new ( resource $stream , mixed $readcb , mixed $writecb , mixed $errorcb [, mixed $arg ] ) : resource

Libevent provides an abstraction layer on top of the regular event API. Using buffered event you don't need to deal with the I/O manually, instead it provides input and output buffers that get filled and drained automatically.

Parameters

stream

Valid PHP stream resource. Must be castable to file descriptor.

readcb

Callback to invoke where there is data to read, or NULL if no callback is desired.

writecb

Callback to invoke where the descriptor is ready for writing, or NULL if no callback is desired.

errorcb

Callback to invoke where there is an error on the descriptor, cannot be NULL.

arg

An argument that will be passed to each of the callbacks (optional).

Return Values

event_buffer_new() returns new buffered event resource on success or FALSE on error.


Assign a priority to a buffered event

  • « event_buffer_new
  • event_buffer_read »
  • PHP Manual
  • Libevent Functions
  • Assign a priority to a buffered event

event_buffer_priority_set

(PECL libevent >= 0.0.1)

event_buffer_priority_set — Assign a priority to a buffered event

Description

event_buffer_priority_set ( resource $bevent , int $priority ) : bool

Assign a priority to the bevent.

Parameters

bevent

Valid buffered event resource.

priority

Priority level. Cannot be less than zero and cannot exceed maximum priority level of the event base (see event_base_priority_init()).

Return Values

event_buffer_priority_set() returns TRUE on success or FALSE on error.


Read data from a buffered event

  • « event_buffer_priority_set
  • event_buffer_set_callback »
  • PHP Manual
  • Libevent Functions
  • Read data from a buffered event

event_buffer_read

(PECL libevent >= 0.0.1)

event_buffer_read — Read data from a buffered event

Description

event_buffer_read ( resource $bevent , int $data_size ) : string

Reads data from the input buffer of the buffered event.

Parameters

bevent

Valid buffered event resource.

data_size

Data size in bytes.


Set or reset callbacks for a buffered event

  • « event_buffer_read
  • event_buffer_timeout_set »
  • PHP Manual
  • Libevent Functions
  • Set or reset callbacks for a buffered event

event_buffer_set_callback

(PECL libevent >= 0.0.4)

event_buffer_set_callback — Set or reset callbacks for a buffered event

Description

event_buffer_set_callback ( resource $event , mixed $readcb , mixed $writecb , mixed $errorcb [, mixed $arg ] ) : bool

Sets or changes existing callbacks for the buffered event.

Parameters

event

Valid buffered event resource.

readcb

Callback to invoke where there is data to read, or NULL if no callback is desired.

writecb

Callback to invoke where the descriptor is ready for writing, or NULL if no callback is desired.

errorcb

Callback to invoke where there is an error on the descriptor, cannot be NULL.

arg

An argument that will be passed to each of the callbacks (optional).

Return Values

Returns TRUE on success or FALSE on failure.


Set read and write timeouts for a buffered event

  • « event_buffer_set_callback
  • event_buffer_watermark_set »
  • PHP Manual
  • Libevent Functions
  • Set read and write timeouts for a buffered event

event_buffer_timeout_set

(PECL libevent >= 0.0.1)

event_buffer_timeout_set — Set read and write timeouts for a buffered event

Description

event_buffer_timeout_set ( resource $bevent , int $read_timeout , int $write_timeout ) : void

Sets the read and write timeouts for the specified buffered event.

Parameters

bevent

Valid buffered event resource.

read_timeout

Read timeout (in seconds).

write_timeout

Write timeout (in seconds).


Set the watermarks for read and write events

  • « event_buffer_timeout_set
  • event_buffer_write »
  • PHP Manual
  • Libevent Functions
  • Set the watermarks for read and write events

event_buffer_watermark_set

(PECL libevent >= 0.0.1)

event_buffer_watermark_set — Set the watermarks for read and write events

Description

event_buffer_watermark_set ( resource $bevent , int $events , int $lowmark , int $highmark ) : void

Sets the watermarks for read and write events. Libevent does not invoke read callback unless there is at least lowmark bytes in the input buffer; if the read buffer is beyond the highmark, reading is stopped. On output, the write callback is invoked whenever the buffered data falls below the lowmark.

Parameters

bevent

Valid buffered event resource.

events

Any combination of EV_READ and EV_WRITE.

lowmark

Low watermark.

highmark

High watermark.


Write data to a buffered event

  • « event_buffer_watermark_set
  • event_del »
  • PHP Manual
  • Libevent Functions
  • Write data to a buffered event

event_buffer_write

(PECL libevent >= 0.0.1)

event_buffer_write — Write data to a buffered event

Description

event_buffer_write ( resource $bevent , string $data [, int $data_size = -1 ] ) : bool

Writes data to the specified buffered event. The data is appended to the output buffer and written to the descriptor when it becomes available for writing.

Parameters

bevent

Valid buffered event resource.

data

The data to be written.

data_size

Optional size parameter. event_buffer_write() writes all the data by default.

Return Values

event_buffer_write() returns TRUE on success or FALSE on error.


Remove an event from the set of monitored events

  • « event_buffer_write
  • event_free »
  • PHP Manual
  • Libevent Functions
  • Remove an event from the set of monitored events

event_del

(PECL libevent >= 0.0.1)

event_del — Remove an event from the set of monitored events

Description

event_del ( resource $event ) : bool

Cancels the event.

Parameters

event

Valid event resource.

Return Values

event_del() returns TRUE on success or FALSE on error.


Free event resource

  • « event_del
  • event_new »
  • PHP Manual
  • Libevent Functions
  • Free event resource

event_free

(PECL libevent >= 0.0.1)

event_free — Free event resource

Description

event_free ( resource $event ) : void

Frees previously created event resource.

Parameters

event

Valid event resource.


Create new event

  • « event_free
  • event_priority_set »
  • PHP Manual
  • Libevent Functions
  • Create new event

event_new

(PECL libevent >= 0.0.1)

event_new — Create new event

Description

event_new ( void ) : resource

Creates and returns a new event resource.

Return Values

event_new() returns a new event resource on success or FALSE on error.


Assign a priority to an event

  • « event_new
  • event_set »
  • PHP Manual
  • Libevent Functions
  • Assign a priority to an event

event_priority_set

(PECL libevent >= 0.0.5)

event_priority_set — Assign a priority to an event

Description

event_priority_set ( resource $event , int $priority ) : bool

Assign a priority to the event.

Parameters

event

Valid event resource.

priority

Priority level. Cannot be less than zero and cannot exceed maximum priority level of the event base (see event_base_priority_init()).

Return Values

Returns TRUE on success or FALSE on failure.


Prepare an event

  • « event_priority_set
  • event_timer_add »
  • PHP Manual
  • Libevent Functions
  • Prepare an event

event_set

(PECL libevent >= 0.0.1)

event_set — Prepare an event

Description

event_set ( resource $event , mixed $fd , int $events , mixed $callback [, mixed $arg ] ) : bool

Prepares the event to be used in event_add(). The event is prepared to call the function specified by the callback on the events specified in parameter events, which is a set of the following flags: EV_TIMEOUT, EV_SIGNAL, EV_READ, EV_WRITE and EV_PERSIST.

If EV_SIGNAL bit is set in parameter events, the fd is interpreted as signal number.

After initializing the event, use event_base_set() to associate the event with its event base.

In case of matching event, these three arguments are passed to the callback function:

fd

Signal number or resource indicating the stream.

events

A flag indicating the event. Consists of the following flags: EV_TIMEOUT, EV_SIGNAL, EV_READ, EV_WRITE and EV_PERSIST.

arg

Optional parameter, previously passed to event_set() as arg.

Parameters

event

Valid event resource.

fd

Valid PHP stream resource. The stream must be castable to file descriptor, so you most likely won't be able to use any of filtered streams.

events

A set of flags indicating the desired event, can be EV_READ and/or EV_WRITE. The additional flag EV_PERSIST makes the event to persist until event_del() is called, otherwise the callback is invoked only once.

callback

Callback function to be called when the matching event occurs.

arg

Optional callback parameter.

Return Values

event_set() returns TRUE on success or FALSE on error.

Changelog

Version | Description
0.0.4 | EV_SIGNAL support was added.


Alias of event_add

  • « event_set
  • event_timer_del »
  • PHP Manual
  • Libevent Functions
  • Alias of event_add

event_timer_add

(PECL libevent >= 0.0.2)

event_timer_add — Alias of event_add()

Description

This function is an alias of: event_add().


Alias of event_del

  • « event_timer_add
  • event_timer_new »
  • PHP Manual
  • Libevent Functions
  • Alias of event_del

event_timer_del

(PECL libevent >= 0.0.2)

event_timer_del — Alias of event_del()

Description

This function is an alias of: event_del().


Alias of event_new

  • « event_timer_del
  • event_timer_set »
  • PHP Manual
  • Libevent Functions
  • Alias of event_new

event_timer_new

(PECL libevent >= 0.0.2)

event_timer_new — Alias of event_new()

Description

This function is an alias of: event_new().


Prepare a timer event

  • « event_timer_new
  • PCNTL »
  • PHP Manual
  • Libevent Functions
  • Prepare a timer event

event_timer_set

(PECL libevent >= 0.0.2)

event_timer_set — Prepare a timer event

Description

event_timer_set ( resource $event , callable $callback [, mixed $arg ] ) : bool

Prepares the timer event to be used in event_add(). The event is prepared to call the function specified by the callback when the event timeout elapses.

After initializing the event, use event_base_set() to associate the event with its event base.

In case of matching event, these three arguments are passed to the callback function:

fd

Signal number or resource indicating the stream.

events

A flag indicating the event. This will always be EV_TIMEOUT for timer events.

arg

Optional parameter, previously passed to event_timer_set() as arg.

Parameters

event

Valid event resource.

callback

Callback function to be called when the matching event occurs.

arg

Optional callback parameter.

Return Values

Returns TRUE on success or FALSE on failure.


Process Control

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
  • PCNTL Functions
    • pcntl_alarm — Set an alarm clock for delivery of a signal
    • pcntl_async_signals — Enable/disable asynchronous signal handling or return the old setting
    • pcntl_errno — Alias of pcntl_get_last_error
    • pcntl_exec — Executes specified program in current process space
    • pcntl_fork — Forks the currently running process
    • pcntl_get_last_error — Retrieve the error number set by the last pcntl function which failed
    • pcntl_getpriority — Get the priority of any process
    • pcntl_setpriority — Change the priority of any process
    • pcntl_signal_dispatch — Calls signal handlers for pending signals
    • pcntl_signal_get_handler — Get the current handler for specified signal
    • pcntl_signal — Installs a signal handler
    • pcntl_sigprocmask — Sets and retrieves blocked signals
    • pcntl_sigtimedwait — Waits for signals, with a timeout
    • pcntl_sigwaitinfo — Waits for signals
    • pcntl_strerror — Retrieve the system error message associated with the given errno
    • pcntl_wait — Waits on or returns the status of a forked child
    • pcntl_waitpid — Waits on or returns the status of a forked child
    • pcntl_wexitstatus — Returns the return code of a terminated child
    • pcntl_wifexited — Checks if status code represents a normal exit
    • pcntl_wifsignaled — Checks whether the status code represents a termination due to a signal
    • pcntl_wifstopped — Checks whether the child process is currently stopped
    • pcntl_wstopsig — Returns the signal which caused the child to stop
    • pcntl_wtermsig — Returns the signal which caused the child to terminate


Introduction

Process Control support in PHP implements the Unix style of process creation, program execution, signal handling and process termination. Process Control should not be enabled within a web server environment and unexpected results may happen if any Process Control functions are used within a web server environment.

This documentation is intended to explain the general usage of each of the Process Control functions. For detailed information about Unix process control you are encouraged to consult your systems documentation including fork(2), waitpid(2) and signal(2) or a comprehensive reference such as Advanced Programming in the UNIX Environment by W. Richard Stevens (Addison-Wesley).

PCNTL now uses ticks as the signal handle callback mechanism, which is much faster than the previous mechanism. This change follows the same semantics as using "user ticks". You use the declare() statement to specify the locations in your program where callbacks are allowed to occur. This allows you to minimize the overhead of handling asynchronous events. In the past, compiling PHP with pcntl enabled would always incur this overhead, whether or not your script actually used pcntl.

Note: This extension is not available on Windows platforms.


Installation

Process Control support in PHP is not enabled by default. You have to compile the CGI or CLI version of PHP with --enable-pcntl configuration option when compiling PHP to enable Process Control support.

Note:

Currently, this module will not function on non-Unix platforms (Windows).


Predefined Constants

The following list of signals are supported by the Process Control functions. Please see your systems signal(7) man page for details of the default behavior of these signals.

WNOHANG (integer)
WUNTRACED (integer)
SIG_IGN (integer)
SIG_DFL (integer)
SIG_ERR (integer)
SIGHUP (integer)
SIGINT (integer)
SIGQUIT (integer)
SIGILL (integer)
SIGTRAP (integer)
SIGABRT (integer)
SIGIOT (integer)
SIGBUS (integer)
SIGFPE (integer)
SIGKILL (integer)
SIGUSR1 (integer)
SIGSEGV (integer)
SIGUSR2 (integer)
SIGPIPE (integer)
SIGALRM (integer)
SIGTERM (integer)
SIGSTKFLT (integer)
SIGCLD (integer)
SIGCHLD (integer)
SIGCONT (integer)
SIGSTOP (integer)
SIGTSTP (integer)
SIGTTIN (integer)
SIGTTOU (integer)
SIGURG (integer)
SIGXCPU (integer)
SIGXFSZ (integer)
SIGVTALRM (integer)
SIGPROF (integer)
SIGWINCH (integer)
SIGPOLL (integer)
SIGIO (integer)
SIGPWR (integer)
SIGSYS (integer)
SIGBABY (integer)
SIG_BLOCK (integer)
Available since PHP 5.3.0.
SIG_UNBLOCK (integer)
Available since PHP 5.3.0.
SIG_SETMASK (integer)
Available since PHP 5.3.0.
SI_USER (integer)
Available since PHP 5.3.0.
SI_NOINFO (integer)
Available since PHP 5.3.0.
SI_KERNEL (integer)
Available since PHP 5.3.0.
SI_QUEUE (integer)
Available since PHP 5.3.0.
SI_TIMER (integer)
Available since PHP 5.3.0.
SI_MSGGQ (integer)
Available since PHP 5.3.0.
SI_ASYNCIO (integer)
Available since PHP 5.3.0.
SI_SIGIO (integer)
Available since PHP 5.3.0.
SI_TKILL (integer)
Available since PHP 5.3.0.
CLD_EXITED (integer)
Available since PHP 5.3.0.
CLD_KILLED (integer)
Available since PHP 5.3.0.
CLD_DUMPED (integer)
Available since PHP 5.3.0.
CLD_TRAPPED (integer)
Available since PHP 5.3.0.
CLD_STOPPED (integer)
Available since PHP 5.3.0.
CLD_CONTINUED (integer)
Available since PHP 5.3.0.
TRAP_BRKPT (integer)
Available since PHP 5.3.0.
TRAP_TRACE (integer)
Available since PHP 5.3.0.
POLL_IN (integer)
Available since PHP 5.3.0.
POLL_OUT (integer)
Available since PHP 5.3.0.
POLL_MSG (integer)
Available since PHP 5.3.0.
POLL_ERR (integer)
Available since PHP 5.3.0.
POLL_PRI (integer)
Available since PHP 5.3.0.
POLL_HUP (integer)
Available since PHP 5.3.0.
ILL_ILLOPC (integer)
Available since PHP 5.3.0.
ILL_ILLOPN (integer)
Available since PHP 5.3.0.
ILL_ILLADR (integer)
Available since PHP 5.3.0.
ILL_ILLTRP (integer)
Available since PHP 5.3.0.
ILL_PRVOPC (integer)
Available since PHP 5.3.0.
ILL_PRVREG (integer)
Available since PHP 5.3.0.
ILL_COPROC (integer)
Available since PHP 5.3.0.
ILL_BADSTK (integer)
Available since PHP 5.3.0.
FPE_INTDIV (integer)
Available since PHP 5.3.0.
FPE_INTOVF (integer)
Available since PHP 5.3.0.
FPE_FLTDIV (integer)
Available since PHP 5.3.0.
FPE_FLTOVF (integer)
Available since PHP 5.3.0.
FPE_FLTUND (integer)
Available since PHP 5.3.0.
FPE_FLTRES (integer)
Available since PHP 5.3.0.
FPE_FLTINV (integer)
Available since PHP 5.3.0.
FPE_FLTSUB (integer)
Available since PHP 5.3.0.
SEGV_MAPERR (integer)
Available since PHP 5.3.0.
SEGV_ACCERR (integer)
Available since PHP 5.3.0.
BUS_ADRALN (integer)
Available since PHP 5.3.0.
BUS_ADRERR (integer)
Available since PHP 5.3.0.
BUS_OBJERR (integer)
Available since PHP 5.3.0.


  • « Predefined Constants
  • Basic usage »
  • PHP Manual
  • PCNTL
  • Examples

Examples

Table of Contents

  • Basic usage


Basic usage

This example forks off a daemon process with a signal handler.

Example #1 Process Control Example

<?php
declare(ticks=1);

$pid = pcntl_fork();
if ($pid == -1) {
     die("could not fork");
} else if ($pid) {
     exit(); // we are the parent
} else {
     // we are the child
}

// detatch from the controlling terminal
if (posix_setsid() == -1) {
    die("could not detach from terminal");
}

// setup signal handlers
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP, "sig_handler");

// loop forever performing tasks
while (1) {

    // do something interesting here

}

function sig_handler($signo)
{

     switch ($signo) {
         case SIGTERM:
             // handle shutdown tasks
             exit;
             break;
         case SIGHUP:
             // handle restart tasks
             break;
         default:
             // handle all other signals
     }

}

?>


PCNTL Functions

See Also

A look at the section about POSIX functions may be useful.

Table of Contents

  • pcntl_alarm — Set an alarm clock for delivery of a signal
  • pcntl_async_signals — Enable/disable asynchronous signal handling or return the old setting
  • pcntl_errno — Alias of pcntl_get_last_error
  • pcntl_exec — Executes specified program in current process space
  • pcntl_fork — Forks the currently running process
  • pcntl_get_last_error — Retrieve the error number set by the last pcntl function which failed
  • pcntl_getpriority — Get the priority of any process
  • pcntl_setpriority — Change the priority of any process
  • pcntl_signal_dispatch — Calls signal handlers for pending signals
  • pcntl_signal_get_handler — Get the current handler for specified signal
  • pcntl_signal — Installs a signal handler
  • pcntl_sigprocmask — Sets and retrieves blocked signals
  • pcntl_sigtimedwait — Waits for signals, with a timeout
  • pcntl_sigwaitinfo — Waits for signals
  • pcntl_strerror — Retrieve the system error message associated with the given errno
  • pcntl_wait — Waits on or returns the status of a forked child
  • pcntl_waitpid — Waits on or returns the status of a forked child
  • pcntl_wexitstatus — Returns the return code of a terminated child
  • pcntl_wifexited — Checks if status code represents a normal exit
  • pcntl_wifsignaled — Checks whether the status code represents a termination due to a signal
  • pcntl_wifstopped — Checks whether the child process is currently stopped
  • pcntl_wstopsig — Returns the signal which caused the child to stop
  • pcntl_wtermsig — Returns the signal which caused the child to terminate


Set an alarm clock for delivery of a signal

  • « PCNTL Functions
  • pcntl_async_signals »
  • PHP Manual
  • PCNTL Functions
  • Set an alarm clock for delivery of a signal

pcntl_alarm

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

pcntl_alarm — Set an alarm clock for delivery of a signal

Description

pcntl_alarm ( int $seconds ) : int

Creates a timer that will send a SIGALRM signal to the process after the given number of seconds. Any call to pcntl_alarm() will cancel any previously set alarm.

Parameters

seconds

The number of seconds to wait. If seconds is zero, no new alarm is created.

Return Values

Returns the time in seconds that any previously scheduled alarm had remaining before it was to be delivered, or 0 if there was no previously scheduled alarm.


Enable/disable asynchronous signal handling or return the old setting

  • « pcntl_alarm
  • pcntl_errno »
  • PHP Manual
  • PCNTL Functions
  • Enable/disable asynchronous signal handling or return the old setting

pcntl_async_signals

(PHP 7 >= 7.1.0)

pcntl_async_signals — Enable/disable asynchronous signal handling or return the old setting

Description

pcntl_async_signals ([ bool $on = NULL ] ) : bool

If the on parameter is omitted, pcntl_async_signals() returns whether asynchronous signal handling is enabled. Otherwise, asynchronous signal handling is enabled or disabled.

Parameters

on

Whether asynchronous signal handling should be enabled.

Return Values

When used as getter (that is without the optional parameter) it returns whether asynchronous signal handling is enabled. When used as setter (that is with the optional parameter given), it returns whether asynchronous signal handling was enabled before the function call.

See Also

  • declare


Alias of pcntl_get_last_error

  • « pcntl_async_signals
  • pcntl_exec »
  • PHP Manual
  • PCNTL Functions
  • Alias of pcntl_get_last_error

pcntl_errno

(PHP 5 >= 5.3.4, PHP 7)

pcntl_errno — Alias of pcntl_get_last_error()

Description

This function is an alias of: pcntl_get_last_error()


Executes specified program in current process space

  • « pcntl_errno
  • pcntl_fork »
  • PHP Manual
  • PCNTL Functions
  • Executes specified program in current process space

pcntl_exec

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

pcntl_exec — Executes specified program in current process space

Description

pcntl_exec ( string $path [, array $args [, array $envs ]] ) : void

Executes the program with the given arguments.

Parameters

path

path must be the path to a binary executable or a script with a valid path pointing to an executable in the shebang ( #!/usr/local/bin/perl for example) as the first line. See your system's man execve(2) page for additional information.

args

args is an array of argument strings passed to the program.

envs

envs is an array of strings which are passed as environment to the program. The array is in the format of name => value, the key being the name of the environmental variable and the value being the value of that variable.

Return Values

Returns NULL on success or FALSE on failure.


Forks the currently running process

  • « pcntl_exec
  • pcntl_get_last_error »
  • PHP Manual
  • PCNTL Functions
  • Forks the currently running process

pcntl_fork

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

pcntl_fork — Forks the currently running process

Description

pcntl_fork ( void ) : int

The pcntl_fork() function creates a child process that differs from the parent process only in its PID and PPID. Please see your system's fork(2) man page for specific details as to how fork works on your system.

Return Values

On success, the PID of the child process is returned in the parent's thread of execution, and a 0 is returned in the child's thread of execution. On failure, a -1 will be returned in the parent's context, no child process will be created, and a PHP error is raised.

Examples

Example #1 pcntl_fork() example

<?php

$pid = pcntl_fork();
if ($pid == -1) {
     die('could not fork');
} else if ($pid) {
     // we are the parent
     pcntl_wait($status); //Protect against Zombie children
} else {
     // we are the child
}

?>

See Also

  • pcntl_waitpid() - Waits on or returns the status of a forked child
  • pcntl_signal() - Installs a signal handler
  • setproctitle() - Set the process title


Retrieve the error number set by the last pcntl function which failed

  • « pcntl_fork
  • pcntl_getpriority »
  • PHP Manual
  • PCNTL Functions
  • Retrieve the error number set by the last pcntl function which failed

pcntl_get_last_error

(PHP 5 >= 5.3.4, PHP 7)

pcntl_get_last_error — Retrieve the error number set by the last pcntl function which failed

Description

pcntl_get_last_error ( void ) : int

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns error code.

See Also

  • pcntl_strerror() - Retrieve the system error message associated with the given errno


Get the priority of any process

  • « pcntl_get_last_error
  • pcntl_setpriority »
  • PHP Manual
  • PCNTL Functions
  • Get the priority of any process

pcntl_getpriority

(PHP 5, PHP 7)

pcntl_getpriority — Get the priority of any process

Description

pcntl_getpriority ([ int $pid = getmypid() [, int $process_identifier = PRIO_PROCESS ]] ) : int

pcntl_getpriority() gets the priority of pid. Because priority levels can differ between system types and kernel versions, please see your system's getpriority(2) man page for specific details.

Parameters

pid

If not specified, the pid of the current process is used.

process_identifier

One of PRIO_PGRP, PRIO_USER or PRIO_PROCESS.

Return Values

pcntl_getpriority() returns the priority of the process or FALSE on error. A lower numerical value causes more favorable scheduling.

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.

See Also

  • pcntl_setpriority() - Change the priority of any process


Change the priority of any process

  • « pcntl_getpriority
  • pcntl_signal_dispatch »
  • PHP Manual
  • PCNTL Functions
  • Change the priority of any process

pcntl_setpriority

(PHP 5, PHP 7)

pcntl_setpriority — Change the priority of any process

Description

pcntl_setpriority ( int $priority [, int $pid = getmypid() [, int $process_identifier = PRIO_PROCESS ]] ) : bool

pcntl_setpriority() sets the priority of pid.

Parameters

priority

priority is generally a value in the range -20 to 20. The default priority is 0 while a lower numerical value causes more favorable scheduling. Because priority levels can differ between system types and kernel versions, please see your system's setpriority(2) man page for specific details.

pid

If not specified, the pid of the current process is used.

process_identifier

One of PRIO_PGRP, PRIO_USER or PRIO_PROCESS.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • pcntl_getpriority() - Get the priority of any process


Calls signal handlers for pending signals

  • « pcntl_setpriority
  • pcntl_signal_get_handler »
  • PHP Manual
  • PCNTL Functions
  • Calls signal handlers for pending signals

pcntl_signal_dispatch

(PHP 5 >= 5.3.0, PHP 7)

pcntl_signal_dispatch — Calls signal handlers for pending signals

Description

pcntl_signal_dispatch ( void ) : bool

The pcntl_signal_dispatch() function calls the signal handlers installed by pcntl_signal() for each pending signal.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pcntl_signal_dispatch() example

<?php
echo "Installing signal handler...\n";
pcntl_signal(SIGHUP,  function($signo) {
     echo "signal handler called\n";
});

echo "Generating signal SIGHUP to self...\n";
posix_kill(posix_getpid(), SIGHUP);

echo "Dispatching...\n";
pcntl_signal_dispatch();

echo "Done\n";

?>

The above example will output something similar to:

Installing signal handler...
Generating signal SIGHUP to self...
Dispatching...
signal handler called
Done

See Also

  • pcntl_signal() - Installs a signal handler
  • pcntl_sigprocmask() - Sets and retrieves blocked signals
  • pcntl_sigwaitinfo() - Waits for signals
  • pcntl_sigtimedwait() - Waits for signals, with a timeout


Get the current handler for specified signal

  • « pcntl_signal_dispatch
  • pcntl_signal »
  • PHP Manual
  • PCNTL Functions
  • Get the current handler for specified signal

pcntl_signal_get_handler

(PHP 7 >= 7.1.0)

pcntl_signal_get_handler — Get the current handler for specified signal

Description

pcntl_signal_get_handler ( int $signo ) : mixed

The pcntl_signal_get_handler() function will get the current handler for the specified signo.

Parameters

signo

The signal number.

Return Values

This function may return an integer value that refers to SIG_DFL or SIG_IGN. If you set a custom handler a string value containing the function name is returned.

Changelog

Version | Description
7.1.0 | pcntl_signal_get_handler() has been added.

Examples

Example #1 pcntl_signal_get_handler() example

<?php
var_dump(pcntl_signal_get_handler(SIGUSR1)); // Outputs: int(0)

function pcntl_test($signo) {}
pcntl_signal(SIGUSR1, 'pcntl_test');
var_dump(pcntl_signal_get_handler(SIGUSR1)); // Outputs: string(10) "pcntl_test"

pcntl_signal(SIGUSR1, SIG_DFL);
var_dump(pcntl_signal_get_handler(SIGUSR1)); // Outputs: int(0)

pcntl_signal(SIGUSR1, SIG_IGN);
var_dump(pcntl_signal_get_handler(SIGUSR1)); // Outputs: int(1)
?>

See Also

  • pcntl_signal() - Installs a signal handler


Installs a signal handler

  • « pcntl_signal_get_handler
  • pcntl_sigprocmask »
  • PHP Manual
  • PCNTL Functions
  • Installs a signal handler

pcntl_signal

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

pcntl_signal — Installs a signal handler

Description

pcntl_signal ( int $signo , callable|int $handler [, bool $restart_syscalls = TRUE ] ) : bool

The pcntl_signal() function installs a new signal handler or replaces the current signal handler for the signal indicated by signo.

Parameters

signo

The signal number.

handler

The signal handler. This may be either a callable, which will be invoked to handle the signal, or either of the two global constants SIG_IGN or SIG_DFL, which will ignore the signal or restore the default signal handler respectively.

If a callable is given, it must implement the following signature:

handler ( int $signo , mixed $signinfo ) : void
signo
The signal being handled.
siginfo
If operating systems supports siginfo_t structures, this will be an array of signal information dependent on the signal.

Note:

Note that when you set a handler to an object method, that object's reference count is increased which makes it persist until you either change the handler to something else, or your script ends.

restart_syscalls

Specifies whether system call restarting should be used when this signal arrives.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.1.0 | As of PHP 7.1.0 the handler callback is given a second argument containing the signinfo of the specific signal. This data is only supplied if the operating system has the signinfo_t structure. If the OS does not implement siginfo_t NULL is supplied.

Examples

Example #1 pcntl_signal() example

<?php
// tick use required
declare(ticks = 1);

// signal handler function
function sig_handler($signo)
{

     switch ($signo) {
         case SIGTERM:
             // handle shutdown tasks
             exit;
             break;
         case SIGHUP:
             // handle restart tasks
             break;
         case SIGUSR1:
             echo "Caught SIGUSR1...\n";
             break;
         default:
             // handle all other signals
     }

}

echo "Installing signal handler...\n";

// setup signal handlers
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP,  "sig_handler");
pcntl_signal(SIGUSR1, "sig_handler");

// or use an object
// pcntl_signal(SIGUSR1, array($obj, "do_something"));

echo"Generating signal SIGUSR1 to self...\n";

// send SIGUSR1 to current process id
// posix_* functions require the posix extension
posix_kill(posix_getpid(), SIGUSR1);

echo "Done\n";

?>

Notes

pcntl_signal() doesn't stack the signal handlers, but replaces them.

See Also

  • pcntl_fork() - Forks the currently running process
  • pcntl_waitpid() - Waits on or returns the status of a forked child


Sets and retrieves blocked signals

  • « pcntl_signal
  • pcntl_sigtimedwait »
  • PHP Manual
  • PCNTL Functions
  • Sets and retrieves blocked signals

pcntl_sigprocmask

(PHP 5 >= 5.3.0, PHP 7)

pcntl_sigprocmask — Sets and retrieves blocked signals

Description

pcntl_sigprocmask ( int $how , array $set [, array &$oldset ] ) : bool

The pcntl_sigprocmask() function adds, removes or sets blocked signals, depending on the how parameter.

Parameters

how

Sets the behavior of pcntl_sigprocmask(). Possible values:

  • SIG_BLOCK: Add the signals to the currently blocked signals.
  • SIG_UNBLOCK: Remove the signals from the currently blocked signals.
  • SIG_SETMASK: Replace the currently blocked signals by the given list of signals.

set

List of signals.

oldset

The oldset parameter is set to an array containing the list of the previously blocked signals.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 pcntl_sigprocmask() example

<?php
pcntl_sigprocmask(SIG_BLOCK, array(SIGHUP));
$oldset = array();
pcntl_sigprocmask(SIG_UNBLOCK, array(SIGHUP), $oldset);
?>

See Also

  • pcntl_sigwaitinfo() - Waits for signals
  • pcntl_sigtimedwait() - Waits for signals, with a timeout


Waits for signals, with a timeout

  • « pcntl_sigprocmask
  • pcntl_sigwaitinfo »
  • PHP Manual
  • PCNTL Functions
  • Waits for signals, with a timeout

pcntl_sigtimedwait

(PHP 5 >= 5.3.0, PHP 7)

pcntl_sigtimedwait — Waits for signals, with a timeout

Description

pcntl_sigtimedwait ( array $set [, array &$siginfo [, int $seconds = 0 [, int $nanoseconds = 0 ]]] ) : int

The pcntl_sigtimedwait() function operates in exactly the same way as pcntl_sigwaitinfo() except that it takes two additional parameters, seconds and nanoseconds, which enable an upper bound to be placed on the time for which the script is suspended.

Parameters

set

Array of signals to wait for.

siginfo

The siginfo is set to an array containing informations about the signal. See pcntl_sigwaitinfo().

seconds

Timeout in seconds.

nanoseconds

Timeout in nanoseconds.

Return Values

On success, pcntl_sigtimedwait() returns a signal number.

See Also

  • pcntl_sigprocmask() - Sets and retrieves blocked signals
  • pcntl_sigwaitinfo() - Waits for signals


Waits for signals

  • « pcntl_sigtimedwait
  • pcntl_strerror »
  • PHP Manual
  • PCNTL Functions
  • Waits for signals

pcntl_sigwaitinfo

(PHP 5 >= 5.3.0, PHP 7)

pcntl_sigwaitinfo — Waits for signals

Description

pcntl_sigwaitinfo ( array $set [, array &$siginfo ] ) : int

The pcntl_sigwaitinfo() function suspends execution of the calling script until one of the signals given in set are delivered. If one of the signal is already pending (e.g. blocked by pcntl_sigprocmask()), pcntl_sigwaitinfo() will return immediately.

Parameters

set

Array of signals to wait for.

siginfo

The siginfo parameter is set to an array containing informations about the signal.

The following elements are set for all signals:

  • signo: Signal number
  • errno: An error number
  • code: Signal code

The following elements may be set for the SIGCHLD signal:

  • status: Exit value or signal
  • utime: User time consumed
  • stime: System time consumed
  • pid: Sending process ID
  • uid: Real user ID of sending process

The following elements may be set for the SIGILL, SIGFPE, SIGSEGV and SIGBUS signals:

  • addr: Memory location which caused fault

The following element may be set for the SIGPOLL signal:

  • band: Band event
  • fd: File descriptor number

Return Values

On success, pcntl_sigwaitinfo() returns a signal number.

Examples

Example #1 pcntl_sigwaitinfo() example

<?php
echo "Blocking SIGHUP signal\n";
pcntl_sigprocmask(SIG_BLOCK, array(SIGHUP));

echo "Sending SIGHUP to self\n";
posix_kill(posix_getpid(), SIGHUP);

echo "Waiting for signals\n";
$info = array();
pcntl_sigwaitinfo(array(SIGHUP), $info);
?>

See Also

  • pcntl_sigprocmask() - Sets and retrieves blocked signals
  • pcntl_sigtimedwait() - Waits for signals, with a timeout


Retrieve the system error message associated with the given errno

  • « pcntl_sigwaitinfo
  • pcntl_wait »
  • PHP Manual
  • PCNTL Functions
  • Retrieve the system error message associated with the given errno

pcntl_strerror

(PHP 5 >= 5.3.4, PHP 7)

pcntl_strerror — Retrieve the system error message associated with the given errno

Description

pcntl_strerror ( int $errno ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

errno

Return Values

Returns error description on success or FALSE on failure.

See Also

  • pcntl_get_last_error() - Retrieve the error number set by the last pcntl function which failed


Waits on or returns the status of a forked child

  • « pcntl_strerror
  • pcntl_waitpid »
  • PHP Manual
  • PCNTL Functions
  • Waits on or returns the status of a forked child

pcntl_wait

(PHP 5, PHP 7)

pcntl_wait — Waits on or returns the status of a forked child

Description

pcntl_wait ( int &$status [, int $options = 0 [, array &$rusage ]] ) : int

The wait function suspends execution of the current process until a child has exited, or until a signal is delivered whose action is to terminate the current process or to call a signal handling function. If a child has already exited by the time of the call (a so-called "zombie" process), the function returns immediately. Any system resources used by the child are freed. Please see your system's wait(2) man page for specific details as to how wait works on your system.

Note:

This function is equivalent to calling pcntl_waitpid() with a -1 pid and no options.

Parameters

status

pcntl_wait() will store status information
in the status parameter which can be
evaluated using the following functions:
pcntl_wifexited(),
pcntl_wifstopped(),
pcntl_wifsignaled(),
pcntl_wexitstatus(),
pcntl_wtermsig() and
pcntl_wstopsig().

options

If wait3 is available on your system (mostly BSD-style systems), you can provide the optional options parameter. If this parameter is not provided, wait will be used for the system call. If wait3 is not available, providing a value for options will have no effect. The value of options is the value of zero or more of the following two constants OR'ed together:

Possible values for options
WNOHANG | Return immediately if no child has exited.
WUNTRACED | Return for children which are stopped, and whose status has not been reported.

Return Values

pcntl_wait() returns the process ID of the child which exited, -1 on error or zero if WNOHANG was provided as an option (on wait3-available systems) and no child was available.

See Also

  • pcntl_fork() - Forks the currently running process
  • pcntl_signal() - Installs a signal handler
  • pcntl_wifexited() - Checks if status code represents a normal exit
  • pcntl_wifstopped() - Checks whether the child process is currently stopped
  • pcntl_wifsignaled() - Checks whether the status code represents a termination due to a signal
  • pcntl_wexitstatus() - Returns the return code of a terminated child
  • pcntl_wtermsig() - Returns the signal which caused the child to terminate
  • pcntl_wstopsig() - Returns the signal which caused the child to stop
  • pcntl_waitpid() - Waits on or returns the status of a forked child


Waits on or returns the status of a forked child

  • « pcntl_wait
  • pcntl_wexitstatus »
  • PHP Manual
  • PCNTL Functions
  • Waits on or returns the status of a forked child

pcntl_waitpid

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

pcntl_waitpid — Waits on or returns the status of a forked child

Description

pcntl_waitpid ( int $pid , int &$status [, int $options = 0 [, array &$rusage ]] ) : int

Suspends execution of the current process until a child as specified by the pid argument has exited, or until a signal is delivered whose action is to terminate the current process or to call a signal handling function.

If a child as requested by pid has already exited by the time of the call (a so-called "zombie" process), the function returns immediately. Any system resources used by the child are freed. Please see your system's waitpid(2) man page for specific details as to how waitpid works on your system.

Parameters

pid

The value of pid can be one of the following:

possible values for pid
< -1 | wait for any child process whose process group ID is equal to the absolute value of pid.
-1 | wait for any child process; this is the same behaviour that the wait function exhibits.
0 | wait for any child process whose process group ID is equal to that of the calling process.
> 0 | wait for the child whose process ID is equal to the value of pid.

Note:

Specifying -1 as the pid is equivalent to the functionality pcntl_wait() provides (minus options).

status

pcntl_waitpid() will store status information
in the status parameter which can be
evaluated using the following functions:
pcntl_wifexited(),
pcntl_wifstopped(),
pcntl_wifsignaled(),
pcntl_wexitstatus(),
pcntl_wtermsig() and
pcntl_wstopsig().

options

The value of options is the value of zero or more of the following two global constants OR'ed together:

possible values for options
WNOHANG | return immediately if no child has exited.
WUNTRACED | return for children which are stopped, and whose status has not been reported.

Return Values

pcntl_waitpid() returns the process ID of the child which exited, -1 on error or zero if WNOHANG was used and no child was available

See Also

  • pcntl_fork() - Forks the currently running process
  • pcntl_signal() - Installs a signal handler
  • pcntl_wifexited() - Checks if status code represents a normal exit
  • pcntl_wifstopped() - Checks whether the child process is currently stopped
  • pcntl_wifsignaled() - Checks whether the status code represents a termination due to a signal
  • pcntl_wexitstatus() - Returns the return code of a terminated child
  • pcntl_wtermsig() - Returns the signal which caused the child to terminate
  • pcntl_wstopsig() - Returns the signal which caused the child to stop


Returns the return code of a terminated child

  • « pcntl_waitpid
  • pcntl_wifexited »
  • PHP Manual
  • PCNTL Functions
  • Returns the return code of a terminated child

pcntl_wexitstatus

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

pcntl_wexitstatus — Returns the return code of a terminated child

Description

pcntl_wexitstatus ( int $status ) : int

Returns the return code of a terminated child. This function is only useful if pcntl_wifexited() returned TRUE.

Parameters

status

The status parameter is the status parameter supplied to a successful call to pcntl_waitpid().

Return Values

Returns the return code, as an integer.

See Also

  • pcntl_waitpid() - Waits on or returns the status of a forked child
  • pcntl_wifexited() - Checks if status code represents a normal exit


Checks if status code represents a normal exit

  • « pcntl_wexitstatus
  • pcntl_wifsignaled »
  • PHP Manual
  • PCNTL Functions
  • Checks if status code represents a normal exit

pcntl_wifexited

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

pcntl_wifexited — Checks if status code represents a normal exit

Description

pcntl_wifexited ( int $status ) : bool

Checks whether the child status code represents a normal exit.

Parameters

status

The status parameter is the status parameter supplied to a successful call to pcntl_waitpid().

Return Values

Returns TRUE if the child status code represents a normal exit, FALSE otherwise.

See Also

  • pcntl_waitpid() - Waits on or returns the status of a forked child
  • pcntl_wexitstatus() - Returns the return code of a terminated child


Checks whether the status code represents a termination due to a signal

  • « pcntl_wifexited
  • pcntl_wifstopped »
  • PHP Manual
  • PCNTL Functions
  • Checks whether the status code represents a termination due to a signal

pcntl_wifsignaled

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

pcntl_wifsignaled — Checks whether the status code represents a termination due to a signal

Description

pcntl_wifsignaled ( int $status ) : bool

Checks whether the child process exited because of a signal which was not caught.

Parameters

status

The status parameter is the status parameter supplied to a successful call to pcntl_waitpid().

Return Values

Returns TRUE if the child process exited because of a signal which was not caught, FALSE otherwise.

See Also

  • pcntl_waitpid() - Waits on or returns the status of a forked child
  • pcntl_signal() - Installs a signal handler


Checks whether the child process is currently stopped

  • « pcntl_wifsignaled
  • pcntl_wstopsig »
  • PHP Manual
  • PCNTL Functions
  • Checks whether the child process is currently stopped

pcntl_wifstopped

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

pcntl_wifstopped — Checks whether the child process is currently stopped

Description

pcntl_wifstopped ( int $status ) : bool

Checks whether the child process which caused the return is currently stopped; this is only possible if the call to pcntl_waitpid() was done using the option WUNTRACED.

Parameters

status

The status parameter is the status parameter supplied to a successful call to pcntl_waitpid().

Return Values

Returns TRUE if the child process which caused the return is currently stopped, FALSE otherwise.

See Also

  • pcntl_waitpid() - Waits on or returns the status of a forked child


Returns the signal which caused the child to stop

  • « pcntl_wifstopped
  • pcntl_wtermsig »
  • PHP Manual
  • PCNTL Functions
  • Returns the signal which caused the child to stop

pcntl_wstopsig

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

pcntl_wstopsig — Returns the signal which caused the child to stop

Description

pcntl_wstopsig ( int $status ) : int

Returns the number of the signal which caused the child to stop. This function is only useful if pcntl_wifstopped() returned TRUE.

Parameters

status

The status parameter is the status parameter supplied to a successful call to pcntl_waitpid().

Return Values

Returns the signal number.

See Also

  • pcntl_waitpid() - Waits on or returns the status of a forked child
  • pcntl_wifstopped() - Checks whether the child process is currently stopped


Returns the signal which caused the child to terminate

  • « pcntl_wstopsig
  • POSIX »
  • PHP Manual
  • PCNTL Functions
  • Returns the signal which caused the child to terminate

pcntl_wtermsig

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

pcntl_wtermsig — Returns the signal which caused the child to terminate

Description

pcntl_wtermsig ( int $status ) : int

Returns the number of the signal that caused the child process to terminate. This function is only useful if pcntl_wifsignaled() returned TRUE.

Parameters

status

The status parameter is the status parameter supplied to a successful call to pcntl_waitpid().

Return Values

Returns the signal number, as an integer.

See Also

  • pcntl_waitpid() - Waits on or returns the status of a forked child
  • pcntl_signal() - Installs a signal handler
  • pcntl_wifsignaled() - Checks whether the status code represents a termination due to a signal


POSIX

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
    • posix_access constants
    • posix_mknod constants
    • posix_setrlimit constants
  • POSIX Functions
    • posix_access — Determine accessibility of a file
    • posix_ctermid — Get path name of controlling terminal
    • posix_errno — Alias of posix_get_last_error
    • posix_get_last_error — Retrieve the error number set by the last posix function that failed
    • posix_getcwd — Pathname of current directory
    • posix_getegid — Return the effective group ID of the current process
    • posix_geteuid — Return the effective user ID of the current process
    • posix_getgid — Return the real group ID of the current process
    • posix_getgrgid — Return info about a group by group id
    • posix_getgrnam — Return info about a group by name
    • posix_getgroups — Return the group set of the current process
    • posix_getlogin — Return login name
    • posix_getpgid — Get process group id for job control
    • posix_getpgrp — Return the current process group identifier
    • posix_getpid — Return the current process identifier
    • posix_getppid — Return the parent process identifier
    • posix_getpwnam — Return info about a user by username
    • posix_getpwuid — Return info about a user by user id
    • posix_getrlimit — Return info about system resource limits
    • posix_getsid — Get the current sid of the process
    • posix_getuid — Return the real user ID of the current process
    • posix_initgroups — Calculate the group access list
    • posix_isatty — Determine if a file descriptor is an interactive terminal
    • posix_kill — Send a signal to a process
    • posix_mkfifo — Create a fifo special file (a named pipe)
    • posix_mknod — Create a special or ordinary file (POSIX.1)
    • posix_setegid — Set the effective GID of the current process
    • posix_seteuid — Set the effective UID of the current process
    • posix_setgid — Set the GID of the current process
    • posix_setpgid — Set process group id for job control
    • posix_setrlimit — Set system resource limits
    • posix_setsid — Make the current process a session leader
    • posix_setuid — Set the UID of the current process
    • posix_strerror — Retrieve the system error message associated with the given errno
    • posix_times — Get process times
    • posix_ttyname — Determine terminal device name
    • posix_uname — Get system name


Introduction

This module contains an interface to those functions defined in the IEEE 1003.1 (POSIX.1) standards document which are not accessible through other means.

Warning

Sensitive data can be retrieved with the POSIX functions, e.g. posix_getpwnam() and friends. None of the POSIX function perform any kind of access checking when safe mode is enabled. It's therefore strongly advised to disable the POSIX extension at all (use --disable-posix in your configure line) if you're operating in such an environment.

Note: This extension is not available on Windows platforms.


Installation

POSIX functions are enabled by default. You can disable POSIX-like functions with --disable-posix .


Predefined Constants

Table of Contents

  • posix_access constants
  • posix_mknod constants
  • posix_setrlimit 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.


posix_access constants

  • « Predefined Constants
  • posix_mknod constants »
  • PHP Manual
  • Predefined Constants
  • posix_access constants

posix_access() constants

Note:

These constants are available starting with PHP 5.1.0. Please note that some of them may not be available on your system.

POSIX_F_OK (integer)
Check whether the file exists.
POSIX_R_OK (integer)
Check whether the file exists and has read permissions.
POSIX_W_OK (integer)
Check whether the file exists and has write permissions.
POSIX_X_OK (integer)
Check whether the file exists and has execute permissions.


posix_mknod constants

  • « posix_access constants
  • posix_setrlimit constants »
  • PHP Manual
  • Predefined Constants
  • posix_mknod constants

posix_mknod() constants

Note:

These constants are available starting with PHP 5.1.0. Please note that some of them may not be available on your system.

POSIX_S_IFBLK (integer)
Block special file
POSIX_S_IFCHR (integer)
Character special file
POSIX_S_IFIFO (integer)
FIFO (named pipe) special file
POSIX_S_IFREG (integer)
Normal file
POSIX_S_IFSOCK (integer)
Socket


posix_setrlimit constants

  • « posix_mknod constants
  • POSIX Functions »
  • PHP Manual
  • Predefined Constants
  • posix_setrlimit constants

posix_setrlimit() constants

Note:

These constants are available starting with PHP 7.0.0. Please note that some of them may not be available on your system.

Note:

You may wish to read the below notes in conjunction with the manpage for setrlimit() on your specific operating system, as there is variance in how these limits are interpreted, even across operating systems that claim to implement POSIX in full.

POSIX_RLIMIT_AS (integer)
The maximum size of the process's address space in bytes. See also PHP's memory_limit configuration directive.
POSIX_RLIMIT_CORE (integer)
The maximum size of a core file. If the limit is set to 0, no core file will be generated.
POSIX_RLIMIT_CPU (integer)
The maximum amount of CPU time that the process can use, in seconds. When the soft limit is hit, a SIGXCPU signal will be sent, which can be caught with pcntl_signal(). Depending on the operating system, additional SIGXCPU signals may be sent each second until the hard limit is hit, at which point an uncatchable SIGKILL signal is sent. See also set_time_limit().
POSIX_RLIMIT_DATA (integer)
The maximum size of the process's data segment, in bytes. It is extremely unlikely that this will have any effect on the execution of PHP unless an extension is in use that calls brk() or sbrk().
POSIX_RLIMIT_FSIZE (integer)
The maximum size of files that the process can create, in bytes.
POSIX_RLIMIT_LOCKS (integer)
The maximum number of locks that the process can create. This is only supported on extremely old Linux kernels.
POSIX_RLIMIT_MEMLOCK (integer)
The maximum number of bytes that can be locked into memory.
POSIX_RLIMIT_MSGQUEUE (integer)
The maximum number of bytes that can be allocated for POSIX message queues. PHP does not ship with support for POSIX message queues, so this limit will not have any effect unless you are using an extension that implements that support.
POSIX_RLIMIT_NICE (integer)
The maximum value to which the process can be reniced to. The value that will be used will be 20 - limit, as resource limit values cannot be negative.
POSIX_RLIMIT_NOFILE (integer)
A value one greater than the maximum file descriptor number that can be opened by this process.
POSIX_RLIMIT_NPROC (integer)
The maximum number of processes (and/or threads, on some operating systems) that can be created for the real user ID of the process.
POSIX_RLIMIT_RSS (integer)
The maximum size of the process's resident set, in pages.
POSIX_RLIMIT_RTPRIO (integer)
The maximum real time priority that can be set via the sched_setscheduler() and sched_setparam() system calls.
POSIX_RLIMIT_RTTIME (integer)
The maximum amount of CPU time, in microseconds, that the process can consume without making a blocking system call if it is using real time scheduling.
POSIX_RLIMIT_SIGPENDING (integer)
The maximum number of signals that can be queued for the real user ID of the process.
POSIX_RLIMIT_STACK (integer)
The maximum size of the process stack, in bytes.
POSIX_RLIMIT_INFINITY (integer)
Used to indicate an infinite value for a resource limit.


POSIX Functions

See Also

The section about Process Control Functions maybe of interest for you.

Table of Contents

  • posix_access — Determine accessibility of a file
  • posix_ctermid — Get path name of controlling terminal
  • posix_errno — Alias of posix_get_last_error
  • posix_get_last_error — Retrieve the error number set by the last posix function that failed
  • posix_getcwd — Pathname of current directory
  • posix_getegid — Return the effective group ID of the current process
  • posix_geteuid — Return the effective user ID of the current process
  • posix_getgid — Return the real group ID of the current process
  • posix_getgrgid — Return info about a group by group id
  • posix_getgrnam — Return info about a group by name
  • posix_getgroups — Return the group set of the current process
  • posix_getlogin — Return login name
  • posix_getpgid — Get process group id for job control
  • posix_getpgrp — Return the current process group identifier
  • posix_getpid — Return the current process identifier
  • posix_getppid — Return the parent process identifier
  • posix_getpwnam — Return info about a user by username
  • posix_getpwuid — Return info about a user by user id
  • posix_getrlimit — Return info about system resource limits
  • posix_getsid — Get the current sid of the process
  • posix_getuid — Return the real user ID of the current process
  • posix_initgroups — Calculate the group access list
  • posix_isatty — Determine if a file descriptor is an interactive terminal
  • posix_kill — Send a signal to a process
  • posix_mkfifo — Create a fifo special file (a named pipe)
  • posix_mknod — Create a special or ordinary file (POSIX.1)
  • posix_setegid — Set the effective GID of the current process
  • posix_seteuid — Set the effective UID of the current process
  • posix_setgid — Set the GID of the current process
  • posix_setpgid — Set process group id for job control
  • posix_setrlimit — Set system resource limits
  • posix_setsid — Make the current process a session leader
  • posix_setuid — Set the UID of the current process
  • posix_strerror — Retrieve the system error message associated with the given errno
  • posix_times — Get process times
  • posix_ttyname — Determine terminal device name
  • posix_uname — Get system name


Determine accessibility of a file

  • « POSIX Functions
  • posix_ctermid »
  • PHP Manual
  • POSIX Functions
  • Determine accessibility of a file

posix_access

(PHP 5 >= 5.1.0, PHP 7)

posix_access — Determine accessibility of a file

Description

posix_access ( string $file [, int $mode = POSIX_F_OK ] ) : bool

posix_access() checks the user's permission of a file.

Parameters

file

The name of the file to be tested.

mode

A mask consisting of one or more of POSIX_F_OK, POSIX_R_OK, POSIX_W_OK and POSIX_X_OK.

POSIX_R_OK, POSIX_W_OK and POSIX_X_OK request checking whether the file exists and has read, write and execute permissions, respectively. POSIX_F_OK just requests checking for the existence of the file.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 posix_access() example

This example will check if the $file is readable and writable, otherwise will print an error message.

<?php

$file = 'some_file';

if (posix_access($file, POSIX_R_OK | POSIX_W_OK)) {
    echo 'The file is readable and writable!';

} else {
    $error = posix_get_last_error();

    echo "Error $error: " . posix_strerror($error);
}

?>

Notes

Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.

See Also

  • posix_get_last_error() - Retrieve the error number set by the last posix function that failed
  • posix_strerror() - Retrieve the system error message associated with the given errno


Get path name of controlling terminal

  • « posix_access
  • posix_errno »
  • PHP Manual
  • POSIX Functions
  • Get path name of controlling terminal

posix_ctermid

(PHP 4, PHP 5, PHP 7)

posix_ctermid — Get path name of controlling terminal

Description

posix_ctermid ( void ) : string

Generates a string which is the pathname for the current controlling terminal for the process. On error this will set errno, which can be checked using posix_get_last_error()

Return Values

Upon successful completion, returns string of the pathname to the current controlling terminal. Otherwise FALSE is returned and errno is set, which can be checked with posix_get_last_error().

Examples

Example #1 posix_ctermid() example

This example will display the path to the current TTY.

<?php
echo "I am running from ".posix_ctermid();
?>

See Also

  • posix_ttyname() - Determine terminal device name
  • posix_get_last_error() - Retrieve the error number set by the last posix function that failed


Alias of posix_get_last_error

  • « posix_ctermid
  • posix_get_last_error »
  • PHP Manual
  • POSIX Functions
  • Alias of posix_get_last_error

posix_errno

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

posix_errno — Alias of posix_get_last_error()

Description

This function is an alias of: posix_get_last_error().


Retrieve the error number set by the last posix function that failed

  • « posix_errno
  • posix_getcwd »
  • PHP Manual
  • POSIX Functions
  • Retrieve the error number set by the last posix function that failed

posix_get_last_error

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

posix_get_last_error — Retrieve the error number set by the last posix function that failed

Description

posix_get_last_error ( void ) : int

Retrieve the error number set by the last posix function that failed. The system error message associated with the errno may be checked with posix_strerror().

Return Values

Returns the errno (error number) set by the last posix function that failed. If no errors exist, 0 is returned.

Examples

Example #1 posix_get_last_error() example

This example attempt to kill a bogus process id, which will set the last error. We will then print out the last errno.

<?php
posix_kill(999459,SIGKILL);
echo 'Your error returned was '.posix_get_last_error(); //Your error was ___
?>

See Also

  • posix_strerror() - Retrieve the system error message associated with the given errno


Pathname of current directory

  • « posix_get_last_error
  • posix_getegid »
  • PHP Manual
  • POSIX Functions
  • Pathname of current directory

posix_getcwd

(PHP 4, PHP 5, PHP 7)

posix_getcwd — Pathname of current directory

Description

posix_getcwd ( void ) : string

Gets the absolute pathname of the script's current working directory. On error, it sets errno which can be checked using posix_get_last_error()

Return Values

Returns a string of the absolute pathname on success. On error, returns FALSE and sets errno which can be checked with posix_get_last_error().

Examples

Example #1 posix_getcwd() example

This example will return the absolute path of the current working directory of the script.

<?php
echo 'My current working directory is '.posix_getcwd();
?>

Notes

Note:

This function can fail on

  • Read or Search permission was denied
  • Pathname no longer exists


Return the effective group ID of the current process

  • « posix_getcwd
  • posix_geteuid »
  • PHP Manual
  • POSIX Functions
  • Return the effective group ID of the current process

posix_getegid

(PHP 4, PHP 5, PHP 7)

posix_getegid — Return the effective group ID of the current process

Description

posix_getegid ( void ) : int

Return the numeric effective group ID of the current process.

Return Values

Returns an integer of the effective group ID.

Examples

Example #1 posix_getegid() example

This example will print out the effective group id, once it is changed with posix_setegid().

<?php
echo 'My real group id is '.posix_getgid(); //20
posix_setegid(40);
echo 'My real group id is '.posix_getgid(); //20
echo 'My effective group id is '.posix_getegid(); //40
?>

Notes

posix_getegid() is different than posix_getgid() because effective group ID can be changed by a calling process using posix_setegid().

See Also

  • posix_getgrgid() - Return info about a group by group id
  • posix_getgid() - Return the real group ID of the current process
  • posix_setgid() - Set the GID of the current process


Return the effective user ID of the current process

  • « posix_getegid
  • posix_getgid »
  • PHP Manual
  • POSIX Functions
  • Return the effective user ID of the current process

posix_geteuid

(PHP 4, PHP 5, PHP 7)

posix_geteuid — Return the effective user ID of the current process

Description

posix_geteuid ( void ) : int

Return the numeric effective user ID of the current process. See also posix_getpwuid() for information on how to convert this into a useable username.

Return Values

Returns the user id, as an integer

Examples

Example #1 posix_geteuid() example

This example will show the current user id then set the effective user id to a separate id using posix_seteuid(), then show the difference between the real id and the effective id.

<?php
echo posix_getuid()."\n"; //10001
echo posix_geteuid()."\n"; //10001
posix_seteuid(10000);
echo posix_getuid()."\n"; //10001
echo posix_geteuid()."\n"; //10000
?>

See Also

  • posix_getpwuid() - Return info about a user by user id
  • posix_getuid() - Return the real user ID of the current process
  • posix_setuid() - Set the UID of the current process
  • POSIX man page GETEUID(2)


Return the real group ID of the current process

  • « posix_geteuid
  • posix_getgrgid »
  • PHP Manual
  • POSIX Functions
  • Return the real group ID of the current process

posix_getgid

(PHP 4, PHP 5, PHP 7)

posix_getgid — Return the real group ID of the current process

Description

posix_getgid ( void ) : int

Return the numeric real group ID of the current process.

Return Values

Returns the real group id, as an integer.

Examples

Example #1 posix_getgid() example

This example will print out the real group id, even once the effective group id has been changed.

<?php
echo 'My real group id is '.posix_getgid(); //20
posix_setegid(40);
echo 'My real group id is '.posix_getgid(); //20
echo 'My effective group id is '.posix_getegid(); //40
?>

See Also

  • posix_getgrgid() - Return info about a group by group id
  • posix_getegid() - Return the effective group ID of the current process
  • posix_setgid() - Set the GID of the current process
  • POSIX man page GETGID(2)


Return info about a group by group id

  • « posix_getgid
  • posix_getgrnam »
  • PHP Manual
  • POSIX Functions
  • Return info about a group by group id

posix_getgrgid

(PHP 4, PHP 5, PHP 7)

posix_getgrgid — Return info about a group by group id

Description

posix_getgrgid ( int $gid ) : array

Gets information about a group provided its id.

Parameters

gid

The group id.

Return Values

The array elements returned are:

The group information array
Element | Description
name | The name element contains the name of the group. This is a short, usually less than 16 character "handle" of the group, not the real, full name.
passwd | The passwd element contains the group's password in an encrypted format. Often, for example on a system employing "shadow" passwords, an asterisk is returned instead.
gid | Group ID, should be the same as the gid parameter used when calling the function, and hence redundant.
members | This consists of an array of string's for all the members in the group.

Examples

Example #1 Example use of posix_getgrgid()

<?php

$groupid   = posix_getegid();
$groupinfo = posix_getgrgid($groupid);

print_r($groupinfo);
?>

The above example will output something similar to:

Array
(
    [name]    => toons
    [passwd]  => x
    [members] => Array
        (
            [0] => tom
            [1] => jerry
        )
    [gid]     => 42
)

See Also

  • posix_getegid() - Return the effective group ID of the current process
  • posix_getgrnam() - Return info about a group by name
  • filegroup() - Gets file group
  • stat() - Gives information about a file
  • safe_mode_gid
  • POSIX man page GETGRNAM(3)


Return info about a group by name

  • « posix_getgrgid
  • posix_getgroups »
  • PHP Manual
  • POSIX Functions
  • Return info about a group by name

posix_getgrnam

(PHP 4, PHP 5, PHP 7)

posix_getgrnam — Return info about a group by name

Description

posix_getgrnam ( string $name ) : array

Gets information about a group provided its name.

Parameters

name

The name of the group

Return Values

Returns an array on success, or FALSE on failure. The array elements returned are:

The group information array
Element | Description
name | The name element contains the name of the group. This is a short, usually less than 16 character "handle" of the group, not the real, full name. This should be the same as the name parameter used when calling the function, and hence redundant.
passwd | The passwd element contains the group's password in an encrypted format. Often, for example on a system employing "shadow" passwords, an asterisk is returned instead.
gid | Group ID of the group in numeric form.
members | This consists of an array of string's for all the members in the group.

Examples

Example #1 Example use of posix_getgrnam()

<?php

$groupinfo = posix_getgrnam("toons");

print_r($groupinfo);
?>

The above example will output something similar to:

Array
(
    [name]    => toons
    [passwd]  => x
    [members] => Array
        (
            [0] => tom
            [1] => jerry
        )
    [gid]     => 42
)

See Also

  • posix_getegid() - Return the effective group ID of the current process
  • posix_getgrgid() - Return info about a group by group id
  • filegroup() - Gets file group
  • stat() - Gives information about a file
  • safe_mode_gid
  • POSIX man page GETGRNAM(3)


Return the group set of the current process

  • « posix_getgrnam
  • posix_getlogin »
  • PHP Manual
  • POSIX Functions
  • Return the group set of the current process

posix_getgroups

(PHP 4, PHP 5, PHP 7)

posix_getgroups — Return the group set of the current process

Description

posix_getgroups ( void ) : array

Gets the group set of the current process.

Return Values

Returns an array of integers containing the numeric group ids of the group set of the current process.

Examples

Example #1 Example use of posix_getgroups()

<?php

$groups = posix_getgroups();

print_r($groups);
?>

The above example will output something similar to:

Array
(
    [0] => 4
    [1] => 20
    [2] => 24
    [3] => 25
    [4] => 29
    [5] => 30
    [6] => 33
    [7] => 44
    [8] => 46
    [9] => 104
    [10] => 109
    [11] => 110
    [12] => 1000
)

See Also

  • posix_getgrgid() - Return info about a group by group id


Return login name

  • « posix_getgroups
  • posix_getpgid »
  • PHP Manual
  • POSIX Functions
  • Return login name

posix_getlogin

(PHP 4, PHP 5, PHP 7)

posix_getlogin — Return login name

Description

posix_getlogin ( void ) : string

Returns the login name of the user owning the current process.

Return Values

Returns the login name of the user, as a string.

Examples

Example #1 Example use of posix_getlogin()

<?php
echo posix_getlogin(); //apache
?>

See Also

  • posix_getpwnam() - Return info about a user by username
  • POSIX man page GETLOGIN(3)


Get process group id for job control

  • « posix_getlogin
  • posix_getpgrp »
  • PHP Manual
  • POSIX Functions
  • Get process group id for job control

posix_getpgid

(PHP 4, PHP 5, PHP 7)

posix_getpgid — Get process group id for job control

Description

posix_getpgid ( int $pid ) : int

Returns the process group identifier of the process pid or FALSE on failure.

Parameters

pid

The process id.

Return Values

Returns the identifier, as an integer.

Examples

Example #1 Example use of posix_getpgid()

<?php
$pid = posix_getppid();
echo posix_getpgid($pid); //35
?>

Notes

Note:

This is a not POSIX function, but is common on BSD and System V systems. If the system does not support this function, then it will not be included at compile time. This may be checked with function_exists().

See Also

  • posix_getppid() - Return the parent process identifier
  • man page SETPGID(2)


Return the current process group identifier

  • « posix_getpgid
  • posix_getpid »
  • PHP Manual
  • POSIX Functions
  • Return the current process group identifier

posix_getpgrp

(PHP 4, PHP 5, PHP 7)

posix_getpgrp — Return the current process group identifier

Description

posix_getpgrp ( void ) : int

Return the process group identifier of the current process.

Return Values

Returns the identifier, as an integer.

See Also

  • POSIX.1 and the getpgrp(2) manual page on the POSIX system for more information on process groups.


Return the current process identifier

  • « posix_getpgrp
  • posix_getppid »
  • PHP Manual
  • POSIX Functions
  • Return the current process identifier

posix_getpid

(PHP 4, PHP 5, PHP 7)

posix_getpid — Return the current process identifier

Description

posix_getpid ( void ) : int

Return the process identifier of the current process.

Return Values

Returns the identifier, as an integer.

Examples

Example #1 Example use of posix_getpid()

<?php
echo posix_getpid(); //8805
?>

See Also

  • posix_kill() - Send a signal to a process
  • POSIX man page GETPID(2)


Return the parent process identifier

  • « posix_getpid
  • posix_getpwnam »
  • PHP Manual
  • POSIX Functions
  • Return the parent process identifier

posix_getppid

(PHP 4, PHP 5, PHP 7)

posix_getppid — Return the parent process identifier

Description

posix_getppid ( void ) : int

Return the process identifier of the parent process of the current process.

Return Values

Returns the identifier, as an integer.

Examples

Example #1 Example use of posix_getppid()

<?php
echo posix_getppid(); //8259
?>


Return info about a user by username

  • « posix_getppid
  • posix_getpwuid »
  • PHP Manual
  • POSIX Functions
  • Return info about a user by username

posix_getpwnam

(PHP 4, PHP 5, PHP 7)

posix_getpwnam — Return info about a user by username

Description

posix_getpwnam ( string $username ) : array

Returns an array of information about the given user.

Parameters

username

An alphanumeric username.

Return Values

On success an array with the following elements is returned, else FALSE is returned:

The user information array
Element | Description
name | The name element contains the username of the user. This is a short, usually less than 16 character "handle" of the user, not the real, full name. This should be the same as the username parameter used when calling the function, and hence redundant.
passwd | The passwd element contains the user's password in an encrypted format. Often, for example on a system employing "shadow" passwords, an asterisk is returned instead.
uid | User ID of the user in numeric form.
gid | The group ID of the user. Use the function posix_getgrgid() to resolve the group name and a list of its members.
gecos | GECOS is an obsolete term that refers to the finger information field on a Honeywell batch processing system. The field, however, lives on, and its contents have been formalized by POSIX. The field contains a comma separated list containing the user's full name, office phone, office number, and home phone number. On most systems, only the user's full name is available.
dir | This element contains the absolute path to the home directory of the user.
shell | The shell element contains the absolute path to the executable of the user's default shell.

Examples

Example #1 Example use of posix_getpwnam()

<?php

$userinfo = posix_getpwnam("tom");

print_r($userinfo);
?>

The above example will output something similar to:

Array
(
    [name]    => tom
    [passwd]  => x
    [uid]     => 10000
    [gid]     => 42
    [gecos]   => "tom,,,"
    [dir]     => "/home/tom"
    [shell]   => "/bin/bash"
)

See Also

  • posix_getpwuid() - Return info about a user by user id
  • POSIX man page GETPWNAM(3)


Return info about a user by user id

  • « posix_getpwnam
  • posix_getrlimit »
  • PHP Manual
  • POSIX Functions
  • Return info about a user by user id

posix_getpwuid

(PHP 4, PHP 5, PHP 7)

posix_getpwuid — Return info about a user by user id

Description

posix_getpwuid ( int $uid ) : array

Returns an array of information about the user referenced by the given user ID.

Parameters

uid

The user identifier.

Return Values

Returns an associative array with the following elements:

The user information array
Element | Description
name | The name element contains the username of the user. This is a short, usually less than 16 character "handle" of the user, not the real, full name.
passwd | The passwd element contains the user's password in an encrypted format. Often, for example on a system employing "shadow" passwords, an asterisk is returned instead.
uid | User ID, should be the same as the uid parameter used when calling the function, and hence redundant.
gid | The group ID of the user. Use the function posix_getgrgid() to resolve the group name and a list of its members.
gecos | GECOS is an obsolete term that refers to the finger information field on a Honeywell batch processing system. The field, however, lives on, and its contents have been formalized by POSIX. The field contains a comma separated list containing the user's full name, office phone, office number, and home phone number. On most systems, only the user's full name is available.
dir | This element contains the absolute path to the home directory of the user.
shell | The shell element contains the absolute path to the executable of the user's default shell.

Examples

Example #1 Example use of posix_getpwuid()

<?php

$userinfo = posix_getpwuid(10000);

print_r($userinfo);
?>

The above example will output something similar to:

Array
(
    [name]    => tom
    [passwd]  => x
    [uid]     => 10000
    [gid]     => 42
    [gecos]   => "tom,,,"
    [dir]     => "/home/tom"
    [shell]   => "/bin/bash"
)

See Also

  • posix_getpwnam() - Return info about a user by username
  • POSIX man page GETPWNAM(3)


Return info about system resource limits

  • « posix_getpwuid
  • posix_getsid »
  • PHP Manual
  • POSIX Functions
  • Return info about system resource limits

posix_getrlimit

(PHP 4, PHP 5, PHP 7)

posix_getrlimit — Return info about system resource limits

Description

posix_getrlimit ( void ) : array

posix_getrlimit() returns an array of information about the current resource's soft and hard limits.

Each resource has an associated soft and hard limit. The soft limit is the value that the kernel enforces for the corresponding resource. The hard limit acts as a ceiling for the soft limit. An unprivileged process may only set its soft limit to a value from 0 to the hard limit, and irreversibly lower its hard limit.

Return Values

Returns an associative array of elements for each limit that is defined. Each limit has a soft and a hard limit.

List of possible limits returned
Limit name | Limit description
core | The maximum size of the core file. When 0, not core files are created. When core files are larger than this size, they will be truncated at this size.
totalmem | The maximum size of the memory of the process, in bytes.
virtualmem | The maximum size of the virtual memory for the process, in bytes.
data | The maximum size of the data segment for the process, in bytes.
stack | The maximum size of the process stack, in bytes.
rss | The maximum number of virtual pages resident in RAM
maxproc | The maximum number of processes that can be created for the real user ID of the calling process.
memlock | The maximum number of bytes of memory that may be locked into RAM.
cpu | The amount of time the process is allowed to use the CPU.
filesize | The maximum size of the data segment for the process, in bytes.
openfiles | One more than the maximum number of open file descriptors.

Examples

Example #1 Example use of posix_getrlimit()

<?php

$limits = posix_getrlimit();

print_r($limits);
?>

The above example will output something similar to:

Array
(
    [soft core] => 0
    [hard core] => unlimited
    [soft data] => unlimited
    [hard data] => unlimited
    [soft stack] => 8388608
    [hard stack] => unlimited
    [soft totalmem] => unlimited
    [hard totalmem] => unlimited
    [soft rss] => unlimited
    [hard rss] => unlimited
    [soft maxproc] => unlimited
    [hard maxproc] => unlimited
    [soft memlock] => unlimited
    [hard memlock] => unlimited
    [soft cpu] => unlimited
    [hard cpu] => unlimited
    [soft filesize] => unlimited
    [hard filesize] => unlimited
    [soft openfiles] => 1024
    [hard openfiles] => 1024
)

See Also

  • man page GETRLIMIT(2)
  • posix_setrlimit() - Set system resource limits


Get the current sid of the process

  • « posix_getrlimit
  • posix_getuid »
  • PHP Manual
  • POSIX Functions
  • Get the current sid of the process

posix_getsid

(PHP 4, PHP 5, PHP 7)

posix_getsid — Get the current sid of the process

Description

posix_getsid ( int $pid ) : int

Return the session id of the process pid. The session id of a process is the process group id of the session leader.

Parameters

pid

The process identifier. If set to 0, the current process is assumed. If an invalid pid is specified, then FALSE is returned and an error is set which can be checked with posix_get_last_error().

Return Values

Returns the identifier, as an integer.

Examples

Example #1 Example use of posix_getsid()

<?php
$pid = posix_getpid();
echo posix_getsid($pid); //8805
?>

See Also

  • posix_getpgid() - Get process group id for job control
  • posix_setsid() - Make the current process a session leader
  • POSIX man page GETSID(2)


Return the real user ID of the current process

  • « posix_getsid
  • posix_initgroups »
  • PHP Manual
  • POSIX Functions
  • Return the real user ID of the current process

posix_getuid

(PHP 4, PHP 5, PHP 7)

posix_getuid — Return the real user ID of the current process

Description

posix_getuid ( void ) : int

Return the numeric real user ID of the current process.

Return Values

Returns the user id, as an integer

Examples

Example #1 Example use of posix_getuid()

<?php
echo posix_getuid(); //10000
?>

See Also

  • posix_getpwuid() - Return info about a user by user id
  • POSIX man page GETUID(2)


Calculate the group access list

  • « posix_getuid
  • posix_isatty »
  • PHP Manual
  • POSIX Functions
  • Calculate the group access list

posix_initgroups

(PHP 5 >= 5.2.0, PHP 7)

posix_initgroups — Calculate the group access list

Description

posix_initgroups ( string $name , int $base_group_id ) : bool

Calculates the group access list for the user specified in name.

Parameters

name

The user to calculate the list for.

base_group_id

Typically the group number from the password file.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • The Unix manual page for initgroups(3).


Determine if a file descriptor is an interactive terminal

  • « posix_initgroups
  • posix_kill »
  • PHP Manual
  • POSIX Functions
  • Determine if a file descriptor is an interactive terminal

posix_isatty

(PHP 4, PHP 5, PHP 7)

posix_isatty — Determine if a file descriptor is an interactive terminal

Description

posix_isatty ( mixed $fd ) : bool

Determines if the file descriptor fd refers to a valid terminal type device.

Parameters

fd

The file descriptor, which is expected to be either a file resource or an integer. An integer will be assumed to be a file descriptor that can be passed directly to the underlying system call.

In almost all cases, you will want to provide a file resource.

Return Values

Returns TRUE if fd is an open descriptor connected to a terminal and FALSE otherwise.

See Also

  • posix_ttyname() - Determine terminal device name
  • stream_isatty() - Check if a stream is a TTY


Send a signal to a process

  • « posix_isatty
  • posix_mkfifo »
  • PHP Manual
  • POSIX Functions
  • Send a signal to a process

posix_kill

(PHP 4, PHP 5, PHP 7)

posix_kill — Send a signal to a process

Description

posix_kill ( int $pid , int $sig ) : bool

Send the signal sig to the process with the process identifier pid.

Parameters

pid

The process identifier.

sig

One of the PCNTL signals constants.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • The kill(2) manual page of the POSIX system, which contains additional information about negative process identifiers, the special pid 0, the special pid -1, and the signal number 0.


Create a fifo special file (a named pipe)

  • « posix_kill
  • posix_mknod »
  • PHP Manual
  • POSIX Functions
  • Create a fifo special file (a named pipe)

posix_mkfifo

(PHP 4, PHP 5, PHP 7)

posix_mkfifo — Create a fifo special file (a named pipe)

Description

posix_mkfifo ( string $pathname , int $mode ) : bool

posix_mkfifo() creates a special FIFO file which exists in the file system and acts as a bidirectional communication endpoint for processes.

Parameters

pathname

Path to the FIFO file.

mode

The second parameter mode has to be given in octal notation (e.g. 0644). The permission of the newly created FIFO also depends on the setting of the current umask(). The permissions of the created file are (mode & ~umask).

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: When safe mode is enabled, PHP checks whether the files or directories being operated upon have the same UID (owner) as the script that is being executed.


Create a special or ordinary file (POSIX.1)

  • « posix_mkfifo
  • posix_setegid »
  • PHP Manual
  • POSIX Functions
  • Create a special or ordinary file (POSIX.1)

posix_mknod

(PHP 5 >= 5.1.0, PHP 7)

posix_mknod — Create a special or ordinary file (POSIX.1)

Description

posix_mknod ( string $pathname , int $mode [, int $major = 0 [, int $minor = 0 ]] ) : bool

Creates a special or ordinary file.

Parameters

pathname

The file to create

mode

This parameter is constructed by a bitwise OR between file type (one of the following constants: POSIX_S_IFREG, POSIX_S_IFCHR, POSIX_S_IFBLK, POSIX_S_IFIFO or POSIX_S_IFSOCK) and permissions.

major

The major device kernel identifier (required to pass when using S_IFCHR or S_IFBLK).

minor

The minor device kernel identifier.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A posix_mknod() example

<?php

$file = '/tmp/tmpfile';  // file name
$type = POSIX_S_IFBLK;   // file type
$permissions = 0777;     // octal
$major = 1;
$minor = 8;              // /dev/random

if (!posix_mknod($file, $type | $permissions, $major, $minor)) {
    die('Error ' . posix_get_last_error() . ': ' . posix_strerror(posix_get_last_error()));
}

?>

See Also

  • posix_mkfifo() - Create a fifo special file (a named pipe)


Set the effective GID of the current process

  • « posix_mknod
  • posix_seteuid »
  • PHP Manual
  • POSIX Functions
  • Set the effective GID of the current process

posix_setegid

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

posix_setegid — Set the effective GID of the current process

Description

posix_setegid ( int $gid ) : bool

Set the effective group ID of the current process. This is a privileged function and needs appropriate privileges (usually root) on the system to be able to perform this function.

Parameters

gid

The group id.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 posix_setegid() example

This example will print out the effective group id, once changed.

<?php
echo 'My real group id is '.posix_getgid(); //20
posix_setegid(40);
echo 'My real group id is '.posix_getgid(); //20
echo 'My effective group id is '.posix_getegid(); //40
?>

See Also

  • posix_getgrgid() - Return info about a group by group id
  • posix_getgid() - Return the real group ID of the current process
  • posix_setgid() - Set the GID of the current process


Set the effective UID of the current process

  • « posix_setegid
  • posix_setgid »
  • PHP Manual
  • POSIX Functions
  • Set the effective UID of the current process

posix_seteuid

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

posix_seteuid — Set the effective UID of the current process

Description

posix_seteuid ( int $uid ) : bool

Set the effective user ID of the current process. This is a privileged function and needs appropriate privileges (usually root) on the system to be able to perform this function.

Parameters

uid

The user id.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • posix_geteuid() - Return the effective user ID of the current process
  • posix_setuid() - Set the UID of the current process
  • posix_getuid() - Return the real user ID of the current process


Set the GID of the current process

  • « posix_seteuid
  • posix_setpgid »
  • PHP Manual
  • POSIX Functions
  • Set the GID of the current process

posix_setgid

(PHP 4, PHP 5, PHP 7)

posix_setgid — Set the GID of the current process

Description

posix_setgid ( int $gid ) : bool

Set the real group ID of the current process. This is a privileged function and needs appropriate privileges (usually root) on the system to be able to perform this function. The appropriate order of function calls is posix_setgid() first, posix_setuid() last.

Note:

If the caller is a super user, this will also set the effective group id.

Parameters

gid

The group id.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 posix_setgid() example

This example will print out the effective group id, once it is changed.

<?php
echo 'My real group id is '.posix_getgid(); //20
posix_setgid(40);
echo 'My real group id is '.posix_getgid(); //40
echo 'My effective group id is '.posix_getegid(); //40
?>

See Also

  • posix_getgrgid() - Return info about a group by group id
  • posix_getgid() - Return the real group ID of the current process


Set process group id for job control

  • « posix_setgid
  • posix_setrlimit »
  • PHP Manual
  • POSIX Functions
  • Set process group id for job control

posix_setpgid

(PHP 4, PHP 5, PHP 7)

posix_setpgid — Set process group id for job control

Description

posix_setpgid ( int $pid , int $pgid ) : bool

Let the process pid join the process group pgid.

Parameters

pid

The process id.

pgid

The process group id.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • See POSIX.1 and the setsid(2) manual page on the POSIX system for more informations on process groups and job control.


Set system resource limits

  • « posix_setpgid
  • posix_setsid »
  • PHP Manual
  • POSIX Functions
  • Set system resource limits

posix_setrlimit

(PHP 7)

posix_setrlimit — Set system resource limits

Description

posix_setrlimit ( int $resource , int $softlimit , int $hardlimit ) : bool

posix_setrlimit() sets the soft and hard limits for a given system resource.

Each resource has an associated soft and hard limit. The soft limit is the value that the kernel enforces for the corresponding resource. The hard limit acts as a ceiling for the soft limit. An unprivileged process may only set its soft limit to a value from 0 to the hard limit, and irreversibly lower its hard limit.

Parameters

resource

The resource limit constant corresponding to the limit that is being set.

softlimit

The soft limit, in whatever unit the resource limit requires, or POSIX_RLIMIT_INFINITY.

hardlimit

The hard limit, in whatever unit the resource limit requires, or POSIX_RLIMIT_INFINITY.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • man page SETRLIMIT(2)
  • posix_getrlimit() - Return info about system resource limits


Make the current process a session leader

  • « posix_setrlimit
  • posix_setuid »
  • PHP Manual
  • POSIX Functions
  • Make the current process a session leader

posix_setsid

(PHP 4, PHP 5, PHP 7)

posix_setsid — Make the current process a session leader

Description

posix_setsid ( void ) : int

Make the current process a session leader.

Return Values

Returns the session id, or -1 on errors.

See Also

  • The POSIX.1 and the setsid(2) manual page on the POSIX system for more information on process groups and job control.


Set the UID of the current process

  • « posix_setsid
  • posix_strerror »
  • PHP Manual
  • POSIX Functions
  • Set the UID of the current process

posix_setuid

(PHP 4, PHP 5, PHP 7)

posix_setuid — Set the UID of the current process

Description

posix_setuid ( int $uid ) : bool

Set the real user ID of the current process. This is a privileged function that needs appropriate privileges (usually root) on the system to be able to perform this function.

Parameters

uid

The user id.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 posix_setuid() example

This example will show the current user id and then set it to a different value.

<?php
echo posix_getuid()."\n"; //10001
echo posix_geteuid()."\n"; //10001
posix_setuid(10000);
echo posix_getuid()."\n"; //10000
echo posix_geteuid()."\n"; //10000
?>

See Also

  • posix_setgid() - Set the GID of the current process
  • posix_seteuid() - Set the effective UID of the current process
  • posix_getuid() - Return the real user ID of the current process
  • posix_geteuid() - Return the effective user ID of the current process


Retrieve the system error message associated with the given errno

  • « posix_setuid
  • posix_times »
  • PHP Manual
  • POSIX Functions
  • Retrieve the system error message associated with the given errno

posix_strerror

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

posix_strerror — Retrieve the system error message associated with the given errno

Description

posix_strerror ( int $errno ) : string

Returns the POSIX system error message associated with the given errno. You may get the errno parameter by calling posix_get_last_error().

Parameters

errno

A POSIX error number, returned by posix_get_last_error(). If set to 0, then the string "Success" is returned.

Return Values

Returns the error message, as a string.

Examples

Example #1 posix_strerror() example

This example will attempt to kill a process which does not exist, then will print out the corresponding error message.

<?php
posix_kill(50,SIGKILL);
echo posix_strerror(posix_get_last_error())."\n";
?>

The above example will output something similar to:

No such process

See Also

  • posix_get_last_error() - Retrieve the error number set by the last posix function that failed


Get process times

  • « posix_strerror
  • posix_ttyname »
  • PHP Manual
  • POSIX Functions
  • Get process times

posix_times

(PHP 4, PHP 5, PHP 7)

posix_times — Get process times

Description

posix_times ( void ) : array

Gets information about the current CPU usage.

Return Values

Returns a hash of strings with information about the current process CPU usage. The indices of the hash are:

  • ticks - the number of clock ticks that have elapsed since reboot.
  • utime - user time used by the current process.
  • stime - system time used by the current process.
  • cutime - user time used by current process and children.
  • cstime - system time used by current process and children.

Notes

Warning

This function isn't reliable to use, it may return negative values for high times.

Examples

Example #1 Example use of posix_times()

<?php

$times = posix_times();

print_r($times);
?>

The above example will output something similar to:

Array
(
    [ticks] => 25814410
    [utime] => 1
    [stime] => 1
    [cutime] => 0
    [cstime] => 0
)


Determine terminal device name

  • « posix_times
  • posix_uname »
  • PHP Manual
  • POSIX Functions
  • Determine terminal device name

posix_ttyname

(PHP 4, PHP 5, PHP 7)

posix_ttyname — Determine terminal device name

Description

posix_ttyname ( mixed $fd ) : string

Returns a string for the absolute path to the current terminal device that is open on the file descriptor fd.

Parameters

fd

The file descriptor, which is expected to be either a file resource or an integer. An integer will be assumed to be a file descriptor that can be passed directly to the underlying system call.

In almost all cases, you will want to provide a file resource.

Return Values

On success, returns a string of the absolute path of the fd. On failure, returns FALSE


Get system name

  • « posix_ttyname
  • Program execution »
  • PHP Manual
  • POSIX Functions
  • Get system name

posix_uname

(PHP 4, PHP 5, PHP 7)

posix_uname — Get system name

Description

posix_uname ( void ) : array

Gets information about the system.

Posix requires that assumptions must not be made about the format of the values, e.g. the assumption that a release may contain three digits or anything else returned by this function.

Return Values

Returns a hash of strings with information about the system. The indices of the hash are

  • sysname - operating system name (e.g. Linux)
  • nodename - system name (e.g. valiant)
  • release - operating system release (e.g. 2.2.10)
  • version - operating system version (e.g. #4 Tue Jul 20 17:01:36 MEST 1999)
  • machine - system architecture (e.g. i586)
  • domainname - DNS domainname (e.g. example.com)

domainname is a GNU extension and not part of POSIX.1, so this field is only available on GNU systems or when using the GNU libc.

Examples

Example #1 Example use of posix_uname()

<?php
$uname=posix_uname();
print_r($uname);
?>

The above example will output something similar to:

Array
(
    [sysname] => Linux
    [nodename] => funbox
    [release] => 2.6.20-15-server
    [version] => #2 SMP Sun Apr 15 07:41:34 UTC 2007
    [machine] => i686
)


System program execution

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Program execution Functions
    • escapeshellarg — Escape a string to be used as a shell argument
    • escapeshellcmd — Escape shell metacharacters
    • exec — Execute an external program
    • passthru — Execute an external program and display raw output
    • proc_close — Close a process opened by proc_open and return the exit code of that process
    • proc_get_status — Get information about a process opened by proc_open
    • proc_nice — Change the priority of the current process
    • proc_open — Execute a command and open file pointers for input/output
    • proc_terminate — Kills a process opened by proc_open
    • shell_exec — Execute command via shell and return the complete output as a string
    • system — Execute an external program and display the output


Introduction

Those functions provide means to execute commands on the system itself, and means to secure such commands.

Note:

All execution functions call the commands through cmd.exe under Windows. Therefore the user calling these functions needs appropriate privilege to run this command. The only exception is proc_open() with bypass_shell option.


  • « Runtime Configuration
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

This extension defines a process resource, returned by proc_open().


  • « Resource Types
  • Program execution Functions »
  • PHP Manual
  • Program execution
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


Program execution Functions

Notes

Warning

Open files with lock (especially open sessions) should be closed before executing a program in the background.

See Also

These functions are also closely related to the backtick operator. Also, while in safe mode you must consider the safe_mode_exec_dir directive.

Table of Contents

  • escapeshellarg — Escape a string to be used as a shell argument
  • escapeshellcmd — Escape shell metacharacters
  • exec — Execute an external program
  • passthru — Execute an external program and display raw output
  • proc_close — Close a process opened by proc_open and return the exit code of that process
  • proc_get_status — Get information about a process opened by proc_open
  • proc_nice — Change the priority of the current process
  • proc_open — Execute a command and open file pointers for input/output
  • proc_terminate — Kills a process opened by proc_open
  • shell_exec — Execute command via shell and return the complete output as a string
  • system — Execute an external program and display the output


Escape a string to be used as a shell argument

  • « Program execution Functions
  • escapeshellcmd »
  • PHP Manual
  • Program execution Functions
  • Escape a string to be used as a shell argument

escapeshellarg

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

escapeshellarg — Escape a string to be used as a shell argument

Description

escapeshellarg ( string $arg ) : string

escapeshellarg() adds single quotes around a string and quotes/escapes any existing single quotes allowing you to pass a string directly to a shell function and having it be treated as a single safe argument. This function should be used to escape individual arguments to shell functions coming from user input. The shell functions include exec(), system() and the backtick operator.

On Windows, escapeshellarg() instead replaces percent signs, exclamation marks (delayed variable substitution) and double quotes with spaces and adds double quotes around the string.

Parameters

arg

The argument that will be escaped.

Return Values

The escaped string.

Examples

Example #1 escapeshellarg() example

<?php
system('ls '.escapeshellarg($dir));
?>

Changelog

Version | Description
5.4.43, 5.5.27, 5.6.11 | Exclamation marks are replaced by spaces.

See Also

  • escapeshellcmd() - Escape shell metacharacters
  • exec() - Execute an external program
  • popen() - Opens process file pointer
  • system() - Execute an external program and display the output
  • backtick operator


Escape shell metacharacters

  • « escapeshellarg
  • exec »
  • PHP Manual
  • Program execution Functions
  • Escape shell metacharacters

escapeshellcmd

(PHP 4, PHP 5, PHP 7)

escapeshellcmd — Escape shell metacharacters

Description

escapeshellcmd ( string $command ) : string

escapeshellcmd() escapes any characters in a string that might be used to trick a shell command into executing arbitrary commands. This function should be used to make sure that any data coming from user input is escaped before this data is passed to the exec() or system() functions, or to the backtick operator.

Following characters are preceded by a backslash: &#;`|*?~<>^()[]{}$\, \x0A and \xFF. ' and " are escaped only if they are not paired. In Windows, all these characters plus % and ! are replaced by a space instead.

Parameters

command

The command that will be escaped.

Return Values

The escaped string.

Examples

Example #1 escapeshellcmd() example

<?php
// We allow arbitrary number of arguments intentionally here.
$command = './configure '.$_POST['configure_options'];

$escaped_command = escapeshellcmd($command);

system($escaped_command);
?>

Warning

escapeshellcmd() should be used on the whole command string, and it still allows the attacker to pass arbitrary number of arguments. For escaping a single argument escapeshellarg() should be used instead.

Changelog

Version | Description
5.4.43, 5.5.27, 5.6.11 | Exclamation marks are replaced by spaces.

See Also

  • escapeshellarg() - Escape a string to be used as a shell argument
  • exec() - Execute an external program
  • popen() - Opens process file pointer
  • system() - Execute an external program and display the output
  • backtick operator


Execute an external program

  • « escapeshellcmd
  • passthru »
  • PHP Manual
  • Program execution Functions
  • Execute an external program

exec

(PHP 4, PHP 5, PHP 7)

exec — Execute an external program

Description

exec ( string $command [, array &$output [, int &$return_var ]] ) : string

exec() executes the given command.

Parameters

command

The command that will be executed.

output

If the output argument is present, then the specified array will be filled with every line of output from the command. Trailing whitespace, such as \n, is not included in this array. Note that if the array already contains some elements, exec() will append to the end of the array. If you do not want the function to append elements, call unset() on the array before passing it to exec().

return_var

If the return_var argument is present along with the output argument, then the return status of the executed command will be written to this variable.

Return Values

The last line from the result of the command. If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.

To get the output of the executed command, be sure to set and use the output parameter.

Examples

Example #1 An exec() example

<?php
// outputs the username that owns the running php/httpd process
// (on a system with the "whoami" executable in the path)
echo exec('whoami');
?>

Notes

Warning

When allowing user-supplied data to be passed to this function, use escapeshellarg() or escapeshellcmd() to ensure that users cannot trick the system into executing arbitrary commands.

Note:

If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.

Note:

On Windows exec() will first start cmd.exe to launch the command. If you want to start an external program without starting cmd.exe use proc_open() with the bypass_shell option set.

Note: When safe mode is enabled, you can only execute files within the safe_mode_exec_dir. For practical reasons, it is currently not allowed to have .. components in the path to the executable.

Warning

With safe mode enabled, the command string is escaped with escapeshellcmd(). Thus, echo y | echo x becomes echo y \| echo x.

See Also

  • system() - Execute an external program and display the output
  • passthru() - Execute an external program and display raw output
  • escapeshellcmd() - Escape shell metacharacters
  • pcntl_exec() - Executes specified program in current process space
  • backtick operator


Execute an external program and display raw output

  • « exec
  • proc_close »
  • PHP Manual
  • Program execution Functions
  • Execute an external program and display raw output

passthru

(PHP 4, PHP 5, PHP 7)

passthru — Execute an external program and display raw output

Description

passthru ( string $command [, int &$return_var ] ) : void

The passthru() function is similar to the exec() function in that it executes a command. This function should be used in place of exec() or system() when the output from the Unix command is binary data which needs to be passed directly back to the browser. A common use for this is to execute something like the pbmplus utilities that can output an image stream directly. By setting the Content-type to image/gif and then calling a pbmplus program to output a gif, you can create PHP scripts that output images directly.

Parameters

command

The command that will be executed.

return_var

If the return_var argument is present, the return status of the Unix command will be placed here.

Return Values

No value is returned.

Notes

Warning

When allowing user-supplied data to be passed to this function, use escapeshellarg() or escapeshellcmd() to ensure that users cannot trick the system into executing arbitrary commands.

Note:

If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.

Note: When safe mode is enabled, you can only execute files within the safe_mode_exec_dir. For practical reasons, it is currently not allowed to have .. components in the path to the executable.

Warning

With safe mode enabled, the command string is escaped with escapeshellcmd(). Thus, echo y | echo x becomes echo y \| echo x.

See Also

  • exec() - Execute an external program
  • system() - Execute an external program and display the output
  • popen() - Opens process file pointer
  • escapeshellcmd() - Escape shell metacharacters
  • backtick operator


Close a process opened by proc_open and return the exit code of that process

  • « passthru
  • proc_get_status »
  • PHP Manual
  • Program execution Functions
  • Close a process opened by proc_open and return the exit code of that process

proc_close

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

proc_close — Close a process opened by proc_open() and return the exit code of that process

Description

proc_close ( resource $process ) : int

proc_close() is similar to pclose() except that it only works on processes opened by proc_open(). proc_close() waits for the process to terminate, and returns its exit code. If you have open pipes to that process, you should fclose() them prior to calling this function in order to avoid a deadlock - the child process may not be able to exit while the pipes are open.

Parameters

process

The proc_open() resource that will be closed.

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.


Get information about a process opened by proc_open

  • « proc_close
  • proc_nice »
  • PHP Manual
  • Program execution Functions
  • Get information about a process opened by proc_open

proc_get_status

(PHP 5, PHP 7)

proc_get_status — Get information about a process opened by proc_open()

Description

proc_get_status ( resource $process ) : array

proc_get_status() fetches data about a process opened using proc_open().

Parameters

process

The proc_open() resource that will be evaluated.

Return Values

An array of collected information on success, and FALSE on failure. The returned array contains the following elements:

element | type | description
command | string | The command string that was passed to proc_open().
pid | int | process id
running | bool | TRUE if the process is still running, FALSE if it has terminated.
signaled | bool | TRUE if the child process has been terminated by an uncaught signal. Always set to FALSE on Windows.
stopped | bool | TRUE if the child process has been stopped by a signal. Always set to FALSE on Windows.
exitcode | int | The exit code returned by the process (which is only meaningful if running is FALSE). Only first call of this function return real value, next calls return -1.
termsig | int | The number of the signal that caused the child process to terminate its execution (only meaningful if signaled is TRUE).
stopsig | int | The number of the signal that caused the child process to stop its execution (only meaningful if stopped is TRUE).

See Also

  • proc_open() - Execute a command and open file pointers for input/output


Change the priority of the current process

  • « proc_get_status
  • proc_open »
  • PHP Manual
  • Program execution Functions
  • Change the priority of the current process

proc_nice

(PHP 5, PHP 7)

proc_nice — Change the priority of the current process

Description

proc_nice ( int $increment ) : bool

proc_nice() changes the priority of the current process by the amount specified in increment. A positive increment will lower the priority of the current process, whereas a negative increment will raise the priority.

proc_nice() is not related to proc_open() and its associated functions in any way.

Parameters

increment

The new priority value, the value of this may differ on platforms.

On Unix, a low value, such as -20 means high priority wheras a positive value have a lower priority.

For Windows the increment parameter have the following meanings:

Priority class | Possible values
High priority | increment < -9
Above normal priority | increment < -4
Normal priority | increment < 5 & increment > -5
Below normal priority | increment > 5
Idle priority | increment > 9

Return Values

Returns TRUE on success or FALSE on failure. If an error occurs, like the user lacks permission to change the priority, an error of level E_WARNING is also generated.

Examples

Example #1 Using proc_nice() to set the process priority to high

<?php
// Highest priority
proc_nice(-20);
?>

Changelog

Version | Description
7.2.0 | This function is now available on Windows.

Notes

Note: Availability

proc_nice() will only exist if your system has 'nice' capabilities. 'nice' conforms to: SVr4, SVID EXT, AT&T, X/OPEN, BSD 4.3.

Note: Windows only

proc_nice() will change the current process priority, even if PHP was compiled using thread safety.


Execute a command and open file pointers for input/output

  • « proc_nice
  • proc_terminate »
  • PHP Manual
  • Program execution Functions
  • Execute a command and open file pointers for input/output

proc_open

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

proc_open — Execute a command and open file pointers for input/output

Description

proc_open ( string $cmd , array $descriptorspec , array &$pipes [, string $cwd = NULL [, array $env = NULL [, array $other_options = NULL ]]] ) : resource

proc_open() is similar to popen() but provides a much greater degree of control over the program execution.

Parameters

cmd

The command to execute

descriptorspec

An indexed array where the key represents the descriptor number and the value represents how PHP will pass that descriptor to the child process. 0 is stdin, 1 is stdout, while 2 is stderr.

Each element can be:

  • An array describing the pipe to pass to the process. The first element is the descriptor type and the second element is an option for the given type. Valid types are pipe (the second element is either r to pass the read end of the pipe to the process, or w to pass the write end) and file (the second element is a filename).
  • A stream resource representing a real file descriptor (e.g. opened file, a socket, STDIN).

The file descriptor numbers are not limited to 0, 1 and 2 - you may specify any valid file descriptor number and it will be passed to the child process. This allows your script to interoperate with other scripts that run as "co-processes". In particular, this is useful for passing passphrases to programs like PGP, GPG and openssl in a more secure manner. It is also useful for reading status information provided by those programs on auxiliary file descriptors.

pipes

Will be set to an indexed array of file pointers that correspond to PHP's end of any pipes that are created.

cwd

The initial working dir for the command. This must be an absolute directory path, or NULL if you want to use the default value (the working dir of the current PHP process)

env

An array with the environment variables for the command that will be run, or NULL to use the same environment as the current PHP process

other_options

Allows you to specify additional options. Currently supported options include:

  • suppress_errors (windows only): suppresses errors generated by this function when it's set to TRUE
  • bypass_shell (windows only): bypass cmd.exe shell when set to TRUE
  • blocking_pipes (windows only): force blocking pipes when set to TRUE
  • create_process_group (windows only): allow the child process to handle CTRL events when set to TRUE

Return Values

Returns a resource representing the process, which should be freed using proc_close() when you are finished with it. On failure returns FALSE.

Changelog

Version | Description
7.4.0 | Added the create_process_group option to the other_options parameter.
7.0.0 | Added the blocking_pipes option to the other_options parameter.
5.2.1 | Added the bypass_shell option to the other_options parameter.

Examples

Example #1 A proc_open() example

<?php
$descriptorspec = array(
   0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
   1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
   2 => array("file", "/tmp/error-output.txt", "a") // stderr is a file to write to
);

$cwd = '/tmp';
$env = array('some_option' => 'aeiou');

$process = proc_open('php', $descriptorspec, $pipes, $cwd, $env);

if (is_resource($process)) {
    // $pipes now looks like this:
    // 0 => writeable handle connected to child stdin
    // 1 => readable handle connected to child stdout
    // Any error output will be appended to /tmp/error-output.txt

    fwrite($pipes[0], '<?php print_r($_ENV); ?>');
    fclose($pipes[0]);

    echo stream_get_contents($pipes[1]);
    fclose($pipes[1]);

    // It is important that you close any pipes before calling
    // proc_close in order to avoid a deadlock
    $return_value = proc_close($process);

    echo "command returned $return_value\n";
}
?>

The above example will output something similar to:

Array
(
    [some_option] => aeiou
    [PWD] => /tmp
    [SHLVL] => 1
    [_] => /usr/local/bin/php
)
command returned 0

Notes

Note:

Windows compatibility: Descriptors beyond 2 (stderr) are made available to the child process as inheritable handles, but since the Windows architecture does not associate file descriptor numbers with low-level handles, the child process does not (yet) have a means of accessing those handles. Stdin, stdout and stderr work as expected.

Note:

If you only need a uni-directional (one-way) process pipe, use popen() instead, as it is much easier to use.

See Also

  • popen() - Opens process file pointer
  • exec() - Execute an external program
  • system() - Execute an external program and display the output
  • passthru() - Execute an external program and display raw output
  • stream_select() - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec
  • The backtick operator


Kills a process opened by proc_open

  • « proc_open
  • shell_exec »
  • PHP Manual
  • Program execution Functions
  • Kills a process opened by proc_open

proc_terminate

(PHP 5, PHP 7)

proc_terminate — Kills a process opened by proc_open

Description

proc_terminate ( resource $process [, int $signal = 15 ] ) : bool

Signals a process (created using proc_open()) that it should terminate. proc_terminate() returns immediately and does not wait for the process to terminate.

proc_terminate() allows you terminate the process and continue with other tasks. You may poll the process (to see if it has stopped yet) by using the proc_get_status() function.

Parameters

process

The proc_open() resource that will be closed.

signal

This optional parameter is only useful on POSIX operating systems; you may specify a signal to send to the process using the kill(2) system call. The default is SIGTERM.

Return Values

Returns the termination status of the process that was run.

Changelog

Version | Description
5.2.2 | Previous versions used to destroy the given process resource.

See Also

  • proc_open() - Execute a command and open file pointers for input/output
  • proc_close() - Close a process opened by proc_open and return the exit code of that process
  • proc_get_status() - Get information about a process opened by proc_open


Execute command via shell and return the complete output as a string

  • « proc_terminate
  • system »
  • PHP Manual
  • Program execution Functions
  • Execute command via shell and return the complete output as a string

shell_exec

(PHP 4, PHP 5, PHP 7)

shell_exec — Execute command via shell and return the complete output as a string

Description

shell_exec ( string $cmd ) : string

This function is identical to the backtick operator.

Note:

On Windows, the underlying pipe is opened in text mode which can cause the function to fail for binary output. Consider to use popen() instead for such cases.

Parameters

cmd

The command that will be executed.

Return Values

The output from the executed command or NULL if an error occurred or the command produces no output.

Note:

This function can return NULL both when an error occurs or the program produces no output. It is not possible to detect execution failures using this function. exec() should be used when access to the program exit code is required.

Examples

Example #1 A shell_exec() example

<?php
$output = shell_exec('ls -lart');
echo "<pre>$output</pre>";
?>

Notes

Note:

This function is disabled when PHP is running in safe mode.

See Also

  • exec() - Execute an external program
  • escapeshellcmd() - Escape shell metacharacters


Execute an external program and display the output

  • « shell_exec
  • parallel »
  • PHP Manual
  • Program execution Functions
  • Execute an external program and display the output

system

(PHP 4, PHP 5, PHP 7)

system — Execute an external program and display the output

Description

system ( string $command [, int &$return_var ] ) : string

system() is just like the C version of the function in that it executes the given command and outputs the result.

The system() call also tries to automatically flush the web server's output buffer after each line of output if PHP is running as a server module.

If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.

Parameters

command

The command that will be executed.

return_var

If the return_var argument is present, then the return status of the executed command will be written to this variable.

Return Values

Returns the last line of the command output on success, and FALSE on failure.

Examples

Example #1 system() example

<?php
echo '<pre>';

// Outputs all the result of shellcommand "ls", and returns
// the last output line into $last_line. Stores the return value
// of the shell command in $retval.
$last_line = system('ls', $retval);

// Printing additional info
echo '
</pre>
<hr />Last line of the output: ' . $last_line . '
<hr />Return value: ' . $retval;
?>

Notes

Warning

When allowing user-supplied data to be passed to this function, use escapeshellarg() or escapeshellcmd() to ensure that users cannot trick the system into executing arbitrary commands.

Note:

If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.

Note: When safe mode is enabled, you can only execute files within the safe_mode_exec_dir. For practical reasons, it is currently not allowed to have .. components in the path to the executable.

Warning

With safe mode enabled, the command string is escaped with escapeshellcmd(). Thus, echo y | echo x becomes echo y \| echo x.

See Also

  • exec() - Execute an external program
  • passthru() - Execute an external program and display raw output
  • popen() - Opens process file pointer
  • escapeshellcmd() - Escape shell metacharacters
  • pcntl_exec() - Executes specified program in current process space
  • backtick operator


parallel

  • Introduction
  • Installation
  • Philosophy
  • Functional API
    • parallel\bootstrap — Bootstrapping
    • parallel\run — Execution
  • parallel\Runtime — The parallel\Runtime class
    • parallel\Runtime::__construct — Runtime Construction
    • parallel\Runtime::run — Execution
    • parallel\Runtime::close — Runtime Graceful Join
    • parallel\Runtime::kill — Runtime Join
  • parallel\Future — The parallel\Future class
    • parallel\Future::cancel — Cancellation
    • parallel\Future::cancelled — State Detection
    • parallel\Future::done — State Detection
    • parallel\Future::value — Resolution
  • parallel\Channel — The parallel\Channel class
    • parallel\Channel::__construct — Channel Construction
    • parallel\Channel::make — Access
    • parallel\Channel::open — Access
    • parallel\Channel::recv — Sharing
    • parallel\Channel::send — Sharing
    • parallel\Channel::close — Closing
  • parallel\Events — The parallel\Events class
    • parallel\Events::setBlocking — Behaviour
    • parallel\Events::setTimeout — Behaviour
    • parallel\Events::setInput — Input
    • parallel\Events::addChannel — Targets
    • parallel\Events::addFuture — Targets
    • parallel\Events::remove — Targets
    • parallel\Events::poll — Polling
  • parallel\Events\Input — The parallel\Events\Input class
    • parallel\Events\Input::add — Inputs
    • parallel\Events\Input::clear — Inputs
    • parallel\Events\Input::remove — Inputs
  • parallel\Events\Event — The parallel\Events\Event class
  • parallel\Events\Event\Type — The parallel\Events\Event\Type class
  • parallel\Sync — The parallel\Sync class
    • parallel\Sync::__construct — Construction
    • parallel\Sync::get — Access
    • parallel\Sync::set — Access
    • parallel\Sync::wait — Synchronization
    • parallel\Sync::notify — Synchronization
    • parallel\Sync::__invoke — Synchronization


Introduction

parallel is a parallel concurrency extension for PHP 7.2+.

A brief description of the concepts core to parallel follows, more detailed information may be found within this section of the manual.

Runtime

A parallel\Runtime represents a PHP interpreter thread. A parallel\Runtime is configured with an optional bootstrap file passed to parallel\Runtime::__construct(), this is typically an autoloader, or some other preloading routine: The bootstrap file will be included before any task is executed.

After construction the parallel\Runtime remains available until it is closed, killed, or destroyed by the normal scoping rules of PHP objects. parallel\Runtime::run() allows the programmer to schedule tasks for execution in parallel. A parallel\Runtime has a FIFO schedule, tasks will be executed in the order that they are scheduled.

Functional API

parallel implements a functional, higher level API on top of parallel\Runtime that provides a single function entry point to executing parallel code with automatic scheduling: parallel\run().

Task

A task is simply a Closure intended for parallel execution. The Closure may contain almost any instruction, including nested closures. However, there are some instructions that are prohibited in tasks:

  • yield

  • use by-reference

  • declare class

  • declare named function

Note:

Nested closures may yield or use by-reference, but must not contain class or named function declarations.

Note:

No instructions are prohibited in the files which the task may include.

Future

The parallel\Future is used to access the return value from the task, and exposes an API for cancellation of the task.

Channel

A task may be scheduled with arguments, use lexical scope variables (by-value), and return a value (via a parallel\Future), but these only allow uni-directional communication: They allow the programmer to send data into and retrieve data from a task, but do not allow bi-directional communication between tasks. The parallel\Channel API allows bi-directional communication between tasks, a parallel\Channel is a socket-like link between tasks that the programmer can use to send and receive data.

Events

The parallel\Events API implements a native feel (Traversable) event loop, and parallel\Events::poll() method. It allows the programmer to work with sets of channels and or futures. The programmer simply adds channels and futures to the event loop, optionally setting the input for writes with parallel\Events::setInput(), and enters into a foreach: parallel will read from and write to objects as they become available yielding parallel\Events\Event objects describing the operations that have occurred.

See Also

  • Philosophy


Installation

Requirements

parallel requires a build of PHP with ZTS (Zend Thread Safety) enabled ( --enable-maintainer-zts or --enable-zts on Windows )

Caution

Zend Thread Safety cannot be enabled post build; it is a build time configuration option.

parallel should build anywhere there is a working Posix Threads header (pthread.h) and ZTS build of PHP, including Windows (using the pthread-w32 project from redhat).

Installation

parallel 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/parallel.

Windows users can download prebuilt release binaries from the » PECL website.

Caution

Windows users need to take the additional step of adding pthreadVC2.dll (distributed with Windows releases) to their PATH.


Philosophy

This section contains philosophies important to writing parallel code and some details about the internal implementation of parallel.

Do not communicate by sharing memory; instead, share memory by communicating.

This philosophy which is embraced by parallel has its origins in Go, one of the most widely admired if not used platforms for writing parallel code at the moment. Go programmers have to work hard to live up to this ideal: PHP and parallel do all the hard work for the programmer, and by default.

In conventional threading models found in other languages, generally threads are communicating with one another through nothing more than by virtue of the fact that they operate in the same address space. The programmer must deploy mutual exclusion, condition variables, and other low level threading or synchronization primitives in order to ensure proper communication of state and consistency.

When the conventional model is inversed, it means that threads only share memory as a result of communication (a variable is passed over a Channel for example).

When parallel passes a variable from one thread to another by any means - Task arguments, return via Future, and Channels - it is passed by value. In all but the case of unbuffered channels, the variable is also buffered so that it may not change (or be destroyed) before it is used in whichever thread the variable is being passed to. An unbuffered read over a channel is the only instance in which a thread directly reads memory allocated by another thread, it can do so safely because the thread that owns the memory is waiting for the read to complete before it can continue to manipulate it, and the thread that does not own the memory reads by value. When both threads continue, they are no longer sharing memory.

This makes writing and reasoning about parallel code much easier than the conventional model of threading. It means the programmer does not need to consider that threads may be manipulating data concurrently, because that is not possible.

This also makes PHP the perfect platform for implementing a parallel concurrency API based on CSP (message passing over channels), because PHP itself is shared nothing - PHP threads operate in their own virtual address space by default, and so may only share memory by communicating.

Data should have a definitive single owner

When approaching the CSP model for the first time, a programmer versed in the traditional model of threading may find themselves looking for concurrent data structures, because that is what they are used too: they pass around shared objects for manipulation.

When it comes to the CSP model, there is no need for data structures to be shared by many tasks, and indeed, it is simpler if they are not. The data should be owned by a single task, changes to (or operations on) that data structure should be communicated over channels and performed by the owner of the data, the success, failure, or result (state) of the change (or operation) being communicated back.

Once again the share nothing nature of PHP and copy by value nature of parallel helps the programmer to achieve this goal, no data will be shared by accident, only ever as a result of communication.


Functional API

The parallel\Runtime API provides a great degree of control to the power PHP programmer, and those intimately familiar with writing applications that use parallel concurrency.

The functional API provides less control in exchange for the ability to make decisions for the programmer:

  • all executing runtimes are bootstrapped identically

  • scheduling is determined by the API, not the programmer

parallel\run() provides the guarantee that the task will begin to execute in parallel as soon as allowed by hardware and operating system constraints, without needlessly creating runtimes. For most applications the functional API should be preferred.

Table of Contents

  • parallel\bootstrap — Bootstrapping
  • parallel\run — Execution


Bootstrapping

  • « Functional API
  • parallel\run »
  • PHP Manual
  • Functional API
  • Bootstrapping

parallel\bootstrap

(1.0.0)

parallel\bootstrap — Bootstrapping

Description

parallel\bootstrap ( string $file ) : void

Shall use the provided file to bootstrap all runtimes created for automatic scheduling via parallel\run().

Exceptions

Warning

Shall throw \parallel\Runtime\Error\Bootstrap if previously called for this process.

Warning

Shall throw \parallel\Runtime\Error\Bootstrap if called after parallel\run().

See Also

  • parallel\Runtime::run


Execution

  • « parallel\bootstrap
  • parallel\Runtime »
  • PHP Manual
  • Functional API
  • Execution

parallel\run

(1.0.0)

parallel\run — Execution

Description

parallel\run ( Closure $task ) : ?Future

Shall schedule task for execution in parallel.

parallel\run ( Closure $task , array $argv ) : ?Future

Shall schedule task for execution in parallel, passing argv at execution time.

Automatic Scheduling

If a \parallel\Runtime internally created and cached by a previous call to parallel\run() is idle, it will be used to execute the task. If no \parallel\Runtime is idle parallel will create and cache a \parallel\Runtime.

Note:

\parallel\Runtime objects created by the programmer are not used for automatic scheduling.

Parameters

task

A Closure with specific characteristics.

argv

An array of arguments with specific characteristics to be passed to task at execution time.

Task Characteristics

Closures scheduled for parallel execution must not:

  • accept or return by reference
  • accept or return internal objects (see notes)
  • execute a limited set of instructions

Instructions prohibited in Closures intended for parallel execution are:

  • yield
  • use by-reference
  • declare class
  • declare named function

Note:

Nested closures may yield or use by-reference, but must not contain class or named function declarations.

Note:

No instructions are prohibited in the files which the task may include.

Arguments Characteristics

Arguments must not:

  • contain references
  • contain resources
  • contain internal objects (see notes)

Note:

In the case of file stream resources, the resource will be cast to the file descriptor and passed as int where possible, this is unsupported on Windows.

Internal Objects Notes

Internal objects generally use a custom structure which cannot be copied by value safely, PHP currently lacks the mechanics to do this (without serialization) and so only objects that do not use a custom structure may be shared.

Some internal objects do not use a custom structure, for example parallel\Events\Event and so may be shared.

Closures are a special kind of internal object and support being copied by value, and so may be shared.

Channels are central to writing parallel code and support concurrent access and execution by necessity, and so may be shared.

Warning

A user class that extends an internal class may use a custom structure as defined by the internal class, in which case they cannot be copied by value safely, and so may not be shared.

Return Values

Warning

The return \parallel\Future must not be ignored when the task contains a return or throw statement.

Exceptions

Warning

Shall throw \parallel\Runtime\Error\Closed if \parallel\Runtime was closed.

Warning

Shall throw \parallel\Runtime\Error\IllegalFunction if task is a closure created from an internal function.

Warning

Shall throw \parallel\Runtime\Error\IllegalInstruction if task contains illegal instructions.

Warning

Shall throw \parallel\Runtime\Error\IllegalParameter if task accepts or argv contains illegal variables.

Warning

Shall throw \parallel\Runtime\Error\IllegalReturn if task returns illegally.

See Also

  • parallel\Runtime::run


The parallel\Runtime class

(0.8.0)

Runtime Objects

Each runtime represents a single PHP thread, the thread is created (and bootstrapped) upon construction. The thread then waits for tasks to be scheduled: Scheduled tasks will be executed FIFO and then the thread will resume waiting until more tasks are scheduled, or it's closed, killed, or destroyed by the normal scoping rules of PHP objects.

Warning

When a runtime is destroyed by the normal scoping rules of PHP objects, it will first execute all of the tasks that were scheduled, and block while doing so.

Runtime Bootstrapping

When a new runtime is created, it does not share code with the thread (or process) that created it. This means it doesn't have the same classes and functions loaded, nor the same autoloader set. In some cases, a very lightweight runtime is desirable because the tasks that will be scheduled do not need access to the code in the parent thread. In those cases where the tasks do need to access the same code, it is enough to set an autoloader as the bootstrap.

Note:

preloading may be used in conjunction with parallel, in this case preloaded code is available without bootstrapping

Class synopsis

final parallel\Runtime {
/* Create */
public __construct ( void )
public __construct ( string $bootstrap )
/* Execute */
public run ( Closure $task ) : ?Future
public run ( Closure $task , array $argv ) : ?Future
/* Join */
public close ( void ) : void
public kill ( void ) : void
}

Table of Contents

  • parallel\Runtime::__construct — Runtime Construction
  • parallel\Runtime::run — Execution
  • parallel\Runtime::close — Runtime Graceful Join
  • parallel\Runtime::kill — Runtime Join


Runtime Construction

  • « parallel\Runtime
  • parallel\Runtime::run »
  • PHP Manual
  • parallel\Runtime
  • Runtime Construction

parallel\Runtime::__construct

(0.8.0)

parallel\Runtime::__construct — Runtime Construction

Description

public parallel\Runtime::__construct ( void )

Shall construct a new runtime without bootstrapping.

public parallel\Runtime::__construct ( string $bootstrap )

Shall construct a bootstrapped runtime.

Parameters

bootstrap

The location of a bootstrap file, generally an autoloader.

Exceptions

Warning

Shall throw \parallel\Runtime\Error if thread could not be created

Warning

Shall throw \parallel\Runtime\Bootstrap if bootstrapping failed


Execution

  • « parallel\Runtime::__construct
  • parallel\Runtime::close »
  • PHP Manual
  • parallel\Runtime
  • Execution

parallel\Runtime::run

(0.8.0)

parallel\Runtime::run — Execution

Description

public parallel\Runtime::run ( Closure $task ) : ?Future

Shall schedule task for execution in parallel.

public parallel\Runtime::run ( Closure $task , array $argv ) : ?Future

Shall schedule task for execution in parallel, passing argv at execution time.

Parameters

task

A Closure with specific characteristics.

argv

An array of arguments with specific characteristics to be passed to task at execution time.

Task Characteristics

Closures scheduled for parallel execution must not:

  • accept or return by reference
  • accept or return internal objects (see notes)
  • execute a limited set of instructions

Instructions prohibited in Closures intended for parallel execution are:

  • yield
  • use by-reference
  • declare class
  • declare named function

Note:

Nested closures may yield or use by-reference, but must not contain class or named function declarations.

Note:

No instructions are prohibited in the files which the task may include.

Arguments Characteristics

Arguments must not:

  • contain references
  • contain resources
  • contain internal objects (see notes)

Note:

In the case of file stream resources, the resource will be cast to the file descriptor and passed as int where possible, this is unsupported on Windows.

Internal Objects Notes

Internal objects generally use a custom structure which cannot be copied by value safely, PHP currently lacks the mechanics to do this (without serialization) and so only objects that do not use a custom structure may be shared.

Some internal objects do not use a custom structure, for example parallel\Events\Event and so may be shared.

Closures are a special kind of internal object and support being copied by value, and so may be shared.

Channels are central to writing parallel code and support concurrent access and execution by necessity, and so may be shared.

Warning

A user class that extends an internal class may use a custom structure as defined by the internal class, in which case they cannot be copied by value safely, and so may not be shared.

Return Values

Warning

The return \parallel\Future must not be ignored when the task contains a return or throw statement.

Exceptions

Warning

Shall throw \parallel\Runtime\Error\Closed if \parallel\Runtime was closed.

Warning

Shall throw \parallel\Runtime\Error\IllegalFunction if task is a closure created from an internal function.

Warning

Shall throw \parallel\Runtime\Error\IllegalInstruction if task contains illegal instructions.

Warning

Shall throw \parallel\Runtime\Error\IllegalParameter if task accepts or argv contains illegal variables.

Warning

Shall throw \parallel\Runtime\Error\IllegalReturn if task returns illegally.


Runtime Graceful Join

  • « parallel\Runtime::run
  • parallel\Runtime::kill »
  • PHP Manual
  • parallel\Runtime
  • Runtime Graceful Join

parallel\Runtime::close

(0.8.0)

parallel\Runtime::close — Runtime Graceful Join

Description

public parallel\Runtime::close ( void ) : void

Shall request that the runtime shutsdown.

Note:

Tasks scheduled for execution will be executed before the shutdown occurs.

Exceptions

Warning

Shall throw \parallel\Runtime\Error\Closed if Runtime was already closed.


Runtime Join

  • « parallel\Runtime::close
  • parallel\Future »
  • PHP Manual
  • parallel\Runtime
  • Runtime Join

parallel\Runtime::kill

(0.8.0)

parallel\Runtime::kill — Runtime Join

Description

public parallel\Runtime::kill ( void ) : void

Shall attempt to force the runtime to shutdown.

Note:

Tasks scheduled for execution will not be executed, the currently running task shall be interrupted.

Warning

Internal function calls in progress cannot be interrupted.

Exceptions

Warning

Shall throw \parallel\Runtime\Error\Closed if Runtime was closed.


The parallel\Future class

(0.8.0)

Futures

A Future represents the return value or uncaught exception from a task, and exposes an API for cancellation.

Example #1 Example showing Future as return value

<?php
$runtime = new \parallel\Runtime;
$future  = $runtime->run(function(){
    return "World";
});
printf("Hello %s\n", $future->value());
?>

The above example will output something similar to:

Hello World

The behaviour of a future also allows it to be used as a simple synchronization point even where the task does not return a value explicitly.

Example #2 Example showing Future as synchronization point

<?php
$runtime = new \parallel\Runtime;
$future  = $runtime->run(function(){
    echo "in child ";
    for ($i = 0; $i < 500; $i++) {
        if ($i % 10 == 0) {
            echo ".";
        }
    }
    echo " leaving child";
});

$future->value();
echo "\nparent continues\n";
?>

The above example will output something similar to:

in child .................................................. leaving child
parent continues

Class synopsis

final parallel\Future {
/* Resolution */
public value ( void ) : mixed
/* State */
public cancelled ( void ) : bool
public done ( void ) : bool
/* Cancellation */
public cancel ( void ) : bool
}

Table of Contents

  • parallel\Future::cancel — Cancellation
  • parallel\Future::cancelled — State Detection
  • parallel\Future::done — State Detection
  • parallel\Future::value — Resolution


Cancellation

  • « parallel\Future
  • parallel\Future::cancelled »
  • PHP Manual
  • parallel\Future
  • Cancellation

parallel\Future::cancel

(0.9.0)

parallel\Future::cancel — Cancellation

Description

public parallel\Future::cancel ( void ) : bool

Shall try to cancel the task

Note:

If task is running, it will be interrupted.

Warning

Internal function calls in progress cannot be interrupted.

Exceptions

Warning

Shall throw \parallel\Future\Error\Killed if \parallel\Runtime executing task was killed.

Warning

Shall throw \parallel\Future\Error\Cancelled if task was already cancelled.


State Detection

  • « parallel\Future::cancel
  • parallel\Future::done »
  • PHP Manual
  • parallel\Future
  • State Detection

parallel\Future::cancelled

(0.9.0)

parallel\Future::cancelled — State Detection

Description

public parallel\Future::cancelled ( void ) : bool

Shall indicate if the task was cancelled


State Detection

  • « parallel\Future::cancelled
  • parallel\Future::value »
  • PHP Manual
  • parallel\Future
  • State Detection

parallel\Future::done

(0.8.0)

parallel\Future::done — State Detection

Description

public parallel\Future::done ( void ) : bool

Shall indicate if the task is completed


Resolution

  • « parallel\Future::done
  • parallel\Channel »
  • PHP Manual
  • parallel\Future
  • Resolution

parallel\Future::value

(0.8.0)

parallel\Future::value — Resolution

Description

public parallel\Future::value ( void ) : mixed

Shall return (and if necessary wait for) return from task

Exceptions

Warning

Shall throw \parallel\Future\Error if waiting failed (internal error).

Warning

Shall throw \parallel\Future\Error\Killed if \parallel\Runtime executing task was killed.

Warning

Shall throw \parallel\Future\Error\Cancelled if task was cancelled.

Warning

Shall throw \parallel\Future\Error\Foreign if task raised an unrecognized uncaught exception.

Warning

Shall rethrow \Throwable uncaught in task


The parallel\Channel class

(0.9.0)

Unbuffered Channels

An unbuffered channel will block on calls to parallel\Channel::send() until there is a receiver, and block on calls to parallel\Channel::recv() until there is a sender. This means an unbuffered channel is not only a way to share data among tasks but also a simple method of synchronization.

An unbuffered channel is the fastest way to share data among tasks, requiring the least copying.

Buffered Channels

A buffered channel will not block on calls to parallel\Channel::send() until capacity is reached, calls to parallel\Channel::recv() will block until there is data in the buffer.

Closures over Channels

A powerful feature of parallel channels is that they allow the exchange of closures between tasks (and runtimes).

When a closure is sent over a channel the closure is buffered, it doesn't change the buffering of the channel transmitting the closure, but it does effect the static scope inside the closure: The same closure sent to different runtimes, or the same runtime, will not share their static scope.

This means that whenever a closure is executed that was transmitted by a channel, static state will be as it was when the closure was buffered.

Anonymous Channels

The anonymous channel constructor allows the programmer to avoid assigning names to every channel: parallel will generate a unique name for anonymous channels.

Class synopsis

final parallel\Channel {
/* Anonymous Constructor */
public __construct ( void )
public __construct ( int $capacity )
/* Access */
public make ( string $name ) : Channel
public make ( string $name , int $capacity ) : Channel
public open ( string $name ) : Channel
/* Sharing */
public recv ( void ) : mixed
public send ( mixed $value ) : void
/* Closing */
public close ( void ) : void
/* Constant for Infinitely Buffered */
const Infinite ;
}

Table of Contents

  • parallel\Channel::__construct — Channel Construction
  • parallel\Channel::make — Access
  • parallel\Channel::open — Access
  • parallel\Channel::recv — Sharing
  • parallel\Channel::send — Sharing
  • parallel\Channel::close — Closing


Channel Construction

  • « parallel\Channel
  • parallel\Channel::make »
  • PHP Manual
  • parallel\Channel
  • Channel Construction

parallel\Channel::__construct

(1.1.0)

parallel\Channel::__construct — Channel Construction

Description

public parallel\Channel::__construct ( void )

Shall make an anonymous unbuffered channel

public parallel\Channel::__construct ( int $capacity )

Shall make an anonymous buffered channel with the given capacity

Parameters

capacity

May be Channel::Infinite or a positive integer


Access

  • « parallel\Channel::__construct
  • parallel\Channel::open »
  • PHP Manual
  • parallel\Channel
  • Access

parallel\Channel::make

(0.9.0)

parallel\Channel::make — Access

Description

public parallel\Channel::make ( string $name ) : Channel

Shall make an unbuffered channel with the given name

public parallel\Channel::make ( string $name , int $capacity ) : Channel

Shall make a buffered channel with the given name and capacity

Parameters

name

The name of the channel.

capacity

May be Channel::Infinite or a positive integer

Exceptions

Warning

Shall throw \parallel\Channel\Error\Existence if channel already exists.


Access

  • « parallel\Channel::make
  • parallel\Channel::recv »
  • PHP Manual
  • parallel\Channel
  • Access

parallel\Channel::open

(0.9.0)

parallel\Channel::open — Access

Description

public parallel\Channel::open ( string $name ) : Channel

Shall open the channel with the given name

Exceptions

Warning

Shall throw \parallel\Channel\Error\Existence if channel does not exist.


Sharing

  • « parallel\Channel::open
  • parallel\Channel::send »
  • PHP Manual
  • parallel\Channel
  • Sharing

parallel\Channel::recv

(0.9.0)

parallel\Channel::recv — Sharing

Description

public parallel\Channel::recv ( void ) : mixed

Shall recv a value from this channel

Exceptions

Warning

Shall throw \parallel\Channel\Error\Closed if channel is closed.


Sharing

  • « parallel\Channel::recv
  • parallel\Channel::close »
  • PHP Manual
  • parallel\Channel
  • Sharing

parallel\Channel::send

(0.9.0)

parallel\Channel::send — Sharing

Description

public parallel\Channel::send ( mixed $value ) : void

Shall send the given value on this channel

Exceptions

Warning

Shall throw \parallel\Channel\Error\Closed if channel is closed.

Warning

Shall throw \parallel\Channel\Error\IllegalValue if value is illegal.


Closing

  • « parallel\Channel::send
  • parallel\Events »
  • PHP Manual
  • parallel\Channel
  • Closing

parallel\Channel::close

(0.9.0)

parallel\Channel::close — Closing

Description

public parallel\Channel::close ( void ) : void

Shall close this channel

Exceptions

Warning

Shall throw \parallel\Channel\Error\Closed if channel is closed.


The parallel\Events class

(0.9.0)

The Event Loop

The Event loop monitors the state of sets of futures and or channels (targets) in order to perform read (parallel\Future::value(), parallel\Channel::recv()) and write (parallel\Channel::send()) operations as the targets become available and the operations may be performed without blocking the event loop.

Class synopsis

final parallel\Events implements Countable , Traversable {
/* Input */
public setInput ( Input $input ) : void
/* Targets */
public addChannel ( parallel\Channel $channel ) : void
public addFuture ( string $name , parallel\Future $future ) : void
public remove ( string $target ) : void
/* Behaviour */
public setBlocking ( bool $blocking ) : void
public setTimeout ( int $timeout ) : void
/* Polling */
public poll ( void ) : ?Event
}

Table of Contents

  • parallel\Events::setBlocking — Behaviour
  • parallel\Events::setTimeout — Behaviour
  • parallel\Events::setInput — Input
  • parallel\Events::addChannel — Targets
  • parallel\Events::addFuture — Targets
  • parallel\Events::remove — Targets
  • parallel\Events::poll — Polling


Behaviour

  • « parallel\Events
  • parallel\Events::setTimeout »
  • PHP Manual
  • parallel\Events
  • Behaviour

parallel\Events::setBlocking

(0.9.0)

parallel\Events::setBlocking — Behaviour

Description

By default when events are polled for, blocking will occur (at the PHP level) until the first event can be returned: Setting blocking mode to false will cause poll to return control if the first target polled is not ready.

This differs from setting a timeout of 0 with parallel\Events::setTimeout(), since a timeout of 0, while allowed, will cause an exception to be raised, which may be extremely slow or wasteful if what is really desired is non-blocking behaviour.

A non-blocking loop effects the return value of parallel\Events::poll(), such that it may be null before all events have been processed.

public parallel\Events::setBlocking ( bool $blocking ) : void

Shall set blocking mode

Exceptions

Warning

Shall throw \parallel\Events\Error if loop has timeout set.


Behaviour

  • « parallel\Events::setBlocking
  • parallel\Events::setInput »
  • PHP Manual
  • parallel\Events
  • Behaviour

parallel\Events::setTimeout

(0.9.0)

parallel\Events::setTimeout — Behaviour

Description

By default when events are polled for, blocking will occur (at the PHP level) until the first event can be returned: Setting the timeout causes an exception to be thrown when the timeout is reached.

This differs from setting blocking mode to false with parallel\Events::setBlocking(), which will not cause an exception to be thrown.

public parallel\Events::setTimeout ( int $timeout ) : void

Shall set the timeout in microseconds

Exceptions

Warning

Shall throw \parallel\Events\Error if loop is non-blocking.


Input

  • « parallel\Events::setTimeout
  • parallel\Events::addChannel »
  • PHP Manual
  • parallel\Events
  • Input

parallel\Events::setInput

(0.9.0)

parallel\Events::setInput — Input

Description

public parallel\Events::setInput ( Input $input ) : void

Shall set input for this event loop


Targets

  • « parallel\Events::setInput
  • parallel\Events::addFuture »
  • PHP Manual
  • parallel\Events
  • Targets

parallel\Events::addChannel

(0.9.0)

parallel\Events::addChannel — Targets

Description

public parallel\Events::addChannel ( parallel\Channel $channel ) : void

Shall watch for events on the given channel

Exceptions

Warning

Shall throw \parallel\Events\Error\Existence if channel was already added.


Targets

  • « parallel\Events::addChannel
  • parallel\Events::remove »
  • PHP Manual
  • parallel\Events
  • Targets

parallel\Events::addFuture

(0.9.0)

parallel\Events::addFuture — Targets

Description

public parallel\Events::addFuture ( string $name , parallel\Future $future ) : void

Shall watch for events on the given future

Exceptions

Warning

Shall throw \parallel\Events\Error\Existence if target with the given name was already added.


Targets

  • « parallel\Events::addFuture
  • parallel\Events::poll »
  • PHP Manual
  • parallel\Events
  • Targets

parallel\Events::remove

(0.9.0)

parallel\Events::remove — Targets

Description

public parallel\Events::remove ( string $target ) : void

Shall remove the given target

Exceptions

Warning

Shall throw \parallel\Events\Error\Existence if target with the given name was not found.


Polling

  • « parallel\Events::remove
  • parallel\Events\Input »
  • PHP Manual
  • parallel\Events
  • Polling

parallel\Events::poll

(0.9.0)

parallel\Events::poll — Polling

Description

public parallel\Events::poll ( void ) : ?Event

Shall poll for the next event

Return Values

Should there be no targets remaining, null shall be returned

Should this be a non-blocking loop, and blocking would occur, null shall be returned

Otherwise, the parallel\Events\Event returned describes the event.

Exceptions

Warning

Shall throw \parallel\Events\Error\Timeout if timeout is used and reached.


The parallel\Events\Input class

(0.9.0)

Events Input

An Input object is a container for data that the parallel\Events object will write to parallel\Channel objects as they become available. Multiple event loops may share an Input container - parallel does not verify the contents of the container when it is set as the input for a parallel\Events object.

Note:

When a parallel\Events object performs a write, the target is removed from the input object as if parallel\Events\Input::remove() were called.

Class synopsis

final parallel\Events\Input {
public add ( string $target , mixed $value ) : void
public remove ( string $target ) : void
public clear ( void ) : void
}

Table of Contents

  • parallel\Events\Input::add — Inputs
  • parallel\Events\Input::clear — Inputs
  • parallel\Events\Input::remove — Inputs


Inputs

  • « parallel\Events\Input
  • parallel\Events\Input::clear »
  • PHP Manual
  • parallel\Events\Input
  • Inputs

parallel\Events\Input::add

(0.9.0)

parallel\Events\Input::add — Inputs

Description

public parallel\Events\Input::add ( string $target , mixed $value ) : void

Shall set input for the given target

Exceptions

Warning

Shall throw \parallel\Events\Input\Error\Existence if input for target already exists.

Warning

Shall throw \parallel\Events\Input\Error\IllegalValue if value is illegal (object, null).


Inputs

  • « parallel\Events\Input::add
  • parallel\Events\Input::remove »
  • PHP Manual
  • parallel\Events\Input
  • Inputs

parallel\Events\Input::clear

(0.9.0)

parallel\Events\Input::clear — Inputs

Description

public parallel\Events\Input::clear ( void ) : void

Shall remove input for all targets


Inputs

  • « parallel\Events\Input::clear
  • parallel\Events\Event »
  • PHP Manual
  • parallel\Events\Input
  • Inputs

parallel\Events\Input::remove

(0.9.0)

parallel\Events\Input::remove — Inputs

Description

public parallel\Events\Input::remove ( string $target ) : void

Shall remove input for the given target

Exceptions

Warning

Shall throw \parallel\Events\Input\Error\Existence if input for target does not exist.


The parallel\Events\Event class

(0.9.0)

Event Objects

When an Event is returned, Event::$object shall be removed from the loop that returned it, should the event be a write event the Input for Event::$source shall also be removed.

Class synopsis

final parallel\Events\Event {
/* Shall be one of Event\Type constants */
public int $type ;
/* Shall be the source of the event (target name) */
public string $source ;
/* Shall be either Future or Channel */
public object $object ;
/* Shall be set for Read/Error events */
public $value ;
}


The parallel\Events\Event\Type class

(0.9.0)

Class synopsis

final parallel\Events\Event\Type {
/* Event::$object was read into Event::$value */
const Read ;
/* Input for Event::$source written to Event::$object */
const Write ;
/* Event::$object (Channel) was closed */
const Close ;
/* Event::$object (Future) was cancelled */
const Cancel ;
/* Runtime executing Event::$object (Future) was killed */
const Kill ;
/* Event::$object (Future) raised error */
const Error ;
}


The parallel\Sync class

(1.1.0)

Low Level Synchronization

The parallel\Sync class provides access to low level synchronization primitives, mutex, condition variables, and allows the implementation of semaphores.

Synchronization for most applications is much better implemented using channels, however, in some cases authors of low level code may find it useful to be able to access these lower level mechanisms.

Class synopsis

final parallel\Sync {
/* Constructor */
public __construct ( void )
public __construct ( scalar $value )
/* Access */
public get ( void ) : scalar
public set ( scalar $value )
/* Synchronization */
public wait ( void )
public notify ([ bool $all ] )
public __invoke ( callable $critical )
}

Table of Contents

  • parallel\Sync::__construct — Construction
  • parallel\Sync::get — Access
  • parallel\Sync::set — Access
  • parallel\Sync::wait — Synchronization
  • parallel\Sync::notify — Synchronization
  • parallel\Sync::__invoke — Synchronization


Construction

  • « parallel\Sync
  • parallel\Sync::get »
  • PHP Manual
  • parallel\Sync
  • Construction

parallel\Sync::__construct

(1.1.0)

parallel\Sync::__construct — Construction

Description

public parallel\Sync::__construct ( void )

Shall construct a new synchronization object with no value

public parallel\Sync::__construct ( scalar $value )

Shall construct a new synchronization object containing the given scalar value

Exceptions

Warning

Shall throw \parallel\Sync\Error\IllegalValue if value is non-scalar.


Access

  • « parallel\Sync::__construct
  • parallel\Sync::set »
  • PHP Manual
  • parallel\Sync
  • Access

parallel\Sync::get

(1.1.0)

parallel\Sync::get — Access

Description

public parallel\Sync::get ( void ) : scalar

Shall atomically return the syncrhonization objects value


Access

  • « parallel\Sync::get
  • parallel\Sync::wait »
  • PHP Manual
  • parallel\Sync
  • Access

parallel\Sync::set

(1.1.0)

parallel\Sync::set — Access

Description

public parallel\Sync::set ( scalar $value )

Shall atomically set the value of the synchronization object

Exceptions

Warning

Shall throw \parallel\Sync\Error\IllegalValue if value is non-scalar.


Synchronization

  • « parallel\Sync::set
  • parallel\Sync::notify »
  • PHP Manual
  • parallel\Sync
  • Synchronization

parallel\Sync::wait

(1.1.0)

parallel\Sync::wait — Synchronization

Description

public parallel\Sync::wait ( void )

Shall wait for notification on this synchronization object


Synchronization

  • « parallel\Sync::wait
  • parallel\Sync::__invoke »
  • PHP Manual
  • parallel\Sync
  • Synchronization

parallel\Sync::notify

(1.1.0)

parallel\Sync::notify — Synchronization

Description

public parallel\Sync::notify ([ bool $all ] )

Shall notify one (by default) or all threads waiting on the synchronization object


Synchronization

  • « parallel\Sync::notify
  • pthreads »
  • PHP Manual
  • parallel\Sync
  • Synchronization

parallel\Sync::__invoke

(1.1.0)

parallel\Sync::__invoke — Synchronization

Description

public parallel\Sync::__invoke ( callable $critical )

Shall exclusively enter into the critical code


pthreads

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
  • Predefined Constants
  • Threaded — The Threaded class
    • Threaded::chunk — Manipulation
    • Threaded::count — Manipulation
    • Threaded::extend — Runtime Manipulation
    • Threaded::from — Creation
    • Threaded::getTerminationInfo — Error Detection
    • Threaded::isRunning — State Detection
    • Threaded::isTerminated — State Detection
    • Threaded::isWaiting — State Detection
    • Threaded::lock — Synchronization
    • Threaded::merge — Manipulation
    • Threaded::notify — Synchronization
    • Threaded::notifyOne — Synchronization
    • Threaded::pop — Manipulation
    • Threaded::run — Execution
    • Threaded::shift — Manipulation
    • Threaded::synchronized — Synchronization
    • Threaded::unlock — Synchronization
    • Threaded::wait — Synchronization
  • Thread — The Thread class
    • Thread::detach — Execution
    • Thread::getCreatorId — Identification
    • Thread::getCurrentThread — Identification
    • Thread::getCurrentThreadId — Identification
    • Thread::getThreadId — Identification
    • Thread::globally — Execution
    • Thread::isJoined — State Detection
    • Thread::isStarted — State Detection
    • Thread::join — Synchronization
    • Thread::kill — Execution
    • Thread::start — Execution
  • Worker — The Worker class
    • Worker::collect — Collect references to completed tasks
    • Worker::getStacked — Gets the remaining stack size
    • Worker::isShutdown — State Detection
    • Worker::isWorking — State Detection
    • Worker::shutdown — Shutdown the worker
    • Worker::stack — Stacking work
    • Worker::unstack — Unstacking work
  • Collectable — The Collectable interface
    • Collectable::isGarbage — Determine whether an object has been marked as garbage
    • Collectable::setGarbage — Mark an object as garbage
  • Modifiers — Method Modifiers
  • Pool — The Pool class
    • Pool::collect — Collect references to completed tasks
    • Pool::__construct — Creates a new Pool of Workers
    • Pool::resize — Resize the Pool
    • Pool::shutdown — Shutdown all workers
    • Pool::submit — Submits an object for execution
    • Pool::submitTo — Submits a task to a specific worker for execution
  • Mutex — The Mutex class
    • Mutex::create — Create a Mutex
    • Mutex::destroy — Destroy Mutex
    • Mutex::lock — Acquire Mutex
    • Mutex::trylock — Attempt to Acquire Mutex
    • Mutex::unlock — Release Mutex
  • Cond — The Cond class
    • Cond::broadcast — Broadcast a Condition
    • Cond::create — Create a Condition
    • Cond::destroy — Destroy a Condition
    • Cond::signal — Signal a Condition
    • Cond::wait — Wait for Condition
  • Volatile — The Volatile class


Introduction

pthreads is an object-orientated API that provides all of the tools needed for multi-threading in PHP. PHP applications can create, read, write, execute and synchronize with Threads, Workers and Threaded objects.

Tip

Consider using parallel instead.

Warning

The pthreads extension cannot be used in a web server environment. Threading in PHP is therefore restricted to CLI-based applications only.

Warning

pthreads (v3) can only be used with PHP 7.2+: This is due to ZTS mode being unsafe in 7.0 and 7.1.

The Threaded class forms the basis of the functionality that allows pthreads to operate. It exposes synchronization methods and some useful interfaces for the programmer.

The Thread class enables for threads to be created by simply extending it and implementing a run method. Any members can be written to and read by any context with a reference to the thread. Any context can also execute any public and protected methods. The body of the run method will be executed in a separate thread when the Thread::start() method of the implementation is called from the context that created it. Only the context that creates a thread can start and join it.

The Worker class has a persistent state, and will be available from the call to Thread::start() (an inherited method) until the object goes out of scope, or is explicitly shutdown (via Worker::shutdown()). Any context with a reference to the worker object can stack tasks onto the Worker (via Worker::stack()), where these tasks will be executed by the worker in a separate thread. The run method of a worker object will be executed before any objects on the worker's stack, enabling for resources to be initialized that the objects to be executed may need.

The Pool class is used to create a group of workers to distribute Threaded objects amongst them. It is the easiest and most efficient way of using multiple threads in PHP applications.

Caution

The Pool class does not extend the Threaded class, and so pool-based objects are considered a normal PHP objects. As such, its instances of it should not be shared amongst different contexts.

The Volatile class is new to pthreads v3. It is used to denote mutable Threaded properties of Threaded classes (since these are now immutable by default). It is also used to store PHP arrays in Threaded contexts.

Synchronization is an important ability when threading. All of the objects that pthreads creates have built in synchronization in the (which will be familiar to java programmers) form of Threaded::wait() and Threaded::notify(). Calling Threaded::wait() on an object will cause the context to wait for another context to call Threaded::notify() on the same object. This mechanism allows for powerful synchronization between Threaded objects in PHP.

Caution

Any objects that are intended for use in the multi-threaded parts of your application should extend Threaded.

Data Storage: As a rule of thumb, any data type that can be serialized can be used as a member of a Threaded object, it can be read and written from any context with a reference to the Threaded Object. Not every type of data is stored serially, basic types are stored in their true form. Complex types, Arrays, and Objects that are not Threaded are stored serially; they can be read and written to the Threaded Object from any context with a reference. With the exception of Threaded Objects any reference used to set a member of a Threaded Object is separated from the reference in the Threaded Object; the same data can be read directly from the Threaded Object at any time by any context with a reference to the Threaded Object.

Static Members: When a new context is created ( Thread or Worker ), they are generally copied, but resources and objects with internal state are nullified (for safety reasons). This allows them to function as a kind of thread local storage. For example, upon starting the context, a class whose static members include connection information for a database server, and the connection itself, will only have the simple connection information copied, not the connection. Allowing the new context to initiate a connection in the same way as the context that created it, storing the connection in the same place without affecting the original context.

Caution

When print_r, var_dump and other object debug functions are executed, they do not include recursion protection.

Note:

Resources: The extensions and functionality that define resources in PHP are completely unprepared for this kind of environment; pthreads makes provisions for Resources to be shared among contexts, however, for most types of resource it should be considered unsafe. Extreme caution and care should be used when sharing resources among contexts.

Caution

In the environment which pthreads executes, some restrictions and limitations are necessary in order to provide a stable environment.


Requirements

pthreads requires a build of PHP with ZTS (Zend Thread Safety) enabled ( --enable-maintainer-zts or --enable-zts on Windows )

Caution

Zend Thread Safety cannot be enabled post build; it is a build time configuration option.

pthreads should build anywhere there is a working Posix Threads header (pthread.h) and ZTS build of PHP, including Windows (using the pthread-w32 project from redhat).


Installation

pthreads 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/pthreads.

Windows users can download prebuilt release binaries from the » PECL website.

Caution

Windows users need to take the additional step of adding pthreadVC2.dll (distributed with Windows releases) to their PATH.


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.

PTHREADS_INHERIT_ALL (integer)
The default options for all Threads, causes pthreads to copy the environment when new Threads are started
PTHREADS_INHERIT_NONE (integer)
Do not inherit anything when new Threads are started
PTHREADS_INHERIT_INI (integer)
Inherit INI entries when new Threads are started
PTHREADS_INHERIT_CONSTANTS (integer)
Inherit user declared constants when new Threads are started
PTHREADS_INHERIT_CLASSES (integer)
Inherit user declared classes when new Threads are started
PTHREADS_INHERIT_FUNCTIONS (integer)
Inherit user declared functions when new Threads are started
PTHREADS_INHERIT_INCLUDES (integer)
Inherit included file information when new Threads are started
PTHREADS_INHERIT_COMMENTS (integer)
Inherit all comments when new Threads are started
PTHREADS_ALLOW_HEADERS (integer)
Allow new Threads to send headers to standard output (normally prohibited)


The Threaded class

(PECL pthreads >= 2.0.0)

Introduction

Threaded objects form the basis of pthreads ability to execute user code in parallel; they expose synchronization methods and various useful interfaces.

Threaded objects, most importantly, provide implicit safety for the programmer; all operations on the object scope are safe.

Class synopsis

Threaded implements Collectable , Traversable , Countable , ArrayAccess {
/* Methods */
public chunk ( int $size , bool $preserve ) : array
public count ( void ) : int
public extend ( string $class ) : bool
public from ( Closure $run [, Closure $construct [, array $args ]] ) : Threaded
public getTerminationInfo ( void ) : array
public isRunning ( void ) : bool
public isTerminated ( void ) : bool
public isWaiting ( void ) : bool
public lock ( void ) : bool
public merge ( mixed $from [, bool $overwrite ] ) : bool
public notify ( void ) : bool
public notifyOne ( void ) : bool
public pop ( void ) : bool
public run ( void ) : void
public shift ( void ) : mixed
public synchronized ( Closure $block [, mixed $... ] ) : mixed
public unlock ( void ) : bool
public wait ([ int $timeout ] ) : bool
}

Table of Contents

  • Threaded::chunk — Manipulation
  • Threaded::count — Manipulation
  • Threaded::extend — Runtime Manipulation
  • Threaded::from — Creation
  • Threaded::getTerminationInfo — Error Detection
  • Threaded::isRunning — State Detection
  • Threaded::isTerminated — State Detection
  • Threaded::isWaiting — State Detection
  • Threaded::lock — Synchronization
  • Threaded::merge — Manipulation
  • Threaded::notify — Synchronization
  • Threaded::notifyOne — Synchronization
  • Threaded::pop — Manipulation
  • Threaded::run — Execution
  • Threaded::shift — Manipulation
  • Threaded::synchronized — Synchronization
  • Threaded::unlock — Synchronization
  • Threaded::wait — Synchronization


Manipulation

  • « Threaded
  • Threaded::count »
  • PHP Manual
  • Threaded
  • Manipulation

Threaded::chunk

(PECL pthreads >= 2.0.0)

Threaded::chunk — Manipulation

Description

public Threaded::chunk ( int $size , bool $preserve ) : array

Fetches a chunk of the objects property table of the given size, optionally preserving keys

Parameters

size

The number of items to fetch

preserve

Preserve the keys of members, by default false

Return Values

An array of items from the objects property table

Examples

Example #1 Fetch a chunk of the property table

<?php
$safe = new Threaded();

while (count($safe) < 10) {
    $safe[] = count($safe);
}

var_dump($safe->chunk(5));
?>

The above example will output:

array(5) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(2)
  [3]=>
  int(3)
  [4]=>
  int(4)
}


Manipulation

  • « Threaded::chunk
  • Threaded::extend »
  • PHP Manual
  • Threaded
  • Manipulation

Threaded::count

(PECL pthreads >= 2.0.0)

Threaded::count — Manipulation

Description

public Threaded::count ( void ) : int

Returns the number of properties for this object

Parameters

This function has no parameters.

Return Values

Examples

Example #1 Counting the properties of an object

<?php
$safe = new Threaded();

while (count($safe) < 10) {
    $safe[] = count($safe);
}

var_dump(count($safe));
?>

The above example will output:

int(10)


Runtime Manipulation

  • « Threaded::count
  • Threaded::from »
  • PHP Manual
  • Threaded
  • Runtime Manipulation

Threaded::extend

(PECL pthreads >= 2.0.8)

Threaded::extend — Runtime Manipulation

Description

public Threaded::extend ( string $class ) : bool

Makes thread safe standard class at runtime

Parameters

class

The class to extend

Return Values

A boolean indication of success

Examples

Example #1 Runtime inheritance

<?php
class My {}

Threaded::extend(My::class);

$my = new My();

var_dump($my instanceof Threaded);
?>

The above example will output:

bool(true)


Creation

  • « Threaded::extend
  • Threaded::getTerminationInfo »
  • PHP Manual
  • Threaded
  • Creation

Threaded::from

(PECL pthreads >= 2.0.9)

Threaded::from — Creation

Warning

This method has been removed in pthreads v3. With the introduction of anonymous classes in PHP 7, these can now be used instead.

Description

public Threaded::from ( Closure $run [, Closure $construct [, array $args ]] ) : Threaded

Creates an anonymous Threaded object from closures

Parameters

run

The closure to use for ::run

construct

The constructor to use for anonymous object

args

The arguments to pass to constructor

Return Values

A new anonymous Threaded object

Examples

Example #1 Thread safe objects from closures

<?php
$pool = new Pool(4);
$pool->submit(Collectable::from(function(){
    echo "Hello World";
    $this->setGarbage();
}));
/* ... */
$pool->shutdown();
?>

The above example will output:

Hello World


Error Detection

  • « Threaded::from
  • Threaded::isRunning »
  • PHP Manual
  • Threaded
  • Error Detection

Threaded::getTerminationInfo

(PECL pthreads < 3.0.0)

Threaded::getTerminationInfo — Error Detection

Warning

This method has been removed in pthreads v3. Instead, the body of Threaded::run() can be wrapped in a try...catch block to detect errors (since most errors in PHP 7 have been converted to exceptions).

Description

public Threaded::getTerminationInfo ( void ) : array

Retrieves terminal error information from the referenced object

Parameters

This function has no parameters.

Return Values

array containing the termination conditions of the referenced object

Examples

Example #1 Detecting fatal errors in Threads

<?php
class My extends Thread {
    public function run() {
        @not_found();
    }
}

$my = new My();
$my->start();
$my->join();

var_dump($my->isTerminated(), $my->getTerminationInfo());
?>

The above example will output:

bool(true)
array(4) {
  ["scope"]=>
  string(2) "My"
  ["function"]=>
  string(3) "run"
  ["file"]=>
  string(29) "/usr/src/pthreads/sandbox.php"
  ["line"]=>
  int(4)
}


State Detection

  • « Threaded::getTerminationInfo
  • Threaded::isTerminated »
  • PHP Manual
  • Threaded
  • State Detection

Threaded::isRunning

(PECL pthreads >= 2.0.0)

Threaded::isRunning — State Detection

Description

public Threaded::isRunning ( void ) : bool

Tell if the referenced object is executing

Parameters

This function has no parameters.

Return Values

A boolean indication of state

Note:

A object is considered running while executing the run method

Examples

Example #1 Detect the state of the referenced object

<?php
class My extends Thread {
    public function run() {
        $this->synchronized(function($thread){
            if (!$thread->done)
                $thread->wait();
        }, $this);
    }
}
$my = new My();
$my->start();
var_dump($my->isRunning());
$my->synchronized(function($thread){
    $thread->done = true;
    $thread->notify();
}, $my);
?>

The above example will output:

bool(true)


State Detection

  • « Threaded::isRunning
  • Threaded::isWaiting »
  • PHP Manual
  • Threaded
  • State Detection

Threaded::isTerminated

(PECL pthreads >= 2.0.0)

Threaded::isTerminated — State Detection

Description

public Threaded::isTerminated ( void ) : bool

Tell if the referenced object was terminated during execution; suffered fatal errors, or threw uncaught exceptions

Parameters

This function has no parameters.

Return Values

A boolean indication of state

Examples

Example #1 Detect the state of the referenced object

<?php
class My extends Thread {
    public function run() {
        i_do_not_exist();
    }
}
$my = new My();
$my->start();
$my->join();
var_dump($my->isTerminated());
?>

The above example will output:

bool(true)


State Detection

  • « Threaded::isTerminated
  • Threaded::lock »
  • PHP Manual
  • Threaded
  • State Detection

Threaded::isWaiting

(PECL pthreads < 3.0.0)

Threaded::isWaiting — State Detection

Warning

This method has been removed in pthreads v3.

Description

public Threaded::isWaiting ( void ) : bool

Tell if the referenced object is waiting for notification

Parameters

This function has no parameters.

Return Values

A boolean indication of state

Examples

Example #1 Detect the state of the referenced object

<?php
class My extends Thread {
    public function run() {
        $this->synchronized(function($thread){
            if (!$this->done)
                $thread->wait();
        }, $this);
    }

    protected $done;
}
$my = new My();
$my->start();
$my->synchronized(function($thread){
    var_dump(
        $thread->isWaiting());
    $thread->done = true;
    $thread->notify();
}, $my);
?>

The above example will output:

bool(true)


Synchronization

  • « Threaded::isWaiting
  • Threaded::merge »
  • PHP Manual
  • Threaded
  • Synchronization

Threaded::lock

(PECL pthreads < 3.0.0)

Threaded::lock — Synchronization

Warning

This method has been removed in pthreads v3. The Threaded::synchronized() method should now be used.

Description

public Threaded::lock ( void ) : bool

Lock the referenced objects property table

Parameters

This function has no parameters.

Return Values

A boolean indication of success

Examples

Example #1 Locking Object Properties

<?php
class My extends Thread {
    public function run() {
        var_dump($this->lock());
        /** nobody can read or write **/
        var_dump($this->unlock());
        /** reading / writing resumed for all other contexts */
    }
}
$my = new My();
$my->start();
?>

The above example will output:

bool(true)
bool(true)


Manipulation

  • « Threaded::lock
  • Threaded::notify »
  • PHP Manual
  • Threaded
  • Manipulation

Threaded::merge

(PECL pthreads >= 2.0.0)

Threaded::merge — Manipulation

Description

public Threaded::merge ( mixed $from [, bool $overwrite ] ) : bool

Merges data into the current object

Parameters

from

The data to merge

overwrite

Overwrite existing keys, by default true

Return Values

A boolean indication of success

Examples

Example #1 Merging into the property table of a threaded object

<?php
$array = [];

while (count($array) < 10)
    $array[] = count($array);

$stdClass = new stdClass();
$stdClass->foo = "foo";
$stdClass->bar = "bar";
$stdClass->baz = "baz";

$safe = new Threaded();
$safe->merge($array);

$safe->foo = "bar";
$safe->merge($stdClass, false);

var_dump($safe);
?>

The above example will output:

object(Threaded)#2 (13) {
  ["0"]=>
  int(0)
  ["1"]=>
  int(1)
  ["2"]=>
  int(2)
  ["3"]=>
  int(3)
  ["4"]=>
  int(4)
  ["5"]=>
  int(5)
  ["6"]=>
  int(6)
  ["7"]=>
  int(7)
  ["8"]=>
  int(8)
  ["9"]=>
  int(9)
  ["foo"]=>
  string(3) "bar"
  ["bar"]=>
  string(3) "bar"
  ["baz"]=>
  string(3) "baz"
}


Synchronization

  • « Threaded::merge
  • Threaded::notifyOne »
  • PHP Manual
  • Threaded
  • Synchronization

Threaded::notify

(PECL pthreads >= 2.0.0)

Threaded::notify — Synchronization

Description

public Threaded::notify ( void ) : bool

Send notification to the referenced object

Parameters

This function has no parameters.

Return Values

A boolean indication of success

Examples

Example #1 Notifications and Waiting

<?php
class My extends Thread {
    public function run() {
        /** cause this thread to wait **/
        $this->synchronized(function($thread){
            if (!$thread->done)
                $thread->wait();
        }, $this);
    }
}
$my = new My();
$my->start();
/** send notification to the waiting thread **/
$my->synchronized(function($thread){
    $thread->done = true;
    $thread->notify();
}, $my);
var_dump($my->join());
?>

The above example will output:

bool(true)


Synchronization

  • « Threaded::notify
  • Threaded::pop »
  • PHP Manual
  • Threaded
  • Synchronization

Threaded::notifyOne

(PECL pthreads >= 3.0.0)

Threaded::notifyOne — Synchronization

Description

public Threaded::notifyOne ( void ) : bool

Send notification to the referenced object. This unblocks at least one of the blocked threads (as opposed to unblocking all of them, as seen with Threaded::notify()).

Parameters

This function has no parameters.

Return Values

A boolean indication of success

Examples

Example #1 Notifications and Waiting

<?php
class My extends Thread {
    public function run() {
        /** cause this thread to wait **/
        $this->synchronized(function($thread){
            if (!$thread->done)
                $thread->wait();
        }, $this);
    }
}
$my = new My();
$my->start();
/** send notification to the waiting thread **/
$my->synchronized(function($thread){
    $thread->done = true;
    $thread->notifyOne();
}, $my);
var_dump($my->join());
?>

The above example will output:

bool(true)


Manipulation

  • « Threaded::notifyOne
  • Threaded::run »
  • PHP Manual
  • Threaded
  • Manipulation

Threaded::pop

(PECL pthreads >= 2.0.0)

Threaded::pop — Manipulation

Description

public Threaded::pop ( void ) : bool

Pops an item from the objects property table

Return Values

The last item from the objects property table

Examples

Example #1 Popping the last item from the property table of a threaded object

<?php
$safe = new Threaded();

while (count($safe) < 10)
    $safe[] = count($safe);

var_dump($safe->pop());
?>

The above example will output:

int(9)


Execution

  • « Threaded::pop
  • Threaded::shift »
  • PHP Manual
  • Threaded
  • Execution

Threaded::run

(PECL pthreads >= 2.0.0)

Threaded::run — Execution

Description

public Threaded::run ( void ) : void

The programmer should always implement the run method for objects that are intended for execution.

Parameters

This function has no parameters.

Return Values

The methods return value, if used, will be ignored


Manipulation

  • « Threaded::run
  • Threaded::synchronized »
  • PHP Manual
  • Threaded
  • Manipulation

Threaded::shift

(PECL pthreads >= 2.0.0)

Threaded::shift — Manipulation

Description

public Threaded::shift ( void ) : mixed

Shifts an item from the objects property table

Return Values

The first item from the objects property table

Examples

Example #1 Shifting the first item from the property table of a threaded object

<?php
$safe = new Threaded();

while (count($safe) < 10)
    $safe[] = count($safe);

var_dump($safe->shift());
?>

The above example will output:

int(0)


Synchronization

  • « Threaded::shift
  • Threaded::unlock »
  • PHP Manual
  • Threaded
  • Synchronization

Threaded::synchronized

(PECL pthreads >= 2.0.0)

Threaded::synchronized — Synchronization

Description

public Threaded::synchronized ( Closure $block [, mixed $... ] ) : mixed

Executes the block while retaining the referenced objects synchronization lock for the calling context

Parameters

block

The block of code to execute

...

Variable length list of arguments to use as function arguments to the block

Return Values

The return value from the block

Examples

Example #1 Synchronizing

<?php
class My extends Thread {
    public function run() {
        $this->synchronized(function($thread){
            if (!$thread->done)
                $thread->wait();
        }, $this);
    }
}
$my = new My();
$my->start();
$my->synchronized(function($thread){
    $thread->done = true;
    $thread->notify();
}, $my);
var_dump($my->join());
?>

The above example will output:

bool(true)


Synchronization

  • « Threaded::synchronized
  • Threaded::wait »
  • PHP Manual
  • Threaded
  • Synchronization

Threaded::unlock

(PECL pthreads < 3.0.0)

Threaded::unlock — Synchronization

Warning

This method has been removed in pthreads v3. The Threaded::synchronized() method should now be used.

Description

public Threaded::unlock ( void ) : bool

Unlock the referenced objects storage for the calling context

Parameters

This function has no parameters.

Return Values

A boolean indication of success

Examples

Example #1 Locking the property table of a threaded object

<?php
class My extends Thread {
    public function run() {
        var_dump($this->lock());
        /** nobody can read or write **/
        var_dump($this->unlock());
        /** reading / writing resumed for all other contexts */
    }
}
$my = new My();
$my->start();
?>

The above example will output:

bool(true)
bool(true)


Synchronization

  • « Threaded::unlock
  • Thread »
  • PHP Manual
  • Threaded
  • Synchronization

Threaded::wait

(PECL pthreads >= 2.0.0)

Threaded::wait — Synchronization

Description

public Threaded::wait ([ int $timeout ] ) : bool

Will cause the calling context to wait for notification from the referenced object

Parameters

timeout

An optional timeout in microseconds

Return Values

A boolean indication of success

Examples

Example #1 Notifications and Waiting

<?php
class My extends Thread {
    public function run() {
        /** cause this thread to wait **/
        $this->synchronized(function($thread){
            if (!$thread->done)
                $thread->wait();
        }, $this);
    }
}
$my = new My();
$my->start();
/** send notification to the waiting thread **/
$my->synchronized(function($thread){
    $thread->done = true;
    $thread->notify();
}, $my);
var_dump($my->join());
?>

The above example will output:

bool(true)


The Thread class

(PECL pthreads >= 2.0.0)

Introduction

When the start method of a Thread is invoked, the run method code will be executed in separate Thread, in parallel.

After the run method is executed the Thread will exit immediately, it will be joined with the creating Thread at the appropriate time.

Warning

Relying on the engine to determine when a Thread should join may cause undesirable behaviour; the programmer should be explicit, where possible.

Class synopsis

Thread extends Threaded implements Countable , Traversable , ArrayAccess {
/* Methods */
public detach ( void ) : void
public getCreatorId ( void ) : int
public static getCurrentThread ( void ) : Thread
public static getCurrentThreadId ( void ) : int
public getThreadId ( void ) : int
public static globally ( void ) : mixed
public isJoined ( void ) : bool
public isStarted ( void ) : bool
public join ( void ) : bool
public kill ( void ) : void
public start ([ int $options ] ) : bool
/* Inherited methods */
public Threaded::chunk ( int $size , bool $preserve ) : array
public Threaded::count ( void ) : int
public Threaded::extend ( string $class ) : bool
public Threaded::from ( Closure $run [, Closure $construct [, array $args ]] ) : Threaded
public Threaded::getTerminationInfo ( void ) : array
public Threaded::isRunning ( void ) : bool
public Threaded::isTerminated ( void ) : bool
public Threaded::isWaiting ( void ) : bool
public Threaded::lock ( void ) : bool
public Threaded::merge ( mixed $from [, bool $overwrite ] ) : bool
public Threaded::notify ( void ) : bool
public Threaded::notifyOne ( void ) : bool
public Threaded::pop ( void ) : bool
public Threaded::run ( void ) : void
public Threaded::shift ( void ) : mixed
public Threaded::synchronized ( Closure $block [, mixed $... ] ) : mixed
public Threaded::unlock ( void ) : bool
public Threaded::wait ([ int $timeout ] ) : bool
}

Table of Contents

  • Thread::detach — Execution
  • Thread::getCreatorId — Identification
  • Thread::getCurrentThread — Identification
  • Thread::getCurrentThreadId — Identification
  • Thread::getThreadId — Identification
  • Thread::globally — Execution
  • Thread::isJoined — State Detection
  • Thread::isStarted — State Detection
  • Thread::join — Synchronization
  • Thread::kill — Execution
  • Thread::start — Execution


Execution

  • « Thread
  • Thread::getCreatorId »
  • PHP Manual
  • Thread
  • Execution

Thread::detach

(PECL pthreads < 3.0.0)

Thread::detach — Execution

Warning

This method has been removed in pthreads v3.

Description

public Thread::detach ( void ) : void

Detaches the referenced Thread from the calling context, dangerous!

Warning

This method can cause undefined, unsafe behaviour. It should not usually be used, it is present for completeness and advanced use cases.

Parameters

This function has no parameters.

Return Values


Identification

  • « Thread::detach
  • Thread::getCurrentThread »
  • PHP Manual
  • Thread
  • Identification

Thread::getCreatorId

(PECL pthreads >= 2.0.0)

Thread::getCreatorId — Identification

Description

public Thread::getCreatorId ( void ) : int

Will return the identity of the Thread that created the referenced Thread

Parameters

This function has no parameters.

Return Values

A numeric identity

Examples

Example #1 Return the identity of the Thread or Process that created the referenced Thread

<?php
class My extends Thread {
    public function run() {
        printf("%s created by Thread #%lu\n", __CLASS__, $this->getCreatorId());
    }
}
$my = new My();
$my->start();
?>

The above example will output:

My created by Thread #123456778899


Identification

  • « Thread::getCreatorId
  • Thread::getCurrentThreadId »
  • PHP Manual
  • Thread
  • Identification

Thread::getCurrentThread

(PECL pthreads >= 2.0.0)

Thread::getCurrentThread — Identification

Description

public static Thread::getCurrentThread ( void ) : Thread

Return a reference to the currently executing Thread

Parameters

This function has no parameters.

Return Values

An object representing the currently executing Thread

Examples

Example #1 Return the currently executing Thread

<?php
class My extends Thread {
    public function run() {
        var_dump(Thread::getCurrentThread());
    }
}
$my = new My();
$my->start();
?>

The above example will output:

object(My)#2 (0) {
}


Identification

  • « Thread::getCurrentThread
  • Thread::getThreadId »
  • PHP Manual
  • Thread
  • Identification

Thread::getCurrentThreadId

(PECL pthreads >= 2.0.0)

Thread::getCurrentThreadId — Identification

Description

public static Thread::getCurrentThreadId ( void ) : int

Will return the identity of the currently executing Thread

Parameters

This function has no parameters.

Return Values

A numeric identity

Examples

Example #1 Return the identity of the currently executing Thread

<?php
class My extends Thread {
    public function run() {
        printf("%s is Thread #%lu\n", __CLASS__, Thread::getCurrentThreadId());
    }
}
$my = new My();
$my->start();
?>

The above example will output:

My is Thread #123456778899


Identification

  • « Thread::getCurrentThreadId
  • Thread::globally »
  • PHP Manual
  • Thread
  • Identification

Thread::getThreadId

(PECL pthreads >= 2.0.0)

Thread::getThreadId — Identification

Description

public Thread::getThreadId ( void ) : int

Will return the identity of the referenced Thread

Parameters

This function has no parameters.

Return Values

A numeric identity

Examples

Example #1 Return the identity of the referenced Thread

<?php
class My extends Thread {
    public function run() {
        printf("%s is Thread #%lu\n", __CLASS__, $this->getThreadId());
    }
}
$my = new My();
$my->start();
?>

The above example will output:

My is Thread #123456778899


Execution

  • « Thread::getThreadId
  • Thread::isJoined »
  • PHP Manual
  • Thread
  • Execution

Thread::globally

(PECL pthreads < 3.0.0)

Thread::globally — Execution

Warning

This method has been removed in pthreads v3.

Description

public static Thread::globally ( void ) : mixed

Will execute a Callable in the global scope

Parameters

This function has no parameters.

Return Values

The return value of the Callable

Examples

Example #1 Execute in the global scope

<?php
class My extends Thread {
    public function run() {
        global $std;

        Thread::globally(function(){
            $std = new stdClass;
        });

        var_dump($std);
    }
}
$my = new My();
$my->start();
?>

The above example will output:

object(stdClass)#3 (0) {
}


State Detection

  • « Thread::globally
  • Thread::isStarted »
  • PHP Manual
  • Thread
  • State Detection

Thread::isJoined

(PECL pthreads >= 2.0.0)

Thread::isJoined — State Detection

Description

public Thread::isJoined ( void ) : bool

Tell if the referenced Thread has been joined

Parameters

This function has no parameters.

Return Values

A boolean indication of state

Examples

Example #1 Detect the state of the referenced Thread

<?php
class My extends Thread {
    public function run() {
        $this->synchronized(function($thread){
            if (!$thread->done)
                $thread->wait();
        }, $this);
    }
}
$my = new My();
$my->start();
var_dump($my->isJoined());
$my->synchronized(function($thread){
    $thread->done = true;
    $thread->notify();
}, $my);
?>

The above example will output:

bool(false)


State Detection

  • « Thread::isJoined
  • Thread::join »
  • PHP Manual
  • Thread
  • State Detection

Thread::isStarted

(PECL pthreads >= 2.0.0)

Thread::isStarted — State Detection

Description

public Thread::isStarted ( void ) : bool

Tell if the referenced Thread was started

Parameters

This function has no parameters.

Return Values

boolean indication of state

Examples

Example #1 Tell if the referenced Thread was started

<?php
$worker = new Worker();
$worker->start();
var_dump($worker->isStarted());
?>

The above example will output:

bool(true)


Synchronization

  • « Thread::isStarted
  • Thread::kill »
  • PHP Manual
  • Thread
  • Synchronization

Thread::join

(PECL pthreads >= 2.0.0)

Thread::join — Synchronization

Description

public Thread::join ( void ) : bool

Causes the calling context to wait for the referenced Thread to finish executing

Parameters

This function has no parameters.

Return Values

A boolean indication of success

Examples

Example #1 Join with the referenced Thread

<?php
class My extends Thread {
    public function run() {
        /* ... */
    }
}
$my = new My();
$my->start();
/* ... */
var_dump($my->join());
/* ... */
?>

The above example will output:

bool(true)


Execution

  • « Thread::join
  • Thread::start »
  • PHP Manual
  • Thread
  • Execution

Thread::kill

(PECL pthreads < 3.0.0)

Thread::kill — Execution

Warning

This method has been removed in pthreads v3.

Description

public Thread::kill ( void ) : void

Forces the referenced Thread to terminate

Warning

The programmer should not ordinarily kill Threads by force

Parameters

This function has no parameters.

Return Values

A boolean indication of success

Examples

Example #1 Kill the referenced Thread

<?php
class T extends Thread {
    public function run() {
        $stdin = fopen("php://stdin", "r");
        while(($line = fgets($stdin))) {
            echo $line;
        }
    }
}

$t = new T();
$t->start();

var_dump($t->kill());
?>

The above example will output:

bool(true)


Execution

  • « Thread::kill
  • Worker »
  • PHP Manual
  • Thread
  • Execution

Thread::start

(PECL pthreads >= 2.0.0)

Thread::start — Execution

Description

public Thread::start ([ int $options ] ) : bool

Will start a new Thread to execute the implemented run method

Parameters

options

An optional mask of inheritance constants, by default PTHREADS_INHERIT_ALL

Return Values

A boolean indication of success

Examples

Example #1 Starting Threads

<?php
class My extends Thread {
    public function run() {
        /** ... **/
    }
}
$my = new My();
var_dump($my->start());
?>

The above example will output:

bool(true)


The Worker class

(PECL pthreads >= 2.0.0)

Introduction

Worker Threads have a persistent context, as such should be used over Threads in most cases.

When a Worker is started, the run method will be executed, but the Thread will not leave until one of the following conditions are met:

  • the Worker goes out of scope (no more references remain)

  • the programmer calls shutdown

  • the script dies

This means the programmer can reuse the context throughout execution; placing objects on the stack of the Worker will cause the Worker to execute the stacked objects run method.

Class synopsis

Worker extends Thread implements Traversable , Countable , ArrayAccess {
/* Methods */
public collect ([ Callable $collector ] ) : int
public getStacked ( void ) : int
public isShutdown ( void ) : bool
public isWorking ( void ) : bool
public shutdown ( void ) : bool
public stack ( Threaded &$work ) : int
public unstack ( void ) : int
/* Inherited methods */
public Thread::detach ( void ) : void
public Thread::getCreatorId ( void ) : int
public static Thread::getCurrentThread ( void ) : Thread
public static Thread::getCurrentThreadId ( void ) : int
public Thread::getThreadId ( void ) : int
public static Thread::globally ( void ) : mixed
public Thread::isJoined ( void ) : bool
public Thread::isStarted ( void ) : bool
public Thread::join ( void ) : bool
public Thread::kill ( void ) : void
public Thread::start ([ int $options ] ) : bool
}

Table of Contents

  • Worker::collect — Collect references to completed tasks
  • Worker::getStacked — Gets the remaining stack size
  • Worker::isShutdown — State Detection
  • Worker::isWorking — State Detection
  • Worker::shutdown — Shutdown the worker
  • Worker::stack — Stacking work
  • Worker::unstack — Unstacking work


Collect references to completed tasks

  • « Worker
  • Worker::getStacked »
  • PHP Manual
  • Worker
  • Collect references to completed tasks

Worker::collect

(PECL pthreads >= 3.0.0)

Worker::collect — Collect references to completed tasks

Description

public Worker::collect ([ Callable $collector ] ) : int

Allows the worker to collect references determined to be garbage by the optionally given collector.

Parameters

collector

A Callable collector that returns a boolean on whether the task can be collected or not. Only in rare cases should a custom collector need to be used.

Return Values

The number of remaining tasks on the worker's stack to be collected.

Examples

Example #1 A basic example of Worker::collect()

<?php
$worker = new Worker();

echo "There are currently {$worker->collect()} tasks on the stack to be collected\n";

for ($i = 0; $i < 15; ++$i) {
    $worker->stack(new class extends Threaded {});
}

echo "There are {$worker->collect()} tasks remaining on the stack to be collected\n";

$worker->start();

while ($worker->collect()); // blocks until all tasks have finished executing

echo "There are now {$worker->collect()} tasks on the stack to be collected\n";

$worker->shutdown();

The above example will output:

There are currently 0 tasks on the stack to be collected
There are 15 tasks remaining on the stack to be collected
There are now 0 tasks on the stack to be collected


Gets the remaining stack size

  • « Worker::collect
  • Worker::isShutdown »
  • PHP Manual
  • Worker
  • Gets the remaining stack size

Worker::getStacked

(PECL pthreads >= 2.0.0)

Worker::getStacked — Gets the remaining stack size

Description

public Worker::getStacked ( void ) : int

Returns the number of tasks left on the stack

Parameters

This function has no parameters.

Return Values

Returns the number of tasks currently waiting to be executed by the worker

Examples

Example #1 A basic example of Worker::getStacked

<?php
$worker = new Worker();

for ($i = 0; $i < 5; ++$i) {
    $worker->stack(new class extends Threaded {});
}

echo "There are {$worker->getStacked()} stacked tasks\n";

The above example will output:

There are 5 stacked tasks


State Detection

  • « Worker::getStacked
  • Worker::isWorking »
  • PHP Manual
  • Worker
  • State Detection

Worker::isShutdown

(PECL pthreads >= 2.0.0)

Worker::isShutdown — State Detection

Description

public Worker::isShutdown ( void ) : bool

Whether the worker has been shutdown or not.

Parameters

This function has no parameters.

Return Values

Returns whether the worker has been shutdown or not.

Examples

Example #1 Detect the state of a worker

<?php
$worker = new Worker();
$worker->start();

var_dump($worker->isShutdown());

$worker->shutdown();

var_dump($worker->isShutdown());

The above example will output:

bool(false)
bool(true)


State Detection

  • « Worker::isShutdown
  • Worker::shutdown »
  • PHP Manual
  • Worker
  • State Detection

Worker::isWorking

(PECL pthreads >= 2.0.0)

Worker::isWorking — State Detection

Warning

This method has been removed in pthreads v3. The Worker::getStacked() method should be used to see if the worker still has tasks to execute.

Description

public Worker::isWorking ( void ) : bool

Tell if a Worker is executing Stackables

Parameters

This function has no parameters.

Return Values

A boolean indication of state

Examples

Example #1 Detect the state of a Worker

<?php
$my = new Worker();
$my->start();
/* ... */
if ($my->isWorking()) {
    /* ... the Worker is busy executing another object */
}
?>


Shutdown the worker

  • « Worker::isWorking
  • Worker::stack »
  • PHP Manual
  • Worker
  • Shutdown the worker

Worker::shutdown

(PECL pthreads >= 2.0.0)

Worker::shutdown — Shutdown the worker

Description

public Worker::shutdown ( void ) : bool

Shuts down the worker after executing all of the stacked tasks.

Parameters

This function has no parameters.

Return Values

Whether the worker was successfully shutdown or not.

Examples

Example #1 Shutdown the referenced worker

<?php
$my = new Worker();
$my->start();
/* stack/execute tasks */
var_dump($my->shutdown());

The above example will output:

bool(true)


Stacking work

  • « Worker::shutdown
  • Worker::unstack »
  • PHP Manual
  • Worker
  • Stacking work

Worker::stack

(PECL pthreads >= 2.0.0)

Worker::stack — Stacking work

Description

public Worker::stack ( Threaded &$work ) : int

Appends the new work to the stack of the referenced worker.

Parameters

work

A Threaded object to be executed by the worker.

Return Values

The new size of the stack.

Examples

Example #1 Stacking a task for execution onto a worker

<?php
$worker = new Worker();
$work = new class extends Threaded {};

var_dump($worker->stack($work));

The above example will output:

int(1)


Unstacking work

  • « Worker::stack
  • Collectable »
  • PHP Manual
  • Worker
  • Unstacking work

Worker::unstack

(PECL pthreads >= 2.0.0)

Worker::unstack — Unstacking work

Description

public Worker::unstack ( void ) : int

Removes the first task (the oldest one) in the stack.

Parameters

This function has no parameters.

Return Values

The new size of the stack.

Changelog

Version | Description
v3 | The parameter to specify the task to unstack has been removed. Now, only the first task in the stack is removed.

Examples

Example #1 Removing objects from the stack of Workers

<?php
$my = new Worker();
$work = new class extends Threaded {};

var_dump($my->stack($work));
var_dump($my->unstack());

The above example will output:

int(1)
int(0)


The Collectable interface

(PECL pthreads >= 2.0.8)

Introduction

Caution

Collectable was previously a class (in pthreads v2 and below). Now, it is an interface in pthreads v3 that is implemented by the Threaded class.

Represents a garbage-collectable object.

Interface synopsis

Collectable {
/* Methods */
public isGarbage ( void ) : bool
public setGarbage ( void ) : void
}

Table of Contents

  • Collectable::isGarbage — Determine whether an object has been marked as garbage
  • Collectable::setGarbage — Mark an object as garbage


Determine whether an object has been marked as garbage

  • « Collectable
  • Collectable::setGarbage »
  • PHP Manual
  • Collectable
  • Determine whether an object has been marked as garbage

Collectable::isGarbage

(PECL pthreads >= 2.0.8)

Collectable::isGarbage — Determine whether an object has been marked as garbage

Description

public Collectable::isGarbage ( void ) : bool

Can be called in Pool::collect() to determine if this object is garbage.

See Also

  • Pool::collect() - Collect references to completed tasks


Mark an object as garbage

  • « Collectable::isGarbage
  • Modifiers »
  • PHP Manual
  • Collectable
  • Mark an object as garbage

Collectable::setGarbage

(PECL pthreads < 3.0.0)

Collectable::setGarbage — Mark an object as garbage

Warning

This method has been removed in pthreads v3.

Description

public Collectable::setGarbage ( void ) : void

Should be called once per object when the object is finished being executed or referenced.

See Also

  • Collectable::isGarbage() - Determine whether an object has been marked as garbage


Method Modifiers

Warning

These semantics are only applicable to pthreads v2 - they have been removed in pthreads v3.

pthreads overrides the functionality of the protected and private method modifiers in order to provide functionality more suited to multi-threaded objects. pthreads applies this functionality to all Threaded objects from creation.

Example #1 protected method example: protected methods can only be executed by one Thread at a time.

<?php
class ExampleThread extends Thread {
    public function run() {
        /* thread code */
        if ($this->synchronized()) {

        }
    }

    protected function exclusive() {
        /* synchronized method */
    }
}

$thread = new ExampleThread();
if ($thread->start()) {
    $thread->exclusive();
}
?>

Example #2 private method example: private methods may only be executed by the Threaded object during execution

<?php
class ExampleThread extends Thread {
    public function run() {
        /* thread code */
        if ($this->insideonly()) {

        }
    }

    private function insideonly() {
        /* private method */
    }
}

$thread = new ExampleThread();
if ($thread->start()) {
    $thread->insideonly();
}
?>


The Pool class

(PECL pthreads >= 2.0.0)

Introduction

A Pool is a container for, and controller of, an adjustable number of Workers.

Pooling provides a higher level abstraction of the Worker functionality, including the management of references in the way required by pthreads.

Class synopsis

Pool {
/* Properties */
protected $size ;
protected $class ;
protected $workers ;
protected $ctor ;
protected $last ;
/* Methods */
public collect ([ Callable $collector ] ) : int
public __construct ( int $size [, string $class [, array $ctor ]] ) : Pool
public resize ( int $size ) : void
public shutdown ( void ) : void
public submit ( Threaded $task ) : int
public submitTo ( int $worker , Threaded $task ) : int
}

Properties

size

maximum number of Workers this Pool can use

class

the class of the Worker

workers

references to Workers

ctor

the arguments for constructor of new Workers

last

offset in workers of the last Worker used

Table of Contents

  • Pool::collect — Collect references to completed tasks
  • Pool::__construct — Creates a new Pool of Workers
  • Pool::resize — Resize the Pool
  • Pool::shutdown — Shutdown all workers
  • Pool::submit — Submits an object for execution
  • Pool::submitTo — Submits a task to a specific worker for execution


Collect references to completed tasks

  • « Pool
  • Pool::__construct »
  • PHP Manual
  • Pool
  • Collect references to completed tasks

Pool::collect

(PECL pthreads >= 2.0.0)

Pool::collect — Collect references to completed tasks

Description

public Pool::collect ([ Callable $collector ] ) : int

Allows the pool to collect references determined to be garbage by the optionally given collector.

Parameters

collector

A Callable collector that returns a boolean on whether the task can be collected or not. Only in rare cases should a custom collector need to be used.

Return Values

The number of remaining tasks in the pool to be collected.

Changelog

Version | Description
v3 | An integer is now returned, and the collector parameter is now optional.

Examples

Example #1 A basic example of Pool::collect()

<?php
$pool = new Pool(4);

for ($i = 0; $i < 15; ++$i) {
    $pool->submit(new class extends Threaded {});
}

while ($pool->collect()); // blocks until all tasks have finished executing

$pool->shutdown();


Creates a new Pool of Workers

  • « Pool::collect
  • Pool::resize »
  • PHP Manual
  • Pool
  • Creates a new Pool of Workers

Pool::__construct

(PECL pthreads >= 2.0.0)

Pool::__construct — Creates a new Pool of Workers

Description

public Pool::__construct ( int $size [, string $class [, array $ctor ]] ) : Pool

Construct a new pool of workers. Pools lazily create their threads, which means new threads will only be spawned when they are required to execute tasks.

Parameters

size

The maximum number of workers for this pool to create

class

The class for new Workers. If no class is given, then it defaults to the Worker class.

ctor

An array of arguments to be passed to new workers' constructors

Return Values

The new pool

Examples

Example #1 Creating Pools

<?php
class MyWorker extends Worker {

    public function __construct(Something $something) {
        $this->something = $something;
    }

    public function run() {
        /** ... **/
    }
}

$pool = new Pool(8, \MyWorker::class, [new Something()]);

var_dump($pool);
?>

The above example will output:

object(Pool)#1 (6) {
  ["size":protected]=>
  int(8)
  ["class":protected]=>
  string(8) "MyWorker"
  ["workers":protected]=>
  NULL
  ["work":protected]=>
  NULL
  ["ctor":protected]=>
  array(1) {
    [0]=>
    object(Something)#2 (0) {
    }
  }
  ["last":protected]=>
  int(0)
}


Resize the Pool

  • « Pool::__construct
  • Pool::shutdown »
  • PHP Manual
  • Pool
  • Resize the Pool

Pool::resize

(PECL pthreads >= 2.0.0)

Pool::resize — Resize the Pool

Description

public Pool::resize ( int $size ) : void

Resize the Pool

Parameters

size

The maximum number of Workers this Pool can create

Return Values

void


Shutdown all workers

  • « Pool::resize
  • Pool::submit »
  • PHP Manual
  • Pool
  • Shutdown all workers

Pool::shutdown

(PECL pthreads >= 2.0.0)

Pool::shutdown — Shutdown all workers

Description

public Pool::shutdown ( void ) : void

Shuts down all of the workers in the pool. This will block until all submitted tasks have been executed.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 Shutting down a pool

<?php
class Task extends Threaded
{
    public function run()
    {
        usleep(500000);
    }
}

$pool = new Pool(4);

for ($i = 0; $i < 10; ++$i) {
    $pool->submit(new Task());
}

$pool->shutdown(); // blocks until all submitted tasks have finished executing


Submits an object for execution

  • « Pool::shutdown
  • Pool::submitTo »
  • PHP Manual
  • Pool
  • Submits an object for execution

Pool::submit

(PECL pthreads >= 2.0.0)

Pool::submit — Submits an object for execution

Description

public Pool::submit ( Threaded $task ) : int

Submit the task to the next Worker in the Pool

Parameters

task

The task for execution

Return Values

the identifier of the Worker executing the object

Examples

Example #1 Submitting Tasks

<?php
class MyWork extends Threaded {

    public function run() {
        /* ... */
    }
}

class MyWorker extends Worker {

    public function __construct(Something $something) {
        $this->something = $something;
    }

    public function run() {
        /** ... **/
    }
}

$pool = new Pool(8, \MyWorker::class, [new Something()]);
$pool->submit(new MyWork());
var_dump($pool);
?>

The above example will output:

object(Pool)#1 (6) {
  ["size":protected]=>
  int(8)
  ["class":protected]=>
  string(8) "MyWorker"
  ["workers":protected]=>
  array(1) {
    [0]=>
    object(MyWorker)#4 (1) {
      ["something"]=>
      object(Something)#5 (0) {
      }
    }
  }
  ["work":protected]=>
  array(1) {
    [0]=>
    object(MyWork)#3 (1) {
      ["worker"]=>
      object(MyWorker)#5 (1) {
        ["something"]=>
        object(Something)#6 (0) {
        }
      }
    }
  }
  ["ctor":protected]=>
  array(1) {
    [0]=>
    object(Something)#2 (0) {
    }
  }
  ["last":protected]=>
  int(1)
}


Submits a task to a specific worker for execution

  • « Pool::submit
  • Mutex »
  • PHP Manual
  • Pool
  • Submits a task to a specific worker for execution

Pool::submitTo

(PECL pthreads >= 2.0.0)

Pool::submitTo — Submits a task to a specific worker for execution

Description

public Pool::submitTo ( int $worker , Threaded $task ) : int

Submit a task to the specified worker in the pool. The workers are indexed from 0, and will only exist if the pool has needed to create them (since threads are lazily spawned).

Parameters

worker

The worker to stack the task onto, indexed from 0.

task

The task for execution.

Return Values

The identifier of the worker that accepted the task.

Examples

Example #1 Submitting tasks to a specific worker

<?php
class Task extends Threaded {
    public function run() {
        var_dump(Thread::getCurrentThreadID());
    }
}

$pool = new Pool(2);

$pool->submit(new Task());

for ($i = 0; $i < 5; ++$i) {
    $pool->submitTo(0, new Task()); // stack all tasks onto the first worker
}

$pool->submitTo(1, new Task()); // cannot stack the task onto the second worker due to it not existing yet

$pool->shutdown();

The above example will output:

int(4475011072)
int(4475011072)
int(4475011072)
int(4475011072)
int(4475011072)
int(4475011072)

Fatal error: Uncaught Exception: The selected worker (1) does not exist in %s:%d


The Mutex class

(PECL pthreads < 3.0.0)

Introduction

Warning

The Mutex class has been removed in pthreads v3.

The static methods contained in the Mutex class provide direct access to Posix Mutex functionality.

Class synopsis

Mutex {
/* Methods */
final public static create ([ bool $lock ] ) : int
final public static destroy ( int $mutex ) : bool
final public static lock ( int $mutex ) : bool
final public static trylock ( int $mutex ) : bool
final public static unlock ( int $mutex [, bool $destroy ] ) : bool
}

Table of Contents

  • Mutex::create — Create a Mutex
  • Mutex::destroy — Destroy Mutex
  • Mutex::lock — Acquire Mutex
  • Mutex::trylock — Attempt to Acquire Mutex
  • Mutex::unlock — Release Mutex


Create a Mutex

  • « Mutex
  • Mutex::destroy »
  • PHP Manual
  • Mutex
  • Create a Mutex

Mutex::create

(PECL pthreads < 3.0.0)

Mutex::create — Create a Mutex

Warning

The Mutex class has been removed in pthreads v3.

Description

final public static Mutex::create ([ bool $lock ] ) : int

Create, and optionally lock a new Mutex for the caller

Parameters

lock

Setting lock to true will lock the Mutex for the caller before returning the handle

Return Values

A newly created and optionally locked Mutex handle

Examples

Example #1 Mutex Creation and Destruction

<?php
/** You cannot use the "new" keyword, a Mutex is not a PHP object **/
$mutex = Mutex::create();
/** You have the physical address of the Mutex **/
var_dump($mutex);
/** Always destroy mutex you have created **/
Mutex::destroy($mutex);
?>

The above example will output:

int(40096976)


Destroy Mutex

  • « Mutex::create
  • Mutex::lock »
  • PHP Manual
  • Mutex
  • Destroy Mutex

Mutex::destroy

(PECL pthreads < 3.0.0)

Mutex::destroy — Destroy Mutex

Warning

The Mutex class has been removed in pthreads v3.

Description

final public static Mutex::destroy ( int $mutex ) : bool

Destroying Mutex handles must be carried out explicitly by the programmer when they are finished with the Mutex handle.

Parameters

mutex

A handle returned by a previous call to Mutex::create(). The handle should not be locked by any Thread when Mutex::destroy() is called.

Return Values

A boolean indication of success

Examples

Example #1 Mutex Creation and Destruction

<?php
/** You cannot use the "new" keyword, a Mutex is not a PHP object **/
$mutex = Mutex::create();
/** You have the physical address of the Mutex **/
var_dump($mutex);
/** Always destroy mutex you have created **/
Mutex::destroy($mutex);
?>

The above example will output:

int(40096976)


Acquire Mutex

  • « Mutex::destroy
  • Mutex::trylock »
  • PHP Manual
  • Mutex
  • Acquire Mutex

Mutex::lock

(PECL pthreads < 3.0.0)

Mutex::lock — Acquire Mutex

Warning

The Mutex class has been removed in pthreads v3.

Description

final public static Mutex::lock ( int $mutex ) : bool

Attempt to lock the Mutex for the caller.

An attempt to lock a Mutex owned (locked) by another Thread will result in blocking.

Parameters

mutex

A handle returned by a previous call to Mutex::create().

Return Values

A boolean indication of success.

Examples

Example #1 Mutex Locking and Unlocking

<?php
/** You cannot use the "new" keyword, a Mutex is not a PHP object **/
$mutex = Mutex::create();
/** You can now lock the mutex in any context **/
var_dump(Mutex::lock($mutex));
/** It is invalid to attempt to destroy a locked Mutex **/
var_dump(Mutex::unlock($mutex));
/** Always destroy mutex you have created **/
Mutex::destroy($mutex);
?>

The above example will output:

bool(true)
bool(true)


Attempt to Acquire Mutex

  • « Mutex::lock
  • Mutex::unlock »
  • PHP Manual
  • Mutex
  • Attempt to Acquire Mutex

Mutex::trylock

(PECL pthreads < 3.0.0)

Mutex::trylock — Attempt to Acquire Mutex

Warning

The Mutex class has been removed in pthreads v3.

Description

final public static Mutex::trylock ( int $mutex ) : bool

Attempt to lock the Mutex for the caller without blocking if the Mutex is owned (locked) by another Thread.

Parameters

mutex

A handle returned by a previous call to Mutex::create().

Return Values

A boolean indication of success.

Examples

Example #1 Mutex Locking and Unlocking

<?php
/** You cannot use the "new" keyword, a Mutex is not a PHP object **/
$mutex = Mutex::create();
/** You can now try to lock the mutex in any context **/
var_dump(Mutex::trylock($mutex));
/** It is invalid to attempt to destroy a locked Mutex **/
var_dump(Mutex::unlock($mutex));
/** Always destroy mutex you have created **/
Mutex::destroy($mutex);
?>

The above example will output:

bool(true)
bool(true)


Release Mutex

  • « Mutex::trylock
  • Cond »
  • PHP Manual
  • Mutex
  • Release Mutex

Mutex::unlock

(PECL pthreads < 3.0.0)

Mutex::unlock — Release Mutex

Warning

The Mutex class has been removed in pthreads v3.

Description

final public static Mutex::unlock ( int $mutex [, bool $destroy ] ) : bool

Attempts to unlock the Mutex for the caller, optionally destroying the Mutex handle. The calling thread should own the Mutex at the time of the call.

Parameters

mutex

A handle returned by a previous call to Mutex::create().

destroy

When true pthreads will destroy the Mutex after a successful unlock.

Return Values

A boolean indication of success.

Examples

Example #1 Mutex Locking and Unlocking

<?php
/** You cannot use the "new" keyword, a Mutex is not a PHP object **/
$mutex = Mutex::create();
/** You can now lock the mutex in any context **/
var_dump(Mutex::lock($mutex));
/** It is invalid to attempt to destroy a locked Mutex **/
var_dump(Mutex::unlock($mutex));
/** Always destroy mutex you have created **/
Mutex::destroy($mutex);
?>

The above example will output:

bool(true)
bool(true)


The Cond class

(PECL pthreads < 3.0.0)

Introduction

Warning

The Cond class has been removed in pthreads v3.

The static methods contained in the Cond class provide direct access to Posix Condition Variables.

Class synopsis

Cond {
/* Methods */
final public static broadcast ( int $condition ) : bool
final public static create ( void ) : int
final public static destroy ( int $condition ) : bool
final public static signal ( int $condition ) : bool
final public static wait ( int $condition , int $mutex [, int $timeout ] ) : bool
}

Table of Contents

  • Cond::broadcast — Broadcast a Condition
  • Cond::create — Create a Condition
  • Cond::destroy — Destroy a Condition
  • Cond::signal — Signal a Condition
  • Cond::wait — Wait for Condition


Broadcast a Condition

  • « Cond
  • Cond::create »
  • PHP Manual
  • Cond
  • Broadcast a Condition

Cond::broadcast

(PECL pthreads < 3.0.0)

Cond::broadcast — Broadcast a Condition

Warning

The Cond class has been removed in pthreads v3.

Description

final public static Cond::broadcast ( int $condition ) : bool

Broadcast to all Threads blocking on a call to Cond::wait().

Parameters

condition

A handle to a Condition Variable returned by a previous call to Cond::create()

Return Values

A boolean indication of success.

Examples

Example #1 Condition Broadcasting

<?php
/** You cannot use the "new" keyword, a Cond is not a PHP object **/
$cond = Cond::create();
/** The caller must lock the associated Mutex before a call to broadcast **/
var_dump(Cond::broadcast($cond));
/** Always destroy Cond you have created **/
Cond::destroy($cond);
?>

The above example will output:

bool(true)


Create a Condition

  • « Cond::broadcast
  • Cond::destroy »
  • PHP Manual
  • Cond
  • Create a Condition

Cond::create

(PECL pthreads < 3.0.0)

Cond::create — Create a Condition

Warning

The Cond class has been removed in pthreads v3.

Description

final public static Cond::create ( void ) : int

Creates a new Condition Variable for the caller.

Parameters

This function has no parameters.

Return Values

A handle to a Condition Variable

Examples

Example #1 Condition Creation and Destruction

<?php
/** You cannot use the "new" keyword, a Cond is not a PHP object **/
$cond = Cond::create();
/** You can now use the Cond in any context **/
var_dump($cond);
/** Always destroy Cond you have created **/
Cond::destroy($cond);
?>

The above example will output:

int(4540682)


Destroy a Condition

  • « Cond::create
  • Cond::signal »
  • PHP Manual
  • Cond
  • Destroy a Condition

Cond::destroy

(PECL pthreads < 3.0.0)

Cond::destroy — Destroy a Condition

Warning

The Cond class has been removed in pthreads v3.

Description

final public static Cond::destroy ( int $condition ) : bool

Destroying Condition Variable handles must be carried out explicitly by the programmer when they are finished with the Condition Variable. No Threads should be blocking on a call to Cond::wait() when the call to Cond::destroy() takes place.

Parameters

condition

A handle to a Condition Variable returned by a previous call to Cond::create()

Return Values

A boolean indication of success.

Examples

Example #1 Condition Creation and Destruction

<?php
/** You cannot use the "new" keyword, a Cond is not a PHP object **/
$cond = Cond::create();
/** You can now use the Cond in any context **/
var_dump($cond);
/** Always destroy Cond you have created **/
Cond::destroy($cond);
?>

The above example will output:

int(4540682)


Signal a Condition

  • « Cond::destroy
  • Cond::wait »
  • PHP Manual
  • Cond
  • Signal a Condition

Cond::signal

(PECL pthreads < 3.0.0)

Cond::signal — Signal a Condition

Warning

The Cond class has been removed in pthreads v3.

Description

final public static Cond::signal ( int $condition ) : bool

Parameters

condition

A handle returned by a previous call to Cond::create()

Return Values

A boolean indication of success.

Examples

Example #1 Condition Signalling

<?php
/** You cannot use the "new" keyword, a Cond is not a PHP object **/
$cond = Cond::create();
/** The caller must lock the associated Mutex before a call to broadcast **/
var_dump(Cond::signal($cond));
/** Always destroy Cond you have created **/
Cond::destroy($cond);
?>

The above example will output:

bool(true)


Wait for Condition

  • « Cond::signal
  • Volatile »
  • PHP Manual
  • Cond
  • Wait for Condition

Cond::wait

(PECL pthreads < 3.0.0)

Cond::wait — Wait for Condition

Warning

The Cond class has been removed in pthreads v3.

Description

final public static Cond::wait ( int $condition , int $mutex [, int $timeout ] ) : bool

Wait for a signal on a Condition Variable, optionally specifying a timeout to limit waiting time.

Parameters

condition

A handle returned by a previous call to Cond::create().

mutex

A handle returned by a previous call to Mutex::create() and owned (locked) by the caller.

timeout

An optional timeout, in microseconds ( millionths of a second ).

Return Values

A boolean indication of success.

Examples

Example #1 Waiting for Conditions

<?php
/** PLEASE NOTE THIS EXAMPLE WILL CAUSE THE PROCESS TO HANG **/
$mutex = Mutex::create(true);
/** You cannot use the "new" keyword, a Cond is not a PHP object **/
$cond = Cond::create();
/** The caller must lock the associated Mutex before a call to broadcast **/
var_dump(Cond::wait($cond, $mutex));
/** Always destroy Cond you have created **/
Cond::destroy($cond);
Mutex::unlock($mutex);
Mutex::destroy($mutex);
?>

The above example will output:

int(49685473)


The Volatile class

(PECL pthreads >= 3.0.0)

Introduction

The Volatile class is new to pthreads v3. Its introduction is a consequence of the new immutability semantics of Threaded members of Threaded classes. The Volatile class enables for mutability of its Threaded members, and is also used to store PHP arrays in Threaded contexts.

Class synopsis

Volatile extends Threaded implements Collectable , Traversable {
/* Inherited methods */
public Threaded::chunk ( int $size , bool $preserve ) : array
public Threaded::count ( void ) : int
public Threaded::extend ( string $class ) : bool
public Threaded::from ( Closure $run [, Closure $construct [, array $args ]] ) : Threaded
public Threaded::getTerminationInfo ( void ) : array
public Threaded::isRunning ( void ) : bool
public Threaded::isTerminated ( void ) : bool
public Threaded::isWaiting ( void ) : bool
public Threaded::lock ( void ) : bool
public Threaded::merge ( mixed $from [, bool $overwrite ] ) : bool
public Threaded::notify ( void ) : bool
public Threaded::notifyOne ( void ) : bool
public Threaded::pop ( void ) : bool
public Threaded::run ( void ) : void
public Threaded::shift ( void ) : mixed
public Threaded::synchronized ( Closure $block [, mixed $... ] ) : mixed
public Threaded::unlock ( void ) : bool
public Threaded::wait ([ int $timeout ] ) : bool
}

Examples

Example #1 New immutability semantics of Threaded

<?php

class Task extends Threaded
{
    public function __construct()
    {
        $this->data = new Threaded();

        // attempt to overwrite a Threaded property of a Threaded class (invalid)
        $this->data = new StdClass();
    }
}

var_dump((new Task())->data);

The above example will output something similar to:

RuntimeException: Threaded members previously set to Threaded objects are immutable, cannot overwrite data in %s:%d

Example #2 Volatile use-case

<?php

class Task extends Volatile
{
    public function __construct()
    {
        $this->data = new Threaded();

        // attempt to overwrite a Threaded property of a Volatile class (valid)
        $this->data = new StdClass();
    }
}

var_dump((new Task())->data);

The above example will output something similar to:

object(stdClass)#3 (0) {
}


pht

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
  • pht\Thread — The Thread class
    • pht\Thread::addClassTask — Class threading
    • pht\Thread::addFileTask — File threading
    • pht\Thread::addFunctionTask — Function threading
    • pht\Thread::join — Joins a thread
    • pht\Thread::start — Starts the new thread
    • pht\Thread::taskCount — Gets a thread's task count
  • pht\Runnable — The Runnable interface
    • pht\Runnable::run — The entry point of a threaded class
  • pht\HashTable — The HashTable class
    • pht\HashTable::lock — Acquires the hash table's mutex lock
    • pht\HashTable::size — Gets the size of the hash table
    • pht\HashTable::unlock — Releases the hash table's mutex lock
  • pht\Vector — The Vector class
    • pht\Vector::__construct — Vector creation
    • pht\Vector::deleteAt — Deletes a value in the vector
    • pht\Vector::insertAt — Inserts a value into the vector
    • pht\Vector::lock — Acquires the vector's mutex lock
    • pht\Vector::pop — Pops a value to the vector
    • pht\Vector::push — Pushes a value to the vector
    • pht\Vector::resize — Resizes a vector
    • pht\Vector::shift — Shifts a value from the vector
    • pht\Vector::size — Gets the size of the vector
    • pht\Vector::unlock — Releases the vector's mutex lock
    • pht\Vector::unshift — Unshifts a value to the vector front
    • pht\Vector::updateAt — Updates a value in the vector
  • pht\Queue — The Queue class
    • pht\Queue::front — Returns the first value from a queue
    • pht\Queue::lock — Acquires the queue's mutex lock
    • pht\Queue::pop — Pops a value off of the front of a queue
    • pht\Queue::push — Pushes a value to the end of a queue
    • pht\Queue::size — Gets the size of the queue
    • pht\Queue::unlock — Releases the queue's mutex lock
  • pht\AtomicInteger — The AtomicInteger class
    • pht\AtomicInteger::__construct — AtomicInteger creation
    • pht\AtomicInteger::dec — Decrements the atomic integer's value by one
    • pht\AtomicInteger::get — Gets the atomic integer's value
    • pht\AtomicInteger::inc — Increments the atomic integer's value by one
    • pht\AtomicInteger::lock — Acquires the atomic integer's mutex lock
    • pht\AtomicInteger::set — Sets the atomic integer's value
    • pht\AtomicInteger::unlock — Releases the atomic integer's mutex lock
  • pht\Threaded — The Threaded interface
    • pht\Threaded::lock — Acquires the mutex lock
    • pht\Threaded::unlock — Releases the mutex lock


Introduction

pht is a new threading extension for PHP. It enables for classes, functions, and even entire files to be threaded. Currently, pht can only be used with PHP 7.2. This is due to ZTS mode being unsafe in PHP 7.0 and 7.1. Support for PHP >7.2 is coming soon.

Warning

The pht extension should not be used in a web server environment. Threading should be restricted to CLI-based applications only.

The approach to threading that pht takes is to abstract away the thread itself behind a dedicated object (pht\Thread). Tasks are then added to the thread's internal task queue, where they are processed when the thread is started (via pht\Thread::start()).

All thread tasks will execute in isolation inside of the newly spawned thread. For class tasks, this means the spawned objects cannot be passed around between threads. By keeping the threading contexts completely separate from one-another, there becomes no need to serialise the properties of threaded objects (which is a necessary evil if such objects have to operate in multiple threads).

The isolation of threading contexts makes the passing around of data between them somewhat problematic. To solve this problem, threadable data structures (pht\HashTable, pht\Vector, and pht\Queue) have been implemented to allow for a two-way communication style between threads, where they expose mutex locks to control their integrity. These data structures can be safely passed around between threads, and manipulated by multiple threads using the mutex locks that have been packed in with them. They are reference-counted across threads, and so they do not need to be explicitly destroyed. This approach to threading means that only the given built-in data structures need to be safely passed around between threads.

Atomic values are also supported by pht. Currently, only an pht\AtomicInteger class exists. Like the threaded data structures, it too can safely be passed around between threads.


Requirements

pht requires a ZTS (Zend Thread Safety) version of PHP. Currently, only PHP 7.2 is supported. Support for PHP 7.3 (which will be released at the end of 2018) will be coming soon. PHP 7.0 and 7.1 are unsafe to support, due to race conditions in ZTS mode.

pht should be compatible for any OS with the pthread library (or pthread-win32 library, which is for Windows).


Installation

pht releases are hosted (along with its source code) on the » pht GitHub repository. Unix developers will need to build from source (» instructions here). Windows developers can download the appropriate .dll file from the » repository's releases page. They will need to ensure that the provided pthreadVC2.dll file (which is distributed alongside the extension's .dll file) is made available in their PATH environment variable.


  • « Installation
  • pht\Thread »
  • PHP Manual
  • Installing/Configuring
  • Runtime Configuration

Runtime Configuration

This extension has no configuration directives defined in php.ini.


The Thread class

(PECL pht >= 0.0.1)

Introduction

The pht\Thread class abstracts away a native thread. It has an internal task queue, where the methods pht\Thread::addClassTask(), pht\Thread::addFunctionTask(), and pht\Thread::addFileTask() push new tasks onto this queue. Invoking the pht\Thread::start() method will cause the new thread to be spawned, where it will then begin working through the task queue. A thread may be reused for any number of tasks.

Class synopsis

pht\Thread {
/* Methods */
public addClassTask ( string $className [, mixed $...ctorArgs ] ) : void
public addFileTask ( string $fileName [, mixed $...globals ] ) : void
public addFunctionTask ( callable $func [, mixed $...funcArgs ] ) : void
public join ( void ) : void
public start ( void ) : void
public taskCount ( void ) : int
}

Table of Contents

  • pht\Thread::addClassTask — Class threading
  • pht\Thread::addFileTask — File threading
  • pht\Thread::addFunctionTask — Function threading
  • pht\Thread::join — Joins a thread
  • pht\Thread::start — Starts the new thread
  • pht\Thread::taskCount — Gets a thread's task count


Class threading

  • « pht\Thread
  • pht\Thread::addFileTask »
  • PHP Manual
  • pht\Thread
  • Class threading

pht\Thread::addClassTask

(PECL pht >= 0.0.1)

pht\Thread::addClassTask — Class threading

Description

public pht\Thread::addClassTask ( string $className [, mixed $...ctorArgs ] ) : void

Adds a new class task to a pht\Threads internal task queue.

Parameters

className

The name of the class to be threaded. This class must implement the pht\Runnable interface.

...ctorArgs

An optional list of arguments for the threaded class' constructor. These arguments will be serialised (since they are being passed to another thread).

Return Values

No return value.

Examples

Example #1 Adding a new class task to a thread

<?php

use pht\{Thread, Runnable};

class Task implements Runnable
{
    private $one;

    public function __construct(int $one)
    {
        $this->one = $one;
    }

    public function run()
    {
        var_dump($this->one);
    }
}

$thread = new Thread();

$thread->addClassTask(Task::class, 1);

$thread->start();
$thread->join();

The above example will output:

int(1)


File threading

  • « pht\Thread::addClassTask
  • pht\Thread::addFunctionTask »
  • PHP Manual
  • pht\Thread
  • File threading

pht\Thread::addFileTask

(PECL pht >= 0.0.1)

pht\Thread::addFileTask — File threading

Description

public pht\Thread::addFileTask ( string $fileName [, mixed $...globals ] ) : void

Adds a new file task to a pht\Threads internal task queue.

Parameters

func

The name of the file to be threaded.

...globals

An optional list of arguments for the file. These arguments will be placed into a $_THREAD superglobal, which will be made available inside of the threaded file. All arguments will be serialised (since they are being passed to another thread).

Return Values

No return value.

Examples

Example #1 Adding a new file task to a thread

<?php

use pht\Thread;

$thread = new Thread();

$thread->addFileTask('file.php', 1, 2, 3);

$thread->start();
$thread->join();

file.php:

<?php

[$one, $two, $three] = $_THREAD;

var_dump($one, $two, $three);

The above example will output:

int(1)
int(2)
int(3)


Function threading

  • « pht\Thread::addFileTask
  • pht\Thread::join »
  • PHP Manual
  • pht\Thread
  • Function threading

pht\Thread::addFunctionTask

(PECL pht >= 0.0.1)

pht\Thread::addFunctionTask — Function threading

Description

public pht\Thread::addFunctionTask ( callable $func [, mixed $...funcArgs ] ) : void

Adds a new function task to a pht\Threads internal task queue.

Parameters

func

The function to be threaded. If it is bound to an instance, then $this will become NULL.

...funcArgs

An optional list of arguments for the function. These arguments will be serialised (since they are being passed to another thread).

Return Values

No return value.

Examples

Example #1 Adding a new function task to a thread

<?php

use pht\Thread;

class Test
{
    public static function run(){var_dump(5);}
    public static function run2(){var_dump(6);}
}

function aFunc(){var_dump(3);}

$thread = new Thread();

$thread->addFunctionTask(static function($one) {var_dump($one);}, 1);
$thread->addFunctionTask(function() {var_dump(2);});
$thread->addFunctionTask('aFunc');
$thread->addFunctionTask('array_map', function ($n) {var_dump($n);}, [4]);
$thread->addFunctionTask(['Test', 'run']);
$thread->addFunctionTask([new Test, 'run2']);

$thread->start();
$thread->join();

The above example will output:

int(1)
int(2)
int(3)
int(4)
int(5)
int(6)


Joins a thread

  • « pht\Thread::addFunctionTask
  • pht\Thread::start »
  • PHP Manual
  • pht\Thread
  • Joins a thread

pht\Thread::join

(PECL pht >= 0.0.1)

pht\Thread::join — Joins a thread

Description

public pht\Thread::join ( void ) : void

This method will join the spawned thread (though it will first wait for that thread's internal task queue to finish). As a matter of good practice, threads should always be joined. Not joining a thread may lead to undefined behaviour.

Parameters

This function has no parameters.

Return Values

No return value.

Examples

Example #1 Joining a thread

<?php

use pht\Thread;

$thread = new Thread();

$thread->start();
$thread->join();


Starts the new thread

  • « pht\Thread::join
  • pht\Thread::taskCount »
  • PHP Manual
  • pht\Thread
  • Starts the new thread

pht\Thread::start

(PECL pht >= 0.0.1)

pht\Thread::start — Starts the new thread

Description

public pht\Thread::start ( void ) : void

This will cause a new thread to be spawned for the associated pht\Thread object, where its internal task queue will begin to be processed.

Parameters

This function has no parameters.

Return Values

No return value.

Examples

Example #1 Starting a new thread

<?php

use pht\Thread;

$thread = new Thread();

$thread->start();
$thread->join();


Gets a thread's task count

  • « pht\Thread::start
  • pht\Runnable »
  • PHP Manual
  • pht\Thread
  • Gets a thread's task count

pht\Thread::taskCount

(PECL pht >= 0.0.1)

pht\Thread::taskCount — Gets a thread's task count

Description

public pht\Thread::taskCount ( void ) : int

Retrieves the current task count of a pht\Thread.

Parameters

This function has no parameters.

Return Values

The number of tasks remaining to be processed.

Examples

Example #1 Getting the task count of a thread

<?php

use pht\Thread;

$thread = new Thread();

$thread->addFunctionTask(function (){});
$thread->addFunctionTask(function (){});
$thread->addFunctionTask(function (){});

var_dump($thread->taskCount());

The above example will output:

int(3)


The Runnable interface

(PECL pht >= 0.0.1)

Introduction

The pht\Runnable interface enforces the implementation of a run() method on classes that should be threaded. This method acts as the entry point of the threaded class.

Interface synopsis

pht\Runnable {
/* Methods */
public run ( void ) : void
}

Table of Contents

  • pht\Runnable::run — The entry point of a threaded class


The entry point of a threaded class

  • « pht\Runnable
  • pht\HashTable »
  • PHP Manual
  • pht\Runnable
  • The entry point of a threaded class

pht\Runnable::run

(PECL pht >= 0.0.1)

pht\Runnable::run — The entry point of a threaded class

Description

public pht\Runnable::run ( void ) : void

This method acts as the entry point of execution for a threaded class. It must be defined by all classes that will be threaded.

Parameters

This function has no parameters.

Return Values

No return value.


The HashTable class

(PECL pht >= 0.0.1)

Introduction

The pht\HashTable class is one of the Inter-Thread Communication (ITC) data structures exposed by pht. It can be safely passed around between threads, and manipulated by multiple threads using the mutex locks that have been packed in with the data structure. It is reference-counted across threads, and so it does not need to be explicitly destroyed.

The pht\HashTable class enables for array access upon its objects (along with the isset() and unset() functions). The ArrayAccess interface is not explicitly implemented, however, because it is only needed for such abilities by userland classes.

Class synopsis

pht\HashTable implements pht\Threaded {
/* Methods */
public lock ( void ) : void
public size ( void ) : int
public unlock ( void ) : void
}

Table of Contents

  • pht\HashTable::lock — Acquires the hash table's mutex lock
  • pht\HashTable::size — Gets the size of the hash table
  • pht\HashTable::unlock — Releases the hash table's mutex lock


Acquires the hash table's mutex lock

  • « pht\HashTable
  • pht\HashTable::size »
  • PHP Manual
  • pht\HashTable
  • Acquires the hash table's mutex lock

pht\HashTable::lock

(PECL pht >= 0.0.1)

pht\HashTable::lock — Acquires the hash table's mutex lock

Description

public pht\HashTable::lock ( void ) : void

This method will acquire the mutex lock associated with the hash table. The mutex lock should always be acquired when manipulating the hash table if it is being used by multiple threads.

The mutex locks of the Inter-Thread Communication (ITC) data structures are not reentrant. Attempting to reacquire an already-acquired mutex lock by the same thread will therefore cause a deadlock.

Parameters

This function has no parameters.

Return Values

No return value.

Examples

Example #1 Locking a hash table's mutex lock

<?php

use pht\{Thread, HashTable};

$thread = new Thread();
$hashTable = new HashTable();

$thread->addFunctionTask(function ($hashTable) {
    $hashTable->lock();
    $hashTable['a'] = 1;
    $hashTable->unlock();
}, $hashTable);

$thread->start();

// $hashTable is currently being used by multiple threads
$hashTable->lock();
$hashTable['b'] = 2;
$hashTable->unlock();

$thread->join();


Gets the size of the hash table

  • « pht\HashTable::lock
  • pht\HashTable::unlock »
  • PHP Manual
  • pht\HashTable
  • Gets the size of the hash table

pht\HashTable::size

(PECL pht >= 0.0.1)

pht\HashTable::size — Gets the size of the hash table

Description

public pht\HashTable::size ( void ) : int

Returns the current size of the hash table. This operation requires a pht\HashTable's mutex lock to be held if it is being used by multiple threads.

Parameters

This function has no parameters.

Return Values

The size of the hash table.

Examples

Example #1 Getting a hash table's size

<?php

use pht\HashTable;

$hashTable = new HashTable();

$hashTable['a'] = 1;
$hashTable['b'] = 2;

var_dump($hashTable->size());

The above example will output:

int(2)


Releases the hash table's mutex lock

  • « pht\HashTable::size
  • pht\Vector »
  • PHP Manual
  • pht\HashTable
  • Releases the hash table's mutex lock

pht\HashTable::unlock

(PECL pht >= 0.0.1)

pht\HashTable::unlock — Releases the hash table's mutex lock

Description

public pht\HashTable::unlock ( void ) : void

This method will release the mutex lock associated with the hash table.

Parameters

This function has no parameters.

Return Values

No return value.

Examples

Example #1 Locking a hash table's mutex lock

<?php

use pht\{Thread, HashTable};

$thread = new Thread();
$hashTable = new HashTable();

$thread->addFunctionTask(function ($hashTable) {
    $hashTable->lock();
    $hashTable['a'] = 1;
    $hashTable->unlock();
}, $hashTable);

$thread->start();

// $hashTable is currently being used by multiple threads
$hashTable->lock();
$hashTable['b'] = 2;
$hashTable->unlock();

$thread->join();


The Vector class

(PECL pht >= 0.0.1)

Introduction

The pht\Vector class is one of the Inter-Thread Communication (ITC) data structures exposed by pht. It can be safely passed around between threads, and manipulated by multiple threads using the mutex locks that have been packed in with the data structure. It is reference-counted across threads, and so is does not need to be explicitly destroyed.

The pht\Vector class enables for array access upon its objects (along with the isset() and unset() functions). The ArrayAccess interface is not explicitly implemented, however, because it is only needed for such abilities by userland classes.

Class synopsis

pht\Vector implements pht\Threaded {
/* Methods */
public __construct ([ int $size = 0 [, mixed $value = 0 ]] ) : Vector
public deleteAt ( int $offset ) : void
public insertAt ( mixed $value , int $offset ) : void
public lock ( void ) : void
public pop ( void ) : mixed
public push ( mixed $value ) : void
public resize ( int $size [, mixed $value = 0 ] ) : void
public shift ( void ) : mixed
public size ( void ) : int
public unlock ( void ) : void
public unshift ( mixed $value ) : void
public updateAt ( mixed $value , int $offset ) : void
}

Table of Contents

  • pht\Vector::__construct — Vector creation
  • pht\Vector::deleteAt — Deletes a value in the vector
  • pht\Vector::insertAt — Inserts a value into the vector
  • pht\Vector::lock — Acquires the vector's mutex lock
  • pht\Vector::pop — Pops a value to the vector
  • pht\Vector::push — Pushes a value to the vector
  • pht\Vector::resize — Resizes a vector
  • pht\Vector::shift — Shifts a value from the vector
  • pht\Vector::size — Gets the size of the vector
  • pht\Vector::unlock — Releases the vector's mutex lock
  • pht\Vector::unshift — Unshifts a value to the vector front
  • pht\Vector::updateAt — Updates a value in the vector


Vector creation

  • « pht\Vector
  • pht\Vector::deleteAt »
  • PHP Manual
  • pht\Vector
  • Vector creation

pht\Vector::__construct

(PECL pht >= 0.0.1)

pht\Vector::__construct — Vector creation

Description

public pht\Vector::__construct ([ int $size = 0 [, mixed $value = 0 ]] ) : Vector

Handles the creation of a new vector.

Parameters

size

The size of the vector that will be created.

value

The value to initialise the empty slots in the vector to.

Return Values

No return value.

Examples

Example #1 Creating a new vector

<?php

use pht\Vector;

$vector1 = new Vector(1);
$vector2 = new Vector(2, 1);

var_dump($vector1, $vector2);

The above example will output:

object(pht\Vector)#1 (1) {
  [0]=>
  int(0)
}
object(pht\Vector)#2 (2) {
  [0]=>
  int(1)
  [1]=>
  int(1)
}


Deletes a value in the vector

  • « pht\Vector::__construct
  • pht\Vector::insertAt »
  • PHP Manual
  • pht\Vector
  • Deletes a value in the vector

pht\Vector::deleteAt

(PECL pht >= 0.0.1)

pht\Vector::deleteAt — Deletes a value in the vector

Description

public pht\Vector::deleteAt ( int $offset ) : void

This method deletes a value at the specified offset in the vector (in linear time).

Since the pht\Vector class supports array access, deleting values can also be performed using the array subset notation ([]) in combination with the unset() function.

Parameters

offset

The offset at which the value will be deleted at. This offset must be within the 0..(N-1) range (inclusive), where N is the size of the vector. Attempting to delete at offsets outside of this range will result in an Error exception.

Return Values

No return value.

Examples

Example #1 Deleting values in a vector

<?php

use pht\Vector;

$vector = new Vector();

$vector[] = 1;
$vector[] = 2;
$vector[] = 3;
$vector[] = 4;

$vector->deleteAt(1);
unset($vector[1]);

var_dump($vector);

The above example will output:

object(pht\Vector)#1 (2) {
  [0]=>
  int(1)
  [1]=>
  int(4)
}


Inserts a value into the vector

  • « pht\Vector::deleteAt
  • pht\Vector::lock »
  • PHP Manual
  • pht\Vector
  • Inserts a value into the vector

pht\Vector::insertAt

(PECL pht >= 0.0.1)

pht\Vector::insertAt — Inserts a value into the vector

Description

public pht\Vector::insertAt ( mixed $value , int $offset ) : void

This method inserts a value at the specified offset into the vector (in linear time). The vector will automatically be resized if it is not large enough.

Parameters

value

The value to be inserted into the vector. This value will be serialised (since it may be passed around between threads).

offset

The offset at which the value will be inserted at. This offset must be within the 0..N range (inclusive), where N is the size of the vector. Inserting at position N is the equivalent of using pht\Vector::push(), and inserting at position 0 is the equivalent of using pht\Vector::unshift(). Attempting to insert at offsets outside of this range will result in an Error exception.

Return Values

No return value.

Examples

Example #1 Inserting a value into a vector

<?php

use pht\Vector;

$vector = new Vector();

$vector->insertAt(3, 0); // insert 3 at start
$vector->insertAt(1, 0); // insert 1 at start (before 3)
$vector->insertAt(2, 1); // insert 2 in middle (after 1 and before 3)

var_dump($vector);

The above example will output:

object(pht\Vector)#1 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}


Acquires the vector's mutex lock

  • « pht\Vector::insertAt
  • pht\Vector::pop »
  • PHP Manual
  • pht\Vector
  • Acquires the vector's mutex lock

pht\Vector::lock

(PECL pht >= 0.0.1)

pht\Vector::lock — Acquires the vector's mutex lock

Description

public pht\Vector::lock ( void ) : void

This method will acquire the mutex lock associated with the vector. The mutex lock should always be acquired when manipulating the vector if it is being used by multiple threads.

The mutex locks of the Inter-Thread Communication (ITC) data structures are not reentrant. Attempting to reacquire an already-acquired mutex lock by the same thread will therefore cause a deadlock.

Parameters

This function has no parameters.

Return Values

No return value.

Examples

Example #1 Locking a vector's mutex lock

<?php

use pht\{Thread, Vector};

$thread = new Thread();
$vector = new Vector();

$thread->addFunctionTask(function ($vector) {
    $vector->lock();
    $vector[] = 1;
    $vector->unlock();
}, $vector);

$thread->start();

// $vector is currently being used by multiple threads
$vector->lock();
$vector[] = 2;
$vector->unlock();

$thread->join();


Pops a value to the vector

  • « pht\Vector::lock
  • pht\Vector::push »
  • PHP Manual
  • pht\Vector
  • Pops a value to the vector

pht\Vector::pop

(PECL pht >= 0.0.1)

pht\Vector::pop — Pops a value to the vector

Description

public pht\Vector::pop ( void ) : mixed

This method pops a value from the end of a vector (in constant time). Popping a value from an empty vector will result in an Error exception.

Parameters

This function has no parameters.

Return Values

The value from the end of the vector.

Examples

Example #1 Popping a value from a vector

<?php

use pht\Vector;

$vector = new Vector();

$vector->push(1);
$vector[] = 2;

var_dump($vector->pop());

The above example will output:

int(2)


Pushes a value to the vector

  • « pht\Vector::pop
  • pht\Vector::resize »
  • PHP Manual
  • pht\Vector
  • Pushes a value to the vector

pht\Vector::push

(PECL pht >= 0.0.1)

pht\Vector::push — Pushes a value to the vector

Description

public pht\Vector::push ( mixed $value ) : void

This method pushes a value onto the end of a vector (in constant time). The vector will automatically be resized if it is not large enough.

Since the pht\Vector class supports array access, new values can also be pushed onto the vector using the empty subset notation ([]).

Parameters

value

The value to be pushed onto the end of the vector. This value will be serialised (since it may be passed around between threads).

Return Values

No return value.

Examples

Example #1 Pushing values to a vector

<?php

use pht\Vector;

$vector = new Vector();

$vector->push(1);
$vector[] = 2;

var_dump($vector);

The above example will output:

object(pht\Vector)#1 (2) {
  [0]=>
  int(1)
  [1]=>
  int(2)
}


Resizes a vector

  • « pht\Vector::push
  • pht\Vector::shift »
  • PHP Manual
  • pht\Vector
  • Resizes a vector

pht\Vector::resize

(PECL pht >= 0.0.1)

pht\Vector::resize — Resizes a vector

Description

public pht\Vector::resize ( int $size [, mixed $value = 0 ] ) : void

Resizes the vector. If it is enlarged, then the value parameter will be used to fill in the new slots. If it is made smaller, then the end values will be truncated.

Parameters

size

The new size of the vector.

value

The value to initialise the empty vector slots to (only used if the vector is enlarged).

Return Values

No return value.

Examples

Example #1 Resizing a vector

<?php

use pht\Vector;

$vector = new Vector(1);
var_dump($vector);
$vector->resize(2, 1);
var_dump($vector);
$vector->resize(1, 2); // unused second arg
var_dump($vector);

The above example will output:

object(pht\Vector)#1 (1) {
  [0]=>
  int(0)
}
object(pht\Vector)#1 (2) {
  [0]=>
  int(0)
  [1]=>
  int(1)
}
object(pht\Vector)#1 (1) {
  [0]=>
  int(0)
}


Shifts a value from the vector

  • « pht\Vector::resize
  • pht\Vector::size »
  • PHP Manual
  • pht\Vector
  • Shifts a value from the vector

pht\Vector::shift

(PECL pht >= 0.0.1)

pht\Vector::shift — Shifts a value from the vector

Description

public pht\Vector::shift ( void ) : mixed

This method shifts a value from the front of a vector (in linear time). Shifting a value from an empty vector will result in an Error exception.

Parameters

This function has no parameters.

Return Values

The value from the front of the vector.

Examples

Example #1 Shifting a value from a vector

<?php

use pht\Vector;

$vector = new Vector();

$vector->push(1);
$vector[] = 2;

var_dump($vector->shift());

The above example will output:

int(1)


Gets the size of the vector

  • « pht\Vector::shift
  • pht\Vector::unlock »
  • PHP Manual
  • pht\Vector
  • Gets the size of the vector

pht\Vector::size

(PECL pht >= 0.0.1)

pht\Vector::size — Gets the size of the vector

Description

public pht\Vector::size ( void ) : int

Returns the current size of the vector. This operation requires a pht\Vector's mutex lock to be held if it is being used by multiple threads.

Parameters

This function has no parameters.

Return Values

The size of the vector.

Examples

Example #1 Getting a vector's size

<?php

use pht\Vector;

$vector = new Vector();

$vector[] = 1;
$vector[] = 2;
$vector[] = 3;

var_dump($vector->size());

The above example will output:

int(3)


Releases the vector's mutex lock

  • « pht\Vector::size
  • pht\Vector::unshift »
  • PHP Manual
  • pht\Vector
  • Releases the vector's mutex lock

pht\Vector::unlock

(PECL pht >= 0.0.1)

pht\Vector::unlock — Releases the vector's mutex lock

Description

public pht\Vector::unlock ( void ) : void

This method will release the mutex lock associated with the vector.

Parameters

This function has no parameters.

Return Values

No return value.

Examples

Example #1 Locking a vector's mutex lock

<?php

use pht\{Thread, Vector};

$thread = new Thread();
$vector = new Vector();

$thread->addFunctionTask(function ($vector) {
    $vector->lock();
    $vector[] = 1;
    $vector->unlock();
}, $vector);

$thread->start();

// $vector is currently being used by multiple threads
$vector->lock();
$vector[] = 2;
$vector->unlock();

$thread->join();


Unshifts a value to the vector front

  • « pht\Vector::unlock
  • pht\Vector::updateAt »
  • PHP Manual
  • pht\Vector
  • Unshifts a value to the vector front

pht\Vector::unshift

(PECL pht >= 0.0.1)

pht\Vector::unshift — Unshifts a value to the vector front

Description

public pht\Vector::unshift ( mixed $value ) : void

This method unshifts a value to the front of a vector (in linear time). The vector will automatically be resized if it is not large enough.

Parameters

value

The value to be pushed onto the beginning of the vector. This value will be serialised (since it may be passed around between threads).

Return Values

No return value.

Examples

Example #1 Unshifting a value to the front of a vector

<?php

use pht\Vector;

$vector = new Vector();

for ($i = 0; $i < 3; ++$i) {
    $vector->unshift($i); // causes a quadratic runtime, beware
}

var_dump($vector);

The above example will output:

object(pht\Vector)#1 (3) {
  [0]=>
  int(2)
  [1]=>
  int(1)
  [2]=>
  int(0)
}


Updates a value in the vector

  • « pht\Vector::unshift
  • pht\Queue »
  • PHP Manual
  • pht\Vector
  • Updates a value in the vector

pht\Vector::updateAt

(PECL pht >= 0.0.1)

pht\Vector::updateAt — Updates a value in the vector

Description

public pht\Vector::updateAt ( mixed $value , int $offset ) : void

This method updates a value at the specified offset in the vector (in linear time). The vector will automatically be resized if it is not large enough.

Since the pht\Vector class supports array access, updating values can also be performed using the array subset notation ([]).

Parameters

value

The value to be inserted into the vector. This value will be serialised (since it may be passed around between threads).

offset

The offset at which the value will be updated at. This offset must be within the 0..(N-1) range (inclusive), where N is the size of the vector. Attempting to update at offsets outside of this range will result in an Error exception.

Return Values

No return value.

Examples

Example #1 Updating a value in a vector

<?php

use pht\Vector;

$vector = new Vector();

$vector[] = 1;
$vector[] = 2;

$vector->updateAt(3, 0);
$vector[1] = 4;

var_dump($vector);

The above example will output:

object(pht\Vector)#1 (2) {
  [0]=>
  int(3)
  [1]=>
  int(4)
}


The Queue class

(PECL pht >= 0.0.1)

Introduction

The pht\Queue class is one of the Inter-Thread Communication (ITC) data structures exposed by pht. It can be safely passed around between threads, and manipulated by multiple threads using the mutex locks that have been packed in with the data structure. It is reference-counted across threads, and so it does not need to be explicitly destroyed.

Class synopsis

pht\Queue implements pht\Threaded {
/* Methods */
public front ( void ) : mixed
public lock ( void ) : void
public pop ( void ) : mixed
public push ( mixed $value ) : void
public size ( void ) : int
public unlock ( void ) : void
}

Table of Contents

  • pht\Queue::front — Returns the first value from a queue
  • pht\Queue::lock — Acquires the queue's mutex lock
  • pht\Queue::pop — Pops a value off of the front of a queue
  • pht\Queue::push — Pushes a value to the end of a queue
  • pht\Queue::size — Gets the size of the queue
  • pht\Queue::unlock — Releases the queue's mutex lock


Returns the first value from a queue

  • « pht\Queue
  • pht\Queue::lock »
  • PHP Manual
  • pht\Queue
  • Returns the first value from a queue

pht\Queue::front

(PECL pht >= 0.0.1)

pht\Queue::front — Returns the first value from a queue

Description

public pht\Queue::front ( void ) : mixed

This method will remove a value from the front of the queue (in constant time). Attempting to return the front value from an empty queue will result in an Error exception.

Caution

Due to the fact that all values in a pht\Queue are serialised, extracting a value from the queue will require it to be deserialised. This can incur a noticeable performance hit if the inspection of the queue's front value is performed within a loop.

Parameters

This function has no parameters.

Return Values

The value on the front of the queue.

Examples

Example #1 Retrieving the front value of a queue

<?php

use pht\Queue;

$queue = new Queue();

$queue->push(1);

var_dump($queue->front());

The above example will output:

int(1)

Example #2 Retrieving the front value in a loop (bad example - don't do this)

<?php

use pht\Queue;

$queue = new Queue();

$queue->push(array_fill(0, 2000, 0));

for ($i = 0; $i < count($queue->front()); ++$i); // quadratic runtime

Example #3 Retrieving the front value in a loop (good example)

<?php

use pht\Queue;

$queue = new Queue();

$queue->push(array_fill(0, 2000, 0));

$front = $queue->front(); // create a separate variable
for ($i = 0; $i < count($front); ++$i); // linear runtime


Acquires the queue's mutex lock

  • « pht\Queue::front
  • pht\Queue::pop »
  • PHP Manual
  • pht\Queue
  • Acquires the queue's mutex lock

pht\Queue::lock

(PECL pht >= 0.0.1)

pht\Queue::lock — Acquires the queue's mutex lock

Description

public pht\Queue::lock ( void ) : void

This method will acquire the mutex lock associated with the queue. The mutex lock should always be acquired when manipulating the queue if it is being used by multiple threads.

The mutex locks of the Inter-Thread Communication (ITC) data structures are not reentrant. Attempting to reacquire an already-acquired mutex lock by the same thread will therefore cause a deadlock.

Parameters

This function has no parameters.

Return Values

No return value.

Examples

Example #1 Locking a queue's mutex lock

<?php

use pht\{Thread, Queue};

$thread = new Thread();
$queue = new Queue();

$thread->addFunctionTask(function ($queue) {
    $queue->lock();
    $queue->push(1);
    $queue->unlock();
}, $queue);

$thread->start();

// $queue is currently being used by multiple threads
$queue->lock();
$queue->push(1);
$queue->unlock();

$thread->join();

// $queue is only being used in this thread now, so no need to lock it
while ($queue->size()) {
    var_dump($queue->pop());
}

The above example will output:

int(1)
int(1)


Pops a value off of the front of a queue

  • « pht\Queue::lock
  • pht\Queue::push »
  • PHP Manual
  • pht\Queue
  • Pops a value off of the front of a queue

pht\Queue::pop

(PECL pht >= 0.0.1)

pht\Queue::pop — Pops a value off of the front of a queue

Description

public pht\Queue::pop ( void ) : mixed

This method will remove a value from the front of the queue (in constant time). Attempting to pop a value from an empty queue will result in an Error exception.

Parameters

This function has no parameters.

Return Values

The value removed from the queue.

Examples

Example #1 Popping a value from a queue

<?php

use pht\Queue;

$queue = new Queue();

$queue->push(1);

var_dump($queue->pop());

The above example will output:

int(1)


Pushes a value to the end of a queue

  • « pht\Queue::pop
  • pht\Queue::size »
  • PHP Manual
  • pht\Queue
  • Pushes a value to the end of a queue

pht\Queue::push

(PECL pht >= 0.0.1)

pht\Queue::push — Pushes a value to the end of a queue

Description

public pht\Queue::push ( mixed $value ) : void

This method will add a value onto the queue.

Parameters

value

The value to be added to a pht\Queue. This value will be serialised (since it may be passed around between threads).

Return Values

No return value.

Examples

Example #1 Pushing a value to a queue

<?php

use pht\Queue;

$queue = new Queue();

$queue->push(1);

var_dump($queue);

The above example will output:

object(pht\Queue)#1 (1) {
  [0]=>
  int(1)
}


Gets the size of the queue

  • « pht\Queue::push
  • pht\Queue::unlock »
  • PHP Manual
  • pht\Queue
  • Gets the size of the queue

pht\Queue::size

(PECL pht >= 0.0.1)

pht\Queue::size — Gets the size of the queue

Description

public pht\Queue::size ( void ) : int

Returns the current size of the queue. This operation requires a pht\Queue's mutex lock to be held if it is being used by multiple threads.

Parameters

This function has no parameters.

Return Values

The size of the queue.

Examples

Example #1 Getting a queue's size

<?php

use pht\Queue;

$queue = new Queue();

$queue->push(1);
$queue->push(1);

var_dump($queue->size());

The above example will output:

int(2)


Releases the queue's mutex lock

  • « pht\Queue::size
  • pht\AtomicInteger »
  • PHP Manual
  • pht\Queue
  • Releases the queue's mutex lock

pht\Queue::unlock

(PECL pht >= 0.0.1)

pht\Queue::unlock — Releases the queue's mutex lock

Description

public pht\Queue::unlock ( void ) : void

This method will release the mutex lock associated with the queue.

Parameters

This function has no parameters.

Return Values

No return value.

Examples

Example #1 Locking a queue's mutex lock

<?php

use pht\{Thread, Queue};

$thread = new Thread();
$queue = new Queue();

$thread->addFunctionTask(function ($queue) {
    $queue->lock();
    $queue->push(1);
    $queue->unlock();
}, $queue);

$thread->start();

// $queue is currently being used by multiple threads
$queue->lock();
$queue->push(1);
$queue->unlock();

$thread->join();

// $queue is only being used in this thread now, so no need to lock it
while ($queue->size()) {
    var_dump($queue->pop());
}

The above example will output:

int(1)
int(1)


The AtomicInteger class

(PECL pht >= 0.0.1)

Introduction

The pht\AtomicInteger class is currently the only supported atomic value. It allows for an integer to be safely passed around between, and manipulated, by multiple threads. The methods exposed by this class do not need mutex locking, since they will acquire the internal mutex lock implicitly. pht\AtomicInteger::lock() and pht\AtomicInteger::unlock() are still exposed, however, for when multiple operations involving the same pht\AtomicInteger object need to be grouped together.

The mutex locks of the atomic values are reentrant safe.

Class synopsis

pht\AtomicInteger implements pht\Threaded {
/* Methods */
public __construct ([ int $value = 0 ] ) : AtomicInteger
public dec ( void ) : void
public get ( void ) : int
public inc ( void ) : void
public lock ( void ) : void
public set ( int $value ) : void
public unlock ( void ) : void
}

Table of Contents

  • pht\AtomicInteger::__construct — AtomicInteger creation
  • pht\AtomicInteger::dec — Decrements the atomic integer's value by one
  • pht\AtomicInteger::get — Gets the atomic integer's value
  • pht\AtomicInteger::inc — Increments the atomic integer's value by one
  • pht\AtomicInteger::lock — Acquires the atomic integer's mutex lock
  • pht\AtomicInteger::set — Sets the atomic integer's value
  • pht\AtomicInteger::unlock — Releases the atomic integer's mutex lock


AtomicInteger creation

  • « pht\AtomicInteger
  • pht\AtomicInteger::dec »
  • PHP Manual
  • pht\AtomicInteger
  • AtomicInteger creation

pht\AtomicInteger::__construct

(PECL pht >= 0.0.1)

pht\AtomicInteger::__construct — AtomicInteger creation

Description

public pht\AtomicInteger::__construct ([ int $value = 0 ] ) : AtomicInteger

Handles the creation of a new atomic integer.

Parameters

value

The value to initialise the atomic integer to.

Return Values

No return value.

Examples

Example #1 Creating a new atomic integer

<?php

use pht\AtomicInteger;

$atomicInteger = new AtomicInteger(100);

var_dump($atomicInteger->get());

The above example will output:

int(100)


Decrements the atomic integer's value by one

  • « pht\AtomicInteger::__construct
  • pht\AtomicInteger::get »
  • PHP Manual
  • pht\AtomicInteger
  • Decrements the atomic integer's value by one

pht\AtomicInteger::dec

(PECL pht >= 0.0.1)

pht\AtomicInteger::dec — Decrements the atomic integer's value by one

Description

public pht\AtomicInteger::dec ( void ) : void

This method will decrement the atomic integer's value by one. Internally, the mutex lock of the atomic integer will be acquired, and so there is no need to manually acquire it (unless this operation needs to be grouped with other operations on the same atomic integer - see the example in pht\AtomicInteger::lock() for a demonstration of this).

Parameters

This function has no parameters.

Return Values

No return value.

Examples

Example #1 Decrementing an atomic integer's value

<?php

use pht\AtomicInteger;

$atomicInteger = new AtomicInteger();

$atomicInteger->dec();
$atomicInteger->dec();

var_dump($atomicInteger->get());

The above example will output:

int(-2)


Gets the atomic integer's value

  • « pht\AtomicInteger::dec
  • pht\AtomicInteger::inc »
  • PHP Manual
  • pht\AtomicInteger
  • Gets the atomic integer's value

pht\AtomicInteger::get

(PECL pht >= 0.0.1)

pht\AtomicInteger::get — Gets the atomic integer's value

Description

public pht\AtomicInteger::get ( void ) : int

This method will fetch the current value of the atomic integer. Internally, the mutex lock of the atomic integer will be acquired, and so there is no need to manually acquire it (unless this operation needs to be grouped with other operations on the same atomic integer - see the example in pht\AtomicInteger::lock() for a demonstration of this).

Parameters

This function has no parameters.

Return Values

The current integer value of the atomic integer.

Examples

Example #1 Getting an atomic integer's value

<?php

use pht\AtomicInteger;

$atomicInteger = new AtomicInteger(2);

var_dump($atomicInteger->get());

The above example will output:

int(2)


Increments the atomic integer's value by one

  • « pht\AtomicInteger::get
  • pht\AtomicInteger::lock »
  • PHP Manual
  • pht\AtomicInteger
  • Increments the atomic integer's value by one

pht\AtomicInteger::inc

(PECL pht >= 0.0.1)

pht\AtomicInteger::inc — Increments the atomic integer's value by one

Description

public pht\AtomicInteger::inc ( void ) : void

This method will increment the atomic integer's value by one. Internally, the mutex lock of the atomic integer will be acquired, and so there is no need to manually acquire it (unless this operation needs to be grouped with other operations on the same atomic integer - see the example in pht\AtomicInteger::lock() for a demonstration of this).

Parameters

This function has no parameters.

Return Values

No return value.

Examples

Example #1 Incrementing an atomic integer's value

<?php

use pht\AtomicInteger;

$atomicInteger = new AtomicInteger();

$atomicInteger->inc();
$atomicInteger->inc();

var_dump($atomicInteger->get());

The above example will output:

int(2)


Acquires the atomic integer's mutex lock

  • « pht\AtomicInteger::inc
  • pht\AtomicInteger::set »
  • PHP Manual
  • pht\AtomicInteger
  • Acquires the atomic integer's mutex lock

pht\AtomicInteger::lock

(PECL pht >= 0.0.1)

pht\AtomicInteger::lock — Acquires the atomic integer's mutex lock

Description

public pht\AtomicInteger::lock ( void ) : void

This method will acquire the mutex lock associated with the atomic integer. The mutex lock only needs to be acquired when needing to group together multiple operations.

The mutex locks of the atomic values are reentrant safe. It is therefore valid for the same thread to reacquire a mutex lock that it has already acquired.

Parameters

This function has no parameters.

Return Values

No return value.

Examples

Example #1 Grouping together an atomic integer's operations (requiring a mutex lock)

<?php

use pht\AtomicInteger;

$atomicInteger = new AtomicInteger(2);

// assumes $atomicInteger is being used by multiple threads
$atomicInteger->lock();
$atomicInteger->set($atomicInteger->get() * 2); // double the value
$atomicInteger->unlock();

var_dump($atomicInteger->get());

The above example will output:

int(4)


Sets the atomic integer's value

  • « pht\AtomicInteger::lock
  • pht\AtomicInteger::unlock »
  • PHP Manual
  • pht\AtomicInteger
  • Sets the atomic integer's value

pht\AtomicInteger::set

(PECL pht >= 0.0.1)

pht\AtomicInteger::set — Sets the atomic integer's value

Description

public pht\AtomicInteger::set ( int $value ) : void

This method will set the value of the atomic integer. Internally, the mutex lock of the atomic integer will be acquired, and so there is no need to manually acquire it (unless this operation needs to be grouped with other operations on the same atomic integer - see the example in pht\AtomicInteger::lock() for a demonstration of this).

Parameters

value

The value to set the atomic integer to.

Return Values

No return value.

Examples

Example #1 Setting an atomic integer's value

<?php

use pht\AtomicInteger;

$atomicInteger = new AtomicInteger();

$atomicInteger->set(20);

var_dump($atomicInteger->get());

The above example will output:

int(20)


Releases the atomic integer's mutex lock

  • « pht\AtomicInteger::set
  • pht\Threaded »
  • PHP Manual
  • pht\AtomicInteger
  • Releases the atomic integer's mutex lock

pht\AtomicInteger::unlock

(PECL pht >= 0.0.1)

pht\AtomicInteger::unlock — Releases the atomic integer's mutex lock

Description

public pht\AtomicInteger::unlock ( void ) : void

This method will release the mutex lock associated with the atomic integer.

Parameters

This function has no parameters.

Return Values

No return value.

Examples

Example #1 Grouping together an atomic integer's operations (requiring a mutex lock)

<?php

use pht\AtomicInteger;

$atomicInteger = new AtomicInteger(2);

// assumes $atomicInteger is being used by multiple threads
$atomicInteger->lock();
$atomicInteger->set($atomicInteger->get() * 2); // double the value
$atomicInteger->unlock();

var_dump($atomicInteger->get());

The above example will output:

int(4)


The Threaded interface

(PECL pht >= 0.0.1)

Introduction

The pht\Threaded interface is an internal interface used by the Inter-Thread Communication (ITC) data structures (pht\HashTable, pht\Queue, and pht\Vector). It allows those data structures to be threaded and ensures that the mutex locking API (pht\Threaded::lock() and pht\Threaded::unlock()) is implemented by each of the ITC data structures. It is not implementable by userland classes (since standalone mutex locks are not exposed).

Interface synopsis

pht\Threaded {
/* Methods */
public lock ( void ) : void
public unlock ( void ) : void
}

Table of Contents

  • pht\Threaded::lock — Acquires the mutex lock
  • pht\Threaded::unlock — Releases the mutex lock


Acquires the mutex lock

  • « pht\Threaded
  • pht\Threaded::unlock »
  • PHP Manual
  • pht\Threaded
  • Acquires the mutex lock

pht\Threaded::lock

(PECL pht >= 0.0.1)

pht\Threaded::lock — Acquires the mutex lock

Description

public pht\Threaded::lock ( void ) : void

This method will acquire the mutex lock associated with the given class (either a pht\HashTable, pht\Queue, pht\Vector, or pht\AtomicInteger).

Parameters

This function has no parameters.

Return Values

No return value.


Releases the mutex lock

  • « pht\Threaded::lock
  • Semaphore »
  • PHP Manual
  • pht\Threaded
  • Releases the mutex lock

pht\Threaded::unlock

(PECL pht >= 0.0.1)

pht\Threaded::unlock — Releases the mutex lock

Description

public pht\Threaded::unlock ( void ) : void

This method will unlock the mutex lock associated with the given class (either a pht\HashTable, pht\Queue, pht\Vector, or pht\AtomicInteger).

Parameters

This function has no parameters.

Return Values

No return value.


Semaphore, Shared Memory and IPC

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Semaphore Functions
    • ftok — Convert a pathname and a project identifier to a System V IPC key
    • msg_get_queue — Create or attach to a message queue
    • msg_queue_exists — Check whether a message queue exists
    • msg_receive — Receive a message from a message queue
    • msg_remove_queue — Destroy a message queue
    • msg_send — Send a message to a message queue
    • msg_set_queue — Set information in the message queue data structure
    • msg_stat_queue — Returns information from the message queue data structure
    • sem_acquire — Acquire a semaphore
    • sem_get — Get a semaphore id
    • sem_release — Release a semaphore
    • sem_remove — Remove a semaphore
    • shm_attach — Creates or open a shared memory segment
    • shm_detach — Disconnects from shared memory segment
    • shm_get_var — Returns a variable from shared memory
    • shm_has_var — Check whether a specific entry exists
    • shm_put_var — Inserts or updates a variable in shared memory
    • shm_remove_var — Removes a variable from shared memory
    • shm_remove — Removes shared memory from Unix systems


Introduction

This module provides wrappers for the System V IPC family of functions. It includes semaphores, shared memory and inter-process messaging (IPC).

Semaphores may be used to provide exclusive access to resources on the current machine, or to limit the number of processes that may simultaneously use a resource.

This module provides also shared memory functions using System V shared memory. Shared memory may be used to provide access to global variables. Different httpd-daemons and even other programs (such as Perl, C, ...) are able to access this data to provide a global data-exchange. Remember, that shared memory is NOT safe against simultaneous access. Use semaphores for synchronization.

Limits of Shared Memory by the Unix OS
SHMMAX | max size of shared memory, normally 131072 bytes
SHMMIN | minimum size of shared memory, normally 1 byte
SHMMNI | max amount of shared memory segments on a system, normally 100
SHMSEG | max amount of shared memory segments per process, normally 6

The messaging functions may be used to send and receive messages to/from other processes. They provide a simple and effective means of exchanging data between processes, without the need for setting up an alternative using Unix domain sockets.

Note: This extension is not available on Windows platforms.


Installation

Support for this functions are not enabled by default. To enable System V semaphore support compile PHP with the option --enable-sysvsem . To enable the System V shared memory support compile PHP with the option --enable-sysvshm . To enable the System V messages support compile PHP with the option --enable-sysvmsg .


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Semaphore Configuration Options
Name | Default | Changeable | Changelog
sysvshm.init_mem | 10000 | PHP_INI_SYSTEM |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

sysvshm.init_mem int

A default size of the shared memory segment.


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.

System V message constants
Constant | Type | Changelog
MSG_IPC_NOWAIT | integer |
MSG_EAGAIN | integer | As of 5.2.0
MSG_ENOMSG | integer | As of 5.2.0
MSG_NOERROR | integer |
MSG_EXCEPT | integer |


Semaphore Functions

Table of Contents

  • ftok — Convert a pathname and a project identifier to a System V IPC key
  • msg_get_queue — Create or attach to a message queue
  • msg_queue_exists — Check whether a message queue exists
  • msg_receive — Receive a message from a message queue
  • msg_remove_queue — Destroy a message queue
  • msg_send — Send a message to a message queue
  • msg_set_queue — Set information in the message queue data structure
  • msg_stat_queue — Returns information from the message queue data structure
  • sem_acquire — Acquire a semaphore
  • sem_get — Get a semaphore id
  • sem_release — Release a semaphore
  • sem_remove — Remove a semaphore
  • shm_attach — Creates or open a shared memory segment
  • shm_detach — Disconnects from shared memory segment
  • shm_get_var — Returns a variable from shared memory
  • shm_has_var — Check whether a specific entry exists
  • shm_put_var — Inserts or updates a variable in shared memory
  • shm_remove_var — Removes a variable from shared memory
  • shm_remove — Removes shared memory from Unix systems


Convert a pathname and a project identifier to a System V IPC key

  • « Semaphore Functions
  • msg_get_queue »
  • PHP Manual
  • Semaphore Functions
  • Convert a pathname and a project identifier to a System V IPC key

ftok

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

ftok — Convert a pathname and a project identifier to a System V IPC key

Description

ftok ( string $pathname , string $proj ) : int

The function converts the pathname of an existing accessible file and a project identifier into an integer for use with for example shmop_open() and other System V IPC keys.

Parameters

pathname

Path to an accessible file.

proj

Project identifier. This must be a one character string.

Return Values

On success the return value will be the created key value, otherwise -1 is returned.

See Also

  • shmop_open() - Create or open shared memory block
  • sem_get() - Get a semaphore id


Create or attach to a message queue

  • « ftok
  • msg_queue_exists »
  • PHP Manual
  • Semaphore Functions
  • Create or attach to a message queue

msg_get_queue

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

msg_get_queue — Create or attach to a message queue

Description

msg_get_queue ( int $key [, int $perms = 0666 ] ) : resource

msg_get_queue() returns an id that can be used to access the System V message queue with the given key. The first call creates the message queue with the optional perms. A second call to msg_get_queue() for the same key will return a different message queue identifier, but both identifiers access the same underlying message queue.

Parameters

key

Message queue numeric ID

perms

Queue permissions. Default to 0666. If the message queue already exists, the perms will be ignored.

Return Values

Returns a resource handle that can be used to access the System V message queue.

See Also

  • msg_remove_queue() - Destroy a message queue
  • msg_receive() - Receive a message from a message queue
  • msg_send() - Send a message to a message queue
  • msg_stat_queue() - Returns information from the message queue data structure
  • msg_set_queue() - Set information in the message queue data structure


Check whether a message queue exists

  • « msg_get_queue
  • msg_receive »
  • PHP Manual
  • Semaphore Functions
  • Check whether a message queue exists

msg_queue_exists

(PHP 5 >= 5.3.0, PHP 7)

msg_queue_exists — Check whether a message queue exists

Description

msg_queue_exists ( int $key ) : bool

Checks whether the message queue key exists.

Parameters

key

Queue key.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • msg_remove_queue() - Destroy a message queue
  • msg_receive() - Receive a message from a message queue
  • msg_stat_queue() - Returns information from the message queue data structure


Receive a message from a message queue

  • « msg_queue_exists
  • msg_remove_queue »
  • PHP Manual
  • Semaphore Functions
  • Receive a message from a message queue

msg_receive

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

msg_receive — Receive a message from a message queue

Description

msg_receive ( resource $queue , int $desiredmsgtype , int &$msgtype , int $maxsize , mixed &$message [, bool $unserialize = TRUE [, int $flags = 0 [, int &$errorcode ]]] ) : bool

msg_receive() will receive the first message from the specified queue of the type specified by desiredmsgtype.

Parameters

queue

Message queue resource handle

desiredmsgtype

If desiredmsgtype is 0, the message from the front of the queue is returned. If desiredmsgtype is greater than 0, then the first message of that type is returned. If desiredmsgtype is less than 0, the first message on the queue with a type less than or equal to the absolute value of desiredmsgtype will be read. If no messages match the criteria, your script will wait until a suitable message arrives on the queue. You can prevent the script from blocking by specifying MSG_IPC_NOWAIT in the flags parameter.

msgtype

The type of the message that was received will be stored in this parameter.

maxsize

The maximum size of message to be accepted is specified by the maxsize; if the message in the queue is larger than this size the function will fail (unless you set flags as described below).

message

The received message will be stored in message, unless there were errors receiving the message.

unserialize

If set to TRUE, the message is treated as though it was serialized using the same mechanism as the session module. The message will be unserialized and then returned to your script. This allows you to easily receive arrays or complex object structures from other PHP scripts, or if you are using the WDDX serializer, from any WDDX compatible source.

If unserialize is FALSE, the message will be returned as a binary-safe string.

flags

The optional flags allows you to pass flags to the low-level msgrcv system call. It defaults to 0, but you may specify one or more of the following values (by adding or ORing them together).

Flag values for msg_receive
MSG_IPC_NOWAIT | If there are no messages of the desiredmsgtype, return immediately and do not wait. The function will fail and return an integer value corresponding to MSG_ENOMSG.
MSG_EXCEPT | Using this flag in combination with a desiredmsgtype greater than 0 will cause the function to receive the first message that is not equal to desiredmsgtype.
MSG_NOERROR | If the message is longer than maxsize, setting this flag will truncate the message to maxsize and will not signal an error.

errorcode

If the function fails, the optional errorcode will be set to the value of the system errno variable.

Return Values

Returns TRUE on success or FALSE on failure.

Upon successful completion the message queue data structure is updated as follows: msg_lrpid is set to the process-ID of the calling process, msg_qnum is decremented by 1 and msg_rtime is set to the current time.

See Also

  • msg_remove_queue() - Destroy a message queue
  • msg_send() - Send a message to a message queue
  • msg_stat_queue() - Returns information from the message queue data structure
  • msg_set_queue() - Set information in the message queue data structure


Destroy a message queue

  • « msg_receive
  • msg_send »
  • PHP Manual
  • Semaphore Functions
  • Destroy a message queue

msg_remove_queue

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

msg_remove_queue — Destroy a message queue

Description

msg_remove_queue ( resource $queue ) : bool

msg_remove_queue() destroys the message queue specified by the queue. Only use this function when all processes have finished working with the message queue and you need to release the system resources held by it.

Parameters

queue

Message queue resource handle

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • msg_get_queue() - Create or attach to a message queue
  • msg_receive() - Receive a message from a message queue
  • msg_stat_queue() - Returns information from the message queue data structure
  • msg_set_queue() - Set information in the message queue data structure


Send a message to a message queue

  • « msg_remove_queue
  • msg_set_queue »
  • PHP Manual
  • Semaphore Functions
  • Send a message to a message queue

msg_send

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

msg_send — Send a message to a message queue

Description

msg_send ( resource $queue , int $msgtype , mixed $message [, bool $serialize = TRUE [, bool $blocking = TRUE [, int &$errorcode ]]] ) : bool

msg_send() sends a message of type msgtype (which MUST be greater than 0) to the message queue specified by queue.

Parameters

queue

Message queue resource handle

msgtype

The type of the message (MUST be greater than 0)

message

The body of the message.

Note:

If serialize set to FALSE is supplied, MUST be of type: string, integer, float or bool. In other case a warning will be issued.

serialize

The optional serialize controls how the message is sent. serialize defaults to TRUE which means that the message is serialized using the same mechanism as the session module before being sent to the queue. This allows complex arrays and objects to be sent to other PHP scripts, or if you are using the WDDX serializer, to any WDDX compatible client.

blocking

If the message is too large to fit in the queue, your script will wait until another process reads messages from the queue and frees enough space for your message to be sent. This is called blocking; you can prevent blocking by setting the optional blocking parameter to FALSE, in which case msg_send() will immediately return FALSE if the message is too big for the queue, and set the optional errorcode to MSG_EAGAIN, indicating that you should try to send your message again a little later on.

errorcode

If the function fails, the optional errorcode will be set to the value of the system errno variable.

Return Values

Returns TRUE on success or FALSE on failure.

Upon successful completion the message queue data structure is updated as follows: msg_lspid is set to the process-ID of the calling process, msg_qnum is incremented by 1 and msg_stime is set to the current time.

See Also

  • msg_remove_queue() - Destroy a message queue
  • msg_receive() - Receive a message from a message queue
  • msg_stat_queue() - Returns information from the message queue data structure
  • msg_set_queue() - Set information in the message queue data structure


Set information in the message queue data structure

  • « msg_send
  • msg_stat_queue »
  • PHP Manual
  • Semaphore Functions
  • Set information in the message queue data structure

msg_set_queue

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

msg_set_queue — Set information in the message queue data structure

Description

msg_set_queue ( resource $queue , array $data ) : bool

msg_set_queue() allows you to change the values of the msg_perm.uid, msg_perm.gid, msg_perm.mode and msg_qbytes fields of the underlying message queue data structure.

Changing the data structure will require that PHP be running as the same user that created the queue, owns the queue (as determined by the existing msg_perm.xxx fields), or be running with root privileges. root privileges are required to raise the msg_qbytes values above the system defined limit.

Parameters

queue

Message queue resource handle

data

You specify the values you require by setting the value of the keys that you require in the data array.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • msg_remove_queue() - Destroy a message queue
  • msg_receive() - Receive a message from a message queue
  • msg_stat_queue() - Returns information from the message queue data structure
  • msg_get_queue() - Create or attach to a message queue


Returns information from the message queue data structure

  • « msg_set_queue
  • sem_acquire »
  • PHP Manual
  • Semaphore Functions
  • Returns information from the message queue data structure

msg_stat_queue

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

msg_stat_queue — Returns information from the message queue data structure

Description

msg_stat_queue ( resource $queue ) : array

msg_stat_queue() returns the message queue meta data for the message queue specified by the queue. This is useful, for example, to determine which process sent the message that was just received.

Parameters

queue

Message queue resource handle

Return Values

The return value is an array whose keys and values have the following meanings:

Array structure for msg_stat_queue
msg_perm.uid | The uid of the owner of the queue.
msg_perm.gid | The gid of the owner of the queue.
msg_perm.mode | The file access mode of the queue.
msg_stime | The time that the last message was sent to the queue.
msg_rtime | The time that the last message was received from the queue.
msg_ctime | The time that the queue was last changed.
msg_qnum | The number of messages waiting to be read from the queue.
msg_qbytes | The maximum number of bytes allowed in one message queue. On Linux, this value may be read and modified via /proc/sys/kernel/msgmnb.
msg_lspid | The pid of the process that sent the last message to the queue.
msg_lrpid | The pid of the process that received the last message from the queue.

See Also

  • msg_remove_queue() - Destroy a message queue
  • msg_receive() - Receive a message from a message queue
  • msg_get_queue() - Create or attach to a message queue
  • msg_set_queue() - Set information in the message queue data structure


Acquire a semaphore

  • « msg_stat_queue
  • sem_get »
  • PHP Manual
  • Semaphore Functions
  • Acquire a semaphore

sem_acquire

(PHP 4, PHP 5, PHP 7)

sem_acquire — Acquire a semaphore

Description

sem_acquire ( resource $sem_identifier [, bool $nowait = FALSE ] ) : bool

sem_acquire() by default blocks (if necessary) until the semaphore can be acquired. A process attempting to acquire a semaphore which it has already acquired will block forever if acquiring the semaphore would cause its maximum number of semaphore to be exceeded.

After processing a request, any semaphores acquired by the process but not explicitly released will be released automatically and a warning will be generated.

Parameters

sem_identifier

sem_identifier is a semaphore resource, obtained from sem_get().

nowait

Specifies if the process shouldn't wait for the semaphore to be acquired. If set to true, the call will return false immediately if a semaphore cannot be immediately acquired.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.6.1 | The $nowait parameter was added.

See Also

  • sem_get() - Get a semaphore id
  • sem_release() - Release a semaphore


Get a semaphore id

  • « sem_acquire
  • sem_release »
  • PHP Manual
  • Semaphore Functions
  • Get a semaphore id

sem_get

(PHP 4, PHP 5, PHP 7)

sem_get — Get a semaphore id

Description

sem_get ( int $key [, int $max_acquire = 1 [, int $perm = 0666 [, int $auto_release = 1 ]]] ) : resource

sem_get() returns an id that can be used to access the System V semaphore with the given key.

A second call to sem_get() for the same key will return a different semaphore identifier, but both identifiers access the same underlying semaphore.

Parameters

key

max_acquire

The number of processes that can acquire the semaphore simultaneously is set to max_acquire.

perm

The semaphore permissions. Actually this value is set only if the process finds it is the only process currently attached to the semaphore.

auto_release

Specifies if the semaphore should be automatically released on request shutdown.

Return Values

Returns a positive semaphore identifier on success, or FALSE on error.

Notes

Warning

When using sem_get() to access a semaphore created outside PHP, note that the semaphore must have been created as a set of 3 semaphores (for example, by specifying 3 as the nsems parameter when calling the C semget() function), otherwise PHP will be unable to access the semaphore.

See Also

  • sem_acquire() - Acquire a semaphore
  • sem_release() - Release a semaphore
  • ftok() - Convert a pathname and a project identifier to a System V IPC key


Release a semaphore

  • « sem_get
  • sem_remove »
  • PHP Manual
  • Semaphore Functions
  • Release a semaphore

sem_release

(PHP 4, PHP 5, PHP 7)

sem_release — Release a semaphore

Description

sem_release ( resource $sem_identifier ) : bool

sem_release() releases the semaphore if it is currently acquired by the calling process, otherwise a warning is generated.

After releasing the semaphore, sem_acquire() may be called to re-acquire it.

Parameters

sem_identifier

A Semaphore resource handle as returned by sem_get().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • sem_get() - Get a semaphore id
  • sem_acquire() - Acquire a semaphore


Remove a semaphore

  • « sem_release
  • shm_attach »
  • PHP Manual
  • Semaphore Functions
  • Remove a semaphore

sem_remove

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

sem_remove — Remove a semaphore

Description

sem_remove ( resource $sem_identifier ) : bool

sem_remove() removes the given semaphore.

After removing the semaphore, it is no longer accessible.

Parameters

sem_identifier

A semaphore resource identifier as returned by sem_get().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • sem_get() - Get a semaphore id
  • sem_release() - Release a semaphore
  • sem_acquire() - Acquire a semaphore


Creates or open a shared memory segment

  • « sem_remove
  • shm_detach »
  • PHP Manual
  • Semaphore Functions
  • Creates or open a shared memory segment

shm_attach

(PHP 4, PHP 5, PHP 7)

shm_attach — Creates or open a shared memory segment

Description

shm_attach ( int $key [, int $memsize [, int $perm = 0666 ]] ) : resource

shm_attach() returns an id that can be used to access the System V shared memory with the given key, the first call creates the shared memory segment with memsize and the optional perm-bits perm.

A second call to shm_attach() for the same key will return a different shared memory identifier, but both identifiers access the same underlying shared memory. memsize and perm will be ignored.

Parameters

key

A numeric shared memory segment ID

memsize

The memory size. If not provided, default to the sysvshm.init_mem in the php.ini, otherwise 10000 bytes.

perm

The optional permission bits. Default to 0666.

Return Values

Returns a shared memory segment identifier.

Changelog

Version | Description
5.3.0 | This function now returns a resource instead of an integer.

Notes

Note:

This function used to return an integer value prior to PHP 5.3.0. To achieve the same value in a portable manner, the return value can be cast to an integer like:

<?php
// Create a temporary file and return its path
$tmp = tempnam('/tmp', 'PHP');

// Get the file token key
$key = ftok($tmp, 'a');

// Attach the SHM resource, notice the cast afterwards
$id = shm_attach($key);

if ($id === false) {
    die('Unable to create the shared memory segment');
}

// Cast to integer, since prior to PHP 5.3.0 the resource id
// is returned which can be exposed when casting a resource
// to an integer
$id = (integer) $id;
?>

See Also

  • shm_detach() - Disconnects from shared memory segment
  • ftok() - Convert a pathname and a project identifier to a System V IPC key


Disconnects from shared memory segment

  • « shm_attach
  • shm_get_var »
  • PHP Manual
  • Semaphore Functions
  • Disconnects from shared memory segment

shm_detach

(PHP 4, PHP 5, PHP 7)

shm_detach — Disconnects from shared memory segment

Description

shm_detach ( resource $shm_identifier ) : bool

shm_detach() disconnects from the shared memory given by the shm_identifier created by shm_attach(). Remember, that shared memory still exist in the Unix system and the data is still present.

Parameters

shm_identifier

A shared memory resource handle as returned by shm_attach()

Return Values

shm_detach() always returns TRUE.

See Also

  • shm_attach() - Creates or open a shared memory segment
  • shm_remove() - Removes shared memory from Unix systems
  • shm_remove_var() - Removes a variable from shared memory


Returns a variable from shared memory

  • « shm_detach
  • shm_has_var »
  • PHP Manual
  • Semaphore Functions
  • Returns a variable from shared memory

shm_get_var

(PHP 4, PHP 5, PHP 7)

shm_get_var — Returns a variable from shared memory

Description

shm_get_var ( resource $shm_identifier , int $variable_key ) : mixed

shm_get_var() returns the variable with a given variable_key, in the given shared memory segment. The variable is still present in the shared memory.

Parameters

shm_identifier

Shared memory segment, obtained from shm_attach().

variable_key

The variable key.

Return Values

Returns the variable with the given key.

See Also

  • shm_has_var() - Check whether a specific entry exists
  • shm_put_var() - Inserts or updates a variable in shared memory


Check whether a specific entry exists

  • « shm_get_var
  • shm_put_var »
  • PHP Manual
  • Semaphore Functions
  • Check whether a specific entry exists

shm_has_var

(PHP 5 >= 5.3.0, PHP 7)

shm_has_var — Check whether a specific entry exists

Description

shm_has_var ( resource $shm_identifier , int $variable_key ) : bool

Checks whether a specific key exists inside a shared memory segment.

Parameters

shm_identifier

Shared memory segment, obtained from shm_attach().

variable_key

The variable key.

Return Values

Returns TRUE if the entry exists, otherwise FALSE

See Also

  • shm_get_var() - Returns a variable from shared memory
  • shm_put_var() - Inserts or updates a variable in shared memory


Inserts or updates a variable in shared memory

  • « shm_has_var
  • shm_remove_var »
  • PHP Manual
  • Semaphore Functions
  • Inserts or updates a variable in shared memory

shm_put_var

(PHP 4, PHP 5, PHP 7)

shm_put_var — Inserts or updates a variable in shared memory

Description

shm_put_var ( resource $shm_identifier , int $variable_key , mixed $variable ) : bool

shm_put_var() inserts or updates the variable with the given variable_key.

Warnings (E_WARNING level) will be issued if shm_identifier is not a valid SysV shared memory index or if there was not enough shared memory remaining to complete your request.

Parameters

shm_identifier

A shared memory resource handle as returned by shm_attach()

variable_key

The variable key.

variable

The variable. All variable types that serialize() supports may be used: generally this means all types except for resources and some internal objects that cannot be serialized.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • shm_get_var() - Returns a variable from shared memory
  • shm_has_var() - Check whether a specific entry exists


Removes a variable from shared memory

  • « shm_put_var
  • shm_remove »
  • PHP Manual
  • Semaphore Functions
  • Removes a variable from shared memory

shm_remove_var

(PHP 4, PHP 5, PHP 7)

shm_remove_var — Removes a variable from shared memory

Description

shm_remove_var ( resource $shm_identifier , int $variable_key ) : bool

Removes a variable with a given variable_key and frees the occupied memory.

Parameters

shm_identifier

The shared memory identifier as returned by shm_attach()

variable_key

The variable key.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • shm_remove() - Removes shared memory from Unix systems


Removes shared memory from Unix systems

  • « shm_remove_var
  • Shared Memory »
  • PHP Manual
  • Semaphore Functions
  • Removes shared memory from Unix systems

shm_remove

(PHP 4, PHP 5, PHP 7)

shm_remove — Removes shared memory from Unix systems

Description

shm_remove ( resource $shm_identifier ) : bool

shm_remove() removes the shared memory shm_identifier. All data will be destroyed.

Parameters

shm_identifier

The shared memory identifier as returned by shm_attach()

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • shm_remove_var() - Removes a variable from shared memory


Shared Memory

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
  • Shared Memory Functions
    • shmop_close — Close shared memory block
    • shmop_delete — Delete shared memory block
    • shmop_open — Create or open shared memory block
    • shmop_read — Read data from shared memory block
    • shmop_size — Get size of shared memory block
    • shmop_write — Write data into shared memory block


Introduction

Shmop is an easy to use set of functions that allows PHP to read, write, create and delete Unix shared memory segments.


Installation

To use shmop you will need to compile PHP with the --enable-shmop parameter in your configure line.


Resource Types

As of PHP 7.0.0 this extension defines the resource type shmop which is a handle to a shared memory block.


  • « Resource Types
  • Examples »
  • PHP Manual
  • Shared Memory
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


  • « Predefined Constants
  • Basic usage »
  • PHP Manual
  • Shared Memory
  • Examples

Examples

Table of Contents

  • Basic usage


Basic usage

Example #1 Shared Memory Operations Overview

<?php

// Create 100 byte shared memory block with system id of 0xff3
$shm_id = shmop_open(0xff3, "c", 0644, 100);
if (!$shm_id) {
    echo "Couldn't create shared memory segment\n";
}

// Get shared memory block's size
$shm_size = shmop_size($shm_id);
echo "SHM Block Size: " . $shm_size . " has been created.\n";

// Lets write a test string into shared memory
$shm_bytes_written = shmop_write($shm_id, "my shared memory block", 0);
if ($shm_bytes_written != strlen("my shared memory block")) {
    echo "Couldn't write the entire length of data\n";
}

// Now lets read the string back
$my_string = shmop_read($shm_id, 0, $shm_size);
if (!$my_string) {
    echo "Couldn't read from shared memory block\n";
}
echo "The data inside shared memory was: " . $my_string . "\n";

//Now lets delete the block and close the shared memory segment
if (!shmop_delete($shm_id)) {
    echo "Couldn't mark shared memory block for deletion.";
}
shmop_close($shm_id);

?>


Shared Memory Functions

Table of Contents

  • shmop_close — Close shared memory block
  • shmop_delete — Delete shared memory block
  • shmop_open — Create or open shared memory block
  • shmop_read — Read data from shared memory block
  • shmop_size — Get size of shared memory block
  • shmop_write — Write data into shared memory block


Close shared memory block

  • « Shared Memory Functions
  • shmop_delete »
  • PHP Manual
  • Shared Memory Functions
  • Close shared memory block

shmop_close

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

shmop_close — Close shared memory block

Description

shmop_close ( resource $shmid ) : void

shmop_close() is used to close a shared memory block.

Parameters

shmid

The shared memory block resource created by shmop_open()

Return Values

No value is returned.

Changelog

Version | Description
7.0.0 | The type of shmid has been changed from int to resource.

Examples

Example #1 Closing shared memory block

<?php
shmop_close($shm_id);
?>

This example will close shared memory block identified by $shm_id.

See Also

  • shmop_open() - Create or open shared memory block


Delete shared memory block

  • « shmop_close
  • shmop_open »
  • PHP Manual
  • Shared Memory Functions
  • Delete shared memory block

shmop_delete

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

shmop_delete — Delete shared memory block

Description

shmop_delete ( resource $shmid ) : bool

shmop_delete() is used to delete a shared memory block.

Parameters

shmid

The shared memory block resource created by shmop_open()

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.0.0 | The type of shmid has been changed from int to resource.

Examples

Example #1 Deleting shared memory block

<?php
shmop_delete($shm_id);
?>

This example will delete shared memory block identified by $shm_id.


Create or open shared memory block

  • « shmop_delete
  • shmop_read »
  • PHP Manual
  • Shared Memory Functions
  • Create or open shared memory block

shmop_open

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

shmop_open — Create or open shared memory block

Description

shmop_open ( int $key , string $flags , int $mode , int $size ) : resource

shmop_open() can create or open a shared memory block.

Parameters

key

System's id for the shared memory block. Can be passed as a decimal or hex.

flags

The flags that you can use:

  • "a" for access (sets SHM_RDONLY for shmat) use this flag when you need to open an existing shared memory segment for read only
  • "c" for create (sets IPC_CREATE) use this flag when you need to create a new shared memory segment or if a segment with the same key exists, try to open it for read and write
  • "w" for read & write access use this flag when you need to read and write to a shared memory segment, use this flag in most cases.
  • "n" create a new memory segment (sets IPC_CREATE|IPC_EXCL) use this flag when you want to create a new shared memory segment but if one already exists with the same flag, fail. This is useful for security purposes, using this you can prevent race condition exploits.

mode

The permissions that you wish to assign to your memory segment, those are the same as permission for a file. Permissions need to be passed in octal form, like for example 0644

size

The size of the shared memory block you wish to create in bytes

Note:

Note: the 3rd and 4th should be entered as 0 if you are opening an existing memory segment.

Return Values

On success shmop_open() will return an resource that you can use to access the shared memory segment you've created. FALSE is returned on failure.

Changelog

Version | Description
7.0.0 | The return type of shmop_open() has been changed from int to resource.

Examples

Example #1 Create a new shared memory block

<?php
$shm_key = ftok(__FILE__, 't');
$shm_id = shmop_open($shm_key, "c", 0644, 100);
?>

This example opened a shared memory block with a system id returned by ftok().

See Also

  • shmop_close() - Close shared memory block
  • shmop_delete() - Delete shared memory block


Read data from shared memory block

  • « shmop_open
  • shmop_size »
  • PHP Manual
  • Shared Memory Functions
  • Read data from shared memory block

shmop_read

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

shmop_read — Read data from shared memory block

Description

shmop_read ( resource $shmid , int $start , int $count ) : string

shmop_read() will read a string from shared memory block.

Parameters

shmid

The shared memory block identifier created by shmop_open()

start

Offset from which to start reading

count

The number of bytes to read. 0 reads shmop_size($shmid) - $start bytes.

Return Values

Returns the data or FALSE on failure.

Changelog

Version | Description
7.0.0 | The type of shmid has been changed from int to resource.

Examples

Example #1 Reading shared memory block

<?php
$shm_data = shmop_read($shm_id, 0, 50);
?>

This example will read 50 bytes from shared memory block and place the data inside $shm_data.

See Also

  • shmop_write() - Write data into shared memory block


Get size of shared memory block

  • « shmop_read
  • shmop_write »
  • PHP Manual
  • Shared Memory Functions
  • Get size of shared memory block

shmop_size

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

shmop_size — Get size of shared memory block

Description

shmop_size ( resource $shmid ) : int

shmop_size() is used to get the size, in bytes of the shared memory block.

Parameters

shmid

The shared memory block identifier created by shmop_open()

Return Values

Returns an int, which represents the number of bytes the shared memory block occupies.

Changelog

Version | Description
7.0.0 | The type of shmid has been changed from int to resource.

Examples

Example #1 Getting the size of the shared memory block

<?php
$shm_size = shmop_size($shm_id);
?>

This example will put the size of shared memory block identified by $shm_id into $shm_size.


Write data into shared memory block

  • « shmop_size
  • Sync »
  • PHP Manual
  • Shared Memory Functions
  • Write data into shared memory block

shmop_write

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

shmop_write — Write data into shared memory block

Description

shmop_write ( resource $shmid , string $data , int $offset ) : int

shmop_write() will write a string into shared memory block.

Parameters

shmid

The shared memory block identifier created by shmop_open()

data

A string to write into shared memory block

offset

Specifies where to start writing data inside the shared memory segment.

Return Values

The size of the written data, or FALSE on failure.

Changelog

Version | Description
7.0.0 | The type of shmid has been changed from int to resource.

Examples

Example #1 Writing to shared memory block

<?php
$shm_bytes_written = shmop_write($shm_id, $my_string, 0);
?>

This example will write data inside $my_string into shared memory block, $shm_bytes_written will contain the number of bytes written.

See Also

  • shmop_read() - Read data from shared memory block


Sync

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • SyncMutex — The SyncMutex class
    • SyncMutex::__construct — Constructs a new SyncMutex object
    • SyncMutex::lock — Waits for an exclusive lock
    • SyncMutex::unlock — Unlocks the mutex
  • SyncSemaphore — The SyncSemaphore class
    • SyncSemaphore::__construct — Constructs a new SyncSemaphore object
    • SyncSemaphore::lock — Decreases the count of the semaphore or waits
    • SyncSemaphore::unlock — Increases the count of the semaphore
  • SyncEvent — The SyncEvent class
    • SyncEvent::__construct — Constructs a new SyncEvent object
    • SyncEvent::fire — Fires/sets the event
    • SyncEvent::reset — Resets a manual event
    • SyncEvent::wait — Waits for the event to be fired/set
  • SyncReaderWriter — The SyncReaderWriter class
    • SyncReaderWriter::__construct — Constructs a new SyncReaderWriter object
    • SyncReaderWriter::readlock — Waits for a read lock
    • SyncReaderWriter::readunlock — Releases a read lock
    • SyncReaderWriter::writelock — Waits for an exclusive write lock
    • SyncReaderWriter::writeunlock — Releases a write lock
  • SyncSharedMemory — The SyncSharedMemory class
    • SyncSharedMemory::__construct — Constructs a new SyncSharedMemory object
    • SyncSharedMemory::first — Check to see if the object is the first instance system-wide of named shared memory
    • SyncSharedMemory::read — Copy data from named shared memory
    • SyncSharedMemory::size — Returns the size of the named shared memory
    • SyncSharedMemory::write — Copy data to named shared memory


Introduction

The 'sync' extension introduces cross-platform synchonization objects into PHP. Named and unnamed Mutex, Semaphore, Event, Reader-Writer, and named Shared Memory objects provide OS-level synchronization on both POSIX (e.g. Linux) and Windows platforms.

Automatic cleanup of acquired synchronization objects takes place during extension teardown. This means that if PHP prematurely terminates a script (e.g. script execution time is exceeded), objects will not be left in an unknown state. The only exception to this is if PHP itself crashes (e.g. an internal buffer overflow).

Unnamed synchronization objects don't have a lot of use outside of a multithreaded scenario. Unnamed objects are more useful in conjunction with the pthreads PECL extension.

Note:

Named objects require additional care to be used on all systems. If an object is instantiated with a specific set of parameters, it must always be instantiated with those parameters or the object will probably end up in an inconsistent state until the next reboot or a system administrator cleans up the mess.


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

A system with support for POSIX shared memory (shm_open()) or running Windows.


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/sync.


  • « Resource Types
  • SyncMutex »
  • PHP Manual
  • Sync
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


The SyncMutex class

(PECL sync >= 1.0.0)

Introduction

A cross-platform, native implementation of named and unnamed countable mutex objects.

A mutex is a mutual exclusion object that restricts access to a shared resource (e.g. a file) to a single instance. Countable mutexes acquire the mutex a single time and internally track the number of times the mutex is locked. The mutex is unlocked as soon as it goes out of scope or is unlocked the same number of times that it was locked.

Class synopsis

SyncMutex {
/* Methods */
public __construct ([ string $name ] )
public lock ([ int $wait = -1 ] ) : bool
public unlock ([ bool $all = FALSE ] ) : bool
}

Table of Contents

  • SyncMutex::__construct — Constructs a new SyncMutex object
  • SyncMutex::lock — Waits for an exclusive lock
  • SyncMutex::unlock — Unlocks the mutex


Constructs a new SyncMutex object

  • « SyncMutex
  • SyncMutex::lock »
  • PHP Manual
  • SyncMutex
  • Constructs a new SyncMutex object

SyncMutex::__construct

(PECL sync >= 1.0.0)

SyncMutex::__construct — Constructs a new SyncMutex object

Description

public SyncMutex::__construct ([ string $name ] )

Constructs a named or unnamed countable mutex.

Parameters

name

The name of the mutex if this is a named mutex object.

Note:

If the name already exists, it must be able to be opened by the current user that the process is running as or an exception will be thrown with a meaningless error message.

Return Values

The new SyncMutex object. An exception is thrown if the mutex cannot be created or opened.

Examples

Example #1 SyncMutex::__construct() named mutex with lock timeout example

<?php
$mutex = new SyncMutex("UniqueName");

if (!$mutex->lock(3000))
{
    echo "Unable to lock mutex.";

    exit();
}

/* ... */

$mutex->unlock();
?>

Example #2 SyncMutex::__construct() unnamed mutex example

<?php
$mutex = new SyncMutex();

$mutex->lock();

/* ... */

$mutex->unlock();
?>

See Also

  • SyncMutex::lock() - Waits for an exclusive lock
  • SyncMutex::unlock() - Unlocks the mutex


Waits for an exclusive lock

  • « SyncMutex::__construct
  • SyncMutex::unlock »
  • PHP Manual
  • SyncMutex
  • Waits for an exclusive lock

SyncMutex::lock

(PECL sync >= 1.0.0)

SyncMutex::lock — Waits for an exclusive lock

Description

public SyncMutex::lock ([ int $wait = -1 ] ) : bool

Obtains an exclusive lock on a SyncMutex object. If the lock is already acquired, then this increments an internal counter.

Parameters

wait

The number of milliseconds to wait for the exclusive lock. A value of -1 is infinite.

Return Values

A boolean of TRUE if the lock was obtained, FALSE otherwise.

Examples

Example #1 SyncMutex::lock() example

<?php
$mutex = new SyncMutex("UniqueName");

if (!$mutex->lock(3000))
{
    echo "Unable to lock mutex.";

    exit();
}

/* ... */

$mutex->unlock();
?>

See Also

  • SyncMutex::unlock() - Unlocks the mutex


Unlocks the mutex

  • « SyncMutex::lock
  • SyncSemaphore »
  • PHP Manual
  • SyncMutex
  • Unlocks the mutex

SyncMutex::unlock

(PECL sync >= 1.0.0)

SyncMutex::unlock — Unlocks the mutex

Description

public SyncMutex::unlock ([ bool $all = FALSE ] ) : bool

Decreases the internal counter of a SyncMutex object. When the internal counter reaches zero, the actual lock on the object is released.

Parameters

all

Specifies whether or not to set the internal counter to zero and therefore release the lock.

Return Values

A boolean of TRUE if the unlock operation was successful, FALSE otherwise.

Examples

Example #1 SyncMutex::unlock() example

<?php
$mutex = new SyncMutex("UniqueName");

$mutex->lock();

/* ... */

$mutex->unlock();
?>

See Also

  • SyncMutex::lock() - Waits for an exclusive lock


The SyncSemaphore class

(PECL sync >= 1.0.0)

Introduction

A cross-platform, native implementation of named and unnamed semaphore objects.

A semaphore restricts access to a limited resource to a limited number of instances. Semaphores differ from mutexes in that they can allow more than one instance to access a resource at one time while a mutex only allows one instance at a time.

Class synopsis

SyncSemaphore {
/* Methods */
public __construct ([ string $name [, int $initialval = 1 [, bool $autounlock = TRUE ]]] )
public lock ([ int $wait = -1 ] ) : bool
public unlock ([ int &$prevcount ] ) : bool
}

Table of Contents

  • SyncSemaphore::__construct — Constructs a new SyncSemaphore object
  • SyncSemaphore::lock — Decreases the count of the semaphore or waits
  • SyncSemaphore::unlock — Increases the count of the semaphore


Constructs a new SyncSemaphore object

  • « SyncSemaphore
  • SyncSemaphore::lock »
  • PHP Manual
  • SyncSemaphore
  • Constructs a new SyncSemaphore object

SyncSemaphore::__construct

(PECL sync >= 1.0.0)

SyncSemaphore::__construct — Constructs a new SyncSemaphore object

Description

public SyncSemaphore::__construct ([ string $name [, int $initialval = 1 [, bool $autounlock = TRUE ]]] )

Constructs a named or unnamed semaphore.

Parameters

name

The name of the semaphore if this is a named semaphore object.

Note:

If the name already exists, it must be able to be opened by the current user that the process is running as or an exception will be thrown with a meaningless error message.

initialval

The initial value of the semaphore. This is the number of locks that may be obtained.

autounlock

Specifies whether or not to automatically unlock the semaphore at the conclusion of the PHP script.

Warning

If an object is: A named semaphore with an autounlock of FALSE, the object is locked, and the PHP script concludes before the object is unlocked, then the underlying semaphore will end up in an inconsistent state.

Return Values

The new SyncSemaphore object. An exception is thrown if the semaphore cannot be created or opened.

Examples

Example #1 SyncSemaphore::__construct() example

<?php
$semaphore = new SyncSemaphore("LimitedResource_2clients", 2);

if (!$semaphore->lock(3000))
{
    echo "Unable to lock semaphore.";

    exit();
}

/* ... */

$semaphore->unlock();
?>

See Also

  • SyncSemaphore::lock() - Decreases the count of the semaphore or waits
  • SyncSemaphore::unlock() - Increases the count of the semaphore


Decreases the count of the semaphore or waits

  • « SyncSemaphore::__construct
  • SyncSemaphore::unlock »
  • PHP Manual
  • SyncSemaphore
  • Decreases the count of the semaphore or waits

SyncSemaphore::lock

(PECL sync >= 1.0.0)

SyncSemaphore::lock — Decreases the count of the semaphore or waits

Description

public SyncSemaphore::lock ([ int $wait = -1 ] ) : bool

Decreases the count of a SyncSemaphore object or waits until the semaphore becomes non-zero.

Parameters

wait

The number of milliseconds to wait for the semaphore. A value of -1 is infinite.

Return Values

A boolean of TRUE if the lock operation was successful, FALSE otherwise.

Examples

Example #1 SyncSemaphore::lock() example

<?php
$semaphore = new SyncSemaphore("LimitedResource_2clients", 2);

if (!$semaphore->lock(3000))
{
    echo "Unable to lock semaphore.";

    exit();
}

/* ... */

$semaphore->unlock();
?>

See Also

  • SyncSemaphore::unlock() - Increases the count of the semaphore


Increases the count of the semaphore

  • « SyncSemaphore::lock
  • SyncEvent »
  • PHP Manual
  • SyncSemaphore
  • Increases the count of the semaphore

SyncSemaphore::unlock

(PECL sync >= 1.0.0)

SyncSemaphore::unlock — Increases the count of the semaphore

Description

public SyncSemaphore::unlock ([ int &$prevcount ] ) : bool

Increases the count of a SyncSemaphore object.

Parameters

prevcount

Returns the previous count of the semaphore.

Return Values

A boolean of TRUE if the unlock operation was successful, FALSE otherwise.

Examples

Example #1 SyncSemaphore::unlock() example

<?php
$semaphore = new SyncSemaphore("LimitedResource_2clients", 2);

if (!$semaphore->lock(3000))
{
    echo "Unable to lock semaphore.";

    exit();
}

/* ... */

$semaphore->unlock();
?>

See Also

  • SyncSemaphore::lock() - Decreases the count of the semaphore or waits


The SyncEvent class

(PECL sync >= 1.0.0)

Introduction

A cross-platform, native implementation of named and unnamed event objects. Both automatic and manual event objects are supported.

An event object waits, without polling, for the object to be fired/set. One instance waits on the event object while another instance fires/sets the event. Event objects are useful wherever a long-running process would otherwise poll a resource (e.g. checking to see if uploaded data needs to be processed).

Class synopsis

SyncEvent {
/* Methods */
public __construct ([ string $name [, bool $manual = FALSE [, bool $prefire = FALSE ]]] )
public fire ( void ) : bool
public reset ( void ) : bool
public wait ([ int $wait = -1 ] ) : bool
}

Table of Contents

  • SyncEvent::__construct — Constructs a new SyncEvent object
  • SyncEvent::fire — Fires/sets the event
  • SyncEvent::reset — Resets a manual event
  • SyncEvent::wait — Waits for the event to be fired/set


Constructs a new SyncEvent object

  • « SyncEvent
  • SyncEvent::fire »
  • PHP Manual
  • SyncEvent
  • Constructs a new SyncEvent object

SyncEvent::__construct

(PECL sync >= 1.0.0)

SyncEvent::__construct — Constructs a new SyncEvent object

Description

public SyncEvent::__construct ([ string $name [, bool $manual = FALSE [, bool $prefire = FALSE ]]] )

Constructs a named or unnamed event object.

Parameters

name

The name of the event if this is a named event object.

Note:

If the name already exists, it must be able to be opened by the current user that the process is running as or an exception will be thrown with a meaningless error message.

manual

Specifies whether or not the event object must be reset manually.

Note:

Manual reset event objects allow all waiting processes through until the object is reset.

prefire

Specifies whether or not to prefire (signal) the event object.

Note:

Only has impact if the calling process/thread is the first to create the object.

Return Values

The new SyncEvent object. An exception is thrown if the event object cannot be created or opened.

Examples

Example #1 SyncEvent::__construct() example

<?php
// In a web application:
$event = new SyncEvent("GetAppReport");
$event->fire();

// In a cron job:
$event = new SyncEvent("GetAppReport");
$event->wait();
?>

Changelog

Version | Description
1.1.0 | Added prefire.

See Also

  • SyncEvent::fire() - Fires/sets the event
  • SyncEvent::reset() - Resets a manual event
  • SyncEvent::wait() - Waits for the event to be fired/set


Fires/sets the event

  • « SyncEvent::__construct
  • SyncEvent::reset »
  • PHP Manual
  • SyncEvent
  • Fires/sets the event

SyncEvent::fire

(PECL sync >= 1.0.0)

SyncEvent::fire — Fires/sets the event

Description

public SyncEvent::fire ( void ) : bool

Fires/sets a SyncEvent object. Lets multiple threads through that are waiting if the event object was created with a manual value of TRUE.

Parameters

This function has no parameters.

Return Values

A boolean of TRUE if the event was fired, FALSE otherwise.

Examples

Example #1 SyncEvent::fire() example

<?php
// In a web application:
$event = new SyncEvent("GetAppReport");
$event->fire();

// In a cron job:
$event = new SyncEvent("GetAppReport");
$event->wait();
?>

See Also

  • SyncEvent::reset() - Resets a manual event
  • SyncEvent::wait() - Waits for the event to be fired/set


Resets a manual event

  • « SyncEvent::fire
  • SyncEvent::wait »
  • PHP Manual
  • SyncEvent
  • Resets a manual event

SyncEvent::reset

(PECL sync >= 1.0.0)

SyncEvent::reset — Resets a manual event

Description

public SyncEvent::reset ( void ) : bool

Resets a SyncEvent object that has been fired/set. Only valid for manual event objects.

Parameters

This function has no parameters.

Return Values

A boolean value of TRUE if the object was successfully reset, FALSE otherwise.

Examples

Example #1 SyncEvent::reset() example

<?php
// In a web application:
$event = new SyncEvent("DemoApplication", true);
$event->wait();

// In a cron job:
$event = new SyncEvent("DemoApplication", true);
$event->reset();
/* ... Do some maintenance task(s) ... */
$event->fire();
?>

See Also

  • SyncEvent::fire() - Fires/sets the event
  • SyncEvent::reset()
  • SyncEvent::wait() - Waits for the event to be fired/set


Waits for the event to be fired/set

  • « SyncEvent::reset
  • SyncReaderWriter »
  • PHP Manual
  • SyncEvent
  • Waits for the event to be fired/set

SyncEvent::wait

(PECL sync >= 1.0.0)

SyncEvent::wait — Waits for the event to be fired/set

Description

public SyncEvent::wait ([ int $wait = -1 ] ) : bool

Waits for the SyncEvent object to be fired.

Parameters

wait

The number of milliseconds to wait for the event to be fired. A value of -1 is infinite.

Return Values

A boolean of TRUE if the event was fired, FALSE otherwise.

Examples

Example #1 SyncEvent::wait() example

<?php
// In a web application:
$event = new SyncEvent("GetAppReport");
$event->fire();

// In a cron job:
$event = new SyncEvent("GetAppReport");
$event->wait();
?>

See Also

  • SyncEvent::fire() - Fires/sets the event


The SyncReaderWriter class

(PECL sync >= 1.0.0)

Introduction

A cross-platform, native implementation of named and unnamed reader-writer objects.

A reader-writer object allows many readers or one writer to access a resource. This is an efficient solution for managing resources where access will primarily be read-only but exclusive write access is occasionally necessary.

Class synopsis

SyncReaderWriter {
/* Methods */
public __construct ([ string $name [, bool $autounlock = TRUE ]] )
public readlock ([ int $wait = -1 ] ) : bool
public readunlock ( void ) : bool
public writelock ([ int $wait = -1 ] ) : bool
public writeunlock ( void ) : bool
}

Table of Contents

  • SyncReaderWriter::__construct — Constructs a new SyncReaderWriter object
  • SyncReaderWriter::readlock — Waits for a read lock
  • SyncReaderWriter::readunlock — Releases a read lock
  • SyncReaderWriter::writelock — Waits for an exclusive write lock
  • SyncReaderWriter::writeunlock — Releases a write lock


Constructs a new SyncReaderWriter object

  • « SyncReaderWriter
  • SyncReaderWriter::readlock »
  • PHP Manual
  • SyncReaderWriter
  • Constructs a new SyncReaderWriter object

SyncReaderWriter::__construct

(PECL sync >= 1.0.0)

SyncReaderWriter::__construct — Constructs a new SyncReaderWriter object

Description

public SyncReaderWriter::__construct ([ string $name [, bool $autounlock = TRUE ]] )

Constructs a named or unnamed reader-writer object.

Parameters

name

The name of the reader-writer if this is a named reader-writer object.

Note:

If the name already exists, it must be able to be opened by the current user that the process is running as or an exception will be thrown with a meaningless error message.

autounlock

Specifies whether or not to automatically unlock the reader-writer at the conclusion of the PHP script.

Warning

If an object is: A named reader-writer with an autounlock of FALSE, the object is locked for either reading or writing, and the PHP script concludes before the object is unlocked, then the underlying objects will end up in an inconsistent state.

Return Values

The new SyncReaderWriter object. An exception is thrown if the reader-writer cannot be created or opened.

Examples

Example #1 SyncReaderWriter::__construct() example

<?php
$readwrite = new SyncReaderWriter("FileCacheLock");
$readwrite->readlock();
/* ... */
$readwrite->readunlock();

$readwrite->writelock();
/* ... */
$readwrite->writeunlock();
?>

See Also

  • SyncReaderWriter::readlock() - Waits for a read lock
  • SyncReaderWriter::readunlock() - Releases a read lock
  • SyncReaderWriter::writelock() - Waits for an exclusive write lock
  • SyncReaderWriter::writeunlock() - Releases a write lock


Waits for a read lock

  • « SyncReaderWriter::__construct
  • SyncReaderWriter::readunlock »
  • PHP Manual
  • SyncReaderWriter
  • Waits for a read lock

SyncReaderWriter::readlock

(PECL sync >= 1.0.0)

SyncReaderWriter::readlock — Waits for a read lock

Description

public SyncReaderWriter::readlock ([ int $wait = -1 ] ) : bool

Obtains a read lock on a SyncReaderWriter object.

Parameters

wait

The number of milliseconds to wait for a lock. A value of -1 is infinite.

Return Values

A boolean of TRUE if the lock was obtained, FALSE otherwise.

Examples

Example #1 SyncReaderWriter::readlock() example

<?php
$readwrite = new SyncReaderWriter("FileCacheLock");
$readwrite->readlock();
/* ... */
$readwrite->readunlock();
?>

See Also

  • SyncReaderWriter::readunlock() - Releases a read lock


Releases a read lock

  • « SyncReaderWriter::readlock
  • SyncReaderWriter::writelock »
  • PHP Manual
  • SyncReaderWriter
  • Releases a read lock

SyncReaderWriter::readunlock

(PECL sync >= 1.0.0)

SyncReaderWriter::readunlock — Releases a read lock

Description

public SyncReaderWriter::readunlock ( void ) : bool

Releases a read lock on a SyncReaderWriter object.

Parameters

This function has no parameters.

Return Values

A boolean of TRUE if the unlock operation was successful, FALSE otherwise.

Examples

Example #1 SyncReaderWriter::readunlock() example

<?php
$readwrite = new SyncReaderWriter("FileCacheLock");
$readwrite->readlock();
/* ... */
$readwrite->readunlock();
?>

See Also

  • SyncReaderWriter::readlock() - Waits for a read lock


Waits for an exclusive write lock

  • « SyncReaderWriter::readunlock
  • SyncReaderWriter::writeunlock »
  • PHP Manual
  • SyncReaderWriter
  • Waits for an exclusive write lock

SyncReaderWriter::writelock

(PECL sync >= 1.0.0)

SyncReaderWriter::writelock — Waits for an exclusive write lock

Description

public SyncReaderWriter::writelock ([ int $wait = -1 ] ) : bool

Obtains an exclusive write lock on a SyncReaderWriter object.

Parameters

wait

The number of milliseconds to wait for a lock. A value of -1 is infinite.

Return Values

A boolean of TRUE if the lock was obtained, FALSE otherwise.

Examples

Example #1 SyncReaderWriter::writelock() example

<?php
$readwrite = new SyncReaderWriter("FileCacheLock");
$readwrite->writelock();
/* ... */
$readwrite->writeunlock();
?>

See Also

  • SyncReaderWriter::writeunlock() - Releases a write lock


Releases a write lock

  • « SyncReaderWriter::writelock
  • SyncSharedMemory »
  • PHP Manual
  • SyncReaderWriter
  • Releases a write lock

SyncReaderWriter::writeunlock

(PECL sync >= 1.0.0)

SyncReaderWriter::writeunlock — Releases a write lock

Description

public SyncReaderWriter::writeunlock ( void ) : bool

Releases a write lock on a SyncReaderWriter object.

Parameters

This function has no parameters.

Return Values

A boolean of TRUE if the unlock operation was successful, FALSE otherwise.

Examples

Example #1 SyncReaderWriter::writeunlock() example

<?php
$readwrite = new SyncReaderWriter("FileCacheLock");
$readwrite->writelock();
/* ... */
$readwrite->writeunlock();
?>

See Also

  • SyncReaderWriter::writelock() - Waits for an exclusive write lock


The SyncSharedMemory class

(PECL sync >= 1.1.0)

Introduction

A cross-platform, native, consistent implementation of named shared memory objects.

Shared memory lets two separate processes communicate without the need for complex pipes or sockets. There are several integer-based shared memory implementations for PHP. Named shared memory is an alternative.

Synchronization objects (e.g. SyncMutex) are still required to protect most uses of shared memory.

Class synopsis

SyncSharedMemory {
/* Methods */
public __construct ( string $name , int $size )
public first ( void ) : bool
public read ([ int $start = 0 [, int $length ]] )
public size ( void ) : bool
public write ([ string $string [, int $start = 0 ]] )
}

Table of Contents

  • SyncSharedMemory::__construct — Constructs a new SyncSharedMemory object
  • SyncSharedMemory::first — Check to see if the object is the first instance system-wide of named shared memory
  • SyncSharedMemory::read — Copy data from named shared memory
  • SyncSharedMemory::size — Returns the size of the named shared memory
  • SyncSharedMemory::write — Copy data to named shared memory


Constructs a new SyncSharedMemory object

  • « SyncSharedMemory
  • SyncSharedMemory::first »
  • PHP Manual
  • SyncSharedMemory
  • Constructs a new SyncSharedMemory object

SyncSharedMemory::__construct

(PECL sync >= 1.1.0)

SyncSharedMemory::__construct — Constructs a new SyncSharedMemory object

Description

public SyncSharedMemory::__construct ( string $name , int $size )

Constructs a named shared memory object.

Parameters

name

The name of the shared memory object.

Note:

If the name already exists, it must be able to be opened by the current user that the process is running as or an exception will be thrown with a meaningless error message.

size

The size, in bytes, of shared memory to reserve.

Note:

The amount of memory cannot be resized later. Request sufficient storage up front.

Return Values

The new SyncSharedMemory object. An exception is thrown if the shared memory object cannot be created or opened.

Examples

Example #1 SyncSharedMemory::__construct() example

<?php
// You will probably need to protect shared memory with other synchronization objects.
// Shared memory goes away when the last reference to it disappears.
$mem = new SyncSharedMemory("AppReportName", 1024);
if ($mem->first())
{
    // Do first time initialization work here.
}

$result = $mem->write(json_encode(array("name" => "my_report.txt")));
?>

See Also

  • SyncSharedMemory::first() - Check to see if the object is the first instance system-wide of named shared memory
  • SyncSharedMemory::size() - Returns the size of the named shared memory
  • SyncSharedMemory::write() - Copy data to named shared memory
  • SyncSharedMemory::read() - Copy data from named shared memory


Check to see if the object is the first instance system-wide of named shared memory

  • « SyncSharedMemory::__construct
  • SyncSharedMemory::read »
  • PHP Manual
  • SyncSharedMemory
  • Check to see if the object is the first instance system-wide of named shared memory

SyncSharedMemory::first

(PECL sync >= 1.1.0)

SyncSharedMemory::first — Check to see if the object is the first instance system-wide of named shared memory

Description

public SyncSharedMemory::first ( void ) : bool

Retrieves the system-wide first instance status of a SyncSharedMemory object.

Parameters

This function has no parameters.

Return Values

A boolean of TRUE if the object is the first instance system-wide, FALSE otherwise.

Examples

Example #1 SyncSharedMemory::first() example

<?php
$mem = new SyncSharedMemory("AppReportName", 1024);
if ($mem->first())
{
    // Do first time initialization work here.
}

var_dump($mem->first());

$mem2 = new SyncSharedMemory("AppReportName", 1024);

var_dump($mem2->first());
?>

The above example will output something similar to:

bool(true)
bool(false)

See Also

  • SyncSharedMemory::write() - Copy data to named shared memory
  • SyncSharedMemory::read() - Copy data from named shared memory


Copy data from named shared memory

  • « SyncSharedMemory::first
  • SyncSharedMemory::size »
  • PHP Manual
  • SyncSharedMemory
  • Copy data from named shared memory

SyncSharedMemory::read

(PECL sync >= 1.1.0)

SyncSharedMemory::read — Copy data from named shared memory

Description

public SyncSharedMemory::read ([ int $start = 0 [, int $length ]] )

Copies data from named shared memory.

Parameters

start

The start/offset, in bytes, to begin reading.

Note:

If the value is negative, the starting position will begin at the specified number of bytes from the end of the shared memory segment.

length

The number of bytes to read.

Note:

If unspecified, reading will stop at the end of the shared memory segment.

If the value is negative, reading will stop the specified number of bytes from the end of the shared memory segment.

Return Values

A string containing the data read from shared memory.

Examples

Example #1 SyncSharedMemory::__construct() example

<?php
// You will probably need to protect shared memory with other synchronization objects.
// Shared memory goes away when the last reference to it disappears.
$mem = new SyncSharedMemory("AppReportName", 1024);
if ($mem->first())
{
    // Do first time initialization work here.
}

$result = $mem->write("report.txt");

$result = $mem->read(3, -4);
var_dump($result);
?>

The above example will output something similar to:

string(3) "ort"

See Also

  • SyncSharedMemory::__construct() - Constructs a new SyncSharedMemory object
  • SyncSharedMemory::first() - Check to see if the object is the first instance system-wide of named shared memory
  • SyncSharedMemory::write() - Copy data to named shared memory
  • SyncSharedMemory::read()


Returns the size of the named shared memory

  • « SyncSharedMemory::read
  • SyncSharedMemory::write »
  • PHP Manual
  • SyncSharedMemory
  • Returns the size of the named shared memory

SyncSharedMemory::size

(PECL sync >= 1.1.0)

SyncSharedMemory::size — Returns the size of the named shared memory

Description

public SyncSharedMemory::size ( void ) : bool

Retrieves the shared memory size of a SyncSharedMemory object.

Parameters

This function has no parameters.

Return Values

An integer containing the size of the shared memory. This will be the same size that was passed to the constructor.

Examples

Example #1 SyncSharedMemory::size() example

<?php
$mem = new SyncSharedMemory("AppReportName", 1024);
var_dump($mem->size());
?>

The above example will output something similar to:

int(1024)

See Also

  • SyncSharedMemory::__construct() - Constructs a new SyncSharedMemory object
  • SyncSharedMemory::write() - Copy data to named shared memory
  • SyncSharedMemory::read() - Copy data from named shared memory


Copy data to named shared memory

  • « SyncSharedMemory::size
  • Other Basic Extensions »
  • PHP Manual
  • SyncSharedMemory
  • Copy data to named shared memory

SyncSharedMemory::write

(PECL sync >= 1.1.0)

SyncSharedMemory::write — Copy data to named shared memory

Description

public SyncSharedMemory::write ([ string $string [, int $start = 0 ]] )

Copies data to named shared memory.

Parameters

string

The data to write to shared memoy.

Note:

If the size of the data exceeds the size of the shared memory, the number of bytes written returned will be less than the length of the input.

start

The start/offset, in bytes, to begin writing.

Note:

If the value is negative, the starting position will begin at the specified number of bytes from the end of the shared memory segment.

Return Values

An integer containing the number of bytes written to shared memory.

Examples

Example #1 SyncSharedMemory::write() example

<?php
// You will probably need to protect shared memory with other synchronization objects.
// Shared memory goes away when the last reference to it disappears.
$mem = new SyncSharedMemory("AppReportName", 1024);
if ($mem->first())
{
    // Do first time initialization work here.
}

$result = $mem->write("report.txt");
var_dump($result);

$result = $mem->write("report.txt", -3);
var_dump($result);
?>

The above example will output something similar to:

int(10)
int(3)

See Also

  • SyncSharedMemory::__construct() - Constructs a new SyncSharedMemory object
  • SyncSharedMemory::first() - Check to see if the object is the first instance system-wide of named shared memory
  • SyncSharedMemory::write()
  • SyncSharedMemory::read() - Copy data from named shared memory


Other Basic Extensions

  • GeoIP — Geo IP Location
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • GeoIP Functions
  • FANN — FANN (Fast Artificial Neural Network)
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Fann Functions
    • FANNConnection — The FANNConnection class
  • JSON — JavaScript Object Notation
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • JsonException — The JsonException class
    • JsonSerializable — The JsonSerializable interface
    • JSON Functions
  • Judy — Judy Arrays
    • Introduction
    • Installing/Configuring
    • Judy — The Judy class
    • Judy Functions
  • Lua
    • Introduction
    • Installing/Configuring
    • Lua — The Lua class
    • LuaClosure — The LuaClosure class
  • LuaSandbox
    • Introduction
    • Installing/Configuring
    • Differences from Standard Lua
    • Examples
    • LuaSandbox — The LuaSandbox class
    • LuaSandboxFunction — The LuaSandboxFunction class
    • LuaSandboxError — The LuaSandboxError class
    • LuaSandboxErrorError — The LuaSandboxErrorError class
    • LuaSandboxFatalError — The LuaSandboxFatalError class
    • LuaSandboxMemoryError — The LuaSandboxMemoryError class
    • LuaSandboxRuntimeError — The LuaSandboxRuntimeError class
    • LuaSandboxSyntaxError — The LuaSandboxSyntaxError class
    • LuaSandboxTimeoutError — The LuaSandboxTimeoutError class
  • Misc. — Miscellaneous Functions
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Misc. Functions
    • Changelog
  • Parsekit
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Parsekit Functions
  • Seaslog
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Seaslog Functions
    • SeasLog — The SeasLog class
  • SPL — Standard PHP Library (SPL)
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Datastructures
    • Iterators
    • Interfaces
    • Exceptions
    • SPL Functions
    • File Handling
    • Miscellaneous Classes and Interfaces
  • SPL Types — SPL Type Handling
    • Introduction
    • Installing/Configuring
    • SplType — The SplType class
    • SplInt — The SplInt class
    • SplFloat — The SplFloat class
    • SplEnum — The SplEnum class
    • SplBool — The SplBool class
    • SplString — The SplString class
  • Streams
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Stream Filters
    • Stream Contexts
    • Stream Errors
    • Examples
    • php_user_filter — The php_user_filter class
    • streamWrapper — The streamWrapper class
    • Stream Functions
  • Swoole
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Swoole Functions
    • Swoole\Async — The Swoole\Async class
    • Swoole\Atomic — The Swoole\Atomic class
    • Swoole\Buffer — The Swoole\Buffer class
    • Swoole\Channel — The Swoole\Channel class
    • Swoole\Client — The Swoole\Client class
    • Swoole\Connection\Iterator — The Swoole\Connection\Iterator class
    • Swoole\Coroutine — The Swoole\Coroutine class
    • Swoole\Event — The Swoole\Event class
    • Swoole\Exception — The Swoole\Exception class
    • Swoole\Http\Client — The Swoole\Http\Client class
    • Swoole\Http\Request — The Swoole\Http\Request class
    • Swoole\Http\Response — The Swoole\Http\Response class
    • Swoole\Http\Server — The Swoole\Http\Server class
    • Swoole\Lock — The Swoole\Lock class
    • Swoole\Mmap — The Swoole\Mmap class
    • Swoole\MySQL — The Swoole\MySQL class
    • Swoole\MySQL\Exception — The Swoole\MySQL\Exception class
    • Swoole\Process — The Swoole\Process class
    • Swoole\Redis\Server — The Swoole\Redis\Server class
    • Swoole\Serialize — The Swoole\Serialize class
    • Swoole\Server — The Swoole\Server class
    • Swoole\Table — The Swoole\Table class
    • Swoole\Timer — The Swoole\Timer class
    • Swoole\WebSocket\Frame — The Swoole\WebSocket\Frame class
    • Swoole\WebSocket\Server — The Swoole\WebSocket\Server class
  • Tidy
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • tidy — The tidy class
    • tidyNode — The tidyNode class
    • Tidy Functions
  • Tokenizer
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Tokenizer Functions
  • URLs
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • URL Functions
  • V8js — V8 Javascript Engine Integration
    • Introduction
    • Installing/Configuring
    • Examples
    • V8Js — The V8Js class
    • V8JsException — The V8JsException class
  • Yaml — YAML Data Serialization
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Callbacks
    • Yaml Functions
  • Yaf — Yet Another Framework
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Application Configuration
    • Yaf_Application — The Yaf_Application class
    • Yaf_Bootstrap_Abstract — The Yaf_Bootstrap_Abstract class
    • Yaf_Dispatcher — The Yaf_Dispatcher class
    • Yaf_Config_Abstract — The Yaf_Config_Abstract class
    • Yaf_Config_Ini — The Yaf_Config_Ini class
    • Yaf_Config_Simple — The Yaf_Config_Simple class
    • Yaf_Controller_Abstract — The Yaf_Controller_Abstract class
    • Yaf_Action_Abstract — The Yaf_Action_Abstract class
    • Yaf_View_Interface — The Yaf_View_Interface class
    • Yaf_View_Simple — The Yaf_View_Simple class
    • Yaf_Loader — The Yaf_Loader class
    • Yaf_Plugin_Abstract — The Yaf_Plugin_Abstract class
    • Yaf_Registry — The Yaf_Registry class
    • Yaf_Request_Abstract — The Yaf_Request_Abstract class
    • Yaf_Request_Http — The Yaf_Request_Http class
    • Yaf_Request_Simple — The Yaf_Request_Simple class
    • Yaf_Response_Abstract — The Yaf_Response_Abstract class
    • Yaf_Route_Interface — The Yaf_Route_Interface class
    • Yaf_Route_Map — The Yaf_Route_Map class
    • Yaf_Route_Regex — The Yaf_Route_Regex class
    • Yaf_Route_Rewrite — The Yaf_Route_Rewrite class
    • Yaf_Router — The Yaf_Router class
    • Yaf_Route_Simple — The Yaf_Route_Simple class
    • Yaf_Route_Static — The Yaf_Route_Static class
    • Yaf_Route_Supervar — The Yaf_Route_Supervar class
    • Yaf_Session — The Yaf_Session class
    • Yaf_Exception — The Yaf_Exception class
    • Yaf_Exception_TypeError — The Yaf_Exception_TypeError class
    • Yaf_Exception_StartupError — The Yaf_Exception_StartupError class
    • Yaf_Exception_DispatchFailed — The Yaf_Exception_DispatchFailed class
    • Yaf_Exception_RouterFailed — The Yaf_Exception_RouterFailed class
    • Yaf_Exception_LoadFailed — The Yaf_Exception_LoadFailed class
    • Yaf_Exception_LoadFailed_Module — The Yaf_Exception_LoadFailed_Module class
    • Yaf_Exception_LoadFailed_Controller — The Yaf_Exception_LoadFailed_Controller class
    • Yaf_Exception_LoadFailed_Action — The Yaf_Exception_LoadFailed_Action class
    • Yaf_Exception_LoadFailed_View — The Yaf_Exception_LoadFailed_View class
  • Yaconf
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Yaconf — The Yaconf class
  • Taint
    • Introduction
    • Installing/Configuring
    • More Details
    • Taint Functions
  • Data Structures
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Collection — The Collection interface
    • Hashable — The Hashable interface
    • Sequence — The Sequence interface
    • Vector — The Vector class
    • Deque — The Deque class
    • Map — The Map class
    • Pair — The Pair class
    • Set — The Set class
    • Stack — The Stack class
    • Queue — The Queue class
    • PriorityQueue — The PriorityQueue class


Geo IP Location

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • GeoIP Functions
    • geoip_asnum_by_name — Get the Autonomous System Numbers (ASN)
    • geoip_continent_code_by_name — Get the two letter continent code
    • geoip_country_code_by_name — Get the two letter country code
    • geoip_country_code3_by_name — Get the three letter country code
    • geoip_country_name_by_name — Get the full country name
    • geoip_database_info — Get GeoIP Database information
    • geoip_db_avail — Determine if GeoIP Database is available
    • geoip_db_filename — Returns the filename of the corresponding GeoIP Database
    • geoip_db_get_all_info — Returns detailed information about all GeoIP database types
    • geoip_domain_by_name — Get the second level domain name
    • geoip_id_by_name — Get the Internet connection type
    • geoip_isp_by_name — Get the Internet Service Provider (ISP) name
    • geoip_netspeedcell_by_name — Get the Internet connection speed
    • geoip_org_by_name — Get the organization name
    • geoip_record_by_name — Returns the detailed City information found in the GeoIP Database
    • geoip_region_by_name — Get the country code and region
    • geoip_region_name_by_code — Returns the region name for some country and region code combo
    • geoip_setup_custom_directory — Set a custom directory for the GeoIP database
    • geoip_time_zone_by_country_and_region — Returns the time zone for some country and region code combo


Introduction

The GeoIP extension allows you to find the location of an IP address. City, State, Country, Longitude, Latitude, and other information as all, such as ISP and connection type can be obtained with the help of GeoIP.

Warning

This extension does not support MaxMind's current "GeoIP2" databases, only the "GeoIP legacy" database files.


Requirements

This extension requires the GeoIP C library version 1.4.0 or higher to be installed. You can grab the latest version from » http://www.maxmind.com/app/c and compile it yourself.

By default, you will only have access to the Free GeoIP Country or GeoLite City databases. While this module can work with other types of database, you must buy a commercial license from » Maxmind.


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/geoip.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

GeoIP Configure Options
Name | Default | Changeable | Changelog
geoip.custom_directory | "" | PHP_INI_ALL |

Here's a short explanation of the configuration directives.

geoip.custom_directory string

Empty by default, but can be set to force a different database path than the one compiled in the 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.

GEOIP_COUNTRY_EDITION (integer)
GEOIP_REGION_EDITION_REV0 (integer)
GEOIP_CITY_EDITION_REV0 (integer)
GEOIP_ORG_EDITION (integer)
GEOIP_ISP_EDITION (integer)
GEOIP_CITY_EDITION_REV1 (integer)
GEOIP_REGION_EDITION_REV1 (integer)
GEOIP_PROXY_EDITION (integer)
GEOIP_ASNUM_EDITION (integer)
GEOIP_NETSPEED_EDITION (integer)
GEOIP_DOMAIN_EDITION (integer)

The following constants are for net speed:

GEOIP_UNKNOWN_SPEED (integer)
GEOIP_DIALUP_SPEED (integer)
GEOIP_CABLEDSL_SPEED (integer)
GEOIP_CORPORATE_SPEED (integer)


GeoIP Functions

Table of Contents

  • geoip_asnum_by_name — Get the Autonomous System Numbers (ASN)
  • geoip_continent_code_by_name — Get the two letter continent code
  • geoip_country_code_by_name — Get the two letter country code
  • geoip_country_code3_by_name — Get the three letter country code
  • geoip_country_name_by_name — Get the full country name
  • geoip_database_info — Get GeoIP Database information
  • geoip_db_avail — Determine if GeoIP Database is available
  • geoip_db_filename — Returns the filename of the corresponding GeoIP Database
  • geoip_db_get_all_info — Returns detailed information about all GeoIP database types
  • geoip_domain_by_name — Get the second level domain name
  • geoip_id_by_name — Get the Internet connection type
  • geoip_isp_by_name — Get the Internet Service Provider (ISP) name
  • geoip_netspeedcell_by_name — Get the Internet connection speed
  • geoip_org_by_name — Get the organization name
  • geoip_record_by_name — Returns the detailed City information found in the GeoIP Database
  • geoip_region_by_name — Get the country code and region
  • geoip_region_name_by_code — Returns the region name for some country and region code combo
  • geoip_setup_custom_directory — Set a custom directory for the GeoIP database
  • geoip_time_zone_by_country_and_region — Returns the time zone for some country and region code combo


Get the Autonomous System Numbers (ASN)

  • « GeoIP Functions
  • geoip_continent_code_by_name »
  • PHP Manual
  • GeoIP Functions
  • Get the Autonomous System Numbers (ASN)

geoip_asnum_by_name

(PECL geoip >= 1.1.0)

geoip_asnum_by_name — Get the Autonomous System Numbers (ASN)

Description

geoip_asnum_by_name ( string $hostname ) : string

The geoip_asnum_by_name() function will return the Autonomous System Numbers (ASN) associated with an IP address.

Parameters

hostname

The hostname or IP address.

Return Values

Returns the ASN on success, or FALSE if the address cannot be found in the database.

Examples

Example #1 A geoip_asnum_by_name() example

This will output the ASN of the host www.example.com.

<?php
$asn = geoip_asnum_by_name('www.example.com');

if ($asn) {
    echo 'The ASN is: ' . $asn;
}
?>

The above example will output:

The ASN is: AS15133 EdgeCast Networks, Inc


Get the two letter continent code

  • « geoip_asnum_by_name
  • geoip_country_code_by_name »
  • PHP Manual
  • GeoIP Functions
  • Get the two letter continent code

geoip_continent_code_by_name

(PECL geoip >= 1.0.3)

geoip_continent_code_by_name — Get the two letter continent code

Description

geoip_continent_code_by_name ( string $hostname ) : string

The geoip_continent_code_by_name() function will return the two letter continent code corresponding to a hostname or an IP address.

Parameters

hostname

The hostname or IP address whose location is to be looked-up.

Return Values

Returns the two letter continent code on success, or FALSE if the address cannot be found in the database.

Continent codes
Code | Continent name
AF | Africa
AN | Antarctica
AS | Asia
EU | Europe
NA | North america
OC | Oceania
SA | South america

Examples

Example #1 A geoip_continent_code_by_name() example

This will print where the host example.com is located.

<?php
$continent = geoip_continent_code_by_name('www.example.com');
if ($continent) {
    echo 'This host is located in: ' . $continent;
}
?>

The above example will output:

 This host is located in: NA

See Also

  • geoip_country_code_by_name() - Get the two letter country code


Get the two letter country code

  • « geoip_continent_code_by_name
  • geoip_country_code3_by_name »
  • PHP Manual
  • GeoIP Functions
  • Get the two letter country code

geoip_country_code_by_name

(PECL geoip >= 0.2.0)

geoip_country_code_by_name — Get the two letter country code

Description

geoip_country_code_by_name ( string $hostname ) : string

The geoip_country_code_by_name() function will return the two letter country code corresponding to a hostname or an IP address.

Parameters

hostname

The hostname or IP address whose location is to be looked-up.

Return Values

Returns the two letter ISO country code on success, or FALSE if the address cannot be found in the database.

Examples

Example #1 A geoip_country_code_by_name() example

This will print where the host example.com is located.

<?php
$country = geoip_country_code_by_name('www.example.com');
if ($country) {
    echo 'This host is located in: ' . $country;
}
?>

The above example will output:

This host is located in: US

Notes

Caution

Please see » http://www.maxmind.com/en/iso3166 for a complete list of possible return values, including special codes.

See Also

  • geoip_country_code3_by_name() - Get the three letter country code
  • geoip_country_name_by_name() - Get the full country name


Get the three letter country code

  • « geoip_country_code_by_name
  • geoip_country_name_by_name »
  • PHP Manual
  • GeoIP Functions
  • Get the three letter country code

geoip_country_code3_by_name

(PECL geoip >= 0.2.0)

geoip_country_code3_by_name — Get the three letter country code

Description

geoip_country_code3_by_name ( string $hostname ) : string

The geoip_country_code3_by_name() function will return the three letter country code corresponding to a hostname or an IP address.

Parameters

hostname

The hostname or IP address whose location is to be looked-up.

Return Values

Returns the three letter country code on success, or FALSE if the address cannot be found in the database.

Examples

Example #1 A geoip_country_code3_by_name() example

This will print where the host example.com is located.

<?php
$country = geoip_country_code3_by_name('www.example.com');
if ($country) {
    echo 'This host is located in: ' . $country;
}
?>

The above example will output:

This host is located in: USA

See Also

  • geoip_country_code_by_name() - Get the two letter country code
  • geoip_country_name_by_name() - Get the full country name


Get the full country name

  • « geoip_country_code3_by_name
  • geoip_database_info »
  • PHP Manual
  • GeoIP Functions
  • Get the full country name

geoip_country_name_by_name

(PECL geoip >= 0.2.0)

geoip_country_name_by_name — Get the full country name

Description

geoip_country_name_by_name ( string $hostname ) : string

The geoip_country_name_by_name() function will return the full country name corresponding to a hostname or an IP address.

Parameters

hostname

The hostname or IP address whose location is to be looked-up.

Return Values

Returns the country name on success, or FALSE if the address cannot be found in the database.

Examples

Example #1 A geoip_country_name_by_name() example

This will print where the host example.com is located.

<?php
$country = geoip_country_name_by_name('www.example.com');
if ($country) {
    echo 'This host is located in: ' . $country;
}
?>

The above example will output:

 This host is located in: United States

See Also

  • geoip_country_code_by_name() - Get the two letter country code
  • geoip_country_code3_by_name() - Get the three letter country code


Get GeoIP Database information

  • « geoip_country_name_by_name
  • geoip_db_avail »
  • PHP Manual
  • GeoIP Functions
  • Get GeoIP Database information

geoip_database_info

(PECL geoip >= 0.2.0)

geoip_database_info — Get GeoIP Database information

Description

geoip_database_info ([ int $database = GEOIP_COUNTRY_EDITION ] ) : string

The geoip_database_info() function returns the corresponding GeoIP Database version as it is defined inside the binary file.

If this function is called without arguments, it returns the version of the GeoIP Free Country Edition.

Parameters

database

The database type as an integer. You can use the various constants defined with this extension (ie: GEOIP_*_EDITION).

Return Values

Returns the corresponding database version, or NULL on error.

Examples

Example #1 A geoip_database_info() example

This will output information regarding the database.

<?php
print geoip_database_info(GEOIP_COUNTRY_EDITION);
?>

The above example will output:

GEO-106FREE 20060801 Build 1 Copyright (c) 2006 MaxMind LLC All Rights Reserved


Determine if GeoIP Database is available

  • « geoip_database_info
  • geoip_db_filename »
  • PHP Manual
  • GeoIP Functions
  • Determine if GeoIP Database is available

geoip_db_avail

(PECL geoip >= 1.0.1)

geoip_db_avail — Determine if GeoIP Database is available

Description

geoip_db_avail ( int $database ) : bool

The geoip_db_avail() function returns if the corresponding GeoIP Database is available and can be opened on disk.

It does not indicate if the file is a proper database, only if it is readable.

Parameters

database

The database type as an integer. You can use the various constants defined with this extension (ie: GEOIP_*_EDITION).

Return Values

Returns TRUE is database exists, FALSE if not found, or NULL on error.

Examples

Example #1 A geoip_db_avail() example

This will output the current database version string.

<?php

if (geoip_db_avail(GEOIP_COUNTRY_EDITION))
    print geoip_database_info(GEOIP_COUNTRY_EDITION);
?>

The above example will output:

GEO-106FREE 20080801 Build 1 Copyright (c) 2006 MaxMind LLC All Rights Reserved


Returns the filename of the corresponding GeoIP Database

  • « geoip_db_avail
  • geoip_db_get_all_info »
  • PHP Manual
  • GeoIP Functions
  • Returns the filename of the corresponding GeoIP Database

geoip_db_filename

(PECL geoip >= 1.0.1)

geoip_db_filename — Returns the filename of the corresponding GeoIP Database

Description

geoip_db_filename ( int $database ) : string

The geoip_db_filename() function returns the filename of the corresponding GeoIP Database.

It does not indicate if the file exists or not on disk, only where the library is looking for the database.

Parameters

database

The database type as an integer. You can use the various constants defined with this extension (ie: GEOIP_*_EDITION).

Return Values

Returns the filename of the corresponding database, or NULL on error.

Examples

Example #1 A geoip_db_filename() example

This will output the filename of the corresponding database.

<?php

print geoip_db_filename(GEOIP_COUNTRY_EDITION);

?>

The above example will output:

/usr/share/GeoIP/GeoIP.dat


Returns detailed information about all GeoIP database types

  • « geoip_db_filename
  • geoip_domain_by_name »
  • PHP Manual
  • GeoIP Functions
  • Returns detailed information about all GeoIP database types

geoip_db_get_all_info

(PECL geoip >= 1.0.1)

geoip_db_get_all_info — Returns detailed information about all GeoIP database types

Description

geoip_db_get_all_info ( void ) : array

The geoip_db_get_all_info() function will return detailed information as a multi-dimensional array about all the GeoIP database types.

This function is available even if no databases are installed. It will simply list them as non-available.

The names of the different keys of the returning associative array are as follows:

  • "available" -- Boolean, indicate if DB is available (see geoip_db_avail())
  • "description" -- The database description
  • "filename" -- The database filename on disk (see geoip_db_filename())

Return Values

Returns the associative array.

Examples

Example #1 A geoip_db_get_all_info() example

This will print the array containing all the information.

<?php
$infos = geoip_db_get_all_info();
if (is_array($infos)) {
    var_dump($infos);
}
?>

The above example will output:

array(11) {
  [1]=>
  array(3) {
    ["available"]=>
    bool(true)
    ["description"]=>
    string(21) "GeoIP Country Edition"
    ["filename"]=>
    string(32) "/usr/share/GeoIP/GeoIP.dat"
  }

[ ... ]

  [11]=>
  array(3) {
    ["available"]=>
    bool(false)
    ["description"]=>
    string(25) "GeoIP Domain Name Edition"
    ["filename"]=>
    string(38) "/usr/share/GeoIP/GeoIPDomain.dat"
  }
}

Example #2 A geoip_db_get_all_info() example

You can use the various constants as keys to get only parts of the information.

<?php
$infos = geoip_db_get_all_info();
if ($infos[GEOIP_COUNTRY_EDITION]['available']) {
    echo $infos[GEOIP_COUNTRY_EDITION]['description'];
}
?>

The above example will output:

GeoIP Country Edition


Get the second level domain name

  • « geoip_db_get_all_info
  • geoip_id_by_name »
  • PHP Manual
  • GeoIP Functions
  • Get the second level domain name

geoip_domain_by_name

(PECL geoip >= 1.1.0)

geoip_domain_by_name — Get the second level domain name

Description

geoip_domain_by_name ( string $hostname ) : string

The geoip_domain_by_name() function will return the second level domain names associated with a hostname or an IP address.

This function is currently only available to users who have bought a commercial GeoIP Domain Edition. A warning will be issued if the proper database cannot be located.

Parameters

hostname

The hostname or IP address.

Return Values

Returns the domain name on success, or FALSE if the address cannot be found in the database.

Examples

Example #1 A geoip_domain_by_name() example

This will output the domain associated with IP 61.106.139.1.

<?php
$domain = geoip_domain_by_name('61.106.139.1');

if ($domain) {
    echo 'The domain is: '. $domain;
}

?>

The above example will output:

The domain is: von.co.kr


Get the Internet connection type

  • « geoip_domain_by_name
  • geoip_isp_by_name »
  • PHP Manual
  • GeoIP Functions
  • Get the Internet connection type

geoip_id_by_name

(PECL geoip >= 0.2.0)

geoip_id_by_name — Get the Internet connection type

Description

geoip_id_by_name ( string $hostname ) : int

The geoip_id_by_name() function will return the Internet connection type corresponding to a hostname or an IP address.

The return value is numeric and can be compared to the following constants:

  • GEOIP_UNKNOWN_SPEED
  • GEOIP_DIALUP_SPEED
  • GEOIP_CABLEDSL_SPEED
  • GEOIP_CORPORATE_SPEED

Parameters

hostname

The hostname or IP address whose connection type is to be looked-up.

Return Values

Returns the connection type.

Examples

Example #1 A geoip_id_by_name() example

This will output the connection type of the host example.com.

<?php
$netspeed = geoip_id_by_name('www.example.com');

echo 'The connection type is ';

switch ($netspeed) {
    case GEOIP_DIALUP_SPEED:
        echo 'dial-up';
        break;
    case GEOIP_CABLEDSL_SPEED:
        echo 'cable or DSL';
        break;
    case GEOIP_CORPORATE_SPEED:
        echo 'corporate';
        break;
    case GEOIP_UNKNOWN_SPEED:
    default:
        echo 'unknown';
}
?>

The above example will output:

The connection type is corporate


Get the Internet Service Provider (ISP) name

  • « geoip_id_by_name
  • geoip_netspeedcell_by_name »
  • PHP Manual
  • GeoIP Functions
  • Get the Internet Service Provider (ISP) name

geoip_isp_by_name

(PECL geoip >= 1.0.2)

geoip_isp_by_name — Get the Internet Service Provider (ISP) name

Description

geoip_isp_by_name ( string $hostname ) : string

The geoip_isp_by_name() function will return the name of the Internet Service Provider (ISP) that an IP is assigned to.

This function is currently only available to users who have bought a commercial GeoIP ISP Edition. A warning will be issued if the proper database cannot be located.

Parameters

hostname

The hostname or IP address.

Return Values

Returns the ISP name on success, or FALSE if the address cannot be found in the database.

Examples

Example #1 A geoip_isp_by_name() example

This will print the ISP name of host example.com.

<?php
$isp = geoip_isp_by_name('www.example.com');
if ($isp) {
    echo 'This host IP is from ISP: ' . $isp;
}
?>

The above example will output:

This host IP is from ISP: ICANN c/o Internet Assigned Numbers Authority


Get the Internet connection speed

  • « geoip_isp_by_name
  • geoip_org_by_name »
  • PHP Manual
  • GeoIP Functions
  • Get the Internet connection speed

geoip_netspeedcell_by_name

(PECL geoip >= 1.1.0)

geoip_netspeedcell_by_name — Get the Internet connection speed

Description

geoip_netspeedcell_by_name ( string $hostname ) : string

The geoip_netspeedcell_by_name() function will return the Internet connection type and speed corresponding to a hostname or an IP address.

This function is only available if using GeoIP Library version 1.4.8 or newer.

This function is currently only available to users who have bought a commercial GeoIP NetSpeedCell Edition. A warning will be issued if the proper database cannot be located.

The return value is a string, common values are:

  • Cable/DSL
  • Dialup
  • Cellular
  • Corporate

Parameters

hostname

The hostname or IP address.

Return Values

Returns the connection speed on success, or FALSE if the address cannot be found in the database.

Examples

Example #1 A geoip_netspeedcell_by_name() example

This will output the connection speed of the host example.com.

<?php
$netspeed = geoip_netspeedcell_by_name('www.example.com');

if ($netspeed) {
    echo 'The connection type is: '. $netspeed;
}
?>

The above example will output:

The connection type is: Corporate


Get the organization name

  • « geoip_netspeedcell_by_name
  • geoip_record_by_name »
  • PHP Manual
  • GeoIP Functions
  • Get the organization name

geoip_org_by_name

(PECL geoip >= 0.2.0)

geoip_org_by_name — Get the organization name

Description

geoip_org_by_name ( string $hostname ) : string

The geoip_org_by_name() function will return the name of the organization that an IP is assigned to.

This function is currently only available to users who have bought a commercial GeoIP Organization, ISP or AS Edition. A warning will be issued if the proper database cannot be located.

Parameters

hostname

The hostname or IP address.

Return Values

Returns the organization name on success, or FALSE if the address cannot be found in the database.

Examples

Example #1 A geoip_org_by_name() example

This will print to whom the host example.com IP is allocated.

<?php
$org = geoip_org_by_name('www.example.com');
if ($org) {
    echo 'This host IP is allocated to: ' . $org;
}
?>

The above example will output:

This host IP is allocated to: ICANN c/o Internet Assigned Numbers Authority


Returns the detailed City information found in the GeoIP Database

  • « geoip_org_by_name
  • geoip_region_by_name »
  • PHP Manual
  • GeoIP Functions
  • Returns the detailed City information found in the GeoIP Database

geoip_record_by_name

(PECL geoip >= 0.2.0)

geoip_record_by_name — Returns the detailed City information found in the GeoIP Database

Description

geoip_record_by_name ( string $hostname ) : array

The geoip_record_by_name() function will return the record information corresponding to a hostname or an IP address.

This function is available for both GeoLite City Edition and commercial GeoIP City Edition. A warning will be issued if the proper database cannot be located.

The names of the different keys of the returning associative array are as follows:

  • "continent_code" -- Two letter continent code (as of version 1.0.4 with libgeoip 1.4.3 or newer)
  • "country_code" -- Two letter country code (see geoip_country_code_by_name())
  • "country_code3" -- Three letter country code (see geoip_country_code3_by_name())
  • "country_name" -- The country name (see geoip_country_name_by_name())
  • "region" -- The region code (ex: CA for California)
  • "city" -- The city.
  • "postal_code" -- The Postal Code, FSA or Zip Code.
  • "latitude" -- The Latitude as signed double.
  • "longitude" -- The Longitude as signed double.
  • "dma_code" -- Designated Market Area code (USA and Canada only)
  • "area_code" -- The PSTN area code (ex: 212)

Parameters

hostname

The hostname or IP address whose record is to be looked-up.

Return Values

Returns the associative array on success, or FALSE if the address cannot be found in the database.

Changelog

Version | Description
1.0.4 | Adding the continent_code with GeoIP Library 1.4.3 or newer only
1.0.3 | Adding country_code3 and country_name

Examples

Example #1 A geoip_record_by_name() example

This will print the array containing the record of host example.com.

<?php
$record = geoip_record_by_name('www.example.com');
if ($record) {
    print_r($record);
}
?>

The above example will output:

Array
(
    [continent_code] => NA
    [country_code] => US
    [country_code3] => USA
    [country_name] => United States
    [region] => CA
    [city] => Marina Del Rey
    [postal_code] =>
    [latitude] => 33.9776992798
    [longitude] => -118.435096741
    [dma_code] => 803
    [area_code] => 310
)


Get the country code and region

  • « geoip_record_by_name
  • geoip_region_name_by_code »
  • PHP Manual
  • GeoIP Functions
  • Get the country code and region

geoip_region_by_name

(PECL geoip >= 0.2.0)

geoip_region_by_name — Get the country code and region

Description

geoip_region_by_name ( string $hostname ) : array

The geoip_region_by_name() function will return the country and region corresponding to a hostname or an IP address.

This function is currently only available to users who have bought a commercial GeoIP Region Edition. A warning will be issued if the proper database cannot be located.

The names of the different keys of the returning associative array are as follows:

  • "country_code" -- Two letter country code (see geoip_country_code_by_name())
  • "region" -- The region code (ex: CA for California)

Parameters

hostname

The hostname or IP address whose region is to be looked-up.

Return Values

Returns the associative array on success, or FALSE if the address cannot be found in the database.

Examples

Example #1 A geoip_region_by_name() example

This will print the array containing the country code and region of the host example.com.

<?php
$region = geoip_region_by_name('www.example.com');
if ($region) {
    print_r($region);
}
?>

The above example will output:

Array
(
    [country_code] => US
    [region] => CA
)


Returns the region name for some country and region code combo

  • « geoip_region_by_name
  • geoip_setup_custom_directory »
  • PHP Manual
  • GeoIP Functions
  • Returns the region name for some country and region code combo

geoip_region_name_by_code

(PECL geoip >= 1.0.4)

geoip_region_name_by_code — Returns the region name for some country and region code combo

Description

geoip_region_name_by_code ( string $country_code , string $region_code ) : string

The geoip_region_name_by_code() function will return the region name corresponding to a country and region code combo.

In the United States, the region code corresponds to the two-letter abbreviation of each state. In Canada, the region code corresponds to the two-letter province or territory code as attributed by Canada Post.

For the rest of the world, GeoIP uses FIPS 10-4 codes to represent regions. You can check » http://www.maxmind.com/app/fips10_4 for a detailed list of FIPS 10-4 codes.

This function is always available if using GeoIP Library version 1.4.1 or newer. The data is taken directly from the GeoIP Library and not from any database.

Parameters

country_code

The two-letter country code (see geoip_country_code_by_name())

region_code

The two-letter (or digit) region code (see geoip_region_by_name())

Return Values

Returns the region name on success, or FALSE if the country and region code combo cannot be found.

Examples

Example #1 A geoip_region_name_by_code() example using region code for US/Canada

This will print the region name for country CA (Canada), region QC (Quebec).

<?php
$region = geoip_region_name_by_code('CA', 'QC');
if ($region) {
    echo 'Region name for CA/QC is: ' . $region;
}
?>

The above example will output:

Region name for CA/QC is: Quebec

Example #2 A geoip_region_name_by_code() example using FIPS codes

This will print the region name for country JP (Japan), region 01.

<?php
$region = geoip_region_name_by_code('JP', '01');
if ($region) {
    echo 'Region name for JP/01 is: ' . $region;
}
?>

The above example will output:

Region name for JP/01 is: Aichi


Set a custom directory for the GeoIP database

  • « geoip_region_name_by_code
  • geoip_time_zone_by_country_and_region »
  • PHP Manual
  • GeoIP Functions
  • Set a custom directory for the GeoIP database

geoip_setup_custom_directory

(PECL geoip >= 1.1.0)

geoip_setup_custom_directory — Set a custom directory for the GeoIP database

Description

geoip_setup_custom_directory ( string $path ) : void

The geoip_setup_custom_directory() function will change the default directory of the GeoIP database. This is equivalent to changing geoip.custom_directory.

Parameters

path

The full path of where the GeoIP database is on disk.

Return Values

No value is returned.

Examples

Example #1 A geoip_setup_custom_directory() example

This will change the GeoIP default database path.

<?php

geoip_setup_custom_directory('/some/other/path');

print geoip_db_filename(GEOIP_COUNTRY_EDITION);

?>

The above example will output:

/some/other/path/GeoIP.dat


Returns the time zone for some country and region code combo

  • « geoip_setup_custom_directory
  • FANN »
  • PHP Manual
  • GeoIP Functions
  • Returns the time zone for some country and region code combo

geoip_time_zone_by_country_and_region

(PECL geoip >= 1.0.4)

geoip_time_zone_by_country_and_region — Returns the time zone for some country and region code combo

Description

geoip_time_zone_by_country_and_region ( string $country_code [, string $region_code ] ) : string

The geoip_time_zone_by_country_and_region() function will return the time zone corresponding to a country and region code combo.

In the United States, the region code corresponds to the two-letter abbreviation of each state. In Canada, the region code corresponds to the two-letter province or territory code as attributed by Canada Post.

For the rest of the world, GeoIP uses FIPS 10-4 codes to represent regions. You can check » http://www.maxmind.com/app/fips10_4 for a detailed list of FIPS 10-4 codes.

This function is always available if using GeoIP Library version 1.4.1 or newer. The data is taken directly from the GeoIP Library and not from any database.

Parameters

country_code

The two-letter country code (see geoip_country_code_by_name())

region_code

The two-letter (or digit) region code (see geoip_region_by_name())

Return Values

Returns the time zone on success, or FALSE if the country and region code combo cannot be found.

Examples

Example #1 A geoip_time_zone_by_country_and_region() example using region code for US/Canada

This will print the time zone for country CA (Canada), region QC (Quebec).

<?php
$timezone = geoip_time_zone_by_country_and_region('CA', 'QC');
if ($timezone) {
    echo 'Time zone for CA/QC is: ' . $timezone;
}
?>

The above example will output:

Time zone for CA/QC is: America/Montreal

Example #2 A geoip_time_zone_by_country_and_region() example using FIPS codes

This will print the time zone for country JP (Japan), region 01 (Aichi).

<?php
$timezone = geoip_time_zone_by_country_and_region('JP', '01');
if ($timezone) {
    echo 'Time zone for JP/01 is: ' . $timezone;
}
?>

The above example will output:

Time zone for JP/01 is: Asia/Tokyo


FANN (Fast Artificial Neural Network)

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • XOR training
  • Fann Functions
    • fann_cascadetrain_on_data — Trains on an entire dataset, for a period of time using the Cascade2 training algorithm
    • fann_cascadetrain_on_file — Trains on an entire dataset read from file, for a period of time using the Cascade2 training algorithm
    • fann_clear_scaling_params — Clears scaling parameters
    • fann_copy — Creates a copy of a fann structure
    • fann_create_from_file — Constructs a backpropagation neural network from a configuration file
    • fann_create_shortcut_array — Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections
    • fann_create_shortcut — Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections
    • fann_create_sparse_array — Creates a standard backpropagation neural network, which is not fully connected using an array of layer sizes
    • fann_create_sparse — Creates a standard backpropagation neural network, which is not fully connected
    • fann_create_standard_array — Creates a standard fully connected backpropagation neural network using an array of layer sizes
    • fann_create_standard — Creates a standard fully connected backpropagation neural network
    • fann_create_train_from_callback — Creates the training data struct from a user supplied function
    • fann_create_train — Creates an empty training data struct
    • fann_descale_input — Scale data in input vector after get it from ann based on previously calculated parameters
    • fann_descale_output — Scale data in output vector after get it from ann based on previously calculated parameters
    • fann_descale_train — Descale input and output data based on previously calculated parameters
    • fann_destroy_train — Destructs the training data
    • fann_destroy — Destroys the entire network and properly freeing all the associated memory
    • fann_duplicate_train_data — Returns an exact copy of a fann train data
    • fann_get_activation_function — Returns the activation function
    • fann_get_activation_steepness — Returns the activation steepness for supplied neuron and layer number
    • fann_get_bias_array — Get the number of bias in each layer in the network
    • fann_get_bit_fail_limit — Returns the bit fail limit used during training
    • fann_get_bit_fail — The number of fail bits
    • fann_get_cascade_activation_functions_count — Returns the number of cascade activation functions
    • fann_get_cascade_activation_functions — Returns the cascade activation functions
    • fann_get_cascade_activation_steepnesses_count — The number of activation steepnesses
    • fann_get_cascade_activation_steepnesses — Returns the cascade activation steepnesses
    • fann_get_cascade_candidate_change_fraction — Returns the cascade candidate change fraction
    • fann_get_cascade_candidate_limit — Return the candidate limit
    • fann_get_cascade_candidate_stagnation_epochs — Returns the number of cascade candidate stagnation epochs
    • fann_get_cascade_max_cand_epochs — Returns the maximum candidate epochs
    • fann_get_cascade_max_out_epochs — Returns the maximum out epochs
    • fann_get_cascade_min_cand_epochs — Returns the minimum candidate epochs
    • fann_get_cascade_min_out_epochs — Returns the minimum out epochs
    • fann_get_cascade_num_candidate_groups — Returns the number of candidate groups
    • fann_get_cascade_num_candidates — Returns the number of candidates used during training
    • fann_get_cascade_output_change_fraction — Returns the cascade output change fraction
    • fann_get_cascade_output_stagnation_epochs — Returns the number of cascade output stagnation epochs
    • fann_get_cascade_weight_multiplier — Returns the weight multiplier
    • fann_get_connection_array — Get connections in the network
    • fann_get_connection_rate — Get the connection rate used when the network was created
    • fann_get_errno — Returns the last error number
    • fann_get_errstr — Returns the last errstr
    • fann_get_layer_array — Get the number of neurons in each layer in the network
    • fann_get_learning_momentum — Returns the learning momentum
    • fann_get_learning_rate — Returns the learning rate
    • fann_get_MSE — Reads the mean square error from the network
    • fann_get_network_type — Get the type of neural network it was created as
    • fann_get_num_input — Get the number of input neurons
    • fann_get_num_layers — Get the number of layers in the neural network
    • fann_get_num_output — Get the number of output neurons
    • fann_get_quickprop_decay — Returns the decay which is a factor that weights should decrease in each iteration during quickprop training
    • fann_get_quickprop_mu — Returns the mu factor
    • fann_get_rprop_decrease_factor — Returns the increase factor used during RPROP training
    • fann_get_rprop_delta_max — Returns the maximum step-size
    • fann_get_rprop_delta_min — Returns the minimum step-size
    • fann_get_rprop_delta_zero — Returns the initial step-size
    • fann_get_rprop_increase_factor — Returns the increase factor used during RPROP training
    • fann_get_sarprop_step_error_shift — Returns the sarprop step error shift
    • fann_get_sarprop_step_error_threshold_factor — Returns the sarprop step error threshold factor
    • fann_get_sarprop_temperature — Returns the sarprop temperature
    • fann_get_sarprop_weight_decay_shift — Returns the sarprop weight decay shift
    • fann_get_total_connections — Get the total number of connections in the entire network
    • fann_get_total_neurons — Get the total number of neurons in the entire network
    • fann_get_train_error_function — Returns the error function used during training
    • fann_get_train_stop_function — Returns the stop function used during training
    • fann_get_training_algorithm — Returns the training algorithm
    • fann_init_weights — Initialize the weights using Widrow + Nguyen’s algorithm
    • fann_length_train_data — Returns the number of training patterns in the train data
    • fann_merge_train_data — Merges the train data
    • fann_num_input_train_data — Returns the number of inputs in each of the training patterns in the train data
    • fann_num_output_train_data — Returns the number of outputs in each of the training patterns in the train data
    • fann_print_error — Prints the error string
    • fann_randomize_weights — Give each connection a random weight between min_weight and max_weight
    • fann_read_train_from_file — Reads a file that stores training data
    • fann_reset_errno — Resets the last error number
    • fann_reset_errstr — Resets the last error string
    • fann_reset_MSE — Resets the mean square error from the network
    • fann_run — Will run input through the neural network
    • fann_save_train — Save the training structure to a file
    • fann_save — Saves the entire network to a configuration file
    • fann_scale_input_train_data — Scales the inputs in the training data to the specified range
    • fann_scale_input — Scale data in input vector before feed it to ann based on previously calculated parameters
    • fann_scale_output_train_data — Scales the outputs in the training data to the specified range
    • fann_scale_output — Scale data in output vector before feed it to ann based on previously calculated parameters
    • fann_scale_train_data — Scales the inputs and outputs in the training data to the specified range
    • fann_scale_train — Scale input and output data based on previously calculated parameters
    • fann_set_activation_function_hidden — Sets the activation function for all of the hidden layers
    • fann_set_activation_function_layer — Sets the activation function for all the neurons in the supplied layer
    • fann_set_activation_function_output — Sets the activation function for the output layer
    • fann_set_activation_function — Sets the activation function for supplied neuron and layer
    • fann_set_activation_steepness_hidden — Sets the steepness of the activation steepness for all neurons in the all hidden layers
    • fann_set_activation_steepness_layer — Sets the activation steepness for all of the neurons in the supplied layer number
    • fann_set_activation_steepness_output — Sets the steepness of the activation steepness in the output layer
    • fann_set_activation_steepness — Sets the activation steepness for supplied neuron and layer number
    • fann_set_bit_fail_limit — Set the bit fail limit used during training
    • fann_set_callback — Sets the callback function for use during training
    • fann_set_cascade_activation_functions — Sets the array of cascade candidate activation functions
    • fann_set_cascade_activation_steepnesses — Sets the array of cascade candidate activation steepnesses
    • fann_set_cascade_candidate_change_fraction — Sets the cascade candidate change fraction
    • fann_set_cascade_candidate_limit — Sets the candidate limit
    • fann_set_cascade_candidate_stagnation_epochs — Sets the number of cascade candidate stagnation epochs
    • fann_set_cascade_max_cand_epochs — Sets the max candidate epochs
    • fann_set_cascade_max_out_epochs — Sets the maximum out epochs
    • fann_set_cascade_min_cand_epochs — Sets the min candidate epochs
    • fann_set_cascade_min_out_epochs — Sets the minimum out epochs
    • fann_set_cascade_num_candidate_groups — Sets the number of candidate groups
    • fann_set_cascade_output_change_fraction — Sets the cascade output change fraction
    • fann_set_cascade_output_stagnation_epochs — Sets the number of cascade output stagnation epochs
    • fann_set_cascade_weight_multiplier — Sets the weight multiplier
    • fann_set_error_log — Sets where the errors are logged to
    • fann_set_input_scaling_params — Calculate input scaling parameters for future use based on training data
    • fann_set_learning_momentum — Sets the learning momentum
    • fann_set_learning_rate — Sets the learning rate
    • fann_set_output_scaling_params — Calculate output scaling parameters for future use based on training data
    • fann_set_quickprop_decay — Sets the quickprop decay factor
    • fann_set_quickprop_mu — Sets the quickprop mu factor
    • fann_set_rprop_decrease_factor — Sets the decrease factor used during RPROP training
    • fann_set_rprop_delta_max — Sets the maximum step-size
    • fann_set_rprop_delta_min — Sets the minimum step-size
    • fann_set_rprop_delta_zero — Sets the initial step-size
    • fann_set_rprop_increase_factor — Sets the increase factor used during RPROP training
    • fann_set_sarprop_step_error_shift — Sets the sarprop step error shift
    • fann_set_sarprop_step_error_threshold_factor — Sets the sarprop step error threshold factor
    • fann_set_sarprop_temperature — Sets the sarprop temperature
    • fann_set_sarprop_weight_decay_shift — Sets the sarprop weight decay shift
    • fann_set_scaling_params — Calculate input and output scaling parameters for future use based on training data
    • fann_set_train_error_function — Sets the error function used during training
    • fann_set_train_stop_function — Sets the stop function used during training
    • fann_set_training_algorithm — Sets the training algorithm
    • fann_set_weight_array — Set connections in the network
    • fann_set_weight — Set a connection in the network
    • fann_shuffle_train_data — Shuffles training data, randomizing the order
    • fann_subset_train_data — Returns an copy of a subset of the train data
    • fann_test_data — Test a set of training data and calculates the MSE for the training data
    • fann_test — Test with a set of inputs, and a set of desired outputs
    • fann_train_epoch — Train one epoch with a set of training data
    • fann_train_on_data — Trains on an entire dataset for a period of time
    • fann_train_on_file — Trains on an entire dataset, which is read from file, for a period of time
    • fann_train — Train one iteration with a set of inputs, and a set of desired outputs
  • FANNConnection — The FANNConnection class
    • FANNConnection::__construct — The connection constructor
    • FANNConnection::getFromNeuron — Returns the postions of starting neuron
    • FANNConnection::getToNeuron — Returns the postions of terminating neuron
    • FANNConnection::getWeight — Returns the connection weight
    • FANNConnection::setWeight — Sets the connections weight


Introduction

PHP binding for FANN (Fast Artificial Neural Network) Library which implements multilayer artificial neural networks with support for both fully connected and sparsely connected networks. It includes a framework for easy handling of training data sets. It is easy to use, versatile, well documented, and fast.


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

PHP >= 5.2.0 and libfann >= 2.1.0


Installation

The FANN PHP extension should work on all Linux systems.

  • FANN Library Installation
  • PECL Installation
  • Manual Installation

FANN Library Installation

Before you start installation make sure that libfann is installed on your system. It's part of the main repository in the most Linux distributions (search for fann). You need a development version.

If it is not installed, you need to install it first. Either download it from the » official site or get it from your distro repository. For example on Fedora:

$ sudo yum install fann-devel
or Ubuntu:

$ sudo apt-get install libfann-dev

If the library is re-installed manually, then all old library file should be removed before re-installing otherwise the old library version could be linked.

PECL Installation

This extension is available on PECL. The installation is very simple. Just run:

$ sudo pecl install fann

Manual Installation

For developers and people interested in the latest changes, you can compile the driver from the latest source code on » Github. Go to Github and click the "Download ZIP" button. Then run:

$ unzip php-fann-master.zip
$ cd php-fann-master
$ phpize
$ ./configure
$ make all
$ sudo make install

Make the following changes to php.ini:

  • Make sure the extension_dir variable is pointing to the directory containing fann.so. The build will display where it is installing the PHP driver with output that looks something like:

Installing '/usr/lib/php/extensions/no-debug-non-zts-20060613/fann.so'
    Make sure that it is the same as the PHP extension directory by runnning:

$ php -i | grep extension_dir
  extension_dir => /usr/lib/php/extensions/no-debug-non-zts-20060613 =>
                   /usr/lib/php/extensions/no-debug-non-zts-20060613
    If it's not, change the extension_dir in php.ini or move fann.so.

  • To load the extension on PHP startup, add a line:

extension=fann.so


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.

Training algorithms
FANN_TRAIN_INCREMENTAL (integer)
Standard backpropagation algorithm, where the weights are updated after each training pattern. This means that the weights are updated many times during a single epoch. For this reason some problems, will train very fast with this algorithm, while other more advanced problems will not train very well.
FANN_TRAIN_BATCH (integer)
Standard backpropagation algorithm, where the weights are updated after calculating the mean square error for the whole training set. This means that the weights are only updated once during a epoch. For this reason some problems, will train slower with this algorithm. But since the mean square error is calculated more correctly than in incremental training, some problems will reach a better solutions with this algorithm.
FANN_TRAIN_RPROP (integer)
A more advanced batch training algorithm which achieves good results for many problems. The RPROP training algorithm is adaptive, and does therefore not use the learning_rate. Some other parameters can however be set to change the way the RPROP algorithm works, but it is only recommended for users with insight in how the RPROP training algorithm works. The RPROP training algorithm is described by [Riedmiller and Braun, 1993], but the actual learning algorithm used here is the iRPROP- training algorithm which is described by [Igel and Husken, 2000] which is an variety of the standard RPROP training algorithm.
FANN_TRAIN_QUICKPROP (integer)
A more advanced batch training algorithm which achieves good results for many problems. The quickprop training algorithm uses the learning_rate parameter along with other more advanced parameters, but it is only recommended to change these advanced parameters, for users with insight in how the quickprop training algorithm works. The quickprop training algorithm is described by [Fahlman, 1988].
FANN_TRAIN_SARPROP (integer)
Even more advance training algorithm. Only for version 2.2
Activation functions
FANN_LINEAR (integer)
Linear activation function.
FANN_THRESHOLD (integer)
Threshold activation function.
FANN_THRESHOLD_SYMMETRIC (integer)
Threshold activation function.
FANN_SIGMOID (integer)
Sigmoid activation function.
FANN_SIGMOID_STEPWISE (integer)
Stepwise linear approximation to sigmoid.
FANN_SIGMOID_SYMMETRIC (integer)
Symmetric sigmoid activation function, aka. tanh.
FANN_SIGMOID_SYMMETRIC_STEPWISE (integer)
Stepwise linear approximation to symmetric sigmoid
FANN_GAUSSIAN (integer)
Gaussian activation function.
FANN_GAUSSIAN_SYMMETRIC (integer)
Symmetric gaussian activation function.
FANN_GAUSSIAN_STEPWISE (integer)
Stepwise gaussian activation function.
FANN_ELLIOT (integer)
Fast (sigmoid like) activation function defined by David Elliott.
FANN_ELLIOT_SYMMETRIC (integer)
Fast (symmetric sigmoid like) activation function defined by David Elliott.
FANN_LINEAR_PIECE (integer)
Bounded linear activation function.
FANN_LINEAR_PIECE_SYMMETRIC (integer)
Bounded linear activation function.
FANN_SIN_SYMMETRIC (integer)
Periodical sinus activation function.
FANN_COS_SYMMETRIC (integer)
Periodical cosinus activation function.
FANN_SIN (integer)
Periodical sinus activation function.
FANN_COS (integer)
Periodical cosinus activation function.
Error function used during training
FANN_ERRORFUNC_LINEAR (integer)
Standard linear error function.
FANN_ERRORFUNC_TANH (integer)
Tanh error function, usually better but can require a lower learning rate. This error function agressively targets outputs that differ much from the desired, while not targetting outputs that only differ a little that much. This activation function is not recommended for cascade training and incremental training.
Stop criteria used during training
FANN_STOPFUNC_MSE (integer)
Stop criteria is Mean Square Error (MSE) value.
FANN_STOPFUNC_BIT (integer)
Stop criteria is number of bits that fail. The number of bits means the number of output neurons which differs more than the bit fail limit (see fann_get_bit_fail_limit, fann_set_bit_fail_limit). The bits are counted in all of the training data, so this number can be higher than the number of training data.
Definition of network types used by fann_get_network_type()
FANN_NETTYPE_LAYER (integer)
Each layer only has connections to the next layer.
FANN_NETTYPE_SHORTCUT (integer)
Each layer has connections to all following layers
Errors
FANN_E_NO_ERROR (integer)
No error.
FANN_E_CANT_OPEN_CONFIG_R (integer)
Unable to open configuration file for reading.
FANN_E_CANT_OPEN_CONFIG_W (integer)
Unable to open configuration file for writing.
FANN_E_WRONG_CONFIG_VERSION (integer)
Wrong version of configuration file.
FANN_E_CANT_READ_CONFIG (integer)
Error reading info from configuration file.
FANN_E_CANT_READ_NEURON (integer)
Error reading neuron info from configuration file.
FANN_E_CANT_READ_CONNECTIONS (integer)
Error reading connections from configuration file.
FANN_E_WRONG_NUM_CONNECTIONS (integer)
Number of connections not equal to the number expected.
FANN_E_CANT_OPEN_TD_W (integer)
Unable to open train data file for writing.
FANN_E_CANT_OPEN_TD_R (integer)
Unable to open train data file for reading.
FANN_E_CANT_READ_TD (integer)
Error reading training data from file.
FANN_E_CANT_ALLOCATE_MEM (integer)
Unable to allocate memory.
FANN_E_CANT_TRAIN_ACTIVATION (integer)
Unable to train with the selected activation function.
FANN_E_CANT_USE_ACTIVATION (integer)
Unable to use the selected activation function.
FANN_E_TRAIN_DATA_MISMATCH (integer)
Irreconcilable differences between two struct fann_train_data structures.
FANN_E_CANT_USE_TRAIN_ALG (integer)
Unable to use the selected training algorithm.
FANN_E_TRAIN_DATA_SUBSET (integer)
Trying to take subset which is not within the training set.
FANN_E_INDEX_OUT_OF_BOUND (integer)
Index is out of bound.
FANN_E_SCALE_NOT_PRESENT (integer)
Scaling parameters not present.
FANN_E_INPUT_NO_MATCH (integer)
The number of input neurons in the ann data do not match
FANN_E_OUTPUT_NO_MATCH (integer)
The number of output neurons in the ann and data do not match.


  • « Predefined Constants
  • XOR training »
  • PHP Manual
  • FANN
  • Examples

Examples

Table of Contents

  • XOR training


XOR training

This example shows how to train data for XOR function

Example #1 xor.data file

4 2 1
-1 -1
-1
-1 1
1
1 -1
1
1 1
-1

Example #2 Simple train

<?php
$num_input = 2;
$num_output = 1;
$num_layers = 3;
$num_neurons_hidden = 3;
$desired_error = 0.001;
$max_epochs = 500000;
$epochs_between_reports = 1000;

$ann = fann_create_standard($num_layers, $num_input, $num_neurons_hidden, $num_output);

if ($ann) {
    fann_set_activation_function_hidden($ann, FANN_SIGMOID_SYMMETRIC);
    fann_set_activation_function_output($ann, FANN_SIGMOID_SYMMETRIC);

    $filename = dirname(__FILE__) . "/xor.data";
    if (fann_train_on_file($ann, $filename, $max_epochs, $epochs_between_reports, $desired_error))
        fann_save($ann, dirname(__FILE__) . "/xor_float.net");

    fann_destroy($ann);
}
?>

This example shows how to read and run data for XOR function

Example #3 Simple test

<?php
$train_file = (dirname(__FILE__) . "/xor_float.net");
if (!is_file($train_file))
    die("The file xor_float.net has not been created! Please run simple_train.php to generate it");

$ann = fann_create_from_file($train_file);
if (!$ann)
    die("ANN could not be created");

$input = array(-1, 1);
$calc_out = fann_run($ann, $input);
printf("xor test (%f,%f) -> %f\n", $input[0], $input[1], $calc_out[0]);
fann_destroy($ann);
?>


Fann Functions

Table of Contents

  • fann_cascadetrain_on_data — Trains on an entire dataset, for a period of time using the Cascade2 training algorithm
  • fann_cascadetrain_on_file — Trains on an entire dataset read from file, for a period of time using the Cascade2 training algorithm
  • fann_clear_scaling_params — Clears scaling parameters
  • fann_copy — Creates a copy of a fann structure
  • fann_create_from_file — Constructs a backpropagation neural network from a configuration file
  • fann_create_shortcut_array — Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections
  • fann_create_shortcut — Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections
  • fann_create_sparse_array — Creates a standard backpropagation neural network, which is not fully connected using an array of layer sizes
  • fann_create_sparse — Creates a standard backpropagation neural network, which is not fully connected
  • fann_create_standard_array — Creates a standard fully connected backpropagation neural network using an array of layer sizes
  • fann_create_standard — Creates a standard fully connected backpropagation neural network
  • fann_create_train_from_callback — Creates the training data struct from a user supplied function
  • fann_create_train — Creates an empty training data struct
  • fann_descale_input — Scale data in input vector after get it from ann based on previously calculated parameters
  • fann_descale_output — Scale data in output vector after get it from ann based on previously calculated parameters
  • fann_descale_train — Descale input and output data based on previously calculated parameters
  • fann_destroy_train — Destructs the training data
  • fann_destroy — Destroys the entire network and properly freeing all the associated memory
  • fann_duplicate_train_data — Returns an exact copy of a fann train data
  • fann_get_activation_function — Returns the activation function
  • fann_get_activation_steepness — Returns the activation steepness for supplied neuron and layer number
  • fann_get_bias_array — Get the number of bias in each layer in the network
  • fann_get_bit_fail_limit — Returns the bit fail limit used during training
  • fann_get_bit_fail — The number of fail bits
  • fann_get_cascade_activation_functions_count — Returns the number of cascade activation functions
  • fann_get_cascade_activation_functions — Returns the cascade activation functions
  • fann_get_cascade_activation_steepnesses_count — The number of activation steepnesses
  • fann_get_cascade_activation_steepnesses — Returns the cascade activation steepnesses
  • fann_get_cascade_candidate_change_fraction — Returns the cascade candidate change fraction
  • fann_get_cascade_candidate_limit — Return the candidate limit
  • fann_get_cascade_candidate_stagnation_epochs — Returns the number of cascade candidate stagnation epochs
  • fann_get_cascade_max_cand_epochs — Returns the maximum candidate epochs
  • fann_get_cascade_max_out_epochs — Returns the maximum out epochs
  • fann_get_cascade_min_cand_epochs — Returns the minimum candidate epochs
  • fann_get_cascade_min_out_epochs — Returns the minimum out epochs
  • fann_get_cascade_num_candidate_groups — Returns the number of candidate groups
  • fann_get_cascade_num_candidates — Returns the number of candidates used during training
  • fann_get_cascade_output_change_fraction — Returns the cascade output change fraction
  • fann_get_cascade_output_stagnation_epochs — Returns the number of cascade output stagnation epochs
  • fann_get_cascade_weight_multiplier — Returns the weight multiplier
  • fann_get_connection_array — Get connections in the network
  • fann_get_connection_rate — Get the connection rate used when the network was created
  • fann_get_errno — Returns the last error number
  • fann_get_errstr — Returns the last errstr
  • fann_get_layer_array — Get the number of neurons in each layer in the network
  • fann_get_learning_momentum — Returns the learning momentum
  • fann_get_learning_rate — Returns the learning rate
  • fann_get_MSE — Reads the mean square error from the network
  • fann_get_network_type — Get the type of neural network it was created as
  • fann_get_num_input — Get the number of input neurons
  • fann_get_num_layers — Get the number of layers in the neural network
  • fann_get_num_output — Get the number of output neurons
  • fann_get_quickprop_decay — Returns the decay which is a factor that weights should decrease in each iteration during quickprop training
  • fann_get_quickprop_mu — Returns the mu factor
  • fann_get_rprop_decrease_factor — Returns the increase factor used during RPROP training
  • fann_get_rprop_delta_max — Returns the maximum step-size
  • fann_get_rprop_delta_min — Returns the minimum step-size
  • fann_get_rprop_delta_zero — Returns the initial step-size
  • fann_get_rprop_increase_factor — Returns the increase factor used during RPROP training
  • fann_get_sarprop_step_error_shift — Returns the sarprop step error shift
  • fann_get_sarprop_step_error_threshold_factor — Returns the sarprop step error threshold factor
  • fann_get_sarprop_temperature — Returns the sarprop temperature
  • fann_get_sarprop_weight_decay_shift — Returns the sarprop weight decay shift
  • fann_get_total_connections — Get the total number of connections in the entire network
  • fann_get_total_neurons — Get the total number of neurons in the entire network
  • fann_get_train_error_function — Returns the error function used during training
  • fann_get_train_stop_function — Returns the stop function used during training
  • fann_get_training_algorithm — Returns the training algorithm
  • fann_init_weights — Initialize the weights using Widrow + Nguyen’s algorithm
  • fann_length_train_data — Returns the number of training patterns in the train data
  • fann_merge_train_data — Merges the train data
  • fann_num_input_train_data — Returns the number of inputs in each of the training patterns in the train data
  • fann_num_output_train_data — Returns the number of outputs in each of the training patterns in the train data
  • fann_print_error — Prints the error string
  • fann_randomize_weights — Give each connection a random weight between min_weight and max_weight
  • fann_read_train_from_file — Reads a file that stores training data
  • fann_reset_errno — Resets the last error number
  • fann_reset_errstr — Resets the last error string
  • fann_reset_MSE — Resets the mean square error from the network
  • fann_run — Will run input through the neural network
  • fann_save_train — Save the training structure to a file
  • fann_save — Saves the entire network to a configuration file
  • fann_scale_input_train_data — Scales the inputs in the training data to the specified range
  • fann_scale_input — Scale data in input vector before feed it to ann based on previously calculated parameters
  • fann_scale_output_train_data — Scales the outputs in the training data to the specified range
  • fann_scale_output — Scale data in output vector before feed it to ann based on previously calculated parameters
  • fann_scale_train_data — Scales the inputs and outputs in the training data to the specified range
  • fann_scale_train — Scale input and output data based on previously calculated parameters
  • fann_set_activation_function_hidden — Sets the activation function for all of the hidden layers
  • fann_set_activation_function_layer — Sets the activation function for all the neurons in the supplied layer
  • fann_set_activation_function_output — Sets the activation function for the output layer
  • fann_set_activation_function — Sets the activation function for supplied neuron and layer
  • fann_set_activation_steepness_hidden — Sets the steepness of the activation steepness for all neurons in the all hidden layers
  • fann_set_activation_steepness_layer — Sets the activation steepness for all of the neurons in the supplied layer number
  • fann_set_activation_steepness_output — Sets the steepness of the activation steepness in the output layer
  • fann_set_activation_steepness — Sets the activation steepness for supplied neuron and layer number
  • fann_set_bit_fail_limit — Set the bit fail limit used during training
  • fann_set_callback — Sets the callback function for use during training
  • fann_set_cascade_activation_functions — Sets the array of cascade candidate activation functions
  • fann_set_cascade_activation_steepnesses — Sets the array of cascade candidate activation steepnesses
  • fann_set_cascade_candidate_change_fraction — Sets the cascade candidate change fraction
  • fann_set_cascade_candidate_limit — Sets the candidate limit
  • fann_set_cascade_candidate_stagnation_epochs — Sets the number of cascade candidate stagnation epochs
  • fann_set_cascade_max_cand_epochs — Sets the max candidate epochs
  • fann_set_cascade_max_out_epochs — Sets the maximum out epochs
  • fann_set_cascade_min_cand_epochs — Sets the min candidate epochs
  • fann_set_cascade_min_out_epochs — Sets the minimum out epochs
  • fann_set_cascade_num_candidate_groups — Sets the number of candidate groups
  • fann_set_cascade_output_change_fraction — Sets the cascade output change fraction
  • fann_set_cascade_output_stagnation_epochs — Sets the number of cascade output stagnation epochs
  • fann_set_cascade_weight_multiplier — Sets the weight multiplier
  • fann_set_error_log — Sets where the errors are logged to
  • fann_set_input_scaling_params — Calculate input scaling parameters for future use based on training data
  • fann_set_learning_momentum — Sets the learning momentum
  • fann_set_learning_rate — Sets the learning rate
  • fann_set_output_scaling_params — Calculate output scaling parameters for future use based on training data
  • fann_set_quickprop_decay — Sets the quickprop decay factor
  • fann_set_quickprop_mu — Sets the quickprop mu factor
  • fann_set_rprop_decrease_factor — Sets the decrease factor used during RPROP training
  • fann_set_rprop_delta_max — Sets the maximum step-size
  • fann_set_rprop_delta_min — Sets the minimum step-size
  • fann_set_rprop_delta_zero — Sets the initial step-size
  • fann_set_rprop_increase_factor — Sets the increase factor used during RPROP training
  • fann_set_sarprop_step_error_shift — Sets the sarprop step error shift
  • fann_set_sarprop_step_error_threshold_factor — Sets the sarprop step error threshold factor
  • fann_set_sarprop_temperature — Sets the sarprop temperature
  • fann_set_sarprop_weight_decay_shift — Sets the sarprop weight decay shift
  • fann_set_scaling_params — Calculate input and output scaling parameters for future use based on training data
  • fann_set_train_error_function — Sets the error function used during training
  • fann_set_train_stop_function — Sets the stop function used during training
  • fann_set_training_algorithm — Sets the training algorithm
  • fann_set_weight_array — Set connections in the network
  • fann_set_weight — Set a connection in the network
  • fann_shuffle_train_data — Shuffles training data, randomizing the order
  • fann_subset_train_data — Returns an copy of a subset of the train data
  • fann_test_data — Test a set of training data and calculates the MSE for the training data
  • fann_test — Test with a set of inputs, and a set of desired outputs
  • fann_train_epoch — Train one epoch with a set of training data
  • fann_train_on_data — Trains on an entire dataset for a period of time
  • fann_train_on_file — Trains on an entire dataset, which is read from file, for a period of time
  • fann_train — Train one iteration with a set of inputs, and a set of desired outputs


Trains on an entire dataset, for a period of time using the Cascade2 training algorithm

  • « Fann Functions
  • fann_cascadetrain_on_file »
  • PHP Manual
  • Fann Functions
  • Trains on an entire dataset, for a period of time using the Cascade2 training algorithm

fann_cascadetrain_on_data

(PECL fann >= 1.0.0)

fann_cascadetrain_on_data — Trains on an entire dataset, for a period of time using the Cascade2 training algorithm

Description

fann_cascadetrain_on_data ( resource $ann , resource $data , int $max_neurons , int $neurons_between_reports , float $desired_error ) : bool

The cascade output change fraction is a number between 0 and 1 determining how large a fraction the fann_get_MSE() value should change within fann_get_cascade_output_stagnation_epochs() during training of the output connections, in order for the training not to stagnate. If the training stagnates, the training of the output connections will be ended and new candidates will be prepared.

This training uses the parameters set using the fann_set_cascade_..., but it also uses another training algorithm as it’s internal training algorithm. This algorithm can be set to either FANN_TRAIN_RPROP or FANN_TRAIN_QUICKPROP by fann_set_training_algorithm(), and the parameters set for these training algorithms will also affect the cascade training.

Parameters

ann

Neural network resource.

data

Neural network training data resource.

max_neurons

The maximum number of neurons to be added to neural network.

neurons_between_reports

The number of neurons between printing a status report. A value of zero means no reports should be printed.

desired_error

The desired fann_get_MSE() or fann_get_bit_fail(), depending on which stop function is chosen by fann_set_train_stop_function()

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_train_on_data() - Trains on an entire dataset for a period of time
  • fann_cascadetrain_on_file() - Trains on an entire dataset read from file, for a period of time using the Cascade2 training algorithm


Trains on an entire dataset read from file, for a period of time using the Cascade2 training algorithm

  • « fann_cascadetrain_on_data
  • fann_clear_scaling_params »
  • PHP Manual
  • Fann Functions
  • Trains on an entire dataset read from file, for a period of time using the Cascade2 training algorithm

fann_cascadetrain_on_file

(PECL fann >= 1.0.0)

fann_cascadetrain_on_file — Trains on an entire dataset read from file, for a period of time using the Cascade2 training algorithm

Description

fann_cascadetrain_on_file ( resource $ann , string $filename , int $max_neurons , int $neurons_between_reports , float $desired_error ) : bool

Does the same as fann_cascadetrain_on_data(), but reads the training data directly from a file.

Parameters

ann

Neural network resource.

filename

A file containing the data for training.

max_neurons

The maximum number of neurons to be added to neural network

neurons_between_reports

The number of neurons between printing a status report. A value of zero means no reports should be printed.

desired_error

The desired fann_get_MSE() or fann_get_bit_fail(), depending on which stop function is chosen by fann_set_train_stop_function().

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_train_on_data() - Trains on an entire dataset for a period of time
  • fann_cascadetrain_on_data() - Trains on an entire dataset, for a period of time using the Cascade2 training algorithm


Clears scaling parameters

  • « fann_cascadetrain_on_file
  • fann_copy »
  • PHP Manual
  • Fann Functions
  • Clears scaling parameters

fann_clear_scaling_params

(PECL fann >= 1.0.0)

fann_clear_scaling_params — Clears scaling parameters

Description

fann_clear_scaling_params ( resource $ann ) : bool

Clears scaling parameters.

Parameters

ann

Neural network resource.

Return Values

Returns TRUE on success, or FALSE otherwise.


Creates a copy of a fann structure

  • « fann_clear_scaling_params
  • fann_create_from_file »
  • PHP Manual
  • Fann Functions
  • Creates a copy of a fann structure

fann_copy

(PECL fann >= 1.0.0)

fann_copy — Creates a copy of a fann structure

Description

fann_copy ( resource $ann ) : resource

Creates a copy of a fann structure.

Parameters

ann

Neural network resource.

Return Values

Returns a copy of neural network resource on success, or FALSE on error

See Also

  • fann_test() - Test with a set of inputs, and a set of desired outputs


Constructs a backpropagation neural network from a configuration file

  • « fann_copy
  • fann_create_shortcut_array »
  • PHP Manual
  • Fann Functions
  • Constructs a backpropagation neural network from a configuration file

fann_create_from_file

(PECL fann >= 1.0.0)

fann_create_from_file — Constructs a backpropagation neural network from a configuration file

Description

fann_create_from_file ( string $configuration_file ) : resource

Constructs a backpropagation neural network from a configuration file, which have been saved by fann_save().

Parameters

configuration_file

The configuration file path.

Return Values

Returns a neural network resource on success, or FALSE on error.

See Also

  • fann_save() - Saves the entire network to a configuration file


Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections

  • « fann_create_from_file
  • fann_create_shortcut »
  • PHP Manual
  • Fann Functions
  • Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections

fann_create_shortcut_array

(PECL fann >= 1.0.0)

fann_create_shortcut_array — Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections

Description

fann_create_shortcut_array ( int $num_layers , array $layers ) : resource

Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections using an array of layers sizes.

Parameters

num_layers

The total number of layers including the input and the output layer.

layers

An array of layers sizes.

Return Values

Returns a neural network resource on success, or FALSE on error.

See Also

  • fann_create_shortcut() - Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections
  • fann_create_sparse() - Creates a standard backpropagation neural network, which is not fully connected
  • fann_create_standard() - Creates a standard fully connected backpropagation neural network


Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections

  • « fann_create_shortcut_array
  • fann_create_sparse_array »
  • PHP Manual
  • Fann Functions
  • Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections

fann_create_shortcut

(PECL fann >= 1.0.0)

fann_create_shortcut — Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections

Description

fann_create_shortcut ( int $num_layers , int $num_neurons1 , int $num_neurons2 [, int $... ] ) : resource

Creates a standard backpropagation neural network, which is not fully connected and which also has shortcut connections.

Shortcut connections are connections that skip layers. A fully connected network with shortcut connections, is a network where all neurons are connected to all neurons in later layers. Including direct connections from the input layer to the output layer.

Parameters

num_layers

The total number of layers including the input and the output layer.

num_neurons1

Number of neurons in the first layer.

num_neurons2

Number of neurons in the second layer.

...

Number of neurons in other layers.

Return Values

Returns a neural network resource on success, or FALSE on error.

See Also

  • fann_create_shortcut_array() - Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections
  • fann_create_sparse() - Creates a standard backpropagation neural network, which is not fully connected
  • fann_create_standard() - Creates a standard fully connected backpropagation neural network


Creates a standard backpropagation neural network, which is not fully connected using an array of layer sizes

  • « fann_create_shortcut
  • fann_create_sparse »
  • PHP Manual
  • Fann Functions
  • Creates a standard backpropagation neural network, which is not fully connected using an array of layer sizes

fann_create_sparse_array

(PECL fann >= 1.0.0)

fann_create_sparse_array — Creates a standard backpropagation neural network, which is not fully connected using an array of layer sizes

Description

fann_create_sparse_array ( float $connection_rate , int $num_layers , array $layers ) : resource

Creates a standard backpropagation neural network, which is not fully connected using an array of layer sizes.

Parameters

connection_rate

The connection rate controls how many connections there will be in the network. If the connection rate is set to 1, the network will be fully connected, but if it is set to 0.5 only half of the connections will be set. A connection rate of 1 will yield the same result as fann_create_standard().

num_layers

The total number of layers including the input and the output layer.

layers

An array of layer sizes.

Return Values

Returns a neural network resource on success, or FALSE on error.

See Also

  • fann_create_sparse() - Creates a standard backpropagation neural network, which is not fully connected
  • fann_create_standard() - Creates a standard fully connected backpropagation neural network
  • fann_create_shortcut() - Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections


Creates a standard backpropagation neural network, which is not fully connected

  • « fann_create_sparse_array
  • fann_create_standard_array »
  • PHP Manual
  • Fann Functions
  • Creates a standard backpropagation neural network, which is not fully connected

fann_create_sparse

(PECL fann >= 1.0.0)

fann_create_sparse — Creates a standard backpropagation neural network, which is not fully connected

Description

fann_create_sparse ( float $connection_rate , int $num_layers , int $num_neurons1 , int $num_neurons2 [, int $... ] ) : resource

Creates a standard backpropagation neural network, which is not fully connected.

Parameters

connection_rate

The connection rate controls how many connections there will be in the network. If the connection rate is set to 1, the network will be fully connected, but if it is set to 0.5 only half of the connections will be set. A connection rate of 1 will yield the same result as fann_create_standard().

num_layers

The total number of layers including the input and the output layer.

num_neurons1

Number of neurons in the first layer.

num_neurons2

Number of neurons in the second layer.

...

Number of neurons in other layers.

Return Values

Returns a neural network resource on success, or FALSE on error.

See Also

  • fann_create_sparse_array() - Creates a standard backpropagation neural network, which is not fully connected using an array of layer sizes
  • fann_create_standard() - Creates a standard fully connected backpropagation neural network
  • fann_create_shortcut() - Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections


Creates a standard fully connected backpropagation neural network using an array of layer sizes

  • « fann_create_sparse
  • fann_create_standard »
  • PHP Manual
  • Fann Functions
  • Creates a standard fully connected backpropagation neural network using an array of layer sizes

fann_create_standard_array

(PECL fann >= 1.0.0)

fann_create_standard_array — Creates a standard fully connected backpropagation neural network using an array of layer sizes

Description

fann_create_standard_array ( int $num_layers , array $layers ) : resource

Creates a standard fully connected backpropagation neural network.

There will be a bias neuron in each layer (except the output layer), and this bias neuron will be connected to all neurons in the next layer. When running the network, the bias nodes always emits 1.

To destroy a neural network use the fann_destroy() function.

Parameters

num_layers

The total number of layers including the input and the output layer.

layers

An array of layer sizes.

Return Values

Returns a neural network resource on success, or FALSE on error.

See Also

  • fann_create_standard() - Creates a standard fully connected backpropagation neural network
  • fann_create_sparse() - Creates a standard backpropagation neural network, which is not fully connected
  • fann_create_shortcut() - Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections


Creates a standard fully connected backpropagation neural network

  • « fann_create_standard_array
  • fann_create_train_from_callback »
  • PHP Manual
  • Fann Functions
  • Creates a standard fully connected backpropagation neural network

fann_create_standard

(PECL fann >= 1.0.0)

fann_create_standard — Creates a standard fully connected backpropagation neural network

Description

fann_create_standard ( int $num_layers , int $num_neurons1 , int $num_neurons2 [, int $... ] ) : resource

Creates a standard fully connected backpropagation neural network.

There will be a bias neuron in each layer (except the output layer), and this bias neuron will be connected to all neurons in the next layer. When running the network, the bias nodes always emits 1.

To destroy a neural network use the fann_destroy() function.

Parameters

num_layers

The total number of layers including the input and the output layer.

num_neurons1

Number of neurons in the first layer.

num_neurons2

Number of neurons in the second layer.

...

Number of neurons in other layers.

Return Values

Returns a neural network resource on success, or FALSE on error.

See Also

  • fann_create_standard_array() - Creates a standard fully connected backpropagation neural network using an array of layer sizes
  • fann_create_sparse() - Creates a standard backpropagation neural network, which is not fully connected
  • fann_create_shortcut() - Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections


Creates the training data struct from a user supplied function

  • « fann_create_standard
  • fann_create_train »
  • PHP Manual
  • Fann Functions
  • Creates the training data struct from a user supplied function

fann_create_train_from_callback

(PECL fann >= 1.0.0)

fann_create_train_from_callback — Creates the training data struct from a user supplied function

Description

fann_create_train_from_callback ( int $num_data , int $num_input , int $num_output , callable $user_function ) : resource

Creates the training data struct from a user supplied function. As the training data are numerable (data 1, data 2...), the user must write a function that receives the number of the training data set (input, output) and returns the set.

Parameters

num_data

The number of training data

num_input

The number of inputs per training data

num_output

The number of ouputs per training data

user_function

The user supplied function with following parameters:

  • num - The number of the training data set
  • num_input - The number of inputs per training data
  • num_output - The number of ouputs per training data

The function should return an associative array with keys input and output and two array values of input and output.

Return Values

Returns a train data resource on success, or FALSE on error.

Examples

Example #1 fann_create_train_from_callback() example

<?php
function create_train_callback($num_data, $num_input, $num_output) {
    return array(
        "input" => array_fill(0, $num_input, 1),
        "output" => array_fill(0, $num_output, 1),
    );
}

$num_data = 3;
$num_input = 2;
$num_output = 1;
$train_data = fann_create_train_from_callback($num_data, $num_input, $num_output, "create_train_callback");
if ($train_data) {
    // Do something with $train_data
}
?>

See Also

  • fann_read_train_from_file() - Reads a file that stores training data
  • fann_train_on_data() - Trains on an entire dataset for a period of time
  • fann_destroy_train() - Destructs the training data
  • fann_save_train() - Save the training structure to a file


Creates an empty training data struct

  • « fann_create_train_from_callback
  • fann_descale_input »
  • PHP Manual
  • Fann Functions
  • Creates an empty training data struct

fann_create_train

(PECL fann >= 1.0.0)

fann_create_train — Creates an empty training data struct

Description

fann_create_train ( int $num_data , int $num_input , int $num_output ) : resource

Creates an empty training data struct.

Parameters

num_data

The number of training data

num_input

The number of inputs per training data

num_output

The number of ouputs per training data

Return Values

Returns a train data resource on success, or FALSE on error.

See Also

  • fann_read_train_from_file() - Reads a file that stores training data
  • fann_train_on_data() - Trains on an entire dataset for a period of time
  • fann_destroy_train() - Destructs the training data
  • fann_save_train() - Save the training structure to a file


Scale data in input vector after get it from ann based on previously calculated parameters

  • « fann_create_train
  • fann_descale_output »
  • PHP Manual
  • Fann Functions
  • Scale data in input vector after get it from ann based on previously calculated parameters

fann_descale_input

(PECL fann >= 1.0.0)

fann_descale_input — Scale data in input vector after get it from ann based on previously calculated parameters

Description

fann_descale_input ( resource $ann , array $input_vector ) : bool

Scale data in input vector after get it from ann based on previously calculated parameters.

Parameters

ann

Neural network resource.

input_vector

Input vector that will be descaled

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_scale_input() - Scale data in input vector before feed it to ann based on previously calculated parameters
  • fann_descale_output() - Scale data in output vector after get it from ann based on previously calculated parameters


Scale data in output vector after get it from ann based on previously calculated parameters

  • « fann_descale_input
  • fann_descale_train »
  • PHP Manual
  • Fann Functions
  • Scale data in output vector after get it from ann based on previously calculated parameters

fann_descale_output

(PECL fann >= 1.0.0)

fann_descale_output — Scale data in output vector after get it from ann based on previously calculated parameters

Description

fann_descale_output ( resource $ann , array $output_vector ) : bool

Scale data in output vector after get it from ann based on previously calculated parameters.

Parameters

ann

Neural network resource.

output_vector

Output vector that will be descaled

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_scale_output() - Scale data in output vector before feed it to ann based on previously calculated parameters
  • fann_descale_input() - Scale data in input vector after get it from ann based on previously calculated parameters


Descale input and output data based on previously calculated parameters

  • « fann_descale_output
  • fann_destroy_train »
  • PHP Manual
  • Fann Functions
  • Descale input and output data based on previously calculated parameters

fann_descale_train

(PECL fann >= 1.0.0)

fann_descale_train — Descale input and output data based on previously calculated parameters

Description

fann_descale_train ( resource $ann , resource $train_data ) : bool

Descale input and output data based on previously calculated parameters.

Parameters

ann

Neural network resource.

train_data

Neural network training data resource.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_scale_train() - Scale input and output data based on previously calculated parameters
  • fann_set_scaling_params() - Calculate input and output scaling parameters for future use based on training data


Destructs the training data

  • « fann_descale_train
  • fann_destroy »
  • PHP Manual
  • Fann Functions
  • Destructs the training data

fann_destroy_train

(PECL fann >= 1.0.0)

fann_destroy_train — Destructs the training data

Description

fann_destroy_train ( resource $train_data ) : bool

Destructs the training data

Parameters

train_data

Neural network training data resource.

Return Values

Returns TRUE on success, or FALSE otherwise.


Destroys the entire network and properly freeing all the associated memory

  • « fann_destroy_train
  • fann_duplicate_train_data »
  • PHP Manual
  • Fann Functions
  • Destroys the entire network and properly freeing all the associated memory

fann_destroy

(PECL fann >= 1.0.0)

fann_destroy — Destroys the entire network and properly freeing all the associated memory

Description

fann_destroy ( resource $ann ) : bool

Destroys the entire network and properly freeing all the associated memory.

Parameters

ann

Neural network resource.

Return Values

Returns TRUE on success, or FALSE otherwise.


Returns an exact copy of a fann train data

  • « fann_destroy
  • fann_get_activation_function »
  • PHP Manual
  • Fann Functions
  • Returns an exact copy of a fann train data

fann_duplicate_train_data

(PECL fann >= 1.0.0)

fann_duplicate_train_data — Returns an exact copy of a fann train data

Description

fann_duplicate_train_data ( resource $data ) : resource

Returns an exact copy of a fann train data resource.

Parameters

data

Neural network training data resource.

Return Values

Returns a train data resource on success, or FALSE on error.


Returns the activation function

  • « fann_duplicate_train_data
  • fann_get_activation_steepness »
  • PHP Manual
  • Fann Functions
  • Returns the activation function

fann_get_activation_function

(PECL fann >= 1.0.0)

fann_get_activation_function — Returns the activation function

Description

fann_get_activation_function ( resource $ann , int $layer , int $neuron ) : int

Get the activation function for neuron number neuron in layer number layer, counting the input layer as layer 0.

It is not possible to get activation functions for the neurons in the input layer.

The return value is one of the activation functions constants.

Parameters

ann

Neural network resource.

layer

Layer number.

neuron

Neuron number.

Return Values

Learning functions constant or -1 if the neuron is not defined in the neural network, or FALSE on error.

See Also

  • fann_set_activation_function_layer() - Sets the activation function for all the neurons in the supplied layer
  • fann_set_activation_function_hidden() - Sets the activation function for all of the hidden layers
  • fann_set_activation_function_output() - Sets the activation function for the output layer
  • fann_set_activation_steepness() - Sets the activation steepness for supplied neuron and layer number
  • fann_set_activation_function() - Sets the activation function for supplied neuron and layer


Returns the activation steepness for supplied neuron and layer number

  • « fann_get_activation_function
  • fann_get_bias_array »
  • PHP Manual
  • Fann Functions
  • Returns the activation steepness for supplied neuron and layer number

fann_get_activation_steepness

(PECL fann >= 1.0.0)

fann_get_activation_steepness — Returns the activation steepness for supplied neuron and layer number

Description

fann_get_activation_steepness ( resource $ann , int $layer , int $neuron ) : float

Get the activation steepness for neuron number neuron in layer number layer, counting the input layer as layer 0.

It is not possible to get activation steepness for the neurons in the input layer.

The steepness of an activation function says something about how fast the activation function goes from the minimum to the maximum. A high value for the activation function will also give a more agressive training.

When training neural networks where the output values should be at the extremes (usually 0 and 1, depending on the activation function), a steep activation function can be used (e.g. 1.0).

The default activation steepness is 0.5.

Parameters

ann

Neural network resource.

layer

Layer number

neuron

Neuron number

Return Values

The activation steepness for the neuron or -1 if the neuron is not defined in the neural network, or FALSE on error.

See Also

  • fann_set_activation_function() - Sets the activation function for supplied neuron and layer
  • fann_set_activation_steepness_layer() - Sets the activation steepness for all of the neurons in the supplied layer number
  • fann_set_activation_steepness_hidden() - Sets the steepness of the activation steepness for all neurons in the all hidden layers
  • fann_set_activation_steepness_output() - Sets the steepness of the activation steepness in the output layer
  • fann_set_activation_steepness() - Sets the activation steepness for supplied neuron and layer number


Get the number of bias in each layer in the network

  • « fann_get_activation_steepness
  • fann_get_bit_fail_limit »
  • PHP Manual
  • Fann Functions
  • Get the number of bias in each layer in the network

fann_get_bias_array

(PECL fann >= 1.0.0)

fann_get_bias_array — Get the number of bias in each layer in the network

Description

fann_get_bias_array ( resource $ann ) : array

Get the number of bias in each layer in the network.

Parameters

ann

Neural network resource.

Return Values

An array of numbers of bias in each layer


Returns the bit fail limit used during training

  • « fann_get_bias_array
  • fann_get_bit_fail »
  • PHP Manual
  • Fann Functions
  • Returns the bit fail limit used during training

fann_get_bit_fail_limit

(PECL fann >= 1.0.0)

fann_get_bit_fail_limit — Returns the bit fail limit used during training

Description

fann_get_bit_fail_limit ( resource $ann ) : float

Returns the bit fail limit used during training.

The bit fail limit is used during training where the stop function is set to FANN_STOPFUNC_BIT.

The limit is the maximum accepted difference between the desired output and the actual output during training. Each output that diverges more than this limit is counted as an error bit. This difference is divided by two when dealing with symmetric activation functions, so that symmetric and not symmetric activation functions can use the same limit.

The default bit fail limit is 0.35.

Parameters

ann

Neural network resource.

Return Values

The bit fail limit, or FALSE on error.

See Also

  • fann_set_bit_fail_limit() - Set the bit fail limit used during training


The number of fail bits

  • « fann_get_bit_fail_limit
  • fann_get_cascade_activation_functions_count »
  • PHP Manual
  • Fann Functions
  • The number of fail bits

fann_get_bit_fail

(PECL fann >= 1.0.0)

fann_get_bit_fail — The number of fail bits

Description

fann_get_bit_fail ( resource $ann ) : int

The number of fail bits; means the number of output neurons which differ more than the bit fail limit (see fann_get_bit_fail_limit(), fann_set_bit_fail_limit()). The bits are counted in all of the training data, so this number can be higher than the number of training data.

This value is reset by fann_reset_MSE() and updated by all the same functions which also updates the MSE value (e.g. fann_test_data(), fann_train_epoch())

Parameters

ann

Neural network resource.

Return Values

The number of bits fail, or FALSE on error.

See Also

  • fann_get_MSE() - Reads the mean square error from the network
  • fann_reset_MSE() - Resets the mean square error from the network
  • fann_test_data() - Test a set of training data and calculates the MSE for the training data
  • fann_train_epoch() - Train one epoch with a set of training data
  • fann_get_bit_fail_limit() - Returns the bit fail limit used during training
  • fann_set_bit_fail_limit() - Set the bit fail limit used during training


Returns the number of cascade activation functions

  • « fann_get_bit_fail
  • fann_get_cascade_activation_functions »
  • PHP Manual
  • Fann Functions
  • Returns the number of cascade activation functions

fann_get_cascade_activation_functions_count

(PECL fann >= 1.0.0)

fann_get_cascade_activation_functions_count — Returns the number of cascade activation functions

Description

fann_get_cascade_activation_functions_count ( resource $ann ) : int

The number of activation functions in the fann_get_cascade_activation_functions() array.

The default number of activation functions is 6.

Parameters

ann

Neural network resource.

Return Values

The number of cascade activation functions, or FALSE on error.

See Also

  • fann_get_cascade_activation_functions() - Returns the cascade activation functions
  • fann_set_cascade_activation_functions() - Sets the array of cascade candidate activation functions


Returns the cascade activation functions

  • « fann_get_cascade_activation_functions_count
  • fann_get_cascade_activation_steepnesses_count »
  • PHP Manual
  • Fann Functions
  • Returns the cascade activation functions

fann_get_cascade_activation_functions

(PECL fann >= 1.0.0)

fann_get_cascade_activation_functions — Returns the cascade activation functions

Description

fann_get_cascade_activation_functions ( resource $ann ) : array

The cascade activation functions array is an array of the different activation functions used by the candidates

See fann_get_cascade_num_candidates() for a description of which candidate neurons will be generated by this array.

The default activation functions are FANN_SIGMOID, FANN_SIGMOID_SYMMETRIC, FANN_GAUSSIAN, FANN_GAUSSIAN_SYMMETRIC, FANN_ELLIOT, FANN_ELLIOT_SYMMETRIC.

Parameters

ann

Neural network resource.

Return Values

The cascade activation functions, or FALSE on error.

See Also

  • fann_get_cascade_activation_functions_count() - Returns the number of cascade activation functions
  • fann_set_cascade_activation_functions() - Sets the array of cascade candidate activation functions


The number of activation steepnesses

  • « fann_get_cascade_activation_functions
  • fann_get_cascade_activation_steepnesses »
  • PHP Manual
  • Fann Functions
  • The number of activation steepnesses

fann_get_cascade_activation_steepnesses_count

(PECL fann >= 1.0.0)

fann_get_cascade_activation_steepnesses_count — The number of activation steepnesses

Description

fann_get_cascade_activation_steepnesses_count ( resource $ann ) : int

The number of activation steepnesses in the fann_get_cascade_activation_functions() array.

The default number of activation steepnesses is 4.

Parameters

ann

Neural network resource.

Return Values

The number of activation steepnesses, or FALSE on error.

See Also

  • fann_get_cascade_activation_steepnesses() - Returns the cascade activation steepnesses
  • fann_set_cascade_activation_functions() - Sets the array of cascade candidate activation functions


Returns the cascade activation steepnesses

  • « fann_get_cascade_activation_steepnesses_count
  • fann_get_cascade_candidate_change_fraction »
  • PHP Manual
  • Fann Functions
  • Returns the cascade activation steepnesses

fann_get_cascade_activation_steepnesses

(PECL fann >= 1.0.0)

fann_get_cascade_activation_steepnesses — Returns the cascade activation steepnesses

Description

fann_get_cascade_activation_steepnesses ( resource $ann ) : array

The cascade activation steepnesses array is an array of the different activation functions used by the candidates.

See fann_get_cascade_num_candidates() for a description of which candidate neurons will be generated by this array.

The default activation steepnesses are {0.25, 0.50, 0.75, 1.00}.

Parameters

ann

Neural network resource.

Return Values

The cascade activation steepnesses, or FALSE on error.

See Also

  • fann_get_cascade_activation_steepnesses_count() - The number of activation steepnesses
  • fann_set_cascade_activation_steepnesses() - Sets the array of cascade candidate activation steepnesses


Returns the cascade candidate change fraction

  • « fann_get_cascade_activation_steepnesses
  • fann_get_cascade_candidate_limit »
  • PHP Manual
  • Fann Functions
  • Returns the cascade candidate change fraction

fann_get_cascade_candidate_change_fraction

(PECL fann >= 1.0.0)

fann_get_cascade_candidate_change_fraction — Returns the cascade candidate change fraction

Description

fann_get_cascade_candidate_change_fraction ( resource $ann ) : float

The cascade candidate change fraction is a number between 0 and 1 determining how large a fraction the fann_get_MSE() value should change within fann_get_cascade_candidate_stagnation_epochs() during training of the candidate neurons, in order for the training not to stagnate. If the training stagnates, the training of the candidate neurons will be ended and the best candidate will be selected.

It means that if the MSE does not change by a fraction of fann_get_cascade_candidate_change_fraction() during a period of fann_get_cascade_candidate_stagnation_epochs(), the training of the candidate neurons is stopped because the training has stagnated.

If the cascade candidate change fraction is low, the candidate neurons will be trained more and if the fraction is high they will be trained less.

The default cascade candidate change fraction is 0.01, which is equalent to a 1% change in MSE.

Parameters

ann

Neural network resource.

Return Values

The cascade candidate change fraction, or FALSE on error.

See Also

  • fann_set_cascade_candidate_change_fraction() - Sets the cascade candidate change fraction
  • fann_get_MSE() - Reads the mean square error from the network
  • fann_get_cascade_candidate_stagnation_epochs() - Returns the number of cascade candidate stagnation epochs


Return the candidate limit

  • « fann_get_cascade_candidate_change_fraction
  • fann_get_cascade_candidate_stagnation_epochs »
  • PHP Manual
  • Fann Functions
  • Return the candidate limit

fann_get_cascade_candidate_limit

(PECL fann >= 1.0.0)

fann_get_cascade_candidate_limit — Return the candidate limit

Description

fann_get_cascade_candidate_limit ( resource $ann ) : float

The candidate limit is a limit for how much the candidate neuron may be trained. The limit is a limit on the proportion between the MSE and candidate score.

Set this to a lower value to avoid overfitting and to a higher if overfitting is not a problem.

The default candidate limit is 1000.0.

Parameters

ann

Neural network resource.

Return Values

The candidate limit, or FALSE on error.

See Also

  • fann_set_cascade_candidate_limit() - Sets the candidate limit


Returns the number of cascade candidate stagnation epochs

  • « fann_get_cascade_candidate_limit
  • fann_get_cascade_max_cand_epochs »
  • PHP Manual
  • Fann Functions
  • Returns the number of cascade candidate stagnation epochs

fann_get_cascade_candidate_stagnation_epochs

(PECL fann >= 1.0.0)

fann_get_cascade_candidate_stagnation_epochs — Returns the number of cascade candidate stagnation epochs

Description

fann_get_cascade_candidate_stagnation_epochs ( resource $ann ) : int

The number of cascade candidate stagnation epochs determines the number of epochs training is allowed to continue without changing the MSE by a fraction of fann_get_cascade_candidate_change_fraction().

See more info about this parameter in fann_get_cascade_candidate_change_fraction().

The default number of cascade candidate stagnation epochs is 12.

Parameters

ann

Neural network resource.

Return Values

The number of cascade candidate stagnation epochs, or FALSE on error.

See Also

  • fann_set_cascade_candidate_stagnation_epochs() - Sets the number of cascade candidate stagnation epochs
  • fann_get_cascade_candidate_change_fraction() - Returns the cascade candidate change fraction


Returns the maximum candidate epochs

  • « fann_get_cascade_candidate_stagnation_epochs
  • fann_get_cascade_max_out_epochs »
  • PHP Manual
  • Fann Functions
  • Returns the maximum candidate epochs

fann_get_cascade_max_cand_epochs

(PECL fann >= 1.0.0)

fann_get_cascade_max_cand_epochs — Returns the maximum candidate epochs

Description

fann_get_cascade_max_cand_epochs ( resource $ann ) : int

The maximum candidate epochs determines the maximum number of epochs the input connections to the candidates may be trained before adding a new candidate neuron.

The default max candidate epochs is 150.

Parameters

ann

Neural network resource.

Return Values

The maximum candidate epochs, or FALSE on error.

See Also

  • fann_set_cascade_max_cand_epochs() - Sets the max candidate epochs


Returns the maximum out epochs

  • « fann_get_cascade_max_cand_epochs
  • fann_get_cascade_min_cand_epochs »
  • PHP Manual
  • Fann Functions
  • Returns the maximum out epochs

fann_get_cascade_max_out_epochs

(PECL fann >= 1.0.0)

fann_get_cascade_max_out_epochs — Returns the maximum out epochs

Description

fann_get_cascade_max_out_epochs ( resource $ann ) : int

The maximum out epochs determines the maximum number of epochs the output connections may be trained after adding a new candidate neuron.

The default max out epochs is 150.

Parameters

ann

Neural network resource.

Return Values

The maximum out epochs, or FALSE on error.

See Also

  • fann_set_cascade_max_out_epochs() - Sets the maximum out epochs


Returns the minimum candidate epochs

  • « fann_get_cascade_max_out_epochs
  • fann_get_cascade_min_out_epochs »
  • PHP Manual
  • Fann Functions
  • Returns the minimum candidate epochs

fann_get_cascade_min_cand_epochs

(PECL fann >= 1.0.0)

fann_get_cascade_min_cand_epochs — Returns the minimum candidate epochs

Description

fann_get_cascade_min_cand_epochs ( resource $ann ) : int

The minimum candidate epochs determines the minimum number of epochs the input connections to the candidates may be trained before adding a new candidate neuron.

The default min candidate epochs is 50.

Parameters

ann

Neural network resource.

Return Values

The minimum candidate epochs, or FALSE on error.

See Also

  • fann_set_cascade_min_cand_epochs() - Sets the min candidate epochs


Returns the minimum out epochs

  • « fann_get_cascade_min_cand_epochs
  • fann_get_cascade_num_candidate_groups »
  • PHP Manual
  • Fann Functions
  • Returns the minimum out epochs

fann_get_cascade_min_out_epochs

(PECL fann >= 1.0.0)

fann_get_cascade_min_out_epochs — Returns the minimum out epochs

Description

fann_get_cascade_min_out_epochs ( resource $ann ) : int

The minimum out epochs determines the minimum number of epochs the output connections must be trained after adding a new candidate neuron.

The default min out epochs is 50.

Parameters

ann

Neural network resource.

Return Values

The minimum out epochs, or FALSE on error.

See Also

  • fann_set_cascade_min_out_epochs() - Sets the minimum out epochs


Returns the number of candidate groups

  • « fann_get_cascade_min_out_epochs
  • fann_get_cascade_num_candidates »
  • PHP Manual
  • Fann Functions
  • Returns the number of candidate groups

fann_get_cascade_num_candidate_groups

(PECL fann >= 1.0.0)

fann_get_cascade_num_candidate_groups — Returns the number of candidate groups

Description

fann_get_cascade_num_candidate_groups ( resource $ann ) : int

The number of candidate groups is the number of groups of identical candidates which will be used during training.

This number can be used to have more candidates without having to define new parameters for the candidates.

See fann_get_cascade_num_candidates() for a description of which candidate neurons will be generated by this parameter.

The default number of candidate groups is 2.

Parameters

ann

Neural network resource.

Return Values

The number of candidate groups, or FALSE on error.

See Also

  • fann_set_cascade_num_candidate_groups() - Sets the number of candidate groups


Returns the number of candidates used during training

  • « fann_get_cascade_num_candidate_groups
  • fann_get_cascade_output_change_fraction »
  • PHP Manual
  • Fann Functions
  • Returns the number of candidates used during training

fann_get_cascade_num_candidates

(PECL fann >= 1.0.0)

fann_get_cascade_num_candidates — Returns the number of candidates used during training

Description

fann_get_cascade_num_candidates ( resource $ann ) : int

The number of candidates used during training (calculated by multiplying
fann_get_cascade_activation_functions_count(),
fann_get_cascade_activation_steepnesses_count() and
fann_get_cascade_num_candidate_groups()).

The actual candidates is defined by the fann_get_cascade_activation_functions() and fann_get_cascade_activation_steepnesses() arrays. These arrays define the activation functions and activation steepnesses used for the candidate neurons. If there are 2 activation functions in the activation function array and 3 steepnesses in the steepness array, then there will be 2x3=6 different candidates which will be trained. These 6 different candidates can be copied into several candidate groups, where the only difference between these groups is the initial weights. If the number of groups is set to 2, then the number of candidate neurons will be 2x3x2=12. The number of candidate groups is defined by fann_set_cascade_num_candidate_groups().

The default number of candidates is 6x4x2 = 48

Parameters

ann

Neural network resource.

Return Values

The number of candidates used during training, or FALSE on error.

See Also

  • fann_get_cascade_activation_functions() - Returns the cascade activation functions
  • fann_get_cascade_activation_functions_count() - Returns the number of cascade activation functions
  • fann_get_cascade_activation_steepnesses() - Returns the cascade activation steepnesses
  • fann_get_cascade_activation_steepnesses_count() - The number of activation steepnesses
  • fann_get_cascade_num_candidate_groups() - Returns the number of candidate groups


Returns the cascade output change fraction

  • « fann_get_cascade_num_candidates
  • fann_get_cascade_output_stagnation_epochs »
  • PHP Manual
  • Fann Functions
  • Returns the cascade output change fraction

fann_get_cascade_output_change_fraction

(PECL fann >= 1.0.0)

fann_get_cascade_output_change_fraction — Returns the cascade output change fraction

Description

fann_get_cascade_output_change_fraction ( resource $ann ) : float

The cascade output change fraction is a number between 0 and 1 determining how large a fraction of the fann_get_MSE() value should change within fann_get_cascade_output_stagnation_epochs() during training of the output connections, in order for the training not to stagnate. If the training stagnates, the training of the output connections will be ended and new candidates will be prepared.

It means that if the MSE does not change by a fraction of fann_get_cascade_output_change_fraction() during a period of fann_get_cascade_output_stagnation_epochs(), the training of the output connections is stopped because the training has stagnated.

If the cascade output change fraction is low, the output connections will be trained more and if the fraction is high, they will be trained less.

The default cascade output change fraction is 0.01, which is equalent to a 1% change in MSE.

Parameters

ann

Neural network resource.

Return Values

The cascade output change fraction, or FALSE on error.

See Also

  • fann_set_cascade_output_change_fraction() - Sets the cascade output change fraction
  • fann_get_MSE() - Reads the mean square error from the network
  • fann_get_cascade_output_stagnation_epochs() - Returns the number of cascade output stagnation epochs


Returns the number of cascade output stagnation epochs

  • « fann_get_cascade_output_change_fraction
  • fann_get_cascade_weight_multiplier »
  • PHP Manual
  • Fann Functions
  • Returns the number of cascade output stagnation epochs

fann_get_cascade_output_stagnation_epochs

(PECL fann >= 1.0.0)

fann_get_cascade_output_stagnation_epochs — Returns the number of cascade output stagnation epochs

Description

fann_get_cascade_output_stagnation_epochs ( resource $ann ) : int

The number of cascade output stagnation epochs determines the number of epochs training is allowed to continue without changing the MSE by a fraction of fann_get_cascade_output_change_fraction().

See more info about this parameter in fann_get_cascade_output_change_fraction().

The default number of cascade output stagnation epochs is 12.

Parameters

ann

Neural network resource.

Return Values

The number of cascade output stagnation epochs, or FALSE on error.

See Also

  • fann_set_cascade_output_stagnation_epochs() - Sets the number of cascade output stagnation epochs
  • fann_get_cascade_output_change_fraction() - Returns the cascade output change fraction


Returns the weight multiplier

  • « fann_get_cascade_output_stagnation_epochs
  • fann_get_connection_array »
  • PHP Manual
  • Fann Functions
  • Returns the weight multiplier

fann_get_cascade_weight_multiplier

(PECL fann >= 1.0.0)

fann_get_cascade_weight_multiplier — Returns the weight multiplier

Description

fann_get_cascade_weight_multiplier ( resource $ann ) : float

The weight multiplier is a parameter which is used to multiply the weights from the candidate neuron before adding the neuron to the neural network. This parameter is usually between 0 and 1, and is used to make the training a bit less aggressive.

The default weight multiplier is 0.4.

Parameters

ann

Neural network resource.

Return Values

The weight multiplier, or FALSE on error.

See Also

  • fann_set_cascade_weight_multiplier() - Sets the weight multiplier


Get connections in the network

  • « fann_get_cascade_weight_multiplier
  • fann_get_connection_rate »
  • PHP Manual
  • Fann Functions
  • Get connections in the network

fann_get_connection_array

(PECL fann >= 1.0.0)

fann_get_connection_array — Get connections in the network

Description

fann_get_connection_array ( resource $ann ) : array

Get connections in the network.

Parameters

ann

Neural network resource.

Return Values

An array of connections in the network


Get the connection rate used when the network was created

  • « fann_get_connection_array
  • fann_get_errno »
  • PHP Manual
  • Fann Functions
  • Get the connection rate used when the network was created

fann_get_connection_rate

(PECL fann >= 1.0.0)

fann_get_connection_rate — Get the connection rate used when the network was created

Description

fann_get_connection_rate ( resource $ann ) : float

Get the connection rate used when the network was created.

Parameters

ann

Neural network resource.

Return Values

The connection rate used when the network was created, or FALSE on error.


Returns the last error number

  • « fann_get_connection_rate
  • fann_get_errstr »
  • PHP Manual
  • Fann Functions
  • Returns the last error number

fann_get_errno

(PECL fann >= 1.0.0)

fann_get_errno — Returns the last error number

Description

fann_get_errno ( resource $errdat ) : int

Returns the last error number.

Parameters

errdat

Either neural network resource or neural network trainining data resource.

Return Values

The error number, or FALSE on error.

See Also

  • fann_reset_errno() - Resets the last error number
  • fann_get_errstr() - Returns the last errstr


Returns the last errstr

  • « fann_get_errno
  • fann_get_layer_array »
  • PHP Manual
  • Fann Functions
  • Returns the last errstr

fann_get_errstr

(PECL fann >= 1.0.0)

fann_get_errstr — Returns the last errstr

Description

fann_get_errstr ( resource $errdat ) : string

Returns the last errstr.

Parameters

errdat

Either neural network resource or neural network trainining data resource.

Return Values

The last error string, or FALSE on error.

See Also

  • fann_reset_errstr() - Resets the last error string
  • fann_get_errno() - Returns the last error number


Get the number of neurons in each layer in the network

  • « fann_get_errstr
  • fann_get_learning_momentum »
  • PHP Manual
  • Fann Functions
  • Get the number of neurons in each layer in the network

fann_get_layer_array

(PECL fann >= 1.0.0)

fann_get_layer_array — Get the number of neurons in each layer in the network

Description

fann_get_layer_array ( resource $ann ) : array

Get the number of neurons in each layer in the neural network.

Bias is not included so the layers match the fann_create functions.

Parameters

ann

Neural network resource.

Return Values

An array of numbers of neurons in each leayer


Returns the learning momentum

  • « fann_get_layer_array
  • fann_get_learning_rate »
  • PHP Manual
  • Fann Functions
  • Returns the learning momentum

fann_get_learning_momentum

(PECL fann >= 1.0.0)

fann_get_learning_momentum — Returns the learning momentum

Description

fann_get_learning_momentum ( resource $ann ) : float

The learning momentum can be used to speed up FANN_TRAIN_INCREMENTAL training. A too high momentum will however not benefit training. Setting momentum to 0 will be the same as not using the momentum parameter. The recommended value of this parameter is between 0.0 and 1.0.

The default momentum is 0.

Parameters

ann

Neural network resource.

Return Values

Returns TRUE on success, or FALSE otherwise.

The learning momentum, or FALSE on error.

See Also

  • fann_set_learning_momentum() - Sets the learning momentum
  • fann_set_training_algorithm() - Sets the training algorithm


Returns the learning rate

  • « fann_get_learning_momentum
  • fann_get_MSE »
  • PHP Manual
  • Fann Functions
  • Returns the learning rate

fann_get_learning_rate

(PECL fann >= 1.0.0)

fann_get_learning_rate — Returns the learning rate

Description

fann_get_learning_rate ( resource $ann ) : float

The learning rate is used to determine how aggressive training should be for some of the training algorithms (FANN_TRAIN_INCREMENTAL, FANN_TRAIN_BATCH, FANN_TRAIN_QUICKPROP). Do however note that it is not used in FANN_TRAIN_RPROP.

The default learning rate is 0.7.

Parameters

ann

Neural network resource.

Return Values

The learning rate, or FALSE on error.

See Also

  • fann_set_learning_rate() - Sets the learning rate
  • fann_set_training_algorithm() - Sets the training algorithm


Reads the mean square error from the network

  • « fann_get_learning_rate
  • fann_get_network_type »
  • PHP Manual
  • Fann Functions
  • Reads the mean square error from the network

fann_get_MSE

(PECL fann >= 1.0.0)

fann_get_MSE — Reads the mean square error from the network

Description

fann_get_MSE ( resource $ann ) : float

Reads the mean square error from the network.

Reads the mean square error from the network. This value is calculated during training or testing and can therefore sometimes be a bit off if the weights have been changed since the last calculation of the value.

Parameters

ann

Neural network resource.

Return Values

The mean square error, or FALSE on error.

See Also

  • fann_test_data() - Test a set of training data and calculates the MSE for the training data


Get the type of neural network it was created as

  • « fann_get_MSE
  • fann_get_num_input »
  • PHP Manual
  • Fann Functions
  • Get the type of neural network it was created as

fann_get_network_type

(PECL fann >= 1.0.0)

fann_get_network_type — Get the type of neural network it was created as

Description

fann_get_network_type ( resource $ann ) : int

Get the type of neural network it was created as.

Parameters

ann

Neural network resource.

Return Values

Network type constant, or FALSE on error.


Get the number of input neurons

  • « fann_get_network_type
  • fann_get_num_layers »
  • PHP Manual
  • Fann Functions
  • Get the number of input neurons

fann_get_num_input

(PECL fann >= 1.0.0)

fann_get_num_input — Get the number of input neurons

Description

fann_get_num_input ( resource $ann ) : int

Get the number of input neurons.

Parameters

ann

Neural network resource.

Return Values

Number of input neurons, or FALSE on error


Get the number of layers in the neural network

  • « fann_get_num_input
  • fann_get_num_output »
  • PHP Manual
  • Fann Functions
  • Get the number of layers in the neural network

fann_get_num_layers

(PECL fann >= 1.0.0)

fann_get_num_layers — Get the number of layers in the neural network

Description

fann_get_num_layers ( resource $ann ) : int

Get the number of layers in the neural network.

Parameters

ann

Neural network resource.

Return Values

The number of leayers in the neural network, or FALSE on error.


Get the number of output neurons

  • « fann_get_num_layers
  • fann_get_quickprop_decay »
  • PHP Manual
  • Fann Functions
  • Get the number of output neurons

fann_get_num_output

(PECL fann >= 1.0.0)

fann_get_num_output — Get the number of output neurons

Description

fann_get_num_output ( resource $ann ) : int

Get the number of output neurons.

Parameters

ann

Neural network resource.

Return Values

Number of output neurons, or FALSE on error


Returns the decay which is a factor that weights should decrease in each iteration during quickprop training

  • « fann_get_num_output
  • fann_get_quickprop_mu »
  • PHP Manual
  • Fann Functions
  • Returns the decay which is a factor that weights should decrease in each iteration during quickprop training

fann_get_quickprop_decay

(PECL fann >= 1.0.0)

fann_get_quickprop_decay — Returns the decay which is a factor that weights should decrease in each iteration during quickprop training

Description

fann_get_quickprop_decay ( resource $ann ) : float

The decay is a small negative valued number which is a factor that the weights should decrease in each iteration during quickprop training. This is used to make sure that the weights do not become too high during training.

The default decay is -0.0001.

Parameters

ann

Neural network resource.

Return Values

The decay, or FALSE on error.

See Also

  • fann_set_quickprop_decay() - Sets the quickprop decay factor


Returns the mu factor

  • « fann_get_quickprop_decay
  • fann_get_rprop_decrease_factor »
  • PHP Manual
  • Fann Functions
  • Returns the mu factor

fann_get_quickprop_mu

(PECL fann >= 1.0.0)

fann_get_quickprop_mu — Returns the mu factor

Description

fann_get_quickprop_mu ( resource $ann ) : float

The mu factor is used to increase and decrease the step-size during quickprop training. The mu factor should always be above 1, since it would otherwise decrease the step-size when it was suppose to increase it.

The default mu factor is 1.75.

Parameters

ann

Neural network resource.

Return Values

The mu factor, or FALSE on error.

See Also

  • fann_set_quickprop_mu() - Sets the quickprop mu factor


Returns the increase factor used during RPROP training

  • « fann_get_quickprop_mu
  • fann_get_rprop_delta_max »
  • PHP Manual
  • Fann Functions
  • Returns the increase factor used during RPROP training

fann_get_rprop_decrease_factor

(PECL fann >= 1.0.0)

fann_get_rprop_decrease_factor — Returns the increase factor used during RPROP training

Description

fann_get_rprop_decrease_factor ( resource $ann ) : float

The decrease factor is a value smaller than 1, which is used to decrease the step-size during RPROP training.

The default decrease factor is 0.5.

Parameters

ann

Neural network resource.

Return Values

The decrease factor, or FALSE on error.

See Also

  • fann_set_rprop_decrease_factor() - Sets the decrease factor used during RPROP training


Returns the maximum step-size

  • « fann_get_rprop_decrease_factor
  • fann_get_rprop_delta_min »
  • PHP Manual
  • Fann Functions
  • Returns the maximum step-size

fann_get_rprop_delta_max

(PECL fann >= 1.0.0)

fann_get_rprop_delta_max — Returns the maximum step-size

Description

fann_get_rprop_delta_max ( resource $ann ) : float

The maximum step-size is a positive number determining how large the maximum step-size may be.

The default delta max is 50.0.

Parameters

ann

Neural network resource.

Return Values

The maximum step-size, or FALSE on error.

See Also

  • fann_set_rprop_delta_max() - Sets the maximum step-size
  • fann_get_rprop_delta_min() - Returns the minimum step-size


Returns the minimum step-size

  • « fann_get_rprop_delta_max
  • fann_get_rprop_delta_zero »
  • PHP Manual
  • Fann Functions
  • Returns the minimum step-size

fann_get_rprop_delta_min

(PECL fann >= 1.0.0)

fann_get_rprop_delta_min — Returns the minimum step-size

Description

fann_get_rprop_delta_min ( resource $ann ) : float

The minimum step-size is a small positive number determining how small the minimum step-size may be.

The default value delta min is 0.0.

Parameters

ann

Neural network resource.

Return Values

The minimum step-size, or FALSE on error.

See Also

  • fann_set_rprop_delta_min() - Sets the minimum step-size


Returns the initial step-size

  • « fann_get_rprop_delta_min
  • fann_get_rprop_increase_factor »
  • PHP Manual
  • Fann Functions
  • Returns the initial step-size

fann_get_rprop_delta_zero

(PECL fann >= 1.0.0)

fann_get_rprop_delta_zero — Returns the initial step-size

Description

fann_get_rprop_delta_zero ( resource $ann ) : int

The initial step-size is a positive number determining the initial step size.

The default delta zero is 0.1.

Parameters

ann

Neural network resource.

Return Values

The initial step-size, or FALSE on error.

See Also

  • fann_set_rprop_delta_zero() - Sets the initial step-size
  • fann_get_rprop_delta_min() - Returns the minimum step-size
  • fann_get_rprop_delta_max() - Returns the maximum step-size


Returns the increase factor used during RPROP training

  • « fann_get_rprop_delta_zero
  • fann_get_sarprop_step_error_shift »
  • PHP Manual
  • Fann Functions
  • Returns the increase factor used during RPROP training

fann_get_rprop_increase_factor

(PECL fann >= 1.0.0)

fann_get_rprop_increase_factor — Returns the increase factor used during RPROP training

Description

fann_get_rprop_increase_factor ( resource $ann ) : float

The increase factor is a value larger than 1, which is used to increase the step-size during RPROP training.

The default increase factor is 1.2.

Parameters

ann

Neural network resource.

Return Values

The increase factor, or FALSE on error.

See Also

  • fann_set_rprop_increase_factor() - Sets the increase factor used during RPROP training


Returns the sarprop step error shift

  • « fann_get_rprop_increase_factor
  • fann_get_sarprop_step_error_threshold_factor »
  • PHP Manual
  • Fann Functions
  • Returns the sarprop step error shift

fann_get_sarprop_step_error_shift

(PECL fann >= 1.0.0)

fann_get_sarprop_step_error_shift — Returns the sarprop step error shift

Description

fann_get_sarprop_step_error_shift ( resource $ann ) : float

Returns the sarprop step error shift.

The default step error shift is 1.385.

Parameters

ann

Neural network resource.

Return Values

The sarprop step error shift , or FALSE on error.

See Also

  • fann_set_sarprop_step_error_shift() - Sets the sarprop step error shift


Returns the sarprop step error threshold factor

  • « fann_get_sarprop_step_error_shift
  • fann_get_sarprop_temperature »
  • PHP Manual
  • Fann Functions
  • Returns the sarprop step error threshold factor

fann_get_sarprop_step_error_threshold_factor

(PECL fann >= 1.0.0)

fann_get_sarprop_step_error_threshold_factor — Returns the sarprop step error threshold factor

Description

fann_get_sarprop_step_error_threshold_factor ( resource $ann ) : float

The sarprop step error threshold factor.

The default factor is 0.1.

Parameters

ann

Neural network resource.

Return Values

The sarprop step error threshold factor, or FALSE on error.

See Also

  • fann_set_sarprop_step_error_threshold_factor() - Sets the sarprop step error threshold factor


Returns the sarprop temperature

  • « fann_get_sarprop_step_error_threshold_factor
  • fann_get_sarprop_weight_decay_shift »
  • PHP Manual
  • Fann Functions
  • Returns the sarprop temperature

fann_get_sarprop_temperature

(PECL fann >= 1.0.0)

fann_get_sarprop_temperature — Returns the sarprop temperature

Description

fann_get_sarprop_temperature ( resource $ann ) : float

Returns the sarprop temperature.

The default temperature is 0.015.

Parameters

ann

Neural network resource.

Return Values

The sarprop temperature, or FALSE on error.

See Also

  • fann_set_sarprop_temperature() - Sets the sarprop temperature


Returns the sarprop weight decay shift

  • « fann_get_sarprop_temperature
  • fann_get_total_connections »
  • PHP Manual
  • Fann Functions
  • Returns the sarprop weight decay shift

fann_get_sarprop_weight_decay_shift

(PECL fann >= 1.0.0)

fann_get_sarprop_weight_decay_shift — Returns the sarprop weight decay shift

Description

fann_get_sarprop_weight_decay_shift ( resource $ann ) : float

The sarprop weight decay shift.

The default delta max is -6.644.

Parameters

ann

Neural network resource.

Return Values

The sarprop weight decay shift, or FALSE on error.

See Also

  • fann_set_sarprop_weight_decay_shift() - Sets the sarprop weight decay shift


Get the total number of connections in the entire network

  • « fann_get_sarprop_weight_decay_shift
  • fann_get_total_neurons »
  • PHP Manual
  • Fann Functions
  • Get the total number of connections in the entire network

fann_get_total_connections

(PECL fann >= 1.0.0)

fann_get_total_connections — Get the total number of connections in the entire network

Description

fann_get_total_connections ( resource $ann ) : int

Get the total number of connections in the entire network.

Parameters

ann

Neural network resource.

Return Values

Total number of connections in the entire network, or FALSE on error


Get the total number of neurons in the entire network

  • « fann_get_total_connections
  • fann_get_train_error_function »
  • PHP Manual
  • Fann Functions
  • Get the total number of neurons in the entire network

fann_get_total_neurons

(PECL fann >= 1.0.0)

fann_get_total_neurons — Get the total number of neurons in the entire network

Description

fann_get_total_neurons ( resource $ann ) : int

Get the total number of neurons in the entire network. This number does also include the bias neurons, so a 2-4-2 network has 2+4+2 +2(bias) = 10 neurons.

Parameters

ann

Neural network resource.

Return Values

Total number of neurons in the entire network, or FALSE on error.


Returns the error function used during training

  • « fann_get_total_neurons
  • fann_get_train_stop_function »
  • PHP Manual
  • Fann Functions
  • Returns the error function used during training

fann_get_train_error_function

(PECL fann >= 1.0.0)

fann_get_train_error_function — Returns the error function used during training

Description

fann_get_train_error_function ( resource $ann ) : int

Returns the error function used during training.

The error functions are described further in error functions constants.

The default error function is FANN_ERRORFUNC_TANH.

Parameters

ann

Neural network resource.

Return Values

The error function constant, or FALSE on error.

See Also

  • fann_set_train_error_function() - Sets the error function used during training


Returns the stop function used during training

  • « fann_get_train_error_function
  • fann_get_training_algorithm »
  • PHP Manual
  • Fann Functions
  • Returns the stop function used during training

fann_get_train_stop_function

(PECL fann >= 1.0.0)

fann_get_train_stop_function — Returns the stop function used during training

Description

fann_get_train_stop_function ( resource $ann ) : int

Returns the stop function used during training.

The stop functions are described further in stop functions constants.

The default stop function is FANN_STOPFUNC_MSE.

Parameters

ann

Neural network resource.

Return Values

The stop function constant, or FALSE on error.

See Also

  • fann_set_train_stop_function() - Sets the stop function used during training


Returns the training algorithm

  • « fann_get_train_stop_function
  • fann_init_weights »
  • PHP Manual
  • Fann Functions
  • Returns the training algorithm

fann_get_training_algorithm

(PECL fann >= 1.0.0)

fann_get_training_algorithm — Returns the training algorithm

Description

fann_get_training_algorithm ( resource $ann ) : int

Returns the training algorithm. This training algorithm is used by fann_train_on_data() and associated functions.

Note that this algorithm is also used during fann_cascadetrain_on_data(), although only FANN_TRAIN_RPROP and FANN_TRAIN_QUICKPROP is allowed during cascade training.

Parameters

ann

Neural network resource.

Return Values

Training algorithm constant, or FALSE on error.

See Also

  • fann_set_training_algorithm() - Sets the training algorithm


Initialize the weights using Widrow + Nguyen’s algorithm

  • « fann_get_training_algorithm
  • fann_length_train_data »
  • PHP Manual
  • Fann Functions
  • Initialize the weights using Widrow + Nguyen’s algorithm

fann_init_weights

(PECL fann >= 1.0.0)

fann_init_weights — Initialize the weights using Widrow + Nguyen’s algorithm

Description

fann_init_weights ( resource $ann , resource $train_data ) : bool

Initialize the weights using Widrow + Nguyen’s algorithm.

This function behaves similarly to fann_randomize_weights(). It will use the algorithm developed by Derrick Nguyen and Bernard Widrow to set the weights in such a way as to speed up training. This technique is not always successful, and in some cases can be less efficient than a purely random initialization.

The algorithm requires access to the range of the input data (for example largest and smallest input), and therefore accepts a second argument, data, which is the training data that will be used to train the network.

Parameters

ann

Neural network resource.

train_data

Neural network training data resource.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_randomize_weights() - Give each connection a random weight between min_weight and max_weight
  • fann_read_train_from_file() - Reads a file that stores training data


Returns the number of training patterns in the train data

  • « fann_init_weights
  • fann_merge_train_data »
  • PHP Manual
  • Fann Functions
  • Returns the number of training patterns in the train data

fann_length_train_data

(PECL fann >= 1.0.0)

fann_length_train_data — Returns the number of training patterns in the train data

Description

fann_length_train_data ( resource $data ) : int

Returns the number of training patterns in the train data resource.

Parameters

data

Neural network training data resource.

Return Values

Number of elements in the train data resource, or FALSE on error.


Merges the train data

  • « fann_length_train_data
  • fann_num_input_train_data »
  • PHP Manual
  • Fann Functions
  • Merges the train data

fann_merge_train_data

(PECL fann >= 1.0.0)

fann_merge_train_data — Merges the train data

Description

fann_merge_train_data ( resource $data1 , resource $data2 ) : resource

Merges the data from data1 and data2 into a new train data resource.

Parameters

data1

Neural network training data resource.

data2

Neural network training data resource.

Return Values

New merged train data resource, or FALSE on error.


Returns the number of inputs in each of the training patterns in the train data

  • « fann_merge_train_data
  • fann_num_output_train_data »
  • PHP Manual
  • Fann Functions
  • Returns the number of inputs in each of the training patterns in the train data

fann_num_input_train_data

(PECL fann >= 1.0.0)

fann_num_input_train_data — Returns the number of inputs in each of the training patterns in the train data

Description

fann_num_input_train_data ( resource $data ) : int

Returns the number of inputs in each of the training patterns in the train data resource.

Parameters

data

Neural network training data resource.

Return Values

The number of inputs, or FALSE on error.

See Also

  • fann_length_train_data() - Returns the number of training patterns in the train data
  • fann_num_output_train_data() - Returns the number of outputs in each of the training patterns in the train data


Returns the number of outputs in each of the training patterns in the train data

  • « fann_num_input_train_data
  • fann_print_error »
  • PHP Manual
  • Fann Functions
  • Returns the number of outputs in each of the training patterns in the train data

fann_num_output_train_data

(PECL fann >= 1.0.0)

fann_num_output_train_data — Returns the number of outputs in each of the training patterns in the train data

Description

fann_num_output_train_data ( resource $data ) : int

Returns the number of outputs in each of the training patterns in the train data resource.

Parameters

data

Neural network training data resource.

Return Values

The number of outputs, or FALSE on error.

See Also

  • fann_length_train_data() - Returns the number of training patterns in the train data
  • fann_num_input_train_data() - Returns the number of inputs in each of the training patterns in the train data


Prints the error string

  • « fann_num_output_train_data
  • fann_randomize_weights »
  • PHP Manual
  • Fann Functions
  • Prints the error string

fann_print_error

(PECL fann >= 1.0.0)

fann_print_error — Prints the error string

Description

fann_print_error ( resource $errdat ) : void

Prints the error string.

Parameters

errdat

Either neural network resource or neural network trainining data resource.

Return Values

No value is returned.

See Also

  • fann_get_errstr() - Returns the last errstr


Give each connection a random weight between min_weight and max_weight

  • « fann_print_error
  • fann_read_train_from_file »
  • PHP Manual
  • Fann Functions
  • Give each connection a random weight between min_weight and max_weight

fann_randomize_weights

(PECL fann >= 1.0.0)

fann_randomize_weights — Give each connection a random weight between min_weight and max_weight

Description

fann_randomize_weights ( resource $ann , float $min_weight , float $max_weight ) : bool

Give each connection a random weight between min_weight and max_weight

From the beginning the weights are random between -0.1 and 0.1.

Parameters

ann

Neural network resource.

min_weight

Minimum weight value

max_weight

Maximum weight value

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_init_weights() - Initialize the weights using Widrow + Nguyen’s algorithm


Reads a file that stores training data

  • « fann_randomize_weights
  • fann_reset_errno »
  • PHP Manual
  • Fann Functions
  • Reads a file that stores training data

fann_read_train_from_file

(PECL fann >= 1.0.0)

fann_read_train_from_file — Reads a file that stores training data

Description

fann_read_train_from_file ( string $filename ) : resource

Reads a file that stores training data.

Parameters

filename

The input file in the following format:

num_train_data num_input num_output
inputdata seperated by space
outputdata seperated by space

.
.
.

inputdata seperated by space
outputdata seperated by space

Return Values

Returns a train data resource on success, or FALSE on error.

Examples

Example #1 fann_read_train_from_file() example

<?php
$train_data = fann_read_train_from_file("xor.data");
if ($train_data) {
    // Do something with $train_data for XOR function
}
?>

Contents of xor.data

4 2 1
-1 -1
-1
-1 1
1
1 -1
1
1 1
-1

See Also

  • fann_train_on_data() - Trains on an entire dataset for a period of time
  • fann_destroy_train() - Destructs the training data
  • fann_save_train() - Save the training structure to a file


Resets the last error number

  • « fann_read_train_from_file
  • fann_reset_errstr »
  • PHP Manual
  • Fann Functions
  • Resets the last error number

fann_reset_errno

(PECL fann >= 1.0.0)

fann_reset_errno — Resets the last error number

Description

fann_reset_errno ( resource $errdat ) : void

Resets the last error number.

Parameters

errdat

Either neural network resource or neural network trainining data resource.

Return Values

No value is returned.

See Also

  • fann_get_errno() - Returns the last error number
  • fann_reset_errstr() - Resets the last error string


Resets the last error string

  • « fann_reset_errno
  • fann_reset_MSE »
  • PHP Manual
  • Fann Functions
  • Resets the last error string

fann_reset_errstr

(PECL fann >= 1.0.0)

fann_reset_errstr — Resets the last error string

Description

fann_reset_errstr ( resource $errdat ) : void

Resets the last error string.

Parameters

errdat

Either neural network resource or neural network trainining data resource.

Return Values

No value is returned.

See Also

  • fann_get_errstr() - Returns the last errstr
  • fann_reset_errno() - Resets the last error number


Resets the mean square error from the network

  • « fann_reset_errstr
  • fann_run »
  • PHP Manual
  • Fann Functions
  • Resets the mean square error from the network

fann_reset_MSE

(PECL fann >= 1.0.0)

fann_reset_MSE — Resets the mean square error from the network

Description

fann_reset_MSE ( string $ann ) : bool

Resets the mean square error from the network.

This function also resets the number of bits that fail.

Parameters

ann

Neural network resource.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_MSE() - Reads the mean square error from the network
  • fann_get_bit_fail() - The number of fail bits
  • fann_get_bit_fail_limit() - Returns the bit fail limit used during training


Will run input through the neural network

  • « fann_reset_MSE
  • fann_save_train »
  • PHP Manual
  • Fann Functions
  • Will run input through the neural network

fann_run

(PECL fann >= 1.0.0)

fann_run — Will run input through the neural network

Description

fann_run ( resource $ann , array $input ) : array

Will run input through the neural network, returning an array of outputs, the number of which being equal to the number of neurons in the output layer.

Parameters

ann

Neural network resource.

input

Array of input values

Return Values

Array of output values, or FALSE on error


Save the training structure to a file

  • « fann_run
  • fann_save »
  • PHP Manual
  • Fann Functions
  • Save the training structure to a file

fann_save_train

(PECL fann >= 1.0.0)

fann_save_train — Save the training structure to a file

Description

fann_save_train ( resource $data , string $file_name ) : bool

Save the training data to a file, with the format as specified in fann_read_train_from_file().

Parameters

data

Neural network training data resource.

file_name

The file name of the file where training data is saved to.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_read_train_from_file() - Reads a file that stores training data


Saves the entire network to a configuration file

  • « fann_save_train
  • fann_scale_input_train_data »
  • PHP Manual
  • Fann Functions
  • Saves the entire network to a configuration file

fann_save

(PECL fann >= 1.0.0)

fann_save — Saves the entire network to a configuration file

Description

fann_save ( resource $ann , string $configuration_file ) : bool

Saves the entire network to a configuration file.

The configuration file contains all information about the neural network and enables fann_create_from_file() to create an exact copy of the neural network and all of the parameters associated with the neural network.

These three parameters (fann_set_callback(), fann_set_error_log(), fann_set_user_data()) are NOT saved to the file because they cannot safely be ported to a different location. Also temporary parameters generated during training like fann_get_MSE() is not saved.

Parameters

ann

Neural network resource.

configuration_file

The configuration file path.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_create_from_file() - Constructs a backpropagation neural network from a configuration file


Scales the inputs in the training data to the specified range

  • « fann_save
  • fann_scale_input »
  • PHP Manual
  • Fann Functions
  • Scales the inputs in the training data to the specified range

fann_scale_input_train_data

(PECL fann >= 1.0.0)

fann_scale_input_train_data — Scales the inputs in the training data to the specified range

Description

fann_scale_input_train_data ( resource $train_data , float $new_min , float $new_max ) : bool

Scales the inputs in the training data to the specified range.

Parameters

train_data

Neural network training data resource.

new_min

New minimum after scaling inputs in training data.

new_max

New maximum after scaling inputs in training data.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_scale_output_train_data() - Scales the outputs in the training data to the specified range
  • fann_scale_train_data() - Scales the inputs and outputs in the training data to the specified range


Scale data in input vector before feed it to ann based on previously calculated parameters

  • « fann_scale_input_train_data
  • fann_scale_output_train_data »
  • PHP Manual
  • Fann Functions
  • Scale data in input vector before feed it to ann based on previously calculated parameters

fann_scale_input

(PECL fann >= 1.0.0)

fann_scale_input — Scale data in input vector before feed it to ann based on previously calculated parameters

Description

fann_scale_input ( resource $ann , array $input_vector ) : bool

Scale data in input vector before feed it to ann based on previously calculated parameters.

Parameters

ann

Neural network resource.

input_vector

Input vector that will be scaled

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_descale_input() - Scale data in input vector after get it from ann based on previously calculated parameters
  • fann_scale_output() - Scale data in output vector before feed it to ann based on previously calculated parameters


Scales the outputs in the training data to the specified range

  • « fann_scale_input
  • fann_scale_output »
  • PHP Manual
  • Fann Functions
  • Scales the outputs in the training data to the specified range

fann_scale_output_train_data

(PECL fann >= 1.0.0)

fann_scale_output_train_data — Scales the outputs in the training data to the specified range

Description

fann_scale_output_train_data ( resource $train_data , float $new_min , float $new_max ) : bool

Scales the outputs in the training data to the specified range.

Parameters

train_data

Neural network training data resource.

new_min

New minimum after scaling outputs in training data.

new_max

New maximum after scaling outputs in training data.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_scale_input_train_data() - Scales the inputs in the training data to the specified range
  • fann_scale_train_data() - Scales the inputs and outputs in the training data to the specified range


Scale data in output vector before feed it to ann based on previously calculated parameters

  • « fann_scale_output_train_data
  • fann_scale_train_data »
  • PHP Manual
  • Fann Functions
  • Scale data in output vector before feed it to ann based on previously calculated parameters

fann_scale_output

(PECL fann >= 1.0.0)

fann_scale_output — Scale data in output vector before feed it to ann based on previously calculated parameters

Description

fann_scale_output ( resource $ann , array $output_vector ) : bool

Scale data in output vector before feed it to ann based on previously calculated parameters.

Parameters

ann

Neural network resource.

output_vector

Output vector that will be scaled

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_descale_output() - Scale data in output vector after get it from ann based on previously calculated parameters
  • fann_scale_input() - Scale data in input vector before feed it to ann based on previously calculated parameters


Scales the inputs and outputs in the training data to the specified range

  • « fann_scale_output
  • fann_scale_train »
  • PHP Manual
  • Fann Functions
  • Scales the inputs and outputs in the training data to the specified range

fann_scale_train_data

(PECL fann >= 1.0.0)

fann_scale_train_data — Scales the inputs and outputs in the training data to the specified range

Description

fann_scale_train_data ( resource $train_data , float $new_min , float $new_max ) : bool

Scales the inputs and outputs in the training data to the specified range.

Parameters

train_data

Neural network training data resource.

new_min

New minimum after scaling inputs and outputs in training data.

new_max

New maximum after scaling inputs and outputs in training data.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_scale_output_train_data() - Scales the outputs in the training data to the specified range
  • fann_scale_input_train_data() - Scales the inputs in the training data to the specified range


Scale input and output data based on previously calculated parameters

  • « fann_scale_train_data
  • fann_set_activation_function_hidden »
  • PHP Manual
  • Fann Functions
  • Scale input and output data based on previously calculated parameters

fann_scale_train

(PECL fann >= 1.0.0)

fann_scale_train — Scale input and output data based on previously calculated parameters

Description

fann_scale_train ( resource $ann , resource $train_data ) : bool

Scale input and output data based on previously calculated parameters.

Parameters

ann

Neural network resource.

train_data

Neural network training data resource.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_descale_train() - Descale input and output data based on previously calculated parameters
  • fann_set_scaling_params() - Calculate input and output scaling parameters for future use based on training data


Sets the activation function for all of the hidden layers

  • « fann_scale_train
  • fann_set_activation_function_layer »
  • PHP Manual
  • Fann Functions
  • Sets the activation function for all of the hidden layers

fann_set_activation_function_hidden

(PECL fann >= 1.0.0)

fann_set_activation_function_hidden — Sets the activation function for all of the hidden layers

Description

fann_set_activation_function_hidden ( resource $ann , int $activation_function ) : bool

Sets the activation function for all of the hidden layers.

Parameters

ann

Neural network resource.

activation_function

The activation functions constant.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_set_activation_function() - Sets the activation function for supplied neuron and layer
  • fann_set_activation_function_layer() - Sets the activation function for all the neurons in the supplied layer
  • fann_set_activation_function_output() - Sets the activation function for the output layer
  • fann_set_activation_steepness() - Sets the activation steepness for supplied neuron and layer number


Sets the activation function for all the neurons in the supplied layer

  • « fann_set_activation_function_hidden
  • fann_set_activation_function_output »
  • PHP Manual
  • Fann Functions
  • Sets the activation function for all the neurons in the supplied layer

fann_set_activation_function_layer

(PECL fann >= 1.0.0)

fann_set_activation_function_layer — Sets the activation function for all the neurons in the supplied layer

Description

fann_set_activation_function_layer ( resource $ann , int $activation_function , int $layer ) : bool

Set the activation function for all the neurons in the layer number layer, counting the input layer as layer 0.

It is not possible to set activation functions for the neurons in the input layer.

Parameters

ann

Neural network resource.

activation_function

The activation functions constant.

layer

Layer number.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_set_activation_function() - Sets the activation function for supplied neuron and layer
  • fann_set_activation_function_hidden() - Sets the activation function for all of the hidden layers
  • fann_set_activation_function_output() - Sets the activation function for the output layer
  • fann_set_activation_steepness() - Sets the activation steepness for supplied neuron and layer number


Sets the activation function for the output layer

  • « fann_set_activation_function_layer
  • fann_set_activation_function »
  • PHP Manual
  • Fann Functions
  • Sets the activation function for the output layer

fann_set_activation_function_output

(PECL fann >= 1.0.0)

fann_set_activation_function_output — Sets the activation function for the output layer

Description

fann_set_activation_function_output ( resource $ann , int $activation_function ) : bool

Sets the activation function for the output layer.

Parameters

ann

Neural network resource.

activation_function

The activation functions constant.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_set_activation_function() - Sets the activation function for supplied neuron and layer
  • fann_set_activation_function_layer() - Sets the activation function for all the neurons in the supplied layer
  • fann_set_activation_function_hidden() - Sets the activation function for all of the hidden layers
  • fann_set_activation_steepness() - Sets the activation steepness for supplied neuron and layer number


Sets the activation function for supplied neuron and layer

  • « fann_set_activation_function_output
  • fann_set_activation_steepness_hidden »
  • PHP Manual
  • Fann Functions
  • Sets the activation function for supplied neuron and layer

fann_set_activation_function

(PECL fann >= 1.0.0)

fann_set_activation_function — Sets the activation function for supplied neuron and layer

Description

fann_set_activation_function ( resource $ann , int $activation_function , int $layer , int $neuron ) : bool

Set the activation function for neuron number neuron in layer number layer, counting the input layer as layer 0.

It is not possible to set activation functions for the neurons in the input layer.

When choosing an activation function it is important to note that the activation functions have different range. FANN_SIGMOID is e.g. in the 0 - 1 range while FANN_SIGMOID_SYMMETRIC is in the -1 - 1 range and FANN_LINEAR is unbound.

The supplied activation_function value must be one of the activation functions constants.

The return value is one of the activation functions constants.

Parameters

ann

Neural network resource.

activation_function

The activation functions constant.

layer

Layer number.

neuron

Neuron number.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_set_activation_function_layer() - Sets the activation function for all the neurons in the supplied layer
  • fann_set_activation_function_hidden() - Sets the activation function for all of the hidden layers
  • fann_set_activation_function_output() - Sets the activation function for the output layer
  • fann_set_activation_steepness() - Sets the activation steepness for supplied neuron and layer number
  • fann_get_activation_function() - Returns the activation function


Sets the steepness of the activation steepness for all neurons in the all hidden layers

  • « fann_set_activation_function
  • fann_set_activation_steepness_layer »
  • PHP Manual
  • Fann Functions
  • Sets the steepness of the activation steepness for all neurons in the all hidden layers

fann_set_activation_steepness_hidden

(PECL fann >= 1.0.0)

fann_set_activation_steepness_hidden — Sets the steepness of the activation steepness for all neurons in the all hidden layers

Description

fann_set_activation_steepness_hidden ( resource $ann , float $activation_steepness ) : bool

Sets the steepness of the activation steepness for all neurons in the all hidden layers.

Parameters

ann

Neural network resource.

activation_steepness

The activation steepness.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_set_activation_steepness() - Sets the activation steepness for supplied neuron and layer number
  • fann_set_activation_steepness_layer() - Sets the activation steepness for all of the neurons in the supplied layer number
  • fann_set_activation_steepness_output() - Sets the steepness of the activation steepness in the output layer
  • fann_get_activation_steepness() - Returns the activation steepness for supplied neuron and layer number
  • fann_set_activation_function() - Sets the activation function for supplied neuron and layer


Sets the activation steepness for all of the neurons in the supplied layer number

  • « fann_set_activation_steepness_hidden
  • fann_set_activation_steepness_output »
  • PHP Manual
  • Fann Functions
  • Sets the activation steepness for all of the neurons in the supplied layer number

fann_set_activation_steepness_layer

(PECL fann >= 1.0.0)

fann_set_activation_steepness_layer — Sets the activation steepness for all of the neurons in the supplied layer number

Description

fann_set_activation_steepness_layer ( resource $ann , float $activation_steepness , int $layer ) : bool

Set the activation steepness for all of the neurons in layer number layer, counting the input layer as layer 0.

It is not possible to set activation steepness for the neurons in the input layer.

Parameters

ann

Neural network resource.

activation_steepness

The activation steepness.

layer

Layer number.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_set_activation_steepness() - Sets the activation steepness for supplied neuron and layer number
  • fann_set_activation_steepness_hidden() - Sets the steepness of the activation steepness for all neurons in the all hidden layers
  • fann_set_activation_steepness_output() - Sets the steepness of the activation steepness in the output layer
  • fann_get_activation_steepness() - Returns the activation steepness for supplied neuron and layer number
  • fann_set_activation_function() - Sets the activation function for supplied neuron and layer


Sets the steepness of the activation steepness in the output layer

  • « fann_set_activation_steepness_layer
  • fann_set_activation_steepness »
  • PHP Manual
  • Fann Functions
  • Sets the steepness of the activation steepness in the output layer

fann_set_activation_steepness_output

(PECL fann >= 1.0.0)

fann_set_activation_steepness_output — Sets the steepness of the activation steepness in the output layer

Description

fann_set_activation_steepness_output ( resource $ann , float $activation_steepness ) : bool

Sets the steepness of the activation steepness in the output layer.

Parameters

ann

Neural network resource.

activation_steepness

The activation steepness.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_set_activation_steepness() - Sets the activation steepness for supplied neuron and layer number
  • fann_set_activation_steepness_layer() - Sets the activation steepness for all of the neurons in the supplied layer number
  • fann_set_activation_steepness_hidden() - Sets the steepness of the activation steepness for all neurons in the all hidden layers
  • fann_get_activation_steepness() - Returns the activation steepness for supplied neuron and layer number
  • fann_set_activation_function() - Sets the activation function for supplied neuron and layer


Sets the activation steepness for supplied neuron and layer number

  • « fann_set_activation_steepness_output
  • fann_set_bit_fail_limit »
  • PHP Manual
  • Fann Functions
  • Sets the activation steepness for supplied neuron and layer number

fann_set_activation_steepness

(PECL fann >= 1.0.0)

fann_set_activation_steepness — Sets the activation steepness for supplied neuron and layer number

Description

fann_set_activation_steepness ( resource $ann , float $activation_steepness , int $layer , int $neuron ) : bool

Set the activation steepness for neuron number neuron in layer number layer, counting the input layer as layer 0.

It is not possible to set activation steepness for the neurons in the input layer.

The steepness of an activation function says something about how fast the activation function goes from the minimum to the maximum. A high value for the activation function will also give a more agressive training.

When training neural networks where the output values should be at the extremes (usually 0 and 1, depending on the activation function), a steep activation function can be used (e.g. 1.0).

The default activation steepness is 0.5.

Parameters

ann

Neural network resource.

activation_steepness

The activation steepness.

layer

Layer number.

neuron

Neuron number.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_set_activation_steepness_layer() - Sets the activation steepness for all of the neurons in the supplied layer number
  • fann_set_activation_steepness_hidden() - Sets the steepness of the activation steepness for all neurons in the all hidden layers
  • fann_set_activation_steepness_output() - Sets the steepness of the activation steepness in the output layer
  • fann_get_activation_steepness() - Returns the activation steepness for supplied neuron and layer number
  • fann_set_activation_function() - Sets the activation function for supplied neuron and layer


Set the bit fail limit used during training

  • « fann_set_activation_steepness
  • fann_set_callback »
  • PHP Manual
  • Fann Functions
  • Set the bit fail limit used during training

fann_set_bit_fail_limit

(PECL fann >= 1.0.0)

fann_set_bit_fail_limit — Set the bit fail limit used during training

Description

fann_set_bit_fail_limit ( resource $ann , float $bit_fail_limit ) : bool

Set the bit fail limit used during training.

Parameters

ann

Neural network resource.

bit_fail_limit

The bit fail limit.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_bit_fail_limit() - Returns the bit fail limit used during training


Sets the callback function for use during training

  • « fann_set_bit_fail_limit
  • fann_set_cascade_activation_functions »
  • PHP Manual
  • Fann Functions
  • Sets the callback function for use during training

fann_set_callback

(PECL fann >= 1.0.0)

fann_set_callback — Sets the callback function for use during training

Description

fann_set_callback ( resource $ann , callable $callback ) : bool

Sets the callback function for use during training. It means that it is called from fann_train_on_data() or fann_train_on_file().

Parameters

ann

Neural network resource.

callback

The supplied callback function takes following parameters:

  • ann - The neural network resource
  • train - The train data resource or NULL if called from fann_train_on_file()
  • max_epochs - The maximum number of epochs the training should continue
  • epochs_between_reports - The number of epochs between calling this function
  • desired_error - The desired fann_get_MSE() or fann_get_bit_fail(), depending on the stop function chosen by fann_set_train_stop_function()
  • epochs - The current epoch

The callback should return TRUE. If it returns FALSE, the training will terminate.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_train_on_data() - Trains on an entire dataset for a period of time
  • fann_train_on_file() - Trains on an entire dataset, which is read from file, for a period of time


Sets the array of cascade candidate activation functions

  • « fann_set_callback
  • fann_set_cascade_activation_steepnesses »
  • PHP Manual
  • Fann Functions
  • Sets the array of cascade candidate activation functions

fann_set_cascade_activation_functions

(PECL fann >= 1.0.0)

fann_set_cascade_activation_functions — Sets the array of cascade candidate activation functions

Description

fann_set_cascade_activation_functions ( resource $ann , array $cascade_activation_functions ) : bool

Sets the array of cascade candidate activation functions.

See fann_get_cascade_num_candidates() for a description of which candidate neurons will be generated by this array.

Parameters

ann

Neural network resource.

cascade_activation_functions

The array of cascade candidate activation functions.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_cascade_activation_functions_count() - Returns the number of cascade activation functions
  • fann_set_cascade_activation_functions()


Sets the array of cascade candidate activation steepnesses

  • « fann_set_cascade_activation_functions
  • fann_set_cascade_candidate_change_fraction »
  • PHP Manual
  • Fann Functions
  • Sets the array of cascade candidate activation steepnesses

fann_set_cascade_activation_steepnesses

(PECL fann >= 1.0.0)

fann_set_cascade_activation_steepnesses — Sets the array of cascade candidate activation steepnesses

Description

fann_set_cascade_activation_steepnesses ( resource $ann , array $cascade_activation_steepnesses_count ) : bool

Sets the array of cascade candidate activation steepnesses.

See fann_get_cascade_num_candidates() for a description of which candidate neurons will be generated by this array.

Parameters

ann

Neural network resource.

cascade_activation_steepnesses_count

The array of cascade candidate activation steepnesses.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_cascade_activation_steepnesses() - Returns the cascade activation steepnesses
  • fann_get_cascade_activation_steepnesses_count() - The number of activation steepnesses


Sets the cascade candidate change fraction

  • « fann_set_cascade_activation_steepnesses
  • fann_set_cascade_candidate_limit »
  • PHP Manual
  • Fann Functions
  • Sets the cascade candidate change fraction

fann_set_cascade_candidate_change_fraction

(PECL fann >= 1.0.0)

fann_set_cascade_candidate_change_fraction — Sets the cascade candidate change fraction

Description

fann_set_cascade_candidate_change_fraction ( resource $ann , float $cascade_candidate_change_fraction ) : bool

Sets the cascade candidate change fraction.

Parameters

ann

Neural network resource.

cascade_candidate_change_fraction

The cascade candidate change fraction.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_cascade_candidate_change_fraction() - Returns the cascade candidate change fraction


Sets the candidate limit

  • « fann_set_cascade_candidate_change_fraction
  • fann_set_cascade_candidate_stagnation_epochs »
  • PHP Manual
  • Fann Functions
  • Sets the candidate limit

fann_set_cascade_candidate_limit

(PECL fann >= 1.0.0)

fann_set_cascade_candidate_limit — Sets the candidate limit

Description

fann_set_cascade_candidate_limit ( resource $ann , float $cascade_candidate_limit ) : bool

Sets the candidate limit.

Parameters

ann

Neural network resource.

cascade_candidate_limit

The candidate limit.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_cascade_candidate_limit() - Return the candidate limit


Sets the number of cascade candidate stagnation epochs

  • « fann_set_cascade_candidate_limit
  • fann_set_cascade_max_cand_epochs »
  • PHP Manual
  • Fann Functions
  • Sets the number of cascade candidate stagnation epochs

fann_set_cascade_candidate_stagnation_epochs

(PECL fann >= 1.0.0)

fann_set_cascade_candidate_stagnation_epochs — Sets the number of cascade candidate stagnation epochs

Description

fann_set_cascade_candidate_stagnation_epochs ( resource $ann , int $cascade_candidate_stagnation_epochs ) : bool

Sets the number of cascade candidate stagnation epochs.

Parameters

ann

Neural network resource.

cascade_candidate_stagnation_epochs

The number of cascade candidate stagnation epochs.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_cascade_candidate_stagnation_epochs() - Returns the number of cascade candidate stagnation epochs


Sets the max candidate epochs

  • « fann_set_cascade_candidate_stagnation_epochs
  • fann_set_cascade_max_out_epochs »
  • PHP Manual
  • Fann Functions
  • Sets the max candidate epochs

fann_set_cascade_max_cand_epochs

(PECL fann >= 1.0.0)

fann_set_cascade_max_cand_epochs — Sets the max candidate epochs

Description

fann_set_cascade_max_cand_epochs ( resource $ann , int $cascade_max_cand_epochs ) : bool

Sets the max candidate epochs.

Parameters

ann

Neural network resource.

cascade_max_cand_epochs

The max candidate epochs.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_cascade_max_cand_epochs() - Returns the maximum candidate epochs


Sets the maximum out epochs

  • « fann_set_cascade_max_cand_epochs
  • fann_set_cascade_min_cand_epochs »
  • PHP Manual
  • Fann Functions
  • Sets the maximum out epochs

fann_set_cascade_max_out_epochs

(PECL fann >= 1.0.0)

fann_set_cascade_max_out_epochs — Sets the maximum out epochs

Description

fann_set_cascade_max_out_epochs ( resource $ann , int $cascade_max_out_epochs ) : bool

Sets the maximum out epochs.

Parameters

ann

Neural network resource.

cascade_max_out_epochs

The maximum out epochs.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_cascade_max_out_epochs() - Returns the maximum out epochs


Sets the min candidate epochs

  • « fann_set_cascade_max_out_epochs
  • fann_set_cascade_min_out_epochs »
  • PHP Manual
  • Fann Functions
  • Sets the min candidate epochs

fann_set_cascade_min_cand_epochs

(PECL fann >= 1.0.0)

fann_set_cascade_min_cand_epochs — Sets the min candidate epochs

Description

fann_set_cascade_min_cand_epochs ( resource $ann , int $cascade_min_cand_epochs ) : bool

Sets the min candidate epochs.

Parameters

ann

Neural network resource.

cascade_min_cand_epochs

The minimum candidate epochs.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_cascade_min_cand_epochs() - Returns the minimum candidate epochs


Sets the minimum out epochs

  • « fann_set_cascade_min_cand_epochs
  • fann_set_cascade_num_candidate_groups »
  • PHP Manual
  • Fann Functions
  • Sets the minimum out epochs

fann_set_cascade_min_out_epochs

(PECL fann >= 1.0.0)

fann_set_cascade_min_out_epochs — Sets the minimum out epochs

Description

fann_set_cascade_min_out_epochs ( resource $ann , int $cascade_min_out_epochs ) : bool

Sets the minimum out epochs.

Parameters

ann

Neural network resource.

cascade_min_out_epochs

The minimum out epochs.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_cascade_min_out_epochs() - Returns the minimum out epochs


Sets the number of candidate groups

  • « fann_set_cascade_min_out_epochs
  • fann_set_cascade_output_change_fraction »
  • PHP Manual
  • Fann Functions
  • Sets the number of candidate groups

fann_set_cascade_num_candidate_groups

(PECL fann >= 1.0.0)

fann_set_cascade_num_candidate_groups — Sets the number of candidate groups

Description

fann_set_cascade_num_candidate_groups ( resource $ann , int $cascade_num_candidate_groups ) : bool

Sets the number of candidate groups.

Parameters

ann

Neural network resource.

cascade_num_candidate_groups

The number of candidate groups.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_cascade_num_candidate_groups() - Returns the number of candidate groups


Sets the cascade output change fraction

  • « fann_set_cascade_num_candidate_groups
  • fann_set_cascade_output_stagnation_epochs »
  • PHP Manual
  • Fann Functions
  • Sets the cascade output change fraction

fann_set_cascade_output_change_fraction

(PECL fann >= 1.0.0)

fann_set_cascade_output_change_fraction — Sets the cascade output change fraction

Description

fann_set_cascade_output_change_fraction ( resource $ann , float $cascade_output_change_fraction ) : bool

Sets the cascade output change fraction.

Parameters

ann

Neural network resource.

cascade_output_change_fraction

The cascade output change fraction.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_cascade_output_change_fraction() - Returns the cascade output change fraction


Sets the number of cascade output stagnation epochs

  • « fann_set_cascade_output_change_fraction
  • fann_set_cascade_weight_multiplier »
  • PHP Manual
  • Fann Functions
  • Sets the number of cascade output stagnation epochs

fann_set_cascade_output_stagnation_epochs

(PECL fann >= 1.0.0)

fann_set_cascade_output_stagnation_epochs — Sets the number of cascade output stagnation epochs

Description

fann_set_cascade_output_stagnation_epochs ( resource $ann , int $cascade_output_stagnation_epochs ) : bool

Sets the number of cascade output stagnation epochs.

Parameters

ann

Neural network resource.

cascade_output_stagnation_epochs

The number of cascade output stagnation epochs.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_cascade_output_stagnation_epochs() - Returns the number of cascade output stagnation epochs


Sets the weight multiplier

  • « fann_set_cascade_output_stagnation_epochs
  • fann_set_error_log »
  • PHP Manual
  • Fann Functions
  • Sets the weight multiplier

fann_set_cascade_weight_multiplier

(PECL fann >= 1.0.0)

fann_set_cascade_weight_multiplier — Sets the weight multiplier

Description

fann_set_cascade_weight_multiplier ( resource $ann , float $cascade_weight_multiplier ) : bool

Sets the weight multiplier.

Parameters

ann

Neural network resource.

cascade_weight_multiplier

The weight multiplier.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_cascade_weight_multiplier() - Returns the weight multiplier


Sets where the errors are logged to

  • « fann_set_cascade_weight_multiplier
  • fann_set_input_scaling_params »
  • PHP Manual
  • Fann Functions
  • Sets where the errors are logged to

fann_set_error_log

(PECL fann >= 1.0.0)

fann_set_error_log — Sets where the errors are logged to

Description

fann_set_error_log ( resource $errdat , string $log_file ) : void

Sets where the errors are logged to.

Parameters

errdat

Either neural network resource or neural network trainining data resource.

log_file

The log file path.

Return Values

No value is returned.


Calculate input scaling parameters for future use based on training data

  • « fann_set_error_log
  • fann_set_learning_momentum »
  • PHP Manual
  • Fann Functions
  • Calculate input scaling parameters for future use based on training data

fann_set_input_scaling_params

(PECL fann >= 1.0.0)

fann_set_input_scaling_params — Calculate input scaling parameters for future use based on training data

Description

fann_set_input_scaling_params ( resource $ann , resource $train_data , float $new_input_min , float $new_input_max ) : bool

Calculate input scaling parameters for future use based on training data.

Parameters

ann

Neural network resource.

train_data

Neural network training data resource.

new_input_min

The desired lower bound in input data after scaling (not strictly followed)

new_input_max

The desired upper bound in input data after scaling (not strictly followed)

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_set_output_scaling_params() - Calculate output scaling parameters for future use based on training data


Sets the learning momentum

  • « fann_set_input_scaling_params
  • fann_set_learning_rate »
  • PHP Manual
  • Fann Functions
  • Sets the learning momentum

fann_set_learning_momentum

(PECL fann >= 1.0.0)

fann_set_learning_momentum — Sets the learning momentum

Description

fann_set_learning_momentum ( resource $ann , float $learning_momentum ) : bool

Sets the learning momentum.

More info available in fann_get_learning_momentum().

Parameters

ann

Neural network resource.

learning_momentum

The learning momentum.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_learning_momentum() - Returns the learning momentum
  • fann_set_training_algorithm() - Sets the training algorithm


Sets the learning rate

  • « fann_set_learning_momentum
  • fann_set_output_scaling_params »
  • PHP Manual
  • Fann Functions
  • Sets the learning rate

fann_set_learning_rate

(PECL fann >= 1.0.0)

fann_set_learning_rate — Sets the learning rate

Description

fann_set_learning_rate ( resource $ann , float $learning_rate ) : bool

Sets the learning rate.

More info available in fann_get_learning_rate().

Parameters

ann

Neural network resource.

learning_rate

The learning rate.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_learning_rate() - Returns the learning rate
  • fann_set_training_algorithm() - Sets the training algorithm


Calculate output scaling parameters for future use based on training data

  • « fann_set_learning_rate
  • fann_set_quickprop_decay »
  • PHP Manual
  • Fann Functions
  • Calculate output scaling parameters for future use based on training data

fann_set_output_scaling_params

(PECL fann >= 1.0.0)

fann_set_output_scaling_params — Calculate output scaling parameters for future use based on training data

Description

fann_set_output_scaling_params ( resource $ann , resource $train_data , float $new_output_min , float $new_output_max ) : bool

Calculate output scaling parameters for future use based on training data.

Parameters

ann

Neural network resource.

train_data

Neural network training data resource.

new_output_min

The desired lower bound in output data after scaling (not strictly followed)

new_output_max

The desired upper bound in output data after scaling (not strictly followed)

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_set_input_scaling_params() - Calculate input scaling parameters for future use based on training data


Sets the quickprop decay factor

  • « fann_set_output_scaling_params
  • fann_set_quickprop_mu »
  • PHP Manual
  • Fann Functions
  • Sets the quickprop decay factor

fann_set_quickprop_decay

(PECL fann >= 1.0.0)

fann_set_quickprop_decay — Sets the quickprop decay factor

Description

fann_set_quickprop_decay ( resource $ann , float $quickprop_decay ) : bool

Sets the quickprop decay factor.

Parameters

ann

Neural network resource.

quickprop_decay

The quickprop decay factor.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_quickprop_decay() - Returns the decay which is a factor that weights should decrease in each iteration during quickprop training


Sets the quickprop mu factor

  • « fann_set_quickprop_decay
  • fann_set_rprop_decrease_factor »
  • PHP Manual
  • Fann Functions
  • Sets the quickprop mu factor

fann_set_quickprop_mu

(PECL fann >= 1.0.0)

fann_set_quickprop_mu — Sets the quickprop mu factor

Description

fann_set_quickprop_mu ( resource $ann , float $quickprop_mu ) : bool

Sets the quickprop mu factor.

Parameters

ann

Neural network resource.

quickprop_mu

The mu factor.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_quickprop_mu() - Returns the mu factor


Sets the decrease factor used during RPROP training

  • « fann_set_quickprop_mu
  • fann_set_rprop_delta_max »
  • PHP Manual
  • Fann Functions
  • Sets the decrease factor used during RPROP training

fann_set_rprop_decrease_factor

(PECL fann >= 1.0.0)

fann_set_rprop_decrease_factor — Sets the decrease factor used during RPROP training

Description

fann_set_rprop_decrease_factor ( resource $ann , float $rprop_decrease_factor ) : bool

Sets the decrease factor used during RPROP training.

Parameters

ann

Neural network resource.

rprop_decrease_factor

The decrease factor.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_rprop_decrease_factor() - Returns the increase factor used during RPROP training


Sets the maximum step-size

  • « fann_set_rprop_decrease_factor
  • fann_set_rprop_delta_min »
  • PHP Manual
  • Fann Functions
  • Sets the maximum step-size

fann_set_rprop_delta_max

(PECL fann >= 1.0.0)

fann_set_rprop_delta_max — Sets the maximum step-size

Description

fann_set_rprop_delta_max ( resource $ann , float $rprop_delta_max ) : bool

The maximum step-size is a positive number determining how large the maximum step-size may be.

Parameters

ann

Neural network resource.

rprop_delta_max

The maximum step-size.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_rprop_delta_max() - Returns the maximum step-size
  • fann_get_rprop_delta_min() - Returns the minimum step-size


Sets the minimum step-size

  • « fann_set_rprop_delta_max
  • fann_set_rprop_delta_zero »
  • PHP Manual
  • Fann Functions
  • Sets the minimum step-size

fann_set_rprop_delta_min

(PECL fann >= 1.0.0)

fann_set_rprop_delta_min — Sets the minimum step-size

Description

fann_set_rprop_delta_min ( resource $ann , float $rprop_delta_min ) : bool

The minimum step-size is a small positive number determining how small the minimum step-size may be.

Parameters

ann

Neural network resource.

rprop_delta_min

The minimum step-size.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_rprop_delta_min() - Returns the minimum step-size


Sets the initial step-size

  • « fann_set_rprop_delta_min
  • fann_set_rprop_increase_factor »
  • PHP Manual
  • Fann Functions
  • Sets the initial step-size

fann_set_rprop_delta_zero

(PECL fann >= 1.0.0)

fann_set_rprop_delta_zero — Sets the initial step-size

Description

fann_set_rprop_delta_zero ( resource $ann , float $rprop_delta_zero ) : bool

The initial step-size is a positive number determining the initial step size.

Parameters

ann

Neural network resource.

rprop_delta_zero

The initial step-size.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_rprop_delta_zero() - Returns the initial step-size
  • fann_get_rprop_delta_min() - Returns the minimum step-size
  • fann_get_rprop_delta_max() - Returns the maximum step-size


Sets the increase factor used during RPROP training

  • « fann_set_rprop_delta_zero
  • fann_set_sarprop_step_error_shift »
  • PHP Manual
  • Fann Functions
  • Sets the increase factor used during RPROP training

fann_set_rprop_increase_factor

(PECL fann >= 1.0.0)

fann_set_rprop_increase_factor — Sets the increase factor used during RPROP training

Description

fann_set_rprop_increase_factor ( resource $ann , float $rprop_increase_factor ) : bool

Sets the increase factor used during RPROP training.

Parameters

ann

Neural network resource.

rprop_increase_factor

The increase factor.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_rprop_increase_factor() - Returns the increase factor used during RPROP training


Sets the sarprop step error shift

  • « fann_set_rprop_increase_factor
  • fann_set_sarprop_step_error_threshold_factor »
  • PHP Manual
  • Fann Functions
  • Sets the sarprop step error shift

fann_set_sarprop_step_error_shift

(PECL fann >= 1.0.0)

fann_set_sarprop_step_error_shift — Sets the sarprop step error shift

Description

fann_set_sarprop_step_error_shift ( resource $ann , float $sarprop_step_error_shift ) : bool

Sets the sarprop step error shift.

Parameters

ann

Neural network resource.

sarprop_step_error_shift

The sarprop step error shift.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_sarprop_step_error_shift() - Returns the sarprop step error shift


Sets the sarprop step error threshold factor

  • « fann_set_sarprop_step_error_shift
  • fann_set_sarprop_temperature »
  • PHP Manual
  • Fann Functions
  • Sets the sarprop step error threshold factor

fann_set_sarprop_step_error_threshold_factor

(PECL fann >= 1.0.0)

fann_set_sarprop_step_error_threshold_factor — Sets the sarprop step error threshold factor

Description

fann_set_sarprop_step_error_threshold_factor ( resource $ann , float $sarprop_step_error_threshold_factor ) : bool

Sets the sarprop step error threshold factor.

Parameters

ann

Neural network resource.

sarprop_step_error_threshold_factor

The sarprop step error threshold factor.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_sarprop_step_error_threshold_factor() - Returns the sarprop step error threshold factor


Sets the sarprop temperature

  • « fann_set_sarprop_step_error_threshold_factor
  • fann_set_sarprop_weight_decay_shift »
  • PHP Manual
  • Fann Functions
  • Sets the sarprop temperature

fann_set_sarprop_temperature

(PECL fann >= 1.0.0)

fann_set_sarprop_temperature — Sets the sarprop temperature

Description

fann_set_sarprop_temperature ( resource $ann , float $sarprop_temperature ) : bool

Sets the sarprop temperature.

Parameters

ann

Neural network resource.

sarprop_temperature

The sarprop temperature.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_sarprop_temperature() - Returns the sarprop temperature


Sets the sarprop weight decay shift

  • « fann_set_sarprop_temperature
  • fann_set_scaling_params »
  • PHP Manual
  • Fann Functions
  • Sets the sarprop weight decay shift

fann_set_sarprop_weight_decay_shift

(PECL fann >= 1.0.0)

fann_set_sarprop_weight_decay_shift — Sets the sarprop weight decay shift

Description

fann_set_sarprop_weight_decay_shift ( resource $ann , float $sarprop_weight_decay_shift ) : bool

Sets the sarprop weight decay shift.

Parameters

ann

Neural network resource.

sarprop_weight_decay_shift

The sarprop weight decay shift.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_sarprop_weight_decay_shift() - Returns the sarprop weight decay shift


Calculate input and output scaling parameters for future use based on training data

  • « fann_set_sarprop_weight_decay_shift
  • fann_set_train_error_function »
  • PHP Manual
  • Fann Functions
  • Calculate input and output scaling parameters for future use based on training data

fann_set_scaling_params

(PECL fann >= 1.0.0)

fann_set_scaling_params — Calculate input and output scaling parameters for future use based on training data

Description

fann_set_scaling_params ( resource $ann , resource $train_data , float $new_input_min , float $new_input_max , float $new_output_min , float $new_output_max ) : bool

Calculate input and output scaling parameters for future use based on training data.

Parameters

ann

Neural network resource.

train_data

Neural network training data resource.

new_input_min

The desired lower bound in input data after scaling (not strictly followed)

new_input_max

The desired upper bound in input data after scaling (not strictly followed)

new_output_min

The desired lower bound in output data after scaling (not strictly followed)

new_output_max

The desired upper bound in output data after scaling (not strictly followed)

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_set_input_scaling_params() - Calculate input scaling parameters for future use based on training data
  • fann_set_output_scaling_params() - Calculate output scaling parameters for future use based on training data


Sets the error function used during training

  • « fann_set_scaling_params
  • fann_set_train_stop_function »
  • PHP Manual
  • Fann Functions
  • Sets the error function used during training

fann_set_train_error_function

(PECL fann >= 1.0.0)

fann_set_train_error_function — Sets the error function used during training

Description

fann_set_train_error_function ( resource $ann , int $error_function ) : bool

Sets the error function used during training.

The error functions are described further in error functions constants.

Parameters

ann

Neural network resource.

error_function

The error function constant

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_train_error_function() - Returns the error function used during training


Sets the stop function used during training

  • « fann_set_train_error_function
  • fann_set_training_algorithm »
  • PHP Manual
  • Fann Functions
  • Sets the stop function used during training

fann_set_train_stop_function

(PECL fann >= 1.0.0)

fann_set_train_stop_function — Sets the stop function used during training

Description

fann_set_train_stop_function ( resource $ann , int $stop_function ) : bool

Sets the stop function used during training.

The stop functions are described further in stop functions constants.

Parameters

ann

Neural network resource.

stop_function

The stop function constant.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_train_stop_function() - Returns the stop function used during training


Sets the training algorithm

  • « fann_set_train_stop_function
  • fann_set_weight_array »
  • PHP Manual
  • Fann Functions
  • Sets the training algorithm

fann_set_training_algorithm

(PECL fann >= 1.0.0)

fann_set_training_algorithm — Sets the training algorithm

Description

fann_set_training_algorithm ( resource $ann , int $training_algorithm ) : bool

Sets the training algorithm.

More info available in fann_get_training_algorithm().

Parameters

ann

Neural network resource.

training_algorithm

Training algorithm constant

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_get_training_algorithm() - Returns the training algorithm


Set connections in the network

  • « fann_set_training_algorithm
  • fann_set_weight »
  • PHP Manual
  • Fann Functions
  • Set connections in the network

fann_set_weight_array

(PECL fann >= 1.0.0)

fann_set_weight_array — Set connections in the network

Description

fann_set_weight_array ( resource $ann , array $connections ) : bool

Set connections in the network.

Only the weights can be changed, connections and weights are ignored if they do not already exist in the network.

Parameters

ann

Neural network resource.

connections

An array of FANNConnection objects

Return Values

Returns TRUE on success, or FALSE otherwise.


Set a connection in the network

  • « fann_set_weight_array
  • fann_shuffle_train_data »
  • PHP Manual
  • Fann Functions
  • Set a connection in the network

fann_set_weight

(PECL fann >= 1.0.0)

fann_set_weight — Set a connection in the network

Description

fann_set_weight ( resource $ann , int $from_neuron , int $to_neuron , float $weight ) : bool

Set a connections in the network.

Parameters

ann

Neural network resource.

from_neuron

The neuron where the connection starts

to_neuron

The neuron where the connection ends

weight

Connection weight

Return Values

Returns TRUE on success, or FALSE otherwise.


Shuffles training data, randomizing the order

  • « fann_set_weight
  • fann_subset_train_data »
  • PHP Manual
  • Fann Functions
  • Shuffles training data, randomizing the order

fann_shuffle_train_data

(PECL fann >= 1.0.0)

fann_shuffle_train_data — Shuffles training data, randomizing the order

Description

fann_shuffle_train_data ( resource $train_data ) : bool

Shuffles training data, randomizing the order. This is recommended for incremental training, while it have no influence during batch training.

Parameters

train_data

Neural network training data resource.

Return Values

Returns TRUE on success, or FALSE otherwise.


Returns an copy of a subset of the train data

  • « fann_shuffle_train_data
  • fann_test_data »
  • PHP Manual
  • Fann Functions
  • Returns an copy of a subset of the train data

fann_subset_train_data

(PECL fann >= 1.0.0)

fann_subset_train_data — Returns an copy of a subset of the train data

Description

fann_subset_train_data ( resource $data , int $pos , int $length ) : resource

Returns an copy of a subset of the train data resource, starting at position pos and length elements forward.

The fann_subset_train_data(train_data, 0, fann_length_train_data(train_data)) do the same as fann_duplicate_train_data()

Parameters

data

Neural network training data resource.

pos

Starting position.

length

The number of copied elements.

Return Values

Returns a train data resource on success, or FALSE on error.

See Also

  • fann_duplicate_train_data() - Returns an exact copy of a fann train data


Test a set of training data and calculates the MSE for the training data

  • « fann_subset_train_data
  • fann_test »
  • PHP Manual
  • Fann Functions
  • Test a set of training data and calculates the MSE for the training data

fann_test_data

(PECL fann >= 1.0.0)

fann_test_data — Test a set of training data and calculates the MSE for the training data

Description

fann_test_data ( resource $ann , resource $data ) : float

Test a set of training data and calculates the MSE for the training data.

This function updates the MSE and the bit fail values.

Parameters

ann

Neural network resource.

data

Neural network training data resource.

Return Values

The updated MSE, or FALSE on error.

See Also

  • fann_train_on_data() - Trains on an entire dataset for a period of time
  • fann_train_epoch() - Train one epoch with a set of training data
  • fann_get_bit_fail() - The number of fail bits
  • fann_get_MSE() - Reads the mean square error from the network
  • fann_set_training_algorithm() - Sets the training algorithm


Test with a set of inputs, and a set of desired outputs

  • « fann_test_data
  • fann_train_epoch »
  • PHP Manual
  • Fann Functions
  • Test with a set of inputs, and a set of desired outputs

fann_test

(PECL fann >= 1.0.0)

fann_test — Test with a set of inputs, and a set of desired outputs

Description

fann_test ( resource $ann , array $input , array $desired_output ) : array

Test with a set of inputs, and a set of desired outputs. This operation updates the mean square error, but does not change the network in any way.

Parameters

ann

Neural network resource.

input

An array of inputs. This array must be exactly fann_get_num_input() long.

desired_output

An array of desired outputs. This array must be exactly fann_get_num_output() long.

Return Values

Returns test outputs on success, or FALSE on error.

See Also

  • fann_test_data() - Test a set of training data and calculates the MSE for the training data
  • fann_train() - Train one iteration with a set of inputs, and a set of desired outputs
  • fann_get_num_input() - Get the number of input neurons
  • fann_get_num_output() - Get the number of output neurons


Train one epoch with a set of training data

  • « fann_test
  • fann_train_on_data »
  • PHP Manual
  • Fann Functions
  • Train one epoch with a set of training data

fann_train_epoch

(PECL fann >= 1.0.0)

fann_train_epoch — Train one epoch with a set of training data

Description

fann_train_epoch ( resource $ann , resource $data ) : float

Train one epoch with the training data stored in data. One epoch is where all of the training data is considered exactly once.

This function returns the MSE error as it is calculated either before or during the actual training. This is not the actual MSE after the training epoch, but since calculating this will require to go through the entire training set once more. It is more than adequate to use this value during training.

The training algorithm used by this function is chosen by fann_set_training_algorithm() function.

Parameters

ann

Neural network resource.

data

Neural network training data resource.

Return Values

The MSE, or FALSE on error.

See Also

  • fann_train_on_data() - Trains on an entire dataset for a period of time
  • fann_test_data() - Test a set of training data and calculates the MSE for the training data
  • fann_get_MSE() - Reads the mean square error from the network
  • fann_set_training_algorithm() - Sets the training algorithm


Trains on an entire dataset for a period of time

  • « fann_train_epoch
  • fann_train_on_file »
  • PHP Manual
  • Fann Functions
  • Trains on an entire dataset for a period of time

fann_train_on_data

(PECL fann >= 1.0.0)

fann_train_on_data — Trains on an entire dataset for a period of time

Description

fann_train_on_data ( resource $ann , resource $data , int $max_epochs , int $epochs_between_reports , float $desired_error ) : bool

Trains on an entire dataset for a period of time.

This training uses the training algorithm chosen by fann_set_training_algorithm() and the parameters set for these training algorithms.

Parameters

ann

Neural network resource.

data

Neural network training data resource.

max_epochs

The maximum number of epochs the training should continue

epochs_between_reports

The number of epochs between calling a callback function. A value of zero means that user function is not called.

desired_error

The desired fann_get_MSE() or fann_get_bit_fail(), depending on the stop function chosen by fann_set_train_stop_function()

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_train_on_file() - Trains on an entire dataset, which is read from file, for a period of time
  • fann_train_epoch() - Train one epoch with a set of training data
  • fann_get_bit_fail() - The number of fail bits
  • fann_get_MSE() - Reads the mean square error from the network
  • fann_set_train_stop_function() - Sets the stop function used during training
  • fann_set_training_algorithm() - Sets the training algorithm
  • fann_set_callback() - Sets the callback function for use during training


Trains on an entire dataset, which is read from file, for a period of time

  • « fann_train_on_data
  • fann_train »
  • PHP Manual
  • Fann Functions
  • Trains on an entire dataset, which is read from file, for a period of time

fann_train_on_file

(PECL fann >= 1.0.0)

fann_train_on_file — Trains on an entire dataset, which is read from file, for a period of time

Description

fann_train_on_file ( resource $ann , string $filename , int $max_epochs , int $epochs_between_reports , float $desired_error ) : bool

Trains on an entire dataset, which is read from file, for a period of time.

This training uses the training algorithm chosen by fann_set_training_algorithm() and the parameters set for these training algorithms.

Parameters

ann

Neural network resource.

filename

The file containing train data

max_epochs

The maximum number of epochs the training should continue

epochs_between_reports

The number of epochs between calling a user function. A value of zero means that user function is not called.

desired_error

The desired fann_get_MSE() or fann_get_bit_fail(), depending on the stop function chosen by fann_set_train_stop_function()

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_train_on_data() - Trains on an entire dataset for a period of time
  • fann_train_epoch() - Train one epoch with a set of training data
  • fann_get_bit_fail() - The number of fail bits
  • fann_get_MSE() - Reads the mean square error from the network
  • fann_set_train_stop_function() - Sets the stop function used during training
  • fann_set_training_algorithm() - Sets the training algorithm
  • fann_set_callback() - Sets the callback function for use during training


Train one iteration with a set of inputs, and a set of desired outputs

  • « fann_train_on_file
  • FANNConnection »
  • PHP Manual
  • Fann Functions
  • Train one iteration with a set of inputs, and a set of desired outputs

fann_train

(PECL fann >= 1.0.0)

fann_train — Train one iteration with a set of inputs, and a set of desired outputs

Description

fann_train ( resource $ann , array $input , array $desired_output ) : bool

Train one iteration with a set of inputs, and a set of desired outputs. This training is always incremental training, since only one pattern is presented.

Parameters

ann

Neural network resource.

input

An array of inputs. This array must be exactly fann_get_num_input() long.

desired_output

An array of desired outputs. This array must be exactly fann_get_num_output() long.

Return Values

Returns TRUE on success, or FALSE otherwise.

See Also

  • fann_train_on_data() - Trains on an entire dataset for a period of time
  • fann_train_epoch() - Train one epoch with a set of training data
  • fann_get_num_input() - Get the number of input neurons
  • fann_get_num_output() - Get the number of output neurons


The FANNConnection class

(No version information available, might only be in Git)

Introduction

FANNConnection is used for the neural network connection. The objects of this class are used in fann_get_connection_array() and fann_set_weight_array().

Class synopsis

FANNConnection {
/* Properties */
public $from_neuron ;
public $to_neuron ;
public $weight ;
/* Methods */
public __construct ( int $from_neuron , int $to_neuron , float $weight )
public getFromNeuron ( void ) : int
public getToNeuron ( void ) : int
public getWeight ( void ) : void
public setWeight ( float $weight ) : void
}

Properties

from_neuron

The neuron where the connection starts.

to_neuron

The neuron where the connection ends.

weight

The weight of the connection.

Table of Contents

  • FANNConnection::__construct — The connection constructor
  • FANNConnection::getFromNeuron — Returns the postions of starting neuron
  • FANNConnection::getToNeuron — Returns the postions of terminating neuron
  • FANNConnection::getWeight — Returns the connection weight
  • FANNConnection::setWeight — Sets the connections weight


The connection constructor

  • « FANNConnection
  • FANNConnection::getFromNeuron »
  • PHP Manual
  • FANNConnection
  • The connection constructor

FANNConnection::__construct

(PECL fann >= 1.0.0)

FANNConnection::__construct — The connection constructor

Description

public FANNConnection::__construct ( int $from_neuron , int $to_neuron , float $weight )

Create new connection and initialize its params. After creating the connection, only weight can be changed.

Parameters

from_neuron

The postion number of starting neuron.

to_neuron

The postion number of terminating neuron.

weight

The connection weight value.


Returns the postions of starting neuron

  • « FANNConnection::__construct
  • FANNConnection::getToNeuron »
  • PHP Manual
  • FANNConnection
  • Returns the postions of starting neuron

FANNConnection::getFromNeuron

(PECL fann >= 1.0.0)

FANNConnection::getFromNeuron — Returns the postions of starting neuron

Description

public FANNConnection::getFromNeuron ( void ) : int

Returns the postions of starting neuron.

Parameters

This function has no parameters.

Return Values

The postions of starting neuron.


Returns the postions of terminating neuron

  • « FANNConnection::getFromNeuron
  • FANNConnection::getWeight »
  • PHP Manual
  • FANNConnection
  • Returns the postions of terminating neuron

FANNConnection::getToNeuron

(PECL fann >= 1.0.0)

FANNConnection::getToNeuron — Returns the postions of terminating neuron

Description

public FANNConnection::getToNeuron ( void ) : int

Returns the postions of terminating neuron.

Parameters

This function has no parameters.

Return Values

The postions of terminating neuron.


Returns the connection weight

  • « FANNConnection::getToNeuron
  • FANNConnection::setWeight »
  • PHP Manual
  • FANNConnection
  • Returns the connection weight

FANNConnection::getWeight

(PECL fann >= 1.0.0)

FANNConnection::getWeight — Returns the connection weight

Description

public FANNConnection::getWeight ( void ) : void

Returns the connection weight.

Parameters

This function has no parameters.

Return Values

The connection weight.


Sets the connections weight

  • « FANNConnection::getWeight
  • JSON »
  • PHP Manual
  • FANNConnection
  • Sets the connections weight

FANNConnection::setWeight

(PECL fann >= 1.0.0)

FANNConnection::setWeight — Sets the connections weight

Description

public FANNConnection::setWeight ( float $weight ) : void

Sets the connection weight.

This method is different than fann_set_weight(). It does not update the weight value in the network. The network value is updated only after calling fann_set_weight_array().

Parameters

weight

The connection weight.

Return Values

No value is returned.


JavaScript Object Notation

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • JsonException — The JsonException class
  • JsonSerializable — The JsonSerializable interface
    • JsonSerializable::jsonSerialize — Specify data which should be serialized to JSON
  • JSON Functions
    • json_decode — Decodes a JSON string
    • json_encode — Returns the JSON representation of a value
    • json_last_error_msg — Returns the error string of the last json_encode() or json_decode() call
    • json_last_error — Returns the last error occurred


Introduction

This extension implements the » JavaScript Object Notation (JSON) data-interchange format. The decoding in PHP 5 is handled by a parser based on the JSON_checker by Douglas Crockford. PHP 7 comes with a completely new and improved parser that is specifically written for PHP and licensed under the PHP license.

Note:

PHP implements a superset of JSON as specified in the original » RFC 7159.


Installation

As of PHP 5.2.0, the JSON extension is bundled and compiled into PHP by default.

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/json


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 indicate the type of error returned by json_last_error() or stored as the code of a JsonException.

JSON_ERROR_NONE (integer)
No error has occurred. Available as of PHP 5.3.0.
JSON_ERROR_DEPTH (integer)
The maximum stack depth has been exceeded. Available as of PHP 5.3.0.
JSON_ERROR_STATE_MISMATCH (integer)
Occurs with underflow or with the modes mismatch. Available as of PHP 5.3.0.
JSON_ERROR_CTRL_CHAR (integer)
Control character error, possibly incorrectly encoded. Available as of PHP 5.3.0.
JSON_ERROR_SYNTAX (integer)
Syntax error. Available as of PHP 5.3.0.
JSON_ERROR_UTF8 (integer)
Malformed UTF-8 characters, possibly incorrectly encoded. Available as of PHP 5.3.3.
JSON_ERROR_RECURSION (integer)
The object or array passed to json_encode() include recursive references and cannot be encoded. If the JSON_PARTIAL_OUTPUT_ON_ERROR option was given, NULL will be encoded in the place of the recursive reference. Available as of PHP 5.5.0.
JSON_ERROR_INF_OR_NAN (integer)
The value passed to json_encode() includes either NAN or INF. If the JSON_PARTIAL_OUTPUT_ON_ERROR option was given, 0 will be encoded in the place of these special numbers. Available as of PHP 5.5.0.
JSON_ERROR_UNSUPPORTED_TYPE (integer)
A value of an unsupported type was given to json_encode(), such as a resource. If the JSON_PARTIAL_OUTPUT_ON_ERROR option was given, NULL will be encoded in the place of the unsupported value. Available as of PHP 5.5.0.
JSON_ERROR_INVALID_PROPERTY_NAME (integer)
A key starting with \u0000 character was in the string passed to json_decode() when decoding a JSON object into a PHP object. Available as of PHP 7.0.0.
JSON_ERROR_UTF16 (integer)
Single unpaired UTF-16 surrogate in unicode escape contained in the JSON string passed to json_decode(). Available as of PHP 7.0.0.

The following constants can be combined to form options for json_decode().

JSON_BIGINT_AS_STRING (integer)
Decodes large integers as their original string value. Available as of PHP 5.4.0.
JSON_OBJECT_AS_ARRAY (integer)
Decodes JSON objects as PHP array. This option can be added automatically by calling json_decode() with the second parameter equal to TRUE. Available as of PHP 5.4.0.

The following constants can be combined to form options for json_encode().

JSON_HEX_TAG (integer)
All < and > are converted to \u003C and \u003E. Available as of PHP 5.3.0.
JSON_HEX_AMP (integer)
All & are converted to \u0026. Available as of PHP 5.3.0.
JSON_HEX_APOS (integer)
All ' are converted to \u0027. Available as of PHP 5.3.0.
JSON_HEX_QUOT (integer)
All " are converted to \u0022. Available as of PHP 5.3.0.
JSON_FORCE_OBJECT (integer)
Outputs an object rather than an array when a non-associative array is used. Especially useful when the recipient of the output is expecting an object and the array is empty. Available as of PHP 5.3.0.
JSON_NUMERIC_CHECK (integer)
Encodes numeric strings as numbers. Available as of PHP 5.3.3.
JSON_PRETTY_PRINT (integer)
Use whitespace in returned data to format it. Available as of PHP 5.4.0.
JSON_UNESCAPED_SLASHES (integer)
Don't escape /. Available as of PHP 5.4.0.
JSON_UNESCAPED_UNICODE (integer)
Encode multibyte Unicode characters literally (default is to escape as \uXXXX). Available as of PHP 5.4.0.
JSON_PARTIAL_OUTPUT_ON_ERROR (integer)
Substitute some unencodable values instead of failing. Available as of PHP 5.5.0.
JSON_PRESERVE_ZERO_FRACTION (integer)
Ensures that float values are always encoded as a float value. Available as of PHP 5.6.6.
JSON_UNESCAPED_LINE_TERMINATORS (integer)
The line terminators are kept unescaped when JSON_UNESCAPED_UNICODE is supplied. It uses the same behaviour as it was before PHP 7.1 without this constant. Available as of PHP 7.1.0.

The following constants can be combined to form options for json_decode() and json_encode().

JSON_INVALID_UTF8_IGNORE (integer)
Ignore invalid UTF-8 characters. Available as of PHP 7.2.0.
JSON_INVALID_UTF8_SUBSTITUTE (integer)
Convert invalid UTF-8 characters to \0xfffd (Unicode Character 'REPLACEMENT CHARACTER') Available as of PHP 7.2.0.
JSON_THROW_ON_ERROR (integer)
Throws JsonException if an error occurs instead of setting the global error state that is retrieved with json_last_error() and json_last_error_msg(). JSON_PARTIAL_OUTPUT_ON_ERROR takes precedence over JSON_THROW_ON_ERROR. Available as of PHP 7.3.0.


The JsonException class

(PHP 7 >= 7.3.0)

Introduction

Exception thrown if JSON_THROW_ON_ERROR option is
set for json_encode() or
json_decode(). code contains the error
type, for possible values see json_last_error().

Class synopsis

JsonException extends Exception {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The JsonSerializable interface

(PHP 5 >= 5.4.0, PHP 7)

Introduction

Objects implementing JsonSerializable can customize their JSON representation when encoded with json_encode().

Interface synopsis

JsonSerializable {
/* Methods */
abstract public jsonSerialize ( void ) : mixed
}

Table of Contents

  • JsonSerializable::jsonSerialize — Specify data which should be serialized to JSON


Specify data which should be serialized to JSON

  • « JsonSerializable
  • JSON Functions »
  • PHP Manual
  • JsonSerializable
  • Specify data which should be serialized to JSON

JsonSerializable::jsonSerialize

(PHP 5 >= 5.4.0, PHP 7)

JsonSerializable::jsonSerialize — Specify data which should be serialized to JSON

Description

abstract public JsonSerializable::jsonSerialize ( void ) : mixed

Serializes the object to a value that can be serialized natively by json_encode().

Parameters

This function has no parameters.

Return Values

Returns data which can be serialized by json_encode(), which is a value of any type other than a resource.

Examples

Example #1 JsonSerializable::jsonSerialize() example returning an array

<?php
class ArrayValue implements JsonSerializable {
    public function __construct(array $array) {
        $this->array = $array;
    }

    public function jsonSerialize() {
        return $this->array;
    }
}

$array = [1, 2, 3];
echo json_encode(new ArrayValue($array), JSON_PRETTY_PRINT);
?>

The above example will output:

[
    1,
    2,
    3
]

Example #2 JsonSerializable::jsonSerialize() example returning an associative array

<?php
class ArrayValue implements JsonSerializable {
    public function __construct(array $array) {
        $this->array = $array;
    }

    public function jsonSerialize() {
        return $this->array;
    }
}

$array = ['foo' => 'bar', 'quux' => 'baz'];
echo json_encode(new ArrayValue($array), JSON_PRETTY_PRINT);
?>

The above example will output:

{
    "foo": "bar",
    "quux": "baz"
}

Example #3 JsonSerializable::jsonSerialize() example returning an integer

<?php
class IntegerValue implements JsonSerializable {
    public function __construct($number) {
        $this->number = (integer) $number;
    }

    public function jsonSerialize() {
        return $this->number;
    }
}

echo json_encode(new IntegerValue(1), JSON_PRETTY_PRINT);
?>

The above example will output:

1

Example #4 JsonSerializable::jsonSerialize() example returning a string

<?php
class StringValue implements JsonSerializable {
    public function __construct($string) {
        $this->string = (string) $string;
    }

    public function jsonSerialize() {
        return $this->string;
    }
}

echo json_encode(new StringValue('Hello!'), JSON_PRETTY_PRINT);
?>

The above example will output:

"Hello!"


JSON Functions

Table of Contents

  • json_decode — Decodes a JSON string
  • json_encode — Returns the JSON representation of a value
  • json_last_error_msg — Returns the error string of the last json_encode() or json_decode() call
  • json_last_error — Returns the last error occurred


Decodes a JSON string

  • « JSON Functions
  • json_encode »
  • PHP Manual
  • JSON Functions
  • Decodes a JSON string

json_decode

(PHP 5 >= 5.2.0, PHP 7, PECL json >= 1.2.0)

json_decode — Decodes a JSON string

Description

json_decode ( string $json [, bool $assoc = FALSE [, int $depth = 512 [, int $options = 0 ]]] ) : mixed

Takes a JSON encoded string and converts it into a PHP variable.

Parameters

json

The json string being decoded.

This function only works with UTF-8 encoded strings.

Note:

PHP implements a superset of JSON as specified in the original » RFC 7159.

assoc

When TRUE, returned objects will be converted into associative arrays.

depth

User specified recursion depth.

options

Bitmask of JSON_BIGINT_AS_STRING, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_OBJECT_AS_ARRAY, JSON_THROW_ON_ERROR. The behaviour of these constants is described on the JSON constants page.

Return Values

Returns the value encoded in json in appropriate PHP type. Values true, false and null are returned as TRUE, FALSE and NULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.

Changelog

Version | Description
7.3.0 | JSON_THROW_ON_ERROR options was added.
7.2.0 | JSON_INVALID_UTF8_IGNORE, and JSON_INVALID_UTF8_SUBSTITUTE options were added.
7.1.0 | An empty JSON key ("") can be encoded to the empty object property instead of using a key with value _empty_.
7.0.0 | Rejected RFC 7159 incompatible number formats - top level (07, 0xff, .1, -.1) and all levels ([1.], [1.e1])
7.0.0 | An empty PHP string or value that after casting to string is an empty string (NULL, FALSE) results in JSON syntax error.
5.6.0 | Invalid non-lowercased variants of the true, false and null literals are no longer accepted as valid input, and will generate warnings.
5.4.0 | JSON_BIGINT_AS_STRING, and JSON_OBJECT_AS_ARRAY options were added.
5.4.0 | The options parameter was added.
5.3.0 | Added the optional depth. The default recursion depth was increased from 128 to 512
5.2.3 | The nesting limit was increased from 20 to 128
5.2.1 | Added support for JSON decoding of basic types.

Examples

Example #1 json_decode() examples

<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($json, true));

?>

The above example will output:

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

Example #2 Accessing invalid object properties

Accessing elements within an object that contain characters not permitted under PHP's naming convention (e.g. the hyphen) can be accomplished by encapsulating the element name within braces and the apostrophe.

<?php

$json = '{"foo-bar": 12345}';

$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345

?>

Example #3 common mistakes using json_decode()

<?php

// the following strings are valid JavaScript but not valid JSON

// the name and value must be enclosed in double quotes
// single quotes are not valid
$bad_json = "{ 'bar': 'baz' }";
json_decode($bad_json); // null

// the name must be enclosed in double quotes
$bad_json = '{ bar: "baz" }';
json_decode($bad_json); // null

// trailing commas are not allowed
$bad_json = '{ bar: "baz", }';
json_decode($bad_json); // null

?>

Example #4 depth errors

<?php
// Encode the data.
$json = json_encode(
    array(
        1 => array(
            'English' => array(
                'One',
                'January'
            ),
            'French' => array(
                'Une',
                'Janvier'
            )
        )
    )
);

// Define the errors.
$constants = get_defined_constants(true);
$json_errors = array();
foreach ($constants["json"] as $name => $value) {
    if (!strncmp($name, "JSON_ERROR_", 11)) {
        $json_errors[$value] = $name;
    }
}

// Show the errors for different depths.
foreach (range(4, 3, -1) as $depth) {
    var_dump(json_decode($json, true, $depth));
    echo 'Last error: ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL;
}
?>

The above example will output:

array(1) {
  [1]=>
  array(2) {
    ["English"]=>
    array(2) {
      [0]=>
      string(3) "One"
      [1]=>
      string(7) "January"
    }
    ["French"]=>
    array(2) {
      [0]=>
      string(3) "Une"
      [1]=>
      string(7) "Janvier"
    }
  }
}
Last error: JSON_ERROR_NONE

NULL
Last error: JSON_ERROR_DEPTH

Example #5 json_decode() of large integers

<?php
$json = '{"number": 12345678901234567890}';

var_dump(json_decode($json));
var_dump(json_decode($json, false, 512, JSON_BIGINT_AS_STRING));

?>

The above example will output:

object(stdClass)#1 (1) {
  ["number"]=>
  float(1.2345678901235E+19)
}
object(stdClass)#1 (1) {
  ["number"]=>
  string(20) "12345678901234567890"
}

Notes

Note:

The JSON spec is not JavaScript, but a subset of JavaScript.

Note:

In the event of a failure to decode, json_last_error() can be used to determine the exact nature of the error.

See Also

  • json_encode() - Returns the JSON representation of a value
  • json_last_error() - Returns the last error occurred


Returns the JSON representation of a value

  • « json_decode
  • json_last_error_msg »
  • PHP Manual
  • JSON Functions
  • Returns the JSON representation of a value

json_encode

(PHP 5 >= 5.2.0, PHP 7, PECL json >= 1.2.0)

json_encode — Returns the JSON representation of a value

Description

json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] ) : string

Returns a string containing the JSON representation of the supplied value.

The encoding is affected by the supplied options and additionally the encoding of float values depends on the value of serialize_precision.

Parameters

value

The value being encoded. Can be any type except a resource.

All string data must be UTF-8 encoded.

Note:

PHP implements a superset of JSON as specified in the original » RFC 7159.

options

Bitmask consisting of JSON_FORCE_OBJECT, JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_NUMERIC_CHECK, JSON_PARTIAL_OUTPUT_ON_ERROR, JSON_PRESERVE_ZERO_FRACTION, JSON_PRETTY_PRINT, JSON_UNESCAPED_LINE_TERMINATORS, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE, JSON_THROW_ON_ERROR. The behaviour of these constants is described on the JSON constants page.

depth

Set the maximum depth. Must be greater than zero.

Return Values

Returns a JSON encoded string on success or FALSE on failure.

Changelog

Version | Description
7.3.0 | JSON_THROW_ON_ERROR options was added.
7.2.0 | JSON_INVALID_UTF8_IGNORE, and JSON_INVALID_UTF8_SUBSTITUTE options were added.
7.1.0 | JSON_UNESCAPED_LINE_TERMINATORS options was added.
7.1.0 | serialize_precision is used instead of precision when encoding double values.
5.6.6 | JSON_PRESERVE_ZERO_FRACTION options was added.
5.5.0 | depth parameter was added.
5.5.0 | JSON_PARTIAL_OUTPUT_ON_ERROR options was added.
5.5.0 | The return value on failure was changed from null string to FALSE.
5.4.0 | JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, and JSON_UNESCAPED_UNICODE options were added.
5.3.3 | JSON_NUMERIC_CHECK options was added.
5.3.0 | JSON_FORCE_OBJECT, JSON_HEX_AMP, JSON_HEX_APOS, JSON_HEX_QUOT, and JSON_HEX_TAG, options were added.
5.3.0 | The options parameter was added.

Examples

Example #1 A json_encode() example

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr);
?>

The above example will output:

{"a":1,"b":2,"c":3,"d":4,"e":5}

Example #2 A json_encode() example showing some options in use

<?php
$a = array('<foo>',"'bar'",'"baz"','&blong&', "\xc3\xa9");

echo "Normal: ",  json_encode($a), "\n";
echo "Tags: ",    json_encode($a, JSON_HEX_TAG), "\n";
echo "Apos: ",    json_encode($a, JSON_HEX_APOS), "\n";
echo "Quot: ",    json_encode($a, JSON_HEX_QUOT), "\n";
echo "Amp: ",     json_encode($a, JSON_HEX_AMP), "\n";
echo "Unicode: ", json_encode($a, JSON_UNESCAPED_UNICODE), "\n";
echo "All: ",     json_encode($a, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE), "\n\n";

$b = array();

echo "Empty array output as array: ", json_encode($b), "\n";
echo "Empty array output as object: ", json_encode($b, JSON_FORCE_OBJECT), "\n\n";

$c = array(array(1,2,3));

echo "Non-associative array output as array: ", json_encode($c), "\n";
echo "Non-associative array output as object: ", json_encode($c, JSON_FORCE_OBJECT), "\n\n";

$d = array('foo' => 'bar', 'baz' => 'long');

echo "Associative array always output as object: ", json_encode($d), "\n";
echo "Associative array always output as object: ", json_encode($d, JSON_FORCE_OBJECT), "\n\n";
?>

The above example will output:

Normal: ["<foo>","'bar'","\"baz\"","&blong&","\u00e9"]
Tags: ["\u003Cfoo\u003E","'bar'","\"baz\"","&blong&","\u00e9"]
Apos: ["<foo>","\u0027bar\u0027","\"baz\"","&blong&","\u00e9"]
Quot: ["<foo>","'bar'","\u0022baz\u0022","&blong&","\u00e9"]
Amp: ["<foo>","'bar'","\"baz\"","\u0026blong\u0026","\u00e9"]
Unicode: ["<foo>","'bar'","\"baz\"","&blong&","é"]
All: ["\u003Cfoo\u003E","\u0027bar\u0027","\u0022baz\u0022","\u0026blong\u0026","é"]

Empty array output as array: []
Empty array output as object: {}

Non-associative array output as array: [[1,2,3]]
Non-associative array output as object: {"0":{"0":1,"1":2,"2":3}}

Associative array always output as object: {"foo":"bar","baz":"long"}
Associative array always output as object: {"foo":"bar","baz":"long"}

Example #3 JSON_NUMERIC_CHECK option example

<?php
echo "Strings representing numbers automatically turned into numbers".PHP_EOL;
$numbers = array('+123123', '-123123', '1.2e3', '0.00001');
var_dump(
 $numbers,
 json_encode($numbers, JSON_NUMERIC_CHECK)
);
echo "Strings containing improperly formatted numbers".PHP_EOL;
$strings = array('+a33123456789', 'a123');
var_dump(
 $strings,
 json_encode($strings, JSON_NUMERIC_CHECK)
);
?>

The above example will output something similar to:

Strings representing numbers automatically turned into numbers
array(4) {
  [0]=>
  string(7) "+123123"
  [1]=>
  string(7) "-123123"
  [2]=>
  string(5) "1.2e3"
  [3]=>
  string(7) "0.00001"
}
string(28) "[123123,-123123,1200,1.0e-5]"
Strings containing improperly formatted numbers
array(2) {
  [0]=>
  string(13) "+a33123456789"
  [1]=>
  string(4) "a123"
}
string(24) "["+a33123456789","a123"]"

Example #4 Sequential versus non-sequential array example

<?php
echo "Sequential array".PHP_EOL;
$sequential = array("foo", "bar", "baz", "blong");
var_dump(
 $sequential,
 json_encode($sequential)
);

echo PHP_EOL."Non-sequential array".PHP_EOL;
$nonsequential = array(1=>"foo", 2=>"bar", 3=>"baz", 4=>"blong");
var_dump(
 $nonsequential,
 json_encode($nonsequential)
);

echo PHP_EOL."Sequential array with one key unset".PHP_EOL;
unset($sequential[1]);
var_dump(
 $sequential,
 json_encode($sequential)
);
?>

The above example will output:

Sequential array
array(4) {
  [0]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  [2]=>
  string(3) "baz"
  [3]=>
  string(5) "blong"
}
string(27) "["foo","bar","baz","blong"]"

Non-sequential array
array(4) {
  [1]=>
  string(3) "foo"
  [2]=>
  string(3) "bar"
  [3]=>
  string(3) "baz"
  [4]=>
  string(5) "blong"
}
string(43) "{"1":"foo","2":"bar","3":"baz","4":"blong"}"

Sequential array with one key unset
array(3) {
  [0]=>
  string(3) "foo"
  [2]=>
  string(3) "baz"
  [3]=>
  string(5) "blong"
}
string(33) "{"0":"foo","2":"baz","3":"blong"}"

Example #5 JSON_PRESERVE_ZERO_FRACTION option example

<?php
var_dump(json_encode(12.0, JSON_PRESERVE_ZERO_FRACTION));
var_dump(json_encode(12.0));
?>

The above example will output:

string(4) "12.0"
string(2) "12"

Notes

Note:

In the event of a failure to encode, json_last_error() can be used to determine the exact nature of the error.

Note:

When encoding an array, if the keys are not a continuous numeric sequence starting from 0, all keys are encoded as strings, and specified explicitly for each key-value pair.

Note:

Like the reference JSON encoder, json_encode() will generate JSON that is a simple value (that is, neither an object nor an array) if given a string, integer, float or boolean as an input value. While most decoders will accept these values as valid JSON, some may not, as the specification is ambiguous on this point.

To summarise, always test that your JSON decoder can handle the output you generate from json_encode().

See Also

  • JsonSerializable
  • json_decode() - Decodes a JSON string
  • json_last_error() - Returns the last error occurred
  • serialize() - Generates a storable representation of a value


Returns the error string of the last json_encode() or json_decode() call

  • « json_encode
  • json_last_error »
  • PHP Manual
  • JSON Functions
  • Returns the error string of the last json_encode() or json_decode() call

json_last_error_msg

(PHP 5 >= 5.5.0, PHP 7)

json_last_error_msg — Returns the error string of the last json_encode() or json_decode() call

Description

json_last_error_msg ( void ) : string

Returns the error string of the last json_encode() or json_decode() call, which did not specify JSON_THROW_ON_ERROR.

Parameters

This function has no parameters.

Return Values

Returns the error message on success, "No error" if no error has occurred, or FALSE on failure.

See Also

  • json_last_error() - Returns the last error occurred


Returns the last error occurred

  • « json_last_error_msg
  • Judy »
  • PHP Manual
  • JSON Functions
  • Returns the last error occurred

json_last_error

(PHP 5 >= 5.3.0, PHP 7)

json_last_error — Returns the last error occurred

Description

json_last_error ( void ) : int

Returns the last error (if any) occurred during the last JSON encoding/decoding, which did not specify JSON_THROW_ON_ERROR.

Parameters

This function has no parameters.

Return Values

Returns an integer, the value can be one of the following constants:

JSON error codes
Constant | Meaning | Availability
JSON_ERROR_NONE | No error has occurred |
JSON_ERROR_DEPTH | The maximum stack depth has been exceeded |
JSON_ERROR_STATE_MISMATCH | Invalid or malformed JSON |
JSON_ERROR_CTRL_CHAR | Control character error, possibly incorrectly encoded |
JSON_ERROR_SYNTAX | Syntax error |
JSON_ERROR_UTF8 | Malformed UTF-8 characters, possibly incorrectly encoded | PHP 5.3.3
JSON_ERROR_RECURSION | One or more recursive references in the value to be encoded | PHP 5.5.0
JSON_ERROR_INF_OR_NAN | One or more NAN or INF values in the value to be encoded | PHP 5.5.0
JSON_ERROR_UNSUPPORTED_TYPE | A value of a type that cannot be encoded was given | PHP 5.5.0
JSON_ERROR_INVALID_PROPERTY_NAME | A property name that cannot be encoded was given | PHP 7.0.0
JSON_ERROR_UTF16 | Malformed UTF-16 characters, possibly incorrectly encoded | PHP 7.0.0

Examples

Example #1 json_last_error() example

<?php
// A valid json string
$json[] = '{"Organization": "PHP Documentation Team"}';

// An invalid json string which will cause an syntax
// error, in this case we used ' instead of " for quotation
$json[] = "{'Organization': 'PHP Documentation Team'}";

foreach ($json as $string) {
    echo 'Decoding: ' . $string;
    json_decode($string);

    switch (json_last_error()) {
        case JSON_ERROR_NONE:
            echo ' - No errors';
        break;
        case JSON_ERROR_DEPTH:
            echo ' - Maximum stack depth exceeded';
        break;
        case JSON_ERROR_STATE_MISMATCH:
            echo ' - Underflow or the modes mismatch';
        break;
        case JSON_ERROR_CTRL_CHAR:
            echo ' - Unexpected control character found';
        break;
        case JSON_ERROR_SYNTAX:
            echo ' - Syntax error, malformed JSON';
        break;
        case JSON_ERROR_UTF8:
            echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
        break;
        default:
            echo ' - Unknown error';
        break;
    }

    echo PHP_EOL;
}
?>

The above example will output:

Decoding: {"Organization": "PHP Documentation Team"} - No errors
Decoding: {'Organization': 'PHP Documentation Team'} - Syntax error, malformed JSON

Example #2 json_last_error() with json_encode()

<?php
// An invalid UTF8 sequence
$text = "\xB1\x31";

$json  = json_encode($text);
$error = json_last_error();

var_dump($json, $error === JSON_ERROR_UTF8);
?>

The above example will output:

string(4) "null"
bool(true)

Example #3 json_last_error() and JSON_THROW_ON_ERROR

<?php
// An invalid UTF8 sequence which causes JSON_ERROR_UTF8
json_encode("\xB1\x31");

// The following does not cause a JSON error
json_encode('okay', JSON_THROW_ON_ERROR);

// The global error state has not been changed by the former json_encode()
var_dump(json_last_error() === JSON_ERROR_UTF8);
?>

The above example will output:

bool(true)

See Also

  • json_last_error_msg() - Returns the error string of the last json_encode() or json_decode() call
  • json_decode() - Decodes a JSON string
  • json_encode() - Returns the JSON representation of a value


Judy Arrays

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Judy — The Judy class
    • Judy::byCount — Locate the Nth index present in the Judy array
    • Judy::__construct — Construct a new Judy object
    • Judy::count — Count the number of elements in the Judy array
    • Judy::__destruct — Destruct a Judy object
    • Judy::first — Search for the first index in the Judy array
    • Judy::firstEmpty — Search for the first absent index in the Judy array
    • Judy::free — Free the entire Judy array
    • Judy::getType — Return the type of the current Judy array
    • Judy::last — Search for the last index in the Judy array
    • Judy::lastEmpty — Search for the last absent index in the Judy array
    • Judy::memoryUsage — Return the memory used by the Judy array
    • Judy::next — Search for the next index in the Judy array
    • Judy::nextEmpty — Search for the next absent index in the Judy array
    • Judy::offsetExists — Whether a offset exists
    • Judy::offsetGet — Offset to retrieve
    • Judy::offsetSet — Offset to set
    • Judy::offsetUnset — Offset to unset
    • Judy::prev — Search for the previous index in the Judy array
    • Judy::prevEmpty — Search for the previous absent index in the Judy array
    • Judy::size — Return the size of the current Judy array
  • Judy Functions
    • judy_type — Return the type of a Judy array
    • judy_version — Return or print the current PHP Judy version


Introduction

PHP Judy is a PECL extension for the » Judy C library implementing dynamic sparse arrays.

A Judy array is a complex but very fast associative array data structure for storing and looking up values using integer or string keys. Unlike normal arrays, Judy arrays may be sparse; that is, they may have large ranges of unassigned indices.

A Judy array consumes memory only when populated yet can grow to take advantage of all available memory. Judy's key benefits are: scalability, performance, memory efficiency, and ease of use. Judy arrays are designed to grow without tuning into the peta-element range, scaling near O(log-base-256) -- 1 more RAM access at 256 X population.


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

This extension require the » Judy C library.


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/judy

Installation on Linux Systems

From sources

Download and install » libJudy, then :

     phpize
     ./configure --with-judy[=DIR]
     make
     make test
     make install

Ubuntu/Debian

libJudy can be installed with apt-get :

    apt-get install libjudydebian1 libjudy-dev
Then by installing the Judy extension from PECL or from the sources.

Installation on Windows Systems

Download » libJudy, then extract the sources and open the Visual Studio command prompt and navigate to the source directory. Then execute :

build
This creates "Judy.lib", copy this into the php-sdk library folder and name it "libJudy.lib" Then copy the include file "judy.h" into the php-sdk includes folder.

Next, the PHP Judy extension can be installed from PECL or from the sources by extracting the pecl/judy into your build folder where the build scripts will be able to pick it up, e.g.:

    C:\php\pecl\judy\
If your source of PHP is located in:
    C:\php\src\
The rest of the steps is pretty straight forward, like any other external extension:
    buildconf
    configure --with-judy=shared
    nmake

Installation on macOS

Download and install » libJudy. Then install the Judy extension from PECL or from the sources.


  • « Runtime Configuration
  • Judy »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

This extension has no resource types defined.


The Judy class

(PECL judy >= 0.1.1)

Introduction

The Judy class implements the ArrayAccess interface and the Iterator interface. This class, once instantiated, can be accessed like a PHP array.

A PHP Judy object (or Judy Array) can be one of the following type :

  • Judy::BITSET
  • Judy::INT_TO_INT
  • Judy::INT_TO_MIXED
  • Judy::STRING_TO_INT
  • Judy::STRING_TO_MIXED

Example #1 Judy array example

<?php
    $judy = new Judy(Judy::INT_TO_MIXED);
    $judy[1] = "one";
    $judy[2] = array('a', 'b', 'c');
    $judy[3] = new Judy(Judy::BITSET);
?>

Class synopsis

Judy implements ArrayAccess , Iterator {
/* Constants */
const integer BITSET = 1 ;
const integer INT_TO_INT = 2 ;
const integer INT_TO_MIXED = 3 ;
const integer STRING_TO_INT = 4 ;
const integer STRING_TO_MIXED = 5 ;
/* Methods */
public byCount ( int $nth_index ) : int
public __construct ( int $judy_type )
public count ([ int $index_start = 0 [, int $index_end = -1 ]] ) : int
public __destruct ( void ) : void
public first ([ mixed $index ] ) : mixed
public firstEmpty ([ mixed $index = 0 ] ) : int
public free ( void ) : int
public getType ( void ) : int
public last ([ string $index ] ) : void
public lastEmpty ([ int $index = -1 ] ) : int
public memoryUsage ( void ) : int
public next ( mixed $index ) : mixed
public nextEmpty ( int $index ) : int
public offsetExists ( mixed $offset ) : bool
public offsetGet ( mixed $offset ) : mixed
public offsetSet ( mixed $offset , mixed $value ) : bool
public offsetUnset ( mixed $offset ) : bool
public prev ( mixed $index ) : mixed
public prevEmpty ( mixed $index ) : int
public size ( void ) : void
}

Predefined Constants

Judy::BITSET

Define the Judy Array as a Bitset with keys as Integer and Values as a Boolean

Judy::INT_TO_INT

Define the Judy Array with key/values as Integer, and Integer only.

Judy::INT_TO_MIXED

Define the Judy Array with keys as Integer and Values of any type.

Judy::STRING_TO_INT

Define the Judy Array with keys as a String and Values as Integer, and Integer only.

Judy::STRING_TO_MIXED

Define the Judy Array with keys as a String and Values of any type.

Table of Contents

  • Judy::byCount — Locate the Nth index present in the Judy array
  • Judy::__construct — Construct a new Judy object
  • Judy::count — Count the number of elements in the Judy array
  • Judy::__destruct — Destruct a Judy object
  • Judy::first — Search for the first index in the Judy array
  • Judy::firstEmpty — Search for the first absent index in the Judy array
  • Judy::free — Free the entire Judy array
  • Judy::getType — Return the type of the current Judy array
  • Judy::last — Search for the last index in the Judy array
  • Judy::lastEmpty — Search for the last absent index in the Judy array
  • Judy::memoryUsage — Return the memory used by the Judy array
  • Judy::next — Search for the next index in the Judy array
  • Judy::nextEmpty — Search for the next absent index in the Judy array
  • Judy::offsetExists — Whether a offset exists
  • Judy::offsetGet — Offset to retrieve
  • Judy::offsetSet — Offset to set
  • Judy::offsetUnset — Offset to unset
  • Judy::prev — Search for the previous index in the Judy array
  • Judy::prevEmpty — Search for the previous absent index in the Judy array
  • Judy::size — Return the size of the current Judy array


Locate the Nth index present in the Judy array

  • « Judy
  • Judy::__construct »
  • PHP Manual
  • Judy
  • Locate the Nth index present in the Judy array

Judy::byCount

(PECL judy >= 0.1.1)

Judy::byCount — Locate the Nth index present in the Judy array

Description

public Judy::byCount ( int $nth_index ) : int

Locate the Nth index present in the Judy array.

Parameters

nth_index

Nth index to return. If nth_index equal 1, then it will return the first index in the array.

Return Values

Return the index at the given Nth position.


Construct a new Judy object

  • « Judy::byCount
  • Judy::count »
  • PHP Manual
  • Judy
  • Construct a new Judy object

Judy::__construct

(PECL judy >= 0.1.1)

Judy::__construct — Construct a new Judy object

Description

public Judy::__construct ( int $judy_type )

Construct a new Judy object. A Judy object can be accessed like a PHP Array.

Parameters

judy_type

The Judy type to be used.

Return Values

Return the new Judy instance.


Count the number of elements in the Judy array

  • « Judy::__construct
  • Judy::__destruct »
  • PHP Manual
  • Judy
  • Count the number of elements in the Judy array

Judy::count

(PECL judy >= 0.1.1)

Judy::count — Count the number of elements in the Judy array

Description

public Judy::count ([ int $index_start = 0 [, int $index_end = -1 ]] ) : int

Count the number of elements in the Judy array.

Parameters

index_start

Start counting from the given index. Default is first index.

index_end

Stop counting when reaching this index. Default is last index.

Return Values

Return the number of elements.


Destruct a Judy object

  • « Judy::count
  • Judy::first »
  • PHP Manual
  • Judy
  • Destruct a Judy object

Judy::__destruct

(PECL judy >= 0.1.1)

Judy::__destruct — Destruct a Judy object

Description

public Judy::__destruct ( void ) : void

Destruct a Judy object.

Parameters

This function has no parameters.

Return Values


Search for the first index in the Judy array

  • « Judy::__destruct
  • Judy::firstEmpty »
  • PHP Manual
  • Judy
  • Search for the first index in the Judy array

Judy::first

(PECL judy >= 0.1.1)

Judy::first — Search for the first index in the Judy array

Description

public Judy::first ([ mixed $index ] ) : mixed

Search (inclusive) for the first index present that is equal to or greater than the passed Index.

Parameters

index

The index can be an integer or a string corresponding to the index where to start the search.

Return Values

Return the corresponding index in the array.


Search for the first absent index in the Judy array

  • « Judy::first
  • Judy::free »
  • PHP Manual
  • Judy
  • Search for the first absent index in the Judy array

Judy::firstEmpty

(PECL judy >= 0.1.1)

Judy::firstEmpty — Search for the first absent index in the Judy array

Description

public Judy::firstEmpty ([ mixed $index = 0 ] ) : int

Search (inclusive) for the first absent index that is equal to or greater than the passed Index.

Parameters

index

The index can be an integer or a string corresponding to the index where to start the search.

Return Values

Return the corresponding index in the array.


Free the entire Judy array

  • « Judy::firstEmpty
  • Judy::getType »
  • PHP Manual
  • Judy
  • Free the entire Judy array

Judy::free

(PECL judy >= 0.1.1)

Judy::free — Free the entire Judy array

Description

public Judy::free ( void ) : int

Free the entire Judy array.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Return the type of the current Judy array

  • « Judy::free
  • Judy::last »
  • PHP Manual
  • Judy
  • Return the type of the current Judy array

Judy::getType

(PECL judy >= 0.1.1)

Judy::getType — Return the type of the current Judy array

Description

public Judy::getType ( void ) : int

Return an integer corresponding to the Judy type of the current object.

Parameters

This function has no parameters.

Return Values

Return an integer corresponding to a Judy type.


Search for the last index in the Judy array

  • « Judy::getType
  • Judy::lastEmpty »
  • PHP Manual
  • Judy
  • Search for the last index in the Judy array

Judy::last

(PECL judy >= 0.1.1)

Judy::last — Search for the last index in the Judy array

Description

public Judy::last ([ string $index ] ) : void

Search (inclusive) for the last index present that is equal to or less than the passed Index.

Parameters

index

The index can be an integer or a string corresponding to the index where to start the search.

Return Values

Return the corresponding index in the array.


Search for the last absent index in the Judy array

  • « Judy::last
  • Judy::memoryUsage »
  • PHP Manual
  • Judy
  • Search for the last absent index in the Judy array

Judy::lastEmpty

(PECL judy >= 0.1.1)

Judy::lastEmpty — Search for the last absent index in the Judy array

Description

public Judy::lastEmpty ([ int $index = -1 ] ) : int

Search (inclusive) for the last absent index that is equal to or less than the passed Index.

Parameters

index

The index can be an integer or a string corresponding to the index where to start the search.

Return Values

Return the corresponding index in the array.


Return the memory used by the Judy array

  • « Judy::lastEmpty
  • Judy::next »
  • PHP Manual
  • Judy
  • Return the memory used by the Judy array

Judy::memoryUsage

(PECL judy >= 0.1.1)

Judy::memoryUsage — Return the memory used by the Judy array

Description

public Judy::memoryUsage ( void ) : int

Return the memory used by the Judy array.

Parameters

This function has no parameters.

Return Values

Return the memory used in bytes.


Search for the next index in the Judy array

  • « Judy::memoryUsage
  • Judy::nextEmpty »
  • PHP Manual
  • Judy
  • Search for the next index in the Judy array

Judy::next

(PECL judy >= 0.1.1)

Judy::next — Search for the next index in the Judy array

Description

public Judy::next ( mixed $index ) : mixed

Search (exclusive) for the next index present that is greater than the passed Index.

Parameters

index

The index can be an integer or a string corresponding to the index where to start the search.

Return Values

Return the corresponding index in the array.


Search for the next absent index in the Judy array

  • « Judy::next
  • Judy::offsetExists »
  • PHP Manual
  • Judy
  • Search for the next absent index in the Judy array

Judy::nextEmpty

(PECL judy >= 0.1.1)

Judy::nextEmpty — Search for the next absent index in the Judy array

Description

public Judy::nextEmpty ( int $index ) : int

Search (exclusive) for the next absent index that is greater than the passed Index.

Parameters

index

The index can be an integer or a string corresponding to the index where to start the search.

Return Values

Return the corresponding index in the array.


Whether a offset exists

  • « Judy::nextEmpty
  • Judy::offsetGet »
  • PHP Manual
  • Judy
  • Whether a offset exists

Judy::offsetExists

(PECL judy >= 0.1.1)

Judy::offsetExists — Whether a offset exists

Description

public Judy::offsetExists ( mixed $offset ) : bool

Whether or not an offset exists.

Parameters

offset

An offset to check for.

Return Values

Returns TRUE on success or FALSE on failure.


Offset to retrieve

  • « Judy::offsetExists
  • Judy::offsetSet »
  • PHP Manual
  • Judy
  • Offset to retrieve

Judy::offsetGet

(PECL judy >= 0.1.1)

Judy::offsetGet — Offset to retrieve

Description

public Judy::offsetGet ( mixed $offset ) : mixed

Returns the value at specified offset.

Parameters

offset

The offset to retrieve.

Return Values

Can return all value types.


Offset to set

  • « Judy::offsetGet
  • Judy::offsetUnset »
  • PHP Manual
  • Judy
  • Offset to set

Judy::offsetSet

(PECL judy >= 0.1.1)

Judy::offsetSet — Offset to set

Description

public Judy::offsetSet ( mixed $offset , mixed $value ) : bool

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.


Offset to unset

  • « Judy::offsetSet
  • Judy::prev »
  • PHP Manual
  • Judy
  • Offset to unset

Judy::offsetUnset

(PECL judy >= 0.1.1)

Judy::offsetUnset — Offset to unset

Description

public Judy::offsetUnset ( mixed $offset ) : bool

Unsets an offset.

Parameters

offset

The offset to unset.

Return Values

No value is returned.


Search for the previous index in the Judy array

  • « Judy::offsetUnset
  • Judy::prevEmpty »
  • PHP Manual
  • Judy
  • Search for the previous index in the Judy array

Judy::prev

(PECL judy >= 0.1.1)

Judy::prev — Search for the previous index in the Judy array

Description

public Judy::prev ( mixed $index ) : mixed

Search (exclusive) for the previous index present that is less than the passed Index.

Parameters

index

The index can be an integer or a string corresponding to the index where to start the search.

Return Values

Return the corresponding index in the array.


Search for the previous absent index in the Judy array

  • « Judy::prev
  • Judy::size »
  • PHP Manual
  • Judy
  • Search for the previous absent index in the Judy array

Judy::prevEmpty

(PECL judy >= 0.1.1)

Judy::prevEmpty — Search for the previous absent index in the Judy array

Description

public Judy::prevEmpty ( mixed $index ) : int

Search (exclusive) for the previous index absent that is less than the passed Index.

Parameters

index

The index can be an integer or a string corresponding to the index where to start the search.

Return Values

Return the corresponding index in the array.


Return the size of the current Judy array

  • « Judy::prevEmpty
  • Judy Functions »
  • PHP Manual
  • Judy
  • Return the size of the current Judy array

Judy::size

(PECL judy >= 0.1.1)

Judy::size — Return the size of the current Judy array

Description

public Judy::size ( void ) : void

This method is an alias of: Judy::count().

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Return an integer.


Judy Functions

Table of Contents

  • judy_type — Return the type of a Judy array
  • judy_version — Return or print the current PHP Judy version


Return the type of a Judy array

  • « Judy Functions
  • judy_version »
  • PHP Manual
  • Judy Functions
  • Return the type of a Judy array

judy_type

(PECL judy >= 0.1.1)

judy_type — Return the type of a Judy array

Description

judy_type ( Judy $array ) : int

judy_type() return an integer corresponding to the Judy type of the specified Judy array.

Parameters

array

The Judy Array to test.

Return Values

Return an integer corresponding to a Judy type.


Return or print the current PHP Judy version

  • « judy_type
  • Lua »
  • PHP Manual
  • Judy Functions
  • Return or print the current PHP Judy version

judy_version

(PECL judy >= 0.1.1)

judy_version — Return or print the current PHP Judy version

Description

judy_version ( void ) : string

Return a string of the PHP Judy version. If the return value is not used, the string will be printed.

Parameters

This function has no parameters.

Return Values

Return a string of the PHP Judy version.


Lua

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Lua — The Lua class
    • Lua::assign — Assign a PHP variable to Lua
    • Lua::call — Call Lua functions
    • Lua::__construct — Lua constructor
    • Lua::eval — Evaluate a string as Lua code
    • Lua::getVersion — The getversion purpose
    • Lua::include — Parse a Lua script file
    • Lua::registerCallback — Register a PHP function to Lua
  • LuaClosure — The LuaClosure class
    • LuaClosure::__invoke — Invoke luaclosure


Introduction

"Lua is a powerful, fast, light-weight, embeddable scripting language." This extension embeds the lua interpreter and offers an OO-API to lua variables and functions.


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

To use this extension, you will need Lua installed, available on the » Lua homepage


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/lua.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.


  • « Runtime Configuration
  • Lua »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

This extension has no resource types defined.


The Lua class

(PECL lua >=0.9.0)

Introduction

Class synopsis

Lua {
/* Constants */
const string LUA_VERSION = Lua 5.1.4 ;
/* Methods */
public assign ( string $name , string $value ) : mixed
public call ( callable $lua_func [, array $args [, int $use_self = 0 ]] ) : mixed
public __call ( callable $lua_func [, array $args [, int $use_self = 0 ]] ) : mixed
public __construct ( string $lua_script_file = NULL )
public eval ( string $statements ) : mixed
public getVersion ( void ) : string
public include ( string $file ) : mixed
public registerCallback ( string $name , callable $function ) : mixed
}

Predefined Constants

Lua::LUA_VERSION

Table of Contents

  • Lua::assign — Assign a PHP variable to Lua
  • Lua::call — Call Lua functions
  • Lua::__construct — Lua constructor
  • Lua::eval — Evaluate a string as Lua code
  • Lua::getVersion — The getversion purpose
  • Lua::include — Parse a Lua script file
  • Lua::registerCallback — Register a PHP function to Lua


Assign a PHP variable to Lua

  • « Lua
  • Lua::call »
  • PHP Manual
  • Lua
  • Assign a PHP variable to Lua

Lua::assign

(PECL lua >=0.9.0)

Lua::assign — Assign a PHP variable to Lua

Description

public Lua::assign ( string $name , string $value ) : mixed

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

value

Return Values

Returns $this or NULL on failure.

Examples

Example #1 Lua::assign()example

<?php
$lua = new Lua();
$lua->assign("php_var", array(1=>1, 2, 3)); //lua table index begin with 1
$lua->eval(<<<CODE
    print(php_var);
CODE
);
?>

The above example will output:

Array
 (
     [1] => 1
     [2] => 2
     [3] => 3
 )


Call Lua functions

  • « Lua::assign
  • Lua::__construct »
  • PHP Manual
  • Lua
  • Call Lua functions

Lua::call

Lua::__call

(PECL lua >=0.9.0)

Lua::call -- Lua::__call — Call Lua functions

Description

public Lua::call ( callable $lua_func [, array $args [, int $use_self = 0 ]] ) : mixed
public Lua::__call ( callable $lua_func [, array $args [, int $use_self = 0 ]] ) : mixed

Warning

This function is currently not documented; only its argument list is available.

Parameters

lua_func

Function name in lua

args

Arguments passed to the Lua function

use_self

Whether to use self

Return Values

Returns result of the called function, NULL for wrong arguments or FALSE on other failure.

Examples

Example #1 Lua::call()example

<?php
$lua = new Lua();
$lua->eval(<<<CODE
    function dummy(foo, bar)
        print(foo, ",", bar)
    end
CODE
);
$lua->call("dummy", array("Lua", "geiliable\n"));
$lua->dummy("Lua", "geiliable"); // __call()
var_dump($lua->call(array("table", "concat"), array(array(1=>1, 2=>2, 3=>3), "-")));
?>

The above example will output:

Lua,geiliable
Lua,geiliable
string(5) "1-2-3"

See Also

  • __call()


Lua constructor

  • « Lua::call
  • Lua::eval »
  • PHP Manual
  • Lua
  • Lua constructor

Lua::__construct

(PECL lua >=0.9.0)

Lua::__construct — Lua constructor

Description

public Lua::__construct ( string $lua_script_file = NULL )

Warning

This function is currently not documented; only its argument list is available.

Parameters

lua_script_file

Return Values


Evaluate a string as Lua code

  • « Lua::__construct
  • Lua::getVersion »
  • PHP Manual
  • Lua
  • Evaluate a string as Lua code

Lua::eval

(PECL lua >=0.9.0)

Lua::eval — Evaluate a string as Lua code

Description

public Lua::eval ( string $statements ) : mixed

Warning

This function is currently not documented; only its argument list is available.

Parameters

statements

Return Values

Returns result of evaled code, NULL for wrong arguments or FALSE on other failure.

Examples

Example #1 Lua::eval()example

<?php
$lua = new Lua();
$lua->eval(<<<CODE
    print(2);
CODE
);
?>

The above example will output:

2


The getversion purpose

  • « Lua::eval
  • Lua::include »
  • PHP Manual
  • Lua
  • The getversion purpose

Lua::getVersion

(PECL lua >=0.9.0)

Lua::getVersion — The getversion purpose

Description

public Lua::getVersion ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns Lua::LUA_VERSION.


Parse a Lua script file

  • « Lua::getVersion
  • Lua::registerCallback »
  • PHP Manual
  • Lua
  • Parse a Lua script file

Lua::include

(PECL lua >=0.9.0)

Lua::include — Parse a Lua script file

Description

public Lua::include ( string $file ) : mixed

Warning

This function is currently not documented; only its argument list is available.

Parameters

file

Return Values

Returns result of included code, NULL for wrong arguments or FALSE on other failure.


Register a PHP function to Lua

  • « Lua::include
  • LuaClosure »
  • PHP Manual
  • Lua
  • Register a PHP function to Lua

Lua::registerCallback

(No version information available, might only be in Git)

Lua::registerCallback — Register a PHP function to Lua

Description

public Lua::registerCallback ( string $name , callable $function ) : mixed

Register a PHP function to Lua as a function named "$name"

Parameters

name

function

A valid PHP function callback

Return Values

Returns $this, NULL for wrong arguments or FALSE on other failure.

Examples

Example #1 Lua::registerCallback()example

<?php
$lua = new Lua();
$lua->registerCallback("echo", "var_dump");
$lua->eval(<<<CODE
    echo({1, 2, 3});
CODE
);
?>

The above example will output:

array(3) {
  [1]=>
  float(1)
  [2]=>
  float(2)
  [3]=>
  float(3)
}


The LuaClosure class

(PECL lua >=0.9.0)

Introduction

LuaClosure is a wrapper class for LUA_TFUNCTION which could be return from calling to Lua function.

Class synopsis

LuaClosure {
/* Methods */
public __invoke ([ mixed $... ] ) : void
}

Table of Contents

  • LuaClosure::__invoke — Invoke luaclosure


Invoke luaclosure

  • « LuaClosure
  • LuaSandbox »
  • PHP Manual
  • LuaClosure
  • Invoke luaclosure

LuaClosure::__invoke

(PECL lua >=0.9.0)

LuaClosure::__invoke — Invoke luaclosure

Description

public LuaClosure::__invoke ([ mixed $... ] ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

...

Return Values

Examples

Example #1 LuaClosure::__invoke()example

<?php
$lua = new Lua();
$closure = $lua->eval(<<<CODE
    return (function ()
        print("hello world")
    end)
CODE
);

$lua->call($closure);
/* after PHP 5.3 */
$closure();
?>

The above example will output:

hello worldhello world


LuaSandbox

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Differences from Standard Lua
  • Examples
    • Basic usage for LuaSandbox
  • LuaSandbox — The LuaSandbox class
    • LuaSandbox::callFunction — Call a function in a Lua global variable
    • LuaSandbox::disableProfiler — Disable the profiler
    • LuaSandbox::enableProfiler — Enable the profiler.
    • LuaSandbox::getCPUUsage — Fetch the current CPU time usage of the Lua environment
    • LuaSandbox::getMemoryUsage — Fetch the current memory usage of the Lua environment
    • LuaSandbox::getPeakMemoryUsage — Fetch the peak memory usage of the Lua environment
    • LuaSandbox::getProfilerFunctionReport — Fetch profiler data
    • LuaSandbox::getVersionInfo — Return the versions of LuaSandbox and Lua
    • LuaSandbox::loadBinary — Load a precompiled binary chunk into the Lua environment
    • LuaSandbox::loadString — Load Lua code into the Lua environment
    • LuaSandbox::pauseUsageTimer — Pause the CPU usage timer
    • LuaSandbox::registerLibrary — Register a set of PHP functions as a Lua library
    • LuaSandbox::setCPULimit — Set the CPU time limit for the Lua environment
    • LuaSandbox::setMemoryLimit — Set the memory limit for the Lua environment
    • LuaSandbox::unpauseUsageTimer — Unpause the timer paused by LuaSandbox::pauseUsageTimer
    • LuaSandbox::wrapPhpFunction — Wrap a PHP callable in a LuaSandboxFunction
  • LuaSandboxFunction — The LuaSandboxFunction class
    • LuaSandboxFunction::call — Call a Lua function
    • LuaSandboxFunction::__construct — Unused
    • LuaSandboxFunction::dump — Dump the function as a binary blob
  • LuaSandboxError — The LuaSandboxError class
  • LuaSandboxErrorError — The LuaSandboxErrorError class
  • LuaSandboxFatalError — The LuaSandboxFatalError class
  • LuaSandboxMemoryError — The LuaSandboxMemoryError class
  • LuaSandboxRuntimeError — The LuaSandboxRuntimeError class
  • LuaSandboxSyntaxError — The LuaSandboxSyntaxError class
  • LuaSandboxTimeoutError — The LuaSandboxTimeoutError class


Introduction

LuaSandbox is an extension for PHP 5, PHP 7, and HHVM to allow safely running untrusted Lua 5.1 code from within PHP.

Differences compared to the Lua extension:

  • LuaSandbox has support for time and memory limits.

  • LuaSandbox provides a default-safe environment for running untrusted code. Stock Lua functions were reviewed for security, and several were patched accordingly.

  • LuaSandbox has a PHP interface which is more complex, precise and powerful, but it is less convenient for developers.

  • LuaSandbox supports only Lua 5.1. It is difficult to change this, because LuaSandbox uses heavily modified Lua standard libraries, and due to the lack of backwards compatibility between major Lua versions. LuaSandbox aims to maximise backwards compatibility with user-supplied scripts.


Requirements

To use this extension, Lua 5.1 will need to be installed, available on the » Lua homepage.

To make full use of the timer features, LuaSandbox should be installed on Linux.

If FreeBSD or Mac OS X is used, only real (wall-clock) time is supported, the functions purporting to return CPU time will actually return wall clock time.

If Windows is used, no timer functions will be supported. The time limits will be inoperable.


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/luasandbox.

If the operating system is Debian 9 or later, or Ubuntu 18.04 or later, then LuaSandbox should typically be installed from the package php-luasandbox:

sudo apt-get install php-luasandbox

Debian 9 users may need to add

deb http://ftp.debian.org/debian stretch-backports main
to their » sources.list.


  • « Runtime Configuration
  • Differences from Standard Lua »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

This extension has no resource types defined.


Differences from Standard Lua

LuaSandbox provides a sandboxed environment which differs in some ways from standard Lua 5.1.

Features that are not available

  • dofile(), loadfile(), and the io package, as they allow direct filesystem access. If needed, filesystem access should be done via PHP callbacks.

  • The package package, including require() and module(), as it depends heavily on direct filesystem access. A pure-Lua rewrite such as that used in the MediaWiki Scribunto extension may be used instead.

  • load() and loadstring(), to allow for static analysis of Lua code.

  • print(), since it outputs to standard output. If needed, output should be done via PHP callbacks.

  • Most of the os package, as it allows manipulation of the process and executing of other processes.

    • os.clock(), os.date(), os.difftime(), and os.time() remain available.

  • Most of the debug package, as it allows manipulation of Lua state and metadata in ways that can break sandboxing.

    • debug.traceback() remains available.

  • string.dump(), as it may expose internal data.

  • collectgarbage(), gcinfo(), and the coroutine package have not been reviewed for security.

Features that have been modified

  • pcall() and xpcall() cannot catch certain errors, particularly timeout errors.

  • tostring() does not include pointer addresses.

  • string.match() has been patched to limit the recursion depth and to periodically check for a timeout.

  • math.random() and math.randomseed() are replaced with versions that don't share state with PHP's rand().

  • The Lua 5.2 __pairs and __ipairs metamethods are supported by pairs() and ipairs().


  • « Differences from Standard Lua
  • Basic usage for LuaSandbox »
  • PHP Manual
  • LuaSandbox
  • Examples

Examples

Table of Contents

  • Basic usage for LuaSandbox


Basic usage for LuaSandbox

Once you've compiled PHP with LuaSandbox support, you can begin using LuaSandbox to safely run user-provided Lua code.

Example #1 Execute some Lua code

<?php

$sandbox = new LuaSandbox;
$sandbox->setMemoryLimit( 50 * 1024 * 1024 );
$sandbox->setCPULimit( 10 );

// Register some functions in the Lua environment

function frobnosticate( $v ) {
    return [ $v + 42 ];
}

$sandbox->registerLibrary( 'php', [
    'frobnosticate' => 'frobnosticate',
    'output' => function ( $string ) {
        echo "$string\n";
    },
    'error' => function () {
        throw new LuaSandboxRuntimeError( "Something is wrong" );
    }
] );

// Execute some Lua code, including callbacks into PHP and into Lua

$luaCode = <<<EOF
php.output( "Hello, world" );

return "Hi", function ( v )
    return php.frobnosticate( v + 200 )
end
EOF;

list( $hi, $frob ) = $sandbox->loadString( $luaCode )->call();
assert( $frob->call( 4000 ) === [ 4242 ] );

// PHP-thrown LuaSandboxRuntimeError exceptions can be caught inside Lua

list( $ok, $message ) = $sandbox->loadString( 'return pcall( php.error )' )->call();
assert( !$ok );
assert( $message === 'Something is wrong' );

?>


The LuaSandbox class

(PECL luasandbox >= 1.0.0)

Introduction

The LuaSandbox class creates a Lua environment and allows for execution of Lua code.

Class synopsis

LuaSandbox {
/* Constants */
const integer SAMPLES = 0 ;
const integer SECONDS = 1 ;
const integer PERCENT = 2 ;
/* Methods */
public callFunction ( string $name [, mixed $... ] ) : array|bool
public disableProfiler ( void ) : void
public enableProfiler ([ float $period = 0.02 ] ) : bool
public getCPUUsage ( void ) : float
public getMemoryUsage ( void ) : int
public getPeakMemoryUsage ( void ) : int
public getProfilerFunctionReport ([ int $units = LuaSandbox::SECONDS ] ) : array
public static getVersionInfo ( void ) : array
public loadBinary ( string $code [, string $chunkName = '' ] ) : LuaSandboxFunction
public loadString ( string $code [, string $chunkName = '' ] ) : LuaSandboxFunction
public pauseUsageTimer ( void ) : bool
public registerLibrary ( string $libname , array $functions ) : void
public setCPULimit ( float|bool $limit ) : void
public setMemoryLimit ( int $limit ) : void
public unpauseUsageTimer ( void ) : void
public wrapPhpFunction ( callable $function ) : LuaSandboxFunction
}

Predefined Constants

LuaSandbox::SAMPLES

Used with LuaSandbox::getProfilerFunctionReport() to return timings in samples.

LuaSandbox::SECONDS

Used with LuaSandbox::getProfilerFunctionReport() to return timings in seconds.

LuaSandbox::PERCENT

Used with LuaSandbox::getProfilerFunctionReport() to return timings in percentages of the total.

Table of Contents

  • LuaSandbox::callFunction — Call a function in a Lua global variable
  • LuaSandbox::disableProfiler — Disable the profiler
  • LuaSandbox::enableProfiler — Enable the profiler.
  • LuaSandbox::getCPUUsage — Fetch the current CPU time usage of the Lua environment
  • LuaSandbox::getMemoryUsage — Fetch the current memory usage of the Lua environment
  • LuaSandbox::getPeakMemoryUsage — Fetch the peak memory usage of the Lua environment
  • LuaSandbox::getProfilerFunctionReport — Fetch profiler data
  • LuaSandbox::getVersionInfo — Return the versions of LuaSandbox and Lua
  • LuaSandbox::loadBinary — Load a precompiled binary chunk into the Lua environment
  • LuaSandbox::loadString — Load Lua code into the Lua environment
  • LuaSandbox::pauseUsageTimer — Pause the CPU usage timer
  • LuaSandbox::registerLibrary — Register a set of PHP functions as a Lua library
  • LuaSandbox::setCPULimit — Set the CPU time limit for the Lua environment
  • LuaSandbox::setMemoryLimit — Set the memory limit for the Lua environment
  • LuaSandbox::unpauseUsageTimer — Unpause the timer paused by LuaSandbox::pauseUsageTimer
  • LuaSandbox::wrapPhpFunction — Wrap a PHP callable in a LuaSandboxFunction


Call a function in a Lua global variable

  • « LuaSandbox
  • LuaSandbox::disableProfiler »
  • PHP Manual
  • LuaSandbox
  • Call a function in a Lua global variable

LuaSandbox::callFunction

(PECL luasandbox >= 1.0.0)

LuaSandbox::callFunction — Call a function in a Lua global variable

Description

public LuaSandbox::callFunction ( string $name [, mixed $... ] ) : array|bool

Calls a function in a Lua global variable.

If the name contains "." characters, the function is located via recursive table accesses, as if the name were a Lua expression.

If the variable does not exist, or is not a function, false will be returned and a warning issued.

For more information about calling Lua functions and the return values, see LuaSandboxFunction::call().

Parameters

name

Lua variable name.

...

Arguments to the function.

Return Values

Returns an array of values returned by the Lua function, which may be empty, or false in case of failure.

Examples

Example #1 Calling a Lua function

<?php

// create a new LuaSandbox
$sandbox = new LuaSandbox();

// Call Lua's string.match
$captures = $sandbox->callFunction( 'string.match', $string, $pattern );

?>


Disable the profiler

  • « LuaSandbox::callFunction
  • LuaSandbox::enableProfiler »
  • PHP Manual
  • LuaSandbox
  • Disable the profiler

LuaSandbox::disableProfiler

(PECL luasandbox >= 1.1.0)

LuaSandbox::disableProfiler — Disable the profiler

Description

public LuaSandbox::disableProfiler ( void ) : void

Disables the profiler.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • LuaSandbox::enableProfiler() - Enable the profiler.
  • LuaSandbox::getProfilerFunctionReport() - Fetch profiler data


Enable the profiler.

  • « LuaSandbox::disableProfiler
  • LuaSandbox::getCPUUsage »
  • PHP Manual
  • LuaSandbox
  • Enable the profiler.

LuaSandbox::enableProfiler

(PECL luasandbox >= 1.1.0)

LuaSandbox::enableProfiler — Enable the profiler.

Description

public LuaSandbox::enableProfiler ([ float $period = 0.02 ] ) : bool

Enables the profiler. Profiling will begin when Lua code is entered.

The profiler periodically samples the Lua environment to record the running function. Testing indicates that at least on Linux, setting a period less than 1ms will lead to a high overrun count but no performance problems.

Parameters

period

Sampling period in seconds.

Return Values

Returns a boolean indicating whether the profiler is enabled.

See Also

  • LuaSandbox::disableProfiler() - Disable the profiler
  • LuaSandbox::getProfilerFunctionReport() - Fetch profiler data


Fetch the current CPU time usage of the Lua environment

  • « LuaSandbox::enableProfiler
  • LuaSandbox::getMemoryUsage »
  • PHP Manual
  • LuaSandbox
  • Fetch the current CPU time usage of the Lua environment

LuaSandbox::getCPUUsage

(PECL luasandbox >= 1.0.0)

LuaSandbox::getCPUUsage — Fetch the current CPU time usage of the Lua environment

Description

public LuaSandbox::getCPUUsage ( void ) : float

Fetches the current CPU time usage of the Lua environment.

This includes time spent in PHP callbacks.

Parameters

This function has no parameters.

Return Values

Returns the current CPU time usage in seconds.

Note:

On Windows, this function always returns zero. On operating systems that do not support CLOCK_THREAD_CPUTIME_ID, such as FreeBSD and Mac OS X, this function will return the elapsed wall-clock time, not CPU time.

See Also

  • LuaSandbox::getMemoryUsage() - Fetch the current memory usage of the Lua environment
  • LuaSandbox::getPeakMemoryUsage() - Fetch the peak memory usage of the Lua environment
  • LuaSandbox::setCPULimit() - Set the CPU time limit for the Lua environment


Fetch the current memory usage of the Lua environment

  • « LuaSandbox::getCPUUsage
  • LuaSandbox::getPeakMemoryUsage »
  • PHP Manual
  • LuaSandbox
  • Fetch the current memory usage of the Lua environment

LuaSandbox::getMemoryUsage

(PECL luasandbox >= 1.0.0)

LuaSandbox::getMemoryUsage — Fetch the current memory usage of the Lua environment

Description

public LuaSandbox::getMemoryUsage ( void ) : int

Fetches the current memory usage of the Lua environment.

Parameters

This function has no parameters.

Return Values

Returns the current memory usage in bytes.

See Also

  • LuaSandbox::getPeakMemoryUsage() - Fetch the peak memory usage of the Lua environment
  • LuaSandbox::getCPUUsage() - Fetch the current CPU time usage of the Lua environment
  • LuaSandbox::setMemoryLimit() - Set the memory limit for the Lua environment


Fetch the peak memory usage of the Lua environment

  • « LuaSandbox::getMemoryUsage
  • LuaSandbox::getProfilerFunctionReport »
  • PHP Manual
  • LuaSandbox
  • Fetch the peak memory usage of the Lua environment

LuaSandbox::getPeakMemoryUsage

(PECL luasandbox >= 1.0.0)

LuaSandbox::getPeakMemoryUsage — Fetch the peak memory usage of the Lua environment

Description

public LuaSandbox::getPeakMemoryUsage ( void ) : int

Fetches the peak memory usage of the Lua environment.

Parameters

This function has no parameters.

Return Values

Returns the peak memory usage in bytes.

See Also

  • LuaSandbox::getMemoryUsage() - Fetch the current memory usage of the Lua environment
  • LuaSandbox::getCPUUsage() - Fetch the current CPU time usage of the Lua environment
  • LuaSandbox::setMemoryLimit() - Set the memory limit for the Lua environment


Fetch profiler data

  • « LuaSandbox::getPeakMemoryUsage
  • LuaSandbox::getVersionInfo »
  • PHP Manual
  • LuaSandbox
  • Fetch profiler data

LuaSandbox::getProfilerFunctionReport

(PECL luasandbox >= 1.1.0)

LuaSandbox::getProfilerFunctionReport — Fetch profiler data

Description

public LuaSandbox::getProfilerFunctionReport ([ int $units = LuaSandbox::SECONDS ] ) : array

For a profiling instance previously started by LuaSandbox::enableProfiler(), get a report of the cost of each function.

The measurement unit used for the cost is determined by the $units parameter:

LuaSandbox::SAMPLES

Measure in number of samples.

LuaSandbox::SECONDS

Measure in seconds of CPU time.

LuaSandbox::PERCENT

Measure percentage of CPU time.

Parameters

units

Measurement unit constant.

Return Values

Returns profiler measurements, sorted in descending order, as an associative array. Keys are the Lua function names (with source file and line defined in angle brackets), values are the measurements as integer or float.

Note:

On Windows, this function always returns an empty array. On operating systems that do not support CLOCK_THREAD_CPUTIME_ID, such as FreeBSD and Mac OS X, this function will report the elapsed wall-clock time, not CPU time.

Examples

Example #1 Profiling Lua code

<?php

// create a new LuaSandbox
$sandbox = new LuaSandbox();

// Start the profiler
$sandbox->enableProfiler( 0.01 );

// ... Execute some Lua code here ...

// Fetch the profiler data
$data = $sandbox->getProfilerFunctionReport();

?>


Return the versions of LuaSandbox and Lua

  • « LuaSandbox::getProfilerFunctionReport
  • LuaSandbox::loadBinary »
  • PHP Manual
  • LuaSandbox
  • Return the versions of LuaSandbox and Lua

LuaSandbox::getVersionInfo

(PECL luasandbox >= 1.6.0)

LuaSandbox::getVersionInfo — Return the versions of LuaSandbox and Lua

Description

public static LuaSandbox::getVersionInfo ( void ) : array

Returns the versions of LuaSandbox and Lua.

Parameters

This function has no parameters.

Return Values

Returns an array with two keys:

element | type | description
LuaSandbox | string | The version of the LuaSandbox extension.
Lua | string | The library name and version as defined by the LUA_RELEASE macro, for example, "Lua 5.1.5".


Load a precompiled binary chunk into the Lua environment

  • « LuaSandbox::getVersionInfo
  • LuaSandbox::loadString »
  • PHP Manual
  • LuaSandbox
  • Load a precompiled binary chunk into the Lua environment

LuaSandbox::loadBinary

(PECL luasandbox >= 1.0.0)

LuaSandbox::loadBinary — Load a precompiled binary chunk into the Lua environment

Description

public LuaSandbox::loadBinary ( string $code [, string $chunkName = '' ] ) : LuaSandboxFunction

Loads data generated by LuaSandboxFunction::dump().

Parameters

code

Data from LuaSandboxFunction::dump().

chunkName

Name for the loaded function.

Return Values

Returns a LuaSandboxFunction.

See Also

  • LuaSandbox::loadString() - Load Lua code into the Lua environment


Load Lua code into the Lua environment

  • « LuaSandbox::loadBinary
  • LuaSandbox::pauseUsageTimer »
  • PHP Manual
  • LuaSandbox
  • Load Lua code into the Lua environment

LuaSandbox::loadString

(PECL luasandbox >= 1.0.0)

LuaSandbox::loadString — Load Lua code into the Lua environment

Description

public LuaSandbox::loadString ( string $code [, string $chunkName = '' ] ) : LuaSandboxFunction

Loads Lua code into the Lua environment.

This is the equivalent of standard Lua's loadstring() function.

Parameters

code

Lua code.

chunkName

Name for the loaded chunk, for use in error traces.

Return Values

Returns a LuaSandboxFunction which, when executed, will execute the passed $code.

Examples

Example #1 Loading code into Lua

<?php

// create a new LuaSandbox
$sandbox = new LuaSandbox();

// Load the code
$function = $sandbox->loadString(
<<<CODE
    return "Hello, world"
CODE
);

// Execute the loaded code
var_dump( $function->call() );

?>

The above example will output:

array(1) {
  [0]=>
  string(12) "Hello, world"
}

See Also

  • LuaSandbox::registerLibrary() - Register a set of PHP functions as a Lua library
  • LuaSandbox::wrapPhpFunction() - Wrap a PHP callable in a LuaSandboxFunction


Pause the CPU usage timer

  • « LuaSandbox::loadString
  • LuaSandbox::registerLibrary »
  • PHP Manual
  • LuaSandbox
  • Pause the CPU usage timer

LuaSandbox::pauseUsageTimer

(PECL luasandbox >= 1.4.0)

LuaSandbox::pauseUsageTimer — Pause the CPU usage timer

Description

public LuaSandbox::pauseUsageTimer ( void ) : bool

Pauses the CPU usage timer.

This only has effect when called from within a callback from Lua. When execution returns to Lua, the timer will be automatically unpaused. If a new call into Lua is made, the timer will be unpaused for the duration of that call.

If a PHP callback calls into Lua again with timer not paused, and then that Lua function calls into PHP again, the second PHP call will not be able to pause the timer. The logic is that even though the second PHP call would avoid counting the CPU usage against the limit, the first call still counts it.

Parameters

This function has no parameters.

Return Values

Returns a boolean indicating whether the timer is now paused.

Examples

Example #1 Manipulating the usage timer

<?php

// create a new LuaSandbox and set a CPU limit
$sandbox = new LuaSandbox();
$sandbox->setCPULimit( 1 );

function doWait( $t ) {
    $end = microtime( true ) + $t;
    while ( microtime( true ) < $end ) {
        // waste CPU cycles
    }
}

// Register a PHP callback
$sandbox->registerLibrary( 'php', [
    'test' => function () use ( $sandbox ) {
        $sandbox->pauseUsageTimer();
        doWait( 5 );

        $sandbox->unpauseUsageTimer();
        doWait( 0.1 );
    },
    'test2' => function () use ( $sandbox ) {
        $sandbox->pauseUsageTimer();
        $sandbox->unpauseUsageTimer();
        doWait( 1.1 );
    }
] );

echo "This should not time out...\n";
$sandbox->loadString( 'php.test()' )->call();

echo "This should time out.\n";
try {
    $sandbox->loadString( 'php.test2()' )->call();
    echo "It did not?\n";
} catch ( LuaSandboxTimeoutError $ex ) {
    echo "It did! " . $ex->getMessage() . "\n";
}

?>

The above example will output:

This should not time out...
This should time out.
It did! The maximum execution time for this script was exceeded

See Also

  • LuaSandbox::setCPULimit() - Set the CPU time limit for the Lua environment
  • LuaSandbox::unpauseUsageTimer() - Unpause the timer paused by LuaSandbox::pauseUsageTimer


Register a set of PHP functions as a Lua library

  • « LuaSandbox::pauseUsageTimer
  • LuaSandbox::setCPULimit »
  • PHP Manual
  • LuaSandbox
  • Register a set of PHP functions as a Lua library

LuaSandbox::registerLibrary

(PECL luasandbox >= 1.0.0)

LuaSandbox::registerLibrary — Register a set of PHP functions as a Lua library

Description

public LuaSandbox::registerLibrary ( string $libname , array $functions ) : void

Registers a set of PHP functions as a Lua library, so that Lua can call the relevant PHP code.

For more information about calling Lua functions and the return values, see LuaSandboxFunction::call().

Parameters

libname

The name of the library. In the Lua state, the global variable of this name will be set to the table of functions. If the table already exists, the new functions will be added to it.

functions

An array, where each key is a function name, and each value is a corresponding PHP callable.

Return Values

No value is returned.

Examples

Example #1 Registering PHP functions to call from Lua

<?php

// create a new LuaSandbox
$sandbox = new LuaSandbox();

// Register some functions in the Lua environment

function frobnosticate( $v ) {
    return [ $v + 42 ];
}

$sandbox->registerLibrary( 'php', [
    'frobnosticate' => 'frobnosticate',
    'output' => function ( $string ) {
        echo "$string\n";
    },
    'error' => function () {
        throw new LuaSandboxRuntimeError( "Something is wrong" );
    }
] );

?>

See Also

  • LuaSandbox::loadString() - Load Lua code into the Lua environment
  • LuaSandbox::wrapPhpFunction() - Wrap a PHP callable in a LuaSandboxFunction


Set the CPU time limit for the Lua environment

  • « LuaSandbox::registerLibrary
  • LuaSandbox::setMemoryLimit »
  • PHP Manual
  • LuaSandbox
  • Set the CPU time limit for the Lua environment

LuaSandbox::setCPULimit

(PECL luasandbox >= 1.0.0)

LuaSandbox::setCPULimit — Set the CPU time limit for the Lua environment

Description

public LuaSandbox::setCPULimit ( float|bool $limit ) : void

Sets the CPU time limit for the Lua environment.

If the total user and system time used by the environment after the call to this method exceeds this limit, a LuaSandboxTimeoutError exception is thrown.

Time used in PHP callbacks is included in the limit.

Setting the time limit from a callback while Lua is running causes the timer to be reset, or started if it was not already running.

Note:

On Windows, the CPU limit will be ignored. On operating systems that do not support CLOCK_THREAD_CPUTIME_ID, such as FreeBSD and Mac OS X, wall-clock time rather than CPU time will be limited.

Parameters

limit

Limit as a float in seconds, or false for no limit.

Return Values

No value is returned.

Examples

Example #1 Calling a Lua function

<?php

// create a new LuaSandbox
$sandbox = new LuaSandbox();

// set a time limit
$sandbox->setCPULimit( 2 );

// Run Lua code
$sandbox->loadString( 'while true do end' )->call();

?>

The above example will output something similar to:

PHP Fatal error:  Uncaught LuaSandboxTimeoutError: The maximum execution time for this script was exceeded

See Also

  • LuaSandbox::getCPUUsage() - Fetch the current CPU time usage of the Lua environment
  • LuaSandbox::setMemoryLimit() - Set the memory limit for the Lua environment


Set the memory limit for the Lua environment

  • « LuaSandbox::setCPULimit
  • LuaSandbox::unpauseUsageTimer »
  • PHP Manual
  • LuaSandbox
  • Set the memory limit for the Lua environment

LuaSandbox::setMemoryLimit

(PECL luasandbox >= 1.0.0)

LuaSandbox::setMemoryLimit — Set the memory limit for the Lua environment

Description

public LuaSandbox::setMemoryLimit ( int $limit ) : void

Sets the memory limit for the Lua environment.

If this limit is exceeded, a LuaSandboxMemoryError exception is thrown.

Parameters

limit

Memory limit in bytes.

Return Values

No value is returned.

Examples

Example #1 Calling a Lua function

<?php

// create a new LuaSandbox
$sandbox = new LuaSandbox();

// set a memory limit
$sandbox->setMemoryLimit( 50 * 1024 * 1024 );

// Run Lua code
$sandbox->loadString( 'local x = "x"; while true do x = x .. x; end' )->call();

?>

The above example will output something similar to:

PHP Fatal error:  Uncaught LuaSandboxMemoryError: not enough memory

See Also

  • LuaSandbox::getMemoryUsage() - Fetch the current memory usage of the Lua environment
  • LuaSandbox::getPeakMemoryUsage() - Fetch the peak memory usage of the Lua environment
  • LuaSandbox::setCPULimit() - Set the CPU time limit for the Lua environment


Unpause the timer paused by LuaSandbox::pauseUsageTimer

  • « LuaSandbox::setMemoryLimit
  • LuaSandbox::wrapPhpFunction »
  • PHP Manual
  • LuaSandbox
  • Unpause the timer paused by LuaSandbox::pauseUsageTimer

LuaSandbox::unpauseUsageTimer

(PECL luasandbox >= 1.4.0)

LuaSandbox::unpauseUsageTimer — Unpause the timer paused by LuaSandbox::pauseUsageTimer()

Description

public LuaSandbox::unpauseUsageTimer ( void ) : void

Unpauses the timer paused by LuaSandbox::pauseUsageTimer().

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • LuaSandbox::pauseUsageTimer() - Pause the CPU usage timer
  • LuaSandbox::setCPULimit() - Set the CPU time limit for the Lua environment


Wrap a PHP callable in a LuaSandboxFunction

  • « LuaSandbox::unpauseUsageTimer
  • LuaSandboxFunction »
  • PHP Manual
  • LuaSandbox
  • Wrap a PHP callable in a LuaSandboxFunction

LuaSandbox::wrapPhpFunction

(PECL luasandbox >= 1.2.0)

LuaSandbox::wrapPhpFunction — Wrap a PHP callable in a LuaSandboxFunction

Description

public LuaSandbox::wrapPhpFunction ( callable $function ) : LuaSandboxFunction

Wraps a PHP callable in a LuaSandboxFunction, so it can be passed into Lua as an anonymous function.

The function must return either an array of values (which may be empty), or NULL which is equivalent to returning the empty array.

Exceptions will be raised as errors in Lua, however only LuaSandboxRuntimeError exceptions may be caught inside Lua with pcall() or xpcall().

For more information about calling Lua functions and the return values, see LuaSandboxFunction::call().

Parameters

function

Callable to wrap.

Return Values

Returns a LuaSandboxFunction.

See Also

  • LuaSandbox::loadString() - Load Lua code into the Lua environment
  • LuaSandbox::registerLibrary() - Register a set of PHP functions as a Lua library


The LuaSandboxFunction class

(PECL luasandbox >= 1.0.0)

Introduction

Represents a Lua function, allowing it to be called from PHP.

A LuaSandboxFunction may be obtained as a return value from Lua, as a parameter
passed to a callback from Lua, or by using
LuaSandbox::wrapPhpFunction(),
LuaSandbox::loadString(), or
LuaSandbox::loadBinary().

Class synopsis

LuaSandboxFunction {
/* Methods */
public call ([ string $... ] ) : array|bool
public dump ( void ) : string
}

Table of Contents

  • LuaSandboxFunction::call — Call a Lua function
  • LuaSandboxFunction::__construct — Unused
  • LuaSandboxFunction::dump — Dump the function as a binary blob


Call a Lua function

  • « LuaSandboxFunction
  • LuaSandboxFunction::__construct »
  • PHP Manual
  • LuaSandboxFunction
  • Call a Lua function

LuaSandboxFunction::call

(PECL luasandbox >= 1.0.0)

LuaSandboxFunction::call — Call a Lua function

Description

public LuaSandboxFunction::call ([ string $... ] ) : array|bool

Calls a Lua function.

Errors considered to be the fault of the PHP code will result in the function returning false and E_WARNING being raised, for example, a resource type being used as an argument. Lua errors will result in a LuaSandboxRuntimeError exception being thrown.

PHP and Lua types are converted as follows:

  • PHP NULL is Lua nil, and vice versa.

  • PHP integers and floats are converted to Lua numbers. Infinity and NAN are supported.

  • Lua numbers without a fractional part between approximately -2**53 and 2**53 are converted to PHP integers, with others being converted to PHP floats.

  • PHP booleans are Lua booleans, and vice versa.

  • PHP strings are Lua strings, and vice versa.

  • Lua functions are PHP LuaSandboxFunction objects, and vice versa. General PHP callables are not supported.

  • PHP arrays are converted to Lua tables, and vice versa.

    • Note that Lua typically indexes arrays from 1, while PHP indexes arrays from 0. No adjustment is made for these differing conventions.

    • Self-referential arrays are not supported in either direction.

    • PHP references are dereferenced.

    • Lua __pairs and __ipairs are processed. __index is ignored.

    • When converting from PHP to Lua, integer keys between -2**53 and 2**53 are represented as Lua numbers. All other keys are represented as Lua strings.

    • When converting from Lua to PHP, keys other than strings and numbers will result in an error, as will collisions when converting numbers to strings or vice versa (since PHP considers things like $a[0] and $a["0"] as being equivalent).

  • All other types are unsupported and will raise an error/exception, including general PHP objects and Lua userdata and thread types.

Lua functions inherently return a list of results. So on success, this method returns an array containing all of the values returned by Lua, with integer keys starting from zero. Lua may return no results, in which case an empty array is returned.

Parameters

...

Arguments passed to the function.

Return Values

Returns an array of values returned by the function, which may be empty, or false on error.


Unused

  • « LuaSandboxFunction::call
  • LuaSandboxFunction::dump »
  • PHP Manual
  • LuaSandboxFunction
  • Unused

LuaSandboxFunction::__construct

(PECL luasandbox >= 1.0.0)

LuaSandboxFunction::__construct — Unused

Description

final private LuaSandboxFunction::__construct ( void )

LuaSandboxFunction are obtained as a return value from Lua,
as a parameter passed to a callback from Lua, or by using
LuaSandbox::wrapPhpFunction(),
LuaSandbox::loadString(), or
LuaSandbox::loadBinary(). They cannot be constructed directly.

Parameters

This function has no parameters.


Dump the function as a binary blob

  • « LuaSandboxFunction::__construct
  • LuaSandboxError »
  • PHP Manual
  • LuaSandboxFunction
  • Dump the function as a binary blob

LuaSandboxFunction::dump

(PECL luasandbox >= 1.0.0)

LuaSandboxFunction::dump — Dump the function as a binary blob

Description

public LuaSandboxFunction::dump ( void ) : string

Dumps the function as a binary blob.

Parameters

This function has no parameters.

Return Values

Returns a string that may be passed to LuaSandbox::loadBinary().


The LuaSandboxError class

(PECL luasandbox >= 1.0.0)

Introduction

Base class for LuaSandbox exceptions

Class synopsis

LuaSandboxError extends Exception {
/* Constants */
const integer RUN = 2 ;
const integer SYNTAX = 3 ;
const integer MEM = 4 ;
const integer ERR = 5 ;
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}

Predefined Constants

LuaSandboxError::RUN

LuaSandboxError::SYNTAX

LuaSandboxError::MEM

LuaSandboxError::ERR


The LuaSandboxErrorError class

(PECL luasandbox >= 1.0.0)

Introduction

Exception thrown when Lua encounters an error inside an error handler.

Class synopsis

LuaSandboxErrorError extends LuaSandboxFatalError {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The LuaSandboxFatalError class

(PECL luasandbox >= 1.0.0)

Introduction

Uncatchable LuaSandbox exceptions.

These may not be caught inside Lua using pcall() or xpcall().

Class synopsis

LuaSandboxFatalError extends LuaSandboxError {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The LuaSandboxMemoryError class

(PECL luasandbox >= 1.0.0)

Introduction

Exception thrown when Lua cannot allocate memory.

Class synopsis

LuaSandboxMemoryError extends LuaSandboxFatalError {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}

See Also

  • LuaSandbox::setMemoryLimit()


The LuaSandboxRuntimeError class

(PECL luasandbox >= 1.0.0)

Introduction

Catchable LuaSandbox runtime exceptions.

These may be caught inside Lua using pcall() or xpcall().

Class synopsis

LuaSandboxRuntimeError extends LuaSandboxError {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The LuaSandboxSyntaxError class

(PECL luasandbox >= 1.0.0)

Introduction

Exception thrown when Lua code cannot be parsed.

Class synopsis

LuaSandboxSyntaxError extends LuaSandboxFatalError {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The LuaSandboxTimeoutError class

(PECL luasandbox >= 1.0.0)

Introduction

Exception thrown when the configured CPU time limit is exceeded.

Class synopsis

LuaSandboxTimeoutError extends LuaSandboxFatalError {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}

See Also

  • LuaSandbox::setCPULimit()


Miscellaneous Functions

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Misc. Functions
    • connection_aborted — Check whether client disconnected
    • connection_status — Returns connection status bitfield
    • constant — Returns the value of a constant
    • define — Defines a named constant
    • defined — Checks whether a given named constant exists
    • die — Equivalent to exit
    • eval — Evaluate a string as PHP code
    • exit — Output a message and terminate the current script
    • get_browser — Tells what the user's browser is capable of
    • __halt_compiler — Halts the compiler execution
    • highlight_file — Syntax highlighting of a file
    • highlight_string — Syntax highlighting of a string
    • hrtime — Get the system's high resolution time
    • ignore_user_abort — Set whether a client disconnect should abort script execution
    • pack — Pack data into binary string
    • php_check_syntax — Check the PHP syntax of (and execute) the specified file
    • php_strip_whitespace — Return source with stripped comments and whitespace
    • sapi_windows_cp_conv — Convert string from one codepage to another
    • sapi_windows_cp_get — Get process codepage
    • sapi_windows_cp_is_utf8 — Indicates whether the codepage is UTF-8 compatible
    • sapi_windows_cp_set — Set process codepage
    • sapi_windows_generate_ctrl_event — Send a CTRL event to another process
    • sapi_windows_set_ctrl_handler — Set or remove a CTRL event handler
    • sapi_windows_vt100_support — Get or set VT100 support for the specified stream associated to an output buffer of a Windows console.
    • show_source — Alias of highlight_file
    • sleep — Delay execution
    • sys_getloadavg — Gets system load average
    • time_nanosleep — Delay for a number of seconds and nanoseconds
    • time_sleep_until — Make the script sleep until the specified time
    • uniqid — Generate a unique ID
    • unpack — Unpack data from binary string
    • usleep — Delay execution in microseconds
  • Changelog


Introduction

These functions were placed here because none of the other categories seemed to fit.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Misc. Configuration Options
Name | Default | Changeable | Changelog
ignore_user_abort | "0" | PHP_INI_ALL |
highlight.string | "#DD0000" | PHP_INI_ALL |
highlight.comment | "#FF8000" | PHP_INI_ALL |
highlight.keyword | "#007700" | PHP_INI_ALL |
highlight.bg | "#FFFFFF" | PHP_INI_ALL | Removed in PHP 5.4.0.
highlight.default | "#0000BB" | PHP_INI_ALL |
highlight.html | "#000000" | PHP_INI_ALL |
browscap | NULL | PHP_INI_SYSTEM |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

ignore_user_abort boolean

FALSE by default. If changed to TRUE scripts will not be terminated after a client has aborted their connection.

See also ignore_user_abort().

highlight.bg string
highlight.comment string
highlight.default string
highlight.html string
highlight.keyword string
highlight.string string

Colors for Syntax Highlighting mode. Anything that's acceptable in <font color="??????"> would work.

browscap string

Name (e.g.: browscap.ini) and location of browser capabilities file. See also get_browser().


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.

CONNECTION_ABORTED (integer)
CONNECTION_NORMAL (integer)
CONNECTION_TIMEOUT (integer)
__COMPILER_HALT_OFFSET__ (integer)
Added in PHP 5.1.


Misc. Functions

Table of Contents

  • connection_aborted — Check whether client disconnected
  • connection_status — Returns connection status bitfield
  • constant — Returns the value of a constant
  • define — Defines a named constant
  • defined — Checks whether a given named constant exists
  • die — Equivalent to exit
  • eval — Evaluate a string as PHP code
  • exit — Output a message and terminate the current script
  • get_browser — Tells what the user's browser is capable of
  • __halt_compiler — Halts the compiler execution
  • highlight_file — Syntax highlighting of a file
  • highlight_string — Syntax highlighting of a string
  • hrtime — Get the system's high resolution time
  • ignore_user_abort — Set whether a client disconnect should abort script execution
  • pack — Pack data into binary string
  • php_check_syntax — Check the PHP syntax of (and execute) the specified file
  • php_strip_whitespace — Return source with stripped comments and whitespace
  • sapi_windows_cp_conv — Convert string from one codepage to another
  • sapi_windows_cp_get — Get process codepage
  • sapi_windows_cp_is_utf8 — Indicates whether the codepage is UTF-8 compatible
  • sapi_windows_cp_set — Set process codepage
  • sapi_windows_generate_ctrl_event — Send a CTRL event to another process
  • sapi_windows_set_ctrl_handler — Set or remove a CTRL event handler
  • sapi_windows_vt100_support — Get or set VT100 support for the specified stream associated to an output buffer of a Windows console.
  • show_source — Alias of highlight_file
  • sleep — Delay execution
  • sys_getloadavg — Gets system load average
  • time_nanosleep — Delay for a number of seconds and nanoseconds
  • time_sleep_until — Make the script sleep until the specified time
  • uniqid — Generate a unique ID
  • unpack — Unpack data from binary string
  • usleep — Delay execution in microseconds


Check whether client disconnected

  • « Misc. Functions
  • connection_status »
  • PHP Manual
  • Misc. Functions
  • Check whether client disconnected

connection_aborted

(PHP 4, PHP 5, PHP 7)

connection_aborted — Check whether client disconnected

Description

connection_aborted ( void ) : int

Checks whether the client disconnected.

Return Values

Returns 1 if client disconnected, 0 otherwise.

See Also

  • connection_status() - Returns connection status bitfield
  • ignore_user_abort() - Set whether a client disconnect should abort script execution
  • Connection Handling for a complete description of connection handling in PHP.


Returns connection status bitfield

  • « connection_aborted
  • constant »
  • PHP Manual
  • Misc. Functions
  • Returns connection status bitfield

connection_status

(PHP 4, PHP 5, PHP 7)

connection_status — Returns connection status bitfield

Description

connection_status ( void ) : int

Gets the connection status bitfield.

Return Values

Returns the connection status bitfield, which can be used against the CONNECTION_XXX constants to determine the connection status.

See Also

  • connection_aborted() - Check whether client disconnected
  • ignore_user_abort() - Set whether a client disconnect should abort script execution
  • Connection Handling for a complete description of connection handling in PHP.


Returns the value of a constant

  • « connection_status
  • define »
  • PHP Manual
  • Misc. Functions
  • Returns the value of a constant

constant

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

constant — Returns the value of a constant

Description

constant ( string $name ) : mixed

Return the value of the constant indicated by name.

constant() is useful if you need to retrieve the value of a constant, but do not know its name. I.e. it is stored in a variable or returned by a function.

This function works also with class constants.

Parameters

name

The constant name.

Return Values

Returns the value of the constant, or NULL if the constant is not defined.

Errors/Exceptions

An E_WARNING level error is generated if the constant is not defined.

Examples

Example #1 constant() example

<?php

define("MAXSIZE", 100);

echo MAXSIZE;
echo constant("MAXSIZE"); // same thing as the previous line

interface bar {
    const test = 'foobar!';
}

class foo {
    const test = 'foobar!';
}

$const = 'test';

var_dump(constant('bar::'. $const)); // string(7) "foobar!"
var_dump(constant('foo::'. $const)); // string(7) "foobar!"

?>

See Also

  • define() - Defines a named constant
  • defined() - Checks whether a given named constant exists
  • The section on Constants


Defines a named constant

  • « constant
  • defined »
  • PHP Manual
  • Misc. Functions
  • Defines a named constant

define

(PHP 4, PHP 5, PHP 7)

define — Defines a named constant

Description

define ( string $name , mixed $value [, bool $case_insensitive = FALSE ] ) : bool

Defines a named constant at runtime.

Parameters

name

The name of the constant.

Note:

It is possible to define() constants with reserved or even invalid names, whose value can (only) be retrieved with constant(). However, doing so is not recommended.

value

The value of the constant. In PHP 5, value must be a scalar value (integer, float, string, boolean, or NULL). In PHP 7, array values are also accepted.

Warning

While it is possible to define resource constants, it is not recommended and may cause unpredictable behavior.

case_insensitive

If set to TRUE, the constant will be defined case-insensitive. The default behavior is case-sensitive; i.e. CONSTANT and Constant represent different values.

Warning

Defining case-insensitive constants is deprecated as of PHP 7.3.0.

Note:

Case-insensitive constants are stored as lower-case.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.3.0 | case_insensitive has been deprecated and will be removed in version 8.0.0.
7.0.0 | array values are allowed.

Examples

Example #1 Defining Constants

<?php
define("CONSTANT", "Hello world.");
echo CONSTANT; // outputs "Hello world."
echo Constant; // outputs "Constant" and issues a notice.

define("GREETING", "Hello you.", true);
echo GREETING; // outputs "Hello you."
echo Greeting; // outputs "Hello you."

// Works as of PHP 7
define('ANIMALS', array(
    'dog',
    'cat',
    'bird'
));
echo ANIMALS[1]; // outputs "cat"

?>

Example #2 Constants with Reserved Names

This example illustrates the possibility to define a constant with the same name as a magic constant. Since the resulting behavior is obviously confusing, it is not recommended to do this in practise, though.

<?php
var_dump(defined('__LINE__'));
var_dump(define('__LINE__', 'test'));
var_dump(constant('__LINE__'));
var_dump(__LINE__);
?>

The above example will output:

bool(false)
bool(true)
string(4) "test"
int(5)

See Also

  • defined() - Checks whether a given named constant exists
  • constant() - Returns the value of a constant
  • The section on Constants


Checks whether a given named constant exists

  • « define
  • die »
  • PHP Manual
  • Misc. Functions
  • Checks whether a given named constant exists

defined

(PHP 4, PHP 5, PHP 7)

defined — Checks whether a given named constant exists

Description

defined ( string $name ) : bool

Checks whether the given constant exists and is defined.

Note:

If you want to see if a variable exists, use isset() as defined() only applies to constants. If you want to see if a function exists, use function_exists().

Parameters

name

The constant name.

Return Values

Returns TRUE if the named constant given by name has been defined, FALSE otherwise.

Examples

Example #1 Checking Constants

<?php
/* Note the use of quotes, this is important.  This example is checking
 * if the string 'TEST' is the name of a constant named TEST */
if (defined('TEST')) {
    echo TEST;
}
?>

See Also

  • define() - Defines a named constant
  • constant() - Returns the value of a constant
  • get_defined_constants() - Returns an associative array with the names of all the constants and their values
  • function_exists() - Return TRUE if the given function has been defined
  • The section on Constants


Equivalent to exit

  • « defined
  • eval »
  • PHP Manual
  • Misc. Functions
  • Equivalent to exit

die

(PHP 4, PHP 5, PHP 7)

die — Equivalent to exit

Description

This language construct is equivalent to exit().


Evaluate a string as PHP code

  • « die
  • exit »
  • PHP Manual
  • Misc. Functions
  • Evaluate a string as PHP code

eval

(PHP 4, PHP 5, PHP 7)

eval — Evaluate a string as PHP code

Description

eval ( string $code ) : mixed

Evaluates the given code as PHP.

Caution

The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.

Parameters

code

Valid PHP code to be evaluated.

The code must not be wrapped in opening and closing PHP tags, i.e. 'echo "Hi!";' must be passed instead of '<?php echo "Hi!"; ?>'. It is still possible to leave and re-enter PHP mode though using the appropriate PHP tags, e.g. 'echo "In PHP mode!"; ?>In HTML mode!<?php echo "Back in PHP mode!";'.

Apart from that the passed code must be valid PHP. This includes that all statements must be properly terminated using a semicolon. 'echo "Hi!"' for example will cause a parse error, whereas 'echo "Hi!";' will work.

A return statement will immediately terminate the evaluation of the code.

The code will be executed in the scope of the code calling eval(). Thus any variables defined or changed in the eval() call will remain visible after it terminates.

Return Values

eval() returns NULL unless return is called in the evaluated code, in which case the value passed to return is returned. As of PHP 7, if there is a parse error in the evaluated code, eval() throws a ParseError exception. Before PHP 7, in this case eval() returned FALSE and execution of the following code continued normally. It is not possible to catch a parse error in eval() using set_error_handler().

Examples

Example #1 eval() example - simple text merge

<?php
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$str = \"$str\";");
echo $str. "\n";
?>

The above example will output:

This is a $string with my $name in it.
This is a cup with my coffee in it.

Notes

Note: Because this is a language construct and not a function, it cannot be called using variable functions.

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).

Note:

In case of a fatal error in the evaluated code, the whole script exits.

See Also

  • call_user_func() - Call the callback given by the first parameter


Output a message and terminate the current script

  • « eval
  • get_browser »
  • PHP Manual
  • Misc. Functions
  • Output a message and terminate the current script

exit

(PHP 4, PHP 5, PHP 7)

exit — Output a message and terminate the current script

Description

exit ([ string $status ] ) : void
exit ( int $status ) : void

Terminates execution of the script. Shutdown functions and object destructors will always be executed even if exit is called.

exit is a language construct and it can be called without parentheses if no status is passed.

Parameters

status

If status is a string, this function prints the status just before exiting.

If status is an integer, that value will be used as the exit status and not printed. Exit statuses should be in the range 0 to 254, the exit status 255 is reserved by PHP and shall not be used. The status 0 is used to terminate the program successfully.

Return Values

No value is returned.

Examples

Example #1 exit example

<?php

$filename = '/path/to/data-file';
$file = fopen($filename, 'r')
    or exit("unable to open file ($filename)");

?>

Example #2 exit status example

<?php

//exit program normally
exit;
exit();
exit(0);

//exit with an error code
exit(1);
exit(0376); //octal

?>

Example #3 Shutdown functions and destructors run regardless

<?php
class Foo
{
    public function __destruct()
    {
        echo 'Destruct: ' . __METHOD__ . '()' . PHP_EOL;
    }
}

function shutdown()
{
    echo 'Shutdown: ' . __FUNCTION__ . '()' . PHP_EOL;
}

$foo = new Foo();
register_shutdown_function('shutdown');

exit();
echo 'This will not be output.';
?>

The above example will output:

 Shutdown: shutdown()
 Destruct: Foo::__destruct()

Notes

Note: Because this is a language construct and not a function, it cannot be called using variable functions.

Note:

This language construct is equivalent to die().

See Also

  • register_shutdown_function() - Register a function for execution on shutdown


Tells what the user's browser is capable of

  • « exit
  • __halt_compiler »
  • PHP Manual
  • Misc. Functions
  • Tells what the user's browser is capable of

get_browser

(PHP 4, PHP 5, PHP 7)

get_browser — Tells what the user's browser is capable of

Description

get_browser ([ string $user_agent [, bool $return_array = FALSE ]] ) : mixed

Attempts to determine the capabilities of the user's browser, by looking up the browser's information in the browscap.ini file.

Parameters

user_agent

The User Agent to be analyzed. By default, the value of HTTP User-Agent header is used; however, you can alter this (i.e., look up another browser's info) by passing this parameter.

You can bypass this parameter with a NULL value.

return_array

If set to TRUE, this function will return an array instead of an object.

Return Values

The information is returned in an object or an array which will contain various data elements representing, for instance, the browser's major and minor version numbers and ID string; TRUE/FALSE values for features such as frames, JavaScript, and cookies; and so forth.

The cookies value simply means that the browser itself is capable of accepting cookies and does not mean the user has enabled the browser to accept cookies or not. The only way to test if cookies are accepted is to set one with setcookie(), reload, and check for the value.

Examples

Example #1 Listing all information about the users browser

<?php
echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";

$browser = get_browser(null, true);
print_r($browser);
?>

The above example will output something similar to:

Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7) Gecko/20040803 Firefox/0.9.3

Array
(
    [browser_name_regex] => ^mozilla/5\.0 (windows; .; windows nt 5\.1; .*rv:.*) gecko/.* firefox/0\.9.*$
    [browser_name_pattern] => Mozilla/5.0 (Windows; ?; Windows NT 5.1; *rv:*) Gecko/* Firefox/0.9*
    [parent] => Firefox 0.9
    [platform] => WinXP
    [browser] => Firefox
    [version] => 0.9
    [majorver] => 0
    [minorver] => 9
    [cssversion] => 2
    [frames] => 1
    [iframes] => 1
    [tables] => 1
    [cookies] => 1
    [backgroundsounds] =>
    [vbscript] =>
    [javascript] => 1
    [javaapplets] => 1
    [activexcontrols] =>
    [cdf] =>
    [aol] =>
    [beta] => 1
    [win16] =>
    [crawler] =>
    [stripper] =>
    [wap] =>
    [netclr] =>
)

Notes

Note:

In order for this to work, your browscap configuration setting in php.ini must point to the correct location of the browscap.ini file on your system.

browscap.ini is not bundled with PHP, but you may find an up-to-date » php_browscap.ini file here.

While browscap.ini contains information on many browsers, it relies on user updates to keep the database current. The format of the file is fairly self-explanatory.


Halts the compiler execution

  • « get_browser
  • highlight_file »
  • PHP Manual
  • Misc. Functions
  • Halts the compiler execution

__halt_compiler

(PHP 5 >= 5.1.0, PHP 7)

__halt_compiler — Halts the compiler execution

Description

__halt_compiler ( void ) : void

Halts the execution of the compiler. This can be useful to embed data in PHP scripts, like the installation files.

Byte position of the data start can be determined by the __COMPILER_HALT_OFFSET__ constant which is defined only if there is a __halt_compiler() presented in the file.

Return Values

No value is returned.

Examples

Example #1 A __halt_compiler() example

<?php

// open this file
$fp = fopen(__FILE__, 'r');

// seek file pointer to data
fseek($fp, __COMPILER_HALT_OFFSET__);

// and output it
var_dump(stream_get_contents($fp));

// the end of the script execution
__halt_compiler(); the installation data (eg. tar, gz, PHP, etc.)

Notes

Note:

__halt_compiler() can only be used from the outermost scope.


Syntax highlighting of a file

  • « __halt_compiler
  • highlight_string »
  • PHP Manual
  • Misc. Functions
  • Syntax highlighting of a file

highlight_file

(PHP 4, PHP 5, PHP 7)

highlight_file — Syntax highlighting of a file

Description

highlight_file ( string $filename [, bool $return = FALSE ] ) : mixed

Prints out or returns a syntax highlighted version of the code contained in filename using the colors defined in the built-in syntax highlighter for PHP.

Many servers are configured to automatically highlight files with a phps extension. For example, example.phps when viewed will show the syntax highlighted source of the file. To enable this, add this line to the httpd.conf:

AddType application/x-httpd-php-source .phps

Parameters

filename

Path to the PHP file to be highlighted.

return

Set this parameter to TRUE to make this function return the highlighted code.

Return Values

If return is set to TRUE, returns the highlighted code as a string instead of printing it out. Otherwise, it will return TRUE on success, FALSE on failure.

Notes

Caution

Care should be taken when using the highlight_file() function to make sure that you do not inadvertently reveal sensitive information such as passwords or any other type of information that might create a potential security risk.

Note:

When the return parameter is used, this function uses internal output buffering so it cannot be used inside an ob_start() callback function.

See Also

  • highlight_string() - Syntax highlighting of a string
  • Highlighting INI directives


Syntax highlighting of a string

  • « highlight_file
  • hrtime »
  • PHP Manual
  • Misc. Functions
  • Syntax highlighting of a string

highlight_string

(PHP 4, PHP 5, PHP 7)

highlight_string — Syntax highlighting of a string

Description

highlight_string ( string $str [, bool $return = FALSE ] ) : mixed

Outputs or returns html markup for a syntax highlighted version of the given PHP code using the colors defined in the built-in syntax highlighter for PHP.

Parameters

str

The PHP code to be highlighted. This should include the opening tag.

return

Set this parameter to TRUE to make this function return the highlighted code.

Return Values

If return is set to TRUE, returns the highlighted code as a string instead of printing it out. Otherwise, it will return TRUE on success, FALSE on failure.

Examples

Example #1 highlight_string() example

<?php
highlight_string('<?php phpinfo(); ?>');
?>

The above example will output:

<code><span style="color: #000000">
<span style="color: #0000BB">&lt;?php phpinfo</span><span style="color: #007700">(); </span><span style="color: #0000BB">?&gt;</span>
</span>
</code>

Notes

Note:

When the return parameter is used, this function uses internal output buffering so it cannot be used inside an ob_start() callback function.

The HTML markup generated is subject to change.

See Also

  • highlight_file() - Syntax highlighting of a file
  • Highlighting INI directives


Get the system's high resolution time

  • « highlight_string
  • ignore_user_abort »
  • PHP Manual
  • Misc. Functions
  • Get the system's high resolution time

hrtime

(PHP 7 >= 7.3.0)

hrtime — Get the system's high resolution time

Description

hrtime ([ bool $get_as_number = FALSE ] ) : mixed

Returns the system's high resolution time, counted from an arbitrary point in time. The delivered timestamp is monotonic and can not be adjusted.

Parameters

get_as_number

Whether the high resolution time should be returned as array or number.

Return Values

Returns an array of integers in the form [seconds, nanoseconds], if the parameter get_as_number is false. Otherwise the nanoseconds are returned as integer (64bit platforms) or float (32bit platforms).

Examples

Example #1 hrtime() usage

<?php
echo hrtime(true), PHP_EOL;
print_r(hrtime());
?>

The above example will output something similar to:

10444739687370679
Array
(
    [0] => 10444739
    [1] => 687464812
)

See Also

  • The High resolution timing extension


Set whether a client disconnect should abort script execution

  • « hrtime
  • pack »
  • PHP Manual
  • Misc. Functions
  • Set whether a client disconnect should abort script execution

ignore_user_abort

(PHP 4, PHP 5, PHP 7)

ignore_user_abort — Set whether a client disconnect should abort script execution

Description

ignore_user_abort ([ bool $value ] ) : int

Sets whether a client disconnect should cause a script to be aborted.

When running PHP as a command line script, and the script's tty goes away without the script being terminated then the script will die the next time it tries to write anything, unless value is set to TRUE

Parameters

value

If set, this function will set the ignore_user_abort ini setting to the given value. If not, this function will only return the previous setting without changing it.

Return Values

Returns the previous setting, as an integer.

Examples

Example #1 A ignore_user_abort() example

<?php
// Ignore user aborts and allow the script
// to run forever
ignore_user_abort(true);
set_time_limit(0);

echo 'Testing connection handling in PHP';

// Run a pointless loop that sometime
// hopefully will make us click away from
// page or click the "Stop" button.
while(1)
{
    // Did the connection fail?
    if(connection_status() != CONNECTION_NORMAL)
    {
        break;
    }

    // Sleep for 10 seconds
    sleep(10);
}

// If this is reached, then the 'break'
// was triggered from inside the while loop

// So here we can log, or perform any other tasks
// we need without actually being dependent on the
// browser.
?>

Notes

PHP will not detect that the user has aborted the connection until an attempt is made to send information to the client. Simply using an echo statement does not guarantee that information is sent, see flush().

See Also

  • connection_aborted() - Check whether client disconnected
  • connection_status() - Returns connection status bitfield
  • Connection Handling for a complete description of connection handling in PHP.


Pack data into binary string

  • « ignore_user_abort
  • php_check_syntax »
  • PHP Manual
  • Misc. Functions
  • Pack data into binary string

pack

(PHP 4, PHP 5, PHP 7)

pack — Pack data into binary string

Description

pack ( string $format [, mixed $... ] ) : string

Pack given arguments into a binary string according to format.

The idea for this function was taken from Perl and all formatting codes work the same as in Perl. However, there are some formatting codes that are missing such as Perl's "u" format code.

Note that the distinction between signed and unsigned values only affects the function unpack(), where as function pack() gives the same result for signed and unsigned format codes.

Parameters

format

The format string consists of format codes followed by an optional repeater argument. The repeater argument can be either an integer value or * for repeating to the end of the input data. For a, A, h, H the repeat count specifies how many characters of one data argument are taken, for @ it is the absolute position where to put the next data, for everything else the repeat count specifies how many data arguments are consumed and packed into the resulting binary string.

Currently implemented formats are:

pack() format characters
Code | Description
a | NUL-padded string
A | SPACE-padded string
h | Hex string, low nibble first
H | Hex string, high nibble first
c | signed char
C | unsigned char
s | signed short (always 16 bit, machine byte order)
S | unsigned short (always 16 bit, machine byte order)
n | unsigned short (always 16 bit, big endian byte order)
v | unsigned short (always 16 bit, little endian byte order)
i | signed integer (machine dependent size and byte order)
I | unsigned integer (machine dependent size and byte order)
l | signed long (always 32 bit, machine byte order)
L | unsigned long (always 32 bit, machine byte order)
N | unsigned long (always 32 bit, big endian byte order)
V | unsigned long (always 32 bit, little endian byte order)
q | signed long long (always 64 bit, machine byte order)
Q | unsigned long long (always 64 bit, machine byte order)
J | unsigned long long (always 64 bit, big endian byte order)
P | unsigned long long (always 64 bit, little endian byte order)
f | float (machine dependent size and representation)
g | float (machine dependent size, little endian byte order)
G | float (machine dependent size, big endian byte order)
d | double (machine dependent size and representation)
e | double (machine dependent size, little endian byte order)
E | double (machine dependent size, big endian byte order)
x | NUL byte
X | Back up one byte
Z | NUL-padded string (new in PHP 5.5)
@ NUL-fill to absolute position

...

Return Values

Returns a binary string containing data.

Changelog

Version | Description
7.2.0 | float and double types supports both Big Endian and Little Endian.
7.0.15,7.1.1 | The "e", "E", "g" and "G" codes were added to enable byte order support for float and double.
5.6.3 | The "q", "Q", "J" and "P" codes were added to enable working with 64-bit numbers.
5.5.0 | The "Z" code was added with equivalent functionality to "a" for Perl compatibility.

Examples

Example #1 pack() example

<?php
$binarydata = pack("nvc*", 0x1234, 0x5678, 65, 66);
?>

The resulting binary string will be 6 bytes long and contain the byte sequence 0x12, 0x34, 0x78, 0x56, 0x41, 0x42.

Notes

Caution

Note that PHP internally stores integer values as signed values of a machine-dependent size (C type long). Integer literals and operations that yield numbers outside the bounds of the integer type will be stored as float. When packing these floats as integers, they are first cast into the integer type. This may or may not result in the desired byte pattern.

The most relevant case is when packing unsigned numbers that would be representable with the integer type if it were unsigned. In systems where the integer type has a 32-bit size, the cast usually results in the same byte pattern as if the integer were unsigned (although this relies on implementation-defined unsigned to signed conversions, as per the C standard). In systems where the integer type has 64-bit size, the float most likely does not have a mantissa large enough to hold the value without loss of precision. If those systems also have a native 64-bit C int type (most UNIX-like systems don't), the only way to use the I pack format in the upper range is to create integer negative values with the same byte representation as the desired unsigned value.

See Also

  • unpack() - Unpack data from binary string


Check the PHP syntax of (and execute) the specified file

  • « pack
  • php_strip_whitespace »
  • PHP Manual
  • Misc. Functions
  • Check the PHP syntax of (and execute) the specified file

php_check_syntax

(PHP 5 < 5.0.5)

php_check_syntax — Check the PHP syntax of (and execute) the specified file

Description

php_check_syntax ( string $filename [, string &$error_message ] ) : bool

Performs a syntax (lint) check on the specified filename testing for scripting errors.

This is similar to using php -l from the commandline except that this function will execute (but not output) the checked filename.

For example, if a function is defined in filename, this defined function will be available to the file that executed php_check_syntax(), but output from filename will be suppressed.

Note:

For technical reasons, this function is deprecated and removed from PHP. Instead, use php -l somefile.php from the commandline.

Parameters

filename

The name of the file being checked.

error_message

If the error_message parameter is used, it will contain the error message generated by the syntax check. error_message is passed by reference.

Return Values

Returns TRUE if the lint check passed, and FALSE if the link check failed or if filename cannot be opened.

Changelog

Version | Description
5.0.5 | This function was removed from PHP.
5.0.3 | Calling exit() after php_check_syntax() resulted in a Segfault.
5.0.1 | error_message is passed by reference.

Examples

php -l somefile.php

The above example will output something similar to:

PHP Parse error: unexpected T_STRING in /tmp/somefile.php on line 81

See Also

  • include - include
  • is_readable() - Tells whether a file exists and is readable


Return source with stripped comments and whitespace

  • « php_check_syntax
  • sapi_windows_cp_conv »
  • PHP Manual
  • Misc. Functions
  • Return source with stripped comments and whitespace

php_strip_whitespace

(PHP 5, PHP 7)

php_strip_whitespace — Return source with stripped comments and whitespace

Description

php_strip_whitespace ( string $filename ) : string

Returns the PHP source code in filename with PHP comments and whitespace removed. This may be useful for determining the amount of actual code in your scripts compared with the amount of comments. This is similar to using php -w from the commandline.

Parameters

filename

Path to the PHP file.

Return Values

The stripped source code will be returned on success, or an empty string on failure.

Note:

This function respects the value of the short_open_tag ini directive.

Note:

This function works as described as of PHP 5.0.1. Before this it would only return an empty string. For more information on this bug and its prior behavior, see bug report » #29606.

Examples

Example #1 php_strip_whitespace() example

<?php
// PHP comment here

/*
 * Another PHP comment
 */

echo        php_strip_whitespace(__FILE__);
// Newlines are considered whitespace, and are removed too:
do_nothing();
?>

The above example will output:

<?php
 echo php_strip_whitespace(__FILE__); do_nothing(); ?>

Notice the PHP comments are gone, as are the whitespace and newline after the first echo statement.


Convert string from one codepage to another

  • « php_strip_whitespace
  • sapi_windows_cp_get »
  • PHP Manual
  • Misc. Functions
  • Convert string from one codepage to another

sapi_windows_cp_conv

(PHP 7 >= 7.1.0)

sapi_windows_cp_conv — Convert string from one codepage to another

Description

sapi_windows_cp_conv ( int|string $in_codepage , int|string $out_codepage , string $subject ) : string

Convert string from one codepage to another.

Parameters

in_codepage

The codepage of the subject string. Either the codepage name or identifier.

out_codepage

The codepage to convert the subject string to. Either the codepage name or identifier.

subject

The string to convert.

Return Values

The subject string converted to out_codepage, or NULL on failure.

Errors/Exceptions

This function issues E_WARNING level errors, if invalid codepages are given, or if the subject is not valid for in_codepage.

See Also

  • sapi_windows_cp_get() - Get process codepage
  • iconv() - Convert string to requested character encoding


Get process codepage

  • « sapi_windows_cp_conv
  • sapi_windows_cp_is_utf8 »
  • PHP Manual
  • Misc. Functions
  • Get process codepage

sapi_windows_cp_get

(PHP 7 >= 7.1.0)

sapi_windows_cp_get — Get process codepage

Description

sapi_windows_cp_get ( string $kind ) : int

Get the identifier of the codepage of the current process.

Parameters

kind

The kind of codepage: either 'ansi' or 'oem'.

Return Values

Returns the codepage identifier.

See Also

  • sapi_windows_cp_set() - Set process codepage


Indicates whether the codepage is UTF-8 compatible

  • « sapi_windows_cp_get
  • sapi_windows_cp_set »
  • PHP Manual
  • Misc. Functions
  • Indicates whether the codepage is UTF-8 compatible

sapi_windows_cp_is_utf8

(PHP 7 >= 7.1.0)

sapi_windows_cp_is_utf8 — Indicates whether the codepage is UTF-8 compatible

Description

sapi_windows_cp_is_utf8 ( void ) : bool

Indicates whether the codepage of the current process is UTF-8 compatible.

Parameters

This function has no parameters.

Return Values

Returns whether the codepage of the current process is UTF-8 compatible.

See Also

  • sapi_windows_cp_get() - Get process codepage


Set process codepage

  • « sapi_windows_cp_is_utf8
  • sapi_windows_generate_ctrl_event »
  • PHP Manual
  • Misc. Functions
  • Set process codepage

sapi_windows_cp_set

(PHP 7 >= 7.1.0)

sapi_windows_cp_set — Set process codepage

Description

sapi_windows_cp_set ( int $cp ) : bool

Set the codepage of the current process.

Parameters

cp

A codepage identifier.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • sapi_windows_cp_get() - Get process codepage


Send a CTRL event to another process

  • « sapi_windows_cp_set
  • sapi_windows_set_ctrl_handler »
  • PHP Manual
  • Misc. Functions
  • Send a CTRL event to another process

sapi_windows_generate_ctrl_event

(PHP 7 >= 7.4.0)

sapi_windows_generate_ctrl_event — Send a CTRL event to another process

Description

sapi_windows_generate_ctrl_event ( int $event [, int $pid = 0 ] ) : bool

Sends a CTRL event to another process in the same process group.

Parameters

event

The CTRL even to send; either PHP_WINDOWS_EVENT_CTRL_C or PHP_WINDOWS_EVENT_CTRL_BREAK.

pid

The ID of the process to which to send the event to. If 0 is given, the event is sent to all processes of the process group.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Basic sapi_windows_generate_ctrl_event() Usage

This example shows how to pass along CTRL+BREAK events to a child process. In this case the child process echoes I'm still alive every second, until the user presses CTRL+BREAK, what causes only the child process to be terminated.

<?php
// forward CTRL+BREAK events to the child process
sapi_windows_set_ctrl_handler('sapi_windows_generate_ctrl_event');

// create a child process which echoes every second
$cmd = ['php', '-r', 'while (true) { echo "I\'m still alive\n"; sleep(1); }'];
$descspec = array(['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']);
$options = ['create_process_group' => true];
$proc = proc_open($cmd, $descspec, $pipes, null, null, $options);
while (true) {
    echo fgets($pipes[1]);
}
?>

See Also

  • proc_open() - Execute a command and open file pointers for input/output
  • sapi_windows_set_ctrl_handler() - Set or remove a CTRL event handler


Set or remove a CTRL event handler

  • « sapi_windows_generate_ctrl_event
  • sapi_windows_vt100_support »
  • PHP Manual
  • Misc. Functions
  • Set or remove a CTRL event handler

sapi_windows_set_ctrl_handler

(PHP 7 >= 7.4.0)

sapi_windows_set_ctrl_handler — Set or remove a CTRL event handler

Description

sapi_windows_set_ctrl_handler ( callable $callable [, bool $add = TRUE ] ) : bool

Sets or removes a CTRL event handler, which allows Windows CLI processes to intercept or ignore CTRL+C and CTRL+BREAK events. Note that in multithreaded environments, this is only possible when called from the main thread.

Parameters

callable

A callback function to set or remove. If set, this function will be called whenever a CTRL+C or CTRL+BREAK event occurs. The function is supposed to have the following signature:

handler ( int $event ) : void
event
The CTRL event which has been received; either PHP_WINDOWS_EVENT_CTRL_C or PHP_WINDOWS_EVENT_CTRL_BREAK.
Setting a NULL callable causes the process to ignore CTRL+C events, but not CTRL+BREAK events.

add

If TRUE, the handler is set. If FALSE, the handler is removed.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Basic sapi_windows_set_ctrl_handler() Usage

This example shows how to intercept CTRL events.

<?php
function ctrl_handler(int $event)
{
    switch ($event) {
        case PHP_WINDOWS_EVENT_CTRL_C:
            echo "You have pressed CTRL+C\n";
            break;
        case PHP_WINDOWS_EVENT_CTRL_BREAK:
            echo "You have pressed CTRL+BREAK\n";
            break;
    }
}

sapi_windows_set_ctrl_handler('ctrl_handler');
while (true); // infinite loop, so the handler can be triggered
?>

See Also

  • sapi_windows_generate_ctrl_event() - Send a CTRL event to another process


Get or set VT100 support for the specified stream associated to an output buffer of a Windows console.

  • « sapi_windows_set_ctrl_handler
  • show_source »
  • PHP Manual
  • Misc. Functions
  • Get or set VT100 support for the specified stream associated to an output buffer of a Windows console.

sapi_windows_vt100_support

(PHP 7 >= 7.2.0)

sapi_windows_vt100_support — Get or set VT100 support for the specified stream associated to an output buffer of a Windows console.

Description

sapi_windows_vt100_support ( resource $stream [, bool $enable ] ) : bool

If enable is omitted, the function returns TRUE if the stream stream has VT100 control codes enabled, FALSE otherwise.

If enable is specified, the function will try to enable or disable the VT100 features of the stream stream. If the feature has been successfully enabled (or disabled), the function will return TRUE, or FALSE otherwise.

At startup, PHP tries to enable the VT100 feature of the STDOUT/STDERR streams. By the way, if those streams are redirected to a file, the VT100 features may not be enabled.

If VT100 support is enabled, it is possible to use control sequences as they are known from the VT100 terminal. They allow the modification of the terminal's output. On Windows these sequences are called Console Virtual Terminal Sequences.

Warning

This function uses the ENABLE_VIRTUAL_TERMINAL_PROCESSING flag implemented in the Windows 10 API, so the VT100 feature may not be available on older Windows versions.

Parameters

stream

The stream on which the function will operate.

enable

If specified, the VT100 feature will be enabled (if TRUE) or disabled (if FALSE).

Return Values

If enable is not specified: returns TRUE if the VT100 feature is enabled, FALSE otherwise.

If enable is specified: Returns TRUE on success or FALSE on failure.

Examples

Example #1 sapi_windows_vt100_support() default state

By default, STDOUT and STDERR have the VT100 feature enabled.

php -r "var_export(sapi_windows_vt100_support(STDOUT));echo ' ';var_export(sapi_windows_vt100_support(STDERR));"

The above example will output something similar to:

true true

By the way, if a stream is redirected, the VT100 feature will not be enabled:

php -r "var_export(sapi_windows_vt100_support(STDOUT));echo ' ';var_export(sapi_windows_vt100_support(STDERR));" 2>NUL

The above example will output something similar to:

true false

Example #2 sapi_windows_vt100_support() changing state

You won't be able to enable the VT100 feature of STDOUT or STDERR if the stream is redirected.

php -r "var_export(sapi_windows_vt100_support(STDOUT, true));echo ' ';var_export(sapi_windows_vt100_support(STDERR, true));" 2>NUL

The above example will output something similar to:

true false

Example #3 Example usage of VT100 support enabled

<?php
$out = fopen('php://stdout','w');
fwrite($out, 'Just forgot a lettr.');
// Moves the cursor two characters backwards
fwrite($out, "\033[2D");
// Inserts one blank, shifting existing text to the right -> Just forgot a lett r.
fwrite($out, "\033[1@");
fwrite($out, 'e');
?>

The above example will output:

Just forgot a letter.


Alias of highlight_file

  • « sapi_windows_vt100_support
  • sleep »
  • PHP Manual
  • Misc. Functions
  • Alias of highlight_file

show_source

(PHP 4, PHP 5, PHP 7)

show_source — Alias of highlight_file()

Description

This function is an alias of: highlight_file().


Delay execution

  • « show_source
  • sys_getloadavg »
  • PHP Manual
  • Misc. Functions
  • Delay execution

sleep

(PHP 4, PHP 5, PHP 7)

sleep — Delay execution

Description

sleep ( int $seconds ) : int

Delays the program execution for the given number of seconds.

Parameters

seconds

Halt time in seconds.

Return Values

Returns zero on success, or FALSE on error.

If the call was interrupted by a signal, sleep() returns a non-zero value. On Windows, this value will always be 192 (the value of the WAIT_IO_COMPLETION constant within the Windows API). On other platforms, the return value will be the number of seconds left to sleep.

Errors/Exceptions

If the specified number of seconds is negative, this function will generate a E_WARNING.

Changelog

Version | Description
5.3.4 | Before PHP 5.3.4, on Windows, sleep() always returns NULL when sleep has occurred, regardless of whether the sleep was interrupted or not.

Examples

Example #1 sleep() example

<?php

// current time
echo date('h:i:s') . "\n";

// sleep for 10 seconds
sleep(10);

// wake up !
echo date('h:i:s') . "\n";

?>

This example will output (after 10 seconds)

05:31:23
05:31:33

See Also

  • usleep() - Delay execution in microseconds
  • time_nanosleep() - Delay for a number of seconds and nanoseconds
  • time_sleep_until() - Make the script sleep until the specified time
  • set_time_limit() - Limits the maximum execution time


Gets system load average

  • « sleep
  • time_nanosleep »
  • PHP Manual
  • Misc. Functions
  • Gets system load average

sys_getloadavg

(PHP 5 >= 5.1.3, PHP 7)

sys_getloadavg — Gets system load average

Description

sys_getloadavg ( void ) : array

Returns three samples representing the average system load (the number of processes in the system run queue) over the last 1, 5 and 15 minutes, respectively.

Return Values

Returns an array with three samples (last 1, 5 and 15 minutes).

Examples

Example #1 A sys_getloadavg() example

<?php
$load = sys_getloadavg();
if ($load[0] > 0.80) {
    header('HTTP/1.1 503 Too busy, try again later');
    die('Server too busy. Please try again later.');
}
?>

Notes

Note: This function is not implemented on Windows platforms.


Delay for a number of seconds and nanoseconds

  • « sys_getloadavg
  • time_sleep_until »
  • PHP Manual
  • Misc. Functions
  • Delay for a number of seconds and nanoseconds

time_nanosleep

(PHP 5, PHP 7)

time_nanosleep — Delay for a number of seconds and nanoseconds

Description

time_nanosleep ( int $seconds , int $nanoseconds ) : mixed

Delays program execution for the given number of seconds and nanoseconds.

Parameters

seconds

Must be a non-negative integer.

nanoseconds

Must be a non-negative integer less than 1 billion.

Return Values

Returns TRUE on success or FALSE on failure.

If the delay was interrupted by a signal, an associative array will be returned with the components:

  • seconds - number of seconds remaining in the delay
  • nanoseconds - number of nanoseconds remaining in the delay

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms.

Examples

Example #1 time_nanosleep() example

<?php
// Careful! This won't work as expected if an array is returned
if (time_nanosleep(0, 500000000)) {
    echo "Slept for half a second.\n";
}

// This is better:
if (time_nanosleep(0, 500000000) === true) {
    echo "Slept for half a second.\n";
}

// And this is the best:
$nano = time_nanosleep(2, 100000);

if ($nano === true) {
    echo "Slept for 2 seconds, 100 microseconds.\n";
} elseif ($nano === false) {
    echo "Sleeping failed.\n";
} elseif (is_array($nano)) {
    $seconds = $nano['seconds'];
    $nanoseconds = $nano['nanoseconds'];
    echo "Interrupted by a signal.\n";
    echo "Time remaining: $seconds seconds, $nanoseconds nanoseconds.";
}
?>

See Also

  • sleep() - Delay execution
  • usleep() - Delay execution in microseconds
  • time_sleep_until() - Make the script sleep until the specified time
  • set_time_limit() - Limits the maximum execution time


Make the script sleep until the specified time

  • « time_nanosleep
  • uniqid »
  • PHP Manual
  • Misc. Functions
  • Make the script sleep until the specified time

time_sleep_until

(PHP 5 >= 5.1.0, PHP 7)

time_sleep_until — Make the script sleep until the specified time

Description

time_sleep_until ( float $timestamp ) : bool

Makes the script sleep until the specified timestamp.

Parameters

timestamp

The timestamp when the script should wake.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms.

Errors/Exceptions

If the specified timestamp is in the past, this function will generate a E_WARNING.

Examples

Example #1 A time_sleep_until() example

<?php

//returns false and generates a warning
var_dump(time_sleep_until(time()-1));

// may only work on faster computers, will sleep up to 0.2 seconds
var_dump(time_sleep_until(microtime(true)+0.2));

?>

Notes

Note: All signals will be delivered after the script wakes up.

See Also

  • sleep() - Delay execution
  • usleep() - Delay execution in microseconds
  • time_nanosleep() - Delay for a number of seconds and nanoseconds
  • set_time_limit() - Limits the maximum execution time


Generate a unique ID

  • « time_sleep_until
  • unpack »
  • PHP Manual
  • Misc. Functions
  • Generate a unique ID

uniqid

(PHP 4, PHP 5, PHP 7)

uniqid — Generate a unique ID

Description

uniqid ([ string $prefix = "" [, bool $more_entropy = FALSE ]] ) : string

Gets a prefixed unique identifier based on the current time in microseconds.

Caution

This function does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using random_int(), random_bytes(), or openssl_random_pseudo_bytes() instead.

Warning

This function does not guarantee uniqueness of return value. Since most systems adjust system clock by NTP or like, system time is changed constantly. Therefore, it is possible that this function does not return unique ID for the process/thread. Use more_entropy to increase likelihood of uniqueness.

Parameters

prefix

Can be useful, for instance, if you generate identifiers simultaneously on several hosts that might happen to generate the identifier at the same microsecond.

With an empty prefix, the returned string will be 13 characters long. If more_entropy is TRUE, it will be 23 characters.

more_entropy

If set to TRUE, uniqid() will add additional entropy (using the combined linear congruential generator) at the end of the return value, which increases the likelihood that the result will be unique.

Return Values

Returns timestamp based unique identifier as a string.

Warning

This function tries to create unique identifier, but it does not guarantee 100% uniqueness of return value.

Examples

Example #1 uniqid() Example

<?php
/* A uniqid, like: 4b3403665fea6 */
printf("uniqid(): %s\r\n", uniqid());

/* We can also prefix the uniqid, this the same as
 * doing:
 *
 * $uniqid = $prefix . uniqid();
 * $uniqid = uniqid($prefix);
 */
printf("uniqid('php_'): %s\r\n", uniqid('php_'));

/* We can also activate the more_entropy parameter, which is
 * required on some systems, like Cygwin. This makes uniqid()
 * produce a value like: 4b340550242239.64159797
 */
printf("uniqid('', true): %s\r\n", uniqid('', true));
?>

Notes

Note:

Under Cygwin, the more_entropy must be set to TRUE for this function to work.


Unpack data from binary string

  • « uniqid
  • usleep »
  • PHP Manual
  • Misc. Functions
  • Unpack data from binary string

unpack

(PHP 4, PHP 5, PHP 7)

unpack — Unpack data from binary string

Description

unpack ( string $format , string $data [, int $offset = 0 ] ) : array

Unpacks from a binary string into an array according to the given format.

The unpacked data is stored in an associative array. To accomplish this you have to name the different format codes and separate them by a slash /. If a repeater argument is present, then each of the array keys will have a sequence number behind the given name.

Parameters

format

See pack() for an explanation of the format codes.

data

The packed data.

offset

The offset to begin unpacking from.

Return Values

Returns an associative array containing unpacked elements of binary string.

Changelog

Version | Description
7.2.0 | float and double types supports both Big Endian and Little Endian.
7.1.0 | The optional offset has been added.
5.5.0 | Changes were made to bring this function into line with Perl: The "a" code now retains trailing NULL bytes. The "A" code now strips all trailing ASCII whitespace (spaces, tabs, newlines, carriage returns, and NULL bytes). The "Z" code was added for NULL-padded strings, and removes trailing NULL bytes.

Examples

Example #1 unpack() example

<?php
$binarydata = "\x04\x00\xa0\x00";
$array = unpack("cchars/nint", $binarydata);
print_r($array);
?>

The above example will output:

Array
(
    [chars] => 4
    [int] => 160
)

Example #2 unpack() example with a repeater

<?php
$binarydata = "\x04\x00\xa0\x00";
$array = unpack("c2chars/nint", $binarydata);
print_r($array);
?>

The above example will output:

Array
(
    [chars1] => 4
    [chars2] => 0
    [int] => 40960
)

Notes

Caution

Note that PHP internally stores integral values as signed. If you unpack a large unsigned long and it is of the same size as PHP internally stored values the result will be a negative number even though unsigned unpacking was specified.

Caution

If you do not name an element, numeric indices starting from 1 are used. Be aware that if you have more than one unnamed element, some data is overwritten because the numbering restarts from 1 for each element.

Example #3 unpack() example with unnamed keys

<?php
$binarydata = "\x32\x42\x00\xa0";
$array = unpack("c2/n", $binarydata);
var_dump($array);
?>

The above example will output:

array(2) {
  [1]=>
  int(160)
  [2]=>
  int(66)
}

Note that the first value from the c specifier is overwritten by the first value from the n specifier.

See Also

  • pack() - Pack data into binary string


Delay execution in microseconds

  • « unpack
  • Changelog »
  • PHP Manual
  • Misc. Functions
  • Delay execution in microseconds

usleep

(PHP 4, PHP 5, PHP 7)

usleep — Delay execution in microseconds

Description

usleep ( int $micro_seconds ) : void

Delays program execution for the given number of microseconds.

Parameters

micro_seconds

Halt time in microseconds. A microsecond is one millionth of a second.

Return Values

No value is returned.

Examples

Example #1 usleep() example

<?php

// Current time
echo date('h:i:s') . "\n";

// wait for 2 seconds
usleep(2000000);

// back!
echo date('h:i:s') . "\n";

?>

The above example will output:

11:13:28
11:13:30

See Also

  • sleep() - Delay execution
  • time_nanosleep() - Delay for a number of seconds and nanoseconds
  • time_sleep_until() - Make the script sleep until the specified time
  • set_time_limit() - Limits the maximum execution time


Changelog

The following changes have been made to classes/functions/methods of this extension.

Version | Function | Description
7.3.0 | define | case_insensitive has been deprecated and will be removed in version 8.0.0.
7.2.0 | pack | float and double types supports both Big Endian and Little Endian.
 | unpack | float and double types supports both Big Endian and Little Endian.
7.1.0 | unpack | The optional offset has been added.
7.0.15,7.1.1 | pack | The "e", "E", "g" and "G" codes were added to enable byte order support for float and double.
7.0.0 | define | array values are allowed.
5.6.3 | pack | The "q", "Q", "J" and "P" codes were added to enable working with 64-bit numbers.
5.5.0 | pack | The "Z" code was added with equivalent functionality to "a" for Perl compatibility.
 | unpack | Changes were made to bring this function into line with Perl: The "a" code now retains trailing NULL bytes. The "A" code now strips all trailing ASCII whitespace (spaces, tabs, newlines, carriage returns, and NULL bytes). The "Z" code was added for NULL-padded strings, and removes trailing NULL bytes.
5.3.4 | sleep | Before PHP 5.3.4, on Windows, sleep always returns NULL when sleep has occurred, regardless of whether the sleep was interrupted or not.
5.3.0 | time_nanosleep | This function is now available on Windows platforms.
 | time_sleep_until | This function is now available on Windows platforms.
5.0.5 | php_check_syntax | This function was removed from PHP.
5.0.3 | php_check_syntax | Calling exit after php_check_syntax resulted in a Segfault.
5.0.1 | php_check_syntax | error_message is passed by reference.


Parsekit

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Parsekit Functions
    • parsekit_compile_file — Compile a PHP file and return the resulting op array
    • parsekit_compile_string — Compile a string of PHP code and return the resulting op array
    • parsekit_func_arginfo — Return information regarding function argument(s)


Introduction

These functions allow runtime analysis of opcodes compiled from PHP scripts.


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/parsekit.

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.

PARSEKIT_QUIET (int)
Return full detail, but without unnecessary NULL entries.
PARSEKIT_SIMPLE (int)
Return shorthand opcode notation.
PARSEKIT_EXTENDED_VALUE (int)
Opnode Flag
PARSEKIT_RESULT_CONST (int)
Opnode Flag
PARSEKIT_RESULT_EA_TYPE (int)
Opnode Flag
PARSEKIT_RESULT_JMP_ADDR (int)
Opnode Flag
PARSEKIT_RESULT_OPARRAY (int)
Opnode Flag
PARSEKIT_RESULT_OPLINE (int)
Opnode Flag
PARSEKIT_RESULT_VAR (int)
Opnode Flag
PARSEKIT_USAGE_UNKNOWN (int)
Opnode Flag
PARSEKIT_ZEND_INTERNAL_CLASS (int)
Class Type
PARSEKIT_ZEND_USER_CLASS (int)
Class Type
PARSEKIT_ZEND_EVAL_CODE (int)
Function Type
PARSEKIT_ZEND_INTERNAL_FUNCTION (int)
Function Type
PARSEKIT_ZEND_OVERLOADED_FUNCTION (int)
Function Type
PARSEKIT_ZEND_OVERLOADED_FUNCTION_TEMPORARY (int) PHP >= 5.0.0
Function Type
PARSEKIT_ZEND_USER_FUNCTION (int)
Function Type
PARSEKIT_IS_CONST (int)
Node Type
PARSEKIT_IS_TMP_VAR (int)
Node Type
PARSEKIT_IS_UNUSED (int)
Node Type
PARSEKIT_IS_VAR (int)
Node Type
PARSEKIT_ZEND_ADD (int)
Opcode
PARSEKIT_ZEND_ADD_ARRAY_ELEMENT (int)
Opcode
PARSEKIT_ZEND_ADD_CHAR (int)
Opcode
PARSEKIT_ZEND_ADD_INTERFACE (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_ADD_STRING (int)
Opcode
PARSEKIT_ZEND_ADD_VAR (int)
Opcode
PARSEKIT_ZEND_ASSIGN (int)
Opcode
PARSEKIT_ZEND_ASSIGN_ADD (int)
Opcode
PARSEKIT_ZEND_ASSIGN_BW_AND (int)
Opcode
PARSEKIT_ZEND_ASSIGN_BW_OR (int)
Opcode
PARSEKIT_ZEND_ASSIGN_BW_XOR (int)
Opcode
PARSEKIT_ZEND_ASSIGN_CONCAT (int)
Opcode
PARSEKIT_ZEND_ASSIGN_DIM (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_ASSIGN_DIV (int)
Opcode
PARSEKIT_ZEND_ASSIGN_MOD (int)
Opcode
PARSEKIT_ZEND_ASSIGN_MUL (int)
Opcode
PARSEKIT_ZEND_ASSIGN_OBJ (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_ASSIGN_REF (int)
Opcode
PARSEKIT_ZEND_ASSIGN_SL (int)
Opcode
PARSEKIT_ZEND_ASSIGN_SR (int)
Opcode
PARSEKIT_ZEND_ASSIGN_SUB (int)
Opcode
PARSEKIT_ZEND_BEGIN_SILENCE (int)
Opcode
PARSEKIT_ZEND_BOOL (int)
Opcode
PARSEKIT_ZEND_BOOL_NOT (int)
Opcode
PARSEKIT_ZEND_BOOL_XOR (int)
Opcode
PARSEKIT_ZEND_BRK (int)
Opcode
PARSEKIT_ZEND_BW_AND (int)
Opcode
PARSEKIT_ZEND_BW_NOT (int)
Opcode
PARSEKIT_ZEND_BW_OR (int)
Opcode
PARSEKIT_ZEND_BW_XOR (int)
Opcode
PARSEKIT_ZEND_CASE (int)
Opcode
PARSEKIT_ZEND_CAST (int)
Opcode
PARSEKIT_ZEND_CATCH (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_CLONE (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_CONCAT (int)
Opcode
PARSEKIT_ZEND_CONT (int)
Opcode
PARSEKIT_ZEND_DECLARE_CLASS (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_DECLARE_FUNCTION (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_DECLARE_INHERITED_CLASS (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_DIV (int)
Opcode
PARSEKIT_ZEND_DO_FCALL (int)
Opcode
PARSEKIT_ZEND_DO_FCALL_BY_NAME (int)
Opcode
PARSEKIT_ZEND_ECHO (int)
Opcode
PARSEKIT_ZEND_END_SILENCE (int)
Opcode
PARSEKIT_ZEND_EXIT (int)
Opcode
PARSEKIT_ZEND_EXT_FCALL_BEGIN (int)
Opcode
PARSEKIT_ZEND_EXT_FCALL_END (int)
Opcode
PARSEKIT_ZEND_EXT_NOP (int)
Opcode
PARSEKIT_ZEND_EXT_STMT (int)
Opcode
PARSEKIT_ZEND_FETCH_CLASS (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_FETCH_CONSTANT (int)
Opcode
PARSEKIT_ZEND_FETCH_DIM_FUNC_ARG (int)
Opcode
PARSEKIT_ZEND_FETCH_DIM_IS (int)
Opcode
PARSEKIT_ZEND_FETCH_DIM_R (int)
Opcode
PARSEKIT_ZEND_FETCH_DIM_RW (int)
Opcode
PARSEKIT_ZEND_FETCH_DIM_TMP_VAR (int)
Opcode
PARSEKIT_ZEND_FETCH_DIM_UNSET (int)
Opcode
PARSEKIT_ZEND_FETCH_DIM_W (int)
Opcode
PARSEKIT_ZEND_FETCH_FUNC_ARG (int)
Opcode
PARSEKIT_ZEND_FETCH_IS (int)
Opcode
PARSEKIT_ZEND_FETCH_OBJ_FUNC_ARG (int)
Opcode
PARSEKIT_ZEND_FETCH_OBJ_IS (int)
Opcode
PARSEKIT_ZEND_FETCH_OBJ_R (int)
Opcode
PARSEKIT_ZEND_FETCH_OBJ_RW (int)
Opcode
PARSEKIT_ZEND_FETCH_OBJ_UNSET (int)
Opcode
PARSEKIT_ZEND_FETCH_OBJ_W (int)
Opcode
PARSEKIT_ZEND_FETCH_R (int)
Opcode
PARSEKIT_ZEND_FETCH_RW (int)
Opcode
PARSEKIT_ZEND_FETCH_UNSET (int)
Opcode
PARSEKIT_ZEND_FETCH_W (int)
Opcode
PARSEKIT_ZEND_FE_FETCH (int)
Opcode
PARSEKIT_ZEND_FE_RESET (int)
Opcode
PARSEKIT_ZEND_FREE (int)
Opcode
PARSEKIT_ZEND_HANDLE_EXCEPTION (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_IMPORT_CLASS (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_IMPORT_CONST (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_IMPORT_FUNCTION (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_INCLUDE_OR_EVAL (int)
Opcode
PARSEKIT_ZEND_INIT_ARRAY (int)
Opcode
PARSEKIT_ZEND_INIT_CTOR_CALL (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_INIT_FCALL_BY_NAME (int)
Opcode
PARSEKIT_ZEND_INIT_METHOD_CALL (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_INIT_STATIC_METHOD_CALL (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_INIT_STRING (int)
Opcode
PARSEKIT_ZEND_INSTANCEOF (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_ISSET_ISEMPTY (int) PHP < 5.0.0
Opcode
PARSEKIT_ZEND_ISSET_ISEMPTY_DIM_OBJ (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_ISSET_ISEMPTY_PROP_OBJ (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_ISSET_ISEMPTY_VAR (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_IS_EQUAL (int)
Opcode
PARSEKIT_ZEND_IS_IDENTICAL (int)
Opcode
PARSEKIT_ZEND_IS_NOT_EQUAL (int)
Opcode
PARSEKIT_ZEND_IS_NOT_IDENTICAL (int)
Opcode
PARSEKIT_ZEND_IS_SMALLER (int)
Opcode
PARSEKIT_ZEND_IS_SMALLER_OR_EQUAL (int)
Opcode
PARSEKIT_ZEND_JMP (int)
Opcode
PARSEKIT_ZEND_JMPNZ (int)
Opcode
PARSEKIT_ZEND_JMPNZ_EX (int)
Opcode
PARSEKIT_ZEND_JMPZ (int)
Opcode
PARSEKIT_ZEND_JMPZNZ (int)
Opcode
PARSEKIT_ZEND_JMPZ_EX (int)
Opcode
PARSEKIT_ZEND_JMP_NO_CTOR (int)
Opcode
PARSEKIT_ZEND_MOD (int)
Opcode
PARSEKIT_ZEND_MUL (int)
Opcode
PARSEKIT_ZEND_NEW (int)
Opcode
PARSEKIT_ZEND_NOP (int)
Opcode
PARSEKIT_ZEND_OP_DATA (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_POST_DEC (int)
Opcode
PARSEKIT_ZEND_POST_DEC_OBJ (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_POST_INC (int)
Opcode
PARSEKIT_ZEND_POST_INC_OBJ (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_PRE_DEC (int)
Opcode
PARSEKIT_ZEND_PRE_DEC_OBJ (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_PRE_INC (int)
Opcode
PARSEKIT_ZEND_PRE_INC_OBJ (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_PRINT (int)
Opcode
PARSEKIT_ZEND_QM_ASSIGN (int)
Opcode
PARSEKIT_ZEND_RAISE_ABSTRACT_ERROR (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_RECV (int)
Opcode
PARSEKIT_ZEND_RECV_INIT (int)
Opcode
PARSEKIT_ZEND_RETURN (int)
Opcode
PARSEKIT_ZEND_SEND_REF (int)
Opcode
PARSEKIT_ZEND_SEND_VAL (int)
Opcode
PARSEKIT_ZEND_SEND_VAR (int)
Opcode
PARSEKIT_ZEND_SEND_VAR_NO_REF (int)
Opcode
PARSEKIT_ZEND_SL (int)
Opcode
PARSEKIT_ZEND_SR (int)
Opcode
PARSEKIT_ZEND_SUB (int)
Opcode
PARSEKIT_ZEND_SWITCH_FREE (int)
Opcode
PARSEKIT_ZEND_THROW (int) PHP >= 5.0.0
Opcode
PARSEKIT_ZEND_TICKS (int)
Opcode
PARSEKIT_ZEND_UNSET_DIM_OBJ (int)
Opcode
PARSEKIT_ZEND_UNSET_VAR (int)
Opcode
PARSEKIT_ZEND_VERIFY_ABSTRACT_CLASS (int) PHP >= 5.0.0
Opcode


Parsekit Functions

Table of Contents

  • parsekit_compile_file — Compile a PHP file and return the resulting op array
  • parsekit_compile_string — Compile a string of PHP code and return the resulting op array
  • parsekit_func_arginfo — Return information regarding function argument(s)


Compile a PHP file and return the resulting op array

  • « Parsekit Functions
  • parsekit_compile_string »
  • PHP Manual
  • Parsekit Functions
  • Compile a PHP file and return the resulting op array

parsekit_compile_file

(PECL parsekit >= 0.2.0)

parsekit_compile_file — Compile a PHP file and return the resulting op array

Description

parsekit_compile_file ( string $filename [, array &$errors [, int $options = PARSEKIT_QUIET ]] ) : array
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.

Parameters

filename

A string containing the name of the file to compile. Similar to the argument to include.

errors

A 2D hash of errors (including fatal errors) encountered during compilation. Returned by reference.

options

One of either PARSEKIT_QUIET or PARSEKIT_SIMPLE. To produce varying degrees of verbosity in the returned output.

Return Values

Returns a complex multi-layer array structure as detailed below.

Examples

Example #1 parsekit_compile_file() example

<?php
var_dump(parsekit_compile_file('hello_world.php', $errors, PARSEKIT_SIMPLE));
?>

The above example will output:

array(5) {
  [0]=>
  string(37) "ZEND_ECHO UNUSED 'Hello World' UNUSED"
  [1]=>
  string(30) "ZEND_RETURN UNUSED NULL UNUSED"
  [2]=>
  string(42) "ZEND_HANDLE_EXCEPTION UNUSED UNUSED UNUSED"
  ["function_table"]=>
  NULL
  ["class_table"]=>
  NULL
}

See Also

  • parsekit_compile_string() - Compile a string of PHP code and return the resulting op array


Compile a string of PHP code and return the resulting op array

  • « parsekit_compile_file
  • parsekit_func_arginfo »
  • PHP Manual
  • Parsekit Functions
  • Compile a string of PHP code and return the resulting op array

parsekit_compile_string

(PECL parsekit >= 0.2.0)

parsekit_compile_string — Compile a string of PHP code and return the resulting op array

Description

parsekit_compile_string ( string $phpcode [, array &$errors [, int $options = PARSEKIT_QUIET ]] ) : array
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.

Parameters

phpcode

A string containing phpcode. Similar to the argument to eval().

errors

A 2D hash of errors (including fatal errors) encountered during compilation. Returned by reference.

options

One of either PARSEKIT_QUIET or PARSEKIT_SIMPLE. To produce varying degrees of verbosity in the returned output.

Return Values

Returns a complex multi-layer array structure as detailed below.

Examples

Example #1 parsekit_compile_string() example

<?php
  $ops = parsekit_compile_string('
echo "Foo\n";
', $errors, PARSEKIT_QUIET);

  var_dump($ops);
?>

The above example will output:

array(20) {
  ["type"]=>
  int(4)
  ["type_name"]=>
  string(14) "ZEND_EVAL_CODE"
  ["fn_flags"]=>
  int(0)
  ["num_args"]=>
  int(0)
  ["required_num_args"]=>
  int(0)
  ["pass_rest_by_reference"]=>
  bool(false)
  ["uses_this"]=>
  bool(false)
  ["line_start"]=>
  int(0)
  ["line_end"]=>
  int(0)
  ["return_reference"]=>
  bool(false)
  ["refcount"]=>
  int(1)
  ["last"]=>
  int(3)
  ["size"]=>
  int(3)
  ["T"]=>
  int(0)
  ["last_brk_cont"]=>
  int(0)
  ["current_brk_cont"]=>
  int(-1)
  ["backpatch_count"]=>
  int(0)
  ["done_pass_two"]=>
  bool(true)
  ["filename"]=>
  string(17) "Parsekit Compiler"
  ["opcodes"]=>
  array(3) {
    [8594800]=>
    array(5) {
      ["opcode"]=>
      int(40)
      ["opcode_name"]=>
      string(9) "ZEND_ECHO"
      ["flags"]=>
      int(768)
      ["op1"]=>
      array(3) {
        ["type"]=>
        int(1)
        ["type_name"]=>
        string(8) "IS_CONST"
        ["constant"]=>
        &string(4) "Foo
"
      }
      ["lineno"]=>
      int(2)
    }
    ["859484C"]=>
    array(6) {
      ["opcode"]=>
      int(62)
      ["opcode_name"]=>
      string(11) "ZEND_RETURN"
      ["flags"]=>
      int(16777984)
      ["op1"]=>
      array(3) {
        ["type"]=>
        int(1)
        ["type_name"]=>
        string(8) "IS_CONST"
        ["constant"]=>
        &NULL
      }
      ["extended_value"]=>
      int(0)
      ["lineno"]=>
      int(3)
    }
    [8594898]=>
    array(4) {
      ["opcode"]=>
      int(149)
      ["opcode_name"]=>
      string(21) "ZEND_HANDLE_EXCEPTION"
      ["flags"]=>
      int(0)
      ["lineno"]=>
      int(3)
    }
  }
}

See Also

  • parsekit_compile_file() - Compile a PHP file and return the resulting op array


Return information regarding function argument(s)

  • « parsekit_compile_string
  • Seaslog »
  • PHP Manual
  • Parsekit Functions
  • Return information regarding function argument(s)

parsekit_func_arginfo

(PECL parsekit >= 0.3.0)

parsekit_func_arginfo — Return information regarding function argument(s)

Description

parsekit_func_arginfo ( mixed $function ) : array
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.

Parameters

function

A string describing a function, or an array describing a class/method.

Return Values

Returns an array containing argument information.

Examples

Example #1 parsekit_func_arginfo() example

<?php
function foo($bar, stdClass $baz, &$bomb, $bling = false) {
}

var_dump(parsekit_func_arginfo('foo'));
?>

The above example will output:

array(4) {
  [0]=>
  array(3) {
    ["name"]=>
    string(3) "bar"
    ["allow_null"]=>
    bool(true)
    ["pass_by_reference"]=>
    bool(false)
  }
  [1]=>
  array(4) {
    ["name"]=>
    string(3) "baz"
    ["class_name"]=>
    string(8) "stdClass"
    ["allow_null"]=>
    bool(false)
    ["pass_by_reference"]=>
    bool(false)
  }
  [2]=>
  array(3) {
    ["name"]=>
    string(4) "bomb"
    ["allow_null"]=>
    bool(true)
    ["pass_by_reference"]=>
    bool(true)
  }
  [3]=>
  array(3) {
    ["name"]=>
    string(5) "bling"
    ["allow_null"]=>
    bool(true)
    ["pass_by_reference"]=>
    bool(false)
  }
}


Seaslog

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Seaslog Functions
    • seaslog_get_author — Get SeasLog author.
    • seaslog_get_version — Get SeasLog version.
  • SeasLog — The SeasLog class
    • SeasLog::alert — Record alert log information
    • SeasLog::analyzerCount — Get log count by level, log_path and key_word
    • SeasLog::analyzerDetail — Get log detail by level, log_path, key_word, start, limit, order
    • SeasLog::closeLoggerStream — Manually release stream flow from logger
    • SeasLog::__construct — Description
    • SeasLog::critical — Record critical log information
    • SeasLog::debug — Record debug log information
    • SeasLog::__destruct — Description
    • SeasLog::emergency — Record emergency log information
    • SeasLog::error — Record error log information
    • SeasLog::flushBuffer — Flush logs buffer, dump to appender file, or send to remote api with tcp/udp
    • SeasLog::getBasePath — Get SeasLog base path.
    • SeasLog::getBuffer — Get the logs buffer in memory as array
    • SeasLog::getBufferEnabled — Determin if buffer enabled
    • SeasLog::getDatetimeFormat — Get SeasLog datetime format style
    • SeasLog::getLastLogger — Get SeasLog last logger path
    • SeasLog::getRequestID — Get SeasLog request_id differentiated requests
    • SeasLog::getRequestVariable — Get SeasLog request variable
    • SeasLog::info — Record info log information
    • SeasLog::log — The Common Record Log Function
    • SeasLog::notice — Record notice log information
    • SeasLog::setBasePath — Set SeasLog base path
    • SeasLog::setDatetimeFormat — Set SeasLog datetime format style
    • SeasLog::setLogger — Set SeasLog logger name
    • SeasLog::setRequestID — Set SeasLog request_id differentiated requests
    • SeasLog::setRequestVariable — Manually set SeasLog request variable
    • SeasLog::warning — Record warning log information


Introduction

The Seaslog is an effective,fast,stable log extension for PHP.

SeasLog requires PHP 5.2.0 or greater. Earlier versions may not work.

The log journal，which is usually the operate record of the system， software and the application record. Through the analysis of the log，it can facilitate users to understand the operation of the system， software and the application situation. If your application log is rich enough, it can also analyze the previous use’s operation behavior,type, regional distribution or other more information. The application log also points the multiple levels at the same time, you can easily get the application analysis of health status, timely find problems and quick positioning, and solve the problem, remedy the loss.

The error_log, syslog function which built in PHP is powerful and excellent performance, but due to various defects (error_log have no error level, no fixed format, syslog regardless of module, and mix with system log ), reducing a lot of flexibility , and can't meet the application requirements.

The good news is that there are a number of third-party log class library established to make up for the defects, such as log4php, plog, monolog (of course, there are many applications in the project development of the log class).

So is there a log of libraries meet the following requirements：

  • Modules, classification
  • Simple configuration(preferably without configuration)
  • Clear log format and easy understanding
  • Simple application and well performance
Seaslog just meet these demands.

What is provided at present:

  • In the PHP project, record the log specification and repidly.
  • Configure the default log directory and module
  • Specified log directory and capture current configuration
  • Preliminary analysis of the early warning framework
  • Efficient log buffer and convenient buffer debug
  • Follow the PSR-3 log interface specification
  • Automatically record error information
  • Automatically record abnormal information
  • Support Connect the TCP port, send with RFC5424
  • Support Connect the UDP port, send with RFC5424
  • Support RequestId differentiated requests
  • Support for log template customizations

Read More » SeasLog Document at Github.


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/seaslog


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Seaslog Configure Options
Name | Default | Changeable | Changelog
seaslog.appender | 1 | PHP_INI_SYSTEM |
seaslog.appender_retry | 0 | PHP_INI_ALL |
seaslog.level | 8 | PHP_INI_ALL |
seaslog.remote_host | 127.0.0.1 | PHP_INI_ALL |
seaslog.remote_port | 514 | PHP_INI_ALL |
seaslog.remote_timeout | 1 | PHP_INI_SYSTEM |
seaslog.default_basepath | /var/log/www | PHP_INI_SYSTEM |
seaslog.default_logger | default | PHP_INI_SYSTEM |
seaslog.default_template | %T | %L | %P | %Q | %t | %M | PHP_INI_SYSTEM |
seaslog.default_datetime_format | Y-m-d H:i:s | PHP_INI_SYSTEM |
seaslog.trace_error | 1 | PHP_INI_ALL |
seaslog.trace_exception | 0 | PHP_INI_SYSTEM |
seaslog.trace_notice | 0 | PHP_INI_ALL |
seaslog.trace_warning | 0 | PHP_INI_ALL |
seaslog.use_buffer | 0 | PHP_INI_SYSTEM |
seaslog.buffer_size | 0 | PHP_INI_ALL |
seaslog.buffer_disabled_in_cli | 0 | PHP_INI_SYSTEM |
seaslog.disting_type | 0 | PHP_INI_SYSTEM |
seaslog.disting_folder | 1 | PHP_INI_SYSTEM |
seaslog.disting_by_hour | 0 | PHP_INI_SYSTEM |
seaslog.recall_depth | 0 | PHP_INI_ALL |
seaslog.trim_wrap | 0 | PHP_INI_ALL |
seaslog.ignore_warning | 1 | PHP_INI_ALL |
seaslog.throw_exception | 1 | PHP_INI_ALL |

Here's a short explanation of the configuration directives.

seaslog.appender integer

Switch the Record Log Data Store. 1File 2TCP 3UDP (Switch default 1)

SeasLog will send log to tcp://remote_host:remote_port or udp://remote_host:remote_port server, when seaslog.appender configured to `2 (TCP)` or `3 (UDP)`.

When SeasLog send log to TCP/UDP，style follow RFC5424. The `{logInfo}` affected by seaslog.default_template.

The log style finally formatted such as:
<15>1 2017-08-27T01:24:59+08:00 vagrant-ubuntu-trusty test/logger[27171]: 2016-06-25 00:59:43 | DEBUG | 21423 | 599157af4e937 | 1466787583.322 | this is a neeke debug
<14>1 2017-08-27T01:24:59+08:00 vagrant-ubuntu-trusty test/logger[27171]: 2016-06-25 00:59:43 | INFO | 21423 | 599157af4e937 | 1466787583.323 | this is a info log
<13>1 2017-08-27T01:24:59+08:00 vagrant-ubuntu-trusty test/logger[27171]: 2016-06-25 00:59:43 | NOTICE | 21423 | 599157af4e937 | 1466787583.324 | this is a notice log
seaslog.appender_retry integer

Record Log Retry Count. Default 0 (Do Not Retry)

seaslog.buffer_disabled_in_cli integer

Disable buffer in cli. 1-Y 0-N(Default)

Switch the configure buffer_disabled_in_cli on. The buffer_disabled_in_cli switch default off. If switch buffer_disabled_in_cli on, and running in cli, seaslog.use_buffer setting will be discarded, Seaslog write to the Data Store IMMEDIATELY.

seaslog.buffer_size integer

Configure the buffer_size with 100. The buffer_size default 0, it’s meaning don’t use buffer. If buffer_size > 0,SeasLog will rewritten down into the Data Store when the prerecorded log in memory count >= this buffer_size,and then refresh the memory poll.

seaslog.default_basepath string

Default Log Base Path. Defult "/var/log/www".

seaslog.default_datetime_format string

The DateTime Style. Default "Y-m-d H:i:s".

seaslog.default_logger string

Default Logger Path. Default "default".

seaslog.disting_by_hour integer

Switch use the logger with hour. 1-Y 0-N(Default)

Note:

seaslog.disting_by_hour = 1 Switch use Logger DisTing by hour. It’s meaning SeasLog will create the file each one hour.

seaslog.disting_folder integer

Switch use the logger with folder. 1-Y(Default) 0-N

Note:

seaslog.disting_folder = 1 Switch use Logger DisTing by folder, it’s meaning SeasLog will create the file deistic by folder, and when this configure close SeasLog will create file use underline connect Logger and Time like default_20180211.log.

seaslog.disting_type integer

Switch use the logger with type. 1-Y 0-N(Default)

Note:

seaslog.disting_type = 1 Switch use Logger DisTing by type, it’s meaning SeasLog will create the file deistic info\warn\error and the other type.

seaslog.ignore_warning integer

Switch ignore SeasLog warning. 1-On(Default) 0-Off

Note:

seaslog.ignore_warning = 1 Open a warning to ignore SeasLog itself. When directory permissions or receive server ports are blocked, they are ignored; when closed, a warning is thrown.

seaslog.level integer

Record logger level. Default 8 (All of them). 0-EMERGENCY 1-ALERT 2-CRITICAL 3-ERROR 4-WARNING 5-NOTICE 6-INFO 7-DEBUG 8-ALL

Note:

Tips: The configuration item has changed since the 1.7.0 version. Before the 1.7.0 version, the smaller the value, the more logs are taken according to the level: 0-all 1-debug 2-info 3-notice 4-warning 5-error 6-critical 7-alert 8-emergency Before the 1.7.0 version, Default 0 (All of them).

seaslog.recall_depth integer

Log function recall depth.Will affected variable `LineNo` in `%F`. Default 0

seaslog.remote_host string

If you use Record TCP or UDP, configure this remote ip. Default "127.0.0.1"

seaslog.remote_port integer

If you use Record TCP or UDP, configure this remote port. Default 514

seaslog.remote_timeout integer

If you use Record TCP or UDP, configure this remote timeout. Default 1 second

seaslog.throw_exception integer

Switch throw SeasLog exception. 1-On(Default) 0-Off

Note:

seaslog.throw_exception = 1 Open an exception that throws the SeasLog to throw itself. When the directory authority or the receive server port is blocked, throw an exception; do not throw an exception when closed.

seaslog.trace_error integer

Automatic Record final error with default logger. 1-Y(Default) 0-N

seaslog.trace_exception integer

Automatic Record exception with default logger. 1-Y 0-N(Default)

seaslog.trace_notice integer

Automatic Record notice with default logger. 1-Y 0-N(Default)

seaslog.trace_warning integer

Automatic Record warning with default logger. 1-Y 0-N(Default)

seaslog.trim_wrap integer

Trim the \n and \r in log message. 1-On 0-Off(Default)

seaslog.use_buffer integer

Switch use the log buffer with memory. 1-Y 0-N(Default)

Note:

seaslog.use_buffer = 1 Switch the configure use_buffer on. The use_buffer switch default off. If switch use_buffer on, SeasLog prerecord the log with memory, and them would be rewritten down into the Data Store by request shutdown or php process exit (PHP RSHUTDOWN or PHP MSHUTDOWN).

seaslog.default_template string

Default Log template. Default "%T | %L | %P | %Q | %t | %M".

Note:

`SeasLog`The following default variables are provided, which can be used directly in the log template and replaced as a corresponding value when the log is eventually generated.

Default log template is:`seaslog.default_template = "%T | %L | %P | %Q | %t | %M"`, that's mean,default log style is:`{dateTime} | {level} | {pid} | {uniqid} | {timeStamp} | {logInfo}`

If you custom log template, such as:`seaslog.default_template = "[%T]:%L %P %Q %t %M" `, that's will mean,log style was custom as:`[{dateTime}]:{level} {pid} {uniqid} {timeStamp} {logInfo}`

Seaslog Default Variable Table
Variable Name | Description
%L | Level.
%M | Message.
%T | DateTime. Such as`2017-08-16 19:15:02`,affected by `seaslog.default_datetime_format`.
%t | Timestamp. Such as`1502882102.862`,accurate to milliseconds.
%Q | RequestId. To distinguish a single request, such as not invoking the `SeasLog::setRequestId($string)` function, the unique value generated by the built-in `static char *get_uniqid ()` function is used when the request is initialized.
%H | HostName.
%P | ProcessId.
%D | Domain:Port. Such as`www.cloudwise.com:80`; When Cli, Such as `cli`.
%R | Request URI. Such as`/app/user/signin`; When Cli it's the index script, Such as `CliIndex.php`.
%m | Request Method. Such as`Get`; When Cli it's the command script, Such as `/bin/bash`.
%I | Client IP; When Cli it's `local`. Priority value: HTTP_X_REAL_IP > HTTP_X_FORWARDED_FOR > REMOTE_ADDR
%F | FileName:LineNo. Such as `UserService.php:118`.
%U | MemoryUsage. byte. Call `zend_memory_usage`.
%u | PeakMemoryUsage. byte. Call `zend_memory_peak_usage`.
%C | `TODO` Class::Action. Such as `UserService::getUserInfo`


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.

SEASLOG_VERSION (string)
SEASLOG_AUTHOR (string)
SEASLOG_ALL (string)
"ALL"
SEASLOG_DEBUG (string)
"DEBUG" - Detailed debug information.Fine-grained information events.
SEASLOG_INFO (string)
"INFO" - Interesting events.Emphasizes the running process of the application.
SEASLOG_NOTICE (string)
"NOTICE" - Normal but significant events.Information that is more important than the INFO level during execution.
SEASLOG_WARNING (string)
"WARNING" - Exceptional occurrences that are not errors.Potentially aberrant information that needs attention and needs to be repaired.
SEASLOG_ERROR (string)
"ERROR" - Runtime errors that do not require immediate action but should typically.
SEASLOG_CRITICAL (string)
"CRITICAL" - Critical conditions.Need to be repaired immediately, and the program component is unavailable.
SEASLOG_ALERT (string)
"ALERT" - Action must be taken immediately.Immediate attention should be given to relevant personnel for emergency repairs.
SEASLOG_EMERGENCY (string)
"EMERGENCY" - System is unusable.
SEASLOG_DETAIL_ORDER_ASC (integer)
1
SEASLOG_DETAIL_ORDER_DESC (integer)
2
SEASLOG_APPENDER_FILE (integer)
1
SEASLOG_APPENDER_TCP (integer)
2
SEASLOG_APPENDER_UDP (integer)
3
SEASLOG_CLOSE_LOGGER_STREAM_MOD_ALL (integer)
1
SEASLOG_CLOSE_LOGGER_STREAM_MOD_ASSIGN (integer)
2
SEASLOG_REQUEST_VARIABLE_DOMAIN_PORT (integer)
1
SEASLOG_REQUEST_VARIABLE_REQUEST_URI (integer)
2
SEASLOG_REQUEST_VARIABLE_REQUEST_METHOD (integer)
3
SEASLOG_REQUEST_VARIABLE_CLIENT_IP (integer)
4


Examples

Example #1 Get and set base path

<?php
  $basePath1 = SeasLog::getBasePath();

  SeasLog::setBasePath('/log/base_test');
  $basePath2 = SeasLog::getBasePath();

  var_dump($basePath1,$basePath2);

  ?>

The above example will output something similar to:

  string(12) "/var/log/www"
  string(14) "/log/base_test"

Example #2 Get and set logger

<?php
$lastLogger1 = SeasLog::getLastLogger();

SeasLog::setLogger('testModule/app1');
$lastLogger2 = SeasLog::getLastLogger();

var_dump($lastLogger1,$lastLogger2);

?>

The above example will output something similar to:

string(7) "default"
string(15) "testModule/app1"

Example #3 Fast write log

<?php
SeasLog::log(SEASLOG_ERROR,'this is a error test by ::log');
SeasLog::debug('this is a {userName} debug',array('{userName}' => 'neeke'));
SeasLog::info('this is a info log');
SeasLog::notice('this is a notice log');
SeasLog::warning('your {website} was down,please {action} it ASAP!',array('{website}' => 'github.com','{action}' => 'rboot'));
SeasLog::error('a error log');
SeasLog::critical('some thing was critical');
SeasLog::alert('yes this is a {messageName}',array('{messageName}' => 'alertMSG'));
SeasLog::emergency('Just now, the house next door was completely burnt out! {note}',array('{note}' => 'it`s a joke'));
?>

As the default, seaslog.default_template = "%T | %L | %P | %Q | %t | %M". That's mean,as the default,log record style is： `{dateTime} | {level} | {pid} | {uniqid} | {timeStamp} | {logInfo}`.

The above example will output something similar to:

seaslog.appender = 1

2014-07-27 08:53:52 | ERROR | 23625 | 599159975a9ff | 1406422432.786 | this is a error test by log
2014-07-27 08:53:52 | DEBUG | 23625 | 599159975a9ff | 1406422432.786 | this is a neeke debug
2014-07-27 08:53:52 | INFO | 23625 | 599159975a9ff | 1406422432.787 | this is a info log
2014-07-27 08:53:52 | NOTICE | 23625 | 599159975a9ff | 1406422432.787 | this is a notice log
2014-07-27 08:53:52 | WARNING | 23625 | 599159975a9ff | 1406422432.787 | your github.com was down,please rboot it ASAP!
2014-07-27 08:53:52 | ERROR | 23625 | 599159975a9ff | 1406422432.787 | a error log
2014-07-27 08:53:52 | CRITICAL | 23625 | 599159975a9ff | 1406422432.787 | some thing was critical
2014-07-27 08:53:52 | EMERGENCY | 23625 | 599159975a9ff | 1406422432.787 | Just now, the house next door was completely burnt out! it is a joke

The above example will output something similar to:

seaslog.appender = 2 or seaslog.appender = 3

The log style finally formatted such as:
<15>1 2017-08-27T01:24:59+08:00 vagrant-ubuntu-trusty test/logger[27171]: 2016-06-25 00:59:43 | DEBUG | 21423 | 599157af4e937 | 1466787583.322 | this is a neeke debug
<14>1 2017-08-27T01:24:59+08:00 vagrant-ubuntu-trusty test/logger[27171]: 2016-06-25 00:59:43 | INFO | 21423 | 599157af4e937 | 1466787583.323 | this is a info log
<13>1 2017-08-27T01:24:59+08:00 vagrant-ubuntu-trusty test/logger[27171]: 2016-06-25 00:59:43 | NOTICE | 21423 | 599157af4e937 | 1466787583.324 | this is a notice log

Example #4 Fast count some type of log count value

SeasLog get count value of `grep -wc` use system pipe and return to PHP (array or int).

<?php
$countResult1 = SeasLog::analyzerCount();
$countResult2 = SeasLog::analyzerCount(SEASLOG_WARNING);
$countResult3 = SeasLog::analyzerCount(SEASLOG_ERROR,date('Ymd',time()));

var_dump($countResult1,$countResult2,$countResult3);

?>

The above example will output something similar to:

array(8) {
  ["DEBUG"]=>
  int(3)
  ["INFO"]=>
  int(3)
  ["NOTICE"]=>
  int(3)
  ["WARNING"]=>
  int(3)
  ["ERROR"]=>
  int(6)
  ["CRITICAL"]=>
  int(3)
  ["ALERT"]=>
  int(3)
  ["EMERGENCY"]=>
  int(3)
}
int(7)
int(1)

Example #5 Acquisit some type of log list

SeasLog get count value of `grep -w` use system pipe and return array to PHP.

<?php
$detailErrorArray = SeasLog::analyzerDetail(SEASLOG_ERROR);
var_dump($detailErrorArray);

var_dump(SeasLog::analyzerDetail(SEASLOG_ERROR,date('Ymd',time())));
?>

The above example will output something similar to:

array(6) {
  [0] =>
  string(83) "2014-02-24 00:14:02 | ERROR | 8568 | 599157af4e937 | 1393172042.717 | test error 3 "
  [1] =>
  string(83) "2014-02-24 00:14:04 | ERROR | 8594 | 5991576584446 | 1393172044.104 | test error 3 "
  [2] =>
  string(83) "2014-02-24 00:14:04 | ERROR | 8620 | 1502697015147 | 1393172044.862 | test error 3 "
  [3] =>
  string(83) "2014-02-24 00:14:05 | ERROR | 8646 | 599159975a9ff | 1393172045.989 | test error 3 "
  [4] =>
  string(83) "2014-02-24 00:14:07 | ERROR | 8672 | 599159986ec28 | 1393172047.882 | test error 3 "
  [5] =>
  string(83) "2014-02-24 00:14:08 | ERROR | 8698 | 5991599981cec | 1393172048.736 | test error 3 "
}

array(2) {
  [0] =>
  string(83) "2014-02-24 00:14:02 | ERROR | 8568 | 599157af4e937 | 1393172042.717 | test error 3 "
  [1] =>
  string(83) "2014-02-24 00:14:04 | ERROR | 8594 | 5991576584446 | 1393172044.104 | test error 3 "
}


Seaslog Functions

Table of Contents

  • seaslog_get_author — Get SeasLog author.
  • seaslog_get_version — Get SeasLog version.


Get SeasLog author.

  • « Seaslog Functions
  • seaslog_get_version »
  • PHP Manual
  • Seaslog Functions
  • Get SeasLog author.

seaslog_get_author

(PECL seaslog >=1.0.0)

seaslog_get_author — Get SeasLog author.

Description

seaslog_get_author ( void ) : string

Parameters

This function has no parameters.

Return Values

Return SeasLog author as string.

Examples

Example #1 seaslog_get_author() example

<?php

var_dump(seaslog_get_author());

?>

The above example will output something similar to:

string(29) "Chitao.Gao  [ neeke@php.net ]"


Get SeasLog version.

  • « seaslog_get_author
  • SeasLog »
  • PHP Manual
  • Seaslog Functions
  • Get SeasLog version.

seaslog_get_version

(PECL seaslog >=1.0.0)

seaslog_get_version — Get SeasLog version.

Description

seaslog_get_version ( void ) : string

Parameters

This function has no parameters.

Return Values

Return SeasLog version (SEASLOG_VERSION) as string.

Examples

Example #1 seaslog_get_version() example

<?php

var_dump(seaslog_get_version());

?>

The above example will output something similar to:

string(5) "1.8.4"


The SeasLog class

(PECL seaslog >=1.0.0)

Introduction

Class synopsis

SeasLog {
/* Methods */
public static alert ( string $message [, array $content [, string $logger ]] ) : bool
public static analyzerCount ( string $level [, string $log_path [, string $key_word ]] ) : mixed
public static analyzerDetail ( string $level [, string $log_path [, string $key_word [, int $start [, int $limit [, int $order ]]]]] ) : mixed
public static closeLoggerStream ( int $model , string $logger ) : bool
public static critical ( string $message [, array $content [, string $logger ]] ) : bool
public static debug ( string $message [, array $content [, string $logger ]] ) : bool
public __destruct ( void )
public static emergency ( string $message [, array $content [, string $logger ]] ) : bool
public static error ( string $message [, array $content [, string $logger ]] ) : bool
public static flushBuffer ( void ) : bool
public static Seaslog::getBasePath ( void ) : string
public static getBuffer ( void ) : array
public static getBufferEnabled ( void ) : bool
public static getDatetimeFormat ( void ) : string
public static getLastLogger ( void ) : string
public static getRequestID ( void ) : string
public static getRequestVariable ( int $key ) : bool
public static info ( string $message [, array $content [, string $logger ]] ) : bool
public static log ( string $level [, string $message [, array $content [, string $logger ]]] ) : bool
public static notice ( string $message [, array $content [, string $logger ]] ) : bool
public static setBasePath ( string $base_path ) : bool
public static setDatetimeFormat ( string $format ) : bool
public static setLogger ( string $logger ) : bool
public static setRequestID ( string $request_id ) : bool
public static setRequestVariable ( int $key , string $value ) : bool
public static warning ( string $message [, array $content [, string $logger ]] ) : bool
}

Table of Contents

  • SeasLog::alert — Record alert log information
  • SeasLog::analyzerCount — Get log count by level, log_path and key_word
  • SeasLog::analyzerDetail — Get log detail by level, log_path, key_word, start, limit, order
  • SeasLog::closeLoggerStream — Manually release stream flow from logger
  • SeasLog::__construct — Description
  • SeasLog::critical — Record critical log information
  • SeasLog::debug — Record debug log information
  • SeasLog::__destruct — Description
  • SeasLog::emergency — Record emergency log information
  • SeasLog::error — Record error log information
  • SeasLog::flushBuffer — Flush logs buffer, dump to appender file, or send to remote api with tcp/udp
  • SeasLog::getBasePath — Get SeasLog base path.
  • SeasLog::getBuffer — Get the logs buffer in memory as array
  • SeasLog::getBufferEnabled — Determin if buffer enabled
  • SeasLog::getDatetimeFormat — Get SeasLog datetime format style
  • SeasLog::getLastLogger — Get SeasLog last logger path
  • SeasLog::getRequestID — Get SeasLog request_id differentiated requests
  • SeasLog::getRequestVariable — Get SeasLog request variable
  • SeasLog::info — Record info log information
  • SeasLog::log — The Common Record Log Function
  • SeasLog::notice — Record notice log information
  • SeasLog::setBasePath — Set SeasLog base path
  • SeasLog::setDatetimeFormat — Set SeasLog datetime format style
  • SeasLog::setLogger — Set SeasLog logger name
  • SeasLog::setRequestID — Set SeasLog request_id differentiated requests
  • SeasLog::setRequestVariable — Manually set SeasLog request variable
  • SeasLog::warning — Record warning log information


Record alert log information

  • « SeasLog
  • SeasLog::analyzerCount »
  • PHP Manual
  • SeasLog
  • Record alert log information

SeasLog::alert

(PECL seaslog >=1.0.0)

SeasLog::alert — Record alert log information

Description

public static SeasLog::alert ( string $message [, array $content [, string $logger ]] ) : bool

Record alert log information.

Note:

"ALERT" - Action must be taken immediately. Immediate attention should be given to relevant personnel for emergency repairs.

Parameters

message

The log message.

content

The `message` contain placeholders which implementors replace with values from content array. Sush as `message` is `log info from {NAME}` and `content` is `array('NAME' => neeke)`, the log information will `log info from neeke`.

logger

The `logger` cased by the third param would be used right this right now, like a temp logger, when the function SeasLog::setLogger() called in pre content. If `logger` NULL or "", SeasLog will use lastest logger setted by SeasLog::setLogger().

Return Values

Return TRUE on record log information success, FALSE on failure.

Examples

Example #1 SeasLog::alert() example

<?php

var_dump(SeasLog::alert('log message'));

//with content
var_dump(SeasLog::alert('log message from {NAME}',array('NAME' => 'neeke')));

//with tmp logger
var_dump(SeasLog::alert('log message from {NAME}',array('NAME' => 'neeke'),'tmp_logger'));

var_dump(SeasLog::getBuffer());

?>

The above example will output something similar to:

bool(true)
bool(true)
bool(true)
array(2) {
  ["/var/log/www/default/20180707.log"]=>
  array(2) {
    [0]=>
    string(81) "2018-07-07 11:45:49 | ALERT | 73263 | 5b40376d1067c | 1530935149.68 | log message
"
    [1]=>
    string(92) "2018-07-07 11:45:49 | ALERT | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
  ["/var/log/www/tmp_logger/20180707.log"]=>
  array(1) {
    [0]=>
    string(92) "2018-07-07 11:45:49 | ALERT | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
}

See Also

  • seaslog.default_template
  • SeasLog::debug() - Record debug log information
  • SeasLog::info() - Record info log information
  • SeasLog::notice() - Record notice log information
  • SeasLog::warning() - Record warning log information
  • SeasLog::error() - Record error log information
  • SeasLog::critical() - Record critical log information
  • SeasLog::emergency() - Record emergency log information
  • SeasLog::log() - The Common Record Log Function


Get log count by level, log_path and key_word

  • « SeasLog::alert
  • SeasLog::analyzerDetail »
  • PHP Manual
  • SeasLog
  • Get log count by level, log_path and key_word

SeasLog::analyzerCount

(PECL seaslog >=1.1.6)

SeasLog::analyzerCount — Get log count by level, log_path and key_word

Description

public static SeasLog::analyzerCount ( string $level [, string $log_path [, string $key_word ]] ) : mixed

`SeasLog` get count value of `grep -ai '{level}' | grep -aic '{key_word}'` use system pipe and return to PHP (array or int).

Parameters

level

String. The log information level.

log_path

String. The log information path.

key_word

String. The search key word for log information.

Return Values

If `level` is SEASLOG_ALL or Empty, return all levels count as `array`. If `level` is SEASLOG_INFO or the other level, return count as `int`.

Examples

Example #1 SeasLog::analyzerCount() example

<?php

$countResult1 = SeasLog::analyzerCount();

//with `level`
$countResult2 = SeasLog::analyzerCount(SEASLOG_DEBUG);

//with `level` and `log_path`
$countResult3 = SeasLog::analyzerCount(SEASLOG_ERROR,date('Ymd',time()));

//with `level` and `key_word`
$countResult4 = SeasLog::analyzerCount(SEASLOG_DEBUG,NULL,'accessToken');

var_dump($countResult1,$countResult2,$countResult3,$countResult4);

?>

The above example will output something similar to:

array(8) {
  ["DEBUG"]=>
  int(180)
  ["INFO"]=>
  int(214)
  ["NOTICE"]=>
  int(0)
  ["WARNING"]=>
  int(0)
  ["ERROR"]=>
  int(228)
  ["CRITICAL"]=>
  int(244)
  ["ALERT"]=>
  int(1)
  ["EMERGENCY"]=>
  int(0)
}

int(180)

int(228)

int(29)

See Also

  • SeasLog::analyzerDetail() - Get log detail by level, log_path, key_word, start, limit, order


Get log detail by level, log_path, key_word, start, limit, order

  • « SeasLog::analyzerCount
  • SeasLog::closeLoggerStream »
  • PHP Manual
  • SeasLog
  • Get log detail by level, log_path, key_word, start, limit, order

SeasLog::analyzerDetail

(PECL seaslog >=1.1.6)

SeasLog::analyzerDetail — Get log detail by level, log_path, key_word, start, limit, order

Description

public static SeasLog::analyzerDetail ( string $level [, string $log_path [, string $key_word [, int $start [, int $limit [, int $order ]]]]] ) : mixed

`SeasLog` get results of `grep -ai '{level}' | grep -ai '{key_word}' | sed -n '{start},{limit}'p` use system pipe and return array to PHP.

Parameters

level

String. The log information level.

log_path

String. The log information path.

key_word

String. The search key word for log information.

start

Int. Default is `1`.

limit

Int. Default is `20`.

order

Int. Default is SEASLOG_DETAIL_ORDER_ASC. See also:

  • SEASLOG_DETAIL_ORDER_ASC
  • SEASLOG_DETAIL_ORDER_DESC

Return Values

Return results as array.

Note:

When `start`,`limit` is not NULL and in Windows, SeasLog will threw exception with message 'Param start and limit don't support Windows'.

Examples

Example #1 SeasLog::analyzerDetail() example

<?php

$result1 = SeasLog::analyzerDetail(SEASLOG_ERROR);

//with `logger` and `key_word`
$result2 = SeasLog::analyzerDetail(SEASLOG_ERROR,'test/logger/','neeke');

//with `start` and `limit`
$result3 = SeasLog::analyzerDetail(SEASLOG_ERROR,'test/logger/','neeke',1,2);

var_dump($result1,$result2,$result3);
?>

The above example will output something similar to:

array(20) {
  [0]=>
  string(93) "2018-07-09 12:52:53 | ERROR | 12247 | 5b42ea2580e51 | 1531111973.528 | log message from neeke"
  [1]=>
  string(93) "2018-07-09 12:52:54 | ERROR | 12256 | 5b42ea26d6657 | 1531111974.878 | log message from neeke"
  [2]=>
  string(93) "2018-07-09 12:52:55 | ERROR | 12265 | 5b42ea277b8d4 | 1531111975.506 | log message from neeke"
  [3]=>
  string(104) "2018-07-09 12:52:55 | ERROR | 12274 | 5b42ea27db5dc | 1531111975.898 | log message from the other people"
...
}

array(3) {
  [0]=>
  string(93) "2018-07-09 12:52:53 | ERROR | 12247 | 5b42ea2580e51 | 1531111973.528 | log message from neeke"
  [1]=>
  string(93) "2018-07-09 12:52:54 | ERROR | 12256 | 5b42ea26d6657 | 1531111974.878 | log message from neeke"
  [2]=>
  string(93) "2018-07-09 12:52:55 | ERROR | 12265 | 5b42ea277b8d4 | 1531111975.506 | log message from neeke"
}

array(2) {
  [0]=>
  string(93) "2018-07-09 12:52:53 | ERROR | 12247 | 5b42ea2580e51 | 1531111973.528 | log message from neeke"
  [1]=>
  string(93) "2018-07-09 12:52:54 | ERROR | 12256 | 5b42ea26d6657 | 1531111974.878 | log message from neeke"
}

See Also

  • SeasLog::analyzerCount() - Get log count by level, log_path and key_word


Manually release stream flow from logger

  • « SeasLog::analyzerDetail
  • SeasLog::__construct »
  • PHP Manual
  • SeasLog
  • Manually release stream flow from logger

SeasLog::closeLoggerStream

(PECL seaslog >=1.8.6)

SeasLog::closeLoggerStream — Manually release stream flow from logger

Description

public static SeasLog::closeLoggerStream ( int $model , string $logger ) : bool

Manually release stream flow from logger. SeasLog caches the stream handle opened by the log logger to save the overhead of creating a stream. The handle will be automatically released at the end of the request. If in CLI mode, the process will also automatically release when it exits. Or you can use the following functions to manually release(manually release function needs to update SeasLog 1.8.6 or updated version).

Parameters

model

Constant int.

  • SEASLOG_CLOSE_LOGGER_STREAM_MOD_ALL
  • SEASLOG_CLOSE_LOGGER_STREAM_MOD_ASSIGN

logger

The logger name.

Return Values

Return TRUE on released stream flow success, FALSE on failure.

Examples

Example #1 SeasLog::closeLoggerStream() example

<?php

var_dump(SeasLog::closeLoggerStream());
var_dump(SeasLog::closeLoggerStream(SEASLOG_CLOSE_LOGGER_STREAM_MOD_ALL));
var_dump(SeasLog::closeLoggerStream(SEASLOG_CLOSE_LOGGER_STREAM_MOD_ASSIGN, 'logger_name'));

?>

The above example will output something similar to:

bool(true)
bool(true)
bool(true)

See Also

  • SeasLog::setLogger() - Set SeasLog logger name
  • SeasLog::getLastLogger() - Get SeasLog last logger path


Description

  • « SeasLog::closeLoggerStream
  • SeasLog::critical »
  • PHP Manual
  • SeasLog
  • Description

SeasLog::__construct

(PECL seaslog >=1.0.0)

SeasLog::__construct — Description

Description

public SeasLog::__construct ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Examples

Example #1 SeasLog::__construct() example

<?php

/* ... */

?>

The above example will output something similar to:

...


Record critical log information

  • « SeasLog::__construct
  • SeasLog::debug »
  • PHP Manual
  • SeasLog
  • Record critical log information

SeasLog::critical

(PECL seaslog >=1.0.0)

SeasLog::critical — Record critical log information

Description

public static SeasLog::critical ( string $message [, array $content [, string $logger ]] ) : bool

Record critical log information.

Note:

"CRITICAL" - Critical conditions.Need to be repaired immediately, and the program component is unavailable.

Parameters

message

The log message.

content

The `message` contain placeholders which implementors replace with values from content array. Sush as `message` is `log info from {NAME}` and `content` is `array('NAME' => neeke)`, the log information will `log info from neeke`.

logger

The `logger` cased by the third param would be used right this right now, like a temp logger, when the function SeasLog::setLogger() called in pre content. If `logger` NULL or "", SeasLog will use lastest logger setted by SeasLog::setLogger().

Return Values

Return TRUE on record log information success, FALSE on failure.

Examples

Example #1 SeasLog::critical() example

<?php

var_dump(SeasLog::critical('log message'));

//with content
var_dump(SeasLog::critical('log message from {NAME}',array('NAME' => 'neeke')));

//with tmp logger
var_dump(SeasLog::critical('log message from {NAME}',array('NAME' => 'neeke'),'tmp_logger'));

var_dump(SeasLog::getBuffer());

?>

The above example will output something similar to:

bool(true)
bool(true)
bool(true)
array(2) {
  ["/var/log/www/default/20180707.log"]=>
  array(2) {
    [0]=>
    string(81) "2018-07-07 11:45:49 | CRITICAL | 73263 | 5b40376d1067c | 1530935149.68 | log message
"
    [1]=>
    string(92) "2018-07-07 11:45:49 | CRITICAL | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
  ["/var/log/www/tmp_logger/20180707.log"]=>
  array(1) {
    [0]=>
    string(92) "2018-07-07 11:45:49 | CRITICAL | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
}

See Also

  • seaslog.default_template
  • SeasLog::debug() - Record debug log information
  • SeasLog::info() - Record info log information
  • SeasLog::notice() - Record notice log information
  • SeasLog::warning() - Record warning log information
  • SeasLog::error() - Record error log information
  • SeasLog::alert() - Record alert log information
  • SeasLog::emergency() - Record emergency log information
  • SeasLog::log() - The Common Record Log Function


Record debug log information

  • « SeasLog::critical
  • SeasLog::__destruct »
  • PHP Manual
  • SeasLog
  • Record debug log information

SeasLog::debug

(PECL seaslog >=1.0.0)

SeasLog::debug — Record debug log information

Description

public static SeasLog::debug ( string $message [, array $content [, string $logger ]] ) : bool

Record debug log information.

Note:

"DEBUG" - Detailed debug information.Fine-grained information events.

Parameters

message

The log message.

content

The `message` contain placeholders which implementors replace with values from content array. Sush as `message` is `log info from {NAME}` and `content` is `array('NAME' => neeke)`, the log information will `log info from neeke`.

logger

The `logger` cased by the third param would be used right this right now, like a temp logger, when the function SeasLog::setLogger() called in pre content. If `logger` NULL or "", SeasLog will use lastest logger setted by SeasLog::setLogger().

Return Values

Return TRUE on record log information success, FALSE on failure.

Examples

Example #1 SeasLog::debug() example

<?php

var_dump(SeasLog::debug('log message'));

//with content
var_dump(SeasLog::debug('log message from {NAME}',array('NAME' => 'neeke')));

//with tmp logger
var_dump(SeasLog::debug('log message from {NAME}',array('NAME' => 'neeke'),'tmp_logger'));

var_dump(SeasLog::getBuffer());

?>

The above example will output something similar to:

bool(true)
bool(true)
bool(true)
array(2) {
  ["/var/log/www/default/20180707.log"]=>
  array(2) {
    [0]=>
    string(81) "2018-07-07 11:45:49 | DEBUG | 73263 | 5b40376d1067c | 1530935149.68 | log message
"
    [1]=>
    string(92) "2018-07-07 11:45:49 | DEBUG | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
  ["/var/log/www/tmp_logger/20180707.log"]=>
  array(1) {
    [0]=>
    string(92) "2018-07-07 11:45:49 | DEBUG | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
}

See Also

  • seaslog.default_template
  • SeasLog::info() - Record info log information
  • SeasLog::notice() - Record notice log information
  • SeasLog::warning() - Record warning log information
  • SeasLog::error() - Record error log information
  • SeasLog::critical() - Record critical log information
  • SeasLog::alert() - Record alert log information
  • SeasLog::emergency() - Record emergency log information
  • SeasLog::log() - The Common Record Log Function


Description

  • « SeasLog::debug
  • SeasLog::emergency »
  • PHP Manual
  • SeasLog
  • Description

SeasLog::__destruct

(PECL seaslog >=1.0.0)

SeasLog::__destruct — Description

Description

public SeasLog::__destruct ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Examples

Example #1 SeasLog::__destruct() example

<?php

/* ... */

?>

The above example will output something similar to:

...


Record emergency log information

  • « SeasLog::__destruct
  • SeasLog::error »
  • PHP Manual
  • SeasLog
  • Record emergency log information

SeasLog::emergency

(PECL seaslog >=1.0.0)

SeasLog::emergency — Record emergency log information

Description

public static SeasLog::emergency ( string $message [, array $content [, string $logger ]] ) : bool

Record emergency log information.

Note:

"EMERGENCY" - System is unusable.

Parameters

message

The log message.

content

The `message` contain placeholders which implementors replace with values from content array. Sush as `message` is `log info from {NAME}` and `content` is `array('NAME' => neeke)`, the log information will `log info from neeke`.

logger

The `logger` cased by the third param would be used right this right now, like a temp logger, when the function SeasLog::setLogger() called in pre content. If `logger` NULL or "", SeasLog will use lastest logger setted by SeasLog::setLogger().

Return Values

Return TRUE on record log information success, FALSE on failure.

Examples

Example #1 SeasLog::emergency() example

<?php

var_dump(SeasLog::emergency('log message'));

//with content
var_dump(SeasLog::emergency('log message from {NAME}',array('NAME' => 'neeke')));

//with tmp logger
var_dump(SeasLog::emergency('log message from {NAME}',array('NAME' => 'neeke'),'tmp_logger'));

var_dump(SeasLog::getBuffer());

?>

The above example will output something similar to:

bool(true)
bool(true)
bool(true)
array(2) {
  ["/var/log/www/default/20180707.log"]=>
  array(2) {
    [0]=>
    string(81) "2018-07-07 11:45:49 | EMERGENCY | 73263 | 5b40376d1067c | 1530935149.68 | log message
"
    [1]=>
    string(92) "2018-07-07 11:45:49 | EMERGENCY | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
  ["/var/log/www/tmp_logger/20180707.log"]=>
  array(1) {
    [0]=>
    string(92) "2018-07-07 11:45:49 | EMERGENCY | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
}

See Also

  • seaslog.default_template
  • SeasLog::debug() - Record debug log information
  • SeasLog::info() - Record info log information
  • SeasLog::notice() - Record notice log information
  • SeasLog::warning() - Record warning log information
  • SeasLog::error() - Record error log information
  • SeasLog::critical() - Record critical log information
  • SeasLog::alert() - Record alert log information
  • SeasLog::log() - The Common Record Log Function


Record error log information

  • « SeasLog::emergency
  • SeasLog::flushBuffer »
  • PHP Manual
  • SeasLog
  • Record error log information

SeasLog::error

(PECL seaslog >=1.0.0)

SeasLog::error — Record error log information

Description

public static SeasLog::error ( string $message [, array $content [, string $logger ]] ) : bool

Record error log information.

Note:

"ERROR" - Runtime errors that do not require immediate action but should typically.

Parameters

message

The log message.

content

The `message` contain placeholders which implementors replace with values from content array. Sush as `message` is `log info from {NAME}` and `content` is `array('NAME' => neeke)`, the log information will `log info from neeke`.

logger

The `logger` cased by the third param would be used right this right now, like a temp logger, when the function SeasLog::setLogger() called in pre content. If `logger` NULL or "", SeasLog will use lastest logger setted by SeasLog::setLogger().

Return Values

Return TRUE on record log information success, FALSE on failure.

Examples

Example #1 SeasLog::error() example

<?php

var_dump(SeasLog::error('log message'));

//with content
var_dump(SeasLog::error('log message from {NAME}',array('NAME' => 'neeke')));

//with tmp logger
var_dump(SeasLog::error('log message from {NAME}',array('NAME' => 'neeke'),'tmp_logger'));

var_dump(SeasLog::getBuffer());

?>

The above example will output something similar to:

bool(true)
bool(true)
bool(true)
array(2) {
  ["/var/log/www/default/20180707.log"]=>
  array(2) {
    [0]=>
    string(81) "2018-07-07 11:45:49 | ERROR | 73263 | 5b40376d1067c | 1530935149.68 | log message
"
    [1]=>
    string(92) "2018-07-07 11:45:49 | ERROR | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
  ["/var/log/www/tmp_logger/20180707.log"]=>
  array(1) {
    [0]=>
    string(92) "2018-07-07 11:45:49 | ERROR | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
}

See Also

  • seaslog.default_template
  • SeasLog::debug() - Record debug log information
  • SeasLog::info() - Record info log information
  • SeasLog::notice() - Record notice log information
  • SeasLog::warning() - Record warning log information
  • SeasLog::critical() - Record critical log information
  • SeasLog::alert() - Record alert log information
  • SeasLog::emergency() - Record emergency log information
  • SeasLog::log() - The Common Record Log Function


Flush logs buffer, dump to appender file, or send to remote api with tcp/udp

  • « SeasLog::error
  • SeasLog::getBasePath »
  • PHP Manual
  • SeasLog
  • Flush logs buffer, dump to appender file, or send to remote api with tcp/udp

SeasLog::flushBuffer

(PECL seaslog >=1.0.0)

SeasLog::flushBuffer — Flush logs buffer, dump to appender file, or send to remote api with tcp/udp

Description

public static SeasLog::flushBuffer ( void ) : bool

Flush logs buffer by seaslog.appender: dump to file, or send to remote api with tcp/udp.

Note:

See also: seaslog.appender_retry seaslog.remote_host seaslog.remote_port

Parameters

This function has no parameters.

Return Values

Return TRUE on flush buffer success, FALSE on failure.

Examples

Example #1 SeasLog::flushBuffer() example

<?php

SeasLog::info('info log');
SeasLog::debug('debug log');
var_dump(SeasLog::getBuffer());
var_dump(SeasLog::flushBuffer());
var_dump(SeasLog::getBuffer());

?>

The above example will output something similar to:

array(1) {
  ["/var/log/www/default/20180707.log"]=>
  array(2) {
    [0]=>
    string(79) "2018-07-07 10:47:58 | INFO | 71910 | 5b4029ded6009 | 1530931678.877 | info log
"
    [1]=>
    string(81) "2018-07-07 10:47:58 | DEBUG | 71910 | 5b4029ded6009 | 1530931678.877 | debug log
"
  }
}
bool(true)
array(0) {
}

See Also

  • seaslog.use_buffer
  • seaslog.buffer_size
  • seaslog.buffer_disabled_in_cli
  • SeasLog::getBufferEnabled() - Determin if buffer enabled
  • SeasLog::getBuffer() - Get the logs buffer in memory as array


Get SeasLog base path.

  • « SeasLog::flushBuffer
  • SeasLog::getBuffer »
  • PHP Manual
  • SeasLog
  • Get SeasLog base path.

SeasLog::getBasePath

(PECL seaslog >=1.0.0)

SeasLog::getBasePath — Get SeasLog base path.

Description

public static Seaslog::getBasePath ( void ) : string

Use the Function SeasLog::getBasePath() will get the value of seaslog.default_basepath what configured in php.ini(seaslog.ini).

If you use Seaslog::setBasePath(), will change the result.

Parameters

This function has no parameters.

Return Values

Return seaslog.default_basepath as string.

Examples

Example #1 SeasLog::getBasePath() example

<?php

var_dump(SeasLog::getBasePath());

?>

The above example will output something similar to:

string(12) "/var/log/www"


Get the logs buffer in memory as array

  • « SeasLog::getBasePath
  • SeasLog::getBufferEnabled »
  • PHP Manual
  • SeasLog
  • Get the logs buffer in memory as array

SeasLog::getBuffer

(PECL seaslog >=1.0.0)

SeasLog::getBuffer — Get the logs buffer in memory as array

Description

public static SeasLog::getBuffer ( void ) : array

Parameters

This function has no parameters.

Return Values

Return an array from logs buffer in memory.

Examples

Example #1 SeasLog::getBuffer() example

<?php

var_dump(SeasLog::info('info log'));
var_dump(SeasLog::debug('debug log'));
var_dump(SeasLog::getBuffer());

?>

The above example will output something similar to:

bool(true)
bool(true)
array(1) {
  ["/var/log/www/default/20180707.log"]=>
  array(2) {
    [0]=>
    string(79) "2018-07-07 10:43:32 | INFO | 71785 | 5b4028d4c58d5 | 1530931412.810 | info log
"
    [1]=>
    string(81) "2018-07-07 10:43:32 | DEBUG | 71785 | 5b4028d4c58d5 | 1530931412.810 | debug log
"
  }
}

See Also

  • seaslog.use_buffer
  • seaslog.buffer_size
  • seaslog.buffer_disabled_in_cli
  • SeasLog::getBufferEnabled() - Determin if buffer enabled
  • SeasLog::flushBuffer() - Flush logs buffer, dump to appender file, or send to remote api with tcp/udp


Determin if buffer enabled

  • « SeasLog::getBuffer
  • SeasLog::getDatetimeFormat »
  • PHP Manual
  • SeasLog
  • Determin if buffer enabled

SeasLog::getBufferEnabled

(PECL seaslog >=1.0.0)

SeasLog::getBufferEnabled — Determin if buffer enabled

Description

public static SeasLog::getBufferEnabled ( void ) : bool

Result join seaslog.use_buffer and seaslog.buffer_disabled_in_cli.

Parameters

This function has no parameters.

Return Values

Return TRUE on seaslog.use_buffer is true. If switch seaslog.buffer_disabled_in_cli on, and running in cli, seaslog.use_buffer setting will be discarded, Seaslog write to the Data Store IMMEDIATELY.

Examples

Example #1 SeasLog::getBufferEnabled() example

<?php

var_dump(SeasLog::getBufferEnabled());

?>

The above example will output something similar to:

bool(false)

See Also

  • seaslog.use_buffer
  • seaslog.buffer_size
  • seaslog.buffer_disabled_in_cli
  • SeasLog::getBuffer() - Get the logs buffer in memory as array
  • SeasLog::flushBuffer() - Flush logs buffer, dump to appender file, or send to remote api with tcp/udp


Get SeasLog datetime format style

  • « SeasLog::getBufferEnabled
  • SeasLog::getLastLogger »
  • PHP Manual
  • SeasLog
  • Get SeasLog datetime format style

SeasLog::getDatetimeFormat

(PECL seaslog >=1.0.0)

SeasLog::getDatetimeFormat — Get SeasLog datetime format style

Description

public static SeasLog::getDatetimeFormat ( void ) : string

Get SeasLog datetime format style. Use the Function SeasLog::getDatetimeFormat() will get the value of seaslog.default_datetime_format what configured in php.ini(seaslog.ini).

Parameters

This function has no parameters.

Return Values

Get SeasLog datetime format style of seaslog.default_datetime_format. Use the Function SeasLog::setDatetimeFormat() will change this value.

Examples

Example #1 SeasLog::getDatetimeFormat() example

<?php

var_dump(SeasLog::getDateTimeFormat());
var_dump(SeasLog::setDateTimeFormat('Ymd His'));
var_dump(SeasLog::getDateTimeFormat());

?>

The above example will output something similar to:

string(11) "Y-m-d H:i:s"
bool(true)
string(7) "Ymd His"

See Also

  • SeasLog::setDatetimeFormat() - Set SeasLog datetime format style


Get SeasLog last logger path

  • « SeasLog::getDatetimeFormat
  • SeasLog::getRequestID »
  • PHP Manual
  • SeasLog
  • Get SeasLog last logger path

SeasLog::getLastLogger

(PECL seaslog >=1.0.0)

SeasLog::getLastLogger — Get SeasLog last logger path

Description

public static SeasLog::getLastLogger ( void ) : string

Use the Function SeasLog::getLastLogger() will get the value of seaslog.default_logger what configured in php.ini(seaslog.ini).

Parameters

This function has no parameters.

Return Values

Use the Function SeasLog::setLogger() will change the value of function SeasLog::getLastLogger().

Examples

Example #1 SeasLog::getLastLogger() example

<?php

var_dump(SeasLog::getLastLogger());
SeasLog::setLogger('theNewLogger');
var_dump(SeasLog::getLastLogger());
?>

The above example will output something similar to:

string(7) "default"
string(12) "theNewLogger"

See Also

  • SeasLog::setLogger() - Set SeasLog logger name


Get SeasLog request_id differentiated requests

  • « SeasLog::getLastLogger
  • SeasLog::getRequestVariable »
  • PHP Manual
  • SeasLog
  • Get SeasLog request_id differentiated requests

SeasLog::getRequestID

(PECL seaslog >=1.0.0)

SeasLog::getRequestID — Get SeasLog request_id differentiated requests

Description

public static SeasLog::getRequestID ( void ) : string

To distinguish a single request, such as not invoking the SeasLog::setRequestId() function， the unique value generated by the built-in `static char *get_uniqid ()` function is used when the request is initialized.

Parameters

This function has no parameters.

Return Values

Return string generated by the built-in `static char *get_uniqid ()` function, or setted by SeasLog::setRequestId() function.

Examples

Example #1 SeasLog::getRequestID() example

<?php

var_dump(SeasLog::getRequestID());
var_dump(SeasLog::setRequestID('reqeust_id_test_'.time()))
var_dump(SeasLog::getRequestID());

?>

The above example will output something similar to:

string(13) "5b3f21a209519"
bool(true)
string(26) "reqeust_id_test_1530864034"

See Also

  • SeasLog::setRequestID() - Set SeasLog request_id differentiated requests
  • The Variable `%Q` in Seaslog Default Variable Table.


Get SeasLog request variable

  • « SeasLog::getRequestID
  • SeasLog::info »
  • PHP Manual
  • SeasLog
  • Get SeasLog request variable

SeasLog::getRequestVariable

(PECL seaslog >=1.9.0)

SeasLog::getRequestVariable — Get SeasLog request variable

Description

public static SeasLog::getRequestVariable ( int $key ) : bool

Get SeasLog request variable.

Parameters

key

Constant int.

  • SEASLOG_REQUEST_VARIABLE_DOMAIN_PORT
  • SEASLOG_REQUEST_VARIABLE_REQUEST_URI
  • SEASLOG_REQUEST_VARIABLE_REQUEST_METHOD
  • SEASLOG_REQUEST_VARIABLE_CLIENT_IP

Return Values

Return request variable value on set success.

Examples

Example #1 SeasLog::getRequestVariable() example

<?php

$sDomainPort = 'domain:port';
$sRequestUri = 'uri';
$sRequestMethod = 'method';
$sClientIp = 'client_ip';

$iErrorKey = 1000;

$oSeasLog = new SeasLog();

var_dump($oSeasLog->setRequestVariable(SEASLOG_REQUEST_VARIABLE_DOMAIN_PORT, $sDomainPort));
var_dump($oSeasLog->setRequestVariable(SEASLOG_REQUEST_VARIABLE_REQUEST_URI, $sRequestUri));
var_dump($oSeasLog->setRequestVariable(SEASLOG_REQUEST_VARIABLE_REQUEST_METHOD, $sRequestMethod));
var_dump($oSeasLog->setRequestVariable(SEASLOG_REQUEST_VARIABLE_CLIENT_IP, $sClientIp));

var_dump($oSeasLog->setRequestVariable($iErrorKey,NULL));

var_dump($oSeasLog->getRequestVariable(SEASLOG_REQUEST_VARIABLE_DOMAIN_PORT) == $sDomainPort);
var_dump($oSeasLog->getRequestVariable(SEASLOG_REQUEST_VARIABLE_REQUEST_URI) == $sRequestUri);
var_dump($oSeasLog->getRequestVariable(SEASLOG_REQUEST_VARIABLE_REQUEST_METHOD) == $sRequestMethod);
var_dump($oSeasLog->getRequestVariable(SEASLOG_REQUEST_VARIABLE_CLIENT_IP) == $sClientIp);

var_dump($oSeasLog->getRequestVariable($iErrorKey));

?>

The above example will output something similar to:

bool(true)
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(true)
bool(true)
bool(true)
bool(false)

See Also

  • SeasLog::setRequestVariable() - Manually set SeasLog request variable


Record info log information

  • « SeasLog::getRequestVariable
  • SeasLog::log »
  • PHP Manual
  • SeasLog
  • Record info log information

SeasLog::info

(PECL seaslog >=1.0.0)

SeasLog::info — Record info log information

Description

public static SeasLog::info ( string $message [, array $content [, string $logger ]] ) : bool

Record info log information.

Note:

"INFO" - Interesting events.Emphasizes the running process of the application.

Parameters

message

The log message.

content

The `message` contain placeholders which implementors replace with values from content array. Sush as `message` is `log info from {NAME}` and `content` is `array('NAME' => neeke)`, the log information will `log info from neeke`.

logger

The `logger` cased by the third param would be used right this right now, like a temp logger, when the function SeasLog::setLogger() called in pre content. If `logger` NULL or "", SeasLog will use lastest logger setted by SeasLog::setLogger().

Return Values

Return TRUE on record log information success, FALSE on failure.

Examples

Example #1 SeasLog::info() example

<?php

var_dump(SeasLog::info('log message'));

//with content
var_dump(SeasLog::info('log message from {NAME}',array('NAME' => 'neeke')));

//with tmp logger
var_dump(SeasLog::info('log message from {NAME}',array('NAME' => 'neeke'),'tmp_logger'));

var_dump(SeasLog::getBuffer());

?>

The above example will output something similar to:

bool(true)
bool(true)
bool(true)
array(2) {
  ["/var/log/www/default/20180707.log"]=>
  array(2) {
    [0]=>
    string(81) "2018-07-07 11:45:49 | INFO | 73263 | 5b40376d1067c | 1530935149.68 | log message
"
    [1]=>
    string(92) "2018-07-07 11:45:49 | INFO | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
  ["/var/log/www/tmp_logger/20180707.log"]=>
  array(1) {
    [0]=>
    string(92) "2018-07-07 11:45:49 | INFO | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
}

See Also

  • seaslog.default_template
  • SeasLog::debug() - Record debug log information
  • SeasLog::notice() - Record notice log information
  • SeasLog::warning() - Record warning log information
  • SeasLog::error() - Record error log information
  • SeasLog::critical() - Record critical log information
  • SeasLog::alert() - Record alert log information
  • SeasLog::emergency() - Record emergency log information
  • SeasLog::log() - The Common Record Log Function


The Common Record Log Function

  • « SeasLog::info
  • SeasLog::notice »
  • PHP Manual
  • SeasLog
  • The Common Record Log Function

SeasLog::log

(PECL seaslog >=1.0.0)

SeasLog::log — The Common Record Log Function

Description

public static SeasLog::log ( string $level [, string $message [, array $content [, string $logger ]]] ) : bool

The Common Record Log Function.

Parameters

level

Can use level in:

  • SEASLOG_DEBUG
  • SEASLOG_INFO
  • SEASLOG_NOTICE
  • SEASLOG_WARNING
  • SEASLOG_ERROR
  • SEASLOG_CRITICAL
  • SEASLOG_ALERT
  • SEASLOG_EMERGENCY
Or you can create a new level self-help.

message

The log message.

content

The `message` contain placeholders which implementors replace with values from content array. Sush as `message` is `log info from {NAME}` and `content` is `array('NAME' => neeke)`, the log information will `log info from neeke`.

logger

The `logger` cased by the third param would be used right this right now, like a temp logger, when the function SeasLog::setLogger() called in pre content. If `logger` NULL or "", SeasLog will use lastest logger setted by SeasLog::setLogger().

Return Values

Return TRUE on record log information success, FALSE on failure.

Examples

Example #1 SeasLog::log() example

<?php

var_dump(SeasLog::log(SEASLOG_INFO,'info log'));
var_dump(SeasLog::getBuffer());

//create a new level self-help.
var_dump(SeasLog::log('MySelfLevel','info log'));
var_dump(SeasLog::getBuffer());

//with `content`
var_dump(SeasLog::log('MySelfLevel','info log {NAME}',array('NAME' => 'neeke')));
var_dump(SeasLog::getBuffer());

//with `logger`
var_dump(SeasLog::log('MySelfLevel','info log {NAME}',array('NAME' => 'neeke'),'tmp_logger'));
var_dump(SeasLog::getBuffer());

?>

The above example will output something similar to:

bool(true)
array(1) {
  ["/var/log/www/default/20180707.log"]=>
  array(1) {
    [0]=>
    string(79) "2018-07-07 11:12:37 | INFO | 72427 | 5b402fa56a2ea | 1530933157.436 | info log
"
  }
}

bool(true)
array(1) {
  ["/var/log/www/default/20180707.log"]=>
  array(1) {
    [0]=>
    string(86) "2018-07-07 11:13:59 | MySelfLevel | 72470 | 5b402ff781c5e | 1530933239.532 | info log
"
  }
}

bool(true)
array(1) {
  ["/var/log/www/tmp_logger/20180707.log"]=>
  array(1) {
    [0]=>
    string(92) "2018-07-07 11:28:12 | MySelfLevel | 72833 | 5b40334ce6a2f | 1530934092.946 | info log neeke
"
  }
}

bool(true)
array(1) {
  ["/var/log/www/default/20180707.log"]=>
  array(1) {
    [0]=>
    string(86) "2018-07-07 11:20:12 | INFO | 72616 | 5b40316c3641e | 1530933612.222 | info log neeke
"
  }
}

See Also

  • seaslog.default_template
  • SeasLog::debug() - Record debug log information
  • SeasLog::info() - Record info log information
  • SeasLog::notice() - Record notice log information
  • SeasLog::warning() - Record warning log information
  • SeasLog::error() - Record error log information
  • SeasLog::critical() - Record critical log information
  • SeasLog::alert() - Record alert log information
  • SeasLog::emergency() - Record emergency log information


Record notice log information

  • « SeasLog::log
  • SeasLog::setBasePath »
  • PHP Manual
  • SeasLog
  • Record notice log information

SeasLog::notice

(PECL seaslog >=1.0.0)

SeasLog::notice — Record notice log information

Description

public static SeasLog::notice ( string $message [, array $content [, string $logger ]] ) : bool

Record notice log information.

Note:

"NOTICE" - Normal but significant events.Information that is more important than the INFO level during execution.

Parameters

message

The log message.

content

The `message` contain placeholders which implementors replace with values from content array. Sush as `message` is `log info from {NAME}` and `content` is `array('NAME' => neeke)`, the log information will `log info from neeke`.

logger

The `logger` cased by the third param would be used right this right now, like a temp logger, when the function SeasLog::setLogger() called in pre content. If `logger` NULL or "", SeasLog will use lastest logger setted by SeasLog::setLogger().

Return Values

Return TRUE on record log information success, FALSE on failure.

Examples

Example #1 SeasLog::notice() example

<?php

var_dump(SeasLog::notice('log message'));

//with content
var_dump(SeasLog::notice('log message from {NAME}',array('NAME' => 'neeke')));

//with tmp logger
var_dump(SeasLog::notice('log message from {NAME}',array('NAME' => 'neeke'),'tmp_logger'));

var_dump(SeasLog::getBuffer());

?>

The above example will output something similar to:

bool(true)
bool(true)
bool(true)
array(2) {
  ["/var/log/www/default/20180707.log"]=>
  array(2) {
    [0]=>
    string(81) "2018-07-07 11:45:49 | NOTICE | 73263 | 5b40376d1067c | 1530935149.68 | log message
"
    [1]=>
    string(92) "2018-07-07 11:45:49 | NOTICE | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
  ["/var/log/www/tmp_logger/20180707.log"]=>
  array(1) {
    [0]=>
    string(92) "2018-07-07 11:45:49 | NOTICE | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
}

See Also

  • seaslog.default_template
  • SeasLog::debug() - Record debug log information
  • SeasLog::info() - Record info log information
  • SeasLog::warning() - Record warning log information
  • SeasLog::error() - Record error log information
  • SeasLog::critical() - Record critical log information
  • SeasLog::alert() - Record alert log information
  • SeasLog::emergency() - Record emergency log information
  • SeasLog::log() - The Common Record Log Function


Set SeasLog base path

  • « SeasLog::notice
  • SeasLog::setDatetimeFormat »
  • PHP Manual
  • SeasLog
  • Set SeasLog base path

SeasLog::setBasePath

(PECL seaslog >=1.0.0)

SeasLog::setBasePath — Set SeasLog base path

Description

public static SeasLog::setBasePath ( string $base_path ) : bool

Set SeasLog base path.

Parameters

base_path

String.

Return Values

Return TRUE on setted base path success, FALSE on failure.

Examples

Example #1 SeasLog::setBasePath() example

<?php

/* ... */

?>

The above example will output something similar to:

...


Set SeasLog datetime format style

  • « SeasLog::setBasePath
  • SeasLog::setLogger »
  • PHP Manual
  • SeasLog
  • Set SeasLog datetime format style

SeasLog::setDatetimeFormat

(PECL seaslog >=1.0.0)

SeasLog::setDatetimeFormat — Set SeasLog datetime format style

Description

public static SeasLog::setDatetimeFormat ( string $format ) : bool

Set SeasLog datetime format style.

Warning

This function is currently not documented; only its argument list is available.

Parameters

format

String. Such as `Y-m-d H:i:s` or `Ymd His`. See also first param `format` at date().

Return Values

Return TRUE on setted datetime format success, FALSE on failure.

Examples

Example #1 SeasLog::setDatetimeFormat() example

<?php

var_dump(SeasLog::setDateTimeFormat('Ymd His'));

?>

The above example will output something similar to:

bool(true)

See Also

  • SeasLog::getDateTimeFormat() - Get SeasLog datetime format style


Set SeasLog logger name

  • « SeasLog::setDatetimeFormat
  • SeasLog::setRequestID »
  • PHP Manual
  • SeasLog
  • Set SeasLog logger name

SeasLog::setLogger

(PECL seaslog >=1.0.0)

SeasLog::setLogger — Set SeasLog logger name

Description

public static SeasLog::setLogger ( string $logger ) : bool

Use the Function SeasLog::setLogger() will change the value of function SeasLog::getLastLogger(). Than's mean, SeasLog will record loginfo into the logger directory.

Parameters

logger

Logger name.

Return Values

Return TRUE on created logger disectory success, FALSE on failure.

Examples

Example #1 SeasLog::setLogger() example

<?php

var_dump(SeasLog::setLogger('testModule/testLogger'));

?>

The above example will output something similar to:

bool(true)

See Also

  • SeasLog::getLastLogger() - Get SeasLog last logger path
  • SeasLog::closeLoggerStream() - Manually release stream flow from logger


Set SeasLog request_id differentiated requests

  • « SeasLog::setLogger
  • SeasLog::setRequestVariable »
  • PHP Manual
  • SeasLog
  • Set SeasLog request_id differentiated requests

SeasLog::setRequestID

(PECL seaslog >=1.0.0)

SeasLog::setRequestID — Set SeasLog request_id differentiated requests

Description

public static SeasLog::setRequestID ( string $request_id ) : bool

To distinguish a single request, such as not invoking the SeasLog::setRequestId() function， the unique value generated by the built-in `static char *get_uniqid ()` function is used when the request is initialized.

Parameters

request_id

String.

Return Values

Return TRUE on set request_id success, FALSE on failure.

Examples

Example #1 SeasLog::setRequestID() example

<?php

var_dump(SeasLog::setRequestID(time() . rand()));

?>

The above example will output something similar to:

bool(true)

See Also

  • SeasLog::getRequestID() - Get SeasLog request_id differentiated requests


Manually set SeasLog request variable

  • « SeasLog::setRequestID
  • SeasLog::warning »
  • PHP Manual
  • SeasLog
  • Manually set SeasLog request variable

SeasLog::setRequestVariable

(PECL seaslog >=1.9.0)

SeasLog::setRequestVariable — Manually set SeasLog request variable

Description

public static SeasLog::setRequestVariable ( int $key , string $value ) : bool

Manually set SeasLog request variable.

Parameters

key

Constant int.

  • SEASLOG_REQUEST_VARIABLE_DOMAIN_PORT
  • SEASLOG_REQUEST_VARIABLE_REQUEST_URI
  • SEASLOG_REQUEST_VARIABLE_REQUEST_METHOD
  • SEASLOG_REQUEST_VARIABLE_CLIENT_IP

value

The request variable value.

Return Values

Return TRUE on set success, FALSE on failure.

Examples

Example #1 SeasLog::setRequestVariable() example

<?php

$sDomainPort = 'domain:port';
$sRequestUri = 'uri';
$sRequestMethod = 'method';
$sClientIp = 'client_ip';

$iErrorKey = 1000;

$oSeasLog = new SeasLog();

var_dump($oSeasLog->setRequestVariable(SEASLOG_REQUEST_VARIABLE_DOMAIN_PORT, $sDomainPort));
var_dump($oSeasLog->setRequestVariable(SEASLOG_REQUEST_VARIABLE_REQUEST_URI, $sRequestUri));
var_dump($oSeasLog->setRequestVariable(SEASLOG_REQUEST_VARIABLE_REQUEST_METHOD, $sRequestMethod));
var_dump($oSeasLog->setRequestVariable(SEASLOG_REQUEST_VARIABLE_CLIENT_IP, $sClientIp));

var_dump($oSeasLog->setRequestVariable($iErrorKey,NULL));

var_dump($oSeasLog->getRequestVariable(SEASLOG_REQUEST_VARIABLE_DOMAIN_PORT) == $sDomainPort);
var_dump($oSeasLog->getRequestVariable(SEASLOG_REQUEST_VARIABLE_REQUEST_URI) == $sRequestUri);
var_dump($oSeasLog->getRequestVariable(SEASLOG_REQUEST_VARIABLE_REQUEST_METHOD) == $sRequestMethod);
var_dump($oSeasLog->getRequestVariable(SEASLOG_REQUEST_VARIABLE_CLIENT_IP) == $sClientIp);

var_dump($oSeasLog->getRequestVariable($iErrorKey));

?>

The above example will output something similar to:

bool(true)
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(true)
bool(true)
bool(true)
bool(false)

See Also

  • SeasLog::getRequestVariable() - Get SeasLog request variable


Record warning log information

  • « SeasLog::setRequestVariable
  • SPL »
  • PHP Manual
  • SeasLog
  • Record warning log information

SeasLog::warning

(PECL seaslog >=1.0.0)

SeasLog::warning — Record warning log information

Description

public static SeasLog::warning ( string $message [, array $content [, string $logger ]] ) : bool

Record warning log information.

Note:

"WARNING" - Exceptional occurrences that are not errors. Potentially aberrant information that needs attention and needs to be repaired.

Parameters

message

The log message.

content

The `message` contain placeholders which implementors replace with values from content array. Sush as `message` is `log info from {NAME}` and `content` is `array('NAME' => neeke)`, the log information will `log info from neeke`.

logger

The `logger` cased by the third param would be used right this right now, like a temp logger, when the function SeasLog::setLogger() called in pre content. If `logger` NULL or "", SeasLog will use lastest logger setted by SeasLog::setLogger().

Return Values

Return TRUE on record log information success, FALSE on failure.

Examples

Example #1 SeasLog::warning() example

<?php

var_dump(SeasLog::warning('log message'));

//with content
var_dump(SeasLog::warning('log message from {NAME}',array('NAME' => 'neeke')));

//with tmp logger
var_dump(SeasLog::warning('log message from {NAME}',array('NAME' => 'neeke'),'tmp_logger'));

var_dump(SeasLog::getBuffer());

?>

The above example will output something similar to:

bool(true)
bool(true)
bool(true)
array(2) {
  ["/var/log/www/default/20180707.log"]=>
  array(2) {
    [0]=>
    string(81) "2018-07-07 11:45:49 | WARNING | 73263 | 5b40376d1067c | 1530935149.68 | log message
"
    [1]=>
    string(92) "2018-07-07 11:45:49 | WARNING | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
  ["/var/log/www/tmp_logger/20180707.log"]=>
  array(1) {
    [0]=>
    string(92) "2018-07-07 11:45:49 | WARNING | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
}

See Also

  • seaslog.default_template
  • SeasLog::debug() - Record debug log information
  • SeasLog::info() - Record info log information
  • SeasLog::notice() - Record notice log information
  • SeasLog::error() - Record error log information
  • SeasLog::critical() - Record critical log information
  • SeasLog::alert() - Record alert log information
  • SeasLog::emergency() - Record emergency log information
  • SeasLog::log() - The Common Record Log Function


Standard PHP Library (SPL)

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Datastructures
    • SplDoublyLinkedList — The SplDoublyLinkedList class
    • SplStack — The SplStack class
    • SplQueue — The SplQueue class
    • SplHeap — The SplHeap class
    • SplMaxHeap — The SplMaxHeap class
    • SplMinHeap — The SplMinHeap class
    • SplPriorityQueue — The SplPriorityQueue class
    • SplFixedArray — The SplFixedArray class
    • SplObjectStorage — The SplObjectStorage class
  • Iterators
    • AppendIterator — The AppendIterator class
    • ArrayIterator — The ArrayIterator class
    • CachingIterator — The CachingIterator class
    • CallbackFilterIterator — The CallbackFilterIterator class
    • DirectoryIterator — The DirectoryIterator class
    • EmptyIterator — The EmptyIterator class
    • FilesystemIterator — The FilesystemIterator class
    • FilterIterator — The FilterIterator class
    • GlobIterator — The GlobIterator class
    • InfiniteIterator — The InfiniteIterator class
    • IteratorIterator — The IteratorIterator class
    • LimitIterator — The LimitIterator class
    • MultipleIterator — The MultipleIterator class
    • NoRewindIterator — The NoRewindIterator class
    • ParentIterator — The ParentIterator class
    • RecursiveArrayIterator — The RecursiveArrayIterator class
    • RecursiveCachingIterator — The RecursiveCachingIterator class
    • RecursiveCallbackFilterIterator — The RecursiveCallbackFilterIterator class
    • RecursiveDirectoryIterator — The RecursiveDirectoryIterator class
    • RecursiveFilterIterator — The RecursiveFilterIterator class
    • RecursiveIteratorIterator — The RecursiveIteratorIterator class
    • RecursiveRegexIterator — The RecursiveRegexIterator class
    • RecursiveTreeIterator — The RecursiveTreeIterator class
    • RegexIterator — The RegexIterator class
  • Interfaces
    • Countable — The Countable interface
    • OuterIterator — The OuterIterator interface
    • RecursiveIterator — The RecursiveIterator interface
    • SeekableIterator — The SeekableIterator interface
  • Exceptions
    • BadFunctionCallException — The BadFunctionCallException class
    • BadMethodCallException — The BadMethodCallException class
    • DomainException — The DomainException class
    • InvalidArgumentException — The InvalidArgumentException class
    • LengthException — The LengthException class
    • LogicException — The LogicException class
    • OutOfBoundsException — The OutOfBoundsException class
    • OutOfRangeException — The OutOfRangeException class
    • OverflowException — The OverflowException class
    • RangeException — The RangeException class
    • RuntimeException — The RuntimeException class
    • UnderflowException — The UnderflowException class
    • UnexpectedValueException — The UnexpectedValueException class
  • SPL Functions
    • class_implements — Return the interfaces which are implemented by the given class or interface
    • class_parents — Return the parent classes of the given class
    • class_uses — Return the traits used by the given class
    • iterator_apply — Call a function for every element in an iterator
    • iterator_count — Count the elements in an iterator
    • iterator_to_array — Copy the iterator into an array
    • spl_autoload_call — Try all registered __autoload() functions to load the requested class
    • spl_autoload_extensions — Register and return default file extensions for spl_autoload
    • spl_autoload_functions — Return all registered __autoload() functions
    • spl_autoload_register — Register given function as __autoload() implementation
    • spl_autoload_unregister — Unregister given function as __autoload() implementation
    • spl_autoload — Default implementation for __autoload()
    • spl_classes — Return available SPL classes
    • spl_object_hash — Return hash id for given object
    • spl_object_id — Return the integer object handle for given object
  • File Handling
    • SplFileInfo — The SplFileInfo class
    • SplFileObject — The SplFileObject class
    • SplTempFileObject — The SplTempFileObject class
  • Miscellaneous Classes and Interfaces
    • ArrayObject — The ArrayObject class
    • SplObserver — The SplObserver interface
    • SplSubject — The SplSubject interface


Introduction

The Standard PHP Library (SPL) is a collection of interfaces and classes that are meant to solve common problems.

No external libraries are needed to build this extension and it is available and compiled by default in PHP 5.0.0.

SPL provides a set of standard datastructure, a set of iterators to traverse over objects, a set of interfaces, a set of standard Exceptions, a number of classes to work with files and it provides a set of functions like spl_autoload_register()


Installation

This extension is available and compiled by default in PHP 5.0.0.

Note:

As of PHP 5.3.0 this extension can no longer be disabled and is therefore always 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.

Warning

SPL uses class constants since PHP 5.1. Prior releases use global constants in the form RIT_LEAVES_ONLY.


Datastructures

Table of Contents

  • SplDoublyLinkedList
  • SplStack
  • SplQueue
  • SplHeap
  • SplMaxHeap
  • SplMinHeap
  • SplPriorityQueue
  • SplFixedArray
  • SplObjectStorage

SPL provides a set of standard datastructures. They are grouped here by their underlying implementation which usually defines their general field of application.

Doubly Linked Lists

A Doubly Linked List (DLL) is a list of nodes linked in both directions to each other. Iterator's operations, access to both ends, addition or removal of nodes have a cost of O(1) when the underlying structure is a DLL. It hence provides a decent implementation for stacks and queues.

  • SplDoublyLinkedList
    • SplStack
    • SplQueue

Heaps

Heaps are tree-like structures that follow the heap-property: each node is greater than or equal to its children, when compared using the implemented compare method which is global to the heap.

  • SplHeap
    • SplMaxHeap
    • SplMinHeap
  • SplPriorityQueue

Arrays

Arrays are structures that store the data in a continuous way, accessible via indexes. Don't confuse them with PHP arrays: PHP arrays are in fact implemented as ordered hashtables.

  • SplFixedArray

Map

A map is a datastructure holding key-value pairs. PHP arrays can be seen as maps from integers/strings to values. SPL provides a map from objects to data. This map can also be used as an object set.

  • SplObjectStorage


The SplDoublyLinkedList class

(PHP 5 >= 5.3.0, PHP 7)

Introduction

The SplDoublyLinkedList class provides the main functionalities of a doubly linked list.

Class synopsis

SplDoublyLinkedList implements Iterator , ArrayAccess , Countable {
/* Constants */
const integer IT_MODE_LIFO = 2 ;
const integer IT_MODE_FIFO = 0 ;
const integer IT_MODE_DELETE = 1 ;
const integer IT_MODE_KEEP = 0 ;
/* Methods */
public __construct ( void )
public add ( mixed $index , mixed $newval ) : void
public bottom ( void ) : mixed
public count ( void ) : int
public current ( void ) : mixed
public getIteratorMode ( void ) : int
public isEmpty ( void ) : bool
public key ( void ) : mixed
public next ( void ) : void
public offsetExists ( mixed $index ) : bool
public offsetGet ( mixed $index ) : mixed
public offsetSet ( mixed $index , mixed $newval ) : void
public offsetUnset ( mixed $index ) : void
public pop ( void ) : mixed
public prev ( void ) : void
public push ( mixed $value ) : void
public rewind ( void ) : void
public serialize ( void ) : string
public setIteratorMode ( int $mode ) : void
public shift ( void ) : mixed
public top ( void ) : mixed
public unserialize ( string $serialized ) : void
public unshift ( mixed $value ) : void
public valid ( void ) : bool
}

Predefined Constants

Iteration Direction

SplDoublyLinkedList::IT_MODE_LIFO

The list will be iterated in a last in, first out order, like a stack.

SplDoublyLinkedList::IT_MODE_FIFO

The list will be iterated in a first in, first out order, like a queue.

Iteration Behavior

SplDoublyLinkedList::IT_MODE_DELETE

Iteration will remove the iterated elements.

SplDoublyLinkedList::IT_MODE_KEEP

Iteration will not remove the iterated elements.

Table of Contents

  • SplDoublyLinkedList::add — Add/insert a new value at the specified index
  • SplDoublyLinkedList::bottom — Peeks at the node from the beginning of the doubly linked list
  • SplDoublyLinkedList::__construct — Constructs a new doubly linked list
  • SplDoublyLinkedList::count — Counts the number of elements in the doubly linked list
  • SplDoublyLinkedList::current — Return current array entry
  • SplDoublyLinkedList::getIteratorMode — Returns the mode of iteration
  • SplDoublyLinkedList::isEmpty — Checks whether the doubly linked list is empty
  • SplDoublyLinkedList::key — Return current node index
  • SplDoublyLinkedList::next — Move to next entry
  • SplDoublyLinkedList::offsetExists — Returns whether the requested $index exists
  • SplDoublyLinkedList::offsetGet — Returns the value at the specified $index
  • SplDoublyLinkedList::offsetSet — Sets the value at the specified $index to $newval
  • SplDoublyLinkedList::offsetUnset — Unsets the value at the specified $index
  • SplDoublyLinkedList::pop — Pops a node from the end of the doubly linked list
  • SplDoublyLinkedList::prev — Move to previous entry
  • SplDoublyLinkedList::push — Pushes an element at the end of the doubly linked list
  • SplDoublyLinkedList::rewind — Rewind iterator back to the start
  • SplDoublyLinkedList::serialize — Serializes the storage
  • SplDoublyLinkedList::setIteratorMode — Sets the mode of iteration
  • SplDoublyLinkedList::shift — Shifts a node from the beginning of the doubly linked list
  • SplDoublyLinkedList::top — Peeks at the node from the end of the doubly linked list
  • SplDoublyLinkedList::unserialize — Unserializes the storage
  • SplDoublyLinkedList::unshift — Prepends the doubly linked list with an element
  • SplDoublyLinkedList::valid — Check whether the doubly linked list contains more nodes


Add/insert a new value at the specified index

  • « SplDoublyLinkedList
  • SplDoublyLinkedList::bottom »
  • PHP Manual
  • SplDoublyLinkedList
  • Add/insert a new value at the specified index

SplDoublyLinkedList::add

(PHP 5 >= 5.5.0, PHP 7)

SplDoublyLinkedList::add — Add/insert a new value at the specified index

Description

public SplDoublyLinkedList::add ( mixed $index , mixed $newval ) : void

Insert the value newval at the specified index, shuffling the previous value at that index (and all subsequent values) up through the list.

Parameters

index

The index where the new value is to be inserted.

newval

The new value for the index.

Return Values

No value is returned.

Errors/Exceptions

Throws OutOfRangeException when index is out of bounds or when index cannot be parsed as an integer.


Peeks at the node from the beginning of the doubly linked list

  • « SplDoublyLinkedList::add
  • SplDoublyLinkedList::__construct »
  • PHP Manual
  • SplDoublyLinkedList
  • Peeks at the node from the beginning of the doubly linked list

SplDoublyLinkedList::bottom

(PHP 5 >= 5.3.0, PHP 7)

SplDoublyLinkedList::bottom — Peeks at the node from the beginning of the doubly linked list

Description

public SplDoublyLinkedList::bottom ( void ) : mixed

Parameters

This function has no parameters.

Return Values

The value of the first node.

Errors/Exceptions

Throws RuntimeException when the data-structure is empty.


Constructs a new doubly linked list

  • « SplDoublyLinkedList::bottom
  • SplDoublyLinkedList::count »
  • PHP Manual
  • SplDoublyLinkedList
  • Constructs a new doubly linked list

SplDoublyLinkedList::__construct

(PHP 5 >= 5.3.0, PHP 7)

SplDoublyLinkedList::__construct — Constructs a new doubly linked list

Description

public SplDoublyLinkedList::__construct ( void )

This constructs a new empty doubly linked list.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 SplDoublyLinkedList::__construct() example

<?php
$dll = new SplDoublyLinkedList();

$dll->push(2);
$dll->push(3);
$dll->unshift(5);

var_dump($dll);
?>

The above example will output:

object(SplDoublyLinkedList)#1 (2) {
  ["flags":"SplDoublyLinkedList":private]=>
  int(0)
  ["dllist":"SplDoublyLinkedList":private]=>
  array(3) {
    [0]=>
    int(5)
    [1]=>
    int(2)
    [2]=>
    int(3)
  }
}


Counts the number of elements in the doubly linked list

  • « SplDoublyLinkedList::__construct
  • SplDoublyLinkedList::current »
  • PHP Manual
  • SplDoublyLinkedList
  • Counts the number of elements in the doubly linked list

SplDoublyLinkedList::count

(PHP 5 >= 5.3.0, PHP 7)

SplDoublyLinkedList::count — Counts the number of elements in the doubly linked list

Description

public SplDoublyLinkedList::count ( void ) : int

Parameters

This function has no parameters.

Return Values

Returns the number of elements in the doubly linked list.


Return current array entry

  • « SplDoublyLinkedList::count
  • SplDoublyLinkedList::getIteratorMode »
  • PHP Manual
  • SplDoublyLinkedList
  • Return current array entry

SplDoublyLinkedList::current

(PHP 5 >= 5.3.0, PHP 7)

SplDoublyLinkedList::current — Return current array entry

Description

public SplDoublyLinkedList::current ( void ) : mixed

Get the current doubly linked list node.

Parameters

This function has no parameters.

Return Values

The current node value.


Returns the mode of iteration

  • « SplDoublyLinkedList::current
  • SplDoublyLinkedList::isEmpty »
  • PHP Manual
  • SplDoublyLinkedList
  • Returns the mode of iteration

SplDoublyLinkedList::getIteratorMode

(PHP 5 >= 5.3.0, PHP 7)

SplDoublyLinkedList::getIteratorMode — Returns the mode of iteration

Description

public SplDoublyLinkedList::getIteratorMode ( void ) : int

Parameters

This function has no parameters.

Return Values

Returns the different modes and flags that affect the iteration.


Checks whether the doubly linked list is empty

  • « SplDoublyLinkedList::getIteratorMode
  • SplDoublyLinkedList::key »
  • PHP Manual
  • SplDoublyLinkedList
  • Checks whether the doubly linked list is empty

SplDoublyLinkedList::isEmpty

(PHP 5 >= 5.3.0, PHP 7)

SplDoublyLinkedList::isEmpty — Checks whether the doubly linked list is empty

Description

public SplDoublyLinkedList::isEmpty ( void ) : bool

Parameters

This function has no parameters.

Return Values

Returns whether the doubly linked list is empty.


Return current node index

  • « SplDoublyLinkedList::isEmpty
  • SplDoublyLinkedList::next »
  • PHP Manual
  • SplDoublyLinkedList
  • Return current node index

SplDoublyLinkedList::key

(PHP 5 >= 5.3.0, PHP 7)

SplDoublyLinkedList::key — Return current node index

Description

public SplDoublyLinkedList::key ( void ) : mixed

This function returns the current node index

Parameters

This function has no parameters.

Return Values

The current node index.


Move to next entry

  • « SplDoublyLinkedList::key
  • SplDoublyLinkedList::offsetExists »
  • PHP Manual
  • SplDoublyLinkedList
  • Move to next entry

SplDoublyLinkedList::next

(PHP 5 >= 5.3.0, PHP 7)

SplDoublyLinkedList::next — Move to next entry

Description

public SplDoublyLinkedList::next ( void ) : void

Move the iterator to the next node.

Parameters

This function has no parameters.

Return Values

No value is returned.


Returns whether the requested $index exists

  • « SplDoublyLinkedList::next
  • SplDoublyLinkedList::offsetGet »
  • PHP Manual
  • SplDoublyLinkedList
  • Returns whether the requested $index exists

SplDoublyLinkedList::offsetExists

(PHP 5 >= 5.3.0, PHP 7)

SplDoublyLinkedList::offsetExists — Returns whether the requested $index exists

Description

public SplDoublyLinkedList::offsetExists ( mixed $index ) : bool

Parameters

index

The index being checked.

Return Values

TRUE if the requested index exists, otherwise FALSE


Returns the value at the specified $index

  • « SplDoublyLinkedList::offsetExists
  • SplDoublyLinkedList::offsetSet »
  • PHP Manual
  • SplDoublyLinkedList
  • Returns the value at the specified $index

SplDoublyLinkedList::offsetGet

(PHP 5 >= 5.3.0, PHP 7)

SplDoublyLinkedList::offsetGet — Returns the value at the specified $index

Description

public SplDoublyLinkedList::offsetGet ( mixed $index ) : mixed

Parameters

index

The index with the value.

Return Values

The value at the specified index.

Errors/Exceptions

Throws OutOfRangeException when index is out of bounds or when index cannot be parsed as an integer.


Sets the value at the specified $index to $newval

  • « SplDoublyLinkedList::offsetGet
  • SplDoublyLinkedList::offsetUnset »
  • PHP Manual
  • SplDoublyLinkedList
  • Sets the value at the specified $index to $newval

SplDoublyLinkedList::offsetSet

(PHP 5 >= 5.3.0, PHP 7)

SplDoublyLinkedList::offsetSet — Sets the value at the specified $index to $newval

Description

public SplDoublyLinkedList::offsetSet ( mixed $index , mixed $newval ) : void

Sets the value at the specified index to newval.

Parameters

index

The index being set.

newval

The new value for the index.

Return Values

No value is returned.

Errors/Exceptions

Throws OutOfRangeException when index is out of bounds or when index cannot be parsed as an integer.


Unsets the value at the specified $index

  • « SplDoublyLinkedList::offsetSet
  • SplDoublyLinkedList::pop »
  • PHP Manual
  • SplDoublyLinkedList
  • Unsets the value at the specified $index

SplDoublyLinkedList::offsetUnset

(PHP 5 >= 5.3.0, PHP 7)

SplDoublyLinkedList::offsetUnset — Unsets the value at the specified $index

Description

public SplDoublyLinkedList::offsetUnset ( mixed $index ) : void

Unsets the value at the specified index.

Parameters

index

The index being unset.

Return Values

No value is returned.

Errors/Exceptions

Throws OutOfRangeException when index is out of bounds or when index cannot be parsed as an integer.


Pops a node from the end of the doubly linked list

  • « SplDoublyLinkedList::offsetUnset
  • SplDoublyLinkedList::prev »
  • PHP Manual
  • SplDoublyLinkedList
  • Pops a node from the end of the doubly linked list

SplDoublyLinkedList::pop

(PHP 5 >= 5.3.0, PHP 7)

SplDoublyLinkedList::pop — Pops a node from the end of the doubly linked list

Description

public SplDoublyLinkedList::pop ( void ) : mixed

Parameters

This function has no parameters.

Return Values

The value of the popped node.

Errors/Exceptions

Throws RuntimeException when the data-structure is empty.


Move to previous entry

  • « SplDoublyLinkedList::pop
  • SplDoublyLinkedList::push »
  • PHP Manual
  • SplDoublyLinkedList
  • Move to previous entry

SplDoublyLinkedList::prev

(PHP 5 >= 5.3.0, PHP 7)

SplDoublyLinkedList::prev — Move to previous entry

Description

public SplDoublyLinkedList::prev ( void ) : void

Move the iterator to the previous node.

Parameters

This function has no parameters.

Return Values

No value is returned.


Pushes an element at the end of the doubly linked list

  • « SplDoublyLinkedList::prev
  • SplDoublyLinkedList::rewind »
  • PHP Manual
  • SplDoublyLinkedList
  • Pushes an element at the end of the doubly linked list

SplDoublyLinkedList::push

(PHP 5 >= 5.3.0, PHP 7)

SplDoublyLinkedList::push — Pushes an element at the end of the doubly linked list

Description

public SplDoublyLinkedList::push ( mixed $value ) : void

Pushes value at the end of the doubly linked list.

Parameters

value

The value to push.

Return Values

No value is returned.


Rewind iterator back to the start

  • « SplDoublyLinkedList::push
  • SplDoublyLinkedList::serialize »
  • PHP Manual
  • SplDoublyLinkedList
  • Rewind iterator back to the start

SplDoublyLinkedList::rewind

(PHP 5 >= 5.3.0, PHP 7)

SplDoublyLinkedList::rewind — Rewind iterator back to the start

Description

public SplDoublyLinkedList::rewind ( void ) : void

This rewinds the iterator to the beginning.

Parameters

This function has no parameters.

Return Values

No value is returned.


Serializes the storage

  • « SplDoublyLinkedList::rewind
  • SplDoublyLinkedList::setIteratorMode »
  • PHP Manual
  • SplDoublyLinkedList
  • Serializes the storage

SplDoublyLinkedList::serialize

(PHP 5 >= 5.4.0, PHP 7)

SplDoublyLinkedList::serialize — Serializes the storage

Description

public SplDoublyLinkedList::serialize ( void ) : string

Serializes the storage.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The serialized string.

See Also

  • SplDoublyLinkedList::unserialize() - Unserializes the storage


Sets the mode of iteration

  • « SplDoublyLinkedList::serialize
  • SplDoublyLinkedList::shift »
  • PHP Manual
  • SplDoublyLinkedList
  • Sets the mode of iteration

SplDoublyLinkedList::setIteratorMode

(PHP 5 >= 5.3.0, PHP 7)

SplDoublyLinkedList::setIteratorMode — Sets the mode of iteration

Description

public SplDoublyLinkedList::setIteratorMode ( int $mode ) : void

Parameters

mode

There are two orthogonal sets of modes that can be set:

  • The direction of the iteration (either one or the other):
    • SplDoublyLinkedList::IT_MODE_LIFO (Stack style)
    • SplDoublyLinkedList::IT_MODE_FIFO (Queue style)
  • The behavior of the iterator (either one or the other):
    • SplDoublyLinkedList::IT_MODE_DELETE (Elements are deleted by the iterator)
    • SplDoublyLinkedList::IT_MODE_KEEP (Elements are traversed by the iterator)

The default mode is: SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_KEEP

Return Values

No value is returned.


Shifts a node from the beginning of the doubly linked list

  • « SplDoublyLinkedList::setIteratorMode
  • SplDoublyLinkedList::top »
  • PHP Manual
  • SplDoublyLinkedList
  • Shifts a node from the beginning of the doubly linked list

SplDoublyLinkedList::shift

(PHP 5 >= 5.3.0, PHP 7)

SplDoublyLinkedList::shift — Shifts a node from the beginning of the doubly linked list

Description

public SplDoublyLinkedList::shift ( void ) : mixed

Parameters

This function has no parameters.

Return Values

The value of the shifted node.

Errors/Exceptions

Throws RuntimeException when the data-structure is empty.


Peeks at the node from the end of the doubly linked list

  • « SplDoublyLinkedList::shift
  • SplDoublyLinkedList::unserialize »
  • PHP Manual
  • SplDoublyLinkedList
  • Peeks at the node from the end of the doubly linked list

SplDoublyLinkedList::top

(PHP 5 >= 5.3.0, PHP 7)

SplDoublyLinkedList::top — Peeks at the node from the end of the doubly linked list

Description

public SplDoublyLinkedList::top ( void ) : mixed

Parameters

This function has no parameters.

Return Values

The value of the last node.

Errors/Exceptions

Throws RuntimeException when the data-structure is empty.


Unserializes the storage

  • « SplDoublyLinkedList::top
  • SplDoublyLinkedList::unshift »
  • PHP Manual
  • SplDoublyLinkedList
  • Unserializes the storage

SplDoublyLinkedList::unserialize

(PHP 5 >= 5.4.0, PHP 7)

SplDoublyLinkedList::unserialize — Unserializes the storage

Description

public SplDoublyLinkedList::unserialize ( string $serialized ) : void

Unserializes the storage, from SplDoublyLinkedList::serialize().

Warning

This function is currently not documented; only its argument list is available.

Parameters

serialized

The serialized string.

Return Values

No value is returned.

See Also

  • SplDoublyLinkedList::serialize() - Serializes the storage


Prepends the doubly linked list with an element

  • « SplDoublyLinkedList::unserialize
  • SplDoublyLinkedList::valid »
  • PHP Manual
  • SplDoublyLinkedList
  • Prepends the doubly linked list with an element

SplDoublyLinkedList::unshift

(PHP 5 >= 5.3.0, PHP 7)

SplDoublyLinkedList::unshift — Prepends the doubly linked list with an element

Description

public SplDoublyLinkedList::unshift ( mixed $value ) : void

Prepends value at the beginning of the doubly linked list.

Parameters

value

The value to unshift.

Return Values

No value is returned.


Check whether the doubly linked list contains more nodes

  • « SplDoublyLinkedList::unshift
  • SplStack »
  • PHP Manual
  • SplDoublyLinkedList
  • Check whether the doubly linked list contains more nodes

SplDoublyLinkedList::valid

(PHP 5 >= 5.3.0, PHP 7)

SplDoublyLinkedList::valid — Check whether the doubly linked list contains more nodes

Description

public SplDoublyLinkedList::valid ( void ) : bool

Checks if the doubly linked list contains any more nodes.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the doubly linked list contains any more nodes, FALSE otherwise.


The SplStack class

(PHP 5 >= 5.3.0, PHP 7)

Introduction

The SplStack class provides the main functionalities of a stack implemented using a doubly linked list.

Class synopsis

SplStack extends SplDoublyLinkedList implements Iterator , ArrayAccess , Countable {
/* Methods */
__construct ( void )
setIteratorMode ( int $mode ) : void
/* Inherited methods */
public SplDoublyLinkedList::add ( mixed $index , mixed $newval ) : void
public SplDoublyLinkedList::bottom ( void ) : mixed
public SplDoublyLinkedList::count ( void ) : int
public SplDoublyLinkedList::current ( void ) : mixed
public SplDoublyLinkedList::getIteratorMode ( void ) : int
public SplDoublyLinkedList::isEmpty ( void ) : bool
public SplDoublyLinkedList::key ( void ) : mixed
public SplDoublyLinkedList::next ( void ) : void
public SplDoublyLinkedList::offsetExists ( mixed $index ) : bool
public SplDoublyLinkedList::offsetGet ( mixed $index ) : mixed
public SplDoublyLinkedList::offsetSet ( mixed $index , mixed $newval ) : void
public SplDoublyLinkedList::offsetUnset ( mixed $index ) : void
public SplDoublyLinkedList::pop ( void ) : mixed
public SplDoublyLinkedList::prev ( void ) : void
public SplDoublyLinkedList::push ( mixed $value ) : void
public SplDoublyLinkedList::rewind ( void ) : void
public SplDoublyLinkedList::serialize ( void ) : string
public SplDoublyLinkedList::setIteratorMode ( int $mode ) : void
public SplDoublyLinkedList::shift ( void ) : mixed
public SplDoublyLinkedList::top ( void ) : mixed
public SplDoublyLinkedList::unserialize ( string $serialized ) : void
public SplDoublyLinkedList::unshift ( mixed $value ) : void
public SplDoublyLinkedList::valid ( void ) : bool
}

Table of Contents

  • SplStack::__construct — Constructs a new stack implemented using a doubly linked list
  • SplStack::setIteratorMode — Sets the mode of iteration


Constructs a new stack implemented using a doubly linked list

  • « SplStack
  • SplStack::setIteratorMode »
  • PHP Manual
  • SplStack
  • Constructs a new stack implemented using a doubly linked list

SplStack::__construct

(PHP 5 >= 5.3.0, PHP 7)

SplStack::__construct — Constructs a new stack implemented using a doubly linked list

Description

SplStack::__construct ( void )

This constructs a new empty stack.

Note:

This method automatically sets the iterator mode to SplDoublyLinkedList::IT_MODE_LIFO.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 SplStack::__construct() example

<?php
$q = new SplStack();

$q[] = 1;
$q[] = 2;
$q[] = 3;

foreach ($q as $elem)  {
 echo $elem."\n";
}
?>

The above example will output:

3
2
1


Sets the mode of iteration

  • « SplStack::__construct
  • SplQueue »
  • PHP Manual
  • SplStack
  • Sets the mode of iteration

SplStack::setIteratorMode

(PHP 5 >= 5.3.0, PHP 7)

SplStack::setIteratorMode — Sets the mode of iteration

Description

SplStack::setIteratorMode ( int $mode ) : void

Parameters

mode

There is only one iteration parameter you can modify.

  • The behavior of the iterator (either one or the other):
    • SplDoublyLinkedList::IT_MODE_DELETE (Elements are deleted by the iterator)
    • SplDoublyLinkedList::IT_MODE_KEEP (Elements are traversed by the iterator)

The default mode is 0x2 : SplDoublyLinkedList::IT_MODE_LIFO | SplDoublyLinkedList::IT_MODE_KEEP

Warning

The direction of iteration can no longer be changed for SplStacks. Trying to do so will result in a RuntimeException being thrown.

Return Values

No value is returned.


The SplQueue class

(PHP 5 >= 5.3.0, PHP 7)

Introduction

The SplQueue class provides the main functionalities of a queue implemented using a doubly linked list.

Class synopsis

SplQueue extends SplDoublyLinkedList implements Iterator , ArrayAccess , Countable {
/* Methods */
__construct ( void )
dequeue ( void ) : mixed
enqueue ( mixed $value ) : void
setIteratorMode ( int $mode ) : void
/* Inherited methods */
public SplDoublyLinkedList::add ( mixed $index , mixed $newval ) : void
public SplDoublyLinkedList::bottom ( void ) : mixed
public SplDoublyLinkedList::count ( void ) : int
public SplDoublyLinkedList::current ( void ) : mixed
public SplDoublyLinkedList::getIteratorMode ( void ) : int
public SplDoublyLinkedList::isEmpty ( void ) : bool
public SplDoublyLinkedList::key ( void ) : mixed
public SplDoublyLinkedList::next ( void ) : void
public SplDoublyLinkedList::offsetExists ( mixed $index ) : bool
public SplDoublyLinkedList::offsetGet ( mixed $index ) : mixed
public SplDoublyLinkedList::offsetSet ( mixed $index , mixed $newval ) : void
public SplDoublyLinkedList::offsetUnset ( mixed $index ) : void
public SplDoublyLinkedList::pop ( void ) : mixed
public SplDoublyLinkedList::prev ( void ) : void
public SplDoublyLinkedList::push ( mixed $value ) : void
public SplDoublyLinkedList::rewind ( void ) : void
public SplDoublyLinkedList::serialize ( void ) : string
public SplDoublyLinkedList::setIteratorMode ( int $mode ) : void
public SplDoublyLinkedList::shift ( void ) : mixed
public SplDoublyLinkedList::top ( void ) : mixed
public SplDoublyLinkedList::unserialize ( string $serialized ) : void
public SplDoublyLinkedList::unshift ( mixed $value ) : void
public SplDoublyLinkedList::valid ( void ) : bool
}

Table of Contents

  • SplQueue::__construct — Constructs a new queue implemented using a doubly linked list
  • SplQueue::dequeue — Dequeues a node from the queue
  • SplQueue::enqueue — Adds an element to the queue
  • SplQueue::setIteratorMode — Sets the mode of iteration


Constructs a new queue implemented using a doubly linked list

  • « SplQueue
  • SplQueue::dequeue »
  • PHP Manual
  • SplQueue
  • Constructs a new queue implemented using a doubly linked list

SplQueue::__construct

(PHP 5 >= 5.3.0, PHP 7)

SplQueue::__construct — Constructs a new queue implemented using a doubly linked list

Description

SplQueue::__construct ( void )

This constructs a new empty queue.

Note:

This method automatically sets the iterator mode to SplDoublyLinkedList::IT_MODE_FIFO.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 SplQueue::__construct() example

<?php
$q = new SplQueue();

$q[] = 1;
$q[] = 2;
$q[] = 3;

foreach ($q as $elem)  {
 echo $elem."\n";
}
?>

The above example will output:

1
2
3

Example #2 Efficiently handling tasks with SplQueue

<?php
$q = new SplQueue();
$q->setIteratorMode(SplQueue::IT_MODE_DELETE);

// ... enqueue some tasks on the queue ...

// process them
foreach ($q as $task) {
    // ... process $task ...

    // add new tasks on the queue
    $q[] = $newTask;
    // ...
}
?>


Dequeues a node from the queue

  • « SplQueue::__construct
  • SplQueue::enqueue »
  • PHP Manual
  • SplQueue
  • Dequeues a node from the queue

SplQueue::dequeue

(PHP 5 >= 5.3.0, PHP 7)

SplQueue::dequeue — Dequeues a node from the queue

Description

SplQueue::dequeue ( void ) : mixed

Dequeues value from the top of the queue.

Note:

SplQueue::dequeue() is an alias of SplDoublyLinkedList::shift().

Parameters

This function has no parameters.

Return Values

The value of the dequeued node.


Adds an element to the queue

  • « SplQueue::dequeue
  • SplQueue::setIteratorMode »
  • PHP Manual
  • SplQueue
  • Adds an element to the queue

SplQueue::enqueue

(PHP 5 >= 5.3.0, PHP 7)

SplQueue::enqueue — Adds an element to the queue

Description

SplQueue::enqueue ( mixed $value ) : void

Enqueues value at the end of the queue.

Note:

SplQueue::enqueue() is an alias of SplDoublyLinkedList::push().

Parameters

value

The value to enqueue.

Return Values

No value is returned.


Sets the mode of iteration

  • « SplQueue::enqueue
  • SplHeap »
  • PHP Manual
  • SplQueue
  • Sets the mode of iteration

SplQueue::setIteratorMode

(PHP 5 >= 5.3.0, PHP 7)

SplQueue::setIteratorMode — Sets the mode of iteration

Description

SplQueue::setIteratorMode ( int $mode ) : void

Parameters

mode

There is only one iteration parameter you can modify.

  • The behavior of the iterator (either one or the other):
    • SplDoublyLinkedList::IT_MODE_DELETE (Elements are deleted by the iterator)
    • SplDoublyLinkedList::IT_MODE_KEEP (Elements are traversed by the iterator)

The default mode is: SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_KEEP

Warning

The direction of iteration can not be changed for SplQueues, it is always SplDoublyLinkedList::IT_MODE_FIFO.

Return Values

No value is returned.

Errors/Exceptions

Throws a RuntimeException on trying to change the direction of iteration by using SplDoublyLinkedList::IT_MODE_LIFO.


The SplHeap class

(PHP 5 >= 5.3.0, PHP 7)

Introduction

The SplHeap class provides the main functionalities of a Heap.

Class synopsis

abstract SplHeap implements Iterator , Countable {
/* Methods */
public __construct ( void )
abstract protected compare ( mixed $value1 , mixed $value2 ) : int
public count ( void ) : int
public current ( void ) : mixed
public extract ( void ) : mixed
public insert ( mixed $value ) : void
public isCorrupted ( void ) : bool
public isEmpty ( void ) : bool
public key ( void ) : mixed
public next ( void ) : void
public recoverFromCorruption ( void ) : void
public rewind ( void ) : void
public top ( void ) : mixed
public valid ( void ) : bool
}

Table of Contents

  • SplHeap::compare — Compare elements in order to place them correctly in the heap while sifting up
  • SplHeap::__construct — Constructs a new empty heap
  • SplHeap::count — Counts the number of elements in the heap
  • SplHeap::current — Return current node pointed by the iterator
  • SplHeap::extract — Extracts a node from top of the heap and sift up
  • SplHeap::insert — Inserts an element in the heap by sifting it up
  • SplHeap::isCorrupted — Tells if the heap is in a corrupted state
  • SplHeap::isEmpty — Checks whether the heap is empty
  • SplHeap::key — Return current node index
  • SplHeap::next — Move to the next node
  • SplHeap::recoverFromCorruption — Recover from the corrupted state and allow further actions on the heap
  • SplHeap::rewind — Rewind iterator back to the start (no-op)
  • SplHeap::top — Peeks at the node from the top of the heap
  • SplHeap::valid — Check whether the heap contains more nodes


Compare elements in order to place them correctly in the heap while sifting up

  • « SplHeap
  • SplHeap::__construct »
  • PHP Manual
  • SplHeap
  • Compare elements in order to place them correctly in the heap while sifting up

SplHeap::compare

(PHP 5 >= 5.3.0, PHP 7)

SplHeap::compare — Compare elements in order to place them correctly in the heap while sifting up

Description

abstract protected SplHeap::compare ( mixed $value1 , mixed $value2 ) : int

Compare value1 with value2.

Warning

Throwing exceptions in SplHeap::compare() can corrupt the Heap and place it in a blocked state. You can unblock it by calling SplHeap::recoverFromCorruption(). However, some elements might not be placed correctly and it may hence break the heap-property.

Parameters

value1

The value of the first node being compared.

value2

The value of the second node being compared.

Return Values

Result of the comparison, positive integer if value1 is greater than value2, 0 if they are equal, negative integer otherwise.

Note:

Having multiple elements with the same value in a Heap is not recommended. They will end up in an arbitrary relative position.


Constructs a new empty heap

  • « SplHeap::compare
  • SplHeap::count »
  • PHP Manual
  • SplHeap
  • Constructs a new empty heap

SplHeap::__construct

(PHP 5 >= 5.3.0, PHP 7)

SplHeap::__construct — Constructs a new empty heap

Description

public SplHeap::__construct ( void )

This constructs a new empty heap.

Parameters

This function has no parameters.

Return Values

No value is returned.


Counts the number of elements in the heap

  • « SplHeap::__construct
  • SplHeap::current »
  • PHP Manual
  • SplHeap
  • Counts the number of elements in the heap

SplHeap::count

(PHP 5 >= 5.3.0, PHP 7)

SplHeap::count — Counts the number of elements in the heap

Description

public SplHeap::count ( void ) : int

Parameters

This function has no parameters.

Return Values

Returns the number of elements in the heap.


Return current node pointed by the iterator

  • « SplHeap::count
  • SplHeap::extract »
  • PHP Manual
  • SplHeap
  • Return current node pointed by the iterator

SplHeap::current

(PHP 5 >= 5.3.0, PHP 7)

SplHeap::current — Return current node pointed by the iterator

Description

public SplHeap::current ( void ) : mixed

Get the current datastructure node.

Parameters

This function has no parameters.

Return Values

The current node value.


Extracts a node from top of the heap and sift up

  • « SplHeap::current
  • SplHeap::insert »
  • PHP Manual
  • SplHeap
  • Extracts a node from top of the heap and sift up

SplHeap::extract

(PHP 5 >= 5.3.0, PHP 7)

SplHeap::extract — Extracts a node from top of the heap and sift up

Description

public SplHeap::extract ( void ) : mixed

Parameters

This function has no parameters.

Return Values

The value of the extracted node.

Errors/Exceptions

Throws RuntimeException when the data-structure is empty.


Inserts an element in the heap by sifting it up

  • « SplHeap::extract
  • SplHeap::isCorrupted »
  • PHP Manual
  • SplHeap
  • Inserts an element in the heap by sifting it up

SplHeap::insert

(PHP 5 >= 5.3.0, PHP 7)

SplHeap::insert — Inserts an element in the heap by sifting it up

Description

public SplHeap::insert ( mixed $value ) : void

Insert value in the heap.

Parameters

value

The value to insert.

Return Values

No value is returned.


Tells if the heap is in a corrupted state

  • « SplHeap::insert
  • SplHeap::isEmpty »
  • PHP Manual
  • SplHeap
  • Tells if the heap is in a corrupted state

SplHeap::isCorrupted

(PHP 7)

SplHeap::isCorrupted — Tells if the heap is in a corrupted state

Description

public SplHeap::isCorrupted ( void ) : bool

Parameters

This function has no parameters.

Return Values

Returns TRUE if the heap is corrupted, FALSE otherwise.


Checks whether the heap is empty

  • « SplHeap::isCorrupted
  • SplHeap::key »
  • PHP Manual
  • SplHeap
  • Checks whether the heap is empty

SplHeap::isEmpty

(PHP 5 >= 5.3.0, PHP 7)

SplHeap::isEmpty — Checks whether the heap is empty

Description

public SplHeap::isEmpty ( void ) : bool

Parameters

This function has no parameters.

Return Values

Returns whether the heap is empty.


Return current node index

  • « SplHeap::isEmpty
  • SplHeap::next »
  • PHP Manual
  • SplHeap
  • Return current node index

SplHeap::key

(PHP 5 >= 5.3.0, PHP 7)

SplHeap::key — Return current node index

Description

public SplHeap::key ( void ) : mixed

This function returns the current node index

Parameters

This function has no parameters.

Return Values

The current node index.


Move to the next node

  • « SplHeap::key
  • SplHeap::recoverFromCorruption »
  • PHP Manual
  • SplHeap
  • Move to the next node

SplHeap::next

(PHP 5 >= 5.3.0, PHP 7)

SplHeap::next — Move to the next node

Description

public SplHeap::next ( void ) : void

Move to the next node. This will delete the top node of the heap.

Parameters

This function has no parameters.

Return Values

No value is returned.


Recover from the corrupted state and allow further actions on the heap

  • « SplHeap::next
  • SplHeap::rewind »
  • PHP Manual
  • SplHeap
  • Recover from the corrupted state and allow further actions on the heap

SplHeap::recoverFromCorruption

(PHP 5 >= 5.3.0, PHP 7)

SplHeap::recoverFromCorruption — Recover from the corrupted state and allow further actions on the heap

Description

public SplHeap::recoverFromCorruption ( void ) : void

Parameters

This function has no parameters.

Return Values

No value is returned.


Rewind iterator back to the start (no-op)

  • « SplHeap::recoverFromCorruption
  • SplHeap::top »
  • PHP Manual
  • SplHeap
  • Rewind iterator back to the start (no-op)

SplHeap::rewind

(PHP 5 >= 5.3.0, PHP 7)

SplHeap::rewind — Rewind iterator back to the start (no-op)

Description

public SplHeap::rewind ( void ) : void

This rewinds the iterator to the beginning. This is a no-op for heaps as the iterator is virtual and in fact never moves from the top of the heap.

Parameters

This function has no parameters.

Return Values

No value is returned.


Peeks at the node from the top of the heap

  • « SplHeap::rewind
  • SplHeap::valid »
  • PHP Manual
  • SplHeap
  • Peeks at the node from the top of the heap

SplHeap::top

(PHP 5 >= 5.3.0, PHP 7)

SplHeap::top — Peeks at the node from the top of the heap

Description

public SplHeap::top ( void ) : mixed

Parameters

This function has no parameters.

Return Values

The value of the node on the top.

Errors/Exceptions

Throws RuntimeException when the data-structure is empty.


Check whether the heap contains more nodes

  • « SplHeap::top
  • SplMaxHeap »
  • PHP Manual
  • SplHeap
  • Check whether the heap contains more nodes

SplHeap::valid

(PHP 5 >= 5.3.0, PHP 7)

SplHeap::valid — Check whether the heap contains more nodes

Description

public SplHeap::valid ( void ) : bool

Checks if the heap contains any more nodes.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the heap contains any more nodes, FALSE otherwise.


The SplMaxHeap class

(PHP 5 >= 5.3.0, PHP 7)

Introduction

The SplMaxHeap class provides the main functionalities of a heap, keeping the maximum on the top.

Class synopsis

SplMaxHeap extends SplHeap implements Iterator , Countable {
/* Methods */
protected compare ( mixed $value1 , mixed $value2 ) : int
/* Inherited methods */
abstract protected SplHeap::compare ( mixed $value1 , mixed $value2 ) : int
public SplHeap::count ( void ) : int
public SplHeap::current ( void ) : mixed
public SplHeap::extract ( void ) : mixed
public SplHeap::insert ( mixed $value ) : void
public SplHeap::isCorrupted ( void ) : bool
public SplHeap::isEmpty ( void ) : bool
public SplHeap::key ( void ) : mixed
public SplHeap::next ( void ) : void
public SplHeap::recoverFromCorruption ( void ) : void
public SplHeap::rewind ( void ) : void
public SplHeap::top ( void ) : mixed
public SplHeap::valid ( void ) : bool
}

Table of Contents

  • SplMaxHeap::compare — Compare elements in order to place them correctly in the heap while sifting up


Compare elements in order to place them correctly in the heap while sifting up

  • « SplMaxHeap
  • SplMinHeap »
  • PHP Manual
  • SplMaxHeap
  • Compare elements in order to place them correctly in the heap while sifting up

SplMaxHeap::compare

(PHP 5 >= 5.3.0, PHP 7)

SplMaxHeap::compare — Compare elements in order to place them correctly in the heap while sifting up

Description

protected SplMaxHeap::compare ( mixed $value1 , mixed $value2 ) : int

Compare value1 with value2.

Parameters

value1

The value of the first node being compared.

value2

The value of the second node being compared.

Return Values

Result of the comparison, positive integer if value1 is greater than value2, 0 if they are equal, negative integer otherwise.

Note:

Having multiple elements with the same value in a Heap is not recommended. They will end up in an arbitrary relative position.


The SplMinHeap class

(PHP 5 >= 5.3.0, PHP 7)

Introduction

The SplMinHeap class provides the main functionalities of a heap, keeping the minimum on the top.

Class synopsis

SplMinHeap extends SplHeap implements Iterator , Countable {
/* Methods */
protected compare ( mixed $value1 , mixed $value2 ) : int
/* Inherited methods */
abstract protected SplHeap::compare ( mixed $value1 , mixed $value2 ) : int
public SplHeap::count ( void ) : int
public SplHeap::current ( void ) : mixed
public SplHeap::extract ( void ) : mixed
public SplHeap::insert ( mixed $value ) : void
public SplHeap::isCorrupted ( void ) : bool
public SplHeap::isEmpty ( void ) : bool
public SplHeap::key ( void ) : mixed
public SplHeap::next ( void ) : void
public SplHeap::recoverFromCorruption ( void ) : void
public SplHeap::rewind ( void ) : void
public SplHeap::top ( void ) : mixed
public SplHeap::valid ( void ) : bool
}

Table of Contents

  • SplMinHeap::compare — Compare elements in order to place them correctly in the heap while sifting up


Compare elements in order to place them correctly in the heap while sifting up

  • « SplMinHeap
  • SplPriorityQueue »
  • PHP Manual
  • SplMinHeap
  • Compare elements in order to place them correctly in the heap while sifting up

SplMinHeap::compare

(PHP 5 >= 5.3.0, PHP 7)

SplMinHeap::compare — Compare elements in order to place them correctly in the heap while sifting up

Description

protected SplMinHeap::compare ( mixed $value1 , mixed $value2 ) : int

Compare value1 with value2.

Parameters

value1

The value of the first node being compared.

value2

The value of the second node being compared.

Return Values

Result of the comparison, positive integer if value1 is lower than value2, 0 if they are equal, negative integer otherwise.

Note:

Having multiple elements with the same value in a Heap is not recommended. They will end up in an arbitrary relative position.


The SplPriorityQueue class

(PHP 5 >= 5.3.0, PHP 7)

Introduction

The SplPriorityQueue class provides the main functionalities of a prioritized queue, implemented using a max heap.

Note: The order of elements with identical priority is undefined. It may differ from the order in which they have been inserted.

Class synopsis

SplPriorityQueue implements Iterator , Countable {
/* Methods */
public __construct ( void )
public compare ( mixed $priority1 , mixed $priority2 ) : int
public count ( void ) : int
public current ( void ) : mixed
public extract ( void ) : mixed
public getExtractFlags ( void ) : int
public insert ( mixed $value , mixed $priority ) : bool
public isCorrupted ( void ) : bool
public isEmpty ( void ) : bool
public key ( void ) : mixed
public next ( void ) : void
public recoverFromCorruption ( void ) : void
public rewind ( void ) : void
public setExtractFlags ( int $flags ) : void
public top ( void ) : mixed
public valid ( void ) : bool
}

Table of Contents

  • SplPriorityQueue::compare — Compare priorities in order to place elements correctly in the heap while sifting up
  • SplPriorityQueue::__construct — Constructs a new empty queue
  • SplPriorityQueue::count — Counts the number of elements in the queue
  • SplPriorityQueue::current — Return current node pointed by the iterator
  • SplPriorityQueue::extract — Extracts a node from top of the heap and sift up
  • SplPriorityQueue::getExtractFlags — Get the flags of extraction
  • SplPriorityQueue::insert — Inserts an element in the queue by sifting it up
  • SplPriorityQueue::isCorrupted — Tells if the priority queue is in a corrupted state
  • SplPriorityQueue::isEmpty — Checks whether the queue is empty
  • SplPriorityQueue::key — Return current node index
  • SplPriorityQueue::next — Move to the next node
  • SplPriorityQueue::recoverFromCorruption — Recover from the corrupted state and allow further actions on the queue
  • SplPriorityQueue::rewind — Rewind iterator back to the start (no-op)
  • SplPriorityQueue::setExtractFlags — Sets the mode of extraction
  • SplPriorityQueue::top — Peeks at the node from the top of the queue
  • SplPriorityQueue::valid — Check whether the queue contains more nodes


Compare priorities in order to place elements correctly in the heap while sifting up

  • « SplPriorityQueue
  • SplPriorityQueue::__construct »
  • PHP Manual
  • SplPriorityQueue
  • Compare priorities in order to place elements correctly in the heap while sifting up

SplPriorityQueue::compare

(PHP 5 >= 5.3.0, PHP 7)

SplPriorityQueue::compare — Compare priorities in order to place elements correctly in the heap while sifting up

Description

public SplPriorityQueue::compare ( mixed $priority1 , mixed $priority2 ) : int

Compare priority1 with priority2.

Parameters

priority1

The priority of the first node being compared.

priority2

The priority of the second node being compared.

Return Values

Result of the comparison, positive integer if priority1 is greater than priority2, 0 if they are equal, negative integer otherwise.

Note:

Multiple elements with the same priority will get dequeued in no particular order.


Constructs a new empty queue

  • « SplPriorityQueue::compare
  • SplPriorityQueue::count »
  • PHP Manual
  • SplPriorityQueue
  • Constructs a new empty queue

SplPriorityQueue::__construct

(PHP 5 >= 5.3.0, PHP 7)

SplPriorityQueue::__construct — Constructs a new empty queue

Description

public SplPriorityQueue::__construct ( void )

This constructs a new empty queue.

Parameters

This function has no parameters.

Return Values

No value is returned.


Counts the number of elements in the queue

  • « SplPriorityQueue::__construct
  • SplPriorityQueue::current »
  • PHP Manual
  • SplPriorityQueue
  • Counts the number of elements in the queue

SplPriorityQueue::count

(PHP 5 >= 5.3.0, PHP 7)

SplPriorityQueue::count — Counts the number of elements in the queue

Description

public SplPriorityQueue::count ( void ) : int

Parameters

This function has no parameters.

Return Values

Returns the number of elements in the queue.


Return current node pointed by the iterator

  • « SplPriorityQueue::count
  • SplPriorityQueue::extract »
  • PHP Manual
  • SplPriorityQueue
  • Return current node pointed by the iterator

SplPriorityQueue::current

(PHP 5 >= 5.3.0, PHP 7)

SplPriorityQueue::current — Return current node pointed by the iterator

Description

public SplPriorityQueue::current ( void ) : mixed

Get the current datastructure node.

Parameters

This function has no parameters.

Return Values

The value or priority (or both) of the current node, depending on the extract flag.


Extracts a node from top of the heap and sift up

  • « SplPriorityQueue::current
  • SplPriorityQueue::getExtractFlags »
  • PHP Manual
  • SplPriorityQueue
  • Extracts a node from top of the heap and sift up

SplPriorityQueue::extract

(PHP 5 >= 5.3.0, PHP 7)

SplPriorityQueue::extract — Extracts a node from top of the heap and sift up

Description

public SplPriorityQueue::extract ( void ) : mixed

Parameters

This function has no parameters.

Return Values

The value or priority (or both) of the extracted node, depending on the extract flag.


Get the flags of extraction

  • « SplPriorityQueue::extract
  • SplPriorityQueue::insert »
  • PHP Manual
  • SplPriorityQueue
  • Get the flags of extraction

SplPriorityQueue::getExtractFlags

(PHP 7)

SplPriorityQueue::getExtractFlags — Get the flags of extraction

Description

public SplPriorityQueue::getExtractFlags ( void ) : int

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Inserts an element in the queue by sifting it up

  • « SplPriorityQueue::getExtractFlags
  • SplPriorityQueue::isCorrupted »
  • PHP Manual
  • SplPriorityQueue
  • Inserts an element in the queue by sifting it up

SplPriorityQueue::insert

(PHP 5 >= 5.3.0, PHP 7)

SplPriorityQueue::insert — Inserts an element in the queue by sifting it up

Description

public SplPriorityQueue::insert ( mixed $value , mixed $priority ) : bool

Insert value with the priority priority in the queue.

Parameters

value

The value to insert.

priority

The associated priority.

Return Values

Returns TRUE.


Tells if the priority queue is in a corrupted state

  • « SplPriorityQueue::insert
  • SplPriorityQueue::isEmpty »
  • PHP Manual
  • SplPriorityQueue
  • Tells if the priority queue is in a corrupted state

SplPriorityQueue::isCorrupted

(No version information available, might only be in Git)

SplPriorityQueue::isCorrupted — Tells if the priority queue is in a corrupted state

Description

public SplPriorityQueue::isCorrupted ( void ) : bool

Parameters

This function has no parameters.

Return Values

Returns TRUE if the priority queue is corrupted, FALSE otherwise.


Checks whether the queue is empty

  • « SplPriorityQueue::isCorrupted
  • SplPriorityQueue::key »
  • PHP Manual
  • SplPriorityQueue
  • Checks whether the queue is empty

SplPriorityQueue::isEmpty

(PHP 5 >= 5.3.0, PHP 7)

SplPriorityQueue::isEmpty — Checks whether the queue is empty

Description

public SplPriorityQueue::isEmpty ( void ) : bool

Parameters

This function has no parameters.

Return Values

Returns whether the queue is empty.


Return current node index

  • « SplPriorityQueue::isEmpty
  • SplPriorityQueue::next »
  • PHP Manual
  • SplPriorityQueue
  • Return current node index

SplPriorityQueue::key

(PHP 5 >= 5.3.0, PHP 7)

SplPriorityQueue::key — Return current node index

Description

public SplPriorityQueue::key ( void ) : mixed

This function returns the current node index

Parameters

This function has no parameters.

Return Values

The current node index.


Move to the next node

  • « SplPriorityQueue::key
  • SplPriorityQueue::recoverFromCorruption »
  • PHP Manual
  • SplPriorityQueue
  • Move to the next node

SplPriorityQueue::next

(PHP 5 >= 5.3.0, PHP 7)

SplPriorityQueue::next — Move to the next node

Description

public SplPriorityQueue::next ( void ) : void

Extracts the top node from the queue.

Parameters

This function has no parameters.

Return Values

No value is returned.


Recover from the corrupted state and allow further actions on the queue

  • « SplPriorityQueue::next
  • SplPriorityQueue::rewind »
  • PHP Manual
  • SplPriorityQueue
  • Recover from the corrupted state and allow further actions on the queue

SplPriorityQueue::recoverFromCorruption

(PHP 5 >= 5.3.0, PHP 7)

SplPriorityQueue::recoverFromCorruption — Recover from the corrupted state and allow further actions on the queue

Description

public SplPriorityQueue::recoverFromCorruption ( void ) : void

Parameters

This function has no parameters.

Return Values

No value is returned.


Rewind iterator back to the start (no-op)

  • « SplPriorityQueue::recoverFromCorruption
  • SplPriorityQueue::setExtractFlags »
  • PHP Manual
  • SplPriorityQueue
  • Rewind iterator back to the start (no-op)

SplPriorityQueue::rewind

(PHP 5 >= 5.3.0, PHP 7)

SplPriorityQueue::rewind — Rewind iterator back to the start (no-op)

Description

public SplPriorityQueue::rewind ( void ) : void

This rewinds the iterator to the beginning. This is a no-op for heaps as the iterator is virtual and in fact never moves from the top of the heap.

Parameters

This function has no parameters.

Return Values

No value is returned.


Sets the mode of extraction

  • « SplPriorityQueue::rewind
  • SplPriorityQueue::top »
  • PHP Manual
  • SplPriorityQueue
  • Sets the mode of extraction

SplPriorityQueue::setExtractFlags

(PHP 5 >= 5.3.0, PHP 7)

SplPriorityQueue::setExtractFlags — Sets the mode of extraction

Description

public SplPriorityQueue::setExtractFlags ( int $flags ) : void

Parameters

flags

Defines what is extracted by SplPriorityQueue::current(),
SplPriorityQueue::top() and
SplPriorityQueue::extract().

  • SplPriorityQueue::EXTR_DATA (0x00000001): Extract the data
  • SplPriorityQueue::EXTR_PRIORITY (0x00000002): Extract the priority
  • SplPriorityQueue::EXTR_BOTH (0x00000003): Extract an array containing both

The default mode is SplPriorityQueue::EXTR_DATA.

Return Values

No value is returned.


Peeks at the node from the top of the queue

  • « SplPriorityQueue::setExtractFlags
  • SplPriorityQueue::valid »
  • PHP Manual
  • SplPriorityQueue
  • Peeks at the node from the top of the queue

SplPriorityQueue::top

(PHP 5 >= 5.3.0, PHP 7)

SplPriorityQueue::top — Peeks at the node from the top of the queue

Description

public SplPriorityQueue::top ( void ) : mixed

Parameters

This function has no parameters.

Return Values

The value or priority (or both) of the top node, depending on the extract flag.


Check whether the queue contains more nodes

  • « SplPriorityQueue::top
  • SplFixedArray »
  • PHP Manual
  • SplPriorityQueue
  • Check whether the queue contains more nodes

SplPriorityQueue::valid

(PHP 5 >= 5.3.0, PHP 7)

SplPriorityQueue::valid — Check whether the queue contains more nodes

Description

public SplPriorityQueue::valid ( void ) : bool

Checks if the queue contains any more nodes.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the queue contains any more nodes, FALSE otherwise.


The SplFixedArray class

(PHP 5 >= 5.3.0, PHP 7)

Introduction

The SplFixedArray class provides the main functionalities of array. The main differences between a SplFixedArray and a normal PHP array is that the SplFixedArray is of fixed length and allows only integers within the range as indexes. The advantage is that it uses less memory than a standard array.

Class synopsis

SplFixedArray implements Iterator , ArrayAccess , Countable {
/* Methods */
public __construct ([ int $size = 0 ] )
public count ( void ) : int
public current ( void ) : mixed
public static fromArray ( array $array [, bool $save_indexes = TRUE ] ) : SplFixedArray
public getSize ( void ) : int
public key ( void ) : int
public next ( void ) : void
public offsetExists ( int $index ) : bool
public offsetGet ( int $index ) : mixed
public offsetSet ( int $index , mixed $newval ) : void
public offsetUnset ( int $index ) : void
public rewind ( void ) : void
public setSize ( int $size ) : bool
public toArray ( void ) : array
public valid ( void ) : bool
public __wakeup ( void ) : void
}

Examples

Example #1 SplFixedArray usage example

<?php
// Initialize the array with a fixed length
$array = new SplFixedArray(5);

$array[1] = 2;
$array[4] = "foo";

var_dump($array[0]); // NULL
var_dump($array[1]); // int(2)

var_dump($array["4"]); // string(3) "foo"

// Increase the size of the array to 10
$array->setSize(10);

$array[9] = "asdf";

// Shrink the array to a size of 2
$array->setSize(2);

// The following lines throw a RuntimeException: Index invalid or out of range
try {
    var_dump($array["non-numeric"]);
} catch(RuntimeException $re) {
    echo "RuntimeException: ".$re->getMessage()."\n";
}

try {
    var_dump($array[-1]);
} catch(RuntimeException $re) {
    echo "RuntimeException: ".$re->getMessage()."\n";
}

try {
    var_dump($array[5]);
} catch(RuntimeException $re) {
    echo "RuntimeException: ".$re->getMessage()."\n";
}
?>

The above example will output:

NULL
int(2)
string(3) "foo"
RuntimeException: Index invalid or out of range
RuntimeException: Index invalid or out of range
RuntimeException: Index invalid or out of range

Table of Contents

  • SplFixedArray::__construct — Constructs a new fixed array
  • SplFixedArray::count — Returns the size of the array
  • SplFixedArray::current — Return current array entry
  • SplFixedArray::fromArray — Import a PHP array in a SplFixedArray instance
  • SplFixedArray::getSize — Gets the size of the array
  • SplFixedArray::key — Return current array index
  • SplFixedArray::next — Move to next entry
  • SplFixedArray::offsetExists — Returns whether the requested index exists
  • SplFixedArray::offsetGet — Returns the value at the specified index
  • SplFixedArray::offsetSet — Sets a new value at a specified index
  • SplFixedArray::offsetUnset — Unsets the value at the specified $index
  • SplFixedArray::rewind — Rewind iterator back to the start
  • SplFixedArray::setSize — Change the size of an array
  • SplFixedArray::toArray — Returns a PHP array from the fixed array
  • SplFixedArray::valid — Check whether the array contains more elements
  • SplFixedArray::__wakeup — Reinitialises the array after being unserialised


Constructs a new fixed array

  • « SplFixedArray
  • SplFixedArray::count »
  • PHP Manual
  • SplFixedArray
  • Constructs a new fixed array

SplFixedArray::__construct

(PHP 5 >= 5.3.0, PHP 7)

SplFixedArray::__construct — Constructs a new fixed array

Description

public SplFixedArray::__construct ([ int $size = 0 ] )

Initializes a fixed array with a number of NULL values equal to size.

Parameters

size

The size of the fixed array. This expects a number between 0 and PHP_INT_MAX.

Return Values

No value is returned.

Errors/Exceptions

Throws InvalidArgumentException when size is a negative number.

Raises E_WARNING when size cannot be parsed as a number.

Examples

Example #1 SplFixedArray::__construct() example

<?php
$array = new SplFixedArray(5);

$array[1] = 2;
$array[4] = "foo";

foreach($array as $v) {
  var_dump($v);
}
?>

The above example will output:

NULL
int(2)
NULL
NULL
string(3) "foo"


Returns the size of the array

  • « SplFixedArray::__construct
  • SplFixedArray::current »
  • PHP Manual
  • SplFixedArray
  • Returns the size of the array

SplFixedArray::count

(PHP 5 >= 5.3.0, PHP 7)

SplFixedArray::count — Returns the size of the array

Description

public SplFixedArray::count ( void ) : int

Returns the size of the array.

Parameters

This function has no parameters.

Return Values

Returns the size of the array.

Examples

Example #1 SplFixedArray::count() example

<?php
$array = new SplFixedArray(5);
echo $array->count() . "\n";
echo count($array) . "\n";
?>

The above example will output:

5
5

Notes

Note:

This method is functionally equivalent to SplFixedArray::getSize().

Note:

The count of elements is always equal to the set size because all values are initially initialized with NULL.

See Also

  • SplFixedArray::getSize() - Gets the size of the array


Return current array entry

  • « SplFixedArray::count
  • SplFixedArray::fromArray »
  • PHP Manual
  • SplFixedArray
  • Return current array entry

SplFixedArray::current

(PHP 5 >= 5.3.0, PHP 7)

SplFixedArray::current — Return current array entry

Description

public SplFixedArray::current ( void ) : mixed

Get the current array element.

Parameters

This function has no parameters.

Return Values

The current element value.

Errors/Exceptions

Throws RuntimeException when the internal array pointer points to an invalid index or is out of bounds.


Import a PHP array in a SplFixedArray instance

  • « SplFixedArray::current
  • SplFixedArray::getSize »
  • PHP Manual
  • SplFixedArray
  • Import a PHP array in a SplFixedArray instance

SplFixedArray::fromArray

(PHP 5 >= 5.3.0, PHP 7)

SplFixedArray::fromArray — Import a PHP array in a SplFixedArray instance

Description

public static SplFixedArray::fromArray ( array $array [, bool $save_indexes = TRUE ] ) : SplFixedArray

Import the PHP array array in a new SplFixedArray instance

Parameters

array

The array to import.

save_indexes

Try to save the numeric indexes used in the original array.

Return Values

Returns an instance of SplFixedArray containing the array content.

Examples

Example #1 SplFixedArray::fromArray() example

<?php
$fa = SplFixedArray::fromArray(array(1 => 1, 0 => 2, 3 => 3));

var_dump($fa);

$fa = SplFixedArray::fromArray(array(1 => 1, 0 => 2, 3 => 3), false);

var_dump($fa);
?>

The above example will output:

object(SplFixedArray)#1 (4) {
  [0]=>
  int(2)
  [1]=>
  int(1)
  [2]=>
  NULL
  [3]=>
  int(3)
}
object(SplFixedArray)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}


Gets the size of the array

  • « SplFixedArray::fromArray
  • SplFixedArray::key »
  • PHP Manual
  • SplFixedArray
  • Gets the size of the array

SplFixedArray::getSize

(PHP 5 >= 5.3.0, PHP 7)

SplFixedArray::getSize — Gets the size of the array

Description

public SplFixedArray::getSize ( void ) : int

Gets the size of the array.

Parameters

This function has no parameters.

Return Values

Returns the size of the array, as an integer.

Examples

Example #1 SplFixedArray::getSize() example

<?php
$array = new SplFixedArray(5);
echo $array->getSize()."\n";
$array->setSize(10);
echo $array->getSize()."\n";
?>

The above example will output:

5
10

Notes

Note:

This method is functionally equivalent to SplFixedArray::count()

See Also

  • SplFixedArray::count() - Returns the size of the array


Return current array index

  • « SplFixedArray::getSize
  • SplFixedArray::next »
  • PHP Manual
  • SplFixedArray
  • Return current array index

SplFixedArray::key

(PHP 5 >= 5.3.0, PHP 7)

SplFixedArray::key — Return current array index

Description

public SplFixedArray::key ( void ) : int

Returns the current array index.

Parameters

This function has no parameters.

Return Values

The current array index.


Move to next entry

  • « SplFixedArray::key
  • SplFixedArray::offsetExists »
  • PHP Manual
  • SplFixedArray
  • Move to next entry

SplFixedArray::next

(PHP 5 >= 5.3.0, PHP 7)

SplFixedArray::next — Move to next entry

Description

public SplFixedArray::next ( void ) : void

Move the iterator to the next array entry.

Parameters

This function has no parameters.

Return Values

No value is returned.


Returns whether the requested index exists

  • « SplFixedArray::next
  • SplFixedArray::offsetGet »
  • PHP Manual
  • SplFixedArray
  • Returns whether the requested index exists

SplFixedArray::offsetExists

(PHP 5 >= 5.3.0, PHP 7)

SplFixedArray::offsetExists — Returns whether the requested index exists

Description

public SplFixedArray::offsetExists ( int $index ) : bool

Checks whether the requested index index exists.

Parameters

index

The index being checked.

Return Values

TRUE if the requested index exists, otherwise FALSE


Returns the value at the specified index

  • « SplFixedArray::offsetExists
  • SplFixedArray::offsetSet »
  • PHP Manual
  • SplFixedArray
  • Returns the value at the specified index

SplFixedArray::offsetGet

(PHP 5 >= 5.3.0, PHP 7)

SplFixedArray::offsetGet — Returns the value at the specified index

Description

public SplFixedArray::offsetGet ( int $index ) : mixed

Returns the value at the index index.

Parameters

index

The index with the value.

Return Values

The value at the specified index.

Errors/Exceptions

Throws RuntimeException when index is outside the defined size of the array or when index cannot be parsed as an integer.


Sets a new value at a specified index

  • « SplFixedArray::offsetGet
  • SplFixedArray::offsetUnset »
  • PHP Manual
  • SplFixedArray
  • Sets a new value at a specified index

SplFixedArray::offsetSet

(PHP 5 >= 5.3.0, PHP 7)

SplFixedArray::offsetSet — Sets a new value at a specified index

Description

public SplFixedArray::offsetSet ( int $index , mixed $newval ) : void

Sets the value at the specified index to newval.

Parameters

index

The index being set.

newval

The new value for the index.

Return Values

No value is returned.

Errors/Exceptions

Throws RuntimeException when index is outside the defined size of the array or when index cannot be parsed as an integer.


Unsets the value at the specified $index

  • « SplFixedArray::offsetSet
  • SplFixedArray::rewind »
  • PHP Manual
  • SplFixedArray
  • Unsets the value at the specified $index

SplFixedArray::offsetUnset

(PHP 5 >= 5.3.0, PHP 7)

SplFixedArray::offsetUnset — Unsets the value at the specified $index

Description

public SplFixedArray::offsetUnset ( int $index ) : void

Unsets the value at the specified index.

Parameters

index

The index being unset.

Return Values

No value is returned.

Errors/Exceptions

Throws RuntimeException when index is outside the defined size of the array or when index cannot be parsed as an integer.


Rewind iterator back to the start

  • « SplFixedArray::offsetUnset
  • SplFixedArray::setSize »
  • PHP Manual
  • SplFixedArray
  • Rewind iterator back to the start

SplFixedArray::rewind

(PHP 5 >= 5.3.0, PHP 7)

SplFixedArray::rewind — Rewind iterator back to the start

Description

public SplFixedArray::rewind ( void ) : void

Rewinds the iterator to the beginning.

Parameters

This function has no parameters.

Return Values

No value is returned.


Change the size of an array

  • « SplFixedArray::rewind
  • SplFixedArray::toArray »
  • PHP Manual
  • SplFixedArray
  • Change the size of an array

SplFixedArray::setSize

(PHP 5 >= 5.3.0, PHP 7)

SplFixedArray::setSize — Change the size of an array

Description

public SplFixedArray::setSize ( int $size ) : bool

Change the size of an array to the new size of size. If size is less than the current array size, any values after the new size will be discarded. If size is greater than the current array size, the array will be padded with NULL values.

Parameters

size

The new array size. This should be a value between 0 and PHP_INT_MAX.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws InvalidArgumentException when size is less than zero.

Raises E_WARNING when size cannot be used as a number.

Examples

Example #1 SplFixedArray::setSize() example

<?php
   $array = new SplFixedArray(5);
   echo $array->getSize()."\n";
   $array->setSize(10);
   echo $array->getSize()."\n";
?>

The above example will output:

5
10


Returns a PHP array from the fixed array

  • « SplFixedArray::setSize
  • SplFixedArray::valid »
  • PHP Manual
  • SplFixedArray
  • Returns a PHP array from the fixed array

SplFixedArray::toArray

(PHP 5 >= 5.3.0, PHP 7)

SplFixedArray::toArray — Returns a PHP array from the fixed array

Description

public SplFixedArray::toArray ( void ) : array

Returns a PHP array from the fixed array.

Parameters

This function has no parameters.

Return Values

Returns a PHP array, similar to the fixed array.

Examples

Example #1 SplFixedArray::toArray() example

<?php
$fa = new SplFixedArray(3);
$fa[0] = 0;
$fa[2] = 2;
var_dump($fa->toArray());
?>

The above example will output:

array(3) {
  [0]=>
  int(0)
  [1]=>
  NULL
  [2]=>
  int(2)
}


Check whether the array contains more elements

  • « SplFixedArray::toArray
  • SplFixedArray::__wakeup »
  • PHP Manual
  • SplFixedArray
  • Check whether the array contains more elements

SplFixedArray::valid

(PHP 5 >= 5.3.0, PHP 7)

SplFixedArray::valid — Check whether the array contains more elements

Description

public SplFixedArray::valid ( void ) : bool

Checks if the array contains any more elements.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the array contains any more elements, FALSE otherwise.


Reinitialises the array after being unserialised

  • « SplFixedArray::valid
  • SplObjectStorage »
  • PHP Manual
  • SplFixedArray
  • Reinitialises the array after being unserialised

SplFixedArray::__wakeup

(PHP 5 >= 5.5.0, PHP 7)

SplFixedArray::__wakeup — Reinitialises the array after being unserialised

Description

public SplFixedArray::__wakeup ( void ) : void

Reinitialises the array after being unserialised.

Parameters

This function has no parameters.

Return Values

No value is returned.


The SplObjectStorage class

(PHP 5 >= 5.3.0, PHP 7)

Introduction

The SplObjectStorage class provides a map from objects to data or, by ignoring data, an object set. This dual purpose can be useful in many cases involving the need to uniquely identify objects.

Class synopsis

SplObjectStorage implements Countable , Iterator , Serializable , ArrayAccess {
/* Methods */
public addAll ( SplObjectStorage $storage ) : void
public attach ( object $object [, mixed $data = NULL ] ) : void
public contains ( object $object ) : bool
public count ( void ) : int
public current ( void ) : object
public detach ( object $object ) : void
public getHash ( object $object ) : string
public getInfo ( void ) : mixed
public key ( void ) : int
public next ( void ) : void
public offsetExists ( object $object ) : bool
public offsetGet ( object $object ) : mixed
public offsetSet ( object $object [, mixed $data = NULL ] ) : void
public offsetUnset ( object $object ) : void
public removeAll ( SplObjectStorage $storage ) : void
public removeAllExcept ( SplObjectStorage $storage ) : void
public rewind ( void ) : void
public serialize ( void ) : string
public setInfo ( mixed $data ) : void
public unserialize ( string $serialized ) : void
public valid ( void ) : bool
}

Examples

Example #1 SplObjectStorage as a set

<?php
// As an object set
$s = new SplObjectStorage();

$o1 = new StdClass;
$o2 = new StdClass;
$o3 = new StdClass;

$s->attach($o1);
$s->attach($o2);

var_dump($s->contains($o1));
var_dump($s->contains($o2));
var_dump($s->contains($o3));

$s->detach($o2);

var_dump($s->contains($o1));
var_dump($s->contains($o2));
var_dump($s->contains($o3));
?>

The above example will output:

bool(true)
bool(true)
bool(false)
bool(true)
bool(false)
bool(false)

Example #2 SplObjectStorage as a map

<?php
// As a map from objects to data
$s = new SplObjectStorage();

$o1 = new StdClass;
$o2 = new StdClass;
$o3 = new StdClass;

$s[$o1] = "data for object 1";
$s[$o2] = array(1,2,3);

if (isset($s[$o2])) {
    var_dump($s[$o2]);
}
?>

The above example will output:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

Table of Contents

  • SplObjectStorage::addAll — Adds all objects from another storage
  • SplObjectStorage::attach — Adds an object in the storage
  • SplObjectStorage::contains — Checks if the storage contains a specific object
  • SplObjectStorage::count — Returns the number of objects in the storage
  • SplObjectStorage::current — Returns the current storage entry
  • SplObjectStorage::detach — Removes an object from the storage
  • SplObjectStorage::getHash — Calculate a unique identifier for the contained objects
  • SplObjectStorage::getInfo — Returns the data associated with the current iterator entry
  • SplObjectStorage::key — Returns the index at which the iterator currently is
  • SplObjectStorage::next — Move to the next entry
  • SplObjectStorage::offsetExists — Checks whether an object exists in the storage
  • SplObjectStorage::offsetGet — Returns the data associated with an object
  • SplObjectStorage::offsetSet — Associates data to an object in the storage
  • SplObjectStorage::offsetUnset — Removes an object from the storage
  • SplObjectStorage::removeAll — Removes objects contained in another storage from the current storage
  • SplObjectStorage::removeAllExcept — Removes all objects except for those contained in another storage from the current storage
  • SplObjectStorage::rewind — Rewind the iterator to the first storage element
  • SplObjectStorage::serialize — Serializes the storage
  • SplObjectStorage::setInfo — Sets the data associated with the current iterator entry
  • SplObjectStorage::unserialize — Unserializes a storage from its string representation
  • SplObjectStorage::valid — Returns if the current iterator entry is valid


Adds all objects from another storage

  • « SplObjectStorage
  • SplObjectStorage::attach »
  • PHP Manual
  • SplObjectStorage
  • Adds all objects from another storage

SplObjectStorage::addAll

(PHP 5 >= 5.3.0, PHP 7)

SplObjectStorage::addAll — Adds all objects from another storage

Description

public SplObjectStorage::addAll ( SplObjectStorage $storage ) : void

Adds all objects-data pairs from a different storage in the current storage.

Parameters

storage

The storage you want to import.

Return Values

No value is returned.

Examples

Example #1 SplObjectStorage::addAll() example

<?php
$o = new StdClass;
$a = new SplObjectStorage();
$a[$o] = "hello";

$b = new SplObjectStorage();
$b->addAll($a);
echo $b[$o]."\n";
?>

The above example will output something similar to:

hello

See Also

  • SplObjectStorage::removeAll() - Removes objects contained in another storage from the current storage


Adds an object in the storage

  • « SplObjectStorage::addAll
  • SplObjectStorage::contains »
  • PHP Manual
  • SplObjectStorage
  • Adds an object in the storage

SplObjectStorage::attach

(PHP 5 >= 5.1.0, PHP 7)

SplObjectStorage::attach — Adds an object in the storage

Description

public SplObjectStorage::attach ( object $object [, mixed $data = NULL ] ) : void

Adds an object inside the storage, and optionally associate it to some data.

Parameters

object

The object to add.

data

The data to associate with the object.

Return Values

No value is returned.

Examples

Example #1 SplObjectStorage::attach() example

<?php
$o1 = new StdClass;
$o2 = new StdClass;
$s = new SplObjectStorage();
$s->attach($o1); // similar to $s[$o1] = NULL;
$s->attach($o2, "hello"); // similar to $s[$o2] = "hello";

var_dump($s[$o1]);
var_dump($s[$o2]);

?>

The above example will output something similar to:

NULL
string(5) "hello"

Changelog

Version | Description
5.3.0 | Added the data parameter.

See Also

  • SplObjectStorage::detach() - Removes an object from the storage
  • SplObjectStorage::offsetSet() - Associates data to an object in the storage


Checks if the storage contains a specific object

  • « SplObjectStorage::attach
  • SplObjectStorage::count »
  • PHP Manual
  • SplObjectStorage
  • Checks if the storage contains a specific object

SplObjectStorage::contains

(PHP 5 >= 5.1.0, PHP 7)

SplObjectStorage::contains — Checks if the storage contains a specific object

Description

public SplObjectStorage::contains ( object $object ) : bool

Checks if the storage contains the object provided.

Parameters

object

The object to look for.

Return Values

Returns TRUE if the object is in the storage, FALSE otherwise.

Examples

Example #1 SplObjectStorage::contains() example

<?php
$o1 = new StdClass;
$o2 = new StdClass;

$s = new SplObjectStorage();

$s[$o1] = "hello";
var_dump($s->contains($o1));
var_dump($s->contains($o2));
?>

The above example will output something similar to:

bool(true)
bool(false)

See Also

  • SplObjectStorage::offsetExists() - Checks whether an object exists in the storage


Returns the number of objects in the storage

  • « SplObjectStorage::contains
  • SplObjectStorage::current »
  • PHP Manual
  • SplObjectStorage
  • Returns the number of objects in the storage

SplObjectStorage::count

(PHP 5 >= 5.1.0, PHP 7)

SplObjectStorage::count — Returns the number of objects in the storage

Description

public SplObjectStorage::count ( void ) : int

Counts the number of objects in the storage.

Parameters

This function has no parameters.

Return Values

The number of objects in the storage.

Examples

Example #1 SplObjectStorage::count() example

<?php
$s = new SplObjectStorage();
$o1 = new StdClass;
$o2 = new StdClass;

$s->attach($o1);
$s->attach($o2);
$s->attach($o1);
var_dump($s->count());
var_dump(count($s));
?>

The above example will output something similar to:

int(2)
int(2)

See Also

  • SplObjectStorage::attach() - Adds an object in the storage
  • SplObjectStorage::detach() - Removes an object from the storage


Returns the current storage entry

  • « SplObjectStorage::count
  • SplObjectStorage::detach »
  • PHP Manual
  • SplObjectStorage
  • Returns the current storage entry

SplObjectStorage::current

(PHP 5 >= 5.1.0, PHP 7)

SplObjectStorage::current — Returns the current storage entry

Description

public SplObjectStorage::current ( void ) : object

Returns the current storage entry.

Parameters

This function has no parameters.

Return Values

The object at the current iterator position.

Examples

Example #1 SplObjectStorage::current() example

<?php
$s = new SplObjectStorage();

$o1 = new StdClass;
$o2 = new StdClass;

$s->attach($o1, "d1");
$s->attach($o2, "d2");

$s->rewind();
while($s->valid()) {
    $index  = $s->key();
    $object = $s->current(); // similar to current($s)
    $data   = $s->getInfo();

    var_dump($object);
    var_dump($data);
    $s->next();
}
?>

The above example will output something similar to:

object(stdClass)#2 (0) {
}
string(2) "d1"
object(stdClass)#3 (0) {
}
string(2) "d2"

See Also

  • SplObjectStorage::rewind() - Rewind the iterator to the first storage element
  • SplObjectStorage::key() - Returns the index at which the iterator currently is
  • SplObjectStorage::next() - Move to the next entry
  • SplObjectStorage::valid() - Returns if the current iterator entry is valid
  • SplObjectStorage::getInfo() - Returns the data associated with the current iterator entry


Removes an object from the storage

  • « SplObjectStorage::current
  • SplObjectStorage::getHash »
  • PHP Manual
  • SplObjectStorage
  • Removes an object from the storage

SplObjectStorage::detach

(PHP 5 >= 5.1.0, PHP 7)

SplObjectStorage::detach — Removes an object from the storage

Description

public SplObjectStorage::detach ( object $object ) : void

Removes the object from the storage.

Parameters

object

The object to remove.

Return Values

No value is returned.

Examples

Example #1 SplObjectStorage::detach() example

<?php
$o = new StdClass;
$s = new SplObjectStorage();
$s->attach($o);
var_dump(count($s));
$s->detach($o);
var_dump(count($s));
?>

The above example will output something similar to:

int(1)
int(0)

See Also

  • SplObjectStorage::attach() - Adds an object in the storage
  • SplObjectStorage::removeAll() - Removes objects contained in another storage from the current storage


Calculate a unique identifier for the contained objects

  • « SplObjectStorage::detach
  • SplObjectStorage::getInfo »
  • PHP Manual
  • SplObjectStorage
  • Calculate a unique identifier for the contained objects

SplObjectStorage::getHash

(PHP 5 >= 5.4.0, PHP 7)

SplObjectStorage::getHash — Calculate a unique identifier for the contained objects

Description

public SplObjectStorage::getHash ( object $object ) : string

This method calculates an identifier for the objects added to an SplObjectStorage object.

The implementation in SplObjectStorage returns the same value as spl_object_hash().

The storage object will never contain more than one object with the same identifier. As such, it can be used to implement a set (a collection of unique values) where the quality of an object being unique is determined by the value returned by this function being unique.

Parameters

object

The object whose identifier is to be calculated.

Return Values

A string with the calculated identifier.

Errors/Exceptions

A RuntimeException is thrown when the returned value is not a string.

Examples

Example #1 SplObjectStorage::getHash() example

<?php
class OneSpecimenPerClassStorage extends SplObjectStorage {
    public function getHash($o) {
        return get_class($o);
    }
}
class A {}

$s = new OneSpecimenPerClassStorage;
$o1 = new stdClass;
$o2 = new stdClass;
$o3 = new A;

$s[$o1] = 1;
//$o2 is considered equal to $o1 so the value is replaced
$s[$o2] = 2;
$s[$o3] = 3;

//these are considered equal to the objects before
//so they can be used to access the values stored under them
$p1 = new stdClass;
$p2 = new A;
echo $s[$p1], "\n";
echo $s[$p2], "\n";
?>

The above example will output something similar to:

2
3

See Also

  • spl_object_hash() - Return hash id for given object


Returns the data associated with the current iterator entry

  • « SplObjectStorage::getHash
  • SplObjectStorage::key »
  • PHP Manual
  • SplObjectStorage
  • Returns the data associated with the current iterator entry

SplObjectStorage::getInfo

(PHP 5 >= 5.3.0, PHP 7)

SplObjectStorage::getInfo — Returns the data associated with the current iterator entry

Description

public SplObjectStorage::getInfo ( void ) : mixed

Returns the data, or info, associated with the object pointed by the current iterator position.

Parameters

This function has no parameters.

Return Values

The data associated with the current iterator position.

Examples

Example #1 SplObjectStorage::getInfo() example

<?php
$s = new SplObjectStorage();

$o1 = new StdClass;
$o2 = new StdClass;

$s->attach($o1, "d1");
$s->attach($o2, "d2");

$s->rewind();
while($s->valid()) {
    $index  = $s->key();
    $object = $s->current(); // similar to current($s)
    $data   = $s->getInfo();

    var_dump($object);
    var_dump($data);
    $s->next();
}
?>

The above example will output something similar to:

object(stdClass)#2 (0) {
}
string(2) "d1"
object(stdClass)#3 (0) {
}
string(2) "d2"

See Also

  • SplObjectStorage::current() - Returns the current storage entry
  • SplObjectStorage::rewind() - Rewind the iterator to the first storage element
  • SplObjectStorage::key() - Returns the index at which the iterator currently is
  • SplObjectStorage::next() - Move to the next entry
  • SplObjectStorage::valid() - Returns if the current iterator entry is valid
  • SplObjectStorage::setInfo() - Sets the data associated with the current iterator entry


Returns the index at which the iterator currently is

  • « SplObjectStorage::getInfo
  • SplObjectStorage::next »
  • PHP Manual
  • SplObjectStorage
  • Returns the index at which the iterator currently is

SplObjectStorage::key

(PHP 5 >= 5.1.0, PHP 7)

SplObjectStorage::key — Returns the index at which the iterator currently is

Description

public SplObjectStorage::key ( void ) : int

Returns the index at which the iterator currently is.

Parameters

This function has no parameters.

Return Values

The index corresponding to the position of the iterator.

Examples

Example #1 SplObjectStorage::key() example

<?php
$s = new SplObjectStorage();

$o1 = new StdClass;
$o2 = new StdClass;

$s->attach($o1, "d1");
$s->attach($o2, "d2");

$s->rewind();
while($s->valid()) {
    $index  = $s->key();
    $object = $s->current(); // similar to current($s)

    var_dump($index);
    var_dump($object);
    $s->next();
}
?>

The above example will output something similar to:

int(0)
object(stdClass)#2 (0) {
}
int(1)
object(stdClass)#3 (0) {
}

See Also

  • SplObjectStorage::rewind() - Rewind the iterator to the first storage element
  • SplObjectStorage::current() - Returns the current storage entry
  • SplObjectStorage::next() - Move to the next entry
  • SplObjectStorage::valid() - Returns if the current iterator entry is valid


Move to the next entry

  • « SplObjectStorage::key
  • SplObjectStorage::offsetExists »
  • PHP Manual
  • SplObjectStorage
  • Move to the next entry

SplObjectStorage::next

(PHP 5 >= 5.1.0, PHP 7)

SplObjectStorage::next — Move to the next entry

Description

public SplObjectStorage::next ( void ) : void

Moves the iterator to the next object in the storage.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 SplObjectStorage::next() example

<?php
$s = new SplObjectStorage();

$o1 = new StdClass;
$o2 = new StdClass;

$s->attach($o1, "d1");
$s->attach($o2, "d2");

$s->rewind();
while($s->valid()) {
    $index  = $s->key();
    $object = $s->current(); // similar to current($s)

    var_dump($index);
    var_dump($object);
    $s->next();
}
?>

The above example will output something similar to:

int(0)
object(stdClass)#2 (0) {
}
int(1)
object(stdClass)#3 (0) {
}

See Also

  • SPLObjectStorage::rewind() - Rewind the iterator to the first storage element


Checks whether an object exists in the storage

  • « SplObjectStorage::next
  • SplObjectStorage::offsetGet »
  • PHP Manual
  • SplObjectStorage
  • Checks whether an object exists in the storage

SplObjectStorage::offsetExists

(PHP 5 >= 5.3.0, PHP 7)

SplObjectStorage::offsetExists — Checks whether an object exists in the storage

Description

public SplObjectStorage::offsetExists ( object $object ) : bool

Checks whether an object exists in the storage.

Note:

SplObjectStorage::offsetExists() is an alias of SplObjectStorage::contains().

Parameters

object

The object to look for.

Return Values

Returns TRUE if the object exists in the storage, and FALSE otherwise.

Examples

Example #1 SplObjectStorage::offsetExists() example

<?php
$s = new SplObjectStorage;
$o1 = new StdClass;
$o2 = new StdClass;

$s->attach($o1);

var_dump($s->offsetExists($o1)); // Similar to isset($s[$o1])
var_dump($s->offsetExists($o2)); // Similar to isset($s[$o2])
?>

The above example will output something similar to:

bool(true)
bool(false)

See Also

  • SplObjectStorage::offsetSet() - Associates data to an object in the storage
  • SplObjectStorage::offsetGet() - Returns the data associated with an object
  • SplObjectStorage::offsetUnset() - Removes an object from the storage


Returns the data associated with an object

  • « SplObjectStorage::offsetExists
  • SplObjectStorage::offsetSet »
  • PHP Manual
  • SplObjectStorage
  • Returns the data associated with an object

SplObjectStorage::offsetGet

(PHP 5 >= 5.3.0, PHP 7)

SplObjectStorage::offsetGet — Returns the data associated with an object

Description

public SplObjectStorage::offsetGet ( object $object ) : mixed

Returns the data associated with an object in the storage.

Parameters

object

The object to look for.

Return Values

The data previously associated with the object in the storage.

Errors/Exceptions

Throws UnexpectedValueException when object could not be found.

Examples

Example #1 SplObjectStorage::offsetGet() example

<?php
$s = new SplObjectStorage;

$o1 = new StdClass;
$o2 = new StdClass;

$s[$o1] = "hello";
$s->attach($o2);

var_dump($s->offsetGet($o1)); // Similar to $s[$o1]
var_dump($s->offsetGet($o2)); // Similar to $s[$o2]
?>

The above example will output something similar to:

string(5) "hello"
NULL

See Also

  • SplObjectStorage::offsetSet() - Associates data to an object in the storage
  • SplObjectStorage::offsetExists() - Checks whether an object exists in the storage
  • SplObjectStorage::offsetUnset() - Removes an object from the storage


Associates data to an object in the storage

  • « SplObjectStorage::offsetGet
  • SplObjectStorage::offsetUnset »
  • PHP Manual
  • SplObjectStorage
  • Associates data to an object in the storage

SplObjectStorage::offsetSet

(PHP 5 >= 5.3.0, PHP 7)

SplObjectStorage::offsetSet — Associates data to an object in the storage

Description

public SplObjectStorage::offsetSet ( object $object [, mixed $data = NULL ] ) : void

Associate data to an object in the storage.

Note:

SplObjectStorage::offsetSet() is an alias of SplObjectStorage::attach().

Parameters

object

The object to associate data with.

data

The data to associate with the object.

Return Values

No value is returned.

Examples

Example #1 SplObjectStorage::offsetSet() example

<?php
$s = new SplObjectStorage;

$o1 = new StdClass;

$s->offsetSet($o1, "hello"); // Similar to $s[$o1] = "hello";

var_dump($s[$o1]);
?>

The above example will output something similar to:

string(5) "hello"

See Also

  • SplObjectStorage::attach() - Adds an object in the storage
  • SplObjectStorage::offsetGet() - Returns the data associated with an object
  • SplObjectStorage::offsetExists() - Checks whether an object exists in the storage
  • SplObjectStorage::offsetUnset() - Removes an object from the storage


Removes an object from the storage

  • « SplObjectStorage::offsetSet
  • SplObjectStorage::removeAll »
  • PHP Manual
  • SplObjectStorage
  • Removes an object from the storage

SplObjectStorage::offsetUnset

(PHP 5 >= 5.3.0, PHP 7)

SplObjectStorage::offsetUnset — Removes an object from the storage

Description

public SplObjectStorage::offsetUnset ( object $object ) : void

Removes an object from the storage.

Note:

SplObjectStorage::offsetUnset() is an alias of SplObjectStorage::detach().

Parameters

object

The object to remove.

Return Values

No value is returned.

Examples

Example #1 SplObjectStorage::offsetUnset() example

<?php
$o = new StdClass;
$s = new SplObjectStorage();
$s->attach($o);
var_dump(count($s));
$s->offsetUnset($o); // Similar to unset($s[$o])
var_dump(count($s));
?>

The above example will output something similar to:

int(1)
int(0)

See Also

  • SplObjectStorage::offsetGet() - Returns the data associated with an object
  • SplObjectStorage::offsetSet() - Associates data to an object in the storage
  • SplObjectStorage::offsetExists() - Checks whether an object exists in the storage


Removes objects contained in another storage from the current storage

  • « SplObjectStorage::offsetUnset
  • SplObjectStorage::removeAllExcept »
  • PHP Manual
  • SplObjectStorage
  • Removes objects contained in another storage from the current storage

SplObjectStorage::removeAll

(PHP 5 >= 5.3.0, PHP 7)

SplObjectStorage::removeAll — Removes objects contained in another storage from the current storage

Description

public SplObjectStorage::removeAll ( SplObjectStorage $storage ) : void

Removes objects contained in another storage from the current storage.

Parameters

storage

The storage containing the elements to remove.

Return Values

No value is returned.

Examples

Example #1 SplObjectStorage::removeAll() example

<?php
$o1 = new StdClass;
$o2 = new StdClass;
$a = new SplObjectStorage();
$a[$o1] = "foo";

$b = new SplObjectStorage();
$b[$o1] = "bar";
$b[$o2] = "gee";

var_dump(count($b));
$b->removeAll($a);
var_dump(count($b));
?>

The above example will output something similar to:

int(2)
int(1)

See Also

  • SplObjectStorage::addAll() - Adds all objects from another storage


Removes all objects except for those contained in another storage from the current storage

  • « SplObjectStorage::removeAll
  • SplObjectStorage::rewind »
  • PHP Manual
  • SplObjectStorage
  • Removes all objects except for those contained in another storage from the current storage

SplObjectStorage::removeAllExcept

(PHP 5 >= 5.3.6, PHP 7)

SplObjectStorage::removeAllExcept — Removes all objects except for those contained in another storage from the current storage

Description

public SplObjectStorage::removeAllExcept ( SplObjectStorage $storage ) : void

Removes all objects except for those contained in another storage from the current storage.

Parameters

storage

The storage containing the elements to retain in the current storage.

Return Values

No value is returned.

Examples

Example #1 SplObjectStorage::removeAllExcept() example

<?php
$a = (object) 'a';
$b = (object) 'b';
$c = (object) 'c';

$foo = new SplObjectStorage;
$foo->attach($a);
$foo->attach($b);

$bar = new SplObjectStorage;
$bar->attach($b);
$bar->attach($c);

$foo->removeAllExcept($bar);
var_dump($foo->contains($a));
var_dump($foo->contains($b));
?>

The above example will output something similar to:

bool(false)
bool(true)


Rewind the iterator to the first storage element

  • « SplObjectStorage::removeAllExcept
  • SplObjectStorage::serialize »
  • PHP Manual
  • SplObjectStorage
  • Rewind the iterator to the first storage element

SplObjectStorage::rewind

(PHP 5 >= 5.1.0, PHP 7)

SplObjectStorage::rewind — Rewind the iterator to the first storage element

Description

public SplObjectStorage::rewind ( void ) : void

Rewind the iterator to the first storage element.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 SplObjectStorage::rewind() example

<?php
$s = new SplObjectStorage();

$o1 = new StdClass;
$o2 = new StdClass;

$s->attach($o1, "d1");
$s->attach($o2, "d2");

$s->rewind();
while($s->valid()) {
    $index  = $s->key();
    $object = $s->current(); // similar to current($s)
    $data   = $s->getInfo();

    var_dump($object);
    var_dump($data);
    $s->next();
}
?>

The above example will output something similar to:

int(1)
int(0)

See Also

  • SplObjectStorage::next() - Move to the next entry


Serializes the storage

  • « SplObjectStorage::rewind
  • SplObjectStorage::setInfo »
  • PHP Manual
  • SplObjectStorage
  • Serializes the storage

SplObjectStorage::serialize

(PHP 5 >= 5.2.2, PHP 7)

SplObjectStorage::serialize — Serializes the storage

Description

public SplObjectStorage::serialize ( void ) : string

Returns a string representation of the storage.

Parameters

This function has no parameters.

Return Values

A string representing the storage.

Examples

Example #1 SplObjectStorage::serialize() example

<?php
$s = new SplObjectStorage;
$o = new StdClass;
$s[$o] = "data";

echo $s->serialize()."\n";
?>

The above example will output something similar to:

x:i:1;O:8:"stdClass":0:{},s:4:"data";;m:a:0:{}

See Also

  • SplObjectStorage::unserialize() - Unserializes a storage from its string representation


Sets the data associated with the current iterator entry

  • « SplObjectStorage::serialize
  • SplObjectStorage::unserialize »
  • PHP Manual
  • SplObjectStorage
  • Sets the data associated with the current iterator entry

SplObjectStorage::setInfo

(PHP 5 >= 5.3.0, PHP 7)

SplObjectStorage::setInfo — Sets the data associated with the current iterator entry

Description

public SplObjectStorage::setInfo ( mixed $data ) : void

Associates data, or info, with the object currently pointed to by the iterator.

Parameters

data

The data to associate with the current iterator entry.

Return Values

No value is returned.

Examples

Example #1 SplObjectStorage::setInfo() example

<?php
$s = new SplObjectStorage();

$o1 = new StdClass;
$o2 = new StdClass;

$s->attach($o1, "d1");
$s->attach($o2, "d2");

$s->rewind();
while($s->valid()) {
    $s->setInfo("new");
    $s->next();
}
var_dump($s[$o1]);
var_dump($s[$o2]);
?>

The above example will output something similar to:

string(3) "new"
string(3) "new"

See Also

  • SplObjectStorage::current() - Returns the current storage entry
  • SplObjectStorage::rewind() - Rewind the iterator to the first storage element
  • SplObjectStorage::key() - Returns the index at which the iterator currently is
  • SplObjectStorage::next() - Move to the next entry
  • SplObjectStorage::valid() - Returns if the current iterator entry is valid
  • SplObjectStorage::getInfo() - Returns the data associated with the current iterator entry


Unserializes a storage from its string representation

  • « SplObjectStorage::setInfo
  • SplObjectStorage::valid »
  • PHP Manual
  • SplObjectStorage
  • Unserializes a storage from its string representation

SplObjectStorage::unserialize

(PHP 5 >= 5.2.2, PHP 7)

SplObjectStorage::unserialize — Unserializes a storage from its string representation

Description

public SplObjectStorage::unserialize ( string $serialized ) : void

Unserializes storage entries and attach them to the current storage.

Parameters

serialized

The serialized representation of a storage.

Return Values

No value is returned.

Examples

Example #1 SplObjectStorage::unserialize() example

<?php
$s1 = new SplObjectStorage;
$s2 = new SplObjectStorage;
$o = new StdClass;
$s1[$o] = "data";

$s2->unserialize($s1->serialize());

var_dump(count($s2));
?>

The above example will output something similar to:

int(1)

See Also

  • SplObjectStorage::serialize() - Serializes the storage


Returns if the current iterator entry is valid

  • « SplObjectStorage::unserialize
  • Iterators »
  • PHP Manual
  • SplObjectStorage
  • Returns if the current iterator entry is valid

SplObjectStorage::valid

(PHP 5 >= 5.1.0, PHP 7)

SplObjectStorage::valid — Returns if the current iterator entry is valid

Description

public SplObjectStorage::valid ( void ) : bool

Returns if the current iterator entry is valid.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the iterator entry is valid, FALSE otherwise.

Examples

Example #1 SplObjectStorage::valid() example

<?php
$s = new SplObjectStorage();

$o1 = new StdClass;
$o2 = new StdClass;

$s->attach($o1, "d1");
$s->attach($o2, "d2");

$s->rewind();
while($s->valid()) {
    echo $s->key()."\n";
    $s->next();
}
?>

The above example will output something similar to:

0
1

See Also

  • SplObjectStorage::current() - Returns the current storage entry
  • SplObjectStorage::getInfo() - Returns the data associated with the current iterator entry


Iterators

Table of Contents

  • AppendIterator
  • ArrayIterator
  • CachingIterator
  • CallbackFilterIterator
  • DirectoryIterator
  • EmptyIterator
  • FilesystemIterator
  • FilterIterator
  • GlobIterator
  • InfiniteIterator
  • IteratorIterator
  • LimitIterator
  • MultipleIterator
  • NoRewindIterator
  • ParentIterator
  • RecursiveArrayIterator
  • RecursiveCachingIterator
  • RecursiveCallbackFilterIterator
  • RecursiveDirectoryIterator
  • RecursiveFilterIterator
  • RecursiveIteratorIterator
  • RecursiveRegexIterator
  • RecursiveTreeIterator
  • RegexIterator

SPL provides a set of iterators to traverse over objects.

SPL Iterators Class Tree

  • ArrayIterator
    • RecursiveArrayIterator
  • EmptyIterator
  • IteratorIterator
    • AppendIterator
    • CachingIterator
      • RecursiveCachingIterator
    • FilterIterator
      • CallbackFilterIterator
        • RecursiveCallbackFilterIterator
      • RecursiveFilterIterator
        • ParentIterator
      • RegexIterator
        • RecursiveRegexIterator
    • InfiniteIterator
    • LimitIterator
    • NoRewindIterator
  • MultipleIterator
  • RecursiveIteratorIterator
    • RecursiveTreeIterator
  • DirectoryIterator (extends SplFileInfo)
    • FilesystemIterator
      • GlobIterator
      • RecursiveDirectoryIterator


The AppendIterator class

(PHP 5 >= 5.1.0, PHP 7)

Introduction

An Iterator that iterates over several iterators one after the other.

Class synopsis

AppendIterator extends IteratorIterator implements OuterIterator {
/* Methods */
public __construct ( void )
public append ( Iterator $iterator ) : void
public current ( void ) : mixed
public getArrayIterator ( void ) : ArrayIterator
public getInnerIterator ( void ) : Iterator
public getIteratorIndex ( void ) : int
public key ( void ) : scalar
public next ( void ) : void
public rewind ( void ) : void
public valid ( void ) : bool
/* Inherited methods */
public IteratorIterator::__construct ( Traversable $iterator )
public IteratorIterator::current ( void ) : mixed
public IteratorIterator::getInnerIterator ( void ) : Traversable
public IteratorIterator::key ( void ) : mixed
public IteratorIterator::next ( void ) : void
public IteratorIterator::rewind ( void ) : void
public IteratorIterator::valid ( void ) : bool
}

Table of Contents

  • AppendIterator::append — Appends an iterator
  • AppendIterator::__construct — Constructs an AppendIterator
  • AppendIterator::current — Gets the current value
  • AppendIterator::getArrayIterator — Gets the ArrayIterator
  • AppendIterator::getInnerIterator — Gets the inner iterator
  • AppendIterator::getIteratorIndex — Gets an index of iterators
  • AppendIterator::key — Gets the current key
  • AppendIterator::next — Moves to the next element
  • AppendIterator::rewind — Rewinds the Iterator
  • AppendIterator::valid — Checks validity of the current element


Appends an iterator

  • « AppendIterator
  • AppendIterator::__construct »
  • PHP Manual
  • AppendIterator
  • Appends an iterator

AppendIterator::append

(PHP 5 >= 5.1.0, PHP 7)

AppendIterator::append — Appends an iterator

Description

public AppendIterator::append ( Iterator $iterator ) : void

Appends an iterator.

Parameters

iterator

The iterator to append.

Return Values

No value is returned.

Examples

Example #1 AppendIterator::append() example

<?php
$array_a = new ArrayIterator(array('a', 'b', 'c'));
$array_b = new ArrayIterator(array('d', 'e', 'f'));

$iterator = new AppendIterator;
$iterator->append($array_a);
$iterator->append($array_b);

foreach ($iterator as $current) {
    echo $current;
}
?>

The above example will output:

abcdef

See Also

  • AppendIterator::__construct() - Constructs an AppendIterator


Constructs an AppendIterator

  • « AppendIterator::append
  • AppendIterator::current »
  • PHP Manual
  • AppendIterator
  • Constructs an AppendIterator

AppendIterator::__construct

(PHP 5 >= 5.1.0, PHP 7)

AppendIterator::__construct — Constructs an AppendIterator

Description

public AppendIterator::__construct ( void )

Constructs an AppendIterator.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 Iterating AppendIterator with foreach

<?php
$pizzas   = new ArrayIterator(array('Margarita', 'Siciliana', 'Hawaii'));
$toppings = new ArrayIterator(array('Cheese', 'Anchovies', 'Olives', 'Pineapple', 'Ham'));

$appendIterator = new AppendIterator;
$appendIterator->append($pizzas);
$appendIterator->append($toppings);

foreach ($appendIterator as $key => $item) {
    echo $key . ' => ' . $item . PHP_EOL;
}
?>

The above example will output:

0 => Margarita
1 => Siciliana
2 => Hawaii
0 => Cheese
1 => Anchovies
2 => Olives
3 => Pineapple
4 => Ham

Example #2 Iterating AppendIterator with the AppendIterator API

<?php
$pizzas   = new ArrayIterator(array('Margarita', 'Siciliana', 'Hawaii'));
$toppings = new ArrayIterator(array('Cheese', 'Anchovies', 'Olives', 'Pineapple', 'Ham'));

$appendIterator = new AppendIterator;
$appendIterator->append($pizzas);
$appendIterator->append($toppings);

while ($appendIterator->valid()) {
    printf(
        '%s => %s => %s%s',
        $appendIterator->getIteratorIndex(),
        $appendIterator->key(),
        $appendIterator->current(),
        PHP_EOL
    );
    $appendIterator->next();
}
?>

The above example will output:

0 => 0 => Margarita
0 => 1 => Siciliana
0 => 2 => Hawaii
1 => 0 => Cheese
1 => 1 => Anchovies
1 => 2 => Olives
1 => 3 => Pineapple
1 => 4 => Ham

Notes

Caution

When using iterator_to_array() to copy the values of the AppendIterator into an array, you have to set the optional use_key argument to FALSE. When use_key is not FALSE any keys reoccuring in inner iterators will get overwritten in the returned array. There is no way to preserve the original keys.

See Also

  • AppendIterator::append() - Appends an iterator


Gets the current value

  • « AppendIterator::__construct
  • AppendIterator::getArrayIterator »
  • PHP Manual
  • AppendIterator
  • Gets the current value

AppendIterator::current

(PHP 5 >= 5.1.0, PHP 7)

AppendIterator::current — Gets the current value

Description

public AppendIterator::current ( void ) : mixed

Gets the current value.

Parameters

This function has no parameters.

Return Values

The current value if it is valid or NULL otherwise.

See Also

  • Iterator::current() - Return the current element
  • AppendIterator::key() - Gets the current key
  • AppendIterator::valid() - Checks validity of the current element
  • AppendIterator::next() - Moves to the next element
  • AppendIterator::rewind() - Rewinds the Iterator


Gets the ArrayIterator

  • « AppendIterator::current
  • AppendIterator::getInnerIterator »
  • PHP Manual
  • AppendIterator
  • Gets the ArrayIterator

AppendIterator::getArrayIterator

(PHP 5 >= 5.2.0, PHP 7)

AppendIterator::getArrayIterator — Gets the ArrayIterator

Description

public AppendIterator::getArrayIterator ( void ) : ArrayIterator

This method gets the ArrayIterator that is used to store the iterators added with AppendIterator::append().

Parameters

This function has no parameters.

Return Values

Returns an ArrayIterator containing the appended iterators.

See Also

  • AppendIterator::getInnerIterator() - Gets the inner iterator


Gets the inner iterator

  • « AppendIterator::getArrayIterator
  • AppendIterator::getIteratorIndex »
  • PHP Manual
  • AppendIterator
  • Gets the inner iterator

AppendIterator::getInnerIterator

(PHP 5 >= 5.1.0, PHP 7)

AppendIterator::getInnerIterator — Gets the inner iterator

Description

public AppendIterator::getInnerIterator ( void ) : Iterator

This method returns the current inner iterator.

Parameters

This function has no parameters.

Return Values

The current inner iterator, or NULL if there is not one.

Examples

Example #1 AppendIterator::getInnerIterator() example

<?php
$array_a = new ArrayIterator(array('a' => 'aardwolf', 'b' => 'bear', 'c' => 'capybara'));
$array_b = new RegexIterator($array_a, '/^[ac]/');

$iterator = new AppendIterator;
$iterator->append($array_a);
$iterator->append($array_b);

foreach ($iterator as $current) {
    $inner = $iterator->getInnerIterator();
    if ($inner instanceOf RegexIterator) {
        echo 'Filtered: ';
    } else {
        echo 'Original: ';
    }
    echo $current . PHP_EOL;
}
?>

The above example will output:

Original: aardwolf
Original: bear
Original: capybara
Filtered: aardwolf
Filtered: capybara

See Also

  • AppendIterator::getIteratorIndex() - Gets an index of iterators


Gets an index of iterators

  • « AppendIterator::getInnerIterator
  • AppendIterator::key »
  • PHP Manual
  • AppendIterator
  • Gets an index of iterators

AppendIterator::getIteratorIndex

(PHP 5 >= 5.2.0, PHP 7)

AppendIterator::getIteratorIndex — Gets an index of iterators

Description

public AppendIterator::getIteratorIndex ( void ) : int

Gets the index of the current inner iterator.

Parameters

This function has no parameters.

Return Values

Returns an integer, which is the zero-based index of the current inner iterator.

Examples

Example #1 AppendIterator.getIteratorIndex() basic example

<?php
$array_a = new ArrayIterator(array('a' => 'aardwolf', 'b' => 'bear', 'c' => 'capybara'));
$array_b = new ArrayIterator(array('apple', 'orange', 'lemon'));

$iterator = new AppendIterator;
$iterator->append($array_a);
$iterator->append($array_b);

foreach ($iterator as $key => $current) {
    echo $iterator->getIteratorIndex() . '  ' . $key . ' ' . $current . PHP_EOL;
}
?>

The above example will output:

0  a aardwolf
0  b bear
0  c capybara
1  0 apple
1  1 orange
1  2 lemon

See Also

  • AppendIterator::getInnerIterator() - Gets the inner iterator
  • AppendIterator::getArrayIterator() - Gets the ArrayIterator


Gets the current key

  • « AppendIterator::getIteratorIndex
  • AppendIterator::next »
  • PHP Manual
  • AppendIterator
  • Gets the current key

AppendIterator::key

(PHP 5 >= 5.1.0, PHP 7)

AppendIterator::key — Gets the current key

Description

public AppendIterator::key ( void ) : scalar

Get the current key.

Parameters

This function has no parameters.

Return Values

The current key if it is valid or NULL otherwise.

Examples

Example #1 AppendIterator::key() basic example

<?php
$array_a = new ArrayIterator(array('a' => 'aardwolf', 'b' => 'bear', 'c' => 'capybara'));
$array_b = new ArrayIterator(array('apple', 'orange', 'lemon'));

$iterator = new AppendIterator;
$iterator->append($array_a);
$iterator->append($array_b);

// Manual iteration
$iterator->rewind();
while ($iterator->valid()) {
    echo $iterator->key() . ' ' . $iterator->current() . PHP_EOL;
    $iterator->next();
}

echo PHP_EOL;

// With foreach
foreach ($iterator as $key => $current) {
    echo $key . ' ' . $current . PHP_EOL;
}
?>

The above example will output:

a aardwolf
b bear
c capybara
0 apple
1 orange
2 lemon

a aardwolf
b bear
c capybara
0 apple
1 orange
2 lemon

See Also

  • Iterator::key() - Return the key of the current element
  • AppendIterator::current() - Gets the current value
  • AppendIterator::valid() - Checks validity of the current element
  • AppendIterator::next() - Moves to the next element
  • AppendIterator::rewind() - Rewinds the Iterator


Moves to the next element

  • « AppendIterator::key
  • AppendIterator::rewind »
  • PHP Manual
  • AppendIterator
  • Moves to the next element

AppendIterator::next

(PHP 5 >= 5.1.0, PHP 7)

AppendIterator::next — Moves to the next element

Description

public AppendIterator::next ( void ) : void

Moves to the next element. If this means to another Iterator then it rewinds that Iterator.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • Iterator::next() - Move forward to next element
  • AppendIterator::current() - Gets the current value
  • AppendIterator::key() - Gets the current key
  • AppendIterator::valid() - Checks validity of the current element
  • AppendIterator::rewind() - Rewinds the Iterator


Rewinds the Iterator

  • « AppendIterator::next
  • AppendIterator::valid »
  • PHP Manual
  • AppendIterator
  • Rewinds the Iterator

AppendIterator::rewind

(PHP 5 >= 5.1.0, PHP 7)

AppendIterator::rewind — Rewinds the Iterator

Description

public AppendIterator::rewind ( void ) : void

Rewind to the first element of the first inner Iterator.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • Iterator::rewind() - Rewind the Iterator to the first element
  • AppendIterator::current() - Gets the current value
  • AppendIterator::key() - Gets the current key
  • AppendIterator::next() - Moves to the next element
  • AppendIterator::valid() - Checks validity of the current element


Checks validity of the current element

  • « AppendIterator::rewind
  • ArrayIterator »
  • PHP Manual
  • AppendIterator
  • Checks validity of the current element

AppendIterator::valid

(PHP 5 >= 5.1.0, PHP 7)

AppendIterator::valid — Checks validity of the current element

Description

public AppendIterator::valid ( void ) : bool

Checks validity of the current element.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the current iteration is valid, FALSE otherwise.

See Also

  • AppendIterator::current() - Gets the current value
  • AppendIterator::key() - Gets the current key
  • AppendIterator::next() - Moves to the next element
  • AppendIterator::rewind() - Rewinds the Iterator


The ArrayIterator class

(PHP 5, PHP 7)

Introduction

This iterator allows to unset and modify values and keys while iterating over Arrays and Objects.

When you want to iterate over the same array multiple times you need to instantiate ArrayObject and let it create ArrayIterator instances that refer to it either by using foreach or by calling its getIterator() method manually.

Class synopsis

ArrayIterator implements ArrayAccess , SeekableIterator , Countable , Serializable {
/* Constants */
const integer STD_PROP_LIST = 1 ;
const integer ARRAY_AS_PROPS = 2 ;
/* Methods */
public append ( mixed $value ) : void
public asort ( void ) : void
public __construct ([ mixed $array = array() [, int $flags = 0 ]] )
public count ( void ) : int
public current ( void ) : mixed
public getArrayCopy ( void ) : array
public getFlags ( void ) : int
public key ( void ) : mixed
public ksort ( void ) : void
public natcasesort ( void ) : void
public natsort ( void ) : void
public next ( void ) : void
public offsetExists ( mixed $index ) : bool
public offsetGet ( mixed $index ) : mixed
public offsetSet ( mixed $index , mixed $newval ) : void
public offsetUnset ( mixed $index ) : void
public rewind ( void ) : void
public seek ( int $position ) : void
public serialize ( void ) : string
public setFlags ( string $flags ) : void
public uasort ( callable $cmp_function ) : void
public uksort ( callable $cmp_function ) : void
public unserialize ( string $serialized ) : void
public valid ( void ) : bool
}

Predefined Constants

ArrayIterator Flags

ArrayIterator::STD_PROP_LIST

Properties of the object have their normal functionality when accessed as list (var_dump, foreach, etc.).

ArrayIterator::ARRAY_AS_PROPS

Entries can be accessed as properties (read and write).

Table of Contents

  • ArrayIterator::append — Append an element
  • ArrayIterator::asort — Sort array by values
  • ArrayIterator::__construct — Construct an ArrayIterator
  • ArrayIterator::count — Count elements
  • ArrayIterator::current — Return current array entry
  • ArrayIterator::getArrayCopy — Get array copy
  • ArrayIterator::getFlags — Get behavior flags
  • ArrayIterator::key — Return current array key
  • ArrayIterator::ksort — Sort array by keys
  • ArrayIterator::natcasesort — Sort an array naturally, case insensitive
  • ArrayIterator::natsort — Sort an array naturally
  • ArrayIterator::next — Move to next entry
  • ArrayIterator::offsetExists — Check if offset exists
  • ArrayIterator::offsetGet — Get value for an offset
  • ArrayIterator::offsetSet — Set value for an offset
  • ArrayIterator::offsetUnset — Unset value for an offset
  • ArrayIterator::rewind — Rewind array back to the start
  • ArrayIterator::seek — Seek to position
  • ArrayIterator::serialize — Serialize
  • ArrayIterator::setFlags — Set behaviour flags
  • ArrayIterator::uasort — Sort with a user-defined comparison function and maintain index association
  • ArrayIterator::uksort — Sort by keys using a user-defined comparison function
  • ArrayIterator::unserialize — Unserialize
  • ArrayIterator::valid — Check whether array contains more entries


Append an element

  • « ArrayIterator
  • ArrayIterator::asort »
  • PHP Manual
  • ArrayIterator
  • Append an element

ArrayIterator::append

(PHP 5, PHP 7)

ArrayIterator::append — Append an element

Description

public ArrayIterator::append ( mixed $value ) : void

Appends value as the last element.

Warning

This function is currently not documented; only its argument list is available.

Parameters

value

The value to append.

Return Values

No value is returned.

Notes

Note:

This method cannot be called when the ArrayIterator refers to an object.

See Also

  • ArrayIterator::next() - Move to next entry


Sort array by values

  • « ArrayIterator::append
  • ArrayIterator::__construct »
  • PHP Manual
  • ArrayIterator
  • Sort array by values

ArrayIterator::asort

(PHP 5 >= 5.2.0, PHP 7)

ArrayIterator::asort — Sort array by values

Description

public ArrayIterator::asort ( void ) : void

Sorts an array by values.

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.

See Also

  • ArrayIterator::ksort() - Sort array by keys
  • ArrayIterator::natcasesort() - Sort an array naturally, case insensitive
  • ArrayIterator::natsort() - Sort an array naturally


Construct an ArrayIterator

  • « ArrayIterator::asort
  • ArrayIterator::count »
  • PHP Manual
  • ArrayIterator
  • Construct an ArrayIterator

ArrayIterator::__construct

(PHP 5, PHP 7)

ArrayIterator::__construct — Construct an ArrayIterator

Description

public ArrayIterator::__construct ([ mixed $array = array() [, int $flags = 0 ]] )

Constructs an ArrayIterator object.

Warning

This function is currently not documented; only its argument list is available.

Parameters

array

The array or object to be iterated on.

flags

Flags to control the behaviour of the ArrayIterator object. See ArrayIterator::setFlags().

Return Values

An ArrayIterator object.

Errors/Exceptions

ArrayIterator::__construct() throws an InvalidArgumentException if anything besides an array or an object is given.

See Also

  • ArrayIterator::getArrayCopy() - Get array copy


Count elements

  • « ArrayIterator::__construct
  • ArrayIterator::current »
  • PHP Manual
  • ArrayIterator
  • Count elements

ArrayIterator::count

(PHP 5, PHP 7)

ArrayIterator::count — Count elements

Description

public ArrayIterator::count ( void ) : int

Gets the number of elements in the array, or the number of public properties in the object.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The number of elements or public properties in the associated array or object, respectively.

See Also

  • ArrayIterator::getFlags() - Get behavior flags


Return current array entry

  • « ArrayIterator::count
  • ArrayIterator::getArrayCopy »
  • PHP Manual
  • ArrayIterator
  • Return current array entry

ArrayIterator::current

(PHP 5, PHP 7)

ArrayIterator::current — Return current array entry

Description

public ArrayIterator::current ( void ) : mixed

Get the current array entry.

Parameters

This function has no parameters.

Return Values

The current array entry.

Examples

Example #1 ArrayIterator::current() example

<?php
$array = array('1' => 'one',
               '2' => 'two',
               '3' => 'three');

$arrayobject = new ArrayObject($array);

for($iterator = $arrayobject->getIterator();
    $iterator->valid();
    $iterator->next()) {

    echo $iterator->key() . ' => ' . $iterator->current() . "\n";
}
?>

The above example will output:

1 => one
2 => two
3 => three


Get array copy

  • « ArrayIterator::current
  • ArrayIterator::getFlags »
  • PHP Manual
  • ArrayIterator
  • Get array copy

ArrayIterator::getArrayCopy

(PHP 5, PHP 7)

ArrayIterator::getArrayCopy — Get array copy

Description

public ArrayIterator::getArrayCopy ( void ) : array

Get a copy of an array.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

A copy of the array, or array of public properties if ArrayIterator refers to an object.

See Also

  • ArrayIterator::valid() - Check whether array contains more entries


Get behavior flags

  • « ArrayIterator::getArrayCopy
  • ArrayIterator::key »
  • PHP Manual
  • ArrayIterator
  • Get behavior flags

ArrayIterator::getFlags

(PHP 5 >= 5.1.0, PHP 7)

ArrayIterator::getFlags — Get behavior flags

Description

public ArrayIterator::getFlags ( void ) : int

Gets the behavior flags of the ArrayIterator. See the ArrayIterator::setFlags method for a list of the available flags.

Parameters

This function has no parameters.

Return Values

Returns the behavior flags of the ArrayIterator.

See Also

  • >ArrayIterator::setFlags()
  • ArrayIterator::valid() - Check whether array contains more entries


Return current array key

  • « ArrayIterator::getFlags
  • ArrayIterator::ksort »
  • PHP Manual
  • ArrayIterator
  • Return current array key

ArrayIterator::key

(PHP 5, PHP 7)

ArrayIterator::key — Return current array key

Description

public ArrayIterator::key ( void ) : mixed

This function returns the current array key

Parameters

This function has no parameters.

Return Values

The current array key.

Examples

Example #1 ArrayIterator::key() example

<?php
$array = array('key' => 'value');

$arrayobject = new ArrayObject($array);
$iterator = $arrayobject->getIterator();

echo $iterator->key(); //key
?>


Sort array by keys

  • « ArrayIterator::key
  • ArrayIterator::natcasesort »
  • PHP Manual
  • ArrayIterator
  • Sort array by keys

ArrayIterator::ksort

(PHP 5 >= 5.2.0, PHP 7)

ArrayIterator::ksort — Sort array by keys

Description

public ArrayIterator::ksort ( void ) : void

Sorts an array by the keys.

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.

See Also

  • ArrayIterator::asort() - Sort array by values
  • ArrayIterator::natcasesort() - Sort an array naturally, case insensitive
  • ArrayIterator::natsort() - Sort an array naturally


Sort an array naturally, case insensitive

  • « ArrayIterator::ksort
  • ArrayIterator::natsort »
  • PHP Manual
  • ArrayIterator
  • Sort an array naturally, case insensitive

ArrayIterator::natcasesort

(PHP 5 >= 5.2.0, PHP 7)

ArrayIterator::natcasesort — Sort an array naturally, case insensitive

Description

public ArrayIterator::natcasesort ( void ) : void

Sort the entries by values using a case insensitive "natural order" algorithm.

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.

See Also

  • ArrayIterator::asort() - Sort array by values
  • ArrayIterator::ksort() - Sort array by keys
  • ArrayIterator::natsort() - Sort an array naturally
  • natcasesort() - Sort an array using a case insensitive "natural order" algorithm


Sort an array naturally

  • « ArrayIterator::natcasesort
  • ArrayIterator::next »
  • PHP Manual
  • ArrayIterator
  • Sort an array naturally

ArrayIterator::natsort

(PHP 5 >= 5.2.0, PHP 7)

ArrayIterator::natsort — Sort an array naturally

Description

public ArrayIterator::natsort ( void ) : void

Sort the entries by values using "natural order" algorithm.

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.

See Also

  • ArrayIterator::asort() - Sort array by values
  • ArrayIterator::ksort() - Sort array by keys
  • ArrayIterator::natcasesort() - Sort an array naturally, case insensitive
  • natsort() - Sort an array using a "natural order" algorithm


Move to next entry

  • « ArrayIterator::natsort
  • ArrayIterator::offsetExists »
  • PHP Manual
  • ArrayIterator
  • Move to next entry

ArrayIterator::next

(PHP 5, PHP 7)

ArrayIterator::next — Move to next entry

Description

public ArrayIterator::next ( void ) : void

The iterator to the next entry.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 ArrayIterator::next() example

<?php
$arrayobject = new ArrayObject();

$arrayobject[] = 'zero';
$arrayobject[] = 'one';

$iterator = $arrayobject->getIterator();

while($iterator->valid()) {
    echo $iterator->key() . ' => ' . $iterator->current() . "\n";

    $iterator->next();
}
?>

The above example will output:

0 => zero
1 => one


Check if offset exists

  • « ArrayIterator::next
  • ArrayIterator::offsetGet »
  • PHP Manual
  • ArrayIterator
  • Check if offset exists

ArrayIterator::offsetExists

(PHP 5, PHP 7)

ArrayIterator::offsetExists — Check if offset exists

Description

public ArrayIterator::offsetExists ( mixed $index ) : bool

Checks if the offset exists.

Warning

This function is currently not documented; only its argument list is available.

Parameters

index

The offset being checked.

Return Values

TRUE if the offset exists, otherwise FALSE

See Also

  • ArrayIterator::valid() - Check whether array contains more entries


Get value for an offset

  • « ArrayIterator::offsetExists
  • ArrayIterator::offsetSet »
  • PHP Manual
  • ArrayIterator
  • Get value for an offset

ArrayIterator::offsetGet

(PHP 5, PHP 7)

ArrayIterator::offsetGet — Get value for an offset

Description

public ArrayIterator::offsetGet ( mixed $index ) : mixed

Gets the value from the provided offset.

Warning

This function is currently not documented; only its argument list is available.

Parameters

index

The offset to get the value from.

Return Values

The value at offset index.

See Also

  • ArrayIterator::offsetSet() - Set value for an offset
  • ArrayIterator::offsetUnset() - Unset value for an offset


Set value for an offset

  • « ArrayIterator::offsetGet
  • ArrayIterator::offsetUnset »
  • PHP Manual
  • ArrayIterator
  • Set value for an offset

ArrayIterator::offsetSet

(PHP 5, PHP 7)

ArrayIterator::offsetSet — Set value for an offset

Description

public ArrayIterator::offsetSet ( mixed $index , mixed $newval ) : void

Sets a value for a given offset.

Warning

This function is currently not documented; only its argument list is available.

Parameters

index

The index to set for.

newval

The new value to store at the index.

Return Values

No value is returned.

See Also

  • ArrayIterator::offsetGet() - Get value for an offset
  • ArrayIterator::offsetUnset() - Unset value for an offset


Unset value for an offset

  • « ArrayIterator::offsetSet
  • ArrayIterator::rewind »
  • PHP Manual
  • ArrayIterator
  • Unset value for an offset

ArrayIterator::offsetUnset

(PHP 5, PHP 7)

ArrayIterator::offsetUnset — Unset value for an offset

Description

public ArrayIterator::offsetUnset ( mixed $index ) : void

Unsets a value for an offset.

Warning

This function is currently not documented; only its argument list is available.

Parameters

index

The offset to unset.

Return Values

No value is returned.

See Also

  • ArrayIterator::offsetGet() - Get value for an offset
  • ArrayIterator::offsetSet() - Set value for an offset


Rewind array back to the start

  • « ArrayIterator::offsetUnset
  • ArrayIterator::seek »
  • PHP Manual
  • ArrayIterator
  • Rewind array back to the start

ArrayIterator::rewind

(PHP 5, PHP 7)

ArrayIterator::rewind — Rewind array back to the start

Description

public ArrayIterator::rewind ( void ) : void

This rewinds the iterator to the beginning.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 ArrayIterator::rewind() example

<?php
$arrayobject = new ArrayObject();

$arrayobject[] = 'zero';
$arrayobject[] = 'one';
$arrayobject[] = 'two';

$iterator = $arrayobject->getIterator();

$iterator->next();
echo $iterator->key(); //1

$iterator->rewind(); //rewinding to the begining
echo $iterator->key(); //0
?>


Seek to position

  • « ArrayIterator::rewind
  • ArrayIterator::serialize »
  • PHP Manual
  • ArrayIterator
  • Seek to position

ArrayIterator::seek

(PHP 5, PHP 7)

ArrayIterator::seek — Seek to position

Description

public ArrayIterator::seek ( int $position ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

position

The position to seek to.

Return Values

No value is returned.


Serialize

  • « ArrayIterator::seek
  • ArrayIterator::setFlags »
  • PHP Manual
  • ArrayIterator
  • Serialize

ArrayIterator::serialize

(PHP 5 >= 5.3.0, PHP 7)

ArrayIterator::serialize — Serialize

Description

public ArrayIterator::serialize ( void ) : string

Serialize.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The serialized ArrayIterator.

See Also

  • ArrayIterator::unserialize() - Unserialize


Set behaviour flags

  • « ArrayIterator::serialize
  • ArrayIterator::uasort »
  • PHP Manual
  • ArrayIterator
  • Set behaviour flags

ArrayIterator::setFlags

(PHP 5 >= 5.1.0, PHP 7)

ArrayIterator::setFlags — Set behaviour flags

Description

public ArrayIterator::setFlags ( string $flags ) : void

Set the flags that change the behavior of the ArrayIterator.

Parameters

flags

The new ArrayIterator behavior. It takes on either a bitmask, or named constants. Using named constants is strongly encouraged to ensure compatibility for future versions.

The available behavior flags are listed below. The actual meanings of these flags are described in the predefined constants.

ArrayIterator behavior flags
value | constant
1 | ArrayIterator::STD_PROP_LIST
2 | ArrayIterator::ARRAY_AS_PROPS

Return Values

No value is returned.

See Also

  • ArrayIterator::getFlags() - Get behavior flags


Sort with a user-defined comparison function and maintain index association

  • « ArrayIterator::setFlags
  • ArrayIterator::uksort »
  • PHP Manual
  • ArrayIterator
  • Sort with a user-defined comparison function and maintain index association

ArrayIterator::uasort

(PHP 5 >= 5.2.0, PHP 7)

ArrayIterator::uasort — Sort with a user-defined comparison function and maintain index association

Description

public ArrayIterator::uasort ( callable $cmp_function ) : void

This method sorts the elements such that indices maintain their correlation with the values they are associated with, using a user-defined comparison function.

Note:

If two members compare as equal, their relative order in the sorted array is undefined.

Parameters

cmp_function

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. Note that before PHP 7.0.0 this integer had to be in the range from -2147483648 to 2147483647.

callback ( mixed $a, mixed $b ) : int

Return Values

No value is returned.

See Also

  • ArrayIterator::asort() - Sort array by values
  • ArrayIterator::uksort() - Sort by keys using a user-defined comparison function
  • usort() - Sort an array by values using a user-defined comparison function


Sort by keys using a user-defined comparison function

  • « ArrayIterator::uasort
  • ArrayIterator::unserialize »
  • PHP Manual
  • ArrayIterator
  • Sort by keys using a user-defined comparison function

ArrayIterator::uksort

(PHP 5 >= 5.2.0, PHP 7)

ArrayIterator::uksort — Sort by keys using a user-defined comparison function

Description

public ArrayIterator::uksort ( callable $cmp_function ) : void

This method sorts the elements by keys using a user-supplied comparison function.

Note:

If two members compare as equal, their relative order in the sorted array is undefined.

Parameters

cmp_function

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. Note that before PHP 7.0.0 this integer had to be in the range from -2147483648 to 2147483647.

callback ( mixed $a, mixed $b ) : int

Return Values

No value is returned.

See Also

  • ArrayIterator::ksort() - Sort array by keys
  • ArrayIterator::uasort() - Sort with a user-defined comparison function and maintain index association
  • uksort() - Sort an array by keys using a user-defined comparison function


Unserialize

  • « ArrayIterator::uksort
  • ArrayIterator::valid »
  • PHP Manual
  • ArrayIterator
  • Unserialize

ArrayIterator::unserialize

(PHP 5 >= 5.3.0, PHP 7)

ArrayIterator::unserialize — Unserialize

Description

public ArrayIterator::unserialize ( string $serialized ) : void

Unserialize.

Warning

This function is currently not documented; only its argument list is available.

Parameters

serialized

The serialized ArrayIterator object to be unserialized.

Return Values

No value is returned.

See Also

  • ArrayIterator::serialize() - Serialize


Check whether array contains more entries

  • « ArrayIterator::unserialize
  • CachingIterator »
  • PHP Manual
  • ArrayIterator
  • Check whether array contains more entries

ArrayIterator::valid

(PHP 5, PHP 7)

ArrayIterator::valid — Check whether array contains more entries

Description

public ArrayIterator::valid ( void ) : bool

Checks if the array contains any more entries.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the iterator is valid, otherwise FALSE

Examples

Example #1 ArrayIterator::valid() example

<?php
$array = array('1' => 'one');

$arrayobject = new ArrayObject($array);
$iterator = $arrayobject->getIterator();

var_dump($iterator->valid()); //bool(true)

$iterator->next(); // advance to the next item

//bool(false) because there is only one array element
var_dump($iterator->valid());
?>


The CachingIterator class

(PHP 5, PHP 7)

Introduction

This object supports cached iteration over another iterator.

Class synopsis

CachingIterator extends IteratorIterator implements OuterIterator , ArrayAccess , Countable {
/* Constants */
const integer CALL_TOSTRING = 1 ;
const integer CATCH_GET_CHILD = 16 ;
const integer TOSTRING_USE_KEY = 2 ;
const integer TOSTRING_USE_CURRENT = 4 ;
const integer TOSTRING_USE_INNER = 8 ;
const integer FULL_CACHE = 256 ;
/* Methods */
public __construct ( Iterator $iterator [, int $flags = self::CALL_TOSTRING ] )
public count ( void ) : int
public current ( void ) : mixed
public getCache ( void ) : array
public getFlags ( void ) : int
public getInnerIterator ( void ) : Iterator
public hasNext ( void ) : void
public key ( void ) : scalar
public next ( void ) : void
public offsetExists ( mixed $index ) : void
public offsetGet ( string $index ) : void
public offsetSet ( mixed $index , mixed $newval ) : void
public offsetUnset ( string $index ) : void
public rewind ( void ) : void
public setFlags ( int $flags ) : void
public __toString ( void ) : void
public valid ( void ) : void
}

Predefined Constants

CachingIterator::CALL_TOSTRING

Convert every element to string.

CachingIterator::CATCH_GET_CHILD

Don't throw exception in accessing children.

CachingIterator::TOSTRING_USE_KEY

Use key for conversion to string.

CachingIterator::TOSTRING_USE_CURRENT

Use current for conversion to string.

CachingIterator::TOSTRING_USE_INNER

Use inner for conversion to string.

CachingIterator::FULL_CACHE

Cache all read data.

Table of Contents

  • CachingIterator::__construct — Construct a new CachingIterator object for the iterator
  • CachingIterator::count — The number of elements in the iterator
  • CachingIterator::current — Return the current element
  • CachingIterator::getCache — Retrieve the contents of the cache
  • CachingIterator::getFlags — Get flags used
  • CachingIterator::getInnerIterator — Returns the inner iterator
  • CachingIterator::hasNext — Check whether the inner iterator has a valid next element
  • CachingIterator::key — Return the key for the current element
  • CachingIterator::next — Move the iterator forward
  • CachingIterator::offsetExists — The offsetExists purpose
  • CachingIterator::offsetGet — The offsetGet purpose
  • CachingIterator::offsetSet — The offsetSet purpose
  • CachingIterator::offsetUnset — The offsetUnset purpose
  • CachingIterator::rewind — Rewind the iterator
  • CachingIterator::setFlags — The setFlags purpose
  • CachingIterator::__toString — Return the string representation of the current element
  • CachingIterator::valid — Check whether the current element is valid


Construct a new CachingIterator object for the iterator

  • « CachingIterator
  • CachingIterator::count »
  • PHP Manual
  • CachingIterator
  • Construct a new CachingIterator object for the iterator

CachingIterator::__construct

(PHP 5, PHP 7)

CachingIterator::__construct — Construct a new CachingIterator object for the iterator

Description

public CachingIterator::__construct ( Iterator $iterator [, int $flags = self::CALL_TOSTRING ] )
Warning

This function is currently not documented; only its argument list is available.

Parameters

iterator

Iterator to cache

flags

Bitmask of flags.


The number of elements in the iterator

  • « CachingIterator::__construct
  • CachingIterator::current »
  • PHP Manual
  • CachingIterator
  • The number of elements in the iterator

CachingIterator::count

(PHP 5 >= 5.2.2, PHP 7)

CachingIterator::count — The number of elements in the iterator

Description

public CachingIterator::count ( void ) : int
Warning

This function is currently not documented; only its argument list is available.

May return the number of elements in the iterator.

Parameters

This function has no parameters.

Return Values

The count of the elements iterated over.


Return the current element

  • « CachingIterator::count
  • CachingIterator::getCache »
  • PHP Manual
  • CachingIterator
  • Return the current element

CachingIterator::current

(PHP 5, PHP 7)

CachingIterator::current — Return the current element

Description

public CachingIterator::current ( void ) : mixed
Warning

This function is currently not documented; only its argument list is available.

May return the current element in the iteration.

Parameters

This function has no parameters.

Return Values

Mixed

See Also

  • Iterator::current() - Return the current element


Retrieve the contents of the cache

  • « CachingIterator::current
  • CachingIterator::getFlags »
  • PHP Manual
  • CachingIterator
  • Retrieve the contents of the cache

CachingIterator::getCache

(PHP 5 >= 5.2.0, PHP 7)

CachingIterator::getCache — Retrieve the contents of the cache

Description

public CachingIterator::getCache ( void ) : array

Retrieve the contents of the cache.

Note:

The CachingIterator::FULL_CACHE flag must be being used.

Parameters

This function has no parameters.

Return Values

An array containing the cache items.

Errors/Exceptions

Throws a BadMethodCallException when the CachingIterator::FULL_CACHE flag is not being used.

Examples

Example #1 CachingIterator::getCache() example

<?php
$iterator = new ArrayIterator(array(1, 2, 3));
$cache    = new CachingIterator($iterator, CachingIterator::FULL_CACHE);

$cache->next();
$cache->next();
var_dump($cache->getCache());

$cache->next();
var_dump($cache->getCache());
?>

The above example will output:

array(2) {
  [0]=>
  int(1)
  [1]=>
  int(2)
}
array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}


Get flags used

  • « CachingIterator::getCache
  • CachingIterator::getInnerIterator »
  • PHP Manual
  • CachingIterator
  • Get flags used

CachingIterator::getFlags

(PHP 5 >= 5.2.0, PHP 7)

CachingIterator::getFlags — Get flags used

Description

public CachingIterator::getFlags ( void ) : int
Warning

This function is currently not documented; only its argument list is available.

Get the bitmask of the flags used for this CachingIterator instance.

Parameters

This function has no parameters.

Return Values

Description...


Returns the inner iterator

  • « CachingIterator::getFlags
  • CachingIterator::hasNext »
  • PHP Manual
  • CachingIterator
  • Returns the inner iterator

CachingIterator::getInnerIterator

(PHP 5, PHP 7)

CachingIterator::getInnerIterator — Returns the inner iterator

Description

public CachingIterator::getInnerIterator ( void ) : Iterator
Warning

This function is currently not documented; only its argument list is available.

Returns the iterator sent to the constructor.

Parameters

This function has no parameters.

Return Values

Returns an object implementing the Iterator interface.


Check whether the inner iterator has a valid next element

  • « CachingIterator::getInnerIterator
  • CachingIterator::key »
  • PHP Manual
  • CachingIterator
  • Check whether the inner iterator has a valid next element

CachingIterator::hasNext

(PHP 5, PHP 7)

CachingIterator::hasNext — Check whether the inner iterator has a valid next element

Description

public CachingIterator::hasNext ( void ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.


Return the key for the current element

  • « CachingIterator::hasNext
  • CachingIterator::next »
  • PHP Manual
  • CachingIterator
  • Return the key for the current element

CachingIterator::key

(PHP 5, PHP 7)

CachingIterator::key — Return the key for the current element

Description

public CachingIterator::key ( void ) : scalar
Warning

This function is currently not documented; only its argument list is available.

This method may return a key for the current element.

Parameters

This function has no parameters.


Move the iterator forward

  • « CachingIterator::key
  • CachingIterator::offsetExists »
  • PHP Manual
  • CachingIterator
  • Move the iterator forward

CachingIterator::next

(PHP 5, PHP 7)

CachingIterator::next — Move the iterator forward

Description

public CachingIterator::next ( void ) : void
Warning

This function is currently not documented; only its argument list is available.

Move the iterator forward.

Parameters

This function has no parameters.

Return Values

No value is returned.


The offsetExists purpose

  • « CachingIterator::next
  • CachingIterator::offsetGet »
  • PHP Manual
  • CachingIterator
  • The offsetExists purpose

CachingIterator::offsetExists

(PHP 5 >= 5.2.0, PHP 7)

CachingIterator::offsetExists — The offsetExists purpose

Description

public CachingIterator::offsetExists ( mixed $index ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

index

The index being checked.

Return Values

Returns TRUE if an entry referenced by the offset exists, FALSE otherwise.


The offsetGet purpose

  • « CachingIterator::offsetExists
  • CachingIterator::offsetSet »
  • PHP Manual
  • CachingIterator
  • The offsetGet purpose

CachingIterator::offsetGet

(PHP 5 >= 5.2.0, PHP 7)

CachingIterator::offsetGet — The offsetGet purpose

Description

public CachingIterator::offsetGet ( string $index ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

index

Description...

Return Values

Description...


The offsetSet purpose

  • « CachingIterator::offsetGet
  • CachingIterator::offsetUnset »
  • PHP Manual
  • CachingIterator
  • The offsetSet purpose

CachingIterator::offsetSet

(PHP 5 >= 5.2.0, PHP 7)

CachingIterator::offsetSet — The offsetSet purpose

Description

public CachingIterator::offsetSet ( mixed $index , mixed $newval ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

index

The index of the element to be set.

newval

The new value for the index.

Return Values

No value is returned.


The offsetUnset purpose

  • « CachingIterator::offsetSet
  • CachingIterator::rewind »
  • PHP Manual
  • CachingIterator
  • The offsetUnset purpose

CachingIterator::offsetUnset

(PHP 5 >= 5.2.0, PHP 7)

CachingIterator::offsetUnset — The offsetUnset purpose

Description

public CachingIterator::offsetUnset ( string $index ) : void
Warning

This function is currently not documented; only its argument list is available.

Parameters

index

The index of the element to be unset.

Return Values

No value is returned.


Rewind the iterator

  • « CachingIterator::offsetUnset
  • CachingIterator::setFlags »
  • PHP Manual
  • CachingIterator
  • Rewind the iterator

CachingIterator::rewind

(PHP 5, PHP 7)

CachingIterator::rewind — Rewind the iterator

Description

public CachingIterator::rewind ( void ) : void
Warning

This function is currently not documented; only its argument list is available.

Rewind the iterator.

Parameters

This function has no parameters.

Return Values

No value is returned.


The setFlags purpose

  • « CachingIterator::rewind
  • CachingIterator::__toString »
  • PHP Manual
  • CachingIterator
  • The setFlags purpose

CachingIterator::setFlags

(PHP 5 >= 5.2.0, PHP 7)

CachingIterator::setFlags — The setFlags purpose

Description

public CachingIterator::setFlags ( int $flags ) : void
Warning

This function is currently not documented; only its argument list is available.

Set the flags for the CachingIterator object.

Parameters

flags

Bitmask of the flags to set.

Return Values

No value is returned.


Return the string representation of the current element

  • « CachingIterator::setFlags
  • CachingIterator::valid »
  • PHP Manual
  • CachingIterator
  • Return the string representation of the current element

CachingIterator::__toString

(PHP 5, PHP 7)

CachingIterator::__toString — Return the string representation of the current element

Description

public CachingIterator::__toString ( void ) : void
Warning

This function is currently not documented; only its argument list is available.

Get the string representation of the current element.

Parameters

This function has no parameters.

Return Values

The string representation of the current element.


Check whether the current element is valid

  • « CachingIterator::__toString
  • CallbackFilterIterator »
  • PHP Manual
  • CachingIterator
  • Check whether the current element is valid

CachingIterator::valid

(PHP 5, PHP 7)

CachingIterator::valid — Check whether the current element is valid

Description

public CachingIterator::valid ( void ) : void
Warning

This function is currently not documented; only its argument list is available.

Check whether the current element is valid.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.


The CallbackFilterIterator class

(PHP 5 >= 5.4.0, PHP 7)

Introduction

Class synopsis

CallbackFilterIterator extends FilterIterator implements OuterIterator {
/* Methods */
public __construct ( Iterator $iterator , callable $callback )
public accept ( void ) : bool
/* Inherited methods */
public abstract FilterIterator::accept ( void ) : bool
public FilterIterator::__construct ( Iterator $iterator )
public FilterIterator::current ( void ) : mixed
public FilterIterator::getInnerIterator ( void ) : Iterator
public FilterIterator::key ( void ) : mixed
public FilterIterator::next ( void ) : void
public FilterIterator::rewind ( void ) : void
public FilterIterator::valid ( void ) : bool
}

Examples

The callback should accept up to three arguments: the current item, the current key and the iterator, respectively.

Example #1 Available callback arguments

<?php

/**
 * Callback for CallbackFilterIterator
 *
 * @param $current   Current item's value
 * @param $key       Current item's key
 * @param $iterator  Iterator being filtered
 * @return boolean   TRUE to accept the current item, FALSE otherwise
 */
function my_callback($current, $key, $iterator) {
    // Your filtering code here
}

?>

Any callable may be used; such as a string containing a function name, an array for a method, or an anonymous function.

Example #2 Callback basic examples

<?php

$dir = new FilesystemIterator(__DIR__);

// Filter large files ( > 100MB)
function is_large_file($current) {
    return $current->isFile() && $current->getSize() > 104857600;
}
$large_files = new CallbackFilterIterator($dir, 'is_large_file');

// Filter directories
$files = new CallbackFilterIterator($dir, function ($current, $key, $iterator) {
    return $current->isDir() && ! $iterator->isDot();
});

?>

Table of Contents

  • CallbackFilterIterator::accept — Calls the callback with the current value, the current key and the inner iterator as arguments
  • CallbackFilterIterator::__construct — Create a filtered iterator from another iterator


Calls the callback with the current value, the current key and the inner iterator as arguments

  • « CallbackFilterIterator
  • CallbackFilterIterator::__construct »
  • PHP Manual
  • CallbackFilterIterator
  • Calls the callback with the current value, the current key and the inner iterator as arguments

CallbackFilterIterator::accept

(PHP 5 >= 5.4.0, PHP 7)

CallbackFilterIterator::accept — Calls the callback with the current value, the current key and the inner iterator as arguments

Description

public CallbackFilterIterator::accept ( void ) : bool

This method calls the callback with the current value, current key and the inner iterator.

The callback is expected to return TRUE if the current item is to be accepted, or FALSE otherwise.

Parameters

This function has no parameters.

Return Values

Returns TRUE to accept the current item, or FALSE otherwise.

See Also

  • CallbackFilterIterator Examples
  • CallbackFilterIterator::__construct() - Create a filtered iterator from another iterator


Create a filtered iterator from another iterator

  • « CallbackFilterIterator::accept
  • DirectoryIterator »
  • PHP Manual
  • CallbackFilterIterator
  • Create a filtered iterator from another iterator

CallbackFilterIterator::__construct

(PHP 5 >= 5.4.0, PHP 7)

CallbackFilterIterator::__construct — Create a filtered iterator from another iterator

Description

public CallbackFilterIterator::__construct ( Iterator $iterator , callable $callback )

Creates a filtered iterator using the callback to determine which items are accepted or rejected.

Parameters

iterator

The iterator to be filtered.

callback

The callback, which should return TRUE to accept the current item or FALSE otherwise. See Examples.

May be any valid callable value.

Return Values

No value is returned.

See Also

  • CallbackFilterIterator Examples
  • CallbackFilterIterator::accept() - Calls the callback with the current value, the current key and the inner iterator as arguments


The DirectoryIterator class

(PHP 5, PHP 7)

Introduction

The DirectoryIterator class provides a simple interface for viewing the contents of filesystem directories.

Class synopsis

DirectoryIterator extends SplFileInfo implements SeekableIterator {
/* Methods */
public __construct ( string $path )
public current ( void ) : DirectoryIterator
public getATime ( void ) : int
public getBasename ([ string $suffix ] ) : string
public getCTime ( void ) : int
public getExtension ( void ) : string
public getFilename ( void ) : string
public getGroup ( void ) : int
public getInode ( void ) : int
public getMTime ( void ) : int
public getOwner ( void ) : int
public getPath ( void ) : string
public getPathname ( void ) : string
public getPerms ( void ) : int
public getSize ( void ) : int
public getType ( void ) : string
public isDir ( void ) : bool
public isDot ( void ) : bool
public isExecutable ( void ) : bool
public isFile ( void ) : bool
public isLink ( void ) : bool
public isReadable ( void ) : bool
public isWritable ( void ) : bool
public key ( void ) : string
public next ( void ) : void
public rewind ( void ) : void
public seek ( int $position ) : void
public __toString ( void ) : string
public valid ( void ) : bool
}

Changelog

Version | Description
5.1.2 | DirectoryIterator extends SplFileInfo.

Table of Contents

  • DirectoryIterator::__construct — Constructs a new directory iterator from a path
  • DirectoryIterator::current — Return the current DirectoryIterator item
  • DirectoryIterator::getATime — Get last access time of the current DirectoryIterator item
  • DirectoryIterator::getBasename — Get base name of current DirectoryIterator item
  • DirectoryIterator::getCTime — Get inode change time of the current DirectoryIterator item
  • DirectoryIterator::getExtension — Gets the file extension
  • DirectoryIterator::getFilename — Return file name of current DirectoryIterator item
  • DirectoryIterator::getGroup — Get group for the current DirectoryIterator item
  • DirectoryIterator::getInode — Get inode for the current DirectoryIterator item
  • DirectoryIterator::getMTime — Get last modification time of current DirectoryIterator item
  • DirectoryIterator::getOwner — Get owner of current DirectoryIterator item
  • DirectoryIterator::getPath — Get path of current Iterator item without filename
  • DirectoryIterator::getPathname — Return path and file name of current DirectoryIterator item
  • DirectoryIterator::getPerms — Get the permissions of current DirectoryIterator item
  • DirectoryIterator::getSize — Get size of current DirectoryIterator item
  • DirectoryIterator::getType — Determine the type of the current DirectoryIterator item
  • DirectoryIterator::isDir — Determine if current DirectoryIterator item is a directory
  • DirectoryIterator::isDot — Determine if current DirectoryIterator item is '.' or '..'
  • DirectoryIterator::isExecutable — Determine if current DirectoryIterator item is executable
  • DirectoryIterator::isFile — Determine if current DirectoryIterator item is a regular file
  • DirectoryIterator::isLink — Determine if current DirectoryIterator item is a symbolic link
  • DirectoryIterator::isReadable — Determine if current DirectoryIterator item can be read
  • DirectoryIterator::isWritable — Determine if current DirectoryIterator item can be written to
  • DirectoryIterator::key — Return the key for the current DirectoryIterator item
  • DirectoryIterator::next — Move forward to next DirectoryIterator item
  • DirectoryIterator::rewind — Rewind the DirectoryIterator back to the start
  • DirectoryIterator::seek — Seek to a DirectoryIterator item
  • DirectoryIterator::__toString — Get file name as a string
  • DirectoryIterator::valid — Check whether current DirectoryIterator position is a valid file


Constructs a new directory iterator from a path

  • « DirectoryIterator
  • DirectoryIterator::current »
  • PHP Manual
  • DirectoryIterator
  • Constructs a new directory iterator from a path

DirectoryIterator::__construct

(PHP 5, PHP 7)

DirectoryIterator::__construct — Constructs a new directory iterator from a path

Description

public DirectoryIterator::__construct ( string $path )

Constructs a new directory iterator from a path.

Parameters

path

The path of the directory to traverse.

Errors/Exceptions

Throws an UnexpectedValueException if the path cannot be opened.

Throws a RuntimeException if the path is an empty string.

Changelog

Version | Description
5.3.0 | Throws UnexpectedValueException if the path cannot be opened.
5.1.3 | Throws RuntimeException if the path is an empty string.
5.1.0 | Throws RuntimeException on error. Previously, threw Exception.

Examples

Example #1 A DirectoryIterator::__construct() example

This example will list the contents of the directory containing the script.

<?php
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
    if (!$fileinfo->isDot()) {
        var_dump($fileinfo->getFilename());
    }
}
?>

See Also

  • SplFileInfo
  • Iterator


Return the current DirectoryIterator item

  • « DirectoryIterator::__construct
  • DirectoryIterator::getATime »
  • PHP Manual
  • DirectoryIterator
  • Return the current DirectoryIterator item

DirectoryIterator::current

(PHP 5, PHP 7)

DirectoryIterator::current — Return the current DirectoryIterator item

Description

public DirectoryIterator::current ( void ) : DirectoryIterator

Get the current DirectoryIterator item.

Parameters

This function has no parameters.

Return Values

The current DirectoryIterator item.

Examples

Example #1 A DirectoryIterator::current() example

This example will list the contents of the directory containing the script.

<?php
$iterator = new DirectoryIterator(__DIR__);
while($iterator->valid()) {
    $file = $iterator->current();
    echo $iterator->key() . " => " . $file->getFilename() . "\n";
    $iterator->next();
}
?>

The above example will output something similar to:

0 => .
1 => ..
2 => apple.jpg
3 => banana.jpg
4 => index.php
5 => pear.jpg

See Also

  • DirectoryIterator::key() - Return the key for the current DirectoryIterator item
  • DirectoryIterator::next() - Move forward to next DirectoryIterator item
  • DirectoryIterator::rewind() - Rewind the DirectoryIterator back to the start
  • DirectoryIterator::valid() - Check whether current DirectoryIterator position is a valid file
  • Iterator::current() - Return the current element


Get last access time of the current DirectoryIterator item

  • « DirectoryIterator::current
  • DirectoryIterator::getBasename »
  • PHP Manual
  • DirectoryIterator
  • Get last access time of the current DirectoryIterator item

DirectoryIterator::getATime

(PHP 5, PHP 7)

DirectoryIterator::getATime — Get last access time of the current DirectoryIterator item

Description

public DirectoryIterator::getATime ( void ) : int

Get the last access time of the current DirectoryIterator item.

Parameters

This function has no parameters.

Return Values

Returns the time the file was last accessed, as a Unix timestamp.

Examples

Example #1 A DirectoryIterator::getATime() example

Displays a list of the files in the directory of the script and their last access times.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isFile()) {
        echo $fileinfo->getFilename() . " " . $fileinfo->getATime() . "\n";
    }
}
?>

The above example will output something similar to:

apple.jpg 1240047118
banana.jpg 1240065176
index.php 1240047208
pear.jpg 12240047979

See Also

  • DirectoryIterator::getCTime() - Get inode change time of the current DirectoryIterator item
  • DirectoryIterator::getMTime() - Get last modification time of current DirectoryIterator item
  • fileatime() - Gets last access time of file


Get base name of current DirectoryIterator item

  • « DirectoryIterator::getATime
  • DirectoryIterator::getCTime »
  • PHP Manual
  • DirectoryIterator
  • Get base name of current DirectoryIterator item

DirectoryIterator::getBasename

(PHP 5 >= 5.2.2, PHP 7)

DirectoryIterator::getBasename — Get base name of current DirectoryIterator item

Description

public DirectoryIterator::getBasename ([ string $suffix ] ) : string

Get the base name of the current DirectoryIterator item.

Parameters

suffix

If the base name ends in suffix, this will be cut.

Return Values

The base name of the current DirectoryIterator item.

Examples

Example #1 A DirectoryIterator::getBasename() example

This example will list the full base name and the base name with suffix .jpg removed for the files in the directory containing the script.

<?php
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
    if ($fileinfo->isFile()) {
        echo $fileinfo->getBasename() . "\n";
        echo $fileinfo->getBasename('.jpg') . "\n";
    }
}
?>

The above example will output something similar to:

apple.jpg
apple
banana.jpg
banana
index.php
index.php
pear.jpg
pear

See Also

  • DirectoryIterator::getFilename() - Return file name of current DirectoryIterator item
  • DirectoryIterator::getPath() - Get path of current Iterator item without filename
  • DirectoryIterator::getPathname() - Return path and file name of current DirectoryIterator item
  • basename() - Returns trailing name component of path
  • pathinfo() - Returns information about a file path


Get inode change time of the current DirectoryIterator item

  • « DirectoryIterator::getBasename
  • DirectoryIterator::getExtension »
  • PHP Manual
  • DirectoryIterator
  • Get inode change time of the current DirectoryIterator item

DirectoryIterator::getCTime

(PHP 5, PHP 7)

DirectoryIterator::getCTime — Get inode change time of the current DirectoryIterator item

Description

public DirectoryIterator::getCTime ( void ) : int

Get the inode change time for the current DirectoryIterator item.

Parameters

This function has no parameters.

Return Values

Returns the last change time of the file, as a Unix timestamp.

Examples

Example #1 DirectoryIterator::getCTime() example

This example displays the file name and last change time of the files in the directory containing the script.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isFile()) {
        echo $fileinfo->getFilename() . " changed at " . $fileinfo->getCTime() . "\n";
    }
}
?>

The above example will output something similar to:

apple.jpg changed at 1240398312
banana.jpg changed at 1238605440
index.php changed at 1240398935
pear.jpg changed at 1237423740

See Also

  • DirectoryIterator::getATime() - Get last access time of the current DirectoryIterator item
  • DirectoryIterator::getMTime() - Get last modification time of current DirectoryIterator item
  • filectime() - Gets inode change time of file


Gets the file extension

  • « DirectoryIterator::getCTime
  • DirectoryIterator::getFilename »
  • PHP Manual
  • DirectoryIterator
  • Gets the file extension

DirectoryIterator::getExtension

(PHP 5 >= 5.3.6, PHP 7)

DirectoryIterator::getExtension — Gets the file extension

Description

public DirectoryIterator::getExtension ( void ) : string

Retrieves the file extension.

Parameters

This function has no parameters.

Return Values

Returns a string containing the file extension, or an empty string if the file has no extension.

Examples

Example #1 DirectoryIterator::getExtension() example

<?php

$directory = new DirectoryIterator(__DIR__);
foreach ($directory as $fileinfo) {
    if ($fileinfo->isFile()) {
        echo $fileinfo->getExtension() . "\n";
    }
}

?>

The above example will output something similar to:

php
txt
jpg
gz

Notes

Note:

This method is only available as of PHP 5.3.6. Another way of getting the extension is to use the pathinfo() function.

<?php
$extension = pathinfo($fileinfo->getFilename(), PATHINFO_EXTENSION);
?>

See Also

  • DirectoryIterator::getFilename() - Return file name of current DirectoryIterator item
  • DirectoryIterator::getBasename() - Get base name of current DirectoryIterator item
  • pathinfo() - Returns information about a file path


Return file name of current DirectoryIterator item

  • « DirectoryIterator::getExtension
  • DirectoryIterator::getGroup »
  • PHP Manual
  • DirectoryIterator
  • Return file name of current DirectoryIterator item

DirectoryIterator::getFilename

(PHP 5, PHP 7)

DirectoryIterator::getFilename — Return file name of current DirectoryIterator item

Description

public DirectoryIterator::getFilename ( void ) : string

Get the file name of the current DirectoryIterator item.

Parameters

This function has no parameters.

Return Values

Returns the file name of the current DirectoryIterator item.

Examples

Example #1 A DirectoryIterator::getFilename() example

This example will list the contents of the directory containing the script.

<?php
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
    echo $fileinfo->getFilename() . "\n";
}
?>

The above example will output something similar to:

.
..
apple.jpg
banana.jpg
index.php
pear.jpg

See Also

  • DirectoryIterator::getBasename() - Get base name of current DirectoryIterator item
  • DirectoryIterator::getPath() - Get path of current Iterator item without filename
  • DirectoryIterator::getPathname() - Return path and file name of current DirectoryIterator item
  • pathinfo() - Returns information about a file path


Get group for the current DirectoryIterator item

  • « DirectoryIterator::getFilename
  • DirectoryIterator::getInode »
  • PHP Manual
  • DirectoryIterator
  • Get group for the current DirectoryIterator item

DirectoryIterator::getGroup

(PHP 5, PHP 7)

DirectoryIterator::getGroup — Get group for the current DirectoryIterator item

Description

public DirectoryIterator::getGroup ( void ) : int

Get the group id of the file.

Parameters

This function has no parameters.

Return Values

Returns the group id of the current DirectoryIterator item in numerical format.

Examples

Example #1 DirectoryIterator::getGroup() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
$groupid  = $iterator->getGroup();
echo 'Directory belongs to group id ' . $groupid . "\n";
print_r(posix_getgrgid($groupid));
?>

The above example will output something similar to:

Directory belongs to group id 42
Array
(
    [name]    => toons
    [passwd]  => x
    [members] => Array
        (
            [0] => tom
            [1] => jerry
        )
    [gid]     => 42
)

See Also

  • DirectoryIterator::getiNode() - Get inode for the current DirectoryIterator item
  • DirectoryIterator::getOwner() - Get owner of current DirectoryIterator item
  • DirectoryIterator::getPerms() - Get the permissions of current DirectoryIterator item
  • filegroup() - Gets file group
  • posix_getgrgid() - Return info about a group by group id


Get inode for the current DirectoryIterator item

  • « DirectoryIterator::getGroup
  • DirectoryIterator::getMTime »
  • PHP Manual
  • DirectoryIterator
  • Get inode for the current DirectoryIterator item

DirectoryIterator::getInode

(PHP 5, PHP 7)

DirectoryIterator::getInode — Get inode for the current DirectoryIterator item

Description

public DirectoryIterator::getInode ( void ) : int

Get the inode number for the current DirectoryIterator item.

Parameters

This function has no parameters.

Return Values

Returns the inode number for the file.

Examples

Example #1 DirectoryIterator::getInode() example

This example displays the inode number for the directory containing the script.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
echo $iterator->getInode();
?>

See Also

  • DirectoryIterator::getGroup() - Get group for the current DirectoryIterator item
  • DirectoryIterator::getOwner() - Get owner of current DirectoryIterator item
  • DirectoryIterator::getPerms() - Get the permissions of current DirectoryIterator item
  • fileinode() - Gets file inode


Get last modification time of current DirectoryIterator item

  • « DirectoryIterator::getInode
  • DirectoryIterator::getOwner »
  • PHP Manual
  • DirectoryIterator
  • Get last modification time of current DirectoryIterator item

DirectoryIterator::getMTime

(PHP 5, PHP 7)

DirectoryIterator::getMTime — Get last modification time of current DirectoryIterator item

Description

public DirectoryIterator::getMTime ( void ) : int

Get the last modification time of the current DirectoryIterator item, as a Unix timestamp.

Parameters

This function has no parameters.

Return Values

The last modification time of the file, as a Unix timestamp.

Examples

Example #1 A DirectoryIterator::getMTime() example

Displays a list of the files in the directory of the script and their last modified times.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isFile()) {
        echo $fileinfo->getFilename() . " " . $fileinfo->getMTime() . "\n";
    }
}
?>

The above example will output something similar to:

apple.jpg 1240047118
banana.jpg 1240065176
index.php 1240047208
pear.jpg 12240047979

See Also

  • DirectoryIterator::getATime() - Get last access time of the current DirectoryIterator item
  • DirectoryIterator::getCTime() - Get inode change time of the current DirectoryIterator item
  • filemtime() - Gets file modification time


Get owner of current DirectoryIterator item

  • « DirectoryIterator::getMTime
  • DirectoryIterator::getPath »
  • PHP Manual
  • DirectoryIterator
  • Get owner of current DirectoryIterator item

DirectoryIterator::getOwner

(PHP 5, PHP 7)

DirectoryIterator::getOwner — Get owner of current DirectoryIterator item

Description

public DirectoryIterator::getOwner ( void ) : int

Get the owner of the current DirectoryIterator item, in numerical format.

Parameters

This function has no parameters.

Return Values

The file owner of the file, in numerical format.

Examples

Example #1 DirectoryIterator::getOwner() example

This example displays the owner of the directory which contains the script.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
print_r(posix_getpwuid($iterator->getOwner()));
?>

The above example will output something similar to:

Array
(
    [name] => tom
    [passwd] => x
    [uid] => 501
    [gid] => 42
    [gecos] => Tom Cat
    [dir] => /home/tom
    [shell] => /bin/bash
)

See Also

  • DirectoryIterator::getGroup() - Get group for the current DirectoryIterator item
  • DirectoryIterator::getiNode() - Get inode for the current DirectoryIterator item
  • DirectoryIterator::getPerms() - Get the permissions of current DirectoryIterator item
  • posix_getpwuid() - Return info about a user by user id


Get path of current Iterator item without filename

  • « DirectoryIterator::getOwner
  • DirectoryIterator::getPathname »
  • PHP Manual
  • DirectoryIterator
  • Get path of current Iterator item without filename

DirectoryIterator::getPath

(PHP 5, PHP 7)

DirectoryIterator::getPath — Get path of current Iterator item without filename

Description

public DirectoryIterator::getPath ( void ) : string

Get the path to the current DirectoryIterator item.

Parameters

This function has no parameters.

Return Values

Returns the path to the file, omitting the file name and any trailing slash.

Examples

Example #1 DirectoryIterator::getPath() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
echo $iterator->getPath();
?>

The above example will output something similar to:

/home/examples/public_html

See Also

  • DirectoryIterator::getBasename() - Get base name of current DirectoryIterator item
  • DirectoryIterator::getFilename() - Return file name of current DirectoryIterator item
  • DirectoryIterator::getPathname() - Return path and file name of current DirectoryIterator item
  • pathinfo() - Returns information about a file path


Return path and file name of current DirectoryIterator item

  • « DirectoryIterator::getPath
  • DirectoryIterator::getPerms »
  • PHP Manual
  • DirectoryIterator
  • Return path and file name of current DirectoryIterator item

DirectoryIterator::getPathname

(PHP 5, PHP 7)

DirectoryIterator::getPathname — Return path and file name of current DirectoryIterator item

Description

public DirectoryIterator::getPathname ( void ) : string

Get the path and file name of the current file.

Parameters

This function has no parameters.

Return Values

Returns the path and file name of current file. Directories do not have a trailing slash.

Examples

Example #1 DirectoryIterator::getPathname() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    echo $fileinfo->getPathname() . "\n";
}
?>

The above example will output something similar to:

/home/examples/.
/home/examples/..
/home/examples/apple.jpg
/home/examples/banana.jpg
/home/examples/getpathname.php
/home/examples/pear.jpg

See Also

  • DirectoryIterator::getBasename() - Get base name of current DirectoryIterator item
  • DirectoryIterator::getFilename() - Return file name of current DirectoryIterator item
  • DirectoryIterator::getPath() - Get path of current Iterator item without filename
  • pathinfo() - Returns information about a file path


Get the permissions of current DirectoryIterator item

  • « DirectoryIterator::getPathname
  • DirectoryIterator::getSize »
  • PHP Manual
  • DirectoryIterator
  • Get the permissions of current DirectoryIterator item

DirectoryIterator::getPerms

(PHP 5, PHP 7)

DirectoryIterator::getPerms — Get the permissions of current DirectoryIterator item

Description

public DirectoryIterator::getPerms ( void ) : int

Get the permissions of the current DirectoryIterator item.

Parameters

This function has no parameters.

Return Values

Returns the permissions of the file, as a decimal integer.

Examples

Example #1 DirectoryIterator::getPerms() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if (!$fileinfo->isDot()) {
        $octal_perms = substr(sprintf('%o', $fileinfo->getPerms()), -4);
        echo $fileinfo->getFilename() . " " . $octal_perms . "\n";
    }
}
?>

The above example will output something similar to:

apple.jpg 0644
banana.jpg 0644
index.php 0744
pear.jpg 0644

See Also

  • DirectoryIterator::isExecutable() - Determine if current DirectoryIterator item is executable
  • DirectoryIterator::isReadable() - Determine if current DirectoryIterator item can be read
  • DirectoryIterator::isWritable() - Determine if current DirectoryIterator item can be written to


Get size of current DirectoryIterator item

  • « DirectoryIterator::getPerms
  • DirectoryIterator::getType »
  • PHP Manual
  • DirectoryIterator
  • Get size of current DirectoryIterator item

DirectoryIterator::getSize

(PHP 5, PHP 7)

DirectoryIterator::getSize — Get size of current DirectoryIterator item

Description

public DirectoryIterator::getSize ( void ) : int

Get the file size for the current DirectoryIterator item.

Parameters

This function has no parameters.

Return Values

Returns the size of the file, in bytes.

Examples

Example #1 DirectoryIterator::getSize() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isFile()) {
        echo $fileinfo->getFilename() . " " . $fileinfo->getSize() . "\n";
    }
}
?>

The above example will output something similar to:

apple.jpg 15385
banana.jpg 15190
example.php 170
pear.jpg 34406

See Also

  • filesize() - Gets file size


Determine the type of the current DirectoryIterator item

  • « DirectoryIterator::getSize
  • DirectoryIterator::isDir »
  • PHP Manual
  • DirectoryIterator
  • Determine the type of the current DirectoryIterator item

DirectoryIterator::getType

(PHP 5, PHP 7)

DirectoryIterator::getType — Determine the type of the current DirectoryIterator item

Description

public DirectoryIterator::getType ( void ) : string

Determines which file type the current DirectoryIterator item belongs to. One of file, link, or dir.

Parameters

This function has no parameters.

Return Values

Returns a string representing the type of the file. May be one of file, link, or dir.

Examples

Example #1 DirectoryIterator::getType() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    echo $fileinfo->getFilename() . " " . $fileinfo->getType() . "\n";
}
?>

The above example will output something similar to:

. dir
.. dir
apple.jpg file
banana.jpg file
example.php file
pear.jpg file

See Also

  • DirectoryIterator::isDir() - Determine if current DirectoryIterator item is a directory
  • DirectoryIterator::isDot() - Determine if current DirectoryIterator item is '.' or '..'
  • DirectoryIterator::isFile() - Determine if current DirectoryIterator item is a regular file
  • DirectoryIterator::isLink() - Determine if current DirectoryIterator item is a symbolic link


Determine if current DirectoryIterator item is a directory

  • « DirectoryIterator::getType
  • DirectoryIterator::isDot »
  • PHP Manual
  • DirectoryIterator
  • Determine if current DirectoryIterator item is a directory

DirectoryIterator::isDir

(PHP 5, PHP 7)

DirectoryIterator::isDir — Determine if current DirectoryIterator item is a directory

Description

public DirectoryIterator::isDir ( void ) : bool

Determines if the current DirectoryIterator item is a directory.

Parameters

This function has no parameters.

Return Values

Returns TRUE if it is a directory, otherwise FALSE

Examples

Example #1 DirectoryIterator::isDir() example

This example lists the directories within the directory of the current script.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isDir()) {
        echo $fileinfo->getFilename() . "\n";
    }
}
?>

The above example will output something similar to:

.
..
apples
bananas
pears

See Also

  • DirectoryIterator::getType() - Determine the type of the current DirectoryIterator item
  • DirectoryIterator::isDot() - Determine if current DirectoryIterator item is '.' or '..'
  • DirectoryIterator::isFile() - Determine if current DirectoryIterator item is a regular file
  • DirectoryIterator::isLink() - Determine if current DirectoryIterator item is a symbolic link


Determine if current DirectoryIterator item is '.' or '..'

  • « DirectoryIterator::isDir
  • DirectoryIterator::isExecutable »
  • PHP Manual
  • DirectoryIterator
  • Determine if current DirectoryIterator item is '.' or '..'

DirectoryIterator::isDot

(PHP 5, PHP 7)

DirectoryIterator::isDot — Determine if current DirectoryIterator item is '.' or '..'

Description

public DirectoryIterator::isDot ( void ) : bool

Determines if the current DirectoryIterator item is a directory and either . or ..

Parameters

This function has no parameters.

Return Values

TRUE if the entry is . or .., otherwise FALSE

Examples

Example #1 A DirectoryIterator::isDot() example

This example will list all files, omitting the . and .. entries.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if (!$fileinfo->isDot()) {
        echo $fileinfo->getFilename() . "\n";
    }
}
?>

The above example will output something similar to:

apple.jpg
banana.jpg
example.php
pears.jpg

See Also

  • DirectoryIterator::getType() - Determine the type of the current DirectoryIterator item
  • DirectoryIterator::isDir() - Determine if current DirectoryIterator item is a directory
  • DirectoryIterator::isFile() - Determine if current DirectoryIterator item is a regular file
  • DirectoryIterator::isLink() - Determine if current DirectoryIterator item is a symbolic link


Determine if current DirectoryIterator item is executable

  • « DirectoryIterator::isDot
  • DirectoryIterator::isFile »
  • PHP Manual
  • DirectoryIterator
  • Determine if current DirectoryIterator item is executable

DirectoryIterator::isExecutable

(PHP 5, PHP 7)

DirectoryIterator::isExecutable — Determine if current DirectoryIterator item is executable

Description

public DirectoryIterator::isExecutable ( void ) : bool

Determines if the current DirectoryIterator item is executable.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the entry is executable, otherwise FALSE

Examples

Example #1 DirectoryIterator::isExecutable() example

This example lists files in the directory containing the script which are executable.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isExecutable()) {
        echo $fileinfo->getFilename() . "\n";
    }
}
?>

The above example will output something similar to:

example.php
myscript.sh

See Also

  • DirectoryIterator::isReadable() - Determine if current DirectoryIterator item can be read
  • DirectoryIterator::isWritable() - Determine if current DirectoryIterator item can be written to
  • DirectoryIterator::getPerms() - Get the permissions of current DirectoryIterator item


Determine if current DirectoryIterator item is a regular file

  • « DirectoryIterator::isExecutable
  • DirectoryIterator::isLink »
  • PHP Manual
  • DirectoryIterator
  • Determine if current DirectoryIterator item is a regular file

DirectoryIterator::isFile

(PHP 5, PHP 7)

DirectoryIterator::isFile — Determine if current DirectoryIterator item is a regular file

Description

public DirectoryIterator::isFile ( void ) : bool

Determines if the current DirectoryIterator item is a regular file.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the file exists and is a regular file (not a link or dir), otherwise FALSE

Examples

Example #1 DirectoryIterator::isFile() example

This example will list all regular files in the directory containing the script.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isFile()) {
        echo $fileinfo->getFilename() . "\n";
    }
}
?>

The above example will output something similar to:

apple.jpg
banana.jpg
example.php
pears.jpg

See Also

  • DirectoryIterator::getType() - Determine the type of the current DirectoryIterator item
  • DirectoryIterator::isDir() - Determine if current DirectoryIterator item is a directory
  • DirectoryIterator::isDot() - Determine if current DirectoryIterator item is '.' or '..'
  • DirectoryIterator::isLink() - Determine if current DirectoryIterator item is a symbolic link


Determine if current DirectoryIterator item is a symbolic link

  • « DirectoryIterator::isFile
  • DirectoryIterator::isReadable »
  • PHP Manual
  • DirectoryIterator
  • Determine if current DirectoryIterator item is a symbolic link

DirectoryIterator::isLink

(PHP 5, PHP 7)

DirectoryIterator::isLink — Determine if current DirectoryIterator item is a symbolic link

Description

public DirectoryIterator::isLink ( void ) : bool

Determines if the current DirectoryIterator item is a symbolic link.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the item is a symbolic link, otherwise FALSE

Examples

Example #1 A DirectoryIterator::isLink() example

This example contains a recursive function for removing a directory tree.

<?php
/**
 * This function will recursively delete all files in the given path, without
 * following symlinks.
 *
 * @param string $path Path to the directory to remove.
 */
function removeDir($path) {
    $dir = new DirectoryIterator($path);
    foreach ($dir as $fileinfo) {
        if ($fileinfo->isFile() || $fileinfo->isLink()) {
            unlink($fileinfo->getPathName());
        } elseif (!$fileinfo->isDot() && $fileinfo->isDir()) {
            removeDir($fileinfo->getPathName());
        }
    }
    rmdir($path);
}

removeDir('foo');
?>

See Also

  • DirectoryIterator::getType() - Determine the type of the current DirectoryIterator item
  • DirectoryIterator::isDir() - Determine if current DirectoryIterator item is a directory
  • DirectoryIterator::isDot() - Determine if current DirectoryIterator item is '.' or '..'
  • DirectoryIterator::isFile() - Determine if current DirectoryIterator item is a regular file


Determine if current DirectoryIterator item can be read

  • « DirectoryIterator::isLink
  • DirectoryIterator::isWritable »
  • PHP Manual
  • DirectoryIterator
  • Determine if current DirectoryIterator item can be read

DirectoryIterator::isReadable

(PHP 5, PHP 7)

DirectoryIterator::isReadable — Determine if current DirectoryIterator item can be read

Description

public DirectoryIterator::isReadable ( void ) : bool

Determines if the current DirectoryIterator item is readable.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the file is readable, otherwise FALSE

Examples

Example #1 DirectoryIterator::isReadable() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isReadable()) {
        echo $fileinfo->getFilename() . "\n";
    }
}
?>

The above example will output something similar to:

apple.jpg
banana.jpg
example.php
pears.jpg

See Also

  • DirectoryIterator::isExecutable() - Determine if current DirectoryIterator item is executable
  • DirectoryIterator::isWritable() - Determine if current DirectoryIterator item can be written to
  • DirectoryIterator::getPerms() - Get the permissions of current DirectoryIterator item


Determine if current DirectoryIterator item can be written to

  • « DirectoryIterator::isReadable
  • DirectoryIterator::key »
  • PHP Manual
  • DirectoryIterator
  • Determine if current DirectoryIterator item can be written to

DirectoryIterator::isWritable

(PHP 5, PHP 7)

DirectoryIterator::isWritable — Determine if current DirectoryIterator item can be written to

Description

public DirectoryIterator::isWritable ( void ) : bool

Determines if the current DirectoryIterator item is writable.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the file/directory is writable, otherwise FALSE

Examples

Example #1 DirectoryIterator::isWritable() example

This example lists the files and directories which can be opened for writing in the directory containing the script.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isWritable()) {
        echo $fileinfo->getFilename() . "\n";
    }
}
?>

The above example will output something similar to:

apples.txt
bananas.html
pears

See Also

  • DirectoryIterator::getPerms() - Get the permissions of current DirectoryIterator item
  • DirectoryIterator::isExecutable() - Determine if current DirectoryIterator item is executable
  • DirectoryIterator::isReadable() - Determine if current DirectoryIterator item can be read


Return the key for the current DirectoryIterator item

  • « DirectoryIterator::isWritable
  • DirectoryIterator::next »
  • PHP Manual
  • DirectoryIterator
  • Return the key for the current DirectoryIterator item

DirectoryIterator::key

(PHP 5, PHP 7)

DirectoryIterator::key — Return the key for the current DirectoryIterator item

Description

public DirectoryIterator::key ( void ) : string

Get the key for the current DirectoryIterator item.

Parameters

This function has no parameters.

Return Values

The key for the current DirectoryIterator item.

Examples

Example #1 A DirectoryIterator::key() example

<?php
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
    if (!$fileinfo->isDot()) {
        echo $fileinfo->key() . " => " . $fileinfo->getFilename() . "\n";
    }
}
?>

The above example will output something similar to:

0 => apple.jpg
1 => banana.jpg
2 => index.php
3 => pear.jpg

See Also

  • DirectoryIterator::current() - Return the current DirectoryIterator item
  • DirectoryIterator::next() - Move forward to next DirectoryIterator item
  • DirectoryIterator::rewind() - Rewind the DirectoryIterator back to the start
  • DirectoryIterator::valid() - Check whether current DirectoryIterator position is a valid file
  • Iterator::key() - Return the key of the current element


Move forward to next DirectoryIterator item

  • « DirectoryIterator::key
  • DirectoryIterator::rewind »
  • PHP Manual
  • DirectoryIterator
  • Move forward to next DirectoryIterator item

DirectoryIterator::next

(PHP 5, PHP 7)

DirectoryIterator::next — Move forward to next DirectoryIterator item

Description

public DirectoryIterator::next ( void ) : void

Move forward to the next DirectoryIterator item.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 DirectoryIterator::next() example

List the contents of a directory using a while loop.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
while($iterator->valid()) {
    echo $iterator->getFilename() . "\n";
    $iterator->next();
}
?>

The above example will output something similar to:

.
..
apple.jpg
banana.jpg
index.php
pear.jpg

See Also

  • DirectoryIterator::current() - Return the current DirectoryIterator item
  • DirectoryIterator::key() - Return the key for the current DirectoryIterator item
  • DirectoryIterator::rewind() - Rewind the DirectoryIterator back to the start
  • DirectoryIterator::valid() - Check whether current DirectoryIterator position is a valid file
  • Iterator::next() - Move forward to next element


Rewind the DirectoryIterator back to the start

  • « DirectoryIterator::next
  • DirectoryIterator::seek »
  • PHP Manual
  • DirectoryIterator
  • Rewind the DirectoryIterator back to the start

DirectoryIterator::rewind

(PHP 5, PHP 7)

DirectoryIterator::rewind — Rewind the DirectoryIterator back to the start

Description

public DirectoryIterator::rewind ( void ) : void

Rewind the DirectoryIterator back to the start.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 DirectoryIterator::rewind() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));

$iterator->next();
echo $iterator->key(); //1

$iterator->rewind(); //rewinding to the beginning
echo $iterator->key(); //0
?>

See Also

  • DirectoryIterator::current() - Return the current DirectoryIterator item
  • DirectoryIterator::key() - Return the key for the current DirectoryIterator item
  • DirectoryIterator::next() - Move forward to next DirectoryIterator item
  • DirectoryIterator::valid() - Check whether current DirectoryIterator position is a valid file
  • Iterator::rewind() - Rewind the Iterator to the first element


Seek to a DirectoryIterator item

  • « DirectoryIterator::rewind
  • DirectoryIterator::__toString »
  • PHP Manual
  • DirectoryIterator
  • Seek to a DirectoryIterator item

DirectoryIterator::seek

(PHP 5 >= 5.3.0, PHP 7)

DirectoryIterator::seek — Seek to a DirectoryIterator item

Description

public DirectoryIterator::seek ( int $position ) : void

Seek to a given position in the DirectoryIterator.

Parameters

position

The zero-based numeric position to seek to.

Return Values

No value is returned.

Examples

Example #1 DirectoryIterator::seek() example

Seek to the fourth item in the directory containing the script. The first two are usually . and ..

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
$iterator->seek(3);
if ($iterator->valid()) {
    echo $iterator->getFilename();
} else {
    echo 'No file at position 3';
}
?>

See Also

  • DirectoryIterator::rewind() - Rewind the DirectoryIterator back to the start
  • DirectoryIterator::next() - Move forward to next DirectoryIterator item
  • SeekableIterator::seek() - Seeks to a position


Get file name as a string

  • « DirectoryIterator::seek
  • DirectoryIterator::valid »
  • PHP Manual
  • DirectoryIterator
  • Get file name as a string

DirectoryIterator::__toString

(PHP 5, PHP 7)

DirectoryIterator::__toString — Get file name as a string

Description

public DirectoryIterator::__toString ( void ) : string

Get the file name of the current DirectoryIterator item.

Parameters

This function has no parameters.

Return Values

Returns the file name of the current DirectoryIterator item.

Examples

Example #1 A DirectoryIterator::__toString() example

This example will list the contents of the directory containing the script.

<?php
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
    echo $fileinfo;
}
?>

The above example will output something similar to:

.
..
apple.jpg
banana.jpg
index.php
pear.jpg

See Also

  • DirectoryIterator::getFilename() - Return file name of current DirectoryIterator item
  • The __toString() magic method


Check whether current DirectoryIterator position is a valid file

  • « DirectoryIterator::__toString
  • EmptyIterator »
  • PHP Manual
  • DirectoryIterator
  • Check whether current DirectoryIterator position is a valid file

DirectoryIterator::valid

(PHP 5, PHP 7)

DirectoryIterator::valid — Check whether current DirectoryIterator position is a valid file

Description

public DirectoryIterator::valid ( void ) : bool

Check whether current DirectoryIterator position is a valid file.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the position is valid, otherwise FALSE

Examples

Example #1 A DirectoryIterator::valid() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));

// Loop to end of iterator
while($iterator->valid()) {
    $iterator->next();
}

$iterator->valid(); // FALSE
$iterator->rewind();
$iterator->valid(); // TRUE

?>

See Also

  • DirectoryIterator::current() - Return the current DirectoryIterator item
  • DirectoryIterator::key() - Return the key for the current DirectoryIterator item
  • DirectoryIterator::next() - Move forward to next DirectoryIterator item
  • DirectoryIterator::rewind() - Rewind the DirectoryIterator back to the start
  • Iterator::valid() - Checks if current position is valid


The EmptyIterator class

(PHP 5 >= 5.1.0, PHP 7)

Introduction

The EmptyIterator class for an empty iterator.

Class synopsis

EmptyIterator implements Iterator {
/* Methods */
public current ( void ) : mixed
public key ( void ) : scalar
public next ( void ) : void
public rewind ( void ) : void
public valid ( void ) : bool
}

Table of Contents

  • EmptyIterator::current — The current() method
  • EmptyIterator::key — The key() method
  • EmptyIterator::next — The next() method
  • EmptyIterator::rewind — The rewind() method
  • EmptyIterator::valid — The valid() method


The current() method

  • « EmptyIterator
  • EmptyIterator::key »
  • PHP Manual
  • EmptyIterator
  • The current() method

EmptyIterator::current

(PHP 5 >= 5.1.0, PHP 7)

EmptyIterator::current — The current() method

Description

public EmptyIterator::current ( void ) : mixed

This function must not be called. It throws an exception upon access.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Errors/Exceptions

Throws an Exception if called.

Return Values

No value is returned.


The key() method

  • « EmptyIterator::current
  • EmptyIterator::next »
  • PHP Manual
  • EmptyIterator
  • The key() method

EmptyIterator::key

(PHP 5 >= 5.1.0, PHP 7)

EmptyIterator::key — The key() method

Description

public EmptyIterator::key ( void ) : scalar

This function must not be called. It throws an exception upon access.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Errors/Exceptions

Throws an Exception if called.

Return Values

No value is returned.


The next() method

  • « EmptyIterator::key
  • EmptyIterator::rewind »
  • PHP Manual
  • EmptyIterator
  • The next() method

EmptyIterator::next

(PHP 5 >= 5.1.0, PHP 7)

EmptyIterator::next — The next() method

Description

public EmptyIterator::next ( void ) : void

No operation, nothing to do.

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.


The rewind() method

  • « EmptyIterator::next
  • EmptyIterator::valid »
  • PHP Manual
  • EmptyIterator
  • The rewind() method

EmptyIterator::rewind

(PHP 5 >= 5.1.0, PHP 7)

EmptyIterator::rewind — The rewind() method

Description

public EmptyIterator::rewind ( void ) : void

No operation, nothing to do.

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.


The valid() method

  • « EmptyIterator::rewind
  • FilesystemIterator »
  • PHP Manual
  • EmptyIterator
  • The valid() method

EmptyIterator::valid

(PHP 5 >= 5.1.0, PHP 7)

EmptyIterator::valid — The valid() method

Description

public EmptyIterator::valid ( void ) : bool

The EmptyIterator valid() method.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

FALSE


The FilesystemIterator class

(PHP 5 >= 5.3.0, PHP 7)

Introduction

The Filesystem iterator

Class synopsis

FilesystemIterator extends DirectoryIterator implements SeekableIterator {
/* Constants */
const integer CURRENT_AS_PATHNAME = 32 ;
const integer CURRENT_AS_FILEINFO = 0 ;
const integer CURRENT_AS_SELF = 16 ;
const integer CURRENT_MODE_MASK = 240 ;
const integer KEY_AS_PATHNAME = 0 ;
const integer KEY_AS_FILENAME = 256 ;
const integer FOLLOW_SYMLINKS = 512 ;
const integer KEY_MODE_MASK = 3840 ;
const integer NEW_CURRENT_AND_KEY = 256 ;
const integer SKIP_DOTS = 4096 ;
const integer UNIX_PATHS = 8192 ;
/* Methods */
public __construct ( string $path [, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS ] )
public current ( void ) : mixed
public getFlags ( void ) : int
public key ( void ) : string
public next ( void ) : void
public rewind ( void ) : void
public setFlags ([ int $flags ] ) : void
/* Inherited methods */
public DirectoryIterator::current ( void ) : DirectoryIterator
public DirectoryIterator::getATime ( void ) : int
public DirectoryIterator::getBasename ([ string $suffix ] ) : string
public DirectoryIterator::getCTime ( void ) : int
public DirectoryIterator::getExtension ( void ) : string
public DirectoryIterator::getFilename ( void ) : string
public DirectoryIterator::getGroup ( void ) : int
public DirectoryIterator::getInode ( void ) : int
public DirectoryIterator::getMTime ( void ) : int
public DirectoryIterator::getOwner ( void ) : int
public DirectoryIterator::getPath ( void ) : string
public DirectoryIterator::getPathname ( void ) : string
public DirectoryIterator::getPerms ( void ) : int
public DirectoryIterator::getSize ( void ) : int
public DirectoryIterator::getType ( void ) : string
public DirectoryIterator::isDir ( void ) : bool
public DirectoryIterator::isDot ( void ) : bool
public DirectoryIterator::isExecutable ( void ) : bool
public DirectoryIterator::isFile ( void ) : bool
public DirectoryIterator::isLink ( void ) : bool
public DirectoryIterator::isReadable ( void ) : bool
public DirectoryIterator::isWritable ( void ) : bool
public DirectoryIterator::key ( void ) : string
public DirectoryIterator::next ( void ) : void
public DirectoryIterator::rewind ( void ) : void
public DirectoryIterator::seek ( int $position ) : void
public DirectoryIterator::__toString ( void ) : string
public DirectoryIterator::valid ( void ) : bool
}

Predefined Constants

FilesystemIterator::CURRENT_AS_PATHNAME

Makes FilesystemIterator::current() return the pathname.

FilesystemIterator::CURRENT_AS_FILEINFO

Makes FilesystemIterator::current() return an SplFileInfo instance.

FilesystemIterator::CURRENT_AS_SELF

Makes FilesystemIterator::current() return $this (the FilesystemIterator).

FilesystemIterator::CURRENT_MODE_MASK

Masks FilesystemIterator::current()

FilesystemIterator::KEY_AS_PATHNAME

Makes FilesystemIterator::key() return the pathname.

FilesystemIterator::KEY_AS_FILENAME

Makes FilesystemIterator::key() return the filename.

FilesystemIterator::FOLLOW_SYMLINKS

Makes RecursiveDirectoryIterator::hasChildren() follow symlinks.

FilesystemIterator::KEY_MODE_MASK

Masks FilesystemIterator::key()

FilesystemIterator::NEW_CURRENT_AND_KEY

Same as FilesystemIterator::KEY_AS_FILENAME | FilesystemIterator::CURRENT_AS_FILEINFO.

FilesystemIterator::SKIP_DOTS

Skips dot files (. and ..).

FilesystemIterator::UNIX_PATHS

Makes paths use Unix-style forward slash irrespective of system default. Note that the path that is passed to the constructor is not modified.

Changelog

Version | Description
5.3.1 | Added FilesystemIterator::FOLLOW_SYMLINKS

Table of Contents

  • FilesystemIterator::__construct — Constructs a new filesystem iterator
  • FilesystemIterator::current — The current file
  • FilesystemIterator::getFlags — Get the handling flags
  • FilesystemIterator::key — Retrieve the key for the current file
  • FilesystemIterator::next — Move to the next file
  • FilesystemIterator::rewind — Rewinds back to the beginning
  • FilesystemIterator::setFlags — Sets handling flags


Constructs a new filesystem iterator

  • « FilesystemIterator
  • FilesystemIterator::current »
  • PHP Manual
  • FilesystemIterator
  • Constructs a new filesystem iterator

FilesystemIterator::__construct

(PHP 5 >= 5.3.0, PHP 7)

FilesystemIterator::__construct — Constructs a new filesystem iterator

Description

public FilesystemIterator::__construct ( string $path [, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS ] )

Constructs a new filesystem iterator from the path.

Parameters

path

The path of the filesystem item to be iterated over.

flags

Flags may be provided which will affect the behavior of some methods. A list of the flags can found under FilesystemIterator predefined constants. They can also be set later with FilesystemIterator::setFlags()

Return Values

No value is returned.

Errors/Exceptions

Throws an UnexpectedValueException if the path cannot be found.

Examples

Example #1 FilesystemIterator::__construct() example

<?php
$it = new FilesystemIterator(dirname(__FILE__));
foreach ($it as $fileinfo) {
    echo $fileinfo->getFilename() . "\n";
}
?>

The above example will output:

apples.jpg
banana.jpg
example.php

See Also

  • FilesystemIterator::setFlags() - Sets handling flags
  • DirectoryIterator::__construct() - Constructs a new directory iterator from a path


The current file

  • « FilesystemIterator::__construct
  • FilesystemIterator::getFlags »
  • PHP Manual
  • FilesystemIterator
  • The current file

FilesystemIterator::current

(PHP 5 >= 5.3.0, PHP 7)

FilesystemIterator::current — The current file

Description

public FilesystemIterator::current ( void ) : mixed

Get file information of the current element.

Parameters

This function has no parameters.

Return Values

The filename, file information, or $this depending on the set flags. See the FilesystemIterator constants.

Examples

Example #1 FilesystemIterator::current() example

This example will list the contents of the directory containing the script.

<?php
$iterator = new FilesystemIterator(__DIR__, FilesystemIterator::CURRENT_AS_PATHNAME);
foreach ($iterator as $fileinfo) {
    echo $iterator->current() . "\n";
}
?>

The above example will output something similar to:

/www/examples/apple.jpg
/www/examples/banana.jpg
/www/examples/example.php

See Also

  • FilesystemIterator constants
  • DirectoryIterator::current() - Return the current DirectoryIterator item
  • DirectoryIterator::getFileName() - Return file name of current DirectoryIterator item


Get the handling flags

  • « FilesystemIterator::current
  • FilesystemIterator::key »
  • PHP Manual
  • FilesystemIterator
  • Get the handling flags

FilesystemIterator::getFlags

(PHP 5 >= 5.3.0, PHP 7)

FilesystemIterator::getFlags — Get the handling flags

Description

public FilesystemIterator::getFlags ( void ) : int

Gets the handling flags, as set in FilesystemIterator::__construct() or FilesystemIterator::setFlags().

Parameters

This function has no parameters.

Return Values

The integer value of the set flags.

See Also

  • FilesystemIterator::__construct() - Constructs a new filesystem iterator
  • FilesystemIterator::setFlags() - Sets handling flags


Retrieve the key for the current file

  • « FilesystemIterator::getFlags
  • FilesystemIterator::next »
  • PHP Manual
  • FilesystemIterator
  • Retrieve the key for the current file

FilesystemIterator::key

(PHP 5 >= 5.3.0, PHP 7)

FilesystemIterator::key — Retrieve the key for the current file

Description

public FilesystemIterator::key ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns the pathname or filename depending on the set flags. See the FilesystemIterator constants.

Examples

Example #1 FilesystemIterator::key() example

This example will list the contents of the directory containing the script.

<?php
$iterator = new FilesystemIterator(dirname(__FILE__), FilesystemIterator::KEY_AS_FILENAME);
foreach ($iterator as $fileinfo) {
    echo $iterator->key() . "\n";
}
?>

The above example will output something similar to:

apple.jpg
banana.jpg
example.php

See Also

  • FilesystemIterator constants
  • DirectoryIterator::key() - Return the key for the current DirectoryIterator item
  • DirectoryIterator::getFilename() - Return file name of current DirectoryIterator item
  • DirectoryIterator::getPathname() - Return path and file name of current DirectoryIterator item


Move to the next file

  • « FilesystemIterator::key
  • FilesystemIterator::rewind »
  • PHP Manual
  • FilesystemIterator
  • Move to the next file

FilesystemIterator::next

(PHP 5 >= 5.3.0, PHP 7)

FilesystemIterator::next — Move to the next file

Description

public FilesystemIterator::next ( void ) : void

Move to the next file.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 FilesystemIterator::next() example

List the contents of a directory using a while loop.

<?php
$iterator = new FilesystemIterator(dirname(__FILE__));
while($iterator->valid()) {
    echo $iterator->getFilename() . "\n";
    $iterator->next();
}
?>

The above example will output something similar to:

apple.jpg
banana.jpg
example.php

See Also

  • DirectoryIterator::next() - Move forward to next DirectoryIterator item


Rewinds back to the beginning

  • « FilesystemIterator::next
  • FilesystemIterator::setFlags »
  • PHP Manual
  • FilesystemIterator
  • Rewinds back to the beginning

FilesystemIterator::rewind

(PHP 5 >= 5.3.0, PHP 7)

FilesystemIterator::rewind — Rewinds back to the beginning

Description

public FilesystemIterator::rewind ( void ) : void

Rewinds the directory back to the start.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 FilesystemIterator::rewind() example

<?php
$iterator = new FilesystemIterator(dirname(__FILE__), FilesystemIterator::KEY_AS_FILENAME);

echo $iterator->key() . "\n";

$iterator->next();
echo $iterator->key() . "\n";

$iterator->rewind();
echo $iterator->key() . "\n";
?>

The above example will output something similar to:

apple.jpg
banana.jpg
apple.jpg

See Also

  • DirectoryIterator::rewind() - Rewind the DirectoryIterator back to the start


Sets handling flags

  • « FilesystemIterator::rewind
  • FilterIterator »
  • PHP Manual
  • FilesystemIterator
  • Sets handling flags

FilesystemIterator::setFlags

(PHP 5 >= 5.3.0, PHP 7)

FilesystemIterator::setFlags — Sets handling flags

Description

public FilesystemIterator::setFlags ([ int $flags ] ) : void

Sets handling flags.

Parameters

flags

The handling flags to set. See the FilesystemIterator constants.

Return Values

No value is returned.

Examples

Example #1 FilesystemIterator::key() example

This example demonstrates the difference between the FilesystemIterator::KEY_AS_PATHNAME and FilesystemIterator::KEY_AS_FILENAME flags.

<?php
$iterator = new FilesystemIterator(dirname(__FILE__), FilesystemIterator::KEY_AS_PATHNAME);
echo "Key as Pathname:\n";
foreach ($iterator as $key => $fileinfo) {
    echo $key . "\n";
}

$iterator->setFlags(FilesystemIterator::KEY_AS_FILENAME);
echo "\nKey as Filename:\n";
foreach ($iterator as $key => $fileinfo) {
    echo $key . "\n";
}
?>

The above example will output something similar to:

Key as Pathname:
/www/examples/apple.jpg
/www/examples/banana.jpg
/www/examples/example.php

Key as Filename:
apple.jpg
banana.jpg
example.php

See Also

  • FilesystemIterator::__construct() - Constructs a new filesystem iterator
  • FilesystemIterator::getFlags() - Get the handling flags


The FilterIterator class

(PHP 5 >= 5.1.0, PHP 7)

Introduction

This abstract iterator filters out unwanted values. This class should be extended to implement custom iterator filters. The FilterIterator::accept() must be implemented in the subclass.

Class synopsis

abstract FilterIterator extends IteratorIterator implements OuterIterator {
/* Methods */
public abstract accept ( void ) : bool
public __construct ( Iterator $iterator )
public current ( void ) : mixed
public getInnerIterator ( void ) : Iterator
public key ( void ) : mixed
public next ( void ) : void
public rewind ( void ) : void
public valid ( void ) : bool
}

Table of Contents

  • FilterIterator::accept — Check whether the current element of the iterator is acceptable
  • FilterIterator::__construct — Construct a filterIterator
  • FilterIterator::current — Get the current element value
  • FilterIterator::getInnerIterator — Get the inner iterator
  • FilterIterator::key — Get the current key
  • FilterIterator::next — Move the iterator forward
  • FilterIterator::rewind — Rewind the iterator
  • FilterIterator::valid — Check whether the current element is valid


Check whether the current element of the iterator is acceptable

  • « FilterIterator
  • FilterIterator::__construct »
  • PHP Manual
  • FilterIterator
  • Check whether the current element of the iterator is acceptable

FilterIterator::accept

(PHP 5 >= 5.1.0, PHP 7)

FilterIterator::accept — Check whether the current element of the iterator is acceptable

Description

public abstract FilterIterator::accept ( void ) : bool

Returns whether the current element of the iterator is acceptable through this filter.

Parameters

This function has no parameters.

Return Values

TRUE if the current element is acceptable, otherwise FALSE.

Examples

Example #1 FilterIterator::accept() example

<?php
// This iterator filters all values with less than 10 characters
class LengthFilterIterator extends FilterIterator {

    public function accept() {
        // Only accept strings with a length of 10 and greater
        return strlen(parent::current()) >= 10;
    }

}

$arrayIterator = new ArrayIterator(array('test1', 'more than 10 characters'));
$lengthFilter = new LengthFilterIterator($arrayIterator);

foreach ($lengthFilter as $value) {
    echo $value . "\n";
}
?>

The above example will output:

more than 10 characters


Construct a filterIterator

  • « FilterIterator::accept
  • FilterIterator::current »
  • PHP Manual
  • FilterIterator
  • Construct a filterIterator

FilterIterator::__construct

(PHP 5 >= 5.1.0, PHP 7)

FilterIterator::__construct — Construct a filterIterator

Description

public FilterIterator::__construct ( Iterator $iterator )

Constructs a new FilterIterator, which consists of a passed in iterator with filters applied to it.

Warning

This function is currently not documented; only its argument list is available.

Parameters

iterator

The iterator that is being filtered.

Return Values

The FilterIterator.

See Also

  • LimitIterator::__construct() - Construct a LimitIterator


Get the current element value

  • « FilterIterator::__construct
  • FilterIterator::getInnerIterator »
  • PHP Manual
  • FilterIterator
  • Get the current element value

FilterIterator::current

(PHP 5 >= 5.1.0, PHP 7)

FilterIterator::current — Get the current element value

Description

public FilterIterator::current ( void ) : mixed
Warning

This function is currently not documented; only its argument list is available.

Get the current element value.

Parameters

This function has no parameters.

Return Values

The current element value.

See Also

  • FilterIterator::key() - Get the current key
  • FilterIterator::next() - Move the iterator forward


Get the inner iterator

  • « FilterIterator::current
  • FilterIterator::key »
  • PHP Manual
  • FilterIterator
  • Get the inner iterator

FilterIterator::getInnerIterator

(PHP 5 >= 5.1.0, PHP 7)

FilterIterator::getInnerIterator — Get the inner iterator

Description

public FilterIterator::getInnerIterator ( void ) : Iterator
Warning

This function is currently not documented; only its argument list is available.

Get the inner iterator.

Parameters

This function has no parameters.

Return Values

The inner iterator.


Get the current key

  • « FilterIterator::getInnerIterator
  • FilterIterator::next »
  • PHP Manual
  • FilterIterator
  • Get the current key

FilterIterator::key

(PHP 5 >= 5.1.0, PHP 7)

FilterIterator::key — Get the current key

Description

public FilterIterator::key ( void ) : mixed
Warning

This function is currently not documented; only its argument list is available.

Get the current key.

Parameters

This function has no parameters.

Return Values

The current key.

See Also

  • FilterIterator::next() - Move the iterator forward
  • FilterIterator::current() - Get the current element value


Move the iterator forward

  • « FilterIterator::key
  • FilterIterator::rewind »
  • PHP Manual
  • FilterIterator
  • Move the iterator forward

FilterIterator::next

(PHP 5 >= 5.1.0, PHP 7)

FilterIterator::next — Move the iterator forward

Description

public FilterIterator::next ( void ) : void
Warning

This function is currently not documented; only its argument list is available.

Move the iterator forward.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • FilterIterator::current() - Get the current element value
  • FilterIterator::key() - Get the current key


Rewind the iterator

  • « FilterIterator::next
  • FilterIterator::valid »
  • PHP Manual
  • FilterIterator
  • Rewind the iterator

FilterIterator::rewind

(PHP 5 >= 5.1.0, PHP 7)

FilterIterator::rewind — Rewind the iterator

Description

public FilterIterator::rewind ( void ) : void
Warning

This function is currently not documented; only its argument list is available.

Rewind the iterator.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • FilterIterator::current() - Get the current element value
  • FilterIterator::key() - Get the current key
  • FilterIterator::next() - Move the iterator forward


Check whether the current element is valid

  • « FilterIterator::rewind
  • GlobIterator »
  • PHP Manual
  • FilterIterator
  • Check whether the current element is valid

FilterIterator::valid

(PHP 5 >= 5.1.0, PHP 7)

FilterIterator::valid — Check whether the current element is valid

Description

public FilterIterator::valid ( void ) : bool
Warning

This function is currently not documented; only its argument list is available.

Checks whether the current element is valid.

Parameters

This function has no parameters.

Return Values

TRUE if the current element is valid, otherwise FALSE


The GlobIterator class

(PHP 5 >= 5.3.0, PHP 7)

Introduction

Iterates through a file system in a similar fashion to glob().

Class synopsis

GlobIterator extends FilesystemIterator implements SeekableIterator , Countable {
/* Inherited constants */
const integer FilesystemIterator::CURRENT_AS_PATHNAME = 32 ;
const integer FilesystemIterator::CURRENT_AS_FILEINFO = 0 ;
const integer FilesystemIterator::CURRENT_AS_SELF = 16 ;
const integer FilesystemIterator::CURRENT_MODE_MASK = 240 ;
const integer FilesystemIterator::KEY_AS_PATHNAME = 0 ;
const integer FilesystemIterator::KEY_AS_FILENAME = 256 ;
const integer FilesystemIterator::FOLLOW_SYMLINKS = 512 ;
const integer FilesystemIterator::KEY_MODE_MASK = 3840 ;
const integer FilesystemIterator::NEW_CURRENT_AND_KEY = 256 ;
const integer FilesystemIterator::SKIP_DOTS = 4096 ;
const integer FilesystemIterator::UNIX_PATHS = 8192 ;
/* Methods */
public __construct ( string $pattern [, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO ] )
public count ( void ) : int
/* Inherited methods */
public FilesystemIterator::__construct ( string $path [, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS ] )
public FilesystemIterator::current ( void ) : mixed
public FilesystemIterator::getFlags ( void ) : int
public FilesystemIterator::key ( void ) : string
public FilesystemIterator::next ( void ) : void
public FilesystemIterator::rewind ( void ) : void
public FilesystemIterator::setFlags ([ int $flags ] ) : void
}

Table of Contents

  • GlobIterator::__construct — Construct a directory using glob
  • GlobIterator::count — Get the number of directories and files


Construct a directory using glob

  • « GlobIterator
  • GlobIterator::count »
  • PHP Manual
  • GlobIterator
  • Construct a directory using glob

GlobIterator::__construct

(PHP 5 >= 5.3.0, PHP 7)

GlobIterator::__construct — Construct a directory using glob

Description

public GlobIterator::__construct ( string $pattern [, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO ] )

Constructs a new directory iterator from a glob expression.

Parameters

pattern

A glob() pattern.

flags

Option flags, the flags may be a bitmask of the FilesystemIterator constants.

Examples

Example #1 GlobIterator example

<?php
$iterator = new GlobIterator('*.dll', FilesystemIterator::KEY_AS_FILENAME);

if (!$iterator->count()) {
    echo 'No matches';
} else {
    $n = 0;

    printf("Matched %d item(s)\r\n", $iterator->count());

    foreach ($iterator as $item) {
        printf("[%d] %s\r\n", ++$n, $iterator->key());
    }
}
?>

The above example will output something similar to:

Matched 2 item(s)
[1] php5ts.dll
[2] php_gd2.dll

See Also

  • DirectoryIterator::__construct() - Constructs a new directory iterator from a path
  • GlobIterator::count() - Get the number of directories and files
  • glob() - Find pathnames matching a pattern


Get the number of directories and files

  • « GlobIterator::__construct
  • InfiniteIterator »
  • PHP Manual
  • GlobIterator
  • Get the number of directories and files

GlobIterator::count

(PHP 5 >= 5.3.0, PHP 7)

GlobIterator::count — Get the number of directories and files

Description

public GlobIterator::count ( void ) : int

Gets the number of directories and files found by the glob expression.

Parameters

This function has no parameters.

Return Values

The number of returned directories and files, as an integer.

Examples

Example #1 GlobIterator::count() example

<?php
$iterator = new GlobIterator('*.xml');

printf("Matched %d item(s)\r\n", $iterator->count());
?>

The above example will output something similar to:

Matched 8 item(s)

See Also

  • GlobIterator::__construct() - Construct a directory using glob
  • count() - Count all elements in an array, or something in an object
  • glob() - Find pathnames matching a pattern


The InfiniteIterator class

(PHP 5 >= 5.1.0, PHP 7)

Introduction

The InfiniteIterator allows one to infinitely iterate over an iterator without having to manually rewind the iterator upon reaching its end.

Class synopsis

InfiniteIterator extends IteratorIterator implements OuterIterator {
/* Methods */
public __construct ( Iterator $iterator )
public next ( void ) : void
/* Inherited methods */
public IteratorIterator::__construct ( Traversable $iterator )
public IteratorIterator::current ( void ) : mixed
public IteratorIterator::getInnerIterator ( void ) : Traversable
public IteratorIterator::key ( void ) : mixed
public IteratorIterator::next ( void ) : void
public IteratorIterator::rewind ( void ) : void
public IteratorIterator::valid ( void ) : bool
}

Table of Contents

  • InfiniteIterator::__construct — Constructs an InfiniteIterator
  • InfiniteIterator::next — Moves the inner Iterator forward or rewinds it


Constructs an InfiniteIterator

  • « InfiniteIterator
  • InfiniteIterator::next »
  • PHP Manual
  • InfiniteIterator
  • Constructs an InfiniteIterator

InfiniteIterator::__construct

(PHP 5 >= 5.1.0, PHP 7)

InfiniteIterator::__construct — Constructs an InfiniteIterator

Description

public InfiniteIterator::__construct ( Iterator $iterator )

Constructs an InfiniteIterator from an Iterator.

Parameters

iterator

The iterator to infinitely iterate over.

Return Values

No value is returned.

Errors/Exceptions

Throws an E_RECOVERABLE_ERROR if the iterator parameter is not an Iterator.

Examples

Example #1 InfiniteIterator::__construct() example

<?php
$arrayit  = new ArrayIterator(array('cat','dog'));
$infinite = new InfiniteIterator($arrayit);
$limit    = new LimitIterator($infinite, 0, 7);
foreach($limit as $value)
{
    echo "$value\n";
}
?>

The above example will output:

cat
dog
cat
dog
cat
dog
cat

See Also

  • InfiniteIterator::next() - Moves the inner Iterator forward or rewinds it


Moves the inner Iterator forward or rewinds it

  • « InfiniteIterator::__construct
  • IteratorIterator »
  • PHP Manual
  • InfiniteIterator
  • Moves the inner Iterator forward or rewinds it

InfiniteIterator::next

(PHP 5 >= 5.1.0, PHP 7)

InfiniteIterator::next — Moves the inner Iterator forward or rewinds it

Description

public InfiniteIterator::next ( void ) : void

Moves the inner Iterator forward to its next element if there is one, otherwise rewinds the inner Iterator back to the beginning.

Note:

Even an InfiniteIterator stops if its inner Iterator is empty.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • InfiniteIterator::__construct() - Constructs an InfiniteIterator


The IteratorIterator class

(PHP 5 >= 5.1.0, PHP 7)

Introduction

This iterator wrapper allows the conversion of anything that is Traversable into an Iterator. It is important to understand that most classes that do not implement Iterators have reasons as most likely they do not allow the full Iterator feature set. If so, techniques should be provided to prevent misuse, otherwise expect exceptions or fatal errors.

Class synopsis

IteratorIterator implements OuterIterator {
/* Methods */
public __construct ( Traversable $iterator )
public current ( void ) : mixed
public getInnerIterator ( void ) : Traversable
public key ( void ) : mixed
public next ( void ) : void
public rewind ( void ) : void
public valid ( void ) : bool
}

Notes

Note:

This class permits access to methods of the inner iterator via the __call magic method.

Table of Contents

  • IteratorIterator::__construct — Create an iterator from anything that is traversable
  • IteratorIterator::current — Get the current value
  • IteratorIterator::getInnerIterator — Get the inner iterator
  • IteratorIterator::key — Get the key of the current element
  • IteratorIterator::next — Forward to the next element
  • IteratorIterator::rewind — Rewind to the first element
  • IteratorIterator::valid — Checks if the iterator is valid


Create an iterator from anything that is traversable

  • « IteratorIterator
  • IteratorIterator::current »
  • PHP Manual
  • IteratorIterator
  • Create an iterator from anything that is traversable

IteratorIterator::__construct

(PHP 5 >= 5.1.0, PHP 7)

IteratorIterator::__construct — Create an iterator from anything that is traversable

Description

public IteratorIterator::__construct ( Traversable $iterator )

Creates an iterator from anything that is traversable.

Parameters

iterator

The traversable iterator.

Return Values

No value is returned.

See Also

  • Traversable


Get the current value

  • « IteratorIterator::__construct
  • IteratorIterator::getInnerIterator »
  • PHP Manual
  • IteratorIterator
  • Get the current value

IteratorIterator::current

(PHP 5 >= 5.1.0, PHP 7)

IteratorIterator::current — Get the current value

Description

public IteratorIterator::current ( void ) : mixed

Get the value of the current element.

Parameters

This function has no parameters.

Return Values

The value of the current element.

See Also

  • IteratorIterator::key() - Get the key of the current element


Get the inner iterator

  • « IteratorIterator::current
  • IteratorIterator::key »
  • PHP Manual
  • IteratorIterator
  • Get the inner iterator

IteratorIterator::getInnerIterator

(PHP 5 >= 5.1.0, PHP 7)

IteratorIterator::getInnerIterator — Get the inner iterator

Description

public IteratorIterator::getInnerIterator ( void ) : Traversable

Get the inner iterator.

Parameters

This function has no parameters.

Return Values

The inner iterator as passed to IteratorIterator::__construct().

See Also

  • Iterator
  • OuterIterator


Get the key of the current element

  • « IteratorIterator::getInnerIterator
  • IteratorIterator::next »
  • PHP Manual
  • IteratorIterator
  • Get the key of the current element

IteratorIterator::key

(PHP 5 >= 5.1.0, PHP 7)

IteratorIterator::key — Get the key of the current element

Description

public IteratorIterator::key ( void ) : mixed

Get the key of the current element.

Parameters

This function has no parameters.

Return Values

The key of the current element.

See Also

  • IteratorIterator::current() - Get the current value


Forward to the next element

  • « IteratorIterator::key
  • IteratorIterator::rewind »
  • PHP Manual
  • IteratorIterator
  • Forward to the next element

IteratorIterator::next

(PHP 5 >= 5.1.0, PHP 7)

IteratorIterator::next — Forward to the next element

Description

public IteratorIterator::next ( void ) : void

Forward to the next element.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • IteratorIterator::rewind() - Rewind to the first element
  • IteratorIterator::valid() - Checks if the iterator is valid


Rewind to the first element

  • « IteratorIterator::next
  • IteratorIterator::valid »
  • PHP Manual
  • IteratorIterator
  • Rewind to the first element

IteratorIterator::rewind

(PHP 5 >= 5.1.0, PHP 7)

IteratorIterator::rewind — Rewind to the first element

Description

public IteratorIterator::rewind ( void ) : void

Rewinds to the first element.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • IteratorIterator::next() - Forward to the next element
  • IteratorIterator::valid() - Checks if the iterator is valid


Checks if the iterator is valid

  • « IteratorIterator::rewind
  • LimitIterator »
  • PHP Manual
  • IteratorIterator
  • Checks if the iterator is valid

IteratorIterator::valid

(PHP 5 >= 5.1.0, PHP 7)

IteratorIterator::valid — Checks if the iterator is valid

Description

public IteratorIterator::valid ( void ) : bool

Checks if the iterator is valid.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the iterator is valid, otherwise FALSE

See Also

  • iterator_count() - Count the elements in an iterator
  • IteratorIterator::current() - Get the current value


The LimitIterator class

(PHP 5 >= 5.1.0, PHP 7)

Introduction

The LimitIterator class allows iteration over a limited subset of items in an Iterator.

Class synopsis

LimitIterator extends IteratorIterator implements OuterIterator {
/* Methods */
public __construct ( Iterator $iterator [, int $offset = 0 [, int $count = -1 ]] )
public current ( void ) : mixed
public getInnerIterator ( void ) : Iterator
public getPosition ( void ) : int
public key ( void ) : mixed
public next ( void ) : void
public rewind ( void ) : void
public seek ( int $position ) : int
public valid ( void ) : bool
}

Examples

Example #1 LimitIterator usage example

<?php

// Create an iterator to be limited
$fruits = new ArrayIterator(array(
    'apple',
    'banana',
    'cherry',
    'damson',
    'elderberry'
));

// Loop over first three fruits only
foreach (new LimitIterator($fruits, 0, 3) as $fruit) {
    var_dump($fruit);
}

echo "\n";

// Loop from third fruit until the end
// Note: offset starts from zero for apple
foreach (new LimitIterator($fruits, 2) as $fruit) {
    var_dump($fruit);
}

?>

The above example will output:

string(5) "apple"
string(6) "banana"
string(6) "cherry"

string(6) "cherry"
string(6) "damson"
string(10) "elderberry"

Table of Contents

  • LimitIterator::__construct — Construct a LimitIterator
  • LimitIterator::current — Get current element
  • LimitIterator::getInnerIterator — Get inner iterator
  • LimitIterator::getPosition — Return the current position
  • LimitIterator::key — Get current key
  • LimitIterator::next — Move the iterator forward
  • LimitIterator::rewind — Rewind the iterator to the specified starting offset
  • LimitIterator::seek — Seek to the given position
  • LimitIterator::valid — Check whether the current element is valid


Construct a LimitIterator

  • « LimitIterator
  • LimitIterator::current »
  • PHP Manual
  • LimitIterator
  • Construct a LimitIterator

LimitIterator::__construct

(PHP 5 >= 5.1.0, PHP 7)

LimitIterator::__construct — Construct a LimitIterator

Description

public LimitIterator::__construct ( Iterator $iterator [, int $offset = 0 [, int $count = -1 ]] )

Constructs a new LimitIterator from an iterator with a given starting offset and maximum count.

Parameters

iterator

The Iterator to limit.

offset

Optional offset of the limit.

count

Optional count of the limit.

Return Values

The new LimitIterator.

Errors/Exceptions

Throws an OutOfRangeException if the offset is less than 0 or the count is less than -1.

Examples

Example #1 LimitIterator::__construct() example

<?php
$ait = new ArrayIterator(array('a', 'b', 'c', 'd', 'e'));
$lit = new LimitIterator($ait, 1, 3);
foreach ($lit as $value) {
    echo $value . "\n";
}
?>

The above example will output:

b
c
d

See Also

  • LimitIterator examples


Get current element

  • « LimitIterator::__construct
  • LimitIterator::getInnerIterator »
  • PHP Manual
  • LimitIterator
  • Get current element

LimitIterator::current

(PHP 5 >= 5.1.0, PHP 7)

LimitIterator::current — Get current element

Description

public LimitIterator::current ( void ) : mixed

Gets the current element of the inner Iterator.

Parameters

This function has no parameters.

Return Values

Returns the current element or NULL if there is none.

See Also

  • LimitIterator::key() - Get current key
  • LimitIterator::next() - Move the iterator forward
  • LimitIterator::rewind() - Rewind the iterator to the specified starting offset
  • LimitIterator::seek() - Seek to the given position
  • LimitIterator::valid() - Check whether the current element is valid


Get inner iterator

  • « LimitIterator::current
  • LimitIterator::getPosition »
  • PHP Manual
  • LimitIterator
  • Get inner iterator

LimitIterator::getInnerIterator

(PHP 5 >= 5.1.0, PHP 7)

LimitIterator::getInnerIterator — Get inner iterator

Description

public LimitIterator::getInnerIterator ( void ) : Iterator

Gets the inner Iterator.

Parameters

This function has no parameters.

Return Values

The inner iterator passed to LimitIterator::__construct().

See Also

  • LimitIterator::__construct() - Construct a LimitIterator
  • IteratorIterator::getInnerIterator() - Get the inner iterator


Return the current position

  • « LimitIterator::getInnerIterator
  • LimitIterator::key »
  • PHP Manual
  • LimitIterator
  • Return the current position

LimitIterator::getPosition

(PHP 5 >= 5.1.0, PHP 7)

LimitIterator::getPosition — Return the current position

Description

public LimitIterator::getPosition ( void ) : int

Gets the current zero-based position of the inner Iterator.

Parameters

This function has no parameters.

Return Values

The current position.

Examples

Example #1 LimitIterator::getPosition() example

<?php
$fruits = array(
    'a' => 'apple',
    'b' => 'banana',
    'c' => 'cherry',
    'd' => 'damson',
    'e' => 'elderberry'
);
$array_it = new ArrayIterator($fruits);
$limit_it = new LimitIterator($array_it, 2, 3);
foreach ($limit_it as $item) {
    echo $limit_it->getPosition() . ' ' . $item . "\n";
}
?>

The above example will output:

2 cherry
3 damson
4 elderberry

See Also

  • FilterIterator::key() - Get the current key


Get current key

  • « LimitIterator::getPosition
  • LimitIterator::next »
  • PHP Manual
  • LimitIterator
  • Get current key

LimitIterator::key

(PHP 5 >= 5.1.0, PHP 7)

LimitIterator::key — Get current key

Description

public LimitIterator::key ( void ) : mixed

Gets the key for the current item in the inner Iterator.

Parameters

This function has no parameters.

Return Values

Returns the key for the current item.

See Also

  • LimitIterator::getPosition() - Return the current position
  • LimitIterator::current() - Get current element
  • LimitIterator::next() - Move the iterator forward
  • LimitIterator::rewind() - Rewind the iterator to the specified starting offset
  • LimitIterator::seek() - Seek to the given position
  • LimitIterator::valid() - Check whether the current element is valid


Move the iterator forward

  • « LimitIterator::key
  • LimitIterator::rewind »
  • PHP Manual
  • LimitIterator
  • Move the iterator forward

LimitIterator::next

(PHP 5 >= 5.1.0, PHP 7)

LimitIterator::next — Move the iterator forward

Description

public LimitIterator::next ( void ) : void

Moves the iterator forward.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • LimitIterator::current() - Get current element
  • LimitIterator::key() - Get current key
  • LimitIterator::rewind() - Rewind the iterator to the specified starting offset
  • LimitIterator::seek() - Seek to the given position
  • LimitIterator::valid() - Check whether the current element is valid


Rewind the iterator to the specified starting offset

  • « LimitIterator::next
  • LimitIterator::seek »
  • PHP Manual
  • LimitIterator
  • Rewind the iterator to the specified starting offset

LimitIterator::rewind

(PHP 5 >= 5.1.0, PHP 7)

LimitIterator::rewind — Rewind the iterator to the specified starting offset

Description

public LimitIterator::rewind ( void ) : void

Rewinds the iterator to the starting offset specified in LimitIterator::__construct().

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • LimitIterator::current() - Get current element
  • LimitIterator::key() - Get current key
  • LimitIterator::next() - Move the iterator forward
  • LimitIterator::seek() - Seek to the given position
  • LimitIterator::valid() - Check whether the current element is valid


Seek to the given position

  • « LimitIterator::rewind
  • LimitIterator::valid »
  • PHP Manual
  • LimitIterator
  • Seek to the given position

LimitIterator::seek

(PHP 5 >= 5.1.0, PHP 7)

LimitIterator::seek — Seek to the given position

Description

public LimitIterator::seek ( int $position ) : int

Moves the iterator to the offset specified by position.

Parameters

position

The position to seek to.

Return Values

Returns the offset position after seeking.

Errors/Exceptions

Throws an OutOfBoundsException if the position is outside of the limits specified in LimitIterator::__construct().

See Also

  • LimitIterator::current() - Get current element
  • LimitIterator::key() - Get current key
  • LimitIterator::rewind() - Rewind the iterator to the specified starting offset
  • LimitIterator::next() - Move the iterator forward
  • LimitIterator::valid() - Check whether the current element is valid


Check whether the current element is valid

  • « LimitIterator::seek
  • MultipleIterator »
  • PHP Manual
  • LimitIterator
  • Check whether the current element is valid

LimitIterator::valid

(PHP 5 >= 5.1.0, PHP 7)

LimitIterator::valid — Check whether the current element is valid

Description

public LimitIterator::valid ( void ) : bool

Checks whether the current element is valid.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • LimitIterator::current() - Get current element
  • LimitIterator::key() - Get current key
  • LimitIterator::rewind() - Rewind the iterator to the specified starting offset
  • LimitIterator::next() - Move the iterator forward
  • LimitIterator::seek() - Seek to the given position


The MultipleIterator class

(PHP 5 >= 5.3.0, PHP 7)

Introduction

An Iterator that sequentially iterates over all attached iterators

Class synopsis

MultipleIterator implements Iterator {
/* Constants */
const integer MIT_NEED_ANY = 0 ;
const integer MIT_NEED_ALL = 1 ;
const integer MIT_KEYS_NUMERIC = 0 ;
const integer MIT_KEYS_ASSOC = 2 ;
/* Methods */
public __construct ([ int $flags = MultipleIterator::MIT_NEED_ALL|MultipleIterator::MIT_KEYS_NUMERIC ] )
public attachIterator ( Iterator $iterator [, string $infos ] ) : void
public containsIterator ( Iterator $iterator ) : bool
public countIterators ( void ) : int
public current ( void ) : array
public detachIterator ( Iterator $iterator ) : void
public getFlags ( void ) : int
public key ( void ) : array
public next ( void ) : void
public rewind ( void ) : void
public setFlags ( int $flags ) : void
public valid ( void ) : bool
}

Predefined Constants

MultipleIterator::MIT_NEED_ANY

Do not require all sub iterators to be valid in iteration.

MultipleIterator::MIT_NEED_ALL

Require all sub iterators to be valid in iteration.

MultipleIterator::MIT_KEYS_NUMERIC

Keys are created from the sub iterators position.

MultipleIterator::MIT_KEYS_ASSOC

Keys are created from sub iterators associated information.

Table of Contents

  • MultipleIterator::attachIterator — Attaches iterator information
  • MultipleIterator::__construct — Constructs a new MultipleIterator
  • MultipleIterator::containsIterator — Checks if an iterator is attached
  • MultipleIterator::countIterators — Gets the number of attached iterator instances
  • MultipleIterator::current — Gets the registered iterator instances
  • MultipleIterator::detachIterator — Detaches an iterator
  • MultipleIterator::getFlags — Gets the flag information
  • MultipleIterator::key — Gets the registered iterator instances
  • MultipleIterator::next — Moves all attached iterator instances forward
  • MultipleIterator::rewind — Rewinds all attached iterator instances
  • MultipleIterator::setFlags — Sets flags
  • MultipleIterator::valid — Checks the validity of sub iterators


Attaches iterator information

  • « MultipleIterator
  • MultipleIterator::__construct »
  • PHP Manual
  • MultipleIterator
  • Attaches iterator information

MultipleIterator::attachIterator

(PHP 5 >= 5.3.0, PHP 7)

MultipleIterator::attachIterator — Attaches iterator information

Description

public MultipleIterator::attachIterator ( Iterator $iterator [, string $infos ] ) : void

Attaches iterator information.

Warning

This function is currently not documented; only its argument list is available.

Parameters

iterator

The new iterator to attach.

infos

The associative information for the Iterator, which must be an integer, a string, or NULL.

Return Values

Description...

Errors/Exceptions

An IllegalValueException if the iterator parameter is invalid, or if infos is already associated information.

See Also

  • MultipleIterator::__construct() - Constructs a new MultipleIterator


Constructs a new MultipleIterator

  • « MultipleIterator::attachIterator
  • MultipleIterator::containsIterator »
  • PHP Manual
  • MultipleIterator
  • Constructs a new MultipleIterator

MultipleIterator::__construct

(PHP 5 >= 5.3.0, PHP 7)

MultipleIterator::__construct — Constructs a new MultipleIterator

Description

public MultipleIterator::__construct ([ int $flags = MultipleIterator::MIT_NEED_ALL|MultipleIterator::MIT_KEYS_NUMERIC ] )

Construct a new MultipleIterator.

Parameters

flags

The flags to set, according to the Flag Constants.

  • MultipleIterator::MIT_NEED_ALL or MultipleIterator::MIT_NEED_ANY
  • MultipleIterator::MIT_KEYS_NUMERIC or MultipleIterator::MIT_KEYS_ASSOC

Defaults to MultipleIterator::MIT_NEED_ALL|MultipleIterator::MIT_KEYS_NUMERIC.

Return Values

No value is returned.

Examples

Example #1 Iterating a MultipleIterator

<?php
$people = new ArrayIterator(array('John', 'Jane', 'Jack', 'Judy'));
$roles  = new ArrayIterator(array('Developer', 'Scrum Master', 'Project Owner'));

$team = new MultipleIterator($flags);
$team->attachIterator($people, 'person');
$team->attachIterator($roles, 'role');

foreach ($team as $member) {
    print_r($member);
}
?>

Output with $flags = MIT_NEED_ALL|MIT_KEYS_NUMERIC

Array
(
    [0] => John
    [1] => Developer
)
Array
(
    [0] => Jane
    [1] => Scrum Master
)
Array
(
    [0] => Jack
    [1] => Project Owner
)

Output with $flags = MIT_NEED_ANY|MIT_KEYS_NUMERIC

Array
(
    [0] => John
    [1] => Developer
)
Array
(
    [0] => Jane
    [1] => Scrum Master
)
Array
(
    [0] => Jack
    [1] => Project Owner
)
Array
(
    [0] => Judy
    [1] =>
)

Output with $flags = MIT_NEED_ALL|MIT_KEYS_ASSOC

Array
(
    [person] => John
    [role] => Developer
)
Array
(
    [person] => Jane
    [role] => Scrum Master
)
Array
(
    [person] => Jack
    [role] => Project Owner
)

Output with $flags = MIT_NEED_ANY|MIT_KEYS_ASSOC

Array
(
    [person] => John
    [role] => Developer
)
Array
(
    [person] => Jane
    [role] => Scrum Master
)
Array
(
    [person] => Jack
    [role] => Project Owner
)
Array
(
    [person] => Judy
    [role] =>
)

See Also

  • Flag Constants
  • MultipleIterator::valid() - Checks the validity of sub iterators


Checks if an iterator is attached

  • « MultipleIterator::__construct
  • MultipleIterator::countIterators »
  • PHP Manual
  • MultipleIterator
  • Checks if an iterator is attached

MultipleIterator::containsIterator

(PHP 5 >= 5.3.0, PHP 7)

MultipleIterator::containsIterator — Checks if an iterator is attached

Description

public MultipleIterator::containsIterator ( Iterator $iterator ) : bool

Checks if an iterator is attached or not.

Warning

This function is currently not documented; only its argument list is available.

Parameters

iterator

The iterator to check.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • MultipleIterator::valid() - Checks the validity of sub iterators


Gets the number of attached iterator instances

  • « MultipleIterator::containsIterator
  • MultipleIterator::current »
  • PHP Manual
  • MultipleIterator
  • Gets the number of attached iterator instances

MultipleIterator::countIterators

(PHP 5 >= 5.3.0, PHP 7)

MultipleIterator::countIterators — Gets the number of attached iterator instances

Description

public MultipleIterator::countIterators ( void ) : int

Gets the number of attached iterator instances.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The number of attached iterator instances (as an integer).

See Also

  • MultipleIterator::containsIterator() - Checks if an iterator is attached


Gets the registered iterator instances

  • « MultipleIterator::countIterators
  • MultipleIterator::detachIterator »
  • PHP Manual
  • MultipleIterator
  • Gets the registered iterator instances

MultipleIterator::current

(PHP 5 >= 5.3.0, PHP 7)

MultipleIterator::current — Gets the registered iterator instances

Description

public MultipleIterator::current ( void ) : array

Get the registered iterator instances current() result.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

An array containing the current values of each attached iterator, or FALSE if no iterators are attached.

Errors/Exceptions

A RuntimeException if mode MIT_NEED_ALL is set and at least one attached iterator is not valid. Or an IllegalValueException if a key is NULL and MIT_KEYS_ASSOC is set.

See Also

  • MultipleIterator::valid() - Checks the validity of sub iterators


Detaches an iterator

  • « MultipleIterator::current
  • MultipleIterator::getFlags »
  • PHP Manual
  • MultipleIterator
  • Detaches an iterator

MultipleIterator::detachIterator

(PHP 5 >= 5.3.0, PHP 7)

MultipleIterator::detachIterator — Detaches an iterator

Description

public MultipleIterator::detachIterator ( Iterator $iterator ) : void

Detaches an iterator.

Warning

This function is currently not documented; only its argument list is available.

Parameters

iterator

The iterator to detach.

Return Values

No value is returned.

See Also

  • MultipleIterator::attachIterator() - Attaches iterator information


Gets the flag information

  • « MultipleIterator::detachIterator
  • MultipleIterator::key »
  • PHP Manual
  • MultipleIterator
  • Gets the flag information

MultipleIterator::getFlags

(PHP 5 >= 5.3.0, PHP 7)

MultipleIterator::getFlags — Gets the flag information

Description

public MultipleIterator::getFlags ( void ) : int

Gets information about the flags.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Information about the flags, as an integer.

See Also

  • Flag Constants
  • MultipleIterator::__construct() - Constructs a new MultipleIterator
  • MultipleIterator::setFlags() - Sets flags


Gets the registered iterator instances

  • « MultipleIterator::getFlags
  • MultipleIterator::next »
  • PHP Manual
  • MultipleIterator
  • Gets the registered iterator instances

MultipleIterator::key

(PHP 5 >= 5.3.0, PHP 7)

MultipleIterator::key — Gets the registered iterator instances

Description

public MultipleIterator::key ( void ) : array

Get the registered iterator instances key() result.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

An array of all registered iterator instances, or FALSE if no sub iterator is attached.

Errors/Exceptions

A LogicException if mode MIT_NEED_ALL is set, and at least one attached iterator is not valid.

Calling this method from foreach triggers warning "Illegal type returned".

See Also

  • MultipleIterator::current() - Gets the registered iterator instances


Moves all attached iterator instances forward

  • « MultipleIterator::key
  • MultipleIterator::rewind »
  • PHP Manual
  • MultipleIterator
  • Moves all attached iterator instances forward

MultipleIterator::next

(PHP 5 >= 5.3.0, PHP 7)

MultipleIterator::next — Moves all attached iterator instances forward

Description

public MultipleIterator::next ( void ) : void

Moves all attached iterator instances forward.

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.

See Also

  • MultipleIterator::rewind() - Rewinds all attached iterator instances


Rewinds all attached iterator instances

  • « MultipleIterator::next
  • MultipleIterator::setFlags »
  • PHP Manual
  • MultipleIterator
  • Rewinds all attached iterator instances

MultipleIterator::rewind

(PHP 5 >= 5.3.0, PHP 7)

MultipleIterator::rewind — Rewinds all attached iterator instances

Description

public MultipleIterator::rewind ( void ) : void

Rewinds all attached iterator instances.

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.

See Also

  • MultipleIterator::next() - Moves all attached iterator instances forward


Sets flags

  • « MultipleIterator::rewind
  • MultipleIterator::valid »
  • PHP Manual
  • MultipleIterator
  • Sets flags

MultipleIterator::setFlags

(PHP 5 >= 5.3.0, PHP 7)

MultipleIterator::setFlags — Sets flags

Description

public MultipleIterator::setFlags ( int $flags ) : void

Sets flags.

Warning

This function is currently not documented; only its argument list is available.

Parameters

flags

The flags to set, according to the Flag Constants

Return Values

No value is returned.

See Also

  • Flag Constants
  • MultipleIterator::__construct() - Constructs a new MultipleIterator
  • MultipleIterator::getFlags() - Gets the flag information


Checks the validity of sub iterators

  • « MultipleIterator::setFlags
  • NoRewindIterator »
  • PHP Manual
  • MultipleIterator
  • Checks the validity of sub iterators

MultipleIterator::valid

(PHP 5 >= 5.3.0, PHP 7)

MultipleIterator::valid — Checks the validity of sub iterators

Description

public MultipleIterator::valid ( void ) : bool

Checks the validity of sub iterators.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns TRUE if one or all sub iterators are valid depending on flags, otherwise FALSE

See Also

  • MultipleIterator::__construct() - Constructs a new MultipleIterator


The NoRewindIterator class

(PHP 5 >= 5.1.0, PHP 7)

Introduction

This iterator ignores rewind operations. This allows processing an iterator in multiple partial foreach loops.

Class synopsis

NoRewindIterator extends IteratorIterator {
/* Methods */
public __construct ( Iterator $iterator )
public current ( void ) : mixed
public getInnerIterator ( void ) : iterator
public key ( void ) : mixed
public next ( void ) : void
public rewind ( void ) : void
public valid ( void ) : bool
/* Inherited methods */
public IteratorIterator::__construct ( Traversable $iterator )
public IteratorIterator::current ( void ) : mixed
public IteratorIterator::getInnerIterator ( void ) : Traversable
public IteratorIterator::key ( void ) : mixed
public IteratorIterator::next ( void ) : void
public IteratorIterator::rewind ( void ) : void
public IteratorIterator::valid ( void ) : bool
}

Table of Contents

  • NoRewindIterator::__construct — Construct a NoRewindIterator
  • NoRewindIterator::current — Get the current value
  • NoRewindIterator::getInnerIterator — Get the inner iterator
  • NoRewindIterator::key — Get the current key
  • NoRewindIterator::next — Forward to the next element
  • NoRewindIterator::rewind — Prevents the rewind operation on the inner iterator
  • NoRewindIterator::valid — Validates the iterator


Construct a NoRewindIterator

  • « NoRewindIterator
  • NoRewindIterator::current »
  • PHP Manual
  • NoRewindIterator
  • Construct a NoRewindIterator

NoRewindIterator::__construct

(PHP 5 >= 5.1.0, PHP 7)

NoRewindIterator::__construct — Construct a NoRewindIterator

Description

public NoRewindIterator::__construct ( Iterator $iterator )

Constructs a NoRewindIterator.

Parameters

iterator

The iterator being used.

Return Values

A NoRewindIterator() based on the passed in iterator.

Examples

Example #1 NoRewindIterator::__construct() example

The second loop does not output because the iterator is only used once, as it does not rewind.

<?php
$fruit = array('apple', 'banana', 'cranberry');

$arr = new ArrayObject($fruit);
$it  = new NoRewindIterator($arr->getIterator());

echo "Fruit A:\n";
foreach( $it as $item ) {
    echo $item . "\n";
}

echo "Fruit B:\n";
foreach( $it as $item ) {
    echo $item . "\n";
}
?>

The above example will output something similar to:

Fruit A:
apple
banana
cranberry
Fruit B:

See Also

  • NoRewindIterator::valid() - Validates the iterator


Get the current value

  • « NoRewindIterator::__construct
  • NoRewindIterator::getInnerIterator »
  • PHP Manual
  • NoRewindIterator
  • Get the current value

NoRewindIterator::current

(PHP 5 >= 5.1.0, PHP 7)

NoRewindIterator::current — Get the current value

Description

public NoRewindIterator::current ( void ) : mixed

Gets the current value.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The current value.

See Also

  • NoRewindIterator::key() - Get the current key


Get the inner iterator

  • « NoRewindIterator::current
  • NoRewindIterator::key »
  • PHP Manual
  • NoRewindIterator
  • Get the inner iterator

NoRewindIterator::getInnerIterator

(PHP 5 >= 5.1.0, PHP 7)

NoRewindIterator::getInnerIterator — Get the inner iterator

Description

public NoRewindIterator::getInnerIterator ( void ) : iterator

Gets the inner iterator, that was passed in to NoRewindIterator.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The inner iterator, as passed to NoRewindIterator::__construct().

See Also

  • NoRewindIterator::valid() - Validates the iterator


Get the current key

  • « NoRewindIterator::getInnerIterator
  • NoRewindIterator::next »
  • PHP Manual
  • NoRewindIterator
  • Get the current key

NoRewindIterator::key

(PHP 5 >= 5.1.0, PHP 7)

NoRewindIterator::key — Get the current key

Description

public NoRewindIterator::key ( void ) : mixed

Gets the current key.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The current key.

See Also

  • NoRewindIterator::next() - Forward to the next element


Forward to the next element

  • « NoRewindIterator::key
  • NoRewindIterator::rewind »
  • PHP Manual
  • NoRewindIterator
  • Forward to the next element

NoRewindIterator::next

(PHP 5 >= 5.1.0, PHP 7)

NoRewindIterator::next — Forward to the next element

Description

public NoRewindIterator::next ( void ) : void

Forwards to the next element.

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.

See Also

  • NoRewindIterator::rewind() - Prevents the rewind operation on the inner iterator


Prevents the rewind operation on the inner iterator

  • « NoRewindIterator::next
  • NoRewindIterator::valid »
  • PHP Manual
  • NoRewindIterator
  • Prevents the rewind operation on the inner iterator

NoRewindIterator::rewind

(PHP 5 >= 5.1.0, PHP 7)

NoRewindIterator::rewind — Prevents the rewind operation on the inner iterator

Description

public NoRewindIterator::rewind ( void ) : void

Prevents the rewind operation on the inner iterator.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 NoRewindIterator::rewind() example

This example demonstrates that calling rewind on a NoRewindIterator object has no effect.

<?php
$fruits = array("lemon", "orange", "apple", "pear");

$noRewindIterator = new NoRewindIterator(new ArrayIterator($fruits));

echo $noRewindIterator->current() . "\n";
$noRewindIterator->next();
// now rewind the iterator (nothing should happen)
$noRewindIterator->rewind();
echo $noRewindIterator->current() . "\n";
?>

The above example will output:

lemon
orange


Validates the iterator

  • « NoRewindIterator::rewind
  • ParentIterator »
  • PHP Manual
  • NoRewindIterator
  • Validates the iterator

NoRewindIterator::valid

(PHP 5 >= 5.1.0, PHP 7)

NoRewindIterator::valid — Validates the iterator

Description

public NoRewindIterator::valid ( void ) : bool

Checks whether the iterator is valid.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • NoRewindIterator::getInnerIterator() - Get the inner iterator


The ParentIterator class

(PHP 5 >= 5.1.0, PHP 7)

Introduction

This extended FilterIterator allows a recursive iteration using RecursiveIteratorIterator that only shows those elements which have children.

Class synopsis

ParentIterator extends RecursiveFilterIterator implements RecursiveIterator , OuterIterator {
/* Methods */
public accept ( void ) : bool
public __construct ( RecursiveIterator $iterator )
public getChildren ( void ) : ParentIterator
public hasChildren ( void ) : bool
public next ( void ) : void
public rewind ( void ) : void
/* Inherited methods */
public OuterIterator::getInnerIterator ( void ) : Iterator
}

Table of Contents

  • ParentIterator::accept — Determines acceptability
  • ParentIterator::__construct — Constructs a ParentIterator
  • ParentIterator::getChildren — Return the inner iterator's children contained in a ParentIterator
  • ParentIterator::hasChildren — Check whether the inner iterator's current element has children
  • ParentIterator::next — Move the iterator forward
  • ParentIterator::rewind — Rewind the iterator


Determines acceptability

  • « ParentIterator
  • ParentIterator::__construct »
  • PHP Manual
  • ParentIterator
  • Determines acceptability

ParentIterator::accept

(PHP 5 >= 5.1.0, PHP 7)

ParentIterator::accept — Determines acceptability

Description

public ParentIterator::accept ( void ) : bool

Determines if the current element has children.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

TRUE if the current element is acceptable, otherwise FALSE.

See Also

  • ParentIterator::hasChildren() - Check whether the inner iterator's current element has children
  • FilterIterator::accept() - Check whether the current element of the iterator is acceptable


Constructs a ParentIterator

  • « ParentIterator::accept
  • ParentIterator::getChildren »
  • PHP Manual
  • ParentIterator
  • Constructs a ParentIterator

ParentIterator::__construct

(PHP 5 >= 5.1.0, PHP 7)

ParentIterator::__construct — Constructs a ParentIterator

Description

public ParentIterator::__construct ( RecursiveIterator $iterator )

Constructs a ParentIterator on an iterator.

Warning

This function is currently not documented; only its argument list is available.

Parameters

iterator

The iterator being constructed upon.

Return Values

The ParentIterator.


Return the inner iterator's children contained in a ParentIterator

  • « ParentIterator::__construct
  • ParentIterator::hasChildren »
  • PHP Manual
  • ParentIterator
  • Return the inner iterator's children contained in a ParentIterator

ParentIterator::getChildren

(PHP 5 >= 5.1.0, PHP 7)

ParentIterator::getChildren — Return the inner iterator's children contained in a ParentIterator

Description

public ParentIterator::getChildren ( void ) : ParentIterator

Get the inner iterator's children contained in a ParentIterator.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

An object.


Check whether the inner iterator's current element has children

  • « ParentIterator::getChildren
  • ParentIterator::next »
  • PHP Manual
  • ParentIterator
  • Check whether the inner iterator's current element has children

ParentIterator::hasChildren

(PHP 5 >= 5.1.0, PHP 7)

ParentIterator::hasChildren — Check whether the inner iterator's current element has children

Description

public ParentIterator::hasChildren ( void ) : bool

Check whether the inner iterator's current element has children.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.


Move the iterator forward

  • « ParentIterator::hasChildren
  • ParentIterator::rewind »
  • PHP Manual
  • ParentIterator
  • Move the iterator forward

ParentIterator::next

(PHP 5 >= 5.1.0, PHP 7)

ParentIterator::next — Move the iterator forward

Description

public ParentIterator::next ( void ) : void

Moves the iterator forward.

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.


Rewind the iterator

  • « ParentIterator::next
  • RecursiveArrayIterator »
  • PHP Manual
  • ParentIterator
  • Rewind the iterator

ParentIterator::rewind

(PHP 5 >= 5.1.0, PHP 7)

ParentIterator::rewind — Rewind the iterator

Description

public ParentIterator::rewind ( void ) : void

Rewinds the iterator.

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.


The RecursiveArrayIterator class

(PHP 5 >= 5.1.0, PHP 7)

Introduction

This iterator allows to unset and modify values and keys while iterating over Arrays and Objects in the same way as the ArrayIterator. Additionally it is possible to iterate over the current iterator entry.

Class synopsis

RecursiveArrayIterator extends ArrayIterator implements RecursiveIterator {
/* Inherited constants */
const integer STD_PROP_LIST = 1 ;
const integer ARRAY_AS_PROPS = 2 ;
/* Constants */
const integer CHILD_ARRAYS_ONLY = 4 ;
/* Methods */
public getChildren ( void ) : RecursiveArrayIterator
public hasChildren ( void ) : bool
/* Inherits */
public ArrayIterator::append ( mixed $value ) : void
public ArrayIterator::asort ( void ) : void
public ArrayIterator::__construct ([ mixed $array = array() [, int $flags = 0 ]] )
public ArrayIterator::count ( void ) : int
public ArrayIterator::current ( void ) : mixed
public ArrayIterator::getArrayCopy ( void ) : array
public ArrayIterator::getFlags ( void ) : int
public ArrayIterator::key ( void ) : mixed
public ArrayIterator::ksort ( void ) : void
public ArrayIterator::natcasesort ( void ) : void
public ArrayIterator::natsort ( void ) : void
public ArrayIterator::next ( void ) : void
public ArrayIterator::offsetExists ( mixed $index ) : bool
public ArrayIterator::offsetGet ( mixed $index ) : mixed
public ArrayIterator::offsetSet ( mixed $index , mixed $newval ) : void
public ArrayIterator::offsetUnset ( mixed $index ) : void
public ArrayIterator::rewind ( void ) : void
public ArrayIterator::seek ( int $position ) : void
public ArrayIterator::serialize ( void ) : string
public ArrayIterator::setFlags ( string $flags ) : void
public ArrayIterator::uasort ( callable $cmp_function ) : void
public ArrayIterator::uksort ( callable $cmp_function ) : void
public ArrayIterator::unserialize ( string $serialized ) : void
public ArrayIterator::valid ( void ) : bool
}

Predefined Constants

RecursiveArrayIterator Flags

RecursiveArrayIterator::CHILD_ARRAYS_ONLY

Treat only arrays (not objects) as having children for recursive iteration.

Changelog

Version | Description
5.3.0 | CHILD_ARRAYS_ONLY flag was added.

Table of Contents

  • RecursiveArrayIterator::getChildren — Returns an iterator for the current entry if it is an array or an object
  • RecursiveArrayIterator::hasChildren — Returns whether current entry is an array or an object


Returns an iterator for the current entry if it is an array or an object

  • « RecursiveArrayIterator
  • RecursiveArrayIterator::hasChildren »
  • PHP Manual
  • RecursiveArrayIterator
  • Returns an iterator for the current entry if it is an array or an object

RecursiveArrayIterator::getChildren

(PHP 5 >= 5.1.0, PHP 7)

RecursiveArrayIterator::getChildren — Returns an iterator for the current entry if it is an array or an object

Description

public RecursiveArrayIterator::getChildren ( void ) : RecursiveArrayIterator

Returns an iterator for the current iterator entry.

Parameters

This function has no parameters.

Return Values

An iterator for the current entry, if it is an array or object.

Errors/Exceptions

An InvalidArgumentException will be thrown if the current entry does not contain an array or an object.

Examples

Example #1 RecursiveArrayIterator::getChildren() example

<?php
$fruits = array("a" => "lemon", "b" => "orange", array("a" => "apple", "p" => "pear"));

$iterator = new RecursiveArrayIterator($fruits);

while ($iterator->valid()) {

    if ($iterator->hasChildren()) {
        // print all children
        foreach ($iterator->getChildren() as $key => $value) {
            echo $key . ' : ' . $value . "\n";
        }
    } else {
        echo "No children.\n";
    }

    $iterator->next();
}
?>

The above example will output:

No children.
No children.
a : apple
p : pear

See Also

  • RecursiveArrayIterator::hasChildren() - Returns whether current entry is an array or an object


Returns whether current entry is an array or an object

  • « RecursiveArrayIterator::getChildren
  • RecursiveCachingIterator »
  • PHP Manual
  • RecursiveArrayIterator
  • Returns whether current entry is an array or an object

RecursiveArrayIterator::hasChildren

(PHP 5 >= 5.1.0, PHP 7)

RecursiveArrayIterator::hasChildren — Returns whether current entry is an array or an object

Description

public RecursiveArrayIterator::hasChildren ( void ) : bool

Returns whether current entry is an array or an object for which an iterator can be obtained via RecursiveArrayIterator::getChildren().

Parameters

This function has no parameters.

Return Values

Returns TRUE if the current entry is an array or an object, otherwise FALSE is returned.

Examples

Example #1 RecursiveArrayIterator::hasChildren() example

<?php
$fruits = array("a" => "lemon", "b" => "orange", array("a" => "apple", "p" => "pear"));

$iterator = new RecursiveArrayIterator($fruits);

while ($iterator->valid()) {

    // Check if there are children
    if ($iterator->hasChildren()) {
        // print all children
        foreach ($iterator->getChildren() as $key => $value) {
            echo $key . ' : ' . $value . "\n";
        }
    } else {
        echo "No children.\n";
    }

    $iterator->next();
}
?>

The above example will output:

No children.
No children.
a : apple
p : pear

See Also

  • RecursiveArrayIterator::getChildren() - Returns an iterator for the current entry if it is an array or an object


The RecursiveCachingIterator class

(PHP 5 >= 5.1.0, PHP 7)

Introduction

...

Class synopsis

RecursiveCachingIterator extends CachingIterator implements Countable , ArrayAccess , OuterIterator , RecursiveIterator {
/* Inherited constants */
const integer CachingIterator::CALL_TOSTRING = 1 ;
const integer CachingIterator::CATCH_GET_CHILD = 16 ;
const integer CachingIterator::TOSTRING_USE_KEY = 2 ;
const integer CachingIterator::TOSTRING_USE_CURRENT = 4 ;
const integer CachingIterator::TOSTRING_USE_INNER = 8 ;
const integer CachingIterator::FULL_CACHE = 256 ;
/* Methods */
public __construct ( Iterator $iterator [, int $flags = self::CALL_TOSTRING ] )
public getChildren ( void ) : RecursiveCachingIterator
public hasChildren ( void ) : bool
/* Inherits */
public CachingIterator::__construct ( Iterator $iterator [, int $flags = self::CALL_TOSTRING ] )
public CachingIterator::count ( void ) : int
public CachingIterator::current ( void ) : mixed
public CachingIterator::getCache ( void ) : array
public CachingIterator::getFlags ( void ) : int
public CachingIterator::getInnerIterator ( void ) : Iterator
public CachingIterator::hasNext ( void ) : void
public CachingIterator::key ( void ) : scalar
public CachingIterator::next ( void ) : void
public CachingIterator::offsetExists ( mixed $index ) : void
public CachingIterator::offsetGet ( string $index ) : void
public CachingIterator::offsetSet ( mixed $index , mixed $newval ) : void
public CachingIterator::offsetUnset ( string $index ) : void
public CachingIterator::rewind ( void ) : void
public CachingIterator::setFlags ( int $flags ) : void
public CachingIterator::__toString ( void ) : void
public CachingIterator::valid ( void ) : void
}

Table of Contents

  • RecursiveCachingIterator::__construct — Construct
  • RecursiveCachingIterator::getChildren — Return the inner iterator's children as a RecursiveCachingIterator
  • RecursiveCachingIterator::hasChildren — Check whether the current element of the inner iterator has children


Construct

  • « RecursiveCachingIterator
  • RecursiveCachingIterator::getChildren »
  • PHP Manual
  • RecursiveCachingIterator
  • Construct

RecursiveCachingIterator::__construct

(PHP 5 >= 5.1.0, PHP 7)

RecursiveCachingIterator::__construct — Construct

Description

public RecursiveCachingIterator::__construct ( Iterator $iterator [, int $flags = self::CALL_TOSTRING ] )

Constructs a new RecursiveCachingIterator, which consists of a passed in iterator.

Warning

This function is currently not documented; only its argument list is available.

Parameters

iterator

The iterator being used.

flags

The flags. Use CALL_TOSTRING to call RecursiveCachingIterator::__toString() for every element (the default), and/or CATCH_GET_CHILD to catch exceptions when trying to get children.

Return Values

The RecursiveCachingIterator.

See Also

  • CachingIterator::__construct() - Construct a new CachingIterator object for the iterator


Return the inner iterator's children as a RecursiveCachingIterator

  • « RecursiveCachingIterator::__construct
  • RecursiveCachingIterator::hasChildren »
  • PHP Manual
  • RecursiveCachingIterator
  • Return the inner iterator's children as a RecursiveCachingIterator

RecursiveCachingIterator::getChildren

(PHP 5 >= 5.1.0, PHP 7)

RecursiveCachingIterator::getChildren — Return the inner iterator's children as a RecursiveCachingIterator

Description

public RecursiveCachingIterator::getChildren ( void ) : RecursiveCachingIterator
Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The inner iterator's children, as a RecursiveCachingIterator.


Check whether the current element of the inner iterator has children

  • « RecursiveCachingIterator::getChildren
  • RecursiveCallbackFilterIterator »
  • PHP Manual
  • RecursiveCachingIterator
  • Check whether the current element of the inner iterator has children

RecursiveCachingIterator::hasChildren

(PHP 5 >= 5.1.0, PHP 7)

RecursiveCachingIterator::hasChildren — Check whether the current element of the inner iterator has children

Description

public RecursiveCachingIterator::hasChildren ( void ) : 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 inner iterator has children, otherwise FALSE


The RecursiveCallbackFilterIterator class

(PHP 5 >= 5.4.0, PHP 7)

Introduction

Class synopsis

RecursiveCallbackFilterIterator extends CallbackFilterIterator implements OuterIterator , RecursiveIterator {
/* Methods */
public __construct ( RecursiveIterator $iterator , string $callback )
public getChildren ( void ) : RecursiveCallbackFilterIterator
public hasChildren ( void ) : bool
/* Inherited methods */
public CallbackFilterIterator::accept ( void ) : bool
}

Examples

The callback should accept up to three arguments: the current item, the current key and the iterator, respectively.

Example #1 Available callback arguments

<?php

/**
 * Callback for RecursiveCallbackFilterIterator
 *
 * @param $current   Current item's value
 * @param $key       Current item's key
 * @param $iterator  Iterator being filtered
 * @return boolean   TRUE to accept the current item, FALSE otherwise
 */
function my_callback($current, $key, $iterator) {
    // Your filtering code here
}

?>

Filtering a recursive iterator generally involves two conditions. The first is that, to allow recursion, the callback function should return TRUE if the current iterator item has children. The second is the normal filter condition, such as a file size or extension check as in the example below.

Example #2 Recursive callback basic example

<?php

$dir = new RecursiveDirectoryIterator(__DIR__);

// Filter large files ( > 100MB)
$files = new RecursiveCallbackFilterIterator($dir, function ($current, $key, $iterator) {
    // Allow recursion
    if ($iterator->hasChildren()) {
        return TRUE;
    }
    // Check for large file
    if ($current->isFile() && $current->getSize() > 104857600) {
        return TRUE;
    }
    return FALSE;
});

foreach (new RecursiveIteratorIterator($files) as $file) {
    echo $file->getPathname() . PHP_EOL;
}

?>

Table of Contents

  • RecursiveCallbackFilterIterator::__construct — Create a RecursiveCallbackFilterIterator from a RecursiveIterator
  • RecursiveCallbackFilterIterator::getChildren — Return the inner iterator's children contained in a RecursiveCallbackFilterIterator
  • RecursiveCallbackFilterIterator::hasChildren — Check whether the inner iterator's current element has children


Create a RecursiveCallbackFilterIterator from a RecursiveIterator

  • « RecursiveCallbackFilterIterator
  • RecursiveCallbackFilterIterator::getChildren »
  • PHP Manual
  • RecursiveCallbackFilterIterator
  • Create a RecursiveCallbackFilterIterator from a RecursiveIterator

RecursiveCallbackFilterIterator::__construct

(PHP 5 >= 5.4.0, PHP 7)

RecursiveCallbackFilterIterator::__construct — Create a RecursiveCallbackFilterIterator from a RecursiveIterator

Description

public RecursiveCallbackFilterIterator::__construct ( RecursiveIterator $iterator , string $callback )

Creates a filtered iterator from a RecursiveIterator using the callback to determine which items are accepted or rejected.

Parameters

iterator

The recursive iterator to be filtered.

callback

The callback, which should return TRUE to accept the current item or FALSE otherwise. See Examples.

May be any valid callable value.

Return Values

No value is returned.

See Also

  • RecursiveCallbackFilterIterator Examples
  • RecursiveCallbackFilterIterator::getChildren() - Return the inner iterator's children contained in a RecursiveCallbackFilterIterator
  • RecursiveCallbackFilteriterator::hasChildren() - Check whether the inner iterator's current element has children


Return the inner iterator's children contained in a RecursiveCallbackFilterIterator

  • « RecursiveCallbackFilterIterator::__construct
  • RecursiveCallbackFilterIterator::hasChildren »
  • PHP Manual
  • RecursiveCallbackFilterIterator
  • Return the inner iterator's children contained in a RecursiveCallbackFilterIterator

RecursiveCallbackFilterIterator::getChildren

(PHP 5 >= 5.4.0, PHP 7)

RecursiveCallbackFilterIterator::getChildren — Return the inner iterator's children contained in a RecursiveCallbackFilterIterator

Description

public RecursiveCallbackFilterIterator::getChildren ( void ) : RecursiveCallbackFilterIterator

Fetches the filtered children of the inner iterator.

RecursiveCallbackFilterIterator::hasChildren() should be used to determine if there are children to be fetched.

Parameters

This function has no parameters.

Return Values

Returns a RecursiveCallbackFilterIterator containing the children.

See Also

  • RecursiveCallbackFilterIterator Examples
  • RecursiveCallbackFilterIterator::__construct() - Create a RecursiveCallbackFilterIterator from a RecursiveIterator
  • RecursiveCallbackFilteriterator::hasChildren() - Check whether the inner iterator's current element has children


Check whether the inner iterator's current element has children

  • « RecursiveCallbackFilterIterator::getChildren
  • RecursiveDirectoryIterator »
  • PHP Manual
  • RecursiveCallbackFilterIterator
  • Check whether the inner iterator's current element has children

RecursiveCallbackFilterIterator::hasChildren

(PHP 5 >= 5.4.0, PHP 7)

RecursiveCallbackFilterIterator::hasChildren — Check whether the inner iterator's current element has children

Description

public RecursiveCallbackFilterIterator::hasChildren ( void ) : bool

Returns TRUE if the current element has children, FALSE otherwise.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the current element has children, FALSE otherwise.

Examples

Example #1 RecursiveCallbackFilterIterator::hasChildren() basic usage

<?php

$dir = new RecursiveDirectoryIterator(__DIR__);

// Recursively iterate over XML files
$files = new RecursiveCallbackFilterIterator($dir, function ($current, $key, $iterator) {
    // Allow recursion into directories
    if ($iterator->hasChildren()) {
        return TRUE;
    }
    // Check for XML file
    if (!strcasecmp($current->getExtension(), 'xml')) {
        return TRUE;
    }
    return FALSE;
});

?>

See Also

  • RecursiveCallbackFilterIterator Examples
  • RecursiveCallbackFilterIterator::__construct() - Create a RecursiveCallbackFilterIterator from a RecursiveIterator
  • RecursiveCallbackFilteriterator::getChildren() - Return the inner iterator's children contained in a RecursiveCallbackFilterIterator


The RecursiveDirectoryIterator class

(PHP 5, PHP 7)

Introduction

The RecursiveDirectoryIterator provides an interface for iterating recursively over filesystem directories.

Class synopsis

RecursiveDirectoryIterator extends FilesystemIterator implements SeekableIterator , RecursiveIterator {
/* Inherited constants */
const integer FilesystemIterator::CURRENT_AS_PATHNAME = 32 ;
const integer FilesystemIterator::CURRENT_AS_FILEINFO = 0 ;
const integer FilesystemIterator::CURRENT_AS_SELF = 16 ;
const integer FilesystemIterator::CURRENT_MODE_MASK = 240 ;
const integer FilesystemIterator::KEY_AS_PATHNAME = 0 ;
const integer FilesystemIterator::KEY_AS_FILENAME = 256 ;
const integer FilesystemIterator::FOLLOW_SYMLINKS = 512 ;
const integer FilesystemIterator::KEY_MODE_MASK = 3840 ;
const integer FilesystemIterator::NEW_CURRENT_AND_KEY = 256 ;
const integer FilesystemIterator::SKIP_DOTS = 4096 ;
const integer FilesystemIterator::UNIX_PATHS = 8192 ;
/* Methods */
public __construct ( string $path [, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO ] )
public getChildren ( void ) : mixed
public getSubPath ( void ) : string
public getSubPathname ( void ) : string
public hasChildren ([ bool $allow_links = FALSE ] ) : bool
public key ( void ) : string
public next ( void ) : void
public rewind ( void ) : void
/* Inherits */
public FilesystemIterator::__construct ( string $path [, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS ] )
public FilesystemIterator::current ( void ) : mixed
public FilesystemIterator::getFlags ( void ) : int
public FilesystemIterator::key ( void ) : string
public FilesystemIterator::next ( void ) : void
public FilesystemIterator::rewind ( void ) : void
public FilesystemIterator::setFlags ([ int $flags ] ) : void
}

Changelog

Version | Description
5.3.0 | The FilesystemIterator was introduced as the parent class. Previously, the parent was the DirectoryIterator.
5.3.0 | Implements SeekableIterator.
5.2.11, 5.3.1 | Added RecursiveDirectoryIterator::FOLLOW_SYMLINKS

Table of Contents

  • RecursiveDirectoryIterator::__construct — Constructs a RecursiveDirectoryIterator
  • RecursiveDirectoryIterator::getChildren — Returns an iterator for the current entry if it is a directory
  • RecursiveDirectoryIterator::getSubPath — Get sub path
  • RecursiveDirectoryIterator::getSubPathname — Get sub path and name
  • RecursiveDirectoryIterator::hasChildren — Returns whether current entry is a directory and not '.' or '..'
  • RecursiveDirectoryIterator::key — Return path and filename of current dir entry
  • RecursiveDirectoryIterator::next — Move to next entry
  • RecursiveDirectoryIterator::rewind — Rewind dir back to the start


Constructs a RecursiveDirectoryIterator

  • « RecursiveDirectoryIterator
  • RecursiveDirectoryIterator::getChildren »
  • PHP Manual
  • RecursiveDirectoryIterator
  • Constructs a RecursiveDirectoryIterator

RecursiveDirectoryIterator::__construct

(PHP 5 >= 5.1.2, PHP 7)

RecursiveDirectoryIterator::__construct — Constructs a RecursiveDirectoryIterator

Description

public RecursiveDirectoryIterator::__construct ( string $path [, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO ] )

Constructs a RecursiveDirectoryIterator() for the provided path.

Parameters

path

The path of the directory to be iterated over.

flags

Flags may be provided which will affect the behavior of some methods. A list of the flags can found under FilesystemIterator predefined constants. They can also be set later with FilesystemIterator::setFlags().

Return Values

Returns the newly created RecursiveDirectoryIterator.

Errors/Exceptions

Throws an UnexpectedValueException if the path cannot be found or is not a directory.

Examples

Example #1 RecursiveDirectoryIterator example

<?php

$directory = '/tmp';

$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));

$it->rewind();
while($it->valid()) {

    if (!$it->isDot()) {
        echo 'SubPathName: ' . $it->getSubPathName() . "\n";
        echo 'SubPath:     ' . $it->getSubPath() . "\n";
        echo 'Key:         ' . $it->key() . "\n\n";
    }

    $it->next();
}

?>

The above example will output something similar to:

SubPathName: fruit/apple.xml
SubPath:     fruit
Key:         /tmp/fruit/apple.xml

SubPathName: stuff.xml
SubPath:
Key:         /tmp/stuff.xml

SubPathName: veggies/carrot.xml
SubPath:     veggies
Key:         /tmp/veggies/carrot.xml

See Also

  • FilesystemIterator::__construct() - Constructs a new filesystem iterator
  • RecursiveIteratorIterator::__construct() - Construct a RecursiveIteratorIterator
  • FilesystemIterator predefined constants


Returns an iterator for the current entry if it is a directory

  • « RecursiveDirectoryIterator::__construct
  • RecursiveDirectoryIterator::getSubPath »
  • PHP Manual
  • RecursiveDirectoryIterator
  • Returns an iterator for the current entry if it is a directory

RecursiveDirectoryIterator::getChildren

(PHP 5 >= 5.1.0, PHP 7)

RecursiveDirectoryIterator::getChildren — Returns an iterator for the current entry if it is a directory

Description

public RecursiveDirectoryIterator::getChildren ( void ) : mixed
Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The filename, file information, or $this depending on the set flags. See the FilesystemIterator constants.


Get sub path

  • « RecursiveDirectoryIterator::getChildren
  • RecursiveDirectoryIterator::getSubPathname »
  • PHP Manual
  • RecursiveDirectoryIterator
  • Get sub path

RecursiveDirectoryIterator::getSubPath

(PHP 5 >= 5.1.0, PHP 7)

RecursiveDirectoryIterator::getSubPath — Get sub path

Description

public RecursiveDirectoryIterator::getSubPath ( void ) : string

Returns the sub path relative to the directory given in the constructor.

Parameters

This function has no parameters.

Return Values

The sub path.

Examples

Example #1 getSubPath() example

$directory = '/tmp';

      $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));

      foreach ($it as $file) {
          echo 'SubPathName: ' . $it->getSubPathName() . "\n";
          echo 'SubPath:     ' . $it->getSubPath() . "\n\n";
      }

The above example will output something similar to:

     SubPathName: fruit/apple.xml
     SubPath:     fruit

     SubPathName: stuff.xml
     SubPath:

     SubPathName: veggies/carrot.xml
     SubPath:     veggies

See Also

  • RecursiveDirectoryIterator::getSubPathName() - Get sub path and name
  • RecursiveDirectoryIterator::key() - Return path and filename of current dir entry


Get sub path and name

  • « RecursiveDirectoryIterator::getSubPath
  • RecursiveDirectoryIterator::hasChildren »
  • PHP Manual
  • RecursiveDirectoryIterator
  • Get sub path and name

RecursiveDirectoryIterator::getSubPathname

(PHP 5 >= 5.1.0, PHP 7)

RecursiveDirectoryIterator::getSubPathname — Get sub path and name

Description

public RecursiveDirectoryIterator::getSubPathname ( void ) : string

Gets the sub path and filename.

Parameters

This function has no parameters.

Return Values

The sub path (sub directory) and filename.

Examples

Example #1 getSubPathname() example

$directory = '/tmp';

      $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));

      foreach ($it as $file) {
          echo 'SubPathName: ' . $it->getSubPathName() . "\n";
          echo 'SubPath:     ' . $it->getSubPath() . "\n\n";
      }

The above example will output something similar to:

     SubPathName: fruit/apple.xml
     SubPath:     fruit

     SubPathName: stuff.xml
     SubPath:

     SubPathName: veggies/carrot.xml
     SubPath:     veggies

See Also

  • RecursiveDirectoryIterator::getSubPath() - Get sub path
  • RecursiveDirectoryIterator::key() - Return path and filename of current dir entry


Returns whether current entry is a directory and not '.' or '..'

  • « RecursiveDirectoryIterator::getSubPathname
  • RecursiveDirectoryIterator::key »
  • PHP Manual
  • RecursiveDirectoryIterator
  • Returns whether current entry is a directory and not '.' or '..'

RecursiveDirectoryIterator::hasChildren

(PHP 5, PHP 7)

RecursiveDirectoryIterator::hasChildren — Returns whether current entry is a directory and not '.' or '..'

Description

public RecursiveDirectoryIterator::hasChildren ([ bool $allow_links = FALSE ] ) : bool
Warning

This function is currently not documented; only its argument list is available.

Parameters

allow_links

Return Values

Returns whether the current entry is a directory, but not '.' or '..'


Return path and filename of current dir entry

  • « RecursiveDirectoryIterator::hasChildren
  • RecursiveDirectoryIterator::next »
  • PHP Manual
  • RecursiveDirectoryIterator
  • Return path and filename of current dir entry

RecursiveDirectoryIterator::key

(PHP 5, PHP 7)

RecursiveDirectoryIterator::key — Return path and filename of current dir entry

Description

public RecursiveDirectoryIterator::key ( void ) : string
Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The path and filename of the current dir entry.


Move to next entry

  • « RecursiveDirectoryIterator::key
  • RecursiveDirectoryIterator::rewind »
  • PHP Manual
  • RecursiveDirectoryIterator
  • Move to next entry

RecursiveDirectoryIterator::next

(PHP 5, PHP 7)

RecursiveDirectoryIterator::next — Move to next entry

Description

public RecursiveDirectoryIterator::next ( void ) : 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.


Rewind dir back to the start

  • « RecursiveDirectoryIterator::next
  • RecursiveFilterIterator »
  • PHP Manual
  • RecursiveDirectoryIterator
  • Rewind dir back to the start

RecursiveDirectoryIterator::rewind

(PHP 5, PHP 7)

RecursiveDirectoryIterator::rewind — Rewind dir back to the start

Description

public RecursiveDirectoryIterator::rewind ( void ) : 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.


The RecursiveFilterIterator class

(PHP 5 >= 5.1.0, PHP 7)

Introduction

This abstract iterator filters out unwanted values for a RecursiveIterator. This class should be extended to implement custom filters. The RecursiveFilterIterator::accept() must be implemented in the subclass.

Class synopsis

abstract RecursiveFilterIterator extends FilterIterator implements OuterIterator , RecursiveIterator {
/* Methods */
public __construct ( RecursiveIterator $iterator )
public getChildren ( void ) : RecursiveFilterIterator
public hasChildren ( void ) : bool
/* Inherited methods */
public abstract FilterIterator::accept ( void ) : bool
public FilterIterator::__construct ( Iterator $iterator )
public FilterIterator::current ( void ) : mixed
public FilterIterator::getInnerIterator ( void ) : Iterator
public FilterIterator::key ( void ) : mixed
public FilterIterator::next ( void ) : void
public FilterIterator::rewind ( void ) : void
public FilterIterator::valid ( void ) : bool
}

Table of Contents

  • RecursiveFilterIterator::__construct — Create a RecursiveFilterIterator from a RecursiveIterator
  • RecursiveFilterIterator::getChildren — Return the inner iterator's children contained in a RecursiveFilterIterator
  • RecursiveFilterIterator::hasChildren — Check whether the inner iterator's current element has children


Create a RecursiveFilterIterator from a RecursiveIterator

  • « RecursiveFilterIterator
  • RecursiveFilterIterator::getChildren »
  • PHP Manual
  • RecursiveFilterIterator
  • Create a RecursiveFilterIterator from a RecursiveIterator

RecursiveFilterIterator::__construct

(PHP 5 >= 5.1.0, PHP 7)

RecursiveFilterIterator::__construct — Create a RecursiveFilterIterator from a RecursiveIterator

Description

public RecursiveFilterIterator::__construct ( RecursiveIterator $iterator )

Create a RecursiveFilterIterator from a RecursiveIterator.

Parameters

iterator

The RecursiveIterator to be filtered.

Return Values

No value is returned.

Examples

Example #1 Basic RecursiveFilterIterator() example

<?php
class TestsOnlyFilter extends RecursiveFilterIterator {
    public function accept() {
        // Accept the current item if we can recurse into it
        // or it is a value starting with "test"
        return $this->hasChildren() || (strpos($this->current(), "test") !== FALSE);
    }
}

$array    = array("test1", array("taste2", "test3", "test4"), "test5");
$iterator = new RecursiveArrayIterator($array);
$filter   = new TestsOnlyFilter($iterator);

foreach(new RecursiveIteratorIterator($filter) as $key => $value)
{
    echo $value . "\n";
}
?>

The above example will output something similar to:

test1
test3
test4
test5

Example #2 RecursiveFilterIterator() example

<?php
class StartsWithFilter extends RecursiveFilterIterator {

    protected $word;

    public function __construct(RecursiveIterator $rit, $word) {
        $this->word = $word;
        parent::__construct($rit);
    }

    public function accept() {
        return $this->hasChildren() OR strpos($this->current(), $this->word) === 0;
    }

    public function getChildren() {
        return new self($this->getInnerIterator()->getChildren(), $this->word);
    }
}

$array    = array("test1", array("taste2", "test3", "test4"), "test5");
$iterator = new RecursiveArrayIterator($array);
$filter   = new StartsWithFilter($iterator, "test");

foreach(new RecursiveIteratorIterator($filter) as $key => $value)
{
    echo $value . "\n";
}
?>

The above example will output something similar to:

test1
test3
test4
test5

See Also

  • RecursiveFilterIterator::getChildren() - Return the inner iterator's children contained in a RecursiveFilterIterator
  • RecursiveFilterIterator::hasChildren() - Check whether the inner iterator's current element has children
  • FilterIterator::accept() - Check whether the current element of the iterator is acceptable


Return the inner iterator's children contained in a RecursiveFilterIterator

  • « RecursiveFilterIterator::__construct
  • RecursiveFilterIterator::hasChildren »
  • PHP Manual
  • RecursiveFilterIterator
  • Return the inner iterator's children contained in a RecursiveFilterIterator

RecursiveFilterIterator::getChildren

(PHP 5 >= 5.1.0, PHP 7)

RecursiveFilterIterator::getChildren — Return the inner iterator's children contained in a RecursiveFilterIterator

Description

public RecursiveFilterIterator::getChildren ( void ) : RecursiveFilterIterator

Return the inner iterator's children contained in a RecursiveFilterIterator.

Parameters

This function has no parameters.

Return Values

Returns a RecursiveFilterIterator containing the inner iterator's children.

See Also

  • RecursiveFilterIterator::hasChildren() - Check whether the inner iterator's current element has children
  • RecursiveIterator::getChildren() - Returns an iterator for the current entry


Check whether the inner iterator's current element has children

  • « RecursiveFilterIterator::getChildren
  • RecursiveIteratorIterator »
  • PHP Manual
  • RecursiveFilterIterator
  • Check whether the inner iterator's current element has children

RecursiveFilterIterator::hasChildren

(PHP 5 >= 5.1.0, PHP 7)

RecursiveFilterIterator::hasChildren — Check whether the inner iterator's current element has children

Description

public RecursiveFilterIterator::hasChildren ( void ) : bool

Check whether the inner iterator's current element has children.

Parameters

This function has no parameters.

Return Values

TRUE if the inner iterator has children, otherwise FALSE

See Also

  • RecursiveFilterIterator::getChildren() - Return the inner iterator's children contained in a RecursiveFilterIterator
  • RecursiveIterator::hasChildren() - Returns if an iterator can be created for the current entry


The RecursiveIteratorIterator class

(PHP 5, PHP 7)

Introduction

Can be used to iterate through recursive iterators.

Class synopsis

RecursiveIteratorIterator implements OuterIterator {
/* Constants */
const integer LEAVES_ONLY = 0 ;
const integer SELF_FIRST = 1 ;
const integer CHILD_FIRST = 2 ;
const integer CATCH_GET_CHILD = 16 ;
/* Methods */
public beginChildren ( void ) : void
public beginIteration ( void ) : void
public callGetChildren ( void ) : RecursiveIterator
public callHasChildren ( void ) : bool
public __construct ( Traversable $iterator [, int $mode = RecursiveIteratorIterator::LEAVES_ONLY [, int $flags = 0 ]] )
public current ( void ) : mixed
public endChildren ( void ) : void
public endIteration ( void ) : void
public getDepth ( void ) : int
public getInnerIterator ( void ) : iterator
public getMaxDepth ( void ) : mixed
public getSubIterator ([ int $level ] ) : RecursiveIterator
public key ( void ) : mixed
public next ( void ) : void
public nextElement ( void ) : void
public rewind ( void ) : void
public setMaxDepth ([ int $max_depth = -1 ] ) : void
public valid ( void ) : bool
/* Inherited methods */
public OuterIterator::getInnerIterator ( void ) : Iterator
}

Predefined Constants

RecursiveIteratorIterator::LEAVES_ONLY

RecursiveIteratorIterator::SELF_FIRST

RecursiveIteratorIterator::CHILD_FIRST

RecursiveIteratorIterator::CATCH_GET_CHILD

Table of Contents

  • RecursiveIteratorIterator::beginChildren — Begin children
  • RecursiveIteratorIterator::beginIteration — Begin Iteration
  • RecursiveIteratorIterator::callGetChildren — Get children
  • RecursiveIteratorIterator::callHasChildren — Has children
  • RecursiveIteratorIterator::__construct — Construct a RecursiveIteratorIterator
  • RecursiveIteratorIterator::current — Access the current element value
  • RecursiveIteratorIterator::endChildren — End children
  • RecursiveIteratorIterator::endIteration — End Iteration
  • RecursiveIteratorIterator::getDepth — Get the current depth of the recursive iteration
  • RecursiveIteratorIterator::getInnerIterator — Get inner iterator
  • RecursiveIteratorIterator::getMaxDepth — Get max depth
  • RecursiveIteratorIterator::getSubIterator — The current active sub iterator
  • RecursiveIteratorIterator::key — Access the current key
  • RecursiveIteratorIterator::next — Move forward to the next element
  • RecursiveIteratorIterator::nextElement — Next element
  • RecursiveIteratorIterator::rewind — Rewind the iterator to the first element of the top level inner iterator
  • RecursiveIteratorIterator::setMaxDepth — Set max depth
  • RecursiveIteratorIterator::valid — Check whether the current position is valid


Begin children

  • « RecursiveIteratorIterator
  • RecursiveIteratorIterator::beginIteration »
  • PHP Manual
  • RecursiveIteratorIterator
  • Begin children

RecursiveIteratorIterator::beginChildren

(PHP 5 >= 5.1.0, PHP 7)

RecursiveIteratorIterator::beginChildren — Begin children

Description

public RecursiveIteratorIterator::beginChildren ( void ) : void

Is called after calling RecursiveIteratorIterator::getChildren(), and its associated RecursiveIteratorIterator::rewind().

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.


Begin Iteration

  • « RecursiveIteratorIterator::beginChildren
  • RecursiveIteratorIterator::callGetChildren »
  • PHP Manual
  • RecursiveIteratorIterator
  • Begin Iteration

RecursiveIteratorIterator::beginIteration

(PHP 5 >= 5.1.0, PHP 7)

RecursiveIteratorIterator::beginIteration — Begin Iteration

Description

public RecursiveIteratorIterator::beginIteration ( void ) : void

Called when iteration begins (after the first RecursiveIteratorIterator::rewind() call.

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.


Get children

  • « RecursiveIteratorIterator::beginIteration
  • RecursiveIteratorIterator::callHasChildren »
  • PHP Manual
  • RecursiveIteratorIterator
  • Get children

RecursiveIteratorIterator::callGetChildren

(PHP 5 >= 5.1.0, PHP 7)

RecursiveIteratorIterator::callGetChildren — Get children

Description

public RecursiveIteratorIterator::callGetChildren ( void ) : RecursiveIterator

Get children of the current element.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

A RecursiveIterator().


Has children

  • « RecursiveIteratorIterator::callGetChildren
  • RecursiveIteratorIterator::__construct »
  • PHP Manual
  • RecursiveIteratorIterator
  • Has children

RecursiveIteratorIterator::callHasChildren

(PHP 5 >= 5.1.0, PHP 7)

RecursiveIteratorIterator::callHasChildren — Has children

Description

public RecursiveIteratorIterator::callHasChildren ( void ) : bool

Called for each element to test whether it has children.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

TRUE if the element has children, otherwise FALSE


Construct a RecursiveIteratorIterator

  • « RecursiveIteratorIterator::callHasChildren
  • RecursiveIteratorIterator::current »
  • PHP Manual
  • RecursiveIteratorIterator
  • Construct a RecursiveIteratorIterator

RecursiveIteratorIterator::__construct

(PHP 5 >= 5.1.3, PHP 7)

RecursiveIteratorIterator::__construct — Construct a RecursiveIteratorIterator

Description

public RecursiveIteratorIterator::__construct ( Traversable $iterator [, int $mode = RecursiveIteratorIterator::LEAVES_ONLY [, int $flags = 0 ]] )

Creates a RecursiveIteratorIterator from a RecursiveIterator.

Parameters

iterator

The iterator being constructed from. Either a RecursiveIterator or IteratorAggregate.

mode

Optional mode. Possible values are

  • RecursiveIteratorIterator::LEAVES_ONLY - The default. Lists only leaves in iteration.
  • RecursiveIteratorIterator::SELF_FIRST - Lists leaves and parents in iteration with parents coming first.
  • RecursiveIteratorIterator::CHILD_FIRST - Lists leaves and parents in iteration with leaves coming first.

flags

Optional flag. Possible values are RecursiveIteratorIterator::CATCH_GET_CHILD which will then ignore exceptions thrown in calls to RecursiveIteratorIterator::getChildren().

Return Values

No value is returned.

Examples

Example #1 Iterating a RecursiveIteratorIterator

<?php
$array = array(
    array(
        array(
            array(
                'leaf-0-0-0-0',
                'leaf-0-0-0-1'
            ),
            'leaf-0-0-0'
        ),
        array(
            array(
                'leaf-0-1-0-0',
                'leaf-0-1-0-1'
            ),
            'leaf-0-1-0'
        ),
        'leaf-0-0'
    )
);

$iterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator($array),
    $mode
);
foreach ($iterator as $key => $leaf) {
    echo "$key => $leaf", PHP_EOL;
}
?>

Output with $mode = RecursiveIteratorIterator::LEAVES_ONLY

0 => leaf-0-0-0-0
1 => leaf-0-0-0-1
0 => leaf-0-0-0
0 => leaf-0-1-0-0
1 => leaf-0-1-0-1
0 => leaf-0-1-0
0 => leaf-0-0

Output with $mode = RecursiveIteratorIterator::SELF_FIRST

0 => Array
0 => Array
0 => Array
0 => leaf-0-0-0-0
1 => leaf-0-0-0-1
1 => leaf-0-0-0
1 => Array
0 => Array
0 => leaf-0-1-0-0
1 => leaf-0-1-0-1
1 => leaf-0-1-0
2 => leaf-0-0

Output with $mode = RecursiveIteratorIterator::CHILD_FIRST

0 => leaf-0-0-0-0
1 => leaf-0-0-0-1
0 => Array
1 => leaf-0-0-0
0 => Array
0 => leaf-0-1-0-0
1 => leaf-0-1-0-1
0 => Array
1 => leaf-0-1-0
1 => Array
2 => leaf-0-0
0 => Array


Access the current element value

  • « RecursiveIteratorIterator::__construct
  • RecursiveIteratorIterator::endChildren »
  • PHP Manual
  • RecursiveIteratorIterator
  • Access the current element value

RecursiveIteratorIterator::current

(PHP 5, PHP 7)

RecursiveIteratorIterator::current — Access the current element value

Description

public RecursiveIteratorIterator::current ( void ) : mixed
Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The current elements value.


End children

  • « RecursiveIteratorIterator::current
  • RecursiveIteratorIterator::endIteration »
  • PHP Manual
  • RecursiveIteratorIterator
  • End children

RecursiveIteratorIterator::endChildren

(PHP 5 >= 5.1.0, PHP 7)

RecursiveIteratorIterator::endChildren — End children

Description

public RecursiveIteratorIterator::endChildren ( void ) : void

Called when end recursing one level.

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.


End Iteration

  • « RecursiveIteratorIterator::endChildren
  • RecursiveIteratorIterator::getDepth »
  • PHP Manual
  • RecursiveIteratorIterator
  • End Iteration

RecursiveIteratorIterator::endIteration

(PHP 5 >= 5.1.0, PHP 7)

RecursiveIteratorIterator::endIteration — End Iteration

Description

public RecursiveIteratorIterator::endIteration ( void ) : void

Called when the iteration ends (when RecursiveIteratorIterator::valid() first returns FALSE.

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.


Get the current depth of the recursive iteration

  • « RecursiveIteratorIterator::endIteration
  • RecursiveIteratorIterator::getInnerIterator »
  • PHP Manual
  • RecursiveIteratorIterator
  • Get the current depth of the recursive iteration

RecursiveIteratorIterator::getDepth

(PHP 5, PHP 7)

RecursiveIteratorIterator::getDepth — Get the current depth of the recursive iteration

Description

public RecursiveIteratorIterator::getDepth ( void ) : int
Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The current depth of the recursive iteration.


Get inner iterator

  • « RecursiveIteratorIterator::getDepth
  • RecursiveIteratorIterator::getMaxDepth »
  • PHP Manual
  • RecursiveIteratorIterator
  • Get inner iterator

RecursiveIteratorIterator::getInnerIterator

(PHP 5 >= 5.1.0, PHP 7)

RecursiveIteratorIterator::getInnerIterator — Get inner iterator

Description

public RecursiveIteratorIterator::getInnerIterator ( void ) : iterator

Gets the current active sub iterator.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The current active sub iterator.


Get max depth

  • « RecursiveIteratorIterator::getInnerIterator
  • RecursiveIteratorIterator::getSubIterator »
  • PHP Manual
  • RecursiveIteratorIterator
  • Get max depth

RecursiveIteratorIterator::getMaxDepth

(PHP 5 >= 5.1.0, PHP 7)

RecursiveIteratorIterator::getMaxDepth — Get max depth

Description

public RecursiveIteratorIterator::getMaxDepth ( void ) : mixed

Gets the maximum allowable depth.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The maximum accepted depth, or FALSE if any depth is allowed.

See Also

  • RecursiveIteratorIterator::setMaxDepth() - Set max depth


The current active sub iterator

  • « RecursiveIteratorIterator::getMaxDepth
  • RecursiveIteratorIterator::key »
  • PHP Manual
  • RecursiveIteratorIterator
  • The current active sub iterator

RecursiveIteratorIterator::getSubIterator

(PHP 5, PHP 7)

RecursiveIteratorIterator::getSubIterator — The current active sub iterator

Description

public RecursiveIteratorIterator::getSubIterator ([ int $level ] ) : RecursiveIterator
Warning

This function is currently not documented; only its argument list is available.

Parameters

level

Return Values

The current active sub iterator.


Access the current key

  • « RecursiveIteratorIterator::getSubIterator
  • RecursiveIteratorIterator::next »
  • PHP Manual
  • RecursiveIteratorIterator
  • Access the current key

RecursiveIteratorIterator::key

(PHP 5, PHP 7)

RecursiveIteratorIterator::key — Access the current key

Description

public RecursiveIteratorIterator::key ( void ) : mixed
Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The current key.


Move forward to the next element

  • « RecursiveIteratorIterator::key
  • RecursiveIteratorIterator::nextElement »
  • PHP Manual
  • RecursiveIteratorIterator
  • Move forward to the next element

RecursiveIteratorIterator::next

(PHP 5, PHP 7)

RecursiveIteratorIterator::next — Move forward to the next element

Description

public RecursiveIteratorIterator::next ( void ) : 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.


Next element

  • « RecursiveIteratorIterator::next
  • RecursiveIteratorIterator::rewind »
  • PHP Manual
  • RecursiveIteratorIterator
  • Next element

RecursiveIteratorIterator::nextElement

(PHP 5 >= 5.1.0, PHP 7)

RecursiveIteratorIterator::nextElement — Next element

Description

public RecursiveIteratorIterator::nextElement ( void ) : void

Called when the next element is available.

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.


Rewind the iterator to the first element of the top level inner iterator

  • « RecursiveIteratorIterator::nextElement
  • RecursiveIteratorIterator::setMaxDepth »
  • PHP Manual
  • RecursiveIteratorIterator
  • Rewind the iterator to the first element of the top level inner iterator

RecursiveIteratorIterator::rewind

(PHP 5, PHP 7)

RecursiveIteratorIterator::rewind — Rewind the iterator to the first element of the top level inner iterator

Description

public RecursiveIteratorIterator::rewind ( void ) : 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.


Set max depth

  • « RecursiveIteratorIterator::rewind
  • RecursiveIteratorIterator::valid »
  • PHP Manual
  • RecursiveIteratorIterator
  • Set max depth

RecursiveIteratorIterator::setMaxDepth

(PHP 5 >= 5.1.0, PHP 7)

RecursiveIteratorIterator::setMaxDepth — Set max depth

Description

public RecursiveIteratorIterator::setMaxDepth ([ int $max_depth = -1 ] ) : void

Set the maximum allowed depth.

Warning

This function is currently not documented; only its argument list is available.

Parameters

max_depth

The maximum allowed depth. -1 is used for any depth.

Return Values

No value is returned.

Errors/Exceptions

Emits an Exception if max_depth is less than -1.


Check whether the current position is valid

  • « RecursiveIteratorIterator::setMaxDepth
  • RecursiveRegexIterator »
  • PHP Manual
  • RecursiveIteratorIterator
  • Check whether the current position is valid

RecursiveIteratorIterator::valid

(PHP 5, PHP 7)

RecursiveIteratorIterator::valid — Check whether the current position is valid

Description

public RecursiveIteratorIterator::valid ( void ) : 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 current position is valid, otherwise FALSE


The RecursiveRegexIterator class

(PHP 5 >= 5.2.0, PHP 7)

Introduction

This recursive iterator can filter another recursive iterator via a regular expression.

Class synopsis

RecursiveRegexIterator extends RegexIterator implements RecursiveIterator {
/* Inherited constants */
const integer MATCH = 0 ;
const integer GET_MATCH = 1 ;
const integer ALL_MATCHES = 2 ;
const integer SPLIT = 3 ;
const integer REPLACE = 4 ;
const integer USE_KEY = 1 ;
/* Methods */
public __construct ( RecursiveIterator $iterator , string $regex [, int $mode = self::MATCH [, int $flags = 0 [, int $preg_flags = 0 ]]] )
public getChildren ( void ) : RecursiveRegexIterator
public hasChildren ( void ) : bool
/* Inherited methods */
public RecursiveIterator::getChildren ( void ) : RecursiveIterator
public RecursiveIterator::hasChildren ( void ) : bool
public RegexIterator::accept ( void ) : bool
public RegexIterator::getFlags ( void ) : int
public RegexIterator::getMode ( void ) : int
public RegexIterator::getPregFlags ( void ) : int
public RegexIterator::getRegex ( void ) : string
public RegexIterator::setFlags ( int $flags ) : void
public RegexIterator::setMode ( int $mode ) : void
public RegexIterator::setPregFlags ( int $preg_flags ) : void
}

Table of Contents

  • RecursiveRegexIterator::__construct — Creates a new RecursiveRegexIterator
  • RecursiveRegexIterator::getChildren — Returns an iterator for the current entry
  • RecursiveRegexIterator::hasChildren — Returns whether an iterator can be obtained for the current entry


Creates a new RecursiveRegexIterator

  • « RecursiveRegexIterator
  • RecursiveRegexIterator::getChildren »
  • PHP Manual
  • RecursiveRegexIterator
  • Creates a new RecursiveRegexIterator

RecursiveRegexIterator::__construct

(PHP 5 >= 5.2.0, PHP 7)

RecursiveRegexIterator::__construct — Creates a new RecursiveRegexIterator

Description

public RecursiveRegexIterator::__construct ( RecursiveIterator $iterator , string $regex [, int $mode = self::MATCH [, int $flags = 0 [, int $preg_flags = 0 ]]] )

Creates a new regular expression iterator.

Parameters

iterator

The recursive iterator to apply this regex filter to.

regex

The regular expression to match.

mode

Operation mode, see RegexIterator::setMode() for a list of modes.

flags

Special flags, see RegexIterator::setFlags() for a list of available flags.

preg_flags

The regular expression flags. These flags depend on the operation mode parameter:

RegexIterator preg_flags
operation mode | available flags
RecursiveRegexIterator::ALL_MATCHES | See preg_match_all().
RecursiveRegexIterator::GET_MATCH | See preg_match().
RecursiveRegexIterator::MATCH | See preg_match().
RecursiveRegexIterator::REPLACE | none.
RecursiveRegexIterator::SPLIT | See preg_split().

Examples

Example #1 RecursiveRegexIterator::__construct() example

Creates a new RegexIterator that filters all strings that start with 'test'.

<?php
$rArrayIterator = new RecursiveArrayIterator(array('test1', array('tet3', 'test4', 'test5')));
$rRegexIterator = new RecursiveRegexIterator($rArrayIterator, '/^test/',
    RecursiveRegexIterator::ALL_MATCHES);

foreach ($rRegexIterator as $key1 => $value1) {

    if ($rRegexIterator->hasChildren()) {

        // print all children
        echo "Children: ";
        foreach ($rRegexIterator->getChildren() as $key => $value) {
            echo $value . " ";
        }
        echo "\n";
    } else {
        echo "No children\n";
    }

}
?>

The above example will output something similar to:

No children
Children: test4 test5

See Also

  • preg_match() - Perform a regular expression match
  • preg_match_all() - Perform a global regular expression match
  • preg_replace() - Perform a regular expression search and replace
  • preg_split() - Split string by a regular expression


Returns an iterator for the current entry

  • « RecursiveRegexIterator::__construct
  • RecursiveRegexIterator::hasChildren »
  • PHP Manual
  • RecursiveRegexIterator
  • Returns an iterator for the current entry

RecursiveRegexIterator::getChildren

(PHP 5 >= 5.2.0, PHP 7)

RecursiveRegexIterator::getChildren — Returns an iterator for the current entry

Description

public RecursiveRegexIterator::getChildren ( void ) : RecursiveRegexIterator

Returns an iterator for the current iterator entry.

Parameters

This function has no parameters.

Return Values

An iterator for the current entry, if it can be iterated over by the inner iterator.

Errors/Exceptions

An InvalidArgumentException will be thrown if the current entry does not contain a value that can be iterated over by the inner iterator.

Examples

Example #1 RecursiveRegexIterator::getChildren() example

<?php
$rArrayIterator = new RecursiveArrayIterator(array('test1', array('tet3', 'test4', 'test5')));
$rRegexIterator = new RecursiveRegexIterator($rArrayIterator, '/^test/',
    RecursiveRegexIterator::ALL_MATCHES);

foreach ($rRegexIterator as $key1 => $value1) {

    if ($rRegexIterator->hasChildren()) {

        // print all children
        echo "Children: ";
        foreach ($rRegexIterator->getChildren() as $key => $value) {
            echo $value . " ";
        }
        echo "\n";
    } else {
        echo "No children\n";
    }

}
?>

The above example will output:

No children
Children: test4 test5

See Also

  • RecursiveRegexIterator::hasChildren() - Returns whether an iterator can be obtained for the current entry


Returns whether an iterator can be obtained for the current entry

  • « RecursiveRegexIterator::getChildren
  • RecursiveTreeIterator »
  • PHP Manual
  • RecursiveRegexIterator
  • Returns whether an iterator can be obtained for the current entry

RecursiveRegexIterator::hasChildren

(PHP 5 >= 5.2.0, PHP 7)

RecursiveRegexIterator::hasChildren — Returns whether an iterator can be obtained for the current entry

Description

public RecursiveRegexIterator::hasChildren ( void ) : bool

Returns whether an iterator can be obtained for the current entry. This iterator can be obtained via RecursiveRegexIterator::getChildren().

Parameters

This function has no parameters.

Return Values

Returns TRUE if an iterator can be obtained for the current entry, otherwise returns FALSE.

Examples

Example #1 RecursiveRegexIterator::hasChildren() example

<?php
$rArrayIterator = new RecursiveArrayIterator(array('test1', array('tet3', 'test4', 'test5')));
$rRegexIterator = new RecursiveRegexIterator($rArrayIterator, '/^test/',
    RecursiveRegexIterator::ALL_MATCHES);

foreach ($rRegexIterator as $value) {
    var_dump($rRegexIterator->hasChildren());
}
?>

The above example will output:

bool(false)
bool(true)

See Also

  • RecursiveRegexIterator::getChildren() - Returns an iterator for the current entry


The RecursiveTreeIterator class

(PHP 5 >= 5.3.0, PHP 7)

Introduction

Allows iterating over a RecursiveIterator to generate an ASCII graphic tree.

Class synopsis

RecursiveTreeIterator extends RecursiveIteratorIterator implements OuterIterator {
/* Inherited constants */
const integer RecursiveIteratorIterator::LEAVES_ONLY = 0 ;
const integer RecursiveIteratorIterator::SELF_FIRST = 1 ;
const integer RecursiveIteratorIterator::CHILD_FIRST = 2 ;
const integer RecursiveIteratorIterator::CATCH_GET_CHILD = 16 ;
/* Constants */
const integer BYPASS_CURRENT = 4 ;
const integer BYPASS_KEY = 8 ;
const integer PREFIX_LEFT = 0 ;
const integer PREFIX_MID_HAS_NEXT = 1 ;
const integer PREFIX_MID_LAST = 2 ;
const integer PREFIX_END_HAS_NEXT = 3 ;
const integer PREFIX_END_LAST = 4 ;
const integer PREFIX_RIGHT = 5 ;
/* Methods */
public beginChildren ( void ) : void
public beginIteration ( void ) : RecursiveIterator
public callGetChildren ( void ) : RecursiveIterator
public callHasChildren ( void ) : bool
public __construct ( RecursiveIterator|IteratorAggregate $it [, int $flags = RecursiveTreeIterator::BYPASS_KEY [, int $cit_flags = CachingIterator::CATCH_GET_CHILD [, int $mode = RecursiveIteratorIterator::SELF_FIRST ]]] )
public current ( void ) : string
public endChildren ( void ) : void
public endIteration ( void ) : void
public getEntry ( void ) : string
public getPostfix ( void ) : string
public getPrefix ( void ) : string
public key ( void ) : string
public next ( void ) : void
public nextElement ( void ) : void
public rewind ( void ) : void
public setPostfix ( string $postfix ) : void
public setPrefixPart ( int $part , string $value ) : void
public valid ( void ) : bool
/* Inherited methods */
public RecursiveIteratorIterator::beginChildren ( void ) : void
public RecursiveIteratorIterator::beginIteration ( void ) : void
public RecursiveIteratorIterator::callGetChildren ( void ) : RecursiveIterator
public RecursiveIteratorIterator::callHasChildren ( void ) : bool
public RecursiveIteratorIterator::__construct ( Traversable $iterator [, int $mode = RecursiveIteratorIterator::LEAVES_ONLY [, int $flags = 0 ]] )
public RecursiveIteratorIterator::current ( void ) : mixed
public RecursiveIteratorIterator::endChildren ( void ) : void
public RecursiveIteratorIterator::endIteration ( void ) : void
public RecursiveIteratorIterator::getDepth ( void ) : int
public RecursiveIteratorIterator::getInnerIterator ( void ) : iterator
public RecursiveIteratorIterator::getMaxDepth ( void ) : mixed
public RecursiveIteratorIterator::getSubIterator ([ int $level ] ) : RecursiveIterator
public RecursiveIteratorIterator::key ( void ) : mixed
public RecursiveIteratorIterator::next ( void ) : void
public RecursiveIteratorIterator::nextElement ( void ) : void
public RecursiveIteratorIterator::rewind ( void ) : void
public RecursiveIteratorIterator::setMaxDepth ([ int $max_depth = -1 ] ) : void
public RecursiveIteratorIterator::valid ( void ) : bool
}

Predefined Constants

RecursiveTreeIterator::BYPASS_CURRENT

RecursiveTreeIterator::BYPASS_KEY

RecursiveTreeIterator::PREFIX_LEFT

RecursiveTreeIterator::PREFIX_MID_HAS_NEXT

RecursiveTreeIterator::PREFIX_MID_LAST

RecursiveTreeIterator::PREFIX_END_HAS_NEXT

RecursiveTreeIterator::PREFIX_END_LAST

RecursiveTreeIterator::PREFIX_RIGHT

Table of Contents

  • RecursiveTreeIterator::beginChildren — Begin children
  • RecursiveTreeIterator::beginIteration — Begin iteration
  • RecursiveTreeIterator::callGetChildren — Get children
  • RecursiveTreeIterator::callHasChildren — Has children
  • RecursiveTreeIterator::__construct — Construct a RecursiveTreeIterator
  • RecursiveTreeIterator::current — Get current element
  • RecursiveTreeIterator::endChildren — End children
  • RecursiveTreeIterator::endIteration — End iteration
  • RecursiveTreeIterator::getEntry — Get current entry
  • RecursiveTreeIterator::getPostfix — Get the postfix
  • RecursiveTreeIterator::getPrefix — Get the prefix
  • RecursiveTreeIterator::key — Get the key of the current element
  • RecursiveTreeIterator::next — Move to next element
  • RecursiveTreeIterator::nextElement — Next element
  • RecursiveTreeIterator::rewind — Rewind iterator
  • RecursiveTreeIterator::setPostfix — Set postfix
  • RecursiveTreeIterator::setPrefixPart — Set a part of the prefix
  • RecursiveTreeIterator::valid — Check validity


Begin children

  • « RecursiveTreeIterator
  • RecursiveTreeIterator::beginIteration »
  • PHP Manual
  • RecursiveTreeIterator
  • Begin children

RecursiveTreeIterator::beginChildren

(PHP 5 >= 5.3.0, PHP 7)

RecursiveTreeIterator::beginChildren — Begin children

Description

public RecursiveTreeIterator::beginChildren ( void ) : void

Called when recursing one level down.

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.


Begin iteration

  • « RecursiveTreeIterator::beginChildren
  • RecursiveTreeIterator::callGetChildren »
  • PHP Manual
  • RecursiveTreeIterator
  • Begin iteration

RecursiveTreeIterator::beginIteration

(PHP 5 >= 5.3.0, PHP 7)

RecursiveTreeIterator::beginIteration — Begin iteration

Description

public RecursiveTreeIterator::beginIteration ( void ) : RecursiveIterator

Called when iteration begins (after the first RecursiveTreeIterator::rewind() call).

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

A RecursiveIterator.


Get children

  • « RecursiveTreeIterator::beginIteration
  • RecursiveTreeIterator::callHasChildren »
  • PHP Manual
  • RecursiveTreeIterator
  • Get children

RecursiveTreeIterator::callGetChildren

(PHP 5 >= 5.3.0, PHP 7)

RecursiveTreeIterator::callGetChildren — Get children

Description

public RecursiveTreeIterator::callGetChildren ( void ) : RecursiveIterator

Gets children of the current element.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

A RecursiveIterator.


Has children

  • « RecursiveTreeIterator::callGetChildren
  • RecursiveTreeIterator::__construct »
  • PHP Manual
  • RecursiveTreeIterator
  • Has children

RecursiveTreeIterator::callHasChildren

(PHP 5 >= 5.3.0, PHP 7)

RecursiveTreeIterator::callHasChildren — Has children

Description

public RecursiveTreeIterator::callHasChildren ( void ) : bool

Called for each element to test whether it has children.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

TRUE if there are children, otherwise FALSE


Construct a RecursiveTreeIterator

  • « RecursiveTreeIterator::callHasChildren
  • RecursiveTreeIterator::current »
  • PHP Manual
  • RecursiveTreeIterator
  • Construct a RecursiveTreeIterator

RecursiveTreeIterator::__construct

(PHP 5 >= 5.3.0, PHP 7)

RecursiveTreeIterator::__construct — Construct a RecursiveTreeIterator

Description

 public RecursiveTreeIterator::__construct
  ( RecursiveIterator|IteratorAggregate $it
 [, int $flags = RecursiveTreeIterator::BYPASS_KEY
 [, int $cit_flags = CachingIterator::CATCH_GET_CHILD
 [, int $mode = RecursiveIteratorIterator::SELF_FIRST
]]] )

Constructs a new RecursiveTreeIterator from the supplied recursive iterator.

Warning

This function is currently not documented; only its argument list is available.

Parameters

it

The RecursiveIterator or IteratorAggregate to iterate over.

flags

Flags may be provided which will affect the behavior of some methods. A list of the flags can found under RecursiveTreeIterator predefined constants.

caching_it_flags

Flags to affect the behavior of the RecursiveCachingIterator used internally.

mode

Flags to affect the behavior of the RecursiveIteratorIterator used internally.

Return Values

No value is returned.


Get current element

  • « RecursiveTreeIterator::__construct
  • RecursiveTreeIterator::endChildren »
  • PHP Manual
  • RecursiveTreeIterator
  • Get current element

RecursiveTreeIterator::current

(PHP 5 >= 5.3.0, PHP 7)

RecursiveTreeIterator::current — Get current element

Description

public RecursiveTreeIterator::current ( void ) : string

Gets the current element prefixed and postfixed.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns the current element prefixed and postfixed.


End children

  • « RecursiveTreeIterator::current
  • RecursiveTreeIterator::endIteration »
  • PHP Manual
  • RecursiveTreeIterator
  • End children

RecursiveTreeIterator::endChildren

(PHP 5 >= 5.3.0, PHP 7)

RecursiveTreeIterator::endChildren — End children

Description

public RecursiveTreeIterator::endChildren ( void ) : void

Called when end recursing one level.

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.


End iteration

  • « RecursiveTreeIterator::endChildren
  • RecursiveTreeIterator::getEntry »
  • PHP Manual
  • RecursiveTreeIterator
  • End iteration

RecursiveTreeIterator::endIteration

(PHP 5 >= 5.3.0, PHP 7)

RecursiveTreeIterator::endIteration — End iteration

Description

public RecursiveTreeIterator::endIteration ( void ) : void

Called when the iteration ends (when RecursiveTreeIterator::valid() first returns FALSE)

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.


Get current entry

  • « RecursiveTreeIterator::endIteration
  • RecursiveTreeIterator::getPostfix »
  • PHP Manual
  • RecursiveTreeIterator
  • Get current entry

RecursiveTreeIterator::getEntry

(PHP 5 >= 5.3.0, PHP 7)

RecursiveTreeIterator::getEntry — Get current entry

Description

public RecursiveTreeIterator::getEntry ( void ) : string

Gets the part of the tree built for the current element.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns the part of the tree built for the current element.


Get the postfix

  • « RecursiveTreeIterator::getEntry
  • RecursiveTreeIterator::getPrefix »
  • PHP Manual
  • RecursiveTreeIterator
  • Get the postfix

RecursiveTreeIterator::getPostfix

(PHP 5 >= 5.3.0, PHP 7)

RecursiveTreeIterator::getPostfix — Get the postfix

Description

public RecursiveTreeIterator::getPostfix ( void ) : string

Gets the string to place after the current element.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns the string to place after the current element.


Get the prefix

  • « RecursiveTreeIterator::getPostfix
  • RecursiveTreeIterator::key »
  • PHP Manual
  • RecursiveTreeIterator
  • Get the prefix

RecursiveTreeIterator::getPrefix

(PHP 5 >= 5.3.0, PHP 7)

RecursiveTreeIterator::getPrefix — Get the prefix

Description

public RecursiveTreeIterator::getPrefix ( void ) : string

Gets the string to place in front of current element

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns the string to place in front of current element


Get the key of the current element

  • « RecursiveTreeIterator::getPrefix
  • RecursiveTreeIterator::next »
  • PHP Manual
  • RecursiveTreeIterator
  • Get the key of the current element

RecursiveTreeIterator::key

(PHP 5 >= 5.3.0, PHP 7)

RecursiveTreeIterator::key — Get the key of the current element

Description

public RecursiveTreeIterator::key ( void ) : string

Gets the current key prefixed and postfixed.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns the current key prefixed and postfixed.


Move to next element

  • « RecursiveTreeIterator::key
  • RecursiveTreeIterator::nextElement »
  • PHP Manual
  • RecursiveTreeIterator
  • Move to next element

RecursiveTreeIterator::next

(PHP 5 >= 5.3.0, PHP 7)

RecursiveTreeIterator::next — Move to next element

Description

public RecursiveTreeIterator::next ( void ) : void

Moves forward to the next element.

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.


Next element

  • « RecursiveTreeIterator::next
  • RecursiveTreeIterator::rewind »
  • PHP Manual
  • RecursiveTreeIterator
  • Next element

RecursiveTreeIterator::nextElement

(PHP 5 >= 5.3.0, PHP 7)

RecursiveTreeIterator::nextElement — Next element

Description

public RecursiveTreeIterator::nextElement ( void ) : void

Called when the next element is available.

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.


Rewind iterator

  • « RecursiveTreeIterator::nextElement
  • RecursiveTreeIterator::setPostfix »
  • PHP Manual
  • RecursiveTreeIterator
  • Rewind iterator

RecursiveTreeIterator::rewind

(PHP 5 >= 5.3.0, PHP 7)

RecursiveTreeIterator::rewind — Rewind iterator

Description

public RecursiveTreeIterator::rewind ( void ) : void

Rewinds the iterator to the first element of the top level inner iterator.

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.


Set postfix

  • « RecursiveTreeIterator::rewind
  • RecursiveTreeIterator::setPrefixPart »
  • PHP Manual
  • RecursiveTreeIterator
  • Set postfix

RecursiveTreeIterator::setPostfix

(PHP 5 >= 5.5.3, PHP 7)

RecursiveTreeIterator::setPostfix — Set postfix

Description

public RecursiveTreeIterator::setPostfix ( string $postfix ) : void

Sets postfix as used in RecursiveTreeIterator::getPostfix().

Warning

This function is currently not documented; only its argument list is available.

Parameters

postfix

Return Values

No value is returned.


Set a part of the prefix

  • « RecursiveTreeIterator::setPostfix
  • RecursiveTreeIterator::valid »
  • PHP Manual
  • RecursiveTreeIterator
  • Set a part of the prefix

RecursiveTreeIterator::setPrefixPart

(PHP 5 >= 5.3.0, PHP 7)

RecursiveTreeIterator::setPrefixPart — Set a part of the prefix

Description

public RecursiveTreeIterator::setPrefixPart ( int $part , string $value ) : void

Sets a part of the prefix used in the graphic tree.

Warning

This function is currently not documented; only its argument list is available.

Parameters

part

One of the RecursiveTreeIterator::PREFIX_* constants.

value

The value to assign to the part of the prefix specified in part.

Return Values

No value is returned.


Check validity

  • « RecursiveTreeIterator::setPrefixPart
  • RegexIterator »
  • PHP Manual
  • RecursiveTreeIterator
  • Check validity

RecursiveTreeIterator::valid

(PHP 5 >= 5.3.0, PHP 7)

RecursiveTreeIterator::valid — Check validity

Description

public RecursiveTreeIterator::valid ( void ) : bool

Check whether the current position is valid.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

TRUE if the current position is valid, otherwise FALSE


The RegexIterator class

(PHP 5 >= 5.2.0, PHP 7)

Introduction

This iterator can be used to filter another iterator based on a regular expression.

Class synopsis

RegexIterator extends FilterIterator {
/* Constants */
const integer MATCH = 0 ;
const integer GET_MATCH = 1 ;
const integer ALL_MATCHES = 2 ;
const integer SPLIT = 3 ;
const integer REPLACE = 4 ;
const integer USE_KEY = 1 ;
/* Methods */
public __construct ( Iterator $iterator , string $regex [, int $mode = self::MATCH [, int $flags = 0 [, int $preg_flags = 0 ]]] )
public accept ( void ) : bool
public getFlags ( void ) : int
public getMode ( void ) : int
public getPregFlags ( void ) : int
public getRegex ( void ) : string
public setFlags ( int $flags ) : void
public setMode ( int $mode ) : void
public setPregFlags ( int $preg_flags ) : void
/* Inherited methods */
public abstract FilterIterator::accept ( void ) : bool
public FilterIterator::__construct ( Iterator $iterator )
public FilterIterator::current ( void ) : mixed
public FilterIterator::getInnerIterator ( void ) : Iterator
public FilterIterator::key ( void ) : mixed
public FilterIterator::next ( void ) : void
public FilterIterator::rewind ( void ) : void
public FilterIterator::valid ( void ) : bool
}

Predefined Constants

RegexIterator operation modes

RegexIterator::ALL_MATCHES

Return all matches for the current entry (see preg_match_all()).

RegexIterator::GET_MATCH

Return the first match for the current entry (see preg_match()).

RegexIterator::MATCH

Only execute match (filter) for the current entry (see preg_match()).

RegexIterator::REPLACE

Replace the current entry (see preg_replace(); Not fully implemented yet)

RegexIterator::SPLIT

Returns the split values for the current entry (see preg_split()).

RegexIterator Flags

RegexIterator::USE_KEY

Special flag: Match the entry key instead of the entry value.

Table of Contents

  • RegexIterator::accept — Get accept status
  • RegexIterator::__construct — Create a new RegexIterator
  • RegexIterator::getFlags — Get flags
  • RegexIterator::getMode — Returns operation mode
  • RegexIterator::getPregFlags — Returns the regular expression flags
  • RegexIterator::getRegex — Returns current regular expression
  • RegexIterator::setFlags — Sets the flags
  • RegexIterator::setMode — Sets the operation mode
  • RegexIterator::setPregFlags — Sets the regular expression flags


Get accept status

  • « RegexIterator
  • RegexIterator::__construct »
  • PHP Manual
  • RegexIterator
  • Get accept status

RegexIterator::accept

(PHP 5 >= 5.2.0, PHP 7)

RegexIterator::accept — Get accept status

Description

public RegexIterator::accept ( void ) : bool

Matches (string) RegexIterator::current()
(or RegexIterator::key() if the
RegexIterator::USE_KEY flag is set)
against the regular expression.

Parameters

This function has no parameters.

Return Values

TRUE if a match, FALSE otherwise.

Examples

Example #1 RegexIterator::accept() example

This example shows that only items matching the regular expression are accepted.

<?php
$names = new ArrayIterator(array('Ann', 'Bob', 'Charlie', 'David'));
$filter = new RegexIterator($names, '/^[B-D]/');
foreach ($filter as $name) {
    echo $name . PHP_EOL;
}
?>

The above example will output:

Bob
Charlie
David

See Also

  • RegexIterator constants
  • RegexIterator::setFlags() - Sets the flags


Create a new RegexIterator

  • « RegexIterator::accept
  • RegexIterator::getFlags »
  • PHP Manual
  • RegexIterator
  • Create a new RegexIterator

RegexIterator::__construct

(PHP 5 >= 5.2.0, PHP 7)

RegexIterator::__construct — Create a new RegexIterator

Description

public RegexIterator::__construct ( Iterator $iterator , string $regex [, int $mode = self::MATCH [, int $flags = 0 [, int $preg_flags = 0 ]]] )

Create a new RegexIterator which filters an Iterator using a regular expression.

Parameters

iterator

The iterator to apply this regex filter to.

regex

The regular expression to match.

mode

Operation mode, see RegexIterator::setMode() for a list of modes.

flags

Special flags, see RegexIterator::setFlags() for a list of available flags.

preg_flags

The regular expression flags. These flags depend on the operation mode parameter:

RegexIterator preg_flags
operation mode | available flags
RegexIterator::ALL_MATCHES | See preg_match_all().
RegexIterator::GET_MATCH | See preg_match().
RegexIterator::MATCH | See preg_match().
RegexIterator::REPLACE | none.
RegexIterator::SPLIT | See preg_split().

Errors/Exceptions

Throws an InvalidArgumentException if the regex argument is invalid.

Examples

Example #1 RegexIterator::__construct() example

Creates a new RegexIterator that filters all strings that start with 'test'.

<?php
$arrayIterator = new ArrayIterator(array('test 1', 'another test', 'test 123'));
$regexIterator = new RegexIterator($arrayIterator, '/^test/');

foreach ($regexIterator as $value) {
    echo $value . "\n";
}
?>

The above example will output something similar to:

test 1
test 123

See Also

  • preg_match() - Perform a regular expression match
  • preg_match_all() - Perform a global regular expression match
  • preg_replace() - Perform a regular expression search and replace
  • preg_split() - Split string by a regular expression


Get flags

  • « RegexIterator::__construct
  • RegexIterator::getMode »
  • PHP Manual
  • RegexIterator
  • Get flags

RegexIterator::getFlags

(PHP 5 >= 5.2.0, PHP 7)

RegexIterator::getFlags — Get flags

Description

public RegexIterator::getFlags ( void ) : int

Returns the flags, see RegexIterator::setFlags() for a list of available flags.

Return Values

Returns the set flags.

Examples

Example #1 RegexIterator::getFlags() example

<?php

$test = array ('str1' => 'test 1', 'teststr2' => 'another test', 'str3' => 'test 123');

$arrayIterator = new ArrayIterator($test);
$regexIterator = new RegexIterator($arrayIterator, '/^test/');
$regexIterator->setFlags(RegexIterator::USE_KEY);

if ($regexIterator->getFlags() & RegexIterator::USE_KEY) {
    echo 'Filtering based on the array keys.';
} else {
    echo 'Filtering based on the array values.';
}
?>

The above example will output:

Filtering based on the array keys.

See Also

  • RegexIterator::setFlags() - Sets the flags


Returns operation mode

  • « RegexIterator::getFlags
  • RegexIterator::getPregFlags »
  • PHP Manual
  • RegexIterator
  • Returns operation mode

RegexIterator::getMode

(PHP 5 >= 5.2.0, PHP 7)

RegexIterator::getMode — Returns operation mode

Description

public RegexIterator::getMode ( void ) : int

Returns the operation mode, see RegexIterator::setMode() for the list of operation modes.

Return Values

Returns the operation mode.

Examples

Example #1 RegexIterator::getMode() example

<?php

$test = array ('str1' => 'test 1', 'teststr2' => 'another test', 'str3' => 'test 123');

$arrayIterator = new ArrayIterator($test);
$regexIterator = new RegexIterator($arrayIterator, '/^[a-z]+/', RegexIterator::GET_MATCH);

$mode = $regexIterator->getMode();
if ($mode & RegexIterator::GET_MATCH) {
    echo 'Getting the match for each item.';
} elseif ($mode & RegexIterator::ALL_MATCHES) {
    echo 'Getting all matches for each item.';
} elseif ($mode & RegexIterator::MATCH) {
    echo 'Getting each item if it matches.';
} elseif ($mode & RegexIterator::SPLIT) {
    echo 'Getting split pieces of each.';
}
?>

The above example will output:

Getting the match for each item.

See Also

  • RegexIterator::setMode() - Sets the operation mode


Returns the regular expression flags

  • « RegexIterator::getMode
  • RegexIterator::getRegex »
  • PHP Manual
  • RegexIterator
  • Returns the regular expression flags

RegexIterator::getPregFlags

(PHP 5 >= 5.2.0, PHP 7)

RegexIterator::getPregFlags — Returns the regular expression flags

Description

public RegexIterator::getPregFlags ( void ) : int

Returns the regular expression flags, see RegexIterator::__construct() for the list of flags.

Return Values

Returns a bitmask of the regular expression flags.

Examples

Example #1 RegexIterator::getPregFlags() example

<?php

$test = array ('str1' => 'test 1', 'teststr2' => 'another test', 'str3' => 'test 123');

$arrayIterator = new ArrayIterator($test);
$regexIterator = new RegexIterator($arrayIterator, '/\s/', RegexIterator::SPLIT);
$regexIterator->setPregFlags(PREG_SPLIT_NO_EMPTY | PREG_SPLIT_OFFSET_CAPTURE);

if ($regexIterator->getPregFlags() & PREG_SPLIT_NO_EMPTY) {
    echo 'Ignoring empty pieces';
} else {
    echo 'Not ignoring empty pieces';
}

?>

The above example will output:

Ignoring empty pieces

See Also

  • RegexIterator::setPregFlags() - Sets the regular expression flags


Returns current regular expression

  • « RegexIterator::getPregFlags
  • RegexIterator::setFlags »
  • PHP Manual
  • RegexIterator
  • Returns current regular expression

RegexIterator::getRegex

(PHP 5 >= 5.4.0, PHP 7)

RegexIterator::getRegex — Returns current regular expression

Description

public RegexIterator::getRegex ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Sets the flags

  • « RegexIterator::getRegex
  • RegexIterator::setMode »
  • PHP Manual
  • RegexIterator
  • Sets the flags

RegexIterator::setFlags

(PHP 5 >= 5.2.0, PHP 7)

RegexIterator::setFlags — Sets the flags

Description

public RegexIterator::setFlags ( int $flags ) : void

Sets the flags.

Parameters

flags

The flags to set, a bitmask of class constants.

The available flags are listed below. The actual meanings of these flags are described in the predefined constants.

RegexIterator flags
value | constant
1 | RegexIterator::USE_KEY

Return Values

No value is returned.

Examples

Example #1 RegexIterator::setFlags() example

Creates a new RegexIterator that filters all entries whose key starts with 'test'.

<?php
$test = array ('str1' => 'test 1', 'teststr2' => 'another test', 'str3' => 'test 123');

$arrayIterator = new ArrayIterator($test);
$regexIterator = new RegexIterator($arrayIterator, '/^test/');
$regexIterator->setFlags(RegexIterator::USE_KEY);

foreach ($regexIterator as $key => $value) {
    echo $key . ' => ' . $value . "\n";
}
?>

The above example will output:

teststr2 => another test

See Also

  • RegexIterator::getFlags() - Get flags


Sets the operation mode

  • « RegexIterator::setFlags
  • RegexIterator::setPregFlags »
  • PHP Manual
  • RegexIterator
  • Sets the operation mode

RegexIterator::setMode

(PHP 5 >= 5.2.0, PHP 7)

RegexIterator::setMode — Sets the operation mode

Description

public RegexIterator::setMode ( int $mode ) : void

Sets the operation mode.

Parameters

mode

The operation mode.

The available modes are listed below. The actual meanings of these modes are described in the predefined constants.

RegexIterator modes
value | constant
0 | RegexIterator::MATCH
1 | RegexIterator::GET_MATCH
2 | RegexIterator::ALL_MATCHES
3 | RegexIterator::SPLIT
4 | RegexIterator::REPLACE

Return Values

No value is returned.

Examples

Example #1 RegexIterator::setMode() example

<?php
$test = array ('str1' => 'test 1', 'test str2' => 'another test', 'str3' => 'test 123');

$arrayIterator = new ArrayIterator($test);
// Filter everything that starts with 'test ' followed by one or more numbers.
$regexIterator = new RegexIterator($arrayIterator, '/^test (\d+)/');
// Operation mode: Replace actual value with the matches
$regexIterator->setMode(RegexIterator::GET_MATCH);

foreach ($regexIterator as $key => $value) {
    // print out the matched number(s)
    echo $key . ' => ' . $value[1] . PHP_EOL;
}
?>

The above example will output something similar to:

str1 => 1
str3 => 123

See Also

  • RegexIterator::getMode() - Returns operation mode


Sets the regular expression flags

  • « RegexIterator::setMode
  • Interfaces »
  • PHP Manual
  • RegexIterator
  • Sets the regular expression flags

RegexIterator::setPregFlags

(PHP 5 >= 5.2.0, PHP 7)

RegexIterator::setPregFlags — Sets the regular expression flags

Description

public RegexIterator::setPregFlags ( int $preg_flags ) : void

Sets the regular expression flags.

Parameters

preg_flags

The regular expression flags. See RegexIterator::__construct() for an overview of available flags.

Return Values

No value is returned.

Examples

Example #1 RegexIterator::setPregFlags() example

Creates a new RegexIterator that filters all entries with where the array key starts with 'test'.

<?php
$test = array ('test 1', 'another test', 'test 123');

$arrayIterator = new ArrayIterator($test);
$regexIterator = new RegexIterator($arrayIterator, '/^test/', RegexIterator::GET_MATCH);

$regexIterator->setPregFlags(PREG_OFFSET_CAPTURE);

foreach ($regexIterator as $key => $value) {
    var_dump($value);
}
?>

The above example will output something similar to:

array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(4) "test"
    [1]=>
    int(0)
  }
}
array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(4) "test"
    [1]=>
    int(0)
  }
}

See Also

  • RegexIterator::getPregFlags() - Returns the regular expression flags


Interfaces

Table of Contents

  • Countable
  • OuterIterator
  • RecursiveIterator
  • SeekableIterator

SPL provides a set of interfaces.

See also the Predefined Interfaces and Classes

Interface list

  • Countable
  • OuterIterator
  • RecursiveIterator
  • SeekableIterator
  • SplObserver
  • SplSubject


The Countable interface

(PHP 5 >= 5.1.0, PHP 7)

Introduction

Classes implementing Countable can be used with the count() function.

Interface synopsis

Countable {
/* Methods */
abstract public count ( void ) : int
}

Table of Contents

  • Countable::count — Count elements of an object


Count elements of an object

  • « Countable
  • OuterIterator »
  • PHP Manual
  • Countable
  • Count elements of an object

Countable::count

(PHP 5 >= 5.1.0, PHP 7)

Countable::count — Count elements of an object

Description

abstract public Countable::count ( void ) : int

This method is executed when using the count() function on an object implementing Countable.

Parameters

This function has no parameters.

Return Values

The custom count as an integer.

Note:

The return value is cast to an integer.

Examples

Example #1 Countable::count() example

<?php
class myCounter implements Countable {
    private $count = 0;
    public function count() {
        return ++$this->count;
    }
}

$counter = new myCounter;

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


The OuterIterator interface

(PHP 5 >= 5.1.0, PHP 7)

Introduction

Classes implementing OuterIterator can be used to iterate over iterators.

Interface synopsis

OuterIterator extends Iterator {
/* Methods */
public getInnerIterator ( void ) : Iterator
/* Inherited methods */
abstract public Iterator::current ( void ) : mixed
abstract public Iterator::key ( void ) : scalar
abstract public Iterator::next ( void ) : void
abstract public Iterator::rewind ( void ) : void
abstract public Iterator::valid ( void ) : bool
}

Table of Contents

  • OuterIterator::getInnerIterator — Returns the inner iterator for the current entry


Returns the inner iterator for the current entry

  • « OuterIterator
  • RecursiveIterator »
  • PHP Manual
  • OuterIterator
  • Returns the inner iterator for the current entry

OuterIterator::getInnerIterator

(PHP 5 >= 5.1.0, PHP 7)

OuterIterator::getInnerIterator — Returns the inner iterator for the current entry

Description

public OuterIterator::getInnerIterator ( void ) : Iterator

Returns the inner iterator for the current iterator entry.

Parameters

This function has no parameters.

Return Values

The inner iterator for the current entry.


The RecursiveIterator interface

(PHP 5 >= 5.1.0, PHP 7)

Introduction

Classes implementing RecursiveIterator can be used to iterate over iterators recursively.

Interface synopsis

RecursiveIterator extends Iterator {
/* Methods */
public getChildren ( void ) : RecursiveIterator
public hasChildren ( void ) : bool
/* Inherited methods */
abstract public Iterator::current ( void ) : mixed
abstract public Iterator::key ( void ) : scalar
abstract public Iterator::next ( void ) : void
abstract public Iterator::rewind ( void ) : void
abstract public Iterator::valid ( void ) : bool
}

Table of Contents

  • RecursiveIterator::getChildren — Returns an iterator for the current entry
  • RecursiveIterator::hasChildren — Returns if an iterator can be created for the current entry


Returns an iterator for the current entry

  • « RecursiveIterator
  • RecursiveIterator::hasChildren »
  • PHP Manual
  • RecursiveIterator
  • Returns an iterator for the current entry

RecursiveIterator::getChildren

(PHP 5 >= 5.1.0, PHP 7)

RecursiveIterator::getChildren — Returns an iterator for the current entry

Description

public RecursiveIterator::getChildren ( void ) : RecursiveIterator

Returns an iterator for the current iterator entry.

Parameters

This function has no parameters.

Return Values

An iterator for the current entry.

See Also

  • RecursiveIterator::hasChildren() - Returns if an iterator can be created for the current entry


Returns if an iterator can be created for the current entry

  • « RecursiveIterator::getChildren
  • SeekableIterator »
  • PHP Manual
  • RecursiveIterator
  • Returns if an iterator can be created for the current entry

RecursiveIterator::hasChildren

(PHP 5 >= 5.1.0, PHP 7)

RecursiveIterator::hasChildren — Returns if an iterator can be created for the current entry

Description

public RecursiveIterator::hasChildren ( void ) : bool

Returns if an iterator can be created for the current entry. RecursiveIterator::getChildren().

Parameters

This function has no parameters.

Return Values

Returns TRUE if the current entry can be iterated over, otherwise returns FALSE.

See Also

  • RecursiveIterator::getChildren() - Returns an iterator for the current entry


The SeekableIterator interface

(PHP 5 >= 5.1.0, PHP 7)

Introduction

The Seekable iterator.

Interface synopsis

SeekableIterator extends Iterator {
/* Methods */
abstract public seek ( int $position ) : void
/* Inherited methods */
abstract public Iterator::current ( void ) : mixed
abstract public Iterator::key ( void ) : scalar
abstract public Iterator::next ( void ) : void
abstract public Iterator::rewind ( void ) : void
abstract public Iterator::valid ( void ) : bool
}

Example #1 Basic usage

This example demonstrates creating a custom SeekableIterator, seeking to a position and handling an invalid position.

<?php
class MySeekableIterator implements SeekableIterator {

    private $position;

    private $array = array(
        "first element",
        "second element",
        "third element",
        "fourth element"
    );

    /* Method required for SeekableIterator interface */

    public function seek($position) {
      if (!isset($this->array[$position])) {
          throw new OutOfBoundsException("invalid seek position ($position)");
      }

      $this->position = $position;
    }

    /* Methods required for Iterator interface */

    public function rewind() {
        $this->position = 0;
    }

    public function current() {
        return $this->array[$this->position];
    }

    public function key() {
        return $this->position;
    }

    public function next() {
        ++$this->position;
    }

    public function valid() {
        return isset($this->array[$this->position]);
    }
}

try {

    $it = new MySeekableIterator;
    echo $it->current(), "\n";

    $it->seek(2);
    echo $it->current(), "\n";

    $it->seek(1);
    echo $it->current(), "\n";

    $it->seek(10);

} catch (OutOfBoundsException $e) {
    echo $e->getMessage();
}
?>

The above example will output something similar to:

first element
third element
second element
invalid seek position (10)

Table of Contents

  • SeekableIterator::seek — Seeks to a position


Seeks to a position

  • « SeekableIterator
  • Exceptions »
  • PHP Manual
  • SeekableIterator
  • Seeks to a position

SeekableIterator::seek

(PHP 5 >= 5.1.0, PHP 7)

SeekableIterator::seek — Seeks to a position

Description

abstract public SeekableIterator::seek ( int $position ) : void

Seeks to a given position in the iterator.

Parameters

position

The position to seek to.

Return Values

No value is returned.

Errors/Exceptions

Implementations should throw an OutOfBoundsException if the position is not seekable.

Examples

Example #1 SeekableIterator::seek() example

Seek to the item at position 3 in the iterator (ArrayIterator implements SeekableIterator).

<?php
$array = array("apple", "banana", "cherry", "damson", "elderberry");
$iterator = new ArrayIterator($array);
$iterator->seek(3);
echo $iterator->current();
?>

The above example will output something similar to:

damson

See Also

  • SeekableIterator
  • Iterator


Exceptions

Table of Contents

  • BadFunctionCallException
  • BadMethodCallException
  • DomainException
  • InvalidArgumentException
  • LengthException
  • LogicException
  • OutOfBoundsException
  • OutOfRangeException
  • OverflowException
  • RangeException
  • RuntimeException
  • UnderflowException
  • UnexpectedValueException

SPL provides a set of standard Exceptions.

See also the Predefined Exceptions

SPL Exceptions Class Tree

  • LogicException (extends Exception)
    • BadFunctionCallException
      • BadMethodCallException
    • DomainException
    • InvalidArgumentException
    • LengthException
    • OutOfRangeException
  • RuntimeException (extends Exception)
    • OutOfBoundsException
    • OverflowException
    • RangeException
    • UnderflowException
    • UnexpectedValueException


The BadFunctionCallException class

(PHP 5 >= 5.1.0, PHP 7)

Introduction

Exception thrown if a callback refers to an undefined function or if some arguments are missing.

Class synopsis

BadFunctionCallException extends LogicException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The BadMethodCallException class

(PHP 5 >= 5.1.0, PHP 7)

Introduction

Exception thrown if a callback refers to an undefined method or if some arguments are missing.

Class synopsis

BadMethodCallException extends BadFunctionCallException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The DomainException class

(PHP 5 >= 5.1.0, PHP 7)

Introduction

Exception thrown if a value does not adhere to a defined valid data domain.

Class synopsis

DomainException extends LogicException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The InvalidArgumentException class

(PHP 5 >= 5.1.0, PHP 7)

Introduction

Exception thrown if an argument is not of the expected type.

Class synopsis

InvalidArgumentException extends LogicException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The LengthException class

(PHP 5 >= 5.1.0, PHP 7)

Introduction

Exception thrown if a length is invalid.

Class synopsis

LengthException extends LogicException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The LogicException class

(PHP 5 >= 5.1.0, PHP 7)

Introduction

Exception that represents error in the program logic. This kind of exception should lead directly to a fix in your code.

Class synopsis

LogicException extends Exception {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The OutOfBoundsException class

(PHP 5 >= 5.1.0, PHP 7)

Introduction

Exception thrown if a value is not a valid key. This represents errors that cannot be detected at compile time.

Class synopsis

OutOfBoundsException extends RuntimeException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The OutOfRangeException class

(PHP 5 >= 5.1.0, PHP 7)

Introduction

Exception thrown when an illegal index was requested. This represents errors that should be detected at compile time.

Class synopsis

OutOfRangeException extends LogicException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The OverflowException class

(PHP 5 >= 5.1.0, PHP 7)

Introduction

Exception thrown when adding an element to a full container.

Class synopsis

OverflowException extends RuntimeException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The RangeException class

(PHP 5 >= 5.1.0, PHP 7)

Introduction

Exception thrown to indicate range errors during program execution. Normally this means there was an arithmetic error other than under/overflow. This is the runtime version of DomainException.

Class synopsis

RangeException extends RuntimeException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The RuntimeException class

(PHP 5 >= 5.1.0, PHP 7)

Introduction

Exception thrown if an error which can only be found on runtime occurs.

Class synopsis

RuntimeException extends Exception {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The UnderflowException class

(PHP 5 >= 5.1.0, PHP 7)

Introduction

Exception thrown when performing an invalid operation on an empty container, such as removing an element.

Class synopsis

UnderflowException extends RuntimeException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The UnexpectedValueException class

(PHP 5 >= 5.1.0, PHP 7)

Introduction

Exception thrown if a value does not match with a set of values. Typically this happens when a function calls another function and expects the return value to be of a certain type or value not including arithmetic or buffer related errors.

Class synopsis

UnexpectedValueException extends RuntimeException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


SPL Functions

Table of Contents

  • class_implements — Return the interfaces which are implemented by the given class or interface
  • class_parents — Return the parent classes of the given class
  • class_uses — Return the traits used by the given class
  • iterator_apply — Call a function for every element in an iterator
  • iterator_count — Count the elements in an iterator
  • iterator_to_array — Copy the iterator into an array
  • spl_autoload_call — Try all registered __autoload() functions to load the requested class
  • spl_autoload_extensions — Register and return default file extensions for spl_autoload
  • spl_autoload_functions — Return all registered __autoload() functions
  • spl_autoload_register — Register given function as __autoload() implementation
  • spl_autoload_unregister — Unregister given function as __autoload() implementation
  • spl_autoload — Default implementation for __autoload()
  • spl_classes — Return available SPL classes
  • spl_object_hash — Return hash id for given object
  • spl_object_id — Return the integer object handle for given object


Return the interfaces which are implemented by the given class or interface

  • « SPL Functions
  • class_parents »
  • PHP Manual
  • SPL Functions
  • Return the interfaces which are implemented by the given class or interface

class_implements

(PHP 5, PHP 7)

class_implements — Return the interfaces which are implemented by the given class or interface

Description

class_implements ( mixed $class [, bool $autoload = TRUE ] ) : array

This function returns an array with the names of the interfaces that the given class and its parents implement.

Parameters

class

An object (class instance) or a string (class or interface name).

autoload

Whether to allow this function to load the class automatically through the __autoload() magic method.

Return Values

An array on success, or FALSE on error.

Changelog

Version | Description
5.1.0 | Added the option to pass the class parameter as a string. Added the autoload parameter.

Examples

Example #1 class_implements() example

<?php

interface foo { }
class bar implements foo {}

print_r(class_implements(new bar));

// since PHP 5.1.0 you may also specify the parameter as a string
print_r(class_implements('bar'));

function __autoload($class_name) {
   require_once $class_name . '.php';
}

// use __autoload to load the 'not_loaded' class
print_r(class_implements('not_loaded', true));

?>

The above example will output something similar to:

Array
(
    [foo] => foo
)

Array
(
    [interface_of_not_loaded] => interface_of_not_loaded
)

See Also

  • class_parents() - Return the parent classes of the given class
  • get_declared_interfaces() - Returns an array of all declared interfaces


Return the parent classes of the given class

  • « class_implements
  • class_uses »
  • PHP Manual
  • SPL Functions
  • Return the parent classes of the given class

class_parents

(PHP 5, PHP 7)

class_parents — Return the parent classes of the given class

Description

class_parents ( mixed $class [, bool $autoload = TRUE ] ) : array

This function returns an array with the name of the parent classes of the given class.

Parameters

class

An object (class instance) or a string (class name).

autoload

Whether to allow this function to load the class automatically through the __autoload() magic method.

Return Values

An array on success, or FALSE on error.

Changelog

Version | Description
5.1.0 | Added the option to pass the class parameter as a string. Added the autoload parameter.

Examples

Example #1 class_parents() example

<?php

class foo { }
class bar extends foo {}

print_r(class_parents(new bar));

// since PHP 5.1.0 you may also specify the parameter as a string
print_r(class_parents('bar'));

function __autoload($class_name) {
   require_once $class_name . '.php';
}

// use __autoload to load the 'not_loaded' class
print_r(class_parents('not_loaded', true));
?>

The above example will output something similar to:

Array
(
    [foo] => foo
)

Array
(
    [parent_of_not_loaded] => parent_of_not_loaded
)

See Also

  • class_implements() - Return the interfaces which are implemented by the given class or interface


Return the traits used by the given class

  • « class_parents
  • iterator_apply »
  • PHP Manual
  • SPL Functions
  • Return the traits used by the given class

class_uses

(PHP 5 >= 5.4.0, PHP 7)

class_uses — Return the traits used by the given class

Description

class_uses ( mixed $class [, bool $autoload = TRUE ] ) : array

This function returns an array with the names of the traits that the given class uses. This does however not include any traits used by a parent class.

Parameters

class

An object (class instance) or a string (class name).

autoload

Whether to allow this function to load the class automatically through the __autoload() magic method.

Return Values

An array on success, or FALSE on error.

Examples

Example #1 class_uses() example

<?php

trait foo { }
class bar {
  use foo;
}

print_r(class_uses(new bar));

print_r(class_uses('bar'));

function __autoload($class_name) {
   require_once $class_name . '.php';
}

// use __autoload to load the 'not_loaded' class
print_r(class_uses('not_loaded', true));

?>

The above example will output something similar to:

Array
(
    [foo] => foo
)

Array
(
    [foo] => foo
)

Array
(
    [trait_of_not_loaded] => trait_of_not_loaded
)

See Also

  • class_parents() - Return the parent classes of the given class
  • get_declared_traits() - Returns an array of all declared traits


Call a function for every element in an iterator

  • « class_uses
  • iterator_count »
  • PHP Manual
  • SPL Functions
  • Call a function for every element in an iterator

iterator_apply

(PHP 5 >= 5.1.0, PHP 7)

iterator_apply — Call a function for every element in an iterator

Description

iterator_apply ( Traversable $iterator , callable $function [, array $args = NULL ] ) : int

Calls a function for every element in an iterator.

Parameters

iterator

The iterator object to iterate over.

function

The callback function to call on every element. This function only receives the given args, so it is nullary by default. If count($args) === 3, for instance, the callback function is ternary.

Note: The function must return TRUE in order to continue iterating over the iterator.

args

An array of arguments; each element of args is passed to the callback function as separate argument.

Return Values

Returns the iteration count.

Examples

Example #1 iterator_apply() example

<?php
function print_caps(Iterator $iterator) {
    echo strtoupper($iterator->current()) . "\n";
    return TRUE;
}

$it = new ArrayIterator(array("Apples", "Bananas", "Cherries"));
iterator_apply($it, "print_caps", array($it));
?>

The above example will output:

APPLES
BANANAS
CHERRIES

See Also

  • array_walk() - Apply a user supplied function to every member of an array


Count the elements in an iterator

  • « iterator_apply
  • iterator_to_array »
  • PHP Manual
  • SPL Functions
  • Count the elements in an iterator

iterator_count

(PHP 5 >= 5.1.0, PHP 7)

iterator_count — Count the elements in an iterator

Description

iterator_count ( Traversable $iterator ) : int

Count the elements in an iterator. iterator_count() is not guaranteed to retain the current position of the iterator.

Parameters

iterator

The iterator being counted.

Return Values

The number of elements in iterator.

Examples

Example #1 iterator_count() example

<?php
$iterator = new ArrayIterator(array('recipe'=>'pancakes', 'egg', 'milk', 'flour'));
var_dump(iterator_count($iterator));
?>

The above example will output:

int(4)

Example #2 iterator_count() modifies position

<?php
$iterator = new ArrayIterator(['one', 'two', 'three']);
var_dump($iterator->current());
var_dump(iterator_count($iterator));
var_dump($iterator->current());
?>

The above example will output:

string(3) "one"
int(3)
NULL

Example #3 iterator_count() in foreach loops

<?php
$iterator = new ArrayIterator(['one', 'two', 'three']);
foreach ($iterator as $key => $value) {
    echo "$key: $value (", iterator_count($iterator), ")\n";
}?>

The above example will output:

0: one (3)


Copy the iterator into an array

  • « iterator_count
  • spl_autoload_call »
  • PHP Manual
  • SPL Functions
  • Copy the iterator into an array

iterator_to_array

(PHP 5 >= 5.1.0, PHP 7)

iterator_to_array — Copy the iterator into an array

Description

iterator_to_array ( Traversable $iterator [, bool $use_keys = TRUE ] ) : array

Copy the elements of an iterator into an array.

Parameters

iterator

The iterator being copied.

use_keys

Whether to use the iterator element keys as index.

In PHP 5.5 and later, if a key is an array or object, a warning will be generated. NULL keys will be converted to an empty string, float keys will be truncated to their integer counterpart, resource keys will generate a warning and be converted to their resource ID, and boolean keys will be converted to integers.

Note:

If this parameter is not set or set to TRUE, duplicate keys will be overwritten. The last value with a given key will be in the returned array. Set this paramater to FALSE to get all the values in any case.

Return Values

An array containing the elements of the iterator.

Changelog

Version | Description
5.5.0 | iterator_to_array() gained support for key types other than integer and string when the use_keys parameter is enabled.
5.2.1 | The use_keys parameter was added.

Examples

Example #1 iterator_to_array() example

<?php
$iterator = new ArrayIterator(array('recipe'=>'pancakes', 'egg', 'milk', 'flour'));
var_dump(iterator_to_array($iterator, true));
var_dump(iterator_to_array($iterator, false));
?>

The above example will output:

array(4) {
  ["recipe"]=>
  string(8) "pancakes"
  [0]=>
  string(3) "egg"
  [1]=>
  string(4) "milk"
  [2]=>
  string(5) "flour"
}
array(4) {
  [0]=>
  string(8) "pancakes"
  [1]=>
  string(3) "egg"
  [2]=>
  string(4) "milk"
  [3]=>
  string(5) "flour"
}


Try all registered __autoload() functions to load the requested class

  • « iterator_to_array
  • spl_autoload_extensions »
  • PHP Manual
  • SPL Functions
  • Try all registered __autoload() functions to load the requested class

spl_autoload_call

(PHP 5 >= 5.1.0, PHP 7)

spl_autoload_call — Try all registered __autoload() functions to load the requested class

Description

spl_autoload_call ( string $class_name ) : void

This function can be used to manually search for a class or interface using the registered __autoload functions.

Parameters

class_name

The class name being searched.

Return Values

No value is returned.


Register and return default file extensions for spl_autoload

  • « spl_autoload_call
  • spl_autoload_functions »
  • PHP Manual
  • SPL Functions
  • Register and return default file extensions for spl_autoload

spl_autoload_extensions

(PHP 5 >= 5.1.0, PHP 7)

spl_autoload_extensions — Register and return default file extensions for spl_autoload

Description

spl_autoload_extensions ([ string $file_extensions ] ) : string

This function can modify and check the file extensions that the built in __autoload() fallback function spl_autoload() will be using.

Note: There should not be a space between the defined file extensions.

Parameters

file_extensions

When calling without an argument, it simply returns the current list of extensions each separated by comma. To modify the list of file extensions, simply invoke the functions with the new list of file extensions to use in a single string with each extensions separated by comma.

Return Values

A comma delimited list of default file extensions for spl_autoload().

Examples

Example #1 spl_autoload_extensions() example

<?php
spl_autoload_extensions(".php,.inc");
?>


Return all registered __autoload() functions

  • « spl_autoload_extensions
  • spl_autoload_register »
  • PHP Manual
  • SPL Functions
  • Return all registered __autoload() functions

spl_autoload_functions

(PHP 5 >= 5.1.0, PHP 7)

spl_autoload_functions — Return all registered __autoload() functions

Description

spl_autoload_functions ( void ) : array

Get all registered __autoload() functions.

Parameters

This function has no parameters.

Return Values

An array of all registered __autoload functions. If the autoload queue is not activated then the return value is FALSE. If no function is registered the return value will be an empty array.


Register given function as __autoload() implementation

  • « spl_autoload_functions
  • spl_autoload_unregister »
  • PHP Manual
  • SPL Functions
  • Register given function as __autoload() implementation

spl_autoload_register

(PHP 5 >= 5.1.0, PHP 7)

spl_autoload_register — Register given function as __autoload() implementation

Description

spl_autoload_register ([ callable $autoload_function [, bool $throw = TRUE [, bool $prepend = FALSE ]]] ) : bool

Register a function with the spl provided __autoload queue. If the queue is not yet activated it will be activated.

If your code has an existing __autoload() function then this function must be explicitly registered on the __autoload queue. This is because spl_autoload_register() will effectively replace the engine cache for the __autoload() function by either spl_autoload() or spl_autoload_call().

If there must be multiple autoload functions, spl_autoload_register() allows for this. It effectively creates a queue of autoload functions, and runs through each of them in the order they are defined. By contrast, __autoload() may only be defined once.

Parameters

autoload_function

The autoload function being registered. If no parameter is provided, then the default implementation of spl_autoload() will be registered.

throw

This parameter specifies whether spl_autoload_register() should throw exceptions when the autoload_function cannot be registered.

prepend

If true, spl_autoload_register() will prepend the autoloader on the autoload queue instead of appending it.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.3.0 | Namespaces support was introduced.
5.3.0 | The prepend parameter was added.

Examples

Example #1 spl_autoload_register() as a replacement for an __autoload() function

<?php

// function __autoload($class) {
//     include 'classes/' . $class . '.class.php';
// }

function my_autoloader($class) {
    include 'classes/' . $class . '.class.php';
}

spl_autoload_register('my_autoloader');

// Or, using an anonymous function as of PHP 5.3.0
spl_autoload_register(function ($class) {
    include 'classes/' . $class . '.class.php';
});

?>

Example #2 spl_autoload_register() example where the class is not loaded

<?php

namespace Foobar;

class Foo {
    static public function test($name) {
        print '[['. $name .']]';
    }
}

spl_autoload_register(__NAMESPACE__ .'\Foo::test'); // As of PHP 5.3.0

new InexistentClass;

?>

The above example will output something similar to:

[[Foobar\InexistentClass]]
Fatal error: Class 'Foobar\InexistentClass' not found in ...

See Also

  • __autoload() - Attempt to load undefined class


Unregister given function as __autoload() implementation

  • « spl_autoload_register
  • spl_autoload »
  • PHP Manual
  • SPL Functions
  • Unregister given function as __autoload() implementation

spl_autoload_unregister

(PHP 5 >= 5.1.0, PHP 7)

spl_autoload_unregister — Unregister given function as __autoload() implementation

Description

spl_autoload_unregister ( mixed $autoload_function ) : bool

Removes a function from the autoload queue. If the queue is activated and empty after removing the given function then it will be deactivated.

When this function results in the queue being deactivated, any __autoload function that previously existed will not be reactivated.

Parameters

autoload_function

The autoload function being unregistered.

Return Values

Returns TRUE on success or FALSE on failure.


Default implementation for __autoload()

  • « spl_autoload_unregister
  • spl_classes »
  • PHP Manual
  • SPL Functions
  • Default implementation for __autoload()

spl_autoload

(PHP 5 >= 5.1.0, PHP 7)

spl_autoload — Default implementation for __autoload()

Description

spl_autoload ( string $class_name [, string $file_extensions = spl_autoload_extensions() ] ) : void

This function is intended to be used as a default implementation for __autoload(). If nothing else is specified and spl_autoload_register() is called without any parameters then this function will be used for any later call to __autoload().

Parameters

class_name

The lowercased name of the class (and namespace) being instantiated.

file_extensions

By default it checks all include paths to contain filenames built up by the lowercase class name appended by the filename extensions .inc and .php.

Return Values

No value is returned.

Errors/Exceptions

Throws LogicException when the class is not found and there are no other autoloaders registered.


Return available SPL classes

  • « spl_autoload
  • spl_object_hash »
  • PHP Manual
  • SPL Functions
  • Return available SPL classes

spl_classes

(PHP 5, PHP 7)

spl_classes — Return available SPL classes

Description

spl_classes ( void ) : array

This function returns an array with the current available SPL classes.

Parameters

This function has no parameters.

Return Values

Returns an array containing the currently available SPL classes.

Examples

Example #1 spl_classes() example

<?php

print_r(spl_classes());

?>

The above example will output something similar to:

Array
(
    [ArrayObject] => ArrayObject
    [ArrayIterator] => ArrayIterator
    [CachingIterator] => CachingIterator
    [RecursiveCachingIterator] => RecursiveCachingIterator
    [DirectoryIterator] => DirectoryIterator
    [FilterIterator] => FilterIterator
    [LimitIterator] => LimitIterator
    [ParentIterator] => ParentIterator
    [RecursiveDirectoryIterator] => RecursiveDirectoryIterator
    [RecursiveIterator] => RecursiveIterator
    [RecursiveIteratorIterator] => RecursiveIteratorIterator
    [SeekableIterator] => SeekableIterator
    [SimpleXMLIterator] => SimpleXMLIterator
)


Return hash id for given object

  • « spl_classes
  • spl_object_id »
  • PHP Manual
  • SPL Functions
  • Return hash id for given object

spl_object_hash

(PHP 5 >= 5.2.0, PHP 7)

spl_object_hash — Return hash id for given object

Description

spl_object_hash ( object $obj ) : string

This function returns a unique identifier for the object. This id can be used as a hash key for storing objects, or for identifying an object, as long as the object is not destroyed. Once the object is destroyed, its hash may be reused for other objects.

Parameters

object

Any object.

Return Values

A string that is unique for each currently existing object and is always the same for each object.

Examples

Example #1 A spl_object_hash() example

<?php
$id = spl_object_hash($object);
$storage[$id] = $object;
?>

Notes

Note:

When an object is destroyed, its hash may be reused for other objects.


Return the integer object handle for given object

  • « spl_object_hash
  • File Handling »
  • PHP Manual
  • SPL Functions
  • Return the integer object handle for given object

spl_object_id

(PHP 7 >= 7.2.0)

spl_object_id — Return the integer object handle for given object

Description

spl_object_id ( object $obj ) : int

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

object

Any object.

Return Values

An integer identifier that is unique for each currently existing object and is always the same for each object.

Examples

Example #1 A spl_object_id() example

<?php
$id = spl_object_id($object);
$storage[$id] = $object;
?>

Notes

Note:

When an object is destroyed, its id may be reused for other objects.


File Handling

Table of Contents

  • SplFileInfo
  • SplFileObject
  • SplTempFileObject

SPL provides a number of classes to work with files.


The SplFileInfo class

(PHP 5 >= 5.1.2, PHP 7)

Introduction

The SplFileInfo class offers a high-level object oriented interface to information for an individual file.

Class synopsis

SplFileInfo {
/* Methods */
public __construct ( string $file_name )
public getATime ( void ) : int
public getBasename ([ string $suffix ] ) : string
public getCTime ( void ) : int
public getExtension ( void ) : string
public getFileInfo ([ string $class_name ] ) : SplFileInfo
public getFilename ( void ) : string
public getGroup ( void ) : int
public getInode ( void ) : int
public getLinkTarget ( void ) : string
public getMTime ( void ) : int
public getOwner ( void ) : int
public getPath ( void ) : string
public getPathInfo ([ string $class_name ] ) : SplFileInfo
public getPathname ( void ) : string
public getPerms ( void ) : int
public getRealPath ( void ) : string
public getSize ( void ) : int
public getType ( void ) : string
public isDir ( void ) : bool
public isExecutable ( void ) : bool
public isFile ( void ) : bool
public isLink ( void ) : bool
public isReadable ( void ) : bool
public isWritable ( void ) : bool
public openFile ([ string $open_mode = "r" [, bool $use_include_path = FALSE [, resource $context = NULL ]]] ) : SplFileObject
public setFileClass ([ string $class_name = "SplFileObject" ] ) : void
public setInfoClass ([ string $class_name = "SplFileInfo" ] ) : void
public __toString ( void ) : string
}

Table of Contents

  • SplFileInfo::__construct — Construct a new SplFileInfo object
  • SplFileInfo::getATime — Gets last access time of the file
  • SplFileInfo::getBasename — Gets the base name of the file
  • SplFileInfo::getCTime — Gets the inode change time
  • SplFileInfo::getExtension — Gets the file extension
  • SplFileInfo::getFileInfo — Gets an SplFileInfo object for the file
  • SplFileInfo::getFilename — Gets the filename
  • SplFileInfo::getGroup — Gets the file group
  • SplFileInfo::getInode — Gets the inode for the file
  • SplFileInfo::getLinkTarget — Gets the target of a link
  • SplFileInfo::getMTime — Gets the last modified time
  • SplFileInfo::getOwner — Gets the owner of the file
  • SplFileInfo::getPath — Gets the path without filename
  • SplFileInfo::getPathInfo — Gets an SplFileInfo object for the path
  • SplFileInfo::getPathname — Gets the path to the file
  • SplFileInfo::getPerms — Gets file permissions
  • SplFileInfo::getRealPath — Gets absolute path to file
  • SplFileInfo::getSize — Gets file size
  • SplFileInfo::getType — Gets file type
  • SplFileInfo::isDir — Tells if the file is a directory
  • SplFileInfo::isExecutable — Tells if the file is executable
  • SplFileInfo::isFile — Tells if the object references a regular file
  • SplFileInfo::isLink — Tells if the file is a link
  • SplFileInfo::isReadable — Tells if file is readable
  • SplFileInfo::isWritable — Tells if the entry is writable
  • SplFileInfo::openFile — Gets an SplFileObject object for the file
  • SplFileInfo::setFileClass — Sets the class used with SplFileInfo::openFile
  • SplFileInfo::setInfoClass — Sets the class used with SplFileInfo::getFileInfo and SplFileInfo::getPathInfo
  • SplFileInfo::__toString — Returns the path to the file as a string


Construct a new SplFileInfo object

  • « SplFileInfo
  • SplFileInfo::getATime »
  • PHP Manual
  • SplFileInfo
  • Construct a new SplFileInfo object

SplFileInfo::__construct

(PHP 5 >= 5.1.2, PHP 7)

SplFileInfo::__construct — Construct a new SplFileInfo object

Description

public SplFileInfo::__construct ( string $file_name )

Creates a new SplFileInfo object for the file_name specified. The file does not need to exist, or be readable.

Parameters

file_name

Path to the file.

Examples

Example #1 SplFileInfo::__construct() example

<?php
$info = new SplFileInfo('example.php');
if ($info->isFile()) {
    echo $info->getRealPath();
}
?>


Gets last access time of the file

  • « SplFileInfo::__construct
  • SplFileInfo::getBasename »
  • PHP Manual
  • SplFileInfo
  • Gets last access time of the file

SplFileInfo::getATime

(PHP 5 >= 5.1.2, PHP 7)

SplFileInfo::getATime — Gets last access time of the file

Description

public SplFileInfo::getATime ( void ) : int

Gets the last access time for the file.

Parameters

This function has no parameters.

Return Values

Returns the time the file was last accessed.

Errors/Exceptions

Throws RunTimeException on error.

See Also

  • fileatime() - Gets last access time of file


Gets the base name of the file

  • « SplFileInfo::getATime
  • SplFileInfo::getCTime »
  • PHP Manual
  • SplFileInfo
  • Gets the base name of the file

SplFileInfo::getBasename

(PHP 5 >= 5.2.2, PHP 7)

SplFileInfo::getBasename — Gets the base name of the file

Description

public SplFileInfo::getBasename ([ string $suffix ] ) : string

This method returns the base name of the file, directory, or link without path info.

Caution

SplFileInfo::getBasename() 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.

Parameters

suffix

Optional suffix to omit from the base name returned.

Return Values

Returns the base name without path information.

Examples

Example #1 SplFileInfo::getBasename() example

<?php
$info = new SplFileInfo('file.txt');
var_dump($info->getBasename());

$info = new SplFileInfo('/path/to/file.txt');
var_dump($info->getBasename());

$info = new SplFileInfo('/path/to/file.txt');
var_dump($info->getBasename('.txt'));
?>

The above example will output something similar to:

string(8) "file.txt"
string(8) "file.txt"
string(4) "file"

See Also

  • SplFileInfo::getFilename() - Gets the filename


Gets the inode change time

  • « SplFileInfo::getBasename
  • SplFileInfo::getExtension »
  • PHP Manual
  • SplFileInfo
  • Gets the inode change time

SplFileInfo::getCTime

(PHP 5 >= 5.1.2, PHP 7)

SplFileInfo::getCTime — Gets the inode change time

Description

public SplFileInfo::getCTime ( void ) : int

Returns the inode change time for the file. The time returned is a Unix timestamp.

Parameters

This function has no parameters.

Return Values

The last change time, in a Unix timestamp.

Errors/Exceptions

Throws RunTimeException on error.

Examples

Example #1 SplFileInfo::getCTime() example

<?php
$info = new SplFileInfo(__FILE__);
echo 'Last changed at ' . date('g:i a', $info->getCTime());
?>

The above example will output something similar to:

Last changed at 1:49 pm

See Also

  • filectime() - Gets inode change time of file


Gets the file extension

  • « SplFileInfo::getCTime
  • SplFileInfo::getFileInfo »
  • PHP Manual
  • SplFileInfo
  • Gets the file extension

SplFileInfo::getExtension

(PHP 5 >= 5.3.6, PHP 7)

SplFileInfo::getExtension — Gets the file extension

Description

public SplFileInfo::getExtension ( void ) : string

Retrieves the file extension.

Parameters

This function has no parameters.

Return Values

Returns a string containing the file extension, or an empty string if the file has no extension.

Examples

Example #1 SplFileInfo::getExtension() example

<?php

$info = new SplFileInfo('foo.txt');
var_dump($info->getExtension());

$info = new SplFileInfo('photo.jpg');
var_dump($info->getExtension());

$info = new SplFileInfo('something.tar.gz');
var_dump($info->getExtension());

?>

The above example will output:

string(3) "txt"
string(3) "jpg"
string(2) "gz"

Notes

Note:

This method is only available as of PHP 5.3.6. Another way of getting the extension is to use the pathinfo() function.

<?php
$extension = pathinfo($info->getFilename(), PATHINFO_EXTENSION);
?>

See Also

  • SplFileInfo::getFilename() - Gets the filename
  • SplFileInfo::getBasename() - Gets the base name of the file
  • pathinfo() - Returns information about a file path


Gets an SplFileInfo object for the file

  • « SplFileInfo::getExtension
  • SplFileInfo::getFilename »
  • PHP Manual
  • SplFileInfo
  • Gets an SplFileInfo object for the file

SplFileInfo::getFileInfo

(PHP 5 >= 5.1.2, PHP 7)

SplFileInfo::getFileInfo — Gets an SplFileInfo object for the file

Description

public SplFileInfo::getFileInfo ([ string $class_name ] ) : SplFileInfo

This method gets an SplFileInfo object for the referenced file.

Parameters

class_name

Name of an SplFileInfo derived class to use.

Return Values

An SplFileInfo object created for the file.

See Also

  • SplFileInfo::setInfoClass() - Sets the class used with SplFileInfo::getFileInfo and SplFileInfo::getPathInfo


Gets the filename

  • « SplFileInfo::getFileInfo
  • SplFileInfo::getGroup »
  • PHP Manual
  • SplFileInfo
  • Gets the filename

SplFileInfo::getFilename

(PHP 5 >= 5.1.2, PHP 7)

SplFileInfo::getFilename — Gets the filename

Description

public SplFileInfo::getFilename ( void ) : string

Gets the filename without any path information.

Parameters

This function has no parameters.

Return Values

The filename.

Examples

Example #1 SplFileInfo::getFilename() example

<?php
$info = new SplFileInfo('foo.txt');
var_dump($info->getFilename());

$info = new SplFileInfo('/path/to/foo.txt');
var_dump($info->getFilename());

$info = new SplFileInfo('http://www.php.net/');
var_dump($info->getFilename());

$info = new SplFileInfo('http://www.php.net/svn.php');
var_dump($info->getFilename());
?>

The above example will output something similar to:

string(7) "foo.txt"
string(7) "foo.txt"
string(0) ""
string(7) "svn.php"

See Also

  • SplFileInfo::getBasename() - Gets the base name of the file


Gets the file group

  • « SplFileInfo::getFilename
  • SplFileInfo::getInode »
  • PHP Manual
  • SplFileInfo
  • Gets the file group

SplFileInfo::getGroup

(PHP 5 >= 5.1.2, PHP 7)

SplFileInfo::getGroup — Gets the file group

Description

public SplFileInfo::getGroup ( void ) : int

Gets the file group. The group ID is returned in numerical format.

Parameters

This function has no parameters.

Return Values

The group id in numerical format.

Errors/Exceptions

Throws RuntimeException on error.

Examples

Example #1 SplFileInfo::getGroup() example

<?php
$info = new SplFileInfo(__FILE__);
print_r(posix_getgrgid($info->getGroup()));
?>

The above example will output something similar to:

See Also

  • posix_getgrgid() - Return info about a group by group id


Gets the inode for the file

  • « SplFileInfo::getGroup
  • SplFileInfo::getLinkTarget »
  • PHP Manual
  • SplFileInfo
  • Gets the inode for the file

SplFileInfo::getInode

(PHP 5 >= 5.1.2, PHP 7)

SplFileInfo::getInode — Gets the inode for the file

Description

public SplFileInfo::getInode ( void ) : int

Gets the inode number for the filesystem object.

Parameters

This function has no parameters.

Return Values

Returns the inode number for the filesystem object.

Errors/Exceptions

Throws RuntimeException on error.

See Also

  • fileinode() - Gets file inode


Gets the target of a link

  • « SplFileInfo::getInode
  • SplFileInfo::getMTime »
  • PHP Manual
  • SplFileInfo
  • Gets the target of a link

SplFileInfo::getLinkTarget

(PHP 5 >= 5.2.2, PHP 7)

SplFileInfo::getLinkTarget — Gets the target of a link

Description

public SplFileInfo::getLinkTarget ( void ) : string

Gets the target of a filesystem link.

Note:

The target may not be the real path on the filesystem. Use SplFileInfo::getRealPath() to determine the true path on the filesystem.

Parameters

This function has no parameters.

Return Values

Returns the target of the filesystem link.

Errors/Exceptions

Throws RuntimeException on error.

Examples

Example #1 SplFileInfo::getLinkTarget() example

<?php
$info = new SplFileInfo('/Users/bbieber/workspace');
if ($info->isLink()) {
    var_dump($info->getLinkTarget());
    var_dump($info->getRealPath());
}
?>

The above example will output something similar to:

string(19) "Documents/workspace"
string(34) "/Users/bbieber/Documents/workspace"

See Also

  • SplFileInfo::isLink() - Tells if the file is a link
  • SplFileInfo::getRealPath() - Gets absolute path to file


Gets the last modified time

  • « SplFileInfo::getLinkTarget
  • SplFileInfo::getOwner »
  • PHP Manual
  • SplFileInfo
  • Gets the last modified time

SplFileInfo::getMTime

(PHP 5 >= 5.1.2, PHP 7)

SplFileInfo::getMTime — Gets the last modified time

Description

public SplFileInfo::getMTime ( void ) : int

Returns the time when the contents of the file were changed. The time returned is a Unix timestamp.

Parameters

This function has no parameters.

Return Values

Returns the last modified time for the file, in a Unix timestamp.

See Also

  • filemtime() - Gets file modification time


Gets the owner of the file

  • « SplFileInfo::getMTime
  • SplFileInfo::getPath »
  • PHP Manual
  • SplFileInfo
  • Gets the owner of the file

SplFileInfo::getOwner

(PHP 5 >= 5.1.2, PHP 7)

SplFileInfo::getOwner — Gets the owner of the file

Description

public SplFileInfo::getOwner ( void ) : int

Gets the file owner. The owner ID is returned in numerical format.

Parameters

This function has no parameters.

Return Values

The owner id in numerical format.

Errors/Exceptions

Throws RuntimeException on error.

Examples

Example #1 SplFileInfo::getOwner() example

<?php
$info = new SplFileInfo('file.txt');
print_r(posix_getpwuid($info->getOwner()));
?>

See Also

  • posix_getpwuid() - Return info about a user by user id
  • SplFileInfo::getGroup() - Gets the file group


Gets the path without filename

  • « SplFileInfo::getOwner
  • SplFileInfo::getPathInfo »
  • PHP Manual
  • SplFileInfo
  • Gets the path without filename

SplFileInfo::getPath

(PHP 5 >= 5.1.2, PHP 7)

SplFileInfo::getPath — Gets the path without filename

Description

public SplFileInfo::getPath ( void ) : string

Returns the path to the file, omitting the filename and any trailing slash.

Parameters

This function has no parameters.

Return Values

Returns the path to the file.

Examples

Example #1 SplFileInfo::getPath() example

<?php
$info = new SplFileInfo('/usr/bin/php');
var_dump($info->getPath());

$info = new SplFileInfo('/usr/');
var_dump($info->getPath());?>

The above example will output something similar to:

string(8) "/usr/bin"
string(4) "/usr"

See Also

  • SplFileInfo::getRealPath() - Gets absolute path to file
  • SplFileInfo::getFilename() - Gets the filename
  • SplFileInfo::getPathInfo() - Gets an SplFileInfo object for the path


Gets an SplFileInfo object for the path

  • « SplFileInfo::getPath
  • SplFileInfo::getPathname »
  • PHP Manual
  • SplFileInfo
  • Gets an SplFileInfo object for the path

SplFileInfo::getPathInfo

(PHP 5 >= 5.1.2, PHP 7)

SplFileInfo::getPathInfo — Gets an SplFileInfo object for the path

Description

public SplFileInfo::getPathInfo ([ string $class_name ] ) : SplFileInfo

Gets an SplFileInfo object for the parent of the current file.

Parameters

class_name

Name of an SplFileInfo derived class to use.

Return Values

Returns an SplFileInfo object for the parent path of the file.

Examples

Example #1 SplFileInfo::getPathInfo() example

<?php
$info = new SplFileInfo('/usr/bin/php');
$parent_info = $info->getPathInfo();
var_dump($parent_info->getRealPath());
?>

The above example will output something similar to:

string(8) "/usr/bin"

See Also

  • SplFileInfo::setInfoClass() - Sets the class used with SplFileInfo::getFileInfo and SplFileInfo::getPathInfo


Gets the path to the file

  • « SplFileInfo::getPathInfo
  • SplFileInfo::getPerms »
  • PHP Manual
  • SplFileInfo
  • Gets the path to the file

SplFileInfo::getPathname

(PHP 5 >= 5.1.2, PHP 7)

SplFileInfo::getPathname — Gets the path to the file

Description

public SplFileInfo::getPathname ( void ) : string

Returns the path to the file.

Parameters

This function has no parameters.

Return Values

The path to the file.

Examples

Example #1 SplFileInfo::getPathname() example

<?php
$info = new SplFileInfo('/usr/bin/php');
var_dump($info->getPathname());
?>

The above example will output something similar to:

string(12) "/usr/bin/php"

See Also

  • SplFileInfo::getRealPath() - Gets absolute path to file


Gets file permissions

  • « SplFileInfo::getPathname
  • SplFileInfo::getRealPath »
  • PHP Manual
  • SplFileInfo
  • Gets file permissions

SplFileInfo::getPerms

(PHP 5 >= 5.1.2, PHP 7)

SplFileInfo::getPerms — Gets file permissions

Description

public SplFileInfo::getPerms ( void ) : int

Gets the file permissions for the file.

Parameters

This function has no parameters.

Return Values

Returns the file permissions.

Examples

Example #1 SplFileInfo::getPerms() example

<?php
$info = new SplFileInfo('/tmp');
echo substr(sprintf('%o', $info->getPerms()), -4);

$info = new SplFileInfo(__FILE__);
echo substr(sprintf('%o', $info->getPerms()), -4);
?>

The above example will output something similar to:

1777
0644


Gets absolute path to file

  • « SplFileInfo::getPerms
  • SplFileInfo::getSize »
  • PHP Manual
  • SplFileInfo
  • Gets absolute path to file

SplFileInfo::getRealPath

(PHP 5 >= 5.2.2, PHP 7)

SplFileInfo::getRealPath — Gets absolute path to file

Description

public SplFileInfo::getRealPath ( void ) : string

This method expands all symbolic links, resolves relative references and returns the real path to the file.

Parameters

This function has no parameters.

Return Values

Returns the path to the file, or FALSE if the file does not exist.

Examples

Example #1 SplFileInfo::getRealPath() example

<?php
$info = new SplFileInfo('/..//./../../'.__FILE__);
var_dump($info->getRealPath());

$info = new SplFileInfo('/tmp');
var_dump($info->getRealPath());

$info = new SplFileInfo('/I/Do/Not/Exist');
var_dump($info->getRealPath());

$info = new SplFileInfo('php://output');
var_dump($info->getRealPath());

$info = new SplFileInfo("");
var_dump($info->getRealPath());
?>

The above example will output something similar to:

string(28) "/private/tmp/phptempfile.php"
string(12) "/private/tmp"
bool(false)
bool(false)
string(12) "/private/tmp"

See Also

  • SplFileInfo::isLink() - Tells if the file is a link
  • realpath() - Returns canonicalized absolute pathname


Gets file size

  • « SplFileInfo::getRealPath
  • SplFileInfo::getType »
  • PHP Manual
  • SplFileInfo
  • Gets file size

SplFileInfo::getSize

(PHP 5 >= 5.1.2, PHP 7)

SplFileInfo::getSize — Gets file size

Description

public SplFileInfo::getSize ( void ) : int

Returns the filesize in bytes for the file referenced.

Parameters

This function has no parameters.

Return Values

The filesize in bytes.

Errors/Exceptions

A RuntimeException will be thrown if the file does not exist or an error occurs.

See Also

  • filesize() - Gets file size


Gets file type

  • « SplFileInfo::getSize
  • SplFileInfo::isDir »
  • PHP Manual
  • SplFileInfo
  • Gets file type

SplFileInfo::getType

(PHP 5 >= 5.1.2, PHP 7)

SplFileInfo::getType — Gets file type

Description

public SplFileInfo::getType ( void ) : string

Returns the type of the file referenced.

Parameters

This function has no parameters.

Return Values

A string representing the type of the entry. May be one of file, link, or dir

Errors/Exceptions

Throws a RuntimeException on error.

Examples

Example #1 SplFileInfo::getType() example

<?php

$info = new SplFileInfo(__FILE__);
echo $info->getType().PHP_EOL;

$info = new SplFileInfo(dirname(__FILE__));
echo $info->getType();

?>

The above example will output something similar to:

file
dir


Tells if the file is a directory

  • « SplFileInfo::getType
  • SplFileInfo::isExecutable »
  • PHP Manual
  • SplFileInfo
  • Tells if the file is a directory

SplFileInfo::isDir

(PHP 5 >= 5.1.2, PHP 7)

SplFileInfo::isDir — Tells if the file is a directory

Description

public SplFileInfo::isDir ( void ) : bool

This method can be used to determine if the file is a directory.

Parameters

This function has no parameters.

Return Values

Returns TRUE if a directory, FALSE otherwise.

Examples

Example #1 SplFileInfo::isDir() example

<?php
$d = new SplFileInfo(dirname(__FILE__));
var_dump($d->isDir());

$d = new SplFileInfo(__FILE__);
var_dump($d->isDir());
?>

The above example will output something similar to:

bool(true)
bool(false)


Tells if the file is executable

  • « SplFileInfo::isDir
  • SplFileInfo::isFile »
  • PHP Manual
  • SplFileInfo
  • Tells if the file is executable

SplFileInfo::isExecutable

(PHP 5 >= 5.1.2, PHP 7)

SplFileInfo::isExecutable — Tells if the file is executable

Description

public SplFileInfo::isExecutable ( void ) : bool

Checks if the file is executable.

Parameters

This function has no parameters.

Return Values

Returns TRUE if executable, FALSE otherwise.

Examples

Example #1 SplFileInfo::isExecutable() example

<?php
$info = new SplFileInfo('/usr/bin/php');
var_dump($info->isExecutable());

$info = new SplFileInfo('/usr/bin');
var_dump($info->isExecutable());

$info = new SplFileInfo('foo');
var_dump($info->isExecutable());
?>

The above example will output something similar to:

bool(true)
bool(true)
bool(false)


Tells if the object references a regular file

  • « SplFileInfo::isExecutable
  • SplFileInfo::isLink »
  • PHP Manual
  • SplFileInfo
  • Tells if the object references a regular file

SplFileInfo::isFile

(PHP 5 >= 5.1.2, PHP 7)

SplFileInfo::isFile — Tells if the object references a regular file

Description

public SplFileInfo::isFile ( void ) : bool

Checks if the file referenced by this SplFileInfo object exists and is a regular file.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the file exists and is a regular file (not a link), FALSE otherwise.

Examples

Example #1 SplFileInfo::isFile() example

<?php
$info = new SplFileInfo(__FILE__);
var_dump($info->isFile());

$info = new SplFileInfo(dirname(__FILE__));
var_dump($info->isFile());
?>

The above example will output something similar to:

bool(true)
bool(false)


Tells if the file is a link

  • « SplFileInfo::isFile
  • SplFileInfo::isReadable »
  • PHP Manual
  • SplFileInfo
  • Tells if the file is a link

SplFileInfo::isLink

(PHP 5 >= 5.1.2, PHP 7)

SplFileInfo::isLink — Tells if the file is a link

Description

public SplFileInfo::isLink ( void ) : bool

Use this method to check if the file referenced by the SplFileInfo object is a link.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the file is a link, FALSE otherwise.

Examples

Example #1 SplFileInfo::isLink() example

<?php
$info = new SplFileInfo('/path/to/symlink');
if ($info->isLink()) {
    echo 'The real path is '.$info->getRealPath();
}
?>

See Also

  • SplFileInfo::getRealPath() - Gets absolute path to file


Tells if file is readable

  • « SplFileInfo::isLink
  • SplFileInfo::isWritable »
  • PHP Manual
  • SplFileInfo
  • Tells if file is readable

SplFileInfo::isReadable

(PHP 5 >= 5.1.2, PHP 7)

SplFileInfo::isReadable — Tells if file is readable

Description

public SplFileInfo::isReadable ( void ) : bool

Check if the file is readable.

Parameters

This function has no parameters.

Return Values

Returns TRUE if readable, FALSE otherwise.

Examples

Example #1 SplFileInfo::isReadable() example

<?php
$info = new SplFileInfo(__FILE__);
var_dump($info->isReadable());

$info = new SplFileInfo('foo');
var_dump($info->isReadable());
?>

The above example will output something similar to:

bool(true)
bool(false)


Tells if the entry is writable

  • « SplFileInfo::isReadable
  • SplFileInfo::openFile »
  • PHP Manual
  • SplFileInfo
  • Tells if the entry is writable

SplFileInfo::isWritable

(PHP 5 >= 5.1.2, PHP 7)

SplFileInfo::isWritable — Tells if the entry is writable

Description

public SplFileInfo::isWritable ( void ) : bool

Checks if the current entry is writable.

Parameters

This function has no parameters.

Return Values

Returns TRUE if writable, FALSE otherwise;


Gets an SplFileObject object for the file

  • « SplFileInfo::isWritable
  • SplFileInfo::setFileClass »
  • PHP Manual
  • SplFileInfo
  • Gets an SplFileObject object for the file

SplFileInfo::openFile

(PHP 5 >= 5.1.2, PHP 7)

SplFileInfo::openFile — Gets an SplFileObject object for the file

Description

public SplFileInfo::openFile ([ string $open_mode = "r" [, bool $use_include_path = FALSE [, resource $context = NULL ]]] ) : SplFileObject

Creates an SplFileObject object of the file. This is useful because SplFileObject contains additional methods for manipulating the file whereas SplFileInfo is only useful for gaining information, like whether the file is writable.

Parameters

open_mode

The mode for opening the file. See the fopen() documentation for descriptions of possible modes. The default is read only.

use_include_path

When set to TRUE, the filename is also searched for within the include_path

context

Refer to the context section of the manual for a description of contexts.

Return Values

The opened file as an SplFileObject object.

Errors/Exceptions

A RuntimeException if the file cannot be opened (e.g. insufficient access rights).

Examples

Example #1 SplFileInfo::openFile() example

<?php
$fileinfo = new SplFileInfo('/tmp/foo.txt');

if ($fileinfo->isWritable()) {

    $fileobj = $fileinfo->openFile('a');

    $fileobj->fwrite("appended this sample text");
}
?>

See Also

  • SplFileObject
  • stream_context_create() - Creates a stream context
  • fopen() - Opens file or URL


Sets the class used with SplFileInfo::openFile

  • « SplFileInfo::openFile
  • SplFileInfo::setInfoClass »
  • PHP Manual
  • SplFileInfo
  • Sets the class used with SplFileInfo::openFile

SplFileInfo::setFileClass

(PHP 5 >= 5.1.2, PHP 7)

SplFileInfo::setFileClass — Sets the class used with SplFileInfo::openFile()

Description

public SplFileInfo::setFileClass ([ string $class_name = "SplFileObject" ] ) : void

Use this method to set a custom class which will be used when SplFileInfo::openFile() is called. The class name passed to this method must be SplFileObject or a class derived from SplFileObject.

Parameters

class_name

The class name to use when SplFileInfo::openFile() is called.

Return Values

No value is returned.

Examples

Example #1 SplFileInfo::setFileClass() example

<?php
// Create a class extending SplFileObject
class MyFoo extends SplFileObject {}

$info = new SplFileInfo(__FILE__);
// Set the class to use
$info->setFileClass('MyFoo');
var_dump($info->openFile());
?>

The above example will output something similar to:

object(MyFoo)#2 (0) { }

See Also

  • SplFileInfo::openFile() - Gets an SplFileObject object for the file


Sets the class used with SplFileInfo::getFileInfo and SplFileInfo::getPathInfo

  • « SplFileInfo::setFileClass
  • SplFileInfo::__toString »
  • PHP Manual
  • SplFileInfo
  • Sets the class used with SplFileInfo::getFileInfo and SplFileInfo::getPathInfo

SplFileInfo::setInfoClass

(PHP 5 >= 5.1.2, PHP 7)

SplFileInfo::setInfoClass — Sets the class used with SplFileInfo::getFileInfo() and SplFileInfo::getPathInfo()

Description

public SplFileInfo::setInfoClass ([ string $class_name = "SplFileInfo" ] ) : void

Use this method to set a custom class which will be used when SplFileInfo::getFileInfo() and SplFileInfo::getPathInfo() are called. The class name passed to this method must be SplFileInfo or a class derived from SplFileInfo.

Parameters

class_name

The class name to use when SplFileInfo::getFileInfo() and SplFileInfo::getPathInfo() are called.

Return Values

No value is returned.

Examples

Example #1 SplFileInfo::setFileClass() example

<?php
// Define a class which extends SplFileInfo
class MyFoo extends SplFileInfo {}

$info = new SplFileInfo('foo');
// Set the class name to use
$info->setInfoClass('MyFoo');
var_dump($info->getFileInfo());
?>

The above example will output something similar to:

object(MyFoo)#2 (0) { }

See Also

  • SplFileInfo::getFileInfo() - Gets an SplFileInfo object for the file


Returns the path to the file as a string

  • « SplFileInfo::setInfoClass
  • SplFileObject »
  • PHP Manual
  • SplFileInfo
  • Returns the path to the file as a string

SplFileInfo::__toString

(PHP 5 >= 5.1.2, PHP 7)

SplFileInfo::__toString — Returns the path to the file as a string

Description

public SplFileInfo::__toString ( void ) : string

This method will return the file name of the referenced file.

Parameters

This function has no parameters.

Return Values

Returns the path to the file.

Examples

Example #1 SplFileInfo::__toString() example

<?php
$info = new SplFileInfo('foo');
var_dump($info->__toString());
echo $info.PHP_EOL;

$info = new SplFileInfo('/usr/bin/php');
var_dump($info->__toString());
echo $info.PHP_EOL;
?>

The above example will output something similar to:

string(3) "foo"
foo
string(12) "/usr/bin/php"
/usr/bin/php


The SplFileObject class

(PHP 5 >= 5.1.0, PHP 7)

Introduction

The SplFileObject class offers an object oriented interface for a file.

Class synopsis

SplFileObject extends SplFileInfo implements RecursiveIterator , SeekableIterator {
/* Constants */
const integer DROP_NEW_LINE = 1 ;
const integer READ_AHEAD = 2 ;
const integer SKIP_EMPTY = 4 ;
const integer READ_CSV = 8 ;
/* Methods */
public __construct ( string $filename [, string $open_mode = "r" [, bool $use_include_path = FALSE [, resource $context ]]] )
public current ( void ) : string|array
public eof ( void ) : bool
public fflush ( void ) : bool
public fgetc ( void ) : string
 public fgetcsv
  ([ string $delimiter = ","
 [, string $enclosure = "\""
 [, string $escape = "\\"
]]] ) : array
public fgets ( void ) : string
public fgetss ([ string $allowable_tags ] ) : string
public flock ( int $operation [, int &$wouldblock ] ) : bool
public fpassthru ( void ) : int
public fputcsv ( array $fields [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\\" ]]] ) : int
public fread ( int $length ) : string
public fscanf ( string $format [, mixed &$... ] ) : mixed
public fseek ( int $offset [, int $whence = SEEK_SET ] ) : int
public fstat ( void ) : array
public ftell ( void ) : int
public ftruncate ( int $size ) : bool
public fwrite ( string $str [, int $length ] ) : int
public getChildren ( void ) : void
public getCsvControl ( void ) : array
public getFlags ( void ) : int
public getMaxLineLen ( void ) : int
public hasChildren ( void ) : bool
public key ( void ) : int
public next ( void ) : void
public rewind ( void ) : void
public seek ( int $line_pos ) : void
 public setCsvControl
  ([ string $delimiter = ","
 [, string $enclosure = "\""
 [, string $escape = "\\"
]]] ) : void
public setFlags ( int $flags ) : void
public setMaxLineLen ( int $max_len ) : void
public valid ( void ) : bool
/* Inherited methods */
public SplFileInfo::getATime ( void ) : int
public SplFileInfo::getBasename ([ string $suffix ] ) : string
public SplFileInfo::getCTime ( void ) : int
public SplFileInfo::getExtension ( void ) : string
public SplFileInfo::getFileInfo ([ string $class_name ] ) : SplFileInfo
public SplFileInfo::getFilename ( void ) : string
public SplFileInfo::getGroup ( void ) : int
public SplFileInfo::getInode ( void ) : int
public SplFileInfo::getLinkTarget ( void ) : string
public SplFileInfo::getMTime ( void ) : int
public SplFileInfo::getOwner ( void ) : int
public SplFileInfo::getPath ( void ) : string
public SplFileInfo::getPathInfo ([ string $class_name ] ) : SplFileInfo
public SplFileInfo::getPathname ( void ) : string
public SplFileInfo::getPerms ( void ) : int
public SplFileInfo::getRealPath ( void ) : string
public SplFileInfo::getSize ( void ) : int
public SplFileInfo::getType ( void ) : string
public SplFileInfo::isDir ( void ) : bool
public SplFileInfo::isExecutable ( void ) : bool
public SplFileInfo::isFile ( void ) : bool
public SplFileInfo::isLink ( void ) : bool
public SplFileInfo::isReadable ( void ) : bool
public SplFileInfo::isWritable ( void ) : bool
public SplFileInfo::openFile ([ string $open_mode = "r" [, bool $use_include_path = FALSE [, resource $context = NULL ]]] ) : SplFileObject
public SplFileInfo::setFileClass ([ string $class_name = "SplFileObject" ] ) : void
public SplFileInfo::setInfoClass ([ string $class_name = "SplFileInfo" ] ) : void
public SplFileInfo::__toString ( void ) : string
}

Predefined Constants

SplFileObject::DROP_NEW_LINE

Drop newlines at the end of a line.

SplFileObject::READ_AHEAD

Read on rewind/next.

SplFileObject::SKIP_EMPTY

Skips empty lines in the file. This requires the READ_AHEAD flag be enabled, to work as expected.

SplFileObject::READ_CSV

Read lines as CSV rows.

Changelog

Version | Description
5.3.9 | SplFileObject::SKIP_EMPTY value changed to 4. Previously, value was 6.

Table of Contents

  • SplFileObject::__construct — Construct a new file object
  • SplFileObject::current — Retrieve current line of file
  • SplFileObject::eof — Reached end of file
  • SplFileObject::fflush — Flushes the output to the file
  • SplFileObject::fgetc — Gets character from file
  • SplFileObject::fgetcsv — Gets line from file and parse as CSV fields
  • SplFileObject::fgets — Gets line from file
  • SplFileObject::fgetss — Gets line from file and strip HTML tags
  • SplFileObject::flock — Portable file locking
  • SplFileObject::fpassthru — Output all remaining data on a file pointer
  • SplFileObject::fputcsv — Write a field array as a CSV line
  • SplFileObject::fread — Read from file
  • SplFileObject::fscanf — Parses input from file according to a format
  • SplFileObject::fseek — Seek to a position
  • SplFileObject::fstat — Gets information about the file
  • SplFileObject::ftell — Return current file position
  • SplFileObject::ftruncate — Truncates the file to a given length
  • SplFileObject::fwrite — Write to file
  • SplFileObject::getChildren — No purpose
  • SplFileObject::getCsvControl — Get the delimiter, enclosure and escape character for CSV
  • SplFileObject::getCurrentLine — Alias of SplFileObject::fgets
  • SplFileObject::getFlags — Gets flags for the SplFileObject
  • SplFileObject::getMaxLineLen — Get maximum line length
  • SplFileObject::hasChildren — SplFileObject does not have children
  • SplFileObject::key — Get line number
  • SplFileObject::next — Read next line
  • SplFileObject::rewind — Rewind the file to the first line
  • SplFileObject::seek — Seek to specified line
  • SplFileObject::setCsvControl — Set the delimiter, enclosure and escape character for CSV
  • SplFileObject::setFlags — Sets flags for the SplFileObject
  • SplFileObject::setMaxLineLen — Set maximum line length
  • SplFileObject::__toString — Alias of SplFileObject::fgets
  • SplFileObject::valid — Not at EOF


Construct a new file object

  • « SplFileObject
  • SplFileObject::current »
  • PHP Manual
  • SplFileObject
  • Construct a new file object

SplFileObject::__construct

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::__construct — Construct a new file object

Description

public SplFileObject::__construct ( string $filename [, string $open_mode = "r" [, bool $use_include_path = FALSE [, resource $context ]]] )

Construct a new file object.

Parameters

filename

The file to 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.

open_mode

The mode in which to open the file. See fopen() for a list of allowed modes.

use_include_path

Whether to search in the include_path for filename.

context

A valid context resource created with stream_context_create().

Return Values

No value is returned.

Errors/Exceptions

Throws a RuntimeException if the filename cannot be opened.

Throws a LogicException if the filename is a directory.

Examples

Example #1 SplFileObject::__construct() example

This example opens the current file and iterates over its contents line by line.

<?php
$file = new SplFileObject(__FILE__);
foreach ($file as $line_num => $line) {
    echo "Line $line_num is $line";
}
?>

The above example will output something similar to:

Line 0 is <?php
Line 1 is $file = new SplFileObject(__FILE__);
Line 2 is foreach ($file as $line_num => $line) {
Line 3 is     echo "Line $line_num is $line";
Line 4 is }
Line 5 is ?>

See Also

  • SplFileInfo::openFile() - Gets an SplFileObject object for the file
  • fopen() - Opens file or URL


Retrieve current line of file

  • « SplFileObject::__construct
  • SplFileObject::eof »
  • PHP Manual
  • SplFileObject
  • Retrieve current line of file

SplFileObject::current

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::current — Retrieve current line of file

Description

public SplFileObject::current ( void ) : string|array

Retrieves the current line of the file.

Parameters

This function has no parameters.

Return Values

Retrieves the current line of the file. If the SplFileObject::READ_CSV flag is set, this method returns an array containing the current line parsed as CSV data.

Examples

Example #1 SplFileObject::current() example

<?php
$file = new SplFileObject(__FILE__);
foreach ($file as $k => $line) {
   echo ($file->key() + 1) . ': ' . $file->current();
}
?>

The above example will output something similar to:

1: <?php
2: $file = new SplFileObject(__FILE__);
3: foreach ($file as $line) {
4:     echo ($file->key() + 1) . ': ' . $file->current();
5: }
6: ?>

See Also

  • SplFileObject::key() - Get line number
  • SplFileObject::seek() - Seek to specified line
  • SplFileObject::next() - Read next line
  • SplFileObject::rewind() - Rewind the file to the first line
  • SplFileObject::valid() - Not at EOF


Reached end of file

  • « SplFileObject::current
  • SplFileObject::fflush »
  • PHP Manual
  • SplFileObject
  • Reached end of file

SplFileObject::eof

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::eof — Reached end of file

Description

public SplFileObject::eof ( void ) : bool

Determine whether the end of file has been reached

Parameters

This function has no parameters.

Return Values

Returns TRUE if file is at EOF, FALSE otherwise.

Examples

Example #1 SplFileObject::eof() example

<?php
$file = new SplFileObject("fruits.txt");
while ( ! $file->eof()) {
    echo $file->fgets();
}
?>

The above example will output something similar to:

apple
banana
cherry
date
elderberry

See Also

  • SplFileObject::valid() - Not at EOF
  • feof() - Tests for end-of-file on a file pointer


Flushes the output to the file

  • « SplFileObject::eof
  • SplFileObject::fgetc »
  • PHP Manual
  • SplFileObject
  • Flushes the output to the file

SplFileObject::fflush

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::fflush — Flushes the output to the file

Description

public SplFileObject::fflush ( void ) : bool

Forces a write of all buffered output to the file.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 SplFileObject::fflush() example

<?php
$file = new SplFileObject('misc.txt', 'r+');
$file->rewind();
$file->fwrite("Foo");
$file->fflush();
$file->ftruncate($file->ftell());
?>

See Also

  • SplFileObject::fwrite() - Write to file


Gets character from file

  • « SplFileObject::fflush
  • SplFileObject::fgetcsv »
  • PHP Manual
  • SplFileObject
  • Gets character from file

SplFileObject::fgetc

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::fgetc — Gets character from file

Description

public SplFileObject::fgetc ( void ) : string

Gets a character from the file.

Parameters

This function has no parameters.

Return Values

Returns a string containing a single character read from the file or 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 SplFileObject::fgetc() example

<?php
$file = new SplFileObject('file.txt');
while (false !== ($char = $file->fgetc())) {
    echo "$char\n";
}
?>

See Also

  • SplFileObject::fgets() - Gets line from file


Gets line from file and parse as CSV fields

  • « SplFileObject::fgetc
  • SplFileObject::fgets »
  • PHP Manual
  • SplFileObject
  • Gets line from file and parse as CSV fields

SplFileObject::fgetcsv

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::fgetcsv — Gets line from file and parse as CSV fields

Description

 public SplFileObject::fgetcsv
  ([ string $delimiter = ","
 [, string $enclosure = "\""
 [, string $escape = "\\"
]]] ) : array

Gets a line from the file which is in CSV format and returns an array containing the fields read.

Note:

The locale settings are taken into account by this function. If LC_CTYPE is e.g. en_US.UTF-8, files in one-byte encodings may be read wrongly by this function.

Parameters

delimiter

The field delimiter (one character only). Defaults as a comma or the value set using SplFileObject::setCsvControl().

enclosure

The field enclosure character (one character only). Defaults as a double quotation mark or the value set using SplFileObject::setCsvControl().

escape

The escape character (at most one character). Defaults as a backslash (\) or the value set using SplFileObject::setCsvControl(). An empty string ("") disables the proprietary escape mechanism.

Note: Usually an enclosure character is escpaped inside a field by doubling it; however, the escape character can be used as an alternative. So for the default parameter values "" and \" have the same meaning. Other than allowing to escape the enclosure character the escape character has no special meaning; it isn't even meant to escape itself.

Return Values

Returns an indexed array containing the fields read, or FALSE on error.

Note:

A blank line in a CSV file will be returned as an array comprising a single NULL field unless using SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE, in which case empty lines are skipped.

Changelog

Version | Description
7.4.0 | The escape parameter now also accepts an empty string to disable the proprietary escape mechanism.

Examples

Example #1 SplFileObject::fgetcsv() example

<?php
$file = new SplFileObject("data.csv");
while (!$file->eof()) {
    var_dump($file->fgetcsv());
}
?>

Example #2 SplFileObject::READ_CSV example

<?php
$file = new SplFileObject("animals.csv");
$file->setFlags(SplFileObject::READ_CSV);
foreach ($file as $row) {
    list($animal, $class, $legs) = $row;
    printf("A %s is a %s with %d legs\n", $animal, $class, $legs);
}
?>

Contents of animals.csv

crocodile,reptile,4
dolphin,mammal,0
duck,bird,2
koala,mammal,4
salmon,fish,0

The above example will output something similar to:

A crocodile is a reptile with 4 legs
A dolphin is a mammal with 0 legs
A duck is a bird with 2 legs
A koala is a mammal with 4 legs
A salmon is a fish with 0 legs

See Also

  • SplFileObject::setCsvControl() - Set the delimiter, enclosure and escape character for CSV
  • SplFileObject::setFlags() - Sets flags for the SplFileObject
  • SplFileObject::READ_CSV
  • SplFileObject::current() - Retrieve current line of file


Gets line from file

  • « SplFileObject::fgetcsv
  • SplFileObject::fgetss »
  • PHP Manual
  • SplFileObject
  • Gets line from file

SplFileObject::fgets

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::fgets — Gets line from file

Description

public SplFileObject::fgets ( void ) : string

Gets a line from the file.

Parameters

This function has no parameters.

Return Values

Returns a string containing the next line from the file, or FALSE on error.

Errors/Exceptions

Throws a RuntimeException if the file cannot be read.

Examples

Example #1 SplFileObject::fgets() example

This example simply outputs the contents of file.txt line-by-line.

<?php
$file = new SplFileObject("file.txt");
while (!$file->eof()) {
    echo $file->fgets();
}
?>

See Also

  • fgets() - Gets line from file pointer
  • SplFileObject::fgetss() - Gets line from file and strip HTML tags
  • SplFileObject::fgetc() - Gets character from file
  • SplFileObject::current() - Retrieve current line of file


Gets line from file and strip HTML tags

  • « SplFileObject::fgets
  • SplFileObject::flock »
  • PHP Manual
  • SplFileObject
  • Gets line from file and strip HTML tags

SplFileObject::fgetss

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::fgetss — Gets line from file and strip HTML tags

Warning

This function has been DEPRECATED as of PHP 7.3.0. Relying on this function is highly discouraged.

Description

public SplFileObject::fgetss ([ string $allowable_tags ] ) : string

Identical to SplFileObject::fgets(), except that SplFileObject::fgetss() attempts to strip any 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 SplFileObject::fgets().

Parameters

allowable_tags

Optional parameter to specify tags which should not be stripped.

Return Values

Returns a string containing the next line of the file with HTML and PHP code stripped, or FALSE on error.

Examples

Example #1 SplFileObject::fgetss() example

<?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);

$file = new SplFileObject("sample.php");
while (!$file->eof()) {
    echo $file->fgetss();
}
?>

The above example will output something similar to:

 Welcome! Today is the  of .

Text outside of the HTML block.

See Also

  • fgetss() - Gets line from file pointer and strip HTML tags
  • SplFileObject::fgets() - Gets line from file
  • SplFileObject::fgetc() - Gets character from file
  • SplFileObject::current() - Retrieve current line of file
  • The string.strip_tags filter


Portable file locking

  • « SplFileObject::fgetss
  • SplFileObject::fpassthru »
  • PHP Manual
  • SplFileObject
  • Portable file locking

SplFileObject::flock

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::flock — Portable file locking

Description

public SplFileObject::flock ( int $operation [, int &$wouldblock ] ) : bool

Locks or unlocks the file in the same portable way as flock().

Parameters

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).
  • LOCK_NB to not block while locking.

wouldblock

Set to TRUE if the lock would block (EWOULDBLOCK errno condition).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 SplFileObject::flock() example

<?php
$file = new SplFileObject("/tmp/lock.txt", "w");
if ($file->flock(LOCK_EX)) { // do an exclusive lock
    $file->ftruncate(0);     // truncate file
    $file->fwrite("Write something here\n");
    $file->flock(LOCK_UN);   // release the lock
} else {
    echo "Couldn't get the lock!";
}
?>

Changelog

Version | Description
5.5.22, 5.6.6 | Added support for the wouldblock parameter on Windows.
5.3.2 | The automatic unlocking when the file's resource handle is closed was removed. Unlocking now always has to be done manually.

See Also

  • flock() - Portable advisory file locking


Output all remaining data on a file pointer

  • « SplFileObject::flock
  • SplFileObject::fputcsv »
  • PHP Manual
  • SplFileObject
  • Output all remaining data on a file pointer

SplFileObject::fpassthru

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::fpassthru — Output all remaining data on a file pointer

Description

public SplFileObject::fpassthru ( void ) : 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 SplFileObject::rewind() to reset the file pointer to the beginning of the file if you have already written data to the file.

Parameters

This function has no parameters.

Return Values

Returns the number of characters read from handle and passed through to the output.

Examples

Example #1 SplFileObject::fpassthru() example

<?php

// Open the file in binary mode
$file = new SplFileObject("./img/ok.png", "rb");

// Send the right headers
header("Content-Type: image/png");
header("Content-Length: " . $file->getSize());

// Dump the picture and end script
$file->fpassthru();
exit;

?>

See Also

  • fpassthru() - Output all remaining data on a file pointer


Write a field array as a CSV line

  • « SplFileObject::fpassthru
  • SplFileObject::fread »
  • PHP Manual
  • SplFileObject
  • Write a field array as a CSV line

SplFileObject::fputcsv

(PHP 5 >= 5.4.0, PHP 7)

SplFileObject::fputcsv — Write a field array as a CSV line

Description

 public SplFileObject::fputcsv
  ( array $fields
 [, string $delimiter = ","
 [, string $enclosure = '"'
 [, string $escape = "\\"
]]] ) : int

Writes the fields array to the file as a CSV line.

Parameters

fields

An array of values.

delimiter

The optional delimiter parameter sets the field delimiter (one character only).

enclosure

The optional enclosure parameter sets the field enclosure (one character only).

escape

The optional escape parameter sets the escape character (at most one character). An empty string ("") disables the proprietary escape mechanism.

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_char.

Return Values

Returns the length of the written string or FALSE on failure.

Returns FALSE, and does not write the CSV line to the file, if the delimiter or enclosure parameter is not a single character.

Errors/Exceptions

An E_WARNING level error is issued if the delimiter or enclosure parameter is not a single character.

Changelog

Version | Description
7.4.0 | The escape parameter now also accepts an empty string to disable the proprietary escape mechanism.
5.5.21, 5.6.5 | Added the escape parameter.

Examples

Example #1 SplFileObject::fputcsv() example

<?php

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);

$file = new SplFileObject('file.csv', 'w');

foreach ($list as $fields) {
    $file->fputcsv($fields);
}

?>

The above example will write the following to file.csv:

aaa,bbb,ccc,dddd
123,456,789
"""aaa""","""bbb"""

See Also

  • fputcsv() - Format line as CSV and write to file pointer
  • SplFileObject::fgetcsv() - Gets line from file and parse as CSV fields


Read from file

  • « SplFileObject::fputcsv
  • SplFileObject::fscanf »
  • PHP Manual
  • SplFileObject
  • Read from file

SplFileObject::fread

(PHP 5 >= 5.5.11, PHP 7)

SplFileObject::fread — Read from file

Description

public SplFileObject::fread ( int $length ) : string

Reads the given number of bytes from the file.

Parameters

length

The number of bytes to read.

Return Values

Returns the string read from the file or FALSE on failure.

Examples

Example #1 SplFileObject::fread() example

<?php
// Get contents of a file into a string
$filename = "/usr/local/something.txt";
$file = new SplFileObject($filename, "r");
$contents = $file->fread($file->getSize());
?>

Notes

Note:

Note that SplFileObject::fread() reads from the current position of the file pointer. Use SplFileObject::ftell() to find the current position of the pointer and SplFileObject::rewind() (or SplFileObject::fseek()) to rewind the pointer position.

See Also

  • fread() - Binary-safe file read


Parses input from file according to a format

  • « SplFileObject::fread
  • SplFileObject::fseek »
  • PHP Manual
  • SplFileObject
  • Parses input from file according to a format

SplFileObject::fscanf

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::fscanf — Parses input from file according to a format

Description

public SplFileObject::fscanf ( string $format [, mixed &$... ] ) : mixed

Reads a line from the file and interprets it according to the specified format, which is described in the documentation for sprintf().

Any whitespace in the format string matches any whitespace in the line from the file. This means that even a tab \t in the format string can match a single space character in the input stream.

Parameters

format

The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result and conversion specifications, each of which results in fetching its own parameter.

A conversion specification follows this prototype: %[argnum$][flags][width][.precision]specifier.

Argnum

An integer followed by a dollar sign $, to specify which number argument to treat in the conversion.

Flags
Flag | Description
- Left-justify within the given field width; Right justification is the default
+ Prefix positive numbers with a plus sign +; Default only negative are prefixed with a negative sign.
(space) | Pads the result with spaces. This is the default.
0 | Only left-pads numbers with zeros. With s specifiers this can also right-pad with zeros.
'(char) | Pads the result with the character (char).

Width

An integer that says how many characters (minimum) this conversion should result in.

Precision

A period . followed by an integer who's meaning depends on the specifier:

  • For e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
  • For g and G specifiers: this is the maximum number of significant digits to be printed.
  • For s specifier: it acts as a cutoff point, setting a maximum character limit to the string.

Note: If the period is specified without an explicit value for precision, 0 is assumed.

Note: Attempting to use a position specifier greater than PHP_INT_MAX will generate warnings.

Specifiers
Specifier | Description
% A literal percent character. No argument is required.
b | The argument is treated as an integer and presented as a binary number.
c | The argument is treated as an integer and presented as the character with that ASCII.
d | The argument is treated as an integer and presented as a (signed) decimal number.
e | The argument is treated as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point since PHP 5.2.1. In earlier versions, it was taken as number of significant digits (one less).
E | Like the e specifier but uses uppercase letter (e.g. 1.2E+2).
f | The argument is treated as a float and presented as a floating-point number (locale aware).
F | The argument is treated as a float and presented as a floating-point number (non-locale aware). Available as of PHP 5.0.3.
g

General format.

Let P equal the precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero. Then, if a conversion with style E would have an exponent of X:

If P > X ≥ −4, the conversion is with style f and precision P − (X + 1). Otherwise, the conversion is with style e and precision P − 1.

G | Like the g specifier but uses E and F.
o | The argument is treated as an integer and presented as an octal number.
s | The argument is treated and presented as a string.
u | The argument is treated as an integer and presented as an unsigned decimal number.
x | The argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).
X | The argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).

Warning

The c type specifier ignores padding and width

Warning

Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results

Variables will be co-erced to a suitable type for the specifier:

Type Handling
Type | Specifiers
string | s
integer | d, u, c, o, x, X, b
double | g, G, e, E, f, F

...

The optional assigned values.

Return Values

If only one parameter is passed to this method, 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.

Examples

Example #1 SplFileObject::fscanf() example

<?php
$file = new SplFileObject("misc.txt");
while ($userinfo = $file->fscanf("%s %s %s")) {
    list ($name, $profession, $countrycode) = $userinfo;
    // Do something with $name $profession $countrycode
}
?>

Contents of users.txt

javier   argonaut    pe
hiroshi  sculptor    jp
robert   slacker     us
luigi    florist     it

See Also

  • fscanf() - Parses input from a file according to a format
  • sscanf() - Parses input from a string according to a format
  • printf() - Output a formatted string
  • sprintf() - Return a formatted string


Seek to a position

  • « SplFileObject::fscanf
  • SplFileObject::fstat »
  • PHP Manual
  • SplFileObject
  • Seek to a position

SplFileObject::fseek

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::fseek — Seek to a position

Description

public SplFileObject::fseek ( int $offset [, int $whence = SEEK_SET ] ) : int

Seek to a position in the file measured in bytes from the beginning of the file, obtained by adding offset to the position specified by whence.

Parameters

offset

The offset. A negative value can be used to move backwards through the file which is useful when SEEK_END is used as the whence value.

whence

whence values are:

  • SEEK_SET - Set position equal to offset bytes.
  • SEEK_CUR - Set position to current location plus offset.
  • SEEK_END - Set position to end-of-file plus offset.

If whence is not specified, it is assumed to be SEEK_SET.

Return Values

Returns 0 if the seek was successful, -1 otherwise. Note that seeking past EOF is not considered an error.

Examples

Example #1 SplFileObject::fseek() example

<?php
$file = new SplFileObject("somefile.txt");

// Read first line
$data = $file->fgets();

// Move back to the beginning of the file
// Same as $file->rewind();
$file->fseek(0);
?>

See Also

  • fseek() - Seeks on a file pointer


Gets information about the file

  • « SplFileObject::fseek
  • SplFileObject::ftell »
  • PHP Manual
  • SplFileObject
  • Gets information about the file

SplFileObject::fstat

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::fstat — Gets information about the file

Description

public SplFileObject::fstat ( void ) : array

Gathers the statistics of the file. Behaves identically to fstat().

Parameters

This function has no parameters.

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.

Examples

Example #1 SplFileObject::fstat() example

<?php
$file = new SplFileObject("/etc/passwd");
$stat = $file->fstat();

// Print only the associative part
print_r(array_slice($stat, 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
)

See Also

  • fstat() - Gets information about a file using an open file pointer
  • stat() - Gives information about a file


Return current file position

  • « SplFileObject::fstat
  • SplFileObject::ftruncate »
  • PHP Manual
  • SplFileObject
  • Return current file position

SplFileObject::ftell

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::ftell — Return current file position

Description

public SplFileObject::ftell ( void ) : int

Returns the position of the file pointer which represents the current offset in the file stream.

Parameters

This function has no parameters.

Return Values

Returns the position of the file pointer as an integer, or FALSE on error.

Examples

Example #1 SplFileObject::ftell() example

<?php
$file = new SplFileObject("/etc/passwd");

// Read first line
$data = $file->fgets();

// Where are we?
echo $file->ftell();
?>

See Also

  • ftell() - Returns the current position of the file read/write pointer


Truncates the file to a given length

  • « SplFileObject::ftell
  • SplFileObject::fwrite »
  • PHP Manual
  • SplFileObject
  • Truncates the file to a given length

SplFileObject::ftruncate

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::ftruncate — Truncates the file to a given length

Description

public SplFileObject::ftruncate ( int $size ) : bool

Truncates the file to size bytes.

Parameters

size

The size to truncate to.

Note:

If size is larger than the file it is extended with null bytes.

If size is smaller than the file, the extra data will be lost.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 SplFileObject::ftruncate() example

<?php
// Create file containing "Hello World!"
$file = new SplFileObject("/tmp/ftruncate", "w+");
$file->fwrite("Hello World!");

// Truncate to 5 bytes
$file->ftruncate(5);

// Rewind and read data
$file->rewind();
echo $file->fgets();
?>

The above example will output something similar to:

Hello

See Also

  • ftruncate() - Truncates a file to a given length


Write to file

  • « SplFileObject::ftruncate
  • SplFileObject::getChildren »
  • PHP Manual
  • SplFileObject
  • Write to file

SplFileObject::fwrite

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::fwrite — Write to file

Description

public SplFileObject::fwrite ( string $str [, int $length ] ) : int

Writes the contents of string to the file

Parameters

str

The string to be written to the file.

length

If the length argument is given, writing will stop after length bytes have been written or the end of string is reached, whichever comes first.

Return Values

Returns the number of bytes written, or 0 on error.

Examples

Example #1 SplFileObject::fwrite() example

<?php
$file = new SplFileObject("fwrite.txt", "w");
$written = $file->fwrite("12345");
echo "Wrote $written bytes to file";
?>

The above example will output something similar to:

Wrote 5 bytes to file

See Also

  • fwrite() - Binary-safe file write


No purpose

  • « SplFileObject::fwrite
  • SplFileObject::getCsvControl »
  • PHP Manual
  • SplFileObject
  • No purpose

SplFileObject::getChildren

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::getChildren — No purpose

Description

public SplFileObject::getChildren ( void ) : void

An SplFileObject does not have children so this method returns NULL.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • RecursiveIterator::getChildren() - Returns an iterator for the current entry


Get the delimiter, enclosure and escape character for CSV

  • « SplFileObject::getChildren
  • SplFileObject::getCurrentLine »
  • PHP Manual
  • SplFileObject
  • Get the delimiter, enclosure and escape character for CSV

SplFileObject::getCsvControl

(PHP 5 >= 5.2.0, PHP 7)

SplFileObject::getCsvControl — Get the delimiter, enclosure and escape character for CSV

Description

public SplFileObject::getCsvControl ( void ) : array

Gets the delimiter, enclosure and escape character used for parsing CSV fields.

Parameters

This function has no parameters.

Return Values

Returns an indexed array containing the delimiter, enclosure and escape character.

Changelog

Version | Description
7.4.0 | The escape character can now be an empty string.
5.6.25, 7.0.10 | Added the escape character to the returned array.

Examples

Example #1 SplFileObject::getCsvControl() example

<?php
$file = new SplFileObject("data.txt");
print_r($file->getCsvControl());
?>

The above example will output something similar to:

Array
(
    [0] => ,
    [1] => "
    [2] => \
)

See Also

  • SplFileObject::setCsvControl() - Set the delimiter, enclosure and escape character for CSV
  • SplFileObject::fgetcsv() - Gets line from file and parse as CSV fields


Alias of SplFileObject::fgets

  • « SplFileObject::getCsvControl
  • SplFileObject::getFlags »
  • PHP Manual
  • SplFileObject
  • Alias of SplFileObject::fgets

SplFileObject::getCurrentLine

(PHP 5 >= 5.1.2, PHP 7)

SplFileObject::getCurrentLine — Alias of SplFileObject::fgets()

Description

This method is an alias of: SplFileObject::fgets().


Gets flags for the SplFileObject

  • « SplFileObject::getCurrentLine
  • SplFileObject::getMaxLineLen »
  • PHP Manual
  • SplFileObject
  • Gets flags for the SplFileObject

SplFileObject::getFlags

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::getFlags — Gets flags for the SplFileObject

Description

public SplFileObject::getFlags ( void ) : int

Gets the flags set for an instance of SplFileObject as an integer.

Parameters

This function has no parameters.

Return Values

Returns an integer representing the flags.

Examples

Example #1 SplFileObject::getFlags() example

<?php
$file = new SplFileObject(__FILE__, "r");

if ($file->getFlags() & SplFileObject::SKIP_EMPTY) {
    echo "Skipping empty lines\n";
} else {
    echo "Not skipping empty lines\n";
}

$file->setFlags(SplFileObject::SKIP_EMPTY);

if ($file->getFlags() & SplFileObject::SKIP_EMPTY) {
    echo "Skipping empty lines\n";
} else {
    echo "Not skipping empty lines\n";
}
?>

The above example will output something similar to:

Not skipping empty lines
Skipping empty lines

See Also

  • SplFileObject::setFlags() - Sets flags for the SplFileObject


Get maximum line length

  • « SplFileObject::getFlags
  • SplFileObject::hasChildren »
  • PHP Manual
  • SplFileObject
  • Get maximum line length

SplFileObject::getMaxLineLen

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::getMaxLineLen — Get maximum line length

Description

public SplFileObject::getMaxLineLen ( void ) : int

Gets the maximum line length as set by SplFileObject::setMaxLineLen().

Parameters

This function has no parameters.

Return Values

Returns the maximum line length if one has been set with SplFileObject::setMaxLineLen(), default is 0.

Examples

Example #1 SplFileObject::getMaxLineLen() example

<?php
$file = new SplFileObject("file.txt");
var_dump($file->getMaxLineLen());

$file->setMaxLineLen(20);
var_dump($file->getMaxLineLen());
?>

The above example will output something similar to:

int(0)
int(20)

See Also

  • Classname::Method()


SplFileObject does not have children

  • « SplFileObject::getMaxLineLen
  • SplFileObject::key »
  • PHP Manual
  • SplFileObject
  • SplFileObject does not have children

SplFileObject::hasChildren

(PHP 5 >= 5.1.2, PHP 7)

SplFileObject::hasChildren — SplFileObject does not have children

Description

public SplFileObject::hasChildren ( void ) : bool

An SplFileObject does not have children so this method always return FALSE.

Parameters

This function has no parameters.

Return Values

Returns FALSE

See Also

  • RecursiveIterator::hasChildren() - Returns if an iterator can be created for the current entry


Get line number

  • « SplFileObject::hasChildren
  • SplFileObject::next »
  • PHP Manual
  • SplFileObject
  • Get line number

SplFileObject::key

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::key — Get line number

Description

public SplFileObject::key ( void ) : int

Gets the current line number.

Note:

This number may not reflect the actual line number in the file if SplFileObject::setMaxLineLen() is used to read fixed lengths of the file.

Parameters

This function has no parameters.

Return Values

Returns the current line number.

Examples

Example #1 SplFileObject::key() example

<?php
$file = new SplFileObject("lipsum.txt");
foreach ($file as $line) {
    echo $file->key() . ". " . $line;
}
?>

The above example will output something similar to:

0. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
1. Duis nec sapien felis, ac sodales nisl.
2. Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Example #2 SplFileObject::key() example with SplFileObject::setMaxLineLen()

<?php
$file = new SplFileObject("lipsum.txt");
$file->setMaxLineLen(20);
foreach ($file as $line) {
    echo $file->key() . ". " . $line . "\n";
}
?>

The above example will output something similar to:

0. Lorem ipsum dolor s
1. it amet, consectetu
2. r adipiscing elit.
3.

4. Duis nec sapien fel
5. is, ac sodales nisl
6. .

7. Lorem ipsum dolor s
8. it amet, consectetu
9. r adipiscing elit.

See Also

  • SplFileObject::current() - Retrieve current line of file
  • SplFileObject::seek() - Seek to specified line
  • SplFileObject::next() - Read next line
  • SplFileObject::rewind() - Rewind the file to the first line
  • SplFileObject::valid() - Not at EOF


Read next line

  • « SplFileObject::key
  • SplFileObject::rewind »
  • PHP Manual
  • SplFileObject
  • Read next line

SplFileObject::next

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::next — Read next line

Description

public SplFileObject::next ( void ) : void

Moves ahead to the next line in the file.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 SplFileObject::next() example

<?php
// Read through file line by line
$file = new SplFileObject("misc.txt");
while (!$file->eof()) {
    echo $file->current();
    $file->next();
}
?>

See Also

  • SplFileObject::current() - Retrieve current line of file
  • SplFileObject::key() - Get line number
  • SplFileObject::seek() - Seek to specified line
  • SplFileObject::rewind() - Rewind the file to the first line
  • SplFileObject::valid() - Not at EOF


Rewind the file to the first line

  • « SplFileObject::next
  • SplFileObject::seek »
  • PHP Manual
  • SplFileObject
  • Rewind the file to the first line

SplFileObject::rewind

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::rewind — Rewind the file to the first line

Description

public SplFileObject::rewind ( void ) : void

Rewinds the file back to the first line.

Parameters

This function has no parameters.

Return Values

No value is returned.

Errors/Exceptions

Throws a RuntimeException if cannot be rewound.

Examples

Example #1 SplFileObject::rewind() example

<?php
$file = new SplFileObject("misc.txt");

// Loop over whole file
foreach ($file as $line) { }

// Rewind to first line
$file->rewind();

// Output first line
echo $file->current();
?>

See Also

  • SplFileObject::current() - Retrieve current line of file
  • SplFileObject::key() - Get line number
  • SplFileObject::seek() - Seek to specified line
  • SplFileObject::next() - Read next line
  • SplFileObject::valid() - Not at EOF


Seek to specified line

  • « SplFileObject::rewind
  • SplFileObject::setCsvControl »
  • PHP Manual
  • SplFileObject
  • Seek to specified line

SplFileObject::seek

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::seek — Seek to specified line

Description

public SplFileObject::seek ( int $line_pos ) : void

Seek to specified line in the file.

Parameters

line_pos

The zero-based line number to seek to.

Return Values

No value is returned.

Errors/Exceptions

Throws a LogicException if the line_pos is negative.

Examples

Example #1 SplFileObject::seek() example

This example outputs the third line of the script which is found at position 2.

<?php
$file = new SplFileObject(__FILE__);
$file->seek(2);
echo $file->current();
?>

The above example will output something similar to:

$file->seek(2);

See Also

  • SplFileObject::current() - Retrieve current line of file
  • SplFileObject::key() - Get line number
  • SplFileObject::next() - Read next line
  • SplFileObject::rewind() - Rewind the file to the first line
  • SplFileObject::valid() - Not at EOF


Set the delimiter, enclosure and escape character for CSV

  • « SplFileObject::seek
  • SplFileObject::setFlags »
  • PHP Manual
  • SplFileObject
  • Set the delimiter, enclosure and escape character for CSV

SplFileObject::setCsvControl

(PHP 5 >= 5.2.0, PHP 7)

SplFileObject::setCsvControl — Set the delimiter, enclosure and escape character for CSV

Description

 public SplFileObject::setCsvControl
  ([ string $delimiter = ","
 [, string $enclosure = "\""
 [, string $escape = "\\"
]]] ) : void

Sets the delimiter, enclosure and escape character for parsing CSV fields.

Parameters

delimiter

The field delimiter (one character only).

enclosure

The field enclosure character (one character only).

escape

The field escape character (at most one character). An empty string ("") disables the proprietary escape mechanism.

Return Values

No value is returned.

Changelog

Version | Description
7.4.0 | The escape parameter now also accepts an empty string to disable the proprietary escape mechanism.
5.3.0 | Added the escape parameter.

Examples

Example #1 SplFileObject::setCsvControl() example

<?php
$file = new SplFileObject("data.csv");
$file->setFlags(SplFileObject::READ_CSV);
$file->setCsvControl('|');
foreach ($file as $row) {
    list ($fruit, $quantity) = $row;
    // Do something with values
}
?>

Contents of data.csv

<?php
apples|20
bananas|14
cherries|87
?>

See Also

  • SplFileObject::getCsvControl() - Get the delimiter, enclosure and escape character for CSV
  • SplFileObject::fgetcsv() - Gets line from file and parse as CSV fields


Sets flags for the SplFileObject

  • « SplFileObject::setCsvControl
  • SplFileObject::setMaxLineLen »
  • PHP Manual
  • SplFileObject
  • Sets flags for the SplFileObject

SplFileObject::setFlags

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::setFlags — Sets flags for the SplFileObject

Description

public SplFileObject::setFlags ( int $flags ) : void

Sets the flags to be used by the SplFileObject.

Parameters

flags

Bit mask of the flags to set. See SplFileObject constants for the available flags.

Return Values

No value is returned.

Examples

Example #1 SplFileObject::setFlags() example

<?php
$file = new SplFileObject("data.csv");
$file->setFlags(SplFileObject::READ_CSV);
foreach ($file as $fields) {
    var_dump($fields);
}
?>

See Also

  • SplFileObject::getFlags() - Gets flags for the SplFileObject


Set maximum line length

  • « SplFileObject::setFlags
  • SplFileObject::__toString »
  • PHP Manual
  • SplFileObject
  • Set maximum line length

SplFileObject::setMaxLineLen

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::setMaxLineLen — Set maximum line length

Description

public SplFileObject::setMaxLineLen ( int $max_len ) : void

Sets the maximum length of a line to be read.

Parameters

max_len

The maximum length of a line.

Return Values

No value is returned.

Errors/Exceptions

Throws DomainException when max_len is less than zero.

Examples

Example #1 SplFileObject::setMaxLineLen() example

<?php
$file = new SplFileObject("lipsum.txt");
$file->setMaxLineLen(20);
foreach ($file as $line) {
    echo $line . "\n";
}
?>

Contents of lipsum.txt

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Duis nec sapien felis, ac sodales nisl.
Nulla vitae magna vitae purus aliquet consequat.

The above example will output something similar to:

Lorem ipsum dolor s
it amet, consectetu
r adipiscing elit.

Duis nec sapien fel
is, ac sodales nisl
.

Nulla vitae magna v
itae purus aliquet
consequat.

See Also

  • Classname::Method()


Alias of SplFileObject::fgets

  • « SplFileObject::setMaxLineLen
  • SplFileObject::valid »
  • PHP Manual
  • SplFileObject
  • Alias of SplFileObject::fgets

SplFileObject::__toString

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::__toString — Alias of SplFileObject::fgets()

Description

This method is an alias of: SplFileObject::fgets().

Changelog

Version | Description
7.2.19, 7.3.6 | Changed from an alias of SplFileObject::current() to an alias of SplFileObject::fgets().


Not at EOF

  • « SplFileObject::__toString
  • SplTempFileObject »
  • PHP Manual
  • SplFileObject
  • Not at EOF

SplFileObject::valid

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::valid — Not at EOF

Description

public SplFileObject::valid ( void ) : bool

Check whether EOF has been reached.

Parameters

This function has no parameters.

Return Values

Returns TRUE if not reached EOF, FALSE otherwise.

Examples

Example #1 SplFileObject::valid() example

<?php
// Loop over a file, line by line
$file = new SplFileObject("file.txt");
while ($file->valid()) {
    echo $file->fgets();
}
?>

See Also

  • SplFileObject::current() - Retrieve current line of file
  • SplFileObject::key() - Get line number
  • SplFileObject::seek() - Seek to specified line
  • SplFileObject::next() - Read next line
  • SplFileObject::rewind() - Rewind the file to the first line


The SplTempFileObject class

(PHP 5 >= 5.1.2, PHP 7)

Introduction

The SplTempFileObject class offers an object oriented interface for a temporary file.

Class synopsis

SplTempFileObject extends SplFileObject implements SeekableIterator , RecursiveIterator {
/* Inherited constants */
const integer SplFileObject::DROP_NEW_LINE = 1 ;
const integer SplFileObject::READ_AHEAD = 2 ;
const integer SplFileObject::SKIP_EMPTY = 4 ;
const integer SplFileObject::READ_CSV = 8 ;
/* Methods */
public __construct ([ int $max_memory ] )
/* Inherited methods */
public SplFileObject::current ( void ) : string|array
public SplFileObject::eof ( void ) : bool
public SplFileObject::fflush ( void ) : bool
public SplFileObject::fgetc ( void ) : string
 public SplFileObject::fgetcsv
  ([ string $delimiter = ","
 [, string $enclosure = "\""
 [, string $escape = "\\"
]]] ) : array
public SplFileObject::fgets ( void ) : string
public SplFileObject::fgetss ([ string $allowable_tags ] ) : string
public SplFileObject::flock ( int $operation [, int &$wouldblock ] ) : bool
public SplFileObject::fpassthru ( void ) : int
 public SplFileObject::fputcsv
  ( array $fields
 [, string $delimiter = ","
 [, string $enclosure = '"'
 [, string $escape = "\\"
]]] ) : int
public SplFileObject::fread ( int $length ) : string
public SplFileObject::fscanf ( string $format [, mixed &$... ] ) : mixed
public SplFileObject::fseek ( int $offset [, int $whence = SEEK_SET ] ) : int
public SplFileObject::fstat ( void ) : array
public SplFileObject::ftell ( void ) : int
public SplFileObject::ftruncate ( int $size ) : bool
public SplFileObject::fwrite ( string $str [, int $length ] ) : int
public SplFileObject::getChildren ( void ) : void
public SplFileObject::getCsvControl ( void ) : array
public SplFileObject::getFlags ( void ) : int
public SplFileObject::getMaxLineLen ( void ) : int
public SplFileObject::hasChildren ( void ) : bool
public SplFileObject::key ( void ) : int
public SplFileObject::next ( void ) : void
public SplFileObject::rewind ( void ) : void
public SplFileObject::seek ( int $line_pos ) : void
 public SplFileObject::setCsvControl
  ([ string $delimiter = ","
 [, string $enclosure = "\""
 [, string $escape = "\\"
]]] ) : void
public SplFileObject::setFlags ( int $flags ) : void
public SplFileObject::setMaxLineLen ( int $max_len ) : void
public SplFileObject::valid ( void ) : bool
}

Table of Contents

  • SplTempFileObject::__construct — Construct a new temporary file object


Construct a new temporary file object

  • « SplTempFileObject
  • Miscellaneous Classes and Interfaces »
  • PHP Manual
  • SplTempFileObject
  • Construct a new temporary file object

SplTempFileObject::__construct

(PHP 5 >= 5.1.2, PHP 7)

SplTempFileObject::__construct — Construct a new temporary file object

Description

public SplTempFileObject::__construct ([ int $max_memory ] )

Construct a new temporary file object.

Parameters

max_memory

The maximum amount of memory (in bytes, default is 2 MB) for the temporary file to use. If the temporary file exceeds this size, it will be moved to a file in the system's temp directory.

If max_memory is negative, only memory will be used. If max_memory is zero, no memory will be used.

Return Values

No value is returned.

Errors/Exceptions

Throws a RuntimeException if an error occurs.

Examples

Example #1 SplTempFileObject() example

This example writes a temporary file in memory which can be written to and read from.

<?php
$temp = new SplTempFileObject();
$temp->fwrite("This is the first line\n");
$temp->fwrite("And this is the second.\n");
echo "Written " . $temp->ftell() . " bytes to temporary file.\n\n";

// Rewind and read what was written
$temp->rewind();
foreach ($temp as $line) {
    echo $line;
}
?>

The above example will output something similar to:

Written 47 bytes to temporary file.

This is the first line
And this is the second.

See Also

  • SplFileObject
  • PHP input/output streams (for php://temp and php://memory)


Miscellaneous Classes and Interfaces

Table of Contents

  • ArrayObject
  • SplObserver
  • SplSubject

Classes and interfaces which do not fit into the other SPL categories.


The ArrayObject class

(PHP 5, PHP 7)

Introduction

This class allows objects to work as arrays.

Class synopsis

ArrayObject implements IteratorAggregate , ArrayAccess , Serializable , Countable {
/* Constants */
const integer STD_PROP_LIST = 1 ;
const integer ARRAY_AS_PROPS = 2 ;
/* Methods */
public __construct ([ mixed $input = array() [, int $flags = 0 [, string $iterator_class = "ArrayIterator" ]]] )
public append ( mixed $value ) : void
public asort ( void ) : void
public count ( void ) : int
public exchangeArray ( mixed $input ) : array
public getArrayCopy ( void ) : array
public getFlags ( void ) : int
public getIterator ( void ) : ArrayIterator
public getIteratorClass ( void ) : string
public ksort ( void ) : void
public natcasesort ( void ) : void
public natsort ( void ) : void
public offsetExists ( mixed $index ) : bool
public offsetGet ( mixed $index ) : mixed
public offsetSet ( mixed $index , mixed $newval ) : void
public offsetUnset ( mixed $index ) : void
public serialize ( void ) : string
public setFlags ( int $flags ) : void
public setIteratorClass ( string $iterator_class ) : void
public uasort ( callable $cmp_function ) : void
public uksort ( callable $cmp_function ) : void
public unserialize ( string $serialized ) : void
}

Predefined Constants

ArrayObject Flags

ArrayObject::STD_PROP_LIST

Properties of the object have their normal functionality when accessed as list (var_dump, foreach, etc.).

ArrayObject::ARRAY_AS_PROPS

Entries can be accessed as properties (read and write).

Changelog

Version | Description
5.3.0 | Implements Serializable.

Table of Contents

  • ArrayObject::append — Appends the value
  • ArrayObject::asort — Sort the entries by value
  • ArrayObject::__construct — Construct a new array object
  • ArrayObject::count — Get the number of public properties in the ArrayObject
  • ArrayObject::exchangeArray — Exchange the array for another one
  • ArrayObject::getArrayCopy — Creates a copy of the ArrayObject
  • ArrayObject::getFlags — Gets the behavior flags
  • ArrayObject::getIterator — Create a new iterator from an ArrayObject instance
  • ArrayObject::getIteratorClass — Gets the iterator classname for the ArrayObject
  • ArrayObject::ksort — Sort the entries by key
  • ArrayObject::natcasesort — Sort an array using a case insensitive "natural order" algorithm
  • ArrayObject::natsort — Sort entries using a "natural order" algorithm
  • ArrayObject::offsetExists — Returns whether the requested index exists
  • ArrayObject::offsetGet — Returns the value at the specified index
  • ArrayObject::offsetSet — Sets the value at the specified index to newval
  • ArrayObject::offsetUnset — Unsets the value at the specified index
  • ArrayObject::serialize — Serialize an ArrayObject
  • ArrayObject::setFlags — Sets the behavior flags
  • ArrayObject::setIteratorClass — Sets the iterator classname for the ArrayObject
  • ArrayObject::uasort — Sort the entries with a user-defined comparison function and maintain key association
  • ArrayObject::uksort — Sort the entries by keys using a user-defined comparison function
  • ArrayObject::unserialize — Unserialize an ArrayObject


Appends the value

  • « ArrayObject
  • ArrayObject::asort »
  • PHP Manual
  • ArrayObject
  • Appends the value

ArrayObject::append

(PHP 5, PHP 7)

ArrayObject::append — Appends the value

Description

public ArrayObject::append ( mixed $value ) : void

Appends a new value as the last element.

Note:

This method cannot be called when the ArrayObject was constructed from an object. Use ArrayObject::offsetSet() instead.

Parameters

value

The value being appended.

Return Values

No value is returned.

Examples

Example #1 ArrayObject::append() example

<?php
$arrayobj = new ArrayObject(array('first','second','third'));
$arrayobj->append('fourth');
$arrayobj->append(array('five', 'six'));
var_dump($arrayobj);
?>

The above example will output:

object(ArrayObject)#1 (5) {
  [0]=>
  string(5) "first"
  [1]=>
  string(6) "second"
  [2]=>
  string(5) "third"
  [3]=>
  string(6) "fourth"
  [4]=>
  array(2) {
    [0]=>
    string(4) "five"
    [1]=>
    string(3) "six"
  }
}

See Also

  • ArrayObject::offsetSet() - Sets the value at the specified index to newval


Sort the entries by value

  • « ArrayObject::append
  • ArrayObject::__construct »
  • PHP Manual
  • ArrayObject
  • Sort the entries by value

ArrayObject::asort

(PHP 5 >= 5.2.0, PHP 7)

ArrayObject::asort — Sort the entries by value

Description

public ArrayObject::asort ( void ) : void

Sorts the entries such that the keys maintain their correlation with the entries they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 ArrayObject::asort() example

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
$fruitArrayObject = new ArrayObject($fruits);
$fruitArrayObject->asort();

foreach ($fruitArrayObject as $key => $val) {
    echo "$key = $val\n";
}
?>

The above example will output:

c = apple
b = banana
d = lemon
a = orange

The fruits have been sorted in alphabetical order, and the key associated with each entry has been maintained.

See Also

  • ArrayObject::ksort() - Sort the entries by key
  • ArrayObject::natsort() - Sort entries using a "natural order" algorithm
  • ArrayObject::natcasesort() - Sort an array using a case insensitive "natural order" algorithm
  • ArrayObject::uasort() - Sort the entries with a user-defined comparison function and maintain key association
  • ArrayObject::uksort() - Sort the entries by keys using a user-defined comparison function


Construct a new array object

  • « ArrayObject::asort
  • ArrayObject::count »
  • PHP Manual
  • ArrayObject
  • Construct a new array object

ArrayObject::__construct

(PHP 5, PHP 7)

ArrayObject::__construct — Construct a new array object

Description

public ArrayObject::__construct ([ mixed $input = array() [, int $flags = 0 [, string $iterator_class = "ArrayIterator" ]]] )

This constructs a new array object.

Parameters

input

The input parameter accepts an array or an Object.

flags

Flags to control the behaviour of the ArrayObject object. See ArrayObject::setFlags().

iterator_class

Specify the class that will be used for iteration of the ArrayObject object.

Return Values

Returns an ArrayObject object on success.

Errors/Exceptions

Throws InvalidArgumentException when:

  • input is not an array or object
  • flags is not an integer
  • iterator_class is not an object that implements Iterator

Examples

Example #1 ArrayObject::__construct() example

<?php
$array = array('1' => 'one',
               '2' => 'two',
               '3' => 'three');

$arrayobject = new ArrayObject($array);

var_dump($arrayobject);
?>

The above example will output:

object(ArrayObject)#1 (3) {
  [1]=>
  string(3) "one"
  [2]=>
  string(3) "two"
  [3]=>
  string(5) "three"
}

See Also

  • ArrayObject::setflags() - Sets the behavior flags


Get the number of public properties in the ArrayObject

  • « ArrayObject::__construct
  • ArrayObject::exchangeArray »
  • PHP Manual
  • ArrayObject
  • Get the number of public properties in the ArrayObject

ArrayObject::count

(PHP 5, PHP 7)

ArrayObject::count — Get the number of public properties in the ArrayObject

Description

public ArrayObject::count ( void ) : int

Get the number of public properties in the ArrayObject.

Parameters

This function has no parameters.

Return Values

The number of public properties in the ArrayObject.

Note:

When the ArrayObject is constructed from an array all properties are public.

Examples

Example #1 ArrayObject::count() example

<?php
class Example {
    public $public = 'prop:public';
    private $prv   = 'prop:private';
    protected $prt = 'prop:protected';
}

$arrayobj = new ArrayObject(new Example());
var_dump($arrayobj->count());

$arrayobj = new ArrayObject(array('first','second','third'));
var_dump($arrayobj->count());
?>

The above example will output:

int(1)
int(3)


Exchange the array for another one

  • « ArrayObject::count
  • ArrayObject::getArrayCopy »
  • PHP Manual
  • ArrayObject
  • Exchange the array for another one

ArrayObject::exchangeArray

(PHP 5 >= 5.1.0, PHP 7)

ArrayObject::exchangeArray — Exchange the array for another one

Description

public ArrayObject::exchangeArray ( mixed $input ) : array

Exchange the current array with another array or object.

Parameters

input

The new array or object to exchange with the current array.

Return Values

Returns the old array.

Examples

Example #1 ArrayObject::exchangeArray() example

<?php
// Array of available fruits
$fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10);
// Array of locations in Europe
$locations = array('Amsterdam', 'Paris', 'London');

$fruitsArrayObject = new ArrayObject($fruits);

// Now exchange fruits for locations
$old = $fruitsArrayObject->exchangeArray($locations);
print_r($old);
print_r($fruitsArrayObject);

?>

The above example will output:

Array
(
    [lemons] => 1
    [oranges] => 4
    [bananas] => 5
    [apples] => 10
)
ArrayObject Object
(
    [0] => Amsterdam
    [1] => Paris
    [2] => London
)


Creates a copy of the ArrayObject

  • « ArrayObject::exchangeArray
  • ArrayObject::getFlags »
  • PHP Manual
  • ArrayObject
  • Creates a copy of the ArrayObject

ArrayObject::getArrayCopy

(PHP 5, PHP 7)

ArrayObject::getArrayCopy — Creates a copy of the ArrayObject

Description

public ArrayObject::getArrayCopy ( void ) : array

Exports the ArrayObject to an array.

Parameters

This function has no parameters.

Return Values

Returns a copy of the array. When the ArrayObject refers to an object, an array of the public properties of that object will be returned.

Examples

Example #1 ArrayObject::getArrayCopy() example

<?php
// Array of available fruits
$fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10);

$fruitsArrayObject = new ArrayObject($fruits);
$fruitsArrayObject['pears'] = 4;

// create a copy of the array
$copy = $fruitsArrayObject->getArrayCopy();
print_r($copy);

?>

The above example will output:

Array
(
    [lemons] => 1
    [oranges] => 4
    [bananas] => 5
    [apples] => 10
    [pears] => 4
)


Gets the behavior flags

  • « ArrayObject::getArrayCopy
  • ArrayObject::getIterator »
  • PHP Manual
  • ArrayObject
  • Gets the behavior flags

ArrayObject::getFlags

(PHP 5 >= 5.1.0, PHP 7)

ArrayObject::getFlags — Gets the behavior flags

Description

public ArrayObject::getFlags ( void ) : int

Gets the behavior flags of the ArrayObject. See the ArrayObject::setFlags method for a list of the available flags.

Parameters

This function has no parameters.

Return Values

Returns the behavior flags of the ArrayObject.

Examples

Example #1 ArrayObject::getFlags() example

<?php
// Array of available fruits
$fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10);

$fruitsArrayObject = new ArrayObject($fruits);

// Get the current flags
$flags = $fruitsArrayObject->getFlags();
var_dump($flags);

// Set new flags
$fruitsArrayObject->setFlags(ArrayObject::ARRAY_AS_PROPS);

// Get the new flags
$flags = $fruitsArrayObject->getFlags();
var_dump($flags);
?>

The above example will output:

int(0)
int(2)

See Also

  • ArrayObject::setFlags() - Sets the behavior flags


Create a new iterator from an ArrayObject instance

  • « ArrayObject::getFlags
  • ArrayObject::getIteratorClass »
  • PHP Manual
  • ArrayObject
  • Create a new iterator from an ArrayObject instance

ArrayObject::getIterator

(PHP 5, PHP 7)

ArrayObject::getIterator — Create a new iterator from an ArrayObject instance

Description

public ArrayObject::getIterator ( void ) : ArrayIterator

Create a new iterator from an ArrayObject instance.

Parameters

This function has no parameters.

Return Values

An iterator from an ArrayObject.

Examples

Example #1 ArrayObject::getIterator() example

<?php
$array = array('1' => 'one',
               '2' => 'two',
               '3' => 'three');

$arrayobject = new ArrayObject($array);

$iterator = $arrayobject->getIterator();

while($iterator->valid()) {
    echo $iterator->key() . ' => ' . $iterator->current() . "\n";

    $iterator->next();
}
?>

The above example will output:

1 => one
2 => two
3 => three


Gets the iterator classname for the ArrayObject

  • « ArrayObject::getIterator
  • ArrayObject::ksort »
  • PHP Manual
  • ArrayObject
  • Gets the iterator classname for the ArrayObject

ArrayObject::getIteratorClass

(PHP 5 >= 5.1.0, PHP 7)

ArrayObject::getIteratorClass — Gets the iterator classname for the ArrayObject

Description

public ArrayObject::getIteratorClass ( void ) : string

Gets the class name of the array iterator that is used by ArrayObject::getIterator().

Parameters

This function has no parameters.

Return Values

Returns the iterator class name that is used to iterate over this object.

Examples

Example #1 ArrayObject::getIteratorClass() example

<?php
// Custom ArrayIterator (inherits from ArrayIterator)
class MyArrayIterator extends ArrayIterator {
    // custom implementation
}

// Array of available fruits
$fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10);

$fruitsArrayObject = new ArrayObject($fruits);

// Get the current class name
$className = $fruitsArrayObject->getIteratorClass();
var_dump($className);

// Set new classname
$fruitsArrayObject->setIteratorClass('MyArrayIterator');

// Get the new iterator classname
$className = $fruitsArrayObject->getIteratorClass();
var_dump($className);
?>

The above example will output:

string(13) "ArrayIterator"
string(15) "MyArrayIterator"

See Also

  • The ArrayObject::setIteratorClass method


Sort the entries by key

  • « ArrayObject::getIteratorClass
  • ArrayObject::natcasesort »
  • PHP Manual
  • ArrayObject
  • Sort the entries by key

ArrayObject::ksort

(PHP 5 >= 5.2.0, PHP 7)

ArrayObject::ksort — Sort the entries by key

Description

public ArrayObject::ksort ( void ) : void

Sorts the entries by key, maintaining key to entry correlations. This is useful mainly for associative arrays.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 ArrayObject::ksort() example

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
$fruitArrayObject = new ArrayObject($fruits);
$fruitArrayObject->ksort();

foreach ($fruitArrayObject as $key => $val) {
    echo "$key = $val\n";
}
 ?>

The above example will output:

a = orange
b = banana
c = apple
d = lemon

See Also

  • ArrayObject::asort() - Sort the entries by value
  • ArrayObject::natsort() - Sort entries using a "natural order" algorithm
  • ArrayObject::natcasesort() - Sort an array using a case insensitive "natural order" algorithm
  • ArrayObject::uasort() - Sort the entries with a user-defined comparison function and maintain key association
  • ArrayObject::uksort() - Sort the entries by keys using a user-defined comparison function


Sort an array using a case insensitive "natural order" algorithm

  • « ArrayObject::ksort
  • ArrayObject::natsort »
  • PHP Manual
  • ArrayObject
  • Sort an array using a case insensitive "natural order" algorithm

ArrayObject::natcasesort

(PHP 5 >= 5.2.0, PHP 7)

ArrayObject::natcasesort — Sort an array using a case insensitive "natural order" algorithm

Description

public ArrayObject::natcasesort ( void ) : void

This method is a case insensitive version of ArrayObject::natsort.

This method implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations. This is described as a "natural ordering".

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 ArrayObject::natcasesort() example

<?php
$array = array('IMG0.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png');

$arr1 = new ArrayObject($array);
$arr2 = clone $arr1;

$arr1->asort();
echo "Standard sorting\n";
print_r($arr1);

$arr2->natcasesort();
echo "\nNatural order sorting (case-insensitive)\n";
print_r($arr2);
?>

The above example will output:

Standard sorting
ArrayObject Object
(
    [0] => IMG0.png
    [5] => IMG3.png
    [4] => img1.png
    [2] => img10.png
    [1] => img12.png
    [3] => img2.png
)

Natural order sorting (case-insensitive)
ArrayObject Object
(
    [0] => IMG0.png
    [4] => img1.png
    [3] => img2.png
    [5] => IMG3.png
    [2] => img10.png
    [1] => img12.png
)

For more information see: Martin Pool's » Natural Order String Comparison page.

See Also

  • ArrayObject::asort() - Sort the entries by value
  • ArrayObject::ksort() - Sort the entries by key
  • ArrayObject::natsort() - Sort entries using a "natural order" algorithm
  • ArrayObject::uasort() - Sort the entries with a user-defined comparison function and maintain key association
  • ArrayObject::uksort() - Sort the entries by keys using a user-defined comparison function


Sort entries using a "natural order" algorithm

  • « ArrayObject::natcasesort
  • ArrayObject::offsetExists »
  • PHP Manual
  • ArrayObject
  • Sort entries using a "natural order" algorithm

ArrayObject::natsort

(PHP 5 >= 5.2.0, PHP 7)

ArrayObject::natsort — Sort entries using a "natural order" algorithm

Description

public ArrayObject::natsort ( void ) : void

This method implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations. This is described as a "natural ordering". An example of the difference between this algorithm and the regular computer string sorting algorithms (used in ArrayObject::asort) method can be seen in the example below.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 ArrayObject::natsort() example

<?php
$array = array("img12.png", "img10.png", "img2.png", "img1.png");

$arr1 = new ArrayObject($array);
$arr2 = clone $arr1;

$arr1->asort();
echo "Standard sorting\n";
print_r($arr1);

$arr2->natsort();
echo "\nNatural order sorting\n";
print_r($arr2);
?>

The above example will output:

Standard sorting
ArrayObject Object
(
    [3] => img1.png
    [1] => img10.png
    [0] => img12.png
    [2] => img2.png
)

Natural order sorting
ArrayObject Object
(
    [3] => img1.png
    [2] => img2.png
    [1] => img10.png
    [0] => img12.png
)

For more information see: Martin Pool's » Natural Order String Comparison page.

See Also

  • ArrayObject::asort() - Sort the entries by value
  • ArrayObject::ksort() - Sort the entries by key
  • ArrayObject::natcasesort() - Sort an array using a case insensitive "natural order" algorithm
  • ArrayObject::uasort() - Sort the entries with a user-defined comparison function and maintain key association
  • ArrayObject::uksort() - Sort the entries by keys using a user-defined comparison function


Returns whether the requested index exists

  • « ArrayObject::natsort
  • ArrayObject::offsetGet »
  • PHP Manual
  • ArrayObject
  • Returns whether the requested index exists

ArrayObject::offsetExists

(PHP 5, PHP 7)

ArrayObject::offsetExists — Returns whether the requested index exists

Description

public ArrayObject::offsetExists ( mixed $index ) : bool

Parameters

index

The index being checked.

Return Values

TRUE if the requested index exists, otherwise FALSE

Examples

Example #1 ArrayObject::offsetExists() example

<?php
$arrayobj = new ArrayObject(array('zero', 'one', 'example'=>'e.g.'));
var_dump($arrayobj->offsetExists(1));
var_dump($arrayobj->offsetExists('example'));
var_dump($arrayobj->offsetExists('notfound'));
?>

The above example will output:

bool(true)
bool(true)
bool(false)


Returns the value at the specified index

  • « ArrayObject::offsetExists
  • ArrayObject::offsetSet »
  • PHP Manual
  • ArrayObject
  • Returns the value at the specified index

ArrayObject::offsetGet

(PHP 5, PHP 7)

ArrayObject::offsetGet — Returns the value at the specified index

Description

public ArrayObject::offsetGet ( mixed $index ) : mixed

Parameters

index

The index with the value.

Return Values

The value at the specified index or NULL.

Errors/Exceptions

Produces an E_NOTICE error message when the specified index does not exist.

Examples

Example #1 ArrayObject::offsetGet() example

<?php
$arrayobj = new ArrayObject(array('zero', 7, 'example'=>'e.g.'));
var_dump($arrayobj->offsetGet(1));
var_dump($arrayobj->offsetGet('example'));
var_dump($arrayobj->offsetExists('notfound'));
?>

The above example will output:

int(7)
string(4) "e.g."
bool(false)


Sets the value at the specified index to newval

  • « ArrayObject::offsetGet
  • ArrayObject::offsetUnset »
  • PHP Manual
  • ArrayObject
  • Sets the value at the specified index to newval

ArrayObject::offsetSet

(PHP 5, PHP 7)

ArrayObject::offsetSet — Sets the value at the specified index to newval

Description

public ArrayObject::offsetSet ( mixed $index , mixed $newval ) : void

Sets the value at the specified index to newval.

Parameters

index

The index being set.

newval

The new value for the index.

Return Values

No value is returned.

Examples

Example #1 ArrayObject::offsetSet() example

<?php
class Example {
    public $property = 'prop:public';
}
$arrayobj = new ArrayObject(new Example());
$arrayobj->offsetSet(4, 'four');
$arrayobj->offsetSet('group', array('g1', 'g2'));
var_dump($arrayobj);

$arrayobj = new ArrayObject(array('zero','one'));
$arrayobj->offsetSet(null, 'last');
var_dump($arrayobj);
?>

The above example will output:

object(ArrayObject)#1 (3) {
  ["property"]=>
  string(11) "prop:public"
  [4]=>
  string(4) "four"
  ["group"]=>
  array(2) {
    [0]=>
    string(2) "g1"
    [1]=>
    string(2) "g2"
  }
}
object(ArrayObject)#3 (3) {
  [0]=>
  string(4) "zero"
  [1]=>
  string(3) "one"
  [2]=>
  string(4) "last"
}

See Also

  • ArrayObject::append() - Appends the value


Unsets the value at the specified index

  • « ArrayObject::offsetSet
  • ArrayObject::serialize »
  • PHP Manual
  • ArrayObject
  • Unsets the value at the specified index

ArrayObject::offsetUnset

(PHP 5, PHP 7)

ArrayObject::offsetUnset — Unsets the value at the specified index

Description

public ArrayObject::offsetUnset ( mixed $index ) : void

Unsets the value at the specified index.

Parameters

index

The index being unset.

Return Values

No value is returned.

Examples

Example #1 ArrayObject::offsetUnset() example

<?php
$arrayobj = new ArrayObject(array(0=>'zero',2=>'two'));
$arrayobj->offsetUnset(2);
var_dump($arrayobj);
?>

The above example will output:

object(ArrayObject)#1 (1) {
  [0]=>
  string(4) "zero"
}


Serialize an ArrayObject

  • « ArrayObject::offsetUnset
  • ArrayObject::setFlags »
  • PHP Manual
  • ArrayObject
  • Serialize an ArrayObject

ArrayObject::serialize

(PHP 5 >= 5.3.0, PHP 7)

ArrayObject::serialize — Serialize an ArrayObject

Description

public ArrayObject::serialize ( void ) : string

Serializes an ArrayObject.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The serialized representation of the ArrayObject.

Examples

Example #1 ArrayObject::serialize() example

<?php
$o = new ArrayObject();

$s1 = serialize($o);
$s2 = $o->serialize();

var_dump($s1);
var_dump($s2);
?>

The above example will output:

string(45) "C:11:"ArrayObject":21:{x:i:0;a:0:{};m:a:0:{}}"
string(21) "x:i:0;a:0:{};m:a:0:{}"

See Also

  • ArrayObject::unserialize() - Unserialize an ArrayObject
  • serialize() - Generates a storable representation of a value
  • Serializing Objects


Sets the behavior flags

  • « ArrayObject::serialize
  • ArrayObject::setIteratorClass »
  • PHP Manual
  • ArrayObject
  • Sets the behavior flags

ArrayObject::setFlags

(PHP 5 >= 5.1.0, PHP 7)

ArrayObject::setFlags — Sets the behavior flags

Description

public ArrayObject::setFlags ( int $flags ) : void

Set the flags that change the behavior of the ArrayObject.

Parameters

flags

The new ArrayObject behavior. It takes on either a bitmask, or named constants. Using named constants is strongly encouraged to ensure compatibility for future versions.

The available behavior flags are listed below. The actual meanings of these flags are described in the predefined constants.

ArrayObject behavior flags
value | constant
1 | ArrayObject::STD_PROP_LIST
2 | ArrayObject::ARRAY_AS_PROPS

Return Values

No value is returned.

Examples

Example #1 ArrayObject::setFlags() example

<?php
// Array of available fruits
$fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10);

$fruitsArrayObject = new ArrayObject($fruits);

// Try to use array key as property
var_dump($fruitsArrayObject->lemons);
// Set the flag so that the array keys can be used as properties of the ArrayObject
$fruitsArrayObject->setFlags(ArrayObject::ARRAY_AS_PROPS);
// Try it again
var_dump($fruitsArrayObject->lemons);
?>

The above example will output:

NULL
int(1)


Sets the iterator classname for the ArrayObject

  • « ArrayObject::setFlags
  • ArrayObject::uasort »
  • PHP Manual
  • ArrayObject
  • Sets the iterator classname for the ArrayObject

ArrayObject::setIteratorClass

(PHP 5 >= 5.1.0, PHP 7)

ArrayObject::setIteratorClass — Sets the iterator classname for the ArrayObject

Description

public ArrayObject::setIteratorClass ( string $iterator_class ) : void

Sets the classname of the array iterator that is used by ArrayObject::getIterator().

Parameters

iterator_class

The classname of the array iterator to use when iterating over this object.

Return Values

No value is returned.

Examples

Example #1 ArrayObject::setIteratorClass() example

<?php
// Custom ArrayIterator (inherits from ArrayIterator)
class MyArrayIterator extends ArrayIterator {
    // custom implementation
}

// Array of available fruits
$fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10);

$fruitsArrayObject = new ArrayObject($fruits);

// Set the iterator classname to the newly
$fruitsArrayObject->setIteratorClass('MyArrayIterator');
print_r($fruitsArrayObject->getIterator());

?>

The above example will output:

MyArrayIterator Object
(
    [lemons] => 1
    [oranges] => 4
    [bananas] => 5
    [apples] => 10
)


Sort the entries with a user-defined comparison function and maintain key association

  • « ArrayObject::setIteratorClass
  • ArrayObject::uksort »
  • PHP Manual
  • ArrayObject
  • Sort the entries with a user-defined comparison function and maintain key association

ArrayObject::uasort

(PHP 5 >= 5.2.0, PHP 7)

ArrayObject::uasort — Sort the entries with a user-defined comparison function and maintain key association

Description

public ArrayObject::uasort ( callable $cmp_function ) : void

This function sorts the entries such that keys maintain their correlation with the entry that they are associated with, using a user-defined comparison function.

This is used mainly when sorting associative arrays where the actual element order is significant.

Parameters

cmp_function

Function cmp_function should accept two parameters which will be filled by pairs of entries. The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Return Values

No value is returned.

Examples

Example #1 ArrayObject::uasort() example

<?php
// Comparison function
function cmp($a, $b) {
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

// Array to be sorted
$array = array('a' => 4, 'b' => 8, 'c' => -1, 'd' => -9, 'e' => 2, 'f' => 5, 'g' => 3, 'h' => -4);
$arrayObject = new ArrayObject($array);
print_r($arrayObject);

// Sort and print the resulting array
$arrayObject->uasort('cmp');
print_r($arrayObject);
?>

The above example will output:

Array
(
    [a] => 4
    [b] => 8
    [c] => -1
    [d] => -9
    [e] => 2
    [f] => 5
    [g] => 3
    [h] => -4
)
Array
(
    [d] => -9
    [h] => -4
    [c] => -1
    [e] => 2
    [g] => 3
    [a] => 4
    [f] => 5
    [b] => 8
)

See Also

  • ArrayObject::asort() - Sort the entries by value
  • ArrayObject::ksort() - Sort the entries by key
  • ArrayObject::natsort() - Sort entries using a "natural order" algorithm
  • ArrayObject::natcasesort() - Sort an array using a case insensitive "natural order" algorithm
  • ArrayObject::uksort() - Sort the entries by keys using a user-defined comparison function


Sort the entries by keys using a user-defined comparison function

  • « ArrayObject::uasort
  • ArrayObject::unserialize »
  • PHP Manual
  • ArrayObject
  • Sort the entries by keys using a user-defined comparison function

ArrayObject::uksort

(PHP 5 >= 5.2.0, PHP 7)

ArrayObject::uksort — Sort the entries by keys using a user-defined comparison function

Description

public ArrayObject::uksort ( callable $cmp_function ) : void

This function sorts the keys of the entries using a user-supplied comparison function. The key to entry correlations will be maintained.

Parameters

cmp_function

The callback comparison function.

Function cmp_function should accept two parameters which will be filled by pairs of entry keys. The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Return Values

No value is returned.

Examples

Example #1 ArrayObject::uksort() example

<?php
function cmp($a, $b) {
    $a = preg_replace('@^(a|an|the) @', '', $a);
    $b = preg_replace('@^(a|an|the) @', '', $b);
    return strcasecmp($a, $b);
}

$array = array("John" => 1, "the Earth" => 2, "an apple" => 3, "a banana" => 4);
$arrayObject = new ArrayObject($array);
$arrayObject->uksort('cmp');

foreach ($arrayObject as $key => $value) {
    echo "$key: $value\n";
}
?>

The above example will output:

an apple: 3
a banana: 4
the Earth: 2
John: 1

See Also

  • ArrayObject::asort() - Sort the entries by value
  • ArrayObject::ksort() - Sort the entries by key
  • ArrayObject::natsort() - Sort entries using a "natural order" algorithm
  • ArrayObject::natcasesort() - Sort an array using a case insensitive "natural order" algorithm
  • ArrayObject::uasort() - Sort the entries with a user-defined comparison function and maintain key association


Unserialize an ArrayObject

  • « ArrayObject::uksort
  • SplObserver »
  • PHP Manual
  • ArrayObject
  • Unserialize an ArrayObject

ArrayObject::unserialize

(PHP 5 >= 5.3.0, PHP 7)

ArrayObject::unserialize — Unserialize an ArrayObject

Description

public ArrayObject::unserialize ( string $serialized ) : void

Unserializes a serialized ArrayObject.

Warning

This function is currently not documented; only its argument list is available.

Parameters

serialized

The serialized ArrayObject.

Return Values

The unserialized ArrayObject.

See Also

  • ArrayIterator::serialize() - Serialize
  • unserialize() - Creates a PHP value from a stored representation
  • Serializing Objects


The SplObserver interface

(PHP 5 >= 5.1.0, PHP 7)

Introduction

The SplObserver interface is used alongside SplSubject to implement the Observer Design Pattern.

Interface synopsis

SplObserver {
/* Methods */
abstract public update ( SplSubject $subject ) : void
}

Table of Contents

  • SplObserver::update — Receive update from subject


Receive update from subject

  • « SplObserver
  • SplSubject »
  • PHP Manual
  • SplObserver
  • Receive update from subject

SplObserver::update

(PHP 5 >= 5.1.0, PHP 7)

SplObserver::update — Receive update from subject

Description

abstract public SplObserver::update ( SplSubject $subject ) : void

This method is called when any SplSubject to which the observer is attached calls SplSubject::notify().

Warning

This function is currently not documented; only its argument list is available.

Parameters

subject

The SplSubject notifying the observer of an update.

Return Values

No value is returned.


The SplSubject interface

(PHP 5 >= 5.1.0, PHP 7)

Introduction

The SplSubject interface is used alongside SplObserver to implement the Observer Design Pattern.

Interface synopsis

SplSubject {
/* Methods */
abstract public attach ( SplObserver $observer ) : void
abstract public detach ( SplObserver $observer ) : void
abstract public notify ( void ) : void
}

Table of Contents

  • SplSubject::attach — Attach an SplObserver
  • SplSubject::detach — Detach an observer
  • SplSubject::notify — Notify an observer


Attach an SplObserver

  • « SplSubject
  • SplSubject::detach »
  • PHP Manual
  • SplSubject
  • Attach an SplObserver

SplSubject::attach

(PHP 5 >= 5.1.0, PHP 7)

SplSubject::attach — Attach an SplObserver

Description

abstract public SplSubject::attach ( SplObserver $observer ) : void

Attaches an SplObserver so that it can be notified of updates.

Warning

This function is currently not documented; only its argument list is available.

Parameters

observer

The SplObserver to attach.

Return Values

No value is returned.


Detach an observer

  • « SplSubject::attach
  • SplSubject::notify »
  • PHP Manual
  • SplSubject
  • Detach an observer

SplSubject::detach

(PHP 5 >= 5.1.0, PHP 7)

SplSubject::detach — Detach an observer

Description

abstract public SplSubject::detach ( SplObserver $observer ) : void

Detaches an observer from the subject to no longer notify it of updates.

Warning

This function is currently not documented; only its argument list is available.

Parameters

observer

The SplObserver to detach.

Return Values

No value is returned.


Notify an observer

  • « SplSubject::detach
  • SPL Types »
  • PHP Manual
  • SplSubject
  • Notify an observer

SplSubject::notify

(PHP 5 >= 5.1.0, PHP 7)

SplSubject::notify — Notify an observer

Description

abstract public SplSubject::notify ( void ) : void

Notifies all attached observers.

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.


SPL Type Handling

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • SplType — The SplType class
    • SplType::__construct — Creates a new value of some type
  • SplInt — The SplInt class
  • SplFloat — The SplFloat class
  • SplEnum — The SplEnum class
    • SplEnum::getConstList — Returns all consts (possible values) as an array
  • SplBool — The SplBool class
  • SplString — The SplString class


Introduction

This extension aims at helping people making PHP a stronger typed language and can be a good alternative to scalar type hinting. It provides different typehandling classes as such as integer, float, bool, enum and string

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.


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/SPL_Types.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.


  • « Runtime Configuration
  • SplType »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

This extension has no resource types defined.


The SplType class

(PECL spl_types >= 0.1.0)

Introduction

Parent class for all SPL types.

Class synopsis

abstract SplType {
/* Constants */
const NULL __default = NULL ;
/* Methods */
__construct ([ mixed $initial_value [, bool $strict ]] )
}

Predefined Constants

SplType::__default

Table of Contents

  • SplType::__construct — Creates a new value of some type


Creates a new value of some type

  • « SplType
  • SplInt »
  • PHP Manual
  • SplType
  • Creates a new value of some type

SplType::__construct

(PECL spl_types >= 0.1.0)

SplType::__construct — Creates a new value of some type

Description

SplType::__construct ([ mixed $initial_value [, bool $strict ]] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

initial_value

Type and default value depends on the extension class.

strict

Whether to set the object's sctrictness.

Errors/Exceptions

Throws an UnexpectedValueException if incompatible type is given.


The SplInt class

(PECL spl_types >= 0.1.0)

Introduction

The SplInt class is used to enforce strong typing of the integer type.

Class synopsis

SplInt extends SplType {
/* Constants */
const integer __default = 0 ;
/* Inherited methods */
SplType::__construct ([ mixed $initial_value [, bool $strict ]] )
}

Predefined Constants

SplInt::__default

Examples

Example #1 SplInt usage example

<?php
$int = new SplInt(94);

try {
    $int = 'Try to cast a string value for fun';
} catch (UnexpectedValueException $uve) {
    echo $uve->getMessage() . PHP_EOL;
}

echo $int . PHP_EOL;
?>

The above example will output:

Value not an integer
94


The SplFloat class

(PECL spl_types >= 0.1.0)

Introduction

The SplFloat class is used to enforce strong typing of the float type.

Class synopsis

SplFloat extends SplType {
/* Constants */
const float __default = 0 ;
/* Inherited methods */
SplType::__construct ([ mixed $initial_value [, bool $strict ]] )
}

Predefined Constants

SplFloat::__default

Examples

Example #1 SplFloat usage example

<?php
$float = new SplFloat(3.154);
$newFloat = new SplFloat(3);

try {
    $float = 'Try to cast a string value for fun';
} catch (UnexpectedValueException $uve) {
    echo $uve->getMessage() . PHP_EOL;
}

echo $float . PHP_EOL;
echo $newFloat . PHP_EOL;
?>

The above example will output:

Value not a float
3.154
3


The SplEnum class

(PECL spl_types >= 0.1.0)

Introduction

SplEnum gives the ability to emulate and create enumeration objects natively in PHP.

Class synopsis

SplEnum extends SplType {
/* Constants */
const NULL __default = NULL ;
/* Methods */
public getConstList ([ bool $include_default = FALSE ] ) : array
/* Inherited methods */
SplType::__construct ([ mixed $initial_value [, bool $strict ]] )
}

Predefined Constants

SplEnum::__default

Examples

Example #1 SplEnum usage example

<?php
class Month extends SplEnum {
    const __default = self::January;

    const January = 1;
    const February = 2;
    const March = 3;
    const April = 4;
    const May = 5;
    const June = 6;
    const July = 7;
    const August = 8;
    const September = 9;
    const October = 10;
    const November = 11;
    const December = 12;
}

echo new Month(Month::June) . PHP_EOL;

try {
    new Month(13);
} catch (UnexpectedValueException $uve) {
    echo $uve->getMessage() . PHP_EOL;
}
?>

The above example will output:

6
Value not a const in enum Month

Table of Contents

  • SplEnum::getConstList — Returns all consts (possible values) as an array


Returns all consts (possible values) as an array

  • « SplEnum
  • SplBool »
  • PHP Manual
  • SplEnum
  • Returns all consts (possible values) as an array

SplEnum::getConstList

(PECL spl_types >= 0.1.0)

SplEnum::getConstList — Returns all consts (possible values) as an array

Description

public SplEnum::getConstList ([ bool $include_default = FALSE ] ) : array

Warning

This function is currently not documented; only its argument list is available.

Parameters

include_default

Whether to include __default property.

Return Values

Examples

Example #1 SplEnum::getConstList() example

<?php
$bool = new SplBool;
var_dump($bool->getConstList(true));
?>

The above example will output:

array(3) {
  ["__default"]=>
  bool(false)
  ["false"]=>
  bool(false)
  ["true"]=>
  bool(true)
}


The SplBool class

(PECL spl_types >= 0.1.0)

Introduction

The SplBool class is used to enforce strong typing of the bool type.

Class synopsis

SplBool extends SplEnum {
/* Constants */
const boolean __default = FALSE ;
const boolean false = FALSE ;
const boolean true = TRUE ;
/* Inherited methods */
public SplEnum::getConstList ([ bool $include_default = FALSE ] ) : array
}

Predefined Constants

SplBool::__default

SplBool::false

SplBool::true

Examples

Example #1 SplBool usage example

<?php
$true = new SplBool(true);
if ($true) {
    echo "TRUE\n";
}

$false = new SplBool;
if ($false) {
    echo "FALSE\n";
}
?>

The above example will output:

TRUE


The SplString class

(PECL spl_types >= 0.1.0)

Introduction

The SplString class is used to enforce strong typing of the string type.

Class synopsis

SplString extends SplType {
/* Constants */
const string __default = '' ;
/* Inherited methods */
SplType::__construct ([ mixed $initial_value [, bool $strict ]] )
}

Predefined Constants

SplString::__default

Examples

Example #1 SplString usage example

<?php
$string = new SplString("Testing");

try {
    $string = array();
} catch (UnexpectedValueException $uve) {
    echo $uve->getMessage() . PHP_EOL;
}

var_dump($string);
echo $string; // Outputs "Testing"
?>

The above example will output:

Value not a string
object(SplString)#1 (1) {
  ["__default"]=>
  string(7) "Testing"
}
Testing


Streams

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Stream Classes
  • Predefined Constants
  • Stream Filters
  • Stream Contexts
  • Stream Errors
  • Examples
    • Example class registered as stream wrapper
  • php_user_filter — The php_user_filter class
    • php_user_filter::filter — Called when applying the filter
    • php_user_filter::onClose — Called when closing the filter
    • php_user_filter::onCreate — Called when creating the filter
  • streamWrapper — The streamWrapper class
    • streamWrapper::__construct — Constructs a new stream wrapper
    • streamWrapper::__destruct — Destructs an existing stream wrapper
    • streamWrapper::dir_closedir — Close directory handle
    • streamWrapper::dir_opendir — Open directory handle
    • streamWrapper::dir_readdir — Read entry from directory handle
    • streamWrapper::dir_rewinddir — Rewind directory handle
    • streamWrapper::mkdir — Create a directory
    • streamWrapper::rename — Renames a file or directory
    • streamWrapper::rmdir — Removes a directory
    • streamWrapper::stream_cast — Retrieve the underlaying resource
    • streamWrapper::stream_close — Close a resource
    • streamWrapper::stream_eof — Tests for end-of-file on a file pointer
    • streamWrapper::stream_flush — Flushes the output
    • streamWrapper::stream_lock — Advisory file locking
    • streamWrapper::stream_metadata — Change stream metadata
    • streamWrapper::stream_open — Opens file or URL
    • streamWrapper::stream_read — Read from stream
    • streamWrapper::stream_seek — Seeks to specific location in a stream
    • streamWrapper::stream_set_option — Change stream options
    • streamWrapper::stream_stat — Retrieve information about a file resource
    • streamWrapper::stream_tell — Retrieve the current position of a stream
    • streamWrapper::stream_truncate — Truncate stream
    • streamWrapper::stream_write — Write to stream
    • streamWrapper::unlink — Delete a file
    • streamWrapper::url_stat — Retrieve information about a file
  • Stream Functions
    • set_socket_blocking — Alias of stream_set_blocking
    • stream_bucket_append — Append bucket to brigade
    • stream_bucket_make_writeable — Return a bucket object from the brigade for operating on
    • stream_bucket_new — Create a new bucket for use on the current stream
    • stream_bucket_prepend — Prepend bucket to brigade
    • stream_context_create — Creates a stream context
    • stream_context_get_default — Retrieve the default stream context
    • stream_context_get_options — Retrieve options for a stream/wrapper/context
    • stream_context_get_params — Retrieves parameters from a context
    • stream_context_set_default — Set the default stream context
    • stream_context_set_option — Sets an option for a stream/wrapper/context
    • stream_context_set_params — Set parameters for a stream/wrapper/context
    • stream_copy_to_stream — Copies data from one stream to another
    • stream_filter_append — Attach a filter to a stream
    • stream_filter_prepend — Attach a filter to a stream
    • stream_filter_register — Register a user defined stream filter
    • stream_filter_remove — Remove a filter from a stream
    • stream_get_contents — Reads remainder of a stream into a string
    • stream_get_filters — Retrieve list of registered filters
    • stream_get_line — Gets line from stream resource up to a given delimiter
    • stream_get_meta_data — Retrieves header/meta data from streams/file pointers
    • stream_get_transports — Retrieve list of registered socket transports
    • stream_get_wrappers — Retrieve list of registered streams
    • stream_is_local — Checks if a stream is a local stream
    • stream_isatty — Check if a stream is a TTY
    • stream_notification_callback — A callback function for the notification context parameter
    • stream_register_wrapper — Alias of stream_wrapper_register
    • stream_resolve_include_path — Resolve filename against the include path
    • stream_select — Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec
    • stream_set_blocking — Set blocking/non-blocking mode on a stream
    • stream_set_chunk_size — Set the stream chunk size
    • stream_set_read_buffer — Set read file buffering on the given stream
    • stream_set_timeout — Set timeout period on a stream
    • stream_set_write_buffer — Sets write file buffering on the given stream
    • stream_socket_accept — Accept a connection on a socket created by stream_socket_server
    • stream_socket_client — Open Internet or Unix domain socket connection
    • stream_socket_enable_crypto — Turns encryption on/off on an already connected socket
    • stream_socket_get_name — Retrieve the name of the local or remote sockets
    • stream_socket_pair — Creates a pair of connected, indistinguishable socket streams
    • stream_socket_recvfrom — Receives data from a socket, connected or not
    • stream_socket_sendto — Sends a message to a socket, whether it is connected or not
    • stream_socket_server — Create an Internet or Unix domain server socket
    • stream_socket_shutdown — Shutdown a full-duplex connection
    • stream_supports_lock — Tells whether the stream supports locking
    • stream_wrapper_register — Register a URL wrapper implemented as a PHP class
    • stream_wrapper_restore — Restores a previously unregistered built-in wrapper
    • stream_wrapper_unregister — Unregister a URL wrapper


Introduction

Streams are the way of generalizing file, network, data compression, and other operations which share a common set of functions and uses. In its simplest definition, a stream is a resource object which exhibits streamable behavior. That is, it can be read from or written to in a linear fashion, and may be able to fseek() to an arbitrary location within the stream.

A wrapper is additional code which tells the stream how to handle specific protocols/encodings. For example, the http wrapper knows how to translate a URL into an HTTP/1.0 request for a file on a remote server. There are many wrappers built into PHP by default (See Supported Protocols and Wrappers), and additional, custom wrappers may be added either within a PHP script using stream_wrapper_register(), or directly from an extension using the API Reference in Working with streams. Because any variety of wrapper may be added to PHP, there is no set limit on what can be done with them. To access the list of currently registered wrappers, use stream_get_wrappers().

A stream is referenced as: scheme://target

  • scheme(string) - The name of the wrapper to be used. Examples include: file, http, https, ftp, ftps, compress.zlib, compress.bz2, and php. See Supported Protocols and Wrappers for a list of PHP built-in wrappers. If no wrapper is specified, the function default is used (typically file://).
  • target - Depends on the wrapper used. For filesystem related streams this is typically a path and filename of the desired file. For network related streams this is typically a hostname, often with a path appended. Again, see Supported Protocols and Wrappers for a description of targets for built-in streams.

Note:

Information on using streams within the PHP source code can be found in the Streams API for PHP Extension Authors reference.


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Stream Classes


  • « Installation
  • Stream Classes »
  • PHP Manual
  • Installing/Configuring
  • Runtime Configuration

Runtime Configuration

This extension has no configuration directives defined in php.ini.


Stream Classes

User designed wrappers can be registered via stream_wrapper_register(), using the class definition shown on that manual page.

Class php_user_filter is predefined and is an abstract baseclass for use with user defined filters. See the manual page for stream_filter_register() for details on implementing user defined filters.


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.

Constant | Description
STREAM_FILTER_READ | Used with stream_filter_append() and stream_filter_prepend() to indicate that the specified filter should only be applied when reading
STREAM_FILTER_WRITE | Used with stream_filter_append() and stream_filter_prepend() to indicate that the specified filter should only be applied when writing
STREAM_FILTER_ALL | This constant is equivalent to STREAM_FILTER_READ | STREAM_FILTER_WRITE
PSFS_PASS_ON | Return Code indicating that the userspace filter returned buckets in $out.
PSFS_FEED_ME | Return Code indicating that the userspace filter did not return buckets in $out (i.e. No data available).
PSFS_ERR_FATAL | Return Code indicating that the userspace filter encountered an unrecoverable error (i.e. Invalid data received).
PSFS_FLAG_NORMAL | Regular read/write.
PSFS_FLAG_FLUSH_INC | An incremental flush.
PSFS_FLAG_FLUSH_CLOSE | Final flush prior to closing.
STREAM_USE_PATH | Flag indicating if the stream used the include path.
STREAM_REPORT_ERRORS | Flag indicating if the wrapper is responsible for raising errors using trigger_error() during opening of the stream. If this flag is not set, you should not raise any errors.
STREAM_CLIENT_ASYNC_CONNECT | Open client socket asynchronously. This option must be used together with the STREAM_CLIENT_CONNECT flag. Used with stream_socket_client().
STREAM_CLIENT_CONNECT | Open client socket connection. Client sockets should always include this flag. Used with stream_socket_client().
STREAM_CLIENT_PERSISTENT | Client socket opened with stream_socket_client() should remain persistent between page loads.
STREAM_SERVER_BIND | Tells a stream created with stream_socket_server() to bind to the specified target. Server sockets should always include this flag.
STREAM_SERVER_LISTEN | Tells a stream created with stream_socket_server() and bound using the STREAM_SERVER_BIND flag to start listening on the socket. Connection-orientated transports (such as TCP) must use this flag, otherwise the server socket will not be enabled. Using this flag for connect-less transports (such as UDP) is an error.
STREAM_NOTIFY_RESOLVE | A remote address required for this stream has been resolved, or the resolution failed. See severity for an indication of which happened.
STREAM_NOTIFY_CONNECT | A connection with an external resource has been established.
STREAM_NOTIFY_AUTH_REQUIRED | Additional authorization is required to access the specified resource. Typical issued with severity level of STREAM_NOTIFY_SEVERITY_ERR.
STREAM_NOTIFY_MIME_TYPE_IS | The mime-type of resource has been identified, refer to message for a description of the discovered type.
STREAM_NOTIFY_FILE_SIZE_IS | The size of the resource has been discovered.
STREAM_NOTIFY_REDIRECTED | The external resource has redirected the stream to an alternate location. Refer to message.
STREAM_NOTIFY_PROGRESS | Indicates current progress of the stream transfer in bytes_transferred and possibly bytes_max as well.
STREAM_NOTIFY_COMPLETED | There is no more data available on the stream.
STREAM_NOTIFY_FAILURE | A generic error occurred on the stream, consult message and message_code for details.
STREAM_NOTIFY_AUTH_RESULT | Authorization has been completed (with or without success).
STREAM_NOTIFY_SEVERITY_INFO | Normal, non-error related, notification.
STREAM_NOTIFY_SEVERITY_WARN | Non critical error condition. Processing may continue.
STREAM_NOTIFY_SEVERITY_ERR | A critical error occurred. Processing cannot continue.
STREAM_IPPROTO_ICMP + | Provides a ICMP socket.
STREAM_IPPROTO_IP + | Provides a IP socket.
STREAM_IPPROTO_RAW + | Provides a RAW socket.
STREAM_IPPROTO_TCP + | Provides a TCP socket.
STREAM_IPPROTO_UDP + | Provides a UDP socket.
STREAM_PF_INET + | Internet Protocol Version 4 (IPv4).
STREAM_PF_INET6 + | Internet Protocol Version 6 (IPv6).
STREAM_PF_UNIX + | Unix system internal protocols.
STREAM_SOCK_DGRAM + | Provides datagrams, which are connectionless messages (UDP, for example).
STREAM_SOCK_RAW + | Provides a raw socket, which provides access to internal network protocols and interfaces. Usually this type of socket is just available to the root user.
STREAM_SOCK_RDM + | Provides a RDM (Reliably-delivered messages) socket.
STREAM_SOCK_SEQPACKET + | Provides a sequenced packet stream socket.
STREAM_SOCK_STREAM + | Provides sequenced, two-way byte streams with a transmission mechanism for out-of-band data (TCP, for example).
STREAM_SHUT_RD | Used with stream_socket_shutdown() to disable further receptions. Added in PHP 5.2.1.
STREAM_SHUT_WR | Used with stream_socket_shutdown() to disable further transmissions. Added in PHP 5.2.1.
STREAM_SHUT_RDWR | Used with stream_socket_shutdown() to disable further receptions and transmissions. Added in PHP 5.2.1.
STREAM_CAST_FOR_SELECT | Stream casting, for when stream_select() is calling stream_cast().
STREAM_CAST_AS_STREAM | Stream casting, when stream_cast() is called otherwise (see above).
STREAM_META_TOUCH | Used with stream_metadata(), to specify touch() call.
STREAM_META_OWNER | Used with stream_metadata(), to specify chown() call.
STREAM_META_OWNER_NAME | Used with stream_metadata(), to specify chown() call.
STREAM_META_GROUP | Used with stream_metadata(), to specify chgrp() call.
STREAM_META_GROUP_NAME | Used with stream_metadata(), to specify chgrp() call.
STREAM_META_ACCESS | Used with stream_metadata(), to specify chmod() call.

Note: The constants marked with + are available since PHP 5.1.0 and are meant to be used with stream_socket_pair(). Please note that some of these constants might not be available in your system.

Note: The STREAM_META_* constants are available since PHP 5.4.0 and are meant to be used with stream_metadata().


Stream Filters

A filter is a final piece of code which may perform operations on data as it is being read from or written to a stream. Any number of filters may be stacked onto a stream. Custom filters can be defined in a PHP script using stream_filter_register() or in an extension using the API Reference in Working with streams. To access the list of currently registered filters, use stream_get_filters().


Stream Contexts

A context is a set of parameters and wrapper specific options which modify or enhance the behavior of a stream. Contexts are created using stream_context_create() and can be passed to most filesystem related stream creation functions (i.e. fopen(), file(), file_get_contents(), etc...).

Options can be specified when calling stream_context_create(), or later using stream_context_set_option(). A list of wrapper specific options can be found in the Context options and parameters chapter.

Parameters can be specified for contexts using the stream_context_set_params() function.


Stream Errors

As with any file or socket related function, an operation on a stream may fail for a variety of normal reasons (i.e.: Unable to connect to remote host, file not found, etc...). A stream related call may also fail because the desired stream is not registered on the running system. See the array returned by stream_get_wrappers() for a list of streams supported by your installation of PHP. As with most PHP internal functions if a failure occurs an E_WARNING message will be generated describing the nature of the error.


Examples

Table of Contents

  • Example class registered as stream wrapper

Example #1 Using file_get_contents() to retrieve data from multiple sources

<?php
/* Read local file from /home/bar */
$localfile = file_get_contents("/home/bar/foo.txt");

/* Identical to above, explicitly naming FILE scheme */
$localfile = file_get_contents("file:///home/bar/foo.txt");

/* Read remote file from www.example.com using HTTP */
$httpfile  = file_get_contents("http://www.example.com/foo.txt");

/* Read remote file from www.example.com using HTTPS */
$httpsfile = file_get_contents("https://www.example.com/foo.txt");

/* Read remote file from ftp.example.com using FTP */
$ftpfile   = file_get_contents("ftp://user:pass@ftp.example.com/foo.txt");

/* Read remote file from ftp.example.com using FTPS */
$ftpsfile  = file_get_contents("ftps://user:pass@ftp.example.com/foo.txt");
?>

Example #2 Making a POST request to an https server

<?php
/* Send POST request to https://secure.example.com/form_action.php
* Include form elements named "foo" and "bar" with dummy values
*/

$sock = fsockopen("ssl://secure.example.com", 443, $errno, $errstr, 30);
if (!$sock) die("$errstr ($errno)\n");

$data = "foo=" . urlencode("Value for Foo") . "&bar=" . urlencode("Value for Bar");

fwrite($sock, "POST /form_action.php HTTP/1.0\r\n");
fwrite($sock, "Host: secure.example.com\r\n");
fwrite($sock, "Content-type: application/x-www-form-urlencoded\r\n");
fwrite($sock, "Content-length: " . strlen($data) . "\r\n");
fwrite($sock, "Accept: */*\r\n");
fwrite($sock, "\r\n");
fwrite($sock, $data);

$headers = "";
while ($str = trim(fgets($sock, 4096)))
$headers .= "$str\n";

echo "\n";

$body = "";
while (!feof($sock))
$body .= fgets($sock, 4096);

fclose($sock);
?>

Example #3 Writing data to a compressed file

<?php
/* Create a compressed file containing an arbitrarty string
* File can be read back using compress.zlib stream or just
* decompressed from the command line using 'gzip -d foo-bar.txt.gz'
*/
$fp = fopen("compress.zlib://foo-bar.txt.gz", "wb");
if (!$fp) die("Unable to create file.");

fwrite($fp, "This is a test.\n");

fclose($fp);
?>


Example class registered as stream wrapper

The example below implements a var:// protocol handler that allows read/write access to a named global variable using standard filesystem stream functions such as fread(). The var:// protocol implemented below, given the URL "var://foo" will read/write data to/from $GLOBALS["foo"].

Example #1 A Stream for reading/writing global variables

<?php

class VariableStream {
    var $position;
    var $varname;

    function stream_open($path, $mode, $options, &$opened_path)
    {
        $url = parse_url($path);
        $this->varname = $url["host"];
        $this->position = 0;

        return true;
    }

    function stream_read($count)
    {
        $ret = substr($GLOBALS[$this->varname], $this->position, $count);
        $this->position += strlen($ret);
        return $ret;
    }

    function stream_write($data)
    {
        $left = substr($GLOBALS[$this->varname], 0, $this->position);
        $right = substr($GLOBALS[$this->varname], $this->position + strlen($data));
        $GLOBALS[$this->varname] = $left . $data . $right;
        $this->position += strlen($data);
        return strlen($data);
    }

    function stream_tell()
    {
        return $this->position;
    }

    function stream_eof()
    {
        return $this->position >= strlen($GLOBALS[$this->varname]);
    }

    function stream_seek($offset, $whence)
    {
        switch ($whence) {
            case SEEK_SET:
                if ($offset < strlen($GLOBALS[$this->varname]) && $offset >= 0) {
                     $this->position = $offset;
                     return true;
                } else {
                     return false;
                }
                break;

            case SEEK_CUR:
                if ($offset >= 0) {
                     $this->position += $offset;
                     return true;
                } else {
                     return false;
                }
                break;

            case SEEK_END:
                if (strlen($GLOBALS[$this->varname]) + $offset >= 0) {
                     $this->position = strlen($GLOBALS[$this->varname]) + $offset;
                     return true;
                } else {
                     return false;
                }
                break;

            default:
                return false;
        }
    }

    function stream_metadata($path, $option, $var)
    {
        if($option == STREAM_META_TOUCH) {
            $url = parse_url($path);
            $varname = $url["host"];
            if(!isset($GLOBALS[$varname])) {
                $GLOBALS[$varname] = '';
            }
            return true;
        }
        return false;
    }
}

stream_wrapper_register("var", "VariableStream")
    or die("Failed to register protocol");

$myvar = "";

$fp = fopen("var://myvar", "r+");

fwrite($fp, "line1\n");
fwrite($fp, "line2\n");
fwrite($fp, "line3\n");

rewind($fp);
while (!feof($fp)) {
    echo fgets($fp);
}
fclose($fp);
var_dump($myvar);

?>

The above example will output:

line1
line2
line3
string(18) "line1
line2
line3
"


The php_user_filter class

(PHP 5, PHP 7)

Introduction

Children of this class are passed to stream_filter_register().

Class synopsis

php_user_filter {
/* Properties */
public $filtername ;
public $params ;
/* Methods */
public filter ( resource $in , resource $out , int &$consumed , bool $closing ) : int
public onClose ( void ) : void
public onCreate ( void ) : bool
}

Properties

filtername

Name of the filter registered by stream_filter_append().

params

Table of Contents

  • php_user_filter::filter — Called when applying the filter
  • php_user_filter::onClose — Called when closing the filter
  • php_user_filter::onCreate — Called when creating the filter


Called when applying the filter

  • « php_user_filter
  • php_user_filter::onClose »
  • PHP Manual
  • php_user_filter
  • Called when applying the filter

php_user_filter::filter

(PHP 5, PHP 7)

php_user_filter::filter — Called when applying the filter

Description

public php_user_filter::filter ( resource $in , resource $out , int &$consumed , bool $closing ) : int

This method is called whenever data is read from or written to the attached stream (such as with fread() or fwrite()).

Parameters

in

in is a resource pointing to a bucket brigade which contains one or more bucket objects containing data to be filtered.

out

out is a resource pointing to a second bucket brigade into which your modified buckets should be placed.

consumed

consumed, which must always be declared by reference, should be incremented by the length of the data which your filter reads in and alters. In most cases this means you will increment consumed by $bucket->datalen for each $bucket.

closing

If the stream is in the process of closing (and therefore this is the last pass through the filterchain), the closing parameter will be set to TRUE.

Return Values

The filter() method must return one of three values upon completion.

Return Value | Meaning
PSFS_PASS_ON | Filter processed successfully with data available in the out bucket brigade.
PSFS_FEED_ME | Filter processed successfully, however no data was available to return. More data is required from the stream or prior filter.
PSFS_ERR_FATAL (default) | The filter experienced an unrecoverable error and cannot continue.


Called when closing the filter

  • « php_user_filter::filter
  • php_user_filter::onCreate »
  • PHP Manual
  • php_user_filter
  • Called when closing the filter

php_user_filter::onClose

(PHP 5, PHP 7)

php_user_filter::onClose — Called when closing the filter

Description

public php_user_filter::onClose ( void ) : void

This method is called upon filter shutdown (typically, this is also during stream shutdown), and is executed after the flush method is called. If any resources were allocated or initialized during onCreate() this would be the time to destroy or dispose of them.

Parameters

This function has no parameters.

Return Values

Return value is ignored.


Called when creating the filter

  • « php_user_filter::onClose
  • streamWrapper »
  • PHP Manual
  • php_user_filter
  • Called when creating the filter

php_user_filter::onCreate

(PHP 5, PHP 7)

php_user_filter::onCreate — Called when creating the filter

Description

public php_user_filter::onCreate ( void ) : bool

This method is called during instantiation of the filter class object. If your filter allocates or initializes any other resources (such as a buffer), this is the place to do it.

When your filter is first instantiated, and yourfilter->onCreate() is called, a number of properties will be available as shown in the table below.

Property | Contents
FilterClass->filtername | A string containing the name the filter was instantiated with. Filters may be registered under multiple names or under wildcards. Use this property to determine which name was used.
FilterClass->params | The contents of the params parameter passed to stream_filter_append() or stream_filter_prepend().
FilterClass->stream | The stream resource being filtered. Maybe available only during filter() calls when the closing parameter is set to FALSE.

Parameters

This function has no parameters.

Return Values

Your implementation of this method should return FALSE on failure, or TRUE on success.


The streamWrapper class

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

Introduction

Allows you to implement your own protocol handlers and streams for use with all the other filesystem functions (such as fopen(), fread() etc.).

Note:

This is NOT a real class, only a prototype of how a class defining its own protocol should be.

Note:

Implementing the methods in other ways than described here can lead to undefined behaviour.

An instance of this class is initialized as soon as a stream function tries to access the protocol it is associated with.

Class synopsis

streamWrapper {
/* Properties */
public resource $context ;
/* Methods */
__construct ( void )
__destruct ( void )
public dir_closedir ( void ) : bool
public dir_opendir ( string $path , int $options ) : bool
public dir_readdir ( void ) : string
public dir_rewinddir ( void ) : bool
public mkdir ( string $path , int $mode , int $options ) : bool
public rename ( string $path_from , string $path_to ) : bool
public rmdir ( string $path , int $options ) : bool
public stream_cast ( int $cast_as ) : resource
public stream_close ( void ) : void
public stream_eof ( void ) : bool
public stream_flush ( void ) : bool
public stream_lock ( int $operation ) : bool
public stream_metadata ( string $path , int $option , mixed $value ) : bool
public stream_open ( string $path , string $mode , int $options , string &$opened_path ) : bool
public stream_read ( int $count ) : string
public stream_seek ( int $offset , int $whence = SEEK_SET ) : bool
public stream_set_option ( int $option , int $arg1 , int $arg2 ) : bool
public stream_stat ( void ) : array
public stream_tell ( void ) : int
public stream_truncate ( int $new_size ) : bool
public stream_write ( string $data ) : int
public unlink ( string $path ) : bool
public url_stat ( string $path , int $flags ) : array
}

Properties

resource context

The current context, or NULL if no context was passed to the caller function.

Use the stream_context_get_options() to parse the context.

Note:

This property must be public so PHP can populate it with the actual context resource.

See Also

  • Example class registered as stream wrapper
  • stream_wrapper_register()
  • stream_wrapper_unregister()
  • stream_wrapper_restore()

Table of Contents

  • streamWrapper::__construct — Constructs a new stream wrapper
  • streamWrapper::__destruct — Destructs an existing stream wrapper
  • streamWrapper::dir_closedir — Close directory handle
  • streamWrapper::dir_opendir — Open directory handle
  • streamWrapper::dir_readdir — Read entry from directory handle
  • streamWrapper::dir_rewinddir — Rewind directory handle
  • streamWrapper::mkdir — Create a directory
  • streamWrapper::rename — Renames a file or directory
  • streamWrapper::rmdir — Removes a directory
  • streamWrapper::stream_cast — Retrieve the underlaying resource
  • streamWrapper::stream_close — Close a resource
  • streamWrapper::stream_eof — Tests for end-of-file on a file pointer
  • streamWrapper::stream_flush — Flushes the output
  • streamWrapper::stream_lock — Advisory file locking
  • streamWrapper::stream_metadata — Change stream metadata
  • streamWrapper::stream_open — Opens file or URL
  • streamWrapper::stream_read — Read from stream
  • streamWrapper::stream_seek — Seeks to specific location in a stream
  • streamWrapper::stream_set_option — Change stream options
  • streamWrapper::stream_stat — Retrieve information about a file resource
  • streamWrapper::stream_tell — Retrieve the current position of a stream
  • streamWrapper::stream_truncate — Truncate stream
  • streamWrapper::stream_write — Write to stream
  • streamWrapper::unlink — Delete a file
  • streamWrapper::url_stat — Retrieve information about a file


Constructs a new stream wrapper

  • « streamWrapper
  • streamWrapper::__destruct »
  • PHP Manual
  • streamWrapper
  • Constructs a new stream wrapper

streamWrapper::__construct

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

streamWrapper::__construct — Constructs a new stream wrapper

Description

streamWrapper::__construct ( void )

Called when opening the stream wrapper, right before streamWrapper::stream_open().

Parameters

This function has no parameters.


Destructs an existing stream wrapper

  • « streamWrapper::__construct
  • streamWrapper::dir_closedir »
  • PHP Manual
  • streamWrapper
  • Destructs an existing stream wrapper

streamWrapper::__destruct

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

streamWrapper::__destruct — Destructs an existing stream wrapper

Description

streamWrapper::__destruct ( void )

Called when closing the stream wrapper, right before streamWrapper::stream_flush().

Parameters

This function has no parameters.


Close directory handle

  • « streamWrapper::__destruct
  • streamWrapper::dir_opendir »
  • PHP Manual
  • streamWrapper
  • Close directory handle

streamWrapper::dir_closedir

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

streamWrapper::dir_closedir — Close directory handle

Description

public streamWrapper::dir_closedir ( void ) : bool

This method is called in response to closedir().

Any resources which were locked, or allocated, during opening and use of the directory stream should be released.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • closedir() - Close directory handle
  • streamWrapper::dir_opendir() - Open directory handle


Open directory handle

  • « streamWrapper::dir_closedir
  • streamWrapper::dir_readdir »
  • PHP Manual
  • streamWrapper
  • Open directory handle

streamWrapper::dir_opendir

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

streamWrapper::dir_opendir — Open directory handle

Description

public streamWrapper::dir_opendir ( string $path , int $options ) : bool

This method is called in response to opendir().

Parameters

path

Specifies the URL that was passed to opendir().

Note:

The URL can be broken apart with parse_url().

options

Whether or not to enforce safe_mode (0x04).

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • opendir() - Open directory handle
  • streamWrapper::dir_closedir() - Close directory handle
  • parse_url() - Parse a URL and return its components


Read entry from directory handle

  • « streamWrapper::dir_opendir
  • streamWrapper::dir_rewinddir »
  • PHP Manual
  • streamWrapper
  • Read entry from directory handle

streamWrapper::dir_readdir

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

streamWrapper::dir_readdir — Read entry from directory handle

Description

public streamWrapper::dir_readdir ( void ) : string

This method is called in response to readdir().

Parameters

This function has no parameters.

Return Values

Should return string representing the next filename, or FALSE if there is no next file.

Note:

The return value will be casted to string.

Errors/Exceptions

Emits E_WARNING if call to this method fails (i.e. not implemented).

Examples

Example #1 Listing files from tar archives

<?php
class streamWrapper {
    protected $fp;

    public function dir_opendir($path, $options) {
        $url = parse_url($path);

        $path = $url["host"] . $url["path"];

        if (!is_readable($path)) {
            trigger_error("$path isn't readable for me", E_USER_NOTICE);
            return false;
        }
        if (!is_file($path)) {
            trigger_error("$path isn't a file", E_USER_NOTICE);
            return false;
        }

        $this->fp = fopen($path, "rb");
        return true;
    }

    public function dir_readdir() {
        // Extract the header for this entry
        $header      = fread($this->fp, 512);
        $data = unpack("a100filename/a8mode/a8uid/a8gid/a12size/a12mtime/a8checksum/a1filetype/a100link/a100linkedfile", $header);

        // Trim the filename and filesize
        $filename    = trim($data["filename"]);

        // No filename? We are the end of the archive
        if (!$filename) {
            return false;
        }

        $octal_bytes = trim($data["size"]);
        // Filesize is defined in octects
        $bytes       = octdec($octal_bytes);

        // tar rounds up filesizes up to multiple of 512 bytes (zero filled)
        $rest        = $bytes % 512;
        if ($rest > 0) {
            $bytes      += 512 - $rest;
        }

        // Seek over the file
        fseek($this->fp, $bytes, SEEK_CUR);

        return $filename;
    }

    public function dir_closedir() {
        return fclose($this->fp);
    }

    public function dir_rewinddir() {
        return fseek($this->fp, 0, SEEK_SET);
    }
}

stream_wrapper_register("tar", "streamWrapper");
$handle = opendir("tar://example.tar");
while (false !== ($file = readdir($handle))) {
    var_dump($file);
}

echo "Rewinding..\n";
rewind($handle);
var_dump(readdir($handle));

closedir($handle);
?>

The above example will output something similar to:

string(13) "construct.xml"
string(16) "dir-closedir.xml"
string(15) "dir-opendir.xml"
string(15) "dir-readdir.xml"
string(17) "dir-rewinddir.xml"
string(9) "mkdir.xml"
string(10) "rename.xml"
string(9) "rmdir.xml"
string(15) "stream-cast.xml"
string(16) "stream-close.xml"
string(14) "stream-eof.xml"
string(16) "stream-flush.xml"
string(15) "stream-lock.xml"
string(15) "stream-open.xml"
string(15) "stream-read.xml"
string(15) "stream-seek.xml"
string(21) "stream-set-option.xml"
string(15) "stream-stat.xml"
string(15) "stream-tell.xml"
string(16) "stream-write.xml"
string(10) "unlink.xml"
string(12) "url-stat.xml"
Rewinding..
string(13) "construct.xml"

See Also

  • readdir() - Read entry from directory handle


Rewind directory handle

  • « streamWrapper::dir_readdir
  • streamWrapper::mkdir »
  • PHP Manual
  • streamWrapper
  • Rewind directory handle

streamWrapper::dir_rewinddir

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

streamWrapper::dir_rewinddir — Rewind directory handle

Description

public streamWrapper::dir_rewinddir ( void ) : bool

This method is called in response to rewinddir().

Should reset the output generated by streamWrapper::dir_readdir(). i.e.: The next call to streamWrapper::dir_readdir() should return the first entry in the location returned by streamWrapper::dir_opendir().

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • rewinddir() - Rewind directory handle
  • streamWrapper::dir_readdir() - Read entry from directory handle


Create a directory

  • « streamWrapper::dir_rewinddir
  • streamWrapper::rename »
  • PHP Manual
  • streamWrapper
  • Create a directory

streamWrapper::mkdir

(PHP 5, PHP 7)

streamWrapper::mkdir — Create a directory

Description

public streamWrapper::mkdir ( string $path , int $mode , int $options ) : bool

This method is called in response to mkdir().

Note:

In order for the appropriate error message to be returned this method should not be defined if the wrapper does not support creating directories.

Parameters

path

Directory which should be created.

mode

The value passed to mkdir().

options

A bitwise mask of values, such as STREAM_MKDIR_RECURSIVE.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Emits E_WARNING if call to this method fails (i.e. not implemented).

Notes

Note:

The streamWrapper::$context property is updated if a valid context is passed to the caller function.

See Also

  • mkdir() - Makes directory
  • streamwrapper::rmdir() - Removes a directory


Renames a file or directory

  • « streamWrapper::mkdir
  • streamWrapper::rmdir »
  • PHP Manual
  • streamWrapper
  • Renames a file or directory

streamWrapper::rename

(PHP 5, PHP 7)

streamWrapper::rename — Renames a file or directory

Description

public streamWrapper::rename ( string $path_from , string $path_to ) : bool

This method is called in response to rename().

Should attempt to rename path_from to path_to

Note:

In order for the appropriate error message to be returned this method should not be defined if the wrapper does not support renaming files.

Parameters

path_from

The URL to the current file.

path_to

The URL which the path_from should be renamed to.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Emits E_WARNING if call to this method fails (i.e. not implemented).

Notes

Note:

The streamWrapper::$context property is updated if a valid context is passed to the caller function.

See Also

  • rename() - Renames a file or directory


Removes a directory

  • « streamWrapper::rename
  • streamWrapper::stream_cast »
  • PHP Manual
  • streamWrapper
  • Removes a directory

streamWrapper::rmdir

(PHP 5, PHP 7)

streamWrapper::rmdir — Removes a directory

Description

public streamWrapper::rmdir ( string $path , int $options ) : bool

This method is called in response to rmdir().

Note:

In order for the appropriate error message to be returned this method should not be defined if the wrapper does not support removing directories.

Parameters

path

The directory URL which should be removed.

options

A bitwise mask of values, such as STREAM_MKDIR_RECURSIVE.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Emits E_WARNING if call to this method fails (i.e. not implemented).

Notes

Note:

The streamWrapper::$context property is updated if a valid context is passed to the caller function.

See Also

  • rmdir() - Removes directory
  • streamwrapper::mkdir() - Create a directory
  • streamwrapper::unlink() - Delete a file


Retrieve the underlaying resource

  • « streamWrapper::rmdir
  • streamWrapper::stream_close »
  • PHP Manual
  • streamWrapper
  • Retrieve the underlaying resource

streamWrapper::stream_cast

(PHP 5 >= 5.3.0, PHP 7)

streamWrapper::stream_cast — Retrieve the underlaying resource

Description

public streamWrapper::stream_cast ( int $cast_as ) : resource

This method is called in response to stream_select().

Parameters

cast_as

Can be STREAM_CAST_FOR_SELECT when stream_select() is calling stream_cast() or STREAM_CAST_AS_STREAM when stream_cast() is called for other uses.

Return Values

Should return the underlying stream resource used by the wrapper, or FALSE.

See Also

  • stream_select() - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec


Close a resource

  • « streamWrapper::stream_cast
  • streamWrapper::stream_eof »
  • PHP Manual
  • streamWrapper
  • Close a resource

streamWrapper::stream_close

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

streamWrapper::stream_close — Close a resource

Description

public streamWrapper::stream_close ( void ) : void

This method is called in response to fclose().

All resources that were locked, or allocated, by the wrapper should be released.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • fclose() - Closes an open file pointer
  • streamWrapper::dir_closedir() - Close directory handle


Tests for end-of-file on a file pointer

  • « streamWrapper::stream_close
  • streamWrapper::stream_flush »
  • PHP Manual
  • streamWrapper
  • Tests for end-of-file on a file pointer

streamWrapper::stream_eof

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

streamWrapper::stream_eof — Tests for end-of-file on a file pointer

Description

public streamWrapper::stream_eof ( void ) : bool

This method is called in response to feof().

Parameters

This function has no parameters.

Return Values

Should return TRUE if the read/write position is at the end of the stream and if no more data is available to be read, or FALSE otherwise.

Notes

Warning

When reading the whole file (for example, with file_get_contents()), PHP will call streamWrapper::stream_read() followed by streamWrapper::stream_eof() in a loop but as long as streamWrapper::stream_read() returns a non-empty string, the return value of streamWrapper::stream_eof() is ignored.

See Also

  • feof() - Tests for end-of-file on a file pointer


Flushes the output

  • « streamWrapper::stream_eof
  • streamWrapper::stream_lock »
  • PHP Manual
  • streamWrapper
  • Flushes the output

streamWrapper::stream_flush

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

streamWrapper::stream_flush — Flushes the output

Description

public streamWrapper::stream_flush ( void ) : bool

This method is called in response to fflush() and when the stream is being closed while any unflushed data has been written to it before.

If you have cached data in your stream but not yet stored it into the underlying storage, you should do so now.

Parameters

This function has no parameters.

Return Values

Should return TRUE if the cached data was successfully stored (or if there was no data to store), or FALSE if the data could not be stored.

Notes

Note:

If not implemented, FALSE is assumed as the return value.

See Also

  • fflush() - Flushes the output to a file


Advisory file locking

  • « streamWrapper::stream_flush
  • streamWrapper::stream_metadata »
  • PHP Manual
  • streamWrapper
  • Advisory file locking

streamWrapper::stream_lock

(PHP 5, PHP 7)

streamWrapper::stream_lock — Advisory file locking

Description

public streamWrapper::stream_lock ( int $operation ) : bool

This method is called in response to flock(), when file_put_contents() (when flags contains LOCK_EX), stream_set_blocking() and when closing the stream (LOCK_UN).

Parameters

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).
  • LOCK_NB if you don't want flock() to block while locking. (not supported on Windows)

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Emits E_WARNING if call to this method fails (i.e. not implemented).

See Also

  • stream_set_blocking() - Set blocking/non-blocking mode on a stream
  • flock() - Portable advisory file locking


Change stream metadata

  • « streamWrapper::stream_lock
  • streamWrapper::stream_open »
  • PHP Manual
  • streamWrapper
  • Change stream metadata

streamWrapper::stream_metadata

(PHP 5 >= 5.4.0, PHP 7)

streamWrapper::stream_metadata — Change stream metadata

Description

public streamWrapper::stream_metadata ( string $path , int $option , mixed $value ) : bool

This method is called to set metadata on the stream. It is called when one of the following functions is called on a stream URL:

  • touch()
  • chmod()
  • chown()
  • chgrp()
Please note that some of these operations may not be available on your system.

Parameters

path

The file path or URL to set metadata. Note that in the case of a URL, it must be a :// delimited URL. Other URL forms are not supported.

option

One of:

  • STREAM_META_TOUCH (The method was called in response to touch())
  • STREAM_META_OWNER_NAME (The method was called in response to chown() with string parameter)
  • STREAM_META_OWNER (The method was called in response to chown())
  • STREAM_META_GROUP_NAME (The method was called in response to chgrp())
  • STREAM_META_GROUP (The method was called in response to chgrp())
  • STREAM_META_ACCESS (The method was called in response to chmod())

value

If option is

  • STREAM_META_TOUCH: Array consisting of two arguments of the touch() function.
  • STREAM_META_OWNER_NAME or STREAM_META_GROUP_NAME: The name of the owner user/group as string.
  • STREAM_META_OWNER or STREAM_META_GROUP: The value owner user/group argument as integer.
  • STREAM_META_ACCESS: The argument of the chmod() as integer.

Return Values

Returns TRUE on success or FALSE on failure. If option is not implemented, FALSE should be returned.

See Also

  • touch() - Sets access and modification time of file
  • chmod() - Changes file mode
  • chown() - Changes file owner
  • chgrp() - Changes file group


Opens file or URL

  • « streamWrapper::stream_metadata
  • streamWrapper::stream_read »
  • PHP Manual
  • streamWrapper
  • Opens file or URL

streamWrapper::stream_open

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

streamWrapper::stream_open — Opens file or URL

Description

public streamWrapper::stream_open ( string $path , string $mode , int $options , string &$opened_path ) : bool

This method is called immediately after the wrapper is initialized (f.e. by fopen() and file_get_contents()).

Parameters

path

Specifies the URL that was passed to the original function.

Note:

The URL can be broken apart with parse_url(). Note that only URLs delimited by :// are supported. : and :/ while technically valid URLs, are not.

mode

The mode used to open the file, as detailed for fopen().

Note:

Remember to check if the mode is valid for the path requested.

options

Holds additional flags set by the streams API. It can hold one or more of the following values OR'd together.

Flag | Description
STREAM_USE_PATH | If path is relative, search for the resource using the include_path.
STREAM_REPORT_ERRORS | If this flag is set, you are responsible for raising errors using trigger_error() during opening of the stream. If this flag is not set, you should not raise any errors.

opened_path

If the path is opened successfully, and STREAM_USE_PATH is set in options, opened_path should be set to the full path of the file/resource that was actually opened.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Emits E_WARNING if call to this method fails (i.e. not implemented).

Notes

Note:

The streamWrapper::$context property is updated if a valid context is passed to the caller function.

See Also

  • fopen() - Opens file or URL
  • parse_url() - Parse a URL and return its components


Read from stream

  • « streamWrapper::stream_open
  • streamWrapper::stream_seek »
  • PHP Manual
  • streamWrapper
  • Read from stream

streamWrapper::stream_read

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

streamWrapper::stream_read — Read from stream

Description

public streamWrapper::stream_read ( int $count ) : string

This method is called in response to fread() and fgets().

Note:

Remember to update the read/write position of the stream (by the number of bytes that were successfully read).

Parameters

count

How many bytes of data from the current position should be returned.

Return Values

If there are less than count bytes available, return as many as are available. If no more data is available, return either FALSE or an empty string.

Errors/Exceptions

Emits E_WARNING if call to this method fails (i.e. not implemented).

Note:

If the return value is longer then count an E_WARNING error will be emitted, and excess data will be lost.

Notes

Note:

streamWrapper::stream_eof() is called directly after calling streamWrapper::stream_read() to check if EOF has been reached. If not implemented, EOF is assumed.

Warning

When reading the whole file (for example, with file_get_contents()), PHP will call streamWrapper::stream_read() followed by streamWrapper::stream_eof() in a loop but as long as streamWrapper::stream_read() returns a non-empty string, the return value of streamWrapper::stream_eof() is ignored.

See Also

  • fread() - Binary-safe file read
  • fgets() - Gets line from file pointer


Seeks to specific location in a stream

  • « streamWrapper::stream_read
  • streamWrapper::stream_set_option »
  • PHP Manual
  • streamWrapper
  • Seeks to specific location in a stream

streamWrapper::stream_seek

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

streamWrapper::stream_seek — Seeks to specific location in a stream

Description

public streamWrapper::stream_seek ( int $offset , int $whence = SEEK_SET ) : bool

This method is called in response to fseek().

The read/write position of the stream should be updated according to the offset and whence.

Parameters

offset

The stream offset to seek to.

whence

Possible values:

  • SEEK_SET - Set position equal to offset bytes.
  • SEEK_CUR - Set position to current location plus offset.
  • SEEK_END - Set position to end-of-file plus offset.

Return Values

Return TRUE if the position was updated, FALSE otherwise.

Notes

Note:

If not implemented, FALSE is assumed as the return value.

Note:

Upon success,
streamWrapper::stream_tell() is called directly after
calling streamWrapper::stream_seek(). If
streamWrapper::stream_tell() fails, the return
value to the caller function will be set to FALSE

Note:

Not all seeks operations on the stream will result in this function being called. PHP streams have read buffering enabled by default (see also stream_set_read_buffer()) and seeking may be done by merely moving the buffer pointer.

See Also

  • fseek() - Seeks on a file pointer


Change stream options

  • « streamWrapper::stream_seek
  • streamWrapper::stream_stat »
  • PHP Manual
  • streamWrapper
  • Change stream options

streamWrapper::stream_set_option

(PHP 5 >= 5.3.0, PHP 7)

streamWrapper::stream_set_option — Change stream options

Description

public streamWrapper::stream_set_option ( int $option , int $arg1 , int $arg2 ) : bool

This method is called to set options on the stream.

Parameters

option

One of:

  • STREAM_OPTION_BLOCKING (The method was called in response to stream_set_blocking())
  • STREAM_OPTION_READ_TIMEOUT (The method was called in response to stream_set_timeout())
  • STREAM_OPTION_WRITE_BUFFER (The method was called in response to stream_set_write_buffer())

arg1

If option is

  • STREAM_OPTION_BLOCKING: requested blocking mode (1 meaning block 0 not blocking).
  • STREAM_OPTION_READ_TIMEOUT: the timeout in seconds.
  • STREAM_OPTION_WRITE_BUFFER: buffer mode (STREAM_BUFFER_NONE or STREAM_BUFFER_FULL).

arg2

If option is

  • STREAM_OPTION_BLOCKING: This option is not set.
  • STREAM_OPTION_READ_TIMEOUT: the timeout in microseconds.
  • STREAM_OPTION_WRITE_BUFFER: the requested buffer size.

Return Values

Returns TRUE on success or FALSE on failure. If option is not implemented, FALSE should be returned.

See Also

  • stream_set_blocking() - Set blocking/non-blocking mode on a stream
  • stream_set_timeout() - Set timeout period on a stream
  • stream_set_write_buffer() - Sets write file buffering on the given stream


Retrieve information about a file resource

  • « streamWrapper::stream_set_option
  • streamWrapper::stream_tell »
  • PHP Manual
  • streamWrapper
  • Retrieve information about a file resource

streamWrapper::stream_stat

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

streamWrapper::stream_stat — Retrieve information about a file resource

Description

public streamWrapper::stream_stat ( void ) : array

This method is called in response to fstat().

Parameters

This function has no parameters.

Return Values

See stat().

Errors/Exceptions

Emits E_WARNING if call to this method fails (i.e. not implemented).

See Also

  • stat() - Gives information about a file
  • streamwrapper::url_stat() - Retrieve information about a file


Retrieve the current position of a stream

  • « streamWrapper::stream_stat
  • streamWrapper::stream_truncate »
  • PHP Manual
  • streamWrapper
  • Retrieve the current position of a stream

streamWrapper::stream_tell

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

streamWrapper::stream_tell — Retrieve the current position of a stream

Description

public streamWrapper::stream_tell ( void ) : int

This method is called in response to fseek() to determine the current position.

Parameters

This function has no parameters.

Return Values

Should return the current position of the stream.

See Also

  • streamWrapper::stream_tell()


Truncate stream

  • « streamWrapper::stream_tell
  • streamWrapper::stream_write »
  • PHP Manual
  • streamWrapper
  • Truncate stream

streamWrapper::stream_truncate

(PHP 5 >= 5.4.0, PHP 7)

streamWrapper::stream_truncate — Truncate stream

Description

public streamWrapper::stream_truncate ( int $new_size ) : bool

Will respond to truncation, e.g., through ftruncate().

Parameters

new_size

The new size.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ftruncate() - Truncates a file to a given length


Write to stream

  • « streamWrapper::stream_truncate
  • streamWrapper::unlink »
  • PHP Manual
  • streamWrapper
  • Write to stream

streamWrapper::stream_write

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

streamWrapper::stream_write — Write to stream

Description

public streamWrapper::stream_write ( string $data ) : int

This method is called in response to fwrite().

Note:

Remember to update the current position of the stream by number of bytes that were successfully written.

Parameters

data

Should be stored into the underlying stream.

Note:

If there is not enough room in the underlying stream, store as much as possible.

Return Values

Should return the number of bytes that were successfully stored, or 0 if none could be stored.

Errors/Exceptions

Emits E_WARNING if call to this method fails (i.e. not implemented).

Note:

If the return value is greater the length of data, E_WARNING will be emitted and the return value will truncated to its length.

See Also

  • fwrite() - Binary-safe file write


Delete a file

  • « streamWrapper::stream_write
  • streamWrapper::url_stat »
  • PHP Manual
  • streamWrapper
  • Delete a file

streamWrapper::unlink

(PHP 5, PHP 7)

streamWrapper::unlink — Delete a file

Description

public streamWrapper::unlink ( string $path ) : bool

This method is called in response to unlink().

Note:

In order for the appropriate error message to be returned this method should not be defined if the wrapper does not support removing files.

Parameters

path

The file URL which should be deleted.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Emits E_WARNING if call to this method fails (i.e. not implemented).

Notes

Note:

The streamWrapper::$context property is updated if a valid context is passed to the caller function.

See Also

  • unlink() - Deletes a file
  • streamWrapper::rmdir() - Removes a directory


Retrieve information about a file

  • « streamWrapper::unlink
  • Stream Functions »
  • PHP Manual
  • streamWrapper
  • Retrieve information about a file

streamWrapper::url_stat

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

streamWrapper::url_stat — Retrieve information about a file

Description

public streamWrapper::url_stat ( string $path , int $flags ) : array

This method is called in response to all stat() related functions, such as:

  • chmod() (only when safe_mode is enabled)
  • copy()
  • fileperms()
  • fileinode()
  • filesize()
  • fileowner()
  • filegroup()
  • fileatime()
  • filemtime()
  • filectime()
  • filetype()
  • is_writable()
  • is_readable()
  • is_executable()
  • is_file()
  • is_dir()
  • is_link()
  • file_exists()
  • lstat()
  • stat()
  • SplFileInfo::getPerms()
  • SplFileInfo::getInode()
  • SplFileInfo::getSize()
  • SplFileInfo::getOwner()
  • SplFileInfo::getGroup()
  • SplFileInfo::getATime()
  • SplFileInfo::getMTime()
  • SplFileInfo::getCTime()
  • SplFileInfo::getType()
  • SplFileInfo::isWritable()
  • SplFileInfo::isReadable()
  • SplFileInfo::isExecutable()
  • SplFileInfo::isFile()
  • SplFileInfo::isDir()
  • SplFileInfo::isLink()
  • RecursiveDirectoryIterator::hasChildren()

Parameters

path

The file path or URL to stat. Note that in the case of a URL, it must be a :// delimited URL. Other URL forms are not supported.

flags

Holds additional flags set by the streams API. It can hold one or more of the following values OR'd together.

Flag | Description
STREAM_URL_STAT_LINK | For resources with the ability to link to other resource (such as an HTTP Location: forward, or a filesystem symlink). This flag specified that only information about the link itself should be returned, not the resource pointed to by the link. This flag is set in response to calls to lstat(), is_link(), or filetype().
STREAM_URL_STAT_QUIET | If this flag is set, your wrapper should not raise any errors. If this flag is not set, you are responsible for reporting errors using the trigger_error() function during stating of the path.

Return Values

Should return as many elements as stat() does. Unknown or unavailable values should be set to a rational value (usually 0). Pay special attention to mode as documented under stat().

Errors/Exceptions

Emits E_WARNING if call to this method fails (i.e. not implemented).

Notes

Note:

The streamWrapper::$context property is updated if a valid context is passed to the caller function.

See Also

  • stat() - Gives information about a file
  • streamwrapper::stream_stat() - Retrieve information about a file resource


Stream Functions

Table of Contents

  • set_socket_blocking — Alias of stream_set_blocking
  • stream_bucket_append — Append bucket to brigade
  • stream_bucket_make_writeable — Return a bucket object from the brigade for operating on
  • stream_bucket_new — Create a new bucket for use on the current stream
  • stream_bucket_prepend — Prepend bucket to brigade
  • stream_context_create — Creates a stream context
  • stream_context_get_default — Retrieve the default stream context
  • stream_context_get_options — Retrieve options for a stream/wrapper/context
  • stream_context_get_params — Retrieves parameters from a context
  • stream_context_set_default — Set the default stream context
  • stream_context_set_option — Sets an option for a stream/wrapper/context
  • stream_context_set_params — Set parameters for a stream/wrapper/context
  • stream_copy_to_stream — Copies data from one stream to another
  • stream_filter_append — Attach a filter to a stream
  • stream_filter_prepend — Attach a filter to a stream
  • stream_filter_register — Register a user defined stream filter
  • stream_filter_remove — Remove a filter from a stream
  • stream_get_contents — Reads remainder of a stream into a string
  • stream_get_filters — Retrieve list of registered filters
  • stream_get_line — Gets line from stream resource up to a given delimiter
  • stream_get_meta_data — Retrieves header/meta data from streams/file pointers
  • stream_get_transports — Retrieve list of registered socket transports
  • stream_get_wrappers — Retrieve list of registered streams
  • stream_is_local — Checks if a stream is a local stream
  • stream_isatty — Check if a stream is a TTY
  • stream_notification_callback — A callback function for the notification context parameter
  • stream_register_wrapper — Alias of stream_wrapper_register
  • stream_resolve_include_path — Resolve filename against the include path
  • stream_select — Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec
  • stream_set_blocking — Set blocking/non-blocking mode on a stream
  • stream_set_chunk_size — Set the stream chunk size
  • stream_set_read_buffer — Set read file buffering on the given stream
  • stream_set_timeout — Set timeout period on a stream
  • stream_set_write_buffer — Sets write file buffering on the given stream
  • stream_socket_accept — Accept a connection on a socket created by stream_socket_server
  • stream_socket_client — Open Internet or Unix domain socket connection
  • stream_socket_enable_crypto — Turns encryption on/off on an already connected socket
  • stream_socket_get_name — Retrieve the name of the local or remote sockets
  • stream_socket_pair — Creates a pair of connected, indistinguishable socket streams
  • stream_socket_recvfrom — Receives data from a socket, connected or not
  • stream_socket_sendto — Sends a message to a socket, whether it is connected or not
  • stream_socket_server — Create an Internet or Unix domain server socket
  • stream_socket_shutdown — Shutdown a full-duplex connection
  • stream_supports_lock — Tells whether the stream supports locking
  • stream_wrapper_register — Register a URL wrapper implemented as a PHP class
  • stream_wrapper_restore — Restores a previously unregistered built-in wrapper
  • stream_wrapper_unregister — Unregister a URL wrapper


Alias of stream_set_blocking

  • « Stream Functions
  • stream_bucket_append »
  • PHP Manual
  • Stream Functions
  • Alias of stream_set_blocking

set_socket_blocking

(PHP 4, PHP 5)

set_socket_blocking — Alias of stream_set_blocking()

Warning

This alias was DEPRECATED in PHP 5.3.0, and REMOVED as of PHP 7.0.0.

Description

This function is an alias of: stream_set_blocking()


Append bucket to brigade

  • « set_socket_blocking
  • stream_bucket_make_writeable »
  • PHP Manual
  • Stream Functions
  • Append bucket to brigade

stream_bucket_append

(PHP 5, PHP 7)

stream_bucket_append — Append bucket to brigade

Description

stream_bucket_append ( resource $brigade , object $bucket ) : void
Warning

This function is currently not documented; only its argument list is available.


Return a bucket object from the brigade for operating on

  • « stream_bucket_append
  • stream_bucket_new »
  • PHP Manual
  • Stream Functions
  • Return a bucket object from the brigade for operating on

stream_bucket_make_writeable

(PHP 5, PHP 7)

stream_bucket_make_writeable — Return a bucket object from the brigade for operating on

Description

stream_bucket_make_writeable ( resource $brigade ) : object
Warning

This function is currently not documented; only its argument list is available.


Create a new bucket for use on the current stream

  • « stream_bucket_make_writeable
  • stream_bucket_prepend »
  • PHP Manual
  • Stream Functions
  • Create a new bucket for use on the current stream

stream_bucket_new

(PHP 5, PHP 7)

stream_bucket_new — Create a new bucket for use on the current stream

Description

stream_bucket_new ( resource $stream , string $buffer ) : object
Warning

This function is currently not documented; only its argument list is available.


Prepend bucket to brigade

  • « stream_bucket_new
  • stream_context_create »
  • PHP Manual
  • Stream Functions
  • Prepend bucket to brigade

stream_bucket_prepend

(PHP 5, PHP 7)

stream_bucket_prepend — Prepend bucket to brigade

Description

stream_bucket_prepend ( resource $brigade , object $bucket ) : void

This function can be called to prepend a bucket to a bucket brigade. It is typically called from php_user_filter::filter().

Parameters

brigade

brigade is a resource pointing to a bucket brigade which contains one or more bucket objects.

bucket

A bucket object.

Return Values

No value is returned.

Examples

Example #1 stream_bucket_prepend() examples

<?php

class foo extends php_user_filter {
  protected $calls = 0;
  public function filter($in, $out, &$consumed, $closing) {
    while ($bucket = stream_bucket_make_writeable($in)) {
      $consumed += $bucket->datalen;
      if ($this->calls++ == 2) {
        // This bucket will appear again before any other bucket.
        stream_bucket_prepend($in, $bucket);
      }
    }
    return PSFS_FEED_ME;
  }
}
stream_filter_register('test', 'foo');
print  file_get_contents('php://filter/read=test/resource=foo');
?>


Creates a stream context

  • « stream_bucket_prepend
  • stream_context_get_default »
  • PHP Manual
  • Stream Functions
  • Creates a stream context

stream_context_create

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

stream_context_create — Creates a stream context

Description

stream_context_create ([ array $options [, array $params ]] ) : resource

Creates and returns a stream context with any options supplied in options preset.

Parameters

options

Must be an associative array of associative arrays in the format $arr['wrapper']['option'] = $value. Refer to context options for a list of available wrappers and options.

Default to an empty array.

params

Must be an associative array in the format $arr['parameter'] = $value. Refer to context parameters for a listing of standard stream parameters.

Return Values

A stream context resource.

Changelog

Version | Description
5.3.0 | Added the optional params argument.

Examples

Example #1 Using stream_context_create()

<?php
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n"
  )
);

$context = stream_context_create($opts);

/* Sends an http request to www.example.com
   with additional headers shown above */
$fp = fopen('http://www.example.com', 'r', false, $context);
fpassthru($fp);
fclose($fp);
?>

See Also

  • stream_context_set_option() - Sets an option for a stream/wrapper/context
  • Listing of supported wrappers (Supported Protocols and Wrappers)
  • Context options (Context options and parameters)


Retrieve the default stream context

  • « stream_context_create
  • stream_context_get_options »
  • PHP Manual
  • Stream Functions
  • Retrieve the default stream context

stream_context_get_default

(PHP 5 >= 5.1.0, PHP 7)

stream_context_get_default — Retrieve the default stream context

Description

stream_context_get_default ([ array $options ] ) : resource

Returns the default stream context which is used whenever file operations (fopen(), file_get_contents(), etc...) are called without a context parameter. Options for the default context can optionally be specified with this function using the same syntax as stream_context_create().

Parameters

options
options must be an associative array of associative arrays in the format $arr['wrapper']['option'] = $value.

Note:

As of PHP 5.3.0, the stream_context_set_default() function can be used to set the default context.

Return Values

A stream context resource.

Examples

Example #1 Using stream_context_get_default()

<?php
$default_opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar",
    'proxy'=>"tcp://10.54.1.39:8000"
  )
);

$alternate_opts = array(
  'http'=>array(
    'method'=>"POST",
    'header'=>"Content-type: application/x-www-form-urlencoded\r\n" .
              "Content-length: " . strlen("baz=bomb"),
    'content'=>"baz=bomb"
  )
);

$default = stream_context_get_default($default_opts);
$alternate = stream_context_create($alternate_opts);

/* Sends a regular GET request to proxy server at 10.54.1.39
 * For www.example.com using context options specified in $default_opts
 */
readfile('http://www.example.com');

/* Sends a POST request directly to www.example.com
 * Using context options specified in $alternate_opts
 */
readfile('http://www.example.com', false, $alternate);

?>

See Also

  • stream_context_create() - Creates a stream context
  • Listing of supported wrappers with context options (Supported Protocols and Wrappers).


Retrieve options for a stream/wrapper/context

  • « stream_context_get_default
  • stream_context_get_params »
  • PHP Manual
  • Stream Functions
  • Retrieve options for a stream/wrapper/context

stream_context_get_options

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

stream_context_get_options — Retrieve options for a stream/wrapper/context

Description

stream_context_get_options ( resource $stream_or_context ) : array

Returns an array of options on the specified stream or context.

Parameters

stream_or_context

The stream or context to get options from

Return Values

Returns an associative array with the options.

Examples

Example #1 stream_context_get_options() example

<?php
$params = array("method" => "POST");

stream_context_set_default(array("http" => $params));

var_dump(stream_context_get_options(stream_context_get_default()));

?>

The above example will output something similar to:

array(1) {
  ["http"]=>
  array(1) {
    ["method"]=>
    string(4) "POST"
  }
}


Retrieves parameters from a context

  • « stream_context_get_options
  • stream_context_set_default »
  • PHP Manual
  • Stream Functions
  • Retrieves parameters from a context

stream_context_get_params

(PHP 5 >= 5.3.0, PHP 7)

stream_context_get_params — Retrieves parameters from a context

Description

stream_context_get_params ( resource $stream_or_context ) : array

Retrieves parameter and options information from the stream or context.

Parameters

stream_or_context

A stream resource or a context resource

Return Values

Returns an associate array containing all context options and parameters.

Examples

Example #1 stream_context_get_params() example

Basic usage example

<?php
$ctx = stream_context_create();
$params = array("notification" => "stream_notification_callback");
stream_context_set_params($ctx, $params);

var_dump(stream_context_get_params($ctx));
?>

The above example will output something similar to:

array(2) {
  ["notification"]=>
  string(28) "stream_notification_callback"
  ["options"]=>
  array(0) {
  }
}

See Also

  • stream_context_set_option() - Sets an option for a stream/wrapper/context
  • stream_context_set_params() - Set parameters for a stream/wrapper/context


Set the default stream context

  • « stream_context_get_params
  • stream_context_set_option »
  • PHP Manual
  • Stream Functions
  • Set the default stream context

stream_context_set_default

(PHP 5 >= 5.3.0, PHP 7)

stream_context_set_default — Set the default stream context

Description

stream_context_set_default ( array $options ) : resource

Set the default stream context which will be used whenever file operations (fopen(), file_get_contents(), etc...) are called without a context parameter. Uses the same syntax as stream_context_create().

Parameters

options

The options to set for the default context.

Note:

options must be an associative array of associative arrays in the format $arr['wrapper']['option'] = $value.

Return Values

Returns the default stream context.

Examples

Example #1 stream_context_set_default() example

<?php
$default_opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar",
    'proxy'=>"tcp://10.54.1.39:8000"
  )
);

$default = stream_context_set_default($default_opts);

/* Sends a regular GET request to proxy server at 10.54.1.39
 * For www.example.com using context options specified in $default_opts
 */
readfile('http://www.example.com');
?>

See Also

  • stream_context_create() - Creates a stream context
  • stream_context_get_default() - Retrieve the default stream context
  • Listing of supported wrappers with context options (Supported Protocols and Wrappers).


Sets an option for a stream/wrapper/context

  • « stream_context_set_default
  • stream_context_set_params »
  • PHP Manual
  • Stream Functions
  • Sets an option for a stream/wrapper/context

stream_context_set_option

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

stream_context_set_option — Sets an option for a stream/wrapper/context

Description

stream_context_set_option ( resource $stream_or_context , string $wrapper , string $option , mixed $value ) : bool
stream_context_set_option ( resource $stream_or_context , array $options ) : bool

Sets an option on the specified context. value is set to option for wrapper

Parameters

stream_or_context

The stream or context resource to apply the options to.

options

The options to set for stream_or_context.

Note:

options must be an associative array of associative arrays in the format $arr['wrapper']['option'] = $value.

Refer to context options and parameters for a listing of stream options.

Return Values

Returns TRUE on success or FALSE on failure.


Set parameters for a stream/wrapper/context

  • « stream_context_set_option
  • stream_copy_to_stream »
  • PHP Manual
  • Stream Functions
  • Set parameters for a stream/wrapper/context

stream_context_set_params

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

stream_context_set_params — Set parameters for a stream/wrapper/context

Description

stream_context_set_params ( resource $stream_or_context , array $params ) : bool

Sets parameters on the specified context.

Parameters

stream_or_context

The stream or context to apply the parameters too.

params

An array of parameters to set.

Note:

params should be an associative array of the structure: $params['paramname'] = "paramvalue";.

Supported parameters

Parameters | Purpose
notification | Name of user-defined callback function to be called whenever a stream triggers a notification. Only supported for http:// and ftp:// stream wrappers.
options | Array of options as in context options and parameters.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • stream_notification_callback() - A callback function for the notification context parameter


Copies data from one stream to another

  • « stream_context_set_params
  • stream_filter_append »
  • PHP Manual
  • Stream Functions
  • Copies data from one stream to another

stream_copy_to_stream

(PHP 5, PHP 7)

stream_copy_to_stream — Copies data from one stream to another

Description

stream_copy_to_stream ( resource $source , resource $dest [, int $maxlength = -1 [, int $offset = 0 ]] ) : int

Makes a copy of up to maxlength bytes of data from the current position (or from the offset position, if specified) in source to dest. If maxlength is not specified, all remaining content in source will be copied.

Parameters

source

The source stream

dest

The destination stream

maxlength

Maximum bytes to copy

offset

The offset where to start to copy data

Return Values

Returns the total count of bytes copied, or FALSE on failure.

Changelog

Version | Description
5.1.0 | Added the offset parameter

Examples

Example #1 A stream_copy_to_stream() example

<?php
$src = fopen('http://www.example.com', 'r');
$dest1 = fopen('first1k.txt', 'w');
$dest2 = fopen('remainder.txt', 'w');

echo stream_copy_to_stream($src, $dest1, 1024) . " bytes copied to first1k.txt\n";
echo stream_copy_to_stream($src, $dest2) . " bytes copied to remainder.txt\n";

?>

See Also

  • copy() - Copies file


Attach a filter to a stream

  • « stream_copy_to_stream
  • stream_filter_prepend »
  • PHP Manual
  • Stream Functions
  • Attach a filter to a stream

stream_filter_append

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

stream_filter_append — Attach a filter to a stream

Description

stream_filter_append ( resource $stream , string $filtername [, int $read_write [, mixed $params ]] ) : resource

Adds filtername to the list of filters attached to stream.

Parameters

stream

The target stream.

filtername

The filter name.

read_write

By default, stream_filter_append() will attach the filter to the read filter chain if the file was opened for reading (i.e. File Mode: r, and/or +). The filter will also be attached to the write filter chain if the file was opened for writing (i.e. File Mode: w, a, and/or +). STREAM_FILTER_READ, STREAM_FILTER_WRITE, and/or STREAM_FILTER_ALL can also be passed to the read_write parameter to override this behavior.

params

This filter will be added with the specified params to the end of the list and will therefore be called last during stream operations. To add a filter to the beginning of the list, use stream_filter_prepend().

Return Values

Returns a resource on success or FALSE on failure. The resource can be used to refer to this filter instance during a call to stream_filter_remove().

FALSE is returned if stream is not a resource or if filtername cannot be located.

Changelog

Version | Description
5.1.0 | Prior to PHP 5.1.0, this function returns TRUE on success or FALSE on failure.

Examples

Example #1 Controlling where filters are applied

<?php
/* Open a test file for reading and writing */
$fp = fopen('test.txt', 'w+');

/* Apply the ROT13 filter to the
 * write filter chain, but not the
 * read filter chain */
stream_filter_append($fp, "string.rot13", STREAM_FILTER_WRITE);

/* Write a simple string to the file
 * it will be ROT13 transformed on the
 * way out */
fwrite($fp, "This is a test\n");

/* Back up to the beginning of the file */
rewind($fp);

/* Read the contents of the file back out.
 * Had the filter been applied to the
 * read filter chain as well, we would see
 * the text ROT13ed back to its original state */
fpassthru($fp);

fclose($fp);

/* Expected Output
   ---------------

Guvf vf n grfg

 */
?>

Notes

Note: When using custom (user) filters
stream_filter_register() must be called first in order to register the desired user filter to filtername.

Note: Stream data is read from resources (both local and remote) in chunks, with any unconsumed data kept in internal buffers. When a new filter is appended to a stream, data in the internal buffers is processed through the new filter at that time. This differs from the behavior of stream_filter_prepend().

Note: When a filter is added for read and write, two instances of the filter are created. stream_filter_append() must be called twice with STREAM_FILTER_READ and STREAM_FILTER_WRITE to get both filter resources.

See Also

  • stream_filter_register() - Register a user defined stream filter
  • stream_filter_prepend() - Attach a filter to a stream
  • stream_get_filters() - Retrieve list of registered filters


Attach a filter to a stream

  • « stream_filter_append
  • stream_filter_register »
  • PHP Manual
  • Stream Functions
  • Attach a filter to a stream

stream_filter_prepend

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

stream_filter_prepend — Attach a filter to a stream

Description

stream_filter_prepend ( resource $stream , string $filtername [, int $read_write [, mixed $params ]] ) : resource

Adds filtername to the list of filters attached to stream.

Parameters

stream

The target stream.

filtername

The filter name.

read_write

By default, stream_filter_prepend() will attach the filter to the read filter chain if the file was opened for reading (i.e. File Mode: r, and/or +). The filter will also be attached to the write filter chain if the file was opened for writing (i.e. File Mode: w, a, and/or +). STREAM_FILTER_READ, STREAM_FILTER_WRITE, and/or STREAM_FILTER_ALL can also be passed to the read_write parameter to override this behavior. See stream_filter_append() for an example of using this parameter.

params

This filter will be added with the specified params to the beginning of the list and will therefore be called first during stream operations. To add a filter to the end of the list, use stream_filter_append().

Return Values

Returns a resource on success or FALSE on failure. The resource can be used to refer to this filter instance during a call to stream_filter_remove().

FALSE is returned if stream is not a resource or if filtername cannot be located.

Changelog

Version | Description
5.1.0 | Prior to PHP 5.1.0, this function returns TRUE on success or FALSE on failure.

Notes

Note: When using custom (user) filters
stream_filter_register() must be called first in order to register the desired user filter to filtername.

Note: Stream data is read from resources (both local and remote) in chunks, with any unconsumed data kept in internal buffers. When a new filter is prepended to a stream, data in the internal buffers, which has already been processed through other filters will not be reprocessed through the new filter at that time. This differs from the behavior of stream_filter_append().

Note: When a filter is added for read and write, two instances of the filter are created. stream_filter_prepend() must be called twice with STREAM_FILTER_READ and STREAM_FILTER_WRITE to get both filter resources.

See Also

  • stream_filter_register() - Register a user defined stream filter
  • stream_filter_append() - Attach a filter to a stream


Register a user defined stream filter

  • « stream_filter_prepend
  • stream_filter_remove »
  • PHP Manual
  • Stream Functions
  • Register a user defined stream filter

stream_filter_register

(PHP 5, PHP 7)

stream_filter_register — Register a user defined stream filter

Description

stream_filter_register ( string $filtername , string $classname ) : bool

stream_filter_register() allows you to implement your own filter on any registered stream used with all the other filesystem functions (such as fopen(), fread() etc.).

Parameters

filtername

The filter name to be registered.

classname

To implement a filter, you need to define a class as an extension of php_user_filter with a number of member functions. When performing read/write operations on the stream to which your filter is attached, PHP will pass the data through your filter (and any other filters attached to that stream) so that the data may be modified as desired. You must implement the methods exactly as described in php_user_filter - doing otherwise will lead to undefined behaviour.

Return Values

Returns TRUE on success or FALSE on failure.

stream_filter_register() will return FALSE if the filtername is already defined.

Examples

Example #1 Filter for capitalizing characters on foo-bar.txt stream

The example below implements a filter named strtoupper on the foo-bar.txt stream which will capitalize all letter characters written to/read from that stream.

<?php

/* Define our filter class */
class strtoupper_filter extends php_user_filter {
  function filter($in, $out, &$consumed, $closing)
  {
    while ($bucket = stream_bucket_make_writeable($in)) {
      $bucket->data = strtoupper($bucket->data);
      $consumed += $bucket->datalen;
      stream_bucket_append($out, $bucket);
    }
    return PSFS_PASS_ON;
  }
}

/* Register our filter with PHP */
stream_filter_register("strtoupper", "strtoupper_filter")
    or die("Failed to register filter");

$fp = fopen("foo-bar.txt", "w");

/* Attach the registered filter to the stream just opened */
stream_filter_append($fp, "strtoupper");

fwrite($fp, "Line1\n");
fwrite($fp, "Word - 2\n");
fwrite($fp, "Easy As 123\n");

fclose($fp);

/* Read the contents back out
 */
readfile("foo-bar.txt");

?>

The above example will output:

LINE1
WORD - 2
EASY AS 123

Example #2 Registering a generic filter class to match multiple filter names.

<?php

/* Define our filter class */
class string_filter extends php_user_filter {
  var $mode;

  function filter($in, $out, &$consumed, $closing)
  {
    while ($bucket = stream_bucket_make_writeable($in)) {
      if ($this->mode == 1) {
        $bucket->data = strtoupper($bucket->data);
      } elseif ($this->mode == 0) {
        $bucket->data = strtolower($bucket->data);
      }

      $consumed += $bucket->datalen;
      stream_bucket_append($out, $bucket);
    }
    return PSFS_PASS_ON;
  }

  function onCreate()
  {
    if ($this->filtername == 'str.toupper') {
      $this->mode = 1;
    } elseif ($this->filtername == 'str.tolower') {
      $this->mode = 0;
    } else {
      /* Some other str.* filter was asked for,
         report failure so that PHP will keep looking */
      return false;
    }

    return true;
  }
}

/* Register our filter with PHP */
stream_filter_register("str.*", "string_filter")
    or die("Failed to register filter");

$fp = fopen("foo-bar.txt", "w");

/* Attach the registered filter to the stream just opened
   We could alternately bind to str.tolower here */
stream_filter_append($fp, "str.toupper");

fwrite($fp, "Line1\n");
fwrite($fp, "Word - 2\n");
fwrite($fp, "Easy As 123\n");

fclose($fp);

/* Read the contents back out
 */
readfile("foo-bar.txt");
?>

The above example will output:

LINE1
WORD - 2
EASY AS 123

See Also

  • stream_wrapper_register() - Register a URL wrapper implemented as a PHP class
  • stream_filter_append() - Attach a filter to a stream
  • stream_filter_prepend() - Attach a filter to a stream


Remove a filter from a stream

  • « stream_filter_register
  • stream_get_contents »
  • PHP Manual
  • Stream Functions
  • Remove a filter from a stream

stream_filter_remove

(PHP 5 >= 5.1.0, PHP 7)

stream_filter_remove — Remove a filter from a stream

Description

stream_filter_remove ( resource $stream_filter ) : bool

Removes a stream filter previously added to a stream with stream_filter_prepend() or stream_filter_append(). Any data remaining in the filter's internal buffer will be flushed through to the next filter before removing it.

Parameters

stream_filter

The stream filter to be removed.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Dynamically refiltering a stream

<?php
/* Open a test file for reading and writing */
$fp = fopen("test.txt", "rw");

$rot13_filter = stream_filter_append($fp, "string.rot13", STREAM_FILTER_WRITE);
fwrite($fp, "This is ");
stream_filter_remove($rot13_filter);
fwrite($fp, "a test\n");

rewind($fp);
fpassthru($fp);
fclose($fp);

?>

The above example will output:

Guvf vf a test

See Also

  • stream_filter_register() - Register a user defined stream filter
  • stream_filter_append() - Attach a filter to a stream
  • stream_filter_prepend() - Attach a filter to a stream


Reads remainder of a stream into a string

  • « stream_filter_remove
  • stream_get_filters »
  • PHP Manual
  • Stream Functions
  • Reads remainder of a stream into a string

stream_get_contents

(PHP 5, PHP 7)

stream_get_contents — Reads remainder of a stream into a string

Description

stream_get_contents ( resource $handle [, int $maxlength = -1 [, int $offset = -1 ]] ) : string

Identical to file_get_contents(), except that stream_get_contents() operates on an already open stream resource and returns the remaining contents in a string, up to maxlength bytes and starting at the specified offset.

Parameters

handle (resource)

A stream resource (e.g. returned from fopen())

maxlength (integer)

The maximum bytes to read. Defaults to -1 (read all the remaining buffer).

offset (integer)

Seek to the specified offset before reading. If this number is negative, no seeking will occur and reading will start from the current position.

Return Values

Returns a string or FALSE on failure.

Changelog

Version | Description
5.1.0 | The offset was added.

Examples

Example #1 stream_get_contents() example

<?php

if ($stream = fopen('http://www.example.com', 'r')) {
    // print all the page starting at the offset 10
    echo stream_get_contents($stream, -1, 10);

    fclose($stream);
}

if ($stream = fopen('http://www.example.net', 'r')) {
    // print the first 5 bytes
    echo stream_get_contents($stream, 5);

    fclose($stream);
}

?>

Notes

Note: This function is binary-safe.

See Also

  • fgets() - Gets line from file pointer
  • fread() - Binary-safe file read
  • fpassthru() - Output all remaining data on a file pointer


Retrieve list of registered filters

  • « stream_get_contents
  • stream_get_line »
  • PHP Manual
  • Stream Functions
  • Retrieve list of registered filters

stream_get_filters

(PHP 5, PHP 7)

stream_get_filters — Retrieve list of registered filters

Description

stream_get_filters ( void ) : array

Retrieve the list of registered filters on the running system.

Return Values

Returns an indexed array containing the name of all stream filters available.

Examples

Example #1 Using stream_get_filters()

<?php
$streamlist = stream_get_filters();
print_r($streamlist);
?>

The above example will output something similar to:

Array (
  [0] => string.rot13
  [1] => string.toupper
  [2] => string.tolower
  [3] => string.base64
  [4] => string.quoted-printable
)

See Also

  • stream_filter_register() - Register a user defined stream filter
  • stream_get_wrappers() - Retrieve list of registered streams


Gets line from stream resource up to a given delimiter

  • « stream_get_filters
  • stream_get_meta_data »
  • PHP Manual
  • Stream Functions
  • Gets line from stream resource up to a given delimiter

stream_get_line

(PHP 5, PHP 7)

stream_get_line — Gets line from stream resource up to a given delimiter

Description

stream_get_line ( resource $handle , int $length [, string $ending ] ) : string

Gets a line from the given handle.

Reading ends when length bytes have been read, when the string specified by ending is found (which is not included in the return value), or on EOF (whichever comes first).

This function is nearly identical to fgets() except in that it allows end of line delimiters other than the standard \n, \r, and \r\n, and does not return the delimiter itself.

Parameters

handle

A valid file handle.

length

The number of bytes to read from the handle.

ending

An optional string delimiter.

Return Values

Returns a string of up to length bytes read from the file pointed to by handle.

If an error occurs, returns FALSE.

See Also

  • fread() - Binary-safe file read
  • fgets() - Gets line from file pointer
  • fgetc() - Gets character from file pointer


Retrieves header/meta data from streams/file pointers

  • « stream_get_line
  • stream_get_transports »
  • PHP Manual
  • Stream Functions
  • Retrieves header/meta data from streams/file pointers

stream_get_meta_data

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

stream_get_meta_data — Retrieves header/meta data from streams/file pointers

Description

stream_get_meta_data ( resource $stream ) : array

Returns information about an existing stream.

Parameters

stream

The stream can be any stream created by fopen(), fsockopen() and pfsockopen().

Return Values

The result array contains the following items:

  • timed_out (bool) - TRUE if the stream timed out while waiting for data on the last call to fread() or fgets().

  • blocked (bool) - TRUE if the stream is in blocking IO mode. See stream_set_blocking().

  • eof (bool) - TRUE if the stream has reached end-of-file. Note that for socket streams this member can be TRUE even when unread_bytes is non-zero. To determine if there is more data to be read, use feof() instead of reading this item.

  • unread_bytes (int) - the number of bytes currently contained in the PHP's own internal buffer.

    Note: You shouldn't use this value in a script.

  • stream_type (string) - a label describing the underlying implementation of the stream.

  • wrapper_type (string) - a label describing the protocol wrapper implementation layered over the stream. See Supported Protocols and Wrappers for more information about wrappers.

  • wrapper_data (mixed) - wrapper specific data attached to this stream. See Supported Protocols and Wrappers for more information about wrappers and their wrapper data.

  • mode (string) - the type of access required for this stream (see Table 1 of the fopen() reference)

  • seekable (bool) - whether the current stream can be seeked.

  • uri (string) - the URI/filename associated with this stream.

Examples

Example #1 stream_get_meta_data() example

<?php
$url = 'http://www.example.com/';

if (!$fp = fopen($url, 'r')) {
    trigger_error("Unable to open URL ($url)", E_USER_ERROR);
}

$meta = stream_get_meta_data($fp);

print_r($meta);

fclose($fp);
?>

The above example will output something similar to:

Array
(
    [wrapper_data] => Array
        (
            [0] => HTTP/1.1 200 OK
            [1] => Server: Apache/2.2.3 (Red Hat)
            [2] => Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT
            [3] => ETag: "b300b4-1b6-4059a80bfd280"
            [4] => Accept-Ranges: bytes
            [5] => Content-Type: text/html; charset=UTF-8
            [6] => Set-Cookie: FOO=BAR; expires=Fri, 21-Dec-2012 12:00:00 GMT; path=/; domain=.example.com
            [6] => Connection: close
            [7] => Date: Fri, 16 Oct 2009 12:00:00 GMT
            [8] => Age: 1164
            [9] => Content-Length: 438
        )

    [wrapper_type] => http
    [stream_type] => tcp_socket/ssl
    [mode] => r
    [unread_bytes] => 438
    [seekable] =>
    [uri] => http://www.example.com/
    [timed_out] =>
    [blocked] => 1
    [eof] =>
)

Notes

Note:

This function does NOT work on sockets created by the Socket extension.

See Also

  • get_headers() - Fetches all the headers sent by the server in response to an HTTP request
  • $http_response_header


Retrieve list of registered socket transports

  • « stream_get_meta_data
  • stream_get_wrappers »
  • PHP Manual
  • Stream Functions
  • Retrieve list of registered socket transports

stream_get_transports

(PHP 5, PHP 7)

stream_get_transports — Retrieve list of registered socket transports

Description

stream_get_transports ( void ) : array

Returns an indexed array containing the name of all socket transports available on the running system.

Return Values

Returns an indexed array of socket transports names.

Examples

Example #1 Using stream_get_transports()

<?php
$xportlist = stream_get_transports();
print_r($xportlist);
?>

The above example will output something similar to:

Array (
  [0] => tcp
  [1] => udp
  [2] => unix
  [3] => udg
)

See Also

  • stream_get_filters() - Retrieve list of registered filters
  • stream_get_wrappers() - Retrieve list of registered streams


Retrieve list of registered streams

  • « stream_get_transports
  • stream_is_local »
  • PHP Manual
  • Stream Functions
  • Retrieve list of registered streams

stream_get_wrappers

(PHP 5, PHP 7)

stream_get_wrappers — Retrieve list of registered streams

Description

stream_get_wrappers ( void ) : array

Retrieve list of registered streams available on the running system.

Return Values

Returns an indexed array containing the name of all stream wrappers available on the running system.

Examples

Example #1 stream_get_wrappers() example

<?php
print_r(stream_get_wrappers());
?>

The above example will output something similar to:

Array
(
    [0] => php
    [1] => file
    [2] => http
    [3] => ftp
    [4] => compress.bzip2
    [5] => compress.zlib
)

Example #2 Checking for the existence of a stream wrapper

<?php
// check for the existence of the bzip2 stream wrapper
if (in_array('compress.bzip2', stream_get_wrappers())) {
    echo 'compress.bzip2:// support enabled.';
} else {
    echo 'compress.bzip2:// support not enabled.';
}
?>

See Also

  • stream_wrapper_register() - Register a URL wrapper implemented as a PHP class


Checks if a stream is a local stream

  • « stream_get_wrappers
  • stream_isatty »
  • PHP Manual
  • Stream Functions
  • Checks if a stream is a local stream

stream_is_local

(PHP 5 >= 5.2.4, PHP 7)

stream_is_local — Checks if a stream is a local stream

Description

stream_is_local ( mixed $stream_or_url ) : bool

Checks if a stream, or a URL, is a local one or not.

Parameters

stream_or_url

The stream resource or URL to check.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 stream_is_local() example

Basic usage example.

<?php
var_dump(stream_is_local("http://example.com"));
var_dump(stream_is_local("/etc"));
?>

The above example will output something similar to:

bool(false)
bool(true)


Check if a stream is a TTY

  • « stream_is_local
  • stream_notification_callback »
  • PHP Manual
  • Stream Functions
  • Check if a stream is a TTY

stream_isatty

(PHP 7 >= 7.2.0)

stream_isatty — Check if a stream is a TTY

Description

stream_isatty ( resource $stream ) : bool

Determines if stream stream refers to a valid terminal type device. This is a more portable version of posix_isatty(), since it works on Windows systems too.

Parameters

stream

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 stream_isatty() example

This command can be used to determine if a standard output / standard error stream is redirected to a file.

php -r "var_export(stream_isatty(STDERR));"

The above example will output something similar to:

true
php -r "var_export(stream_isatty(STDERR));" 2>output.txt

The above example will output something similar to:

false


A callback function for the notification context parameter

  • « stream_isatty
  • stream_register_wrapper »
  • PHP Manual
  • Stream Functions
  • A callback function for the notification context parameter

stream_notification_callback

(PHP 5 >= 5.2.0, PHP 7)

stream_notification_callback — A callback function for the notification context parameter

Description

stream_notification_callback ( int $notification_code , int $severity , string $message , int $message_code , int $bytes_transferred , int $bytes_max ) : void

A callable function, used by the notification context parameter, called during an event.

Note:

This is not a real function, only a prototype of how the function should be.

Parameters

notification_code

One of the STREAM_NOTIFY_* notification constants.

severity

One of the STREAM_NOTIFY_SEVERITY_* notification constants.

message

Passed if a descriptive message is available for the event.

message_code

Passed if a descriptive message code is available for the event.

The meaning of this value is dependent on the specific wrapper in use.

bytes_transferred

If applicable, the bytes_transferred will be populated.

bytes_max

If applicable, the bytes_max will be populated.

Return Values

No value is returned.

Examples

Example #1 stream_notification_callback() example

<?php
function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) {

    switch($notification_code) {
        case STREAM_NOTIFY_RESOLVE:
        case STREAM_NOTIFY_AUTH_REQUIRED:
        case STREAM_NOTIFY_COMPLETED:
        case STREAM_NOTIFY_FAILURE:
        case STREAM_NOTIFY_AUTH_RESULT:
            var_dump($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max);
            /* Ignore */
            break;

        case STREAM_NOTIFY_REDIRECTED:
            echo "Being redirected to: ", $message;
            break;

        case STREAM_NOTIFY_CONNECT:
            echo "Connected...";
            break;

        case STREAM_NOTIFY_FILE_SIZE_IS:
            echo "Got the filesize: ", $bytes_max;
            break;

        case STREAM_NOTIFY_MIME_TYPE_IS:
            echo "Found the mime-type: ", $message;
            break;

        case STREAM_NOTIFY_PROGRESS:
            echo "Made some progress, downloaded ", $bytes_transferred, " so far";
            break;
    }
    echo "\n";
}

$ctx = stream_context_create();
stream_context_set_params($ctx, array("notification" => "stream_notification_callback"));

file_get_contents("http://php.net/contact", false, $ctx);
?>

The above example will output something similar to:

Connected...
Found the mime-type: text/html; charset=utf-8
Being redirected to: http://no.php.net/contact
Connected...
Got the filesize: 0
Found the mime-type: text/html; charset=utf-8
Being redirected to: http://no.php.net/contact.php
Connected...
Got the filesize: 4589
Found the mime-type: text/html;charset=utf-8
Made some progress, downloaded 0 so far
Made some progress, downloaded 0 so far
Made some progress, downloaded 0 so far
Made some progress, downloaded 1440 so far
Made some progress, downloaded 2880 so far
Made some progress, downloaded 4320 so far
Made some progress, downloaded 5760 so far
Made some progress, downloaded 6381 so far
Made some progress, downloaded 7002 so far

Example #2 Simple progressbar for commandline download client

<?php
function usage($argv) {
    echo "Usage:\n";
    printf("\tphp %s <http://example.com/file> <localfile>\n", $argv[0]);
    exit(1);
}

function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) {
    static $filesize = null;

    switch($notification_code) {
    case STREAM_NOTIFY_RESOLVE:
    case STREAM_NOTIFY_AUTH_REQUIRED:
    case STREAM_NOTIFY_COMPLETED:
    case STREAM_NOTIFY_FAILURE:
    case STREAM_NOTIFY_AUTH_RESULT:
        /* Ignore */
        break;

    case STREAM_NOTIFY_REDIRECTED:
        echo "Being redirected to: ", $message, "\n";
        break;

    case STREAM_NOTIFY_CONNECT:
        echo "Connected...\n";
        break;

    case STREAM_NOTIFY_FILE_SIZE_IS:
        $filesize = $bytes_max;
        echo "Filesize: ", $filesize, "\n";
        break;

    case STREAM_NOTIFY_MIME_TYPE_IS:
        echo "Mime-type: ", $message, "\n";
        break;

    case STREAM_NOTIFY_PROGRESS:
        if ($bytes_transferred > 0) {
            if (!isset($filesize)) {
                printf("\rUnknown filesize.. %2d kb done..", $bytes_transferred/1024);
            } else {
                $length = (int)(($bytes_transferred/$filesize)*100);
                printf("\r[%-100s] %d%% (%2d/%2d kb)", str_repeat("=", $length). ">", $length, ($bytes_transferred/1024), $filesize/1024);
            }
        }
        break;
    }
}

isset($argv[1], $argv[2]) or usage($argv);

$ctx = stream_context_create();
stream_context_set_params($ctx, array("notification" => "stream_notification_callback"));

$fp = fopen($argv[1], "r", false, $ctx);
if (is_resource($fp) && file_put_contents($argv[2], $fp)) {
    echo "\nDone!\n";
    exit(0);
}

$err = error_get_last();
echo "\nErrrrrorr..\n", $err["message"], "\n";
exit(1);
?>

Executing the example above with: php -n fetch.php http://no2.php.net/get/php-5-LATEST.tar.bz2/from/this/mirror php-latest.tar.bz2 will output something similar too:

Connected...
Mime-type: text/html; charset=utf-8
Being redirected to: http://no2.php.net/distributions/php-5.2.5.tar.bz2
Connected...
Filesize: 7773024
Mime-type: application/octet-stream
[========================================>                                                           ] 40% (3076/7590 kb)

See Also

  • Context parameters


Alias of stream_wrapper_register

  • « stream_notification_callback
  • stream_resolve_include_path »
  • PHP Manual
  • Stream Functions
  • Alias of stream_wrapper_register

stream_register_wrapper

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

stream_register_wrapper — Alias of stream_wrapper_register()

Description

This function is an alias of: stream_wrapper_register().


Resolve filename against the include path

  • « stream_register_wrapper
  • stream_select »
  • PHP Manual
  • Stream Functions
  • Resolve filename against the include path

stream_resolve_include_path

(PHP 5 >= 5.3.2, PHP 7)

stream_resolve_include_path — Resolve filename against the include path

Description

stream_resolve_include_path ( string $filename ) : string

Resolve filename against the include path according to the same rules as fopen()/include.

Parameters

filename

The filename to resolve.

Return Values

Returns a string containing the resolved absolute filename, or FALSE on failure.

Examples

Example #1 stream_resolve_include_path() example

Basic usage example.

<?php
var_dump(stream_resolve_include_path("test.php"));
?>

The above example will output something similar to:

string(22) "/var/www/html/test.php"


Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec

  • « stream_resolve_include_path
  • stream_set_blocking »
  • PHP Manual
  • Stream Functions
  • Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec

stream_select

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

stream_select — Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec

Description

stream_select ( array &$read , array &$write , array &$except , int $tv_sec [, int $tv_usec = 0 ] ) : int

The stream_select() function accepts arrays of streams and waits for them to change status. Its operation is equivalent to that of the socket_select() function except in that it acts on streams.

Parameters

read

The streams listed in the read array will be watched to see if characters become available for reading (more precisely, to see if a read will not block - in particular, a stream resource is also ready on end-of-file, in which case an fread() will return a zero length string).

write

The streams listed in the write array will be watched to see if a write will not block.

except

The streams listed in the except array will be watched for high priority exceptional ("out-of-band") data arriving.

Note:

When stream_select() returns, the arrays read, write and except are modified to indicate which stream resource(s) actually changed status.

You do not need to pass every array to stream_select(). You can leave it out and use an empty array or NULL instead. Also do not forget that those arrays are passed by reference and will be modified after stream_select() returns.
tv_sec

The tv_sec and tv_usec together form the timeout parameter, tv_sec specifies the number of seconds while tv_usec the number of microseconds. The timeout is an upper bound on the amount of time that stream_select() will wait before it returns. If tv_sec and tv_usec are both set to 0, stream_select() will not wait for data - instead it will return immediately, indicating the current status of the streams.

If tv_sec is NULL stream_select() can block indefinitely, returning only when an event on one of the watched streams occurs (or if a signal interrupts the system call).

Warning

Using a timeout value of 0 allows you to instantaneously poll the status of the streams, however, it is NOT a good idea to use a 0 timeout value in a loop as it will cause your script to consume too much CPU time.

It is much better to specify a timeout value of a few seconds, although if you need to be checking and running other code concurrently, using a timeout value of at least 200000 microseconds will help reduce the CPU usage of your script.

Remember that the timeout value is the maximum time that will elapse; stream_select() will return as soon as the requested streams are ready for use.

tv_usec

See tv_sec description.

Return Values

On success stream_select() returns the number of stream resources contained in the modified arrays, which may be zero if the timeout expires before anything interesting happens. On error FALSE is returned and a warning raised (this can happen if the system call is interrupted by an incoming signal).

Examples

Example #1 stream_select() Example

This example checks to see if data has arrived for reading on either $stream1 or $stream2. Since the timeout value is 0 it will return immediately:

<?php
/* Prepare the read array */
$read   = array($stream1, $stream2);
$write  = NULL;
$except = NULL;
if (false === ($num_changed_streams = stream_select($read, $write, $except, 0))) {
    /* Error handling */
} elseif ($num_changed_streams > 0) {
    /* At least on one of the streams something interesting happened */
}
?>

Notes

Note:

Due to a limitation in the current Zend Engine it is not possible to pass a constant modifier like NULL directly as a parameter to a function which expects this parameter to be passed by reference. Instead use a temporary variable or an expression with the leftmost member being a temporary variable:

<?php
$e = NULL;
stream_select($r, $w, $e, 0);
?>

Note:

Be sure to use the === operator when checking for an error. Since the stream_select() may return 0 the comparison with == would evaluate to TRUE:

<?php
$e = NULL;
if (false === stream_select($r, $w, $e, 0)) {
    echo "stream_select() failed\n";
}
?>

Note:

If you read/write to a stream returned in the arrays be aware that they do not necessarily read/write the full amount of data you have requested. Be prepared to even only be able to read/write a single byte.

Note:

Some streams (like zlib) cannot be selected by this function.

Note:

Windows compatibility: stream_select() used on a pipe returned from proc_open() may cause data loss under Windows 98.

Use of stream_select() on file descriptors returned by proc_open() will fail and return FALSE under Windows.

See Also

  • stream_set_blocking() - Set blocking/non-blocking mode on a stream


Set blocking/non-blocking mode on a stream

  • « stream_select
  • stream_set_chunk_size »
  • PHP Manual
  • Stream Functions
  • Set blocking/non-blocking mode on a stream

stream_set_blocking

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

stream_set_blocking — Set blocking/non-blocking mode on a stream

Description

stream_set_blocking ( resource $stream , bool $mode ) : bool

Sets blocking or non-blocking mode on a stream.

This function works for any stream that supports non-blocking mode (currently, regular files and socket streams).

Parameters

stream

The stream.

mode

If mode is FALSE, the given stream will be switched to non-blocking mode, and if TRUE, it will be switched to blocking mode. This affects calls like fgets() and fread() that read from the stream. In non-blocking mode an fgets() call will always return right away while in blocking mode it will wait for data to become available on the stream.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note:

This function was previously called as set_socket_blocking() and later socket_set_blocking() but this usage is deprecated.

Note:

On Windows, this has no affect on local files. Non-blocking IO for local files is not supported on Windows.

See Also

  • stream_select() - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec


Set the stream chunk size

  • « stream_set_blocking
  • stream_set_read_buffer »
  • PHP Manual
  • Stream Functions
  • Set the stream chunk size

stream_set_chunk_size

(PHP 5 >= 5.4.0, PHP 7)

stream_set_chunk_size — Set the stream chunk size

Description

stream_set_chunk_size ( resource $fp , int $chunk_size ) : int

Set the stream chunk size.

Parameters

fp

The target stream.

chunk_size

The desired new chunk size.

Return Values

Returns the previous chunk size on success.

Will return FALSE if chunk_size is less than 1 or greater than PHP_INT_MAX.

Errors/Exceptions

Will emit an E_WARNING level error if chunk_size is less than 1 or greater than PHP_INT_MAX.


Set read file buffering on the given stream

  • « stream_set_chunk_size
  • stream_set_timeout »
  • PHP Manual
  • Stream Functions
  • Set read file buffering on the given stream

stream_set_read_buffer

(PHP 5 >= 5.3.3, PHP 7)

stream_set_read_buffer — Set read file buffering on the given stream

Description

stream_set_read_buffer ( resource $stream , int $buffer ) : int

Sets the read buffer. It's the equivalent of stream_set_write_buffer(), but for read operations.

Parameters

stream

The file pointer.

buffer

The number of bytes to buffer. If buffer is 0 then read operations are unbuffered. This ensures that all reads with fread() are completed before other processes are allowed to read from that input stream.

Return Values

Returns 0 on success, or another value if the request cannot be honored.

See Also

  • stream_set_write_buffer() - Sets write file buffering on the given stream


Set timeout period on a stream

  • « stream_set_read_buffer
  • stream_set_write_buffer »
  • PHP Manual
  • Stream Functions
  • Set timeout period on a stream

stream_set_timeout

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

stream_set_timeout — Set timeout period on a stream

Description

stream_set_timeout ( resource $stream , int $seconds [, int $microseconds = 0 ] ) : bool

Sets the timeout value on stream, expressed in the sum of seconds and microseconds.

When the stream times out, the 'timed_out' key of the array returned by stream_get_meta_data() is set to TRUE, although no error/warning is generated.

Parameters

stream

The target stream.

seconds

The seconds part of the timeout to be set.

microseconds

The microseconds part of the timeout to be set.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 stream_set_timeout() example

<?php
$fp = fsockopen("www.example.com", 80);
if (!$fp) {
    echo "Unable to open\n";
} else {

    fwrite($fp, "GET / HTTP/1.0\r\n\r\n");
    stream_set_timeout($fp, 2);
    $res = fread($fp, 2000);

    $info = stream_get_meta_data($fp);
    fclose($fp);

    if ($info['timed_out']) {
        echo 'Connection timed out!';
    } else {
        echo $res;
    }

}
?>

Notes

Note:

This function doesn't work with advanced operations like stream_socket_recvfrom(), use stream_select() with timeout parameter instead.

This function was previously called as set_socket_timeout() and later socket_set_timeout() but this usage is deprecated.

See Also

  • fsockopen() - Open Internet or Unix domain socket connection
  • fopen() - Opens file or URL


Sets write file buffering on the given stream

  • « stream_set_timeout
  • stream_socket_accept »
  • PHP Manual
  • Stream Functions
  • Sets write file buffering on the given stream

stream_set_write_buffer

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

stream_set_write_buffer — Sets write file buffering on the given stream

Description

stream_set_write_buffer ( resource $stream , int $buffer ) : int

Sets the buffering for write operations on the given stream to buffer bytes.

Parameters

stream

The file pointer.

buffer

The number of bytes to buffer. If buffer is 0 then write operations are unbuffered. This ensures that all writes with fwrite() are completed before other processes are allowed to write to that output stream.

Return Values

Returns 0 on success, or another value if the request cannot be honored.

Examples

Example #1 stream_set_write_buffer() example

The following example demonstrates how to use stream_set_write_buffer() to create an unbuffered stream.

<?php
$fp = fopen($file, "w");
if ($fp) {
  if (stream_set_write_buffer($fp, 0) !== 0) {
      // changing the buffering failed
  }
  fwrite($fp, $output);
  fclose($fp);
}
?>

See Also

  • fopen() - Opens file or URL
  • fwrite() - Binary-safe file write


Accept a connection on a socket created by stream_socket_server

  • « stream_set_write_buffer
  • stream_socket_client »
  • PHP Manual
  • Stream Functions
  • Accept a connection on a socket created by stream_socket_server

stream_socket_accept

(PHP 5, PHP 7)

stream_socket_accept — Accept a connection on a socket created by stream_socket_server()

Description

stream_socket_accept ( resource $server_socket [, float $timeout = ini_get("default_socket_timeout") [, string &$peername ]] ) : resource

Accept a connection on a socket previously created by stream_socket_server().

Parameters

server_socket

The server socket to accept a connection from.

timeout

Override the default socket accept timeout. Time should be given in seconds.

peername

Will be set to the name (address) of the client which connected, if included and available from the selected transport.

Note:

Can also be determined later using stream_socket_get_name().

Return Values

Returns a stream to the accepted socket connection or FALSE on failure.

Notes

Warning

This function should not be used with UDP server sockets. Instead, use stream_socket_recvfrom() and stream_socket_sendto().

See Also

  • stream_socket_server() - Create an Internet or Unix domain server socket
  • stream_socket_get_name() - Retrieve the name of the local or remote sockets
  • stream_set_blocking() - Set blocking/non-blocking mode on a stream
  • stream_set_timeout() - Set timeout period on a stream
  • fgets() - Gets line from file pointer
  • fgetss() - Gets line from file pointer and strip HTML tags
  • fwrite() - Binary-safe file write
  • fclose() - Closes an open file pointer
  • feof() - Tests for end-of-file on a file pointer
  • cURL Functions


Open Internet or Unix domain socket connection

  • « stream_socket_accept
  • stream_socket_enable_crypto »
  • PHP Manual
  • Stream Functions
  • Open Internet or Unix domain socket connection

stream_socket_client

(PHP 5, PHP 7)

stream_socket_client — Open Internet or Unix domain socket connection

Description

stream_socket_client ( string $remote_socket [, int &$errno [, string &$errstr [, float $timeout = ini_get("default_socket_timeout") [, int $flags = STREAM_CLIENT_CONNECT [, resource $context ]]]]] ) : resource

Initiates a stream or datagram connection to the destination specified by remote_socket. The type of socket created is determined by the transport specified using standard URL formatting: transport://target. For Internet Domain sockets (AF_INET) such as TCP and UDP, the target portion of the remote_socket parameter should consist of a hostname or IP address followed by a colon and a port number. For Unix domain sockets, the target portion should point to the socket file on the filesystem.

Note:

The stream will by default be opened in blocking mode. You can switch it to non-blocking mode by using stream_set_blocking().

Parameters

remote_socket

Address to the socket to connect to.

errno

Will be set to the system level error number if connection fails.

errstr

Will be set to the system level error message if the connection fails.

timeout

Number of seconds until the connect() system call should timeout.

Note: This parameter only applies when not making asynchronous connection attempts.

Note:

To set a timeout for reading/writing data over the socket, use the stream_set_timeout(), as the timeout only applies while making connecting the socket.

flags

Bitmask field which may be set to any combination of connection flags. Currently the select of connection flags is limited to STREAM_CLIENT_CONNECT (default), STREAM_CLIENT_ASYNC_CONNECT and STREAM_CLIENT_PERSISTENT.

context

A valid context resource created with stream_context_create().

Return Values

On success a stream resource is returned which may
be used together with the other file functions (such as
fgets(), fgetss(),
fwrite(), fclose(), and
feof()), FALSE on failure.

Errors/Exceptions

On failure the errno and errstr arguments will be populated with the actual system level error that occurred in the system-level connect() call. If the value returned in errno is 0 and the function returned FALSE, it is an indication that the error occurred before the connect() call. This is most likely due to a problem initializing the socket. Note that the errno and errstr arguments will always be passed by reference.

Examples

Example #1 stream_socket_client() example

<?php
$fp = stream_socket_client("tcp://www.example.com:80", $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    fwrite($fp, "GET / HTTP/1.0\r\nHost: www.example.com\r\nAccept: */*\r\n\r\n");
    while (!feof($fp)) {
        echo fgets($fp, 1024);
    }
    fclose($fp);
}
?>

Example #2 Using UDP connection

Retrieving the day and time from the UDP service "daytime" (port 13) on localhost.

<?php
$fp = stream_socket_client("udp://127.0.0.1:13", $errno, $errstr);
if (!$fp) {
    echo "ERROR: $errno - $errstr<br />\n";
} else {
    fwrite($fp, "\n");
    echo fread($fp, 26);
    fclose($fp);
}
?>

Notes

Warning

UDP sockets will sometimes appear to have opened without an error, even if the remote host is unreachable. The error will only become apparent when you read or write data to/from the socket. The reason for this is because UDP is a "connectionless" protocol, which means that the operating system does not try to establish a link for the socket until it actually needs to send or receive data.

Note: When specifying a numerical IPv6 address (e.g. fe80::1), you must enclose the IP in square brackets—for example, tcp://[fe80::1]:80.

Note:

Depending on the environment, the Unix domain or the optional connect timeout may not be available. A list of available transports can be retrieved using stream_get_transports(). See List of Supported Socket Transports for a list of built in transports.

See Also

  • stream_socket_server() - Create an Internet or Unix domain server socket
  • stream_set_blocking() - Set blocking/non-blocking mode on a stream
  • stream_set_timeout() - Set timeout period on a stream
  • stream_select() - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec
  • fgets() - Gets line from file pointer
  • fgetss() - Gets line from file pointer and strip HTML tags
  • fwrite() - Binary-safe file write
  • fclose() - Closes an open file pointer
  • feof() - Tests for end-of-file on a file pointer
  • cURL Functions


Turns encryption on/off on an already connected socket

  • « stream_socket_client
  • stream_socket_get_name »
  • PHP Manual
  • Stream Functions
  • Turns encryption on/off on an already connected socket

stream_socket_enable_crypto

(PHP 5 >= 5.1.0, PHP 7)

stream_socket_enable_crypto — Turns encryption on/off on an already connected socket

Description

stream_socket_enable_crypto ( resource $stream , bool $enable [, int $crypto_type [, resource $session_stream ]] ) : mixed

Enable or disable encryption on the stream.

Once the crypto settings are established, cryptography can be turned on and off dynamically by passing TRUE or FALSE in the enable parameter.

Parameters

stream

The stream resource.

enable

Enable/disable cryptography on the stream.

crypto_type

Setup encryption on the stream. Valid methods are

  • STREAM_CRYPTO_METHOD_SSLv2_CLIENT
  • STREAM_CRYPTO_METHOD_SSLv3_CLIENT
  • STREAM_CRYPTO_METHOD_SSLv23_CLIENT
  • STREAM_CRYPTO_METHOD_ANY_CLIENT
  • STREAM_CRYPTO_METHOD_TLS_CLIENT
  • STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT
  • STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT
  • STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
  • STREAM_CRYPTO_METHOD_SSLv2_SERVER
  • STREAM_CRYPTO_METHOD_SSLv3_SERVER
  • STREAM_CRYPTO_METHOD_SSLv23_SERVER
  • STREAM_CRYPTO_METHOD_ANY_SERVER
  • STREAM_CRYPTO_METHOD_TLS_SERVER
  • STREAM_CRYPTO_METHOD_TLSv1_0_SERVER
  • STREAM_CRYPTO_METHOD_TLSv1_1_SERVER
  • STREAM_CRYPTO_METHOD_TLSv1_2_SERVER

If omitted, the crypto_method context option on the stream's SSL context will be used instead.

session_stream

Seed the stream with settings from session_stream.

Return Values

Returns TRUE on success, FALSE if negotiation has failed or 0 if there isn't enough data and you should try again (only for non-blocking sockets).

Changelog

Version | Description
5.6.0 | Introduce STREAM_CRYPTO_METHOD_ANY_CLIENT, STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT, STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT, STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT, STREAM_CRYPTO_METHOD_ANY_SERVER, STREAM_CRYPTO_METHOD_TLSv1_0_SERVER, STREAM_CRYPTO_METHOD_TLSv1_1_SERVER, STREAM_CRYPTO_METHOD_TLSv1_2_SERVER.
5.6.0 | The crypto_type is now optional.

Examples

Example #1 stream_socket_enable_crypto() example

<?php
$fp = stream_socket_client("tcp://myproto.example.com:31337", $errno, $errstr, 30);
if (!$fp) {
    die("Unable to connect: $errstr ($errno)");
}

/* Turn on encryption for login phase */
stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
fwrite($fp, "USER god\r\n");
fwrite($fp, "PASS secret\r\n");

/* Turn off encryption for the rest */
stream_socket_enable_crypto($fp, false);

while ($motd = fgets($fp)) {
    echo $motd;
}

fclose($fp);
?>

The above example will output something similar to:

See Also

  • OpenSSL Functions
    •

  • List of Supported Socket Transports
    •


Retrieve the name of the local or remote sockets

  • « stream_socket_enable_crypto
  • stream_socket_pair »
  • PHP Manual
  • Stream Functions
  • Retrieve the name of the local or remote sockets

stream_socket_get_name

(PHP 5, PHP 7)

stream_socket_get_name — Retrieve the name of the local or remote sockets

Description

stream_socket_get_name ( resource $handle , bool $want_peer ) : string

Returns the local or remote name of a given socket connection.

Parameters

handle

The socket to get the name of.

want_peer

If set to TRUE the remote socket name will be returned, if set to FALSE the local socket name will be returned.

Return Values

The name of the socket.

See Also

  • stream_socket_accept() - Accept a connection on a socket created by stream_socket_server


Creates a pair of connected, indistinguishable socket streams

  • « stream_socket_get_name
  • stream_socket_recvfrom »
  • PHP Manual
  • Stream Functions
  • Creates a pair of connected, indistinguishable socket streams

stream_socket_pair

(PHP 5 >= 5.1.0, PHP 7)

stream_socket_pair — Creates a pair of connected, indistinguishable socket streams

Description

stream_socket_pair ( int $domain , int $type , int $protocol ) : array

stream_socket_pair() creates a pair of connected, indistinguishable socket streams. This function is commonly used in IPC (Inter-Process Communication).

Parameters

domain

The protocol family to be used: STREAM_PF_INET, STREAM_PF_INET6 or STREAM_PF_UNIX

type

The type of communication to be used: STREAM_SOCK_DGRAM, STREAM_SOCK_RAW, STREAM_SOCK_RDM, STREAM_SOCK_SEQPACKET or STREAM_SOCK_STREAM

protocol

The protocol to be used: STREAM_IPPROTO_ICMP, STREAM_IPPROTO_IP, STREAM_IPPROTO_RAW, STREAM_IPPROTO_TCP or STREAM_IPPROTO_UDP

Note: Please consult the Streams constant list for further details on each constant.

Return Values

Returns an array with the two socket resources on success, or FALSE on failure.

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms.

Examples

Example #1 A stream_socket_pair() example

This example shows the basic usage of stream_socket_pair() in Inter-Process Communication.

<?php

$sockets = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);
$pid     = pcntl_fork();

if ($pid == -1) {
     die('could not fork');

} else if ($pid) {
     /* parent */
    fclose($sockets[0]);

    fwrite($sockets[1], "child PID: $pid\n");
    echo fgets($sockets[1]);

    fclose($sockets[1]);

} else {
    /* child */
    fclose($sockets[1]);

    fwrite($sockets[0], "message from child\n");
    echo fgets($sockets[0]);

    fclose($sockets[0]);
}

?>

The above example will output something similar to:

child PID: 1378
message from child


Receives data from a socket, connected or not

  • « stream_socket_pair
  • stream_socket_sendto »
  • PHP Manual
  • Stream Functions
  • Receives data from a socket, connected or not

stream_socket_recvfrom

(PHP 5, PHP 7)

stream_socket_recvfrom — Receives data from a socket, connected or not

Description

stream_socket_recvfrom ( resource $socket , int $length [, int $flags = 0 [, string &$address ]] ) : string

stream_socket_recvfrom() accepts data from a remote socket up to length bytes.

Parameters

socket

The remote socket.

length

The number of bytes to receive from the socket.

flags

The value of flags can be any combination of the following:

Possible values for flags
STREAM_OOB | Process OOB (out-of-band) data.
STREAM_PEEK | Retrieve data from the socket, but do not consume the buffer. Subsequent calls to fread() or stream_socket_recvfrom() will see the same data.

address

If address is provided it will be populated with the address of the remote socket.

Return Values

Returns the read data, as a string

Examples

Example #1 stream_socket_recvfrom() example

<?php
/* Open a server socket to port 1234 on localhost */
$server = stream_socket_server('tcp://127.0.0.1:1234');

/* Accept a connection */
$socket = stream_socket_accept($server);

/* Grab a packet (1500 is a typical MTU size) of OOB data */
echo "Received Out-Of-Band: '" . stream_socket_recvfrom($socket, 1500, STREAM_OOB) . "'\n";

/* Take a peek at the normal in-band data, but don't consume it. */
echo "Data: '" . stream_socket_recvfrom($socket, 1500, STREAM_PEEK) . "'\n";

/* Get the exact same packet again, but remove it from the buffer this time. */
echo "Data: '" . stream_socket_recvfrom($socket, 1500) . "'\n";

/* Close it up */
fclose($socket);
fclose($server);
?>

Notes

Note:

If a message received is longer than the length parameter, excess bytes may be discarded depending on the type of socket the message is received from (such as UDP).

Note:

Calls to stream_socket_recvfrom() on socket-based streams, after calls to buffer-based stream functions (like fread() or stream_get_line()) read data directly from the socket and bypass the stream buffer.

See Also

  • stream_socket_sendto() - Sends a message to a socket, whether it is connected or not
  • stream_socket_client() - Open Internet or Unix domain socket connection
  • stream_socket_server() - Create an Internet or Unix domain server socket


Sends a message to a socket, whether it is connected or not

  • « stream_socket_recvfrom
  • stream_socket_server »
  • PHP Manual
  • Stream Functions
  • Sends a message to a socket, whether it is connected or not

stream_socket_sendto

(PHP 5, PHP 7)

stream_socket_sendto — Sends a message to a socket, whether it is connected or not

Description

stream_socket_sendto ( resource $socket , string $data [, int $flags = 0 [, string $address ]] ) : int

Sends the specified data through the socket.

Parameters

socket

The socket to send data to.

data

The data to be sent.

flags

The value of flags can be any combination of the following:

possible values for flags
STREAM_OOB Process OOB (out-of-band) data.

address

The address specified when the socket stream was created will be used unless an alternate address is specified in address.

If specified, it must be in dotted quad (or [ipv6]) format.

Return Values

Returns a result code, as an integer.

Examples

Example #1 stream_socket_sendto() Example

<?php
/* Open a socket to port 1234 on localhost */
$socket = stream_socket_client('tcp://127.0.0.1:1234');

/* Send ordinary data via ordinary channels. */
fwrite($socket, "Normal data transmit.");

/* Send more data out of band. */
stream_socket_sendto($socket, "Out of Band data.", STREAM_OOB);

/* Close it up */
fclose($socket);
?>

See Also

  • stream_socket_recvfrom() - Receives data from a socket, connected or not
  • stream_socket_client() - Open Internet or Unix domain socket connection
  • stream_socket_server() - Create an Internet or Unix domain server socket


Create an Internet or Unix domain server socket

  • « stream_socket_sendto
  • stream_socket_shutdown »
  • PHP Manual
  • Stream Functions
  • Create an Internet or Unix domain server socket

stream_socket_server

(PHP 5, PHP 7)

stream_socket_server — Create an Internet or Unix domain server socket

Description

stream_socket_server ( string $local_socket [, int &$errno [, string &$errstr [, int $flags = STREAM_SERVER_BIND | STREAM_SERVER_LISTEN [, resource $context ]]]] ) : resource

Creates a stream or datagram socket on the specified local_socket.

This function only creates a socket, to begin accepting connections use stream_socket_accept().

Parameters

local_socket

The type of socket created is determined by the transport specified using standard URL formatting: transport://target.

For Internet Domain sockets (AF_INET) such as TCP and UDP, the target portion of the remote_socket parameter should consist of a hostname or IP address followed by a colon and a port number. For Unix domain sockets, the target portion should point to the socket file on the filesystem.

Depending on the environment, Unix domain sockets may not be available. A list of available transports can be retrieved using stream_get_transports(). See List of Supported Socket Transports for a list of bulitin transports.

errno

If the optional errno and errstr arguments are present they will be set to indicate the actual system level error that occurred in the system-level socket(), bind(), and listen() calls. If the value returned in errno is 0 and the function returned FALSE, it is an indication that the error occurred before the bind() call. This is most likely due to a problem initializing the socket. Note that the errno and errstr arguments will always be passed by reference.

errstr

See errno description.

flags

A bitmask field which may be set to any combination of socket creation flags.

Note:

For UDP sockets, you must use STREAM_SERVER_BIND as the flags parameter.

context

Return Values

Returns the created stream, or FALSE on error.

Examples

Example #1 Using TCP server sockets

<?php
$socket = stream_socket_server("tcp://0.0.0.0:8000", $errno, $errstr);
if (!$socket) {
  echo "$errstr ($errno)<br />\n";
} else {
  while ($conn = stream_socket_accept($socket)) {
    fwrite($conn, 'The local time is ' . date('n/j/Y g:i a') . "\n");
    fclose($conn);
  }
  fclose($socket);
}
?>

The example below shows how to act as a time server which can respond to time queries as shown in an example on stream_socket_client().

Note: Most systems require root access to create a server socket on a port below 1024.

Example #2 Using UDP server sockets

<?php
$socket = stream_socket_server("udp://127.0.0.1:1113", $errno, $errstr, STREAM_SERVER_BIND);
if (!$socket) {
    die("$errstr ($errno)");
}

do {
    $pkt = stream_socket_recvfrom($socket, 1, 0, $peer);
    echo "$peer\n";
    stream_socket_sendto($socket, date("D M j H:i:s Y\r\n"), 0, $peer);
} while ($pkt !== false);

?>

Notes

Note: When specifying a numerical IPv6 address (e.g. fe80::1), you must enclose the IP in square brackets—for example, tcp://[fe80::1]:80.

See Also

  • stream_socket_client() - Open Internet or Unix domain socket connection
  • stream_set_blocking() - Set blocking/non-blocking mode on a stream
  • stream_set_timeout() - Set timeout period on a stream
  • fgets() - Gets line from file pointer
  • fgetss() - Gets line from file pointer and strip HTML tags
  • fwrite() - Binary-safe file write
  • fclose() - Closes an open file pointer
  • feof() - Tests for end-of-file on a file pointer
  • Curl extension


Shutdown a full-duplex connection

  • « stream_socket_server
  • stream_supports_lock »
  • PHP Manual
  • Stream Functions
  • Shutdown a full-duplex connection

stream_socket_shutdown

(PHP 5 >= 5.2.1, PHP 7)

stream_socket_shutdown — Shutdown a full-duplex connection

Description

stream_socket_shutdown ( resource $stream , int $how ) : bool

Shutdowns (partially or not) a full-duplex connection.

Note:

The associated buffer, or buffers, may or may not be emptied.

Parameters

stream

An open stream (opened with stream_socket_client(), for example)

how

One of the following constants: STREAM_SHUT_RD (disable further receptions), STREAM_SHUT_WR (disable further transmissions) or STREAM_SHUT_RDWR (disable further receptions and transmissions).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 A stream_socket_shutdown() example

<?php

$server = stream_socket_server('tcp://127.0.0.1:1337');
$client = stream_socket_client('tcp://127.0.0.1:1337');

var_dump(fputs($client, "hello"));

stream_socket_shutdown($client, STREAM_SHUT_WR);
var_dump(fputs($client, "hello")); // doesn't work now

?>

The above example will output something similar to:

int(5)

Notice: fputs(): send of 5 bytes failed with errno=32 Broken pipe in test.php on line 9
int(0)

See Also

  • fclose() - Closes an open file pointer


Tells whether the stream supports locking

  • « stream_socket_shutdown
  • stream_wrapper_register »
  • PHP Manual
  • Stream Functions
  • Tells whether the stream supports locking

stream_supports_lock

(PHP 5 >= 5.3.0, PHP 7)

stream_supports_lock — Tells whether the stream supports locking

Description

stream_supports_lock ( resource $stream ) : bool

Tells whether the stream supports locking through flock().

Parameters

stream

The stream to check.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • flock() - Portable advisory file locking


Register a URL wrapper implemented as a PHP class

  • « stream_supports_lock
  • stream_wrapper_restore »
  • PHP Manual
  • Stream Functions
  • Register a URL wrapper implemented as a PHP class

stream_wrapper_register

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

stream_wrapper_register — Register a URL wrapper implemented as a PHP class

Description

stream_wrapper_register ( string $protocol , string $classname [, int $flags = 0 ] ) : bool

Allows you to implement your own protocol handlers and streams for use with all the other filesystem functions (such as fopen(), fread() etc.).

Parameters

protocol

The wrapper name to be registered.

classname

The classname which implements the protocol.

flags

Should be set to STREAM_IS_URL if protocol is a URL protocol. Default is 0, local stream.

Return Values

Returns TRUE on success or FALSE on failure.

stream_wrapper_register() will return FALSE if the protocol already has a handler.

Changelog

Version | Description
5.2.4 | Added the flags parameter.

Examples

Example #1 How to register a stream wrapper

<?php
$existed = in_array("var", stream_get_wrappers());
if ($existed) {
    stream_wrapper_unregister("var");
}
stream_wrapper_register("var", "VariableStream");
$myvar = "";

$fp = fopen("var://myvar", "r+");

fwrite($fp, "line1\n");
fwrite($fp, "line2\n");
fwrite($fp, "line3\n");

rewind($fp);
while (!feof($fp)) {
    echo fgets($fp);
}
fclose($fp);
var_dump($myvar);

if ($existed) {
    stream_wrapper_restore("var");
}

?>

The above example will output:

line1
line2
line3
string(18) "line1
line2
line3
"

See Also

  • The streamWrapper prototype class
  • Example class registered as stream wrapper
  • stream_wrapper_unregister() - Unregister a URL wrapper
  • stream_wrapper_restore() - Restores a previously unregistered built-in wrapper
  • stream_get_wrappers() - Retrieve list of registered streams


Restores a previously unregistered built-in wrapper

  • « stream_wrapper_register
  • stream_wrapper_unregister »
  • PHP Manual
  • Stream Functions
  • Restores a previously unregistered built-in wrapper

stream_wrapper_restore

(PHP 5 >= 5.1.0, PHP 7)

stream_wrapper_restore — Restores a previously unregistered built-in wrapper

Description

stream_wrapper_restore ( string $protocol ) : bool

Restores a built-in wrapper previously unregistered with stream_wrapper_unregister().

Parameters

protocol

Return Values

Returns TRUE on success or FALSE on failure.


Unregister a URL wrapper

  • « stream_wrapper_restore
  • Swoole »
  • PHP Manual
  • Stream Functions
  • Unregister a URL wrapper

stream_wrapper_unregister

(PHP 5 >= 5.1.0, PHP 7)

stream_wrapper_unregister — Unregister a URL wrapper

Description

stream_wrapper_unregister ( string $protocol ) : bool

Allows you to disable an already defined stream wrapper. Once the wrapper has been disabled you may override it with a user-defined wrapper using stream_wrapper_register() or reenable it later on with stream_wrapper_restore().

Parameters

protocol

Return Values

Returns TRUE on success or FALSE on failure.


Swoole

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Swoole Functions
    • swoole_async_dns_lookup — Async and non-blocking hostname to IP lookup
    • swoole_async_read — Read file stream asynchronously
    • swoole_async_readfile — Read a file asynchronously
    • swoole_async_set — Update the async I/O options
    • swoole_async_write — Write data to a file stream asynchronously
    • swoole_async_writefile — Write data to a file asynchronously
    • swoole_client_select — Get the file description which are ready to read/write or error
    • swoole_cpu_num — Get the number of CPU
    • swoole_errno — Get the error code of the latest system call
    • swoole_event_add — Add new callback functions of a socket into the EventLoop
    • swoole_event_defer — Add callback function to the next event loop
    • swoole_event_del — Remove all event callback functions of a socket
    • swoole_event_exit — Exit the eventloop, only available at the client side
    • swoole_event_set — Update the event callback functions of a socket
    • swoole_event_wait — Start the event loop
    • swoole_event_write — Write data to a socket
    • swoole_get_local_ip — Get the IPv4 IP addresses of each NIC on the machine
    • swoole_last_error — Get the lastest error message
    • swoole_load_module — Load a swoole extension
    • swoole_select — Select the file descriptions which are ready to read/write or error in the eventloop
    • swoole_set_process_name — Set the process name
    • swoole_strerror — Convert the Errno into error messages
    • swoole_timer_after — Trigger a one time callback function in the future
    • swoole_timer_exists — Check if a timer callback function is existed
    • swoole_timer_tick — Trigger a timer tick callback function by time interval
    • swoole_version — Get the version of Swoole
  • Swoole\Async — The Swoole\Async class
    • Swoole\Async::dnsLookup — Async and non-blocking hostname to IP lookup.
    • Swoole\Async::read — Read file stream asynchronously.
    • Swoole\Async::readFile — Read a file asynchronously.
    • Swoole\Async::set — Update the async I/O options.
    • Swoole\Async::write — Write data to a file stream asynchronously.
    • Swoole\Async::writeFile — Description
  • Swoole\Atomic — The Swoole\Atomic class
    • Swoole\Atomic::add — Add a number to the value to the atomic object.
    • Swoole\Atomic::cmpset — Compare and set the value of the atomic object.
    • Swoole\Atomic::__construct — Construct a swoole atomic object.
    • Swoole\Atomic::get — Get the current value of the atomic object.
    • Swoole\Atomic::set — Set a new value to the atomic object.
    • Swoole\Atomic::sub — Subtract a number to the value of the atomic object.
  • Swoole\Buffer — The Swoole\Buffer class
    • Swoole\Buffer::append — Append the string or binary data at the end of the memory buffer and return the new size of memory allocated.
    • Swoole\Buffer::clear — Reset the memory buffer.
    • Swoole\Buffer::__construct — Fixed size memory blocks allocation.
    • Swoole\Buffer::__destruct — Destruct the Swoole memory buffer.
    • Swoole\Buffer::expand — Expand the size of memory buffer.
    • Swoole\Buffer::read — Read data from the memory buffer based on offset and length.
    • Swoole\Buffer::recycle — Release the memory to OS which is not used by the memory buffer.
    • Swoole\Buffer::substr — Read data from the memory buffer based on offset and length. Or remove data from the memory buffer.
    • Swoole\Buffer::__toString — Get the string value of the memory buffer.
    • Swoole\Buffer::write — Write data to the memory buffer. The memory allocated for the buffer will not be changed.
  • Swoole\Channel — The Swoole\Channel class
    • Swoole\Channel::__construct — Construct a Swoole Channel
    • Swoole\Channel::__destruct — Destruct a Swoole channel.
    • Swoole\Channel::pop — Read and pop data from swoole channel.
    • Swoole\Channel::push — Write and push data into Swoole channel.
    • Swoole\Channel::stats — Get stats of swoole channel.
  • Swoole\Client — The Swoole\Client class
    • Swoole\Client::close — Close the connection established.
    • Swoole\Client::connect — Connect to the remote TCP or UDP port.
    • Swoole\Client::__construct — Create Swoole sync or async TCP/UDP client, with or without SSL.
    • Swoole\Client::__destruct — Destruct the Swoole client.
    • Swoole\Client::getpeername — Get the remote socket name of the connection.
    • Swoole\Client::getsockname — Get the local socket name of the connection.
    • Swoole\Client::isConnected — Check if the connection is established.
    • Swoole\Client::on — Add callback functions triggered by events.
    • Swoole\Client::pause — Pause receiving data.
    • Swoole\Client::pipe — Redirect the data to another file descriptor.
    • Swoole\Client::recv — Receive data from the remote socket.
    • Swoole\Client::resume — Resume receiving data.
    • Swoole\Client::send — Send data to the remote TCP socket.
    • Swoole\Client::sendfile — Send file to the remote TCP socket.
    • Swoole\Client::sendto — Send data to the remote UDP address.
    • Swoole\Client::set — Set the Swoole client parameters before the connection is established.
    • Swoole\Client::sleep — Remove the TCP client from system event loop.
    • Swoole\Client::wakeup — Add the TCP client back into the system event loop.
  • Swoole\Connection\Iterator — The Swoole\Connection\Iterator class
    • Swoole\Connection\Iterator::count — Count connections.
    • Swoole\Connection\Iterator::current — Return current connection entry.
    • Swoole\Connection\Iterator::key — Return key of the current connection.
    • Swoole\Connection\Iterator::next — Move to the next connection.
    • Swoole\Connection\Iterator::offsetExists — Check if offet exists.
    • Swoole\Connection\Iterator::offsetGet — Offset to retrieve.
    • Swoole\Connection\Iterator::offsetSet — Assign a Connection to the specified offset.
    • Swoole\Connection\Iterator::offsetUnset — Unset an offset.
    • Swoole\Connection\Iterator::rewind — Rewinds iterator
    • Swoole\Connection\Iterator::valid — Check if current position is valid.
  • Swoole\Coroutine — The Swoole\Coroutine class
    • Swoole\Coroutine::call_user_func_array — Call a callback with an array of parameters
    • Swoole\Coroutine::call_user_func — Call a callback given by the first parameter
    • Swoole\Coroutine::cli_wait — Description
    • Swoole\Coroutine::create — Description
    • Swoole\Coroutine\Client::close — Description
    • Swoole\Coroutine\Client::connect — Description
    • Swoole\Coroutine\Client::__construct — Description
    • Swoole\Coroutine\Client::__destruct — Description
    • Swoole\Coroutine\Client::getpeername — Description
    • Swoole\Coroutine\Client::getsockname — Description
    • Swoole\Coroutine\Client::isConnected — Description
    • Swoole\Coroutine\Client::recv — Description
    • Swoole\Coroutine\Client::send — Description
    • Swoole\Coroutine\Client::sendfile — Description
    • Swoole\Coroutine\Client::sendto — Description
    • Swoole\Coroutine\Client::set — Description
    • Swoole\Coroutine\Http\Client::addFile — Description
    • Swoole\Coroutine\Http\Client::close — Description
    • Swoole\Coroutine\Http\Client::__construct — Description
    • Swoole\Coroutine\Http\Client::__destruct — Description
    • Swoole\Coroutine\Http\Client::execute — Description
    • Swoole\Coroutine\Http\Client::get — Description
    • Swoole\Coroutine\Http\Client::getDefer — Description
    • Swoole\Coroutine\Http\Client::isConnected — Description
    • Swoole\Coroutine\Http\Client::post — Description
    • Swoole\Coroutine\Http\Client::recv — Description
    • Swoole\Coroutine\Http\Client::set — Description
    • Swoole\Coroutine\Http\Client::setCookies — Description
    • Swoole\Coroutine\Http\Client::setData — Description
    • Swoole\Coroutine\Http\Client::setDefer — Description
    • Swoole\Coroutine\Http\Client::setHeaders — Description
    • Swoole\Coroutine\Http\Client::setMethod — Description
    • Swoole\Coroutine\MySQL::close — Description
    • Swoole\Coroutine\MySQL::connect — Description
    • Swoole\Coroutine\MySQL::__construct — Description
    • Swoole\Coroutine\MySQL::__destruct — Description
    • Swoole\Coroutine\MySQL::getDefer — Description
    • Swoole\Coroutine\MySQL::query — Description
    • Swoole\Coroutine\MySQL::recv — Description
    • Swoole\Coroutine\MySQL::setDefer — Description
    • Swoole\Coroutine::getuid — Description
    • Swoole\Coroutine::resume — Description
    • Swoole\Coroutine::suspend — Description
  • Swoole\Event — The Swoole\Event class
    • Swoole\Event::add — Add new callback functions of a socket into the EventLoop.
    • Swoole\Event::defer — Add a callback function to the next event loop.
    • Swoole\Event::del — Remove all event callback functions of a socket.
    • Swoole\Event::exit — Exit the eventloop, only available at client side.
    • Swoole\Event::set — Update the event callback functions of a socket.
    • Swoole\Event::wait — Description
    • Swoole\Event::write — Write data to the socket.
  • Swoole\Exception — The Swoole\Exception class
  • Swoole\Http\Client — The Swoole\Http\Client class
    • Swoole\Http\Client::addFile — Add a file to the post form.
    • Swoole\Http\Client::close — Close the http connection.
    • Swoole\Http\Client::__construct — Construct the async HTTP client.
    • Swoole\Http\Client::__destruct — Destruct the HTTP client.
    • Swoole\Http\Client::download — Download a file from the remote server.
    • Swoole\Http\Client::execute — Send the HTTP request after setting the parameters.
    • Swoole\Http\Client::get — Send GET http request to the remote server.
    • Swoole\Http\Client::isConnected — Check if the HTTP connection is connected.
    • Swoole\Http\Client::on — Register callback function by event name.
    • Swoole\Http\Client::post — Send POST http request to the remote server.
    • Swoole\Http\Client::push — Push data to websocket client.
    • Swoole\Http\Client::set — Update the HTTP client paramters.
    • Swoole\Http\Client::setCookies — Set the http request cookies.
    • Swoole\Http\Client::setData — Set the HTTP request body data.
    • Swoole\Http\Client::setHeaders — Set the HTTP request headers.
    • Swoole\Http\Client::setMethod — Set the HTTP request method.
    • Swoole\Http\Client::upgrade — Upgrade to websocket protocol.
  • Swoole\Http\Request — The Swoole\Http\Request class
    • Swoole\Http\Request::__destruct — Destruct the HTTP request.
    • Swoole\Http\Request::rawcontent — Get the raw HTTP POST body.
  • Swoole\Http\Response — The Swoole\Http\Response class
    • Swoole\Http\Response::cookie — Set the cookies of the HTTP response.
    • Swoole\Http\Response::__destruct — Destruct the HTTP response.
    • Swoole\Http\Response::end — Send data for the HTTP request and finish the response.
    • Swoole\Http\Response::gzip — Enable the gzip of response content.
    • Swoole\Http\Response::header — Set the HTTP response headers.
    • Swoole\Http\Response::initHeader — Init the HTTP response header.
    • Swoole\Http\Response::rawcookie — Set the raw cookies to the HTTP response.
    • Swoole\Http\Response::sendfile — Send file through the HTTP response.
    • Swoole\Http\Response::status — Set the status code of the HTTP response.
    • Swoole\Http\Response::write — Append HTTP body content to the HTTP response.
  • Swoole\Http\Server — The Swoole\Http\Server class
    • Swoole\Http\Server::on — Bind callback function to HTTP server by event name.
    • Swoole\Http\Server::start — Start the swoole http server.
  • Swoole\Lock — The Swoole\Lock class
    • Swoole\Lock::__construct — Construct a memory lock.
    • Swoole\Lock::__destruct — Destory a Swoole memory lock.
    • Swoole\Lock::lock_read — Lock a read-write lock for reading.
    • Swoole\Lock::lock — Try to acquire the lock. It will block if the lock is not available.
    • Swoole\Lock::trylock_read — Try to lock a read-write lock for reading and return straight away even the lock is not available.
    • Swoole\Lock::trylock — Try to acquire the lock and return straight away even the lock is not available.
    • Swoole\Lock::unlock — Release the lock.
  • Swoole\Mmap — The Swoole\Mmap class
    • Swoole\Mmap::open — Map a file into memory and return the stream resource which can be used by PHP stream operations.
  • Swoole\MySQL — The Swoole\MySQL class
    • Swoole\MySQL::close — Close the async MySQL connection.
    • Swoole\MySQL::connect — Connect to the remote MySQL server.
    • Swoole\MySQL::__construct — Construct an async MySQL client.
    • Swoole\MySQL::__destruct — Destory the async MySQL client.
    • Swoole\MySQL::getBuffer — Description
    • Swoole\MySQL::on — Register callback function based on event name.
    • Swoole\MySQL::query — Run the SQL query.
  • Swoole\MySQL\Exception — The Swoole\MySQL\Exception class
  • Swoole\Process — The Swoole\Process class
    • Swoole\Process::alarm — High precision timer which triggers signal with fixed interval.
    • Swoole\Process::close — Close the pipe to the child process.
    • Swoole\Process::__construct — Construct a process.
    • Swoole\Process::daemon — Change the process to be a daemon process.
    • Swoole\Process::__destruct — Destory the process.
    • Swoole\Process::exec — Execute system commands.
    • Swoole\Process::exit — Stop the child processes.
    • Swoole\Process::freeQueue — Destroy the message queue created by swoole_process::useQueue.
    • Swoole\Process::kill — Send signal to the child process.
    • Swoole\Process::name — Set name of the process.
    • Swoole\Process::pop — Read and pop data from the message queue.
    • Swoole\Process::push — Write and push data into the message queue.
    • Swoole\Process::read — Read data sending to the process.
    • Swoole\Process::signal — Send signal to the child processes.
    • Swoole\Process::start — Start the process.
    • Swoole\Process::statQueue — Get the stats of the message queue used as the communication method between processes.
    • Swoole\Process::useQueue — Create a message queue as the communication method between the parent process and child processes.
    • Swoole\Process::wait — Wait for the events of child processes.
    • Swoole\Process::write — Write data into the pipe and communicate with the parent process or child processes.
  • Swoole\Redis\Server — The Swoole\Redis\Server class
    • Swoole\Redis\Server::format — Description
    • Swoole\Redis\Server::setHandler — Description
    • Swoole\Redis\Server::start — Description
  • Swoole\Serialize — The Swoole\Serialize class
    • Swoole\Serialize::pack — Serialize the data.
    • Swoole\Serialize::unpack — Unserialize the data.
  • Swoole\Server — The Swoole\Server class
    • Swoole\Server::addlistener — Add a new listener to the server.
    • Swoole\Server::addProcess — Add a user defined swoole_process to the server.
    • Swoole\Server::after — Trigger a callback function after a period of time.
    • Swoole\Server::bind — Bind the connection to a user defined user ID.
    • Swoole\Server::clearTimer — Stop and destory a timer.
    • Swoole\Server::close — Close a connection to the client.
    • Swoole\Server::confirm — Check status of the connection.
    • Swoole\Server::connection_info — Get the connection info by file description.
    • Swoole\Server::connection_list — Get all of the established connections.
    • Swoole\Server::__construct — Construct a Swoole server.
    • Swoole\Server::defer — Delay execution of the callback function at the end of current EventLoop.
    • Swoole\Server\Port::__construct — Construct a server port
    • Swoole\Server\Port::__destruct — Destory server port
    • Swoole\Server\Port::on — Register callback functions by event.
    • Swoole\Server\Port::set — Set protocol of the server port.
    • Swoole\Server::exist — Check if the connection is existed.
    • Swoole\Server::finish — Used in task process for sending result to the worker process when the task is finished.
    • Swoole\Server::getClientInfo — Get the connection info by file description.
    • Swoole\Server::getClientList — Get all of the established connections.
    • Swoole\Server::getLastError — Get the error code of the most recent error.
    • Swoole\Server::heartbeat — Check all the connections on the server.
    • Swoole\Server::listen — Listen on the given IP and port, socket type.
    • Swoole\Server::on — Register a callback function by event name.
    • Swoole\Server::pause — Stop receiving data from the connection.
    • Swoole\Server::protect — Set the connection to be protected mode.
    • Swoole\Server::reload — Restart all the worker process.
    • Swoole\Server::resume — Start receving data from the connection.
    • Swoole\Server::send — Send data to the client.
    • Swoole\Server::sendfile — Send file to the connection.
    • Swoole\Server::sendMessage — Send message to worker processes by ID.
    • Swoole\Server::sendto — Send data to the remote UDP address.
    • Swoole\Server::sendwait — Send data to the remote socket in the blocking way.
    • Swoole\Server::set — Set the runtime settings of the swoole server.
    • Swoole\Server::shutdown — Shutdown the master server process, this function can be called in worker processes.
    • Swoole\Server::start — Start the Swoole server.
    • Swoole\Server::stats — Get the stats of the Swoole server.
    • Swoole\Server::stop — Stop the Swoole server.
    • Swoole\Server::task — Send data to the task worker processes.
    • Swoole\Server::taskwait — Send data to the task worker processes in blocking way.
    • Swoole\Server::taskWaitMulti — Execute multiple tasks concurrently.
    • Swoole\Server::tick — Repeats a given function at every given time-interval.
  • Swoole\Table — The Swoole\Table class
    • Swoole\Table::column — Set the data type and size of the columns.
    • Swoole\Table::__construct — Construct a Swoole memory table with fixed size.
    • Swoole\Table::count — Count the rows in the table, or count all the elements in the table if $mode = 1.
    • Swoole\Table::create — Create the swoole memory table.
    • Swoole\Table::current — Get the current row.
    • Swoole\Table::decr — Decrement the value in the Swoole table by $row_key and $column_key.
    • Swoole\Table::del — Delete a row in the Swoole table by $row_key.
    • Swoole\Table::destroy — Destroy the Swoole table.
    • Swoole\Table::exist — Check if a row is existed by $row_key.
    • Swoole\Table::get — Get the value in the Swoole table by $row_key and $column_key.
    • Swoole\Table::incr — Increment the value by $row_key and $column_key.
    • Swoole\Table::key — Get the key of current row.
    • Swoole\Table::next — Iterator the next row.
    • Swoole\Table::rewind — Rewind the iterator.
    • Swoole\Table::set — Update a row of the table by $row_key.
    • Swoole\Table::valid — Check current if the current row is valid.
  • Swoole\Timer — The Swoole\Timer class
    • Swoole\Timer::after — Trigger a callback function after a period of time.
    • Swoole\Timer::clear — Delete a timer by timer ID.
    • Swoole\Timer::exists — Check if a timer is existed.
    • Swoole\Timer::tick — Repeats a given function at every given time-interval.
  • Swoole\WebSocket\Frame — The Swoole\WebSocket\Frame class
  • Swoole\WebSocket\Server — The Swoole\WebSocket\Server class
    • Swoole\WebSocket\Server::exist — Check if the file descriptor exists.
    • Swoole\WebSocket\Server::on — Register event callback function
    • Swoole\WebSocket\Server::pack — Get a pack of binary data to send in a single frame.
    • Swoole\WebSocket\Server::push — Push data to the remote client.
    • Swoole\WebSocket\Server::unpack — Unpack the binary data received from the client.


Introduction

Swoole is a high-performance networking framework using an event-driven, asynchronous, non-blocking I/O model. It can be used to develop high-performance, scalable, concurrent TCP, UDP, Unix socket, HTTP, Websocket services. To get started, please check the » Swoole Docs.

Note: This extension is not available on Windows platforms.


Installation

Use --with-swoole[=DIR] when compiling 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/swoole


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Swoole Configure Options
Name | Default | Changeable | Changelog
swoole.aio_thread_num | 2 | PHP_INI_ALL |
swoole.display_errors | On | PHP_INI_ALL |
swoole.fast_serialize | Off | PHP_INI_ALL |
swoole.unixsock_buffer_size | 8388608 | PHP_INI_ALL |
swoole.use_namespace | On | PHP_INI_SYSTEM |

Here's a short explanation of the configuration directives.

swoole.aio_thread_num integer

POSIX asynchronous I/O thread number

swoole.display_errors string

This determines whether Swoole errors should be printed to the screen.

swoole.fast_serialize string

Whether to enable Swoole fast_serialize.

swoole.unixsock_buffer_size integer

Buffer size of Unix socket.

swoole.use_namespace string

Whether to use PHP namespaces


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.

SWOOLE_BASE (integer)
SWOOLE_THREAD (integer)
SWOOLE_PROCESS (integer)
SWOOLE_IPC_UNSOCK (integer)
SWOOLE_IPC_MSGQUEUE (integer)
SWOOLE_IPC_PREEMPTIVE (integer)
SWOOLE_SOCK_TCP (integer)
SWOOLE_SOCK_TCP6 (integer)
SWOOLE_SOCK_UDP (integer)
SWOOLE_SOCK_UDP6 (integer)
SWOOLE_SOCK_UNIX_DGRAM (integer)
SWOOLE_SOCK_UNIX_STREAM (integer)
SWOOLE_TCP (integer)
SWOOLE_TCP6 (integer)
SWOOLE_UDP (integer)
SWOOLE_UDP6 (integer)
SWOOLE_UNIX_DGRAM (integer)
SWOOLE_UNIX_STREAM (integer)
SWOOLE_SOCK_SYNC (integer)
SWOOLE_SOCK_ASYNC (integer)
SWOOLE_SYNC (integer)
SWOOLE_ASYNC (integer)
SWOOLE_KEEP (integer)
SWOOLE_EVENT_READ (integer)
SWOOLE_EVENT_WRITE (integer)
SWOOLE_VERSION (string)
SWOOLE_AIO_BASE (integer)
SWOOLE_AIO_LINUX (integer)
SWOOLE_FILELOCK (integer)
SWOOLE_MUTEX (integer)
SWOOLE_SEM (integer)
SWOOLE_RWLOCK (integer)
WEBSOCKET_OPCODE_TEXT (integer)
WEBSOCKET_OPCODE_BINARY (integer)
WEBSOCKET_OPCODE_PING (integer)
WEBSOCKET_STATUS_CONNECTION (integer)
WEBSOCKET_STATUS_HANDSHAKE (integer)
WEBSOCKET_STATUS_FRAME (integer)
WEBSOCKET_STATUS_ACTIVE (integer)
SWOOLE_FAST_PACK (integer)


Swoole Functions

Table of Contents

  • swoole_async_dns_lookup — Async and non-blocking hostname to IP lookup
  • swoole_async_read — Read file stream asynchronously
  • swoole_async_readfile — Read a file asynchronously
  • swoole_async_set — Update the async I/O options
  • swoole_async_write — Write data to a file stream asynchronously
  • swoole_async_writefile — Write data to a file asynchronously
  • swoole_client_select — Get the file description which are ready to read/write or error
  • swoole_cpu_num — Get the number of CPU
  • swoole_errno — Get the error code of the latest system call
  • swoole_event_add — Add new callback functions of a socket into the EventLoop
  • swoole_event_defer — Add callback function to the next event loop
  • swoole_event_del — Remove all event callback functions of a socket
  • swoole_event_exit — Exit the eventloop, only available at the client side
  • swoole_event_set — Update the event callback functions of a socket
  • swoole_event_wait — Start the event loop
  • swoole_event_write — Write data to a socket
  • swoole_get_local_ip — Get the IPv4 IP addresses of each NIC on the machine
  • swoole_last_error — Get the lastest error message
  • swoole_load_module — Load a swoole extension
  • swoole_select — Select the file descriptions which are ready to read/write or error in the eventloop
  • swoole_set_process_name — Set the process name
  • swoole_strerror — Convert the Errno into error messages
  • swoole_timer_after — Trigger a one time callback function in the future
  • swoole_timer_exists — Check if a timer callback function is existed
  • swoole_timer_tick — Trigger a timer tick callback function by time interval
  • swoole_version — Get the version of Swoole


Async and non-blocking hostname to IP lookup

  • « Swoole Functions
  • swoole_async_read »
  • PHP Manual
  • Swoole Functions
  • Async and non-blocking hostname to IP lookup

swoole_async_dns_lookup

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

swoole_async_dns_lookup — Async and non-blocking hostname to IP lookup

Description

swoole_async_dns_lookup ( string $hostname , callable $callback ) : bool

Parameters

hostname

The host name.

callback
callback ( string $hostname , string $ip ) : mixed
hostname

The host name.

IP

The IP address.

Return Values

Returns TRUE on success or FALSE on failure.


Read file stream asynchronously

  • « swoole_async_dns_lookup
  • swoole_async_readfile »
  • PHP Manual
  • Swoole Functions
  • Read file stream asynchronously

swoole_async_read

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

swoole_async_read — Read file stream asynchronously

Description

swoole_async_read ( string $filename , callable $callback [, int $chunk_size = 65536 [, int $offset = 0 ]] ) : bool

Parameters

filename

The filename of the file being read.

callback
callback ( string $filename , string $content ) : mixed
filename

The name of the file.

content

The content readed from the file stream.

chunk_size

The chunk length.

offset

The offset.

Return Values

Whether the read is succeed.


Read a file asynchronously

  • « swoole_async_read
  • swoole_async_set »
  • PHP Manual
  • Swoole Functions
  • Read a file asynchronously

swoole_async_readfile

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

swoole_async_readfile — Read a file asynchronously

Description

swoole_async_readfile ( string $filename , callable $callback ) : bool

Parameters

filename

The filename of the file being read.

callback
callback ( string $filename , string $content ) : mixed
filename

The name of the file.

content

The content readed from the file.

Return Values

Returns TRUE on success or FALSE on failure.


Update the async I/O options

  • « swoole_async_readfile
  • swoole_async_write »
  • PHP Manual
  • Swoole Functions
  • Update the async I/O options

swoole_async_set

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

swoole_async_set — Update the async I/O options

Description

swoole_async_set ( array $settings ) : void

Parameters

settings


Write data to a file stream asynchronously

  • « swoole_async_set
  • swoole_async_writefile »
  • PHP Manual
  • Swoole Functions
  • Write data to a file stream asynchronously

swoole_async_write

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

swoole_async_write — Write data to a file stream asynchronously

Description

swoole_async_write ( string $filename , string $content [, integer $offset [, callable $callback ]] ) : bool

Parameters

filename

The filename being written.

content

The content writing to the file.

offset

The offset.

callback

Return Values

Returns TRUE on success or FALSE on failure.


Write data to a file asynchronously

  • « swoole_async_write
  • swoole_client_select »
  • PHP Manual
  • Swoole Functions
  • Write data to a file asynchronously

swoole_async_writefile

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

swoole_async_writefile — Write data to a file asynchronously

Description

swoole_async_writefile ( string $filename , string $content [, callable $callback [, int $flags = 0 ]] ) : bool

Parameters

filename

The filename being written.

content

The content writing to the file.

callback

flags

Return Values

Returns TRUE on success or FALSE on failure.


Get the file description which are ready to read/write or error

  • « swoole_async_writefile
  • swoole_cpu_num »
  • PHP Manual
  • Swoole Functions
  • Get the file description which are ready to read/write or error

swoole_client_select

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

swoole_client_select — Get the file description which are ready to read/write or error

Description

swoole_client_select ( array &$read_array , array &$write_array , array &$error_array [, float $timeout = 0.5 ] ) : int

Parameters

read_array

write_array

error_array

timeout

Return Values


Get the number of CPU

  • « swoole_client_select
  • swoole_errno »
  • PHP Manual
  • Swoole Functions
  • Get the number of CPU

swoole_cpu_num

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

swoole_cpu_num — Get the number of CPU

Description

swoole_cpu_num ( void ) : int

Parameters

This function has no parameters.

Return Values

The number of CPU.


Get the error code of the latest system call

  • « swoole_cpu_num
  • swoole_event_add »
  • PHP Manual
  • Swoole Functions
  • Get the error code of the latest system call

swoole_errno

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

swoole_errno — Get the error code of the latest system call

Description

swoole_errno ( void ) : int

Parameters

This function has no parameters.

Return Values


Add new callback functions of a socket into the EventLoop

  • « swoole_errno
  • swoole_event_defer »
  • PHP Manual
  • Swoole Functions
  • Add new callback functions of a socket into the EventLoop

swoole_event_add

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

swoole_event_add — Add new callback functions of a socket into the EventLoop

Description

swoole_event_add ( int $fd [, callable $read_callback [, callable $write_callback [, int $events = 0 ]]] ) : int

Parameters

fd

read_callback

write_callback

events

Return Values


Add callback function to the next event loop

  • « swoole_event_add
  • swoole_event_del »
  • PHP Manual
  • Swoole Functions
  • Add callback function to the next event loop

swoole_event_defer

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

swoole_event_defer — Add callback function to the next event loop

Description

swoole_event_defer ( callable $callback ) : bool

Parameters

callback

Return Values

Returns TRUE on success or FALSE on failure.


Remove all event callback functions of a socket

  • « swoole_event_defer
  • swoole_event_exit »
  • PHP Manual
  • Swoole Functions
  • Remove all event callback functions of a socket

swoole_event_del

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

swoole_event_del — Remove all event callback functions of a socket

Description

swoole_event_del ( int $fd ) : bool

Parameters

fd

Return Values

Returns TRUE on success or FALSE on failure.


Exit the eventloop, only available at the client side

  • « swoole_event_del
  • swoole_event_set »
  • PHP Manual
  • Swoole Functions
  • Exit the eventloop, only available at the client side

swoole_event_exit

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

swoole_event_exit — Exit the eventloop, only available at the client side

Description

swoole_event_exit ( void ) : void

Parameters

This function has no parameters.

Return Values


Update the event callback functions of a socket

  • « swoole_event_exit
  • swoole_event_wait »
  • PHP Manual
  • Swoole Functions
  • Update the event callback functions of a socket

swoole_event_set

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

swoole_event_set — Update the event callback functions of a socket

Description

swoole_event_set ( int $fd [, callable $read_callback [, callable $write_callback [, int $events = 0 ]]] ) : bool

Parameters

fd

read_callback

write_callback

events

Return Values


Start the event loop

  • « swoole_event_set
  • swoole_event_write »
  • PHP Manual
  • Swoole Functions
  • Start the event loop

swoole_event_wait

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

swoole_event_wait — Start the event loop

Description

swoole_event_wait ( void ) : void

Parameters

This function has no parameters.

Return Values


Write data to a socket

  • « swoole_event_wait
  • swoole_get_local_ip »
  • PHP Manual
  • Swoole Functions
  • Write data to a socket

swoole_event_write

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

swoole_event_write — Write data to a socket

Description

swoole_event_write ( int $fd , string $data ) : bool

Parameters

fd

data

Return Values

Returns TRUE on success or FALSE on failure.


Get the IPv4 IP addresses of each NIC on the machine

  • « swoole_event_write
  • swoole_last_error »
  • PHP Manual
  • Swoole Functions
  • Get the IPv4 IP addresses of each NIC on the machine

swoole_get_local_ip

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

swoole_get_local_ip — Get the IPv4 IP addresses of each NIC on the machine

Description

swoole_get_local_ip ( void ) : array

Parameters

This function has no parameters.

Return Values


Get the lastest error message

  • « swoole_get_local_ip
  • swoole_load_module »
  • PHP Manual
  • Swoole Functions
  • Get the lastest error message

swoole_last_error

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

swoole_last_error — Get the lastest error message

Description

swoole_last_error ( void ) : int

Parameters

This function has no parameters.

Return Values


Load a swoole extension

  • « swoole_last_error
  • swoole_select »
  • PHP Manual
  • Swoole Functions
  • Load a swoole extension

swoole_load_module

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

swoole_load_module — Load a swoole extension

Description

swoole_load_module ( string $filename ) : mixed

Parameters

This function has no parameters.

Return Values


Select the file descriptions which are ready to read/write or error in the eventloop

  • « swoole_load_module
  • swoole_set_process_name »
  • PHP Manual
  • Swoole Functions
  • Select the file descriptions which are ready to read/write or error in the eventloop

swoole_select

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

swoole_select — Select the file descriptions which are ready to read/write or error in the eventloop

Description

swoole_select ( array &$read_array , array &$write_array , array &$error_array [, float $timeout ] ) : int

Parameters

read_array

write_array

error_array

timeout

Return Values


Set the process name

  • « swoole_select
  • swoole_strerror »
  • PHP Manual
  • Swoole Functions
  • Set the process name

swoole_set_process_name

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

swoole_set_process_name — Set the process name

Description

swoole_set_process_name ( string $process_name [, int $size = 128 ] ) : void

Parameters

process_name

Return Values


Convert the Errno into error messages

  • « swoole_set_process_name
  • swoole_timer_after »
  • PHP Manual
  • Swoole Functions
  • Convert the Errno into error messages

swoole_strerror

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

swoole_strerror — Convert the Errno into error messages

Description

swoole_strerror ( int $errno [, int $error_type = 0 ] ) : string

Parameters

errno

Return Values


Trigger a one time callback function in the future

  • « swoole_strerror
  • swoole_timer_exists »
  • PHP Manual
  • Swoole Functions
  • Trigger a one time callback function in the future

swoole_timer_after

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

swoole_timer_after — Trigger a one time callback function in the future

Description

swoole_timer_after ( int $ms , callable $callback [, mixed $param ] ) : int

Parameters

ms

callback

param

Return Values


Check if a timer callback function is existed

  • « swoole_timer_after
  • swoole_timer_tick »
  • PHP Manual
  • Swoole Functions
  • Check if a timer callback function is existed

swoole_timer_exists

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

swoole_timer_exists — Check if a timer callback function is existed

Description

swoole_timer_exists ( int $timer_id ) : bool

Parameters

timer_id

Return Values


Trigger a timer tick callback function by time interval

  • « swoole_timer_exists
  • swoole_version »
  • PHP Manual
  • Swoole Functions
  • Trigger a timer tick callback function by time interval

swoole_timer_tick

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

swoole_timer_tick — Trigger a timer tick callback function by time interval

Description

swoole_timer_tick ( int $ms , callable $callback [, mixed $param ] ) : int

Parameters

ms

callback

Return Values


Get the version of Swoole

  • « swoole_timer_tick
  • Swoole\Async »
  • PHP Manual
  • Swoole Functions
  • Get the version of Swoole

swoole_version

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

swoole_version — Get the version of Swoole

Description

swoole_version ( void ) : string

Parameters

This function has no parameters.

Return Values

The version of Swoole.


The Swoole\Async class

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Introduction

Class synopsis

Swoole\Async {
/* Methods */
public static dnsLookup ( string $hostname , callable $callback ) : void
public static read ( string $filename , callable $callback [, integer $chunk_size [, integer $offset ]] ) : bool
public static readFile ( string $filename , callable $callback ) : void
public static set ( array $settings ) : void
public static write ( string $filename , string $content [, integer $offset [, callable $callback ]] ) : void
public static writeFile ( string $filename , string $content [, callable $callback [, string $flags ]] ) : void
}

Table of Contents

  • Swoole\Async::dnsLookup — Async and non-blocking hostname to IP lookup.
  • Swoole\Async::read — Read file stream asynchronously.
  • Swoole\Async::readFile — Read a file asynchronously.
  • Swoole\Async::set — Update the async I/O options.
  • Swoole\Async::write — Write data to a file stream asynchronously.
  • Swoole\Async::writeFile — Description


Async and non-blocking hostname to IP lookup.

  • « Swoole\Async
  • Swoole\Async::read »
  • PHP Manual
  • Swoole\Async
  • Async and non-blocking hostname to IP lookup.

Swoole\Async::dnsLookup

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Async::dnsLookup — Async and non-blocking hostname to IP lookup.

Description

public static Swoole\Async::dnsLookup ( string $hostname , callable $callback ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

hostname

The host name.

callback
callback ( string $hostname , string $ip ) : mixed
hostname

The host name.

IP

The IP address.


Read file stream asynchronously.

  • « Swoole\Async::dnsLookup
  • Swoole\Async::readFile »
  • PHP Manual
  • Swoole\Async
  • Read file stream asynchronously.

Swoole\Async::read

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Async::read — Read file stream asynchronously.

Description

public static Swoole\Async::read ( string $filename , callable $callback [, integer $chunk_size [, integer $offset ]] ) : bool

Parameters

filename

The name of the file.

callback
callback ( string $filename , string $content ) : mixed
filename

The name of the file.

content

The content readed from the file stream.

chunk_size

The chunk length.

offset

The offset.

Return Values

Whether the read is succeed.


Read a file asynchronously.

  • « Swoole\Async::read
  • Swoole\Async::set »
  • PHP Manual
  • Swoole\Async
  • Read a file asynchronously.

Swoole\Async::readFile

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Async::readFile — Read a file asynchronously.

Description

public static Swoole\Async::readFile ( string $filename , callable $callback ) : void

Parameters

filename

The filename of the file being read.

callback
callback ( string $filename , string $content ) : mixed
filename

The name of the file.

content

The content readed from the file.


Update the async I/O options.

  • « Swoole\Async::readFile
  • Swoole\Async::write »
  • PHP Manual
  • Swoole\Async
  • Update the async I/O options.

Swoole\Async::set

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Async::set — Update the async I/O options.

Description

public static Swoole\Async::set ( array $settings ) : void

Parameters

settings


Write data to a file stream asynchronously.

  • « Swoole\Async::set
  • Swoole\Async::writeFile »
  • PHP Manual
  • Swoole\Async
  • Write data to a file stream asynchronously.

Swoole\Async::write

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Async::write — Write data to a file stream asynchronously.

Description

public static Swoole\Async::write ( string $filename , string $content [, integer $offset [, callable $callback ]] ) : void

Parameters

filename

The filename being written.

content

The content writing to the file.

offset

The offset.

callback


Description

  • « Swoole\Async::write
  • Swoole\Atomic »
  • PHP Manual
  • Swoole\Async
  • Description

Swoole\Async::writeFile

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Async::writeFile — Description

Description

public static Swoole\Async::writeFile ( string $filename , string $content [, callable $callback [, string $flags ]] ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

filename

The filename being written.

content

The content writing to the file.

callback

flags


The Swoole\Atomic class

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Introduction

Class synopsis

Swoole\Atomic {
/* Methods */
public add ([ integer $add_value ] ) : integer
public cmpset ( integer $cmp_value , integer $new_value ) : integer
public get ( void ) : integer
public set ( integer $value ) : integer
public sub ([ integer $sub_value ] ) : integer
}

Table of Contents

  • Swoole\Atomic::add — Add a number to the value to the atomic object.
  • Swoole\Atomic::cmpset — Compare and set the value of the atomic object.
  • Swoole\Atomic::__construct — Construct a swoole atomic object.
  • Swoole\Atomic::get — Get the current value of the atomic object.
  • Swoole\Atomic::set — Set a new value to the atomic object.
  • Swoole\Atomic::sub — Subtract a number to the value of the atomic object.


Add a number to the value to the atomic object.

  • « Swoole\Atomic
  • Swoole\Atomic::cmpset »
  • PHP Manual
  • Swoole\Atomic
  • Add a number to the value to the atomic object.

Swoole\Atomic::add

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Atomic::add — Add a number to the value to the atomic object.

Description

public Swoole\Atomic::add ([ integer $add_value ] ) : integer

Add a number to the value to the atomic object.

Parameters

add_value

The value which will be added to the current value.

Return Values

The new value of the atomic object.


Compare and set the value of the atomic object.

  • « Swoole\Atomic::add
  • Swoole\Atomic::__construct »
  • PHP Manual
  • Swoole\Atomic
  • Compare and set the value of the atomic object.

Swoole\Atomic::cmpset

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Atomic::cmpset — Compare and set the value of the atomic object.

Description

public Swoole\Atomic::cmpset ( integer $cmp_value , integer $new_value ) : integer

Parameters

cmp_value

The value to compare with the current value of the atomic object.

new_value

The value to set to the atomic object if the cmp_value is the same as the current value of the atomic object.

Return Values

The new value of the atomic object.


Construct a swoole atomic object.

  • « Swoole\Atomic::cmpset
  • Swoole\Atomic::get »
  • PHP Manual
  • Swoole\Atomic
  • Construct a swoole atomic object.

Swoole\Atomic::__construct

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Atomic::__construct — Construct a swoole atomic object.

Description

public Swoole\Atomic::__construct ([ integer $value ] )

Swoole atomic object is a integer variable allows any processor to atomically test and modify. It is implemented based on CPU atomic instructions. The Swoole atomic variables have to defined before swoole_server->start.

Compare-and-swap (CAS) is an atomic instruction used in multithreading to achieve synchronization. It compares the content of a memory location with a given value and, only if they are the same, modifies the content of that memory location to a new given value.

Parameters

value

The value of the atomic object.


Get the current value of the atomic object.

  • « Swoole\Atomic::__construct
  • Swoole\Atomic::set »
  • PHP Manual
  • Swoole\Atomic
  • Get the current value of the atomic object.

Swoole\Atomic::get

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Atomic::get — Get the current value of the atomic object.

Description

public Swoole\Atomic::get ( void ) : integer

Get the current value of the atomic object.

Parameters

This function has no parameters.

Return Values

The current value of the atomic object.


Set a new value to the atomic object.

  • « Swoole\Atomic::get
  • Swoole\Atomic::sub »
  • PHP Manual
  • Swoole\Atomic
  • Set a new value to the atomic object.

Swoole\Atomic::set

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Atomic::set — Set a new value to the atomic object.

Description

public Swoole\Atomic::set ( integer $value ) : integer

Set a new value to the atomic object.

Warning

This function is currently not documented; only its argument list is available.

Parameters

value

The value to set to the atomic object.

Return Values

The current value of the atomic object.


Subtract a number to the value of the atomic object.

  • « Swoole\Atomic::set
  • Swoole\Buffer »
  • PHP Manual
  • Swoole\Atomic
  • Subtract a number to the value of the atomic object.

Swoole\Atomic::sub

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Atomic::sub — Subtract a number to the value of the atomic object.

Description

public Swoole\Atomic::sub ([ integer $sub_value ] ) : integer

Subtract a number to the value of the atomic object.

Parameters

sub_value

The value which will be subtracted to the current value.

Return Values

The current value of the atomic object.


The Swoole\Buffer class

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Introduction

Class synopsis

Swoole\Buffer {
/* Methods */
public append ( string $data ) : integer
public clear ( void ) : void
public __destruct ( void ) : void
public expand ( integer $size ) : integer
public read ( integer $offset , integer $length ) : string
public recycle ( void ) : void
public substr ( integer $offset [, integer $length [, bool $remove ]] ) : string
public __toString ( void ) : string
public write ( integer $offset , string $data ) : void
}

Table of Contents

  • Swoole\Buffer::append — Append the string or binary data at the end of the memory buffer and return the new size of memory allocated.
  • Swoole\Buffer::clear — Reset the memory buffer.
  • Swoole\Buffer::__construct — Fixed size memory blocks allocation.
  • Swoole\Buffer::__destruct — Destruct the Swoole memory buffer.
  • Swoole\Buffer::expand — Expand the size of memory buffer.
  • Swoole\Buffer::read — Read data from the memory buffer based on offset and length.
  • Swoole\Buffer::recycle — Release the memory to OS which is not used by the memory buffer.
  • Swoole\Buffer::substr — Read data from the memory buffer based on offset and length. Or remove data from the memory buffer.
  • Swoole\Buffer::__toString — Get the string value of the memory buffer.
  • Swoole\Buffer::write — Write data to the memory buffer. The memory allocated for the buffer will not be changed.


Append the string or binary data at the end of the memory buffer and return the new size of memory allocated.

  • « Swoole\Buffer
  • Swoole\Buffer::clear »
  • PHP Manual
  • Swoole\Buffer
  • Append the string or binary data at the end of the memory buffer and return the new size of memory allocated.

Swoole\Buffer::append

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Buffer::append — Append the string or binary data at the end of the memory buffer and return the new size of memory allocated.

Description

public Swoole\Buffer::append ( string $data ) : integer

Parameters

data

The string or binary data to append at the end of the memory buffer.

Return Values

The new size of the memory buffer.


Reset the memory buffer.

  • « Swoole\Buffer::append
  • Swoole\Buffer::__construct »
  • PHP Manual
  • Swoole\Buffer
  • Reset the memory buffer.

Swoole\Buffer::clear

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Buffer::clear — Reset the memory buffer.

Description

public Swoole\Buffer::clear ( void ) : void

Parameters

This function has no parameters.


Fixed size memory blocks allocation.

  • « Swoole\Buffer::clear
  • Swoole\Buffer::__destruct »
  • PHP Manual
  • Swoole\Buffer
  • Fixed size memory blocks allocation.

Swoole\Buffer::__construct

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Buffer::__construct — Fixed size memory blocks allocation.

Description

public Swoole\Buffer::__construct ([ integer $size ] )

Parameters

size

The size of the memory to allocate.


Destruct the Swoole memory buffer.

  • « Swoole\Buffer::__construct
  • Swoole\Buffer::expand »
  • PHP Manual
  • Swoole\Buffer
  • Destruct the Swoole memory buffer.

Swoole\Buffer::__destruct

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Buffer::__destruct — Destruct the Swoole memory buffer.

Description

public Swoole\Buffer::__destruct ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.


Expand the size of memory buffer.

  • « Swoole\Buffer::__destruct
  • Swoole\Buffer::read »
  • PHP Manual
  • Swoole\Buffer
  • Expand the size of memory buffer.

Swoole\Buffer::expand

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Buffer::expand — Expand the size of memory buffer.

Description

public Swoole\Buffer::expand ( integer $size ) : integer

Parameters

size

The new size of the memory buffer.

Return Values

The new size of the memory buffer.


Read data from the memory buffer based on offset and length.

  • « Swoole\Buffer::expand
  • Swoole\Buffer::recycle »
  • PHP Manual
  • Swoole\Buffer
  • Read data from the memory buffer based on offset and length.

Swoole\Buffer::read

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Buffer::read — Read data from the memory buffer based on offset and length.

Description

public Swoole\Buffer::read ( integer $offset , integer $length ) : string

Parameters

offset

The offset.

length

The length.

Return Values

The data readed from the memory buffer.


Release the memory to OS which is not used by the memory buffer.

  • « Swoole\Buffer::read
  • Swoole\Buffer::substr »
  • PHP Manual
  • Swoole\Buffer
  • Release the memory to OS which is not used by the memory buffer.

Swoole\Buffer::recycle

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Buffer::recycle — Release the memory to OS which is not used by the memory buffer.

Description

public Swoole\Buffer::recycle ( void ) : void

Parameters

This function has no parameters.


Read data from the memory buffer based on offset and length. Or remove data from the memory buffer.

  • « Swoole\Buffer::recycle
  • Swoole\Buffer::__toString »
  • PHP Manual
  • Swoole\Buffer
  • Read data from the memory buffer based on offset and length. Or remove data from the memory buffer.

Swoole\Buffer::substr

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Buffer::substr — Read data from the memory buffer based on offset and length. Or remove data from the memory buffer.

Description

public Swoole\Buffer::substr ( integer $offset [, integer $length [, bool $remove ]] ) : string

If $remove is set to be true and $offset is set to be 0, the data will be removed from the buffer. The memory for storing the data will be released when the buffer object is deconstructed.

Parameters

offset

The offset.

length

The length.

remove

Whether to remove the data from the memory buffer.

Return Values

The data or string readed from the memory buffer.


Get the string value of the memory buffer.

  • « Swoole\Buffer::substr
  • Swoole\Buffer::write »
  • PHP Manual
  • Swoole\Buffer
  • Get the string value of the memory buffer.

Swoole\Buffer::__toString

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Buffer::__toString — Get the string value of the memory buffer.

Description

public Swoole\Buffer::__toString ( void ) : string

Parameters

This function has no parameters.

Return Values

The string value of the memory buffer.


Write data to the memory buffer. The memory allocated for the buffer will not be changed.

  • « Swoole\Buffer::__toString
  • Swoole\Channel »
  • PHP Manual
  • Swoole\Buffer
  • Write data to the memory buffer. The memory allocated for the buffer will not be changed.

Swoole\Buffer::write

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Buffer::write — Write data to the memory buffer. The memory allocated for the buffer will not be changed.

Description

public Swoole\Buffer::write ( integer $offset , string $data ) : void

Parameters

offset

The offset.

data

The data to write to the memory buffer.

Return Values


The Swoole\Channel class

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Introduction

Class synopsis

Swoole\Channel {
/* Methods */
public __destruct ( void ) : void
public pop ( void ) : mixed
public push ( string $data ) : bool
public stats ( void ) : array
}

Table of Contents

  • Swoole\Channel::__construct — Construct a Swoole Channel
  • Swoole\Channel::__destruct — Destruct a Swoole channel.
  • Swoole\Channel::pop — Read and pop data from swoole channel.
  • Swoole\Channel::push — Write and push data into Swoole channel.
  • Swoole\Channel::stats — Get stats of swoole channel.


Construct a Swoole Channel

  • « Swoole\Channel
  • Swoole\Channel::__destruct »
  • PHP Manual
  • Swoole\Channel
  • Construct a Swoole Channel

Swoole\Channel::__construct

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Channel::__construct — Construct a Swoole Channel

Description

public Swoole\Channel::__construct ( string $size )

Swoole channel is memory data structure works like Chan in Golang, implemented based on shared memory and mutex locks. It can be used as high performance message queue in memory. Construct a swoole channel with a fixed size. The minimum size of a swoole channel is 64KB. Exceptions will be thrown if there is not enough memory.

Parameters

size

The size of the Swoole channel.


Destruct a Swoole channel.

  • « Swoole\Channel::__construct
  • Swoole\Channel::pop »
  • PHP Manual
  • Swoole\Channel
  • Destruct a Swoole channel.

Swoole\Channel::__destruct

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Channel::__destruct — Destruct a Swoole channel.

Description

public Swoole\Channel::__destruct ( void ) : void

Parameters

This function has no parameters.


Read and pop data from swoole channel.

  • « Swoole\Channel::__destruct
  • Swoole\Channel::push »
  • PHP Manual
  • Swoole\Channel
  • Read and pop data from swoole channel.

Swoole\Channel::pop

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Channel::pop — Read and pop data from swoole channel.

Description

public Swoole\Channel::pop ( void ) : mixed

Parameters

This function has no parameters.

Return Values

If the channel is empty, the function will return false, or return the unserialized data.


Write and push data into Swoole channel.

  • « Swoole\Channel::pop
  • Swoole\Channel::stats »
  • PHP Manual
  • Swoole\Channel
  • Write and push data into Swoole channel.

Swoole\Channel::push

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Channel::push — Write and push data into Swoole channel.

Description

public Swoole\Channel::push ( string $data ) : bool

Data can be any non-empty PHP variable, the variable will be serialized if it is not string type.

If size of the data is more than 8KB, swoole channel will use temp files storage.

The function will return true if the write operation is succeeded, or return false if there is not enough space.

Parameters

data

The data to push into the Swoole channel.

Return Values

Wheter the data is pushed into he Swoole channel.


Get stats of swoole channel.

  • « Swoole\Channel::push
  • Swoole\Client »
  • PHP Manual
  • Swoole\Channel
  • Get stats of swoole channel.

Swoole\Channel::stats

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Channel::stats — Get stats of swoole channel.

Description

public Swoole\Channel::stats ( void ) : array

Get the numbers of queued elements and total size of the memory used by the queue.

Parameters

This function has no parameters.

Return Values

The stats of the Swoole channel.


The Swoole\Client class

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Introduction

Class synopsis

Swoole\Client {
/* Constants */
const integer MSG_OOB = 1 ;
const integer MSG_PEEK = 2 ;
const integer MSG_DONTWAIT = 128 ;
const integer MSG_WAITALL = 64 ;
/* Properties */
public $errCode ;
public $sock ;
public $reuse ;
public $reuseCount ;
/* Methods */
public close ([ bool $force ] ) : bool
public connect ( string $host [, integer $port [, integer $timeout [, integer $flag ]]] ) : bool
public __destruct ( void ) : void
public getpeername ( void ) : array
public getsockname ( void ) : array
public isConnected ( void ) : bool
public on ( string $event , callable $callback ) : void
public pause ( void ) : void
public pipe ( string $socket ) : void
public recv ([ string $size [, string $flag ]] ) : void
public resume ( void ) : void
public send ( string $data [, string $flag ] ) : integer
public sendfile ( string $filename [, int $offset ] ) : boolean
public sendto ( string $ip , integer $port , string $data ) : boolean
public set ( array $settings ) : void
public sleep ( void ) : void
public wakeup ( void ) : void
}

Properties

errCode

sock

reuse

reuseCount

Predefined Constants

Swoole\Client::MSG_OOB

Swoole\Client::MSG_PEEK

Swoole\Client::MSG_DONTWAIT

Swoole\Client::MSG_WAITALL

Table of Contents

  • Swoole\Client::close — Close the connection established.
  • Swoole\Client::connect — Connect to the remote TCP or UDP port.
  • Swoole\Client::__construct — Create Swoole sync or async TCP/UDP client, with or without SSL.
  • Swoole\Client::__destruct — Destruct the Swoole client.
  • Swoole\Client::getpeername — Get the remote socket name of the connection.
  • Swoole\Client::getsockname — Get the local socket name of the connection.
  • Swoole\Client::isConnected — Check if the connection is established.
  • Swoole\Client::on — Add callback functions triggered by events.
  • Swoole\Client::pause — Pause receiving data.
  • Swoole\Client::pipe — Redirect the data to another file descriptor.
  • Swoole\Client::recv — Receive data from the remote socket.
  • Swoole\Client::resume — Resume receiving data.
  • Swoole\Client::send — Send data to the remote TCP socket.
  • Swoole\Client::sendfile — Send file to the remote TCP socket.
  • Swoole\Client::sendto — Send data to the remote UDP address.
  • Swoole\Client::set — Set the Swoole client parameters before the connection is established.
  • Swoole\Client::sleep — Remove the TCP client from system event loop.
  • Swoole\Client::wakeup — Add the TCP client back into the system event loop.


Close the connection established.

  • « Swoole\Client
  • Swoole\Client::connect »
  • PHP Manual
  • Swoole\Client
  • Close the connection established.

Swoole\Client::close

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Client::close — Close the connection established.

Description

public Swoole\Client::close ([ bool $force ] ) : bool

Parameters

force

Whether force to close the connection.

Return Values

Whether the connection is closed.


Connect to the remote TCP or UDP port.

  • « Swoole\Client::close
  • Swoole\Client::__construct »
  • PHP Manual
  • Swoole\Client
  • Connect to the remote TCP or UDP port.

Swoole\Client::connect

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Client::connect — Connect to the remote TCP or UDP port.

Description

public Swoole\Client::connect ( string $host [, integer $port [, integer $timeout [, integer $flag ]]] ) : bool

Parameters

host

The host name of the remote address.

port

The port number of the remote address.

timeout

The timeout(second) of connect/send/recv, the dafault value is 0.1s

flag

If the type of client is UDP, the $flag means if to enable the configuration udp_connect. If the configuration udp_connect is enabled, the client will only receive the data from specified ip:port. If the type of client is TCP and the $flag is set to 1, it must use swoole_client_select to check the connection status before send/recv.

Return Values

Whether the connection is established.


Create Swoole sync or async TCP/UDP client, with or without SSL.

  • « Swoole\Client::connect
  • Swoole\Client::__destruct »
  • PHP Manual
  • Swoole\Client
  • Create Swoole sync or async TCP/UDP client, with or without SSL.

Swoole\Client::__construct

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Client::__construct — Create Swoole sync or async TCP/UDP client, with or without SSL.

Description

public Swoole\Client::__construct ( int $sock_type [, integer $is_async ] )

Parameters

sock_type

The type of socket: SWOOLE_TCP, SWOOLE_UDP, SWOOLE_ASYNC, SWOOLE_SSL, SWOOLE_KEEP.

is_async

Synchronous or asynchronous client.


Destruct the Swoole client.

  • « Swoole\Client::__construct
  • Swoole\Client::getpeername »
  • PHP Manual
  • Swoole\Client
  • Destruct the Swoole client.

Swoole\Client::__destruct

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Client::__destruct — Destruct the Swoole client.

Description

public Swoole\Client::__destruct ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.


Get the remote socket name of the connection.

  • « Swoole\Client::__destruct
  • Swoole\Client::getsockname »
  • PHP Manual
  • Swoole\Client
  • Get the remote socket name of the connection.

Swoole\Client::getpeername

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Client::getpeername — Get the remote socket name of the connection.

Description

public Swoole\Client::getpeername ( void ) : array

Parameters

This function has no parameters.

Return Values

The host and port of the remote socket.


Get the local socket name of the connection.

  • « Swoole\Client::getpeername
  • Swoole\Client::isConnected »
  • PHP Manual
  • Swoole\Client
  • Get the local socket name of the connection.

Swoole\Client::getsockname

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Client::getsockname — Get the local socket name of the connection.

Description

public Swoole\Client::getsockname ( void ) : array

Parameters

This function has no parameters.

Return Values

The host and port of the local socket.


Check if the connection is established.

  • « Swoole\Client::getsockname
  • Swoole\Client::on »
  • PHP Manual
  • Swoole\Client
  • Check if the connection is established.

Swoole\Client::isConnected

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Client::isConnected — Check if the connection is established.

Description

public Swoole\Client::isConnected ( void ) : bool

This method returns the connection status of application layer.

Parameters

This function has no parameters.

Return Values

Whether the connection is established.


Add callback functions triggered by events.

  • « Swoole\Client::isConnected
  • Swoole\Client::pause »
  • PHP Manual
  • Swoole\Client
  • Add callback functions triggered by events.

Swoole\Client::on

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Client::on — Add callback functions triggered by events.

Description

public Swoole\Client::on ( string $event , callable $callback ) : void

Parameters

event

callback


Pause receiving data.

  • « Swoole\Client::on
  • Swoole\Client::pipe »
  • PHP Manual
  • Swoole\Client
  • Pause receiving data.

Swoole\Client::pause

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Client::pause — Pause receiving data.

Description

public Swoole\Client::pause ( void ) : void

Parameters

This function has no parameters.


Redirect the data to another file descriptor.

  • « Swoole\Client::pause
  • Swoole\Client::recv »
  • PHP Manual
  • Swoole\Client
  • Redirect the data to another file descriptor.

Swoole\Client::pipe

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Client::pipe — Redirect the data to another file descriptor.

Description

public Swoole\Client::pipe ( string $socket ) : void

Parameters

socket


Receive data from the remote socket.

  • « Swoole\Client::pipe
  • Swoole\Client::resume »
  • PHP Manual
  • Swoole\Client
  • Receive data from the remote socket.

Swoole\Client::recv

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Client::recv — Receive data from the remote socket.

Description

public Swoole\Client::recv ([ string $size [, string $flag ]] ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

size

flag

Return Values


Resume receiving data.

  • « Swoole\Client::recv
  • Swoole\Client::send »
  • PHP Manual
  • Swoole\Client
  • Resume receiving data.

Swoole\Client::resume

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Client::resume — Resume receiving data.

Description

public Swoole\Client::resume ( void ) : void

Parameters

This function has no parameters.


Send data to the remote TCP socket.

  • « Swoole\Client::resume
  • Swoole\Client::sendfile »
  • PHP Manual
  • Swoole\Client
  • Send data to the remote TCP socket.

Swoole\Client::send

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Client::send — Send data to the remote TCP socket.

Description

public Swoole\Client::send ( string $data [, string $flag ] ) : integer

Parameters

data

The data to send which can be string or binary

flag

Return Values

If the client sends data successfully, it returns the length of data sent. Or it returns false and sets $swoole_client->errCode. For sync client, there is no limit for the data to send. For async client, The limit for the data to send is socket_buffer_size.


Send file to the remote TCP socket.

  • « Swoole\Client::send
  • Swoole\Client::sendto »
  • PHP Manual
  • Swoole\Client
  • Send file to the remote TCP socket.

Swoole\Client::sendfile

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Client::sendfile — Send file to the remote TCP socket.

Description

public Swoole\Client::sendfile ( string $filename [, int $offset ] ) : boolean

This is a wrapper of the Linux sendfile system call.

Parameters

filename

File path of the file to send.

offset

Offset of the file to send

Return Values


Send data to the remote UDP address.

  • « Swoole\Client::sendfile
  • Swoole\Client::set »
  • PHP Manual
  • Swoole\Client
  • Send data to the remote UDP address.

Swoole\Client::sendto

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Client::sendto — Send data to the remote UDP address.

Description

public Swoole\Client::sendto ( string $ip , integer $port , string $data ) : boolean

The swoole client should be type of SWOOLE_SOCK_UDP or SWOOLE_SOCK_UDP6.

Parameters

ip

The IP address of remote host, IPv4 or IPv6.

port

The port number of remote host.

data

The data to send which should be less-than 64K.

Return Values


Set the Swoole client parameters before the connection is established.

  • « Swoole\Client::sendto
  • Swoole\Client::sleep »
  • PHP Manual
  • Swoole\Client
  • Set the Swoole client parameters before the connection is established.

Swoole\Client::set

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Client::set — Set the Swoole client parameters before the connection is established.

Description

public Swoole\Client::set ( array $settings ) : void

Parameters

settings

Return Values


Remove the TCP client from system event loop.

  • « Swoole\Client::set
  • Swoole\Client::wakeup »
  • PHP Manual
  • Swoole\Client
  • Remove the TCP client from system event loop.

Swoole\Client::sleep

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Client::sleep — Remove the TCP client from system event loop.

Description

public Swoole\Client::sleep ( void ) : void

Remove the TCP client from system event loop.

Parameters

This function has no parameters.

Return Values


Add the TCP client back into the system event loop.

  • « Swoole\Client::sleep
  • Swoole\Connection\Iterator »
  • PHP Manual
  • Swoole\Client
  • Add the TCP client back into the system event loop.

Swoole\Client::wakeup

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Client::wakeup — Add the TCP client back into the system event loop.

Description

public Swoole\Client::wakeup ( void ) : void

Parameters

This function has no parameters.

Return Values


The Swoole\Connection\Iterator class

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Introduction

Class synopsis

Swoole\Connection\Iterator implements Iterator , Countable , ArrayAccess {
/* Methods */
public count ( void ) : int
public current ( void ) : Connection
public key ( void ) : int
public next ( void ) : Connection
public offsetExists ( int $index ) : boolean
public offsetGet ( string $index ) : Connection
public offsetSet ( int $offset , mixed $connection ) : void
public offsetUnset ( int $offset ) : void
public rewind ( void ) : void
public valid ( void ) : boolean
}

Table of Contents

  • Swoole\Connection\Iterator::count — Count connections.
  • Swoole\Connection\Iterator::current — Return current connection entry.
  • Swoole\Connection\Iterator::key — Return key of the current connection.
  • Swoole\Connection\Iterator::next — Move to the next connection.
  • Swoole\Connection\Iterator::offsetExists — Check if offet exists.
  • Swoole\Connection\Iterator::offsetGet — Offset to retrieve.
  • Swoole\Connection\Iterator::offsetSet — Assign a Connection to the specified offset.
  • Swoole\Connection\Iterator::offsetUnset — Unset an offset.
  • Swoole\Connection\Iterator::rewind — Rewinds iterator
  • Swoole\Connection\Iterator::valid — Check if current position is valid.


Count connections.

  • « Swoole\Connection\Iterator
  • Swoole\Connection\Iterator::current »
  • PHP Manual
  • Swoole\Connection\Iterator
  • Count connections.

Swoole\Connection\Iterator::count

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Connection\Iterator::count — Count connections.

Description

public Swoole\Connection\Iterator::count ( void ) : int

Gets the number of connections.

Parameters

This function has no parameters.

Return Values

The number of connections.


Return current connection entry.

  • « Swoole\Connection\Iterator::count
  • Swoole\Connection\Iterator::key »
  • PHP Manual
  • Swoole\Connection\Iterator
  • Return current connection entry.

Swoole\Connection\Iterator::current

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Connection\Iterator::current — Return current connection entry.

Description

public Swoole\Connection\Iterator::current ( void ) : Connection

Get current connection entry.

Parameters

This function has no parameters.

Return Values

The current connection entry.


Return key of the current connection.

  • « Swoole\Connection\Iterator::current
  • Swoole\Connection\Iterator::next »
  • PHP Manual
  • Swoole\Connection\Iterator
  • Return key of the current connection.

Swoole\Connection\Iterator::key

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Connection\Iterator::key — Return key of the current connection.

Description

public Swoole\Connection\Iterator::key ( void ) : int

This function returns key of the current connection.

Parameters

This function has no parameters.

Return Values

Key of the current connection.


Move to the next connection.

  • « Swoole\Connection\Iterator::key
  • Swoole\Connection\Iterator::offsetExists »
  • PHP Manual
  • Swoole\Connection\Iterator
  • Move to the next connection.

Swoole\Connection\Iterator::next

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Connection\Iterator::next — Move to the next connection.

Description

public Swoole\Connection\Iterator::next ( void ) : Connection

The iterator to the next connection.

Parameters

This function has no parameters.

Return Values


Check if offet exists.

  • « Swoole\Connection\Iterator::next
  • Swoole\Connection\Iterator::offsetGet »
  • PHP Manual
  • Swoole\Connection\Iterator
  • Check if offet exists.

Swoole\Connection\Iterator::offsetExists

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Connection\Iterator::offsetExists — Check if offet exists.

Description

public Swoole\Connection\Iterator::offsetExists ( int $index ) : boolean

Check if offset exists.

Parameters

index

The offset being checked.

Return Values

Returns TRUE if the offset exists, otherwise FALSE.


Offset to retrieve.

  • « Swoole\Connection\Iterator::offsetExists
  • Swoole\Connection\Iterator::offsetSet »
  • PHP Manual
  • Swoole\Connection\Iterator
  • Offset to retrieve.

Swoole\Connection\Iterator::offsetGet

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Connection\Iterator::offsetGet — Offset to retrieve.

Description

public Swoole\Connection\Iterator::offsetGet ( string $index ) : Connection

Return the connection at specified offset.

Parameters

index

The offset to retrieve.

Return Values


Assign a Connection to the specified offset.

  • « Swoole\Connection\Iterator::offsetGet
  • Swoole\Connection\Iterator::offsetUnset »
  • PHP Manual
  • Swoole\Connection\Iterator
  • Assign a Connection to the specified offset.

Swoole\Connection\Iterator::offsetSet

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Connection\Iterator::offsetSet — Assign a Connection to the specified offset.

Description

public Swoole\Connection\Iterator::offsetSet ( int $offset , mixed $connection ) : void

Assign a Connection to the specified offset.

Parameters

offset

The offset to assign the Connection to.

connection

The connection to set.

Return Values


Unset an offset.

  • « Swoole\Connection\Iterator::offsetSet
  • Swoole\Connection\Iterator::rewind »
  • PHP Manual
  • Swoole\Connection\Iterator
  • Unset an offset.

Swoole\Connection\Iterator::offsetUnset

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Connection\Iterator::offsetUnset — Unset an offset.

Description

public Swoole\Connection\Iterator::offsetUnset ( int $offset ) : void

Unsets an offset.

Parameters

offset

The offset to unset.

Return Values


Rewinds iterator

  • « Swoole\Connection\Iterator::offsetUnset
  • Swoole\Connection\Iterator::valid »
  • PHP Manual
  • Swoole\Connection\Iterator
  • Rewinds iterator

Swoole\Connection\Iterator::rewind

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Connection\Iterator::rewind — Rewinds iterator

Description

public Swoole\Connection\Iterator::rewind ( void ) : void

Parameters

This function has no parameters.

Return Values


Check if current position is valid.

  • « Swoole\Connection\Iterator::rewind
  • Swoole\Coroutine »
  • PHP Manual
  • Swoole\Connection\Iterator
  • Check if current position is valid.

Swoole\Connection\Iterator::valid

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Connection\Iterator::valid — Check if current position is valid.

Description

public Swoole\Connection\Iterator::valid ( void ) : boolean

Checks if the current position is valid.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the current iterator position is valid, otherwise FALSE.


The Swoole\Coroutine class

(PHP 7, PECL swoole >= 2.0.0)

Introduction

Class synopsis

Swoole\Coroutine {
/* Methods */
public static call_user_func_array ( callable $callback , array $param_array ) : mixed
public static call_user_func ( callable $callback [, mixed $... ] ) : mixed
public static cli_wait ( void ) : ReturnType
public static create ( void ) : ReturnType
public Swoole\Coroutine\Client::close ( void ) : ReturnType
public Swoole\Coroutine\Client::connect ( void ) : ReturnType
public Swoole\Coroutine\Client::__destruct ( void ) : ReturnType
public Swoole\Coroutine\Client::getpeername ( void ) : ReturnType
public Swoole\Coroutine\Client::getsockname ( void ) : ReturnType
public Swoole\Coroutine\Client::isConnected ( void ) : ReturnType
public Swoole\Coroutine\Client::recv ( void ) : ReturnType
public Swoole\Coroutine\Client::send ( void ) : ReturnType
public Swoole\Coroutine\Client::sendfile ( void ) : ReturnType
public Swoole\Coroutine\Client::sendto ( void ) : ReturnType
public Swoole\Coroutine\Client::set ( void ) : ReturnType
public Swoole\Coroutine\Http\Client::addFile ( void ) : ReturnType
public Swoole\Coroutine\Http\Client::close ( void ) : ReturnType
public Swoole\Coroutine\Http\Client::__destruct ( void ) : ReturnType
public Swoole\Coroutine\Http\Client::execute ( void ) : ReturnType
public Swoole\Coroutine\Http\Client::get ( void ) : ReturnType
public Swoole\Coroutine\Http\Client::getDefer ( void ) : ReturnType
public Swoole\Coroutine\Http\Client::isConnected ( void ) : ReturnType
public Swoole\Coroutine\Http\Client::post ( void ) : ReturnType
public Swoole\Coroutine\Http\Client::recv ( void ) : ReturnType
public Swoole\Coroutine\Http\Client::set ( void ) : ReturnType
public Swoole\Coroutine\Http\Client::setCookies ( void ) : ReturnType
public Swoole\Coroutine\Http\Client::setData ( void ) : ReturnType
public Swoole\Coroutine\Http\Client::setDefer ( void ) : ReturnType
public Swoole\Coroutine\Http\Client::setHeaders ( void ) : ReturnType
public Swoole\Coroutine\Http\Client::setMethod ( void ) : ReturnType
public Swoole\Coroutine\MySQL::close ( void ) : ReturnType
public Swoole\Coroutine\MySQL::connect ( void ) : ReturnType
public Swoole\Coroutine\MySQL::__destruct ( void ) : ReturnType
public Swoole\Coroutine\MySQL::getDefer ( void ) : ReturnType
public Swoole\Coroutine\MySQL::query ( void ) : ReturnType
public Swoole\Coroutine\MySQL::recv ( void ) : ReturnType
public Swoole\Coroutine\MySQL::setDefer ( void ) : ReturnType
public static getuid ( void ) : ReturnType
public static resume ( void ) : ReturnType
public static suspend ( void ) : ReturnType
}

Table of Contents

  • Swoole\Coroutine::call_user_func_array — Call a callback with an array of parameters
  • Swoole\Coroutine::call_user_func — Call a callback given by the first parameter
  • Swoole\Coroutine::cli_wait — Description
  • Swoole\Coroutine::create — Description
  • Swoole\Coroutine\Client::close — Description
  • Swoole\Coroutine\Client::connect — Description
  • Swoole\Coroutine\Client::__construct — Description
  • Swoole\Coroutine\Client::__destruct — Description
  • Swoole\Coroutine\Client::getpeername — Description
  • Swoole\Coroutine\Client::getsockname — Description
  • Swoole\Coroutine\Client::isConnected — Description
  • Swoole\Coroutine\Client::recv — Description
  • Swoole\Coroutine\Client::send — Description
  • Swoole\Coroutine\Client::sendfile — Description
  • Swoole\Coroutine\Client::sendto — Description
  • Swoole\Coroutine\Client::set — Description
  • Swoole\Coroutine\Http\Client::addFile — Description
  • Swoole\Coroutine\Http\Client::close — Description
  • Swoole\Coroutine\Http\Client::__construct — Description
  • Swoole\Coroutine\Http\Client::__destruct — Description
  • Swoole\Coroutine\Http\Client::execute — Description
  • Swoole\Coroutine\Http\Client::get — Description
  • Swoole\Coroutine\Http\Client::getDefer — Description
  • Swoole\Coroutine\Http\Client::isConnected — Description
  • Swoole\Coroutine\Http\Client::post — Description
  • Swoole\Coroutine\Http\Client::recv — Description
  • Swoole\Coroutine\Http\Client::set — Description
  • Swoole\Coroutine\Http\Client::setCookies — Description
  • Swoole\Coroutine\Http\Client::setData — Description
  • Swoole\Coroutine\Http\Client::setDefer — Description
  • Swoole\Coroutine\Http\Client::setHeaders — Description
  • Swoole\Coroutine\Http\Client::setMethod — Description
  • Swoole\Coroutine\MySQL::close — Description
  • Swoole\Coroutine\MySQL::connect — Description
  • Swoole\Coroutine\MySQL::__construct — Description
  • Swoole\Coroutine\MySQL::__destruct — Description
  • Swoole\Coroutine\MySQL::getDefer — Description
  • Swoole\Coroutine\MySQL::query — Description
  • Swoole\Coroutine\MySQL::recv — Description
  • Swoole\Coroutine\MySQL::setDefer — Description
  • Swoole\Coroutine::getuid — Description
  • Swoole\Coroutine::resume — Description
  • Swoole\Coroutine::suspend — Description


Call a callback with an array of parameters

  • « Swoole\Coroutine
  • Swoole\Coroutine::call_user_func »
  • PHP Manual
  • Swoole\Coroutine
  • Call a callback with an array of parameters

Swoole\Coroutine::call_user_func_array

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine::call_user_func_array — Call a callback with an array of parameters

Description

public static Swoole\Coroutine::call_user_func_array ( callable $callback , array $param_array ) : mixed

Calls the callback given by the first parameter with the parameters in param_array.

Parameters

callback

The callable to be called.

param_array

Zero or more parameters in the array to be passed to the callback.

Return Values


Call a callback given by the first parameter

  • « Swoole\Coroutine::call_user_func_array
  • Swoole\Coroutine::cli_wait »
  • PHP Manual
  • Swoole\Coroutine
  • Call a callback given by the first parameter

Swoole\Coroutine::call_user_func

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine::call_user_func — Call a callback given by the first parameter

Description

public static Swoole\Coroutine::call_user_func ( callable $callback [, mixed $... ] ) : mixed

Calls the callback given by the first parameter and passes the remaining parameters as arguments.

Parameters

callback

The callable to be called.

...

Zero or more parameters to be passed to the callback.

Return Values


Description

  • « Swoole\Coroutine::call_user_func
  • Swoole\Coroutine::create »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine::cli_wait

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine::cli_wait — Description

Description

public static Swoole\Coroutine::cli_wait ( void ) : ReturnType

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine::cli_wait
  • Swoole\Coroutine\Client::close »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine::create

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine::create — Description

Description

public static Swoole\Coroutine::create ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine::create
  • Swoole\Coroutine\Client::connect »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Client::close

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\Client::close — Description

Description

public Swoole\Coroutine\Client::close ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\Client::close
  • Swoole\Coroutine\Client::__construct »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Client::connect

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\Client::connect — Description

Description

public Swoole\Coroutine\Client::connect ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\Client::connect
  • Swoole\Coroutine\Client::__destruct »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Client::__construct

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\Client::__construct — Description

Description

public Swoole\Coroutine\Client::__construct ( void )

Parameters

This function has no parameters.


Description

  • « Swoole\Coroutine\Client::__construct
  • Swoole\Coroutine\Client::getpeername »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Client::__destruct

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\Client::__destruct — Description

Description

public Swoole\Coroutine\Client::__destruct ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\Client::__destruct
  • Swoole\Coroutine\Client::getsockname »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Client::getpeername

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\Client::getpeername — Description

Description

public Swoole\Coroutine\Client::getpeername ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\Client::getpeername
  • Swoole\Coroutine\Client::isConnected »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Client::getsockname

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\Client::getsockname — Description

Description

public Swoole\Coroutine\Client::getsockname ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\Client::getsockname
  • Swoole\Coroutine\Client::recv »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Client::isConnected

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\Client::isConnected — Description

Description

public Swoole\Coroutine\Client::isConnected ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\Client::isConnected
  • Swoole\Coroutine\Client::send »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Client::recv

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\Client::recv — Description

Description

public Swoole\Coroutine\Client::recv ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\Client::recv
  • Swoole\Coroutine\Client::sendfile »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Client::send

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\Client::send — Description

Description

public Swoole\Coroutine\Client::send ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\Client::send
  • Swoole\Coroutine\Client::sendto »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Client::sendfile

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\Client::sendfile — Description

Description

public Swoole\Coroutine\Client::sendfile ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\Client::sendfile
  • Swoole\Coroutine\Client::set »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Client::sendto

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\Client::sendto — Description

Description

public Swoole\Coroutine\Client::sendto ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\Client::sendto
  • Swoole\Coroutine\Http\Client::addFile »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Client::set

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\Client::set — Description

Description

public Swoole\Coroutine\Client::set ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\Client::set
  • Swoole\Coroutine\Http\Client::close »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::addFile

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::addFile — Description

Description

public Swoole\Coroutine\Http\Client::addFile ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\Http\Client::addFile
  • Swoole\Coroutine\Http\Client::__construct »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::close

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::close — Description

Description

public Swoole\Coroutine\Http\Client::close ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\Http\Client::close
  • Swoole\Coroutine\Http\Client::__destruct »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::__construct

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::__construct — Description

Description

public Swoole\Coroutine\Http\Client::__construct ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.


Description

  • « Swoole\Coroutine\Http\Client::__construct
  • Swoole\Coroutine\Http\Client::execute »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::__destruct

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::__destruct — Description

Description

public Swoole\Coroutine\Http\Client::__destruct ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\Http\Client::__destruct
  • Swoole\Coroutine\Http\Client::get »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::execute

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::execute — Description

Description

public Swoole\Coroutine\Http\Client::execute ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\Http\Client::execute
  • Swoole\Coroutine\Http\Client::getDefer »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::get

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::get — Description

Description

public Swoole\Coroutine\Http\Client::get ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\Http\Client::get
  • Swoole\Coroutine\Http\Client::isConnected »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::getDefer

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::getDefer — Description

Description

public Swoole\Coroutine\Http\Client::getDefer ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\Http\Client::getDefer
  • Swoole\Coroutine\Http\Client::post »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::isConnected

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::isConnected — Description

Description

public Swoole\Coroutine\Http\Client::isConnected ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\Http\Client::isConnected
  • Swoole\Coroutine\Http\Client::recv »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::post

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::post — Description

Description

public Swoole\Coroutine\Http\Client::post ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\Http\Client::post
  • Swoole\Coroutine\Http\Client::set »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::recv

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::recv — Description

Description

public Swoole\Coroutine\Http\Client::recv ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\Http\Client::recv
  • Swoole\Coroutine\Http\Client::setCookies »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::set

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::set — Description

Description

public Swoole\Coroutine\Http\Client::set ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\Http\Client::set
  • Swoole\Coroutine\Http\Client::setData »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::setCookies

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::setCookies — Description

Description

public Swoole\Coroutine\Http\Client::setCookies ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\Http\Client::setCookies
  • Swoole\Coroutine\Http\Client::setDefer »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::setData

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::setData — Description

Description

public Swoole\Coroutine\Http\Client::setData ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\Http\Client::setData
  • Swoole\Coroutine\Http\Client::setHeaders »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::setDefer

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::setDefer — Description

Description

public Swoole\Coroutine\Http\Client::setDefer ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\Http\Client::setDefer
  • Swoole\Coroutine\Http\Client::setMethod »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::setHeaders

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::setHeaders — Description

Description

public Swoole\Coroutine\Http\Client::setHeaders ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\Http\Client::setHeaders
  • Swoole\Coroutine\MySQL::close »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::setMethod

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::setMethod — Description

Description

public Swoole\Coroutine\Http\Client::setMethod ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\Http\Client::setMethod
  • Swoole\Coroutine\MySQL::connect »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\MySQL::close

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\MySQL::close — Description

Description

public Swoole\Coroutine\MySQL::close ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\MySQL::close
  • Swoole\Coroutine\MySQL::__construct »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\MySQL::connect

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\MySQL::connect — Description

Description

public Swoole\Coroutine\MySQL::connect ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\MySQL::connect
  • Swoole\Coroutine\MySQL::__destruct »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\MySQL::__construct

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\MySQL::__construct — Description

Description

public Swoole\Coroutine\MySQL::__construct ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.


Description

  • « Swoole\Coroutine\MySQL::__construct
  • Swoole\Coroutine\MySQL::getDefer »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\MySQL::__destruct

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\MySQL::__destruct — Description

Description

public Swoole\Coroutine\MySQL::__destruct ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\MySQL::__destruct
  • Swoole\Coroutine\MySQL::query »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\MySQL::getDefer

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\MySQL::getDefer — Description

Description

public Swoole\Coroutine\MySQL::getDefer ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\MySQL::getDefer
  • Swoole\Coroutine\MySQL::recv »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\MySQL::query

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\MySQL::query — Description

Description

public Swoole\Coroutine\MySQL::query ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\MySQL::query
  • Swoole\Coroutine\MySQL::setDefer »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\MySQL::recv

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\MySQL::recv — Description

Description

public Swoole\Coroutine\MySQL::recv ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\MySQL::recv
  • Swoole\Coroutine::getuid »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\MySQL::setDefer

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine\MySQL::setDefer — Description

Description

public Swoole\Coroutine\MySQL::setDefer ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine\MySQL::setDefer
  • Swoole\Coroutine::resume »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine::getuid

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine::getuid — Description

Description

public static Swoole\Coroutine::getuid ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine::getuid
  • Swoole\Coroutine::suspend »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine::resume

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine::resume — Description

Description

public static Swoole\Coroutine::resume ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\Coroutine::resume
  • Swoole\Event »
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine::suspend

(PHP 7, PECL swoole >= 2.0.0)

Swoole\Coroutine::suspend — Description

Description

public static Swoole\Coroutine::suspend ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The Swoole\Event class

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Introduction

Class synopsis

Swoole\Event {
/* Methods */
public static add ( int $fd , callable $read_callback [, callable $write_callback [, string $events ]] ) : boolean
public static defer ( mixed $callback ) : void
public static del ( string $fd ) : boolean
public static exit ( void ) : void
public static set ( int $fd [, string $read_callback [, string $write_callback [, string $events ]]] ) : boolean
public static wait ( void ) : void
public static write ( string $fd , string $data ) : void
}

Table of Contents

  • Swoole\Event::add — Add new callback functions of a socket into the EventLoop.
  • Swoole\Event::defer — Add a callback function to the next event loop.
  • Swoole\Event::del — Remove all event callback functions of a socket.
  • Swoole\Event::exit — Exit the eventloop, only available at client side.
  • Swoole\Event::set — Update the event callback functions of a socket.
  • Swoole\Event::wait — Description
  • Swoole\Event::write — Write data to the socket.


Add new callback functions of a socket into the EventLoop.

  • « Swoole\Event
  • Swoole\Event::defer »
  • PHP Manual
  • Swoole\Event
  • Add new callback functions of a socket into the EventLoop.

Swoole\Event::add

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Event::add — Add new callback functions of a socket into the EventLoop.

Description

public static Swoole\Event::add ( int $fd , callable $read_callback [, callable $write_callback [, string $events ]] ) : boolean

Parameters

fd

read_callback

write_callback

events

Return Values


Add a callback function to the next event loop.

  • « Swoole\Event::add
  • Swoole\Event::del »
  • PHP Manual
  • Swoole\Event
  • Add a callback function to the next event loop.

Swoole\Event::defer

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Event::defer — Add a callback function to the next event loop.

Description

public static Swoole\Event::defer ( mixed $callback ) : void

Parameters

callback

Return Values


Remove all event callback functions of a socket.

  • « Swoole\Event::defer
  • Swoole\Event::exit »
  • PHP Manual
  • Swoole\Event
  • Remove all event callback functions of a socket.

Swoole\Event::del

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Event::del — Remove all event callback functions of a socket.

Description

public static Swoole\Event::del ( string $fd ) : boolean

Parameters

fd

Return Values


Exit the eventloop, only available at client side.

  • « Swoole\Event::del
  • Swoole\Event::set »
  • PHP Manual
  • Swoole\Event
  • Exit the eventloop, only available at client side.

Swoole\Event::exit

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Event::exit — Exit the eventloop, only available at client side.

Description

public static Swoole\Event::exit ( void ) : void

Parameters

This function has no parameters.

Return Values


Update the event callback functions of a socket.

  • « Swoole\Event::exit
  • Swoole\Event::wait »
  • PHP Manual
  • Swoole\Event
  • Update the event callback functions of a socket.

Swoole\Event::set

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Event::set — Update the event callback functions of a socket.

Description

public static Swoole\Event::set ( int $fd [, string $read_callback [, string $write_callback [, string $events ]]] ) : boolean

Parameters

fd

read_callback

write_callback

events

Return Values


Description

  • « Swoole\Event::set
  • Swoole\Event::write »
  • PHP Manual
  • Swoole\Event
  • Description

Swoole\Event::wait

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Event::wait — Description

Description

public static Swoole\Event::wait ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Write data to the socket.

  • « Swoole\Event::wait
  • Swoole\Exception »
  • PHP Manual
  • Swoole\Event
  • Write data to the socket.

Swoole\Event::write

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Event::write — Write data to the socket.

Description

public static Swoole\Event::write ( string $fd , string $data ) : void

Parameters

fd

data

Return Values


The Swoole\Exception class

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Introduction

Class synopsis

Swoole\Exception extends Exception implements Throwable {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
}


The Swoole\Http\Client class

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Introduction

Class synopsis

Swoole\Http\Client {
/* Properties */
public $errCode ;
public $sock ;
/* Methods */
public addFile ( string $path , string $name [, string $type [, string $filename [, string $offset ]]] ) : void
public close ( void ) : void
public __destruct ( void ) : void
public download ( string $path , string $file , callable $callback [, integer $offset ] ) : void
public execute ( string $path , string $callback ) : void
public get ( string $path , callable $callback ) : void
public isConnected ( void ) : boolean
public on ( string $event_name , callable $callback ) : void
public post ( string $path , string $data , callable $callback ) : void
public push ( string $data [, string $opcode [, string $finish ]] ) : void
public set ( array $settings ) : void
public setCookies ( array $cookies ) : void
public setData ( string $data ) : ReturnType
public setHeaders ( array $headers ) : void
public setMethod ( string $method ) : void
public upgrade ( string $path , string $callback ) : void
}

Properties

errCode

sock

Table of Contents

  • Swoole\Http\Client::addFile — Add a file to the post form.
  • Swoole\Http\Client::close — Close the http connection.
  • Swoole\Http\Client::__construct — Construct the async HTTP client.
  • Swoole\Http\Client::__destruct — Destruct the HTTP client.
  • Swoole\Http\Client::download — Download a file from the remote server.
  • Swoole\Http\Client::execute — Send the HTTP request after setting the parameters.
  • Swoole\Http\Client::get — Send GET http request to the remote server.
  • Swoole\Http\Client::isConnected — Check if the HTTP connection is connected.
  • Swoole\Http\Client::on — Register callback function by event name.
  • Swoole\Http\Client::post — Send POST http request to the remote server.
  • Swoole\Http\Client::push — Push data to websocket client.
  • Swoole\Http\Client::set — Update the HTTP client paramters.
  • Swoole\Http\Client::setCookies — Set the http request cookies.
  • Swoole\Http\Client::setData — Set the HTTP request body data.
  • Swoole\Http\Client::setHeaders — Set the HTTP request headers.
  • Swoole\Http\Client::setMethod — Set the HTTP request method.
  • Swoole\Http\Client::upgrade — Upgrade to websocket protocol.


Add a file to the post form.

  • « Swoole\Http\Client
  • Swoole\Http\Client::close »
  • PHP Manual
  • Swoole\Http\Client
  • Add a file to the post form.

Swoole\Http\Client::addFile

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Http\Client::addFile — Add a file to the post form.

Description

public Swoole\Http\Client::addFile ( string $path , string $name [, string $type [, string $filename [, string $offset ]]] ) : void

Parameters

path

name

type

filename

offset

Return Values


Close the http connection.

  • « Swoole\Http\Client::addFile
  • Swoole\Http\Client::__construct »
  • PHP Manual
  • Swoole\Http\Client
  • Close the http connection.

Swoole\Http\Client::close

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Http\Client::close — Close the http connection.

Description

public Swoole\Http\Client::close ( void ) : void

Parameters

This function has no parameters.

Return Values


Construct the async HTTP client.

  • « Swoole\Http\Client::close
  • Swoole\Http\Client::__destruct »
  • PHP Manual
  • Swoole\Http\Client
  • Construct the async HTTP client.

Swoole\Http\Client::__construct

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Http\Client::__construct — Construct the async HTTP client.

Description

public Swoole\Http\Client::__construct ( string $host [, string $port [, boolean $ssl ]] )

Parameters

host

The hostname of the remote host.

port

The port number of the remote host.

ssl

Whether to enable SSL.


Destruct the HTTP client.

  • « Swoole\Http\Client::__construct
  • Swoole\Http\Client::download »
  • PHP Manual
  • Swoole\Http\Client
  • Destruct the HTTP client.

Swoole\Http\Client::__destruct

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Http\Client::__destruct — Destruct the HTTP client.

Description

public Swoole\Http\Client::__destruct ( void ) : void

Parameters

This function has no parameters.

Return Values


Download a file from the remote server.

  • « Swoole\Http\Client::__destruct
  • Swoole\Http\Client::execute »
  • PHP Manual
  • Swoole\Http\Client
  • Download a file from the remote server.

Swoole\Http\Client::download

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Http\Client::download — Download a file from the remote server.

Description

public Swoole\Http\Client::download ( string $path , string $file , callable $callback [, integer $offset ] ) : void

Parameters

path

file

callback

offset

Return Values


Send the HTTP request after setting the parameters.

  • « Swoole\Http\Client::download
  • Swoole\Http\Client::get »
  • PHP Manual
  • Swoole\Http\Client
  • Send the HTTP request after setting the parameters.

Swoole\Http\Client::execute

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Http\Client::execute — Send the HTTP request after setting the parameters.

Description

public Swoole\Http\Client::execute ( string $path , string $callback ) : void

Parameters

path

callback

Return Values


Send GET http request to the remote server.

  • « Swoole\Http\Client::execute
  • Swoole\Http\Client::isConnected »
  • PHP Manual
  • Swoole\Http\Client
  • Send GET http request to the remote server.

Swoole\Http\Client::get

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Http\Client::get — Send GET http request to the remote server.

Description

public Swoole\Http\Client::get ( string $path , callable $callback ) : void

Parameters

path

callback

Return Values


Check if the HTTP connection is connected.

  • « Swoole\Http\Client::get
  • Swoole\Http\Client::on »
  • PHP Manual
  • Swoole\Http\Client
  • Check if the HTTP connection is connected.

Swoole\Http\Client::isConnected

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Http\Client::isConnected — Check if the HTTP connection is connected.

Description

public Swoole\Http\Client::isConnected ( void ) : boolean

Parameters

This function has no parameters.

Return Values


Register callback function by event name.

  • « Swoole\Http\Client::isConnected
  • Swoole\Http\Client::post »
  • PHP Manual
  • Swoole\Http\Client
  • Register callback function by event name.

Swoole\Http\Client::on

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Http\Client::on — Register callback function by event name.

Description

public Swoole\Http\Client::on ( string $event_name , callable $callback ) : void

Parameters

event_name

callback

Return Values


Send POST http request to the remote server.

  • « Swoole\Http\Client::on
  • Swoole\Http\Client::push »
  • PHP Manual
  • Swoole\Http\Client
  • Send POST http request to the remote server.

Swoole\Http\Client::post

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Http\Client::post — Send POST http request to the remote server.

Description

public Swoole\Http\Client::post ( string $path , string $data , callable $callback ) : void

Parameters

path

data

callback

Return Values


Push data to websocket client.

  • « Swoole\Http\Client::post
  • Swoole\Http\Client::set »
  • PHP Manual
  • Swoole\Http\Client
  • Push data to websocket client.

Swoole\Http\Client::push

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Http\Client::push — Push data to websocket client.

Description

public Swoole\Http\Client::push ( string $data [, string $opcode [, string $finish ]] ) : void

Parameters

data

opcode

finish

Return Values


Update the HTTP client paramters.

  • « Swoole\Http\Client::push
  • Swoole\Http\Client::setCookies »
  • PHP Manual
  • Swoole\Http\Client
  • Update the HTTP client paramters.

Swoole\Http\Client::set

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Http\Client::set — Update the HTTP client paramters.

Description

public Swoole\Http\Client::set ( array $settings ) : void

Parameters

settings

Return Values


Set the http request cookies.

  • « Swoole\Http\Client::set
  • Swoole\Http\Client::setData »
  • PHP Manual
  • Swoole\Http\Client
  • Set the http request cookies.

Swoole\Http\Client::setCookies

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Http\Client::setCookies — Set the http request cookies.

Description

public Swoole\Http\Client::setCookies ( array $cookies ) : void

Parameters

cookies

Return Values


Set the HTTP request body data.

  • « Swoole\Http\Client::setCookies
  • Swoole\Http\Client::setHeaders »
  • PHP Manual
  • Swoole\Http\Client
  • Set the HTTP request body data.

Swoole\Http\Client::setData

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Http\Client::setData — Set the HTTP request body data.

Description

public Swoole\Http\Client::setData ( string $data ) : ReturnType

The HTTP method will be changed to be POST.

Parameters

data

Return Values


Set the HTTP request headers.

  • « Swoole\Http\Client::setData
  • Swoole\Http\Client::setMethod »
  • PHP Manual
  • Swoole\Http\Client
  • Set the HTTP request headers.

Swoole\Http\Client::setHeaders

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Http\Client::setHeaders — Set the HTTP request headers.

Description

public Swoole\Http\Client::setHeaders ( array $headers ) : void

Parameters

headers

Return Values


Set the HTTP request method.

  • « Swoole\Http\Client::setHeaders
  • Swoole\Http\Client::upgrade »
  • PHP Manual
  • Swoole\Http\Client
  • Set the HTTP request method.

Swoole\Http\Client::setMethod

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Http\Client::setMethod — Set the HTTP request method.

Description

public Swoole\Http\Client::setMethod ( string $method ) : void

Parameters

method

Return Values


Upgrade to websocket protocol.

  • « Swoole\Http\Client::setMethod
  • Swoole\Http\Request »
  • PHP Manual
  • Swoole\Http\Client
  • Upgrade to websocket protocol.

Swoole\Http\Client::upgrade

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Http\Client::upgrade — Upgrade to websocket protocol.

Description

public Swoole\Http\Client::upgrade ( string $path , string $callback ) : void

Parameters

path

callback

Return Values


The Swoole\Http\Request class

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Introduction

Class synopsis

Swoole\Http\Request {
/* Methods */
public __destruct ( void ) : void
public rawcontent ( void ) : string
}

Table of Contents

  • Swoole\Http\Request::__destruct — Destruct the HTTP request.
  • Swoole\Http\Request::rawcontent — Get the raw HTTP POST body.


Destruct the HTTP request.

  • « Swoole\Http\Request
  • Swoole\Http\Request::rawcontent »
  • PHP Manual
  • Swoole\Http\Request
  • Destruct the HTTP request.

Swoole\Http\Request::__destruct

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Http\Request::__destruct — Destruct the HTTP request.

Description

public Swoole\Http\Request::__destruct ( void ) : void

Parameters

This function has no parameters.

Return Values


Get the raw HTTP POST body.

  • « Swoole\Http\Request::__destruct
  • Swoole\Http\Response »
  • PHP Manual
  • Swoole\Http\Request
  • Get the raw HTTP POST body.

Swoole\Http\Request::rawcontent

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Http\Request::rawcontent — Get the raw HTTP POST body.

Description

public Swoole\Http\Request::rawcontent ( void ) : string

This method is used for the POST data which isn't in the form of `application/x-www-form-urlencoded`.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The Swoole\Http\Response class

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Introduction

Class synopsis

Swoole\Http\Response {
/* Methods */
public cookie ( string $name [, string $value [, string $expires [, string $path [, string $domain [, string $secure [, string $httponly ]]]]]] ) : string
public __destruct ( void ) : void
public end ([ string $content ] ) : void
public gzip ([ string $compress_level ] ) : ReturnType
public header ( string $key , string $value [, string $ucwords ] ) : void
public initHeader ( void ) : ReturnType
public rawcookie ( string $name [, string $value [, string $expires [, string $path [, string $domain [, string $secure [, string $httponly ]]]]]] ) : ReturnType
public sendfile ( string $filename [, int $offset ] ) : ReturnType
public status ( string $http_code ) : ReturnType
public write ( string $content ) : void
}

Table of Contents

  • Swoole\Http\Response::cookie — Set the cookies of the HTTP response.
  • Swoole\Http\Response::__destruct — Destruct the HTTP response.
  • Swoole\Http\Response::end — Send data for the HTTP request and finish the response.
  • Swoole\Http\Response::gzip — Enable the gzip of response content.
  • Swoole\Http\Response::header — Set the HTTP response headers.
  • Swoole\Http\Response::initHeader — Init the HTTP response header.
  • Swoole\Http\Response::rawcookie — Set the raw cookies to the HTTP response.
  • Swoole\Http\Response::sendfile — Send file through the HTTP response.
  • Swoole\Http\Response::status — Set the status code of the HTTP response.
  • Swoole\Http\Response::write — Append HTTP body content to the HTTP response.


Set the cookies of the HTTP response.

  • « Swoole\Http\Response
  • Swoole\Http\Response::__destruct »
  • PHP Manual
  • Swoole\Http\Response
  • Set the cookies of the HTTP response.

Swoole\Http\Response::cookie

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Http\Response::cookie — Set the cookies of the HTTP response.

Description

public Swoole\Http\Response::cookie ( string $name [, string $value [, string $expires [, string $path [, string $domain [, string $secure [, string $httponly ]]]]]] ) : string

Parameters

name

value

expires

path

domain

secure

httponly

Return Values


Destruct the HTTP response.

  • « Swoole\Http\Response::cookie
  • Swoole\Http\Response::end »
  • PHP Manual
  • Swoole\Http\Response
  • Destruct the HTTP response.

Swoole\Http\Response::__destruct

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Http\Response::__destruct — Destruct the HTTP response.

Description

public Swoole\Http\Response::__destruct ( void ) : void

Parameters

This function has no parameters.

Return Values


Send data for the HTTP request and finish the response.

  • « Swoole\Http\Response::__destruct
  • Swoole\Http\Response::gzip »
  • PHP Manual
  • Swoole\Http\Response
  • Send data for the HTTP request and finish the response.

Swoole\Http\Response::end

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Http\Response::end — Send data for the HTTP request and finish the response.

Description

public Swoole\Http\Response::end ([ string $content ] ) : void

Parameters

content

Return Values


Enable the gzip of response content.

  • « Swoole\Http\Response::end
  • Swoole\Http\Response::header »
  • PHP Manual
  • Swoole\Http\Response
  • Enable the gzip of response content.

Swoole\Http\Response::gzip

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Http\Response::gzip — Enable the gzip of response content.

Description

public Swoole\Http\Response::gzip ([ string $compress_level ] ) : ReturnType

The header about Content-Encoding will be added automatically.

Parameters

compress_level

Return Values


Set the HTTP response headers.

  • « Swoole\Http\Response::gzip
  • Swoole\Http\Response::initHeader »
  • PHP Manual
  • Swoole\Http\Response
  • Set the HTTP response headers.

Swoole\Http\Response::header

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Http\Response::header — Set the HTTP response headers.

Description

public Swoole\Http\Response::header ( string $key , string $value [, string $ucwords ] ) : void

Parameters

key

value

ucwords

Return Values


Init the HTTP response header.

  • « Swoole\Http\Response::header
  • Swoole\Http\Response::rawcookie »
  • PHP Manual
  • Swoole\Http\Response
  • Init the HTTP response header.

Swoole\Http\Response::initHeader

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Http\Response::initHeader — Init the HTTP response header.

Description

public Swoole\Http\Response::initHeader ( void ) : ReturnType

Init the HTTP response header.

Parameters

This function has no parameters.

Return Values


Set the raw cookies to the HTTP response.

  • « Swoole\Http\Response::initHeader
  • Swoole\Http\Response::sendfile »
  • PHP Manual
  • Swoole\Http\Response
  • Set the raw cookies to the HTTP response.

Swoole\Http\Response::rawcookie

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Http\Response::rawcookie — Set the raw cookies to the HTTP response.

Description

public Swoole\Http\Response::rawcookie ( string $name [, string $value [, string $expires [, string $path [, string $domain [, string $secure [, string $httponly ]]]]]] ) : ReturnType

Parameters

name

value

expires

path

domain

secure

httponly

Return Values


Send file through the HTTP response.

  • « Swoole\Http\Response::rawcookie
  • Swoole\Http\Response::status »
  • PHP Manual
  • Swoole\Http\Response
  • Send file through the HTTP response.

Swoole\Http\Response::sendfile

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Http\Response::sendfile — Send file through the HTTP response.

Description

public Swoole\Http\Response::sendfile ( string $filename [, int $offset ] ) : ReturnType

Send file through the HTTP response.

Parameters

filename

offset

Return Values


Set the status code of the HTTP response.

  • « Swoole\Http\Response::sendfile
  • Swoole\Http\Response::write »
  • PHP Manual
  • Swoole\Http\Response
  • Set the status code of the HTTP response.

Swoole\Http\Response::status

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Http\Response::status — Set the status code of the HTTP response.

Description

public Swoole\Http\Response::status ( string $http_code ) : ReturnType

Set the status code of the HTTP response.

Parameters

http_code

Return Values


Append HTTP body content to the HTTP response.

  • « Swoole\Http\Response::status
  • Swoole\Http\Server »
  • PHP Manual
  • Swoole\Http\Response
  • Append HTTP body content to the HTTP response.

Swoole\Http\Response::write

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Http\Response::write — Append HTTP body content to the HTTP response.

Description

public Swoole\Http\Response::write ( string $content ) : void

Append HTTP body content to the HTTP response.

Parameters

content

Return Values


The Swoole\Http\Server class

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Introduction

Class synopsis

Swoole\Http\Server extends Swoole\Server {
/* Methods */
public on ( string $event_name , callable $callback ) : void
public start ( void ) : void
/* Inherited methods */
public Swoole\Server::addlistener ( string $host , integer $port , string $socket_type ) : void
public Swoole\Server::addProcess ( swoole_process $process ) : boolean
public Swoole\Server::after ( integer $after_time_ms , callable $callback [, string $param ] ) : ReturnType
public Swoole\Server::bind ( integer $fd , integer $uid ) : boolean
public Swoole\Server::clearTimer ( integer $timer_id ) : void
swoole_timer_clear ( integer $timer_id ) : void
public Swoole\Server::close ( integer $fd [, boolean $reset ] ) : boolean
public Swoole\Server::confirm ( integer $fd ) : boolean
public Swoole\Server::connection_info ( integer $fd [, integer $reactor_id ] ) : array
public Swoole\Server::connection_list ( integer $start_fd [, integer $pagesize ] ) : array
public Swoole\Server::defer ( callable $callback ) : void
public Swoole\Server\Port::__destruct ( void ) : void
public Swoole\Server\Port::on ( string $event_name , callable $callback ) : ReturnType
public Swoole\Server\Port::set ( array $settings ) : void
public Swoole\Server::exist ( integer $fd ) : boolean
public Swoole\Server::finish ( string $data ) : void
public Swoole\Server::getClientInfo ( integer $fd [, integer $reactor_id ] ) : ReturnType
public Swoole\Server::getClientList ( integer $start_fd [, integer $pagesize ] ) : array
public Swoole\Server::getLastError ( void ) : integer
public Swoole\Server::heartbeat ( boolean $if_close_connection ) : mixed
public Swoole\Server::listen ( string $host , integer $port , string $socket_type ) : boolean
public Swoole\Server::on ( string $event_name , callable $callback ) : void
public Swoole\Server::pause ( integer $fd ) : void
public Swoole\Server::protect ( integer $fd [, boolean $is_protected ] ) : void
public Swoole\Server::reload ( void ) : boolean
public Swoole\Server::resume ( integer $fd ) : void
public Swoole\Server::send ( integer $fd , string $data [, integer $reactor_id ] ) : boolean
public Swoole\Server::sendfile ( integer $fd , string $filename [, integer $offset ] ) : boolean
public Swoole\Server::sendMessage ( integer $worker_id , string $data ) : boolean
public Swoole\Server::sendto ( string $ip , integer $port , string $data [, string $server_socket ] ) : boolean
public Swoole\Server::sendwait ( integer $fd , string $data ) : boolean
public Swoole\Server::set ( array $settings ) : ReturnType
public Swoole\Server::shutdown ( void ) : void
public Swoole\Server::start ( void ) : void
public Swoole\Server::stats ( void ) : array
public Swoole\Server::stop ([ integer $worker_id ] ) : boolean
public Swoole\Server::task ( string $data [, integer $dst_worker_id [, callable $callback ]] ) : mixed
public Swoole\Server::taskwait ( string $data [, float $timeout [, integer $worker_id ]] ) : void
public Swoole\Server::taskWaitMulti ( array $tasks [, double $timeout_ms ] ) : void
public Swoole\Server::tick ( integer $interval_ms , callable $callback ) : void
}

Table of Contents

  • Swoole\Http\Server::on — Bind callback function to HTTP server by event name.
  • Swoole\Http\Server::start — Start the swoole http server.


Bind callback function to HTTP server by event name.

  • « Swoole\Http\Server
  • Swoole\Http\Server::start »
  • PHP Manual
  • Swoole\Http\Server
  • Bind callback function to HTTP server by event name.

Swoole\Http\Server::on

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Http\Server::on — Bind callback function to HTTP server by event name.

Description

public Swoole\Http\Server::on ( string $event_name , callable $callback ) : void

Bind callback function to HTTP server by event name.

Parameters

event_name

callback

Return Values


Start the swoole http server.

  • « Swoole\Http\Server::on
  • Swoole\Lock »
  • PHP Manual
  • Swoole\Http\Server
  • Start the swoole http server.

Swoole\Http\Server::start

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Http\Server::start — Start the swoole http server.

Description

public Swoole\Http\Server::start ( void ) : void

Start the swoole http server.

Parameters

This function has no parameters.

Return Values


The Swoole\Lock class

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Introduction

Class synopsis

Swoole\Lock {
/* Methods */
public __destruct ( void ) : void
public lock_read ( void ) : void
public lock ( void ) : void
public trylock_read ( void ) : void
public trylock ( void ) : void
public unlock ( void ) : void
}

Table of Contents

  • Swoole\Lock::__construct — Construct a memory lock.
  • Swoole\Lock::__destruct — Destory a Swoole memory lock.
  • Swoole\Lock::lock_read — Lock a read-write lock for reading.
  • Swoole\Lock::lock — Try to acquire the lock. It will block if the lock is not available.
  • Swoole\Lock::trylock_read — Try to lock a read-write lock for reading and return straight away even the lock is not available.
  • Swoole\Lock::trylock — Try to acquire the lock and return straight away even the lock is not available.
  • Swoole\Lock::unlock — Release the lock.


Construct a memory lock.

  • « Swoole\Lock
  • Swoole\Lock::__destruct »
  • PHP Manual
  • Swoole\Lock
  • Construct a memory lock.

Swoole\Lock::__construct

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Lock::__construct — Construct a memory lock.

Description

public Swoole\Lock::__construct ([ string $type [, string $file_lock_location ]] )

Swoole lock is used for data synchronization between multiple theads or processes.

Parameters

type

file_lock_location


Destory a Swoole memory lock.

  • « Swoole\Lock::__construct
  • Swoole\Lock::lock_read »
  • PHP Manual
  • Swoole\Lock
  • Destory a Swoole memory lock.

Swoole\Lock::__destruct

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Lock::__destruct — Destory a Swoole memory lock.

Description

public Swoole\Lock::__destruct ( void ) : void

Parameters

This function has no parameters.

Return Values


Lock a read-write lock for reading.

  • « Swoole\Lock::__destruct
  • Swoole\Lock::lock »
  • PHP Manual
  • Swoole\Lock
  • Lock a read-write lock for reading.

Swoole\Lock::lock_read

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Lock::lock_read — Lock a read-write lock for reading.

Description

public Swoole\Lock::lock_read ( void ) : void

Lock a read-write lock for reading.

Parameters

This function has no parameters.

Return Values


Try to acquire the lock. It will block if the lock is not available.

  • « Swoole\Lock::lock_read
  • Swoole\Lock::trylock_read »
  • PHP Manual
  • Swoole\Lock
  • Try to acquire the lock. It will block if the lock is not available.

Swoole\Lock::lock

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Lock::lock — Try to acquire the lock. It will block if the lock is not available.

Description

public Swoole\Lock::lock ( void ) : void

Parameters

This function has no parameters.

Return Values


Try to lock a read-write lock for reading and return straight away even the lock is not available.

  • « Swoole\Lock::lock
  • Swoole\Lock::trylock »
  • PHP Manual
  • Swoole\Lock
  • Try to lock a read-write lock for reading and return straight away even the lock is not available.

Swoole\Lock::trylock_read

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Lock::trylock_read — Try to lock a read-write lock for reading and return straight away even the lock is not available.

Description

public Swoole\Lock::trylock_read ( void ) : void

Parameters

This function has no parameters.

Return Values


Try to acquire the lock and return straight away even the lock is not available.

  • « Swoole\Lock::trylock_read
  • Swoole\Lock::unlock »
  • PHP Manual
  • Swoole\Lock
  • Try to acquire the lock and return straight away even the lock is not available.

Swoole\Lock::trylock

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Lock::trylock — Try to acquire the lock and return straight away even the lock is not available.

Description

public Swoole\Lock::trylock ( void ) : void

Parameters

This function has no parameters.

Return Values


Release the lock.

  • « Swoole\Lock::trylock
  • Swoole\Mmap »
  • PHP Manual
  • Swoole\Lock
  • Release the lock.

Swoole\Lock::unlock

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Lock::unlock — Release the lock.

Description

public Swoole\Lock::unlock ( void ) : void

Parameters

This function has no parameters.

Return Values


The Swoole\Mmap class

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Introduction

Class synopsis

Swoole\Mmap {
/* Methods */
public static open ( string $filename [, string $size [, string $offset ]] ) : ReturnType
}

Table of Contents

  • Swoole\Mmap::open — Map a file into memory and return the stream resource which can be used by PHP stream operations.


Map a file into memory and return the stream resource which can be used by PHP stream operations.

  • « Swoole\Mmap
  • Swoole\MySQL »
  • PHP Manual
  • Swoole\Mmap
  • Map a file into memory and return the stream resource which can be used by PHP stream operations.

Swoole\Mmap::open

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Mmap::open — Map a file into memory and return the stream resource which can be used by PHP stream operations.

Description

public static Swoole\Mmap::open ( string $filename [, string $size [, string $offset ]] ) : ReturnType

Parameters

filename

size

offset

Return Values


The Swoole\MySQL class

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Introduction

Class synopsis

Swoole\MySQL {
/* Methods */
public close ( void ) : void
public connect ( array $server_config , callable $callback ) : void
public __destruct ( void ) : void
public getBuffer ( void ) : ReturnType
public on ( string $event_name , callable $callback ) : void
public query ( string $sql , callable $callback ) : ReturnType
}

Table of Contents

  • Swoole\MySQL::close — Close the async MySQL connection.
  • Swoole\MySQL::connect — Connect to the remote MySQL server.
  • Swoole\MySQL::__construct — Construct an async MySQL client.
  • Swoole\MySQL::__destruct — Destory the async MySQL client.
  • Swoole\MySQL::getBuffer — Description
  • Swoole\MySQL::on — Register callback function based on event name.
  • Swoole\MySQL::query — Run the SQL query.


Close the async MySQL connection.

  • « Swoole\MySQL
  • Swoole\MySQL::connect »
  • PHP Manual
  • Swoole\MySQL
  • Close the async MySQL connection.

Swoole\MySQL::close

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\MySQL::close — Close the async MySQL connection.

Description

public Swoole\MySQL::close ( void ) : void

Parameters

This function has no parameters.

Return Values


Connect to the remote MySQL server.

  • « Swoole\MySQL::close
  • Swoole\MySQL::__construct »
  • PHP Manual
  • Swoole\MySQL
  • Connect to the remote MySQL server.

Swoole\MySQL::connect

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\MySQL::connect — Connect to the remote MySQL server.

Description

public Swoole\MySQL::connect ( array $server_config , callable $callback ) : void

Connect to the remote MySQL server.

Parameters

server_config

callback

Return Values


Construct an async MySQL client.

  • « Swoole\MySQL::connect
  • Swoole\MySQL::__destruct »
  • PHP Manual
  • Swoole\MySQL
  • Construct an async MySQL client.

Swoole\MySQL::__construct

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\MySQL::__construct — Construct an async MySQL client.

Description

public Swoole\MySQL::__construct ( void )

Construct an async MySQL client.

Parameters

This function has no parameters.


Destory the async MySQL client.

  • « Swoole\MySQL::__construct
  • Swoole\MySQL::getBuffer »
  • PHP Manual
  • Swoole\MySQL
  • Destory the async MySQL client.

Swoole\MySQL::__destruct

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\MySQL::__destruct — Destory the async MySQL client.

Description

public Swoole\MySQL::__destruct ( void ) : void

Parameters

This function has no parameters.

Return Values


Description

  • « Swoole\MySQL::__destruct
  • Swoole\MySQL::on »
  • PHP Manual
  • Swoole\MySQL
  • Description

Swoole\MySQL::getBuffer

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\MySQL::getBuffer — Description

Description

public Swoole\MySQL::getBuffer ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Register callback function based on event name.

  • « Swoole\MySQL::getBuffer
  • Swoole\MySQL::query »
  • PHP Manual
  • Swoole\MySQL
  • Register callback function based on event name.

Swoole\MySQL::on

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\MySQL::on — Register callback function based on event name.

Description

public Swoole\MySQL::on ( string $event_name , callable $callback ) : void

Register callback function based on event name, current only 'close' event is supported.

Parameters

event_name

callback

Return Values


Run the SQL query.

  • « Swoole\MySQL::on
  • Swoole\MySQL\Exception »
  • PHP Manual
  • Swoole\MySQL
  • Run the SQL query.

Swoole\MySQL::query

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\MySQL::query — Run the SQL query.

Description

public Swoole\MySQL::query ( string $sql , callable $callback ) : ReturnType

Parameters

sql

callback

Return Values


The Swoole\MySQL\Exception class

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Introduction

Class synopsis

Swoole\MySQL\Exception extends Exception implements Throwable {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
}


The Swoole\Process class

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Introduction

Class synopsis

Swoole\Process {
/* Constants */
const integer IPC_NOWAIT = 256 ;
/* Methods */
public static alarm ( integer $interval_usec ) : void
public close ( void ) : void
public static daemon ([ boolean $nochdir [, boolean $noclose ]] ) : void
public __destruct ( void ) : void
public exec ( string $exec_file , string $args ) : ReturnType
public exit ([ string $exit_code ] ) : void
public freeQueue ( void ) : void
public static kill ( integer $pid [, string $signal_no ] ) : void
public name ( string $process_name ) : void
public pop ([ integer $maxsize ] ) : mixed
public push ( string $data ) : boolean
public read ([ integer $maxsize ] ) : string
public static signal ( string $signal_no , callable $callback ) : void
public start ( void ) : void
public statQueue ( void ) : array
public useQueue ( integer $key [, integer $mode ] ) : boolean
public static wait ([ boolean $blocking ] ) : array
public write ( string $data ) : integer
}

Predefined Constants

Swoole\Process::IPC_NOWAIT

Table of Contents

  • Swoole\Process::alarm — High precision timer which triggers signal with fixed interval.
  • Swoole\Process::close — Close the pipe to the child process.
  • Swoole\Process::__construct — Construct a process.
  • Swoole\Process::daemon — Change the process to be a daemon process.
  • Swoole\Process::__destruct — Destory the process.
  • Swoole\Process::exec — Execute system commands.
  • Swoole\Process::exit — Stop the child processes.
  • Swoole\Process::freeQueue — Destroy the message queue created by swoole_process::useQueue.
  • Swoole\Process::kill — Send signal to the child process.
  • Swoole\Process::name — Set name of the process.
  • Swoole\Process::pop — Read and pop data from the message queue.
  • Swoole\Process::push — Write and push data into the message queue.
  • Swoole\Process::read — Read data sending to the process.
  • Swoole\Process::signal — Send signal to the child processes.
  • Swoole\Process::start — Start the process.
  • Swoole\Process::statQueue — Get the stats of the message queue used as the communication method between processes.
  • Swoole\Process::useQueue — Create a message queue as the communication method between the parent process and child processes.
  • Swoole\Process::wait — Wait for the events of child processes.
  • Swoole\Process::write — Write data into the pipe and communicate with the parent process or child processes.


High precision timer which triggers signal with fixed interval.

  • « Swoole\Process
  • Swoole\Process::close »
  • PHP Manual
  • Swoole\Process
  • High precision timer which triggers signal with fixed interval.

Swoole\Process::alarm

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Process::alarm — High precision timer which triggers signal with fixed interval.

Description

public static Swoole\Process::alarm ( integer $interval_usec ) : void

Parameters

interval_usec

Return Values


Close the pipe to the child process.

  • « Swoole\Process::alarm
  • Swoole\Process::__construct »
  • PHP Manual
  • Swoole\Process
  • Close the pipe to the child process.

Swoole\Process::close

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Process::close — Close the pipe to the child process.

Description

public Swoole\Process::close ( void ) : void

Close the pipe to the child process.

Parameters

This function has no parameters.

Return Values


Construct a process.

  • « Swoole\Process::close
  • Swoole\Process::daemon »
  • PHP Manual
  • Swoole\Process
  • Construct a process.

Swoole\Process::__construct

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Process::__construct — Construct a process.

Description

public Swoole\Process::__construct ( callable $callback [, boolean $redirect_stdin_and_stdout [, integer $pipe_type ]] )

Parameters

callback

redirect_stdin_and_stdout

pipe_type


Change the process to be a daemon process.

  • « Swoole\Process::__construct
  • Swoole\Process::__destruct »
  • PHP Manual
  • Swoole\Process
  • Change the process to be a daemon process.

Swoole\Process::daemon

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Process::daemon — Change the process to be a daemon process.

Description

public static Swoole\Process::daemon ([ boolean $nochdir [, boolean $noclose ]] ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

nochdir

noclose

Return Values


Destory the process.

  • « Swoole\Process::daemon
  • Swoole\Process::exec »
  • PHP Manual
  • Swoole\Process
  • Destory the process.

Swoole\Process::__destruct

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Process::__destruct — Destory the process.

Description

public Swoole\Process::__destruct ( void ) : void

Parameters

This function has no parameters.

Return Values


Execute system commands.

  • « Swoole\Process::__destruct
  • Swoole\Process::exit »
  • PHP Manual
  • Swoole\Process
  • Execute system commands.

Swoole\Process::exec

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Process::exec — Execute system commands.

Description

public Swoole\Process::exec ( string $exec_file , string $args ) : ReturnType

The process will be replaced to be the system command process, but the pipe to the parent process will be kept.

Parameters

exec_file

args

Return Values


Stop the child processes.

  • « Swoole\Process::exec
  • Swoole\Process::freeQueue »
  • PHP Manual
  • Swoole\Process
  • Stop the child processes.

Swoole\Process::exit

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Process::exit — Stop the child processes.

Description

public Swoole\Process::exit ([ string $exit_code ] ) : void

Parameters

exit_code

Return Values


Destroy the message queue created by swoole_process::useQueue.

  • « Swoole\Process::exit
  • Swoole\Process::kill »
  • PHP Manual
  • Swoole\Process
  • Destroy the message queue created by swoole_process::useQueue.

Swoole\Process::freeQueue

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Process::freeQueue — Destroy the message queue created by swoole_process::useQueue.

Description

public Swoole\Process::freeQueue ( void ) : void

Parameters

This function has no parameters.

Return Values


Send signal to the child process.

  • « Swoole\Process::freeQueue
  • Swoole\Process::name »
  • PHP Manual
  • Swoole\Process
  • Send signal to the child process.

Swoole\Process::kill

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Process::kill — Send signal to the child process.

Description

public static Swoole\Process::kill ( integer $pid [, string $signal_no ] ) : void

Send signal to the child process.

Parameters

pid

signal_no

Return Values


Set name of the process.

  • « Swoole\Process::kill
  • Swoole\Process::pop »
  • PHP Manual
  • Swoole\Process
  • Set name of the process.

Swoole\Process::name

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Process::name — Set name of the process.

Description

public Swoole\Process::name ( string $process_name ) : void

Parameters

process_name

Return Values


Read and pop data from the message queue.

  • « Swoole\Process::name
  • Swoole\Process::push »
  • PHP Manual
  • Swoole\Process
  • Read and pop data from the message queue.

Swoole\Process::pop

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Process::pop — Read and pop data from the message queue.

Description

public Swoole\Process::pop ([ integer $maxsize ] ) : mixed

Parameters

maxsize

Return Values


Write and push data into the message queue.

  • « Swoole\Process::pop
  • Swoole\Process::read »
  • PHP Manual
  • Swoole\Process
  • Write and push data into the message queue.

Swoole\Process::push

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Process::push — Write and push data into the message queue.

Description

public Swoole\Process::push ( string $data ) : boolean

Parameters

data

Return Values


Read data sending to the process.

  • « Swoole\Process::push
  • Swoole\Process::signal »
  • PHP Manual
  • Swoole\Process
  • Read data sending to the process.

Swoole\Process::read

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Process::read — Read data sending to the process.

Description

public Swoole\Process::read ([ integer $maxsize ] ) : string

Parameters

maxsize

Return Values


Send signal to the child processes.

  • « Swoole\Process::read
  • Swoole\Process::start »
  • PHP Manual
  • Swoole\Process
  • Send signal to the child processes.

Swoole\Process::signal

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Process::signal — Send signal to the child processes.

Description

public static Swoole\Process::signal ( string $signal_no , callable $callback ) : void

Parameters

signal_no

callback

Return Values

If signal sent successfully, it returns TRUE, otherwise it returns FALSE.


Start the process.

  • « Swoole\Process::signal
  • Swoole\Process::statQueue »
  • PHP Manual
  • Swoole\Process
  • Start the process.

Swoole\Process::start

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Process::start — Start the process.

Description

public Swoole\Process::start ( void ) : void

Parameters

This function has no parameters.

Return Values


Get the stats of the message queue used as the communication method between processes.

  • « Swoole\Process::start
  • Swoole\Process::useQueue »
  • PHP Manual
  • Swoole\Process
  • Get the stats of the message queue used as the communication method between processes.

Swoole\Process::statQueue

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Process::statQueue — Get the stats of the message queue used as the communication method between processes.

Description

public Swoole\Process::statQueue ( void ) : array

Parameters

This function has no parameters.

Return Values

The array of status of the message queue.


Create a message queue as the communication method between the parent process and child processes.

  • « Swoole\Process::statQueue
  • Swoole\Process::wait »
  • PHP Manual
  • Swoole\Process
  • Create a message queue as the communication method between the parent process and child processes.

Swoole\Process::useQueue

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Process::useQueue — Create a message queue as the communication method between the parent process and child processes.

Description

public Swoole\Process::useQueue ( integer $key [, integer $mode ] ) : boolean

Parameters

key

mode

Return Values


Wait for the events of child processes.

  • « Swoole\Process::useQueue
  • Swoole\Process::write »
  • PHP Manual
  • Swoole\Process
  • Wait for the events of child processes.

Swoole\Process::wait

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Process::wait — Wait for the events of child processes.

Description

public static Swoole\Process::wait ([ boolean $blocking ] ) : array

Parameters

blocking

Return Values


Write data into the pipe and communicate with the parent process or child processes.

  • « Swoole\Process::wait
  • Swoole\Redis\Server »
  • PHP Manual
  • Swoole\Process
  • Write data into the pipe and communicate with the parent process or child processes.

Swoole\Process::write

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Process::write — Write data into the pipe and communicate with the parent process or child processes.

Description

public Swoole\Process::write ( string $data ) : integer

Parameters

data

Return Values


The Swoole\Redis\Server class

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Introduction

Class synopsis

Swoole\Redis\Server extends Swoole\Server {
/* Constants */
const integer NIL = 1 ;
const integer ERROR = 0 ;
const integer STATUS = 2 ;
const integer INT = 3 ;
const integer STRING = 4 ;
const integer SET = 5 ;
const integer MAP = 6 ;
/* Methods */
public static format ( string $type [, string $value ] ) : ReturnType
public setHandler ( string $command , string $callback [, string $number_of_string_param [, string $type_of_array_param ]] ) : ReturnType
public start ( void ) : ReturnType
/* Inherited methods */
public Swoole\Server::addlistener ( string $host , integer $port , string $socket_type ) : void
public Swoole\Server::addProcess ( swoole_process $process ) : boolean
public Swoole\Server::after ( integer $after_time_ms , callable $callback [, string $param ] ) : ReturnType
public Swoole\Server::bind ( integer $fd , integer $uid ) : boolean
public Swoole\Server::clearTimer ( integer $timer_id ) : void
swoole_timer_clear ( integer $timer_id ) : void
public Swoole\Server::close ( integer $fd [, boolean $reset ] ) : boolean
public Swoole\Server::confirm ( integer $fd ) : boolean
public Swoole\Server::connection_info ( integer $fd [, integer $reactor_id ] ) : array
public Swoole\Server::connection_list ( integer $start_fd [, integer $pagesize ] ) : array
public Swoole\Server::defer ( callable $callback ) : void
public Swoole\Server\Port::__destruct ( void ) : void
public Swoole\Server\Port::on ( string $event_name , callable $callback ) : ReturnType
public Swoole\Server\Port::set ( array $settings ) : void
public Swoole\Server::exist ( integer $fd ) : boolean
public Swoole\Server::finish ( string $data ) : void
public Swoole\Server::getClientInfo ( integer $fd [, integer $reactor_id ] ) : ReturnType
public Swoole\Server::getClientList ( integer $start_fd [, integer $pagesize ] ) : array
public Swoole\Server::getLastError ( void ) : integer
public Swoole\Server::heartbeat ( boolean $if_close_connection ) : mixed
public Swoole\Server::listen ( string $host , integer $port , string $socket_type ) : boolean
public Swoole\Server::on ( string $event_name , callable $callback ) : void
public Swoole\Server::pause ( integer $fd ) : void
public Swoole\Server::protect ( integer $fd [, boolean $is_protected ] ) : void
public Swoole\Server::reload ( void ) : boolean
public Swoole\Server::resume ( integer $fd ) : void
public Swoole\Server::send ( integer $fd , string $data [, integer $reactor_id ] ) : boolean
public Swoole\Server::sendfile ( integer $fd , string $filename [, integer $offset ] ) : boolean
public Swoole\Server::sendMessage ( integer $worker_id , string $data ) : boolean
public Swoole\Server::sendto ( string $ip , integer $port , string $data [, string $server_socket ] ) : boolean
public Swoole\Server::sendwait ( integer $fd , string $data ) : boolean
public Swoole\Server::set ( array $settings ) : ReturnType
public Swoole\Server::shutdown ( void ) : void
public Swoole\Server::start ( void ) : void
public Swoole\Server::stats ( void ) : array
public Swoole\Server::stop ([ integer $worker_id ] ) : boolean
public Swoole\Server::task ( string $data [, integer $dst_worker_id [, callable $callback ]] ) : mixed
public Swoole\Server::taskwait ( string $data [, float $timeout [, integer $worker_id ]] ) : void
public Swoole\Server::taskWaitMulti ( array $tasks [, double $timeout_ms ] ) : void
public Swoole\Server::tick ( integer $interval_ms , callable $callback ) : void
}

Predefined Constants

Swoole\Redis\Server::NIL

Swoole\Redis\Server::ERROR

Swoole\Redis\Server::STATUS

Swoole\Redis\Server::INT

Swoole\Redis\Server::STRING

Swoole\Redis\Server::SET

Swoole\Redis\Server::MAP

Table of Contents

  • Swoole\Redis\Server::format — Description
  • Swoole\Redis\Server::setHandler — Description
  • Swoole\Redis\Server::start — Description


Description

  • « Swoole\Redis\Server
  • Swoole\Redis\Server::setHandler »
  • PHP Manual
  • Swoole\Redis\Server
  • Description

Swoole\Redis\Server::format

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Redis\Server::format — Description

Description

public static Swoole\Redis\Server::format ( string $type [, string $value ] ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

type

value

Return Values


Description

  • « Swoole\Redis\Server::format
  • Swoole\Redis\Server::start »
  • PHP Manual
  • Swoole\Redis\Server
  • Description

Swoole\Redis\Server::setHandler

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Redis\Server::setHandler — Description

Description

public Swoole\Redis\Server::setHandler ( string $command , string $callback [, string $number_of_string_param [, string $type_of_array_param ]] ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

command

callback

number_of_string_param

type_of_array_param

Return Values


Description

  • « Swoole\Redis\Server::setHandler
  • Swoole\Serialize »
  • PHP Manual
  • Swoole\Redis\Server
  • Description

Swoole\Redis\Server::start

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Redis\Server::start — Description

Description

public Swoole\Redis\Server::start ( void ) : ReturnType

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The Swoole\Serialize class

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Introduction

Class synopsis

Swoole\Serialize {
/* Methods */
public static pack ( string $data [, int $is_fast ] ) : ReturnType
public static unpack ( string $data [, string $args ] ) : ReturnType
}

Table of Contents

  • Swoole\Serialize::pack — Serialize the data.
  • Swoole\Serialize::unpack — Unserialize the data.


Serialize the data.

  • « Swoole\Serialize
  • Swoole\Serialize::unpack »
  • PHP Manual
  • Swoole\Serialize
  • Serialize the data.

Swoole\Serialize::pack

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Serialize::pack — Serialize the data.

Description

public static Swoole\Serialize::pack ( string $data [, int $is_fast ] ) : ReturnType

Swoole provides a fast and high performance serialization module.

Parameters

data

is_fast

Return Values


Unserialize the data.

  • « Swoole\Serialize::pack
  • Swoole\Server »
  • PHP Manual
  • Swoole\Serialize
  • Unserialize the data.

Swoole\Serialize::unpack

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Serialize::unpack — Unserialize the data.

Description

public static Swoole\Serialize::unpack ( string $data [, string $args ] ) : ReturnType

Unserialize the data.

Parameters

string

args

Return Values


The Swoole\Server class

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Introduction

Class synopsis

Swoole\Server {
/* Methods */
public addlistener ( string $host , integer $port , string $socket_type ) : void
public addProcess ( swoole_process $process ) : boolean
public after ( integer $after_time_ms , callable $callback [, string $param ] ) : ReturnType
public bind ( integer $fd , integer $uid ) : boolean
public clearTimer ( integer $timer_id ) : void
swoole_timer_clear ( integer $timer_id ) : void
public close ( integer $fd [, boolean $reset ] ) : boolean
public confirm ( integer $fd ) : boolean
public connection_info ( integer $fd [, integer $reactor_id ] ) : array
public connection_list ( integer $start_fd [, integer $pagesize ] ) : array
public defer ( callable $callback ) : void
public Swoole\Server\Port::__destruct ( void ) : void
public Swoole\Server\Port::on ( string $event_name , callable $callback ) : ReturnType
public Swoole\Server\Port::set ( array $settings ) : void
public exist ( integer $fd ) : boolean
public finish ( string $data ) : void
public getClientInfo ( integer $fd [, integer $reactor_id ] ) : ReturnType
public getClientList ( integer $start_fd [, integer $pagesize ] ) : array
public getLastError ( void ) : integer
public heartbeat ( boolean $if_close_connection ) : mixed
public listen ( string $host , integer $port , string $socket_type ) : boolean
public on ( string $event_name , callable $callback ) : void
public pause ( integer $fd ) : void
public protect ( integer $fd [, boolean $is_protected ] ) : void
public reload ( void ) : boolean
public resume ( integer $fd ) : void
public send ( integer $fd , string $data [, integer $reactor_id ] ) : boolean
public sendfile ( integer $fd , string $filename [, integer $offset ] ) : boolean
public sendMessage ( integer $worker_id , string $data ) : boolean
public sendto ( string $ip , integer $port , string $data [, string $server_socket ] ) : boolean
public sendwait ( integer $fd , string $data ) : boolean
public set ( array $settings ) : ReturnType
public shutdown ( void ) : void
public start ( void ) : void
public stats ( void ) : array
public stop ([ integer $worker_id ] ) : boolean
public task ( string $data [, integer $dst_worker_id [, callable $callback ]] ) : mixed
public taskwait ( string $data [, float $timeout [, integer $worker_id ]] ) : void
public taskWaitMulti ( array $tasks [, double $timeout_ms ] ) : void
public tick ( integer $interval_ms , callable $callback ) : void
}

Table of Contents

  • Swoole\Server::addlistener — Add a new listener to the server.
  • Swoole\Server::addProcess — Add a user defined swoole_process to the server.
  • Swoole\Server::after — Trigger a callback function after a period of time.
  • Swoole\Server::bind — Bind the connection to a user defined user ID.
  • Swoole\Server::clearTimer — Stop and destory a timer.
  • Swoole\Server::close — Close a connection to the client.
  • Swoole\Server::confirm — Check status of the connection.
  • Swoole\Server::connection_info — Get the connection info by file description.
  • Swoole\Server::connection_list — Get all of the established connections.
  • Swoole\Server::__construct — Construct a Swoole server.
  • Swoole\Server::defer — Delay execution of the callback function at the end of current EventLoop.
  • Swoole\Server\Port::__construct — Construct a server port
  • Swoole\Server\Port::__destruct — Destory server port
  • Swoole\Server\Port::on — Register callback functions by event.
  • Swoole\Server\Port::set — Set protocol of the server port.
  • Swoole\Server::exist — Check if the connection is existed.
  • Swoole\Server::finish — Used in task process for sending result to the worker process when the task is finished.
  • Swoole\Server::getClientInfo — Get the connection info by file description.
  • Swoole\Server::getClientList — Get all of the established connections.
  • Swoole\Server::getLastError — Get the error code of the most recent error.
  • Swoole\Server::heartbeat — Check all the connections on the server.
  • Swoole\Server::listen — Listen on the given IP and port, socket type.
  • Swoole\Server::on — Register a callback function by event name.
  • Swoole\Server::pause — Stop receiving data from the connection.
  • Swoole\Server::protect — Set the connection to be protected mode.
  • Swoole\Server::reload — Restart all the worker process.
  • Swoole\Server::resume — Start receving data from the connection.
  • Swoole\Server::send — Send data to the client.
  • Swoole\Server::sendfile — Send file to the connection.
  • Swoole\Server::sendMessage — Send message to worker processes by ID.
  • Swoole\Server::sendto — Send data to the remote UDP address.
  • Swoole\Server::sendwait — Send data to the remote socket in the blocking way.
  • Swoole\Server::set — Set the runtime settings of the swoole server.
  • Swoole\Server::shutdown — Shutdown the master server process, this function can be called in worker processes.
  • Swoole\Server::start — Start the Swoole server.
  • Swoole\Server::stats — Get the stats of the Swoole server.
  • Swoole\Server::stop — Stop the Swoole server.
  • Swoole\Server::task — Send data to the task worker processes.
  • Swoole\Server::taskwait — Send data to the task worker processes in blocking way.
  • Swoole\Server::taskWaitMulti — Execute multiple tasks concurrently.
  • Swoole\Server::tick — Repeats a given function at every given time-interval.


Add a new listener to the server.

  • « Swoole\Server
  • Swoole\Server::addProcess »
  • PHP Manual
  • Swoole\Server
  • Add a new listener to the server.

Swoole\Server::addlistener

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::addlistener — Add a new listener to the server.

Description

public Swoole\Server::addlistener ( string $host , integer $port , string $socket_type ) : void

Parameters

host

port

socket_type

Return Values


Add a user defined swoole_process to the server.

  • « Swoole\Server::addlistener
  • Swoole\Server::after »
  • PHP Manual
  • Swoole\Server
  • Add a user defined swoole_process to the server.

Swoole\Server::addProcess

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::addProcess — Add a user defined swoole_process to the server.

Description

public Swoole\Server::addProcess ( swoole_process $process ) : boolean

Parameters

process

Return Values


Trigger a callback function after a period of time.

  • « Swoole\Server::addProcess
  • Swoole\Server::bind »
  • PHP Manual
  • Swoole\Server
  • Trigger a callback function after a period of time.

Swoole\Server::after

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::after — Trigger a callback function after a period of time.

Description

public Swoole\Server::after ( integer $after_time_ms , callable $callback [, string $param ] ) : ReturnType

Parameters

after_time_ms

callback

param

Return Values


Bind the connection to a user defined user ID.

  • « Swoole\Server::after
  • Swoole\Server::clearTimer »
  • PHP Manual
  • Swoole\Server
  • Bind the connection to a user defined user ID.

Swoole\Server::bind

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::bind — Bind the connection to a user defined user ID.

Description

public Swoole\Server::bind ( integer $fd , integer $uid ) : boolean

Parameters

fd

uid

Return Values


Stop and destory a timer.

  • « Swoole\Server::bind
  • Swoole\Server::close »
  • PHP Manual
  • Swoole\Server
  • Stop and destory a timer.

Swoole\Server::clearTimer

swoole_timer_clear

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::clearTimer -- swoole_timer_clear — Stop and destory a timer.

Description

Object oriented style (method):

public Swoole\Server::clearTimer ( integer $timer_id ) : void

Procedural style:

swoole_timer_clear ( integer $timer_id ) : void

Stop and destory a timer

Parameters

timer_id

Return Values


Close a connection to the client.

  • « Swoole\Server::clearTimer
  • Swoole\Server::confirm »
  • PHP Manual
  • Swoole\Server
  • Close a connection to the client.

Swoole\Server::close

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::close — Close a connection to the client.

Description

public Swoole\Server::close ( integer $fd [, boolean $reset ] ) : boolean

Parameters

fd

reset

Return Values


Check status of the connection.

  • « Swoole\Server::close
  • Swoole\Server::connection_info »
  • PHP Manual
  • Swoole\Server
  • Check status of the connection.

Swoole\Server::confirm

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::confirm — Check status of the connection.

Description

public Swoole\Server::confirm ( integer $fd ) : boolean

Parameters

fd

Return Values


Get the connection info by file description.

  • « Swoole\Server::confirm
  • Swoole\Server::connection_list »
  • PHP Manual
  • Swoole\Server
  • Get the connection info by file description.

Swoole\Server::connection_info

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::connection_info — Get the connection info by file description.

Description

public Swoole\Server::connection_info ( integer $fd [, integer $reactor_id ] ) : array

Parameters

fd

reactor_id

Return Values


Get all of the established connections.

  • « Swoole\Server::connection_info
  • Swoole\Server::__construct »
  • PHP Manual
  • Swoole\Server
  • Get all of the established connections.

Swoole\Server::connection_list

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::connection_list — Get all of the established connections.

Description

public Swoole\Server::connection_list ( integer $start_fd [, integer $pagesize ] ) : array

Parameters

start_fd

pagesize

Return Values


Construct a Swoole server.

  • « Swoole\Server::connection_list
  • Swoole\Server::defer »
  • PHP Manual
  • Swoole\Server
  • Construct a Swoole server.

Swoole\Server::__construct

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::__construct — Construct a Swoole server.

Description

public Swoole\Server::__construct ( string $host [, integer $port [, integr $mode [, integer $sock_type ]]] )

Parameters

host

port

mode

sock_type


Delay execution of the callback function at the end of current EventLoop.

  • « Swoole\Server::__construct
  • Swoole\Server\Port::__construct »
  • PHP Manual
  • Swoole\Server
  • Delay execution of the callback function at the end of current EventLoop.

Swoole\Server::defer

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::defer — Delay execution of the callback function at the end of current EventLoop.

Description

public Swoole\Server::defer ( callable $callback ) : void

Parameters

callback

Return Values


Construct a server port

  • « Swoole\Server::defer
  • Swoole\Server\Port::__destruct »
  • PHP Manual
  • Swoole\Server
  • Construct a server port

Swoole\Server\Port::__construct

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server\Port::__construct — Construct a server port

Description

private Swoole\Server\Port::__construct ( void )

Parameters

This function has no parameters.


Destory server port

  • « Swoole\Server\Port::__construct
  • Swoole\Server\Port::on »
  • PHP Manual
  • Swoole\Server
  • Destory server port

Swoole\Server\Port::__destruct

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server\Port::__destruct — Destory server port

Description

public Swoole\Server\Port::__destruct ( void ) : void

Parameters

This function has no parameters.

Return Values


Register callback functions by event.

  • « Swoole\Server\Port::__destruct
  • Swoole\Server\Port::set »
  • PHP Manual
  • Swoole\Server
  • Register callback functions by event.

Swoole\Server\Port::on

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server\Port::on — Register callback functions by event.

Description

public Swoole\Server\Port::on ( string $event_name , callable $callback ) : ReturnType

Parameters

event_name

callback

Return Values


Set protocol of the server port.

  • « Swoole\Server\Port::on
  • Swoole\Server::exist »
  • PHP Manual
  • Swoole\Server
  • Set protocol of the server port.

Swoole\Server\Port::set

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server\Port::set — Set protocol of the server port.

Description

public Swoole\Server\Port::set ( array $settings ) : void

Parameters

settings

Return Values


Check if the connection is existed.

  • « Swoole\Server\Port::set
  • Swoole\Server::finish »
  • PHP Manual
  • Swoole\Server
  • Check if the connection is existed.

Swoole\Server::exist

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::exist — Check if the connection is existed.

Description

public Swoole\Server::exist ( integer $fd ) : boolean

Parameters

fd

Return Values


Used in task process for sending result to the worker process when the task is finished.

  • « Swoole\Server::exist
  • Swoole\Server::getClientInfo »
  • PHP Manual
  • Swoole\Server
  • Used in task process for sending result to the worker process when the task is finished.

Swoole\Server::finish

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::finish — Used in task process for sending result to the worker process when the task is finished.

Description

public Swoole\Server::finish ( string $data ) : void

Parameters

data

Return Values


Get the connection info by file description.

  • « Swoole\Server::finish
  • Swoole\Server::getClientList »
  • PHP Manual
  • Swoole\Server
  • Get the connection info by file description.

Swoole\Server::getClientInfo

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::getClientInfo — Get the connection info by file description.

Description

public Swoole\Server::getClientInfo ( integer $fd [, integer $reactor_id ] ) : ReturnType

Parameters

fd

reactor_id

Return Values


Get all of the established connections.

  • « Swoole\Server::getClientInfo
  • Swoole\Server::getLastError »
  • PHP Manual
  • Swoole\Server
  • Get all of the established connections.

Swoole\Server::getClientList

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::getClientList — Get all of the established connections.

Description

public Swoole\Server::getClientList ( integer $start_fd [, integer $pagesize ] ) : array

Warning

This function is currently not documented; only its argument list is available.

Parameters

start_fd

pagesize

Return Values


Get the error code of the most recent error.

  • « Swoole\Server::getClientList
  • Swoole\Server::heartbeat »
  • PHP Manual
  • Swoole\Server
  • Get the error code of the most recent error.

Swoole\Server::getLastError

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::getLastError — Get the error code of the most recent error.

Description

public Swoole\Server::getLastError ( void ) : integer

Parameters

This function has no parameters.

Return Values


Check all the connections on the server.

  • « Swoole\Server::getLastError
  • Swoole\Server::listen »
  • PHP Manual
  • Swoole\Server
  • Check all the connections on the server.

Swoole\Server::heartbeat

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::heartbeat — Check all the connections on the server.

Description

public Swoole\Server::heartbeat ( boolean $if_close_connection ) : mixed

Parameters

if_close_connection

Return Values


Listen on the given IP and port, socket type.

  • « Swoole\Server::heartbeat
  • Swoole\Server::on »
  • PHP Manual
  • Swoole\Server
  • Listen on the given IP and port, socket type.

Swoole\Server::listen

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::listen — Listen on the given IP and port, socket type.

Description

public Swoole\Server::listen ( string $host , integer $port , string $socket_type ) : boolean

Parameters

host

port

socket_type

Return Values


Register a callback function by event name.

  • « Swoole\Server::listen
  • Swoole\Server::pause »
  • PHP Manual
  • Swoole\Server
  • Register a callback function by event name.

Swoole\Server::on

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::on — Register a callback function by event name.

Description

public Swoole\Server::on ( string $event_name , callable $callback ) : void

Parameters

event_name

callback

Return Values


Stop receiving data from the connection.

  • « Swoole\Server::on
  • Swoole\Server::protect »
  • PHP Manual
  • Swoole\Server
  • Stop receiving data from the connection.

Swoole\Server::pause

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::pause — Stop receiving data from the connection.

Description

public Swoole\Server::pause ( integer $fd ) : void

Parameters

fd

Return Values


Set the connection to be protected mode.

  • « Swoole\Server::pause
  • Swoole\Server::reload »
  • PHP Manual
  • Swoole\Server
  • Set the connection to be protected mode.

Swoole\Server::protect

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::protect — Set the connection to be protected mode.

Description

public Swoole\Server::protect ( integer $fd [, boolean $is_protected ] ) : void

Parameters

fd

is_protected

Return Values


Restart all the worker process.

  • « Swoole\Server::protect
  • Swoole\Server::resume »
  • PHP Manual
  • Swoole\Server
  • Restart all the worker process.

Swoole\Server::reload

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::reload — Restart all the worker process.

Description

public Swoole\Server::reload ( void ) : boolean

Parameters

This function has no parameters.

Return Values


Start receving data from the connection.

  • « Swoole\Server::reload
  • Swoole\Server::send »
  • PHP Manual
  • Swoole\Server
  • Start receving data from the connection.

Swoole\Server::resume

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::resume — Start receving data from the connection.

Description

public Swoole\Server::resume ( integer $fd ) : void

Parameters

fd

Return Values


Send data to the client.

  • « Swoole\Server::resume
  • Swoole\Server::sendfile »
  • PHP Manual
  • Swoole\Server
  • Send data to the client.

Swoole\Server::send

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::send — Send data to the client.

Description

public Swoole\Server::send ( integer $fd , string $data [, integer $reactor_id ] ) : boolean

Warning

This function is currently not documented; only its argument list is available.

Parameters

fd

data

reactor_id

Return Values


Send file to the connection.

  • « Swoole\Server::send
  • Swoole\Server::sendMessage »
  • PHP Manual
  • Swoole\Server
  • Send file to the connection.

Swoole\Server::sendfile

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::sendfile — Send file to the connection.

Description

public Swoole\Server::sendfile ( integer $fd , string $filename [, integer $offset ] ) : boolean

Warning

This function is currently not documented; only its argument list is available.

Parameters

fd

filename

offset

Return Values


Send message to worker processes by ID.

  • « Swoole\Server::sendfile
  • Swoole\Server::sendto »
  • PHP Manual
  • Swoole\Server
  • Send message to worker processes by ID.

Swoole\Server::sendMessage

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::sendMessage — Send message to worker processes by ID.

Description

public Swoole\Server::sendMessage ( integer $worker_id , string $data ) : boolean

Parameters

dst_worker_id

data

Return Values


Send data to the remote UDP address.

  • « Swoole\Server::sendMessage
  • Swoole\Server::sendwait »
  • PHP Manual
  • Swoole\Server
  • Send data to the remote UDP address.

Swoole\Server::sendto

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::sendto — Send data to the remote UDP address.

Description

public Swoole\Server::sendto ( string $ip , integer $port , string $data [, string $server_socket ] ) : boolean

Parameters

ip

port

data

server_socket

Return Values


Send data to the remote socket in the blocking way.

  • « Swoole\Server::sendto
  • Swoole\Server::set »
  • PHP Manual
  • Swoole\Server
  • Send data to the remote socket in the blocking way.

Swoole\Server::sendwait

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::sendwait — Send data to the remote socket in the blocking way.

Description

public Swoole\Server::sendwait ( integer $fd , string $data ) : boolean

Warning

This function is currently not documented; only its argument list is available.

Parameters

fd

data

Return Values


Set the runtime settings of the swoole server.

  • « Swoole\Server::sendwait
  • Swoole\Server::shutdown »
  • PHP Manual
  • Swoole\Server
  • Set the runtime settings of the swoole server.

Swoole\Server::set

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::set — Set the runtime settings of the swoole server.

Description

public Swoole\Server::set ( array $settings ) : ReturnType

Set the runtime settings of the swoole server. The settings can be accessed by $server->setting when the swoole server has started.

Parameters

settings

Return Values


Shutdown the master server process, this function can be called in worker processes.

  • « Swoole\Server::set
  • Swoole\Server::start »
  • PHP Manual
  • Swoole\Server
  • Shutdown the master server process, this function can be called in worker processes.

Swoole\Server::shutdown

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::shutdown — Shutdown the master server process, this function can be called in worker processes.

Description

public Swoole\Server::shutdown ( void ) : void

Parameters

This function has no parameters.

Return Values


Start the Swoole server.

  • « Swoole\Server::shutdown
  • Swoole\Server::stats »
  • PHP Manual
  • Swoole\Server
  • Start the Swoole server.

Swoole\Server::start

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::start — Start the Swoole server.

Description

public Swoole\Server::start ( void ) : void

Parameters

This function has no parameters.

Return Values


Get the stats of the Swoole server.

  • « Swoole\Server::start
  • Swoole\Server::stop »
  • PHP Manual
  • Swoole\Server
  • Get the stats of the Swoole server.

Swoole\Server::stats

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::stats — Get the stats of the Swoole server.

Description

public Swoole\Server::stats ( void ) : array

Parameters

This function has no parameters.

Return Values


Stop the Swoole server.

  • « Swoole\Server::stats
  • Swoole\Server::task »
  • PHP Manual
  • Swoole\Server
  • Stop the Swoole server.

Swoole\Server::stop

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::stop — Stop the Swoole server.

Description

public Swoole\Server::stop ([ integer $worker_id ] ) : boolean

Parameters

worker_id

Return Values


Send data to the task worker processes.

  • « Swoole\Server::stop
  • Swoole\Server::taskwait »
  • PHP Manual
  • Swoole\Server
  • Send data to the task worker processes.

Swoole\Server::task

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::task — Send data to the task worker processes.

Description

public Swoole\Server::task ( string $data [, integer $dst_worker_id [, callable $callback ]] ) : mixed

Warning

This function is currently not documented; only its argument list is available.

Parameters

data

dst_worker_id

callback

Return Values


Send data to the task worker processes in blocking way.

  • « Swoole\Server::task
  • Swoole\Server::taskWaitMulti »
  • PHP Manual
  • Swoole\Server
  • Send data to the task worker processes in blocking way.

Swoole\Server::taskwait

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::taskwait — Send data to the task worker processes in blocking way.

Description

public Swoole\Server::taskwait ( string $data [, float $timeout [, integer $worker_id ]] ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

data

timeout

worker_id

Return Values


Execute multiple tasks concurrently.

  • « Swoole\Server::taskwait
  • Swoole\Server::tick »
  • PHP Manual
  • Swoole\Server
  • Execute multiple tasks concurrently.

Swoole\Server::taskWaitMulti

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::taskWaitMulti — Execute multiple tasks concurrently.

Description

public Swoole\Server::taskWaitMulti ( array $tasks [, double $timeout_ms ] ) : void

Parameters

tasks

timeout_ms

Return Values


Repeats a given function at every given time-interval.

  • « Swoole\Server::taskWaitMulti
  • Swoole\Table »
  • PHP Manual
  • Swoole\Server
  • Repeats a given function at every given time-interval.

Swoole\Server::tick

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Server::tick — Repeats a given function at every given time-interval.

Description

public Swoole\Server::tick ( integer $interval_ms , callable $callback ) : void

Parameters

interval_ms

callback

Return Values


The Swoole\Table class

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Introduction

Class synopsis

Swoole\Table implements Iterator , Countable {
/* Constants */
const integer TYPE_INT = 1 ;
const integer TYPE_STRING = 7 ;
const integer TYPE_FLOAT = 6 ;
/* Methods */
public column ( string $name , string $type [, integer $size ] ) : ReturnType
public count ( void ) : integer
public create ( void ) : void
public current ( void ) : array
public decr ( string $key , string $column [, integer $decrby ] ) : ReturnType
public del ( string $key ) : void
public destroy ( void ) : void
public exist ( string $key ) : boolean
public get ( string $row_key , string $column_key ) : integer
public incr ( string $key , string $column [, integer $incrby ] ) : void
public key ( void ) : string
public next ( void ) : ReturnType
public rewind ( void ) : void
public set ( string $key , array $value ) : VOID
public valid ( void ) : boolean
}

Predefined Constants

Swoole\Table::TYPE_INT

Swoole\Table::TYPE_STRING

Swoole\Table::TYPE_FLOAT

Table of Contents

  • Swoole\Table::column — Set the data type and size of the columns.
  • Swoole\Table::__construct — Construct a Swoole memory table with fixed size.
  • Swoole\Table::count — Count the rows in the table, or count all the elements in the table if $mode = 1.
  • Swoole\Table::create — Create the swoole memory table.
  • Swoole\Table::current — Get the current row.
  • Swoole\Table::decr — Decrement the value in the Swoole table by $row_key and $column_key.
  • Swoole\Table::del — Delete a row in the Swoole table by $row_key.
  • Swoole\Table::destroy — Destroy the Swoole table.
  • Swoole\Table::exist — Check if a row is existed by $row_key.
  • Swoole\Table::get — Get the value in the Swoole table by $row_key and $column_key.
  • Swoole\Table::incr — Increment the value by $row_key and $column_key.
  • Swoole\Table::key — Get the key of current row.
  • Swoole\Table::next — Iterator the next row.
  • Swoole\Table::rewind — Rewind the iterator.
  • Swoole\Table::set — Update a row of the table by $row_key.
  • Swoole\Table::valid — Check current if the current row is valid.


Set the data type and size of the columns.

  • « Swoole\Table
  • Swoole\Table::__construct »
  • PHP Manual
  • Swoole\Table
  • Set the data type and size of the columns.

Swoole\Table::column

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Table::column — Set the data type and size of the columns.

Description

public Swoole\Table::column ( string $name , string $type [, integer $size ] ) : ReturnType

Parameters

name

type

size

Return Values


Construct a Swoole memory table with fixed size.

  • « Swoole\Table::column
  • Swoole\Table::count »
  • PHP Manual
  • Swoole\Table
  • Construct a Swoole memory table with fixed size.

Swoole\Table::__construct

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Table::__construct — Construct a Swoole memory table with fixed size.

Description

public Swoole\Table::__construct ( integer $table_size )

Parameters

table_size


Count the rows in the table, or count all the elements in the table if $mode = 1.

  • « Swoole\Table::__construct
  • Swoole\Table::create »
  • PHP Manual
  • Swoole\Table
  • Count the rows in the table, or count all the elements in the table if $mode = 1.

Swoole\Table::count

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Table::count — Count the rows in the table, or count all the elements in the table if $mode = 1.

Description

public Swoole\Table::count ( void ) : integer

Parameters

This function has no parameters.

Return Values


Create the swoole memory table.

  • « Swoole\Table::count
  • Swoole\Table::current »
  • PHP Manual
  • Swoole\Table
  • Create the swoole memory table.

Swoole\Table::create

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Table::create — Create the swoole memory table.

Description

public Swoole\Table::create ( void ) : void

Parameters

This function has no parameters.

Return Values


Get the current row.

  • « Swoole\Table::create
  • Swoole\Table::decr »
  • PHP Manual
  • Swoole\Table
  • Get the current row.

Swoole\Table::current

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Table::current — Get the current row.

Description

public Swoole\Table::current ( void ) : array

Parameters

This function has no parameters.

Return Values


Decrement the value in the Swoole table by $row_key and $column_key.

  • « Swoole\Table::current
  • Swoole\Table::del »
  • PHP Manual
  • Swoole\Table
  • Decrement the value in the Swoole table by $row_key and $column_key.

Swoole\Table::decr

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Table::decr — Decrement the value in the Swoole table by $row_key and $column_key.

Description

public Swoole\Table::decr ( string $key , string $column [, integer $decrby ] ) : ReturnType

Parameters

key

column

decrby

Return Values


Delete a row in the Swoole table by $row_key.

  • « Swoole\Table::decr
  • Swoole\Table::destroy »
  • PHP Manual
  • Swoole\Table
  • Delete a row in the Swoole table by $row_key.

Swoole\Table::del

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Table::del — Delete a row in the Swoole table by $row_key.

Description

public Swoole\Table::del ( string $key ) : void

Parameters

key

Return Values


Destroy the Swoole table.

  • « Swoole\Table::del
  • Swoole\Table::exist »
  • PHP Manual
  • Swoole\Table
  • Destroy the Swoole table.

Swoole\Table::destroy

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Table::destroy — Destroy the Swoole table.

Description

public Swoole\Table::destroy ( void ) : void

Parameters

This function has no parameters.

Return Values


Check if a row is existed by $row_key.

  • « Swoole\Table::destroy
  • Swoole\Table::get »
  • PHP Manual
  • Swoole\Table
  • Check if a row is existed by $row_key.

Swoole\Table::exist

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Table::exist — Check if a row is existed by $row_key.

Description

public Swoole\Table::exist ( string $key ) : boolean

Parameters

key

Return Values


Get the value in the Swoole table by $row_key and $column_key.

  • « Swoole\Table::exist
  • Swoole\Table::incr »
  • PHP Manual
  • Swoole\Table
  • Get the value in the Swoole table by $row_key and $column_key.

Swoole\Table::get

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Table::get — Get the value in the Swoole table by $row_key and $column_key.

Description

public Swoole\Table::get ( string $row_key , string $column_key ) : integer

Parameters

row_key

column_key

Return Values


Increment the value by $row_key and $column_key.

  • « Swoole\Table::get
  • Swoole\Table::key »
  • PHP Manual
  • Swoole\Table
  • Increment the value by $row_key and $column_key.

Swoole\Table::incr

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Table::incr — Increment the value by $row_key and $column_key.

Description

public Swoole\Table::incr ( string $key , string $column [, integer $incrby ] ) : void

Parameters

key

column

incrby

Return Values


Get the key of current row.

  • « Swoole\Table::incr
  • Swoole\Table::next »
  • PHP Manual
  • Swoole\Table
  • Get the key of current row.

Swoole\Table::key

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Table::key — Get the key of current row.

Description

public Swoole\Table::key ( void ) : string

Parameters

This function has no parameters.

Return Values


Iterator the next row.

  • « Swoole\Table::key
  • Swoole\Table::rewind »
  • PHP Manual
  • Swoole\Table
  • Iterator the next row.

Swoole\Table::next

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Table::next — Iterator the next row.

Description

public Swoole\Table::next ( void ) : ReturnType

Parameters

This function has no parameters.

Return Values


Rewind the iterator.

  • « Swoole\Table::next
  • Swoole\Table::set »
  • PHP Manual
  • Swoole\Table
  • Rewind the iterator.

Swoole\Table::rewind

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Table::rewind — Rewind the iterator.

Description

public Swoole\Table::rewind ( void ) : void

Parameters

This function has no parameters.

Return Values


Update a row of the table by $row_key.

  • « Swoole\Table::rewind
  • Swoole\Table::valid »
  • PHP Manual
  • Swoole\Table
  • Update a row of the table by $row_key.

Swoole\Table::set

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Table::set — Update a row of the table by $row_key.

Description

public Swoole\Table::set ( string $key , array $value ) : VOID

Parameters

key

value

Return Values


Check current if the current row is valid.

  • « Swoole\Table::set
  • Swoole\Timer »
  • PHP Manual
  • Swoole\Table
  • Check current if the current row is valid.

Swoole\Table::valid

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Table::valid — Check current if the current row is valid.

Description

public Swoole\Table::valid ( void ) : boolean

Parameters

This function has no parameters.

Return Values


The Swoole\Timer class

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Introduction

Class synopsis

Swoole\Timer {
/* Methods */
public static after ( int $after_time_ms , callable $callback ) : void
public static clear ( integer $timer_id ) : void
public static exists ( integer $timer_id ) : boolean
public static tick ( integer $interval_ms , callable $callback [, string $param ] ) : void
}

Table of Contents

  • Swoole\Timer::after — Trigger a callback function after a period of time.
  • Swoole\Timer::clear — Delete a timer by timer ID.
  • Swoole\Timer::exists — Check if a timer is existed.
  • Swoole\Timer::tick — Repeats a given function at every given time-interval.


Trigger a callback function after a period of time.

  • « Swoole\Timer
  • Swoole\Timer::clear »
  • PHP Manual
  • Swoole\Timer
  • Trigger a callback function after a period of time.

Swoole\Timer::after

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Timer::after — Trigger a callback function after a period of time.

Description

public static Swoole\Timer::after ( int $after_time_ms , callable $callback ) : void

Trigger a callback function after a period of time.

Parameters

after_time_ms

callback

Return Values


Delete a timer by timer ID.

  • « Swoole\Timer::after
  • Swoole\Timer::exists »
  • PHP Manual
  • Swoole\Timer
  • Delete a timer by timer ID.

Swoole\Timer::clear

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Timer::clear — Delete a timer by timer ID.

Description

public static Swoole\Timer::clear ( integer $timer_id ) : void

Delete a timer by timer ID.

Parameters

timer_id

Return Values


Check if a timer is existed.

  • « Swoole\Timer::clear
  • Swoole\Timer::tick »
  • PHP Manual
  • Swoole\Timer
  • Check if a timer is existed.

Swoole\Timer::exists

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Timer::exists — Check if a timer is existed.

Description

public static Swoole\Timer::exists ( integer $timer_id ) : boolean

Check if a timer is existed.

Parameters

timer_id

Return Values


Repeats a given function at every given time-interval.

  • « Swoole\Timer::exists
  • Swoole\WebSocket\Frame »
  • PHP Manual
  • Swoole\Timer
  • Repeats a given function at every given time-interval.

Swoole\Timer::tick

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\Timer::tick — Repeats a given function at every given time-interval.

Description

public static Swoole\Timer::tick ( integer $interval_ms , callable $callback [, string $param ] ) : void

Parameters

interval_ms

callback

param

Return Values


The Swoole\WebSocket\Frame class

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Introduction

Class synopsis

Swoole\WebSocket\Frame {
/* Methods */
}


The Swoole\WebSocket\Server class

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Introduction

Class synopsis

Swoole\WebSocket\Server extends Swoole\Http\Server {
/* Methods */
public exist ( integer $fd ) : boolean
public on ( string $event_name , callable $callback ) : ReturnType
public static pack ( string $data [, string $opcode [, string $finish [, string $mask ]]] ) : binary
public push ( string $fd , string $data [, string $opcode [, string $finish ]] ) : void
public static unpack ( binary $data ) : string
/* Inherited methods */
public Swoole\Http\Server::on ( string $event_name , callable $callback ) : void
public Swoole\Http\Server::start ( void ) : void
}

Table of Contents

  • Swoole\WebSocket\Server::exist — Check if the file descriptor exists.
  • Swoole\WebSocket\Server::on — Register event callback function
  • Swoole\WebSocket\Server::pack — Get a pack of binary data to send in a single frame.
  • Swoole\WebSocket\Server::push — Push data to the remote client.
  • Swoole\WebSocket\Server::unpack — Unpack the binary data received from the client.


Check if the file descriptor exists.

  • « Swoole\WebSocket\Server
  • Swoole\WebSocket\Server::on »
  • PHP Manual
  • Swoole\WebSocket\Server
  • Check if the file descriptor exists.

Swoole\WebSocket\Server::exist

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\WebSocket\Server::exist — Check if the file descriptor exists.

Description

public Swoole\WebSocket\Server::exist ( integer $fd ) : boolean

Parameters

fd

Return Values


Register event callback function

  • « Swoole\WebSocket\Server::exist
  • Swoole\WebSocket\Server::pack »
  • PHP Manual
  • Swoole\WebSocket\Server
  • Register event callback function

Swoole\WebSocket\Server::on

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\WebSocket\Server::on — Register event callback function

Description

public Swoole\WebSocket\Server::on ( string $event_name , callable $callback ) : ReturnType

Register event callback function

Parameters

event_name

callback

Return Values


Get a pack of binary data to send in a single frame.

  • « Swoole\WebSocket\Server::on
  • Swoole\WebSocket\Server::push »
  • PHP Manual
  • Swoole\WebSocket\Server
  • Get a pack of binary data to send in a single frame.

Swoole\WebSocket\Server::pack

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\WebSocket\Server::pack — Get a pack of binary data to send in a single frame.

Description

public static Swoole\WebSocket\Server::pack ( string $data [, string $opcode [, string $finish [, string $mask ]]] ) : binary

Parameters

data

opcode

finish

mask

Return Values


Push data to the remote client.

  • « Swoole\WebSocket\Server::pack
  • Swoole\WebSocket\Server::unpack »
  • PHP Manual
  • Swoole\WebSocket\Server
  • Push data to the remote client.

Swoole\WebSocket\Server::push

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\WebSocket\Server::push — Push data to the remote client.

Description

public Swoole\WebSocket\Server::push ( string $fd , string $data [, string $opcode [, string $finish ]] ) : void

Parameters

fd

data

opcode

finish

Return Values


Unpack the binary data received from the client.

  • « Swoole\WebSocket\Server::push
  • Tidy »
  • PHP Manual
  • Swoole\WebSocket\Server
  • Unpack the binary data received from the client.

Swoole\WebSocket\Server::unpack

(PHP 5 >= 5.2.0, PHP 7, PECL swoole >= 1.9.0)

Swoole\WebSocket\Server::unpack — Unpack the binary data received from the client.

Description

public static Swoole\WebSocket\Server::unpack ( binary $data ) : string

Parameters

data

Return Values


Tidy

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Tidy example
  • tidy — The tidy class
    • tidy::body — Returns a tidyNode object starting from the <body> tag of the tidy parse tree
    • tidy::cleanRepair — Execute configured cleanup and repair operations on parsed markup
    • tidy::__construct — Constructs a new tidy object
    • tidy::diagnose — Run configured diagnostics on parsed and repaired markup
    • tidy::$errorBuffer — Return warnings and errors which occurred parsing the specified document
    • tidy::getConfig — Get current Tidy configuration
    • tidy::getHtmlVer — Get the Detected HTML version for the specified document
    • tidy::getOpt — Returns the value of the specified configuration option for the tidy document
    • tidy::getOptDoc — Returns the documentation for the given option name
    • tidy::getRelease — Get release date (version) for Tidy library
    • tidy::getStatus — Get status of specified document
    • tidy::head — Returns a tidyNode object starting from the <head> tag of the tidy parse tree
    • tidy::html — Returns a tidyNode object starting from the <html> tag of the tidy parse tree
    • tidy::isXhtml — Indicates if the document is a XHTML document
    • tidy::isXml — Indicates if the document is a generic (non HTML/XHTML) XML document
    • tidy::parseFile — Parse markup in file or URI
    • tidy::parseString — Parse a document stored in a string
    • tidy::repairFile — Repair a file and return it as a string
    • tidy::repairString — Repair a string using an optionally provided configuration file
    • tidy::root — Returns a tidyNode object representing the root of the tidy parse tree
  • tidyNode — The tidyNode class
    • tidyNode::__construct — Private constructor to disallow direct instantiation
    • tidyNode::getParent — Returns the parent node of the current node
    • tidyNode::hasChildren — Checks if a node has children
    • tidyNode::hasSiblings — Checks if a node has siblings
    • tidyNode::isAsp — Checks if this node is ASP
    • tidyNode::isComment — Checks if a node represents a comment
    • tidyNode::isHtml — Checks if a node is part of a HTML document
    • tidyNode::isJste — Checks if this node is JSTE
    • tidyNode::isPhp — Checks if a node is PHP
    • tidyNode::isText — Checks if a node represents text (no markup)
  • Tidy Functions
    • ob_tidyhandler — ob_start callback function to repair the buffer
    • tidy_access_count — Returns the Number of Tidy accessibility warnings encountered for specified document
    • tidy_config_count — Returns the Number of Tidy configuration errors encountered for specified document
    • tidy_error_count — Returns the Number of Tidy errors encountered for specified document
    • tidy_get_output — Return a string representing the parsed tidy markup
    • tidy_warning_count — Returns the Number of Tidy warnings encountered for specified document


Introduction

Tidy is a binding for the Tidy HTML clean and repair utility which allows you to not only clean and otherwise manipulate HTML, XHTML, and XML documents, but also traverse the document tree, including ones with embedded scripting languages such as PHP or ASP within them using object oriented constructs.


Requirements

To use Tidy, you will need libtidy installed, available on the » tidy homepage. As of PHP 7.1.0, the HTML5 aware successor » libtidy5 can be used alternatively. As of PHP 7.3.0, another option is to use » libtidyp.


Installation

This extension is bundled with PHP 5 and greater, and is installed using the --with-tidy configure option.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Tidy Configuration Options
Name | Default | Changeable | Changelog
tidy.default_config | "" | PHP_INI_SYSTEM |
tidy.clean_output | "0" | PHP_INI_USER | PHP_INI_PERDIR prior to PHP 5.4.0
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

tidy.default_config string

Default path for tidy config file.

tidy.clean_output boolean

Turns on/off the output repairing by Tidy.

Warning

Do not turn on tidy.clean_output if you are generating non-html content such as dynamic images.


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.

Each TIDY_TAG_XXX represents a HTML tag. For example, TIDY_TAG_A represents a "<a href="XX">link</a>" tag.

The following constants are defined:

tidy tag constants
Constant | Notes
TIDY_TAG_UNKNOWN |
TIDY_TAG_A |
TIDY_TAG_ABBR |
TIDY_TAG_ACRONYM |
TIDY_TAG_ALIGN |
TIDY_TAG_APPLET |
TIDY_TAG_AREA |
TIDY_TAG_ARTICLE | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_ASIDE | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_AUDIO | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_B |
TIDY_TAG_BASE |
TIDY_TAG_BASEFONT |
TIDY_TAG_BDI | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_BDO |
TIDY_TAG_BGSOUND |
TIDY_TAG_BIG |
TIDY_TAG_BLINK |
TIDY_TAG_BLOCKQUOTE |
TIDY_TAG_BODY |
TIDY_TAG_BR |
TIDY_TAG_BUTTON |
TIDY_TAG_CANVAS | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_CAPTION |
TIDY_TAG_CENTER |
TIDY_TAG_CITE |
TIDY_TAG_CODE |
TIDY_TAG_COL |
TIDY_TAG_COLGROUP |
TIDY_TAG_COMMAND | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_COMMENT |
TIDY_TAG_DATALIST | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_DD |
TIDY_TAG_DEL |
TIDY_TAG_DETAILS | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_DFN |
TIDY_TAG_DIALOG | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_DIR |
TIDY_TAG_DIV |
TIDY_TAG_DL |
TIDY_TAG_DT |
TIDY_TAG_EM |
TIDY_TAG_EMBED |
TIDY_TAG_FIELDSET |
TIDY_TAG_FIGCAPTION | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_FIGURE | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_FONT |
TIDY_TAG_FOOTER | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_FORM |
TIDY_TAG_FRAME |
TIDY_TAG_FRAMESET |
TIDY_TAG_H1 |
TIDY_TAG_H2 |
TIDY_TAG_H3 |
TIDY_TAG_H4 |
TIDY_TAG_H5 |
TIDY_TAG_H6 |
TIDY_TAG_HEAD |
TIDY_TAG_HEADER | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_HGROUP | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_HR |
TIDY_TAG_HTML |
TIDY_TAG_I |
TIDY_TAG_IFRAME |
TIDY_TAG_ILAYER |
TIDY_TAG_IMG |
TIDY_TAG_INPUT |
TIDY_TAG_INS |
TIDY_TAG_ISINDEX |
TIDY_TAG_KBD |
TIDY_TAG_KEYGEN |
TIDY_TAG_LABEL |
TIDY_TAG_LAYER |
TIDY_TAG_LEGEND |
TIDY_TAG_LI |
TIDY_TAG_LINK |
TIDY_TAG_LISTING |
TIDY_TAG_MAIN | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_MAP |
TIDY_TAG_MARK | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_MARQUEE |
TIDY_TAG_MENU |
TIDY_TAG_MENUITEM | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_META |
TIDY_TAG_METER | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_MULTICOL |
TIDY_TAG_NAV | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_NOBR |
TIDY_TAG_NOEMBED |
TIDY_TAG_NOFRAMES |
TIDY_TAG_NOLAYER |
TIDY_TAG_NOSAVE |
TIDY_TAG_NOSCRIPT |
TIDY_TAG_OBJECT |
TIDY_TAG_OL |
TIDY_TAG_OPTGROUP |
TIDY_TAG_OPTION |
TIDY_TAG_OUTPUT | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_P |
TIDY_TAG_PARAM |
TIDY_TAG_PLAINTEXT |
TIDY_TAG_PRE |
TIDY_TAG_PROGRESS | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_Q |
TIDY_TAG_RB |
TIDY_TAG_RBC |
TIDY_TAG_RP |
TIDY_TAG_RT |
TIDY_TAG_RTC |
TIDY_TAG_RUBY |
TIDY_TAG_S |
TIDY_TAG_SAMP |
TIDY_TAG_SCRIPT |
TIDY_TAG_SECTION | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_SELECT |
TIDY_TAG_SERVER |
TIDY_TAG_SERVLET |
TIDY_TAG_SMALL |
TIDY_TAG_SOURCE | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_SPACER |
TIDY_TAG_SPAN |
TIDY_TAG_STRIKE |
TIDY_TAG_STRONG |
TIDY_TAG_STYLE |
TIDY_TAG_SUB |
TIDY_TAG_SUMMARY | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_SUP |
TIDY_TAG_TABLE |
TIDY_TAG_TBODY |
TIDY_TAG_TD |
TIDY_TAG_TEMPLATE | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_TEXTAREA |
TIDY_TAG_TFOOT |
TIDY_TAG_TH |
TIDY_TAG_THEAD |
TIDY_TAG_TIME | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_TITLE |
TIDY_TAG_TR |
TIDY_TAG_TRACK | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_TT |
TIDY_TAG_U |
TIDY_TAG_UL |
TIDY_TAG_VAR |
TIDY_TAG_VIDEO | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_WBR |
TIDY_TAG_XMP |

tidy nodetype constants
constant | description
TIDY_NODETYPE_ROOT | root node
TIDY_NODETYPE_DOCTYPE | doctype
TIDY_NODETYPE_COMMENT | HTML comment
TIDY_NODETYPE_PROCINS | Processing Instruction
TIDY_NODETYPE_TEXT | Text
TIDY_NODETYPE_START | start tag
TIDY_NODETYPE_END | end tag
TIDY_NODETYPE_STARTEND | empty tag
TIDY_NODETYPE_CDATA | CDATA
TIDY_NODETYPE_SECTION | XML section
TIDY_NODETYPE_ASP | ASP code
TIDY_NODETYPE_JSTE | JSTE code
TIDY_NODETYPE_PHP | PHP code
TIDY_NODETYPE_XMLDECL | XML declaration


  • « Predefined Constants
  • Tidy example »
  • PHP Manual
  • Tidy
  • Examples

Examples

Table of Contents

  • Tidy example


Tidy example

This simple example shows basic Tidy usage.

Example #1 Basic Tidy usage

<?php
ob_start();
?>
<html>a html document</html>
<?php
$html = ob_get_clean();

// Specify configuration
$config = array(
           'indent'         => true,
           'output-xhtml'   => true,
           'wrap'           => 200);

// Tidy
$tidy = new tidy;
$tidy->parseString($html, $config, 'utf8');
$tidy->cleanRepair();

// Output
echo $tidy;
?>


The tidy class

(PHP 5, PHP 7, PECL tidy >= 0.5.2)

Introduction

An HTML node in an HTML file, as detected by tidy.

Class synopsis

tidy {
/* Properties */
public string $errorBuffer;
/* Methods */
public body ( void ) : tidyNode
public cleanRepair ( void ) : bool
public __construct ([ string $filename [, mixed $config [, string $encoding [, bool $use_include_path ]]]] )
public diagnose ( void ) : bool
public getConfig ( void ) : array
public getHtmlVer ( void ) : int
public getOpt ( string $option ) : mixed
public getOptDoc ( string $optname ) : string
public getRelease ( void ) : string
public getStatus ( void ) : int
public head ( void ) : tidyNode
public html ( void ) : tidyNode
public isXhtml ( void ) : bool
public isXml ( void ) : bool
public parseFile ( string $filename [, mixed $config [, string $encoding [, bool $use_include_path = FALSE ]]] ) : bool
public parseString ( string $input [, mixed $config [, string $encoding ]] ) : bool
public repairFile ( string $filename [, mixed $config [, string $encoding [, bool $use_include_path = FALSE ]]] ) : string
public repairString ( string $data [, mixed $config [, string $encoding ]] ) : string
public root ( void ) : tidyNode
}

Table of Contents

  • tidy::body — Returns a tidyNode object starting from the <body> tag of the tidy parse tree
  • tidy::cleanRepair — Execute configured cleanup and repair operations on parsed markup
  • tidy::__construct — Constructs a new tidy object
  • tidy::diagnose — Run configured diagnostics on parsed and repaired markup
  • tidy::$errorBuffer — Return warnings and errors which occurred parsing the specified document
  • tidy::getConfig — Get current Tidy configuration
  • tidy::getHtmlVer — Get the Detected HTML version for the specified document
  • tidy::getOpt — Returns the value of the specified configuration option for the tidy document
  • tidy::getOptDoc — Returns the documentation for the given option name
  • tidy::getRelease — Get release date (version) for Tidy library
  • tidy::getStatus — Get status of specified document
  • tidy::head — Returns a tidyNode object starting from the <head> tag of the tidy parse tree
  • tidy::html — Returns a tidyNode object starting from the <html> tag of the tidy parse tree
  • tidy::isXhtml — Indicates if the document is a XHTML document
  • tidy::isXml — Indicates if the document is a generic (non HTML/XHTML) XML document
  • tidy::parseFile — Parse markup in file or URI
  • tidy::parseString — Parse a document stored in a string
  • tidy::repairFile — Repair a file and return it as a string
  • tidy::repairString — Repair a string using an optionally provided configuration file
  • tidy::root — Returns a tidyNode object representing the root of the tidy parse tree


Returns a tidyNode object starting from the <body> tag of the tidy parse tree

  • « tidy
  • tidy::cleanRepair »
  • PHP Manual
  • tidy
  • Returns a tidyNode object starting from the <body> tag of the tidy parse tree

tidy::body

tidy_get_body

(PHP 5, PHP 7, PECL tidy 0.5.2-1.0)

tidy::body -- tidy_get_body — Returns a tidyNode object starting from the <body> tag of the tidy parse tree

Description

Object oriented style

public tidy::body ( void ) : tidyNode

Procedural style

tidy_get_body ( tidy $object ) : tidyNode

Returns a tidyNode object starting from the <body> tag of the tidy parse tree.

Parameters

object

The Tidy object.

Return Values

Returns a tidyNode object starting from the <body> tag of the tidy parse tree.

Examples

Example #1 tidy::getBody() example

<?php
$html = '
<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <p>paragraph</p>
  </body>
</html>';

$tidy = tidy_parse_string($html);

$body = $tidy->Body();
echo $body->value;
?>

The above example will output:

<body>
<p>paragraph</p>
</body>

See Also

  • tidy::head() - Returns a tidyNode object starting from the <head> tag of the tidy parse tree
  • tidy::html() - Returns a tidyNode object starting from the <html> tag of the tidy parse tree


Execute configured cleanup and repair operations on parsed markup

  • « tidy::body
  • tidy::__construct »
  • PHP Manual
  • tidy
  • Execute configured cleanup and repair operations on parsed markup

tidy::cleanRepair

tidy_clean_repair

(PHP 5, PHP 7, PECL tidy >= 0.5.2)

tidy::cleanRepair -- tidy_clean_repair — Execute configured cleanup and repair operations on parsed markup

Description

Object oriented style

public tidy::cleanRepair ( void ) : bool

Procedural style

tidy_clean_repair ( tidy $object ) : bool

This function cleans and repairs the given tidy object.

Parameters

object

The Tidy object.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 tidy::cleanrepair() example

<?php
$html = '<p>test</I>';

$tidy = tidy_parse_string($html);
$tidy->cleanRepair();

echo $tidy;
?>

The above example will output:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title></title>
</head>
<body>
<p>test</p>
</body>
</html>

See Also

  • tidy::repairFile() - Repair a file and return it as a string
  • tidy::repairString() - Repair a string using an optionally provided configuration file


Constructs a new tidy object

  • « tidy::cleanRepair
  • tidy::diagnose »
  • PHP Manual
  • tidy
  • Constructs a new tidy object

tidy::__construct

(PHP 5, PHP 7, PECL tidy >= 0.5.2)

tidy::__construct — Constructs a new tidy object

Description

public tidy::__construct ([ string $filename [, mixed $config [, string $encoding [, bool $use_include_path ]]]] )

Constructs a new tidy object.

Parameters

filename

If the filename parameter is given, this function will also read that file and initialize the object with the file, acting like tidy_parse_file().

config

The config config can be passed either as an array or as a string. If a string is passed, it is interpreted as the name of the configuration file, otherwise, it is interpreted as the options themselves.

For an explanation about each option, visit » http://tidy.sourceforge.net/docs/quickref.html.

encoding

The encoding parameter sets the encoding for input/output documents. The possible values for encoding are: ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5, and shiftjis.

use_include_path

Search for the file in the include_path.

Return Values

Returns the new tidy instance.

Examples

Example #1 tidy::__construct() example

<?php

$html = <<< HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head><title>title</title></head>
<body>
<p>paragraph <bt />
text</p>
</body></html>

HTML;

$tidy = new tidy();
$tidy->ParseString($html);

$tidy->cleanRepair();

if ($tidy->errorBuffer) {
    echo "The following errors were detected:\n";
    echo $tidy->errorBuffer;
}

?>

The above example will output:

The following errors were detected:
line 8 column 14 - Error: <bt> is not recognized!
line 8 column 14 - Warning: discarding unexpected <bt>

See Also

  • tidy::parseFile() - Parse markup in file or URI
  • tidy::parseString() - Parse a document stored in a string


Run configured diagnostics on parsed and repaired markup

  • « tidy::__construct
  • tidy::$errorBuffer »
  • PHP Manual
  • tidy
  • Run configured diagnostics on parsed and repaired markup

tidy::diagnose

tidy_diagnose

(PHP 5, PHP 7, PECL tidy >= 0.5.2)

tidy::diagnose -- tidy_diagnose — Run configured diagnostics on parsed and repaired markup

Description

Object oriented style

public tidy::diagnose ( void ) : bool

Procedural style

tidy_diagnose ( tidy $object ) : bool

Runs diagnostic tests on the given tidy object, adding some more information about the document in the error buffer.

Parameters

object

The Tidy object.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 tidy::diagnose() example

<?php

$html = <<< HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<p>paragraph</p>
HTML;

$tidy = tidy_parse_string($html);
$tidy->cleanRepair();

// note the difference between the two outputs
echo $tidy->errorBuffer . "\n";

$tidy->diagnose();
echo $tidy->errorBuffer;

?>

The above example will output:

line 4 column 1 - Warning: <p> isn't allowed in <head> elements
line 4 column 1 - Warning: inserting missing 'title' element
line 4 column 1 - Warning: <p> isn't allowed in <head> elements
line 4 column 1 - Warning: inserting missing 'title' element
Info: Doctype given is "-//W3C//DTD XHTML 1.0 Strict//EN"
Info: Document content looks like XHTML 1.0 Strict
2 warnings, 0 errors were found!

See Also

  • tidy::errorBuffer()


Return warnings and errors which occurred parsing the specified document

  • « tidy::diagnose
  • tidy::getConfig »
  • PHP Manual
  • tidy
  • Return warnings and errors which occurred parsing the specified document

tidy::$errorBuffer

tidy_get_error_buffer

(PHP 5, PHP 7, PECL tidy >= 0.5.2)

tidy::$errorBuffer -- tidy_get_error_buffer — Return warnings and errors which occurred parsing the specified document

Description

Object oriented style (property):

public string $tidy->errorBuffer;

Procedural style:

tidy_get_error_buffer ( tidy $tidy ) : string

Returns warnings and errors which occurred parsing the specified document.

Parameters

tidy

The Tidy object.

Return Values

Returns the error buffer as a string.

Examples

Example #1 tidy_get_error_buffer() example

<?php
$html = '<p>paragraph</p>';

$tidy = tidy_parse_string($html);

echo tidy_get_error_buffer($tidy);
/* or in OO: */
echo $tidy->errorBuffer;
?>

The above example will output:

line 1 column 1 - Warning: missing <!DOCTYPE> declaration
line 1 column 1 - Warning: inserting missing 'title' element

See Also

  • tidy_access_count() - Returns the Number of Tidy accessibility warnings encountered for specified document
  • tidy_error_count() - Returns the Number of Tidy errors encountered for specified document
  • tidy_warning_count() - Returns the Number of Tidy warnings encountered for specified document


Get current Tidy configuration

  • « tidy::$errorBuffer
  • tidy::getHtmlVer »
  • PHP Manual
  • tidy
  • Get current Tidy configuration

tidy::getConfig

tidy_get_config

(PHP 5, PHP 7, PECL tidy >= 0.7.0)

tidy::getConfig -- tidy_get_config — Get current Tidy configuration

Description

Object oriented style

public tidy::getConfig ( void ) : array

Procedural style

tidy_get_config ( tidy $object ) : array

Gets the list of the configuration options in use by the given tidy object.

Parameters

object

The Tidy object.

Return Values

Returns an array of configuration options.

For an explanation about each option, visit » http://tidy.sourceforge.net/docs/quickref.html.

Examples

Example #1 tidy::getConfig() example

<?php
$html = '<p>test</p>';
$config = array('indent' => TRUE,
                'output-xhtml' => TRUE,
                'wrap' => 200);

$tidy = tidy_parse_string($html, $config);

print_r($tidy->getConfig());
?>

The above example will output:

Array
(
    [indent-spaces] => 2
    [wrap] => 200
    [tab-size] => 8
    [char-encoding] => 1
    [input-encoding] => 3
    [output-encoding] => 1
    [newline] => 1
    [doctype-mode] => 1
    [doctype] =>
    [repeated-attributes] => 1
    [alt-text] =>
    [slide-style] =>
    [error-file] =>
    [output-file] =>
    [write-back] =>
    [markup] => 1
    [show-warnings] => 1
    [quiet] =>
    [indent] => 1
    [hide-endtags] =>
    [input-xml] =>
    [output-xml] => 1
    [output-xhtml] => 1
    [output-html] =>
    [add-xml-decl] =>
    [uppercase-tags] =>
    [uppercase-attributes] =>
    [bare] =>
    [clean] =>
    [logical-emphasis] =>
    [drop-proprietary-attributes] =>
    [drop-font-tags] =>
    [drop-empty-paras] => 1
    [fix-bad-comments] => 1
    [break-before-br] =>
    [split] =>
    [numeric-entities] =>
    [quote-marks] =>
    [quote-nbsp] => 1
    [quote-ampersand] => 1
    [wrap-attributes] =>
    [wrap-script-literals] =>
    [wrap-sections] => 1
    [wrap-asp] => 1
    [wrap-jste] => 1
    [wrap-php] => 1
    [fix-backslash] => 1
    [indent-attributes] =>
    [assume-xml-procins] =>
    [add-xml-space] =>
    [enclose-text] =>
    [enclose-block-text] =>
    [keep-time] =>
    [word-2000] =>
    [tidy-mark] =>
    [gnu-emacs] =>
    [gnu-emacs-file] =>
    [literal-attributes] =>
    [show-body-only] =>
    [fix-uri] => 1
    [lower-literals] => 1
    [hide-comments] =>
    [indent-cdata] =>
    [force-output] => 1
    [show-errors] => 6
    [ascii-chars] => 1
    [join-classes] =>
    [join-styles] => 1
    [escape-cdata] =>
    [language] =>
    [ncr] => 1
    [output-bom] => 2
    [replace-color] =>
    [css-prefix] =>
    [new-inline-tags] =>
    [new-blocklevel-tags] =>
    [new-empty-tags] =>
    [new-pre-tags] =>
    [accessibility-check] => 0
    [vertical-space] =>
    [punctuation-wrap] =>
    [merge-divs] => 1
)

See Also

  • tidy_reset_config()
  • tidy_save_config()


Get the Detected HTML version for the specified document

  • « tidy::getConfig
  • tidy::getOpt »
  • PHP Manual
  • tidy
  • Get the Detected HTML version for the specified document

tidy::getHtmlVer

tidy_get_html_ver

(PHP 5, PHP 7, PECL tidy >= 0.5.2)

tidy::getHtmlVer -- tidy_get_html_ver — Get the Detected HTML version for the specified document

Description

Object oriented style

public tidy::getHtmlVer ( void ) : int

Procedural style

tidy_get_html_ver ( tidy $object ) : int

Returns the detected HTML version for the specified tidy object.

Parameters

object

The Tidy object.

Return Values

Returns the detected HTML version.

Warning

This function is not yet implemented in the Tidylib itself, so it always return 0.


Returns the value of the specified configuration option for the tidy document

  • « tidy::getHtmlVer
  • tidy::getOptDoc »
  • PHP Manual
  • tidy
  • Returns the value of the specified configuration option for the tidy document

tidy::getOpt

tidy_getopt

(PHP 5, PHP 7, PECL tidy >= 0.5.2)

tidy::getOpt -- tidy_getopt — Returns the value of the specified configuration option for the tidy document

Description

Object oriented style

public tidy::getOpt ( string $option ) : mixed

Procedural style

tidy_getopt ( tidy $object , string $option ) : mixed

Returns the value of the specified option for the specified tidy object.

Parameters

object

The Tidy object.

option

You will find a list with each configuration option and their types at: » http://tidy.sourceforge.net/docs/quickref.html.

Return Values

Returns the value of the specified option. The return type depends on the type of the specified one.

Examples

Example #1 tidy_getopt() example

<?php

$html ='<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html><head><title>Title</title></head>
<body>

<p><img src="img.png"></p>

</body></html>';

$config = array('accessibility-check' => 3,
                'alt-text' => 'some text');

$tidy = new tidy();
$tidy->parseString($html, $config);

var_dump($tidy->getOpt('accessibility-check')); //integer
var_dump($tidy->getOpt('lower-literals')); //boolean
var_dump($tidy->getOpt('alt-text')); //string

?>

The above example will output:

int(3)
bool(true)
string(9) "some text"


Returns the documentation for the given option name

  • « tidy::getOpt
  • tidy::getRelease »
  • PHP Manual
  • tidy
  • Returns the documentation for the given option name

tidy::getOptDoc

tidy_get_opt_doc

(PHP 5 >= 5.1.0, PHP 7)

tidy::getOptDoc -- tidy_get_opt_doc — Returns the documentation for the given option name

Description

Object oriented style

public tidy::getOptDoc ( string $optname ) : string

Procedural style

tidy_get_opt_doc ( tidy $object , string $optname ) : string

tidy_get_opt_doc() returns the documentation for the given option name.

Note:

You need at least libtidy from 25 April, 2005 for this function be available.

Parameters

object

The Tidy object.

optname

The option name

Return Values

Returns a string if the option exists and has documentation available, or FALSE otherwise.

Examples

Example #1 Print all options along with their documentation and default value

<?php

$tidy = new tidy;
$config = $tidy->getConfig();

ksort($config);

foreach ($config as $opt => $val) {

    if (!$doc = $tidy->getOptDoc($opt))
        $doc = 'no documentation available!';

    $val = ($tidy->getOpt($opt) === true)  ? 'true'  : $val;
    $val = ($tidy->getOpt($opt) === false) ? 'false' : $val;

    echo "<p><b>$opt</b> (default: '$val')<br />".
         "$doc</p><hr />\n";
}

?>

See Also

  • tidy::getconfig() - Get current Tidy configuration
  • tidy::getopt() - Returns the value of the specified configuration option for the tidy document


Get release date (version) for Tidy library

  • « tidy::getOptDoc
  • tidy::getStatus »
  • PHP Manual
  • tidy
  • Get release date (version) for Tidy library

tidy::getRelease

tidy_get_release

(PHP 5, PHP 7, PECL tidy >= 0.5.2)

tidy::getRelease -- tidy_get_release — Get release date (version) for Tidy library

Description

Object oriented style

public tidy::getRelease ( void ) : string

Procedural style

tidy_get_release ( void ) : string

Gets the release date of the Tidy library.

Return Values

Returns a string with the release date of the Tidy library, which may be 'unknown'.


Get status of specified document

  • « tidy::getRelease
  • tidy::head »
  • PHP Manual
  • tidy
  • Get status of specified document

tidy::getStatus

tidy_get_status

(PHP 5, PHP 7, PECL tidy >= 0.5.2)

tidy::getStatus -- tidy_get_status — Get status of specified document

Description

Object oriented style

public tidy::getStatus ( void ) : int

Procedural style

tidy_get_status ( tidy $object ) : int

Returns the status for the specified tidy object.

Parameters

object

The Tidy object.

Return Values

Returns 0 if no error/warning was raised, 1 for warnings or accessibility errors, or 2 for errors.

Examples

Example #1 tidy::getStatus() example

<?php
$html = '<p>paragraph</i>';
$tidy = new tidy();
$tidy->parseString($html);

$tidy2 = new tidy();
$html2 = '<bogus>test</bogus>';
$tidy2->parseString($html2);

echo $tidy->getStatus(); //1

echo $tidy2->getStatus(); //2
?>


Returns a tidyNode object starting from the <head> tag of the tidy parse tree

  • « tidy::getStatus
  • tidy::html »
  • PHP Manual
  • tidy
  • Returns a tidyNode object starting from the <head> tag of the tidy parse tree

tidy::head

tidy_get_head

(PHP 5, PHP 7, PECL tidy 0.5.2-1.0.0)

tidy::head -- tidy_get_head — Returns a tidyNode object starting from the <head> tag of the tidy parse tree

Description

Object oriented style

public tidy::head ( void ) : tidyNode

Procedural style

tidy_get_head ( tidy $object ) : tidyNode

Returns a tidyNode object starting from the <head> tag of the tidy parse tree.

Parameters

object

The Tidy object.

Return Values

Returns the tidyNode object.

Examples

Example #1 tidy::head() example

<?php
$html = '
<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <p>paragraph</p>
  </body>
</html>';

$tidy = tidy_parse_string($html);

$head = $tidy->head();
echo $head->value;
?>

The above example will output:

<head>
<title>test</title>
</head>

See Also

  • tidy::body() - Returns a tidyNode object starting from the <body> tag of the tidy parse tree
  • tidy::html() - Returns a tidyNode object starting from the <html> tag of the tidy parse tree


Returns a tidyNode object starting from the <html> tag of the tidy parse tree

  • « tidy::head
  • tidy::isXhtml »
  • PHP Manual
  • tidy
  • Returns a tidyNode object starting from the <html> tag of the tidy parse tree

tidy::html

tidy_get_html

(PHP 5, PHP 7, PECL tidy 0.5.2-1.0.0)

tidy::html -- tidy_get_html — Returns a tidyNode object starting from the <html> tag of the tidy parse tree

Description

Object oriented style

public tidy::html ( void ) : tidyNode

Procedural style

tidy_get_html ( tidy $object ) : tidyNode

Returns a tidyNode object starting from the <html> tag of the tidy parse tree.

Parameters

object

The Tidy object.

Return Values

Returns the tidyNode object.

Examples

Example #1 tidy::html() example

<?php
$html = '
<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <p>paragraph</p>
  </body>
</html>';

$tidy = tidy_parse_string($html);

$html = $tidy->html();
echo $html->value;
?>

The above example will output:

<html>
<head>
<title>test</title>
</head>
<body>
<p>paragraph</p>
</body>
</html>

See Also

  • tidy::body() - Returns a tidyNode object starting from the <body> tag of the tidy parse tree
  • tidy::head() - Returns a tidyNode object starting from the <head> tag of the tidy parse tree


Indicates if the document is a XHTML document

  • « tidy::html
  • tidy::isXml »
  • PHP Manual
  • tidy
  • Indicates if the document is a XHTML document

tidy::isXhtml

tidy_is_xhtml

(PHP 5, PHP 7, PECL tidy >= 0.5.2)

tidy::isXhtml -- tidy_is_xhtml — Indicates if the document is a XHTML document

Description

Object oriented style

public tidy::isXhtml ( void ) : bool

Procedural style

tidy_is_xhtml ( tidy $object ) : bool

Tells if the document is a XHTML document.

Parameters

object

The Tidy object.

Return Values

This function returns TRUE if the specified tidy object is a XHTML document, or FALSE otherwise.

Warning

This function is not yet implemented in the Tidylib itself, so it always return FALSE.


Indicates if the document is a generic (non HTML/XHTML) XML document

  • « tidy::isXhtml
  • tidy::parseFile »
  • PHP Manual
  • tidy
  • Indicates if the document is a generic (non HTML/XHTML) XML document

tidy::isXml

tidy_is_xml

(PHP 5, PHP 7, PECL tidy >= 0.5.2)

tidy::isXml -- tidy_is_xml — Indicates if the document is a generic (non HTML/XHTML) XML document

Description

Object oriented style

public tidy::isXml ( void ) : bool

Procedural style

tidy_is_xml ( tidy $object ) : bool

Tells if the document is a generic (non HTML/XHTML) XML document.

Parameters

object

The Tidy object.

Return Values

This function returns TRUE if the specified tidy object is a generic XML document (non HTML/XHTML), or FALSE otherwise.

Warning

This function is not yet implemented in the Tidylib itself, so it always return FALSE.


Parse markup in file or URI

  • « tidy::isXml
  • tidy::parseString »
  • PHP Manual
  • tidy
  • Parse markup in file or URI

tidy::parseFile

tidy_parse_file

(PHP 5, PHP 7, PECL tidy >= 0.5.2)

tidy::parseFile -- tidy_parse_file — Parse markup in file or URI

Description

Object oriented style

public tidy::parseFile ( string $filename [, mixed $config [, string $encoding [, bool $use_include_path = FALSE ]]] ) : bool

Procedural style

tidy_parse_file ( string $filename [, mixed $config [, string $encoding [, bool $use_include_path = FALSE ]]] ) : tidy

Parses the given file.

Parameters

filename

If the filename parameter is given, this function will also read that file and initialize the object with the file, acting like tidy_parse_file().

config

The config config can be passed either as an array or as a string. If a string is passed, it is interpreted as the name of the configuration file, otherwise, it is interpreted as the options themselves.

For an explanation about each option, see » http://tidy.sourceforge.net/docs/quickref.html.

encoding

The encoding parameter sets the encoding for input/output documents. The possible values for encoding are: ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5, and shiftjis.

use_include_path

Search for the file in the include_path.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 tidy::parseFile() example

<?php
$tidy = new tidy();
$tidy->parseFile('file.html');

$tidy->cleanRepair();

if(!empty($tidy->errorBuffer)) {
    echo "The following errors or warnings occurred:\n";
    echo $tidy->errorBuffer;
}
?>

See Also

  • tidy::parsestring() - Parse a document stored in a string
  • tidy::repairfile() - Repair a file and return it as a string
  • tidy::repairstring() - Repair a string using an optionally provided configuration file


Parse a document stored in a string

  • « tidy::parseFile
  • tidy::repairFile »
  • PHP Manual
  • tidy
  • Parse a document stored in a string

tidy::parseString

tidy_parse_string

(PHP 5, PHP 7, PECL tidy >= 0.5.2)

tidy::parseString -- tidy_parse_string — Parse a document stored in a string

Description

Object oriented style

public tidy::parseString ( string $input [, mixed $config [, string $encoding ]] ) : bool

Procedural style

tidy_parse_string ( string $input [, mixed $config [, string $encoding ]] ) : tidy

Parses a document stored in a string.

Parameters

input

The data to be parsed.

config

The config config can be passed either as an array or as a string. If a string is passed, it is interpreted as the name of the configuration file, otherwise, it is interpreted as the options themselves.

For an explanation about each option, visit » http://tidy.sourceforge.net/docs/quickref.html.

encoding

The encoding parameter sets the encoding for input/output documents. The possible values for encoding are: ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5, and shiftjis.

Return Values

Returns a new tidy instance.

Examples

Example #1 tidy::parseString() example

<?php
ob_start();
?>

<html>
  <head>
   <title>test</title>
  </head>
  <body>
   <p>error<br>another line</i>
  </body>
</html>

<?php

$buffer = ob_get_clean();
$config = array('indent' => TRUE,
                'output-xhtml' => TRUE,
                'wrap' => 200);

$tidy = tidy_parse_string($buffer, $config, 'UTF8');

$tidy->cleanRepair();
echo $tidy;
?>

The above example will output:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>
      test
    </title>
  </head>
  <body>
    <p>
      error<br />
      another line
    </p>
  </body>
</html>

See Also

  • tidy::parseFile() - Parse markup in file or URI
  • tidy::repairFile() - Repair a file and return it as a string
  • tidy::repairString() - Repair a string using an optionally provided configuration file


Repair a file and return it as a string

  • « tidy::parseString
  • tidy::repairString »
  • PHP Manual
  • tidy
  • Repair a file and return it as a string

tidy::repairFile

tidy_repair_file

(PHP 5, PHP 7, PECL tidy >= 0.7.0)

tidy::repairFile -- tidy_repair_file — Repair a file and return it as a string

Description

Object oriented style

public tidy::repairFile ( string $filename [, mixed $config [, string $encoding [, bool $use_include_path = FALSE ]]] ) : string

Procedural style

tidy_repair_file ( string $filename [, mixed $config [, string $encoding [, bool $use_include_path = FALSE ]]] ) : string

Repairs the given file and returns it as a string.

Parameters

filename

The file to be repaired.

config

The config config can be passed either as an array or as a string. If a string is passed, it is interpreted as the name of the configuration file, otherwise, it is interpreted as the options themselves.

Check http://tidy.sourceforge.net/docs/quickref.html for an explanation about each option.

encoding

The encoding parameter sets the encoding for input/output documents. The possible values for encoding are: ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5, and shiftjis.

use_include_path

Search for the file in the include_path.

Return Values

Returns the repaired contents as a string.

Examples

Example #1 tidy::repairFile() example

<?php
$file = 'file.html';

$tidy = new tidy();
$repaired = $tidy->repairfile($file);
rename($file, $file . '.bak');

file_put_contents($file, $repaired);
?>

See Also

  • tidy::parseFile() - Parse markup in file or URI
  • tidy::parseString() - Parse a document stored in a string
  • tidy::repairString() - Repair a string using an optionally provided configuration file


Repair a string using an optionally provided configuration file

  • « tidy::repairFile
  • tidy::root »
  • PHP Manual
  • tidy
  • Repair a string using an optionally provided configuration file

tidy::repairString

tidy_repair_string

(PHP 5, PHP 7, PECL tidy >= 0.7.0)

tidy::repairString -- tidy_repair_string — Repair a string using an optionally provided configuration file

Description

Object oriented style

public tidy::repairString ( string $data [, mixed $config [, string $encoding ]] ) : string

Procedural style

tidy_repair_string ( string $data [, mixed $config [, string $encoding ]] ) : string

Repairs the given string.

Parameters

data

The data to be repaired.

config

The config config can be passed either as an array or as a string. If a string is passed, it is interpreted as the name of the configuration file, otherwise, it is interpreted as the options themselves.

Check » http://tidy.sourceforge.net/docs/quickref.html for an explanation about each option.

encoding

The encoding parameter sets the encoding for input/output documents. The possible values for encoding are: ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5, and shiftjis.

Return Values

Returns the repaired string.

Examples

Example #1 tidy::repairString() example

<?php
ob_start();
?>

<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <p>error</i>
  </body>
</html>

<?php

$buffer = ob_get_clean();
$tidy = new tidy();
$clean = $tidy->repairString($buffer);

echo $clean;
?>

The above example will output:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title>test</title>
</head>
<body>
<p>error</p>
</body>
</html>

See Also

  • tidy::parseFile() - Parse markup in file or URI
  • tidy::parseString() - Parse a document stored in a string
  • tidy::repairFile() - Repair a file and return it as a string


Returns a tidyNode object representing the root of the tidy parse tree

  • « tidy::repairString
  • tidyNode »
  • PHP Manual
  • tidy
  • Returns a tidyNode object representing the root of the tidy parse tree

tidy::root

tidy_get_root

(PHP 5, PHP 7, PECL tidy 0.5.2-1.0.0)

tidy::root -- tidy_get_root — Returns a tidyNode object representing the root of the tidy parse tree

Description

Object oriented style

public tidy::root ( void ) : tidyNode

Procedural style

tidy_get_root ( tidy $object ) : tidyNode

Returns a tidyNode object representing the root of the tidy parse tree.

Parameters

object

The Tidy object.

Return Values

Returns the tidyNode object.

Examples

Example #1 tidy::root() example

<?php

$html = <<< HTML
<html><body>

<p>paragraph</p>
<br/>

</body></html>
HTML;

$tidy = tidy_parse_string($html);
dump_nodes($tidy->root(), 1);

function dump_nodes($node, $indent) {

    if($node->hasChildren()) {
        foreach($node->child as $child) {
            echo str_repeat('.', $indent*2) . ($child->name ? $child->name : '"'.$child->value.'"'). "\n";

            dump_nodes($child, $indent+1);
        }
    }
}
?>

The above example will output:

..html
....head
......title
....body
......p
........"paragraph"
......br


The tidyNode class

(PHP 5, PHP 7)

Introduction

An HTML node in an HTML file, as detected by tidy.

Class synopsis

final
tidyNode {
/* Properties */
public string $value;
public string $name;
public int $type;
public int $line;
public int $column;
public bool $proprietary;
public int $id;
public array $attribute;
public array $child;
/* Methods */
private __construct ( void )
public getParent ( void ) : tidyNode
public hasChildren ( void ) : bool
public hasSiblings ( void ) : bool
public isAsp ( void ) : bool
public isComment ( void ) : bool
public isHtml ( void ) : bool
public isJste ( void ) : bool
public isPhp ( void ) : bool
public isText ( void ) : bool
}

Properties

value

The HTML representation of the node, including the surrounding tags.

name

The name of the HTML node

type

The type of the node (one of the nodetype constants, e.g. TIDY_NODETYPE_PHP)

line

The line number at which the tags is located in the file

column

The column number at which the tags is located in the file

proprietary

Indicates if the node is a proprietary tag

id

The ID of the node (one of the tag constants, e.g. TIDY_TAG_FRAME)

attribute

An array of string, representing the attributes names (as keys) of the current node.

child

An array of tidyNode, representing the children of the current node.

Version | Description
5.1.0 | line, column and proprietary were added

Table of Contents

  • tidyNode::__construct — Private constructor to disallow direct instantiation
  • tidyNode::getParent — Returns the parent node of the current node
  • tidyNode::hasChildren — Checks if a node has children
  • tidyNode::hasSiblings — Checks if a node has siblings
  • tidyNode::isAsp — Checks if this node is ASP
  • tidyNode::isComment — Checks if a node represents a comment
  • tidyNode::isHtml — Checks if a node is part of a HTML document
  • tidyNode::isJste — Checks if this node is JSTE
  • tidyNode::isPhp — Checks if a node is PHP
  • tidyNode::isText — Checks if a node represents text (no markup)


Private constructor to disallow direct instantiation

  • « tidyNode
  • tidyNode::getParent »
  • PHP Manual
  • tidyNode
  • Private constructor to disallow direct instantiation

tidyNode::__construct

(PHP 5, PHP 7)

tidyNode::__construct — Private constructor to disallow direct instantiation

Description

private tidyNode::__construct ( void )

Parameters

This function has no parameters.


Returns the parent node of the current node

  • « tidyNode::__construct
  • tidyNode::hasChildren »
  • PHP Manual
  • tidyNode
  • Returns the parent node of the current node

tidyNode::getParent

(PHP 5 >= 5.2.2, PHP 7)

tidyNode::getParent — Returns the parent node of the current node

Description

public tidyNode::getParent ( void ) : tidyNode

Returns the parent node of the current node.

Examples

Example #1 tidyNode::hasChildren() example

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
  /* JSTE code */
  alert('Hello World');
#>
 </head>
 <body>
 Hello World
 </body>
</html>

HTML;

$tidy = tidy_parse_string($html);
$num = 0;

$node = $tidy->html()->child[0]->child[0];

var_dump($node->getparent()->name);
?>

The above example will output:

string(4) "head"

Return Values

Returns a tidyNode if the node has a parent, or NULL otherwise.


Checks if a node has children

  • « tidyNode::getParent
  • tidyNode::hasSiblings »
  • PHP Manual
  • tidyNode
  • Checks if a node has children

tidyNode::hasChildren

(PHP 5, PHP 7)

tidyNode::hasChildren — Checks if a node has children

Description

public tidyNode::hasChildren ( void ) : bool

Tells if the node has children.

Return Values

Returns TRUE if the node has children, FALSE otherwise.

Examples

Example #1 tidyNode::hasChildren() example

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
  /* JSTE code */
  alert('Hello World');
#>
</head>
<body>

<?php
  // PHP code
  echo 'hello world!';
?>

<%
  /* ASP code */
  response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

// the head tag
var_dump($tidy->html()->child[0]->hasChildren());

// the php inside the head tag
var_dump($tidy->html()->child[0]->child[0]->hasChildren());

?>

The above example will output:

bool(true)
bool(false)


Checks if a node has siblings

  • « tidyNode::hasChildren
  • tidyNode::isAsp »
  • PHP Manual
  • tidyNode
  • Checks if a node has siblings

tidyNode::hasSiblings

(PHP 5, PHP 7)

tidyNode::hasSiblings — Checks if a node has siblings

Description

public tidyNode::hasSiblings ( void ) : bool

Tells if the node has siblings.

Return Values

Returns TRUE if the node has siblings, FALSE otherwise.

Examples

Example #1 tidyNode::hasSiblings() example

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
  /* JSTE code */
  alert('Hello World');
#>
</head>
<body>

<?php
  // PHP code
  echo 'hello world!';
?>

<%
  /* ASP code */
  response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

// the html tag
var_dump($tidy->html()->hasSiblings());

// the head tag
var_dump($tidy->html()->child[0]->hasSiblings());

?>

The above example will output:

bool(false)
bool(true)


Checks if this node is ASP

  • « tidyNode::hasSiblings
  • tidyNode::isComment »
  • PHP Manual
  • tidyNode
  • Checks if this node is ASP

tidyNode::isAsp

(PHP 5, PHP 7)

tidyNode::isAsp — Checks if this node is ASP

Description

public tidyNode::isAsp ( void ) : bool

Tells whether the current node is ASP.

Return Values

Returns TRUE if the node is ASP, FALSE otherwise.

Examples

Example #1 Extract ASP code from a mixed HTML document

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
  /* JSTE code */
  alert('Hello World');
#>
</head>
<body>

<?php
  // PHP code
  echo 'hello world!';
?>

<%
  /* ASP code */
  response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

get_nodes($tidy->html());

function get_nodes($node) {

    // check if the current node is of requested type
    if($node->isAsp()) {
        echo "\n\n# asp node #" . ++$GLOBALS['num'] . "\n";
        echo $node->value;
    }

    // check if the current node has childrens
    if($node->hasChildren()) {
        foreach($node->child as $child) {
            get_nodes($child);
        }
    }
}

?>

The above example will output:

# asp node #1
<%
  /* ASP code */
  response.write("Hello World!")
%>


Checks if a node represents a comment

  • « tidyNode::isAsp
  • tidyNode::isHtml »
  • PHP Manual
  • tidyNode
  • Checks if a node represents a comment

tidyNode::isComment

(PHP 5, PHP 7)

tidyNode::isComment — Checks if a node represents a comment

Description

public tidyNode::isComment ( void ) : bool

Tells if the node is a comment.

Return Values

Returns TRUE if the node is a comment, FALSE otherwise.

Examples

Example #1 Extract comments from a mixed HTML document

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
  /* JSTE code */
  alert('Hello World');
#>
</head>
<body>

<?php
  // PHP code
  echo 'hello world!';
?>

<%
  /* ASP code */
  response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

get_nodes($tidy->html());

function get_nodes($node) {

    // check if the current node is of requested type
    if($node->isComment()) {
        echo "\n\n# comment node #" . ++$GLOBALS['num'] . "\n";
        echo $node->value;
    }

    // check if the current node has childrens
    if($node->hasChildren()) {
        foreach($node->child as $child) {
            get_nodes($child);
        }
    }
}

?>

The above example will output:

# comment node #1
<!-- Comments -->


Checks if a node is part of a HTML document

  • « tidyNode::isComment
  • tidyNode::isJste »
  • PHP Manual
  • tidyNode
  • Checks if a node is part of a HTML document

tidyNode::isHtml

(PHP 5, PHP 7)

tidyNode::isHtml — Checks if a node is part of a HTML document

Description

public tidyNode::isHtml ( void ) : bool

Tells if the node is part of HTML document.

Return Values

Returns TRUE if the node is part of a HTML document, FALSE otherwise.

Examples

Example #1 Extract HTML code from a mixed HTML document

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
  /* JSTE code */
  alert('Hello World');
#>
</head>
<body>

<?php
  // PHP code
  echo 'hello world!';
?>

<%
  /* ASP code */
  response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

get_nodes($tidy->html());

function get_nodes($node) {
    // check if the current node is of requested type
    if($node->isHtml()) {
        echo "\n\n# html node #" . ++$GLOBALS['num'] . "\n";
        echo $node->value;
    }

    // check if the current node has childrens
    if($node->hasChildren()) {
        foreach($node->child as $child) {
            get_nodes($child);
        }
    }
}

?>

The above example will output:

# html node #1
<html>
<head>
<?php echo '<title>title</title>'; ?><#
  /* JSTE code */
  alert('Hello World');
#>
<title></title>
</head>
<body>
<?php
  // PHP code
  echo 'hello world!';
?><%
  /* ASP code */
  response.write("Hello World!")
%><!-- Comments -->
Hello WorldOutside HTML
</body>
</html>

# html node #2
<head>
<?php echo '<title>title</title>'; ?><#
  /* JSTE code */
  alert('Hello World');
#>
<title></title>
</head>

# html node #3
<?php echo '<title>title</title>'; ?>

# html node #4
<#
  /* JSTE code */
  alert('Hello World');
#>

# html node #5
<title></title>

# html node #6
<body>
<?php
  // PHP code
  echo 'hello world!';
?><%
  /* ASP code */
  response.write("Hello World!")
%><!-- Comments -->
Hello WorldOutside HTML
</body>

# html node #7
<?php
  // PHP code
  echo 'hello world!';
?>

# html node #8
<%
  /* ASP code */
  response.write("Hello World!")
%>

# html node #9
<!-- Comments -->

# html node #10
Hello World

# html node #11
Outside HTML


Checks if this node is JSTE

  • « tidyNode::isHtml
  • tidyNode::isPhp »
  • PHP Manual
  • tidyNode
  • Checks if this node is JSTE

tidyNode::isJste

(PHP 5, PHP 7)

tidyNode::isJste — Checks if this node is JSTE

Description

public tidyNode::isJste ( void ) : bool

Tells if the node is JSTE.

Return Values

Returns TRUE if the node is JSTE, FALSE otherwise.

Examples

Example #1 Extract JSTE code from a mixed HTML document

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
  /* JSTE code */
  alert('Hello World');
#>
</head>
<body>

<?php
  // PHP code
  echo 'hello world!';
?>

<%
  /* ASP code */
  response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

get_nodes($tidy->html());

function get_nodes($node) {

    // check if the current node is of requested type
    if($node->isJste()) {
        echo "\n\n# jste node #" . ++$GLOBALS['num'] . "\n";
        echo $node->value;
    }

    // check if the current node has childrens
    if($node->hasChildren()) {
        foreach($node->child as $child) {
            get_nodes($child);
        }
    }
}

?>

The above example will output:

# jste node #1
<#
  /* JSTE code */
  alert('Hello World');
#>


Checks if a node is PHP

  • « tidyNode::isJste
  • tidyNode::isText »
  • PHP Manual
  • tidyNode
  • Checks if a node is PHP

tidyNode::isPhp

(PHP 5, PHP 7)

tidyNode::isPhp — Checks if a node is PHP

Description

public tidyNode::isPhp ( void ) : bool

Tells if the node is PHP.

Return Values

Returns TRUE if the current node is PHP code, FALSE otherwise.

Examples

Example #1 Extract PHP code from a mixed HTML document

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
  /* JSTE code */
  alert('Hello World');
#>
</head>
<body>

<?php
  // PHP code
  echo 'hello world!';
?>

<%
  /* ASP code */
  response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

get_nodes($tidy->html());

function get_nodes($node) {

    // check if the current node is of requested type
    if($node->isPhp()) {
        echo "\n\n# php node #" . ++$GLOBALS['num'] . "\n";
        echo $node->value;
    }

    // check if the current node has childrens
    if($node->hasChildren()) {
        foreach($node->child as $child) {
            get_nodes($child);
        }
    }
}

?>

The above example will output:

# php node #1
<?php echo '<title>title</title>'; ?>

# php node #2
<?php
  // PHP code
  echo 'hello world!';
?>


Checks if a node represents text (no markup)

  • « tidyNode::isPhp
  • Tidy Functions »
  • PHP Manual
  • tidyNode
  • Checks if a node represents text (no markup)

tidyNode::isText

(PHP 5, PHP 7)

tidyNode::isText — Checks if a node represents text (no markup)

Description

public tidyNode::isText ( void ) : bool

Tells if the node represents a text (without any markup).

Return Values

Returns TRUE if the node represent a text, FALSE otherwise.

Examples

Example #1 Extract text from a mixed HTML document

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
  /* JSTE code */
  alert('Hello World');
#>
</head>
<body>

<?php
  // PHP code
  echo 'hello world!';
?>

<%
  /* ASP code */
  response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

get_nodes($tidy->html());

function get_nodes($node) {

    // check if the current node is of requested type
    if($node->isText()) {
        echo "\n\n# text node #" . ++$GLOBALS['num'] . "\n";
        echo $node->value;
    }

    // check if the current node has childrens
    if($node->hasChildren()) {
        foreach($node->child as $child) {
            get_nodes($child);
        }
    }
}

?>

The above example will output:

# text node #1
Hello World

# text node #2
Outside HTML


Tidy Functions

Table of Contents

  • ob_tidyhandler — ob_start callback function to repair the buffer
  • tidy_access_count — Returns the Number of Tidy accessibility warnings encountered for specified document
  • tidy_config_count — Returns the Number of Tidy configuration errors encountered for specified document
  • tidy_error_count — Returns the Number of Tidy errors encountered for specified document
  • tidy_get_output — Return a string representing the parsed tidy markup
  • tidy_warning_count — Returns the Number of Tidy warnings encountered for specified document


ob_start callback function to repair the buffer

  • « Tidy Functions
  • tidy_access_count »
  • PHP Manual
  • Tidy Functions
  • ob_start callback function to repair the buffer

ob_tidyhandler

(PHP 5, PHP 7)

ob_tidyhandler — ob_start callback function to repair the buffer

Description

ob_tidyhandler ( string $input [, int $mode ] ) : string

Callback function for ob_start() to repair the buffer.

Parameters

input

The buffer.

mode

The buffer mode.

Return Values

Returns the modified buffer.

Examples

Example #1 ob_tidyhandler() example

<?php
ob_start('ob_tidyhandler');

echo '<p>test</i>';
?>

The above example will output:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title></title>
</head>
<body>
<p>test</p>
</body>
</html>

See Also

  • ob_start() - Turn on output buffering


Returns the Number of Tidy accessibility warnings encountered for specified document

  • « ob_tidyhandler
  • tidy_config_count »
  • PHP Manual
  • Tidy Functions
  • Returns the Number of Tidy accessibility warnings encountered for specified document

tidy_access_count

(PHP 5, PHP 7, PECL tidy >= 0.5.2)

tidy_access_count — Returns the Number of Tidy accessibility warnings encountered for specified document

Description

tidy_access_count ( tidy $object ) : int

tidy_access_count() returns the number of accessibility warnings found for the specified document.

Parameters

object

The Tidy object.

Return Values

Returns the number of warnings.

Examples

Example #1 tidy_access_count() example

<?php

$html ='<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html><head><title>Title</title></head>
<body>

<p><img src="img.png"></p>

</body></html>';

// select the accessibility check level: 1, 2 or 3
$config = array('accessibility-check' => 3);

$tidy = new tidy();
$tidy->parseString($html, $config);
$tidy->cleanRepair();

/* Never forget to call this! */
$tidy->diagnose();

echo tidy_access_count($tidy); //5

?>

Notes

Note:

Due to the design of the TidyLib, you must call tidy_diagnose() before tidy_access_count() or it will return always 0. You must also need to enable the accessibility-check option.

See Also

  • tidy_error_count() - Returns the Number of Tidy errors encountered for specified document
  • tidy_warning_count() - Returns the Number of Tidy warnings encountered for specified document


Returns the Number of Tidy configuration errors encountered for specified document

  • « tidy_access_count
  • tidy_error_count »
  • PHP Manual
  • Tidy Functions
  • Returns the Number of Tidy configuration errors encountered for specified document

tidy_config_count

(PHP 5, PHP 7, PECL tidy >= 0.5.2)

tidy_config_count — Returns the Number of Tidy configuration errors encountered for specified document

Description

tidy_config_count ( tidy $object ) : int

Returns the number of errors encountered in the configuration of the specified tidy object.

Parameters

object

The Tidy object.

Return Values

Returns the number of errors.

Examples

Example #1 tidy_config_count() example

<?php
$html = '<p>test</I>';

$config = array('doctype' => 'bogus');

$tidy = tidy_parse_string($html, $config);

/* This outputs 1, because 'bogus' isn't a valid doctype */
echo tidy_config_count($tidy);
?>


Returns the Number of Tidy errors encountered for specified document

  • « tidy_config_count
  • tidy_get_output »
  • PHP Manual
  • Tidy Functions
  • Returns the Number of Tidy errors encountered for specified document

tidy_error_count

(PHP 5, PHP 7, PECL tidy >= 0.5.2)

tidy_error_count — Returns the Number of Tidy errors encountered for specified document

Description

tidy_error_count ( tidy $object ) : int

Returns the number of Tidy errors encountered for the specified document.

Parameters

object

The Tidy object.

Return Values

Returns the number of errors.

Examples

Example #1 tidy_error_count() example

<?php
$html = '<p>test</i>
<bogustag>bogus</bogustag>';

$tidy = tidy_parse_string($html);

echo tidy_error_count($tidy) . "\n"; //1

echo $tidy->errorBuffer;
?>

The above example will output:

1
line 1 column 1 - Warning: missing <!DOCTYPE> declaration
line 1 column 8 - Warning: discarding unexpected </i>
line 2 column 1 - Error: <bogustag> is not recognized!
line 2 column 1 - Warning: discarding unexpected <bogustag>
line 2 column 16 - Warning: discarding unexpected </bogustag>
line 1 column 1 - Warning: inserting missing 'title' element

See Also

  • tidy_access_count() - Returns the Number of Tidy accessibility warnings encountered for specified document
  • tidy_warning_count() - Returns the Number of Tidy warnings encountered for specified document


Return a string representing the parsed tidy markup

  • « tidy_error_count
  • tidy_warning_count »
  • PHP Manual
  • Tidy Functions
  • Return a string representing the parsed tidy markup

tidy_get_output

(PHP 5, PHP 7, PECL tidy >= 0.5.2)

tidy_get_output — Return a string representing the parsed tidy markup

Description

tidy_get_output ( tidy $object ) : string

Gets a string with the repaired html.

Parameters

object

The Tidy object.

Return Values

Returns the parsed tidy markup.

Examples

Example #1 tidy_get_output() example

<?php

$html = '<p>paragraph</i>';
$tidy = tidy_parse_string($html);

$tidy->cleanRepair();

echo tidy_get_output($tidy);
?>

The above example will output:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title></title>
</head>
<body>
<p>paragraph</p>
</body>
</html>


Returns the Number of Tidy warnings encountered for specified document

  • « tidy_get_output
  • Tokenizer »
  • PHP Manual
  • Tidy Functions
  • Returns the Number of Tidy warnings encountered for specified document

tidy_warning_count

(PHP 5, PHP 7, PECL tidy >= 0.5.2)

tidy_warning_count — Returns the Number of Tidy warnings encountered for specified document

Description

tidy_warning_count ( tidy $object ) : int

Returns the number of Tidy warnings encountered for the specified document.

Parameters

object

The Tidy object.

Return Values

Returns the number of warnings.

Examples

Example #1 tidy_warning_count() example

<?php
$html = '<p>test</i>
<bogustag>bogus</bogustag>';

$tidy = tidy_parse_string($html);

echo tidy_error_count($tidy) . "\n"; //1
echo tidy_warning_count($tidy) . "\n"; //5
?>

See Also

  • tidy_error_count() - Returns the Number of Tidy errors encountered for specified document
  • tidy_access_count() - Returns the Number of Tidy accessibility warnings encountered for specified document


Tokenizer

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Tokenizer Functions
    • token_get_all — Split given source into PHP tokens
    • token_name — Get the symbolic name of a given PHP token


Introduction

The tokenizer functions provide an interface to the PHP tokenizer embedded in the Zend Engine. Using these functions you may write your own PHP source analyzing or modification tools without having to deal with the language specification at the lexical level.

See also the appendix about tokens.


Installation

These functions are enabled by default. You can disable tokenizer support with --disable-tokenizer .

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

When the extension has either been compiled into PHP or dynamically loaded at runtime, the tokens listed in List of Parser Tokens are defined as constants.


Examples

Here is a simple example PHP script using the tokenizer that will read in a PHP file, strip all comments from the source and print the pure code only.

Example #1 Strip comments with the tokenizer

<?php
$source = file_get_contents('example.php');
$tokens = token_get_all($source);

foreach ($tokens as $token) {
   if (is_string($token)) {
       // simple 1-character token
       echo $token;
   } else {
       // token array
       list($id, $text) = $token;

       switch ($id) {
           case T_COMMENT:
           case T_DOC_COMMENT:
               // no action on comments
               break;

           default:
               // anything else -> output "as is"
               echo $text;
               break;
       }
   }
}
?>


Tokenizer Functions

Table of Contents

  • token_get_all — Split given source into PHP tokens
  • token_name — Get the symbolic name of a given PHP token


Split given source into PHP tokens

  • « Tokenizer Functions
  • token_name »
  • PHP Manual
  • Tokenizer Functions
  • Split given source into PHP tokens

token_get_all

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

token_get_all — Split given source into PHP tokens

Description

token_get_all ( string $source [, int $flags = 0 ] ) : array

token_get_all() parses the given source string into PHP language tokens using the Zend engine's lexical scanner.

For a list of parser tokens, see List of Parser Tokens, or use token_name() to translate a token value into its string representation.

Parameters

source

The PHP source to parse.

flags

Valid flags:

  • TOKEN_PARSE - Recognises the ability to use reserved words in specific contexts.

Return Values

An array of token identifiers. Each individual token identifier is either a single character (i.e.: ;, ., >, !, etc...), or a three element array containing the token index in element 0, the string content of the original token in element 1 and the line number in element 2.

Changelog

Version | Description
7.0.0 | Added the optional flags parameter along with the TOKEN_PARSE flag.
5.2.2 | Line numbers are returned in element 2

Examples

Example #1 token_get_all() example

<?php
$tokens = token_get_all('<?php echo; ?>');

foreach ($tokens as $token) {
    if (is_array($token)) {
        echo "Line {$token[2]}: ", token_name($token[0]), " ('{$token[1]}')", PHP_EOL;
    }
}
?>

The above example will output something similar to:

Line 1: T_OPEN_TAG ('<?php ')
Line 1: T_ECHO ('echo')
Line 1: T_WHITESPACE (' ')
Line 1: T_CLOSE_TAG ('?>')

Example #2 token_get_all() incorrect usage example

<?php
$tokens = token_get_all('/* comment */');

foreach ($tokens as $token) {
    if (is_array($token)) {
        echo "Line {$token[2]}: ", token_name($token[0]), " ('{$token[1]}')", PHP_EOL;
    }
}
?>

The above example will output something similar to:

Line 1: T_INLINE_HTML ('/* comment */')
Note in the previous example that the string is parsed as T_INLINE_HTML rather than the expected T_COMMENT. This is because no open tag was used in the code provided. This would be equivalent to putting a comment outside of the PHP tags in a normal file.

Example #3 token_get_all() on a class using a reserved word example

<?php

$source = <<<'code'
<?php

class A
{
    const PUBLIC = 1;
}
code;

$tokens = token_get_all($source, TOKEN_PARSE);

foreach ($tokens as $token) {
    if (is_array($token)) {
        echo token_name($token[0]) , PHP_EOL;
    }
}
?>

The above example will output something similar to:

T_OPEN_TAG
T_WHITESPACE
T_CLASS
T_WHITESPACE
T_STRING
T_CONST
T_WHITESPACE
T_STRING
T_LNUMBER
Without the TOKEN_PARSE flag, the penultimate token (T_STRING) would have been T_PUBLIC.

See Also

  • token_name() - Get the symbolic name of a given PHP token


Get the symbolic name of a given PHP token

  • « token_get_all
  • URLs »
  • PHP Manual
  • Tokenizer Functions
  • Get the symbolic name of a given PHP token

token_name

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

token_name — Get the symbolic name of a given PHP token

Description

token_name ( int $token ) : string

token_name() gets the symbolic name for a PHP token value.

Parameters

token

The token value.

Return Values

The symbolic name of the given token.

Examples

Example #1 token_name() example

<?php
// 260 is the token value for the T_EVAL token
echo token_name(260);        // -> "T_EVAL"

// a token constant maps to its own name
echo token_name(T_FUNCTION); // -> "T_FUNCTION"
?>

See Also

  • List of Parser Tokens


URLs

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • URL Functions
    • base64_decode — Decodes data encoded with MIME base64
    • base64_encode — Encodes data with MIME base64
    • get_headers — Fetches all the headers sent by the server in response to an HTTP request
    • get_meta_tags — Extracts all meta tag content attributes from a file and returns an array
    • http_build_query — Generate URL-encoded query string
    • parse_url — Parse a URL and return its components
    • rawurldecode — Decode URL-encoded strings
    • rawurlencode — URL-encode according to RFC 3986
    • urldecode — Decodes URL-encoded string
    • urlencode — URL-encodes string


  • « URLs
  • Installing/Configuring »
  • PHP Manual
  • URLs
  • Introduction

Introduction

Dealing with URL strings: encoding, decoding and parsing.


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 are meant to be used with parse_url() and are available since PHP 5.1.2.

PHP_URL_SCHEME (integer)
PHP_URL_HOST (integer)
Outputs the hostname of the URL parsed.
PHP_URL_PORT (integer)
Outputs the port of the URL parsed.
PHP_URL_USER (integer)
Outputs the user of the URL parsed.
PHP_URL_PASS (integer)
Outputs the password of the URL parsed.
PHP_URL_PATH (integer)
Outputs the path of the URL parsed.
PHP_URL_QUERY (integer)
Outputs the query string of the URL parsed.
PHP_URL_FRAGMENT (integer)
Outputs the fragment (string after the hashmark #) of the URL parsed.

The following constants are meant to be used with http_build_query().

PHP_QUERY_RFC1738 (integer)
Encoding is performed per » RFC 1738 and the application/x-www-form-urlencoded media type, which implies that spaces are encoded as plus (+) signs.
PHP_QUERY_RFC3986 (integer)
Encoding is performed according to » RFC 3986, and spaces will be percent encoded (%20).


URL Functions

Table of Contents

  • base64_decode — Decodes data encoded with MIME base64
  • base64_encode — Encodes data with MIME base64
  • get_headers — Fetches all the headers sent by the server in response to an HTTP request
  • get_meta_tags — Extracts all meta tag content attributes from a file and returns an array
  • http_build_query — Generate URL-encoded query string
  • parse_url — Parse a URL and return its components
  • rawurldecode — Decode URL-encoded strings
  • rawurlencode — URL-encode according to RFC 3986
  • urldecode — Decodes URL-encoded string
  • urlencode — URL-encodes string


Decodes data encoded with MIME base64

  • « URL Functions
  • base64_encode »
  • PHP Manual
  • URL Functions
  • Decodes data encoded with MIME base64

base64_decode

(PHP 4, PHP 5, PHP 7)

base64_decode — Decodes data encoded with MIME base64

Description

base64_decode ( string $data [, bool $strict = FALSE ] ) : string

Decodes a base64 encoded data.

Parameters

data

The encoded data.

strict

If the strict parameter is set to TRUE then the base64_decode() function will return FALSE if the input contains character from outside the base64 alphabet. Otherwise invalid characters will be silently discarded.

Return Values

Returns the decoded data or FALSE on failure. The returned data may be binary.

Changelog

Version | Description
5.2.0 | strict added

Examples

Example #1 base64_decode() example

<?php
$str = 'VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==';
echo base64_decode($str);
?>

The above example will output:

This is an encoded string

See Also

  • base64_encode() - Encodes data with MIME base64
  • » RFC 2045 section 6.8


Encodes data with MIME base64

  • « base64_decode
  • get_headers »
  • PHP Manual
  • URL Functions
  • Encodes data with MIME base64

base64_encode

(PHP 4, PHP 5, PHP 7)

base64_encode — Encodes data with MIME base64

Description

base64_encode ( string $data ) : string

Encodes the given data with base64.

This encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean, such as mail bodies.

Base64-encoded data takes about 33% more space than the original data.

Parameters

data

The data to encode.

Return Values

The encoded data, as a string.

Examples

Example #1 base64_encode() example

<?php
$str = 'This is an encoded string';
echo base64_encode($str);
?>

The above example will output:

VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==

See Also

  • base64_decode() - Decodes data encoded with MIME base64
  • chunk_split() - Split a string into smaller chunks
  • convert_uuencode() - Uuencode a string
  • » RFC 2045 section 6.8


Fetches all the headers sent by the server in response to an HTTP request

  • « base64_encode
  • get_meta_tags »
  • PHP Manual
  • URL Functions
  • Fetches all the headers sent by the server in response to an HTTP request

get_headers

(PHP 5, PHP 7)

get_headers — Fetches all the headers sent by the server in response to an HTTP request

Description

get_headers ( string $url [, int $format = 0 [, resource $context ]] ) : array

get_headers() returns an array with the headers sent by the server in response to a HTTP request.

Parameters

url

The target URL.

format

If the optional format parameter is set to non-zero, get_headers() parses the response and sets the array's keys.

context

A valid context resource created with stream_context_create().

Return Values

Returns an indexed or associative array with the headers, or FALSE on failure.

Changelog

Version | Description
7.1.0 | The context parameter was added.
5.1.3 | This function now uses the default stream context, which can be set/changed with the stream_context_set_default() function.

Examples

Example #1 get_headers() example

<?php
$url = 'http://www.example.com';

print_r(get_headers($url));

print_r(get_headers($url, 1));
?>

The above example will output something similar to:

Array
(
    [0] => HTTP/1.1 200 OK
    [1] => Date: Sat, 29 May 2004 12:28:13 GMT
    [2] => Server: Apache/1.3.27 (Unix)  (Red-Hat/Linux)
    [3] => Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
    [4] => ETag: "3f80f-1b6-3e1cb03b"
    [5] => Accept-Ranges: bytes
    [6] => Content-Length: 438
    [7] => Connection: close
    [8] => Content-Type: text/html
)

Array
(
    [0] => HTTP/1.1 200 OK
    [Date] => Sat, 29 May 2004 12:28:14 GMT
    [Server] => Apache/1.3.27 (Unix)  (Red-Hat/Linux)
    [Last-Modified] => Wed, 08 Jan 2003 23:11:55 GMT
    [ETag] => "3f80f-1b6-3e1cb03b"
    [Accept-Ranges] => bytes
    [Content-Length] => 438
    [Connection] => close
    [Content-Type] => text/html
)

Example #2 get_headers() using HEAD example

<?php
// By default get_headers uses a GET request to fetch the headers. If you
// want to send a HEAD request instead, you can do so using a stream context:
stream_context_set_default(
    array(
        'http' => array(
            'method' => 'HEAD'
        )
    )
);
$headers = get_headers('http://example.com');
?>

See Also

  • apache_request_headers() - Fetch all HTTP request headers


Extracts all meta tag content attributes from a file and returns an array

  • « get_headers
  • http_build_query »
  • PHP Manual
  • URL Functions
  • Extracts all meta tag content attributes from a file and returns an array

get_meta_tags

(PHP 4, PHP 5, PHP 7)

get_meta_tags — Extracts all meta tag content attributes from a file and returns an array

Description

get_meta_tags ( string $filename [, bool $use_include_path = FALSE ] ) : array

Opens filename and parses it line by line for <meta> tags in the file. The parsing stops at </head>.

Parameters

filename

The path to the HTML file, as a string. This can be a local file or an URL.

Example #1 What get_meta_tags() parses

<meta name="author" content="name">
<meta name="keywords" content="php documentation">
<meta name="DESCRIPTION" content="a php manual">
<meta name="geo.position" content="49.33;-86.59">
</head> <!-- parsing stops here -->
(pay attention to line endings - PHP uses a native function to parse the input, so a Mac file won't work on Unix).

use_include_path

Setting use_include_path to TRUE will result in PHP trying to open the file along the standard include path as per the include_path directive. This is used for local files, not URLs.

Return Values

Returns an array with all the parsed meta tags.

The value of the name property becomes the key, the value of the content property becomes the value of the returned array, so you can easily use standard array functions to traverse it or access single values. Special characters in the value of the name property are substituted with '_', the rest is converted to lower case. If two meta tags have the same name, only the last one is returned.

Examples

Example #2 What get_meta_tags() returns

<?php
// Assuming the above tags are at www.example.com
$tags = get_meta_tags('http://www.example.com/');

// Notice how the keys are all lowercase now, and
// how . was replaced by _ in the key.
echo $tags['author'];       // name
echo $tags['keywords'];     // php documentation
echo $tags['description'];  // a php manual
echo $tags['geo_position']; // 49.33;-86.59
?>

Notes

Note:

Only meta tags with name attributes will be parsed. Quotes are not required.

See Also

  • htmlentities() - Convert all applicable characters to HTML entities
  • urlencode() - URL-encodes string


Generate URL-encoded query string

  • « get_meta_tags
  • parse_url »
  • PHP Manual
  • URL Functions
  • Generate URL-encoded query string

http_build_query

(PHP 5, PHP 7)

http_build_query — Generate URL-encoded query string

Description

http_build_query ( mixed $query_data [, string $numeric_prefix [, string $arg_separator [, int $enc_type = PHP_QUERY_RFC1738 ]]] ) : string

Generates a URL-encoded query string from the associative (or indexed) array provided.

Parameters

query_data

May be an array or object containing properties.

If query_data is an array, it may be a simple one-dimensional structure, or an array of arrays (which in turn may contain other arrays).

If query_data is an object, then only public properties will be incorporated into the result.

numeric_prefix

If numeric indices are used in the base array and this parameter is provided, it will be prepended to the numeric index for elements in the base array only.

This is meant to allow for legal variable names when the data is decoded by PHP or another CGI application later on.

arg_separator

arg_separator.output is used to separate arguments but may be overridden by specifying this parameter.

enc_type

By default, PHP_QUERY_RFC1738.

If enc_type is PHP_QUERY_RFC1738, then encoding is performed per » RFC 1738 and the application/x-www-form-urlencoded media type, which implies that spaces are encoded as plus (+) signs.

If enc_type is PHP_QUERY_RFC3986, then encoding is performed according to » RFC 3986, and spaces will be percent encoded (%20).

Return Values

Returns a URL-encoded string.

Changelog

Version | Description
5.4.0 | The enc_type parameter was added.
5.1.3 | Square brackets are escaped.
5.1.2 | The arg_separator parameter was added.

Examples

Example #1 Simple usage of http_build_query()

<?php
$data = array(
    'foo' => 'bar',
    'baz' => 'boom',
    'cow' => 'milk',
    'php' => 'hypertext processor'
);

echo http_build_query($data) . "\n";
echo http_build_query($data, '', '&amp;');

?>

The above example will output:

foo=bar&baz=boom&cow=milk&php=hypertext+processor
foo=bar&amp;baz=boom&amp;cow=milk&amp;php=hypertext+processor

Example #2 http_build_query() with numerically index elements.

<?php
$data = array('foo', 'bar', 'baz', 'boom', 'cow' => 'milk', 'php' => 'hypertext processor');

echo http_build_query($data) . "\n";
echo http_build_query($data, 'myvar_');
?>

The above example will output:

0=foo&1=bar&2=baz&3=boom&cow=milk&php=hypertext+processor
myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=boom&cow=milk&php=hypertext+processor

Example #3 http_build_query() with complex arrays

<?php
$data = array(
    'user' => array(
        'name' => 'Bob Smith',
        'age'  => 47,
        'sex'  => 'M',
        'dob'  => '5/12/1956'
    ),
    'pastimes' => array('golf', 'opera', 'poker', 'rap'),
    'children' => array(
        'bobby' => array('age'=>12, 'sex'=>'M'),
        'sally' => array('age'=>8, 'sex'=>'F')
    ),
    'CEO'
);

echo http_build_query($data, 'flags_');
?>

this will output : (word wrapped for readability)

user%5Bname%5D=Bob+Smith&user%5Bage%5D=47&user%5Bsex%5D=M&
user%5Bdob%5D=5%2F12%2F1956&pastimes%5B0%5D=golf&pastimes%5B1%5D=opera&
pastimes%5B2%5D=poker&pastimes%5B3%5D=rap&children%5Bbobby%5D%5Bage%5D=12&
children%5Bbobby%5D%5Bsex%5D=M&children%5Bsally%5D%5Bage%5D=8&
children%5Bsally%5D%5Bsex%5D=F&flags_0=CEO

Note:

Only the numerically indexed element in the base array "CEO" received a prefix. The other numeric indices, found under pastimes, do not require a string prefix to be legal variable names.

Example #4 Using http_build_query() with an object

<?php
class parentClass {
    public    $pub      = 'publicParent';
    protected $prot     = 'protectedParent';
    private   $priv     = 'privateParent';
    public    $pub_bar  = Null;
    protected $prot_bar = Null;
    private   $priv_bar = Null;

    public function __construct(){
        $this->pub_bar  = new childClass();
        $this->prot_bar = new childClass();
        $this->priv_bar = new childClass();
    }
}

class childClass {
    public    $pub  = 'publicChild';
    protected $prot = 'protectedChild';
    private   $priv = 'privateChild';
}

$parent = new parentClass();

echo http_build_query($parent);
?>

The above example will output:

pub=publicParent&pub_bar%5Bpub%5D=publicChild

See Also

  • parse_str() - Parses the string into variables
  • parse_url() - Parse a URL and return its components
  • urlencode() - URL-encodes string
  • array_walk() - Apply a user supplied function to every member of an array


Parse a URL and return its components

  • « http_build_query
  • rawurldecode »
  • PHP Manual
  • URL Functions
  • Parse a URL and return its components

parse_url

(PHP 4, PHP 5, PHP 7)

parse_url — Parse a URL and return its components

Description

parse_url ( string $url [, int $component = -1 ] ) : mixed

This function parses a URL and returns an associative array containing any of the various components of the URL that are present. The values of the array elements are not URL decoded.

This function is not meant to validate the given URL, it only breaks it up into the above listed parts. Partial URLs are also accepted, parse_url() tries its best to parse them correctly.

Parameters

url

The URL to parse. Invalid characters are replaced by _.

component

Specify one of PHP_URL_SCHEME, PHP_URL_HOST, PHP_URL_PORT, PHP_URL_USER, PHP_URL_PASS, PHP_URL_PATH, PHP_URL_QUERY or PHP_URL_FRAGMENT to retrieve just a specific URL component as a string (except when PHP_URL_PORT is given, in which case the return value will be an integer).

Return Values

On seriously malformed URLs, parse_url() may return FALSE.

If the component parameter is omitted, an associative array is returned. At least one element will be present within the array. Potential keys within this array are:

  • scheme - e.g. http
  • host
  • port
  • user
  • pass
  • path
  • query - after the question mark ?
  • fragment - after the hashmark #

If the component parameter is specified, parse_url() returns a string (or an integer, in the case of PHP_URL_PORT) instead of an array. If the requested component doesn't exist within the given URL, NULL will be returned.

Changelog

Version | Description
5.4.7 | Fixed host recognition when scheme is omitted and a leading component separator is present.
5.3.3 | Removed the E_WARNING that was emitted when URL parsing failed.
5.1.2 | Added the component parameter.

Examples

Example #1 A parse_url() example

<?php
$url = 'http://username:password@hostname:9090/path?arg=value#anchor';

var_dump(parse_url($url));
var_dump(parse_url($url, PHP_URL_SCHEME));
var_dump(parse_url($url, PHP_URL_USER));
var_dump(parse_url($url, PHP_URL_PASS));
var_dump(parse_url($url, PHP_URL_HOST));
var_dump(parse_url($url, PHP_URL_PORT));
var_dump(parse_url($url, PHP_URL_PATH));
var_dump(parse_url($url, PHP_URL_QUERY));
var_dump(parse_url($url, PHP_URL_FRAGMENT));
?>

The above example will output:

array(8) {
  ["scheme"]=>
  string(4) "http"
  ["host"]=>
  string(8) "hostname"
  ["port"]=>
  int(9090)
  ["user"]=>
  string(8) "username"
  ["pass"]=>
  string(8) "password"
  ["path"]=>
  string(5) "/path"
  ["query"]=>
  string(9) "arg=value"
  ["fragment"]=>
  string(6) "anchor"
}
string(4) "http"
string(8) "username"
string(8) "password"
string(8) "hostname"
int(9090)
string(5) "/path"
string(9) "arg=value"
string(6) "anchor"

Example #2 A parse_url() example with missing scheme

<?php
$url = '//www.example.com/path?googleguy=googley';

// Prior to 5.4.7 this would show the path as "//www.example.com/path"
var_dump(parse_url($url));
?>

The above example will output:

array(3) {
  ["host"]=>
  string(15) "www.example.com"
  ["path"]=>
  string(5) "/path"
  ["query"]=>
  string(17) "googleguy=googley"
}

Notes

Note:

This function may not give correct results for relative URLs.

Note:

This function is intended specifically for the purpose of parsing URLs and not URIs. However, to comply with PHP's backwards compatibility requirements it makes an exception for the file:// scheme where triple slashes (file:///...) are allowed. For any other scheme this is invalid.

See Also

  • pathinfo() - Returns information about a file path
  • parse_str() - Parses the string into variables
  • http_build_query() - Generate URL-encoded query string
  • dirname() - Returns a parent directory's path
  • basename() - Returns trailing name component of path
  • » RFC 3986


Decode URL-encoded strings

  • « parse_url
  • rawurlencode »
  • PHP Manual
  • URL Functions
  • Decode URL-encoded strings

rawurldecode

(PHP 4, PHP 5, PHP 7)

rawurldecode — Decode URL-encoded strings

Description

rawurldecode ( string $str ) : string

Returns a string in which the sequences with percent (%) signs followed by two hex digits have been replaced with literal characters.

Parameters

str

The URL to be decoded.

Return Values

Returns the decoded URL, as a string.

Examples

Example #1 rawurldecode() example

<?php

echo rawurldecode('foo%20bar%40baz'); // foo bar@baz

?>

Notes

Note:

rawurldecode() does not decode plus symbols ('+') into spaces. urldecode() does.

See Also

  • rawurlencode() - URL-encode according to RFC 3986
  • urldecode() - Decodes URL-encoded string
  • urlencode() - URL-encodes string
  • » RFC 3986


URL-encode according to RFC 3986

  • « rawurldecode
  • urldecode »
  • PHP Manual
  • URL Functions
  • URL-encode according to RFC 3986

rawurlencode

(PHP 4, PHP 5, PHP 7)

rawurlencode — URL-encode according to RFC 3986

Description

rawurlencode ( string $str ) : string

Encodes the given string according to » RFC 3986.

Parameters

str

The URL to be encoded.

Return Values

Returns a string in which all non-alphanumeric characters except -_.~ have been replaced with a percent (%) sign followed by two hex digits. This is the encoding described in » RFC 3986 for protecting literal characters from being interpreted as special URL delimiters, and for protecting URLs from being mangled by transmission media with character conversions (like some email systems).

Note:

Prior to PHP 5.3.0, rawurlencode encoded tildes (~) as per » RFC 1738.

Changelog

Version | Description
5.3.4 | Tilde characters are no longer encoded when rawurlencode() is used with EBCDIC strings.
5.3.0 | Now conforms to » RFC 3986.

Examples

Example #1 including a password in an FTP URL

<?php
echo '<a href="ftp://user:', rawurlencode('foo @+%/'),
     '@ftp.example.com/x.txt">';
?>

The above example will output:

<a href="ftp://user:foo%20%40%2B%25%2F@ftp.example.com/x.txt">

Or, if you pass information in a PATH_INFO component of the URL:

Example #2 rawurlencode() example 2

<?php
echo '<a href="http://example.com/department_list_script/',
    rawurlencode('sales and marketing/Miami'), '">';
?>

The above example will output:

<a href="http://example.com/department_list_script/sales%20and%20marketing%2FMiami">

See Also

  • rawurldecode() - Decode URL-encoded strings
  • urldecode() - Decodes URL-encoded string
  • urlencode() - URL-encodes string
  • » RFC 3986


Decodes URL-encoded string

  • « rawurlencode
  • urlencode »
  • PHP Manual
  • URL Functions
  • Decodes URL-encoded string

urldecode

(PHP 4, PHP 5, PHP 7)

urldecode — Decodes URL-encoded string

Description

urldecode ( string $str ) : string

Decodes any %## encoding in the given string. Plus symbols ('+') are decoded to a space character.

Parameters

str

The string to be decoded.

Return Values

Returns the decoded string.

Examples

Example #1 urldecode() example

<?php
$query = "my=apples&are=green+and+red";

foreach (explode('&', $query) as $chunk) {
    $param = explode("=", $chunk);

    if ($param) {
        printf("Value for parameter \"%s\" is \"%s\"<br/>\n", urldecode($param[0]), urldecode($param[1]));
    }
}
?>

Notes

Warning

The superglobals $_GET and $_REQUEST are already decoded. Using urldecode() on an element in $_GET or $_REQUEST could have unexpected and dangerous results.

See Also

  • urlencode() - URL-encodes string
  • rawurlencode() - URL-encode according to RFC 3986
  • rawurldecode() - Decode URL-encoded strings
  • » RFC 3986


URL-encodes string

  • « urldecode
  • V8js »
  • PHP Manual
  • URL Functions
  • URL-encodes string

urlencode

(PHP 4, PHP 5, PHP 7)

urlencode — URL-encodes string

Description

urlencode ( string $str ) : string

This function is convenient when encoding a string to be used in a query part of a URL, as a convenient way to pass variables to the next page.

Parameters

str

The string to be encoded.

Return Values

Returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. It is encoded the same way that the posted data from a WWW form is encoded, that is the same way as in application/x-www-form-urlencoded media type. This differs from the » RFC 3986 encoding (see rawurlencode()) in that for historical reasons, spaces are encoded as plus (+) signs.

Examples

Example #1 urlencode() example

<?php
echo '<a href="mycgi?foo=', urlencode($userinput), '">';
?>

Example #2 urlencode() and htmlentities() example

<?php
$query_string = 'foo=' . urlencode($foo) . '&bar=' . urlencode($bar);
echo '<a href="mycgi?' . htmlentities($query_string) . '">';
?>

Notes

Note:

Be careful about variables that may match HTML entities. Things like &amp, &copy and &pound are parsed by the browser and the actual entity is used instead of the desired variable name. This is an obvious hassle that the W3C has been telling people about for years. The reference is here: » http://www.w3.org/TR/html4/appendix/notes.html#h-B.2.2.

PHP supports changing the argument separator to the W3C-suggested semi-colon through the arg_separator .ini directive. Unfortunately most user agents do not send form data in this semi-colon separated format. A more portable way around this is to use &amp; instead of & as the separator. You don't need to change PHP's arg_separator for this. Leave it as &, but simply encode your URLs using htmlentities() or htmlspecialchars().

See Also

  • urldecode() - Decodes URL-encoded string
  • htmlentities() - Convert all applicable characters to HTML entities
  • rawurlencode() - URL-encode according to RFC 3986
  • rawurldecode() - Decode URL-encoded strings
  • » RFC 3986


V8 Javascript Engine Integration

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Examples
  • V8Js — The V8Js class
    • V8Js::__construct — Construct a new V8Js object
    • V8Js::executeString — Execute a string as Javascript code
    • V8Js::getExtensions — Return an array of registered extensions
    • V8Js::getPendingException — Return pending uncaught Javascript exception
    • V8Js::registerExtension — Register Javascript extensions for V8Js
  • V8JsException — The V8JsException class
    • V8JsException::getJsFileName — The getJsFileName purpose
    • V8JsException::getJsLineNumber — The getJsLineNumber purpose
    • V8JsException::getJsSourceLine — The getJsSourceLine purpose
    • V8JsException::getJsTrace — The getJsTrace purpose


  • « V8js
  • Installing/Configuring »
  • PHP Manual
  • V8js
  • Introduction

Introduction

This extension embeds the » V8 Javascript Engine into PHP.


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

PHP 5.3.3+ and V8 library and headers installed in proper paths.


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/v8js


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

V8js Configure Options
Name | Default | Changeable | Changelog
v8js.max_disposed_contexts | 25 | PHP_INI_ALL |
v8js.flags |  | PHP_INI_ALL |

Here's a short explanation of the configuration directives.

v8js.max_disposed_contexts integer

Sets limit for disposed contexts before forcing V8 to do garbage collection.

v8js.flags string

Sets V8 command line flags. The list of available flags can be obtained in CLI mode by setting this parameter to --help. Example:

$ php -r 'ini_set("v8js.flags", "--help"); new V8Js;' | less

Note:

For these flags to be effective in runtime the ini_set() call has to be done before any V8Js objects are instantiated!


Examples

Basic usage

Example #1 Basic Javascript execution

<?php

$v8 = new V8Js();

/* basic.js */
$JS = <<< EOT
len = print('Hello' + ' ' + 'World!' + "\\n");
len;
EOT;

try {
  var_dump($v8->executeString($JS, 'basic.js'));
} catch (V8JsException $e) {
  var_dump($e);
}

?>

The above example will output:

Hello World!
int(13)


The V8Js class

(PECL v8js >= 0.1.0)

Introduction

This is the core class for V8Js extension. Each instance created from this class has own context in which all JavaScript is compiled and executed.

See V8Js::__construct() for more information.

Class synopsis

V8Js {
/* Constants */
const string V8_VERSION ;
const integer FLAG_NONE = 1 ;
const integer FLAG_FORCE_ARRAY = 2 ;
/* Methods */
public __construct ([ string $object_name = "PHP" [, array $variables = array() [, array $extensions = array() [, bool $report_uncaught_exceptions = TRUE ]]]] )
public executeString ( string $script [, string $identifier = "V8Js::executeString()" [, int $flags = V8Js::FLAG_NONE ]] ) : mixed
public static getExtensions ( void ) : array
public getPendingException ( void ) : V8JsException
public static registerExtension ( string $extension_name , string $script [, array $dependencies = array() [, bool $auto_enable = FALSE ]] ) : bool
}

Predefined Constants

V8Js::V8_VERSION

The V8 Javascript Engine version.

V8Js::FLAG_NONE

No flags.

V8Js::FLAG_FORCE_ARRAY

Forces all JS objects to be associative arrays in PHP.

Table of Contents

  • V8Js::__construct — Construct a new V8Js object
  • V8Js::executeString — Execute a string as Javascript code
  • V8Js::getExtensions — Return an array of registered extensions
  • V8Js::getPendingException — Return pending uncaught Javascript exception
  • V8Js::registerExtension — Register Javascript extensions for V8Js


Construct a new V8Js object

  • « V8Js
  • V8Js::executeString »
  • PHP Manual
  • V8Js
  • Construct a new V8Js object

V8Js::__construct

(PECL v8js >= 0.1.0)

V8Js::__construct — Construct a new V8Js object

Description

 public V8Js::__construct
  ([ string $object_name = "PHP"
 [, array $variables = array()
 [, array $extensions = array()
 [, bool $report_uncaught_exceptions = TRUE
]]]] )

Constructs a new V8Js object.

Parameters

object_name

The name of the object passed to Javascript.

variables

Map of PHP variables that will be available in Javascript. Must be an associative array in format array("name-for-js" => "name-of-php-variable"). Defaults to empty array.

extensions

List of extensions registered using V8Js::registerExtension() which should be available in the Javascript context of the created V8Js object.

Note:

Extensions registered to be enabled automatically do not need to be listed in this array. Also if an extension has dependencies, those dependencies can be omitted as well. Defaults to empty array.

report_uncaught_exceptions

Controls whether uncaught Javascript exceptions are reported immediately or not. Defaults to TRUE. If set to FALSE the uncaught exception can be accessed using V8Js::getPendingException().

Return Values

Returns a new V8Js context object.


Execute a string as Javascript code

  • « V8Js::__construct
  • V8Js::getExtensions »
  • PHP Manual
  • V8Js
  • Execute a string as Javascript code

V8Js::executeString

(PECL v8js >= 0.1.0)

V8Js::executeString — Execute a string as Javascript code

Description

public V8Js::executeString ( string $script [, string $identifier = "V8Js::executeString()" [, int $flags = V8Js::FLAG_NONE ]] ) : mixed

Compiles and executes the string passed with script as Javascript code.

Parameters

script

The code string to be executed.

identifier

Identifier string for the executed code. Used for debugging.

flags

Execution flags. This value must be one of the V8Js::FLAG_* constants, defaulting to V8Js::FLAG_NONE.

  • V8Js::FLAG_NONE: no flags

  • V8Js::FLAG_FORCE_ARRAY: forces all Javascript objects passed to PHP to be associative arrays

Return Values

Returns the last variable instantiated in the Javascript code converted to matching PHP variable type.


Return an array of registered extensions

  • « V8Js::executeString
  • V8Js::getPendingException »
  • PHP Manual
  • V8Js
  • Return an array of registered extensions

V8Js::getExtensions

(PECL v8js >= 0.1.0)

V8Js::getExtensions — Return an array of registered extensions

Description

public static V8Js::getExtensions ( void ) : array

This function returns array of Javascript extensions registered using V8Js::registerExtension().

Parameters

This function has no parameters.

Return Values

Returns an array of registered extensions or an empty array if there are none.


Return pending uncaught Javascript exception

  • « V8Js::getExtensions
  • V8Js::registerExtension »
  • PHP Manual
  • V8Js
  • Return pending uncaught Javascript exception

V8Js::getPendingException

(PECL v8js >= 0.1.0)

V8Js::getPendingException — Return pending uncaught Javascript exception

Description

public V8Js::getPendingException ( void ) : V8JsException

Returns any pending uncaught Javascript exception as V8JsException left from earlier V8Js::executeString() call(s).

Parameters

This function has no parameters.

Return Values

Either V8JsException or NULL.


Register Javascript extensions for V8Js

  • « V8Js::getPendingException
  • V8JsException »
  • PHP Manual
  • V8Js
  • Register Javascript extensions for V8Js

V8Js::registerExtension

(PECL v8js >= 0.1.0)

V8Js::registerExtension — Register Javascript extensions for V8Js

Description

public static V8Js::registerExtension ( string $extension_name , string $script [, array $dependencies = array() [, bool $auto_enable = FALSE ]] ) : bool

Registers passed Javascript script as extension to be used in V8Js contexts.

Parameters

extension_name

Name of the extension to be registered.

script

The Javascript code to be registered.

dependencies

Array of extension names the extension to be registered depends on. Any such extension is enabled automatically when this extension is loaded.

Note:

All extensions, including the dependencies, must be registered before any V8Js are created which use them.

auto_enable

If set to TRUE, the extension will be enabled automatically in all V8Js contexts.

Return Values

Returns TRUE if extension was registered successfully, FALSE otherwise.


The V8JsException class

(PECL v8js >= 0.1.0)

Introduction

Class synopsis

V8JsException extends Exception {
/* Properties */
protected $JsFileName ;
protected $JsLineNumber ;
protected $JsSourceLine ;
protected $JsTrace ;
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Methods */
final public getJsFileName ( void ) : string
final public getJsLineNumber ( void ) : int
final public getJsSourceLine ( void ) : string
final public getJsTrace ( void ) : string
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}

Properties

JsFileName

JsLineNumber

JsSourceLine

JsTrace

Table of Contents

  • V8JsException::getJsFileName — The getJsFileName purpose
  • V8JsException::getJsLineNumber — The getJsLineNumber purpose
  • V8JsException::getJsSourceLine — The getJsSourceLine purpose
  • V8JsException::getJsTrace — The getJsTrace purpose


The getJsFileName purpose

  • « V8JsException
  • V8JsException::getJsLineNumber »
  • PHP Manual
  • V8JsException
  • The getJsFileName purpose

V8JsException::getJsFileName

(PECL v8js >= 0.1.0)

V8JsException::getJsFileName — The getJsFileName purpose

Description

final public V8JsException::getJsFileName ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The getJsLineNumber purpose

  • « V8JsException::getJsFileName
  • V8JsException::getJsSourceLine »
  • PHP Manual
  • V8JsException
  • The getJsLineNumber purpose

V8JsException::getJsLineNumber

(PECL v8js >= 0.1.0)

V8JsException::getJsLineNumber — The getJsLineNumber purpose

Description

final public V8JsException::getJsLineNumber ( void ) : int

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The getJsSourceLine purpose

  • « V8JsException::getJsLineNumber
  • V8JsException::getJsTrace »
  • PHP Manual
  • V8JsException
  • The getJsSourceLine purpose

V8JsException::getJsSourceLine

(PECL v8js >= 0.1.0)

V8JsException::getJsSourceLine — The getJsSourceLine purpose

Description

final public V8JsException::getJsSourceLine ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The getJsTrace purpose

  • « V8JsException::getJsSourceLine
  • Yaml »
  • PHP Manual
  • V8JsException
  • The getJsTrace purpose

V8JsException::getJsTrace

(PECL v8js >= 0.1.0)

V8JsException::getJsTrace — The getJsTrace purpose

Description

final public V8JsException::getJsTrace ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


YAML Data Serialization

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Callbacks
    • Parse callbacks
    • Emit callbacks
  • Yaml Functions
    • yaml_emit_file — Send the YAML representation of a value to a file
    • yaml_emit — Returns the YAML representation of a value
    • yaml_parse_file — Parse a YAML stream from a file
    • yaml_parse_url — Parse a Yaml stream from a URL
    • yaml_parse — Parse a YAML stream


Introduction

This extension implements the » YAML Ain't Markup Language (YAML) data serialization standard. Parsing and emiting are handled by the » LibYAML library.


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

This extension requires the » LibYAML C library version 0.1.0 or higher to be installed.


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/yaml.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Yaml Configure Options
Name | Default | Changeable | Changelog
yaml.decode_binary | 0 | PHP_INI_ALL |
yaml.decode_php | 0 | PHP_INI_ALL | Added in 1.2.0, before 2.0.0 the default was 1
yaml.decode_timestamp | 0 | PHP_INI_ALL |
yaml.output_canonical | 0 | PHP_INI_ALL |
yaml.output_indent | 2 | PHP_INI_ALL |
yaml.output_width | 80 | PHP_INI_ALL |

Here's a short explanation of the configuration directives.

yaml.decode_binary boolean

Off by default, but can be set to on to cause base64 binary encoded entities which have the explicit tag "tag:yaml.org,2002:binary" to be decoded.

yaml.decode_php boolean

Off by default, but can be set to on to cause serialized php objects which have the explicit tag "!php/object" to be unserialized.

yaml.decode_timestamp integer

Controls the decoding of both implicit and explicit "tag:yaml.org,2002:timestamp" scalars in the YAML document stream. The default setting of 0 will not apply any decoding. A setting of 1 will use strtotime() to parse the timestamp value as a Unix timestamp. A setting of 2 will use date_create() to parse the timestamp value as DateTime object.

yaml.output_canonical boolean

Off by default, but can be set to on to cause canonical form output.

yaml.output_indent integer

Number of spaces to indent sections. Value should be between 1 and 10.

yaml.output_width integer

Set the preferred line width. -1 means unlimited.


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.

Scalar entity styles usable by yaml_parse() callback methods.
YAML_ANY_SCALAR_STYLE (integer)
YAML_PLAIN_SCALAR_STYLE (integer)
YAML_SINGLE_QUOTED_SCALAR_STYLE (integer)
YAML_DOUBLE_QUOTED_SCALAR_STYLE (integer)
YAML_LITERAL_SCALAR_STYLE (integer)
YAML_FOLDED_SCALAR_STYLE (integer)
Common tags usable by yaml_parse() callback methods.
YAML_NULL_TAG (string)
"tag:yaml.org,2002:null"
YAML_BOOL_TAG (string)
"tag:yaml.org,2002:bool"
YAML_STR_TAG (string)
"tag:yaml.org,2002:str"
YAML_INT_TAG (string)
"tag:yaml.org,2002:int"
YAML_FLOAT_TAG (string)
"tag:yaml.org,2002:float"
YAML_TIMESTAMP_TAG (string)
"tag:yaml.org,2002:timestamp"
YAML_SEQ_TAG (string)
"tag:yaml.org,2002:seq"
YAML_MAP_TAG (string)
"tag:yaml.org,2002:map"
YAML_PHP_TAG (string)
"!php/object"
Encoding types for yaml_emit()
YAML_ANY_ENCODING (integer)
Let the emitter choose an encoding.
YAML_UTF8_ENCODING (integer)
Encode as UTF8.
YAML_UTF16LE_ENCODING (integer)
Encode as UTF16LE.
YAML_UTF16BE_ENCODING (integer)
Encode as UTF16BE.
Linebreak types for yaml_emit()
YAML_ANY_BREAK (integer)
Let emitter choose linebreak character.
YAML_CR_BREAK (integer)
Use \r as break character (Mac style).
YAML_LN_BREAK (integer)
Use \n as break character (Unix style).
YAML_CRLN_BREAK (integer)
Use \r\n as break character (DOS style).


Examples

Example #1 Yaml Example

<?php
$addr = array(
    "given" => "Chris",
    "family"=> "Dumars",
    "address"=> array(
        "lines"=> "458 Walkman Dr.
        Suite #292",
        "city"=> "Royal Oak",
        "state"=> "MI",
        "postal"=> 48046,
      ),
  );
$invoice = array (
    "invoice"=> 34843,
    "date"=> "2001-01-23",
    "bill-to"=> $addr,
    "ship-to"=> $addr,
    "product"=> array(
        array(
            "sku"=> "BL394D",
            "quantity"=> 4,
            "description"=> "Basketball",
            "price"=> 450,
          ),
        array(
            "sku"=> "BL4438H",
            "quantity"=> 1,
            "description"=> "Super Hoop",
            "price"=> 2392,
          ),
      ),
    "tax"=> 251.42,
    "total"=> 4443.52,
    "comments"=> "Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.",
    );

// generate a YAML representation of the invoice
$yaml = yaml_emit($invoice);
var_dump($yaml);

// convert the YAML back into a PHP variable
$parsed = yaml_parse($yaml);

// check that roundtrip conversion produced an equivalent structure
var_dump($parsed == $invoice);
?>

The above example will output something similar to:

string(631) "---
invoice: 34843
date: "2001-01-23"
bill-to:
  given: Chris
  family: Dumars
  address:
    lines: |-
      458 Walkman Dr.
              Suite #292
    city: Royal Oak
    state: MI
    postal: 48046
ship-to:
  given: Chris
  family: Dumars
  address:
    lines: |-
      458 Walkman Dr.
              Suite #292
    city: Royal Oak
    state: MI
    postal: 48046
product:
- sku: BL394D
  quantity: 4
  description: Basketball
  price: 450
- sku: BL4438H
  quantity: 1
  description: Super Hoop
  price: 2392
tax: 251.420000
total: 4443.520000
comments: Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.
...
"
bool(true)


  • « Examples
  • Parse callbacks »
  • PHP Manual
  • Yaml
  • Callbacks

Callbacks

Table of Contents

  • Parse callbacks
  • Emit callbacks


Parse callbacks

Parse callbacks are invoked by yaml_parse(), yaml_parse_file() or yaml_parse_url() functions when a registered YAML tag is encountered. The callback is passed the tagged entity's value, the tag, and flags indicating the scalar entity style. The callback must return the data that the YAML parser should emit for this entity.

Example #1 Parse callback example

<?php
/**
 * Parsing callback for yaml tag.
 * @param mixed $value Data from yaml file
 * @param string $tag Tag that triggered callback
 * @param int $flags Scalar entity style (see YAML_*_SCALAR_STYLE)
 * @return mixed Value that YAML parser should emit for the given value
 */
function tag_callback ($value, $tag, $flags) {
  var_dump(func_get_args()); // debugging
  return "Hello {$value}";
}

$yaml = <<<YAML
greeting: !example/hello World
YAML;

$result = yaml_parse($yaml, 0, $ndocs, array(
    '!example/hello' => 'tag_callback',
  ));

var_dump($result);
?>

The above example will output something similar to:

array(3) {
  [0]=>
  string(5) "World"
  [1]=>
  string(14) "!example/hello"
  [2]=>
  int(1)
}
array(1) {
  ["greeting"]=>
  string(11) "Hello World"
}


Emit callbacks

Emit callbacks are invoked when an instance of a registered class is emitted by yaml_emit() or yaml_emit_file(). The callback is passed the object to be emitted. The callback must return an array having two keys: "tag" and "data". The value associated with the "tag" key must be a string to be used as the YAML tag in the output. The value associated with the "data" key will be encoded as YAML and emitted in place of the intercepted object.

Example #1 Emit callback example

<?php
class EmitExample {
  public $data;    // data may be in any pecl/yaml suitable type

  public function __construct ($d) {
    $this->data = $d;
  }

  /**
   * Yaml emit callback function, referred on yaml_emit call by class name.
   *
   * Expected to return an array with 2 values:
   *   - 'tag': custom tag for this serialization
   *   - 'data': value to convert to yaml (array, string, bool, number)
   *
   * @param object $obj Object to be emitted
   * @return array Tag and surrogate data to emit
   */
  public static function yamlEmit (EmitExample $obj) {
    return array(
      'tag' => '!example/emit',
      'data' => $obj->data,
    );
  }
}

$emit_callbacks = array(
  'EmitExample' => array('EmitExample', 'yamlEmit')
);

$t = new EmitExample(array('a','b','c'));
$yaml = yaml_emit(
  array(
    'example' => $t,
  ),
  YAML_ANY_ENCODING,
  YAML_ANY_BREAK,
  $emit_callbacks
);
var_dump($yaml);
?>

The above example will output something similar to:

string(43) "---
example: !example/emit
- a
- b
- c
...
"


Yaml Functions

Table of Contents

  • yaml_emit_file — Send the YAML representation of a value to a file
  • yaml_emit — Returns the YAML representation of a value
  • yaml_parse_file — Parse a YAML stream from a file
  • yaml_parse_url — Parse a Yaml stream from a URL
  • yaml_parse — Parse a YAML stream


Send the YAML representation of a value to a file

  • « Yaml Functions
  • yaml_emit »
  • PHP Manual
  • Yaml Functions
  • Send the YAML representation of a value to a file

yaml_emit_file

(PECL yaml >= 0.5.0)

yaml_emit_file — Send the YAML representation of a value to a file

Description

yaml_emit_file ( string $filename , mixed $data [, int $encoding = YAML_ANY_ENCODING [, int $linebreak = YAML_ANY_BREAK [, array $callbacks = NULL ]]] ) : bool

Generate a YAML representation of the provided data in the filename.

Parameters

filename

Path to the file.

data

The data being encoded. Can be any type except a resource.

encoding

Output character encoding chosen from YAML_ANY_ENCODING, YAML_UTF8_ENCODING, YAML_UTF16LE_ENCODING, YAML_UTF16BE_ENCODING.

linebreak

Output linebreak style chosen from YAML_ANY_BREAK, YAML_CR_BREAK, YAML_LN_BREAK, YAML_CRLN_BREAK.

callbacks

Content handlers for emitting YAML nodes. Associative array of classname => callable mappings. See emit callbacks for more details.

Return Values

Returns TRUE on success.

Changelog

Version | Description
1.1.0 | The callbacks parameter was added.

See Also

  • yaml_emit() - Returns the YAML representation of a value
  • yaml_parse() - Parse a YAML stream


Returns the YAML representation of a value

  • « yaml_emit_file
  • yaml_parse_file »
  • PHP Manual
  • Yaml Functions
  • Returns the YAML representation of a value

yaml_emit

(PECL yaml >= 0.5.0)

yaml_emit — Returns the YAML representation of a value

Description

yaml_emit ( mixed $data [, int $encoding = YAML_ANY_ENCODING [, int $linebreak = YAML_ANY_BREAK [, array $callbacks = NULL ]]] ) : string

Generate a YAML representation of the provided data.

Parameters

data

The data being encoded. Can be any type except a resource.

encoding

Output character encoding chosen from YAML_ANY_ENCODING, YAML_UTF8_ENCODING, YAML_UTF16LE_ENCODING, YAML_UTF16BE_ENCODING.

linebreak

Output linebreak style chosen from YAML_ANY_BREAK, YAML_CR_BREAK, YAML_LN_BREAK, YAML_CRLN_BREAK.

callbacks

Content handlers for emitting YAML nodes. Associative array of classname => callable mappings. See emit callbacks for more details.

Return Values

Returns a YAML encoded string on success.

Changelog

Version | Description
1.1.0 | The callbacks parameter was added.

Examples

Example #1 yaml_emit() example

<?php
$addr = array(
    "given" => "Chris",
    "family"=> "Dumars",
    "address"=> array(
        "lines"=> "458 Walkman Dr.
        Suite #292",
        "city"=> "Royal Oak",
        "state"=> "MI",
        "postal"=> 48046,
      ),
  );
$invoice = array (
    "invoice"=> 34843,
    "date"=> 980208000,
    "bill-to"=> $addr,
    "ship-to"=> $addr,
    "product"=> array(
        array(
            "sku"=> "BL394D",
            "quantity"=> 4,
            "description"=> "Basketball",
            "price"=> 450,
          ),
        array(
            "sku"=> "BL4438H",
            "quantity"=> 1,
            "description"=> "Super Hoop",
            "price"=> 2392,
          ),
      ),
    "tax"=> 251.42,
    "total"=> 4443.52,
    "comments"=> "Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.",
  );
var_dump(yaml_emit($invoice));
?>

The above example will output something similar to:

string(628) "---
invoice: 34843
date: 980208000
bill-to:
  given: Chris
  family: Dumars
  address:
    lines: |-
      458 Walkman Dr.
              Suite #292
    city: Royal Oak
    state: MI
    postal: 48046
ship-to:
  given: Chris
  family: Dumars
  address:
    lines: |-
      458 Walkman Dr.
              Suite #292
    city: Royal Oak
    state: MI
    postal: 48046
product:
- sku: BL394D
  quantity: 4
  description: Basketball
  price: 450
- sku: BL4438H
  quantity: 1
  description: Super Hoop
  price: 2392
tax: 251.420000
total: 4443.520000
comments: Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.
...
"

See Also

  • yaml_emit_file() - Send the YAML representation of a value to a file
  • yaml_parse() - Parse a YAML stream


Parse a YAML stream from a file

  • « yaml_emit
  • yaml_parse_url »
  • PHP Manual
  • Yaml Functions
  • Parse a YAML stream from a file

yaml_parse_file

(PECL yaml >= 0.4.0)

yaml_parse_file — Parse a YAML stream from a file

Description

yaml_parse_file ( string $filename [, int $pos = 0 [, int &$ndocs [, array $callbacks = NULL ]]] ) : mixed

Convert all or part of a YAML document stream read from a file to a PHP variable.

Parameters

filename

Path to the file.

pos

Document to extract from stream (-1 for all documents, 0 for first document, ...).

ndocs

If ndocs is provided, then it is filled with the number of documents found in stream.

callbacks

Content handlers for YAML nodes. Associative array of YAML tag => callable mappings. See parse callbacks for more details.

Return Values

Returns the value encoded in input in appropriate PHP type or FALSE on failure. If pos is -1 an array will be returned with one entry for each document found in the stream.

Notes

Warning

Processing untrusted user input with yaml_parse_file() is dangerous if the use of unserialize() is enabled for nodes using the !php/object tag. This behavior can be disabled by using the yaml.decode_php ini setting.

See Also

  • yaml_parse() - Parse a YAML stream
  • yaml_parse_url() - Parse a Yaml stream from a URL
  • yaml_emit() - Returns the YAML representation of a value


Parse a Yaml stream from a URL

  • « yaml_parse_file
  • yaml_parse »
  • PHP Manual
  • Yaml Functions
  • Parse a Yaml stream from a URL

yaml_parse_url

(PECL yaml >= 0.4.0)

yaml_parse_url — Parse a Yaml stream from a URL

Description

yaml_parse_url ( string $url [, int $pos = 0 [, int &$ndocs [, array $callbacks = NULL ]]] ) : mixed

Convert all or part of a YAML document stream read from a URL to a PHP variable.

Parameters

url

url should be of the form "scheme://...". 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.

pos

Document to extract from stream (-1 for all documents, 0 for first document, ...).

ndocs

If ndocs is provided, then it is filled with the number of documents found in stream.

callbacks

Content handlers for YAML nodes. Associative array of YAML tag => callable mappings. See parse callbacks for more

Return Values

Returns the value encoded in input in appropriate PHP type or FALSE on failure. If pos is -1 an array will be returned with one entry for each document found in the stream.

Notes

Warning

Processing untrusted user input with yaml_parse_url() is dangerous if the use of unserialize() is enabled for nodes using the !php/object tag. This behavior can be disabled by using the yaml.decode_php ini setting.

See Also

  • yaml_parse() - Parse a YAML stream
  • yaml_parse_file() - Parse a YAML stream from a file
  • yaml_emit() - Returns the YAML representation of a value


Parse a YAML stream

  • « yaml_parse_url
  • Yaf »
  • PHP Manual
  • Yaml Functions
  • Parse a YAML stream

yaml_parse

(PECL yaml >= 0.4.0)

yaml_parse — Parse a YAML stream

Description

yaml_parse ( string $input [, int $pos = 0 [, int &$ndocs [, array $callbacks = NULL ]]] ) : mixed

Convert all or part of a YAML document stream to a PHP variable.

Parameters

input

The string to parse as a YAML document stream.

pos

Document to extract from stream (-1 for all documents, 0 for first document, ...).

ndocs

If ndocs is provided, then it is filled with the number of documents found in stream.

callbacks

Content handlers for YAML nodes. Associative array of YAML tag => callable mappings. See parse callbacks for more details.

Return Values

Returns the value encoded in input in appropriate PHP type or FALSE on failure. If pos is -1 an array will be returned with one entry for each document found in the stream.

Examples

Example #1 yaml_parse() example

<?php
$yaml = <<<EOD
---
invoice: 34843
date: "2001-01-23"
bill-to: &id001
  given: Chris
  family: Dumars
  address:
    lines: |-
      458 Walkman Dr.
              Suite #292
    city: Royal Oak
    state: MI
    postal: 48046
ship-to: *id001
product:
- sku: BL394D
  quantity: 4
  description: Basketball
  price: 450
- sku: BL4438H
  quantity: 1
  description: Super Hoop
  price: 2392
tax: 251.420000
total: 4443.520000
comments: Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.
...
EOD;

$parsed = yaml_parse($yaml);
var_dump($parsed);
?>

The above example will output something similar to:

array(8) {
  ["invoice"]=>
  int(34843)
  ["date"]=>
  string(10) "2001-01-23"
  ["bill-to"]=>
  &array(3) {
    ["given"]=>
    string(5) "Chris"
    ["family"]=>
    string(6) "Dumars"
    ["address"]=>
    array(4) {
      ["lines"]=>
      string(34) "458 Walkman Dr.
        Suite #292"
      ["city"]=>
      string(9) "Royal Oak"
      ["state"]=>
      string(2) "MI"
      ["postal"]=>
      int(48046)
    }
  }
  ["ship-to"]=>
  &array(3) {
    ["given"]=>
    string(5) "Chris"
    ["family"]=>
    string(6) "Dumars"
    ["address"]=>
    array(4) {
      ["lines"]=>
      string(34) "458 Walkman Dr.
        Suite #292"
      ["city"]=>
      string(9) "Royal Oak"
      ["state"]=>
      string(2) "MI"
      ["postal"]=>
      int(48046)
    }
  }
  ["product"]=>
  array(2) {
    [0]=>
    array(4) {
      ["sku"]=>
      string(6) "BL394D"
      ["quantity"]=>
      int(4)
      ["description"]=>
      string(10) "Basketball"
      ["price"]=>
      int(450)
    }
    [1]=>
    array(4) {
      ["sku"]=>
      string(7) "BL4438H"
      ["quantity"]=>
      int(1)
      ["description"]=>
      string(10) "Super Hoop"
      ["price"]=>
      int(2392)
    }
  }
  ["tax"]=>
  float(251.42)
  ["total"]=>
  float(4443.52)
  ["comments"]=>
  string(68) "Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338."
}

Notes

Warning

Processing untrusted user input with yaml_parse() is dangerous if the use of unserialize() is enabled for nodes using the !php/object tag. This behavior can be disabled by using the yaml.decode_php ini setting.

See Also

  • yaml_parse_file() - Parse a YAML stream from a file
  • yaml_parse_url() - Parse a Yaml stream from a URL
  • yaml_emit() - Returns the YAML representation of a value


Yet Another Framework

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Application Configuration
  • Yaf_Application — The Yaf_Application class
    • Yaf_Application::app — Retrieve an Application instance
    • Yaf_Application::bootstrap — Call bootstrap
    • Yaf_Application::clearLastError — Clear the last error info
    • Yaf_Application::__clone — Yaf_Application can not be cloned
    • Yaf_Application::__construct — Yaf_Application constructor
    • Yaf_Application::__destruct — The __destruct purpose
    • Yaf_Application::environ — Retrive environ
    • Yaf_Application::execute — Execute a callback
    • Yaf_Application::getAppDirectory — Get the application directory
    • Yaf_Application::getConfig — Retrive the config instance
    • Yaf_Application::getDispatcher — Get Yaf_Dispatcher instance
    • Yaf_Application::getLastErrorMsg — Get message of the last occurred error
    • Yaf_Application::getLastErrorNo — Get code of last occurred error
    • Yaf_Application::getModules — Get defined module names
    • Yaf_Application::run — Start Yaf_Application
    • Yaf_Application::setAppDirectory — Change the application directory
    • Yaf_Application::__sleep — Yaf_Application can not be serialized
    • Yaf_Application::__wakeup — Yaf_Application can not be unserialized
  • Yaf_Bootstrap_Abstract — The Yaf_Bootstrap_Abstract class
  • Yaf_Dispatcher — The Yaf_Dispatcher class
    • Yaf_Dispatcher::autoRender — Switch on/off autorendering
    • Yaf_Dispatcher::catchException — Switch on/off exception catching
    • Yaf_Dispatcher::__clone — Yaf_Dispatcher can not be cloned
    • Yaf_Dispatcher::__construct — Yaf_Dispatcher constructor
    • Yaf_Dispatcher::disableView — Disable view rendering
    • Yaf_Dispatcher::dispatch — Dispatch a request
    • Yaf_Dispatcher::enableView — Enable view rendering
    • Yaf_Dispatcher::flushInstantly — Switch on/off the instant flushing
    • Yaf_Dispatcher::getApplication — Retrive the application
    • Yaf_Dispatcher::getInstance — Retrive the dispatcher instance
    • Yaf_Dispatcher::getRequest — Retrive the request instance
    • Yaf_Dispatcher::getRouter — Retrive router instance
    • Yaf_Dispatcher::initView — Initialize view and return it
    • Yaf_Dispatcher::registerPlugin — Register a plugin
    • Yaf_Dispatcher::returnResponse — The returnResponse purpose
    • Yaf_Dispatcher::setDefaultAction — Change default action name
    • Yaf_Dispatcher::setDefaultController — Change default controller name
    • Yaf_Dispatcher::setDefaultModule — Change default module name
    • Yaf_Dispatcher::setErrorHandler — Set error handler
    • Yaf_Dispatcher::setRequest — The setRequest purpose
    • Yaf_Dispatcher::setView — Set a custom view engine
    • Yaf_Dispatcher::__sleep — Yaf_Dispatcher can not be serialized
    • Yaf_Dispatcher::throwException — Switch on/off exception throwing
    • Yaf_Dispatcher::__wakeup — Yaf_Dispatcher can not be unserialized
  • Yaf_Config_Abstract — The Yaf_Config_Abstract class
    • Yaf_Config_Abstract::get — Getter
    • Yaf_Config_Abstract::readonly — Find a config whether readonly
    • Yaf_Config_Abstract::set — Setter
    • Yaf_Config_Abstract::toArray — Cast to array
  • Yaf_Config_Ini — The Yaf_Config_Ini class
    • Yaf_Config_Ini::__construct — Yaf_Config_Ini constructor
    • Yaf_Config_Ini::count — Count all elements in Yaf_Config.ini
    • Yaf_Config_Ini::current — Retrieve the current value
    • Yaf_Config_Ini::__get — Retrieve a element
    • Yaf_Config_Ini::__isset — Determine if a key is exists
    • Yaf_Config_Ini::key — Fetch current element's key
    • Yaf_Config_Ini::next — Advance the internal pointer
    • Yaf_Config_Ini::offsetExists — The offsetExists purpose
    • Yaf_Config_Ini::offsetGet — The offsetGet purpose
    • Yaf_Config_Ini::offsetSet — The offsetSet purpose
    • Yaf_Config_Ini::offsetUnset — The offsetUnset purpose
    • Yaf_Config_Ini::readonly — The readonly purpose
    • Yaf_Config_Ini::rewind — The rewind purpose
    • Yaf_Config_Ini::__set — The __set purpose
    • Yaf_Config_Ini::toArray — Return config as a PHP array
    • Yaf_Config_Ini::valid — The valid purpose
  • Yaf_Config_Simple — The Yaf_Config_Simple class
    • Yaf_Config_Simple::__construct — The __construct purpose
    • Yaf_Config_Simple::count — The count purpose
    • Yaf_Config_Simple::current — The current purpose
    • Yaf_Config_Simple::__get — The __get purpose
    • Yaf_Config_Simple::__isset — The __isset purpose
    • Yaf_Config_Simple::key — The key purpose
    • Yaf_Config_Simple::next — The next purpose
    • Yaf_Config_Simple::offsetExists — The offsetExists purpose
    • Yaf_Config_Simple::offsetGet — The offsetGet purpose
    • Yaf_Config_Simple::offsetSet — The offsetSet purpose
    • Yaf_Config_Simple::offsetUnset — The offsetUnset purpose
    • Yaf_Config_Simple::readonly — The readonly purpose
    • Yaf_Config_Simple::rewind — The rewind purpose
    • Yaf_Config_Simple::__set — The __set purpose
    • Yaf_Config_Simple::toArray — Returns a PHP array
    • Yaf_Config_Simple::valid — The valid purpose
  • Yaf_Controller_Abstract — The Yaf_Controller_Abstract class
    • Yaf_Controller_Abstract::__clone — Yaf_Controller_Abstract can not be cloned
    • Yaf_Controller_Abstract::__construct — Yaf_Controller_Abstract constructor
    • Yaf_Controller_Abstract::display — The display purpose
    • Yaf_Controller_Abstract::forward — Foward to another action
    • Yaf_Controller_Abstract::getInvokeArg — The getInvokeArg purpose
    • Yaf_Controller_Abstract::getInvokeArgs — The getInvokeArgs purpose
    • Yaf_Controller_Abstract::getModuleName — Get module name
    • Yaf_Controller_Abstract::getRequest — Retrieve current request object
    • Yaf_Controller_Abstract::getResponse — Retrieve current response object
    • Yaf_Controller_Abstract::getView — Retrieve the view engine
    • Yaf_Controller_Abstract::getViewpath — The getViewpath purpose
    • Yaf_Controller_Abstract::init — Controller initializer
    • Yaf_Controller_Abstract::initView — The initView purpose
    • Yaf_Controller_Abstract::redirect — Redirect to a URL
    • Yaf_Controller_Abstract::render — Render view template
    • Yaf_Controller_Abstract::setViewpath — The setViewpath purpose
  • Yaf_Action_Abstract — The Yaf_Action_Abstract class
    • Yaf_Action_Abstract::execute — Action entry point
    • Yaf_Action_Abstract::getController — Retrieve controller object
  • Yaf_View_Interface — The Yaf_View_Interface class
    • Yaf_View_Interface::assign — Assign value to View engine
    • Yaf_View_Interface::display — Render and output a template
    • Yaf_View_Interface::getScriptPath — The getScriptPath purpose
    • Yaf_View_Interface::render — Render a template
    • Yaf_View_Interface::setScriptPath — The setScriptPath purpose
  • Yaf_View_Simple — The Yaf_View_Simple class
    • Yaf_View_Simple::assign — Assign values
    • Yaf_View_Simple::assignRef — The assignRef purpose
    • Yaf_View_Simple::clear — Clear Assigned values
    • Yaf_View_Simple::__construct — Constructor of Yaf_View_Simple
    • Yaf_View_Simple::display — Render and display
    • Yaf_View_Simple::eval — Render template
    • Yaf_View_Simple::__get — Retrieve assigned variable
    • Yaf_View_Simple::getScriptPath — Get templates directory
    • Yaf_View_Simple::__isset — The __isset purpose
    • Yaf_View_Simple::render — Render template
    • Yaf_View_Simple::__set — Set value to engine
    • Yaf_View_Simple::setScriptPath — Set tempaltes directory
  • Yaf_Loader — The Yaf_Loader class
    • Yaf_Loader::autoload — The autoload purpose
    • Yaf_Loader::clearLocalNamespace — The clearLocalNamespace purpose
    • Yaf_Loader::__clone — The __clone purpose
    • Yaf_Loader::__construct — The __construct purpose
    • Yaf_Loader::getInstance — The getInstance purpose
    • Yaf_Loader::getLibraryPath — Get the library path
    • Yaf_Loader::getLocalNamespace — The getLocalNamespace purpose
    • Yaf_Loader::import — The import purpose
    • Yaf_Loader::isLocalName — The isLocalName purpose
    • Yaf_Loader::registerLocalNamespace — Register local class prefix
    • Yaf_Loader::setLibraryPath — Change the library path
    • Yaf_Loader::__sleep — The __sleep purpose
    • Yaf_Loader::__wakeup — The __wakeup purpose
  • Yaf_Plugin_Abstract — The Yaf_Plugin_Abstract class
    • Yaf_Plugin_Abstract::dispatchLoopShutdown — The dispatchLoopShutdown purpose
    • Yaf_Plugin_Abstract::dispatchLoopStartup — Hook before dispatch loop
    • Yaf_Plugin_Abstract::postDispatch — The postDispatch purpose
    • Yaf_Plugin_Abstract::preDispatch — The preDispatch purpose
    • Yaf_Plugin_Abstract::preResponse — The preResponse purpose
    • Yaf_Plugin_Abstract::routerShutdown — The routerShutdown purpose
    • Yaf_Plugin_Abstract::routerStartup — RouterStartup hook
  • Yaf_Registry — The Yaf_Registry class
    • Yaf_Registry::__clone — The __clone purpose
    • Yaf_Registry::__construct — Yaf_Registry implements singleton
    • Yaf_Registry::del — Remove an item from registry
    • Yaf_Registry::get — Retrieve an item from registry
    • Yaf_Registry::has — Check whether an item exists
    • Yaf_Registry::set — Add an item into registry
  • Yaf_Request_Abstract — The Yaf_Request_Abstract class
    • Yaf_Request_Abstract::getActionName — The getActionName purpose
    • Yaf_Request_Abstract::getBaseUri — The getBaseUri purpose
    • Yaf_Request_Abstract::getControllerName — The getControllerName purpose
    • Yaf_Request_Abstract::getEnv — Retrieve ENV varialbe
    • Yaf_Request_Abstract::getException — The getException purpose
    • Yaf_Request_Abstract::getLanguage — Retrieve client's prefered language
    • Yaf_Request_Abstract::getMethod — Retrieve the request method
    • Yaf_Request_Abstract::getModuleName — The getModuleName purpose
    • Yaf_Request_Abstract::getParam — Retrieve calling parameter
    • Yaf_Request_Abstract::getParams — Retrieve all calling parameters
    • Yaf_Request_Abstract::getRequestUri — The getRequestUri purpose
    • Yaf_Request_Abstract::getServer — Retrieve SERVER variable
    • Yaf_Request_Abstract::isCli — Determine if request is CLI request
    • Yaf_Request_Abstract::isDispatched — Determin if the request is dispatched
    • Yaf_Request_Abstract::isGet — Determine if request is GET request
    • Yaf_Request_Abstract::isHead — Determine if request is HEAD request
    • Yaf_Request_Abstract::isOptions — Determine if request is OPTIONS request
    • Yaf_Request_Abstract::isPost — Determine if request is POST request
    • Yaf_Request_Abstract::isPut — Determine if request is PUT request
    • Yaf_Request_Abstract::isRouted — Determin if request has been routed
    • Yaf_Request_Abstract::isXmlHttpRequest — Determine if request is AJAX request
    • Yaf_Request_Abstract::setActionName — The setActionName purpose
    • Yaf_Request_Abstract::setBaseUri — Set base URI
    • Yaf_Request_Abstract::setControllerName — The setControllerName purpose
    • Yaf_Request_Abstract::setDispatched — The setDispatched purpose
    • Yaf_Request_Abstract::setModuleName — The setModuleName purpose
    • Yaf_Request_Abstract::setParam — Set a calling parameter to a request
    • Yaf_Request_Abstract::setRequestUri — The setRequestUri purpose
    • Yaf_Request_Abstract::setRouted — The setRouted purpose
  • Yaf_Request_Http — The Yaf_Request_Http class
    • Yaf_Request_Http::__clone — Yaf_Request_Http can not be cloned
    • Yaf_Request_Http::__construct — Constructor of Yaf_Request_Http
    • Yaf_Request_Http::get — Retrieve variable from client
    • Yaf_Request_Http::getCookie — Retrieve Cookie variable
    • Yaf_Request_Http::getFiles — The getFiles purpose
    • Yaf_Request_Http::getPost — Retrieve POST variable
    • Yaf_Request_Http::getQuery — Fetch a query parameter
    • Yaf_Request_Http::getRaw — Retrieve Raw request body
    • Yaf_Request_Http::getRequest — The getRequest purpose
    • Yaf_Request_Http::isXmlHttpRequest — Determin if request is Ajax Request
  • Yaf_Request_Simple — The Yaf_Request_Simple class
    • Yaf_Request_Simple::__clone — The __clone purpose
    • Yaf_Request_Simple::__construct — Constructor of Yaf_Request_Simple
    • Yaf_Request_Simple::get — The get purpose
    • Yaf_Request_Simple::getCookie — The getCookie purpose
    • Yaf_Request_Simple::getFiles — The getFiles purpose
    • Yaf_Request_Simple::getPost — The getPost purpose
    • Yaf_Request_Simple::getQuery — The getQuery purpose
    • Yaf_Request_Simple::getRequest — The getRequest purpose
    • Yaf_Request_Simple::isXmlHttpRequest — Determin if request is AJAX request
  • Yaf_Response_Abstract — The Yaf_Response_Abstract class
    • Yaf_Response_Abstract::appendBody — Append to response body
    • Yaf_Response_Abstract::clearBody — Discard all exists response body
    • Yaf_Response_Abstract::clearHeaders — Discard all set headers
    • Yaf_Response_Abstract::__clone — The __clone purpose
    • Yaf_Response_Abstract::__construct — The __construct purpose
    • Yaf_Response_Abstract::__destruct — The __destruct purpose
    • Yaf_Response_Abstract::getBody — Retrieve a exists content
    • Yaf_Response_Abstract::getHeader — The getHeader purpose
    • Yaf_Response_Abstract::prependBody — The prependBody purpose
    • Yaf_Response_Abstract::response — Send response
    • Yaf_Response_Abstract::setAllHeaders — The setAllHeaders purpose
    • Yaf_Response_Abstract::setBody — Set content to response
    • Yaf_Response_Abstract::setHeader — Set reponse header
    • Yaf_Response_Abstract::setRedirect — The setRedirect purpose
    • Yaf_Response_Abstract::__toString — Retrieve all bodys as string
  • Yaf_Route_Interface — The Yaf_Route_Interface class
    • Yaf_Route_Interface::assemble — Assemble a request
    • Yaf_Route_Interface::route — Route a request
  • Yaf_Route_Map — The Yaf_Route_Map class
    • Yaf_Route_Map::assemble — Assemble a url
    • Yaf_Route_Map::__construct — The __construct purpose
    • Yaf_Route_Map::route — The route purpose
  • Yaf_Route_Regex — The Yaf_Route_Regex class
    • Yaf_Route_Regex::assemble — Assemble a url
    • Yaf_Route_Regex::__construct — Yaf_Route_Regex constructor
    • Yaf_Route_Regex::route — The route purpose
  • Yaf_Route_Rewrite — The Yaf_Route_Rewrite class
    • Yaf_Route_Rewrite::assemble — Assemble a url
    • Yaf_Route_Rewrite::__construct — Yaf_Route_Rewrite constructor
    • Yaf_Route_Rewrite::route — The route purpose
  • Yaf_Router — The Yaf_Router class
    • Yaf_Router::addConfig — Add config-defined routes into Router
    • Yaf_Router::addRoute — Add new Route into Router
    • Yaf_Router::__construct — Yaf_Router constructor
    • Yaf_Router::getCurrentRoute — Get the effective route name
    • Yaf_Router::getRoute — Retrieve a route by name
    • Yaf_Router::getRoutes — Retrieve registered routes
    • Yaf_Router::route — The route purpose
  • Yaf_Route_Simple — The Yaf_Route_Simple class
    • Yaf_Route_Simple::assemble — Assemble a url
    • Yaf_Route_Simple::__construct — Yaf_Route_Simple constructor
    • Yaf_Route_Simple::route — Route a request
  • Yaf_Route_Static — The Yaf_Route_Static class
    • Yaf_Route_Static::assemble — Assemble a url
    • Yaf_Route_Static::match — The match purpose
    • Yaf_Route_Static::route — Route a request
  • Yaf_Route_Supervar — The Yaf_Route_Supervar class
    • Yaf_Route_Supervar::assemble — Assemble a url
    • Yaf_Route_Supervar::__construct — The __construct purpose
    • Yaf_Route_Supervar::route — The route purpose
  • Yaf_Session — The Yaf_Session class
    • Yaf_Session::__clone — The __clone purpose
    • Yaf_Session::__construct — Constructor of Yaf_Session
    • Yaf_Session::count — The count purpose
    • Yaf_Session::current — The current purpose
    • Yaf_Session::del — The del purpose
    • Yaf_Session::__get — The __get purpose
    • Yaf_Session::getInstance — The getInstance purpose
    • Yaf_Session::has — The has purpose
    • Yaf_Session::__isset — The __isset purpose
    • Yaf_Session::key — The key purpose
    • Yaf_Session::next — The next purpose
    • Yaf_Session::offsetExists — The offsetExists purpose
    • Yaf_Session::offsetGet — The offsetGet purpose
    • Yaf_Session::offsetSet — The offsetSet purpose
    • Yaf_Session::offsetUnset — The offsetUnset purpose
    • Yaf_Session::rewind — The rewind purpose
    • Yaf_Session::__set — The __set purpose
    • Yaf_Session::__sleep — The __sleep purpose
    • Yaf_Session::start — The start purpose
    • Yaf_Session::__unset — The __unset purpose
    • Yaf_Session::valid — The valid purpose
    • Yaf_Session::__wakeup — The __wakeup purpose
  • Yaf_Exception — The Yaf_Exception class
    • Yaf_Exception::__construct — The __construct purpose
    • Yaf_Exception::getPrevious — The getPrevious purpose
  • Yaf_Exception_TypeError — The Yaf_Exception_TypeError class
  • Yaf_Exception_StartupError — The Yaf_Exception_StartupError class
  • Yaf_Exception_DispatchFailed — The Yaf_Exception_DispatchFailed class
  • Yaf_Exception_RouterFailed — The Yaf_Exception_RouterFailed class
  • Yaf_Exception_LoadFailed — The Yaf_Exception_LoadFailed class
  • Yaf_Exception_LoadFailed_Module — The Yaf_Exception_LoadFailed_Module class
  • Yaf_Exception_LoadFailed_Controller — The Yaf_Exception_LoadFailed_Controller class
  • Yaf_Exception_LoadFailed_Action — The Yaf_Exception_LoadFailed_Action class
  • Yaf_Exception_LoadFailed_View — The Yaf_Exception_LoadFailed_View class


Introduction

The Yet Another Framework (Yaf) extension is a PHP framework that is used to develop web applications.

Yaf requires PHP 5.2.1 or greater. Earlier versions may not work.

A simple Yaf benchmark can be found at » Yaf Performance.

For a quick start guide, please refer to the Tutorials section.


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/yaf.

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.

Yaf Configure Options
Name | Default | Changeable | Changelog
yaf.library |  | PHP_INI_ALL |
yaf.action_prefer | 0 | PHP_INI_ALL |
yaf.lowcase_path | 0 | PHP_INI_ALL |
yaf.use_spl_autoload | 0 | PHP_INI_ALL |
yaf.forward_limit | 5 | PHP_INI_ALL |
yaf.name_suffix | 1 | PHP_INI_ALL |
yaf.name_separator |  | PHP_INI_ALL |
yaf.cache_config | 0 | PHP_INI_SYSTEM |
yaf.environ | product | PHP_INI_SYSTEM |
yaf.use_namespace | 0 | PHP_INI_SYSTEM |

Here's a short explanation of the configuration directives.

yaf.library string

The global library path, Yaf_loader will search global library in this directory.

yaf.action_prefer integer

If there is only one part in PATH_INFO, should it consider as a controller or action.

If this configure On, it will be considered as a Action name.

yaf.lowcase_path integer

Whether lowercase all the path during the class autoloading.

yaf.use_spl_autoload integer

When this value is On, if Yaf_Loader can not find a class, it will return FALSE, then give chance to other auto load function to be called.

When this value is Off, if Yaf_Loader can not find a class, it will return TRUE, and make the class autoloading failed immediately.

Note:

Yaf will register its loader during a instantiation of Yaf_Application, so any other auto loaders which is register before the instantiation will be called before Yaf_Loader::autoload().

When this value is Off(default), Yaf_Loader::autoload() will always return TRUE.

yaf.forward_limit integer

The max forward count, default is 5. that means you can have a max value of 5 in the forward stack.

This is a protection for prevent recursive Yaf_Controller_Abstract::forward().

yaf.name_suffix integer

When this On, Yaf_Loader will identify a class by it's suffix to decide whether it is a MVC Class.

When this Off, Yaf_Loader will look at the prefix of the class name.

yaf.name_separator string

When this is not empty, Yaf_Loader will identify the class suffix and string value of this.

For example, when this value is "_", Yaf_Loader will take Index_Controller as a Controller Class, IndexController as a normal class.

yaf.cache_config integer

If this is On, and in the meantime you are using ini config file as the parameter of Yaf_Application(), the compiling result of the ini config file will be cached in the PHP process.

Note:

Yaf examine the mtime of the ini file, if it was changed since last compiling, Yaf will reload it.

Warning

Yaf use the ini file path as the cache entry key, so do use the absolute path in ini file path, otherwise there might be some conflicts if two application use the same relative path of ini config.

yaf.environ string

This value is "product" by default, used for Yaf to fetch the config section of a ini config file.

That is, if this value is "product", Yaf will use the section named "product" in the ini config file(the first parameter of the Yaf_Application) as the final config of the Yaf_Application.

yaf.use_namespace integer

Only works as of PHP 5.3, if this value is On, All classes of Yaf will named in namespace style.

For example:

Yaf_Route_Rewrite => \Yaf\Route\Rewrite
Yaf_Request_Http  => \Yaf\Request\Http
There is a exception, that is some classes like Yaf_Controller_Abstract. The last component is a keyword of PHP, could not be used as a class name, so for such classes:
Yaf_Controller_Abstract => \Yaf\Controller_Abstract
Yaf_Route_Static => \Yaf\Route_Static


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.

YAF_VERSION (string)
YAF_ENVIRON (string)
YAF_ERR_STARTUP_FAILED (integer)
YAF_ERR_ROUTE_FAILED (integer)
YAF_ERR_DISPATCH_FAILED (integer)
YAF_ERR_AUTOLOAD_FAILED (integer)
YAF_ERR_NOTFOUND_MODULE (integer)
YAF_ERR_NOTFOUND_CONTROLLER (integer)
YAF_ERR_NOTFOUND_ACTION (integer)
YAF_ERR_NOTFOUND_VIEW (integer)
YAF_ERR_CALL_FAILED (integer)
YAF_ERR_TYPE_ERROR (integer)


Examples

Example #1 A classic Application directory layout

- index.php
- .htaccess
+ conf
  |- application.ini //application config
- application/
  - Bootstrap.php
  + controllers
     - Index.php //default controller
  + views
     |+ index
        - index.phtml //view template for default action
  + modules
  - library
  - models
  - plugins

Example #2 Entry

index.php in the top directory is the only way in of the application, you should rewrite all request to it. (You can use .htaccess in Apache + php_mod)

<?php
define("APPLICATION_PATH",  dirname(__FILE__));

$app  = new Yaf_Application(APPLICATION_PATH . "/conf/application.ini");
$app->bootstrap() //call bootstrap methods defined in Bootstrap.php
 ->run();
?>

Example #3 Rewrite rule

#for apache (.htaccess)
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* index.php

#for nginx
server {
  listen ****;
  server_name  domain.com;
  root   document_root;
  index  index.php index.html index.htm;

  if (!-e $request_filename) {
    rewrite ^/(.*)  /index.php/$1 last;
  }
}

#for lighttpd
$HTTP["host"] =~ "(www.)?domain.com$" {
  url.rewrite = (
     "^/(.+)/?$"  => "/index.php/$1",
  )
}

Example #4 Application config

[yaf]
;APPLICATION_PATH is the constant defined in index.php
application.directory=APPLICATION_PATH "/application/"

;product section inherit from yaf section
[product:yaf]
foo=bar

Example #5 Default controller

<?php
class IndexController extends Yaf_Controller_Abstract {
   /* default action */
   public function indexAction() {
       $this->_view->word = "hello world";
       //or
       // $this->getView()->word = "hello world";
   }
}
?>

Example #6 Default view template

<html>
 <head>
   <title>Hello World</title>
 </head>
 <body>
   <?php echo $word;?>
 </body>
</html>

Example #7 Run the Application

The above example will output something similar to:

<html>
 <head>
   <title>Hello World</title>
 </head>
 <body>
   hello world
 </body>
</html>

Note:

you can also generate above example by use Yaf codes generator, which could be found here yaf@github.


Application Configuration

You should give an array of config or an ini config file(see Yaf_Config_Ini) path to Yaf_Application::__construct().

Yaf will merge the application configurations and user configurations automatically. The application configurations have prefix "yaf." or "application.". If both "yaf." and "application." exist, "application." will be accepted preferentially.

Example #1 An PHP array example

<?php
    $configs = array(
            "application" => array(
                "directory" => dirname(__FILE__),
                "dispatcher" => array(
                      "catchException" => 0,
                    ),
                "view" => array(
                       "ext" => "phtml",
                    ),
                ),
           );
    $app = new Yaf_Application($configs);
?>

Example #2 An ini file example

[yaf]
yaf.directory = APPLICATION_PATH "/appliation"
yaf.dispatcher.catchException = 0

[product : yaf]
; user configuration list here

Yaf Application Config
Name | Default | Changelog
application.directory |  |
application.ext | "php" |
application.view.ext | "phtml" |
application.modules | "index" |
application.library | application.directory . "/library" |
application.library.directory | application.directory . "/library" |
application.library.namespace | "" |
application.bootstrap | application.directory . "/Bootstrap" . application.ext |
application.baseUri | "" |
application.dispatcher.defaultRoute |  |
application.dispatcher.throwException | 1 |
application.dispatcher.catchException | 0 |
application.dispatcher.defaultModule | "index" |
application.dispatcher.defaultController | "index" |
application.dispatcher.defaultAction | "index" |
application.system |  |

Here's a short explanation of the configuration directives.

application.directory string

The directory of the application, that is the folder which contains the "controllers", "views", "models", "plugins" folders.

Note:

This config entry is the only one which doesn't has a default value. You should always define it manually.

application.ext string

The file ext of the PHP script, used in class autoloading( Yaf_Loader).

application.view.ext string

The file ext of the view template scripts.

application.modules string

A comma-separated list of the registered modules, used in the route process, especially while there are more than three segments in the PATH_INFO,

Yaf need a way to find out whether the first segment is a module name or not.

application.library string

The local library directory, see Yaf_Loader and yaf.library.

Note:

After Yaf 2.1.6, this config entry can be an array. The library path will try to use the items setted in application.library.directory

application.library.directory string

Alias of application.library. Introduced in Yaf 2.1.6

application.library.namespace string

A comma-separated prefix of local library namespace.

Introduced in Yaf 2.1.6

application.bootstrap string

A absolute path of the Bootstrap class script.

application.baseUri string

Used to remove a fixed prefix of request uri in route process. Take a example, comes a request with request uri "/prefix/controller/action". if you set application.baseUri to "/prefix", then only "/controller/action" will take as the PATH_INFO in route process.

In generally, there is no need to set this value.

application.dispatcher.throwException bool

If it set to On, Yaf will throw an exception while some error occurring. See also Yaf_Dispatcher::throwException().

application.dispatcher.catchException bool

If it set to On, Yaf will forward to Error controller/Action while there is an unhandled exception. See also Yaf_Dispatcher::catchException().

application.dispatcher.defaultRoute string

The default Route, if it is not specificed, Static route will be used as default. See: Yaf_Router::addRoute().

application.dispatcher.defaultModule string

The default module name, see also Yaf_Dispatcher::setDefaultModule().

application.dispatcher.defaultController string

The default controller name, see also Yaf_Dispatcher::setDefaultController().

application.dispatcher.defaultAction string

The default action name, see also Yaf_Dispatcher::setDefaultAction().

application.system string

Set yaf runtime configure in application.ini, like: application.system.lowcase_path

Note:

only those PHP_INI_ALL configures can be set in this way


The Yaf_Application class

(No version information available, might only be in Git)

Introduction

Yaf_Application provides a bootstrapping facility for applications which provides reusable resources, common- and module-based bootstrap classes and dependency checking.

Note:

Yaf_Application implements the singleton pattern, and Yaf_Application can not be serialized or unserialized which will cause problem when you try to use PHPUnit to write some test case for Yaf.

You may use @backupGlobals annotation of PHPUnit to control the backup and restore operations for global variables. thus can solve this problem.

Class synopsis

final Yaf_Application {
/* Properties */
protected $config ;
protected $dispatcher ;
protected static $_app ;
protected $_modules ;
protected $_running ;
protected $_environ ;
/* Methods */
public staticapp ( void ) : mixed
public bootstrap ([ Yaf_Bootstrap_Abstract $bootstrap ] ) : void
public clearLastError ( void ) : Yaf_Application
private __clone ( void ) : void
public __construct ( mixed $config [, string $envrion ] )
public __destruct ( void ) : void
public environ ( void ) : void
public execute ( callable $entry , string $... ) : void
public getAppDirectory ( void ) : Yaf_Application
public getConfig ( void ) : Yaf_Config_Abstract
public getDispatcher ( void ) : Yaf_Dispatcher
public getLastErrorMsg ( void ) : string
public getLastErrorNo ( void ) : int
public getModules ( void ) : array
public run ( void ) : void
public setAppDirectory ( string $directory ) : Yaf_Application
private __sleep ( void ) : void
private __wakeup ( void ) : void
}

Properties

config

dispatcher

_app

_modules

_running

_environ

Table of Contents

  • Yaf_Application::app — Retrieve an Application instance
  • Yaf_Application::bootstrap — Call bootstrap
  • Yaf_Application::clearLastError — Clear the last error info
  • Yaf_Application::__clone — Yaf_Application can not be cloned
  • Yaf_Application::__construct — Yaf_Application constructor
  • Yaf_Application::__destruct — The __destruct purpose
  • Yaf_Application::environ — Retrive environ
  • Yaf_Application::execute — Execute a callback
  • Yaf_Application::getAppDirectory — Get the application directory
  • Yaf_Application::getConfig — Retrive the config instance
  • Yaf_Application::getDispatcher — Get Yaf_Dispatcher instance
  • Yaf_Application::getLastErrorMsg — Get message of the last occurred error
  • Yaf_Application::getLastErrorNo — Get code of last occurred error
  • Yaf_Application::getModules — Get defined module names
  • Yaf_Application::run — Start Yaf_Application
  • Yaf_Application::setAppDirectory — Change the application directory
  • Yaf_Application::__sleep — Yaf_Application can not be serialized
  • Yaf_Application::__wakeup — Yaf_Application can not be unserialized


Retrieve an Application instance

  • « Yaf_Application
  • Yaf_Application::bootstrap »
  • PHP Manual
  • Yaf_Application
  • Retrieve an Application instance

Yaf_Application::app

(Yaf >=1.0.0)

Yaf_Application::app — Retrieve an Application instance

Description

public staticYaf_Application::app ( void ) : mixed

Retrieve the Yaf_Application instance. Alternatively, we also could use Yaf_Dispatcher::getApplication().

Parameters

This function has no parameters.

Return Values

A Yaf_Application instance, if no Yaf_Application was initialized before, NULL will be returned.

See Also

  • Yaf_Dispatcher::getApplication() - Retrive the application


Call bootstrap

  • « Yaf_Application::app
  • Yaf_Application::clearLastError »
  • PHP Manual
  • Yaf_Application
  • Call bootstrap

Yaf_Application::bootstrap

(Yaf >=1.0.0)

Yaf_Application::bootstrap — Call bootstrap

Description

public Yaf_Application::bootstrap ([ Yaf_Bootstrap_Abstract $bootstrap ] ) : void

Run a Bootstrap, all the methods defined in the Bootstrap and named with prefix "_init" will be called according to their declaration order, if the parameter bootstrap is not supplied, Yaf will look for a Bootstrap under application.directory.

Parameters

bootstrap

A Yaf_Bootstrap_Abstract instance

Return Values

Yaf_Application instance

Examples

Example #1 A Bootstrap()example

<?php
/**
 * This file should be under the APPLICATION_PATH . "/application/"(which was defined in the config passed to Yaf_Application).
 * and named Bootstrap.php,  so the Yaf_Application can find it
 */
class Bootstrap extends Yaf_Bootstrap_Abstract {
    function _initConfig(Yaf_Dispatcher $dispatcher) {
        echo "1st called\n";
    }

    function _initPlugin($dispatcher) {
        echo "2nd called\n";
    }
}
?>

Example #2 Yaf_Application::bootstrap()example

<?php

defined('APPLICATION_PATH')                  // APPLICATION_PATH will be used in the ini config file
    || define('APPLICATION_PATH', __DIR__)); //__DIR__ was introduced after PHP 5.3

$application = new Yaf_Application(APPLICATION_PATH.'/conf/application.ini');
$application->bootstrap();
?>

The above example will output something similar to:

1st called
2nd called

See Also

  • Yaf_Bootstrap_Abstract


Clear the last error info

  • « Yaf_Application::bootstrap
  • Yaf_Application::__clone »
  • PHP Manual
  • Yaf_Application
  • Clear the last error info

Yaf_Application::clearLastError

(Yaf >=2.1.2)

Yaf_Application::clearLastError — Clear the last error info

Description

public Yaf_Application::clearLastError ( void ) : Yaf_Application

Parameters

This function has no parameters.

Return Values

Examples

Example #1 Yaf_Application::clearLastError()example

<?php
function error_handler($errno, $errstr, $errfile, $errline) {
   Yaf_Application::app()->clearLastError();
   var_dump(Yaf_Application::app()->getLastErrorNo());
}

$config = array(
 "application" => array(
   "directory" => "/tmp/notexists",
     "dispatcher" => array(
       "throwException" => 0, //trigger error instead of throw exception when error occure
      ),
  ),
);

$app = new Yaf_Application($config);
$app->getDispatcher()->setErrorHandler("error_handler", E_RECOVERABLE_ERROR);
$app->run();
?>

The above example will output something similar to:

int(0)


Yaf_Application can not be cloned

  • « Yaf_Application::clearLastError
  • Yaf_Application::__construct »
  • PHP Manual
  • Yaf_Application
  • Yaf_Application can not be cloned

Yaf_Application::__clone

(Yaf >=1.0.0)

Yaf_Application::__clone — Yaf_Application can not be cloned

Description

private Yaf_Application::__clone ( void ) : void

Parameters

This function has no parameters.

Return Values


Yaf_Application constructor

  • « Yaf_Application::__clone
  • Yaf_Application::__destruct »
  • PHP Manual
  • Yaf_Application
  • Yaf_Application constructor

Yaf_Application::__construct

(Yaf >=1.0.0)

Yaf_Application::__construct — Yaf_Application constructor

Description

public Yaf_Application::__construct ( mixed $config [, string $envrion ] )

Instance a Yaf_Application.

Parameters

config

A ini config file path, or a config array

If is a ini config file, there should be a section named as the one defined by yaf.environ, which is "product" by default.

Note:

If you use a ini configuration file as your applicatioin's config container. you would open the yaf.cache_config to improve performance.

And the config entry(and there default value) list blow:

Example #1 A ini config file example

[product]
;this one should alway be defined, and have no default value
application.directory=APPLICATION_PATH

;following configs have default value, you may no need to define them
application.library = APPLICATION_PATH . "/library"
application.dispatcher.throwException=1
application.dispatcher.catchException=1

application.baseUri=""

;the php script ext name
ap.ext=php

;the view template ext name
ap.view.ext=phtml

ap.dispatcher.defaultModuel=Index
ap.dispatcher.defaultController=Index
ap.dispatcher.defaultAction=index

;defined modules
ap.modules=Index

envrion

Which section will be loaded as the final config

Return Values

Examples

Example #2 Yaf_Application::__construct()example

<?php
defined('APPLICATION_PATH')                  // APPLICATION_PATH will be used in the ini config file
    || define('APPLICATION_PATH', __DIR__)); //__DIR__ was introduced after PHP 5.3

$application = new Yaf_Application(APPLICATION_PATH.'/conf/application.ini');
$application->bootstrap()->run();
?>

The above example will output something similar to:

Example #3 Yaf_Application::__construct()example

<?php
$config = array(
    "application" => array(
        "directory" => realpath(dirname(__FILE__)) . "/application",
    ),
);

/** Yaf_Application */
$application = new Yaf_Application($config);
$application->bootstrap()->run();
?>

The above example will output
something similar to:

See Also

  • Yaf_Config_Ini
    •


The __destruct purpose

  • « Yaf_Application::__construct
  • Yaf_Application::environ »
  • PHP Manual
  • Yaf_Application
  • The __destruct purpose

Yaf_Application::__destruct

(Yaf >=1.0.0)

Yaf_Application::__destruct — The __destruct purpose

Description

public Yaf_Application::__destruct ( void ) : void

Parameters

This function has no parameters.

Return Values


Retrive environ

  • « Yaf_Application::__destruct
  • Yaf_Application::execute »
  • PHP Manual
  • Yaf_Application
  • Retrive environ

Yaf_Application::environ

(Yaf >=1.0.0)

Yaf_Application::environ — Retrive environ

Description

public Yaf_Application::environ ( void ) : void

Retrive environ which was defined in yaf.environ which has a default value "product".

Parameters

This function has no parameters.

Return Values

Examples

Example #1 Yaf_Application::environ()example

<?php
$config = array(
    "application" => array(
        "directory" => realpath(dirname(__FILE__)) . "/application",
    ),
);

/** Yaf_Application */
$application = new Yaf_Application($config);
print_r($application->environ());
?>

The above example will output something similar to:

product


Execute a callback

  • « Yaf_Application::environ
  • Yaf_Application::getAppDirectory »
  • PHP Manual
  • Yaf_Application
  • Execute a callback

Yaf_Application::execute

(Yaf >=1.0.0)

Yaf_Application::execute — Execute a callback

Description

public Yaf_Application::execute ( callable $entry , string $... ) : void

This method is typically used to run Yaf_Application in a crontab work. Make the crontab work can also use the autoloader and Bootstrap mechanism.

Parameters

entry

a valid callback

...

parameters will pass to the callback

Return Values

Examples

Example #1 Yaf_Application::execute()example

<?php
function main($argc, $argv) {
}

$config = array(
    "application" => array(
        "directory" => realpath(dirname(__FILE__)) . "/application",
    ),
);

/** Yaf_Application */
$application = new Yaf_Application($config);
$application->execute("main", $argc,  $argv);
?>

The above example will output something similar to:


Get the application directory

  • « Yaf_Application::execute
  • Yaf_Application::getConfig »
  • PHP Manual
  • Yaf_Application
  • Get the application directory

Yaf_Application::getAppDirectory

(Yaf >=2.1.4)

Yaf_Application::getAppDirectory — Get the application directory

Description

public Yaf_Application::getAppDirectory ( void ) : Yaf_Application

Parameters

directory

Return Values


Retrive the config instance

  • « Yaf_Application::getAppDirectory
  • Yaf_Application::getDispatcher »
  • PHP Manual
  • Yaf_Application
  • Retrive the config instance

Yaf_Application::getConfig

(Yaf >=1.0.0)

Yaf_Application::getConfig — Retrive the config instance

Description

public Yaf_Application::getConfig ( void ) : Yaf_Config_Abstract

Parameters

This function has no parameters.

Return Values

A Yaf_Config_Abstract instance

Examples

Example #1 Yaf_Application::getConfig()example

<?php
$config = array(
    "application" => array(
        "directory" => realpath(dirname(__FILE__)) . "/application",
    ),
);

/** Yaf_Application */
$application = new Yaf_Application($config);
print_r($application->getConfig());
?>

The above example will output something similar to:

Yaf_Config_Simple Object
(
    [_config:protected] => Array
        (
            [application] => Array
                (
                    [directory] => /home/laruence/local/www/htdocs/application
                )

        )

    [_readonly:protected] => 1
)


Get Yaf_Dispatcher instance

  • « Yaf_Application::getConfig
  • Yaf_Application::getLastErrorMsg »
  • PHP Manual
  • Yaf_Application
  • Get Yaf_Dispatcher instance

Yaf_Application::getDispatcher

(Yaf >=1.0.0)

Yaf_Application::getDispatcher — Get Yaf_Dispatcher instance

Description

public Yaf_Application::getDispatcher ( void ) : Yaf_Dispatcher

Parameters

This function has no parameters.

Return Values

Examples

Example #1 Yaf_Application::getDispatcher()example

<?php
$config = array(
    "application" => array(
        "directory" => realpath(dirname(__FILE__)) . "/application",
    ),
);

/** Yaf_Application */
$application = new Yaf_Application($config);
print_r($application->getDispatcher());
?>

The above example will output something similar to:

Yaf_Dispatcher Object
(
    [_router:protected] => Yaf_Router Object
        (
            [_routes:protected] => Array
                (
                    [_default] => Yaf_Route_Static Object
                        (
                        )

                )

            [_current:protected] =>
        )

    [_view:protected] =>
    [_request:protected] => Yaf_Request_Http Object
        (
            [module] =>
            [controller] =>
            [action] =>
            [method] => Cli
            [params:protected] => Array
                (
                )

            [language:protected] =>
            [_exception:protected] =>
            [_base_uri:protected] =>
            [uri:protected] =>
            [dispatched:protected] =>
            [routed:protected] =>
        )

    [_plugins:protected] => Array
        (
        )

    [_auto_render:protected] => 1
    [_return_response:protected] =>
    [_instantly_flush:protected] =>
    [_default_module:protected] => Index
    [_default_controller:protected] => Index
    [_default_action:protected] => index
    [_response] => Yaf_Response_Cli Object
        (
            [_header:protected] => Array
                (
                )

            [_body:protected] =>
            [_sendheader:protected] =>
        )

)


Get message of the last occurred error

  • « Yaf_Application::getDispatcher
  • Yaf_Application::getLastErrorNo »
  • PHP Manual
  • Yaf_Application
  • Get message of the last occurred error

Yaf_Application::getLastErrorMsg

(Yaf >=2.1.2)

Yaf_Application::getLastErrorMsg — Get message of the last occurred error

Description

public Yaf_Application::getLastErrorMsg ( void ) : string

Parameters

This function has no parameters.

Return Values

Examples

Example #1 Yaf_Application::getLastErrorMsg()example

<?php
function error_handler($errno, $errstr, $errfile, $errline) {
   var_dump(Yaf_Application::app()->getLastErrorMsg());
}

$config = array(
 "application" => array(
   "directory" => "/tmp/notexists",
     "dispatcher" => array(
       "throwException" => 0, //trigger error instead of throw exception when error occure
      ),
  ),
);

$app = new Yaf_Application($config);
$app->getDispatcher()->setErrorHandler("error_handler", E_RECOVERABLE_ERROR);
$app->run();
?>

The above example will output something similar to:

string(69) "Could not find controller script /tmp/notexists/controllers/Index.php"


Get code of last occurred error

  • « Yaf_Application::getLastErrorMsg
  • Yaf_Application::getModules »
  • PHP Manual
  • Yaf_Application
  • Get code of last occurred error

Yaf_Application::getLastErrorNo

(Yaf >=2.1.2)

Yaf_Application::getLastErrorNo — Get code of last occurred error

Description

public Yaf_Application::getLastErrorNo ( void ) : int

Parameters

This function has no parameters.

Return Values

Examples

Example #1 Yaf_Application::getLastErrorNo()example

<?php
function error_handler($errno, $errstr, $errfile, $errline) {
   var_dump(Yaf_Application::app()->getLastErrorNo());
   var_dump(Yaf_Application::app()->getLastErrorNo() == YAF_ERR_NOTFOUND_CONTROLLER);
}

$config = array(
  "application" => array(
   "directory" => "/tmp/notexists",
     "dispatcher" => array(
       "throwException" => 0, //trigger error instead of throw exception when error occure
      ),
  ),
);

$app = new Yaf_Application($config);
$app->getDispatcher()->setErrorHandler("error_handler", E_RECOVERABLE_ERROR);
$app->run();
?>

The above example will output something similar to:

int(516)
bool(true)


Get defined module names

  • « Yaf_Application::getLastErrorNo
  • Yaf_Application::run »
  • PHP Manual
  • Yaf_Application
  • Get defined module names

Yaf_Application::getModules

(Yaf >=1.0.0)

Yaf_Application::getModules — Get defined module names

Description

public Yaf_Application::getModules ( void ) : array

Get the modules list defined in config, if no one defined, there will always be a module named "Index".

Parameters

This function has no parameters.

Return Values

Examples

Example #1 Yaf_Application::getModules()example

<?php
$config = array(
    "application" => array(
        "directory" => realpath(dirname(__FILE__)) . "/application",
    ),
);

/** Yaf_Application */
$application = new Yaf_Application($config);
print_r($application->getModules());
?>

The above example will output something similar to:

Array
(
    [0] => Index
)


Start Yaf_Application

  • « Yaf_Application::getModules
  • Yaf_Application::setAppDirectory »
  • PHP Manual
  • Yaf_Application
  • Start Yaf_Application

Yaf_Application::run

(Yaf >=1.0.0)

Yaf_Application::run — Start Yaf_Application

Description

public Yaf_Application::run ( void ) : void

Run a Yaf_Application, let the Yaf_Application accept a request and route this request, dispatch to controller/action and render response. Finally, return the response to the client.

Parameters

This function has no parameters.

Return Values


Change the application directory

  • « Yaf_Application::run
  • Yaf_Application::__sleep »
  • PHP Manual
  • Yaf_Application
  • Change the application directory

Yaf_Application::setAppDirectory

(Yaf >=2.1.4)

Yaf_Application::setAppDirectory — Change the application directory

Description

public Yaf_Application::setAppDirectory ( string $directory ) : Yaf_Application

Parameters

directory

Return Values


Yaf_Application can not be serialized

  • « Yaf_Application::setAppDirectory
  • Yaf_Application::__wakeup »
  • PHP Manual
  • Yaf_Application
  • Yaf_Application can not be serialized

Yaf_Application::__sleep

(Yaf >=1.0.0)

Yaf_Application::__sleep — Yaf_Application can not be serialized

Description

private Yaf_Application::__sleep ( void ) : void

Parameters

This function has no parameters.

Return Values


Yaf_Application can not be unserialized

  • « Yaf_Application::__sleep
  • Yaf_Bootstrap_Abstract »
  • PHP Manual
  • Yaf_Application
  • Yaf_Application can not be unserialized

Yaf_Application::__wakeup

(Yaf >=1.0.0)

Yaf_Application::__wakeup — Yaf_Application can not be unserialized

Description

private Yaf_Application::__wakeup ( void ) : void

Parameters

This function has no parameters.

Return Values


The Yaf_Bootstrap_Abstract class

(No version information available, might only be in Git)

Introduction

Bootstrap is a mechanism used to do some initial config before a Application run.

User may define their own Bootstrap class by inheriting Yaf_Bootstrap_Abstract

Any method declared in Bootstrap class with leading "_init", will be called by Yaf_Application::bootstrap() one by one according to their defined order.

Examples

Example #1 Bootstrap example

<?php
   /* bootstrap class should be defined under ./application/Bootstrap.php */
   class Bootstrap extends Yaf_Bootstrap_Abstract {
        public function _initConfig(Yaf_Dispatcher $dispatcher) {
            var_dump(__METHOD__);
        }
        public function _initPlugin(Yaf_Dispatcher $dispatcher) {
            var_dump(__METHOD__);
        }
   }

   $config = array(
       "application" => array(
           "directory" => dirname(__FILE__) . "/application/",
       ),
   );

   $app = new Yaf_Application($config);
   $app->bootstrap();
?>

The above example will output something similar to:

string(22) "Bootstrap::_initConfig"
string(22) "Bootstrap::_initPlugin"

Class synopsis

abstract Yaf_Bootstrap_Abstract {
/* Properties */
/* Methods */
}


The Yaf_Dispatcher class

(Yaf >=1.0.0)

Introduction

Yaf_Dispatcher purpose is to initialize the request environment, route the incoming request, and then dispatch any discovered actions; it aggregates any responses and returns them when the process is complete.

Yaf_Dispatcher also implements the Singleton pattern, meaning only a single instance of it may be available at any given time. This allows it to also act as a registry on which the other objects in the dispatch process may draw.

Class synopsis

final Yaf_Dispatcher {
/* Properties */
protected $_router ;
protected $_view ;
protected $_request ;
protected $_plugins ;
protected static $_instance ;
protected $_auto_render ;
protected $_return_response ;
protected $_instantly_flush ;
protected $_default_module ;
protected $_default_controller ;
protected $_default_action ;
/* Methods */
public autoRender ([ bool $flag ] ) : Yaf_Dispatcher
public catchException ([ bool $flag ] ) : Yaf_Dispatcher
private __clone ( void ) : void
public __construct ( void )
public disableView ( void ) : bool
public dispatch ( Yaf_Request_Abstract $request ) : Yaf_Response_Abstract
public enableView ( void ) : Yaf_Dispatcher
public flushInstantly ([ bool $flag ] ) : Yaf_Dispatcher
public getApplication ( void ) : Yaf_Application
public static getInstance ( void ) : Yaf_Dispatcher
public getRequest ( void ) : Yaf_Request_Abstract
public getRouter ( void ) : Yaf_Router
public initView ( string $templates_dir [, array $options ] ) : Yaf_View_Interface
public registerPlugin ( Yaf_Plugin_Abstract $plugin ) : Yaf_Dispatcher
public returnResponse ( bool $flag ) : Yaf_Dispatcher
public setDefaultAction ( string $action ) : Yaf_Dispatcher
public setDefaultController ( string $controller ) : Yaf_Dispatcher
public setDefaultModule ( string $module ) : Yaf_Dispatcher
public setErrorHandler ( call $callback , int $error_types ) : Yaf_Dispatcher
public setRequest ( Yaf_Request_Abstract $request ) : Yaf_Dispatcher
public setView ( Yaf_View_Interface $view ) : Yaf_Dispatcher
private __sleep ( void ) : void
public throwException ([ bool $flag ] ) : Yaf_Dispatcher
private __wakeup ( void ) : void
}

Properties

_router

_view

_request

_plugins

_instance

_auto_render

_return_response

_instantly_flush

_default_module

_default_controller

_default_action

Table of Contents

  • Yaf_Dispatcher::autoRender — Switch on/off autorendering
  • Yaf_Dispatcher::catchException — Switch on/off exception catching
  • Yaf_Dispatcher::__clone — Yaf_Dispatcher can not be cloned
  • Yaf_Dispatcher::__construct — Yaf_Dispatcher constructor
  • Yaf_Dispatcher::disableView — Disable view rendering
  • Yaf_Dispatcher::dispatch — Dispatch a request
  • Yaf_Dispatcher::enableView — Enable view rendering
  • Yaf_Dispatcher::flushInstantly — Switch on/off the instant flushing
  • Yaf_Dispatcher::getApplication — Retrive the application
  • Yaf_Dispatcher::getInstance — Retrive the dispatcher instance
  • Yaf_Dispatcher::getRequest — Retrive the request instance
  • Yaf_Dispatcher::getRouter — Retrive router instance
  • Yaf_Dispatcher::initView — Initialize view and return it
  • Yaf_Dispatcher::registerPlugin — Register a plugin
  • Yaf_Dispatcher::returnResponse — The returnResponse purpose
  • Yaf_Dispatcher::setDefaultAction — Change default action name
  • Yaf_Dispatcher::setDefaultController — Change default controller name
  • Yaf_Dispatcher::setDefaultModule — Change default module name
  • Yaf_Dispatcher::setErrorHandler — Set error handler
  • Yaf_Dispatcher::setRequest — The setRequest purpose
  • Yaf_Dispatcher::setView — Set a custom view engine
  • Yaf_Dispatcher::__sleep — Yaf_Dispatcher can not be serialized
  • Yaf_Dispatcher::throwException — Switch on/off exception throwing
  • Yaf_Dispatcher::__wakeup — Yaf_Dispatcher can not be unserialized


Switch on/off autorendering

  • « Yaf_Dispatcher
  • Yaf_Dispatcher::catchException »
  • PHP Manual
  • Yaf_Dispatcher
  • Switch on/off autorendering

Yaf_Dispatcher::autoRender

(Yaf >=1.0.0)

Yaf_Dispatcher::autoRender — Switch on/off autorendering

Description

public Yaf_Dispatcher::autoRender ([ bool $flag ] ) : Yaf_Dispatcher

Yaf_Dispatcher will render automatically after dispatches a incoming request, you can prevent the rendering by calling this method with flag TRUE

Note:

you can simply return FALSE in a action to prevent the auto-rendering of that action

Parameters

flag

bool

Note:

since 2.2.0, if this parameter is not given, then the current state will be renturned

Return Values

Examples

Example #1 Yaf_Dispatcher::autoRender()example

<?php
class IndexController extends Yaf_Controller_Abstract {
     /* init method will be called as soon as a controller is initialized */
     public function init() {
         if ($this->getRequest()->isXmlHttpRequest()) {
             //do not call render for ajax request
             //we will outpu a json string
             Yaf_Dispatcher::getInstance()->autoRender(FALSE);
         }
     }

}
?>

The above example will output something similar to:


Switch on/off exception catching

  • « Yaf_Dispatcher::autoRender
  • Yaf_Dispatcher::__clone »
  • PHP Manual
  • Yaf_Dispatcher
  • Switch on/off exception catching

Yaf_Dispatcher::catchException

(Yaf >=1.0.0)

Yaf_Dispatcher::catchException — Switch on/off exception catching

Description

public Yaf_Dispatcher::catchException ([ bool $flag ] ) : Yaf_Dispatcher

While the application.dispatcher.throwException is On(you can also calling to Yaf_Dispatcher::throwException(TRUE)() to enable it), Yaf will throw Exception whe error occurrs instead of trigger error.

then if you enable Yaf_Dispatcher::catchException()(also can enabled by set application.dispatcher.catchException), all uncaught Exceptions will be caught by ErrorController::error if you have defined one.

Parameters

flag

bool

Return Values

Examples

Example #1 Yaf_Dispatcher::catchException()example

/* if you defined a ErrorController like following */
<?php
class ErrorController extends Yaf_Controller_Abstract {
     /**
      * you can also call to Yaf_Request_Abstract::getException to get the
      * un-caught exception.
      */
     public function errorAction($exception) {
        /* error occurs */
        switch ($exception->getCode()) {
            case YAF_ERR_NOTFOUND_MODULE:
            case YAF_ERR_NOTFOUND_CONTROLLER:
            case YAF_ERR_NOTFOUND_ACTION:
            case YAF_ERR_NOTFOUND_VIEW:
                echo 404, ":", $exception->getMessage();
                break;
            default :
                $message = $exception->getMessage();
                echo 0, ":", $exception->getMessage();
                break;
        }
     }
}
?>

The above example will output something similar to:

/* now if some error occur, assuming access a non-exists controller(or you can throw a exception yourself): */
404:Could not find controller script **/application/controllers/No-exists-controller.php

See Also

  • Yaf_Dispatcher::throwException() - Switch on/off exception throwing
  • Yaf_Dispatcher::setErrorHandler() - Set error handler


Yaf_Dispatcher can not be cloned

  • « Yaf_Dispatcher::catchException
  • Yaf_Dispatcher::__construct »
  • PHP Manual
  • Yaf_Dispatcher
  • Yaf_Dispatcher can not be cloned

Yaf_Dispatcher::__clone

(Yaf >=1.0.0)

Yaf_Dispatcher::__clone — Yaf_Dispatcher can not be cloned

Description

private Yaf_Dispatcher::__clone ( void ) : void

Parameters

This function has no parameters.

Return Values


Yaf_Dispatcher constructor

  • « Yaf_Dispatcher::__clone
  • Yaf_Dispatcher::disableView »
  • PHP Manual
  • Yaf_Dispatcher
  • Yaf_Dispatcher constructor

Yaf_Dispatcher::__construct

(Yaf >=1.0.0)

Yaf_Dispatcher::__construct — Yaf_Dispatcher constructor

Description

public Yaf_Dispatcher::__construct ( void )

Parameters

This function has no parameters.

Return Values


Disable view rendering

  • « Yaf_Dispatcher::__construct
  • Yaf_Dispatcher::dispatch »
  • PHP Manual
  • Yaf_Dispatcher
  • Disable view rendering

Yaf_Dispatcher::disableView

(Yaf >=1.0.0)

Yaf_Dispatcher::disableView — Disable view rendering

Description

public Yaf_Dispatcher::disableView ( void ) : bool

disable view engine, used in some app that user will output by theirself

Note:

you can simply return FALSE in a action to prevent the auto-rendering of that action

Parameters

This function has no parameters.

Return Values


Dispatch a request

  • « Yaf_Dispatcher::disableView
  • Yaf_Dispatcher::enableView »
  • PHP Manual
  • Yaf_Dispatcher
  • Dispatch a request

Yaf_Dispatcher::dispatch

(Yaf >=1.0.0)

Yaf_Dispatcher::dispatch — Dispatch a request

Description

public Yaf_Dispatcher::dispatch ( Yaf_Request_Abstract $request ) : Yaf_Response_Abstract

This method does the heavy work of the Yaf_Dispatcher. It take a request object.

The dispatch process has three distinct events:

  • Routing
  • Dispatching
  • Response
Routing takes place exactly once, using the values in the request object when dispatch() is called. Dispatching takes place in a loop; a request may either indicate multiple actions to dispatch, or the controller or a plugin may reset the request object to force additional actions to dispatch(see Yaf_Plugin_Abstract. When all is done, the Yaf_Dispatcher returns a response.

Parameters

request

Return Values


Enable view rendering

  • « Yaf_Dispatcher::dispatch
  • Yaf_Dispatcher::flushInstantly »
  • PHP Manual
  • Yaf_Dispatcher
  • Enable view rendering

Yaf_Dispatcher::enableView

(Yaf >=1.0.0)

Yaf_Dispatcher::enableView — Enable view rendering

Description

public Yaf_Dispatcher::enableView ( void ) : Yaf_Dispatcher

Parameters

This function has no parameters.

Return Values


Switch on/off the instant flushing

  • « Yaf_Dispatcher::enableView
  • Yaf_Dispatcher::getApplication »
  • PHP Manual
  • Yaf_Dispatcher
  • Switch on/off the instant flushing

Yaf_Dispatcher::flushInstantly

(Yaf >=1.0.0)

Yaf_Dispatcher::flushInstantly — Switch on/off the instant flushing

Description

public Yaf_Dispatcher::flushInstantly ([ bool $flag ] ) : Yaf_Dispatcher

Parameters

flag

bool

Note:

since 2.2.0, if this parameter is not given, then the current state will be renturned

Return Values


Retrive the application

  • « Yaf_Dispatcher::flushInstantly
  • Yaf_Dispatcher::getInstance »
  • PHP Manual
  • Yaf_Dispatcher
  • Retrive the application

Yaf_Dispatcher::getApplication

(Yaf >=1.0.0)

Yaf_Dispatcher::getApplication — Retrive the application

Description

public Yaf_Dispatcher::getApplication ( void ) : Yaf_Application

Retrive the Yaf_Application instance. same as Yaf_Application::app().

Parameters

This function has no parameters.

Return Values

See Also

  • Yaf_Application::app() - Retrieve an Application instance


Retrive the dispatcher instance

  • « Yaf_Dispatcher::getApplication
  • Yaf_Dispatcher::getRequest »
  • PHP Manual
  • Yaf_Dispatcher
  • Retrive the dispatcher instance

Yaf_Dispatcher::getInstance

(Yaf >=1.0.0)

Yaf_Dispatcher::getInstance — Retrive the dispatcher instance

Description

public static Yaf_Dispatcher::getInstance ( void ) : Yaf_Dispatcher

Parameters

This function has no parameters.

Return Values


Retrive the request instance

  • « Yaf_Dispatcher::getInstance
  • Yaf_Dispatcher::getRouter »
  • PHP Manual
  • Yaf_Dispatcher
  • Retrive the request instance

Yaf_Dispatcher::getRequest

(Yaf >=1.0.0)

Yaf_Dispatcher::getRequest — Retrive the request instance

Description

public Yaf_Dispatcher::getRequest ( void ) : Yaf_Request_Abstract

Parameters

This function has no parameters.

Return Values


Retrive router instance

  • « Yaf_Dispatcher::getRequest
  • Yaf_Dispatcher::initView »
  • PHP Manual
  • Yaf_Dispatcher
  • Retrive router instance

Yaf_Dispatcher::getRouter

(Yaf >=1.0.0)

Yaf_Dispatcher::getRouter — Retrive router instance

Description

public Yaf_Dispatcher::getRouter ( void ) : Yaf_Router

Parameters

This function has no parameters.

Return Values


Initialize view and return it

  • « Yaf_Dispatcher::getRouter
  • Yaf_Dispatcher::registerPlugin »
  • PHP Manual
  • Yaf_Dispatcher
  • Initialize view and return it

Yaf_Dispatcher::initView

(Yaf >=1.0.0)

Yaf_Dispatcher::initView — Initialize view and return it

Description

public Yaf_Dispatcher::initView ( string $templates_dir [, array $options ] ) : Yaf_View_Interface

Parameters

templates_dir

options

Return Values


Register a plugin

  • « Yaf_Dispatcher::initView
  • Yaf_Dispatcher::returnResponse »
  • PHP Manual
  • Yaf_Dispatcher
  • Register a plugin

Yaf_Dispatcher::registerPlugin

(Yaf >=1.0.0)

Yaf_Dispatcher::registerPlugin — Register a plugin

Description

public Yaf_Dispatcher::registerPlugin ( Yaf_Plugin_Abstract $plugin ) : Yaf_Dispatcher

Register a plugin(see Yaf_Plugin_Abstract). Generally, we register plugins in Bootstrap(see Yaf_Bootstrap_Abstract).

Parameters

plugin

Return Values

Examples

Example #1 Yaf_Dispatcher::registerPlugin()example

<?php
class Bootstrap extends Yaf_Bootstrap_Abstract {
  public function _initPlugin(Yaf_Dispatcher $dispatcher) {
    /**
    * Yaf assumes plugin scripts under [application.directory] .  "/plugins"
    * for this case, it will be:
    * [application.directory] . "/plugins/" . "User" . [application.ext]
    */
    $user = new UserPlugin();
    $dispatcher->registerPlugin($user);
  }
}
?>

See Also

  • Yaf_Plugin_Abstract
  • Yaf_Bootstrap_Abstract


The returnResponse purpose

  • « Yaf_Dispatcher::registerPlugin
  • Yaf_Dispatcher::setDefaultAction »
  • PHP Manual
  • Yaf_Dispatcher
  • The returnResponse purpose

Yaf_Dispatcher::returnResponse

(Yaf >=1.0.0)

Yaf_Dispatcher::returnResponse — The returnResponse purpose

Description

public Yaf_Dispatcher::returnResponse ( bool $flag ) : Yaf_Dispatcher

Parameters

flag

Return Values


Change default action name

  • « Yaf_Dispatcher::returnResponse
  • Yaf_Dispatcher::setDefaultController »
  • PHP Manual
  • Yaf_Dispatcher
  • Change default action name

Yaf_Dispatcher::setDefaultAction

(Yaf >=1.0.0)

Yaf_Dispatcher::setDefaultAction — Change default action name

Description

public Yaf_Dispatcher::setDefaultAction ( string $action ) : Yaf_Dispatcher

Parameters

action

Return Values


Change default controller name

  • « Yaf_Dispatcher::setDefaultAction
  • Yaf_Dispatcher::setDefaultModule »
  • PHP Manual
  • Yaf_Dispatcher
  • Change default controller name

Yaf_Dispatcher::setDefaultController

(Yaf >=1.0.0)

Yaf_Dispatcher::setDefaultController — Change default controller name

Description

public Yaf_Dispatcher::setDefaultController ( string $controller ) : Yaf_Dispatcher

Parameters

controller

Return Values


Change default module name

  • « Yaf_Dispatcher::setDefaultController
  • Yaf_Dispatcher::setErrorHandler »
  • PHP Manual
  • Yaf_Dispatcher
  • Change default module name

Yaf_Dispatcher::setDefaultModule

(Yaf >=1.0.0)

Yaf_Dispatcher::setDefaultModule — Change default module name

Description

public Yaf_Dispatcher::setDefaultModule ( string $module ) : Yaf_Dispatcher

Parameters

module

Return Values


Set error handler

  • « Yaf_Dispatcher::setDefaultModule
  • Yaf_Dispatcher::setRequest »
  • PHP Manual
  • Yaf_Dispatcher
  • Set error handler

Yaf_Dispatcher::setErrorHandler

(Yaf >=1.0.0)

Yaf_Dispatcher::setErrorHandler — Set error handler

Description

public Yaf_Dispatcher::setErrorHandler ( call $callback , int $error_types ) : Yaf_Dispatcher

Set error handler for Yaf. when application.dispatcher.throwException is off, Yaf will trigger catchable error while unexpected errors occrred.

Thus, this error handler will be called while the error raise.

Parameters

callback

A callable callback

error_types

Return Values

See Also

  • Yaf_Dispatcher::throwException() - Switch on/off exception throwing
  • Yaf_Application::getLastErrorNo() - Get code of last occurred error
  • Yaf_Application::getLastErrorMsg() - Get message of the last occurred error


The setRequest purpose

  • « Yaf_Dispatcher::setErrorHandler
  • Yaf_Dispatcher::setView »
  • PHP Manual
  • Yaf_Dispatcher
  • The setRequest purpose

Yaf_Dispatcher::setRequest

(Yaf >=1.0.0)

Yaf_Dispatcher::setRequest — The setRequest purpose

Description

public Yaf_Dispatcher::setRequest ( Yaf_Request_Abstract $request ) : Yaf_Dispatcher

Parameters

plugin

Return Values


Set a custom view engine

  • « Yaf_Dispatcher::setRequest
  • Yaf_Dispatcher::__sleep »
  • PHP Manual
  • Yaf_Dispatcher
  • Set a custom view engine

Yaf_Dispatcher::setView

(Yaf >=1.0.0)

Yaf_Dispatcher::setView — Set a custom view engine

Description

public Yaf_Dispatcher::setView ( Yaf_View_Interface $view ) : Yaf_Dispatcher

This method proviods a solution for that if you want use a custom view engine instead of Yaf_View_Simple

Parameters

view

A Yaf_View_Interface instance

Return Values

Examples

Example #1 A custom View engine()example

<?php
require "/path/to/smarty/Smarty.class.php";

class Smarty_Adapter implements Yaf_View_Interface
{
    /**
     * Smarty object
     * @var Smarty
     */
    public $_smarty;

    /**
     * Constructor
     *
     * @param string $tmplPath
     * @param array $extraParams
     * @return void
     */
    public function __construct($tmplPath = null, $extraParams = array()) {
        $this->_smarty = new Smarty;

        if (null !== $tmplPath) {
            $this->setScriptPath($tmplPath);
        }

        foreach ($extraParams as $key => $value) {
            $this->_smarty->$key = $value;
        }
    }

    /**
     * Set the path to the templates
     *
     * @param string $path The directory to set as the path.
     * @return void
     */
    public function setScriptPath($path)
    {
        if (is_readable($path)) {
            $this->_smarty->template_dir = $path;
            return;
        }

        throw new Exception('Invalid path provided');
    }

    /**
     * Assign a variable to the template
     *
     * @param string $key The variable name.
     * @param mixed $val The variable value.
     * @return void
     */
    public function __set($key, $val)
    {
        $this->_smarty->assign($key, $val);
    }

    /**
     * Allows testing with empty() and isset() to work
     *
     * @param string $key
     * @return boolean
     */
    public function __isset($key)
    {
        return (null !== $this->_smarty->get_template_vars($key));
    }

    /**
     * Allows unset() on object properties to work
     *
     * @param string $key
     * @return void
     */
    public function __unset($key)
    {
        $this->_smarty->clear_assign($key);
    }

    /**
     * Assign variables to the template
     *
     * Allows setting a specific key to the specified value, OR passing
     * an array of key => value pairs to set en masse.
     *
     * @see __set()
     * @param string|array $spec The assignment strategy to use (key or
     * array of key => value pairs)
     * @param mixed $value (Optional) If assigning a named variable,
     * use this as the value.
     * @return void
     */
    public function assign($spec, $value = null) {
        if (is_array($spec)) {
            $this->_smarty->assign($spec);
            return;
        }

        $this->_smarty->assign($spec, $value);
    }

    /**
     * Clear all assigned variables
     *
     * Clears all variables assigned to Yaf_View either via
     * {@link assign()} or property overloading
     * ({@link __get()}/{@link __set()}).
     *
     * @return void
     */
    public function clearVars() {
        $this->_smarty->clear_all_assign();
    }

    /**
     * Processes a template and returns the output.
     *
     * @param string $name The template to process.
     * @return string The output.
     */
    public function render($name, $value = NULL) {
        return $this->_smarty->fetch($name);
    }

    public function display($name, $value = NULL) {
        echo $this->_smarty->fetch($name);
    }

}
?>

Example #2 Yaf_Dispatcher::setView()example

<?php
class Bootstrap extends Yaf_Bootstrap_Abstract {

    /**
     * there are some config for smarty in the config:
     *
     * smarty.left_delimiter   = "{{"
     * smarty.right_delimiter  = "}}"
     * smarty.template_dir     = APPLICATION_PATH "/views/scripts/"
     * smarty.compile_dir      = APPLICATION_PATH "/views/templates_c/"
     * smarty.cache_dir        = APPLICATION_PATH "/views/templates_d/"
     *
     */
    public function _initConfig() {
        $config = Yaf_Application::app()->getConfig();
        Yaf_Registry::set("config", $config);
    }

    public function _initLocalName() {
        /** we put class Smarty_Adapter under the local library directory */
        Yaf_Loader::getInstance()->registerLocalNamespace('Smarty');
    }

    public function _initSmarty(Yaf_Dispatcher $dispatcher) {
        $smarty = new Smarty_Adapter(null, Yaf_Registry::get("config")->get("smarty"));
        $dispatcher->setView($smarty);
        /* now the Smarty view engine become the default view engine of Yaf */
    }
}
?>

See Also

  • Yaf_View_Interface
  • Yaf_View_Simple


Yaf_Dispatcher can not be serialized

  • « Yaf_Dispatcher::setView
  • Yaf_Dispatcher::throwException »
  • PHP Manual
  • Yaf_Dispatcher
  • Yaf_Dispatcher can not be serialized

Yaf_Dispatcher::__sleep

(Yaf >=1.0.0)

Yaf_Dispatcher::__sleep — Yaf_Dispatcher can not be serialized

Description

private Yaf_Dispatcher::__sleep ( void ) : void

Parameters

This function has no parameters.

Return Values


Switch on/off exception throwing

  • « Yaf_Dispatcher::__sleep
  • Yaf_Dispatcher::__wakeup »
  • PHP Manual
  • Yaf_Dispatcher
  • Switch on/off exception throwing

Yaf_Dispatcher::throwException

(Yaf >=1.0.0)

Yaf_Dispatcher::throwException — Switch on/off exception throwing

Description

public Yaf_Dispatcher::throwException ([ bool $flag ] ) : Yaf_Dispatcher

Siwtch on/off exception throwing while unexpected error occurring. When this is on, Yaf will throwing exceptions instead of triggering catchable errors.

You can also use application.dispatcher.throwException to achieve the same purpose.

Parameters

flag

bool

Return Values

Examples

Example #1 Yaf_Dispatcher::throwexception()example

<?php

$config = array(
    'application' => array(
        'directory' => dirname(__FILE__),
    ),
);
$app = new Yaf_Application($config);

$app->getDispatcher()->throwException(true);

try {
    $app->run();
} catch (Yaf_Exception $e) {
    var_dump($e->getMessage());
}
?>

The above example will output something similar to:

string(59) "Could not find controller script /tmp/controllers/Index.php"

Example #2 Yaf_Dispatcher::throwexception()example

<?php

$config = array(
    'application' => array(
        'directory' => dirname(__FILE__),
    ),
);
$app = new Yaf_Application($config);

$app->getDispatcher()->throwException(false);

$app->run();
?>

The above example will output something similar to:

PHP Catchable fatal error:  Yaf_Application::run(): Could not find controller script /tmp/controllers/Index.php in /tmp/1.php on line 12

See Also

  • Yaf_Dispatcher::catchException() - Switch on/off exception catching
  • Yaf_Exception


Yaf_Dispatcher can not be unserialized

  • « Yaf_Dispatcher::throwException
  • Yaf_Config_Abstract »
  • PHP Manual
  • Yaf_Dispatcher
  • Yaf_Dispatcher can not be unserialized

Yaf_Dispatcher::__wakeup

(Yaf >=1.0.0)

Yaf_Dispatcher::__wakeup — Yaf_Dispatcher can not be unserialized

Description

private Yaf_Dispatcher::__wakeup ( void ) : void

Parameters

This function has no parameters.

Return Values


The Yaf_Config_Abstract class

(Yaf >=1.0.0)

Introduction

Class synopsis

abstract Yaf_Config_Abstract {
/* Properties */
protected $_config ;
protected $_readonly ;
/* Methods */
abstract public get ( string $name , mixed $value ) : mixed
abstract public readonly ( void ) : bool
abstract public set ( void ) : Yaf_Config_Abstract
abstract public toArray ( void ) : array
}

Properties

_config

_readonly

Table of Contents

  • Yaf_Config_Abstract::get — Getter
  • Yaf_Config_Abstract::readonly — Find a config whether readonly
  • Yaf_Config_Abstract::set — Setter
  • Yaf_Config_Abstract::toArray — Cast to array


Getter

  • « Yaf_Config_Abstract
  • Yaf_Config_Abstract::readonly »
  • PHP Manual
  • Yaf_Config_Abstract
  • Getter

Yaf_Config_Abstract::get

(Yaf >=1.0.0)

Yaf_Config_Abstract::get — Getter

Description

abstract public Yaf_Config_Abstract::get ( string $name , mixed $value ) : mixed

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Find a config whether readonly

  • « Yaf_Config_Abstract::get
  • Yaf_Config_Abstract::set »
  • PHP Manual
  • Yaf_Config_Abstract
  • Find a config whether readonly

Yaf_Config_Abstract::readonly

(Yaf >=1.0.0)

Yaf_Config_Abstract::readonly — Find a config whether readonly

Description

abstract public Yaf_Config_Abstract::readonly ( void ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Setter

  • « Yaf_Config_Abstract::readonly
  • Yaf_Config_Abstract::toArray »
  • PHP Manual
  • Yaf_Config_Abstract
  • Setter

Yaf_Config_Abstract::set

(Yaf >=1.0.0)

Yaf_Config_Abstract::set — Setter

Description

abstract public Yaf_Config_Abstract::set ( void ) : Yaf_Config_Abstract

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Cast to array

  • « Yaf_Config_Abstract::set
  • Yaf_Config_Ini »
  • PHP Manual
  • Yaf_Config_Abstract
  • Cast to array

Yaf_Config_Abstract::toArray

(Yaf >=1.0.0)

Yaf_Config_Abstract::toArray — Cast to array

Description

abstract public Yaf_Config_Abstract::toArray ( void ) : array

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The Yaf_Config_Ini class

(Yaf >=1.0.0)

Introduction

Yaf_Config_Ini enables developers to store configuration data in a familiar INI format and read them in the application by using nested object property syntax. The INI format is specialized to provide both the ability to have a hierarchy of configuration data keys and inheritance between configuration data sections. Configuration data hierarchies are supported by separating the keys with the dot or period character ("."). A section may extend or inherit from another section by following the section name with a colon character (":") and the name of the section from which data are to be inherited.

Note:

Yaf_Config_Ini utilizes the » parse_ini_file() PHP function. Please review this documentation to be aware of its specific behaviors, which propagate to Yaf_Config_Ini, such as how the special values of "TRUE", "FALSE", "yes", "no", and "NULL" are handled.

Class synopsis

Yaf_Config_Ini extends Yaf_Config_Abstract implements Iterator , ArrayAccess , Countable {
/* Properties */
/* Methods */
public __construct ( string $config_file [, string $section ] )
public count ( void ) : void
public current ( void ) : void
public __get ([ string $name ] ) : void
public __isset ( string $name ) : void
public key ( void ) : void
public next ( void ) : void
public offsetExists ( string $name ) : void
public offsetGet ( string $name ) : void
public offsetSet ( string $name , string $value ) : void
public offsetUnset ( string $name ) : void
public readonly ( void ) : void
public rewind ( void ) : void
public __set ( string $name , mixed $value ) : void
public toArray ( void ) : array
public valid ( void ) : void
/* Inherited methods */
abstract public Yaf_Config_Abstract::get ( string $name , mixed $value ) : mixed
abstract public Yaf_Config_Abstract::readonly ( void ) : bool
abstract public Yaf_Config_Abstract::set ( void ) : Yaf_Config_Abstract
abstract public Yaf_Config_Abstract::toArray ( void ) : array
}

Properties

_config

_readonly

Examples

Example #1 Yaf_Config_Ini()example

This example illustrates a basic use of Yaf_Config_Ini for loading configuration data from an INI file. In this example there are configuration data for both a production system and for a staging system. Because the staging system configuration data are very similar to those for production, the staging section inherits from the production section. In this case, the decision is arbitrary and could have been written conversely, with the production section inheriting from the staging section, though this may not be the case for more complex situations. Suppose, then, that the following configuration data are contained in /path/to/config.ini:

; Production site configuration data
[production]
webhost                  = www.example.com
database.adapter         = pdo_mysql
database.params.host     = db.example.com
database.params.username = dbuser
database.params.password = secret
database.params.dbname   = dbname

; Staging site configuration data inherits from production and
; overrides values as necessary
[staging : production]
database.params.host     = dev.example.com
database.params.username = devuser
database.params.password = devsecret
<?php
$config = new Yaf_Config_Ini('/path/to/config.ini', 'staging');

var_dump($config->database->params->host);
var_dump($config->database->params->dbname);
var_dump($config->get("database.params.username"));
?>

The above example will output something similar to:

string(15) "dev.example.com"
string(6) "dbname"
string(7) "devuser

Table of Contents

  • Yaf_Config_Ini::__construct — Yaf_Config_Ini constructor
  • Yaf_Config_Ini::count — Count all elements in Yaf_Config.ini
  • Yaf_Config_Ini::current — Retrieve the current value
  • Yaf_Config_Ini::__get — Retrieve a element
  • Yaf_Config_Ini::__isset — Determine if a key is exists
  • Yaf_Config_Ini::key — Fetch current element's key
  • Yaf_Config_Ini::next — Advance the internal pointer
  • Yaf_Config_Ini::offsetExists — The offsetExists purpose
  • Yaf_Config_Ini::offsetGet — The offsetGet purpose
  • Yaf_Config_Ini::offsetSet — The offsetSet purpose
  • Yaf_Config_Ini::offsetUnset — The offsetUnset purpose
  • Yaf_Config_Ini::readonly — The readonly purpose
  • Yaf_Config_Ini::rewind — The rewind purpose
  • Yaf_Config_Ini::__set — The __set purpose
  • Yaf_Config_Ini::toArray — Return config as a PHP array
  • Yaf_Config_Ini::valid — The valid purpose


Yaf_Config_Ini constructor

  • « Yaf_Config_Ini
  • Yaf_Config_Ini::count »
  • PHP Manual
  • Yaf_Config_Ini
  • Yaf_Config_Ini constructor

Yaf_Config_Ini::__construct

(Yaf >=1.0.0)

Yaf_Config_Ini::__construct — Yaf_Config_Ini constructor

Description

public Yaf_Config_Ini::__construct ( string $config_file [, string $section ] )

Yaf_Config_Ini constructor

Parameters

config_file

path to an INI configure file

section

which section in that INI file you want to be parsed

Return Values


Count all elements in Yaf_Config.ini

  • « Yaf_Config_Ini::__construct
  • Yaf_Config_Ini::current »
  • PHP Manual
  • Yaf_Config_Ini
  • Count all elements in Yaf_Config.ini

Yaf_Config_Ini::count

(Yaf >=1.0.0)

Yaf_Config_Ini::count — Count all elements in Yaf_Config.ini

Description

public Yaf_Config_Ini::count ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Retrieve the current value

  • « Yaf_Config_Ini::count
  • Yaf_Config_Ini::__get »
  • PHP Manual
  • Yaf_Config_Ini
  • Retrieve the current value

Yaf_Config_Ini::current

(Yaf >=1.0.0)

Yaf_Config_Ini::current — Retrieve the current value

Description

public Yaf_Config_Ini::current ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Retrieve a element

  • « Yaf_Config_Ini::current
  • Yaf_Config_Ini::__isset »
  • PHP Manual
  • Yaf_Config_Ini
  • Retrieve a element

Yaf_Config_Ini::__get

(Yaf >=1.0.0)

Yaf_Config_Ini::__get — Retrieve a element

Description

public Yaf_Config_Ini::__get ([ string $name ] ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values


Determine if a key is exists

  • « Yaf_Config_Ini::__get
  • Yaf_Config_Ini::key »
  • PHP Manual
  • Yaf_Config_Ini
  • Determine if a key is exists

Yaf_Config_Ini::__isset

(Yaf >=1.0.0)

Yaf_Config_Ini::__isset — Determine if a key is exists

Description

public Yaf_Config_Ini::__isset ( string $name ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values


Fetch current element's key

  • « Yaf_Config_Ini::__isset
  • Yaf_Config_Ini::next »
  • PHP Manual
  • Yaf_Config_Ini
  • Fetch current element's key

Yaf_Config_Ini::key

(Yaf >=1.0.0)

Yaf_Config_Ini::key — Fetch current element's key

Description

public Yaf_Config_Ini::key ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Advance the internal pointer

  • « Yaf_Config_Ini::key
  • Yaf_Config_Ini::offsetExists »
  • PHP Manual
  • Yaf_Config_Ini
  • Advance the internal pointer

Yaf_Config_Ini::next

(Yaf >=1.0.0)

Yaf_Config_Ini::next — Advance the internal pointer

Description

public Yaf_Config_Ini::next ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The offsetExists purpose

  • « Yaf_Config_Ini::next
  • Yaf_Config_Ini::offsetGet »
  • PHP Manual
  • Yaf_Config_Ini
  • The offsetExists purpose

Yaf_Config_Ini::offsetExists

(Yaf >=1.0.0)

Yaf_Config_Ini::offsetExists — The offsetExists purpose

Description

public Yaf_Config_Ini::offsetExists ( string $name ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values


The offsetGet purpose

  • « Yaf_Config_Ini::offsetExists
  • Yaf_Config_Ini::offsetSet »
  • PHP Manual
  • Yaf_Config_Ini
  • The offsetGet purpose

Yaf_Config_Ini::offsetGet

(Yaf >=1.0.0)

Yaf_Config_Ini::offsetGet — The offsetGet purpose

Description

public Yaf_Config_Ini::offsetGet ( string $name ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values


The offsetSet purpose

  • « Yaf_Config_Ini::offsetGet
  • Yaf_Config_Ini::offsetUnset »
  • PHP Manual
  • Yaf_Config_Ini
  • The offsetSet purpose

Yaf_Config_Ini::offsetSet

(Yaf >=1.0.0)

Yaf_Config_Ini::offsetSet — The offsetSet purpose

Description

public Yaf_Config_Ini::offsetSet ( string $name , string $value ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

value

Return Values


The offsetUnset purpose

  • « Yaf_Config_Ini::offsetSet
  • Yaf_Config_Ini::readonly »
  • PHP Manual
  • Yaf_Config_Ini
  • The offsetUnset purpose

Yaf_Config_Ini::offsetUnset

(Yaf >=1.0.0)

Yaf_Config_Ini::offsetUnset — The offsetUnset purpose

Description

public Yaf_Config_Ini::offsetUnset ( string $name ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values


The readonly purpose

  • « Yaf_Config_Ini::offsetUnset
  • Yaf_Config_Ini::rewind »
  • PHP Manual
  • Yaf_Config_Ini
  • The readonly purpose

Yaf_Config_Ini::readonly

(Yaf >=1.0.0)

Yaf_Config_Ini::readonly — The readonly purpose

Description

public Yaf_Config_Ini::readonly ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The rewind purpose

  • « Yaf_Config_Ini::readonly
  • Yaf_Config_Ini::__set »
  • PHP Manual
  • Yaf_Config_Ini
  • The rewind purpose

Yaf_Config_Ini::rewind

(Yaf >=1.0.0)

Yaf_Config_Ini::rewind — The rewind purpose

Description

public Yaf_Config_Ini::rewind ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The __set purpose

  • « Yaf_Config_Ini::rewind
  • Yaf_Config_Ini::toArray »
  • PHP Manual
  • Yaf_Config_Ini
  • The __set purpose

Yaf_Config_Ini::__set

(Yaf >=1.0.0)

Yaf_Config_Ini::__set — The __set purpose

Description

public Yaf_Config_Ini::__set ( string $name , mixed $value ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

value

Return Values


Return config as a PHP array

  • « Yaf_Config_Ini::__set
  • Yaf_Config_Ini::valid »
  • PHP Manual
  • Yaf_Config_Ini
  • Return config as a PHP array

Yaf_Config_Ini::toArray

(Yaf >=1.0.0)

Yaf_Config_Ini::toArray — Return config as a PHP array

Description

public Yaf_Config_Ini::toArray ( void ) : array

Returns a PHP array from the Yaf_Config_Ini

Parameters

This function has no parameters.

Return Values


The valid purpose

  • « Yaf_Config_Ini::toArray
  • Yaf_Config_Simple »
  • PHP Manual
  • Yaf_Config_Ini
  • The valid purpose

Yaf_Config_Ini::valid

(Yaf >=1.0.0)

Yaf_Config_Ini::valid — The valid purpose

Description

public Yaf_Config_Ini::valid ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The Yaf_Config_Simple class

(Yaf >=1.0.0)

Introduction

Class synopsis

Yaf_Config_Simple extends Yaf_Config_Abstract implements Iterator , ArrayAccess , Countable {
/* Properties */
protected $_readonly ;
/* Methods */
public __construct ( string $config_file [, string $section ] )
public count ( void ) : void
public current ( void ) : void
public __get ([ string $name ] ) : void
public __isset ( string $name ) : void
public key ( void ) : void
public next ( void ) : void
public offsetExists ( string $name ) : void
public offsetGet ( string $name ) : void
public offsetSet ( string $name , string $value ) : void
public offsetUnset ( string $name ) : void
public readonly ( void ) : void
public rewind ( void ) : void
public __set ( string $name , string $value ) : void
public toArray ( void ) : array
public valid ( void ) : void
/* Inherited methods */
abstract public Yaf_Config_Abstract::get ( string $name , mixed $value ) : mixed
abstract public Yaf_Config_Abstract::readonly ( void ) : bool
abstract public Yaf_Config_Abstract::set ( void ) : Yaf_Config_Abstract
abstract public Yaf_Config_Abstract::toArray ( void ) : array
}

Properties

_config

_readonly

Table of Contents

  • Yaf_Config_Simple::__construct — The __construct purpose
  • Yaf_Config_Simple::count — The count purpose
  • Yaf_Config_Simple::current — The current purpose
  • Yaf_Config_Simple::__get — The __get purpose
  • Yaf_Config_Simple::__isset — The __isset purpose
  • Yaf_Config_Simple::key — The key purpose
  • Yaf_Config_Simple::next — The next purpose
  • Yaf_Config_Simple::offsetExists — The offsetExists purpose
  • Yaf_Config_Simple::offsetGet — The offsetGet purpose
  • Yaf_Config_Simple::offsetSet — The offsetSet purpose
  • Yaf_Config_Simple::offsetUnset — The offsetUnset purpose
  • Yaf_Config_Simple::readonly — The readonly purpose
  • Yaf_Config_Simple::rewind — The rewind purpose
  • Yaf_Config_Simple::__set — The __set purpose
  • Yaf_Config_Simple::toArray — Returns a PHP array
  • Yaf_Config_Simple::valid — The valid purpose


The __construct purpose

  • « Yaf_Config_Simple
  • Yaf_Config_Simple::count »
  • PHP Manual
  • Yaf_Config_Simple
  • The __construct purpose

Yaf_Config_Simple::__construct

(Yaf >=1.0.0)

Yaf_Config_Simple::__construct — The __construct purpose

Description

public Yaf_Config_Simple::__construct ( string $config_file [, string $section ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

config_file

section

Return Values


The count purpose

  • « Yaf_Config_Simple::__construct
  • Yaf_Config_Simple::current »
  • PHP Manual
  • Yaf_Config_Simple
  • The count purpose

Yaf_Config_Simple::count

(Yaf >=1.0.0)

Yaf_Config_Simple::count — The count purpose

Description

public Yaf_Config_Simple::count ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The current purpose

  • « Yaf_Config_Simple::count
  • Yaf_Config_Simple::__get »
  • PHP Manual
  • Yaf_Config_Simple
  • The current purpose

Yaf_Config_Simple::current

(Yaf >=1.0.0)

Yaf_Config_Simple::current — The current purpose

Description

public Yaf_Config_Simple::current ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The __get purpose

  • « Yaf_Config_Simple::current
  • Yaf_Config_Simple::__isset »
  • PHP Manual
  • Yaf_Config_Simple
  • The __get purpose

Yaf_Config_Simple::__get

(Yaf >=1.0.0)

Yaf_Config_Simple::__get — The __get purpose

Description

public Yaf_Config_Simple::__get ([ string $name ] ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values


The __isset purpose

  • « Yaf_Config_Simple::__get
  • Yaf_Config_Simple::key »
  • PHP Manual
  • Yaf_Config_Simple
  • The __isset purpose

Yaf_Config_Simple::__isset

(Yaf >=1.0.0)

Yaf_Config_Simple::__isset — The __isset purpose

Description

public Yaf_Config_Simple::__isset ( string $name ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values


The key purpose

  • « Yaf_Config_Simple::__isset
  • Yaf_Config_Simple::next »
  • PHP Manual
  • Yaf_Config_Simple
  • The key purpose

Yaf_Config_Simple::key

(Yaf >=1.0.0)

Yaf_Config_Simple::key — The key purpose

Description

public Yaf_Config_Simple::key ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The next purpose

  • « Yaf_Config_Simple::key
  • Yaf_Config_Simple::offsetExists »
  • PHP Manual
  • Yaf_Config_Simple
  • The next purpose

Yaf_Config_Simple::next

(Yaf >=1.0.0)

Yaf_Config_Simple::next — The next purpose

Description

public Yaf_Config_Simple::next ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The offsetExists purpose

  • « Yaf_Config_Simple::next
  • Yaf_Config_Simple::offsetGet »
  • PHP Manual
  • Yaf_Config_Simple
  • The offsetExists purpose

Yaf_Config_Simple::offsetExists

(Yaf >=1.0.0)

Yaf_Config_Simple::offsetExists — The offsetExists purpose

Description

public Yaf_Config_Simple::offsetExists ( string $name ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values


The offsetGet purpose

  • « Yaf_Config_Simple::offsetExists
  • Yaf_Config_Simple::offsetSet »
  • PHP Manual
  • Yaf_Config_Simple
  • The offsetGet purpose

Yaf_Config_Simple::offsetGet

(Yaf >=1.0.0)

Yaf_Config_Simple::offsetGet — The offsetGet purpose

Description

public Yaf_Config_Simple::offsetGet ( string $name ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values


The offsetSet purpose

  • « Yaf_Config_Simple::offsetGet
  • Yaf_Config_Simple::offsetUnset »
  • PHP Manual
  • Yaf_Config_Simple
  • The offsetSet purpose

Yaf_Config_Simple::offsetSet

(Yaf >=1.0.0)

Yaf_Config_Simple::offsetSet — The offsetSet purpose

Description

public Yaf_Config_Simple::offsetSet ( string $name , string $value ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

value

Return Values


The offsetUnset purpose

  • « Yaf_Config_Simple::offsetSet
  • Yaf_Config_Simple::readonly »
  • PHP Manual
  • Yaf_Config_Simple
  • The offsetUnset purpose

Yaf_Config_Simple::offsetUnset

(Yaf >=1.0.0)

Yaf_Config_Simple::offsetUnset — The offsetUnset purpose

Description

public Yaf_Config_Simple::offsetUnset ( string $name ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values


The readonly purpose

  • « Yaf_Config_Simple::offsetUnset
  • Yaf_Config_Simple::rewind »
  • PHP Manual
  • Yaf_Config_Simple
  • The readonly purpose

Yaf_Config_Simple::readonly

(Yaf >=1.0.0)

Yaf_Config_Simple::readonly — The readonly purpose

Description

public Yaf_Config_Simple::readonly ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The rewind purpose

  • « Yaf_Config_Simple::readonly
  • Yaf_Config_Simple::__set »
  • PHP Manual
  • Yaf_Config_Simple
  • The rewind purpose

Yaf_Config_Simple::rewind

(Yaf >=1.0.0)

Yaf_Config_Simple::rewind — The rewind purpose

Description

public Yaf_Config_Simple::rewind ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The __set purpose

  • « Yaf_Config_Simple::rewind
  • Yaf_Config_Simple::toArray »
  • PHP Manual
  • Yaf_Config_Simple
  • The __set purpose

Yaf_Config_Simple::__set

(Yaf >=1.0.0)

Yaf_Config_Simple::__set — The __set purpose

Description

public Yaf_Config_Simple::__set ( string $name , string $value ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

value

Return Values


Returns a PHP array

  • « Yaf_Config_Simple::__set
  • Yaf_Config_Simple::valid »
  • PHP Manual
  • Yaf_Config_Simple
  • Returns a PHP array

Yaf_Config_Simple::toArray

(Yaf >=1.0.0)

Yaf_Config_Simple::toArray — Returns a PHP array

Description

public Yaf_Config_Simple::toArray ( void ) : array

Returns a PHP array from the Yaf_Config_Simple

Parameters

This function has no parameters.

Return Values


The valid purpose

  • « Yaf_Config_Simple::toArray
  • Yaf_Controller_Abstract »
  • PHP Manual
  • Yaf_Config_Simple
  • The valid purpose

Yaf_Config_Simple::valid

(Yaf >=1.0.0)

Yaf_Config_Simple::valid — The valid purpose

Description

public Yaf_Config_Simple::valid ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The Yaf_Controller_Abstract class

(Yaf >=1.0.0)

Introduction

Yaf_Controller_Abstract is the heart of Yaf's system. MVC stands for Model-View-Controller and is a design pattern targeted at separating application logic from display logic.

Every custom controller shall inherit Yaf_Controller_Abstract.

You will find that you can not define __construct function for your custom controller, thus, Yaf_Controller_Abstract provides a magic method: Yaf_Controller_Abstract::init().

If you have defined a init() method in your custom controller, it will be called as long as the controller was instantiated.

Action may have arguments, when a request coming, if there are the same name variable in the request parameters(see Yaf_Request_Abstract::getParam()) after routed, Yaf will pass them to the action method (see Yaf_Action_Abstract::execute()).

Note:

These arguments are directly fetched without filtering, it should be carefully processed before use them.

Class synopsis

abstract Yaf_Controller_Abstract {
/* Properties */
public $actions ;
protected $_module ;
protected $_name ;
protected $_request ;
protected $_response ;
protected $_invoke_args ;
protected $_view ;
/* Methods */
final private __clone ( void ) : void
final private __construct ( void )
protected display ( string $tpl [, array $parameters ] ) : bool
public forward ( string $action [, array $paramters ] ) : void
public getInvokeArg ( string $name ) : void
public getInvokeArgs ( void ) : void
public getModuleName ( void ) : string
public getRequest ( void ) : Yaf_Request_Abstract
public getResponse ( void ) : Yaf_Response_Abstract
public getView ( void ) : Yaf_View_Interface
public getViewpath ( void ) : string
public init ( void ) : void
public initView ([ array $options ] ) : void
public redirect ( string $url ) : bool
protected render ( string $tpl [, array $parameters ] ) : string
public setViewpath ( string $view_directory ) : void
}

Properties

actions

You can also define a action method in a separate PHP script by using this property and Yaf_Action_Abstract.

Example #1 define action in a separate file

<?php
class IndexController extends Yaf_Controller_Abstract {
    protected $actions = array(
        /** now dummyAction is defined in a separate file */
        "dummy" => "actions/Dummy_action.php",
    );

    /* action method may have arguments */
    public indexAction($name, $id) {
       /* $name and $id are unsafe raw data */
       assert($name == $this->getRequest()->getParam("name"));
       assert($id   == $this->_request->getParam("id"));
    }
}
?>

Example #2 Dummy_action.php

<?php
class DummyAction extends Yaf_Action_Abstract {
    /* a action class shall define this method  as the entry point */
    public execute() {
    }
}
?>

_module

module name

_name

controller name

_request

current request object

_response

current response object

_invoke_args

_view

view engine object

Table of Contents

  • Yaf_Controller_Abstract::__clone — Yaf_Controller_Abstract can not be cloned
  • Yaf_Controller_Abstract::__construct — Yaf_Controller_Abstract constructor
  • Yaf_Controller_Abstract::display — The display purpose
  • Yaf_Controller_Abstract::forward — Foward to another action
  • Yaf_Controller_Abstract::getInvokeArg — The getInvokeArg purpose
  • Yaf_Controller_Abstract::getInvokeArgs — The getInvokeArgs purpose
  • Yaf_Controller_Abstract::getModuleName — Get module name
  • Yaf_Controller_Abstract::getRequest — Retrieve current request object
  • Yaf_Controller_Abstract::getResponse — Retrieve current response object
  • Yaf_Controller_Abstract::getView — Retrieve the view engine
  • Yaf_Controller_Abstract::getViewpath — The getViewpath purpose
  • Yaf_Controller_Abstract::init — Controller initializer
  • Yaf_Controller_Abstract::initView — The initView purpose
  • Yaf_Controller_Abstract::redirect — Redirect to a URL
  • Yaf_Controller_Abstract::render — Render view template
  • Yaf_Controller_Abstract::setViewpath — The setViewpath purpose


Yaf_Controller_Abstract can not be cloned

  • « Yaf_Controller_Abstract
  • Yaf_Controller_Abstract::__construct »
  • PHP Manual
  • Yaf_Controller_Abstract
  • Yaf_Controller_Abstract can not be cloned

Yaf_Controller_Abstract::__clone

(Yaf >=1.0.0)

Yaf_Controller_Abstract::__clone — Yaf_Controller_Abstract can not be cloned

Description

final private Yaf_Controller_Abstract::__clone ( void ) : void

Parameters

This function has no parameters.

Return Values


Yaf_Controller_Abstract constructor

  • « Yaf_Controller_Abstract::__clone
  • Yaf_Controller_Abstract::display »
  • PHP Manual
  • Yaf_Controller_Abstract
  • Yaf_Controller_Abstract constructor

Yaf_Controller_Abstract::__construct

(Yaf >=1.0.0)

Yaf_Controller_Abstract::__construct — Yaf_Controller_Abstract constructor

Description

final private Yaf_Controller_Abstract::__construct ( void )

Yaf_Controller_Abstract::__construct() is final, which means it can not be overridden. You may want to see Yaf_Controller_Abstract::init() instead.

Parameters

This function has no parameters.

Return Values

See Also

  • Yaf_Controller_Abstract::init() - Controller initializer


The display purpose

  • « Yaf_Controller_Abstract::__construct
  • Yaf_Controller_Abstract::forward »
  • PHP Manual
  • Yaf_Controller_Abstract
  • The display purpose

Yaf_Controller_Abstract::display

(Yaf >=1.0.0)

Yaf_Controller_Abstract::display — The display purpose

Description

protected Yaf_Controller_Abstract::display ( string $tpl [, array $parameters ] ) : bool

Parameters

tpl

parameters

Return Values


Foward to another action

  • « Yaf_Controller_Abstract::display
  • Yaf_Controller_Abstract::getInvokeArg »
  • PHP Manual
  • Yaf_Controller_Abstract
  • Foward to another action

Yaf_Controller_Abstract::forward

(Yaf >=1.0.0)

Yaf_Controller_Abstract::forward — Foward to another action

Description

public Yaf_Controller_Abstract::forward ( string $action [, array $paramters ] ) : void
public Yaf_Controller_Abstract::forward ( string $controller , string $action [, array $paramters ] ) : void
public Yaf_Controller_Abstract::forward ( string $module , string $controller , string $action [, array $paramters ] ) : void

forward current execution process to other action.

Note:

this method doesn't switch to the destination action immediately, it will take place after current flow finish.

Parameters

module

destination module name, if NULL was given, then default module name is assumed

controller

destination controller name

action

destination action name

paramters

calling arguments

Examples

Example #1 Yaf_Controller_Abstract::forward()example

<?php
class IndexController extends Yaf_Controller_Abstract
{
    public function indexAction(){
         $logined = $_SESSION["login"];
         if (!$logined) {
             $this->forward("login", array("from" => "Index")); // forward to login action
             return FALSE;  // this is important, this finish current working flow
                            // and tell the Yaf do not doing auto-render
         }

         // other processes
    }

    public function loginAction() {
         echo "login, redirected from ", $this->_request->getParam("from") , " action";
    }
}
?>

The above example will output something similar to:

   login, redirected from Index action

Return Values

return FALSE on failure

See Also

  • Yaf_Request_Abstrace::getParam()


The getInvokeArg purpose

  • « Yaf_Controller_Abstract::forward
  • Yaf_Controller_Abstract::getInvokeArgs »
  • PHP Manual
  • Yaf_Controller_Abstract
  • The getInvokeArg purpose

Yaf_Controller_Abstract::getInvokeArg

(Yaf >=1.0.0)

Yaf_Controller_Abstract::getInvokeArg — The getInvokeArg purpose

Description

public Yaf_Controller_Abstract::getInvokeArg ( string $name ) : void

Parameters

name

Return Values


The getInvokeArgs purpose

  • « Yaf_Controller_Abstract::getInvokeArg
  • Yaf_Controller_Abstract::getModuleName »
  • PHP Manual
  • Yaf_Controller_Abstract
  • The getInvokeArgs purpose

Yaf_Controller_Abstract::getInvokeArgs

(Yaf >=1.0.0)

Yaf_Controller_Abstract::getInvokeArgs — The getInvokeArgs purpose

Description

public Yaf_Controller_Abstract::getInvokeArgs ( void ) : void

Parameters

This function has no parameters.

Return Values


Get module name

  • « Yaf_Controller_Abstract::getInvokeArgs
  • Yaf_Controller_Abstract::getRequest »
  • PHP Manual
  • Yaf_Controller_Abstract
  • Get module name

Yaf_Controller_Abstract::getModuleName

(Yaf >=1.0.0)

Yaf_Controller_Abstract::getModuleName — Get module name

Description

public Yaf_Controller_Abstract::getModuleName ( void ) : string

get the controller's module name

Parameters

This function has no parameters.

Return Values


Retrieve current request object

  • « Yaf_Controller_Abstract::getModuleName
  • Yaf_Controller_Abstract::getResponse »
  • PHP Manual
  • Yaf_Controller_Abstract
  • Retrieve current request object

Yaf_Controller_Abstract::getRequest

(Yaf >=1.0.0)

Yaf_Controller_Abstract::getRequest — Retrieve current request object

Description

public Yaf_Controller_Abstract::getRequest ( void ) : Yaf_Request_Abstract

retrieve current request object

Parameters

This function has no parameters.

Return Values

Yaf_Request_Abstract instance


Retrieve current response object

  • « Yaf_Controller_Abstract::getRequest
  • Yaf_Controller_Abstract::getView »
  • PHP Manual
  • Yaf_Controller_Abstract
  • Retrieve current response object

Yaf_Controller_Abstract::getResponse

(Yaf >=1.0.0)

Yaf_Controller_Abstract::getResponse — Retrieve current response object

Description

public Yaf_Controller_Abstract::getResponse ( void ) : Yaf_Response_Abstract

retrieve current response object

Parameters

This function has no parameters.

Return Values

Yaf_Response_Abstract instance


Retrieve the view engine

  • « Yaf_Controller_Abstract::getResponse
  • Yaf_Controller_Abstract::getViewpath »
  • PHP Manual
  • Yaf_Controller_Abstract
  • Retrieve the view engine

Yaf_Controller_Abstract::getView

(Yaf >=1.0.0)

Yaf_Controller_Abstract::getView — Retrieve the view engine

Description

public Yaf_Controller_Abstract::getView ( void ) : Yaf_View_Interface

retrieve view engine

Parameters

This function has no parameters.

Return Values


The getViewpath purpose

  • « Yaf_Controller_Abstract::getView
  • Yaf_Controller_Abstract::init »
  • PHP Manual
  • Yaf_Controller_Abstract
  • The getViewpath purpose

Yaf_Controller_Abstract::getViewpath

(Yaf >=1.0.0)

Yaf_Controller_Abstract::getViewpath — The getViewpath purpose

Description

public Yaf_Controller_Abstract::getViewpath ( void ) : string

Parameters

This function has no parameters.

Return Values


Controller initializer

  • « Yaf_Controller_Abstract::getViewpath
  • Yaf_Controller_Abstract::initView »
  • PHP Manual
  • Yaf_Controller_Abstract
  • Controller initializer

Yaf_Controller_Abstract::init

(Yaf >=1.0.0)

Yaf_Controller_Abstract::init — Controller initializer

Description

public Yaf_Controller_Abstract::init ( void ) : void

Yaf_Controller_Abstract::__construct() is final, which means users can not override it. but users can define Yaf_Controller_Abstract::init(), which will be called after controller object is instantiated.

Parameters

This function has no parameters.

Return Values

See Also

  • Yaf_Controller_Abstract::__construct() - Yaf_Controller_Abstract constructor


The initView purpose

  • « Yaf_Controller_Abstract::init
  • Yaf_Controller_Abstract::redirect »
  • PHP Manual
  • Yaf_Controller_Abstract
  • The initView purpose

Yaf_Controller_Abstract::initView

(Yaf >=1.0.0)

Yaf_Controller_Abstract::initView — The initView purpose

Description

public Yaf_Controller_Abstract::initView ([ array $options ] ) : void

Parameters

options

Return Values


Redirect to a URL

  • « Yaf_Controller_Abstract::initView
  • Yaf_Controller_Abstract::render »
  • PHP Manual
  • Yaf_Controller_Abstract
  • Redirect to a URL

Yaf_Controller_Abstract::redirect

(Yaf >=1.0.0)

Yaf_Controller_Abstract::redirect — Redirect to a URL

Description

public Yaf_Controller_Abstract::redirect ( string $url ) : bool

redirect to a URL by sending a 302 header

Parameters

url

a location URL

Return Values

bool


Render view template

  • « Yaf_Controller_Abstract::redirect
  • Yaf_Controller_Abstract::setViewpath »
  • PHP Manual
  • Yaf_Controller_Abstract
  • Render view template

Yaf_Controller_Abstract::render

(Yaf >=1.0.0)

Yaf_Controller_Abstract::render — Render view template

Description

protected Yaf_Controller_Abstract::render ( string $tpl [, array $parameters ] ) : string

Parameters

tpl

parameters

Return Values


The setViewpath purpose

  • « Yaf_Controller_Abstract::render
  • Yaf_Action_Abstract »
  • PHP Manual
  • Yaf_Controller_Abstract
  • The setViewpath purpose

Yaf_Controller_Abstract::setViewpath

(Yaf >=1.0.0)

Yaf_Controller_Abstract::setViewpath — The setViewpath purpose

Description

public Yaf_Controller_Abstract::setViewpath ( string $view_directory ) : void

Parameters

view_directory

Return Values


The Yaf_Action_Abstract class

(Yaf >=1.0.0)

Introduction

A action can be defined in a separate file in Yaf(see Yaf_Controller_Abstract). that is a action method can also be a Yaf_Action_Abstract class.

Since there should be a entry point which can be called by Yaf (as of PHP 5.3, there is a new magic method __invoke, but Yaf is not only works with PHP 5.3+, Yaf choose another magic method execute), you must implement the abstract method Yaf_Action_Abstract::execute() in your custom action class.

Class synopsis

Yaf_Action_Abstract extends Yaf_Controller_Abstract {
/* Properties */
protected $_controller ;
/* Methods */
abstract publicexecute ([ mixed $arg [, mixed $... ]] ) : mixed
publicgetController ( void ) : Yaf_Controller_Abstract
/* Inherited methods */
final private Yaf_Controller_Abstract::__clone ( void ) : void
final private Yaf_Controller_Abstract::__construct ( void )
protected Yaf_Controller_Abstract::display ( string $tpl [, array $parameters ] ) : bool
public Yaf_Controller_Abstract::forward ( string $action [, array $paramters ] ) : void
public Yaf_Controller_Abstract::getInvokeArg ( string $name ) : void
public Yaf_Controller_Abstract::getInvokeArgs ( void ) : void
public Yaf_Controller_Abstract::getModuleName ( void ) : string
public Yaf_Controller_Abstract::getRequest ( void ) : Yaf_Request_Abstract
public Yaf_Controller_Abstract::getResponse ( void ) : Yaf_Response_Abstract
public Yaf_Controller_Abstract::getView ( void ) : Yaf_View_Interface
public Yaf_Controller_Abstract::getViewpath ( void ) : string
public Yaf_Controller_Abstract::init ( void ) : void
public Yaf_Controller_Abstract::initView ([ array $options ] ) : void
public Yaf_Controller_Abstract::redirect ( string $url ) : bool
protected Yaf_Controller_Abstract::render ( string $tpl [, array $parameters ] ) : string
public Yaf_Controller_Abstract::setViewpath ( string $view_directory ) : void
}

Properties

_module

_name

_request

_response

_invoke_args

_view

_controller

Table of Contents

  • Yaf_Action_Abstract::execute — Action entry point
  • Yaf_Action_Abstract::getController — Retrieve controller object


Action entry point

  • « Yaf_Action_Abstract
  • Yaf_Action_Abstract::getController »
  • PHP Manual
  • Yaf_Action_Abstract
  • Action entry point

Yaf_Action_Abstract::execute

(Yaf >=1.0.0)

Yaf_Action_Abstract::execute — Action entry point

Description

abstract publicYaf_Action_Abstract::execute ([ mixed $arg [, mixed $... ]] ) : mixed

user should always define this method for a action, this is the entry point of an action. Yaf_Action_Abstract::execute() may have agruments.

Note:

The value retrived from the request is not safe. you should do some filtering work before you use it.

Parameters

This function has no parameters.

Return Values

Examples

Example #1 Yaf_Action_Abstract::execute()example

<?php
/**
 * A controller example
 */
class ProductController extends Yaf_Controller_Abstract {
      protected $actions = array(
          "index" => "actions/Index.php",
      );
}
?>

Example #2 Yaf_Action_Abstract::execute()example

<?php
/**
 * ListAction
 */
class ListAction extends Yaf_Action_Abstract {
     public function execute ($name, $id) {
         assert($name == $this->getRequest()->getParam("name"));
         assert($id   == $this->getRequest()->getParam("id"));
     }
}
?>

The above example will output something similar to:

/**
 * Now assuming we are using the Yaf_Route_Static route
 * for request: http://yourdomain/product/list/name/yaf/id/22
 * will result:
 */
 bool(true)
 bool(true)

See Also


Retrieve controller object

  • « Yaf_Action_Abstract::execute
  • Yaf_View_Interface »
  • PHP Manual
  • Yaf_Action_Abstract
  • Retrieve controller object

Yaf_Action_Abstract::getController

(Yaf >=1.0.0)

Yaf_Action_Abstract::getController — Retrieve controller object

Description

publicYaf_Action_Abstract::getController ( void ) : Yaf_Controller_Abstract

retrieve current controller object.

Parameters

This function has no parameters.

Return Values

Yaf_Controller_Abstract instance


The Yaf_View_Interface class

(Yaf >=1.0.0)

Introduction

Yaf provides a ability for developers to use custom view engine instead of built-in engine which is Yaf_View_Simple. There is a example to explain how to do this, please see Yaf_Dispatcher::setView().

Class synopsis

Yaf_View_Interface {
/* Methods */
abstract public assign ( string $name [, string $value ] ) : bool
abstract public display ( string $tpl [, array $tpl_vars ] ) : bool
abstract public getScriptPath ( void ) : void
abstract public render ( string $tpl [, array $tpl_vars ] ) : string
abstract public setScriptPath ( string $template_dir ) : void
}

Table of Contents

  • Yaf_View_Interface::assign — Assign value to View engine
  • Yaf_View_Interface::display — Render and output a template
  • Yaf_View_Interface::getScriptPath — The getScriptPath purpose
  • Yaf_View_Interface::render — Render a template
  • Yaf_View_Interface::setScriptPath — The setScriptPath purpose


Assign value to View engine

  • « Yaf_View_Interface
  • Yaf_View_Interface::display »
  • PHP Manual
  • Yaf_View_Interface
  • Assign value to View engine

Yaf_View_Interface::assign

(Yaf >=1.0.0)

Yaf_View_Interface::assign — Assign value to View engine

Description

abstract public Yaf_View_Interface::assign ( string $name [, string $value ] ) : bool

Assigan values to View engine, then the value can access directly by name in template.

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

value

Return Values


Render and output a template

  • « Yaf_View_Interface::assign
  • Yaf_View_Interface::getScriptPath »
  • PHP Manual
  • Yaf_View_Interface
  • Render and output a template

Yaf_View_Interface::display

(Yaf >=1.0.0)

Yaf_View_Interface::display — Render and output a template

Description

abstract public Yaf_View_Interface::display ( string $tpl [, array $tpl_vars ] ) : bool

Render a template and output the result immediatly.

Warning

This function is currently not documented; only its argument list is available.

Parameters

tpl

tpl_vars

Return Values


The getScriptPath purpose

  • « Yaf_View_Interface::display
  • Yaf_View_Interface::render »
  • PHP Manual
  • Yaf_View_Interface
  • The getScriptPath purpose

Yaf_View_Interface::getScriptPath

(Yaf >=1.0.0)

Yaf_View_Interface::getScriptPath — The getScriptPath purpose

Description

abstract public Yaf_View_Interface::getScriptPath ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Render a template

  • « Yaf_View_Interface::getScriptPath
  • Yaf_View_Interface::setScriptPath »
  • PHP Manual
  • Yaf_View_Interface
  • Render a template

Yaf_View_Interface::render

(Yaf >=1.0.0)

Yaf_View_Interface::render — Render a template

Description

abstract public Yaf_View_Interface::render ( string $tpl [, array $tpl_vars ] ) : string

Render a template and return the result.

Warning

This function is currently not documented; only its argument list is available.

Parameters

tpl

tpl_vars

Return Values


The setScriptPath purpose

  • « Yaf_View_Interface::render
  • Yaf_View_Simple »
  • PHP Manual
  • Yaf_View_Interface
  • The setScriptPath purpose

Yaf_View_Interface::setScriptPath

(Yaf >=1.0.0)

Yaf_View_Interface::setScriptPath — The setScriptPath purpose

Description

abstract public Yaf_View_Interface::setScriptPath ( string $template_dir ) : void

Set the templates base directory, this is usually called by Yaf_Dispatcher

Warning

This function is currently not documented; only its argument list is available.

Parameters

template_dir

A absolute path to the template directory, by default, Yaf_Dispatcher use application.directory . "/views" as this paramter.

Return Values


The Yaf_View_Simple class

(Yaf >=1.0.0)

Introduction

Yaf_View_Simple is the built-in template engine in Yaf, it is a simple but fast template engine, and only support PHP script template.

Class synopsis

Yaf_View_Simple implements Yaf_View_Interface {
/* Properties */
protected $_tpl_vars ;
protected $_tpl_dir ;
/* Methods */
public assign ( string $name [, mixed $value ] ) : bool
public assignRef ( string $name , mixed &$value ) : bool
public clear ([ string $name ] ) : bool
final public __construct ( string $template_dir [, array $options ] )
public display ( string $tpl [, array $tpl_vars ] ) : bool
public eval ( string $tpl_content [, array $tpl_vars ] ) : string
public __get ([ string $name ] ) : void
public getScriptPath ( void ) : string
public __isset ( string $name ) : void
public render ( string $tpl [, array $tpl_vars ] ) : string
public __set ( string $name , mixed $value ) : void
public setScriptPath ( string $template_dir ) : bool
}

Properties

_tpl_vars

_tpl_dir

Table of Contents

  • Yaf_View_Simple::assign — Assign values
  • Yaf_View_Simple::assignRef — The assignRef purpose
  • Yaf_View_Simple::clear — Clear Assigned values
  • Yaf_View_Simple::__construct — Constructor of Yaf_View_Simple
  • Yaf_View_Simple::display — Render and display
  • Yaf_View_Simple::eval — Render template
  • Yaf_View_Simple::__get — Retrieve assigned variable
  • Yaf_View_Simple::getScriptPath — Get templates directory
  • Yaf_View_Simple::__isset — The __isset purpose
  • Yaf_View_Simple::render — Render template
  • Yaf_View_Simple::__set — Set value to engine
  • Yaf_View_Simple::setScriptPath — Set tempaltes directory


Assign values

  • « Yaf_View_Simple
  • Yaf_View_Simple::assignRef »
  • PHP Manual
  • Yaf_View_Simple
  • Assign values

Yaf_View_Simple::assign

(Yaf >=1.0.0)

Yaf_View_Simple::assign — Assign values

Description

public Yaf_View_Simple::assign ( string $name [, mixed $value ] ) : bool

assign variable to view engine

Parameters

name

A string or an array.

if is string, then the next argument $value is required.

value

mixed value

Return Values

Examples

Example #1 Yaf_View_Simple::assign()example

<?php
class IndexController extends Yaf_Controller_Abstract {
    public function indexAction() {
        $this->getView()->assign("foo", "bar");
        $this->_view->assign( array( "key" => "value", "name" => "value"));
    }
?>

Example #2 template()example

<html>
 <head>
  <title><?php echo $foo; ?></title>
 </head>
<body>
  <?php
    foreach ($this->_tpl_vars as $name => value) {
         echo $$name; // or echo $this->_tpl_vars[$name];
    }
  ?>
</body>
</html>

See Also

  • Yaf_View_Simple::assignRef() - The assignRef purpose
  • Yaf_View_Interface::clear()
  • Yaf_View_Simple::__set() - Set value to engine


The assignRef purpose

  • « Yaf_View_Simple::assign
  • Yaf_View_Simple::clear »
  • PHP Manual
  • Yaf_View_Simple
  • The assignRef purpose

Yaf_View_Simple::assignRef

(Yaf >=1.0.0)

Yaf_View_Simple::assignRef — The assignRef purpose

Description

public Yaf_View_Simple::assignRef ( string $name , mixed &$value ) : bool

unlike Yaf_View_Simple::assign(), this method assign a ref value to engine.

Parameters

name

A string name which will be used to access the value in the tempalte.

value

mixed value

Return Values

Examples

Example #1 Yaf_View_Simple::assignRef()example

<?php
class IndexController extends Yaf_Controller_Abstract {
    public function indexAction() {
        $value = "bar";
        $this->getView()->assign("foo", $value);

        /* plz note that there was a bug before Yaf 2.1.4,
         * which make following output "bar";
         */
        $dummy = $this->getView()->render("index/index.phtml");
        echo $value;

        //prevent the auto-render
        Yaf_Dispatcher::getInstance()->autoRender(FALSE);
    }
?>

Example #2 template()example

<html>
 <head>
  <title><?php echo $foo;  $foo = "changed"; ?></title>
 </head>
<body>
</body>
</html>

The above example will output something similar to:

/* access the index controller will result: */
changed

See Also

  • Yaf_View_Simple::assign() - Assign values
  • Yaf_View_Simple::__set() - Set value to engine


Clear Assigned values

  • « Yaf_View_Simple::assignRef
  • Yaf_View_Simple::__construct »
  • PHP Manual
  • Yaf_View_Simple
  • Clear Assigned values

Yaf_View_Simple::clear

(Yaf >=2.2.0)

Yaf_View_Simple::clear — Clear Assigned values

Description

public Yaf_View_Simple::clear ([ string $name ] ) : bool

clear assigned variable

Parameters

name

assigned variable name

if empty, will clear all assigned variables

Return Values

Examples

Example #1 Yaf_View_Simple::clear()example

<?php
class IndexController extends Yaf_Controller_Abstract {
    public function indexAction() {
        $this->getView()->clear("foo")->clear("bar"); // clear "foo" and "bar"
        $this->_view->clear(); //clear all assigned variables
    }
?>

See Also

  • Yaf_View_Simple::assignRef() - The assignRef purpose
  • Yaf_View_Interface::assign() - Assign value to View engine
  • Yaf_View_Simple::__set() - Set value to engine


Constructor of Yaf_View_Simple

  • « Yaf_View_Simple::clear
  • Yaf_View_Simple::display »
  • PHP Manual
  • Yaf_View_Simple
  • Constructor of Yaf_View_Simple

Yaf_View_Simple::__construct

(Yaf >=1.0.0)

Yaf_View_Simple::__construct — Constructor of Yaf_View_Simple

Description

final public Yaf_View_Simple::__construct ( string $template_dir [, array $options ] )

Parameters

template_dir

The base directory of the templates, by default, it is APPLICATOIN . "/views" for Yaf.

options

Options for the engine, as of Yaf 2.1.13, you can use short tag
      "<?=$var?>" in your template(regardless of "short_open_tag"),
      so comes a option named "short_tag",  you can switch this off
      to prevent use short_tag in template.

Examples

Example #1 Yaf_View_Simple::__constructor()example

<?php
   define ("TEMPLATE_DIRECTORY", APPLICATOIN_PATH . '/views');
   $view = new Yaf_View_Simple(TEMPLATE_DIRECTORY, array(
                           'short_tag' => false //doesn't allow use short tag in template
   ));
?>

Return Values


Render and display

  • « Yaf_View_Simple::__construct
  • Yaf_View_Simple::eval »
  • PHP Manual
  • Yaf_View_Simple
  • Render and display

Yaf_View_Simple::display

(Yaf >=1.0.0)

Yaf_View_Simple::display — Render and display

Description

public Yaf_View_Simple::display ( string $tpl [, array $tpl_vars ] ) : bool

Render a template and display the result instantly.

Parameters

tpl

tpl_vars

Return Values


Render template

  • « Yaf_View_Simple::display
  • Yaf_View_Simple::__get »
  • PHP Manual
  • Yaf_View_Simple
  • Render template

Yaf_View_Simple::eval

(Yaf >=2.2.0)

Yaf_View_Simple::eval — Render template

Description

public Yaf_View_Simple::eval ( string $tpl_content [, array $tpl_vars ] ) : string

Render a string tempalte and return the result.

Parameters

tpl_content

string template

tpl_vars

Return Values


Retrieve assigned variable

  • « Yaf_View_Simple::eval
  • Yaf_View_Simple::getScriptPath »
  • PHP Manual
  • Yaf_View_Simple
  • Retrieve assigned variable

Yaf_View_Simple::__get

(Yaf >=1.0.0)

Yaf_View_Simple::__get — Retrieve assigned variable

Description

public Yaf_View_Simple::__get ([ string $name ] ) : void

Retrieve assigned varaiable

Note:

parameter can be empty since 2.1.11

Parameters

name

the assigned variable name

if this is empty, all assigned variables will be returned

Return Values


Get templates directory

  • « Yaf_View_Simple::__get
  • Yaf_View_Simple::__isset »
  • PHP Manual
  • Yaf_View_Simple
  • Get templates directory

Yaf_View_Simple::getScriptPath

(Yaf >=1.0.0)

Yaf_View_Simple::getScriptPath — Get templates directory

Description

public Yaf_View_Simple::getScriptPath ( void ) : string

Parameters

This function has no parameters.

Return Values


The __isset purpose

  • « Yaf_View_Simple::getScriptPath
  • Yaf_View_Simple::render »
  • PHP Manual
  • Yaf_View_Simple
  • The __isset purpose

Yaf_View_Simple::__isset

(Yaf >=1.0.0)

Yaf_View_Simple::__isset — The __isset purpose

Description

public Yaf_View_Simple::__isset ( string $name ) : void

Parameters

name

Return Values


Render template

  • « Yaf_View_Simple::__isset
  • Yaf_View_Simple::__set »
  • PHP Manual
  • Yaf_View_Simple
  • Render template

Yaf_View_Simple::render

(Yaf >=1.0.0)

Yaf_View_Simple::render — Render template

Description

public Yaf_View_Simple::render ( string $tpl [, array $tpl_vars ] ) : string

Render a template and return the result.

Parameters

tpl

tpl_vars

Return Values


Set value to engine

  • « Yaf_View_Simple::render
  • Yaf_View_Simple::setScriptPath »
  • PHP Manual
  • Yaf_View_Simple
  • Set value to engine

Yaf_View_Simple::__set

(Yaf >=1.0.0)

Yaf_View_Simple::__set — Set value to engine

Description

public Yaf_View_Simple::__set ( string $name , mixed $value ) : void

This is a alternative and easier way to Yaf_View_Simple::assign().

Parameters

name

A string value name.

value

Mixed value.

Return Values

Examples

Example #1 Yaf_View_Simple::__set()example

<?php
class IndexController extends Yaf_Controller_Abstract {
    public function indexAction() {
        $this->getView()->foo = "bar"; // same as assign("foo", "bar");
    }
?>

See Also

  • Yaf_View_Simple::assignRef() - The assignRef purpose
  • Yaf_View_Interface::assign() - Assign value to View engine


Set tempaltes directory

  • « Yaf_View_Simple::__set
  • Yaf_Loader »
  • PHP Manual
  • Yaf_View_Simple
  • Set tempaltes directory

Yaf_View_Simple::setScriptPath

(Yaf >=1.0.0)

Yaf_View_Simple::setScriptPath — Set tempaltes directory

Description

public Yaf_View_Simple::setScriptPath ( string $template_dir ) : bool

Parameters

template_dir

Return Values


The Yaf_Loader class

(Yaf >=1.0.0)

Introduction

Yaf_Loader introduces a comprehensive autoloading solution for Yaf.

The first time an instance of Yaf_Application is retrieved, Yaf_Loader will instance a singleton, and registers itself with spl_autoload. You retrieve an instance using the Yaf_Loader::getInstance()

Yaf_Loader attempt to load a class only one shot, if failed, depend on yaf.use_spl_auload, if this config is On Yaf_Loader::autoload() will return FALSE, thus give the chance to other autoload function. if it is Off (by default), Yaf_Loader::autoload() will return TRUE, and more important is that a very useful warning will be triggered (very useful to find out why a class could not be loaded).

Note:

Please keep yaf.use_spl_autoload Off unless there is some library have their own autoload mechanism and impossible to rewrite it.

By default, Yaf_Loader assume all library (class defined script) store in the global library directory, which is defined in the php.ini(yaf.library).

If you want Yaf_Loader search some classes(libraries) in the local class directory(which is defined in application.ini, and by default, it is application.directory . "/library"), you should register the class prefix using the Yaf_Loader::registerLocalNameSpace()

Let's see some examples(assuming APPLICATION_PATH is application.directory):

Example #1 Config example

// Assuming the following configure in php.ini:
yaf.library = "/global_dir"

//Assuming the following configure in application.ini
application.library = APPLICATION_PATH "/library"
Assuming the following local name space is registered:

Example #2 Register localnamespace

<?php
class Bootstrap extends Yaf_Bootstrap_Abstract{
     public function _initLoader($dispatcher) {
          Yaf_Loader::getInstance()->registerLocalNameSpace(array("Foo", "Bar"));
     }
?>
Then the autoload examples:

Example #3 Load class example

class Foo_Bar_Test =>
  // APPLICATION_PATH/library/Foo/Bar/Test.php

class GLO_Name  =>
  // /global_dir/Glo/Name.php

class BarNon_Test
  // /global_dir/Barnon/Test.php
As of PHP 5.3, you can use namespace:

Example #4 Load namespace class example

class \Foo\Bar\Dummy =>
   // APPLICATION_PATH/library/Foo/Bar/Dummy.php

class \FooBar\Bar\Dummy =>
   // /global_dir/FooBar/Bar/Dummy.php

You may noticed that all the folder with the first letter capitalized, you can make them lowercase by set yaf.lowcase_path = On in php.ini

Yaf_Loader is also designed to load the MVC classes, and the rule is:

Example #5 MVC class loading example

Controller Classes =>
// APPLICATION_PATH/controllers/

Model Classes =>
// APPLICATION_PATH/models/

Plugin Classes =>
// APPLICATION_PATH/plugins/
Yaf identify a class's suffix(this is by default, you can also change to the prefix by change the configure yaf.name_suffix) to decide whether it is a MVC class:

Example #6 MVC class distinctions

Controller Classes =>
    // ***Controller

Model Classes =>
    // ***Model

Plugin Classes =>
    // ***Plugin
some examples:

Example #7 MVC loading example

class IndexController
    // APPLICATION_PATH/controllers/Index.php

class DataModel =>
   // APPLICATION_PATH/models/Data.php

class DummyPlugin =>
  // APPLICATION_PATH/plugins/Dummy.php

class A_B_TestModel =>
  // APPLICATION_PATH/models/A/B/Test.php

Note:

As of 2.1.18, Yaf supports Controllers autoloading for user script side, (which means the autoloading triggered by user php script, eg: access a controller static property in Bootstrap or Plugins), but autoloader only try to locate controller class script under the default module folder, which is "APPLICATION_PATH/controllers/".

also, the directory will be affected by yaf.lowcase_path.

Class synopsis

Yaf_Loader {
/* Properties */
protected $_local_ns ;
protected $_library ;
protected $_global_library ;
static $_instance ;
/* Methods */
public autoload ( void ) : void
public clearLocalNamespace ( void ) : void
private __clone ( void ) : void
private __construct ( void )
public static getInstance ( void ) : void
public getLibraryPath ([ bool $is_global = FALSE ] ) : Yaf_Loader
public getLocalNamespace ( void ) : void
public static import ( void ) : void
public isLocalName ( void ) : void
public registerLocalNamespace ( mixed $prefix ) : void
public setLibraryPath ( string $directory [, bool $is_global = FALSE ] ) : Yaf_Loader
private __sleep ( void ) : void
private __wakeup ( void ) : void
}

Properties

_local_ns

_library

By default, this value is application.directory . "/library", you can change this either in the application.ini(application.library) or call to Yaf_Loader::setLibraryPath()

_global_library

_instance

Table of Contents

  • Yaf_Loader::autoload — The autoload purpose
  • Yaf_Loader::clearLocalNamespace — The clearLocalNamespace purpose
  • Yaf_Loader::__clone — The __clone purpose
  • Yaf_Loader::__construct — The __construct purpose
  • Yaf_Loader::getInstance — The getInstance purpose
  • Yaf_Loader::getLibraryPath — Get the library path
  • Yaf_Loader::getLocalNamespace — The getLocalNamespace purpose
  • Yaf_Loader::import — The import purpose
  • Yaf_Loader::isLocalName — The isLocalName purpose
  • Yaf_Loader::registerLocalNamespace — Register local class prefix
  • Yaf_Loader::setLibraryPath — Change the library path
  • Yaf_Loader::__sleep — The __sleep purpose
  • Yaf_Loader::__wakeup — The __wakeup purpose


The autoload purpose

  • « Yaf_Loader
  • Yaf_Loader::clearLocalNamespace »
  • PHP Manual
  • Yaf_Loader
  • The autoload purpose

Yaf_Loader::autoload

(Yaf >=1.0.0)

Yaf_Loader::autoload — The autoload purpose

Description

public Yaf_Loader::autoload ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The clearLocalNamespace purpose

  • « Yaf_Loader::autoload
  • Yaf_Loader::__clone »
  • PHP Manual
  • Yaf_Loader
  • The clearLocalNamespace purpose

Yaf_Loader::clearLocalNamespace

(Yaf >=1.0.0)

Yaf_Loader::clearLocalNamespace — The clearLocalNamespace purpose

Description

public Yaf_Loader::clearLocalNamespace ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The __clone purpose

  • « Yaf_Loader::clearLocalNamespace
  • Yaf_Loader::__construct »
  • PHP Manual
  • Yaf_Loader
  • The __clone purpose

Yaf_Loader::__clone

(Yaf >=1.0.0)

Yaf_Loader::__clone — The __clone purpose

Description

private Yaf_Loader::__clone ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The __construct purpose

  • « Yaf_Loader::__clone
  • Yaf_Loader::getInstance »
  • PHP Manual
  • Yaf_Loader
  • The __construct purpose

Yaf_Loader::__construct

(Yaf >=1.0.0)

Yaf_Loader::__construct — The __construct purpose

Description

private Yaf_Loader::__construct ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The getInstance purpose

  • « Yaf_Loader::__construct
  • Yaf_Loader::getLibraryPath »
  • PHP Manual
  • Yaf_Loader
  • The getInstance purpose

Yaf_Loader::getInstance

(Yaf >=1.0.0)

Yaf_Loader::getInstance — The getInstance purpose

Description

public static Yaf_Loader::getInstance ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Get the library path

  • « Yaf_Loader::getInstance
  • Yaf_Loader::getLocalNamespace »
  • PHP Manual
  • Yaf_Loader
  • Get the library path

Yaf_Loader::getLibraryPath

(Yaf >=2.1.4)

Yaf_Loader::getLibraryPath — Get the library path

Description

public Yaf_Loader::getLibraryPath ([ bool $is_global = FALSE ] ) : Yaf_Loader

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The getLocalNamespace purpose

  • « Yaf_Loader::getLibraryPath
  • Yaf_Loader::import »
  • PHP Manual
  • Yaf_Loader
  • The getLocalNamespace purpose

Yaf_Loader::getLocalNamespace

(Yaf >=1.0.0)

Yaf_Loader::getLocalNamespace — The getLocalNamespace purpose

Description

public Yaf_Loader::getLocalNamespace ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The import purpose

  • « Yaf_Loader::getLocalNamespace
  • Yaf_Loader::isLocalName »
  • PHP Manual
  • Yaf_Loader
  • The import purpose

Yaf_Loader::import

(Yaf >=1.0.0)

Yaf_Loader::import — The import purpose

Description

public static Yaf_Loader::import ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The isLocalName purpose

  • « Yaf_Loader::import
  • Yaf_Loader::registerLocalNamespace »
  • PHP Manual
  • Yaf_Loader
  • The isLocalName purpose

Yaf_Loader::isLocalName

(Yaf >=1.0.0)

Yaf_Loader::isLocalName — The isLocalName purpose

Description

public Yaf_Loader::isLocalName ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Register local class prefix

  • « Yaf_Loader::isLocalName
  • Yaf_Loader::setLibraryPath »
  • PHP Manual
  • Yaf_Loader
  • Register local class prefix

Yaf_Loader::registerLocalNamespace

(Yaf >=1.0.0)

Yaf_Loader::registerLocalNamespace — Register local class prefix

Description

public Yaf_Loader::registerLocalNamespace ( mixed $prefix ) : void

Register local class prefix name, Yaf_Loader search classes in two library directories, the one is configured via application.library.directory(in application.ini) which is called local libraray directory; the other is configured via yaf.library (in php.ini) which is callled global library directory, since it can be shared by many applications in the same server.

When an autloading is trigger, Yaf_Loader will determine which library directory should be searched in by exame the prefix name of the missed classname. If the prefix name is registered as a localnamespack then look for it in local library directory, otherwise look for it in global library directory.

Note:

If yaf.library is not configured, then the global library directory is assumed to be the local library directory. in that case, all autoloading will look for local library directory. But if you want your Yaf application be strong, then always register your own classes as local classes.

Parameters

prefix

a string or a array of class name prefix. all class prefix with these prefix will be loaded in local library path.

Return Values

bool

Examples

Example #1 Yaf_Loader::registerLocalNamespace()example

<?php
$loader = Yaf_Loader::getInstance('/local/library/', '/global/library');
$loader->registerLocalNamespace("Baidu");
$loader->registerLocalNamespace(array("Sina", "Weibo"));

$loader->autoload("Baidu_Name"); // search in '/local/library/'
$loader->autoload("Sina");       // search '/local/library/'
$loader->autoload("Global_Name");// search in '/global/library/'
$loader->autoload("Foo_Bar");    // search in '/global/library/'

?>


Change the library path

  • « Yaf_Loader::registerLocalNamespace
  • Yaf_Loader::__sleep »
  • PHP Manual
  • Yaf_Loader
  • Change the library path

Yaf_Loader::setLibraryPath

(Yaf >=2.1.4)

Yaf_Loader::setLibraryPath — Change the library path

Description

public Yaf_Loader::setLibraryPath ( string $directory [, bool $is_global = FALSE ] ) : Yaf_Loader

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The __sleep purpose

  • « Yaf_Loader::setLibraryPath
  • Yaf_Loader::__wakeup »
  • PHP Manual
  • Yaf_Loader
  • The __sleep purpose

Yaf_Loader::__sleep

(Yaf >=1.0.0)

Yaf_Loader::__sleep — The __sleep purpose

Description

private Yaf_Loader::__sleep ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The __wakeup purpose

  • « Yaf_Loader::__sleep
  • Yaf_Plugin_Abstract »
  • PHP Manual
  • Yaf_Loader
  • The __wakeup purpose

Yaf_Loader::__wakeup

(Yaf >=1.0.0)

Yaf_Loader::__wakeup — The __wakeup purpose

Description

private Yaf_Loader::__wakeup ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The Yaf_Plugin_Abstract class

(Yaf >=1.0.0)

Introduction

Plugins allow for easy extensibility and customization of the framework.

Plugins are classes. The actual class definition will vary based on the component -- you may need to implement this interface, but the fact remains that the plugin is itself a class.

A plugin could be loaded into Yaf by using Yaf_Dispatcher::registerPlugin(), after registering, All the methods which the plugin implemented according to this interface, will be called at the proper time.

Examples

Example #1 Plugin example

<?php
   /* bootstrap class should be defined under ./application/Bootstrap.php */
   class Bootstrap extends Yaf_Bootstrap_Abstract {
        public function _initPlugin(Yaf_Dispatcher $dispatcher) {
            /* register a plugin */
            $dispatcher->registerPlugin(new TestPlugin());
        }
   }

   /* plugin class should be placed under ./application/plugins/ */
   class TestPlugin extends Yaf_Plugin_Abstract {
        public function routerStartup(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
            /* before router
               in this hook,  user can do some url rewrite */
            var_dump("routerStartup");
        }
        public function routerShutdown(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
            /* router complete
               in this hook, user can do login check */
            var_dump("routerShutdown");
        }
        public function dispatchLoopStartup(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
            var_dump("dispatchLoopStartup");
        }
        public function preDispatch(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
            var_dump("preDispatch");
        }
        public function postDispatch(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
            var_dump("postDispatch");
        }
        public function dispatchLoopShutdown(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
            /* final hook
               in this hook user can do logging or implement layout */
            var_dump("dispatchLoopShutdown");
        }
   }

   Class IndexController extends Yaf_Controller_Abstract {
        public function indexAction() {
            return FALSE; //prevent rendering
        }
   }

   $config = array(
       "application" => array(
           "directory" => dirname(__FILE__) . "/application/",
       ),
   );

   $app = new Yaf_Application($config);
   $app->bootstrap()->run();
?>

The above example will output something similar to:

string(13) "routerStartup"
string(14) "routerShutdown"
string(19) "dispatchLoopStartup"
string(11) "preDispatch"
string(12) "postDispatch"
string(20) "dispatchLoopShutdown"

Class synopsis

Yaf_Plugin_Abstract {
/* Methods */
public dispatchLoopShutdown ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response ) : void
public dispatchLoopStartup ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response ) : void
public postDispatch ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response ) : void
public preDispatch ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response ) : void
public preResponse ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response ) : void
public routerShutdown ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response ) : void
public routerStartup ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response ) : void
}

Table of Contents

  • Yaf_Plugin_Abstract::dispatchLoopShutdown — The dispatchLoopShutdown purpose
  • Yaf_Plugin_Abstract::dispatchLoopStartup — Hook before dispatch loop
  • Yaf_Plugin_Abstract::postDispatch — The postDispatch purpose
  • Yaf_Plugin_Abstract::preDispatch — The preDispatch purpose
  • Yaf_Plugin_Abstract::preResponse — The preResponse purpose
  • Yaf_Plugin_Abstract::routerShutdown — The routerShutdown purpose
  • Yaf_Plugin_Abstract::routerStartup — RouterStartup hook


The dispatchLoopShutdown purpose

  • « Yaf_Plugin_Abstract
  • Yaf_Plugin_Abstract::dispatchLoopStartup »
  • PHP Manual
  • Yaf_Plugin_Abstract
  • The dispatchLoopShutdown purpose

Yaf_Plugin_Abstract::dispatchLoopShutdown

(Yaf >=1.0.0)

Yaf_Plugin_Abstract::dispatchLoopShutdown — The dispatchLoopShutdown purpose

Description

public Yaf_Plugin_Abstract::dispatchLoopShutdown ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response ) : void

This is the latest hook in Yaf plugin hook system, if a custom plugin implement this method, then it will be called after the dispatch loop finished.

Warning

This function is currently not documented; only its argument list is available.

Parameters

request

response

Return Values

See Also

  • Yaf_Plugin_Abstract::routerStartup() - RouterStartup hook
  • Yaf_Plugin_Abstract::routerShutdown() - The routerShutdown purpose
  • Yaf_Plugin_Abstract::dispatchLoopStartup() - Hook before dispatch loop
  • Yaf_Plugin_Abstract::preDispatch() - The preDispatch purpose
  • Yaf_Plugin_Abstract::postDispatch() - The postDispatch purpose


Hook before dispatch loop

  • « Yaf_Plugin_Abstract::dispatchLoopShutdown
  • Yaf_Plugin_Abstract::postDispatch »
  • PHP Manual
  • Yaf_Plugin_Abstract
  • Hook before dispatch loop

Yaf_Plugin_Abstract::dispatchLoopStartup

(Yaf >=1.0.0)

Yaf_Plugin_Abstract::dispatchLoopStartup — Hook before dispatch loop

Description

public Yaf_Plugin_Abstract::dispatchLoopStartup ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response ) : void

Parameters

request

response

Return Values


The postDispatch purpose

  • « Yaf_Plugin_Abstract::dispatchLoopStartup
  • Yaf_Plugin_Abstract::preDispatch »
  • PHP Manual
  • Yaf_Plugin_Abstract
  • The postDispatch purpose

Yaf_Plugin_Abstract::postDispatch

(Yaf >=1.0.0)

Yaf_Plugin_Abstract::postDispatch — The postDispatch purpose

Description

public Yaf_Plugin_Abstract::postDispatch ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

request

response

Return Values


The preDispatch purpose

  • « Yaf_Plugin_Abstract::postDispatch
  • Yaf_Plugin_Abstract::preResponse »
  • PHP Manual
  • Yaf_Plugin_Abstract
  • The preDispatch purpose

Yaf_Plugin_Abstract::preDispatch

(Yaf >=1.0.0)

Yaf_Plugin_Abstract::preDispatch — The preDispatch purpose

Description

public Yaf_Plugin_Abstract::preDispatch ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

request

response

Return Values


The preResponse purpose

  • « Yaf_Plugin_Abstract::preDispatch
  • Yaf_Plugin_Abstract::routerShutdown »
  • PHP Manual
  • Yaf_Plugin_Abstract
  • The preResponse purpose

Yaf_Plugin_Abstract::preResponse

(Yaf >=1.0.0)

Yaf_Plugin_Abstract::preResponse — The preResponse purpose

Description

public Yaf_Plugin_Abstract::preResponse ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

request

response

Return Values


The routerShutdown purpose

  • « Yaf_Plugin_Abstract::preResponse
  • Yaf_Plugin_Abstract::routerStartup »
  • PHP Manual
  • Yaf_Plugin_Abstract
  • The routerShutdown purpose

Yaf_Plugin_Abstract::routerShutdown

(Yaf >=1.0.0)

Yaf_Plugin_Abstract::routerShutdown — The routerShutdown purpose

Description

public Yaf_Plugin_Abstract::routerShutdown ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response ) : void

This hook will be trigged after the route process finished, this hook is usually used for login check.

Warning

This function is currently not documented; only its argument list is available.

Parameters

request

response

Return Values

Examples

Example #1 Yaf_Plugin_Abstract::routerShutdown()example

<?php
class UserInitPlugin extends Yaf_Plugin_Abstract {

    public function routerShutdown(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
        $controller = $request->getControllerName();

        /**
         * Use access controller is unecessary for APIs
         */
        if (in_array(strtolower($controller), array(
            'api',
        ))) {
            return TRUE;
        }

        if (Yaf_Session::getInstance()->has("login")) {
            return TRUE;
        }

        /* Use access check failed, need to login */
        $response->redirect("http://yourdomain.com/login/");
        return FALSE;
    }
?>

See Also

  • Yaf_Plugin_Abstract::routerStartup() - RouterStartup hook
  • Yaf_Plugin_Abstract::dispatchLoopStartup() - Hook before dispatch loop
  • Yaf_Plugin_Abstract::preDispatch() - The preDispatch purpose
  • Yaf_Plugin_Abstract::postDispatch() - The postDispatch purpose
  • Yaf_Plugin_Abstract::dispatchLoopShutdown() - The dispatchLoopShutdown purpose


RouterStartup hook

  • « Yaf_Plugin_Abstract::routerShutdown
  • Yaf_Registry »
  • PHP Manual
  • Yaf_Plugin_Abstract
  • RouterStartup hook

Yaf_Plugin_Abstract::routerStartup

(Yaf >=1.0.0)

Yaf_Plugin_Abstract::routerStartup — RouterStartup hook

Description

public Yaf_Plugin_Abstract::routerStartup ( Yaf_Request_Abstract $request , Yaf_Response_Abstract $response ) : void

This is the earliest hook in Yaf plugin hook system, if a custom plugin implement this method, then it will be called before routing a request.

Warning

This function is currently not documented; only its argument list is available.

Parameters

request

response

Return Values

See Also

  • Yaf_Plugin_Abstract::routerShutdown() - The routerShutdown purpose
  • Yaf_Plugin_Abstract::dispatchLoopStartup() - Hook before dispatch loop
  • Yaf_Plugin_Abstract::preDispatch() - The preDispatch purpose
  • Yaf_Plugin_Abstract::postDispatch() - The postDispatch purpose
  • Yaf_Plugin_Abstract::dispatchLoopShutdown() - The dispatchLoopShutdown purpose


The Yaf_Registry class

(Yaf >=1.0.0)

Introduction

All methods of Yaf_Registry declared as static, making it unversally accessible. This provides the ability to get or set any custom data from anyway in your code as necessary.

Class synopsis

Yaf_Registry {
/* Properties */
static $_instance ;
protected $_entries ;
/* Methods */
private __clone ( void ) : void
private __construct ( void )
public static del ( string $name ) : void
public static get ( string $name ) : mixed
public static has ( string $name ) : bool
public static set ( string $name , string $value ) : bool
}

Properties

_instance

_entries

Table of Contents

  • Yaf_Registry::__clone — The __clone purpose
  • Yaf_Registry::__construct — Yaf_Registry implements singleton
  • Yaf_Registry::del — Remove an item from registry
  • Yaf_Registry::get — Retrieve an item from registry
  • Yaf_Registry::has — Check whether an item exists
  • Yaf_Registry::set — Add an item into registry


The __clone purpose

  • « Yaf_Registry
  • Yaf_Registry::__construct »
  • PHP Manual
  • Yaf_Registry
  • The __clone purpose

Yaf_Registry::__clone

(Yaf >=1.0.0)

Yaf_Registry::__clone — The __clone purpose

Description

private Yaf_Registry::__clone ( void ) : void

Parameters

This function has no parameters.

Return Values


Yaf_Registry implements singleton

  • « Yaf_Registry::__clone
  • Yaf_Registry::del »
  • PHP Manual
  • Yaf_Registry
  • Yaf_Registry implements singleton

Yaf_Registry::__construct

(Yaf >=1.0.0)

Yaf_Registry::__construct — Yaf_Registry implements singleton

Description

private Yaf_Registry::__construct ( void )

Parameters

This function has no parameters.

Return Values


Remove an item from registry

  • « Yaf_Registry::__construct
  • Yaf_Registry::get »
  • PHP Manual
  • Yaf_Registry
  • Remove an item from registry

Yaf_Registry::del

(Yaf >=1.0.0)

Yaf_Registry::del — Remove an item from registry

Description

public static Yaf_Registry::del ( string $name ) : void

Remove an item from registry

Parameters

name

Return Values


Retrieve an item from registry

  • « Yaf_Registry::del
  • Yaf_Registry::has »
  • PHP Manual
  • Yaf_Registry
  • Retrieve an item from registry

Yaf_Registry::get

(Yaf >=1.0.0)

Yaf_Registry::get — Retrieve an item from registry

Description

public static Yaf_Registry::get ( string $name ) : mixed

Retrieve an item from registry

Parameters

name

Return Values


Check whether an item exists

  • « Yaf_Registry::get
  • Yaf_Registry::set »
  • PHP Manual
  • Yaf_Registry
  • Check whether an item exists

Yaf_Registry::has

(Yaf >=1.0.0)

Yaf_Registry::has — Check whether an item exists

Description

public static Yaf_Registry::has ( string $name ) : bool

Check whether an item exists

Parameters

name

Return Values


Add an item into registry

  • « Yaf_Registry::has
  • Yaf_Request_Abstract »
  • PHP Manual
  • Yaf_Registry
  • Add an item into registry

Yaf_Registry::set

(Yaf >=1.0.0)

Yaf_Registry::set — Add an item into registry

Description

public static Yaf_Registry::set ( string $name , string $value ) : bool

Add an item into registry

Parameters

name

value

Return Values


The Yaf_Request_Abstract class

(Yaf >=1.0.0)

Introduction

Class synopsis

Yaf_Request_Abstract {
/* Constants */
const string SCHEME_HTTP = http ;
const string SCHEME_HTTPS = https ;
/* Properties */
public $module ;
public $controller ;
public $action ;
public $method ;
protected $params ;
protected $language ;
protected $_exception ;
protected $_base_uri ;
protected $uri ;
protected $dispatched ;
protected $routed ;
/* Methods */
public getActionName ( void ) : void
public getBaseUri ( void ) : void
public getControllerName ( void ) : void
public getEnv ( string $name [, string $default ] ) : void
public getException ( void ) : void
public getLanguage ( void ) : void
public getMethod ( void ) : string
public getModuleName ( void ) : void
public getParam ( string $name [, string $default ] ) : mixed
public getParams ( void ) : array
public getRequestUri ( void ) : void
public getServer ( string $name [, string $default ] ) : void
public isCli ( void ) : bool
public isDispatched ( void ) : bool
public isGet ( void ) : bool
public isHead ( void ) : bool
public isOptions ( void ) : bool
public isPost ( void ) : bool
public isPut ( void ) : bool
public isRouted ( void ) : bool
public isXmlHttpRequest ( void ) : bool
public setActionName ( string $action ) : void
public setBaseUri ( string $uir ) : bool
public setControllerName ( string $controller ) : void
public setDispatched ( void ) : void
public setModuleName ( string $module ) : void
public setParam ( string $name [, string $value ] ) : bool
public setRequestUri ( string $uir ) : void
public setRouted ([ string $flag ] ) : void
}

Properties

module

controller

action

method

params

language

_exception

_base_uri

uri

dispatched

routed

Predefined Constants

Yaf_Request_Abstract::SCHEME_HTTP

Yaf_Request_Abstract::SCHEME_HTTPS

Table of Contents

  • Yaf_Request_Abstract::getActionName — The getActionName purpose
  • Yaf_Request_Abstract::getBaseUri — The getBaseUri purpose
  • Yaf_Request_Abstract::getControllerName — The getControllerName purpose
  • Yaf_Request_Abstract::getEnv — Retrieve ENV varialbe
  • Yaf_Request_Abstract::getException — The getException purpose
  • Yaf_Request_Abstract::getLanguage — Retrieve client's prefered language
  • Yaf_Request_Abstract::getMethod — Retrieve the request method
  • Yaf_Request_Abstract::getModuleName — The getModuleName purpose
  • Yaf_Request_Abstract::getParam — Retrieve calling parameter
  • Yaf_Request_Abstract::getParams — Retrieve all calling parameters
  • Yaf_Request_Abstract::getRequestUri — The getRequestUri purpose
  • Yaf_Request_Abstract::getServer — Retrieve SERVER variable
  • Yaf_Request_Abstract::isCli — Determine if request is CLI request
  • Yaf_Request_Abstract::isDispatched — Determin if the request is dispatched
  • Yaf_Request_Abstract::isGet — Determine if request is GET request
  • Yaf_Request_Abstract::isHead — Determine if request is HEAD request
  • Yaf_Request_Abstract::isOptions — Determine if request is OPTIONS request
  • Yaf_Request_Abstract::isPost — Determine if request is POST request
  • Yaf_Request_Abstract::isPut — Determine if request is PUT request
  • Yaf_Request_Abstract::isRouted — Determin if request has been routed
  • Yaf_Request_Abstract::isXmlHttpRequest — Determine if request is AJAX request
  • Yaf_Request_Abstract::setActionName — The setActionName purpose
  • Yaf_Request_Abstract::setBaseUri — Set base URI
  • Yaf_Request_Abstract::setControllerName — The setControllerName purpose
  • Yaf_Request_Abstract::setDispatched — The setDispatched purpose
  • Yaf_Request_Abstract::setModuleName — The setModuleName purpose
  • Yaf_Request_Abstract::setParam — Set a calling parameter to a request
  • Yaf_Request_Abstract::setRequestUri — The setRequestUri purpose
  • Yaf_Request_Abstract::setRouted — The setRouted purpose


The getActionName purpose

  • « Yaf_Request_Abstract
  • Yaf_Request_Abstract::getBaseUri »
  • PHP Manual
  • Yaf_Request_Abstract
  • The getActionName purpose

Yaf_Request_Abstract::getActionName

(Yaf >=1.0.0)

Yaf_Request_Abstract::getActionName — The getActionName purpose

Description

public Yaf_Request_Abstract::getActionName ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The getBaseUri purpose

  • « Yaf_Request_Abstract::getActionName
  • Yaf_Request_Abstract::getControllerName »
  • PHP Manual
  • Yaf_Request_Abstract
  • The getBaseUri purpose

Yaf_Request_Abstract::getBaseUri

(Yaf >=1.0.0)

Yaf_Request_Abstract::getBaseUri — The getBaseUri purpose

Description

public Yaf_Request_Abstract::getBaseUri ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The getControllerName purpose

  • « Yaf_Request_Abstract::getBaseUri
  • Yaf_Request_Abstract::getEnv »
  • PHP Manual
  • Yaf_Request_Abstract
  • The getControllerName purpose

Yaf_Request_Abstract::getControllerName

(Yaf >=1.0.0)

Yaf_Request_Abstract::getControllerName — The getControllerName purpose

Description

public Yaf_Request_Abstract::getControllerName ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Retrieve ENV varialbe

  • « Yaf_Request_Abstract::getControllerName
  • Yaf_Request_Abstract::getException »
  • PHP Manual
  • Yaf_Request_Abstract
  • Retrieve ENV varialbe

Yaf_Request_Abstract::getEnv

(Yaf >=1.0.0)

Yaf_Request_Abstract::getEnv — Retrieve ENV varialbe

Description

public Yaf_Request_Abstract::getEnv ( string $name [, string $default ] ) : void

Retrieve ENV variable

Parameters

name

the variable name

default

if this parameter is provide, this will be returned if the varialbe can not be found

Return Values

Returns string

See Also

  • Yaf_Request_Abstract::getServer() - Retrieve SERVER variable
  • Yaf_Request_Abstract::getParam() - Retrieve calling parameter


The getException purpose

  • « Yaf_Request_Abstract::getEnv
  • Yaf_Request_Abstract::getLanguage »
  • PHP Manual
  • Yaf_Request_Abstract
  • The getException purpose

Yaf_Request_Abstract::getException

(Yaf >=1.0.0)

Yaf_Request_Abstract::getException — The getException purpose

Description

public Yaf_Request_Abstract::getException ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Retrieve client's prefered language

  • « Yaf_Request_Abstract::getException
  • Yaf_Request_Abstract::getMethod »
  • PHP Manual
  • Yaf_Request_Abstract
  • Retrieve client's prefered language

Yaf_Request_Abstract::getLanguage

(Yaf >=1.0.0)

Yaf_Request_Abstract::getLanguage — Retrieve client's prefered language

Description

public Yaf_Request_Abstract::getLanguage ( void ) : void

Parameters

This function has no parameters.

Return Values

Returns a string


Retrieve the request method

  • « Yaf_Request_Abstract::getLanguage
  • Yaf_Request_Abstract::getModuleName »
  • PHP Manual
  • Yaf_Request_Abstract
  • Retrieve the request method

Yaf_Request_Abstract::getMethod

(Yaf >=1.0.0)

Yaf_Request_Abstract::getMethod — Retrieve the request method

Description

public Yaf_Request_Abstract::getMethod ( void ) : string

Parameters

This function has no parameters.

Return Values

Return a string, like "POST", "GET" etc.

See Also

  • Yaf_Request_Abstract::isHead() - Determine if request is HEAD request
  • Yaf_Request_Abstract::isCli() - Determine if request is CLI request
  • Yaf_Request_Abstract::isPost() - Determine if request is POST request
  • Yaf_Request_Abstract::isPut() - Determine if request is PUT request
  • Yaf_Request_Abstract::isOptions() - Determine if request is OPTIONS request
  • Yaf_Request_Abstract::isXmlHTTPRequest() - Determine if request is AJAX request


The getModuleName purpose

  • « Yaf_Request_Abstract::getMethod
  • Yaf_Request_Abstract::getParam »
  • PHP Manual
  • Yaf_Request_Abstract
  • The getModuleName purpose

Yaf_Request_Abstract::getModuleName

(Yaf >=1.0.0)

Yaf_Request_Abstract::getModuleName — The getModuleName purpose

Description

public Yaf_Request_Abstract::getModuleName ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Retrieve calling parameter

  • « Yaf_Request_Abstract::getModuleName
  • Yaf_Request_Abstract::getParams »
  • PHP Manual
  • Yaf_Request_Abstract
  • Retrieve calling parameter

Yaf_Request_Abstract::getParam

(Yaf >=1.0.0)

Yaf_Request_Abstract::getParam — Retrieve calling parameter

Description

public Yaf_Request_Abstract::getParam ( string $name [, string $default ] ) : mixed

Parameters

name

default

Return Values

See Also

  • Yaf_Request_Abstract::setParam() - Set a calling parameter to a request


Retrieve all calling parameters

  • « Yaf_Request_Abstract::getParam
  • Yaf_Request_Abstract::getRequestUri »
  • PHP Manual
  • Yaf_Request_Abstract
  • Retrieve all calling parameters

Yaf_Request_Abstract::getParams

(Yaf >=1.0.0)

Yaf_Request_Abstract::getParams — Retrieve all calling parameters

Description

public Yaf_Request_Abstract::getParams ( void ) : array

Parameters

This function has no parameters.

Return Values

See Also

  • Yaf_Request_Abstract::setParam() - Set a calling parameter to a request


The getRequestUri purpose

  • « Yaf_Request_Abstract::getParams
  • Yaf_Request_Abstract::getServer »
  • PHP Manual
  • Yaf_Request_Abstract
  • The getRequestUri purpose

Yaf_Request_Abstract::getRequestUri

(Yaf >=1.0.0)

Yaf_Request_Abstract::getRequestUri — The getRequestUri purpose

Description

public Yaf_Request_Abstract::getRequestUri ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Retrieve SERVER variable

  • « Yaf_Request_Abstract::getRequestUri
  • Yaf_Request_Abstract::isCli »
  • PHP Manual
  • Yaf_Request_Abstract
  • Retrieve SERVER variable

Yaf_Request_Abstract::getServer

(Yaf >=1.0.0)

Yaf_Request_Abstract::getServer — Retrieve SERVER variable

Description

public Yaf_Request_Abstract::getServer ( string $name [, string $default ] ) : void

Retrieve SERVER variable

Parameters

name

the variable name

default

if this parameter is provide, this will be returned if the variable can not be found

Return Values

See Also

  • Yaf_Request_Abstract::getParam() - Retrieve calling parameter
  • Yaf_Request_Abstract::getEnv() - Retrieve ENV varialbe


Determine if request is CLI request

  • « Yaf_Request_Abstract::getServer
  • Yaf_Request_Abstract::isDispatched »
  • PHP Manual
  • Yaf_Request_Abstract
  • Determine if request is CLI request

Yaf_Request_Abstract::isCli

(Yaf >=1.0.0)

Yaf_Request_Abstract::isCli — Determine if request is CLI request

Description

public Yaf_Request_Abstract::isCli ( void ) : bool

Parameters

This function has no parameters.

Return Values

bolean

See Also

  • Yaf_Request_Abstract::isHead() - Determine if request is HEAD request
  • Yaf_Request_Abstract::isGet() - Determine if request is GET request
  • Yaf_Request_Abstract::isPost() - Determine if request is POST request
  • Yaf_Request_Abstract::isPut() - Determine if request is PUT request
  • Yaf_Request_Abstract::isOptions() - Determine if request is OPTIONS request
  • Yaf_Request_Abstract::isXmlHTTPRequest() - Determine if request is AJAX request


Determin if the request is dispatched

  • « Yaf_Request_Abstract::isCli
  • Yaf_Request_Abstract::isGet »
  • PHP Manual
  • Yaf_Request_Abstract
  • Determin if the request is dispatched

Yaf_Request_Abstract::isDispatched

(Yaf >=1.0.0)

Yaf_Request_Abstract::isDispatched — Determin if the request is dispatched

Description

public Yaf_Request_Abstract::isDispatched ( void ) : bool

Parameters

This function has no parameters.

Return Values

boolean

See Also

  • Yaf_Dispatcher::dispatch() - Dispatch a request


Determine if request is GET request

  • « Yaf_Request_Abstract::isDispatched
  • Yaf_Request_Abstract::isHead »
  • PHP Manual
  • Yaf_Request_Abstract
  • Determine if request is GET request

Yaf_Request_Abstract::isGet

(Yaf >=1.0.0)

Yaf_Request_Abstract::isGet — Determine if request is GET request

Description

public Yaf_Request_Abstract::isGet ( void ) : bool

Parameters

This function has no parameters.

Return Values

boolean

See Also

  • Yaf_Request_Abstract::isHead() - Determine if request is HEAD request
  • Yaf_Request_Abstract::isCli() - Determine if request is CLI request
  • Yaf_Request_Abstract::isPost() - Determine if request is POST request
  • Yaf_Request_Abstract::isPut() - Determine if request is PUT request
  • Yaf_Request_Abstract::isOptions() - Determine if request is OPTIONS request
  • Yaf_Request_Abstract::isXmlHTTPRequest() - Determine if request is AJAX request


Determine if request is HEAD request

  • « Yaf_Request_Abstract::isGet
  • Yaf_Request_Abstract::isOptions »
  • PHP Manual
  • Yaf_Request_Abstract
  • Determine if request is HEAD request

Yaf_Request_Abstract::isHead

(Yaf >=1.0.0)

Yaf_Request_Abstract::isHead — Determine if request is HEAD request

Description

public Yaf_Request_Abstract::isHead ( void ) : bool

Parameters

This function has no parameters.

Return Values

boolean

See Also

  • Yaf_Request_Abstract::isGet() - Determine if request is GET request
  • Yaf_Request_Abstract::isCli() - Determine if request is CLI request
  • Yaf_Request_Abstract::isPost() - Determine if request is POST request
  • Yaf_Request_Abstract::isPut() - Determine if request is PUT request
  • Yaf_Request_Abstract::isOptions() - Determine if request is OPTIONS request
  • Yaf_Request_Abstract::isXmlHTTPRequest() - Determine if request is AJAX request


Determine if request is OPTIONS request

  • « Yaf_Request_Abstract::isHead
  • Yaf_Request_Abstract::isPost »
  • PHP Manual
  • Yaf_Request_Abstract
  • Determine if request is OPTIONS request

Yaf_Request_Abstract::isOptions

(Yaf >=1.0.0)

Yaf_Request_Abstract::isOptions — Determine if request is OPTIONS request

Description

public Yaf_Request_Abstract::isOptions ( void ) : bool

Parameters

This function has no parameters.

Return Values

boolean


Determine if request is POST request

  • « Yaf_Request_Abstract::isOptions
  • Yaf_Request_Abstract::isPut »
  • PHP Manual
  • Yaf_Request_Abstract
  • Determine if request is POST request

Yaf_Request_Abstract::isPost

(Yaf >=1.0.0)

Yaf_Request_Abstract::isPost — Determine if request is POST request

Description

public Yaf_Request_Abstract::isPost ( void ) : bool

Parameters

This function has no parameters.

Return Values

boolean

See Also

  • Yaf_Request_Abstract::isGet() - Determine if request is GET request
  • Yaf_Request_Abstract::isCli() - Determine if request is CLI request
  • Yaf_Request_Abstract::isHead() - Determine if request is HEAD request
  • Yaf_Request_Abstract::isPut() - Determine if request is PUT request
  • Yaf_Request_Abstract::isOptions() - Determine if request is OPTIONS request
  • Yaf_Request_Abstract::isXmlHTTPRequest() - Determine if request is AJAX request


Determine if request is PUT request

  • « Yaf_Request_Abstract::isPost
  • Yaf_Request_Abstract::isRouted »
  • PHP Manual
  • Yaf_Request_Abstract
  • Determine if request is PUT request

Yaf_Request_Abstract::isPut

(Yaf >=1.0.0)

Yaf_Request_Abstract::isPut — Determine if request is PUT request

Description

public Yaf_Request_Abstract::isPut ( void ) : bool

Parameters

This function has no parameters.

Return Values

boolean

See Also

  • Yaf_Request_Abstract::isHead() - Determine if request is HEAD request
  • Yaf_Request_Abstract::isCli() - Determine if request is CLI request
  • Yaf_Request_Abstract::isPost() - Determine if request is POST request
  • Yaf_Request_Abstract::isGet() - Determine if request is GET request
  • Yaf_Request_Abstract::isOptions() - Determine if request is OPTIONS request
  • Yaf_Request_Abstract::isXmlHTTPRequest() - Determine if request is AJAX request


Determin if request has been routed

  • « Yaf_Request_Abstract::isPut
  • Yaf_Request_Abstract::isXmlHttpRequest »
  • PHP Manual
  • Yaf_Request_Abstract
  • Determin if request has been routed

Yaf_Request_Abstract::isRouted

(Yaf >=1.0.0)

Yaf_Request_Abstract::isRouted — Determin if request has been routed

Description

public Yaf_Request_Abstract::isRouted ( void ) : bool

Parameters

This function has no parameters.

Return Values

boolean


Determine if request is AJAX request

  • « Yaf_Request_Abstract::isRouted
  • Yaf_Request_Abstract::setActionName »
  • PHP Manual
  • Yaf_Request_Abstract
  • Determine if request is AJAX request

Yaf_Request_Abstract::isXmlHttpRequest

(Yaf >=1.0.0)

Yaf_Request_Abstract::isXmlHttpRequest — Determine if request is AJAX request

Description

public Yaf_Request_Abstract::isXmlHttpRequest ( void ) : bool

Parameters

This function has no parameters.

Return Values

boolean

See Also

  • Yaf_Request_Abstract::isHead() - Determine if request is HEAD request
  • Yaf_Request_Abstract::isCli() - Determine if request is CLI request
  • Yaf_Request_Abstract::isPost() - Determine if request is POST request
  • Yaf_Request_Abstract::isPut() - Determine if request is PUT request
  • Yaf_Request_Abstract::isOptions() - Determine if request is OPTIONS request
  • Yaf_Request_Abstract::isGet() - Determine if request is GET request


The setActionName purpose

  • « Yaf_Request_Abstract::isXmlHttpRequest
  • Yaf_Request_Abstract::setBaseUri »
  • PHP Manual
  • Yaf_Request_Abstract
  • The setActionName purpose

Yaf_Request_Abstract::setActionName

(Yaf >=1.0.0)

Yaf_Request_Abstract::setActionName — The setActionName purpose

Description

public Yaf_Request_Abstract::setActionName ( string $action ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

action

Return Values


Set base URI

  • « Yaf_Request_Abstract::setActionName
  • Yaf_Request_Abstract::setControllerName »
  • PHP Manual
  • Yaf_Request_Abstract
  • Set base URI

Yaf_Request_Abstract::setBaseUri

(Yaf >=1.0.0)

Yaf_Request_Abstract::setBaseUri — Set base URI

Description

public Yaf_Request_Abstract::setBaseUri ( string $uir ) : bool

Set base URI, base URI is used when doing routing, in routing phase request URI is used to route a request, while base URI is used to skip the leadding part(base URI) of request URI. That is, if comes a request with request URI a/b/c, then if you set base URI to "a/b", only "/c" will be used in routing phase.

Note:

generally, you don't need to set this, Yaf will determine it automatically.

Parameters

uir

base URI

Return Values

bool


The setControllerName purpose

  • « Yaf_Request_Abstract::setBaseUri
  • Yaf_Request_Abstract::setDispatched »
  • PHP Manual
  • Yaf_Request_Abstract
  • The setControllerName purpose

Yaf_Request_Abstract::setControllerName

(Yaf >=1.0.0)

Yaf_Request_Abstract::setControllerName — The setControllerName purpose

Description

public Yaf_Request_Abstract::setControllerName ( string $controller ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

controller

Return Values


The setDispatched purpose

  • « Yaf_Request_Abstract::setControllerName
  • Yaf_Request_Abstract::setModuleName »
  • PHP Manual
  • Yaf_Request_Abstract
  • The setDispatched purpose

Yaf_Request_Abstract::setDispatched

(Yaf >=1.0.0)

Yaf_Request_Abstract::setDispatched — The setDispatched purpose

Description

public Yaf_Request_Abstract::setDispatched ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The setModuleName purpose

  • « Yaf_Request_Abstract::setDispatched
  • Yaf_Request_Abstract::setParam »
  • PHP Manual
  • Yaf_Request_Abstract
  • The setModuleName purpose

Yaf_Request_Abstract::setModuleName

(Yaf >=1.0.0)

Yaf_Request_Abstract::setModuleName — The setModuleName purpose

Description

public Yaf_Request_Abstract::setModuleName ( string $module ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

module

Return Values


Set a calling parameter to a request

  • « Yaf_Request_Abstract::setModuleName
  • Yaf_Request_Abstract::setRequestUri »
  • PHP Manual
  • Yaf_Request_Abstract
  • Set a calling parameter to a request

Yaf_Request_Abstract::setParam

(Yaf >=1.0.0)

Yaf_Request_Abstract::setParam — Set a calling parameter to a request

Description

public Yaf_Request_Abstract::setParam ( string $name [, string $value ] ) : bool

Set a parameter to request, which can be retrieved by Yaf_Request_Abstract::getParam()

Parameters

name

value

Return Values

See Also

  • Yaf_Request_Abstract::getParam() - Retrieve calling parameter
  • Yaf_Request_Abstract::getParams() - Retrieve all calling parameters


The setRequestUri purpose

  • « Yaf_Request_Abstract::setParam
  • Yaf_Request_Abstract::setRouted »
  • PHP Manual
  • Yaf_Request_Abstract
  • The setRequestUri purpose

Yaf_Request_Abstract::setRequestUri

(Yaf >=2.1.0)

Yaf_Request_Abstract::setRequestUri — The setRequestUri purpose

Description

public Yaf_Request_Abstract::setRequestUri ( string $uir ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

uir

Return Values


The setRouted purpose

  • « Yaf_Request_Abstract::setRequestUri
  • Yaf_Request_Http »
  • PHP Manual
  • Yaf_Request_Abstract
  • The setRouted purpose

Yaf_Request_Abstract::setRouted

(Yaf >=1.0.0)

Yaf_Request_Abstract::setRouted — The setRouted purpose

Description

public Yaf_Request_Abstract::setRouted ([ string $flag ] ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

flag

Return Values


The Yaf_Request_Http class

(Yaf >=1.0.0)

Introduction

Any request from client is initialized as a Yaf_Request_Http. you can get the request information like, uri query and post parameters via methods of this class.

Note:

For security, $_GET/$_POST are readonly in Yaf, which means if you set a value to these global variables, you can not get it from Yaf_Request_Http::getQuery() or Yaf_Request_Http::getPost().

But there do is some usage need such feature, like unit testing. thus Yaf can be built with --enable-yaf-debug, which will allow Yaf read the value user set via script.

in such case, Yaf will throw a E_STRICT warning to remind you about that: Strict Standards: you are running yaf in debug mode

Class synopsis

Yaf_Request_Http extends Yaf_Request_Abstract {
/* Properties */
/* Methods */
private __clone ( void ) : void
public __construct ([ string $request_uri [, string $base_uri ]] )
public get ( string $name [, string $default ] ) : mixed
public getCookie ( string $name [, string $default ] ) : mixed
public getFiles ( void ) : void
public getPost ( string $name [, string $default ] ) : mixed
public getQuery ( string $name [, string $default ] ) : mixed
public getRaw ( void ) : mixed
public getRequest ( void ) : void
public isXmlHttpRequest ( void ) : bool
/* Inherited methods */
public Yaf_Request_Abstract::getActionName ( void ) : void
public Yaf_Request_Abstract::getBaseUri ( void ) : void
public Yaf_Request_Abstract::getControllerName ( void ) : void
public Yaf_Request_Abstract::getEnv ( string $name [, string $default ] ) : void
public Yaf_Request_Abstract::getException ( void ) : void
public Yaf_Request_Abstract::getLanguage ( void ) : void
public Yaf_Request_Abstract::getMethod ( void ) : string
public Yaf_Request_Abstract::getModuleName ( void ) : void
public Yaf_Request_Abstract::getParam ( string $name [, string $default ] ) : mixed
public Yaf_Request_Abstract::getParams ( void ) : array
public Yaf_Request_Abstract::getRequestUri ( void ) : void
public Yaf_Request_Abstract::getServer ( string $name [, string $default ] ) : void
public Yaf_Request_Abstract::isCli ( void ) : bool
public Yaf_Request_Abstract::isDispatched ( void ) : bool
public Yaf_Request_Abstract::isGet ( void ) : bool
public Yaf_Request_Abstract::isHead ( void ) : bool
public Yaf_Request_Abstract::isOptions ( void ) : bool
public Yaf_Request_Abstract::isPost ( void ) : bool
public Yaf_Request_Abstract::isPut ( void ) : bool
public Yaf_Request_Abstract::isRouted ( void ) : bool
public Yaf_Request_Abstract::isXmlHttpRequest ( void ) : bool
public Yaf_Request_Abstract::setActionName ( string $action ) : void
public Yaf_Request_Abstract::setBaseUri ( string $uir ) : bool
public Yaf_Request_Abstract::setControllerName ( string $controller ) : void
public Yaf_Request_Abstract::setDispatched ( void ) : void
public Yaf_Request_Abstract::setModuleName ( string $module ) : void
public Yaf_Request_Abstract::setParam ( string $name [, string $value ] ) : bool
public Yaf_Request_Abstract::setRequestUri ( string $uir ) : void
public Yaf_Request_Abstract::setRouted ([ string $flag ] ) : void
}

Properties

module

controller

action

method

params

language

_exception

_base_uri

uri

dispatched

routed

Table of Contents

  • Yaf_Request_Http::__clone — Yaf_Request_Http can not be cloned
  • Yaf_Request_Http::__construct — Constructor of Yaf_Request_Http
  • Yaf_Request_Http::get — Retrieve variable from client
  • Yaf_Request_Http::getCookie — Retrieve Cookie variable
  • Yaf_Request_Http::getFiles — The getFiles purpose
  • Yaf_Request_Http::getPost — Retrieve POST variable
  • Yaf_Request_Http::getQuery — Fetch a query parameter
  • Yaf_Request_Http::getRaw — Retrieve Raw request body
  • Yaf_Request_Http::getRequest — The getRequest purpose
  • Yaf_Request_Http::isXmlHttpRequest — Determin if request is Ajax Request


Yaf_Request_Http can not be cloned

  • « Yaf_Request_Http
  • Yaf_Request_Http::__construct »
  • PHP Manual
  • Yaf_Request_Http
  • Yaf_Request_Http can not be cloned

Yaf_Request_Http::__clone

(Yaf >=1.0.0)

Yaf_Request_Http::__clone — Yaf_Request_Http can not be cloned

Description

private Yaf_Request_Http::__clone ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Constructor of Yaf_Request_Http

  • « Yaf_Request_Http::__clone
  • Yaf_Request_Http::get »
  • PHP Manual
  • Yaf_Request_Http
  • Constructor of Yaf_Request_Http

Yaf_Request_Http::__construct

(Yaf >=1.0.0)

Yaf_Request_Http::__construct — Constructor of Yaf_Request_Http

Description

public Yaf_Request_Http::__construct ([ string $request_uri [, string $base_uri ]] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Retrieve variable from client

  • « Yaf_Request_Http::__construct
  • Yaf_Request_Http::getCookie »
  • PHP Manual
  • Yaf_Request_Http
  • Retrieve variable from client

Yaf_Request_Http::get

(Yaf >=1.0.0)

Yaf_Request_Http::get — Retrieve variable from client

Description

public Yaf_Request_Http::get ( string $name [, string $default ] ) : mixed

Retrieve variable from client, this method will search the name in request pramas, if the name is not found, then will search in POST, GET, Cookie, Server

Parameters

name

the variable name

default

if this parameter is provide, this will be returned if the varialbe can not be found

Return Values

See Also

  • Yaf_Request_Http::getQuery() - Fetch a query parameter
  • Yaf_Request_Http::getPost() - Retrieve POST variable
  • Yaf_Request_Http::getCookie() - Retrieve Cookie variable
  • Yaf_Request_Http::getRaw() - Retrieve Raw request body
  • Yaf_Request_Abstract::getServer() - Retrieve SERVER variable
  • Yaf_Request_Abstract::getParam() - Retrieve calling parameter


Retrieve Cookie variable

  • « Yaf_Request_Http::get
  • Yaf_Request_Http::getFiles »
  • PHP Manual
  • Yaf_Request_Http
  • Retrieve Cookie variable

Yaf_Request_Http::getCookie

(Yaf >=1.0.0)

Yaf_Request_Http::getCookie — Retrieve Cookie variable

Description

public Yaf_Request_Http::getCookie ( string $name [, string $default ] ) : mixed

Retrieve Cookie variable

Parameters

name

the cookie name

default

if this parameter is provide, this will be returned if the cookie can not be found

Return Values

See Also

  • Yaf_Request_Http::get() - Retrieve variable from client
  • Yaf_Request_Http::getQuery() - Fetch a query parameter
  • Yaf_Request_Http::getPost() - Retrieve POST variable
  • Yaf_Request_Http::getRaw() - Retrieve Raw request body
  • Yaf_Request_Abstract::getServer() - Retrieve SERVER variable
  • Yaf_Request_Abstract::getParam() - Retrieve calling parameter


The getFiles purpose

  • « Yaf_Request_Http::getCookie
  • Yaf_Request_Http::getPost »
  • PHP Manual
  • Yaf_Request_Http
  • The getFiles purpose

Yaf_Request_Http::getFiles

(Yaf >=1.0.0)

Yaf_Request_Http::getFiles — The getFiles purpose

Description

public Yaf_Request_Http::getFiles ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Retrieve POST variable

  • « Yaf_Request_Http::getFiles
  • Yaf_Request_Http::getQuery »
  • PHP Manual
  • Yaf_Request_Http
  • Retrieve POST variable

Yaf_Request_Http::getPost

(Yaf >=1.0.0)

Yaf_Request_Http::getPost — Retrieve POST variable

Description

public Yaf_Request_Http::getPost ( string $name [, string $default ] ) : mixed

Retrieve POST variable

Parameters

name

the variable name

default

if this parameter is provide, this will be returned if the varialbe can not be found

Return Values

See Also

  • Yaf_Request_Http::get() - Retrieve variable from client
  • Yaf_Request_Http::getQuery() - Fetch a query parameter
  • Yaf_Request_Http::getCookie() - Retrieve Cookie variable
  • Yaf_Request_Http::getRaw() - Retrieve Raw request body
  • Yaf_Request_Abstract::getServer() - Retrieve SERVER variable
  • Yaf_Request_Abstract::getParam() - Retrieve calling parameter


Fetch a query parameter

  • « Yaf_Request_Http::getPost
  • Yaf_Request_Http::getRaw »
  • PHP Manual
  • Yaf_Request_Http
  • Fetch a query parameter

Yaf_Request_Http::getQuery

(Yaf >=1.0.0)

Yaf_Request_Http::getQuery — Fetch a query parameter

Description

public Yaf_Request_Http::getQuery ( string $name [, string $default ] ) : mixed

Retrieve GET variable

Parameters

name

the variable name

default

if this parameter is provide, this will be returned if the variable can not be found

Return Values

See Also

  • Yaf_Request_Http::get() - Retrieve variable from client
  • Yaf_Request_Http::getPost() - Retrieve POST variable
  • Yaf_Request_Http::getCookie() - Retrieve Cookie variable
  • Yaf_Request_Http::getRaw() - Retrieve Raw request body
  • Yaf_Request_Abstract::getServer() - Retrieve SERVER variable
  • Yaf_Request_Abstract::getParam() - Retrieve calling parameter


Retrieve Raw request body

  • « Yaf_Request_Http::getQuery
  • Yaf_Request_Http::getRequest »
  • PHP Manual
  • Yaf_Request_Http
  • Retrieve Raw request body

Yaf_Request_Http::getRaw

(Yaf >=3.0.7)

Yaf_Request_Http::getRaw — Retrieve Raw request body

Description

public Yaf_Request_Http::getRaw ( void ) : mixed

Retrieve Raw request body

Parameters

This function has no parameters.

Return Values

Return string on success, FALSE on failure.

See Also

  • Yaf_Request_Http::get() - Retrieve variable from client
  • Yaf_Request_Http::getPost() - Retrieve POST variable
  • Yaf_Request_Http::getCookie() - Retrieve Cookie variable
  • Yaf_Request_Http::getQuery() - Fetch a query parameter
  • Yaf_Request_Abstract::getServer() - Retrieve SERVER variable
  • Yaf_Request_Abstract::getParam() - Retrieve calling parameter


The getRequest purpose

  • « Yaf_Request_Http::getRaw
  • Yaf_Request_Http::isXmlHttpRequest »
  • PHP Manual
  • Yaf_Request_Http
  • The getRequest purpose

Yaf_Request_Http::getRequest

(Yaf >=1.0.0)

Yaf_Request_Http::getRequest — The getRequest purpose

Description

public Yaf_Request_Http::getRequest ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Determin if request is Ajax Request

  • « Yaf_Request_Http::getRequest
  • Yaf_Request_Simple »
  • PHP Manual
  • Yaf_Request_Http
  • Determin if request is Ajax Request

Yaf_Request_Http::isXmlHttpRequest

(Yaf >=1.0.0)

Yaf_Request_Http::isXmlHttpRequest — Determin if request is Ajax Request

Description

public Yaf_Request_Http::isXmlHttpRequest ( void ) : bool

Check the request whether it is a Ajax Request.

Note:

This method depends on the request header: HTTP_X_REQUESTED_WITH, some Javascript library doesn't set this header while doing Ajax request

Parameters

This function has no parameters.

Return Values

boolean


The Yaf_Request_Simple class

(Yaf >=1.0.0)

Introduction

Yaf_Request_Simple is particularlly used for test puporse. ie. simulate some espacial request under CLI mode.

Class synopsis

Yaf_Request_Simple extends Yaf_Request_Abstract {
/* Constants */
const string SCHEME_HTTP = http ;
const string SCHEME_HTTPS = https ;
/* Properties */
/* Methods */
private __clone ( void ) : void
public __construct ([ string $method [, string $module [, string $controller [, string $action [, array $params ]]]]] )
public get ( void ) : void
public getCookie ( void ) : void
public getFiles ( void ) : void
public getPost ( void ) : void
public getQuery ( void ) : void
public getRequest ( void ) : void
public isXmlHttpRequest ( void ) : void
/* Inherited methods */
public Yaf_Request_Abstract::getActionName ( void ) : void
public Yaf_Request_Abstract::getBaseUri ( void ) : void
public Yaf_Request_Abstract::getControllerName ( void ) : void
public Yaf_Request_Abstract::getEnv ( string $name [, string $default ] ) : void
public Yaf_Request_Abstract::getException ( void ) : void
public Yaf_Request_Abstract::getLanguage ( void ) : void
public Yaf_Request_Abstract::getMethod ( void ) : string
public Yaf_Request_Abstract::getModuleName ( void ) : void
public Yaf_Request_Abstract::getParam ( string $name [, string $default ] ) : mixed
public Yaf_Request_Abstract::getParams ( void ) : array
public Yaf_Request_Abstract::getRequestUri ( void ) : void
public Yaf_Request_Abstract::getServer ( string $name [, string $default ] ) : void
public Yaf_Request_Abstract::isCli ( void ) : bool
public Yaf_Request_Abstract::isDispatched ( void ) : bool
public Yaf_Request_Abstract::isGet ( void ) : bool
public Yaf_Request_Abstract::isHead ( void ) : bool
public Yaf_Request_Abstract::isOptions ( void ) : bool
public Yaf_Request_Abstract::isPost ( void ) : bool
public Yaf_Request_Abstract::isPut ( void ) : bool
public Yaf_Request_Abstract::isRouted ( void ) : bool
public Yaf_Request_Abstract::isXmlHttpRequest ( void ) : bool
public Yaf_Request_Abstract::setActionName ( string $action ) : void
public Yaf_Request_Abstract::setBaseUri ( string $uir ) : bool
public Yaf_Request_Abstract::setControllerName ( string $controller ) : void
public Yaf_Request_Abstract::setDispatched ( void ) : void
public Yaf_Request_Abstract::setModuleName ( string $module ) : void
public Yaf_Request_Abstract::setParam ( string $name [, string $value ] ) : bool
public Yaf_Request_Abstract::setRequestUri ( string $uir ) : void
public Yaf_Request_Abstract::setRouted ([ string $flag ] ) : void
}

Properties

module

controller

action

method

params

language

_exception

_base_uri

uri

dispatched

routed

Predefined Constants

Yaf_Request_Simple::SCHEME_HTTP

Yaf_Request_Simple::SCHEME_HTTPS

Table of Contents

  • Yaf_Request_Simple::__clone — The __clone purpose
  • Yaf_Request_Simple::__construct — Constructor of Yaf_Request_Simple
  • Yaf_Request_Simple::get — The get purpose
  • Yaf_Request_Simple::getCookie — The getCookie purpose
  • Yaf_Request_Simple::getFiles — The getFiles purpose
  • Yaf_Request_Simple::getPost — The getPost purpose
  • Yaf_Request_Simple::getQuery — The getQuery purpose
  • Yaf_Request_Simple::getRequest — The getRequest purpose
  • Yaf_Request_Simple::isXmlHttpRequest — Determin if request is AJAX request


The __clone purpose

  • « Yaf_Request_Simple
  • Yaf_Request_Simple::__construct »
  • PHP Manual
  • Yaf_Request_Simple
  • The __clone purpose

Yaf_Request_Simple::__clone

(Yaf >=1.0.0)

Yaf_Request_Simple::__clone — The __clone purpose

Description

private Yaf_Request_Simple::__clone ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Constructor of Yaf_Request_Simple

  • « Yaf_Request_Simple::__clone
  • Yaf_Request_Simple::get »
  • PHP Manual
  • Yaf_Request_Simple
  • Constructor of Yaf_Request_Simple

Yaf_Request_Simple::__construct

(Yaf >=1.0.0)

Yaf_Request_Simple::__construct — Constructor of Yaf_Request_Simple

Description

public Yaf_Request_Simple::__construct ([ string $method [, string $module [, string $controller [, string $action [, array $params ]]]]] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The get purpose

  • « Yaf_Request_Simple::__construct
  • Yaf_Request_Simple::getCookie »
  • PHP Manual
  • Yaf_Request_Simple
  • The get purpose

Yaf_Request_Simple::get

(Yaf >=1.0.0)

Yaf_Request_Simple::get — The get purpose

Description

public Yaf_Request_Simple::get ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The getCookie purpose

  • « Yaf_Request_Simple::get
  • Yaf_Request_Simple::getFiles »
  • PHP Manual
  • Yaf_Request_Simple
  • The getCookie purpose

Yaf_Request_Simple::getCookie

(Yaf >=1.0.0)

Yaf_Request_Simple::getCookie — The getCookie purpose

Description

public Yaf_Request_Simple::getCookie ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The getFiles purpose

  • « Yaf_Request_Simple::getCookie
  • Yaf_Request_Simple::getPost »
  • PHP Manual
  • Yaf_Request_Simple
  • The getFiles purpose

Yaf_Request_Simple::getFiles

(Yaf >=1.0.0)

Yaf_Request_Simple::getFiles — The getFiles purpose

Description

public Yaf_Request_Simple::getFiles ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The getPost purpose

  • « Yaf_Request_Simple::getFiles
  • Yaf_Request_Simple::getQuery »
  • PHP Manual
  • Yaf_Request_Simple
  • The getPost purpose

Yaf_Request_Simple::getPost

(Yaf >=1.0.0)

Yaf_Request_Simple::getPost — The getPost purpose

Description

public Yaf_Request_Simple::getPost ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The getQuery purpose

  • « Yaf_Request_Simple::getPost
  • Yaf_Request_Simple::getRequest »
  • PHP Manual
  • Yaf_Request_Simple
  • The getQuery purpose

Yaf_Request_Simple::getQuery

(Yaf >=1.0.0)

Yaf_Request_Simple::getQuery — The getQuery purpose

Description

public Yaf_Request_Simple::getQuery ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The getRequest purpose

  • « Yaf_Request_Simple::getQuery
  • Yaf_Request_Simple::isXmlHttpRequest »
  • PHP Manual
  • Yaf_Request_Simple
  • The getRequest purpose

Yaf_Request_Simple::getRequest

(Yaf >=1.0.0)

Yaf_Request_Simple::getRequest — The getRequest purpose

Description

public Yaf_Request_Simple::getRequest ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Determin if request is AJAX request

  • « Yaf_Request_Simple::getRequest
  • Yaf_Response_Abstract »
  • PHP Manual
  • Yaf_Request_Simple
  • Determin if request is AJAX request

Yaf_Request_Simple::isXmlHttpRequest

(Yaf >=1.0.0)

Yaf_Request_Simple::isXmlHttpRequest — Determin if request is AJAX request

Description

public Yaf_Request_Simple::isXmlHttpRequest ( void ) : void

Parameters

This function has no parameters.

Return Values

Always returns false for Yaf_Request_Simple

See Also

  • Yaf_Request_Abstract::isXmlHTTPRequest() - Determine if request is AJAX request
  • Yaf_Request_Http::isXmlHTTPRequest() - Determin if request is Ajax Request


The Yaf_Response_Abstract class

(Yaf >=1.0.0)

Introduction

Class synopsis

Yaf_Response_Abstract {
/* Constants */
const string DEFAULT_BODY = "content" ;
/* Properties */
protected $_header ;
protected $_body ;
protected $_sendheader ;
/* Methods */
public appendBody ( string $content [, string $key ] ) : bool
public clearBody ([ string $key ] ) : bool
public clearHeaders ( void ) : void
private __clone ( void ) : void
public __construct ( void )
public __destruct ( void ) : void
public getBody ([ string $key ] ) : mixed
public getHeader ( void ) : void
public prependBody ( string $content [, string $key ] ) : bool
public response ( void ) : void
protected setAllHeaders ( void ) : void
public setBody ( string $content [, string $key ] ) : bool
public setHeader ( string $name , string $value [, bool $replace ] ) : bool
public setRedirect ( void ) : void
private __toString ( void ) : string
}

Properties

_header

_body

_sendheader

Table of Contents

  • Yaf_Response_Abstract::appendBody — Append to response body
  • Yaf_Response_Abstract::clearBody — Discard all exists response body
  • Yaf_Response_Abstract::clearHeaders — Discard all set headers
  • Yaf_Response_Abstract::__clone — The __clone purpose
  • Yaf_Response_Abstract::__construct — The __construct purpose
  • Yaf_Response_Abstract::__destruct — The __destruct purpose
  • Yaf_Response_Abstract::getBody — Retrieve a exists content
  • Yaf_Response_Abstract::getHeader — The getHeader purpose
  • Yaf_Response_Abstract::prependBody — The prependBody purpose
  • Yaf_Response_Abstract::response — Send response
  • Yaf_Response_Abstract::setAllHeaders — The setAllHeaders purpose
  • Yaf_Response_Abstract::setBody — Set content to response
  • Yaf_Response_Abstract::setHeader — Set reponse header
  • Yaf_Response_Abstract::setRedirect — The setRedirect purpose
  • Yaf_Response_Abstract::__toString — Retrieve all bodys as string


Append to response body

  • « Yaf_Response_Abstract
  • Yaf_Response_Abstract::clearBody »
  • PHP Manual
  • Yaf_Response_Abstract
  • Append to response body

Yaf_Response_Abstract::appendBody

(Yaf >=1.0.0)

Yaf_Response_Abstract::appendBody — Append to response body

Description

public Yaf_Response_Abstract::appendBody ( string $content [, string $key ] ) : bool

Append a content to a exists content block

Parameters

body

content string

key

the content key, you can set a content with a key, if you don't specific, then Yaf_Response_Abstract::DEFAULT_BODY will be used

Note:

this parameter is introduced as of 2.2.0

Return Values

bool

Examples

Example #1 Yaf_Response_Abstract::appendBody()example

<?php
$response = new Yaf_Response_Http();

$response->setBody("Hello")->prependBody(" World");

echo $response;
?>

The above example will output something similar to:

Hello World

See Also

  • Yaf_Config_Ini

See Also

  • Yaf_Response_Abstract::getBody() - Retrieve a exists content
  • Yaf_Response_Abstract::setBody() - Set content to response
  • Yaf_Response_Abstract::prependBody() - The prependBody purpose
  • Yaf_Response_Abstract::clearBody() - Discard all exists response body


Discard all exists response body

  • « Yaf_Response_Abstract::appendBody
  • Yaf_Response_Abstract::clearHeaders »
  • PHP Manual
  • Yaf_Response_Abstract
  • Discard all exists response body

Yaf_Response_Abstract::clearBody

(Yaf >=1.0.0)

Yaf_Response_Abstract::clearBody — Discard all exists response body

Description

public Yaf_Response_Abstract::clearBody ([ string $key ] ) : bool

Clear existsed content

Parameters

key

the content key, if you don't specific, then all contents will be cleared.

Note:

this parameter is introduced as of 2.2.0

Return Values

See Also

  • Yaf_Response_Abstract::setBody() - Set content to response
  • Yaf_Response_Abstract::appendBody() - Append to response body
  • Yaf_Response_Abstract::prependBody() - The prependBody purpose
  • Yaf_Response_Abstract::getBody() - Retrieve a exists content


Discard all set headers

  • « Yaf_Response_Abstract::clearBody
  • Yaf_Response_Abstract::__clone »
  • PHP Manual
  • Yaf_Response_Abstract
  • Discard all set headers

Yaf_Response_Abstract::clearHeaders

(Yaf >=1.0.0)

Yaf_Response_Abstract::clearHeaders — Discard all set headers

Description

public Yaf_Response_Abstract::clearHeaders ( void ) : void

Parameters

This function has no parameters.

Return Values

See Also

  • Yaf_Response_Abstract::getHeader() - The getHeader purpose
  • Yaf_Response_Abstract::setHeader() - Set reponse header


The __clone purpose

  • « Yaf_Response_Abstract::clearHeaders
  • Yaf_Response_Abstract::__construct »
  • PHP Manual
  • Yaf_Response_Abstract
  • The __clone purpose

Yaf_Response_Abstract::__clone

(Yaf >=1.0.0)

Yaf_Response_Abstract::__clone — The __clone purpose

Description

private Yaf_Response_Abstract::__clone ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The __construct purpose

  • « Yaf_Response_Abstract::__clone
  • Yaf_Response_Abstract::__destruct »
  • PHP Manual
  • Yaf_Response_Abstract
  • The __construct purpose

Yaf_Response_Abstract::__construct

(Yaf >=1.0.0)

Yaf_Response_Abstract::__construct — The __construct purpose

Description

public Yaf_Response_Abstract::__construct ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The __destruct purpose

  • « Yaf_Response_Abstract::__construct
  • Yaf_Response_Abstract::getBody »
  • PHP Manual
  • Yaf_Response_Abstract
  • The __destruct purpose

Yaf_Response_Abstract::__destruct

(Yaf >=1.0.0)

Yaf_Response_Abstract::__destruct — The __destruct purpose

Description

public Yaf_Response_Abstract::__destruct ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Retrieve a exists content

  • « Yaf_Response_Abstract::__destruct
  • Yaf_Response_Abstract::getHeader »
  • PHP Manual
  • Yaf_Response_Abstract
  • Retrieve a exists content

Yaf_Response_Abstract::getBody

(Yaf >=1.0.0)

Yaf_Response_Abstract::getBody — Retrieve a exists content

Description

public Yaf_Response_Abstract::getBody ([ string $key ] ) : mixed

Retrieve a exists content

Parameters

key

the content key, if you don't specific, then Yaf_Response_Abstract::DEFAULT_BODY will be used. if you pass in a NULL, then all contents will be returned as a array

Note:

this parameter is introduced as of 2.2.0

Return Values

Examples

Example #1 Yaf_Response_Abstract::getBody()example

<?php
$response = new Yaf_Response_Http();

$response->setBody("Hello")->setBody(" World", "footer");

var_dump($response->getBody()); //default
var_dump($response->getBody(Yaf_Response_Abstract::DEFAULT_BODY)); //same as above
var_dump($response->getBody("footer"));
var_dump($response->getBody(NULL)); //get all
?>

The above example will output something similar to:

string(5) "Hello"
string(5) "Hello"
string(6) " World"
array(2) {
  ["content"]=>
  string(5) "Hello"
  ["footer"]=>
  string(6) " World"
}

See Also

  • Yaf_Response_Abstract::setBody() - Set content to response
  • Yaf_Response_Abstract::appendBody() - Append to response body
  • Yaf_Response_Abstract::prependBody() - The prependBody purpose
  • Yaf_Response_Abstract::clearBody() - Discard all exists response body


The getHeader purpose

  • « Yaf_Response_Abstract::getBody
  • Yaf_Response_Abstract::prependBody »
  • PHP Manual
  • Yaf_Response_Abstract
  • The getHeader purpose

Yaf_Response_Abstract::getHeader

(Yaf >=1.0.0)

Yaf_Response_Abstract::getHeader — The getHeader purpose

Description

public Yaf_Response_Abstract::getHeader ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

See Also

  • Yaf_Response_Abstract::setHeader() - Set reponse header
  • Yaf_Response_Abstract::cleanHeaders()


The prependBody purpose

  • « Yaf_Response_Abstract::getHeader
  • Yaf_Response_Abstract::response »
  • PHP Manual
  • Yaf_Response_Abstract
  • The prependBody purpose

Yaf_Response_Abstract::prependBody

(Yaf >=1.0.0)

Yaf_Response_Abstract::prependBody — The prependBody purpose

Description

public Yaf_Response_Abstract::prependBody ( string $content [, string $key ] ) : bool

prepend a content to a exists content block

Parameters

body

content string

key

the content key, you can set a content with a key, if you don't specific, then Yaf_Response_Abstract::DEFAULT_BODY will be used

Note:

this parameter is introduced as of 2.2.0

Return Values

bool

Examples

Example #1 Yaf_Response_Abstract::prependBody()example

<?php
$response = new Yaf_Response_Http();

$response->setBody("World")->prependBody("Hello ");

echo $response;
?>

The above example will output something similar to:

Hello World

See Also

  • Yaf_Response_Abstract::getBody() - Retrieve a exists content
  • Yaf_Response_Abstract::setBody() - Set content to response
  • Yaf_Response_Abstract::appendBody() - Append to response body
  • Yaf_Response_Abstract::clearBody() - Discard all exists response body


Send response

  • « Yaf_Response_Abstract::prependBody
  • Yaf_Response_Abstract::setAllHeaders »
  • PHP Manual
  • Yaf_Response_Abstract
  • Send response

Yaf_Response_Abstract::response

(Yaf >=1.0.0)

Yaf_Response_Abstract::response — Send response

Description

public Yaf_Response_Abstract::response ( void ) : void

send response

Parameters

This function has no parameters.

Return Values

Examples

Example #1 Yaf_Response_Abstract::response()example

<?php
$response = new Yaf_Response_Http();

$response->setBody("Hello")->setBody(" World", "footer");

$response->response();
?>

The above example will output something similar to:

Hello World

See Also

  • Yaf_Response_Abstract::setBody() - Set content to response
  • Yaf_Response_Abstract::clearBody() - Discard all exists response body


The setAllHeaders purpose

  • « Yaf_Response_Abstract::response
  • Yaf_Response_Abstract::setBody »
  • PHP Manual
  • Yaf_Response_Abstract
  • The setAllHeaders purpose

Yaf_Response_Abstract::setAllHeaders

(Yaf >=1.0.0)

Yaf_Response_Abstract::setAllHeaders — The setAllHeaders purpose

Description

protected Yaf_Response_Abstract::setAllHeaders ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Set content to response

  • « Yaf_Response_Abstract::setAllHeaders
  • Yaf_Response_Abstract::setHeader »
  • PHP Manual
  • Yaf_Response_Abstract
  • Set content to response

Yaf_Response_Abstract::setBody

(Yaf >=1.0.0)

Yaf_Response_Abstract::setBody — Set content to response

Description

public Yaf_Response_Abstract::setBody ( string $content [, string $key ] ) : bool

Set content to response

Parameters

body

content string

key

the content key, you can set a content with a key, if you don't specific, then Yaf_Response_Abstract::DEFAULT_BODY will be used

Note:

this parameter is introduced as of 2.2.0

Return Values

Examples

Example #1 Yaf_Response_Abstract::setBody()example

<?php
$response = new Yaf_Response_Http();

$response->setBody("Hello")->setBody(" World", "footer");

print_r($response);
echo $response;
?>

The above example will output something similar to:

Yaf_Response_Http Object
(
    [_header:protected] => Array
        (
        )

    [_body:protected] => Array
        (
            [content] => Hello
            [footer] =>  World
        )

    [_sendheader:protected] => 1
    [_response_code:protected] => 200
)
Hello World

See Also

  • Yaf_Response_Abstract::getBody() - Retrieve a exists content
  • Yaf_Response_Abstract::appendBody() - Append to response body
  • Yaf_Response_Abstract::prependBody() - The prependBody purpose
  • Yaf_Response_Abstract::clearBody() - Discard all exists response body


Set reponse header

  • « Yaf_Response_Abstract::setBody
  • Yaf_Response_Abstract::setRedirect »
  • PHP Manual
  • Yaf_Response_Abstract
  • Set reponse header

Yaf_Response_Abstract::setHeader

(Yaf >=1.0.0)

Yaf_Response_Abstract::setHeader — Set reponse header

Description

public Yaf_Response_Abstract::setHeader ( string $name , string $value [, bool $replace ] ) : bool

Used to send a HTTP header

Parameters

This function has no parameters.

Return Values

See Also

  • Yaf_Response_Abstract::getHeader() - The getHeader purpose
  • Yaf_Response_Abstract::cleanHeaders()


The setRedirect purpose

  • « Yaf_Response_Abstract::setHeader
  • Yaf_Response_Abstract::__toString »
  • PHP Manual
  • Yaf_Response_Abstract
  • The setRedirect purpose

Yaf_Response_Abstract::setRedirect

(Yaf >=1.0.0)

Yaf_Response_Abstract::setRedirect — The setRedirect purpose

Description

public Yaf_Response_Abstract::setRedirect ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Retrieve all bodys as string

  • « Yaf_Response_Abstract::setRedirect
  • Yaf_Route_Interface »
  • PHP Manual
  • Yaf_Response_Abstract
  • Retrieve all bodys as string

Yaf_Response_Abstract::__toString

(Yaf >=1.0.0)

Yaf_Response_Abstract::__toString — Retrieve all bodys as string

Description

private Yaf_Response_Abstract::__toString ( void ) : string

Parameters

This function has no parameters.

Return Values


The Yaf_Route_Interface class

(Yaf >=1.0.0)

Introduction

Yaf_Route_Interface used for developer defined their custom route.

Class synopsis

Yaf_Route_Interface {
/* Methods */
abstract public assemble ( array $info [, array $query ] ) : string
abstract public route ( Yaf_Request_Abstract $request ) : bool
}

Table of Contents

  • Yaf_Route_Interface::assemble — Assemble a request
  • Yaf_Route_Interface::route — Route a request


Assemble a request

  • « Yaf_Route_Interface
  • Yaf_Route_Interface::route »
  • PHP Manual
  • Yaf_Route_Interface
  • Assemble a request

Yaf_Route_Interface::assemble

(Yaf >=2.3.0)

Yaf_Route_Interface::assemble — Assemble a request

Description

abstract public Yaf_Route_Interface::assemble ( array $info [, array $query ] ) : string

this method returns a url according to the argument info, and append query strings to the url according to the argument query.

a route should implement this method according to its own route rules, and do a reverse progress.

Parameters

info

query

Return Values


Route a request

  • « Yaf_Route_Interface::assemble
  • Yaf_Route_Map »
  • PHP Manual
  • Yaf_Route_Interface
  • Route a request

Yaf_Route_Interface::route

(Yaf >=1.0.0)

Yaf_Route_Interface::route — Route a request

Description

abstract public Yaf_Route_Interface::route ( Yaf_Request_Abstract $request ) : bool

Yaf_Route_Interface::route() is the only method that a custom route should implement.

Note:

since of 2.3.0, there is another method should also be implemented, see Yaf_Route_Interface::assemble().

if this method return TRUE, then the route process will be end. otherwise, Yaf_Router will call next route in the route stack to route request.

This method would set the route result to the parameter request, by
calling Yaf_Request_Abstract::setControllerName(),
Yaf_Request_Abstract::setActionName() and
Yaf_Request_Abstract::setModuleName().

This method should also call Yaf_Request_Abstract::setRouted() to make the request routed at last.

Parameters

request

A Yaf_Request_Abstract instance.

Return Values


The Yaf_Route_Map class

(Yaf >=1.0.0)

Introduction

Yaf_Route_Map is a built-in route, it simply convert a URI endpoint (that part of the URI which comes after the base URI: see Yaf_Request_Abstract::setBaseUri()) to a controller name or action name(depends on the parameter passed to Yaf_Route_Map::__construct()) in following rule: A => controller A. A/B/C => controller A_B_C. A/B/C/D/E => controller A_B_C_D_E.

If the second parameter of Yaf_Route_Map::__construct() is specified, then only the part before delimiter of URI will used to routing, the part after it is used to routing request parameters (see the example section of Yaf_Route_Map::__construct()).

Class synopsis

Yaf_Route_Map implements Yaf_Route_Interface {
/* Properties */
protected $_ctl_router ;
protected $_delimiter ;
/* Methods */
public assemble ( array $info [, array $query ] ) : string
public __construct ([ string $controller_prefer = FALSE [, string $delimiter = "" ]] )
public route ( Yaf_Request_Abstract $request ) : bool
}

Properties

_ctl_router

_delimiter

Table of Contents

  • Yaf_Route_Map::assemble — Assemble a url
  • Yaf_Route_Map::__construct — The __construct purpose
  • Yaf_Route_Map::route — The route purpose


Assemble a url

  • « Yaf_Route_Map
  • Yaf_Route_Map::__construct »
  • PHP Manual
  • Yaf_Route_Map
  • Assemble a url

Yaf_Route_Map::assemble

(Yaf >=2.3.0)

Yaf_Route_Map::assemble — Assemble a url

Description

public Yaf_Route_Map::assemble ( array $info [, array $query ] ) : string

Assemble a url.

Parameters

info

query

Examples

Example #1 Yaf_Route_Map::assemble()example

<?php

$router = new Yaf_Router();

$route  = new Yaf_Route_Map();

$router->addRoute("map", $route);

var_dump($router->getRoute('map')->assemble(
                        array(
                                ':c' => 'foo_bar'
                        ),
                        array(
                                'tkey1' => 'tval1',
                                'tkey2' => 'tval2'
                        )
                   )
);

$route = new Yaf_Route_Map(true, '_');
$router->addRoute("map", $route);

var_dump($router->getRoute('map')->assemble(
                        array(
                                ':a' => 'foo_bar'
                        ),
                        array(
                                'tkey1' => 'tval1',
                                'tkey2' => 'tval2'
                        )
                   )
);

The above example will output something similar to:

string(%d) "/foo/bar?tkey1=tval1&tkey2=tval2"
string(%d) "/foo/bar/_/tkey1/tval1/tkey2/tval2"

Return Values


The __construct purpose

  • « Yaf_Route_Map::assemble
  • Yaf_Route_Map::route »
  • PHP Manual
  • Yaf_Route_Map
  • The __construct purpose

Yaf_Route_Map::__construct

(Yaf >=1.0.0)

Yaf_Route_Map::__construct — The __construct purpose

Description

public Yaf_Route_Map::__construct ([ string $controller_prefer = FALSE [, string $delimiter = "" ]] )

Parameters

controller_prefer

Whether the result should considering as controller or action

delimiter

Return Values

Examples

Example #1 Yaf_Route_Map()example

<?php
   /**
    * Add a map route to Yaf_Router route stack
    */
    Yaf_Dispatcher::getInstance()->getRouter()->addRoute("name",
        new Yaf_Route_Map());
?>

The above example will output something similar to:

/* for http://yourdomain.com/product/foo/bar
 * route will result in following values:
 */
array(
  "controller" => "product_foo_bar",
)

Example #2 Yaf_Route_Map()example

<?php
   /**
    * Add a map route to Yaf_Router route stack
    */
    Yaf_Dispatcher::getInstance()->getRouter()->addRoute("name",
        new Yaf_Route_Map(true, "_"));
?>

The above example will output something similar to:

/* for http://yourdomain.com/user/list/_/foo/22
 * route will result in following values:
 */
array(
    "action" => "user_list",
)

/**
 * and request parameters:
 */
array(
  "foo"   => 22,
)

Example #3 Yaf_Route_Map()example

<?php
   /**
    * Add a map route to Yaf_Router route stack by calling addconfig
    */
    $config = array(
        "name" => array(
           "type"  => "map",         //Yaf_Route_Map route
           "controllerPrefer" => FALSE,
           "delimiter"        => "#!",
           ),
    );
    Yaf_Dispatcher::getInstance()->getRouter()->addConfig(
        new Yaf_Config_Simple($config));
?>

See Also

  • Yaf_Router::addRoute() - Add new Route into Router
  • Yaf_Route_Static
  • Yaf_Route_Supervar
  • Yaf_Route_Simple
  • Yaf_Route_Regex
  • Yaf_Route_Rewrite


The route purpose

  • « Yaf_Route_Map::__construct
  • Yaf_Route_Regex »
  • PHP Manual
  • Yaf_Route_Map
  • The route purpose

Yaf_Route_Map::route

(Yaf >=1.0.0)

Yaf_Route_Map::route — The route purpose

Description

public Yaf_Route_Map::route ( Yaf_Request_Abstract $request ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

request

Return Values


The Yaf_Route_Regex class

(Yaf >=1.0.0)

Introduction

Yaf_Route_Regex is the most flexible route among the Yaf built-in routes.

Class synopsis

Yaf_Route_Regex extends Yaf_Route_Interface implements Yaf_Route_Interface {
/* Properties */
protected $_route ;
protected $_default ;
protected $_maps ;
protected $_verify ;
/* Methods */
public assemble ( array $info [, array $query ] ) : string
public __construct ( string $match , array $route [, array $map [, array $verify [, string $reverse ]]] )
public route ( Yaf_Request_Abstract $request ) : bool
/* Inherited methods */
abstract public Yaf_Route_Interface::assemble ( array $info [, array $query ] ) : string
abstract public Yaf_Route_Interface::route ( Yaf_Request_Abstract $request ) : bool
}

Properties

_route

_default

_maps

_verify

Table of Contents

  • Yaf_Route_Regex::assemble — Assemble a url
  • Yaf_Route_Regex::__construct — Yaf_Route_Regex constructor
  • Yaf_Route_Regex::route — The route purpose


Assemble a url

  • « Yaf_Route_Regex
  • Yaf_Route_Regex::__construct »
  • PHP Manual
  • Yaf_Route_Regex
  • Assemble a url

Yaf_Route_Regex::assemble

(Yaf >=2.3.0)

Yaf_Route_Regex::assemble — Assemble a url

Description

public Yaf_Route_Regex::assemble ( array $info [, array $query ] ) : string

Assemble a url.

Parameters

info

query

Examples

Example #1 Yaf_Route_Regex::assemble()example

<?php

$router = new Yaf_Router();

$route  = new Yaf_Route_Regex(
            "#^/product/([^/]+)/([^/])+#",
            array(
                'controller' => "product",  //route to product controller,
                ),
            array(),
            array(),
            '/:m/:c/:a'
        );

$router->addRoute("regex", $route);

var_dump($router->getRoute('regex')->assemble(
            array(
                ':m' => 'module',
                ':c' => 'controller',
                ':a' => 'action'
                ),
            array(
                'tkey1' => 'tval1',
                'tkey2' =>
                'tval2'
                )
            )
        );

The above example will output something similar to:

string(49) "/module/controller/action?tkey1=tval1&tkey2=tval2"

Return Values


Yaf_Route_Regex constructor

  • « Yaf_Route_Regex::assemble
  • Yaf_Route_Regex::route »
  • PHP Manual
  • Yaf_Route_Regex
  • Yaf_Route_Regex constructor

Yaf_Route_Regex::__construct

(Yaf >=1.0.0)

Yaf_Route_Regex::__construct — Yaf_Route_Regex constructor

Description

public Yaf_Route_Regex::__construct ( string $match , array $route [, array $map [, array $verify [, string $reverse ]]] )

Parameters

match

A complete Regex pattern, will be used to match a request uri, if doesn't matched, Yaf_Route_Regex will return FALSE.

route

When the match pattern matches the request uri, Yaf_Route_Regex will use this to decide which m/c/a to routed.

either of m/c/a in this array is optianl, if you don't assgian a specific value, it will be routed to default.

map

A array to assign name to the captrues in the match result.

verify

reverse

a string, used to assemble url, see Yaf_Route_Regex::assemble().

Note:

this parameter is introduced in 2.3.0

Return Values

Examples

Example #1 Yaf_Route_Regex()example

<?php
   /**
    * Add a regex route to Yaf_Router route stack
    */
    Yaf_Dispatcher::getInstance()->getRouter()->addRoute("name",
        new Yaf_Route_Regex(
           "#^/product/([^/]+)/([^/])+#", //match request uri leading "/product"
           array(
               'controller' => "product",  //route to product controller,
           ),
           array(
              1 => "name",   // now you can call $request->getParam("name")
              2 => "id",     // to get the first captrue in the match pattern.
           )
        )
    );
?>

Example #2 Yaf_Route_Regex(as of 2.3.0)()example

<?php
   /**
    * Use match result as MVC name
    */
    Yaf_Dispatcher::getInstance()->getRouter()->addRoute("name",
        new Yaf_Route_Regex(
           "#^/product/([^/]+)/([^/])+#i", //match request uri leading "/product"
           array(
              'controller' => ":name", // route to :name, which is $1 in the match result as controller name
           ),
           array(
              1 => "name",   // now you can call $request->getParam("name")
              2 => "id",     // to get the first captrue in the match pattern.
           )
        )
    );
?>

Example #3 Yaf_Route_Regex and named capture ground(as of 2.3.0)()example

<?php
   /**
    * Use match result as MVC name
    */
    Yaf_Dispatcher::getInstance()->getRouter()->addRoute("name",
        new Yaf_Route_Regex(
           "#^/product/(?<name>[^/]+)/([^/])+#i", //match request uri leading "/product"
           array(
           'controller' => ":name", // route to :name,
                                    // which is named capture group 'name' in the match result as controller name
           ),
           array(
              2 => "id",     // to get the first captrue in the match pattern.
           )
        )
    );
?>

Example #4 Yaf_Route_Regex()example

<?php
   /**
    * Add a regex route to Yaf_Router route stack by calling addconfig
    */
    $config = array(
        "name" => array(
           "type"  => "regex",          //Yaf_Route_Regex route
           "match" => "#(.*)#",         //match arbitrary request uri
           "route" => array(
               'controller' => "product",  //route to product controller,
               'action'     => "dummy",    //route to dummy action
           ),
           "map" => array(
              1 => "uri",   // now you can call $request->getParam("uri")
           ),
        ),
    );
    Yaf_Dispatcher::getInstance()->getRouter()->addConfig(
        new Yaf_Config_Simple($config));
?>

See Also

  • Yaf_Router::addRoute() - Add new Route into Router
  • Yaf_Router::addConfig() - Add config-defined routes into Router
  • Yaf_Route_Static
  • Yaf_Route_Supervar
  • Yaf_Route_Simple
  • Yaf_Route_Rewrite
  • Yaf_Route_Map


The route purpose

  • « Yaf_Route_Regex::__construct
  • Yaf_Route_Rewrite »
  • PHP Manual
  • Yaf_Route_Regex
  • The route purpose

Yaf_Route_Regex::route

(Yaf >=1.0.0)

Yaf_Route_Regex::route — The route purpose

Description

public Yaf_Route_Regex::route ( Yaf_Request_Abstract $request ) : bool

Route a incoming request.

Warning

This function is currently not documented; only its argument list is available.

Parameters

request

Return Values

If the pattern given by the first parameter of Yaf_Route_Regex::_construct() matche the request uri, return TRUE, otherwise return FALSE.


The Yaf_Route_Rewrite class

(Yaf >=1.0.0)

Introduction

For usage, please see the example section of Yaf_Route_Rewrite::__construct()

Class synopsis

Yaf_Route_Rewrite extends Yaf_Route_Interface implements Yaf_Route_Interface {
/* Properties */
protected $_route ;
protected $_default ;
protected $_verify ;
/* Methods */
public assemble ( array $info [, array $query ] ) : string
public __construct ( string $match , array $route [, array $verify ] )
public route ( Yaf_Request_Abstract $request ) : bool
/* Inherited methods */
abstract public Yaf_Route_Interface::assemble ( array $info [, array $query ] ) : string
abstract public Yaf_Route_Interface::route ( Yaf_Request_Abstract $request ) : bool
}

Properties

_route

_default

_verify

Table of Contents

  • Yaf_Route_Rewrite::assemble — Assemble a url
  • Yaf_Route_Rewrite::__construct — Yaf_Route_Rewrite constructor
  • Yaf_Route_Rewrite::route — The route purpose


Assemble a url

  • « Yaf_Route_Rewrite
  • Yaf_Route_Rewrite::__construct »
  • PHP Manual
  • Yaf_Route_Rewrite
  • Assemble a url

Yaf_Route_Rewrite::assemble

(Yaf >=2.3.0)

Yaf_Route_Rewrite::assemble — Assemble a url

Description

public Yaf_Route_Rewrite::assemble ( array $info [, array $query ] ) : string

Assemble a url.

Parameters

info

query

Examples

Example #1 Yaf_Route_Rewrite::assemble()example

router = new Yaf_Router();

$route  = new Yaf_Route_Rewrite(
                "/product/:name/:id/*",
                array(
                        'controller' => "product",
                ),
                array()
);

$router->addRoute("rewrite", $route);

var_dump($router->getRoute('rewrite')->assemble(
                        array(
                                ':name' => 'foo',
                                ':id' => 'bar',
                                ':tmpkey1' => 'tmpval1'
                        ),
                        array(
                                'tkey1' => 'tval1',
                                'tkey2' => 'tval2'
                             )
                        )
);

The above example will output something similar to:

string(57) "/product/foo/bar/tmpkey1/tmpval1/?tkey1=tval1&tkey2=tval2"

Return Values


Yaf_Route_Rewrite constructor

  • « Yaf_Route_Rewrite::assemble
  • Yaf_Route_Rewrite::route »
  • PHP Manual
  • Yaf_Route_Rewrite
  • Yaf_Route_Rewrite constructor

Yaf_Route_Rewrite::__construct

(Yaf >=1.0.0)

Yaf_Route_Rewrite::__construct — Yaf_Route_Rewrite constructor

Description

public Yaf_Route_Rewrite::__construct ( string $match , array $route [, array $verify ] )

Parameters

match

A pattern, will be used to match a request uri, if it doesn't match, Yaf_Route_Rewrite will return FALSE.

You can use :name style to name segments matched, and use * to match the rest of the URL segments.

route

When the match pattern matches the request uri, Yaf_Route_Rewrite will use this to decide which module/controller/action is the destination.

Either of module/controller/action in this array is optional, if you don't assign a specific value, it will be routed to default.

verify

Return Values

Examples

Example #1 Yaf_Route_Rewrite()example

<?php
   /**
    * Add a rewrite route to Yaf_Router route stack
    */
    Yaf_Dispatcher::getInstance()->getRouter()->addRoute("name",
        new Yaf_Route_rewrite(
           "/product/:name/:id/*", //match request uri leading "/product"
           array(
               'controller' => "product",  //route to product controller,
           ),
        )
    );
?>

The above example will output something similar to:

/* for http://yourdomain.com/product/foo/22/foo/bar
 * route will result in following values:
 */
array(
  "controller" => "product",
  "module"     => "index", //(default)
  "action"     => "index", //(default)
)

/**
 * and request parameters:
 */
array(
  "name" => "foo",
  "id"   => 22,
  "foo"  => bar
)

Example #2 Yaf_Route_Rewrite()example

<?php
   /**
    * Add a rewrite route to Yaf_Router route stack by calling addconfig
    */
    $config = array(
        "name" => array(
           "type"  => "rewrite",        //Yaf_Route_Rewrite route
           "match" => "/user-list/:id", //match only /user/list/?/
           "route" => array(
               'controller' => "user",  //route to user controller,
               'action'     => "list",  //route to list action
           ),
        ),
    );
    Yaf_Dispatcher::getInstance()->getRouter()->addConfig(
        new Yaf_Config_Simple($config));
?>

The above example will output something similar to:

/* for http://yourdomain.com/user-list/22
 * route will result in following values:
 */
array(
  "controller" => "user",
  "action"     => "list",
  "module"     => "index", //(default)
)

/**
 * and request parameters:
 */
array(
  "id"   => 22,
)

Example #3 Yaf_Route_Rewrite(as of 2.3.0)()example

<?php
   /**
    * Add a rewrite route use match result as m/c/a name
    */
    $config = array(
        "name" => array(
           "type"  => "rewrite",
           "match" => "/user-list/:a/:id", //match only /user-list/*
           "route" => array(
               'controller' => "user",   //route to user controller,
               'action'     => ":a",     //route to :a action
           ),
        ),
    );
    Yaf_Dispatcher::getInstance()->getRouter()->addConfig(
        new Yaf_Config_Simple($config));
?>

The above example will output something similar to:

/* for http://yourdomain.com/user-list/list/22
 * route will result in following values:
 */
array(
  "controller" => "user",
  "action"     => "list",
  "module"     => "index", //(default)
)

/**
 * and request parameters:
 */
array(
  "id"   => 22,
)

See Also

  • Yaf_Router::addRoute() - Add new Route into Router
  • Yaf_Router::addConfig() - Add config-defined routes into Router
  • Yaf_Route_Static
  • Yaf_Route_Supervar
  • Yaf_Route_Simple
  • Yaf_Route_Regex
  • Yaf_Route_Map


The route purpose

  • « Yaf_Route_Rewrite::__construct
  • Yaf_Router »
  • PHP Manual
  • Yaf_Route_Rewrite
  • The route purpose

Yaf_Route_Rewrite::route

(Yaf >=1.0.0)

Yaf_Route_Rewrite::route — The route purpose

Description

public Yaf_Route_Rewrite::route ( Yaf_Request_Abstract $request ) : bool

Parameters

request

Return Values


The Yaf_Router class

(Yaf >=1.0.0)

Introduction

Yaf_Router is the standard framework router. Routing is the process of taking a URI endpoint (that part of the URI which comes after the base URI: see Yaf_Request_Abstract::setBaseUri()) and decomposing it into parameters to determine which module, controller, and action of that controller should receive the request. This values of the module, controller, action and other parameters are packaged into a Yaf_Request_Abstract object which is then processed by Yaf_Dispatcher. Routing occurs only once: when the request is initially received and before the first controller is dispatched. Yaf_Router is designed to allow for mod_rewrite-like functionality using pure PHP structures. It is very loosely based on Ruby on Rails routing and does not require any prior knowledge of webserver URL rewriting. It is designed to work with a single Apache mod_rewrite rule (one of):

Example #1 Rewrite rule for Apache

RewriteEngine on
RewriteRule !\.(js|ico|gif|jpg|png|css|html)$ index.php
or (preferred):

Example #2 Rewrite rule for Apache

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
If using Lighttpd, the following rewrite rule is valid:

Example #3 Rewrite rule for Lighttpd

url.rewrite-once = (
  ".*\?(.*)$" => "/index.php?$1",
  ".*\.(js|ico|gif|jpg|png|css|html)$" => "$0",
  "" => "/index.php"
)
If using Nginx, use the following rewrite rule:

Example #4 Rewrite rule for Nginx

server {
  listen ****;
  server_name  yourdomain.com;
  root   document_root;
  index  index.php index.html;

  if (!-e $request_filename) {
    rewrite ^/(.*)  /index.php/$1 last;
  }
}

Default route

Yaf_Router comes preconfigured with a default route Yaf_Route_Static, which will match URIs in the shape of controller/action. Additionally, a module name may be specified as the first path element, allowing URIs of the form module/controller/action. Finally, it will also match any additional parameters appended to the URI by default - controller/action/var1/value1/var2/value2.

Note:

Module name must be defined in config, considering application.module="Index,Foo,Bar", in this case, only index, foo and bar can be considered as a module name. if doesn't config, there is only one module named "Index".

Some examples of how such routes are matched:

Example #5 Yaf_Route_Static(default route)example

// Assuming the following configure:
$conf = array(
   "application" => array(
      "modules" => "Index,Blog",
   ),
);

Controller only:
http://example/news
    controller == news
Action only(when defined yaf.action_prefer=1 in php.ini)
    action  == news

Invalid module maps to controller name:
http://example/foo
    controller == foo

Module + controller:
http://example/blog/archive
    module     == blog
    controller == archive

Module + controller + action:
http://example/blog/archive/list
    module     == blog
    controller == archive
    action     == list

Module + controller + action + params:
http://example/blog/archive/list/sort/alpha/date/desc
    module     == blog
    controller == archive
    action     == list
    sort       == alpha
    date       == desc

Class synopsis

Yaf_Router {
/* Properties */
protected $_routes ;
protected $_current ;
/* Methods */
public addConfig ( Yaf_Config_Abstract $config ) : bool
public addRoute ( string $name , Yaf_Route_Abstract $route ) : bool
public __construct ( void )
public getCurrentRoute ( void ) : string
public getRoute ( string $name ) : Yaf_Route_Interface
public getRoutes ( void ) : mixed
public route ( Yaf_Request_Abstract $request ) : bool
}

Properties

_routes

registered routes stack

_current

after routing phase, this indicated the name of which route is used to route current request. you can get this name by Yaf_Router::getCurrentRoute().

Table of Contents

  • Yaf_Router::addConfig — Add config-defined routes into Router
  • Yaf_Router::addRoute — Add new Route into Router
  • Yaf_Router::__construct — Yaf_Router constructor
  • Yaf_Router::getCurrentRoute — Get the effective route name
  • Yaf_Router::getRoute — Retrieve a route by name
  • Yaf_Router::getRoutes — Retrieve registered routes
  • Yaf_Router::route — The route purpose


Add config-defined routes into Router

  • « Yaf_Router
  • Yaf_Router::addRoute »
  • PHP Manual
  • Yaf_Router
  • Add config-defined routes into Router

Yaf_Router::addConfig

(Yaf >=1.0.0)

Yaf_Router::addConfig — Add config-defined routes into Router

Description

public Yaf_Router::addConfig ( Yaf_Config_Abstract $config ) : bool

Add routes defined by configs into Yaf_Router's route stack

Parameters

This function has no parameters.

Return Values

An Yaf_Config_Abstract instance, which should contains one or more valid route configs

Examples

Example #1 application.ini()example

;the order is very important, the prior one will be called first

;a rewrite route match request /product/*/*
routes.route_name.type="rewrite"
routes.route_name.match="/product/:name/:value"
routes.route_name.route.controller=product
routes.route_name.route.action=info

;a regex route match request /list/*/*
routes.route_name1.type="regex"
routes.route_name1.match="#^list/([^/]*)/([^/]*)#"
routes.route_name1.route.controller=Index
routes.route_name1.route.action=action
routes.route_name1.map.1=name
routes.route_name1.map.2=value

;a simple route match /**?c=controller&a=action&m=module
routes.route_name2.type="simple"
routes.route_name2.controller=c
routes.route_name2.module=m
routes.route_name2.action=a

;a simple router match /**?r=PATH_INFO
routes.route_name3.type="supervar"
routes.route_name3.varname=r

;a map route match any request to controller
routes.route_name4.type="map"
routes.route_name4.controllerPrefer=TRUE
routes.route_namer.delimiter="#!"

Example #2 Yaf_Dispatcher::autoConfig()example

<?php
class Bootstrap extends Yaf_Bootstrap_Abstract{
    public function _initConfig() {
        $config = Yaf_Application::app()->getConfig();
        Yaf_Registry::set("config", $config);
    }

    public function _initRoute(Yaf_Dispatcher $dispatcher) {
        $router = $dispatcher->getRouter();
        /**
         * we can add some pre-defined routes in application.ini
         */
        $router->addConfig(Yaf_Registry::get("config")->routes);
    }
?>

See Also

  • Yaf_Router::addRoute() - Add new Route into Router
  • Yaf_Route_Static
  • Yaf_Route_Supervar
  • Yaf_Route_Simple
  • Yaf_Route_Regex
  • Yaf_Route_Rewrite
  • Yaf_Route_Map


Add new Route into Router

  • « Yaf_Router::addConfig
  • Yaf_Router::__construct »
  • PHP Manual
  • Yaf_Router
  • Add new Route into Router

Yaf_Router::addRoute

(Yaf >=1.0.0)

Yaf_Router::addRoute — Add new Route into Router

Description

public Yaf_Router::addRoute ( string $name , Yaf_Route_Abstract $route ) : bool

defaultly, Yaf_Router using a Yaf_Route_Static as its defualt route. you can add new routes into router's route stack by calling this method.

the newer route will be called before the older(route stack), and if the newer router return TRUE, the router process will be end. otherwise, the older one will be called.

Parameters

This function has no parameters.

Return Values

Examples

Example #1 Yaf_Dispatcher::autoRender()example

<?php
class Bootstrap extends Yaf_Bootstrap_Abstract{
    public function _initConfig() {
        $config = Yaf_Application::app()->getConfig();
        Yaf_Registry::set("config", $config);
    }

    public function _initRoute(Yaf_Dispatcher $dispatcher) {
        $router = $dispatcher->getRouter();
        /**
         * we can add some pre-defined routes in application.ini
         */
        $router->addConfig(Yaf_Registry::get("config")->routes);
        /**
         * add a Rewrite route, then for a request uri:
         * http://***/product/list/22/foo
         * will be matched by this route, and result:
         *
         *  [module] =>
         *  [controller] => product
         *  [action] => info
         *  [method] => GET
         *  [params:protected] => Array
         *      (
         *          [id] => 22
         *          [name] => foo
         *      )
         *
         */
        $route  = new Yaf_Route_Rewrite(
            "/product/list/:id/:name",
            array(
                "controller" => "product",
                "action"     => "info",
            )
        );

        $router->addRoute('dummy', $route);
    }
?>

See Also

  • Yaf_Router::addConfig() - Add config-defined routes into Router
  • Yaf_Route_Static
  • Yaf_Route_Supervar
  • Yaf_Route_Simple
  • Yaf_Route_Regex
  • Yaf_Route_Rewrite
  • Yaf_Route_Map


Yaf_Router constructor

  • « Yaf_Router::addRoute
  • Yaf_Router::getCurrentRoute »
  • PHP Manual
  • Yaf_Router
  • Yaf_Router constructor

Yaf_Router::__construct

(Yaf >=1.0.0)

Yaf_Router::__construct — Yaf_Router constructor

Description

public Yaf_Router::__construct ( void )

Parameters

This function has no parameters.

Return Values


Get the effective route name

  • « Yaf_Router::__construct
  • Yaf_Router::getRoute »
  • PHP Manual
  • Yaf_Router
  • Get the effective route name

Yaf_Router::getCurrentRoute

(Yaf >=1.0.0)

Yaf_Router::getCurrentRoute — Get the effective route name

Description

public Yaf_Router::getCurrentRoute ( void ) : string

Get the name of the route which is effective in the route process.

Note:

You should call this method after the route process finished, since before that, this method will always return NULL.

Parameters

This function has no parameters.

Return Values

String, the name of the effective route.

Examples

Example #1 Register some routes in Bootstrap

<?php
class Bootstrap extends Yaf_Bootstrap_Abstract{
    public function _initConfig() {
        $config = Yaf_Application::app()->getConfig();
        Yaf_Registry::set("config", $config);
    }

    public function _initRoute(Yaf_Dispatcher $dispatcher) {
        $router = $dispatcher->getRouter();
        $rewrite_route  = new Yaf_Route_Rewrite(
            "/product/list/:page",
            array(
                "controller" => "product",
                "action"     => "list",
            )
        );

        $regex_route  = new Yaf_Route_Rewrite(
            "#^/product/info/(\d+)",
            array(
                "controller" => "product",
                "action"     => "info",
            )
        );

        $router->addRoute('rewrite', $rewrite_route)->addRoute('regex', $regex_route);
    }

    /**
     * register plugin
     */
    public function __initPlugins(Yaf_Dispatcher $dispatcher) {
        $dispatcher->registerPlugin(new DummyPlugin());
    }
?>

Example #2 plugin Dummy.php (under application.directory/plugins)

<?php
class DummyPlugin extends Yaf_Plugin_Abstract {

    public function routerShutdown(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
         var_dump(Yaf_Dispatcher::getInstance()->getRouter()->getCurrentRoute());
    }
?>
?>

The above example will output something similar to:

/* for http://yourdomain.com/product/list/1
 * DummyPlugin will output:
 */
string(7) "rewrite"

/* for http://yourdomain.com/product/info/34
 * DummyPlugin will output:
 */
string(5) "regex"

/* for other request URI
 * DummyPlugin will output:
 */
string(8) "_default"

See Also

  • Yaf_Bootstrap_Abstract
  • Yaf_Plugin_Abstract
  • Yaf_Router::addRoute() - Add new Route into Router


Retrieve a route by name

  • « Yaf_Router::getCurrentRoute
  • Yaf_Router::getRoutes »
  • PHP Manual
  • Yaf_Router
  • Retrieve a route by name

Yaf_Router::getRoute

(Yaf >=1.0.0)

Yaf_Router::getRoute — Retrieve a route by name

Description

public Yaf_Router::getRoute ( string $name ) : Yaf_Route_Interface

Retrieve a route by name, see also Yaf_Router::getCurrentRoute()

Parameters

This function has no parameters.

Return Values

See Also

  • Yaf_Bootstrap_Abstract
  • Yaf_Plugin_Abstract
  • Yaf_Router::addRoute() - Add new Route into Router
  • Yaf_Router::getCurrentRoute() - Get the effective route name


Retrieve registered routes

  • « Yaf_Router::getRoute
  • Yaf_Router::route »
  • PHP Manual
  • Yaf_Router
  • Retrieve registered routes

Yaf_Router::getRoutes

(Yaf >=1.0.0)

Yaf_Router::getRoutes — Retrieve registered routes

Description

public Yaf_Router::getRoutes ( void ) : mixed

Retrieve registered routes

Parameters

This function has no parameters.

Return Values


The route purpose

  • « Yaf_Router::getRoutes
  • Yaf_Route_Simple »
  • PHP Manual
  • Yaf_Router
  • The route purpose

Yaf_Router::route

(Yaf >=1.0.0)

Yaf_Router::route — The route purpose

Description

public Yaf_Router::route ( Yaf_Request_Abstract $request ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The Yaf_Route_Simple class

(Yaf >=1.0.0)

Introduction

Yaf_Route_Simple will match the query string, and find the route info.

all you need to do is tell Yaf_Route_Simple what key in the $_GET is module, what key is controller, and what key is action.

Yaf_Route_Simple::route() will always return TRUE, so it is important put Yaf_Route_Simple in the front of the Route stack, otherwise all the other routes will not be called.

Class synopsis

Yaf_Route_Simple implements Yaf_Route_Interface {
/* Properties */
protected $controller ;
protected $module ;
protected $action ;
/* Methods */
public assemble ( array $info [, array $query ] ) : string
public __construct ( string $module_name , string $controller_name , string $action_name )
public route ( Yaf_Request_Abstract $request ) : bool
}

Properties

controller

module

action

Table of Contents

  • Yaf_Route_Simple::assemble — Assemble a url
  • Yaf_Route_Simple::__construct — Yaf_Route_Simple constructor
  • Yaf_Route_Simple::route — Route a request


Assemble a url

  • « Yaf_Route_Simple
  • Yaf_Route_Simple::__construct »
  • PHP Manual
  • Yaf_Route_Simple
  • Assemble a url

Yaf_Route_Simple::assemble

(Yaf >=2.3.0)

Yaf_Route_Simple::assemble — Assemble a url

Description

public Yaf_Route_Simple::assemble ( array $info [, array $query ] ) : string

Assemble a url.

Parameters

info

query

Examples

Example #1 Yaf_Route_Simple::assemble()example

<?php

$router = new Yaf_Router();

$route  = new Yaf_Route_Simple('m', 'c', 'a');

$router->addRoute("simple", $route);

var_dump($router->getRoute('simple')->assemble(
            array(
                ':a' => 'yafaction',
                'tkey' => 'tval',
                ':c' => 'yafcontroller',
                ':m' => 'yafmodule'
                ),
            array(
                'tkey1' => 'tval1',
                'tkey2' => 'tval2'
                )
            ));

The above example will output something similar to:

string(64) "?m=yafmodule&c=yafcontroller&a=yafaction&tkey1=tval1&tkey2=tval2"

Return Values


Yaf_Route_Simple constructor

  • « Yaf_Route_Simple::assemble
  • Yaf_Route_Simple::route »
  • PHP Manual
  • Yaf_Route_Simple
  • Yaf_Route_Simple constructor

Yaf_Route_Simple::__construct

(Yaf >=1.0.0)

Yaf_Route_Simple::__construct — Yaf_Route_Simple constructor

Description

public Yaf_Route_Simple::__construct ( string $module_name , string $controller_name , string $action_name )

Yaf_Route_Simple will get route info from query string. and the parameters of this constructor will used as keys while searching for the route info in $_GET.

Warning

This function is currently not documented; only its argument list is available.

Parameters

module_name

The key name of the module info.

controller_name

the key name of the controller info.

action_name

the key name of the action info.

Return Values

Always return TRUE.

Examples

Example #1 Yaf_Route_Simple::route()example

<?php
   $route = new Yaf_Route_Simple("m", "controller", "act");
   Yaf_Router::getInstance()->addRoute("simple", $route);
?>

Example #2 Yaf_Route_Simple::route()example

Request: http://yourdomain.com/path/?controller=a&act=b
=> module = default(index), controller = a, action = b

Request: http://yourdomain.com/path
=> module = default(index), controller = default(index), action = default(index)

See Also

  • Yaf_Route_Supervar::route() - The route purpose
  • Yaf_Route_Static::route() - Route a request
  • Yaf_Route_Regex::route() - The route purpose
  • Yaf_Route_Rewrite::route() - The route purpose
  • Yaf_Route_Map::route() - The route purpose


Route a request

  • « Yaf_Route_Simple::__construct
  • Yaf_Route_Static »
  • PHP Manual
  • Yaf_Route_Simple
  • Route a request

Yaf_Route_Simple::route

(Yaf >=1.0.0)

Yaf_Route_Simple::route — Route a request

Description

public Yaf_Route_Simple::route ( Yaf_Request_Abstract $request ) : bool

see Yaf_Route_Simple::__construct()

Warning

This function is currently not documented; only its argument list is available.

Parameters

request

Return Values

always be TRUE

See Also

  • Yaf_Route_Supervar::route() - The route purpose
  • Yaf_Route_Static::route() - Route a request
  • Yaf_Route_Regex::route() - The route purpose
  • Yaf_Route_Rewrite::route() - The route purpose
  • Yaf_Route_Map::route() - The route purpose


The Yaf_Route_Static class

(Yaf >=1.0.0)

Introduction

Defaultly, Yaf_Router only have a Yaf_Route_Static as its default route.

And Yaf_Route_Static is designed to handle the 80% requirement.

please *NOTE* that it is unnecessary to instance a Yaf_Route_Static, also unecesary to add it into Yaf_Router's routes stack, since there is always be one in Yaf_Router's routes stack, and always be called at the last time.

Class synopsis

Yaf_Route_Static implements Yaf_Router {
/* Methods */
public assemble ( array $info [, array $query ] ) : string
public match ( string $uri ) : void
public route ( Yaf_Request_Abstract $request ) : bool
}

Table of Contents

  • Yaf_Route_Static::assemble — Assemble a url
  • Yaf_Route_Static::match — The match purpose
  • Yaf_Route_Static::route — Route a request


Assemble a url

  • « Yaf_Route_Static
  • Yaf_Route_Static::match »
  • PHP Manual
  • Yaf_Route_Static
  • Assemble a url

Yaf_Route_Static::assemble

(Yaf >=2.3.0)

Yaf_Route_Static::assemble — Assemble a url

Description

public Yaf_Route_Static::assemble ( array $info [, array $query ] ) : string

Assemble a url.

Parameters

info

query

Examples

Example #1 Yaf_Route_Static::assemble()example

<?php

$router = new Yaf_Router();

$route  = new Yaf_Route_Static();

$router->addRoute("static", $route);

var_dump($router->getRoute('static')->assemble(
            array(
                ':a' => 'yafaction',
                'tkey' => 'tval',
                ':c' => 'yafcontroller',
                ':m' => 'yafmodule'
            ),
        )
);

var_dump($router->getRoute('static')->assemble(
            array(
                ':a' => 'yafaction',
                'tkey' => 'tval',
                ':c' => 'yafcontroller',
                ':m' => 'yafmodule'
            ),
            array(
                'tkey1' => 'tval1',
                'tkey2' => 'tval2'
            )
        )
);

The above example will output something similar to:

string(%d) "/yafmodule/yafcontroller/yafaction"
string(%d) "/yafmodule/yafcontroller/yafaction?tkey1=tval1&tkey2=tval2"

Return Values


The match purpose

  • « Yaf_Route_Static::assemble
  • Yaf_Route_Static::route »
  • PHP Manual
  • Yaf_Route_Static
  • The match purpose

Yaf_Route_Static::match

(Yaf >=1.0.0)

Yaf_Route_Static::match — The match purpose

Description

public Yaf_Route_Static::match ( string $uri ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

uri

Return Values


Route a request

  • « Yaf_Route_Static::match
  • Yaf_Route_Supervar »
  • PHP Manual
  • Yaf_Route_Static
  • Route a request

Yaf_Route_Static::route

(Yaf >=1.0.0)

Yaf_Route_Static::route — Route a request

Description

public Yaf_Route_Static::route ( Yaf_Request_Abstract $request ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

request

Return Values

always be TRUE

Examples

Example #1 Yaf_Route_Static::route()example

// assuming there is only one module defined:Index
Request: http://yourdomain.com/a/b
=> module = index, controller=a, action=b

//assuming ap.action_prefer = On
Request: http://yourdomain.com/b
=> module = default(index), controller = default(index), action = b

//assuming ap.action_prefer = Off
Request: http://yourdomain.com/b
=> module = default(index), controller = b, action = default(index)

Request: http://yourdomain.com/a/b/foo/bar/test/a/id/4
=> module = default(index), controller = a, action = b, request parameters: foo = bar, test = a, id = 4

See Also

  • Yaf_Route_Supervar::route() - The route purpose
  • Yaf_Route_Simple::route() - Route a request
  • Yaf_Route_Regex::route() - The route purpose
  • Yaf_Route_Rewrite::route() - The route purpose
  • Yaf_Route_Map::route() - The route purpose


The Yaf_Route_Supervar class

(Yaf >=1.0.0)

Introduction

Class synopsis

Yaf_Route_Supervar implements Yaf_Route_Interface {
/* Properties */
protected $_var_name ;
/* Methods */
public assemble ( array $info [, array $query ] ) : string
public __construct ( string $supervar_name )
public route ( Yaf_Request_Abstract $request ) : bool
}

Properties

_var_name

Table of Contents

  • Yaf_Route_Supervar::assemble — Assemble a url
  • Yaf_Route_Supervar::__construct — The __construct purpose
  • Yaf_Route_Supervar::route — The route purpose


Assemble a url

  • « Yaf_Route_Supervar
  • Yaf_Route_Supervar::__construct »
  • PHP Manual
  • Yaf_Route_Supervar
  • Assemble a url

Yaf_Route_Supervar::assemble

(Yaf >=2.3.0)

Yaf_Route_Supervar::assemble — Assemble a url

Description

public Yaf_Route_Supervar::assemble ( array $info [, array $query ] ) : string

Assemble a url.

Parameters

info

query

Examples

Example #1 Yaf_Route_Supervar::assemble()example

<?php

$router = new Yaf_Router();

$route  = new Yaf_Route_Supervar('r');

$router->addRoute("supervar", $route);

var_dump($router->getRoute('supervar')->assemble(
        array(
              ':a' => 'yafaction',
              'tkey' => 'tval',
              ':c' => 'yafcontroller',
              ':m' => 'yafmodule'
        ),
        array(
              'tkey1' => 'tval1',
              'tkey2' => 'tval2'
        )
));

try {
var_dump($router->getRoute('supervar')->assemble(
        array(
              ':a' => 'yafaction',
              'tkey' => 'tval',
              ':m' => 'yafmodule'
        ),
        array(
              'tkey1' => 'tval1',
              'tkey2' => 'tval2',
              1 => array(),
        )
));
} catch (Exception $e) {
    var_dump($e->getMessage());
}

The above example will output something similar to:

string(%d) "?r=/yafmodule/yafcontroller/yafaction&tkey1=tval1&tkey2=tval2"
string(%d) "You need to specify the controller by ':c'"

Return Values


The __construct purpose

  • « Yaf_Route_Supervar::assemble
  • Yaf_Route_Supervar::route »
  • PHP Manual
  • Yaf_Route_Supervar
  • The __construct purpose

Yaf_Route_Supervar::__construct

(Yaf >=1.0.0)

Yaf_Route_Supervar::__construct — The __construct purpose

Description

public Yaf_Route_Supervar::__construct ( string $supervar_name )

Yaf_Route_Supervar is similar with Yaf_Route_Static, the difference is Yaf_Route_Supervar will look for path info in query string, and the parameter supervar_name is the key.

Parameters

supervar_name

The name of key.

Return Values

Examples

Example #1 Yaf_Route_Supervar()example

<?php
   /**
    * Add a supervar route to Yaf_Router route stack
    */
    Yaf_Dispatcher::getInstance()->getRouter()->addRoute("name",
        new Yaf_Route_Supervar("r"));
    );
?>

The above example will output something similar to:

/** for request: http://yourdomain.com/xx/oo/?r=/ctr/act/var/value
  * will result in following:
  */
  array (
    "module"   => index(default),
    "controller" => ctr,
    "action"     => act,
    "params"     => array(
          "var" => value,
     )
  )

See Also

  • Yaf_Router::addRoute() - Add new Route into Router
  • Yaf_Router::addConfig() - Add config-defined routes into Router
  • Yaf_Route_Static
  • Yaf_Route_Regex
  • Yaf_Route_Simple
  • Yaf_Route_Rewrite
  • Yaf_Route_Map


The route purpose

  • « Yaf_Route_Supervar::__construct
  • Yaf_Session »
  • PHP Manual
  • Yaf_Route_Supervar
  • The route purpose

Yaf_Route_Supervar::route

(Yaf >=1.0.0)

Yaf_Route_Supervar::route — The route purpose

Description

public Yaf_Route_Supervar::route ( Yaf_Request_Abstract $request ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

request

Return Values

If there is a key(which was defined in Yaf_Route_Supervar::__construct()) in $_GET, return TRUE. otherwise return FALSE.


The Yaf_Session class

(Yaf >=1.0.0)

Introduction

Class synopsis

Yaf_Session implements Iterator , ArrayAccess , Countable {
/* Properties */
protected static $_instance ;
protected $_session ;
protected $_started ;
/* Methods */
private __clone ( void ) : void
private __construct ( void )
public count ( void ) : void
public current ( void ) : void
public del ( string $name ) : void
public __get ( string $name ) : void
public static getInstance ( void ) : void
public has ( string $name ) : void
public __isset ( string $name ) : void
public key ( void ) : void
public next ( void ) : void
public offsetExists ( string $name ) : void
public offsetGet ( string $name ) : void
public offsetSet ( string $name , string $value ) : void
public offsetUnset ( string $name ) : void
public rewind ( void ) : void
public __set ( string $name , string $value ) : void
private __sleep ( void ) : void
public start ( void ) : void
public __unset ( string $name ) : void
public valid ( void ) : void
private __wakeup ( void ) : void
}

Properties

_instance

_session

_started

Table of Contents

  • Yaf_Session::__clone — The __clone purpose
  • Yaf_Session::__construct — Constructor of Yaf_Session
  • Yaf_Session::count — The count purpose
  • Yaf_Session::current — The current purpose
  • Yaf_Session::del — The del purpose
  • Yaf_Session::__get — The __get purpose
  • Yaf_Session::getInstance — The getInstance purpose
  • Yaf_Session::has — The has purpose
  • Yaf_Session::__isset — The __isset purpose
  • Yaf_Session::key — The key purpose
  • Yaf_Session::next — The next purpose
  • Yaf_Session::offsetExists — The offsetExists purpose
  • Yaf_Session::offsetGet — The offsetGet purpose
  • Yaf_Session::offsetSet — The offsetSet purpose
  • Yaf_Session::offsetUnset — The offsetUnset purpose
  • Yaf_Session::rewind — The rewind purpose
  • Yaf_Session::__set — The __set purpose
  • Yaf_Session::__sleep — The __sleep purpose
  • Yaf_Session::start — The start purpose
  • Yaf_Session::__unset — The __unset purpose
  • Yaf_Session::valid — The valid purpose
  • Yaf_Session::__wakeup — The __wakeup purpose


The __clone purpose

  • « Yaf_Session
  • Yaf_Session::__construct »
  • PHP Manual
  • Yaf_Session
  • The __clone purpose

Yaf_Session::__clone

(Yaf >=1.0.0)

Yaf_Session::__clone — The __clone purpose

Description

private Yaf_Session::__clone ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Constructor of Yaf_Session

  • « Yaf_Session::__clone
  • Yaf_Session::count »
  • PHP Manual
  • Yaf_Session
  • Constructor of Yaf_Session

Yaf_Session::__construct

(Yaf >=1.0.0)

Yaf_Session::__construct — Constructor of Yaf_Session

Description

private Yaf_Session::__construct ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The count purpose

  • « Yaf_Session::__construct
  • Yaf_Session::current »
  • PHP Manual
  • Yaf_Session
  • The count purpose

Yaf_Session::count

(Yaf >=1.0.0)

Yaf_Session::count — The count purpose

Description

public Yaf_Session::count ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The current purpose

  • « Yaf_Session::count
  • Yaf_Session::del »
  • PHP Manual
  • Yaf_Session
  • The current purpose

Yaf_Session::current

(Yaf >=1.0.0)

Yaf_Session::current — The current purpose

Description

public Yaf_Session::current ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The del purpose

  • « Yaf_Session::current
  • Yaf_Session::__get »
  • PHP Manual
  • Yaf_Session
  • The del purpose

Yaf_Session::del

(Yaf >=1.0.0)

Yaf_Session::del — The del purpose

Description

public Yaf_Session::del ( string $name ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values


The __get purpose

  • « Yaf_Session::del
  • Yaf_Session::getInstance »
  • PHP Manual
  • Yaf_Session
  • The __get purpose

Yaf_Session::__get

(Yaf >=1.0.0)

Yaf_Session::__get — The __get purpose

Description

public Yaf_Session::__get ( string $name ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values


The getInstance purpose

  • « Yaf_Session::__get
  • Yaf_Session::has »
  • PHP Manual
  • Yaf_Session
  • The getInstance purpose

Yaf_Session::getInstance

(Yaf >=1.0.0)

Yaf_Session::getInstance — The getInstance purpose

Description

public static Yaf_Session::getInstance ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The has purpose

  • « Yaf_Session::getInstance
  • Yaf_Session::__isset »
  • PHP Manual
  • Yaf_Session
  • The has purpose

Yaf_Session::has

(Yaf >=1.0.0)

Yaf_Session::has — The has purpose

Description

public Yaf_Session::has ( string $name ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values


The __isset purpose

  • « Yaf_Session::has
  • Yaf_Session::key »
  • PHP Manual
  • Yaf_Session
  • The __isset purpose

Yaf_Session::__isset

(Yaf >=1.0.0)

Yaf_Session::__isset — The __isset purpose

Description

public Yaf_Session::__isset ( string $name ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values


The key purpose

  • « Yaf_Session::__isset
  • Yaf_Session::next »
  • PHP Manual
  • Yaf_Session
  • The key purpose

Yaf_Session::key

(Yaf >=1.0.0)

Yaf_Session::key — The key purpose

Description

public Yaf_Session::key ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The next purpose

  • « Yaf_Session::key
  • Yaf_Session::offsetExists »
  • PHP Manual
  • Yaf_Session
  • The next purpose

Yaf_Session::next

(Yaf >=1.0.0)

Yaf_Session::next — The next purpose

Description

public Yaf_Session::next ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The offsetExists purpose

  • « Yaf_Session::next
  • Yaf_Session::offsetGet »
  • PHP Manual
  • Yaf_Session
  • The offsetExists purpose

Yaf_Session::offsetExists

(Yaf >=1.0.0)

Yaf_Session::offsetExists — The offsetExists purpose

Description

public Yaf_Session::offsetExists ( string $name ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values


The offsetGet purpose

  • « Yaf_Session::offsetExists
  • Yaf_Session::offsetSet »
  • PHP Manual
  • Yaf_Session
  • The offsetGet purpose

Yaf_Session::offsetGet

(Yaf >=1.0.0)

Yaf_Session::offsetGet — The offsetGet purpose

Description

public Yaf_Session::offsetGet ( string $name ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values


The offsetSet purpose

  • « Yaf_Session::offsetGet
  • Yaf_Session::offsetUnset »
  • PHP Manual
  • Yaf_Session
  • The offsetSet purpose

Yaf_Session::offsetSet

(Yaf >=1.0.0)

Yaf_Session::offsetSet — The offsetSet purpose

Description

public Yaf_Session::offsetSet ( string $name , string $value ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

value

Return Values


The offsetUnset purpose

  • « Yaf_Session::offsetSet
  • Yaf_Session::rewind »
  • PHP Manual
  • Yaf_Session
  • The offsetUnset purpose

Yaf_Session::offsetUnset

(Yaf >=1.0.0)

Yaf_Session::offsetUnset — The offsetUnset purpose

Description

public Yaf_Session::offsetUnset ( string $name ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values


The rewind purpose

  • « Yaf_Session::offsetUnset
  • Yaf_Session::__set »
  • PHP Manual
  • Yaf_Session
  • The rewind purpose

Yaf_Session::rewind

(Yaf >=1.0.0)

Yaf_Session::rewind — The rewind purpose

Description

public Yaf_Session::rewind ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The __set purpose

  • « Yaf_Session::rewind
  • Yaf_Session::__sleep »
  • PHP Manual
  • Yaf_Session
  • The __set purpose

Yaf_Session::__set

(Yaf >=1.0.0)

Yaf_Session::__set — The __set purpose

Description

public Yaf_Session::__set ( string $name , string $value ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

value

Return Values


The __sleep purpose

  • « Yaf_Session::__set
  • Yaf_Session::start »
  • PHP Manual
  • Yaf_Session
  • The __sleep purpose

Yaf_Session::__sleep

(Yaf >=1.0.0)

Yaf_Session::__sleep — The __sleep purpose

Description

private Yaf_Session::__sleep ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The start purpose

  • « Yaf_Session::__sleep
  • Yaf_Session::__unset »
  • PHP Manual
  • Yaf_Session
  • The start purpose

Yaf_Session::start

(Yaf >=1.0.0)

Yaf_Session::start — The start purpose

Description

public Yaf_Session::start ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The __unset purpose

  • « Yaf_Session::start
  • Yaf_Session::valid »
  • PHP Manual
  • Yaf_Session
  • The __unset purpose

Yaf_Session::__unset

(Yaf >=1.0.0)

Yaf_Session::__unset — The __unset purpose

Description

public Yaf_Session::__unset ( string $name ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values


The valid purpose

  • « Yaf_Session::__unset
  • Yaf_Session::__wakeup »
  • PHP Manual
  • Yaf_Session
  • The valid purpose

Yaf_Session::valid

(Yaf >=1.0.0)

Yaf_Session::valid — The valid purpose

Description

public Yaf_Session::valid ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The __wakeup purpose

  • « Yaf_Session::valid
  • Yaf_Exception »
  • PHP Manual
  • Yaf_Session
  • The __wakeup purpose

Yaf_Session::__wakeup

(Yaf >=1.0.0)

Yaf_Session::__wakeup — The __wakeup purpose

Description

private Yaf_Session::__wakeup ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The Yaf_Exception class

(Yaf >=1.0.0)

Introduction

Class synopsis

Yaf_Exception extends Exception {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Methods */
public __construct ( void )
public getPrevious ( void ) : void
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}

Table of Contents

  • Yaf_Exception::__construct — The __construct purpose
  • Yaf_Exception::getPrevious — The getPrevious purpose


The __construct purpose

  • « Yaf_Exception
  • Yaf_Exception::getPrevious »
  • PHP Manual
  • Yaf_Exception
  • The __construct purpose

Yaf_Exception::__construct

(Yaf >=1.0.0)

Yaf_Exception::__construct — The __construct purpose

Description

public Yaf_Exception::__construct ( void )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The getPrevious purpose

  • « Yaf_Exception::__construct
  • Yaf_Exception_TypeError »
  • PHP Manual
  • Yaf_Exception
  • The getPrevious purpose

Yaf_Exception::getPrevious

(Yaf >=1.0.0)

Yaf_Exception::getPrevious — The getPrevious purpose

Description

public Yaf_Exception::getPrevious ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The Yaf_Exception_TypeError class

(Yaf >=1.0.0)

Introduction

Class synopsis

Yaf_Exception_TypeError extends Yaf_Exception {
/* Properties */
/* Methods */
/* Inherited methods */
public Yaf_Exception::__construct ( void )
public Yaf_Exception::getPrevious ( void ) : void
}


The Yaf_Exception_StartupError class

(Yaf >=1.0.0)

Introduction

Class synopsis

Yaf_Exception_StartupError extends Yaf_Exception {
/* Properties */
/* Methods */
/* Inherited methods */
public Yaf_Exception::__construct ( void )
public Yaf_Exception::getPrevious ( void ) : void
}


The Yaf_Exception_DispatchFailed class

(Yaf >=1.0.0)

Introduction

Class synopsis

Yaf_Exception_DispatchFailed extends Yaf_Exception {
/* Properties */
/* Methods */
/* Inherited methods */
public Yaf_Exception::__construct ( void )
public Yaf_Exception::getPrevious ( void ) : void
}


The Yaf_Exception_RouterFailed class

(Yaf >=1.0.0)

Introduction

Class synopsis

Yaf_Exception_RouterFailed extends Yaf_Exception {
/* Properties */
/* Methods */
/* Inherited methods */
public Yaf_Exception::__construct ( void )
public Yaf_Exception::getPrevious ( void ) : void
}


The Yaf_Exception_LoadFailed class

(Yaf >=1.0.0)

Introduction

Class synopsis

Yaf_Exception_LoadFailed extends Yaf_Exception {
/* Properties */
/* Methods */
/* Inherited methods */
public Yaf_Exception::__construct ( void )
public Yaf_Exception::getPrevious ( void ) : void
}


The Yaf_Exception_LoadFailed_Module class

(Yaf >=1.0.0)

Introduction

Class synopsis

Yaf_Exception_LoadFailed_Module extends Yaf_Exception_LoadFailed {
/* Properties */
/* Methods */
/* Inherited methods */
public Yaf_Exception::__construct ( void )
public Yaf_Exception::getPrevious ( void ) : void
}


The Yaf_Exception_LoadFailed_Controller class

(Yaf >=1.0.0)

Introduction

Class synopsis

Yaf_Exception_LoadFailed_Controller extends Yaf_Exception_LoadFailed {
/* Properties */
/* Methods */
/* Inherited methods */
public Yaf_Exception::__construct ( void )
public Yaf_Exception::getPrevious ( void ) : void
}


The Yaf_Exception_LoadFailed_Action class

(Yaf >=1.0.0)

Introduction

Class synopsis

Yaf_Exception_LoadFailed_Action extends Yaf_Exception_LoadFailed {
/* Properties */
/* Methods */
/* Inherited methods */
public Yaf_Exception::__construct ( void )
public Yaf_Exception::getPrevious ( void ) : void
}


The Yaf_Exception_LoadFailed_View class

(Yaf >=1.0.0)

Introduction

Class synopsis

Yaf_Exception_LoadFailed_View extends Yaf_Exception_LoadFailed {
/* Properties */
/* Methods */
/* Inherited methods */
public Yaf_Exception::__construct ( void )
public Yaf_Exception::getPrevious ( void ) : void
}


Yaconf

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Yaconf — The Yaconf class
    • Yaconf::get — Retrieve a item
    • Yaconf::has — Determine if a item exists


Introduction

Yet Another Configurations Container (Yaconf) is a configurations container, it parses INI files, and store the result in PHP when PHP is started, the result lives with the whole PHP lifecycle.

Yaconf stores all configurations as interned string or immutable array, which means they are not refcounted-able, thus when you retrieving configurations from yaconf, it could be considered as zero-copy, very fast.

Yaconf supports sections and sections inheritance in INI files. if PHP is built as non-ZTS build, Yaconf also supports automatically reloading after INI files are changed.

Yaconf requires PHP 7.0 or greater.

Example #1 INI example

;simple key val
key=val
;hash
hash.a=val
;array
arr.0=val
;or
arr[]=val
;use PHP constants
version=PHP_VERION
;use enviroment
env=${PATH}

Example #2 INI sections example

[SectionA]
key=val
hash.a=val

;SectionB inherits SectionA
[SectionB:SectionA]
;override configuration key in SectionA
key=new_val


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

Yaconf requires PHP 7.0 and above.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Yaconf Configure Options
Name | Default | Changeable | Changelog
yaconf.check_delay | 300 | PHP_INI_SYSTEM |
yaconf.directory | /tmp/conf/ | PHP_INI_SYSTEM |

Here's a short explanation of the configuration directives.

yaconf.check_delay integer

In which interval Yaconf will detect ini file's change(by directory's mtime), if it is set to zero, you have to restart php to reloading configurations.

yaconf.directory string

Path to directory which all INI configuration files are placed in.


  • « Resource Types
  • Yaconf »
  • PHP Manual
  • Yaconf
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


The Yaconf class

(PECL yaconf >= 1.0.0)

Introduction

Yaconf is a configurations container, it parses INIT files, stores the result in PHP when PHP is started, the result lives with the whole PHP lifecycle.

Class synopsis

Yaconf {
/* Methods */
public static get ( string $name [, mixed $default_value = NULL ] ) : mixed
public static has ( string $name ) : bool
}

Table of Contents

  • Yaconf::get — Retrieve a item
  • Yaconf::has — Determine if a item exists


Retrieve a item

  • « Yaconf
  • Yaconf::has »
  • PHP Manual
  • Yaconf
  • Retrieve a item

Yaconf::get

(PECL yaconf >= 1.0.0)

Yaconf::get — Retrieve a item

Description

public static Yaconf::get ( string $name [, mixed $default_value = NULL ] ) : mixed

Parameters

name

Configuration key, the key looks like "filename.key", or "filename.sectionName,key".

default_value

if the key doesn't exists, Yaconf::get will return this as result.

Return Values

Returns configuration result(string or array) if the key exists, return default_value if not.

Examples

Example #1 INI()example

;filenmame foo.ini, placed in directory which is yaconf.directoy
[SectionA]
;key value pair
key=val
;hash[a]=val
hash.a=val
;arr[0]=val
arr.0=val
;or
arr[]=val

;SectionB inherits SectionA
[SectionB:SectionA]
;override configuration key in SectionA
key=new_val

The above example will output something similar to:

php7 -r 'var_dump(Yaconf::get("foo.SectionA.key"));'
//string(3) "val"

php7 -r 'var_dump(Yaconf::get("foo.SectionB.key"));'
//string(7) "new_val"

php7 -r 'var_dump(Yaconf::get("foo")["SectionA"]["hash"]);'
//array(1)


Determine if a item exists

  • « Yaconf::get
  • Taint »
  • PHP Manual
  • Yaconf
  • Determine if a item exists

Yaconf::has

(PECL yaconf >= 1.0.0)

Yaconf::has — Determine if a item exists

Description

public static Yaconf::has ( string $name ) : bool

Parameters

name

Return Values


Taint

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • More Details
    • Functions and Statements which will spread the tainted mark of a tainted string
    • Functions and statements which will check tainted string
    • Functions which untaint the tainted string
  • Taint Functions
    • is_tainted — Checks whether a string is tainted
    • taint — Taint a string
    • untaint — Untaint strings


Introduction

Taint is an extension, which is used for detecting XSS codes(tainted string). And also can be used to spot sql injection vulnerabilities, and shell inject, etc.

When taint is enabled, if you pass a tainted string (comes from $_GET, $_POST or $_COOKIE) to some functions, taint will warn you about that.

Example #1 Taint()example

<?php
$a = trim($_GET['a']);

$file_name = '/tmp' .  $a;
$output    = "Welcome, {$a} !!!";
$var       = "output";
$sql       = "Select *  from " . $a;
$sql      .= "ooxx";

echo $output;

print $$var;

include($file_name);

mysql_query($sql);
?>

The above example will output something similar to:

Warning: main() [function.echo]: Attempt to echo a string that might be tainted

Warning: main() [function.echo]: Attempt to print a string that might be tainted

Warning: include() [function.include]: File path contains data that might be tainted

Warning: mysql_query() [function.mysql-query]: SQL statement contains data that might be tainted


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/taint.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Taint Configure Options
Name | Default | Changeable | Changelog
taint.enable | 0 | PHP_INI_SYSTEM |
taint.error_level | E_WARNING | PHP_INI_ALL |

Here's a short explanation of the configuration directives.

taint.enable integer

Whether enable the taint.

taint.error_level integer

the error type which taint will report as when taint find a tainted string.


  • « Runtime Configuration
  • More Details »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

This extension has no resource types defined.


More Details

Table of Contents

  • Functions and Statements which will spread the tainted mark of a tainted string
  • Functions and statements which will check tainted string
  • Functions which untaint the tainted string


Functions and Statements which will spread the tainted mark of a tainted string

Function/Statement | Since
= (assign) | 0.1.0
. (concat) | 0.1.0
"{$var}" (variable substitution) | 0.1.0
.= (assign concat) | 0.1.0
strval | 0.3.0
explode/split | 0.3.0
implode/join | 0.3.0
sprintf | 0.3.0
vsprintf | 0.3.0
trim | 0.4.0
rtrim | 0.4.0
ltrim | 0.4.0
strstr | 0.5.0
str_pad | 0.5.0
str_replace | 0.5.0
substr | 0.5.0
strtolower | 0.5.0
strtoupper | 0.5.0


Functions and statements which will check tainted string

Function/Statement | Since
Basic statments
eval | 0.1.0
include/include_once | 0.1.0
require/require_once | 0.1.0
Outputing Functions
echo | 0.1.0
print | 0.1.0
printf | 0.1.0
file_put_contents | 0.1.0
File System Functions
fopen | 0.2.0
opendir | 0.2.0
basename | 0.2.0
dirname | 0.2.0
file | 0.2.0
pathinfo | 0.2.0
Database relevant Functions
mysql_query | 0.2.0
mysqli_query/MySQLi::query | 0.2.0
sqlite_query/SqliteDataBase::query | 0.3.0
sqlite_single_query/SqliteDataBase::singleQuery | 0.3.0
oci_parse | 0.3.0
PDO::query | 0.3.0
PDO::prepare | 0.3.0
SQLite3::query | 2.0.1
SQLite3::prepare | 2.0.1
Command Line relevant Functions
system | 0.1.0
exec | 0.1.0
proc_open | 0.1.0
passthru | 0.1.0
shell_exec | 0.3.0


Functions which untaint the tainted string

Function | Since
addslashes | 0.1.0
addcslashes | 0.1.0
htmlspecialchars | 0.1.0
htmlentities | 0.1.0
escapeshellcmd | 0.1.0
mysql_escape_string | 0.1.0
mysql_real_escape_string | 0.1.0
mysqli_escape_string/MySQLi::escape_string | 0.1.0
mysqli_real_escape_string/MySQLi::real_escape_string | 0.1.0
sqlite_escape_string/SqliteDataBase::escapeString | 0.3.0
PDO::quote | 0.3.0


Taint Functions

Table of Contents

  • is_tainted — Checks whether a string is tainted
  • taint — Taint a string
  • untaint — Untaint strings


Checks whether a string is tainted

  • « Taint Functions
  • taint »
  • PHP Manual
  • Taint Functions
  • Checks whether a string is tainted

is_tainted

(PECL taint >=0.1.0)

is_tainted — Checks whether a string is tainted

Description

is_tainted ( string $string ) : bool

Checks whether a string is tainted

Parameters

string

Return Values

Return TRUE if the string is tainted, FALSE otherwise.


Taint a string

  • « is_tainted
  • untaint »
  • PHP Manual
  • Taint Functions
  • Taint a string

taint

(PECL taint >=0.1.0)

taint — Taint a string

Description

taint ( string &$string [, string $... ] ) : bool

Make a string tainted. This is used for testing purpose only.

Parameters

string

...

Return Values

Return TRUE if the transformation is done. Always return TRUE if the taint extension is not enabled.


Untaint strings

  • « taint
  • Data Structures »
  • PHP Manual
  • Taint Functions
  • Untaint strings

untaint

(PECL taint >=0.1.0)

untaint — Untaint strings

Description

untaint ( string &$string [, string $... ] ) : bool

Untaint strings

Parameters

string

...

Return Values


Data Structures

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
  • Predefined Constants
  • Examples
  • Collection — The Collection interface
    • Ds\Collection::clear — Removes all values
    • Ds\Collection::copy — Returns a shallow copy of the collection
    • Ds\Collection::isEmpty — Returns whether the collection is empty
    • Ds\Collection::toArray — Converts the collection to an array
  • Hashable — The Hashable interface
    • Ds\Hashable::equals — Determines whether an object is equal to the current instance
    • Ds\Hashable::hash — Returns a scalar value to be used as a hash value
  • Sequence — The Sequence interface
    • Ds\Sequence::allocate — Allocates enough memory for a required capacity
    • Ds\Sequence::apply — Updates all values by applying a callback function to each value
    • Ds\Sequence::capacity — Returns the current capacity
    • Ds\Sequence::contains — Determines if the sequence contains given values
    • Ds\Sequence::filter — Creates a new sequence using a callable to determine which values to include
    • Ds\Sequence::find — Attempts to find a value's index
    • Ds\Sequence::first — Returns the first value in the sequence
    • Ds\Sequence::get — Returns the value at a given index
    • Ds\Sequence::insert — Inserts values at a given index
    • Ds\Sequence::join — Joins all values together as a string
    • Ds\Sequence::last — Returns the last value
    • Ds\Sequence::map — Returns the result of applying a callback to each value
    • Ds\Sequence::merge — Returns the result of adding all given values to the sequence
    • Ds\Sequence::pop — Removes and returns the last value
    • Ds\Sequence::push — Adds values to the end of the sequence
    • Ds\Sequence::reduce — Reduces the sequence to a single value using a callback function
    • Ds\Sequence::remove — Removes and returns a value by index
    • Ds\Sequence::reverse — Reverses the sequence in-place
    • Ds\Sequence::reversed — Returns a reversed copy
    • Ds\Sequence::rotate — Rotates the sequence by a given number of rotations
    • Ds\Sequence::set — Updates a value at a given index
    • Ds\Sequence::shift — Removes and returns the first value
    • Ds\Sequence::slice — Returns a sub-sequence of a given range
    • Ds\Sequence::sort — Sorts the sequence in-place
    • Ds\Sequence::sorted — Returns a sorted copy
    • Ds\Sequence::sum — Returns the sum of all values in the sequence
    • Ds\Sequence::unshift — Adds values to the front of the sequence
  • Vector — The Vector class
    • Ds\Vector::allocate — Allocates enough memory for a required capacity
    • Ds\Vector::apply — Updates all values by applying a callback function to each value
    • Ds\Vector::capacity — Returns the current capacity
    • Ds\Vector::clear — Removes all values
    • Ds\Vector::__construct — Creates a new instance
    • Ds\Vector::contains — Determines if the vector contains given values
    • Ds\Vector::copy — Returns a shallow copy of the vector
    • Ds\Vector::count — Returns the number of values in the collection
    • Ds\Vector::filter — Creates a new vector using a callable to determine which values to include
    • Ds\Vector::find — Attempts to find a value's index
    • Ds\Vector::first — Returns the first value in the vector
    • Ds\Vector::get — Returns the value at a given index
    • Ds\Vector::insert — Inserts values at a given index
    • Ds\Vector::isEmpty — Returns whether the vector is empty
    • Ds\Vector::join — Joins all values together as a string
    • Ds\Vector::jsonSerialize — Returns a representation that can be converted to JSON
    • Ds\Vector::last — Returns the last value
    • Ds\Vector::map — Returns the result of applying a callback to each value
    • Ds\Vector::merge — Returns the result of adding all given values to the vector
    • Ds\Vector::pop — Removes and returns the last value
    • Ds\Vector::push — Adds values to the end of the vector
    • Ds\Vector::reduce — Reduces the vector to a single value using a callback function
    • Ds\Vector::remove — Removes and returns a value by index
    • Ds\Vector::reverse — Reverses the vector in-place
    • Ds\Vector::reversed — Returns a reversed copy
    • Ds\Vector::rotate — Rotates the vector by a given number of rotations
    • Ds\Vector::set — Updates a value at a given index
    • Ds\Vector::shift — Removes and returns the first value
    • Ds\Vector::slice — Returns a sub-vector of a given range
    • Ds\Vector::sort — Sorts the vector in-place
    • Ds\Vector::sorted — Returns a sorted copy
    • Ds\Vector::sum — Returns the sum of all values in the vector
    • Ds\Vector::toArray — Converts the vector to an array
    • Ds\Vector::unshift — Adds values to the front of the vector
  • Deque — The Deque class
    • Ds\Deque::allocate — Allocates enough memory for a required capacity
    • Ds\Deque::apply — Updates all values by applying a callback function to each value
    • Ds\Deque::capacity — Returns the current capacity
    • Ds\Deque::clear — Removes all values from the deque
    • Ds\Deque::__construct — Creates a new instance
    • Ds\Deque::contains — Determines if the deque contains given values
    • Ds\Deque::copy — Returns a shallow copy of the deque
    • Ds\Deque::count — Returns the number of values in the collection
    • Ds\Deque::filter — Creates a new deque using a callable to determine which values to include
    • Ds\Deque::find — Attempts to find a value's index
    • Ds\Deque::first — Returns the first value in the deque
    • Ds\Deque::get — Returns the value at a given index
    • Ds\Deque::insert — Inserts values at a given index
    • Ds\Deque::isEmpty — Returns whether the deque is empty
    • Ds\Deque::join — Joins all values together as a string
    • Ds\Deque::jsonSerialize — Returns a representation that can be converted to JSON
    • Ds\Deque::last — Returns the last value
    • Ds\Deque::map — Returns the result of applying a callback to each value
    • Ds\Deque::merge — Returns the result of adding all given values to the deque
    • Ds\Deque::pop — Removes and returns the last value
    • Ds\Deque::push — Adds values to the end of the deque
    • Ds\Deque::reduce — Reduces the deque to a single value using a callback function
    • Ds\Deque::remove — Removes and returns a value by index
    • Ds\Deque::reverse — Reverses the deque in-place
    • Ds\Deque::reversed — Returns a reversed copy
    • Ds\Deque::rotate — Rotates the deque by a given number of rotations
    • Ds\Deque::set — Updates a value at a given index
    • Ds\Deque::shift — Removes and returns the first value
    • Ds\Deque::slice — Returns a sub-deque of a given range
    • Ds\Deque::sort — Sorts the deque in-place
    • Ds\Deque::sorted — Returns a sorted copy
    • Ds\Deque::sum — Returns the sum of all values in the deque
    • Ds\Deque::toArray — Converts the deque to an array
    • Ds\Deque::unshift — Adds values to the front of the deque
  • Map — The Map class
    • Ds\Map::allocate — Allocates enough memory for a required capacity
    • Ds\Map::apply — Updates all values by applying a callback function to each value
    • Ds\Map::capacity — Returns the current capacity
    • Ds\Map::clear — Removes all values
    • Ds\Map::__construct — Creates a new instance
    • Ds\Map::copy — Returns a shallow copy of the map
    • Ds\Map::count — Returns the number of values in the map
    • Ds\Map::diff — Creates a new map using keys that aren't in another map
    • Ds\Map::filter — Creates a new map using a callable to determine which pairs to include
    • Ds\Map::first — Returns the first pair in the map
    • Ds\Map::get — Returns the value for a given key
    • Ds\Map::hasKey — Determines whether the map contains a given key
    • Ds\Map::hasValue — Determines whether the map contains a given value
    • Ds\Map::intersect — Creates a new map by intersecting keys with another map
    • Ds\Map::isEmpty — Returns whether the map is empty
    • Ds\Map::jsonSerialize — Returns a representation that can be converted to JSON
    • Ds\Map::keys — Returns a set of the map's keys
    • Ds\Map::ksort — Sorts the map in-place by key
    • Ds\Map::ksorted — Returns a copy, sorted by key
    • Ds\Map::last — Returns the last pair of the map
    • Ds\Map::map — Returns the result of applying a callback to each value
    • Ds\Map::merge — Returns the result of adding all given associations
    • Ds\Map::pairs — Returns a sequence containing all the pairs of the map
    • Ds\Map::put — Associates a key with a value
    • Ds\Map::putAll — Associates all key-value pairs of a traversable object or array
    • Ds\Map::reduce — Reduces the map to a single value using a callback function
    • Ds\Map::remove — Removes and returns a value by key
    • Ds\Map::reverse — Reverses the map in-place
    • Ds\Map::reversed — Returns a reversed copy
    • Ds\Map::skip — Returns the pair at a given positional index
    • Ds\Map::slice — Returns a subset of the map defined by a starting index and length
    • Ds\Map::sort — Sorts the map in-place by value
    • Ds\Map::sorted — Returns a copy, sorted by value
    • Ds\Map::sum — Returns the sum of all values in the map
    • Ds\Map::toArray — Converts the map to an array
    • Ds\Map::union — Creates a new map using values from the current instance and another map
    • Ds\Map::values — Returns a sequence of the map's values
    • Ds\Map::xor — Creates a new map using keys of either the current instance or of another map, but not of both
  • Pair — The Pair class
    • Ds\Pair::clear — Removes all values
    • Ds\Pair::__construct — Creates a new instance
    • Ds\Pair::copy — Returns a shallow copy of the pair
    • Ds\Pair::isEmpty — Returns whether the pair is empty
    • Ds\Pair::jsonSerialize — Returns a representation that can be converted to JSON
    • Ds\Pair::toArray — Converts the pair to an array
  • Set — The Set class
    • Ds\Set::add — Adds values to the set
    • Ds\Set::allocate — Allocates enough memory for a required capacity
    • Ds\Set::capacity — Returns the current capacity
    • Ds\Set::clear — Removes all values
    • Ds\Set::__construct — Creates a new instance
    • Ds\Set::contains — Determines if the set contains all values
    • Ds\Set::copy — Returns a shallow copy of the set
    • Ds\Set::count — Returns the number of values in the set
    • Ds\Set::diff — Creates a new set using values that aren't in another set
    • Ds\Set::filter — Creates a new set using a callable to determine which values to include
    • Ds\Set::first — Returns the first value in the set
    • Ds\Set::get — Returns the value at a given index
    • Ds\Set::intersect — Creates a new set by intersecting values with another set
    • Ds\Set::isEmpty — Returns whether the set is empty
    • Ds\Set::join — Joins all values together as a string
    • Ds\Set::jsonSerialize — Returns a representation that can be converted to JSON
    • Ds\Set::last — Returns the last value in the set
    • Ds\Set::merge — Returns the result of adding all given values to the set
    • Ds\Set::reduce — Reduces the set to a single value using a callback function
    • Ds\Set::remove — Removes all given values from the set
    • Ds\Set::reverse — Reverses the set in-place
    • Ds\Set::reversed — Returns a reversed copy
    • Ds\Set::slice — Returns a sub-set of a given range
    • Ds\Set::sort — Sorts the set in-place
    • Ds\Set::sorted — Returns a sorted copy
    • Ds\Set::sum — Returns the sum of all values in the set
    • Ds\Set::toArray — Converts the set to an array
    • Ds\Set::union — Creates a new set using values from the current instance and another set
    • Ds\Set::xor — Creates a new set using values in either the current instance or in another set, but not in both
  • Stack — The Stack class
    • Ds\Stack::allocate — Allocates enough memory for a required capacity
    • Ds\Stack::capacity — Returns the current capacity
    • Ds\Stack::clear — Removes all values
    • Ds\Stack::__construct — Creates a new instance
    • Ds\Stack::copy — Returns a shallow copy of the stack
    • Ds\Stack::count — Returns the number of values in the stack
    • Ds\Stack::isEmpty — Returns whether the stack is empty
    • Ds\Stack::jsonSerialize — Returns a representation that can be converted to JSON
    • Ds\Stack::peek — Returns the value at the top of the stack
    • Ds\Stack::pop — Removes and returns the value at the top of the stack
    • Ds\Stack::push — Pushes values onto the stack
    • Ds\Stack::toArray — Converts the stack to an array
  • Queue — The Queue class
    • Ds\Queue::allocate — Allocates enough memory for a required capacity
    • Ds\Queue::capacity — Returns the current capacity
    • Ds\Queue::clear — Removes all values
    • Ds\Queue::__construct — Creates a new instance
    • Ds\Queue::copy — Returns a shallow copy of the queue
    • Ds\Queue::count — Returns the number of values in the queue
    • Ds\Queue::isEmpty — Returns whether the queue is empty
    • Ds\Queue::jsonSerialize — Returns a representation that can be converted to JSON
    • Ds\Queue::peek — Returns the value at the front of the queue
    • Ds\Queue::pop — Removes and returns the value at the front of the queue
    • Ds\Queue::push — Pushes values into the queue
    • Ds\Queue::toArray — Converts the queue to an array
  • PriorityQueue — The PriorityQueue class
    • Ds\PriorityQueue::allocate — Allocates enough memory for a required capacity
    • Ds\PriorityQueue::capacity — Returns the current capacity
    • Ds\PriorityQueue::clear — Removes all values
    • Ds\PriorityQueue::__construct — Creates a new instance
    • Ds\PriorityQueue::copy — Returns a shallow copy of the queue
    • Ds\PriorityQueue::count — Returns the number of values in the queue
    • Ds\PriorityQueue::isEmpty — Returns whether the queue is empty
    • Ds\PriorityQueue::jsonSerialize — Returns a representation that can be converted to JSON
    • Ds\PriorityQueue::peek — Returns the value at the front of the queue
    • Ds\PriorityQueue::pop — Removes and returns the value with the highest priority
    • Ds\PriorityQueue::push — Pushes values into the queue
    • Ds\PriorityQueue::toArray — Converts the queue to an array


Introduction

Efficient data structures for PHP 7, provided as an alternative to the array.

See » this blog post for benchmarks, discussion and frequently asked questions.


  • « Introduction
  • Requirements »
  • PHP Manual
  • Data Structures
  • Installing/Configuring

Installing/Configuring

Table of Contents

  • Requirements
  • Installation


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

PHP 7 is required by both the extension and the compatibility polyfill.


Installation

The easiest way to install the extension is via » PECL

pecl install ds

You can also build directly from source:

# Dependencies you might need to install
# sudo apt-get install git build-essential php7.0-dev

git clone https://github.com/php-ds/extension "php-ds"
cd php-ds

# Build and install the extension
phpize
./configure
make
make install

# Clean up the build files
make clean
phpize --clean

If you're on Windows, you can » download a compiled .dll on PECL

Note:

If you're using Composer, it's highly recommended that you include » php-ds/php-ds in your project so that your code is still functional in an environment where the extension is not installed. The extension will take priority if installed.


  • « Installation
  • Examples »
  • PHP Manual
  • Data Structures
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


Examples

Example #1 Vector

<?php

$vector = new \Ds\Vector();

$vector->push('a');
$vector->push('b', 'c');

$vector[] = 'd';

print_r($vector);

?>

The above example will output something similar to:

Ds\Vector Object
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
)

Example #2 Map

<?php

$map = new \Ds\Map();

$map->put('a', 1);
$map->put('b', 2);

$map['c'] = 3;

print_r($map);

?>

The above example will output something similar to:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

)


The Collection interface

(No version information available, might only be in Git)

Introduction

Collection is the base interface which covers functionality common to all the data structures in this library. It guarantees that all structures are traversable, countable, and can be converted to json using json_encode().

Interface synopsis

Ds\Collection implements Traversable , Countable , JsonSerializable {
/* Methods */
abstract public clear ( void ) : void
abstract public copy ( void ) : Ds\Collection
abstract public isEmpty ( void ) : bool
abstract public toArray ( void ) : array
}

Table of Contents

  • Ds\Collection::clear — Removes all values
  • Ds\Collection::copy — Returns a shallow copy of the collection
  • Ds\Collection::isEmpty — Returns whether the collection is empty
  • Ds\Collection::toArray — Converts the collection to an array


Removes all values

  • « Collection
  • Ds\Collection::copy »
  • PHP Manual
  • Collection
  • Removes all values

Ds\Collection::clear

(PECL ds >= 1.0.0)

Ds\Collection::clear — Removes all values

Description

abstract public Ds\Collection::clear ( void ) : void

Removes all values from the collection.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 Ds\Collection::clear() example

<?php
$collection = new \Ds\Vector([1, 2, 3]);
print_r($collection);

$collection->clear();
print_r($collection);
?>

The above example will output something similar to:

Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Vector Object
(
)


Returns a shallow copy of the collection

  • « Ds\Collection::clear
  • Ds\Collection::isEmpty »
  • PHP Manual
  • Collection
  • Returns a shallow copy of the collection

Ds\Collection::copy

(PECL ds >= 1.0.0)

Ds\Collection::copy — Returns a shallow copy of the collection

Description

abstract public Ds\Collection::copy ( void ) : Ds\Collection

Returns a shallow copy of the collection.

Parameters

This function has no parameters.

Return Values

Returns a shallow copy of the collection.

Examples

Example #1 Ds\Collection::copy() example

<?php
$a = new \Ds\Vector([1, 2, 3]);
$b = $a->copy();

$b->push(4);

print_r($a);
print_r($b);
?>

The above example will output something similar to:

Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)


Returns whether the collection is empty

  • « Ds\Collection::copy
  • Ds\Collection::toArray »
  • PHP Manual
  • Collection
  • Returns whether the collection is empty

Ds\Collection::isEmpty

(PECL ds >= 1.0.0)

Ds\Collection::isEmpty — Returns whether the collection is empty

Description

abstract public Ds\Collection::isEmpty ( void ) : bool

Returns whether the collection is empty.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the collection is empty, FALSE otherwise.

Examples

Example #1 Ds\Collection::isEmpty() example

<?php
$a = new \Ds\Vector([1, 2, 3]);
$b = new \Ds\Vector();

var_dump($a->isEmpty());
var_dump($b->isEmpty());
?>

The above example will output something similar to:

bool(false)
bool(true)


Converts the collection to an array

  • « Ds\Collection::isEmpty
  • Hashable »
  • PHP Manual
  • Collection
  • Converts the collection to an array

Ds\Collection::toArray

(PECL ds >= 1.0.0)

Ds\Collection::toArray — Converts the collection to an array

Description

abstract public Ds\Collection::toArray ( void ) : array

Converts the collection to an array.

Note:

Casting to an array is not supported yet.

Parameters

This function has no parameters.

Return Values

An array containing all the values in the same order as the collection.

Examples

Example #1 Ds\Collection::toArray() example

<?php
$collection = new \Ds\Vector([1, 2, 3]);

var_dump($collection->toArray());
?>

The above example will output something similar to:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}


The Hashable interface

(No version information available, might only be in Git)

Introduction

Hashable is an interface which allows objects to be used as keys. It’s an alternative to spl_object_hash(), which determines an object’s hash based on its handle: this means that two objects that are considered equal by an implicit definition would not treated as equal because they are not the same instance.

hash() is used to return a scalar value to be used as the object's hash value, which determines where it goes in the hash table. While this value does not have to be unique, objects which are equal must have the same hash value.

equals() is used to determine if two objects are equal. It's guaranteed that the comparing object will be an instance of the same class as the subject.

Interface synopsis

Ds\Hashable {
/* Methods */
abstract public equals ( object $obj ) : bool
abstract public hash ( void ) : mixed
}

Table of Contents

  • Ds\Hashable::equals — Determines whether an object is equal to the current instance
  • Ds\Hashable::hash — Returns a scalar value to be used as a hash value


Determines whether an object is equal to the current instance

  • « Hashable
  • Ds\Hashable::hash »
  • PHP Manual
  • Hashable
  • Determines whether an object is equal to the current instance

Ds\Hashable::equals

(PECL ds >= 1.0.0)

Ds\Hashable::equals — Determines whether an object is equal to the current instance

Description

abstract public Ds\Hashable::equals ( object $obj ) : bool

Determines whether another object is equal to the current instance.

This method allows objects to be used as keys in structures such as Ds\Map and Ds\Set, or any other lookup structure that honors this interface.

Note:

It's guaranteed that obj is an instance of the same class.

Caution

It's important that objects which are equal also have the same hash value. See Ds\Hashable::hash().

Parameters

obj

The object to compare the current instance to, which is always an instance of the same class.

Return Values

TRUE if equal, FALSE otherwise.


Returns a scalar value to be used as a hash value

  • « Ds\Hashable::equals
  • Sequence »
  • PHP Manual
  • Hashable
  • Returns a scalar value to be used as a hash value

Ds\Hashable::hash

(PECL ds >= 1.0.0)

Ds\Hashable::hash — Returns a scalar value to be used as a hash value

Description

abstract public Ds\Hashable::hash ( void ) : mixed

Returns a scalar value to be used as the hash value of the objects.

While the hash value does not define equality, all objects that are equal according to Ds\Hashable::equals() must have the same hash value. Hash values of equal objects don't have to be unique, for example you could just return TRUE for all objects and nothing would break - the only implication would be that hash tables then turn into linked lists because all your objects will be hashed to the same bucket. It's therefore very important that you pick a good hash value, such as an ID or email address.

This method allows objects to be used as keys in structures such as Ds\Map and Ds\Set, or any other lookup structure that honors this interface.

Caution

Do not pick a value that might change within the object, such as a public property. Hash table lookups would fail because the hash has changed.

Caution

All objects that are equal must have the same hash value.

Parameters

This function has no parameters.

Return Values

A scalar value to be used as this object's hash value.

Examples

Example #1 Ds\Hashable::hash() example

<?php
class HashableObject implements \Ds\Hashable
{
    private $name;
    private $email;

    public function __construct($name, $email)
    {
        $this->name  = $name;
        $this->email = $email;
    }

    /**
     * Should return the same value for all equal objects, but doesn't have to
     * be unique. This value will not be used to determine equality.
     */
    public function hash()
    {
        return $this->email;
    }

    /**
     * This determines equality, usually during a hash table lookup to determine
     * if the bucket's key matches the lookup key. The hash has to be equal if
     * the objects are equal, otherwise this determination wouldn't be reached.
     */
    public function equals($obj): bool
    {
        return $this->name  === $obj->name
            && $this->email === $obj->email;
    }
}
?>


The Sequence interface

(No version information available, might only be in Git)

Introduction

A Sequence describes the behaviour of values arranged in a single, linear dimension. Some languages refer to this as a "List". It’s similar to an array that uses incremental integer keys, with the exception of a few characteristics:

  • Values will always be indexed as [0, 1, 2, …, size - 1].
  • Only allowed to access values by index in the range [0, size - 1].

Use cases:

  • Wherever you would use an array as a list (not concerned with keys).
  • A more efficient alternative to SplDoublyLinkedList and SplFixedArray.

Interface synopsis

Ds\Sequence implements Ds\Collection {
/* Methods */
abstract public allocate ( int $capacity ) : void
abstract public apply ( callable $callback ) : void
abstract public capacity ( void ) : int
abstract public contains ([ mixed $...values ] ) : bool
abstract public filter ([ callable $callback ] ) : Ds\Sequence
abstract public find ( mixed $value ) : mixed
abstract public first ( void ) : mixed
abstract public get ( int $index ) : mixed
abstract public insert ( int $index [, mixed $...values ] ) : void
abstract public join ([ string $glue ] ) : string
abstract public last ( void ) : mixed
abstract public map ( callable $callback ) : Ds\Sequence
abstract public merge ( mixed $values ) : Ds\Sequence
abstract public pop ( void ) : mixed
abstract public push ([ mixed $...values ] ) : void
abstract public reduce ( callable $callback [, mixed $initial ] ) : mixed
abstract public remove ( int $index ) : mixed
abstract public reverse ( void ) : void
abstract public reversed ( void ) : Ds\Sequence
abstract public rotate ( int $rotations ) : void
abstract public set ( int $index , mixed $value ) : void
abstract public shift ( void ) : mixed
abstract public slice ( int $index [, int $length ] ) : Ds\Sequence
abstract public sort ([ callable $comparator ] ) : void
abstract public sorted ([ callable $comparator ] ) : Ds\Sequence
abstract public sum ( void ) : number
abstract public unshift ([ mixed $values ] ) : void
}

Table of Contents

  • Ds\Sequence::allocate — Allocates enough memory for a required capacity
  • Ds\Sequence::apply — Updates all values by applying a callback function to each value
  • Ds\Sequence::capacity — Returns the current capacity
  • Ds\Sequence::contains — Determines if the sequence contains given values
  • Ds\Sequence::filter — Creates a new sequence using a callable to determine which values to include
  • Ds\Sequence::find — Attempts to find a value's index
  • Ds\Sequence::first — Returns the first value in the sequence
  • Ds\Sequence::get — Returns the value at a given index
  • Ds\Sequence::insert — Inserts values at a given index
  • Ds\Sequence::join — Joins all values together as a string
  • Ds\Sequence::last — Returns the last value
  • Ds\Sequence::map — Returns the result of applying a callback to each value
  • Ds\Sequence::merge — Returns the result of adding all given values to the sequence
  • Ds\Sequence::pop — Removes and returns the last value
  • Ds\Sequence::push — Adds values to the end of the sequence
  • Ds\Sequence::reduce — Reduces the sequence to a single value using a callback function
  • Ds\Sequence::remove — Removes and returns a value by index
  • Ds\Sequence::reverse — Reverses the sequence in-place
  • Ds\Sequence::reversed — Returns a reversed copy
  • Ds\Sequence::rotate — Rotates the sequence by a given number of rotations
  • Ds\Sequence::set — Updates a value at a given index
  • Ds\Sequence::shift — Removes and returns the first value
  • Ds\Sequence::slice — Returns a sub-sequence of a given range
  • Ds\Sequence::sort — Sorts the sequence in-place
  • Ds\Sequence::sorted — Returns a sorted copy
  • Ds\Sequence::sum — Returns the sum of all values in the sequence
  • Ds\Sequence::unshift — Adds values to the front of the sequence


Allocates enough memory for a required capacity

  • « Sequence
  • Ds\Sequence::apply »
  • PHP Manual
  • Sequence
  • Allocates enough memory for a required capacity

Ds\Sequence::allocate

(PECL ds >= 1.0.0)

Ds\Sequence::allocate — Allocates enough memory for a required capacity

Description

abstract public Ds\Sequence::allocate ( int $capacity ) : void

Ensures that enough memory is allocated for a required capacity. This removes the need to reallocate the internal as values are added.

Parameters

capacity

The number of values for which capacity should be allocated.

Note:

Capacity will stay the same if this value is less than or equal to the current capacity.

Return Values

No value is returned.

Examples

Example #1 Ds\Sequence::allocate() example

<?php
$sequence = new \Ds\Vector();
var_dump($sequence->capacity());

$vector->allocate(100);
var_dump($sequence->capacity());
?>

The above example will output something similar to:

int(10)
int(100)


Updates all values by applying a callback function to each value

  • « Ds\Sequence::allocate
  • Ds\Sequence::capacity »
  • PHP Manual
  • Sequence
  • Updates all values by applying a callback function to each value

Ds\Sequence::apply

(PECL ds >= 1.0.0)

Ds\Sequence::apply — Updates all values by applying a callback function to each value

Description

abstract public Ds\Sequence::apply ( callable $callback ) : void

Updates all values by applying a callback function to each value in the sequence.

Parameters

callback

callback ( mixed $value ) : mixed

A callable to apply to each value in the sequence.

The callback should return what the value should be replaced by.

Return Values

No value is returned.

Examples

Example #1 Ds\Sequence::apply() example

<?php
$sequence = new \Ds\Sequence([1, 2, 3]);
$sequence->apply(function($value) { return $value * 2; });

print_r($sequence);
?>

The above example will output something similar to:

Ds\Vector Object
(
    [0] => 2
    [1] => 4
    [2] => 6
)


Returns the current capacity

  • « Ds\Sequence::apply
  • Ds\Sequence::contains »
  • PHP Manual
  • Sequence
  • Returns the current capacity

Ds\Sequence::capacity

(PECL ds >= 1.0.0)

Ds\Sequence::capacity — Returns the current capacity

Description

abstract public Ds\Sequence::capacity ( void ) : int

Returns the current capacity.

Parameters

This function has no parameters.

Return Values

The current capacity.

Examples

Example #1 Ds\Sequence::capacity() example

<?php
$sequence = new \Ds\Vector();
var_dump($sequence->capacity());

$sequence->push(...range(1, 50));
var_dump($sequence->capacity());

$sequence[] = "a";
var_dump($sequence->capacity());
?>

The above example will output something similar to:

int(10)
int(50)
int(75)


Determines if the sequence contains given values

  • « Ds\Sequence::capacity
  • Ds\Sequence::filter »
  • PHP Manual
  • Sequence
  • Determines if the sequence contains given values

Ds\Sequence::contains

(PECL ds >= 1.0.0)

Ds\Sequence::contains — Determines if the sequence contains given values

Description

abstract public Ds\Sequence::contains ([ mixed $...values ] ) : bool

Determines if the sequence contains all values.

Parameters

values

Values to check.

Return Values

FALSE if any of the provided values are not in the sequence, TRUE otherwise.

Examples

Example #1 Ds\Sequence::contains() example

<?php
$sequence = new \Ds\Vector(['a', 'b', 'c', 1, 2, 3]);

var_dump($sequence->contains('a'));                // true
var_dump($sequence->contains('a', 'b'));           // true
var_dump($sequence->contains('c', 'd'));           // false

var_dump($sequence->contains(...['c', 'b', 'a'])); // true

// Always strict
var_dump($sequence->contains(1));                  // true
var_dump($sequence->contains('1'));                // false

var_dump($sequece->contains(...[]));               // true
?>

The above example will output something similar to:

bool(true)
bool(true)
bool(false)
bool(true)
bool(true)
bool(false)
bool(true)


Creates a new sequence using a callable to determine which values to include

  • « Ds\Sequence::contains
  • Ds\Sequence::find »
  • PHP Manual
  • Sequence
  • Creates a new sequence using a callable to determine which values to include

Ds\Sequence::filter

(PECL ds >= 1.0.0)

Ds\Sequence::filter — Creates a new sequence using a callable to determine which values to include

Description

abstract public Ds\Sequence::filter ([ callable $callback ] ) : Ds\Sequence

Creates a new sequence using a callable to determine which values to include.

Parameters

callback

callback ( mixed $value ) : bool

Optional callable which returns TRUE if the value should be included, FALSE otherwise.

If a callback is not provided, only values which are TRUE (see converting to boolean) will be included.

Return Values

A new sequence containing all the values for which either the callback returned TRUE, or all values that convert to TRUE if a callback was not provided.

Examples

Example #1 Ds\Sequence::filter() example using callback function

<?php
$sequence = new \Ds\Vector([1, 2, 3, 4, 5]);

var_dump($sequence->filter(function($value) {
    return $value % 2 == 0;
}));
?>

The above example will output something similar to:

object(Ds\Vector)#3 (2) {
  [0]=>
  int(2)
  [1]=>
  int(4)
}

Example #2 Ds\Sequence::filter() example without a callback function

<?php
$sequence = new \Ds\Vector([0, 1, 'a', true, false]);

var_dump($sequence->filter());
?>

The above example will output something similar to:

object(Ds\Vector)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  string(1) "a"
  [2]=>
  bool(true)
}


Attempts to find a value's index

  • « Ds\Sequence::filter
  • Ds\Sequence::first »
  • PHP Manual
  • Sequence
  • Attempts to find a value's index

Ds\Sequence::find

(PECL ds >= 1.0.0)

Ds\Sequence::find — Attempts to find a value's index

Description

abstract public Ds\Sequence::find ( mixed $value ) : mixed

Returns the index of the value, or FALSE if not found.

Parameters

value

The value to find.

Return Values

The index of the value, or FALSE if not found.

Note:

Values will be compared by value and by type.

Examples

Example #1 Ds\Sequence::find() example

<?php
$sequence = new \Ds\Vector(["a", 1, true]);

var_dump($sequence->find("a")); // 0
var_dump($sequence->find("b")); // false
var_dump($sequence->find("1")); // false
var_dump($sequence->find(1));   // 1
?>

The above example will output something similar to:

int(0)
bool(false)
bool(false)
int(1)


Returns the first value in the sequence

  • « Ds\Sequence::find
  • Ds\Sequence::get »
  • PHP Manual
  • Sequence
  • Returns the first value in the sequence

Ds\Sequence::first

(PECL ds >= 1.0.0)

Ds\Sequence::first — Returns the first value in the sequence

Description

abstract public Ds\Sequence::first ( void ) : mixed

Returns the first value in the sequence.

Parameters

This function has no parameters.

Return Values

The first value in the sequence.

Errors/Exceptions

UnderflowException if empty.

Examples

Example #1 Ds\Sequence::first() example

<?php
$sequence = new \Ds\Vector([1, 2, 3]);
var_dump($sequence->first());
?>

The above example will output something similar to:

int(1)


Returns the value at a given index

  • « Ds\Sequence::first
  • Ds\Sequence::insert »
  • PHP Manual
  • Sequence
  • Returns the value at a given index

Ds\Sequence::get

(PECL ds >= 1.0.0)

Ds\Sequence::get — Returns the value at a given index

Description

abstract public Ds\Sequence::get ( int $index ) : mixed

Returns the value at a given index.

Parameters

index

The index to access, starting at 0.

Return Values

The value at the requested index.

Errors/Exceptions

OutOfRangeException if the index is not valid.

Examples

Example #1 Ds\Sequence::get() example

<?php
$sequence = new \Ds\Vector(["a", "b", "c"]);

var_dump($sequence->get(0));
var_dump($sequence->get(1));
var_dump($sequence->get(2));
?>

The above example will output something similar to:

string(1) "a"
string(1) "b"
string(1) "c"

Example #2 Ds\Sequence::get() example using array syntax

<?php
$sequence = new \Ds\Vector(["a", "b", "c"]);

var_dump($sequence[0]);
var_dump($sequence[1]);
var_dump($sequence[2]);
?>

The above example will output something similar to:

string(1) "a"
string(1) "b"
string(1) "c"


Inserts values at a given index

  • « Ds\Sequence::get
  • Ds\Sequence::join »
  • PHP Manual
  • Sequence
  • Inserts values at a given index

Ds\Sequence::insert

(PECL ds >= 1.0.0)

Ds\Sequence::insert — Inserts values at a given index

Description

abstract public Ds\Sequence::insert ( int $index [, mixed $...values ] ) : void

Inserts values into the sequence at a given index.

Parameters

index

The index at which to insert. 0 <= index <= count

Note:

You can insert at the index equal to the number of values.

values

The value or values to insert.

Return Values

No value is returned.

Errors/Exceptions

OutOfRangeException if the index is not valid.

Examples

Example #1 Ds\Sequence::insert() example

<?php
$sequence = new \Ds\Vector();

$sequence->insert(0, "e");             // [e]
$sequence->insert(1, "f");             // [e, f]
$sequence->insert(2, "g");             // [e, f, g]
$sequence->insert(0, "a", "b");        // [a, b, e, f, g]
$sequence->insert(2, ...["c", "d"]);   // [a, b, c, d, e, f, g]

var_dump($sequence);
?>

The above example will output something similar to:

object(Ds\Vector)#1 (7) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  string(1) "e"
  [5]=>
  string(1) "f"
  [6]=>
  string(1) "g"
}


Joins all values together as a string

  • « Ds\Sequence::insert
  • Ds\Sequence::last »
  • PHP Manual
  • Sequence
  • Joins all values together as a string

Ds\Sequence::join

(PECL ds >= 1.0.0)

Ds\Sequence::join — Joins all values together as a string

Description

abstract public Ds\Sequence::join ([ string $glue ] ) : string

Joins all values together as a string using an optional separator between each value.

Parameters

glue

An optional string to separate each value.

Return Values

All values of the sequence joined together as a string.

Examples

Example #1 Ds\Sequence::join() example using a separator string

<?php
$sequence = new \Ds\Vector(["a", "b", "c", 1, 2, 3]);

var_dump($sequence->join("|"));
?>

The above example will output something similar to:

string(11) "a|b|c|1|2|3"

Example #2 Ds\Sequence::join() example without a separator string

<?php
$sequence = new \Ds\Vector(["a", "b", "c", 1, 2, 3]);

var_dump($sequence->join());
?>

The above example will output something similar to:

string(11) "abc123"


Returns the last value

  • « Ds\Sequence::join
  • Ds\Sequence::map »
  • PHP Manual
  • Sequence
  • Returns the last value

Ds\Sequence::last

(PECL ds >= 1.0.0)

Ds\Sequence::last — Returns the last value

Description

abstract public Ds\Sequence::last ( void ) : mixed

Returns the last value in the sequence.

Parameters

This function has no parameters.

Return Values

The last value in the sequence.

Errors/Exceptions

UnderflowException if empty.

Examples

Example #1 Ds\Sequence::last() example

<?php
$sequence = new \Ds\Vector([1, 2, 3]);
var_dump($sequence->last());
?>

The above example will output something similar to:

int(3)


Returns the result of applying a callback to each value

  • « Ds\Sequence::last
  • Ds\Sequence::merge »
  • PHP Manual
  • Sequence
  • Returns the result of applying a callback to each value

Ds\Sequence::map

(PECL ds >= 1.0.0)

Ds\Sequence::map — Returns the result of applying a callback to each value

Description

abstract public Ds\Sequence::map ( callable $callback ) : Ds\Sequence

Returns the result of applying a callback function to each value in the sequence.

Parameters

callback

callback ( mixed $value ) : mixed

A callable to apply to each value in the sequence.

The callable should return what the new value will be in the new sequence.

Return Values

The result of applying a callback to each value in the sequence.

Note:

The values of the current instance won't be affected.

Examples

Example #1 Ds\Sequence::map() example

<?php
$sequence = new \Ds\Vector([1, 2, 3]);

print_r($sequence->map(function($value) { return $value * 2; }));
print_r($sequence);
?>

The above example will output something similar to:

Ds\Vector Object
(
    [0] => 2
    [1] => 4
    [2] => 6
)
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)


Returns the result of adding all given values to the sequence

  • « Ds\Sequence::map
  • Ds\Sequence::pop »
  • PHP Manual
  • Sequence
  • Returns the result of adding all given values to the sequence

Ds\Sequence::merge

(PECL ds >= 1.0.0)

Ds\Sequence::merge — Returns the result of adding all given values to the sequence

Description

abstract public Ds\Sequence::merge ( mixed $values ) : Ds\Sequence

Returns the result of adding all given values to the sequence.

Parameters

values

A traversable object or an array.

Return Values

The result of adding all given values to the sequence, effectively the same as adding the values to a copy, then returning that copy.

Note:

The current instance won't be affected.

Examples

Example #1 Ds\Sequence::merge() example

<?php
$sequence = new \Ds\Vector([1, 2, 3]);

var_dump($sequence->merge([4, 5, 6]));
var_dump($sequence);
?>

The above example will output something similar to:

object(Ds\Vector)#2 (6) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
  [4]=>
  int(5)
  [5]=>
  int(6)
}
object(Ds\Vector)#1 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}


Removes and returns the last value

  • « Ds\Sequence::merge
  • Ds\Sequence::push »
  • PHP Manual
  • Sequence
  • Removes and returns the last value

Ds\Sequence::pop

(PECL ds >= 1.0.0)

Ds\Sequence::pop — Removes and returns the last value

Description

abstract public Ds\Sequence::pop ( void ) : mixed

Removes and returns the last value.

Parameters

This function has no parameters.

Return Values

The removed last value.

Errors/Exceptions

UnderflowException if empty.

Examples

Example #1 Ds\Sequence::pop() example

<?php
$sequence = new \Ds\Vector([1, 2, 3]);

var_dump($sequence->pop());
var_dump($sequence->pop());
var_dump($sequence->pop());
?>

The above example will output something similar to:

int(3)
int(2)
int(1)


Adds values to the end of the sequence

  • « Ds\Sequence::pop
  • Ds\Sequence::reduce »
  • PHP Manual
  • Sequence
  • Adds values to the end of the sequence

Ds\Sequence::push

(PECL ds >= 1.0.0)

Ds\Sequence::push — Adds values to the end of the sequence

Description

abstract public Ds\Sequence::push ([ mixed $...values ] ) : void

Adds values to the end of the sequence.

Parameters

values

The values to add.

Return Values

No value is returned.

Examples

Example #1 Ds\Sequence::push() example

<?php
$sequence = new \Ds\Vector();

$sequence->push("a");
$sequence->push("b");
$sequence->push("c", "d");
$sequence->push(...["e", "f"]);

print_r($sequence);
?>

The above example will output something similar to:

Ds\Vector Object
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
    [5] => f
)


Reduces the sequence to a single value using a callback function

  • « Ds\Sequence::push
  • Ds\Sequence::remove »
  • PHP Manual
  • Sequence
  • Reduces the sequence to a single value using a callback function

Ds\Sequence::reduce

(PECL ds >= 1.0.0)

Ds\Sequence::reduce — Reduces the sequence to a single value using a callback function

Description

abstract public Ds\Sequence::reduce ( callable $callback [, mixed $initial ] ) : mixed

Reduces the sequence to a single value using a callback function.

Parameters

callback
callback ( mixed $carry , mixed $value ) : mixed
carry

The return value of the previous callback, or initial if it's the first iteration.

value

The value of the current iteration.

initial

The initial value of the carry value. Can be NULL.

Return Values

The return value of the final callback.

Examples

Example #1 Ds\Sequence::reduce() with initial value example

<?php
$sequence = new \Ds\Vector([1, 2, 3]);

$callback = function($carry, $value) {
    return $carry * $value;
};

var_dump($sequence->reduce($callback, 5));

// Iterations:
//
// $carry = $initial = 5
//
// $carry = $carry * 1 =  5
// $carry = $carry * 2 = 10
// $carry = $carry * 3 = 30
?>

The above example will output something similar to:

int(30)

Example #2 Ds\Sequence::reduce() without an initial value example

<?php
$sequence = new \Ds\Vector([1, 2, 3]);

var_dump($sequence->reduce(function($carry, $value) {
    return $carry + $value + 5;
}));

// Iterations:
//
// $carry = $initial = null
//
// $carry = $carry + 1 + 5 =  6
// $carry = $carry + 2 + 5 = 13
// $carry = $carry + 3 + 5 = 21
?>

The above example will output something similar to:

int(21)


Removes and returns a value by index

  • « Ds\Sequence::reduce
  • Ds\Sequence::reverse »
  • PHP Manual
  • Sequence
  • Removes and returns a value by index

Ds\Sequence::remove

(PECL ds >= 1.0.0)

Ds\Sequence::remove — Removes and returns a value by index

Description

abstract public Ds\Sequence::remove ( int $index ) : mixed

Removes and returns a value by index.

Parameters

index

The index of the value to remove.

Return Values

The value that was removed.

Errors/Exceptions

OutOfRangeException if the index is not valid.

Examples

Example #1 Ds\Sequence::remove() example

<?php
$sequence = new \Ds\Vector(["a", "b", "c"]);

var_dump($sequence->remove(1));
var_dump($sequence->remove(0));
var_dump($sequence->remove(0));
?>

The above example will output something similar to:

string(1) "b"
string(1) "a"
string(1) "c"


Reverses the sequence in-place

  • « Ds\Sequence::remove
  • Ds\Sequence::reversed »
  • PHP Manual
  • Sequence
  • Reverses the sequence in-place

Ds\Sequence::reverse

(PECL ds >= 1.0.0)

Ds\Sequence::reverse — Reverses the sequence in-place

Description

abstract public Ds\Sequence::reverse ( void ) : void

Reverses the sequence in-place.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 Ds\Sequence::reverse() example

<?php
$sequence = new \Ds\Vector(["a", "b", "c"]);
$sequence->reverse();

print_r($sequence);
?>

The above example will output something similar to:

Ds\Vector Object
(
    [0] => c
    [1] => b
    [2] => a
)


Returns a reversed copy

  • « Ds\Sequence::reverse
  • Ds\Sequence::rotate »
  • PHP Manual
  • Sequence
  • Returns a reversed copy

Ds\Sequence::reversed

(PECL ds >= 1.0.0)

Ds\Sequence::reversed — Returns a reversed copy

Description

abstract public Ds\Sequence::reversed ( void ) : Ds\Sequence

Returns a reversed copy of the sequence.

Parameters

This function has no parameters.

Return Values

A reversed copy of the sequence.

Note:

The current instance is not affected.

Examples

Example #1 Ds\Sequence::reversed() example

<?php
$sequence = new \Ds\Vector(["a", "b", "c"]);

print_r($sequence->reversed());
print_r($sequence);
?>

The above example will output something similar to:

Ds\Vector Object
(
    [0] => c
    [1] => b
    [2] => a
)
Ds\Vector Object
(
    [0] => a
    [1] => b
    [2] => c
)


Rotates the sequence by a given number of rotations

  • « Ds\Sequence::reversed
  • Ds\Sequence::set »
  • PHP Manual
  • Sequence
  • Rotates the sequence by a given number of rotations

Ds\Sequence::rotate

(PECL ds >= 1.0.0)

Ds\Sequence::rotate — Rotates the sequence by a given number of rotations

Description

abstract public Ds\Sequence::rotate ( int $rotations ) : void

Rotates the sequence by a given number of rotations, which is equivalent to successively calling $sequence->push($sequence->shift()) if the number of rotations is positive, or $sequence->unshift($sequence->pop()) if negative.

Parameters

rotations

The number of times the sequence should be rotated.

Return Values

No value is returned.. The sequence of the current instance will be rotated.

Examples

Example #1 Ds\Sequence::rotate() example

<?php
$sequence = new \Ds\Vector(["a", "b", "c", "d"]);

$sequence->rotate(1);  // "a" is shifted, then pushed.
print_r($sequence);

$sequence->rotate(2);  // "b" and "c" are both shifted, the pushed.
print_r($sequence);
?>

The above example will output something similar to:

(
    [0] => b
    [1] => c
    [2] => d
    [3] => a
)
Ds\Vector Object
(
    [0] => d
    [1] => a
    [2] => b
    [3] => c
)


Updates a value at a given index

  • « Ds\Sequence::rotate
  • Ds\Sequence::shift »
  • PHP Manual
  • Sequence
  • Updates a value at a given index

Ds\Sequence::set

(PECL ds >= 1.0.0)

Ds\Sequence::set — Updates a value at a given index

Description

abstract public Ds\Sequence::set ( int $index , mixed $value ) : void

Updates a value at a given index.

Parameters

index

The index of the value to update.

value

The new value.

Return Values

No value is returned.

Errors/Exceptions

OutOfRangeException if the index is not valid.

Examples

Example #1 Ds\Sequence::set() example

<?php
$sequence = new \Ds\Vector(["a", "b", "c"]);

$sequence->set(1, "_");
print_r($sequence);
?>

The above example will output something similar to:

Ds\Vector Object
(
    [0] => a
    [1] => _
    [2] => c
)

Example #2 Ds\Sequence::set() example using array syntax

<?php
$sequence = new \Ds\Vector(["a", "b", "c"]);

$sequence[1] = "_";
print_r($sequence);
?>

The above example will output something similar to:

Ds\Vector Object
(
    [0] => a
    [1] => _
    [2] => c
)


Removes and returns the first value

  • « Ds\Sequence::set
  • Ds\Sequence::slice »
  • PHP Manual
  • Sequence
  • Removes and returns the first value

Ds\Sequence::shift

(PECL ds >= 1.0.0)

Ds\Sequence::shift — Removes and returns the first value

Description

abstract public Ds\Sequence::shift ( void ) : mixed

Removes and returns the first value.

Parameters

This function has no parameters.

Return Values

The first value, which was removed.

Errors/Exceptions

UnderflowException if empty.

Examples

Example #1 Ds\Sequence::shift() example

<?php
$sequence = new \Ds\Vector(["a", "b", "c"]);

var_dump($sequence->shift());
var_dump($sequence->shift());
var_dump($sequence->shift());
?>

The above example will output something similar to:

string(1) "a"
string(1) "b"
string(1) "c"


Returns a sub-sequence of a given range

  • « Ds\Sequence::shift
  • Ds\Sequence::sort »
  • PHP Manual
  • Sequence
  • Returns a sub-sequence of a given range

Ds\Sequence::slice

(PECL ds >= 1.0.0)

Ds\Sequence::slice — Returns a sub-sequence of a given range

Description

abstract public Ds\Sequence::slice ( int $index [, int $length ] ) : Ds\Sequence

Creates a sub-sequence of a given range.

Parameters

index

The index at which the sub-sequence starts.

If positive, the sequence will start at that index in the sequence. If negative, the sequence will start that far from the end.

length

If a length is given and is positive, the resulting sequence will have up to that many values in it. If the length results in an overflow, only values up to the end of the sequence will be included. If a length is given and is negative, the sequence will stop that many values from the end. If a length is not provided, the resulting sequence will contain all values between the index and the end of the sequence.

Return Values

A sub-sequence of the given range.

Examples

Example #1 Ds\Sequence::slice() example

<?php
$sequence = new \Ds\Vector(["a", "b", "c", "d", "e"]);

// Slice from 2 onwards
print_r($sequence->slice(2));

// Slice from 1, for a length of 3
print_r($sequence->slice(1, 3));

// Slice from 1 onwards
print_r($sequence->slice(1));

// Slice from 2 from the end onwards
print_r($sequence->slice(-2));

// Slice from 1 to 1 from the end
print_r($sequence->slice(1, -1));
?>

The above example will output something similar to:

Ds\Vector Object
(
    [0] => c
    [1] => d
    [2] => e
)
Ds\Vector Object
(
    [0] => b
    [1] => c
    [2] => d
)
Ds\Vector Object
(
    [0] => b
    [1] => c
    [2] => d
    [3] => e
)
Ds\Vector Object
(
    [0] => d
    [1] => e
)
Ds\Vector Object
(
    [0] => b
    [1] => c
    [2] => d
)


Sorts the sequence in-place

  • « Ds\Sequence::slice
  • Ds\Sequence::sorted »
  • PHP Manual
  • Sequence
  • Sorts the sequence in-place

Ds\Sequence::sort

(PECL ds >= 1.0.0)

Ds\Sequence::sort — Sorts the sequence in-place

Description

abstract public Ds\Sequence::sort ([ callable $comparator ] ) : void

Sorts the sequence in-place, using an optional comparator function.

Parameters

comparator

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. Note that before PHP 7.0.0 this integer had to be in the range from -2147483648 to 2147483647.

callback ( mixed $a, mixed $b ) : int
Caution

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

Return Values

No value is returned.

Examples

Example #1 Ds\Sequence::sort() example

<?php
$sequence = new \Ds\Vector([4, 5, 1, 3, 2]);
$sequence->sort();

print_r($sequence);
?>

The above example will output something similar to:

Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Example #2 Ds\Sequence::sort() example using a comparator

<?php
$sequence = new \Ds\Vector([4, 5, 1, 3, 2]);

$sequence->sort(function($a, $b) {
    return $b <=> $a;
});

print_r($sequence);
?>

The above example will output something similar to:

Ds\Vector Object
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)


Returns a sorted copy

  • « Ds\Sequence::sort
  • Ds\Sequence::sum »
  • PHP Manual
  • Sequence
  • Returns a sorted copy

Ds\Sequence::sorted

(PECL ds >= 1.0.0)

Ds\Sequence::sorted — Returns a sorted copy

Description

abstract public Ds\Sequence::sorted ([ callable $comparator ] ) : Ds\Sequence

Returns a sorted copy, using an optional comparator function.

Parameters

comparator

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. Note that before PHP 7.0.0 this integer had to be in the range from -2147483648 to 2147483647.

callback ( mixed $a, mixed $b ) : int
Caution

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

Return Values

Returns a sorted copy of the sequence.

Examples

Example #1 Ds\Sequence::sorted() example

<?php
$sequence = new \Ds\Vector([4, 5, 1, 3, 2]);

print_r($sequence->sorted());
?>

The above example will output something similar to:

Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Example #2 Ds\Sequence::sorted() example using a comparator

<?php
$sequence = new \Ds\Vector([4, 5, 1, 3, 2]);

$sorted = $sequence->sorted(function($a, $b) {
    return $b <=> $a;
});

print_r($sorted);
?>

The above example will output something similar to:

Ds\Vector Object
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)


Returns the sum of all values in the sequence

  • « Ds\Sequence::sorted
  • Ds\Sequence::unshift »
  • PHP Manual
  • Sequence
  • Returns the sum of all values in the sequence

Ds\Sequence::sum

(PECL ds >= 1.0.0)

Ds\Sequence::sum — Returns the sum of all values in the sequence

Description

abstract public Ds\Sequence::sum ( void ) : number

Returns the sum of all values in the sequence.

Note:

Arrays and objects are considered equal to zero when calculating the sum.

Parameters

This function has no parameters.

Return Values

The sum of all the values in the sequence as either a float or int depending on the values in the sequence.

Examples

Example #1 Ds\Sequence::sum() integer example

<?php
$sequence = new \Ds\Vector([1, 2, 3]);
var_dump($sequence->sum());
?>

The above example will output something similar to:

int(6)

Example #2 Ds\Sequence::sum() float example

<?php
$sequence = new \Ds\Vector([1, 2.5, 3]);
var_dump($sequence->sum());
?>

The above example will output something similar to:

float(6.5)


Adds values to the front of the sequence

  • « Ds\Sequence::sum
  • Vector »
  • PHP Manual
  • Sequence
  • Adds values to the front of the sequence

Ds\Sequence::unshift

(PECL ds >= 1.0.0)

Ds\Sequence::unshift — Adds values to the front of the sequence

Description

abstract public Ds\Sequence::unshift ([ mixed $values ] ) : void

Adds values to the front of the sequence, moving all the current values forward to make room for the new values.

Parameters

values

The values to add to the front of the sequence.

Note:

Multiple values will be added in the same order that they are passed.

Return Values

No value is returned.

Examples

Example #1 Ds\Sequence::unshift() example

<?php
$sequence = new \Ds\Vector([1, 2, 3]);

$sequence->unshift("a");
$sequence->unshift("b", "c");

print_r($sequence);
?>

The above example will output something similar to:

Ds\Vector Object
(
    [0] => b
    [1] => c
    [2] => a
    [3] => 1
    [4] => 2
    [5] => 3
)


The Vector class

(No version information available, might only be in Git)

Introduction

A Vector is a sequence of values in a contiguous buffer that grows and shrinks automatically. It’s the most efficient sequential structure because a value’s index is a direct mapping to its index in the buffer, and the growth factor isn't bound to a specific multiple or exponent.

Strengths

  • Supports array syntax (square brackets).
  • Uses less overall memory than an array for the same number of values.
  • Automatically frees allocated memory when its size drops low enough.
  • Capacity does not have to be a power of 2.
  • get(),
set(),
push(),
pop() are all O(1).

Weaknesses

  • shift(),
unshift(),
insert() and
remove() are all O(n).

Class synopsis

Ds\Vector implements Ds\Sequence {
/* Constants */
const int MIN_CAPACITY = 10 ;
/* Methods */
public allocate ( int $capacity ) : void
public apply ( callable $callback ) : void
public capacity ( void ) : int
public clear ( void ) : void
public contains ([ mixed $...values ] ) : bool
public copy ( void ) : Ds\Vector
public filter ([ callable $callback ] ) : Ds\Vector
public find ( mixed $value ) : mixed
public first ( void ) : mixed
public get ( int $index ) : mixed
public insert ( int $index [, mixed $...values ] ) : void
public isEmpty ( void ) : bool
public join ([ string $glue ] ) : string
public last ( void ) : mixed
public map ( callable $callback ) : Ds\Vector
public merge ( mixed $values ) : Ds\Vector
public pop ( void ) : mixed
public push ([ mixed $...values ] ) : void
public reduce ( callable $callback [, mixed $initial ] ) : mixed
public remove ( int $index ) : mixed
public reverse ( void ) : void
public reversed ( void ) : Ds\Vector
public rotate ( int $rotations ) : void
public set ( int $index , mixed $value ) : void
public shift ( void ) : mixed
public slice ( int $index [, int $length ] ) : Ds\Vector
public sort ([ callable $comparator ] ) : void
public sorted ([ callable $comparator ] ) : Ds\Vector
public sum ( void ) : number
public toArray ( void ) : array
public unshift ([ mixed $values ] ) : void
}

Predefined Constants

Ds\Vector::MIN_CAPACITY

Table of Contents

  • Ds\Vector::allocate — Allocates enough memory for a required capacity
  • Ds\Vector::apply — Updates all values by applying a callback function to each value
  • Ds\Vector::capacity — Returns the current capacity
  • Ds\Vector::clear — Removes all values
  • Ds\Vector::__construct — Creates a new instance
  • Ds\Vector::contains — Determines if the vector contains given values
  • Ds\Vector::copy — Returns a shallow copy of the vector
  • Ds\Vector::count — Returns the number of values in the collection
  • Ds\Vector::filter — Creates a new vector using a callable to determine which values to include
  • Ds\Vector::find — Attempts to find a value's index
  • Ds\Vector::first — Returns the first value in the vector
  • Ds\Vector::get — Returns the value at a given index
  • Ds\Vector::insert — Inserts values at a given index
  • Ds\Vector::isEmpty — Returns whether the vector is empty
  • Ds\Vector::join — Joins all values together as a string
  • Ds\Vector::jsonSerialize — Returns a representation that can be converted to JSON
  • Ds\Vector::last — Returns the last value
  • Ds\Vector::map — Returns the result of applying a callback to each value
  • Ds\Vector::merge — Returns the result of adding all given values to the vector
  • Ds\Vector::pop — Removes and returns the last value
  • Ds\Vector::push — Adds values to the end of the vector
  • Ds\Vector::reduce — Reduces the vector to a single value using a callback function
  • Ds\Vector::remove — Removes and returns a value by index
  • Ds\Vector::reverse — Reverses the vector in-place
  • Ds\Vector::reversed — Returns a reversed copy
  • Ds\Vector::rotate — Rotates the vector by a given number of rotations
  • Ds\Vector::set — Updates a value at a given index
  • Ds\Vector::shift — Removes and returns the first value
  • Ds\Vector::slice — Returns a sub-vector of a given range
  • Ds\Vector::sort — Sorts the vector in-place
  • Ds\Vector::sorted — Returns a sorted copy
  • Ds\Vector::sum — Returns the sum of all values in the vector
  • Ds\Vector::toArray — Converts the vector to an array
  • Ds\Vector::unshift — Adds values to the front of the vector


Allocates enough memory for a required capacity

  • « Vector
  • Ds\Vector::apply »
  • PHP Manual
  • Vector
  • Allocates enough memory for a required capacity

Ds\Vector::allocate

(PECL ds >= 1.0.0)

Ds\Vector::allocate — Allocates enough memory for a required capacity

Description

public Ds\Vector::allocate ( int $capacity ) : void

Ensures that enough memory is allocated for a required capacity. This removes the need to reallocate the internal as values are added.

Parameters

capacity

The number of values for which capacity should be allocated.

Note:

Capacity will stay the same if this value is less than or equal to the current capacity.

Return Values

No value is returned.

Examples

Example #1 Ds\Vector::allocate() example

<?php
$vector = new \Ds\Vector();
var_dump($vector->capacity());

$vector->allocate(100);
var_dump($vector->capacity());
?>

The above example will output something similar to:

int(10)
int(100)


Updates all values by applying a callback function to each value

  • « Ds\Vector::allocate
  • Ds\Vector::capacity »
  • PHP Manual
  • Vector
  • Updates all values by applying a callback function to each value

Ds\Vector::apply

(PECL ds >= 1.0.0)

Ds\Vector::apply — Updates all values by applying a callback function to each value

Description

public Ds\Vector::apply ( callable $callback ) : void

Updates all values by applying a callback function to each value in the vector.

Parameters

callback

callback ( mixed $value ) : mixed

A callable to apply to each value in the vector.

The callback should return what the value should be replaced by.

Return Values

No value is returned.

Examples

Example #1 Ds\Vector::apply() example

<?php
$vector = new \Ds\Vector([1, 2, 3]);
$vector->apply(function($value) { return $value * 2; });

print_r($vector);
?>

The above example will output something similar to:

Ds\Vector Object
(
    [0] => 2
    [1] => 4
    [2] => 6
)


Returns the current capacity

  • « Ds\Vector::apply
  • Ds\Vector::clear »
  • PHP Manual
  • Vector
  • Returns the current capacity

Ds\Vector::capacity

(PECL ds >= 1.0.0)

Ds\Vector::capacity — Returns the current capacity

Description

public Ds\Vector::capacity ( void ) : int

Returns the current capacity.

Parameters

This function has no parameters.

Return Values

The current capacity.

Examples

Example #1 Ds\Vector::capacity() example

<?php
$vector = new \Ds\Vector();
var_dump($vector->capacity());

$vector->push(...range(1, 50));
var_dump($vector->capacity());

$vector[] = "a";
var_dump($vector->capacity());
?>

The above example will output something similar to:

int(10)
int(50)
int(75)


Removes all values

  • « Ds\Vector::capacity
  • Ds\Vector::__construct »
  • PHP Manual
  • Vector
  • Removes all values

Ds\Vector::clear

(PECL ds >= 1.0.0)

Ds\Vector::clear — Removes all values

Description

public Ds\Vector::clear ( void ) : void

Removes all values from the vector.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 Ds\Vector::clear() example

<?php
$vector = new \Ds\Vector([1, 2, 3]);
print_r($vector);

$vector->clear();
print_r($vector);
?>

The above example will output something similar to:

Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Vector Object
(
)


Creates a new instance

  • « Ds\Vector::clear
  • Ds\Vector::contains »
  • PHP Manual
  • Vector
  • Creates a new instance

Ds\Vector::__construct

(PECL ds >= 1.0.0)

Ds\Vector::__construct — Creates a new instance

Description

public Ds\Vector::__construct ([ mixed $values ] )

Creates a new instance, using either a traversable object or an array for the initial values.

Parameters

values

A traversable object or an array to use for the initial values.

Examples

Example #1 Ds\Vector::__construct() example

<?php
$vector = new \Ds\Vector();
var_dump($vector);

$vector = new \Ds\Vector([1, 2, 3]);
var_dump($vector);
?>

The above example will output something similar to:

object(Ds\Vector)#2 (0) {
}
object(Ds\Vector)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}


Determines if the vector contains given values

  • « Ds\Vector::__construct
  • Ds\Vector::copy »
  • PHP Manual
  • Vector
  • Determines if the vector contains given values

Ds\Vector::contains

(PECL ds >= 1.0.0)

Ds\Vector::contains — Determines if the vector contains given values

Description

public Ds\Vector::contains ([ mixed $...values ] ) : bool

Determines if the vector contains all values.

Parameters

values

Values to check.

Return Values

FALSE if any of the provided values are not in the vector, TRUE otherwise.

Examples

Example #1 Ds\Vector::contains() example

<?php
$vector = new \Ds\Vector(['a', 'b', 'c', 1, 2, 3]);

var_dump($vector->contains('a'));                // true
var_dump($vector->contains('a', 'b'));           // true
var_dump($vector->contains('c', 'd'));           // false

var_dump($vector->contains(...['c', 'b', 'a'])); // true

// Always strict
var_dump($vector->contains(1));                  // true
var_dump($vector->contains('1'));                // false

var_dump($sequece->contains(...[]));               // true
?>

The above example will output something similar to:

bool(true)
bool(true)
bool(false)
bool(true)
bool(true)
bool(false)
bool(true)


Returns a shallow copy of the vector

  • « Ds\Vector::contains
  • Ds\Vector::count »
  • PHP Manual
  • Vector
  • Returns a shallow copy of the vector

Ds\Vector::copy

(PECL ds >= 1.0.0)

Ds\Vector::copy — Returns a shallow copy of the vector

Description

public Ds\Vector::copy ( void ) : Ds\Vector

Returns a shallow copy of the vector.

Parameters

This function has no parameters.

Return Values

Returns a shallow copy of the vector.

Examples

Example #1 Ds\Vector::copy() example

<?php
$a = new \Ds\Vector([1, 2, 3]);
$b = $a->copy();

// Updating the copy doesn't affect the original
$b->push(4);

print_r($a);
print_r($b);
?>

The above example will output something similar to:

Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)


Returns the number of values in the collection

  • « Ds\Vector::copy
  • Ds\Vector::filter »
  • PHP Manual
  • Vector
  • Returns the number of values in the collection

Ds\Vector::count

(PECL ds >= 1.0.0)

Ds\Vector::count — Returns the number of values in the collection

See Countable::count()


Creates a new vector using a callable to determine which values to include

  • « Ds\Vector::count
  • Ds\Vector::find »
  • PHP Manual
  • Vector
  • Creates a new vector using a callable to determine which values to include

Ds\Vector::filter

(PECL ds >= 1.0.0)

Ds\Vector::filter — Creates a new vector using a callable to determine which values to include

Description

public Ds\Vector::filter ([ callable $callback ] ) : Ds\Vector

Creates a new vector using a callable to determine which values to include.

Parameters

callback

callback ( mixed $value ) : bool

Optional callable which returns TRUE if the value should be included, FALSE otherwise.

If a callback is not provided, only values which are TRUE (see converting to boolean) will be included.

Return Values

A new vector containing all the values for which either the callback returned TRUE, or all values that convert to TRUE if a callback was not provided.

Examples

Example #1 Ds\Vector::filter() example using callback function

<?php
$vector = new \Ds\Vector([1, 2, 3, 4, 5]);

var_dump($vector->filter(function($value) {
    return $value % 2 == 0;
}));
?>

The above example will output something similar to:

object(Ds\Vector)#3 (2) {
  [0]=>
  int(2)
  [1]=>
  int(4)
}

Example #2 Ds\Vector::filter() example without a callback function

<?php
$vector = new \Ds\Vector([0, 1, 'a', true, false]);

var_dump($vector->filter());
?>

The above example will output something similar to:

object(Ds\Vector)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  string(1) "a"
  [2]=>
  bool(true)
}


Attempts to find a value's index

  • « Ds\Vector::filter
  • Ds\Vector::first »
  • PHP Manual
  • Vector
  • Attempts to find a value's index

Ds\Vector::find

(PECL ds >= 1.0.0)

Ds\Vector::find — Attempts to find a value's index

Description

public Ds\Vector::find ( mixed $value ) : mixed

Returns the index of the value, or FALSE if not found.

Parameters

value

The value to find.

Return Values

The index of the value, or FALSE if not found.

Note:

Values will be compared by value and by type.

Examples

Example #1 Ds\Vector::find() example

<?php
$vector = new \Ds\Vector(["a", 1, true]);

var_dump($vector->find("a")); // 0
var_dump($vector->find("b")); // false
var_dump($vector->find("1")); // false
var_dump($vector->find(1));   // 1
?>

The above example will output something similar to:

int(0)
bool(false)
bool(false)
int(1)


Returns the first value in the vector

  • « Ds\Vector::find
  • Ds\Vector::get »
  • PHP Manual
  • Vector
  • Returns the first value in the vector

Ds\Vector::first

(PECL ds >= 1.0.0)

Ds\Vector::first — Returns the first value in the vector

Description

public Ds\Vector::first ( void ) : mixed

Returns the first value in the vector.

Parameters

This function has no parameters.

Return Values

The first value in the vector.

Errors/Exceptions

UnderflowException if empty.

Examples

Example #1 Ds\Vector::first() example

<?php
$vector = new \Ds\Vector([1, 2, 3]);
var_dump($vector->first());
?>

The above example will output something similar to:

int(1)


Returns the value at a given index

  • « Ds\Vector::first
  • Ds\Vector::insert »
  • PHP Manual
  • Vector
  • Returns the value at a given index

Ds\Vector::get

(PECL ds >= 1.0.0)

Ds\Vector::get — Returns the value at a given index

Description

public Ds\Vector::get ( int $index ) : mixed

Returns the value at a given index.

Parameters

index

The index to access, starting at 0.

Return Values

The value at the requested index.

Errors/Exceptions

OutOfRangeException if the index is not valid.

Examples

Example #1 Ds\Vector::get() example

<?php
$vector = new \Ds\Vector(["a", "b", "c"]);

var_dump($vector->get(0));
var_dump($vector->get(1));
var_dump($vector->get(2));
?>

The above example will output something similar to:

string(1) "a"
string(1) "b"
string(1) "c"

Example #2 Ds\Vector::get() example using array syntax

<?php
$vector = new \Ds\Vector(["a", "b", "c"]);

var_dump($vector[0]);
var_dump($vector[1]);
var_dump($vector[2]);
?>

The above example will output something similar to:

string(1) "a"
string(1) "b"
string(1) "c"


Inserts values at a given index

  • « Ds\Vector::get
  • Ds\Vector::isEmpty »
  • PHP Manual
  • Vector
  • Inserts values at a given index

Ds\Vector::insert

(PECL ds >= 1.0.0)

Ds\Vector::insert — Inserts values at a given index

Description

public Ds\Vector::insert ( int $index [, mixed $...values ] ) : void

Inserts values into the vector at a given index.

Parameters

index

The index at which to insert. 0 <= index <= count

Note:

You can insert at the index equal to the number of values.

values

The value or values to insert.

Return Values

No value is returned.

Errors/Exceptions

OutOfRangeException if the index is not valid.

Examples

Example #1 Ds\Vector::insert() example

<?php
$vector = new \Ds\Vector();

$vector->insert(0, "e");             // [e]
$vector->insert(1, "f");             // [e, f]
$vector->insert(2, "g");             // [e, f, g]
$vector->insert(0, "a", "b");        // [a, b, e, f, g]
$vector->insert(2, ...["c", "d"]);   // [a, b, c, d, e, f, g]

var_dump($vector);
?>

The above example will output something similar to:

object(Ds\Vector)#1 (7) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  string(1) "e"
  [5]=>
  string(1) "f"
  [6]=>
  string(1) "g"
}


Returns whether the vector is empty

  • « Ds\Vector::insert
  • Ds\Vector::join »
  • PHP Manual
  • Vector
  • Returns whether the vector is empty

Ds\Vector::isEmpty

(PECL ds >= 1.0.0)

Ds\Vector::isEmpty — Returns whether the vector is empty

Description

public Ds\Vector::isEmpty ( void ) : bool

Returns whether the vector is empty.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the vector is empty, FALSE otherwise.

Examples

Example #1 Ds\Vector::isEmpty() example

<?php
$a = new \Ds\Vector([1, 2, 3]);
$b = new \Ds\Vector();

var_dump($a->isEmpty());
var_dump($b->isEmpty());
?>

The above example will output something similar to:

bool(false)
bool(true)


Joins all values together as a string

  • « Ds\Vector::isEmpty
  • Ds\Vector::jsonSerialize »
  • PHP Manual
  • Vector
  • Joins all values together as a string

Ds\Vector::join

(PECL ds >= 1.0.0)

Ds\Vector::join — Joins all values together as a string

Description

public Ds\Vector::join ([ string $glue ] ) : string

Joins all values together as a string using an optional separator between each value.

Parameters

glue

An optional string to separate each value.

Return Values

All values of the vector joined together as a string.

Examples

Example #1 Ds\Vector::join() example using a separator string

<?php
$vector = new \Ds\Vector(["a", "b", "c", 1, 2, 3]);

var_dump($vector->join("|"));
?>

The above example will output something similar to:

string(11) "a|b|c|1|2|3"

Example #2 Ds\Vector::join() example without a separator string

<?php
$vector = new \Ds\Vector(["a", "b", "c", 1, 2, 3]);

var_dump($vector->join());
?>

The above example will output something similar to:

string(11) "abc123"


Returns a representation that can be converted to JSON

  • « Ds\Vector::join
  • Ds\Vector::last »
  • PHP Manual
  • Vector
  • Returns a representation that can be converted to JSON

Ds\Vector::jsonSerialize

(PECL ds >= 1.0.0)

Ds\Vector::jsonSerialize — Returns a representation that can be converted to JSON

See JsonSerializable::jsonSerialize()

Note:

You should never need to call this directly.


Returns the last value

  • « Ds\Vector::jsonSerialize
  • Ds\Vector::map »
  • PHP Manual
  • Vector
  • Returns the last value

Ds\Vector::last

(PECL ds >= 1.0.0)

Ds\Vector::last — Returns the last value

Description

public Ds\Vector::last ( void ) : mixed

Returns the last value in the vector.

Parameters

This function has no parameters.

Return Values

The last value in the vector.

Errors/Exceptions

UnderflowException if empty.

Examples

Example #1 Ds\Vector::last() example

<?php
$vector = new \Ds\Vector([1, 2, 3]);
var_dump($vector->last());
?>

The above example will output something similar to:

int(3)


Returns the result of applying a callback to each value

  • « Ds\Vector::last
  • Ds\Vector::merge »
  • PHP Manual
  • Vector
  • Returns the result of applying a callback to each value

Ds\Vector::map

(PECL ds >= 1.0.0)

Ds\Vector::map — Returns the result of applying a callback to each value

Description

public Ds\Vector::map ( callable $callback ) : Ds\Vector

Returns the result of applying a callback function to each value in the vector.

Parameters

callback

callback ( mixed $value ) : mixed

A callable to apply to each value in the vector.

The callable should return what the new value will be in the new vector.

Return Values

The result of applying a callback to each value in the vector.

Note:

The values of the current instance won't be affected.

Examples

Example #1 Ds\Vector::map() example

<?php
$vector = new \Ds\Vector([1, 2, 3]);

print_r($vector->map(function($value) { return $value * 2; }));
print_r($vector);
?>

The above example will output something similar to:

Ds\Vector Object
(
    [0] => 2
    [1] => 4
    [2] => 6
)
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)


Returns the result of adding all given values to the vector

  • « Ds\Vector::map
  • Ds\Vector::pop »
  • PHP Manual
  • Vector
  • Returns the result of adding all given values to the vector

Ds\Vector::merge

(PECL ds >= 1.0.0)

Ds\Vector::merge — Returns the result of adding all given values to the vector

Description

public Ds\Vector::merge ( mixed $values ) : Ds\Vector

Returns the result of adding all given values to the vector.

Parameters

values

A traversable object or an array.

Return Values

The result of adding all given values to the vector, effectively the same as adding the values to a copy, then returning that copy.

Note:

The current instance won't be affected.

Examples

Example #1 Ds\Vector::merge() example

<?php
$vector = new \Ds\Vector([1, 2, 3]);

var_dump($vector->merge([4, 5, 6]));
var_dump($vector);
?>

The above example will output something similar to:

object(Ds\Vector)#2 (6) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
  [4]=>
  int(5)
  [5]=>
  int(6)
}
object(Ds\Vector)#1 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}


Removes and returns the last value

  • « Ds\Vector::merge
  • Ds\Vector::push »
  • PHP Manual
  • Vector
  • Removes and returns the last value

Ds\Vector::pop

(PECL ds >= 1.0.0)

Ds\Vector::pop — Removes and returns the last value

Description

public Ds\Vector::pop ( void ) : mixed

Removes and returns the last value.

Parameters

This function has no parameters.

Return Values

The removed last value.

Errors/Exceptions

UnderflowException if empty.

Examples

Example #1 Ds\Vector::pop() example

<?php
$vector = new \Ds\Vector([1, 2, 3]);

var_dump($vector->pop());
var_dump($vector->pop());
var_dump($vector->pop());
?>

The above example will output something similar to:

int(3)
int(2)
int(1)


Adds values to the end of the vector

  • « Ds\Vector::pop
  • Ds\Vector::reduce »
  • PHP Manual
  • Vector
  • Adds values to the end of the vector

Ds\Vector::push

(PECL ds >= 1.0.0)

Ds\Vector::push — Adds values to the end of the vector

Description

public Ds\Vector::push ([ mixed $...values ] ) : void

Adds values to the end of the vector.

Parameters

values

The values to add.

Return Values

No value is returned.

Examples

Example #1 Ds\Vector::push() example

<?php
$vector = new \Ds\Vector();

$vector->push("a");
$vector->push("b");
$vector->push("c", "d");
$vector->push(...["e", "f"]);

print_r($vector);
?>

The above example will output something similar to:

Ds\Vector Object
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
    [5] => f
)


Reduces the vector to a single value using a callback function

  • « Ds\Vector::push
  • Ds\Vector::remove »
  • PHP Manual
  • Vector
  • Reduces the vector to a single value using a callback function

Ds\Vector::reduce

(PECL ds >= 1.0.0)

Ds\Vector::reduce — Reduces the vector to a single value using a callback function

Description

public Ds\Vector::reduce ( callable $callback [, mixed $initial ] ) : mixed

Reduces the vector to a single value using a callback function.

Parameters

callback
callback ( mixed $carry , mixed $value ) : mixed
carry

The return value of the previous callback, or initial if it's the first iteration.

value

The value of the current iteration.

initial

The initial value of the carry value. Can be NULL.

Return Values

The return value of the final callback.

Examples

Example #1 Ds\Vector::reduce() with initial value example

<?php
$vector = new \Ds\Vector([1, 2, 3]);

$callback = function($carry, $value) {
    return $carry * $value;
};

var_dump($vector->reduce($callback, 5));

// Iterations:
//
// $carry = $initial = 5
//
// $carry = $carry * 1 =  5
// $carry = $carry * 2 = 10
// $carry = $carry * 3 = 30
?>

The above example will output something similar to:

int(30)

Example #2 Ds\Vector::reduce() without an initial value example

<?php
$vector = new \Ds\Vector([1, 2, 3]);

var_dump($vector->reduce(function($carry, $value) {
    return $carry + $value + 5;
}));

// Iterations:
//
// $carry = $initial = null
//
// $carry = $carry + 1 + 5 =  6
// $carry = $carry + 2 + 5 = 13
// $carry = $carry + 3 + 5 = 21
?>

The above example will output something similar to:

int(21)


Removes and returns a value by index

  • « Ds\Vector::reduce
  • Ds\Vector::reverse »
  • PHP Manual
  • Vector
  • Removes and returns a value by index

Ds\Vector::remove

(PECL ds >= 1.0.0)

Ds\Vector::remove — Removes and returns a value by index

Description

public Ds\Vector::remove ( int $index ) : mixed

Removes and returns a value by index.

Parameters

index

The index of the value to remove.

Return Values

The value that was removed.

Errors/Exceptions

OutOfRangeException if the index is not valid.

Examples

Example #1 Ds\Vector::remove() example

<?php
$vector = new \Ds\Vector(["a", "b", "c"]);

var_dump($vector->remove(1));
var_dump($vector->remove(0));
var_dump($vector->remove(0));
?>

The above example will output something similar to:

string(1) "b"
string(1) "a"
string(1) "c"


Reverses the vector in-place

  • « Ds\Vector::remove
  • Ds\Vector::reversed »
  • PHP Manual
  • Vector
  • Reverses the vector in-place

Ds\Vector::reverse

(PECL ds >= 1.0.0)

Ds\Vector::reverse — Reverses the vector in-place

Description

public Ds\Vector::reverse ( void ) : void

Reverses the vector in-place.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 Ds\Vector::reverse() example

<?php
$vector = new \Ds\Vector(["a", "b", "c"]);
$vector->reverse();

print_r($vector);
?>

The above example will output something similar to:

Ds\Vector Object
(
    [0] => c
    [1] => b
    [2] => a
)


Returns a reversed copy

  • « Ds\Vector::reverse
  • Ds\Vector::rotate »
  • PHP Manual
  • Vector
  • Returns a reversed copy

Ds\Vector::reversed

(PECL ds >= 1.0.0)

Ds\Vector::reversed — Returns a reversed copy

Description

public Ds\Vector::reversed ( void ) : Ds\Vector

Returns a reversed copy of the vector.

Parameters

This function has no parameters.

Return Values

A reversed copy of the vector.

Note:

The current instance is not affected.

Examples

Example #1 Ds\Vector::reversed() example

<?php
$vector = new \Ds\Vector(["a", "b", "c"]);

print_r($vector->reversed());
print_r($vector);
?>

The above example will output something similar to:

Ds\Vector Object
(
    [0] => c
    [1] => b
    [2] => a
)
Ds\Vector Object
(
    [0] => a
    [1] => b
    [2] => c
)


Rotates the vector by a given number of rotations

  • « Ds\Vector::reversed
  • Ds\Vector::set »
  • PHP Manual
  • Vector
  • Rotates the vector by a given number of rotations

Ds\Vector::rotate

(PECL ds >= 1.0.0)

Ds\Vector::rotate — Rotates the vector by a given number of rotations

Description

public Ds\Vector::rotate ( int $rotations ) : void

Rotates the vector by a given number of rotations, which is equivalent to successively calling $vector->push($vector->shift()) if the number of rotations is positive, or $vector->unshift($vector->pop()) if negative.

Parameters

rotations

The number of times the vector should be rotated.

Return Values

No value is returned.. The vector of the current instance will be rotated.

Examples

Example #1 Ds\Vector::rotate() example

<?php
$vector = new \Ds\Vector(["a", "b", "c", "d"]);

$vector->rotate(1);  // "a" is shifted, then pushed.
print_r($vector);

$vector->rotate(2);  // "b" and "c" are both shifted, the pushed.
print_r($vector);
?>

The above example will output something similar to:

(
    [0] => b
    [1] => c
    [2] => d
    [3] => a
)
Ds\Vector Object
(
    [0] => d
    [1] => a
    [2] => b
    [3] => c
)


Updates a value at a given index

  • « Ds\Vector::rotate
  • Ds\Vector::shift »
  • PHP Manual
  • Vector
  • Updates a value at a given index

Ds\Vector::set

(PECL ds >= 1.0.0)

Ds\Vector::set — Updates a value at a given index

Description

public Ds\Vector::set ( int $index , mixed $value ) : void

Updates a value at a given index.

Parameters

index

The index of the value to update.

value

The new value.

Return Values

No value is returned.

Errors/Exceptions

OutOfRangeException if the index is not valid.

Examples

Example #1 Ds\Vector::set() example

<?php
$vector = new \Ds\Vector(["a", "b", "c"]);

$vector->set(1, "_");
print_r($vector);
?>

The above example will output something similar to:

Ds\Vector Object
(
    [0] => a
    [1] => _
    [2] => c
)

Example #2 Ds\Vector::set() example using array syntax

<?php
$vector = new \Ds\Vector(["a", "b", "c"]);

$vector[1] = "_";
print_r($vector);
?>

The above example will output something similar to:

Ds\Vector Object
(
    [0] => a
    [1] => _
    [2] => c
)


Removes and returns the first value

  • « Ds\Vector::set
  • Ds\Vector::slice »
  • PHP Manual
  • Vector
  • Removes and returns the first value

Ds\Vector::shift

(PECL ds >= 1.0.0)

Ds\Vector::shift — Removes and returns the first value

Description

public Ds\Vector::shift ( void ) : mixed

Removes and returns the first value.

Parameters

This function has no parameters.

Return Values

The first value, which was removed.

Errors/Exceptions

UnderflowException if empty.

Examples

Example #1 Ds\Vector::shift() example

<?php
$vector = new \Ds\Vector(["a", "b", "c"]);

var_dump($vector->shift());
var_dump($vector->shift());
var_dump($vector->shift());
?>

The above example will output something similar to:

string(1) "a"
string(1) "b"
string(1) "c"


Returns a sub-vector of a given range

  • « Ds\Vector::shift
  • Ds\Vector::sort »
  • PHP Manual
  • Vector
  • Returns a sub-vector of a given range

Ds\Vector::slice

(PECL ds >= 1.0.0)

Ds\Vector::slice — Returns a sub-vector of a given range

Description

public Ds\Vector::slice ( int $index [, int $length ] ) : Ds\Vector

Creates a sub-vector of a given range.

Parameters

index

The index at which the sub-vector starts.

If positive, the vector will start at that index in the vector. If negative, the vector will start that far from the end.

length

If a length is given and is positive, the resulting vector will have up to that many values in it. If the length results in an overflow, only values up to the end of the vector will be included. If a length is given and is negative, the vector will stop that many values from the end. If a length is not provided, the resulting vector will contain all values between the index and the end of the vector.

Return Values

A sub-vector of the given range.

Examples

Example #1 Ds\Vector::slice() example

<?php
$vector = new \Ds\Vector(["a", "b", "c", "d", "e"]);

// Slice from 2 onwards
print_r($vector->slice(2));

// Slice from 1, for a length of 3
print_r($vector->slice(1, 3));

// Slice from 1 onwards
print_r($vector->slice(1));

// Slice from 2 from the end onwards
print_r($vector->slice(-2));

// Slice from 1 to 1 from the end
print_r($vector->slice(1, -1));
?>

The above example will output something similar to:

Ds\Vector Object
(
    [0] => c
    [1] => d
    [2] => e
)
Ds\Vector Object
(
    [0] => b
    [1] => c
    [2] => d
)
Ds\Vector Object
(
    [0] => b
    [1] => c
    [2] => d
    [3] => e
)
Ds\Vector Object
(
    [0] => d
    [1] => e
)
Ds\Vector Object
(
    [0] => b
    [1] => c
    [2] => d
)


Sorts the vector in-place

  • « Ds\Vector::slice
  • Ds\Vector::sorted »
  • PHP Manual
  • Vector
  • Sorts the vector in-place

Ds\Vector::sort

(PECL ds >= 1.0.0)

Ds\Vector::sort — Sorts the vector in-place

Description

public Ds\Vector::sort ([ callable $comparator ] ) : void

Sorts the vector in-place, using an optional comparator function.

Parameters

comparator

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. Note that before PHP 7.0.0 this integer had to be in the range from -2147483648 to 2147483647.

callback ( mixed $a, mixed $b ) : int
Caution

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

Return Values

No value is returned.

Examples

Example #1 Ds\Vector::sort() example

<?php
$vector = new \Ds\Vector([4, 5, 1, 3, 2]);
$vector->sort();

print_r($vector);
?>

The above example will output something similar to:

Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Example #2 Ds\Vector::sort() example using a comparator

<?php
$vector = new \Ds\Vector([4, 5, 1, 3, 2]);

$vector->sort(function($a, $b) {
    return $b <=> $a;
});

print_r($vector);
?>

The above example will output something similar to:

Ds\Vector Object
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)


Returns a sorted copy

  • « Ds\Vector::sort
  • Ds\Vector::sum »
  • PHP Manual
  • Vector
  • Returns a sorted copy

Ds\Vector::sorted

(PECL ds >= 1.0.0)

Ds\Vector::sorted — Returns a sorted copy

Description

public Ds\Vector::sorted ([ callable $comparator ] ) : Ds\Vector

Returns a sorted copy, using an optional comparator function.

Parameters

comparator

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. Note that before PHP 7.0.0 this integer had to be in the range from -2147483648 to 2147483647.

callback ( mixed $a, mixed $b ) : int
Caution

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

Return Values

Returns a sorted copy of the vector.

Examples

Example #1 Ds\Vector::sorted() example

<?php
$vector = new \Ds\Vector([4, 5, 1, 3, 2]);

print_r($vector->sorted());
?>

The above example will output something similar to:

Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Example #2 Ds\Vector::sorted() example using a comparator

<?php
$vector = new \Ds\Vector([4, 5, 1, 3, 2]);

$sorted = $vector->sorted(function($a, $b) {
    return $b <=> $a;
});

print_r($sorted);
?>

The above example will output something similar to:

Ds\Vector Object
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)


Returns the sum of all values in the vector

  • « Ds\Vector::sorted
  • Ds\Vector::toArray »
  • PHP Manual
  • Vector
  • Returns the sum of all values in the vector

Ds\Vector::sum

(PECL ds >= 1.0.0)

Ds\Vector::sum — Returns the sum of all values in the vector

Description

public Ds\Vector::sum ( void ) : number

Returns the sum of all values in the vector.

Note:

Arrays and objects are considered equal to zero when calculating the sum.

Parameters

This function has no parameters.

Return Values

The sum of all the values in the vector as either a float or int depending on the values in the vector.

Examples

Example #1 Ds\Vector::sum() integer example

<?php
$vector = new \Ds\Vector([1, 2, 3]);
var_dump($vector->sum());
?>

The above example will output something similar to:

int(6)

Example #2 Ds\Vector::sum() float example

<?php
$vector = new \Ds\Vector([1, 2.5, 3]);
var_dump($vector->sum());
?>

The above example will output something similar to:

float(6.5)


Converts the vector to an array

  • « Ds\Vector::sum
  • Ds\Vector::unshift »
  • PHP Manual
  • Vector
  • Converts the vector to an array

Ds\Vector::toArray

(PECL ds >= 1.0.0)

Ds\Vector::toArray — Converts the vector to an array

Description

public Ds\Vector::toArray ( void ) : array

Converts the vector to an array.

Note:

Casting to an array is not supported yet.

Parameters

This function has no parameters.

Return Values

An array containing all the values in the same order as the vector.

Examples

Example #1 Ds\Vector::toArray() example

<?php
$vector = new \Ds\Vector([1, 2, 3]);

var_dump($vector->toArray());
?>

The above example will output something similar to:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}


Adds values to the front of the vector

  • « Ds\Vector::toArray
  • Deque »
  • PHP Manual
  • Vector
  • Adds values to the front of the vector

Ds\Vector::unshift

(PECL ds >= 1.0.0)

Ds\Vector::unshift — Adds values to the front of the vector

Description

public Ds\Vector::unshift ([ mixed $values ] ) : void

Adds values to the front of the vector, moving all the current values forward to make room for the new values.

Parameters

values

The values to add to the front of the vector.

Note:

Multiple values will be added in the same order that they are passed.

Return Values

No value is returned.

Examples

Example #1 Ds\Vector::unshift() example

<?php
$vector = new \Ds\Vector([1, 2, 3]);

$vector->unshift("a");
$vector->unshift("b", "c");

print_r($vector);
?>

The above example will output something similar to:

Ds\Vector Object
(
    [0] => b
    [1] => c
    [2] => a
    [3] => 1
    [4] => 2
    [5] => 3
)


The Deque class

(No version information available, might only be in Git)

Introduction

A Deque (pronounced “deck”) is a sequence of values in a contiguous buffer that grows and shrinks automatically. The name is a common abbreviation of “double-ended queue” and is used internally by Ds\Queue.

Two pointers are used to keep track of a head and a tail. The pointers can “wrap around” the end of the buffer, which avoids the need to move other values around to make room. This makes shift and unshift very fast —  something a Ds\Vector can’t compete with.

Accessing a value by index requires a translation between the index and its corresponding position in the buffer: ((head + position) % capacity).

Strengths

  • Supports array syntax (square brackets).
  • Uses less overall memory than an array for the same number of values.
  • Automatically frees allocated memory when its size drops low enough.
  • get(),
set(),
push(),
pop(),
shift(), and
unshift() are all O(1).

Weaknesses

  • Capacity must be a power of 2.
  • insert() and remove() are O(n).

Class synopsis

Ds\Deque implements Ds\Sequence {
/* Constants */
const int MIN_CAPACITY = 8 ;
/* Methods */
public allocate ( int $capacity ) : void
public apply ( callable $callback ) : void
public capacity ( void ) : int
public clear ( void ) : void
public contains ([ mixed $...values ] ) : bool
public copy ( void ) : Ds\Deque
public filter ([ callable $callback ] ) : Ds\Deque
public find ( mixed $value ) : mixed
public first ( void ) : mixed
public get ( int $index ) : mixed
public insert ( int $index [, mixed $...values ] ) : void
public isEmpty ( void ) : bool
public join ([ string $glue ] ) : string
public last ( void ) : mixed
public map ( callable $callback ) : Ds\Deque
public merge ( mixed $values ) : Ds\Deque
public pop ( void ) : mixed
public push ([ mixed $...values ] ) : void
public reduce ( callable $callback [, mixed $initial ] ) : mixed
public remove ( int $index ) : mixed
public reverse ( void ) : void
public reversed ( void ) : Ds\Deque
public rotate ( int $rotations ) : void
public set ( int $index , mixed $value ) : void
public shift ( void ) : mixed
public slice ( int $index [, int $length ] ) : Ds\Deque
public sort ([ callable $comparator ] ) : void
public sorted ([ callable $comparator ] ) : Ds\Deque
public sum ( void ) : number
public toArray ( void ) : array
public unshift ([ mixed $values ] ) : void
}

Predefined Constants

Ds\Deque::MIN_CAPACITY

Table of Contents

  • Ds\Deque::allocate — Allocates enough memory for a required capacity
  • Ds\Deque::apply — Updates all values by applying a callback function to each value
  • Ds\Deque::capacity — Returns the current capacity
  • Ds\Deque::clear — Removes all values from the deque
  • Ds\Deque::__construct — Creates a new instance
  • Ds\Deque::contains — Determines if the deque contains given values
  • Ds\Deque::copy — Returns a shallow copy of the deque
  • Ds\Deque::count — Returns the number of values in the collection
  • Ds\Deque::filter — Creates a new deque using a callable to determine which values to include
  • Ds\Deque::find — Attempts to find a value's index
  • Ds\Deque::first — Returns the first value in the deque
  • Ds\Deque::get — Returns the value at a given index
  • Ds\Deque::insert — Inserts values at a given index
  • Ds\Deque::isEmpty — Returns whether the deque is empty
  • Ds\Deque::join — Joins all values together as a string
  • Ds\Deque::jsonSerialize — Returns a representation that can be converted to JSON
  • Ds\Deque::last — Returns the last value
  • Ds\Deque::map — Returns the result of applying a callback to each value
  • Ds\Deque::merge — Returns the result of adding all given values to the deque
  • Ds\Deque::pop — Removes and returns the last value
  • Ds\Deque::push — Adds values to the end of the deque
  • Ds\Deque::reduce — Reduces the deque to a single value using a callback function
  • Ds\Deque::remove — Removes and returns a value by index
  • Ds\Deque::reverse — Reverses the deque in-place
  • Ds\Deque::reversed — Returns a reversed copy
  • Ds\Deque::rotate — Rotates the deque by a given number of rotations
  • Ds\Deque::set — Updates a value at a given index
  • Ds\Deque::shift — Removes and returns the first value
  • Ds\Deque::slice — Returns a sub-deque of a given range
  • Ds\Deque::sort — Sorts the deque in-place
  • Ds\Deque::sorted — Returns a sorted copy
  • Ds\Deque::sum — Returns the sum of all values in the deque
  • Ds\Deque::toArray — Converts the deque to an array
  • Ds\Deque::unshift — Adds values to the front of the deque


Allocates enough memory for a required capacity

  • « Deque
  • Ds\Deque::apply »
  • PHP Manual
  • Deque
  • Allocates enough memory for a required capacity

Ds\Deque::allocate

(PECL ds >= 1.0.0)

Ds\Deque::allocate — Allocates enough memory for a required capacity

Description

public Ds\Deque::allocate ( int $capacity ) : void

Ensures that enough memory is allocated for a required capacity. This removes the need to reallocate the internal as values are added.

Parameters

capacity

The number of values for which capacity should be allocated.

Note:

Capacity will stay the same if this value is less than or equal to the current capacity.

Note:

Capacity will always be rounded up to the nearest power of 2.

Return Values

No value is returned.

Examples

Example #1 Ds\Deque::allocate() example

<?php
$deque = new \Ds\Deque();
var_dump($deque->capacity());

$deque->allocate(100);
var_dump($deque->capacity());
?>

The above example will output something similar to:

int(8)
int(128)


Updates all values by applying a callback function to each value

  • « Ds\Deque::allocate
  • Ds\Deque::capacity »
  • PHP Manual
  • Deque
  • Updates all values by applying a callback function to each value

Ds\Deque::apply

(PECL ds >= 1.0.0)

Ds\Deque::apply — Updates all values by applying a callback function to each value

Description

public Ds\Deque::apply ( callable $callback ) : void

Updates all values by applying a callback function to each value in the deque.

Parameters

callback

callback ( mixed $value ) : mixed

A callable to apply to each value in the deque.

The callback should return what the value should be replaced by.

Return Values

No value is returned.

Examples

Example #1 Ds\Deque::apply() example

<?php
$deque = new \Ds\Deque([1, 2, 3]);
$deque->apply(function($value) { return $value * 2; });

print_r($deque);
?>

The above example will output something similar to:

Ds\Deque Object
(
    [0] => 2
    [1] => 4
    [2] => 6
)


Returns the current capacity

  • « Ds\Deque::apply
  • Ds\Deque::clear »
  • PHP Manual
  • Deque
  • Returns the current capacity

Ds\Deque::capacity

(PECL ds >= 1.0.0)

Ds\Deque::capacity — Returns the current capacity

Description

public Ds\Deque::capacity ( void ) : int

Returns the current capacity.

Parameters

This function has no parameters.

Return Values

The current capacity.

Examples

Example #1 Ds\Deque::capacity() example

<?php
$deque = new \Ds\Deque();
var_dump($deque->capacity());

$deque->push(...range(1, 50));
var_dump($deque->capacity());
?>

The above example will output something similar to:

int(8)
int(64)


Removes all values from the deque

  • « Ds\Deque::capacity
  • Ds\Deque::__construct »
  • PHP Manual
  • Deque
  • Removes all values from the deque

Ds\Deque::clear

(PECL ds >= 1.0.0)

Ds\Deque::clear — Removes all values from the deque

Description

public Ds\Deque::clear ( void ) : void

Removes all values from the deque.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 Ds\Deque::clear() example

<?php
$deque = new \Ds\Deque([1, 2, 3]);
print_r($deque);

$deque->clear();
print_r($deque);
?>

The above example will output something similar to:

Ds\Deque Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Deque Object
(
)


Creates a new instance

  • « Ds\Deque::clear
  • Ds\Deque::contains »
  • PHP Manual
  • Deque
  • Creates a new instance

Ds\Deque::__construct

(PECL ds >= 1.0.0)

Ds\Deque::__construct — Creates a new instance

Description

public Ds\Deque::__construct ([ mixed $values ] )

Creates a new instance, using either a traversable object or an array for the initial values.

Parameters

values

A traversable object or an array to use for the initial values.

Examples

Example #1 Ds\Deque::__construct() example

<?php
$deque = new \Ds\Deque();
var_dump($deque);

$deque = new \Ds\Deque([1, 2, 3]);
var_dump($deque);
?>

The above example will output something similar to:

object(Ds\Deque)#2 (0) {
}
object(Ds\Deque)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}


Determines if the deque contains given values

  • « Ds\Deque::__construct
  • Ds\Deque::copy »
  • PHP Manual
  • Deque
  • Determines if the deque contains given values

Ds\Deque::contains

(PECL ds >= 1.0.0)

Ds\Deque::contains — Determines if the deque contains given values

Description

public Ds\Deque::contains ([ mixed $...values ] ) : bool

Determines if the deque contains all values.

Parameters

values

Values to check.

Return Values

FALSE if any of the provided values are not in the deque, TRUE otherwise.

Examples

Example #1 Ds\Deque::contains() example

<?php
$deque = new \Ds\Deque(['a', 'b', 'c', 1, 2, 3]);

var_dump($deque->contains('a'));                // true
var_dump($deque->contains('a', 'b'));           // true
var_dump($deque->contains('c', 'd'));           // false

var_dump($deque->contains(...['c', 'b', 'a'])); // true

// Always strict
var_dump($deque->contains(1));                  // true
var_dump($deque->contains('1'));                // false

var_dump($sequece->contains(...[]));               // true
?>

The above example will output something similar to:

bool(true)
bool(true)
bool(false)
bool(true)
bool(true)
bool(false)
bool(true)


Returns a shallow copy of the deque

  • « Ds\Deque::contains
  • Ds\Deque::count »
  • PHP Manual
  • Deque
  • Returns a shallow copy of the deque

Ds\Deque::copy

(PECL ds >= 1.0.0)

Ds\Deque::copy — Returns a shallow copy of the deque

Description

public Ds\Deque::copy ( void ) : Ds\Deque

Returns a shallow copy of the deque.

Parameters

This function has no parameters.

Return Values

A shallow copy of the deque.

Examples

Example #1 Ds\Deque::copy() example

<?php
$a = new \Ds\Deque([1, 2, 3]);
$b = $a->copy();

$b->push(4);

print_r($a);
print_r($b);
?>

The above example will output something similar to:

Ds\Deque Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Deque Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)


Returns the number of values in the collection

  • « Ds\Deque::copy
  • Ds\Deque::filter »
  • PHP Manual
  • Deque
  • Returns the number of values in the collection

Ds\Deque::count

(PECL ds >= 1.0.0)

Ds\Deque::count — Returns the number of values in the collection

See Countable::count()


Creates a new deque using a callable to determine which values to include

  • « Ds\Deque::count
  • Ds\Deque::find »
  • PHP Manual
  • Deque
  • Creates a new deque using a callable to determine which values to include

Ds\Deque::filter

(PECL ds >= 1.0.0)

Ds\Deque::filter — Creates a new deque using a callable to determine which values to include

Description

public Ds\Deque::filter ([ callable $callback ] ) : Ds\Deque

Creates a new deque using a callable to determine which values to include.

Parameters

callback

callback ( mixed $value ) : bool

Optional callable which returns TRUE if the value should be included, FALSE otherwise.

If a callback is not provided, only values which are TRUE (see converting to boolean) will be included.

Return Values

A new deque containing all the values for which either the callback returned TRUE, or all values that convert to TRUE if a callback was not provided.

Examples

Example #1 Ds\Deque::filter() example using callback function

<?php
$deque = new \Ds\Deque([1, 2, 3, 4, 5]);

var_dump($deque->filter(function($value) {
    return $value % 2 == 0;
}));
?>

The above example will output something similar to:

object(Ds\Deque)#3 (2) {
  [0]=>
  int(2)
  [1]=>
  int(4)
}

Example #2 Ds\Deque::filter() example without a callback function

<?php
$deque = new \Ds\Deque([0, 1, 'a', true, false]);

var_dump($deque->filter());
?>

The above example will output something similar to:

object(Ds\Deque)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  string(1) "a"
  [2]=>
  bool(true)
}


Attempts to find a value's index

  • « Ds\Deque::filter
  • Ds\Deque::first »
  • PHP Manual
  • Deque
  • Attempts to find a value's index

Ds\Deque::find

(PECL ds >= 1.0.0)

Ds\Deque::find — Attempts to find a value's index

Description

public Ds\Deque::find ( mixed $value ) : mixed

Returns the index of the value, or FALSE if not found.

Parameters

value

The value to find.

Return Values

The index of the value, or FALSE if not found.

Note:

Values will be compared by value and by type.

Examples

Example #1 Ds\Deque::find() example

<?php
$deque = new \Ds\Deque(["a", 1, true]);

var_dump($deque->find("a")); // 0
var_dump($deque->find("b")); // false
var_dump($deque->find("1")); // false
var_dump($deque->find(1));   // 1
?>

The above example will output something similar to:

int(0)
bool(false)
bool(false)
int(1)


Returns the first value in the deque

  • « Ds\Deque::find
  • Ds\Deque::get »
  • PHP Manual
  • Deque
  • Returns the first value in the deque

Ds\Deque::first

(PECL ds >= 1.0.0)

Ds\Deque::first — Returns the first value in the deque

Description

public Ds\Deque::first ( void ) : mixed

Returns the first value in the deque.

Parameters

This function has no parameters.

Return Values

The first value in the deque.

Errors/Exceptions

UnderflowException if empty.

Examples

Example #1 Ds\Deque::first() example

<?php
$deque = new \Ds\Deque([1, 2, 3]);
var_dump($deque->first());
?>

The above example will output something similar to:

int(1)


Returns the value at a given index

  • « Ds\Deque::first
  • Ds\Deque::insert »
  • PHP Manual
  • Deque
  • Returns the value at a given index

Ds\Deque::get

(PECL ds >= 1.0.0)

Ds\Deque::get — Returns the value at a given index

Description

public Ds\Deque::get ( int $index ) : mixed

Returns the value at a given index.

Parameters

index

The index to access, starting at 0.

Return Values

The value at the requested index.

Errors/Exceptions

OutOfRangeException if the index is not valid.

Examples

Example #1 Ds\Deque::get() example

<?php
$deque = new \Ds\Deque(["a", "b", "c"]);

var_dump($deque->get(0));
var_dump($deque->get(1));
var_dump($deque->get(2));
?>

The above example will output something similar to:

string(1) "a"
string(1) "b"
string(1) "c"

Example #2 Ds\Deque::get() example using array syntax

<?php
$deque = new \Ds\Deque(["a", "b", "c"]);

var_dump($deque[0]);
var_dump($deque[1]);
var_dump($deque[2]);
?>

The above example will output something similar to:

string(1) "a"
string(1) "b"
string(1) "c"


Inserts values at a given index

  • « Ds\Deque::get
  • Ds\Deque::isEmpty »
  • PHP Manual
  • Deque
  • Inserts values at a given index

Ds\Deque::insert

(PECL ds >= 1.0.0)

Ds\Deque::insert — Inserts values at a given index

Description

public Ds\Deque::insert ( int $index [, mixed $...values ] ) : void

Inserts values into the deque at a given index.

Parameters

index

The index at which to insert. 0 <= index <= count

Note:

You can insert at the index equal to the number of values.

values

The value or values to insert.

Return Values

No value is returned.

Errors/Exceptions

OutOfRangeException if the index is not valid.

Examples

Example #1 Ds\Deque::insert() example

<?php
$deque = new \Ds\Deque();

$deque->insert(0, "e");             // [e]
$deque->insert(1, "f");             // [e, f]
$deque->insert(2, "g");             // [e, f, g]
$deque->insert(0, "a", "b");        // [a, b, e, f, g]
$deque->insert(2, ...["c", "d"]);   // [a, b, c, d, e, f, g]

var_dump($deque);
?>

The above example will output something similar to:

object(Ds\Deque)#1 (7) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  string(1) "e"
  [5]=>
  string(1) "f"
  [6]=>
  string(1) "g"
}


Returns whether the deque is empty

  • « Ds\Deque::insert
  • Ds\Deque::join »
  • PHP Manual
  • Deque
  • Returns whether the deque is empty

Ds\Deque::isEmpty

(PECL ds >= 1.0.0)

Ds\Deque::isEmpty — Returns whether the deque is empty

Description

public Ds\Deque::isEmpty ( void ) : bool

Returns whether the deque is empty.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the deque is empty, FALSE otherwise.

Examples

Example #1 Ds\Deque::isEmpty() example

<?php
$a = new \Ds\Deque([1, 2, 3]);
$b = new \Ds\Deque();

var_dump($a->isEmpty());
var_dump($b->isEmpty());
?>

The above example will output something similar to:

bool(false)
bool(true)


Joins all values together as a string

  • « Ds\Deque::isEmpty
  • Ds\Deque::jsonSerialize »
  • PHP Manual
  • Deque
  • Joins all values together as a string

Ds\Deque::join

(PECL ds >= 1.0.0)

Ds\Deque::join — Joins all values together as a string

Description

public Ds\Deque::join ([ string $glue ] ) : string

Joins all values together as a string using an optional separator between each value.

Parameters

glue

An optional string to separate each value.

Return Values

All values of the deque joined together as a string.

Examples

Example #1 Ds\Deque::join() example using a separator string

<?php
$deque = new \Ds\Deque(["a", "b", "c", 1, 2, 3]);

var_dump($deque->join("|"));
?>

The above example will output something similar to:

string(11) "a|b|c|1|2|3"

Example #2 Ds\Deque::join() example without a separator string

<?php
$deque = new \Ds\Deque(["a", "b", "c", 1, 2, 3]);

var_dump($deque->join());
?>

The above example will output something similar to:

string(11) "abc123"


Returns a representation that can be converted to JSON

  • « Ds\Deque::join
  • Ds\Deque::last »
  • PHP Manual
  • Deque
  • Returns a representation that can be converted to JSON

Ds\Deque::jsonSerialize

(PECL ds >= 1.0.0)

Ds\Deque::jsonSerialize — Returns a representation that can be converted to JSON

See JsonSerializable::jsonSerialize()

Note:

You should never need to call this directly.


Returns the last value

  • « Ds\Deque::jsonSerialize
  • Ds\Deque::map »
  • PHP Manual
  • Deque
  • Returns the last value

Ds\Deque::last

(PECL ds >= 1.0.0)

Ds\Deque::last — Returns the last value

Description

public Ds\Deque::last ( void ) : mixed

Returns the last value in the deque.

Parameters

This function has no parameters.

Return Values

The last value in the deque.

Errors/Exceptions

UnderflowException if empty.

Examples

Example #1 Ds\Deque::last() example

<?php
$deque = new \Ds\Deque([1, 2, 3]);
var_dump($deque->last());
?>

The above example will output something similar to:

int(3)


Returns the result of applying a callback to each value

  • « Ds\Deque::last
  • Ds\Deque::merge »
  • PHP Manual
  • Deque
  • Returns the result of applying a callback to each value

Ds\Deque::map

(PECL ds >= 1.0.0)

Ds\Deque::map — Returns the result of applying a callback to each value

Description

public Ds\Deque::map ( callable $callback ) : Ds\Deque

Returns the result of applying a callback function to each value in the deque.

Parameters

callback

callback ( mixed $value ) : mixed

A callable to apply to each value in the deque.

The callable should return what the new value will be in the new deque.

Return Values

The result of applying a callback to each value in the deque.

Note:

The values of the current instance won't be affected.

Examples

Example #1 Ds\Deque::map() example

<?php
$deque = new \Ds\Deque([1, 2, 3]);

print_r($deque->map(function($value) { return $value * 2; }));
print_r($deque);
?>

The above example will output something similar to:

Ds\Deque Object
(
    [0] => 2
    [1] => 4
    [2] => 6
)
Ds\Deque Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)


Returns the result of adding all given values to the deque

  • « Ds\Deque::map
  • Ds\Deque::pop »
  • PHP Manual
  • Deque
  • Returns the result of adding all given values to the deque

Ds\Deque::merge

(PECL ds >= 1.0.0)

Ds\Deque::merge — Returns the result of adding all given values to the deque

Description

public Ds\Deque::merge ( mixed $values ) : Ds\Deque

Returns the result of adding all given values to the deque.

Parameters

values

A traversable object or an array.

Return Values

The result of adding all given values to the deque, effectively the same as adding the values to a copy, then returning that copy.

Note:

The current instance won't be affected.

Examples

Example #1 Ds\Deque::merge() example

<?php
$deque = new \Ds\Deque([1, 2, 3]);

var_dump($deque->merge([4, 5, 6]));
var_dump($deque);
?>

The above example will output something similar to:

object(Ds\Deque)#2 (6) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
  [4]=>
  int(5)
  [5]=>
  int(6)
}
object(Ds\Deque)#1 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}


Removes and returns the last value

  • « Ds\Deque::merge
  • Ds\Deque::push »
  • PHP Manual
  • Deque
  • Removes and returns the last value

Ds\Deque::pop

(PECL ds >= 1.0.0)

Ds\Deque::pop — Removes and returns the last value

Description

public Ds\Deque::pop ( void ) : mixed

Removes and returns the last value.

Parameters

This function has no parameters.

Return Values

The removed last value.

Errors/Exceptions

UnderflowException if empty.

Examples

Example #1 Ds\Deque::pop() example

<?php
$deque = new \Ds\Deque([1, 2, 3]);

var_dump($deque->pop());
var_dump($deque->pop());
var_dump($deque->pop());
?>

The above example will output something similar to:

int(3)
int(2)
int(1)


Adds values to the end of the deque

  • « Ds\Deque::pop
  • Ds\Deque::reduce »
  • PHP Manual
  • Deque
  • Adds values to the end of the deque

Ds\Deque::push

(PECL ds >= 1.0.0)

Ds\Deque::push — Adds values to the end of the deque

Description

public Ds\Deque::push ([ mixed $...values ] ) : void

Adds values to the end of the deque.

Parameters

values

The values to add.

Return Values

No value is returned.

Examples

Example #1 Ds\Deque::push() example

<?php
$deque = new \Ds\Deque();

$deque->push("a");
$deque->push("b");
$deque->push("c", "d");
$deque->push(...["e", "f"]);

print_r($deque);
?>

The above example will output something similar to:

Ds\Deque Object
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
    [5] => f
)


Reduces the deque to a single value using a callback function

  • « Ds\Deque::push
  • Ds\Deque::remove »
  • PHP Manual
  • Deque
  • Reduces the deque to a single value using a callback function

Ds\Deque::reduce

(PECL ds >= 1.0.0)

Ds\Deque::reduce — Reduces the deque to a single value using a callback function

Description

public Ds\Deque::reduce ( callable $callback [, mixed $initial ] ) : mixed

Reduces the deque to a single value using a callback function.

Parameters

callback
callback ( mixed $carry , mixed $value ) : mixed
carry

The return value of the previous callback, or initial if it's the first iteration.

value

The value of the current iteration.

initial

The initial value of the carry value. Can be NULL.

Return Values

The return value of the final callback.

Examples

Example #1 Ds\Deque::reduce() with initial value example

<?php
$deque = new \Ds\Deque([1, 2, 3]);

$callback = function($carry, $value) {
    return $carry * $value;
};

var_dump($deque->reduce($callback, 5));

// Iterations:
//
// $carry = $initial = 5
//
// $carry = $carry * 1 =  5
// $carry = $carry * 2 = 10
// $carry = $carry * 3 = 30
?>

The above example will output something similar to:

int(30)

Example #2 Ds\Deque::reduce() without an initial value example

<?php
$deque = new \Ds\Deque([1, 2, 3]);

var_dump($deque->reduce(function($carry, $value) {
    return $carry + $value + 5;
}));

// Iterations:
//
// $carry = $initial = null
//
// $carry = $carry + 1 + 5 =  6
// $carry = $carry + 2 + 5 = 13
// $carry = $carry + 3 + 5 = 21
?>

The above example will output something similar to:

int(21)


Removes and returns a value by index

  • « Ds\Deque::reduce
  • Ds\Deque::reverse »
  • PHP Manual
  • Deque
  • Removes and returns a value by index

Ds\Deque::remove

(PECL ds >= 1.0.0)

Ds\Deque::remove — Removes and returns a value by index

Description

public Ds\Deque::remove ( int $index ) : mixed

Removes and returns a value by index.

Parameters

index

The index of the value to remove.

Return Values

The value that was removed.

Errors/Exceptions

OutOfRangeException if the index is not valid.

Examples

Example #1 Ds\Deque::remove() example

<?php
$deque = new \Ds\Deque(["a", "b", "c"]);

var_dump($deque->remove(1));
var_dump($deque->remove(0));
var_dump($deque->remove(0));
?>

The above example will output something similar to:

string(1) "b"
string(1) "a"
string(1) "c"


Reverses the deque in-place

  • « Ds\Deque::remove
  • Ds\Deque::reversed »
  • PHP Manual
  • Deque
  • Reverses the deque in-place

Ds\Deque::reverse

(PECL ds >= 1.0.0)

Ds\Deque::reverse — Reverses the deque in-place

Description

public Ds\Deque::reverse ( void ) : void

Reverses the deque in-place.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 Ds\Deque::reverse() example

<?php
$deque = new \Ds\Deque(["a", "b", "c"]);
$deque->reverse();

print_r($deque);
?>

The above example will output something similar to:

Ds\Deque Object
(
    [0] => c
    [1] => b
    [2] => a
)


Returns a reversed copy

  • « Ds\Deque::reverse
  • Ds\Deque::rotate »
  • PHP Manual
  • Deque
  • Returns a reversed copy

Ds\Deque::reversed

(PECL ds >= 1.0.0)

Ds\Deque::reversed — Returns a reversed copy

Description

public Ds\Deque::reversed ( void ) : Ds\Deque

Returns a reversed copy of the deque.

Parameters

This function has no parameters.

Return Values

A reversed copy of the deque.

Note:

The current instance is not affected.

Examples

Example #1 Ds\Deque::reversed() example

<?php
$deque = new \Ds\Deque(["a", "b", "c"]);

print_r($deque->reversed());
print_r($deque);
?>

The above example will output something similar to:

Ds\Deque Object
(
    [0] => c
    [1] => b
    [2] => a
)
Ds\Deque Object
(
    [0] => a
    [1] => b
    [2] => c
)


Rotates the deque by a given number of rotations

  • « Ds\Deque::reversed
  • Ds\Deque::set »
  • PHP Manual
  • Deque
  • Rotates the deque by a given number of rotations

Ds\Deque::rotate

(PECL ds >= 1.0.0)

Ds\Deque::rotate — Rotates the deque by a given number of rotations

Description

public Ds\Deque::rotate ( int $rotations ) : void

Rotates the deque by a given number of rotations, which is equivalent to successively calling $deque->push($deque->shift()) if the number of rotations is positive, or $deque->unshift($deque->pop()) if negative.

Parameters

rotations

The number of times the deque should be rotated.

Return Values

No value is returned.. The deque of the current instance will be rotated.

Examples

Example #1 Ds\Deque::rotate() example

<?php
$deque = new \Ds\Deque(["a", "b", "c", "d"]);

$deque->rotate(1);  // "a" is shifted, then pushed.
print_r($deque);

$deque->rotate(2);  // "b" and "c" are both shifted, the pushed.
print_r($deque);
?>

The above example will output something similar to:

(
    [0] => b
    [1] => c
    [2] => d
    [3] => a
)
Ds\Deque Object
(
    [0] => d
    [1] => a
    [2] => b
    [3] => c
)


Updates a value at a given index

  • « Ds\Deque::rotate
  • Ds\Deque::shift »
  • PHP Manual
  • Deque
  • Updates a value at a given index

Ds\Deque::set

(PECL ds >= 1.0.0)

Ds\Deque::set — Updates a value at a given index

Description

public Ds\Deque::set ( int $index , mixed $value ) : void

Updates a value at a given index.

Parameters

index

The index of the value to update.

value

The new value.

Return Values

No value is returned.

Errors/Exceptions

OutOfRangeException if the index is not valid.

Examples

Example #1 Ds\Deque::set() example

<?php
$deque = new \Ds\Deque(["a", "b", "c"]);

$deque->set(1, "_");
print_r($deque);
?>

The above example will output something similar to:

Ds\Deque Object
(
    [0] => a
    [1] => _
    [2] => c
)

Example #2 Ds\Deque::set() example using array syntax

<?php
$deque = new \Ds\Deque(["a", "b", "c"]);

$deque[1] = "_";
print_r($deque);
?>

The above example will output something similar to:

Ds\Deque Object
(
    [0] => a
    [1] => _
    [2] => c
)


Removes and returns the first value

  • « Ds\Deque::set
  • Ds\Deque::slice »
  • PHP Manual
  • Deque
  • Removes and returns the first value

Ds\Deque::shift

(PECL ds >= 1.0.0)

Ds\Deque::shift — Removes and returns the first value

Description

public Ds\Deque::shift ( void ) : mixed

Removes and returns the first value.

Parameters

This function has no parameters.

Return Values

The first value, which was removed.

Errors/Exceptions

UnderflowException if empty.

Examples

Example #1 Ds\Deque::shift() example

<?php
$deque = new \Ds\Deque(["a", "b", "c"]);

var_dump($deque->shift());
var_dump($deque->shift());
var_dump($deque->shift());
?>

The above example will output something similar to:

string(1) "a"
string(1) "b"
string(1) "c"


Returns a sub-deque of a given range

  • « Ds\Deque::shift
  • Ds\Deque::sort »
  • PHP Manual
  • Deque
  • Returns a sub-deque of a given range

Ds\Deque::slice

(PECL ds >= 1.0.0)

Ds\Deque::slice — Returns a sub-deque of a given range

Description

public Ds\Deque::slice ( int $index [, int $length ] ) : Ds\Deque

Creates a sub-deque of a given range.

Parameters

index

The index at which the sub-deque starts.

If positive, the deque will start at that index in the deque. If negative, the deque will start that far from the end.

length

If a length is given and is positive, the resulting deque will have up to that many values in it. If the length results in an overflow, only values up to the end of the deque will be included. If a length is given and is negative, the deque will stop that many values from the end. If a length is not provided, the resulting deque will contain all values between the index and the end of the deque.

Return Values

A sub-deque of the given range.

Examples

Example #1 Ds\Deque::slice() example

<?php
$deque = new \Ds\Deque(["a", "b", "c", "d", "e"]);

// Slice from 2 onwards
print_r($deque->slice(2));

// Slice from 1, for a length of 3
print_r($deque->slice(1, 3));

// Slice from 1 onwards
print_r($deque->slice(1));

// Slice from 2 from the end onwards
print_r($deque->slice(-2));

// Slice from 1 to 1 from the end
print_r($deque->slice(1, -1));
?>

The above example will output something similar to:

Ds\Deque Object
(
    [0] => c
    [1] => d
    [2] => e
)
Ds\Deque Object
(
    [0] => b
    [1] => c
    [2] => d
)
Ds\Deque Object
(
    [0] => b
    [1] => c
    [2] => d
    [3] => e
)
Ds\Deque Object
(
    [0] => d
    [1] => e
)
Ds\Deque Object
(
    [0] => b
    [1] => c
    [2] => d
)


Sorts the deque in-place

  • « Ds\Deque::slice
  • Ds\Deque::sorted »
  • PHP Manual
  • Deque
  • Sorts the deque in-place

Ds\Deque::sort

(PECL ds >= 1.0.0)

Ds\Deque::sort — Sorts the deque in-place

Description

public Ds\Deque::sort ([ callable $comparator ] ) : void

Sorts the deque in-place, using an optional comparator function.

Parameters

comparator

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. Note that before PHP 7.0.0 this integer had to be in the range from -2147483648 to 2147483647.

callback ( mixed $a, mixed $b ) : int
Caution

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

Return Values

No value is returned.

Examples

Example #1 Ds\Deque::sort() example

<?php
$deque = new \Ds\Deque([4, 5, 1, 3, 2]);
$deque->sort();

print_r($deque);
?>

The above example will output something similar to:

Ds\Deque Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Example #2 Ds\Deque::sort() example using a comparator

<?php
$deque = new \Ds\Deque([4, 5, 1, 3, 2]);

$deque->sort(function($a, $b) {
    return $b <=> $a;
});

print_r($deque);
?>

The above example will output something similar to:

Ds\Deque Object
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)


Returns a sorted copy

  • « Ds\Deque::sort
  • Ds\Deque::sum »
  • PHP Manual
  • Deque
  • Returns a sorted copy

Ds\Deque::sorted

(PECL ds >= 1.0.0)

Ds\Deque::sorted — Returns a sorted copy

Description

public Ds\Deque::sorted ([ callable $comparator ] ) : Ds\Deque

Returns a sorted copy, using an optional comparator function.

Parameters

comparator

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. Note that before PHP 7.0.0 this integer had to be in the range from -2147483648 to 2147483647.

callback ( mixed $a, mixed $b ) : int
Caution

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

Return Values

Returns a sorted copy of the deque.

Examples

Example #1 Ds\Deque::sorted() example

<?php
$deque = new \Ds\Deque([4, 5, 1, 3, 2]);

print_r($deque->sorted());
?>

The above example will output something similar to:

Ds\Deque Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Example #2 Ds\Deque::sorted() example using a comparator

<?php
$deque = new \Ds\Deque([4, 5, 1, 3, 2]);

$sorted = $deque->sorted(function($a, $b) {
    return $b <=> $a;
});

print_r($sorted);
?>

The above example will output something similar to:

Ds\Deque Object
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)


Returns the sum of all values in the deque

  • « Ds\Deque::sorted
  • Ds\Deque::toArray »
  • PHP Manual
  • Deque
  • Returns the sum of all values in the deque

Ds\Deque::sum

(PECL ds >= 1.0.0)

Ds\Deque::sum — Returns the sum of all values in the deque

Description

public Ds\Deque::sum ( void ) : number

Returns the sum of all values in the deque.

Note:

Arrays and objects are considered equal to zero when calculating the sum.

Parameters

This function has no parameters.

Return Values

The sum of all the values in the deque as either a float or int depending on the values in the deque.

Examples

Example #1 Ds\Deque::sum() integer example

<?php
$deque = new \Ds\Deque([1, 2, 3]);
var_dump($deque->sum());
?>

The above example will output something similar to:

int(6)

Example #2 Ds\Deque::sum() float example

<?php
$deque = new \Ds\Deque([1, 2.5, 3]);
var_dump($deque->sum());
?>

The above example will output something similar to:

float(6.5)


Converts the deque to an array

  • « Ds\Deque::sum
  • Ds\Deque::unshift »
  • PHP Manual
  • Deque
  • Converts the deque to an array

Ds\Deque::toArray

(PECL ds >= 1.0.0)

Ds\Deque::toArray — Converts the deque to an array

Description

public Ds\Deque::toArray ( void ) : array

Converts the deque to an array.

Note:

Casting to an array is not supported yet.

Parameters

This function has no parameters.

Return Values

An array containing all the values in the same order as the deque.

Examples

Example #1 Ds\Deque::toArray() example

<?php
$deque = new \Ds\Deque([1, 2, 3]);

var_dump($deque->toArray());
?>

The above example will output something similar to:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}


Adds values to the front of the deque

  • « Ds\Deque::toArray
  • Map »
  • PHP Manual
  • Deque
  • Adds values to the front of the deque

Ds\Deque::unshift

(PECL ds >= 1.0.0)

Ds\Deque::unshift — Adds values to the front of the deque

Description

public Ds\Deque::unshift ([ mixed $values ] ) : void

Adds values to the front of the deque, moving all the current values forward to make room for the new values.

Parameters

values

The values to add to the front of the deque.

Note:

Multiple values will be added in the same order that they are passed.

Return Values

No value is returned.

Examples

Example #1 Ds\Deque::unshift() example

<?php
$deque = new \Ds\Deque([1, 2, 3]);

$deque->unshift("a");
$deque->unshift("b", "c");

print_r($deque);
?>

The above example will output something similar to:

Ds\Deque Object
(
    [0] => b
    [1] => c
    [2] => a
    [3] => 1
    [4] => 2
    [5] => 3
)


The Map class

(No version information available, might only be in Git)

Introduction

A Map is a sequential collection of key-value pairs, almost identical to an array used in a similar context. Keys can be any type, but must be unique. Values are replaced if added to the map using the same key.

Strengths

  • Keys and values can be any type, including objects.
  • Supports array syntax (square brackets).
  • Insertion order is preserved.
  • Performance and memory efficiency is very similar to an array.
  • Automatically frees allocated memory when its size drops low enough.

Weaknesses

  • Can’t be converted to an array when objects are used as keys.

Class synopsis

Ds\Map implements Ds\Collection {
/* Constants */
const int MIN_CAPACITY = 16 ;
/* Methods */
public allocate ( int $capacity ) : void
public apply ( callable $callback ) : void
public capacity ( void ) : int
public clear ( void ) : void
public copy ( void ) : Ds\Map
public diff ( Ds\Map $map ) : Ds\Map
public filter ([ callable $callback ] ) : Ds\Map
public first ( void ) : Ds\Pair
public get ( mixed $key [, mixed $default ] ) : mixed
public hasKey ( mixed $key ) : bool
public hasValue ( mixed $value ) : bool
public intersect ( Ds\Map $map ) : Ds\Map
public isEmpty ( void ) : bool
public keys ( void ) : Ds\Set
public ksort ([ callable $comparator ] ) : void
public ksorted ([ callable $comparator ] ) : Ds\Map
public last ( void ) : Ds\Pair
public map ( callable $callback ) : Ds\Map
public merge ( mixed $values ) : Ds\Map
public pairs ( void ) : Ds\Sequence
public put ( mixed $key , mixed $value ) : void
public putAll ( mixed $pairs ) : void
public reduce ( callable $callback [, mixed $initial ] ) : mixed
public remove ( mixed $key [, mixed $default ] ) : mixed
public reverse ( void ) : void
public reversed ( void ) : Ds\Map
public skip ( int $position ) : Ds\Pair
public slice ( int $index [, int $length ] ) : Ds\Map
public sort ([ callable $comparator ] ) : void
public sorted ([ callable $comparator ] ) : Ds\Map
public sum ( void ) : number
public toArray ( void ) : array
public union ( Ds\Map $map ) : Ds\Map
public values ( void ) : Ds\Sequence
public xor ( Ds\Map $map ) : Ds\Map
}

Predefined Constants

Ds\Map::MIN_CAPACITY

Table of Contents

  • Ds\Map::allocate — Allocates enough memory for a required capacity
  • Ds\Map::apply — Updates all values by applying a callback function to each value
  • Ds\Map::capacity — Returns the current capacity
  • Ds\Map::clear — Removes all values
  • Ds\Map::__construct — Creates a new instance
  • Ds\Map::copy — Returns a shallow copy of the map
  • Ds\Map::count — Returns the number of values in the map
  • Ds\Map::diff — Creates a new map using keys that aren't in another map
  • Ds\Map::filter — Creates a new map using a callable to determine which pairs to include
  • Ds\Map::first — Returns the first pair in the map
  • Ds\Map::get — Returns the value for a given key
  • Ds\Map::hasKey — Determines whether the map contains a given key
  • Ds\Map::hasValue — Determines whether the map contains a given value
  • Ds\Map::intersect — Creates a new map by intersecting keys with another map
  • Ds\Map::isEmpty — Returns whether the map is empty
  • Ds\Map::jsonSerialize — Returns a representation that can be converted to JSON
  • Ds\Map::keys — Returns a set of the map's keys
  • Ds\Map::ksort — Sorts the map in-place by key
  • Ds\Map::ksorted — Returns a copy, sorted by key
  • Ds\Map::last — Returns the last pair of the map
  • Ds\Map::map — Returns the result of applying a callback to each value
  • Ds\Map::merge — Returns the result of adding all given associations
  • Ds\Map::pairs — Returns a sequence containing all the pairs of the map
  • Ds\Map::put — Associates a key with a value
  • Ds\Map::putAll — Associates all key-value pairs of a traversable object or array
  • Ds\Map::reduce — Reduces the map to a single value using a callback function
  • Ds\Map::remove — Removes and returns a value by key
  • Ds\Map::reverse — Reverses the map in-place
  • Ds\Map::reversed — Returns a reversed copy
  • Ds\Map::skip — Returns the pair at a given positional index
  • Ds\Map::slice — Returns a subset of the map defined by a starting index and length
  • Ds\Map::sort — Sorts the map in-place by value
  • Ds\Map::sorted — Returns a copy, sorted by value
  • Ds\Map::sum — Returns the sum of all values in the map
  • Ds\Map::toArray — Converts the map to an array
  • Ds\Map::union — Creates a new map using values from the current instance and another map
  • Ds\Map::values — Returns a sequence of the map's values
  • Ds\Map::xor — Creates a new map using keys of either the current instance or of another map, but not of both


Allocates enough memory for a required capacity

  • « Map
  • Ds\Map::apply »
  • PHP Manual
  • Map
  • Allocates enough memory for a required capacity

Ds\Map::allocate

(PECL ds >= 1.0.0)

Ds\Map::allocate — Allocates enough memory for a required capacity

Description

public Ds\Map::allocate ( int $capacity ) : void

Allocates enough memory for a required capacity.

Parameters

capacity

The number of values for which capacity should be allocated.

Note:

Capacity will stay the same if this value is less than or equal to the current capacity.

Note:

Capacity will always be rounded up to the nearest power of 2.

Return Values

No value is returned.

Examples

Example #1 Ds\Map::allocate() example

<?php
$map = new \Ds\Map();
var_dump($map->capacity());

$map->allocate(100);
var_dump($map->capacity());
?>

The above example will output something similar to:

int(16)
int(128)


Updates all values by applying a callback function to each value

  • « Ds\Map::allocate
  • Ds\Map::capacity »
  • PHP Manual
  • Map
  • Updates all values by applying a callback function to each value

Ds\Map::apply

(PECL ds >= 1.0.0)

Ds\Map::apply — Updates all values by applying a callback function to each value

Description

public Ds\Map::apply ( callable $callback ) : void

Updates all values by applying a callback function to each value in the map.

Parameters

callback

callback ( mixed $key , mixed $value ) : mixed

A callable to apply to each value in the map.

The callback should return what the value should be replaced by.

Return Values

No value is returned.

Examples

Example #1 Ds\Map::apply() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
$map->apply(function($key, $value) { return $value * 2; });

print_r($map);
?>

The above example will output something similar to:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 2
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 4
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 6
        )

)


Returns the current capacity

  • « Ds\Map::apply
  • Ds\Map::clear »
  • PHP Manual
  • Map
  • Returns the current capacity

Ds\Map::capacity

(PECL ds >= 1.0.0)

Ds\Map::capacity — Returns the current capacity

Description

public Ds\Map::capacity ( void ) : int

Returns the current capacity.

Parameters

This function has no parameters.

Return Values

The current capacity.

Examples

Example #1 Ds\Map::capacity() example

<?php
$map = new \Ds\Map();
var_dump($map->capacity());
?>

The above example will output something similar to:

int(16)


Removes all values

  • « Ds\Map::capacity
  • Ds\Map::__construct »
  • PHP Manual
  • Map
  • Removes all values

Ds\Map::clear

(PECL ds >= 1.0.0)

Ds\Map::clear — Removes all values

Description

public Ds\Map::clear ( void ) : void

Removes all values from the map.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 Ds\Map::clear() example

<?php
$map = new \Ds\Map([
    "a" => 1,
    "b" => 2,
    "c" => 3,
]);
print_r($map);

$map->clear();
print_r($map);
?>

The above example will output something similar to:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

)
Ds\Map Object
(
)


Creates a new instance

  • « Ds\Map::clear
  • Ds\Map::copy »
  • PHP Manual
  • Map
  • Creates a new instance

Ds\Map::__construct

(PECL ds >= 1.0.0)

Ds\Map::__construct — Creates a new instance

Description

public Ds\Map::__construct ([ mixed $...values ] )

Creates a new instance, using either a traversable object or an array for the initial values.

Parameters

values

A traversable object or an array to use for the initial values.

Examples

Example #1 Ds\Map::__construct() example

<?php
$map = new \Ds\Map();
var_dump($map);

$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
var_dump($map);
?>

The above example will output something similar to:

object(Ds\Map)#1 (0) {
}
object(Ds\Map)#2 (3) {
  [0]=>
  object(Ds\Pair)#1 (2) {
    ["key"]=>
    string(1) "a"
    ["value"]=>
    int(1)
  }
  [1]=>
  object(Ds\Pair)#3 (2) {
    ["key"]=>
    string(1) "b"
    ["value"]=>
    int(2)
  }
  [2]=>
  object(Ds\Pair)#4 (2) {
    ["key"]=>
    string(1) "c"
    ["value"]=>
    int(3)
  }
}


Returns a shallow copy of the map

  • « Ds\Map::__construct
  • Ds\Map::count »
  • PHP Manual
  • Map
  • Returns a shallow copy of the map

Ds\Map::copy

(PECL ds >= 1.0.0)

Ds\Map::copy — Returns a shallow copy of the map

Description

public Ds\Map::copy ( void ) : Ds\Map

Returns a shallow copy of the map.

Parameters

This function has no parameters.

Return Values

Returns a shallow copy of the map.

Examples

Example #1 Ds\Map::copy() example

<?php
$map = new \Ds\Map([
    "a" => 1,
    "b" => 2,
    "c" => 3,
]);

print_r($map->copy());
?>

The above example will output something similar to:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

)


Returns the number of values in the map

  • « Ds\Map::copy
  • Ds\Map::diff »
  • PHP Manual
  • Map
  • Returns the number of values in the map

Ds\Map::count

(PECL ds >= 1.0.0)

Ds\Map::count — Returns the number of values in the map

See Countable::count()


Creates a new map using keys that aren't in another map

  • « Ds\Map::count
  • Ds\Map::filter »
  • PHP Manual
  • Map
  • Creates a new map using keys that aren't in another map

Ds\Map::diff

(PECL ds >= 1.0.0)

Ds\Map::diff — Creates a new map using keys that aren't in another map

Description

public Ds\Map::diff ( Ds\Map $map ) : Ds\Map

Returns the result of removing all keys from the current instance that are present in a given map.

A \ B = {x ∈ A | x ∉ B}

Parameters

map

The map containing the keys to exclude in the resulting map.

Return Values

The result of removing all keys from the current instance that are present in a given map.

See Also

  • » Compliment on Wikipedia

Examples

Example #1 Ds\Map::diff() example

<?php
$a = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
$b = new \Ds\Map(["b" => 4, "c" => 5, "d" => 6]);

var_dump($a->diff($b));
?>

The above example will output something similar to:

object(Ds\Map)#3 (1) {
  [0]=>
  object(Ds\Pair)#4 (2) {
    ["key"]=>
    string(1) "a"
    ["value"]=>
    int(1)
  }
}


Creates a new map using a callable to determine which pairs to include

  • « Ds\Map::diff
  • Ds\Map::first »
  • PHP Manual
  • Map
  • Creates a new map using a callable to determine which pairs to include

Ds\Map::filter

(PECL ds >= 1.0.0)

Ds\Map::filter — Creates a new map using a callable to determine which pairs to include

Description

public Ds\Map::filter ([ callable $callback ] ) : Ds\Map

Creates a new map using a callable to determine which pairs to include.

Parameters

callback

callback ( mixed $key , mixed $value ) : bool

Optional callable which returns TRUE if the pair should be included, FALSE otherwise.

If a callback is not provided, only values which are TRUE (see converting to boolean) will be included.

Return Values

A new map containing all the pairs for which either the callback returned TRUE, or all values that convert to TRUE if a callback was not provided.

Examples

Example #1 Ds\Map::filter() example using callback function

<?php
$map = new \Ds\Map(["a", "b", "c", "d", "e"]);

var_dump($map->filter(function($key, $value) {
    return $key % 2 == 0;
}));
?>

The above example will output something similar to:

object(Ds\Map)#3 (3) {
  [0]=>
  object(Ds\Pair)#2 (2) {
    ["key"]=>
    int(0)
    ["value"]=>
    string(1) "a"
  }
  [1]=>
  object(Ds\Pair)#4 (2) {
    ["key"]=>
    int(2)
    ["value"]=>
    string(1) "c"
  }
  [2]=>
  object(Ds\Pair)#5 (2) {
    ["key"]=>
    int(4)
    ["value"]=>
    string(1) "e"
  }
}

Example #2 Ds\Map::filter() example without a callback function

<?php
$map = new \Ds\Map(["a" => 0, "b" => 1, "c" => true, "d" => false]);

var_dump($map->filter());
?>

The above example will output something similar to:

object(Ds\Map)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  string(1) "a"
  [2]=>
  bool(true)
}


Returns the first pair in the map

  • « Ds\Map::filter
  • Ds\Map::get »
  • PHP Manual
  • Map
  • Returns the first pair in the map

Ds\Map::first

(PECL ds >= 1.0.0)

Ds\Map::first — Returns the first pair in the map

Description

public Ds\Map::first ( void ) : Ds\Pair

Returns the first pair in the map.

Parameters

This function has no parameters.

Return Values

The first pair in the map.

Errors/Exceptions

UnderflowException if empty.

Examples

Example #1 Ds\Map::first() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
var_dump($map->first());
?>

The above example will output something similar to:

object(Ds\Pair)#2 (2) {
  ["key"]=>
  string(1) "a"
  ["value"]=>
  int(1)
}


Returns the value for a given key

  • « Ds\Map::first
  • Ds\Map::hasKey »
  • PHP Manual
  • Map
  • Returns the value for a given key

Ds\Map::get

(PECL ds >= 1.0.0)

Ds\Map::get — Returns the value for a given key

Description

public Ds\Map::get ( mixed $key [, mixed $default ] ) : mixed

Returns the value for a given key, or an optional default value if the key could not be found.

Note:

Keys of type object are supported. If an object implements Ds\Hashable, equality will be determined by the object's equals function. If an object does not implement Ds\Hashable, objects must be references to the same instance to be considered equal.

Note:

You can also use array syntax to access values by key, eg. $map["key"].

Caution

Be careful when using array syntax. Scalar keys will be coerced to integers by the engine. For example, $map["1"] will attempt to access int(1), while $map->get("1") will correctly look up the string key.

See Arrays.

Parameters

key

The key to look up.

default

The optional default value, returned if the key could not be found.

Return Values

The value mapped to the given key, or the default value if provided and the key could not be found in the map.

Errors/Exceptions

OutOfBoundsException if the key could not be found and a default value was not provided.

Examples

Example #1 Ds\Map::get() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

var_dump($map->get("a"));       // 1
var_dump($map->get("d", 10));   // 10 (default used)
?>

The above example will output something similar to:

int(1)
int(10)

Example #2 Ds\Map::get() example using array syntax

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

var_dump($map["a"])); // 1
?>

The above example will output something similar to:

int(1)


Determines whether the map contains a given key

  • « Ds\Map::get
  • Ds\Map::hasValue »
  • PHP Manual
  • Map
  • Determines whether the map contains a given key

Ds\Map::hasKey

(PECL ds >= 1.0.0)

Ds\Map::hasKey — Determines whether the map contains a given key

Description

public Ds\Map::hasKey ( mixed $key ) : bool

Determines whether the map contains a given key.

Parameters

key

The key to look for.

Return Values

Returns TRUE if the key could found, FALSE otherwise.

Examples

Example #1 Ds\Map::hasKey() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

var_dump($map->hasKey("a")); // true
var_dump($map->hasKey("e")); // false
?>

The above example will output something similar to:

bool(true)
bool(false)


Determines whether the map contains a given value

  • « Ds\Map::hasKey
  • Ds\Map::intersect »
  • PHP Manual
  • Map
  • Determines whether the map contains a given value

Ds\Map::hasValue

(PECL ds >= 1.0.0)

Ds\Map::hasValue — Determines whether the map contains a given value

Description

public Ds\Map::hasValue ( mixed $value ) : bool

Determines whether the map contains a given value.

Parameters

value

The value to look for.

Return Values

Returns TRUE if the value could found, FALSE otherwise.

Examples

Example #1 Ds\Map::hasValue() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

var_dump($map->hasValue(1)); // true
var_dump($map->hasValue(4)); // false
?>

The above example will output something similar to:

bool(true)
bool(false)


Creates a new map by intersecting keys with another map

  • « Ds\Map::hasValue
  • Ds\Map::isEmpty »
  • PHP Manual
  • Map
  • Creates a new map by intersecting keys with another map

Ds\Map::intersect

(PECL ds >= 1.0.0)

Ds\Map::intersect — Creates a new map by intersecting keys with another map

Description

public Ds\Map::intersect ( Ds\Map $map ) : Ds\Map

Creates a new map containing the pairs of the current instance whose keys are also present in the given map. In other words, returns a copy of the current instance with all keys removed that are not also in the other map.

A ∩ B = {x : x ∈ A ∧ x ∈ B}

Note:

Values from the current instance will be kept.

Parameters

map

The other map, containing the keys to intersect with.

Return Values

The key intersection of the current instance and another map.

See Also

  • » Intersection on Wikipedia

Examples

Example #1 Ds\Map::intersect() example

<?php
$a = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
$b = new \Ds\Map(["b" => 4, "c" => 5, "d" => 6]);

var_dump($a->intersect($b));
?>

The above example will output something similar to:

object(Ds\Map)#3 (2) {
  [0]=>
  object(Ds\Pair)#4 (2) {
    ["key"]=>
    string(1) "b"
    ["value"]=>
    int(2)
  }
  [1]=>
  object(Ds\Pair)#5 (2) {
    ["key"]=>
    string(1) "c"
    ["value"]=>
    int(3)
  }
}


Returns whether the map is empty

  • « Ds\Map::intersect
  • Ds\Map::jsonSerialize »
  • PHP Manual
  • Map
  • Returns whether the map is empty

Ds\Map::isEmpty

(PECL ds >= 1.0.0)

Ds\Map::isEmpty — Returns whether the map is empty

Description

public Ds\Map::isEmpty ( void ) : bool

Returns whether the map is empty.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the map is empty, FALSE otherwise.

Examples

Example #1 Ds\Map::isEmpty() example

<?php
$a = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
$b = new \Ds\Map();

var_dump($a->isEmpty());
var_dump($b->isEmpty());
?>

The above example will output something similar to:

bool(false)
bool(true)


Returns a representation that can be converted to JSON

  • « Ds\Map::isEmpty
  • Ds\Map::keys »
  • PHP Manual
  • Map
  • Returns a representation that can be converted to JSON

Ds\Map::jsonSerialize

(PECL ds >= 1.0.0)

Ds\Map::jsonSerialize — Returns a representation that can be converted to JSON

See JsonSerializable::jsonSerialize()

Note:

You should never need to call this directly.


Returns a set of the map's keys

  • « Ds\Map::jsonSerialize
  • Ds\Map::ksort »
  • PHP Manual
  • Map
  • Returns a set of the map's keys

Ds\Map::keys

(PECL ds >= 1.0.0)

Ds\Map::keys — Returns a set of the map's keys

Description

public Ds\Map::keys ( void ) : Ds\Set

Returns a set containing all the keys of the map, in the same order.

Parameters

This function has no parameters.

Return Values

A Ds\Set containing all the keys of the map.

Examples

Example #1 Ds\Map::keys() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
var_dump($map->keys());
?>

The above example will output something similar to:

object(Ds\Set)#2 (3) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
}


Sorts the map in-place by key

  • « Ds\Map::keys
  • Ds\Map::ksorted »
  • PHP Manual
  • Map
  • Sorts the map in-place by key

Ds\Map::ksort

(PECL ds >= 1.0.0)

Ds\Map::ksort — Sorts the map in-place by key

Description

public Ds\Map::ksort ([ callable $comparator ] ) : void

Sorts the map in-place by key, using an optional comparator function.

Parameters

comparator

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. Note that before PHP 7.0.0 this integer had to be in the range from -2147483648 to 2147483647.

callback ( mixed $a, mixed $b ) : int
Caution

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

Return Values

No value is returned.

Examples

Example #1 Ds\Map::ksort() example

<?php
$map = new \Ds\Map(["b" => 2, "c" => 3, "a" => 1]);
$map->ksort();

print_r($map);
?>

The above example will output something similar to:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

)

Example #2 Ds\Map::ksort() example using a comparator

<?php
$map = new \Ds\Map([1 => "x", 2 => "y", 0 => "z"]);

// Reverse
$map->ksort(function($a, $b) {
    return $b <=> $a;
});

print_r($map);
?>

The above example will output something similar to:

Ds\Map Object
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => 2
            [value] => y
        )

    [1] => Ds\Pair Object
        (
            [key] => 1
            [value] => x
        )

    [2] => Ds\Pair Object
        (
            [key] => 0
            [value] => z
        )

)


Returns a copy, sorted by key

  • « Ds\Map::ksort
  • Ds\Map::last »
  • PHP Manual
  • Map
  • Returns a copy, sorted by key

Ds\Map::ksorted

(No version information available, might only be in Git)

Ds\Map::ksorted — Returns a copy, sorted by key

Description

public Ds\Map::ksorted ([ callable $comparator ] ) : Ds\Map

Returns a copy sorted by key, using an optional comparator function.

Parameters

comparator

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. Note that before PHP 7.0.0 this integer had to be in the range from -2147483648 to 2147483647.

callback ( mixed $a, mixed $b ) : int
Caution

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

Return Values

Returns a copy of the map, sorted by key.

Examples

Example #1 Ds\Map::ksorted() example

<?php
$map = new \Ds\Map(["b" => 2, "c" => 3, "a" => 1]);

print_r($map->ksorted());
?>

The above example will output something similar to:

Ds\Map Object
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

)

Example #2 Ds\Map::ksorted() example using a comparator

<?php
$map = new \Ds\Map([1 => "x", 2 => "y", 0 => "z"]);

// Reverse
$sorted = $map->ksorted(function($a, $b) {
    return $b <=> $a;
});

print_r($sorted);
?>

The above example will output something similar to:

Ds\Map Object
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => 2
            [value] => y
        )

    [1] => Ds\Pair Object
        (
            [key] => 1
            [value] => x
        )

    [2] => Ds\Pair Object
        (
            [key] => 0
            [value] => z
        )

)


Returns the last pair of the map

  • « Ds\Map::ksorted
  • Ds\Map::map »
  • PHP Manual
  • Map
  • Returns the last pair of the map

Ds\Map::last

(PECL ds >= 1.0.0)

Ds\Map::last — Returns the last pair of the map

Description

public Ds\Map::last ( void ) : Ds\Pair

Returns the last pair of the map.

Parameters

This function has no parameters.

Return Values

The last pair of the map.

Errors/Exceptions

UnderflowException if empty.

Examples

Example #1 Ds\Map::last() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
var_dump($map->last());
?>

The above example will output something similar to:

object(Ds\Pair)#2 (2) {
  ["key"]=>
  string(1) "c"
  ["value"]=>
  int(3)
}


Returns the result of applying a callback to each value

  • « Ds\Map::last
  • Ds\Map::merge »
  • PHP Manual
  • Map
  • Returns the result of applying a callback to each value

Ds\Map::map

(PECL ds >= 1.0.0)

Ds\Map::map — Returns the result of applying a callback to each value

Description

public Ds\Map::map ( callable $callback ) : Ds\Map

Returns the result of applying a callback function to each value of the map.

Parameters

callback

callback ( mixed $key , mixed $value ) : mixed

A callable to apply to each value in the map.

The callable should return what the key will be mapped to in the resulting map.

Return Values

The result of applying a callback to each value in the map.

Note:

The keys and values of the current instance won't be affected.

Examples

Example #1 Ds\Map::map() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

print_r($map->map(function($key, $value) { return $value * 2; }));
print_r($map);
?>

The above example will output something similar to:

(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 2
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 4
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 6
        )

)
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

)


Returns the result of adding all given associations

  • « Ds\Map::map
  • Ds\Map::pairs »
  • PHP Manual
  • Map
  • Returns the result of adding all given associations

Ds\Map::merge

(PECL ds >= 1.0.0)

Ds\Map::merge — Returns the result of adding all given associations

Description

public Ds\Map::merge ( mixed $values ) : Ds\Map

Returns the result of associating all keys of a given traversable object or array with their corresponding values, combined with the current instance.

Note:

Values of the current instance will be overwritten by those provided where keys are equal.

Parameters

values

A traversable object or an array.

Return Values

The result of associating all keys of a given traversable object or array with their corresponding values, combined with the current instance.

Note:

The current instance won't be affected.

Examples

Example #1 Ds\Map::merge() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

print_r($map->merge(["a" => 10, "e" => 50]));
?>

The above example will output something similar to:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 10
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

    [3] => Ds\Pair Object
        (
            [key] => e
            [value] => 50
        )

)


Returns a sequence containing all the pairs of the map

  • « Ds\Map::merge
  • Ds\Map::put »
  • PHP Manual
  • Map
  • Returns a sequence containing all the pairs of the map

Ds\Map::pairs

(PECL ds >= 1.0.0)

Ds\Map::pairs — Returns a sequence containing all the pairs of the map

Description

public Ds\Map::pairs ( void ) : Ds\Sequence

Returns a Ds\Sequence containing all the pairs of the map.

Parameters

This function has no parameters.

Return Values

Ds\Sequence containing all the pairs of the map.

Examples

Example #1 Ds\Map::pairs() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

var_dump($map->pairs());
?>

The above example will output something similar to:

object(Ds\Map)#8 (3) {
  [0]=>
  object(Ds\Pair)#5 (2) {
    ["key"]=>
    string(1) "a"
    ["value"]=>
    int(1)
  }
  [1]=>
  object(Ds\Pair)#6 (2) {
    ["key"]=>
    string(1) "b"
    ["value"]=>
    int(2)
  }
  [2]=>
  object(Ds\Pair)#7 (2) {
    ["key"]=>
    string(1) "c"
    ["value"]=>
    int(3)
  }
}
p


Associates a key with a value

  • « Ds\Map::pairs
  • Ds\Map::putAll »
  • PHP Manual
  • Map
  • Associates a key with a value

Ds\Map::put

(PECL ds >= 1.0.0)

Ds\Map::put — Associates a key with a value

Description

public Ds\Map::put ( mixed $key , mixed $value ) : void

Associates a key with a value, overwriting a previous association if one exists.

Note:

Keys of type object are supported. If an object implements Ds\Hashable, equality will be determined by the object's equals function. If an object does not implement Ds\Hashable, objects must be references to the same instance to be considered equal.

Note:

You can also use array syntax to associate values by key, eg. $map["key"] = $value.

Caution

Be careful when using array syntax. Scalar keys will be coerced to integers by the engine. For example, $map["1"] will attempt to access int(1), while $map->get("1") will correctly look up the string key.

See Arrays.

Parameters

key

The key to associate the value with.

value

The value to be associated with the key.

Return Values

No value is returned.

Examples

Example #1 Ds\Map::put() example

<?php
$map = new \Ds\Map();

$map->put("a", 1);
$map->put("b", 2);
$map->put("c", 3);

print_r($map);
?>

The above example will output something similar to:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

)

Example #2 Ds\Map::put() example using objects as keys

<?php
class HashableObject implements \Ds\Hashable
{
    /**
     * An arbitrary value to use as the hash value. Does not define equality.
     */
    private $value;

    public function __construct($value)
    {
        $this->value = $value;
    }

    public function hash()
    {
        return $this->value;
    }

    public function equals($obj): bool
    {
        return $this->value === $obj->value;
    }
}

$map = new \Ds\Map();

$obj = new \ArrayIterator([]);

// Using the same instance multiple times will overwrite the previous value.
$map->put($obj, 1);
$map->put($obj, 2);

// Using multiple instances of the same object will create new associations.
$map->put(new \stdClass(), 3);
$map->put(new \stdClass(), 4);

// Using multiple instances of equal hashable objects will overwrite previous values.
$map->put(new \HashableObject(1), 5);
$map->put(new \HashableObject(1), 6);
$map->put(new \HashableObject(2), 7);
$map->put(new \HashableObject(2), 8);

var_dump($map);
?>

The above example will output something similar to:

object(Ds\Map)#1 (5) {
  [0]=>
  object(Ds\Pair)#7 (2) {
    ["key"]=>
    object(ArrayIterator)#2 (1) {
      ["storage":"ArrayIterator":private]=>
      array(0) {
      }
    }
    ["value"]=>
    int(2)
  }
  [1]=>
  object(Ds\Pair)#8 (2) {
    ["key"]=>
    object(stdClass)#3 (0) {
    }
    ["value"]=>
    int(3)
  }
  [2]=>
  object(Ds\Pair)#9 (2) {
    ["key"]=>
    object(stdClass)#4 (0) {
    }
    ["value"]=>
    int(4)
  }
  [3]=>
  object(Ds\Pair)#10 (2) {
    ["key"]=>
    object(HashableObject)#5 (1) {
      ["value":"HashableObject":private]=>
      int(1)
    }
    ["value"]=>
    int(6)
  }
  [4]=>
  object(Ds\Pair)#11 (2) {
    ["key"]=>
    object(HashableObject)#6 (1) {
      ["value":"HashableObject":private]=>
      int(2)
    }
    ["value"]=>
    int(8)
  }
}


Associates all key-value pairs of a traversable object or array

  • « Ds\Map::put
  • Ds\Map::reduce »
  • PHP Manual
  • Map
  • Associates all key-value pairs of a traversable object or array

Ds\Map::putAll

(PECL ds >= 1.0.2)

Ds\Map::putAll — Associates all key-value pairs of a traversable object or array

Description

public Ds\Map::putAll ( mixed $pairs ) : void

Associates all key-value pairs of a traversable object or array.

Note:

Keys of type object are supported. If an object implements Ds\Hashable, equality will be determined by the object's equals function. If an object does not implement Ds\Hashable, objects must be references to the same instance to be considered equal.

Parameters

pairs

traversable object or array.

Return Values

No value is returned.

Examples

Example #1 Ds\Map::putAll() example

<?php
$map = new \Ds\Map();

$map->putAll([
    "a" => 1,
    "b" => 2,
    "c" => 3,
]);

print_r($map);
?>

The above example will output something similar to:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

)


Reduces the map to a single value using a callback function

  • « Ds\Map::putAll
  • Ds\Map::remove »
  • PHP Manual
  • Map
  • Reduces the map to a single value using a callback function

Ds\Map::reduce

(PECL ds >= 1.0.0)

Ds\Map::reduce — Reduces the map to a single value using a callback function

Description

public Ds\Map::reduce ( callable $callback [, mixed $initial ] ) : mixed

Reduces the map to a single value using a callback function.

Parameters

callback
callback ( mixed $carry , mixed $key , mixed $value ) : mixed
carry

The return value of the previous callback, or initial if it's the first iteration.

key

The key of the current iteration.

value

The value of the current iteration.

initial

The initial value of the carry value. Can be NULL.

Return Values

The return value of the final callback.

Examples

Example #1 Ds\Map::reduce() with initial value example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

$callback = function($carry, $key, $value) {
    return $carry * $value;
};

var_dump($map->reduce($callback, 5));

// Iterations:
//
// $carry = $initial = 5
//
// $carry = $carry * 1 =  5
// $carry = $carry * 2 = 10
// $carry = $carry * 3 = 30
?>

The above example will output something similar to:

int(30)

Example #2 Ds\Map::reduce() without an initial value example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

var_dump($map->reduce(function($carry, $key, $value) {
    return $carry + $value + 5;
}));

// Iterations:
//
// $carry = $initial = null
//
// $carry = $carry + 1 + 5 =  6
// $carry = $carry + 2 + 5 = 13
// $carry = $carry + 3 + 5 = 21
?>

The above example will output something similar to:

int(21)


Removes and returns a value by key

  • « Ds\Map::reduce
  • Ds\Map::reverse »
  • PHP Manual
  • Map
  • Removes and returns a value by key

Ds\Map::remove

(PECL ds >= 1.0.0)

Ds\Map::remove — Removes and returns a value by key

Description

public Ds\Map::remove ( mixed $key [, mixed $default ] ) : mixed

Removes and returns a value by key, or return an optional default value if the key could not be found.

Note:

Keys of type object are supported. If an object implements Ds\Hashable, equality will be determined by the object's equals function. If an object does not implement Ds\Hashable, objects must be references to the same instance to be considered equal.

Note:

You can also use array syntax to access values by key, eg. $map["key"].

Caution

Be careful when using array syntax. Scalar keys will be coerced to integers by the engine. For example, $map["1"] will attempt to access int(1), while $map->get("1") will correctly look up the string key.

See Arrays.

Parameters

key

The key to remove.

default

The optional default value, returned if the key could not be found.

Return Values

The value that was removed, or the default value if provided and the key could not be found in the map.

Errors/Exceptions

OutOfBoundsException if the key could not be found and a default value was not provided.

Examples

Example #1 Ds\Map::remove() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

var_dump($map->remove("a"));      //  1
var_dump($map->remove("e", 10));  // 10 (default used)
?>

The above example will output something similar to:

int(1)
int(10)


Reverses the map in-place

  • « Ds\Map::remove
  • Ds\Map::reversed »
  • PHP Manual
  • Map
  • Reverses the map in-place

Ds\Map::reverse

(PECL ds >= 1.0.0)

Ds\Map::reverse — Reverses the map in-place

Description

public Ds\Map::reverse ( void ) : void

Reverses the map in-place.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 Ds\Map::reverse() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
$map->reverse();

print_r($map);
?>

The above example will output something similar to:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

)


Returns a reversed copy

  • « Ds\Map::reverse
  • Ds\Map::skip »
  • PHP Manual
  • Map
  • Returns a reversed copy

Ds\Map::reversed

(PECL ds >= 1.0.0)

Ds\Map::reversed — Returns a reversed copy

Description

public Ds\Map::reversed ( void ) : Ds\Map

Returns a reversed copy of the map.

Parameters

This function has no parameters.

Return Values

A reversed copy of the map.

Note:

The current instance is not affected.

Examples

Example #1 Ds\Map::reversed() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

print_r($map->reversed());
?>

The above example will output something similar to:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

)


Returns the pair at a given positional index

  • « Ds\Map::reversed
  • Ds\Map::slice »
  • PHP Manual
  • Map
  • Returns the pair at a given positional index

Ds\Map::skip

(PECL ds >= 1.0.0)

Ds\Map::skip — Returns the pair at a given positional index

Description

public Ds\Map::skip ( int $position ) : Ds\Pair

Returns the pair at a given zero-based position.

Parameters

position

The zero-based positional index to return.

Return Values

Returns the Ds\Pair at the given position.

Errors/Exceptions

OutOfRangeException if the position is not valid.

Examples

Example #1 Ds\Map::skip() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

var_dump($map->skip(1));
?>

The above example will output something similar to:

object(Ds\Pair)#2 (2) {
  ["key"]=>
  string(1) "b"
  ["value"]=>
  int(2)
}


Returns a subset of the map defined by a starting index and length

  • « Ds\Map::skip
  • Ds\Map::sort »
  • PHP Manual
  • Map
  • Returns a subset of the map defined by a starting index and length

Ds\Map::slice

(PECL ds >= 1.0.0)

Ds\Map::slice — Returns a subset of the map defined by a starting index and length

Description

public Ds\Map::slice ( int $index [, int $length ] ) : Ds\Map

Returns a subset of the map defined by a starting index and length.

Parameters

index

The index at which the range starts.

If positive, the range will start at that index in the map. If negative, the range will start that far from the end.

length

If a length is given and is positive, the resulting map will have up to that many pairs in it. If a length is given and is negative, the range will stop that many pairs from the end. If the length results in an overflow, only pairs up to the end of the map will be included. If a length is not provided, the resulting map will contain all pairs between the index and the end of the map.

Return Values

A subset of the map defined by a starting index and length.

Examples

Example #1 Ds\Map::slice() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3, "d" => 4, "e" => 5]);

// Slice from 2 onwards
print_r($map->slice(2)->toArray());

// Slice from 1, for a length of 3
print_r($map->slice(1, 3)->toArray());

// Slice from 1 onwards
print_r($map->slice(1)->toArray());

// Slice from 2 from the end onwards
print_r($map->slice(-2)->toArray());

// Slice from 1 to 1 from the end
print_r($map->slice(1, -1)->toArray());
?>

The above example will output something similar to:

Array
(
    [c] => 3
    [d] => 4
    [e] => 5
)
Array
(
    [b] => 2
    [c] => 3
    [d] => 4
)
Array
(
    [b] => 2
    [c] => 3
    [d] => 4
    [e] => 5
)
Array
(
    [d] => 4
    [e] => 5
)
Array
(
    [b] => 2
    [c] => 3
    [d] => 4
)


Sorts the map in-place by value

  • « Ds\Map::slice
  • Ds\Map::sorted »
  • PHP Manual
  • Map
  • Sorts the map in-place by value

Ds\Map::sort

(PECL ds >= 1.0.0)

Ds\Map::sort — Sorts the map in-place by value

Description

public Ds\Map::sort ([ callable $comparator ] ) : void

Sorts the map in-place by value, using an optional comparator function.

Parameters

comparator

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. Note that before PHP 7.0.0 this integer had to be in the range from -2147483648 to 2147483647.

callback ( mixed $a, mixed $b ) : int
Caution

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

Return Values

No value is returned.

Examples

Example #1 Ds\Map::sort() example

<?php
$map = new \Ds\Map(["a" => 2, "b" => 3, "c" => 1]);
$map->sort();

print_r($map);
?>

The above example will output something similar to:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => c
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => a
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => b
            [value] => 3
        )

)

Example #2 Ds\Map::sort() example using a comparator

<?php
$map = new \Ds\Map(["a" => 2, "b" => 3, "c" => 1]);

$map->sort(function($a, $b) {
    return $b <=> $a;
});

print_r($map);
?>

The above example will output something similar to:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => b
            [value] => 3
        )

    [1] => Ds\Pair Object
        (
            [key] => a
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 1
        )

)


Returns a copy, sorted by value

  • « Ds\Map::sort
  • Ds\Map::sum »
  • PHP Manual
  • Map
  • Returns a copy, sorted by value

Ds\Map::sorted

(PECL ds >= 1.0.0)

Ds\Map::sorted — Returns a copy, sorted by value

Description

public Ds\Map::sorted ([ callable $comparator ] ) : Ds\Map

Returns a copy, sorted by value using an optional comparator function.

Parameters

comparator

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. Note that before PHP 7.0.0 this integer had to be in the range from -2147483648 to 2147483647.

callback ( mixed $a, mixed $b ) : int
Caution

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

Return Values

Returns a copy of the map, sorted by value.

Examples

Example #1 Ds\Map::sort() example

<?php
$map = new \Ds\Map(["a" => 2, "b" => 3, "c" => 1]);

print_r($map->sorted());
?>

The above example will output something similar to:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => c
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => a
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => b
            [value] => 3
        )

)

Example #2 Ds\Map::sort() example using a comparator

<?php
$map = new \Ds\Map(["a" => 2, "b" => 3, "c" => 1]);

// Reverse
$sorted = $map->sorted(function($a, $b) {
    return $b <=> $a;
});

print_r($sorted);
?>

The above example will output something similar to:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => b
            [value] => 3
        )

    [1] => Ds\Pair Object
        (
            [key] => a
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 1
        )

)


Returns the sum of all values in the map

  • « Ds\Map::sorted
  • Ds\Map::toArray »
  • PHP Manual
  • Map
  • Returns the sum of all values in the map

Ds\Map::sum

(No version information available, might only be in Git)

Ds\Map::sum — Returns the sum of all values in the map

Description

public Ds\Map::sum ( void ) : number

Returns the sum of all values in the map.

Note:

Arrays and objects are considered equal to zero when calculating the sum.

Parameters

This function has no parameters.

Return Values

The sum of all the values in the map as either a float or int depending on the values in the map.

Examples

Example #1 Ds\Map::sum() integer example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
var_dump($map->sum());
?>

The above example will output something similar to:

int(6)

Example #2 Ds\Map::sum() float example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2.5, "c" => 3]);
var_dump($map->sum());
?>

The above example will output something similar to:

float(6.5)


Converts the map to an array

  • « Ds\Map::sum
  • Ds\Map::union »
  • PHP Manual
  • Map
  • Converts the map to an array

Ds\Map::toArray

(PECL ds >= 1.0.0)

Ds\Map::toArray — Converts the map to an array

Description

public Ds\Map::toArray ( void ) : array

Converts the map to an array.

Caution

Maps where non-scalar keys are can't be converted to an array.

Caution

An array will treat all numeric keys as integers, eg. "1" and 1 as keys in the map will only result in 1 being included in the array.

Note:

Casting to an array is not supported yet.

Parameters

This function has no parameters.

Return Values

An array containing all the values in the same order as the map.

Examples

Example #1 Ds\Map::toArray() example

<?php
$map = new \Ds\Map([
    "a" => 1,
    "b" => 2,
    "c" => 3,
]);

var_dump($map->toArray());
?>

The above example will output something similar to:

array(3) {
  ["a"]=>
  int(1)
  ["b"]=>
  int(2)
  ["c"]=>
  int(3)
}


Creates a new map using values from the current instance and another map

  • « Ds\Map::toArray
  • Ds\Map::values »
  • PHP Manual
  • Map
  • Creates a new map using values from the current instance and another map

Ds\Map::union

(PECL ds >= 1.0.0)

Ds\Map::union — Creates a new map using values from the current instance and another map

Description

public Ds\Map::union ( Ds\Map $map ) : Ds\Map

Creates a new map that contains the pairs of the current instance as well as the pairs of another map.

A ∪ B = {x: x ∈ A ∨ x ∈ B}

Note:

Values of the current instance will be overwritten by those provided where keys are equal.

Parameters

map

The other map, to combine with the current instance.

Return Values

A new map containing all the pairs of the current instance as well as another map.

See Also

  • » Union on Wikipedia

Examples

Example #1 Ds\Map::union() example

<?php
$a = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
$b = new \Ds\Map(["b" => 3, "c" => 4, "d" => 5]);

print_r($a->union($b));
?>

The above example will output something similar to:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 3
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 4
        )

    [3] => Ds\Pair Object
        (
            [key] => d
            [value] => 5
        )

)


Returns a sequence of the map's values

  • « Ds\Map::union
  • Ds\Map::xor »
  • PHP Manual
  • Map
  • Returns a sequence of the map's values

Ds\Map::values

(PECL ds >= 1.0.0)

Ds\Map::values — Returns a sequence of the map's values

Description

public Ds\Map::values ( void ) : Ds\Sequence

Returns a sequence containing all the values of the map, in the same order.

Parameters

This function has no parameters.

Return Values

A Ds\Sequence containing all the values of the map.

Examples

Example #1 Ds\Map::values() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
var_dump($map->values());
?>

The above example will output something similar to:

object(Ds\Map)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}


Creates a new map using keys of either the current instance or of another map, but not of both

  • « Ds\Map::values
  • Pair »
  • PHP Manual
  • Map
  • Creates a new map using keys of either the current instance or of another map, but not of both

Ds\Map::xor

(PECL ds >= 1.0.0)

Ds\Map::xor — Creates a new map using keys of either the current instance or of another map, but not of both

Description

public Ds\Map::xor ( Ds\Map $map ) : Ds\Map

Creates a new map containing keys of the current instance as well as another map, but not of both.

A ⊖ B = {x : x ∈ (A \ B) ∪ (B \ A)}

Parameters

map

The other map.

Return Values

A new map containing keys in the current instance as well as another map, but not in both.

See Also

  • » Symmetric Difference on Wikipedia

Examples

Example #1 Ds\Map::xor() example

<?php
$a = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
$b = new \Ds\Map(["b" => 4, "c" => 5, "d" => 6]);

print_r($a->xor($b));
?>

The above example will output something similar to:

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => d
            [value] => 6
        )

)


The Pair class

(No version information available, might only be in Git)

Introduction

A pair is used by Ds\Map to pair keys with values.

Class synopsis

Ds\Pair implements JsonSerializable {
/* Methods */
public __construct ([ mixed $key [, mixed $value ]] )
public clear ( void ) : void
public copy ( void ) : Ds\Pair
public isEmpty ( void ) : bool
public toArray ( void ) : array
}

Table of Contents

  • Ds\Pair::clear — Removes all values
  • Ds\Pair::__construct — Creates a new instance
  • Ds\Pair::copy — Returns a shallow copy of the pair
  • Ds\Pair::isEmpty — Returns whether the pair is empty
  • Ds\Pair::jsonSerialize — Returns a representation that can be converted to JSON
  • Ds\Pair::toArray — Converts the pair to an array


Removes all values

  • « Pair
  • Ds\Pair::__construct »
  • PHP Manual
  • Pair
  • Removes all values

Ds\Pair::clear

(No version information available, might only be in Git)

Ds\Pair::clear — Removes all values

Description

public Ds\Pair::clear ( void ) : void

Removes all values from the pair.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 Ds\Pair::clear() example

<?php
$pair = new \Ds\Pair("a", 1);
print_r($pair);

$pair->clear();
print_r($pair);
?>

The above example will output something similar to:

Ds\Pair Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Pair Object
(
)


Creates a new instance

  • « Ds\Pair::clear
  • Ds\Pair::copy »
  • PHP Manual
  • Pair
  • Creates a new instance

Ds\Pair::__construct

(PECL ds >= 1.0.0)

Ds\Pair::__construct — Creates a new instance

Description

public Ds\Pair::__construct ([ mixed $key [, mixed $value ]] )

Creates a new instance using a given key and value.

Parameters

key

The key.

value

The value.


Returns a shallow copy of the pair

  • « Ds\Pair::__construct
  • Ds\Pair::isEmpty »
  • PHP Manual
  • Pair
  • Returns a shallow copy of the pair

Ds\Pair::copy

(No version information available, might only be in Git)

Ds\Pair::copy — Returns a shallow copy of the pair

Description

public Ds\Pair::copy ( void ) : Ds\Pair

Returns a shallow copy of the pair.

Parameters

This function has no parameters.

Return Values

Returns a shallow copy of the pair.

Examples

Example #1 Ds\Pair::copy() example

<?php
$a = new \Ds\Pair("a", 1);
$b = $a->copy();

$a->key = "x";

print_r($a);
print_r($b);
?>

The above example will output something similar to:

Ds\Pair Object
(
    [key] => x
    [value] => 1
)
Ds\Pair Object
(
    [key] => a
    [value] => 1
)


Returns whether the pair is empty

  • « Ds\Pair::copy
  • Ds\Pair::jsonSerialize »
  • PHP Manual
  • Pair
  • Returns whether the pair is empty

Ds\Pair::isEmpty

(No version information available, might only be in Git)

Ds\Pair::isEmpty — Returns whether the pair is empty

Description

public Ds\Pair::isEmpty ( void ) : bool

Returns whether the pair is empty.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the pair is empty, FALSE otherwise.

Examples

Example #1 Ds\Pair::isEmpty() example

<?php
$a = new \Ds\Pair("a", 1);
$b = new \Ds\Pair();

var_dump($a->isEmpty());
var_dump($b->isEmpty());
?>

The above example will output something similar to:

bool(false)
bool(true)


Returns a representation that can be converted to JSON

  • « Ds\Pair::isEmpty
  • Ds\Pair::toArray »
  • PHP Manual
  • Pair
  • Returns a representation that can be converted to JSON

Ds\Pair::jsonSerialize

(PECL ds >= 1.0.0)

Ds\Pair::jsonSerialize — Returns a representation that can be converted to JSON

See JsonSerializable::jsonSerialize()

Note:

You should never need to call this directly.


Converts the pair to an array

  • « Ds\Pair::jsonSerialize
  • Set »
  • PHP Manual
  • Pair
  • Converts the pair to an array

Ds\Pair::toArray

(PECL ds >= 1.0.0)

Ds\Pair::toArray — Converts the pair to an array

Description

public Ds\Pair::toArray ( void ) : array

Converts the pair to an array.

Note:

Casting to an array is not supported yet.

Parameters

This function has no parameters.

Return Values

An array containing all the values in the same order as the pair.

Examples

Example #1 Ds\Pair::toArray() example

<?php
$pair = new \Ds\Pair("a", 1);

var_dump($pair->toArray());
?>

The above example will output something similar to:

array(2) {
  ["key"]=>
  string(1) "a"
  ["value"]=>
  int(1)
}


The Set class

(No version information available, might only be in Git)

Introduction

A Set is a sequence of unique values. This implementation uses the same hash table as Ds\Map, where values are used as keys and the mapped value is ignored.

Strengths

  • Values can be any type, including objects.
  • Supports array syntax (square brackets).
  • Insertion order is preserved.
  • Automatically frees allocated memory when its size drops low enough.
  • add(),
remove() and
contains() are all O(1).

Weaknesses

  • Doesn’t support
                push(),
                pop(),
                insert(),
                shift(), or
                unshift().
  • get() is O(n) if there are deleted values in the buffer before the accessed index, O(1) otherwise.

Class synopsis

Ds\Set implements Ds\Collection {
/* Constants */
const int MIN_CAPACITY = 16 ;
/* Methods */
public add ([ mixed $...values ] ) : void
public allocate ( int $capacity ) : void
public capacity ( void ) : int
public clear ( void ) : void
public contains ([ mixed $...values ] ) : bool
public copy ( void ) : Ds\Set
public diff ( Ds\Set $set ) : Ds\Set
public filter ([ callable $callback ] ) : Ds\Set
public first ( void ) : mixed
public get ( int $index ) : mixed
public intersect ( Ds\Set $set ) : Ds\Set
public isEmpty ( void ) : bool
public join ([ string $glue ] ) : string
public last ( void ) : void
public merge ( mixed $values ) : Ds\Set
public reduce ( callable $callback [, mixed $initial ] ) : mixed
public remove ([ mixed $...values ] ) : void
public reverse ( void ) : void
public reversed ( void ) : Ds\Set
public slice ( int $index [, int $length ] ) : Ds\Set
public sort ([ callable $comparator ] ) : void
public sorted ([ callable $comparator ] ) : Ds\Set
public sum ( void ) : number
public toArray ( void ) : array
public union ( Ds\Set $set ) : Ds\Set
public xor ( Ds\Set $set ) : Ds\Set
}

Predefined Constants

Ds\Set::MIN_CAPACITY

Table of Contents

  • Ds\Set::add — Adds values to the set
  • Ds\Set::allocate — Allocates enough memory for a required capacity
  • Ds\Set::capacity — Returns the current capacity
  • Ds\Set::clear — Removes all values
  • Ds\Set::__construct — Creates a new instance
  • Ds\Set::contains — Determines if the set contains all values
  • Ds\Set::copy — Returns a shallow copy of the set
  • Ds\Set::count — Returns the number of values in the set
  • Ds\Set::diff — Creates a new set using values that aren't in another set
  • Ds\Set::filter — Creates a new set using a callable to determine which values to include
  • Ds\Set::first — Returns the first value in the set
  • Ds\Set::get — Returns the value at a given index
  • Ds\Set::intersect — Creates a new set by intersecting values with another set
  • Ds\Set::isEmpty — Returns whether the set is empty
  • Ds\Set::join — Joins all values together as a string
  • Ds\Set::jsonSerialize — Returns a representation that can be converted to JSON
  • Ds\Set::last — Returns the last value in the set
  • Ds\Set::merge — Returns the result of adding all given values to the set
  • Ds\Set::reduce — Reduces the set to a single value using a callback function
  • Ds\Set::remove — Removes all given values from the set
  • Ds\Set::reverse — Reverses the set in-place
  • Ds\Set::reversed — Returns a reversed copy
  • Ds\Set::slice — Returns a sub-set of a given range
  • Ds\Set::sort — Sorts the set in-place
  • Ds\Set::sorted — Returns a sorted copy
  • Ds\Set::sum — Returns the sum of all values in the set
  • Ds\Set::toArray — Converts the set to an array
  • Ds\Set::union — Creates a new set using values from the current instance and another set
  • Ds\Set::xor — Creates a new set using values in either the current instance or in another set, but not in both


Adds values to the set

  • « Set
  • Ds\Set::allocate »
  • PHP Manual
  • Set
  • Adds values to the set

Ds\Set::add

(PECL ds >= 1.0.0)

Ds\Set::add — Adds values to the set

Description

public Ds\Set::add ([ mixed $...values ] ) : void

Adds all given values to the set that haven't already been added.

Note:

Values of type object are supported. If an object implements Ds\Hashable, equality will be determined by the object's equals function. If an object does not implement Ds\Hashable, objects must be references to the same instance to be considered equal.

Caution

All comparisons are strict (type and value).

Parameters

values

Values to add to the set.

Return Values

No value is returned.

Examples

Example #1 Ds\Set::add() example using integers

<?php
$set = new \Ds\Set();

$set->add(1);
$set->add(1);
$set->add(2);
$set->add(3);

// Strict comparison would not treat these the same as int(1)
$set->add("1");
$set->add(true);

var_dump($set);
?>

The above example will output something similar to:

object(Ds\Set)#1 (5) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  string(1) "1"
  [4]=>
  bool(true)
}

Example #2 Ds\Set::add() example using objects

<?php
class HashableObject implements \Ds\Hashable
{
    /**
     * An arbitrary value to use as the hash value. Does not define equality.
     */
    private $value;

    public function __construct($value)
    {
        $this->value = $value;
    }

    public function hash()
    {
        return $this->value;
    }

    public function equals($obj): bool
    {
        return $this->value === $obj->value;
    }
}

$set = new \Ds\Set();

$obj = new \ArrayIterator([]);

// Adding the same instance multiple times will only add the first.
$set->add($obj);
$set->add($obj);

// Adding multiple instances of the same object will add them all.
$set->add(new \stdClass());
$set->add(new \stdClass());

// Adding multiple instances of equal hashable objects will only add the first.
$set->add(new \HashableObject(1));
$set->add(new \HashableObject(1));
$set->add(new \HashableObject(2));
$set->add(new \HashableObject(2));

var_dump($set);
?>

The above example will output something similar to:

object(Ds\Set)#1 (5) {
  [0]=>
  object(ArrayIterator)#2 (1) {
    ["storage":"ArrayIterator":private]=>
    array(0) {
    }
  }
  [1]=>
  object(stdClass)#3 (0) {
  }
  [2]=>
  object(stdClass)#4 (0) {
  }
  [3]=>
  object(HashableObject)#5 (1) {
    ["value":"HashableObject":private]=>
    int(1)
  }
  [4]=>
  object(HashableObject)#6 (1) {
    ["value":"HashableObject":private]=>
    int(2)
  }
}


Allocates enough memory for a required capacity

  • « Ds\Set::add
  • Ds\Set::capacity »
  • PHP Manual
  • Set
  • Allocates enough memory for a required capacity

Ds\Set::allocate

(PECL ds >= 1.0.0)

Ds\Set::allocate — Allocates enough memory for a required capacity

Description

public Ds\Set::allocate ( int $capacity ) : void

Allocates enough memory for a required capacity.

Parameters

capacity

The number of values for which capacity should be allocated.

Note:

Capacity will stay the same if this value is less than or equal to the current capacity.

Note:

Capacity will always be rounded up to the nearest power of 2.

Return Values

No value is returned.

Examples

Example #1 Ds\Set::allocate() example

<?php
$set = new \Ds\Set();
var_dump($set->capacity());

$set->allocate(100);
var_dump($set->capacity());
?>

The above example will output something similar to:

int(16)
int(128)


Returns the current capacity

  • « Ds\Set::allocate
  • Ds\Set::clear »
  • PHP Manual
  • Set
  • Returns the current capacity

Ds\Set::capacity

(PECL ds >= 1.0.0)

Ds\Set::capacity — Returns the current capacity

Description

public Ds\Set::capacity ( void ) : int

Returns the current capacity.

Parameters

This function has no parameters.

Return Values

The current capacity.

Examples

Example #1 Ds\Set::capacity() example

<?php
$set = new \Ds\Set();
var_dump($set->capacity());

$set->push(...range(1, 50));
var_dump($set->capacity());
?>

The above example will output something similar to:

int(16)
int(64)


Removes all values

  • « Ds\Set::capacity
  • Ds\Set::__construct »
  • PHP Manual
  • Set
  • Removes all values

Ds\Set::clear

(PECL ds >= 1.0.0)

Ds\Set::clear — Removes all values

Description

public Ds\Set::clear ( void ) : void

Removes all values from the set.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 Ds\Set::clear() example

<?php
$set = new \Ds\Set([1, 2, 3]);
print_r($set);

$set->clear();
print_r($set);
?>

The above example will output something similar to:

Ds\Set Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Set Object
(
)


Creates a new instance

  • « Ds\Set::clear
  • Ds\Set::contains »
  • PHP Manual
  • Set
  • Creates a new instance

Ds\Set::__construct

(PECL ds >= 1.0.0)

Ds\Set::__construct — Creates a new instance

Description

public Ds\Set::__construct ([ mixed $...values ] )

Creates a new instance, using either a traversable object or an array for the initial values.

Parameters

values

A traversable object or an array to use for the initial values.

Examples

Example #1 Ds\Set::__construct() example

<?php
$set = new \Ds\Set();
var_dump($set);

$set = new \Ds\Set([1, 2, 3]);
var_dump($set);
?>

The above example will output something similar to:

object(Ds\Set)#1 (0) {
}
object(Ds\Set)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}


Determines if the set contains all values

  • « Ds\Set::__construct
  • Ds\Set::copy »
  • PHP Manual
  • Set
  • Determines if the set contains all values

Ds\Set::contains

(PECL ds >= 1.0.0)

Ds\Set::contains — Determines if the set contains all values

Description

public Ds\Set::contains ([ mixed $...values ] ) : bool

Determines if the set contains all values.

Note:

Values of type object are supported. If an object implements Ds\Hashable, equality will be determined by the object's equals function. If an object does not implement Ds\Hashable, objects must be references to the same instance to be considered equal.

Caution

All comparisons are strict (type and value).

Parameters

values

Values to check.

Return Values

FALSE if any of the provided values are not in the set, TRUE otherwise.

Examples

Example #1 Ds\Set::contains() example

<?php
$set = new \Ds\Set([1, 2, 3]);

var_dump($set->contains(1));                // true
var_dump($set->contains(1, 2));             // true
var_dump($set->contains(...[1, 2]));        // true

var_dump($set->contains("1"));              // false
var_dump($set->contains(...[1, 2, 3, 4]));  // false

var_dump($set->contains(...[]));            // true
?>

The above example will output something similar to:

bool(true)
bool(true)
bool(true)
bool(false)
bool(false)
bool(true)


Returns a shallow copy of the set

  • « Ds\Set::contains
  • Ds\Set::count »
  • PHP Manual
  • Set
  • Returns a shallow copy of the set

Ds\Set::copy

(PECL ds >= 1.0.0)

Ds\Set::copy — Returns a shallow copy of the set

Description

public Ds\Set::copy ( void ) : Ds\Set

Returns a shallow copy of the set.

Parameters

This function has no parameters.

Return Values

Returns a shallow copy of the set.

Examples

Example #1 Ds\Set::copy() example

<?php
$a = new \Ds\Set([1, 2, 3]);
$b = $a->copy();

// Updating the copy doesn't affect the original
$b->add(4);

print_r($a);
print_r($b);
?>

The above example will output something similar to:

Ds\Set Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Set Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)


Returns the number of values in the set

  • « Ds\Set::copy
  • Ds\Set::diff »
  • PHP Manual
  • Set
  • Returns the number of values in the set

Ds\Set::count

(PECL ds >= 1.0.0)

Ds\Set::count — Returns the number of values in the set

See Countable::count()


Creates a new set using values that aren't in another set

  • « Ds\Set::count
  • Ds\Set::filter »
  • PHP Manual
  • Set
  • Creates a new set using values that aren't in another set

Ds\Set::diff

(PECL ds >= 1.0.0)

Ds\Set::diff — Creates a new set using values that aren't in another set

Description

public Ds\Set::diff ( Ds\Set $set ) : Ds\Set

Creates a new set using values that aren't in another set.

A \ B = {x ∈ A | x ∉ B}

Parameters

set

Set containing the values to exclude.

Return Values

A new set containing all values that were not in the other set.

See Also

  • » Compliment on Wikipedia

Examples

Example #1 Ds\Set::diff() example

<?php
$a = new \Ds\Set([1, 2, 3]);
$b = new \Ds\Set([3, 4, 5]);

var_dump($a->diff($b));
?>

The above example will output something similar to:

object(Ds\Set)#3 (2) {
  [0]=>
  int(1)
  [1]=>
  int(2)
}


Creates a new set using a callable to determine which values to include

  • « Ds\Set::diff
  • Ds\Set::first »
  • PHP Manual
  • Set
  • Creates a new set using a callable to determine which values to include

Ds\Set::filter

(PECL ds >= 1.0.0)

Ds\Set::filter — Creates a new set using a callable to determine which values to include

Description

public Ds\Set::filter ([ callable $callback ] ) : Ds\Set

Creates a new set using a callable to determine which values to include.

Parameters

callback

callback ( mixed $value ) : bool

Optional callable which returns TRUE if the value should be included, FALSE otherwise.

If a callback is not provided, only values which are TRUE (see converting to boolean) will be included.

Return Values

A new set containing all the values for which either the callback returned TRUE, or all values that convert to TRUE if a callback was not provided.

Examples

Example #1 Ds\Set::filter() example using callback function

<?php
$set = new \Ds\Set([1, 2, 3, 4, 5]);

var_dump($set->filter(function($value) {
    return $value % 2 == 0;
}));
?>

The above example will output something similar to:

object(Ds\Set)#3 (2) {
  [0]=>
  int(2)
  [1]=>
  int(4)
}

Example #2 Ds\Set::filter() example without a callback function

<?php
$set = new \Ds\Set([0, 1, 'a', true, false]);

var_dump($set->filter());
?>

The above example will output something similar to:

object(Ds\Set)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  string(1) "a"
  [2]=>
  bool(true)
}


Returns the first value in the set

  • « Ds\Set::filter
  • Ds\Set::get »
  • PHP Manual
  • Set
  • Returns the first value in the set

Ds\Set::first

(PECL ds >= 1.0.0)

Ds\Set::first — Returns the first value in the set

Description

public Ds\Set::first ( void ) : mixed

Returns the first value in the set.

Parameters

This function has no parameters.

Return Values

The first value in the set.

Errors/Exceptions

UnderflowException if empty.

Examples

Example #1 Ds\Set::first() example

<?php
$set = new \Ds\Set([1, 2, 3]);
var_dump($set->first());
?>

The above example will output something similar to:

int(1)


Returns the value at a given index

  • « Ds\Set::first
  • Ds\Set::intersect »
  • PHP Manual
  • Set
  • Returns the value at a given index

Ds\Set::get

(PECL ds >= 1.0.0)

Ds\Set::get — Returns the value at a given index

Description

public Ds\Set::get ( int $index ) : mixed

Returns the value at a given index.

Parameters

index

The index to access, starting at 0.

Return Values

The value at the requested index.

Errors/Exceptions

OutOfRangeException if the index is not valid.

Examples

Example #1 Ds\Set::get() example

<?php
$set = new \Ds\Set(["a", "b", "c"]);

var_dump($set->get(0));
var_dump($set->get(1));
var_dump($set->get(2));
?>

The above example will output something similar to:

string(1) "a"
string(1) "b"
string(1) "c"

Example #2 Ds\Set::get() example using array syntax

<?php
$set = new \Ds\Set(["a", "b", "c"]);

var_dump($set[0]);
var_dump($set[1]);
var_dump($set[2]);
?>

The above example will output something similar to:

string(1) "a"
string(1) "b"
string(1) "c"


Creates a new set by intersecting values with another set

  • « Ds\Set::get
  • Ds\Set::isEmpty »
  • PHP Manual
  • Set
  • Creates a new set by intersecting values with another set

Ds\Set::intersect

(PECL ds >= 1.0.0)

Ds\Set::intersect — Creates a new set by intersecting values with another set

Description

public Ds\Set::intersect ( Ds\Set $set ) : Ds\Set

Creates a new set using values common to both the current instance and another set. In other words, returns a copy of the current instance with all values removed that are not in the other set.

A ∩ B = {x : x ∈ A ∧ x ∈ B}

Parameters

set

The other set.

Return Values

The intersection of the current instance and another set.

See Also

  • » Intersection on Wikipedia

Examples

Example #1 Ds\Set::intersect() example

<?php
$a = new \Ds\Set([1, 2, 3]);
$b = new \Ds\Set([3, 4, 5]);

var_dump($a->intersect($b));
?>

The above example will output something similar to:

object(Ds\Set)#3 (1) {
  [0]=>
  int(3)
}


Returns whether the set is empty

  • « Ds\Set::intersect
  • Ds\Set::join »
  • PHP Manual
  • Set
  • Returns whether the set is empty

Ds\Set::isEmpty

(PECL ds >= 1.0.0)

Ds\Set::isEmpty — Returns whether the set is empty

Description

public Ds\Set::isEmpty ( void ) : bool

Returns whether the set is empty.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the set is empty, FALSE otherwise.

Examples

Example #1 Ds\Set::isEmpty() example

<?php
$a = new \Ds\Set([1, 2, 3]);
$b = new \Ds\Set();

var_dump($a->isEmpty());
var_dump($b->isEmpty());
?>

The above example will output something similar to:

bool(false)
bool(true)


Joins all values together as a string

  • « Ds\Set::isEmpty
  • Ds\Set::jsonSerialize »
  • PHP Manual
  • Set
  • Joins all values together as a string

Ds\Set::join

(PECL ds >= 1.0.0)

Ds\Set::join — Joins all values together as a string

Description

public Ds\Set::join ([ string $glue ] ) : string

Joins all values together as a string using an optional separator between each value.

Parameters

glue

An optional string to separate each value.

Return Values

All values of the set joined together as a string.

Examples

Example #1 Ds\Set::join() example using a separator string

<?php
$set = new \Ds\Set(["a", "b", "c", 1, 2, 3]);

var_dump($set->join("|"));
?>

The above example will output something similar to:

string(11) "a|b|c|1|2|3"

Example #2 Ds\Set::join() example without a separator string

<?php
$set = new \Ds\Set(["a", "b", "c", 1, 2, 3]);

var_dump($set->join());
?>

The above example will output something similar to:

string(11) "abc123"


Returns a representation that can be converted to JSON

  • « Ds\Set::join
  • Ds\Set::last »
  • PHP Manual
  • Set
  • Returns a representation that can be converted to JSON

Ds\Set::jsonSerialize

(PECL ds >= 1.0.0)

Ds\Set::jsonSerialize — Returns a representation that can be converted to JSON

See JsonSerializable::jsonSerialize()

Note:

You should never need to call this directly.


Returns the last value in the set

  • « Ds\Set::jsonSerialize
  • Ds\Set::merge »
  • PHP Manual
  • Set
  • Returns the last value in the set

Ds\Set::last

(PECL ds >= 1.0.0)

Ds\Set::last — Returns the last value in the set

Description

public Ds\Set::last ( void ) : void

Returns the last value in the set.

Parameters

This function has no parameters.

Return Values

The last value in the set.

Errors/Exceptions

UnderflowException if empty.

Examples

Example #1 Ds\Set::last() example

<?php
$set = new \Ds\Set([1, 2, 3]);
var_dump($set->last());
?>

The above example will output something similar to:

int(3)


Returns the result of adding all given values to the set

  • « Ds\Set::last
  • Ds\Set::reduce »
  • PHP Manual
  • Set
  • Returns the result of adding all given values to the set

Ds\Set::merge

(PECL ds >= 1.0.3)

Ds\Set::merge — Returns the result of adding all given values to the set

Description

public Ds\Set::merge ( mixed $values ) : Ds\Set

Returns the result of adding all given values to the set.

Parameters

values

A traversable object or an array.

Return Values

The result of adding all given values to the set, effectively the same as adding the values to a copy, then returning that copy.

Note:

The current instance won't be affected.

Examples

Example #1 Ds\Set::merge() example

<?php
$set = new \Ds\Set([1, 2, 3]);

var_dump($set->merge([3, 4, 5]));
var_dump($set);
?>

The above example will output something similar to:

object(Ds\Set)#2 (6) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
  [4]=>
  int(5)
}
object(Ds\Set)#1 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}


Reduces the set to a single value using a callback function

  • « Ds\Set::merge
  • Ds\Set::remove »
  • PHP Manual
  • Set
  • Reduces the set to a single value using a callback function

Ds\Set::reduce

(PECL ds >= 1.0.0)

Ds\Set::reduce — Reduces the set to a single value using a callback function

Description

public Ds\Set::reduce ( callable $callback [, mixed $initial ] ) : mixed

Reduces the set to a single value using a callback function.

Parameters

callback
callback ( mixed $carry , mixed $value ) : mixed
carry

The return value of the previous callback, or initial if it's the first iteration.

value

The value of the current iteration.

initial

The initial value of the carry value. Can be NULL.

Return Values

The return value of the final callback.

Examples

Example #1 Ds\Set::reduce() with initial value example

<?php
$set = new \Ds\Set([1, 2, 3]);

$callback = function($carry, $value) {
    return $carry * $value;
};

var_dump($set->reduce($callback, 5));

// Iterations:
//
// $carry = $initial = 5
//
// $carry = $carry * 1 =  5
// $carry = $carry * 2 = 10
// $carry = $carry * 3 = 30
?>

The above example will output something similar to:

int(30)

Example #2 Ds\Set::reduce() without an initial value example

<?php
$set = new \Ds\Set([1, 2, 3]);

var_dump($set->reduce(function($carry, $value) {
    return $carry + $value + 5;
}));

// Iterations:
//
// $carry = $initial = null
//
// $carry = $carry + 1 + 5 =  6
// $carry = $carry + 2 + 5 = 13
// $carry = $carry + 3 + 5 = 21
?>

The above example will output something similar to:

int(21)


Removes all given values from the set

  • « Ds\Set::reduce
  • Ds\Set::reverse »
  • PHP Manual
  • Set
  • Removes all given values from the set

Ds\Set::remove

(PECL ds >= 1.0.0)

Ds\Set::remove — Removes all given values from the set

Description

public Ds\Set::remove ([ mixed $...values ] ) : void

Removes all given values from the set, ignoring any that are not in the set.

Parameters

values

The values to remove.

Return Values

No value is returned.

Examples

Example #1 Ds\Set::remove() example

<?php
$set = new \Ds\Set([1, 2, 3, 4, 5]);

$set->remove(1);            // Remove 1
$set->remove(1, 2);         // Can't find 1, but remove 2
$set->remove(...[3, 4]);    // Remove 3 and 4

var_dump($set);
?>

The above example will output something similar to:

object(Ds\Set)#1 (1) {
  [0]=>
  int(5)
}


Reverses the set in-place

  • « Ds\Set::remove
  • Ds\Set::reversed »
  • PHP Manual
  • Set
  • Reverses the set in-place

Ds\Set::reverse

(PECL ds >= 1.0.0)

Ds\Set::reverse — Reverses the set in-place

Description

public Ds\Set::reverse ( void ) : void

Reverses the set in-place.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 Ds\Set::reverse() example

<?php
$set = new \Ds\Set(["a", "b", "c"]);
$set->reverse();

print_r($set);
?>

The above example will output something similar to:

Ds\Set Object
(
    [0] => c
    [1] => b
    [2] => a
)


Returns a reversed copy

  • « Ds\Set::reverse
  • Ds\Set::slice »
  • PHP Manual
  • Set
  • Returns a reversed copy

Ds\Set::reversed

(PECL ds >= 1.0.0)

Ds\Set::reversed — Returns a reversed copy

Description

public Ds\Set::reversed ( void ) : Ds\Set

Returns a reversed copy of the set.

Parameters

This function has no parameters.

Return Values

A reversed copy of the set.

Note:

The current instance is not affected.

Examples

Example #1 Ds\Set::reversed() example

<?php
$set = new \Ds\Set(["a", "b", "c"]);

print_r($set->reversed());
print_r($set);
?>

The above example will output something similar to:

Ds\Set Object
(
    [0] => c
    [1] => b
    [2] => a
)
Ds\Set Object
(
    [0] => a
    [1] => b
    [2] => c
)


Returns a sub-set of a given range

  • « Ds\Set::reversed
  • Ds\Set::sort »
  • PHP Manual
  • Set
  • Returns a sub-set of a given range

Ds\Set::slice

(PECL ds >= 1.0.0)

Ds\Set::slice — Returns a sub-set of a given range

Description

public Ds\Set::slice ( int $index [, int $length ] ) : Ds\Set

Creates a sub-set of a given range.

Parameters

index

The index at which the sub-set starts.

If positive, the set will start at that index in the set. If negative, the set will start that far from the end.

length

If a length is given and is positive, the resulting set will have up to that many values in it. If the length results in an overflow, only values up to the end of the set will be included. If a length is given and is negative, the set will stop that many values from the end. If a length is not provided, the resulting set will contain all values between the index and the end of the set.

Return Values

A sub-set of the given range.

Examples

Example #1 Ds\Set::slice() example

<?php
$set = new \Ds\Set(["a", "b", "c", "d", "e"]);

// Slice from 2 onwards
print_r($set->slice(2));

// Slice from 1, for a length of 3
print_r($set->slice(1, 3));

// Slice from 1 onwards
print_r($set->slice(1));

// Slice from 2 from the end onwards
print_r($set->slice(-2));

// Slice from 1 to 1 from the end
print_r($set->slice(1, -1));
?>

The above example will output something similar to:

Ds\Set Object
(
    [0] => c
    [1] => d
    [2] => e
)
Ds\Set Object
(
    [0] => b
    [1] => c
    [2] => d
)
Ds\Set Object
(
    [0] => b
    [1] => c
    [2] => d
    [3] => e
)
Ds\Set Object
(
    [0] => d
    [1] => e
)
Ds\Set Object
(
    [0] => b
    [1] => c
    [2] => d
)


Sorts the set in-place

  • « Ds\Set::slice
  • Ds\Set::sorted »
  • PHP Manual
  • Set
  • Sorts the set in-place

Ds\Set::sort

(PECL ds >= 1.0.0)

Ds\Set::sort — Sorts the set in-place

Description

public Ds\Set::sort ([ callable $comparator ] ) : void

Sorts the set in-place, using an optional comparator function.

Parameters

comparator

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. Note that before PHP 7.0.0 this integer had to be in the range from -2147483648 to 2147483647.

callback ( mixed $a, mixed $b ) : int
Caution

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

Return Values

No value is returned.

Examples

Example #1 Ds\Set::sort() example

<?php
$set = new \Ds\Set([4, 5, 1, 3, 2]);
$set->sort();

print_r($set);
?>

The above example will output something similar to:

Ds\Set Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Example #2 Ds\Set::sort() example using a comparator

<?php
$set = new \Ds\Set([4, 5, 1, 3, 2]);

$set->sort(function($a, $b) {
    return $b <=> $a;
});

print_r($set);
?>

The above example will output something similar to:

Ds\Set Object
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)


Returns a sorted copy

  • « Ds\Set::sort
  • Ds\Set::sum »
  • PHP Manual
  • Set
  • Returns a sorted copy

Ds\Set::sorted

(PECL ds >= 1.0.0)

Ds\Set::sorted — Returns a sorted copy

Description

public Ds\Set::sorted ([ callable $comparator ] ) : Ds\Set

Returns a sorted copy, using an optional comparator function.

Parameters

comparator

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. Note that before PHP 7.0.0 this integer had to be in the range from -2147483648 to 2147483647.

callback ( mixed $a, mixed $b ) : int
Caution

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

Return Values

Returns a sorted copy of the set.

Examples

Example #1 Ds\Set::sorted() example

<?php
$set = new \Ds\Set([4, 5, 1, 3, 2]);

print_r($set->sorted());
?>

The above example will output something similar to:

Ds\Set Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Example #2 Ds\Set::sorted() example using a comparator

<?php
$set = new \Ds\Set([4, 5, 1, 3, 2]);

$sorted = $set->sorted(function($a, $b) {
    return $b <=> $a;
});

print_r($sorted);
?>

The above example will output something similar to:

Ds\Set Object
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)


Returns the sum of all values in the set

  • « Ds\Set::sorted
  • Ds\Set::toArray »
  • PHP Manual
  • Set
  • Returns the sum of all values in the set

Ds\Set::sum

(PECL ds >= 1.0.0)

Ds\Set::sum — Returns the sum of all values in the set

Description

public Ds\Set::sum ( void ) : number

Returns the sum of all values in the set.

Note:

Arrays and objects are considered equal to zero when calculating the sum.

Parameters

This function has no parameters.

Return Values

The sum of all the values in the set as either a float or int depending on the values in the set.

Examples

Example #1 Ds\Set::sum() integer example

<?php
$set = new \Ds\Set([1, 2, 3]);
var_dump($set->sum());
?>

The above example will output something similar to:

int(6)

Example #2 Ds\Set::sum() float example

<?php
$set = new \Ds\Set([1, 2.5, 3]);
var_dump($set->sum());
?>

The above example will output something similar to:

float(6.5)


Converts the set to an array

  • « Ds\Set::sum
  • Ds\Set::union »
  • PHP Manual
  • Set
  • Converts the set to an array

Ds\Set::toArray

(PECL ds >= 1.0.0)

Ds\Set::toArray — Converts the set to an array

Description

public Ds\Set::toArray ( void ) : array

Converts the set to an array.

Note:

Casting to an array is not supported yet.

Parameters

This function has no parameters.

Return Values

An array containing all the values in the same order as the set.

Examples

Example #1 Ds\Set::toArray() example

<?php
$set = new \Ds\Set([1, 2, 3]);

var_dump($set->toArray());
?>

The above example will output something similar to:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}


Creates a new set using values from the current instance and another set

  • « Ds\Set::toArray
  • Ds\Set::xor »
  • PHP Manual
  • Set
  • Creates a new set using values from the current instance and another set

Ds\Set::union

(PECL ds >= 1.0.0)

Ds\Set::union — Creates a new set using values from the current instance and another set

Description

public Ds\Set::union ( Ds\Set $set ) : Ds\Set

Creates a new set that contains the values of the current instance as well as the values of another set.

A ∪ B = {x: x ∈ A ∨ x ∈ B}

Parameters

set

The other set, to combine with the current instance.

Return Values

A new set containing all the values of the current instance as well as another set.

See Also

  • » Union on Wikipedia

Examples

Example #1 Ds\Set::union() example

<?php
$a = new \Ds\Set([1, 2, 3]);
$b = new \Ds\Set([3, 4, 5]);

var_dump($a->union($b));
?>

The above example will output something similar to:

object(Ds\Set)#3 (5) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
  [4]=>
  int(5)
}


Creates a new set using values in either the current instance or in another set, but not in both

  • « Ds\Set::union
  • Stack »
  • PHP Manual
  • Set
  • Creates a new set using values in either the current instance or in another set, but not in both

Ds\Set::xor

(PECL ds >= 1.0.0)

Ds\Set::xor — Creates a new set using values in either the current instance or in another set, but not in both

Description

public Ds\Set::xor ( Ds\Set $set ) : Ds\Set

Creates a new set containing values in the current instance as well as another set, but not in both.

A ⊖ B = {x : x ∈ (A \ B) ∪ (B \ A)}

Parameters

set

The other set.

Return Values

A new set containing values in the current instance as well as another set, but not in both.

See Also

  • » Symmetric Difference on Wikipedia

Examples

Example #1 Ds\Set::xor() example

<?php
$a = new \Ds\Set([1, 2, 3]);
$b = new \Ds\Set([3, 4, 5]);

var_dump($a->xor($b));
?>

The above example will output something similar to:

object(Ds\Set)#3 (4) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(4)
  [3]=>
  int(5)
}


The Stack class

(No version information available, might only be in Git)

Introduction

A Stack is a “last in, first out” or “LIFO” collection that only allows access to the value at the top of the structure and iterates in that order, destructively.

Uses a Ds\Vector internally.

Class synopsis

Ds\Stack implements Ds\Collection {
/* Methods */
public allocate ( int $capacity ) : void
public capacity ( void ) : int
public clear ( void ) : void
public copy ( void ) : Ds\Stack
public isEmpty ( void ) : bool
public peek ( void ) : mixed
public pop ( void ) : mixed
public push ([ mixed $...values ] ) : void
public toArray ( void ) : array
}

Table of Contents

  • Ds\Stack::allocate — Allocates enough memory for a required capacity
  • Ds\Stack::capacity — Returns the current capacity
  • Ds\Stack::clear — Removes all values
  • Ds\Stack::__construct — Creates a new instance
  • Ds\Stack::copy — Returns a shallow copy of the stack
  • Ds\Stack::count — Returns the number of values in the stack
  • Ds\Stack::isEmpty — Returns whether the stack is empty
  • Ds\Stack::jsonSerialize — Returns a representation that can be converted to JSON
  • Ds\Stack::peek — Returns the value at the top of the stack
  • Ds\Stack::pop — Removes and returns the value at the top of the stack
  • Ds\Stack::push — Pushes values onto the stack
  • Ds\Stack::toArray — Converts the stack to an array


Allocates enough memory for a required capacity

  • « Stack
  • Ds\Stack::capacity »
  • PHP Manual
  • Stack
  • Allocates enough memory for a required capacity

Ds\Stack::allocate

(PECL ds >= 1.0.0)

Ds\Stack::allocate — Allocates enough memory for a required capacity

Description

public Ds\Stack::allocate ( int $capacity ) : void

Ensures that enough memory is allocated for a required capacity. This removes the need to reallocate the internal as values are added.

Parameters

capacity

The number of values for which capacity should be allocated.

Note:

Capacity will stay the same if this value is less than or equal to the current capacity.

Return Values

No value is returned.


Returns the current capacity

  • « Ds\Stack::allocate
  • Ds\Stack::clear »
  • PHP Manual
  • Stack
  • Returns the current capacity

Ds\Stack::capacity

(PECL ds >= 1.0.0)

Ds\Stack::capacity — Returns the current capacity

Description

public Ds\Stack::capacity ( void ) : int

Returns the current capacity.

Parameters

This function has no parameters.

Return Values

The current capacity.


Removes all values

  • « Ds\Stack::capacity
  • Ds\Stack::__construct »
  • PHP Manual
  • Stack
  • Removes all values

Ds\Stack::clear

(PECL ds >= 1.0.0)

Ds\Stack::clear — Removes all values

Description

public Ds\Stack::clear ( void ) : void

Removes all values from the stack.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 Ds\Stack::clear() example

<?php
$stack = new \Ds\Stack([1, 2, 3]);
print_r($stack);

$stack->clear();
print_r($stack);
?>

The above example will output something similar to:

Ds\Stack Object
(
    [0] => 3
    [1] => 2
    [2] => 1
)
Ds\Stack Object
(
)


Creates a new instance

  • « Ds\Stack::clear
  • Ds\Stack::copy »
  • PHP Manual
  • Stack
  • Creates a new instance

Ds\Stack::__construct

(PECL ds >= 1.0.0)

Ds\Stack::__construct — Creates a new instance

Description

public Ds\Stack::__construct ([ mixed $values ] )

Creates a new instance, using either a traversable object or an array for the initial values.

Parameters

values

A traversable object or an array to use for the initial values.

Examples

Example #1 Ds\Stack::__construct() example

<?php
$stack = new \Ds\Stack();
print_r($stack);

$stack = new \Ds\Stack([1, 2, 3]);
print_r($stack);
?>

The above example will output something similar to:

Ds\Stack Object
(
)
Ds\Stack Object
(
    [0] => 3
    [1] => 2
    [2] => 1
)


Returns a shallow copy of the stack

  • « Ds\Stack::__construct
  • Ds\Stack::count »
  • PHP Manual
  • Stack
  • Returns a shallow copy of the stack

Ds\Stack::copy

(PECL ds >= 1.0.0)

Ds\Stack::copy — Returns a shallow copy of the stack

Description

public Ds\Stack::copy ( void ) : Ds\Stack

Returns a shallow copy of the stack.

Parameters

This function has no parameters.

Return Values

Returns a shallow copy of the stack.

Examples

Example #1 Ds\Stack::copy() example

<?php
$a = new \Ds\Stack([1, 2, 3]);
$b = $a->copy();

// Updating the copy doesn't affect the original
$b->push(4);

print_r($a);
print_r($b);
?>

The above example will output something similar to:

Ds\Stack Object
(
    [0] => 3
    [1] => 2
    [2] => 1
)
Ds\Stack Object
(
    [0] => 4
    [1] => 3
    [2] => 2
    [3] => 1
)


Returns the number of values in the stack

  • « Ds\Stack::copy
  • Ds\Stack::isEmpty »
  • PHP Manual
  • Stack
  • Returns the number of values in the stack

Ds\Stack::count

(PECL ds >= 1.0.0)

Ds\Stack::count — Returns the number of values in the stack

See Countable::count()


Returns whether the stack is empty

  • « Ds\Stack::count
  • Ds\Stack::jsonSerialize »
  • PHP Manual
  • Stack
  • Returns whether the stack is empty

Ds\Stack::isEmpty

(PECL ds >= 1.0.0)

Ds\Stack::isEmpty — Returns whether the stack is empty

Description

public Ds\Stack::isEmpty ( void ) : bool

Returns whether the stack is empty.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the stack is empty, FALSE otherwise.

Examples

Example #1 Ds\Stack::isEmpty() example

<?php
$a = new \Ds\Stack([1, 2, 3]);
$b = new \Ds\Stack();

var_dump($a->isEmpty());
var_dump($b->isEmpty());
?>

The above example will output something similar to:

bool(false)
bool(true)


Returns a representation that can be converted to JSON

  • « Ds\Stack::isEmpty
  • Ds\Stack::peek »
  • PHP Manual
  • Stack
  • Returns a representation that can be converted to JSON

Ds\Stack::jsonSerialize

(PECL ds >= 1.0.0)

Ds\Stack::jsonSerialize — Returns a representation that can be converted to JSON

See JsonSerializable::jsonSerialize()

Note:

You should never need to call this directly.


Returns the value at the top of the stack

  • « Ds\Stack::jsonSerialize
  • Ds\Stack::pop »
  • PHP Manual
  • Stack
  • Returns the value at the top of the stack

Ds\Stack::peek

(PECL ds >= 1.0.0)

Ds\Stack::peek — Returns the value at the top of the stack

Description

public Ds\Stack::peek ( void ) : mixed

Returns the value at the top of the stack, but does not remove it.

Parameters

This function has no parameters.

Return Values

The value at the top of the stack.

Errors/Exceptions

UnderflowException if empty.

Examples

Example #1 Ds\Stack::peek() example

<?php
$stack = new \Ds\Stack();

$stack->push("a");
$stack->push("b");
$stack->push("c");

var_dump($stack->peek());
?>

The above example will output something similar to:

string(1) "c"


Removes and returns the value at the top of the stack

  • « Ds\Stack::peek
  • Ds\Stack::push »
  • PHP Manual
  • Stack
  • Removes and returns the value at the top of the stack

Ds\Stack::pop

(PECL ds >= 1.0.0)

Ds\Stack::pop — Removes and returns the value at the top of the stack

Description

public Ds\Stack::pop ( void ) : mixed

Removes and returns the value at the top of the stack.

Parameters

This function has no parameters.

Return Values

The removed value which was at the top of the stack.

Errors/Exceptions

UnderflowException if empty.

Examples

Example #1 Ds\Stack::pop() example

<?php
$stack = new \Ds\Stack();

$stack->push("a");
$stack->push("b");
$stack->push("c");

var_dump($stack->pop());
var_dump($stack->pop());
var_dump($stack->pop());
?>

The above example will output something similar to:

string(1) "c"
string(1) "b"
string(1) "a"


Pushes values onto the stack

  • « Ds\Stack::pop
  • Ds\Stack::toArray »
  • PHP Manual
  • Stack
  • Pushes values onto the stack

Ds\Stack::push

(PECL ds >= 1.0.0)

Ds\Stack::push — Pushes values onto the stack

Description

public Ds\Stack::push ([ mixed $...values ] ) : void

Pushes values onto the stack.

Parameters

values

The values to push onto the stack.

Return Values

No value is returned.

Examples

Example #1 Ds\Stack::push() example

<?php
$stack = new \Ds\Stack();

$stack->push("a");
$stack->push("b");
$stack->push("c", "d");
$stack->push(...["e", "f"]);

print_r($stack);
?>

The above example will output something similar to:

Ds\Stack Object
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
    [5] => f
)


Converts the stack to an array

  • « Ds\Stack::push
  • Queue »
  • PHP Manual
  • Stack
  • Converts the stack to an array

Ds\Stack::toArray

(PECL ds >= 1.0.0)

Ds\Stack::toArray — Converts the stack to an array

Description

public Ds\Stack::toArray ( void ) : array

Converts the stack to an array.

Note:

Casting to an array is not supported yet.

Parameters

This function has no parameters.

Return Values

An array containing all the values in the same order as the stack.

Examples

Example #1 Ds\Stack::toArray() example

<?php
$stack = new \Ds\Stack([1, 2, 3]);

var_dump($stack->toArray());
?>

The above example will output something similar to:

array(3) {
  [0]=>
  int(3)
  [1]=>
  int(2)
  [2]=>
  int(1)
}


The Queue class

(No version information available, might only be in Git)

Introduction

A Queue is a “first in, first out” or “FIFO” collection that only allows access to the value at the front of the queue and iterates in that order, destructively.

Class synopsis

Ds\Queue implements Ds\Collection {
/* Constants */
const int MIN_CAPACITY = 8 ;
/* Methods */
public allocate ( int $capacity ) : void
public capacity ( void ) : int
public clear ( void ) : void
public copy ( void ) : Ds\Queue
public isEmpty ( void ) : bool
public peek ( void ) : mixed
public pop ( void ) : mixed
public push ([ mixed $...values ] ) : void
public toArray ( void ) : array
}

Predefined Constants

Ds\Queue::MIN_CAPACITY

Table of Contents

  • Ds\Queue::allocate — Allocates enough memory for a required capacity
  • Ds\Queue::capacity — Returns the current capacity
  • Ds\Queue::clear — Removes all values
  • Ds\Queue::__construct — Creates a new instance
  • Ds\Queue::copy — Returns a shallow copy of the queue
  • Ds\Queue::count — Returns the number of values in the queue
  • Ds\Queue::isEmpty — Returns whether the queue is empty
  • Ds\Queue::jsonSerialize — Returns a representation that can be converted to JSON
  • Ds\Queue::peek — Returns the value at the front of the queue
  • Ds\Queue::pop — Removes and returns the value at the front of the queue
  • Ds\Queue::push — Pushes values into the queue
  • Ds\Queue::toArray — Converts the queue to an array


Allocates enough memory for a required capacity

  • « Queue
  • Ds\Queue::capacity »
  • PHP Manual
  • Queue
  • Allocates enough memory for a required capacity

Ds\Queue::allocate

(PECL ds >= 1.0.0)

Ds\Queue::allocate — Allocates enough memory for a required capacity

Description

public Ds\Queue::allocate ( int $capacity ) : void

Ensures that enough memory is allocated for a required capacity. This removes the need to reallocate the internal as values are added.

Note:

Capacity will always be rounded up to the nearest power of 2.

Parameters

capacity

The number of values for which capacity should be allocated.

Note:

Capacity will stay the same if this value is less than or equal to the current capacity.

Note:

Capacity will always be rounded up to the nearest power of 2.

Return Values

No value is returned.

Examples

Example #1 Ds\Queue::allocate() example

<?php
$queue = new \Ds\Queue();
var_dump($queue->capacity());

$queue->allocate(100);
var_dump($queue->capacity());
?>

The above example will output something similar to:

int(8)
int(128)


Returns the current capacity

  • « Ds\Queue::allocate
  • Ds\Queue::clear »
  • PHP Manual
  • Queue
  • Returns the current capacity

Ds\Queue::capacity

(PECL ds >= 1.0.0)

Ds\Queue::capacity — Returns the current capacity

Description

public Ds\Queue::capacity ( void ) : int

Returns the current capacity.

Parameters

This function has no parameters.

Return Values

The current capacity.

Examples

Example #1 Ds\Queue::capacity() example

<?php
$queue = new \Ds\Queue();
var_dump($queue->capacity());

$queue->push(...range(1, 50));
var_dump($queue->capacity());
?>

The above example will output something similar to:

int(8)
int(64)


Removes all values

  • « Ds\Queue::capacity
  • Ds\Queue::__construct »
  • PHP Manual
  • Queue
  • Removes all values

Ds\Queue::clear

(PECL ds >= 1.0.0)

Ds\Queue::clear — Removes all values

Description

public Ds\Queue::clear ( void ) : void

Removes all values from the queue.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 Ds\Queue::clear() example

<?php
$queue = new \Ds\Queue([1, 2, 3]);
print_r($queue);

$queue->clear();
print_r($queue);
?>

The above example will output something similar to:

Ds\Queue Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Queue Object
(
)


Creates a new instance

  • « Ds\Queue::clear
  • Ds\Queue::copy »
  • PHP Manual
  • Queue
  • Creates a new instance

Ds\Queue::__construct

(PECL ds >= 1.0.0)

Ds\Queue::__construct — Creates a new instance

Description

public Ds\Queue::__construct ([ mixed $values ] )

Creates a new instance, using either a traversable object or an array for the initial values.

Parameters

values

A traversable object or an array to use for the initial values.

Examples

Example #1 Ds\Queue::__construct() example

<?php
$queue = new \Ds\Queue();
var_dump($queue);

$queue = new \Ds\Queue([1, 2, 3]);
var_dump($queue);
?>

The above example will output something similar to:

object(Ds\Queue)#2 (0) {
}
object(Ds\Queue)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}


Returns a shallow copy of the queue

  • « Ds\Queue::__construct
  • Ds\Queue::count »
  • PHP Manual
  • Queue
  • Returns a shallow copy of the queue

Ds\Queue::copy

(PECL ds >= 1.0.0)

Ds\Queue::copy — Returns a shallow copy of the queue

Description

public Ds\Queue::copy ( void ) : Ds\Queue

Returns a shallow copy of the queue.

Parameters

This function has no parameters.

Return Values

Returns a shallow copy of the queue.

Examples

Example #1 Ds\Queue::copy() example

<?php
$a = new \Ds\Queue([1, 2, 3]);
$b = $a->copy();

// Updating the copy doesn't affect the original
$b->push(4);

print_r($a);
print_r($b);
?>

The above example will output something similar to:

Ds\Queue Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Queue Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)


Returns the number of values in the queue

  • « Ds\Queue::copy
  • Ds\Queue::isEmpty »
  • PHP Manual
  • Queue
  • Returns the number of values in the queue

Ds\Queue::count

(PECL ds >= 1.0.0)

Ds\Queue::count — Returns the number of values in the queue

See Countable::count()


Returns whether the queue is empty

  • « Ds\Queue::count
  • Ds\Queue::jsonSerialize »
  • PHP Manual
  • Queue
  • Returns whether the queue is empty

Ds\Queue::isEmpty

(PECL ds >= 1.0.0)

Ds\Queue::isEmpty — Returns whether the queue is empty

Description

public Ds\Queue::isEmpty ( void ) : bool

Returns whether the queue is empty.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the queue is empty, FALSE otherwise.

Examples

Example #1 Ds\Queue::isEmpty() example

<?php
$a = new \Ds\Queue([1, 2, 3]);
$b = new \Ds\Queue();

var_dump($a->isEmpty());
var_dump($b->isEmpty());
?>

The above example will output something similar to:

bool(false)
bool(true)


Returns a representation that can be converted to JSON

  • « Ds\Queue::isEmpty
  • Ds\Queue::peek »
  • PHP Manual
  • Queue
  • Returns a representation that can be converted to JSON

Ds\Queue::jsonSerialize

(PECL ds >= 1.0.0)

Ds\Queue::jsonSerialize — Returns a representation that can be converted to JSON

See JsonSerializable::jsonSerialize()

Note:

You should never need to call this directly.


Returns the value at the front of the queue

  • « Ds\Queue::jsonSerialize
  • Ds\Queue::pop »
  • PHP Manual
  • Queue
  • Returns the value at the front of the queue

Ds\Queue::peek

(PECL ds >= 1.0.0)

Ds\Queue::peek — Returns the value at the front of the queue

Description

public Ds\Queue::peek ( void ) : mixed

Returns the value at the front of the queue, but does not remove it.

Parameters

This function has no parameters.

Return Values

The value at the front of the queue.

Errors/Exceptions

UnderflowException if empty.

Examples

Example #1 Ds\Queue::peek() example

<?php
$queue = new \Ds\Queue();

$queue->push("a");
$queue->push("b");
$queue->push("c");

var_dump($queue->peek());
?>

The above example will output something similar to:

string(1) "a"


Removes and returns the value at the front of the queue

  • « Ds\Queue::peek
  • Ds\Queue::push »
  • PHP Manual
  • Queue
  • Removes and returns the value at the front of the queue

Ds\Queue::pop

(PECL ds >= 1.0.0)

Ds\Queue::pop — Removes and returns the value at the front of the queue

Description

public Ds\Queue::pop ( void ) : mixed

Removes and returns the value at the front of the queue.

Parameters

This function has no parameters.

Return Values

The removed value which was at the front of the queue.

Errors/Exceptions

UnderflowException if empty.

Examples

Example #1 Ds\Queue::pop() example

<?php
$queue = new \Ds\Queue();

$queue->push("a");
$queue->push("b");
$queue->push("c");

var_dump($queue->pop());
var_dump($queue->pop());
var_dump($queue->pop());
?>

The above example will output something similar to:

string(1) "a"
string(1) "b"
string(1) "c"


Pushes values into the queue

  • « Ds\Queue::pop
  • Ds\Queue::toArray »
  • PHP Manual
  • Queue
  • Pushes values into the queue

Ds\Queue::push

(PECL ds >= 1.0.0)

Ds\Queue::push — Pushes values into the queue

Description

public Ds\Queue::push ([ mixed $...values ] ) : void

Pushes values into the queue.

Parameters

values

The values to push into the queue.

Return Values

No value is returned.

Examples

Example #1 Ds\Queue::push() example

<?php
$queue = new \Ds\Queue();

$queue->push("a");
$queue->push("b");
$queue->push("c", "d");
$queue->push(...["e", "f"]);

print_r($queue);
?>

The above example will output something similar to:

Ds\Queue Object
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
    [5] => f
)


Converts the queue to an array

  • « Ds\Queue::push
  • PriorityQueue »
  • PHP Manual
  • Queue
  • Converts the queue to an array

Ds\Queue::toArray

(PECL ds >= 1.0.0)

Ds\Queue::toArray — Converts the queue to an array

Description

public Ds\Queue::toArray ( void ) : array

Converts the queue to an array.

Note:

Casting to an array is not supported yet.

Note:

This method is not destructive.

Parameters

This function has no parameters.

Return Values

An array containing all the values in the same order as the queue.

Examples

Example #1 Ds\Queue::toArray() example

<?php
$queue = new \Ds\Queue([1, 2, 3]);

var_dump($queue->toArray());
?>

The above example will output something similar to:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}


The PriorityQueue class

(No version information available, might only be in Git)

Introduction

A PriorityQueue is very similar to a Queue. Values are pushed into the queue with an assigned priority, and the value with the highest priority will always be at the front of the queue.

Implemented using a max heap.

Note:

"First in, first out" ordering is preserved for values with the same priority.

Note:

Iterating over a PriorityQueue is destructive, equivalent to successive pop operations until the queue is empty.

Class synopsis

Ds\PriorityQueue implements Ds\Collection {
/* Constants */
const int MIN_CAPACITY = 8 ;
/* Methods */
public allocate ( int $capacity ) : void
public capacity ( void ) : int
public clear ( void ) : void
public copy ( void ) : Ds\PriorityQueue
public isEmpty ( void ) : bool
public peek ( void ) : mixed
public pop ( void ) : mixed
public push ( mixed $value , int $priority ) : void
public toArray ( void ) : array
}

Predefined Constants

Ds\PriorityQueue::MIN_CAPACITY

Table of Contents

  • Ds\PriorityQueue::allocate — Allocates enough memory for a required capacity
  • Ds\PriorityQueue::capacity — Returns the current capacity
  • Ds\PriorityQueue::clear — Removes all values
  • Ds\PriorityQueue::__construct — Creates a new instance
  • Ds\PriorityQueue::copy — Returns a shallow copy of the queue
  • Ds\PriorityQueue::count — Returns the number of values in the queue
  • Ds\PriorityQueue::isEmpty — Returns whether the queue is empty
  • Ds\PriorityQueue::jsonSerialize — Returns a representation that can be converted to JSON
  • Ds\PriorityQueue::peek — Returns the value at the front of the queue
  • Ds\PriorityQueue::pop — Removes and returns the value with the highest priority
  • Ds\PriorityQueue::push — Pushes values into the queue
  • Ds\PriorityQueue::toArray — Converts the queue to an array


Allocates enough memory for a required capacity

  • « PriorityQueue
  • Ds\PriorityQueue::capacity »
  • PHP Manual
  • PriorityQueue
  • Allocates enough memory for a required capacity

Ds\PriorityQueue::allocate

(PECL ds >= 1.0.0)

Ds\PriorityQueue::allocate — Allocates enough memory for a required capacity

Description

public Ds\PriorityQueue::allocate ( int $capacity ) : void

Ensures that enough memory is allocated for a required capacity. This removes the need to reallocate the internal as values are added.

Parameters

capacity

The number of values for which capacity should be allocated.

Note:

Capacity will stay the same if this value is less than or equal to the current capacity.

Note:

Capacity will always be rounded up to the nearest power of 2.

Return Values

No value is returned.

Examples

Example #1 Ds\PriorityQueue::allocate() example

<?php
$queue = new \Ds\PriorityQueue();
var_dump($queue->capacity());

$queue->allocate(100);
var_dump($queue->capacity());
?>

The above example will output something similar to:

int(8)
int(128)


Returns the current capacity

  • « Ds\PriorityQueue::allocate
  • Ds\PriorityQueue::clear »
  • PHP Manual
  • PriorityQueue
  • Returns the current capacity

Ds\PriorityQueue::capacity

(PECL ds >= 1.0.0)

Ds\PriorityQueue::capacity — Returns the current capacity

Description

public Ds\PriorityQueue::capacity ( void ) : int

Returns the current capacity.

Parameters

This function has no parameters.

Return Values

The current capacity.

Examples

Example #1 Ds\PriorityQueue::capacity() example

<?php
$queue = new \Ds\PriorityQueue();
var_dump($queue->capacity());
?>

The above example will output something similar to:

int(8)


Removes all values

  • « Ds\PriorityQueue::capacity
  • Ds\PriorityQueue::__construct »
  • PHP Manual
  • PriorityQueue
  • Removes all values

Ds\PriorityQueue::clear

(PECL ds >= 1.0.0)

Ds\PriorityQueue::clear — Removes all values

Description

public Ds\PriorityQueue::clear ( void ) : void

Removes all values from the queue.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 Ds\PriorityQueue::clear() example

<?php
$queue = new \Ds\PriorityQueue();

$queue->push("a",  5);
$queue->push("b", 15);
$queue->push("c", 10);

$queue->clear();
print_r($queue);
?>

The above example will output something similar to:

Ds\PriorityQueue Object
(
)


Creates a new instance

  • « Ds\PriorityQueue::clear
  • Ds\PriorityQueue::copy »
  • PHP Manual
  • PriorityQueue
  • Creates a new instance

Ds\PriorityQueue::__construct

(PECL ds >= 1.0.0)

Ds\PriorityQueue::__construct — Creates a new instance

Description

public Ds\PriorityQueue::__construct ( void )

Creates a new instance.

Examples

Example #1 Ds\PriorityQueue::__construct() example

<?php
$queue = new \Ds\PriorityQueue();
var_dump($queue);
?>

The above example will output something similar to:

object(Ds\PriorityQueue)#1 (0) {
}


Returns a shallow copy of the queue

  • « Ds\PriorityQueue::__construct
  • Ds\PriorityQueue::count »
  • PHP Manual
  • PriorityQueue
  • Returns a shallow copy of the queue

Ds\PriorityQueue::copy

(PECL ds >= 1.0.0)

Ds\PriorityQueue::copy — Returns a shallow copy of the queue

Description

public Ds\PriorityQueue::copy ( void ) : Ds\PriorityQueue

Returns a shallow copy of the queue.

Parameters

This function has no parameters.

Return Values

Returns a shallow copy of the queue.

Examples

Example #1 Ds\PriorityQueue::copy() example

<?php
$queue = new \Ds\PriorityQueue();

$queue->push("a",  5);
$queue->push("b", 15);
$queue->push("c", 10);

print_r($queue->copy());
?>

The above example will output something similar to:

Ds\PriorityQueue Object
(
    [0] => b
    [1] => c
    [2] => a
)


Returns the number of values in the queue

  • « Ds\PriorityQueue::copy
  • Ds\PriorityQueue::isEmpty »
  • PHP Manual
  • PriorityQueue
  • Returns the number of values in the queue

Ds\PriorityQueue::count

(PECL ds >= 1.0.0)

Ds\PriorityQueue::count — Returns the number of values in the queue

See Countable::count()


Returns whether the queue is empty

  • « Ds\PriorityQueue::count
  • Ds\PriorityQueue::jsonSerialize »
  • PHP Manual
  • PriorityQueue
  • Returns whether the queue is empty

Ds\PriorityQueue::isEmpty

(PECL ds >= 1.0.0)

Ds\PriorityQueue::isEmpty — Returns whether the queue is empty

Description

public Ds\PriorityQueue::isEmpty ( void ) : bool

Returns whether the queue is empty.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the queue is empty, FALSE otherwise.

Examples

Example #1 Ds\PriorityQueue::isEmpty() example

<?php
$a = new \Ds\PriorityQueue();
$b = new \Ds\PriorityQueue();

$a->push("a",  5);
$a->push("b", 15);
$a->push("c", 10);

var_dump($a->isEmpty());
var_dump($b->isEmpty());
?>

The above example will output something similar to:

bool(false)
bool(true)


Returns a representation that can be converted to JSON

  • « Ds\PriorityQueue::isEmpty
  • Ds\PriorityQueue::peek »
  • PHP Manual
  • PriorityQueue
  • Returns a representation that can be converted to JSON

Ds\PriorityQueue::jsonSerialize

(PECL ds >= 1.0.0)

Ds\PriorityQueue::jsonSerialize — Returns a representation that can be converted to JSON

See JsonSerializable::jsonSerialize()

Note:

You should never need to call this directly.


Returns the value at the front of the queue

  • « Ds\PriorityQueue::jsonSerialize
  • Ds\PriorityQueue::pop »
  • PHP Manual
  • PriorityQueue
  • Returns the value at the front of the queue

Ds\PriorityQueue::peek

(PECL ds >= 1.0.0)

Ds\PriorityQueue::peek — Returns the value at the front of the queue

Description

public Ds\PriorityQueue::peek ( void ) : mixed

Returns the value at the front of the queue, but does not remove it.

Parameters

This function has no parameters.

Return Values

The value at the front of the queue.

Errors/Exceptions

UnderflowException if empty.

Examples

Example #1 Ds\PriorityQueue::peek() example

<?php
$queue = new \Ds\PriorityQueue();

$queue->push("a",  5);
$queue->push("b", 15);
$queue->push("c", 10);

var_dump($queue->peek());
?>

The above example will output something similar to:

string(1) "b"


Removes and returns the value with the highest priority

  • « Ds\PriorityQueue::peek
  • Ds\PriorityQueue::push »
  • PHP Manual
  • PriorityQueue
  • Removes and returns the value with the highest priority

Ds\PriorityQueue::pop

(PECL ds >= 1.0.0)

Ds\PriorityQueue::pop — Removes and returns the value with the highest priority

Description

public Ds\PriorityQueue::pop ( void ) : mixed

Removes and returns the value at the front of the queue, ie. the value with the highest priority.

Note:

Values with equal priority fall back to FIFO (first in first out).

Parameters

This function has no parameters.

Return Values

The removed value which was at the front of the queue.

Errors/Exceptions

UnderflowException if empty.

Examples

Example #1 Ds\PriorityQueue::pop() example

<?php
$queue = new \Ds\PriorityQueue();

$queue->push("a",  5);
$queue->push("b", 15);
$queue->push("c", 10);

print_r($queue->pop());
print_r($queue->pop());
print_r($queue->pop());
?>

The above example will output something similar to:

string(1) "a"
string(1) "b"
string(1) "c"


Pushes values into the queue

  • « Ds\PriorityQueue::pop
  • Ds\PriorityQueue::toArray »
  • PHP Manual
  • PriorityQueue
  • Pushes values into the queue

Ds\PriorityQueue::push

(PECL ds >= 1.0.0)

Ds\PriorityQueue::push — Pushes values into the queue

Description

public Ds\PriorityQueue::push ( mixed $value , int $priority ) : void

Pushes a value with a given priority into the queue.

Parameters

value

The value to push into the queue.

priority

The priority associated with the value.

Return Values

No value is returned.

Examples

Example #1 Ds\PriorityQueue::push() example

<?php
$queue = new \Ds\PriorityQueue();

$queue->push("a",  5);
$queue->push("b", 15);
$queue->push("c", 10);

print_r($queue->pop());
print_r($queue->pop());
print_r($queue->pop());
?>

The above example will output something similar to:

string(1) "b"
string(1) "c"
string(1) "a"


Converts the queue to an array

  • « Ds\PriorityQueue::push
  • Other Services »
  • PHP Manual
  • PriorityQueue
  • Converts the queue to an array

Ds\PriorityQueue::toArray

(PECL ds >= 1.0.0)

Ds\PriorityQueue::toArray — Converts the queue to an array

Description

public Ds\PriorityQueue::toArray ( void ) : array

Converts the queue to an array.

Note:

This method is not destructive.

Note:

Casting to an array is not supported yet.

Parameters

This function has no parameters.

Return Values

An array containing all the values in the same order as the queue.

Examples

Example #1 Ds\PriorityQueue::toArray() example

<?php
$queue = new \Ds\PriorityQueue();

$queue->push("a",  5);
$queue->push("b", 15);
$queue->push("c", 10);

var_dump($queue->toArray());
?>

The above example will output something similar to:

array(3) {
  [0]=>
  string(1) "b"
  [1]=>
  string(1) "c"
  [2]=>
  string(1) "a"
}


Other Services

  • chdb — Constant hash database
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • chdb — The chdb class
    • chdb Functions
  • cURL — Client URL Library
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • cURL Functions
    • CURLFile — The CURLFile class
  • Event
    • Introduction
    • Installing/Configuring
    • Examples
    • Event flags
    • About event persistence
    • Event callbacks
    • Constructing signal events
    • Event — The Event class
    • EventBase — The EventBase class
    • EventBuffer — The EventBuffer class
    • EventBufferEvent — The EventBufferEvent class
    • About buffer event callbacks
    • EventConfig — The EventConfig class
    • EventDnsBase — The EventDnsBase class
    • EventHttp — The EventHttp class
    • EventHttpConnection — The EventHttpConnection class
    • EventHttpRequest — The EventHttpRequest class
    • EventListener — The EventListener class
    • EventSslContext — The EventSslContext class
    • EventUtil — The EventUtil class
  • FAM — File Alteration Monitor
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • FAM Functions
  • FTP
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • FTP Functions
  • Gearman
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • GearmanClient — The GearmanClient class
    • GearmanJob — The GearmanJob class
    • GearmanTask — The GearmanTask class
    • GearmanWorker — The GearmanWorker class
    • GearmanException — The GearmanException class
  • Gopher — Net Gopher
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Gopher Functions
  • Gupnp
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Gupnp Functions
  • Hyperwave API
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Integration with Apache
    • Hyperwave API Functions
  • LDAP — Lightweight Directory Access Protocol
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Using the PHP LDAP calls
    • LDAP controls
    • Examples
    • LDAP Functions
  • Memcache
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Memcache — The Memcache class
    • Memcache Functions
  • Memcached
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Expiration Times
    • Callbacks
    • Sessions support
    • Memcached — The Memcached class
    • MemcachedException — The MemcachedException class
  • mqseries
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • mqseries Functions
  • Network
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Network Functions
  • RRD — RRDtool
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • RRD Functions
    • RRDCreator — The RRDCreator class
    • RRDGraph — The RRDGraph class
    • RRDUpdater — The RRDUpdater class
  • SAM — Simple Asynchronous Messaging
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • SAM Functions
  • ScoutAPM
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Scoutapm Functions
  • SNMP
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • SNMP Functions
    • SNMP — The SNMP class
    • SNMPException — The SNMPException class
  • Sockets
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Socket Errors
    • Socket Functions
  • SSH2 — Secure Shell2
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • SSH2 Functions
  • Stomp — Stomp Client
    • Introduction
    • Installing/Configuring
    • Examples
    • Stomp Functions
    • Stomp — The Stomp class
    • StompFrame — The StompFrame class
    • StompException — The StompException class
  • SVM — Support Vector Machine
    • Introduction
    • Installing/Configuring
    • Examples
    • SVM — The SVM class
    • SVMModel — The SVMModel class
  • SVN — Subversion
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • SVN Functions
  • TCP — TCP Wrappers
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • TCP Functions
  • Varnish
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • VarnishAdmin — The VarnishAdmin class
    • VarnishStat — The VarnishStat class
    • VarnishLog — The VarnishLog class
  • YAZ
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • YAZ Functions
  • YP/NIS
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • YP/NIS Functions
  • 0MQ messaging — ZMQ
    • Introduction
    • Installing/Configuring
    • ZMQ — The ZMQ class
    • ZMQContext — The ZMQContext class
    • ZMQSocket — The ZMQSocket class
    • ZMQPoll — The ZMQPoll class
    • ZMQDevice — The ZMQDevice class
  • ZooKeeper
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • ZooKeeper Functions
    • Zookeeper — The Zookeeper class
    • ZookeeperConfig — The ZookeeperConfig class
    • ZookeeperException — The ZookeeperException class
    • ZookeeperAuthenticationException — The ZookeeperAuthenticationException class
    • ZookeeperConnectionException — The ZookeeperConnectionException class
    • ZookeeperMarshallingException — The ZookeeperMarshallingException class
    • ZookeeperNoNodeException — The ZookeeperNoNodeException class
    • ZookeeperOperationTimeoutException — The ZookeeperOperationTimeoutException class
    • ZookeeperSessionException — The ZookeeperSessionException class


Constant hash database

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • chdb — The chdb class
    • chdb::__construct — Creates a chdb instance
    • chdb::get — Gets the value associated with a key
  • chdb Functions
    • chdb_create — Creates a chdb file


Introduction

CHDB (constant hash database) is a fast key-value database for constant data, realized by using a memory-mapped file and thus providing the following functionalities:

  • Extremely fast initial load, regardless of the size of the database.

  • Only the pages of the file which are actually used are loaded from the disk.

  • Once a page is loaded it is shared across multiple processes.

  • Loaded pages are cached across multiple requests and even process recycling.

A typical use of CHDB is as a faster alternative to defining many PHP constants.

CHDB is internally implemented as a hash-table using a » perfect hashing function, thus guaranteeing worst case O(1) lookup time.


Requirements

This module uses » cmph (version 0.9) for providing the » perfect hashing function.

cmph 0.9 is required to install this module.


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/chdb

» cmph (version 0.9) is required for installing this extension. If cmph is installed in a non-standard directory, use the --with-libcmph-dir=DIR switch, where DIR is the cmph install prefix.


  • « Resource Types
  • Examples »
  • PHP Manual
  • chdb
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


Examples

Example #1 Creating a chdb file

<?php

$data = array(
    'key1' => 'value1',
    'key2' => 'value2',
    // ...
);
chdb_create('data.chdb', $data);

?>

The above example will generate a chdb file named data.chdb and containing the key-value pairs defined in $data.

Example #2 Loading and looking up a chdb file

<?php

$chdb = new chdb('data.chdb');
$value1 = $chdb->get('key1');
$value2 = $chdb->get('key2');

echo $value1, PHP_EOL;
echo $value2, PHP_EOL;

?>

The above example will output something similar to:

value1
value2


The chdb class

(PECL chdb >= 0.1.0)

Introduction

Represents a loaded chdb file.

Class synopsis

chdb {
/* Methods */
public __construct ( string $pathname )
public get ( string $key ) : string
}

Table of Contents

  • chdb::__construct — Creates a chdb instance
  • chdb::get — Gets the value associated with a key


Creates a chdb instance

  • « chdb
  • chdb::get »
  • PHP Manual
  • chdb
  • Creates a chdb instance

chdb::__construct

(PECL chdb >= 0.1.0)

chdb::__construct — Creates a chdb instance

Description

public chdb::__construct ( string $pathname )

Loads a chdb file, by mapping it into memory.

Note:

While some validity checks are performed on the specified file, they are mostly there to avoid the possibility of common mistakes (for example, loading a file which is not a chdb database, or that is somehow incompatible with the current system). A maliciously crafted chdb file can thus be dangerous if loaded, so chdb files should be trusted and treated with the same security protections used for PHP shared libraries.

Parameters

pathname

The name of the file to load.

Errors/Exceptions

Throws an exception in case the chdb file hasn't been successfully loaded.

Note:

A valid chdb file might fail to load in case it was created on an architecture with a different endianness, with a different version of chdb, or if the file is too big to be mapped into memory (mostly in case of huge files and 32-bit architectures). In these cases the load will fail by throwing an exception, but otherwise not performing any illegal operation.


Gets the value associated with a key

  • « chdb::__construct
  • chdb Functions »
  • PHP Manual
  • chdb
  • Gets the value associated with a key

chdb::get

(PECL chdb >= 0.1.0)

chdb::get — Gets the value associated with a key

Description

public chdb::get ( string $key ) : string

Gets the value associated with a key from a chdb database.

Parameters

key

The key for which to get the value.

Return Values

Returns a string containing the value associated with the given key, or NULL if not found.

Examples

Example #1 chdb::get() example

<?php

$data = array(
    'key1' => 'value1',
    'key2' => 'value2',
    // ...
);
chdb_create('data.chdb', $data);

$chdb = new chdb('data.chdb');
$value1 = $chdb->get('key1');
$value2 = $chdb->get('key2');

echo $value1, PHP_EOL;
echo $value2, PHP_EOL;

?>

The above example will output something similar to:

value1
value2


  • « chdb::get
  • chdb_create »
  • PHP Manual
  • chdb
  • chdb Functions

chdb Functions

Table of Contents

  • chdb_create — Creates a chdb file


Creates a chdb file

  • « chdb Functions
  • cURL »
  • PHP Manual
  • chdb Functions
  • Creates a chdb file

chdb_create

(PECL chdb >= 0.1.0)

chdb_create — Creates a chdb file

Description

chdb_create ( string $pathname , array $data ) : bool

chdb_create() creates a chdb file containing the specified key-value pairs.

Note:

chdb files are not portable across little-endian and big-endian environments. Except for that, they are portable across different architectures. Also compatibility across different versions of chdb is not guaranteed.

Parameters

pathname

The name of the file to create.

If a file with the same name already exists, it is overwritten.

data

An array containing the key-value pairs to store in the chdb file.

Keys and values are converted to strings before being written to the file, as chdb only support the string type. Note that binary strings are supported as well, both as keys and values.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws an exception in case the chdb file hasn't been successfully created.

Examples

Example #1 chdb_create() example

<?php

$data = array(
    'key1' => 'value1',
    'key2' => 'value2',
    // ...
);
chdb_create('data.chdb', $data);

?>

The above example will generate a chdb file named data.chdb and containing the key-value pairs defined in $data.


Client URL Library

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic curl example
  • cURL Functions
    • curl_close — Close a cURL session
    • curl_copy_handle — Copy a cURL handle along with all of its preferences
    • curl_errno — Return the last error number
    • curl_error — Return a string containing the last error for the current session
    • curl_escape — URL encodes the given string
    • curl_exec — Perform a cURL session
    • curl_file_create — Create a CURLFile object
    • curl_getinfo — Get information regarding a specific transfer
    • curl_init — Initialize a cURL session
    • curl_multi_add_handle — Add a normal cURL handle to a cURL multi handle
    • curl_multi_close — Close a set of cURL handles
    • curl_multi_errno — Return the last multi curl error number
    • curl_multi_exec — Run the sub-connections of the current cURL handle
    • curl_multi_getcontent — Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set
    • curl_multi_info_read — Get information about the current transfers
    • curl_multi_init — Returns a new cURL multi handle
    • curl_multi_remove_handle — Remove a multi handle from a set of cURL handles
    • curl_multi_select — Wait for activity on any curl_multi connection
    • curl_multi_setopt — Set an option for the cURL multi handle
    • curl_multi_strerror — Return string describing error code
    • curl_pause — Pause and unpause a connection
    • curl_reset — Reset all options of a libcurl session handle
    • curl_setopt_array — Set multiple options for a cURL transfer
    • curl_setopt — Set an option for a cURL transfer
    • curl_share_close — Close a cURL share handle
    • curl_share_errno — Return the last share curl error number
    • curl_share_init — Initialize a cURL share handle
    • curl_share_setopt — Set an option for a cURL share handle
    • curl_share_strerror — Return string describing the given error code
    • curl_strerror — Return string describing the given error code
    • curl_unescape — Decodes the given URL encoded string
    • curl_version — Gets cURL version information
  • CURLFile — The CURLFile class
    • CURLFile::__construct — Create a CURLFile object
    • CURLFile::getFilename — Get file name
    • CURLFile::getMimeType — Get MIME type
    • CURLFile::getPostFilename — Get file name for POST
    • CURLFile::setMimeType — Set MIME type
    • CURLFile::setPostFilename — Set file name for POST
    • CURLFile::__wakeup — Unserialization handler


Introduction

PHP supports libcurl, a library created by Daniel Stenberg, that allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.


Requirements

In order to use PHP's cURL functions you need to install the » libcurl package. PHP requires libcurl version 7.10.5 or later.


Installation

To use PHP's cURL support you must also compile PHP --with-curl[=DIR] where DIR is the location of the directory containing the lib and include directories. In the include directory there should be a folder named curl which should contain the easy.h and curl.h files. There should be a file named libcurl.a located in the lib directory. Before PHP 5.5.0 it was possible to configure PHP to use cURL for URL streams --with-curlwrappers .

Note: Note to Win32 Users
In order to enable this module on a Windows environment, libeay32.dll and ssleay32.dll, or, as of OpenSSL 1.1 libcrypto-*.dll and libssl-*.dll, must be present in your PATH. Also libssh2.dll must be present in your PATH. You don't need libcurl.dll from the cURL site.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

cURL Configuration Options
Name | Default | Changeable | Changelog
curl.cainfo | NULL | PHP_INI_SYSTEM | Available since PHP 5.3.7.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

curl.cainfo string

A default value for the CURLOPT_CAINFO option. This is required to be an absolute path.


  • « Runtime Configuration
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

This extension defines two resource types: a cURL handle and a cURL multi handle.


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.

Descriptions and uses for these constants are described within the curl_setopt(), curl_multi_setopt() and curl_getinfo() documentation.

CURLOPT_AUTOREFERER (integer)
Available since PHP 5.1.0
CURLOPT_COOKIESESSION (integer)
Available since PHP 5.1.0
CURLOPT_DNS_USE_GLOBAL_CACHE (integer)
CURLOPT_DNS_CACHE_TIMEOUT (integer)
CURLOPT_FTP_SSL (integer)
Available since PHP 5.2.0
CURLFTP_CREATE_DIR (integer)
Available since PHP 7.0.7 and cURL 7.19.3
CURLFTP_CREATE_DIR_NONE (integer)
Available since PHP 7.0.7 and cURL 7.19.3
CURLFTP_CREATE_DIR_RETRY (integer)
Available since PHP 7.0.7 and cURL 7.19.3
CURLFTPSSL_TRY (integer)
Available since PHP 5.2.0
CURLFTPSSL_ALL (integer)
Available since PHP 5.2.0
CURLFTPSSL_CONTROL (integer)
Available since PHP 5.2.0
CURLFTPSSL_NONE (integer)
Available since PHP 5.2.0
CURLOPT_PRIVATE (integer)
Available since PHP 5.2.4
CURLOPT_FTPSSLAUTH (integer)
Available since PHP 5.1.0
CURLOPT_PORT (integer)
CURLOPT_FILE (integer)
CURLOPT_INFILE (integer)
CURLOPT_INFILESIZE (integer)
CURLOPT_URL (integer)
CURLOPT_PROXY (integer)
CURLOPT_VERBOSE (integer)
CURLOPT_HEADER (integer)
CURLOPT_HTTPHEADER (integer)
CURLOPT_NOPROGRESS (integer)
CURLOPT_NOBODY (integer)
CURLOPT_FAILONERROR (integer)
CURLOPT_UPLOAD (integer)
CURLOPT_POST (integer)
CURLOPT_FTPLISTONLY (integer)
CURLOPT_FTPAPPEND (integer)
CURLOPT_FTP_CREATE_MISSING_DIRS (integer)
CURLOPT_NETRC (integer)
CURLOPT_FOLLOWLOCATION (integer)
This constant is not available when open_basedir or safe_mode are enabled.
CURLOPT_FTPASCII (integer)
CURLOPT_PUT (integer)
CURLOPT_MUTE (integer)
CURLOPT_USERPWD (integer)
CURLOPT_PROXYUSERPWD (integer)
CURLOPT_RANGE (integer)
CURLOPT_TIMEOUT (integer)
CURLOPT_TIMEOUT_MS (integer)
CURLOPT_TCP_NODELAY (integer)
Available since PHP 5.2.1
CURLOPT_POSTFIELDS (integer)
CURLOPT_PROGRESSFUNCTION (integer)
Available since PHP 5.3.0
CURLOPT_REFERER (integer)
CURLOPT_USERAGENT (integer)
CURLOPT_FTPPORT (integer)
CURLOPT_FTP_USE_EPSV (integer)
CURLOPT_LOW_SPEED_LIMIT (integer)
CURLOPT_LOW_SPEED_TIME (integer)
CURLOPT_RESUME_FROM (integer)
CURLOPT_COOKIE (integer)
CURLOPT_SSLCERT (integer)
CURLOPT_SSLCERTPASSWD (integer)
CURLOPT_WRITEHEADER (integer)
CURLOPT_SSL_VERIFYHOST (integer)
CURLOPT_COOKIEFILE (integer)
CURLOPT_SSLVERSION (integer)
CURL_SSLVERSION_DEFAULT (integer)
CURL_SSLVERSION_TLSv1 (integer)
CURL_SSLVERSION_SSLv2 (integer)
CURL_SSLVERSION_SSLv3 (integer)
CURL_SSLVERSION_TLSv1_0 (integer)
Available since PHP 5.5.19 and 5.6.3
CURL_SSLVERSION_TLSv1_1 (integer)
Available since PHP 5.5.19 and 5.6.3
CURL_SSLVERSION_TLSv1_2 (integer)
Available since PHP 5.5.19 and 5.6.3
CURLOPT_TIMECONDITION (integer)
CURLOPT_TIMEVALUE (integer)
CURLOPT_CUSTOMREQUEST (integer)
CURLOPT_STDERR (integer)
CURLOPT_TRANSFERTEXT (integer)
CURLOPT_RETURNTRANSFER (integer)
CURLOPT_QUOTE (integer)
CURLOPT_POSTQUOTE (integer)
CURLOPT_INTERFACE (integer)
CURLOPT_KRB4LEVEL (integer)
CURLOPT_HTTPPROXYTUNNEL (integer)
CURLOPT_FILETIME (integer)
CURLOPT_WRITEFUNCTION (integer)
CURLOPT_READFUNCTION (integer)
CURLOPT_PASSWDFUNCTION (integer)
CURLOPT_HEADERFUNCTION (integer)
CURLOPT_MAXREDIRS (integer)
CURLOPT_MAXCONNECTS (integer)
CURLOPT_CLOSEPOLICY (integer)
Removed in PHP 5.6.0.
CURLOPT_FRESH_CONNECT (integer)
CURLOPT_FORBID_REUSE (integer)
CURLOPT_RANDOM_FILE (integer)
CURLOPT_EGDSOCKET (integer)
CURLOPT_CONNECTTIMEOUT (integer)
CURLOPT_CONNECTTIMEOUT_MS (integer)
CURLOPT_SSL_VERIFYPEER (integer)
CURLOPT_CAINFO (integer)
CURLOPT_CAPATH (integer)
CURLOPT_COOKIEJAR (integer)
CURLOPT_SSL_CIPHER_LIST (integer)
CURLOPT_BINARYTRANSFER (integer)
CURLOPT_NOSIGNAL (integer)
CURLOPT_PROXYTYPE (integer)
Available as of cURL 7.10.
CURLOPT_BUFFERSIZE (integer)
CURLOPT_HTTPGET (integer)
CURLOPT_HTTP_VERSION (integer)
CURLOPT_SSLKEY (integer)
CURLOPT_SSLKEYTYPE (integer)
CURLOPT_SSLKEYPASSWD (integer)
CURLOPT_SSLENGINE (integer)
CURLOPT_SSLENGINE_DEFAULT (integer)
CURLOPT_SSLCERTTYPE (integer)
CURLOPT_CRLF (integer)
CURLOPT_ENCODING (integer)
CURLOPT_PROXYPORT (integer)
CURLOPT_UNRESTRICTED_AUTH (integer)
CURLOPT_FTP_USE_EPRT (integer)
CURLOPT_HTTP200ALIASES (integer)
CURLOPT_HTTPAUTH (integer)
CURLAUTH_BASIC (integer)
CURLAUTH_DIGEST (integer)
CURLAUTH_GSSNEGOTIATE (integer)
CURLAUTH_NEGOTIATE (integer)
Available since PHP 7.0.7 and cURL 7.38.0.
CURLAUTH_NTLM (integer)
CURLAUTH_NTLM_WB (integer)
Available since PHP 7.0.7 and cURL 7.22.0
CURLAUTH_ANY (integer)
CURLAUTH_ANYSAFE (integer)
CURLOPT_PROXYAUTH (integer)
CURLOPT_MAX_RECV_SPEED_LARGE (integer)
Available since PHP 5.4.0 and cURL 7.15.5
CURLOPT_MAX_SEND_SPEED_LARGE (integer)
Available since PHP 5.4.0 and cURL 7.15.5
CURLOPT_HEADEROPT (integer)
Available since PHP 7.0.7 and cURL 7.37.0
CURLOPT_PROXYHEADER (integer)
Available since PHP 7.0.7 and cURL 7.37.0
CURLCLOSEPOLICY_LEAST_RECENTLY_USED (integer)
Removed in PHP 5.6.0.
CURLCLOSEPOLICY_LEAST_TRAFFIC (integer)
Removed in PHP 5.6.0.
CURLCLOSEPOLICY_SLOWEST (integer)
Removed in PHP 5.6.0.
CURLCLOSEPOLICY_CALLBACK (integer)
Removed in PHP 5.6.0.
CURLCLOSEPOLICY_OLDEST (integer)
Removed in PHP 5.6.0.
CURLINFO_PRIVATE (integer)
Available since PHP 5.2.4
CURLINFO_EFFECTIVE_URL (integer)
CURLINFO_HTTP_CODE (integer)
As of PHP 5.5.0 and cURL 7.10.8, this is a legacy alias of CURLINFO_RESPONSE_CODE
CURLINFO_RESPONSE_CODE (integer)
Available since PHP 5.5.0 and cURL 7.10.8
CURLINFO_HEADER_OUT (integer)
Available since PHP 5.1.3
CURLINFO_HEADER_SIZE (integer)
CURLINFO_REQUEST_SIZE (integer)
CURLINFO_TOTAL_TIME (integer)
CURLINFO_NAMELOOKUP_TIME (integer)
CURLINFO_CONNECT_TIME (integer)
CURLINFO_PRETRANSFER_TIME (integer)
CURLINFO_SIZE_UPLOAD (integer)
CURLINFO_SIZE_DOWNLOAD (integer)
CURLINFO_SPEED_DOWNLOAD (integer)
CURLINFO_SPEED_UPLOAD (integer)
CURLINFO_FILETIME (integer)
CURLINFO_SSL_VERIFYRESULT (integer)
CURLINFO_CONTENT_LENGTH_DOWNLOAD (integer)
CURLINFO_CONTENT_LENGTH_UPLOAD (integer)
CURLINFO_STARTTRANSFER_TIME (integer)
CURLINFO_CONTENT_TYPE (integer)
CURLINFO_REDIRECT_TIME (integer)
CURLINFO_REDIRECT_COUNT (integer)
CURLINFO_REDIRECT_URL (string)
Available since PHP 5.3.7
CURLINFO_PRIMARY_IP (string)
Available since PHP 5.4.7
CURLINFO_PRIMARY_PORT (integer)
Available since PHP 5.4.7
CURLINFO_LOCAL_IP (string)
Available since PHP 5.4.7
CURLINFO_LOCAL_PORT (integer)
Available since PHP 5.4.7
CURL_PUSH_OK (integer)
Available since PHP 7.1.0 and cURL 7.44.0
CURL_PUSH_DENY (integer)
Available since PHP 7.1.0 and cURL 7.44.0
CURL_REDIR_POST_301 (integer)
Available since PHP 7.0.7 and cURL 7.18.2
CURL_REDIR_POST_302 (integer)
Available since PHP 7.0.7 and cURL 7.18.2
CURL_REDIR_POST_303 (integer)
Available since PHP 7.0.7 and cURL 7.25.1
CURL_REDIR_POST_ALL (integer)
Available since PHP 7.0.7 and cURL 7.18.2
CURL_TIMECOND_IFMODSINCE (integer)
CURL_TIMECOND_IFUNMODSINCE (integer)
CURL_TIMECOND_LASTMOD (integer)
CURL_VERSION_ALTSVC (integer)
Available since PHP 7.3.6 and cURL 7.64.1
CURL_VERSION_ASYNCHDNS (integer)
Available since PHP 7.3.0 and cURL 7.10.7
CURL_VERSION_BROTLI (integer)
Available since PHP 7.3.0 and cURL 7.57.0
CURL_VERSION_CONV (integer)
Available since PHP 7.3.0 and cURL 7.15.4
CURL_VERSION_CURLDEBUG (integer)
Available since PHP 7.3.6 and cURL 7.19.6
CURL_VERSION_DEBUG (integer)
Available since PHP 7.3.0 and cURL 7.10.6
CURL_VERSION_GSSAPI (integer)
Available since PHP 7.3.0 and cURL 7.38.0
CURL_VERSION_GSSNEGOTIATE (integer)
Available since PHP 7.3.0 and cURL 7.10.6 (deprecated since 7.38.0)
CURL_VERSION_IDN (integer)
Available since PHP 7.3.0 and cURL 7.12.0
CURL_VERSION_MULTI_SSL (integer)
Available since PHP 7.3.0 and cURL 7.56.0
CURL_VERSION_NTLM (integer)
Available since PHP 7.3.0 and cURL 7.10.6
CURL_VERSION_NTLM_WB (integer)
Available since PHP 7.3.0 and cURL 7.22.0
CURL_VERSION_IPV6 (integer)
CURL_VERSION_KERBEROS4 (integer)
CURL_VERSION_KERBEROS5 (integer)
Available since PHP 7.0.7 and cURL 7.40.0
CURL_VERSION_HTTP2 (integer)
Available since PHP 5.5.24 and 5.6.8 and cURL 7.33.0
CURL_VERSION_PSL (integer)
Available since PHP 7.3.6 and cURL 7.47.0
CURL_VERSION_SPNEGO (integer)
Available since PHP 7.3.0 and cURL 7.10.8
CURL_VERSION_SSPI (integer)
Available since PHP 7.3.0 and cURL 7.13.2
CURL_VERSION_SSL (integer)
CURL_VERSION_TLSAUTH_SRP (integer)
Available since PHP 7.3.0 and cURL 7.21.4
CURL_VERSION_UNIX_SOCKETS (integer)
Available since PHP 7.0.7 and cURL 7.40.0
CURL_VERSION_LIBZ (integer)
CURLVERSION_NOW (integer)
CURLE_OK (integer)
CURLE_UNSUPPORTED_PROTOCOL (integer)
CURLE_FAILED_INIT (integer)
CURLE_URL_MALFORMAT (integer)
CURLE_URL_MALFORMAT_USER (integer)
CURLE_COULDNT_RESOLVE_PROXY (integer)
CURLE_COULDNT_RESOLVE_HOST (integer)
CURLE_COULDNT_CONNECT (integer)
CURLE_FTP_WEIRD_SERVER_REPLY (integer)
CURLE_FTP_ACCESS_DENIED (integer)
CURLE_FTP_USER_PASSWORD_INCORRECT (integer)
CURLE_FTP_WEIRD_PASS_REPLY (integer)
CURLE_FTP_WEIRD_USER_REPLY (integer)
CURLE_FTP_WEIRD_PASV_REPLY (integer)
CURLE_FTP_WEIRD_227_FORMAT (integer)
CURLE_FTP_CANT_GET_HOST (integer)
CURLE_FTP_CANT_RECONNECT (integer)
CURLE_FTP_COULDNT_SET_BINARY (integer)
CURLE_PARTIAL_FILE (integer)
CURLE_FTP_COULDNT_RETR_FILE (integer)
CURLE_FTP_WRITE_ERROR (integer)
CURLE_FTP_QUOTE_ERROR (integer)
CURLE_HTTP_NOT_FOUND (integer)
CURLE_WRITE_ERROR (integer)
CURLE_MALFORMAT_USER (integer)
CURLE_FTP_COULDNT_STOR_FILE (integer)
CURLE_READ_ERROR (integer)
CURLE_OUT_OF_MEMORY (integer)
CURLE_OPERATION_TIMEOUTED (integer)
CURLE_FTP_COULDNT_SET_ASCII (integer)
CURLE_FTP_PORT_FAILED (integer)
CURLE_FTP_COULDNT_USE_REST (integer)
CURLE_FTP_COULDNT_GET_SIZE (integer)
CURLE_HTTP_RANGE_ERROR (integer)
CURLE_HTTP_POST_ERROR (integer)
CURLE_SSL_CONNECT_ERROR (integer)
CURLE_FTP_BAD_DOWNLOAD_RESUME (integer)
CURLE_FILE_COULDNT_READ_FILE (integer)
CURLE_LDAP_CANNOT_BIND (integer)
CURLE_LDAP_SEARCH_FAILED (integer)
CURLE_LIBRARY_NOT_FOUND (integer)
CURLE_FUNCTION_NOT_FOUND (integer)
CURLE_ABORTED_BY_CALLBACK (integer)
CURLE_BAD_FUNCTION_ARGUMENT (integer)
CURLE_BAD_CALLING_ORDER (integer)
CURLE_HTTP_PORT_FAILED (integer)
CURLE_BAD_PASSWORD_ENTERED (integer)
CURLE_TOO_MANY_REDIRECTS (integer)
CURLE_UNKNOWN_TELNET_OPTION (integer)
CURLE_TELNET_OPTION_SYNTAX (integer)
CURLE_OBSOLETE (integer)
CURLE_SSL_PEER_CERTIFICATE (integer)
CURLE_GOT_NOTHING (integer)
CURLE_SSL_ENGINE_NOTFOUND (integer)
CURLE_SSL_ENGINE_SETFAILED (integer)
CURLE_SEND_ERROR (integer)
CURLE_RECV_ERROR (integer)
CURLE_SHARE_IN_USE (integer)
CURLE_SSL_CERTPROBLEM (integer)
CURLE_SSL_CIPHER (integer)
CURLE_SSL_CACERT (integer)
CURLE_BAD_CONTENT_ENCODING (integer)
CURLE_LDAP_INVALID_URL (integer)
CURLE_FILESIZE_EXCEEDED (integer)
CURLE_FTP_SSL_FAILED (integer)
CURLE_SSH (integer)
Available since PHP 5.3.0 and cURL 7.16.1.
CURLFTPAUTH_DEFAULT (integer)
Available since PHP 5.1.0
CURLFTPAUTH_SSL (integer)
Available since PHP 5.1.0
CURLFTPAUTH_TLS (integer)
Available since PHP 5.1.0
CURLPROXY_HTTP (integer)
Available since cURL 7.10.
CURLPROXY_HTTP_1_0 (integer)
Available since PHP 7.0.7 and cURL 7.19.3
CURLPROXY_SOCKS4 (integer)
Available since PHP 5.2.10 and cURL 7.10.
CURLPROXY_SOCKS5 (integer)
Available since cURL 7.10.
CURL_NETRC_OPTIONAL (integer)
CURL_NETRC_IGNORED (integer)
CURL_NETRC_REQUIRED (integer)
CURL_HTTP_VERSION_NONE (integer)
CURL_HTTP_VERSION_1_0 (integer)
CURL_HTTP_VERSION_1_1 (integer)
CURL_HTTP_VERSION_2 (integer)
Available since PHP 7.0.7 and cURL 7.43.0
CURL_HTTP_VERSION_2_0 (integer)
Available since PHP 5.5.24 and 5.6.8 and cURL 7.33.0
CURL_HTTP_VERSION_2TLS (integer)
Available since PHP 7.0.7 and cURL 7.47.0
CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE (integer)
Available since PHP 7.0.7 and cURL 7.49.0
CURLM_CALL_MULTI_PERFORM (integer)
CURLM_OK (integer)
CURLM_BAD_HANDLE (integer)
CURLM_BAD_EASY_HANDLE (integer)
CURLM_OUT_OF_MEMORY (integer)
CURLM_INTERNAL_ERROR (integer)
CURLMSG_DONE (integer)
CURLOPT_KEYPASSWD (integer)
CURLOPT_SSH_AUTH_TYPES (integer)
CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 (integer)
CURLOPT_SSH_PRIVATE_KEYFILE (integer)
CURLOPT_SSH_PUBLIC_KEYFILE (integer)
CURLOPT_SSL_OPTIONS (integer)
Available since PHP 5.5.0 and cURL 7.25.0
CURLSSLOPT_ALLOW_BEAST (integer)
Available since PHP 5.5.0 and cURL 7.25.0
CURLSSLOPT_NO_REVOKE (integer)
Available since PHP 7.0.7 and cURL 7.44.0
CURLOPT_USERNAME (integer)
Available since PHP 5.5.0 and cURL 7.19.1
CURLOPT_SASL_IR (integer)
Available since PHP 7.0.7 and cURL 7.31.0
CURLOPT_DNS_INTERFACE (integer)
Available since PHP 7.0.7 and cURL 7.33.0
CURLOPT_DNS_LOCAL_IP4 (integer)
Available since PHP 7.0.7 and cURL 7.33.0
CURLOPT_DNS_LOCAL_IP6 (integer)
Available since PHP 7.0.7 and cURL 7.33.0
CURLOPT_XOAUTH2_BEARER (integer)
Available since PHP 7.0.7 and cURL 7.33.0
CURLOPT_LOGIN_OPTIONS (integer)
Available since PHP 7.0.7 and cURL 7.34.0
CURLOPT_EXPECT_100_TIMEOUT_MS (integer)
Available since PHP 7.0.7 and cURL 7.36.0
CURLOPT_SSL_ENABLE_ALPN (integer)
Available since PHP 7.0.7 and cURL 7.36.0
CURLOPT_SSL_ENABLE_NPN (integer)
Available since PHP 7.0.7 and cURL 7.36.0
CURLOPT_PINNEDPUBLICKEY (integer)
Available since PHP 7.0.7 and cURL 7.39.0
CURLOPT_UNIX_SOCKET_PATH (integer)
Available since PHP 7.0.7 and cURL 7.40.0
CURLOPT_SSL_VERIFYSTATUS (integer)
Available since PHP 7.0.7 and cURL 7.41.0
CURLOPT_PATH_AS_IS (integer)
Available since PHP 7.0.7 and cURL 7.42.0
CURLOPT_SSL_FALSESTART (integer)
Available since PHP 7.0.7 and cURL 7.42.0
CURLOPT_PIPEWAIT (integer)
Available since PHP 7.0.7 and cURL 7.43.0
CURLOPT_PROXY_SERVICE_NAME (integer)
Available since PHP 7.0.7 and cURL 7.43.0
CURLOPT_SERVICE_NAME (integer)
Available since PHP 7.0.7 and cURL 7.43.0
CURLOPT_DEFAULT_PROTOCOL (integer)
Available since PHP 7.0.7 and cURL 7.45.0
CURLOPT_STREAM_WEIGHT (integer)
Available since PHP 7.0.7 and cURL 7.46.0
CURLOPT_TFTP_NO_OPTIONS (integer)
Available since PHP 7.0.7 and cURL 7.48.0
CURLOPT_CONNECT_TO (integer)
Available since PHP 7.0.7 and cURL 7.49.0
CURLOPT_TCP_FASTOPEN (integer)
Available since PHP 7.0.7 and cURL 7.49.0
CURLMOPT_PIPELINING (integer)
Available since PHP 5.5.0 and cURL 7.16.0.
CURLMOPT_MAXCONNECTS (integer)
Available since PHP 5.5.0 and cURL 7.16.3.
CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE (integer)
Available since PHP 7.0.7 and cURL 7.30.0
CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE (integer)
Available since PHP 7.0.7 and cURL 7.30.0
CURLMOPT_MAX_HOST_CONNECTIONS (integer)
Available since PHP 7.0.7 and cURL 7.30.0
CURLMOPT_MAX_PIPELINE_LENGTH (integer)
Available since PHP 7.0.7 and cURL 7.30.0
CURLMOPT_MAX_TOTAL_CONNECTIONS (integer)
Available since PHP 7.0.7 and cURL 7.30.0
CURLMOPT_PUSHFUNCTION (integer)
Available since PHP 7.1.0 and cURL 7.44.0
CURLSSH_AUTH_AGENT (integer)
Available since PHP 7.0.7 and cURL 7.28.0
CURLSSH_AUTH_ANY (integer)
CURLSSH_AUTH_DEFAULT (integer)
CURLSSH_AUTH_HOST (integer)
CURLSSH_AUTH_KEYBOARD (integer)
CURLSSH_AUTH_NONE (integer)
CURLSSH_AUTH_PASSWORD (integer)
CURLSSH_AUTH_PUBLICKEY (integer)
CURL_WRAPPERS_ENABLED (integer)
Defined if PHP was configured with --with-curlwrappers . Moved to PECL in PHP 5.5.0.
CURLPAUSE_ALL (integer)
Available since PHP 5.5.0 and cURL 7.18.0.
CURLPAUSE_CONT (integer)
Available since PHP 5.5.0 and cURL 7.18.0.
CURLPAUSE_RECV (integer)
Available since PHP 5.5.0 and cURL 7.18.0.
CURLPAUSE_RECV_CONT (integer)
Available since PHP 5.5.0 and cURL 7.18.0.
CURLPAUSE_SEND (integer)
Available since PHP 5.5.0 and cURL 7.18.0.
CURLPAUSE_SEND_CONT (integer)
Available since PHP 5.5.0 and cURL 7.18.0.
CURLPIPE_NOTHING (integer)
Available since PHP 7.0.0 and cURL 7.43.0.
CURLPIPE_HTTP1 (integer)
Available since PHP 7.0.0 and cURL 7.43.0.
CURLPIPE_MULTIPLEX (integer)
Available since PHP 7.0.0 and cURL 7.43.0.
CURLPROXY_SOCKS4A (integer)
Available since PHP 5.5.23 and PHP 5.6.7 and cURL 7.18.0.
CURLPROXY_SOCKS5_HOSTNAME (integer)
Available since PHP 5.5.23 and PHP 5.6.7 and cURL 7.18.0.
CURLHEADER_SEPARATE (integer)
Available since PHP 7.0.7 and cURL 7.37.0.
CURLHEADER_UNIFIED (integer)
Available since PHP 7.0.7 and cURL 7.37.0.
CURLPROTO_SMB (integer)
Available since PHP 7.0.7 and cURL 7.40.0.
CURLPROTO_SMBS (integer)
Available since PHP 7.0.7 and cURL 7.40.0.
CURLOPT_REQUEST_TARGET (integer)
Available since PHP 7.3.0 and cURL 7.55.0.
CURLAUTH_GSSAPI (integer)
Available since PHP 7.3.0 and cURL 7.54.1
CURLE_WEIRD_SERVER_REPLY (integer)
Available since PHP 7.3.0 and cURL 7.51.0
CURLINFO_CONTENT_LENGTH_DOWNLOAD_T (integer)
Available since PHP 7.3.0 and cURL 7.55.0
CURLINFO_CONTENT_LENGTH_UPLOAD_T (integer)
Available since PHP 7.3.0 and cURL 7.55.0
CURLINFO_HTTP_VERSION (integer)
Available since PHP 7.3.0 and cURL 7.50.0
CURLINFO_PROTOCOL (integer)
Available since PHP 7.3.0 and cURL 7.52.0
CURLINFO_PROXY_SSL_VERIFYRESULT (integer)
Available since PHP 7.3.0 and cURL 7.52.0
CURLINFO_SCHEME (integer)
Available since PHP 7.3.0 and cURL 7.52.0
CURLINFO_SIZE_DOWNLOAD_T (integer)
Available since PHP 7.3.0 and cURL 7.50.0
CURLINFO_SIZE_UPLOAD_T (integer)
Available since PHP 7.3.0 and cURL 7.50.0
CURLINFO_SPEED_DOWNLOAD_T (integer)
Available since PHP 7.3.0 and cURL 7.50.0
CURLINFO_SPEED_UPLOAD_T (integer)
Available since PHP 7.3.0 and cURL 7.50.0
CURL_MAX_READ_SIZE (integer)
Available since PHP 7.3.0 and cURL 7.53.0
CURLOPT_ABSTRACT_UNIX_SOCKET (integer)
Available since PHP 7.3.0 and cURL 7.53.0
CURLOPT_KEEP_SENDING_ON_ERROR (integer)
Available since PHP 7.3.0 and cURL 7.51.0
CURLOPT_PRE_PROXY (integer)
Available since PHP 7.3.0 and cURL 7.52.0
CURLOPT_PROXY_CAINFO (integer)
Available since PHP 7.3.0 and cURL 7.52.0
CURLOPT_PROXY_CAPATH (integer)
Available since PHP 7.3.0 and cURL 7.52.0
CURLOPT_PROXY_CRLFILE (integer)
Available since PHP 7.3.0 and cURL 7.52.0
CURLOPT_PROXY_KEYPASSWD (integer)
Available since PHP 7.3.0 and cURL 7.52.0
CURLOPT_PROXY_PINNEDPUBLICKEY (integer)
Available since PHP 7.3.0 and cURL 7.52.0
CURLOPT_PROXY_SSLCERT (integer)
Available since PHP 7.3.0 and cURL 7.52.0
CURLOPT_PROXY_SSLCERTTYPE (integer)
Available since PHP 7.3.0 and cURL 7.52.0
CURLOPT_PROXY_SSL_CIPHER_LIST (integer)
Available since PHP 7.3.0 and cURL 7.52.0
CURLOPT_PROXY_SSLKEY (integer)
Available since PHP 7.3.0 and cURL 7.52.0
CURLOPT_PROXY_SSLKEYTYPE (integer)
Available since PHP 7.3.0 and cURL 7.52.0
CURLOPT_PROXY_SSL_OPTIONS (integer)
Available since PHP 7.3.0 and cURL 7.52.0
CURLOPT_PROXY_SSL_VERIFYHOST (integer)
Available since PHP 7.3.0 and cURL 7.52.0
CURLOPT_PROXY_SSL_VERIFYPEER (integer)
Available since PHP 7.3.0 and cURL 7.52.0
CURLOPT_PROXY_SSLVERSION (integer)
Available since PHP 7.3.0 and cURL 7.52.0
CURLOPT_PROXY_TLSAUTH_PASSWORD (integer)
Available since PHP 7.3.0 and cURL 7.52.0
CURLOPT_PROXY_TLSAUTH_TYPE (integer)
Available since PHP 7.3.0 and cURL 7.52.0
CURLOPT_PROXY_TLSAUTH_USERNAME (integer)
Available since PHP 7.3.0 and cURL 7.52.0
CURLOPT_SOCKS5_AUTH (integer)
Available since PHP 7.3.0 and cURL 7.55.0
CURLOPT_SUPPRESS_CONNECT_HEADERS (integer)
Available since PHP 7.3.0 and cURL 7.54.0
CURLPROXY_HTTPS (integer)
Available since PHP 7.3.0 and cURL 7.52.0
CURL_SSLVERSION_MAX_DEFAULT (integer)
Available since PHP 7.3.0 and cURL 7.54.0
CURL_SSLVERSION_MAX_NONE (integer)
Available since PHP 7.3.0 and cURL 7.54.0
CURL_SSLVERSION_MAX_TLSv1_0 (integer)
Available since PHP 7.3.0 and cURL 7.54.0
CURL_SSLVERSION_MAX_TLSv1_1 (integer)
Available since PHP 7.3.0 and cURL 7.54.0
CURL_SSLVERSION_MAX_TLSv1_2 (integer)
Available since PHP 7.3.0 and cURL 7.54.0
CURL_SSLVERSION_MAX_TLSv1_3 (integer)
Available since PHP 7.3.0 and cURL 7.54.0
CURL_SSLVERSION_TLSv1_3 (integer)
Available since PHP 7.3.0 and cURL 7.52.0
CURL_VERSION_HTTPS_PROXY (integer)
Available since PHP 7.3.0 and cURL 7.52.0
CURLAUTH_BEARER (integer)
Available since PHP 7.3.0 and cURL 7.61.0.
CURLINFO_APPCONNECT_TIME_T (integer)
Available since PHP 7.3.0 and cURL 7.61.0
CURLINFO_CONNECT_TIME_T (integer)
Available since PHP 7.3.0 and cURL 7.61.0
CURLINFO_FILETIME_T (integer)
Available since PHP 7.3.0 and cURL 7.59.0
CURLINFO_NAMELOOKUP_TIME_T (integer)
Available since PHP 7.3.0 and cURL 7.61.0
CURLINFO_PRETRANSFER_TIME_T (integer)
Available since PHP 7.3.0 and cURL 7.61.0
CURLINFO_REDIRECT_TIME_T (integer)
Available since PHP 7.3.0 and cURL 7.61.0
CURLINFO_STARTTRANSFER_TIME_T (integer)
Available since PHP 7.3.0 and cURL 7.61.0
CURLINFO_TOTAL_TIME_T (integer)
Available since PHP 7.3.0 and cURL 7.61.0
CURL_LOCK_DATA_CONNECT (integer)
Available since PHP 7.3.0 and cURL 7.10.0
CURL_LOCK_DATA_PSL (integer)
Available since PHP 7.3.0 and cURL 7.61.0
CURLOPT_DISALLOW_USERNAME_IN_URL (integer)
Available since PHP 7.3.0 and cURL 7.61.0
CURLOPT_DNS_SHUFFLE_ADDRESSES (integer)
Available since PHP 7.3.0 and cURL 7.60.0
CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS (integer)
Available since PHP 7.3.0 and cURL 7.59.0
CURLOPT_HAPROXYPROTOCOL (integer)
Available since PHP 7.3.0 and cURL 7.60.0
CURLOPT_PROXY_TLS13_CIPHERS (integer)
Available since PHP 7.3.0 and cURL 7.61.0
CURLOPT_SSH_COMPRESSION (integer)
Available since PHP 7.3.0 and cURL 7.56.0
CURLOPT_TIMEVALUE_LARGE (integer)
Available since PHP 7.3.0 and cURL 7.59.0
CURLOPT_TLS13_CIPHERS (integer)
Available since PHP 7.3.0 and cURL 7.61.0
CURLSSH_AUTH_GSSAPI (integer)
Available since PHP 7.3.0 and cURL 7.58.0
CURLOPT_HTTP09_ALLOWED (integer)
Available since PHP 7.3.15 and 7.4.3, respectively, and cURL 7.64.0


  • « Predefined Constants
  • Basic curl example »
  • PHP Manual
  • cURL
  • Examples

Examples

Table of Contents

  • Basic curl example


Basic curl example

Once you've compiled PHP with cURL support, you can begin using the cURL functions. The basic idea behind the cURL functions is that you initialize a cURL session using the curl_init(), then you can set all your options for the transfer via the curl_setopt(), then you can execute the session with the curl_exec() and then you finish off your session using the curl_close(). Here is an example that uses the cURL functions to fetch the example.com homepage into a file:

Example #1 Using PHP's cURL module to fetch the example.com homepage

<?php

$ch = curl_init("http://www.example.com/");
$fp = fopen("example_homepage.txt", "w");

curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

curl_exec($ch);
if(curl_error($ch)) {
    fwrite($fp, curl_error($ch));
}
curl_close($ch);
fclose($fp);
?>


cURL Functions

Table of Contents

  • curl_close — Close a cURL session
  • curl_copy_handle — Copy a cURL handle along with all of its preferences
  • curl_errno — Return the last error number
  • curl_error — Return a string containing the last error for the current session
  • curl_escape — URL encodes the given string
  • curl_exec — Perform a cURL session
  • curl_file_create — Create a CURLFile object
  • curl_getinfo — Get information regarding a specific transfer
  • curl_init — Initialize a cURL session
  • curl_multi_add_handle — Add a normal cURL handle to a cURL multi handle
  • curl_multi_close — Close a set of cURL handles
  • curl_multi_errno — Return the last multi curl error number
  • curl_multi_exec — Run the sub-connections of the current cURL handle
  • curl_multi_getcontent — Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set
  • curl_multi_info_read — Get information about the current transfers
  • curl_multi_init — Returns a new cURL multi handle
  • curl_multi_remove_handle — Remove a multi handle from a set of cURL handles
  • curl_multi_select — Wait for activity on any curl_multi connection
  • curl_multi_setopt — Set an option for the cURL multi handle
  • curl_multi_strerror — Return string describing error code
  • curl_pause — Pause and unpause a connection
  • curl_reset — Reset all options of a libcurl session handle
  • curl_setopt_array — Set multiple options for a cURL transfer
  • curl_setopt — Set an option for a cURL transfer
  • curl_share_close — Close a cURL share handle
  • curl_share_errno — Return the last share curl error number
  • curl_share_init — Initialize a cURL share handle
  • curl_share_setopt — Set an option for a cURL share handle
  • curl_share_strerror — Return string describing the given error code
  • curl_strerror — Return string describing the given error code
  • curl_unescape — Decodes the given URL encoded string
  • curl_version — Gets cURL version information


Close a cURL session

  • « cURL Functions
  • curl_copy_handle »
  • PHP Manual
  • cURL Functions
  • Close a cURL session

curl_close

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

curl_close — Close a cURL session

Description

curl_close ( resource $ch ) : void

Closes a cURL session and frees all resources. The cURL handle, ch, is also deleted.

Parameters

ch

A cURL handle returned by curl_init().

Return Values

No value is returned.

Examples

Example #1 Initializing a new cURL session and fetching a web page

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
?>

See Also

  • curl_init() - Initialize a cURL session
  • curl_multi_close() - Close a set of cURL handles


Copy a cURL handle along with all of its preferences

  • « curl_close
  • curl_errno »
  • PHP Manual
  • cURL Functions
  • Copy a cURL handle along with all of its preferences

curl_copy_handle

(PHP 5, PHP 7)

curl_copy_handle — Copy a cURL handle along with all of its preferences

Description

curl_copy_handle ( resource $ch ) : resource

Copies a cURL handle keeping the same preferences.

Parameters

ch

A cURL handle returned by curl_init().

Return Values

Returns a new cURL handle.

Examples

Example #1 Copying a cURL handle

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/');
curl_setopt($ch, CURLOPT_HEADER, 0);

// copy the handle
$ch2 = curl_copy_handle($ch);

// grab URL (http://www.example.com/) and pass it to the browser
curl_exec($ch2);

// close cURL resources, and free up system resources
curl_close($ch2);
curl_close($ch);
?>


Return the last error number

  • « curl_copy_handle
  • curl_error »
  • PHP Manual
  • cURL Functions
  • Return the last error number

curl_errno

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

curl_errno — Return the last error number

Description

curl_errno ( resource $ch ) : int

Returns the error number for the last cURL operation.

Parameters

ch

A cURL handle returned by curl_init().

Return Values

Returns the error number or 0 (zero) if no error occurred.

Examples

Example #1 curl_errno() example

<?php
// Create a curl handle to a non-existing location
$ch = curl_init('http://404.php.net/');

// Execute
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);

// Check if any error occurred
if(curl_errno($ch))
{
    echo 'Curl error: ' . curl_error($ch);
}

// Close handle
curl_close($ch);
?>

See Also

  • curl_error() - Return a string containing the last error for the current session
  • » Curl error codes


Return a string containing the last error for the current session

  • « curl_errno
  • curl_escape »
  • PHP Manual
  • cURL Functions
  • Return a string containing the last error for the current session

curl_error

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

curl_error — Return a string containing the last error for the current session

Description

curl_error ( resource $ch ) : string

Returns a clear text error message for the last cURL operation.

Parameters

ch

A cURL handle returned by curl_init().

Return Values

Returns the error message or '' (the empty string) if no error occurred.

Examples

Example #1 curl_error() example

<?php
// Create a curl handle to a non-existing location
$ch = curl_init('http://404.php.net/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

if(curl_exec($ch) === false)
{
    echo 'Curl error: ' . curl_error($ch);
}
else
{
    echo 'Operation completed without any errors';
}

// Close handle
curl_close($ch);
?>

See Also

  • curl_errno() - Return the last error number
  • » Curl error codes


URL encodes the given string

  • « curl_error
  • curl_exec »
  • PHP Manual
  • cURL Functions
  • URL encodes the given string

curl_escape

(PHP 5 >= 5.5.0, PHP 7)

curl_escape — URL encodes the given string

Description

curl_escape ( resource $ch , string $str ) : string

This function URL encodes the given string according to » RFC 3986.

Parameters

ch

A cURL handle returned by curl_init().

str

The string to be encoded.

Return Values

Returns escaped string or FALSE on failure.

Examples

Example #1 curl_escape() example

<?php
// Create a curl handle
$ch = curl_init();

// Escape a string used as a GET parameter
$location = curl_escape($ch, 'Hofbräuhaus / München');
// Result: Hofbr%C3%A4uhaus%20%2F%20M%C3%BCnchen

// Compose an URL with the escaped string
$url = "http://example.com/add_location.php?location={$location}";
// Result: http://example.com/add_location.php?location=Hofbr%C3%A4uhaus%20%2F%20M%C3%BCnchen

// Send HTTP request and close the handle
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);
?>

See Also

  • curl_unescape() - Decodes the given URL encoded string
  • urlencode() - URL-encodes string
  • rawurlencode() - URL-encode according to RFC 3986
  • » RFC 3986


Perform a cURL session

  • « curl_escape
  • curl_file_create »
  • PHP Manual
  • cURL Functions
  • Perform a cURL session

curl_exec

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

curl_exec — Perform a cURL session

Description

curl_exec ( resource $ch ) : mixed

Execute the given cURL session.

This function should be called after initializing a cURL session and all the options for the session are set.

Parameters

ch

A cURL handle returned by curl_init().

Return Values

Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.

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.

Note:

Note that response status codes which indicate errors (such as 404 Not found) are not regarded as failure. curl_getinfo() can be used to check for these.

Examples

Example #1 Fetching a web page

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
?>

See Also

  • curl_multi_exec() - Run the sub-connections of the current cURL handle


Create a CURLFile object

  • « curl_exec
  • curl_getinfo »
  • PHP Manual
  • cURL Functions
  • Create a CURLFile object

curl_file_create

(PHP 5 >= 5.5.0, PHP 7)

curl_file_create — Create a CURLFile object

Description

This function is an alias of: CURLFile::__construct()


Get information regarding a specific transfer

  • « curl_file_create
  • curl_init »
  • PHP Manual
  • cURL Functions
  • Get information regarding a specific transfer

curl_getinfo

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

curl_getinfo — Get information regarding a specific transfer

Description

curl_getinfo ( resource $ch [, int $opt ] ) : mixed

Gets information about the last transfer.

Parameters

ch

A cURL handle returned by curl_init().

opt

This may be one of the following constants:

  • CURLINFO_EFFECTIVE_URL - Last effective URL
  • CURLINFO_HTTP_CODE - The last response code. As of PHP 5.5.0 and cURL 7.10.8, this is a legacy alias of CURLINFO_RESPONSE_CODE
  • CURLINFO_FILETIME - Remote time of the retrieved document, with the CURLOPT_FILETIME enabled; if -1 is returned the time of the document is unknown
  • CURLINFO_TOTAL_TIME - Total transaction time in seconds for last transfer
  • CURLINFO_NAMELOOKUP_TIME - Time in seconds until name resolving was complete
  • CURLINFO_CONNECT_TIME - Time in seconds it took to establish the connection
  • CURLINFO_PRETRANSFER_TIME - Time in seconds from start until just before file transfer begins
  • CURLINFO_STARTTRANSFER_TIME - Time in seconds until the first byte is about to be transferred
  • CURLINFO_REDIRECT_COUNT - Number of redirects, with the CURLOPT_FOLLOWLOCATION option enabled
  • CURLINFO_REDIRECT_TIME - Time in seconds of all redirection steps before final transaction was started, with the CURLOPT_FOLLOWLOCATION option enabled
  • CURLINFO_REDIRECT_URL - With the CURLOPT_FOLLOWLOCATION option disabled: redirect URL found in the last transaction, that should be requested manually next. With the CURLOPT_FOLLOWLOCATION option enabled: this is empty. The redirect URL in this case is available in CURLINFO_EFFECTIVE_URL
  • CURLINFO_PRIMARY_IP - IP address of the most recent connection
  • CURLINFO_PRIMARY_PORT - Destination port of the most recent connection
  • CURLINFO_LOCAL_IP - Local (source) IP address of the most recent connection
  • CURLINFO_LOCAL_PORT - Local (source) port of the most recent connection
  • CURLINFO_SIZE_UPLOAD - Total number of bytes uploaded
  • CURLINFO_SIZE_DOWNLOAD - Total number of bytes downloaded
  • CURLINFO_SPEED_DOWNLOAD - Average download speed
  • CURLINFO_SPEED_UPLOAD - Average upload speed
  • CURLINFO_HEADER_SIZE - Total size of all headers received
  • CURLINFO_HEADER_OUT - The request string sent. For this to work, add the CURLINFO_HEADER_OUT option to the handle by calling curl_setopt()
  • CURLINFO_REQUEST_SIZE - Total size of issued requests, currently only for HTTP requests
  • CURLINFO_SSL_VERIFYRESULT - Result of SSL certification verification requested by setting CURLOPT_SSL_VERIFYPEER
  • CURLINFO_CONTENT_LENGTH_DOWNLOAD - Content length of download, read from Content-Length: field
  • CURLINFO_CONTENT_LENGTH_UPLOAD - Specified size of upload
  • CURLINFO_CONTENT_TYPE - Content-Type: of the requested document. NULL indicates server did not send valid Content-Type: header
  • CURLINFO_PRIVATE - Private data associated with this cURL handle, previously set with the CURLOPT_PRIVATE option of curl_setopt()
  • CURLINFO_RESPONSE_CODE - The last response code
  • CURLINFO_HTTP_CONNECTCODE - The CONNECT response code
  • CURLINFO_HTTPAUTH_AVAIL - Bitmask indicating the authentication method(s) available according to the previous response
  • CURLINFO_PROXYAUTH_AVAIL - Bitmask indicating the proxy authentication method(s) available according to the previous response
  • CURLINFO_OS_ERRNO - Errno from a connect failure. The number is OS and system specific.
  • CURLINFO_NUM_CONNECTS - Number of connections curl had to create to achieve the previous transfer
  • CURLINFO_SSL_ENGINES - OpenSSL crypto-engines supported
  • CURLINFO_COOKIELIST - All known cookies
  • CURLINFO_FTP_ENTRY_PATH - Entry path in FTP server
  • CURLINFO_APPCONNECT_TIME - Time in seconds it took from the start until the SSL/SSH connect/handshake to the remote host was completed
  • CURLINFO_CERTINFO - TLS certificate chain
  • CURLINFO_CONDITION_UNMET - Info on unmet time conditional
  • CURLINFO_RTSP_CLIENT_CSEQ - Next RTSP client CSeq
  • CURLINFO_RTSP_CSEQ_RECV - Recently received CSeq
  • CURLINFO_RTSP_SERVER_CSEQ - Next RTSP server CSeq
  • CURLINFO_RTSP_SESSION_ID - RTSP session ID
  • CURLINFO_CONTENT_LENGTH_DOWNLOAD_T - The content-length of the download. This is the value read from the Content-Type: field. -1 if the size isn't known
  • CURLINFO_CONTENT_LENGTH_UPLOAD_T - The specified size of the upload. -1 if the size isn't known
  • CURLINFO_HTTP_VERSION - The version used in the last HTTP connection. The return value will be one of the defined CURL_HTTP_VERSION_* constants or 0 if the version can't be determined
  • CURLINFO_PROTOCOL - The protocol used in the last HTTP connection. The returned value will be exactly one of the CURLPROTO_* values
  • CURLINFO_PROXY_SSL_VERIFYRESULT - The result of the certificate verification that was requested (using the CURLOPT_PROXY_SSL_VERIFYPEER option). Only used for HTTPS proxies
  • CURLINFO_SCHEME - The URL scheme used for the most recent connection
  • CURLINFO_SIZE_DOWNLOAD_T - Total number of bytes that were downloaded. The number is only for the latest transfer and will be reset again for each new transfer
  • CURLINFO_SIZE_UPLOAD_T - Total number of bytes that were uploaded
  • CURLINFO_SPEED_DOWNLOAD_T - The average download speed in bytes/second that curl measured for the complete download
  • CURLINFO_SPEED_UPLOAD_T - The average upload speed in bytes/second that curl measured for the complete upload
  • CURLINFO_APPCONNECT_TIME_T - Time, in microseconds, it took from the start until the SSL/SSH connect/handshake to the remote host was completed
  • CURLINFO_CONNECT_TIME_T - Total time taken, in microseconds, from the start until the connection to the remote host (or proxy) was completed
  • CURLINFO_FILETIME_T - Remote time of the retrieved document (as Unix timestamp), an alternative to CURLINFO_FILETIME to allow systems with 32 bit long variables to extract dates outside of the 32bit timestamp range
  • CURLINFO_NAMELOOKUP_TIME_T - Time in microseconds from the start until the name resolving was completed
  • CURLINFO_PRETRANSFER_TIME_T - Time taken from the start until the file transfer is just about to begin, in microseconds
  • CURLINFO_REDIRECT_TIME_T - Total time, in microseconds, it took for all redirection steps include name lookup, connect, pretransfer and transfer before final transaction was started
  • CURLINFO_STARTTRANSFER_TIME_T - Time, in microseconds, it took from the start until the first byte is received
  • CURLINFO_TOTAL_TIME_T - Total time in microseconds for the previous transfer, including name resolving, TCP connect etc.

Return Values

If opt is given, returns its value. Otherwise, returns an associative array with the following elements (which correspond to opt), or FALSE on failure:

  • "url"
  • "content_type"
  • "http_code"
  • "header_size"
  • "request_size"
  • "filetime"
  • "ssl_verify_result"
  • "redirect_count"
  • "total_time"
  • "namelookup_time"
  • "connect_time"
  • "pretransfer_time"
  • "size_upload"
  • "size_download"
  • "speed_download"
  • "speed_upload"
  • "download_content_length"
  • "upload_content_length"
  • "starttransfer_time"
  • "redirect_time"
  • "certinfo"
  • "primary_ip"
  • "primary_port"
  • "local_ip"
  • "local_port"
  • "redirect_url"
  • "request_header" (This is only set if the CURLINFO_HEADER_OUT is set by a previous call to curl_setopt())
Note that private data is not included in the associative array and must be retrieved individually with the CURLINFO_PRIVATE option.

Changelog

Version | Description
7.3.0 | Introduced CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, CURLINFO_CONTENT_LENGTH_UPLOAD_T, CURLINFO_HTTP_VERSION, CURLINFO_PROTOCOL, CURLINFO_PROXY_SSL_VERIFYRESULT, CURLINFO_SCHEME, CURLINFO_SIZE_DOWNLOAD_T, CURLINFO_SIZE_UPLOAD_T, CURLINFO_SPEED_DOWNLOAD_T, CURLINFO_SPEED_UPLOAD_T, CURLINFO_APPCONNECT_TIME_T, CURLINFO_CONNECT_TIME_T, CURLINFO_FILETIME_T, CURLINFO_NAMELOOKUP_TIME_T, CURLINFO_PRETRANSFER_TIME_T, CURLINFO_REDIRECT_TIME_T, CURLINFO_STARTTRANSFER_TIME_T, CURLINFO_TOTAL_TIME_T.
5.5.0 | Introduced CURLINFO_RESPONSE_CODE, CURLINFO_HTTP_CONNECTCODE, CURLINFO_HTTPAUTH_AVAIL, CURLINFO_PROXYAUTH_AVAIL, CURLINFO_OS_ERRNO, CURLINFO_NUM_CONNECTS, CURLINFO_SSL_ENGINES, CURLINFO_COOKIELIST, CURLINFO_FTP_ENTRY_PATH, CURLINFO_APPCONNECT_TIME, CURLINFO_CONDITION_UNMET, CURLINFO_RTSP_CLIENT_CSEQ, CURLINFO_RTSP_CSEQ_RECV, CURLINFO_RTSP_SERVER_CSEQ and CURLINFO_RTSP_SESSION_ID.
5.4.7 | Introduced CURLINFO_PRIMARY_IP, CURLINFO_PRIMARY_PORT, CURLINFO_LOCAL_IP and CURLINFO_LOCAL_PORT.
5.3.7 | Introduced CURLINFO_REDIRECT_URL.
5.3.0 | Introduced CURLINFO_CERTINFO.
5.2.4 | Introduced CURLINFO_PRIVATE.
5.1.3 | Introduced CURLINFO_HEADER_OUT.

Examples

Example #1 curl_getinfo() example

<?php
// Create a cURL handle
$ch = curl_init('http://www.example.com/');

// Execute
curl_exec($ch);

// Check if any error occurred
if (!curl_errno($ch)) {
  $info = curl_getinfo($ch);
  echo 'Took ', $info['total_time'], ' seconds to send a request to ', $info['url'], "\n";
}

// Close handle
curl_close($ch);
?>

Example #2 curl_getinfo() example with opt parameter

<?php
// Create a cURL handle
$ch = curl_init('http://www.example.com/');

// Execute
curl_exec($ch);

// Check HTTP status code
if (!curl_errno($ch)) {
  switch ($http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE)) {
    case 200:  # OK
      break;
    default:
      echo 'Unexpected HTTP code: ', $http_code, "\n";
  }
}

// Close handle
curl_close($ch);
?>

Notes

Note:

Information gathered by this function is kept if the handle is re-used. This means that unless a statistic is overridden internally by this function, the previous info is returned.


Initialize a cURL session

  • « curl_getinfo
  • curl_multi_add_handle »
  • PHP Manual
  • cURL Functions
  • Initialize a cURL session

curl_init

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

curl_init — Initialize a cURL session

Description

curl_init ([ string $url = NULL ] ) : resource

Initializes a new session and return a cURL handle for use with the curl_setopt(), curl_exec(), and curl_close() functions.

Parameters

url

If provided, the CURLOPT_URL option will be set to its value. You can manually set this using the curl_setopt() function.

Note:

The file protocol is disabled by cURL if open_basedir is set.

Return Values

Returns a cURL handle on success, FALSE on errors.

Examples

Example #1 Initializing a new cURL session and fetching a web page

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
?>

See Also

  • curl_close() - Close a cURL session
  • curl_multi_init() - Returns a new cURL multi handle


Add a normal cURL handle to a cURL multi handle

  • « curl_init
  • curl_multi_close »
  • PHP Manual
  • cURL Functions
  • Add a normal cURL handle to a cURL multi handle

curl_multi_add_handle

(PHP 5, PHP 7)

curl_multi_add_handle — Add a normal cURL handle to a cURL multi handle

Description

curl_multi_add_handle ( resource $mh , resource $ch ) : int

Adds the ch handle to the multi handle mh

Parameters

mh

A cURL multi handle returned by curl_multi_init().

ch

A cURL handle returned by curl_init().

Return Values

Returns 0 on success, or one of the CURLM_XXX errors code.

Examples

Example #1 curl_multi_add_handle() example

This example will create two cURL handles, add them to a multi handle, and process them asynchronously.

<?php
// create both cURL resources
$ch1 = curl_init();
$ch2 = curl_init();

// set URL and other appropriate options
curl_setopt($ch1, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);

//create the multiple cURL handle
$mh = curl_multi_init();

//add the two handles
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

//execute the multi handle
do {
    $status = curl_multi_exec($mh, $active);
    if ($active) {
        curl_multi_select($mh);
    }
} while ($active && $status == CURLM_OK);

//close all the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);
?>

See Also

  • curl_multi_remove_handle() - Remove a multi handle from a set of cURL handles
  • curl_multi_init() - Returns a new cURL multi handle
  • curl_init() - Initialize a cURL session


Close a set of cURL handles

  • « curl_multi_add_handle
  • curl_multi_errno »
  • PHP Manual
  • cURL Functions
  • Close a set of cURL handles

curl_multi_close

(PHP 5, PHP 7)

curl_multi_close — Close a set of cURL handles

Description

curl_multi_close ( resource $mh ) : void

Closes a set of cURL handles.

Parameters

mh

A cURL multi handle returned by curl_multi_init().

Return Values

No value is returned.

Examples

Example #1 curl_multi_close() example

This example will create two cURL handles, add them to a multi handle, and process them asynchronously.

<?php
// create both cURL resources
$ch1 = curl_init();
$ch2 = curl_init();

// set URL and other appropriate options
curl_setopt($ch1, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);

//create the multiple cURL handle
$mh = curl_multi_init();

//add the two handles
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

//execute the multi handle
do {
    $status = curl_multi_exec($mh, $active);
    if ($active) {
        curl_multi_select($mh);
    }
} while ($active && $status == CURLM_OK);

//close the handles
curl_multi_remove_handle($mh, $ch1);
curl_close($ch1);
curl_multi_remove_handle($mh, $ch2);
curl_close($ch2);
curl_multi_close($mh);

?>

See Also

  • curl_multi_init() - Returns a new cURL multi handle
  • curl_close() - Close a cURL session


Return the last multi curl error number

  • « curl_multi_close
  • curl_multi_exec »
  • PHP Manual
  • cURL Functions
  • Return the last multi curl error number

curl_multi_errno

(PHP 7 >= 7.1.0)

curl_multi_errno — Return the last multi curl error number

Description

curl_multi_errno ( resource $mh ) : int

Return an integer containing the last multi curl error number.

Parameters

mh

A cURL multi handle returned by curl_multi_init().

Return Values

Return an integer containing the last multi curl error number, or FALSE on failure.

See Also

  • curl_errno() - Return the last error number


Run the sub-connections of the current cURL handle

  • « curl_multi_errno
  • curl_multi_getcontent »
  • PHP Manual
  • cURL Functions
  • Run the sub-connections of the current cURL handle

curl_multi_exec

(PHP 5, PHP 7)

curl_multi_exec — Run the sub-connections of the current cURL handle

Description

curl_multi_exec ( resource $mh , int &$still_running ) : int

Processes each of the handles in the stack. This method can be called whether or not a handle needs to read or write data.

Parameters

mh

A cURL multi handle returned by curl_multi_init().

still_running

A reference to a flag to tell whether the operations are still running.

Return Values

A cURL code defined in the cURL Predefined Constants.

Note:

This only returns errors regarding the whole multi stack. There might still have occurred problems on individual transfers even when this function returns CURLM_OK.

Examples

Example #1 curl_multi_exec() example

This example will create two cURL handles, add them to a multi handle, and process them asynchronously.

<?php
// create both cURL resources
$ch1 = curl_init();
$ch2 = curl_init();

// set URL and other appropriate options
curl_setopt($ch1, CURLOPT_URL, "http://example.com/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);

//create the multiple cURL handle
$mh = curl_multi_init();

//add the two handles
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

//execute the multi handle
do {
    $status = curl_multi_exec($mh, $active);
    if ($active) {
        // Wait a short time for more activity
        curl_multi_select($mh);
    }
} while ($active && $status == CURLM_OK);

//close the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);

?>

See Also

  • curl_multi_init() - Returns a new cURL multi handle
  • curl_multi_select() - Wait for activity on any curl_multi connection
  • curl_exec() - Perform a cURL session


Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set

  • « curl_multi_exec
  • curl_multi_info_read »
  • PHP Manual
  • cURL Functions
  • Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set

curl_multi_getcontent

(PHP 5, PHP 7)

curl_multi_getcontent — Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set

Description

curl_multi_getcontent ( resource $ch ) : string

If CURLOPT_RETURNTRANSFER is an option that is set for a specific handle, then this function will return the content of that cURL handle in the form of a string.

Parameters

ch

A cURL handle returned by curl_init().

Return Values

Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set.

See Also

  • curl_multi_init() - Returns a new cURL multi handle


Get information about the current transfers

  • « curl_multi_getcontent
  • curl_multi_init »
  • PHP Manual
  • cURL Functions
  • Get information about the current transfers

curl_multi_info_read

(PHP 5, PHP 7)

curl_multi_info_read — Get information about the current transfers

Description

curl_multi_info_read ( resource $mh [, int &$msgs_in_queue = NULL ] ) : array

Ask the multi handle if there are any messages or information from the individual transfers. Messages may include information such as an error code from the transfer or just the fact that a transfer is completed.

Repeated calls to this function will return a new result each time, until a FALSE is returned as a signal that there is no more to get at this point. The integer pointed to with msgs_in_queue will contain the number of remaining messages after this function was called.

Warning

The data the returned resource points to will not survive calling curl_multi_remove_handle().

Parameters

mh

A cURL multi handle returned by curl_multi_init().

msgs_in_queue

Number of messages that are still in the queue

Return Values

On success, returns an associative array for the message, FALSE on failure.

Contents of the returned array
Key: | Value:
msg | The CURLMSG_DONE constant. Other return values are currently not available.
result | One of the CURLE_* constants. If everything is OK, the CURLE_OK will be the result.
handle | Resource of type curl indicates the handle which it concerns.

Examples

Example #1 A curl_multi_info_read() example

<?php

$urls = array(
   "http://www.cnn.com/",
   "http://www.bbc.co.uk/",
   "http://www.yahoo.com/"
);

$mh = curl_multi_init();

foreach ($urls as $i => $url) {
    $conn[$i] = curl_init($url);
    curl_setopt($conn[$i], CURLOPT_RETURNTRANSFER, 1);
    curl_multi_add_handle($mh, $conn[$i]);
}

do {
    $status = curl_multi_exec($mh, $active);
    if ($active) {
        curl_multi_select($mh);
    }
    $info = curl_multi_info_read($mh);
    if (false !== $info) {
        var_dump($info);
    }
} while ($active && $status == CURLM_OK);

foreach ($urls as $i => $url) {
    $res[$i] = curl_multi_getcontent($conn[$i]);
    curl_close($conn[$i]);
}

var_dump(curl_multi_info_read($mh));

?>

The above example will output something similar to:

array(3) {
  ["msg"]=>
  int(1)
  ["result"]=>
  int(0)
  ["handle"]=>
  resource(5) of type (curl)
}
array(3) {
  ["msg"]=>
  int(1)
  ["result"]=>
  int(0)
  ["handle"]=>
  resource(7) of type (curl)
}
array(3) {
  ["msg"]=>
  int(1)
  ["result"]=>
  int(0)
  ["handle"]=>
  resource(6) of type (curl)
}
bool(false)

Changelog

Version | Description
5.2.0 | msgs_in_queue was added.

See Also

  • curl_multi_init() - Returns a new cURL multi handle


Returns a new cURL multi handle

  • « curl_multi_info_read
  • curl_multi_remove_handle »
  • PHP Manual
  • cURL Functions
  • Returns a new cURL multi handle

curl_multi_init

(PHP 5, PHP 7)

curl_multi_init — Returns a new cURL multi handle

Description

curl_multi_init ( void ) : resource

Allows the processing of multiple cURL handles asynchronously.

Parameters

This function has no parameters.

Return Values

Returns a cURL multi handle resource on success, FALSE on failure.

Examples

Example #1 curl_multi_init() example

This example will create two cURL handles, add them to a multi handle, and process them asynchronously.

<?php
// create both cURL resources
$ch1 = curl_init();
$ch2 = curl_init();

// set URL and other appropriate options
curl_setopt($ch1, CURLOPT_URL, "http://lxr.php.net/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);

//create the multiple cURL handle
$mh = curl_multi_init();

//add the two handles
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

//execute the multi handle
do {
    $status = curl_multi_exec($mh, $active);
    if ($active) {
        curl_multi_select($mh);
    }
} while ($active && $status == CURLM_OK);

//close the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);

?>

See Also

  • curl_init() - Initialize a cURL session
  • curl_multi_close() - Close a set of cURL handles


Remove a multi handle from a set of cURL handles

  • « curl_multi_init
  • curl_multi_select »
  • PHP Manual
  • cURL Functions
  • Remove a multi handle from a set of cURL handles

curl_multi_remove_handle

(PHP 5, PHP 7)

curl_multi_remove_handle — Remove a multi handle from a set of cURL handles

Description

curl_multi_remove_handle ( resource $mh , resource $ch ) : int

Removes a given ch handle from the given mh handle. When the ch handle has been removed, it is again perfectly legal to run curl_exec() on this handle. Removing the ch handle while being used, will effectively halt the transfer in progress involving that handle.

Parameters

mh

A cURL multi handle returned by curl_multi_init().

ch

A cURL handle returned by curl_init().

Return Values

Returns 0 on success, or one of the CURLM_XXX error codes.

See Also

  • curl_init() - Initialize a cURL session
  • curl_multi_init() - Returns a new cURL multi handle
  • curl_multi_add_handle() - Add a normal cURL handle to a cURL multi handle


Wait for activity on any curl_multi connection

  • « curl_multi_remove_handle
  • curl_multi_setopt »
  • PHP Manual
  • cURL Functions
  • Wait for activity on any curl_multi connection

curl_multi_select

(PHP 5, PHP 7)

curl_multi_select — Wait for activity on any curl_multi connection

Description

curl_multi_select ( resource $mh [, float $timeout = 1.0 ] ) : int

Blocks until there is activity on any of the curl_multi connections.

Parameters

mh

A cURL multi handle returned by curl_multi_init().

timeout

Time, in seconds, to wait for a response.

Return Values

On success, returns the number of descriptors contained in the descriptor sets. This may be 0 if there was no activity on any of the descriptors. On failure, this function will return -1 on a select failure (from the underlying select system call).

See Also

  • curl_multi_init() - Returns a new cURL multi handle


Set an option for the cURL multi handle

  • « curl_multi_select
  • curl_multi_strerror »
  • PHP Manual
  • cURL Functions
  • Set an option for the cURL multi handle

curl_multi_setopt

(PHP 5 >= 5.5.0, PHP 7)

curl_multi_setopt — Set an option for the cURL multi handle

Description

curl_multi_setopt ( resource $mh , int $option , mixed $value ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

mh

option

One of the CURLMOPT_* constants.

value

The value to be set on option.

value should be an int for the following values of the option parameter:

Option | Set value to
CURLMOPT_PIPELINING | Pass 1 to enable or 0 to disable. Enabling pipelining on a multi handle will make it attempt to perform HTTP Pipelining as far as possible for transfers using this handle. This means that if you add a second request that can use an already existing connection, the second request will be "piped" on the same connection. As of cURL 7.43.0, the value is a bitmask, and you can also pass 2 to try to multiplex the new transfer over an existing HTTP/2 connection if possible. Passing 3 instructs cURL to ask for pipelining and multiplexing independently of each other. As of cURL 7.62.0, setting the pipelining bit has no effect. Instead of integer literals, you can also use the CURLPIPE_* constants if available.
CURLMOPT_MAXCONNECTS | Pass a number that will be used as the maximum amount of simultaneously open connections that libcurl may cache. By default the size will be enlarged to fit four times the number of handles added via curl_multi_add_handle(). When the cache is full, curl closes the oldest one in the cache to prevent the number of open connections from increasing.
CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE | Pass a number that specifies the chunk length threshold for pipelining in bytes.
CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE | Pass a number that specifies the size threshold for pipelining penalty in bytes.
CURLMOPT_MAX_HOST_CONNECTIONS | Pass a number that specifies the maximum number of connections to a single host.
CURLMOPT_MAX_PIPELINE_LENGTH | Pass a number that specifies the maximum number of requests in a pipeline.
CURLMOPT_MAX_TOTAL_CONNECTIONS | Pass a number that specifies the maximum number of simultaneously open connections.
CURLMOPT_PUSHFUNCTION Pass a callable that will be registered to handle server pushes and should have the following signature:
pushfunction ( resource $parent_ch , resource $pushed_ch , array $headers ) : int
parent_ch

The parent cURL handle (the request the client made).

pushed_ch

A new cURL handle for the pushed request.

headers

The push promise headers.

The push function is supposed to return either CURL_PUSH_OK if it can handle the push, or CURL_PUSH_DENY to reject it.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.1.0 | Introduced CURLMOPT_PUSHFUNCTION.
7.0.7 | Introduced CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE, CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE, CURLMOPT_MAX_HOST_CONNECTIONS, CURLMOPT_MAX_PIPELINE_LENGTH and CURLMOPT_MAX_TOTAL_CONNECTIONS.


Return string describing error code

  • « curl_multi_setopt
  • curl_pause »
  • PHP Manual
  • cURL Functions
  • Return string describing error code

curl_multi_strerror

(PHP 5 >= 5.5.0, PHP 7)

curl_multi_strerror — Return string describing error code

Description

curl_multi_strerror ( int $errornum ) : string

Returns a text error message describing the given CURLM error code.

Parameters

errornum

One of the » CURLM error codes constants.

Return Values

Returns error string for valid error code, NULL otherwise.

Examples

Example #1 curl_multi_strerror() example

<?php
// Create cURL handles
$ch1 = curl_init("http://example.com"/);
$ch2 = curl_init("http://php.net/");

// Create a cURL multi handle
$mh = curl_multi_init();

// Add the handles to the multi handle
curl_multi_add_handle($mh, $ch1);
curl_multi_add_handle($mh, $ch2);

// Execute the multi handle
do {
    $status = curl_multi_exec($mh, $active);
    if ($active) {
        curl_multi_select($mh);
    }
} while ($active && $status === CURLM_OK);

// Check for errors
if ($status != CURLM_OK) {
    // Display error message
    echo "ERROR!\n " . curl_multi_strerror($status);
}

?>

See Also

  • curl_strerror() - Return string describing the given error code
  • » cURL error codes


Pause and unpause a connection

  • « curl_multi_strerror
  • curl_reset »
  • PHP Manual
  • cURL Functions
  • Pause and unpause a connection

curl_pause

(PHP 5 >= 5.5.0, PHP 7)

curl_pause — Pause and unpause a connection

Description

curl_pause ( resource $ch , int $bitmask ) : int

Warning

This function is currently not documented; only its argument list is available.

Parameters

ch

A cURL handle returned by curl_init().

bitmask

One of CURLPAUSE_* constants.

Return Values

Returns an error code (CURLE_OK for no error).


Reset all options of a libcurl session handle

  • « curl_pause
  • curl_setopt_array »
  • PHP Manual
  • cURL Functions
  • Reset all options of a libcurl session handle

curl_reset

(PHP 5 >= 5.5.0, PHP 7)

curl_reset — Reset all options of a libcurl session handle

Description

curl_reset ( resource $ch ) : void

This function re-initializes all options set on the given cURL handle to the default values.

Parameters

ch

A cURL handle returned by curl_init().

Return Values

No value is returned.

Examples

Example #1 curl_reset() example

<?php
// Create a curl handle
$ch = curl_init();

// Set CURLOPT_USERAGENT option
curl_setopt($ch, CURLOPT_USERAGENT, "My test user-agent");

// Reset all previously set options
curl_reset($ch);

// Send HTTP request
curl_setopt($ch, CURLOPT_URL, 'http://example.com/');
curl_exec($ch); // the previously set user-agent will be not sent, it has been reset by curl_reset

// Close the handle
curl_close($ch);
?>

Notes

Note:

curl_reset() also resets the URL given as the curl_init() parameter.

See Also

  • curl_setopt() - Set an option for a cURL transfer


Set multiple options for a cURL transfer

  • « curl_reset
  • curl_setopt »
  • PHP Manual
  • cURL Functions
  • Set multiple options for a cURL transfer

curl_setopt_array

(PHP 5 >= 5.1.3, PHP 7)

curl_setopt_array — Set multiple options for a cURL transfer

Description

curl_setopt_array ( resource $ch , array $options ) : bool

Sets multiple options for a cURL session. This function is useful for setting a large number of cURL options without repetitively calling curl_setopt().

Parameters

ch

A cURL handle returned by curl_init().

options

An array specifying which options to set and their values. The keys should be valid curl_setopt() constants or their integer equivalents.

Return Values

Returns TRUE if all options were successfully set. If an option could not be successfully set, FALSE is immediately returned, ignoring any future options in the options array.

Examples

Example #1 Initializing a new cURL session and fetching a web page

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
$options = array(CURLOPT_URL => 'http://www.example.com/',
                 CURLOPT_HEADER => false
                );

curl_setopt_array($ch, $options);

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
?>

Prior to PHP 5.1.3 this function can be simulated with:

Example #2 Our own implementation of curl_setopt_array()

<?php
if (!function_exists('curl_setopt_array')) {
   function curl_setopt_array(&$ch, $curl_options)
   {
       foreach ($curl_options as $option => $value) {
           if (!curl_setopt($ch, $option, $value)) {
               return false;
           }
       }
       return true;
   }
}
?>

Notes

Note:

As with curl_setopt(), passing an array to CURLOPT_POST will encode the data as multipart/form-data, while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded.

See Also

  • curl_setopt() - Set an option for a cURL transfer


Set an option for a cURL transfer

  • « curl_setopt_array
  • curl_share_close »
  • PHP Manual
  • cURL Functions
  • Set an option for a cURL transfer

curl_setopt

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

curl_setopt — Set an option for a cURL transfer

Description

curl_setopt ( resource $ch , int $option , mixed $value ) : bool

Sets an option on the given cURL session handle.

Parameters

ch

A cURL handle returned by curl_init().

option

The CURLOPT_XXX option to set.

value

The value to be set on option.

value should be a bool for the following values of the option parameter:

Option | Set value to | Notes
CURLOPT_AUTOREFERER | TRUE to automatically set the Referer: field in requests where it follows a Location: redirect.
CURLOPT_BINARYTRANSFER | TRUE to return the raw output when CURLOPT_RETURNTRANSFER is used. | From PHP 5.1.3, this option has no effect: the raw output will always be returned when CURLOPT_RETURNTRANSFER is used.
CURLOPT_COOKIESESSION | TRUE to mark this as a new cookie "session". It will force libcurl to ignore all cookies it is about to load that are "session cookies" from the previous session. By default, libcurl always stores and loads all cookies, independent if they are session cookies or not. Session cookies are cookies without expiry date and they are meant to be alive and existing for this "session" only.
CURLOPT_CERTINFO | TRUE to output SSL certification information to STDERR on secure transfers. | Added in cURL 7.19.1. Available since PHP 5.3.2. Requires CURLOPT_VERBOSE to be on to have an effect.
CURLOPT_CONNECT_ONLY | TRUE tells the library to perform all the required proxy authentication and connection setup, but no data transfer. This option is implemented for HTTP, SMTP and POP3. | Added in 7.15.2. Available since PHP 5.5.0.
CURLOPT_CRLF | TRUE to convert Unix newlines to CRLF newlines on transfers.
CURLOPT_DISALLOW_USERNAME_IN_URL | TRUE to not allow URLs that include a username. Usernames are allowed by default (0). | Added in cURL 7.61.0. Available since PHP 7.3.0.
CURLOPT_DNS_SHUFFLE_ADDRESSES | TRUE to shuffle the order of all returned addresses so that they will be used in a random order, when a name is resolved and more than one IP address is returned. This may cause IPv4 to be used before IPv6 or vice versa. | Added in cURL 7.60.0. Available since PHP 7.3.0.
CURLOPT_HAPROXYPROTOCOL | TRUE to send an HAProxy PROXY protocol v1 header at the start of the connection. The default action is not to send this header. | Added in cURL 7.60.0. Available since PHP 7.3.0.
CURLOPT_SSH_COMPRESSION | TRUE to enable built-in SSH compression. This is a request, not an order; the server may or may not do it. | Added in cURL 7.56.0. Available since PHP 7.3.0.
CURLOPT_DNS_USE_GLOBAL_CACHE | TRUE to use a global DNS cache. This option is not thread-safe. It is conditionally enabled by default if PHP is built for non-threaded use (CLI, FCGI, Apache2-Prefork, etc.).
CURLOPT_FAILONERROR | TRUE to fail verbosely if the HTTP code returned is greater than or equal to 400. The default behavior is to return the page normally, ignoring the code.
CURLOPT_SSL_FALSESTART | TRUE to enable TLS false start. | Added in cURL 7.42.0. Available since PHP 7.0.7.
CURLOPT_FILETIME | TRUE to attempt to retrieve the modification date of the remote document. This value can be retrieved using the CURLINFO_FILETIME option with curl_getinfo().
CURLOPT_FOLLOWLOCATION | TRUE to follow any "Location: " header that the server sends as part of the HTTP header (note this is recursive, PHP will follow as many "Location: " headers that it is sent, unless CURLOPT_MAXREDIRS is set).
CURLOPT_FORBID_REUSE | TRUE to force the connection to explicitly close when it has finished processing, and not be pooled for reuse.
CURLOPT_FRESH_CONNECT | TRUE to force the use of a new connection instead of a cached one.
CURLOPT_FTP_USE_EPRT | TRUE to use EPRT (and LPRT) when doing active FTP downloads. Use FALSE to disable EPRT and LPRT and use PORT only.
CURLOPT_FTP_USE_EPSV | TRUE to first try an EPSV command for FTP transfers before reverting back to PASV. Set to FALSE to disable EPSV.
CURLOPT_FTP_CREATE_MISSING_DIRS | TRUE to create missing directories when an FTP operation encounters a path that currently doesn't exist.
CURLOPT_FTPAPPEND | TRUE to append to the remote file instead of overwriting it.
CURLOPT_TCP_NODELAY | TRUE to disable TCP's Nagle algorithm, which tries to minimize the number of small packets on the network. | Available since PHP 5.2.1 for versions compiled with libcurl 7.11.2 or greater.
CURLOPT_FTPASCII | An alias of CURLOPT_TRANSFERTEXT. Use that instead.
CURLOPT_FTPLISTONLY | TRUE to only list the names of an FTP directory.
CURLOPT_HEADER | TRUE to include the header in the output.
CURLINFO_HEADER_OUT | TRUE to track the handle's request string. | Available since PHP 5.1.3. The CURLINFO_ prefix is intentional.
CURLOPT_HTTP09_ALLOWED | Whether to allow HTTP/0.9 responses. Defaults to FALSE as of libcurl 7.66.0; formerly it defaulted to TRUE. | Available since PHP 7.3.15 and 7.4.3, respectively, if built against libcurl >= 7.64.0
CURLOPT_HTTPGET | TRUE to reset the HTTP request method to GET. Since GET is the default, this is only necessary if the request method has been changed.
CURLOPT_HTTPPROXYTUNNEL | TRUE to tunnel through a given HTTP proxy.
CURLOPT_HTTP_CONTENT_DECODING | FALSE to get the raw HTTP response body. | Available as of PHP 5.5.0 if built against libcurl >= 7.16.2.
CURLOPT_KEEP_SENDING_ON_ERROR | TRUE to keep sending the request body if the HTTP code returned is equal to or larger than 300. The default action would be to stop sending and close the stream or connection. Suitable for manual NTLM authentication. Most applications do not need this option. | Available as of PHP 7.3.0 if built against libcurl >= 7.51.0.
CURLOPT_MUTE | TRUE to be completely silent with regards to the cURL functions. | Removed in cURL 7.15.5 (You can use CURLOPT_RETURNTRANSFER instead)
CURLOPT_NETRC | TRUE to scan the ~/.netrc file to find a username and password for the remote site that a connection is being established with.
CURLOPT_NOBODY | TRUE to exclude the body from the output. Request method is then set to HEAD. Changing this to FALSE does not change it to GET.
CURLOPT_NOPROGRESS

TRUE to disable the progress meter for cURL transfers.

Note:

PHP automatically sets this option to TRUE, this should only be changed for debugging purposes.

CURLOPT_NOSIGNAL | TRUE to ignore any cURL function that causes a signal to be sent to the PHP process. This is turned on by default in multi-threaded SAPIs so timeout options can still be used. | Added in cURL 7.10.
CURLOPT_PATH_AS_IS | TRUE to not handle dot dot sequences. | Added in cURL 7.42.0. Available since PHP 7.0.7.
CURLOPT_PIPEWAIT | TRUE to wait for pipelining/multiplexing. | Added in cURL 7.43.0. Available since PHP 7.0.7.
CURLOPT_POST | TRUE to do a regular HTTP POST. This POST is the normal application/x-www-form-urlencoded kind, most commonly used by HTML forms.
CURLOPT_PUT | TRUE to HTTP PUT a file. The file to PUT must be set with CURLOPT_INFILE and CURLOPT_INFILESIZE.
CURLOPT_RETURNTRANSFER | TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it directly.
CURLOPT_SAFE_UPLOAD | TRUE to disable support for the @ prefix for uploading files in CURLOPT_POSTFIELDS, which means that values starting with @ can be safely passed as fields. CURLFile may be used for uploads instead. | Added in PHP 5.5.0 with FALSE as the default value. PHP 5.6.0 changes the default value to TRUE. PHP 7 removes this option; the CURLFile interface must be used to upload files.
CURLOPT_SASL_IR | TRUE to enable sending the initial response in the first packet. | Added in cURL 7.31.10. Available since PHP 7.0.7.
CURLOPT_SSL_ENABLE_ALPN | FALSE to disable ALPN in the SSL handshake (if the SSL backend libcurl is built to use supports it), which can be used to negotiate http2. | Added in cURL 7.36.0. Available since PHP 7.0.7.
CURLOPT_SSL_ENABLE_NPN | FALSE to disable NPN in the SSL handshake (if the SSL backend libcurl is built to use supports it), which can be used to negotiate http2. | Added in cURL 7.36.0. Available since PHP 7.0.7.
CURLOPT_SSL_VERIFYPEER | FALSE to stop cURL from verifying the peer's certificate. Alternate certificates to verify against can be specified with the CURLOPT_CAINFO option or a certificate directory can be specified with the CURLOPT_CAPATH option. | TRUE by default as of cURL 7.10. Default bundle installed as of cURL 7.10.
CURLOPT_SSL_VERIFYSTATUS | TRUE to verify the certificate's status. | Added in cURL 7.41.0. Available since PHP 7.0.7.
CURLOPT_PROXY_SSL_VERIFYPEER | FALSE to stop cURL from verifying the peer's certificate. Alternate certificates to verify against can be specified with the CURLOPT_CAINFO option or a certificate directory can be specified with the CURLOPT_CAPATH option. When set to false, the peer certificate verification succeeds regardless. | TRUE by default. Available since PHP 7.3.0 and libcurl >= cURL 7.52.0.
CURLOPT_SUPPRESS_CONNECT_HEADERS | TRUE to suppress proxy CONNECT response headers from the user callback functions CURLOPT_HEADERFUNCTION and CURLOPT_WRITEFUNCTION, when CURLOPT_HTTPPROXYTUNNEL is used and a CONNECT request is made. | Added in cURL 7.54.0. Available since PHP 7.3.0.
CURLOPT_TCP_FASTOPEN | TRUE to enable TCP Fast Open. | Added in cURL 7.49.0. Available since PHP 7.0.7.
CURLOPT_TFTP_NO_OPTIONS | TRUE to not send TFTP options requests. | Added in cURL 7.48.0. Available since PHP 7.0.7.
CURLOPT_TRANSFERTEXT | TRUE to use ASCII mode for FTP transfers. For LDAP, it retrieves data in plain text instead of HTML. On Windows systems, it will not set STDOUT to binary mode.
CURLOPT_UNRESTRICTED_AUTH | TRUE to keep sending the username and password when following locations (using CURLOPT_FOLLOWLOCATION), even when the hostname has changed.
CURLOPT_UPLOAD | TRUE to prepare for an upload.
CURLOPT_VERBOSE | TRUE to output verbose information. Writes output to STDERR, or the file specified using CURLOPT_STDERR.

value should be an integer for the following values of the option parameter:

Option | Set value to | Notes
CURLOPT_BUFFERSIZE | The size of the buffer to use for each read. There is no guarantee this request will be fulfilled, however. | Added in cURL 7.10.
CURLOPT_CLOSEPOLICY One of the CURLCLOSEPOLICY_* values.

Note:

This option is deprecated, as it was never implemented in cURL and never had any effect.

Removed in PHP 5.6.0.
CURLOPT_CONNECTTIMEOUT | The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.
CURLOPT_CONNECTTIMEOUT_MS | The number of milliseconds to wait while trying to connect. Use 0 to wait indefinitely. If libcurl is built to use the standard system name resolver, that portion of the connect will still use full-second resolution for timeouts with a minimum timeout allowed of one second. | Added in cURL 7.16.2. Available since PHP 5.2.3.
CURLOPT_DNS_CACHE_TIMEOUT | The number of seconds to keep DNS entries in memory. This option is set to 120 (2 minutes) by default.
CURLOPT_EXPECT_100_TIMEOUT_MS | The timeout for Expect: 100-continue responses in milliseconds. Defaults to 1000 milliseconds. | Added in cURL 7.36.0. Available since PHP 7.0.7.
CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS | Head start for ipv6 for the happy eyeballs algorithm. Happy eyeballs attempts to connect to both IPv4 and IPv6 addresses for dual-stack hosts, preferring IPv6 first for timeout milliseconds. Defaults to CURL_HET_DEFAULT, which is currently 200 milliseconds. | Added in cURL 7.59.0. Available since PHP 7.3.0.
CURLOPT_FTPSSLAUTH | The FTP authentication method (when is activated): CURLFTPAUTH_SSL (try SSL first), CURLFTPAUTH_TLS (try TLS first), or CURLFTPAUTH_DEFAULT (let cURL decide). | Added in cURL 7.12.2.
CURLOPT_HEADEROPT | How to deal with headers. One of the following constants: CURLHEADER_UNIFIED: the headers specified in CURLOPT_HTTPHEADER will be used in requests both to servers and proxies. With this option enabled, CURLOPT_PROXYHEADER will not have any effect. CURLHEADER_SEPARATE: makes CURLOPT_HTTPHEADER headers only get sent to a server and not to a proxy. Proxy headers must be set with CURLOPT_PROXYHEADER to get used. Note that if a non-CONNECT request is sent to a proxy, libcurl will send both server headers and proxy headers. When doing CONNECT, libcurl will send CURLOPT_PROXYHEADER headers only to the proxy and then CURLOPT_HTTPHEADER headers only to the server. Defaults to CURLHEADER_SEPARATE as of cURL 7.42.1, and CURLHEADER_UNIFIED before. | Added in cURL 7.37.0. Available since PHP 7.0.7.
CURLOPT_HTTP_VERSION | CURL_HTTP_VERSION_NONE (default, lets CURL decide which version to use), CURL_HTTP_VERSION_1_0 (forces HTTP/1.0), or CURL_HTTP_VERSION_1_1 (forces HTTP/1.1).
CURLOPT_HTTPAUTH

The HTTP authentication method(s) to use. The options are: CURLAUTH_BASIC, CURLAUTH_DIGEST, CURLAUTH_GSSNEGOTIATE, CURLAUTH_NTLM, CURLAUTH_ANY, and CURLAUTH_ANYSAFE.

The bitwise | (or) operator can be used to combine more than one method. If this is done, cURL will poll the server to see what methods it supports and pick the best one.

CURLAUTH_ANY is an alias for CURLAUTH_BASIC | CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM.

CURLAUTH_ANYSAFE is an alias for CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM.

CURLOPT_INFILESIZE | The expected size, in bytes, of the file when uploading a file to a remote site. Note that using this option will not stop libcurl from sending more data, as exactly what is sent depends on CURLOPT_READFUNCTION.
CURLOPT_LOW_SPEED_LIMIT | The transfer speed, in bytes per second, that the transfer should be below during the count of CURLOPT_LOW_SPEED_TIME seconds before PHP considers the transfer too slow and aborts.
CURLOPT_LOW_SPEED_TIME | The number of seconds the transfer speed should be below CURLOPT_LOW_SPEED_LIMIT before PHP considers the transfer too slow and aborts.
CURLOPT_MAXCONNECTS | The maximum amount of persistent connections that are allowed. When the limit is reached, CURLOPT_CLOSEPOLICY is used to determine which connection to close.
CURLOPT_MAXREDIRS | The maximum amount of HTTP redirections to follow. Use this option alongside CURLOPT_FOLLOWLOCATION.
CURLOPT_PORT | An alternative port number to connect to.
CURLOPT_POSTREDIR | A bitmask of 1 (301 Moved Permanently), 2 (302 Found) and 4 (303 See Other) if the HTTP POST method should be maintained when CURLOPT_FOLLOWLOCATION is set and a specific type of redirect occurs. | Added in cURL 7.19.1. Available since PHP 5.3.2.
CURLOPT_PROTOCOLS

Bitmask of CURLPROTO_* values. If used, this bitmask limits what protocols libcurl may use in the transfer. This allows you to have a libcurl built to support a wide range of protocols but still limit specific transfers to only be allowed to use a subset of them. By default libcurl will accept all protocols it supports. See also CURLOPT_REDIR_PROTOCOLS.

Valid protocol options are: CURLPROTO_HTTP, CURLPROTO_HTTPS, CURLPROTO_FTP, CURLPROTO_FTPS, CURLPROTO_SCP, CURLPROTO_SFTP, CURLPROTO_TELNET, CURLPROTO_LDAP, CURLPROTO_LDAPS, CURLPROTO_DICT, CURLPROTO_FILE, CURLPROTO_TFTP, CURLPROTO_ALL

Added in cURL 7.19.4.
CURLOPT_PROXYAUTH | The HTTP authentication method(s) to use for the proxy connection. Use the same bitmasks as described in CURLOPT_HTTPAUTH. For proxy authentication, only CURLAUTH_BASIC and CURLAUTH_NTLM are currently supported. | Added in cURL 7.10.7.
CURLOPT_PROXYPORT | The port number of the proxy to connect to. This port number can also be set in CURLOPT_PROXY.
CURLOPT_PROXYTYPE | Either CURLPROXY_HTTP (default), CURLPROXY_SOCKS4, CURLPROXY_SOCKS5, CURLPROXY_SOCKS4A or CURLPROXY_SOCKS5_HOSTNAME. | Added in cURL 7.10.
CURLOPT_REDIR_PROTOCOLS | Bitmask of CURLPROTO_* values. If used, this bitmask limits what protocols libcurl may use in a transfer that it follows to in a redirect when CURLOPT_FOLLOWLOCATION is enabled. This allows you to limit specific transfers to only be allowed to use a subset of protocols in redirections. By default libcurl will allow all protocols except for FILE and SCP. This is a difference compared to pre-7.19.4 versions which unconditionally would follow to all protocols supported. See also CURLOPT_PROTOCOLS for protocol constant values. | Added in cURL 7.19.4.
CURLOPT_RESUME_FROM | The offset, in bytes, to resume a transfer from.
CURLOPT_SOCKS5_AUTH

The SOCKS5 authentication method(s) to use. The options are: CURLAUTH_BASIC, CURLAUTH_GSSAPI, CURLAUTH_NONE.

The bitwise | (or) operator can be used to combine more than one method. If this is done, cURL will poll the server to see what methods it supports and pick the best one.

CURLAUTH_BASIC allows username/password authentication.

CURLAUTH_GSSAPI allows GSS-API authentication.

CURLAUTH_NONE allows no authentication.

Defaults to CURLAUTH_BASIC|CURLAUTH_GSSAPI. Set the actual username and password with the CURLOPT_PROXYUSERPWD option.

Available as of 7.3.0 and curl >= 7.55.0.
CURLOPT_SSL_OPTIONS | Set SSL behavior options, which is a bitmask of any of the following constants: CURLSSLOPT_ALLOW_BEAST: do not attempt to use any workarounds for a security flaw in the SSL3 and TLS1.0 protocols. CURLSSLOPT_NO_REVOKE: disable certificate revocation checks for those SSL backends where such behavior is present. | Added in cURL 7.25.0. Available since PHP 7.0.7.
CURLOPT_SSL_VERIFYHOST | 1 to check the existence of a common name in the SSL peer certificate. 2 to check the existence of a common name and also verify that it matches the hostname provided. 0 to not check the names. In production environments the value of this option should be kept at 2 (default value). | Support for value 1 removed in cURL 7.28.1.
CURLOPT_SSLVERSION One of CURL_SSLVERSION_DEFAULT (0), CURL_SSLVERSION_TLSv1 (1), CURL_SSLVERSION_SSLv2 (2), CURL_SSLVERSION_SSLv3 (3), CURL_SSLVERSION_TLSv1_0 (4), CURL_SSLVERSION_TLSv1_1 (5) or CURL_SSLVERSION_TLSv1_2 (6).

Note:

Your best bet is to not set this and let it use the default. Setting it to 2 or 3 is very dangerous given the known vulnerabilities in SSLv2 and SSLv3.

CURLOPT_PROXY_SSL_OPTIONS | Set proxy SSL behavior options, which is a bitmask of any of the following constants: CURLSSLOPT_ALLOW_BEAST: do not attempt to use any workarounds for a security flaw in the SSL3 and TLS1.0 protocols. CURLSSLOPT_NO_REVOKE: disable certificate revocation checks for those SSL backends where such behavior is present. (curl >= 7.44.0) CURLSSLOPT_NO_PARTIALCHAIN: do not accept "partial" certificate chains, which it otherwise does by default. (curl >= 7.68.0) | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0.
CURLOPT_PROXY_SSL_VERIFYHOST | Set to 2 to verify in the HTTPS proxy's certificate name fields against the proxy name. When set to 0 the connection succeeds regardless of the names used in the certificate. Use that ability with caution! 1 treated as a debug option in curl 7.28.0 and earlier. From curl 7.28.1 to 7.65.3 CURLE_BAD_FUNCTION_ARGUMENT is returned. From curl 7.66.0 onwards 1 and 2 is treated as the same value. In production environments the value of this option should be kept at 2 (default value). | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0.
CURLOPT_PROXY_SSLVERSION One of CURL_SSLVERSION_DEFAULT, CURL_SSLVERSION_TLSv1, CURL_SSLVERSION_TLSv1_0, CURL_SSLVERSION_TLSv1_1, CURL_SSLVERSION_TLSv1_2, CURL_SSLVERSION_TLSv1_3, CURL_SSLVERSION_MAX_DEFAULT, CURL_SSLVERSION_MAX_TLSv1_0, CURL_SSLVERSION_MAX_TLSv1_2, CURL_SSLVERSION_MAX_TLSv1_2, CURL_SSLVERSION_MAX_TLSv1_3 or CURL_SSLVERSION_SSLv3.

Note:

Your best bet is to not set this and let it use the default CURL_SSLVERSION_DEFAULT which will attempt to figure out the remote SSL protocol version.

Available since PHP 7.3.0 and libcurl >= cURL 7.52.0.
CURLOPT_STREAM_WEIGHT | Set the numerical stream weight (a number between 1 and 256). | Added in cURL 7.46.0. Available since PHP 7.0.7.
CURLOPT_TIMECONDITION | How CURLOPT_TIMEVALUE is treated. Use CURL_TIMECOND_IFMODSINCE to return the page only if it has been modified since the time specified in CURLOPT_TIMEVALUE. If it hasn't been modified, a "304 Not Modified" header will be returned assuming CURLOPT_HEADER is TRUE. Use CURL_TIMECOND_IFUNMODSINCE for the reverse effect. CURL_TIMECOND_IFMODSINCE is the default.
CURLOPT_TIMEOUT | The maximum number of seconds to allow cURL functions to execute.
CURLOPT_TIMEOUT_MS | The maximum number of milliseconds to allow cURL functions to execute. If libcurl is built to use the standard system name resolver, that portion of the connect will still use full-second resolution for timeouts with a minimum timeout allowed of one second. | Added in cURL 7.16.2. Available since PHP 5.2.3.
CURLOPT_TIMEVALUE | The time in seconds since January 1st, 1970. The time will be used by CURLOPT_TIMECONDITION. By default, CURL_TIMECOND_IFMODSINCE is used.
CURLOPT_TIMEVALUE_LARGE | The time in seconds since January 1st, 1970. The time will be used by CURLOPT_TIMECONDITION. Defaults to zero. The difference between this option and CURLOPT_TIMEVALUE is the type of the argument. On systems where 'long' is only 32 bit wide, this option has to be used to set dates beyond the year 2038. | Added in cURL 7.59.0. Available since PHP 7.3.0.
CURLOPT_MAX_RECV_SPEED_LARGE | If a download exceeds this speed (counted in bytes per second) on cumulative average during the transfer, the transfer will pause to keep the average rate less than or equal to the parameter value. Defaults to unlimited speed. | Added in cURL 7.15.5. Available since PHP 5.4.0.
CURLOPT_MAX_SEND_SPEED_LARGE | If an upload exceeds this speed (counted in bytes per second) on cumulative average during the transfer, the transfer will pause to keep the average rate less than or equal to the parameter value. Defaults to unlimited speed. | Added in cURL 7.15.5. Available since PHP 5.4.0.
CURLOPT_SSH_AUTH_TYPES | A bitmask consisting of one or more of CURLSSH_AUTH_PUBLICKEY, CURLSSH_AUTH_PASSWORD, CURLSSH_AUTH_HOST, CURLSSH_AUTH_KEYBOARD. Set to CURLSSH_AUTH_ANY to let libcurl pick one. | Added in cURL 7.16.1.
CURLOPT_IPRESOLVE | Allows an application to select what kind of IP addresses to use when resolving host names. This is only interesting when using host names that resolve addresses using more than one version of IP, possible values are CURL_IPRESOLVE_WHATEVER, CURL_IPRESOLVE_V4, CURL_IPRESOLVE_V6, by default CURL_IPRESOLVE_WHATEVER. | Added in cURL 7.10.8.
CURLOPT_FTP_FILEMETHOD | Tell curl which method to use to reach a file on a FTP(S) server. Possible values are CURLFTPMETHOD_MULTICWD, CURLFTPMETHOD_NOCWD and CURLFTPMETHOD_SINGLECWD. | Added in cURL 7.15.1. Available since PHP 5.3.0.

value should be a string for the following values of the option parameter:

Option | Set value to | Notes
CURLOPT_ABSTRACT_UNIX_SOCKET | Enables the use of an abstract Unix domain socket instead of establishing a TCP connection to a host and sets the path to the given string. This option shares the same semantics as CURLOPT_UNIX_SOCKET_PATH. These two options share the same storage and therefore only one of them can be set per handle. | Available since PHP 7.3.0 and cURL 7.53.0
CURLOPT_CAINFO | The name of a file holding one or more certificates to verify the peer with. This only makes sense when used in combination with CURLOPT_SSL_VERIFYPEER. | Might require an absolute path.
CURLOPT_CAPATH | A directory that holds multiple CA certificates. Use this option alongside CURLOPT_SSL_VERIFYPEER.
CURLOPT_COOKIE | The contents of the "Cookie: " header to be used in the HTTP request. Note that multiple cookies are separated with a semicolon followed by a space (e.g., "fruit=apple; colour=red")
CURLOPT_COOKIEFILE | The name of the file containing the cookie data. The cookie file can be in Netscape format, or just plain HTTP-style headers dumped into a file. If the name is an empty string, no cookies are loaded, but cookie handling is still enabled.
CURLOPT_COOKIEJAR | The name of a file to save all internal cookies to when the handle is closed, e.g. after a call to curl_close.
CURLOPT_CUSTOMREQUEST

A custom request method to use instead of "GET" or "HEAD" when doing a HTTP request. This is useful for doing "DELETE" or other, more obscure HTTP requests. Valid values are things like "GET", "POST", "CONNECT" and so on; i.e. Do not enter a whole HTTP request line here. For instance, entering "GET /index.html HTTP/1.0\r\n\r\n" would be incorrect.

Note:

Don't do this without making sure the server supports the custom request method first.

CURLOPT_DEFAULT_PROTOCOL

The default protocol to use if the URL is missing a scheme name.

Added in cURL 7.45.0. Available since PHP 7.0.7.
CURLOPT_DNS_INTERFACE

Set the name of the network interface that the DNS resolver should bind to. This must be an interface name (not an address).

Added in cURL 7.33.0. Available since PHP 7.0.7.
CURLOPT_DNS_LOCAL_IP4

Set the local IPv4 address that the resolver should bind to. The argument should contain a single numerical IPv4 address as a string.

Added in cURL 7.33.0. Available since PHP 7.0.7.
CURLOPT_DNS_LOCAL_IP6

Set the local IPv6 address that the resolver should bind to. The argument should contain a single numerical IPv6 address as a string.

Added in cURL 7.33.0. Available since PHP 7.0.7.
CURLOPT_EGDSOCKET | Like CURLOPT_RANDOM_FILE, except a filename to an Entropy Gathering Daemon socket.
CURLOPT_ENCODING | The contents of the "Accept-Encoding: " header. This enables decoding of the response. Supported encodings are "identity", "deflate", and "gzip". If an empty string, "", is set, a header containing all supported encoding types is sent. | Added in cURL 7.10.
CURLOPT_FTPPORT | The value which will be used to get the IP address to use for the FTP "PORT" instruction. The "PORT" instruction tells the remote server to connect to our specified IP address. The string may be a plain IP address, a hostname, a network interface name (under Unix), or just a plain '-' to use the systems default IP address.
CURLOPT_INTERFACE | The name of the outgoing network interface to use. This can be an interface name, an IP address or a host name.
CURLOPT_KEYPASSWD | The password required to use the CURLOPT_SSLKEY or CURLOPT_SSH_PRIVATE_KEYFILE private key. | Added in cURL 7.16.1.
CURLOPT_KRB4LEVEL | The KRB4 (Kerberos 4) security level. Any of the following values (in order from least to most powerful) are valid: "clear", "safe", "confidential", "private".. If the string does not match one of these, "private" is used. Setting this option to NULL will disable KRB4 security. Currently KRB4 security only works with FTP transactions.
CURLOPT_LOGIN_OPTIONS | Can be used to set protocol specific login options, such as the preferred authentication mechanism via "AUTH=NTLM" or "AUTH=*", and should be used in conjunction with the CURLOPT_USERNAME option. | Added in cURL 7.34.0. Available since PHP 7.0.7.
CURLOPT_PINNEDPUBLICKEY | Set the pinned public key. The string can be the file name of your pinned public key. The file format expected is "PEM" or "DER". The string can also be any number of base64 encoded sha256 hashes preceded by "sha256//" and separated by ";". | Added in cURL 7.39.0. Available since PHP 7.0.7.
CURLOPT_POSTFIELDS | The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'. This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data. As of PHP 5.2.0, value must be an array if files are passed to this option with the @ prefix. As of PHP 5.5.0, the @ prefix is deprecated and files can be sent using CURLFile. The @ prefix can be disabled for safe passing of values beginning with @ by setting the CURLOPT_SAFE_UPLOAD option to TRUE.
CURLOPT_PRIVATE | Any data that should be associated with this cURL handle. This data can subsequently be retrieved with the CURLINFO_PRIVATE option of curl_getinfo(). cURL does nothing with this data. When using a cURL multi handle, this private data is typically a unique key to identify a standard cURL handle. | Added in cURL 7.10.3.
CURLOPT_PRE_PROXY | Set a string holding the host name or dotted numerical IP address to be used as the preproxy that curl connects to before it connects to the HTTP(S) proxy specified in the CURLOPT_PROXY option for the upcoming request. The preproxy can only be a SOCKS proxy and it should be prefixed with [scheme]:// to specify which kind of socks is used. A numerical IPv6 address must be written within [brackets]. Setting the preproxy to an empty string explicitly disables the use of a preproxy. To specify port number in this string, append :[port] to the end of the host name. The proxy's port number may optionally be specified with the separate option CURLOPT_PROXYPORT. Defaults to using port 1080 for proxies if a port is not specified. | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0.
CURLOPT_PROXY | The HTTP proxy to tunnel requests through.
CURLOPT_PROXY_SERVICE_NAME | The proxy authentication service name. | Added in cURL 7.34.0. Available since PHP 7.0.7.
CURLOPT_PROXY_CAINFO | The path to proxy Certificate Authority (CA) bundle. Set the path as a string naming a file holding one or more certificates to verify the HTTPS proxy with. This option is for connecting to an HTTPS proxy, not an HTTPS server. Defaults set to the system path where libcurl's cacert bundle is assumed to be stored. | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0.
CURLOPT_PROXY_CAPATH | The directory holding multiple CA certificates to verify the HTTPS proxy with. | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0.
CURLOPT_PROXY_CRLFILE | Set the file name with the concatenation of CRL (Certificate Revocation List) in PEM format to use in the certificate validation that occurs during the SSL exchange. | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0.
CURLOPT_PROXY_KEYPASSWD | Set the string be used as the password required to use the CURLOPT_PROXY_SSLKEY private key. You never needed a passphrase to load a certificate but you need one to load your private key. This option is for connecting to an HTTPS proxy, not an HTTPS server. | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0.
CURLOPT_PROXY_PINNEDPUBLICKEY | Set the pinned public key for HTTPS proxy. The string can be the file name of your pinned public key. The file format expected is "PEM" or "DER". The string can also be any number of base64 encoded sha256 hashes preceded by "sha256//" and separated by ";" | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0.
CURLOPT_PROXY_SSLCERT | The file name of your client certificate used to connect to the HTTPS proxy. The default format is "P12" on Secure Transport and "PEM" on other engines, and can be changed with CURLOPT_PROXY_SSLCERTTYPE. With NSS or Secure Transport, this can also be the nickname of the certificate you wish to authenticate with as it is named in the security database. If you want to use a file from the current directory, please precede it with "./" prefix, in order to avoid confusion with a nickname. | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0.
CURLOPT_PROXY_SSLCERTTYPE | The format of your client certificate used when connecting to an HTTPS proxy. Supported formats are "PEM" and "DER", except with Secure Transport. OpenSSL (versions 0.9.3 and later) and Secure Transport (on iOS 5 or later, or OS X 10.7 or later) also support "P12" for PKCS#12-encoded files. Defaults to "PEM". | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0.
CURLOPT_PROXY_SSL_CIPHER_LIST | The list of ciphers to use for the connection to the HTTPS proxy. The list must be syntactically correct, it consists of one or more cipher strings separated by colons. Commas or spaces are also acceptable separators but colons are normally used, !, - and + can be used as operators. | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0.
CURLOPT_PROXY_TLS13_CIPHERS | The list of cipher suites to use for the TLS 1.3 connection to a proxy. The list must be syntactically correct, it consists of one or more cipher suite strings separated by colons. This option is currently used only when curl is built to use OpenSSL 1.1.1 or later. If you are using a different SSL backend you can try setting TLS 1.3 cipher suites by using the CURLOPT_PROXY_SSL_CIPHER_LIST option. | Available since PHP 7.3.0 and libcurl >= cURL 7.61.0. Available when built with OpenSSL >= 1.1.1.
CURLOPT_PROXY_SSLKEY | The file name of your private key used for connecting to the HTTPS proxy. The default format is "PEM" and can be changed with CURLOPT_PROXY_SSLKEYTYPE. (iOS and Mac OS X only) This option is ignored if curl was built against Secure Transport. | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0. Available if built TLS enabled.
CURLOPT_PROXY_SSLKEYTYPE | The format of your private key. Supported formats are "PEM", "DER" and "ENG". | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0.
CURLOPT_PROXY_TLSAUTH_PASSWORD | The password to use for the TLS authentication method specified with the CURLOPT_PROXY_TLSAUTH_TYPE option. Requires that the CURLOPT_PROXY_TLSAUTH_USERNAME option to also be set. | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0.
CURLOPT_PROXY_TLSAUTH_TYPE The method of the TLS authentication used for the HTTPS connection. Supported method is "SRP".

Note:

Secure Remote Password (SRP) authentication for TLS provides mutual authentication if both sides have a shared secret. To use TLS-SRP, you must also set the CURLOPT_PROXY_TLSAUTH_USERNAME and CURLOPT_PROXY_TLSAUTH_PASSWORD options.

Available since PHP 7.3.0 and libcurl >= cURL 7.52.0.
CURLOPT_PROXY_TLSAUTH_USERNAME | Tusername to use for the HTTPS proxy TLS authentication method specified with the CURLOPT_PROXY_TLSAUTH_TYPE option. Requires that the CURLOPT_PROXY_TLSAUTH_PASSWORD option to also be set. | Available since PHP 7.3.0 and libcurl >= cURL 7.52.0.
CURLOPT_PROXYUSERPWD | A username and password formatted as "[username]:[password]" to use for the connection to the proxy.
CURLOPT_RANDOM_FILE | A filename to be used to seed the random number generator for SSL.
CURLOPT_RANGE | Range(s) of data to retrieve in the format "X-Y" where X or Y are optional. HTTP transfers also support several intervals, separated with commas in the format "X-Y,N-M".
CURLOPT_REFERER | The contents of the "Referer: " header to be used in a HTTP request.
CURLOPT_SERVICE_NAME | The authentication service name. | Added in cURL 7.43.0. Available since PHP 7.0.7.
CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 | A string containing 32 hexadecimal digits. The string should be the MD5 checksum of the remote host's public key, and libcurl will reject the connection to the host unless the md5sums match. This option is only for SCP and SFTP transfers. | Added in cURL 7.17.1.
CURLOPT_SSH_PUBLIC_KEYFILE | The file name for your public key. If not used, libcurl defaults to $HOME/.ssh/id_dsa.pub if the HOME environment variable is set, and just "id_dsa.pub" in the current directory if HOME is not set. | Added in cURL 7.16.1.
CURLOPT_SSH_PRIVATE_KEYFILE | The file name for your private key. If not used, libcurl defaults to $HOME/.ssh/id_dsa if the HOME environment variable is set, and just "id_dsa" in the current directory if HOME is not set. If the file is password-protected, set the password with CURLOPT_KEYPASSWD. | Added in cURL 7.16.1.
CURLOPT_SSL_CIPHER_LIST | A list of ciphers to use for SSL. For example, RC4-SHA and TLSv1 are valid cipher lists.
CURLOPT_SSLCERT | The name of a file containing a PEM formatted certificate.
CURLOPT_SSLCERTPASSWD | The password required to use the CURLOPT_SSLCERT certificate.
CURLOPT_SSLCERTTYPE | The format of the certificate. Supported formats are "PEM" (default), "DER", and "ENG". | Added in cURL 7.9.3.
CURLOPT_SSLENGINE | The identifier for the crypto engine of the private SSL key specified in CURLOPT_SSLKEY.
CURLOPT_SSLENGINE_DEFAULT | The identifier for the crypto engine used for asymmetric crypto operations.
CURLOPT_SSLKEY | The name of a file containing a private SSL key.
CURLOPT_SSLKEYPASSWD

The secret password needed to use the private SSL key specified in CURLOPT_SSLKEY.

Note:

Since this option contains a sensitive password, remember to keep the PHP script it is contained within safe.

CURLOPT_SSLKEYTYPE | The key type of the private SSL key specified in CURLOPT_SSLKEY. Supported key types are "PEM" (default), "DER", and "ENG".
CURLOPT_TLS13_CIPHERS | The list of cipher suites to use for the TLS 1.3 connection. The list must be syntactically correct, it consists of one or more cipher suite strings separated by colons. This option is currently used only when curl is built to use OpenSSL 1.1.1 or later. If you are using a different SSL backend you can try setting TLS 1.3 cipher suites by using the CURLOPT_SSL_CIPHER_LIST option. | Available since PHP 7.3.0 and libcurl >= cURL 7.61.0. Available when built with OpenSSL >= 1.1.1.
CURLOPT_UNIX_SOCKET_PATH | Enables the use of Unix domain sockets as connection endpoint and sets the path to the given string. | Added in cURL 7.40.0. Available since PHP 7.0.7.
CURLOPT_URL | The URL to fetch. This can also be set when initializing a session with curl_init().
CURLOPT_USERAGENT | The contents of the "User-Agent: " header to be used in a HTTP request.
CURLOPT_USERNAME | The user name to use in authentication. | Added in cURL 7.19.1. Available since PHP 5.5.0.
CURLOPT_USERPWD | A username and password formatted as "[username]:[password]" to use for the connection.
CURLOPT_XOAUTH2_BEARER | Specifies the OAuth 2.0 access token. | Added in cURL 7.33.0. Available since PHP 7.0.7.

value should be an array for the following values of the option parameter:

Option | Set value to | Notes
CURLOPT_CONNECT_TO | Connect to a specific host and port instead of the URL's host and port. Accepts an array of strings with the format HOST:PORT:CONNECT-TO-HOST:CONNECT-TO-PORT. | Added in cURL 7.49.0. Available since PHP 7.0.7.
CURLOPT_HTTP200ALIASES | An array of HTTP 200 responses that will be treated as valid responses and not as errors. | Added in cURL 7.10.3.
CURLOPT_HTTPHEADER | An array of HTTP header fields to set, in the format array('Content-type: text/plain', 'Content-length: 100')
CURLOPT_POSTQUOTE | An array of FTP commands to execute on the server after the FTP request has been performed.
CURLOPT_PROXYHEADER | An array of custom HTTP headers to pass to proxies. | Added in cURL 7.37.0. Available since PHP 7.0.7.
CURLOPT_QUOTE | An array of FTP commands to execute on the server prior to the FTP request.
CURLOPT_RESOLVE | Provide a custom address for a specific host and port pair. An array of hostname, port, and IP address strings, each element separated by a colon. In the format: array("example.com:80:127.0.0.1") | Added in cURL 7.21.3. Available since PHP 5.5.0.

value should be a stream resource (using fopen(), for example) for the following values of the option parameter:

Option | Set value to
CURLOPT_FILE | The file that the transfer should be written to. The default is STDOUT (the browser window).
CURLOPT_INFILE | The file that the transfer should be read from when uploading.
CURLOPT_STDERR | An alternative location to output errors to instead of STDERR.
CURLOPT_WRITEHEADER | The file that the header part of the transfer is written to.

value should be the name of a valid function or a Closure for the following values of the option parameter:

Option | Set value to
CURLOPT_HEADERFUNCTION | A callback accepting two parameters. The first is the cURL resource, the second is a string with the header data to be written. The header data must be written by this callback. Return the number of bytes written.
CURLOPT_PASSWDFUNCTION | A callback accepting three parameters. The first is the cURL resource, the second is a string containing a password prompt, and the third is the maximum password length. Return the string containing the password.
CURLOPT_PROGRESSFUNCTION

A callback accepting five parameters. The first is the cURL resource, the second is the total number of bytes expected to be downloaded in this transfer, the third is the number of bytes downloaded so far, the fourth is the total number of bytes expected to be uploaded in this transfer, and the fifth is the number of bytes uploaded so far.

Note:

The callback is only called when the CURLOPT_NOPROGRESS option is set to FALSE.

Return a non-zero value to abort the transfer. In which case, the transfer will set a CURLE_ABORTED_BY_CALLBACK error.

CURLOPT_READFUNCTION | A callback accepting three parameters. The first is the cURL resource, the second is a stream resource provided to cURL through the option CURLOPT_INFILE, and the third is the maximum amount of data to be read. The callback must return a string with a length equal or smaller than the amount of data requested, typically by reading it from the passed stream resource. It should return an empty string to signal EOF.
CURLOPT_WRITEFUNCTION | A callback accepting two parameters. The first is the cURL resource, and the second is a string with the data to be written. The data must be saved by this callback. It must return the exact number of bytes written or the transfer will be aborted with an error.

Other values:

Option | Set value to
CURLOPT_SHARE | A result of curl_share_init(). Makes the cURL handle to use the data from the shared handle.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.3.15, 7.4.3 | Introduced CURLOPT_HTTP09_ALLOWED .
7.3.0 | Introduced CURLOPT_ABSTRACT_UNIX_SOCKET, CURLOPT_KEEP_SENDING_ON_ERROR, CURLOPT_PRE_PROXY, CURLOPT_PROXY_CAINFO, CURLOPT_PROXY_CAPATH, CURLOPT_PROXY_CRLFILE, CURLOPT_PROXY_KEYPASSWD, CURLOPT_PROXY_PINNEDPUBLICKEY, CURLOPT_PROXY_SSLCERT, CURLOPT_PROXY_SSLCERTTYPE, CURLOPT_PROXY_SSL_CIPHER_LIST, CURLOPT_PROXY_SSLKEY, CURLOPT_PROXY_SSLKEYTYPE, CURLOPT_PROXY_SSL_OPTIONS, CURLOPT_PROXY_SSL_VERIFYHOST, CURLOPT_PROXY_SSL_VERIFYPEER, CURLOPT_PROXY_SSLVERSION, CURLOPT_PROXY_TLSAUTH_PASSWORD, CURLOPT_PROXY_TLSAUTH_TYPE, CURLOPT_PROXY_TLSAUTH_USERNAME, CURLOPT_SOCKS5_AUTH, CURLOPT_SUPPRESS_CONNECT_HEADERS, CURLOPT_DISALLOW_USERNAME_IN_URL, CURLOPT_DNS_SHUFFLE_ADDRESSES, CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS, CURLOPT_HAPROXYPROTOCOL, CURLOPT_PROXY_TLS13_CIPHERS, CURLOPT_SSH_COMPRESSION, CURLOPT_TIMEVALUE_LARGE and CURLOPT_TLS13_CIPHERS.
7.0.7 | Introduced CURL_HTTP_VERSION_2, CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE, CURL_HTTP_VERSION_2TLS, CURL_REDIR_POST_301, CURL_REDIR_POST_302, CURL_REDIR_POST_303, CURL_REDIR_POST_ALL, CURL_VERSION_KERBEROS5, CURL_VERSION_PSL, CURL_VERSION_UNIX_SOCKETS, CURLAUTH_NEGOTIATE, CURLAUTH_NTLM_WB, CURLFTP_CREATE_DIR, CURLFTP_CREATE_DIR_NONE, CURLFTP_CREATE_DIR_RETRY, CURLHEADER_SEPARATE, CURLHEADER_UNIFIED, CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE, CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE, CURLMOPT_MAX_HOST_CONNECTIONS, CURLMOPT_MAX_PIPELINE_LENGTH, CURLMOPT_MAX_TOTAL_CONNECTIONS, CURLOPT_CONNECT_TO, CURLOPT_DEFAULT_PROTOCOL, CURLOPT_DNS_INTERFACE, CURLOPT_DNS_LOCAL_IP4, CURLOPT_DNS_LOCAL_IP6, CURLOPT_EXPECT_100_TIMEOUT_MS, CURLOPT_HEADEROPT, CURLOPT_LOGIN_OPTIONS, CURLOPT_PATH_AS_IS, CURLOPT_PINNEDPUBLICKEY, CURLOPT_PIPEWAIT, CURLOPT_PROXY_SERVICE_NAME, CURLOPT_PROXYHEADER, CURLOPT_SASL_IR, CURLOPT_SERVICE_NAME, CURLOPT_SSL_ENABLE_ALPN, CURLOPT_SSL_ENABLE_NPN, CURLOPT_SSL_FALSESTART, CURLOPT_SSL_VERIFYSTATUS, CURLOPT_STREAM_WEIGHT, CURLOPT_TCP_FASTOPEN, CURLOPT_TFTP_NO_OPTIONS, CURLOPT_UNIX_SOCKET_PATH, CURLOPT_XOAUTH2_BEARER, CURLPROTO_SMB, CURLPROTO_SMBS, CURLPROXY_HTTP_1_0, CURLSSH_AUTH_AGENT and CURLSSLOPT_NO_REVOKE.
7.0.0 | Support for disabling the CURLOPT_SAFE_UPLOAD option has been removed. All curl file uploads must use CURLFile.
5.6.0 | CURLOPT_SAFE_UPLOAD is now TRUE by default.
5.6.0 | Removed CURLOPT_CLOSEPOLICY and associated values.
5.5.0 | Added the cURL resource as the first argument to the CURLOPT_PROGRESSFUNCTION callback.
5.5.0 | Introduced CURLOPT_SHARE.
5.3.0 | Introduced CURLOPT_PROGRESSFUNCTION.
5.2.10 | Introduced CURLOPT_PROTOCOLS, and CURLOPT_REDIR_PROTOCOLS.
5.2.4 | Introduced CURLOPT_PRIVATE.
5.1.0 | Introduced CURLOPT_AUTOREFERER, CURLOPT_BINARYTRANSFER, CURLOPT_FTPSSLAUTH, CURLOPT_PROXYAUTH, and CURLOPT_TIMECONDITION.
5.0.0 | Introduced CURLOPT_FTP_USE_EPRT, CURLOPT_NOSIGNAL, CURLOPT_UNRESTRICTED_AUTH, CURLOPT_BUFFERSIZE, CURLOPT_HTTPAUTH, CURLOPT_PROXYPORT, CURLOPT_PROXYTYPE, CURLOPT_SSLCERTTYPE, and CURLOPT_HTTP200ALIASES.

Examples

Example #1 Initializing a new cURL session and fetching a web page

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, false);

// grab URL and pass it to the browser
curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);
?>

Example #2 Uploading file (deprecated as of PHP 5.5.0)

<?php

/* http://localhost/upload.php:
print_r($_POST);
print_r($_FILES);
*/

$ch = curl_init();

$data = array('name' => 'Foo', 'file' => '@/home/user/test.png');

curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false); // required as of PHP 5.6.0
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_exec($ch);
?>

The above example will output:

Array
(
    [name] => Foo
)
Array
(
    [file] => Array
        (
            [name] => test.png
            [type] => image/png
            [tmp_name] => /tmp/phpcpjNeQ
            [error] => 0
            [size] => 279
        )

)

Notes

Note:

Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data, while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded.

See Also

  • curl_setopt_array() - Set multiple options for a cURL transfer


Close a cURL share handle

  • « curl_setopt
  • curl_share_errno »
  • PHP Manual
  • cURL Functions
  • Close a cURL share handle

curl_share_close

(PHP 5 >= 5.5.0, PHP 7)

curl_share_close — Close a cURL share handle

Description

curl_share_close ( resource $sh ) : void

Closes a cURL share handle and frees all resources.

Parameters

sh

A cURL share handle returned by curl_share_init()

Return Values

No value is returned.

Examples

Example #1 curl_share_setopt() example

This example will create a cURL share handle, add two cURL handles to it, and then run them with cookie data sharing.

<?php
// Create cURL share handle and set it to share cookie data
$sh = curl_share_init();
curl_share_setopt($sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE);

// Initialize the first cURL handle and assign the share handle to it
$ch1 = curl_init("http://example.com/");
curl_setopt($ch1, CURLOPT_SHARE, $sh);

// Execute the first cURL handle
curl_exec($ch1);

// Initialize the second cURL handle and assign the share handle to it
$ch2 = curl_init("http://php.net/");
curl_setopt($ch2, CURLOPT_SHARE, $sh);

// Execute the second cURL handle
//  all cookies from $ch1 handle are shared with $ch2 handle
curl_exec($ch2);

// Close the cURL share handle
curl_share_close($sh);

// Close the cURL handles
curl_close($ch1);
curl_close($ch2);
?>

See Also

  • curl_share_init() - Initialize a cURL share handle


Return the last share curl error number

  • « curl_share_close
  • curl_share_init »
  • PHP Manual
  • cURL Functions
  • Return the last share curl error number

curl_share_errno

(PHP 7 >= 7.1.0)

curl_share_errno — Return the last share curl error number

Description

curl_share_errno ( resource $sh ) : int

Return an integer containing the last share curl error number.

Parameters

sh

A cURL share handle returned by curl_share_init().

Return Values

Returns an integer containing the last share curl error number, or FALSE on failure.

See Also

  • curl_errno() - Return the last error number


Initialize a cURL share handle

  • « curl_share_errno
  • curl_share_setopt »
  • PHP Manual
  • cURL Functions
  • Initialize a cURL share handle

curl_share_init

(PHP 5 >= 5.5.0, PHP 7)

curl_share_init — Initialize a cURL share handle

Description

curl_share_init ( void ) : resource

Allows to share data between cURL handles.

Parameters

This function has no parameters.

Return Values

Returns resource of type "cURL Share Handle".

Examples

Example #1 curl_share_init() example

This example will create a cURL share handle, add two cURL handles to it, and then run them with cookie data sharing.

<?php
// Create cURL share handle and set it to share cookie data
$sh = curl_share_init();
curl_share_setopt($sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE);

// Initialize the first cURL handle and assign the share handle to it
$ch1 = curl_init("http://example.com/");
curl_setopt($ch1, CURLOPT_SHARE, $sh);

// Execute the first cURL handle
curl_exec($ch1);

// Initialize the second cURL handle and assign the share handle to it
$ch2 = curl_init("http://php.net/");
curl_setopt($ch2, CURLOPT_SHARE, $sh);

// Execute the second cURL handle
//  all cookies from $ch1 handle are shared with $ch2 handle
curl_exec($ch2);

// Close the cURL share handle
curl_share_close($sh);

// Close the cURL handles
curl_close($ch1);
curl_close($ch2);
?>

See Also

  • curl_share_setopt() - Set an option for a cURL share handle
  • curl_share_close() - Close a cURL share handle


Set an option for a cURL share handle

  • « curl_share_init
  • curl_share_strerror »
  • PHP Manual
  • cURL Functions
  • Set an option for a cURL share handle

curl_share_setopt

(PHP 5 >= 5.5.0, PHP 7)

curl_share_setopt — Set an option for a cURL share handle

Description

curl_share_setopt ( resource $sh , int $option , string $value ) : bool

Sets an option on the given cURL share handle.

Parameters

sh

A cURL share handle returned by curl_share_init().

option

Option | Description
CURLSHOPT_SHARE | Specifies a type of data that should be shared.
CURLSHOPT_UNSHARE | Specifies a type of data that will be no longer shared.

value

Value | Description
CURL_LOCK_DATA_COOKIE | Shares cookie data.
CURL_LOCK_DATA_DNS | Shares DNS cache. Note that when you use cURL multi handles, all handles added to the same multi handle will share DNS cache by default.
CURL_LOCK_DATA_SSL_SESSION | Shares SSL session IDs, reducing the time spent on the SSL handshake when reconnecting to the same server. Note that SSL session IDs are reused within the same handle by default.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 curl_share_setopt() example

This example will create a cURL share handle, add two cURL handles to it, and then run them with cookie data sharing.

<?php
// Create cURL share handle and set it to share cookie data
$sh = curl_share_init();
curl_share_setopt($sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE);

// Initialize the first cURL handle and assign the share handle to it
$ch1 = curl_init("http://example.com/");
curl_setopt($ch1, CURLOPT_SHARE, $sh);

// Execute the first cURL handle
curl_exec($ch1);

// Initialize the second cURL handle and assign the share handle to it
$ch2 = curl_init("http://php.net/");
curl_setopt($ch2, CURLOPT_SHARE, $sh);

// Execute the second cURL handle
//  all cookies from $ch1 handle are shared with $ch2 handle
curl_exec($ch2);

// Close the cURL share handle
curl_share_close($sh);

// Close the cURL handles
curl_close($ch1);
curl_close($ch2);
?>


Return string describing the given error code

  • « curl_share_setopt
  • curl_strerror »
  • PHP Manual
  • cURL Functions
  • Return string describing the given error code

curl_share_strerror

(PHP 7 >= 7.1.0)

curl_share_strerror — Return string describing the given error code

Description

curl_share_strerror ( int $errornum ) : string

Returns a text error message describing the given error code.

Parameters

errornum

One of the » cURL error codes constants.

Return Values

Returns error description or NULL for invalid error code.

See Also

  • curl_share_errno() - Return the last share curl error number
  • curl_strerror() - Return string describing the given error code


Return string describing the given error code

  • « curl_share_strerror
  • curl_unescape »
  • PHP Manual
  • cURL Functions
  • Return string describing the given error code

curl_strerror

(PHP 5 >= 5.5.0, PHP 7)

curl_strerror — Return string describing the given error code

Description

curl_strerror ( int $errornum ) : string

Returns a text error message describing the given error code.

Parameters

errornum

One of the » cURL error codes constants.

Return Values

Returns error description or NULL for invalid error code.

Examples

Example #1 curl_errno() example

<?php
// Create a curl handle with a mispelled protocol in URL
$ch = curl_init("htp://example.com/");

// Send request
curl_exec($ch);

// Check for errors and display the error message
if($errno = curl_errno($ch)) {
    $error_message = curl_strerror($errno);
    echo "cURL error ({$errno}):\n {$error_message}";
}

// Close the handle
curl_close($ch);
?>

The above example will output:

cURL error (1):
 Unsupported protocol

See Also

  • curl_errno() - Return the last error number
  • curl_error() - Return a string containing the last error for the current session
  • » Curl error codes


Decodes the given URL encoded string

  • « curl_strerror
  • curl_version »
  • PHP Manual
  • cURL Functions
  • Decodes the given URL encoded string

curl_unescape

(PHP 5 >= 5.5.0, PHP 7)

curl_unescape — Decodes the given URL encoded string

Description

curl_unescape ( resource $ch , string $str ) : string

This function decodes the given URL encoded string.

Parameters

ch

A cURL handle returned by curl_init().

str

The URL encoded string to be decoded.

Return Values

Returns decoded string or FALSE on failure.

Examples

Example #1 curl_escape() example

<?php
// Create a curl handle
$ch = curl_init('http://example.com/redirect.php');

// Send HTTP request and follow redirections
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_exec($ch);

// Get the last effective URL
$effective_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
// ie. "http://example.com/show_location.php?loc=M%C3%BCnchen"

// Decode the URL
$effective_url_decoded = curl_unescape($ch, $effective_url);
// "http://example.com/show_location.php?loc=München"

// Close the handle
curl_close($ch);
?>

Notes

Note:

curl_unescape() does not decode plus symbols (+) into spaces. urldecode() does.

See Also

  • curl_escape() - URL encodes the given string
  • urlencode() - URL-encodes string
  • urldecode() - Decodes URL-encoded string
  • rawurlencode() - URL-encode according to RFC 3986
  • rawurldecode() - Decode URL-encoded strings


Gets cURL version information

  • « curl_unescape
  • CURLFile »
  • PHP Manual
  • cURL Functions
  • Gets cURL version information

curl_version

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

curl_version — Gets cURL version information

Description

curl_version ([ int $age = CURLVERSION_NOW ] ) : array

Returns information about the cURL version.

Parameters

age

Return Values

Returns an associative array with the following elements:

Key | Value description
version_number | cURL 24 bit version number
version | cURL version number, as a string
ssl_version_number | OpenSSL 24 bit version number
ssl_version | OpenSSL version number, as a string
libz_version | zlib version number, as a string
host | Information about the host where cURL was built
age |
features | A bitmask of the CURL_VERSION_XXX constants
protocols | An array of protocols names supported by cURL

Examples

Example #1 curl_version() example

This example will check which features that's available in cURL build by using the 'features' bitmask returned by curl_version().

<?php
// Get curl version array
$version = curl_version();

// These are the bitfields that can be used
// to check for features in the curl build
$bitfields = Array(
            'CURL_VERSION_IPV6',
            'CURL_VERSION_KERBEROS4',
            'CURL_VERSION_SSL',
            'CURL_VERSION_LIBZ'
            );

foreach($bitfields as $feature)
{
    echo $feature . ($version['features'] & constant($feature) ? ' matches' : ' does not match');
    echo PHP_EOL;
}
?>


The CURLFile class

(PHP 5 >= 5.5.0, PHP 7)

Introduction

CURLFile should be used to upload a file with CURLOPT_POSTFIELDS.

Class synopsis

CURLFile {
/* Properties */
public $name ;
public $mime ;
public $postname ;
/* Methods */
public __construct ( string $filename [, string $mimetype [, string $postname ]] )
public getFilename ( void ) : string
public getMimeType ( void ) : string
public getPostFilename ( void ) : string
public setMimeType ( string $mime ) : void
public setPostFilename ( string $postname ) : void
public __wakeup ( void ) : void
}

Properties

name

Name of the file to be uploaded.

mime

MIME type of the file (default is application/octet-stream).

postname

The name of the file in the upload data (defaults to the name property).

See Also

  • curl_setopt()

Table of Contents

  • CURLFile::__construct — Create a CURLFile object
  • CURLFile::getFilename — Get file name
  • CURLFile::getMimeType — Get MIME type
  • CURLFile::getPostFilename — Get file name for POST
  • CURLFile::setMimeType — Set MIME type
  • CURLFile::setPostFilename — Set file name for POST
  • CURLFile::__wakeup — Unserialization handler


Create a CURLFile object

  • « CURLFile
  • CURLFile::getFilename »
  • PHP Manual
  • CURLFile
  • Create a CURLFile object

CURLFile::__construct

curl_file_create

(PHP 5 >= 5.5.0, PHP 7)

CURLFile::__construct -- curl_file_create — Create a CURLFile object

Description

Object oriented style

public CURLFile::__construct ( string $filename [, string $mimetype [, string $postname ]] )

Procedural style

curl_file_create ( string $filename [, string $mimetype [, string $postname ]] ) : CURLFile

Creates a CURLFile object, used to upload a file with CURLOPT_POSTFIELDS.

Parameters

filename

Path to the file which will be uploaded.

mimetype

Mimetype of the file.

postname

Name of the file to be used in the upload data.

Return Values

Returns a CURLFile object.

Examples

Example #1 CURLFile::__construct() example

Object oriented style

<?php
/* http://example.com/upload.php:
<?php var_dump($_FILES); ?>
*/

// Create a cURL handle
$ch = curl_init('http://example.com/upload.php');

// Create a CURLFile object
$cfile = new CURLFile('cats.jpg','image/jpeg','test_name');

// Assign POST data
$data = array('test_file' => $cfile);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

// Execute the handle
curl_exec($ch);
?>

Procedural style

<?php
/* http://example.com/upload.php:
<?php var_dump($_FILES); ?>
*/

// Create a cURL handle
$ch = curl_init('http://example.com/upload.php');

// Create a CURLFile object
$cfile = curl_file_create('cats.jpg','image/jpeg','test_name');

// Assign POST data
$data = array('test_file' => $cfile);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

// Execute the handle
curl_exec($ch);
?>

The above example will output:

array(1) {
  ["test_file"]=>
  array(5) {
    ["name"]=>
    string(9) "test_name"
    ["type"]=>
    string(10) "image/jpeg"
    ["tmp_name"]=>
    string(14) "/tmp/phpPC9Kbx"
    ["error"]=>
    int(0)
    ["size"]=>
    int(46334)
  }
}

See Also

  • curl_setopt() - Set an option for a cURL transfer


Get file name

  • « CURLFile::__construct
  • CURLFile::getMimeType »
  • PHP Manual
  • CURLFile
  • Get file name

CURLFile::getFilename

(PHP 5 >= 5.5.0, PHP 7)

CURLFile::getFilename — Get file name

Description

public CURLFile::getFilename ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns file name.


Get MIME type

  • « CURLFile::getFilename
  • CURLFile::getPostFilename »
  • PHP Manual
  • CURLFile
  • Get MIME type

CURLFile::getMimeType

(PHP 5 >= 5.5.0, PHP 7)

CURLFile::getMimeType — Get MIME type

Description

public CURLFile::getMimeType ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns MIME type.


Get file name for POST

  • « CURLFile::getMimeType
  • CURLFile::setMimeType »
  • PHP Manual
  • CURLFile
  • Get file name for POST

CURLFile::getPostFilename

(PHP 5 >= 5.5.0, PHP 7)

CURLFile::getPostFilename — Get file name for POST

Description

public CURLFile::getPostFilename ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns file name for POST.


Set MIME type

  • « CURLFile::getPostFilename
  • CURLFile::setPostFilename »
  • PHP Manual
  • CURLFile
  • Set MIME type

CURLFile::setMimeType

(PHP 5 >= 5.5.0, PHP 7)

CURLFile::setMimeType — Set MIME type

Description

public CURLFile::setMimeType ( string $mime ) : void

Parameters

mime

MIME type to be used in POST data.

Return Values

No value is returned.


Set file name for POST

  • « CURLFile::setMimeType
  • CURLFile::__wakeup »
  • PHP Manual
  • CURLFile
  • Set file name for POST

CURLFile::setPostFilename

(PHP 5 >= 5.5.0, PHP 7)

CURLFile::setPostFilename — Set file name for POST

Description

public CURLFile::setPostFilename ( string $postname ) : void

Parameters

postname

Filename to be used in POST data.

Return Values

No value is returned.


Unserialization handler

  • « CURLFile::setPostFilename
  • Event »
  • PHP Manual
  • CURLFile
  • Unserialization handler

CURLFile::__wakeup

(PHP 5 >= 5.5.0, PHP 7)

CURLFile::__wakeup — Unserialization handler

Description

public CURLFile::__wakeup ( void ) : void

Parameters

This function has no parameters.

Return Values

No value is returned.

Errors/Exceptions

CURLFile is not serializable.


Event

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Examples
  • Event flags
  • About event persistence
  • Event callbacks
  • Constructing signal events
  • Event — The Event class
    • Event::add — Makes event pending
    • Event::addSignal — Makes signal event pending
    • Event::addTimer — Makes timer event pending
    • Event::__construct — Constructs Event object
    • Event::del — Makes event non-pending
    • Event::delSignal — Makes signal event non-pending
    • Event::delTimer — Makes timer event non-pending
    • Event::free — Make event non-pending and free resources allocated for this event
    • Event::getSupportedMethods — Returns array with of the names of the methods supported in this version of Libevent
    • Event::pending — Detects whether event is pending or scheduled
    • Event::set — Re-configures event
    • Event::setPriority — Set event priority
    • Event::setTimer — Re-configures timer event
    • Event::signal — Constructs signal event object
    • Event::timer — Constructs timer event object
  • EventBase — The EventBase class
    • EventBase::__construct — Constructs EventBase object
    • EventBase::dispatch — Dispatch pending events
    • EventBase::exit — Stop dispatching events
    • EventBase::free — Free resources allocated for this event base
    • EventBase::getFeatures — Returns bitmask of features supported
    • EventBase::getMethod — Returns event method in use
    • EventBase::getTimeOfDayCached — Returns the current event base time
    • EventBase::gotExit — Checks if the event loop was told to exit
    • EventBase::gotStop — Checks if the event loop was told to exit
    • EventBase::loop — Dispatch pending events
    • EventBase::priorityInit — Sets number of priorities per event base
    • EventBase::reInit — Re-initialize event base(after a fork)
    • EventBase::stop — Tells event_base to stop dispatching events
  • EventBuffer — The EventBuffer class
    • EventBuffer::add — Append data to the end of an event buffer
    • EventBuffer::addBuffer — Move all data from a buffer provided to the current instance of EventBuffer
    • EventBuffer::appendFrom — Moves the specified number of bytes from a source buffer to the end of the current buffer
    • EventBuffer::__construct — Constructs EventBuffer object
    • EventBuffer::copyout — Copies out specified number of bytes from the front of the buffer
    • EventBuffer::drain — Removes specified number of bytes from the front of the buffer without copying it anywhere
    • EventBuffer::enableLocking — Description
    • EventBuffer::expand — Reserves space in buffer
    • EventBuffer::freeze — Prevent calls that modify an event buffer from succeeding
    • EventBuffer::lock — Acquires a lock on buffer
    • EventBuffer::prepend — Prepend data to the front of the buffer
    • EventBuffer::prependBuffer — Moves all data from source buffer to the front of current buffer
    • EventBuffer::pullup — Linearizes data within buffer and returns it's contents as a string
    • EventBuffer::read — Read data from an evbuffer and drain the bytes read
    • EventBuffer::readFrom — Read data from a file onto the end of the buffer
    • EventBuffer::readLine — Extracts a line from the front of the buffer
    • EventBuffer::search — Scans the buffer for an occurrence of a string
    • EventBuffer::searchEol — Scans the buffer for an occurrence of an end of line
    • EventBuffer::substr — Substracts a portion of the buffer data
    • EventBuffer::unfreeze — Re-enable calls that modify an event buffer
    • EventBuffer::unlock — Releases lock acquired by EventBuffer::lock
    • EventBuffer::write — Write contents of the buffer to a file or socket
  • EventBufferEvent — The EventBufferEvent class
    • EventBufferEvent::close — Closes file descriptor associated with the current buffer event
    • EventBufferEvent::connect — Connect buffer event's file descriptor to given address or UNIX socket
    • EventBufferEvent::connectHost — Connects to a hostname with optionally asyncronous DNS resolving
    • EventBufferEvent::__construct — Constructs EventBufferEvent object
    • EventBufferEvent::createPair — Creates two buffer events connected to each other
    • EventBufferEvent::disable — Disable events read, write, or both on a buffer event
    • EventBufferEvent::enable — Enable events read, write, or both on a buffer event
    • EventBufferEvent::free — Free a buffer event
    • EventBufferEvent::getDnsErrorString — Returns string describing the last failed DNS lookup attempt
    • EventBufferEvent::getEnabled — Returns bitmask of events currently enabled on the buffer event
    • EventBufferEvent::getInput — Returns underlying input buffer associated with current buffer event
    • EventBufferEvent::getOutput — Returns underlying output buffer associated with current buffer event
    • EventBufferEvent::read — Read buffer's data
    • EventBufferEvent::readBuffer — Drains the entire contents of the input buffer and places them into buf
    • EventBufferEvent::setCallbacks — Assigns read, write and event(status) callbacks
    • EventBufferEvent::setPriority — Assign a priority to a bufferevent
    • EventBufferEvent::setTimeouts — Set the read and write timeout for a buffer event
    • EventBufferEvent::setWatermark — Adjusts read and/or write watermarks
    • EventBufferEvent::sslError — Returns most recent OpenSSL error reported on the buffer event
    • EventBufferEvent::sslFilter — Create a new SSL buffer event to send its data over another buffer event
    • EventBufferEvent::sslGetCipherInfo — Returns a textual description of the cipher
    • EventBufferEvent::sslGetCipherName — Returns the current cipher name of the SSL connection
    • EventBufferEvent::sslGetCipherVersion — Returns version of cipher used by current SSL connection
    • EventBufferEvent::sslGetProtocol — Returns the name of the protocol used for current SSL connection
    • EventBufferEvent::sslRenegotiate — Tells a bufferevent to begin SSL renegotiation
    • EventBufferEvent::sslSocket — Creates a new SSL buffer event to send its data over an SSL on a socket
    • EventBufferEvent::write — Adds data to a buffer event's output buffer
    • EventBufferEvent::writeBuffer — Adds contents of the entire buffer to a buffer event's output buffer
  • About buffer event callbacks
  • EventConfig — The EventConfig class
    • EventConfig::avoidMethod — Tells libevent to avoid specific event method
    • EventConfig::__construct — Constructs EventConfig object
    • EventConfig::requireFeatures — Enters a required event method feature that the application demands
    • EventConfig::setMaxDispatchInterval — Prevents priority inversion
  • EventDnsBase — The EventDnsBase class
    • EventDnsBase::addNameserverIp — Adds a nameserver to the DNS base
    • EventDnsBase::addSearch — Adds a domain to the list of search domains
    • EventDnsBase::clearSearch — Removes all current search suffixes
    • EventDnsBase::__construct — Constructs EventDnsBase object
    • EventDnsBase::countNameservers — Gets the number of configured nameservers
    • EventDnsBase::loadHosts — Loads a hosts file (in the same format as /etc/hosts) from hosts file
    • EventDnsBase::parseResolvConf — Scans the resolv.conf-formatted file
    • EventDnsBase::setOption — Set the value of a configuration option
    • EventDnsBase::setSearchNdots — Set the 'ndots' parameter for searches
  • EventHttp — The EventHttp class
    • EventHttp::accept — Makes an HTTP server accept connections on the specified socket stream or resource
    • EventHttp::addServerAlias — Adds a server alias to the HTTP server object
    • EventHttp::bind — Binds an HTTP server on the specified address and port
    • EventHttp::__construct — Constructs EventHttp object(the HTTP server)
    • EventHttp::removeServerAlias — Removes server alias
    • EventHttp::setAllowedMethods — Sets the what HTTP methods are supported in requests accepted by this server, and passed to user callbacks
    • EventHttp::setCallback — Sets a callback for specified URI
    • EventHttp::setDefaultCallback — Sets default callback to handle requests that are not caught by specific callbacks
    • EventHttp::setMaxBodySize — Sets maximum request body size
    • EventHttp::setMaxHeadersSize — Sets maximum HTTP header size
    • EventHttp::setTimeout — Sets the timeout for an HTTP request
  • EventHttpConnection — The EventHttpConnection class
    • EventHttpConnection::__construct — Constructs EventHttpConnection object
    • EventHttpConnection::getBase — Returns event base associated with the connection
    • EventHttpConnection::getPeer — Gets the remote address and port associated with the connection
    • EventHttpConnection::makeRequest — Makes an HTTP request over the specified connection
    • EventHttpConnection::setCloseCallback — Set callback for connection close
    • EventHttpConnection::setLocalAddress — Sets the IP address from which HTTP connections are made
    • EventHttpConnection::setLocalPort — Sets the local port from which connections are made
    • EventHttpConnection::setMaxBodySize — Sets maximum body size for the connection
    • EventHttpConnection::setMaxHeadersSize — Sets maximum header size
    • EventHttpConnection::setRetries — Sets the retry limit for the connection
    • EventHttpConnection::setTimeout — Sets the timeout for the connection
  • EventHttpRequest — The EventHttpRequest class
    • EventHttpRequest::addHeader — Adds an HTTP header to the headers of the request
    • EventHttpRequest::cancel — Cancels a pending HTTP request
    • EventHttpRequest::clearHeaders — Removes all output headers from the header list of the request
    • EventHttpRequest::closeConnection — Closes associated HTTP connection
    • EventHttpRequest::__construct — Constructs EventHttpRequest object
    • EventHttpRequest::findHeader — Finds the value belonging a header
    • EventHttpRequest::free — Frees the object and removes associated events
    • EventHttpRequest::getBufferEvent — Returns EventBufferEvent object
    • EventHttpRequest::getCommand — Returns the request command(method)
    • EventHttpRequest::getConnection — Returns EventHttpConnection object
    • EventHttpRequest::getHost — Returns the request host
    • EventHttpRequest::getInputBuffer — Returns the input buffer
    • EventHttpRequest::getInputHeaders — Returns associative array of the input headers
    • EventHttpRequest::getOutputBuffer — Returns the output buffer of the request
    • EventHttpRequest::getOutputHeaders — Returns associative array of the output headers
    • EventHttpRequest::getResponseCode — Returns the response code
    • EventHttpRequest::getUri — Returns the request URI
    • EventHttpRequest::removeHeader — Removes an HTTP header from the headers of the request
    • EventHttpRequest::sendError — Send an HTML error message to the client
    • EventHttpRequest::sendReply — Send an HTML reply to the client
    • EventHttpRequest::sendReplyChunk — Send another data chunk as part of an ongoing chunked reply
    • EventHttpRequest::sendReplyEnd — Complete a chunked reply, freeing the request as appropriate
    • EventHttpRequest::sendReplyStart — Initiate a chunked reply
  • EventListener — The EventListener class
    • EventListener::__construct — Creates new connection listener associated with an event base
    • EventListener::disable — Disables an event connect listener object
    • EventListener::enable — Enables an event connect listener object
    • EventListener::getBase — Returns event base associated with the event listener
    • EventListener::getSocketName — Retreives the current address to which the listener's socket is bound
    • EventListener::setCallback — The setCallback purpose
    • EventListener::setErrorCallback — Set event listener's error callback
  • EventSslContext — The EventSslContext class
    • EventSslContext::__construct — Constructs an OpenSSL context for use with Event classes
  • EventUtil — The EventUtil class
    • EventUtil::__construct — The abstract constructor
    • EventUtil::getLastSocketErrno — Returns the most recent socket error number
    • EventUtil::getLastSocketError — Returns the most recent socket error
    • EventUtil::getSocketFd — Returns numeric file descriptor of a socket, or stream
    • EventUtil::getSocketName — Retreives the current address to which the socket is bound
    • EventUtil::setSocketOption — Sets socket options
    • EventUtil::sslRandPoll — Generates entropy by means of OpenSSL's RAND_poll()


Introduction

This is an extension to efficiently schedule I/O, time and signal based events using the best I/O notification mechanism available for specific platform. This is a port of libevent to the PHP infrastructure.

Note:

Note, Windows support introduced in event-1.9.0 .

Version 1.0.0 introduces new object-oriented API (breaking backwards compatibility), and support of libevent 2+ including HTTP, DNS, OpenSSL and the event listener.

Note:

Note, event-1.0.0 and greater is not compatible with previous versions.


Requirements

This extension requires » libevent library. Most modern distributions provide packages for libevent.

OpenSSL features require » OpenSSL library.


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/event .


Examples

Example #1 Simple HTTP client

<?php
// Read callback
function readcb($bev, $base) {
    //$input = $bev->input; //$bev->getInput();

    //$pos = $input->search("TTP");
    $pos = $bev->input->search("TTP");

    while (($n = $bev->input->remove($buf, 1024)) > 0) {
        echo $buf;
    }
}

// Event callback
function eventcb($bev, $events, $base) {
    if ($events & EventBufferEvent::CONNECTED) {
        echo "Connected.\n";
    } elseif ($events & (EventBufferEvent::ERROR | EventBufferEvent::EOF)) {
        if ($events & EventBufferEvent::ERROR) {
            echo "DNS error: ", $bev->getDnsErrorString(), PHP_EOL;
        }

        echo "Closing\n";
        $base->exit();
        exit("Done\n");
    }
}

if ($argc != 3) {
    echo <<<EOS
Trivial HTTP 0.x client
Syntax: php {$argv[0]} [hostname] [resource]
Example: php {$argv[0]} www.google.com /

EOS;
    exit();
}

$base = new EventBase();

$dns_base = new EventDnsBase($base, TRUE); // We'll use async DNS resolving
if (!$dns_base) {
    exit("Failed to init DNS Base\n");
}

$bev = new EventBufferEvent($base, /* use internal socket */ NULL,
    EventBufferEvent::OPT_CLOSE_ON_FREE | EventBufferEvent::OPT_DEFER_CALLBACKS,
    "readcb", /* writecb */ NULL, "eventcb"
);
if (!$bev) {
    exit("Failed creating bufferevent socket\n");
}

//$bev->setCallbacks("readcb", /* writecb */ NULL, "eventcb", $base);
$bev->enable(Event::READ | Event::WRITE);

$output = $bev->output; //$bev->getOutput();
if (!$output->add(
    "GET {$argv[2]} HTTP/1.0\r\n".
    "Host: {$argv[1]}\r\n".
    "Connection: Close\r\n\r\n"
)) {
    exit("Failed adding request to output buffer\n");
}

if (!$bev->connectHost($dns_base, $argv[1], 80, EventUtil::AF_UNSPEC)) {
    exit("Can't connect to host {$argv[1]}\n");
}

$base->dispatch();
?>

The above example will output something similar to:

Connected.
HTTP/1.1 301 Moved Permanently
Date: Fri, 01 Mar 2013 18:47:48 GMT
Location: http://www.google.co.uk/
Content-Type: text/html; charset=UTF-8
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 221
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Age: 133438
Expires: Sat, 30 Mar 2013 05:39:28 GMT
Connection: close

<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.co.uk/">here</A>.
</BODY></HTML>
Closing
Done

Example #2 HTTP client using asynchronous DNS resolver

<?php
/*
 * 1. Connect to 127.0.0.1 at port 80
 * by means of EventBufferEvent::connect().
 *
 * 2. Request /index.cphp via HTTP/1.0
 * using the output buffer.
 *
 * 3. Asyncronously read the response and print it to stdout.
 */

// Read callback
function readcb($bev, $base) {
    $input = $bev->getInput();

    while (($n = $input->remove($buf, 1024)) > 0) {
        echo $buf;
    }
}

// Event callback
function eventcb($bev, $events, $base) {
    if ($events & EventBufferEvent::CONNECTED) {
        echo "Connected.\n";
    } elseif ($events & (EventBufferEvent::ERROR | EventBufferEvent::EOF)) {
        if ($events & EventBufferEvent::ERROR) {
            echo "DNS error: ", $bev->getDnsErrorString(), PHP_EOL;
        }

        echo "Closing\n";
        $base->exit();
        exit("Done\n");
    }
}

$base = new EventBase();

echo "step 1\n";
$bev = new EventBufferEvent($base, /* use internal socket */ NULL,
    EventBufferEvent::OPT_CLOSE_ON_FREE | EventBufferEvent::OPT_DEFER_CALLBACKS);
if (!$bev) {
    exit("Failed creating bufferevent socket\n");
}

echo "step 2\n";
$bev->setCallbacks("readcb", /* writecb */ NULL, "eventcb", $base);
$bev->enable(Event::READ | Event::WRITE);

echo "step 3\n";
// Send request
$output = $bev->getOutput();
if (!$output->add(
    "GET /index.cphp HTTP/1.0\r\n".
    "Connection: Close\r\n\r\n"
)) {
    exit("Failed adding request to output buffer\n");
}

/* Connect to the host syncronously.
We know the IP, and don't need to resolve DNS. */
if (!$bev->connect("127.0.0.1:80")) {
    exit("Can't connect to host\n");
}

// Dispatch pending events
$base->dispatch();
?>

Example #3 Echo server

<?php
/*
 * Simple echo server based on libevent's connection listener.
 *
 * Usage:
 * 1) In one terminal window run:
 *
 * $ php listener.php 9881
 *
 * 2) In another terminal window open up connection, e.g.:
 *
 * $ nc 127.0.0.1 9881
 *
 * 3) start typing. The server should repeat the input.
 */

class MyListenerConnection {
    private $bev, $base;

    public function __destruct() {
        $this->bev->free();
    }

    public function __construct($base, $fd) {
        $this->base = $base;

        $this->bev = new EventBufferEvent($base, $fd, EventBufferEvent::OPT_CLOSE_ON_FREE);

        $this->bev->setCallbacks(array($this, "echoReadCallback"), NULL,
            array($this, "echoEventCallback"), NULL);

        if (!$this->bev->enable(Event::READ)) {
            echo "Failed to enable READ\n";
            return;
        }
    }

    public function echoReadCallback($bev, $ctx) {
        // Copy all the data from the input buffer to the output buffer

        // Variant #1
        $bev->output->addBuffer($bev->input);

        /* Variant #2 */
        /*
        $input    = $bev->getInput();
        $output = $bev->getOutput();
        $output->addBuffer($input);
        */
    }

    public function echoEventCallback($bev, $events, $ctx) {
        if ($events & EventBufferEvent::ERROR) {
            echo "Error from bufferevent\n";
        }

        if ($events & (EventBufferEvent::EOF | EventBufferEvent::ERROR)) {
            //$bev->free();
            $this->__destruct();
        }
    }
}

class MyListener {
    public $base,
        $listener,
        $socket;
    private $conn = array();

    public function __destruct() {
        foreach ($this->conn as &$c) $c = NULL;
    }

    public function __construct($port) {
        $this->base = new EventBase();
        if (!$this->base) {
            echo "Couldn't open event base";
            exit(1);
        }

        // Variant #1
        /*
        $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        if (!socket_bind($this->socket, '0.0.0.0', $port)) {
            echo "Unable to bind socket\n";
            exit(1);
        }
        $this->listener = new EventListener($this->base,
            array($this, "acceptConnCallback"), $this->base,
            EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE,
            -1, $this->socket);
         */

        // Variant #2
         $this->listener = new EventListener($this->base,
             array($this, "acceptConnCallback"), $this->base,
             EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE, -1,
             "0.0.0.0:$port");

        if (!$this->listener) {
            echo "Couldn't create listener";
            exit(1);
        }

        $this->listener->setErrorCallback(array($this, "accept_error_cb"));
    }

    public function dispatch() {
        $this->base->dispatch();
    }

    // This callback is invoked when there is data to read on $bev
    public function acceptConnCallback($listener, $fd, $address, $ctx) {
        // We got a new connection! Set up a bufferevent for it. */
        $base = $this->base;
        $this->conn[] = new MyListenerConnection($base, $fd);
    }

    public function accept_error_cb($listener, $ctx) {
        $base = $this->base;

        fprintf(STDERR, "Got an error %d (%s) on the listener. "
            ."Shutting down.\n",
            EventUtil::getLastSocketErrno(),
            EventUtil::getLastSocketError());

        $base->exit(NULL);
    }
}

$port = 9808;

if ($argc > 1) {
    $port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
    exit("Invalid port");
}

$l = new MyListener($port);
$l->dispatch();
?>

Example #4 SSL echo server

<?php
/*
 * SSL echo server
 *
 * To test:
 * 1) Run:
 * $ php examples/ssl-echo-server/server.php 9998
 *
 * 2) in another terminal window run:
 * $ socat - SSL:127.0.0.1:9998,verify=1,cafile=examples/ssl-echo-server/cert.pem
 */

class MySslEchoServer {
    public $port,
        $base,
        $bev,
        $listener,
        $ctx;

    function __construct ($port, $host = "127.0.0.1") {
        $this->port = $port;
        $this->ctx = $this->init_ssl();
        if (!$this->ctx) {
            exit("Failed creating SSL context\n");
        }

        $this->base = new EventBase();
        if (!$this->base) {
            exit("Couldn't open event base\n");
        }

        $this->listener = new EventListener($this->base,
            array($this, "ssl_accept_cb"), $this->ctx,
            EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE,
            -1, "$host:$port");
        if (!$this->listener) {
            exit("Couldn't create listener\n");
        }

        $this->listener->setErrorCallback(array($this, "accept_error_cb"));
    }
    function dispatch() {
        $this->base->dispatch();
    }

    // This callback is invoked when there is data to read on $bev.
    function ssl_read_cb($bev, $ctx) {
        $in = $bev->input; //$bev->getInput();

        printf("Received %zu bytes\n", $in->length);
        printf("----- data ----\n");
        printf("%ld:\t%s\n", (int) $in->length, $in->pullup(-1));

        $bev->writeBuffer($in);
    }

    // This callback is invoked when some even occurs on the event listener,
    // e.g. connection closed, or an error occurred
    function ssl_event_cb($bev, $events, $ctx) {
        if ($events & EventBufferEvent::ERROR) {
            // Fetch errors from the SSL error stack
            while ($err = $bev->sslError()) {
                fprintf(STDERR, "Bufferevent error %s.\n", $err);
            }
        }

        if ($events & (EventBufferEvent::EOF | EventBufferEvent::ERROR)) {
            $bev->free();
        }
    }

    // This callback is invoked when a client accepts new connection
    function ssl_accept_cb($listener, $fd, $address, $ctx) {
        // We got a new connection! Set up a bufferevent for it.
        $this->bev = EventBufferEvent::sslSocket($this->base, $fd, $this->ctx,
            EventBufferEvent::SSL_ACCEPTING, EventBufferEvent::OPT_CLOSE_ON_FREE);

        if (!$this->bev) {
            echo "Failed creating ssl buffer\n";
            $this->base->exit(NULL);
            exit(1);
        }

        $this->bev->enable(Event::READ);
        $this->bev->setCallbacks(array($this, "ssl_read_cb"), NULL,
            array($this, "ssl_event_cb"), NULL);
    }

    // This callback is invoked when we failed to setup new connection for a client
    function accept_error_cb($listener, $ctx) {
        fprintf(STDERR, "Got an error %d (%s) on the listener. "
            ."Shutting down.\n",
            EventUtil::getLastSocketErrno(),
            EventUtil::getLastSocketError());

        $this->base->exit(NULL);
    }

    // Initialize SSL structures, create an EventSslContext
    // Optionally create self-signed certificates
    function init_ssl() {
        // We *must* have entropy. Otherwise there's no point to crypto.
        if (!EventUtil::sslRandPoll()) {
            exit("EventUtil::sslRandPoll failed\n");
        }

        $local_cert = __DIR__."/cert.pem";
        $local_pk   = __DIR__."/privkey.pem";

        if (!file_exists($local_cert) || !file_exists($local_pk)) {
            echo "Couldn't read $local_cert or $local_pk file.  To generate a key\n",
                "and self-signed certificate, run:\n",
                "  openssl genrsa -out $local_pk 2048\n",
                "  openssl req -new -key $local_pk -out cert.req\n",
                "  openssl x509 -req -days 365 -in cert.req -signkey $local_pk -out $local_cert\n";

            return FALSE;
        }

        $ctx = new EventSslContext(EventSslContext::SSLv3_SERVER_METHOD, array (
             EventSslContext::OPT_LOCAL_CERT  => $local_cert,
             EventSslContext::OPT_LOCAL_PK    => $local_pk,
             //EventSslContext::OPT_PASSPHRASE  => "echo server",
             EventSslContext::OPT_VERIFY_PEER => true,
             EventSslContext::OPT_ALLOW_SELF_SIGNED => false,
        ));

        return $ctx;
    }
}

// Allow to override the port
$port = 9999;
if ($argc > 1) {
    $port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
    exit("Invalid port\n");
}

$l = new MySslEchoServer($port);
$l->dispatch();
?>

Example #5 Signal handler

<?php
/*
Launch it in a terminal window:

$ php examples/signal.php

In another terminal window find out the pid and send SIGTERM, e.g.:

$ ps aux | grep examp
ruslan    3976  0.2  0.0 139896 11256 pts/1    S+   10:25   0:00 php examples/signal.php
ruslan    3978  0.0  0.0   9572   864 pts/2    S+   10:26   0:00 grep --color=auto examp
$ kill -TERM 3976

At the first terminal window you should catch the following:

Caught signal 15
*/
class MyEventSignal {
    private $base;

    function __construct($base) {
        $this->base = $base;
    }

    function eventSighandler($no, $c) {
        echo "Caught signal $no\n";
        event_base_loopexit($c->base);
    }
}

$base = event_base_new();
$c    = new MyEventSignal($base);
$no   = SIGTERM;
$ev   = evsignal_new($base, $no, array($c,'eventSighandler'), $c);

evsignal_add($ev);

event_base_loop($base);
?>

Example #6 Use libevent's loop to process requests of `eio' extension

<?php
// Callback for eio_nop()
function my_nop_cb($d, $r) {
    echo "step 6\n";
}

$dir = "/tmp/abc-eio-temp";
if (file_exists($dir)) {
    rmdir($dir);
}

echo "step 1\n";

$base = new EventBase();

echo "step 2\n";

eio_init();

eio_mkdir($dir, 0750, EIO_PRI_DEFAULT, "my_nop_cb");

$event = new Event($base, eio_get_event_stream(),
    Event::READ | Event::PERSIST, function ($fd, $events, $base) {
    echo "step 5\n";

    while (eio_nreqs()) {
        eio_poll();
    }

    $base->stop();
}, $base);

echo "step 3\n";

$event->add();

echo "step 4\n";

$base->dispatch();

echo "Done\n";
?>

Example #7 Miscellaneous

<?php
/* {{{ Config & supported stuff */
echo "Supported methods:\n";
foreach (Event::getSupportedMethods() as $m) {
    echo $m, PHP_EOL;
}

// Avoiding "select" method
$cfg = new EventConfig();
if ($cfg->avoidMethod("select")) {
    echo "`select' method avoided\n";
}

// Create event_base associated with the config
$base = new EventBase($cfg);
echo "Event method used: ", $base->getMethod(), PHP_EOL;

echo "Features:\n";
$features = $base->getFeatures();
($features & EventConfig::FEATURE_ET) and print("ET - edge-triggered IO\n");
($features & EventConfig::FEATURE_O1) and print("O1 - O(1) operation for adding/deletting events\n");
($features & EventConfig::FEATURE_FDS) and print("FDS - arbitrary file descriptor types, and not just sockets\n");

// Require FDS feature
if ($cfg->requireFeatures(EventConfig::FEATURE_FDS)) {
    echo "FDS feature is now requried\n";

    $base = new EventBase($cfg);
    ($base->getFeatures() & EventConfig::FEATURE_FDS)
        and print("FDS - arbitrary file descriptor types, and not just sockets\n");
}
/* }}} */

/* {{{ Base */
$base = new EventBase();
$event = new Event($base, STDIN, Event::READ | Event::PERSIST, function ($fd, $events, $arg) {
    static $max_iterations = 0;

    if (++$max_iterations >= 5) {
        /* exit after 5 iterations with timeout of 2.33 seconds */
        echo "Stopping...\n";
        $arg[0]->exit(2.33);
    }

    echo fgets($fd);
}, array (&$base));

$event->add();
$base->loop();
/* Base }}} */
?>

Example #8 Simple HTTP server

<?php
/*
 * Simple HTTP server.
 *
 * To test it:
 * 1) Run it on a port of your choice, e.g.:
 * $ php examples/http.php 8010
 * 2) In another terminal connect to some address on this port
 * and make GET or POST request(others are turned off here), e.g.:
 * $ nc -t 127.0.0.1 8010
 * POST /about HTTP/1.0
 * Content-Type: text/plain
 * Content-Length: 4
 * Connection: close
 * (press Enter)
 *
 * It will output
 * a=12
 * HTTP/1.0 200 OK
 * Content-Type: text/html; charset=ISO-8859-1
 * Connection: close
 *
 * $ nc -t 127.0.0.1 8010
 * GET /dump HTTP/1.0
 * Content-Type: text/plain
 * Content-Encoding: UTF-8
 * Connection: close
 * (press Enter)
 *
 * It will output:
 * HTTP/1.0 200 OK
 * Content-Type: text/html; charset=ISO-8859-1
 * Connection: close
 * (press Enter)
 *
 * $ nc -t 127.0.0.1 8010
 * GET /unknown HTTP/1.0
 * Connection: close
 *
 * It will output:
 * HTTP/1.0 200 OK
 * Content-Type: text/html; charset=ISO-8859-1
 * Connection: close
 *
 * 3) See what the server outputs on the previous terminal window.
 */

function _http_dump($req, $data) {
    static $counter      = 0;
    static $max_requests = 2;

    if (++$counter >= $max_requests)  {
        echo "Counter reached max requests $max_requests. Exiting\n";
        exit();
    }

    echo __METHOD__, " called\n";
    echo "request:"; var_dump($req);
    echo "data:"; var_dump($data);

    echo "\n===== DUMP =====\n";
    echo "Command:", $req->getCommand(), PHP_EOL;
    echo "URI:", $req->getUri(), PHP_EOL;
    echo "Input headers:"; var_dump($req->getInputHeaders());
    echo "Output headers:"; var_dump($req->getOutputHeaders());

    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";

    echo "\n >> Reading input buffer ...\n";
    $buf = $req->getInputBuffer();
    while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
        echo $s, PHP_EOL;
    }
    echo "No more data in the buffer\n";
}

function _http_about($req) {
    echo __METHOD__, PHP_EOL;
    echo "URI: ", $req->getUri(), PHP_EOL;
    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";
}

function _http_default($req, $data) {
    echo __METHOD__, PHP_EOL;
    echo "URI: ", $req->getUri(), PHP_EOL;
    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";
}

$port = 8010;
if ($argc > 1) {
    $port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
    exit("Invalid port");
}

$base = new EventBase();
$http = new EventHttp($base);
$http->setAllowedMethods(EventHttpRequest::CMD_GET | EventHttpRequest::CMD_POST);

$http->setCallback("/dump", "_http_dump", array(4, 8));
$http->setCallback("/about", "_http_about");
$http->setDefaultCallback("_http_default", "custom data value");

$http->bind("0.0.0.0", 8010);
$base->loop();
?>

The above example will output something similar to:

a=12
HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close

HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close
(press Enter)

HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close

Example #9 Simple HTTPS server

<?php
/*
 * Simple HTTPS server.
 *
 * 1) Run the server: `php examples/https.php 9999`
 * 2) Test it: `php examples/ssl-connection.php 9999`
 */

function _http_dump($req, $data) {
    static $counter      = 0;
    static $max_requests = 200;

    if (++$counter >= $max_requests)  {
        echo "Counter reached max requests $max_requests. Exiting\n";
        exit();
    }

    echo __METHOD__, " called\n";
    echo "request:"; var_dump($req);
    echo "data:"; var_dump($data);

    echo "\n===== DUMP =====\n";
    echo "Command:", $req->getCommand(), PHP_EOL;
    echo "URI:", $req->getUri(), PHP_EOL;
    echo "Input headers:"; var_dump($req->getInputHeaders());
    echo "Output headers:"; var_dump($req->getOutputHeaders());

    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";

    $buf = $req->getInputBuffer();
    echo "\n >> Reading input buffer (", $buf->length, ") ...\n";
    while ($s = $buf->read(1024)) {
        echo $s;
    }
    echo "\nNo more data in the buffer\n";
}

function _http_about($req) {
    echo __METHOD__, PHP_EOL;
    echo "URI: ", $req->getUri(), PHP_EOL;
    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";
}

function _http_default($req, $data) {
    echo __METHOD__, PHP_EOL;
    echo "URI: ", $req->getUri(), PHP_EOL;
    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";
}

function _http_400($req) {
    $req->sendError(400);
}

function _init_ssl() {
    $local_cert = __DIR__."/ssl-echo-server/cert.pem";
    $local_pk   = __DIR__."/ssl-echo-server/privkey.pem";

    $ctx = new EventSslContext(EventSslContext::SSLv3_SERVER_METHOD, array (
        EventSslContext::OPT_LOCAL_CERT  => $local_cert,
        EventSslContext::OPT_LOCAL_PK    => $local_pk,
        //EventSslContext::OPT_PASSPHRASE  => "test",
        EventSslContext::OPT_ALLOW_SELF_SIGNED => true,
    ));

    return $ctx;
}

$port = 9999;
if ($argc > 1) {
    $port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
    exit("Invalid port");
}
$ip = '0.0.0.0';

$base = new EventBase();
$ctx  = _init_ssl();
$http = new EventHttp($base, $ctx);
$http->setAllowedMethods(EventHttpRequest::CMD_GET | EventHttpRequest::CMD_POST);

$http->setCallback("/dump", "_http_dump", array(4, 8));
$http->setCallback("/about", "_http_about");
$http->setCallback("/err400", "_http_400");
$http->setDefaultCallback("_http_default", "custom data value");

$http->bind($ip, $port);
$base->dispatch();

Example #10 OpenSSL connection

<?php
/*
 * Sample OpenSSL client.
 *
 * Usage:
 * 1) Launch a server, e.g.:
 * $ php examples/https.php 9999
 *
 * 2) Launch the client in another terminal:
 * $ php examples/ssl-connection.php 9999
 */

function _request_handler($req, $base) {
    echo __FUNCTION__, PHP_EOL;

    if (is_null($req)) {
        echo "Timed out\n";
    } else {
        $response_code = $req->getResponseCode();

        if ($response_code == 0) {
            echo "Connection refused\n";
        } elseif ($response_code != 200) {
            echo "Unexpected response: $response_code\n";
        } else {
            echo "Success: $response_code\n";
            $buf = $req->getInputBuffer();
            echo "Body:\n";
            while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
                echo $s, PHP_EOL;
            }
        }
    }

    $base->exit(NULL);
}

function _init_ssl() {
    $ctx = new EventSslContext(EventSslContext::SSLv3_CLIENT_METHOD, array ());

    return $ctx;
}

// Allow to override the port
$port = 9999;
if ($argc > 1) {
    $port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
    exit("Invalid port\n");
}
$host = '127.0.0.1';

$ctx = _init_ssl();
if (!$ctx) {
    trigger_error("Failed creating SSL context", E_USER_ERROR);
}

$base = new EventBase();
if (!$base) {
    trigger_error("Failed to initialize event base", E_USER_ERROR);
}

$conn = new EventHttpConnection($base, NULL, $host, $port, $ctx);
$conn->setTimeout(50);

$req = new EventHttpRequest("_request_handler", $base);
$req->addHeader("Host", $host, EventHttpRequest::OUTPUT_HEADER);
$buf = $req->getOutputBuffer();
$buf->add("<html>HTML TEST</html>");
//$req->addHeader("Content-Length", $buf->length, EventHttpRequest::OUTPUT_HEADER);
//$req->addHeader("Connection", "close", EventHttpRequest::OUTPUT_HEADER);
$conn->makeRequest($req, EventHttpRequest::CMD_POST, "/dump");

$base->dispatch();
echo "END\n";
?>

Example #11 EventHttpConnection::makeRequest() example

<?php
function _request_handler($req, $base) {
    echo __FUNCTION__, PHP_EOL;

    if (is_null($req)) {
        echo "Timed out\n";
    } else {
        $response_code = $req->getResponseCode();

        if ($response_code == 0) {
            echo "Connection refused\n";
        } elseif ($response_code != 200) {
            echo "Unexpected response: $response_code\n";
        } else {
            echo "Success: $response_code\n";
            $buf = $req->getInputBuffer();
            echo "Body:\n";
            while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
                echo $s, PHP_EOL;
            }
        }
    }

    $base->exit(NULL);
}

$address = "127.0.0.1";
$port = 80;

$base = new EventBase();
$conn = new EventHttpConnection($base, NULL, $address, $port);
$conn->setTimeout(5);
$req = new EventHttpRequest("_request_handler", $base);

$req->addHeader("Host", $address, EventHttpRequest::OUTPUT_HEADER);
$req->addHeader("Content-Length", "0", EventHttpRequest::OUTPUT_HEADER);
$conn->makeRequest($req, EventHttpRequest::CMD_GET, "/index.cphp");

$base->loop();
?>

The above example will output something similar to:

_request_handler
Success: 200
Body:
PHP, date:
2013-03-13T20:27:52+05:00

Example #12 Connection listener based on a UNIX domain socket

<?php
/*
 * Simple echo server based on libevent's connection listener.
 *
 * Usage:
 * 1) In one terminal window run:
 *
 * $ php unix-domain-listener.php [path-to-socket]
 *
 * 2) In another terminal window open up connection
 * to the socket, e.g.:
 *
 * $ socat - GOPEN:/tmp/1.sock
 *
 * 3) Start typing. The server should repeat the input.
 */

class MyListenerConnection {
    private $bev, $base;

    public function __destruct() {
        if ($this->bev) {
            $this->bev->free();
        }
    }

    public function __construct($base, $fd) {
        $this->base = $base;

        $this->bev = new EventBufferEvent($base, $fd, EventBufferEvent::OPT_CLOSE_ON_FREE);

        $this->bev->setCallbacks(array($this, "echoReadCallback"), NULL,
            array($this, "echoEventCallback"), NULL);

        if (!$this->bev->enable(Event::READ)) {
            echo "Failed to enable READ\n";
            return;
        }
    }

    public function echoReadCallback($bev, $ctx) {
        // Copy all the data from the input buffer to the output buffer
        $bev->output->addBuffer($bev->input);
    }

    public function echoEventCallback($bev, $events, $ctx) {
        if ($events & EventBufferEvent::ERROR) {
            echo "Error from bufferevent\n";
        }

        if ($events & (EventBufferEvent::EOF | EventBufferEvent::ERROR)) {
            $bev->free();
            $bev = NULL;
        }
    }
}

class MyListener {
    public $base,
        $listener,
        $socket;
    private $conn = array();

    public function __destruct() {
        foreach ($this->conn as &$c) $c = NULL;
    }

    public function __construct($sock_path) {
        $this->base = new EventBase();
        if (!$this->base) {
            echo "Couldn't open event base";
            exit(1);
        }

        if (file_exists($sock_path)) {
            unlink($sock_path);
        }

         $this->listener = new EventListener($this->base,
             array($this, "acceptConnCallback"), $this->base,
             EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE, -1,
             "unix:$sock_path");

        if (!$this->listener) {
            trigger_error("Couldn't create listener", E_USER_ERROR);
        }

        $this->listener->setErrorCallback(array($this, "accept_error_cb"));
    }

    public function dispatch() {
        $this->base->dispatch();
    }

    // This callback is invoked when there is data to read on $bev
    public function acceptConnCallback($listener, $fd, $address, $ctx) {
        // We got a new connection! Set up a bufferevent for it. */
        $base = $this->base;
        $this->conn[] = new MyListenerConnection($base, $fd);
    }

    public function accept_error_cb($listener, $ctx) {
        $base = $this->base;

        fprintf(STDERR, "Got an error %d (%s) on the listener. "
            ."Shutting down.\n",
            EventUtil::getLastSocketErrno(),
            EventUtil::getLastSocketError());

        $base->exit(NULL);
    }
}

if ($argc <= 1) {
    exit("Socket path is not provided\n");
}
$sock_path = $argv[1];

$l = new MyListener($sock_path);
$l->dispatch();
?>

Example #13 Simple SMTP server

<?php
 /*
 * Author: Andrew Rose <hello at andrewrose dot co dot uk>
 *
 * Usage:
 * 1) Prepare cert.pem certificate and privkey.pem private key files.
 * 2) Launch the server script
 * 3) Open TLS connection, e.g.:
 *      $ openssl s_client -connect localhost:25 -starttls smtp -crlf
 * 4) Start testing the commands listed in `cmd` method below.
 */

class Handler {
    public $domainName = FALSE;
    public $connections = [];
    public $buffers = [];
    public $maxRead = 256000;

    public function __construct() {
        $this->ctx = new EventSslContext(EventSslContext::SSLv3_SERVER_METHOD, [
            EventSslContext::OPT_LOCAL_CERT  => 'cert.pem',
            EventSslContext::OPT_LOCAL_PK    => 'privkey.pem',
            //EventSslContext::OPT_PASSPHRASE  => '',
            EventSslContext::OPT_VERIFY_PEER => false, // change to true with authentic cert
            EventSslContext::OPT_ALLOW_SELF_SIGNED => true // change to false with authentic cert
        ]);

        $this->base = new EventBase();
        if (!$this->base) {
            exit("Couldn't open event base\n");
        }

        if (!$this->listener = new EventListener($this->base,
            [$this, 'ev_accept'],
            $this->ctx,
            EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE,
            -1,
            '0.0.0.0:25'))
        {
            exit("Couldn't create listener\n");
        }

        $this->listener->setErrorCallback([$this, 'ev_error']);
        $this->base->dispatch();
    }

    public function ev_accept($listener, $fd, $address, $ctx) {
        static $id = 0;
        $id += 1;

        $this->connections[$id]['clientData'] = '';
        $this->connections[$id]['cnx'] = new EventBufferEvent($this->base, $fd,
            EventBufferEvent::OPT_CLOSE_ON_FREE);

        if (!$this->connections[$id]['cnx']) {
            echo "Failed creating buffer\n";
            $this->base->exit(NULL);
            exit(1);
        }

        $this->connections[$id]['cnx']->setCallbacks([$this, "ev_read"], NULL,
            [$this, 'ev_error'], $id);
        $this->connections[$id]['cnx']->enable(Event::READ | Event::WRITE);

        $this->ev_write($id, '220 '.$this->domainName." wazzzap?\r\n");
    }

    function ev_error($listener, $ctx) {
        $errno = EventUtil::getLastSocketErrno();

        fprintf(STDERR, "Got an error %d (%s) on the listener. Shutting down.\n",
            $errno, EventUtil::getLastSocketError());

        if ($errno != 0) {
            $this->base->exit(NULL);
            exit();
        }
    }

    public function ev_close($id) {
        $this->connections[$id]['cnx']->disable(Event::READ | Event::WRITE);
        unset($this->connections[$id]);
    }

    protected function ev_write($id, $string) {
        echo 'S('.$id.'): '.$string;
        $this->connections[$id]['cnx']->write($string);
    }

    public function ev_read($buffer, $id) {
        while($buffer->input->length > 0) {
            $this->connections[$id]['clientData'] .= $buffer->input->read($this->maxRead);
            $clientDataLen = strlen($this->connections[$id]['clientData']);

            if($this->connections[$id]['clientData'][$clientDataLen-1] == "\n"
                && $this->connections[$id]['clientData'][$clientDataLen-2] == "\r")
            {
                // remove the trailing \r\n
                $line = substr($this->connections[$id]['clientData'], 0,
                    strlen($this->connections[$id]['clientData']) - 2);

                $this->connections[$id]['clientData'] = '';
                $this->cmd($buffer, $id, $line);
            }
        }
    }

    protected function cmd($buffer, $id, $line) {
        switch ($line) {
            case strncmp('EHLO ', $line, 4):
                $this->ev_write($id, "250-STARTTLS\r\n");
                $this->ev_write($id, "250 OK ehlo\r\n");
                break;

            case strncmp('HELO ', $line, 4):
                $this->ev_write($id, "250-STARTTLS\r\n");
                $this->ev_write($id, "250 OK helo\r\n");
                break;

            case strncmp('QUIT', $line, 3):
                $this->ev_write($id, "250 OK quit\r\n");
                $this->ev_close($id);
                break;

            case strncmp('STARTTLS', $line, 3):
                $this->ev_write($id, "220 Ready to start TLS\r\n");
                $this->connections[$id]['cnx'] = EventBufferEvent::sslFilter($this->base,
                    $this->connections[$id]['cnx'], $this->ctx,
                    EventBufferEvent::SSL_ACCEPTING,
                    EventBufferEvent::OPT_CLOSE_ON_FREE);
                $this->connections[$id]['cnx']->setCallbacks([$this, "ev_read"], NULL, [$this, 'ev_error'], $id);
                $this->connections[$id]['cnx']->enable(Event::READ | Event::WRITE);
                break;

            default:
                echo 'unknown command: '.$line."\n";
                break;
        }
    }
}

new Handler();


Event flags

Event::READ This flag indicates an event that becomes active when the provided file descriptor (usually a stream resource, or socket) is ready for reading.

Event::WRITE flag indicates an event that becomes active when the provided file descriptor (usually a stream resource, or socket) is ready for writing.

Event::SIGNAL used to implement signal detection. See "Constructing signal events" below.

Event::TIMEOUT indicates an event that becomes active after a timeout elapses. The Event::TIMEOUT flag is ignored when constructing an event: one can either set a timeout when event is added , or not. It is set in the $what argument to the callback function when a timeout has occurred.

See also » Fast portable non-blocking network programming with Libevent, Working with events, Event flags


About event persistence

By default, whenever a pending event becomes active (because its file descriptor is ready to read or write, or because its timeout expires), it becomes non-pending right before its callback is executed. Thus, to make the event pending again one may call Event::add() on it again from inside the callback function.

If the Event::PERSIST flag is set on an event, however, the event is persistent . This means that event remains pending even when its callback is activated. Event::del() method can be called to make it non-pending.

The timeout on a persistent event resets whenever the event's callback runs. Thus, if one has an event with flags Event::READ | Event::PERSIST and a timeout of five seconds, the event will become active:

  1. Whenever the socket or file descriptor is ready for reading.

  2. Whenever five seconds have passed since the event last became active.

See also » Fast portable non-blocking network programming with Libevent, About Event Persistence


Event callbacks

If a callback is registered for an event, it will be called when the event becomes active. To associate a callback with event one can pass a callable to either Event::__construct() , or Event::set() , or one of the factory methods like Event::timer() .

An event callback should match the following prototype:

callback ([ mixed $fd = NULL [, int $what [, mixed $arg = NULL ]]] ) : void

fd

The file descriptor, stream resource or socket associated with the event. For signal event fd is equal to the signal number.

what

Bit mask of all events triggered.

arg

User custom data.

Event::timer() expects the callback to match the following prototype:

callback ([ mixed $arg = NULL ] ) : void

arg

User custom data.

Event::signal() expects the callback to match the following prototype:

callback ([ int $signum [, mixed $arg = NULL ]] ) : void

signum

The number of the triggered signal(e.g. SIGTERM ).

arg

User custom data.


Constructing signal events

Event can also watch for POSIX-style signals. To construct a handler for a signal, use Event::__construct() constructor with Event::SIGNAL flag, or Event::signal() factory method.

Example #1 Handling SIGTERM signal

<?php
/*
Launch it in a terminal window:

$ php examples/signal.php

In another terminal window find out the pid and send SIGTERM, e.g.:

$ ps aux | grep examp
ruslan    3976  0.2  0.0 139896 11256 pts/1    S+   10:25   0:00 php examples/signal.php
ruslan    3978  0.0  0.0   9572   864 pts/2    S+   10:26   0:00 grep --color=auto examp
$ kill -TERM 3976

At the first terminal window you should catch the following:

Caught signal 15
*/
class MyEventSignal {
    private $base, $ev;

    public function __construct($base) {
        $this->base = $base;
        $this->ev = Event::signal($base, SIGTERM, array($this, 'eventSighandler'));
        $this->ev->add();
    }

    public function eventSighandler($no, $c) {
        echo "Caught signal $no\n";
        $this->base->exit();
    }
}

$base = new EventBase();
$c    = new MyEventSignal($base);

$base->loop();
?>

Note that signal callbacks are run in the event loop after the signal occurs, so it is safe for them to call functions that you are not supposed to call from a regular POSIX signal handler.

See also » Fast portable non-blocking network programming with Libevent, Constructing Signal Events .


The Event class

(PECL event >= 1.2.6-beta)

Introduction

Event class represents and event firing on a file descriptor being ready to read from or write to; a file descriptor becoming ready to read from or write to(edge-triggered I/O only); a timeout expiring; a signal occuring; a user-triggered event.

Every event is associated with EventBase . However, event will never fire until it is added (via Event::add() ). An added event remains in pending state until the registered event occurs, thus turning it to active state. To handle events user may register a callback which is called when event becomes active. If event is configured persistent , it remains pending. If it is not persistent, it stops being pending when it's callback runs. Event::del() method deletes event, thus making it non-pending. By means of Event::add() method it could be added again.

Class synopsis

final Event {
/* Constants */
const integer ET = 32 ;
const integer PERSIST = 16 ;
const integer READ = 2 ;
const integer WRITE = 4 ;
const integer SIGNAL = 8 ;
const integer TIMEOUT = 1 ;
/* Properties */
public readonly bool $pending ;
/* Methods */
public add ([ float $timeout ] ) : bool
public addSignal ([ float $timeout ] ) : bool
public addTimer ([ float $timeout ] ) : bool
public __construct ( EventBase $base , mixed $fd , int $what , callable $cb [, mixed $arg = NULL ] )
public del ( void ) : bool
public delSignal ( void ) : bool
public delTimer ( void ) : bool
public free ( void ) : void
public static getSupportedMethods ( void ) : array
public pending ( int $flags ) : bool
public set ( EventBase $base , mixed $fd [, int $what [, callable $cb [, mixed $arg ]]] ) : bool
public setPriority ( int $priority ) : bool
public setTimer ( EventBase $base , callable $cb [, mixed $arg ] ) : bool
public static signal ( EventBase $base , int $signum , callable $cb [, mixed $arg ] ) : Event
public static timer ( EventBase $base , callable $cb [, mixed $arg ] ) : Event
}

Properties

pending

Whether event is pending. See About event persistence .

Predefined Constants

Event::ET

Indicates that the event should be edge-triggered, if the underlying event base backend supports edge-triggered events. This affects the semantics of Event::READ and Event::WRITE .

Event::PERSIST

Indicates that the event is persistent. See About event persistence .

Event::READ

This flag indicates an event that becomes active when the provided file descriptor(usually a stream resource, or socket) is ready for reading.

Event::WRITE

This flag indicates an event that becomes active when the provided file descriptor(usually a stream resource, or socket) is ready for reading.

Event::SIGNAL

Used to implement signal detection. See "Constructing signal events" below.

Event::TIMEOUT

This flag indicates an event that becomes active after a timeout elapses.

The Event::TIMEOUT flag is ignored when constructing an event: one can either set a timeout when event is added , or not. It is set in the $what argument to the callback function when a timeout has occurred.

Table of Contents

  • Event::add — Makes event pending
  • Event::addSignal — Makes signal event pending
  • Event::addTimer — Makes timer event pending
  • Event::__construct — Constructs Event object
  • Event::del — Makes event non-pending
  • Event::delSignal — Makes signal event non-pending
  • Event::delTimer — Makes timer event non-pending
  • Event::free — Make event non-pending and free resources allocated for this event
  • Event::getSupportedMethods — Returns array with of the names of the methods supported in this version of Libevent
  • Event::pending — Detects whether event is pending or scheduled
  • Event::set — Re-configures event
  • Event::setPriority — Set event priority
  • Event::setTimer — Re-configures timer event
  • Event::signal — Constructs signal event object
  • Event::timer — Constructs timer event object


Makes event pending

  • « Event
  • Event::addSignal »
  • PHP Manual
  • Event
  • Makes event pending

Event::add

(PECL libevent >= 0.0.1)

Event::add — Makes event pending

Description

public Event::add ([ float $timeout ] ) : bool

Marks event pending. Non-pending event will never occur, and the event callback will never be called. In conjuction with Event::del() an event could be re-scheduled by user at any time.

If Event::add() is called on an already pending event, libevent will leave it pending and re-schedule it with the given timeout(if specified). If in this case timeout is not specified, Event::add() has no effect.

Parameters

timeout

Timeout in seconds.

Return Values

Returns TRUE on success. Otherwise FALSE

See Also

  • Event::addSignal() - Makes signal event pending
  • Event::addTimer() - Makes timer event pending
  • Event::del() - Makes event non-pending


Makes signal event pending

  • « Event::add
  • Event::addTimer »
  • PHP Manual
  • Event
  • Makes signal event pending

Event::addSignal

(PECL event >= 1.2.6-beta)

Event::addSignal — Makes signal event pending

Description

public Event::addSignal ([ float $timeout ] ) : bool

Event::addSignal() is an alias of Event::add()

Examples

Example #1 Event::addSignal() example

<?php
/*
Launch it in a terminal window:

$ php examples/signal.php

In another terminal window find out the pid and send SIGTERM, e.g.:

$ ps aux | grep examp
ruslan    3976  0.2  0.0 139896 11256 pts/1    S+   10:25   0:00 php examples/signal.php
ruslan    3978  0.0  0.0   9572   864 pts/2    S+   10:26   0:00 grep --color=auto examp
$ kill -TERM 3976

At the first terminal window you should catch the following:

Caught signal 15
*/
class MyEventSignal {
    private $base, $ev;

    public function __construct($base) {
        $this->base = $base;
        $this->ev = Event::signal($base, SIGTERM, array($this, 'eventSighandler'));
        $this->ev->addSignal();
    }

    public function eventSighandler($no, $c) {
        echo "Caught signal $no\n";
        $this->base->exit();
    }
}

$base = new EventBase();
$c    = new MyEventSignal($base);

$base->loop();
?>

The above example will output something similar to:

Caught signal 15

See Also

  • Event::add() - Makes event pending
  • Event::del() - Makes event non-pending
  • Event::delSignal() - Makes signal event non-pending
  • Event::signal() - Constructs signal event object


Makes timer event pending

  • « Event::addSignal
  • Event::__construct »
  • PHP Manual
  • Event
  • Makes timer event pending

Event::addTimer

(PECL event >= 1.2.6-beta)

Event::addTimer — Makes timer event pending

Description

public Event::addTimer ([ float $timeout ] ) : bool

Event::addTimer() is an alias of Event::add()

Return Values

Examples

Example #1 Event::addTimer() example

<?php
$base = new EventBase();
$n = 2;
$e = Event::timer($base, function($n) use (&$e) {
    echo "$n seconds elapsed\n";
    $e->delTimer();
}, $n);
$e->addTimer($n);
$base->loop();
?>

The above example will output something similar to:

2 seconds elapsed

See Also

  • Event::add() - Makes event pending
  • Event::del() - Makes event non-pending
  • Event::delTimer() - Makes timer event non-pending


Constructs Event object

  • « Event::addTimer
  • Event::del »
  • PHP Manual
  • Event
  • Constructs Event object

Event::__construct

(PECL event >= 1.2.6-beta)

Event::__construct — Constructs Event object

Description

public Event::__construct ( EventBase $base , mixed $fd , int $what , callable $cb [, mixed $arg = NULL ] )

Constructs Event object.

Parameters

base

The event base to associate with.

fd

stream resource, socket resource, or numeric file descriptor. For timer events pass -1 . For signal events pass the signal number, e.g. SIGHUP .

what

Event flags. See Event flags .

cb

The event callback. See Event callbacks .

arg

Custom data. If specified, it will be passed to the callback when event triggers.

Return Values

Returns Event object.

See Also

  • Event::signal() - Constructs signal event object
  • Event::timer() - Constructs timer event object


Makes event non-pending

  • « Event::__construct
  • Event::delSignal »
  • PHP Manual
  • Event
  • Makes event non-pending

Event::del

(PECL libevent >= 0.0.1)

Event::del — Makes event non-pending

Description

public Event::del ( void ) : bool

Removes an event from the set of monitored events, i.e. makes it non-pending.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success. Otherwise FALSE

See Also

  • Event::add() - Makes event pending


Makes signal event non-pending

  • « Event::del
  • Event::delTimer »
  • PHP Manual
  • Event
  • Makes signal event non-pending

Event::delSignal

(PECL event >= 1.2.6-beta)

Event::delSignal — Makes signal event non-pending

Description

public Event::delSignal ( void ) : bool

Event::delSignal() is an alias of Event::del()

See Also

  • Event::del() - Makes event non-pending


Makes timer event non-pending

  • « Event::delSignal
  • Event::free »
  • PHP Manual
  • Event
  • Makes timer event non-pending

Event::delTimer

(PECL event >= 1.2.6-beta)

Event::delTimer — Makes timer event non-pending

Description

public Event::delTimer ( void ) : bool

Event::delTimer() is an alias of Event::del() .

See Also

  • Event::del() - Makes event non-pending


Make event non-pending and free resources allocated for this event

  • « Event::delTimer
  • Event::getSupportedMethods »
  • PHP Manual
  • Event
  • Make event non-pending and free resources allocated for this event

Event::free

(PECL libevent >= 0.0.1)

Event::free — Make event non-pending and free resources allocated for this event

Description

public Event::free ( void ) : void

Removes event from the list of events monitored by libevent, and free resources allocated for the event.

Warning

The Event::free() method currently doesn't destruct the object itself. To destruct the object completely call unset() , or assign NULL.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • Event::__construct() - Constructs Event object


Returns array with of the names of the methods supported in this version of Libevent

  • « Event::free
  • Event::pending »
  • PHP Manual
  • Event
  • Returns array with of the names of the methods supported in this version of Libevent

Event::getSupportedMethods

(PECL event >= 1.2.6-beta)

Event::getSupportedMethods — Returns array with of the names of the methods supported in this version of Libevent

Description

public static Event::getSupportedMethods ( void ) : array

Returns array with of the names of the methods(backends) supported in this version of Libevent.

Parameters

This function has no parameters.

Return Values

Returns array.

See Also

  • EventConfig


Detects whether event is pending or scheduled

  • « Event::getSupportedMethods
  • Event::set »
  • PHP Manual
  • Event
  • Detects whether event is pending or scheduled

Event::pending

(PECL event >= 1.2.6-beta)

Event::pending — Detects whether event is pending or scheduled

Description

public Event::pending ( int $flags ) : bool

Detects whether event is pending or scheduled

Parameters

flags

One of, or a composition of the following constants: Event::READ , Event::WRITE , Event::TIMEOUT , Event::SIGNAL .

Return Values

Returns TRUE if event is pending or scheduled. Otherwise FALSE.


Re-configures event

  • « Event::pending
  • Event::setPriority »
  • PHP Manual
  • Event
  • Re-configures event

Event::set

(PECL libevent >= 0.0.1)

Event::set — Re-configures event

Description

public Event::set ( EventBase $base , mixed $fd [, int $what [, callable $cb [, mixed $arg ]]] ) : bool

Re-configures event. Note, this function doesn't invoke obsolete libevent's event_set. It calls event_assign instead.

Parameters

base

The event base to associate the event with.

fd

Stream resource, socket resource, or numeric file descriptor. For timer events pass -1 . For signal events pass the signal number, e.g. SIGHUP .

what

See Event flags .

cb

The event callback. See Event callbacks .

arg

Custom data associated with the event. It will be passed to the callback when the event becomes active.

Return Values

Returns TRUE on success. Otherwise FALSE.


Set event priority

  • « Event::set
  • Event::setTimer »
  • PHP Manual
  • Event
  • Set event priority

Event::setPriority

(PECL event >= 1.2.6-beta)

Event::setPriority — Set event priority

Description

public Event::setPriority ( int $priority ) : bool

Set event priority.

Parameters

priority

The event priority.

Return Values

Returns TRUE on success. Otherwise FALSE.


Re-configures timer event

  • « Event::setPriority
  • Event::signal »
  • PHP Manual
  • Event
  • Re-configures timer event

Event::setTimer

(PECL event >= 1.2.6-beta)

Event::setTimer — Re-configures timer event

Description

public Event::setTimer ( EventBase $base , callable $cb [, mixed $arg ] ) : bool

Re-configures timer event. Note, this function doesn't invoke obsolete libevent's event_set . It calls event_assign instead.

Parameters

base

The event base to associate with.

cb

The timer event callback. See Event callbacks .

arg

Custom data. If specified, it will be passed to the callback when event triggers.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • Event::__construct() - Constructs Event object
  • Event::timer() - Constructs timer event object


Constructs signal event object

  • « Event::setTimer
  • Event::timer »
  • PHP Manual
  • Event
  • Constructs signal event object

Event::signal

(PECL event >= 1.2.6-beta)

Event::signal — Constructs signal event object

Description

public static Event::signal ( EventBase $base , int $signum , callable $cb [, mixed $arg ] ) : Event

Constructs signal event object. This is a straightforward method to create a signal event. Note, the generic Event::__construct() method can contruct signal event objects too.

Parameters

base

The associated event base object.

signum

The signal number.

cb

The signal event callback. See Event callbacks .

arg

Custom data. If specified, it will be passed to the callback when event triggers.

Return Values

Returns Event object on success. Otherwise FALSE.

See Also

  • Constructing signal events


Constructs timer event object

  • « Event::signal
  • EventBase »
  • PHP Manual
  • Event
  • Constructs timer event object

Event::timer

(PECL event >= 1.2.6-beta)

Event::timer — Constructs timer event object

Description

public static Event::timer ( EventBase $base , callable $cb [, mixed $arg ] ) : Event

Constructs timer event object. This is a straightforward method to create a timer event. Note, the generic Event::__construct() method can contruct signal event objects too.

Parameters

base

The associated event base object.

cb

The signal event callback. See Event callbacks .

arg

Custom data. If specified, it will be passed to the callback when event triggers.

Return Values

Returns Event object on success. Otherwise FALSE.


The EventBase class

(PECL event >= 1.2.6-beta)

Introduction

EventBase class represents libevent's event base structure. It holds a set of events and can poll to determine which events are active.

Each event base has a method , or a backend that it uses to determine which events are ready. The recognized methods are: select , poll , epoll , kqueue , devpoll , evport and win32 .

To configure event base to use, or avoid specific backend EventConfig class can be used.

Warning

Do NOT destroy the EventBase object as long as resources of the associated Event objects are not released. Otherwise, it will lead to unpredictable results!

Class synopsis

final EventBase {
/* Constants */
const integer LOOP_ONCE = 1 ;
const integer LOOP_NONBLOCK = 2 ;
const integer NOLOCK = 1 ;
const integer STARTUP_IOCP = 4 ;
const integer NO_CACHE_TIME = 8 ;
const integer EPOLL_USE_CHANGELIST = 16 ;
/* Methods */
public __construct ([ EventConfig $cfg ] )
public dispatch ( void ) : void
public exit ([ float $timeout ] ) : bool
public free ( void ) : void
public getFeatures ( void ) : int
public getMethod ( void ) : string
public getTimeOfDayCached ( void ) : float
public gotExit ( void ) : bool
public gotStop ( void ) : bool
public loop ([ int $flags ] ) : bool
public priorityInit ( int $n_priorities ) : bool
public reInit ( void ) : bool
public stop ( void ) : bool
}

Predefined Constants

EventBase::LOOP_ONCE

Flag used with EventBase::loop() method which means: "block until libevent has an active event, then exit once all active events have had their callbacks run".

EventBase::LOOP_NONBLOCK

Flag used with EventBase::loop() method which means: "do not block: see which events are ready now, run the callbacks of the highest-priority ones, then exit".

EventBase::NOLOCK

Configuration flag. Do not allocate a lock for the event base, even if we have locking set up".

EventBase::STARTUP_IOCP

Windows-only configuration flag. Enables the IOCP dispatcher at startup.

EventBase::NO_CACHE_TIME

Configuration flag. Instead of checking the current time every time the event loop is ready to run timeout callbacks, check after each timeout callback.

EventBase::EPOLL_USE_CHANGELIST

If we are using the epoll backend, this flag says that it is safe to use Libevent's internal change-list code to batch up adds and deletes in order to try to do as few syscalls as possible.

Setting this flag can make code run faster, but it may trigger a Linux bug: it is not safe to use this flag if one has any fds cloned by dup(), or its variants. Doing so will produce strange and hard-to-diagnose bugs.

This flag can also be activated by settnig the EVENT_EPOLL_USE_CHANGELIST environment variable.

This flag has no effect if one winds up using a backend other than epoll .

Table of Contents

  • EventBase::__construct — Constructs EventBase object
  • EventBase::dispatch — Dispatch pending events
  • EventBase::exit — Stop dispatching events
  • EventBase::free — Free resources allocated for this event base
  • EventBase::getFeatures — Returns bitmask of features supported
  • EventBase::getMethod — Returns event method in use
  • EventBase::getTimeOfDayCached — Returns the current event base time
  • EventBase::gotExit — Checks if the event loop was told to exit
  • EventBase::gotStop — Checks if the event loop was told to exit
  • EventBase::loop — Dispatch pending events
  • EventBase::priorityInit — Sets number of priorities per event base
  • EventBase::reInit — Re-initialize event base(after a fork)
  • EventBase::stop — Tells event_base to stop dispatching events


Constructs EventBase object

  • « EventBase
  • EventBase::dispatch »
  • PHP Manual
  • EventBase
  • Constructs EventBase object

EventBase::__construct

(PECL event >= 1.2.6-beta)

EventBase::__construct — Constructs EventBase object

Description

public EventBase::__construct ([ EventConfig $cfg ] )

Constructs EventBase object

Parameters

cfg

Optional EventConfig object.

Return Values

Returns EventBase object.

See Also

  • EventConfig


Dispatch pending events

  • « EventBase::__construct
  • EventBase::exit »
  • PHP Manual
  • EventBase
  • Dispatch pending events

EventBase::dispatch

(PECL event >= 1.2.6-beta)

EventBase::dispatch — Dispatch pending events

Description

public EventBase::dispatch ( void ) : void

Wait for events to become active, and run their callbacks. The same as EventBase::loop() with no flags set.

Warning

Do NOT destroy the EventBase object as long as resources of the associated Event objects are not released. Otherwise, it will lead to unpredictable results!

Parameters

This function has no parameters.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBase::loop() - Dispatch pending events


Stop dispatching events

  • « EventBase::dispatch
  • EventBase::free »
  • PHP Manual
  • EventBase
  • Stop dispatching events

EventBase::exit

(PECL event >= 1.2.6-beta)

EventBase::exit — Stop dispatching events

Description

public EventBase::exit ([ float $timeout ] ) : bool

Tells event base to stop optionally after given number of seconds.

Parameters

timeout

Optional number of seconds after which the event base should stop dispatching events.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBase::stop() - Tells event_base to stop dispatching events


Free resources allocated for this event base

  • « EventBase::exit
  • EventBase::getFeatures »
  • PHP Manual
  • EventBase
  • Free resources allocated for this event base

EventBase::free

(PECL event >= 1.10.0)

EventBase::free — Free resources allocated for this event base

Description

public EventBase::free ( void ) : void

Deallocates resources allocated by libevent for the EventBase object.

Warning

The EventBase::free() method doesn't destruct the object itself. To destruct the object completely call unset() , or assign NULL.

This method does not deallocate or detach any of the events that are currently associated with the EventBase object, or close any of their sockets - beware.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • EventBase::__construct() - Constructs EventBase object


Returns bitmask of features supported

  • « EventBase::free
  • EventBase::getMethod »
  • PHP Manual
  • EventBase
  • Returns bitmask of features supported

EventBase::getFeatures

(PECL event >= 1.2.6-beta)

EventBase::getFeatures — Returns bitmask of features supported

Description

public EventBase::getFeatures ( void ) : int

Returns bitmask of features supported.

Parameters

This function has no parameters.

Return Values

Returns integer representing a bitmask of supported features. See EventConfig::FEATURE_* constants .

Examples

Example #1 EventBase::getFeatures() example

<?php
// Avoiding "select" method
$cfg = new EventConfig();
if ($cfg->avoidMethod("select")) {
    echo "`select' method avoided\n";
}

$base = new EventBase($cfg);

echo "Features:\n";
$features = $base->getFeatures();
($features & EventConfig::FEATURE_ET) and print("ET - edge-triggered IO\n");
($features & EventConfig::FEATURE_O1) and print("O1 - O(1) operation for adding/deletting events\n");
($features & EventConfig::FEATURE_FDS) and print("FDS - arbitrary file descriptor types, and not just sockets\n");
?>

See Also

  • EventBase::getMethod() - Returns event method in use
  • EventConfig


Returns event method in use

  • « EventBase::getFeatures
  • EventBase::getTimeOfDayCached »
  • PHP Manual
  • EventBase
  • Returns event method in use

EventBase::getMethod

(PECL event >= 1.2.6-beta)

EventBase::getMethod — Returns event method in use

Description

public EventBase::getMethod ( void ) : string

Parameters

This function has no parameters.

Return Values

String representing used event method(backend).

Examples

Example #1 EventBase::getMethod() example

<?php
$cfg = new EventConfig();
if ($cfg->avoidMethod("select")) {
    echo "`select' method avoided\n";
}

// Create event_base associated with the config
$base = new EventBase($cfg);
echo "Event method used: ", $base->getMethod(), PHP_EOL;

?>

The above example will output something similar to:

`select' method avoided
Event method used: epoll

See Also

  • EventBase::getFeatures() - Returns bitmask of features supported


Returns the current event base time

  • « EventBase::getMethod
  • EventBase::gotExit »
  • PHP Manual
  • EventBase
  • Returns the current event base time

EventBase::getTimeOfDayCached

(PECL event >= 1.2.6-beta)

EventBase::getTimeOfDayCached — Returns the current event base time

Description

public EventBase::getTimeOfDayCached ( void ) : float

On success returns the current time(as returned by gettimeofday() ), looking at the cached value in base if possible, and calling gettimeofday() or clock_gettime() as appropriate if there is no cached time.

Parameters

This function has no parameters.

Return Values

Returns the current event base time. On failure returns NULL.


Checks if the event loop was told to exit

  • « EventBase::getTimeOfDayCached
  • EventBase::gotStop »
  • PHP Manual
  • EventBase
  • Checks if the event loop was told to exit

EventBase::gotExit

(PECL event >= 1.2.6-beta)

EventBase::gotExit — Checks if the event loop was told to exit

Description

public EventBase::gotExit ( void ) : bool

Checks if the event loop was told to exit by EventBase::exit() .

Parameters

This function has no parameters.

Return Values

Returns TRUE, event loop was told to exit by EventBase::exit() . Otherwise FALSE.

See Also

  • EventBase::exit() - Stop dispatching events
  • EventBase::stop() - Tells event_base to stop dispatching events
  • EventBase::gotStop() - Checks if the event loop was told to exit


Checks if the event loop was told to exit

  • « EventBase::gotExit
  • EventBase::loop »
  • PHP Manual
  • EventBase
  • Checks if the event loop was told to exit

EventBase::gotStop

(PECL event >= 1.2.6-beta)

EventBase::gotStop — Checks if the event loop was told to exit

Description

public EventBase::gotStop ( void ) : bool

Checks if the event loop was told to exit by EventBase::stop() .

Parameters

This function has no parameters.

Return Values

Returns TRUE, event loop was told to stop by EventBase::stop() . Otherwise FALSE.

See Also

  • EventBase::exit() - Stop dispatching events
  • EventBase::stop() - Tells event_base to stop dispatching events
  • EventBase::gotExit() - Checks if the event loop was told to exit


Dispatch pending events

  • « EventBase::gotStop
  • EventBase::priorityInit »
  • PHP Manual
  • EventBase
  • Dispatch pending events

EventBase::loop

(PECL event >= 1.2.6-beta)

EventBase::loop — Dispatch pending events

Description

public EventBase::loop ([ int $flags ] ) : bool

Wait for events to become active, and run their callbacks.

Warning

Do NOT destroy the EventBase object as long as resources of the associated Event objects are not released. Otherwise, it will lead to unpredictable results!

Parameters

flags

Optional flags. One of EventBase::LOOP_* constants. See EventBase constants .

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBase::dispatch() - Dispatch pending events


Sets number of priorities per event base

  • « EventBase::loop
  • EventBase::reInit »
  • PHP Manual
  • EventBase
  • Sets number of priorities per event base

EventBase::priorityInit

(PECL event >= 1.2.6-beta)

EventBase::priorityInit — Sets number of priorities per event base

Description

public EventBase::priorityInit ( int $n_priorities ) : bool

Sets number of priorities per event base.

Parameters

n_priorities

The number of priorities per event base.

Return Values

Returns TRUE on success, otherwise FALSE.

See Also

  • Event::setPriority() - Set event priority


Re-initialize event base(after a fork)

  • « EventBase::priorityInit
  • EventBase::stop »
  • PHP Manual
  • EventBase
  • Re-initialize event base(after a fork)

EventBase::reInit

(PECL event >= 1.2.6-beta)

EventBase::reInit — Re-initialize event base(after a fork)

Description

public EventBase::reInit ( void ) : bool

Re-initialize event base. Should be called after a fork.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success. Otherwise FALSE.


Tells event_base to stop dispatching events

  • « EventBase::reInit
  • EventBuffer »
  • PHP Manual
  • EventBase
  • Tells event_base to stop dispatching events

EventBase::stop

(PECL event >= 1.2.6-beta)

EventBase::stop — Tells event_base to stop dispatching events

Description

public EventBase::stop ( void ) : bool

Tells event_base to stop dispatching events

Parameters

This function has no parameters.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBase::exit() - Stop dispatching events
  • EventBase::gotStop() - Checks if the event loop was told to exit


The EventBuffer class

(PECL event >= 1.5.0)

Introduction

EventBuffer represents Libevent's "evbuffer", an utility functionality for buffered I/O.

Event buffers are meant to be generally useful for doing the "buffer" part of buffered network I/O.

Class synopsis

EventBuffer {
/* Constants */
const integer EOL_ANY = 0 ;
const integer EOL_CRLF = 1 ;
const integer EOL_CRLF_STRICT = 2 ;
const integer EOL_LF = 3 ;
const integer PTR_SET = 0 ;
const integer PTR_ADD = 1 ;
/* Properties */
public readonly int $length ;
public readonly int $contiguous_space ;
/* Methods */
public add ( string $data ) : bool
public addBuffer ( EventBuffer $buf ) : bool
public appendFrom ( EventBuffer $buf , int $len ) : int
public __construct ( void )
public copyout ( string &$data , int $max_bytes ) : int
public drain ( int $len ) : bool
public enableLocking ( void ) : void
public expand ( int $len ) : bool
public freeze ( bool $at_front ) : bool
public lock ( void ) : void
public prepend ( string $data ) : bool
public prependBuffer ( EventBuffer $buf ) : bool
public pullup ( int $size ) : string
public read ( int $max_bytes ) : string
public read ( mixed $fd , int $howmuch ) : int
public readLine ( int $eol_style ) : string
public search ( string $what [, int $start = -1 [, int $end = -1 ]] ) : mixed
public searchEol ([ int $start = -1 [, int $eol_style = EventBuffer::EOL_ANY ]] ) : mixed
public substr ( int $start [, int $length ] ) : string
public unfreeze ( bool $at_front ) : bool
public unlock ( void ) : bool
public write ( mixed $fd [, int $howmuch ] ) : int
}

Properties

length

The number of bytes stored in an event buffer.

contiguous_space

The number of bytes stored contiguously at the front of the buffer. The bytes in a buffer may be stored in multiple separate chunks of memory; the property returns the number of bytes currently stored in the first chunk.

Predefined Constants

EventBuffer::EOL_ANY

The end of line is any sequence of any number of carriage return and linefeed characters. This format is not very useful; it exists mainly for backward compatibility.

EventBuffer::EOL_CRLF

The end of the line is an optional carriage return, followed by a linefeed. (In other words, it is either a "\r\n" or a "\n" .) This format is useful in parsing text-based Internet protocols, since the standards generally prescribe a "\r\n" line-terminator, but nonconformant clients sometimes say just "\n" .

EventBuffer::EOL_CRLF_STRICT

The end of a line is a single carriage return, followed by a single linefeed. (This is also known as "\r\n" . The ASCII values are 0x0D 0x0A ).

EventBuffer::EOL_LF

The end of a line is a single linefeed character. (This is also known as "\n" . It is ASCII value is 0x0A .)

EventBuffer::PTR_SET

Flag used as argument of EventBuffer::setPosition() method. If this flag specified, the position pointer is moved to an absolute position within the buffer.

EventBuffer::PTR_ADD

The same as EventBuffer::PTR_SET , except this flag causes EventBuffer::setPosition() method to move position forward up to the specified number of bytes(instead of setting absolute position).

Table of Contents

  • EventBuffer::add — Append data to the end of an event buffer
  • EventBuffer::addBuffer — Move all data from a buffer provided to the current instance of EventBuffer
  • EventBuffer::appendFrom — Moves the specified number of bytes from a source buffer to the end of the current buffer
  • EventBuffer::__construct — Constructs EventBuffer object
  • EventBuffer::copyout — Copies out specified number of bytes from the front of the buffer
  • EventBuffer::drain — Removes specified number of bytes from the front of the buffer without copying it anywhere
  • EventBuffer::enableLocking — Description
  • EventBuffer::expand — Reserves space in buffer
  • EventBuffer::freeze — Prevent calls that modify an event buffer from succeeding
  • EventBuffer::lock — Acquires a lock on buffer
  • EventBuffer::prepend — Prepend data to the front of the buffer
  • EventBuffer::prependBuffer — Moves all data from source buffer to the front of current buffer
  • EventBuffer::pullup — Linearizes data within buffer and returns it's contents as a string
  • EventBuffer::read — Read data from an evbuffer and drain the bytes read
  • EventBuffer::readFrom — Read data from a file onto the end of the buffer
  • EventBuffer::readLine — Extracts a line from the front of the buffer
  • EventBuffer::search — Scans the buffer for an occurrence of a string
  • EventBuffer::searchEol — Scans the buffer for an occurrence of an end of line
  • EventBuffer::substr — Substracts a portion of the buffer data
  • EventBuffer::unfreeze — Re-enable calls that modify an event buffer
  • EventBuffer::unlock — Releases lock acquired by EventBuffer::lock
  • EventBuffer::write — Write contents of the buffer to a file or socket


Append data to the end of an event buffer

  • « EventBuffer
  • EventBuffer::addBuffer »
  • PHP Manual
  • EventBuffer
  • Append data to the end of an event buffer

EventBuffer::add

(PECL event >= 1.2.6-beta)

EventBuffer::add — Append data to the end of an event buffer

Description

public EventBuffer::add ( string $data ) : bool

Append data to the end of an event buffer.

Parameters

data

String to be appended to the end of the buffer.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBuffer::addBuffer() - Move all data from a buffer provided to the current instance of EventBuffer


Move all data from a buffer provided to the current instance of EventBuffer

  • « EventBuffer::add
  • EventBuffer::appendFrom »
  • PHP Manual
  • EventBuffer
  • Move all data from a buffer provided to the current instance of EventBuffer

EventBuffer::addBuffer

(PECL event >= 1.2.6-beta)

EventBuffer::addBuffer — Move all data from a buffer provided to the current instance of EventBuffer

Description

public EventBuffer::addBuffer ( EventBuffer $buf ) : bool

Move all data from the buffer provided in buf parameter to the end of current EventBuffer . This is a destructive add. The data from one buffer moves into the other buffer. However, no unnecessary memory copies occur.

Parameters

buf

The source EventBuffer object.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBuffer::add() - Append data to the end of an event buffer


Moves the specified number of bytes from a source buffer to the end of the current buffer

  • « EventBuffer::addBuffer
  • EventBuffer::__construct »
  • PHP Manual
  • EventBuffer
  • Moves the specified number of bytes from a source buffer to the end of the current buffer

EventBuffer::appendFrom

(PECL event >= 1.6.0)

EventBuffer::appendFrom — Moves the specified number of bytes from a source buffer to the end of the current buffer

Description

public EventBuffer::appendFrom ( EventBuffer $buf , int $len ) : int

Moves the specified number of bytes from a source buffer to the end of the current buffer. If there are fewer number of bytes, it moves all the bytes available from the source buffer.

Parameters

buf

Source buffer.

len

Return Values

Returns the number of bytes read.

Changelog

Version | Description
1.6.0 | Renamed EventBuffer::appendFrom()(the old method name) to EventBuffer::appendFrom().

See Also

  • EventBuffer::copyout() - Copies out specified number of bytes from the front of the buffer
  • EventBuffer::drain() - Removes specified number of bytes from the front of the buffer without copying it anywhere
  • EventBuffer::pullup() - Linearizes data within buffer and returns it's contents as a string
  • EventBuffer::readLine() - Extracts a line from the front of the buffer
  • EventBuffer::read() - Read data from an evbuffer and drain the bytes read


Constructs EventBuffer object

  • « EventBuffer::appendFrom
  • EventBuffer::copyout »
  • PHP Manual
  • EventBuffer
  • Constructs EventBuffer object

EventBuffer::__construct

(PECL event >= 1.2.6-beta)

EventBuffer::__construct — Constructs EventBuffer object

Description

public EventBuffer::__construct ( void )

Constructs EventBuffer object

Parameters

This function has no parameters.

Return Values

Returns EventBuffer object.


Copies out specified number of bytes from the front of the buffer

  • « EventBuffer::__construct
  • EventBuffer::drain »
  • PHP Manual
  • EventBuffer
  • Copies out specified number of bytes from the front of the buffer

EventBuffer::copyout

(PECL event >= 1.2.6-beta)

EventBuffer::copyout — Copies out specified number of bytes from the front of the buffer

Description

public EventBuffer::copyout ( string &$data , int $max_bytes ) : int

Behaves just like EventBuffer::read() , but does not drain any data from the buffer. I.e. it copies the first max_bytes bytes from the front of the buffer into data . If there are fewer than max_bytes bytes available, the function copies all the bytes there are.

Parameters

data

Output string.

max_bytes

The number of bytes to copy.

Return Values

Returns the number of bytes copied, or -1 on failure.

See Also

  • EventBuffer::read() - Read data from an evbuffer and drain the bytes read
  • EventBuffer::appendFrom() - Moves the specified number of bytes from a source buffer to the end of the current buffer


Removes specified number of bytes from the front of the buffer without copying it anywhere

  • « EventBuffer::copyout
  • EventBuffer::enableLocking »
  • PHP Manual
  • EventBuffer
  • Removes specified number of bytes from the front of the buffer without copying it anywhere

EventBuffer::drain

(PECL event >= 1.2.6-beta)

EventBuffer::drain — Removes specified number of bytes from the front of the buffer without copying it anywhere

Description

public EventBuffer::drain ( int $len ) : bool

Behaves as EventBuffer::read() , except that it does not copy the data: it just removes it from the front of the buffer.

Parameters

len

The number of bytes to remove from the buffer.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBuffer::read() - Read data from an evbuffer and drain the bytes read
  • EventBuffer::appendFrom() - Moves the specified number of bytes from a source buffer to the end of the current buffer


Description

  • « EventBuffer::drain
  • EventBuffer::expand »
  • PHP Manual
  • EventBuffer
  • Description

EventBuffer::enableLocking

(PECL event >= 1.2.6-beta)

EventBuffer::enableLocking —

Description

public EventBuffer::enableLocking ( void ) : void

Enable locking on an EventBuffer so that it can safely be used by multiple threads at the same time. When locking is enabled, the lock will be held when callbacks are invoked. This could result in deadlock if you aren't careful. Plan accordingly!

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • » Evbuffers and Thread-safety


Reserves space in buffer

  • « EventBuffer::enableLocking
  • EventBuffer::freeze »
  • PHP Manual
  • EventBuffer
  • Reserves space in buffer

EventBuffer::expand

(PECL event >= 1.2.6-beta)

EventBuffer::expand — Reserves space in buffer

Description

public EventBuffer::expand ( int $len ) : bool

Alters the last chunk of memory in the buffer, or adds a new chunk, such that the buffer is now large enough to contain len bytes without any further allocations.

Parameters

len

The number of bytes to reserve for the buffer

Return Values

Returns TRUE on success. Otherwise FALSE.


Prevent calls that modify an event buffer from succeeding

  • « EventBuffer::expand
  • EventBuffer::lock »
  • PHP Manual
  • EventBuffer
  • Prevent calls that modify an event buffer from succeeding

EventBuffer::freeze

(PECL event >= 1.2.6-beta)

EventBuffer::freeze — Prevent calls that modify an event buffer from succeeding

Description

public EventBuffer::freeze ( bool $at_front ) : bool

Prevent calls that modify an event buffer from succeeding

Parameters

at_front

Whether to disable changes to the front or end of the buffer.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBuffer::unfreeze() - Re-enable calls that modify an event buffer


Acquires a lock on buffer

  • « EventBuffer::freeze
  • EventBuffer::prepend »
  • PHP Manual
  • EventBuffer
  • Acquires a lock on buffer

EventBuffer::lock

(PECL event >= 1.2.6-beta)

EventBuffer::lock — Acquires a lock on buffer

Description

public EventBuffer::lock ( void ) : void

Acquires a lock on buffer. Can be used in pair with EventBuffer::unlock() to make a set of operations atomic, i.e. thread-safe. Note, it is not needed to lock buffers for individual operations. When locking is enabled(see EventBuffer::enableLocking() ), individual operations on event buffers are already atomic.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • EventBuffer::unlock() - Releases lock acquired by EventBuffer::lock


Prepend data to the front of the buffer

  • « EventBuffer::lock
  • EventBuffer::prependBuffer »
  • PHP Manual
  • EventBuffer
  • Prepend data to the front of the buffer

EventBuffer::prepend

(PECL event >= 1.2.6-beta)

EventBuffer::prepend — Prepend data to the front of the buffer

Description

public EventBuffer::prepend ( string $data ) : bool

Prepend data to the front of the buffer.

Parameters

data

String to be prepended to the front of the buffer.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBuffer::prependBuffer() - Moves all data from source buffer to the front of current buffer
  • EventBuffer::add() - Append data to the end of an event buffer
  • EventBuffer::addBuffer() - Move all data from a buffer provided to the current instance of EventBuffer


Moves all data from source buffer to the front of current buffer

  • « EventBuffer::prepend
  • EventBuffer::pullup »
  • PHP Manual
  • EventBuffer
  • Moves all data from source buffer to the front of current buffer

EventBuffer::prependBuffer

(PECL event >= 1.2.6-beta)

EventBuffer::prependBuffer — Moves all data from source buffer to the front of current buffer

Description

public EventBuffer::prependBuffer ( EventBuffer $buf ) : bool

Behaves as EventBuffer::addBuffer() , except that it moves data to the front of the buffer.

Parameters

buf

Source buffer.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBuffer::add() - Append data to the end of an event buffer
  • EventBuffer::addBuffer() - Move all data from a buffer provided to the current instance of EventBuffer
  • EventBuffer::prepend() - Prepend data to the front of the buffer


Linearizes data within buffer and returns it's contents as a string

  • « EventBuffer::prependBuffer
  • EventBuffer::read »
  • PHP Manual
  • EventBuffer
  • Linearizes data within buffer and returns it's contents as a string

EventBuffer::pullup

(PECL event >= 1.2.6-beta)

EventBuffer::pullup — Linearizes data within buffer and returns it's contents as a string

Description

public EventBuffer::pullup ( int $size ) : string

"Linearizes" the first size bytes of the buffer, copying or moving them as needed to ensure that they are all contiguous and occupying the same chunk of memory. If size is negative, the function linearizes the entire buffer.

Warning

Calling EventBuffer::pullup() with a large size can be quite slow, since it potentially needs to copy the entire buffer's contents.

Parameters

size

The number of bytes required to be contiguous within the buffer.

Return Values

If size is greater than the number of bytes in the buffer, the function returns NULL. Otherwise, EventBuffer::pullup() returns string.

See Also

  • EventBuffer::copyout() - Copies out specified number of bytes from the front of the buffer
  • EventBuffer::drain() - Removes specified number of bytes from the front of the buffer without copying it anywhere
  • EventBuffer::read() - Read data from an evbuffer and drain the bytes read
  • EventBuffer::readLine() - Extracts a line from the front of the buffer
  • EventBuffer::appendFrom() - Moves the specified number of bytes from a source buffer to the end of the current buffer


Read data from an evbuffer and drain the bytes read

  • « EventBuffer::pullup
  • EventBuffer::readFrom »
  • PHP Manual
  • EventBuffer
  • Read data from an evbuffer and drain the bytes read

EventBuffer::read

(PECL event >= 1.6.0)

EventBuffer::read — Read data from an evbuffer and drain the bytes read

Description

public EventBuffer::read ( int $max_bytes ) : string

Read the first max_bytes from the buffer and drain the bytes read. If more max_bytes are requested than are available in the buffer, it only extracts as many bytes as available.

Parameters

max_bytes

Maxmimum number of bytes to read from the buffer.

Return Values

Returns string read, or FALSE on failure.

Changelog

Version | Description
1.6.0 | Renamed EventBuffer::read()(the old method name) to EventBuffer::read(). EventBuffer::read() now takes only max_bytes argument; returns string instead of integer.

See Also

  • EventBuffer::copyout() - Copies out specified number of bytes from the front of the buffer
  • EventBuffer::drain() - Removes specified number of bytes from the front of the buffer without copying it anywhere
  • EventBuffer::pullup() - Linearizes data within buffer and returns it's contents as a string
  • EventBuffer::readLine() - Extracts a line from the front of the buffer
  • EventBuffer::appendFrom() - Moves the specified number of bytes from a source buffer to the end of the current buffer


Read data from a file onto the end of the buffer

  • « EventBuffer::read
  • EventBuffer::readLine »
  • PHP Manual
  • EventBuffer
  • Read data from a file onto the end of the buffer

EventBuffer::readFrom

(PECL event >= 1.7.0)

EventBuffer::readFrom — Read data from a file onto the end of the buffer

Description

public EventBuffer::read ( mixed $fd , int $howmuch ) : int

Read data from the file specified by fd onto the end of the buffer.

Parameters

fd

Socket resource, stream, or numeric file descriptor.

howmuch

Maxmimum number of bytes to read.

Return Values

Returns the number of bytes read, or FALSE on failure.

See Also

  • EventBuffer::copyout() - Copies out specified number of bytes from the front of the buffer
  • EventBuffer::drain() - Removes specified number of bytes from the front of the buffer without copying it anywhere
  • EventBuffer::pullup() - Linearizes data within buffer and returns it's contents as a string
  • EventBuffer::readLine() - Extracts a line from the front of the buffer
  • EventBuffer::appendFrom() - Moves the specified number of bytes from a source buffer to the end of the current buffer


Extracts a line from the front of the buffer

  • « EventBuffer::readFrom
  • EventBuffer::search »
  • PHP Manual
  • EventBuffer
  • Extracts a line from the front of the buffer

EventBuffer::readLine

(PECL event >= 1.2.6-beta)

EventBuffer::readLine — Extracts a line from the front of the buffer

Description

public EventBuffer::readLine ( int $eol_style ) : string

Extracts a line from the front of the buffer and returns it in a newly allocated string. If there is not a whole line to read, the function returns NULL. The line terminator is not included in the copied string.

Parameters

eol_style

One of EventBuffer:EOL_* constants .

Return Values

On success returns the line read from the buffer, otherwise NULL.

See Also

  • EventBuffer::copyout() - Copies out specified number of bytes from the front of the buffer
  • EventBuffer::drain() - Removes specified number of bytes from the front of the buffer without copying it anywhere
  • EventBuffer::pullup() - Linearizes data within buffer and returns it's contents as a string
  • EventBuffer::read() - Read data from an evbuffer and drain the bytes read
  • EventBuffer::appendFrom() - Moves the specified number of bytes from a source buffer to the end of the current buffer


Scans the buffer for an occurrence of a string

  • « EventBuffer::readLine
  • EventBuffer::searchEol »
  • PHP Manual
  • EventBuffer
  • Scans the buffer for an occurrence of a string

EventBuffer::search

(PECL event >= 1.2.6-beta)

EventBuffer::search — Scans the buffer for an occurrence of a string

Description

public EventBuffer::search ( string $what [, int $start = -1 [, int $end = -1 ]] ) : mixed

Scans the buffer for an occurrence of the string what . It returns numeric position of the string, or FALSE if the string was not found.

If the start argument is provided, it points to the position at which the search should begin; otherwise, the search is performed from the start of the string. If end argument provided, the search is performed between start and end buffer positions.

Parameters

what

String to search.

start

Start search position.

end

End search position.

Return Values

Returns numeric position of the first occurance of the string in the buffer, or FALSE if string is not found.

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 EventBuffer::search() example

<?php
// Count total occurances of 'str' in 'buf'
function count_instances($buf, $str) {
    $total = 0;
    $p     = 0;
    $i     = 0;

    while (1) {
        $p = $buf->search($str, $p);
        if ($p === FALSE) {
            break;
        }
        ++$total;
        ++$p;
    }

    return $total;
}

$buf = new EventBuffer();
$buf->add("Some string within a string inside another string");
var_dump(count_instances($buf, "str"));
?>

The above example will output something similar to:

int(3)

See Also

  • EventBuffer::searchEol() - Scans the buffer for an occurrence of an end of line


Scans the buffer for an occurrence of an end of line

  • « EventBuffer::search
  • EventBuffer::substr »
  • PHP Manual
  • EventBuffer
  • Scans the buffer for an occurrence of an end of line

EventBuffer::searchEol

(PECL event >= 1.5.0)

EventBuffer::searchEol — Scans the buffer for an occurrence of an end of line

Description

public EventBuffer::searchEol ([ int $start = -1 [, int $eol_style = EventBuffer::EOL_ANY ]] ) : mixed

Scans the buffer for an occurrence of an end of line specified by eol_style parameter . It returns numeric position of the string, or FALSE if the string was not found.

If the start argument is provided, it represents the position at which the search should begin; otherwise, the search is performed from the start of the string. If end argument provided, the search is performed between start and end buffer positions.

Parameters

start

Start search position.

eol_style

One of EventBuffer:EOL_* constants .

Return Values

Returns numeric position of the first occurance of end-of-line symbol in the buffer, or FALSE if not found.

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.

See Also

  • EventBuffer::search() - Scans the buffer for an occurrence of a string


Substracts a portion of the buffer data

  • « EventBuffer::searchEol
  • EventBuffer::unfreeze »
  • PHP Manual
  • EventBuffer
  • Substracts a portion of the buffer data

EventBuffer::substr

(PECL event >= 1.6.0)

EventBuffer::substr — Substracts a portion of the buffer data

Description

public EventBuffer::substr ( int $start [, int $length ] ) : string

Substracts up to length bytes of the buffer data beginning at start position.

Parameters

start

The start position of data to be substracted.

length

Maximum number of bytes to substract.

Return Values

Returns the data substracted as a string on success, or FALSE on failure.

See Also

  • EventBuffer::read() - Read data from an evbuffer and drain the bytes read


Re-enable calls that modify an event buffer

  • « EventBuffer::substr
  • EventBuffer::unlock »
  • PHP Manual
  • EventBuffer
  • Re-enable calls that modify an event buffer

EventBuffer::unfreeze

(PECL event >= 1.2.6-beta)

EventBuffer::unfreeze — Re-enable calls that modify an event buffer

Description

public EventBuffer::unfreeze ( bool $at_front ) : bool

Re-enable calls that modify an event buffer.

Parameters

at_front

Whether to enable events at the front or at the end of the buffer.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBuffer::freeze() - Prevent calls that modify an event buffer from succeeding


Releases lock acquired by EventBuffer::lock

  • « EventBuffer::unfreeze
  • EventBuffer::write »
  • PHP Manual
  • EventBuffer
  • Releases lock acquired by EventBuffer::lock

EventBuffer::unlock

(PECL event >= 1.2.6-beta)

EventBuffer::unlock — Releases lock acquired by EventBuffer::lock

Description

public EventBuffer::unlock ( void ) : bool

Releases lock acquired by EventBuffer::lock() .

Parameters

This function has no parameters.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBuffer::lock() - Acquires a lock on buffer


Write contents of the buffer to a file or socket

  • « EventBuffer::unlock
  • EventBufferEvent »
  • PHP Manual
  • EventBuffer
  • Write contents of the buffer to a file or socket

EventBuffer::write

(PECL event >= 1.6.0)

EventBuffer::write — Write contents of the buffer to a file or socket

Description

public EventBuffer::write ( mixed $fd [, int $howmuch ] ) : int

Write contents of the buffer to a file descriptor. The buffer will be drained after the bytes have been successfully written.

Parameters

fd

Socket resource, stream or numeric file descriptor associated normally associated with a socket.

howmuch

The maximum number of bytes to write.

Return Values

Returns the number of bytes written, or FALSE on error.

See Also

  • EventBuffer::read() - Read data from an evbuffer and drain the bytes read


The EventBufferEvent class

(PECL event >= 1.2.6-beta)

Introduction

Represents Libevent's buffer event.

Usually an application wants to perform some amount of data buffering in addition to just responding to events. When we want to write data, for example, the usual pattern looks like:

  1. Decide that we want to write some data to a connection; put that data in a buffer.

  2. Wait for the connection to become writable

  3. Write as much of the data as we can

  4. Remember how much we wrote, and if we still have more data to write, wait for the connection to become writable again.

This buffered I/O pattern is common enough that Libevent provides a generic mechanism for it. A "buffer event" consists of an underlying transport (like a socket), a read buffer, and a write buffer. Instead of regular events, which give callbacks when the underlying transport is ready to be read or written, a buffer event invokes its user-supplied callbacks when it has read or written enough data.

Class synopsis

final EventBufferEvent {
/* Constants */
const integer READING = 1 ;
const integer WRITING = 2 ;
const integer EOF = 16 ;
const integer ERROR = 32 ;
const integer TIMEOUT = 64 ;
const integer CONNECTED = 128 ;
const integer OPT_CLOSE_ON_FREE = 1 ;
const integer OPT_THREADSAFE = 2 ;
const integer OPT_DEFER_CALLBACKS = 4 ;
const integer OPT_UNLOCK_CALLBACKS = 8 ;
const integer SSL_OPEN = 0 ;
const integer SSL_CONNECTING = 1 ;
const integer SSL_ACCEPTING = 2 ;
/* Properties */
public integer $fd ;
public integer $priority ;
public readonly EventBuffer $input ;
public readonly EventBuffer $output ;
/* Methods */
public close ( void ) : void
public connect ( string $addr ) : bool
public connectHost ( EventDnsBase $dns_base , string $hostname , int $port [, int $family = EventUtil::AF_UNSPEC ] ) : bool
public __construct ( EventBase $base [, mixed $socket = NULL [, int $options = 0 [, callable $readcb = NULL [, callable $writecb = NULL [, callable $eventcb = NULL ]]]]] )
public static createPair ( EventBase $base [, int $options = 0 ] ) : array
public disable ( int $events ) : bool
public enable ( int $events ) : bool
public free ( void ) : void
public getDnsErrorString ( void ) : string
public getEnabled ( void ) : int
public getInput ( void ) : EventBuffer
public getOutput ( void ) : EventBuffer
public read ( int $size ) : string
public readBuffer ( EventBuffer $buf ) : bool
public setCallbacks ( callable $readcb , callable $writecb , callable $eventcb [, string $arg ] ) : void
public setPriority ( int $priority ) : bool
public setTimeouts ( float $timeout_read , float $timeout_write ) : bool
public setWatermark ( int $events , int $lowmark , int $highmark ) : void
public sslError ( void ) : string
public static sslFilter ( EventBase $base , EventBufferEvent $underlying , EventSslContext $ctx , int $state [, int $options = 0 ] ) : EventBufferEvent
public sslGetCipherInfo ( void ) : string
public sslGetCipherName ( void ) : string
public sslGetCipherVersion ( void ) : string
public sslGetProtocol ( void ) : string
public sslRenegotiate ( void ) : void
public static sslSocket ( EventBase $base , mixed $socket , EventSslContext $ctx , int $state [, int $options ] ) : EventBufferEvent
public write ( string $data ) : bool
public writeBuffer ( EventBuffer $buf ) : bool
}

Properties

fd

Numeric file descriptor associated with the buffer event. Normally represents a bound socket. Equals to NULL, if there is no file descriptor(socket) associated with the buffer event.

priority

The priority of the events used to implement the buffer event.

input

Underlying input buffer object( EventBuffer )

output

Underlying output buffer object( EventBuffer )

Predefined Constants

EventBufferEvent::READING

An event occurred during a read operation on the bufferevent. See the other flags for which event it was.

EventBufferEvent::WRITING

An event occurred during a write operation on the bufferevent. See the other flags for which event it was.

EventBufferEvent::EOF

Got an end-of-file indication on the buffer event.

EventBufferEvent::ERROR

An error occurred during a bufferevent operation. For more information on what the error was, call EventUtil::getLastSocketErrno() and/or EventUtil::getLastSocketError() .

EventBufferEvent::TIMEOUT

EventBufferEvent::CONNECTED

Finished a requested connection on the bufferevent.

EventBufferEvent::OPT_CLOSE_ON_FREE

When the buffer event is freed, close the underlying transport. This will close an underlying socket, free an underlying buffer event, etc.

EventBufferEvent::OPT_THREADSAFE

Automatically allocate locks for the bufferevent, so that it’s safe to use from multiple threads.

EventBufferEvent::OPT_DEFER_CALLBACKS

When this flag is set, the bufferevent defers all of its callbacks. See » Fast portable non-blocking network programming with Libevent, Deferred callbacks .

EventBufferEvent::OPT_UNLOCK_CALLBACKS

By default, when the bufferevent is set up to be threadsafe, the buffer event’s locks are held whenever the any user-provided callback is invoked. Setting this option makes Libevent release the buffer event’s lock when it’s invoking the callbacks.

EventBufferEvent::SSL_OPEN

The SSL handshake is done

EventBufferEvent::SSL_CONNECTING

SSL is currently performing negotiation as a client

EventBufferEvent::SSL_ACCEPTING

SSL is currently performing negotiation as a server

Table of Contents

  • EventBufferEvent::close — Closes file descriptor associated with the current buffer event
  • EventBufferEvent::connect — Connect buffer event's file descriptor to given address or UNIX socket
  • EventBufferEvent::connectHost — Connects to a hostname with optionally asyncronous DNS resolving
  • EventBufferEvent::__construct — Constructs EventBufferEvent object
  • EventBufferEvent::createPair — Creates two buffer events connected to each other
  • EventBufferEvent::disable — Disable events read, write, or both on a buffer event
  • EventBufferEvent::enable — Enable events read, write, or both on a buffer event
  • EventBufferEvent::free — Free a buffer event
  • EventBufferEvent::getDnsErrorString — Returns string describing the last failed DNS lookup attempt
  • EventBufferEvent::getEnabled — Returns bitmask of events currently enabled on the buffer event
  • EventBufferEvent::getInput — Returns underlying input buffer associated with current buffer event
  • EventBufferEvent::getOutput — Returns underlying output buffer associated with current buffer event
  • EventBufferEvent::read — Read buffer's data
  • EventBufferEvent::readBuffer — Drains the entire contents of the input buffer and places them into buf
  • EventBufferEvent::setCallbacks — Assigns read, write and event(status) callbacks
  • EventBufferEvent::setPriority — Assign a priority to a bufferevent
  • EventBufferEvent::setTimeouts — Set the read and write timeout for a buffer event
  • EventBufferEvent::setWatermark — Adjusts read and/or write watermarks
  • EventBufferEvent::sslError — Returns most recent OpenSSL error reported on the buffer event
  • EventBufferEvent::sslFilter — Create a new SSL buffer event to send its data over another buffer event
  • EventBufferEvent::sslGetCipherInfo — Returns a textual description of the cipher
  • EventBufferEvent::sslGetCipherName — Returns the current cipher name of the SSL connection
  • EventBufferEvent::sslGetCipherVersion — Returns version of cipher used by current SSL connection
  • EventBufferEvent::sslGetProtocol — Returns the name of the protocol used for current SSL connection
  • EventBufferEvent::sslRenegotiate — Tells a bufferevent to begin SSL renegotiation
  • EventBufferEvent::sslSocket — Creates a new SSL buffer event to send its data over an SSL on a socket
  • EventBufferEvent::write — Adds data to a buffer event's output buffer
  • EventBufferEvent::writeBuffer — Adds contents of the entire buffer to a buffer event's output buffer


Closes file descriptor associated with the current buffer event

  • « EventBufferEvent
  • EventBufferEvent::connect »
  • PHP Manual
  • EventBufferEvent
  • Closes file descriptor associated with the current buffer event

EventBufferEvent::close

(PECL event >= 1.10.0)

EventBufferEvent::close — Closes file descriptor associated with the current buffer event

Description

public EventBufferEvent::close ( void ) : void

Closes file descriptor associated with the current buffer event.

This method may be used in cases when the EventBufferEvent::OPT_CLOSE_ON_FREE option is not appropriate.

Parameters

This function has no parameters.

Return Values

No value is returned.


Connect buffer event's file descriptor to given address or UNIX socket

  • « EventBufferEvent::close
  • EventBufferEvent::connectHost »
  • PHP Manual
  • EventBufferEvent
  • Connect buffer event's file descriptor to given address or UNIX socket

EventBufferEvent::connect

(PECL event >= 1.2.6-beta)

EventBufferEvent::connect — Connect buffer event's file descriptor to given address or UNIX socket

Description

public EventBufferEvent::connect ( string $addr ) : bool

Connect buffer event's file descriptor to given address(optionally with port), or a UNIX domain socket.

If socket is not assigned to the buffer event, this function allocates a new socket and makes it non-blocking internally.

To resolve DNS names(asyncronously), use EventBufferEvent::connectHost() method.

Parameters

addr

Should contain an IP address with optional port number, or a path to UNIX domain socket. Recognized formats are:

[IPv6Address]:port
[IPv6Address]
IPv6Address
IPv4Address:port
IPv4Address
unix:path
Note, 'unix:' prefix is currently not case sensitive.

Return Values

Returns TRUE on success. Otherwise FALSE.

Examples

Example #1 EventBufferEvent::connect() example

<?php
/*
 * 1. Connect to 127.0.0.1 at port 80
 * by means of EventBufferEvent::connect().
 *
 * 2. Request /index.cphp via HTTP/1.0
 * using the output buffer.
 *
 * 3. Asyncronously read the response and print it to stdout.
 */

/* Read callback */
function readcb($bev, $base) {
    $input = $bev->getInput();

    while (($n = $input->remove($buf, 1024)) > 0) {
        echo $buf;
    }
}

/* Event callback */
function eventcb($bev, $events, $base) {
    if ($events & EventBufferEvent::CONNECTED) {
        echo "Connected.\n";
    } elseif ($events & (EventBufferEvent::ERROR | EventBufferEvent::EOF)) {
        if ($events & EventBufferEvent::ERROR) {
            echo "DNS error: ", $bev->getDnsErrorString(), PHP_EOL;
        }

        echo "Closing\n";
        $base->exit();
        exit("Done\n");
    }
}

$base = new EventBase();

echo "step 1\n";
$bev = new EventBufferEvent($base, /* use internal socket */ NULL,
    EventBufferEvent::OPT_CLOSE_ON_FREE | EventBufferEvent::OPT_DEFER_CALLBACKS);
if (!$bev) {
    exit("Failed creating bufferevent socket\n");
}

echo "step 2\n";
$bev->setCallbacks("readcb", /* writecb */ NULL, "eventcb", $base);
$bev->enable(Event::READ | Event::WRITE);

echo "step 3\n";
/* Send request */
$output = $bev->getOutput();
if (!$output->add(
    "GET /index.cphp HTTP/1.0\r\n".
    "Connection: Close\r\n\r\n"
)) {
    exit("Failed adding request to output buffer\n");
}

/* Connect to the host syncronously.
 * We know the IP, and don't need to resolve DNS. */
if (!$bev->connect("127.0.0.1:80")) {
    exit("Can't connect to host\n");
}

/* Dispatch pending events */
$base->dispatch();

The above example will output something similar to:

step 1
step 2
step 3
Connected.
HTTP/1.1 200 OK
Server: nginx/1.2.6
Date: Sat, 09 Mar 2013 10:06:58 GMT
Content-Type: text/html; charset=utf-8
Connection: close
X-Powered-By: PHP/5.4.11--pl2-gentoo

sdfsdfsf
Closing
Done

Example #2 Connect to UNIX domain socket which presumably is served by a server, read response from the server and output it to the console

<?php
class MyUnixSocketClient {
    private $base, $bev;

    function __construct($base, $sock_path) {
        $this->base = $base;
        $this->bev = new EventBufferEvent($base, NULL, EventBufferEvent::OPT_CLOSE_ON_FREE,
            array ($this, "read_cb"), NULL, array ($this, "event_cb"));

        if (!$this->bev->connect("unix:$sock_path")) {
            trigger_error("Failed to connect to socket `$sock_path'", E_USER_ERROR);
        }

        $this->bev->enable(Event::READ);
    }

    function __destruct() {
        if ($this->bev) {
            $this->bev->free();
            $this->bev = NULL;
        }
    }

    function dispatch() {
        $this->base->dispatch();
    }

    function read_cb($bev, $unused) {
        $in = $bev->input;

        printf("Received %ld bytes\n", $in->length);
        printf("----- data ----\n");
        printf("%ld:\t%s\n", (int) $in->length, $in->pullup(-1));

        $this->bev->free();
        $this->bev = NULL;
        $this->base->exit(NULL);
    }

    function event_cb($bev, $events, $unused) {
        if ($events & EventBufferEvent::ERROR) {
            echo "Error from bufferevent\n";
        }

        if ($events & (EventBufferEvent::EOF | EventBufferEvent::ERROR)) {
            $bev->free();
            $bev = NULL;
        } elseif ($events & EventBufferEvent::CONNECTED) {
            $bev->output->add("test\n");
        }
    }
}

if ($argc <= 1) {
    exit("Socket path is not provided\n");
}
$sock_path = $argv[1];

$base = new EventBase();
$cl = new MyUnixSocketClient($base, $sock_path);
$cl->dispatch();
?>

The above example will output something similar to:

Received 5 bytes
----- data ----
5:  test

See Also

  • EventBufferEvent::connectHost() - Connects to a hostname with optionally asyncronous DNS resolving


Connects to a hostname with optionally asyncronous DNS resolving

  • « EventBufferEvent::connect
  • EventBufferEvent::__construct »
  • PHP Manual
  • EventBufferEvent
  • Connects to a hostname with optionally asyncronous DNS resolving

EventBufferEvent::connectHost

(PECL event >= 1.2.6-beta)

EventBufferEvent::connectHost — Connects to a hostname with optionally asyncronous DNS resolving

Description

public EventBufferEvent::connectHost ( EventDnsBase $dns_base , string $hostname , int $port [, int $family = EventUtil::AF_UNSPEC ] ) : bool

Resolves the DNS name hostname, looking for addresses of type family ( EventUtil::AF_* constants). If the name resolution fails, it invokes the event callback with an error event. If it succeeds, it launches a connection attempt just as EventBufferEvent::connect() would.

dns_base is optional. May be NULL, or an object created with EventDnsBase::__construct() . For asyncronous hostname resolving pass a valid event dns base resource. Otherwise the hostname resolving will block.

Note:

EventDnsBase is available only if Event configured --with-event-extra ( event_extra library, libevent protocol-specific functionality support including HTTP, DNS, and RPC ).

Note:

EventBufferEvent::connectHost() requires libevent-2.0.3-alpha or greater.

Parameters

dns_base

Object of EventDnsBase in case if DNS is to be resolved asyncronously. Otherwise NULL.

hostname

Hostname to connect to. Recognized formats are:

www.example.com (hostname)
 1.2.3.4 (ipv4address)
 ::1 (ipv6address)
[::1] ([ipv6address])

port

Port number

family

Address family. EventUtil::AF_UNSPEC , EventUtil::AF_INET , or EventUtil::AF_INET6 . See EventUtil constants .

Return Values

Returns TRUE on success. Otherwise FALSE.

Examples

Example #1 EventBufferEvent::connectHost() example

<?php
/* Read callback */
function readcb($bev, $base) {
    //$input = $bev->input; //$bev->getInput();

    //$pos = $input->search("TTP");
    $pos = $bev->input->search("TTP");

    while (($n = $bev->input->remove($buf, 1024)) > 0) {
        echo $buf;
    }
}

/* Event callback */
function eventcb($bev, $events, $base) {
    if ($events & EventBufferEvent::CONNECTED) {
        echo "Connected.\n";
    } elseif ($events & (EventBufferEvent::ERROR | EventBufferEvent::EOF)) {
        if ($events & EventBufferEvent::ERROR) {
            echo "DNS error: ", $bev->getDnsErrorString(), PHP_EOL;
        }

        echo "Closing\n";
        $base->exit();
        exit("Done\n");
    }
}

$base = new EventBase();

$dns_base = new EventDnsBase($base, TRUE); // We'll use async DNS resolving
if (!$dns_base) {
    exit("Failed to init DNS Base\n");
}

$bev = new EventBufferEvent($base, /* use internal socket */ NULL,
    EventBufferEvent::OPT_CLOSE_ON_FREE | EventBufferEvent::OPT_DEFER_CALLBACKS,
    "readcb", /* writecb */ NULL, "eventcb", $base
);
if (!$bev) {
    exit("Failed creating bufferevent socket\n");
}

//$bev->setCallbacks("readcb", /* writecb */ NULL, "eventcb", $base);
$bev->enable(Event::READ | Event::WRITE);

$output = $bev->output; //$bev->getOutput();
if (!$output->add(
    "GET {$argv[2]} HTTP/1.0\r\n".
    "Host: {$argv[1]}\r\n".
    "Connection: Close\r\n\r\n"
)) {
    exit("Failed adding request to output buffer\n");
}

if (!$bev->connectHost($dns_base, $argv[1], 80, EventUtil::AF_UNSPEC)) {
    exit("Can't connect to host {$argv[1]}\n");
}

$base->dispatch();
?>

The above example will output something similar to:

Connected.
HTTP/1.0 301 Moved Permanently
Location: http://www.google.co.uk/
Content-Type: text/html; charset=UTF-8
Date: Sat, 09 Mar 2013 12:21:19 GMT
Expires: Mon, 08 Apr 2013 12:21:19 GMT
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 221
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN

<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.co.uk/">here</A>.
</BODY></HTML>
Closing
Done

See Also

  • EventBufferEvent::connect() - Connect buffer event's file descriptor to given address or UNIX socket


Constructs EventBufferEvent object

  • « EventBufferEvent::connectHost
  • EventBufferEvent::createPair »
  • PHP Manual
  • EventBufferEvent
  • Constructs EventBufferEvent object

EventBufferEvent::__construct

(PECL event >= 1.2.6-beta)

EventBufferEvent::__construct — Constructs EventBufferEvent object

Description

public EventBufferEvent::__construct ( EventBase $base [, mixed $socket = NULL [, int $options = 0 [, callable $readcb = NULL [, callable $writecb = NULL [, callable $eventcb = NULL ]]]]] )

Create a buffer event on a socket, stream or a file descriptor. Passing NULL to socket means that the socket should be created later, e.g. by means of EventBufferEvent::connect() .

Parameters

base

Event base that should be associated with the new buffer event.

socket

May be created as a stream(not necessarily by means of sockets extension)

options

One of EventBufferEvent::OPT_* constants , or 0 .

readcb

Read event callback. See About buffer event callbacks .

writecb

Write event callback. See About buffer event callbacks .

eventcb

Status-change event callback. See About buffer event callbacks .

arg

A variable that will be passed to all the callbacks.

Return Values

Returns buffer event resource optionally associated with socket resource. */

See Also

  • EventBufferEvent::sslFilter() - Create a new SSL buffer event to send its data over another buffer event
  • EventBufferEvent::sslSocket() - Creates a new SSL buffer event to send its data over an SSL on a socket


Creates two buffer events connected to each other

  • « EventBufferEvent::__construct
  • EventBufferEvent::disable »
  • PHP Manual
  • EventBufferEvent
  • Creates two buffer events connected to each other

EventBufferEvent::createPair

(PECL event >= 1.2.6-beta)

EventBufferEvent::createPair — Creates two buffer events connected to each other

Description

public static EventBufferEvent::createPair ( EventBase $base [, int $options = 0 ] ) : array

Returns array of two EventBufferEvent objects connected to each other. All the usual options are supported, except for EventBufferEvent::OPT_CLOSE_ON_FREE , which has no effect, and EventBufferEvent::OPT_DEFER_CALLBACKS , which is always on.

Parameters

base

Associated event base

options

EventBufferEvent::OPT_* constants combined with bitwise OR operator.

Return Values

Returns array of two EventBufferEvent objects connected to each other.

Changelog

Version | Description
1.9.0 | Method made static.


Disable events read, write, or both on a buffer event

  • « EventBufferEvent::createPair
  • EventBufferEvent::enable »
  • PHP Manual
  • EventBufferEvent
  • Disable events read, write, or both on a buffer event

EventBufferEvent::disable

(PECL event >= 1.2.6-beta)

EventBufferEvent::disable — Disable events read, write, or both on a buffer event

Description

public EventBufferEvent::disable ( int $events ) : bool

Disable events Event::READ , Event::WRITE , or Event::READ | Event::WRITE on a buffer event.

Parameters

events

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBufferEvent::enable() - Enable events read, write, or both on a buffer event


Enable events read, write, or both on a buffer event

  • « EventBufferEvent::disable
  • EventBufferEvent::free »
  • PHP Manual
  • EventBufferEvent
  • Enable events read, write, or both on a buffer event

EventBufferEvent::enable

(PECL event >= 1.2.6-beta)

EventBufferEvent::enable — Enable events read, write, or both on a buffer event

Description

public EventBufferEvent::enable ( int $events ) : bool

Enable events Event::READ , Event::WRITE , or Event::READ | Event::WRITE on a buffer event.

Parameters

events

Event::READ , Event::WRITE , or Event::READ | Event::WRITE on a buffer event.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBufferEvent::disable() - Disable events read, write, or both on a buffer event


Free a buffer event

  • « EventBufferEvent::enable
  • EventBufferEvent::getDnsErrorString »
  • PHP Manual
  • EventBufferEvent
  • Free a buffer event

EventBufferEvent::free

(PECL event >= 1.2.6-beta)

EventBufferEvent::free — Free a buffer event

Description

public EventBufferEvent::free ( void ) : void

Free resources allocated by buffer event.

Usually there is no need to call this method, since normally it is done within internal object destructors. However, sometimes we have a long-time script allocating lots of instances, or a script with a heavy memory usage, where we need to free resources as soon as possible. In such cases EventBufferEvent::free() may be used to protect the script against running up to the memory_limit .

Parameters

This function has no parameters.

Return Values

No value is returned.


Returns string describing the last failed DNS lookup attempt

  • « EventBufferEvent::free
  • EventBufferEvent::getEnabled »
  • PHP Manual
  • EventBufferEvent
  • Returns string describing the last failed DNS lookup attempt

EventBufferEvent::getDnsErrorString

(PECL event >= 1.2.6-beta)

EventBufferEvent::getDnsErrorString — Returns string describing the last failed DNS lookup attempt

Description

public EventBufferEvent::getDnsErrorString ( void ) : string

Returns string describing the last failed DNS lookup attempt made by EventBufferEvent::connectHost() , or an empty string, if there is no DNS error detected.

Parameters

This function has no parameters.

Return Values

Returns a string describing DNS lookup error, or an empty string for no error.

See Also

  • EventBufferEvent::connectHost() - Connects to a hostname with optionally asyncronous DNS resolving


Returns bitmask of events currently enabled on the buffer event

  • « EventBufferEvent::getDnsErrorString
  • EventBufferEvent::getInput »
  • PHP Manual
  • EventBufferEvent
  • Returns bitmask of events currently enabled on the buffer event

EventBufferEvent::getEnabled

(PECL event >= 1.2.6-beta)

EventBufferEvent::getEnabled — Returns bitmask of events currently enabled on the buffer event

Description

public EventBufferEvent::getEnabled ( void ) : int

Returns bitmask of events currently enabled on the buffer event

Parameters

This function has no parameters.

Return Values

Returns integer representing a bitmask of events currently enabled on the buffer event

See Also

  • EventBufferEvent::enable() - Enable events read, write, or both on a buffer event
  • EventBufferEvent::disable() - Disable events read, write, or both on a buffer event


Returns underlying input buffer associated with current buffer event

  • « EventBufferEvent::getEnabled
  • EventBufferEvent::getOutput »
  • PHP Manual
  • EventBufferEvent
  • Returns underlying input buffer associated with current buffer event

EventBufferEvent::getInput

(PECL event >= 1.2.6-beta)

EventBufferEvent::getInput — Returns underlying input buffer associated with current buffer event

Description

public EventBufferEvent::getInput ( void ) : EventBuffer

Returns underlying input buffer associated with current buffer event. An input buffer is a storage for data to read.

Note, there is also input property of EventBufferEvent class.

Parameters

This function has no parameters.

Return Values

Returns instance of EventBuffer input buffer associated with current buffer event.

Examples

Example #1 Buffer event's read callback

<?php
function readcb($bev, $base) {
    $input = $bev->input; //$bev->getInput();

    while (($n = $input->remove($buf, 1024)) > 0) {
        echo $buf;
    }
}
?>

See Also

  • EventBufferEvent::getOutput() - Returns underlying output buffer associated with current buffer event


Returns underlying output buffer associated with current buffer event

  • « EventBufferEvent::getInput
  • EventBufferEvent::read »
  • PHP Manual
  • EventBufferEvent
  • Returns underlying output buffer associated with current buffer event

EventBufferEvent::getOutput

(PECL event >= 1.2.6-beta)

EventBufferEvent::getOutput — Returns underlying output buffer associated with current buffer event

Description

public EventBufferEvent::getOutput ( void ) : EventBuffer

Returns underlying output buffer associated with current buffer event. An output buffer is a storage for data to be written.

Note, there is also output property of EventBufferEvent class.

Parameters

This function has no parameters.

Return Values

Returns instance of EventBuffer output buffer associated with current buffer event.

Examples

Example #1 EventBufferEvent::getOutput() example

<?php
$base = new EventBase();

$dns_base = new EventDnsBase($base, TRUE); // Use async DNS resolving
if (!$dns_base) {
    exit("Failed to init DNS Base\n");
}

$bev = new EventBufferEvent($base, /* use internal socket */ NULL,
    EventBufferEvent::OPT_CLOSE_ON_FREE | EventBufferEvent::OPT_DEFER_CALLBACKS,
    "readcb", /* writecb */ NULL, "eventcb", $base
);
if (!$bev) {
    exit("Failed creating bufferevent socket\n");
}

$bev->enable(Event::READ | Event::WRITE);

$output = $bev->getOutput();
if (!$output->add(
    "GET {$argv[2]} HTTP/1.0\r\n".
    "Host: {$argv[1]}\r\n".
    "Connection: Close\r\n\r\n"
)) {
    exit("Failed adding request to output buffer\n");
}

/* ... */
?>

See Also

  • EventBufferEvent::getInput() - Returns underlying input buffer associated with current buffer event


Read buffer's data

  • « EventBufferEvent::getOutput
  • EventBufferEvent::readBuffer »
  • PHP Manual
  • EventBufferEvent
  • Read buffer's data

EventBufferEvent::read

(PECL event >= 1.2.6-beta)

EventBufferEvent::read — Read buffer's data

Description

public EventBufferEvent::read ( int $size ) : string

Removes up to size bytes from the input buffer. Returns a string of data read from the input buffer.

Parameters

size

Maximum number of bytes to read

Return Values

Returns string of data read from the input buffer.

See Also

  • EventBufferEvent::readBuffer() - Drains the entire contents of the input buffer and places them into buf


Drains the entire contents of the input buffer and places them into buf

  • « EventBufferEvent::read
  • EventBufferEvent::setCallbacks »
  • PHP Manual
  • EventBufferEvent
  • Drains the entire contents of the input buffer and places them into buf

EventBufferEvent::readBuffer

(PECL event >= 1.2.6-beta)

EventBufferEvent::readBuffer — Drains the entire contents of the input buffer and places them into buf

Description

public EventBufferEvent::readBuffer ( EventBuffer $buf ) : bool

Drains the entire contents of the input buffer and places them into buf .

Parameters

buf

Target buffer

Return Values

Returns TRUE on success; Otherwise FALSE.

See Also

  • EventBufferEvent::read() - Read buffer's data


Assigns read, write and event(status) callbacks

  • « EventBufferEvent::readBuffer
  • EventBufferEvent::setPriority »
  • PHP Manual
  • EventBufferEvent
  • Assigns read, write and event(status) callbacks

EventBufferEvent::setCallbacks

(PECL event >= 1.2.6-beta)

EventBufferEvent::setCallbacks — Assigns read, write and event(status) callbacks

Description

public EventBufferEvent::setCallbacks ( callable $readcb , callable $writecb , callable $eventcb [, string $arg ] ) : void

Assigns read, write and event(status) callbacks.

Parameters

readcb

Read event callback. See About buffer event callbacks .

writecb

Write event callback. See About buffer event callbacks .

eventcb

Status-change event callback. See About buffer event callbacks .

arg

A variable that will be passed to all the callbacks.

Return Values

No value is returned.

See Also

  • EventBufferEvent::__construct() - Constructs EventBufferEvent object


Assign a priority to a bufferevent

  • « EventBufferEvent::setCallbacks
  • EventBufferEvent::setTimeouts »
  • PHP Manual
  • EventBufferEvent
  • Assign a priority to a bufferevent

EventBufferEvent::setPriority

(PECL event >= 1.2.6-beta)

EventBufferEvent::setPriority — Assign a priority to a bufferevent

Description

public EventBufferEvent::setPriority ( int $priority ) : bool

Assign a priority to a bufferevent

Warning

Only supported for socket buffer events

Parameters

priority

Priority value.

Return Values

Returns TRUE on success. Otherwise FALSE.


Set the read and write timeout for a buffer event

  • « EventBufferEvent::setPriority
  • EventBufferEvent::setWatermark »
  • PHP Manual
  • EventBufferEvent
  • Set the read and write timeout for a buffer event

EventBufferEvent::setTimeouts

(PECL event >= 1.2.6-beta)

EventBufferEvent::setTimeouts — Set the read and write timeout for a buffer event

Description

public EventBufferEvent::setTimeouts ( float $timeout_read , float $timeout_write ) : bool

Set the read and write timeout for a buffer event

Parameters

timeout_read

Read timeout

timeout_write

Write timeout

Return Values

Returns TRUE on success. Otherwise FALSE.


Adjusts read and/or write watermarks

  • « EventBufferEvent::setTimeouts
  • EventBufferEvent::sslError »
  • PHP Manual
  • EventBufferEvent
  • Adjusts read and/or write watermarks

EventBufferEvent::setWatermark

(PECL event >= 1.2.6-beta)

EventBufferEvent::setWatermark — Adjusts read and/or write watermarks

Description

public EventBufferEvent::setWatermark ( int $events , int $lowmark , int $highmark ) : void

Adjusts the read watermarks, the write watermarks , or both, of a single buffer event.

A buffer event watermark is an edge, a value specifying number of bytes to be read or written before callback is invoked. By default every read/write event triggers a callback invokation. See » Fast portable non-blocking network programming with Libevent: Callbacks and watermarks

Parameters

events

Bitmask of Event::READ , Event::WRITE , or both.

lowmark

Minimum watermark value.

highmark

Maximum watermark value. 0 means "unlimited".

Return Values

No value is returned.


Returns most recent OpenSSL error reported on the buffer event

  • « EventBufferEvent::setWatermark
  • EventBufferEvent::sslFilter »
  • PHP Manual
  • EventBufferEvent
  • Returns most recent OpenSSL error reported on the buffer event

EventBufferEvent::sslError

(PECL event >= 1.2.6-beta)

EventBufferEvent::sslError — Returns most recent OpenSSL error reported on the buffer event

Description

public EventBufferEvent::sslError ( void ) : string

Returns most recent OpenSSL error reported on the buffer event.

Note:

This function is available only if Event is compiled with OpenSSL support.

Parameters

This function has no parameters.

Return Values

Returns OpenSSL error string reported on the buffer event, or FALSE, if there is no more error to return.

Examples

Example #1 EventBufferEvent::sslError() example

<?php
// This callback is invoked when some even occurs on the event listener,
// e.g. connection closed, or an error occured
function ssl_event_cb($bev, $events, $ctx) {
    if ($events & EventBufferEvent::ERROR) {
        // Fetch errors from the SSL error stack
        while ($err = $bev->sslError()) {
            fprintf(STDERR, "Bufferevent error %s.\n", $err);
        }
    }

    if ($events & (EventBufferEvent::EOF | EventBufferEvent::ERROR)) {
        $bev->free();
    }
}
?>

See Also

  • EventBufferEvent::sslRenegotiate() - Tells a bufferevent to begin SSL renegotiation


Create a new SSL buffer event to send its data over another buffer event

  • « EventBufferEvent::sslError
  • EventBufferEvent::sslGetCipherInfo »
  • PHP Manual
  • EventBufferEvent
  • Create a new SSL buffer event to send its data over another buffer event

EventBufferEvent::sslFilter

(PECL event >= 1.2.6-beta)

EventBufferEvent::sslFilter — Create a new SSL buffer event to send its data over another buffer event

Description

public static EventBufferEvent::sslFilter ( EventBase $base , EventBufferEvent $underlying , EventSslContext $ctx , int $state [, int $options = 0 ] ) : EventBufferEvent

Create a new SSL buffer event to send its data over another buffer event

Note:

This function is available only if Event is compiled with OpenSSL support.

Parameters

base

Associated event base.

underlying

A socket buffer event to use for this SSL.

ctx

Object of EventSslContext class.

state

The current state of SSL connection: EventBufferEvent::SSL_OPEN , EventBufferEvent::SSL_ACCEPTING or EventBufferEvent::SSL_CONNECTING .

options

One or more buffer event options.

Return Values

Returns a new SSL EventBufferEvent object.

Examples

Example #1 Simple SMTP server

<?php
 /*
 * Author: Andrew Rose <hello at andrewrose dot co dot uk>
 *
 * Usage:
 * 1) Prepare cert.pem certificate and privkey.pem private key files.
 * 2) Launch the server script
 * 3) Open TLS connection, e.g.:
 *      $ openssl s_client -connect localhost:25 -starttls smtp -crlf
 * 4) Start testing the commands listed in `cmd` method below.
 */

class Handler {
    public $domainName = FALSE;
    public $connections = [];
    public $buffers = [];
    public $maxRead = 256000;

    public function __construct() {
        $this->ctx = new EventSslContext(EventSslContext::SSLv3_SERVER_METHOD, [
            EventSslContext::OPT_LOCAL_CERT  => 'cert.pem',
            EventSslContext::OPT_LOCAL_PK    => 'privkey.pem',
            //EventSslContext::OPT_PASSPHRASE  => '',
            EventSslContext::OPT_VERIFY_PEER => false, // change to true with authentic cert
            EventSslContext::OPT_ALLOW_SELF_SIGNED => true // change to false with authentic cert
        ]);

        $this->base = new EventBase();
        if (!$this->base) {
            exit("Couldn't open event base\n");
        }

        if (!$this->listener = new EventListener($this->base,
            [$this, 'ev_accept'],
            $this->ctx,
            EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE,
            -1,
            '0.0.0.0:25'))
        {
            exit("Couldn't create listener\n");
        }

        $this->listener->setErrorCallback([$this, 'ev_error']);
        $this->base->dispatch();
    }

    public function ev_accept($listener, $fd, $address, $ctx) {
        static $id = 0;
        $id += 1;

        $this->connections[$id]['clientData'] = '';
        $this->connections[$id]['cnx'] = new EventBufferEvent($this->base, $fd,
            EventBufferEvent::OPT_CLOSE_ON_FREE);

        if (!$this->connections[$id]['cnx']) {
            echo "Failed creating buffer\n";
            $this->base->exit(NULL);
            exit(1);
        }

        $this->connections[$id]['cnx']->setCallbacks([$this, "ev_read"], NULL,
            [$this, 'ev_error'], $id);
        $this->connections[$id]['cnx']->enable(Event::READ | Event::WRITE);

        $this->ev_write($id, '220 '.$this->domainName." wazzzap?\r\n");
    }

    function ev_error($listener, $ctx) {
        $errno = EventUtil::getLastSocketErrno();

        fprintf(STDERR, "Got an error %d (%s) on the listener. Shutting down.\n",
            $errno, EventUtil::getLastSocketError());

        if ($errno != 0) {
            $this->base->exit(NULL);
            exit();
        }
    }

    public function ev_close($id) {
        $this->connections[$id]['cnx']->disable(Event::READ | Event::WRITE);
        unset($this->connections[$id]);
    }

    protected function ev_write($id, $string) {
        echo 'S('.$id.'): '.$string;
        $this->connections[$id]['cnx']->write($string);
    }

    public function ev_read($buffer, $id) {
        while($buffer->input->length > 0) {
            $this->connections[$id]['clientData'] .= $buffer->input->read($this->maxRead);
            $clientDataLen = strlen($this->connections[$id]['clientData']);

            if($this->connections[$id]['clientData'][$clientDataLen-1] == "\n"
                && $this->connections[$id]['clientData'][$clientDataLen-2] == "\r")
            {
                // remove the trailing \r\n
                $line = substr($this->connections[$id]['clientData'], 0,
                    strlen($this->connections[$id]['clientData']) - 2);

                $this->connections[$id]['clientData'] = '';
                $this->cmd($buffer, $id, $line);
            }
        }
    }

    protected function cmd($buffer, $id, $line) {
        switch ($line) {
            case strncmp('EHLO ', $line, 4):
                $this->ev_write($id, "250-STARTTLS\r\n");
                $this->ev_write($id, "250 OK ehlo\r\n");
                break;

            case strncmp('HELO ', $line, 4):
                $this->ev_write($id, "250-STARTTLS\r\n");
                $this->ev_write($id, "250 OK helo\r\n");
                break;

            case strncmp('QUIT', $line, 3):
                $this->ev_write($id, "250 OK quit\r\n");
                $this->ev_close($id);
                break;

            case strncmp('STARTTLS', $line, 3):
                $this->ev_write($id, "220 Ready to start TLS\r\n");
                $this->connections[$id]['cnx'] = EventBufferEvent::sslFilter($this->base,
                    $this->connections[$id]['cnx'], $this->ctx,
                    EventBufferEvent::SSL_ACCEPTING,
                    EventBufferEvent::OPT_CLOSE_ON_FREE);
                $this->connections[$id]['cnx']->setCallbacks([$this, "ev_read"], NULL, [$this, 'ev_error'], $id);
                $this->connections[$id]['cnx']->enable(Event::READ | Event::WRITE);
                break;

            default:
                echo 'unknown command: '.$line."\n";
                break;
        }
    }
}

new Handler();

See Also

  • EventBufferEvent::sslSocket() - Creates a new SSL buffer event to send its data over an SSL on a socket


Returns a textual description of the cipher

  • « EventBufferEvent::sslFilter
  • EventBufferEvent::sslGetCipherName »
  • PHP Manual
  • EventBufferEvent
  • Returns a textual description of the cipher

EventBufferEvent::sslGetCipherInfo

(PECL event >= 1.10.0)

EventBufferEvent::sslGetCipherInfo — Returns a textual description of the cipher

Description

public EventBufferEvent::sslGetCipherInfo ( void ) : string

Retrieves description of the current cipher by means of the SSL_CIPHER_description SSL API function (see SSL_CIPHER_get_name(3) man page).

Note:

This function is available only if Event is compiled with OpenSSL support.

Parameters

This function has no parameters.

Return Values

Returns a textual description of the cipher on success, or FALSE on error.


Returns the current cipher name of the SSL connection

  • « EventBufferEvent::sslGetCipherInfo
  • EventBufferEvent::sslGetCipherVersion »
  • PHP Manual
  • EventBufferEvent
  • Returns the current cipher name of the SSL connection

EventBufferEvent::sslGetCipherName

(PECL event >= 1.10.0)

EventBufferEvent::sslGetCipherName — Returns the current cipher name of the SSL connection

Description

public EventBufferEvent::sslGetCipherName ( void ) : string

Retrieves name of cipher used by current SSL connection.

Note:

This function is available only if Event is compiled with OpenSSL support.

Parameters

This function has no parameters.

Return Values

Returns the current cipher name of the SSL connection, or FALSE on error.


Returns version of cipher used by current SSL connection

  • « EventBufferEvent::sslGetCipherName
  • EventBufferEvent::sslGetProtocol »
  • PHP Manual
  • EventBufferEvent
  • Returns version of cipher used by current SSL connection

EventBufferEvent::sslGetCipherVersion

(PECL event >= 1.10.0)

EventBufferEvent::sslGetCipherVersion — Returns version of cipher used by current SSL connection

Description

public EventBufferEvent::sslGetCipherVersion ( void ) : string

Retrieves version of cipher used by current SSL connection.

Note:

This function is available only if Event is compiled with OpenSSL support.

Parameters

This function has no parameters.

Return Values

Returns the current cipher version of the SSL connection, or FALSE on error.


Returns the name of the protocol used for current SSL connection

  • « EventBufferEvent::sslGetCipherVersion
  • EventBufferEvent::sslRenegotiate »
  • PHP Manual
  • EventBufferEvent
  • Returns the name of the protocol used for current SSL connection

EventBufferEvent::sslGetProtocol

(PECL event >= 1.10.0)

EventBufferEvent::sslGetProtocol — Returns the name of the protocol used for current SSL connection

Description

public EventBufferEvent::sslGetProtocol ( void ) : string

Returns the name of the protocol used for current SSL connection.

Note:

This function is available only if Event is compiled with OpenSSL support.

Parameters

This function has no parameters.

Return Values

Returns the name of the protocol used for current SSL connection.


Tells a bufferevent to begin SSL renegotiation

  • « EventBufferEvent::sslGetProtocol
  • EventBufferEvent::sslSocket »
  • PHP Manual
  • EventBufferEvent
  • Tells a bufferevent to begin SSL renegotiation

EventBufferEvent::sslRenegotiate

(PECL event >= 1.2.6-beta)

EventBufferEvent::sslRenegotiate — Tells a bufferevent to begin SSL renegotiation

Description

public EventBufferEvent::sslRenegotiate ( void ) : void

Tells a bufferevent to begin SSL renegotiation.

Warning

Calling this function tells the SSL to renegotiate, and the buffer event to invoke appropriate callbacks. This is an advanced topic; this should be generally avoided unless one really knows what he/she does, especially since many SSL versions have had known security issues related to renegotiation.

Parameters

This function has no parameters.

Return Values

No value is returned.


Creates a new SSL buffer event to send its data over an SSL on a socket

  • « EventBufferEvent::sslRenegotiate
  • EventBufferEvent::write »
  • PHP Manual
  • EventBufferEvent
  • Creates a new SSL buffer event to send its data over an SSL on a socket

EventBufferEvent::sslSocket

(PECL event >= 1.2.6-beta)

EventBufferEvent::sslSocket — Creates a new SSL buffer event to send its data over an SSL on a socket

Description

public static EventBufferEvent::sslSocket ( EventBase $base , mixed $socket , EventSslContext $ctx , int $state [, int $options ] ) : EventBufferEvent

Creates a new SSL buffer event to send its data over an SSL on a socket.

Parameters

base

Associated event base.

socket

Socket to use for this SSL. Can be stream or socket resource, numeric file descriptor, or NULL. If socket is NULL, it is assumed that the file descriptor for the socket will be assigned later, for instance, by means of EventBufferEvent::connectHost() method.

ctx

Object of EventSslContext class.

state

The current state of SSL connection: EventBufferEvent::SSL_OPEN , EventBufferEvent::SSL_ACCEPTING or EventBufferEvent::SSL_CONNECTING .

options

The buffer event options.

Return Values

Returns EventBufferEvent object.

See Also

  • EventBufferEvent::sslFilter() - Create a new SSL buffer event to send its data over another buffer event


Adds data to a buffer event's output buffer

  • « EventBufferEvent::sslSocket
  • EventBufferEvent::writeBuffer »
  • PHP Manual
  • EventBufferEvent
  • Adds data to a buffer event's output buffer

EventBufferEvent::write

(PECL event >= 1.2.6-beta)

EventBufferEvent::write — Adds data to a buffer event's output buffer

Description

public EventBufferEvent::write ( string $data ) : bool

Adds data to a buffer event's output buffer

Parameters

data

Data to be added to the underlying buffer.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBufferEvent::writeBuffer() - Adds contents of the entire buffer to a buffer event's output buffer


Adds contents of the entire buffer to a buffer event's output buffer

  • « EventBufferEvent::write
  • About buffer event callbacks »
  • PHP Manual
  • EventBufferEvent
  • Adds contents of the entire buffer to a buffer event's output buffer

EventBufferEvent::writeBuffer

(PECL event >= 1.2.6-beta)

EventBufferEvent::writeBuffer — Adds contents of the entire buffer to a buffer event's output buffer

Description

public EventBufferEvent::writeBuffer ( EventBuffer $buf ) : bool

Adds contents of the entire buffer to a buffer event's output buffer

Parameters

buf

Source EventBuffer object.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventBufferEvent::write() - Adds data to a buffer event's output buffer


About buffer event callbacks

An object of EventBufferEvent class represents a buffer event . The asynchronous nature of I/O performed by Libevent implies that a socket(or other kind of file descriptor) is not always available. Event invokes corresponding callbacks when the resource becomes available for reading or writing, or when some event occurs(e.g. error, "end of line" etc.).

Read and write callbacks should match the following prototype:

callback ([ EventBufferEvent $bev = NULL [, mixed $arg = NULL ]] ) : void

bev

Associated EventBufferEvent object.

arg

Custom variable attached to all callbacks via EventBufferEvent::__construct() , or EventBufferEvent::setCallbacks() .

Event callback should match the following prototype:

callback ([ EventBufferEvent $bev = NULL [, int $events = 0 [, mixed $arg = NULL ]]] ) : void

bev

Associated EventBufferEvent object.

events

Bit mask of events: EventBufferEvent::READING , EventBufferEvent::WRITING , EventBufferEvent::EOL , EventBufferEvent::ERROR and EventBufferEvent::TIMEOUT . See EventBufferEvent constants

arg

Custom variable attached to all callbacks via EventBufferEvent::__construct() , or EventBufferEvent::setCallbacks() .


The EventConfig class

(PECL event >= 1.2.6-beta)

Introduction

Represents configuration structure which could be used in construction of the EventBase .

Class synopsis

final EventConfig {
/* Constants */
const integer FEATURE_ET = 1 ;
const integer FEATURE_O1 = 2 ;
const integer FEATURE_FDS = 4 ;
/* Methods */
public avoidMethod ( string $method ) : bool
public __construct ( void )
public requireFeatures ( int $feature ) : bool
public setMaxDispatchInterval ( int $max_interval , int $max_callbacks , int $min_priority ) : void
}

Predefined Constants

EventConfig::FEATURE_ET

Requires a backend method that supports edge-triggered I/O.

EventConfig::FEATURE_O1

Requires a backend method where adding or deleting a single event, or having a single event become active, is an O(1) operation.

EventConfig::FEATURE_FDS

Requires a backend method that can support arbitrary file descriptor types, and not just sockets.

Table of Contents

  • EventConfig::avoidMethod — Tells libevent to avoid specific event method
  • EventConfig::__construct — Constructs EventConfig object
  • EventConfig::requireFeatures — Enters a required event method feature that the application demands
  • EventConfig::setMaxDispatchInterval — Prevents priority inversion


Tells libevent to avoid specific event method

  • « EventConfig
  • EventConfig::__construct »
  • PHP Manual
  • EventConfig
  • Tells libevent to avoid specific event method

EventConfig::avoidMethod

(PECL event >= 1.2.6-beta)

EventConfig::avoidMethod — Tells libevent to avoid specific event method

Description

public EventConfig::avoidMethod ( string $method ) : bool

Tells libevent to avoid specific event method(backend). See » Creating an event base .

Parameters

method

The backend method to avoid. See EventConfig constants .

Return Values

Returns TRUE on success, otherwise FALSE.

Examples

Example #1 EventConfig::avoidMethod() example

<?php
$cfg = new EventConfig();
if ($cfg->avoidMethod("select")) {
    echo "`select' method avoided\n";
}
?>

See Also

  • EventBase::__construct() - Constructs EventBase object


Constructs EventConfig object

  • « EventConfig::avoidMethod
  • EventConfig::requireFeatures »
  • PHP Manual
  • EventConfig
  • Constructs EventConfig object

EventConfig::__construct

(PECL event >= 1.2.6-beta)

EventConfig::__construct — Constructs EventConfig object

Description

public EventConfig::__construct ( void )

Constructs EventConfig object which could be passed to EventBase::__construct() constructor.

Parameters

This function has no parameters.

Return Values

Returns EventConfig object.

Examples

Example #1 EventConfig::__construct() example

<?php
// Avoiding "select" method
$cfg = new EventConfig();
if ($cfg->avoidMethod("select")) {
    echo "`select' method avoided\n";
}

// Create event_base associated with the config
$base = new EventBase($cfg);

/* Now $base is configured to avoid select backend(method) */
?>

See Also

  • EventBase::__construct() - Constructs EventBase object


Enters a required event method feature that the application demands

  • « EventConfig::__construct
  • EventConfig::setMaxDispatchInterval »
  • PHP Manual
  • EventConfig
  • Enters a required event method feature that the application demands

EventConfig::requireFeatures

(PECL event >= 1.2.6-beta)

EventConfig::requireFeatures — Enters a required event method feature that the application demands

Description

public EventConfig::requireFeatures ( int $feature ) : bool

Enters a required event method feature that the application demands

Parameters

feature

Bitmask of required features. See EventConfig::FEATURE_* constants

Return Values

Examples

Example #1 EventConfig::requireFeatures() example

<?php
$cfg = new EventConfig();

// Create event_base associated with the config
$base = new EventBase($cfg);

// Require FDS feature
if ($cfg->requireFeatures(EventConfig::FEATURE_FDS)) {
    echo "FDS feature is now requried\n";

    $base = new EventBase($cfg);
    ($base->getFeatures() & EventConfig::FEATURE_FDS)
        and print("FDS - arbitrary file descriptor types, and not just sockets\n");
}
?>

The above example will output something similar to:

FDS feature is now requried
FDS - arbitrary file descriptor types, and not just sockets

See Also

  • EventBase::getFeatures() - Returns bitmask of features supported


Prevents priority inversion

  • « EventConfig::requireFeatures
  • EventDnsBase »
  • PHP Manual
  • EventConfig
  • Prevents priority inversion

EventConfig::setMaxDispatchInterval

(No version information available, might only be in Git)

EventConfig::setMaxDispatchInterval — Prevents priority inversion

Description

public EventConfig::setMaxDispatchInterval ( int $max_interval , int $max_callbacks , int $min_priority ) : void

Prevents priority inversion by limiting how many low-priority event callbacks can be invoked before checking for more high-priority events.

Note:

Available since libevent 2.1.0-alpha .

Parameters

max_interval

An interval after which Libevent should stop running callbacks and check for more events, or 0 , if there should be no such interval.

max_callbacks

A number of callbacks after which Libevent should stop running callbacks and check for more events, or -1 , if there should be no such limit.

min_priority

A priority below which max_interval and max_callbacks should not be enforced. If this is set to 0 , they are enforced for events of every priority; if it's set to 1 , they're enforced for events of priority 1 and above, and so on.

Return Values

Returns TRUE on success, otherwise FALSE.


The EventDnsBase class

(PECL event >= 1.2.6-beta)

Introduction

Represents Libevent's DNS base structure. Used to resolve DNS asyncronously, parse configuration files like resolv.conf etc.

Class synopsis

final EventDnsBase {
/* Constants */
const integer OPTION_SEARCH = 1 ;
const integer OPTION_NAMESERVERS = 2 ;
const integer OPTION_MISC = 4 ;
const integer OPTION_HOSTSFILE = 8 ;
const integer OPTIONS_ALL = 15 ;
/* Methods */
public addNameserverIp ( string $ip ) : bool
public addSearch ( string $domain ) : void
public clearSearch ( void ) : void
public __construct ( EventBase $base , bool $initialize )
public countNameservers ( void ) : int
public loadHosts ( string $hosts ) : bool
public parseResolvConf ( int $flags , string $filename ) : bool
public setOption ( string $option , string $value ) : bool
public setSearchNdots ( int $ndots ) : bool
}

Predefined Constants

EventDnsBase::OPTION_SEARCH

Tells to read the domain and search fields from the resolv.conf file and the ndots option, and use them to decide which domains(if any) to search for hostnames that aren’t fully-qualified.

EventDnsBase::OPTION_NAMESERVERS

Tells to learn the nameservers from the resolv.conf file.

EventDnsBase::OPTION_MISC

EventDnsBase::OPTION_HOSTSFILE

Tells to read a list of hosts from /etc/hosts as part of loading the resolv.conf file.

EventDnsBase::OPTIONS_ALL

Tells to learn as much as it can from the resolv.conf file.

Table of Contents

  • EventDnsBase::addNameserverIp — Adds a nameserver to the DNS base
  • EventDnsBase::addSearch — Adds a domain to the list of search domains
  • EventDnsBase::clearSearch — Removes all current search suffixes
  • EventDnsBase::__construct — Constructs EventDnsBase object
  • EventDnsBase::countNameservers — Gets the number of configured nameservers
  • EventDnsBase::loadHosts — Loads a hosts file (in the same format as /etc/hosts) from hosts file
  • EventDnsBase::parseResolvConf — Scans the resolv.conf-formatted file
  • EventDnsBase::setOption — Set the value of a configuration option
  • EventDnsBase::setSearchNdots — Set the 'ndots' parameter for searches


Adds a nameserver to the DNS base

  • « EventDnsBase
  • EventDnsBase::addSearch »
  • PHP Manual
  • EventDnsBase
  • Adds a nameserver to the DNS base

EventDnsBase::addNameserverIp

(PECL event >= 1.2.6-beta)

EventDnsBase::addNameserverIp — Adds a nameserver to the DNS base

Description

public EventDnsBase::addNameserverIp ( string $ip ) : bool

Adds a nameserver to the evdns_base.

Parameters

ip

The nameserver string, either as an IPv4 address, an IPv6 address, an IPv4 address with a port ( IPv4:Port ), or an IPv6 address with a port ( [IPv6]:Port ).

Return Values

Returns TRUE on success. Otherwise FALSE.


Adds a domain to the list of search domains

  • « EventDnsBase::addNameserverIp
  • EventDnsBase::clearSearch »
  • PHP Manual
  • EventDnsBase
  • Adds a domain to the list of search domains

EventDnsBase::addSearch

(PECL event >= 1.2.6-beta)

EventDnsBase::addSearch — Adds a domain to the list of search domains

Description

public EventDnsBase::addSearch ( string $domain ) : void

Adds a domain to the list of search domains

Parameters

domain

Search domain.

Return Values

No value is returned.


Removes all current search suffixes

  • « EventDnsBase::addSearch
  • EventDnsBase::__construct »
  • PHP Manual
  • EventDnsBase
  • Removes all current search suffixes

EventDnsBase::clearSearch

(PECL event >= 1.2.6-beta)

EventDnsBase::clearSearch — Removes all current search suffixes

Description

public EventDnsBase::clearSearch ( void ) : void

Removes all current search suffixes from the DNS base; the EventDnsBase::addSearch() function adds a suffix.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • EventDnsBase::addSearch() - Adds a domain to the list of search domains


Constructs EventDnsBase object

  • « EventDnsBase::clearSearch
  • EventDnsBase::countNameservers »
  • PHP Manual
  • EventDnsBase
  • Constructs EventDnsBase object

EventDnsBase::__construct

(PECL event >= 1.2.6-beta)

EventDnsBase::__construct — Constructs EventDnsBase object

Description

public EventDnsBase::__construct ( EventBase $base , bool $initialize )

Constructs EventDnsBase object.

Parameters

base

Event base.

initialize

If the initialize argument is TRUE, it tries to configure the DNS base sensibly given your operating system’s default. Otherwise, it leaves the event DNS base empty, with no nameservers or options configured. In the latter case DNS base should be configured manually, e.g. with EventDnsBase::parseResolvConf() .

Return Values

Returns EventDnsBase object.


Gets the number of configured nameservers

  • « EventDnsBase::__construct
  • EventDnsBase::loadHosts »
  • PHP Manual
  • EventDnsBase
  • Gets the number of configured nameservers

EventDnsBase::countNameservers

(PECL event >= 1.2.6-beta)

EventDnsBase::countNameservers — Gets the number of configured nameservers

Description

public EventDnsBase::countNameservers ( void ) : int

Gets the number of configured nameservers

Parameters

This function has no parameters.

Return Values

Returns the number of configured nameservers(not necessarily the number of running nameservers). This is useful for double-checking whether our calls to the various nameserver configuration functions have been successful.


Loads a hosts file (in the same format as /etc/hosts) from hosts file

  • « EventDnsBase::countNameservers
  • EventDnsBase::parseResolvConf »
  • PHP Manual
  • EventDnsBase
  • Loads a hosts file (in the same format as /etc/hosts) from hosts file

EventDnsBase::loadHosts

(PECL event >= 1.2.6-beta)

EventDnsBase::loadHosts — Loads a hosts file (in the same format as /etc/hosts) from hosts file

Description

public EventDnsBase::loadHosts ( string $hosts ) : bool

Loads a hosts file (in the same format as /etc/hosts ) from hosts file.

Parameters

hosts

Path to the hosts' file.

Return Values

Returns TRUE on success. Otherwise FALSE.


Scans the resolv.conf-formatted file

  • « EventDnsBase::loadHosts
  • EventDnsBase::setOption »
  • PHP Manual
  • EventDnsBase
  • Scans the resolv.conf-formatted file

EventDnsBase::parseResolvConf

(PECL event >= 1.2.6-beta)

EventDnsBase::parseResolvConf — Scans the resolv.conf-formatted file

Description

public EventDnsBase::parseResolvConf ( int $flags , string $filename ) : bool

Scans the resolv.conf-formatted file stored in filename, and read in all the options from it that are listed in flags

Parameters

flags

Determines what information is parsed from the resolv.conf file. See the man page for resolv.conf for the format of this file.

The following directives are not parsed from the file: sortlist, rotate, no-check-names, inet6, debug .

If this function encounters an error, the possible return values are:

  • 1 = failed to open file
  • 2 = failed to stat file
  • 3 = file too large
  • 4 = out of memory
  • 5 = short read from file
  • 6 = no nameservers listed in the file

filename

Path to resolv.conf file.

Return Values

Returns TRUE on success. Otherwise FALSE.


Set the value of a configuration option

  • « EventDnsBase::parseResolvConf
  • EventDnsBase::setSearchNdots »
  • PHP Manual
  • EventDnsBase
  • Set the value of a configuration option

EventDnsBase::setOption

(PECL event >= 1.2.6-beta)

EventDnsBase::setOption — Set the value of a configuration option

Description

public EventDnsBase::setOption ( string $option , string $value ) : bool

Set the value of a configuration option.

Parameters

option

The currently available configuration options are: "ndots" , "timeout" , "max-timeouts" , "max-inflight" , and "attempts" .

value

Option value.

Return Values

Returns TRUE on success. Otherwise FALSE.


Set the 'ndots' parameter for searches

  • « EventDnsBase::setOption
  • EventHttp »
  • PHP Manual
  • EventDnsBase
  • Set the 'ndots' parameter for searches

EventDnsBase::setSearchNdots

(PECL event >= 1.2.6-beta)

EventDnsBase::setSearchNdots — Set the 'ndots' parameter for searches

Description

public EventDnsBase::setSearchNdots ( int $ndots ) : bool

Set the 'ndots' parameter for searches. Sets the number of dots which, when found in a name, causes the first query to be without any search domain.

Parameters

ndots

The number of dots.

Return Values

Returns TRUE on success. Otherwise FALSE.


The EventHttp class

(PECL event >= 1.4.0-beta)

Introduction

Represents HTTP server.

Class synopsis

final EventHttp {
/* Methods */
public accept ( mixed $socket ) : bool
public addServerAlias ( string $alias ) : bool
public bind ( string $address , int $port ) : void
public __construct ( EventBase $base [, EventSslContext $ctx = NULL ] )
public removeServerAlias ( string $alias ) : bool
public setAllowedMethods ( int $methods ) : void
public setCallback ( string $path , string $cb [, string $arg ] ) : void
public setDefaultCallback ( string $cb [, string $arg ] ) : void
public setMaxBodySize ( int $value ) : void
public setMaxHeadersSize ( int $value ) : void
public setTimeout ( int $value ) : void
}

Table of Contents

  • EventHttp::accept — Makes an HTTP server accept connections on the specified socket stream or resource
  • EventHttp::addServerAlias — Adds a server alias to the HTTP server object
  • EventHttp::bind — Binds an HTTP server on the specified address and port
  • EventHttp::__construct — Constructs EventHttp object(the HTTP server)
  • EventHttp::removeServerAlias — Removes server alias
  • EventHttp::setAllowedMethods — Sets the what HTTP methods are supported in requests accepted by this server, and passed to user callbacks
  • EventHttp::setCallback — Sets a callback for specified URI
  • EventHttp::setDefaultCallback — Sets default callback to handle requests that are not caught by specific callbacks
  • EventHttp::setMaxBodySize — Sets maximum request body size
  • EventHttp::setMaxHeadersSize — Sets maximum HTTP header size
  • EventHttp::setTimeout — Sets the timeout for an HTTP request


Makes an HTTP server accept connections on the specified socket stream or resource

  • « EventHttp
  • EventHttp::addServerAlias »
  • PHP Manual
  • EventHttp
  • Makes an HTTP server accept connections on the specified socket stream or resource

EventHttp::accept

(PECL event >= 1.2.6-beta)

EventHttp::accept — Makes an HTTP server accept connections on the specified socket stream or resource

Description

public EventHttp::accept ( mixed $socket ) : bool

Makes an HTTP server accept connections on the specified socket stream or resource. The socket should be ready to accept connections.

Can be called multiple times to accept connections on different sockets.

Note:

To bind a socket, listen , and accept connections on the socket in s single call use EventHttp::bind() . EventHttp::accept() is needed only if one already has a socket ready to accept connections.

Parameters

socket

Socket resource, stream or numeric file descriptor representing a socket ready to accept connections.

Return Values

Returns TRUE on success. Otherwise FALSE.

Examples

Example #1 EventHttp::accept() example

<?php
$base = new EventBase();
$http = new EventHttp($base);

$addresses = array (
     8091 => "127.0.0.1",
     8092 => "127.0.0.2",
);
$i = 0;

$socket = array();

foreach ($addresses as $port => $ip) {
    echo $ip, " ", $port, PHP_EOL;
    $socket[$i] = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if (!socket_bind($socket[$i], $ip, $port)) {
        exit("socket_bind failed\n");
    }
    socket_listen($socket[$i], 0);
    socket_set_nonblock($socket[$i]);

    if (!$http->accept($socket[$i])) {
        echo "Accept failed\n";
        exit(1);
    }

    ++$i;
}

$http->setCallback("/some-page", function() {
 echo "(some-page)\n";
    echo "URI: ", $req->getUri(), PHP_EOL;
    $req->sendReply(200, "OK");
    echo "OK\n";
});

$http->setDefaultCallback(function($req) {
    echo "URI: ", $req->getUri(), PHP_EOL;
    $req->sendReply(200, "OK");
    echo "OK\n";
});

$signal = Event::signal($base, SIGINT, function () use ($base) {
    echo "Caught SIGINT. Stopping...\n";
    $base->stop();
});
$signal->add();

$base->dispatch();
echo "END\n";
// We didn't close sockets, since Libevent already sets
// CLOSE_ON_FREE and CLOSE_ON_EXEC flags on the file
// descriptor associated with the sockets.
?>

The above example will output something similar to:

Client:
$ nc 127.0.0.1 8091
GET /about HTTP/1.0
Connection: close

HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close

Server:
127.0.0.1 8091
127.0.0.2 8092
URI: /about
OK

See Also

  • EventHttp::bind() - Binds an HTTP server on the specified address and port


Adds a server alias to the HTTP server object

  • « EventHttp::accept
  • EventHttp::bind »
  • PHP Manual
  • EventHttp
  • Adds a server alias to the HTTP server object

EventHttp::addServerAlias

(PECL event >= 1.4.0-beta)

EventHttp::addServerAlias — Adds a server alias to the HTTP server object

Description

public EventHttp::addServerAlias ( string $alias ) : bool

Adds a server alias to the HTTP server object.

Parameters

alias

The alias to add.

Return Values

Returns TRUE on success. Otherwise FALSE.

Examples

Example #1 EventHttp::addServerAlias() example

<?php
$base = new EventBase();
$http = new EventHttp($base);

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

if (!$http->bind("127.0.0.1", 8088)) {
    exit("bind(1) failed\n");
};

if (!$http->addServerAlias("local.net")) {
    exit("Failed to add server alias\n");
}

$http->setCallback("/about", function($req) {
    echo "URI: ", $req->getUri(), PHP_EOL;
    $req->sendReply(200, "OK");
});
$base->dispatch();
?>

See Also

  • EventHttp::removeServerAlias() - Removes server alias


Binds an HTTP server on the specified address and port

  • « EventHttp::addServerAlias
  • EventHttp::__construct »
  • PHP Manual
  • EventHttp
  • Binds an HTTP server on the specified address and port

EventHttp::bind

(PECL event >= 1.2.6-beta)

EventHttp::bind — Binds an HTTP server on the specified address and port

Description

public EventHttp::bind ( string $address , int $port ) : void

Binds an HTTP server on the specified address and port.

Can be called multiple times to bind the same HTTP server to multiple different ports.

Parameters

address

A string containing the IP address to listen(2) on.

port

The port number to listen on.

Return Values

Returns TRUE on success. Otherwise FALSE.

Examples

Example #1 EventHttp::bind() example

<?php
$base = new EventBase();
$http = new EventHttp($base);

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

if (!$http->bind("127.0.0.1", 8088)) {
    exit("bind(1) failed\n");
};
if (!$http->bind("127.0.0.1", 8089)) {
    exit("bind(2) failed\n");
};

$http->setCallback("/about", function($req) {
    echo "URI: ", $req->getUri(), PHP_EOL;
    $req->sendReply(200, "OK");
    echo "OK\n";
});

$base->dispatch();
?>

The above example will output something similar to:

Client:

$ nc 127.0.0.1 8088
GET /about HTTP/1.0
Connection: close

HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close

$ nc 127.0.0.1 8089
GET /unknown HTTP/1.0
Connection: close

HTTP/1.1 404 Not Found
Content-Type: text/html
Date: Wed, 13 Mar 2013 04:14:41 GMT
Content-Length: 149
Connection: close

<html><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL /unknown was not found on this server.</p></body></html>

Server:
URI: /about
OK

See Also

  • EventHttp::accept() - Makes an HTTP server accept connections on the specified socket stream or resource


Constructs EventHttp object(the HTTP server)

  • « EventHttp::bind
  • EventHttp::removeServerAlias »
  • PHP Manual
  • EventHttp
  • Constructs EventHttp object(the HTTP server)

EventHttp::__construct

(PECL event >= 1.2.6-beta)

EventHttp::__construct — Constructs EventHttp object(the HTTP server)

Description

public EventHttp::__construct ( EventBase $base [, EventSslContext $ctx = NULL ] )

Constructs the HTTP server object.

Parameters

base

Associated event base.

ctx

EventSslContext class object. Turns plain HTTP server into HTTPS server. It means that if ctx is configured correctly, then the underlying buffer events will be based on OpenSSL sockets. Thus, all traffic will pass through the SSL or TLS.

Note:

This parameter is available only if Event is compiled with OpenSSL support and only with Libevent 2.1.0-alpha and higher.

Return Values

Returns EventHttp object.

Changelog

Version | Description
1.9.0 | OpenSSL support (ctx) added.

Examples

Example #1 Simple HTTP server

<?php
/*
 * Simple HTTP server.
 *
 * To test it:
 * 1) Run it on a port of your choice, e.g.:
 * $ php examples/http.php 8010
 * 2) In another terminal connect to some address on this port
 * and make GET or POST request(others are turned off here), e.g.:
 * $ nc -t 127.0.0.1 8010
 * POST /about HTTP/1.0
 * Content-Type: text/plain
 * Content-Length: 4
 * Connection: close
 * (press Enter)
 *
 * It will output
 * a=12
 * HTTP/1.0 200 OK
 * Content-Type: text/html; charset=ISO-8859-1
 * Connection: close
 *
 * $ nc -t 127.0.0.1 8010
 * GET /dump HTTP/1.0
 * Content-Type: text/plain
 * Content-Encoding: UTF-8
 * Connection: close
 * (press Enter)
 *
 * It will output:
 * HTTP/1.0 200 OK
 * Content-Type: text/html; charset=ISO-8859-1
 * Connection: close
 * (press Enter)
 *
 * $ nc -t 127.0.0.1 8010
 * GET /unknown HTTP/1.0
 * Connection: close
 *
 * It will output:
 * HTTP/1.0 200 OK
 * Content-Type: text/html; charset=ISO-8859-1
 * Connection: close
 *
 * 3) See what the server outputs on the previous terminal window.
 */

function _http_dump($req, $data) {
    static $counter      = 0;
    static $max_requests = 2;

    if (++$counter >= $max_requests)  {
        echo "Counter reached max requests $max_requests. Exiting\n";
        exit();
    }

    echo __METHOD__, " called\n";
    echo "request:"; var_dump($req);
    echo "data:"; var_dump($data);

    echo "\n===== DUMP =====\n";
    echo "Command:", $req->getCommand(), PHP_EOL;
    echo "URI:", $req->getUri(), PHP_EOL;
    echo "Input headers:"; var_dump($req->getInputHeaders());
    echo "Output headers:"; var_dump($req->getOutputHeaders());

    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";

    echo "\n >> Reading input buffer ...\n";
    $buf = $req->getInputBuffer();
    while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
        echo $s, PHP_EOL;
    }
    echo "No more data in the buffer\n";
}

function _http_about($req) {
    echo __METHOD__, PHP_EOL;
    echo "URI: ", $req->getUri(), PHP_EOL;
    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";
}

function _http_default($req, $data) {
    echo __METHOD__, PHP_EOL;
    echo "URI: ", $req->getUri(), PHP_EOL;
    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";
}

$port = 8010;
if ($argc > 1) {
    $port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
    exit("Invalid port");
}

$base = new EventBase();
$http = new EventHttp($base);
$http->setAllowedMethods(EventHttpRequest::CMD_GET | EventHttpRequest::CMD_POST);

$http->setCallback("/dump", "_http_dump", array(4, 8));
$http->setCallback("/about", "_http_about");
$http->setDefaultCallback("_http_default", "custom data value");

$http->bind("0.0.0.0", 8010);
$base->loop();
?>

The above example will output something similar to:

a=12
HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close

HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close
(press Enter)

HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close


Removes server alias

  • « EventHttp::__construct
  • EventHttp::setAllowedMethods »
  • PHP Manual
  • EventHttp
  • Removes server alias

EventHttp::removeServerAlias

(PECL event >= 1.4.0-beta)

EventHttp::removeServerAlias — Removes server alias

Description

public EventHttp::removeServerAlias ( string $alias ) : bool

Removes server alias added with EventHttp::addServerAlias()

Parameters

alias

The alias to remove.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventHttp::addServerAlias() - Adds a server alias to the HTTP server object


Sets the what HTTP methods are supported in requests accepted by this server, and passed to user callbacks

  • « EventHttp::removeServerAlias
  • EventHttp::setCallback »
  • PHP Manual
  • EventHttp
  • Sets the what HTTP methods are supported in requests accepted by this server, and passed to user callbacks

EventHttp::setAllowedMethods

(PECL event >= 1.4.0-beta)

EventHttp::setAllowedMethods — Sets the what HTTP methods are supported in requests accepted by this server, and passed to user callbacks

Description

public EventHttp::setAllowedMethods ( int $methods ) : void

Sets the what HTTP methods are supported in requests accepted by this server, and passed to user callbacks

If not supported they will generate a "405 Method not allowed" response.

By default this includes the following methods: GET , POST , HEAD , PUT , DELETE . See EventHttpRequest::CMD_* constants.

Parameters

methods

A bit mask of EventHttpRequest::CMD_* constants .

Return Values

No value is returned.


Sets a callback for specified URI

  • « EventHttp::setAllowedMethods
  • EventHttp::setDefaultCallback »
  • PHP Manual
  • EventHttp
  • Sets a callback for specified URI

EventHttp::setCallback

(PECL event >= 1.4.0-beta)

EventHttp::setCallback — Sets a callback for specified URI

Description

public EventHttp::setCallback ( string $path , string $cb [, string $arg ] ) : void

Sets a callback for specified URI.

Parameters

path

The path for which to invoke the callback.

cb

The callback callable that gets invoked on requested path . It should match the following prototype:

callback ([ EventHttpRequest $req = NULL [, mixed $arg = NULL ]] ) : void

req

EventHttpRequest object.

arg

Custom data.

arg

Custom data.

Return Values

Returns TRUE on success. Otherwise FALSE.

Examples

Example #1 EventHttp::setCallback() example

<?php
/*
 * Simple HTTP server.
 *
 * To test it:
 * 1) Run it on a port of your choice, e.g.:
 * $ php examples/http.php 8010
 * 2) In another terminal connect to some address on this port
 * and make GET or POST request(others are turned off here), e.g.:
 * $ nc -t 127.0.0.1 8010
 * POST /about HTTP/1.0
 * Content-Type: text/plain
 * Content-Length: 4
 * Connection: close
 * (press Enter)
 *
 * It will output
 * a=12
 * HTTP/1.0 200 OK
 * Content-Type: text/html; charset=ISO-8859-1
 * Connection: close
 *
 * 3) See what the server outputs on the previous terminal window.
 */

function _http_dump($req, $data) {
    static $counter      = 0;
    static $max_requests = 2;

    if (++$counter >= $max_requests)  {
        echo "Counter reached max requests $max_requests. Exiting\n";
        exit();
    }

    echo __METHOD__, " called\n";
    echo "request:"; var_dump($req);
    echo "data:"; var_dump($data);

    echo "\n===== DUMP =====\n";
    echo "Command:", $req->getCommand(), PHP_EOL;
    echo "URI:", $req->getUri(), PHP_EOL;
    echo "Input headers:"; var_dump($req->getInputHeaders());
    echo "Output headers:"; var_dump($req->getOutputHeaders());

    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";

    echo "\n >> Reading input buffer ...\n";
    $buf = $req->getInputBuffer();
    while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
        echo $s, PHP_EOL;
    }
    echo "No more data in the buffer\n";
}

function _http_about($req) {
    echo __METHOD__, PHP_EOL;
    echo "URI: ", $req->getUri(), PHP_EOL;
    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";
}

function _http_default($req, $data) {
    echo __METHOD__, PHP_EOL;
    echo "URI: ", $req->getUri(), PHP_EOL;
    echo "\n >> Sending reply ...";
    $req->sendReply(200, "OK");
    echo "OK\n";
}

$port = 8010;
if ($argc > 1) {
    $port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
    exit("Invalid port");
}

$base = new EventBase();
$http = new EventHttp($base);
$http->setAllowedMethods(EventHttpRequest::CMD_GET | EventHttpRequest::CMD_POST);

$http->setCallback("/dump", "_http_dump", array(4, 8));
$http->setCallback("/about", "_http_about");
$http->setDefaultCallback("_http_default", "custom data value");

$http->bind("0.0.0.0", 8010);
$base->loop();
?>

The above example will output something similar to:

a=12
HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close

See Also

  • EventHttp::setDefaultCallback() - Sets default callback to handle requests that are not caught by specific callbacks


Sets default callback to handle requests that are not caught by specific callbacks

  • « EventHttp::setCallback
  • EventHttp::setMaxBodySize »
  • PHP Manual
  • EventHttp
  • Sets default callback to handle requests that are not caught by specific callbacks

EventHttp::setDefaultCallback

(PECL event >= 1.4.0-beta)

EventHttp::setDefaultCallback — Sets default callback to handle requests that are not caught by specific callbacks

Description

public EventHttp::setDefaultCallback ( string $cb [, string $arg ] ) : void

Sets default callback to handle requests that are not caught by specific callbacks

Parameters

cb

The callback callable . It should match the following prototype:

callback ([ EventHttpRequest $req = NULL [, mixed $arg = NULL ]] ) : void

req

EventHttpRequest object.

arg

Custom data.

arg

User custom data passed to the callback.

Return Values

Returns TRUE on success. Otherwise FALSE.

Examples

Example #1 EventHttp::setDefaultCallback() example

<?php
$base = new EventBase();
$http = new EventHttp($base);

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

if (!$http->bind("127.0.0.1", 8088)) {
    exit("bind(1) failed\n");
};

$http->setDefaultCallback(function($req) {
    echo "URI: ", $req->getUri(), PHP_EOL;
    $req->sendReply(200, "OK");
});

$base->dispatch();
?>

See Also

  • EventHttp::setCallback() - Sets a callback for specified URI


Sets maximum request body size

  • « EventHttp::setDefaultCallback
  • EventHttp::setMaxHeadersSize »
  • PHP Manual
  • EventHttp
  • Sets maximum request body size

EventHttp::setMaxBodySize

(PECL event >= 1.4.0-beta)

EventHttp::setMaxBodySize — Sets maximum request body size

Description

public EventHttp::setMaxBodySize ( int $value ) : void

Sets maximum request body size.

Parameters

value

The body size in bytes.

Return Values

No value is returned.

See Also

  • EventHttp::setMaxHeadersSize() - Sets maximum HTTP header size


Sets maximum HTTP header size

  • « EventHttp::setMaxBodySize
  • EventHttp::setTimeout »
  • PHP Manual
  • EventHttp
  • Sets maximum HTTP header size

EventHttp::setMaxHeadersSize

(PECL event >= 1.4.0-beta)

EventHttp::setMaxHeadersSize — Sets maximum HTTP header size

Description

public EventHttp::setMaxHeadersSize ( int $value ) : void

Sets maximum HTTP header size.

Parameters

value

The header size in bytes.

Return Values

No value is returned.

See Also

  • EventHttp::setMaxHeadersSize()


Sets the timeout for an HTTP request

  • « EventHttp::setMaxHeadersSize
  • EventHttpConnection »
  • PHP Manual
  • EventHttp
  • Sets the timeout for an HTTP request

EventHttp::setTimeout

(PECL event >= 1.4.0-beta)

EventHttp::setTimeout — Sets the timeout for an HTTP request

Description

public EventHttp::setTimeout ( int $value ) : void

Sets the timeout for an HTTP request.

Parameters

value

The timeout in seconds.

Return Values

No value is returned.


The EventHttpConnection class

(PECL event >= 1.4.0-beta)

Introduction

Represents an HTTP connection.

Class synopsis

EventHttpConnection {
/* Methods */
public __construct ( EventBase $base , EventDnsBase $dns_base , string $address , int $port [, EventSslContext $ctx = NULL ] )
public getBase ( void ) : EventBase
public getPeer ( string &$address , int &$port ) : void
public makeRequest ( EventHttpRequest $req , int $type , string $uri ) : bool
public setCloseCallback ( callable $callback [, mixed $data ] ) : void
public setLocalAddress ( string $address ) : void
public setLocalPort ( int $port ) : void
public setMaxBodySize ( string $max_size ) : void
public setMaxHeadersSize ( string $max_size ) : void
public setRetries ( int $retries ) : void
public setTimeout ( int $timeout ) : void
}

Table of Contents

  • EventHttpConnection::__construct — Constructs EventHttpConnection object
  • EventHttpConnection::getBase — Returns event base associated with the connection
  • EventHttpConnection::getPeer — Gets the remote address and port associated with the connection
  • EventHttpConnection::makeRequest — Makes an HTTP request over the specified connection
  • EventHttpConnection::setCloseCallback — Set callback for connection close
  • EventHttpConnection::setLocalAddress — Sets the IP address from which HTTP connections are made
  • EventHttpConnection::setLocalPort — Sets the local port from which connections are made
  • EventHttpConnection::setMaxBodySize — Sets maximum body size for the connection
  • EventHttpConnection::setMaxHeadersSize — Sets maximum header size
  • EventHttpConnection::setRetries — Sets the retry limit for the connection
  • EventHttpConnection::setTimeout — Sets the timeout for the connection


Constructs EventHttpConnection object

  • « EventHttpConnection
  • EventHttpConnection::getBase »
  • PHP Manual
  • EventHttpConnection
  • Constructs EventHttpConnection object

EventHttpConnection::__construct

(PECL event >= 1.2.6-beta)

EventHttpConnection::__construct — Constructs EventHttpConnection object

Description

public EventHttpConnection::__construct ( EventBase $base , EventDnsBase $dns_base , string $address , int $port [, EventSslContext $ctx = NULL ] )

Constructs EventHttpConnection object.

Parameters

base

Associated event base.

dns_base

If dns_base is NULL, hostname resolution will block.

address

The address to connect to.

port

The port to connect to.

ctx

EventSslContext class object. Enables OpenSSL.

Note:

This parameter is available only if Event is compiled with OpenSSL support and only with Libevent 2.1.0-alpha and higher.

Return Values

Returns EventHttpConnection object.

Changelog

Version | Description
1.9.0 | OpenSSL support (ctx) added.


Returns event base associated with the connection

  • « EventHttpConnection::__construct
  • EventHttpConnection::getPeer »
  • PHP Manual
  • EventHttpConnection
  • Returns event base associated with the connection

EventHttpConnection::getBase

(PECL event >= 1.2.6-beta)

EventHttpConnection::getBase — Returns event base associated with the connection

Description

public EventHttpConnection::getBase ( void ) : EventBase

Returns event base associated with the connection.

Parameters

This function has no parameters.

Return Values

On success returns EventBase object associated with the connection. Otherwise FALSE.


Gets the remote address and port associated with the connection

  • « EventHttpConnection::getBase
  • EventHttpConnection::makeRequest »
  • PHP Manual
  • EventHttpConnection
  • Gets the remote address and port associated with the connection

EventHttpConnection::getPeer

(PECL event >= 1.2.6-beta)

EventHttpConnection::getPeer — Gets the remote address and port associated with the connection

Description

public EventHttpConnection::getPeer ( string &$address , int &$port ) : void

Gets the remote address and port associated with the connection

Parameters

address

Address of the peer.

port

Port of the peer.

Return Values

No value is returned.


Makes an HTTP request over the specified connection

  • « EventHttpConnection::getPeer
  • EventHttpConnection::setCloseCallback »
  • PHP Manual
  • EventHttpConnection
  • Makes an HTTP request over the specified connection

EventHttpConnection::makeRequest

(PECL event >= 1.4.0-beta)

EventHttpConnection::makeRequest — Makes an HTTP request over the specified connection

Description

public EventHttpConnection::makeRequest ( EventHttpRequest $req , int $type , string $uri ) : bool

Makes an HTTP request over the specified connection. type is one of EventHttpRequest::CMD_* constants.

Parameters

req

The connection object over which to send the request.

type

One of EventHttpRequest::CMD_* constants .

uri

The URI associated with the request.

Return Values

Returns TRUE on success. Otherwise FALSE.

Examples

Example #1 EventHttpConnection::makeRequest() example

<?php
function _request_handler($req, $base) {
    echo __FUNCTION__, PHP_EOL;

    if (is_null($req)) {
        echo "Timed out\n";
    } else {
        $response_code = $req->getResponseCode();

        if ($response_code == 0) {
            echo "Connection refused\n";
        } elseif ($response_code != 200) {
            echo "Unexpected response: $response_code\n";
        } else {
            echo "Success: $response_code\n";
            $buf = $req->getInputBuffer();
            echo "Body:\n";
            while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
                echo $s, PHP_EOL;
            }
        }
    }

    $base->exit(NULL);
}

$address = "127.0.0.1";
$port = 80;

$base = new EventBase();
$conn = new EventHttpConnection($base, NULL, $address, $port);
$conn->setTimeout(5);
$req = new EventHttpRequest("_request_handler", $base);

$req->addHeader("Host", $address, EventHttpRequest::OUTPUT_HEADER);
$req->addHeader("Content-Length", "0", EventHttpRequest::OUTPUT_HEADER);
$conn->makeRequest($req, EventHttpRequest::CMD_GET, "/index.cphp");

$base->loop();
?>

The above example will output something similar to:

_request_handler
Success: 200
Body:
PHP, date:
2013-03-13T20:27:52+05:00

See Also

  • EventHttpRequest::addHeader() - Adds an HTTP header to the headers of the request


Set callback for connection close

  • « EventHttpConnection::makeRequest
  • EventHttpConnection::setLocalAddress »
  • PHP Manual
  • EventHttpConnection
  • Set callback for connection close

EventHttpConnection::setCloseCallback

(PECL event >= 1.8.0)

EventHttpConnection::setCloseCallback — Set callback for connection close

Description

public EventHttpConnection::setCloseCallback ( callable $callback [, mixed $data ] ) : void

Sets callback for connection close.

Parameters

callback

Callback which is called when connection is closed. Should match the following prototype:

callback ([ EventHttpConnection $conn = NULL [, mixed $arg = NULL ]] ) : void

Return Values

No value is returned.

Examples

Example #1 EventHttpConnection::setCloseCallback() example

<?php
/*
 * Setting up close-connection callback
 *
 * The script handles closed connections using HTTP API.
 *
 * Usage:
 * 1) Launch the server:
 * $ php examples/http_closecb.php 4242
 *
 * 2) Launch a client in another terminal. Telnet-like
 * session should look like the following:
 *
 * $ nc -t 127.0.0.1 4242
 * GET / HTTP/1.0
 * Connection: close
 *
 * The server will output something similar to the following:
 *
 * HTTP/1.0 200 OK
 * Content-Type: multipart/x-mixed-replace;boundary=boundarydonotcross
 * Connection: close
 *
 * <html>
 *
 * 3) Terminate the client connection abruptly,
 * i.e. kill the process, or just press Ctrl-C.
 *
 * 4) Check if the server called _close_callback.
 * The script should output "_close_callback" string to standard output.
 *
 * 5) Check if the server's process has no orphaned connections,
 * e.g. with `lsof` utility.
 */

function _close_callback($conn)
{
    echo __FUNCTION__, PHP_EOL;
}

function _http_default($req, $dummy)
{
    $conn = $req->getConnection();
    $conn->setCloseCallback('_close_callback', NULL);

    /*
    By enabling Event::READ we protect the server against unclosed conections.
    This is a peculiarity of Libevent. The library disables Event::READ events
     on this connection, and the server is not notified about terminated
    connections.

    So each time client terminates connection abruptly, we get an orphaned
    connection. For instance, the following is a part of `lsof -p $PID | grep TCP`
    command after client has terminated connection:

    57-php     15057 ruslan  6u  unix 0xffff8802fb59c780   0t0  125187 socket
    58:php     15057 ruslan  7u  IPv4             125189   0t0     TCP *:4242 (LISTEN)
    59:php     15057 ruslan  8u  IPv4             124342   0t0     TCP localhost:4242->localhost:37375 (CLOSE_WAIT)

    where $PID is our process ID.

    The following block of code fixes such kind of orphaned connections.
     */
    $bev = $req->getBufferEvent();
    $bev->enable(Event::READ);
    // We have to free it explicitly. See
EventHttpRequest::getConnection()
$bev->free(); // we have to free it explicitly

    $req->addHeader(
        'Content-Type',
        'multipart/x-mixed-replace;boundary=boundarydonotcross',
        EventHttpRequest::OUTPUT_HEADER
    );

    $buf = new EventBuffer();
    $buf->add('<html>');

    $req->sendReply(200, "OK");
    $req->sendReplyChunk($buf);
}

$port = 4242;
if ($argc > 1) {
    $port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
    exit("Invalid port");
}

$base = new EventBase();
$http = new EventHttp($base);

$http->setDefaultCallback("_http_default", NULL);
$http->bind("0.0.0.0", $port);
$base->loop();

?>


Sets the IP address from which HTTP connections are made

  • « EventHttpConnection::setCloseCallback
  • EventHttpConnection::setLocalPort »
  • PHP Manual
  • EventHttpConnection
  • Sets the IP address from which HTTP connections are made

EventHttpConnection::setLocalAddress

(PECL event >= 1.2.6-beta)

EventHttpConnection::setLocalAddress — Sets the IP address from which HTTP connections are made

Description

public EventHttpConnection::setLocalAddress ( string $address ) : void

Sets the IP address from which http connections are made.

Parameters

address

The IP address from which HTTP connections are made.

Return Values

No value is returned.

See Also

  • EventHttpConnection::setLocalPort() - Sets the local port from which connections are made


Sets the local port from which connections are made

  • « EventHttpConnection::setLocalAddress
  • EventHttpConnection::setMaxBodySize »
  • PHP Manual
  • EventHttpConnection
  • Sets the local port from which connections are made

EventHttpConnection::setLocalPort

(PECL event >= 1.2.6-beta)

EventHttpConnection::setLocalPort — Sets the local port from which connections are made

Description

public EventHttpConnection::setLocalPort ( int $port ) : void

Sets the local port from which connections are made.

Parameters

port

The port number.

Return Values

See Also

  • EventHttpConnection::setLocalAddress() - Sets the IP address from which HTTP connections are made


Sets maximum body size for the connection

  • « EventHttpConnection::setLocalPort
  • EventHttpConnection::setMaxHeadersSize »
  • PHP Manual
  • EventHttpConnection
  • Sets maximum body size for the connection

EventHttpConnection::setMaxBodySize

(PECL event >= 1.2.6-beta)

EventHttpConnection::setMaxBodySize — Sets maximum body size for the connection

Description

public EventHttpConnection::setMaxBodySize ( string $max_size ) : void

Sets maximum body size for the connection.

Parameters

max_size

The maximum body size in bytes.

Return Values

No value is returned.

See Also

  • EventHttpConnection::setMaxHeadersSize() - Sets maximum header size


Sets maximum header size

  • « EventHttpConnection::setMaxBodySize
  • EventHttpConnection::setRetries »
  • PHP Manual
  • EventHttpConnection
  • Sets maximum header size

EventHttpConnection::setMaxHeadersSize

(PECL event >= 1.2.6-beta)

EventHttpConnection::setMaxHeadersSize — Sets maximum header size

Description

public EventHttpConnection::setMaxHeadersSize ( string $max_size ) : void

Sets maximum header size for the connection.

Parameters

max_size

The maximum header size in bytes.

Return Values

No value is returned.

See Also

  • EventHttpConnection::setMaxBodySize() - Sets maximum body size for the connection


Sets the retry limit for the connection

  • « EventHttpConnection::setMaxHeadersSize
  • EventHttpConnection::setTimeout »
  • PHP Manual
  • EventHttpConnection
  • Sets the retry limit for the connection

EventHttpConnection::setRetries

(PECL event >= 1.2.6-beta)

EventHttpConnection::setRetries — Sets the retry limit for the connection

Description

public EventHttpConnection::setRetries ( int $retries ) : void

Sets the retry limit for the connection

Parameters

retries

The retry limit. -1 means infinity.

Return Values

No value is returned.


Sets the timeout for the connection

  • « EventHttpConnection::setRetries
  • EventHttpRequest »
  • PHP Manual
  • EventHttpConnection
  • Sets the timeout for the connection

EventHttpConnection::setTimeout

(PECL event >= 1.2.6-beta)

EventHttpConnection::setTimeout — Sets the timeout for the connection

Description

public EventHttpConnection::setTimeout ( int $timeout ) : void

Sets the timeout for the connection

Parameters

timeout

Timeout in seconds.

Return Values

No value is returned.


The EventHttpRequest class

(PECL event >= 1.4.0-beta)

Introduction

Represents an HTTP request.

Class synopsis

EventHttpRequest {
/* Constants */
const integer CMD_GET = 1 ;
const integer CMD_POST = 2 ;
const integer CMD_HEAD = 4 ;
const integer CMD_PUT = 8 ;
const integer CMD_DELETE = 16 ;
const integer CMD_OPTIONS = 32 ;
const integer CMD_TRACE = 64 ;
const integer CMD_CONNECT = 128 ;
const integer CMD_PATCH = 256 ;
const integer INPUT_HEADER = 1 ;
const integer OUTPUT_HEADER = 2 ;
/* Methods */
public addHeader ( string $key , string $value , int $type ) : bool
public cancel ( void ) : void
public clearHeaders ( void ) : void
public closeConnection ( void ) : void
public __construct ( callable $callback [, mixed $data = NULL ] )
public findHeader ( string $key , string $type ) : void
public free ( void ) : void
public closeConnection ( void ) : EventBufferEvent
public getCommand ( void ) : void
public closeConnection ( void ) : EventHttpConnection
public getHost ( void ) : string
public getInputBuffer ( void ) : EventBuffer
public getInputHeaders ( void ) : array
public getOutputBuffer ( void ) : EventBuffer
public getOutputHeaders ( void ) : void
public getResponseCode ( void ) : int
public getUri ( void ) : string
public removeHeader ( string $key , string $type ) : void
public sendError ( int $error [, string $reason = NULL ] ) : void
public sendReply ( int $code , string $reason [, EventBuffer $buf ] ) : void
public sendReplyChunk ( EventBuffer $buf ) : void
public sendReplyEnd ( void ) : void
public sendReplyStart ( int $code , string $reason ) : void
}

Predefined Constants

EventHttpRequest::CMD_GET

GET method(command)

EventHttpRequest::CMD_POST

POST method(command)

EventHttpRequest::CMD_HEAD

HEAD method(command)

EventHttpRequest::CMD_PUT

PUT method(command)

EventHttpRequest::CMD_DELETE

DELETE command(method)

EventHttpRequest::CMD_OPTIONS

OPTIONS method(command)

EventHttpRequest::CMD_TRACE

TRACE method(command)

EventHttpRequest::CMD_CONNECT

CONNECT method(command)

EventHttpRequest::CMD_PATCH

PATCH method(command)

EventHttpRequest::INPUT_HEADER

Request input header type.

EventHttpRequest::OUTPUT_HEADER

Request output header type.

Table of Contents

  • EventHttpRequest::addHeader — Adds an HTTP header to the headers of the request
  • EventHttpRequest::cancel — Cancels a pending HTTP request
  • EventHttpRequest::clearHeaders — Removes all output headers from the header list of the request
  • EventHttpRequest::closeConnection — Closes associated HTTP connection
  • EventHttpRequest::__construct — Constructs EventHttpRequest object
  • EventHttpRequest::findHeader — Finds the value belonging a header
  • EventHttpRequest::free — Frees the object and removes associated events
  • EventHttpRequest::getBufferEvent — Returns EventBufferEvent object
  • EventHttpRequest::getCommand — Returns the request command(method)
  • EventHttpRequest::getConnection — Returns EventHttpConnection object
  • EventHttpRequest::getHost — Returns the request host
  • EventHttpRequest::getInputBuffer — Returns the input buffer
  • EventHttpRequest::getInputHeaders — Returns associative array of the input headers
  • EventHttpRequest::getOutputBuffer — Returns the output buffer of the request
  • EventHttpRequest::getOutputHeaders — Returns associative array of the output headers
  • EventHttpRequest::getResponseCode — Returns the response code
  • EventHttpRequest::getUri — Returns the request URI
  • EventHttpRequest::removeHeader — Removes an HTTP header from the headers of the request
  • EventHttpRequest::sendError — Send an HTML error message to the client
  • EventHttpRequest::sendReply — Send an HTML reply to the client
  • EventHttpRequest::sendReplyChunk — Send another data chunk as part of an ongoing chunked reply
  • EventHttpRequest::sendReplyEnd — Complete a chunked reply, freeing the request as appropriate
  • EventHttpRequest::sendReplyStart — Initiate a chunked reply


Adds an HTTP header to the headers of the request

  • « EventHttpRequest
  • EventHttpRequest::cancel »
  • PHP Manual
  • EventHttpRequest
  • Adds an HTTP header to the headers of the request

EventHttpRequest::addHeader

(PECL event >= 1.4.0-beta)

EventHttpRequest::addHeader — Adds an HTTP header to the headers of the request

Description

public EventHttpRequest::addHeader ( string $key , string $value , int $type ) : bool

Adds an HTTP header to the headers of the request.

Parameters

key

Header name.

value

Header value.

type

One of EventHttpRequest::*_HEADER constants .

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventHttpRequest::removeHeader() - Removes an HTTP header from the headers of the request


Cancels a pending HTTP request

  • « EventHttpRequest::addHeader
  • EventHttpRequest::clearHeaders »
  • PHP Manual
  • EventHttpRequest
  • Cancels a pending HTTP request

EventHttpRequest::cancel

(PECL event >= 1.4.0-beta)

EventHttpRequest::cancel — Cancels a pending HTTP request

Description

public EventHttpRequest::cancel ( void ) : void

Cancels a pending HTTP request.

Cancels an ongoing HTTP request. The callback associated with this request is not executed and the request object is freed. If the request is currently being processed, e.g. it is ongoing, the corresponding EventHttpConnection object is going to get reset.

A request cannot be canceled if its callback has executed already. A request may be canceled reentrantly from its chunked callback.

Parameters

This function has no parameters.

Return Values

No value is returned.


Removes all output headers from the header list of the request

  • « EventHttpRequest::cancel
  • EventHttpRequest::closeConnection »
  • PHP Manual
  • EventHttpRequest
  • Removes all output headers from the header list of the request

EventHttpRequest::clearHeaders

(PECL event >= 1.4.0-beta)

EventHttpRequest::clearHeaders — Removes all output headers from the header list of the request

Description

public EventHttpRequest::clearHeaders ( void ) : void

Removes all output headers from the header list of the request.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • EventHttpRequest::addHeader() - Adds an HTTP header to the headers of the request


Closes associated HTTP connection

  • « EventHttpRequest::clearHeaders
  • EventHttpRequest::__construct »
  • PHP Manual
  • EventHttpRequest
  • Closes associated HTTP connection

EventHttpRequest::closeConnection

(PECL event >= 1.8.0)

EventHttpRequest::closeConnection — Closes associated HTTP connection

Description

public EventHttpRequest::closeConnection ( void ) : void

Closes HTTP connection associated with the request.

Parameters

This function has no parameters.

Return Values

No value is returned.


Constructs EventHttpRequest object

  • « EventHttpRequest::closeConnection
  • EventHttpRequest::findHeader »
  • PHP Manual
  • EventHttpRequest
  • Constructs EventHttpRequest object

EventHttpRequest::__construct

(PECL event >= 1.4.0-beta)

EventHttpRequest::__construct — Constructs EventHttpRequest object

Description

public EventHttpRequest::__construct ( callable $callback [, mixed $data = NULL ] )

Constructs EventHttpRequest object.

Parameters

callback

Gets invoked on requesting path. Should match the following prototype:

callback ([ EventHttpRequest $req = NULL [, mixed $arg = NULL ]] ) : void
data

User custom data passed to the callback.

Return Values

Returns EventHttpRequest object.

Examples

Example #1 EventHttpRequest::__construct() example

<?php

function _request_handler($req, $base) {
    echo __FUNCTION__, PHP_EOL;

    if (is_null($req)) {
        echo "Timed out\n";
    } else {
        $response_code = $req->getResponseCode();

        if ($response_code == 0) {
            echo "Connection refused\n";
        } elseif ($response_code != 200) {
            echo "Unexpected response: $response_code\n";
        } else {
            echo "Success: $response_code\n";
            $buf = $req->getInputBuffer();
            echo "Body:\n";
            while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
                echo $s, PHP_EOL;
            }
        }
    }

    $base->exit(NULL);
}

$address = "127.0.0.1";
$port = 80;

$base = new EventBase();
$conn = new EventHttpConnection($base, NULL, $address, $port);
$conn->setTimeout(5);
$req = new EventHttpRequest("_request_handler", $base);

$req->addHeader("Host", $address, EventHttpRequest::OUTPUT_HEADER);
$req->addHeader("Content-Length", "0", EventHttpRequest::OUTPUT_HEADER);
$conn->makeRequest($req, EventHttpRequest::CMD_GET, "/index.cphp");

$base->loop();
?>

See Also

  • EventHttpRequest::cancel() - Cancels a pending HTTP request
  • EventHttpRequest::addHeader() - Adds an HTTP header to the headers of the request


Finds the value belonging a header

  • « EventHttpRequest::__construct
  • EventHttpRequest::free »
  • PHP Manual
  • EventHttpRequest
  • Finds the value belonging a header

EventHttpRequest::findHeader

(PECL event >= 1.4.0-beta)

EventHttpRequest::findHeader — Finds the value belonging a header

Description

public EventHttpRequest::findHeader ( string $key , string $type ) : void

Finds the value belonging a header.

Parameters

key

The header name.

type

One of EventHttpRequest::*_HEADER constants .

Return Values

Returns NULL if header not found.

See Also

  • EventHttpRequest::addHeader() - Adds an HTTP header to the headers of the request


Frees the object and removes associated events

  • « EventHttpRequest::findHeader
  • EventHttpRequest::getBufferEvent »
  • PHP Manual
  • EventHttpRequest
  • Frees the object and removes associated events

EventHttpRequest::free

(PECL event >= 1.4.0-beta)

EventHttpRequest::free — Frees the object and removes associated events

Description

public EventHttpRequest::free ( void ) : void

Frees the object and removes associated events.

Parameters

This function has no parameters.

Return Values

No value is returned.


Returns EventBufferEvent object

  • « EventHttpRequest::free
  • EventHttpRequest::getCommand »
  • PHP Manual
  • EventHttpRequest
  • Returns EventBufferEvent object

EventHttpRequest::getBufferEvent

(PECL event >= 1.8.0)

EventHttpRequest::getBufferEvent — Returns EventBufferEvent object

Description

public EventHttpRequest::closeConnection ( void ) : EventBufferEvent

Returns EventBufferEvent object which represents buffer event that the connection is using.

Warning

The reference counter of the returned object will be incremented by one to protect internal structures against premature destruction when the method is called from a user callback. So the EventBufferEvent object should be freed explicitly with EventBufferEvent::free() method. Otherwise memory will leak.

Parameters

This function has no parameters.

Return Values

Returns EventBufferEvent object.

See Also

  • EventHttpRequest::getConnection() - Returns EventHttpConnection object


Returns the request command(method)

  • « EventHttpRequest::getBufferEvent
  • EventHttpRequest::getConnection »
  • PHP Manual
  • EventHttpRequest
  • Returns the request command(method)

EventHttpRequest::getCommand

(PECL event >= 1.4.0-beta)

EventHttpRequest::getCommand — Returns the request command(method)

Description

public EventHttpRequest::getCommand ( void ) : void

Returns the request command, one of EventHttpRequest::CMD_* constants.

Parameters

This function has no parameters.

Return Values

Returns the request command, one of EventHttpRequest::CMD_* constants.


Returns EventHttpConnection object

  • « EventHttpRequest::getCommand
  • EventHttpRequest::getHost »
  • PHP Manual
  • EventHttpRequest
  • Returns EventHttpConnection object

EventHttpRequest::getConnection

(PECL event >= 1.8.0)

EventHttpRequest::getConnection — Returns EventHttpConnection object

Description

public EventHttpRequest::closeConnection ( void ) : EventHttpConnection

Returns EventHttpConnection object which represents HTTP connection associated with the request.

Warning

Libevent API allows HTTP request objects to be not bound to any HTTP connection. Therefore we can't unambiguously associate EventHttpRequest with EventHttpConnection . Thus, we construct EventHttpConnection object on-the-fly. Having no information about the event base, DNS base and connection-close callback, we just leave these fields unset.

EventHttpRequest::getConnection() method is usually useful when we need to set up a callback on connection close. See EventHttpConnection::setCloseCallback() .

Parameters

This function has no parameters.

Return Values

Returns EventHttpConnection object.

See Also

  • EventHttpConnection::setCloseCallback() - Set callback for connection close
  • EventHttpRequest::getBufferEvent() - Returns EventBufferEvent object


Returns the request host

  • « EventHttpRequest::getConnection
  • EventHttpRequest::getInputBuffer »
  • PHP Manual
  • EventHttpRequest
  • Returns the request host

EventHttpRequest::getHost

(PECL event >= 1.4.0-beta)

EventHttpRequest::getHost — Returns the request host

Description

public EventHttpRequest::getHost ( void ) : string

Returns the request host.

Parameters

This function has no parameters.

Return Values

Returns the request host.

See Also

  • EventHttpRequest::getUri() - Returns the request URI
  • EventHttpRequest::getCommand() - Returns the request command(method)


Returns the input buffer

  • « EventHttpRequest::getHost
  • EventHttpRequest::getInputHeaders »
  • PHP Manual
  • EventHttpRequest
  • Returns the input buffer

EventHttpRequest::getInputBuffer

(PECL event >= 1.4.0-beta)

EventHttpRequest::getInputBuffer — Returns the input buffer

Description

public EventHttpRequest::getInputBuffer ( void ) : EventBuffer

Returns the input buffer.

Parameters

This function has no parameters.

Return Values

Returns the input buffer.

See Also

  • EventHttpRequest::getOutputBuffer() - Returns the output buffer of the request


Returns associative array of the input headers

  • « EventHttpRequest::getInputBuffer
  • EventHttpRequest::getOutputBuffer »
  • PHP Manual
  • EventHttpRequest
  • Returns associative array of the input headers

EventHttpRequest::getInputHeaders

(PECL event >= 1.4.0-beta)

EventHttpRequest::getInputHeaders — Returns associative array of the input headers

Description

public EventHttpRequest::getInputHeaders ( void ) : array

Returns associative array of the input headers.

Parameters

This function has no parameters.

Return Values

Returns associative array of the input headers.

See Also

  • EventHttpRequest::getOutputHeaders() - Returns associative array of the output headers


Returns the output buffer of the request

  • « EventHttpRequest::getInputHeaders
  • EventHttpRequest::getOutputHeaders »
  • PHP Manual
  • EventHttpRequest
  • Returns the output buffer of the request

EventHttpRequest::getOutputBuffer

(PECL event >= 1.4.0-beta)

EventHttpRequest::getOutputBuffer — Returns the output buffer of the request

Description

public EventHttpRequest::getOutputBuffer ( void ) : EventBuffer

Returns the output buffer of the request.

Parameters

This function has no parameters.

Return Values

Returns the output buffer of the request.

See Also

  • EventHttpRequest::getInputBuffer() - Returns the input buffer


Returns associative array of the output headers

  • « EventHttpRequest::getOutputBuffer
  • EventHttpRequest::getResponseCode »
  • PHP Manual
  • EventHttpRequest
  • Returns associative array of the output headers

EventHttpRequest::getOutputHeaders

(PECL event >= 1.4.0-beta)

EventHttpRequest::getOutputHeaders — Returns associative array of the output headers

Description

public EventHttpRequest::getOutputHeaders ( void ) : void

Returns associative array of the output headers.

Parameters

This function has no parameters.

Return Values

See Also

  • EventHttpRequest::getInputHeaders() - Returns associative array of the input headers


Returns the response code

  • « EventHttpRequest::getOutputHeaders
  • EventHttpRequest::getUri »
  • PHP Manual
  • EventHttpRequest
  • Returns the response code

EventHttpRequest::getResponseCode

(PECL event >= 1.4.0-beta)

EventHttpRequest::getResponseCode — Returns the response code

Description

public EventHttpRequest::getResponseCode ( void ) : int

Returns the response code.

Parameters

This function has no parameters.

Return Values

Returns the response code of the request.

See Also

  • EventHttpRequest::getCommand() - Returns the request command(method)
  • EventHttpRequest::getHost() - Returns the request host
  • EventHttpRequest::getUri() - Returns the request URI


Returns the request URI

  • « EventHttpRequest::getResponseCode
  • EventHttpRequest::removeHeader »
  • PHP Manual
  • EventHttpRequest
  • Returns the request URI

EventHttpRequest::getUri

(PECL event >= 1.4.0-beta)

EventHttpRequest::getUri — Returns the request URI

Description

public EventHttpRequest::getUri ( void ) : string

Returns the request URI

Parameters

This function has no parameters.

Return Values

Returns the request URI

See Also

  • EventHttpRequest::getCommand() - Returns the request command(method)
  • EventHttpRequest::getHost() - Returns the request host
  • EventHttpRequest::getResponseCode() - Returns the response code


Removes an HTTP header from the headers of the request

  • « EventHttpRequest::getUri
  • EventHttpRequest::sendError »
  • PHP Manual
  • EventHttpRequest
  • Removes an HTTP header from the headers of the request

EventHttpRequest::removeHeader

(PECL event >= 1.4.0-beta)

EventHttpRequest::removeHeader — Removes an HTTP header from the headers of the request

Description

public EventHttpRequest::removeHeader ( string $key , string $type ) : void

Removes an HTTP header from the headers of the request.

Parameters

key

The header name.

type

type is one of EventHttpRequest::*_HEADER constants.

Return Values

Removes an HTTP header from the headers of the request.

See Also

  • EventHttpRequest::addHeader() - Adds an HTTP header to the headers of the request


Send an HTML error message to the client

  • « EventHttpRequest::removeHeader
  • EventHttpRequest::sendReply »
  • PHP Manual
  • EventHttpRequest
  • Send an HTML error message to the client

EventHttpRequest::sendError

(PECL event >= 1.4.0-beta)

EventHttpRequest::sendError — Send an HTML error message to the client

Description

public EventHttpRequest::sendError ( int $error [, string $reason = NULL ] ) : void

Send an HTML error message to the client.

Parameters

error

The HTTP error code.

reason

A brief explanation ofthe error. If NULL, the standard meaning of the error code will be used.

Return Values

No value is returned.

Examples

Example #1 EventHttpRequest::sendError() example

<?php
function _http_400($req) {
    $req->sendError(400);
}

$base = new EventBase();
$http = new EventHttp($base);

$http->setCallback("/err400", "_http_400");

$http->bind("0.0.0.0", 8010);
$base->loop();
?>

See Also

  • EventHttpRequest::sendReply() - Send an HTML reply to the client


Send an HTML reply to the client

  • « EventHttpRequest::sendError
  • EventHttpRequest::sendReplyChunk »
  • PHP Manual
  • EventHttpRequest
  • Send an HTML reply to the client

EventHttpRequest::sendReply

(PECL event >= 1.4.0-beta)

EventHttpRequest::sendReply — Send an HTML reply to the client

Description

public EventHttpRequest::sendReply ( int $code , string $reason [, EventBuffer $buf ] ) : void

Send an HTML reply to the client. The body of the reply consists of data in optional buf parameter.

Parameters

code

The HTTP response code to send.

reason

A brief message to send with the response code.

buf

The body of the response.

Return Values

No value is returned.

See Also

  • EventHttpRequest::sendError() - Send an HTML error message to the client
  • EventHttpRequest::sendReplyChunk() - Send another data chunk as part of an ongoing chunked reply


Send another data chunk as part of an ongoing chunked reply

  • « EventHttpRequest::sendReply
  • EventHttpRequest::sendReplyEnd »
  • PHP Manual
  • EventHttpRequest
  • Send another data chunk as part of an ongoing chunked reply

EventHttpRequest::sendReplyChunk

(PECL event >= 1.4.0-beta)

EventHttpRequest::sendReplyChunk — Send another data chunk as part of an ongoing chunked reply

Description

public EventHttpRequest::sendReplyChunk ( EventBuffer $buf ) : void

Send another data chunk as part of an ongoing chunked reply. After calling this method buf will be empty.

Parameters

buf

The data chunk to send as part of the reply.

Return Values

No value is returned.

See Also

  • EventHttpRequest::sendReplyStart() - Initiate a chunked reply
  • EventHttpRequest::sendReplyEnd() - Complete a chunked reply, freeing the request as appropriate


Complete a chunked reply, freeing the request as appropriate

  • « EventHttpRequest::sendReplyChunk
  • EventHttpRequest::sendReplyStart »
  • PHP Manual
  • EventHttpRequest
  • Complete a chunked reply, freeing the request as appropriate

EventHttpRequest::sendReplyEnd

(PECL event >= 1.4.0-beta)

EventHttpRequest::sendReplyEnd — Complete a chunked reply, freeing the request as appropriate

Description

public EventHttpRequest::sendReplyEnd ( void ) : void

Complete a chunked reply, freeing the request as appropriate.

Parameters

This function has no parameters.

Return Values

No value is returned.

See Also

  • EventHttpRequest::sendReplyStart() - Initiate a chunked reply
  • EventHttpRequest::sendReplyChunk() - Send another data chunk as part of an ongoing chunked reply


Initiate a chunked reply

  • « EventHttpRequest::sendReplyEnd
  • EventListener »
  • PHP Manual
  • EventHttpRequest
  • Initiate a chunked reply

EventHttpRequest::sendReplyStart

(PECL event >= 1.4.0-beta)

EventHttpRequest::sendReplyStart — Initiate a chunked reply

Description

public EventHttpRequest::sendReplyStart ( int $code , string $reason ) : void

Initiate a reply that uses Transfer-Encoding chunked .

This allows the caller to stream the reply back to the client and is useful when either not all of the reply data is immediately available or when sending very large replies.

The caller needs to supply data chunks with EventHttpRequest::sendReplyChunk() and complete the reply by calling EventHttpRequest::sendReplyEnd() .

Parameters

code

The HTTP response code to send.

reason

A brief message to send with the response code.

Return Values

No value is returned.

See Also

  • EventHttpRequest::sendReplyChunk() - Send another data chunk as part of an ongoing chunked reply
  • EventHttpRequest::sendReplyEnd() - Complete a chunked reply, freeing the request as appropriate


The EventListener class

(PECL event >= 1.5.0)

Introduction

Represents a connection listener.

Class synopsis

final EventListener {
/* Constants */
const integer OPT_LEAVE_SOCKETS_BLOCKING = 1 ;
const integer OPT_CLOSE_ON_FREE = 2 ;
const integer OPT_CLOSE_ON_EXEC = 4 ;
const integer OPT_REUSEABLE = 8 ;
const integer OPT_THREADSAFE = 16 ;
/* Properties */
public readonly int $fd ;
/* Methods */
public __construct ( EventBase $base , callable $cb , mixed $data , int $flags , int $backlog , mixed $target )
public disable ( void ) : bool
public enable ( void ) : bool
public getBase ( void ) : void
public static getSocketName ( string &$address [, mixed &$port ] ) : bool
public setCallback ( callable $cb [, mixed $arg = NULL ] ) : void
public setErrorCallback ( string $cb ) : void
}

Properties

fd

Numeric file descriptor of the underlying socket. (Added in event-1.6.0 .)

Predefined Constants

EventListener::OPT_LEAVE_SOCKETS_BLOCKING

By default Libevent turns underlying file descriptors, or sockets, to non-blocking mode. This flag tells Libevent to leave them in blocking mode.

EventListener::OPT_CLOSE_ON_FREE

If this option is set, the connection listener closes its underlying socket when the EventListener object is freed.

EventListener::OPT_CLOSE_ON_EXEC

If this option is set, the connection listener sets the close-on-exec flag on the underlying listener socket. See platform documentation for fcntl and FD_CLOEXEC for more information.

EventListener::OPT_REUSEABLE

By default on some platforms, once a listener socket is closed, no other socket can bind to the same port until a while has passed. Setting this option makes Libevent mark the socket as reusable, so that once it is closed, another socket can be opened to listen on the same port.

EventListener::OPT_THREADSAFE

Allocate locks for the listener, so that it’s safe to use it from multiple threads.

Table of Contents

  • EventListener::__construct — Creates new connection listener associated with an event base
  • EventListener::disable — Disables an event connect listener object
  • EventListener::enable — Enables an event connect listener object
  • EventListener::getBase — Returns event base associated with the event listener
  • EventListener::getSocketName — Retreives the current address to which the listener's socket is bound
  • EventListener::setCallback — The setCallback purpose
  • EventListener::setErrorCallback — Set event listener's error callback


Creates new connection listener associated with an event base

  • « EventListener
  • EventListener::disable »
  • PHP Manual
  • EventListener
  • Creates new connection listener associated with an event base

EventListener::__construct

(PECL event >= 1.2.6-beta)

EventListener::__construct — Creates new connection listener associated with an event base

Description

public EventListener::__construct ( EventBase $base , callable $cb , mixed $data , int $flags , int $backlog , mixed $target )

Creates new connection listener associated with an event base.

Parameters

base

Associated event base.

cb

A callable that will be invoked when new connection received.

data

Custom user data attached to cb .

flags

Bit mask of EventListener::OPT_* constants. See EventListener constants .

backlog

Controls the maximum number of pending connections that the network stack should allow to wait in a not-yet-accepted state at any time; see documentation for your system’s listen function for more details. If backlog is negative, Libevent tries to pick a good value for the backlog ; if it is zero, Event assumes that listen is already called on the socket( target )

target

May be string, socket resource, or a stream associated with a socket. In case if target is a string, the string will be parsed as network address. It will be interpreted as a UNIX domain socket path, if prefixed with 'unix:' , e.g. 'unix:/tmp/my.sock' .

Return Values

Returns EventListener object representing the event connection listener.

Changelog

Version | Description
1.5.0 | UNIX domain sockets' support added.

Examples

Example #1 EventListener::__construct() example

<?php
/*
 * Simple echo server based on libevent's connection listener.
 *
 * Usage:
 * 1) In one terminal window run:
 *
 * $ php listener.php 9881
 *
 * 2) In another terminal window open up connection, e.g.:
 *
 * $ nc 127.0.0.1 9881
 *
 * 3) start typing. The server should repeat the input.
 */

class MyListenerConnection {
    private $bev, $base;

    public function __destruct() {
        $this->bev->free();
    }

    public function __construct($base, $fd) {
        $this->base = $base;

        $this->bev = new EventBufferEvent($base, $fd, EventBufferEvent::OPT_CLOSE_ON_FREE);

        $this->bev->setCallbacks(array($this, "echoReadCallback"), NULL,
            array($this, "echoEventCallback"), NULL);

        if (!$this->bev->enable(Event::READ)) {
            echo "Failed to enable READ\n";
            return;
        }
    }

    public function echoReadCallback($bev, $ctx) {
        // Copy all the data from the input buffer to the output buffer

        // Variant #1
        $bev->output->addBuffer($bev->input);

        /* Variant #2 */
        /*
        $input    = $bev->getInput();
        $output = $bev->getOutput();
        $output->addBuffer($input);
        */
    }

    public function echoEventCallback($bev, $events, $ctx) {
        if ($events & EventBufferEvent::ERROR) {
            echo "Error from bufferevent\n";
        }

        if ($events & (EventBufferEvent::EOF | EventBufferEvent::ERROR)) {
            //$bev->free();
            $this->__destruct();
        }
    }
}

class MyListener {
    public $base,
        $listener,
        $socket;
    private $conn = array();

    public function __destruct() {
        foreach ($this->conn as &$c) $c = NULL;
    }

    public function __construct($port) {
        $this->base = new EventBase();
        if (!$this->base) {
            echo "Couldn't open event base";
            exit(1);
        }

        // Variant #1
        /*
        $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        if (!socket_bind($this->socket, '0.0.0.0', $port)) {
            echo "Unable to bind socket\n";
            exit(1);
        }
        $this->listener = new EventListener($this->base,
            array($this, "acceptConnCallback"), $this->base,
            EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE,
            -1, $this->socket);
         */

        // Variant #2
         $this->listener = new EventListener($this->base,
             array($this, "acceptConnCallback"), $this->base,
             EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE, -1,
             "0.0.0.0:$port");

        if (!$this->listener) {
            echo "Couldn't create listener";
            exit(1);
        }

        $this->listener->setErrorCallback(array($this, "accept_error_cb"));
    }

    public function dispatch() {
        $this->base->dispatch();
    }

    // This callback is invoked when there is data to read on $bev
    public function acceptConnCallback($listener, $fd, $address, $ctx) {
        // We got a new connection! Set up a bufferevent for it. */
        $base = $this->base;
        $this->conn[] = new MyListenerConnection($base, $fd);
    }

    public function accept_error_cb($listener, $ctx) {
        $base = $this->base;

        fprintf(STDERR, "Got an error %d (%s) on the listener. "
            ."Shutting down.\n",
            EventUtil::getLastSocketErrno(),
            EventUtil::getLastSocketError());

        $base->exit(NULL);
    }
}

$port = 9808;

if ($argc > 1) {
    $port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
    exit("Invalid port");
}

$l = new MyListener($port);
$l->dispatch();
?>


Disables an event connect listener object

  • « EventListener::__construct
  • EventListener::enable »
  • PHP Manual
  • EventListener
  • Disables an event connect listener object

EventListener::disable

(PECL event >= 1.2.6-beta)

EventListener::disable — Disables an event connect listener object

Description

public EventListener::disable ( void ) : bool

Disables an event connect listener object

Parameters

This function has no parameters.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventListener::enable() - Enables an event connect listener object


Enables an event connect listener object

  • « EventListener::disable
  • EventListener::getBase »
  • PHP Manual
  • EventListener
  • Enables an event connect listener object

EventListener::enable

(PECL event >= 1.2.6-beta)

EventListener::enable — Enables an event connect listener object

Description

public EventListener::enable ( void ) : bool

Enables an event connect listener object

Parameters

This function has no parameters.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • EventListener::disable() - Disables an event connect listener object


Returns event base associated with the event listener

  • « EventListener::enable
  • EventListener::getSocketName »
  • PHP Manual
  • EventListener
  • Returns event base associated with the event listener

EventListener::getBase

(PECL event >= 1.2.6-beta)

EventListener::getBase — Returns event base associated with the event listener

Description

public EventListener::getBase ( void ) : void

Returns event base associated with the event listener.

Parameters

This function has no parameters.

Return Values

Returns event base associated with the event listener.


Retreives the current address to which the listener's socket is bound

  • « EventListener::getBase
  • EventListener::setCallback »
  • PHP Manual
  • EventListener
  • Retreives the current address to which the listener's socket is bound

EventListener::getSocketName

(PECL event >= 1.5.0)

EventListener::getSocketName — Retreives the current address to which the listener's socket is bound

Description

public static EventListener::getSocketName ( string &$address [, mixed &$port ] ) : bool

Retreives the current address to which the listener's socket is bound.

Parameters

address

Output parameter. IP-address depending on the socket address family.

port

Output parameter. The port the socket is bound to.

Return Values

Returns TRUE on success. Otherwise FALSE.


The setCallback purpose

  • « EventListener::getSocketName
  • EventListener::setErrorCallback »
  • PHP Manual
  • EventListener
  • The setCallback purpose

EventListener::setCallback

(PECL event >= 1.2.6-beta)

EventListener::setCallback — The setCallback purpose

Description

public EventListener::setCallback ( callable $cb [, mixed $arg = NULL ] ) : void

Adjust event connect listener's callback and optionally the callback argument.

Parameters

cb

The new callback for new connections. Ignored if NULL.

Should match the following prototype:

callback ([ EventListener $listener = NULL [, mixed $fd = NULL [, array $address = NULL [, mixed $arg = NULL ]]]] ) : void

listener

The EventListener object.

fd

The file descriptor or a resource associated with the listener.

address

Array of two elements: IP address and the server port.

arg

User custom data attached to the callback.

arg

Custom user data attached to the callback. Ignored if NULL.

Return Values

No value is returned.


Set event listener's error callback

  • « EventListener::setCallback
  • EventSslContext »
  • PHP Manual
  • EventListener
  • Set event listener's error callback

EventListener::setErrorCallback

(PECL event >= 1.2.6-beta)

EventListener::setErrorCallback — Set event listener's error callback

Description

public EventListener::setErrorCallback ( string $cb ) : void

Set event listener's error callback

Parameters

cb

The error callback. Should match the following prototype:

callback ([ EventListener $listener = NULL [, mixed $data = NULL ]] ) : void

listener

The EventListener object.

data

User custom data attached to the callback.

Return Values

See Also

  • EventListener::setCallback() - The setCallback purpose


The EventSslContext class

(PECL event >= 1.2.6-beta)

Introduction

Represents SSL_CTX structure. Provides methods and properties to configure the SSL context.

Class synopsis

final EventSslContext {
/* Constants */
const integer SSLv2_CLIENT_METHOD = 1 ;
const integer SSLv3_CLIENT_METHOD = 2 ;
const integer SSLv23_CLIENT_METHOD = 3 ;
const integer TLS_CLIENT_METHOD = 4 ;
const integer SSLv2_SERVER_METHOD = 5 ;
const integer SSLv3_SERVER_METHOD = 6 ;
const integer SSLv23_SERVER_METHOD = 7 ;
const integer TLS_SERVER_METHOD = 8 ;
const integer OPT_LOCAL_CERT = 1 ;
const integer OPT_LOCAL_PK = 2 ;
const integer OPT_PASSPHRASE = 3 ;
const integer OPT_CA_FILE = 4 ;
const integer OPT_CA_PATH = 5 ;
const integer OPT_ALLOW_SELF_SIGNED = 6 ;
const integer OPT_VERIFY_PEER = 7 ;
const integer OPT_VERIFY_DEPTH = 8 ;
const integer OPT_CIPHERS = 9 ;
/* Properties */
public string $local_cert ;
public string $local_pk ;
/* Methods */
public __construct ( string $method , string $options )
}

Properties

local_cert

Path to local certificate file on filesystem. It must be a PEM-encoded file which contains certificate. It can optionally contain the certificate chain of issuers.

local_pk

Path to local private key file

Predefined Constants

EventSslContext::SSLv2_CLIENT_METHOD

SSLv2 client method. See SSL_CTX_new(3) man page.

EventSslContext::SSLv3_CLIENT_METHOD

SSLv3 client method. See SSL_CTX_new(3) man page.

EventSslContext::SSLv23_CLIENT_METHOD

SSLv23 client method. See SSL_CTX_new(3) man page.

EventSslContext::TLS_CLIENT_METHOD

TLS client method. See SSL_CTX_new(3) man page.

EventSslContext::SSLv2_SERVER_METHOD

SSLv2 server method. See SSL_CTX_new(3) man page.

EventSslContext::SSLv3_SERVER_METHOD

SSLv3 server method. See SSL_CTX_new(3) man page.

EventSslContext::SSLv23_SERVER_METHOD

SSLv23 server method. See SSL_CTX_new(3) man page.

EventSslContext::TLS_SERVER_METHOD

TLS server method. See SSL_CTX_new(3) man page.

EventSslContext::OPT_LOCAL_CERT

Key for an item of the options' array used in EventSslContext::__construct() . The option points to path of local certificate.

EventSslContext::OPT_LOCAL_PK

Key for an item of the options' array used in EventSslContext::__construct() . The option points to path of the private key.

EventSslContext::OPT_PASSPHRASE

Key for an item of the options' array used in EventSslContext::__construct() . Represents passphrase of the certificate.

EventSslContext::OPT_CA_FILE

Key for an item of the options' array used in EventSslContext::__construct() . Represents path of the certificate authority file.

EventSslContext::OPT_CA_PATH

Key for an item of the options' array used in EventSslContext::__construct() . Represents path where the certificate authority file should be searched for.

EventSslContext::OPT_ALLOW_SELF_SIGNED

Key for an item of the options' array used in EventSslContext::__construct() . Represents option that allows self-signed certificates.

EventSslContext::OPT_VERIFY_PEER

Key for an item of the options' array used in EventSslContext::__construct() . Represents option that tells Event to verify peer.

EventSslContext::OPT_VERIFY_DEPTH

Key for an item of the options' array used in EventSslContext::__construct() . Represents maximum depth for the certificate chain verification that shall be allowed for the SSL context.

EventSslContext::OPT_CIPHERS

Key for an item of the options' array used in EventSslContext::__construct() . Represents the cipher list for the SSL context.

Table of Contents

  • EventSslContext::__construct — Constructs an OpenSSL context for use with Event classes


Constructs an OpenSSL context for use with Event classes

  • « EventSslContext
  • EventUtil »
  • PHP Manual
  • EventSslContext
  • Constructs an OpenSSL context for use with Event classes

EventSslContext::__construct

(PECL event >= 1.2.6-beta)

EventSslContext::__construct — Constructs an OpenSSL context for use with Event classes

Description

public EventSslContext::__construct ( string $method , string $options )

Creates SSL context holding pointer to SSL_CTX (see the system manual).

Parameters

method

One of EventSslContext::*_METHOD constants .

options

Associative array of SSL context options One of EventSslContext::OPT_* constants .

Return Values

Returns EventSslContext object.

Examples

Example #1 EventSslContext::__construct() example

<?php
$ctx = new EventSslContext(EventSslContext::SSLv3_SERVER_METHOD, array(
     EventSslContext::OPT_LOCAL_CERT        => $local_cert,
     EventSslContext::OPT_LOCAL_PK          => $local_pk,
     EventSslContext::OPT_PASSPHRASE        => "echo server",
     EventSslContext::OPT_VERIFY_PEER       => true,
     EventSslContext::OPT_ALLOW_SELF_SIGNED => false,
));
?>


The EventUtil class

(PECL event >= 1.5.0)

Introduction

EventUtil is a singleton with supplimentary methods and constants.

Class synopsis

final EventUtil {
/* Constants */
const integer AF_INET = 2 ;
const integer AF_INET6 = 10 ;
const integer AF_UNSPEC = 0 ;
const integer LIBEVENT_VERSION_NUMBER = 33559808 ;
const integer SO_DEBUG = 1 ;
const integer SO_REUSEADDR = 2 ;
const integer SO_KEEPALIVE = 9 ;
const integer SO_DONTROUTE = 5 ;
const integer SO_LINGER = 13 ;
const integer SO_BROADCAST = 6 ;
const integer SO_OOBINLINE = 10 ;
const integer SO_SNDBUF = 7 ;
const integer SO_RCVBUF = 8 ;
const integer SO_SNDLOWAT = 19 ;
const integer SO_RCVLOWAT = 18 ;
const integer SO_SNDTIMEO = 21 ;
const integer SO_RCVTIMEO = 20 ;
const integer SO_TYPE = 3 ;
const integer SO_ERROR = 4 ;
const integer SOL_SOCKET = 1 ;
const integer SOL_TCP = 6 ;
const integer SOL_UDP = 17 ;
const integer IPPROTO_IP = 0 ;
const integer IPPROTO_IPV6 = 41 ;
/* Methods */
abstract public __construct ( void )
public static getLastSocketErrno ([ mixed $socket = NULL ] ) : int
public static getLastSocketError ([ mixed $socket ] ) : string
public static getSocketFd ( mixed $socket ) : int
public static getSocketName ( mixed $socket , string &$address [, mixed &$port ] ) : bool
public static setSocketOption ( mixed $socket , int $level , int $optname , mixed $optval ) : bool
public static sslRandPoll ( void ) : void
}

Predefined Constants

EventUtil::AF_INET

IPv4 address family

EventUtil::AF_INET6

IPv6 address family

EventUtil::AF_UNSPEC

Unspecified IP address family

EventUtil::SO_DEBUG

Socket option. Enable socket debugging. Only allowed for processes with the CAP_NET_ADMIN capability or an effective user ID of 0 . (Added in event-1.6.0.)

EventUtil::SO_REUSEADDR

Socket option. Indicates that the rules used in validating addresses supplied in a bind(2) call should allow reuse of local addresses. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_KEEPALIVE

Socket option. Enable sending of keep-alive messages on connection-oriented sockets. Expects an integer boolean flag. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_DONTROUTE

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_LINGER

Socket option. When enabled, a close(2) or shutdown(2) will not return until all queued messages for the socket have been successfully sent or the linger timeout has been reached. Otherwise, the call returns immediately and the closing is done in the background. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_BROADCAST

Socket option. Reports whether transmission of broadcast messages is supported. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_OOBINLINE

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_SNDBUF

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_RCVBUF

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_SNDLOWAT

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_RCVLOWAT

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_SNDTIMEO

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_RCVTIMEO

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_TYPE

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_ERROR

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SOL_SOCKET

Socket option level. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SOL_TCP

Socket option level. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SOL_UDP

Socket option level. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::IPPROTO_IP

See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::IPPROTO_IPV6

See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::LIBEVENT_VERSION_NUMBER

Libevent' version number at the time when Event extension had been compiled with the library.

Table of Contents

  • EventUtil::__construct — The abstract constructor
  • EventUtil::getLastSocketErrno — Returns the most recent socket error number
  • EventUtil::getLastSocketError — Returns the most recent socket error
  • EventUtil::getSocketFd — Returns numeric file descriptor of a socket, or stream
  • EventUtil::getSocketName — Retreives the current address to which the socket is bound
  • EventUtil::setSocketOption — Sets socket options
  • EventUtil::sslRandPoll — Generates entropy by means of OpenSSL's RAND_poll()


The abstract constructor

  • « EventUtil
  • EventUtil::getLastSocketErrno »
  • PHP Manual
  • EventUtil
  • The abstract constructor

EventUtil::__construct

(PECL event >= 1.2.6-beta)

EventUtil::__construct — The abstract constructor

Description

abstract public EventUtil::__construct ( void )

EventUtil is a singleton. Therefore the constructor is abstract, and it is impossible to create objects based on this class.

Parameters

This function has no parameters.

Return Values

No value is returned.


Returns the most recent socket error number

  • « EventUtil::__construct
  • EventUtil::getLastSocketError »
  • PHP Manual
  • EventUtil
  • Returns the most recent socket error number

EventUtil::getLastSocketErrno

(PECL event >= 1.2.6-beta)

EventUtil::getLastSocketErrno — Returns the most recent socket error number

Description

public static EventUtil::getLastSocketErrno ([ mixed $socket = NULL ] ) : int

Returns the most recent socket error number( errno ).

Parameters

socket

Socket resource, stream or a file descriptor of a socket.

Return Values

Returns the most recent socket error number( errno ).

See Also

  • EventUtil::getLastSocketError() - Returns the most recent socket error


Returns the most recent socket error

  • « EventUtil::getLastSocketErrno
  • EventUtil::getSocketFd »
  • PHP Manual
  • EventUtil
  • Returns the most recent socket error

EventUtil::getLastSocketError

(PECL event >= 1.2.6-beta)

EventUtil::getLastSocketError — Returns the most recent socket error

Description

public static EventUtil::getLastSocketError ([ mixed $socket ] ) : string

Returns the most recent socket error.

Parameters

socket

Socket resource, stream or a file descriptor of a socket.

Return Values

Returns the most recent socket error.

See Also

  • EventUtil::getLastSocketErrno() - Returns the most recent socket error number


Returns numeric file descriptor of a socket, or stream

  • « EventUtil::getLastSocketError
  • EventUtil::getSocketName »
  • PHP Manual
  • EventUtil
  • Returns numeric file descriptor of a socket, or stream

EventUtil::getSocketFd

(PECL event >= 1.7.0)

EventUtil::getSocketFd — Returns numeric file descriptor of a socket, or stream

Description

public static EventUtil::getSocketFd ( mixed $socket ) : int

Returns numeric file descriptor of a socket or stream specified by socket argument just like the Event extension does it internally for all methods accepting socket resource or stream.

Parameters

socket

Socket resource or stream.

Return Values

Returns numeric file descriptor of a socket, or stream. EventUtil::getSocketFd() returns FALSE in case if it is whether failed to recognize the type of the underlying file, or detected that the file descriptor associated with socket is not valid.


Retreives the current address to which the socket is bound

  • « EventUtil::getSocketFd
  • EventUtil::setSocketOption »
  • PHP Manual
  • EventUtil
  • Retreives the current address to which the socket is bound

EventUtil::getSocketName

(PECL event >= 1.5.0)

EventUtil::getSocketName — Retreives the current address to which the socket is bound

Description

public static EventUtil::getSocketName ( mixed $socket , string &$address [, mixed &$port ] ) : bool

Retreives the current address to which the socket is bound.

Parameters

socket

Socket resource, stream or a file descriptor of a socket.

address

Output parameter. IP-address, or the UNIX domain socket path depending on the socket address family.

port

Output parameter. The port the socket is bound to. Has no meaning for UNIX domain sockets.

Return Values

Returns TRUE on success. Otherwise FALSE.


Sets socket options

  • « EventUtil::getSocketName
  • EventUtil::sslRandPoll »
  • PHP Manual
  • EventUtil
  • Sets socket options

EventUtil::setSocketOption

(PECL event >= 1.6.0)

EventUtil::setSocketOption — Sets socket options

Description

public static EventUtil::setSocketOption ( mixed $socket , int $level , int $optname , mixed $optval ) : bool

Sets socket options.

Parameters

socket

Socket resource, stream, or numeric file descriptor associated with the socket.

level

One of EventUtil::SOL_* constants. Specifies the protocol level at which the option resides. For example, to retrieve options at the socket level, a level parameter of EventUtil::SOL_SOCKET would be used. Other levels, such as TCP, can be used by specifying the protocol number of that level. Protocol numbers can be found by using the getprotobyname() function. See EventUtil constants .

optname

Option name(type). Has the same meaning as corresponding parameter of socket_get_option() function. See EventUtil constants .

optval

Accepts the same values as optval parameter of the socket_get_option() function.

Return Values

Returns TRUE on success. Otherwise FALSE.

See Also

  • socket_get_option() - Gets socket options for the socket
  • socket_set_option() - Sets socket options for the socket


Generates entropy by means of OpenSSL's RAND_poll()

  • « EventUtil::setSocketOption
  • FAM »
  • PHP Manual
  • EventUtil
  • Generates entropy by means of OpenSSL's RAND_poll()

EventUtil::sslRandPoll

(PECL event >= 1.2.6-beta)

EventUtil::sslRandPoll — Generates entropy by means of OpenSSL's RAND_poll()

Description

public static EventUtil::sslRandPoll ( void ) : void

Generates entropy by means of OpenSSL's RAND_poll() (see the system manual).

Parameters

This function has no parameters.

Return Values

No value is returned.


File Alteration Monitor

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • FAM Functions
    • fam_cancel_monitor — Terminate monitoring
    • fam_close — Close FAM connection
    • fam_monitor_collection — Monitor a collection of files in a directory for changes
    • fam_monitor_directory — Monitor a directory for changes
    • fam_monitor_file — Monitor a regular file for changes
    • fam_next_event — Get next pending FAM event
    • fam_open — Open connection to FAM daemon
    • fam_pending — Check for pending FAM events
    • fam_resume_monitor — Resume suspended monitoring
    • fam_suspend_monitor — Temporarily suspend monitoring


Introduction

FAM monitors files and directories, notifying interested applications of changes. More information about FAM is available at » https://web.archive.org/web/20050827202326/http://oss.sgi.com:80/projects/fam/.

A PHP script may specify a list of files for FAM to monitor using the functions provided by this extension.

The FAM process is started when the first connection from any application to it is opened. It exits after all connections to it have been closed.

Note:

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.1.0.

Note: This extension is not available on Windows platforms.


Requirements

This extension uses the functions of the » FAM library, developed by SGI. Therefore you have to download and install the FAM library.


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/fam.

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.1.0


Resource Types

There are two resource types used in the FAM module. The first one is the connection to the FAM service returned by fam_open(), the second a monitoring resource returned by the fam_monitor_XXX functions.


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.

FAM event constants
Constant | Description
FAMChanged (integer) | Some value which can be obtained with fstat(1) changed for a file or directory.
FAMDeleted (integer) | A file or directory was deleted or renamed.
FAMStartExecuting (integer) | An executable file started executing.
FAMStopExecuting (integer) | An executable file that was running finished.
FAMCreated (integer) | A file was created in a directory.
FAMMoved (integer) | This event never occurs.
FAMAcknowledge (integer) | An event in response to fam_cancel_monitor().
FAMExists (integer) | An event upon request to monitor a file or directory. When a directory is monitored, an event for that directory and every file contained in that directory is issued.
FAMEndExist (integer) | Event after the last FAMEExists event.


FAM Functions

Table of Contents

  • fam_cancel_monitor — Terminate monitoring
  • fam_close — Close FAM connection
  • fam_monitor_collection — Monitor a collection of files in a directory for changes
  • fam_monitor_directory — Monitor a directory for changes
  • fam_monitor_file — Monitor a regular file for changes
  • fam_next_event — Get next pending FAM event
  • fam_open — Open connection to FAM daemon
  • fam_pending — Check for pending FAM events
  • fam_resume_monitor — Resume suspended monitoring
  • fam_suspend_monitor — Temporarily suspend monitoring


Terminate monitoring

  • « FAM Functions
  • fam_close »
  • PHP Manual
  • FAM Functions
  • Terminate monitoring

fam_cancel_monitor

(PHP 5 < 5.1.0)

fam_cancel_monitor — Terminate monitoring

Description

fam_cancel_monitor ( resource $fam , resource $fam_monitor ) : bool

Terminates monitoring on a resource.

In addition an FAMAcknowledge event occurs.

Parameters

fam

A resource representing a connection to the FAM service returned by fam_open()

fam_monitor

A resource returned by one of the fam_monitor_XXX functions

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fam_monitor_file() - Monitor a regular file for changes
  • fam_monitor_directory() - Monitor a directory for changes
  • fam_monitor_collection() - Monitor a collection of files in a directory for changes
  • fam_suspend_monitor() - Temporarily suspend monitoring


Close FAM connection

  • « fam_cancel_monitor
  • fam_monitor_collection »
  • PHP Manual
  • FAM Functions
  • Close FAM connection

fam_close

(PHP 5 < 5.1.0)

fam_close — Close FAM connection

Description

fam_close ( resource $fam ) : void

Closes a connection to the FAM service.

Parameters

fam

A resource representing a connection to the FAM service returned by fam_open()

Return Values

No value is returned.

See Also

  • fam_monitor_open()


Monitor a collection of files in a directory for changes

  • « fam_close
  • fam_monitor_directory »
  • PHP Manual
  • FAM Functions
  • Monitor a collection of files in a directory for changes

fam_monitor_collection

(PHP 5 < 5.1.0)

fam_monitor_collection — Monitor a collection of files in a directory for changes

Description

fam_monitor_collection ( resource $fam , string $dirname , int $depth , string $mask ) : resource

Requests monitoring for a collection of files within a directory.

A FAM event will be generated whenever the status of the files change. The possible event codes are described in detail in the constants part of this section.

Parameters

fam

A resource representing a connection to the FAM service returned by fam_open()

dirname

Directory path to the monitored files

depth

The maximum search depth starting from this directory

mask

A shell pattern mask restricting the file names to look for

Return Values

Returns a monitoring resource or FALSE on errors.

See Also

  • fam_monitor_file() - Monitor a regular file for changes
  • fam_monitor_directory() - Monitor a directory for changes
  • fam_cancel_monitor() - Terminate monitoring
  • fam_suspend_monitor() - Temporarily suspend monitoring
  • fam_resume_monitor() - Resume suspended monitoring


Monitor a directory for changes

  • « fam_monitor_collection
  • fam_monitor_file »
  • PHP Manual
  • FAM Functions
  • Monitor a directory for changes

fam_monitor_directory

(PHP 5 < 5.1.0)

fam_monitor_directory — Monitor a directory for changes

Description

fam_monitor_directory ( resource $fam , string $dirname ) : resource

Requests monitoring for a directory and all contained files.

A FAM event will be generated whenever the status of the directory (i.e. the result of function stat() on that directory) or its content (i.e. the results of readdir()) changes.

The possible event codes are described in detail in the constants part of this section.

Parameters

fam

A resource representing a connection to the FAM service returned by fam_open()

dirname

Path to the monitored directory

Return Values

Returns a monitoring resource or FALSE on errors.

See Also

  • fam_monitor_file() - Monitor a regular file for changes
  • fam_monitor_collection() - Monitor a collection of files in a directory for changes
  • fam_cancel_monitor() - Terminate monitoring
  • fam_suspend_monitor() - Temporarily suspend monitoring
  • fam_resume_monitor() - Resume suspended monitoring


Monitor a regular file for changes

  • « fam_monitor_directory
  • fam_next_event »
  • PHP Manual
  • FAM Functions
  • Monitor a regular file for changes

fam_monitor_file

(PHP 5 < 5.1.0)

fam_monitor_file — Monitor a regular file for changes

Description

fam_monitor_file ( resource $fam , string $filename ) : resource

Requests monitoring for a single file. A FAM event will be generated whenever the file status changes (i.e. the result of function stat() on that file).

The possible event codes are described in detail in the constants part of this section.

Parameters

fam

A resource representing a connection to the FAM service returned by fam_open()

filename

Path to the monitored file

Return Values

Returns a monitoring resource or FALSE on errors.

See Also

  • fam_monitor_directory() - Monitor a directory for changes
  • fam_monitor_collection() - Monitor a collection of files in a directory for changes
  • fam_cancel_monitor() - Terminate monitoring
  • fam_suspend_monitor() - Temporarily suspend monitoring
  • fam_resume_monitor() - Resume suspended monitoring


Get next pending FAM event

  • « fam_monitor_file
  • fam_open »
  • PHP Manual
  • FAM Functions
  • Get next pending FAM event

fam_next_event

(PHP 5 < 5.1.0)

fam_next_event — Get next pending FAM event

Description

fam_next_event ( resource $fam ) : array

Returns the next pending FAM event.

The function will block until an event is available which can be checked for using fam_pending().

Parameters

fam

A resource representing a connection to the FAM service returned by fam_open()

Return Values

Returns an array that contains a FAM event code in the 'code' element, the path of the file this event applies to in the 'filename' element and optionally a hostname in the 'hostname' element.

The possible event codes are described in detail in the constants part of this section.

See Also

  • fam_pending() - Check for pending FAM events


Open connection to FAM daemon

  • « fam_next_event
  • fam_pending »
  • PHP Manual
  • FAM Functions
  • Open connection to FAM daemon

fam_open

(PHP 5 < 5.1.0)

fam_open — Open connection to FAM daemon

Description

fam_open ([ string $appname ] ) : resource

Opens a connection to the FAM service daemon.

Parameters

appname

A string identifying the application for logging reasons

Return Values

Returns a resource representing a connection to the FAM service on success or FALSE on errors.

See Also

  • fam_close() - Close FAM connection


Check for pending FAM events

  • « fam_open
  • fam_resume_monitor »
  • PHP Manual
  • FAM Functions
  • Check for pending FAM events

fam_pending

(PHP 5 < 5.1.0)

fam_pending — Check for pending FAM events

Description

fam_pending ( resource $fam ) : int

Checks for pending FAM events.

Parameters

fam

A resource representing a connection to the FAM service returned by fam_open()

Return Values

Returns non-zero if events are available to be fetched using fam_next_event(), zero otherwise.

See Also

  • fam_next_event() - Get next pending FAM event


Resume suspended monitoring

  • « fam_pending
  • fam_suspend_monitor »
  • PHP Manual
  • FAM Functions
  • Resume suspended monitoring

fam_resume_monitor

(PHP 5 < 5.1.0)

fam_resume_monitor — Resume suspended monitoring

Description

fam_resume_monitor ( resource $fam , resource $fam_monitor ) : bool

Resumes monitoring of a resource previously suspended using fam_suspend_monitor().

Parameters

fam

A resource representing a connection to the FAM service returned by fam_open()

fam_monitor

A resource returned by one of the fam_monitor_XXX functions

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fam_suspend_monitor() - Temporarily suspend monitoring


Temporarily suspend monitoring

  • « fam_resume_monitor
  • FTP »
  • PHP Manual
  • FAM Functions
  • Temporarily suspend monitoring

fam_suspend_monitor

(PHP 5 < 5.1.0)

fam_suspend_monitor — Temporarily suspend monitoring

Description

fam_suspend_monitor ( resource $fam , resource $fam_monitor ) : bool

fam_suspend_monitor() temporarily suspend monitoring of a resource.

Monitoring can later be continued using fam_resume_monitor() without the need of requesting a complete new monitor.

Parameters

fam

A resource representing a connection to the FAM service returned by fam_open()

fam_monitor

A resource returned by one of the fam_monitor_XXX functions

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • fam_cancel_monitor() - Terminate monitoring
  • fam_resume_monitor() - Resume suspended monitoring


FTP

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
  • FTP Functions
    • ftp_alloc — Allocates space for a file to be uploaded
    • ftp_append — Append the contents of a file to another file on the FTP server
    • ftp_cdup — Changes to the parent directory
    • ftp_chdir — Changes the current directory on a FTP server
    • ftp_chmod — Set permissions on a file via FTP
    • ftp_close — Closes an FTP connection
    • ftp_connect — Opens an FTP connection
    • ftp_delete — Deletes a file on the FTP server
    • ftp_exec — Requests execution of a command on the FTP server
    • ftp_fget — Downloads a file from the FTP server and saves to an open file
    • ftp_fput — Uploads from an open file to the FTP server
    • ftp_get_option — Retrieves various runtime behaviours of the current FTP stream
    • ftp_get — Downloads a file from the FTP server
    • ftp_login — Logs in to an FTP connection
    • ftp_mdtm — Returns the last modified time of the given file
    • ftp_mkdir — Creates a directory
    • ftp_mlsd — Returns a list of files in the given directory
    • ftp_nb_continue — Continues retrieving/sending a file (non-blocking)
    • ftp_nb_fget — Retrieves a file from the FTP server and writes it to an open file (non-blocking)
    • ftp_nb_fput — Stores a file from an open file to the FTP server (non-blocking)
    • ftp_nb_get — Retrieves a file from the FTP server and writes it to a local file (non-blocking)
    • ftp_nb_put — Stores a file on the FTP server (non-blocking)
    • ftp_nlist — Returns a list of files in the given directory
    • ftp_pasv — Turns passive mode on or off
    • ftp_put — Uploads a file to the FTP server
    • ftp_pwd — Returns the current directory name
    • ftp_quit — Alias of ftp_close
    • ftp_raw — Sends an arbitrary command to an FTP server
    • ftp_rawlist — Returns a detailed list of files in the given directory
    • ftp_rename — Renames a file or a directory on the FTP server
    • ftp_rmdir — Removes a directory
    • ftp_set_option — Set miscellaneous runtime FTP options
    • ftp_site — Sends a SITE command to the server
    • ftp_size — Returns the size of the given file
    • ftp_ssl_connect — Opens a Secure SSL-FTP connection
    • ftp_systype — Returns the system type identifier of the remote FTP server


Introduction

The functions in this extension implement client access to files servers speaking the File Transfer Protocol (FTP) as defined in » http://www.faqs.org/rfcs/rfc959. This extension is meant for detailed access to an FTP server providing a wide range of control to the executing script. If you only wish to read from or write to a file on an FTP server, consider using the ftp:// wrapper with the filesystem functions which provide a simpler and more intuitive interface.


Installation

In order to use FTP functions with your PHP configuration, you should add the --enable-ftp option when installing PHP.

The Windows version of PHP 5 has built-in support for this extension. You do not need to load any additional extensions in order to use these functions.

As of PHP 7.0.0 on Windows this extension is always built as shared extension and as such has to be enabled in php.ini.


Resource Types

This extension uses one resource type, which is the link identifier of the FTP connection, returned by ftp_connect() or ftp_ssl_connect().


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.

FTP_ASCII (integer)

FTP_AUTOSEEK (integer)

See ftp_set_option() for information.

FTP_AUTORESUME (integer)

Automatically determine resume position and start position for GET and PUT requests (only works if FTP_AUTOSEEK is enabled)

FTP_FAILED (integer)

Asynchronous transfer has failed

FTP_FINISHED (integer)

Asynchronous transfer has finished

FTP_MOREDATA (integer)

Asynchronous transfer is still active

FTP_TEXT (integer)

Alias of FTP_ASCII.

FTP_BINARY (integer)

FTP_IMAGE (integer)

Alias of FTP_BINARY.

FTP_TIMEOUT_SEC (integer)

See ftp_set_option() for information.

FTP_USEPASVADDRESS (bool)

See ftp_set_option() for information. Available as of PHP 5.6.0.


  • « Predefined Constants
  • Basic usage »
  • PHP Manual
  • FTP
  • Examples

Examples

Table of Contents

  • Basic usage


Basic usage

Example #1 FTP example

<?php
// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// check connection
if ((!$conn_id) || (!$login_result)) {
    echo "FTP connection has failed!";
    echo "Attempted to connect to $ftp_server for user $ftp_user_name";
    exit;
} else {
    echo "Connected to $ftp_server, for user $ftp_user_name";
}

// upload the file
$upload = ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY);

// check upload status
if (!$upload) {
    echo "FTP upload has failed!";
} else {
    echo "Uploaded $source_file to $ftp_server as $destination_file";
}

// close the FTP stream
ftp_close($conn_id);
?>


FTP Functions

Table of Contents

  • ftp_alloc — Allocates space for a file to be uploaded
  • ftp_append — Append the contents of a file to another file on the FTP server
  • ftp_cdup — Changes to the parent directory
  • ftp_chdir — Changes the current directory on a FTP server
  • ftp_chmod — Set permissions on a file via FTP
  • ftp_close — Closes an FTP connection
  • ftp_connect — Opens an FTP connection
  • ftp_delete — Deletes a file on the FTP server
  • ftp_exec — Requests execution of a command on the FTP server
  • ftp_fget — Downloads a file from the FTP server and saves to an open file
  • ftp_fput — Uploads from an open file to the FTP server
  • ftp_get_option — Retrieves various runtime behaviours of the current FTP stream
  • ftp_get — Downloads a file from the FTP server
  • ftp_login — Logs in to an FTP connection
  • ftp_mdtm — Returns the last modified time of the given file
  • ftp_mkdir — Creates a directory
  • ftp_mlsd — Returns a list of files in the given directory
  • ftp_nb_continue — Continues retrieving/sending a file (non-blocking)
  • ftp_nb_fget — Retrieves a file from the FTP server and writes it to an open file (non-blocking)
  • ftp_nb_fput — Stores a file from an open file to the FTP server (non-blocking)
  • ftp_nb_get — Retrieves a file from the FTP server and writes it to a local file (non-blocking)
  • ftp_nb_put — Stores a file on the FTP server (non-blocking)
  • ftp_nlist — Returns a list of files in the given directory
  • ftp_pasv — Turns passive mode on or off
  • ftp_put — Uploads a file to the FTP server
  • ftp_pwd — Returns the current directory name
  • ftp_quit — Alias of ftp_close
  • ftp_raw — Sends an arbitrary command to an FTP server
  • ftp_rawlist — Returns a detailed list of files in the given directory
  • ftp_rename — Renames a file or a directory on the FTP server
  • ftp_rmdir — Removes a directory
  • ftp_set_option — Set miscellaneous runtime FTP options
  • ftp_site — Sends a SITE command to the server
  • ftp_size — Returns the size of the given file
  • ftp_ssl_connect — Opens a Secure SSL-FTP connection
  • ftp_systype — Returns the system type identifier of the remote FTP server


Allocates space for a file to be uploaded

  • « FTP Functions
  • ftp_append »
  • PHP Manual
  • FTP Functions
  • Allocates space for a file to be uploaded

ftp_alloc

(PHP 5, PHP 7)

ftp_alloc — Allocates space for a file to be uploaded

Description

ftp_alloc ( resource $ftp_stream , int $filesize [, string &$result ] ) : bool

Sends an ALLO command to the remote FTP server to allocate space for a file to be uploaded.

Note:

Many FTP servers do not support this command. These servers may return a failure code (FALSE) indicating the command is not supported or a success code (TRUE) to indicate that pre-allocation is not necessary and the client should continue as though the operation were successful. Because of this, it may be best to reserve this function for servers which explicitly require preallocation.

Parameters

ftp_stream

The link identifier of the FTP connection.

filesize

The number of bytes to allocate.

result

A textual representation of the servers response will be returned by reference in result if a variable is provided.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ftp_alloc() example

<?php

$file = "/home/user/myfile";

// connect to the server
$conn_id = ftp_connect('ftp.example.com');
$login_result = ftp_login($conn_id, 'anonymous', 'user@example.com');

if (ftp_alloc($conn_id, filesize($file), $result)) {
  echo "Space successfully allocated on server.  Sending $file.\n";
  ftp_put($conn_id, '/incomming/myfile', $file, FTP_BINARY);
} else {
  echo "Unable to allocate space on server.  Server said: $result\n";
}

ftp_close($conn_id);

?>

See Also

  • ftp_put() - Uploads a file to the FTP server
  • ftp_fput() - Uploads from an open file to the FTP server


Append the contents of a file to another file on the FTP server

  • « ftp_alloc
  • ftp_cdup »
  • PHP Manual
  • FTP Functions
  • Append the contents of a file to another file on the FTP server

ftp_append

(PHP 7 >= 7.2.0)

ftp_append — Append the contents of a file to another file on the FTP server

Description

ftp_append ( resource $ftp , string $remote_file , string $local_file [, int $mode = FTP_BINARY ] ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

ftp

remote_file

local_file

mode

Return Values

Returns TRUE on success or FALSE on failure.


Changes to the parent directory

  • « ftp_append
  • ftp_chdir »
  • PHP Manual
  • FTP Functions
  • Changes to the parent directory

ftp_cdup

(PHP 4, PHP 5, PHP 7)

ftp_cdup — Changes to the parent directory

Description

ftp_cdup ( resource $ftp_stream ) : bool

Changes to the parent directory.

Parameters

ftp_stream

The link identifier of the FTP connection.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ftp_cdup() example

<?php
// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// change the current directory to html
ftp_chdir($conn_id, 'html');

echo ftp_pwd($conn_id); // /html

// return to the parent directory
if (ftp_cdup($conn_id)) {
  echo "cdup successful\n";
} else {
  echo "cdup not successful\n";
}

echo ftp_pwd($conn_id); // /

ftp_close($conn_id);
?>

See Also

  • ftp_chdir() - Changes the current directory on a FTP server
  • ftp_pwd() - Returns the current directory name


Changes the current directory on a FTP server

  • « ftp_cdup
  • ftp_chmod »
  • PHP Manual
  • FTP Functions
  • Changes the current directory on a FTP server

ftp_chdir

(PHP 4, PHP 5, PHP 7)

ftp_chdir — Changes the current directory on a FTP server

Description

ftp_chdir ( resource $ftp_stream , string $directory ) : bool

Changes the current directory to the specified one.

Parameters

ftp_stream

The link identifier of the FTP connection.

directory

The target directory.

Return Values

Returns TRUE on success or FALSE on failure. If changing directory fails, PHP will also throw a warning.

Examples

Example #1 ftp_chdir() example

<?php

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// check connection
if ((!$conn_id) || (!$login_result)) {
    die("FTP connection has failed !");
}

echo "Current directory: " . ftp_pwd($conn_id) . "\n";

// try to change the directory to somedir
if (ftp_chdir($conn_id, "somedir")) {
    echo "Current directory is now: " . ftp_pwd($conn_id) . "\n";
} else {
    echo "Couldn't change directory\n";
}

// close the connection
ftp_close($conn_id);
?>

See Also

  • ftp_cdup() - Changes to the parent directory
  • ftp_pwd() - Returns the current directory name


Set permissions on a file via FTP

  • « ftp_chdir
  • ftp_close »
  • PHP Manual
  • FTP Functions
  • Set permissions on a file via FTP

ftp_chmod

(PHP 5, PHP 7)

ftp_chmod — Set permissions on a file via FTP

Description

ftp_chmod ( resource $ftp_stream , int $mode , string $filename ) : int

Sets the permissions on the specified remote file to mode.

Parameters

ftp_stream

The link identifier of the FTP connection.

mode

The new permissions, given as an octal value.

filename

The remote file.

Return Values

Returns the new file permissions on success or FALSE on error.

Examples

Example #1 ftp_chmod() example

<?php
$file = 'public_html/index.php';

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// try to chmod $file to 644
if (ftp_chmod($conn_id, 0644, $file) !== false) {
 echo "$file chmoded successfully to 644\n";
} else {
 echo "could not chmod $file\n";
}

// close the connection
ftp_close($conn_id);
?>

See Also

  • chmod() - Changes file mode


Closes an FTP connection

  • « ftp_chmod
  • ftp_connect »
  • PHP Manual
  • FTP Functions
  • Closes an FTP connection

ftp_close

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

ftp_close — Closes an FTP connection

Description

ftp_close ( resource $ftp_stream ) : bool

ftp_close() closes the given link identifier and releases the resource.

Note:

After calling this function, you can no longer use the FTP connection and must create a new one with ftp_connect().

Parameters

ftp_stream

The link identifier of the FTP connection.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ftp_close() example

<?php

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// print the current directory
echo ftp_pwd($conn_id); // /

// close this connection
ftp_close($conn_id);
?>

See Also

  • ftp_connect() - Opens an FTP connection


Opens an FTP connection

  • « ftp_close
  • ftp_delete »
  • PHP Manual
  • FTP Functions
  • Opens an FTP connection

ftp_connect

(PHP 4, PHP 5, PHP 7)

ftp_connect — Opens an FTP connection

Description

ftp_connect ( string $host [, int $port = 21 [, int $timeout = 90 ]] ) : resource

ftp_connect() opens an FTP connection to the specified host.

Parameters

host

The FTP server address. This parameter shouldn't have any trailing slashes and shouldn't be prefixed with ftp://.

port

This parameter specifies an alternate port to connect to. If it is omitted or set to zero, then the default FTP port, 21, will be used.

timeout

This parameter specifies the timeout in seconds for all subsequent network operations. If omitted, the default value is 90 seconds. The timeout can be changed and queried at any time with ftp_set_option() and ftp_get_option().

Return Values

Returns a FTP stream on success or FALSE on error.

Examples

Example #1 ftp_connect() example

<?php

$ftp_server = "ftp.example.com";

// set up a connection or die
$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");

?>

See Also

  • ftp_close() - Closes an FTP connection
  • ftp_ssl_connect() - Opens a Secure SSL-FTP connection


Deletes a file on the FTP server

  • « ftp_connect
  • ftp_exec »
  • PHP Manual
  • FTP Functions
  • Deletes a file on the FTP server

ftp_delete

(PHP 4, PHP 5, PHP 7)

ftp_delete — Deletes a file on the FTP server

Description

ftp_delete ( resource $ftp_stream , string $path ) : bool

ftp_delete() deletes the file specified by path from the FTP server.

Parameters

ftp_stream

The link identifier of the FTP connection.

path

The file to delete.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ftp_delete() example

<?php
$file = 'public_html/old.txt';

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// try to delete $file
if (ftp_delete($conn_id, $file)) {
 echo "$file deleted successful\n";
} else {
 echo "could not delete $file\n";
}

// close the connection
ftp_close($conn_id);
?>


Requests execution of a command on the FTP server

  • « ftp_delete
  • ftp_fget »
  • PHP Manual
  • FTP Functions
  • Requests execution of a command on the FTP server

ftp_exec

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

ftp_exec — Requests execution of a command on the FTP server

Description

ftp_exec ( resource $ftp_stream , string $command ) : bool

Sends a SITE EXEC command request to the FTP server.

Parameters

ftp_stream

The link identifier of the FTP connection.

command

The command to execute.

Return Values

Returns TRUE if the command was successful (server sent response code: 200); otherwise returns FALSE.

Examples

Example #1 ftp_exec() example

<?php

// variable initialization
$command = 'ls -al >files.txt';

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// execute command
if (ftp_exec($conn_id, $command)) {
    echo "$command executed successfully\n";
} else {
    echo "could not execute $command\n";
}

// close the connection
ftp_close($conn_id);

?>

See Also

  • ftp_raw() - Sends an arbitrary command to an FTP server


Downloads a file from the FTP server and saves to an open file

  • « ftp_exec
  • ftp_fput »
  • PHP Manual
  • FTP Functions
  • Downloads a file from the FTP server and saves to an open file

ftp_fget

(PHP 4, PHP 5, PHP 7)

ftp_fget — Downloads a file from the FTP server and saves to an open file

Description

ftp_fget ( resource $ftp_stream , resource $handle , string $remote_file [, int $mode = FTP_BINARY [, int $resumepos = 0 ]] ) : bool

ftp_fget() retrieves remote_file from the FTP server, and writes it to the given file pointer.

Parameters

ftp_stream

The link identifier of the FTP connection.

handle

An open file pointer in which we store the data.

remote_file

The remote file path.

mode

The transfer mode. Must be either FTP_ASCII or FTP_BINARY.

resumepos

The position in the remote file to start downloading from.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.3.0 | The mode parameter is now optional. Formerly it has been mandatory.

Examples

Example #1 ftp_fget() example

<?php

// path to remote file
$remote_file = 'somefile.txt';
$local_file = 'localfile.txt';

// open some file to write to
$handle = fopen($local_file, 'w');

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// try to download $remote_file and save it to $handle
if (ftp_fget($conn_id, $handle, $remote_file, FTP_ASCII, 0)) {
 echo "successfully written to $local_file\n";
} else {
 echo "There was a problem while downloading $remote_file to $local_file\n";
}

// close the connection and the file handler
ftp_close($conn_id);
fclose($handle);
?>

See Also

  • ftp_get() - Downloads a file from the FTP server
  • ftp_nb_get() - Retrieves a file from the FTP server and writes it to a local file (non-blocking)
  • ftp_nb_fget() - Retrieves a file from the FTP server and writes it to an open file (non-blocking)


Uploads from an open file to the FTP server

  • « ftp_fget
  • ftp_get_option »
  • PHP Manual
  • FTP Functions
  • Uploads from an open file to the FTP server

ftp_fput

(PHP 4, PHP 5, PHP 7)

ftp_fput — Uploads from an open file to the FTP server

Description

ftp_fput ( resource $ftp_stream , string $remote_file , resource $handle [, int $mode = FTP_BINARY [, int $startpos = 0 ]] ) : bool

ftp_fput() uploads the data from a file pointer to a remote file on the FTP server.

Parameters

ftp_stream

The link identifier of the FTP connection.

remote_file

The remote file path.

handle

An open file pointer on the local file. Reading stops at end of file.

mode

The transfer mode. Must be either FTP_ASCII or FTP_BINARY.

startpos

The position in the remote file to start uploading to.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.3.0 | The mode parameter is now optional. Formerly it has been mandatory.

Examples

Example #1 ftp_fput() example

<?php

// open some file for reading
$file = 'somefile.txt';
$fp = fopen($file, 'r');

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// try to upload $file
if (ftp_fput($conn_id, $file, $fp, FTP_ASCII)) {
    echo "Successfully uploaded $file\n";
} else {
    echo "There was a problem while uploading $file\n";
}

// close the connection and the file handler
ftp_close($conn_id);
fclose($fp);

?>

See Also

  • ftp_put() - Uploads a file to the FTP server
  • ftp_nb_fput() - Stores a file from an open file to the FTP server (non-blocking)
  • ftp_nb_put() - Stores a file on the FTP server (non-blocking)


Retrieves various runtime behaviours of the current FTP stream

  • « ftp_fput
  • ftp_get »
  • PHP Manual
  • FTP Functions
  • Retrieves various runtime behaviours of the current FTP stream

ftp_get_option

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

ftp_get_option — Retrieves various runtime behaviours of the current FTP stream

Description

ftp_get_option ( resource $ftp_stream , int $option ) : mixed

This function returns the value for the requested option from the specified FTP connection.

Parameters

ftp_stream

The link identifier of the FTP connection.

option

Currently, the following options are supported:

Supported runtime FTP options
FTP_TIMEOUT_SEC | Returns the current timeout used for network related operations.
FTP_AUTOSEEK | Returns TRUE if this option is on, FALSE otherwise.

Return Values

Returns the value on success or FALSE if the given option is not supported. In the latter case, a warning message is also thrown.

Examples

Example #1 ftp_get_option() example

<?php
// Get the timeout of the given FTP stream
$timeout = ftp_get_option($conn_id, FTP_TIMEOUT_SEC);
?>

See Also

  • ftp_set_option() - Set miscellaneous runtime FTP options


Downloads a file from the FTP server

  • « ftp_get_option
  • ftp_login »
  • PHP Manual
  • FTP Functions
  • Downloads a file from the FTP server

ftp_get

(PHP 4, PHP 5, PHP 7)

ftp_get — Downloads a file from the FTP server

Description

ftp_get ( resource $ftp_stream , string $local_file , string $remote_file [, int $mode = FTP_BINARY [, int $resumepos = 0 ]] ) : bool

ftp_get() retrieves a remote file from the FTP server, and saves it into a local file.

Parameters

ftp_stream

The link identifier of the FTP connection.

local_file

The local file path (will be overwritten if the file already exists).

remote_file

The remote file path.

mode

The transfer mode. Must be either FTP_ASCII or FTP_BINARY.

resumepos

The position in the remote file to start downloading from.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.3.0 | The mode parameter is now optional. Formerly it has been mandatory.

Examples

Example #1 ftp_get() example

<?php

// define some variables
$local_file = 'local.zip';
$server_file = 'server.zip';

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// try to download $server_file and save to $local_file
if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
    echo "Successfully written to $local_file\n";
} else {
    echo "There was a problem\n";
}

// close the connection
ftp_close($conn_id);

?>

See Also

  • ftp_pasv() - Turns passive mode on or off
  • ftp_fget() - Downloads a file from the FTP server and saves to an open file
  • ftp_nb_get() - Retrieves a file from the FTP server and writes it to a local file (non-blocking)
  • ftp_nb_fget() - Retrieves a file from the FTP server and writes it to an open file (non-blocking)


Logs in to an FTP connection

  • « ftp_get
  • ftp_mdtm »
  • PHP Manual
  • FTP Functions
  • Logs in to an FTP connection

ftp_login

(PHP 4, PHP 5, PHP 7)

ftp_login — Logs in to an FTP connection

Description

ftp_login ( resource $ftp_stream , string $username , string $password ) : bool

Logs in to the given FTP stream.

Parameters

ftp_stream

The link identifier of the FTP connection.

username

The username (USER).

password

The password (PASS).

Return Values

Returns TRUE on success or FALSE on failure. If login fails, PHP will also throw a warning.

Examples

Example #1 ftp_login() example

<?php

$ftp_server = "ftp.example.com";
$ftp_user = "foo";
$ftp_pass = "bar";

// set up a connection or die
$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");

// try to login
if (@ftp_login($conn_id, $ftp_user, $ftp_pass)) {
    echo "Connected as $ftp_user@$ftp_server\n";
} else {
    echo "Couldn't connect as $ftp_user\n";
}

// close the connection
ftp_close($conn_id);
?>


Returns the last modified time of the given file

  • « ftp_login
  • ftp_mkdir »
  • PHP Manual
  • FTP Functions
  • Returns the last modified time of the given file

ftp_mdtm

(PHP 4, PHP 5, PHP 7)

ftp_mdtm — Returns the last modified time of the given file

Description

ftp_mdtm ( resource $ftp_stream , string $remote_file ) : int

ftp_mdtm() gets the last modified time for a remote file.

Note:

Not all servers support this feature!

Note:

ftp_mdtm() does not work with directories.

Parameters

ftp_stream

The link identifier of the FTP connection.

remote_file

The file from which to extract the last modification time.

Return Values

Returns the last modified time as a Unix timestamp on success, or -1 on error.

Examples

Example #1 ftp_mdtm() example

<?php

$file = 'somefile.txt';

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

//  get the last modified time
$buff = ftp_mdtm($conn_id, $file);

if ($buff != -1) {
    // somefile.txt was last modified on: March 26 2003 14:16:41.
    echo "$file was last modified on : " . date("F d Y H:i:s.", $buff);
} else {
    echo "Couldn't get mdtime";
}

// close the connection
ftp_close($conn_id);

?>


Creates a directory

  • « ftp_mdtm
  • ftp_mlsd »
  • PHP Manual
  • FTP Functions
  • Creates a directory

ftp_mkdir

(PHP 4, PHP 5, PHP 7)

ftp_mkdir — Creates a directory

Description

ftp_mkdir ( resource $ftp_stream , string $directory ) : string

Creates the specified directory on the FTP server.

Parameters

ftp_stream

The link identifier of the FTP connection.

directory

The name of the directory that will be created.

Return Values

Returns the newly created directory name on success or FALSE on error.

Examples

Example #1 ftp_mkdir() example

<?php

$dir = 'www';

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// try to create the directory $dir
if (ftp_mkdir($conn_id, $dir)) {
 echo "successfully created $dir\n";
} else {
 echo "There was a problem while creating $dir\n";
}

// close the connection
ftp_close($conn_id);
?>

See Also

  • ftp_rmdir() - Removes a directory


Returns a list of files in the given directory

  • « ftp_mkdir
  • ftp_nb_continue »
  • PHP Manual
  • FTP Functions
  • Returns a list of files in the given directory

ftp_mlsd

(PHP 7 >= 7.2.0)

ftp_mlsd — Returns a list of files in the given directory

Description

ftp_mlsd ( resource $ftp_stream , string $directory ) : array

Parameters

ftp_stream

The link identifier of the FTP connection.

directory

The directory to be listed.

Return Values

Returns an array of arrays with file infos from the specified directory on success or FALSE on error.

Examples

Example #1 ftp_mlsd() example

<?php

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// get contents of the current directory
$contents = ftp_mlsd($conn_id, ".");

// output $contents
var_dump($contents);

?>

The above example will output something similar to:

array(5) {
  [0]=>
  array(8) {
    ["name"]=>
    string(1) "."
    ["modify"]=>
    string(14) "20171212154511"
    ["perm"]=>
    string(7) "flcdmpe"
    ["type"]=>
    string(4) "cdir"
    ["unique"]=>
    string(11) "811U5740002"
    ["UNIX.group"]=>
    string(2) "33"
    ["UNIX.mode"]=>
    string(4) "0755"
    ["UNIX.owner"]=>
    string(2) "33"
  }
  [1]=>
  array(8) {
    ["name"]=>
    string(2) ".."
    ["modify"]=>
    string(14) "20171212154511"
    ["perm"]=>
    string(7) "flcdmpe"
    ["type"]=>
    string(4) "pdir"
    ["unique"]=>
    string(11) "811U5740002"
    ["UNIX.group"]=>
    string(2) "33"
    ["UNIX.mode"]=>
    string(4) "0755"
    ["UNIX.owner"]=>
    string(2) "33"
  }
  [2]=>
  array(8) {
    ["name"]=>
    string(11) "public_html"
    ["modify"]=>
    string(14) "20171211171525"
    ["perm"]=>
    string(7) "flcdmpe"
    ["type"]=>
    string(3) "dir"
    ["unique"]=>
    string(11) "811U5740525"
    ["UNIX.group"]=>
    string(2) "33"
    ["UNIX.mode"]=>
    string(4) "0755"
    ["UNIX.owner"]=>
    string(2) "33"
  }
  [3]=>
  array(8) {
    ["name"]=>
    string(10) "public_ftp"
    ["modify"]=>
    string(14) "20171211174536"
    ["perm"]=>
    string(7) "flcdmpe"
    ["type"]=>
    string(3) "dir"
    ["unique"]=>
    string(11) "811U57405EE"
    ["UNIX.group"]=>
    string(2) "33"
    ["UNIX.mode"]=>
    string(4) "0755"
    ["UNIX.owner"]=>
    string(2) "33"
  }
  [4]=>
  array(8) {
    ["name"]=>
    string(3) "www"
    ["modify"]=>
    string(14) "www"
    ["perm"]=>
    string(7) "flcdmpe"
    ["type"]=>
    string(3) "dir"
    ["unique"]=>
    string(11) "811U5740780"
    ["UNIX.group"]=>
    string(2) "33"
    ["UNIX.mode"]=>
    string(4) "0755"
    ["UNIX.owner"]=>
    string(2) "33"
  }
}

See Also

  • ftp_rawlist() - Returns a detailed list of files in the given directory
  • ftp_nlist() - Returns a list of files in the given directory


Continues retrieving/sending a file (non-blocking)

  • « ftp_mlsd
  • ftp_nb_fget »
  • PHP Manual
  • FTP Functions
  • Continues retrieving/sending a file (non-blocking)

ftp_nb_continue

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

ftp_nb_continue — Continues retrieving/sending a file (non-blocking)

Description

ftp_nb_continue ( resource $ftp_stream ) : int

Continues retrieving/sending a file non-blocking.

Parameters

ftp_stream

The link identifier of the FTP connection.

Return Values

Returns FTP_FAILED or FTP_FINISHED or FTP_MOREDATA.

Examples

Example #1 ftp_nb_continue() example

<?php

// Initate the download
$ret = ftp_nb_get($my_connection, "test", "README", FTP_BINARY);
while ($ret == FTP_MOREDATA) {

   // Continue downloading...
   $ret = ftp_nb_continue($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error downloading the file...";
   exit(1);
}
?>


Retrieves a file from the FTP server and writes it to an open file (non-blocking)

  • « ftp_nb_continue
  • ftp_nb_fput »
  • PHP Manual
  • FTP Functions
  • Retrieves a file from the FTP server and writes it to an open file (non-blocking)

ftp_nb_fget

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

ftp_nb_fget — Retrieves a file from the FTP server and writes it to an open file (non-blocking)

Description

ftp_nb_fget ( resource $ftp_stream , resource $handle , string $remote_file [, int $mode = FTP_BINARY [, int $resumepos = 0 ]] ) : int

ftp_nb_fget() retrieves a remote file from the FTP server.

The difference between this function and ftp_fget() is that this function retrieves the file asynchronously, so your program can perform other operations while the file is being downloaded.

Parameters

ftp_stream

The link identifier of the FTP connection.

handle

An open file pointer in which we store the data.

remote_file

The remote file path.

mode

The transfer mode. Must be either FTP_ASCII or FTP_BINARY.

resumepos

The position in the remote file to start downloading from.

Return Values

Returns FTP_FAILED or FTP_FINISHED or FTP_MOREDATA.

Changelog

Version | Description
7.3.0 | The mode parameter is now optional. Formerly it has been mandatory.

Examples

Example #1 ftp_nb_fget() example

<?php

// open some file for reading
$file = 'index.php';
$fp = fopen($file, 'w');

$conn_id = ftp_connect($ftp_server);

$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// Initate the download
$ret = ftp_nb_fget($conn_id, $fp, $file, FTP_BINARY);
while ($ret == FTP_MOREDATA) {

   // Do whatever you want
   echo ".";

   // Continue downloading...
   $ret = ftp_nb_continue($conn_id);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error downloading the file...";
   exit(1);
}

// close filepointer
fclose($fp);
?>

See Also

  • ftp_nb_get() - Retrieves a file from the FTP server and writes it to a local file (non-blocking)
  • ftp_nb_continue() - Continues retrieving/sending a file (non-blocking)
  • ftp_fget() - Downloads a file from the FTP server and saves to an open file
  • ftp_get() - Downloads a file from the FTP server


Stores a file from an open file to the FTP server (non-blocking)

  • « ftp_nb_fget
  • ftp_nb_get »
  • PHP Manual
  • FTP Functions
  • Stores a file from an open file to the FTP server (non-blocking)

ftp_nb_fput

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

ftp_nb_fput — Stores a file from an open file to the FTP server (non-blocking)

Description

ftp_nb_fput ( resource $ftp_stream , string $remote_file , resource $handle [, int $mode = FTP_BINARY [, int $startpos = 0 ]] ) : int

ftp_nb_fput() uploads the data from a file pointer to a remote file on the FTP server.

The difference between this function and the ftp_fput() is that this function uploads the file asynchronously, so your program can perform other operations while the file is being uploaded.

Parameters

ftp_stream

The link identifier of the FTP connection.

remote_file

The remote file path.

handle

An open file pointer on the local file. Reading stops at end of file.

mode

The transfer mode. Must be either FTP_ASCII or FTP_BINARY.

startpos

The position in the remote file to start uploading to.

Return Values

Returns FTP_FAILED or FTP_FINISHED or FTP_MOREDATA.

Changelog

Version | Description
7.3.0 | The mode parameter is now optional. Formerly it has been mandatory.

Examples

Example #1 ftp_nb_fput() example

<?php

$file = 'index.php';

$fp = fopen($file, 'r');

$conn_id = ftp_connect($ftp_server);

$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// Initate the upload
$ret = ftp_nb_fput($conn_id, $file, $fp, FTP_BINARY);
while ($ret == FTP_MOREDATA) {

   // Do whatever you want
   echo ".";

   // Continue upload...
   $ret = ftp_nb_continue($conn_id);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error uploading the file...";
   exit(1);
}

fclose($fp);
?>

See Also

  • ftp_nb_put() - Stores a file on the FTP server (non-blocking)
  • ftp_nb_continue() - Continues retrieving/sending a file (non-blocking)
  • ftp_put() - Uploads a file to the FTP server
  • ftp_fput() - Uploads from an open file to the FTP server


Retrieves a file from the FTP server and writes it to a local file (non-blocking)

  • « ftp_nb_fput
  • ftp_nb_put »
  • PHP Manual
  • FTP Functions
  • Retrieves a file from the FTP server and writes it to a local file (non-blocking)

ftp_nb_get

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

ftp_nb_get — Retrieves a file from the FTP server and writes it to a local file (non-blocking)

Description

ftp_nb_get ( resource $ftp_stream , string $local_file , string $remote_file [, int $mode = FTP_BINARY [, int $resumepos = 0 ]] ) : int

ftp_nb_get() retrieves a remote file from the FTP server, and saves it into a local file.

The difference between this function and ftp_get() is that this function retrieves the file asynchronously, so your program can perform other operations while the file is being downloaded.

Parameters

ftp_stream

The link identifier of the FTP connection.

local_file

The local file path (will be overwritten if the file already exists).

remote_file

The remote file path.

mode

The transfer mode. Must be either FTP_ASCII or FTP_BINARY.

resumepos

The position in the remote file to start downloading from.

Return Values

Returns FTP_FAILED or FTP_FINISHED or FTP_MOREDATA.

Changelog

Version | Description
7.3.0 | The mode parameter is now optional. Formerly it has been mandatory.

Examples

Example #1 ftp_nb_get() example

<?php

// Initate the download
$ret = ftp_nb_get($my_connection, "test", "README", FTP_BINARY);
while ($ret == FTP_MOREDATA) {

   // Do whatever you want
   echo ".";

   // Continue downloading...
   $ret = ftp_nb_continue($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error downloading the file...";
   exit(1);
}
?>

Example #2 Resuming a download with ftp_nb_get()

<?php

// Initate
$ret = ftp_nb_get($my_connection, "test", "README", FTP_BINARY,
                      filesize("test"));
// OR: $ret = ftp_nb_get($my_connection, "test", "README",
//                           FTP_BINARY, FTP_AUTORESUME);
while ($ret == FTP_MOREDATA) {

   // Do whatever you want
   echo ".";

   // Continue downloading...
   $ret = ftp_nb_continue($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error downloading the file...";
   exit(1);
}
?>

Example #3 Resuming a download at position 100 to a new file with ftp_nb_get()

<?php

// Disable Autoseek
ftp_set_option($my_connection, FTP_AUTOSEEK, false);

// Initiate
$ret = ftp_nb_get($my_connection, "newfile", "README", FTP_BINARY, 100);
while ($ret == FTP_MOREDATA) {

   /* ... */

   // Continue downloading...
   $ret = ftp_nb_continue($my_connection);
}
?>

In the example above, newfile is 100 bytes smaller than README on the FTP server because we started reading at offset 100. If we didn't disable FTP_AUTOSEEK, the first 100 bytes of newfile would be '\0'.

See Also

  • ftp_nb_fget() - Retrieves a file from the FTP server and writes it to an open file (non-blocking)
  • ftp_nb_continue() - Continues retrieving/sending a file (non-blocking)
  • ftp_fget() - Downloads a file from the FTP server and saves to an open file
  • ftp_get() - Downloads a file from the FTP server


Stores a file on the FTP server (non-blocking)

  • « ftp_nb_get
  • ftp_nlist »
  • PHP Manual
  • FTP Functions
  • Stores a file on the FTP server (non-blocking)

ftp_nb_put

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

ftp_nb_put — Stores a file on the FTP server (non-blocking)

Description

ftp_nb_put ( resource $ftp_stream , string $remote_file , string $local_file [, int $mode = FTP_BINARY [, int $startpos = 0 ]] ) : int

ftp_nb_put() stores a local file on the FTP server.

The difference between this function and the ftp_put() is that this function uploads the file asynchronously, so your program can perform other operations while the file is being uploaded.

Parameters

ftp_stream

The link identifier of the FTP connection.

remote_file

The remote file path.

local_file

The local file path.

mode

The transfer mode. Must be either FTP_ASCII or FTP_BINARY.

startpos

The position in the remote file to start uploading to.

Return Values

Returns FTP_FAILED or FTP_FINISHED or FTP_MOREDATA.

Changelog

Version | Description
7.3.0 | The mode parameter is now optional. Formerly it has been mandatory.

Examples

Example #1 ftp_nb_put() example

<?php

// Initiate the Upload
$ret = ftp_nb_put($my_connection, "test.remote", "test.local", FTP_BINARY);
while ($ret == FTP_MOREDATA) {

   // Do whatever you want
   echo ".";

   // Continue uploading...
   $ret = ftp_nb_continue($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error uploading the file...";
   exit(1);
}
?>

Example #2 Resuming an upload with ftp_nb_put()

<?php

// Initiate
$ret = ftp_nb_put($my_connection, "test.remote", "test.local",
                      FTP_BINARY, ftp_size("test.remote"));
// OR: $ret = ftp_nb_put($my_connection, "test.remote", "test.local",
//                           FTP_BINARY, FTP_AUTORESUME);

while ($ret == FTP_MOREDATA) {

   // Do whatever you want
   echo ".";

   // Continue uploading...
   $ret = ftp_nb_continue($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error uploading the file...";
   exit(1);
}
?>

See Also

  • ftp_nb_fput() - Stores a file from an open file to the FTP server (non-blocking)
  • ftp_nb_continue() - Continues retrieving/sending a file (non-blocking)
  • ftp_put() - Uploads a file to the FTP server
  • ftp_fput() - Uploads from an open file to the FTP server


Returns a list of files in the given directory

  • « ftp_nb_put
  • ftp_pasv »
  • PHP Manual
  • FTP Functions
  • Returns a list of files in the given directory

ftp_nlist

(PHP 4, PHP 5, PHP 7)

ftp_nlist — Returns a list of files in the given directory

Description

ftp_nlist ( resource $ftp_stream , string $directory ) : array

Parameters

ftp_stream

The link identifier of the FTP connection.

directory

The directory to be listed. This parameter can also include arguments, eg. ftp_nlist($conn_id, "-la /your/dir"); Note that this parameter isn't escaped so there may be some issues with filenames containing spaces and other characters.

Return Values

Returns an array of filenames from the specified directory on success or FALSE on error.

Examples

Example #1 ftp_nlist() example

<?php

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// get contents of the current directory
$contents = ftp_nlist($conn_id, ".");

// output $contents
var_dump($contents);

?>

The above example will output something similar to:

array(3) {
  [0]=>
  string(11) "public_html"
  [1]=>
  string(10) "public_ftp"
  [2]=>
  string(3) "www"

See Also

  • ftp_rawlist() - Returns a detailed list of files in the given directory
  • ftp_mlsd() - Returns a list of files in the given directory


Turns passive mode on or off

  • « ftp_nlist
  • ftp_put »
  • PHP Manual
  • FTP Functions
  • Turns passive mode on or off

ftp_pasv

(PHP 4, PHP 5, PHP 7)

ftp_pasv — Turns passive mode on or off

Description

ftp_pasv ( resource $ftp_stream , bool $pasv ) : bool

ftp_pasv() turns on or off passive mode. In passive mode, data connections are initiated by the client, rather than by the server. It may be needed if the client is behind firewall.

Please note that ftp_pasv() can only be called after a successful login or otherwise it will fail.

Parameters

ftp_stream

The link identifier of the FTP connection.

pasv

If TRUE, the passive mode is turned on, else it's turned off.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ftp_pasv() example

<?php
$file = 'somefile.txt';
$remote_file = 'readme.txt';

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// turn passive mode on
ftp_pasv($conn_id, true);

// upload a file
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
 echo "successfully uploaded $file\n";
} else {
 echo "There was a problem while uploading $file\n";
}

// close the connection
ftp_close($conn_id);
?>


Uploads a file to the FTP server

  • « ftp_pasv
  • ftp_pwd »
  • PHP Manual
  • FTP Functions
  • Uploads a file to the FTP server

ftp_put

(PHP 4, PHP 5, PHP 7)

ftp_put — Uploads a file to the FTP server

Description

ftp_put ( resource $ftp_stream , string $remote_file , string $local_file [, int $mode = FTP_BINARY [, int $startpos = 0 ]] ) : bool

ftp_put() stores a local file on the FTP server.

Parameters

ftp_stream

The link identifier of the FTP connection.

remote_file

The remote file path.

local_file

The local file path.

mode

The transfer mode. Must be either FTP_ASCII or FTP_BINARY.

startpos

The position in the remote file to start uploading to.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.3.0 | The mode parameter is now optional. Formerly it has been mandatory.

Examples

Example #1 ftp_put() example

<?php
$file = 'somefile.txt';
$remote_file = 'readme.txt';

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// upload a file
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
 echo "successfully uploaded $file\n";
} else {
 echo "There was a problem while uploading $file\n";
}

// close the connection
ftp_close($conn_id);
?>

See Also

  • ftp_pasv() - Turns passive mode on or off
  • ftp_fput() - Uploads from an open file to the FTP server
  • ftp_nb_fput() - Stores a file from an open file to the FTP server (non-blocking)
  • ftp_nb_put() - Stores a file on the FTP server (non-blocking)


Returns the current directory name

  • « ftp_put
  • ftp_quit »
  • PHP Manual
  • FTP Functions
  • Returns the current directory name

ftp_pwd

(PHP 4, PHP 5, PHP 7)

ftp_pwd — Returns the current directory name

Description

ftp_pwd ( resource $ftp_stream ) : string

Parameters

ftp_stream

The link identifier of the FTP connection.

Return Values

Returns the current directory name or FALSE on error.

Examples

Example #1 ftp_pwd() example

<?php

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// change directory to public_html
ftp_chdir($conn_id, 'public_html');

// print current directory
echo ftp_pwd($conn_id); // /public_html

// close the connection
ftp_close($conn_id);
?>

See Also

  • ftp_chdir() - Changes the current directory on a FTP server
  • ftp_cdup() - Changes to the parent directory


Alias of ftp_close

  • « ftp_pwd
  • ftp_raw »
  • PHP Manual
  • FTP Functions
  • Alias of ftp_close

ftp_quit

(PHP 4, PHP 5, PHP 7)

ftp_quit — Alias of ftp_close()

Description

This function is an alias of: ftp_close().


Sends an arbitrary command to an FTP server

  • « ftp_quit
  • ftp_rawlist »
  • PHP Manual
  • FTP Functions
  • Sends an arbitrary command to an FTP server

ftp_raw

(PHP 5, PHP 7)

ftp_raw — Sends an arbitrary command to an FTP server

Description

ftp_raw ( resource $ftp_stream , string $command ) : array

Sends an arbitrary command to the FTP server.

Parameters

ftp_stream

The link identifier of the FTP connection.

command

The command to execute.

Return Values

Returns the server's response as an array of strings. No parsing is performed on the response string, nor does ftp_raw() determine if the command succeeded.

Examples

Example #1 Using ftp_raw() to login to an FTP server manually.

<?php
$fp = ftp_connect("ftp.example.com");

/* This is the same as:
   ftp_login($fp, "joeblow", "secret"); */
ftp_raw($fp, "USER joeblow");
ftp_raw($fp, "PASS secret");
?>

See Also

  • ftp_exec() - Requests execution of a command on the FTP server


Returns a detailed list of files in the given directory

  • « ftp_raw
  • ftp_rename »
  • PHP Manual
  • FTP Functions
  • Returns a detailed list of files in the given directory

ftp_rawlist

(PHP 4, PHP 5, PHP 7)

ftp_rawlist — Returns a detailed list of files in the given directory

Description

ftp_rawlist ( resource $ftp_stream , string $directory [, bool $recursive = FALSE ] ) : array

ftp_rawlist() executes the FTP LIST command, and returns the result as an array.

Parameters

ftp_stream

The link identifier of the FTP connection.

directory

The directory path. May include arguments for the LIST command.

recursive

If set to TRUE, the issued command will be LIST -R.

Return Values

Returns an array where each element corresponds to one line of text. Returns FALSE when passed directory is invalid.

The output is not parsed in any way. The system type identifier returned by ftp_systype() can be used to determine how the results should be interpreted.

Examples

Example #1 ftp_rawlist() example

<?php

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// get the file list for /
$buff = ftp_rawlist($conn_id, '/');

// close the connection
ftp_close($conn_id);

// output the buffer
var_dump($buff);
?>

The above example will output something similar to:

array(3) {
  [0]=>
  string(65) "drwxr-x---   3 vincent  vincent      4096 Jul 12 12:16 public_ftp"
  [1]=>
  string(66) "drwxr-x---  15 vincent  vincent      4096 Nov  3 21:31 public_html"
  [2]=>
  string(73) "lrwxrwxrwx   1 vincent  vincent        11 Jul 12 12:16 www -> public_html"
}

See Also

  • ftp_nlist() - Returns a list of files in the given directory
  • ftp_mlsd() - Returns a list of files in the given directory


Renames a file or a directory on the FTP server

  • « ftp_rawlist
  • ftp_rmdir »
  • PHP Manual
  • FTP Functions
  • Renames a file or a directory on the FTP server

ftp_rename

(PHP 4, PHP 5, PHP 7)

ftp_rename — Renames a file or a directory on the FTP server

Description

ftp_rename ( resource $ftp_stream , string $oldname , string $newname ) : bool

ftp_rename() renames a file or a directory on the FTP server.

Parameters

ftp_stream

The link identifier of the FTP connection.

oldname

The old file/directory name.

newname

The new name.

Return Values

Returns TRUE on success or FALSE on failure. Upon failure (such as attempting to rename a non-existent file), an E_WARNING error will be emitted.

Examples

Example #1 ftp_rename() example

<?php
$old_file = 'somefile.txt.bak';
$new_file = 'somefile.txt';

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// try to rename $old_file to $new_file
if (ftp_rename($conn_id, $old_file, $new_file)) {
 echo "successfully renamed $old_file to $new_file\n";
} else {
 echo "There was a problem while renaming $old_file to $new_file\n";
}

// close the connection
ftp_close($conn_id);
?>


Removes a directory

  • « ftp_rename
  • ftp_set_option »
  • PHP Manual
  • FTP Functions
  • Removes a directory

ftp_rmdir

(PHP 4, PHP 5, PHP 7)

ftp_rmdir — Removes a directory

Description

ftp_rmdir ( resource $ftp_stream , string $directory ) : bool

Removes the specified directory on the FTP server.

Parameters

ftp_stream

The link identifier of the FTP connection.

directory

The directory to delete. This must be either an absolute or relative path to an empty directory.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ftp_rmdir() example

<?php

$dir = 'www/';

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// try to delete the directory $dir
if (ftp_rmdir($conn_id, $dir)) {
    echo "Successfully deleted $dir\n";
} else {
    echo "There was a problem while deleting $dir\n";
}

ftp_close($conn_id);

?>

See Also

  • ftp_mkdir() - Creates a directory


Set miscellaneous runtime FTP options

  • « ftp_rmdir
  • ftp_site »
  • PHP Manual
  • FTP Functions
  • Set miscellaneous runtime FTP options

ftp_set_option

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

ftp_set_option — Set miscellaneous runtime FTP options

Description

ftp_set_option ( resource $ftp_stream , int $option , mixed $value ) : bool

This function controls various runtime options for the specified FTP stream.

Parameters

ftp_stream

The link identifier of the FTP connection.

option

Currently, the following options are supported:

Supported runtime FTP options
FTP_TIMEOUT_SEC | Changes the timeout in seconds used for all network related functions. value must be an integer that is greater than 0. The default timeout is 90 seconds.
FTP_AUTOSEEK | When enabled, GET or PUT requests with a resumepos or startpos parameter will first seek to the requested position within the file. This is enabled by default.
FTP_USEPASVADDRESS | When disabled, PHP will ignore the IP address returned by the FTP server in response to the PASV command and instead use the IP address that was supplied in the ftp_connect(). value must be a boolean.

value

This parameter depends on which option is chosen to be altered.

Return Values

Returns TRUE if the option could be set; FALSE if not. A warning message will be thrown if the option is not supported or the passed value doesn't match the expected value for the given option.

Examples

Example #1 ftp_set_option() example

<?php
// Set the network timeout to 10 seconds
ftp_set_option($conn_id, FTP_TIMEOUT_SEC, 10);
?>

See Also

  • ftp_get_option() - Retrieves various runtime behaviours of the current FTP stream


Sends a SITE command to the server

  • « ftp_set_option
  • ftp_size »
  • PHP Manual
  • FTP Functions
  • Sends a SITE command to the server

ftp_site

(PHP 4, PHP 5, PHP 7)

ftp_site — Sends a SITE command to the server

Description

ftp_site ( resource $ftp_stream , string $command ) : bool

ftp_site() sends the given SITE command to the FTP server.

SITE commands are not standardized, and vary from server to server. They are useful for handling such things as file permissions and group membership.

Parameters

ftp_stream

The link identifier of the FTP connection.

command

The SITE command. Note that this parameter isn't escaped so there may be some issues with filenames containing spaces and other characters.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Sending a SITE command to an ftp server

<?php
// Connect to FTP server
$conn = ftp_connect('ftp.example.com');
if (!$conn) die('Unable to connect to ftp.example.com');

// Login as "user" with password "pass"
if (!ftp_login($conn, 'user', 'pass')) die('Error logging into ftp.example.com');

// Issue: "SITE CHMOD 0600 /home/user/privatefile" command to ftp server
if (ftp_site($conn, 'CHMOD 0600 /home/user/privatefile')) {
   echo "Command executed successfully.\n";
} else {
   die('Command failed.');
}
?>

See Also

  • ftp_raw() - Sends an arbitrary command to an FTP server


Returns the size of the given file

  • « ftp_site
  • ftp_ssl_connect »
  • PHP Manual
  • FTP Functions
  • Returns the size of the given file

ftp_size

(PHP 4, PHP 5, PHP 7)

ftp_size — Returns the size of the given file

Description

ftp_size ( resource $ftp_stream , string $remote_file ) : int

ftp_size() returns the size of the given file in bytes.

Note:

Not all servers support this feature.

Parameters

ftp_stream

The link identifier of the FTP connection.

remote_file

The remote file.

Return Values

Returns the file size on success, or -1 on error.

Examples

Example #1 ftp_size() example

<?php

$file = 'somefile.txt';

// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// get the size of $file
$res = ftp_size($conn_id, $file);

if ($res != -1) {
    echo "size of $file is $res bytes";
} else {
    echo "couldn't get the size";
}

// close the connection
ftp_close($conn_id);

?>

See Also

  • ftp_rawlist() - Returns a detailed list of files in the given directory


Opens a Secure SSL-FTP connection

  • « ftp_size
  • ftp_systype »
  • PHP Manual
  • FTP Functions
  • Opens a Secure SSL-FTP connection

ftp_ssl_connect

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

ftp_ssl_connect — Opens a Secure SSL-FTP connection

Description

ftp_ssl_connect ( string $host [, int $port = 21 [, int $timeout = 90 ]] ) : resource

ftp_ssl_connect() opens an explicit SSL-FTP connection to the specified host. That implies that ftp_ssl_connect() will succeed even if the server is not configured for SSL-FTP, or its certificate is invalid. Only when ftp_login() is called, the client will send the appropriate AUTH FTP command, so ftp_login() will fail in the mentioned cases.

Note: Why this function may not exist

ftp_ssl_connect() is only available if both the ftp module and the OpenSSL support is built statically into php, this means that on Windows this function will be undefined in the official PHP builds. To make this function available on Windows you must compile your own PHP binaries.

Note:

ftp_ssl_connect() is not intended for use with sFTP. To use sFTP with PHP, please see ssh2_sftp().

Parameters

host

The FTP server address. This parameter shouldn't have any trailing slashes and shouldn't be prefixed with ftp://.

port

This parameter specifies an alternate port to connect to. If it is omitted or set to zero, then the default FTP port, 21, will be used.

timeout

This parameter specifies the timeout for all subsequent network operations. If omitted, the default value is 90 seconds. The timeout can be changed and queried at any time with ftp_set_option() and ftp_get_option().

Return Values

Returns a SSL-FTP stream on success or FALSE on error.

Changelog

Version | Description
5.2.2 | The function was changed to return FALSE when it can't use an SSL connection, instead of falling back to a non-SSL one as previously.

Examples

Example #1 ftp_ssl_connect() example

<?php

// set up basic ssl connection
$conn_id = ftp_ssl_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

if (!$login_result) {
    // PHP will already have raised an E_WARNING level message in this case
    die("can't login");
}

echo ftp_pwd($conn_id); // /

// close the ssl connection
ftp_close($conn_id);
?>

See Also

  • ftp_connect() - Opens an FTP connection


Returns the system type identifier of the remote FTP server

  • « ftp_ssl_connect
  • Gearman »
  • PHP Manual
  • FTP Functions
  • Returns the system type identifier of the remote FTP server

ftp_systype

(PHP 4, PHP 5, PHP 7)

ftp_systype — Returns the system type identifier of the remote FTP server

Description

ftp_systype ( resource $ftp_stream ) : string

Returns the system type identifier of the remote FTP server.

Parameters

ftp_stream

The link identifier of the FTP connection.

Return Values

Returns the remote system type, or FALSE on error.

Examples

Example #1 ftp_systype() example

<?php

// ftp connection
$ftp = ftp_connect('ftp.example.com');
ftp_login($ftp, 'user', 'password');

// get the system type
if ($type = ftp_systype($ftp)) {
    echo "Example.com is powered by $type\n";
} else {
    echo "Couldn't get the systype";
}

?>

The above example will output something similar to:

Example.com is powered by UNIX


Gearman

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
    • Basic Gearman client and worker, background
    • Basic Gearman client and worker, submitting tasks
  • GearmanClient — The GearmanClient class
    • GearmanClient::addOptions — Add client options
    • GearmanClient::addServer — Add a job server to the client
    • GearmanClient::addServers — Add a list of job servers to the client
    • GearmanClient::addTask — Add a task to be run in parallel
    • GearmanClient::addTaskBackground — Add a background task to be run in parallel
    • GearmanClient::addTaskHigh — Add a high priority task to run in parallel
    • GearmanClient::addTaskHighBackground — Add a high priority background task to be run in parallel
    • GearmanClient::addTaskLow — Add a low priority task to run in parallel
    • GearmanClient::addTaskLowBackground — Add a low priority background task to be run in parallel
    • GearmanClient::addTaskStatus — Add a task to get status
    • GearmanClient::clearCallbacks — Clear all task callback functions
    • GearmanClient::clone — Create a copy of a GearmanClient object
    • GearmanClient::__construct — Create a GearmanClient instance
    • GearmanClient::context — Get the application context
    • GearmanClient::data — Get the application data (deprecated)
    • GearmanClient::do — Run a single task and return a result [deprecated]
    • GearmanClient::doBackground — Run a task in the background
    • GearmanClient::doHigh — Run a single high priority task
    • GearmanClient::doHighBackground — Run a high priority task in the background
    • GearmanClient::doJobHandle — Get the job handle for the running task
    • GearmanClient::doLow — Run a single low priority task
    • GearmanClient::doLowBackground — Run a low priority task in the background
    • GearmanClient::doNormal — Run a single task and return a result
    • GearmanClient::doStatus — Get the status for the running task
    • GearmanClient::echo — Send data to all job servers to see if they echo it back [deprecated]
    • GearmanClient::error — Returns an error string for the last error encountered
    • GearmanClient::getErrno — Get an errno value
    • GearmanClient::jobStatus — Get the status of a background job
    • GearmanClient::ping — Send data to all job servers to see if they echo it back
    • GearmanClient::removeOptions — Remove client options
    • GearmanClient::returnCode — Get the last Gearman return code
    • GearmanClient::runTasks — Run a list of tasks in parallel
    • GearmanClient::setClientCallback — Callback function when there is a data packet for a task (deprecated)
    • GearmanClient::setCompleteCallback — Set a function to be called on task completion
    • GearmanClient::setContext — Set application context
    • GearmanClient::setCreatedCallback — Set a callback for when a task is queued
    • GearmanClient::setData — Set application data (deprecated)
    • GearmanClient::setDataCallback — Callback function when there is a data packet for a task
    • GearmanClient::setExceptionCallback — Set a callback for worker exceptions
    • GearmanClient::setFailCallback — Set callback for job failure
    • GearmanClient::setOptions — Set client options
    • GearmanClient::setStatusCallback — Set a callback for collecting task status
    • GearmanClient::setTimeout — Set socket I/O activity timeout
    • GearmanClient::setWarningCallback — Set a callback for worker warnings
    • GearmanClient::setWorkloadCallback — Set a callback for accepting incremental data updates
    • GearmanClient::timeout — Get current socket I/O activity timeout value
  • GearmanJob — The GearmanJob class
    • GearmanJob::complete — Send the result and complete status (deprecated)
    • GearmanJob::__construct — Create a GearmanJob instance
    • GearmanJob::data — Send data for a running job (deprecated)
    • GearmanJob::exception — Send exception for running job (deprecated)
    • GearmanJob::fail — Send fail status (deprecated)
    • GearmanJob::functionName — Get function name
    • GearmanJob::handle — Get the job handle
    • GearmanJob::returnCode — Get last return code
    • GearmanJob::sendComplete — Send the result and complete status
    • GearmanJob::sendData — Send data for a running job
    • GearmanJob::sendException — Send exception for running job (exception)
    • GearmanJob::sendFail — Send fail status
    • GearmanJob::sendStatus — Send status
    • GearmanJob::sendWarning — Send a warning
    • GearmanJob::setReturn — Set a return value
    • GearmanJob::status — Send status (deprecated)
    • GearmanJob::unique — Get the unique identifier
    • GearmanJob::warning — Send a warning (deprecated)
    • GearmanJob::workload — Get workload
    • GearmanJob::workloadSize — Get size of work load
  • GearmanTask — The GearmanTask class
    • GearmanTask::__construct — Create a GearmanTask instance
    • GearmanTask::create — Create a task (deprecated)
    • GearmanTask::data — Get data returned for a task
    • GearmanTask::dataSize — Get the size of returned data
    • GearmanTask::function — Get associated function name (deprecated)
    • GearmanTask::functionName — Get associated function name
    • GearmanTask::isKnown — Determine if task is known
    • GearmanTask::isRunning — Test whether the task is currently running
    • GearmanTask::jobHandle — Get the job handle
    • GearmanTask::recvData — Read work or result data into a buffer for a task
    • GearmanTask::returnCode — Get the last return code
    • GearmanTask::sendData — Send data for a task (deprecated)
    • GearmanTask::sendWorkload — Send data for a task
    • GearmanTask::taskDenominator — Get completion percentage denominator
    • GearmanTask::taskNumerator — Get completion percentage numerator
    • GearmanTask::unique — Get the unique identifier for a task
    • GearmanTask::uuid — Get the unique identifier for a task (deprecated)
  • GearmanWorker — The GearmanWorker class
    • GearmanWorker::addFunction — Register and add callback function
    • GearmanWorker::addOptions — Add worker options
    • GearmanWorker::addServer — Add a job server
    • GearmanWorker::addServers — Add job servers
    • GearmanWorker::clone — Create a copy of the worker
    • GearmanWorker::__construct — Create a GearmanWorker instance
    • GearmanWorker::echo — Test job server response
    • GearmanWorker::error — Get the last error encountered
    • GearmanWorker::getErrno — Get errno
    • GearmanWorker::options — Get worker options
    • GearmanWorker::register — Register a function with the job server
    • GearmanWorker::removeOptions — Remove worker options
    • GearmanWorker::returnCode — Get last Gearman return code
    • GearmanWorker::setId — Give the worker an identifier so it can be tracked when asking gearmand for the list of available workers
    • GearmanWorker::setOptions — Set worker options
    • GearmanWorker::setTimeout — Set socket I/O activity timeout
    • GearmanWorker::timeout — Get socket I/O activity timeout
    • GearmanWorker::unregister — Unregister a function name with the job servers
    • GearmanWorker::unregisterAll — Unregister all function names with the job servers
    • GearmanWorker::wait — Wait for activity from one of the job servers
    • GearmanWorker::work — Wait for and perform jobs
  • GearmanException — The GearmanException class


Introduction

» Gearman is a generic application framework for farming out work to multiple machines or processes. It allows applications to complete tasks in parallel, to load balance processing, and to call functions between languages. The framework can be used in a variety of applications, from high-availability web sites to the transport of database replication events.

This extension provides classes for writing Gearman clients and workers.


Requirements

This extension requires the » libgearman, » libevent and » uuid libraries, and a running Gearman server.


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/gearman


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.

Return values. Always check GearmanClient::error() or GearmanWorker() for a string error, as it may contain more details:

GEARMAN_SUCCESS (integer)
Whatever action was taken was successful.
GEARMAN_IO_WAIT (integer)
When in non-blocking mode, an event is hit that would have blocked.
GEARMAN_ERRNO (integer)
A system error. Check GearmanClient::errno() or GearmanWorker::errno() for the system error code that was returned.
GEARMAN_NO_ACTIVE_FDS (integer)
GearmanClient::wait() or GearmanWorker() was called with no connections.
GEARMAN_UNEXPECTED_PACKET (integer)
Indicates something going very wrong in gearmand. Applies only to GearmanWorker.
GEARMAN_GETADDRINFO (integer)
DNS resolution failed (invalid host, port, etc).
GEARMAN_NO_SERVERS (integer)
Did not call GearmanClient::addServer() before submitting jobs or tasks.
GEARMAN_LOST_CONNECTION (integer)
Lost a connection during a request.
GEARMAN_MEMORY_ALLOCATION_FAILURE (integer)
Memory allocation failed (ran out of memory).
GEARMAN_SERVER_ERROR (integer)
Something went wrong in the Gearman server and it could not handle the request gracefully.
GEARMAN_WORK_DATA (integer)
Notice return code obtained with GearmanClient::returnCode() when using GearmanClient::do(). Sent to update the client with data from a running job. A worker uses this when it needs to send updates, send partial results, or flush data during long running jobs.
GEARMAN_WORK_WARNING (integer)
Notice return code obtained with GearmanClient::returnCode() when using GearmanClient::do(). Updates the client with a warning. The behavior is just like GEARMAN_WORK_DATA, but should be treated as a warning instead of normal response data.
GEARMAN_WORK_STATUS (integer)
Notice return code obtained with GearmanClient::returnCode() when using GearmanClient::do(). Sent to update the status of a long running job. Use GearmanClient::doStatus() to obtain the percentage complete of the task.
GEARMAN_WORK_EXCEPTION (integer)
Notice return code obtained with GearmanClient::returnCode() when using GearmanClient::do(). Indicates that a job failed with a given exception.
GEARMAN_WORK_FAIL (integer)
Notice return code obtained with GearmanClient::returnCode() when using GearmanClient::do(). Indicates that the job failed.
GEARMAN_COULD_NOT_CONNECT (integer)
Failed to connect to servers.
GEARMAN_INVALID_FUNCTION_NAME (integer)
Trying to register a function name of NULL or using the callback interface without specifying callbacks.
GEARMAN_INVALID_WORKER_FUNCTION (integer)
Trying to register a function with a NULL callback function.
GEARMAN_NO_REGISTERED_FUNCTIONS (integer)
When a worker gets a job for a function it did not register.
GEARMAN_NO_JOBS (integer)
For a non-blocking worker, when GearmanWorker::work() does not have any active jobs.
GEARMAN_ECHO_DATA_CORRUPTION (integer)
After GearmanClient::echo() or GearmanWorker::echo() the data returned doesn't match the data sent.
GEARMAN_NEED_WORKLOAD_FN (integer)
When the client opted to stream the workload of a task, but did not specify a workload callback function.
GEARMAN_PAUSE (integer)
For the non-blocking client task interface, can be returned from the task callback to "pause" the call and return from GearmanClient::runTasks(). Call GearmanClient::runTasks() again to continue.
GEARMAN_UNKNOWN_STATE (integer)
Internal client/worker state error.
GEARMAN_SEND_BUFFER_TOO_SMALL (integer)
Internal error: trying to flush more data in one atomic chunk than is possible due to hard-coded buffer sizes.
GEARMAN_TIMEOUT (integer)
Hit the timeout limit set by the client/worker.

GearmanClient options:

GEARMAN_CLIENT_GENERATE_UNIQUE (integer)
Generate a unique id (UUID) for each task.
GEARMAN_CLIENT_NON_BLOCKING (integer)
Run the cient in a non-blocking mode.
GEARMAN_CLIENT_UNBUFFERED_RESULT (integer)
Allow the client to read data in chunks rather than have the library buffer the entire data result and pass that back.
GEARMAN_CLIENT_FREE_TASKS (integer)
Automatically free task objects once they are complete. This is the default setting in this extension to prevent memory leaks.

GearmanWorker options:

GEARMAN_WORKER_NON_BLOCKING (integer)
Run the worker in non-blocking mode.
GEARMAN_WORKER_GRAB_UNIQ (integer)
Return the client assigned unique ID in addition to the job handle.

Base Gearman configuration:

GEARMAN_DEFAULT_TCP_HOST (string)
GEARMAN_DEFAULT_TCP_PORT (integer)
GEARMAN_DEFAULT_SOCKET_TIMEOUT (integer)
GEARMAN_DEFAULT_SOCKET_SEND_SIZE (integer)
GEARMAN_DEFAULT_SOCKET_RECV_SIZE (integer)
GEARMAN_MAX_ERROR_SIZE (integer)
GEARMAN_PACKET_HEADER_SIZE (integer)
GEARMAN_JOB_HANDLE_SIZE (integer)
GEARMAN_OPTION_SIZE (integer)
GEARMAN_UNIQUE_SIZE (integer)
GEARMAN_MAX_COMMAND_ARGS (integer)
GEARMAN_ARGS_BUFFER_SIZE (integer)
GEARMAN_SEND_BUFFER_SIZE (integer)
GEARMAN_RECV_BUFFER_SIZE (integer)
GEARMAN_WORKER_WAIT_TIMEOUT (integer)


Examples

Table of Contents

  • Basic usage
  • Basic Gearman client and worker, background
  • Basic Gearman client and worker, submitting tasks


Basic usage

Example #1 Basic Gearman client and worker

This example shows a very simple client and worker. The client sends a string to the job server, and the worker reverses the string and sends it back. The job is performed synchronously.

<?php

# Create our client object.
$gmclient= new GearmanClient();

# Add default server (localhost).
$gmclient->addServer();

echo "Sending job\n";

# Send reverse job
do
{
  $result = $gmclient->doNormal("reverse", "Hello!");

  # Check for various return packets and errors.
  switch($gmclient->returnCode())
  {
    case GEARMAN_WORK_DATA:
      echo "Data: $result\n";
      break;
    case GEARMAN_WORK_STATUS:
      list($numerator, $denominator)= $gmclient->doStatus();
      echo "Status: $numerator/$denominator complete\n";
      break;
    case GEARMAN_WORK_FAIL:
      echo "Failed\n";
      exit;
    case GEARMAN_SUCCESS:
      echo "Success: $result\n";
      break;
    default:
      echo "RET: " . $gmclient->returnCode() . "\n";
      exit;
  }
}
while($gmclient->returnCode() != GEARMAN_SUCCESS);

?>
<?php

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server. Change the worker function to
# "reverse_fn_fast" for a faster worker with no output.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
  if ($gmworker->returnCode() != GEARMAN_SUCCESS)
  {
    echo "return_code: " . $gmworker->returnCode() . "\n";
    break;
  }
}

function reverse_fn($job)
{
  echo "Received job: " . $job->handle() . "\n";

  $workload = $job->workload();
  $workload_size = $job->workloadSize();

  echo "Workload: $workload ($workload_size)\n";

  # This status loop is not needed, just showing how it works
  for ($x= 0; $x < $workload_size; $x++)
  {
    echo "Sending status: " . ($x + 1) . "/$workload_size complete\n";
    $job->sendStatus($x, $workload_size);
    sleep(1);
  }

  $result= strrev($workload);
  echo "Result: $result\n";

  # Return what we want to send back to the client.
  return $result;
}

# A much simpler and less verbose version of the above function would be:
function reverse_fn_fast($job)
{
  return strrev($job->workload());
}

?>

The above example will output something similar to:

% php reverse_worker.php
Starting
Waiting for job...
Received job: H:foo.local:36
Workload: Hello! (6)
Sending status: 1/6 complete
Sending status: 2/6 complete
Sending status: 3/6 complete
Sending status: 4/6 complete
Sending status: 5/6 complete
Sending status: 6/6 complete
Result: !olleH

% php reverse_client.php
Starting
Sending job
Status: 1/6 complete
Status: 2/6 complete
Status: 3/6 complete
Status: 4/6 complete
Status: 5/6 complete
Status: 6/6 complete
Success: !olleH


Basic Gearman client and worker, background

Example #1 Basic Gearman client and worker, background

This example shows a very simple client and worker. The client sends a string to the job server as a background job, and the worker reverses the string. Note that since the work is performed asynchronously, the client does not wait for the job to complete and exits (and hence the client never receives the results).

<?php

# create our client object
$gmclient= new GearmanClient();

# add the default server (localhost)
$gmclient->addServer();

# run reverse client in the background
$job_handle = $gmclient->doBackground("reverse", "this is a test");

if ($gmclient->returnCode() != GEARMAN_SUCCESS)
{
  echo "bad return code\n";
  exit;
}

echo "done!\n";

?>
<?php

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server. Change the worker function to
# "reverse_fn_fast" for a faster worker with no output.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
  if ($gmworker->returnCode() != GEARMAN_SUCCESS)
  {
    echo "return_code: " . $gmworker->returnCode() . "\n";
    break;
  }
}

function reverse_fn($job)
{
  echo "Received job: " . $job->handle() . "\n";

  $workload = $job->workload();
  $workload_size = $job->workloadSize();

  echo "Workload: $workload ($workload_size)\n";

  # This status loop is not needed, just showing how it works
  for ($x= 0; $x < $workload_size; $x++)
  {
    echo "Sending status: " . ($x + 1) . "/$workload_size complete\n";
    $job->sendStatus($x, $workload_size);
    sleep(1);
  }

  $result= strrev($workload);
  echo "Result: $result\n";

  # Return what we want to send back to the client.
  return $result;
}

# A much simpler and less verbose version of the above function would be:
function reverse_fn_fast($job)
{
  return strrev($job->workload());
}

?>

The above example will output something similar to:

% php reverse_worker.php
Starting
Waiting for job...
Received job: H:foo.local:41
Workload: this is a test (14)
1/14 complete
2/14 complete
3/14 complete
4/14 complete
5/14 complete
6/14 complete
7/14 complete
8/14 complete
9/14 complete
10/14 complete
11/14 complete
12/14 complete
13/14 complete
14/14 complete
Result: tset a si siht

% php reverse_client_bg.php
done!


Basic Gearman client and worker, submitting tasks

Example #1 Basic Gearman client and worker, submitting tasks

In this example, the basic reverse client extended to run two tasks in parallel. The reverse worker is unchanged except to add sending of data back during processing.

<?php

# create the gearman client
$gmc= new GearmanClient();

# add the default server (localhost)
$gmc->addServer();

# register some callbacks
$gmc->setCreatedCallback("reverse_created");
$gmc->setDataCallback("reverse_data");
$gmc->setStatusCallback("reverse_status");
$gmc->setCompleteCallback("reverse_complete");
$gmc->setFailCallback("reverse_fail");

# set some arbitrary application data
$data['foo'] = 'bar';

# add two tasks
$task= $gmc->addTask("reverse", "foo", $data);
$task2= $gmc->addTaskLow("reverse", "bar", NULL);

# run the tasks in parallel (assuming multiple workers)
if (! $gmc->runTasks())
{
    echo "ERROR " . $gmc->error() . "\n";
    exit;
}

echo "DONE\n";

function reverse_created($task)
{
    echo "CREATED: " . $task->jobHandle() . "\n";
}

function reverse_status($task)
{
    echo "STATUS: " . $task->jobHandle() . " - " . $task->taskNumerator() .
         "/" . $task->taskDenominator() . "\n";
}

function reverse_complete($task)
{
    echo "COMPLETE: " . $task->jobHandle() . ", " . $task->data() . "\n";
}

function reverse_fail($task)
{
    echo "FAILED: " . $task->jobHandle() . "\n";
}

function reverse_data($task)
{
    echo "DATA: " . $task->data() . "\n";
}

?>
<?php

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server. Change the worker function to
# "reverse_fn_fast" for a faster worker with no output.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
  if ($gmworker->returnCode() != GEARMAN_SUCCESS)
  {
    echo "return_code: " . $gmworker->returnCode() . "\n";
    break;
  }
}

function reverse_fn($job)
{
  echo "Received job: " . $job->handle() . "\n";

  $workload = $job->workload();
  $workload_size = $job->workloadSize();

  echo "Workload: $workload ($workload_size)\n";

  # This status loop is not needed, just showing how it works
  for ($x= 0; $x < $workload_size; $x++)
  {
    echo "Sending status: " . ($x + 1) . "/$workload_size complete\n";
    $job->sendStatus($x+1, $workload_size);
    $job->sendData(substr($workload, $x, 1));
    sleep(1);
  }

  $result= strrev($workload);
  echo "Result: $result\n";

  # Return what we want to send back to the client.
  return $result;
}

# A much simpler and less verbose version of the above function would be:
function reverse_fn_fast($job)
{
  return strrev($job->workload());
}

?>

The above example will output something similar to:

% php reverse_worker.php
Starting
Waiting for job...
Received job: H:foo.local:45
Workload: foo (3)
1/3 complete
2/3 complete
3/3 complete
Result: oof
Received job: H:foo.local:44
Workload: bar (3)
1/3 complete
2/3 complete
3/3 complete
Result: rab

% php reverse_client_task.php
CREATED: H:foo.local:44
CREATED: H:foo.local:45
STATUS: H:foo.local:45 - 1/3
DATA: f
STATUS: H:foo.local:45 - 2/3
DATA: o
STATUS: H:foo.local:45 - 3/3
DATA: o
COMPLETE: H:foo.local:45, oof
STATUS: H:foo.local:44 - 1/3
DATA: b
STATUS: H:foo.local:44 - 2/3
DATA: a
STATUS: H:foo.local:44 - 3/3
DATA: r
COMPLETE: H:foo.local:44, rab
DONE


The GearmanClient class

(PECL gearman >= 0.5.0)

Introduction

Represents a class for connecting to a Gearman job server and making requests to perform some function on provided data. The function performed must be one registered by a Gearman worker and the data passed is opaque to the job server.

Class synopsis

GearmanClient {
/* Methods */
public addOptions ( int $options ) : bool
public addServer ([ string $host = 127.0.0.1 [, int $port = 4730 ]] ) : bool
public addServers ([ string $servers = 127.0.0.1:4730 ] ) : bool
public addTask ( string $function_name , string $workload [, mixed &$context [, string $unique ]] ) : GearmanTask
public addTaskBackground ( string $function_name , string $workload [, mixed &$context [, string $unique ]] ) : GearmanTask
public addTaskHigh ( string $function_name , string $workload [, mixed &$context [, string $unique ]] ) : GearmanTask
public addTaskHighBackground ( string $function_name , string $workload [, mixed &$context [, string $unique ]] ) : GearmanTask
public addTaskLow ( string $function_name , string $workload [, mixed &$context [, string $unique ]] ) : GearmanTask
public addTaskLowBackground ( string $function_name , string $workload [, mixed &$context [, string $unique ]] ) : GearmanTask
public addTaskStatus ( string $job_handle [, string &$context ] ) : GearmanTask
public clearCallbacks ( void ) : bool
public clone ( void ) : GearmanClient
public __construct ( void )
public context ( void ) : string
public data ( void ) : string
public do ( string $function_name , string $workload [, string $unique ] ) : string
public doBackground ( string $function_name , string $workload [, string $unique ] ) : string
public doHigh ( string $function_name , string $workload [, string $unique ] ) : string
public doHighBackground ( string $function_name , string $workload [, string $unique ] ) : string
public doJobHandle ( void ) : string
public doLow ( string $function_name , string $workload [, string $unique ] ) : string
public doLowBackground ( string $function_name , string $workload [, string $unique ] ) : string
public doNormal ( string $function_name , string $workload [, string $unique ] ) : string
public doStatus ( void ) : array
public echo ( string $workload ) : bool
public error ( void ) : string
public getErrno ( void ) : int
public jobStatus ( string $job_handle ) : array
public ping ( string $workload ) : bool
public removeOptions ( int $options ) : bool
public returnCode ( void ) : int
public runTasks ( void ) : bool
public setClientCallback ( callable $callback ) : void
public setCompleteCallback ( callable $callback ) : bool
public setContext ( string $context ) : bool
public setCreatedCallback ( string $callback ) : bool
public setData ( string $data ) : bool
public setDataCallback ( callable $callback ) : bool
public setExceptionCallback ( callable $callback ) : bool
public setFailCallback ( callable $callback ) : bool
public setOptions ( int $options ) : bool
public setStatusCallback ( callable $callback ) : bool
public setTimeout ( int $timeout ) : bool
public setWarningCallback ( callable $callback ) : bool
public setWorkloadCallback ( callable $callback ) : bool
public timeout ( void ) : int
}

Table of Contents

  • GearmanClient::addOptions — Add client options
  • GearmanClient::addServer — Add a job server to the client
  • GearmanClient::addServers — Add a list of job servers to the client
  • GearmanClient::addTask — Add a task to be run in parallel
  • GearmanClient::addTaskBackground — Add a background task to be run in parallel
  • GearmanClient::addTaskHigh — Add a high priority task to run in parallel
  • GearmanClient::addTaskHighBackground — Add a high priority background task to be run in parallel
  • GearmanClient::addTaskLow — Add a low priority task to run in parallel
  • GearmanClient::addTaskLowBackground — Add a low priority background task to be run in parallel
  • GearmanClient::addTaskStatus — Add a task to get status
  • GearmanClient::clearCallbacks — Clear all task callback functions
  • GearmanClient::clone — Create a copy of a GearmanClient object
  • GearmanClient::__construct — Create a GearmanClient instance
  • GearmanClient::context — Get the application context
  • GearmanClient::data — Get the application data (deprecated)
  • GearmanClient::do — Run a single task and return a result [deprecated]
  • GearmanClient::doBackground — Run a task in the background
  • GearmanClient::doHigh — Run a single high priority task
  • GearmanClient::doHighBackground — Run a high priority task in the background
  • GearmanClient::doJobHandle — Get the job handle for the running task
  • GearmanClient::doLow — Run a single low priority task
  • GearmanClient::doLowBackground — Run a low priority task in the background
  • GearmanClient::doNormal — Run a single task and return a result
  • GearmanClient::doStatus — Get the status for the running task
  • GearmanClient::echo — Send data to all job servers to see if they echo it back [deprecated]
  • GearmanClient::error — Returns an error string for the last error encountered
  • GearmanClient::getErrno — Get an errno value
  • GearmanClient::jobStatus — Get the status of a background job
  • GearmanClient::ping — Send data to all job servers to see if they echo it back
  • GearmanClient::removeOptions — Remove client options
  • GearmanClient::returnCode — Get the last Gearman return code
  • GearmanClient::runTasks — Run a list of tasks in parallel
  • GearmanClient::setClientCallback — Callback function when there is a data packet for a task (deprecated)
  • GearmanClient::setCompleteCallback — Set a function to be called on task completion
  • GearmanClient::setContext — Set application context
  • GearmanClient::setCreatedCallback — Set a callback for when a task is queued
  • GearmanClient::setData — Set application data (deprecated)
  • GearmanClient::setDataCallback — Callback function when there is a data packet for a task
  • GearmanClient::setExceptionCallback — Set a callback for worker exceptions
  • GearmanClient::setFailCallback — Set callback for job failure
  • GearmanClient::setOptions — Set client options
  • GearmanClient::setStatusCallback — Set a callback for collecting task status
  • GearmanClient::setTimeout — Set socket I/O activity timeout
  • GearmanClient::setWarningCallback — Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback — Set a callback for accepting incremental data updates
  • GearmanClient::timeout — Get current socket I/O activity timeout value


Add client options

  • « GearmanClient
  • GearmanClient::addServer »
  • PHP Manual
  • GearmanClient
  • Add client options

GearmanClient::addOptions

(PECL gearman >= 0.6.0)

GearmanClient::addOptions — Add client options

Description

public GearmanClient::addOptions ( int $options ) : bool

Adds one or more options to those already set.

Parameters

options

The options to add. One of the following constants, or a combination of them using the bitwise OR operator (|): GEARMAN_CLIENT_GENERATE_UNIQUE, GEARMAN_CLIENT_NON_BLOCKING, GEARMAN_CLIENT_UNBUFFERED_RESULT or GEARMAN_CLIENT_FREE_TASKS.

Return Values

Always returns TRUE.


Add a job server to the client

  • « GearmanClient::addOptions
  • GearmanClient::addServers »
  • PHP Manual
  • GearmanClient
  • Add a job server to the client

GearmanClient::addServer

(PECL gearman >= 0.5.0)

GearmanClient::addServer — Add a job server to the client

Description

public GearmanClient::addServer ([ string $host = 127.0.0.1 [, int $port = 4730 ]] ) : bool

Adds a job server to a list of servers that can be used to run a task. No socket I/O happens here; the server is simply added to the list.

Parameters

host

The job server host name.

port

The job server port.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Adding two job servers

<?php

# Create our client object.
$gmclient= new GearmanClient();

# Add two job servers, the first on the default 4730 port
$gmclient->addServer("10.0.0.1");
$gmclient->addServer("10.0.0.2", 7003);

?>

See Also

  • GearmanClient::addServers() - Add a list of job servers to the client


Add a list of job servers to the client

  • « GearmanClient::addServer
  • GearmanClient::addTask »
  • PHP Manual
  • GearmanClient
  • Add a list of job servers to the client

GearmanClient::addServers

(PECL gearman >= 0.5.0)

GearmanClient::addServers — Add a list of job servers to the client

Description

public GearmanClient::addServers ([ string $servers = 127.0.0.1:4730 ] ) : bool

Adds a list of job servers that can be used to run a task. No socket I/O happens here; the servers are simply added to the full list of servers.

Parameters

servers

A comma-separated list of servers, each server specified in the format 'host:port'.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Add two job servers

<?php

# Create our client object.
$gmclient= new GearmanClient();

# Add multiple job servers, the first on the default 4730 port
$gmclient->addServers("10.0.0.1,10.0.0.2:7003");

?>

See Also

  • GearmanClient::addServer() - Add a job server to the client


Add a task to be run in parallel

  • « GearmanClient::addServers
  • GearmanClient::addTaskBackground »
  • PHP Manual
  • GearmanClient
  • Add a task to be run in parallel

GearmanClient::addTask

(PECL gearman >= 0.5.0)

GearmanClient::addTask — Add a task to be run in parallel

Description

public GearmanClient::addTask ( string $function_name , string $workload [, mixed &$context [, string $unique ]] ) : GearmanTask

Adds a task to be run in parallel with other tasks. Call this method for all the tasks to be run in parallel, then call GearmanClient::runTasks() to perform the work. Note that enough workers need to be available for the tasks to all run in parallel.

Parameters

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

context

Application context to associate with a task

unique

A unique ID used to identify a particular task

Return Values

A GearmanTask object or FALSE if the task could not be added.

Examples

Example #1 Basic submission of two tasks

<?php

# Create our gearman client
$gmclient= new GearmanClient();

# add the default job server
$gmclient->addServer();

# set a function to be called when the work is complete
$gmclient->setCompleteCallback("complete");

# add a task to perform the "reverse" function on the string "Hello World!"
$gmclient->addTask("reverse", "Hello World!", null, "1");

# add another task to perform the "reverse" function on the string "!dlroW olleH"
$gmclient->addTask("reverse", "!dlroW olleH", null, "2");

# run the tasks
$gmclient->runTasks();

function complete($task)
{
  print "COMPLETE: " . $task->unique() . ", " . $task->data() . "\n";
}

?>

The above example will output something similar to:

COMPLETE: 2, Hello World!
COMPLETE: 1, !dlroW olleH

Example #2 Basic submission of two tasks with passing application context

<?php

$client = new GearmanClient();
$client->addServer();

# set a function to be called when the work is complete
$client->setCompleteCallback("reverse_complete");

# Add some tasks for a placeholder of where to put the results
$results = array();
$client->addTask("reverse", "Hello World!", &$results, "t1");
$client->addTask("reverse", "!dlroW olleH", &$results, "t2");

$client->runTasks();

# The results should now be filled in from the callbacks
foreach ($results as $id => $result)
   echo $id . ": " . $result['handle'] . ", " . $result['data'] . "\n";

function reverse_complete($task, $results)
{
   $results[$task->unique()] = array("handle"=>$task->jobHandle(), "data"=>$task->data());
}

?>

The above example will output something similar to:

t2: H.foo:21, Hello World!
t1: H:foo:22, !dlroW olleH

See Also

  • GearmanClient::addTaskHigh() - Add a high priority task to run in parallel
  • GearmanClient::addTaskLow() - Add a low priority task to run in parallel
  • GearmanClient::addTaskBackground() - Add a background task to be run in parallel
  • GearmanClient::addTaskHighBackground() - Add a high priority background task to be run in parallel
  • GearmanClient::addTaskLowBackground() - Add a low priority background task to be run in parallel
  • GearmanClient::runTasks() - Run a list of tasks in parallel


Add a background task to be run in parallel

  • « GearmanClient::addTask
  • GearmanClient::addTaskHigh »
  • PHP Manual
  • GearmanClient
  • Add a background task to be run in parallel

GearmanClient::addTaskBackground

(PECL gearman >= 0.5.0)

GearmanClient::addTaskBackground — Add a background task to be run in parallel

Description

public GearmanClient::addTaskBackground ( string $function_name , string $workload [, mixed &$context [, string $unique ]] ) : GearmanTask

Adds a background task to be run in parallel with other tasks. Call this method for all the tasks to be run in parallel, then call GearmanClient::runTasks() to perform the work.

Parameters

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

context

Application context to associate with a task

unique

A unique ID used to identify a particular task

Return Values

A GearmanTask object or FALSE if the task could not be added.

Examples

Example #1 Two tasks, one background and one not

This example illustrates the difference between running a background task and a normal task. The client adds two tasks to execute the same function, but one is added with addTaskBackground(). A callback is set so that progress of the job can be tracked. A simple worker with an artificial delay reports on the job progress and the client picks this up through the callback. Two workers are run for this example. Note that the background task does not show in the client output.

<?php

# The client script

# create our gearman client
$gmc= new GearmanClient();

# add the default job server
$gmc->addServer();

# set a couple of callbacks so we can track progress
$gmc->setCompleteCallback("reverse_complete");
$gmc->setStatusCallback("reverse_status");

# add a task for the "reverse" function
$task= $gmc->addTask("reverse", "Hello World!", null, "1");

# add another task, but this one to run in the background
$task= $gmc->addTaskBackground("reverse", "!dlroW olleH", null, "2");

if (! $gmc->runTasks())
{
    echo "ERROR " . $gmc->error() . "\n";
    exit;
}

echo "DONE\n";

function reverse_status($task)
{
    echo "STATUS: " . $task->unique() . ", " . $task->jobHandle() . " - " . $task->taskNumerator() .
         "/" . $task->taskDenominator() . "\n";
}

function reverse_complete($task)
{
    echo "COMPLETE: " . $task->unique() . ", " . $task->data() . "\n";
}

?>
<?php

# The worker script

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
  if ($gmworker->returnCode() != GEARMAN_SUCCESS)
  {
    echo "return_code: " . $gmworker->returnCode() . "\n";
    break;
  }
}

function reverse_fn($job)
{
  echo "Received job: " . $job->handle() . "\n";

  $workload = $job->workload();
  $workload_size = $job->workloadSize();

  echo "Workload: $workload ($workload_size)\n";

  # This status loop is not needed, just showing how it works
  for ($x= 0; $x < $workload_size; $x++)
  {
    echo "Sending status: " . ($x + 1) . "/$workload_size complete\n";
    $job->sendStatus($x+1, $workload_size);
    $job->sendData(substr($workload, $x, 1));
    sleep(1);
  }

  $result= strrev($workload);
  echo "Result: $result\n";

  # Return what we want to send back to the client.
  return $result;
}

?>

Worker output for two workers running:

Received job: H:foo.local:65
Workload: !dlroW olleH (12)
1/12 complete
Received job: H:foo.local:66
Workload: Hello World! (12)
Sending status: 1/12 complete
Sending status: 2/12 complete
Sending status: 2/12 complete
Sending status: 3/12 complete
Sending status: 3/12 complete
Sending status: 4/12 complete
Sending status: 4/12 complete
Sending status: 5/12 complete
Sending status: 5/12 complete
Sending status: 6/12 complete
Sending status: 6/12 complete
Sending status: 7/12 complete
Sending status: 7/12 complete
Sending status: 8/12 complete
Sending status: 8/12 complete
Sending status: 9/12 complete
Sending status: 9/12 complete
Sending status: 10/12 complete
Sending status: 10/12 complete
Sending status: 11/12 complete
Sending status: 11/12 complete
Sending status: 12/12 complete
Sending status: 12/12 complete
Result: !dlroW olleH
Result: Hello World!

Client output:

STATUS: 1, H:foo.local:66 - 1/12
STATUS: 1, H:foo.local:66 - 2/12
STATUS: 1, H:foo.local:66 - 3/12
STATUS: 1, H:foo.local:66 - 4/12
STATUS: 1, H:foo.local:66 - 5/12
STATUS: 1, H:foo.local:66 - 6/12
STATUS: 1, H:foo.local:66 - 7/12
STATUS: 1, H:foo.local:66 - 8/12
STATUS: 1, H:foo.local:66 - 9/12
STATUS: 1, H:foo.local:66 - 10/12
STATUS: 1, H:foo.local:66 - 11/12
STATUS: 1, H:foo.local:66 - 12/12
COMPLETE: 1, !dlroW olleH
DONE

See Also

  • GearmanClient::addTask() - Add a task to be run in parallel
  • GearmanClient::addTaskHigh() - Add a high priority task to run in parallel
  • GearmanClient::addTaskLow() - Add a low priority task to run in parallel
  • GearmanClient::addTaskHighBackground() - Add a high priority background task to be run in parallel
  • GearmanClient::addTaskLowBackground() - Add a low priority background task to be run in parallel
  • GearmanClient::runTasks() - Run a list of tasks in parallel


Add a high priority task to run in parallel

  • « GearmanClient::addTaskBackground
  • GearmanClient::addTaskHighBackground »
  • PHP Manual
  • GearmanClient
  • Add a high priority task to run in parallel

GearmanClient::addTaskHigh

(PECL gearman >= 0.5.0)

GearmanClient::addTaskHigh — Add a high priority task to run in parallel

Description

public GearmanClient::addTaskHigh ( string $function_name , string $workload [, mixed &$context [, string $unique ]] ) : GearmanTask

Adds a high priority task to be run in parallel with other tasks. Call this method for all the high priority tasks to be run in parallel, then call GearmanClient::runTasks() to perform the work. Tasks with a high priority will be selected from the queue before those of normal or low priority.

Parameters

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

context

Application context to associate with a task

unique

A unique ID used to identify a particular task

Return Values

A GearmanTask object or FALSE if the task could not be added.

Examples

Example #1 A high priority task along with two normal tasks

A high priority task is included among two other tasks. A single worker is available, so that tasks are run one at a time, with the high priority task run first.

<?php

# create the gearman client
$gmc= new GearmanClient();

# add the default job server
$gmc->addServer();

# set the callback for when the job is complete
$gmc->setCompleteCallback("reverse_complete");

# add tasks, one of which is high priority
$task= $gmc->addTask("reverse", "Hello World!", null, "1");
$task= $gmc->addTaskHigh("reverse", "!dlroW olleH", null, "2");
$task= $gmc->addTask("reverse", "Hello World!", null, "3");

if (! $gmc->runTasks())
{
    echo "ERROR " . $gmc->error() . "\n";
    exit;
}
echo "DONE\n";

function reverse_complete($task)
{
    echo "COMPLETE: " . $task->unique() . ", " . $task->data() . "\n";
}

?>

The above example will output something similar to:

COMPLETE: 2, Hello World!
COMPLETE: 3, !dlroW olleH
COMPLETE: 1, !dlroW olleH
DONE

See Also

  • GearmanClient::addTask() - Add a task to be run in parallel
  • GearmanClient::addTaskLow() - Add a low priority task to run in parallel
  • GearmanClient::addTaskBackground() - Add a background task to be run in parallel
  • GearmanClient::addTaskHighBackground() - Add a high priority background task to be run in parallel
  • GearmanClient::addTaskLowBackground() - Add a low priority background task to be run in parallel
  • GearmanClient::runTasks() - Run a list of tasks in parallel


Add a high priority background task to be run in parallel

  • « GearmanClient::addTaskHigh
  • GearmanClient::addTaskLow »
  • PHP Manual
  • GearmanClient
  • Add a high priority background task to be run in parallel

GearmanClient::addTaskHighBackground

(PECL gearman >= 0.5.0)

GearmanClient::addTaskHighBackground — Add a high priority background task to be run in parallel

Description

public GearmanClient::addTaskHighBackground ( string $function_name , string $workload [, mixed &$context [, string $unique ]] ) : GearmanTask

Adds a high priority background task to be run in parallel with other tasks. Call this method for all the tasks to be run in parallel, then call GearmanClient::runTasks() to perform the work. Tasks with a high priority will be selected from the queue before those of normal or low priority.

Parameters

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

context

Application context to associate with a task

unique

A unique ID used to identify a particular task

Return Values

A GearmanTask object or FALSE if the task could not be added.

See Also

  • GearmanClient::addTask() - Add a task to be run in parallel
  • GearmanClient::addTaskHigh() - Add a high priority task to run in parallel
  • GearmanClient::addTaskLow() - Add a low priority task to run in parallel
  • GearmanClient::addTaskBackground() - Add a background task to be run in parallel
  • GearmanClient::addTaskLowBackground() - Add a low priority background task to be run in parallel
  • GearmanClient::runTasks() - Run a list of tasks in parallel


Add a low priority task to run in parallel

  • « GearmanClient::addTaskHighBackground
  • GearmanClient::addTaskLowBackground »
  • PHP Manual
  • GearmanClient
  • Add a low priority task to run in parallel

GearmanClient::addTaskLow

(PECL gearman >= 0.5.0)

GearmanClient::addTaskLow — Add a low priority task to run in parallel

Description

public GearmanClient::addTaskLow ( string $function_name , string $workload [, mixed &$context [, string $unique ]] ) : GearmanTask

Adds a low priority background task to be run in parallel with other tasks. Call this method for all the tasks to be run in parallel, then call GearmanClient::runTasks() to perform the work. Tasks with a low priority will be selected from the queue after those of normal or low priority.

Parameters

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

context

Application context to associate with a task

unique

A unique ID used to identify a particular task

Return Values

A GearmanTask object or FALSE if the task could not be added.

Examples

Example #1 A low priority task along with two normal tasks

A low priority task is included among two other tasks. A single worker is available, so that tasks are run one at a time, with the low priority task run last.

<?php

# create the gearman client
$gmc= new GearmanClient();

# add the default job server
$gmc->addServer();

# set the callback for when the job is complete
$gmc->setCompleteCallback("reverse_complete");

# add tasks, one of which is low priority
$task= $gmc->addTask("reverse", "Hello World!", null, "1");
$task= $gmc->addTaskLow("reverse", "!dlroW olleH", null, "2");
$task= $gmc->addTask("reverse", "Hello World!", null, "3");

if (! $gmc->runTasks())
{
    echo "ERROR " . $gmc->error() . "\n";
    exit;
}
echo "DONE\n";

function reverse_complete($task)
{
    echo "COMPLETE: " . $task->unique() . ", " . $task->data() . "\n";
}

?>

The above example will output something similar to:

COMPLETE: 3, !dlroW olleH
COMPLETE: 1, !dlroW olleH
COMPLETE: 2, Hello World!
DONE

See Also

  • GearmanClient::addTask() - Add a task to be run in parallel
  • GearmanClient::addTaskHigh() - Add a high priority task to run in parallel
  • GearmanClient::addTaskBackground() - Add a background task to be run in parallel
  • GearmanClient::addTaskHighBackground() - Add a high priority background task to be run in parallel
  • GearmanClient::addTaskLowBackground() - Add a low priority background task to be run in parallel
  • GearmanClient::runTasks() - Run a list of tasks in parallel


Add a low priority background task to be run in parallel

  • « GearmanClient::addTaskLow
  • GearmanClient::addTaskStatus »
  • PHP Manual
  • GearmanClient
  • Add a low priority background task to be run in parallel

GearmanClient::addTaskLowBackground

(PECL gearman >= 0.5.0)

GearmanClient::addTaskLowBackground — Add a low priority background task to be run in parallel

Description

public GearmanClient::addTaskLowBackground ( string $function_name , string $workload [, mixed &$context [, string $unique ]] ) : GearmanTask

Adds a low priority background task to be run in parallel with other tasks. Call this method for all the tasks to be run in parallel, then call GearmanClient::runTasks() to perform the work. Tasks with a low priority will be selected from the queue after those of normal or high priority.

Parameters

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

context

Application context to associate with a task

unique

A unique ID used to identify a particular task

Return Values

A GearmanTask object or FALSE if the task could not be added.

See Also

  • GearmanClient::addTask() - Add a task to be run in parallel
  • GearmanClient::addTaskHigh() - Add a high priority task to run in parallel
  • GearmanClient::addTaskLow() - Add a low priority task to run in parallel
  • GearmanClient::addTaskBackground() - Add a background task to be run in parallel
  • GearmanClient::addTaskHighBackground() - Add a high priority background task to be run in parallel
  • GearmanClient::runTasks() - Run a list of tasks in parallel


Add a task to get status

  • « GearmanClient::addTaskLowBackground
  • GearmanClient::clearCallbacks »
  • PHP Manual
  • GearmanClient
  • Add a task to get status

GearmanClient::addTaskStatus

(PECL gearman >= 0.5.0)

GearmanClient::addTaskStatus — Add a task to get status

Description

public GearmanClient::addTaskStatus ( string $job_handle [, string &$context ] ) : GearmanTask

Used to request status information from the Gearman server, which will call the specified status callback (set using GearmanClient::setStatusCallback()).

Parameters

job_handle

The job handle for the task to get status for

context

Data to be passed to the status callback, generally a reference to an array or object

Return Values

A GearmanTask object.

Examples

Example #1 Monitor completion of multiple background tasks

An artificial delay is introduced in the worker in this example to simulate a long running process. There is only one worker running for this example.

<?php

/* create our object */
$gmclient= new GearmanClient();

/* add the default server */
$gmclient->addServer();

/* start some background jobs and save the handles */
$handles = array();
$handles[0] = $gmclient->doBackground("reverse", "Hello World!");
$handles[1] = $gmclient->doBackground("reverse", "!dlroW olleH");

$gmclient->setStatusCallback("reverse_status");

/* Poll the server to see when those background jobs finish; */
/* a better method would be to use event callbacks */
do
{
   /* Use the context variable to track how many tasks have completed */
   $done = 0;
   $gmclient->addTaskStatus($handles[0], &$done);
   $gmclient->addTaskStatus($handles[1], &$done);
   $gmclient->runTasks();
   echo "Done: $done\n";
   sleep(1);
}
while ($done != 2);

function reverse_status($task, $done)
{
   if (!$task->isKnown())
      $done++;
}

?>

The above example will output something similar to:

Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 2

See Also

  • GearmanClient::setStatusCallback() - Set a callback for collecting task status


Clear all task callback functions

  • « GearmanClient::addTaskStatus
  • GearmanClient::clone »
  • PHP Manual
  • GearmanClient
  • Clear all task callback functions

GearmanClient::clearCallbacks

(PECL gearman >= 0.5.0)

GearmanClient::clearCallbacks — Clear all task callback functions

Description

public GearmanClient::clearCallbacks ( void ) : bool

Clears all the task callback functions that have previously been set.

Parameters

This function has no parameters.

Return Values

Always returns TRUE.

See Also

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates


Create a copy of a GearmanClient object

  • « GearmanClient::clearCallbacks
  • GearmanClient::__construct »
  • PHP Manual
  • GearmanClient
  • Create a copy of a GearmanClient object

GearmanClient::clone

(PECL gearman >= 0.5.0)

GearmanClient::clone — Create a copy of a GearmanClient object

Description

public GearmanClient::clone ( void ) : GearmanClient

Creates a copy of a GearmanClient object.

Parameters

This function has no parameters.

Return Values

A GearmanClient on success, FALSE on failure.


Create a GearmanClient instance

  • « GearmanClient::clone
  • GearmanClient::context »
  • PHP Manual
  • GearmanClient
  • Create a GearmanClient instance

GearmanClient::__construct

(PECL gearman >= 0.5.0)

GearmanClient::__construct — Create a GearmanClient instance

Description

public GearmanClient::__construct ( void )

Creates a GearmanClient instance representing a client that connects to the job server and submits tasks to complete.

Parameters

This function has no parameters.

Return Values

A GearmanClient object.

See Also

  • GearmanClient::clone() - Create a copy of a GearmanClient object


Get the application context

  • « GearmanClient::__construct
  • GearmanClient::data »
  • PHP Manual
  • GearmanClient
  • Get the application context

GearmanClient::context

(PECL gearman >= 0.6.0)

GearmanClient::context — Get the application context

Description

public GearmanClient::context ( void ) : string

Get the application context previously set with GearmanClient::setContext().

Parameters

This function has no parameters.

Return Values

The same context data structure set with GearmanClient::setContext()

See Also

  • GearmanClient::setContext() - Set application context


Get the application data (deprecated)

  • « GearmanClient::context
  • GearmanClient::do »
  • PHP Manual
  • GearmanClient
  • Get the application data (deprecated)

GearmanClient::data

(PECL gearman <= 0.5.0)

GearmanClient::data — Get the application data (deprecated)

Description

public GearmanClient::data ( void ) : string

Get the application data previously set with GearmanClient::setData().

Note:

This method was replaced by GearmanClient::setContext() in the 0.6.0 release of the Gearman extension.

Parameters

This function has no parameters.

Return Values

The same string data set with GearmanClient::setData()

See Also

  • GearmanClient::setData() - Set application data (deprecated)


Run a single task and return a result [deprecated]

  • « GearmanClient::data
  • GearmanClient::doBackground »
  • PHP Manual
  • GearmanClient
  • Run a single task and return a result [deprecated]

GearmanClient::do

(PECL gearman >= 0.5.0)

GearmanClient::do — Run a single task and return a result [deprecated]

Description

public GearmanClient::do ( string $function_name , string $workload [, string $unique ] ) : string

The GearmanClient::do() method is deprecated as of pecl/gearman 1.0.0. Use GearmanClient::doNormal().

Parameters

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

unique

A unique ID used to identify a particular task

Return Values

A string representing the results of running a task.

Examples

Example #1 Simple job submission with immediate return

<?php

# Client code

echo "Starting\n";

# Create our client object.
$gmclient= new GearmanClient();

# Add default server (localhost).
$gmclient->addServer();

echo "Sending job\n";

$result = $gmclient->doNormal("reverse", "Hello!");

echo "Success: $result\n";

?>
<?php

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server. Change the worker function to
# "reverse_fn_fast" for a faster worker with no output.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
  if ($gmworker->returnCode() != GEARMAN_SUCCESS)
  {
    echo "return_code: " . $gmworker->returnCode() . "\n";
    break;
  }
}

function reverse_fn($job)
{
  return strrev($job->workload());
}

?>

The above example will output something similar to:

Starting
Sending job
Success: !olleH

Example #2 Submitting a job and retrieving incremental status

A job is submitted and the script loops to retrieve status information. The worker has an artificial delay which results in a long running job and sends status and data as processing occurs. Each subsequent call to GearmanClient::do() produces status information on the running job.

<?php

# Client code

# Create our client object.
$gmclient= new GearmanClient();

# Add default server (localhost).
$gmclient->addServer();

echo "Sending job\n";

# Send reverse job
do
{
  $result = $gmclient->doNormal("reverse", "Hello!");
  # Check for various return packets and errors.

  switch($gmclient->returnCode())
  {
    case GEARMAN_WORK_DATA:
      echo "Data: $result\n";
      break;
    case GEARMAN_WORK_STATUS:
      list($numerator, $denominator)= $gmclient->doStatus();
      echo "Status: $numerator/$denominator complete\n";
      break;
    case GEARMAN_WORK_FAIL:
      echo "Failed\n";
      exit;
    case GEARMAN_SUCCESS:
      break;
    default:
      echo "RET: " . $gmclient->returnCode() . "\n";
      echo "Error: " . $gmclient->error() . "\n";
      echo "Errno: " . $gmclient->getErrno() . "\n";
      exit;
  }
}
while($gmclient->returnCode() != GEARMAN_SUCCESS);

echo "Success: $result\n";

?>
<?php

# Worker code

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
  if ($gmworker->returnCode() != GEARMAN_SUCCESS)
  {
    echo "return_code: " . $gmworker->returnCode() . "\n";
    break;
  }
}

function reverse_fn($job)
{
  echo "Received job: " . $job->handle() . "\n";

  $workload = $job->workload();
  $workload_size = $job->workloadSize();

  echo "Workload: $workload ($workload_size)\n";

  # This status loop is not needed, just showing how it works
  for ($x= 0; $x < $workload_size; $x++)
  {
    echo "Sending status: " + $x + 1 . "/$workload_size complete\n";
    $job->sendStatus($x+1, $workload_size);
    $job->sendData(substr($workload, $x, 1));
    sleep(1);
  }

  $result= strrev($workload);
  echo "Result: $result\n";

  # Return what we want to send back to the client.
  return $result;
}

?>

The above example will output something similar to:

Worker output:

Starting
Waiting for job...
Received job: H:foo.local:106
Workload: Hello! (6)
1/6 complete
2/6 complete
3/6 complete
4/6 complete
5/6 complete
6/6 complete
Result: !olleH

Client output:

Starting
Sending job
Status: 1/6 complete
Data: H
Status: 2/6 complete
Data: e
Status: 3/6 complete
Data: l
Status: 4/6 complete
Data: l
Status: 5/6 complete
Data: o
Status: 6/6 complete
Data: !
Success: !olleH

See Also

  • GearmanClient::doHigh() - Run a single high priority task
  • GearmanClient::doLow() - Run a single low priority task
  • GearmanClient::doBackground() - Run a task in the background
  • GearmanClient::doHighBackground() - Run a high priority task in the background
  • GearmanClient::doLowBackground() - Run a low priority task in the background


Run a task in the background

  • « GearmanClient::do
  • GearmanClient::doHigh »
  • PHP Manual
  • GearmanClient
  • Run a task in the background

GearmanClient::doBackground

(PECL gearman >= 0.5.0)

GearmanClient::doBackground — Run a task in the background

Description

public GearmanClient::doBackground ( string $function_name , string $workload [, string $unique ] ) : string

Runs a task in the background, returning a job handle which can be used to get the status of the running task.

Parameters

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

unique

A unique ID used to identify a particular task

Return Values

The job handle for the submitted task.

Examples

Example #1 Submit and monitor a background job

The worker in this example has an artificial delay introduced to mimic a long running job. The client script periodically checks the status of the running job.

<?php

/* create our object */
$gmclient= new GearmanClient();

/* add the default server */
$gmclient->addServer();

/* run reverse client */
$job_handle = $gmclient->doBackground("reverse", "this is a test");

if ($gmclient->returnCode() != GEARMAN_SUCCESS)
{
  echo "bad return code\n";
  exit;
}

$done = false;
do
{
   sleep(3);
   $stat = $gmclient->jobStatus($job_handle);
   if (!$stat[0]) // the job is known so it is not done
      $done = true;
   echo "Running: " . ($stat[1] ? "true" : "false") . ", numerator: " . $stat[2] . ", denominator: " . $stat[3] . "\n";
}
while(!$done);

echo "done!\n";

?>

The above example will output something similar to:

Running: true, numerator: 3, denominator: 14
Running: true, numerator: 6, denominator: 14
Running: true, numerator: 9, denominator: 14
Running: true, numerator: 12, denominator: 14
Running: false, numerator: 0, denominator: 0
done!

See Also

  • GearmanClient::doNormal() - Run a single task and return a result
  • GearmanClient::doHigh() - Run a single high priority task
  • GearmanClient::doLow() - Run a single low priority task
  • GearmanClient::doHighBackground() - Run a high priority task in the background
  • GearmanClient::doLowBackground() - Run a low priority task in the background


Run a single high priority task

  • « GearmanClient::doBackground
  • GearmanClient::doHighBackground »
  • PHP Manual
  • GearmanClient
  • Run a single high priority task

GearmanClient::doHigh

(PECL gearman >= 0.5.0)

GearmanClient::doHigh — Run a single high priority task

Description

public GearmanClient::doHigh ( string $function_name , string $workload [, string $unique ] ) : string

Runs a single high priority task and returns a string representation of the result. It is up to the GearmanClient and GearmanWorker to agree on the format of the result. High priority tasks will get precedence over normal and low priority tasks in the job queue.

Parameters

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

unique

A unique ID used to identify a particular task

Return Values

A string representing the results of running a task.

See Also

  • GearmanClient::doNormal() - Run a single task and return a result
  • GearmanClient::doLow() - Run a single low priority task
  • GearmanClient::doBackground() - Run a task in the background
  • GearmanClient::doHighBackground() - Run a high priority task in the background
  • GearmanClient::doLowBackground() - Run a low priority task in the background


Run a high priority task in the background

  • « GearmanClient::doHigh
  • GearmanClient::doJobHandle »
  • PHP Manual
  • GearmanClient
  • Run a high priority task in the background

GearmanClient::doHighBackground

(PECL gearman >= 0.5.0)

GearmanClient::doHighBackground — Run a high priority task in the background

Description

public GearmanClient::doHighBackground ( string $function_name , string $workload [, string $unique ] ) : string

Runs a high priority task in the background, returning a job handle which can be used to get the status of the running task. High priority tasks take precedence over normal and low priority tasks in the job queue.

Parameters

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

unique

A unique ID used to identify a particular task

Return Values

The job handle for the submitted task.

See Also

  • GearmanClient::doNormal() - Run a single task and return a result
  • GearmanClient::doHigh() - Run a single high priority task
  • GearmanClient::doLow() - Run a single low priority task
  • GearmanClient::doBackground() - Run a task in the background
  • GearmanClient::doLowBackground() - Run a low priority task in the background


Get the job handle for the running task

  • « GearmanClient::doHighBackground
  • GearmanClient::doLow »
  • PHP Manual
  • GearmanClient
  • Get the job handle for the running task

GearmanClient::doJobHandle

(PECL gearman >= 0.5.0)

GearmanClient::doJobHandle — Get the job handle for the running task

Description

public GearmanClient::doJobHandle ( void ) : string

Gets that job handle for a running task. This should be used between repeated GearmanClient::doNormal() calls. The job handle can then be used to get information on the task.

Parameters

This function has no parameters.

Return Values

The job handle for the running task.

See Also

  • GearmanClient::jobStatus() - Get the status of a background job


Run a single low priority task

  • « GearmanClient::doJobHandle
  • GearmanClient::doLowBackground »
  • PHP Manual
  • GearmanClient
  • Run a single low priority task

GearmanClient::doLow

(PECL gearman >= 0.5.0)

GearmanClient::doLow — Run a single low priority task

Description

public GearmanClient::doLow ( string $function_name , string $workload [, string $unique ] ) : string

Runs a single low priority task and returns a string representation of the result. It is up to the GearmanClient and GearmanWorker to agree on the format of the result. Normal and high priority tasks will get precedence over low priority tasks in the job queue.

Parameters

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

unique

A unique ID used to identify a particular task

Return Values

A string representing the results of running a task.

See Also

  • GearmanClient::doNormal() - Run a single task and return a result
  • GearmanClient::doHigh() - Run a single high priority task
  • GearmanClient::doBackground() - Run a task in the background
  • GearmanClient::doHighBackground() - Run a high priority task in the background
  • GearmanClient::doLowBackground() - Run a low priority task in the background


Run a low priority task in the background

  • « GearmanClient::doLow
  • GearmanClient::doNormal »
  • PHP Manual
  • GearmanClient
  • Run a low priority task in the background

GearmanClient::doLowBackground

(PECL gearman >= 0.5.0)

GearmanClient::doLowBackground — Run a low priority task in the background

Description

public GearmanClient::doLowBackground ( string $function_name , string $workload [, string $unique ] ) : string

Runs a low priority task in the background, returning a job handle which can be used to get the status of the running task. Normal and high priority tasks take precedence over low priority tasks in the job queue.

Parameters

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

unique

A unique ID used to identify a particular task

Return Values

The job handle for the submitted task.

See Also

  • GearmanClient::doNormal() - Run a single task and return a result
  • GearmanClient::doHigh() - Run a single high priority task
  • GearmanClient::doLow() - Run a single low priority task
  • GearmanClient::doBackground() - Run a task in the background
  • GearmanClient::doHighBackground() - Run a high priority task in the background


Run a single task and return a result

  • « GearmanClient::doLowBackground
  • GearmanClient::doStatus »
  • PHP Manual
  • GearmanClient
  • Run a single task and return a result

GearmanClient::doNormal

(No version information available, might only be in Git)

GearmanClient::doNormal — Run a single task and return a result

Description

public GearmanClient::doNormal ( string $function_name , string $workload [, string $unique ] ) : string

Runs a single task and returns a string representation of the result. It is up to the GearmanClient and GearmanWorker to agree on the format of the result.

Parameters

function_name

A registered function the worker is to execute

workload

Serialized data to be processed

unique

A unique ID used to identify a particular task

Return Values

A string representing the results of running a task.

Examples

Example #1 Simple job submission with immediate return

<?php

?>
<?php

# Client code

echo "Starting\n";

# Create our client object.
$gmclient= new GearmanClient();

# Add default server (localhost).
$gmclient->addServer();

echo "Sending job\n";

$result = $gmclient->doNormal("reverse", "Hello!");

echo "Success: $result\n";

?>
<?php

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server. Change the worker function to
# "reverse_fn_fast" for a faster worker with no output.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
  if ($gmworker->returnCode() != GEARMAN_SUCCESS)
  {
    echo "return_code: " . $gmworker->returnCode() . "\n";
    break;
  }
}

function reverse_fn($job)
{
  return strrev($job->workload());
}

?>

The above example will output something similar to:

Starting
Sending job
Success: !olleH

Example #2 Submitting a job and retrieving incremental status

A job is submitted and the script loops to retrieve status information. The worker has an artificial delay which results in a long running job and sends status and data as processing occurs. Each subsequent call to GearmanClient::doNormal() produces status information on the running job.

<?php

# Client code

# Create our client object.
$gmclient= new GearmanClient();

# Add default server (localhost).
$gmclient->addServer();

echo "Sending job\n";

# Send reverse job
do
{
  $result = $gmclient->doNormal("reverse", "Hello!");
  # Check for various return packets and errors.

  switch($gmclient->returnCode())
  {
    case GEARMAN_WORK_DATA:
      echo "Data: $result\n";
      break;
    case GEARMAN_WORK_STATUS:
      list($numerator, $denominator)= $gmclient->doStatus();
      echo "Status: $numerator/$denominator complete\n";
      break;
    case GEARMAN_WORK_FAIL:
      echo "Failed\n";
      exit;
    case GEARMAN_SUCCESS:
      break;
    default:
      echo "RET: " . $gmclient->returnCode() . "\n";
      echo "Error: " . $gmclient->error() . "\n";
      echo "Errno: " . $gmclient->getErrno() . "\n";
      exit;
  }
}
while($gmclient->returnCode() != GEARMAN_SUCCESS);

echo "Success: $result\n";

?>
<?php

# Worker code

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
  if ($gmworker->returnCode() != GEARMAN_SUCCESS)
  {
    echo "return_code: " . $gmworker->returnCode() . "\n";
    break;
  }
}

function reverse_fn($job)
{
  echo "Received job: " . $job->handle() . "\n";

  $workload = $job->workload();
  $workload_size = $job->workloadSize();

  echo "Workload: $workload ($workload_size)\n";

  # This status loop is not needed, just showing how it works
  for ($x= 0; $x < $workload_size; $x++)
  {
    echo "Sending status: " + $x + 1 . "/$workload_size complete\n";
    $job->sendStatus($x+1, $workload_size);
    $job->sendData(substr($workload, $x, 1));
    sleep(1);
  }

  $result= strrev($workload);
  echo "Result: $result\n";

  # Return what we want to send back to the client.
  return $result;
}

?>

The above example will output something similar to:

Worker output:

Starting
Waiting for job...
Received job: H:foo.local:106
Workload: Hello! (6)
1/6 complete
2/6 complete
3/6 complete
4/6 complete
5/6 complete
6/6 complete
Result: !olleH

Client output:

Starting
Sending job
Status: 1/6 complete
Data: H
Status: 2/6 complete
Data: e
Status: 3/6 complete
Data: l
Status: 4/6 complete
Data: l
Status: 5/6 complete
Data: o
Status: 6/6 complete
Data: !
Success: !olleH

See Also

  • GearmanClient::doHigh() - Run a single high priority task
  • GearmanClient::doLow() - Run a single low priority task
  • GearmanClient::doBackground() - Run a task in the background
  • GearmanClient::doHighBackground() - Run a high priority task in the background
  • GearmanClient::doLowBackground() - Run a low priority task in the background


Get the status for the running task

  • « GearmanClient::doNormal
  • GearmanClient::echo »
  • PHP Manual
  • GearmanClient
  • Get the status for the running task

GearmanClient::doStatus

(PECL gearman >= 0.5.0)

GearmanClient::doStatus — Get the status for the running task

Description

public GearmanClient::doStatus ( void ) : array

Returns the status for the running task. This should be used between repeated GearmanClient::doNormal() calls.

Parameters

This function has no parameters.

Return Values

An array representing the percentage completion given as a fraction, with the first element the numerator and the second element the denomintor.

Examples

Example #1 Get the status of a long running job

The worker in this example has an artificial delay added during processing of the string to be reversed. After each delay it calls GearmanJob::status() which the client then picks up.

<?php

echo "Starting\n";

# Create our client object.
$gmclient= new GearmanClient();

# Add default server (localhost).
$gmclient->addServer();

echo "Sending job\n";

# Send reverse job
do
{
  $result = $gmclient->doNormal("reverse", "Hello!");

  # Check for various return packets and errors.
  switch($gmclient->returnCode())
  {
    case GEARMAN_WORK_DATA:
      break;
    case GEARMAN_WORK_STATUS:
      # get the current job status
      list($numerator, $denominator)= $gmclient->doStatus();
      echo "Status: $numerator/$denominator complete\n";
      break;
    case GEARMAN_WORK_FAIL:
      echo "Failed\n";
      exit;
    case GEARMAN_SUCCESS:
      break;
    default:
      echo "RET: " . $gmclient->returnCode() . "\n";
      exit;
  }
}
while($gmclient->returnCode() != GEARMAN_SUCCESS);

echo "Success: $result\n";

?>

The above example will output something similar to:

Starting
Sending job
Status: 1/6 complete
Status: 2/6 complete
Status: 3/6 complete
Status: 4/6 complete
Status: 5/6 complete
Status: 6/6 complete
Success: !olleH

See Also

  • GearmanClient::doNormal() - Run a single task and return a result
  • GearmanJob::status() - Send status (deprecated)


Send data to all job servers to see if they echo it back [deprecated]

  • « GearmanClient::doStatus
  • GearmanClient::error »
  • PHP Manual
  • GearmanClient
  • Send data to all job servers to see if they echo it back [deprecated]

GearmanClient::echo

(PECL gearman >= 0.5.0)

GearmanClient::echo — Send data to all job servers to see if they echo it back [deprecated]

Description

public GearmanClient::echo ( string $workload ) : bool

The GearmanClient::echo() method is deprecated as of pecl/gearman 1.0.0. Use GearmanClient::ping().

Parameters

workload

Some arbitrary serialized data to be echo back

Return Values

Returns TRUE on success or FALSE on failure.


Returns an error string for the last error encountered

  • « GearmanClient::echo
  • GearmanClient::getErrno »
  • PHP Manual
  • GearmanClient
  • Returns an error string for the last error encountered

GearmanClient::error

(PECL gearman >= 0.5.0)

GearmanClient::error — Returns an error string for the last error encountered

Description

public GearmanClient::error ( void ) : string

Returns an error string for the last error encountered.

Parameters

This function has no parameters.

Return Values

A human readable error string.

See Also

  • GearmanClient::getErrno() - Get an errno value


Get an errno value

  • « GearmanClient::error
  • GearmanClient::jobStatus »
  • PHP Manual
  • GearmanClient
  • Get an errno value

GearmanClient::getErrno

(PECL gearman >= 0.5.0)

GearmanClient::getErrno — Get an errno value

Description

public GearmanClient::getErrno ( void ) : int

Value of errno in the case of a GEARMAN_ERRNO return value.

Parameters

This function has no parameters.

Return Values

A valid Gearman errno.

See Also

  • GearmanClient::error() - Returns an error string for the last error encountered


Get the status of a background job

  • « GearmanClient::getErrno
  • GearmanClient::ping »
  • PHP Manual
  • GearmanClient
  • Get the status of a background job

GearmanClient::jobStatus

gearman_job_status

(PECL gearman >= 0.5.0)

GearmanClient::jobStatus -- gearman_job_status — Get the status of a background job

Description

Object oriented style (method):

public GearmanClient::jobStatus ( string $job_handle ) : array

Gets the status for a background job given a job handle. The status information will specify whether the job is known, whether the job is currently running, and the percentage completion.

Parameters

job_handle

The job handle assigned by the Gearman server

Return Values

An array containing status information for the job corresponding to the supplied job handle. The first array element is a boolean indicating whether the job is even known, the second is a boolean indicating whether the job is still running, and the third and fourth elements correspond to the numerator and denominator of the fractional completion percentage, respectively.

Examples

Example #1 Monitor the status of a long running background job

<?php

/* create our object */
$gmclient= new GearmanClient();

/* add the default server */
$gmclient->addServer();

/* run reverse client */
$job_handle = $gmclient->doBackground("reverse", "this is a test");

if ($gmclient->returnCode() != GEARMAN_SUCCESS)
{
  echo "bad return code\n";
  exit;
}

$done = false;
do
{
   sleep(3);
   $stat = $gmclient->jobStatus($job_handle);
   if (!$stat[0]) // the job is known so it is not done
      $done = true;
   echo "Running: " . ($stat[1] ? "true" : "false") . ", numerator: " . $stat[2] . ", denomintor: " . $stat[3] . "\n";
}
while(!$done);

echo "done!\n";

?>

The above example will output something similar to:

Running: true, numerator: 3, denomintor: 14
Running: true, numerator: 6, denomintor: 14
Running: true, numerator: 9, denomintor: 14
Running: true, numerator: 12, denomintor: 14
Running: false, numerator: 0, denomintor: 0
done!

See Also

  • GearmanClient::doStatus() - Get the status for the running task


Send data to all job servers to see if they echo it back

  • « GearmanClient::jobStatus
  • GearmanClient::removeOptions »
  • PHP Manual
  • GearmanClient
  • Send data to all job servers to see if they echo it back

GearmanClient::ping

(No version information available, might only be in Git)

GearmanClient::ping — Send data to all job servers to see if they echo it back

Description

public GearmanClient::ping ( string $workload ) : bool

Sends some arbitrary data to all job servers to see if they echo it back. The data sent is not used or processed in any other way. Primarily used for testing and debugging.

Parameters

workload

Some arbitrary serialized data to be echo back

Return Values

Returns TRUE on success or FALSE on failure.


Remove client options

  • « GearmanClient::ping
  • GearmanClient::returnCode »
  • PHP Manual
  • GearmanClient
  • Remove client options

GearmanClient::removeOptions

(PECL gearman >= 0.6.0)

GearmanClient::removeOptions — Remove client options

Description

public GearmanClient::removeOptions ( int $options ) : bool

Removes (unsets) one or more options.

Parameters

options

The options to be removed (unset)

Return Values

Always returns TRUE.


Get the last Gearman return code

  • « GearmanClient::removeOptions
  • GearmanClient::runTasks »
  • PHP Manual
  • GearmanClient
  • Get the last Gearman return code

GearmanClient::returnCode

(PECL gearman >= 0.5.0)

GearmanClient::returnCode — Get the last Gearman return code

Description

public GearmanClient::returnCode ( void ) : int

Returns the last Gearman return code.

Parameters

This function has no parameters.

Return Values

A valid Gearman return code.


Run a list of tasks in parallel

  • « GearmanClient::returnCode
  • GearmanClient::setClientCallback »
  • PHP Manual
  • GearmanClient
  • Run a list of tasks in parallel

GearmanClient::runTasks

(PECL gearman >= 0.5.0)

GearmanClient::runTasks — Run a list of tasks in parallel

Description

public GearmanClient::runTasks ( void ) : bool

For a set of tasks previously added with GearmanClient::addTask(), GearmanClient::addTaskHigh(), GearmanClient::addTaskLow(), GearmanClient::addTaskBackground(), GearmanClient::addTaskHighBackground(), or GearmanClient::addTaskLowBackground(), this call starts running the tasks in parallel.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanClient::addTask() - Add a task to be run in parallel


Callback function when there is a data packet for a task (deprecated)

  • « GearmanClient::runTasks
  • GearmanClient::setCompleteCallback »
  • PHP Manual
  • GearmanClient
  • Callback function when there is a data packet for a task (deprecated)

GearmanClient::setClientCallback

(PECL gearman <= 0.5.0)

GearmanClient::setClientCallback — Callback function when there is a data packet for a task (deprecated)

Description

public GearmanClient::setClientCallback ( callable $callback ) : void

Sets the callback function for accepting data packets for a task. The callback function should take a single argument, a GearmanTask object.

Note:

This method has been replaced by GearmanClient::setDataCallback() in the 0.6.0 release of the Gearman extension.

Parameters

callback

A function or method to call

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates


Set a function to be called on task completion

  • « GearmanClient::setClientCallback
  • GearmanClient::setContext »
  • PHP Manual
  • GearmanClient
  • Set a function to be called on task completion

GearmanClient::setCompleteCallback

(PECL gearman >= 0.5.0)

GearmanClient::setCompleteCallback — Set a function to be called on task completion

Description

public GearmanClient::setCompleteCallback ( callable $callback ) : bool

Use to set a function to be called when a GearmanTask is completed, or when GearmanJob::sendComplete() is invoked by a worker (whichever happens first).

This callback executes only when executing a GearmanTask using GearmanClient::runTasks(). It is not used for individual jobs.

Parameters

callback

A function to be called

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates


Set application context

  • « GearmanClient::setCompleteCallback
  • GearmanClient::setCreatedCallback »
  • PHP Manual
  • GearmanClient
  • Set application context

GearmanClient::setContext

(PECL gearman >= 0.6.0)

GearmanClient::setContext — Set application context

Description

public GearmanClient::setContext ( string $context ) : bool

Sets an arbitrary string to provide application context that can later be retrieved by GearmanClient::context().

Parameters

context

Arbitrary context data

Return Values

Always returns TRUE.

See Also

  • GearmanClient::context() - Get the application context


Set a callback for when a task is queued

  • « GearmanClient::setContext
  • GearmanClient::setData »
  • PHP Manual
  • GearmanClient
  • Set a callback for when a task is queued

GearmanClient::setCreatedCallback

(PECL gearman >= 0.5.0)

GearmanClient::setCreatedCallback — Set a callback for when a task is queued

Description

public GearmanClient::setCreatedCallback ( string $callback ) : bool

Sets a function to be called when a task is received and queued by the Gearman job server. The callback should accept a single argument, a GearmanTask object.

Parameters

callback

A function to call

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates


Set application data (deprecated)

  • « GearmanClient::setCreatedCallback
  • GearmanClient::setDataCallback »
  • PHP Manual
  • GearmanClient
  • Set application data (deprecated)

GearmanClient::setData

(PECL gearman <= 0.5.0)

GearmanClient::setData — Set application data (deprecated)

Description

public GearmanClient::setData ( string $data ) : bool

Sets some arbitrary application data that can later be retrieved by GearmanClient::data().

Note:

This method has been replaced by GearmanCient::setContext() in the 0.6.0 release of the Gearman extension.

Parameters

data

Return Values

Always returns TRUE.

See Also

  • GearmanClient::data() - Get the application data (deprecated)


Callback function when there is a data packet for a task

  • « GearmanClient::setData
  • GearmanClient::setExceptionCallback »
  • PHP Manual
  • GearmanClient
  • Callback function when there is a data packet for a task

GearmanClient::setDataCallback

(PECL gearman >= 0.6.0)

GearmanClient::setDataCallback — Callback function when there is a data packet for a task

Description

public GearmanClient::setDataCallback ( callable $callback ) : bool

Sets the callback function for accepting data packets for a task. The callback function should take a single argument, a GearmanTask object.

Parameters

callback

A function or method to call

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates


Set a callback for worker exceptions

  • « GearmanClient::setDataCallback
  • GearmanClient::setFailCallback »
  • PHP Manual
  • GearmanClient
  • Set a callback for worker exceptions

GearmanClient::setExceptionCallback

(PECL gearman >= 0.5.0)

GearmanClient::setExceptionCallback — Set a callback for worker exceptions

Description

public GearmanClient::setExceptionCallback ( callable $callback ) : bool

Specifies a function to call when a worker for a task sends an exception.

Parameters

callback

Function to call when the worker throws an exception

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates


Set callback for job failure

  • « GearmanClient::setExceptionCallback
  • GearmanClient::setOptions »
  • PHP Manual
  • GearmanClient
  • Set callback for job failure

GearmanClient::setFailCallback

(PECL gearman >= 0.5.0)

GearmanClient::setFailCallback — Set callback for job failure

Description

public GearmanClient::setFailCallback ( callable $callback ) : bool

Sets the callback function to be used when a task does not complete successfully. The function should accept a single argument, a GearmanTask object.

Parameters

callback

A function to call

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates


Set client options

  • « GearmanClient::setFailCallback
  • GearmanClient::setStatusCallback »
  • PHP Manual
  • GearmanClient
  • Set client options

GearmanClient::setOptions

(PECL gearman >= 0.5.0)

GearmanClient::setOptions — Set client options

Description

public GearmanClient::setOptions ( int $options ) : bool

Sets one or more client options.

Parameters

options

The options to be set

Return Values

Always returns TRUE.


Set a callback for collecting task status

  • « GearmanClient::setOptions
  • GearmanClient::setTimeout »
  • PHP Manual
  • GearmanClient
  • Set a callback for collecting task status

GearmanClient::setStatusCallback

(PECL gearman >= 0.5.0)

GearmanClient::setStatusCallback — Set a callback for collecting task status

Description

public GearmanClient::setStatusCallback ( callable $callback ) : bool

Sets a callback function used for getting updated status information from a worker. The function should accept a single argument, a GearmanTask object.

Parameters

callback

A function to call

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates


Set socket I/O activity timeout

  • « GearmanClient::setStatusCallback
  • GearmanClient::setWarningCallback »
  • PHP Manual
  • GearmanClient
  • Set socket I/O activity timeout

GearmanClient::setTimeout

(PECL gearman >= 0.6.0)

GearmanClient::setTimeout — Set socket I/O activity timeout

Description

public GearmanClient::setTimeout ( int $timeout ) : bool

Sets the timeout for socket I/O activity.

Parameters

timeout

An interval of time in milliseconds

Return Values

Always returns TRUE.


Set a callback for worker warnings

  • « GearmanClient::setTimeout
  • GearmanClient::setWorkloadCallback »
  • PHP Manual
  • GearmanClient
  • Set a callback for worker warnings

GearmanClient::setWarningCallback

(PECL gearman >= 0.5.0)

GearmanClient::setWarningCallback — Set a callback for worker warnings

Description

public GearmanClient::setWarningCallback ( callable $callback ) : bool

Sets a function to be called when a worker sends a warning. The callback should accept a single argument, a GearmanTask object.

Parameters

callback

A function to call

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates


Set a callback for accepting incremental data updates

  • « GearmanClient::setWarningCallback
  • GearmanClient::timeout »
  • PHP Manual
  • GearmanClient
  • Set a callback for accepting incremental data updates

GearmanClient::setWorkloadCallback

(PECL gearman >= 0.5.0)

GearmanClient::setWorkloadCallback — Set a callback for accepting incremental data updates

Description

public GearmanClient::setWorkloadCallback ( callable $callback ) : bool

Sets a function to be called when a worker needs to send back data prior to job completion. A worker can do this when it needs to send updates, send partial results, or flush data during long running jobs. The callback should accept a single argument, a GearmanTask object.

Parameters

callback

A function to call

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings


Get current socket I/O activity timeout value

  • « GearmanClient::setWorkloadCallback
  • GearmanJob »
  • PHP Manual
  • GearmanClient
  • Get current socket I/O activity timeout value

GearmanClient::timeout

(PECL gearman >= 0.6.0)

GearmanClient::timeout — Get current socket I/O activity timeout value

Description

public GearmanClient::timeout ( void ) : int

Returns the timeout in milliseconds to wait for I/O activity.

Parameters

This function has no parameters.

Return Values

Timeout in milliseconds to wait for I/O activity. A negative value means an infinite timeout.

See Also

  • GearmanClient::setTimeout() - Set socket I/O activity timeout


The GearmanJob class

(PECL gearman >= 0.5.0)

Introduction

Class synopsis

GearmanJob {
/* Methods */
public complete ( string $result ) : bool
public __construct ( void )
public data ( string $data ) : bool
public exception ( string $exception ) : bool
public fail ( void ) : bool
public functionName ( void ) : string
public handle ( void ) : string
public returnCode ( void ) : int
public sendComplete ( string $result ) : bool
public sendData ( string $data ) : bool
public sendException ( string $exception ) : bool
public sendFail ( void ) : bool
public sendStatus ( int $numerator , int $denominator ) : bool
public sendWarning ( string $warning ) : bool
public setReturn ( int $gearman_return_t ) : bool
public status ( int $numerator , int $denominator ) : bool
public unique ( void ) : string
public warning ( string $warning ) : bool
public workload ( void ) : string
public workloadSize ( void ) : int
}

Table of Contents

  • GearmanJob::complete — Send the result and complete status (deprecated)
  • GearmanJob::__construct — Create a GearmanJob instance
  • GearmanJob::data — Send data for a running job (deprecated)
  • GearmanJob::exception — Send exception for running job (deprecated)
  • GearmanJob::fail — Send fail status (deprecated)
  • GearmanJob::functionName — Get function name
  • GearmanJob::handle — Get the job handle
  • GearmanJob::returnCode — Get last return code
  • GearmanJob::sendComplete — Send the result and complete status
  • GearmanJob::sendData — Send data for a running job
  • GearmanJob::sendException — Send exception for running job (exception)
  • GearmanJob::sendFail — Send fail status
  • GearmanJob::sendStatus — Send status
  • GearmanJob::sendWarning — Send a warning
  • GearmanJob::setReturn — Set a return value
  • GearmanJob::status — Send status (deprecated)
  • GearmanJob::unique — Get the unique identifier
  • GearmanJob::warning — Send a warning (deprecated)
  • GearmanJob::workload — Get workload
  • GearmanJob::workloadSize — Get size of work load


Send the result and complete status (deprecated)

  • « GearmanJob
  • GearmanJob::__construct »
  • PHP Manual
  • GearmanJob
  • Send the result and complete status (deprecated)

GearmanJob::complete

(PECL gearman <= 0.5.0)

GearmanJob::complete — Send the result and complete status (deprecated)

Description

public GearmanJob::complete ( string $result ) : bool

Sends result data and the complete status update for this job.

Note:

This method has been replaced by GearmanJob::sendComplete() in the 0.6.0 release of the Gearman extension.

Parameters

result

Serialized result data.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanJob::sendFail() - Send fail status
  • GearmanJob::setReturn() - Set a return value


Create a GearmanJob instance

  • « GearmanJob::complete
  • GearmanJob::data »
  • PHP Manual
  • GearmanJob
  • Create a GearmanJob instance

GearmanJob::__construct

(PECL gearman >= 0.5.0)

GearmanJob::__construct — Create a GearmanJob instance

Description

public GearmanJob::__construct ( void )

Creates a GearmanJob instance representing a job the worker is to complete.

Parameters

This function has no parameters.

Return Values

A GearmanJob object.


Send data for a running job (deprecated)

  • « GearmanJob::__construct
  • GearmanJob::exception »
  • PHP Manual
  • GearmanJob
  • Send data for a running job (deprecated)

GearmanJob::data

(PECL gearman <= 0.5.0)

GearmanJob::data — Send data for a running job (deprecated)

Description

public GearmanJob::data ( string $data ) : bool

Sends data to the job server (and any listening clients) for this job.

Note:

This method has been replaced by GearmanJob::sendData() in the 0.6.0 release of the Gearman extension.

Parameters

data

Arbitrary serialized data.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanJob::workload() - Get workload
  • GearmanTask::data() - Get data returned for a task


Send exception for running job (deprecated)

  • « GearmanJob::data
  • GearmanJob::fail »
  • PHP Manual
  • GearmanJob
  • Send exception for running job (deprecated)

GearmanJob::exception

(PECL gearman <= 0.5.0)

GearmanJob::exception — Send exception for running job (deprecated)

Description

public GearmanJob::exception ( string $exception ) : bool

Sends the supplied exception when this job is running.

Note:

This method has been replaced by GearmanJob::sendException() in the 0.6.0 release of the Gearman extension.

Parameters

exception

An exception description.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanJob::setReturn() - Set a return value
  • GearmanJob::sendStatus() - Send status
  • GearmanJob::sendWarning() - Send a warning


Send fail status (deprecated)

  • « GearmanJob::exception
  • GearmanJob::functionName »
  • PHP Manual
  • GearmanJob
  • Send fail status (deprecated)

GearmanJob::fail

(PECL gearman <= 0.5.0)

GearmanJob::fail — Send fail status (deprecated)

Description

public GearmanJob::fail ( void ) : bool

Sends failure status for this job, indicating that the job failed in a known way (as opposed to failing due to a thrown exception).

Note:

This method has been replaced by GearmanJob::sendFail() in the 0.6.0 release of the Gearman extension.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanJob::sendException() - Send exception for running job (exception)
  • GearmanJob::setReturn() - Set a return value
  • GearmanJob::sendStatus() - Send status
  • GearmanJob::sendWarning() - Send a warning


Get function name

  • « GearmanJob::fail
  • GearmanJob::handle »
  • PHP Manual
  • GearmanJob
  • Get function name

GearmanJob::functionName

(PECL gearman >= 0.5.0)

GearmanJob::functionName — Get function name

Description

public GearmanJob::functionName ( void ) : string

Returns the function name for this job. This is the function the work will execute to perform the job.

Parameters

This function has no parameters.

Return Values

The name of a function.

See Also

  • GearmanTask::function() - Get associated function name (deprecated)


Get the job handle

  • « GearmanJob::functionName
  • GearmanJob::returnCode »
  • PHP Manual
  • GearmanJob
  • Get the job handle

GearmanJob::handle

(PECL gearman >= 0.5.0)

GearmanJob::handle — Get the job handle

Description

public GearmanJob::handle ( void ) : string

Returns the opaque job handle assigned by the job server.

Parameters

This function has no parameters.

Return Values

An opaque job handle.

See Also

  • GearmanTask::jobHandle() - Get the job handle


Get last return code

  • « GearmanJob::handle
  • GearmanJob::sendComplete »
  • PHP Manual
  • GearmanJob
  • Get last return code

GearmanJob::returnCode

(PECL gearman >= 0.5.0)

GearmanJob::returnCode — Get last return code

Description

public GearmanJob::returnCode ( void ) : int

Returns the last return code issued by the job server.

Parameters

This function has no parameters.

Return Values

A valid Gearman return code.

See Also

  • GearmanTask::returnCode() - Get the last return code


Send the result and complete status

  • « GearmanJob::returnCode
  • GearmanJob::sendData »
  • PHP Manual
  • GearmanJob
  • Send the result and complete status

GearmanJob::sendComplete

(PECL gearman >= 0.6.0)

GearmanJob::sendComplete — Send the result and complete status

Description

public GearmanJob::sendComplete ( string $result ) : bool

Sends result data and the complete status update for this job.

Parameters

result

Serialized result data.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanJob::sendFail() - Send fail status
  • GearmanJob::setReturn() - Set a return value


Send data for a running job

  • « GearmanJob::sendComplete
  • GearmanJob::sendException »
  • PHP Manual
  • GearmanJob
  • Send data for a running job

GearmanJob::sendData

(PECL gearman >= 0.6.0)

GearmanJob::sendData — Send data for a running job

Description

public GearmanJob::sendData ( string $data ) : bool

Sends data to the job server (and any listening clients) for this job.

Parameters

data

Arbitrary serialized data.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanJob::workload() - Get workload
  • GearmanTask::data() - Get data returned for a task


Send exception for running job (exception)

  • « GearmanJob::sendData
  • GearmanJob::sendFail »
  • PHP Manual
  • GearmanJob
  • Send exception for running job (exception)

GearmanJob::sendException

(PECL gearman >= 0.6.0)

GearmanJob::sendException — Send exception for running job (exception)

Description

public GearmanJob::sendException ( string $exception ) : bool

Sends the supplied exception when this job is running.

Parameters

exception

An exception description.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanJob::setReturn() - Set a return value
  • GearmanJob::sendStatus() - Send status
  • GearmanJob::sendWarning() - Send a warning


Send fail status

  • « GearmanJob::sendException
  • GearmanJob::sendStatus »
  • PHP Manual
  • GearmanJob
  • Send fail status

GearmanJob::sendFail

(PECL gearman >= 0.6.0)

GearmanJob::sendFail — Send fail status

Description

public GearmanJob::sendFail ( void ) : bool

Sends failure status for this job, indicating that the job failed in a known way (as opposed to failing due to a thrown exception).

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanJob::sendException() - Send exception for running job (exception)
  • GearmanJob::setReturn() - Set a return value
  • GearmanJob::sendStatus() - Send status
  • GearmanJob::sendWarning() - Send a warning


Send status

  • « GearmanJob::sendFail
  • GearmanJob::sendWarning »
  • PHP Manual
  • GearmanJob
  • Send status

GearmanJob::sendStatus

(PECL gearman >= 0.6.0)

GearmanJob::sendStatus — Send status

Description

public GearmanJob::sendStatus ( int $numerator , int $denominator ) : bool

Sends status information to the job server and any listening clients. Use this to specify what percentage of the job has been completed.

Parameters

numerator

The numerator of the precentage completed expressed as a fraction.

denominator

The denominator of the precentage completed expressed as a fraction.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanClient::jobStatus() - Get the status of a background job
  • GearmanTask::taskDenominator() - Get completion percentage denominator
  • GearmanTask::taskNumerator() - Get completion percentage numerator


Send a warning

  • « GearmanJob::sendStatus
  • GearmanJob::setReturn »
  • PHP Manual
  • GearmanJob
  • Send a warning

GearmanJob::sendWarning

(PECL gearman >= 0.6.0)

GearmanJob::sendWarning — Send a warning

Description

public GearmanJob::sendWarning ( string $warning ) : bool

Sends a warning for this job while it is running.

Parameters

warning

A warning message.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanJob::sendComplete() - Send the result and complete status
  • GearmanJob::sendException() - Send exception for running job (exception)
  • GearmanJob::sendFail() - Send fail status


Set a return value

  • « GearmanJob::sendWarning
  • GearmanJob::status »
  • PHP Manual
  • GearmanJob
  • Set a return value

GearmanJob::setReturn

(PECL gearman >= 0.5.0)

GearmanJob::setReturn — Set a return value

Description

public GearmanJob::setReturn ( int $gearman_return_t ) : bool

Sets the return value for this job, indicates how the job completed.

Parameters

gearman_return_t

A valid Gearman return value.

Return Values

Description...


Send status (deprecated)

  • « GearmanJob::setReturn
  • GearmanJob::unique »
  • PHP Manual
  • GearmanJob
  • Send status (deprecated)

GearmanJob::status

(PECL gearman <= 0.5.0)

GearmanJob::status — Send status (deprecated)

Description

public GearmanJob::status ( int $numerator , int $denominator ) : bool

Sends status information to the job server and any listening clients. Use this to specify what percentage of the job has been completed.

Note:

This method has been replaced by GearmanJob::sendStatus() in the 0.6.0 release of the Gearman extenstion.

Parameters

numerator

The numerator of the precentage completed expressed as a fraction.

denominator

The denominator of the precentage completed expressed as a fraction.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanClient::jobStatus() - Get the status of a background job
  • GearmanTask::taskDenominator() - Get completion percentage denominator
  • GearmanTask::taskNumerator() - Get completion percentage numerator


Get the unique identifier

  • « GearmanJob::status
  • GearmanJob::warning »
  • PHP Manual
  • GearmanJob
  • Get the unique identifier

GearmanJob::unique

(PECL gearman >= 0.5.0)

GearmanJob::unique — Get the unique identifier

Description

public GearmanJob::unique ( void ) : string

Returns the unique identifiter for this job. The identifier is assigned by the client.

Parameters

This function has no parameters.

Return Values

An opaque unique identifier.

See Also

  • GearmanClient::do() - Run a single task and return a result [deprecated]
  • GearmanTask::uuid() - Get the unique identifier for a task (deprecated)


Send a warning (deprecated)

  • « GearmanJob::unique
  • GearmanJob::workload »
  • PHP Manual
  • GearmanJob
  • Send a warning (deprecated)

GearmanJob::warning

(PECL gearman <= 0.5.0)

GearmanJob::warning — Send a warning (deprecated)

Description

public GearmanJob::warning ( string $warning ) : bool

Sends a warning for this job while it is running.

Note:

This method has been replaced by GearmanJob::sendWarning() in the 0.6.0 release of the Gearman extension.

Parameters

warning

A warning messages.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • GearmanJob::sendComplete() - Send the result and complete status
  • GearmanJob::sendException() - Send exception for running job (exception)
  • GearmanJob::sendFail() - Send fail status


Get workload

  • « GearmanJob::warning
  • GearmanJob::workloadSize »
  • PHP Manual
  • GearmanJob
  • Get workload

GearmanJob::workload

(PECL gearman >= 0.5.0)

GearmanJob::workload — Get workload

Description

public GearmanJob::workload ( void ) : string

Returns the workload for the job. This is serialized data that is to be processed by the worker.

Parameters

This function has no parameters.

Return Values

Serialized data.

See Also

  • GearmanClient::do() - Run a single task and return a result [deprecated]
  • GearmanJob::workloadSize() - Get size of work load


Get size of work load

  • « GearmanJob::workload
  • GearmanTask »
  • PHP Manual
  • GearmanJob
  • Get size of work load

GearmanJob::workloadSize

(PECL gearman >= 0.5.0)

GearmanJob::workloadSize — Get size of work load

Description

public GearmanJob::workloadSize ( void ) : int

Returns the size of the job's work load (the data the worker is to process) in bytes.

Parameters

This function has no parameters.

Return Values

The size in bytes.

See Also

  • GearmanJob::workload() - Get workload


The GearmanTask class

(PECL gearman >= 0.5.0)

Introduction

Class synopsis

GearmanTask {
/* Methods */
public __construct ( void )
public create ( void ) : GearmanTask
public data ( void ) : string
public dataSize ( void ) : int
public function ( void ) : string
public functionName ( void ) : string
public isKnown ( void ) : bool
public isRunning ( void ) : bool
public jobHandle ( void ) : string
public recvData ( int $data_len ) : array
public returnCode ( void ) : int
public sendData ( string $data ) : int
public sendWorkload ( string $data ) : int
public taskDenominator ( void ) : int
public taskNumerator ( void ) : int
public unique ( void ) : string
public uuid ( void ) : string
}

Table of Contents

  • GearmanTask::__construct — Create a GearmanTask instance
  • GearmanTask::create — Create a task (deprecated)
  • GearmanTask::data — Get data returned for a task
  • GearmanTask::dataSize — Get the size of returned data
  • GearmanTask::function — Get associated function name (deprecated)
  • GearmanTask::functionName — Get associated function name
  • GearmanTask::isKnown — Determine if task is known
  • GearmanTask::isRunning — Test whether the task is currently running
  • GearmanTask::jobHandle — Get the job handle
  • GearmanTask::recvData — Read work or result data into a buffer for a task
  • GearmanTask::returnCode — Get the last return code
  • GearmanTask::sendData — Send data for a task (deprecated)
  • GearmanTask::sendWorkload — Send data for a task
  • GearmanTask::taskDenominator — Get completion percentage denominator
  • GearmanTask::taskNumerator — Get completion percentage numerator
  • GearmanTask::unique — Get the unique identifier for a task
  • GearmanTask::uuid — Get the unique identifier for a task (deprecated)


Create a GearmanTask instance

  • « GearmanTask
  • GearmanTask::create »
  • PHP Manual
  • GearmanTask
  • Create a GearmanTask instance

GearmanTask::__construct

(PECL gearman >= 0.5.0)

GearmanTask::__construct — Create a GearmanTask instance

Description

public GearmanTask::__construct ( void )

Creates a GearmanTask instance representing a task to be submitted to a job server.

Parameters

This function has no parameters.

Return Values

A GearmanTask object.


Create a task (deprecated)

  • « GearmanTask::__construct
  • GearmanTask::data »
  • PHP Manual
  • GearmanTask
  • Create a task (deprecated)

GearmanTask::create

(PECL gearman <= 0.5.0)

GearmanTask::create — Create a task (deprecated)

Description

public GearmanTask::create ( void ) : GearmanTask

Returns a new GearmanTask object.

Note:

This method was removed in the 0.6.0 version of the Gearman extension.

Parameters

This function has no parameters.

Return Values

A GearmanTask oject or FALSE on failure.


Get data returned for a task

  • « GearmanTask::create
  • GearmanTask::dataSize »
  • PHP Manual
  • GearmanTask
  • Get data returned for a task

GearmanTask::data

(PECL gearman >= 0.5.0)

GearmanTask::data — Get data returned for a task

Description

public GearmanTask::data ( void ) : string

Returns data being returned for a task by a worker.

Parameters

This function has no parameters.

Return Values

The serialized data, or FALSE if no data is present.

See Also

  • GearmanTask::dataSize() - Get the size of returned data


Get the size of returned data

  • « GearmanTask::data
  • GearmanTask::function »
  • PHP Manual
  • GearmanTask
  • Get the size of returned data

GearmanTask::dataSize

(PECL gearman >= 0.5.0)

GearmanTask::dataSize — Get the size of returned data

Description

public GearmanTask::dataSize ( void ) : int

Returns the size of the data being returned for a task.

Parameters

This function has no parameters.

Return Values

The data size, or FALSE if there is no data.

See Also

  • GearmanTask::data() - Get data returned for a task


Get associated function name (deprecated)

  • « GearmanTask::dataSize
  • GearmanTask::functionName »
  • PHP Manual
  • GearmanTask
  • Get associated function name (deprecated)

GearmanTask::function

(PECL gearman <= 0.5.0)

GearmanTask::function — Get associated function name (deprecated)

Description

public GearmanTask::function ( void ) : string

Returns the name of the function this task is associated with, i.e., the function the Gearman worker calls.

Note:

This method has been replaced by GearmanTask::functionName() in the 0.6.0 release of the Gearman extension.

Parameters

This function has no parameters.

Return Values

A function name.


Get associated function name

  • « GearmanTask::function
  • GearmanTask::isKnown »
  • PHP Manual
  • GearmanTask
  • Get associated function name

GearmanTask::functionName

(PECL gearman >= 0.6.0)

GearmanTask::functionName — Get associated function name

Description

public GearmanTask::functionName ( void ) : string

Returns the name of the function this task is associated with, i.e., the function the Gearman worker calls.

Parameters

This function has no parameters.

Return Values

A function name.


Determine if task is known

  • « GearmanTask::functionName
  • GearmanTask::isRunning »
  • PHP Manual
  • GearmanTask
  • Determine if task is known

GearmanTask::isKnown

(PECL gearman >= 0.5.0)

GearmanTask::isKnown — Determine if task is known

Description

public GearmanTask::isKnown ( void ) : bool

Gets the status information for whether or not this task is known to the job server.

Parameters

This function has no parameters.

Return Values

TRUE if the task is known, FALSE otherwise.


Test whether the task is currently running

  • « GearmanTask::isKnown
  • GearmanTask::jobHandle »
  • PHP Manual
  • GearmanTask
  • Test whether the task is currently running

GearmanTask::isRunning

(PECL gearman >= 0.5.0)

GearmanTask::isRunning — Test whether the task is currently running

Description

public GearmanTask::isRunning ( void ) : bool

Indicates whether or not this task is currently running.

Parameters

This function has no parameters.

Return Values

TRUE if the task is running, FALSE otherwise.


Get the job handle

  • « GearmanTask::isRunning
  • GearmanTask::recvData »
  • PHP Manual
  • GearmanTask
  • Get the job handle

GearmanTask::jobHandle

gearman_job_handle

(PECL gearman >= 0.5.0)

GearmanTask::jobHandle -- gearman_job_handle — Get the job handle

Description

public GearmanTask::jobHandle ( void ) : string

Returns the job handle for this task.

Parameters

This function has no parameters.

Return Values

The opaque job handle.

See Also

  • GearmanClient::doJobHandle() - Get the job handle for the running task


Read work or result data into a buffer for a task

  • « GearmanTask::jobHandle
  • GearmanTask::returnCode »
  • PHP Manual
  • GearmanTask
  • Read work or result data into a buffer for a task

GearmanTask::recvData

(PECL gearman >= 0.5.0)

GearmanTask::recvData — Read work or result data into a buffer for a task

Description

public GearmanTask::recvData ( int $data_len ) : array

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.

Parameters

data_len

Length of data to be read.

Return Values

An array whose first element is the length of data read and the second is the data buffer. Returns FALSE if the read failed.

See Also

  • GearmanTask::sendData() - Send data for a task (deprecated)


Get the last return code

  • « GearmanTask::recvData
  • GearmanTask::sendData »
  • PHP Manual
  • GearmanTask
  • Get the last return code

GearmanTask::returnCode

(PECL gearman >= 0.5.0)

GearmanTask::returnCode — Get the last return code

Description

public GearmanTask::returnCode ( void ) : int

Returns the last Gearman return code for this task.

Parameters

This function has no parameters.

Return Values

A valid Gearman return code.

See Also

  • GearmanClient::returnCode() - Get the last Gearman return code


Send data for a task (deprecated)

  • « GearmanTask::returnCode
  • GearmanTask::sendWorkload »
  • PHP Manual
  • GearmanTask
  • Send data for a task (deprecated)

GearmanTask::sendData

(PECL gearman <= 0.5.0)

GearmanTask::sendData — Send data for a task (deprecated)

Description

public GearmanTask::sendData ( string $data ) : int

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.

Parameters

data

Data to send to the worker.

Return Values

The length of data sent, or FALSE if the send failed.

See Also

  • GearmanTask::recvData() - Read work or result data into a buffer for a task


Send data for a task

  • « GearmanTask::sendData
  • GearmanTask::taskDenominator »
  • PHP Manual
  • GearmanTask
  • Send data for a task

GearmanTask::sendWorkload

(PECL gearman >= 0.6.0)

GearmanTask::sendWorkload — Send data for a task

Description

public GearmanTask::sendWorkload ( string $data ) : int

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.

Parameters

data

Data to send to the worker.

Return Values

The length of data sent, or FALSE if the send failed.

See Also

  • GearmanTask::recvData() - Read work or result data into a buffer for a task


Get completion percentage denominator

  • « GearmanTask::sendWorkload
  • GearmanTask::taskNumerator »
  • PHP Manual
  • GearmanTask
  • Get completion percentage denominator

GearmanTask::taskDenominator

(PECL gearman >= 0.5.0)

GearmanTask::taskDenominator — Get completion percentage denominator

Description

public GearmanTask::taskDenominator ( void ) : int

Returns the denominator of the percentage of the task that is complete expressed as a fraction.

Parameters

This function has no parameters.

Return Values

A number between 0 and 100, or FALSE if cannot be determined.

See Also

  • GearmanTask::taskNumerator() - Get completion percentage numerator


Get completion percentage numerator

  • « GearmanTask::taskDenominator
  • GearmanTask::unique »
  • PHP Manual
  • GearmanTask
  • Get completion percentage numerator

GearmanTask::taskNumerator

(PECL gearman >= 0.5.0)

GearmanTask::taskNumerator — Get completion percentage numerator

Description

public GearmanTask::taskNumerator ( void ) : int

Returns the numerator of the percentage of the task that is complete expressed as a fraction.

Parameters

This function has no parameters.

Return Values

A number between 0 and 100, or FALSE if cannot be determined.

See Also

  • GearmanTask::taskDenominator() - Get completion percentage denominator


Get the unique identifier for a task

  • « GearmanTask::taskNumerator
  • GearmanTask::uuid »
  • PHP Manual
  • GearmanTask
  • Get the unique identifier for a task

GearmanTask::unique

(PECL gearman >= 0.6.0)

GearmanTask::unique — Get the unique identifier for a task

Description

public GearmanTask::unique ( void ) : string

Returns the unique identifier for this task. This is assigned by the GearmanClient, as opposed to the job handle which is set by the Gearman job server.

Parameters

This function has no parameters.

Return Values

The unique identifier, or FALSE if no identifier is assigned.

See Also

  • GearmanClient::do() - Run a single task and return a result [deprecated]
  • GearmanClient::addTask() - Add a task to be run in parallel


Get the unique identifier for a task (deprecated)

  • « GearmanTask::unique
  • GearmanWorker »
  • PHP Manual
  • GearmanTask
  • Get the unique identifier for a task (deprecated)

GearmanTask::uuid

(PECL gearman <= 0.5.0)

GearmanTask::uuid — Get the unique identifier for a task (deprecated)

Description

public GearmanTask::uuid ( void ) : string

Returns the unique identifier for this task. This is assigned by the GearmanClient, as opposed to the job handle which is set by the Gearman job server.

Note:

This method has been replaced by GearmanTask::unique() in the 0.6.0 release of the Gearman extension.

Parameters

This function has no parameters.

Return Values

The unique identifier, or FALSE if no identifier is assigned.

See Also

  • GearmanClient::do() - Run a single task and return a result [deprecated]
  • GearmanClient::addTask() - Add a task to be run in parallel


The GearmanWorker class

(PECL gearman >= 0.5.0)

Introduction

Class synopsis

GearmanWorker {
/* Methods */
public addFunction ( string $function_name , callable $function [, mixed &$context [, int $timeout ]] ) : bool
public addOptions ( int $option ) : bool
public addServer ([ string $host = 127.0.0.1 [, int $port = 4730 ]] ) : bool
public addServers ( string $servers = 127.0.0.1:4730 ) : bool
public clone ( void ) : void
public __construct ( void )
public echo ( string $workload ) : bool
public error ( void ) : string
public getErrno ( void ) : int
public options ( void ) : int
public register ( string $function_name [, int $timeout ] ) : bool
public removeOptions ( int $option ) : bool
public returnCode ( void ) : int
public setId ( string $id ) : bool
public setOptions ( int $option ) : bool
public setTimeout ( int $timeout ) : bool
public timeout ( void ) : int
public unregister ( string $function_name ) : bool
public unregisterAll ( void ) : bool
public wait ( void ) : bool
public work ( void ) : bool
}

Table of Contents

  • GearmanWorker::addFunction — Register and add callback function
  • GearmanWorker::addOptions — Add worker options
  • GearmanWorker::addServer — Add a job server
  • GearmanWorker::addServers — Add job servers
  • GearmanWorker::clone — Create a copy of the worker
  • GearmanWorker::__construct — Create a GearmanWorker instance
  • GearmanWorker::echo — Test job server response
  • GearmanWorker::error — Get the last error encountered
  • GearmanWorker::getErrno — Get errno
  • GearmanWorker::options — Get worker options
  • GearmanWorker::register — Register a function with the job server
  • GearmanWorker::removeOptions — Remove worker options
  • GearmanWorker::returnCode — Get last Gearman return code
  • GearmanWorker::setId — Give the worker an identifier so it can be tracked when asking gearmand for the list of available workers
  • GearmanWorker::setOptions — Set worker options
  • GearmanWorker::setTimeout — Set socket I/O activity timeout
  • GearmanWorker::timeout — Get socket I/O activity timeout
  • GearmanWorker::unregister — Unregister a function name with the job servers
  • GearmanWorker::unregisterAll — Unregister all function names with the job servers
  • GearmanWorker::wait — Wait for activity from one of the job servers
  • GearmanWorker::work — Wait for and perform jobs


Register and add callback function

  • « GearmanWorker
  • GearmanWorker::addOptions »
  • PHP Manual
  • GearmanWorker
  • Register and add callback function

GearmanWorker::addFunction

(PECL gearman >= 0.5.0)

GearmanWorker::addFunction — Register and add callback function

Description

public GearmanWorker::addFunction ( string $function_name , callable $function [, mixed &$context [, int $timeout ]] ) : bool

Registers a function name with the job server and specifies a callback corresponding to that function. Optionally specify extra application context data to be used when the callback is called and a timeout.

Parameters

function_name

The name of a function to register with the job server

function

A callback that gets called when a job for the registered function name is submitted

context

A reference to arbitrary application context data that can be modified by the worker function

timeout

An interval of time in seconds

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Simple worker making use of extra application context data

<?php

# get a gearman worker
$worker= new GearmanWorker();

# add the default server (localhost)
$worker->addServer();

# define a variable to hold application data
$count= 0;

# add the "reverse" function
$worker->addFunction("reverse", "reverse_cb", $count);

# start the worker
while ($worker->work());

function reverse_cb($job, &$count)
{
  $count++;
  return "$count: " . strrev($job->workload());
}

?>

Running a client that submits two jobs for the reverse function would have output similar to the following:

1: olleh
2: dlrow

See Also

  • GearmanClient::do() - Run a single task and return a result [deprecated]


Add worker options

  • « GearmanWorker::addFunction
  • GearmanWorker::addServer »
  • PHP Manual
  • GearmanWorker
  • Add worker options

GearmanWorker::addOptions

(PECL gearman >= 0.6.0)

GearmanWorker::addOptions — Add worker options

Description

public GearmanWorker::addOptions ( int $option ) : bool

Adds one or more options to the options previously set.

Parameters

option

The options to be added

Return Values

Always returns TRUE.

See Also

  • GearmanWorker::options() - Get worker options
  • GearmanClient::setOptions() - Set client options
  • GearmanClient::removeOptions() - Remove client options


Add a job server

  • « GearmanWorker::addOptions
  • GearmanWorker::addServers »
  • PHP Manual
  • GearmanWorker
  • Add a job server

GearmanWorker::addServer

(PECL gearman >= 0.5.0)

GearmanWorker::addServer — Add a job server

Description

public GearmanWorker::addServer ([ string $host = 127.0.0.1 [, int $port = 4730 ]] ) : bool

Adds a job server to this worker. This goes into a list of servers than can be used to run jobs. No socket I/O happens here.

Parameters

host

The job server host name.

port

The job server port.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Add alternate Gearman servers

<?php
$worker= new GearmanWorker();
$worker->addServer("10.0.0.1");
$worker->addServer("10.0.0.2", 7003);
?>

See Also

  • GearmanWorker::addServers() - Add job servers


Add job servers

  • « GearmanWorker::addServer
  • GearmanWorker::clone »
  • PHP Manual
  • GearmanWorker
  • Add job servers

GearmanWorker::addServers

(PECL gearman >= 0.5.0)

GearmanWorker::addServers — Add job servers

Description

public GearmanWorker::addServers ( string $servers = 127.0.0.1:4730 ) : bool

Adds one or more job servers to this worker. These go into a list of servers that can be used to run jobs. No socket I/O happens here.

Parameters

servers

A comma separated list of job servers in the format host:port. If no port is specified, it defaults to 4730.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Add two job servers

<?php

$worker= new GearmanWorker();
$worker->addServers("10.0.0.1,10.0.0.2:7003");

?>

See Also

  • GearmanWorker::addServer() - Add a job server


Create a copy of the worker

  • « GearmanWorker::addServers
  • GearmanWorker::__construct »
  • PHP Manual
  • GearmanWorker
  • Create a copy of the worker

GearmanWorker::clone

(PECL gearman >= 0.5.0)

GearmanWorker::clone — Create a copy of the worker

Description

public GearmanWorker::clone ( void ) : void

Creates a copy of the worker.

Parameters

This function has no parameters.

Return Values

A GearmanWorker object


Create a GearmanWorker instance

  • « GearmanWorker::clone
  • GearmanWorker::echo »
  • PHP Manual
  • GearmanWorker
  • Create a GearmanWorker instance

GearmanWorker::__construct

(PECL gearman >= 0.5.0)

GearmanWorker::__construct — Create a GearmanWorker instance

Description

public GearmanWorker::__construct ( void )

Creates a GearmanWorker instance representing a worker that connects to the job server and accepts tasks to run.

Parameters

This function has no parameters.

Return Values

A GearmanWorker object

See Also

  • GearmanWorker::clone() - Create a copy of the worker


Test job server response

  • « GearmanWorker::__construct
  • GearmanWorker::error »
  • PHP Manual
  • GearmanWorker
  • Test job server response

GearmanWorker::echo

(PECL gearman >= 0.6.0)

GearmanWorker::echo — Test job server response

Description

public GearmanWorker::echo ( string $workload ) : bool

Sends data to all job servers to see if they echo it back. This is a test function to see if job servers are responding properly.

Parameters

workload

Arbitrary serialized data

Return Values

Standard Gearman return value.

See Also

  • GearmanClient::echo() - Send data to all job servers to see if they echo it back [deprecated]


Get the last error encountered

  • « GearmanWorker::echo
  • GearmanWorker::getErrno »
  • PHP Manual
  • GearmanWorker
  • Get the last error encountered

GearmanWorker::error

(PECL gearman >= 0.5.0)

GearmanWorker::error — Get the last error encountered

Description

public GearmanWorker::error ( void ) : string

Returns an error string for the last error encountered.

Parameters

This function has no parameters.

Return Values

An error string.

See Also

  • GearmanWorker::getErrno() - Get errno


Get errno

  • « GearmanWorker::error
  • GearmanWorker::options »
  • PHP Manual
  • GearmanWorker
  • Get errno

GearmanWorker::getErrno

(PECL gearman >= 0.5.0)

GearmanWorker::getErrno — Get errno

Description

public GearmanWorker::getErrno ( void ) : int

Returns the value of errno in the case of a GEARMAN_ERRNO return value.

Parameters

This function has no parameters.

Return Values

A valid errno.

See Also

  • GearmanWorker::error() - Get the last error encountered


Get worker options

  • « GearmanWorker::getErrno
  • GearmanWorker::register »
  • PHP Manual
  • GearmanWorker
  • Get worker options

GearmanWorker::options

(PECL gearman >= 0.6.0)

GearmanWorker::options — Get worker options

Description

public GearmanWorker::options ( void ) : int

Gets the options previously set for the worker.

Parameters

This function has no parameters.

Return Values

The options currently set for the worker.

See Also

  • GearmanWorker::setOptions() - Set worker options


Register a function with the job server

  • « GearmanWorker::options
  • GearmanWorker::removeOptions »
  • PHP Manual
  • GearmanWorker
  • Register a function with the job server

GearmanWorker::register

(PECL gearman >= 0.6.0)

GearmanWorker::register — Register a function with the job server

Description

public GearmanWorker::register ( string $function_name [, int $timeout ] ) : bool

Registers a function name with the job server with an optional timeout. The timeout specifies how many seconds the server will wait before marking a job as failed. If the timeout is set to zero, there is no timeout.

Parameters

function_name

The name of a function to register with the job server

timeout

An interval of time in seconds

Return Values

A standard Gearman return value.

See Also

  • GearmanWorker::unregister() - Unregister a function name with the job servers
  • GearmanWorker::unregisterAll() - Unregister all function names with the job servers


Remove worker options

  • « GearmanWorker::register
  • GearmanWorker::returnCode »
  • PHP Manual
  • GearmanWorker
  • Remove worker options

GearmanWorker::removeOptions

(PECL gearman >= 0.6.0)

GearmanWorker::removeOptions — Remove worker options

Description

public GearmanWorker::removeOptions ( int $option ) : bool

Removes (unsets) one or more worker options.

Parameters

option

The options to be removed (unset)

Return Values

Always returns TRUE.

See Also

  • GearmanWorker::options() - Get worker options
  • GearmanWorker::setOptions() - Set worker options
  • GearmanWorker::addOptions() - Add worker options


Get last Gearman return code

  • « GearmanWorker::removeOptions
  • GearmanWorker::setId »
  • PHP Manual
  • GearmanWorker
  • Get last Gearman return code

GearmanWorker::returnCode

(PECL gearman >= 0.5.0)

GearmanWorker::returnCode — Get last Gearman return code

Description

public GearmanWorker::returnCode ( void ) : int

Returns the last Gearman return code.

Parameters

This function has no parameters.

Return Values

A valid Gearman return code.

See Also

  • GearmanWorker::error() - Get the last error encountered
  • GearmanWorker::getErrno() - Get errno


Give the worker an identifier so it can be tracked when asking gearmand for the list of available workers

  • « GearmanWorker::returnCode
  • GearmanWorker::setOptions »
  • PHP Manual
  • GearmanWorker
  • Give the worker an identifier so it can be tracked when asking gearmand for the list of available workers

GearmanWorker::setId

(No version information available, might only be in Git)

GearmanWorker::setId — Give the worker an identifier so it can be tracked when asking gearmand for the list of available workers

Description

public GearmanWorker::setId ( string $id ) : bool

Assigns the worker an identifier.

Parameters

id

A string identifier.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 GearmanWorker::setId() example

Set an identifier for a simple worker.

<?php
$worker= new GearmanWorker();
$worker->setId('test');
?>

The above example will output something similar to:

Run the following command:
gearadmin --workers

Output:
30 ::3a3a:3361:3361:3a33%976303667 - : test


Set worker options

  • « GearmanWorker::setId
  • GearmanWorker::setTimeout »
  • PHP Manual
  • GearmanWorker
  • Set worker options

GearmanWorker::setOptions

(PECL gearman >= 0.5.0)

GearmanWorker::setOptions — Set worker options

Description

public GearmanWorker::setOptions ( int $option ) : bool

Sets one or more options to the supplied value.

Parameters

option

The options to be set

Return Values

Always returns TRUE.

See Also

  • GearmanWorker::options() - Get worker options
  • GearmanWorker::addOptions() - Add worker options
  • GearmanWorker::removeOptions() - Remove worker options
  • GearmanClient::setOptions() - Set client options


Set socket I/O activity timeout

  • « GearmanWorker::setOptions
  • GearmanWorker::timeout »
  • PHP Manual
  • GearmanWorker
  • Set socket I/O activity timeout

GearmanWorker::setTimeout

(PECL gearman >= 0.6.0)

GearmanWorker::setTimeout — Set socket I/O activity timeout

Description

public GearmanWorker::setTimeout ( int $timeout ) : bool

Sets the interval of time to wait for socket I/O activity.

Parameters

timeout

An interval of time in milliseconds. A negative value indicates an infinite timeout.

Return Values

Always returns TRUE.

Examples

Example #1 A simple worker with a 5 second timeout

<?php

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server.
$gmworker->addFunction("reverse", "reverse_fn");

# Set the timeout to 5 seconds
$gmworker->setTimeout(5000);

echo "Waiting for job...\n";
while(@$gmworker->work() || $gmworker->returnCode() == GEARMAN_TIMEOUT)
{
  if ($gmworker->returnCode() == GEARMAN_TIMEOUT)
  {
    # Normally one would want to do something useful here ...
    echo "Timeout. Waiting for next job...\n";
    continue;
  }

  if ($gmworker->returnCode() != GEARMAN_SUCCESS)
  {
    echo "return_code: " . $gmworker->returnCode() . "\n";
    break;
  }
}

echo "Done\n";

function reverse_fn($job)
{
  return strrev($job->workload());
}

?>

Running the worker with no submitted jobs will generate output that looks like the following:

Starting
Waiting for job...
Timeout. Waiting for next job...
Timeout. Waiting for next job...
Timeout. Waiting for next job...

See Also

  • GearmanWorker::timeout() - Get socket I/O activity timeout


Get socket I/O activity timeout

  • « GearmanWorker::setTimeout
  • GearmanWorker::unregister »
  • PHP Manual
  • GearmanWorker
  • Get socket I/O activity timeout

GearmanWorker::timeout

(PECL gearman >= 0.6.0)

GearmanWorker::timeout — Get socket I/O activity timeout

Description

public GearmanWorker::timeout ( void ) : int

Returns the current time to wait, in milliseconds, for socket I/O activity.

Parameters

This function has no parameters.

Return Values

A time period is milliseconds. A negative value indicates an infinite timeout.

See Also

  • GearmanWorker::setTimeout() - Set socket I/O activity timeout


Unregister a function name with the job servers

  • « GearmanWorker::timeout
  • GearmanWorker::unregisterAll »
  • PHP Manual
  • GearmanWorker
  • Unregister a function name with the job servers

GearmanWorker::unregister

(PECL gearman >= 0.6.0)

GearmanWorker::unregister — Unregister a function name with the job servers

Description

public GearmanWorker::unregister ( string $function_name ) : bool

Unregisters a function name with the job servers ensuring that no more jobs (for that function) are sent to this worker.

Parameters

function_name

The name of a function to register with the job server

Return Values

A standard Gearman return value.

See Also

  • GearmanWorker::register() - Register a function with the job server
  • GearmanWorker::unregisterAll() - Unregister all function names with the job servers


Unregister all function names with the job servers

  • « GearmanWorker::unregister
  • GearmanWorker::wait »
  • PHP Manual
  • GearmanWorker
  • Unregister all function names with the job servers

GearmanWorker::unregisterAll

(PECL gearman >= 0.6.0)

GearmanWorker::unregisterAll — Unregister all function names with the job servers

Description

public GearmanWorker::unregisterAll ( void ) : bool

Unregisters all previously registered functions, ensuring that no more jobs are sent to this worker.

Parameters

This function has no parameters.

Return Values

A standard Gearman return value.

See Also

  • GearmanWorker::register() - Register a function with the job server
  • GearmanWorker::unregister() - Unregister a function name with the job servers


Wait for activity from one of the job servers

  • « GearmanWorker::unregisterAll
  • GearmanWorker::work »
  • PHP Manual
  • GearmanWorker
  • Wait for activity from one of the job servers

GearmanWorker::wait

(PECL gearman >= 0.6.0)

GearmanWorker::wait — Wait for activity from one of the job servers

Description

public GearmanWorker::wait ( void ) : bool

Causes the worker to wait for activity from one of the Gearman job servers when operating in non-blocking I/O mode. On failure, issues a E_WARNING with the last Gearman error encountered.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Running worker in non-blocking mode

<?php

echo "Starting\n";

# Create our worker object
$worker= new GearmanWorker();

# Make the worker non-blocking
$worker->addOptions(GEARMAN_WORKER_NON_BLOCKING);

# Add the default server (localhost, port 4730)
$worker->addServer();

# Add our reverse function
$worker->addFunction('reverse', 'reverse_fn');

# Try to grab a job
while (@$worker->work() ||
       $worker->returnCode() == GEARMAN_IO_WAIT ||
       $worker->returnCode() == GEARMAN_NO_JOBS)
{
  if ($worker->returnCode() == GEARMAN_SUCCESS)
    continue;

  echo "Waiting for next job...\n";
  if (!@$worker->wait())
  {
    if ($worker->returnCode() == GEARMAN_NO_ACTIVE_FDS)
    {
      # We are not connected to any servers, so wait a bit before
      # trying to reconnect.
      sleep(5);
      continue;
    }
    break;
  }
}

echo "Worker Error: " . $worker->error() . "\n";

function reverse_fn($job)
{
  return strrev($job->workload());
}

?>

See Also

  • GearmanWorker::work() - Wait for and perform jobs


Wait for and perform jobs

  • « GearmanWorker::wait
  • GearmanException »
  • PHP Manual
  • GearmanWorker
  • Wait for and perform jobs

GearmanWorker::work

(PECL gearman >= 0.5.0)

GearmanWorker::work — Wait for and perform jobs

Description

public GearmanWorker::work ( void ) : bool

Waits for a job to be assigned and then calls the appropriate callback function. Issues an E_WARNING with the last Gearman error if the return code is not one of GEARMAN_SUCCESS, GEARMAN_IO_WAIT, or GEARMAN_WORK_FAIL.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 GearmanWorker::work() example

<?php

# create the worker
$worker = new GearmanWorker();

# add the default job server (localhost)
$worker->addServer();

# add the reverse function
$worker->addFunction("reverse", "my_reverse_function");

# start te worker listening for job submissions
while ($worker->work());

function my_reverse_function($job)
{
  return strrev($job->workload());
}

?>

See Also

  • GearmanWorker::addFunction() - Register and add callback function


The GearmanException class

(PECL gearman >= 0.5.0)

Introduction

Class synopsis

GearmanException extends Exception {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Methods */
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


Net Gopher

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic Example
  • Gopher Functions
    • gopher_parsedir — Translate a gopher formatted directory entry into an associative array


Introduction

The gopher protocol, as defined by » RFC 1436, is generally considered the ancestor of the modern HTTP protocol. However, gopher was also intended to provide references to non-gopher resources including telnet, wais, nntp, and even http. This extension adds gopher support to PHP's URL Wrappers, and provides a helper function gopher_parsedir() to make sense of gopher formatted directory listings.


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/net_gopher


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.

Net_Gopher constants
Constant | Value | Description
GOPHER_DOCUMENT | 0 | Standard text/plain document.
GOPHER_DIRECTORY | 1 | A resource containing a gopher formatted directory listing.
GOPHER_BINHEX | 4 | A BinHex encoded binary file.
GOPHER_DOSBINARY | 5 | A DOS formatted binary archive.
GOPHER_UUENCODED | 6 | A UUEncoded file.
GOPHER_BINARY | 9 | A generic binary file.
GOPHER_INFO | 255 | An Informational entry
GOPHER_HTTP | 254 | A reference to an HTTP resource.
GOPHER_UNKNOWN | -1 | An unrecognized entry.


  • « Predefined Constants
  • Basic Example »
  • PHP Manual
  • Gopher
  • Examples

Examples

Table of Contents

  • Basic Example


  • « Examples
  • Gopher Functions »
  • PHP Manual
  • Examples
  • Basic Example

Basic Example

<?php
readfile("gopher://gopher.example.com/somedocument");
?>


Gopher Functions

Table of Contents

  • gopher_parsedir — Translate a gopher formatted directory entry into an associative array


Translate a gopher formatted directory entry into an associative array

  • « Gopher Functions
  • Gupnp »
  • PHP Manual
  • Gopher Functions
  • Translate a gopher formatted directory entry into an associative array

gopher_parsedir

(PECL net_gopher >= 0.1)

gopher_parsedir — Translate a gopher formatted directory entry into an associative array

Description

gopher_parsedir ( string $dirent ) : array

gopher_parsedir() parses a gopher formatted directory entry into an associative array.

While gopher returns text/plain documents for actual document requests. A request to a directory (such as /) will return specially encoded series of lines with each line being one directory entry or information line.

Parameters

dirent

The directory entry.

Return Values

Returns an associative array whose components are:

  • type - One of the GOPHER_XXX constants.
  • title - The name of the resource.
  • path - The path of the resource.
  • host - The domain name of the host that has this document (or directory).
  • port - The port at which to connect on host.

Upon failure, the additional data entry of the returned array will hold the parsed line.

Examples

Example #1 Hypothetical output from gopher://gopher.example.com/

0All about my gopher site.               /allabout.txt               gopher.example.com    70
9A picture of my cat.                    /pics/cat.png               gopher.example.com    70
1A collection of my writings.            /stories                    gopher.example.com    70
hThe HTTP version of this site.          URL:http://www.example.com  gopher.example.com    70
1Mirror of this site in Spain.           /                           gopher.ejemplo.co.es  70
iWelcome to my gopher site.                                          error.host            1
iPlease select one of the options above                              error.host            1
iSend complaints to /dev/null                                        error.host            1
iLong live gopher!                                                   error.host            1

In the example above, the root directory at gopher.example.com knows about one DOCUMENT identified by 0 located at gopher://gopher.example.com:70/allabout.txt. It also knows about two other directory (which have their own listing files) at gopher://gopher.exmaple.com:70/stories and at gopher://gopher.ejemplo.co.es:70/. In addition there is a binary file, a link to an HTTP url, and several informative lines.

By passing each line of the directory listing into gopher_parsedir(), an associative array is formed containing a parsed out version of the data.

Example #2 Using gopher_parsedir()

<?php
$directory = file("gopher://gopher.example.com");

foreach($directory as $dirent) {
    print_r(gopher_parsedir($dirent));
}
?>

The above example will output:

Array (
  [type] => 0
  [title] => All about my gopher site.
  [path] => /allabout.txt
  [host] => gopher.example.com
  [port] => 70
)
Array (
  [type] => 9
  [title] => A picture of my cat.
  [path] => /pics/cat.png
  [host] => gopher.example.com
  [port] => 70
)
Array (
  [type] => 1
  [title] => A collection of my writings.
  [path] => /stories
  [host] => gopher.example.com
  [port] => 70
)
Array (
  [type] => 254
  [title] => The HTTP version of this site.
  [path] => URL:http://www.example.com
  [host] => gopher.example.com
  [port] => 70
)
Array (
  [type] => 1
  [title] => Mirror of this site in Spain.
  [path] => /
  [host] => gopher.ejemplo.co.es
  [port] => 70
)
Array (
  [type] => 255
  [title] => Welcome to my gopher site.
  [path] =>
  [host] => error.host
  [port] => 1
)
Array (
  [type] => 255
  [title] => Please select one of the options above.
  [path] =>
  [host] => error.host
  [port] => 1
)
Array (
  [type] => 255
  [title] => Send complaints to /dev/null
  [path] =>
  [host] => error.host
  [port] => 1
)
Array (
  [type] => 255
  [title] => Long live gopher!
  [path] =>
  [host] => error.host
  [port] => 1
)


Gupnp

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Browsing devices and services
    • Implementing the BinaryLight device
  • Gupnp Functions
    • gupnp_context_get_host_ip — Get the IP address
    • gupnp_context_get_port — Get the port
    • gupnp_context_get_subscription_timeout — Get the event subscription timeout
    • gupnp_context_host_path — Start hosting
    • gupnp_context_new — Create a new context
    • gupnp_context_set_subscription_timeout — Sets the event subscription timeout
    • gupnp_context_timeout_add — Sets a function to be called at regular intervals
    • gupnp_context_unhost_path — Stop hosting
    • gupnp_control_point_browse_start — Start browsing
    • gupnp_control_point_browse_stop — Stop browsing
    • gupnp_control_point_callback_set — Set control point callback
    • gupnp_control_point_new — Create a new control point
    • gupnp_device_action_callback_set — Set device callback function
    • gupnp_device_info_get_service — Get the service with type
    • gupnp_device_info_get — Get info of root device
    • gupnp_root_device_get_available — Check whether root device is available
    • gupnp_root_device_get_relative_location — Get the relative location of root device
    • gupnp_root_device_new — Create a new root device
    • gupnp_root_device_set_available — Set whether or not root_device is available
    • gupnp_root_device_start — Start main loop
    • gupnp_root_device_stop — Stop main loop
    • gupnp_service_action_get — Retrieves the specified action arguments
    • gupnp_service_action_return_error — Return error code
    • gupnp_service_action_return — Return successfully
    • gupnp_service_action_set — Sets the specified action return values
    • gupnp_service_freeze_notify — Freeze new notifications
    • gupnp_service_info_get_introspection — Get resource introspection of service
    • gupnp_service_info_get — Get full info of service
    • gupnp_service_introspection_get_state_variable — Returns the state variable data
    • gupnp_service_notify — Notifies listening clients
    • gupnp_service_proxy_action_get — Send action to the service and get value
    • gupnp_service_proxy_action_set — Send action to the service and set value
    • gupnp_service_proxy_add_notify — Sets up callback for variable change notification
    • gupnp_service_proxy_callback_set — Set service proxy callback for signal
    • gupnp_service_proxy_get_subscribed — Check whether subscription is valid to the service
    • gupnp_service_proxy_remove_notify — Cancels the variable change notification
    • gupnp_service_proxy_send_action — Send action with multiple parameters synchronously
    • gupnp_service_proxy_set_subscribed — (Un)subscribes to the service
    • gupnp_service_thaw_notify — Sends out any pending notifications and stops queuing of new ones


Introduction

GUPnP is an object-oriented open source framework for creating UPnP devices and control points, written in C using GObject and libsoup. This extension wraps GUPnP and provides similar API. All sources and additional documentation can be obtained from the » official site


Requirements

In order to use PECL/Gupnp functions you need to install the » gUPnP library version 0.12.7 or greater. It also requires glib-2.0, gssdp-1.0, libsoup-2.4 or greater for all of them.


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/gupnp

Note: If ./configure is having trouble finding the libgupnp files (for example, it was installed into a custom prefix directory), use ./configure --with-gupnp=$PREFIX, where $PREFIX is installation prefix of libgupnp.


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.

GUPNP_TYPE_BOOLEAN (integer)
GUPNP_TYPE_INT (integer)
GUPNP_TYPE_LONG (integer)
GUPNP_TYPE_DOUBLE (integer)
GUPNP_TYPE_FLOAT (integer)
GUPNP_TYPE_STRING (integer)
GUPNP_SIGNAL_DEVICE_PROXY_AVAILABLE (integer)
GUPNP_SIGNAL_DEVICE_PROXY_UNAVAILABLE (integer)
GUPNP_SIGNAL_SERVICE_PROXY_AVAILABLE (integer)
GUPNP_SIGNAL_SERVICE_PROXY_UNAVAILABLE (integer)
GUPNP_SIGNAL_ACTION_INVOKED (integer)
GUPNP_SIGNAL_NOTIFY_FAILED (integer)
GUPNP_SIGNAL_SUBSCRIPTION_LOST (integer)
GUPNP_CONTROL_ERROR_INVALID_ACTION (integer)
GUPNP_CONTROL_ERROR_INVALID_ARGS (integer)
GUPNP_CONTROL_ERROR_OUT_OF_SYNC (integer)
GUPNP_CONTROL_ERROR_ACTION_FAILED (integer)


Examples

Table of Contents

  • Browsing devices and services
  • Implementing the BinaryLight device


Browsing devices and services

This example shows how to obtain information about all devices and services. It starts an infinite loop (use CLI), and if any of available devices or services are found, the proper callback function will be invoked.

Example #1 Search for all UPnP devices and services.

<?php

/* Callback for available device */
function device_proxy_available_cb($proxy, $arg)
{
    $info = gupnp_device_info_get($proxy);

    $type = $info['device_type'];
    $location = $info['location'];

    printf("Device available:\n");
    printf("\ttype:     %s\n", $type);
    printf("\tlocation: %s\n", $location);
}

/* Callback for available service */
function service_proxy_available_cb($proxy, $arg)
{
    $info = gupnp_service_info_get($proxy);

    $type = $info['service_type'];
    $location = $info['location'];

    printf("Service available:\n");
    printf("\ttype:     %s\n", $type);
    printf("\tlocation: %s\n", $location);
}

/* Create the UPnP context */
$context = gupnp_context_new();
if (!$context) {
    printf("Error creating the GUPnP context\n");
    exit(-1);
}

/* We're interested in everything */
$cp = gupnp_control_point_new($context, "ssdp:all");

/* Set callbacks */
gupnp_control_point_callback_set($cp,
    GUPNP_SIGNAL_DEVICE_PROXY_AVAILABLE, 'device_proxy_available_cb');
gupnp_control_point_callback_set($cp,
    GUPNP_SIGNAL_SERVICE_PROXY_AVAILABLE, 'service_proxy_available_cb');

/* Start for browsing (infinite loop, hit Ctrl-C to interrupt) */
gupnp_control_point_browse_start($cp);

?>


Implementing the BinaryLight device

This is an example of UPnP device/service, implementing the BinaryLight device and SwitchPower services to emulate a light switch.

The user interface was purposely simplified in order to show basic concepts and methods.

Example #1 Implementing light server

<?php

/* SetTarget */
function set_target_cb($service, $action, $arg)
{
    /* Get the new target value */
    $target = gupnp_service_action_get($action, 'NewTargetValue', GUPNP_TYPE_BOOLEAN);

    /* If the new target doesn't match the current status, change the status and
       emit a notification that the status has changed. */
    if ($target != $GLOBALS['status']) {
        $GLOBALS['status'] = $target;
        gupnp_service_notify($service, 'Status', GUPNP_TYPE_BOOLEAN, $GLOBALS['status']);
        printf("The light is now %s.\n", $GLOBALS['status'] ? "on" : "off");
    }

    /* Return success to the client */
    gupnp_service_action_return($action);
}

/* GetTarget */
function get_target_cb($service, $action, $arg)
{
    gupnp_service_action_set($action, 'RetTargetValue', GUPNP_TYPE_BOOLEAN, $GLOBALS['status']);
    gupnp_service_action_return($action);
}

/* GetStatus */
function get_status_cb($service, $action, $arg)
{
    gupnp_service_action_set($action, 'ResultStatus', GUPNP_TYPE_BOOLEAN, $GLOBALS['status']);
    gupnp_service_action_return($action);
}

/* By default the light is off */
$GLOBALS['status'] = false;
printf("The light is now %s.\n", $GLOBALS['status'] ? "on" : "off");

/* Create the UPnP context */
$context = gupnp_context_new();
if (!$context) {
    printf("Error creating the GUPnP context\n");
    exit(-1);
}

/* Host the directory that contains device and service description files */
gupnp_context_host_path($context, "./web", "");

/* Create root device */
$location = "/BinaryLight.xml";
$dev = gupnp_root_device_new($context, $location);
gupnp_root_device_set_available($dev, true);

/* Get the switch service from the root device */
$service_type = "urn:schemas-upnp-org:service:SwitchPower:1";
$service = gupnp_device_info_get_service($dev, $service_type);
if (!$service) {
    die("Cannot get SwitchPower1 service\n");
}

/* Set callback for action GetStatus */
gupnp_device_action_callback_set($service, GUPNP_SIGNAL_ACTION_INVOKED, "GetStatus",
    "get_status_cb", "action data, GetStatus");

/* Set callback for action GetTarget */
gupnp_device_action_callback_set($service, GUPNP_SIGNAL_ACTION_INVOKED, "GetTarget",
    "get_target_cb", "action data, GetTarget");

/* Set callback for action SetTarget */
gupnp_device_action_callback_set($service, GUPNP_SIGNAL_ACTION_INVOKED, "SetTarget",
    "set_target_cb", "action data, SetTarget");

/* Run the main loop */
gupnp_root_device_start($dev);

?>

Example #2 Implementing light client

<?php

function service_proxy_available_cb($proxy, $arg)
{
    $mode = $arg['mode'];

    printf("Set subscribed\n");
    gupnp_service_proxy_set_subscribed($proxy, true);

    /* Add notify if status will be changed */
    if (!gupnp_service_proxy_add_notify($proxy, "Status",
            GUPNP_TYPE_BOOLEAN, "status_changed_cb", NULL)) {
        printf("Failed to add notify\n");
    }

    if ($mode == 'TOGGLE') {
        /* We're toggling, so first fetch the current status */
        $target = gupnp_service_proxy_action_get($proxy, 'GetStatus', 'ResultStatus', GUPNP_TYPE_BOOLEAN);

        /* And then toggle it */
        $target = ! $target;
    } else {
        /* Mode is a boolean, so the target is the mode thanks to our well chosen
           enumeration values. */
        $target = ($mode == 'ON') ? true : false;
    }

    /* Set the target */
    if (!gupnp_service_proxy_action_set($proxy, 'SetTarget', 'NewTargetValue', $target, GUPNP_TYPE_BOOLEAN)) {
        printf("Cannot set switch\n");
    } else {
        printf("Set switch to %s.\n", $target ? "on" : "off");
    }

    /* Stop browsing */
    gupnp_control_point_browse_stop($arg['cp']);
}

function status_changed_cb($variable, $value, $arg)
{
    printf("Status has been changed\n");
    printf("\tvariable name: %s\n", $variable);
    printf("\tvalue: %s\n", (int)$value);
    printf("\n");
}

/* Check and parse command line arguments */
if (count($argv) != 2) {
    printf("Usage: light-client.php [on|off|toggle]\n");
    exit(-1);
}

if ($argv[1] == "on") {
    $mode = 'ON';
} elseif ($argv[1] == "off") {
    $mode = 'OFF';
} elseif ($argv[1] == "toggle") {
    $mode = 'TOGGLE';
} else {
    usage ();
    exit(-1);
}

/* Create the UPnP context */
$context = gupnp_context_new();
if (!$context) {
    printf("Error creating the GUPnP context\n");
    exit(-1);
}

/* Create the control point, searching for SwitchPower services */
$cp = gupnp_control_point_new ($context,
        "urn:schemas-upnp-org:service:SwitchPower:1");

/* Connect to the service-found callback */
$cb = "service_proxy_available_cb";
$arg = array('mode' => $mode, 'cp' => $cp);
gupnp_control_point_callback_set($cp, GUPNP_SIGNAL_SERVICE_PROXY_AVAILABLE, $cb, $arg);

/* Start for browsing */
gupnp_control_point_browse_start($cp);

?>


Gupnp Functions

Table of Contents

  • gupnp_context_get_host_ip — Get the IP address
  • gupnp_context_get_port — Get the port
  • gupnp_context_get_subscription_timeout — Get the event subscription timeout
  • gupnp_context_host_path — Start hosting
  • gupnp_context_new — Create a new context
  • gupnp_context_set_subscription_timeout — Sets the event subscription timeout
  • gupnp_context_timeout_add — Sets a function to be called at regular intervals
  • gupnp_context_unhost_path — Stop hosting
  • gupnp_control_point_browse_start — Start browsing
  • gupnp_control_point_browse_stop — Stop browsing
  • gupnp_control_point_callback_set — Set control point callback
  • gupnp_control_point_new — Create a new control point
  • gupnp_device_action_callback_set — Set device callback function
  • gupnp_device_info_get_service — Get the service with type
  • gupnp_device_info_get — Get info of root device
  • gupnp_root_device_get_available — Check whether root device is available
  • gupnp_root_device_get_relative_location — Get the relative location of root device
  • gupnp_root_device_new — Create a new root device
  • gupnp_root_device_set_available — Set whether or not root_device is available
  • gupnp_root_device_start — Start main loop
  • gupnp_root_device_stop — Stop main loop
  • gupnp_service_action_get — Retrieves the specified action arguments
  • gupnp_service_action_return_error — Return error code
  • gupnp_service_action_return — Return successfully
  • gupnp_service_action_set — Sets the specified action return values
  • gupnp_service_freeze_notify — Freeze new notifications
  • gupnp_service_info_get_introspection — Get resource introspection of service
  • gupnp_service_info_get — Get full info of service
  • gupnp_service_introspection_get_state_variable — Returns the state variable data
  • gupnp_service_notify — Notifies listening clients
  • gupnp_service_proxy_action_get — Send action to the service and get value
  • gupnp_service_proxy_action_set — Send action to the service and set value
  • gupnp_service_proxy_add_notify — Sets up callback for variable change notification
  • gupnp_service_proxy_callback_set — Set service proxy callback for signal
  • gupnp_service_proxy_get_subscribed — Check whether subscription is valid to the service
  • gupnp_service_proxy_remove_notify — Cancels the variable change notification
  • gupnp_service_proxy_send_action — Send action with multiple parameters synchronously
  • gupnp_service_proxy_set_subscribed — (Un)subscribes to the service
  • gupnp_service_thaw_notify — Sends out any pending notifications and stops queuing of new ones


Get the IP address

  • « Gupnp Functions
  • gupnp_context_get_port »
  • PHP Manual
  • Gupnp Functions
  • Get the IP address

gupnp_context_get_host_ip

(PECL gupnp >= 0.1.0)

gupnp_context_get_host_ip — Get the IP address

Description

gupnp_context_get_host_ip ( resource $context ) : string

Get the IP address we advertise ourselves as using.

Parameters

context

A context identifier, returned by gupnp_context_new().

Return Values

Returns the IP address for the current context and FALSE on error.

Examples

Example #1 Create new UPnP context and get IP address of the host

<?php

/* Create the UPnP context */
$context = gupnp_context_new();

if (!$context) {
 die("Error creating the GUPnP context\n");
}

/* Get IP address for the UPnP context */
$ip = gupnp_context_get_host_ip($context);
echo $ip;

?>

See Also

  • gupnp_context_new() - Create a new context
  • gupnp_context_get_port() - Get the port


Get the port

  • « gupnp_context_get_host_ip
  • gupnp_context_get_subscription_timeout »
  • PHP Manual
  • Gupnp Functions
  • Get the port

gupnp_context_get_port

(PECL gupnp >= 0.1.0)

gupnp_context_get_port — Get the port

Description

gupnp_context_get_port ( resource $context ) : int

Get the port that the SOAP server is running on.

Parameters

context

A context identifier, returned by gupnp_context_new().

Return Values

Returns the port number for the current context and FALSE on error.

Examples

Example #1 Create new UPnP context and get port number

<?php

/* Create the UPnP context */
$context = gupnp_context_new();

if (!$context) {
 die("Error creating the GUPnP context\n");
}

/* Get the port number for the UPnP context */
$port = gupnp_context_get_port($context);
echo $port;

?>

See Also

  • gupnp_context_new() - Create a new context
  • gupnp_context_get_host_ip() - Get the IP address


Get the event subscription timeout

  • « gupnp_context_get_port
  • gupnp_context_host_path »
  • PHP Manual
  • Gupnp Functions
  • Get the event subscription timeout

gupnp_context_get_subscription_timeout

(PECL gupnp >= 0.1.0)

gupnp_context_get_subscription_timeout — Get the event subscription timeout

Description

gupnp_context_get_subscription_timeout ( resource $context ) : int

Get the event subscription timeout (in seconds), or 0 meaning there is no timeout.

Parameters

context

A context identifier, returned by gupnp_context_new().

Return Values

The event subscription timeout in seconds.

See Also

  • gupnp_context_new() - Create a new context
  • gupnp_context_set_subscription_timeout() - Sets the event subscription timeout


Start hosting

  • « gupnp_context_get_subscription_timeout
  • gupnp_context_new »
  • PHP Manual
  • Gupnp Functions
  • Start hosting

gupnp_context_host_path

(PECL gupnp >= 0.1.0)

gupnp_context_host_path — Start hosting

Description

gupnp_context_host_path ( resource $context , string $local_path , string $server_path ) : bool

Start hosting local_path at server_path. Files with the path local_path.LOCALE (if they exist) will be served up when LOCALE is specified in the request's Accept-Language header.

Parameters

context

A context identifier, returned by gupnp_context_new().

local_path

Path to the local file or folder to be hosted.

server_path

Web server path where local_path should be hosted.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Create new UPnP context and set host path

<?php

/* Create the UPnP context */
$context = gupnp_context_new();

if (!$context) {
 die("Error creating the GUPnP context\n");
}

/* Host current directory */
gupnp_context_host_path($context, "./web", "");

?>

See Also

  • gupnp_context_new() - Create a new context
  • gupnp_context_unhost_path() - Stop hosting


Create a new context

  • « gupnp_context_host_path
  • gupnp_context_set_subscription_timeout »
  • PHP Manual
  • Gupnp Functions
  • Create a new context

gupnp_context_new

(PECL gupnp >= 0.1.0)

gupnp_context_new — Create a new context

Description

gupnp_context_new ([ string $host_ip [, int $port = 0 ]] ) : resource

Create a new context with the specified host_ip and port.

Parameters

host_ip

The local host's IP address, or NULL to use the IP address of the first non-loopback network interface.

port

Port to run on, or 0 if you don't care what port is used.

Return Values

A context identifier.

Examples

Example #1 Create new UPnP context

<?php

/* Create the UPnP context */
$context = gupnp_context_new();

if (!$context) {
 die("Error creating the GUPnP context\n");
}

?>

Errors/Exceptions

Issues E_WARNING with unable to create context.


Sets the event subscription timeout

  • « gupnp_context_new
  • gupnp_context_timeout_add »
  • PHP Manual
  • Gupnp Functions
  • Sets the event subscription timeout

gupnp_context_set_subscription_timeout

(PECL gupnp >= 0.1.0)

gupnp_context_set_subscription_timeout — Sets the event subscription timeout

Description

gupnp_context_set_subscription_timeout ( resource $context , int $timeout ) : void

Sets the event subscription timeout (in seconds) to time out. Note that any client side subscriptions will automatically be renewed.

Parameters

context

A context identifier, returned by gupnp_context_new().

timeout

The event subscription timeout in seconds. Use 0 if you don't want subscriptions to time out.

Return Values

No value is returned.

See Also

  • gupnp_context_new() - Create a new context
  • gupnp_context_get_subscription_timeout() - Get the event subscription timeout


Sets a function to be called at regular intervals

  • « gupnp_context_set_subscription_timeout
  • gupnp_context_unhost_path »
  • PHP Manual
  • Gupnp Functions
  • Sets a function to be called at regular intervals

gupnp_context_timeout_add

(PECL gupnp >= 0.1.0)

gupnp_context_timeout_add — Sets a function to be called at regular intervals

Description

gupnp_context_timeout_add ( resource $context , int $timeout , mixed $callback [, mixed $arg ] ) : bool

Sets a function to be called at regular intervals.

Parameters

context

A context identifier, returned by gupnp_context_new().

timeout

A timeout in miliseconds.

callback

The callback function calling every timeout period of time. Typically, callback function takes on arg parameter.

arg

User data for callback.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Create new UPnP context and set callback

<?php

$user_data = "user data";

function timeout_cb($arg)
{
    printf("Call timeout_cb, user data: '%s'", $arg);
    return true;
}

/* Create the UPnP context */
$context = gupnp_context_new();

if (!$context) {
 die("Error creating the GUPnP context\n");
}

/* Create root device */
$dev = gupnp_root_device_new($context, "/devicedesc.xml");

/* Set callback for timeout */
gupnp_context_timeout_add($context, 5000, "timeout_cb", $user_data);

/* Run the main loop */
gupnp_root_device_start($dev);

?>

Errors/Exceptions

Issues E_WARNING with not valid callback function.

See Also

  • gupnp_context_new() - Create a new context


Stop hosting

  • « gupnp_context_timeout_add
  • gupnp_control_point_browse_start »
  • PHP Manual
  • Gupnp Functions
  • Stop hosting

gupnp_context_unhost_path

(PECL gupnp >= 0.1.0)

gupnp_context_unhost_path — Stop hosting

Description

gupnp_context_unhost_path ( resource $context , string $server_path ) : bool

Stop hosting the file or folder at server_path.

Parameters

context

A context identifier, returned by gupnp_context_new().

server_path

Web server path where the file or folder is hosted.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • gupnp_context_new() - Create a new context
  • gupnp_context_host_path() - Start hosting


Start browsing

  • « gupnp_context_unhost_path
  • gupnp_control_point_browse_stop »
  • PHP Manual
  • Gupnp Functions
  • Start browsing

gupnp_control_point_browse_start

(PECL gupnp >= 0.1.0)

gupnp_control_point_browse_start — Start browsing

Description

gupnp_control_point_browse_start ( resource $cpoint ) : bool

Start the search and calls user-defined callback.

Parameters

cpoint

A control point identifier, returned by gupnp_control_point_new().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Create new UPnP context and start browsing

<?php

function device_proxy_available_cb($proxy, $arg)
{
    $info = gupnp_device_info_get($proxy);

    $type = $info['device_type'];
    $location = $info['location'];

    printf("Device available:\n");
    printf("type:     %s\n", $type);
    printf("location: %s\n", $location);
}

/* Create the UPnP context */
$context = gupnp_context_new();

if (!$context) {
 die("Error creating the GUPnP context\n");
}

/* We're interested in everything */
$cp = gupnp_control_point_new($context, "ssdp:all");

gupnp_control_point_callback_set($cp,
    GUPNP_SIGNAL_DEVICE_PROXY_AVAILABLE, 'device_proxy_available_cb');

/* Start for browsing */
gupnp_control_point_browse_start($cp);

?>

See Also

  • gupnp_control_point_new() - Create a new control point
  • gupnp_control_point_browse_stop() - Stop browsing


Stop browsing

  • « gupnp_control_point_browse_start
  • gupnp_control_point_callback_set »
  • PHP Manual
  • Gupnp Functions
  • Stop browsing

gupnp_control_point_browse_stop

(PECL gupnp >= 0.1.0)

gupnp_control_point_browse_stop — Stop browsing

Description

gupnp_control_point_browse_stop ( resource $cpoint ) : bool

Stop the search and calls user-defined callback.

Parameters

cpoint

A control point identifier, returned by gupnp_control_point_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • gupnp_control_point_new() - Create a new control point
  • gupnp_control_point_browse_start() - Start browsing


Set control point callback

  • « gupnp_control_point_browse_stop
  • gupnp_control_point_new »
  • PHP Manual
  • Gupnp Functions
  • Set control point callback

gupnp_control_point_callback_set

(PECL gupnp >= 0.1.0)

gupnp_control_point_callback_set — Set control point callback

Description

gupnp_control_point_callback_set ( resource $cpoint , int $signal , mixed $callback [, mixed $arg ] ) : bool

Set control point callback function for signal.

Parameters

cpoint

A control point identifier, returned by gupnp_control_point_new().

signal

The value of signal. Signal can be one of the following values:

GUPNP_SIGNAL_DEVICE_PROXY_AVAILABLE
Emitted whenever a new device has become available.
GUPNP_SIGNAL_DEVICE_PROXY_UNAVAILABLE
Emitted whenever a device is not available any more.
GUPNP_SIGNAL_SERVICE_PROXY_AVAILABLE
Emitted whenever a new service has become available.
GUPNP_SIGNAL_SERVICE_PROXY_UNAVAILABLE
Emitted whenever a service is not available any more.

callback

The callback function for the certain signal. Typically, callback function takes on two parameters. The proxy parameter's identifier being the first, and the arg second.

arg

User data for callback.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Create new UPnP context and start browsing

<?php

function device_proxy_available_cb($proxy, $arg)
{
    $info = gupnp_device_info_get($proxy);

    $type = $info['device_type'];
    $location = $info['location'];

    printf("Device available:\n");
    printf("type:     %s\n", $type);
    printf("location: %s\n", $location);
}

/* Create the UPnP context */
$context = gupnp_context_new();

if (!$context) {
 die("Error creating the GUPnP context\n");
}

/* We're interested in everything */
$cp = gupnp_control_point_new($context, "ssdp:all");

gupnp_control_point_callback_set($cp,
    GUPNP_SIGNAL_DEVICE_PROXY_AVAILABLE, 'device_proxy_available_cb');

/* Start for browsing */
gupnp_control_point_browse_start($cp);

?>

Errors/Exceptions

Issues E_WARNING with not valid callback function.

See Also

  • gupnp_control_point_new() - Create a new control point
  • gupnp_control_point_browse_start() - Start browsing


Create a new control point

  • « gupnp_control_point_callback_set
  • gupnp_device_action_callback_set »
  • PHP Manual
  • Gupnp Functions
  • Create a new control point

gupnp_control_point_new

(PECL gupnp >= 0.1.0)

gupnp_control_point_new — Create a new control point

Description

gupnp_control_point_new ( resource $context , string $target ) : resource

Create a new control point with the specified target.

Parameters

context

A context identifier, returned by gupnp_context_new().

target

The search target. target should be a service or device name, such as urn:schemas-upnp-org:service:WANIPConnection:1 or urn:schemas-upnp-org:device:MediaRenderer:1.

Return Values

A control point identifier.


Set device callback function

  • « gupnp_control_point_new
  • gupnp_device_info_get_service »
  • PHP Manual
  • Gupnp Functions
  • Set device callback function

gupnp_device_action_callback_set

(PECL gupnp >= 0.1.0)

gupnp_device_action_callback_set — Set device callback function

Description

gupnp_device_action_callback_set ( resource $root_device , int $signal , string $action_name , mixed $callback [, mixed $arg ] ) : bool

Set device callback function for signal and action.

Parameters

root_device

A root device identifier, returned by gupnp_root_device_new().

signal

The value of signal. Signal can be one of the following values:

GUPNP_SIGNAL_ACTION_INVOKED
Emitted whenever an action is invoked. Handler should process action and must call either gupnp_service_action_return() or gupnp_service_action_return_error().
GUPNP_SIGNAL_NOTIFY_FAILED
Emitted whenever notification of a client fails.

action_name

The name of action.

callback

The callback function for the certain signal. Typically, callback function takes on three parameters. The service parameter's identifier being the first, action parameter's identifier (in case GUPNP_SIGNAL_ACTION_INVOKED signal) or error parameter's message (in case GUPNP_SIGNAL_NOTIFY_FAILED signal) being the second, and the arg is third.

arg

User data for callback.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Issues E_WARNING either with not valid callback function or with not valid signal.

See Also

  • gupnp_root_device_new() - Create a new root device


Get the service with type

  • « gupnp_device_action_callback_set
  • gupnp_device_info_get »
  • PHP Manual
  • Gupnp Functions
  • Get the service with type

gupnp_device_info_get_service

(PECL gupnp >= 0.1.0)

gupnp_device_info_get_service — Get the service with type

Description

gupnp_device_info_get_service ( resource $root_device , string $type ) : resource

Get the service with type or false if no such device was found.

Parameters

root_device

A root device identifier, returned by gupnp_root_device_new().

type

The type of the service to be retrieved.

Return Values

A service identifier.

Examples

Example #1 Create new UPnP context and get device info service

<?php

/* Create the UPnP context */
$context = gupnp_context_new();

if (!$context) {
 die("Error creating the GUPnP context\n");
}

/* Create root device */
$location = "/BinaryLight1.xml";
$dev = gupnp_root_device_new($context, $location);

/* Set root device is available */
gupnp_root_device_set_available($dev, true);

/* Get the switch service from the root device */
$service_type = "urn:schemas-upnp-org:service:SwitchPower:1";
$service = gupnp_device_info_get_service($dev, $service_type);
if (!$service) {
    die("Cannot get SwitchPower1 service\n");
}

?>


Get info of root device

  • « gupnp_device_info_get_service
  • gupnp_root_device_get_available »
  • PHP Manual
  • Gupnp Functions
  • Get info of root device

gupnp_device_info_get

(PECL gupnp >= 0.1.0)

gupnp_device_info_get — Get info of root device

Description

gupnp_device_info_get ( resource $root_device ) : array

Get info of root device.

Parameters

root_device

A root device identifier, returned by gupnp_root_device_new().

Return Values

Return array wich contains the information of the root device (like location, url, udn and etc).


Check whether root device is available

  • « gupnp_device_info_get
  • gupnp_root_device_get_relative_location »
  • PHP Manual
  • Gupnp Functions
  • Check whether root device is available

gupnp_root_device_get_available

(PECL gupnp >= 0.1.0)

gupnp_root_device_get_available — Check whether root device is available

Description

gupnp_root_device_get_available ( resource $root_device ) : bool

Get whether or not root_device is available (announcing its presence).

Parameters

root_device

A root device identifier, returned by gupnp_root_device_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • gupnp_root_device_set_available() - Set whether or not root_device is available


Get the relative location of root device

  • « gupnp_root_device_get_available
  • gupnp_root_device_new »
  • PHP Manual
  • Gupnp Functions
  • Get the relative location of root device

gupnp_root_device_get_relative_location

(PECL gupnp >= 0.1.0)

gupnp_root_device_get_relative_location — Get the relative location of root device

Description

gupnp_root_device_get_relative_location ( resource $root_device ) : string

Get the relative location of root device.

Parameters

root_device

A root device identifier, returned by gupnp_root_device_new().

Return Values

The relative location of root device


Create a new root device

  • « gupnp_root_device_get_relative_location
  • gupnp_root_device_set_available »
  • PHP Manual
  • Gupnp Functions
  • Create a new root device

gupnp_root_device_new

(PECL gupnp >= 0.1.0)

gupnp_root_device_new — Create a new root device

Description

gupnp_root_device_new ( resource $context , string $location , string $description_dir ) : resource

Create a new root device, automatically downloading and parsing location.

Parameters

context

A context identifier, returned by gupnp_context_new().

location

Location of the description file for this device, relative to the HTTP root

Return Values

A root device identifier.

Examples

Example #1 Create new UPnP context and get device info service

<?php

/* Create the UPnP context */
$context = gupnp_context_new();

if (!$context) {
 die("Error creating the GUPnP context\n");
}

/* Create root device */
$location = "/BinaryLight1.xml";
$dev = gupnp_root_device_new($context, $location);

?>

See Also

  • gupnp_root_device_set_available() - Set whether or not root_device is available
  • gupnp_root_device_start() - Start main loop
  • gupnp_root_device_stop() - Stop main loop


Set whether or not root_device is available

  • « gupnp_root_device_new
  • gupnp_root_device_start »
  • PHP Manual
  • Gupnp Functions
  • Set whether or not root_device is available

gupnp_root_device_set_available

(PECL gupnp >= 0.1.0)

gupnp_root_device_set_available — Set whether or not root_device is available

Description

gupnp_root_device_set_available ( resource $root_device , bool $available ) : bool

Controls whether or not root_device is available (announcing its presence).

Parameters

root_device

A root device identifier, returned by gupnp_root_device_new().

available

Set TRUE if root_device should be available.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • gupnp_root_device_get_available() - Check whether root device is available


Start main loop

  • « gupnp_root_device_set_available
  • gupnp_root_device_stop »
  • PHP Manual
  • Gupnp Functions
  • Start main loop

gupnp_root_device_start

(PECL gupnp >= 0.1.0)

gupnp_root_device_start — Start main loop

Description

gupnp_root_device_start ( resource $root_device ) : bool

Start root server's main loop.

Parameters

root_device

A root device identifier, returned by gupnp_root_device_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • gupnp_root_device_stop() - Stop main loop


Stop main loop

  • « gupnp_root_device_start
  • gupnp_service_action_get »
  • PHP Manual
  • Gupnp Functions
  • Stop main loop

gupnp_root_device_stop

(PECL gupnp >= 0.1.0)

gupnp_root_device_stop — Stop main loop

Description

gupnp_root_device_stop ( resource $root_device ) : bool

Stop root server's main loop.

Parameters

root_device

A root device identifier, returned by gupnp_root_device_new().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • gupnp_root_device_start() - Start main loop


Retrieves the specified action arguments

  • « gupnp_root_device_stop
  • gupnp_service_action_return_error »
  • PHP Manual
  • Gupnp Functions
  • Retrieves the specified action arguments

gupnp_service_action_get

(PECL gupnp >= 0.1.0)

gupnp_service_action_get — Retrieves the specified action arguments

Description

gupnp_service_action_get ( resource $action , string $name , int $type ) : mixed

Retrieves the specified action arguments.

Parameters

action

A service action identifier.

name

The name of the variable to retrieve.

type

The type of the variable to retrieve. Type can be one of the following values:

GUPNP_TYPE_BOOLEAN
Type of the variable is boolean.
GUPNP_TYPE_INT
Type of the variable is integer.
GUPNP_TYPE_LONG
Type of the variable is long.
GUPNP_TYPE_DOUBLE
Type of the variable is double.
GUPNP_TYPE_FLOAT
Type of the variable is float.
GUPNP_TYPE_STRING
Type of the variable is string.

Return Values

The value of the variable.

Errors/Exceptions

Issues E_WARNING with not correctly defined type of the variable.

See Also

  • gupnp_service_action_set() - Sets the specified action return values


Return error code

  • « gupnp_service_action_get
  • gupnp_service_action_return »
  • PHP Manual
  • Gupnp Functions
  • Return error code

gupnp_service_action_return_error

(PECL gupnp >= 0.1.0)

gupnp_service_action_return_error — Return error code

Description

gupnp_service_action_return_error ( resource $action , int $error_code [, string $error_description ] ) : bool

Return error code.

Parameters

action

A service action identifier.

error_code

The error code. Signal can be one of the following values or user defined:

GUPNP_CONTROL_ERROR_INVALID_ACTION
The action name was invalid.
GUPNP_CONTROL_ERROR_INVALID_ARGS
The action arguments were invalid.
GUPNP_CONTROL_ERROR_OUT_OF_SYNC
Out of sync (deprecated).
GUPNP_CONTROL_ERROR_ACTION_FAILED
The action failed.

error_description

The error description.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • gupnp_service_action_return() - Return successfully


Return successfully

  • « gupnp_service_action_return_error
  • gupnp_service_action_set »
  • PHP Manual
  • Gupnp Functions
  • Return successfully

gupnp_service_action_return

(PECL gupnp >= 0.1.0)

gupnp_service_action_return — Return successfully

Description

gupnp_service_action_return ( resource $action ) : bool

Return successfully.

Parameters

action

A service action identifier.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • gupnp_service_action_return_error() - Return error code


Sets the specified action return values

  • « gupnp_service_action_return
  • gupnp_service_freeze_notify »
  • PHP Manual
  • Gupnp Functions
  • Sets the specified action return values

gupnp_service_action_set

(PECL gupnp >= 0.1.0)

gupnp_service_action_set — Sets the specified action return values

Description

gupnp_service_action_set ( resource $action , string $name , int $type , mixed $value ) : bool

Sets the specified action return values.

Parameters

action

A service action identifier.

name

The name of the variable to retrieve.

type

The type of the variable to retrieve. Type can be one of the following values:

GUPNP_TYPE_BOOLEAN
Type of the variable is boolean.
GUPNP_TYPE_INT
Type of the variable is integer.
GUPNP_TYPE_LONG
Type of the variable is long.
GUPNP_TYPE_DOUBLE
Type of the variable is double.
GUPNP_TYPE_FLOAT
Type of the variable is float.
GUPNP_TYPE_STRING
Type of the variable is string.

value

The value of the variable to retrieve.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Issues E_WARNING with neither not correctly defined type of the variable or the value is not corresponding to the defined type.

See Also

  • gupnp_service_action_get() - Retrieves the specified action arguments


Freeze new notifications

  • « gupnp_service_action_set
  • gupnp_service_info_get_introspection »
  • PHP Manual
  • Gupnp Functions
  • Freeze new notifications

gupnp_service_freeze_notify

(PECL gupnp >= 0.1.0)

gupnp_service_freeze_notify — Freeze new notifications

Description

gupnp_service_freeze_notify ( resource $service ) : bool

Causes new notifications to be queued up until gupnp_service_thaw_notify() is called.

Parameters

service

A service identifier.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • gupnp_service_notify() - Notifies listening clients
  • gupnp_service_thaw_notify() - Sends out any pending notifications and stops queuing of new ones


Get resource introspection of service

  • « gupnp_service_freeze_notify
  • gupnp_service_info_get »
  • PHP Manual
  • Gupnp Functions
  • Get resource introspection of service

gupnp_service_info_get_introspection

(PECL gupnp >= 0.1.0)

gupnp_service_info_get_introspection — Get resource introspection of service

Description

gupnp_service_info_get_introspection ( resource $proxy [, mixed $callback [, mixed $arg ]] ) : mixed

Get resource introspection of service or register callback if corresponding parameter was passed.

Parameters

proxy

A service proxy identifier.

callback

The callback function to be called when introspection object is ready. Typically, callback function takes on three parameters. The introspection parameter's identifier being the first, error parameter's message being the second, and the arg is third.

arg

User data for callback.

Return Values

Return true if callback function was defined. Return introspection identifier if callback function was omited.

Errors/Exceptions

Issues E_WARNING with not valid callback function.


Get full info of service

  • « gupnp_service_info_get_introspection
  • gupnp_service_introspection_get_state_variable »
  • PHP Manual
  • Gupnp Functions
  • Get full info of service

gupnp_service_info_get

(PECL gupnp >= 0.1.0)

gupnp_service_info_get — Get full info of service

Description

gupnp_service_info_get ( resource $proxy ) : array

Get full info of service.

Parameters

proxy

A service proxy identifier.

Return Values

Return array wich contains the information of the service (like location, url, udn and etc).


Returns the state variable data

  • « gupnp_service_info_get
  • gupnp_service_notify »
  • PHP Manual
  • Gupnp Functions
  • Returns the state variable data

gupnp_service_introspection_get_state_variable

(PECL gupnp >= 0.1.0)

gupnp_service_introspection_get_state_variable — Returns the state variable data

Description

gupnp_service_introspection_get_state_variable ( resource $introspection , string $variable_name ) : array

Returns the state variable data by the name variable_name in this service.

Parameters

introspection

A introspection identifier.

variable_name

The name of the variable to retreive.

Return Values

Return the state variable data or FALSE.


Notifies listening clients

  • « gupnp_service_introspection_get_state_variable
  • gupnp_service_proxy_action_get »
  • PHP Manual
  • Gupnp Functions
  • Notifies listening clients

gupnp_service_notify

(PECL gupnp >= 0.1.0)

gupnp_service_notify — Notifies listening clients

Description

gupnp_service_notify ( resource $service , string $name , int $type , mixed $value ) : bool

Notifies listening clients that the property have changed to the specified values.

Parameters

service

A service identifier.

name

The name of the variable.

type

The type of the variable. Type can be one of the following values:

GUPNP_TYPE_BOOLEAN
Type of the variable is boolean.
GUPNP_TYPE_INT
Type of the variable is integer.
GUPNP_TYPE_LONG
Type of the variable is long.
GUPNP_TYPE_DOUBLE
Type of the variable is double.
GUPNP_TYPE_FLOAT
Type of the variable is float.
GUPNP_TYPE_STRING
Type of the variable is string.

value

The value of the variable.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Issues E_WARNING with either not correctly defined type of the variable or the value is not corresponding to the defined type.

See Also

  • gupnp_service_freeze_notify() - Freeze new notifications
  • gupnp_service_thaw_notify() - Sends out any pending notifications and stops queuing of new ones


Send action to the service and get value

  • « gupnp_service_notify
  • gupnp_service_proxy_action_set »
  • PHP Manual
  • Gupnp Functions
  • Send action to the service and get value

gupnp_service_proxy_action_get

(PECL gupnp >= 0.1.0)

gupnp_service_proxy_action_get — Send action to the service and get value

Description

gupnp_service_proxy_action_get ( resource $proxy , string $action , string $name , int $type ) : mixed

Send action with parameters to the service exposed by proxy synchronously and get value.

Parameters

proxy

A service proxy identifier.

action

An action.

name

The action name.

type

The type of the variable to retrieve. Type can be one of the following values:

GUPNP_TYPE_BOOLEAN
Type of the variable is boolean.
GUPNP_TYPE_INT
Type of the variable is integer.
GUPNP_TYPE_LONG
Type of the variable is long.
GUPNP_TYPE_DOUBLE
Type of the variable is double.
GUPNP_TYPE_FLOAT
Type of the variable is float.
GUPNP_TYPE_STRING
Type of the variable is string.

Return Values

Return value of the action.

Errors/Exceptions

Issues E_WARNING with either not correctly defined type of the action or unable to send action.

See Also

  • gupnp_service_proxy_action_set() - Send action to the service and set value
  • gupnp_service_proxy_send_action() - Send action with multiple parameters synchronously


Send action to the service and set value

  • « gupnp_service_proxy_action_get
  • gupnp_service_proxy_add_notify »
  • PHP Manual
  • Gupnp Functions
  • Send action to the service and set value

gupnp_service_proxy_action_set

(PECL gupnp >= 0.1.0)

gupnp_service_proxy_action_set — Send action to the service and set value

Description

gupnp_service_proxy_action_set ( resource $proxy , string $action , string $name , mixed $value , int $type ) : bool

Send action with parameters to the service exposed by proxy synchronously and set value.

Parameters

proxy

A service proxy identifier.

action

An action.

name

The action name.

value

The action value.

type

The type of the action. Type can be one of the following values:

GUPNP_TYPE_BOOLEAN
Type of the variable is boolean.
GUPNP_TYPE_INT
Type of the variable is integer.
GUPNP_TYPE_LONG
Type of the variable is long.
GUPNP_TYPE_DOUBLE
Type of the variable is double.
GUPNP_TYPE_FLOAT
Type of the variable is float.
GUPNP_TYPE_STRING
Type of the variable is string.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Issues E_WARNING with either not correctly defined type of the action or unable to send action.

See Also

  • gupnp_service_proxy_action_get() - Send action to the service and get value
  • gupnp_service_proxy_send_action() - Send action with multiple parameters synchronously


Sets up callback for variable change notification

  • « gupnp_service_proxy_action_set
  • gupnp_service_proxy_callback_set »
  • PHP Manual
  • Gupnp Functions
  • Sets up callback for variable change notification

gupnp_service_proxy_add_notify

(PECL gupnp >= 0.1.0)

gupnp_service_proxy_add_notify — Sets up callback for variable change notification

Description

gupnp_service_proxy_add_notify ( resource $proxy , string $value , int $type , mixed $callback [, mixed $arg ] ) : bool

Sets up callback to be called whenever a change notification for variable is recieved.

Parameters

proxy

A service proxy identifier.

value

The variable to add notification for.

type

The type of the variable. Type can be one of the following values:

GUPNP_TYPE_BOOLEAN
Type of the variable is boolean.
GUPNP_TYPE_INT
Type of the variable is integer.
GUPNP_TYPE_LONG
Type of the variable is long.
GUPNP_TYPE_DOUBLE
Type of the variable is double.
GUPNP_TYPE_FLOAT
Type of the variable is float.
GUPNP_TYPE_STRING
Type of the variable is string.

callback

The callback to call when variable changes. Typically, callback function takes on three parameters. The variable parameter being the first, value parameter being the second, and the arg is third.

arg

User data for callback.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • gupnp_service_proxy_remove_notify() - Cancels the variable change notification


Set service proxy callback for signal

  • « gupnp_service_proxy_add_notify
  • gupnp_service_proxy_get_subscribed »
  • PHP Manual
  • Gupnp Functions
  • Set service proxy callback for signal

gupnp_service_proxy_callback_set

(PECL gupnp >= 0.1.0)

gupnp_service_proxy_callback_set — Set service proxy callback for signal

Description

gupnp_service_proxy_callback_set ( resource $proxy , int $signal , mixed $callback [, mixed $arg ] ) : bool

Set service proxy callback for signal.

Parameters

proxy

A service proxy identifier.

signal

The value of signal.

GUPNP_SIGNAL_SUBSCRIPTION_LOST
Emitted whenever the subscription to this service has been lost due to an error condition.

callback

The callback function for the certain signal. Typically, callback function takes on two parameters. error parameter's message being the first, and the arg is second.

arg

User data for callback.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Issues E_WARNING either with not valid callback function or with not valid signal.


Check whether subscription is valid to the service

  • « gupnp_service_proxy_callback_set
  • gupnp_service_proxy_remove_notify »
  • PHP Manual
  • Gupnp Functions
  • Check whether subscription is valid to the service

gupnp_service_proxy_get_subscribed

(PECL gupnp >= 0.1.0)

gupnp_service_proxy_get_subscribed — Check whether subscription is valid to the service

Description

gupnp_service_proxy_get_subscribed ( resource $proxy ) : bool

Check whether subscription is valid to the service.

Parameters

proxy

A service proxy identifier.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • gupnp_service_proxy_set_subscribed() - (Un)subscribes to the service


Cancels the variable change notification

  • « gupnp_service_proxy_get_subscribed
  • gupnp_service_proxy_send_action »
  • PHP Manual
  • Gupnp Functions
  • Cancels the variable change notification

gupnp_service_proxy_remove_notify

(PECL gupnp >= 0.1.0)

gupnp_service_proxy_remove_notify — Cancels the variable change notification

Description

gupnp_service_proxy_remove_notify ( resource $proxy , string $value ) : bool

Cancels the variable change notification.

Parameters

proxy

A service proxy identifier.

value

The variable to add notification for.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • gupnp_service_proxy_add_notify() - Sets up callback for variable change notification


Send action with multiple parameters synchronously

  • « gupnp_service_proxy_remove_notify
  • gupnp_service_proxy_set_subscribed »
  • PHP Manual
  • Gupnp Functions
  • Send action with multiple parameters synchronously

gupnp_service_proxy_send_action

(PECL gupnp >= 0.2.0)

gupnp_service_proxy_send_action — Send action with multiple parameters synchronously

Description

gupnp_service_proxy_send_action ( resource $proxy , string $action , array $in_params , array $out_params ) : array

Send action with parameters in_params to the service exposed by proxy synchronously and return out_params with values or FALSE on error.

Parameters

proxy

A service proxy identifier.

action

An action.

in_params

An array of in parameters. Each entry in in_params is supposed to an array containing name, type and value of the parameters.

out_params

An array of out parameters. Each entry in out_params is supposed to an array containing name and type of the parameters.

Return Values

Return out_params array with values or FALSE on error.

Errors/Exceptions

Issues E_WARNING with either not correctly defined in_params and out_params or unable to send action.

See Also

  • gupnp_service_proxy_action_get() - Send action to the service and get value
  • gupnp_service_proxy_action_set() - Send action to the service and set value


(Un)subscribes to the service

  • « gupnp_service_proxy_send_action
  • gupnp_service_thaw_notify »
  • PHP Manual
  • Gupnp Functions
  • (Un)subscribes to the service

gupnp_service_proxy_set_subscribed

(PECL gupnp >= 0.1.0)

gupnp_service_proxy_set_subscribed — (Un)subscribes to the service

Description

gupnp_service_proxy_set_subscribed ( resource $proxy , bool $subscribed ) : bool

(Un)subscribes to the service.

Parameters

proxy

A service proxy identifier.

subscribed

Set TRUE to subscribe to this service.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • gupnp_service_proxy_get_subscribed() - Check whether subscription is valid to the service


Sends out any pending notifications and stops queuing of new ones

  • « gupnp_service_proxy_set_subscribed
  • Hyperwave API »
  • PHP Manual
  • Gupnp Functions
  • Sends out any pending notifications and stops queuing of new ones

gupnp_service_thaw_notify

(PECL gupnp >= 0.1.0)

gupnp_service_thaw_notify — Sends out any pending notifications and stops queuing of new ones

Description

gupnp_service_thaw_notify ( resource $service ) : bool

Sends out any pending notifications and stops queuing of new ones.

Parameters

service

A service identifier.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • gupnp_service_notify() - Notifies listening clients
  • gupnp_service_freeze_notify() - Freeze new notifications


Hyperwave API

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Integration with Apache
  • Hyperwave API Functions
    • hw_api::checkin — Checks in an object
    • hw_api::checkout — Checks out an object
    • hw_api::children — Returns children of an object
    • hw_api::content — Returns content of an object
    • hw_api::copy — Copies physically
    • hw_api::dbstat — Returns statistics about database server
    • hw_api::dcstat — Returns statistics about document cache server
    • hw_api::dstanchors — Returns a list of all destination anchors
    • hw_api::dstofsrcanchor — Returns destination of a source anchor
    • hw_api::find — Search for objects
    • hw_api::ftstat — Returns statistics about fulltext server
    • hw_api::hwstat — Returns statistics about Hyperwave server
    • hw_api::identify — Log into Hyperwave Server
    • hw_api::info — Returns information about server configuration
    • hw_api::insert — Inserts a new object
    • hw_api::insertanchor — Inserts a new object of type anchor
    • hw_api::insertcollection — Inserts a new object of type collection
    • hw_api::insertdocument — Inserts a new object of type document
    • hw_api::link — Creates a link to an object
    • hw_api::lock — Locks an object
    • hw_api::move — Moves object between collections
    • hw_api::object — Retrieve attribute information
    • hw_api::objectbyanchor — Returns the object an anchor belongs to
    • hw_api::parents — Returns parents of an object
    • hw_api::remove — Delete an object
    • hw_api::replace — Replaces an object
    • hw_api::setcommittedversion — Commits version other than last version
    • hw_api::srcanchors — Returns a list of all source anchors
    • hw_api::srcsofdst — Returns source of a destination object
    • hw_api::unlock — Unlocks a locked object
    • hw_api::user — Returns the own user object
    • hw_api::userlist — Returns a list of all logged in users
    • hw_api_attribute::key — Returns key of the attribute
    • hw_api_attribute::langdepvalue — Returns value for a given language
    • hw_api_attribute::value — Returns value of the attribute
    • hw_api_attribute::values — Returns all values of the attribute
    • hw_api_content::mimetype — Returns mimetype
    • hw_api_content::read — Read content
    • hw_api_error::count — Returns number of reasons
    • hw_api_error::reason — Returns reason of error
    • hw_api_object::assign — Clones object
    • hw_api_object::attreditable — Checks whether an attribute is editable
    • hw_api_object::count — Returns number of attributes
    • hw_api_object::insert — Inserts new attribute
    • hw_api_object::remove — Removes attribute
    • hw_api_object::title — Returns the title attribute
    • hw_api_object::value — Returns value of attribute
    • hw_api_reason::description — Returns description of reason
    • hw_api_reason::type — Returns type of reason
    • hwapi_attribute_new — Creates instance of class hw_api_attribute
    • hwapi_content_new — Create new instance of class hw_api_content
    • hwapi_hgcsp — Returns object of class hw_api
    • hwapi_object_new — Creates a new instance of class hwapi_object_new


Introduction

Hyperwave has been developed at » IICM in Graz. It started with the name Hyper-G and changed to Hyperwave when it was commercialised (in 1996).

Hyperwave is not free software. The current version, 5.5, is available at » http://www.hyperwave.com/. A time limited version can be ordered for free (30 days).

Hyperwave is an information system similar to a database (HIS, Hyperwave Information Server). Its focus is the storage and management of documents. A document can be any possible piece of data that may as well be stored in file. Each document is accompanied by its object record. The object record contains meta data for the document. The meta data is a list of attributes which can be extended by the user. Certain attributes are always set by the Hyperwave server, other may be modified by the user.

Note:

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.2.0.


Requirements

Since 2001 there is a Hyperwave SDK available. It supports Java, JavaScript and C++. This PHP Extension is based on the C++ interface. In order to activate the hwapi support in PHP you will have to install the Hyperwave SDK first.


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/hwapi.

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.2.0

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Hyperwave API configuration options
Name | Default | Changeable | Changelog
hwapi.allow_persistent | "0" | PHP_INI_SYSTEM |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.


  • « Resource Types
  • Integration with Apache »
  • PHP Manual
  • Hyperwave API
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


Integration with Apache

The Hyperwave extension is best used when PHP is compiled as an Apache module. In such a case the underlying Hyperwave server can be hidden from users almost completely if Apache uses its rewriting engine. The following instructions will explain this.

Since PHP with Hyperwave support built into Apache is intended to replace the native Hyperwave solution based on Wavemaster, we will assume that the Apache server will only serve as a Hyperwave web interface for these examples. This is not necessary but it simplifies the configuration. The concept is quite simple. First of all you need a PHP script which evaluates the $_ENV['PATH_INFO'] variable and treats its value as the name of a Hyperwave object. Let's call this script 'Hyperwave'. The URL http://your.hostname/Hyperwave/name_of_object would than return the Hyperwave object with the name 'name_of_object'. Depending on the type of the object the script has to react accordingly. If it is a collection, it will probably return a list of children. If it is a document it will return the mime type and the content. A slight improvement can be achieved if the Apache rewriting engine is used. From the users point of view it would be more straight forward if the URL http://your.hostname/name_of_object would return the object. The rewriting rule is quite easy:

RewriteRule ^/(.*) /usr/local/apache/htdocs/HyperWave/$1 [L]
Now every URL relates to an object in the Hyperwave server. This causes a simple to solve problem. There is no way to execute a different script, e.g. for searching, than the 'Hyperwave' script. This can be fixed with another rewriting rule like the following:
RewriteRule ^/hw/(.*) /usr/local/apache/htdocs/hw/$1 [L]
This will reserve the directory /usr/local/apache/htdocs/hw for additional scripts and other files. Just make sure this rule is evaluated before the one above. There is just a little drawback: all Hyperwave objects whose name starts with 'hw/' will be shadowed. So, make sure you don't use such names. If you need more directories, e.g. for images just add more rules or place them all in one directory. Before you put those instructions, don't forget to turn on the rewriting engine with
RewriteEngine on
You will need scripts:
  • to return the object itself
  • to allow searching
  • to identify yourself
  • to set your profile
  • one for each additional function like to show the object attributes, to show information about users, to show the status of the server, etc.

As an alternative to the Rewrite Engine, you can also consider using the Apache ErrorDocument directive, but be aware, that ErrorDocument redirected pages cannot receive POST data.


Hyperwave API Functions

Integration with Apache

The integration with Apache and possible other servers has been described in the separate chapter.

Classes

The API provided by the HW_API extension is fully object oriented. It is very similar to the C++ interface of the Hyperwave SDK. It consist of the following classes.

  • HW_API
  • HW_API_Object
  • HW_API_Attribute
  • HW_API_Error
  • HW_API_Content
  • HW_API_Reason
Some basic classes like HW_API_String, HW_API_String_Array, etc., which exist in the Hyperwave SDK have not been implemented since PHP has powerful replacements for them.

Each class has certain method, whose names are identical to its counterparts in the Hyperwave SDK. Passing arguments to this function differs from all the other PHP extensions but is close to the C++ API of the HW SDK. Instead of passing several parameters they are all put into an associated array and passed as one parameter. The names of the keys are identical to those documented in the HW SDK. The common parameters are listed below. If other parameters are required they will be documented if needed.

  • objectIdentifier The name or id of an object, e.g. "rootcollection", "0x873A8768 0x00000002".
  • parentIdentifier The name or id of an object which is considered to be a parent.
  • object An instance of class HW_API_Object.
  • parameters An instance of class HW_API_Object.
  • version The version of an object.
  • mode An integer value determine the way an operation is executed.
  • attributeSelector Any array of strings, each containing a name of an attribute. This is used if you retrieve the object record and want to include certain attributes.
  • objectQuery A query to select certain object out of a list of objects. This is used to reduce the number of objects which was delivered by a function like hw_api::children() or hw_api::find().

Note:

Methods returning boolean can return TRUE, FALSE or HW_API_Error object.

Table of Contents

  • hw_api::checkin — Checks in an object
  • hw_api::checkout — Checks out an object
  • hw_api::children — Returns children of an object
  • hw_api::content — Returns content of an object
  • hw_api::copy — Copies physically
  • hw_api::dbstat — Returns statistics about database server
  • hw_api::dcstat — Returns statistics about document cache server
  • hw_api::dstanchors — Returns a list of all destination anchors
  • hw_api::dstofsrcanchor — Returns destination of a source anchor
  • hw_api::find — Search for objects
  • hw_api::ftstat — Returns statistics about fulltext server
  • hw_api::hwstat — Returns statistics about Hyperwave server
  • hw_api::identify — Log into Hyperwave Server
  • hw_api::info — Returns information about server configuration
  • hw_api::insert — Inserts a new object
  • hw_api::insertanchor — Inserts a new object of type anchor
  • hw_api::insertcollection — Inserts a new object of type collection
  • hw_api::insertdocument — Inserts a new object of type document
  • hw_api::link — Creates a link to an object
  • hw_api::lock — Locks an object
  • hw_api::move — Moves object between collections
  • hw_api::object — Retrieve attribute information
  • hw_api::objectbyanchor — Returns the object an anchor belongs to
  • hw_api::parents — Returns parents of an object
  • hw_api::remove — Delete an object
  • hw_api::replace — Replaces an object
  • hw_api::setcommittedversion — Commits version other than last version
  • hw_api::srcanchors — Returns a list of all source anchors
  • hw_api::srcsofdst — Returns source of a destination object
  • hw_api::unlock — Unlocks a locked object
  • hw_api::user — Returns the own user object
  • hw_api::userlist — Returns a list of all logged in users
  • hw_api_attribute::key — Returns key of the attribute
  • hw_api_attribute::langdepvalue — Returns value for a given language
  • hw_api_attribute::value — Returns value of the attribute
  • hw_api_attribute::values — Returns all values of the attribute
  • hw_api_content::mimetype — Returns mimetype
  • hw_api_content::read — Read content
  • hw_api_error::count — Returns number of reasons
  • hw_api_error::reason — Returns reason of error
  • hw_api_object::assign — Clones object
  • hw_api_object::attreditable — Checks whether an attribute is editable
  • hw_api_object::count — Returns number of attributes
  • hw_api_object::insert — Inserts new attribute
  • hw_api_object::remove — Removes attribute
  • hw_api_object::title — Returns the title attribute
  • hw_api_object::value — Returns value of attribute
  • hw_api_reason::description — Returns description of reason
  • hw_api_reason::type — Returns type of reason
  • hwapi_attribute_new — Creates instance of class hw_api_attribute
  • hwapi_content_new — Create new instance of class hw_api_content
  • hwapi_hgcsp — Returns object of class hw_api
  • hwapi_object_new — Creates a new instance of class hwapi_object_new


Checks in an object

  • « Hyperwave API Functions
  • hw_api::checkout »
  • PHP Manual
  • Hyperwave API Functions
  • Checks in an object

hw_api::checkin

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::checkin — Checks in an object

Description

hw_api::checkin ( array $parameter ) : bool

This function checks in an object or a whole hierarchy of objects. The parameters array contains the required element 'objectIdentifier' and the optional element 'version', 'comment', 'mode' and 'objectQuery'. 'version' sets the version of the object. It consists of the major and minor version separated by a period. If the version is not set, the minor version is incremented. 'mode' can be one of the following values:

HW_API_CHECKIN_NORMAL
Checks in and commits the object. The object must be a document.
HW_API_CHECKIN_RECURSIVE
If the object to check in is a collection, all children will be checked in recursively if they are documents. Trying to check in a collection would result in an error.
HW_API_CHECKIN_FORCE_VERSION_CONTROL
Checks in an object even if it is not under version control.
HW_API_CHECKIN_REVERT_IF_NOT_CHANGED
Check if the new version is different from the last version. Unless this is the case the object will be checked in.
HW_API_CHECKIN_KEEP_TIME_MODIFIED
Keeps the time modified from the most recent object.
HW_API_CHECKIN_NO_AUTO_COMMIT
The object is not automatically committed on check-in.

Parameters

parameter

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • hw_api::checkout


Checks out an object

  • « hw_api::checkin
  • hw_api::children »
  • PHP Manual
  • Hyperwave API Functions
  • Checks out an object

hw_api::checkout

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::checkout — Checks out an object

Description

hw_api::checkout ( array $parameter ) : bool

This function checks out an object or a whole hierarchy of objects.

Parameters

parameter

The parameters array contains the required element 'objectIdentifier' and the optional element 'version', 'mode' and 'objectQuery'. 'mode' can be one of the following values:

HW_API_CHECKIN_NORMAL
Checks out an object. The object must be a document.
HW_API_CHECKIN_RECURSIVE
If the object to check out is a collection, all children will be checked out recursively if they are documents. Trying to check out a collection would result in an error.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • hw_api::checkin


Returns children of an object

  • « hw_api::checkout
  • hw_api::content »
  • PHP Manual
  • Hyperwave API Functions
  • Returns children of an object

hw_api::children

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::children — Returns children of an object

Description

hw_api::children ( array $parameter ) : array

Retrieves the children of a collection or the attributes of a document. The children can be further filtered by specifying an object query.

Parameters

parameter

The parameter array contains the required elements 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

Return Values

The return value is an array of objects of type HW_API_Object or HW_API_Error.

See Also

  • hw_api::parents


Returns content of an object

  • « hw_api::children
  • hw_api::copy »
  • PHP Manual
  • Hyperwave API Functions
  • Returns content of an object

hw_api::content

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::content — Returns content of an object

Description

hw_api::content ( array $parameter ) : HW_API_Content

This function returns the content of a document as an object of type hw_api_content.

Parameters

parameter

The parameter array contains the required elements 'objectidentifier' and the optional element 'mode'. The mode can be one of the constants HW_API_CONTENT_ALLLINKS, HW_API_CONTENT_REACHABLELINKS or HW_API_CONTENT_PLAIN.

HW_API_CONTENT_ALLLINKS means to insert all anchors even if the destination is not reachable.

HW_API_CONTENT_REACHABLELINKS tells this method to insert only reachable links and HW_API_CONTENT_PLAIN will lead to document without any links.

Return Values

Returns an instance of hw_api_content.


Copies physically

  • « hw_api::content
  • hw_api::dbstat »
  • PHP Manual
  • Hyperwave API Functions
  • Copies physically

hw_api::copy

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::copy — Copies physically

Description

hw_api::copy ( array $parameter ) : hw_api_content

This function will make a physical copy including the content if it exists and returns the new object or an error object.

Parameters

parameter

The parameter array contains the required elements 'objectIdentifier' and 'destinationParentIdentifier'. The optional parameter is 'attributeSelector'`

Return Values

Returns the copied object.

See Also

  • hw_api::move
  • hw_api::link


Returns statistics about database server

  • « hw_api::copy
  • hw_api::dcstat »
  • PHP Manual
  • Hyperwave API Functions
  • Returns statistics about database server

hw_api::dbstat

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::dbstat — Returns statistics about database server

Description

hw_api::dbstat ( array $parameter ) : hw_api_object

Returns statistics about database server.

Parameters

parameter

Return Values

See Also

  • hw_api::dcstat
  • hw_api::hwstat
  • hw_api::ftstat


Returns statistics about document cache server

  • « hw_api::dbstat
  • hw_api::dstanchors »
  • PHP Manual
  • Hyperwave API Functions
  • Returns statistics about document cache server

hw_api::dcstat

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::dcstat — Returns statistics about document cache server

Description

hw_api::dcstat ( array $parameter ) : hw_api_object

Returns statistics about document cache server.

Parameters

parameter

Return Values

See Also

  • hw_api::dbstat
  • hw_api::hwstat
  • hw_api::ftstat


Returns a list of all destination anchors

  • « hw_api::dcstat
  • hw_api::dstofsrcanchor »
  • PHP Manual
  • Hyperwave API Functions
  • Returns a list of all destination anchors

hw_api::dstanchors

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::dstanchors — Returns a list of all destination anchors

Description

hw_api::dstanchors ( array $parameter ) : array

Retrieves all destination anchors of an object.

Parameters

parameter

The parameter array contains the required element 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

Return Values

See Also

  • hw_api::srcanchors


Returns destination of a source anchor

  • « hw_api::dstanchors
  • hw_api::find »
  • PHP Manual
  • Hyperwave API Functions
  • Returns destination of a source anchor

hw_api::dstofsrcanchor

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::dstofsrcanchor — Returns destination of a source anchor

Description

hw_api::dstofsrcanchor ( array $parameter ) : hw_api_object

Retrieves the destination object pointed by the specified source anchors. The destination object can either be a destination anchor or a whole document.

Parameters

parameter

The parameters array contains the required element 'objectIdentifier' and the optional element 'attributeSelector'.

Return Values

See Also

  • hw_api::srcanchors
  • hw_api::dstanchors
  • hw_api::objectbyanchor


Search for objects

  • « hw_api::dstofsrcanchor
  • hw_api::ftstat »
  • PHP Manual
  • Hyperwave API Functions
  • Search for objects

hw_api::find

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::find — Search for objects

Description

hw_api::find ( array $parameter ) : array

This functions searches for objects either by executing a key or/and full text query. The found objects can further be filtered by an optional object query. They are sorted by their importance. The second search operation is relatively slow and its result can be limited to a certain number of hits. This allows to perform an incremental search, each returning just a subset of all found documents, starting at a given index.

Parameters

parameter

The parameter array contains the 'keyquery' or/and 'fulltextquery' depending on who you would like to search. Optional parameters are 'objectquery', 'scope', 'languages' and 'attributeselector'. In case of an incremental search the optional parameters 'startIndex', 'numberOfObjectsToGet' and 'exactMatchUnit' can be passed.

Return Values


Returns statistics about fulltext server

  • « hw_api::find
  • hw_api::hwstat »
  • PHP Manual
  • Hyperwave API Functions
  • Returns statistics about fulltext server

hw_api::ftstat

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::ftstat — Returns statistics about fulltext server

Description

hw_api::ftstat ( array $parameter ) : hw_api_object

Returns statistics about fulltext server.

Parameters

parameter

Return Values

See Also

  • hw_api::dcstat
  • hw_api::dbstat
  • hw_api::hwstat


Returns statistics about Hyperwave server

  • « hw_api::ftstat
  • hw_api::identify »
  • PHP Manual
  • Hyperwave API Functions
  • Returns statistics about Hyperwave server

hw_api::hwstat

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::hwstat — Returns statistics about Hyperwave server

Description

hw_api::hwstat ( array $parameter ) : hw_api_object

Returns statistics about Hyperwave server.

Parameters

parameter

Return Values

See Also

  • hw_api::dcstat
  • hw_api::dbstat
  • hw_api::ftstat


Log into Hyperwave Server

  • « hw_api::hwstat
  • hw_api::info »
  • PHP Manual
  • Hyperwave API Functions
  • Log into Hyperwave Server

hw_api::identify

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::identify — Log into Hyperwave Server

Description

hw_api::identify ( array $parameter ) : bool

Logs into the Hyperwave Server.

Parameters

parameter

The parameter array must contain the elements 'username' and 'password'.

Return Values

Returns an object of typeHW_API_Error if identification failed or TRUE if it was successful.


Returns information about server configuration

  • « hw_api::identify
  • hw_api::insert »
  • PHP Manual
  • Hyperwave API Functions
  • Returns information about server configuration

hw_api::info

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::info — Returns information about server configuration

Description

hw_api::info ( array $parameter ) : array

Returns information about server configuration.

Parameters

parameter

Return Values

See Also

  • hw_api::dcstat
  • hw_api::dbstat
  • hw_api::ftstat
  • hw_api::hwstat


Inserts a new object

  • « hw_api::info
  • hw_api::insertanchor »
  • PHP Manual
  • Hyperwave API Functions
  • Inserts a new object

hw_api::insert

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::insert — Inserts a new object

Description

hw_api::insert ( array $parameter ) : hw_api_object

Insert a new object. The object type can be user, group, document or anchor. Depending on the type other object attributes has to be set.

Parameters

parameter

The parameter array contains the required elements 'object' and 'content' (if the object is a document) and the optional parameters 'parameters', 'mode' and 'attributeSelector'. The 'object' must contain all attributes of the object. 'parameters' is an object as well holding further attributes like the destination (attribute key is 'Parent'). 'content' is the content of the document. 'mode' can be a combination of the following flags:

HW_API_INSERT_NORMAL
The object in inserted into the server.
HW_API_INSERT_FORCE_VERSION_CONTROL
HW_API_INSERT_AUTOMATIC_CHECKOUT
HW_API_INSERT_PLAIN
HW_API_INSERT_KEEP_TIME_MODIFIED
HW_API_INSERT_DELAY_INDEXING

Return Values

See Also

  • hw_api::replace


Inserts a new object of type anchor

  • « hw_api::insert
  • hw_api::insertcollection »
  • PHP Manual
  • Hyperwave API Functions
  • Inserts a new object of type anchor

hw_api::insertanchor

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::insertanchor — Inserts a new object of type anchor

Description

hw_api::insertanchor ( array $parameter ) : hw_api_object

This function is a shortcut for hwapi_insert(). It inserts an object of type anchor and sets some of the attributes required for an anchor.

Parameters

parameter

The parameter array contains the required elements 'object' and 'documentIdentifier' and the optional elements 'destinationIdentifier', 'parameter', 'hint' and 'attributeSelector'. The 'documentIdentifier' specifies the document where the anchor shall be inserted. The target of the anchor is set in 'destinationIdentifier' if it already exists. If the target does not exists the element 'hint' has to be set to the name of object which is supposed to be inserted later. Once it is inserted the anchor target is resolved automatically.

Return Values

See Also

  • hw_api::insert
  • hw_api::insertdocument
  • hw_api::insertcollection


Inserts a new object of type collection

  • « hw_api::insertanchor
  • hw_api::insertdocument »
  • PHP Manual
  • Hyperwave API Functions
  • Inserts a new object of type collection

hw_api::insertcollection

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::insertcollection — Inserts a new object of type collection

Description

hw_api::insertcollection ( array $parameter ) : hw_api_object

This function is a shortcut for hwapi_insert(). It inserts an object of type collection and sets some of the attributes required for a collection.

Parameters

parameter

The parameter array contains the required elements 'object' and 'parentIdentifier' and the optional elements 'parameter' and 'attributeSelector'. See hwapi_insert() for the meaning of each element.

Return Values

See Also

  • hw_api::insert
  • hw_api::insertdocument
  • hw_api::insertanchor


Inserts a new object of type document

  • « hw_api::insertcollection
  • hw_api::link »
  • PHP Manual
  • Hyperwave API Functions
  • Inserts a new object of type document

hw_api::insertdocument

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::insertdocument — Inserts a new object of type document

Description

hw_api::insertdocument ( array $parameter ) : hw_api_object

This function is a shortcut for hwapi_insert(). It inserts an object with content and sets some of the attributes required for a document.

Parameters

parameter

The parameter array contains the required elements 'object', 'parentIdentifier' and 'content' and the optional elements 'mode', 'parameter' and 'attributeSelector'.

See hwapi_insert() for the meaning of each element.

Return Values

See Also

  • hw_api::insert
  • hw_api::insertcollection
  • hw_api::insertanchor


Creates a link to an object

  • « hw_api::insertdocument
  • hw_api::lock »
  • PHP Manual
  • Hyperwave API Functions
  • Creates a link to an object

hw_api::link

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::link — Creates a link to an object

Description

hw_api::link ( array $parameter ) : bool

Creates a link to an object. Accessing this link is like accessing the object to links points to.

Parameters

parameter

The parameter array contains the required elements 'objectIdentifier' and 'destinationParentIdentifier'. 'destinationParentIdentifier' is the target collection.

Return Values

The function returns TRUE on success or an error object.

See Also

  • hw_api::copy


Locks an object

  • « hw_api::link
  • hw_api::move »
  • PHP Manual
  • Hyperwave API Functions
  • Locks an object

hw_api::lock

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::lock — Locks an object

Description

hw_api::lock ( array $parameter ) : bool

Locks an object for exclusive editing by the user calling this function. The object can be only unlocked by this user or the system user.

Parameters

parameter

The parameter array contains the required element 'objectIdentifier' and the optional parameters 'mode' and 'objectquery'.

'mode' determines how an object is locked. HW_API_LOCK_NORMAL means, an object is locked until it is unlocked. HW_API_LOCK_RECURSIVE is only valid for collection and locks all objects within the collection and possible subcollections. HW_API_LOCK_SESSION means, an object is locked only as long as the session is valid.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • hw_api::unlock


Moves object between collections

  • « hw_api::lock
  • hw_api::object »
  • PHP Manual
  • Hyperwave API Functions
  • Moves object between collections

hw_api::move

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::move — Moves object between collections

Description

hw_api::move ( array $parameter ) : bool

Moves object between collections.

Parameters

parameter

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • hw_objrec2array()


Retrieve attribute information

  • « hw_api::move
  • hw_api::objectbyanchor »
  • PHP Manual
  • Hyperwave API Functions
  • Retrieve attribute information

hw_api::object

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::object — Retrieve attribute information

Description

hw_api::object ( array $parameter ) : hw_api_object

This function retrieves the attribute information of an object of any version. It will not return the document content.

Parameters

parameter

The parameter array contains the required elements 'objectIdentifier' and the optional elements 'attributeSelector' and 'version'.

Return Values

The returned object is an instance of class HW_API_Object on success or HW_API_Error if an error occurred.

Examples

This simple example retrieves an object and checks for errors.

Example #1 Retrieve an object

<?php
function handle_error($error)
{
  $reason = $error->reason(0);
  echo "Type: <b>";
  switch ($reason->type()) {
    case 0:
      echo "Error";
      break;
    case 1:
      echo "Warning";
      break;
    case 2:
      echo "Message";
      break;
  }
  echo "</b><br />\n";
  echo "Description: " . $reason->description("en") . "<br />\n";
}

function list_attr($obj)
{
  echo "<table>\n";
  $count = $obj->count();
  for ($i=0; $i<$count; $i++) {
    $attr = $obj->attribute($i);
    printf("<tr><td align=\"right\" bgcolor=\"#c0c0c0\"><b>%s</b></td><td bgcolor=\"#F0F0F0\">%s</td></tr>\n",
             $attr->key(), $attr->value());
  }
  echo "</table>\n";
}

$hwapi = hwapi_hgcsp($g_config[HOSTNAME]);
$parms = array("objectIdentifier"=>"rootcollection", "attributeSelector"=>array("Title", "Name", "DocumentType"));
$root = $hwapi->object($parms);
if (get_class($root) == "HW_API_Error") {
  handle_error($root);
  exit;
}
list_attr($root);
?>

See Also

  • hw_api::content


Returns the object an anchor belongs to

  • « hw_api::object
  • hw_api::parents »
  • PHP Manual
  • Hyperwave API Functions
  • Returns the object an anchor belongs to

hw_api::objectbyanchor

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::objectbyanchor — Returns the object an anchor belongs to

Description

hw_api::objectbyanchor ( array $parameter ) : hw_api_object

This function retrieves an object the specified anchor belongs to.

Parameters

parameter

The parameter array contains the required element 'objectIdentifier' and the optional element 'attributeSelector'.

Return Values

See Also

  • hw_api::dstofsrcanchor
  • hw_api::srcanchors
  • hw_api::dstanchors


Returns parents of an object

  • « hw_api::objectbyanchor
  • hw_api::remove »
  • PHP Manual
  • Hyperwave API Functions
  • Returns parents of an object

hw_api::parents

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::parents — Returns parents of an object

Description

hw_api::parents ( array $parameter ) : array

Retrieves the parents of an object. The parents can be further filtered by specifying an object query.

Parameters

parameter

The parameter array contains the required elements 'objectidentifier' and the optional elements 'attributeselector' and 'objectquery'.

Return Values

The return value is an array of objects of type HW_API_Object or HW_API_Error.

See Also

  • hw_api::children


Delete an object

  • « hw_api::parents
  • hw_api::replace »
  • PHP Manual
  • Hyperwave API Functions
  • Delete an object

hw_api::remove

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::remove — Delete an object

Description

hw_api::remove ( array $parameter ) : bool

Removes an object from the specified parent. Collections will be removed recursively.

Parameters

parameter

You can pass an optional object query to remove only those objects which match the query. An object will be deleted physically if it is the last instance.

The parameter array contains the required elements 'objectidentifier' and 'parentidentifier'. If you want to remove a user or group 'parentidentifier' can be skipped.

The optional parameter 'mode' determines how the deletion is performed. In normal mode the object will not be removed physically until all instances are removed. In physical mode all instances of the object will be deleted immediately. In removelinks mode all references to and from the objects will be deleted as well. In nonrecursive the deletion is not performed recursive. Removing a collection which is not empty will cause an error.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • hw_api::move


Replaces an object

  • « hw_api::remove
  • hw_api::setcommittedversion »
  • PHP Manual
  • Hyperwave API Functions
  • Replaces an object

hw_api::replace

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::replace — Replaces an object

Description

hw_api::replace ( array $parameter ) : hw_api_object

Replaces the attributes and the content of an object.

Parameters

parameter

The parameter array contains the required elements 'objectIdentifier' and 'object' and the optional parameters 'content', 'parameters', 'mode' and 'attributeSelector'. 'objectIdentifier' contains the object to be replaced. 'object' contains the new object. 'content' contains the new content. 'parameters' contain extra information for HTML documents. HTML_Language is the letter abbreviation of the language of the title. HTML_Base sets the base attribute of the HTML document.

'mode' can be a combination of the following flags:

HW_API_REPLACE_NORMAL
The object on the server is replace with the object passed.
HW_API_REPLACE_FORCE_VERSION_CONTROL
HW_API_REPLACE_AUTOMATIC_CHECKOUT
HW_API_REPLACE_AUTOMATIC_CHECKIN
HW_API_REPLACE_PLAIN
HW_API_REPLACE_REVERT_IF_NOT_CHANGED
HW_API_REPLACE_KEEP_TIME_MODIFIED

Return Values

See Also

  • hw_api::insert


Commits version other than last version

  • « hw_api::replace
  • hw_api::srcanchors »
  • PHP Manual
  • Hyperwave API Functions
  • Commits version other than last version

hw_api::setcommittedversion

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::setcommittedversion — Commits version other than last version

Description

hw_api::setcommittedversion ( array $parameter ) : hw_api_object

Commits a version of a document. The committed version is the one which is visible to users with read access. By default the last version is the committed version.

Parameters

parameter

Return Values

See Also

  • hw_api::checkin
  • hw_api::checkout


Returns a list of all source anchors

  • « hw_api::setcommittedversion
  • hw_api::srcsofdst »
  • PHP Manual
  • Hyperwave API Functions
  • Returns a list of all source anchors

hw_api::srcanchors

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::srcanchors — Returns a list of all source anchors

Description

hw_api::srcanchors ( array $parameter ) : array

Retrieves all source anchors of an object.

Parameters

parameter

The parameter array contains the required element 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

Return Values

See Also

  • hw_api::dstanchors


Returns source of a destination object

  • « hw_api::srcanchors
  • hw_api::unlock »
  • PHP Manual
  • Hyperwave API Functions
  • Returns source of a destination object

hw_api::srcsofdst

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::srcsofdst — Returns source of a destination object

Description

hw_api::srcsofdst ( array $parameter ) : array

Retrieves all the source anchors pointing to the specified destination. The destination object can either be a destination anchor or a whole document.

Parameters

parameter

The parameters array contains the required element 'objectIdentifier' and the optional element 'attributeSelector' and 'objectQuery'. The function returns an array of objects or an error.

Return Values

See Also

  • hw_api::dstofsrcanchor


Unlocks a locked object

  • « hw_api::srcsofdst
  • hw_api::user »
  • PHP Manual
  • Hyperwave API Functions
  • Unlocks a locked object

hw_api::unlock

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::unlock — Unlocks a locked object

Description

hw_api::unlock ( array $parameter ) : bool

Unlocks a locked object. Only the user who has locked the object and the system user may unlock an object.

Parameters

parameter

The parameter array contains the required element 'objectIdentifier' and the optional parameters 'mode' and 'objectquery'. The meaning of 'mode' is the same as in function hwapi_lock().

Return Values

Returns TRUE on success or an object of class HW_API_Error.

See Also

  • hw_api::lock


Returns the own user object

  • « hw_api::unlock
  • hw_api::userlist »
  • PHP Manual
  • Hyperwave API Functions
  • Returns the own user object

hw_api::user

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::user — Returns the own user object

Description

hw_api::user ( array $parameter ) : hw_api_object

Returns the own user object.

Parameters

parameter

Return Values

See Also

  • hw_api::userlist


Returns a list of all logged in users

  • « hw_api::user
  • hw_api_attribute::key »
  • PHP Manual
  • Hyperwave API Functions
  • Returns a list of all logged in users

hw_api::userlist

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api::userlist — Returns a list of all logged in users

Description

hw_api::userlist ( array $parameter ) : array

Returns a list of all logged in users.

Parameters

parameter

Return Values

See Also

  • hw_api::user


Returns key of the attribute

  • « hw_api::userlist
  • hw_api_attribute::langdepvalue »
  • PHP Manual
  • Hyperwave API Functions
  • Returns key of the attribute

hw_api_attribute::key

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_attribute::key — Returns key of the attribute

Description

hw_api_attribute::key ( void ) : string

Returns the name of the attribute.

Return Values

Returns the name of the attribute as a string.

See Also

  • hw_api_attribute::value


Returns value for a given language

  • « hw_api_attribute::key
  • hw_api_attribute::value »
  • PHP Manual
  • Hyperwave API Functions
  • Returns value for a given language

hw_api_attribute::langdepvalue

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_attribute::langdepvalue — Returns value for a given language

Description

hw_api_attribute::langdepvalue ( string $language ) : string

Returns the value in the given language of the attribute.

Parameters

language

Return Values

Returns the value of the attribute as a string.

See Also

  • hw_api_attribute::value


Returns value of the attribute

  • « hw_api_attribute::langdepvalue
  • hw_api_attribute::values »
  • PHP Manual
  • Hyperwave API Functions
  • Returns value of the attribute

hw_api_attribute::value

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_attribute::value — Returns value of the attribute

Description

hw_api_attribute::value ( void ) : string

Gets the value of the attribute.

Return Values

Returns the value, as a string.

See Also

  • hw_api_attribute::key
  • hw_api_attribute::values


Returns all values of the attribute

  • « hw_api_attribute::value
  • hw_api_content::mimetype »
  • PHP Manual
  • Hyperwave API Functions
  • Returns all values of the attribute

hw_api_attribute::values

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_attribute::values — Returns all values of the attribute

Description

hw_api_attribute::values ( void ) : array

Gets all values of the attribute.

Return Values

Returns an array of attribute values.

See Also

  • hw_api_attribute::value


Returns mimetype

  • « hw_api_attribute::values
  • hw_api_content::read »
  • PHP Manual
  • Hyperwave API Functions
  • Returns mimetype

hw_api_content::mimetype

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_content::mimetype — Returns mimetype

Description

hw_api_content::mimetype ( void ) : string

Returns the mimetype of the content.

Return Values

Returns the mimetype as a string.


Read content

  • « hw_api_content::mimetype
  • hw_api_error::count »
  • PHP Manual
  • Hyperwave API Functions
  • Read content

hw_api_content::read

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_content::read — Read content

Description

hw_api_content::read ( string $buffer , int $len ) : string

Reads len bytes from the content into the given buffer.

Parameters

buffer

len

Number of bytes to read.

Return Values


Returns number of reasons

  • « hw_api_content::read
  • hw_api_error::reason »
  • PHP Manual
  • Hyperwave API Functions
  • Returns number of reasons

hw_api_error::count

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_error::count — Returns number of reasons

Description

hw_api_error::count ( void ) : int

Returns the number of error reasons.

Return Values

Returns the number of errors, as an integer.

See Also

  • hw_api_error::reason


Returns reason of error

  • « hw_api_error::count
  • hw_api_object::assign »
  • PHP Manual
  • Hyperwave API Functions
  • Returns reason of error

hw_api_error::reason

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_error::reason — Returns reason of error

Description

hw_api_error::reason ( void ) : HW_API_Reason

Returns the first error reason.

Return Values

See Also

  • hw_api_error::count


Clones object

  • « hw_api_error::reason
  • hw_api_object::attreditable »
  • PHP Manual
  • Hyperwave API Functions
  • Clones object

hw_api_object::assign

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_object::assign — Clones object

Description

hw_api_object::assign ( array $parameter ) : bool

Clones the attributes of an object.

Parameters

parameter

Return Values

Returns TRUE on success or FALSE on failure.


Checks whether an attribute is editable

  • « hw_api_object::assign
  • hw_api_object::count »
  • PHP Manual
  • Hyperwave API Functions
  • Checks whether an attribute is editable

hw_api_object::attreditable

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_object::attreditable — Checks whether an attribute is editable

Description

hw_api_object::attreditable ( array $parameter ) : bool

Checks whether an attribute is editable.

Parameters

parameter

Return Values

Returns TRUE if the attribute is editable, FALSE otherwise.


Returns number of attributes

  • « hw_api_object::attreditable
  • hw_api_object::insert »
  • PHP Manual
  • Hyperwave API Functions
  • Returns number of attributes

hw_api_object::count

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_object::count — Returns number of attributes

Description

hw_api_object::count ( array $parameter ) : int

Returns the number of attributes.

Parameters

parameter

Return Values

Returns the number as an integer.


Inserts new attribute

  • « hw_api_object::count
  • hw_api_object::remove »
  • PHP Manual
  • Hyperwave API Functions
  • Inserts new attribute

hw_api_object::insert

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_object::insert — Inserts new attribute

Description

hw_api_object::insert ( HW_API_Attribute $attribute ) : bool

Adds an attribute to the object.

Parameters

attribute

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • hw_api_object::remove


Removes attribute

  • « hw_api_object::insert
  • hw_api_object::title »
  • PHP Manual
  • Hyperwave API Functions
  • Removes attribute

hw_api_object::remove

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_object::remove — Removes attribute

Description

hw_api_object::remove ( string $name ) : bool

Removes the attribute with the given name.

Parameters

name

The attribute name.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • hw_api_object::insert


Returns the title attribute

  • « hw_api_object::remove
  • hw_api_object::value »
  • PHP Manual
  • Hyperwave API Functions
  • Returns the title attribute

hw_api_object::title

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_object::title — Returns the title attribute

Description

hw_api_object::title ( array $parameter ) : string

Returns the title attribute.

Parameters

parameter

Return Values

Returns the title as a string.


Returns value of attribute

  • « hw_api_object::title
  • hw_api_reason::description »
  • PHP Manual
  • Hyperwave API Functions
  • Returns value of attribute

hw_api_object::value

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_object::value — Returns value of attribute

Description

hw_api_object::value ( string $name ) : string

Returns value of an attribute.

Parameters

name

The attribute name.

Return Values

Returns the value of the attribute with the given name or FALSE if an error occurred.


Returns description of reason

  • « hw_api_object::value
  • hw_api_reason::type »
  • PHP Manual
  • Hyperwave API Functions
  • Returns description of reason

hw_api_reason::description

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_reason::description — Returns description of reason

Description

hw_api_reason::description ( void ) : string

Returns the description of a reason

Return Values

Returns the description, as a string.


Returns type of reason

  • « hw_api_reason::description
  • hwapi_attribute_new »
  • PHP Manual
  • Hyperwave API Functions
  • Returns type of reason

hw_api_reason::type

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hw_api_reason::type — Returns type of reason

Description

hw_api_reason::type ( void ) : HW_API_Reason

Returns the type of a reason.

Return Values

Returns an instance of HW_API_Reason.


Creates instance of class hw_api_attribute

  • « hw_api_reason::type
  • hwapi_content_new »
  • PHP Manual
  • Hyperwave API Functions
  • Creates instance of class hw_api_attribute

hwapi_attribute_new

(PHP 5 < 5.2.0)

hwapi_attribute_new — Creates instance of class hw_api_attribute

Description

hwapi_attribute_new ([ string $name [, string $value ]] ) : HW_API_Attribute

Creates a new instance of hw_api_attribute with the given name and value.

Parameters

name

The attribute name.

value

The attribute value.

Return Values

Returns an instance of hw_api_attribute.


Create new instance of class hw_api_content

  • « hwapi_attribute_new
  • hwapi_hgcsp »
  • PHP Manual
  • Hyperwave API Functions
  • Create new instance of class hw_api_content

hwapi_content_new

(PHP 5 < 5.2.0)

hwapi_content_new — Create new instance of class hw_api_content

Description

hwapi_content_new ( string $content , string $mimetype ) : HW_API_Content

Creates a new content object from the string content.

Parameters

content

mimetype

The mimetype for the contents.

Return Values


Returns object of class hw_api

  • « hwapi_content_new
  • hwapi_object_new »
  • PHP Manual
  • Hyperwave API Functions
  • Returns object of class hw_api

hwapi_hgcsp

(PHP 4, PHP 5 < 5.2.0, PECL hwapi SVN)

hwapi_hgcsp — Returns object of class hw_api

Description

hwapi_hgcsp ( string $hostname [, int $port ] ) : HW_API

Opens a connection to the Hyperwave server on host hostname. The protocol used is HGCSP.

Parameters

hostname

The host name.

port

If you do not pass a port number, 418 is used.

Return Values

Returns an instance of HW_API.


Creates a new instance of class hwapi_object_new

  • « hwapi_hgcsp
  • LDAP »
  • PHP Manual
  • Hyperwave API Functions
  • Creates a new instance of class hwapi_object_new

hwapi_object_new

(PHP 5 < 5.2.0)

hwapi_object_new — Creates a new instance of class hwapi_object_new

Description

hwapi_object_new ( array $parameter ) : hw_api_object

Creates a new instance of the class hw_api_object.

Parameters

parameter

Return Values

See Also

  • hw_api::lock


Lightweight Directory Access Protocol

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Using the PHP LDAP calls
  • LDAP controls
  • Examples
    • Basic usage
    • LDAP Controls
  • LDAP Functions
    • ldap_8859_to_t61 — Translate 8859 characters to t61 characters
    • ldap_add_ext — Add entries to LDAP directory
    • ldap_add — Add entries to LDAP directory
    • ldap_bind_ext — Bind to LDAP directory
    • ldap_bind — Bind to LDAP directory
    • ldap_close — Alias of ldap_unbind
    • ldap_compare — Compare value of attribute found in entry specified with DN
    • ldap_connect — Connect to an LDAP server
    • ldap_control_paged_result_response — Retrieve the LDAP pagination cookie
    • ldap_control_paged_result — Send LDAP pagination control
    • ldap_count_entries — Count the number of entries in a search
    • ldap_delete_ext — Delete an entry from a directory
    • ldap_delete — Delete an entry from a directory
    • ldap_dn2ufn — Convert DN to User Friendly Naming format
    • ldap_err2str — Convert LDAP error number into string error message
    • ldap_errno — Return the LDAP error number of the last LDAP command
    • ldap_error — Return the LDAP error message of the last LDAP command
    • ldap_escape — Escape a string for use in an LDAP filter or DN
    • ldap_exop_passwd — PASSWD extended operation helper
    • ldap_exop_refresh — Refresh extended operation helper
    • ldap_exop_whoami — WHOAMI extended operation helper
    • ldap_exop — Performs an extended operation
    • ldap_explode_dn — Splits DN into its component parts
    • ldap_first_attribute — Return first attribute
    • ldap_first_entry — Return first result id
    • ldap_first_reference — Return first reference
    • ldap_free_result — Free result memory
    • ldap_get_attributes — Get attributes from a search result entry
    • ldap_get_dn — Get the DN of a result entry
    • ldap_get_entries — Get all result entries
    • ldap_get_option — Get the current value for given option
    • ldap_get_values_len — Get all binary values from a result entry
    • ldap_get_values — Get all values from a result entry
    • ldap_list — Single-level search
    • ldap_mod_add_ext — Add attribute values to current attributes
    • ldap_mod_add — Add attribute values to current attributes
    • ldap_mod_del_ext — Delete attribute values from current attributes
    • ldap_mod_del — Delete attribute values from current attributes
    • ldap_mod_replace_ext — Replace attribute values with new ones
    • ldap_mod_replace — Replace attribute values with new ones
    • ldap_modify_batch — Batch and execute modifications on an LDAP entry
    • ldap_modify — Alias of ldap_mod_replace
    • ldap_next_attribute — Get the next attribute in result
    • ldap_next_entry — Get next result entry
    • ldap_next_reference — Get next reference
    • ldap_parse_exop — Parse result object from an LDAP extended operation
    • ldap_parse_reference — Extract information from reference entry
    • ldap_parse_result — Extract information from result
    • ldap_read — Read an entry
    • ldap_rename_ext — Modify the name of an entry
    • ldap_rename — Modify the name of an entry
    • ldap_sasl_bind — Bind to LDAP directory using SASL
    • ldap_search — Search LDAP tree
    • ldap_set_option — Set the value of the given option
    • ldap_set_rebind_proc — Set a callback function to do re-binds on referral chasing
    • ldap_sort — Sort LDAP result entries on the client side
    • ldap_start_tls — Start TLS
    • ldap_t61_to_8859 — Translate t61 characters to 8859 characters
    • ldap_unbind — Unbind from LDAP directory


Introduction

LDAP is the Lightweight Directory Access Protocol, and is a protocol used to access "Directory Servers". The Directory is a special kind of database that holds information in a tree structure.

The concept is similar to your hard disk directory structure, except that in this context, the root directory is "The world" and the first level subdirectories are "countries". Lower levels of the directory structure contain entries for companies, organisations or places, while yet lower still we find directory entries for people, and perhaps equipment or documents.

To refer to a file in a subdirectory on your hard disk, you might use something like:

   /usr/local/myapp/docs

The forwards slash marks each division in the reference, and the sequence is read from left to right.

The equivalent to the fully qualified file reference in LDAP is the "distinguished name", referred to simply as "dn". An example dn might be:

   cn=John Smith,ou=Accounts,o=My Company,c=US

The comma marks each division in the reference, and the sequence is read from right to left. You would read this dn as:

   country = US
   organization = My Company
   organizationalUnit = Accounts
   commonName = John Smith

In the same way as there are no hard rules about how you organise the directory structure of a hard disk, a directory server manager can set up any structure that is meaningful for the purpose. However, there are some conventions that are used. The message is that you can not write code to access a directory server unless you know something about its structure, any more than you can use a database without some knowledge of what is available.

Lots of information about LDAP can be found at

  • » Mozilla

  • » OpenLDAP Project

  • Internet Engineering Taskforce RFCs » 4510 through » 4519.

The Netscape SDK contains a helpful » Programmer's Guide in HTML format.


Requirements

You will need to get and compile LDAP client libraries from either » OpenLDAP or » Bind9.net in order to compile PHP with LDAP support. For PHP 5.6 or newer you will need OpenLDAP 2.4 or newer.


Installation

LDAP support in PHP is not enabled by default. You will need to use the --with-ldap[=DIR] configuration option when compiling PHP to enable LDAP support. DIR is the LDAP base install directory. To enable SASL support, be sure --with-ldap-sasl[=DIR] is used, and that sasl.h exists on the system.

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 and ssleay32.dll, or, as of OpenSSL 1.1 libcrypto-*.dll and libssl-*.dll

In order to use Oracle LDAP libraries, proper Oracle environment has to be set.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

LDAP configuration options
Name | Default | Changeable | Changelog
ldap.max_links | "-1" | PHP_INI_SYSTEM |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

ldap.max_links integer

The maximum number of LDAP connections per process.


Resource Types

Most LDAP functions operate on or return resources (e.g. ldap_connect() returns a positive LDAP link identifier required by most LDAP 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.

LDAP_DEREF_NEVER (integer)
Alias dereferencing rule - Never.
LDAP_DEREF_SEARCHING (integer)
Alias dereferencing rule - Searching.
LDAP_DEREF_FINDING (integer)
Alias dereferencing rule - Finding.
LDAP_DEREF_ALWAYS (integer)
Alias dereferencing rule - Always.
LDAP_OPT_DEREF (integer)
Specifies alternative rules for following aliases at the server.
LDAP_OPT_SIZELIMIT (integer)

Specifies the maximum number of entries that can be returned on a search operation.

Note: The actual size limit for operations is also bounded by the server's configured maximum number of return entries. The lesser of these two settings is the actual size limit.

LDAP_OPT_TIMELIMIT (integer)
Specifies the number of seconds to wait for search results.

Note: The actual time limit for operations is also bounded by the server's configured maximum time. The lesser of these two settings is the actual time limit.

LDAP_OPT_NETWORK_TIMEOUT (integer)
Option for ldap_set_option() to allow setting network timeout. (Available as of PHP 5.3.0)
LDAP_OPT_PROTOCOL_VERSION (integer)
Specifies the LDAP protocol to be used (V2 or V3).
LDAP_OPT_ERROR_NUMBER (integer)
Latest session error number.
LDAP_OPT_REFERRALS (integer)
Specifies whether to automatically follow referrals returned by the LDAP server.
LDAP_OPT_RESTART (integer)
Determines whether or not the connection should be implicitly restarted.
LDAP_OPT_HOST_NAME (integer)
Sets/gets a space-separated of hosts when trying to connect.
LDAP_OPT_ERROR_STRING (integer)
Alias of LDAP_OPT_DIAGNOSTIC_MESSAGE.
LDAP_OPT_DIAGNOSTIC_MESSAGE (integer)
Gets the latest session error message.
LDAP_OPT_MATCHED_DN (integer)
Sets/gets the matched DN associated with the connection.
LDAP_OPT_SERVER_CONTROLS (integer)
Specifies a default list of server controls to be sent with each request.
LDAP_OPT_CLIENT_CONTROLS (integer)
Specifies a default list of client controls to be processed with each request.
LDAP_OPT_DEBUG_LEVEL (integer)
Specifies a bitwise level for debug traces.
LDAP_OPT_X_KEEPALIVE_IDLE (integer)
Specifies the number of seconds a connection needs to remain idle before TCP starts sending keepalive probes.
LDAP_OPT_X_KEEPALIVE_PROBES (integer)
Specifies the maximum number of keepalive probes TCP should send before dropping the connection.
LDAP_OPT_X_KEEPALIVE_INTERVAL (integer)
Specifies the interval in seconds between individual keepalive probes.
LDAP_OPT_X_TLS_CACERTDIR (string)
Specifies the path of the directory containing CA certificates.
LDAP_OPT_X_TLS_CACERTFILE (string)
Specifies the full-path of the CA certificate file.
LDAP_OPT_X_TLS_CERTFILE (string)
Specifies the full-path of the certificate file.
LDAP_OPT_X_TLS_CIPHER_SUITE (string)
Specifies the allowed cipher suite.
LDAP_OPT_X_TLS_CRLCHECK (integer)
Specifies the CRL evaluation strategy. This must be one of: LDAP_OPT_X_TLS_CRL_NONE,LDAP_OPT_X_TLS_CRL_PEER, LDAP_OPT_X_TLS_CRL_ALL.

Note: This option is only valid for OpenSSL.

LDAP_OPT_X_TLS_CRLFILE (string)
Specifies the full-path of the CRL file.

Note: This option is only valid for GnuTLS.

LDAP_OPT_X_TLS_DHFILE (string)
Specifies the full-path of the file containing the parameters for Diffie-Hellman ephemeral key exchange.

Note: This option is ignored by GnuTLS and Mozilla NSS.

LDAP_OPT_X_TLS_KEYFILE (string)
Specifies the full-path of the certificate key file.
LDAP_OPT_X_TLS_PROTOCOL_MIN (integer)
Specifies the minimum protocol version. This can be one of: LDAP_OPT_X_TLS_PROTOCOL_SSL2,LDAP_OPT_X_TLS_PROTOCOL_SSL3, LDAP_OPT_X_TLS_PROTOCOL_TLS1_0, LDAP_OPT_X_TLS_PROTOCOL_TLS1_1, LDAP_OPT_X_TLS_PROTOCOL_TLS1_2
LDAP_OPT_X_TLS_RANDOM_FILE (string)
Sets/gets the random file when one of the system default ones are not available.
LDAP_OPT_X_TLS_REQUIRE_CERT (integer)
Specifies the certificate checking checking strategy. This must be one of: LDAP_OPT_X_TLS_NEVER,LDAP_OPT_X_TLS_HARD, LDAP_OPT_X_TLS_DEMAND, LDAP_OPT_X_TLS_ALLOW, LDAP_OPT_X_TLS_TRY. (Available as of PHP 7.0.0)
GSLC_SSL_NO_AUTH (integer)
SSL Authentication Mode - No authentication required. (Only for Oracle LDAP)
GSLC_SSL_ONEWAY_AUTH (integer)
SSL Authentication Mode - Only server authentication required. (Only for Oracle LDAP)
GSLC_SSL_TWOWAY_AUTH (integer)
SSL Authentication Mode - Both server and client authentication required. (Only for Oracle LDAP)
LDAP_EXOP_START_TLS (string)
Extended Operation constant - Start TLS (» RFC 4511).
LDAP_EXOP_MODIFY_PASSWD (string)
Extended Operation constant - Modify password (» RFC 3062).
LDAP_EXOP_REFRESH (string)
Extended Operation Constant - Refresh (» RFC 2589).
LDAP_EXOP_WHO_AM_I (string)
Extended Operation Constant - WHOAMI (» RFC 4532).
LDAP_EXOP_TURN (string)
Extended Operation Constant - Turn (» RFC 4531).
LDAP_CONTROL_MANAGEDSAIT (string)
Control Constant - Manage DSA IT (» RFC 3296). Available as of PHP 7.3.0.
LDAP_CONTROL_PROXY_AUTHZ (string)
Control Constant - Proxied Authorization (» RFC 4370). Available as of PHP 7.3.0.
LDAP_CONTROL_SUBENTRIES (string)
Control Constant - Subentries (» RFC 3672). Available as of PHP 7.3.0.
LDAP_CONTROL_VALUESRETURNFILTER (string)
Control Constant - Filter returned values (» RFC 3876). Available as of PHP 7.3.0.
LDAP_CONTROL_ASSERT (string)
Control Constant - Assertion (» RFC 4528). Available as of PHP 7.3.0.
LDAP_CONTROL_PRE_READ (string)
Control Constant - Pre read (» RFC 4527). Available as of PHP 7.3.0.
LDAP_CONTROL_POST_READ (string)
Control Constant - Post read (» RFC 4527). Available as of PHP 7.3.0.
LDAP_CONTROL_SORTREQUEST (string)
Control Constant - Sort request (» RFC 2891). Available as of PHP 7.3.0.
LDAP_CONTROL_SORTRESPONSE (string)
Control Constant - Sort response (» RFC 2891). Available as of PHP 7.3.0.
LDAP_CONTROL_PAGEDRESULTS (string)
Control Constant - Paged results (» RFC 2696). Available as of PHP 7.3.0.
LDAP_CONTROL_AUTHZID_REQUEST (string)
Control Constant - Authorization Identity Request (» RFC 3829). Available as of PHP 7.3.0.
LDAP_CONTROL_AUTHZID_RESPONSE (string)
Control Constant - Authorization Identity Response (» RFC 3829). Available as of PHP 7.3.0.
LDAP_CONTROL_SYNC (string)
Control Constant - Content Synchronization Operation (» RFC 4533). Available as of PHP 7.3.0.
LDAP_CONTROL_SYNC_STATE (string)
Control Constant - Content Synchronization Operation State (» RFC 4533). Available as of PHP 7.3.0.
LDAP_CONTROL_SYNC_DONE (string)
Control Constant - Content Synchronization Operation Done (» RFC 4533). Available as of PHP 7.3.0.
LDAP_CONTROL_DONTUSECOPY (string)
Control Constant - Don't Use Copy (» RFC 6171). Available as of PHP 7.3.0.
LDAP_CONTROL_PASSWORDPOLICYREQUEST (string)
Control Constant - Password Policy Request. Available as of PHP 7.3.0.
LDAP_CONTROL_PASSWORDPOLICYRESPONSE (string)
Control Constant - Password Policy Response. Available as of PHP 7.3.0.
LDAP_CONTROL_X_INCREMENTAL_VALUES (string)
Control Constant - Active Directory Incremental Values. Available as of PHP 7.3.0.
LDAP_CONTROL_X_DOMAIN_SCOPE (string)
Control Constant - Active Directory Domain Scope. Available as of PHP 7.3.0.
LDAP_CONTROL_X_PERMISSIVE_MODIFY (string)
Control Constant - Active Directory Permissive Modify. Available as of PHP 7.3.0.
LDAP_CONTROL_X_SEARCH_OPTIONS (string)
Control Constant - Active Directory Search Options. Available as of PHP 7.3.0.
LDAP_CONTROL_X_TREE_DELETE (string)
Control Constant - Active Directory Tree Delete. Available as of PHP 7.3.0.
LDAP_CONTROL_X_EXTENDED_DN (string)
Control Constant - Active Directory Extended DN. Available as of PHP 7.3.0.
LDAP_CONTROL_VLVREQUEST (string)
Control Constant - Virtual List View Request. Available as of PHP 7.3.0.
LDAP_CONTROL_VLVRESPONSE (string)
Control Constant - Virtual List View Response. Available as of PHP 7.3.0.


Using the PHP LDAP calls

Before you can use the LDAP calls you will need to know ..

  • The name or address of the directory server you will use

  • The "base dn" of the server (the part of the world directory that is held on this server, which could be "o=My Company,c=US")

  • Whether you need a password to access the server (many servers will provide read access for an "anonymous bind" but require a password for anything else)

The typical sequence of LDAP calls you will make in an application will follow this pattern:

  ldap_connect()    // establish connection to server
     |
  ldap_bind()       // anonymous or authenticated "login"
     |
  do something like search or update the directory
  and display the results
     |
  ldap_close()      // "logout"


LDAP controls

Controls are special objects which may be sent alongside an LDAP request to alter LDAP server behavior while performing the request. There may also be controls sent by the server alongside the response to provide more information, usually to answer a control object from the request.

Note:

Not all controls are supported by all LDAP servers. To know which controls are supported by a server, you need to query the root DSE by reading an empty dn with the filter (objectClass=*).

Example #1 Testing support for paged result control

<?php

// $ds is a valid link identifier for a directory server

$result = ldap_read($ds, '', '(objectClass=*)', ['supportedControl']);
if (!in_array(LDAP_CONTROL_PAGEDRESULTS, ldap_get_entries($ds, $result)[0]['supportedcontrol'])) {
  die("This server does not support paged result control");
}

?>

As of PHP 7.3, you can send controls with your request in all request functions using the serverctrls parameter. When a ext version of a function exists, you should use it if you want to get access to the full response object and be able to parse response controls from it using ldap_parse_result().

serverctrls must be an array containing an array for each control to send, containing the following keys:

oid (string)
The OID of the control. You should use constants starting with LDAP_CONTROL_ for this. See LDAP Constants.
iscritical (boolean)
If a control is noted as critical, the request will fail if the control is not supported by the server, or if it fails to be applied. Note that some controls should always be marked as critical as noted in the RFC introducing them. Defaults to FALSE.
value (mixed)
If applicable, the value of the control. Read below for more information.

Most control values are sent to the server BER-encoded. You may either BER-encode the value yourself, or you can instead pass an array with the correct keys so that the encoding is done for you. Supported controls to be passed as an array are:

  • LDAP_CONTROL_PAGEDRESULTS Expected keys are [size] and [cookie]

  • LDAP_CONTROL_ASSERT Expected key is filter

  • LDAP_CONTROL_VALUESRETURNFILTER Expected key is filter

  • LDAP_CONTROL_PRE_READ Expected key is attrs

  • LDAP_CONTROL_POST_READ Expected key is attrs

  • LDAP_CONTROL_SORTREQUEST Expects an array of arrays with keys attr, [oid], [reverse].

  • LDAP_CONTROL_VLVREQUEST Expected keys are before, after, attrvalue|(offset, count), [context]

The following controls do not need any value:

  • LDAP_CONTROL_PASSWORDPOLICYREQUEST

  • LDAP_CONTROL_MANAGEDSAIT

  • LDAP_CONTROL_DONTUSECOPY

The control LDAP_CONTROL_PROXY_AUTHZ is a special case as its value is not expected to be BER-encoded, so you can directly use a string for its value.

When controls are parsed by ldap_parse_result(), values are turned into an array if supported. This is supported for:

  • LDAP_CONTROL_PASSWORDPOLICYRESPONSE Keys are expire, grace, [error]

  • LDAP_CONTROL_PAGEDRESULTS Keys are size, cookie

  • LDAP_CONTROL_PRE_READ Keys are dn and LDAP attributes names

  • LDAP_CONTROL_POST_READ Keys are dn and LDAP attributes names

  • LDAP_CONTROL_SORTRESPONSE Keys are errcode, [attribute]

  • LDAP_CONTROL_VLVRESPONSE Keys are target, count, errcode, context


  • « LDAP controls
  • Basic usage »
  • PHP Manual
  • LDAP
  • Examples

Examples

Table of Contents

  • Basic usage
  • LDAP Controls


Basic usage

Retrieve information for all entries where the surname starts with "S" from a directory server, displaying an extract with name and email address.

Example #1 LDAP search example

<?php
// basic sequence with LDAP is connect, bind, search, interpret search
// result, close connection

echo "<h3>LDAP query test</h3>";
echo "Connecting ...";
$ds=ldap_connect("localhost");  // must be a valid LDAP server!
echo "connect result is " . $ds . "<br />";

if ($ds) {
    echo "Binding ...";
    $r=ldap_bind($ds);     // this is an "anonymous" bind, typically
                           // read-only access
    echo "Bind result is " . $r . "<br />";

    echo "Searching for (sn=S*) ...";
    // Search surname entry
    $sr=ldap_search($ds, "o=My Company, c=US", "sn=S*");
    echo "Search result is " . $sr . "<br />";

    echo "Number of entries returned is " . ldap_count_entries($ds, $sr) . "<br />";

    echo "Getting entries ...<p>";
    $info = ldap_get_entries($ds, $sr);
    echo "Data for " . $info["count"] . " items returned:<p>";

    for ($i=0; $i<$info["count"]; $i++) {
        echo "dn is: " . $info[$i]["dn"] . "<br />";
        echo "first cn entry is: " . $info[$i]["cn"][0] . "<br />";
        echo "first email entry is: " . $info[$i]["mail"][0] . "<br /><hr />";
    }

    echo "Closing connection";
    ldap_close($ds);

} else {
    echo "<h4>Unable to connect to LDAP server</h4>";
}
?>


LDAP Controls

Here are some examples of using LDAP Controls with PHP >= 7.3.0.

Example #1 Bind with ppolicy information

<?php

$user   = 'cn=admin,dc=example,dc=com';
$passwd = 'adminpassword';

$ds = ldap_connect('ldap://localhost');

if ($ds) {
    $r = ldap_bind_ext($ds, $user, $passwd, [['oid' => LDAP_CONTROL_PASSWORDPOLICYREQUEST]]);

    if (ldap_parse_result($ds, $r, $errcode, $matcheddn, $errmsg, $referrals, $ctrls)) {
        if ($errcode != 0) {
            die("Error: $errmsg ($errcode)");
        }
        if (isset($ctrls[LDAP_CONTROL_PASSWORDPOLICYRESPONSE])) {
            $value = $ctrls[LDAP_CONTROL_PASSWORDPOLICYRESPONSE]['value'];
            echo "Expires in: ".$value['expire']." seconds\n";
            echo "Number of auth left: ".$value['grace']."\n";
            if (isset($value['error'])) {
                echo "Ppolicy error code: ".$value['error'];
            }
        }
    }
} else {
    die("Unable to connect to LDAP server");
}
?>

Example #2 Modify description only if it's not empty

<?php
// $link is an LDAP connection

$result = ldap_mod_replace_ext(
    $link,
    'o=test,dc=example,dc=com',
    ['description' => 'New description'],
    [
        [
            'oid'         => LDAP_CONTROL_ASSERT,
            'iscritical'  => TRUE,
            'value'       => ['filter' => '(!(description=*))']
        ]
    ]
);

// Then use ldap_parse_result
?>

Example #3 Read some values before deletion

<?php
// $link is an LDAP connection

$result = ldap_delete_ext(
    $link,
    'o=test,dc=example,dc=com',
    [
        [
            'oid'         => LDAP_CONTROL_PRE_READ,
            'iscritical'  => TRUE,
            'value'       => ['attrs' => ['o', 'description']]
        ]
    ]
);

// Then use ldap_parse_result
?>

Example #4 Delete a reference

<?php
// $link is an LDAP connection

// Without the control it would delete the referenced node
// Make sure to set the control as critical to avoid that
$result = ldap_delete_ext(
    $link,
    'cn=reference,dc=example,dc=com',
    [['oid' => LDAP_CONTROL_MANAGEDSAIT, 'iscritical' => TRUE]]
);

// Then use ldap_parse_result
?>

Example #5 Use pagination for a search

<?php
// $link is an LDAP connection

$cookie = '';

do {
    $result = ldap_search(
        $link, 'dc=example,dc=base', '(cn=*)', ['cn'], 0, 0, 0, LDAP_DEREF_NEVER,
        [['oid' => LDAP_CONTROL_PAGEDRESULTS, 'value' => ['size' => 2, 'cookie' => $cookie]]]
    );
    ldap_parse_result($link, $result, $errcode , $matcheddn , $errmsg , $referrals, $controls);
    // To keep the example short errors are not tested
    $entries = ldap_get_entries($link, $result);
    foreach ($entries as $entry) {
        echo "cn: ".$entry['cn'][0]."\n";
    }
    if (isset($controls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'])) {
        // You need to pass the cookie from the last call to the next one
        $cookie = $controls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'];
    } else {
        $cookie = '';
    }
    // Empty cookie means last page
} while (!empty($cookie));
?>


LDAP Functions

Table of Contents

  • ldap_8859_to_t61 — Translate 8859 characters to t61 characters
  • ldap_add_ext — Add entries to LDAP directory
  • ldap_add — Add entries to LDAP directory
  • ldap_bind_ext — Bind to LDAP directory
  • ldap_bind — Bind to LDAP directory
  • ldap_close — Alias of ldap_unbind
  • ldap_compare — Compare value of attribute found in entry specified with DN
  • ldap_connect — Connect to an LDAP server
  • ldap_control_paged_result_response — Retrieve the LDAP pagination cookie
  • ldap_control_paged_result — Send LDAP pagination control
  • ldap_count_entries — Count the number of entries in a search
  • ldap_delete_ext — Delete an entry from a directory
  • ldap_delete — Delete an entry from a directory
  • ldap_dn2ufn — Convert DN to User Friendly Naming format
  • ldap_err2str — Convert LDAP error number into string error message
  • ldap_errno — Return the LDAP error number of the last LDAP command
  • ldap_error — Return the LDAP error message of the last LDAP command
  • ldap_escape — Escape a string for use in an LDAP filter or DN
  • ldap_exop_passwd — PASSWD extended operation helper
  • ldap_exop_refresh — Refresh extended operation helper
  • ldap_exop_whoami — WHOAMI extended operation helper
  • ldap_exop — Performs an extended operation
  • ldap_explode_dn — Splits DN into its component parts
  • ldap_first_attribute — Return first attribute
  • ldap_first_entry — Return first result id
  • ldap_first_reference — Return first reference
  • ldap_free_result — Free result memory
  • ldap_get_attributes — Get attributes from a search result entry
  • ldap_get_dn — Get the DN of a result entry
  • ldap_get_entries — Get all result entries
  • ldap_get_option — Get the current value for given option
  • ldap_get_values_len — Get all binary values from a result entry
  • ldap_get_values — Get all values from a result entry
  • ldap_list — Single-level search
  • ldap_mod_add_ext — Add attribute values to current attributes
  • ldap_mod_add — Add attribute values to current attributes
  • ldap_mod_del_ext — Delete attribute values from current attributes
  • ldap_mod_del — Delete attribute values from current attributes
  • ldap_mod_replace_ext — Replace attribute values with new ones
  • ldap_mod_replace — Replace attribute values with new ones
  • ldap_modify_batch — Batch and execute modifications on an LDAP entry
  • ldap_modify — Alias of ldap_mod_replace
  • ldap_next_attribute — Get the next attribute in result
  • ldap_next_entry — Get next result entry
  • ldap_next_reference — Get next reference
  • ldap_parse_exop — Parse result object from an LDAP extended operation
  • ldap_parse_reference — Extract information from reference entry
  • ldap_parse_result — Extract information from result
  • ldap_read — Read an entry
  • ldap_rename_ext — Modify the name of an entry
  • ldap_rename — Modify the name of an entry
  • ldap_sasl_bind — Bind to LDAP directory using SASL
  • ldap_search — Search LDAP tree
  • ldap_set_option — Set the value of the given option
  • ldap_set_rebind_proc — Set a callback function to do re-binds on referral chasing
  • ldap_sort — Sort LDAP result entries on the client side
  • ldap_start_tls — Start TLS
  • ldap_t61_to_8859 — Translate t61 characters to 8859 characters
  • ldap_unbind — Unbind from LDAP directory


Translate 8859 characters to t61 characters

  • « LDAP Functions
  • ldap_add_ext »
  • PHP Manual
  • LDAP Functions
  • Translate 8859 characters to t61 characters

ldap_8859_to_t61

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

ldap_8859_to_t61 — Translate 8859 characters to t61 characters

Description

ldap_8859_to_t61 ( string $value ) : string

Translate ISO-8859 characters to t61 characters.

This function is useful if you have to talk to a legacy LDAPv2 server.

Parameters

value

The text to be translated.

Return Values

Return the t61 translation of value.

See Also

  • ldap_t61_to_8859() - Translate t61 characters to 8859 characters


Add entries to LDAP directory

  • « ldap_8859_to_t61
  • ldap_add »
  • PHP Manual
  • LDAP Functions
  • Add entries to LDAP directory

ldap_add_ext

(PHP 7 >= 7.3.0)

ldap_add_ext — Add entries to LDAP directory

Description

ldap_add_ext ( resource $link_identifier , string $dn , array $entry [, array $serverctrls = array() ] ) : resource

Does the same thing as ldap_add() but returns the LDAP result resource to be parsed with ldap_parse_result().

Parameters

See ldap_add()

Return Values

Returns an LDAP result identifier or FALSE on error.

Notes

Note: This function is binary-safe.

See Also

  • ldap_add() - Add entries to LDAP directory
  • ldap_parse_result() - Extract information from result


Add entries to LDAP directory

  • « ldap_add_ext
  • ldap_bind_ext »
  • PHP Manual
  • LDAP Functions
  • Add entries to LDAP directory

ldap_add

(PHP 4, PHP 5, PHP 7)

ldap_add — Add entries to LDAP directory

Description

ldap_add ( resource $link_identifier , string $dn , array $entry [, array $serverctrls = array() ] ) : bool

Add entries in the LDAP directory.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

dn

The distinguished name of an LDAP entity.

entry

An array that specifies the information about the entry. The values in the entries are indexed by individual attributes. In case of multiple values for an attribute, they are indexed using integers starting with 0.

<?php
$entry["attribute1"] = "value";
$entry["attribute2"][0] = "value1";
$entry["attribute2"][1] = "value2";
?>

serverctrls

Array of LDAP Controls to send with the request.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.3 | Support for serverctrls added

Examples

Example #1 Complete example with authenticated bind

<?php
$ds = ldap_connect("localhost");  // assuming the LDAP server is on this host

if ($ds) {
    // bind with appropriate dn to give update access
    $r = ldap_bind($ds, "cn=root, o=My Company, c=US", "secret");

    // prepare data
    $info["cn"] = "John Jones";
    $info["sn"] = "Jones";
    $info["objectclass"] = "person";

    // add data to directory
    $r = ldap_add($ds, "cn=John Jones, o=My Company, c=US", $info);

    ldap_close($ds);
} else {
    echo "Unable to connect to LDAP server";
}
?>

Notes

Note: This function is binary-safe.

See Also

  • ldap_add_ext() - Add entries to LDAP directory
  • ldap_delete() - Delete an entry from a directory


Bind to LDAP directory

  • « ldap_add
  • ldap_bind »
  • PHP Manual
  • LDAP Functions
  • Bind to LDAP directory

ldap_bind_ext

(PHP 7 >= 7.3.0)

ldap_bind_ext — Bind to LDAP directory

Description

ldap_bind_ext ( resource $link_identifier [, string $bind_rdn = NULL [, string $bind_password = NULL [, array $serverctrls = array() ]]] ) : resource

Does the same thing as ldap_bind() but returns the LDAP result resource to be parsed with ldap_parse_result().

Parameters

See ldap_bind()

Return Values

Returns an LDAP result identifier or FALSE on error.

See Also

  • ldap_bind() - Bind to LDAP directory
  • ldap_parse_result() - Extract information from result


Bind to LDAP directory

  • « ldap_bind_ext
  • ldap_close »
  • PHP Manual
  • LDAP Functions
  • Bind to LDAP directory

ldap_bind

(PHP 4, PHP 5, PHP 7)

ldap_bind — Bind to LDAP directory

Description

ldap_bind ( resource $link_identifier [, string $bind_rdn = NULL [, string $bind_password = NULL ]] ) : bool

Binds to the LDAP directory with specified RDN and password.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

bind_rdn

bind_password

If bind_password is not specified or is empty, an anonymous bind is attempted. The bind_rdn can also be left empty for an anonymous bind. This is defined in https://tools.ietf.org/html/rfc2251#section-4.2.2

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Using LDAP Bind

<?php

// using ldap bind
$ldaprdn  = 'uname';     // ldap rdn or dn
$ldappass = 'password';  // associated password

// connect to ldap server
$ldapconn = ldap_connect("ldap://ldap.example.com")
    or die("Could not connect to LDAP server.");

if ($ldapconn) {

    // binding to ldap server
    $ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);

    // verify binding
    if ($ldapbind) {
        echo "LDAP bind successful...";
    } else {
        echo "LDAP bind failed...";
    }

}

?>

Example #2 Using LDAP Bind Anonymously

<?php

//using ldap bind anonymously

// connect to ldap server
$ldapconn = ldap_connect("ldap://ldap.example.com")
    or die("Could not connect to LDAP server.");

if ($ldapconn) {

    // binding anonymously
    $ldapbind = ldap_bind($ldapconn);

    if ($ldapbind) {
        echo "LDAP bind anonymous successful...";
    } else {
        echo "LDAP bind anonymous failed...";
    }

}

?>

See Also

  • ldap_bind_ext() - Bind to LDAP directory
  • ldap_unbind() - Unbind from LDAP directory


Alias of ldap_unbind

  • « ldap_bind
  • ldap_compare »
  • PHP Manual
  • LDAP Functions
  • Alias of ldap_unbind

ldap_close

(PHP 4, PHP 5, PHP 7)

ldap_close — Alias of ldap_unbind()

Description

This function is an alias of: ldap_unbind().


Compare value of attribute found in entry specified with DN

  • « ldap_close
  • ldap_connect »
  • PHP Manual
  • LDAP Functions
  • Compare value of attribute found in entry specified with DN

ldap_compare

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

ldap_compare — Compare value of attribute found in entry specified with DN

Description

ldap_compare ( resource $link_identifier , string $dn , string $attribute , string $value [, array $serverctrls = array() ] ) : mixed

Compare value of attribute with value of same attribute in an LDAP directory entry.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

dn

The distinguished name of an LDAP entity.

attribute

The attribute name.

value

The compared value.

serverctrls

Array of LDAP Controls to send with the request.

Return Values

Returns TRUE if value matches otherwise returns FALSE. Returns -1 on error.

Changelog

Version | Description
7.3 | Support for serverctrls added

Examples

The following example demonstrates how to check whether or not given password matches the one defined in DN specified entry.

Example #1 Complete example of password check

<?php

$ds=ldap_connect("localhost");  // assuming the LDAP server is on this host

if ($ds) {

    // bind
    if (ldap_bind($ds)) {

        // prepare data
        $dn = "cn=Matti Meikku, ou=My Unit, o=My Company, c=FI";
        $value = "secretpassword";
        $attr = "password";

        // compare value
        $r=ldap_compare($ds, $dn, $attr, $value);

        if ($r === -1) {
            echo "Error: " . ldap_error($ds);
        } elseif ($r === true) {
            echo "Password correct.";
        } elseif ($r === false) {
            echo "Wrong guess! Password incorrect.";
        }

    } else {
        echo "Unable to bind to LDAP server.";
    }

    ldap_close($ds);

} else {
    echo "Unable to connect to LDAP server.";
}
?>

Notes

Warning

ldap_compare() can NOT be used to compare BINARY values!


Connect to an LDAP server

  • « ldap_compare
  • ldap_control_paged_result_response »
  • PHP Manual
  • LDAP Functions
  • Connect to an LDAP server

ldap_connect

(PHP 4, PHP 5, PHP 7)

ldap_connect — Connect to an LDAP server

Description

ldap_connect ([ string $ldap_uri = NULL ] ) : resource
Warning

The following signature is still supported for backwards compatibility, but is considered deprecated and should not be used anymore!

ldap_connect ([ string $host = NULL [, int $port = 389 ]] ) : resource

Creates an LDAP link identifier and checks whether the given host and port are plausible.

Note: This function does not open a connection. It checks whether the given parameters are plausible and can be used to open a connection as soon as one is needed.

Parameters

ldap_uri

A full LDAP URI of the form ldap://hostname:port or ldaps://hostname:port for SSL encryption.

You can also provide multiple LDAP-URIs separated by a space as one string

Note that hostname:port is not a supported LDAP URI as the schema is missing.

host

The hostname to connect to.

port

The port to connect to.

Return Values

Returns a positive LDAP link identifier when the provided LDAP URI seems plausible. It's a syntactic check of the provided parameter but the server(s) will not be contacted! If the syntactic check fails it returns FALSE. ldap_connect() will otherwise return a resource as it does not actually connect but just initializes the connecting parameters. The actual connect happens with the next calls to ldap_* funcs, usually with ldap_bind().

If no argument is specified then the link identifier of the already opened link will be returned.

Examples

Example #1 Example of connecting to LDAP server.

<?php

// LDAP variables
$ldapuri = "ldap://ldap.example.com:389";  // your ldap-uri

// Connecting to LDAP
$ldapconn = ldap_connect($ldapuri)
          or die("That LDAP-URI was not parseable");

?>

Example #2 Example of connecting securely to LDAP server.

<?php

// make sure your host is the correct one
// that you issued your secure certificate to
$ldaphost = "ldaps://ldap.example.com/";

// Connecting to LDAP
$ldapconn = ldap_connect($ldaphost)
          or die("That LDAP-URI was not parseable");

?>

See Also

  • ldap_bind() - Bind to LDAP directory


Retrieve the LDAP pagination cookie

  • « ldap_connect
  • ldap_control_paged_result »
  • PHP Manual
  • LDAP Functions
  • Retrieve the LDAP pagination cookie

ldap_control_paged_result_response

(PHP 5 >= 5.4.0, PHP 7)

ldap_control_paged_result_response — Retrieve the LDAP pagination cookie

Warning

This function has been DEPRECATED as of PHP 7.4.0. Relying on this function is highly discouraged.

Description

ldap_control_paged_result_response ( resource $link , resource $result [, string &$cookie [, int &$estimated ]] ) : bool

Retrieve the pagination information send by the server.

Parameters

link

An LDAP link identifier, returned by ldap_connect().

result

cookie

An opaque structure sent by the server.

estimated

The estimated number of entries to retrieve.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.4.0 | This function has been deprecated.

See Also

  • ldap_control_paged_result() - Send LDAP pagination control
  • » RFC2696 : LDAP Control Extension for Simple Paged Results Manipulation


Send LDAP pagination control

  • « ldap_control_paged_result_response
  • ldap_count_entries »
  • PHP Manual
  • LDAP Functions
  • Send LDAP pagination control

ldap_control_paged_result

(PHP 5 >= 5.4.0, PHP 7)

ldap_control_paged_result — Send LDAP pagination control

Warning

This function has been DEPRECATED as of PHP 7.4.0. Relying on this function is highly discouraged.

Description

ldap_control_paged_result ( resource $link , int $pagesize [, bool $iscritical = FALSE [, string $cookie = "" ]] ) : bool

Enable LDAP pagination by sending the pagination control (page size, cookie...).

Parameters

link

An LDAP link identifier, returned by ldap_connect().

pagesize

The number of entries by page.

iscritical

Indicates whether the pagination is critical or not. If true and if the server doesn't support pagination, the search will return no result.

cookie

An opaque structure sent by the server (ldap_control_paged_result_response()).

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.4.0 | This function has been deprecated.

Examples

The example below show the retrieval of the first page of a search paginated with one entry by page.

Example #1 LDAP pagination

<?php
     // $ds is a valid link identifier (see ldap_connect)
     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);

     $dn        = 'ou=example,dc=org';
     $filter    = '(|(sn=Doe*)(givenname=John*))';
     $justthese = array('ou', 'sn', 'givenname', 'mail');

     // enable pagination with a page size of 1.
     ldap_control_paged_result($ds, 1);

     $sr = ldap_search($ds, $dn, $filter, $justthese);

     $info = ldap_get_entries($ds, $sr);

     echo $info['count'] . ' entries returned' . PHP_EOL;

The example below show the retrieval of all the result paginated with 100 entries by page.

Example #2 LDAP pagination

<?php
     // $ds is a valid link identifier (see ldap_connect)
     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);

     $dn        = 'ou=example,dc=org';
     $filter    = '(|(sn=Doe*)(givenname=John*))';
     $justthese = array('ou', 'sn', 'givenname', 'mail');

     // enable pagination with a page size of 100.
     $pageSize = 100;

     $cookie = '';
     do {
         ldap_control_paged_result($ds, $pageSize, true, $cookie);

         $result  = ldap_search($ds, $dn, $filter, $justthese);
         $entries = ldap_get_entries($ds, $result);

         foreach ($entries as $e) {
             echo $e['dn'] . PHP_EOL;
         }

         ldap_control_paged_result_response($ds, $result, $cookie);

     } while($cookie !== null && $cookie != '');

Notes

Note:

Pagination control is a LDAPv3 protocol feature.

See Also

  • ldap_control_paged_result_response() - Retrieve the LDAP pagination cookie
  • » RFC2696 : LDAP Control Extension for Simple Paged Results Manipulation


Count the number of entries in a search

  • « ldap_control_paged_result
  • ldap_delete_ext »
  • PHP Manual
  • LDAP Functions
  • Count the number of entries in a search

ldap_count_entries

(PHP 4, PHP 5, PHP 7)

ldap_count_entries — Count the number of entries in a search

Description

ldap_count_entries ( resource $link_identifier , resource $result_identifier ) : int

Returns the number of entries stored in the result of previous search operations.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_identifier

The internal LDAP result.

Return Values

Returns number of entries in the result or FALSE on error.

Examples

Example #1 ldap-count-entries() example

Retrieve number of entries in the result.

// $ds is a valid link identifier (see ldap_connect)

     $dn        = 'ou=example,dc=org';
     $filter    = '(|(sn=Doe*)(givenname=John*))';
     $justthese = array('ou', 'sn', 'givenname', 'mail');

     $sr = ldap_search($ds, $dn, $filter, $justthese);

     var_dump(ldap_count_entries($ds, $sr));

The above example will output something similar to:

     int(1)


Delete an entry from a directory

  • « ldap_count_entries
  • ldap_delete »
  • PHP Manual
  • LDAP Functions
  • Delete an entry from a directory

ldap_delete_ext

(PHP 7 >= 7.3.0)

ldap_delete_ext — Delete an entry from a directory

Description

ldap_delete_ext ( resource $link_identifier , string $dn [, array $serverctrls = array() ] ) : resource

Does the same thing as ldap_delete() but returns the LDAP result resource to be parsed with ldap_parse_result().

Parameters

See ldap_delete()

Return Values

Returns an LDAP result identifier or FALSE on error.

See Also

  • ldap_delete() - Delete an entry from a directory
  • ldap_parse_result() - Extract information from result


Delete an entry from a directory

  • « ldap_delete_ext
  • ldap_dn2ufn »
  • PHP Manual
  • LDAP Functions
  • Delete an entry from a directory

ldap_delete

(PHP 4, PHP 5, PHP 7)

ldap_delete — Delete an entry from a directory

Description

ldap_delete ( resource $link_identifier , string $dn [, array $serverctrls = array() ] ) : bool

Deletes a particular entry in LDAP directory.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

dn

The distinguished name of an LDAP entity.

serverctrls

Array of LDAP Controls to send with the request.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.3 | Support for serverctrls added

See Also

  • ldap_delete_ext() - Delete an entry from a directory
  • ldap_add() - Add entries to LDAP directory


Convert DN to User Friendly Naming format

  • « ldap_delete
  • ldap_err2str »
  • PHP Manual
  • LDAP Functions
  • Convert DN to User Friendly Naming format

ldap_dn2ufn

(PHP 4, PHP 5, PHP 7)

ldap_dn2ufn — Convert DN to User Friendly Naming format

Description

ldap_dn2ufn ( string $dn ) : string

Turns the specified dn, into a more user-friendly form, stripping off type names.

Parameters

dn

The distinguished name of an LDAP entity.

Return Values

Returns the user friendly name.


Convert LDAP error number into string error message

  • « ldap_dn2ufn
  • ldap_errno »
  • PHP Manual
  • LDAP Functions
  • Convert LDAP error number into string error message

ldap_err2str

(PHP 4, PHP 5, PHP 7)

ldap_err2str — Convert LDAP error number into string error message

Description

ldap_err2str ( int $errno ) : string

Returns the string error message explaining the error number errno. While LDAP errno numbers are standardized, different libraries return different or even localized textual error messages. Never check for a specific error message text, but always use an error number to check.

Parameters

errno

The error number.

Return Values

Returns the error message, as a string.

Examples

Example #1 Enumerating all LDAP error messages

<?php
  for ($i=0; $i<100; $i++) {
    printf("Error $i: %s<br />\n", ldap_err2str($i));
  }
?>

See Also

  • ldap_errno() - Return the LDAP error number of the last LDAP command
  • ldap_error() - Return the LDAP error message of the last LDAP command


Return the LDAP error number of the last LDAP command

  • « ldap_err2str
  • ldap_error »
  • PHP Manual
  • LDAP Functions
  • Return the LDAP error number of the last LDAP command

ldap_errno

(PHP 4, PHP 5, PHP 7)

ldap_errno — Return the LDAP error number of the last LDAP command

Description

ldap_errno ( resource $link_identifier ) : int

Returns the standardized error number returned by the last LDAP command. This number can be converted into a textual error message using ldap_err2str().

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

Return Values

Return the LDAP error number of the last LDAP command for this link.

Examples

Unless you lower your warning level in your php.ini sufficiently or prefix your LDAP commands with @ (at) characters to suppress warning output, the errors generated will also show up in your HTML output.

Example #1 Generating and catching an error

<?php
// This example contains an error, which we will catch.
$ld = ldap_connect("localhost");
$bind = ldap_bind($ld);
// syntax error in filter expression (errno 87),
// must be "objectclass=*" to work.
$res =  @ldap_search($ld, "o=Myorg, c=DE", "objectclass");
if (!$res) {
    echo "LDAP-Errno: " . ldap_errno($ld) . "<br />\n";
    echo "LDAP-Error: " . ldap_error($ld) . "<br />\n";
    die("Argh!<br />\n");
}
$info = ldap_get_entries($ld, $res);
echo $info["count"] . " matching entries.<br />\n";
?>

See Also

  • ldap_err2str() - Convert LDAP error number into string error message
  • ldap_error() - Return the LDAP error message of the last LDAP command


Return the LDAP error message of the last LDAP command

  • « ldap_errno
  • ldap_escape »
  • PHP Manual
  • LDAP Functions
  • Return the LDAP error message of the last LDAP command

ldap_error

(PHP 4, PHP 5, PHP 7)

ldap_error — Return the LDAP error message of the last LDAP command

Description

ldap_error ( resource $link_identifier ) : string

Returns the string error message explaining the error generated by the last LDAP command for the given link_identifier. While LDAP errno numbers are standardized, different libraries return different or even localized textual error messages. Never check for a specific error message text, but always use an error number to check.

Unless you lower your warning level in your php.ini sufficiently or prefix your LDAP commands with @ (at) characters to suppress warning output, the errors generated will also show up in your HTML output.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

Return Values

Returns string error message.

See Also

  • ldap_err2str() - Convert LDAP error number into string error message
  • ldap_errno() - Return the LDAP error number of the last LDAP command


Escape a string for use in an LDAP filter or DN

  • « ldap_error
  • ldap_exop_passwd »
  • PHP Manual
  • LDAP Functions
  • Escape a string for use in an LDAP filter or DN

ldap_escape

(PHP 5 >= 5.6.0, PHP 7)

ldap_escape — Escape a string for use in an LDAP filter or DN

Description

ldap_escape ( string $value [, string $ignore = "" [, int $flags = 0 ]] ) : string

Escapes value for use in the context implied by flags.

Parameters

value

The value to escape.

ignore

Characters to ignore when escaping.

flags

The context the escaped string will be used in: LDAP_ESCAPE_FILTER for filters to be used with ldap_search(), or LDAP_ESCAPE_DN for DNs. If neither flag is passed, all chars are escaped.

Return Values

Returns the escaped string.

Examples

When building an LDAP filter, you should use ldap_escape with LDAP_ESCAPE_FILTER flag.

Example #1 Searching for an email address

<?php
// $ds is a valid link identifier for a directory server

// $mail is an email address provided by the user in a form

$base   = "o=My Company, c=US";
$filter = "(mail=".ldap_escape($mail, "", LDAP_ESCAPE_FILTER).")";

$sr = ldap_search($ds, $base, $filter, array("sn", "givenname", "mail"));

$info = ldap_get_entries($ds, $sr);

echo $info["count"]." entries returned\n";
?>


PASSWD extended operation helper

  • « ldap_escape
  • ldap_exop_refresh »
  • PHP Manual
  • LDAP Functions
  • PASSWD extended operation helper

ldap_exop_passwd

(PHP 7 >= 7.2.0)

ldap_exop_passwd — PASSWD extended operation helper

Description

ldap_exop_passwd ( resource $link [, string $user = "" [, string $oldpw = "" [, string $newpw = "" [, array &$serverctrls ]]]] ) : mixed

Performs a PASSWD extended operation.

Parameters

link

An LDAP link identifier, returned by ldap_connect().

user

dn of the user to change the password of.

oldpw

The old password of this user. May be ommited depending of server configuration.

newpw

The new password for this user. May be omitted or empty to have a generated password.

serverctrls

If provided, a password policy request control is send with the request and this is filled with an array of LDAP Controls returned with the request.

Return Values

Returns the generated password if newpw is empty or omitted. Otherwise returns TRUE on success and FALSE on failure.

Changelog

Version | Description
7.3 | Support for serverctrls added

Examples

Example #1 PASSWD extended operation

<?php
$ds = ldap_connect("localhost");  // assuming the LDAP server is on this host

if ($ds) {
    // bind with appropriate dn to give update access
    $bind = ldap_bind($ds, "cn=root, o=My Company, c=US", "secret");
    if (!$bind) {
      echo "Unable to bind to LDAP server";
      exit;
    }

    // use PASSWD EXOP to change the user password for a generated one
    $genpw = ldap_exop_passwd($ds, "cn=root, o=My Company, c=US", "secret");
    if ($genpw) {
      // use the generated password to bind
      $bind = ldap_bind($ds, "cn=root, o=My Company, c=US", $genpw);
    }

    // set the password back to "secret"
    ldap_exop_passwd($ds, "cn=root, o=My Company, c=US", $genpw, "secret");

    ldap_close($ds);
} else {
    echo "Unable to connect to LDAP server";
}
?>

See Also

  • ldap_exop() - Performs an extended operation
  • ldap_parse_exop() - Parse result object from an LDAP extended operation


Refresh extended operation helper

  • « ldap_exop_passwd
  • ldap_exop_whoami »
  • PHP Manual
  • LDAP Functions
  • Refresh extended operation helper

ldap_exop_refresh

(PHP 7 >= 7.3.0)

ldap_exop_refresh — Refresh extended operation helper

Description

ldap_exop_refresh ( resource $link , string $dn , int $ttl ) : int

Performs a Refresh extended operation and returns the data.

Parameters

link

An LDAP link identifier, returned by ldap_connect().

dn

dn of the entry to refresh.

ttl

Time in seconds (between 1 and 31557600) that the client requests that the entry exists in the directory before being automatically removed.

Return Values

From RFC: The responseTtl field is the time in seconds which the server chooses to have as the time-to-live field for that entry. It must not be any smaller than that which the client requested, and it may be larger. However, to allow servers to maintain a relatively accurate directory, and to prevent clients from abusing the dynamic extensions, servers are permitted to shorten a client-requested time-to-live value, down to a minimum of 86400 seconds (one day). FALSE will be returned on error.

See Also

  • ldap_exop() - Performs an extended operation


WHOAMI extended operation helper

  • « ldap_exop_refresh
  • ldap_exop »
  • PHP Manual
  • LDAP Functions
  • WHOAMI extended operation helper

ldap_exop_whoami

(PHP 7 >= 7.2.0)

ldap_exop_whoami — WHOAMI extended operation helper

Description

ldap_exop_whoami ( resource $link ) : string

Performs a WHOAMI extended operation and returns the data.

Parameters

link

An LDAP link identifier, returned by ldap_connect().

Return Values

The data returned by the server, or FALSE on error.

See Also

  • ldap_exop() - Performs an extended operation


Performs an extended operation

  • « ldap_exop_whoami
  • ldap_explode_dn »
  • PHP Manual
  • LDAP Functions
  • Performs an extended operation

ldap_exop

(PHP 7 >= 7.2.0)

ldap_exop — Performs an extended operation

Description

ldap_exop ( resource $link , string $reqoid [, string $reqdata = NULL [, array $serverctrls = NULL [, string &$retdata [, string &$retoid ]]]] ) : mixed

Performs an extended operation on the specified link with reqoid the OID of the operation and reqdata the data.

Parameters

link

An LDAP link identifier, returned by ldap_connect().

reqoid

The extended operation request OID. You may use one of LDAP_EXOP_START_TLS, LDAP_EXOP_MODIFY_PASSWD, LDAP_EXOP_REFRESH, LDAP_EXOP_WHO_AM_I, LDAP_EXOP_TURN, or a string with the OID of the operation you want to send.

reqdata

The extended operation request data. May be NULL for some operations like LDAP_EXOP_WHO_AM_I, may also need to be BER encoded.

serverctrls

Array of LDAP Controls to send with the request.

retdata

Will be filled with the extended operation response data if provided. If not provided you may use ldap_parse_exop on the result object later to get this data.

retoid

Will be filled with the response OID if provided, usually equal to the request OID.

Return Values

When used with retdata, returns TRUE on success or FALSE on error. When used without retdata, returns a result identifier or FALSE on error.

Changelog

Version | Description
7.3 | Support for serverctrls added

Examples

Example #1 Whoami extended operation

<?php
$ds = ldap_connect("localhost");  // assuming the LDAP server is on this host

if ($ds) {
    // bind with appropriate dn to give update access
    $bind = ldap_bind($ds, "cn=root, o=My Company, c=US", "secret");
    if (!$bind) {
      echo "Unable to bind to LDAP server";
      exit;
    }

    // Call WHOAMI EXOP
    $r = ldap_exop($ds, LDAP_EXOP_WHO_AM_I);

    // Parse the result object
    ldap_parse_exop($ds, $r, $retdata);
    // Output: string(31) "dn:cn=root, o=My Company, c=US"
    var_dump($retdata);

    // Same thing using $retdata parameter
    $success = ldap_exop($ds, LDAP_EXOP_WHO_AM_I, NULL, NULL, $retdata, $retoid);
    if ($success) {
      var_dump($retdata);
    }

    ldap_close($ds);
} else {
    echo "Unable to connect to LDAP server";
}
?>

See Also

  • ldap_parse_result() - Extract information from result
  • ldap_parse_exop() - Parse result object from an LDAP extended operation
  • ldap_exop_whoami() - WHOAMI extended operation helper
  • ldap_exop_refresh() - Refresh extended operation helper
  • ldap_exop_passwd() - PASSWD extended operation helper


Splits DN into its component parts

  • « ldap_exop
  • ldap_first_attribute »
  • PHP Manual
  • LDAP Functions
  • Splits DN into its component parts

ldap_explode_dn

(PHP 4, PHP 5, PHP 7)

ldap_explode_dn — Splits DN into its component parts

Description

ldap_explode_dn ( string $dn , int $with_attrib ) : array

Splits the DN returned by ldap_get_dn() and breaks it up into its component parts. Each part is known as Relative Distinguished Name, or RDN.

Parameters

dn

The distinguished name of an LDAP entity.

with_attrib

Used to request if the RDNs are returned with only values or their attributes as well. To get RDNs with the attributes (i.e. in attribute=value format) set with_attrib to 0 and to get only values set it to 1.

Return Values

Returns an array of all DN components, or FALSE on failure. The first element in the array has count key and represents the number of returned values, next elements are numerically indexed DN components.


Return first attribute

  • « ldap_explode_dn
  • ldap_first_entry »
  • PHP Manual
  • LDAP Functions
  • Return first attribute

ldap_first_attribute

(PHP 4, PHP 5, PHP 7)

ldap_first_attribute — Return first attribute

Description

ldap_first_attribute ( resource $link_identifier , resource $result_entry_identifier ) : string

Gets the first attribute in the given entry. Remaining attributes are retrieved by calling ldap_next_attribute() successively.

Similar to reading entries, attributes are also read one by one from a particular entry.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_entry_identifier

ber_identifier

ber_identifier is the identifier to internal memory location pointer. It is passed by reference. The same ber_identifier is passed to ldap_next_attribute() , which modifies that pointer.

Note:

This parameter is no longer used as this is now handled automatically by PHP. For backwards compatibility PHP will not throw an error if this parameter is passed.

Return Values

Returns the first attribute in the entry on success and FALSE on error.

Changelog

Version | Description
5.2.4 | The ber_identifier was removed. This is now handled automatically by PHP.

See Also

  • ldap_next_attribute() - Get the next attribute in result
  • ldap_get_attributes() - Get attributes from a search result entry


Return first result id

  • « ldap_first_attribute
  • ldap_first_reference »
  • PHP Manual
  • LDAP Functions
  • Return first result id

ldap_first_entry

(PHP 4, PHP 5, PHP 7)

ldap_first_entry — Return first result id

Description

ldap_first_entry ( resource $link_identifier , resource $result_identifier ) : resource

Returns the entry identifier for first entry in the result. This entry identifier is then supplied to ldap_next_entry() routine to get successive entries from the result.

Entries in the LDAP result are read sequentially using the ldap_first_entry() and ldap_next_entry() functions.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_identifier

Return Values

Returns the result entry identifier for the first entry on success and FALSE on error.

See Also

  • ldap_get_entries() - Get all result entries


Return first reference

  • « ldap_first_entry
  • ldap_free_result »
  • PHP Manual
  • LDAP Functions
  • Return first reference

ldap_first_reference

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

ldap_first_reference — Return first reference

Description

ldap_first_reference ( resource $link , resource $result ) : resource
Warning

This function is currently not documented; only its argument list is available.


Free result memory

  • « ldap_first_reference
  • ldap_get_attributes »
  • PHP Manual
  • LDAP Functions
  • Free result memory

ldap_free_result

(PHP 4, PHP 5, PHP 7)

ldap_free_result — Free result memory

Description

ldap_free_result ( resource $result_identifier ) : bool

Frees up the memory allocated internally to store the result. All result memory will be automatically freed when the script terminates.

Typically all the memory allocated for the LDAP result gets freed at the end of the script. In case the script is making successive searches which return large result sets, ldap_free_result() could be called to keep the runtime memory usage by the script low.

Parameters

result_identifier

Return Values

Returns TRUE on success or FALSE on failure.


Get attributes from a search result entry

  • « ldap_free_result
  • ldap_get_dn »
  • PHP Manual
  • LDAP Functions
  • Get attributes from a search result entry

ldap_get_attributes

(PHP 4, PHP 5, PHP 7)

ldap_get_attributes — Get attributes from a search result entry

Description

ldap_get_attributes ( resource $link_identifier , resource $result_entry_identifier ) : array

Reads attributes and values from an entry in the search result.

Having located a specific entry in the directory, you can find out what information is held for that entry by using this call. You would use this call for an application which "browses" directory entries and/or where you do not know the structure of the directory entries. In many applications you will be searching for a specific attribute such as an email address or a surname, and won't care what other data is held.

return_value["count"] = number of attributes in the entry
return_value[0] = first attribute
return_value[n] = nth attribute

return_value["attribute"]["count"] = number of values for attribute
return_value["attribute"][0] = first value of the attribute
return_value["attribute"][i] = (i+1)th value of the attribute

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_entry_identifier

Return Values

Returns a complete entry information in a multi-dimensional array on success and FALSE on error.

Examples

Example #1 Show the list of attributes held for a particular directory entry

<?php
// $ds is the link identifier for the directory

// $sr is a valid search result from a prior call to
// one of the ldap directory search calls

$entry = ldap_first_entry($ds, $sr);

$attrs = ldap_get_attributes($ds, $entry);

echo $attrs["count"] . " attributes held for this entry:<p>";

for ($i=0; $i < $attrs["count"]; $i++) {
    echo $attrs[$i] . "<br />";
}
?>

See Also

  • ldap_first_attribute() - Return first attribute
  • ldap_next_attribute() - Get the next attribute in result


Get the DN of a result entry

  • « ldap_get_attributes
  • ldap_get_entries »
  • PHP Manual
  • LDAP Functions
  • Get the DN of a result entry

ldap_get_dn

(PHP 4, PHP 5, PHP 7)

ldap_get_dn — Get the DN of a result entry

Description

ldap_get_dn ( resource $link_identifier , resource $result_entry_identifier ) : string

Finds out the DN of an entry in the result.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_entry_identifier

Return Values

Returns the DN of the result entry and FALSE on error.


Get all result entries

  • « ldap_get_dn
  • ldap_get_option »
  • PHP Manual
  • LDAP Functions
  • Get all result entries

ldap_get_entries

(PHP 4, PHP 5, PHP 7)

ldap_get_entries — Get all result entries

Description

ldap_get_entries ( resource $link_identifier , resource $result_identifier ) : array

Reads multiple entries from the given result, and then reading the attributes and multiple values.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_identifier

Return Values

Returns a complete result information in a multi-dimensional array on success and FALSE on error.

The structure of the array is as follows. The attribute index is converted to lowercase. (Attributes are case-insensitive for directory servers, but not when used as array indices.)

return_value["count"] = number of entries in the result
return_value[0] : refers to the details of first entry

return_value[i]["dn"] =  DN of the ith entry in the result

return_value[i]["count"] = number of attributes in ith entry
return_value[i][j] = NAME of the jth attribute in the ith entry in the result

return_value[i]["attribute"]["count"] = number of values for
                                        attribute in ith entry
return_value[i]["attribute"][j] = jth value of attribute in ith entry

See Also

  • ldap_first_entry() - Return first result id
  • ldap_next_entry() - Get next result entry


Get the current value for given option

  • « ldap_get_entries
  • ldap_get_values_len »
  • PHP Manual
  • LDAP Functions
  • Get the current value for given option

ldap_get_option

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

ldap_get_option — Get the current value for given option

Description

ldap_get_option ( resource $link_identifier , int $option , mixed &$retval ) : bool

Sets retval to the value of the specified option.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

option

The parameter option can be one of:

Option | Type | since
LDAP_OPT_DEREF | integer
LDAP_OPT_SIZELIMIT | integer
LDAP_OPT_TIMELIMIT | integer
LDAP_OPT_NETWORK_TIMEOUT | integer
LDAP_OPT_PROTOCOL_VERSION | integer
LDAP_OPT_ERROR_NUMBER | integer
LDAP_OPT_DIAGNOSTIC_MESSAGE | integer
LDAP_OPT_REFERRALS | bool
LDAP_OPT_RESTART | bool
LDAP_OPT_HOST_NAME | string
LDAP_OPT_ERROR_STRING | string
LDAP_OPT_MATCHED_DN | string
LDAP_OPT_SERVER_CONTROLS | array
LDAP_OPT_CLIENT_CONTROLS | array
LDAP_OPT_X_KEEPALIVE_IDLE | int | 7.1
LDAP_OPT_X_KEEPALIVE_PROBES | int | 7.1
LDAP_OPT_X_KEEPALIVE_INTERVAL | int | 7.1
LDAP_OPT_X_TLS_CACERTDIR | string | 7.1
LDAP_OPT_X_TLS_CACERTFILE | string | 7.1
LDAP_OPT_X_TLS_CERTFILE | string | 7.1
LDAP_OPT_X_TLS_CIPHER_SUITE | string | 7.1
LDAP_OPT_X_TLS_CRLCHECK | integer | 7.1
LDAP_OPT_X_TLS_CRL_NONE | integer | 7.1
LDAP_OPT_X_TLS_CRL_PEER | integer | 7.1
LDAP_OPT_X_TLS_CRL_ALL | integer | 7.1
LDAP_OPT_X_TLS_CRLFILE | string | 7.1
LDAP_OPT_X_TLS_DHFILE | string | 7.1
LDAP_OPT_X_TLS_KEYILE | string | 7.1
LDAP_OPT_X_TLS_PACKAGE | string | 7.1
LDAP_OPT_X_TLS_PROTOCOL_MIN | integer | 7.1
LDAP_OPT_X_TLS_RANDOM_FILE | string | 7.1
LDAP_OPT_X_TLS_REQUIRE_CERT | integer

retval

This will be set to the option value.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Check protocol version

<?php
// $ds is a valid link identifier for a directory server
if (ldap_get_option($ds, LDAP_OPT_PROTOCOL_VERSION, $version)) {
    echo "Using protocol version $version\n";
} else {
    echo "Unable to determine protocol version\n";
}
?>

Notes

Note:

This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x.

See Also

  • ldap_set_option() - Set the value of the given option


Get all binary values from a result entry

  • « ldap_get_option
  • ldap_get_values »
  • PHP Manual
  • LDAP Functions
  • Get all binary values from a result entry

ldap_get_values_len

(PHP 4, PHP 5, PHP 7)

ldap_get_values_len — Get all binary values from a result entry

Description

ldap_get_values_len ( resource $link_identifier , resource $result_entry_identifier , string $attribute ) : array

Reads all the values of the attribute in the entry in the result.

This function is used exactly like ldap_get_values() except that it handles binary data and not string data.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_entry_identifier

attribute

Return Values

Returns an array of values for the attribute on success and FALSE on error. Individual values are accessed by integer index in the array. The first index is 0. The number of values can be found by indexing "count" in the resultant array.

See Also

  • ldap_get_values() - Get all values from a result entry


Get all values from a result entry

  • « ldap_get_values_len
  • ldap_list »
  • PHP Manual
  • LDAP Functions
  • Get all values from a result entry

ldap_get_values

(PHP 4, PHP 5, PHP 7)

ldap_get_values — Get all values from a result entry

Description

ldap_get_values ( resource $link_identifier , resource $result_entry_identifier , string $attribute ) : array

Reads all the values of the attribute in the entry in the result.

This call needs a result_entry_identifier, so needs to be preceded by one of the ldap search calls and one of the calls to get an individual entry.

You application will either be hard coded to look for certain attributes (such as "surname" or "mail") or you will have to use the ldap_get_attributes() call to work out what attributes exist for a given entry.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_entry_identifier

attribute

Return Values

Returns an array of values for the attribute on success and FALSE on error. The number of values can be found by indexing "count" in the resultant array. Individual values are accessed by integer index in the array. The first index is 0.

LDAP allows more than one entry for an attribute, so it can, for example, store a number of email addresses for one person's directory entry all labeled with the attribute "mail"

    return_value["count"] = number of values for attribute
    return_value[0] = first value of attribute
    return_value[i] = ith value of attribute

Examples

Example #1 List all values of the "mail" attribute for a directory entry

<?php
// $ds is a valid link identifier for a directory server

// $sr is a valid search result from a prior call to
//     one of the ldap directory search calls

// $entry is a valid entry identifier from a prior call to
//        one of the calls that returns a directory entry

$values = ldap_get_values($ds, $entry, "mail");

echo $values["count"] . " email addresses for this entry.<br />";

for ($i=0; $i < $values["count"]; $i++) {
    echo $values[$i] . "<br />";
}
?>

See Also

  • ldap_get_values_len() - Get all binary values from a result entry


Single-level search

  • « ldap_get_values
  • ldap_mod_add_ext »
  • PHP Manual
  • LDAP Functions
  • Single-level search

ldap_list

(PHP 4, PHP 5, PHP 7)

ldap_list — Single-level search

Description

ldap_list ( resource $link_identifier , string $base_dn , string $filter [, array $attributes = array("*") [, int $attrsonly = 0 [, int $sizelimit = -1 [, int $timelimit = -1 [, int $deref = LDAP_DEREF_NEVER [, array $serverctrls = array() ]]]]]] ) : resource

Performs the search for a specified filter on the directory with the scope LDAP_SCOPE_ONELEVEL.

LDAP_SCOPE_ONELEVEL means that the search should only return information that is at the level immediately below the base_dn given in the call. (Equivalent to typing "ls" and getting a list of files and folders in the current working directory.)

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

base_dn

The base DN for the directory.

filter

attributes

An array of the required attributes, e.g. array("mail", "sn", "cn"). Note that the "dn" is always returned irrespective of which attributes types are requested.

Using this parameter is much more efficient than the default action (which is to return all attributes and their associated values). The use of this parameter should therefore be considered good practice.

attrsonly

Should be set to 1 if only attribute types are wanted. If set to 0 both attributes types and attribute values are fetched which is the default behaviour.

sizelimit

Enables you to limit the count of entries fetched. Setting this to 0 means no limit.

Note:

This parameter can NOT override server-side preset sizelimit. You can set it lower though.

Some directory server hosts will be configured to return no more than a preset number of entries. If this occurs, the server will indicate that it has only returned a partial results set. This also occurs if you use this parameter to limit the count of fetched entries.

timelimit

Sets the number of seconds how long is spend on the search. Setting this to 0 means no limit.

Note:

This parameter can NOT override server-side preset timelimit. You can set it lower though.

deref

Specifies how aliases should be handled during the search. It can be one of the following:

  • LDAP_DEREF_NEVER - (default) aliases are never dereferenced.
  • LDAP_DEREF_SEARCHING - aliases should be dereferenced during the search but not when locating the base object of the search.
  • LDAP_DEREF_FINDING - aliases should be dereferenced when locating the base object but not during the search.
  • LDAP_DEREF_ALWAYS - aliases should be dereferenced always.

serverctrls

Array of LDAP Controls to send with the request.

Return Values

Returns a search result identifier or FALSE on error.

Changelog

Version | Description
7.3 | Support for serverctrls added

Examples

Example #1 Produce a list of all organizational units of an organization

<?php
// $ds is a valid link identifier for a directory server

$basedn = "o=My Company, c=US";
$justthese = array("ou");

$sr = ldap_list($ds, $basedn, "ou=*", $justthese);

$info = ldap_get_entries($ds, $sr);

for ($i=0; $i < $info["count"]; $i++) {
    echo $info[$i]["ou"][0];
}
?>

See Also

  • ldap_search() - Search LDAP tree


Add attribute values to current attributes

  • « ldap_list
  • ldap_mod_add »
  • PHP Manual
  • LDAP Functions
  • Add attribute values to current attributes

ldap_mod_add_ext

(PHP 7 >= 7.3.0)

ldap_mod_add_ext — Add attribute values to current attributes

Description

ldap_mod_add_ext ( resource $link_identifier , string $dn , array $entry [, array $serverctrls = array() ] ) : resource

Does the same thing as ldap_mod_add() but returns the LDAP result resource to be parsed with ldap_parse_result().

Parameters

See ldap_mod_add()

Return Values

Returns an LDAP result identifier or FALSE on error.

See Also

  • ldap_mod_add() - Add attribute values to current attributes
  • ldap_parse_result() - Extract information from result


Add attribute values to current attributes

  • « ldap_mod_add_ext
  • ldap_mod_del_ext »
  • PHP Manual
  • LDAP Functions
  • Add attribute values to current attributes

ldap_mod_add

(PHP 4, PHP 5, PHP 7)

ldap_mod_add — Add attribute values to current attributes

Description

ldap_mod_add ( resource $link_identifier , string $dn , array $entry [, array $serverctrls = array() ] ) : bool

Adds one or more attribute values to the specified dn. To add a whole new object see ldap_add() function.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

dn

The distinguished name of an LDAP entity.

entry

An associative array listing the attirbute values to add. If an attribute was not existing yet it will be added. If an attribute is existing you can only add values to it if it supports multiple values.

serverctrls

Array of LDAP Controls to send with the request.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.3 | Support for serverctrls added

Notes

Note: This function is binary-safe.

See Also

  • ldap_mod_add_ext() - Add attribute values to current attributes
  • ldap_mod_del() - Delete attribute values from current attributes
  • ldap_mod_replace() - Replace attribute values with new ones
  • ldap_modify_batch() - Batch and execute modifications on an LDAP entry


Delete attribute values from current attributes

  • « ldap_mod_add
  • ldap_mod_del »
  • PHP Manual
  • LDAP Functions
  • Delete attribute values from current attributes

ldap_mod_del_ext

(PHP 7 >= 7.3.0)

ldap_mod_del_ext — Delete attribute values from current attributes

Description

ldap_mod_del_ext ( resource $link_identifier , string $dn , array $entry [, array $serverctrls = array() ] ) : resource

Does the same thing as ldap_mod_del() but returns the LDAP result resource to be parsed with ldap_parse_result().

Parameters

See ldap_mod_del()

Return Values

Returns an LDAP result identifier or FALSE on error.

See Also

  • ldap_mod_del() - Delete attribute values from current attributes
  • ldap_parse_result() - Extract information from result


Delete attribute values from current attributes

  • « ldap_mod_del_ext
  • ldap_mod_replace_ext »
  • PHP Manual
  • LDAP Functions
  • Delete attribute values from current attributes

ldap_mod_del

(PHP 4, PHP 5, PHP 7)

ldap_mod_del — Delete attribute values from current attributes

Description

ldap_mod_del ( resource $link_identifier , string $dn , array $entry [, array $serverctrls = array() ] ) : bool

Removes one or more attribute values from the specified dn. Object deletions are done by the ldap_delete() function.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

dn

The distinguished name of an LDAP entity.

entry

serverctrls

Array of LDAP Controls to send with the request.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.3 | Support for serverctrls added

See Also

  • ldap_mod_del_ext() - Delete attribute values from current attributes
  • ldap_mod_add() - Add attribute values to current attributes
  • ldap_mod_replace() - Replace attribute values with new ones
  • ldap_modify_batch() - Batch and execute modifications on an LDAP entry


Replace attribute values with new ones

  • « ldap_mod_del
  • ldap_mod_replace »
  • PHP Manual
  • LDAP Functions
  • Replace attribute values with new ones

ldap_mod_replace_ext

(PHP 7 >= 7.3.0)

ldap_mod_replace_ext — Replace attribute values with new ones

Description

ldap_mod_replace_ext ( resource $link_identifier , string $dn , array $entry [, array $serverctrls = array() ] ) : resource

Does the same thing as ldap_mod_replace() but returns the LDAP result resource to be parsed with ldap_parse_result().

Parameters

See ldap_mod_replace()

Return Values

Returns an LDAP result identifier or FALSE on error.

See Also

  • ldap_mod_replace() - Replace attribute values with new ones
  • ldap_parse_result() - Extract information from result


Replace attribute values with new ones

  • « ldap_mod_replace_ext
  • ldap_modify_batch »
  • PHP Manual
  • LDAP Functions
  • Replace attribute values with new ones

ldap_mod_replace

(PHP 4, PHP 5, PHP 7)

ldap_mod_replace — Replace attribute values with new ones

Description

ldap_mod_replace ( resource $link_identifier , string $dn , array $entry [, array $serverctrls = array() ] ) : bool

Replaces one or more attributes from the specified dn. It may also add or remove attributes.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

dn

The distinguished name of an LDAP entity.

entry

An associative array listing the attributes to replace. Sending an empty array as value will remove the attribute, while sending an attribute not existing yet on this entry will add it.

serverctrls

Array of LDAP Controls to send with the request.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.3 | Support for serverctrls added

Notes

Note: This function is binary-safe.

See Also

  • ldap_mod_replace_ext() - Replace attribute values with new ones
  • ldap_mod_del() - Delete attribute values from current attributes
  • ldap_mod_add() - Add attribute values to current attributes
  • ldap_modify_batch() - Batch and execute modifications on an LDAP entry


Batch and execute modifications on an LDAP entry

  • « ldap_mod_replace
  • ldap_modify »
  • PHP Manual
  • LDAP Functions
  • Batch and execute modifications on an LDAP entry

ldap_modify_batch

(PHP 5.4 >= 5.4.26, PHP 5.5 >= 5.5.10, PHP 5.6 >= 5.6.0, PHP 7)

ldap_modify_batch — Batch and execute modifications on an LDAP entry

Description

ldap_modify_batch ( resource $link_identifier , string $dn , array $entry [, array $serverctrls = array() ] ) : bool

Modifies an existing entry in the LDAP directory. Allows detailed specification of the modifications to perform.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

dn

The distinguished name of an LDAP entity.

entry

An array that specifies the modifications to make. Each entry in this array is an associative array with two or three keys: attrib maps to the name of the attribute to modify, modtype maps to the type of modification to perform, and (depending on the type of modification) values maps to an array of attribute values relevant to the modification.

Possible values for modtype include:

LDAP_MODIFY_BATCH_ADD

Each value specified through values is added (as an additional value) to the attribute named by attrib.

LDAP_MODIFY_BATCH_REMOVE

Each value specified through values is removed from the attribute named by attrib. Any value of the attribute not contained in the values array will remain untouched.

LDAP_MODIFY_BATCH_REMOVE_ALL

All values are removed from the attribute named by attrib. A values entry must not be provided.

LDAP_MODIFY_BATCH_REPLACE

All current values of the attribute named by attrib are replaced with the values specified through values.

Note that any value for attrib must be a string, any value for values must be an array of strings, and any value for modtype must be one of the LDAP_MODIFY_BATCH_* constants listed above.

serverctrls

Array of LDAP Controls to send with the request.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.3 | Support for serverctrls added

Examples

Example #1 Add a telephone number to a contact

<?php
$dn = "cn=John Smith,ou=Wizards,dc=example,dc=com";
$modifs = [
    [
        "attrib"  => "telephoneNumber",
        "modtype" => LDAP_MODIFY_BATCH_ADD,
        "values"  => ["+1 555 555 1717"],
    ],
];
ldap_modify_batch($connection, $dn, $modifs);
?>

Example #2 Rename a user

<?php
$dn = "cn=John Smith,ou=Wizards,dc=example,dc=com";
$modifs = [
    [
        "attrib"  => "sn",
        "modtype" => LDAP_MODIFY_BATCH_REPLACE,
        "values"  => ["Smith-Jones"],
    ],
    [
        "attrib"  => "givenName",
        "modtype" => LDAP_MODIFY_BATCH_REPLACE,
        "values"  => ["Jack"],
    ],
];
ldap_modify_batch($connection, $dn, $modifs);
ldap_rename($connection, $dn, "cn=Jack Smith-Jones", NULL, TRUE);
?>

Example #3 Add two e-mail addresses to a user

<?php
$dn = "cn=Jack Smith-Jones,ou=Wizards,dc=example,dc=com";
$modifs = [
    [
        "attrib"  => "mail",
        "modtype" => LDAP_MODIFY_BATCH_ADD,
        "values"  => [
            "jack.smith@example.com",
            "jack.smith-jones@example.com",
        ],
    ],
];
ldap_modify_batch($connection, $dn, $modifs);
?>

Example #4 Change a user's password

<?php
$dn = "cn=Jack Smith-Jones,ou=Wizards,dc=example,dc=com";
$modifs = [
    [
        "attrib"  => "userPassword",
        "modtype" => LDAP_MODIFY_BATCH_REMOVE,
        "values"  => ["Tr0ub4dor&3"],
    ],
    [
        "attrib"  => "userPassword",
        "modtype" => LDAP_MODIFY_BATCH_ADD,
        "values"  => ["correct horse battery staple"],
    ],
];
ldap_modify_batch($connection, $dn, $modifs);
?>

Example #5 Change a user's password (Active Directory)

<?php
function adifyPw($pw)
{
    return iconv("UTF-8", "UTF-16LE", '"' . $pw . '"');
}

$dn = "cn=Jack Smith-Jones,ou=Wizards,dc=ad,dc=example,dc=com";
$modifs = [
    [
        "attrib"  => "unicodePwd",
        "modtype" => LDAP_MODIFY_BATCH_REMOVE,
        "values"  => [adifyPw("Tr0ub4dor&3")],
    ],
    [
        "attrib"  => "unicodePwd",
        "modtype" => LDAP_MODIFY_BATCH_ADD,
        "values"  => [adifyPw("correct horse battery staple")],
    ],
];
ldap_modify_batch($connection, $dn, $modifs);


Alias of ldap_mod_replace

  • « ldap_modify_batch
  • ldap_next_attribute »
  • PHP Manual
  • LDAP Functions
  • Alias of ldap_mod_replace

ldap_modify

(PHP 4, PHP 5, PHP 7)

ldap_modify — Alias of ldap_mod_replace()

Description

This function is an alias of: ldap_mod_replace().

See Also

  • ldap_rename() - Modify the name of an entry


Get the next attribute in result

  • « ldap_modify
  • ldap_next_entry »
  • PHP Manual
  • LDAP Functions
  • Get the next attribute in result

ldap_next_attribute

(PHP 4, PHP 5, PHP 7)

ldap_next_attribute — Get the next attribute in result

Description

ldap_next_attribute ( resource $link_identifier , resource $result_entry_identifier ) : string

Retrieves the attributes in an entry. The first call to ldap_next_attribute() is made with the result_entry_identifier returned from ldap_first_attribute().

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_entry_identifier

ber_identifier

The internal state of the pointer is maintained by this parameter.

Note:

This parameter is no longer used as this is now handled automatically by PHP. For backwards compatibility PHP will not throw an error if this parameter is passed.

Return Values

Returns the next attribute in an entry on success and FALSE on error.

Changelog

Version | Description
5.2.4 | The ber_identifier was removed. This is now handled automatically by PHP.

See Also

  • ldap_get_attributes() - Get attributes from a search result entry


Get next result entry

  • « ldap_next_attribute
  • ldap_next_reference »
  • PHP Manual
  • LDAP Functions
  • Get next result entry

ldap_next_entry

(PHP 4, PHP 5, PHP 7)

ldap_next_entry — Get next result entry

Description

ldap_next_entry ( resource $link_identifier , resource $result_entry_identifier ) : resource

Retrieve the entries stored in the result. Successive calls to the ldap_next_entry() return entries one by one till there are no more entries. The first call to ldap_next_entry() is made after the call to ldap_first_entry() with the result_entry_identifier as returned from the ldap_first_entry().

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

result_entry_identifier

Return Values

Returns entry identifier for the next entry in the result whose entries are being read starting with ldap_first_entry(). If there are no more entries in the result then it returns FALSE.

See Also

  • ldap_get_entries() - Get all result entries


Get next reference

  • « ldap_next_entry
  • ldap_parse_exop »
  • PHP Manual
  • LDAP Functions
  • Get next reference

ldap_next_reference

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

ldap_next_reference — Get next reference

Description

ldap_next_reference ( resource $link , resource $entry ) : resource
Warning

This function is currently not documented; only its argument list is available.


Parse result object from an LDAP extended operation

  • « ldap_next_reference
  • ldap_parse_reference »
  • PHP Manual
  • LDAP Functions
  • Parse result object from an LDAP extended operation

ldap_parse_exop

(PHP 7 >= 7.2.0)

ldap_parse_exop — Parse result object from an LDAP extended operation

Description

ldap_parse_exop ( resource $link , resource $result [, string &$retdata [, string &$retoid ]] ) : bool

Parse LDAP extended operation data from result object result

Parameters

link

An LDAP link identifier, returned by ldap_connect().

result

An LDAP result resource, returned by ldap_exop().

retdata

Will be filled by the response data.

retoid

Will be filled by the response OID.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ldap_exop() - Performs an extended operation


Extract information from reference entry

  • « ldap_parse_exop
  • ldap_parse_result »
  • PHP Manual
  • LDAP Functions
  • Extract information from reference entry

ldap_parse_reference

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

ldap_parse_reference — Extract information from reference entry

Description

ldap_parse_reference ( resource $link , resource $entry , array &$referrals ) : bool
Warning

This function is currently not documented; only its argument list is available.


Extract information from result

  • « ldap_parse_reference
  • ldap_read »
  • PHP Manual
  • LDAP Functions
  • Extract information from result

ldap_parse_result

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

ldap_parse_result — Extract information from result

Description

ldap_parse_result ( resource $link , resource $result , int &$errcode [, string &$matcheddn [, string &$errmsg [, array &$referrals [, array &$serverctrls ]]]] ) : bool

Parses an LDAP search result.

Parameters

link

An LDAP link identifier, returned by ldap_connect().

result_identifier

An LDAP result resource, returned by ldap_list() or ldap_search().

errcode

A reference to a variable that will be set to the LDAP error code in the result, or 0 if no error occurred.

matcheddn

A reference to a variable that will be set to a matched DN if one was recognised within the request, otherwise it will be set to NULL.

errmsg

A reference to a variable that will be set to the LDAP error message in the result, or an empty string if no error occurred.

referrals

A reference to a variable that will be set to an array set to all of the referral strings in the result, or an empty array if no referrals were returned.

serverctrls

An array of LDAP Controls which have been sent with the response.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.3 | Support for serverctrls added

Examples

Example #1 ldap_parse_result() example

<?php
$result = ldap_search($link, "cn=userref,dc=my-domain,dc=com", "(cn=user*)");
$errcode = $dn = $errmsg = $refs =  null;
if (ldap_parse_result($link, $result, $errcode, $dn, $errmsg, $refs)) {
    // do something with $errcode, $dn, $errmsg and $refs
}
?>


Read an entry

  • « ldap_parse_result
  • ldap_rename_ext »
  • PHP Manual
  • LDAP Functions
  • Read an entry

ldap_read

(PHP 4, PHP 5, PHP 7)

ldap_read — Read an entry

Description

ldap_read ( resource $link_identifier , string $base_dn , string $filter [, array $attributes = array("*") [, int $attrsonly = 0 [, int $sizelimit = -1 [, int $timelimit = -1 [, int $deref = LDAP_DEREF_NEVER [, array $serverctrls = array() ]]]]]] ) : resource

Performs the search for a specified filter on the directory with the scope LDAP_SCOPE_BASE. So it is equivalent to reading an entry from the directory.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

base_dn

The base DN for the directory.

filter

An empty filter is not allowed. If you want to retrieve absolutely all information for this entry, use a filter of objectClass=*. If you know which entry types are used on the directory server, you might use an appropriate filter such as objectClass=inetOrgPerson.

attributes

An array of the required attributes, e.g. array("mail", "sn", "cn"). Note that the "dn" is always returned irrespective of which attributes types are requested.

Using this parameter is much more efficient than the default action (which is to return all attributes and their associated values). The use of this parameter should therefore be considered good practice.

attrsonly

Should be set to 1 if only attribute types are wanted. If set to 0 both attributes types and attribute values are fetched which is the default behaviour.

sizelimit

Enables you to limit the count of entries fetched. Setting this to 0 means no limit.

Note:

This parameter can NOT override server-side preset sizelimit. You can set it lower though.

Some directory server hosts will be configured to return no more than a preset number of entries. If this occurs, the server will indicate that it has only returned a partial results set. This also occurs if you use this parameter to limit the count of fetched entries.

timelimit

Sets the number of seconds how long is spend on the search. Setting this to 0 means no limit.

Note:

This parameter can NOT override server-side preset timelimit. You can set it lower though.

deref

Specifies how aliases should be handled during the search. It can be one of the following:

  • LDAP_DEREF_NEVER - (default) aliases are never dereferenced.
  • LDAP_DEREF_SEARCHING - aliases should be dereferenced during the search but not when locating the base object of the search.
  • LDAP_DEREF_FINDING - aliases should be dereferenced when locating the base object but not during the search.
  • LDAP_DEREF_ALWAYS - aliases should be dereferenced always.

serverctrls

Array of LDAP Controls to send with the request.

Return Values

Returns a search result identifier or FALSE on error.

Changelog

Version | Description
4.0.5 | Parallel searches support was added. See ldap_search() for details.
7.3 | Support for serverctrls added


Modify the name of an entry

  • « ldap_read
  • ldap_rename »
  • PHP Manual
  • LDAP Functions
  • Modify the name of an entry

ldap_rename_ext

(PHP 7 >= 7.3.0)

ldap_rename_ext — Modify the name of an entry

Description

ldap_rename_ext ( resource $link_identifier , string $dn , string $newrdn , string $newparent , bool $deleteoldrdn [, array $serverctrls = array() ] ) : resource

Does the same thing as ldap_rename() but returns the LDAP result resource to be parsed with ldap_parse_result().

Parameters

See ldap_rename()

Return Values

Returns an LDAP result identifier or FALSE on error.

See Also

  • ldap_rename() - Modify the name of an entry
  • ldap_parse_result() - Extract information from result


Modify the name of an entry

  • « ldap_rename_ext
  • ldap_sasl_bind »
  • PHP Manual
  • LDAP Functions
  • Modify the name of an entry

ldap_rename

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

ldap_rename — Modify the name of an entry

Description

ldap_rename ( resource $link_identifier , string $dn , string $newrdn , string $newparent , bool $deleteoldrdn [, array $serverctrls = array() ] ) : bool

The entry specified by dn is renamed/moved.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

dn

The distinguished name of an LDAP entity.

newrdn

The new RDN.

newparent

The new parent/superior entry.

deleteoldrdn

If TRUE the old RDN value(s) is removed, else the old RDN value(s) is retained as non-distinguished values of the entry.

serverctrls

Array of LDAP Controls to send with the request.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.3 | Support for serverctrls added

Notes

Note:

This function currently only works with LDAPv3. You may have to use ldap_set_option() prior to binding to use LDAPv3. This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x.

See Also

  • ldap_rename_ext() - Modify the name of an entry
  • ldap_modify() - Alias of ldap_mod_replace


Bind to LDAP directory using SASL

  • « ldap_rename
  • ldap_search »
  • PHP Manual
  • LDAP Functions
  • Bind to LDAP directory using SASL

ldap_sasl_bind

(PHP 5, PHP 7)

ldap_sasl_bind — Bind to LDAP directory using SASL

Description

ldap_sasl_bind ( resource $link [, string $binddn = NULL [, string $password = NULL [, string $sasl_mech = NULL [, string $sasl_realm = NULL [, string $sasl_authc_id = NULL [, string $sasl_authz_id = NULL [, string $props = NULL ]]]]]]] ) : bool
Warning

This function is currently not documented; only its argument list is available.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: Requirement
ldap_sasl_bind() requires SASL support (sasl.h). Be sure --with-ldap-sasl is used when configuring PHP otherwise this function will be undefined.

Changelog

Version | Description
5.3.3 | Support on Windows was added.


Search LDAP tree

  • « ldap_sasl_bind
  • ldap_set_option »
  • PHP Manual
  • LDAP Functions
  • Search LDAP tree

ldap_search

(PHP 4, PHP 5, PHP 7)

ldap_search — Search LDAP tree

Description

ldap_search ( resource $link_identifier , string $base_dn , string $filter [, array $attributes = array("*") [, int $attrsonly = 0 [, int $sizelimit = -1 [, int $timelimit = -1 [, int $deref = LDAP_DEREF_NEVER [, array $serverctrls = array() ]]]]]] ) : resource

Performs the search for a specified filter on the directory with the scope of LDAP_SCOPE_SUBTREE. This is equivalent to searching the entire directory.

From 4.0.5 on it's also possible to do parallel searches. To do this you use an array of link identifiers, rather than a single identifier, as the first argument. If you don't want the same base DN and the same filter for all the searches, you can also use an array of base DNs and/or an array of filters. Those arrays must be of the same size as the link identifier array since the first entries of the arrays are used for one search, the second entries are used for another, and so on. When doing parallel searches an array of search result identifiers is returned, except in case of error, then the entry corresponding to the search will be FALSE. This is very much like the value normally returned, except that a result identifier is always returned when a search was made. There are some rare cases where the normal search returns FALSE while the parallel search returns an identifier.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

base_dn

The base DN for the directory.

filter

The search filter can be simple or advanced, using boolean operators in the format described in the LDAP documentation (see the » Netscape Directory SDK or » RFC4515 for full information on filters).

attributes

An array of the required attributes, e.g. array("mail", "sn", "cn"). Note that the "dn" is always returned irrespective of which attributes types are requested.

Using this parameter is much more efficient than the default action (which is to return all attributes and their associated values). The use of this parameter should therefore be considered good practice.

attrsonly

Should be set to 1 if only attribute types are wanted. If set to 0 both attributes types and attribute values are fetched which is the default behaviour.

sizelimit

Enables you to limit the count of entries fetched. Setting this to 0 means no limit.

Note:

This parameter can NOT override server-side preset sizelimit. You can set it lower though.

Some directory server hosts will be configured to return no more than a preset number of entries. If this occurs, the server will indicate that it has only returned a partial results set. This also occurs if you use this parameter to limit the count of fetched entries.

timelimit

Sets the number of seconds how long is spend on the search. Setting this to 0 means no limit.

Note:

This parameter can NOT override server-side preset timelimit. You can set it lower though.

deref

Specifies how aliases should be handled during the search. It can be one of the following:

  • LDAP_DEREF_NEVER - (default) aliases are never dereferenced.
  • LDAP_DEREF_SEARCHING - aliases should be dereferenced during the search but not when locating the base object of the search.
  • LDAP_DEREF_FINDING - aliases should be dereferenced when locating the base object but not during the search.
  • LDAP_DEREF_ALWAYS - aliases should be dereferenced always.

serverctrls

Array of LDAP Controls to send with the request.

Return Values

Returns a search result identifier or FALSE on error.

Changelog

Version | Description
7.3 | Support for serverctrls added

Examples

The example below retrieves the organizational unit, surname, given name and email address for all people in "My Company" where the surname or given name contains the substring $person. This example uses a boolean filter to tell the server to look for information in more than one attribute.

Example #1 LDAP search

<?php
// $ds is a valid link identifier for a directory server

// $person is all or part of a person's name, eg "Jo"

$dn = "o=My Company, c=US";
$filter="(|(sn=$person*)(givenname=$person*))";
$justthese = array("ou", "sn", "givenname", "mail");

$sr=ldap_search($ds, $dn, $filter, $justthese);

$info = ldap_get_entries($ds, $sr);

echo $info["count"]." entries returned\n";
?>


Set the value of the given option

  • « ldap_search
  • ldap_set_rebind_proc »
  • PHP Manual
  • LDAP Functions
  • Set the value of the given option

ldap_set_option

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

ldap_set_option — Set the value of the given option

Description

ldap_set_option ( resource $link_identifier , int $option , mixed $newval ) : bool

Sets the value of the specified option to be newval.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

option

The parameter option can be one of:

Option | Type | Available since
LDAP_OPT_DEREF | integer
LDAP_OPT_SIZELIMIT | integer
LDAP_OPT_TIMELIMIT | integer
LDAP_OPT_NETWORK_TIMEOUT | integer | PHP 5.3.0
LDAP_OPT_PROTOCOL_VERSION | integer
LDAP_OPT_ERROR_NUMBER | integer
LDAP_OPT_REFERRALS | bool
LDAP_OPT_RESTART | bool
LDAP_OPT_HOST_NAME | string
LDAP_OPT_ERROR_STRING | string
LDAP_OPT_DIAGNOSTIC_MESSAGE | string
LDAP_OPT_MATCHED_DN | string
LDAP_OPT_SERVER_CONTROLS | array
LDAP_OPT_CLIENT_CONTROLS | array
LDAP_OPT_X_KEEPALIVE_IDLE | int | PHP 7.1.0
LDAP_OPT_X_KEEPALIVE_PROBES | int | PHP 7.1.0
LDAP_OPT_X_KEEPALIVE_INTERVAL | int | PHP 7.1.0
LDAP_OPT_X_TLS_CACERTDIR | string | PHP 7.1.0
LDAP_OPT_X_TLS_CACERTFILE | string | PHP 7.1.0
LDAP_OPT_X_TLS_CERTFILE | string | PHP 7.1.0
LDAP_OPT_X_TLS_CIPHER_SUITE | string | PHP 7.1.0
LDAP_OPT_X_TLS_CRLCHECK | integer | PHP 7.1.0
LDAP_OPT_X_TLS_CRLFILE | string | PHP 7.1.0
LDAP_OPT_X_TLS_DHFILE | string | PHP 7.1.0
LDAP_OPT_X_TLS_KEYFILE | string | PHP 7.1.0
LDAP_OPT_X_TLS_PROTOCOL_MIN | integer | PHP 7.1.0
LDAP_OPT_X_TLS_RANDOM_FILE | string | PHP 7.1.0
LDAP_OPT_X_TLS_REQUIRE_CERT | integer | PHP 7.0.5

LDAP_OPT_SERVER_CONTROLS and LDAP_OPT_CLIENT_CONTROLS require a list of controls, this means that the value must be an array of controls. A control consists of an oid identifying the control, an optional value, and an optional flag for criticality. In PHP a control is given by an array containing an element with the key oid and string value, and two optional elements. The optional elements are key value with string value and key iscritical with boolean value. iscritical defaults to FALSE if not supplied. See » draft-ietf-ldapext-ldap-c-api-xx.txt for details. See also the second example below.

newval

The new value for the specified option.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Set protocol version

<?php
// $ds is a valid link identifier for a directory server
if (ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)) {
    echo "Using LDAPv3";
} else {
    echo "Failed to set protocol version to 3";
}
?>

Example #2 Set server controls

<?php
// $ds is a valid link identifier for a directory server
// control with no value
$ctrl1 = array("oid" => "1.2.752.58.10.1", "iscritical" => true);
// iscritical defaults to FALSE
$ctrl2 = array("oid" => "1.2.752.58.1.10", "value" => "magic");
// try to set both controls
if (!ldap_set_option($ds, LDAP_OPT_SERVER_CONTROLS, array($ctrl1, $ctrl2))) {
    echo "Failed to set server controls";
}
?>

Notes

Note:

This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x.

See Also

  • ldap_get_option() - Get the current value for given option


Set a callback function to do re-binds on referral chasing

  • « ldap_set_option
  • ldap_sort »
  • PHP Manual
  • LDAP Functions
  • Set a callback function to do re-binds on referral chasing

ldap_set_rebind_proc

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

ldap_set_rebind_proc — Set a callback function to do re-binds on referral chasing

Description

ldap_set_rebind_proc ( resource $link , callable $callback ) : bool
Warning

This function is currently not documented; only its argument list is available.


Sort LDAP result entries on the client side

  • « ldap_set_rebind_proc
  • ldap_start_tls »
  • PHP Manual
  • LDAP Functions
  • Sort LDAP result entries on the client side

ldap_sort

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

ldap_sort — Sort LDAP result entries on the client side

Description

ldap_sort ( resource $link , resource $result , string $sortfilter ) : bool

Sort the result of a LDAP search, returned by ldap_search().

As this function sorts the returned values on the client side it is possible that you might not get the expected results in case you reach the sizelimit either of the server or defined within ldap_search().

Warning

This feature has been DEPRECATED as of PHP 7.0.0. Relying on this feature is highly discouraged.

Parameters

link

An LDAP link identifier, returned by ldap_connect().

result

An search result identifier, returned by ldap_search().

sortfilter

The attribute to use as a key in the sort.

Examples

Sorting the result of a search.

Example #1 LDAP sort

<?php
     // $ds is a valid link identifier (see ldap_connect)

     $dn        = 'ou=example,dc=org';
     $filter    = '(|(sn=Doe*)(givenname=John*))';
     $justthese = array('ou', 'sn', 'givenname', 'mail');

     $sr = ldap_search($ds, $dn, $filter, $justthese);

     // Sort
     ldap_sort($ds, $sr, 'sn');

     // Retrieving the data
     $info = ldap_get_entries($ds, $sr);


Start TLS

  • « ldap_sort
  • ldap_t61_to_8859 »
  • PHP Manual
  • LDAP Functions
  • Start TLS

ldap_start_tls

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

ldap_start_tls — Start TLS

Description

ldap_start_tls ( resource $link ) : bool
Warning

This function is currently not documented; only its argument list is available.


Translate t61 characters to 8859 characters

  • « ldap_start_tls
  • ldap_unbind »
  • PHP Manual
  • LDAP Functions
  • Translate t61 characters to 8859 characters

ldap_t61_to_8859

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

ldap_t61_to_8859 — Translate t61 characters to 8859 characters

Description

ldap_t61_to_8859 ( string $value ) : string
Warning

This function is currently not documented; only its argument list is available.


Unbind from LDAP directory

  • « ldap_t61_to_8859
  • Memcache »
  • PHP Manual
  • LDAP Functions
  • Unbind from LDAP directory

ldap_unbind

(PHP 4, PHP 5, PHP 7)

ldap_unbind — Unbind from LDAP directory

Description

ldap_unbind ( resource $link_identifier ) : bool

Unbinds from the LDAP directory.

Parameters

link_identifier

An LDAP link identifier, returned by ldap_connect().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ldap_bind() - Bind to LDAP directory


Memcache

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
  • Memcache — The Memcache class
    • Memcache::add — Add an item to the server
    • Memcache::addServer — Add a memcached server to connection pool
    • Memcache::close — Close memcached server connection
    • Memcache::connect — Open memcached server connection
    • Memcache::decrement — Decrement item's value
    • Memcache::delete — Delete item from the server
    • Memcache::flush — Flush all existing items at the server
    • Memcache::get — Retrieve item from the server
    • Memcache::getExtendedStats — Get statistics from all servers in pool
    • Memcache::getServerStatus — Returns server status
    • Memcache::getStats — Get statistics of the server
    • Memcache::getVersion — Return version of the server
    • Memcache::increment — Increment item's value
    • Memcache::pconnect — Open memcached server persistent connection
    • Memcache::replace — Replace value of the existing item
    • Memcache::set — Store data at the server
    • Memcache::setCompressThreshold — Enable automatic compression of large values
    • Memcache::setServerParams — Changes server parameters and status at runtime
  • Memcache Functions
    • memcache_debug — Turn debug output on/off


Introduction

Memcache module provides handy procedural and object oriented interface to memcached, highly effective caching daemon, which was especially designed to decrease database load in dynamic web applications.

The Memcache module also provides a session handler (memcache).

More information about memcached can be found at » http://www.memcached.org/.


Requirements

This module uses functions of » zlib to support on-the-fly data compression. Zlib is required to install this module.


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/memcache.

Note:

It's possible to disable memcache session handler support. The 'pecl install' option prompts for this (default is enabled) however when compiling statically into PHP the --disable-memcache-session configure option may be used.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Memcache Configuration Options
Name | Default | Changeable | Changelog
memcache.allow_failover | "1" | PHP_INI_ALL | Available since memcache 2.0.2.
memcache.max_failover_attempts | "20" | PHP_INI_ALL | Available since memcache 2.1.0.
memcache.chunk_size | "8192" | PHP_INI_ALL | Available since memcache 2.0.2.
memcache.default_port | "11211" | PHP_INI_ALL | Available since memcache 2.0.2.
memcache.hash_strategy | "standard" | PHP_INI_ALL | Available since memcache 2.2.0.
memcache.hash_function | "crc32" | PHP_INI_ALL | Available since memcache 2.2.0.
session.save_handler | "files" | PHP_INI_ALL | Supported since memcache 2.1.2
session.save_path | "" | PHP_INI_ALL | Supported since memcache 2.1.2
memcache.protocol | ascii | >PHP_INI_ALL | Supported since memcache 3.0.0
memcache.redundancy | 1 | >PHP_INI_ALL | Supported since memcache 3.0.0
memcache.session_redundancy | 2 | >PHP_INI_ALL | Supported since memcache 3.0.0
memcache.compress_threshold | 20000 | >PHP_INI_ALL | Supported since memcache 3.0.3
memcache.lock_timeout | 15 | >PHP_INI_ALL | Supported since memcache 3.0.4
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

memcache.allow_failover boolean

Whether to transparently failover to other servers on errors.

memcache.max_failover_attempts integer

Defines how many servers to try when setting and getting data. Used only in conjunction with memcache.allow_failover.

memcache.chunk_size integer

Data will be transferred in chunks of this size, setting the value lower requires more network writes. Try increasing this value to 32768 if noticing otherwise inexplicable slowdowns.

memcache.default_port string

The default TCP port number to use when connecting to the memcached server if no other port is specified.

memcache.hash_strategy string

Controls which strategy to use when mapping keys to servers. Set this value to consistent to enable consistent hashing which allows servers to be added or removed from the pool without causing keys to be remapped. Setting this value to standard results in the old strategy being used.

memcache.hash_function string

Controls which hash function to apply when mapping keys to servers, crc32 uses the standard CRC32 hash while fnv uses FNV-1a.

session.save_handler string

Use memcache as a session handler by setting this value to memcache.

session.save_path string

Defines a comma separated of server urls to use for session storage, for example "tcp://host1:11211, tcp://host2:11211".

Each url may contain parameters which are applied to that server, they are the same as for the Memcache::addServer() method. For example "tcp://host1:11211?persistent=1&weight=1&timeout=1&retry_interval=15"

memcache.protocol string

memcache.redundancy integer

memcache.session_redundancy integer

memcache.compress_threshold integer

memcache.lock_timeout integer


Resource Types

There is only one resource type used in memcache module - it's the link identifier for a cache server connection.


Predefined Constants

Memcache Constants
Name | Description
MEMCACHE_COMPRESSED (integer) | Used to turn on-the-fly data compression on with Memcache::set(), Memcache::add() and Memcache::replace().
MEMCACHE_HAVE_SESSION (integer) | 1 if this Memcache session handler is available, 0 otherwise.
MEMCACHE_USER1 (integer) | Used to turn user-defined application flag on with Memcache::set(), Memcache::add() and Memcache::replace().
MEMCACHE_USER2 (integer) | Used to turn user-defined application flag on with Memcache::set(), Memcache::add() and Memcache::replace().
MEMCACHE_USER3 (integer) | Used to turn user-defined application flag on with Memcache::set(), Memcache::add() and Memcache::replace().
MEMCACHE_USER4 (integer) | Used to turn user-defined application flag on with Memcache::set(), Memcache::add() and Memcache::replace().


  • « Predefined Constants
  • Basic usage »
  • PHP Manual
  • Memcache
  • Examples

Examples

Table of Contents

  • Basic usage


Basic usage

Example #1 memcache extension overview example

In this example, an object is being saved in the cache and then retrieved back. Object and other non-scalar types are serialized before saving, so it's impossible to store resources (i.e. connection identifiers and others) in the cache.

<?php

$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");

$version = $memcache->getVersion();
echo "Server's version: ".$version."<br/>\n";

$tmp_object = new stdClass;
$tmp_object->str_attr = 'test';
$tmp_object->int_attr = 123;

$memcache->set('key', $tmp_object, false, 10) or die ("Failed to save data at the server");
echo "Store data in the cache (data will expire in 10 seconds)<br/>\n";

$get_result = $memcache->get('key');
echo "Data from the cache:<br/>\n";

var_dump($get_result);

?>

Example #2 Using memcache session handler

<?php

$session_save_path = "tcp://$host:$port?persistent=1&weight=2&timeout=2&retry_interval=10,  ,tcp://$host:$port  ";
ini_set('session.save_handler', 'memcache');
ini_set('session.save_path', $session_save_path);

?>


The Memcache class

(PECL memcache >= 0.2.0)

Introduction

Represents a connection to a set of memcache servers.

Class synopsis

Memcache {
add ( string $key , mixed $var [, int $flag [, int $expire ]] ) : bool
addServer ( string $host [, int $port = 11211 [, bool $persistent [, int $weight [, int $timeout [, int $retry_interval [, bool $status [, callable $failure_callback [, int $timeoutms ]]]]]]]] ) : bool
close ( void ) : bool
connect ( string $host [, int $port [, int $timeout ]] ) : bool
decrement ( string $key [, int $value = 1 ] ) : int
delete ( string $key [, int $timeout = 0 ] ) : bool
flush ( void ) : bool
get ( string $key [, int &$flags ] ) : string
getExtendedStats ([ string $type [, int $slabid [, int $limit = 100 ]]] ) : array
getServerStatus ( string $host [, int $port = 11211 ] ) : int
getStats ([ string $type [, int $slabid [, int $limit = 100 ]]] ) : array
getVersion ( void ) : string
increment ( string $key [, int $value = 1 ] ) : int
pconnect ( string $host [, int $port [, int $timeout ]] ) : mixed
replace ( string $key , mixed $var [, int $flag [, int $expire ]] ) : bool
set ( string $key , mixed $var [, int $flag [, int $expire ]] ) : bool
setCompressThreshold ( int $threshold [, float $min_savings ] ) : bool
setServerParams ( string $host [, int $port = 11211 [, int $timeout [, int $retry_interval = FALSE [, bool $status [, callable $failure_callback ]]]]] ) : bool
}

Table of Contents

  • Memcache::add — Add an item to the server
  • Memcache::addServer — Add a memcached server to connection pool
  • Memcache::close — Close memcached server connection
  • Memcache::connect — Open memcached server connection
  • Memcache::decrement — Decrement item's value
  • Memcache::delete — Delete item from the server
  • Memcache::flush — Flush all existing items at the server
  • Memcache::get — Retrieve item from the server
  • Memcache::getExtendedStats — Get statistics from all servers in pool
  • Memcache::getServerStatus — Returns server status
  • Memcache::getStats — Get statistics of the server
  • Memcache::getVersion — Return version of the server
  • Memcache::increment — Increment item's value
  • Memcache::pconnect — Open memcached server persistent connection
  • Memcache::replace — Replace value of the existing item
  • Memcache::set — Store data at the server
  • Memcache::setCompressThreshold — Enable automatic compression of large values
  • Memcache::setServerParams — Changes server parameters and status at runtime


Add an item to the server

  • « Memcache
  • Memcache::addServer »
  • PHP Manual
  • Memcache
  • Add an item to the server

Memcache::add

(PECL memcache >= 0.2.0)

Memcache::add — Add an item to the server

Description

Memcache::add ( string $key , mixed $var [, int $flag [, int $expire ]] ) : bool

Memcache::add() stores variable var with key only if such key doesn't exist at the server yet. Also you can use memcache_add() function.

Parameters

key

The key that will be associated with the item.

var

The variable to store. Strings and integers are stored as is, other types are stored serialized.

flag

Use MEMCACHE_COMPRESSED to store the item compressed (uses zlib).

expire

Expiration time of the item. If it's equal to zero, the item will never expire. You can also use Unix timestamp or a number of seconds starting from current time, but in the latter case the number of seconds may not exceed 2592000 (30 days).

Return Values

Returns TRUE on success or FALSE on failure. Returns FALSE if such key already exist. For the rest Memcache::add() behaves similarly to Memcache::set().

Examples

Example #1 Memcache::add() example

<?php

$memcache_obj = memcache_connect("localhost", 11211);

/* procedural API */
memcache_add($memcache_obj, 'var_key', 'test variable', false, 30);

/* OO API */
$memcache_obj->add('var_key', 'test variable', false, 30);

?>

See Also

  • Memcache::set() - Store data at the server
  • Memcache::replace() - Replace value of the existing item


Add a memcached server to connection pool

  • « Memcache::add
  • Memcache::close »
  • PHP Manual
  • Memcache
  • Add a memcached server to connection pool

Memcache::addServer

(PECL memcache >= 2.0.0)

Memcache::addServer — Add a memcached server to connection pool

Description

Memcache::addServer ( string $host [, int $port = 11211 [, bool $persistent [, int $weight [, int $timeout [, int $retry_interval [, bool $status [, callable $failure_callback [, int $timeoutms ]]]]]]]] ) : bool

Memcache::addServer() adds a server to the connection pool. You can also use the memcache_add_server() function.

When using this method (as opposed to Memcache::connect() and Memcache::pconnect()) the network connection is not established until actually needed. Thus there is no overhead in adding a large number of servers to the pool, even though they might not all be used.

Failover may occur at any stage in any of the methods, as long as other servers are available the request the user won't notice. Any kind of socket or Memcached server level errors (except out-of-memory) may trigger the failover. Normal client errors such as adding an existing key will not trigger a failover.

Note:

This function has been added to Memcache version 2.0.0.

Parameters

host

Point to the host where memcached is listening for connections. This parameter may also specify other transports like unix:///path/to/memcached.sock to use UNIX domain sockets, in this case port must also be set to 0.

port

Point to the port where memcached is listening for connections. Set this parameter to 0 when using UNIX domain sockets.

Please note: port defaults to memcache.default_port if not specified. For this reason it is wise to specify the port explicitly in this method call.

persistent

Controls the use of a persistent connection. Default to TRUE.

weight

Number of buckets to create for this server which in turn control its probability of it being selected. The probability is relative to the total weight of all servers.

timeout

Value in seconds which will be used for connecting to the daemon. Think twice before changing the default value of 1 second - you can lose all the advantages of caching if your connection is too slow.

retry_interval

Controls how often a failed server will be retried, the default value is 15 seconds. Setting this parameter to -1 disables automatic retry. Neither this nor the persistent parameter has any effect when the extension is loaded dynamically via dl().

Each failed connection struct has its own timeout and before it has expired the struct will be skipped when selecting backends to serve a request. Once expired the connection will be successfully reconnected or marked as failed for another retry_interval seconds. The typical effect is that each web server child will retry the connection about every retry_interval seconds when serving a page.

status

Controls if the server should be flagged as online. Setting this parameter to FALSE and retry_interval to -1 allows a failed server to be kept in the pool so as not to affect the key distribution algorithm. Requests for this server will then failover or fail immediately depending on the memcache.allow_failover setting. Default to TRUE, meaning the server should be considered online.

failure_callback

Allows the user to specify a callback function to run upon encountering an error. The callback is run before failover is attempted. The function takes two parameters, the hostname and port of the failed server.

timeoutms

Notes

Warning

When the port is unspecified, this method defaults to the value set of the PHP ini directive memcache.default_port If this value was changed elsewhere in your application it might lead to unexpected results: for this reason it is wise to always specify the port explicitly in this method call.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Memcache::addServer() example

<?php

/* OO API */

$memcache = new Memcache;
$memcache->addServer('memcache_host', 11211);
$memcache->addServer('memcache_host2', 11211);

/* procedural API */

$memcache_obj = memcache_connect('memcache_host', 11211);
memcache_add_server($memcache_obj, 'memcache_host2', 11211);

?>

See Also

  • Memcache::connect() - Open memcached server connection
  • Memcache::pconnect() - Open memcached server persistent connection
  • Memcache::close() - Close memcached server connection
  • Memcache::setServerParams() - Changes server parameters and status at runtime
  • Memcache::getServerStatus() - Returns server status


Close memcached server connection

  • « Memcache::addServer
  • Memcache::connect »
  • PHP Manual
  • Memcache
  • Close memcached server connection

Memcache::close

(PECL memcache >= 0.4.0)

Memcache::close — Close memcached server connection

Description

Memcache::close ( void ) : bool

Memcache::close() closes connection to memcached server. This function doesn't close persistent connections, which are closed only during web-server shutdown/restart. Also you can use memcache_close() function.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Memcache::close() example

<?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);
/*
do something here ..
*/
memcache_close($memcache_obj);

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);
/*
do something here ..
*/
$memcache_obj->close();

?>

See Also

  • Memcache::connect() - Open memcached server connection
  • Memcache::pconnect() - Open memcached server persistent connection


Open memcached server connection

  • « Memcache::close
  • Memcache::decrement »
  • PHP Manual
  • Memcache
  • Open memcached server connection

Memcache::connect

(PECL memcache >= 0.2.0)

Memcache::connect — Open memcached server connection

Description

Memcache::connect ( string $host [, int $port [, int $timeout ]] ) : bool

Memcache::connect() establishes a connection to the memcached server. The connection, which was opened using Memcache::connect() will be automatically closed at the end of script execution. Also you can close it with Memcache::close(). Also you can use memcache_connect() function.

Parameters

host

Point to the host where memcached is listening for connections. This parameter may also specify other transports like unix:///path/to/memcached.sock to use UNIX domain sockets, in this case port must also be set to 0.

port

Point to the port where memcached is listening for connections. Set this parameter to 0 when using UNIX domain sockets.

Please note: port defaults to memcache.default_port if not specified. For this reason it is wise to specify the port explicitly in this method call.

timeout

Value in seconds which will be used for connecting to the daemon. Think twice before changing the default value of 1 second - you can lose all the advantages of caching if your connection is too slow.

Notes

Warning

When the port is unspecified, this method defaults to the value set of the PHP ini directive memcache.default_port If this value was changed elsewhere in your application it might lead to unexpected results: for this reason it is wise to always specify the port explicitly in this method call.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Memcache::connect() example

<?php

/* procedural API */

$memcache_obj = memcache_connect('memcache_host', 11211);

/* OO API */

$memcache = new Memcache;
$memcache->connect('memcache_host', 11211);

?>

See Also

  • Memcache::pconnect() - Open memcached server persistent connection
  • Memcache::close() - Close memcached server connection


Decrement item's value

  • « Memcache::connect
  • Memcache::delete »
  • PHP Manual
  • Memcache
  • Decrement item's value

Memcache::decrement

(PECL memcache >= 0.2.0)

Memcache::decrement — Decrement item's value

Description

Memcache::decrement ( string $key [, int $value = 1 ] ) : int

Memcache::decrement() decrements value of the item by value. Similarly to Memcache::increment(), current value of the item is being converted to numerical and after that value is subtracted.

Note:

New item's value will not be less than zero.

Note:

Do not use Memcache::decrement() with item, which was stored compressed, because consequent call to Memcache::get() will fail.

Memcache::decrement() does not create an item if it didn't exist. Also you can use memcache_decrement() function.

Parameters

key

Key of the item do decrement.

value

Decrement the item by value.

Return Values

Returns item's new value on success or FALSE on failure.

Examples

Example #1 Memcache::decrement() example

<?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);
/* decrement item by 2 */
$new_value = memcache_decrement($memcache_obj, 'test_item', 2);

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);
/* decrement item by 3 */
$new_value = $memcache_obj->decrement('test_item', 3);
?>

See Also

  • Memcache::increment() - Increment item's value
  • Memcache::replace() - Replace value of the existing item


Delete item from the server

  • « Memcache::decrement
  • Memcache::flush »
  • PHP Manual
  • Memcache
  • Delete item from the server

Memcache::delete

(PECL memcache >= 0.2.0)

Memcache::delete — Delete item from the server

Description

Memcache::delete ( string $key [, int $timeout = 0 ] ) : bool

Memcache::delete() deletes an item with the key.

Parameters

key

The key associated with the item to delete.

timeout

This deprecated parameter is not supported, and defaults to 0 seconds. Do not use this parameter.

Changelog

Version | Description
Unknown | It's not recommended to use the timeout parameter. The behavior differs between memcached versions, but setting to 0 is safe. Other values for this deprecated feature may cause the memcache delete to fail.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Memcache::delete() example

<?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);

/* item will be deleted by the server */
memcache_delete($memcache_obj, 'key_to_delete');

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);

$memcache_obj->delete('key_to_delete');

?>

See Also

  • Memcache::set() - Store data at the server
  • Memcache::replace() - Replace value of the existing item


Flush all existing items at the server

  • « Memcache::delete
  • Memcache::get »
  • PHP Manual
  • Memcache
  • Flush all existing items at the server

Memcache::flush

(PECL memcache >= 1.0.0)

Memcache::flush — Flush all existing items at the server

Description

Memcache::flush ( void ) : bool

Memcache::flush() immediately invalidates all existing items. Memcache::flush() doesn't actually free any resources, it only marks all the items as expired, so occupied memory will be overwritten by new items. Also you can use memcache_flush() function.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Memcache::flush() example

<?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);

memcache_flush($memcache_obj);

/* OO API */

$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);

$memcache_obj->flush();

?>


Retrieve item from the server

  • « Memcache::flush
  • Memcache::getExtendedStats »
  • PHP Manual
  • Memcache
  • Retrieve item from the server

Memcache::get

(PECL memcache >= 0.2.0)

Memcache::get — Retrieve item from the server

Description

Memcache::get ( string $key [, int &$flags ] ) : string
Memcache::get ( array $keys [, array &$flags ] ) : array

Memcache::get() returns previously stored data of an item, if such key exists on the server at this moment.

You can pass array of keys to Memcache::get() to get array of values. The result array will contain only found key-value pairs.

Parameters

key

The key or array of keys to fetch.

flags

If present, flags fetched along with the values will be written to this parameter. These flags are the same as the ones given to for example Memcache::set(). The lowest byte of the int is reserved for pecl/memcache internal usage (e.g. to indicate compression and serialization status).

Return Values

Returns the value associated with the key or an array of found key-value pairs when key is an array. Returns FALSE on failure, key is not found or key is an empty array.

Examples

Example #1 Memcache::get() example

<?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);
$var = memcache_get($memcache_obj, 'some_key');

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);
$var = $memcache_obj->get('some_key');

/*
You also can use array of keys as a parameter.
If such item wasn't found at the server, the result
array simply will not include such key.
*/

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);
$var = memcache_get($memcache_obj, Array('some_key', 'another_key'));

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);
$var = $memcache_obj->get(Array('some_key', 'second_key'));

?>


Get statistics from all servers in pool

  • « Memcache::get
  • Memcache::getServerStatus »
  • PHP Manual
  • Memcache
  • Get statistics from all servers in pool

Memcache::getExtendedStats

(PECL memcache >= 2.0.0)

Memcache::getExtendedStats — Get statistics from all servers in pool

Description

Memcache::getExtendedStats ([ string $type [, int $slabid [, int $limit = 100 ]]] ) : array

Memcache::getExtendedStats() returns a two-dimensional associative array with server statistics. Array keys correspond to host:port of server and values contain the individual server statistics. A failed server will have its corresponding entry set to FALSE. You can also use the memcache_get_extended_stats() function.

Note:

This function has been added to Memcache version 2.0.0.

Parameters

type

The type of statistics to fetch. Valid values are {reset, malloc, maps, cachedump, slabs, items, sizes}. According to the memcached protocol spec these additional arguments "are subject to change for the convenience of memcache developers".

slabid

Used in conjunction with type set to cachedump to identify the slab to dump from. The cachedump command ties up the server and is strictly to be used for debugging purposes.

limit

Used in conjunction with type set to cachedump to limit the number of entries to dump.

Warning

The cachedump stat type has been removed from the memcached daemon due to security reasons.

Return Values

Returns a two-dimensional associative array of server statistics or FALSE on failure.

Examples

Example #1 Memcache::getExtendedStats() example

<?php
    $memcache_obj = new Memcache;
    $memcache_obj->addServer('memcache_host', 11211);
    $memcache_obj->addServer('failed_host', 11211);

    $stats = $memcache_obj->getExtendedStats();
    print_r($stats);
?>

The above example will output:

Array
(
    [memcache_host:11211] => Array
        (
            [pid] => 3756
            [uptime] => 603011
            [time] => 1133810435
            [version] => 1.1.12
            [rusage_user] => 0.451931
            [rusage_system] => 0.634903
            [curr_items] => 2483
            [total_items] => 3079
            [bytes] => 2718136
            [curr_connections] => 2
            [total_connections] => 807
            [connection_structures] => 13
            [cmd_get] => 9748
            [cmd_set] => 3096
            [get_hits] => 5976
            [get_misses] => 3772
            [bytes_read] => 3448968
            [bytes_written] => 2318883
            [limit_maxbytes] => 33554432
        )

    [failed_host:11211] => false
)

See Also

  • Memcache::getVersion() - Return version of the server
  • Memcache::getStats() - Get statistics of the server


Returns server status

  • « Memcache::getExtendedStats
  • Memcache::getStats »
  • PHP Manual
  • Memcache
  • Returns server status

Memcache::getServerStatus

(PECL memcache >= 2.1.0)

Memcache::getServerStatus — Returns server status

Description

Memcache::getServerStatus ( string $host [, int $port = 11211 ] ) : int

Memcache::getServerStatus() returns a the servers online/offline status. You can also use memcache_get_server_status() function.

Note:

This function has been added to Memcache version 2.1.0.

Parameters

host

Point to the host where memcached is listening for connections.

port

Point to the port where memcached is listening for connections.

Return Values

Returns a the servers status. 0 if server is failed, non-zero otherwise

Examples

Example #1 Memcache::getServerStatus() example

<?php

/* OO API */
$memcache = new Memcache;
$memcache->addServer('memcache_host', 11211);
echo $memcache->getServerStatus('memcache_host', 11211);

/* procedural API */
$memcache = memcache_connect('memcache_host', 11211);
echo memcache_get_server_status($memcache, 'memcache_host', 11211);

?>

See Also

  • Memcache::addServer() - Add a memcached server to connection pool
  • Memcache::setServerParams() - Changes server parameters and status at runtime


Get statistics of the server

  • « Memcache::getServerStatus
  • Memcache::getVersion »
  • PHP Manual
  • Memcache
  • Get statistics of the server

Memcache::getStats

(PECL memcache >= 0.2.0)

Memcache::getStats — Get statistics of the server

Description

Memcache::getStats ([ string $type [, int $slabid [, int $limit = 100 ]]] ) : array

Memcache::getStats() returns an associative array with server's statistics. Array keys correspond to stats parameters and values to parameter's values. Also you can use memcache_get_stats() function.

Parameters

type

The type of statistics to fetch. Valid values are {reset, malloc, maps, cachedump, slabs, items, sizes}. According to the memcached protocol spec these additional arguments "are subject to change for the convenience of memcache developers".

slabid

Used in conjunction with type set to cachedump to identify the slab to dump from. The cachedump command ties up the server and is strictly to be used for debugging purposes.

limit

Used in conjunction with type set to cachedump to limit the number of entries to dump.

Return Values

Returns an associative array of server statistics or FALSE on failure.

See Also

  • Memcache::getVersion() - Return version of the server
  • Memcache::getExtendedStats() - Get statistics from all servers in pool


Return version of the server

  • « Memcache::getStats
  • Memcache::increment »
  • PHP Manual
  • Memcache
  • Return version of the server

Memcache::getVersion

(PECL memcache >= 0.2.0)

Memcache::getVersion — Return version of the server

Description

Memcache::getVersion ( void ) : string

Memcache::getVersion() returns a string with server's version number. Also you can use memcache_get_version() function.

Return Values

Returns a string of server version number or FALSE on failure.

Examples

Example #1 Memcache::getVersion() example

<?php

/* OO API */
$memcache = new Memcache;
$memcache->connect('memcache_host', 11211);
echo $memcache->getVersion();

/* procedural API */
$memcache = memcache_connect('memcache_host', 11211);
echo memcache_get_version($memcache);

?>

See Also

  • Memcache::getExtendedStats() - Get statistics from all servers in pool
  • Memcache::getStats() - Get statistics of the server


Increment item's value

  • « Memcache::getVersion
  • Memcache::pconnect »
  • PHP Manual
  • Memcache
  • Increment item's value

Memcache::increment

(PECL memcache >= 0.2.0)

Memcache::increment — Increment item's value

Description

Memcache::increment ( string $key [, int $value = 1 ] ) : int

Memcache::increment() increments value of an item by the specified value. If item specified by key was not numeric and cannot be converted to a number, it will change its value to value. Memcache::increment() does not create an item if it doesn't already exist.

Note:

Do not use Memcache::increment() with items that have been stored compressed because subsequent calls to Memcache::get() will fail.

Also you can use memcache_increment() function.

Parameters

key

Key of the item to increment.

value

Increment the item by value.

Return Values

Returns new items value on success or FALSE on failure.

Examples

Example #1 Memcache::increment() example

<?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);
/* increment counter by 2 */
$current_value = memcache_increment($memcache_obj, 'counter', 2);

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);
/* increment counter by 3 */
$current_value = $memcache_obj->increment('counter', 3);

?>

See Also

  • Memcache::decrement() - Decrement item's value
  • Memcache::replace() - Replace value of the existing item


Open memcached server persistent connection

  • « Memcache::increment
  • Memcache::replace »
  • PHP Manual
  • Memcache
  • Open memcached server persistent connection

Memcache::pconnect

(PECL memcache >= 0.4.0)

Memcache::pconnect — Open memcached server persistent connection

Description

Memcache::pconnect ( string $host [, int $port [, int $timeout ]] ) : mixed

Memcache::pconnect() is similar to Memcache::connect() with the difference, that the connection it establishes is persistent. This connection is not closed after the end of script execution and by Memcache::close() function. Also you can use memcache_pconnect() function.

Parameters

host

Point to the host where memcached is listening for connections. This parameter may also specify other transports like unix:///path/to/memcached.sock to use UNIX domain sockets, in this case port must also be set to 0.

port

Point to the port where memcached is listening for connections. Set this parameter to 0 when using UNIX domain sockets.

timeout

Value in seconds which will be used for connecting to the daemon. Think twice before changing the default value of 1 second - you can lose all the advantages of caching if your connection is too slow.

Return Values

Returns a Memcache object or FALSE on failure.

Examples

Example #1 Memcache::pconnect() example

<?php

/* procedural API */
$memcache_obj = memcache_pconnect('memcache_host', 11211);

/* OO API */

$memcache_obj = new Memcache;
$memcache_obj->pconnect('memcache_host', 11211);

?>

See Also

  • Memcache::connect() - Open memcached server connection


Replace value of the existing item

  • « Memcache::pconnect
  • Memcache::set »
  • PHP Manual
  • Memcache
  • Replace value of the existing item

Memcache::replace

(PECL memcache >= 0.2.0)

Memcache::replace — Replace value of the existing item

Description

Memcache::replace ( string $key , mixed $var [, int $flag [, int $expire ]] ) : bool

Memcache::replace() should be used to replace value of
existing item with key. In case if item with such
key doesn't exists, Memcache::replace() returns
FALSE. For the rest Memcache::replace() behaves
similarly to Memcache::set().
Also you can use memcache_replace() function.

Parameters

key

The key that will be associated with the item.

var

The variable to store. Strings and integers are stored as is, other types are stored serialized.

flag

Use MEMCACHE_COMPRESSED to store the item compressed (uses zlib).

expire

Expiration time of the item. If it's equal to zero, the item will never expire. You can also use Unix timestamp or a number of seconds starting from current time, but in the latter case the number of seconds may not exceed 2592000 (30 days).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Memcache::replace() example

<?php

$memcache_obj = memcache_connect('memcache_host', 11211);

/* procedural API */
memcache_replace($memcache_obj, "test_key", "some variable", false, 30);

/* OO API */
$memcache_obj->replace("test_key", "some variable", false, 30);

?>

See Also

  • Memcache::set() - Store data at the server
  • Memcache::add() - Add an item to the server


Store data at the server

  • « Memcache::replace
  • Memcache::setCompressThreshold »
  • PHP Manual
  • Memcache
  • Store data at the server

Memcache::set

(PECL memcache >= 0.2.0)

Memcache::set — Store data at the server

Description

Memcache::set ( string $key , mixed $var [, int $flag [, int $expire ]] ) : bool

Memcache::set() stores an item var with key on the memcached server. Parameter expire is expiration time in seconds. If it's 0, the item never expires (but memcached server doesn't guarantee this item to be stored all the time, it could be deleted from the cache to make place for other items). You can use MEMCACHE_COMPRESSED constant as flag value if you want to use on-the-fly compression (uses zlib).

Note:

Remember that resource variables (i.e. file and connection descriptors) cannot be stored in the cache, because they cannot be adequately represented in serialized state.

Also you can use memcache_set() function.

Parameters

key

The key that will be associated with the item.

var

The variable to store. Strings and integers are stored as is, other types are stored serialized.

flag

Use MEMCACHE_COMPRESSED to store the item compressed (uses zlib).

expire

Expiration time of the item. If it's equal to zero, the item will never expire. You can also use Unix timestamp or a number of seconds starting from current time, but in the latter case the number of seconds may not exceed 2592000 (30 days).

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Memcache::set() example

<?php
/* procedural API */

/* connect to memcached server */
$memcache_obj = memcache_connect('memcache_host', 11211);

/*
set value of item with key 'var_key'
using 0 as flag value, compression is not used
expire time is 30 seconds
*/
memcache_set($memcache_obj, 'var_key', 'some variable', 0, 30);

echo memcache_get($memcache_obj, 'var_key');

?>

Example #2 Memcache::set() example

<?php
/* OO API */

$memcache_obj = new Memcache;

/* connect to memcached server */
$memcache_obj->connect('memcache_host', 11211);

/*
set value of item with key 'var_key', using on-the-fly compression
expire time is 50 seconds
*/
$memcache_obj->set('var_key', 'some really big variable', MEMCACHE_COMPRESSED, 50);

echo $memcache_obj->get('var_key');

?>

See Also

  • Memcache::add() - Add an item to the server
  • Memcache::replace() - Replace value of the existing item


Enable automatic compression of large values

  • « Memcache::set
  • Memcache::setServerParams »
  • PHP Manual
  • Memcache
  • Enable automatic compression of large values

Memcache::setCompressThreshold

(PECL memcache >= 2.0.0)

Memcache::setCompressThreshold — Enable automatic compression of large values

Description

Memcache::setCompressThreshold ( int $threshold [, float $min_savings ] ) : bool

Memcache::setCompressThreshold() enables automatic compression of large values. You can also use the memcache_set_compress_threshold() function.

Note:

This function has been added to Memcache version 2.0.0.

Parameters

threshold

Controls the minimum value length before attempting to compress automatically.

min_saving

Specifies the minimum amount of savings to actually store the value compressed. The supplied value must be between 0 and 1. Default value is 0.2 giving a minimum 20% compression savings.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Memcache::setCompressThreshold() example

<?php

/* OO API */

$memcache_obj = new Memcache;
$memcache_obj->addServer('memcache_host', 11211);
$memcache_obj->setCompressThreshold(20000, 0.2);

/* procedural API */

$memcache_obj = memcache_connect('memcache_host', 11211);
memcache_set_compress_threshold($memcache_obj, 20000, 0.2);

?>


Changes server parameters and status at runtime

  • « Memcache::setCompressThreshold
  • Memcache Functions »
  • PHP Manual
  • Memcache
  • Changes server parameters and status at runtime

Memcache::setServerParams

(PECL memcache >= 2.1.0)

Memcache::setServerParams — Changes server parameters and status at runtime

Description

Memcache::setServerParams ( string $host [, int $port = 11211 [, int $timeout [, int $retry_interval = FALSE [, bool $status [, callable $failure_callback ]]]]] ) : bool

Memcache::setServerParams() changes server parameters at runtime. You can also use the memcache_set_server_params() function.

Note:

This function has been added to Memcache version 2.1.0.

Parameters

host

Point to the host where memcached is listening for connections.

port

Point to the port where memcached is listening for connections.

timeout

Value in seconds which will be used for connecting to the daemon. Think twice before changing the default value of 1 second - you can lose all the advantages of caching if your connection is too slow.

retry_interval

Controls how often a failed server will be retried, the default value is 15 seconds. Setting this parameter to -1 disables automatic retry. Neither this nor the persistent parameter has any effect when the extension is loaded dynamically via dl().

status

Controls if the server should be flagged as online. Setting this parameter to FALSE and retry_interval to -1 allows a failed server to be kept in the pool so as not to affect the key distribution algorithm. Requests for this server will then failover or fail immediately depending on the memcache.allow_failover setting. Default to TRUE, meaning the server should be considered online.

failure_callback

Allows the user to specify a callback function to run upon encountering an error. The callback is run before failover is attempted. The function takes two parameters, the hostname and port of the failed server.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Memcache::setServerParams() example

<?php

function _callback_memcache_failure($host, $port) {
    print "memcache '$host:$port' failed";
}

/* OO API */

$memcache = new Memcache;

// Add the server in offline mode
$memcache->addServer('memcache_host', 11211, false, 1, 1, -1, false);

// Bring the server back online
$memcache->setServerParams('memcache_host', 11211, 1, 15, true, '_callback_memcache_failure');

/* procedural API */

$memcache_obj = memcache_connect('memcache_host', 11211);
memcache_set_server_params($memcache_obj, 'memcache_host', 11211, 1, 15, true, '_callback_memcache_failure');

?>

See Also

  • Memcache::addServer() - Add a memcached server to connection pool
  • Memcache::getServerStatus() - Returns server status


  • « Memcache::setServerParams
  • memcache_debug »
  • PHP Manual
  • Memcache
  • Memcache Functions

Memcache Functions

Table of Contents

  • memcache_debug — Turn debug output on/off


Turn debug output on/off

  • « Memcache Functions
  • Memcached »
  • PHP Manual
  • Memcache Functions
  • Turn debug output on/off

memcache_debug

(PECL memcache >= 0.2.0)

memcache_debug — Turn debug output on/off

Description

memcache_debug ( bool $on_off ) : bool

memcache_debug() turns on debug output if parameter on_off is equal to TRUE and turns off if it's FALSE.

Note:

memcache_debug() is accessible only if PHP was built with --enable-debug option and always returns TRUE in this case. Otherwise, this function has no effect and always returns FALSE.

Parameters

on_off

Turns debug output on if equals to TRUE. Turns debug output off if equals to FALSE.

Return Values

Returns TRUE if PHP was built with --enable-debug option, otherwise returns FALSE.


Memcached

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Expiration Times
  • Callbacks
    • Result callbacks
    • Read-through cache callbacks
  • Sessions support
  • Memcached — The Memcached class
    • Memcached::add — Add an item under a new key
    • Memcached::addByKey — Add an item under a new key on a specific server
    • Memcached::addServer — Add a server to the server pool
    • Memcached::addServers — Add multiple servers to the server pool
    • Memcached::append — Append data to an existing item
    • Memcached::appendByKey — Append data to an existing item on a specific server
    • Memcached::cas — Compare and swap an item
    • Memcached::casByKey — Compare and swap an item on a specific server
    • Memcached::__construct — Create a Memcached instance
    • Memcached::decrement — Decrement numeric item's value
    • Memcached::decrementByKey — Decrement numeric item's value, stored on a specific server
    • Memcached::delete — Delete an item
    • Memcached::deleteByKey — Delete an item from a specific server
    • Memcached::deleteMulti — Delete multiple items
    • Memcached::deleteMultiByKey — Delete multiple items from a specific server
    • Memcached::fetch — Fetch the next result
    • Memcached::fetchAll — Fetch all the remaining results
    • Memcached::flush — Invalidate all items in the cache
    • Memcached::get — Retrieve an item
    • Memcached::getAllKeys — Gets the keys stored on all the servers
    • Memcached::getByKey — Retrieve an item from a specific server
    • Memcached::getDelayed — Request multiple items
    • Memcached::getDelayedByKey — Request multiple items from a specific server
    • Memcached::getMulti — Retrieve multiple items
    • Memcached::getMultiByKey — Retrieve multiple items from a specific server
    • Memcached::getOption — Retrieve a Memcached option value
    • Memcached::getResultCode — Return the result code of the last operation
    • Memcached::getResultMessage — Return the message describing the result of the last operation
    • Memcached::getServerByKey — Map a key to a server
    • Memcached::getServerList — Get the list of the servers in the pool
    • Memcached::getStats — Get server pool statistics
    • Memcached::getVersion — Get server pool version info
    • Memcached::increment — Increment numeric item's value
    • Memcached::incrementByKey — Increment numeric item's value, stored on a specific server
    • Memcached::isPersistent — Check if a persitent connection to memcache is being used
    • Memcached::isPristine — Check if the instance was recently created
    • Memcached::prepend — Prepend data to an existing item
    • Memcached::prependByKey — Prepend data to an existing item on a specific server
    • Memcached::quit — Close any open connections
    • Memcached::replace — Replace the item under an existing key
    • Memcached::replaceByKey — Replace the item under an existing key on a specific server
    • Memcached::resetServerList — Clears all servers from the server list
    • Memcached::set — Store an item
    • Memcached::setByKey — Store an item on a specific server
    • Memcached::setMulti — Store multiple items
    • Memcached::setMultiByKey — Store multiple items on a specific server
    • Memcached::setOption — Set a Memcached option
    • Memcached::setOptions — Set Memcached options
    • Memcached::setSaslAuthData — Set the credentials to use for authentication
    • Memcached::touch — Set a new expiration on an item
    • Memcached::touchByKey — Set a new expiration on an item on a specific server
  • MemcachedException — The MemcachedException class


Introduction

» memcached is a high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.

This extension uses the libmemcached library to provide an API for communicating with memcached servers. It also provides a session handler (memcached).

Information about libmemcached can be found at » http://libmemcached.org/libMemcached.html.


Requirements

This extension requires » libmemcached client library (version 1.0.0 or greater). For SASL authentication support, libmemcached must be built with SASL enabled.

Since version 0.2.0, this extension requires PHP version 5.2.0 or higher.


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/memcached.

If libmemcached is installed in a non-standard location, use --with-libmemcached-dir=DIR switch, where DIR is the libmemcached install prefix. This directory has to contain the include/libmemcached/memcached.h file.

Zlib is required for compression support. To specify non-standard installation of Zlib, use --with-zlib-dir=DIR switch, where DIR is the Zlib install prefix.

Session handler support is enabled by default. To disable it, use --disable-memcached-session switch.

SASL authentication support is disabled by default. To enable it, use --enable-memcached-sasl switch. This requires that libsasl2 has been installed and that libmemcached has been built with SASL support enabled.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Memcached Configure Options
Name | Default | Changeable | Changelog
memcached.sess_locking | 1 | PHP_INI_ALL |
memcached.sess_consistent_hash | 0 | PHP_INI_ALL |
memcached.sess_binary | 0 | PHP_INI_ALL |
memcached.sess_lock_wait | 150000 | PHP_INI_ALL |
memcached.sess_prefix | memc.sess.key. | PHP_INI_ALL |
memcached.sess_number_of_replicas | 0 | PHP_INI_ALL |
memcached.sess_randomize_replica_read | 0 | PHP_INI_ALL |
memcached.sess_remove_failed | 0 | PHP_INI_ALL |
memcached.compression_type | fastlz | PHP_INI_ALL |
memcached.compression_factor | 1.3 | PHP_INI_ALL |
memcached.compression_threshold | 2000 | PHP_INI_ALL |
memcached.serializer | php | PHP_INI_ALL |
memcached.use_sasl | 0 | PHP_INI_SYSTEM |

Here's a short explanation of the configuration directives.

memcached.sess_locking integer

Use session locking. Valid values: On, Off, the default is On.

memcached.sess_consistent_hash integer

Memcached session consistent hash mode. If set to On, consistent hashing is used for session handling. When consistent hashing is used, one can add or remove cache node(s) without messing up too much with existing keys. The default is Off.

memcached.sess_binary integer

Use memcached session binary mode. Libmemcached replicas only work if binary mode is enabled. The default is Off.

memcached.sess_lock_wait integer

Session spin lock retry wait time in microseconds. Be carefull when setting this value. Valid values are integers, where 0 is interpreted as the default value. Negative values result in a reduces locking to a try lock. The default is 150000.

memcached.sess_prefix string

Memcached session key prefix. Valid values are strings less than 219 bytes long. The default value is "memc.sess.key."

memcached.sess_number_of_replicas integer

The memcached session number of replicas.

memcached.sess_randomize_replica_read integer

Memcached session replica read randomize.

memcached.sess_remove_failed integer

Allow failed memcached server to automatically be removed.

memcached.compression_type string

Set the compression type, valid values are: fastlz, zlib. The default is fastlz.

memcached.compression_factor float

Compression factor. Store compressed value only if the compression factor (saving) exceeds the set limit. Store compressed if: plain_len > comp_len * factor. The default value is 1.3 (23% space saving).

memcached.compression_threshold integer

The compression threshold. Do not compress serialized values below this threshold. The default is 2000 bytes.

memcached.serializer string

Set the default serializer for new memcached objects. Valid values are: php, igbinary, json, json_array.

json

Standard php JSON encoding. This serializer is fast and compact but only works on UTF-8 encoded data and does not fully implement serializing. See the JSON extension.

json_array

As json, but decodes into arrays.

php

The standard PHP serializer.

igbinary

A binary serializer

The default is igbinary if available and php otherwise.

memcached.use_sasl integer

Use SASL authentication for connections. Valid values: On, Off. The default is Off.


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.

Memcached::OPT_COMPRESSION

Enables or disables payload compression. When enabled, item values longer than a certain threshold (currently 100 bytes) will be compressed during storage and decompressed during retrieval transparently.

Type: boolean, default: TRUE.

Memcached::OPT_SERIALIZER

Specifies the serializer to use for serializing non-scalar values. The valid serializers are Memcached::SERIALIZER_PHP or Memcached::SERIALIZER_IGBINARY. The latter is supported only when memcached is configured with --enable-memcached-igbinary option and the igbinary extension is loaded.

Type: integer, default: Memcached::SERIALIZER_PHP.

Memcached::SERIALIZER_PHP

The default PHP serializer.

Memcached::SERIALIZER_IGBINARY

The » igbinary serializer. Instead of textual representation it stores PHP data structures in a compact binary form, resulting in space and time gains.

Memcached::SERIALIZER_JSON

The JSON serializer. Requires PHP 5.2.10+.

Memcached::OPT_PREFIX_KEY

This can be used to create a "domain" for your item keys. The value specified here will be prefixed to each of the keys. It cannot be longer than 128 characters and will reduce the maximum available key size. The prefix is applied only to the item keys, not to the server keys.

Type: string, default: "".

Memcached::OPT_HASH

Specifies the hashing algorithm used for the item keys. The valid values are supplied via Memcached::HASH_* constants. Each hash algorithm has its advantages and its disadvantages. Go with the default if you don't know or don't care.

Type: integer, default: Memcached::HASH_DEFAULT

Memcached::HASH_DEFAULT

The default (Jenkins one-at-a-time) item key hashing algorithm.

Memcached::HASH_MD5

MD5 item key hashing algorithm.

Memcached::HASH_CRC

CRC item key hashing algorithm.

Memcached::HASH_FNV1_64

FNV1_64 item key hashing algorithm.

Memcached::HASH_FNV1A_64

FNV1_64A item key hashing algorithm.

Memcached::HASH_FNV1_32

FNV1_32 item key hashing algorithm.

Memcached::HASH_FNV1A_32

FNV1_32A item key hashing algorithm.

Memcached::HASH_HSIEH

Hsieh item key hashing algorithm.

Memcached::HASH_MURMUR

Murmur item key hashing algorithm.

Memcached::OPT_DISTRIBUTION

Specifies the method of distributing item keys to the servers. Currently supported methods are modulo and consistent hashing. Consistent hashing delivers better distribution and allows servers to be added to the cluster with minimal cache losses.

Type: integer, default: Memcached::DISTRIBUTION_MODULA.

Memcached::DISTRIBUTION_MODULA

Modulo-based key distribution algorithm.

Memcached::DISTRIBUTION_CONSISTENT

Consistent hashing key distribution algorithm (based on libketama).

Memcached::OPT_LIBKETAMA_COMPATIBLE

Enables or disables compatibility with libketama-like behavior. When enabled, the item key hashing algorithm is set to MD5 and distribution is set to be weighted consistent hashing distribution. This is useful because other libketama-based clients (Python, Ruby, etc.) with the same server configuration will be able to access the keys transparently.

Note:

It is highly recommended to enable this option if you want to use consistent hashing, and it may be enabled by default in future releases.

Type: boolean, default: FALSE.

Memcached::OPT_BUFFER_WRITES

Enables or disables buffered I/O. Enabling buffered I/O causes storage commands to "buffer" instead of being sent. Any action that retrieves data causes this buffer to be sent to the remote connection. Quitting the connection or closing down the connection will also cause the buffered data to be pushed to the remote connection.

Type: boolean, default: FALSE.

Memcached::OPT_BINARY_PROTOCOL

Enable the use of the binary protocol. Please note that you cannot toggle this option on an open connection.

Type: boolean, default: FALSE.

Memcached::OPT_NO_BLOCK

Enables or disables asynchronous I/O. This is the fastest transport available for storage functions.

Type: boolean, default: FALSE.

Memcached::OPT_TCP_NODELAY

Enables or disables the no-delay feature for connecting sockets (may be faster in some environments).

Type: boolean, default: FALSE.

Memcached::OPT_SOCKET_SEND_SIZE

The maximum socket send buffer in bytes.

Type: integer, default: varies by platform/kernel configuration.

Memcached::OPT_SOCKET_RECV_SIZE

The maximum socket receive buffer in bytes.

Type: integer, default: varies by platform/kernel configuration.

Memcached::OPT_CONNECT_TIMEOUT

In non-blocking mode this set the value of the timeout during socket connection, in milliseconds.

Type: integer, default: 1000.

Memcached::OPT_RETRY_TIMEOUT

The amount of time, in seconds, to wait until retrying a failed connection attempt.

Type: integer, default: 0.

Memcached::OPT_SEND_TIMEOUT

Socket sending timeout, in microseconds. In cases where you cannot use non-blocking I/O this will allow you to still have timeouts on the sending of data.

Type: integer, default: 0.

Memcached::OPT_RECV_TIMEOUT

Socket reading timeout, in microseconds. In cases where you cannot use non-blocking I/O this will allow you to still have timeouts on the reading of data.

Type: integer, default: 0.

Memcached::OPT_POLL_TIMEOUT

Timeout for connection polling, in milliseconds.

Type: integer, default: 1000.

Memcached::OPT_CACHE_LOOKUPS

Enables or disables caching of DNS lookups.

Type: boolean, default: FALSE.

Memcached::OPT_SERVER_FAILURE_LIMIT

Specifies the failure limit for server connection attempts. The server will be removed after this many continuous connection failures.

Type: integer, default: 0.

Memcached::HAVE_IGBINARY

Indicates whether igbinary serializer support is available.

Type: boolean.

Memcached::HAVE_JSON

Indicates whether JSON serializer support is available.

Type: boolean.

Memcached::HAVE_MSGPACK

Indicates whether msgpack serializer support is available.

Type: boolean.

Available as of Memcached 3.0.0.

Memcached::HAVE_SESSION

Type: boolean.

Available as of Memcached 3.0.0.

Memcached::HAVE_SASL

Type: boolean.

Available as of Memcached 3.0.0.

Memcached::GET_EXTENDED

A flag for Memcached::get(), Memcached::getMulti() and Memcached::getMultiByKey() to ensure that the CAS token values are returned as well.

Available as of Memcached 3.0.0.

Memcached::GET_PRESERVE_ORDER

A flag for Memcached::getMulti() and Memcached::getMultiByKey() to ensure that the keys are returned in the same order as they were requested in. Non-existing keys get a default value of NULL.

Memcached::RES_SUCCESS

The operation was successful.

Memcached::RES_FAILURE

The operation failed in some fashion.

Memcached::RES_HOST_LOOKUP_FAILURE

DNS lookup failed.

Memcached::RES_UNKNOWN_READ_FAILURE

Failed to read network data.

Memcached::RES_PROTOCOL_ERROR

Bad command in memcached protocol.

Memcached::RES_CLIENT_ERROR

Error on the client side.

Memcached::RES_SERVER_ERROR

Error on the server side.

Memcached::RES_WRITE_FAILURE

Failed to write network data.

Memcached::RES_DATA_EXISTS

Failed to do compare-and-swap: item you are trying to store has been modified since you last fetched it.

Memcached::RES_NOTSTORED

Item was not stored: but not because of an error. This normally means that either the condition for an "add" or a "replace" command wasn't met, or that the item is in a delete queue.

Memcached::RES_NOTFOUND

Item with this key was not found (with "get" operation or "cas" operations).

Memcached::RES_PARTIAL_READ

Partial network data read error.

Memcached::RES_SOME_ERRORS

Some errors occurred during multi-get.

Memcached::RES_NO_SERVERS

Server list is empty.

Memcached::RES_END

End of result set.

Memcached::RES_ERRNO

System error.

Memcached::RES_BUFFERED

The operation was buffered.

Memcached::RES_TIMEOUT

The operation timed out.

Memcached::RES_BAD_KEY_PROVIDED

Bad key.

Memcached::RES_CONNECTION_SOCKET_CREATE_FAILURE

Failed to create network socket.

Memcached::RES_PAYLOAD_FAILURE

Payload failure: could not compress/decompress or serialize/unserialize the value.

Memcached::RES_AUTH_PROBLEM

Available as of Memcached 3.0.0.

Memcached::RES_AUTH_FAILURE

Available as of Memcached 3.0.0.

Memcached::RES_AUTH_CONTINUE

Available as of Memcached 3.0.0.

Memcached::RES_E2BIG

Available as of Memcached 3.0.0.

Memcached::RES_KEY_TOO_BIG

Available as of Memcached 3.0.0.

Memcached::RES_SERVER_TEMPORARILY_DISABLED

Available as of Memcached 3.0.0.

Memcached::RES_SERVER_MEMORY_ALLOCATION_FAILURE

Available as of Memcached 3.0.0.


Expiration Times

Some storage commands involve sending an expiration value (relative to an item or to an operation requested by the client) to the server. In all such cases, the actual value sent may either be Unix time (number of seconds since January 1, 1970, as an integer), or a number of seconds starting from current time. In the latter case, this number of seconds may not exceed 60*60*24*30 (number of seconds in 30 days); if the expiration value is larger than that, the server will consider it to be real Unix time value rather than an offset from current time.

If the expiration value is 0 (the default), the item never expires (although it may be deleted from the server to make place for other items).


  • « Expiration Times
  • Result callbacks »
  • PHP Manual
  • Memcached
  • Callbacks

Callbacks

Table of Contents

  • Result callbacks
  • Read-through cache callbacks


Result callbacks

Result callbacks are invoked by Memcached::getDelayed() or Memcached::getDelayedBykey() methods for each item in the result set. The callback is passed the Memcached object and the array with the item information. The callback does not have to return anything.

Example #1 Result callback example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);
$items = array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3'
);
$m->setMulti($items);
$m->getDelayed(array('key1', 'key3'), true, 'result_cb');

function result_cb($memc, $item)
{
    var_dump($item);
}
?>

The above example will output something similar to:

array(3) {
  ["key"]=>
  string(4) "key1"
  ["value"]=>
  string(6) "value1"
  ["cas"]=>
  float(49)
}
array(3) {
  ["key"]=>
  string(4) "key3"
  ["value"]=>
  string(6) "value3"
  ["cas"]=>
  float(50)
}


Read-through cache callbacks

Read-through cache callbacks are invoked when an item cannot be retrieved from the server. The callback is passed the Memcached object, the requested key, and the by-reference value variable. The callback is responsible for setting the value and returning true or false. If the callback returns true, Memcached will store the populated value on the server and return it to the original calling function. Only Memcached::get() and Memcached::getByKey() support these callbacks, because the memcache protocol does not provide information on which keys were not found in the multi-key request.

Example #1 Read-through callback example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$profile_info = $m->get('user:'.$user_id, 'user_info_cb');

function user_info_cb($memc, $key, &$value)
{
    $user_id = substr($key, 5);
    /* lookup profile info in the DB */
    /* ... */
    $value = $profile_info;
    return true;
}
?>


Sessions support

Memcached provides a custom session handler that can be used to store user sessions in memcache. A completely separate memcached instance is used for that internally, so you can use a different server pool if necessary. The session keys are stored under the prefix memc.sess.key., so be aware of this if you use the same server pool for sessions and generic caching.

session.save_handler string

Set to memcached to enable sessions support.

session.save_path string

Defines a comma separated of hostname:port entries to use for session server pool, for example "sess1:11211, sess2:11211".


The Memcached class

(PECL memcached >= 0.1.0)

Introduction

Represents a connection to a set of memcached servers.

Class synopsis

Memcached {
public __construct ([ string $persistent_id ] )
public add ( string $key , mixed $value [, int $expiration ] ) : bool
public addByKey ( string $server_key , string $key , mixed $value [, int $expiration ] ) : bool
public addServer ( string $host , int $port [, int $weight = 0 ] ) : bool
public addServers ( array $servers ) : bool
public append ( string $key , string $value ) : bool
public appendByKey ( string $server_key , string $key , string $value ) : bool
public cas ( float $cas_token , string $key , mixed $value [, int $expiration ] ) : bool
public casByKey ( float $cas_token , string $server_key , string $key , mixed $value [, int $expiration ] ) : bool
public decrement ( string $key [, int $offset = 1 [, int $initial_value = 0 [, int $expiry = 0 ]]] ) : int
public decrementByKey ( string $server_key , string $key [, int $offset = 1 [, int $initial_value = 0 [, int $expiry = 0 ]]] ) : int
public delete ( string $key [, int $time = 0 ] ) : bool
public deleteByKey ( string $server_key , string $key [, int $time = 0 ] ) : bool
public deleteMulti ( array $keys [, int $time = 0 ] ) : array
public deleteMultiByKey ( string $server_key , array $keys [, int $time = 0 ] ) : bool
public fetch ( void ) : array
public fetchAll ( void ) : array
public flush ([ int $delay = 0 ] ) : bool
public get ( string $key [, callable $cache_cb [, int $$flags ]] ) : mixed
public getAllKeys ( void ) : array
public getByKey ( string $server_key , string $key [, callable $cache_cb [, int $flags ]] ) : mixed
public getDelayed ( array $keys [, bool $with_cas [, callable $value_cb ]] ) : bool
public getDelayedByKey ( string $server_key , array $keys [, bool $with_cas [, callable $value_cb ]] ) : bool
public getMulti ( array $keys [, int $flags ] ) : mixed
public getMultiByKey ( string $server_key , array $keys [, int $flags ] ) : array
public getOption ( int $option ) : mixed
public getResultCode ( void ) : int
public getResultMessage ( void ) : string
public getServerByKey ( string $server_key ) : array
public getServerList ( void ) : array
public getStats ( void ) : array
public getVersion ( void ) : array
public increment ( string $key [, int $offset = 1 [, int $initial_value = 0 [, int $expiry = 0 ]]] ) : int
public incrementByKey ( string $server_key , string $key [, int $offset = 1 [, int $initial_value = 0 [, int $expiry = 0 ]]] ) : int
public isPersistent ( void ) : bool
public isPristine ( void ) : bool
public prepend ( string $key , string $value ) : bool
public prependByKey ( string $server_key , string $key , string $value ) : bool
public quit ( void ) : bool
public replace ( string $key , mixed $value [, int $expiration ] ) : bool
public replaceByKey ( string $server_key , string $key , mixed $value [, int $expiration ] ) : bool
public resetServerList ( void ) : bool
public set ( string $key , mixed $value [, int $expiration ] ) : bool
public setByKey ( string $server_key , string $key , mixed $value [, int $expiration ] ) : bool
public setMulti ( array $items [, int $expiration ] ) : bool
public setMultiByKey ( string $server_key , array $items [, int $expiration ] ) : bool
public setOption ( int $option , mixed $value ) : bool
public setOptions ( array $options ) : bool
public setSaslAuthData ( string $username , string $password ) : void
public touch ( string $key , int $expiration ) : bool
public touchByKey ( string $server_key , string $key , int $expiration ) : bool
}

Table of Contents

  • Memcached::add — Add an item under a new key
  • Memcached::addByKey — Add an item under a new key on a specific server
  • Memcached::addServer — Add a server to the server pool
  • Memcached::addServers — Add multiple servers to the server pool
  • Memcached::append — Append data to an existing item
  • Memcached::appendByKey — Append data to an existing item on a specific server
  • Memcached::cas — Compare and swap an item
  • Memcached::casByKey — Compare and swap an item on a specific server
  • Memcached::__construct — Create a Memcached instance
  • Memcached::decrement — Decrement numeric item's value
  • Memcached::decrementByKey — Decrement numeric item's value, stored on a specific server
  • Memcached::delete — Delete an item
  • Memcached::deleteByKey — Delete an item from a specific server
  • Memcached::deleteMulti — Delete multiple items
  • Memcached::deleteMultiByKey — Delete multiple items from a specific server
  • Memcached::fetch — Fetch the next result
  • Memcached::fetchAll — Fetch all the remaining results
  • Memcached::flush — Invalidate all items in the cache
  • Memcached::get — Retrieve an item
  • Memcached::getAllKeys — Gets the keys stored on all the servers
  • Memcached::getByKey — Retrieve an item from a specific server
  • Memcached::getDelayed — Request multiple items
  • Memcached::getDelayedByKey — Request multiple items from a specific server
  • Memcached::getMulti — Retrieve multiple items
  • Memcached::getMultiByKey — Retrieve multiple items from a specific server
  • Memcached::getOption — Retrieve a Memcached option value
  • Memcached::getResultCode — Return the result code of the last operation
  • Memcached::getResultMessage — Return the message describing the result of the last operation
  • Memcached::getServerByKey — Map a key to a server
  • Memcached::getServerList — Get the list of the servers in the pool
  • Memcached::getStats — Get server pool statistics
  • Memcached::getVersion — Get server pool version info
  • Memcached::increment — Increment numeric item's value
  • Memcached::incrementByKey — Increment numeric item's value, stored on a specific server
  • Memcached::isPersistent — Check if a persitent connection to memcache is being used
  • Memcached::isPristine — Check if the instance was recently created
  • Memcached::prepend — Prepend data to an existing item
  • Memcached::prependByKey — Prepend data to an existing item on a specific server
  • Memcached::quit — Close any open connections
  • Memcached::replace — Replace the item under an existing key
  • Memcached::replaceByKey — Replace the item under an existing key on a specific server
  • Memcached::resetServerList — Clears all servers from the server list
  • Memcached::set — Store an item
  • Memcached::setByKey — Store an item on a specific server
  • Memcached::setMulti — Store multiple items
  • Memcached::setMultiByKey — Store multiple items on a specific server
  • Memcached::setOption — Set a Memcached option
  • Memcached::setOptions — Set Memcached options
  • Memcached::setSaslAuthData — Set the credentials to use for authentication
  • Memcached::touch — Set a new expiration on an item
  • Memcached::touchByKey — Set a new expiration on an item on a specific server


Add an item under a new key

  • « Memcached
  • Memcached::addByKey »
  • PHP Manual
  • Memcached
  • Add an item under a new key

Memcached::add

(PECL memcached >= 0.1.0)

Memcached::add — Add an item under a new key

Description

public Memcached::add ( string $key , mixed $value [, int $expiration ] ) : bool

Memcached::add() is similar to Memcached::set(), but the operation fails if the key already exists on the server.

Parameters

key

The key under which to store the value.

value

The value to store.

expiration

The expiration time, defaults to 0. See Expiration Times for more info.

Return Values

Returns TRUE on success or FALSE on failure. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key already exists.

See Also

  • Memcached::addByKey() - Add an item under a new key on a specific server
  • Memcached::set() - Store an item
  • Memcached::replace() - Replace the item under an existing key


Add an item under a new key on a specific server

  • « Memcached::add
  • Memcached::addServer »
  • PHP Manual
  • Memcached
  • Add an item under a new key on a specific server

Memcached::addByKey

(PECL memcached >= 0.1.0)

Memcached::addByKey — Add an item under a new key on a specific server

Description

public Memcached::addByKey ( string $server_key , string $key , mixed $value [, int $expiration ] ) : bool

Memcached::addByKey() is functionally equivalent to Memcached::add(), except that the free-form server_key can be used to map the key to a specific server. This is useful if you need to keep a bunch of related keys on a certain server.

Parameters

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

key

The key under which to store the value.

value

The value to store.

expiration

The expiration time, defaults to 0. See Expiration Times for more info.

Return Values

Returns TRUE on success or FALSE on failure. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key already exists.

See Also

  • Memcached::add() - Add an item under a new key
  • Memcached::set() - Store an item
  • Memcached::replace() - Replace the item under an existing key


Add a server to the server pool

  • « Memcached::addByKey
  • Memcached::addServers »
  • PHP Manual
  • Memcached
  • Add a server to the server pool

Memcached::addServer

(PECL memcached >= 0.1.0)

Memcached::addServer — Add a server to the server pool

Description

public Memcached::addServer ( string $host , int $port [, int $weight = 0 ] ) : bool

Memcached::addServer() adds the specified server to the server pool. No connection is established to the server at this time, but if you are using consistent key distribution option (via Memcached::DISTRIBUTION_CONSISTENT or Memcached::OPT_LIBKETAMA_COMPATIBLE), some of the internal data structures will have to be updated. Thus, if you need to add multiple servers, it is better to use Memcached::addServers() as the update then happens only once.

The same server may appear multiple times in the server pool, because no duplication checks are made. This is not advisable; instead, use the weight option to increase the selection weighting of this server.

Parameters

host

The hostname of the memcache server. If the hostname is invalid, data-related operations will set Memcached::RES_HOST_LOOKUP_FAILURE result code. As of version 2.0.0b1, this parameter may also specify the path of a unix socket filepath ex. /path/to/memcached.sock to use UNIX domain sockets, in this case port must also be set to 0.

port

The port on which memcache is running. Usually, this is 11211. As of version 2.0.0b1, set this parameter to 0 when using UNIX domain sockets.

weight

The weight of the server relative to the total weight of all the servers in the pool. This controls the probability of the server being selected for operations. This is used only with consistent distribution option and usually corresponds to the amount of memory available to memcache on that server.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Memcached::addServer() example

<?php
$m = new Memcached();

/* Add 2 servers, so that the second one
   is twice as likely to be selected. */
$m->addServer('mem1.domain.com', 11211, 33);
$m->addServer('mem2.domain.com', 11211, 67);
?>

See Also

  • Memcached::addServers() - Add multiple servers to the server pool
  • Memcached::resetServerList() - Clears all servers from the server list


Add multiple servers to the server pool

  • « Memcached::addServer
  • Memcached::append »
  • PHP Manual
  • Memcached
  • Add multiple servers to the server pool

Memcached::addServers

(PECL memcached >= 0.1.1)

Memcached::addServers — Add multiple servers to the server pool

Description

public Memcached::addServers ( array $servers ) : bool

Memcached::addServers() adds servers to the server pool. Each entry in servers is supposed to be an array containing hostname, port, and, optionally, weight of the server. No connection is established to the servers at this time.

The same server may appear multiple times in the server pool, because no duplication checks are made. This is not advisable; instead, use the weight option to increase the selection weighting of this server.

Parameters

array

Array of the servers to add to the pool.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Memcached::addServers() example

<?php
$m = new Memcached();

$servers = array(
    array('mem1.domain.com', 11211, 33),
    array('mem2.domain.com', 11211, 67)
);
$m->addServers($servers);
?>

See Also

  • Memcached::addServer() - Add a server to the server pool
  • Memcached::resetServerList() - Clears all servers from the server list


Append data to an existing item

  • « Memcached::addServers
  • Memcached::appendByKey »
  • PHP Manual
  • Memcached
  • Append data to an existing item

Memcached::append

(PECL memcached >= 0.1.0)

Memcached::append — Append data to an existing item

Description

public Memcached::append ( string $key , string $value ) : bool

Memcached::append() appends the given value string to the value of an existing item. The reason that value is forced to be a string is that appending mixed types is not well-defined.

Note:

If the Memcached::OPT_COMPRESSION is enabled, the operation will fail and a warning will be issued, because appending compressed data to a value that is potentially already compressed is not possible.

Parameters

key

The key under which to store the value.

value

The string to append.

Return Values

Returns TRUE on success or FALSE on failure. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key does not exist.

Examples

Example #1 Memcached::append() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);
$m->setOption(Memcached::OPT_COMPRESSION, false);

$m->set('foo', 'abc');
$m->append('foo', 'def');
var_dump($m->get('foo'));
?>

The above example will output:

string(6) "abcdef"

See Also

  • Memcached::appendByKey() - Append data to an existing item on a specific server
  • Memcached::prepend() - Prepend data to an existing item


Append data to an existing item on a specific server

  • « Memcached::append
  • Memcached::cas »
  • PHP Manual
  • Memcached
  • Append data to an existing item on a specific server

Memcached::appendByKey

(PECL memcached >= 0.1.0)

Memcached::appendByKey — Append data to an existing item on a specific server

Description

public Memcached::appendByKey ( string $server_key , string $key , string $value ) : bool

Memcached::appendByKey() is functionally equivalent to Memcached::append(), except that the free-form server_key can be used to map the key to a specific server.

Parameters

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

key

The key under which to store the value.

value

The string to append.

Return Values

Returns TRUE on success or FALSE on failure. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key does not exist.

See Also

  • Memcached::append() - Append data to an existing item
  • Memcached::prepend() - Prepend data to an existing item


Compare and swap an item

  • « Memcached::appendByKey
  • Memcached::casByKey »
  • PHP Manual
  • Memcached
  • Compare and swap an item

Memcached::cas

(PECL memcached >= 0.1.0)

Memcached::cas — Compare and swap an item

Description

public Memcached::cas ( float $cas_token , string $key , mixed $value [, int $expiration ] ) : bool

Memcached::cas() performs a "check and set" operation, so that the item will be stored only if no other client has updated it since it was last fetched by this client. The check is done via the cas_token parameter which is a unique 64-bit value assigned to the existing item by memcache. See the documentation for Memcached::get*() methods for how to obtain this token. Note that the token is represented as a double due to the limitations of PHP's integer space.

Parameters

cas_token

Unique value associated with the existing item. Generated by memcache.

key

The key under which to store the value.

value

The value to store.

expiration

The expiration time, defaults to 0. See Expiration Times for more info.

Return Values

Returns TRUE on success or FALSE on failure. The Memcached::getResultCode() will return Memcached::RES_DATA_EXISTS if the item you are trying to store has been modified since you last fetched it.

Examples

Example #1 Memcached::cas() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

do {
    /* fetch IP list and its token */
    $ips = $m->get('ip_block', null, $cas);
    /* if list doesn't exist yet, create it and do
       an atomic add which will fail if someone else already added it */
    if ($m->getResultCode() == Memcached::RES_NOTFOUND) {
        $ips = array($_SERVER['REMOTE_ADDR']);
        $m->add('ip_block', $ips);
    /* otherwise, add IP to the list and store via compare-and-swap
       with the token, which will fail if someone else updated the list */
    } else {
        $ips[] = $_SERVER['REMOTE_ADDR'];
        $m->cas($cas, 'ip_block', $ips);
    }
} while ($m->getResultCode() != Memcached::RES_SUCCESS);

?>

See Also

  • Memcached::casByKey() - Compare and swap an item on a specific server


Compare and swap an item on a specific server

  • « Memcached::cas
  • Memcached::__construct »
  • PHP Manual
  • Memcached
  • Compare and swap an item on a specific server

Memcached::casByKey

(PECL memcached >= 0.1.0)

Memcached::casByKey — Compare and swap an item on a specific server

Description

public Memcached::casByKey ( float $cas_token , string $server_key , string $key , mixed $value [, int $expiration ] ) : bool

Memcached::casByKey() is functionally equivalent to Memcached::cas(), except that the free-form server_key can be used to map the key to a specific server. This is useful if you need to keep a bunch of related keys on a certain server.

Parameters

cas_token

Unique value associated with the existing item. Generated by memcache.

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

key

The key under which to store the value.

value

The value to store.

expiration

The expiration time, defaults to 0. See Expiration Times for more info.

Return Values

Returns TRUE on success or FALSE on failure. The Memcached::getResultCode() will return Memcached::RES_DATA_EXISTS if the item you are trying to store has been modified since you last fetched it.

See Also

  • Memcached::cas() - Compare and swap an item


Create a Memcached instance

  • « Memcached::casByKey
  • Memcached::decrement »
  • PHP Manual
  • Memcached
  • Create a Memcached instance

Memcached::__construct

(PECL memcached >= 0.1.0)

Memcached::__construct — Create a Memcached instance

Description

public Memcached::__construct ([ string $persistent_id ] )

Creates a Memcached instance representing the connection to the memcache servers.

Parameters

persistent_id

By default the Memcached instances are destroyed at the end of the request. To create an instance that persists between requests, use persistent_id to specify a unique ID for the instance. All instances created with the same persistent_id will share the same connection.

Return Values

A Memcached object.

Examples

Example #1 Creating a Memcached object

<?php
/* Create a regular instance */
$m = new Memcached();
echo get_class($m);

/* Create a persistent instance */
$m2 = new Memcached('story_pool');
$m3 = new Memcached('story_pool');

/* now $m2 and $m3 share the same connection */
?>


Decrement numeric item's value

  • « Memcached::__construct
  • Memcached::decrementByKey »
  • PHP Manual
  • Memcached
  • Decrement numeric item's value

Memcached::decrement

(PECL memcached >= 0.1.0)

Memcached::decrement — Decrement numeric item's value

Description

public Memcached::decrement ( string $key [, int $offset = 1 [, int $initial_value = 0 [, int $expiry = 0 ]]] ) : int

Memcached::decrement() decrements a numeric item's value by the specified offset. If the item's value is not numeric, an error will result. If the operation would decrease the value below 0, the new value will be 0. Memcached::decrement() will set the item to the initial_value parameter if the key doesn't exist.

Parameters

key

The key of the item to decrement.

offset

The amount by which to decrement the item's value.

initial_value

The value to set the item to if it doesn't currently exist.

expiry

The expiry time to set on the item.

Return Values

Returns item's new value on success or FALSE on failure.

Examples

Example #1 Memcached::decrement() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('counter', 5);
$n = $m->decrement('counter');
var_dump($n);

$n = $m->decrement('counter', 10);
var_dump($n);

var_dump($m->get('counter'));

$m->set('counter', 'abc');
$n = $m->increment('counter');
// ^ will fail due to item value not being numeric
var_dump($n);
?>

The above example will output:

int(4)
int(0)
int(0)
bool(false)

See Also

  • Memcached::increment() - Increment numeric item's value
  • Memcached::incrementByKey() - Increment numeric item's value, stored on a specific server
  • Memcached::decrementByKey() - Decrement numeric item's value, stored on a specific server


Decrement numeric item's value, stored on a specific server

  • « Memcached::decrement
  • Memcached::delete »
  • PHP Manual
  • Memcached
  • Decrement numeric item's value, stored on a specific server

Memcached::decrementByKey

(PECL memcached >= 2.0.0)

Memcached::decrementByKey — Decrement numeric item's value, stored on a specific server

Description

public Memcached::decrementByKey ( string $server_key , string $key [, int $offset = 1 [, int $initial_value = 0 [, int $expiry = 0 ]]] ) : int

Memcached::decrementByKey() decrements a numeric item's value by the specified offset. If the item's value is not numeric, an error will result. If the operation would decrease the value below 0, the new value will be 0. Memcached::decrementByKey() will set the item to the initial_value parameter if the key doesn't exist.

Parameters

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

key

The key of the item to decrement.

offset

The amount by which to decrement the item's value.

initial_value

The value to set the item to if it doesn't currently exist.

expiry

The expiry time to set on the item.

Return Values

Returns item's new value on success or FALSE on failure.

See Also

  • Memcached::decrement() - Decrement numeric item's value
  • Memcached::increment() - Increment numeric item's value
  • Memcached::incrementByKey() - Increment numeric item's value, stored on a specific server


Delete an item

  • « Memcached::decrementByKey
  • Memcached::deleteByKey »
  • PHP Manual
  • Memcached
  • Delete an item

Memcached::delete

(PECL memcached >= 0.1.0)

Memcached::delete — Delete an item

Description

public Memcached::delete ( string $key [, int $time = 0 ] ) : bool

Memcached::delete() deletes the key from the server. The time parameter is the amount of time in seconds (or Unix time until which) the client wishes the server to refuse add and replace commands for this key. For this amount of time, the item is put into a delete queue, which means that it won't possible to retrieve it by the get command, but add and replace command with this key will also fail (the set command will succeed, however). After the time passes, the item is finally deleted from server memory. The parameter time defaults to 0 (which means that the item will be deleted immediately and further storage commands with this key will succeed).

Parameters

key

The key to be deleted.

time

The amount of time the server will wait to delete the item.

Return Values

Returns TRUE on success or FALSE on failure. The Memcached::getResultCode() will return Memcached::RES_NOTFOUND if the key does not exist.

Examples

Example #1 Memcached::delete() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->delete('key1');
?>

See Also

  • Memcached::deleteByKey() - Delete an item from a specific server
  • Memcached::deleteMulti() - Delete multiple items


Delete an item from a specific server

  • « Memcached::delete
  • Memcached::deleteMulti »
  • PHP Manual
  • Memcached
  • Delete an item from a specific server

Memcached::deleteByKey

(PECL memcached >= 0.1.0)

Memcached::deleteByKey — Delete an item from a specific server

Description

public Memcached::deleteByKey ( string $server_key , string $key [, int $time = 0 ] ) : bool

Memcached::deleteByKey() is functionally equivalent to Memcached::delete(), except that the free-form server_key can be used to map the key to a specific server.

Parameters

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

key

The key to be deleted.

time

The amount of time the server will wait to delete the item.

Return Values

Returns TRUE on success or FALSE on failure. The Memcached::getResultCode() will return Memcached::RES_NOTFOUND if the key does not exist.

See Also

  • Memcached::delete() - Delete an item
  • Memcached::deleteMulti() - Delete multiple items
  • Memcached::deleteMultiByKey() - Delete multiple items from a specific server


Delete multiple items

  • « Memcached::deleteByKey
  • Memcached::deleteMultiByKey »
  • PHP Manual
  • Memcached
  • Delete multiple items

Memcached::deleteMulti

(PECL memcached >= 2.0.0)

Memcached::deleteMulti — Delete multiple items

Description

public Memcached::deleteMulti ( array $keys [, int $time = 0 ] ) : array

Memcached::deleteMulti() deletes the array of keys from the server. The time parameter is the amount of time in seconds (or Unix time until which) the client wishes the server to refuse add and replace commands for these keys. For this amount of time, the item is put into a delete queue, which means that it won't be possible to retrieve it by the get command, but add and replace command with these keys will also fail (the set command will succeed, however). After the time passes, the item is finally deleted from server memory. The parameter time defaults to 0 (which means that the item will be deleted immediately and further storage commands with these keys will succeed).

Parameters

keys

The keys to be deleted.

time

The amount of time the server will wait to delete the items.

Return Values

Returns array indexed by keys and where values are indicating whether operation succeeded or not. The Memcached::getResultCode() will return Memcached::RES_NOTFOUND if the key does not exist.

See Also

  • Memcached::delete() - Delete an item
  • Memcached::deleteByKey() - Delete an item from a specific server
  • Memcached::deleteMultiByKey() - Delete multiple items from a specific server


Delete multiple items from a specific server

  • « Memcached::deleteMulti
  • Memcached::fetch »
  • PHP Manual
  • Memcached
  • Delete multiple items from a specific server

Memcached::deleteMultiByKey

(PECL memcached >= 2.0.0)

Memcached::deleteMultiByKey — Delete multiple items from a specific server

Description

public Memcached::deleteMultiByKey ( string $server_key , array $keys [, int $time = 0 ] ) : bool

Memcached::deleteMultiByKey() is functionally equivalent to Memcached::deleteMulti(), except that the free-form server_key can be used to map the keys to a specific server.

Parameters

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

keys

The keys to be deleted.

time

The amount of time the server will wait to delete the items.

Return Values

Returns TRUE on success or FALSE on failure. The Memcached::getResultCode() will return Memcached::RES_NOTFOUND if the key does not exist.

See Also

  • Memcached::delete() - Delete an item
  • Memcached::deleteByKey() - Delete an item from a specific server
  • Memcached::deleteMulti() - Delete multiple items


Fetch the next result

  • « Memcached::deleteMultiByKey
  • Memcached::fetchAll »
  • PHP Manual
  • Memcached
  • Fetch the next result

Memcached::fetch

(PECL memcached >= 0.1.0)

Memcached::fetch — Fetch the next result

Description

public Memcached::fetch ( void ) : array

Memcached::fetch() retrieves the next result from the last request.

Parameters

This function has no parameters.

Return Values

Returns the next result or FALSE otherwise. The Memcached::getResultCode() will return Memcached::RES_END if result set is exhausted.

Examples

Example #1 Memcached::fetch() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('int', 99);
$m->set('string', 'a simple string');
$m->set('array', array(11, 12));

$m->getDelayed(array('int', 'array'), true);
while ($result = $m->fetch()) {
    var_dump($result);
}
?>

The above example will output something similar to:

array(3) {
  ["key"]=>
  string(3) "int"
  "value"]=>
  int(99)
  ["cas"]=>
  float(2363)
}
array(3) {
  ["key"]=>
  string(5) "array"
  ["value"]=>
  array(2) {
    [0]=>
    int(11)
    [1]=>
    int(12)
  }
  ["cas"]=>
  float(2365)
}

See Also

  • Memcached::fetchAll() - Fetch all the remaining results
  • Memcached::getDelayed() - Request multiple items


Fetch all the remaining results

  • « Memcached::fetch
  • Memcached::flush »
  • PHP Manual
  • Memcached
  • Fetch all the remaining results

Memcached::fetchAll

(PECL memcached >= 0.1.0)

Memcached::fetchAll — Fetch all the remaining results

Description

public Memcached::fetchAll ( void ) : array

Memcached::fetchAll() retrieves all the remaining results from the last request.

Parameters

This function has no parameters.

Return Values

Returns the results or FALSE on failure. Use Memcached::getResultCode() if necessary.

Examples

Example #1 Memcached::getDelayed() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('int', 99);
$m->set('string', 'a simple string');
$m->set('array', array(11, 12));

$m->getDelayed(array('int', 'array'), true);
var_dump($m->fetchAll());
?>

The above example will output:

array(2) {
  [0]=>
  array(3) {
    ["key"]=>
    string(3) "int"
    ["value"]=>
    int(99)
    ["cas"]=>
    float(2363)
  }
  [1]=>
  array(3) {
    ["key"]=>
    string(5) "array"
    ["value"]=>
    array(2) {
      [0]=>
      int(11)
      [1]=>
      int(12)
    }
    ["cas"]=>
    float(2365)
  }
}

See Also

  • Memcached::fetch() - Fetch the next result
  • Memcached::getDelayed() - Request multiple items


Invalidate all items in the cache

  • « Memcached::fetchAll
  • Memcached::get »
  • PHP Manual
  • Memcached
  • Invalidate all items in the cache

Memcached::flush

(PECL memcached >= 0.1.0)

Memcached::flush — Invalidate all items in the cache

Description

public Memcached::flush ([ int $delay = 0 ] ) : bool

Memcached::flush() invalidates all existing cache items immediately (by default) or after the delay specified. After invalidation none of the items will be returned in response to a retrieval command (unless it's stored again under the same key after Memcached::flush() has invalidated the items). The flush does not actually free all the memory taken up by the existing items; that will happen gradually as new items are stored.

Parameters

delay

Number of seconds to wait before invalidating the items.

Return Values

Returns TRUE on success or FALSE on failure. Use Memcached::getResultCode() if necessary.

Examples

Example #1 Memcached::flush() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

/* flush all items in 10 seconds */
$m->flush(10);
?>


Retrieve an item

  • « Memcached::flush
  • Memcached::getAllKeys »
  • PHP Manual
  • Memcached
  • Retrieve an item

Memcached::get

(PECL memcached >= 0.1.0)

Memcached::get — Retrieve an item

Description

public Memcached::get ( string $key [, callable $cache_cb [, int $$flags ]] ) : mixed

Memcached::get() returns the item that was previously stored under the key. If the item is found and the flags is given Memcached::GET_EXTENDED, it will also return the CAS token value for the item. See Memcached::cas() for how to use CAS tokens. Read-through caching callback may be specified via cache_cb parameter.

Parameters

key

The key of the item to retrieve.

cache_cb

Read-through caching callback or NULL.

flags

Flags to control the returned result. When Memcached::GET_EXTENDED is given, the function will also return the CAS token.

Return Values

Returns the value stored in the cache or FALSE otherwise. If the flags is set to Memcached::GET_EXTENDED, an array containing the value and the CAS token is returned instead of only the value. The Memcached::getResultCode() will return Memcached::RES_NOTFOUND if the key does not exist.

Examples

Example #1 Memcached::get() example #1

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('foo', 100);
var_dump($m->get('foo'));
?>

The above example will output:

int(100)

Example #2 Memcached::get() example #2

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

if (!($ip = $m->get('ip_block'))) {
    if ($m->getResultCode() == Memcached::RES_NOTFOUND) {
        $ip = array();
        $m->set('ip_block', $ip);
    } else {
        /* log error */
        /* ...       */
    }
}
?>

Changelog

Version | Description
3.0.0 | The &cas_token parameter was removed. Instead flags was added and when it is given the value of Memcached::GET_EXTENDED it will ensure the CAS token to be fetched.

See Also

  • Memcached::getByKey() - Retrieve an item from a specific server
  • Memcached::getMulti() - Retrieve multiple items
  • Memcached::getDelayed() - Request multiple items


Gets the keys stored on all the servers

  • « Memcached::get
  • Memcached::getByKey »
  • PHP Manual
  • Memcached
  • Gets the keys stored on all the servers

Memcached::getAllKeys

(PECL memcached >= 2.0.0)

Memcached::getAllKeys — Gets the keys stored on all the servers

Description

public Memcached::getAllKeys ( void ) : array

Memcached::getAllKeys() queries each memcache server and retrieves an array of all keys stored on them at that point in time. This is not an atomic operation, so it isn't a truly consistent snapshot of the keys at point in time. As memcache doesn't guarantee to return all keys you also cannot assume that all keys have been returned.

Parameters

This function has no parameters.

Return Values

Returns the keys stored on all the servers on success or FALSE on failure.


Retrieve an item from a specific server

  • « Memcached::getAllKeys
  • Memcached::getDelayed »
  • PHP Manual
  • Memcached
  • Retrieve an item from a specific server

Memcached::getByKey

(PECL memcached >= 0.1.0)

Memcached::getByKey — Retrieve an item from a specific server

Description

public Memcached::getByKey ( string $server_key , string $key [, callable $cache_cb [, int $flags ]] ) : mixed

Memcached::getByKey() is functionally equivalent to Memcached::get(), except that the free-form server_key can be used to map the key to a specific server.

Parameters

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

key

The key of the item to fetch.

cache_cb

Read-through caching callback or NULL

flags

Flags to control the returned result. When value of Memcached::GET_EXTENDED is given will return the CAS token.

Return Values

Returns the value stored in the cache or FALSE otherwise. The Memcached::getResultCode() will return Memcached::RES_NOTFOUND if the key does not exist.

Changelog

Version | Description
3.0.0 | The &cas_token parameter was removed. Instead flags was added and when it is given the value of Memcached::GET_EXTENDED it will ensure the CAS token to be fetched.

See Also

  • Memcached::get() - Retrieve an item
  • Memcached::getMulti() - Retrieve multiple items
  • Memcached::getDelayed() - Request multiple items


Request multiple items

  • « Memcached::getByKey
  • Memcached::getDelayedByKey »
  • PHP Manual
  • Memcached
  • Request multiple items

Memcached::getDelayed

(PECL memcached >= 0.1.0)

Memcached::getDelayed — Request multiple items

Description

public Memcached::getDelayed ( array $keys [, bool $with_cas [, callable $value_cb ]] ) : bool

Memcached::getDelayed() issues a request to memcache for multiple items the keys of which are specified in the keys array. The method does not wait for response and returns right away. When you are ready to collect the items, call either Memcached::fetch() or Memcached::fetchAll(). If with_cas is true, the CAS token values will also be requested.

Instead of fetching the results explicitly, you can specify a result callback via value_cb parameter.

Parameters

keys

Array of keys to request.

with_cas

Whether to request CAS token values also.

value_cb

The result callback or NULL.

Return Values

Returns TRUE on success or FALSE on failure. Use Memcached::getResultCode() if necessary.

Examples

Example #1 Memcached::getDelayed() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('int', 99);
$m->set('string', 'a simple string');
$m->set('array', array(11, 12));

$m->getDelayed(array('int', 'array'), true);
var_dump($m->fetchAll());
?>

The above example will output:

array(2) {
  [0]=>
  array(3) {
    ["key"]=>
    string(3) "int"
    ["value"]=>
    int(99)
    ["cas"]=>
    float(2363)
  }
  [1]=>
  array(3) {
    ["key"]=>
    string(5) "array"
    ["value"]=>
    array(2) {
      [0]=>
      int(11)
      [1]=>
      int(12)
    }
    ["cas"]=>
    float(2365)
  }
}

See Also

  • Memcached::getDelayedByKey() - Request multiple items from a specific server
  • Memcached::fetch() - Fetch the next result
  • Memcached::fetchAll() - Fetch all the remaining results


Request multiple items from a specific server

  • « Memcached::getDelayed
  • Memcached::getMulti »
  • PHP Manual
  • Memcached
  • Request multiple items from a specific server

Memcached::getDelayedByKey

(PECL memcached >= 0.1.0)

Memcached::getDelayedByKey — Request multiple items from a specific server

Description

public Memcached::getDelayedByKey ( string $server_key , array $keys [, bool $with_cas [, callable $value_cb ]] ) : bool

Memcached::getDelayedByKey() is functionally equivalent to Memcached::getDelayed(), except that the free-form server_key can be used to map the keys to a specific server.

Parameters

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

keys

Array of keys to request.

with_cas

Whether to request CAS token values also.

value_cb

The result callback or NULL.

Return Values

Returns TRUE on success or FALSE on failure. Use Memcached::getResultCode() if necessary.

See Also

  • Memcached::getDelayed() - Request multiple items
  • Memcached::fetch() - Fetch the next result
  • Memcached::fetchAll() - Fetch all the remaining results


Retrieve multiple items

  • « Memcached::getDelayedByKey
  • Memcached::getMultiByKey »
  • PHP Manual
  • Memcached
  • Retrieve multiple items

Memcached::getMulti

(PECL memcached >= 0.1.0)

Memcached::getMulti — Retrieve multiple items

Description

public Memcached::getMulti ( array $keys [, int $flags ] ) : mixed

Memcached::getMulti() is similar to Memcached::get(), but instead of a single key item, it retrieves multiple items the keys of which are specified in the keys array.

Note:

Before v3.0 a second argument &cas_tokens was in use. It was filled with the CAS token values for the found items. The &cas_tokens parameter was removed in v3.0 of the extension. It was replaced with a new flag Memcached::GET_EXTENDED that needs is to be used as the value for flags.

The flags parameter can be used to specify additional options for Memcached::getMulti(). Memcached::GET_PRESERVE_ORDER ensures that the keys are returned in the same order as they were requested in. Memcached::GET_EXTENDED ensures that the CAS tokens will be fetched too.

Parameters

keys

Array of keys to retrieve.

flags

The flags for the get operation.

Return Values

Returns the array of found items or FALSE on failure. Use Memcached::getResultCode() if necessary.

Examples

Example #1 Memcached::getMulti() example for Memcached v3

<?php
// Valid for v3 of the extension

$m = new Memcached();
$m->addServer('localhost', 11211);

$items = array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3'
);
$m->setMulti($items);
$result = $m->getMulti(array('key1', 'key3', 'badkey'));
var_dump($result);
?>

The above example will output something similar to:

array(2) {
  ["key1"]=>
  string(6) "value1"
  ["key3"]=>
  string(6) "value3"
}

Example #2 Memcached::getMulti() example for Memcached v1 and v2

<?php
// Valid for v1 and v2 of the extension

$m = new Memcached();
$m->addServer('localhost', 11211);

$items = array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3'
);
$m->setMulti($items);
$result = $m->getMulti(array('key1', 'key3', 'badkey'), $cas);
var_dump($result, $cas);
?>

The above example will output something similar to:

array(2) {
  ["key1"]=>
  string(6) "value1"
  ["key3"]=>
  string(6) "value3"
}
array(2) {
  ["key1"]=>
  float(2360)
  ["key3"]=>
  float(2362)
}

Example #3 Memcached::GET_PRESERVE_ORDER example for Memcached v3

<?php
// Valid for v3 of the extension

$m = new Memcached();
$m->addServer('localhost', 11211);

$data = array(
    'foo' => 'foo-data',
    'bar' => 'bar-data',
    'baz' => 'baz-data',
    'lol' => 'lol-data',
    'kek' => 'kek-data',
);

$m->setMulti($data, 3600);

$keys = array_keys($data);
$keys[] = 'zoo';
$got = $m->getMulti($keys, Memcached::GET_PRESERVE_ORDER);

foreach ($got as $k => $v) {
    echo "$k $v\n";
}
?>

The above example will output something similar to:

foo foo-data
bar bar-data
baz baz-data
lol lol-data
kek kek-data
zoo

Example #4 Memcached::GET_PRESERVE_ORDER example for Memcached v1 and v2

<?php
// Valid for v1 and v2 of the extension

$m = new Memcached();
$m->addServer('localhost', 11211);

$data = array(
    'foo' => 'foo-data',
    'bar' => 'bar-data',
    'baz' => 'baz-data',
    'lol' => 'lol-data',
    'kek' => 'kek-data',
);

$m->setMulti($data, 3600);

$null = null;
$keys = array_keys($data);
$keys[] = 'zoo';
$got = $m->getMulti($keys, $null, Memcached::GET_PRESERVE_ORDER);

foreach ($got as $k => $v) {
    echo "$k $v\n";
}
?>

The above example will output something similar to:

foo foo-data
bar bar-data
baz baz-data
lol lol-data
kek kek-data
zoo

Changelog

Version | Description
3.0.0 | The &cas_tokens parameter was removed. The Memcached::GET_EXTENDED was added and when passed as a flag it ensures the CAS tokens to be fetched.

See Also

  • Memcached::getMultiByKey() - Retrieve multiple items from a specific server
  • Memcached::get() - Retrieve an item
  • Memcached::getDelayed() - Request multiple items


Retrieve multiple items from a specific server

  • « Memcached::getMulti
  • Memcached::getOption »
  • PHP Manual
  • Memcached
  • Retrieve multiple items from a specific server

Memcached::getMultiByKey

(PECL memcached >= 0.1.0)

Memcached::getMultiByKey — Retrieve multiple items from a specific server

Description

public Memcached::getMultiByKey ( string $server_key , array $keys [, int $flags ] ) : array

Memcached::getMultiByKey() is functionally equivalent to Memcached::getMulti(), except that the free-form server_key can be used to map the keys to a specific server.

Parameters

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

keys

Array of keys to retrieve.

flags

The flags for the get operation.

Return Values

Returns the array of found items or FALSE on failure. Use Memcached::getResultCode() if necessary.

Changelog

Version | Description
3.0.0 | The &cas_tokens parameter was removed. The Memcached::GET_EXTENDED was added and when passed as a flag it ensures the CAS tokens to be fetched.

See Also

  • Memcached::getMulti() - Retrieve multiple items
  • Memcached::get() - Retrieve an item
  • Memcached::getDelayed() - Request multiple items


Retrieve a Memcached option value

  • « Memcached::getMultiByKey
  • Memcached::getResultCode »
  • PHP Manual
  • Memcached
  • Retrieve a Memcached option value

Memcached::getOption

(PECL memcached >= 0.1.0)

Memcached::getOption — Retrieve a Memcached option value

Description

public Memcached::getOption ( int $option ) : mixed

This method returns the value of a Memcached option. Some options correspond to the ones defined by libmemcached, and some are specific to the extension. See Memcached Constants for more information.

Parameters

option

One of the Memcached::OPT_* constants.

Return Values

Returns the value of the requested option, or FALSE on error.

Examples

Example #1 Retrieving Memcached options

<?php
$m = new Memcached();
var_dump($m->getOption(Memcached::OPT_COMPRESSION));
var_dump($m->getOption(Memcached::OPT_POLL_TIMEOUT));
?>

The above example will output something similar to:

bool(true)
int(1000)

See Also

  • Memcached::getOption()
  • Memcached::setOption() - Set a Memcached option
  • Memcached Constants


Return the result code of the last operation

  • « Memcached::getOption
  • Memcached::getResultMessage »
  • PHP Manual
  • Memcached
  • Return the result code of the last operation

Memcached::getResultCode

(PECL memcached >= 0.1.0)

Memcached::getResultCode — Return the result code of the last operation

Description

public Memcached::getResultCode ( void ) : int

Memcached::getResultCode() returns one of the Memcached::RES_* constants that is the result of the last executed Memcached method.

Parameters

This function has no parameters.

Return Values

Result code of the last Memcached operation.

Examples

Example #1 Memcached::getResultCode() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->add('foo', 'bar');
if ($m->getResultCode() == Memcached::RES_NOTSTORED) {
    /* ... */
}
?>


Return the message describing the result of the last operation

  • « Memcached::getResultCode
  • Memcached::getServerByKey »
  • PHP Manual
  • Memcached
  • Return the message describing the result of the last operation

Memcached::getResultMessage

(PECL memcached >= 1.0.0)

Memcached::getResultMessage — Return the message describing the result of the last operation

Description

public Memcached::getResultMessage ( void ) : string

Memcached::getResultMessage() returns a string that describes the result code of the last executed Memcached method.

Parameters

This function has no parameters.

Return Values

Message describing the result of the last Memcached operation.

Examples

Example #1 Memcached::getResultMessage() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->add('foo', 'bar'); // first time should succeed
$m->add('foo', 'bar');
echo $m->getResultMessage(),"\n";
?>

The above example will output:

NOT STORED


Map a key to a server

  • « Memcached::getResultMessage
  • Memcached::getServerList »
  • PHP Manual
  • Memcached
  • Map a key to a server

Memcached::getServerByKey

(PECL memcached >= 0.1.0)

Memcached::getServerByKey — Map a key to a server

Description

public Memcached::getServerByKey ( string $server_key ) : array

Memcached::getServerByKey() returns the server that would be selected by a particular server_key in all the Memcached::*ByKey() operations.

Parameters

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

Return Values

Returns an array containing three keys of host, port, and weight on success or FALSE on failure. Use Memcached::getResultCode() if necessary.

Examples

Example #1 Memcached::getServerByKey() example

<?php
$m = new Memcached();
$m->addServers(array(
    array('mem1.domain.com', 11211, 40),
    array('mem2.domain.com', 11211, 40),
    array('mem3.domain.com', 11211, 20),
));

$m->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);

var_dump($m->getServerByKey('user'));
var_dump($m->getServerByKey('log'));
var_dump($m->getServerByKey('ip'));
?>

The above example will output something similar to:

array(3) {
  ["host"]=>
  string(15) "mem3.domain.com"
  ["port"]=>
  int(11211)
  ["weight"]=>
  int(20)
}
array(3) {
  ["host"]=>
  string(15) "mem2.domain.com"
  ["port"]=>
  int(11211)
  ["weight"]=>
  int(40)
}
array(3) {
  ["host"]=>
  string(15) "mem2.domain.com"
  ["port"]=>
  int(11211)
  ["weight"]=>
  int(40)
}


Get the list of the servers in the pool

  • « Memcached::getServerByKey
  • Memcached::getStats »
  • PHP Manual
  • Memcached
  • Get the list of the servers in the pool

Memcached::getServerList

(PECL memcached >= 0.1.0)

Memcached::getServerList — Get the list of the servers in the pool

Description

public Memcached::getServerList ( void ) : array

Memcached::getServerList() returns the list of all servers that are in its server pool.

Parameters

This function has no parameters.

Return Values

The list of all servers in the server pool.

Examples

Example #1 Memcached::getServerList() example

<?php
$m = new Memcached();
$m->addServers(array(
    array('mem1.domain.com', 11211, 20),
    array('mem2.domain.com', 11311, 80),
));
var_dump($m->getServerList());
?>

The above example will output:

array(2) {
  [0]=>
  array(3) {
    ["host"]=>
    string(15) "mem1.domain.com"
    ["port"]=>
    int(11211)
    ["weight"]=>
    int(20)
  }
  [1]=>
  array(3) {
    ["host"]=>
    string(15) "mem2.domain.com"
    ["port"]=>
    int(11311)
    ["weight"]=>
    int(80)
  }
}


Get server pool statistics

  • « Memcached::getServerList
  • Memcached::getVersion »
  • PHP Manual
  • Memcached
  • Get server pool statistics

Memcached::getStats

(PECL memcached >= 0.1.0)

Memcached::getStats — Get server pool statistics

Description

public Memcached::getStats ( void ) : array

Memcached::getStats() returns an array containing the state of all available memcache servers. See » memcache protocol specification for details on these statistics.

Parameters

This function has no parameters.

Return Values

Array of server statistics, one entry per server.

Examples

Example #1 Memcached::getStats() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

print_r($m->getStats());
?>

The above example will output something similar to:

Array
(
    [localhost:11211] => Array
        (
            [pid] => 4933
            [uptime] => 786123
            [threads] => 1
            [time] => 1233868010
            [pointer_size] => 32
            [rusage_user_seconds] => 0
            [rusage_user_microseconds] => 140000
            [rusage_system_seconds] => 23
            [rusage_system_microseconds] => 210000
            [curr_items] => 145
            [total_items] => 2374
            [limit_maxbytes] => 67108864
            [curr_connections] => 2
            [total_connections] => 151
            [connection_structures] => 3
            [bytes] => 20345
            [cmd_get] => 213343
            [cmd_set] => 2381
            [get_hits] => 204223
            [get_misses] => 9120
            [evictions] => 0
            [bytes_read] => 9092476
            [bytes_written] => 15420512
            [version] => 1.2.6
        )

)


Get server pool version info

  • « Memcached::getStats
  • Memcached::increment »
  • PHP Manual
  • Memcached
  • Get server pool version info

Memcached::getVersion

(PECL memcached >= 0.1.5)

Memcached::getVersion — Get server pool version info

Description

public Memcached::getVersion ( void ) : array

Memcached::getVersion() returns an array containing the version info for all available memcache servers.

Parameters

This function has no parameters.

Return Values

Array of server versions, one entry per server.

Examples

Example #1 Memcached::getVersion() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

print_r($m->getVersion());
?>

The above example will output something similar to:

Array
(
    [localhost:11211] => 1.2.6
)


Increment numeric item's value

  • « Memcached::getVersion
  • Memcached::incrementByKey »
  • PHP Manual
  • Memcached
  • Increment numeric item's value

Memcached::increment

(PECL memcached >= 0.1.0)

Memcached::increment — Increment numeric item's value

Description

public Memcached::increment ( string $key [, int $offset = 1 [, int $initial_value = 0 [, int $expiry = 0 ]]] ) : int

Memcached::increment() increments a numeric item's value by the specified offset. If the item's value is not numeric, an error will result. Memcached::increment() will set the item to the initial_value parameter if the key doesn't exist.

Parameters

key

The key of the item to increment.

offset

The amount by which to increment the item's value.

initial_value

The value to set the item to if it doesn't currently exist.

expiry

The expiry time to set on the item.

Return Values

Returns new item's value on success or FALSE on failure.

Examples

Example #1 Memcached::increment() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('counter', 0);
$m->increment('counter');
$n = $m->increment('counter', 10);
var_dump($n);

$m->set('counter', 'abc');
$n = $m->increment('counter');
// ^ will fail due to item value not being numeric
var_dump($n);
?>

The above example will output:

int(11)
bool(false)

See Also

  • Memcached::decrement() - Decrement numeric item's value
  • Memcached::decrementByKey() - Decrement numeric item's value, stored on a specific server
  • Memcached::incrementByKey() - Increment numeric item's value, stored on a specific server


Increment numeric item's value, stored on a specific server

  • « Memcached::increment
  • Memcached::isPersistent »
  • PHP Manual
  • Memcached
  • Increment numeric item's value, stored on a specific server

Memcached::incrementByKey

(PECL memcached >= 2.0.0)

Memcached::incrementByKey — Increment numeric item's value, stored on a specific server

Description

public Memcached::incrementByKey ( string $server_key , string $key [, int $offset = 1 [, int $initial_value = 0 [, int $expiry = 0 ]]] ) : int

Memcached::incrementByKey() increments a numeric item's value by the specified offset. If the item's value is not numeric, an error will result. Memcached::incrementByKey() will set the item to the initial_value parameter if the key doesn't exist.

Parameters

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

key

The key of the item to increment.

offset

The amount by which to increment the item's value.

initial_value

The value to set the item to if it doesn't currently exist.

expiry

The expiry time to set on the item.

Return Values

Returns new item's value on success or FALSE on failure.

See Also

  • Memcached::decrement() - Decrement numeric item's value
  • Memcached::decrementByKey() - Decrement numeric item's value, stored on a specific server
  • Memcached::increment() - Increment numeric item's value


Check if a persitent connection to memcache is being used

  • « Memcached::incrementByKey
  • Memcached::isPristine »
  • PHP Manual
  • Memcached
  • Check if a persitent connection to memcache is being used

Memcached::isPersistent

(PECL memcached >= 2.0.0)

Memcached::isPersistent — Check if a persitent connection to memcache is being used

Description

public Memcached::isPersistent ( void ) : bool

Memcached::isPersistent() checks if the connections to the memcache servers are persistent connections.

Parameters

This function has no parameters.

Return Values

Returns true if Memcache instance uses a persistent connection, false otherwise.

See Also

  • Memcached::isPristine() - Check if the instance was recently created


Check if the instance was recently created

  • « Memcached::isPersistent
  • Memcached::prepend »
  • PHP Manual
  • Memcached
  • Check if the instance was recently created

Memcached::isPristine

(PECL memcached >= 2.0.0)

Memcached::isPristine — Check if the instance was recently created

Description

public Memcached::isPristine ( void ) : bool

Memcached::isPristine() checks if the Memcache instance was recently created.

Parameters

This function has no parameters.

Return Values

Returns the true if instance is recently created, false otherwise.

See Also

  • Memcached::isPersistent() - Check if a persitent connection to memcache is being used


Prepend data to an existing item

  • « Memcached::isPristine
  • Memcached::prependByKey »
  • PHP Manual
  • Memcached
  • Prepend data to an existing item

Memcached::prepend

(PECL memcached >= 0.1.0)

Memcached::prepend — Prepend data to an existing item

Description

public Memcached::prepend ( string $key , string $value ) : bool

Memcached::prepend() prepends the given value string to the value of an existing item. The reason that value is forced to be a string is that prepending mixed types is not well-defined.

Note:

If the Memcached::OPT_COMPRESSION is enabled, the operation will fail and a warning will be issued, because prepending compressed data to a value that is potentially already compressed is not possible.

Parameters

key

The key of the item to prepend the data to.

value

The string to prepend.

Return Values

Returns TRUE on success or FALSE on failure. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key does not exist.

Examples

Example #1 Memcached::prepend() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);
$m->setOption(Memcached::OPT_COMPRESSION, false);

$m->set('foo', 'abc');
$m->prepend('foo', 'def');
var_dump($m->get('foo'));
?>

The above example will output:

string(6) "defabc"

See Also

  • Memcached::prependByKey() - Prepend data to an existing item on a specific server
  • Memcached::append() - Append data to an existing item


Prepend data to an existing item on a specific server

  • « Memcached::prepend
  • Memcached::quit »
  • PHP Manual
  • Memcached
  • Prepend data to an existing item on a specific server

Memcached::prependByKey

(PECL memcached >= 0.1.0)

Memcached::prependByKey — Prepend data to an existing item on a specific server

Description

public Memcached::prependByKey ( string $server_key , string $key , string $value ) : bool

Memcached::prependByKey() is functionally equivalent to Memcached::prepend(), except that the free-form server_key can be used to map the key to a specific server.

Parameters

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

key

The key of the item to prepend the data to.

value

The string to prepend.

Return Values

Returns TRUE on success or FALSE on failure. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key does not exist.

See Also

  • Memcached::prepend() - Prepend data to an existing item
  • Memcached::append() - Append data to an existing item


Close any open connections

  • « Memcached::prependByKey
  • Memcached::replace »
  • PHP Manual
  • Memcached
  • Close any open connections

Memcached::quit

(PECL memcached >= 2.0.0)

Memcached::quit — Close any open connections

Description

public Memcached::quit ( void ) : bool

Memcached::quit() closes any open connections to the memcache servers.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.


Replace the item under an existing key

  • « Memcached::quit
  • Memcached::replaceByKey »
  • PHP Manual
  • Memcached
  • Replace the item under an existing key

Memcached::replace

(PECL memcached >= 0.1.0)

Memcached::replace — Replace the item under an existing key

Description

public Memcached::replace ( string $key , mixed $value [, int $expiration ] ) : bool

Memcached::replace() is similar to Memcached::set(), but the operation fails if the key does not exist on the server.

Parameters

key

The key under which to store the value.

value

The value to store.

expiration

The expiration time, defaults to 0. See Expiration Times for more info.

Return Values

Returns TRUE on success or FALSE on failure. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key does not exist.

See Also

  • Memcached::replaceByKey() - Replace the item under an existing key on a specific server
  • Memcached::set() - Store an item
  • Memcached::add() - Add an item under a new key


Replace the item under an existing key on a specific server

  • « Memcached::replace
  • Memcached::resetServerList »
  • PHP Manual
  • Memcached
  • Replace the item under an existing key on a specific server

Memcached::replaceByKey

(PECL memcached >= 0.1.0)

Memcached::replaceByKey — Replace the item under an existing key on a specific server

Description

public Memcached::replaceByKey ( string $server_key , string $key , mixed $value [, int $expiration ] ) : bool

Memcached::replaceByKey() is functionally equivalent to Memcached::replace(), except that the free-form server_key can be used to map the key to a specific server. This is useful if you need to keep a bunch of related keys on a certain server.

Parameters

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

key

The key under which to store the value.

value

The value to store.

expiration

The expiration time, defaults to 0. See Expiration Times for more info.

Return Values

Returns TRUE on success or FALSE on failure. The Memcached::getResultCode() will return Memcached::RES_NOTSTORED if the key does not exist.

See Also

  • Memcached::replace() - Replace the item under an existing key
  • Memcached::set() - Store an item
  • Memcached::add() - Add an item under a new key


Clears all servers from the server list

  • « Memcached::replaceByKey
  • Memcached::set »
  • PHP Manual
  • Memcached
  • Clears all servers from the server list

Memcached::resetServerList

(PECL memcached >= 2.0.0)

Memcached::resetServerList — Clears all servers from the server list

Description

public Memcached::resetServerList ( void ) : bool

Memcached::resetserverlist() removes all memcache servers from the known server list, reseting it back to empty.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • Memcached::addServer() - Add a server to the server pool
  • Memcached::addServers() - Add multiple servers to the server pool


Store an item

  • « Memcached::resetServerList
  • Memcached::setByKey »
  • PHP Manual
  • Memcached
  • Store an item

Memcached::set

(PECL memcached >= 0.1.0)

Memcached::set — Store an item

Description

public Memcached::set ( string $key , mixed $value [, int $expiration ] ) : bool

Memcached::set() stores the value on a memcache server under the specified key. The expiration parameter can be used to control when the value is considered expired.

The value can be any valid PHP type except for resources, because those cannot be represented in a serialized form. If the Memcached::OPT_COMPRESSION option is turned on, the serialized value will also be compressed before storage.

Parameters

key

The key under which to store the value.

value

The value to store.

expiration

The expiration time, defaults to 0. See Expiration Times for more info.

Return Values

Returns TRUE on success or FALSE on failure. Use Memcached::getResultCode() if necessary.

Examples

Example #1 Memcached::set() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('int', 99);
$m->set('string', 'a simple string');
$m->set('array', array(11, 12));
/* expire 'object' key in 5 minutes */
$m->set('object', new stdclass, time() + 300);

var_dump($m->get('int'));
var_dump($m->get('string'));
var_dump($m->get('array'));
var_dump($m->get('object'));
?>

The above example will output something similar to:

int(99)
string(15) "a simple string"
array(2) {
  [0]=>
  int(11)
  [1]=>
  int(12)
}
object(stdClass)#1 (0) {
}

See Also

  • Memcached::setByKey() - Store an item on a specific server
  • Memcached::add() - Add an item under a new key
  • Memcached::replace() - Replace the item under an existing key


Store an item on a specific server

  • « Memcached::set
  • Memcached::setMulti »
  • PHP Manual
  • Memcached
  • Store an item on a specific server

Memcached::setByKey

(PECL memcached >= 0.1.0)

Memcached::setByKey — Store an item on a specific server

Description

public Memcached::setByKey ( string $server_key , string $key , mixed $value [, int $expiration ] ) : bool

Memcached::setByKey() is functionally equivalent to Memcached::set(), except that the free-form server_key can be used to map the key to a specific server. This is useful if you need to keep a bunch of related keys on a certain server.

Parameters

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

key

The key under which to store the value.

value

The value to store.

expiration

The expiration time, defaults to 0. See Expiration Times for more info.

Return Values

Returns TRUE on success or FALSE on failure. Use Memcached::getResultCode() if necessary.

Examples

Example #1 Memcached::setByKey() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

/* keep IP blocks on a certain server */
$m->setByKey('api-cache', 'block-ip:169.254.253.252', 1);
$m->setByKey('api-cache', 'block-ip:169.127.127.202', 1);
?>

See Also

  • Memcached::set() - Store an item


Store multiple items

  • « Memcached::setByKey
  • Memcached::setMultiByKey »
  • PHP Manual
  • Memcached
  • Store multiple items

Memcached::setMulti

(PECL memcached >= 0.1.0)

Memcached::setMulti — Store multiple items

Description

public Memcached::setMulti ( array $items [, int $expiration ] ) : bool

Memcached::setMulti() is similar to Memcached::set(), but instead of a single key/value item, it works on multiple items specified in items. The expiration time applies to all the items at once.

Parameters

items

An array of key/value pairs to store on the server.

expiration

The expiration time, defaults to 0. See Expiration Times for more info.

Return Values

Returns TRUE on success or FALSE on failure. Use Memcached::getResultCode() if necessary.

Examples

Example #1 Memcached::setMulti() example

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$items = array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3'
);
$m->setMulti($items, time() + 300);
?>

See Also

  • Memcached::setMultiByKey() - Store multiple items on a specific server
  • Memcached::set() - Store an item


Store multiple items on a specific server

  • « Memcached::setMulti
  • Memcached::setOption »
  • PHP Manual
  • Memcached
  • Store multiple items on a specific server

Memcached::setMultiByKey

(PECL memcached >= 0.1.0)

Memcached::setMultiByKey — Store multiple items on a specific server

Description

public Memcached::setMultiByKey ( string $server_key , array $items [, int $expiration ] ) : bool

Memcached::setMultiByKey() is functionally equivalent to Memcached::setMulti(), except that the free-form server_key can be used to map the keys from items to a specific server. This is useful if you need to keep a bunch of related keys on a certain server.

Parameters

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

items

An array of key/value pairs to store on the server.

expiration

The expiration time, defaults to 0. See Expiration Times for more info.

Return Values

Returns TRUE on success or FALSE on failure. Use Memcached::getResultCode() if necessary.

See Also

  • Memcached::setMulti() - Store multiple items
  • Memcached::set() - Store an item


Set a Memcached option

  • « Memcached::setMultiByKey
  • Memcached::setOptions »
  • PHP Manual
  • Memcached
  • Set a Memcached option

Memcached::setOption

(PECL memcached >= 0.1.0)

Memcached::setOption — Set a Memcached option

Description

public Memcached::setOption ( int $option , mixed $value ) : bool

This method sets the value of a Memcached option. Some options correspond to the ones defined by libmemcached, and some are specific to the extension. See Memcached Constants for more information.

The options listed below require values specified via constants.

  • Memcached::OPT_HASH requires Memcached::HASH_* values.

  • Memcached::OPT_DISTRIBUTION requires Memcached::DISTRIBUTION_* values.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Setting a Memcached option

<?php
$m = new Memcached();
var_dump($m->getOption(Memcached::OPT_HASH) == Memcached::HASH_DEFAULT);
$m->setOption(Memcached::OPT_HASH, Memcached::HASH_MURMUR);
$m->setOption(Memcached::OPT_PREFIX_KEY, "widgets");
echo "Prefix key is now: ", $m->getOption(Memcached::OPT_PREFIX_KEY), "\n";
?>

The above example will output:

bool(true)
Prefix key is now: widgets

See Also

  • Memcached::getOption() - Retrieve a Memcached option value
  • Memcached::setOptions() - Set Memcached options
  • Memcached Constants


Set Memcached options

  • « Memcached::setOption
  • Memcached::setSaslAuthData »
  • PHP Manual
  • Memcached
  • Set Memcached options

Memcached::setOptions

(PECL memcached >= 2.0.0)

Memcached::setOptions — Set Memcached options

Description

public Memcached::setOptions ( array $options ) : bool

Memcached::setOptions() is a variation of the Memcached::setOption() that takes an array of options to be set.

Parameters

options

An associative array of options where the key is the option to set and the value is the new value for the option.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Setting Memcached options

<?php
$m = new Memcached();
var_dump($m->getOption(Memcached::OPT_HASH) == Memcached::HASH_DEFAULT);

$m->setOptions(array(Memcached::OPT_HASH => Memcached::HASH_MURMUR, Memcached::OPT_PREFIX_KEY => "widgets"));

var_dump($m->getOption(Memcached::OPT_HASH) == Memcached::HASH_DEFAULT);
echo "Prefix key is now: ", $m->getOption(Memcached::OPT_PREFIX_KEY), "\n";
?>

The above example will output:

bool(true)
bool(false)
Prefix key is now: widgets

See Also

  • Memcached::getOption() - Retrieve a Memcached option value
  • Memcached::setOption() - Set a Memcached option
  • Memcached Constants


Set the credentials to use for authentication

  • « Memcached::setOptions
  • Memcached::touch »
  • PHP Manual
  • Memcached
  • Set the credentials to use for authentication

Memcached::setSaslAuthData

(PECL memcached >= 2.0.0)

Memcached::setSaslAuthData — Set the credentials to use for authentication

Description

public Memcached::setSaslAuthData ( string $username , string $password ) : void

Memcached::setSaslAuthData() sets the username and password that should be used for SASL authentication with the memcache servers.

This method is only available when the memcached extension is built with SASL support. Please refer to Memcached setup for how to do this.

Parameters

username

The username to use for authentication.

password

The password to use for authentication.

Return Values

No value is returned.


Set a new expiration on an item

  • « Memcached::setSaslAuthData
  • Memcached::touchByKey »
  • PHP Manual
  • Memcached
  • Set a new expiration on an item

Memcached::touch

(PECL memcached >= 2.0.0)

Memcached::touch — Set a new expiration on an item

Description

public Memcached::touch ( string $key , int $expiration ) : bool

Memcached::touch() sets a new expiration value on the given key.

Parameters

key

The key under which to store the value.

expiration

The expiration time, defaults to 0. See Expiration Times for more info.

Return Values

Returns TRUE on success or FALSE on failure. Use Memcached::getResultCode() if necessary.

See Also

  • Memcached::touchByKey() - Set a new expiration on an item on a specific server


Set a new expiration on an item on a specific server

  • « Memcached::touch
  • MemcachedException »
  • PHP Manual
  • Memcached
  • Set a new expiration on an item on a specific server

Memcached::touchByKey

(PECL memcached >= 2.0.0)

Memcached::touchByKey — Set a new expiration on an item on a specific server

Description

public Memcached::touchByKey ( string $server_key , string $key , int $expiration ) : bool

Memcached::touchByKey() is functionally equivalent to Memcached::touch(), except that the free-form server_key can be used to map the key to a specific server.

Parameters

server_key

The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.

key

The key under which to store the value.

expiration

The expiration time, defaults to 0. See Expiration Times for more info.

Return Values

Returns TRUE on success or FALSE on failure. Use Memcached::getResultCode() if necessary.

See Also

  • Memcached::touch() - Set a new expiration on an item


The MemcachedException class

(PECL memcached >= 0.1.0)

Introduction

Class synopsis

MemcachedException extends RuntimeException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


mqseries

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • mqseries Functions
    • mqseries_back — MQSeries MQBACK
    • mqseries_begin — MQseries MQBEGIN
    • mqseries_close — MQSeries MQCLOSE
    • mqseries_cmit — MQSeries MQCMIT
    • mqseries_conn — MQSeries MQCONN
    • mqseries_connx — MQSeries MQCONNX
    • mqseries_disc — MQSeries MQDISC
    • mqseries_get — MQSeries MQGET
    • mqseries_inq — MQSeries MQINQ
    • mqseries_open — MQSeries MQOPEN
    • mqseries_put1 — MQSeries MQPUT1
    • mqseries_put — MQSeries MQPUT
    • mqseries_set — MQSeries MQSET
    • mqseries_strerror — Returns the error message corresponding to a result code (MQRC)


Introduction

This extension aims to provide an interface for communicating with IBMs WebSphere MQ series Queue managers.

The interface mimics the C-API client interface of WebSphere MQ Series as close as possible. Using the same naming conventions and possibilities of the C-API. In order to understand the workings of this extension some level of understanding the C-API is required.

For MQ-options, MQ-structures, MQ-results etc. please read the WebSphere MQ Application Programming Guide and WebSphere MQ Application Programming Reference.


Requirements

A working IBM WebSphere MQ installation. If building the extension the SDK for IBM WebSphere MQ is also required.

Note: Be aware that when running against a IBM WebSphere MQ Client installation some methods are not available. This is not a problem of the extension but just the way the WebSphere MQ Client Interface works.

Installation requirements on non windows platforms

Build the extension and put it in the PHP extension directory.

Installation requirements on Windows

No additional 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/mqseries.

Note: The official name of this extension is mqseries.

There are two ways to connect to a queue manager. These depend on the way the extension is compiled and linked.

  • First one and also the default one is using the mqic libraries. Compiling and linking the extension against these IBM WebSphere MQSeries libraries allows the extension to connect to the Queue manager using the client interface. Remote connections are possible this way.

  • The other way is to compile and link against the mqm libraries. Using these libraries it is possible to make use of the transaction management of a queue manager.

Currently selecting the libraries to use is done by changing the config.m4 file.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

There are no extra configuration parameters.


Resource Types

This extension defines a connection and object_handle resources.

The mqseries_conn() and mqseries_connx() define the connectionn handles.

The mqseries_open() defines the object handle.


Predefined Constants

For each WebSphere MQ Constant there is a mqseries counterpart.

For definitions and usage see the WebSphere MQ Application Programming Guide and WebSphere MQ Application Programming Reference red books.

The name of the mqseries counterpart is made by appending the WebSphere MQ constant with MQSERIES_, for example the CompletionCode constants are:

mqseries constants
PHP Constant | MQ Constant
MQSERIES_MQCC_OK | MQCC_OK
MQSERIES_MQCC_WARNING | MQCC_WARNING
MQSERIES_MQCC_FAILED | MQCC_FAILED
MQSERIES_MQCC_UNKNOWN | MQCC_UNKNOWN


mqseries Functions

Table of Contents

  • mqseries_back — MQSeries MQBACK
  • mqseries_begin — MQseries MQBEGIN
  • mqseries_close — MQSeries MQCLOSE
  • mqseries_cmit — MQSeries MQCMIT
  • mqseries_conn — MQSeries MQCONN
  • mqseries_connx — MQSeries MQCONNX
  • mqseries_disc — MQSeries MQDISC
  • mqseries_get — MQSeries MQGET
  • mqseries_inq — MQSeries MQINQ
  • mqseries_open — MQSeries MQOPEN
  • mqseries_put1 — MQSeries MQPUT1
  • mqseries_put — MQSeries MQPUT
  • mqseries_set — MQSeries MQSET
  • mqseries_strerror — Returns the error message corresponding to a result code (MQRC)


MQSeries MQBACK

  • « mqseries Functions
  • mqseries_begin »
  • PHP Manual
  • mqseries Functions
  • MQSeries MQBACK

mqseries_back

(PECL mqseries >= 0.10.0)

mqseries_back — MQSeries MQBACK

Description

mqseries_back ( resource $hconn , resource &$compCode , resource &$reason ) : void

The mqseries_back() (MQBACK) call indicates to the queue manager that all the message gets and puts that have occurred since the last syncpoint are to be backed out. Messages put as part of a unit of work are deleted; messages retrieved as part of a unit of work are reinstated on the queue.

Using mqseries_back() only works in conjunction with mqseries_begin() and only function when connecting directly to a Queueu manager. Not via the mqclient interface.

Parameters

hConn

Connection handle.

This handle represents the connection to the queue manager.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Return Values

No value is returned.

Examples

Example #1 mqseries_back() example

<?php
    mqseries_back($conn, $comp_code, $reason);

    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
    }
?>

Notes

Note:

mqseries_back() will not function when using MQSeries Client to connect to a Queueu Manager.

See Also

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX
  • mqseries_begin() - MQseries MQBEGIN


MQseries MQBEGIN

  • « mqseries_back
  • mqseries_close »
  • PHP Manual
  • mqseries Functions
  • MQseries MQBEGIN

mqseries_begin

(PECL mqseries >= 0.10.0)

mqseries_begin — MQseries MQBEGIN

Description

mqseries_begin ( resource $hconn , array $beginOptions , resource &$compCode , resource &$reason ) : void

The mqseries_begin() (MQBEGIN) call begins a unit of work that is coordinated by the queue manager, and that may involve external resource managers.

Using mqseries_begin() starts the unit of work. Either mqseries_back() or mqseries_cmit() ends the unit of work.

Parameters

hConn

Connection handle.

This handle represents the connection to the queue manager.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Return Values

No value is returned.

Examples

Example #1 mqseries_begin() example

<?php
    $mqbo = array();
    mqseries_begin( $conn,
                    $mqbo,
                    $comp_code,
                    $reason);
    if ($comp_code !== MQSERIES_MQCC_OK) {
        /* reason code 2121 is a warning for more information see MQSeries reference manual.*/
        if ($reason !== 2121) {
            printf("CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
        }
    }
?>

Notes

Note:

mqseries_begin() will not function when using MQSeries Client to connect to a Queueu Manager.

See Also

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX
  • mqseries_back() - MQSeries MQBACK
  • mqseries_cmit() - MQSeries MQCMIT


MQSeries MQCLOSE

  • « mqseries_begin
  • mqseries_cmit »
  • PHP Manual
  • mqseries Functions
  • MQSeries MQCLOSE

mqseries_close

(PECL mqseries >= 0.10.0)

mqseries_close — MQSeries MQCLOSE

Description

mqseries_close ( resource $hconn , resource $hobj , int $options , resource &$compCode , resource &$reason ) : void

The mqseries_close() (MQCLOSE) call relinquishes access to an object, and is the inverse of the mqseries_open() (MQOPEN) call.

Parameters

hConn

Connection handle.

This handle represents the connection to the queue manager.

hObj

Object handle.

This handle represents the object to be used.

options

compCode

Completion code.

reason

Reason code qualifying the compCode.

Return Values

No value is returned.

Examples

Example #1 mqseries_close() example

<?php
    mqseries_close($conn, $obj, MQSERIES_MQCO_NONE, $comp_code, $reason);
    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("close CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
    }
?>

See Also

  • mqseries_open() - MQSeries MQOPEN
  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX


MQSeries MQCMIT

  • « mqseries_close
  • mqseries_conn »
  • PHP Manual
  • mqseries Functions
  • MQSeries MQCMIT

mqseries_cmit

(PECL mqseries >= 0.10.0)

mqseries_cmit — MQSeries MQCMIT

Description

mqseries_cmit ( resource $hconn , resource &$compCode , resource &$reason ) : void

The mqseries_cmit() (MQCMIT) call indicates to the queue manager that the application has reached a syncpoint, and that all of the message gets and puts that have occurred since the last syncpoint are to be made permanent. Messages put as part of a unit of work are made available to other applications; messages retrieved as part of a unit of work are deleted.

Parameters

hConn

Connection handle.

This handle represents the connection to the queue manager.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Return Values

No value is returned.

Examples

Example #1 mqseries_cmit() example

<?php
    mqseries_cmit($conn, $comp_code, $reason);
    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("cmit CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
    }
?>

Notes

Note:

mqseries_back() will not function when using MQSeries Client to connect to a Queueu Manager.

See Also

  • mqseries_begin() - MQseries MQBEGIN
  • mqseries_back() - MQSeries MQBACK
  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX


MQSeries MQCONN

  • « mqseries_cmit
  • mqseries_connx »
  • PHP Manual
  • mqseries Functions
  • MQSeries MQCONN

mqseries_conn

(PECL mqseries >= 0.10.0)

mqseries_conn — MQSeries MQCONN

Description

mqseries_conn ( string $qManagerName , resource &$hconn , resource &$compCode , resource &$reason ) : void

The mqseries_conn() (MQCONN) call connects an application program to a queue manager. It provides a queue manager connection handle, which is used by the application on subsequent message queuing calls.

Parameters

qManagerName

Name of queue manager.

Name of the queue manager the application wishes to connect.

hConn

Connection handle.

This handle represents the connection to the queue manager.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Return Values

No value is returned.

Examples

Example #1 mqseries_conn() example

<?php
    mqseries_conn('WMQ1', $conn, $comp_code, $reason);
    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("conn CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
        exit;
    }
?>

See Also

  • mqseries_disc() - MQSeries MQDISC


MQSeries MQCONNX

  • « mqseries_conn
  • mqseries_disc »
  • PHP Manual
  • mqseries Functions
  • MQSeries MQCONNX

mqseries_connx

(PECL mqseries >= 0.10.0)

mqseries_connx — MQSeries MQCONNX

Description

mqseries_connx ( string $qManagerName , array &$connOptions , resource &$hconn , resource &$compCode , resource &$reason ) : void

The mqseries_connx() (MQCONNX) call connects an application program to a queue manager. It provides a queue manager connection handle, which is used by the application on subsequent MQ calls.

The mqseries_connx() call is like the mqseries_conn() (MQCONN) call, except that MQCONNX allows options to be specified to control the way that the call works.

Parameters

qManagerName

Name of queue manager.

Name of the queue manager the application wishes to connect.

connOps

Options that control the action of function

See also the MQCNO structure.

hConn

Connection handle.

This handle represents the connection to the queue manager.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Return Values

No value is returned.

Examples

Example #1 mqseries_connx() example

<?php
    $mqcno = array(
        'Version' => MQSERIES_MQCNO_VERSION_2,
        'Options' => MQSERIES_MQCNO_STANDARD_BINDING,
        'MQCD' => array('ChannelName' => 'MQNX9420.CLIENT',
        'ConnectionName' => 'localhost',
        'TransportType' => MQSERIES_MQXPT_TCP)
    );

    mqseries_connx('MQNX9420', $mqcno, $conn, $comp_code,$reason);
    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("Connx CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
        exit;
    }

?>

Example #2 mqseries_connx() example using SSL connection & OCSP Responder URL

<?php
    $mqcno = array(
        'Version' => 4, //MQCNO_VERSION_4
        'Options' => MQSERIES_MQCNO_STANDARD_BINDING,
        'MQCD' => array(
            'Version' => 7, //MQCD_VERSION_7
            'ConnectionName' => 'localhost',
            'TransportType' => MQSERIES_MQXPT_TCP,
            'ChannelName' => 'CONNECTIONCHANNEL',
            'SSLCipherSpec' => 'NULL_SHA'
        ),
        'MQSCO' => array(
            'KeyRepository' => '/var/mqm/qmgrs/QUEUEMGR/ssl/key', //Local path where the SSL key repository can be found
            'MQAIR' => array(
                'Version' => 2, //MQAIR_VERSION_2
                'AuthInfoType' => 2, //MQAIT_OCSP
                'OCSPResponderURL' => 'http://dummy.OCSP.responder'
            )
        )
    );

    mqseries_connx('QUEUEMGR', $mqcno, $conn, $comp_code,$reason);
    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("Connx CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
        exit;
    }

?>

See Also

  • mqseries_disc() - MQSeries MQDISC


MQSeries MQDISC

  • « mqseries_connx
  • mqseries_get »
  • PHP Manual
  • mqseries Functions
  • MQSeries MQDISC

mqseries_disc

(PECL mqseries >= 0.10.0)

mqseries_disc — MQSeries MQDISC

Description

mqseries_disc ( resource $hconn , resource &$compCode , resource &$reason ) : void

The mqseries_disc() (MQDISC) call breaks the connection between the queue manager and the application program, and is the inverse of the mqseries_conn() (MQCONN) or mqseries_connx() (MQCONNX) call.

Parameters

hConn

Connection handle.

This handle represents the connection to the queue manager.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Return Values

No value is returned.

Examples

Example #1 mqseries_disc() example

<?php
    mqseries_disc($conn, $comp_code, $reason);
    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("disc CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
    }
?>

See Also

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX


MQSeries MQGET

  • « mqseries_disc
  • mqseries_inq »
  • PHP Manual
  • mqseries Functions
  • MQSeries MQGET

mqseries_get

(PECL mqseries >= 0.10.0)

mqseries_get — MQSeries MQGET

Description

mqseries_get ( resource $hConn , resource $hObj , array &$md , array &$gmo , int &$bufferLength , string &$msg , int &$data_length , resource &$compCode , resource &$reason ) : void

The mqseries_get() (MQGET) call retrieves a message from a local queue that has been opened using the mqseries_open() (MQOPEN) call

Parameters

hConn

Connection handle.

This handle represents the connection to the queue manager.

hObj

Object handle.

This handle represents the object to be used.

md

Message descriptor (MQMD).

gmo

Get message options (MQGMO).

bufferLength

Expected length of the result buffer

msg

Buffer holding the message that was retrieved from the object.

data_length

Actual buffer length

compCode

Completion code.

reason

Reason code qualifying the compCode.

Return Values

No value is returned.

Examples

Example #1 mqseries_get() example

<?php
// open connection to the queue manager
    mqseries_conn('WMQ1', $conn, $comp_code, $reason);
// $conn now hold the reference to the connection to the queue manager.

// open the connection to the testq queue
    mqseries_open(
                $conn,
                array('ObjectName' => 'TESTQ'),
                MQSERIES_MQOO_INPUT_AS_Q_DEF | MQSERIES_MQOO_FAIL_IF_QUIESCING | MQSERIES_MQOO_OUTPUT,
                $obj,
                $comp_code,
                $reason);
// $obj now holds the reference to the object (TESTQ)

// setup empty message descriptor.
    $mdg = array();
// setup get message options
    $gmo = array('Options' => MQSERIES_MQGMO_FAIL_IF_QUIESCING | MQSERIES_MQGMO_WAIT, 'WaitInterval' => 3000);

// get the message from the queue
    mqseries_get($conn, $obj, $mdg, $gmo, 255, $msg, $data_length, $comp_code, $reason);
    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("GET CompCode:%d Reason:%d Text:%s<br>", $comp_code, $reason, mqseries_strerror($reason));
    }

// close the object reference $obj
    mqseries_close($conn, $obj, MQSERIES_MQCO_NONE, $comp_code, $reason);

// disconnect from the queue manager.
    mqseries_disc($conn, $comp_code, $reason);

?>

See Also

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX
  • mqseries_open() - MQSeries MQOPEN
  • mqseries_put() - MQSeries MQPUT


MQSeries MQINQ

  • « mqseries_get
  • mqseries_open »
  • PHP Manual
  • mqseries Functions
  • MQSeries MQINQ

mqseries_inq

(PECL mqseries >= 0.10.0)

mqseries_inq — MQSeries MQINQ

Description

mqseries_inq ( resource $hconn , resource $hobj , int $selectorCount , array $selectors , int $intAttrCount , resource &$intAttr , int $charAttrLength , resource &$charAttr , resource &$compCode , resource &$reason ) : void

The mqseries_inq() (MQINQ) call returns an array of integers and a set of character strings containing the attributes of an object.

Parameters

hConn

Connection handle.

This handle represents the connection to the queue manager.

hObj

Object handle.

This handle represents the object to be used.

selectorCount

Count of selectors.

selectors

Array of attribute selectors.

intAttrLength

Count of integer attributes.

intAttr

Array of integer attributes.

charAttrLength

Length of character attributes buffer.

charAttr

Character attributes.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Return Values

No value is returned.

Examples

Example #1 mqseries_inq() example

<?php
    $int_attr = array();
    $char_attr = "";

    mqseries_inq($conn, $obj, 1, array(MQSERIES_MQCA_Q_MGR_NAME), 0, $int_attr, 48, $char_attr, $comp_code, $reason);

    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("INQ CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
    } else {
        echo "INQ QManager name result ".$char_attr."<br>\n";
    }
?>

See Also

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX
  • mqseries_open() - MQSeries MQOPEN


MQSeries MQOPEN

  • « mqseries_inq
  • mqseries_put1 »
  • PHP Manual
  • mqseries Functions
  • MQSeries MQOPEN

mqseries_open

(PECL mqseries >= 0.10.0)

mqseries_open — MQSeries MQOPEN

Description

mqseries_open ( resource $hconn , array &$objDesc , int $option , resource &$hobj , resource &$compCode , resource &$reason ) : void

The mqseries_open() (MQOPEN) call establishes access to an object.

Parameters

hConn

Connection handle.

This handle represents the connection to the queue manager.

objDesc

Object descriptor. (MQOD)

options

Options that control the action of the function.

hObj

Object handle.

This handle represents the object to be used.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Return Values

No value is returned.

Examples

Example #1 mqseries_open() example

<?php
    $mqods = array('ObjectName' => 'TESTQ');
    mqseries_open(
                $conn,
                $mqods,
                MQSERIES_MQOO_INPUT_AS_Q_DEF | MQSERIES_MQOO_FAIL_IF_QUIESCING | MQSERIES_MQOO_OUTPUT,
                $obj,
                $comp_code,
                $reason);
    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("open CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
        exit;
    }
?>

See Also

  • mqseries_close() - MQSeries MQCLOSE


MQSeries MQPUT1

  • « mqseries_open
  • mqseries_put »
  • PHP Manual
  • mqseries Functions
  • MQSeries MQPUT1

mqseries_put1

(PECL mqseries >= 0.10.0)

mqseries_put1 — MQSeries MQPUT1

Description

mqseries_put1 ( resource $hconn , resource &$objDesc , resource &$msgDesc , resource &$pmo , string $buffer , resource &$compCode , resource &$reason ) : void

The mqseries_put1() (MQPUT1) call puts one message on a queue. The queue need not be open.

You can use both the mqseries_put() and mqseries_put1() calls to put messages on a queue; which call to use depends on the circumstances. Use the mqseries_put() (MQPUT) call to place multiple messages on the same queue. Use the mqseries_put1() (MQPUT1) call to put only one message on a queue. This call encapsulates the MQOPEN, MQPUT, and MQCLOSE calls into a single call, minimizing the number of calls that must be issued.

Parameters

hConn

Connection handle.

This handle represents the connection to the queue manager.

objDesc

Object descriptor. (MQOD)

This is a structure which identifies the queue to which the message is added.

msgDesc

Message descriptor (MQMD).

pmo

Put message options (MQPMO).

compCode

Completion code.

reason

Reason code qualifying the compCode.

Return Values

No value is returned.

See Also

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX
  • mqseries_open() - MQSeries MQOPEN
  • mqseries_get() - MQSeries MQGET


MQSeries MQPUT

  • « mqseries_put1
  • mqseries_set »
  • PHP Manual
  • mqseries Functions
  • MQSeries MQPUT

mqseries_put

(PECL mqseries >= 0.10.0)

mqseries_put — MQSeries MQPUT

Description

mqseries_put ( resource $hConn , resource $hObj , array &$md , array &$pmo , string $message , resource &$compCode , resource &$reason ) : void

The mqseries_put() (MQPUT) call puts a message on a queue or distribution list. The queue or distribution list must already be open.

Parameters

hConn

Connection handle.

This handle represents the connection to the queue manager.

hObj

Object handle.

This handle represents the object to be used.

md

Message descriptor (MQMD).

pmo

Put message options (MQPMO).

message

The actual message to put onto the queue.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Return Values

No value is returned.

Examples

Example #1 mqseries_put() example

<?php
// open connection to the queue manager
    mqseries_conn('WMQ1', $conn, $comp_code, $reason);
// $conn now hold the reference to the connection to the queue manager.

// open the connectio to the testq queueu
    mqseries_open(
                $conn,
                array('ObjectName' => 'TESTQ'),
                MQSERIES_MQOO_INPUT_AS_Q_DEF | MQSERIES_MQOO_FAIL_IF_QUIESCING | MQSERIES_MQOO_OUTPUT,
                $obj,
                $comp_code,
                $reason);
// $obj now holds the reference to the object (TESTQ)

// setup the message descriptor array. Check MQSeries reference manuals.
    $md = array(
                'Version' => MQSERIES_MQMD_VERSION_1,
                'Expiry' => MQSERIES_MQEI_UNLIMITED,
                'Report' => MQSERIES_MQRO_NONE,
                'MsgType' => MQSERIES_MQMT_DATAGRAM,
                'Format' => MQSERIES_MQFMT_STRING,
                'Priority' => 1,
                'Persistence' => MQSERIES_MQPER_PERSISTENT);

// setup the put message options.
    $pmo = array('Options' => MQSERIES_MQPMO_NEW_MSG_ID|MQSERIES_MQPMO_SYNCPOINT);

// put the message 'Ping' on the queueu.
    mqseries_put($conn, $obj, $md, $pmo, 'Ping', $comp_code, $reason);

    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("put CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
    }

// close the object reference $obj
    mqseries_close($conn, $obj, MQSERIES_MQCO_NONE, $comp_code, $reason);

// disconnect from the queue manager.
    mqseries_disc($conn, $comp_code, $reason);

?>

See Also

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX
  • mqseries_open() - MQSeries MQOPEN
  • mqseries_get() - MQSeries MQGET


MQSeries MQSET

  • « mqseries_put
  • mqseries_strerror »
  • PHP Manual
  • mqseries Functions
  • MQSeries MQSET

mqseries_set

(PECL mqseries >= 0.10.0)

mqseries_set — MQSeries MQSET

Description

mqseries_set ( resource $hConn , resource $hObj , int $selectorCount , array $selectors , int $intAttrCount , array $intAttrs , int $charAttrLength , array $charAttrs , resource &$compCode , resource &$reason ) : void

The mqseries_set() (MQSET) call is used to change the attributes of an object represented by a handle. The object must be a queue.

Parameters

hConn

Connection handle.

This handle represents the connection to the queue manager.

hObj

Object handle.

This handle represents the object to be used.

selectorCount

Count of selectors.

selectors

Array of attribute selectors.

intAttrCount

Count of integer attributes.

intAttrs

Array of integer attributes.

charAttrLength

Length of character attributes buffer.

charAttrs

Character attributes.

compCode

Completion code.

reason

Reason code qualifying the compCode.

Return Values

No value is returned.

See Also

  • mqseries_inq() - MQSeries MQINQ


Returns the error message corresponding to a result code (MQRC)

  • « mqseries_set
  • Network »
  • PHP Manual
  • mqseries Functions
  • Returns the error message corresponding to a result code (MQRC)

mqseries_strerror

(PECL mqseries >= 0.10.0)

mqseries_strerror — Returns the error message corresponding to a result code (MQRC)

Description

mqseries_strerror ( int $reason ) : string

mqseries_strerror() returns the message that correspond to the reason result code.

Parameters

reason

Reason code qualifying the compCode.

Return Values

string representation of the reason code message.

Examples

Example #1 mqseries_strerror() example

<?php
    if ($comp_code !== MQSERIES_MQCC_OK) {
        printf("open CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
        exit;
    }
?>

The above example will output:

Connx CompCode:2 Reason:2059 Text:Queue manager not available for connection.


Network

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Network Functions
    • checkdnsrr — Check DNS records corresponding to a given Internet host name or IP address
    • closelog — Close connection to system logger
    • define_syslog_variables — Initializes all syslog related variables
    • dns_check_record — Alias of checkdnsrr
    • dns_get_mx — Alias of getmxrr
    • dns_get_record — Fetch DNS Resource Records associated with a hostname
    • fsockopen — Open Internet or Unix domain socket connection
    • gethostbyaddr — Get the Internet host name corresponding to a given IP address
    • gethostbyname — Get the IPv4 address corresponding to a given Internet host name
    • gethostbynamel — Get a list of IPv4 addresses corresponding to a given Internet host name
    • gethostname — Gets the host name
    • getmxrr — Get MX records corresponding to a given Internet host name
    • getprotobyname — Get protocol number associated with protocol name
    • getprotobynumber — Get protocol name associated with protocol number
    • getservbyname — Get port number associated with an Internet service and protocol
    • getservbyport — Get Internet service which corresponds to port and protocol
    • header_register_callback — Call a header function
    • header_remove — Remove previously set headers
    • header — Send a raw HTTP header
    • headers_list — Returns a list of response headers sent (or ready to send)
    • headers_sent — Checks if or where headers have been sent
    • http_response_code — Get or Set the HTTP response code
    • inet_ntop — Converts a packed internet address to a human readable representation
    • inet_pton — Converts a human readable IP address to its packed in_addr representation
    • ip2long — Converts a string containing an (IPv4) Internet Protocol dotted address into a long integer
    • long2ip — Converts an long integer address into a string in (IPv4) Internet standard dotted format
    • openlog — Open connection to system logger
    • pfsockopen — Open persistent Internet or Unix domain socket connection
    • setcookie — Send a cookie
    • setrawcookie — Send a cookie without urlencoding the cookie value
    • socket_get_status — Alias of stream_get_meta_data
    • socket_set_blocking — Alias of stream_set_blocking
    • socket_set_timeout — Alias of stream_set_timeout
    • syslog — Generate a system log message


  • « Network
  • Installing/Configuring »
  • PHP Manual
  • Network
  • Introduction

Introduction

Provides various networking functions.


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

Functions checkdnsrr(), getmxrr() and dns_get_record() requires Bind on Linux.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Network Configuration Options
Name | Default | Changeable | Changelog
define_syslog_variables | "0" | PHP_INI_ALL | Deprecated in PHP 5.3.0. Removed in PHP 5.4.0.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

define_syslog_variables boolean

Whether or not to define the various syslog variables (e.g. $LOG_PID, $LOG_CRON, etc.). Turning it off is a good idea performance-wise. At runtime, you can define these variables by calling define_syslog_variables().


  • « Runtime Configuration
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

This extension defines a file pointer resource returned by fsockopen() and pfsockopen().


Predefined Constants

The constants below are always available as part of the PHP core.

openlog() Options
Constant | Description
LOG_CONS | if there is an error while sending data to the system logger, write directly to the system console
LOG_NDELAY | open the connection to the logger immediately
LOG_ODELAY | (default) delay opening the connection until the first message is logged
LOG_NOWAIT |
LOG_PERROR | print log message also to standard error
LOG_PID | include PID with each message
openlog() Facilities
Constant | Description
LOG_AUTH | security/authorization messages (use LOG_AUTHPRIV instead in systems where that constant is defined)
LOG_AUTHPRIV | security/authorization messages (private)
LOG_CRON | clock daemon (cron and at)
LOG_DAEMON | other system daemons
LOG_KERN | kernel messages
LOG_LOCAL0 ... LOG_LOCAL7 | reserved for local use, these are not available in Windows
LOG_LPR | line printer subsystem
LOG_MAIL | mail subsystem
LOG_NEWS | USENET news subsystem
LOG_SYSLOG | messages generated internally by syslogd
LOG_USER | generic user-level messages
LOG_UUCP | UUCP subsystem
syslog() Priorities (in descending order)
Constant | Description
LOG_EMERG | system is unusable
LOG_ALERT | action must be taken immediately
LOG_CRIT | critical conditions
LOG_ERR | error conditions
LOG_WARNING | warning conditions
LOG_NOTICE | normal, but significant, condition
LOG_INFO | informational message
LOG_DEBUG | debug-level message
dns_get_record() Options
Constant | Description
DNS_A | IPv4 Address Resource
DNS_CAA | Certification Authority Authorization Resource (available as of PHP 7.0.16 and 7.1.2)
DNS_MX | Mail Exchanger Resource
DNS_CNAME | Alias (Canonical Name) Resource
DNS_NS | Authoritative Name Server Resource
DNS_PTR | Pointer Resource
DNS_HINFO | Host Info Resource (See IANA's » Operating System Names for the meaning of these values)
DNS_SOA | Start of Authority Resource
DNS_TXT | Text Resource
DNS_ANY | Any Resource Record. On most systems this returns all resource records, however it should not be counted upon for critical uses. Try DNS_ALL instead.
DNS_AAAA | IPv6 Address Resource
DNS_ALL | Iteratively query the name server for each available record type.


Network Functions

Table of Contents

  • checkdnsrr — Check DNS records corresponding to a given Internet host name or IP address
  • closelog — Close connection to system logger
  • define_syslog_variables — Initializes all syslog related variables
  • dns_check_record — Alias of checkdnsrr
  • dns_get_mx — Alias of getmxrr
  • dns_get_record — Fetch DNS Resource Records associated with a hostname
  • fsockopen — Open Internet or Unix domain socket connection
  • gethostbyaddr — Get the Internet host name corresponding to a given IP address
  • gethostbyname — Get the IPv4 address corresponding to a given Internet host name
  • gethostbynamel — Get a list of IPv4 addresses corresponding to a given Internet host name
  • gethostname — Gets the host name
  • getmxrr — Get MX records corresponding to a given Internet host name
  • getprotobyname — Get protocol number associated with protocol name
  • getprotobynumber — Get protocol name associated with protocol number
  • getservbyname — Get port number associated with an Internet service and protocol
  • getservbyport — Get Internet service which corresponds to port and protocol
  • header_register_callback — Call a header function
  • header_remove — Remove previously set headers
  • header — Send a raw HTTP header
  • headers_list — Returns a list of response headers sent (or ready to send)
  • headers_sent — Checks if or where headers have been sent
  • http_response_code — Get or Set the HTTP response code
  • inet_ntop — Converts a packed internet address to a human readable representation
  • inet_pton — Converts a human readable IP address to its packed in_addr representation
  • ip2long — Converts a string containing an (IPv4) Internet Protocol dotted address into a long integer
  • long2ip — Converts an long integer address into a string in (IPv4) Internet standard dotted format
  • openlog — Open connection to system logger
  • pfsockopen — Open persistent Internet or Unix domain socket connection
  • setcookie — Send a cookie
  • setrawcookie — Send a cookie without urlencoding the cookie value
  • socket_get_status — Alias of stream_get_meta_data
  • socket_set_blocking — Alias of stream_set_blocking
  • socket_set_timeout — Alias of stream_set_timeout
  • syslog — Generate a system log message


Check DNS records corresponding to a given Internet host name or IP address

  • « Network Functions
  • closelog »
  • PHP Manual
  • Network Functions
  • Check DNS records corresponding to a given Internet host name or IP address

checkdnsrr

(PHP 4, PHP 5, PHP 7)

checkdnsrr — Check DNS records corresponding to a given Internet host name or IP address

Description

checkdnsrr ( string $host [, string $type = "MX" ] ) : bool

Searches DNS for records of type type corresponding to host.

Parameters

host

host may either be the IP address in dotted-quad notation or the host name.

type

type may be any one of: A, MX, NS, SOA, PTR, CNAME, AAAA, A6, SRV, NAPTR, TXT or ANY.

Return Values

Returns TRUE if any records are found; returns FALSE if no records were found or if an error occurred.

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms.
5.2.4 | TXT type was added.

Notes

Note:

For compatibility with Windows before this was implemented, then try the » PEAR class » Net_DNS.

See Also

  • dns_get_record() - Fetch DNS Resource Records associated with a hostname
  • getmxrr() - Get MX records corresponding to a given Internet host name
  • gethostbyaddr() - Get the Internet host name corresponding to a given IP address
  • gethostbyname() - Get the IPv4 address corresponding to a given Internet host name
  • gethostbynamel() - Get a list of IPv4 addresses corresponding to a given Internet host name
  • the named(8) manual page


Close connection to system logger

  • « checkdnsrr
  • define_syslog_variables »
  • PHP Manual
  • Network Functions
  • Close connection to system logger

closelog

(PHP 4, PHP 5, PHP 7)

closelog — Close connection to system logger

Description

closelog ( void ) : bool

closelog() closes the descriptor being used to write to the system logger. The use of closelog() is optional.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • syslog() - Generate a system log message
  • openlog() - Open connection to system logger


Initializes all syslog related variables

  • « closelog
  • dns_check_record »
  • PHP Manual
  • Network Functions
  • Initializes all syslog related variables

define_syslog_variables

(PHP 4, PHP 5 < 5.4.0)

define_syslog_variables — Initializes all syslog related variables

Description

define_syslog_variables ( void ) : void

Initializes all variables used in the syslog functions.

Return Values

No value is returned.

Syslog variables
Variable | Constant equal | Meaning | Notes
$LOG_EMERG | LOG_EMERG | System is unusable |
$LOG_ALERT | LOG_ALERT | Immediate action required |
$LOG_CRIT | LOG_CRIT | Critical conditions |
$LOG_ERR | LOG_ERR |  |
$LOG_WARNING | LOG_WARNING |  |
$LOG_NOTICE | LOG_NOTICE |  |
$LOG_INFO | LOG_INFO |  |
$LOG_DEBUG | LOG_DEBUG |  |
$LOG_KERN | LOG_KERN |  |
$LOG_USER | LOG_USER | Genetic user level |
$LOG_MAIL | LOG_MAIL | Log to email |
$LOG_DAEMON | LOG_DAEMON | Other system daemons |
$LOG_AUTH | LOG_AUTH |  |
$LOG_SYSLOG | LOG_SYSLOG |  | Not available on Netware
$LOG_LPR | LOG_LPR |  |
$LOG_NEWS | LOG_NEWS | Usenet new | Not available on HP-UX
$LOG_CRON | LOG_CRON |  | Not available on all platforms
$LOG_AUTHPRIV | LOG_AUTHPRIV |  | Not available on AIX
$LOG_LOCAL0 | LOG_LOCAL0 |  | Not available on Windows and Netware
$LOG_LOCAL1 | LOG_LOCAL1 |  | Not available on Windows and Netware
$LOG_LOCAL2 | LOG_LOCAL2 |  | Not available on Windows and Netware
$LOG_LOCAL3 | LOG_LOCAL3 |  | Not available on Windows and Netware
$LOG_LOCAL4 | LOG_LOCAL4 |  | Not available on Windows and Netware
$LOG_LOCAL5 | LOG_LOCAL5 |  | Not available on Windows and Netware
$LOG_LOCAL6 | LOG_LOCAL6 |  | Not available on Windows and Netware
$LOG_LOCAL7 | LOG_LOCAL7 |  | Not available on Windows and Netware
$LOG_PID | LOG_PID |  |
$LOG_CONS | LOG_CONS |  |
$LOG_ODELAY | LOG_ODELAY |  |
$LOG_NDELAY | LOG_NDELAY |  |
$LOG_NOWAIT | LOG_NOWAIT |  | Not available on BeOS
$LOG_PERROR | LOG_PERROR |  | Not available on AIX
Warning

This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

Examples

Example #1 define_syslog_variables() example

<?php
// Check if syslog variables already is defined
if(!get_cfg_var('define_syslog_variables'))
{
    define_syslog_variables();
}

// Open the log
openlog('', $LOG_ODELAY, $LOG_MAIL | $LOG_USER);

// Continue script ...
?>

Changelog

Version | Description
5.4.0 | This function was removed from PHP.
5.3.0 | This function now throws an E_DEPRECATED notice.

See Also

  • openlog() - Open connection to system logger
  • syslog() - Generate a system log message
  • closelog() - Close connection to system logger


Alias of checkdnsrr

  • « define_syslog_variables
  • dns_get_mx »
  • PHP Manual
  • Network Functions
  • Alias of checkdnsrr

dns_check_record

(PHP 5, PHP 7)

dns_check_record — Alias of checkdnsrr()

Description

This function is an alias of: checkdnsrr().


Alias of getmxrr

  • « dns_check_record
  • dns_get_record »
  • PHP Manual
  • Network Functions
  • Alias of getmxrr

dns_get_mx

(PHP 5, PHP 7)

dns_get_mx — Alias of getmxrr()

Description

This function is an alias of: getmxrr().


Fetch DNS Resource Records associated with a hostname

  • « dns_get_mx
  • fsockopen »
  • PHP Manual
  • Network Functions
  • Fetch DNS Resource Records associated with a hostname

dns_get_record

(PHP 5, PHP 7)

dns_get_record — Fetch DNS Resource Records associated with a hostname

Description

dns_get_record ( string $hostname [, int $type = DNS_ANY [, array &$authns [, array &$addtl [, bool $raw = FALSE ]]]] ) : array

Fetch DNS Resource Records associated with the given hostname.

Parameters

hostname

hostname should be a valid DNS hostname such as "www.example.com". Reverse lookups can be generated using in-addr.arpa notation, but gethostbyaddr() is more suitable for the majority of reverse lookups.

Note:

Per DNS standards, email addresses are given in user.host format (for example: hostmaster.example.com as opposed to hostmaster@example.com), be sure to check this value and modify if necessary before using it with a functions such as mail().

type

By default, dns_get_record() will search for any resource records associated with hostname. To limit the query, specify the optional type parameter. May be any one of the following: DNS_A, DNS_CNAME, DNS_HINFO, DNS_CAA, DNS_MX, DNS_NS, DNS_PTR, DNS_SOA, DNS_TXT, DNS_AAAA, DNS_SRV, DNS_NAPTR, DNS_A6, DNS_ALL or DNS_ANY.

Note:

Because of eccentricities in the performance of libresolv between platforms, DNS_ANY will not always return every record, the slower DNS_ALL will collect all records more reliably.

authns

Passed by reference and, if given, will be populated with Resource Records for the Authoritative Name Servers.

addtl

Passed by reference and, if given, will be populated with any Additional Records.

raw

The type will be interpreted as a raw DNS type ID (the DNS_* constants cannot be used). The return value will contain a data key, which needs to be manually parsed.

Return Values

This function returns an array of associative arrays, or FALSE on failure. Each associative array contains at minimum the following keys:

Basic DNS attributes
Attribute | Meaning
host | The record in the DNS namespace to which the rest of the associated data refers.
class | dns_get_record() only returns Internet class records and as such this parameter will always return IN.
type | String containing the record type. Additional attributes will also be contained in the resulting array dependant on the value of type. See table below.
ttl | "Time To Live" remaining for this record. This will not equal the record's original ttl, but will rather equal the original ttl minus whatever length of time has passed since the authoritative name server was queried.

Other keys in associative arrays dependant on 'type'
Type | Extra Columns
A | ip: An IPv4 addresses in dotted decimal notation.
MX | pri: Priority of mail exchanger. Lower numbers indicate greater priority. target: FQDN of the mail exchanger. See also dns_get_mx().
CNAME | target: FQDN of location in DNS namespace to which the record is aliased.
NS | target: FQDN of the name server which is authoritative for this hostname.
PTR | target: Location within the DNS namespace to which this record points.
TXT | txt: Arbitrary string data associated with this record.
HINFO | cpu: IANA number designating the CPU of the machine referenced by this record. os: IANA number designating the Operating System on the machine referenced by this record. See IANA's » Operating System Names for the meaning of these values.
CAA | flags: A one-byte bitfield; currently only bit 0 is defined, meaning 'critical'; other bits are reserved and should be ignored. tag: The CAA tag name (alphanumeric ASCII string). value: The CAA tag value (binary string, may use subformats). For additional information see: » RFC 6844
SOA | mname: FQDN of the machine from which the resource records originated. rname: Email address of the administrative contact for this domain. serial: Serial # of this revision of the requested domain. refresh: Refresh interval (seconds) secondary name servers should use when updating remote copies of this domain. retry: Length of time (seconds) to wait after a failed refresh before making a second attempt. expire: Maximum length of time (seconds) a secondary DNS server should retain remote copies of the zone data without a successful refresh before discarding. minimum-ttl: Minimum length of time (seconds) a client can continue to use a DNS resolution before it should request a new resolution from the server. Can be overridden by individual resource records.
AAAA | ipv6: IPv6 address
A6(PHP >= 5.1.0) | masklen: Length (in bits) to inherit from the target specified by chain. ipv6: Address for this specific record to merge with chain. chain: Parent record to merge with ipv6 data.
SRV | pri: (Priority) lowest priorities should be used first. weight: Ranking to weight which of commonly prioritized targets should be chosen at random. target and port: hostname and port where the requested service can be found. For additional information see: » RFC 2782
NAPTR | order and pref: Equivalent to pri and weight above. flags, services, regex, and replacement: Parameters as defined by » RFC 2915.

Changelog

Version | Description
7.0.16, 7.1.2 | Added support for CAA record type.
5.4.0 | Added raw parameter.
5.3.0 | This function is now available on Windows platforms.
5.3.0 | Prior to this release, if the authns parameter was given, the addtl parameter was also required.

Examples

Example #1 Using dns_get_record()

<?php
$result = dns_get_record("php.net");
print_r($result);
?>

The above example will output something similar to:

Array
(
    [0] => Array
        (
            [host] => php.net
            [type] => MX
            [pri] => 5
            [target] => pair2.php.net
            [class] => IN
            [ttl] => 6765
        )

    [1] => Array
        (
            [host] => php.net
            [type] => A
            [ip] => 64.246.30.37
            [class] => IN
            [ttl] => 8125
        )

)

Example #2 Using dns_get_record() and DNS_ANY

Since it's very common to want the IP address of a mail server once the MX record has been resolved, dns_get_record() also returns an array in addtl which contains associate records. authns is returned as well containing a list of authoritative name servers.

<?php
/* Request "ANY" record for php.net,
   and create $authns and $addtl arrays
   containing list of name servers and
   any additional records which go with
   them */
$result = dns_get_record("php.net", DNS_ANY, $authns, $addtl);
echo "Result = ";
print_r($result);
echo "Auth NS = ";
print_r($authns);
echo "Additional = ";
print_r($addtl);
?>

The above example will output something similar to:

Result = Array
(
    [0] => Array
        (
            [host] => php.net
            [type] => MX
            [pri] => 5
            [target] => pair2.php.net
            [class] => IN
            [ttl] => 6765
        )

    [1] => Array
        (
            [host] => php.net
            [type] => A
            [ip] => 64.246.30.37
            [class] => IN
            [ttl] => 8125
        )

)
Auth NS = Array
(
    [0] => Array
        (
            [host] => php.net
            [type] => NS
            [target] => remote1.easydns.com
            [class] => IN
            [ttl] => 10722
        )

    [1] => Array
        (
            [host] => php.net
            [type] => NS
            [target] => remote2.easydns.com
            [class] => IN
            [ttl] => 10722
        )

    [2] => Array
        (
            [host] => php.net
            [type] => NS
            [target] => ns1.easydns.com
            [class] => IN
            [ttl] => 10722
        )

    [3] => Array
        (
            [host] => php.net
            [type] => NS
            [target] => ns2.easydns.com
            [class] => IN
            [ttl] => 10722
        )

)
Additional = Array
(
    [0] => Array
        (
            [host] => pair2.php.net
            [type] => A
            [ip] => 216.92.131.5
            [class] => IN
            [ttl] => 6766
        )

    [1] => Array
        (
            [host] => remote1.easydns.com
            [type] => A
            [ip] => 64.39.29.212
            [class] => IN
            [ttl] => 100384
        )

    [2] => Array
        (
            [host] => remote2.easydns.com
            [type] => A
            [ip] => 212.100.224.80
            [class] => IN
            [ttl] => 81241
        )

    [3] => Array
        (
            [host] => ns1.easydns.com
            [type] => A
            [ip] => 216.220.40.243
            [class] => IN
            [ttl] => 81241
        )

    [4] => Array
        (
            [host] => ns2.easydns.com
            [type] => A
            [ip] => 216.220.40.244
            [class] => IN
            [ttl] => 81241
        )

)

Notes

Note:

For compatibility with versions before PHP 5.3.0 on some operating systems, try the » PEAR class » Net_DNS.

See Also

  • dns_get_mx() - Alias of getmxrr
  • dns_check_record() - Alias of checkdnsrr


Open Internet or Unix domain socket connection

  • « dns_get_record
  • gethostbyaddr »
  • PHP Manual
  • Network Functions
  • Open Internet or Unix domain socket connection

fsockopen

(PHP 4, PHP 5, PHP 7)

fsockopen — Open Internet or Unix domain socket connection

Description

fsockopen ( string $hostname [, int $port = -1 [, int &$errno [, string &$errstr [, float $timeout = ini_get("default_socket_timeout") ]]]] ) : resource

Initiates a socket connection to the resource specified by hostname.

PHP supports targets in the Internet and Unix domains as described in List of Supported Socket Transports. A list of supported transports can also be retrieved using stream_get_transports().

The socket will by default be opened in blocking mode. You can switch it to non-blocking mode by using stream_set_blocking().

The function stream_socket_client() is similar but provides a richer set of options, including non-blocking connection and the ability to provide a stream context.

Parameters

hostname

If OpenSSL support is installed, you may prefix the hostname with either ssl:// or tls:// to use an SSL or TLS client connection over TCP/IP to connect to the remote host.

port

The port number. This can be omitted and skipped with -1 for transports that do not use ports, such as unix://.

errno

If provided, holds the system level error number that occurred in the system-level connect() call.

If the value returned in errno is 0 and the function returned FALSE, it is an indication that the error occurred before the connect() call. This is most likely due to a problem initializing the socket.

errstr

The error message as a string.

timeout

The connection timeout, in seconds.

Note:

If you need to set a timeout for reading/writing data over the socket, use stream_set_timeout(), as the timeout parameter to fsockopen() only applies while connecting the socket.

Return Values

fsockopen() returns a file pointer which may be used together with the other file functions (such as fgets(), fgetss(), fwrite(), fclose(), and feof()). If the call fails, it will return FALSE

Errors/Exceptions

Throws E_WARNING if hostname is not a valid domain.

Examples

Example #1 fsockopen() Example

<?php
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    $out = "GET / HTTP/1.1\r\n";
    $out .= "Host: www.example.com\r\n";
    $out .= "Connection: Close\r\n\r\n";
    fwrite($fp, $out);
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
}
?>

Example #2 Using UDP connection

The example below shows how to retrieve the day and time from the UDP service "daytime" (port 13) in your own machine.

<?php
$fp = fsockopen("udp://127.0.0.1", 13, $errno, $errstr);
if (!$fp) {
    echo "ERROR: $errno - $errstr<br />\n";
} else {
    fwrite($fp, "\n");
    echo fread($fp, 26);
    fclose($fp);
}
?>

Notes

Note:

Depending on the environment, the Unix domain or the optional connect timeout may not be available.

Warning

UDP sockets will sometimes appear to have opened without an error, even if the remote host is unreachable. The error will only become apparent when you read or write data to/from the socket. The reason for this is because UDP is a "connectionless" protocol, which means that the operating system does not try to establish a link for the socket until it actually needs to send or receive data.

Note: When specifying a numerical IPv6 address (e.g. fe80::1), you must enclose the IP in square brackets—for example, tcp://[fe80::1]:80.

See Also

  • pfsockopen() - Open persistent Internet or Unix domain socket connection
  • stream_socket_client() - Open Internet or Unix domain socket connection
  • stream_set_blocking() - Set blocking/non-blocking mode on a stream
  • stream_set_timeout() - Set timeout period on a stream
  • fgets() - Gets line from file pointer
  • fgetss() - Gets line from file pointer and strip HTML tags
  • fwrite() - Binary-safe file write
  • fclose() - Closes an open file pointer
  • feof() - Tests for end-of-file on a file pointer
  • socket_connect() - Initiates a connection on a socket
  • The Curl extension


Get the Internet host name corresponding to a given IP address

  • « fsockopen
  • gethostbyname »
  • PHP Manual
  • Network Functions
  • Get the Internet host name corresponding to a given IP address

gethostbyaddr

(PHP 4, PHP 5, PHP 7)

gethostbyaddr — Get the Internet host name corresponding to a given IP address

Description

gethostbyaddr ( string $ip_address ) : string

Returns the host name of the Internet host specified by ip_address.

Parameters

ip_address

The host IP address.

Return Values

Returns the host name on success, the unmodified ip_address on failure, or FALSE on malformed input.

Examples

Example #1 A simple gethostbyaddr() example

<?php
$hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);

echo $hostname;
?>

See Also

  • gethostbyname() - Get the IPv4 address corresponding to a given Internet host name
  • gethostbynamel() - Get a list of IPv4 addresses corresponding to a given Internet host name


Get the IPv4 address corresponding to a given Internet host name

  • « gethostbyaddr
  • gethostbynamel »
  • PHP Manual
  • Network Functions
  • Get the IPv4 address corresponding to a given Internet host name

gethostbyname

(PHP 4, PHP 5, PHP 7)

gethostbyname — Get the IPv4 address corresponding to a given Internet host name

Description

gethostbyname ( string $hostname ) : string

Returns the IPv4 address of the Internet host specified by hostname.

Parameters

hostname

The host name.

Return Values

Returns the IPv4 address or a string containing the unmodified hostname on failure.

Examples

Example #1 A simple gethostbyname() example

<?php
$ip = gethostbyname('www.example.com');

echo $ip;
?>

See Also

  • gethostbyaddr() - Get the Internet host name corresponding to a given IP address
  • gethostbynamel() - Get a list of IPv4 addresses corresponding to a given Internet host name
  • inet_pton() - Converts a human readable IP address to its packed in_addr representation
  • inet_ntop() - Converts a packed internet address to a human readable representation


Get a list of IPv4 addresses corresponding to a given Internet host name

  • « gethostbyname
  • gethostname »
  • PHP Manual
  • Network Functions
  • Get a list of IPv4 addresses corresponding to a given Internet host name

gethostbynamel

(PHP 4, PHP 5, PHP 7)

gethostbynamel — Get a list of IPv4 addresses corresponding to a given Internet host name

Description

gethostbynamel ( string $hostname ) : array

Returns a list of IPv4 addresses to which the Internet host specified by hostname resolves.

Parameters

hostname

The host name.

Return Values

Returns an array of IPv4 addresses or FALSE if hostname could not be resolved.

Examples

Example #1 gethostbynamel() example

<?php
$hosts = gethostbynamel('www.example.com');
print_r($hosts);
?>

The above example will output:

Array
(
    [0] => 192.0.34.166
)

See Also

  • gethostbyname() - Get the IPv4 address corresponding to a given Internet host name
  • gethostbyaddr() - Get the Internet host name corresponding to a given IP address
  • checkdnsrr() - Check DNS records corresponding to a given Internet host name or IP address
  • getmxrr() - Get MX records corresponding to a given Internet host name
  • the named(8) manual page


Gets the host name

  • « gethostbynamel
  • getmxrr »
  • PHP Manual
  • Network Functions
  • Gets the host name

gethostname

(PHP 5 >= 5.3.0, PHP 7)

gethostname — Gets the host name

Description

gethostname ( void ) : string

gethostname() gets the standard host name for the local machine.

Return Values

Returns a string with the hostname on success, otherwise FALSE is returned.

Examples

Example #1 A simple gethostname() example

<?php
echo gethostname(); // may output e.g,: sandie

// Or, an option that also works before PHP 5.3
echo php_uname('n'); // may output e.g,: sandie
?>

See Also

  • gethostbyname() - Get the IPv4 address corresponding to a given Internet host name
  • gethostbyaddr() - Get the Internet host name corresponding to a given IP address
  • php_uname() - Returns information about the operating system PHP is running on


Get MX records corresponding to a given Internet host name

  • « gethostname
  • getprotobyname »
  • PHP Manual
  • Network Functions
  • Get MX records corresponding to a given Internet host name

getmxrr

(PHP 4, PHP 5, PHP 7)

getmxrr — Get MX records corresponding to a given Internet host name

Description

getmxrr ( string $hostname , array &$mxhosts [, array &$weight ] ) : bool

Searches DNS for MX records corresponding to hostname.

Parameters

hostname

The Internet host name.

mxhosts

A list of the MX records found is placed into the array mxhosts.

weight

If the weight array is given, it will be filled with the weight information gathered.

Return Values

Returns TRUE if any records are found; returns FALSE if no records were found or if an error occurred.

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms.

Notes

Note:

This function should not be used for the purposes of address verification. Only the mailexchangers found in DNS are returned, however, according to » RFC 2821 when no mail exchangers are listed, hostname itself should be used as the only mail exchanger with a priority of 0.

Note:

For compatibility with Windows before this was implemented, then try the » PEAR class » Net_DNS.

See Also

  • checkdnsrr() - Check DNS records corresponding to a given Internet host name or IP address
  • dns_get_record() - Fetch DNS Resource Records associated with a hostname
  • gethostbyname() - Get the IPv4 address corresponding to a given Internet host name
  • gethostbynamel() - Get a list of IPv4 addresses corresponding to a given Internet host name
  • gethostbyaddr() - Get the Internet host name corresponding to a given IP address
  • the named(8) manual page


Get protocol number associated with protocol name

  • « getmxrr
  • getprotobynumber »
  • PHP Manual
  • Network Functions
  • Get protocol number associated with protocol name

getprotobyname

(PHP 4, PHP 5, PHP 7)

getprotobyname — Get protocol number associated with protocol name

Description

getprotobyname ( string $name ) : int

getprotobyname() returns the protocol number associated with the protocol name as per /etc/protocols.

Parameters

name

The protocol name.

Return Values

Returns the protocol number, or FALSE on failure.

Examples

Example #1 getprotobyname() example

<?php
$protocol = 'tcp';
$get_prot = getprotobyname($protocol);
if ($get_prot === FALSE) {
    echo 'Invalid Protocol';
} else {
    echo 'Protocol #' . $get_prot;
}
?>

See Also

  • getprotobynumber() - Get protocol name associated with protocol number


Get protocol name associated with protocol number

  • « getprotobyname
  • getservbyname »
  • PHP Manual
  • Network Functions
  • Get protocol name associated with protocol number

getprotobynumber

(PHP 4, PHP 5, PHP 7)

getprotobynumber — Get protocol name associated with protocol number

Description

getprotobynumber ( int $number ) : string

getprotobynumber() returns the protocol name associated with protocol number as per /etc/protocols.

Parameters

number

The protocol number.

Return Values

Returns the protocol name as a string, or FALSE on failure.

See Also

  • getprotobyname() - Get protocol number associated with protocol name


Get port number associated with an Internet service and protocol

  • « getprotobynumber
  • getservbyport »
  • PHP Manual
  • Network Functions
  • Get port number associated with an Internet service and protocol

getservbyname

(PHP 4, PHP 5, PHP 7)

getservbyname — Get port number associated with an Internet service and protocol

Description

getservbyname ( string $service , string $protocol ) : int

getservbyname() returns the Internet port which corresponds to service for the specified protocol as per /etc/services.

Parameters

service

The Internet service name, as a string.

protocol

protocol is either "tcp" or "udp" (in lowercase).

Return Values

Returns the port number, or FALSE if service or protocol is not found.

Examples

Example #1 getservbyname() example

<?php
$services = array('http', 'ftp', 'ssh', 'telnet', 'imap',
'smtp', 'nicname', 'gopher', 'finger', 'pop3', 'www');

foreach ($services as $service) {
    $port = getservbyname($service, 'tcp');
    echo $service . ": " . $port . "<br />\n";
}
?>

See Also

  • getservbyport() - Get Internet service which corresponds to port and protocol
  • » http://www.iana.org/assignments/port-numbers for a complete list of port numbers.


Get Internet service which corresponds to port and protocol

  • « getservbyname
  • header_register_callback »
  • PHP Manual
  • Network Functions
  • Get Internet service which corresponds to port and protocol

getservbyport

(PHP 4, PHP 5, PHP 7)

getservbyport — Get Internet service which corresponds to port and protocol

Description

getservbyport ( int $port , string $protocol ) : string

getservbyport() returns the Internet service associated with port for the specified protocol as per /etc/services.

Parameters

port

The port number.

protocol

protocol is either "tcp" or "udp" (in lowercase).

Return Values

Returns the Internet service name as a string.

See Also

  • getservbyname() - Get port number associated with an Internet service and protocol


Call a header function

  • « getservbyport
  • header_remove »
  • PHP Manual
  • Network Functions
  • Call a header function

header_register_callback

(PHP 5 >= 5.4.0, PHP 7)

header_register_callback — Call a header function

Description

header_register_callback ( callable $callback ) : bool

Registers a function that will be called when PHP starts sending output.

The callback is executed just after PHP prepares all headers to be sent, and before any other output is sent, creating a window to manipulate the outgoing headers before being sent.

Parameters

callback

Function called just before the headers are sent. It gets no parameters and the return value is ignored.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 header_register_callback() example

<?php

header('Content-Type: text/plain');
header('X-Test: foo');

function foo() {
 foreach (headers_list() as $header) {
   if (strpos($header, 'X-Powered-By:') !== false) {
     header_remove('X-Powered-By');
   }
   header_remove('X-Test');
 }
}

$result = header_register_callback('foo');
echo "a";
?>

The above example will output something similar to:

Content-Type: text/plain

a

Notes

header_register_callback() is executed just as the headers are about to be sent out, so any output from this function can break output.

Note:

Headers will only be accessible and output when a SAPI that supports them is in use.

See Also

  • headers_list() - Returns a list of response headers sent (or ready to send)
  • header_remove() - Remove previously set headers
  • header() - Send a raw HTTP header


Remove previously set headers

  • « header_register_callback
  • header »
  • PHP Manual
  • Network Functions
  • Remove previously set headers

header_remove

(PHP 5 >= 5.3.0, PHP 7)

header_remove — Remove previously set headers

Description

header_remove ([ string $name ] ) : void

Removes an HTTP header previously set using header().

Parameters

name

The header name to be removed.

Note: This parameter is case-insensitive.

Return Values

No value is returned.

Examples

Example #1 Unsetting specific header.

<?php
header("X-Foo: Bar");
header("X-Bar: Baz");
header_remove("X-Foo");
?>

The above example will output something similar to:

X-Bar: Baz

Example #2 Unsetting all previously set headers.

<?php
header("X-Foo: Bar");
header("X-Bar: Baz");
header_remove();
?>

The above example will output something similar to:

Notes

Caution

    This function will remove all headers set by PHP,
    including cookies, session and the X-Powered-By headers.

Note:

    Headers will only be accessible and output when a SAPI that supports them
    is in use.

See Also

  • header() - Send a raw HTTP header
    •

  • headers_sent() - Checks if or where headers have been sent
    •


Send a raw HTTP header

  • « header_remove
  • headers_list »
  • PHP Manual
  • Network Functions
  • Send a raw HTTP header

header

(PHP 4, PHP 5, PHP 7)

header — Send a raw HTTP header

Description

header ( string $header [, bool $replace = TRUE [, int $http_response_code ]] ) : void

header() is used to send a raw HTTP header. See the » HTTP/1.1 specification for more information on HTTP headers.

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.

<html>
<?php
/* This will give an error. Note the output
 * above, which is before the header() call */
header('Location: http://www.example.com/');
exit;
?>

Parameters

header

The header string.

There are two special-case header calls. The first is a header that starts with the string "HTTP/" (case is not significant), which will be used to figure out the HTTP status code to send. For example, if you have configured Apache to use a PHP script to handle requests for missing files (using the ErrorDocument directive), you may want to make sure that your script generates the proper status code.

<?php
header("HTTP/1.0 404 Not Found");
?>

The second special case is the "Location:" header. Not only does it send this header back to the browser, but it also returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set.

<?php
header("Location: http://www.example.com/"); /* Redirect browser */

/* Make sure that code below does not get executed when we redirect. */
exit;
?>

replace

The optional replace parameter indicates whether the header should replace a previous similar header, or add a second header of the same type. By default it will replace, but if you pass in FALSE as the second argument you can force multiple headers of the same type. For example:

<?php
header('WWW-Authenticate: Negotiate');
header('WWW-Authenticate: NTLM', false);
?>

http_response_code

Forces the HTTP response code to the specified value. Note that this parameter only has an effect if the header is not empty.

Return Values

No value is returned.

Changelog

Version | Description
5.1.2 | This function now prevents more than one header to be sent at once as a protection against header injection attacks.

Examples

Example #1 Download dialog

If you want the user to be prompted to save the data you are sending, such as a generated PDF file, you can use the » Content-Disposition header to supply a recommended filename and force the browser to display the save dialog.

<?php
// We'll be outputting a PDF
header('Content-Type: application/pdf');

// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');

// The PDF source is in original.pdf
readfile('original.pdf');
?>

Example #2 Caching directives

PHP scripts often generate dynamic content that must not be cached by the client browser or any proxy caches between the server and the client browser. Many proxies and clients can be forced to disable caching with:

<?php
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
?>

Note:

You may find that your pages aren't cached even if you don't output all of the headers above. There are a number of options that users may be able to set for their browser that change its default caching behavior. By sending the headers above, you should override any settings that may otherwise cause the output of your script to be cached.

Additionally, session_cache_limiter() and the session.cache_limiter configuration setting can be used to automatically generate the correct caching-related headers when sessions are being used.

Notes

Note:

Headers will only be accessible and output when a SAPI that supports them is in use.

Note:

You can use output buffering to get around this problem, with the overhead of all of your output to the browser being buffered in the server until you send it. You can do this by calling ob_start() and ob_end_flush() in your script, or setting the output_buffering configuration directive on in your php.ini or server configuration files.

Note:

The HTTP status header line will always be the first sent to the client, regardless of the actual header() call being the first or not. The status may be overridden by calling header() with a new status line at any time unless the HTTP headers have already been sent.

Note:

There is a bug in Microsoft Internet Explorer 4.01 that prevents this from working. There is no workaround. There is also a bug in Microsoft Internet Explorer 5.5 that interferes with this, which can be resolved by upgrading to Service Pack 2 or later.

Note: If safe mode is enabled the uid of the script is added to the realm part of the WWW-Authenticate header if you set this header (used for HTTP Authentication).

Note:

Most contemporary clients accept relative URIs as argument to » Location:, but some older clients require an absolute URI including the scheme, hostname and absolute path. You can usually use $_SERVER['HTTP_HOST'], $_SERVER['PHP_SELF'] and dirname() to make an absolute URI from a relative one yourself:

<?php
/* Redirect to a different page in the current directory that was requested */
$host  = $_SERVER['HTTP_HOST'];
$uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'mypage.php';
header("Location: http://$host$uri/$extra");
exit;
?>

Note:

Session ID is not passed with Location header even if session.use_trans_sid is enabled. It must by passed manually using SID constant.

See Also

  • headers_sent() - Checks if or where headers have been sent
  • setcookie() - Send a cookie
  • http_response_code() - Get or Set the HTTP response code
  • header_remove() - Remove previously set headers
  • The section on HTTP authentication


Returns a list of response headers sent (or ready to send)

  • « header
  • headers_sent »
  • PHP Manual
  • Network Functions
  • Returns a list of response headers sent (or ready to send)

headers_list

(PHP 5, PHP 7)

headers_list — Returns a list of response headers sent (or ready to send)

Description

headers_list ( void ) : array

headers_list() will return a list of headers to be sent to the browser / client. To determine whether or not these headers have been sent yet, use headers_sent().

Return Values

Returns a numerically indexed array of headers.

Examples

Example #1 Examples using headers_list()

<?php

/* setcookie() will add a response header on its own */
setcookie('foo', 'bar');

/* Define a custom response header
   This will be ignored by most clients */
header("X-Sample-Test: foo");

/* Specify plain text content in our response */
header('Content-type: text/plain');

/* What headers are going to be sent? */
var_dump(headers_list());

?>

The above example will output:

array(4) {
  [0]=>
  string(23) "X-Powered-By: PHP/5.1.3"
  [1]=>
  string(19) "Set-Cookie: foo=bar"
  [2]=>
  string(18) "X-Sample-Test: foo"
  [3]=>
  string(24) "Content-type: text/plain"
}

Notes

Note:

Headers will only be accessible and output when a SAPI that supports them is in use.

See Also

  • headers_sent() - Checks if or where headers have been sent
  • header() - Send a raw HTTP header
  • setcookie() - Send a cookie
  • apache_response_headers() - Fetch all HTTP response headers
  • http_response_code() - Get or Set the HTTP response code


Checks if or where headers have been sent

  • « headers_list
  • http_response_code »
  • PHP Manual
  • Network Functions
  • Checks if or where headers have been sent

headers_sent

(PHP 4, PHP 5, PHP 7)

headers_sent — Checks if or where headers have been sent

Description

headers_sent ([ string &$file [, int &$line ]] ) : bool

Checks if or where headers have been sent.

You can't add any more header lines using the header() function once the header block has already been sent. Using this function you can at least prevent getting HTTP header related error messages. Another option is to use Output Buffering.

Parameters

file

If the optional file and line parameters are set, headers_sent() will put the PHP source file name and line number where output started in the file and line variables.

line

The line number where the output started.

Return Values

headers_sent() will return FALSE if no HTTP headers have already been sent or TRUE otherwise.

Examples

Example #1 Examples using headers_sent()

<?php

// If no headers are sent, send one
if (!headers_sent()) {
    header('Location: http://www.example.com/');
    exit;
}

// An example using the optional file and line parameters
// Note that $filename and $linenum are passed in for later use.
// Do not assign them values beforehand.
if (!headers_sent($filename, $linenum)) {
    header('Location: http://www.example.com/');
    exit;

// You would most likely trigger an error here.
} else {

    echo "Headers already sent in $filename on line $linenum\n" .
          "Cannot redirect, for now please click this <a " .
          "href=\"http://www.example.com\">link</a> instead\n";
    exit;
}

?>

Notes

Note:

Headers will only be accessible and output when a SAPI that supports them is in use.

See Also

  • ob_start() - Turn on output buffering
  • trigger_error() - Generates a user-level error/warning/notice message
  • headers_list() - Returns a list of response headers sent (or ready to send)
  • header() - Send a raw HTTP header for a more detailed discussion of the matters involved.


Get or Set the HTTP response code

  • « headers_sent
  • inet_ntop »
  • PHP Manual
  • Network Functions
  • Get or Set the HTTP response code

http_response_code

(PHP 5 >= 5.4.0, PHP 7)

http_response_code — Get or Set the HTTP response code

Description

http_response_code ([ int $response_code ] ) : mixed

Gets or sets the HTTP response status code.

Parameters

response_code

The optional response_code will set the response code.

Return Values

If response_code is provided, then the previous status code will be returned. If response_code is not provided, then the current status code will be returned. Both of these values will default to a 200 status code if used in a web server environment.

FALSE will be returned if response_code is not provided and it is not invoked in a web server environment (such as from a CLI application). TRUE will be returned if response_code is provided and it is not invoked in a web server environment (but only when no previous response status has been set).

Examples

Example #1 Using http_response_code() in a web server environment

<?php

// Get the current response code and set a new one
var_dump(http_response_code(404));

// Get the new response code
var_dump(http_response_code());
?>

The above example will output:

int(200)
int(404)

Example #2 Using http_response_code() in a CLI environment

<?php

// Get the current default response code
var_dump(http_response_code());

// Set a response code
var_dump(http_response_code(201));

// Get the new response code
var_dump(http_response_code());
?>

The above example will output:

bool(false)
bool(true)
int(201)

See Also

  • header() - Send a raw HTTP header
  • headers_list() - Returns a list of response headers sent (or ready to send)


Converts a packed internet address to a human readable representation

  • « http_response_code
  • inet_pton »
  • PHP Manual
  • Network Functions
  • Converts a packed internet address to a human readable representation

inet_ntop

(PHP 5 >= 5.1.0, PHP 7)

inet_ntop — Converts a packed internet address to a human readable representation

Description

inet_ntop ( string $in_addr ) : string

This function converts a 32bit IPv4, or 128bit IPv6 address (if PHP was built with IPv6 support enabled) into an address family appropriate string representation.

Parameters

in_addr

A 32bit IPv4, or 128bit IPv6 address.

Return Values

Returns a string representation of the address or FALSE on failure.

Examples

Example #1 inet_ntop() Example

<?php
$packed = chr(127) . chr(0) . chr(0) . chr(1);
$expanded = inet_ntop($packed);

/* Outputs: 127.0.0.1 */
echo $expanded;

$packed = str_repeat(chr(0), 15) . chr(1);
$expanded = inet_ntop($packed);

/* Outputs: ::1 */
echo $expanded;
?>

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms.

See Also

  • long2ip() - Converts an long integer address into a string in (IPv4) Internet standard dotted format
  • ip2long() - Converts a string containing an (IPv4) Internet Protocol dotted address into a long integer
  • inet_pton() - Converts a human readable IP address to its packed in_addr representation


Converts a human readable IP address to its packed in_addr representation

  • « inet_ntop
  • ip2long »
  • PHP Manual
  • Network Functions
  • Converts a human readable IP address to its packed in_addr representation

inet_pton

(PHP 5 >= 5.1.0, PHP 7)

inet_pton — Converts a human readable IP address to its packed in_addr representation

Description

inet_pton ( string $address ) : string

This function converts a human readable IPv4 or IPv6 address (if PHP was built with IPv6 support enabled) into an address family appropriate 32bit or 128bit binary structure.

Parameters

address

A human readable IPv4 or IPv6 address.

Return Values

Returns the in_addr representation of the given address, or FALSE if a syntactically invalid address is given (for example, an IPv4 address without dots or an IPv6 address without colons).

Examples

Example #1 inet_pton() Example

<?php
$in_addr = inet_pton('127.0.0.1');

$in6_addr = inet_pton('::1');
?>

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms.

See Also

  • ip2long() - Converts a string containing an (IPv4) Internet Protocol dotted address into a long integer
  • long2ip() - Converts an long integer address into a string in (IPv4) Internet standard dotted format
  • inet_ntop() - Converts a packed internet address to a human readable representation


Converts a string containing an (IPv4) Internet Protocol dotted address into a long integer

  • « inet_pton
  • long2ip »
  • PHP Manual
  • Network Functions
  • Converts a string containing an (IPv4) Internet Protocol dotted address into a long integer

ip2long

(PHP 4, PHP 5, PHP 7)

ip2long — Converts a string containing an (IPv4) Internet Protocol dotted address into a long integer

Description

ip2long ( string $ip_address ) : int

The function ip2long() generates a long integer representation of IPv4 Internet network address from its Internet standard format (dotted string) representation.

ip2long() will also work with non-complete IP addresses. Read » http://publibn.boulder.ibm.com/doc_link/en_US/a_doc_lib/libs/commtrf2/inet_addr.htm for more info.

Parameters

ip_address

A standard format address.

Return Values

Returns the long integer or FALSE if ip_address is invalid.

Changelog

Version | Description
5.5.0 | Prior to this version, on Windows ip2long() would sometimes return a valid number even if passed a value which was not an (IPv4) Internet Protocol dotted address.
5.2.10 | Prior to this version, ip2long() would sometimes return a valid number even if passed a value which was not an (IPv4) Internet Protocol dotted address.

Examples

Example #1 ip2long() Example

<?php
$ip = gethostbyname('www.example.com');
$out = "The following URLs are equivalent:<br />\n";
$out .= 'http://www.example.com/, http://' . $ip . '/, and http://' . sprintf("%u", ip2long($ip)) . "/<br />\n";
echo $out;
?>

Example #2 Displaying an IP address

This second example shows how to print a converted address with the printf() function:

<?php
$ip   = gethostbyname('www.example.com');
$long = ip2long($ip);

if ($long == -1 || $long === FALSE) {
    echo 'Invalid IP, please try again';
} else {
    echo $ip   . "\n";            // 192.0.34.166
    echo $long . "\n";            // 3221234342 (-1073732954 on 32-bit systems, due to integer overflow)
    printf("%u\n", ip2long($ip)); // 3221234342
}
?>

Notes

Note:

Because PHP's integer type is signed, and many IP addresses will result in negative integers on 32-bit architectures, you need to use the "%u" formatter of sprintf() or printf() to get the string representation of the unsigned IP address.

Note:

ip2long() will return FALSE for the IP 255.255.255.255 in PHP 5 <= 5.0.2, and -1 on 64-bits systems in PHP 5 <=5.2.4. It was fixed in PHP 5.2.5 where it returns 4294967295. 32-bit systems will return -1 due to the integer value overflowing.

See Also

  • long2ip() - Converts an long integer address into a string in (IPv4) Internet standard dotted format
  • sprintf() - Return a formatted string


Converts an long integer address into a string in (IPv4) Internet standard dotted format

  • « ip2long
  • openlog »
  • PHP Manual
  • Network Functions
  • Converts an long integer address into a string in (IPv4) Internet standard dotted format

long2ip

(PHP 4, PHP 5, PHP 7)

long2ip — Converts an long integer address into a string in (IPv4) Internet standard dotted format

Description

long2ip ( int $proper_address ) : string

The function long2ip() generates an Internet address in dotted format (i.e.: aaa.bbb.ccc.ddd) from the long integer representation.

Parameters

proper_address

A proper address representation in long integer.

Return Values

Returns the Internet IP address as a string.

Changelog

Version | Description
7.1.0 | The parameter type of proper_address has been changed from string to integer.

Notes

Note:

On 32-bit architectures, casting integer representations of IP addresses from string to integer will not give correct results for numbers which exceed PHP_INT_MAX.

See Also

  • ip2long() - Converts a string containing an (IPv4) Internet Protocol dotted address into a long integer


Open connection to system logger

  • « long2ip
  • pfsockopen »
  • PHP Manual
  • Network Functions
  • Open connection to system logger

openlog

(PHP 4, PHP 5, PHP 7)

openlog — Open connection to system logger

Description

openlog ( string $ident , int $option , int $facility ) : bool

openlog() opens a connection to the system logger for a program.

The use of openlog() is optional. It will automatically be called by syslog() if necessary, in which case ident will default to FALSE.

Parameters

ident

The string ident is added to each message.

option

The option argument is used to indicate what logging options will be used when generating a log message.

openlog() Options
Constant | Description
LOG_CONS | if there is an error while sending data to the system logger, write directly to the system console
LOG_NDELAY | open the connection to the logger immediately
LOG_ODELAY | (default) delay opening the connection until the first message is logged
LOG_PERROR | print log message also to standard error
LOG_PID | include PID with each message
You can use one or more of these options. When using multiple options you need to OR them, i.e. to open the connection immediately, write to the console and include the PID in each message, you will use: LOG_CONS | LOG_NDELAY | LOG_PID

facility

The facility argument is used to specify what type of program is logging the message. This allows you to specify (in your machine's syslog configuration) how messages coming from different facilities will be handled.

openlog() Facilities
Constant | Description
LOG_AUTH | security/authorization messages (use LOG_AUTHPRIV instead in systems where that constant is defined)
LOG_AUTHPRIV | security/authorization messages (private)
LOG_CRON | clock daemon (cron and at)
LOG_DAEMON | other system daemons
LOG_KERN | kernel messages
LOG_LOCAL0 ... LOG_LOCAL7 | reserved for local use, these are not available in Windows
LOG_LPR | line printer subsystem
LOG_MAIL | mail subsystem
LOG_NEWS | USENET news subsystem
LOG_SYSLOG | messages generated internally by syslogd
LOG_USER | generic user-level messages
LOG_UUCP | UUCP subsystem

Note:

LOG_USER is the only valid log type under Windows operating systems

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • syslog() - Generate a system log message
  • closelog() - Close connection to system logger


Open persistent Internet or Unix domain socket connection

  • « openlog
  • setcookie »
  • PHP Manual
  • Network Functions
  • Open persistent Internet or Unix domain socket connection

pfsockopen

(PHP 4, PHP 5, PHP 7)

pfsockopen — Open persistent Internet or Unix domain socket connection

Description

pfsockopen ( string $hostname [, int $port = -1 [, int &$errno [, string &$errstr [, float $timeout = ini_get("default_socket_timeout") ]]]] ) : resource

This function behaves exactly as fsockopen() with the difference that the connection is not closed after the script finishes. It is the persistent version of fsockopen().

Parameters

For parameter information, see the fsockopen() documentation.

See Also

  • fsockopen() - Open Internet or Unix domain socket connection


Send a cookie

  • « pfsockopen
  • setrawcookie »
  • PHP Manual
  • Network Functions
  • Send a cookie

setcookie

(PHP 4, PHP 5, PHP 7)

setcookie — Send a cookie

Description

setcookie ( string $name [, string $value = "" [, int $expires = 0 [, string $path = "" [, string $domain = "" [, bool $secure = FALSE [, bool $httponly = FALSE ]]]]]] ) : bool
setcookie ( string $name [, string $value = "" [, array $options = [] ]] ) : bool

setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including <html> and <head> tags as well as any whitespace.

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE array. Cookie values may also exist in $_REQUEST.

Parameters

» RFC 6265 provides the normative reference on how each setcookie() parameter is interpreted.

name

The name of the cookie.

value

The value of the cookie. This value is stored on the clients computer; do not store sensitive information. Assuming the name is 'cookiename', this value is retrieved through $_COOKIE['cookiename']

expires

The time the cookie expires. This is a Unix timestamp so is in number of seconds since the epoch. In other words, you'll most likely set this with the time() function plus the number of seconds before you want it to expire. Or you might use mktime(). time()+60*60*24*30 will set the cookie to expire in 30 days. If set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes).

Note:

You may notice the expires parameter takes on a Unix timestamp, as opposed to the date format Wdy, DD-Mon-YYYY HH:MM:SS GMT, this is because PHP does this conversion internally.

path

The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain. If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. The default value is the current directory that the cookie is being set in.

domain

The (sub)domain that the cookie is available to. Setting this to a subdomain (such as 'www.example.com') will make the cookie available to that subdomain and all other sub-domains of it (i.e. w2.www.example.com). To make the cookie available to the whole domain (including all subdomains of it), simply set the value to the domain name ('example.com', in this case).

Older browsers still implementing the deprecated » RFC 2109 may require a leading . to match all subdomains.

secure

Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client. When set to TRUE, the cookie will only be set if a secure connection exists. On the server-side, it's on the programmer to send this kind of cookie only on secure connection (e.g. with respect to $_SERVER["HTTPS"]).

httponly

When TRUE the cookie will be made accessible only through the HTTP protocol. This means that the cookie won't be accessible by scripting languages, such as JavaScript. It has been suggested that this setting can effectively help to reduce identity theft through XSS attacks (although it is not supported by all browsers), but that claim is often disputed. Added in PHP 5.2.0. TRUE or FALSE

options

An associative array which may have any of the keys expires, path, domain, secure, httponly and samesite. The values have the same meaning as described for the parameters with the same name. The value of the samesite element should be either None, Lax or Strict. If any of the allowed options are not given, their default values are the same as the default values of the explicit parameters. If the samesite element is omitted, no SameSite cookie attribute is set.

Return Values

If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie.

Examples

Some examples follow how to send cookies:

Example #1 setcookie() send example

<?php
$value = 'something from somewhere';

setcookie("TestCookie", $value);
setcookie("TestCookie", $value, time()+3600);  /* expire in 1 hour */
setcookie("TestCookie", $value, time()+3600, "/~rasmus/", "example.com", 1);
?>

Note that the value portion of the cookie will automatically be urlencoded when you send the cookie, and when it is received, it is automatically decoded and assigned to a variable by the same name as the cookie name. If you don't want this, you can use setrawcookie() instead if you are using PHP 5. To see the contents of our test cookie in a script, simply use one of the following examples:

<?php
// Print an individual cookie
echo $_COOKIE["TestCookie"];

// Another way to debug/test is to view all cookies
print_r($_COOKIE);
?>

Example #2 setcookie() delete example

When deleting a cookie you should assure that the expiration date is in the past, to trigger the removal mechanism in your browser. Examples follow how to delete cookies sent in previous example:

<?php
// set the expiration date to one hour ago
setcookie("TestCookie", "", time() - 3600);
setcookie("TestCookie", "", time() - 3600, "/~rasmus/", "example.com", 1);
?>

Example #3 setcookie() and arrays

You may also set array cookies by using array notation in the cookie name. This has the effect of setting as many cookies as you have array elements, but when the cookie is received by your script, the values are all placed in an array with the cookie's name:

<?php
// set the cookies
setcookie("cookie[three]", "cookiethree");
setcookie("cookie[two]", "cookietwo");
setcookie("cookie[one]", "cookieone");

// after the page reloads, print them out
if (isset($_COOKIE['cookie'])) {
    foreach ($_COOKIE['cookie'] as $name => $value) {
        $name = htmlspecialchars($name);
        $value = htmlspecialchars($value);
        echo "$name : $value <br />\n";
    }
}
?>

The above example will output:

three : cookiethree
two : cookietwo
one : cookieone

Changelog

Version | Description
7.3.0 | An alternative signature supporting an options array has been added. This signature supports also setting of the SameSite cookie attribute.
5.5.0 | A Max-Age attribute is now included in the Set-Cookie header sent to the client.
5.2.0 | The httponly parameter was added.

Notes

Note:

You can use output buffering to send output prior to the call of this function, with the overhead of all of your output to the browser being buffered in the server until you send it. You can do this by calling ob_start() and ob_end_flush() in your script, or setting the output_buffering configuration directive on in your php.ini or server configuration files.

Note:

If the PHP directive register_globals is set to on then cookie values will also be made into variables. In our examples below, $TestCookie will exist. It's recommended to use $_COOKIE.

Common Pitfalls:

  • Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expires parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.
  • Cookies must be deleted with the same parameters as they were set with. If the value argument is an empty string, or FALSE, and all other arguments match a previous call to setcookie, then the cookie with the specified name will be deleted from the remote client. This is internally achieved by setting value to 'deleted' and expiration time to one year in past.
  • Because setting a cookie with a value of FALSE will try to delete the cookie, you should not use boolean values. Instead, use 0 for FALSE and 1 for TRUE.
  • Cookies names can be set as array names and will be available to your PHP scripts as arrays but separate cookies are stored on the user's system. Consider explode() to set one cookie with multiple names and values. It is not recommended to use serialize() for this purpose, because it can result in security holes.

Multiple calls to setcookie() are performed in the order called.

See Also

  • header() - Send a raw HTTP header
  • setrawcookie() - Send a cookie without urlencoding the cookie value
  • cookies section
  • » RFC 6265
  • » RFC 2109


Send a cookie without urlencoding the cookie value

  • « setcookie
  • socket_get_status »
  • PHP Manual
  • Network Functions
  • Send a cookie without urlencoding the cookie value

setrawcookie

(PHP 5, PHP 7)

setrawcookie — Send a cookie without urlencoding the cookie value

Description

setrawcookie ( string $name [, string $value [, int $expires = 0 [, string $path [, string $domain [, bool $secure = FALSE [, bool $httponly = FALSE ]]]]]] ) : bool
setrawcookie ( string $name [, string $value [, array $options = [] ]] ) : bool

setrawcookie() is exactly the same as setcookie() except that the cookie value will not be automatically urlencoded when sent to the browser.

Parameters

For parameter information, see the setcookie() documentation.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.3.0 | An alternative signature supporting an options array has been added. This signature supports also setting of the SameSite cookie attribute.
5.5.0 | A Max-Age attribute is now included in the Set-Cookie header sent to the client.
5.2.0 | The httponly parameter was added.

See Also

  • setcookie() - Send a cookie


Alias of stream_get_meta_data

  • « setrawcookie
  • socket_set_blocking »
  • PHP Manual
  • Network Functions
  • Alias of stream_get_meta_data

socket_get_status

(PHP 4, PHP 5, PHP 7)

socket_get_status — Alias of stream_get_meta_data()

Description

This function is an alias of: stream_get_meta_data().


Alias of stream_set_blocking

  • « socket_get_status
  • socket_set_timeout »
  • PHP Manual
  • Network Functions
  • Alias of stream_set_blocking

socket_set_blocking

(PHP 4, PHP 5, PHP 7)

socket_set_blocking — Alias of stream_set_blocking()

Description

This function is an alias of: stream_set_blocking().


Alias of stream_set_timeout

  • « socket_set_blocking
  • syslog »
  • PHP Manual
  • Network Functions
  • Alias of stream_set_timeout

socket_set_timeout

(PHP 4, PHP 5, PHP 7)

socket_set_timeout — Alias of stream_set_timeout()

Description

This function is an alias of: stream_set_timeout().


Generate a system log message

  • « socket_set_timeout
  • RRD »
  • PHP Manual
  • Network Functions
  • Generate a system log message

syslog

(PHP 4, PHP 5, PHP 7)

syslog — Generate a system log message

Description

syslog ( int $priority , string $message ) : bool

syslog() generates a log message that will be distributed by the system logger.

For information on setting up a user defined log handler, see the syslog.conf (5) Unix manual page. More information on the syslog facilities and option can be found in the man pages for syslog (3) on Unix machines.

Parameters

priority

priority is a combination of the facility and the level. Possible values are:

syslog() Priorities (in descending order)
Constant | Description
LOG_EMERG | system is unusable
LOG_ALERT | action must be taken immediately
LOG_CRIT | critical conditions
LOG_ERR | error conditions
LOG_WARNING | warning conditions
LOG_NOTICE | normal, but significant, condition
LOG_INFO | informational message
LOG_DEBUG | debug-level message

message

The message to send, except that the two characters %m will be replaced by the error message string (strerror) corresponding to the present value of errno.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Using syslog()

<?php
// open syslog, include the process ID and also send
// the log to standard error, and use a user defined
// logging mechanism
openlog("myScriptLog", LOG_PID | LOG_PERROR, LOG_LOCAL0);

// some code

if (authorized_client()) {
    // do something
} else {
    // unauthorized client!
    // log the attempt
    $access = date("Y/m/d H:i:s");
    syslog(LOG_WARNING, "Unauthorized client: $access {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})");
}

closelog();
?>

Notes

On Windows NT, the syslog service is emulated using the Event Log.

Note:

Use of LOG_LOCAL0 through LOG_LOCAL7 for the facility parameter of openlog() is not available in Windows.

See Also

  • openlog() - Open connection to system logger
  • closelog() - Close connection to system logger


RRDtool

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Procedural PECL/rrd example
    • OOP PECL/rrd example
  • RRD Functions
    • rrd_create — Creates rrd database file
    • rrd_error — Gets latest error message
    • rrd_fetch — Fetch the data for graph as array
    • rrd_first — Gets the timestamp of the first sample from rrd file
    • rrd_graph — Creates image from a data
    • rrd_info — Gets information about rrd file
    • rrd_last — Gets unix timestamp of the last sample
    • rrd_lastupdate — Gets information about last updated data
    • rrd_restore — Restores the RRD file from XML dump
    • rrd_tune — Tunes some RRD database file header options
    • rrd_update — Updates the RRD database
    • rrd_version — Gets information about underlying rrdtool library
    • rrd_xport — Exports the information about RRD database
    • rrdc_disconnect — Close any outstanding connection to rrd caching daemon
  • RRDCreator — The RRDCreator class
    • RRDCreator::addArchive — Adds RRA - archive of data values for each data source
    • RRDCreator::addDataSource — Adds data source definition for RRD database
    • RRDCreator::__construct — Creates new RRDCreator instance
    • RRDCreator::save — Saves the RRD database to a file
  • RRDGraph — The RRDGraph class
    • RRDGraph::__construct — Creates new RRDGraph instance
    • RRDGraph::save — Saves the result of query into image
    • RRDGraph::saveVerbose — Saves the RRD database query into image and returns the verbose information about generated graph
    • RRDGraph::setOptions — Sets the options for rrd graph export
  • RRDUpdater — The RRDUpdater class
    • RRDUpdater::__construct — Creates new RRDUpdater instance
    • RRDUpdater::update — Update the RRD database file


Introduction

The PECL/rrd extension provides bindings to the RRDtool C library. RRDtool is the open source industry standard, high performance data logging and graphing system for time series data.

The RRDtool homepage is » http://www.mrtg.org/rrdtool/.


Requirements

You need to install librrd first to be able to use PECL/rrd. Most common option is using of librrd-dev package from your favourite linux distro. PECL/rrd is tested with librrd 1.4.3, older or newer versions might or might not work for you. PECL/rrd installation is tested with PHP 5.3.2 or newer.

Warning

Librrd and hence extension itself aren't mostly thread safe. There are many global and shared states in librrd. It can be dangerous use this extension in multi threaded environments like Apache2 mpm worker. If there are many parallel requests, one request can change some global librrd state of other runnig requests.


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/rrd.


  • « Resource Types
  • Examples »
  • PHP Manual
  • RRD
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


  • « Predefined Constants
  • Procedural PECL/rrd example »
  • PHP Manual
  • RRD
  • Examples

Examples

Table of Contents

  • Procedural PECL/rrd example
  • OOP PECL/rrd example


Procedural PECL/rrd example

Example #1 Procedural usage of rrd

<?php
$rrdFile = dirname(__FILE__) . "/speed.rrd";

//create rrd file
rrd_create($rrdFile,
 array(
  "--start",920804400,
  "DS:speed:COUNTER:600:U:U",
  "RRA:AVERAGE:0.5:1:24",
  "RRA:AVERAGE:0.5:6:10"
  )
);

//update rrd file
rrd_update($rrdFile,
 array(
  "920804700:12345",
  "920805000:12357"
  )
);

//graph output
rrd_graph(dirname(__FILE__) . "/speed.png",
 array(
  "--start", "920804400",
  "--end", "920808000",
  "--vertical-label", "m/s",
  "DEF:myspeed=$rrdFile:speed:AVERAGE",
  "CDEF:realspeed=myspeed,1000,*",
  "LINE2:realspeed#FF0000"
 )
);
?>


OOP PECL/rrd example

Example #1 OO usage of rrd

<?php
$rrdFile = dirname(__FILE__) . "/speed.rrd";
$outputPngFile = dirname(__FILE__) . "/speed.png";

$creator = new RRDCreator($rrdFile, "now -10d", 500);
$creator->addDataSource("speed:COUNTER:600:U:U");
$creator->addArchive("AVERAGE:0.5:1:24");
$creator->addArchive("AVERAGE:0.5:6:10");
$creator->save();

$updater = new RRDUpdater($rrdFile);
$updater->update(array("speed" => "12345"), "920804700");
$updater->update(array("speed" => "12357"), "920805000");

$graphObj = new RRDGraph($outputPngFile);
$graphObj->setOptions(
    array(
        "--start" => "920804400",
        "--end" => 920808000,
        "--vertical-label" => "m/s",
        "DEF:myspeed=$rrdFile:speed:AVERAGE",
        "CDEF:realspeed=myspeed,1000,*",
        "LINE2:realspeed#FF0000"
    )
);
$graphObj->save();
?>


RRD Functions

Table of Contents

  • rrd_create — Creates rrd database file
  • rrd_error — Gets latest error message
  • rrd_fetch — Fetch the data for graph as array
  • rrd_first — Gets the timestamp of the first sample from rrd file
  • rrd_graph — Creates image from a data
  • rrd_info — Gets information about rrd file
  • rrd_last — Gets unix timestamp of the last sample
  • rrd_lastupdate — Gets information about last updated data
  • rrd_restore — Restores the RRD file from XML dump
  • rrd_tune — Tunes some RRD database file header options
  • rrd_update — Updates the RRD database
  • rrd_version — Gets information about underlying rrdtool library
  • rrd_xport — Exports the information about RRD database
  • rrdc_disconnect — Close any outstanding connection to rrd caching daemon


Creates rrd database file

  • « RRD Functions
  • rrd_error »
  • PHP Manual
  • RRD Functions
  • Creates rrd database file

rrd_create

(PECL rrd >= 0.9.0)

rrd_create — Creates rrd database file

Description

rrd_create ( string $filename , array $options ) : bool

Creates the rdd database file.

Parameters

filename

Filename for newly created rrd file.

options

Options for rrd create - list of strings. See man page of rrd create for whole list of options.

Return Values

Returns TRUE on success or FALSE on failure.


Gets latest error message

  • « rrd_create
  • rrd_fetch »
  • PHP Manual
  • RRD Functions
  • Gets latest error message

rrd_error

(PECL rrd >= 0.9.0)

rrd_error — Gets latest error message

Description

rrd_error ( void ) : string

Returns latest global rrd error message.

Parameters

This function has no parameters.

Return Values

Latest error message.


Fetch the data for graph as array

  • « rrd_error
  • rrd_first »
  • PHP Manual
  • RRD Functions
  • Fetch the data for graph as array

rrd_fetch

(PECL rrd >= 0.9.0)

rrd_fetch — Fetch the data for graph as array

Description

rrd_fetch ( string $filename , array $options ) : array

Gets data for graph output from RRD database file as array. This function has same result as rrd_graph(), but fetched data are returned as array, no image file is created.

Parameters

filename

RRD database file name.

options

Array of options for resolution specification.

Return Values

Returns information about retrieved graph data.


Gets the timestamp of the first sample from rrd file

  • « rrd_fetch
  • rrd_graph »
  • PHP Manual
  • RRD Functions
  • Gets the timestamp of the first sample from rrd file

rrd_first

(PECL rrd >= 0.9.0)

rrd_first — Gets the timestamp of the first sample from rrd file

Description

rrd_first ( string $file [, int $raaindex = 0 ] ) : int

Returns the first data sample from the specified RRA of the RRD file.

Parameters

file

RRD database file name.

raaindex

The index number of the RRA that is to be examined. Default value is 0.

Return Values

Integer number of unix timestamp, FALSE if some error occurs.


Creates image from a data

  • « rrd_first
  • rrd_info »
  • PHP Manual
  • RRD Functions
  • Creates image from a data

rrd_graph

(PECL rrd >= 0.9.0)

rrd_graph — Creates image from a data

Description

rrd_graph ( string $filename , array $options ) : array

Creates image for a particular data from RRD file.

Parameters

filename

The filename to output the graph to. This will generally end in either .png, .svg or .eps, depending on the format you want to output.

options

Options for generating image. See man page of rrd graph for all possible options. All options (data definitions, variable defintions, etc.) are allowed.

Return Values

Array with information about generated image is returned, FALSE when error occurs.


Gets information about rrd file

  • « rrd_graph
  • rrd_last »
  • PHP Manual
  • RRD Functions
  • Gets information about rrd file

rrd_info

(PECL rrd >= 0.9.0)

rrd_info — Gets information about rrd file

Description

rrd_info ( string $filename ) : array

Returns information about particular RRD database file.

Parameters

file

RRD database file name.

Return Values

Array with information about requsted RRD file, FALSE when error occurs.


Gets unix timestamp of the last sample

  • « rrd_info
  • rrd_lastupdate »
  • PHP Manual
  • RRD Functions
  • Gets unix timestamp of the last sample

rrd_last

(PECL rrd >= 0.9.0)

rrd_last — Gets unix timestamp of the last sample

Description

rrd_last ( string $filename ) : int

Returns the UNIX timestamp of the most recent update of the RRD database.

Parameters

filename

RRD database file name.

Return Values

Integer as unix timestamp of the most recent data from the RRD database.


Gets information about last updated data

  • « rrd_last
  • rrd_restore »
  • PHP Manual
  • RRD Functions
  • Gets information about last updated data

rrd_lastupdate

(PECL rrd >= 0.9.0)

rrd_lastupdate — Gets information about last updated data

Description

rrd_lastupdate ( string $filename ) : array

Gets array of the UNIX timestamp and the values stored for each date in the most recent update of the RRD database file.

Parameters

file

RRD database file name.

Return Values

Array of information about last update, FALSE when error occurs.


Restores the RRD file from XML dump

  • « rrd_lastupdate
  • rrd_tune »
  • PHP Manual
  • RRD Functions
  • Restores the RRD file from XML dump

rrd_restore

(PECL rrd >= 0.9.0)

rrd_restore — Restores the RRD file from XML dump

Description

rrd_restore ( string $xml_file , string $rrd_file [, array $options ] ) : bool

Restores the RRD file from the XML dump.

Parameters

xml_file

XML filename with the dump of the original RRD database file.

rrd_file

Restored RRD database file name.

options

Array of options for restoring. See man page for rrd restore.

Return Values

Returns TRUE on success, FALSE otherwise.


Tunes some RRD database file header options

  • « rrd_restore
  • rrd_update »
  • PHP Manual
  • RRD Functions
  • Tunes some RRD database file header options

rrd_tune

(PECL rrd >= 0.9.0)

rrd_tune — Tunes some RRD database file header options

Description

rrd_tune ( string $filename , array $options ) : bool

Change some options in the RRD dabase header file. E.g. renames the source for the data etc.

Parameters

filename

RRD database file name.

options

Options with RRD database file properties which will be changed. See rrd tune man page for details.

Return Values

Returns TRUE on success, FALSE otherwise.


Updates the RRD database

  • « rrd_tune
  • rrd_version »
  • PHP Manual
  • RRD Functions
  • Updates the RRD database

rrd_update

(PECL rrd >= 0.9.0)

rrd_update — Updates the RRD database

Description

rrd_update ( string $filename , array $options ) : bool

Updates the RRD database file. The input data is time interpolated according to the properties of the RRD database file.

Parameters

filename

RRD database file name. This database will be updated.

options

Options for updating the RRD database. This is list of strings. See man page of rrd update for whole list of options.

Return Values

Returns TRUE on success, FALSE when error occurs.


Gets information about underlying rrdtool library

  • « rrd_update
  • rrd_xport »
  • PHP Manual
  • RRD Functions
  • Gets information about underlying rrdtool library

rrd_version

(PECL rrd >= 1.0.0)

rrd_version — Gets information about underlying rrdtool library

Description

rrd_version ( void ) : string

Returns information about underlying rrdtool library.

Parameters

This function has no parameters.

Return Values

String with rrdtool version number e.g. "1.4.3".


Exports the information about RRD database

  • « rrd_version
  • rrdc_disconnect »
  • PHP Manual
  • RRD Functions
  • Exports the information about RRD database

rrd_xport

(PECL rrd >= 0.9.0)

rrd_xport — Exports the information about RRD database

Description

rrd_xport ( array $options ) : array

Exports the information about RRD database file. This data can be converted to XML file via user space PHP script and then restored back as RRD database file.

Parameters

options

Array of options for the export, see rrd xport man page.

Return Values

Array with information about RRD database file, FALSE when error occurs.


Close any outstanding connection to rrd caching daemon

  • « rrd_xport
  • RRDCreator »
  • PHP Manual
  • RRD Functions
  • Close any outstanding connection to rrd caching daemon

rrdc_disconnect

(PECL rrd >= 1.1.2)

rrdc_disconnect — Close any outstanding connection to rrd caching daemon

Description

rrdc_disconnect ( void ) : void

Close any outstanding connection to rrd caching daemon.

This function is automatically called when the whole PHP process is terminated. It depends on used SAPI. For example, it's called automatically at the end of command line script.

It's up user whether he wants to call this function at the end of every request or otherwise.

Parameters

This function has no parameters.

Return Values

No value is returned.


The RRDCreator class

(PECL rrd >= 0.9.0)

Introduction

Class for creation of RRD database file.

Class synopsis

RRDCreator {
/* Methods */
public addArchive ( string $description ) : void
public addDataSource ( string $description ) : void
public __construct ( string $path [, string $startTime [, int $step = 0 ]] )
public save ( void ) : bool
}

Table of Contents

  • RRDCreator::addArchive — Adds RRA - archive of data values for each data source
  • RRDCreator::addDataSource — Adds data source definition for RRD database
  • RRDCreator::__construct — Creates new RRDCreator instance
  • RRDCreator::save — Saves the RRD database to a file


Adds RRA - archive of data values for each data source

  • « RRDCreator
  • RRDCreator::addDataSource »
  • PHP Manual
  • RRDCreator
  • Adds RRA - archive of data values for each data source

RRDCreator::addArchive

(PECL rrd >= 0.9.0)

RRDCreator::addArchive — Adds RRA - archive of data values for each data source

Description

public RRDCreator::addArchive ( string $description ) : void

Adds RRA definition by description of archive. Archive consists of a number of data values or statistics for each of the defined data-sources (DS). Data sources are defined by method RRDCreator::addDataSource(). You need call this method for each requested archive.

Parameters

description

Definition of archive - RRA. This has same format as RRA definition in rrd create command. See man page of rrd create for more details.

Return Values

No value is returned.


Adds data source definition for RRD database

  • « RRDCreator::addArchive
  • RRDCreator::__construct »
  • PHP Manual
  • RRDCreator
  • Adds data source definition for RRD database

RRDCreator::addDataSource

(PECL rrd >= 0.9.0)

RRDCreator::addDataSource — Adds data source definition for RRD database

Description

public RRDCreator::addDataSource ( string $description ) : void

RRD can accept input from several data sources (DS), e.g incoming and outgoing traffic. This method adds data source by description. You need call this method for each data source.

Parameters

description

Definition of data source - DS. This has same format as DS definition in rrd create command. See man page of rrd create for more details.

Return Values

No value is returned.


Creates new RRDCreator instance

  • « RRDCreator::addDataSource
  • RRDCreator::save »
  • PHP Manual
  • RRDCreator
  • Creates new RRDCreator instance

RRDCreator::__construct

(PECL rrd >= 0.9.0)

RRDCreator::__construct — Creates new RRDCreator instance

Description

public RRDCreator::__construct ( string $path [, string $startTime [, int $step = 0 ]] )

Creates new RRDCreator instance.

Parameters

path

Path for newly created RRD database file.

startTime

Time for the first value in RRD database. Parameter supports all formats which are supported by rrd create call.

intstep

Base interval in seconds with which data will be fed into the RRD database.

Return Values

No value is returned.


Saves the RRD database to a file

  • « RRDCreator::__construct
  • RRDGraph »
  • PHP Manual
  • RRDCreator
  • Saves the RRD database to a file

RRDCreator::save

(PECL rrd >= 0.9.0)

RRDCreator::save — Saves the RRD database to a file

Description

public RRDCreator::save ( void ) : bool

Saves the RRD database into file, which name is defined by RRDCreator::__construct().

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.


The RRDGraph class

(PECL rrd >= 0.9.0)

Introduction

Class for exporting data from RRD database to image file.

Class synopsis

RRDGraph {
/* Methods */
public __construct ( string $path )
public save ( void ) : array
public saveVerbose ( void ) : array
public setOptions ( array $options ) : void
}

Table of Contents

  • RRDGraph::__construct — Creates new RRDGraph instance
  • RRDGraph::save — Saves the result of query into image
  • RRDGraph::saveVerbose — Saves the RRD database query into image and returns the verbose information about generated graph
  • RRDGraph::setOptions — Sets the options for rrd graph export


Creates new RRDGraph instance

  • « RRDGraph
  • RRDGraph::save »
  • PHP Manual
  • RRDGraph
  • Creates new RRDGraph instance

RRDGraph::__construct

(PECL rrd >= 0.9.0)

RRDGraph::__construct — Creates new RRDGraph instance

Description

public RRDGraph::__construct ( string $path )

Creates new RRDGraph instance. This instance is responsible for rendering the result of RRD database query into image.

Parameters

path

Full path for the newly created image.

Return Values

No value is returned.


Saves the result of query into image

  • « RRDGraph::__construct
  • RRDGraph::saveVerbose »
  • PHP Manual
  • RRDGraph
  • Saves the result of query into image

RRDGraph::save

(PECL rrd >= 0.9.0)

RRDGraph::save — Saves the result of query into image

Description

public RRDGraph::save ( void ) : array

Saves the result of RRD database query into image defined by RRDGraph::__construct().

Parameters

This function has no parameters.

Return Values

Array with information about generated image is returned, FALSE if error occurs.


Saves the RRD database query into image and returns the verbose information about generated graph

  • « RRDGraph::save
  • RRDGraph::setOptions »
  • PHP Manual
  • RRDGraph
  • Saves the RRD database query into image and returns the verbose information about generated graph

RRDGraph::saveVerbose

(PECL rrd >= 0.9.0)

RRDGraph::saveVerbose — Saves the RRD database query into image and returns the verbose information about generated graph

Description

public RRDGraph::saveVerbose ( void ) : array

Saves the RRD database query into image file defined by method RRDGraph::__construct() and returns the verbose information about generated graph, if "-" is used as image filename, image data are also returned in result array.

Parameters

This function has no parameters.

Return Values

Array with detailed information about generated image is returned, optionally with image data, FALSE if error occurs.


Sets the options for rrd graph export

  • « RRDGraph::saveVerbose
  • RRDUpdater »
  • PHP Manual
  • RRDGraph
  • Sets the options for rrd graph export

RRDGraph::setOptions

(PECL rrd >= 0.9.0)

RRDGraph::setOptions — Sets the options for rrd graph export

Description

public RRDGraph::setOptions ( array $options ) : void

Parameters

options

List of options for the image generation from the RRD database file. It can be list of strings or list of strings with keys for better readability. Read the rrd graph man pages for list of available options.

Return Values

No value is returned.

Examples

Example #1 RRDGraph::setOptions() example

<?php
$graphObj->setOptions(array(
    "--start" => "920804400",
    "--end" => 920808000,
    "--vertical-label" => "m/s",
    "DEF:myspeed=$rrdFile:speed:AVERAGE",
    "CDEF:realspeed=myspeed,1000,*",
    "LINE2:realspeed#FF0000"
));
?>

Example #2 Set multiple color options

<?php
$graphObj->setOptions(array(
    "--start" => "920804400",
    "--end" => 920808000,
    "--vertical-label" => "m/s",
    "--color=BACK#00000000",
    "--color=GRID#00000000",
    "--color=MGRID#00000000",
    "DEF:myspeed=$rrdFile:speed:AVERAGE",
    "CDEF:realspeed=myspeed,1000,*",
    "LINE2:realspeed#FF0000"
));
?>

Don't use key value syntax for same rrd option. It looks more readable, but it doesn't work.

<?php
$graphObj->setOptions(array(
    "--color" => "BACK#00000000",
    "--color" => "GRID#00000000",
    "--color" => "MGRID#00000000"
));
?>

In nature of php it's same as

<?php
$graphObj->setOptions(array(
    "--color" => "MGRID#00000000"
));
?>


The RRDUpdater class

(PECL rrd >= 0.9.0)

Introduction

Class for updating RDD database file.

Class synopsis

RRDUpdater {
/* Methods */
public __construct ( string $path )
public update ( array $values [, string $time = time() ] ) : bool
}

Table of Contents

  • RRDUpdater::__construct — Creates new RRDUpdater instance
  • RRDUpdater::update — Update the RRD database file


Creates new RRDUpdater instance

  • « RRDUpdater
  • RRDUpdater::update »
  • PHP Manual
  • RRDUpdater
  • Creates new RRDUpdater instance

RRDUpdater::__construct

(PECL rrd >= 0.9.0)

RRDUpdater::__construct — Creates new RRDUpdater instance

Description

public RRDUpdater::__construct ( string $path )

Creates new RRDUpdater instance. This instance is responsible for updating the RRD database file.

Parameters

path

Filesystem path for RRD database file, which will be updated.

Return Values

No value is returned.


Update the RRD database file

  • « RRDUpdater::__construct
  • SAM »
  • PHP Manual
  • RRDUpdater
  • Update the RRD database file

RRDUpdater::update

(PECL rrd >= 0.9.0)

RRDUpdater::update — Update the RRD database file

Description

public RRDUpdater::update ( array $values [, string $time = time() ] ) : bool

Updates the RRD file defined via RRDUpdater::__construct(). The file is updated with a specific values.

Parameters

values

Data for update. Key is data source name.

time

Time value for updating the RRD with a particulat data. Default value is current time.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws a Exception on error.

Examples

Example #1 RRDUpdater::update() examples

<?php
$updator = new RRDUpdater("speed.rrd");
//updates the data source "speed" with value "12411"
//for time defined by timestamp "920807700"
$updator->update(array("speed" => "12411"), "920807700");
?>


Simple Asynchronous Messaging

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Connections
    • Messages
    • Messaging operations
    • Publish/Subscribe and subscriptions to topics
    • Error handling
  • SAM Functions
    • SAMConnection::commit — Commits (completes) the current unit of work
    • SAMConnection::connect — Establishes a connection to a Messaging Server
    • SAMConnection::__construct — Creates a new connection to a Messaging Server
    • SAMConnection::disconnect — Disconnects from a Messaging Server
    • SAMConnection::errno — Contains the unique numeric error code of the last executed SAM operation
    • SAMConnection::error — Contains the text description of the last failed SAM operation
    • SAMConnection::isConnected — Queries whether a connection is established to a Messaging Server
    • SAMConnection::peek — Read a message from a queue without removing it from the queue
    • SAMConnection::peekAll — Read one or more messages from a queue without removing it from the queue
    • SAMConnection::receive — Receive a message from a queue or subscription
    • SAMConnection::remove — Remove a message from a queue
    • SAMConnection::rollback — Cancels (rolls back) an in-flight unit of work
    • SAMConnection::send — Send a message to a queue or publish an item to a topic
    • SAMConnection::setDebug — Turn on or off additional debugging output
    • SAMConnection::subscribe — Create a subscription to a specified topic
    • SAMConnection::unsubscribe — Cancel a subscription to a specified topic
    • SAMMessage::body — The body of the message
    • SAMMessage::__construct — Creates a new Message object
    • SAMMessage::header — The header properties of the message


Introduction

This extension provides access to the functionality of messaging and queueing systems, such as the IBM WebSphere MQSeries family of products, from PHP scripts. The interface is designed to make it extremely simple to do the more commonly required tasks such as deliver simple text messages to queues while still allowing skilled users to do more complex messaging operations. For many users the complexities of setting up numerous options can be simply ignored.

The SAM extension is a framework that provides a very simple API that can be used to access a number of messaging middleware systems. Currently the package includes built-in support for the MQTT (MQ Telemetry Transport) messaging protocol and support for the IBM Messaging and Queuing middleware products. SAM is designed to be readily extended to support other messaging systems and extension modules may be written in C or PHP.


Requirements

The SAM extension interfaces to the IBM Messaging and Queuing middleware products using a set of libraries and some client side code referred to as XMS. This package is available as a free download in the guise of IBM support pack IA94. There is a description of this package and download links in the article » Introducing XMS - The IBM Message Service API.

If you intend to use SAM to access the Messaging and Queuing infrastructure within WebSphere MQ then you will also need to have installed a local MQ queue manager or installed the WebSphere MQ clients package. The clients package is freely available as a support pack (» MQC6).

If you are only aiming to experiment with sending messages to and from WebSphere Application Server queues using the WebSphere Platform Messaging protocol (WPM) then you do not need to install the MQC6 package.

After installing these packages you will need to ensure the XMS binary and, if you are using it, the MQ client bin directory are included in the PATH environment variable so that Apache and PHP can find the dependent .DLLs/libraries.


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/sam.

The SAM framework and MQTT support can be built and used without any other prerequisites. Support for protocols other than MQTT is provided via a set of libraries and some client side code referred to as XMS.

If you only intend to use the built-in MQTT support then you can build and configure SAM as an extension or simply refer to php_sam.php with a require or require_once clause in your PHP script. In this case you need only install the code without building the extension using the pear installer:

pecl install -B SAM

Linux installation steps

The sam extension is supplied as a PECL module, which you should be able to download and install in one step as follows:

pecl install sam
(Depending on your php environment, you will probably need to be root to do this.)

Make sure that the module is loaded by PHP, by adding following line to php.ini:

extension=sam.so
If you intend to use the XMS support to access the IBM Messaging and Queuing family you must also enable the SAM XMS extension.
extension=sam_xms.so

If you cannot use the PEAR installer, you can download the extension and build it manually:

pear download sam          #downloads sam-<version>.tgz
tar -xzf sam-<version>.tgz
cd sam-<version>
phpize
./configure
make
make install               #you may need to be root for this step

To work with the very latest source, you'll need to extract it from SVN and build manually as above.

Windows installation steps

You will probably need to build the sam extension for Windows as there are only a limited range of pre-built binaries available from the SAM website. The extension can be built using the standard Windows extension build procedures.

You will need the PHP source tree for the version of PHP you wish to build the SAM extension against which you can obtain from php.net. This should be unpacked into a working directory of your choice.

You will also need the libraries and headers used by PHP extensions available from http://www.php.net/extra/win32build.zip and this should be unzipped so that is in your working directory.

You should have something like:

c:\php-build\-
              |
              |---php-5.0.5--|---build
              |              |---ext
              |              |--- ...
              |
              |---win32build--|---bin
                              |---include
                              |---lib

You will need a compiler such as the free version of Visual Studio C++ Express from the Microsoft web site. Also you need the Microsoft SDK Microsoft Windows Platform which again can be downloaded from the Microsoft web site.

Obtain the SAM extension source using pear (pecl download sam) or by using SVN and copy the files to a new "sam" directory under the "ext" directory in your PHP source tree.

To build the extension open a build environment window by going to the start

menu->all programs->microsoft platform SDK for windows->
open build environment window->windows 200 build environment->
set windows 2000 build environment (retail)

This should open a command prompt with all the environment variables set up to access the platform SDK etc. You then need to set the environment variables for Visual Studio by issuing the command vcvars32.bat in the window.

Change directory to your working directory e.g. cd c:\php-build. Then make sure the win32build tools are accessible by adding them to the PATH environment variable:

set PATH=..\win32build\bin;%PATH%

Run the buildconf.bat command. This should rebuild the configure.js file.

Run the cscript command with the appropriate options. To build just the SAM extension framework and MQTT support use:

cscript /nologo configure.js --with-sam
To build the SAM framework and the XMS support use:
cscript /nologo configure.js --with-sam --with-sam_xms="c:\program files\ibm\xms"

The additional parameter passed for sam_xms is the installation path to the XMS libraries and runtime that were installed as described under prerequisites at the top of this page.

You can specify whatever other cscript parameters you require to include or exclude items from the php build or select options.

Assuming all has gone well so far you can now finally run a make for the SAM framework!

nmake php_sam.dll
Also if you are using the XMS support you must make the sam_xms extensions:
nmake php_sam_xms.dll

If you have used Visual Studio 2005 to build the DLLs please see below for additional steps that must be carried out before proceeding further.

The DLLs created (php_sam.dll and optionally php_sam_xms.dll) can now be copied to the subdirectory appropriate for your PHP set-up. Make sure that the module(s) are loaded by PHP, by adding following line to php.ini:

extension=php_sam.dll
If you intend to use the XMS support to access the IBM Messaging and Queuing family you must also enable the SAM XMS extension.
extension=php_sam_xms.dll

Additional steps for Visual Studio 2005

If you build the SAM extension with the Microsoft Visual Studio 2005 compiler and tools you need to perform an additional step in the build process to ensure the php_sam.dll is able to link with the C runtime libraries at runtime. This step includes the dependancy manifest into the DLL. Switch to the directory where the php_sam.dll has been generated (usually Release_TS or Debug_TS below the php source directory) and issue the following magic incantation:

mt.exe -manifest php_sam.dll.manifest -outputresource:php_sam.dll;2
If you are using the XMS capabilities you will need to do the same with the SAM XMS DLL:
mt.exe -manifest php_sam_xms.dll.manifest -outputresource:php_sam_xms.dll;2

If you build the SAM extension using the compiler and libraries from Microsoft Visual Studio 2005 you will also need to ensure that the runtime components are installed on the system on which you intend to use SAM. This can be accomplished by installing Visual Studio 2005 or by using the freely distributable » runtime package.


Runtime Configuration

Protocol support and mapping

The SAM framework can be extended to support other messaging protocols and connection mechanisms. To add support for a new protocol or connection library a support class has to be defined, either as a C extension or as a PHP script, and a "factory" script must be created. The support class must implement all the methods of the SAMConnection class though it should not inherit from SAMConnection. The factory script will be called by the SAM framework to create an instance of the implemented class. The way SAM chooses which factory to call is based on the protocol specified as the first parameter of the "connect" call.

By default the built-in MQTT support will be used if a connect call specifies a protocol of SAM_MQTT ("mqtt"), for any other protocol SAM will attempt to use the XMS support extension. To add support for additional protocols or to modify the default behavior entries may be added to php.ini in the [sam] section. The default mapping is equivalent to the following entries:

[sam]
sam.factory.mqtt=mqtt
sam.factory.wmq=xms
sam.factory.wmq:client=xms
sam.factory.wmq:bindings=xms
sam.factory.wpm=xms
sam.factory.rtt=xms
As can be seen from these examples the entries take the form of "sam.factory.pppp=xxx" where pppp is the protocol string specified on the connect call and xxx is a factory suffix. Note: SAM defines constants for these protocol strings such that SAM_WMQ=wmq, SAM_WPM=wpm, SAM_RTT=rtt, SAM_MQTT=mqtt, etc.

When identifying the support code to use on a connect call SAM looks up the protocol name in the php.ini entries and then invokes a factory script named sam_factory_xxx.php. If no entry is found the support will default to XMS.


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.

SAM_AUTO (string)
Automatic behaviour
SAM_BOOLEAN (string)
Type specifier used when setting properties on SAM_Message objects.
SAM_BUS (string)
Connect attribute used to set the name of the enterprise service bus to connect to.
SAM_BYTE (string)
Type specifier used when setting properties on SAM_Message objects.
SAM_BYTES (string)
Message body type descriptor.
SAM_CORRELID (string)
Attribute used on receive, send and remove requests to identify specific messages.
SAM_DELIVERYMODE (string)
Message header property.
SAM_DOUBLE (string)
Type specifier used when setting properties on SAM_Message objects.
SAM_ENDPOINTS (string)
Connect attribute used to define the possible endpoints to connect to.
SAM_FLOAT (string)
Type specifier used when setting properties on SAM_Message objects.
SAM_HOST (string)
Connect attribute used to set the hostname of the required messaging server.
SAM_INT (string)
Type specifier used when setting properties on SAM_Message objects.
SAM_LONG (string)
Type specifier used when setting properties on SAM_Message objects.
SAM_MANUAL (string)
Manual (script controlled) behaviour
SAM_MESSAGEID (string)
Attribute used on receive and remove requests to identify specific messages.
SAM_MQTT (string)
Connect protocol definition for selecting the MQTT (MQ Telemetry Transport) protocol.
SAM_MQTT_CLEANSTART (bool)
Optional connect option to indicate to an MQTT server that all previous connection data for this client should be removed and that subscriptions should be deleted when the client disconnects explicitly or unexpectedly.
SAM_NON_PERSISTENT (string)
Connect attribute value used to request messages are not made persistent on the messaging server.
SAM_PASSWORD (string)
Connect attribute used to define the password to be used for the user account being used to connect to a messaging server that requires authorisation for connections.
SAM_PERSISTENT (string)
Connect attribute value used to request messages are made persistent on the messaging server to protect against loss of messages in the event of failure.
SAM_PORT (string)
Connect attribute used to set the port number on which to communicate with the messaging server.
SAM_PRIORITY (string)
Option name used on send requests to specify a delivery priority value.
SAM_REPLY_TO (string)
Message property used to specify the queue identity on to which the script expects response or reply messages to be posted.
SAM_RTT (string)
Connect protocol definition for selecting the IBM Realtime Transport protocol for communication with a business integration messaging server.
SAM_STRING (string)
Type specifier used when setting properties on SAM_Message objects.
SAM_TARGETCHAIN (string)
Connection attribute used to set the required target chain identifier.
SAM_TEXT (string)
Message body type descriptor.
SAM_TIMETOLIVE (string)
Message send option name used to specify the length of time a message should be retained in milliseconds.
SAM_TRANSACTIONS (string)
Connection attribute used to set required transactional behaviour. May be set to SAM_AUTO (default) or SAM_MANUAL.
SAM_USERID (string)
Connect attribute used to define the account to being used to connect to a messaging server that requires authorisation for connections.
SAM_WAIT (string)
Receive property used to specify the wait timeout to be used when receiving a message from a queue or subscription.
SAM_WMQ (string)
Connect protocol definition for selecting the IBM WebSphere MQSeries protocol for communication with the desired messaging server.
SAM_WMQ_BINDINGS (string)
Connect protocol definition for selecting the IBM WebSphere MQSeries protocol for communication with a local messaging server.
SAM_WMQ_CLIENT (string)
Connect protocol definition for selecting the IBM WebSphere MQSeries protocol for communication with a remote messaging server.
SAM_WMQ_TARGET_CLIENT (string)
Option name used on send requests to specify the target client mode. This can either be default to 'jms' or 'mq'. The default is 'jms' which means an RFH2 header is sent with the message whereas the 'mq' setting means no RFH2 is included.
SAM_WPM (string)
Connect protocol definition for selecting the IBM WebSphere Platform Messaging protocol for communication with a WebSphere Application Server messaging server.


Examples

Table of Contents

  • Connections
  • Messages
  • Messaging operations
  • Publish/Subscribe and subscriptions to topics
  • Error handling


Connections

In order to perform any messaging and queueing functions a connection must be established with a messaging server by creating a SAMConnection object and calling its "connect" method, with a set of connection properties, to connect the PHP script to the messaging server. Until such time as the SAMConnection object is destroyed the connection will be maintained and available for use. All SAMConnection objects are destroyed when the PHP script exits.

A set of default properties may be used in connecting to a messaging server but as a minimum the PHP script must specify a protocol to be used.

Example #1 Creating a connection and connecting to a remote WebSphere MQSeries Messaging Server

<?php
$conn = new SAMConnection();
$conn->connect(SAM_WMQ, array(SAM_HOST => 'myhost.mycompany.com',
                              SAM_PORT => 1506,
                              SAM_BROKER => 'mybroker'));
?>

Example #2 Creating a connection and connecting to a remote WebSphere Application Server

<?php
$conn = new SAMConnection();
$conn->connect(SAM_WPM, array(SAM_ENDPOINTS => 'localhost:7278:BootstrapBasicMessaging',
                              SAM_BUS => 'Bus1',
                              SAM_TARGETCHAIN => 'InboundBasicMessaging'));
?>

Example #3 Creating a connection and connecting to an MQTT server

<?php
$conn = new SAMConnection();
$conn->connect(SAM_MQTT, array(SAM_HOST => 'myhost.mycompany.com',
                               SAM_PORT => 1883));
?>


Messages

Messages sent to and received from queues are represented by the SAMMessage object. The SAMMessage object encapsulates the body of the message (if one exists) and the header properties associated with the message. A SAMMessage object is either supplied as a parameter to a messaging operation or returned as a result.

Example #1 Creating a message with a simple text body

<?php
$msg = new SAMMessage('This is a simple text message');
?>

Messages may have header properties associated with them that provide control over the transport of the message or further information to the receiving application. By default message properties are delivered to the underlying messaging system as strings and in this case they may be set with the following simple syntax:

Example #2 Setting a text format property using the default syntax

<?php
$msg->header->myPropertyName = 'textData';
?>

If it is desired to pass type information an alternative syntax may be used where the value and the type hint are passed in an associative array:

Example #3 Setting a property using a type hint

<?php
$msg->header->myPropertyName = array(3.14159, SAM_FLOAT);
?>

Properties may also be extracted from the header of a message.

Example #4 Retrieving a property from a message header

<?php
$myProperty = $msg->header->myPropertyName;
?>


Messaging operations

All messaging operations are performed through calls to methods on the connection object. To add a message to a queue the "send" method is used, to obtain a message from a queue the "receive" method is used. Other methods provide publish and subscribe functionality and control of transaction boundaries.

Example #1 Adding a message to a queue and receiving a response

<?php
$msg = new SAMMessage('This is a simple text message');
$msg->header->SAM_REPLY_TO = 'queue://receive/test';
$correlid = $conn->send('queue://send/test', $msg);

if (!$correlid) {
  // The Send failed!
  echo "Send failed ($conn->errno) $conn->error";
} else {
  $resp = $conn->receive('queue://receive/test', array(SAM_CORRELID => $correlid));
}
?>


Publish/Subscribe and subscriptions to topics

SAM allows messages to be sent either to queues or, for WebSphere MQ and WPM, to publish/subscribe topics. A topic destination is specified to SAM in the usual way, i.e. in the form 'topic://fred', rather than the form 'queue://AQUEUE' used for point to point operation. To use publish/subscribe it is simply necessary to specify the correct broker name on the SAMConnect "connect" call and the desired topic in the destination argument to the SAMConnect "send" and "receive" calls. The PHP interface is otherwise identical to the point to point model.

By default, SAM creates non-durable subscriptions when using publish/subscribe. This means that if a client application is inactive when messages are published to a topic, then it will not receive them when it subsequently restarted. SAM does also allow durable subscriptions to be made to topics when using WPM or WebSphere MQ publish/subscribe. The purpose of these subscriptions is to allow data to be received by a client application even if that client was not active at the time the data was published.

Durable subscriptions are specified by using the SAMConnect "subscribe" call. This method takes the destination topic as an input parameter and returns a subscription identifier that may be used on subsequent "receive" calls. When the subscription is no longer required the SAMConnection "unsubscribe" method should be used to delete the subscription.

Example #1 Creating a durable subscription to a topic

<?php

$subName = $conn->subscribe('topic://A');

if (!$subName) {
   echo "Subscribe failed";
} else {
   # Subscribe was OK
   // ...
}
?>

Example #2 Subscribing to a topic using a WebSphere Platform Messaging (WPM) server

<?php
$conn = new SAMConnection();
// Note: For pub/sub on WPM, when connecting the name of a messaging engine
//   to hold the durable subscription (SAM_WPM_DUR_SUB_HOME) must be specified.
$conn->connect(SAM_WMQ, array(SAM_ENDPOINTS => 'localhost:7278:BootstrapBasicMessaging',
                              SAM_BUS => 'Bus1',
                              SAM_TARGETCHAIN => 'InboundBasicMessaging',
                              SAM_WPM_DUR_SUB_HOME => 'MyMachineNode01.server1-Bus1'));

$subName = $conn->subscribe('topic://A');

if (!$subName) {
   echo "Subscribe failed";
} else {
   # Subscribe was OK
   // ...
}
?>

Example #3 Receiving published data using a durable subscription

<?php

$msg = $conn->receive($subName);
if ($msg) {
   echo "Received a message OK";
} else {
   echo "The receive failed";
}

?>

Example #4 Deleting a durable subscription to a topic

<?php

if (!$conn->unsubscribe($subName)) {
   echo "Unsubscribe failed";
}

?>


Error handling

All SAMConnection methods that provide access to messaging operations return FALSE if an error occurred in processing the request. In addition the SAMConnection object has two properties, "errno" and "error", that provide respectively the error number and text description of the last error to occur on the connection.

Example #1 Handling an error from a method that returns no result

<?php
if (!$conn->commit()) {
    // The commit failed!
    echo "Commit failed ($conn->errno) $conn->error";
}
?>

Example #2 Handling an error from a method that returns a result

<?php
$correlid = $conn->send('queue://send/test', $msg);

if (!$correlid) {
  // The Send failed!
  echo "Send failed ($conn->errno) $conn->error";
} else {
  /* ... */
}
?>


SAM Functions

Predefined Classes

SAMConnection

Object representing a connection to a Messaging Server

Constructor

  • new SAMConnection - construct a new connection object to allow connection to a messaging infrastructure.

Methods

  • commit - a method that commits (successfully completes) an in-flight unit of work.

  • connect - a method that connects a PHP script to a messaging server.

  • disconnect - a method that disconnects a PHP script from a messaging server.

  • isConnected - a method that checks whether a PHP script is connected to a messaging server.

  • peek - a method that receives a message from a queue without removing it from the queue.

  • peekAll - a method that receives one or messages from a queue without removing them from the queue.

  • receive - a method that receives a message from a queue or subscription.

  • remove - a method that removes a message from a queue.

  • rollback - a method that cancels (rolls back) an in-flight unit of work.

  • send - a method that sends a message to a queue or posts to a topic

  • setDebug - a method that switches additional debugging output on or off

  • subscribe - a method that creates a subscription to one or more topics

  • unsubscribe - a method that destroys a subscription to one or more topics

Properties

  • errno - the numeric error code for the last encountered error on this connection. This property is set to 0 if the last operation was successful.

  • error - the text description for the last encountered error on this connection

SAMMessage

Object representing a message to be sent or received

Constructor

  • new SAMMessage - construct a new message.

Properties

  • body - the body of the message.

  • header - the header properties of the message.

Table of Contents

  • SAMConnection::commit — Commits (completes) the current unit of work
  • SAMConnection::connect — Establishes a connection to a Messaging Server
  • SAMConnection::__construct — Creates a new connection to a Messaging Server
  • SAMConnection::disconnect — Disconnects from a Messaging Server
  • SAMConnection::errno — Contains the unique numeric error code of the last executed SAM operation
  • SAMConnection::error — Contains the text description of the last failed SAM operation
  • SAMConnection::isConnected — Queries whether a connection is established to a Messaging Server
  • SAMConnection::peek — Read a message from a queue without removing it from the queue
  • SAMConnection::peekAll — Read one or more messages from a queue without removing it from the queue
  • SAMConnection::receive — Receive a message from a queue or subscription
  • SAMConnection::remove — Remove a message from a queue
  • SAMConnection::rollback — Cancels (rolls back) an in-flight unit of work
  • SAMConnection::send — Send a message to a queue or publish an item to a topic
  • SAMConnection::setDebug — Turn on or off additional debugging output
  • SAMConnection::subscribe — Create a subscription to a specified topic
  • SAMConnection::unsubscribe — Cancel a subscription to a specified topic
  • SAMMessage::body — The body of the message
  • SAMMessage::__construct — Creates a new Message object
  • SAMMessage::header — The header properties of the message


Commits (completes) the current unit of work

  • « SAM Functions
  • SAMConnection::connect »
  • PHP Manual
  • SAM Functions
  • Commits (completes) the current unit of work

SAMConnection::commit

(PECL sam >= 0.1.0)

SAMConnection::commit — Commits (completes) the current unit of work

Description

SAMConnection::commit ( void ) : bool

Calling the "commit" method on a Connection object commits (completes) all in-flight transactions that are part of the current unit of work.

Return Values

This method returns FALSE if an error occurs.

Examples

Example #1 Committing the current unit of work

<?php
  if (!$conn->commit()) {
    // The commit failed!
    echo "Commit failed ($conn->errno) $conn->error";
  }
?>

See Also

  • SAMConnection::rollback


Establishes a connection to a Messaging Server

  • « SAMConnection::commit
  • SAMConnection::__construct »
  • PHP Manual
  • SAM Functions
  • Establishes a connection to a Messaging Server

SAMConnection::connect

(PECL sam >= 0.1.0)

SAMConnection::connect — Establishes a connection to a Messaging Server

Description

SAMConnection::connect ( string $protocol [, array $properties ] ) : bool

Calling the "connect" method on a SAMConnection object connects the PHP script to a messaging server. No messages can be sent or received until a connection is made.

Parameters

Return Values

This method returns FALSE if an error occurs.

Examples

Example #1 Creating a connection to a Messaging Server using the IBM MQSeries protocol (WMQ)

<?php

$conn->connect(SAM_WMQ, array(SAM_HOST => 'Myhost.myco.com', SAM_PORT => 1506, SAM_BROKER => 'MyBroker'));

?>

Example #2 Creating a connection with application transaction control and default host and port values

<?php

$conn->connect(SAM_WMQ, array(SAM_BROKER => 'MyBroker', SAM_TRANSACTIONS => SAM_MANUAL));

?>

Example #3 Creating a connection to a Messaging Server using the IBM WebSphere Platform Messaging protocol (WPM)

<?php

$conn->connect(SAM_WPM, array(SAM_ENDPOINTS => 'localhost:7278:BootstrapBasicMessaging',
                              SAM_BUS => 'Bus1', SAM_TARGETCHAIN => 'InboundBasicMessaging'));

?>

See Also

  • SAMConnection::isConnected
  • SAMConnection::disconnect


Creates a new connection to a Messaging Server

  • « SAMConnection::connect
  • SAMConnection::disconnect »
  • PHP Manual
  • SAM Functions
  • Creates a new connection to a Messaging Server

SAMConnection::__construct

(PECL sam >= 0.1.0)

SAMConnection::__construct — Creates a new connection to a Messaging Server

Description

SAMConnection::__construct ( void )

Creates a new SAMConnection object.

Examples

Example #1 Creating a connection object and connecting to a Messaging Server

<?php

$conn = new SAMConnection();
$conn->connect(SAM_WMQ, array(SAM_HOST => localhost, SAM_PORT => 1414, SAM_BROKER => 'bull'));

?>


Disconnects from a Messaging Server

  • « SAMConnection::__construct
  • SAMConnection::errno »
  • PHP Manual
  • SAM Functions
  • Disconnects from a Messaging Server

SAMConnection::disconnect

(PECL sam >= 0.1.0)

SAMConnection::disconnect — Disconnects from a Messaging Server

Description

SAMConnection::disconnect ( void ) : bool

Calling the "disconnect" method on a SAMConnection object disconnects the PHP script from a messaging server. No messages can be sent or received after a connection has been disconnected.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Disconnecting from a Messaging Server

<?php

$conn->disconnect();

?>

See Also

  • SAMConnection::isConnected
  • SAMConnection::connect


Contains the unique numeric error code of the last executed SAM operation

  • « SAMConnection::disconnect
  • SAMConnection::error »
  • PHP Manual
  • SAM Functions
  • Contains the unique numeric error code of the last executed SAM operation

SAMConnection::errno

(PECL sam >= 0.1.0)

SAMConnection::errno — Contains the unique numeric error code of the last executed SAM operation

Description

int $SAMConnection->errno;

Contains the numeric error code of the last executed SAM operation on this connection. If the last operation completed successfully this property contains 0.

Return Values

An integer greater than zero indicates the last error type encountered on the connection. Zero indicates that the last operation on this connection completed successfully.

Examples

Example #1 Using the error number and description properties

<?php
$conn = new SAMConnection();
$conn->connect(SAM_WMQ, array(SAM_HOST => 'localhost', SAM_PORT => 1506));
$msg = new SAMMessage('This is a simple text item');
if (!$conn->send('topic://test', $msg)) {
    // The Send failed!
    echo "Send failed ($conn->errno) $conn->error";
}
?>

See Also

  • SAMConnection::error


Contains the text description of the last failed SAM operation

  • « SAMConnection::errno
  • SAMConnection::isConnected »
  • PHP Manual
  • SAM Functions
  • Contains the text description of the last failed SAM operation

SAMConnection::error

(PECL sam >= 0.1.0)

SAMConnection::error — Contains the text description of the last failed SAM operation

Description

string $SAMConnection->error;

Contains the text description of the last failed SAM operation on this connection. If the last operation completed successfully this property contains an empty string.

Return Values

A string containing the text description of the last error type encountered on the connection. An empty string indicates that the last operation on this connection completed successfully.

Examples

Example #1 Using the error number and description properties

<?php
$conn = new SAMConnection();
$conn->connect(SAM_WMQ, array(SAM_HOST => 'localhost', SAM_PORT => 1506));
$msg = new SAMMessage('This is a simple text item');
if (!$conn->send('topic://test', $msg)) {
    // The Send failed!
    echo "Send failed ($conn->errno) $conn->error";
}
?>

See Also

  • SAMConnection::errno


Queries whether a connection is established to a Messaging Server

  • « SAMConnection::error
  • SAMConnection::peek »
  • PHP Manual
  • SAM Functions
  • Queries whether a connection is established to a Messaging Server

SAMConnection::isConnected

(PECL sam >= 0.1.0)

SAMConnection::isConnected — Queries whether a connection is established to a Messaging Server

Description

SAMConnection::isConnected ( void ) : bool

Calling the "isConnected" method on a Connection object will check whether the PHP script is connected to a messaging server. No messages can be sent or received unless a connection has been established with a Messaging server.

Return Values

This method returns TRUE if the SAMConnection object is successfully connected to a Messaging server or FALSE otherwise.

Examples

Example #1 Checking whether there us a connection to a Messaging Server

<?php

if ($conn->isConnected()) {
  echo 'Connection is active.';
} else {
  echo 'No active connection!';
}

?>

See Also

  • SAMConnection::disconnect
  • SAMConnection::connect


Read a message from a queue without removing it from the queue

  • « SAMConnection::isConnected
  • SAMConnection::peekAll »
  • PHP Manual
  • SAM Functions
  • Read a message from a queue without removing it from the queue

SAMConnection::peek

(PECL sam >= 0.1.0)

SAMConnection::peek — Read a message from a queue without removing it from the queue

Description

SAMConnection::peek ( string $target [, array $properties ] ) : SAMMessage

Parameters

target

The identity of the queue from which to peek the message.

properties

An optional associative array of properties describing other parameters to control the peek operation.

Property name | Possible values
SAM_CORRELID | This is the target correlation id string of the message. This would typically have been returned by a "send" request.
SAM_MESSAGEID | This is the message id string of the message which is to be peeked.

Return Values

This method returns a SAMMessage object or FALSE if an error occurs.

Examples

Example #1 Retrieve the next message from a queue without removing it

<?php
$msg = $conn->peek('queue://receive/test');

if (!$msg) {
  // The peek failed!
  echo "Peek failed ($conn->errno) $conn->error";
}
?>

Example #2 Retrieve a specific message from a queue without removing it from the queue

<?php

$msg = $conn->peek('queue://receive/test', array(SAM_MESSAGEID => $messageId));

?>

See Also

  • SAMConnection::peekAll


Read one or more messages from a queue without removing it from the queue

  • « SAMConnection::peek
  • SAMConnection::receive »
  • PHP Manual
  • SAM Functions
  • Read one or more messages from a queue without removing it from the queue

SAMConnection::peekAll

(PECL sam >= 0.2.0)

SAMConnection::peekAll — Read one or more messages from a queue without removing it from the queue

Description

SAMConnection::peekAll ( string $target [, array $properties ] ) : array

Parameters

target

The identity of the queue from which messages should be peeked.

properties

An optional associative array of properties describing other parameters to control the peek operation.

Property name | Possible values
SAM_CORRELID | This is the target correlation id string of messages to be peeked. This would typically have been returned by a "send" request.
SAM_MESSAGEID | This is the message id string of a message which is to be peeked.

Return Values

This method returns an array of SAMMessage objects or FALSE if an error occurs.

Examples

Example #1 Retrieve all messages in a queue without removing them

<?php
$msgArray = $conn->peekAll('queue://receive/test');
if ($msgArray) {
   foreach ( $msgArray as $key => $msg) {
       echo "Message $key: body = $msg->body\n";
   }
} else {
   echo "PeekAll failed ($conn->errno) $conn->error";
}
?>

Example #2 Retrieve all messages from a queue with a matching correlation id

<?php

   $msgArray = $conn->peekAll('queue://receive/test', array(SAM_CORRELID => $correlId ));
   if ($msgArray) {

      foreach ( $msgArray as $key => $msg) {
            echo "Message $key: body = $msg->body\n";
         }
   } else {
      echo "PeekAll failed ($conn->errno) $conn->error";
   }

?>

See Also

  • SAMConnection::peek


Receive a message from a queue or subscription

  • « SAMConnection::peekAll
  • SAMConnection::remove »
  • PHP Manual
  • SAM Functions
  • Receive a message from a queue or subscription

SAMConnection::receive

(PECL sam >= 0.1.0)

SAMConnection::receive — Receive a message from a queue or subscription

Description

SAMConnection::receive ( string $target [, array $properties ] ) : SAMMessage

Parameters

target

The identity of the queue, topic or subscription from which to receive the message.

properties

An optional associative array of properties describing other parameters to control the receive operation.

Property name | Possible values
SAM_CORRELID | Used to request selection of the message to receive based upon the correlation id string of the message.
SAM_MESSAGEID | Used to request selection of the message to receive based upon the message id string of the message.
SAM_WAIT | Timeout value in milliseconds to control how long the request should block waiting to receive a message before returning with a failure if no message is available on the queue or topic. The default value is 0 meaning wait indefinitely and should be used with caution as the request may wait until the overall PHP script processing time limit has expired if no message becomes available.

Return Values

This method returns a SAMMessage object or FALSE if an error occurs.

Examples

Example #1 Receiving a message from a queue

<?php
$msg = $conn->receive('queue://receive/test');

if (!$msg) {
  // The receive failed!
  echo "Receive failed ($conn->errno) $conn->error";
}
?>

Example #2 Receiving a message from a queue with options

In this example the SAM_CORRELID option is used to specify a correlation id string to be used to identify the message to receive. A wait timeout of 10 seconds is also specified.

<?php

$msg = $conn->receive('queue://receive/test', array(SAM_CORRELID => $token, SAM_WAIT => 10000));

?>

Example #3 Receiving a message from a subscription

In this example we show how to receive a message from a subscription id.

<?php
$msg = $conn->receive($subscriptionName);

if (!$msg) {
  // The receive failed!
  echo "Receive failed ($conn->errno) $conn->error";
}
?>

Please note that $subscriptionName is a subscription id returned from an earlier subscribe call.

See Also

  • SAMConnection::send


Remove a message from a queue

  • « SAMConnection::receive
  • SAMConnection::rollback »
  • PHP Manual
  • SAM Functions
  • Remove a message from a queue

SAMConnection::remove

(PECL sam >= 0.1.0)

SAMConnection::remove — Remove a message from a queue

Description

SAMConnection::remove ( string $target [, array $properties ] ) : SAMMessage

Removes a message from a queue.

Parameters

target

The identity of the queue from which to remove the message.

properties

An optional associative array of properties describing other parameters to control the remove operation.

Property name | Possible values
SAM_CORRELID | This is the target correlation id string of the message. This would typically have been returned by a "send" request.
SAM_MESSAGEID | This is the message id string of the message which is to be removed.

Return Values

This method returns FALSE if an error occurs.

Examples

Example #1 Removing a message from a queue by message id

<?php
if (!$conn->remove('queue://receive/test', array(SAM_MESSAGEID => $messageId))) {
  // The remove failed!
  echo "Remove failed ($conn->errno) $conn->error";
}
?>


Cancels (rolls back) an in-flight unit of work

  • « SAMConnection::remove
  • SAMConnection::send »
  • PHP Manual
  • SAM Functions
  • Cancels (rolls back) an in-flight unit of work

SAMConnection::rollback

(PECL sam >= 0.1.0)

SAMConnection::rollback — Cancels (rolls back) an in-flight unit of work

Description

SAMConnection::rollback ( void ) : bool

Rolls back an in-flight unit of work.

Return Values

This method returns FALSE if an error occurs.

Examples

Example #1 Cancelling an in-flight unit of work

<?php
if (!$conn->rollback()) {
  // The rollback failed!
  echo "Rollback failed ($conn->errno) $conn->error";
}
?>

See Also

  • SAMConnection::commit


Send a message to a queue or publish an item to a topic

  • « SAMConnection::rollback
  • SAMConnection::setDebug »
  • PHP Manual
  • SAM Functions
  • Send a message to a queue or publish an item to a topic

SAMConnection::send

(PECL sam >= 0.1.0)

SAMConnection::send — Send a message to a queue or publish an item to a topic

Description

SAMConnection::send ( string $target , SAMMessage $msg [, array $properties ] ) : string

The "send" method is used to send a message to a specific queue or to publish to a specific topic. The method returns a correlation id that can be used as a selector to identify reply or response messages when these are requested.

Parameters

target

If sending a message, the identity of the queue (queue://queuename) or if publishing to a topic the identity of the topic (topic://topicname) to which the message is to be delivered.

msg

The message to be sent or published.

properties

An optional associative array of properties describing other parameters to control the receive operation.

Property name | Possible values
SAM_DELIVERYMODE | Indicates whether the messaging server should ensure delivery or whether it is acceptable for messages to be lost in the case of system failures. The value of this property may be set to either SAM_PERSISTENT, to indicate that message loss is not acceptable, or SAM_NON_PERSISTENT, if message loss is acceptable. The resulting behaviour of the send will vary depending on the capabilities of the messaging server the PHP script is currently connected to. If the server does not support persistent messages and SAM_PERSISTENT is specified the send request will fail with an error indication showing the capability is not available.
SAM_PRIORITY | A numeric value between 0 and 9 indicating the desired message delivery priority. A priority value of 0 indicates the lowest priority while 9 indicates highest priority. If no priority is specified a default will be assigned which is dependent on the messaging server being used.
SAM_CORRELID | A string to be assigned as a correlation id for this message. If no value is given the messaging server may assign a value automatically.
SAM_TIMETOLIVE | A time in milliseconds indicating how long the messaging server should retain the message on a queue before discarding it. The default value is 0 indicating the message should be retained indefinitely.
SAM_WMQ_TARGET_CLIENT | This property is only valid when using WebSphere MQ and indicates whether or not an RFH2 header should be included with the message. This option may be set to either 'jms' or 'mq'. The default is 'jms' which means that an RFH2 header is included. If the value 'mq' is specified then no RFH2 is included with the message.

Return Values

A correlation id string that can be used in a subsequent receive call as a selector to obtain any reply or response that has been requested or FALSE if an error occurred.

Note:

A correlation id will only be returned for a successful send to a queue destination (queue://xxxx) in which case it will reflect the message identity of the message on the queue. In the case of a send being used to publish data to a topic the return value will be TRUE as no correlation id is available for return.

Examples

Example #1 Send a message to a queue

<?php
$msg = new SAMMessage('This is a simple text message');
$correlId = $conn->send('queue://send/test', $msg);
if (!$correlId) {
    // The send failed!
    echo "Send failed ($conn->errno) $conn->error";
}

?>

Example #2 Publish a message to a topic

<?php
$msg = new SAMMessage('This is a simple text item');
if (!$conn->send('topic://test', $msg)) {
    // The Send failed!
    echo "Send failed ($conn->errno) $conn->error";
}
?>

Example #3 Send a request and receive a response

<?php
$msg = new SAMMessage('This is a simple text message');
$msg->header->SAM_REPLY_TO = 'queue://receive/test';
$correlid = $conn->send('queue://send/test', $msg);

if (!$correlid) {
    // The Send failed!
    echo "Send failed ($conn->errno) $conn->error";
} else {
    $resp = $conn->receive('queue://receive/test', array(SAM_CORRELID => $correlid));
}
?>

See Also

  • SAMConnection::receive


Turn on or off additional debugging output

  • « SAMConnection::send
  • SAMConnection::subscribe »
  • PHP Manual
  • SAM Functions
  • Turn on or off additional debugging output

SAMConnection::setDebug

(PECL sam >= 1.1.0)

SAMConnection::setDebug — Turn on or off additional debugging output

Description

The "setdebug" method is used to turn on or off additional debugging output. The SAM framework will provide method/function entry and exit trace data plus additional information. Protocol specific implementations also provide extra output.

SAMConnection::setDebug ( bool $switch ) : void

Parameters

switch

If this parameter is set to TRUE additional debugging output will be provided. If the value is set to FALSE output of additional information will be stopped.

Return Values

No value is returned.

Examples

Example #1 Turn on debugging output

<?php
$conn->setdebug(TRUE);
?>

Example #2 Turn off debugging output

<?php
$conn->setdebug(FALSE);
?>


Create a subscription to a specified topic

  • « SAMConnection::setDebug
  • SAMConnection::unsubscribe »
  • PHP Manual
  • SAM Functions
  • Create a subscription to a specified topic

SAMConnection::subscribe

(PECL sam >= 0.1.0)

SAMConnection::subscribe — Create a subscription to a specified topic

Description

SAMConnection::subscribe ( string $targetTopic ) : string

The "subscribe" method is used to create a new subscription to a specified topic.

Parameters

targetTopic

The identity of the topic (topic://topicname) to subscribe to.

Return Values

A subscription identifier that can be used in a subsequent receive call as a selector to obtain any topic data or FALSE if an error occurred. The subscription identifier should be used in the receive call in place of the simple topic name.

Examples

Example #1 Subscribe to a topic

<?php
$subid = $conn->subscribe('topic://A');
if (!$subid) {
  // The subscribe failed!
  echo "Subscribe failed ($conn->errno) $conn->error";
}
?>

See Also

  • SAMConnection::unsubscribe


Cancel a subscription to a specified topic

  • « SAMConnection::subscribe
  • SAMMessage::body »
  • PHP Manual
  • SAM Functions
  • Cancel a subscription to a specified topic

SAMConnection::unsubscribe

(PECL sam >= 0.1.0)

SAMConnection::unsubscribe — Cancel a subscription to a specified topic

Description

SAMConnection::unsubscribe ( string $subscriptionId [, string $targetTopic ] ) : bool

The "unsubscribe" method is used to delete an existing subscription to a specified topic.

Parameters

subscriptionId

The identifier of an existing subscription as returned by a call to the subscribe method.

Return Values

This method returns FALSE if an error occurs.

Examples

Example #1 Delete a subscription

<?php
if (!$conn->unsubscribe($subid)) {
    // The unsubscribe failed!
    echo "Unsubscribe failed ($conn->errno) $conn->error";
}
?>

See Also

  • SAMConnection::subscribe


The body of the message

  • « SAMConnection::unsubscribe
  • SAMMessage::__construct »
  • PHP Manual
  • SAM Functions
  • The body of the message

SAMMessage::body

(PECL sam >= 0.1.0)

SAMMessage::body — The body of the message

Description

string $SAMMessage->body;

The "body" property contains the actual body of the message. It may not always be set.

Examples

Example #1 Setting a text string into the body of a message

<?php
$msg = new SAMMessage();
$msg->body = 'This is a simple message';

?>

See Also

  • SAMMessage::header


Creates a new Message object

  • « SAMMessage::body
  • SAMMessage::header »
  • PHP Manual
  • SAM Functions
  • Creates a new Message object

SAMMessage::__construct

(PECL sam >= 0.1.0)

SAMMessage::__construct — Creates a new Message object

Description

SAMMessage::__construct ([ mixed $body ] )

Creates a new SAMMessage object optionally specifying a message body.

Parameters

body

The optional body for the message.

Examples

Example #1 Creating a message

<?php

$msg = new SAMMessage();

?>

Example #2 Creating a message with a simple text payload

<?php

$msg = new SAMMessage('This is a simple text message');

?>


The header properties of the message

  • « SAMMessage::__construct
  • ScoutAPM »
  • PHP Manual
  • SAM Functions
  • The header properties of the message

SAMMessage::header

(PECL sam >= 0.1.0)

SAMMessage::header — The header properties of the message

Description

object $SAMMessage->header;

The header property is a container for any system or user properties that area associated with the message.

Properties may be assigned by the sender of a message to control the way the messaging systems handles it or may be assigned by the messaging system itself to tell the recipient extra information about the message or the way in which it has been handled.

Some properties are understood by SAM in which case constants have been defined for them. The majority of properties however are ignored by the SAM implementation and simply passed through to the underlying messaging systems allowing the application to use messaging specific property names or to define its own "user" properties.

The SAM defined properties are as follows:

Property name | Possible values
SAM_MESSAGEID | When a message is received this field contains the unique identifier of the message as allocated by the underlying messaging system. When sending a message this field is ignored.
SAM_REPLY_TO | A string providing the identity of the queue on to which responses to this message should be posted.
SAM_TYPE

An indication of the type of message to be sent. The value may be SAM_TEXT indicating the contents of the message body is a text string, or SAM_BYTES indicating the contents of the message body are some application defined format.

The way in which this property is used may depend on the underlying messaging server. For instance a messaging server that supports the JMS (Java Message Service) specification may interpret this value and send messages of type "jms_text" and "jms_bytes". In addition, if the SAM_TYPE property is set to SAM_TEXT the data provided for the message body is expected to be a UTF8 encoded string.

When setting the values of properties it is often useful to give a hint as to the format in which the property should be delivered to the messaging system. By default property values are delivered as text and the following simple syntax may be used to set a value:

Example #1 Setting a text format property using the default syntax

<?php
$msg = new SAMMessage();

$msg->header->myPropertyName = 'textData';
?>

If it is desired to pass type information an alternative syntax may be used where the value and the type hint are passed in an associative array:

Example #2 Setting a text format property using a type hint

<?php
$msg = new SAMMessage();

$msg->header->myPropertyName = array('textData', SAM_STRING);
?>

When passing a type hint the type entry should be one of the SAM defined constant values as defined by the following table:

Constant | Type description
SAM_BOOLEAN | Any value passed will be interpreted as logical true or false. If the value cannot be interpreted as a PHP boolean value the value passed to the messaging system is undefined.
SAM_BYTE | An 8-bit signed integer value. SAM will attempt to convert the property value specified into a single byte value to pass to the messaging system. If a string value is passed an attempt will be made to interpret the string as a numeric value. If the numeric value cannot be expressed as an 8-bit signed binary value data may be lost in the conversion.
SAM_DOUBLE | A long floating point value. SAM will attempt to convert the property value specified into a floating point value with 15 digits of precision. If a string value is passed an attempt will be made to interpret the string as a numeric value. If the passed value cannot be expressed as a 15 digit floating point value data may be lost in the conversion.
SAM_FLOAT | A short floating point value. SAM will attempt to convert the property value specified into a floating point value with 7 digits of precision. If a string value is passed an attempt will be made to interpret the string as a numeric value. If the passed value cannot be expressed as a 7 digit floating point value data may be lost in the conversion.
SAM_INT | An 32-bit signed integer value. SAM will attempt to convert the property value specified into a 32-bit value to pass to the messaging system. If a string value is passed an attempt will be made to interpret the string as a numeric value. If the numeric value cannot be expressed as an 32-bit signed binary value data may be lost in the conversion.
SAM_LONG | An 64-bit signed integer value. SAM will attempt to convert the property value specified into a 64-bit value to pass to the messaging system. If a string value is passed an attempt will be made to interpret the string as a numeric value. If the numeric value cannot be expressed as an 64-bit signed binary value data may be lost in the conversion.
SAM_STRING | SAM will interpret the property value specified as a string and pass it to the messaging system accordingly.

Examples

Example #3 Setting properties as the sender of a message

<?php
$msg = new SAMMessage('This is a test message');

// defining SAM specific properties...
$msg->header->SAM_REPLY_TO = 'queue://test/replyQueue';

// defining arbitrary properties...
//
// a default string property
$msg->header->myStringProp1 = 'a string property';
// a string property with a type hint
$msg->header->myStringProp2 = array('another string property', SAM_STRING);

// a boolean property
$msg->header->myBoolProp = array(FALSE, SAM_BOOL);

// numeric format properties
$msg->header->myIntProp = array(32768, SAM_INT);
$msg->header->myLongProp = array(9876543, SAM_LONG);
$msg->header->myByteProp1 = array(123, SAM_BYTE);
$msg->header->myByteProp2 = array('12', SAM_BYTE);
$msg->header->myFloatProp = array(3.141592, SAM_FLOAT);
$msg->header->myDoubleProp = array(3.14159265358979, SAM_DOUBLE);
?>

Example #4 Retreiving property values from a message

<?php

// accessing an application specific property
$intProp = $msg->header->MyIntProp;

// accessing a messaging system specific property
$encoding = $msg->header->JMS_IBM_Msgtype;

?>

See Also

  • SAMMessage::body


ScoutAPM

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
  • Predefined Constants
  • Scoutapm Functions
    • scoutapm_get_calls — Returns a list of instrumented calls that have occurred
    • scoutapm_list_instrumented_functions — List functions scoutapm will instrument.


Introduction

Note: This extension is not available on Windows platforms.

ScoutAPM's extension for PHP provides additional capabilities to application monitoring over just using the base PHP userland library.


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

  • PHP >= 7.1.0
  • Windows is not currently supported


Installation

This extension is available on PECL. Run:

$ sudo pecl install scoutapm
You may need to add Scout to your php.ini, for example:
extension=scoutapm.so


  • « Runtime Configuration
  • Scoutapm Functions »
  • PHP Manual
  • ScoutAPM
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


Scoutapm Functions

Table of Contents

  • scoutapm_get_calls — Returns a list of instrumented calls that have occurred
  • scoutapm_list_instrumented_functions — List functions scoutapm will instrument.


Returns a list of instrumented calls that have occurred

  • « Scoutapm Functions
  • scoutapm_list_instrumented_functions »
  • PHP Manual
  • Scoutapm Functions
  • Returns a list of instrumented calls that have occurred

scoutapm_get_calls

(PECL scoutapm >= 1.0.0)

scoutapm_get_calls — Returns a list of instrumented calls that have occurred

Description

scoutapm_get_calls ( void ) : array

Returns a list of any instrumented function calls since scoutapm_get_calls() was last called. The list is cleared each time the function is called.

Parameters

This function has no parameters.

Return Values

scoutapm_get_calls() returns an array containing a list of all recorded calls to instrumented function calls.

Examples

Example #1 Fetch instrumented calls

<?php

file_get_contents('a.txt');
file_get_contents('b.txt');

print_r(scoutapm_get_calls());
?>

The above example will output something similar to:

Array
(
    [0] => Array
        (
            [function] => file_get_contents
            [entered] => 1576839727.7934
            [exited] => 1576839727.7935
            [time_taken] => 2.7894973754883E-5
            [argv] => Array
                (
                    [0] => a.txt
                )

        )

    [1] => Array
        (
            [function] => file_get_contents
            [entered] => 1576839727.7935
            [exited] => 1576839727.7935
            [time_taken] => 7.8678131103516E-6
            [argv] => Array
                (
                    [0] => b.txt
                )

        )

)


List functions scoutapm will instrument.

  • « scoutapm_get_calls
  • SNMP »
  • PHP Manual
  • Scoutapm Functions
  • List functions scoutapm will instrument.

scoutapm_list_instrumented_functions

(PECL scoutapm >= 1.0.2)

scoutapm_list_instrumented_functions — List functions scoutapm will instrument.

Description

scoutapm_list_instrumented_functions ( void ) : array

Returns a list of the functions the extension will instrument.

Parameters

This function has no parameters.

Return Values

scoutapm_list_instrumented_functions() returns an array containing a list of all functions that the scoutapm extension is able to instrument in the current installation.

Examples

Example #1 Fetch the list of functions scoutapm will instrument

<?php
print_r(scoutapm_list_instrumented_functions());
?>

The above example will output something similar to:

Array
(
    [0] => file_get_contents
    [1] => file_put_contents
    [2] => fopen
    [3] => fread
    [4] => fwrite
    [5] => pdo->exec
    [6] => pdo->query
    [7] => pdo->prepare
    [8] => pdostatement->execute
)


SNMP

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • SNMP Functions
    • snmp_get_quick_print — Fetches the current value of the UCD library's quick_print setting
    • snmp_get_valueretrieval — Return the method how the SNMP values will be returned
    • snmp_read_mib — Reads and parses a MIB file into the active MIB tree
    • snmp_set_enum_print — Return all values that are enums with their enum value instead of the raw integer
    • snmp_set_oid_numeric_print — Set the OID output format
    • snmp_set_oid_output_format — Set the OID output format
    • snmp_set_quick_print — Set the value of quick_print within the UCD SNMP library
    • snmp_set_valueretrieval — Specify the method how the SNMP values will be returned
    • snmp2_get — Fetch an SNMP object
    • snmp2_getnext — Fetch the SNMP object which follows the given object id
    • snmp2_real_walk — Return all objects including their respective object ID within the specified one
    • snmp2_set — Set the value of an SNMP object
    • snmp2_walk — Fetch all the SNMP objects from an agent
    • snmp3_get — Fetch an SNMP object
    • snmp3_getnext — Fetch the SNMP object which follows the given object id
    • snmp3_real_walk — Return all objects including their respective object ID within the specified one
    • snmp3_set — Set the value of an SNMP object
    • snmp3_walk — Fetch all the SNMP objects from an agent
    • snmpget — Fetch an SNMP object
    • snmpgetnext — Fetch the SNMP object which follows the given object id
    • snmprealwalk — Return all objects including their respective object ID within the specified one
    • snmpset — Set the value of an SNMP object
    • snmpwalk — Fetch all the SNMP objects from an agent
    • snmpwalkoid — Query for a tree of information about a network entity
  • SNMP — The SNMP class
    • SNMP::close — Close SNMP session
    • SNMP::__construct — Creates SNMP instance representing session to remote SNMP agent
    • SNMP::get — Fetch an SNMP object
    • SNMP::getErrno — Get last error code
    • SNMP::getError — Get last error message
    • SNMP::getnext — Fetch an SNMP object which follows the given object id
    • SNMP::set — Set the value of an SNMP object
    • SNMP::setSecurity — Configures security-related SNMPv3 session parameters
    • SNMP::walk — Fetch SNMP object subtree
  • SNMPException — The SNMPException class


Introduction

The SNMP extension provides a very simple and easily usable toolset for managing remote devices via the Simple Network Management Protocol.

As it is a wrapper around the underlying Net-SNMP (or UCD-SNMP on older systems) library, all basic concepts are the same and the PHP functions change their behaviour depending on the Net-SNMP configuration files and environment variables.

Beginning with PHP 5.4, an OO API is available.

More information about Net-SNMP can be found at » http://www.net-snmp.org/


Requirements

In order to use the SNMP functions requires installation of the » Net-SNMP package. SNMPv3 functions available only when » OpenSSL package is installed too.

Beginning with PHP 5.4.0 Net-SNMP version 5.3+ is required for Unix installations and Net-SNMP version 5.4+ for Windows.


Installation

PHP 5.3.0, 5.3.1 and 5.3.2 do not have SNMP support. SNMP support has been restored in PHP 5.3.3.

The Windows distribution of Net-SNMP contains support files for SNMP in the mibs directory. This directory should added to Windows' environment variables, as MIBDIRS, with the value being the full path to the mibs directory: e.g. c:\usr\mibs.

Important notes for PHP prior to 5.4.0: In order to use the UCD SNMP package, you need to define NO_ZEROLENGTH_COMMUNITY to 1 before compiling it. After configuring UCD SNMP, edit config.h or acconfig.h and search for NO_ZEROLENGTH_COMMUNITY. Uncomment the #define line. It should look like this afterwards:

#define NO_ZEROLENGTH_COMMUNITY 1
Now compile PHP --with-snmp[=DIR] .

If you see strange segmentation faults in combination with SNMP commands, you did not follow the above instructions. If you do not want to recompile UCD SNMP, you can compile PHP with the --enable-ucd-snmp-hack switch which will work around the misfeature.


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.

For the snmp_set_oid_output_format()
SNMP_OID_OUTPUT_SUFFIX (integer)
As of 5.4.0
SNMP_OID_OUTPUT_MODULE (integer)
As of 5.4.0
SNMP_OID_OUTPUT_FULL (integer)
As of 5.2.0
SNMP_OID_OUTPUT_NUMERIC (integer)
As of 5.2.0
SNMP_OID_OUTPUT_UCD (integer)
As of 5.4.0
SNMP_OID_OUTPUT_NONE (integer)
As of 5.4.0
For the snmp_set_valueretrieval()
SNMP_VALUE_LIBRARY (integer)
SNMP_VALUE_PLAIN (integer)
SNMP_VALUE_OBJECT (integer)
SNMP types as returned if SNMP_VALUE_OBJECT was used with snmp_set_valueretrieval()
SNMP_BIT_STR (integer)
SNMP_OCTET_STR (integer)
SNMP_OPAQUE (integer)
SNMP_NULL (integer)
SNMP_OBJECT_ID (integer)
SNMP_IPADDRESS (integer)
SNMP_COUNTER (integer)
SNMP_UNSIGNED (integer)
SNMP_TIMETICKS (integer)
SNMP_UINTEGER (integer)
SNMP_INTEGER (integer)
SNMP_COUNTER64 (integer)


SNMP Functions

Table of Contents

  • snmp_get_quick_print — Fetches the current value of the UCD library's quick_print setting
  • snmp_get_valueretrieval — Return the method how the SNMP values will be returned
  • snmp_read_mib — Reads and parses a MIB file into the active MIB tree
  • snmp_set_enum_print — Return all values that are enums with their enum value instead of the raw integer
  • snmp_set_oid_numeric_print — Set the OID output format
  • snmp_set_oid_output_format — Set the OID output format
  • snmp_set_quick_print — Set the value of quick_print within the UCD SNMP library
  • snmp_set_valueretrieval — Specify the method how the SNMP values will be returned
  • snmp2_get — Fetch an SNMP object
  • snmp2_getnext — Fetch the SNMP object which follows the given object id
  • snmp2_real_walk — Return all objects including their respective object ID within the specified one
  • snmp2_set — Set the value of an SNMP object
  • snmp2_walk — Fetch all the SNMP objects from an agent
  • snmp3_get — Fetch an SNMP object
  • snmp3_getnext — Fetch the SNMP object which follows the given object id
  • snmp3_real_walk — Return all objects including their respective object ID within the specified one
  • snmp3_set — Set the value of an SNMP object
  • snmp3_walk — Fetch all the SNMP objects from an agent
  • snmpget — Fetch an SNMP object
  • snmpgetnext — Fetch the SNMP object which follows the given object id
  • snmprealwalk — Return all objects including their respective object ID within the specified one
  • snmpset — Set the value of an SNMP object
  • snmpwalk — Fetch all the SNMP objects from an agent
  • snmpwalkoid — Query for a tree of information about a network entity


Fetches the current value of the UCD library's quick_print setting

  • « SNMP Functions
  • snmp_get_valueretrieval »
  • PHP Manual
  • SNMP Functions
  • Fetches the current value of the UCD library's quick_print setting

snmp_get_quick_print

(PHP 4, PHP 5, PHP 7)

snmp_get_quick_print — Fetches the current value of the UCD library's quick_print setting

Description

snmp_get_quick_print ( void ) : bool

Returns the current value stored in the UCD Library for quick_print. quick_print is off by default.

Return Values

Returns TRUE if quick_print is on, FALSE otherwise.

Examples

Example #1 snmp_get_quick_print() example

<?php
$quickprint = snmp_get_quick_print();
?>

See Also

  • snmp_set_quick_print() - Set the value of quick_print within the UCD SNMP library for a full description of what quick_print does.


Return the method how the SNMP values will be returned

  • « snmp_get_quick_print
  • snmp_read_mib »
  • PHP Manual
  • SNMP Functions
  • Return the method how the SNMP values will be returned

snmp_get_valueretrieval

(PHP 4 >= 4.3.3, PHP 5, PHP 7)

snmp_get_valueretrieval — Return the method how the SNMP values will be returned

Description

snmp_get_valueretrieval ( void ) : int

Return Values

OR-ed combitantion of constants ( SNMP_VALUE_LIBRARY or SNMP_VALUE_PLAIN ) with possible SNMP_VALUE_OBJECT set.

Examples

Example #1 Using snmp_get_valueretrieval

<?php
 $ret = snmpget('localhost', 'public', 'IF-MIB::ifName.1');
 if (snmp_get_valueretrieval() & SNMP_VALUE_OBJECT) {
   echo $ret->value;
 } else {
   echo $ret;
 }
?>

See Also

  • snmp_set_valueretrieval() - Specify the method how the SNMP values will be returned
  • Predefined Constants


Reads and parses a MIB file into the active MIB tree

  • « snmp_get_valueretrieval
  • snmp_set_enum_print »
  • PHP Manual
  • SNMP Functions
  • Reads and parses a MIB file into the active MIB tree

snmp_read_mib

(PHP 5, PHP 7)

snmp_read_mib — Reads and parses a MIB file into the active MIB tree

Description

snmp_read_mib ( string $filename ) : bool

This function is used to load additional, e.g. vendor specific, MIBs so that human readable OIDs like VENDOR-MIB::foo.1 instead of error prone numeric OIDs can be used.

The order in which the MIBs are loaded does matter as the underlying Net-SNMP libary will print warnings if referenced objects cannot be resolved.

Parameters

filename

The filename of the MIB.

Examples

Example #1 Using snmp_read_mib()

<?php
 print_r( snmprealwalk('localhost', 'public', '.1.3.6.1.2.1.2.3.4.5') );

 snmp_read_mib('./FOO-BAR-MIB.txt');
 print_r( snmprealwalk('localhost', 'public', 'FOO-BAR-MIB::someTable' );
?>

The above example is made up but the results would look like:

Array
(
    [iso.3.6.1.2.1.2.3.4.5.0] => Gauge32: 6
)
Array
(
    [FOO-BAR-MIB::someTable.0] => Gauge32: 6
)


Return all values that are enums with their enum value instead of the raw integer

  • « snmp_read_mib
  • snmp_set_oid_numeric_print »
  • PHP Manual
  • SNMP Functions
  • Return all values that are enums with their enum value instead of the raw integer

snmp_set_enum_print

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

snmp_set_enum_print — Return all values that are enums with their enum value instead of the raw integer

Description

snmp_set_enum_print ( int $enum_print ) : bool

This function toggles if snmpwalk/snmpget etc. should automatically lookup enum values in the MIB and return them together with their human readable string.

Parameters

enum_print

As the value is interpreted as boolean by the Net-SNMP library, it can only be "0" or "1".

Examples

Example #1 Using snmp_set_enum_print()

<?php
 snmp_set_enum_print(0);
 echo snmpget('localhost', 'public', 'IF-MIB::ifOperStatus.3') . "\n";
 snmp_set_enum_print(1);
 echo snmpget('localhost', 'public', 'IF-MIB::ifOperStatus.3') . "\n";
?>

The above would return

 INTEGER: up(1)
 INTEGER: 1

Notes

Note:

snmp_set_enum_print() is only available when using the UCD SNMP library. This function is not available when using the Windows SNMP library.


Set the OID output format

  • « snmp_set_enum_print
  • snmp_set_oid_output_format »
  • PHP Manual
  • SNMP Functions
  • Set the OID output format

snmp_set_oid_numeric_print

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

snmp_set_oid_numeric_print — Set the OID output format

Description

snmp_set_oid_numeric_print ( int $oid_format ) : void

This function is an alias of: snmp_set_oid_output_format().

Changelog

Version | Description
5.2.0 | Since PHP 5.2.0.

See Also

  • snmp_set_oid_output_format() - Set the OID output format


Set the OID output format

  • « snmp_set_oid_numeric_print
  • snmp_set_quick_print »
  • PHP Manual
  • SNMP Functions
  • Set the OID output format

snmp_set_oid_output_format

(PHP 5 >= 5.2.0, PHP 7)

snmp_set_oid_output_format — Set the OID output format

Description

snmp_set_oid_output_format ( int $oid_format = SNMP_OID_OUTPUT_MODULE ) : bool

snmp_set_oid_output_format() sets the output format to be full or numeric.

Parameters

oid_format
OID .1.3.6.1.2.1.1.3.0 representation for various oid_format values
SNMP_OID_OUTPUT_FULL | .iso.org.dod.internet.mgmt.mib-2.system.sysUpTime.sysUpTimeInstance
SNMP_OID_OUTPUT_NUMERIC | .1.3.6.1.2.1.1.3.0

Begining from PHP 5.4.0 four additional constants available:

SNMP_OID_OUTPUT_MODULE | DISMAN-EVENT-MIB::sysUpTimeInstance
SNMP_OID_OUTPUT_SUFFIX | sysUpTimeInstance
SNMP_OID_OUTPUT_UCD | system.sysUpTime.sysUpTimeInstance
SNMP_OID_OUTPUT_NONE | Undefined

Return Values

No value is returned.

Notes

Note:

snmp_set_oid_output_format() is only available when using the UCD SNMP library. This function is not available when using the Windows SNMP library.

Examples

Example #1 Using snmprealwalk()

<?php

 snmp_read_mib("/usr/share/mibs/netsnmp/NET-SNMP-TC");

 // default or SNMP_OID_OUTPUT_MODULE in PHP >= 5.3.6
 print_r( snmprealwalk('localhost', 'public', 'RFC1213-MIB::sysObjectID') );

 snmp_set_oid_output_format(SNMP_OID_OUTPUT_NUMERIC);
 print_r( snmprealwalk('localhost', 'public', 'RFC1213-MIB::sysObjectID') );

 snmp_set_oid_output_format(SNMP_OID_OUTPUT_FULL);
 print_r( snmprealwalk('localhost', 'public', 'RFC1213-MIB::sysObjectID') );
?>

The above would output:

 Array
 (
    [RFC1213-MIB::sysObjectID.0] => OID: NET-SNMP-TC::linux
 )
 Array
 (
    [.1.3.6.1.2.1.1.2.0] => OID: .1.3.6.1.4.1.8072.3.2.10
 )
 Array
 (
    [.iso.org.dod.internet.mgmt.mib-2.system.sysObjectID.0] => OID: .iso.org.dod.internet.private.enterprises.netSnmp.netSnmpEnumerations.netSnmpAgentOIDs.linux
 )


Set the value of quick_print within the UCD SNMP library

  • « snmp_set_oid_output_format
  • snmp_set_valueretrieval »
  • PHP Manual
  • SNMP Functions
  • Set the value of quick_print within the UCD SNMP library

snmp_set_quick_print

(PHP 4, PHP 5, PHP 7)

snmp_set_quick_print — Set the value of quick_print within the UCD SNMP library

Description

snmp_set_quick_print ( bool $quick_print ) : bool

Sets the value of quick_print within the UCD SNMP library. When this is set (1), the SNMP library will return 'quick printed' values. This means that just the value will be printed. When quick_print is not enabled (default) the UCD SNMP library prints extra information including the type of the value (i.e. IpAddress or OID). Additionally, if quick_print is not enabled, the library prints additional hex values for all strings of three characters or less.

By default the UCD SNMP library returns verbose values, quick_print is used to return only the value.

Currently strings are still returned with extra quotes, this will be corrected in a later release.

Parameters

quick_print

Return Values

No value is returned.

Examples

Setting quick_print is often used when using the information returned rather than displaying it.

Example #1 Using snmp_set_quick_print()

<?php
snmp_set_quick_print(0);
$a = snmpget("127.0.0.1", "public", ".1.3.6.1.2.1.2.2.1.9.1");
echo "$a\n";
snmp_set_quick_print(1);
$a = snmpget("127.0.0.1", "public", ".1.3.6.1.2.1.2.2.1.9.1");
echo "$a\n";
?>

The above example will output something similar to:

'Timeticks: (0) 0:00:00.00'
'0:00:00.00'

See Also

  • snmp_get_quick_print() - Fetches the current value of the UCD library's quick_print setting


Specify the method how the SNMP values will be returned

  • « snmp_set_quick_print
  • snmp2_get »
  • PHP Manual
  • SNMP Functions
  • Specify the method how the SNMP values will be returned

snmp_set_valueretrieval

(PHP 4 >= 4.3.3, PHP 5, PHP 7)

snmp_set_valueretrieval — Specify the method how the SNMP values will be returned

Description

snmp_set_valueretrieval ( int $method = SNMP_VALUE_LIBRARY ) : bool

Parameters

method
types
SNMP_VALUE_LIBRARY | The return values will be as returned by the Net-SNMP library.
SNMP_VALUE_PLAIN | The return values will be the plain value without the SNMP type hint.
SNMP_VALUE_OBJECT | The return values will be objects with the properties "value" and "type", where the latter is one of the SNMP_OCTET_STR, SNMP_COUNTER etc. constants. The way "value" is returned is based on which one of constants SNMP_VALUE_LIBRARY, SNMP_VALUE_PLAIN is set.

Examples

Example #1 Using snmp_set_valueretrieval()

<?php
 snmp_set_valueretrieval(SNMP_VALUE_LIBRARY);
 $ret = snmpget('localhost', 'public', 'IF-MIB::ifName.1');
 // $ret = "STRING: lo"

 snmp_set_valueretrieval(SNMP_VALUE_PLAIN);
 $ret = snmpget('localhost', 'public', 'IF-MIB::ifName.1');
 // $ret = "lo";

 snmp_set_valueretrieval(SNMP_VALUE_OBJECT);
 $ret = snmpget('localhost', 'public', 'IF-MIB::ifName.1');
 // stdClass Object
 // (
 //   [type] => 4        <-- SNMP_OCTET_STR, see constants
 //   [value] => lo
 // )

 // PHP 5.4+ examples
 snmp_set_valueretrieval(SNMP_VALUE_OBJECT | SNMP_VALUE_PLAIN);
 $ret = snmpget('localhost', 'public', 'IF-MIB::ifName.1');
 // stdClass Object
 // (
 //   [type] => 4        <-- SNMP_OCTET_STR, see constants
 //   [value] => lo
 // )

 snmp_set_valueretrieval(SNMP_VALUE_OBJECT | SNMP_VALUE_LIBRARY);
 $ret = snmpget('localhost', 'public', 'IF-MIB::ifName.1');
 // stdClass Object
 // (
 //   [type] => 4        <-- SNMP_OCTET_STR, see constants
 //   [value] => STRING: lo
 // )

?>

Changelog

Version | Description
5.4.0 | Constants SNMP_VALUE_PLAIN or SNMP_VALUE_LIBRARY may be combined with SNMP_VALUE_OBJECT resulting different way of representing contents of value array element in return value of GET-function. If no SNMP_VALUE_{PLAIN,LIBRARY} constant is accompanying SNMP_VALUE_OBJECT, SNMP_VALUE_LIBRARY is used. Prior to 5.4.0 SNMP_VALUE_OBJECT effecively meant SNMP_VALUE_OBJECT|SNMP_VALUE_PLAIN.

See Also

  • snmp_get_valueretrieval() - Return the method how the SNMP values will be returned
  • Predefined Constants


Fetch an SNMP object

  • « snmp_set_valueretrieval
  • snmp2_getnext »
  • PHP Manual
  • SNMP Functions
  • Fetch an SNMP object

snmp2_get

(PHP 5 >= 5.2.0, PHP 7)

snmp2_get — Fetch an SNMP object

Description

snmp2_get ( string $host , string $community , string $object_id [, int $timeout = 1000000 [, int $retries = 5 ]] ) : string

The snmp2_get() function is used to read the value of an SNMP object specified by the object_id.

Parameters

host

The SNMP agent.

community

The read community.

object_id

The SNMP object.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Return Values

Returns SNMP object value on success or FALSE on error.

Examples

Example #1 Using snmp2_get()

<?php
$syscontact = snmp2_get("127.0.0.1", "public", "system.SysContact.0");
?>

See Also

  • snmp2_set() - Set the value of an SNMP object


Fetch the SNMP object which follows the given object id

  • « snmp2_get
  • snmp2_real_walk »
  • PHP Manual
  • SNMP Functions
  • Fetch the SNMP object which follows the given object id

snmp2_getnext

(PHP >= 5.2.0)

snmp2_getnext — Fetch the SNMP object which follows the given object id

Description

snmp2_getnext ( string $host , string $community , string $object_id [, int $timeout = 1000000 [, int $retries = 5 ]] ) : string

The snmp2_get_next() function is used to read the value of the SNMP object that follows the specified object_id.

Parameters

host

The hostname of the SNMP agent (server).

community

The read community.

object_id

The SNMP object id which precedes the wanted one.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Return Values

Returns SNMP object value on success or FALSE on error. In case of an error, an E_WARNING message is shown.

Examples

Example #1 Using snmp2_get_next()

<?php
$nameOfSecondInterface = snmp2_get_next('localhost', 'public', 'IF-MIB::ifName.1';
?>

See Also

  • snmp2_get() - Fetch an SNMP object
  • snmp2_walk() - Fetch all the SNMP objects from an agent


Return all objects including their respective object ID within the specified one

  • « snmp2_getnext
  • snmp2_set »
  • PHP Manual
  • SNMP Functions
  • Return all objects including their respective object ID within the specified one

snmp2_real_walk

(PHP >= 5.2.0)

snmp2_real_walk — Return all objects including their respective object ID within the specified one

Description

snmp2_real_walk ( string $host , string $community , string $object_id [, int $timeout = 1000000 [, int $retries = 5 ]] ) : array

The snmp2_real_walk() function is used to traverse over a number of SNMP objects starting from object_id and return not only their values but also their object ids.

Parameters

host

The hostname of the SNMP agent (server).

community

The read community.

object_id

The SNMP object id which precedes the wanted one.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Return Values

Returns an associative array of the SNMP object ids and their values on success or FALSE on error. In case of an error, an E_WARNING message is shown.

Examples

Example #1 Using snmp2_real_walk()

<?php
 print_r(snmp2_real_walk("localhost", "public", "IF-MIB::ifName"));
?>

The above will output something like:

    Array
      (
      [IF-MIB::ifName.1] => STRING: lo
      [IF-MIB::ifName.2] => STRING: eth0
      [IF-MIB::ifName.3] => STRING: eth2
      [IF-MIB::ifName.4] => STRING: sit0
      [IF-MIB::ifName.5] => STRING: sixxs
    )

See Also

  • snmp2_walk() - Fetch all the SNMP objects from an agent


Set the value of an SNMP object

  • « snmp2_real_walk
  • snmp2_walk »
  • PHP Manual
  • SNMP Functions
  • Set the value of an SNMP object

snmp2_set

(PHP >= 5.2.0)

snmp2_set — Set the value of an SNMP object

Description

snmp2_set ( string $host , string $community , string $object_id , string $type , string $value [, int $timeout = 1000000 [, int $retries = 5 ]] ) : bool

snmp2_set() is used to set the value of an SNMP object specified by the object_id.

Parameters

host

The hostname of the SNMP agent (server).

community

The write community.

object_id

The SNMP object id.

type

The MIB defines the type of each object id. It has to be specified as a single character from the below list.

types
= The type is taken from the MIB
i | INTEGER
u | INTEGER
s | STRING
x | HEX STRING
d | DECIMAL STRING
n | NULLOBJ
o | OBJID
t | TIMETICKS
a | IPADDRESS
b | BITS

If OPAQUE_SPECIAL_TYPES was defined while compiling the SNMP library, the following are also valid:

types
U | unsigned int64
I | signed int64
F | float
D | double

Most of these will use the obvious corresponding ASN.1 type. 's', 'x', 'd' and 'b' are all different ways of specifying an OCTET STRING value, and the 'u' unsigned type is also used for handling Gauge32 values.

If the MIB-Files are loaded by into the MIB Tree with "snmp_read_mib" or by specifying it in the libsnmp config, '=' may be used as the type parameter for all object ids as the type can then be automatically read from the MIB.

Note that there are two ways to set a variable of the type BITS like e.g. "SYNTAX BITS {telnet(0), ftp(1), http(2), icmp(3), snmp(4), ssh(5), https(6)}":

  • Using type "b" and a list of bit numbers. This method is not recommended since GET query for the same OID would return e.g. 0xF8.
  • Using type "x" and a hex number but without(!) the usual "0x" prefix.

See examples section for more details.

value

The new value.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Return Values

Returns TRUE on success or FALSE on failure.

If the SNMP host rejects the data type, an E_WARNING message like "Warning: Error in packet. Reason: (badValue) The value given has the wrong type or length." is shown. If an unknown or invalid OID is specified the warning probably reads "Could not add variable".

Examples

Example #1 Using snmp2_set()

<?php
  snmp2_set("localhost", "public", "IF-MIB::ifAlias.3", "s", "foo");
?>

Example #2 Using snmp2_set() for setting BITS SNMP object id

<?php
  snmp2_set("localhost", "public", 'FOO-MIB::bar.42', 'b', '0 1 2 3 4');
// or
  snmp2_set("localhost", "public", 'FOO-MIB::bar.42', 'x', 'F0');
?>

See Also

  • snmp2_get() - Fetch an SNMP object


Fetch all the SNMP objects from an agent

  • « snmp2_set
  • snmp3_get »
  • PHP Manual
  • SNMP Functions
  • Fetch all the SNMP objects from an agent

snmp2_walk

(PHP >= 5.2.0)

snmp2_walk — Fetch all the SNMP objects from an agent

Description

snmp2_walk ( string $host , string $community , string $object_id [, int $timeout = 1000000 [, int $retries = 5 ]] ) : array

snmp2_walk() function is used to read all the values from an SNMP agent specified by the hostname.

Parameters

host

The SNMP agent (server).

community

The read community.

object_id

If NULL, object_id is taken as the root of the SNMP objects tree and all objects under that tree are returned as an array.

If object_id is specified, all the SNMP objects below that object_id are returned.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Return Values

Returns an array of SNMP object values starting from the object_id as root or FALSE on error.

Examples

Example #1 snmp2_walk() Example

<?php
$a = snmp2_walk("127.0.0.1", "public", "");

foreach ($a as $val) {
    echo "$val\n";
}

?>

Above function call would return all the SNMP objects from the SNMP agent running on localhost. One can step through the values with a loop

See Also

  • snmp2_real_walk() - Return all objects including their respective object ID within the specified one


Fetch an SNMP object

  • « snmp2_walk
  • snmp3_getnext »
  • PHP Manual
  • SNMP Functions
  • Fetch an SNMP object

snmp3_get

(PHP 4, PHP 5, PHP 7)

snmp3_get — Fetch an SNMP object

Description

snmp3_get ( string $host , string $sec_name , string $sec_level , string $auth_protocol , string $auth_passphrase , string $priv_protocol , string $priv_passphrase , string $object_id [, int $timeout = 1000000 [, int $retries = 5 ]] ) : string

The snmp3_get() function is used to read the value of an SNMP object specified by the object_id.

Parameters

host

The hostname of the SNMP agent (server).

sec_name

the security name, usually some kind of username

sec_level

the security level (noAuthNoPriv|authNoPriv|authPriv)

auth_protocol

the authentication protocol (MD5 or SHA)

auth_passphrase

the authentication pass phrase

priv_protocol

the privacy protocol (DES or AES)

priv_passphrase

the privacy pass phrase

object_id

The SNMP object id.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Return Values

Returns SNMP object value on success or FALSE on error.

Examples

Example #1 Using snmp3_get()

<?php
$nameOfSecondInterface = snmp3_get('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'IF-MIB::ifName.2');
?>

See Also

  • snmp3_set() - Set the value of an SNMP object


Fetch the SNMP object which follows the given object id

  • « snmp3_get
  • snmp3_real_walk »
  • PHP Manual
  • SNMP Functions
  • Fetch the SNMP object which follows the given object id

snmp3_getnext

(PHP 5, PHP 7)

snmp3_getnext — Fetch the SNMP object which follows the given object id

Description

snmp3_getnext ( string $host , string $sec_name , string $sec_level , string $auth_protocol , string $auth_passphrase , string $priv_protocol , string $priv_passphrase , string $object_id [, int $timeout = 1000000 [, int $retries = 5 ]] ) : string

The snmp3_getnext() function is used to read the value of the SNMP object that follows the specified object_id.

Parameters

host

The hostname of the SNMP agent (server).

sec_name

the security name, usually some kind of username

sec_level

the security level (noAuthNoPriv|authNoPriv|authPriv)

auth_protocol

the authentication protocol (MD5 or SHA)

auth_passphrase

the authentication pass phrase

priv_protocol

the privacy protocol (DES or AES)

priv_passphrase

the privacy pass phrase

object_id

The SNMP object id.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Return Values

Returns SNMP object value on success or FALSE on error. In case of an error, an E_WARNING message is shown.

Examples

Example #1 Using snmp3_getnext()

<?php
$nameOfSecondInterface = snmp3_getnext('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'IF-MIB::ifName.1');
?>

See Also

  • snmp3_get() - Fetch an SNMP object
  • snmp3_walk() - Fetch all the SNMP objects from an agent


Return all objects including their respective object ID within the specified one

  • « snmp3_getnext
  • snmp3_set »
  • PHP Manual
  • SNMP Functions
  • Return all objects including their respective object ID within the specified one

snmp3_real_walk

(PHP 4, PHP 5, PHP 7)

snmp3_real_walk — Return all objects including their respective object ID within the specified one

Description

snmp3_real_walk ( string $host , string $sec_name , string $sec_level , string $auth_protocol , string $auth_passphrase , string $priv_protocol , string $priv_passphrase , string $object_id [, int $timeout = 1000000 [, int $retries = 5 ]] ) : array

The snmp3_real_walk() function is used to traverse over a number of SNMP objects starting from object_id and return not only their values but also their object ids.

Parameters

host

The hostname of the SNMP agent (server).

sec_name

the security name, usually some kind of username

sec_level

the security level (noAuthNoPriv|authNoPriv|authPriv)

auth_protocol

the authentication protocol (MD5 or SHA)

auth_passphrase

the authentication pass phrase

priv_protocol

the privacy protocol (DES or AES)

priv_passphrase

the privacy pass phrase

object_id

The SNMP object id.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Return Values

Returns an associative array of the SNMP object ids and their values on success or FALSE on error. In case of an error, an E_WARNING message is shown.

Examples

Example #1 Using snmp3_real_walk()

<?php
 var_export(snmp3_real_walk('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'IF-MIB::ifName'));
?>

The above will output something like:

array (
  'IF-MIB::ifName.1' => 'STRING: lo',
  'IF-MIB::ifName.2' => 'STRING: eth0',
  'IF-MIB::ifName.3' => 'STRING: eth2',
  'IF-MIB::ifName.4' => 'STRING: sit0',
  'IF-MIB::ifName.5' => 'STRING: sixxs',
)

See Also

  • snmpwalk() - Fetch all the SNMP objects from an agent


Set the value of an SNMP object

  • « snmp3_real_walk
  • snmp3_walk »
  • PHP Manual
  • SNMP Functions
  • Set the value of an SNMP object

snmp3_set

(PHP 4, PHP 5, PHP 7)

snmp3_set — Set the value of an SNMP object

Description

snmp3_set ( string $host , string $sec_name , string $sec_level , string $auth_protocol , string $auth_passphrase , string $priv_protocol , string $priv_passphrase , string $object_id , string $type , string $value [, int $timeout = 1000000 [, int $retries = 5 ]] ) : bool

snmp3_set() is used to set the value of an SNMP object specified by the object_id.

Even if the security level does not use an auth or priv protocol/password valid values have to be specified.

Parameters

host

The hostname of the SNMP agent (server).

sec_name

the security name, usually some kind of username

sec_level

the security level (noAuthNoPriv|authNoPriv|authPriv)

auth_protocol

the authentication protocol (MD5 or SHA)

auth_passphrase

the authentication pass phrase

priv_protocol

the privacy protocol (DES or AES)

priv_passphrase

the privacy pass phrase

object_id

The SNMP object id.

type

The MIB defines the type of each object id. It has to be specified as a single character from the below list.

types
= The type is taken from the MIB
i | INTEGER
u | INTEGER
s | STRING
x | HEX STRING
d | DECIMAL STRING
n | NULLOBJ
o | OBJID
t | TIMETICKS
a | IPADDRESS
b | BITS

If OPAQUE_SPECIAL_TYPES was defined while compiling the SNMP library, the following are also valid:

types
U | unsigned int64
I | signed int64
F | float
D | double

Most of these will use the obvious corresponding ASN.1 type. 's', 'x', 'd' and 'b' are all different ways of specifying an OCTET STRING value, and the 'u' unsigned type is also used for handling Gauge32 values.

If the MIB-Files are loaded by into the MIB Tree with "snmp_read_mib" or by specifying it in the libsnmp config, '=' may be used as the type parameter for all object ids as the type can then be automatically read from the MIB.

Note that there are two ways to set a variable of the type BITS like e.g. "SYNTAX BITS {telnet(0), ftp(1), http(2), icmp(3), snmp(4), ssh(5), https(6)}":

  • Using type "b" and a list of bit numbers. This method is not recommended since GET query for the same OID would return e.g. 0xF8.
  • Using type "x" and a hex number but without(!) the usual "0x" prefix.

See examples section for more details.

value

The new value

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Return Values

Returns TRUE on success or FALSE on failure.

If the SNMP host rejects the data type, an E_WARNING message like "Warning: Error in packet. Reason: (badValue) The value given has the wrong type or length." is shown. If an unknown or invalid OID is specified the warning probably reads "Could not add variable".

Examples

Example #1 Using snmp3_set()

<?php
  snmp3_set('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'IF-MIB::ifAlias.3', 's', "foo");
?>

Example #2 Using snmp3_set() for setting BITS SNMP object id

<?php
  snmp3_set('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'FOO-MIB::bar.42', 'b', '0 1 2 3 4');
// or
  snmp3_set('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'FOO-MIB::bar.42', 'x', 'F0');
?>


Fetch all the SNMP objects from an agent

  • « snmp3_set
  • snmpget »
  • PHP Manual
  • SNMP Functions
  • Fetch all the SNMP objects from an agent

snmp3_walk

(PHP 4, PHP 5, PHP 7)

snmp3_walk — Fetch all the SNMP objects from an agent

Description

snmp3_walk ( string $host , string $sec_name , string $sec_level , string $auth_protocol , string $auth_passphrase , string $priv_protocol , string $priv_passphrase , string $object_id [, int $timeout = 1000000 [, int $retries = 5 ]] ) : array

snmp3_walk() function is used to read all the values from an SNMP agent specified by the hostname.

Even if the security level does not use an auth or priv protocol/password valid values have to be specified.

Parameters

host

The hostname of the SNMP agent (server).

sec_name

the security name, usually some kind of username

sec_level

the security level (noAuthNoPriv|authNoPriv|authPriv)

auth_protocol

the authentication protocol (MD5 or SHA)

auth_passphrase

the authentication pass phrase

priv_protocol

the privacy protocol (DES or AES)

priv_passphrase

the privacy pass phrase

object_id

If NULL, object_id is taken as the root of the SNMP objects tree and all objects under that tree are returned as an array.

If object_id is specified, all the SNMP objects below that object_id are returned.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Return Values

Returns an array of SNMP object values starting from the object_id as root or FALSE on error.

Examples

Example #1 snmp3_walk() Example

<?php
$ret = snmp3_walk('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'IF-MIB::ifName');
var_export($ret);
?>

Above function call would return all the SNMP objects from the SNMP agent running on localhost:

array (
  0 => 'STRING: lo',
  1 => 'STRING: eth0',
  2 => 'STRING: eth2',
  3 => 'STRING: sit0',
  4 => 'STRING: sixxs',
)

See Also

  • snmp3_real_walk() - Return all objects including their respective object ID within the specified one


Fetch an SNMP object

  • « snmp3_walk
  • snmpgetnext »
  • PHP Manual
  • SNMP Functions
  • Fetch an SNMP object

snmpget

(PHP 4, PHP 5, PHP 7)

snmpget — Fetch an SNMP object

Description

snmpget ( string $hostname , string $community , string $object_id [, int $timeout = 1000000 [, int $retries = 5 ]] ) : string

The snmpget() function is used to read the value of an SNMP object specified by the object_id.

Parameters

hostname

The SNMP agent.

community

The read community.

object_id

The SNMP object.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Return Values

Returns SNMP object value on success or FALSE on error.

Examples

Example #1 Using snmpget()

<?php
$syscontact = snmpget("127.0.0.1", "public", "system.SysContact.0");
?>

See Also

  • snmpset() - Set the value of an SNMP object


Fetch the SNMP object which follows the given object id

  • « snmpget
  • snmprealwalk »
  • PHP Manual
  • SNMP Functions
  • Fetch the SNMP object which follows the given object id

snmpgetnext

(PHP 5, PHP 7)

snmpgetnext — Fetch the SNMP object which follows the given object id

Description

snmpgetnext ( string $host , string $community , string $object_id [, int $timeout = 1000000 [, int $retries = 5 ]] ) : string

The snmpgetnext() function is used to read the value of the SNMP object that follows the specified object_id.

Parameters

host

The hostname of the SNMP agent (server).

community

The read community.

object_id

The SNMP object id which precedes the wanted one.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Return Values

Returns SNMP object value on success or FALSE on error. In case of an error, an E_WARNING message is shown.

Examples

Example #1 Using snmpgetnext()

<?php
$nameOfSecondInterface = snmpgetnetxt('localhost', 'public', 'IF-MIB::ifName.1';
?>

See Also

  • snmpget() - Fetch an SNMP object
  • snmpwalk() - Fetch all the SNMP objects from an agent


Return all objects including their respective object ID within the specified one

  • « snmpgetnext
  • snmpset »
  • PHP Manual
  • SNMP Functions
  • Return all objects including their respective object ID within the specified one

snmprealwalk

(PHP 4, PHP 5, PHP 7)

snmprealwalk — Return all objects including their respective object ID within the specified one

Description

snmprealwalk ( string $host , string $community , string $object_id [, int $timeout = 1000000 [, int $retries = 5 ]] ) : array

The snmprealwalk() function is used to traverse over a number of SNMP objects starting from object_id and return not only their values but also their object ids.

Parameters

host

The hostname of the SNMP agent (server).

community

The read community.

object_id

The SNMP object id which precedes the wanted one.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Return Values

Returns an associative array of the SNMP object ids and their values on success or FALSE on error. In case of an error, an E_WARNING message is shown.

Examples

Example #1 Using snmprealwalk()

<?php
 print_r(snmprealwalk("localhost", "public", "IF-MIB::ifName"));
?>

The above will output something like:

    Array
      (
      [IF-MIB::ifName.1] => STRING: lo
      [IF-MIB::ifName.2] => STRING: eth0
      [IF-MIB::ifName.3] => STRING: eth2
      [IF-MIB::ifName.4] => STRING: sit0
      [IF-MIB::ifName.5] => STRING: sixxs
    )

See Also

  • snmpwalk() - Fetch all the SNMP objects from an agent


Set the value of an SNMP object

  • « snmprealwalk
  • snmpwalk »
  • PHP Manual
  • SNMP Functions
  • Set the value of an SNMP object

snmpset

(PHP 4, PHP 5, PHP 7)

snmpset — Set the value of an SNMP object

Description

snmpset ( string $host , string $community , string $object_id , string $type , mixed $value [, int $timeout = 1000000 [, int $retries = 5 ]] ) : bool

snmpset() is used to set the value of an SNMP object specified by the object_id.

Parameters

host

The hostname of the SNMP agent (server).

community

The write community.

object_id

The SNMP object id.

type

The MIB defines the type of each object id. It has to be specified as a single character from the below list.

types
= The type is taken from the MIB
i | INTEGER
u | INTEGER
s | STRING
x | HEX STRING
d | DECIMAL STRING
n | NULLOBJ
o | OBJID
t | TIMETICKS
a | IPADDRESS
b | BITS

If OPAQUE_SPECIAL_TYPES was defined while compiling the SNMP library, the following are also valid:

types
U | unsigned int64
I | signed int64
F | float
D | double

Most of these will use the obvious corresponding ASN.1 type. 's', 'x', 'd' and 'b' are all different ways of specifying an OCTET STRING value, and the 'u' unsigned type is also used for handling Gauge32 values.

If the MIB-Files are loaded by into the MIB Tree with "snmp_read_mib" or by specifying it in the libsnmp config, '=' may be used as the type parameter for all object ids as the type can then be automatically read from the MIB.

Note that there are two ways to set a variable of the type BITS like e.g. "SYNTAX BITS {telnet(0), ftp(1), http(2), icmp(3), snmp(4), ssh(5), https(6)}":

  • Using type "b" and a list of bit numbers. This method is not recommended since GET query for the same OID would return e.g. 0xF8.
  • Using type "x" and a hex number but without(!) the usual "0x" prefix.

See examples section for more details.

value

The new value.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Return Values

Returns TRUE on success or FALSE on failure.

If the SNMP host rejects the data type, an E_WARNING message like "Warning: Error in packet. Reason: (badValue) The value given has the wrong type or length." is shown. If an unknown or invalid OID is specified the warning probably reads "Could not add variable".

Examples

Example #1 Using snmpset()

<?php
  snmpset("localhost", "public", "IF-MIB::ifAlias.3", "s", "foo");
?>

Example #2 Using snmpset() for setting BITS SNMP object id

<?php
  snmpset("localhost", "public", 'FOO-MIB::bar.42', 'b', '0 1 2 3 4');
// or
  snmpset("localhost", "public", 'FOO-MIB::bar.42', 'x', 'F0');
?>

See Also

  • snmpget() - Fetch an SNMP object


Fetch all the SNMP objects from an agent

  • « snmpset
  • snmpwalkoid »
  • PHP Manual
  • SNMP Functions
  • Fetch all the SNMP objects from an agent

snmpwalk

(PHP 4, PHP 5, PHP 7)

snmpwalk — Fetch all the SNMP objects from an agent

Description

snmpwalk ( string $hostname , string $community , string $object_id [, int $timeout = 1000000 [, int $retries = 5 ]] ) : array

snmpwalk() function is used to read all the values from an SNMP agent specified by the hostname.

Parameters

hostname

The SNMP agent (server).

community

The read community.

object_id

If NULL, object_id is taken as the root of the SNMP objects tree and all objects under that tree are returned as an array.

If object_id is specified, all the SNMP objects below that object_id are returned.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Return Values

Returns an array of SNMP object values starting from the object_id as root or FALSE on error.

Examples

Example #1 snmpwalk() Example

<?php
$a = snmpwalk("127.0.0.1", "public", "");

foreach ($a as $val) {
    echo "$val\n";
}

?>

Above function call would return all the SNMP objects from the SNMP agent running on localhost. One can step through the values with a loop

See Also

  • snmprealwalk() - Return all objects including their respective object ID within the specified one


Query for a tree of information about a network entity

  • « snmpwalk
  • SNMP »
  • PHP Manual
  • SNMP Functions
  • Query for a tree of information about a network entity

snmpwalkoid

(PHP 4, PHP 5, PHP 7)

snmpwalkoid — Query for a tree of information about a network entity

Description

snmpwalkoid ( string $hostname , string $community , string $object_id [, int $timeout = 1000000 [, int $retries = 5 ]] ) : array

snmpwalkoid() function is used to read all object ids and their respective values from an SNMP agent specified by hostname.

The existence of snmpwalkoid() and snmpwalk() has historical reasons. Both functions are provided for backward compatibility. Use snmprealwalk() instead.

Parameters

hostname

The SNMP agent.

community

The read community.

object_id

If NULL, object_id is taken as the root of the SNMP objects tree and all objects under that tree are returned as an array.

If object_id is specified, all the SNMP objects below that object_id are returned.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

Return Values

Returns an associative array with object ids and their respective object value starting from the object_id as root or FALSE on error.

Examples

Example #1 snmpwalkoid() Example

<?php
$a = snmpwalkoid("127.0.0.1", "public", "");
for (reset($a); $i = key($a); next($a)) {
    echo "$i: $a[$i]<br />\n";
}
?>

Above function call would return all the SNMP objects from the SNMP agent running on localhost. One can step through the values with a loop

See Also

  • snmpwalk() - Fetch all the SNMP objects from an agent


The SNMP class

(PHP 5 >= 5.4.0, PHP 7)

Introduction

Represents SNMP session.

Class synopsis

SNMP {
/* Properties */
public int $max_oids ;
public int $valueretrieval ;
public bool $quick_print ;
public bool $enum_print ;
public int $oid_output_format ;
public bool $oid_increasing_check ;
public int $exceptions_enabled ;
public array $info ;
/* Methods */
public __construct ( int $version , string $hostname , string $community [, int $timeout = 1000000 [, int $retries = 5 ]] )
public close ( void ) : bool
public get ( mixed $object_id [, bool $preserve_keys = FALSE ] ) : mixed
public getErrno ( void ) : int
public getError ( void ) : string
public getnext ( mixed $object_id ) : mixed
public set ( mixed $object_id , mixed $type , mixed $value ) : bool
public setSecurity ( string $sec_level [, string $auth_protocol = [, string $auth_passphrase = [, string $priv_protocol = [, string $priv_passphrase = [, string $contextName = [, string $contextEngineID = ]]]]]] ) : bool
public walk ( string $object_id [, bool $suffix_as_key = FALSE [, int $max_repetitions [, int $non_repeaters ]]] ) : array
/* Constants */
const integer ERRNO_NOERROR = 0 ;
const integer ERRNO_GENERIC = 2 ;
const integer ERRNO_TIMEOUT = 4 ;
const integer ERRNO_ERROR_IN_REPLY = 8 ;
const integer ERRNO_OID_NOT_INCREASING = 16 ;
const integer ERRNO_OID_PARSING_ERROR = 32 ;
const integer ERRNO_MULTIPLE_SET_QUERIES = 64 ;
const integer ERRNO_ANY = 126 ;
const integer VERSION_1 = 0 ;
const integer VERSION_2C = 1 ;
const integer VERSION_2c = 1 ;
const integer VERSION_3 = 3 ;
}

Properties

max_oids

Maximum OID per GET/SET/GETBULK request

valueretrieval

Controls the method how the SNMP values will be returned

SNMP_VALUE_LIBRARY | The return values will be as returned by the Net-SNMP library.
SNMP_VALUE_PLAIN | The return values will be the plain value without the SNMP type hint.
SNMP_VALUE_OBJECT | The return values will be objects with the properties "value" and "type", where the latter is one of the SNMP_OCTET_STR, SNMP_COUNTER etc. constants. The way "value" is returned is based on which one of SNMP_VALUE_LIBRARY, SNMP_VALUE_PLAIN is set
quick_print

Value of quick_print within the NET-SNMP library

Sets the value of quick_print within the NET-SNMP library. When this is set (1), the SNMP library will return 'quick printed' values. This means that just the value will be printed. When quick_print is not enabled (default) the UCD SNMP library prints extra information including the type of the value (i.e. IpAddress or OID). Additionally, if quick_print is not enabled, the library prints additional hex values for all strings of three characters or less.

enum_print

Controls the way enum values are printed

Parameter toggles if walk/get etc. should automatically lookup enum values in the MIB and return them together with their human readable string.

oid_output_format

Controls OID output format

OID .1.3.6.1.2.1.1.3.0 representation for various oid_output_format values
SNMP_OID_OUTPUT_FULL | .iso.org.dod.internet.mgmt.mib-2.system.sysUpTime.sysUpTimeInstance
SNMP_OID_OUTPUT_NUMERIC | .1.3.6.1.2.1.1.3.0
SNMP_OID_OUTPUT_MODULE | DISMAN-EVENT-MIB::sysUpTimeInstance
SNMP_OID_OUTPUT_SUFFIX | sysUpTimeInstance
SNMP_OID_OUTPUT_UCD | system.sysUpTime.sysUpTimeInstance
SNMP_OID_OUTPUT_NONE | Undefined
oid_increasing_check

Controls disabling check for increasing OID while walking OID tree

Some SNMP agents are known for returning OIDs out of order but can complete the walk anyway. Other agents return OIDs that are out of order and can cause SNMP::walk() to loop indefinitely until memory limit will be reached. PHP SNMP library by default performs OID increasing check and stops walking on OID tree when it detects possible loop with issuing warning about non-increasing OID faced. Set oid_increasing_check to FALSE to disable this check.

exceptions_enabled

Controls which failures will raise SNMPException instead of warning. Use bitwise OR'ed SNMP::ERRNO_* constants. By default all SNMP exceptions are disabled.

info

Read-only property with remote agent configuration: hostname, port, default timeout, default retries count

Predefined Constants

SNMP Error Types

SNMP::ERRNO_NOERROR

No SNMP-specific error occurred.

SNMP::ERRNO_GENERIC

A generic SNMP error occurred.

SNMP::ERRNO_TIMEOUT

Request to SNMP agent timed out.

SNMP::ERRNO_ERROR_IN_REPLY

SNMP agent returned an error in reply.

SNMP::ERRNO_OID_NOT_INCREASING

SNMP agent faced OID cycling reporning non-increasing OID while executing (BULK)WALK command. This indicates bogus remote SNMP agent.

SNMP::ERRNO_OID_PARSING_ERROR

Library failed while parsing OID (and/or type for SET command). No queries has been made.

SNMP::ERRNO_MULTIPLE_SET_QUERIES

Library will use multiple queries for SET operation requested. That means that operation will be performed in a non-transaction manner and second or subsequent chunks may fail if a type or value failure will be faced.

SNMP::ERRNO_ANY

All SNMP::ERRNO_* codes bitwise OR'ed.

SNMP Protocol Versions

SNMP::VERSION_1

SNMP::VERSION_2C, SNMP::VERSION_2c

SNMP::VERSION_3

Table of Contents

  • SNMP::close — Close SNMP session
  • SNMP::__construct — Creates SNMP instance representing session to remote SNMP agent
  • SNMP::get — Fetch an SNMP object
  • SNMP::getErrno — Get last error code
  • SNMP::getError — Get last error message
  • SNMP::getnext — Fetch an SNMP object which follows the given object id
  • SNMP::set — Set the value of an SNMP object
  • SNMP::setSecurity — Configures security-related SNMPv3 session parameters
  • SNMP::walk — Fetch SNMP object subtree


Close SNMP session

  • « SNMP
  • SNMP::__construct »
  • PHP Manual
  • SNMP
  • Close SNMP session

SNMP::close

(PHP 5 >= 5.4.0, PHP 7)

SNMP::close — Close SNMP session

Description

public SNMP::close ( void ) : bool

Frees previously allocated SNMP session object.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 SNMP::close() example

<?php
  $session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
  # ...
  # get, walk, etc goes here
  # ...
  $session->close();
?>

See Also

  • SNMP::__construct() - Creates SNMP instance representing session to remote SNMP agent


Creates SNMP instance representing session to remote SNMP agent

  • « SNMP::close
  • SNMP::get »
  • PHP Manual
  • SNMP
  • Creates SNMP instance representing session to remote SNMP agent

SNMP::__construct

(PHP 5 >= 5.4.0, PHP 7)

SNMP::__construct — Creates SNMP instance representing session to remote SNMP agent

Description

public SNMP::__construct ( int $version , string $hostname , string $community [, int $timeout = 1000000 [, int $retries = 5 ]] )

The function description goes here.

Parameters

version

SNMP protocol version:
SNMP::VERSION_1,
SNMP::VERSION_2C,
SNMP::VERSION_3.

hostname

The SNMP agent. hostname may be suffixed with optional SNMP agent port after colon. IPv6 addresses must be enclosed in square brackets if used with port. If FQDN is used for hostname it will be resolved by php-snmp library, not by Net-SNMP engine. Usage of IPv6 addresses when specifying FQDN may be forced by enclosing FQDN into square brackets. Here it is some examples:

IPv4 with default port | 127.0.0.1
IPv6 with default port | ::1 or [::1]
IPv4 with specific port | 127.0.0.1:1161
IPv6 with specific port | [::1]:1161
FQDN with default port | host.domain
FQDN with specific port | host.domain:1161
FQDN with default port, force usage of IPv6 address | [host.domain]
FQDN with specific port, force usage of IPv6 address | [host.domain]:1161

community

The purpuse of community is SNMP version specific:

SNMP::VERSION_1 | SNMP community
SNMP::VERSION_2C | SNMP community
SNMP::VERSION_3 | SNMPv3 securityName
timeout

The number of microseconds until the first timeout.

retries

The number of retries in case timeout occurs.

Return Values

Returns SNMP object representing remote SNMP agent.

Errors/Exceptions

SNMP::__construct() throws an exception when parameters count or types are wrong or unknown SNMP protocol version specified.

Examples

Example #1 Fetching sysLocation

<?php
  $session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
  $sysdescr = $session->get("sysDescr.0");
  echo "$sysdescr\n";
?>

The above example will output something similar to:

STRING: Test server

See Also

  • SNMP::close() - Close SNMP session


Fetch an SNMP object

  • « SNMP::__construct
  • SNMP::getErrno »
  • PHP Manual
  • SNMP
  • Fetch an SNMP object

SNMP::get

(PHP 5 >= 5.4.0, PHP 7)

SNMP::get — Fetch an SNMP object

Description

public SNMP::get ( mixed $object_id [, bool $preserve_keys = FALSE ] ) : mixed

Fetch an SNMP object specified in object_id using GET query.

Parameters

If object_id is a string, then SNMP::get() will return SNMP object as string. If object_id is a array, all requested SNMP objects will be returned as associative array of the SNMP object ids and their values.

object_id

The SNMP object (OID) or objects

preserve_keys

When object_id is a array and preserve_keys set to TRUE keys in results will be taken exactly as in object_id, otherwise SNMP::oid_output_format property is used to determinate the form of keys.

Return Values

Returns SNMP objects requested as string or array depending on object_id type or FALSE on error.

Errors/Exceptions

This method does not throw any exceptions by default. To enable throwing an SNMPException exception when some of library errors occur the SNMP class parameter exceptions_enabled should be set to a corresponding value. See SNMP::$exceptions_enabled explanation for more details.

Examples

Example #1 Single SNMP object

Single SNMP object may be requested in two ways: as string resulting string return value or as single-element array with associative array as output.

<?php
  $session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
  $sysdescr = $session->get("sysDescr.0");
  echo "$sysdescr\n";
  $sysdescr = $session->get(array("sysDescr.0"));
  print_r($sysdescr);
?>

The above example will output something similar to:

STRING: Test server
Array
(
    [SNMPv2-MIB::sysDescr.0] => STRING: Test server
)

Example #2 Multiple SNMP objects

$session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
  $results = $session->get(array("sysDescr.0", "sysName.0"));
  print_r($results);
  $session->close();

The above example will output something similar to:

Array
(
    [SNMPv2-MIB::sysDescr.0] => STRING: Test server
    [SNMPv2-MIB::sysName.0] => STRING: myhost.nodomain
)

See Also

  • SNMP::getErrno() - Get last error code
  • SNMP::getError() - Get last error message


Get last error code

  • « SNMP::get
  • SNMP::getError »
  • PHP Manual
  • SNMP
  • Get last error code

SNMP::getErrno

(PHP 5 >= 5.4.0, PHP 7)

SNMP::getErrno — Get last error code

Description

public SNMP::getErrno ( void ) : int

Returns error code from last SNMP request.

Return Values

Returns one of SNMP error code values described in constants chapter.

Examples

Example #1 SNMP::getErrno() example

<?php
$session = new SNMP(SNMP::VERSION_2c, '127.0.0.1', 'boguscommunity');
var_dump(@$session->get('.1.3.6.1.2.1.1.1.0'));
var_dump($session->getErrno() == SNMP::ERRNO_TIMEOUT);
?>

The above example will output:

bool(false)
bool(true)

See Also

  • SNMP::getError() - Get last error message


Get last error message

  • « SNMP::getErrno
  • SNMP::getnext »
  • PHP Manual
  • SNMP
  • Get last error message

SNMP::getError

(PHP 5 >= 5.4.0, PHP 7)

SNMP::getError — Get last error message

Description

public SNMP::getError ( void ) : string

Returns string with error from last SNMP request.

Return Values

String describing error from last SNMP request.

Examples

Example #1 SNMP::getError() example

<?php
$session = new SNMP(SNMP::VERSION_2c, '127.0.0.1', 'boguscommunity');
var_dump(@$session->get('.1.3.6.1.2.1.1.1.0'));
var_dump($session->getError());
?>

The above example will output:

bool(false)
string(26) "No response from 127.0.0.1"

See Also

  • SNMP::getErrno() - Get last error code


Fetch an SNMP object which follows the given object id

  • « SNMP::getError
  • SNMP::set »
  • PHP Manual
  • SNMP
  • Fetch an SNMP object which follows the given object id

SNMP::getnext

(PHP 5 >= 5.4.0, PHP 7)

SNMP::getnext — Fetch an SNMP object which follows the given object id

Description

public SNMP::getnext ( mixed $object_id ) : mixed

Fetch an SNMP object that follows specified object_id.

Parameters

If object_id is a string, then SNMP::getnext() will return SNMP object as string. If object_id is a array, all requested SNMP objects will be returned as associative array of the SNMP object ids and their values.

object_id

The SNMP object (OID) or objects

Return Values

Returns SNMP objects requested as string or array depending on object_id type or FALSE on error.

Errors/Exceptions

This method does not throw any exceptions by default. To enable throwing an SNMPException exception when some of library errors occur the SNMP class parameter exceptions_enabled should be set to a corresponding value. See SNMP::$exceptions_enabled explanation for more details.

Examples

Example #1 Single SNMP object

Single SNMP object may be requested in two ways: as string resulting string return value or as single-element array with associative array as output.

<?php
  $session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
  $nsysdescr = $session->getnext("sysDescr.0");
  echo "$nsysdescr\n";
  $nsysdescr = $session->getnext(array("sysDescr.0"));
  print_r($nsysdescr);
?>

The above example will output something similar to:

OID: NET-SNMP-MIB::netSnmpAgentOIDs.8
Array
(
    [SNMPv2-MIB::sysObjectID.0] => OID: NET-SNMP-MIB::netSnmpAgentOIDs.8
)

Example #2 Miltiple SNMP objects

<?php
  $session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
  $results = $session->getnext(array("sysDescr.0", "sysName.0"));
  print_r($results);
  $session->close();
?>

The above example will output something similar to:

Array
(
    [SNMPv2-MIB::sysObjectID.0] => OID: NET-SNMP-MIB::netSnmpAgentOIDs.8
    [SNMPv2-MIB::sysLocation.0] => STRING: Nowhere
)

See Also

  • SNMP::getErrno() - Get last error code
  • SNMP::getError() - Get last error message


Set the value of an SNMP object

  • « SNMP::getnext
  • SNMP::setSecurity »
  • PHP Manual
  • SNMP
  • Set the value of an SNMP object

SNMP::set

(PHP 5 >= 5.4.0, PHP 7)

SNMP::set — Set the value of an SNMP object

Description

public SNMP::set ( mixed $object_id , mixed $type , mixed $value ) : bool

Requests remote SNMP agent setting the value of one or more SNMP objects specified by the object_id.

Parameters

If object_id is string, both type and value must be string too. If object_id is array value must be equal-sized array containing corresponding values, type may be either string (it's value will be used for all object_id-value pairs) or equal-sized array with per-OID value. When any other parameters' combinations are used, a number of E_WARNING messages may be shown with detailed description.

object_id

The SNMP object id

When count of OIDs in object_id array is greater than max_oids object property set method will have to use multiple queries to perform requested value updates. In this case type and value checks are made per-chunk so second or subsequent requests may fail due to wrong type or value for OID requested. To mark this a warning is raised when count of OIDs in object_id array is greater than max_oids.

type

The MIB defines the type of each object id. It has to be specified as a single character from the below list.

types
= The type is taken from the MIB
i | INTEGER
u | INTEGER
s | STRING
x | HEX STRING
d | DECIMAL STRING
n | NULLOBJ
o | OBJID
t | TIMETICKS
a | IPADDRESS
b | BITS

If OPAQUE_SPECIAL_TYPES was defined while compiling the SNMP library, the following are also valid:

types
U | unsigned int64
I | signed int64
F | float
D | double

Most of these will use the obvious corresponding ASN.1 type. 's', 'x', 'd' and 'b' are all different ways of specifying an OCTET STRING value, and the 'u' unsigned type is also used for handling Gauge32 values.

If the MIB-Files are loaded by into the MIB Tree with "snmp_read_mib" or by specifying it in the libsnmp config, '=' may be used as the type parameter for all object ids as the type can then be automatically read from the MIB.

Note that there are two ways to set a variable of the type BITS like e.g. "SYNTAX BITS {telnet(0), ftp(1), http(2), icmp(3), snmp(4), ssh(5), https(6)}":

  • Using type "b" and a list of bit numbers. This method is not recommended since GET query for the same OID would return e.g. 0xF8.
  • Using type "x" and a hex number but without(!) the usual "0x" prefix.

See examples section for more details.

value

The new value.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

This method does not throw any exceptions by default. To enable throwing an SNMPException exception when some of library errors occur the SNMP class parameter exceptions_enabled should be set to a corresponding value. See SNMP::$exceptions_enabled explanation for more details.

Examples

Example #1 Set single SNMP object id

<?php
  $session = new SNMP(SNMP::VERSION_2C, "127.0.0.1", "private");
  $session->set('SNMPv2-MIB::sysContact.0', 's', "Nobody");
?>

Example #2 Set multiple values using single SNMP::set() call

<?php
  $session = new SNMP(SNMP::VERSION_2C, "127.0.0.1", "private");
  $session->set(array('SNMPv2-MIB::sysContact.0', 'SNMPv2-MIB::sysLocation.0'), array('s', 's'), array("Nobody", "Nowhere"));
// or
  $session->set(array('SNMPv2-MIB::sysContact.0', 'SNMPv2-MIB::sysLocation.0'), 's', array("Nobody", "Nowhere"));
?>

Example #3 Using SNMP::set() for setting BITS SNMP object id

<?php
  $session = new SNMP(SNMP::VERSION_2C, "127.0.0.1", "private");
  $session->set('FOO-MIB::bar.42', 'b', '0 1 2 3 4');
// or
  $session->set('FOO-MIB::bar.42', 'x', 'F0');
?>

See Also

  • SNMP::get() - Fetch an SNMP object


Configures security-related SNMPv3 session parameters

  • « SNMP::set
  • SNMP::walk »
  • PHP Manual
  • SNMP
  • Configures security-related SNMPv3 session parameters

SNMP::setSecurity

(PHP 5 >= 5.4.0, PHP 7)

SNMP::setSecurity — Configures security-related SNMPv3 session parameters

Description

public SNMP::setSecurity ( string $sec_level [, string $auth_protocol = [, string $auth_passphrase = [, string $priv_protocol = [, string $priv_passphrase = [, string $contextName = [, string $contextEngineID = ]]]]]] ) : bool

setSecurity configures security-related session parameters used in SNMP protocol version 3

Parameters

sec_level

the security level (noAuthNoPriv|authNoPriv|authPriv)

auth_protocol

the authentication protocol (MD5 or SHA)

auth_passphrase

the authentication pass phrase

priv_protocol

the privacy protocol (DES or AES)

priv_passphrase

the privacy pass phrase

contextName

the context name

contextEngineID

the context EngineID

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 SNMP::setSecurity() example

<?php
  $session = new SNMP(SNMP::VERSION_3, $hostname, $rwuser, $timeout, $retries);
  $session->setSecurity('authPriv', 'MD5', $auth_pass, 'AES', $priv_pass, '', 'aeeeff');
?>

See Also

  • SNMP::__construct() - Creates SNMP instance representing session to remote SNMP agent


Fetch SNMP object subtree

  • « SNMP::setSecurity
  • SNMPException »
  • PHP Manual
  • SNMP
  • Fetch SNMP object subtree

SNMP::walk

(PHP 5 >= 5.4.0, PHP 7)

SNMP::walk — Fetch SNMP object subtree

Description

public SNMP::walk ( string $object_id [, bool $suffix_as_key = FALSE [, int $max_repetitions [, int $non_repeaters ]]] ) : array

SNMP::walk() is used to read SNMP subtree rooted at specified object_id.

Parameters

object_id

Root of subtree to be fetched

suffix_as_key

By default full OID notation is used for keys in output array. If set to TRUE subtree prefix will be removed from keys leaving only suffix of object_id.

non_repeaters

This specifies the number of supplied variables that should not be iterated over. The default is to use this value from SNMP object.

max_repetitions

This specifies the maximum number of iterations over the repeating variables. The default is to use this value from SNMP object.

Return Values

Returns an associative array of the SNMP object ids and their values on success or FALSE on error. When a SNMP error occures SNMP::getErrno() and SNMP::getError() can be used for retrieving error number (specific to SNMP extension, see class constants) and error message respectively.

Errors/Exceptions

This method does not throw any exceptions by default. To enable throwing an SNMPException exception when some of library errors occur the SNMP class parameter exceptions_enabled should be set to a corresponding value. See SNMP::$exceptions_enabled explanation for more details.

Examples

Example #1 SNMP::walk() example

<?php
  $session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
  $fulltree = $session->walk(".");
  print_r($fulltree);
  $session->close();
?>

The above example will output something similar to:

Array
(
    [SNMPv2-MIB::sysDescr.0] => STRING: Test server
    [SNMPv2-MIB::sysObjectID.0] => OID: NET-SNMP-MIB::netSnmpAgentOIDs.8
    [DISMAN-EVENT-MIB::sysUpTimeInstance] => Timeticks: (1150681750) 133 days, 4:20:17.50
    [SNMPv2-MIB::sysContact.0] => STRING: Nobody
    [SNMPv2-MIB::sysName.0] => STRING: server.localdomain
    ...
)

Example #2 suffix_as_key example

suffix_as_key may be used when merging multiple SNMP subtrees into one. This example maps interface names to their type.

<?php
  $session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
  $session->valueretrieval = SNMP_VALUE_PLAIN;
  $ifDescr = $session->walk(".1.3.6.1.2.1.2.2.1.2", TRUE);
  $session->valueretrieval = SNMP_VALUE_LIBRARY;
  $ifType = $session->walk(".1.3.6.1.2.1.2.2.1.3", TRUE);
  print_r($ifDescr);
  print_r($ifType);
  $result = array();
  foreach($ifDescr as $i => $n) {
    $result[$n] = $ifType[$i];
  }
  print_r($result);
?>

The above example will output something similar to:

Array
(
    [1] => igb0
    [2] => igb1
    [3] => ipfw0
    [4] => lo0
    [5] => lagg0
)
Array
(
    [1] => INTEGER: ieee8023adLag(161)
    [2] => INTEGER: ieee8023adLag(161)
    [3] => INTEGER: ethernetCsmacd(6)
    [4] => INTEGER: softwareLoopback(24)
    [5] => INTEGER: ethernetCsmacd(6)
)
Array
(
    [igb0] => INTEGER: ieee8023adLag(161)
    [igb1] => INTEGER: ieee8023adLag(161)
    [ipfw0] => INTEGER: ethernetCsmacd(6)
    [lo0] => INTEGER: softwareLoopback(24)
    [lagg0] => INTEGER: ethernetCsmacd(6)
)

See Also

  • SNMP::getErrno() - Get last error code
  • SNMP::getError() - Get last error message


The SNMPException class

(PHP 5 >= 5.4.0, PHP 7)

Introduction

Represents an error raised by SNMP. You should not throw a SNMPException from your own code. See Exceptions for more information about Exceptions in PHP.

Class synopsis

SNMPException extends RuntimeException {
/* Properties */
protected string $code ;
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}

Properties

code

SNMPlibrary error code. Use Exception::getCode() to access it.


Sockets

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Socket Errors
  • Socket Functions
    • socket_accept — Accepts a connection on a socket
    • socket_addrinfo_bind — Create and bind to a socket from a given addrinfo
    • socket_addrinfo_connect — Create and connect to a socket from a given addrinfo
    • socket_addrinfo_explain — Get information about addrinfo
    • socket_addrinfo_lookup — Get array with contents of getaddrinfo about the given hostname
    • socket_bind — Binds a name to a socket
    • socket_clear_error — Clears the error on the socket or the last error code
    • socket_close — Closes a socket resource
    • socket_cmsg_space — Calculate message buffer size
    • socket_connect — Initiates a connection on a socket
    • socket_create_listen — Opens a socket on port to accept connections
    • socket_create_pair — Creates a pair of indistinguishable sockets and stores them in an array
    • socket_create — Create a socket (endpoint for communication)
    • socket_export_stream — Export a socket extension resource into a stream that encapsulates a socket
    • socket_get_option — Gets socket options for the socket
    • socket_getopt — Alias of socket_get_option
    • socket_getpeername — Queries the remote side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
    • socket_getsockname — Queries the local side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
    • socket_import_stream — Import a stream
    • socket_last_error — Returns the last error on the socket
    • socket_listen — Listens for a connection on a socket
    • socket_read — Reads a maximum of length bytes from a socket
    • socket_recv — Receives data from a connected socket
    • socket_recvfrom — Receives data from a socket whether or not it is connection-oriented
    • socket_recvmsg — Read a message
    • socket_select — Runs the select() system call on the given arrays of sockets with a specified timeout
    • socket_send — Sends data to a connected socket
    • socket_sendmsg — Send a message
    • socket_sendto — Sends a message to a socket, whether it is connected or not
    • socket_set_block — Sets blocking mode on a socket resource
    • socket_set_nonblock — Sets nonblocking mode for file descriptor fd
    • socket_set_option — Sets socket options for the socket
    • socket_setopt — Alias of socket_set_option
    • socket_shutdown — Shuts down a socket for receiving, sending, or both
    • socket_strerror — Return a string describing a socket error
    • socket_write — Write to a socket
    • socket_wsaprotocol_info_export — Exports the WSAPROTOCOL_INFO Structure
    • socket_wsaprotocol_info_import — Imports a Socket from another Process
    • socket_wsaprotocol_info_release — Releases an exported WSAPROTOCOL_INFO Structure


Introduction

The socket extension implements a low-level interface to the socket communication functions based on the popular BSD sockets, providing the possibility to act as a socket server as well as a client.

For a more generic client-side socket interface, see
stream_socket_client(),
stream_socket_server(),
fsockopen(), and
pfsockopen().

When using these functions, it is important to remember that while many of them have identical names to their C counterparts, they often have different declarations. Please be sure to read the descriptions to avoid confusion.

Those unfamiliar with socket programming can find a lot of useful material in the appropriate Unix man pages, and there is a great deal of tutorial information on socket programming in C on the web, much of which can be applied, with slight modifications, to socket programming in PHP. The » Unix Socket FAQ might be a good start.


Installation

The socket functions described here are part of an extension to PHP which must be enabled at compile time by giving the --enable-sockets option to configure.


  • « Runtime Configuration
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

socket_accept(),
socket_create_listen() and
socket_create() return socket 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.

AF_UNIX (integer)
AF_INET (integer)
AF_INET6 (integer)
Only available if compiled with IPv6 support.
SOCK_STREAM (integer)
SOCK_DGRAM (integer)
SOCK_RAW (integer)
SOCK_SEQPACKET (integer)
SOCK_RDM (integer)
MSG_OOB (integer)
MSG_WAITALL (integer)
MSG_PEEK (integer)
MSG_DONTROUTE (integer)
MSG_EOR (integer)
Not available on Windows platforms.
MSG_EOF (integer)
Not available on Windows platforms.
SO_DEBUG (integer)
SO_REUSEADDR (integer)
SO_REUSEPORT (integer)
This constant is only available in PHP 5.4.10 or later on platforms that support the SO_REUSEPORT socket option: this includes macOS and FreeBSD, but does not include Linux or Windows.
SO_KEEPALIVE (integer)
SO_DONTROUTE (integer)
SO_LINGER (integer)
SO_BROADCAST (integer)
SO_OOBINLINE (integer)
SO_SNDBUF (integer)
SO_RCVBUF (integer)
SO_SNDLOWAT (integer)
SO_RCVLOWAT (integer)
SO_SNDTIMEO (integer)
SO_RCVTIMEO (integer)
SO_TYPE (integer)
SO_ERROR (integer)
TCP_NODELAY (integer)
Used to disable Nagle TCP algorithm. Added in PHP 5.2.7.
SOL_SOCKET (integer)
PHP_NORMAL_READ (integer)
PHP_BINARY_READ (integer)
SOL_TCP (integer)
SOL_UDP (integer)

The following constants are defined under Windows and UNIX-like platforms. Each constant is only defined if their equal is available on the platform.

SOCKET_EINTR (integer)
Interrupted system call.
SOCKET_EBADF (integer)
Bad file number.
SOCKET_EACCES (integer)
Permission denied.
SOCKET_EFAULT (integer)
Bad address.
SOCKET_EINVAL (integer)
Invalid argument.
SOCKET_EMFILE (integer)
Too many open files.
SOCKET_ENAMETOOLONG (integer)
File name too long.
SOCKET_ENOTEMPTY (integer)
Directory not empty.
SOCKET_ELOOP (integer)
Too many symbolic links encountered.
SOCKET_EWOULDBLOCK (integer)
Operation would block.
SOCKET_EREMOTE (integer)
Object is remote.
SOCKET_EUSERS (integer)
Too many users.
SOCKET_ENOTSOCK (integer)
Socket operation on non-socket.
SOCKET_EDESTADDRREQ (integer)
Destination address required.
SOCKET_EMSGSIZE (integer)
Message too long.
SOCKET_EPROTOTYPE (integer)
Protocol wrong type for socket.
SOCKET_EPROTONOSUPPORT (integer)
Protocol not supported.
SOCKET_ESOCKTNOSUPPORT (integer)
Socket type not supported.
SOCKET_EOPNOTSUPP (integer)
Operation not supported on transport endpoint.
SOCKET_EPFNOSUPPORT (integer)
Protocol family not supported.
SOCKET_EAFNOSUPPORT (integer)
Address family not supported by protocol.
SOCKET_EADDRNOTAVAIL (integer)
Cannot assign requested address.
SOCKET_ENETDOWN (integer)
Network is down.
SOCKET_ENETUNREACH (integer)
Network is unreachable.
SOCKET_ENETRESET (integer)
Network dropped connection because of reset.
SOCKET_ECONNABORTED (integer)
Software caused connection abort.
SOCKET_ECONNRESET (integer)
Connection reset by peer.
SOCKET_ENOBUFS (integer)
No buffer space available.
SOCKET_EISCONN (integer)
Transport endpoint is already connected.
SOCKET_ENOTCONN (integer)
Transport endpoint is not connected.
SOCKET_ESHUTDOWN (integer)
Cannot send after transport endpoint shutdown.
SOCKET_ETIMEDOUT (integer)
Connection timed out.
SOCKET_ECONNREFUSED (integer)
Connection refused.
SOCKET_EHOSTDOWN (integer)
Host is down.
SOCKET_EHOSTUNREACH (integer)
No route to host.
SOCKET_EALREADY (integer)
Operation already in progress.
SOCKET_EINPROGRESS (integer)
Operation now in progress.

The following constants are only defined under Windows.

SOCKET_ENOPROTOOPT (integer)
SOCKET_EADDRINUSE (integer)
SOCKET_ETOOMYREFS (integer)
SOCKET_EPROCLIM (integer)
SOCKET_EDUOT (integer)
SOCKET_ESTALE (integer)
SOCKET_EDISCON (integer)
SOCKET_SYSNOTREADY (integer)
SOCKET_VERNOTSUPPORTED (integer)
SOCKET_NOTINITIALISED (integer)
SOCKET_HOST_NOT_FOUND (integer)
SOCKET_TRY_AGAIN (integer)
SOCKET_NO_RECOVERY (integer)
SOCKET_NO_DATA (integer)
SOCKET_NO_ADDRESS (integer)

The following constants are only available on UNIX-like platforms. Each constant is only defined if their equal is available on the platform.

SOCKET_EPERM (integer)
Operation not permitted.
SOCKET_ENOENT (integer)
No such file or directory.
SOCKET_EIO (integer)
I/O error.
SOCKET_ENXIO (integer)
No such device or address.
SOCKET_E2BIG (integer)
Arg list too long.
SOCKET_EAGAIN (integer)
Try again.
SOCKET_ENOMEM (integer)
Out of memory.
SOCKET_ENOTBLK (integer)
Block device required.
SOCKET_EBUSY (integer)
Device or resource busy.
SOCKET_EEXIST (integer)
File exists.
SOCKET_EXDEV (integer)
Cross-device link.
SOCKET_ENODEV (integer)
No such device.
SOCKET_ENOTDIR (integer)
Not a directory.
SOCKET_EISDIR (integer)
Is a directory.
SOCKET_ENFILE (integer)
File table overflow.
SOCKET_ENOTTY (integer)
Not a typewriter.
SOCKET_ENOSPC (integer)
No space left on device.
SOCKET_ESPIPE (integer)
Illegal seek.
SOCKET_EROFS (integer)
Read-only file system.
SOCKET_EMLINK (integer)
Too many links.
SOCKET_EPIPE (integer)
Broken pipe.
SOCKET_ENOLCK (integer)
No record locks available.
SOCKET_ENOSYS (integer)
Function not implemented.
SOCKET_ENOMSG (integer)
No message of desired type.
SOCKET_EIDRM (integer)
Identifier removed.
SOCKET_ECHRNG (integer)
Channel number out of range.
SOCKET_EL2NSYNC (integer)
Level 2 not synchronized.
SOCKET_EL3HLT (integer)
Level 3 halted.
SOCKET_EL3RST (integer)
Level 3 reset.
SOCKET_ELNRNG (integer)
Link number out of range.
SOCKET_EUNATCH (integer)
Protocol driver not attached.
SOCKET_ENOCSI (integer)
No CSI structure available.
SOCKET_EL2HLT (integer)
Level 2 halted.
SOCKET_EBADE (integer)
Invalid exchange.
SOCKET_EBADR (integer)
Invalid request descriptor.
SOCKET_EXFULL (integer)
Exchange full.
SOCKET_ENOANO (integer)
No anode.
SOCKET_EBADRQC (integer)
Invalid request code.
SOCKET_EBADSLT (integer)
Invalid slot.
SOCKET_ENOSTR (integer)
Device not a stream.
SOCKET_ENODATA (integer)
No data available.
SOCKET_ETIME (integer)
Timer expired.
SOCKET_ENOSR (integer)
Out of streams resources.
SOCKET_ENONET (integer)
Machine is not on the network.
SOCKET_ENOLINK (integer)
Link has been severed.
SOCKET_EADV (integer)
Advertise error.
SOCKET_ESRMNT (integer)
Srmount error.
SOCKET_ECOMM (integer)
Communication error on send.
SOCKET_EPROTO (integer)
Protocol error.
SOCKET_EMULTIHOP (integer)
Multihop attempted.
SOCKET_EBADMSG (integer)
Not a data message.
SOCKET_ENOTUNIQ (integer)
Name not unique on network.
SOCKET_EBADFD (integer)
File descriptor in bad state.
SOCKET_EREMCHG (integer)
Remote address changed.
SOCKET_ERESTART (integer)
Interrupted system call should be restarted.
SOCKET_ESTRPIPE (integer)
Streams pipe error.
SOCKET_EPROTOOPT (integer)
Protocol not available.
SOCKET_ADDRINUSE (integer)
Address already in use.
SOCKET_ETOOMANYREFS (integer)
Too many references: cannot splice.
SOCKET_EISNAM (integer)
Is a named type file.
SOCKET_EREMOTEIO (integer)
Remote I/O error.
SOCKET_EDQUOT (integer)
Quota exceeded.
SOCKET_ENOMEDIUM (integer)
No medium found.
SOCKET_EMEDIUMTYPE (integer)
Wrong medium type.


Examples

Example #1 Socket example: Simple TCP/IP server

This example shows a simple talkback server. Change the address and port variables to suit your setup and execute. You may then connect to the server with a command similar to: telnet 192.168.1.53 10000 (where the address and port match your setup). Anything you type will then be output on the server side, and echoed back to you. To disconnect, enter 'quit'.

#!/usr/local/bin/php -q
<?php
error_reporting(E_ALL);

/* Allow the script to hang around waiting for connections. */
set_time_limit(0);

/* Turn on implicit output flushing so we see what we're getting
 * as it comes in. */
ob_implicit_flush();

$address = '192.168.1.53';
$port = 10000;

if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}

if (socket_bind($sock, $address, $port) === false) {
    echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}

if (socket_listen($sock, 5) === false) {
    echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}

do {
    if (($msgsock = socket_accept($sock)) === false) {
        echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
        break;
    }
    /* Send instructions. */
    $msg = "\nWelcome to the PHP Test Server. \n" .
        "To quit, type 'quit'. To shut down the server type 'shutdown'.\n";
    socket_write($msgsock, $msg, strlen($msg));

    do {
        if (false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
            echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
            break 2;
        }
        if (!$buf = trim($buf)) {
            continue;
        }
        if ($buf == 'quit') {
            break;
        }
        if ($buf == 'shutdown') {
            socket_close($msgsock);
            break 2;
        }
        $talkback = "PHP: You said '$buf'.\n";
        socket_write($msgsock, $talkback, strlen($talkback));
        echo "$buf\n";
    } while (true);
    socket_close($msgsock);
} while (true);

socket_close($sock);
?>

Example #2 Socket example: Simple TCP/IP client

This example shows a simple, one-shot HTTP client. It simply connects to a page, submits a HEAD request, echoes the reply, and exits.

<?php
error_reporting(E_ALL);

echo "<h2>TCP/IP Connection</h2>\n";

/* Get the port for the WWW service. */
$service_port = getservbyname('www', 'tcp');

/* Get the IP address for the target host. */
$address = gethostbyname('www.example.com');

/* 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";
} else {
    echo "OK.\n";
}

echo "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
    echo "OK.\n";
}

$in = "HEAD / HTTP/1.1\r\n";
$in .= "Host: www.example.com\r\n";
$in .= "Connection: Close\r\n\r\n";
$out = '';

echo "Sending HTTP HEAD request...";
socket_write($socket, $in, strlen($in));
echo "OK.\n";

echo "Reading response:\n\n";
while ($out = socket_read($socket, 2048)) {
    echo $out;
}

echo "Closing socket...";
socket_close($socket);
echo "OK.\n\n";
?>


Socket Errors

The socket extension was written to provide a usable interface to the powerful BSD sockets. Care has been taken that the functions work equally well on Win32 and Unix implementations. Almost all of the sockets functions may fail under certain conditions and therefore emit an E_WARNING message describing the error. Sometimes this doesn't happen to the desire of the developer. For example the function socket_read() may suddenly emit an E_WARNING message because the connection broke unexpectedly. It's common to suppress the warning with the @-operator and catch the error code within the application with the socket_last_error() function. You may call the socket_strerror() function with this error code to retrieve a string describing the error. See their description for more information.

Note:

The E_WARNING messages generated by the socket extension are in English though the retrieved error message will appear depending on the current locale (LC_MESSAGES):

Warning - socket_bind() unable to bind address [98]: Die Adresse wird bereits verwendet


Socket Functions

Table of Contents

  • socket_accept — Accepts a connection on a socket
  • socket_addrinfo_bind — Create and bind to a socket from a given addrinfo
  • socket_addrinfo_connect — Create and connect to a socket from a given addrinfo
  • socket_addrinfo_explain — Get information about addrinfo
  • socket_addrinfo_lookup — Get array with contents of getaddrinfo about the given hostname
  • socket_bind — Binds a name to a socket
  • socket_clear_error — Clears the error on the socket or the last error code
  • socket_close — Closes a socket resource
  • socket_cmsg_space — Calculate message buffer size
  • socket_connect — Initiates a connection on a socket
  • socket_create_listen — Opens a socket on port to accept connections
  • socket_create_pair — Creates a pair of indistinguishable sockets and stores them in an array
  • socket_create — Create a socket (endpoint for communication)
  • socket_export_stream — Export a socket extension resource into a stream that encapsulates a socket
  • socket_get_option — Gets socket options for the socket
  • socket_getopt — Alias of socket_get_option
  • socket_getpeername — Queries the remote side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
  • socket_getsockname — Queries the local side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
  • socket_import_stream — Import a stream
  • socket_last_error — Returns the last error on the socket
  • socket_listen — Listens for a connection on a socket
  • socket_read — Reads a maximum of length bytes from a socket
  • socket_recv — Receives data from a connected socket
  • socket_recvfrom — Receives data from a socket whether or not it is connection-oriented
  • socket_recvmsg — Read a message
  • socket_select — Runs the select() system call on the given arrays of sockets with a specified timeout
  • socket_send — Sends data to a connected socket
  • socket_sendmsg — Send a message
  • socket_sendto — Sends a message to a socket, whether it is connected or not
  • socket_set_block — Sets blocking mode on a socket resource
  • socket_set_nonblock — Sets nonblocking mode for file descriptor fd
  • socket_set_option — Sets socket options for the socket
  • socket_setopt — Alias of socket_set_option
  • socket_shutdown — Shuts down a socket for receiving, sending, or both
  • socket_strerror — Return a string describing a socket error
  • socket_write — Write to a socket
  • socket_wsaprotocol_info_export — Exports the WSAPROTOCOL_INFO Structure
  • socket_wsaprotocol_info_import — Imports a Socket from another Process
  • socket_wsaprotocol_info_release — Releases an exported WSAPROTOCOL_INFO Structure


Accepts a connection on a socket

  • « Socket Functions
  • socket_addrinfo_bind »
  • PHP Manual
  • Socket Functions
  • Accepts a connection on a socket

socket_accept

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_accept — Accepts a connection on a socket

Description

socket_accept ( resource $socket ) : resource

After the socket socket has been created using socket_create(), bound to a name with socket_bind(), and told to listen for connections with socket_listen(), this function will accept incoming connections on that socket. Once a successful connection is made, a new socket resource is returned, which may be used for communication. If there are multiple connections queued on the socket, the first will be used. If there are no pending connections, socket_accept() will block until a connection becomes present. If socket has been made non-blocking using socket_set_blocking() or socket_set_nonblock(), FALSE will be returned.

The socket resource returned by socket_accept() may not be used to accept new connections. The original listening socket socket, however, remains open and may be reused.

Parameters

socket

A valid socket resource created with socket_create().

Return Values

Returns a new socket resource on success, or FALSE on error. The actual error code can be retrieved by calling socket_last_error(). This error code may be passed to socket_strerror() to get a textual explanation of the error.

See Also

  • socket_connect() - Initiates a connection on a socket
  • socket_listen() - Listens for a connection on a socket
  • socket_create() - Create a socket (endpoint for communication)
  • socket_bind() - Binds a name to a socket
  • socket_strerror() - Return a string describing a socket error


Create and bind to a socket from a given addrinfo

  • « socket_accept
  • socket_addrinfo_connect »
  • PHP Manual
  • Socket Functions
  • Create and bind to a socket from a given addrinfo

socket_addrinfo_bind

(PHP 7 >= 7.2.0)

socket_addrinfo_bind — Create and bind to a socket from a given addrinfo

Description

socket_addrinfo_bind ( resource $addr ) : resource

Create a Socket resource, and bind it to the provided AddrInfo resource. The return value of this function may be used with socket_listen().

Parameters

addr

Resource created from socket_addrinfo_lookup().

Return Values

Returns a Socket resource on success or NULL on failure.

See Also

  • socket_addrinfo_connect() - Create and connect to a socket from a given addrinfo
  • socket_addrinfo_explain() - Get information about addrinfo
  • socket_addrinfo_lookup() - Get array with contents of getaddrinfo about the given hostname
  • socket_listen() - Listens for a connection on a socket


Create and connect to a socket from a given addrinfo

  • « socket_addrinfo_bind
  • socket_addrinfo_explain »
  • PHP Manual
  • Socket Functions
  • Create and connect to a socket from a given addrinfo

socket_addrinfo_connect

(PHP 7 >= 7.2.0)

socket_addrinfo_connect — Create and connect to a socket from a given addrinfo

Description

socket_addrinfo_connect ( resource $addr ) : resource

Create a Socket resource, and connect it to the provided AddrInfo resource. The return value of this function may be used with the rest of the socket functions.

Parameters

addr

Resource created from socket_addrinfo_lookup()

Return Values

Returns a Socket resource on success or NULL on failure.

See Also

  • socket_addrinfo_bind() - Create and bind to a socket from a given addrinfo
  • socket_addrinfo_explain() - Get information about addrinfo
  • socket_addrinfo_lookup() - Get array with contents of getaddrinfo about the given hostname


Get information about addrinfo

  • « socket_addrinfo_connect
  • socket_addrinfo_lookup »
  • PHP Manual
  • Socket Functions
  • Get information about addrinfo

socket_addrinfo_explain

(PHP 7 >= 7.2.0)

socket_addrinfo_explain — Get information about addrinfo

Description

socket_addrinfo_explain ( resource $addr ) : array

socket_addrinfo_explain() exposed the underlying addrinfo structure.

Parameters

addr

Resource created from socket_addrinfo_lookup()

Return Values

Returns an array containing the fields in the addrinfo structure.

See Also

  • socket_addrinfo_bind() - Create and bind to a socket from a given addrinfo
  • socket_addrinfo_connect() - Create and connect to a socket from a given addrinfo
  • socket_addrinfo_lookup() - Get array with contents of getaddrinfo about the given hostname


Get array with contents of getaddrinfo about the given hostname

  • « socket_addrinfo_explain
  • socket_bind »
  • PHP Manual
  • Socket Functions
  • Get array with contents of getaddrinfo about the given hostname

socket_addrinfo_lookup

(PHP 7 >= 7.2.0)

socket_addrinfo_lookup — Get array with contents of getaddrinfo about the given hostname

Description

socket_addrinfo_lookup ( string $host [, string $service [, array $hints ]] ) : array

Lookup different ways we can connect to host. The returned array contains a set of resources that we can bind to using socket_addrinfo_bind().

Parameters

host

Hostname to search.

service

The service to connect to. If service is a name, it is translated to the corresponding port number.

hints

Hints provide criteria for selecting addresses returned. You may specify the hints as defined by getadrinfo.

Return Values

Returns an array of AddrInfo resource handles that can be used with the other socket_addrinfo functions.

See Also

  • socket_addrinfo_bind() - Create and bind to a socket from a given addrinfo
  • socket_addrinfo_connect() - Create and connect to a socket from a given addrinfo
  • socket_addrinfo_explain() - Get information about addrinfo


Binds a name to a socket

  • « socket_addrinfo_lookup
  • socket_clear_error »
  • PHP Manual
  • Socket Functions
  • Binds a name to a socket

socket_bind

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_bind — Binds a name to a socket

Description

socket_bind ( resource $socket , string $address [, int $port = 0 ] ) : bool

Binds the name given in address to the socket described by socket. This has to be done before a connection is be established using socket_connect() or socket_listen().

Parameters

socket

A valid socket resource created with socket_create().

address

If the socket is of the AF_INET family, the address is an IP in dotted-quad notation (e.g. 127.0.0.1).

If the socket is of the AF_UNIX family, the address is the path of a Unix-domain socket (e.g. /tmp/my.sock).

port (Optional)

The port parameter is only used when binding an AF_INET socket, and designates the port on which to listen for connections.

Return Values

Returns TRUE on success or FALSE on failure.

The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual explanation of the error.

Examples

Example #1 Using socket_bind() to set the source address

<?php
// Create a new socket
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

// An example list of IP addresses owned by the computer
$sourceips['kevin']    = '127.0.0.1';
$sourceips['madcoder'] = '127.0.0.2';

// Bind the source address
socket_bind($sock, $sourceips['madcoder']);

// Connect to destination address
socket_connect($sock, '127.0.0.1', 80);

// Write
$request = 'GET / HTTP/1.1' . "\r\n" .
           'Host: example.com' . "\r\n\r\n";
socket_write($sock, $request);

// Close
socket_close($sock);

?>

Notes

Note:

This function must be used on the socket before socket_connect().

Note:

Windows 9x/ME compatibility note: socket_last_error() may return an invalid error code if trying to bind the socket to a wrong address that does not belong to your machine.

See Also

  • socket_connect() - Initiates a connection on a socket
  • socket_listen() - Listens for a connection on a socket
  • socket_create() - Create a socket (endpoint for communication)
  • socket_last_error() - Returns the last error on the socket
  • socket_strerror() - Return a string describing a socket error


Clears the error on the socket or the last error code

  • « socket_bind
  • socket_close »
  • PHP Manual
  • Socket Functions
  • Clears the error on the socket or the last error code

socket_clear_error

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

socket_clear_error — Clears the error on the socket or the last error code

Description

socket_clear_error ([ resource $socket ] ) : void

This function clears the error code on the given socket or the global last socket error if no socket is specified.

This function allows explicitly resetting the error code value either of a socket or of the extension global last error code. This may be useful to detect within a part of the application if an error occurred or not.

Parameters

socket

A valid socket resource created with socket_create().

Return Values

No value is returned.

See Also

  • socket_last_error() - Returns the last error on the socket
  • socket_strerror() - Return a string describing a socket error


Closes a socket resource

  • « socket_clear_error
  • socket_cmsg_space »
  • PHP Manual
  • Socket Functions
  • Closes a socket resource

socket_close

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_close — Closes a socket resource

Description

socket_close ( resource $socket ) : void

socket_close() closes the socket resource given by socket. This function is specific to sockets and cannot be used on any other type of resources.

Parameters

socket

A valid socket resource created with socket_create() or socket_accept().

Return Values

No value is returned.

See Also

  • socket_bind() - Binds a name to a socket
  • socket_listen() - Listens for a connection on a socket
  • socket_create() - Create a socket (endpoint for communication)
  • socket_strerror() - Return a string describing a socket error


Calculate message buffer size

  • « socket_close
  • socket_connect »
  • PHP Manual
  • Socket Functions
  • Calculate message buffer size

socket_cmsg_space

(PHP 5 >= 5.5.0, PHP 7)

socket_cmsg_space — Calculate message buffer size

Description

socket_cmsg_space ( int $level , int $type [, int $n = 0 ] ) : int

Calculates the size of the buffer that should be allocated for receiving the ancillary data.

Warning

This function is currently not documented; only its argument list is available.

Parameters

level

type

Return Values

See Also

  • socket_recvmsg() - Read a message
  • socket_sendmsg() - Send a message


Initiates a connection on a socket

  • « socket_cmsg_space
  • socket_create_listen »
  • PHP Manual
  • Socket Functions
  • Initiates a connection on a socket

socket_connect

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_connect — Initiates a connection on a socket

Description

socket_connect ( resource $socket , string $address [, int $port = 0 ] ) : bool

Initiate a connection to address using the socket resource socket, which must be a valid socket resource created with socket_create().

Parameters

socket

address

The address parameter is either an IPv4 address in dotted-quad notation (e.g. 127.0.0.1) if socket is AF_INET, a valid IPv6 address (e.g. ::1) if IPv6 support is enabled and socket is AF_INET6 or the pathname of a Unix domain socket, if the socket family is AF_UNIX.

port

The port parameter is only used and is mandatory when connecting to an AF_INET or an AF_INET6 socket, and designates the port on the remote host to which a connection should be made.

Return Values

Returns TRUE on success or FALSE on failure. The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual explanation of the error.

Note:

If the socket is non-blocking then this function returns FALSE with an error Operation now in progress.

See Also

  • socket_bind() - Binds a name to a socket
  • socket_listen() - Listens for a connection on a socket
  • socket_create() - Create a socket (endpoint for communication)
  • socket_last_error() - Returns the last error on the socket
  • socket_strerror() - Return a string describing a socket error


Opens a socket on port to accept connections

  • « socket_connect
  • socket_create_pair »
  • PHP Manual
  • Socket Functions
  • Opens a socket on port to accept connections

socket_create_listen

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_create_listen — Opens a socket on port to accept connections

Description

socket_create_listen ( int $port [, int $backlog = 128 ] ) : resource

socket_create_listen() creates a new socket resource of type AF_INET listening on all local interfaces on the given port waiting for new connections.

This function is meant to ease the task of creating a new socket which only listens to accept new connections.

Parameters

port

The port on which to listen on all interfaces.

backlog

The backlog parameter defines the maximum length the queue of pending connections may grow to. SOMAXCONN may be passed as backlog parameter, see socket_listen() for more information.

Return Values

socket_create_listen() returns a new socket resource on success or FALSE on error. The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual explanation of the error.

Notes

Note:

If you want to create a socket which only listens on a certain interface you need to use socket_create(), socket_bind() and socket_listen().

See Also

  • socket_create() - Create a socket (endpoint for communication)
  • socket_create_pair() - Creates a pair of indistinguishable sockets and stores them in an array
  • socket_bind() - Binds a name to a socket
  • socket_listen() - Listens for a connection on a socket
  • socket_last_error() - Returns the last error on the socket
  • socket_strerror() - Return a string describing a socket error


Creates a pair of indistinguishable sockets and stores them in an array

  • « socket_create_listen
  • socket_create »
  • PHP Manual
  • Socket Functions
  • Creates a pair of indistinguishable sockets and stores them in an array

socket_create_pair

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_create_pair — Creates a pair of indistinguishable sockets and stores them in an array

Description

socket_create_pair ( int $domain , int $type , int $protocol , array &$fd ) : bool

socket_create_pair() creates two connected and indistinguishable sockets, and stores them in fd. This function is commonly used in IPC (InterProcess Communication).

Parameters

domain

The domain parameter specifies the protocol family to be used by the socket. See socket_create() for the full list.

type

The type parameter selects the type of communication to be used by the socket. See socket_create() for the full list.

protocol

The protocol parameter sets the specific protocol within the specified domain to be used when communicating on the returned socket. The proper value can be retrieved by name by using getprotobyname(). If the desired protocol is TCP, or UDP the corresponding constants SOL_TCP, and SOL_UDP can also be used.

See socket_create() for the full list of supported protocols.

fd

Reference to an array in which the two socket resources will be inserted.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.3.0 | This function is now available on Windows platforms.

Examples

Example #1 socket_create_pair() example

<?php
$sockets = array();

/* On Windows we need to use AF_INET */
$domain = (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' ? AF_INET : AF_UNIX);

/* Setup socket pair */
if (socket_create_pair($domain, SOCK_STREAM, 0, $sockets) === false) {
    echo "socket_create_pair failed. Reason: ".socket_strerror(socket_last_error());
}
/* Send and Recieve Data */
if (socket_write($sockets[0], "ABCdef123\n", strlen("ABCdef123\n")) === false) {
    echo "socket_write() failed. Reason: ".socket_strerror(socket_last_error($sockets[0]));
}
if (($data = socket_read($sockets[1], strlen("ABCdef123\n"), PHP_BINARY_READ)) === false) {
    echo "socket_read() failed. Reason: ".socket_strerror(socket_last_error($sockets[1]));
}
var_dump($data);

/* Close sockets */
socket_close($sockets[0]);
socket_close($sockets[1]);
?>

Example #2 socket_create_pair() IPC example

<?php
$ary = array();
$strone = 'Message From Parent.';
$strtwo = 'Message From Child.';

if (socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $ary) === false) {
    echo "socket_create_pair() failed. Reason: ".socket_strerror(socket_last_error());
}
$pid = pcntl_fork();
if ($pid == -1) {
    echo 'Could not fork Process.';
} elseif ($pid) {
    /*parent*/
    socket_close($ary[0]);
    if (socket_write($ary[1], $strone, strlen($strone)) === false) {
        echo "socket_write() failed. Reason: ".socket_strerror(socket_last_error($ary[1]));
    }
    if (socket_read($ary[1], strlen($strtwo), PHP_BINARY_READ) == $strtwo) {
        echo "Recieved $strtwo\n";
    }
    socket_close($ary[1]);
} else {
    /*child*/
    socket_close($ary[1]);
    if (socket_write($ary[0], $strtwo, strlen($strtwo)) === false) {
        echo "socket_write() failed. Reason: ".socket_strerror(socket_last_error($ary[0]));
    }
    if (socket_read($ary[0], strlen($strone), PHP_BINARY_READ) == $strone) {
        echo "Recieved $strone\n";
    }
    socket_close($ary[0]);
}
?>

See Also

  • socket_create() - Create a socket (endpoint for communication)
  • socket_create_listen() - Opens a socket on port to accept connections
  • socket_bind() - Binds a name to a socket
  • socket_listen() - Listens for a connection on a socket
  • socket_last_error() - Returns the last error on the socket
  • socket_strerror() - Return a string describing a socket error


Create a socket (endpoint for communication)

  • « socket_create_pair
  • socket_export_stream »
  • PHP Manual
  • Socket Functions
  • Create a socket (endpoint for communication)

socket_create

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_create — Create a socket (endpoint for communication)

Description

socket_create ( int $domain , int $type , int $protocol ) : resource

Creates and returns a socket resource, also referred to as an endpoint of communication. A typical network connection is made up of 2 sockets, one performing the role of the client, and another performing the role of the server.

Parameters

domain

The domain parameter specifies the protocol family to be used by the socket.

Available address/protocol families
Domain | Description
AF_INET | IPv4 Internet based protocols. TCP and UDP are common protocols of this protocol family.
AF_INET6 | IPv6 Internet based protocols. TCP and UDP are common protocols of this protocol family.
AF_UNIX | Local communication protocol family. High efficiency and low overhead make it a great form of IPC (Interprocess Communication).
type

The type parameter selects the type of communication to be used by the socket.

Available socket types
Type | Description
SOCK_STREAM | Provides sequenced, reliable, full-duplex, connection-based byte streams. An out-of-band data transmission mechanism may be supported. The TCP protocol is based on this socket type.
SOCK_DGRAM | Supports datagrams (connectionless, unreliable messages of a fixed maximum length). The UDP protocol is based on this socket type.
SOCK_SEQPACKET | Provides a sequenced, reliable, two-way connection-based data transmission path for datagrams of fixed maximum length; a consumer is required to read an entire packet with each read call.
SOCK_RAW | Provides raw network protocol access. This special type of socket can be used to manually construct any type of protocol. A common use for this socket type is to perform ICMP requests (like ping).
SOCK_RDM | Provides a reliable datagram layer that does not guarantee ordering. This is most likely not implemented on your operating system.
protocol

The protocol parameter sets the specific protocol within the specified domain to be used when communicating on the returned socket. The proper value can be retrieved by name by using getprotobyname(). If the desired protocol is TCP, or UDP the corresponding constants SOL_TCP, and SOL_UDP can also be used.

Common protocols
Name | Description
icmp | The Internet Control Message Protocol is used primarily by gateways and hosts to report errors in datagram communication. The "ping" command (present in most modern operating systems) is an example application of ICMP.
udp | The User Datagram Protocol is a connectionless, unreliable, protocol with fixed record lengths. Due to these aspects, UDP requires a minimum amount of protocol overhead.
tcp | The Transmission Control Protocol is a reliable, connection based, stream oriented, full duplex protocol. TCP guarantees that all data packets will be received in the order in which they were sent. If any packet is somehow lost during communication, TCP will automatically retransmit the packet until the destination host acknowledges that packet. For reliability and performance reasons, the TCP implementation itself decides the appropriate octet boundaries of the underlying datagram communication layer. Therefore, TCP applications must allow for the possibility of partial record transmission.

Return Values

socket_create() returns a socket resource on success, or FALSE on error. The actual error code can be retrieved by calling socket_last_error(). This error code may be passed to socket_strerror() to get a textual explanation of the error.

Errors/Exceptions

If an invalid domain or type is given, socket_create() defaults to AF_INET and SOCK_STREAM respectively and additionally emits an E_WARNING message.

See Also

  • socket_accept() - Accepts a connection on a socket
  • socket_bind() - Binds a name to a socket
  • socket_connect() - Initiates a connection on a socket
  • socket_listen() - Listens for a connection on a socket
  • socket_last_error() - Returns the last error on the socket
  • socket_strerror() - Return a string describing a socket error


Export a socket extension resource into a stream that encapsulates a socket

  • « socket_create
  • socket_get_option »
  • PHP Manual
  • Socket Functions
  • Export a socket extension resource into a stream that encapsulates a socket

socket_export_stream

(PHP 7 >= 7.0.7)

socket_export_stream — Export a socket extension resource into a stream that encapsulates a socket

Description

socket_export_stream ( resource $socket ) : resource

Warning

This function is currently not documented; only its argument list is available.

Parameters

socket

Return Values

Return resource or FALSE on failure.


Gets socket options for the socket

  • « socket_export_stream
  • socket_getopt »
  • PHP Manual
  • Socket Functions
  • Gets socket options for the socket

socket_get_option

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

socket_get_option — Gets socket options for the socket

Description

socket_get_option ( resource $socket , int $level , int $optname ) : mixed

The socket_get_option() function retrieves the value for the option specified by the optname parameter for the specified socket.

Parameters

socket

A valid socket resource created with socket_create() or socket_accept().

level

The level parameter specifies the protocol level at which the option resides. For example, to retrieve options at the socket level, a level parameter of SOL_SOCKET would be used. Other levels, such as TCP, can be used by specifying the protocol number of that level. Protocol numbers can be found by using the getprotobyname() function.

optname
Available Socket Options
Option | Description | Type
SO_DEBUG | Reports whether debugging information is being recorded. | int
SO_BROADCAST | Reports whether transmission of broadcast messages is supported. | int
SO_REUSEADDR | Reports whether local addresses can be reused. | int
SO_REUSEPORT | Reports whether local ports can be reused. | int
SO_KEEPALIVE | Reports whether connections are kept active with periodic transmission of messages. If the connected socket fails to respond to these messages, the connection is broken and processes writing to that socket are notified with a SIGPIPE signal. | int
SO_LINGER

Reports whether the socket lingers on socket_close() if data is present. By default, when the socket is closed, it attempts to send all unsent data. In the case of a connection-oriented socket, socket_close() will wait for its peer to acknowledge the data.

If l_onoff is non-zero and l_linger is zero, all the unsent data will be discarded and RST (reset) is sent to the peer in the case of a connection-oriented socket.

On the other hand, if l_onoff is non-zero and l_linger is non-zero, socket_close() will block until all the data is sent or the time specified in l_linger elapses. If the socket is non-blocking, socket_close() will fail and return an error.

array. The array will contain two keys: l_onoff and l_linger.
SO_OOBINLINE | Reports whether the socket leaves out-of-band data inline. | int
SO_SNDBUF | Reports the size of the send buffer. | int
SO_RCVBUF | Reports the size of the receive buffer. | int
SO_ERROR | Reports information about error status and clears it. | int (cannot be set by socket_set_option())
SO_TYPE | Reports the socket type (e.g. SOCK_STREAM). | int (cannot be set by socket_set_option())
SO_DONTROUTE | Reports whether outgoing messages bypass the standard routing facilities. | int
SO_RCVLOWAT | Reports the minimum number of bytes to process for socket input operations. | int
SO_RCVTIMEO | Reports the timeout value for input operations. | array. The array will contain two keys: sec which is the seconds part on the timeout value and usec which is the microsecond part of the timeout value.
SO_SNDTIMEO | Reports the timeout value specifying the amount of time that an output function blocks because flow control prevents data from being sent. | array. The array will contain two keys: sec which is the seconds part on the timeout value and usec which is the microsecond part of the timeout value.
SO_SNDLOWAT | Reports the minimum number of bytes to process for socket output operations. | int
TCP_NODELAY | Reports whether the Nagle TCP algorithm is disabled. | int
MCAST_JOIN_GROUP | Joins a multicast group. (added in PHP 5.4) | array with keys "group", specifying a string with an IPv4 or IPv6 multicast address and "interface", specifying either an interface number (type int) or a string with the interface name, like "eth0". 0 can be specified to indicate the interface should be selected using routing rules. (can only be used in socket_set_option())
MCAST_LEAVE_GROUP | Leaves a multicast group. (added in PHP 5.4) | array. See MCAST_JOIN_GROUP for more information. (can only be used in socket_set_option())
MCAST_BLOCK_SOURCE | Blocks packets arriving from a specific source to a specific multicast group, which must have been previously joined. (added in PHP 5.4) | array with the same keys as MCAST_JOIN_GROUP, plus one extra key, source, which maps to a string specifying an IPv4 or IPv6 address of the source to be blocked. (can only be used in socket_set_option())
MCAST_UNBLOCK_SOURCE | Unblocks (start receiving again) packets arriving from a specific source address to a specific multicast group, which must have been previously joined. (added in PHP 5.4) | array with the same format as MCAST_BLOCK_SOURCE. (can only be used in socket_set_option())
MCAST_JOIN_SOURCE_GROUP | Receive packets destined to a specific multicast group whose source address matches a specific value. (added in PHP 5.4) | array with the same format as MCAST_BLOCK_SOURCE. (can only be used in socket_set_option())
MCAST_LEAVE_SOURCE_GROUP | Stop receiving packets destined to a specific multicast group whose soure address matches a specific value. (added in PHP 5.4) | array with the same format as MCAST_BLOCK_SOURCE. (can only be used in socket_set_option())
IP_MULTICAST_IF | The outgoing interface for IPv4 multicast packets. (added in PHP 5.4) | Either int specifying the interface number or a string with an interface name, like eth0. The value 0 can be used to indicate the routing table is to used in the interface selection. The function socket_get_option() returns an interface index. Note that, unlike the C API, this option does NOT take an IP address. This eliminates the interface difference between IP_MULTICAST_IF and IPV6_MULTICAST_IF.
IPV6_MULTICAST_IF | The outgoing interface for IPv6 multicast packets. (added in PHP 5.4) | The same as IP_MULTICAST_IF.
IP_MULTICAST_LOOP | The multicast loopback policy for IPv4 packets, which determines whether multicast packets sent by this socket also reach receivers in the same host that have joined the same multicast group on the outgoing interface used by this socket. This is the case by default. (added in PHP 5.4) | int (either 0 or 1). For socket_set_option() any value will be accepted and will be converted to a boolean following the usual PHP rules.
IPV6_MULTICAST_LOOP | Analogous to IP_MULTICAST_LOOP, but for IPv6. (added in PHP 5.4) | int. See IP_MULTICAST_LOOP.
IP_MULTICAST_TTL | The time-to-live of outgoing IPv4 multicast packets. This should be a value between 0 (don't leave the interface) and 255. The default value is 1 (only the local network is reached). (added in PHP 5.4) | int between 0 and 255.
IPV6_MULTICAST_HOPS | Analogous to IP_MULTICAST_TTL, but for IPv6 packets. The value -1 is also accepted, meaning the route default should be used. (added in PHP 5.4) | int between -1 and 255.

Return Values

Returns the value of the given option, or FALSE on errors.

Examples

Example #1 socket_get_option() example

<?php
$socket = socket_create_listen(1223);

$linger = array('l_linger' => 1, 'l_onoff' => 1);
socket_set_option($socket, SOL_SOCKET, SO_LINGER, $linger);

var_dump(socket_get_option($socket, SOL_SOCKET, SO_REUSEADDR));
?>

See Also

  • socket_create_listen() - Opens a socket on port to accept connections
  • socket_set_option() - Sets socket options for the socket


Alias of socket_get_option

  • « socket_get_option
  • socket_getpeername »
  • PHP Manual
  • Socket Functions
  • Alias of socket_get_option

socket_getopt

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_getopt — Alias of socket_get_option()

Description

This function is an alias of: socket_get_option().


Queries the remote side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type

  • « socket_getopt
  • socket_getsockname »
  • PHP Manual
  • Socket Functions
  • Queries the remote side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type

socket_getpeername

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_getpeername — Queries the remote side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type

Description

socket_getpeername ( resource $socket , string &$address [, int &$port ] ) : bool

Queries the remote side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type.

Parameters

socket

A valid socket resource created with socket_create() or socket_accept().

address

If the given socket is of type AF_INET or AF_INET6, socket_getpeername() will return the peers (remote) IP address in appropriate notation (e.g. 127.0.0.1 or fe80::1) in the address parameter and, if the optional port parameter is present, also the associated port.

If the given socket is of type AF_UNIX, socket_getpeername() will return the Unix filesystem path (e.g. /var/run/daemon.sock) in the address parameter.

port

If given, this will hold the port associated to address.

Return Values

Returns TRUE on success or FALSE on failure. socket_getpeername() may also return FALSE if the socket type is not any of AF_INET, AF_INET6, or AF_UNIX, in which case the last socket error code is not updated.

Notes

Note:

socket_getpeername() should not be used with AF_UNIX sockets created with socket_accept(). Only sockets created with socket_connect() or a primary server socket following a call to socket_bind() will return meaningful values.

Note:

For having socket_getpeername() to return a meaningful value, the socket it is applied upon must of course be one for which the concept of "peer" makes sense.

See Also

  • socket_getsockname() - Queries the local side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
  • socket_last_error() - Returns the last error on the socket
  • socket_strerror() - Return a string describing a socket error


Queries the local side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type

  • « socket_getpeername
  • socket_import_stream »
  • PHP Manual
  • Socket Functions
  • Queries the local side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type

socket_getsockname

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_getsockname — Queries the local side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type

Description

socket_getsockname ( resource $socket , string &$addr [, int &$port ] ) : bool

Note: socket_getsockname() should not be used with AF_UNIX sockets created with socket_connect(). Only sockets created with socket_accept() or a primary server socket following a call to socket_bind() will return meaningful values.

Parameters

socket

A valid socket resource created with socket_create() or socket_accept().

addr

If the given socket is of type AF_INET or AF_INET6, socket_getsockname() will return the local IP address in appropriate notation (e.g. 127.0.0.1 or fe80::1) in the address parameter and, if the optional port parameter is present, also the associated port.

If the given socket is of type AF_UNIX, socket_getsockname() will return the Unix filesystem path (e.g. /var/run/daemon.sock) in the address parameter.

port

If provided, this will hold the associated port.

Return Values

Returns TRUE on success or FALSE on failure. socket_getsockname() may also return FALSE if the socket type is not any of AF_INET, AF_INET6, or AF_UNIX, in which case the last socket error code is not updated.

See Also

  • socket_getpeername() - Queries the remote side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
  • socket_last_error() - Returns the last error on the socket
  • socket_strerror() - Return a string describing a socket error


Import a stream

  • « socket_getsockname
  • socket_last_error »
  • PHP Manual
  • Socket Functions
  • Import a stream

socket_import_stream

(PHP 5 >= 5.4.0, PHP 7)

socket_import_stream — Import a stream

Description

socket_import_stream ( resource $stream ) : resource

Imports a stream that encapsulates a socket into a socket extension resource.

Parameters

stream

The stream resource to import.

Return Values

Returns FALSE or NULL on failure.

Examples

Example #1 socket_import_stream() example

<?php
$stream = stream_socket_server("udp://0.0.0.0:58380", $errno, $errstr, STREAM_SERVER_BIND);
$sock   = socket_import_stream($stream);
?>

See Also

  • stream_socket_server() - Create an Internet or Unix domain server socket


Returns the last error on the socket

  • « socket_import_stream
  • socket_listen »
  • PHP Manual
  • Socket Functions
  • Returns the last error on the socket

socket_last_error

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_last_error — Returns the last error on the socket

Description

socket_last_error ([ resource $socket ] ) : int

If a socket resource is passed to this function, the last error which occurred on this particular socket is returned. If the socket resource is omitted, the error code of the last failed socket function is returned. The latter is particularly helpful for functions like socket_create() which don't return a socket on failure and socket_select() which can fail for reasons not directly tied to a particular socket. The error code is suitable to be fed to socket_strerror() which returns a string describing the given error code.

If no error had occurred, or the error had been cleared with socket_clear_error(), the function returns 0.

Parameters

socket

A valid socket resource created with socket_create().

Return Values

This function returns a socket error code.

Examples

Example #1 socket_last_error() example

<?php
$socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

if ($socket === false) {
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);

    die("Couldn't create socket: [$errorcode] $errormsg");
}
?>

Notes

Note:

socket_last_error() does not clear the error code, use socket_clear_error() for this purpose.


Listens for a connection on a socket

  • « socket_last_error
  • socket_read »
  • PHP Manual
  • Socket Functions
  • Listens for a connection on a socket

socket_listen

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_listen — Listens for a connection on a socket

Description

socket_listen ( resource $socket [, int $backlog = 0 ] ) : bool

After the socket socket has been created using socket_create() and bound to a name with socket_bind(), it may be told to listen for incoming connections on socket.

socket_listen() is applicable only to sockets of type SOCK_STREAM or SOCK_SEQPACKET.

Parameters

socket

A valid socket resource created with socket_create() or socket_addrinfo_bind()

backlog

A maximum of backlog incoming connections will be queued for processing. If a connection request arrives with the queue full the client may receive an error with an indication of ECONNREFUSED, or, if the underlying protocol supports retransmission, the request may be ignored so that retries may succeed.

Note:

The maximum number passed to the backlog parameter highly depends on the underlying platform. On Linux, it is silently truncated to SOMAXCONN. On win32, if passed SOMAXCONN, the underlying service provider responsible for the socket will set the backlog to a maximum reasonable value. There is no standard provision to find out the actual backlog value on this platform.

Return Values

Returns TRUE on success or FALSE on failure. The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual explanation of the error.

See Also

  • socket_accept() - Accepts a connection on a socket
  • socket_bind() - Binds a name to a socket
  • socket_connect() - Initiates a connection on a socket
  • socket_create() - Create a socket (endpoint for communication)
  • socket_strerror() - Return a string describing a socket error
  • socket_addrinfo_bind() - Create and bind to a socket from a given addrinfo


Reads a maximum of length bytes from a socket

  • « socket_listen
  • socket_recv »
  • PHP Manual
  • Socket Functions
  • Reads a maximum of length bytes from a socket

socket_read

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_read — Reads a maximum of length bytes from a socket

Description

socket_read ( resource $socket , int $length [, int $type = PHP_BINARY_READ ] ) : string

The function socket_read() reads from the socket resource socket created by the socket_create() or socket_accept() functions.

Parameters

socket

A valid socket resource created with socket_create() or socket_accept().

length

The maximum number of bytes read is specified by the length parameter. Otherwise you can use \r, \n, or \0 to end reading (depending on the type parameter, see below).

type

Optional type parameter is a named constant:

  • PHP_BINARY_READ (Default) - use the system recv() function. Safe for reading binary data.
  • PHP_NORMAL_READ - reading stops at \n or \r.

Return Values

socket_read() returns the data as a string on success, or FALSE on error (including if the remote host has closed the connection). The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual representation of the error.

Note:

socket_read() returns a zero length string ("") when there is no more data to read.

See Also

  • socket_accept() - Accepts a connection on a socket
  • socket_bind() - Binds a name to a socket
  • socket_connect() - Initiates a connection on a socket
  • socket_listen() - Listens for a connection on a socket
  • socket_last_error() - Returns the last error on the socket
  • socket_strerror() - Return a string describing a socket error
  • socket_write() - Write to a socket


Receives data from a connected socket

  • « socket_read
  • socket_recvfrom »
  • PHP Manual
  • Socket Functions
  • Receives data from a connected socket

socket_recv

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_recv — Receives data from a connected socket

Description

socket_recv ( resource $socket , string &$buf , int $len , int $flags ) : int

The socket_recv() function receives len bytes of data in buf from socket. socket_recv() can be used to gather data from connected sockets. Additionally, one or more flags can be specified to modify the behaviour of the function.

buf is passed by reference, so it must be specified as a variable in the argument list. Data read from socket by socket_recv() will be returned in buf.

Parameters

socket

The socket must be a socket resource previously created by socket_create().

buf

The data received will be fetched to the variable specified with buf. If an error occurs, if the connection is reset, or if no data is available, buf will be set to NULL.

len

Up to len bytes will be fetched from remote host.

flags

The value of flags can be any combination of the following flags, joined with the binary OR (|) operator.

Possible values for flags
Flag | Description
MSG_OOB | Process out-of-band data.
MSG_PEEK | Receive data from the beginning of the receive queue without removing it from the queue.
MSG_WAITALL | Block until at least len are received. However, if a signal is caught or the remote host disconnects, the function may return less data.
MSG_DONTWAIT | With this flag set, the function returns even if it would normally have blocked.

Return Values

socket_recv() returns the number of bytes received, or FALSE if there was an error. The actual error code can be retrieved by calling socket_last_error(). This error code may be passed to socket_strerror() to get a textual explanation of the error.

Examples

Example #1 socket_recv() example

This example is a simple rewrite of the first example from Examples to use socket_recv().

<?php
error_reporting(E_ALL);

echo "<h2>TCP/IP Connection</h2>\n";

/* Get the port for the WWW service. */
$service_port = getservbyname('www', 'tcp');

/* Get the IP address for the target host. */
$address = gethostbyname('www.example.com');

/* 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";
} else {
    echo "OK.\n";
}

echo "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
    echo "OK.\n";
}

$in = "HEAD / HTTP/1.1\r\n";
$in .= "Host: www.example.com\r\n";
$in .= "Connection: Close\r\n\r\n";
$out = '';

echo "Sending HTTP HEAD request...";
socket_write($socket, $in, strlen($in));
echo "OK.\n";

echo "Reading response:\n\n";
$buf = 'This is my buffer.';
if (false !== ($bytes = socket_recv($socket, $buf, 2048, MSG_WAITALL))) {
    echo "Read $bytes bytes from socket_recv(). Closing socket...";
} else {
    echo "socket_recv() failed; reason: " . socket_strerror(socket_last_error($socket)) . "\n";
}
socket_close($socket);

echo $buf . "\n";
echo "OK.\n\n";
?>

The above example will produce something like:

<h2>TCP/IP Connection</h2>
OK.
Attempting to connect to '208.77.188.166' on port '80'...OK.
Sending HTTP HEAD request...OK.
Reading response:

Read 123 bytes from socket_recv(). Closing socket...HTTP/1.1 200 OK
Date: Mon, 14 Sep 2009 08:56:36 GMT
Server: Apache/2.2.3 (Red Hat)
Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT
ETag: "b80f4-1b6-80bfd280"
Accept-Ranges: bytes
Content-Length: 438
Connection: close
Content-Type: text/html; charset=UTF-8

OK.


Receives data from a socket whether or not it is connection-oriented

  • « socket_recv
  • socket_recvmsg »
  • PHP Manual
  • Socket Functions
  • Receives data from a socket whether or not it is connection-oriented

socket_recvfrom

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_recvfrom — Receives data from a socket whether or not it is connection-oriented

Description

socket_recvfrom ( resource $socket , string &$buf , int $len , int $flags , string &$name [, int &$port ] ) : int

The socket_recvfrom() function receives len bytes of data in buf from name on port port (if the socket is not of type AF_UNIX) using socket. socket_recvfrom() can be used to gather data from both connected and unconnected sockets. Additionally, one or more flags can be specified to modify the behaviour of the function.

The name and port must be passed by reference. If the socket is not connection-oriented, name will be set to the internet protocol address of the remote host or the path to the UNIX socket. If the socket is connection-oriented, name is NULL. Additionally, the port will contain the port of the remote host in the case of an unconnected AF_INET or AF_INET6 socket.

Note: This function is binary-safe.

Parameters

socket

The socket must be a socket resource previously created by socket_create().

buf

The data received will be fetched to the variable specified with buf.

len

Up to len bytes will be fetched from remote host.

flags

The value of flags can be any combination of the following flags, joined with the binary OR (|) operator.

Possible values for flags
Flag | Description
MSG_OOB | Process out-of-band data.
MSG_PEEK | Receive data from the beginning of the receive queue without removing it from the queue.
MSG_WAITALL | Block until at least len are received. However, if a signal is caught or the remote host disconnects, the function may return less data.
MSG_DONTWAIT | With this flag set, the function returns even if it would normally have blocked.
name

If the socket is of the type AF_UNIX type, name is the path to the file. Else, for unconnected sockets, name is the IP address of, the remote host, or NULL if the socket is connection-oriented.

port

This argument only applies to AF_INET and AF_INET6 sockets, and specifies the remote port from which the data is received. If the socket is connection-oriented, port will be NULL.

Return Values

socket_recvfrom() returns the number of bytes received, or FALSE if there was an error. The actual error code can be retrieved by calling socket_last_error(). This error code may be passed to socket_strerror() to get a textual explanation of the error.

Examples

Example #1 socket_recvfrom() example

<?php
error_reporting(E_ALL | E_STRICT);

$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_bind($socket, '127.0.0.1', 1223);

$from = '';
$port = 0;
socket_recvfrom($socket, $buf, 12, 0, $from, $port);

echo "Received $buf from remote address $from and remote port $port" . PHP_EOL;
?>

This example will initiate a UDP socket on port 1223 of 127.0.0.1 and print at most 12 characters received from a remote host.

See Also

  • socket_recv() - Receives data from a connected socket
  • socket_send() - Sends data to a connected socket
  • socket_sendto() - Sends a message to a socket, whether it is connected or not
  • socket_create() - Create a socket (endpoint for communication)


Read a message

  • « socket_recvfrom
  • socket_select »
  • PHP Manual
  • Socket Functions
  • Read a message

socket_recvmsg

(PHP 5 >= 5.5.0, PHP 7)

socket_recvmsg — Read a message

Description

socket_recvmsg ( resource $socket , array &$message [, int $flags = 0 ] ) : int

Warning

This function is currently not documented; only its argument list is available.

Parameters

socket

message

flags

Return Values

See Also

  • socket_sendmsg() - Send a message
  • socket_cmsg_space() - Calculate message buffer size


Runs the select() system call on the given arrays of sockets with a specified timeout

  • « socket_recvmsg
  • socket_send »
  • PHP Manual
  • Socket Functions
  • Runs the select() system call on the given arrays of sockets with a specified timeout

socket_select

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_select — Runs the select() system call on the given arrays of sockets with a specified timeout

Description

socket_select ( array &$read , array &$write , array &$except , int $tv_sec [, int $tv_usec = 0 ] ) : int

socket_select() accepts arrays of sockets and waits for them to change status. Those coming with BSD sockets background will recognize that those socket resource arrays are in fact the so-called file descriptor sets. Three independent arrays of socket resources are watched.

Parameters

read

The sockets listed in the read array will be watched to see if characters become available for reading (more precisely, to see if a read will not block - in particular, a socket resource is also ready on end-of-file, in which case a socket_read() will return a zero length string).

write

The sockets listed in the write array will be watched to see if a write will not block.

except

The sockets listed in the except array will be watched for exceptions.

tv_sec

The tv_sec and tv_usec together form the timeout parameter. The timeout is an upper bound on the amount of time elapsed before socket_select() return. tv_sec may be zero , causing socket_select() to return immediately. This is useful for polling. If tv_sec is NULL (no timeout), socket_select() can block indefinitely.

tv_usec

Warning

On exit, the arrays are modified to indicate which socket resource actually changed status.

You do not need to pass every array to socket_select(). You can leave it out and use an empty array or NULL instead. Also do not forget that those arrays are passed by reference and will be modified after socket_select() returns.

Note:

Due a limitation in the current Zend Engine it is not possible to pass a constant modifier like NULL directly as a parameter to a function which expects this parameter to be passed by reference. Instead use a temporary variable or an expression with the leftmost member being a temporary variable:

Example #1 Using NULL with socket_select()

<?php
$e = NULL;
socket_select($r, $w, $e, 0);
?>

Return Values

On success socket_select() returns the number of socket resources contained in the modified arrays, which may be zero if the timeout expires before anything interesting happens. On error FALSE is returned. The error code can be retrieved with socket_last_error().

Note:

Be sure to use the === operator when checking for an error. Since the socket_select() may return 0 the comparison with == would evaluate to TRUE:

Example #2 Understanding socket_select()'s result

<?php
$e = NULL;
if (false === socket_select($r, $w, $e, 0)) {
    echo "socket_select() failed, reason: " .
        socket_strerror(socket_last_error()) . "\n";
}
?>

Examples

Example #3 socket_select() example

<?php
/* Prepare the read array */
$read   = array($socket1, $socket2);
$write  = NULL;
$except = NULL;
$num_changed_sockets = socket_select($read, $write, $except, 0);

if ($num_changed_sockets === false) {
    /* Error handling */
} else if ($num_changed_sockets > 0) {
    /* At least at one of the sockets something interesting happened */
}
?>

Notes

Note:

Be aware that some socket implementations need to be handled very carefully. A few basic rules:

  • You should always try to use socket_select() without timeout. Your program should have nothing to do if there is no data available. Code that depends on timeouts is not usually portable and difficult to debug.
  • No socket resource must be added to any set if you do not intend to check its result after the socket_select() call, and respond appropriately. After socket_select() returns, all socket resources in all arrays must be checked. Any socket resource that is available for writing must be written to, and any socket resource available for reading must be read from.
  • If you read/write to a socket returns in the arrays be aware that they do not necessarily read/write the full amount of data you have requested. Be prepared to even only be able to read/write a single byte.
  • It's common to most socket implementations that the only exception caught with the except array is out-of-bound data received on a socket.

See Also

  • socket_read() - Reads a maximum of length bytes from a socket
  • socket_write() - Write to a socket
  • socket_last_error() - Returns the last error on the socket
  • socket_strerror() - Return a string describing a socket error


Sends data to a connected socket

  • « socket_select
  • socket_sendmsg »
  • PHP Manual
  • Socket Functions
  • Sends data to a connected socket

socket_send

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_send — Sends data to a connected socket

Description

socket_send ( resource $socket , string $buf , int $len , int $flags ) : int

The function socket_send() sends len bytes to the socket socket from buf.

Parameters

socket

A valid socket resource created with socket_create() or socket_accept().

buf

A buffer containing the data that will be sent to the remote host.

len

The number of bytes that will be sent to the remote host from buf.

flags

The value of flags can be any combination of the following flags, joined with the binary OR (|) operator.

Possible values for flags
MSG_OOB | Send OOB (out-of-band) data.
MSG_EOR | Indicate a record mark. The sent data completes the record.
MSG_EOF | Close the sender side of the socket and include an appropriate notification of this at the end of the sent data. The sent data completes the transaction.
MSG_DONTROUTE | Bypass routing, use direct interface.

Return Values

socket_send() returns the number of bytes sent, or FALSE on error.

See Also

  • socket_sendto() - Sends a message to a socket, whether it is connected or not


Send a message

  • « socket_send
  • socket_sendto »
  • PHP Manual
  • Socket Functions
  • Send a message

socket_sendmsg

(PHP 5 >= 5.5.0, PHP 7)

socket_sendmsg — Send a message

Description

socket_sendmsg ( resource $socket , array $message [, int $flags = 0 ] ) : int

Warning

This function is currently not documented; only its argument list is available.

Parameters

socket

message

flags

Return Values

Returns the number of bytes sent, or FALSE on failure.

See Also

  • socket_recvmsg() - Read a message
  • socket_cmsg_space() - Calculate message buffer size


Sends a message to a socket, whether it is connected or not

  • « socket_sendmsg
  • socket_set_block »
  • PHP Manual
  • Socket Functions
  • Sends a message to a socket, whether it is connected or not

socket_sendto

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_sendto — Sends a message to a socket, whether it is connected or not

Description

socket_sendto ( resource $socket , string $buf , int $len , int $flags , string $addr [, int $port = 0 ] ) : int

The function socket_sendto() sends len bytes from buf through the socket socket to the port at the address addr.

Parameters

socket

A valid socket resource created using socket_create().

buf

The sent data will be taken from buffer buf.

len

len bytes from buf will be sent.

flags

The value of flags can be any combination of the following flags, joined with the binary OR (|) operator.

Possible values for flags
MSG_OOB | Send OOB (out-of-band) data.
MSG_EOR | Indicate a record mark. The sent data completes the record.
MSG_EOF | Close the sender side of the socket and include an appropriate notification of this at the end of the sent data. The sent data completes the transaction.
MSG_DONTROUTE | Bypass routing, use direct interface.

addr

IP address of the remote host.

port

port is the remote port number at which the data will be sent.

Return Values

socket_sendto() returns the number of bytes sent to the remote host, or FALSE if an error occurred.

Examples

Example #1 socket_sendto() Example

<?php
    $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);

    $msg = "Ping !";
    $len = strlen($msg);

    socket_sendto($sock, $msg, $len, 0, '127.0.0.1', 1223);
    socket_close($sock);
?>

See Also

  • socket_send() - Sends data to a connected socket


Sets blocking mode on a socket resource

  • « socket_sendto
  • socket_set_nonblock »
  • PHP Manual
  • Socket Functions
  • Sets blocking mode on a socket resource

socket_set_block

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

socket_set_block — Sets blocking mode on a socket resource

Description

socket_set_block ( resource $socket ) : bool

The socket_set_block() function removes the O_NONBLOCK flag on the socket specified by the socket parameter.

When an operation (e.g. receive, send, connect, accept, ...) is performed on a blocking socket, the script will pause its execution until it receives a signal or it can perform the operation.

Parameters

socket

A valid socket resource created with socket_create() or socket_accept().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 socket_set_block() example

<?php
$socket = socket_create_listen(1223);
socket_set_block($socket);

socket_accept($socket);
?>

This example creates a listening socket on all interfaces on port 1223 and sets the socket to O_BLOCK mode. socket_accept() will hang until there is a connection to accept.

See Also

  • socket_set_nonblock() - Sets nonblocking mode for file descriptor fd
  • socket_set_option() - Sets socket options for the socket


Sets nonblocking mode for file descriptor fd

  • « socket_set_block
  • socket_set_option »
  • PHP Manual
  • Socket Functions
  • Sets nonblocking mode for file descriptor fd

socket_set_nonblock

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_set_nonblock — Sets nonblocking mode for file descriptor fd

Description

socket_set_nonblock ( resource $socket ) : bool

The socket_set_nonblock() function sets the O_NONBLOCK flag on the socket specified by the socket parameter.

When an operation (e.g. receive, send, connect, accept, ...) is performed on a non-blocking socket, the script will not pause its execution until it receives a signal or it can perform the operation. Rather, if the operation would result in a block, the called function will fail.

Parameters

socket

A valid socket resource created with socket_create() or socket_accept().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 socket_set_nonblock() example

<?php
$socket = socket_create_listen(1223);
socket_set_nonblock($socket);

socket_accept($socket);
?>

This example creates a listening socket on all interfaces on port 1223 and sets the socket to O_NONBLOCK mode. socket_accept() will immediately fail unless there is a pending connection exactly at this moment.

See Also

  • socket_set_block() - Sets blocking mode on a socket resource
  • socket_set_option() - Sets socket options for the socket
  • stream_set_blocking() - Set blocking/non-blocking mode on a stream


Sets socket options for the socket

  • « socket_set_nonblock
  • socket_setopt »
  • PHP Manual
  • Socket Functions
  • Sets socket options for the socket

socket_set_option

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

socket_set_option — Sets socket options for the socket

Description

socket_set_option ( resource $socket , int $level , int $optname , mixed $optval ) : bool

The socket_set_option() function sets the option specified by the optname parameter, at the specified protocol level, to the value pointed to by the optval parameter for the socket.

Parameters

socket

A valid socket resource created with socket_create() or socket_accept().

level

The level parameter specifies the protocol level at which the option resides. For example, to retrieve options at the socket level, a level parameter of SOL_SOCKET would be used. Other levels, such as TCP, can be used by specifying the protocol number of that level. Protocol numbers can be found by using the getprotobyname() function.

optname

The available socket options are the same as those for the socket_get_option() function.

optval

The option value.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 socket_set_option() example

<?php
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

if (!is_resource($socket)) {
    echo 'Unable to create socket: '. socket_strerror(socket_last_error()) . PHP_EOL;
}

if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
    echo 'Unable to set option on socket: '. socket_strerror(socket_last_error()) . PHP_EOL;
}

if (!socket_bind($socket, '127.0.0.1', 1223)) {
    echo 'Unable to bind socket: '. socket_strerror(socket_last_error()) . PHP_EOL;
}

$rval = socket_get_option($socket, SOL_SOCKET, SO_REUSEADDR);

if ($rval === false) {
    echo 'Unable to get socket option: '. socket_strerror(socket_last_error()) . PHP_EOL;
} else if ($rval !== 0) {
    echo 'SO_REUSEADDR is set on socket !' . PHP_EOL;
}
?>

See Also

  • socket_create() - Create a socket (endpoint for communication)
  • socket_bind() - Binds a name to a socket
  • socket_strerror() - Return a string describing a socket error
  • socket_last_error() - Returns the last error on the socket
  • socket_get_option() - Gets socket options for the socket


Alias of socket_set_option

  • « socket_set_option
  • socket_shutdown »
  • PHP Manual
  • Socket Functions
  • Alias of socket_set_option

socket_setopt

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_setopt — Alias of socket_set_option()

Description

This function is an alias of: socket_set_option().


Shuts down a socket for receiving, sending, or both

  • « socket_setopt
  • socket_strerror »
  • PHP Manual
  • Socket Functions
  • Shuts down a socket for receiving, sending, or both

socket_shutdown

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_shutdown — Shuts down a socket for receiving, sending, or both

Description

socket_shutdown ( resource $socket [, int $how = 2 ] ) : bool

The socket_shutdown() function allows you to stop incoming, outgoing or all data (the default) from being sent through the socket

Note:

The associated buffer, or buffers, may or may not be emptied.

Parameters

socket

A valid socket resource created with socket_create().

how

The value of how can be one of the following:

possible values for how
0 | Shutdown socket reading
1 | Shutdown socket writing
2 | Shutdown socket reading and writing

Return Values

Returns TRUE on success or FALSE on failure.


Return a string describing a socket error

  • « socket_shutdown
  • socket_write »
  • PHP Manual
  • Socket Functions
  • Return a string describing a socket error

socket_strerror

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_strerror — Return a string describing a socket error

Description

socket_strerror ( int $errno ) : string

socket_strerror() takes as its errno parameter a socket error code as returned by socket_last_error() and returns the corresponding explanatory text.

Note:

Although the error messages generated by the socket extension are in English, the system messages retrieved with this function will appear depending on the current locale (LC_MESSAGES).

Parameters

errno

A valid socket error number, likely produced by socket_last_error().

Return Values

Returns the error message associated with the errno parameter.

Examples

Example #1 socket_strerror() example

<?php
if (false == ($socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) {
   echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}

if (false == (@socket_bind($socket, '127.0.0.1', 80))) {
   echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($socket)) . "\n";
}
?>

The expected output from the above example (assuming the script is not run with root privileges):

socket_bind() failed: reason: Permission denied

See Also

  • socket_accept() - Accepts a connection on a socket
  • socket_bind() - Binds a name to a socket
  • socket_connect() - Initiates a connection on a socket
  • socket_listen() - Listens for a connection on a socket
  • socket_create() - Create a socket (endpoint for communication)


Write to a socket

  • « socket_strerror
  • socket_wsaprotocol_info_export »
  • PHP Manual
  • Socket Functions
  • Write to a socket

socket_write

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

socket_write — Write to a socket

Description

socket_write ( resource $socket , string $buffer [, int $length = 0 ] ) : int

The function socket_write() writes to the socket from the given buffer.

Parameters

socket

buffer

The buffer to be written.

length

The optional parameter length can specify an alternate length of bytes written to the socket. If this length is greater than the buffer length, it is silently truncated to the length of the buffer.

Return Values

Returns the number of bytes successfully written to the socket or FALSE on failure. The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual explanation of the error.

Note:

It is perfectly valid for socket_write() to return zero which means no bytes have been written. Be sure to use the === operator to check for FALSE in case of an error.

Notes

Note:

socket_write() does not necessarily write all bytes from the given buffer. It's valid that, depending on the network buffers etc., only a certain amount of data, even one byte, is written though your buffer is greater. You have to watch out so you don't unintentionally forget to transmit the rest of your data.

See Also

  • socket_accept() - Accepts a connection on a socket
  • socket_bind() - Binds a name to a socket
  • socket_connect() - Initiates a connection on a socket
  • socket_listen() - Listens for a connection on a socket
  • socket_read() - Reads a maximum of length bytes from a socket
  • socket_strerror() - Return a string describing a socket error


Exports the WSAPROTOCOL_INFO Structure

  • « socket_write
  • socket_wsaprotocol_info_import »
  • PHP Manual
  • Socket Functions
  • Exports the WSAPROTOCOL_INFO Structure

socket_wsaprotocol_info_export

(PHP 7 >= 7.3.0)

socket_wsaprotocol_info_export — Exports the WSAPROTOCOL_INFO Structure

Description

socket_wsaprotocol_info_export ( resource $socket , int $target_pid ) : string

Exports the WSAPROTOCOL_INFO structure into shared memory and returns an identifier to be used with socket_wsaprotocol_info_import(). The exported ID is only valid for the given target_pid.

Note: This function is available only on Windows.

Parameters

socket

A valid socket resource.

target_pid

The ID of the process which will import the socket.

Return Values

Returns an identifier to be used for the import, or FALSE on failure

See Also

  • socket_wsaprotocol_info_import() - Imports a Socket from another Process
  • socket_wsaprotocol_info_release() - Releases an exported WSAPROTOCOL_INFO Structure


Imports a Socket from another Process

  • « socket_wsaprotocol_info_export
  • socket_wsaprotocol_info_release »
  • PHP Manual
  • Socket Functions
  • Imports a Socket from another Process

socket_wsaprotocol_info_import

(PHP 7 >= 7.3.0)

socket_wsaprotocol_info_import — Imports a Socket from another Process

Description

socket_wsaprotocol_info_import ( string $info_id ) : resource

Imports a socket which has formerly been exported from another process.

Note: This function is available only on Windows.

Parameters

info_id

The ID which has been returned by a former call to socket_wsaprotocol_info_export().

Return Values

Returns the socket resource, or FALSE on failure

See Also

  • socket_wsaprotocol_info_export() - Exports the WSAPROTOCOL_INFO Structure


Releases an exported WSAPROTOCOL_INFO Structure

  • « socket_wsaprotocol_info_import
  • SSH2 »
  • PHP Manual
  • Socket Functions
  • Releases an exported WSAPROTOCOL_INFO Structure

socket_wsaprotocol_info_release

(PHP 7 >= 7.3.0)

socket_wsaprotocol_info_release — Releases an exported WSAPROTOCOL_INFO Structure

Description

socket_wsaprotocol_info_release ( string $info_id ) : bool

Releases the shared memory corresponding to the given info_id.

Note: This function is available only on Windows.

Parameters

info_id

The ID which has been returned by a former call to socket_wsaprotocol_info_export().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • socket_wsaprotocol_info_export() - Exports the WSAPROTOCOL_INFO Structure


Secure Shell2

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • SSH2 Functions
    • ssh2_auth_agent — Authenticate over SSH using the ssh agent
    • ssh2_auth_hostbased_file — Authenticate using a public hostkey
    • ssh2_auth_none — Authenticate as "none"
    • ssh2_auth_password — Authenticate over SSH using a plain password
    • ssh2_auth_pubkey_file — Authenticate using a public key
    • ssh2_connect — Connect to an SSH server
    • ssh2_disconnect — Close a connection to a remote SSH server
    • ssh2_exec — Execute a command on a remote server
    • ssh2_fetch_stream — Fetch an extended data stream
    • ssh2_fingerprint — Retrieve fingerprint of remote server
    • ssh2_methods_negotiated — Return list of negotiated methods
    • ssh2_publickey_add — Add an authorized publickey
    • ssh2_publickey_init — Initialize Publickey subsystem
    • ssh2_publickey_list — List currently authorized publickeys
    • ssh2_publickey_remove — Remove an authorized publickey
    • ssh2_scp_recv — Request a file via SCP
    • ssh2_scp_send — Send a file via SCP
    • ssh2_sftp_chmod — Changes file mode
    • ssh2_sftp_lstat — Stat a symbolic link
    • ssh2_sftp_mkdir — Create a directory
    • ssh2_sftp_readlink — Return the target of a symbolic link
    • ssh2_sftp_realpath — Resolve the realpath of a provided path string
    • ssh2_sftp_rename — Rename a remote file
    • ssh2_sftp_rmdir — Remove a directory
    • ssh2_sftp_stat — Stat a file on a remote filesystem
    • ssh2_sftp_symlink — Create a symlink
    • ssh2_sftp_unlink — Delete a file
    • ssh2_sftp — Initialize SFTP subsystem
    • ssh2_shell — Request an interactive shell
    • ssh2_tunnel — Open a tunnel through a remote server


Introduction

Bindings to the » libssh2 library which provide access to resources (shell, remote exec, tunneling, file transfer) on a remote machine using a secure cryptographic transport.


Requirements

The » OpenSSL and » libssh2 libraries are required. Ensure that the development libraries are installed, where a typical package name might be openssl-dev.

Version 1.2 or newer of the libssh2 library is required, although it's possible newer releases of pecl/ssh2 may require newer versions (see the release notes).

The ssh2_auth_agent() function will only be available with libssh >= 1.2.3.

support for stream_set_timeout() to channel streams will only be available with libssh >= 1.2.9.

Libssh2 comes in two flavours: gcrypt or openssl. Some linux distributions build libssh2 with the gcrypt library, some use openssl. Libssh2 has some issues when compiled with gcrypt, please use openssl.


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/ssh2.

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.

SSH2_FINGERPRINT_MD5 (integer)
Flag to ssh2_fingerprint() requesting hostkey fingerprint as an MD5 hash.
SSH2_FINGERPRINT_SHA1 (integer)
Flag to ssh2_fingerprint() requesting hostkey fingerprint as an SHA1 hash.
SSH2_FINGERPRINT_HEX (integer)
Flag to ssh2_fingerprint() requesting hostkey fingerprint as a string of hexits.
SSH2_FINGERPRINT_RAW (integer)
Flag to ssh2_fingerprint() requesting hostkey fingerprint as a raw string of 8-bit characters.
SSH2_TERM_UNIT_CHARS (integer)
Flag to ssh2_shell() specifying that width and height are provided as character sizes.
SSH2_TERM_UNIT_PIXELS (integer)
Flag to ssh2_shell() specifying that width and height are provided in pixel units.
SSH2_DEFAULT_TERM_WIDTH (integer)
Default terminal width requested by ssh2_shell().
SSH2_DEFAULT_TERM_HEIGHT (integer)
Default terminal height requested by ssh2_shell().
SSH2_DEFAULT_TERM_UNIT (integer)
Default terminal units requested by ssh2_shell().
SSH2_STREAM_STDIO (integer)
Flag to ssh2_fetch_stream() requesting STDIO subchannel.
SSH2_STREAM_STDERR (integer)
Flag to ssh2_fetch_stream() requesting STDERR subchannel.
SSH2_DEFAULT_TERMINAL (string)
Default terminal type (e.g. vt102, ansi, xterm, vanilla) requested by ssh2_shell().


SSH2 Functions

Table of Contents

  • ssh2_auth_agent — Authenticate over SSH using the ssh agent
  • ssh2_auth_hostbased_file — Authenticate using a public hostkey
  • ssh2_auth_none — Authenticate as "none"
  • ssh2_auth_password — Authenticate over SSH using a plain password
  • ssh2_auth_pubkey_file — Authenticate using a public key
  • ssh2_connect — Connect to an SSH server
  • ssh2_disconnect — Close a connection to a remote SSH server
  • ssh2_exec — Execute a command on a remote server
  • ssh2_fetch_stream — Fetch an extended data stream
  • ssh2_fingerprint — Retrieve fingerprint of remote server
  • ssh2_methods_negotiated — Return list of negotiated methods
  • ssh2_publickey_add — Add an authorized publickey
  • ssh2_publickey_init — Initialize Publickey subsystem
  • ssh2_publickey_list — List currently authorized publickeys
  • ssh2_publickey_remove — Remove an authorized publickey
  • ssh2_scp_recv — Request a file via SCP
  • ssh2_scp_send — Send a file via SCP
  • ssh2_sftp_chmod — Changes file mode
  • ssh2_sftp_lstat — Stat a symbolic link
  • ssh2_sftp_mkdir — Create a directory
  • ssh2_sftp_readlink — Return the target of a symbolic link
  • ssh2_sftp_realpath — Resolve the realpath of a provided path string
  • ssh2_sftp_rename — Rename a remote file
  • ssh2_sftp_rmdir — Remove a directory
  • ssh2_sftp_stat — Stat a file on a remote filesystem
  • ssh2_sftp_symlink — Create a symlink
  • ssh2_sftp_unlink — Delete a file
  • ssh2_sftp — Initialize SFTP subsystem
  • ssh2_shell — Request an interactive shell
  • ssh2_tunnel — Open a tunnel through a remote server


Authenticate over SSH using the ssh agent

  • « SSH2 Functions
  • ssh2_auth_hostbased_file »
  • PHP Manual
  • SSH2 Functions
  • Authenticate over SSH using the ssh agent

ssh2_auth_agent

(PECL ssh2 >= 0.12)

ssh2_auth_agent — Authenticate over SSH using the ssh agent

Description

ssh2_auth_agent ( resource $session , string $username ) : bool

Authenticate over SSH using the ssh agent

Note: The ssh2_auth_agent() function will only be available when the ssh2 extension is compiled with libssh >= 1.2.3.

Parameters

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

username

Remote user name.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Authenticating with a ssh agent

<?php
$connection = ssh2_connect('shell.example.com', 22);

if (ssh2_auth_agent($connection, 'username')) {
  echo "Authentication Successful!\n";
} else {
  die('Authentication Failed...');
}
?>


Authenticate using a public hostkey

  • « ssh2_auth_agent
  • ssh2_auth_none »
  • PHP Manual
  • SSH2 Functions
  • Authenticate using a public hostkey

ssh2_auth_hostbased_file

(PECL ssh2 >= 0.9.0)

ssh2_auth_hostbased_file — Authenticate using a public hostkey

Description

ssh2_auth_hostbased_file ( resource $session , string $username , string $hostname , string $pubkeyfile , string $privkeyfile [, string $passphrase [, string $local_username ]] ) : bool

Authenticate using a public hostkey read from a file.

Parameters

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

username

hostname

pubkeyfile

privkeyfile

passphrase

If privkeyfile is encrypted (which it should be), the passphrase must be provided.

local_username

If local_username is omitted, then the value for username will be used for it.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Authentication using a public hostkey

<?php
$connection = ssh2_connect('shell.example.com', 22, array('hostkey'=>'ssh-rsa'));

if (ssh2_auth_hostbased_file($connection, 'remoteusername', 'myhost.example.com',
                             '/usr/local/etc/hostkey_rsa.pub',
                             '/usr/local/etc/hostkey_rsa', 'secret',
                             'localusername')) {
  echo "Public Key Hostbased Authentication Successful\n";
} else {
  die('Public Key Hostbased Authentication Failed');
}
?>

Notes

Note:

ssh2_auth_hostbased_file() requires libssh2 >= 0.7 and PHP/SSH2 >= 0.7


Authenticate as "none"

  • « ssh2_auth_hostbased_file
  • ssh2_auth_password »
  • PHP Manual
  • SSH2 Functions
  • Authenticate as "none"

ssh2_auth_none

(PECL ssh2 >= 0.9.0)

ssh2_auth_none — Authenticate as "none"

Description

ssh2_auth_none ( resource $session , string $username ) : mixed

Attempt "none" authentication which usually will (and should) fail. As part of the failure, this function will return an array of accepted authentication methods.

Parameters

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

username

Remote user name.

Return Values

Returns TRUE if the server does accept "none" as an authentication method, or an array of accepted authentication methods on failure.

Examples

Example #1 Retrieving a list of authentication methods

<?php
$connection = ssh2_connect('shell.example.com', 22);

$auth_methods = ssh2_auth_none($connection, 'user');

if (in_array('password', $auth_methods)) {
  echo "Server supports password based authentication\n";
}
?>


Authenticate over SSH using a plain password

  • « ssh2_auth_none
  • ssh2_auth_pubkey_file »
  • PHP Manual
  • SSH2 Functions
  • Authenticate over SSH using a plain password

ssh2_auth_password

(PECL ssh2 >= 0.9.0)

ssh2_auth_password — Authenticate over SSH using a plain password

Description

ssh2_auth_password ( resource $session , string $username , string $password ) : bool

Authenticate over SSH using a plain password. Since version 0.12 this function also supports keyboard_interactive method.

Parameters

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

username

Remote user name.

password

Password for username

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Authenticating with a password

<?php
$connection = ssh2_connect('shell.example.com', 22);

if (ssh2_auth_password($connection, 'username', 'secret')) {
  echo "Authentication Successful!\n";
} else {
  die('Authentication Failed...');
}
?>


Authenticate using a public key

  • « ssh2_auth_password
  • ssh2_connect »
  • PHP Manual
  • SSH2 Functions
  • Authenticate using a public key

ssh2_auth_pubkey_file

(PECL ssh2 >= 0.9.0)

ssh2_auth_pubkey_file — Authenticate using a public key

Description

ssh2_auth_pubkey_file ( resource $session , string $username , string $pubkeyfile , string $privkeyfile [, string $passphrase ] ) : bool

Authenticate using a public key read from a file.

Parameters

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

username

pubkeyfile

The public key file needs to be in OpenSSH's format. It should look something like:

ssh-rsa AAAAB3NzaC1yc2EAAA....NX6sqSnHA8= rsa-key-20121110

privkeyfile

passphrase

If privkeyfile is encrypted (which it should be), the passphrase must be provided.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Authentication using a public key

<?php
$connection = ssh2_connect('shell.example.com', 22, array('hostkey'=>'ssh-rsa'));

if (ssh2_auth_pubkey_file($connection, 'username',
                          '/home/username/.ssh/id_rsa.pub',
                          '/home/username/.ssh/id_rsa', 'secret')) {
  echo "Public Key Authentication Successful\n";
} else {
  die('Public Key Authentication Failed');
}
?>

Notes

Note:

The underlying libssh library doesn't support partial auths very cleanly That is, if you need to supply both a public key and a password it will appear as if this function has failed. In this particular case a failure from this call may just mean that auth hasn't been completed yet. You would need to ignore this failure and continue on and call ssh2_auth_password() in order to complete authentication.


Connect to an SSH server

  • « ssh2_auth_pubkey_file
  • ssh2_disconnect »
  • PHP Manual
  • SSH2 Functions
  • Connect to an SSH server

ssh2_connect

(PECL ssh2 >= 0.9.0)

ssh2_connect — Connect to an SSH server

Description

ssh2_connect ( string $host [, int $port = 22 [, array $methods [, array $callbacks ]]] ) : resource

Establish a connection to a remote SSH server.

Once connected, the client should verify the server's hostkey using ssh2_fingerprint(), then authenticate using either password or public key.

Parameters

host

port

methods

methods may be an associative array with up to four parameters as described below.

methods may be an associative array with any or all of the following parameters.
Index | Meaning | Supported Values*
kex | List of key exchange methods to advertise, comma separated in order of preference. | diffie-hellman-group1-sha1, diffie-hellman-group14-sha1, and diffie-hellman-group-exchange-sha1
hostkey | List of hostkey methods to advertise, comma separated in order of preference. | ssh-rsa and ssh-dss
client_to_server | Associative array containing crypt, compression, and message authentication code (MAC) method preferences for messages sent from client to server.
server_to_client | Associative array containing crypt, compression, and message authentication code (MAC) method preferences for messages sent from server to client.

* - Supported Values are dependent on methods supported by underlying library. See » libssh2 documentation for additional information.

client_to_server and server_to_client may be an associative array with any or all of the following parameters.
Index | Meaning | Supported Values*
crypt | List of crypto methods to advertise, comma separated in order of preference. | rijndael-cbc@lysator.liu.se, aes256-cbc, aes192-cbc, aes128-cbc, 3des-cbc, blowfish-cbc, cast128-cbc, arcfour, and none**
comp | List of compression methods to advertise, comma separated in order of preference. | zlib and none
mac | List of MAC methods to advertise, comma separated in order of preference. | hmac-sha1, hmac-sha1-96, hmac-ripemd160, hmac-ripemd160@openssh.com, and none**

Note: Crypt and MAC method "none"

For security reasons, none is disabled by the underlying » libssh2 library unless explicitly enabled during build time by using the appropriate ./configure options. See documentation for the underlying library for more information.

callbacks

callbacks may be an associative array with any or all of the following parameters.

Callbacks parameters
Index | Meaning | Prototype
ignore | Name of function to call when an SSH2_MSG_IGNORE packet is received | void ignore_cb($message)
debug | Name of function to call when an SSH2_MSG_DEBUG packet is received | void debug_cb($message, $language, $always_display)
macerror | Name of function to call when a packet is received but the message authentication code failed. If the callback returns TRUE, the mismatch will be ignored, otherwise the connection will be terminated. | bool macerror_cb($packet)
disconnect | Name of function to call when an SSH2_MSG_DISCONNECT packet is received | void disconnect_cb($reason, $message, $language)

Return Values

Returns a resource on success, or FALSE on error.

Examples

Example #1 ssh2_connect() example

Open a connection forcing 3des-cbc when sending packets, any strength aes cipher when receiving packets, no compression in either direction, and Group1 key exchange.

<?php
/* Notify the user if the server terminates the connection */
function my_ssh_disconnect($reason, $message, $language) {
  printf("Server disconnected with reason code [%d] and message: %s\n",
         $reason, $message);
}

$methods = array(
  'kex' => 'diffie-hellman-group1-sha1',
  'client_to_server' => array(
    'crypt' => '3des-cbc',
    'comp' => 'none'),
  'server_to_client' => array(
    'crypt' => 'aes256-cbc,aes192-cbc,aes128-cbc',
    'comp' => 'none'));

$callbacks = array('disconnect' => 'my_ssh_disconnect');

$connection = ssh2_connect('shell.example.com', 22, $methods, $callbacks);
if (!$connection) die('Connection failed');
?>

See Also

  • ssh2_fingerprint() - Retrieve fingerprint of remote server
  • ssh2_auth_none() - Authenticate as "none"
  • ssh2_auth_password() - Authenticate over SSH using a plain password
  • ssh2_auth_pubkey_file() - Authenticate using a public key
  • ssh2_disconnect() - Close a connection to a remote SSH server


Close a connection to a remote SSH server

  • « ssh2_connect
  • ssh2_exec »
  • PHP Manual
  • SSH2 Functions
  • Close a connection to a remote SSH server

ssh2_disconnect

(PECL ssh2 >= 1.0)

ssh2_disconnect — Close a connection to a remote SSH server

Description

ssh2_disconnect ( resource $session ) : bool

Close a connection to a remote SSH server.

Parameters

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ssh2_connect() - Connect to an SSH server


Execute a command on a remote server

  • « ssh2_disconnect
  • ssh2_fetch_stream »
  • PHP Manual
  • SSH2 Functions
  • Execute a command on a remote server

ssh2_exec

(PECL ssh2 >= 0.9.0)

ssh2_exec — Execute a command on a remote server

Description

ssh2_exec ( resource $session , string $command [, string $pty [, array $env [, int $width = 80 [, int $height = 25 [, int $width_height_type = SSH2_TERM_UNIT_CHARS ]]]]] ) : resource

Execute a command at the remote end and allocate a channel for it.

Parameters

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

command

pty

env

env may be passed as an associative array of name/value pairs to set in the target environment.

width

Width of the virtual terminal.

height

Height of the virtual terminal.

width_height_type

width_height_type should be one of SSH2_TERM_UNIT_CHARS or SSH2_TERM_UNIT_PIXELS.

Return Values

Returns a stream on success or FALSE on failure.

Examples

Example #1 Executing a command

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$stream = ssh2_exec($connection, '/usr/local/bin/php -i');
?>

See Also

  • ssh2_connect() - Connect to an SSH server
  • ssh2_shell() - Request an interactive shell
  • ssh2_tunnel() - Open a tunnel through a remote server


Fetch an extended data stream

  • « ssh2_exec
  • ssh2_fingerprint »
  • PHP Manual
  • SSH2 Functions
  • Fetch an extended data stream

ssh2_fetch_stream

(PECL ssh2 >= 0.9.0)

ssh2_fetch_stream — Fetch an extended data stream

Description

ssh2_fetch_stream ( resource $channel , int $streamid ) : resource

Fetches an alternate substream associated with an SSH2 channel stream. The SSH2 protocol currently defines only one substream, STDERR, which has a substream ID of SSH2_STREAM_STDERR (defined as 1).

Parameters

channel

streamid

An SSH2 channel stream.

Return Values

Returns the requested stream resource.

Examples

Example #1 Opening a shell and retrieving the stderr stream associated with it

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$stdio_stream = ssh2_shell($connection);
$stderr_stream = ssh2_fetch_stream($stdio_stream, SSH2_STREAM_STDERR);
?>

See Also

  • ssh2_shell() - Request an interactive shell
  • ssh2_exec() - Execute a command on a remote server
  • ssh2_connect() - Connect to an SSH server


Retrieve fingerprint of remote server

  • « ssh2_fetch_stream
  • ssh2_methods_negotiated »
  • PHP Manual
  • SSH2 Functions
  • Retrieve fingerprint of remote server

ssh2_fingerprint

(PECL ssh2 >= 0.9.0)

ssh2_fingerprint — Retrieve fingerprint of remote server

Description

ssh2_fingerprint ( resource $session [, int $flags = SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX ] ) : string

Returns a server hostkey hash from an active session.

Parameters

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

flags

flags may be either of SSH2_FINGERPRINT_MD5 or SSH2_FINGERPRINT_SHA1 logically ORed with SSH2_FINGERPRINT_HEX or SSH2_FINGERPRINT_RAW.

Return Values

Returns the hostkey hash as a string.

Examples

Example #1 Checking the fingerprint against a known value

<?php
$known_host = '6F89C2F0A719B30CC38ABDF90755F2E4';

$connection = ssh2_connect('shell.example.com', 22);

$fingerprint = ssh2_fingerprint($connection,
               SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX);

if ($fingerprint != $known_host) {
  die("HOSTKEY MISMATCH!\n" .
      "Possible Man-In-The-Middle Attack?");
}
?>


Return list of negotiated methods

  • « ssh2_fingerprint
  • ssh2_publickey_add »
  • PHP Manual
  • SSH2 Functions
  • Return list of negotiated methods

ssh2_methods_negotiated

(PECL ssh2 >= 0.9.0)

ssh2_methods_negotiated — Return list of negotiated methods

Description

ssh2_methods_negotiated ( resource $session ) : array

Returns list of negotiated methods.

Parameters

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

Return Values

Examples

Example #1 Determining what methods were negotiated

<?php
$connection = ssh2_connect('shell.example.com', 22);
$methods = ssh2_methods_negotiated($connection);

echo "Encryption keys were negotiated using: {$methods['kex']}\n";
echo "Server identified using an {$methods['hostkey']} with ";
echo "fingerprint: " . ssh2_fingerprint($connection) . "\n";

echo "Client to Server packets will use methods:\n";
echo "\tCrypt: {$methods['client_to_server']['crypt']}\n";
echo "\tComp: {$methods['client_to_server']['comp']}\n";
echo "\tMAC: {$methods['client_to_server']['mac']}\n";

echo "Server to Client packets will use methods:\n";
echo "\tCrypt: {$methods['server_to_client']['crypt']}\n";
echo "\tComp: {$methods['server_to_client']['comp']}\n";
echo "\tMAC: {$methods['server_to_client']['mac']}\n";

?>

See Also

  • ssh2_connect() - Connect to an SSH server


Add an authorized publickey

  • « ssh2_methods_negotiated
  • ssh2_publickey_init »
  • PHP Manual
  • SSH2 Functions
  • Add an authorized publickey

ssh2_publickey_add

(PECL ssh2 >= 0.10)

ssh2_publickey_add — Add an authorized publickey

Description

ssh2_publickey_add ( resource $pkey , string $algoname , string $blob [, bool $overwrite = FALSE [, array $attributes ]] ) : bool

Note: The public key subsystem is used for managing public keys on a server to which the client is already authenticated. To authenticate to a remote system using public key authentication, use the ssh2_auth_pubkey_file() function instead.

Parameters

pkey

Publickey Subsystem resource created by ssh2_publickey_init().

algoname

Publickey algorithm (e.g.): ssh-dss, ssh-rsa

blob

Publickey blob as raw binary data

overwrite

If the specified key already exists, should it be overwritten?

attributes

Associative array of attributes to assign to this public key. Refer to ietf-secsh-publickey-subsystem for a list of supported attributes. To mark an attribute as mandatory, precede its name with an asterisk. If the server is unable to support an attribute marked mandatory, it will abort the add process.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Adding a publickey with ssh2_publickey_add()

<?php
$ssh2 = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($ssh2, 'jdoe', 'password');
$pkey = ssh2_publickey_init($ssh2);

$keyblob = base64_decode('
AAAAB3NzaC1yc2EAAAABIwAAAIEA5HVt6VqSGd5PTrLRdjNONxXH1tVFGn0
Bd26BF0aCP9qyJRlvdJ3j4WBeX4ZmrveGrjMgkseSYc4xZ26sDHwfL351xj
zaLpipu\BGRrw17mWVBhuCExo476ri5tQFzbTc54VEHYckxQ16CjSTibI5X
69GmnYC9PNqEYq/1TP+HF10=');

ssh2_publickey_add($pkey, 'ssh-rsa', $keyblob, false, array('comment'=>"John's Key"));
?>

See Also

  • ssh2_publickey_init() - Initialize Publickey subsystem
  • ssh2_publickey_remove() - Remove an authorized publickey
  • ssh2_publickey_list() - List currently authorized publickeys


Initialize Publickey subsystem

  • « ssh2_publickey_add
  • ssh2_publickey_list »
  • PHP Manual
  • SSH2 Functions
  • Initialize Publickey subsystem

ssh2_publickey_init

(PECL ssh2 >= 0.10)

ssh2_publickey_init — Initialize Publickey subsystem

Description

ssh2_publickey_init ( resource $session ) : resource

Request the Publickey subsystem from an already connected SSH2 server.

The publickey subsystem allows an already connected and authenticated client to manage the list of authorized public keys stored on the target server in an implementation agnostic manner. If the remote server does not support the publickey subsystem, the ssh2_publickey_init() function will return FALSE.

Parameters

session

Return Values

Returns an SSH2 Publickey Subsystem resource for use with all other ssh2_publickey_*() methods or FALSE on failure.

Notes

Note: The public key subsystem is used for managing public keys on a server to which the client is already authenticated. To authenticate to a remote system using public key authentication, use the ssh2_auth_pubkey_file() function instead.

See Also

  • ssh2_publickey_add() - Add an authorized publickey
  • ssh2_publickey_remove() - Remove an authorized publickey
  • ssh2_publickey_list() - List currently authorized publickeys


List currently authorized publickeys

  • « ssh2_publickey_init
  • ssh2_publickey_remove »
  • PHP Manual
  • SSH2 Functions
  • List currently authorized publickeys

ssh2_publickey_list

(PECL ssh2 >= 0.10)

ssh2_publickey_list — List currently authorized publickeys

Description

ssh2_publickey_list ( resource $pkey ) : array

List currently authorized publickeys.

Parameters

pkey

Publickey Subsystem resource

Return Values

Returns a numerically indexed array of keys, each of which is an associative array containing: name, blob, and attrs elements.

Publickey elements
Array Key | Meaning
name | Name of algorithm used by this publickey, for example: ssh-dss or ssh-rsa.
blob | Publickey blob as raw binary data.
attrs | Attributes assigned to this publickey. The most common attribute, and the only one supported by publickey version 1 servers, is comment, which may be any freeform string.

Examples

Example #1 Listing authorized keys with ssh2_publickey_list()

<?php
$ssh2 = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($ssh2, 'jdoe', 'secret');
$pkey = ssh2_publickey_init($ssh2);

$list = ssh2_publickey_list($pkey);

foreach($list as $key) {
  echo "Key: {$key['name']}\n";
  echo "Blob: " . chunk_split(base64_encode($key['blob']), 40, "\n") . "\n";
  echo "Comment: {$key['attrs']['comment']}\n\n";
}
?>

The above example will output:

Key: ssh-rsa
Blob: AAAAB3NzaC1yc2EAAAABIwAAAIEA5HVt6VqSGd5P
TrLRdjNONxXH1tVFGn0Bd26BF0aCP9qyJRlvdJ3j
4WBeX4ZmrveGrjMgkseSYc4xZ26sDHwfL351xjza
Lpipu\BGRrw17mWVBhuCExo476ri5tQFzbTc54VE
HYckxQ16CjSTibI5X69GmnYC9PNqEYq/1TP+HF10
Comment: John's Key

Key: ssh-rsa
Blob: AAAAB3NzaHVt6VqSGd5C1yc2EAAAABIwA232dnJA
AIEA5HVt6VqSGd5PTrLRdjNONxX/1TP+HF1HVt6V
qSGd50H1tVFGn0BB3NzaC1yc2EAd26BF0aCP9qyJ
RlvdJ3j4WBeX4ZmrveGrjMgkseSYc4xZ26HVt6Vq
SGd5sDHwfL351xjzaLpipu\BGB3NzaC1yc2EA/1T
Comment: Alice's Key

Notes

Note: The public key subsystem is used for managing public keys on a server to which the client is already authenticated. To authenticate to a remote system using public key authentication, use the ssh2_auth_pubkey_file() function instead.

See Also

  • ssh2_publickey_init() - Initialize Publickey subsystem
  • ssh2_publickey_add() - Add an authorized publickey
  • ssh2_publickey_remove() - Remove an authorized publickey


Remove an authorized publickey

  • « ssh2_publickey_list
  • ssh2_scp_recv »
  • PHP Manual
  • SSH2 Functions
  • Remove an authorized publickey

ssh2_publickey_remove

(PECL ssh2 >= 0.10)

ssh2_publickey_remove — Remove an authorized publickey

Description

ssh2_publickey_remove ( resource $pkey , string $algoname , string $blob ) : bool

Removes an authorized publickey.

Parameters

pkey

Publickey Subsystem Resource

algoname

Publickey algorithm (e.g.): ssh-dss, ssh-rsa

blob

Publickey blob as raw binary data

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: The public key subsystem is used for managing public keys on a server to which the client is already authenticated. To authenticate to a remote system using public key authentication, use the ssh2_auth_pubkey_file() function instead.

See Also

  • ssh2_publickey_init() - Initialize Publickey subsystem
  • ssh2_publickey_add() - Add an authorized publickey
  • ssh2_publickey_list() - List currently authorized publickeys


Request a file via SCP

  • « ssh2_publickey_remove
  • ssh2_scp_send »
  • PHP Manual
  • SSH2 Functions
  • Request a file via SCP

ssh2_scp_recv

(PECL ssh2 >= 0.9.0)

ssh2_scp_recv — Request a file via SCP

Description

ssh2_scp_recv ( resource $session , string $remote_file , string $local_file ) : bool

Copy a file from the remote server to the local filesystem using the SCP protocol.

Parameters

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

remote_file

Path to the remote file.

local_file

Path to the local file.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Downloading a file via SCP

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

ssh2_scp_recv($connection, '/remote/filename', '/local/filename');
?>

See Also

  • ssh2_scp_send() - Send a file via SCP
  • copy() - Copies file


Send a file via SCP

  • « ssh2_scp_recv
  • ssh2_sftp_chmod »
  • PHP Manual
  • SSH2 Functions
  • Send a file via SCP

ssh2_scp_send

(PECL ssh2 >= 0.9.0)

ssh2_scp_send — Send a file via SCP

Description

ssh2_scp_send ( resource $session , string $local_file , string $remote_file [, int $create_mode = 0644 ] ) : bool

Copy a file from the local filesystem to the remote server using the SCP protocol.

Parameters

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

local_file

Path to the local file.

remote_file

Path to the remote file.

create_mode

The file will be created with the mode specified by create_mode.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Uploading a file via SCP

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

ssh2_scp_send($connection, '/local/filename', '/remote/filename', 0644);
?>

See Also

  • ssh2_scp_recv() - Request a file via SCP
  • copy() - Copies file


Changes file mode

  • « ssh2_scp_send
  • ssh2_sftp_lstat »
  • PHP Manual
  • SSH2 Functions
  • Changes file mode

ssh2_sftp_chmod

(PECL ssh2 >= 0.12)

ssh2_sftp_chmod — Changes file mode

Description

ssh2_sftp_chmod ( resource $sftp , string $filename , int $mode ) : bool

Attempts to change the mode of the specified file to that given in mode.

Parameters

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

filename

Path to the file.

mode

Permissions on the file. See the chmod() for more details on this parameter.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Changing the mode of a file on a remote server

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_chmod($sftp, '/somedir/somefile', 0755);
?>

See Also

  • chmod() - Changes file mode
  • ssh2_sftp() - Initialize SFTP subsystem
  • ssh2_connect() - Connect to an SSH server


Stat a symbolic link

  • « ssh2_sftp_chmod
  • ssh2_sftp_mkdir »
  • PHP Manual
  • SSH2 Functions
  • Stat a symbolic link

ssh2_sftp_lstat

(PECL ssh2 >= 0.9.0)

ssh2_sftp_lstat — Stat a symbolic link

Description

ssh2_sftp_lstat ( resource $sftp , string $path ) : array

Stats a symbolic link on the remote filesystem without following the link.

This function is similar to using the lstat() function with the ssh2.sftp:// wrapper in PHP 5 and returns the same values.

Parameters

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

path

Path to the remote symbolic link.

Return Values

See the documentation for stat() for details on the values which may be returned.

Examples

Example #1 Stating a symbolic link via SFTP

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$sftp = ssh2_sftp($connection);
$statinfo = ssh2_sftp_lstat($sftp, '/path/to/symlink');

$filesize = $statinfo['size'];
$group = $statinfo['gid'];
$owner = $statinfo['uid'];
$atime = $statinfo['atime'];
$mtime = $statinfo['mtime'];
$mode = $statinfo['mode'];
?>

See Also

  • ssh2_sftp_stat() - Stat a file on a remote filesystem
  • lstat() - Gives information about a file or symbolic link
  • stat() - Gives information about a file


Create a directory

  • « ssh2_sftp_lstat
  • ssh2_sftp_readlink »
  • PHP Manual
  • SSH2 Functions
  • Create a directory

ssh2_sftp_mkdir

(PECL ssh2 >= 0.9.0)

ssh2_sftp_mkdir — Create a directory

Description

ssh2_sftp_mkdir ( resource $sftp , string $dirname [, int $mode = 0777 [, bool $recursive = FALSE ]] ) : bool

Creates a directory on the remote file server with permissions set to mode.

This function is similar to using mkdir() with the ssh2.sftp:// wrapper.

Parameters

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

dirname

Path of the new directory.

mode

Permissions on the new directory.

recursive

If recursive is TRUE any parent directories required for dirname will be automatically created as well.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Creating a directory on a remote server

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_mkdir($sftp, '/home/username/newdir');
/* Or:  mkdir("ssh2.sftp://$sftp/home/username/newdir"); */
?>

See Also

  • mkdir() - Makes directory
  • ssh2_sftp_rmdir() - Remove a directory


Return the target of a symbolic link

  • « ssh2_sftp_mkdir
  • ssh2_sftp_realpath »
  • PHP Manual
  • SSH2 Functions
  • Return the target of a symbolic link

ssh2_sftp_readlink

(PECL ssh2 >= 0.9.0)

ssh2_sftp_readlink — Return the target of a symbolic link

Description

ssh2_sftp_readlink ( resource $sftp , string $link ) : string

Returns the target of a symbolic link.

Parameters

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

link

Path of the symbolic link.

Return Values

Returns the target of the symbolic link.

Examples

Example #1 Reading a symbolic link

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

$target = ssh2_sftp_readlink($sftp, '/tmp/mysql.sock');
/* $target is now (e.g.): '/var/run/mysql.sock' */
?>

See Also

  • readlink() - Returns the target of a symbolic link
  • ssh2_sftp_symlink() - Create a symlink


Resolve the realpath of a provided path string

  • « ssh2_sftp_readlink
  • ssh2_sftp_rename »
  • PHP Manual
  • SSH2 Functions
  • Resolve the realpath of a provided path string

ssh2_sftp_realpath

(PECL ssh2 >= 0.9.0)

ssh2_sftp_realpath — Resolve the realpath of a provided path string

Description

ssh2_sftp_realpath ( resource $sftp , string $filename ) : string

Translates filename into the effective real path on the remote filesystem.

Parameters

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

filename

Return Values

Returns the real path as a string.

Examples

Example #1 Resolving a pathname

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

$realpath = ssh2_sftp_realpath($sftp, '/home/username/../../../..//./usr/../etc/passwd');
/* $realpath is now: '/etc/passwd' */
?>

See Also

  • realpath() - Returns canonicalized absolute pathname
  • ssh2_sftp_symlink() - Create a symlink
  • ssh2_sftp_readlink() - Return the target of a symbolic link


Rename a remote file

  • « ssh2_sftp_realpath
  • ssh2_sftp_rmdir »
  • PHP Manual
  • SSH2 Functions
  • Rename a remote file

ssh2_sftp_rename

(PECL ssh2 >= 0.9.0)

ssh2_sftp_rename — Rename a remote file

Description

ssh2_sftp_rename ( resource $sftp , string $from , string $to ) : bool

Renames a file on the remote filesystem.

Parameters

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

from

The current file that is being renamed.

to

The new file name that replaces from.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Renaming a file via sftp

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_rename($sftp, '/home/username/oldname', '/home/username/newname');
?>

See Also

  • rename() - Renames a file or directory


Remove a directory

  • « ssh2_sftp_rename
  • ssh2_sftp_stat »
  • PHP Manual
  • SSH2 Functions
  • Remove a directory

ssh2_sftp_rmdir

(PECL ssh2 >= 0.9.0)

ssh2_sftp_rmdir — Remove a directory

Description

ssh2_sftp_rmdir ( resource $sftp , string $dirname ) : bool

Removes a directory from the remote file server.

This function is similar to using rmdir() with the ssh2.sftp:// wrapper.

Parameters

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

dirname

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Removing a directory on a remote server

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_rmdir($sftp, '/home/username/deltodel');
/* Or:  rmdir("ssh2.sftp://$sftp/home/username/dirtodel"); */
?>

See Also

  • rmdir() - Removes directory
  • ssh2_sftp_mkdir() - Create a directory


Stat a file on a remote filesystem

  • « ssh2_sftp_rmdir
  • ssh2_sftp_symlink »
  • PHP Manual
  • SSH2 Functions
  • Stat a file on a remote filesystem

ssh2_sftp_stat

(PECL ssh2 >= 0.9.0)

ssh2_sftp_stat — Stat a file on a remote filesystem

Description

ssh2_sftp_stat ( resource $sftp , string $path ) : array

Stats a file on the remote filesystem following any symbolic links.

This function is similar to using the stat() function with the ssh2.sftp:// wrapper in PHP 5 and returns the same values.

Parameters

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

path

Return Values

See the documentation for stat() for details on the values which may be returned.

Examples

Example #1 Stating a file via SFTP

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$sftp = ssh2_sftp($connection);
$statinfo = ssh2_sftp_stat($sftp, '/path/to/file');

$filesize = $statinfo['size'];
$group = $statinfo['gid'];
$owner = $statinfo['uid'];
$atime = $statinfo['atime'];
$mtime = $statinfo['mtime'];
$mode = $statinfo['mode'];
?>

See Also

  • ssh2_sftp_lstat() - Stat a symbolic link
  • lstat() - Gives information about a file or symbolic link
  • stat() - Gives information about a file


Create a symlink

  • « ssh2_sftp_stat
  • ssh2_sftp_unlink »
  • PHP Manual
  • SSH2 Functions
  • Create a symlink

ssh2_sftp_symlink

(PECL ssh2 >= 0.9.0)

ssh2_sftp_symlink — Create a symlink

Description

ssh2_sftp_symlink ( resource $sftp , string $target , string $link ) : bool

Creates a symbolic link named link on the remote filesystem pointing to target.

Parameters

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

target

Target of the symbolic link.

link

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Creating a symbolic link

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_symlink($sftp, '/var/run/mysql.sock', '/tmp/mysql.sock');
?>

See Also

  • ssh2_sftp_readlink() - Return the target of a symbolic link
  • symlink() - Creates a symbolic link


Delete a file

  • « ssh2_sftp_symlink
  • ssh2_sftp »
  • PHP Manual
  • SSH2 Functions
  • Delete a file

ssh2_sftp_unlink

(PECL ssh2 >= 0.9.0)

ssh2_sftp_unlink — Delete a file

Description

ssh2_sftp_unlink ( resource $sftp , string $filename ) : bool

Deletes a file on the remote filesystem.

Parameters

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

filename

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Deleting a file

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_unlink($sftp, '/home/username/stale_file');
?>

See Also

  • unlink() - Deletes a file


Initialize SFTP subsystem

  • « ssh2_sftp_unlink
  • ssh2_shell »
  • PHP Manual
  • SSH2 Functions
  • Initialize SFTP subsystem

ssh2_sftp

(PECL ssh2 >= 0.9.0)

ssh2_sftp — Initialize SFTP subsystem

Description

ssh2_sftp ( resource $session ) : resource

Request the SFTP subsystem from an already connected SSH2 server.

Parameters

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

Return Values

This method returns an SSH2 SFTP resource for use with all other ssh2_sftp_*() methods and the ssh2.sftp:// fopen wrapper, or FALSE on failure.

Examples

Example #1 Opening a file via SFTP

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$sftp = ssh2_sftp($connection);

$stream = fopen('ssh2.sftp://' . intval($sftp) . '/path/to/file', 'r');
?>

See Also

  • ssh2_scp_recv() - Request a file via SCP
  • ssh2_scp_send() - Send a file via SCP


Request an interactive shell

  • « ssh2_sftp
  • ssh2_tunnel »
  • PHP Manual
  • SSH2 Functions
  • Request an interactive shell

ssh2_shell

(PECL ssh2 >= 0.9.0)

ssh2_shell — Request an interactive shell

Description

ssh2_shell ( resource $session [, string $term_type = "vanilla" [, array $env [, int $width = 80 [, int $height = 25 [, int $width_height_type = SSH2_TERM_UNIT_CHARS ]]]]] ) : resource

Open a shell at the remote end and allocate a stream for it.

Parameters

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

term_type

term_type should correspond to one of the entries in the target system's /etc/termcap file.

env

env may be passed as an associative array of name/value pairs to set in the target environment.

width

Width of the virtual terminal.

height

Height of the virtual terminal.

width_height_type

width_height_type should be one of SSH2_TERM_UNIT_CHARS or SSH2_TERM_UNIT_PIXELS.

Return Values

Examples

Example #1 Requesting an interactive shell

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$stream = ssh2_shell($connection, 'vt102', null, 80, 24, SSH2_TERM_UNIT_CHARS);
?>

See Also

  • ssh2_exec() - Execute a command on a remote server
  • ssh2_tunnel() - Open a tunnel through a remote server
  • ssh2_fetch_stream() - Fetch an extended data stream


Open a tunnel through a remote server

  • « ssh2_shell
  • Stomp »
  • PHP Manual
  • SSH2 Functions
  • Open a tunnel through a remote server

ssh2_tunnel

(PECL ssh2 >= 0.9.0)

ssh2_tunnel — Open a tunnel through a remote server

Description

ssh2_tunnel ( resource $session , string $host , int $port ) : resource

Open a socket stream to an arbitrary host/port by way of the currently connected SSH server.

Parameters

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

host

port

Return Values

Examples

Example #1 Opening a tunnel to an arbitrary host

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_pubkey_file($connection, 'username', 'id_dsa.pub', 'id_dsa');

$tunnel = ssh2_tunnel($connection, '10.0.0.101', 12345);
?>

See Also

  • ssh2_connect() - Connect to an SSH server
  • fsockopen() - Open Internet or Unix domain socket connection


Stomp Client

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Examples
  • Stomp Functions
    • stomp_connect_error — Returns a string description of the last connect error
    • stomp_version — Gets the current stomp extension version
  • Stomp — The Stomp class
    • Stomp::abort — Rolls back a transaction in progress
    • Stomp::ack — Acknowledges consumption of a message
    • Stomp::begin — Starts a transaction
    • Stomp::commit — Commits a transaction in progress
    • Stomp::__construct — Opens a connection
    • Stomp::__destruct — Closes stomp connection
    • Stomp::error — Gets the last stomp error
    • Stomp::getReadTimeout — Gets read timeout
    • Stomp::getSessionId — Gets the current stomp session ID
    • Stomp::hasFrame — Indicates whether or not there is a frame ready to read
    • Stomp::readFrame — Reads the next frame
    • Stomp::send — Sends a message
    • Stomp::setReadTimeout — Sets read timeout
    • Stomp::subscribe — Registers to listen to a given destination
    • Stomp::unsubscribe — Removes an existing subscription
  • StompFrame — The StompFrame class
    • StompFrame::__construct — Constructor
  • StompException — The StompException class
    • StompException::getDetails — Get exception details


Introduction

This extension allows php applications to communicate with any Stomp compliant Message Brokers through easy object oriented and procedural interfaces. » Stomp official site


Requirements

PECL/stomp requires PHP 5.2.2 or newer.

The » OpenSSL package >= 0.9.6 and the openssl extension may also be required to use stomp over SSL.


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/stomp


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Stomp Configure Options
Name | Default | Changeable | Changelog
stomp.default_broker | tcp://localhost:61613 | PHP_INI_ALL |
stomp.default_connection_timeout_sec | 2 | PHP_INI_ALL |
stomp.default_connection_timeout_usec | 0 | PHP_INI_ALL |
stomp.default_read_timeout_sec | 2 | PHP_INI_ALL |
stomp.default_read_timeout_usec | 0 | PHP_INI_ALL |

Here's a short explanation of the configuration directives.

stomp.default_broker string

The default broker URI to use when connecting to the message broker if no other URI is specified.

stomp.default_connection_timeout_sec integer

The seconds part of the default connection timeout.

stomp.default_connection_timeout_usec integer

The microseconds part of the default connection timeout.

stomp.default_read_timeout_sec integer

The seconds part of the default reading timeout.

stomp.default_read_timeout_usec integer

The microseconds part of the default reading timeout.


Resource Types

There is only one resource type used in the stomp extension - it's the link identifier for a stomp connection.


Examples

Example #1 Object oriented style

<?php

$queue  = '/queue/foo';
$msg    = 'bar';

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

/* send a message to the queue 'foo' */
$stomp->send($queue, $msg);

/* subscribe to messages from the queue 'foo' */
$stomp->subscribe($queue);

/* read a frame */
$frame = $stomp->readFrame();

if ($frame->body === $msg) {
    var_dump($frame);

    /* acknowledge that the frame was received */
    $stomp->ack($frame);
}

/* close connection */
unset($stomp);

?>

The above example will output something similar to:

object(StompFrame)#2 (3) {
  ["command"]=>
  string(7) "MESSAGE"
  ["headers"]=>
  array(5) {
    ["message-id"]=>
    string(41) "ID:php.net-55293-1257226743606-4:2:-1:1:1"
    ["destination"]=>
    string(10) "/queue/foo"
    ["timestamp"]=>
    string(13) "1257226805828"
    ["expires"]=>
    string(1) "0"
    ["priority"]=>
    string(1) "0"
  }
  ["body"]=>
  string(3) "bar"
}

Example #2 Procedural style

<?php

$queue  = '/queue/foo';
$msg    = 'bar';

/* connection */
$link = stomp_connect('ssl://localhost:61612');

/* check connection */
if (!$link) {
    die('Connection failed: ' . stomp_connect_error());
}

/* begin a transaction */
stomp_begin($link, 't1');

/* send a message to the queue 'foo' */
stomp_send($link, $queue, $msg, array('transaction' => 't1'));

/* commit a transaction */
stomp_commit($link, 't1');

/* subscribe to messages from the queue 'foo' */
stomp_subscribe($link, $queue);

/* read a frame */
$frame = stomp_read_frame($link);

if ($frame['body'] === $msg) {
    var_dump($frame);

    /* acknowledge that the frame was received */
    stomp_ack($link, $frame['headers']['message-id']);
}

/* close connection */
stomp_close($link);

?>

The above example will output something similar to:

array(3) {
  ["command"]=>
  string(7) "MESSAGE"
  ["body"]=>
  string(3) "bar"
  ["headers"]=>
  array(6) {
    ["transaction"]=>
    string(2) "t1"
    ["message-id"]=>
    string(41) "ID:php.net-55293-1257226743606-4:3:-1:1:1"
    ["destination"]=>
    string(10) "/queue/foo"
    ["timestamp"]=>
    string(13) "1257227037059"
    ["expires"]=>
    string(1) "0"
    ["priority"]=>
    string(1) "0"
  }
}


Stomp Functions

Table of Contents

  • stomp_connect_error — Returns a string description of the last connect error
  • stomp_version — Gets the current stomp extension version


Returns a string description of the last connect error

  • « Stomp Functions
  • stomp_version »
  • PHP Manual
  • Stomp Functions
  • Returns a string description of the last connect error

stomp_connect_error

(PECL stomp >= 0.3.0)

stomp_connect_error — Returns a string description of the last connect error

Description

stomp_connect_error ( void ) : string

Returns a string description of the last connect error.

Parameters

This function has no parameters.

Return Values

A string that describes the error, or NULL if no error occurred.

Examples

Example #1 stomp_connect_error() example

<?php
$link = stomp_connect('http://localhost:61613');

if(!$link) {
    die('Connection failed: ' . stomp_connect_error());
}
?>

The above example will output something similar to:

Connection failed: Invalid Broker URI scheme


Gets the current stomp extension version

  • « stomp_connect_error
  • Stomp »
  • PHP Manual
  • Stomp Functions
  • Gets the current stomp extension version

stomp_version

(PECL stomp >= 0.1.0)

stomp_version — Gets the current stomp extension version

Description

stomp_version ( void ) : string

Returns a string containing the version of the current stomp extension.

Parameters

This function has no parameters.

Return Values

It returns the current stomp extension version

Examples

Example #1 stomp_version() example

<?php

var_dump(stomp_version());

?>

The above example will output something similar to:

string(5) "0.2.0"


The Stomp class

(PECL stomp >= 0.1.0)

Introduction

Represents a connection between PHP and a Stomp compliant Message Broker.

Class synopsis

Stomp {
/* Methods */
public abort ( string $transaction_id [, array $headers ] ) : bool
public ack ( mixed $msg [, array $headers ] ) : bool
public begin ( string $transaction_id [, array $headers ] ) : bool
public commit ( string $transaction_id [, array $headers ] ) : bool
public __construct ([ string $broker = ini_get("stomp.default_broker_uri") [, string $username [, string $password [, array $headers ]]]] )
public __destruct ( void ) : bool
public error ( void ) : string
public getReadTimeout ( void ) : array
public getSessionId ( void ) : string
public hasFrame ( void ) : bool
public readFrame ([ string $class_name = "stompFrame" ] ) : stompframe
public send ( string $destination , mixed $msg [, array $headers ] ) : bool
public setReadTimeout ( int $seconds [, int $microseconds ] ) : void
public subscribe ( string $destination [, array $headers ] ) : bool
public unsubscribe ( string $destination [, array $headers ] ) : bool
}

Table of Contents

  • Stomp::abort — Rolls back a transaction in progress
  • Stomp::ack — Acknowledges consumption of a message
  • Stomp::begin — Starts a transaction
  • Stomp::commit — Commits a transaction in progress
  • Stomp::__construct — Opens a connection
  • Stomp::__destruct — Closes stomp connection
  • Stomp::error — Gets the last stomp error
  • Stomp::getReadTimeout — Gets read timeout
  • Stomp::getSessionId — Gets the current stomp session ID
  • Stomp::hasFrame — Indicates whether or not there is a frame ready to read
  • Stomp::readFrame — Reads the next frame
  • Stomp::send — Sends a message
  • Stomp::setReadTimeout — Sets read timeout
  • Stomp::subscribe — Registers to listen to a given destination
  • Stomp::unsubscribe — Removes an existing subscription


Rolls back a transaction in progress

  • « Stomp
  • Stomp::ack »
  • PHP Manual
  • Stomp
  • Rolls back a transaction in progress

Stomp::abort

stomp_abort

(PECL stomp >= 0.1.0)

Stomp::abort -- stomp_abort — Rolls back a transaction in progress

Description

Object oriented style (method):

public Stomp::abort ( string $transaction_id [, array $headers ] ) : bool

Procedural style:

stomp_abort ( resource $link , string $transaction_id [, array $headers ] ) : bool

Rolls back a transaction in progress.

Parameters

link

Procedural style only: The stomp link identifier returned by stomp_connect().

transaction_id

The transaction to abort.

headers

Associative array containing the additional headers (example: receipt).

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Tip

Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached.

Examples

Example #1 Object oriented style

<?php

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

/* begin a transaction */
$stomp->begin('t1');

/* send a message to the queue */
$stomp->send('/queue/foo', 'bar', array('transaction' => 't1'));

/* rollback */
$stomp->abort('t1');

/* close connection */
unset($stomp);
?>

Example #2 Procedural style

<?php

/* connection */
$link = stomp_connect('tcp://localhost:61613');

/* check connection */
if (!$link) {
    die('Connection failed: ' . stomp_connect_error());
}

/* begin a transaction */
stomp_begin($link, 't1');

/* send a message to the queue 'foo' */
stomp_send($link, '/queue/foo', 'bar', array('transaction' => 't1'));

/* rollback */
stomp_abort($link, 't1');

/* close connection */
stomp_close($link);

?>


Acknowledges consumption of a message

  • « Stomp::abort
  • Stomp::begin »
  • PHP Manual
  • Stomp
  • Acknowledges consumption of a message

Stomp::ack

stomp_ack

(PECL stomp >= 0.1.0)

Stomp::ack -- stomp_ack — Acknowledges consumption of a message

Description

Object oriented style (method):

public Stomp::ack ( mixed $msg [, array $headers ] ) : bool

Procedural style:

stomp_ack ( resource $link , mixed $msg [, array $headers ] ) : bool

Acknowledges consumption of a message from a subscription using client acknowledgment.

Parameters

link

Procedural style only: The stomp link identifier returned by stomp_connect().

msg

The message/messageId to be acknowledged.

headers

Associative array containing the additional headers (example: receipt).

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note:

A transaction header may be specified, indicating that the message acknowledgment should be part of the named transaction.

Tip

Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached.

Examples

Example #1 Object oriented style

<?php

$queue  = '/queue/foo';
$msg    = 'bar';

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

/* send a message to the queue 'foo' */
$stomp->send($queue, $msg);

/* subscribe to messages from the queue 'foo' */
$stomp->subscribe($queue);

/* read a frame */
$frame = $stomp->readFrame();

if ($frame->body === $msg) {
    /* acknowledge that the frame was received */
    $stomp->ack($frame);
}

/* remove the subscription */
$stomp->unsubscribe($queue);

/* close connection */
unset($stomp);

?>

Example #2 Procedural style

<?php

$queue  = '/queue/foo';
$msg    = 'bar';

/* connection */
$link = stomp_connect('ssl://localhost:61612');

/* check connection */
if (!$link) {
    die('Connection failed: ' . stomp_connect_error());
}

/* begin a transaction */
stomp_begin($link, 't1');

/* send a message to the queue 'foo' */
stomp_send($link, $queue, $msg, array('transaction' => 't1'));

/* commit a transaction */
stomp_commit($link, 't1');

/* subscribe to messages from the queue 'foo' */
stomp_subscribe($link, $queue);

/* read a frame */
$frame = stomp_read_frame($link);

if ($frame['body'] === $msg) {
    /* acknowledge that the frame was received */
    stomp_ack($link, $frame['headers']['message-id']);
}

/* remove the subscription */
stomp_unsubscribe($link, $queue);

/* close connection */
stomp_close($link);

?>


Starts a transaction

  • « Stomp::ack
  • Stomp::commit »
  • PHP Manual
  • Stomp
  • Starts a transaction

Stomp::begin

stomp_begin

(PECL stomp >= 0.1.0)

Stomp::begin -- stomp_begin — Starts a transaction

Description

Object oriented style (method):

public Stomp::begin ( string $transaction_id [, array $headers ] ) : bool

Procedural style:

stomp_begin ( resource $link , string $transaction_id [, array $headers ] ) : bool

Starts a transaction.

Parameters

link

Procedural style only: The stomp link identifier returned by stomp_connect().

transaction_id

The transaction id.

headers

Associative array containing the additional headers (example: receipt).

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Tip

Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached.

Examples

See stomp_commit() or stomp_abort().


Commits a transaction in progress

  • « Stomp::begin
  • Stomp::__construct »
  • PHP Manual
  • Stomp
  • Commits a transaction in progress

Stomp::commit

stomp_commit

(PECL stomp >= 0.1.0)

Stomp::commit -- stomp_commit — Commits a transaction in progress

Description

Object oriented style (method):

public Stomp::commit ( string $transaction_id [, array $headers ] ) : bool

Procedural style:

stomp_commit ( resource $link , string $transaction_id [, array $headers ] ) : bool

Commits a transaction in progress.

Parameters

link

Procedural style only: The stomp link identifier returned by stomp_connect().

transaction_id

The transaction id.

headers

Associative array containing the additional headers (example: receipt).

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Tip

Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached.

Examples

Example #1 Object oriented style

<?php

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

/* begin a transaction */
$stomp->begin('t1');

/* send a message to the queue */
$stomp->send('/queue/foo', 'bar', array('transaction' => 't1'));

/* commit */
$stomp->commit('t1');

/* close connection */
unset($stomp);

?>

Example #2 Procedural style

<?php

/* connection */
$link = stomp_connect('tcp://localhost:61613');

/* check connection */
if (!$link) {
    die('Connection failed: ' . stomp_connect_error());
}

/* begin a transaction */
stomp_begin($link, 't1');

/* send a message to the queue 'foo' */
stomp_send($link, '/queue/foo', 'bar', array('transaction' => 't1'));

/* commit */
stomp_commit($link, 't1');

/* close connection */
stomp_close($link);

?>


Opens a connection

  • « Stomp::commit
  • Stomp::__destruct »
  • PHP Manual
  • Stomp
  • Opens a connection

Stomp::__construct

stomp_connect

(PECL stomp >= 0.1.0)

Stomp::__construct -- stomp_connect — Opens a connection

Description

Object oriented style (constructor):

public Stomp::__construct ([ string $broker = ini_get("stomp.default_broker_uri") [, string $username [, string $password [, array $headers ]]]] )

Procedural style:

stomp_connect ([ string $broker = ini_get("stomp.default_broker_uri") [, string $username [, string $password [, array $headers ]]]] ) : resource

Opens a connection to a stomp compliant Message Broker.

Parameters

broker

The broker URI

username

The username.

password

The password.

headers

Associative array containing the additional headers (example: receipt).

Return Values

Note:

A transaction header may be specified, indicating that the message acknowledgment should be part of the named transaction.

Changelog

Version | Description
1.0.1 | The headers parameter was added

Examples

Example #1 Object oriented style

<?php

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

/* close connection */
unset($stomp);

?>

Example #2 Procedural style

<?php

/* connection */
$link = stomp_connect('ssl://localhost:61612');

/* check connection */
if (!$link) {
    die('Connection failed: ' . stomp_connect_error());
}

/* close connection */
stomp_close($link);

?>


Closes stomp connection

  • « Stomp::__construct
  • Stomp::error »
  • PHP Manual
  • Stomp
  • Closes stomp connection

Stomp::__destruct

stomp_close

(PECL stomp >= 0.1.0)

Stomp::__destruct -- stomp_close — Closes stomp connection

Description

Object oriented style (destructor):

public Stomp::__destruct ( void ) : bool

Procedural style:

stomp_close ( resource $link ) : bool

Closes a previously opened connection.

Parameters

link

Procedural style only: The stomp link identifier returned by stomp_connect().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

See stomp_connect().


Gets the last stomp error

  • « Stomp::__destruct
  • Stomp::getReadTimeout »
  • PHP Manual
  • Stomp
  • Gets the last stomp error

Stomp::error

stomp_error

(PECL stomp >= 0.1.0)

Stomp::error -- stomp_error — Gets the last stomp error

Description

Object oriented style (method):

public Stomp::error ( void ) : string

Procedural style:

stomp_error ( resource $link ) : string

Gets the last stomp error.

Parameters

link

Procedural style only: The stomp link identifier returned by stomp_connect().

Return Values

Returns an error string or FALSE if no error occurred.

Examples

Example #1 Object oriented style

<?php

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

var_dump($stomp->error());

if (!$stomp->abort('unknown-transaction', array('receipt' => 'foo'))) {
    var_dump($stomp->error());
}

/* close connection */
unset($stomp);

?>

The above example will output something similar to:

bool(false)
string(43) "Invalid transaction id: unknown-transaction"

Example #2 Procedural style

<?php

/* connection */
$link = stomp_connect('ssl://localhost:61612');

/* check connection */
if (!$link) {
    die('Connection failed: ' . stomp_connect_error());
}

var_dump(stomp_error($link));

if (!stomp_abort($link, 'unknown-transaction', array('receipt' => 'foo'))) {
    var_dump(stomp_error($link));
}

/* close connection */
stomp_close($link);

?>

The above example will output something similar to:

bool(false)
string(43) "Invalid transaction id: unknown-transaction"


Gets read timeout

  • « Stomp::error
  • Stomp::getSessionId »
  • PHP Manual
  • Stomp
  • Gets read timeout

Stomp::getReadTimeout

stomp_get_read_timeout

(PECL stomp >= 0.3.0)

Stomp::getReadTimeout -- stomp_get_read_timeout — Gets read timeout

Description

Object oriented style (method):

public Stomp::getReadTimeout ( void ) : array

Procedural style:

stomp_get_read_timeout ( resource $link ) : array

Gets read timeout

Parameters

link

Procedural style only: The stomp link identifier returned by stomp_connect().

Return Values

Returns an array with 2 elements: sec and usec.

Examples

Example #1 Object oriented style

<?php

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

var_dump($stomp->getReadTimeout());

/* close connection */
unset($stomp);

?>

The above example will output something similar to:

array(2) {
  ["sec"]=>
  int(2)
  ["usec"]=>
  int(0)
}

Example #2 Procedural style

<?php

/* connection */
$link = stomp_connect('ssl://localhost:61612');

/* check connection */
if (!$link) {
    die('Connection failed: ' . stomp_connect_error());
}

var_dump(stomp_get_read_timeout($link));

/* close connection */
stomp_close($link);

?>

The above example will output something similar to:

array(2) {
  ["sec"]=>
  int(2)
  ["usec"]=>
  int(0)
}


Gets the current stomp session ID

  • « Stomp::getReadTimeout
  • Stomp::hasFrame »
  • PHP Manual
  • Stomp
  • Gets the current stomp session ID

Stomp::getSessionId

stomp_get_session_id

(PECL stomp >= 0.1.0)

Stomp::getSessionId -- stomp_get_session_id — Gets the current stomp session ID

Description

Object oriented style (method):

public Stomp::getSessionId ( void ) : string

Procedural style:

stomp_get_session_id ( resource $link ) : string

Gets the current stomp session ID.

Parameters

link

Procedural style only: The stomp link identifier returned by stomp_connect().

Return Values

string session id on success or FALSE on failure.

Examples

Example #1 Object oriented style

<?php

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

var_dump($stomp->getSessionId());

/* close connection */
unset($stomp);

?>

The above example will output something similar to:

string(35) "ID:php.net-52873-1257291895530-4:14"

Example #2 Procedural style

<?php

/* connection */
$link = stomp_connect('ssl://localhost:61612');

/* check connection */
if (!$link) {
    die('Connection failed: ' . stomp_connect_error());
}

var_dump(stomp_get_session_id($link));

/* close connection */
stomp_close($link);

?>

The above example will output something similar to:

string(35) "ID:php.net-52873-1257291895530-4:14"


Indicates whether or not there is a frame ready to read

  • « Stomp::getSessionId
  • Stomp::readFrame »
  • PHP Manual
  • Stomp
  • Indicates whether or not there is a frame ready to read

Stomp::hasFrame

stomp_has_frame

(PECL stomp >= 0.1.0)

Stomp::hasFrame -- stomp_has_frame — Indicates whether or not there is a frame ready to read

Description

Object oriented style (method):

public Stomp::hasFrame ( void ) : bool

Procedural style:

stomp_has_frame ( resource $link ) : bool

Indicates whether or not there is a frame ready to read.

Parameters

link

Procedural style only: The stomp link identifier returned by stomp_connect().

Return Values

Returns TRUE if a frame is ready to read, or FALSE otherwise.


Reads the next frame

  • « Stomp::hasFrame
  • Stomp::send »
  • PHP Manual
  • Stomp
  • Reads the next frame

Stomp::readFrame

stomp_read_frame

(PECL stomp >= 0.1.0)

Stomp::readFrame -- stomp_read_frame — Reads the next frame

Description

Object oriented style (method):

public Stomp::readFrame ([ string $class_name = "stompFrame" ] ) : stompframe

Procedural style:

stomp_read_frame ( resource $link ) : array

Reads the next frame. It is possible to instantiate an object of a specific class, and pass parameters to that class's constructor.

Parameters

link

Procedural style only: The stomp link identifier returned by stomp_connect().

class_name

The name of the class to instantiate. If not specified, a stompFrame object is returned.

Return Values

Note:

A transaction header may be specified, indicating that the message acknowledgment should be part of the named transaction.

Changelog

Version | Description
Stomp 0.4.0 | class_name parameter was added.

Examples

Example #1 Object oriented style

<?php

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

/* subscribe to messages from the queue 'foo' */
$stomp->subscribe('/queue/foo');

/* read a frame */
var_dump($stomp->readFrame());

/* close connection */
unset($stomp);

?>

The above example will output something similar to:

object(StompFrame)#2 (3) {
  ["command"]=>
  string(7) "MESSAGE"
  ["headers"]=>
  array(5) {
    ["message-id"]=>
    string(41) "ID:php.net-55293-1257226743606-4:2:-1:1:1"
    ["destination"]=>
    string(10) "/queue/foo"
    ["timestamp"]=>
    string(13) "1257226805828"
    ["expires"]=>
    string(1) "0"
    ["priority"]=>
    string(1) "0"
  }
  ["body"]=>
  string(3) "bar"
}

Example #2 Procedural style

<?php

/* connection */
$link = stomp_connect('ssl://localhost:61612');

/* check connection */
if (!$link) {
    die('Connection failed: ' . stomp_connect_error());
}

/* subscribe to messages from the queue 'foo' */
stomp_subscribe($link, '/queue/foo');

/* read a frame */
$frame = stomp_read_frame($link);

/* close connection */
stomp_close($link);

?>

The above example will output something similar to:

array(3) {
  ["command"]=>
  string(7) "MESSAGE"
  ["body"]=>
  string(3) "bar"
  ["headers"]=>
  array(6) {
    ["transaction"]=>
    string(2) "t1"
    ["message-id"]=>
    string(41) "ID:php.net-55293-1257226743606-4:3:-1:1:1"
    ["destination"]=>
    string(10) "/queue/foo"
    ["timestamp"]=>
    string(13) "1257227037059"
    ["expires"]=>
    string(1) "0"
    ["priority"]=>
    string(1) "0"
  }
}


Sends a message

  • « Stomp::readFrame
  • Stomp::setReadTimeout »
  • PHP Manual
  • Stomp
  • Sends a message

Stomp::send

stomp_send

(PECL stomp >= 0.1.0)

Stomp::send -- stomp_send — Sends a message

Description

Object oriented style (method):

public Stomp::send ( string $destination , mixed $msg [, array $headers ] ) : bool

Procedural style:

stomp_send ( resource $link , string $destination , mixed $msg [, array $headers ] ) : bool

Sends a message to the Message Broker.

Parameters

link

Procedural style only: The stomp link identifier returned by stomp_connect().

destination

Where to send the message

msg

Message to send.

headers

Associative array containing the additional headers (example: receipt).

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note:

A transaction header may be specified, indicating that the message acknowledgment should be part of the named transaction.

Tip

Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached.

Examples

See stomp_ack().


Sets read timeout

  • « Stomp::send
  • Stomp::subscribe »
  • PHP Manual
  • Stomp
  • Sets read timeout

Stomp::setReadTimeout

stomp_set_read_timeout

(PECL stomp >= 0.3.0)

Stomp::setReadTimeout -- stomp_set_read_timeout — Sets read timeout

Description

Object oriented style (method):

public Stomp::setReadTimeout ( int $seconds [, int $microseconds ] ) : void

Procedural style:

stomp_set_read_timeout ( resource $link , int $seconds [, int $microseconds ] ) : void

Sets read timeout.

Parameters

link

Procedural style only: The stomp link identifier returned by stomp_connect().

seconds

The seconds part of the timeout to be set.

microseconds

The microseconds part of the timeout to be set.

Examples

Example #1 Object oriented style

<?php

/* connection */
try {
    $stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

$stomp->setReadTimeout(10);

/* close connection */
unset($stomp);

?>

Example #2 Procedural style

<?php

/* connection */
$link = stomp_connect('ssl://localhost:61612');

/* check connection */
if (!$link) {
    die('Connection failed: ' . stomp_connect_error());
}

stomp_set_read_timeout($link, 10);

/* close connection */
stomp_close($link);

?>


Registers to listen to a given destination

  • « Stomp::setReadTimeout
  • Stomp::unsubscribe »
  • PHP Manual
  • Stomp
  • Registers to listen to a given destination

Stomp::subscribe

stomp_subscribe

(PECL stomp >= 0.1.0)

Stomp::subscribe -- stomp_subscribe — Registers to listen to a given destination

Description

Object oriented style (method):

public Stomp::subscribe ( string $destination [, array $headers ] ) : bool

Procedural style:

stomp_subscribe ( resource $link , string $destination [, array $headers ] ) : bool

Registers to listen to a given destination.

Parameters

link

Procedural style only: The stomp link identifier returned by stomp_connect().

destination

Destination to subscribe to.

headers

Associative array containing the additional headers (example: receipt).

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Tip

Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached.

Examples

See stomp_ack().


Removes an existing subscription

  • « Stomp::subscribe
  • StompFrame »
  • PHP Manual
  • Stomp
  • Removes an existing subscription

Stomp::unsubscribe

stomp_unsubscribe

(PECL stomp >= 0.1.0)

Stomp::unsubscribe -- stomp_unsubscribe — Removes an existing subscription

Description

Object oriented style (method):

public Stomp::unsubscribe ( string $destination [, array $headers ] ) : bool

Procedural style:

stomp_unsubscribe ( resource $link , string $destination [, array $headers ] ) : bool

Removes an existing subscription.

Parameters

link

Procedural style only: The stomp link identifier returned by stomp_connect().

destination

Subscription to remove.

headers

Associative array containing the additional headers (example: receipt).

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Tip

Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached.

Examples

See stomp_ack().


The StompFrame class

(PECL stomp >= 0.1.0)

Introduction

Represents a message which was sent or received from a Stomp compliant Message Broker.

Class synopsis

StompFrame {
/* Properties */
public $command ;
public $headers ;
public $body ;
/* Methods */
__construct ([ string $command [, array $headers [, string $body ]]] )
}

Properties

command

Frame command.

headers

Frame headers (array).

body

Frame body.

Table of Contents

  • StompFrame::__construct — Constructor


Constructor

  • « StompFrame
  • StompException »
  • PHP Manual
  • StompFrame
  • Constructor

StompFrame::__construct

(PECL stomp >= 0.1.0)

StompFrame::__construct — Constructor

Description

StompFrame::__construct ([ string $command [, array $headers [, string $body ]]] )

Constructor.

Parameters

command

Frame command

headers

Frame headers (array).

body

Frame body.


The StompException class

(PECL stomp >= 0.1.0)

Introduction

Represents an error raised by the stomp extension. See Exceptions for more information about Exceptions in PHP.

Class synopsis

StompException extends Exception {
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
/* Methods */
public getDetails ( void ) : string
}

Table of Contents

  • StompException::getDetails — Get exception details


Get exception details

  • « StompException
  • SVM »
  • PHP Manual
  • StompException
  • Get exception details

StompException::getDetails

(PECL stomp >= 0.1.0)

StompException::getDetails — Get exception details

Description

public StompException::getDetails ( void ) : string

Get exception details.

Return Values

string containing the error details.


Support Vector Machine

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Examples
  • SVM — The SVM class
    • SVM::__construct — Construct a new SVM object
    • SVM::crossvalidate — Test training params on subsets of the training data
    • SVM::getOptions — Return the current training parameters
    • SVM::setOptions — Set training parameters
    • SVM::train — Create a SVMModel based on training data
  • SVMModel — The SVMModel class
    • SVMModel::checkProbabilityModel — Returns true if the model has probability information
    • SVMModel::__construct — Construct a new SVMModel
    • SVMModel::getLabels — Get the labels the model was trained on
    • SVMModel::getNrClass — Returns the number of classes the model was trained with
    • SVMModel::getSvmType — Get the SVM type the model was trained with
    • SVMModel::getSvrProbability — Get the sigma value for regression types
    • SVMModel::load — Load a saved SVM Model
    • SVMModel::predict_probability — Return class probabilities for previous unseen data
    • SVMModel::predict — Predict a value for previously unseen data
    • SVMModel::save — Save a model to a file


Introduction

LibSVM is an efficient solver for SVM classification and regression problems. The svm extension wraps this in a PHP interface for easy use in PHP scripts.


Requirements

Libsvm itself is required, and is available through some package management - libsvm-devel for RPM based system or libsvm-dev for Debian based ones. Alternatively it is available direct from the website. If installing from the » official website then some steps will need to be taken as the package does not install automatically. For example, assuming the latest version is 3.1:

wget http://www.csie.ntu.edu.tw/~cjlin/cgi-bin/libsvm.cgi?+http://www.csie.ntu.edu.tw/~cjlin/libsvm+tar.gz
tar xvzf libsvm-3.1.tar.gz
cd libsvm-3.1
make lib
cp libsvm.so.1 /usr/lib
ln -s libsvm.so.1 libsvm.so
ldconfig
ldconfig --print | grep libsvm

This last step should show libsvm is installed.


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/svm


Examples

The basic process is to define parameters, supply training data to generate a model on, then make predictions based on the model. There are a default set of parameters that should get some results with most any input, so we'll start by looking at the data.

Data is supplied in either a file, a stream, or as an array. If supplied in a file or a stream, it must contain one line per training example, which must be formatted as an integer class (usually 1 and -1) followed by a series of feature/value pairs, in increasing feature order. The features are integers, the values floats, usually scaled 0-1. For example:

-1 1:0.43 3:0.12 9284:0.2

In a document classification problem, say a spam checker, each line would represent a document. There would be two classes, -1 for spam, 1 for ham. Each feature would represent some word, and the value would represent that importance of that word to the document (perhaps the frequency count, with the total scaled to unit length). Features that were 0 (e.g. the word did not appear in the document at all) would simply not be included.

In array mode, the data must be passed as an array of arrays. Each sub-array must have the class as the first element, then key => value sets for the feature values pairs.

This data is passed to the SVM class's train function, which will return an SVM model is successful.

Once a model has been generated, it can be used to make predictions about previously unseen data. This can be passed as an array to the model's predict function, in the same format as before, but without the label. The response will be the class.

Models can be saved and restored as required, using the save and load functions, which both take a file location.

Example #1 Train from array

<?php
$data = array(
    array(-1, 1 => 0.43, 3 => 0.12, 9284 => 0.2),
    array(1, 1 => 0.22, 5 => 0.01, 94 => 0.11),
);

$svm = new SVM();
$model = $svm->train($data);

$data = array(1 => 0.43, 3 => 0.12, 9284 => 0.2);
$result = $model->predict($data);
var_dump($result);
$model->save('model.svm');
?>

The above example will output something similar to:

int(-1)

Example #2 Train from a file

<?php
$svm = new SVM();
$model = $svm->train("traindata.txt");
?>


The SVM class

(PECL svm >= 0.1.0)

Introduction

Class synopsis

SVM {
/* Constants */
const integer C_SVC = 0 ;
const integer NU_SVC = 1 ;
const integer ONE_CLASS = 2 ;
const integer EPSILON_SVR = 3 ;
const integer NU_SVR = 4 ;
const integer KERNEL_LINEAR = 0 ;
const integer KERNEL_POLY = 1 ;
const integer KERNEL_RBF = 2 ;
const integer KERNEL_SIGMOID = 3 ;
const integer KERNEL_PRECOMPUTED = 4 ;
const integer OPT_TYPE = 101 ;
const integer OPT_KERNEL_TYPE = 102 ;
const integer OPT_DEGREE = 103 ;
const integer OPT_SHRINKING = 104 ;
const integer OPT_PROPABILITY = 105 ;
const integer OPT_GAMMA = 201 ;
const integer OPT_NU = 202 ;
const integer OPT_EPS = 203 ;
const integer OPT_P = 204 ;
const integer OPT_COEF_ZERO = 205 ;
const integer OPT_C = 206 ;
const integer OPT_CACHE_SIZE = 207 ;
/* Methods */
public __construct ( void )
public svm::crossvalidate ( array $problem , int $number_of_folds ) : float
public getOptions ( void ) : array
public setOptions ( array $params ) : bool
public svm::train ( array $problem [, array $weights ] ) : SVMModel
}

Predefined Constants

SVM Constants

SVM::C_SVC

The basic C_SVC SVM type. The default, and a good starting point

SVM::NU_SVC

The NU_SVC type uses a different, more flexible, error weighting

SVM::ONE_CLASS

One class SVM type. Train just on a single class, using outliers as negative examples

SVM::EPSILON_SVR

A SVM type for regression (predicting a value rather than just a class)

SVM::NU_SVR

A NU style SVM regression type

SVM::KERNEL_LINEAR

A very simple kernel, can work well on large document classification problems

SVM::KERNEL_POLY

A polynomial kernel

SVM::KERNEL_RBF

The common Gaussian RBD kernel. Handles non-linear problems well and is a good default for classification

SVM::KERNEL_SIGMOID

A kernel based on the sigmoid function. Using this makes the SVM very similar to a two layer sigmoid based neural network

SVM::KERNEL_PRECOMPUTED

A precomputed kernel - currently unsupported.

SVM::OPT_TYPE

The options key for the SVM type

SVM::OPT_KERNEL_TYPE

The options key for the kernel type

SVM::OPT_DEGREE

SVM::OPT_SHRINKING

Training parameter, boolean, for whether to use the shrinking heuristics

SVM::OPT_PROBABILITY

Training parameter, boolean, for whether to collect and use probability estimates

SVM::OPT_GAMMA

Algorithm parameter for Poly, RBF and Sigmoid kernel types.

SVM::OPT_NU

The option key for the nu parameter, only used in the NU_ SVM types

SVM::OPT_EPS

The option key for the Epsilon parameter, used in epsilon regression

SVM::OPT_P

Training parameter used by Episilon SVR regression

SVM::OPT_COEF_ZERO

Algorithm parameter for poly and sigmoid kernels

SVM::OPT_C

The option for the cost parameter that controls tradeoff between errors and generality - effectively the penalty for misclassifying training examples.

SVM::OPT_CACHE_SIZE

Memory cache size, in MB

Table of Contents

  • SVM::__construct — Construct a new SVM object
  • SVM::crossvalidate — Test training params on subsets of the training data
  • SVM::getOptions — Return the current training parameters
  • SVM::setOptions — Set training parameters
  • SVM::train — Create a SVMModel based on training data


Construct a new SVM object

  • « SVM
  • SVM::crossvalidate »
  • PHP Manual
  • SVM
  • Construct a new SVM object

SVM::__construct

(PECL svm >= 0.1.0)

SVM::__construct — Construct a new SVM object

Description

public SVM::__construct ( void )

Constructs a new SVM object ready to accept training data.

Parameters

This function has no parameters.

Return Values

Throws SVMException if the libsvm library could not be loaded


Test training params on subsets of the training data

  • « SVM::__construct
  • SVM::getOptions »
  • PHP Manual
  • SVM
  • Test training params on subsets of the training data

SVM::crossvalidate

(PECL svm >= 0.1.0)

SVM::crossvalidate — Test training params on subsets of the training data

Description

public svm::crossvalidate ( array $problem , int $number_of_folds ) : float

Crossvalidate can be used to test the effectiveness of the current parameter set on a subset of the training data. Given a problem set and a n "folds", it separates the problem set into n subsets, and the repeatedly trains on one subset and tests on another. While the accuracy will generally be lower than a SVM trained on the enter data set, the accuracy score returned should be relatively useful, so it can be used to test different training parameters.

Parameters

problem

The problem data. This can either be in the form of an array, the URL of an SVMLight formatted file, or a stream to an opened SVMLight formatted datasource.

number_of_folds

The number of sets the data should be divided into and cross tested. A higher number means smaller training sets and less reliability. 5 is a good number to start with.

Return Values

The correct percentage, expressed as a floating point number from 0-1. In the case of NU_SVC or EPSILON_SVR kernels the mean squared error will returned instead.

See Also

  • SVM::train() - Create a SVMModel based on training data


Return the current training parameters

  • « SVM::crossvalidate
  • SVM::setOptions »
  • PHP Manual
  • SVM
  • Return the current training parameters

SVM::getOptions

(PECL svm >= 0.1.0)

SVM::getOptions — Return the current training parameters

Description

public SVM::getOptions ( void ) : array

Retrieve an array containing the training parameters. The parameters will be keyed on the predefined SVM constants.

Parameters

This function has no parameters.

Return Values

Returns an array of configuration settings.


Set training parameters

  • « SVM::getOptions
  • SVM::train »
  • PHP Manual
  • SVM
  • Set training parameters

SVM::setOptions

(PECL svm >= 0.1.0)

SVM::setOptions — Set training parameters

Description

public SVM::setOptions ( array $params ) : bool

Set one or more training parameters.

Parameters

params

An array of training parameters, keyed on the SVM constants.

Return Values

Return true on success, throws SVMException on error.


Create a SVMModel based on training data

  • « SVM::setOptions
  • SVMModel »
  • PHP Manual
  • SVM
  • Create a SVMModel based on training data

SVM::train

(PECL svm >= 0.1.0)

SVM::train — Create a SVMModel based on training data

Description

public svm::train ( array $problem [, array $weights ] ) : SVMModel

Train a support vector machine based on the supplied training data.

Parameters

problem

The problem can be provided in three different ways. An array, where the data should start with the class label (usually 1 or -1) then followed by a sparse data set of dimension => data pairs. A URL to a file containing a SVM Light formatted problem, with the each line being a new training example, the start of each line containing the class (1, -1) then a series of tab separated data values shows as key:value. A opened stream pointing to a data source formatted as in the file above.

weights

Weights are an optional set of weighting parameters for the different classes, to help account for unbalanced training sets. For example, if the classes were 1 and -1, and -1 had significantly more example than one, the weight for -1 could be 0.5. Weights should be in the range 0-1.

Return Values

Returns an SVMModel that can be used to classify previously unseen data. Throws SVMException on error


The SVMModel class

(PECL svm >= 0.1.0)

Introduction

The SVMModel is the end result of the training process. It can be used to classify previously unseen data.

Class synopsis

SVMModel {
/* Methods */
public checkProbabilityModel ( void ) : bool
public __construct ([ string $filename ] )
public getLabels ( void ) : array
public getNrClass ( void ) : int
public getSvmType ( void ) : int
public getSvrProbability ( void ) : float
public load ( string $filename ) : bool
public predict_probability ( array $data ) : float
public predict ( array $data ) : float
public save ( string $filename ) : bool
}

Table of Contents

  • SVMModel::checkProbabilityModel — Returns true if the model has probability information
  • SVMModel::__construct — Construct a new SVMModel
  • SVMModel::getLabels — Get the labels the model was trained on
  • SVMModel::getNrClass — Returns the number of classes the model was trained with
  • SVMModel::getSvmType — Get the SVM type the model was trained with
  • SVMModel::getSvrProbability — Get the sigma value for regression types
  • SVMModel::load — Load a saved SVM Model
  • SVMModel::predict_probability — Return class probabilities for previous unseen data
  • SVMModel::predict — Predict a value for previously unseen data
  • SVMModel::save — Save a model to a file


Returns true if the model has probability information

  • « SVMModel
  • SVMModel::__construct »
  • PHP Manual
  • SVMModel
  • Returns true if the model has probability information

SVMModel::checkProbabilityModel

(PECL svm >= 0.1.5)

SVMModel::checkProbabilityModel — Returns true if the model has probability information

Description

public SVMModel::checkProbabilityModel ( void ) : bool

Returns true if the model contains probability information.

Parameters

This function has no parameters.

Return Values

Return a boolean value


Construct a new SVMModel

  • « SVMModel::checkProbabilityModel
  • SVMModel::getLabels »
  • PHP Manual
  • SVMModel
  • Construct a new SVMModel

SVMModel::__construct

(PECL svm >= 0.1.0)

SVMModel::__construct — Construct a new SVMModel

Description

public SVMModel::__construct ([ string $filename ] )

Build a new SVMModel. Models will usually be created from the SVM::train function, but then saved models may be restored directly.

Parameters

filename

The filename for the saved model file this model should load.

Return Values

Throws SVMException on error

See Also

  • SVMModel::load() - Load a saved SVM Model


Get the labels the model was trained on

  • « SVMModel::__construct
  • SVMModel::getNrClass »
  • PHP Manual
  • SVMModel
  • Get the labels the model was trained on

SVMModel::getLabels

(PECL svm >= 0.1.5)

SVMModel::getLabels — Get the labels the model was trained on

Description

public SVMModel::getLabels ( void ) : array

Return an array of labels that the model was trained on. For regression and one class models an empty array is returned.

Parameters

This function has no parameters.

Return Values

Return an array of labels

See Also

  • SVMModel::getNrClass() - Returns the number of classes the model was trained with


Returns the number of classes the model was trained with

  • « SVMModel::getLabels
  • SVMModel::getSvmType »
  • PHP Manual
  • SVMModel
  • Returns the number of classes the model was trained with

SVMModel::getNrClass

(PECL svm >= 0.1.5)

SVMModel::getNrClass — Returns the number of classes the model was trained with

Description

public SVMModel::getNrClass ( void ) : int

Returns the number of classes the model was trained with, will return 2 for one class and regression models.

Parameters

This function has no parameters.

Return Values

Return an integer number of classes


Get the SVM type the model was trained with

  • « SVMModel::getNrClass
  • SVMModel::getSvrProbability »
  • PHP Manual
  • SVMModel
  • Get the SVM type the model was trained with

SVMModel::getSvmType

(PECL svm >= 0.1.5)

SVMModel::getSvmType — Get the SVM type the model was trained with

Description

public SVMModel::getSvmType ( void ) : int

Returns an integer value representing the type of the SVM model used, e.g SVM::C_SVC.

Parameters

This function has no parameters.

Return Values

Return an integer SVM type


Get the sigma value for regression types

  • « SVMModel::getSvmType
  • SVMModel::load »
  • PHP Manual
  • SVMModel
  • Get the sigma value for regression types

SVMModel::getSvrProbability

(PECL svm >= 0.1.5)

SVMModel::getSvrProbability — Get the sigma value for regression types

Description

public SVMModel::getSvrProbability ( void ) : float

For regression models, returns a sigma value. If there is no probability information or the model is not SVR, 0 is returned.

Parameters

This function has no parameters.

Return Values

Returns a sigma value


Load a saved SVM Model

  • « SVMModel::getSvrProbability
  • SVMModel::predict_probability »
  • PHP Manual
  • SVMModel
  • Load a saved SVM Model

SVMModel::load

(PECL svm >= 0.1.00.1.0)

SVMModel::load — Load a saved SVM Model

Description

public SVMModel::load ( string $filename ) : bool

Load a model file ready for classification or regression.

Parameters

filename

The filename of the model.

Return Values

Throws SVMException on error. Returns true on success.

See Also

  • SVMModel::save() - Save a model to a file


Return class probabilities for previous unseen data

  • « SVMModel::load
  • SVMModel::predict »
  • PHP Manual
  • SVMModel
  • Return class probabilities for previous unseen data

SVMModel::predict_probability

(PECL svm >= 0.1.4)

SVMModel::predict_probability — Return class probabilities for previous unseen data

Description

public SVMModel::predict_probability ( array $data ) : float

This function accepts an array of data and attempts to predict the class, as with the predict function. Additionally, however, this function returns an array of probabilities, one per class in the model, which represent the estimated chance of the data supplied being a member of that class. Requires that the model to be used has been trained with the probability parameter set to true.

Parameters

data

The array to be classified. This should be a series of key => value pairs in increasing key order, but not necessarily continuous.

probabilities

The supplied value will be filled with the probabilities. This will be either null, in the case of a model without probability information, or an array where the index is the class name and the value the predicted probability.

Return Values

Float the predicted value. This will be a class label in the case of classification, a real value in the case of regression. Throws SVMException on error

See Also

  • SVM::predict()


Predict a value for previously unseen data

  • « SVMModel::predict_probability
  • SVMModel::save »
  • PHP Manual
  • SVMModel
  • Predict a value for previously unseen data

SVMModel::predict

(PECL svm >= 0.1.0)

SVMModel::predict — Predict a value for previously unseen data

Description

public SVMModel::predict ( array $data ) : float

This function accepts an array of data and attempts to predict the class or regression value based on the model extracted from previously trained data.

Parameters

data

The array to be classified. This should be a series of key => value pairs in increasing key order, but not necessarily continuous.

Return Values

Float the predicted value. This will be a class label in the case of classification, a real value in the case of regression. Throws SVMException on error

See Also

  • SVM::train() - Create a SVMModel based on training data


Save a model to a file

  • « SVMModel::predict
  • SVN »
  • PHP Manual
  • SVMModel
  • Save a model to a file

SVMModel::save

(PECL svm >= 0.1.0)

SVMModel::save — Save a model to a file

Description

public SVMModel::save ( string $filename ) : bool

Save the model data to a file, for later use.

Parameters

filename

The file to save the model to.

Return Values

Throws SVMException on error. Returns true on success.

See Also

  • SVMModel::load() - Load a saved SVM Model


Subversion

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • SVN Functions
    • svn_add — Schedules the addition of an item in a working directory
    • svn_auth_get_parameter — Retrieves authentication parameter
    • svn_auth_set_parameter — Sets an authentication parameter
    • svn_blame — Get the SVN blame for a file
    • svn_cat — Returns the contents of a file in a repository
    • svn_checkout — Checks out a working copy from the repository
    • svn_cleanup — Recursively cleanup a working copy directory, finishing incomplete operations and removing locks
    • svn_client_version — Returns the version of the SVN client libraries
    • svn_commit — Sends changes from the local working copy to the repository
    • svn_delete — Delete items from a working copy or repository
    • svn_diff — Recursively diffs two paths
    • svn_export — Export the contents of a SVN directory
    • svn_fs_abort_txn — Abort a transaction, returns true if everything is okay, false otherwise
    • svn_fs_apply_text — Creates and returns a stream that will be used to replace
    • svn_fs_begin_txn2 — Create a new transaction
    • svn_fs_change_node_prop — Return true if everything is ok, false otherwise
    • svn_fs_check_path — Determines what kind of item lives at path in a given repository fsroot
    • svn_fs_contents_changed — Return true if content is different, false otherwise
    • svn_fs_copy — Copies a file or a directory, returns true if all is ok, false otherwise
    • svn_fs_delete — Deletes a file or a directory, return true if all is ok, false otherwise
    • svn_fs_dir_entries — Enumerates the directory entries under path; returns a hash of dir names to file type
    • svn_fs_file_contents — Returns a stream to access the contents of a file from a given version of the fs
    • svn_fs_file_length — Returns the length of a file from a given version of the fs
    • svn_fs_is_dir — Return true if the path points to a directory, false otherwise
    • svn_fs_is_file — Return true if the path points to a file, false otherwise
    • svn_fs_make_dir — Creates a new empty directory, returns true if all is ok, false otherwise
    • svn_fs_make_file — Creates a new empty file, returns true if all is ok, false otherwise
    • svn_fs_node_created_rev — Returns the revision in which path under fsroot was created
    • svn_fs_node_prop — Returns the value of a property for a node
    • svn_fs_props_changed — Return true if props are different, false otherwise
    • svn_fs_revision_prop — Fetches the value of a named property
    • svn_fs_revision_root — Get a handle on a specific version of the repository root
    • svn_fs_txn_root — Creates and returns a transaction root
    • svn_fs_youngest_rev — Returns the number of the youngest revision in the filesystem
    • svn_import — Imports an unversioned path into a repository
    • svn_log — Returns the commit log messages of a repository URL
    • svn_ls — Returns list of directory contents in repository URL, optionally at revision number
    • svn_mkdir — Creates a directory in a working copy or repository
    • svn_repos_create — Create a new subversion repository at path
    • svn_repos_fs_begin_txn_for_commit — Create a new transaction
    • svn_repos_fs_commit_txn — Commits a transaction and returns the new revision
    • svn_repos_fs — Gets a handle on the filesystem for a repository
    • svn_repos_hotcopy — Make a hot-copy of the repos at repospath; copy it to destpath
    • svn_repos_open — Open a shared lock on a repository
    • svn_repos_recover — Run recovery procedures on the repository located at path
    • svn_revert — Revert changes to the working copy
    • svn_status — Returns the status of working copy files and directories
    • svn_update — Update working copy


Introduction

This extension implements PHP bindings for » Subversion (SVN), a version control system, allowing PHP scripts to communicate with SVN repositories and working copies without direct command line calls to the svn executable.

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.


Requirements

The Subversion binaries are not necessary to use this extension. However, when compiling the extension, libsvn (the Subversion headers) must be available.


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/svn

If ./configure is having trouble finding the SVN files (for example, Subversion was installed with a different prefix directory), use ./configure --with-svn=$USR_PATH to specify the directory where the include/subversion-1/ folder is located.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Warning

If the extension is compiled against libsvn 1.3, functions that work with working copies will fail when used on working copies created by Subversion 1.4.


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.

SVN_REVISION_HEAD (integer)
Magic number (-1) specifying the HEAD revision
Constants usable with svn_auth_set_parameter()
SVN_AUTH_PARAM_DEFAULT_USERNAME (string)
Property for default username to use when performing basic authentication
SVN_AUTH_PARAM_DEFAULT_PASSWORD (string)
Property for default password to use when performing basic authentication
SVN_AUTH_PARAM_NON_INTERACTIVE (string)
SVN_AUTH_PARAM_DONT_STORE_PASSWORDS (string)
SVN_AUTH_PARAM_NO_AUTH_CACHE (string)
SVN_AUTH_PARAM_SSL_SERVER_FAILURES (string)
SVN_AUTH_PARAM_SSL_SERVER_CERT_INFO (string)
SVN_AUTH_PARAM_CONFIG (string)
SVN_AUTH_PARAM_SERVER_GROUP (string)
SVN_AUTH_PARAM_CONFIG_DIR (string)
PHP_SVN_AUTH_PARAM_IGNORE_SSL_VERIFY_ERRORS (string)
Custom property for ignoring SSL cert verification errors
Filesystem constants
SVN_FS_CONFIG_FS_TYPE (string)
Configuration key that determines filesystem type
SVN_FS_TYPE_BDB (string)
Filesystem is Berkeley-DB implementation
SVN_FS_TYPE_FSFS (string)
Filesystem is native-filesystem implementation
Reserved property constants
SVN_PROP_REVISION_DATE (string)
svn:date
SVN_PROP_REVISION_ORIG_DATE (string)
svn:original-date
SVN_PROP_REVISION_AUTHOR (string)
svn:author
SVN_PROP_REVISION_LOG (string)
svn:log
Working copy status constants
SVN_WC_STATUS_NONE (int)
Status does not exist
SVN_WC_STATUS_UNVERSIONED (int)
Item is not versioned in working copy
SVN_WC_STATUS_NORMAL (int)
Item exists, nothing else is happening
SVN_WC_STATUS_ADDED (int)
Item is scheduled for addition
SVN_WC_STATUS_MISSING (int)
Item is versioned but missing from the working copy
SVN_WC_STATUS_DELETED (int)
Item is scheduled for deletion
SVN_WC_STATUS_REPLACED (int)
Item was deleted and then re-added
SVN_WC_STATUS_MODIFIED (int)
Item (text or properties) was modified
SVN_WC_STATUS_MERGED (int)
Item's local modifications were merged with repository modifications
SVN_WC_STATUS_CONFLICTED (int)
Item's local modifications conflicted with repository modifications
SVN_WC_STATUS_IGNORED (int)
Item is unversioned but configured to be ignored
SVN_WC_STATUS_OBSTRUCTED (int)
Unversioned item is in the way of a versioned resource
SVN_WC_STATUS_EXTERNAL (int)
Unversioned path that is populated using svn:externals
SVN_WC_STATUS_INCOMPLETE (int)
Directory does not contain complete entries list
Node type constants
SVN_NODE_NONE (int)
Absent
SVN_NODE_FILE (int)
File
SVN_NODE_DIR (int)
Directory
SVN_NODE_UNKNOWN (int)
Something Subversion cannot identify


SVN Functions

Table of Contents

  • svn_add — Schedules the addition of an item in a working directory
  • svn_auth_get_parameter — Retrieves authentication parameter
  • svn_auth_set_parameter — Sets an authentication parameter
  • svn_blame — Get the SVN blame for a file
  • svn_cat — Returns the contents of a file in a repository
  • svn_checkout — Checks out a working copy from the repository
  • svn_cleanup — Recursively cleanup a working copy directory, finishing incomplete operations and removing locks
  • svn_client_version — Returns the version of the SVN client libraries
  • svn_commit — Sends changes from the local working copy to the repository
  • svn_delete — Delete items from a working copy or repository
  • svn_diff — Recursively diffs two paths
  • svn_export — Export the contents of a SVN directory
  • svn_fs_abort_txn — Abort a transaction, returns true if everything is okay, false otherwise
  • svn_fs_apply_text — Creates and returns a stream that will be used to replace
  • svn_fs_begin_txn2 — Create a new transaction
  • svn_fs_change_node_prop — Return true if everything is ok, false otherwise
  • svn_fs_check_path — Determines what kind of item lives at path in a given repository fsroot
  • svn_fs_contents_changed — Return true if content is different, false otherwise
  • svn_fs_copy — Copies a file or a directory, returns true if all is ok, false otherwise
  • svn_fs_delete — Deletes a file or a directory, return true if all is ok, false otherwise
  • svn_fs_dir_entries — Enumerates the directory entries under path; returns a hash of dir names to file type
  • svn_fs_file_contents — Returns a stream to access the contents of a file from a given version of the fs
  • svn_fs_file_length — Returns the length of a file from a given version of the fs
  • svn_fs_is_dir — Return true if the path points to a directory, false otherwise
  • svn_fs_is_file — Return true if the path points to a file, false otherwise
  • svn_fs_make_dir — Creates a new empty directory, returns true if all is ok, false otherwise
  • svn_fs_make_file — Creates a new empty file, returns true if all is ok, false otherwise
  • svn_fs_node_created_rev — Returns the revision in which path under fsroot was created
  • svn_fs_node_prop — Returns the value of a property for a node
  • svn_fs_props_changed — Return true if props are different, false otherwise
  • svn_fs_revision_prop — Fetches the value of a named property
  • svn_fs_revision_root — Get a handle on a specific version of the repository root
  • svn_fs_txn_root — Creates and returns a transaction root
  • svn_fs_youngest_rev — Returns the number of the youngest revision in the filesystem
  • svn_import — Imports an unversioned path into a repository
  • svn_log — Returns the commit log messages of a repository URL
  • svn_ls — Returns list of directory contents in repository URL, optionally at revision number
  • svn_mkdir — Creates a directory in a working copy or repository
  • svn_repos_create — Create a new subversion repository at path
  • svn_repos_fs_begin_txn_for_commit — Create a new transaction
  • svn_repos_fs_commit_txn — Commits a transaction and returns the new revision
  • svn_repos_fs — Gets a handle on the filesystem for a repository
  • svn_repos_hotcopy — Make a hot-copy of the repos at repospath; copy it to destpath
  • svn_repos_open — Open a shared lock on a repository
  • svn_repos_recover — Run recovery procedures on the repository located at path
  • svn_revert — Revert changes to the working copy
  • svn_status — Returns the status of working copy files and directories
  • svn_update — Update working copy


Schedules the addition of an item in a working directory

  • « SVN Functions
  • svn_auth_get_parameter »
  • PHP Manual
  • SVN Functions
  • Schedules the addition of an item in a working directory

svn_add

(PECL svn >= 0.1.0)

svn_add — Schedules the addition of an item in a working directory

Description

svn_add ( string $path [, bool $recursive = TRUE [, bool $force = FALSE ]] ) : bool

Adds the file, directory or symbolic link at path to the working directory. The item will be added to the repository the next time you call svn_commit() on the working copy.

Parameters

path

Path of item to add.

Note: Relative paths will be resolved as if the current working directory was the one that contains the PHP binary. To use the calling script's working directory, use realpath() or dirname(__FILE__).

recursive

If item is directory, whether or not to recursively add all of its contents. Default is TRUE

force

If true, Subversion will recurse into already versioned directories in order to add unversioned files that may be hiding in those directories. Default is FALSE

Return Values

Returns TRUE on success or FALSE on failure.

Notes

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.

Examples

Example #1 svn_add() example

In a working directory where svn status returns:

$ svn status
?      foobar.txt

...this code:

<?php
svn_add('foobar.txt');
?>

...will schedule foobar.txt for addition into the repository.

See Also

  • » SVN documentation on svn add


Retrieves authentication parameter

  • « svn_add
  • svn_auth_set_parameter »
  • PHP Manual
  • SVN Functions
  • Retrieves authentication parameter

svn_auth_get_parameter

(PECL svn >= 0.1.0)

svn_auth_get_parameter — Retrieves authentication parameter

Description

svn_auth_get_parameter ( string $key ) : string

Retrieves authentication parameter at key. For a list of valid keys and their meanings, consult the authentication constants list.

Parameters

key

String key name. Use the authentication constants defined by this extension to specify a key.

Return Values

Returns the string value of the parameter at key; returns NULL if parameter does not exist.

Notes

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.

See Also

  • svn_auth_set_parameter() - Sets an authentication parameter
  • Authentication constants


Sets an authentication parameter

  • « svn_auth_get_parameter
  • svn_blame »
  • PHP Manual
  • SVN Functions
  • Sets an authentication parameter

svn_auth_set_parameter

(PECL svn >= 0.1.0)

svn_auth_set_parameter — Sets an authentication parameter

Description

svn_auth_set_parameter ( string $key , string $value ) : void

Sets authentication parameter at key to value. For a list of valid keys and their meanings, consult the authentication constants list.

Parameters

key

String key name. Use the authentication constants defined by this extension to specify a key.

value

String value to set to parameter at key. Format of value varies with the parameter.

Return Values

No value is returned.

Notes

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.

Examples

Example #1 Default authentication example

This example configures SVN so that the default username to use is 'Bob' and the default password is 'abc123':

<?php
svn_auth_set_parameter(SVN_AUTH_PARAM_DEFAULT_USERNAME, 'Bob');
svn_auth_set_parameter(SVN_AUTH_PARAM_DEFAULT_PASSWORD, 'abc123');
?>

See Also

  • svn_auth_get_parameter() - Retrieves authentication parameter
  • Authentication constants


Get the SVN blame for a file

  • « svn_auth_set_parameter
  • svn_cat »
  • PHP Manual
  • SVN Functions
  • Get the SVN blame for a file

svn_blame

(PECL svn >= 0.3.0)

svn_blame — Get the SVN blame for a file

Description

svn_blame ( string $repository_url [, int $revision_no = SVN_REVISION_HEAD ] ) : array

Get the SVN blame of a file from a repository URL.

Parameters

repository_url

The repository URL.

revision_no

The revision number.

Return Values

An array of SVN blame information separated by line which includes the revision number, line number, line of code, author, and date.

Examples

Example #1 svn_blame() example

<?php
$svnurl = 'http://svn.example.org/svnroot/foo/trunk/index.php';

print_r( svn_blame($svnurl) );

?>

The above example will output something similar to:

Array
(
    [0] = Array
          (
           [rev] = 1
           [line_no] = 1
           [line] = Hello World
           [author] = joesmith
           [date] = 2007-07-02T05:51:26.628396Z
          )
    [1] = Array
          ...

See Also

  • svn_diff() - Recursively diffs two paths
  • svn_logs()
  • svn_status() - Returns the status of working copy files and directories


Returns the contents of a file in a repository

  • « svn_blame
  • svn_checkout »
  • PHP Manual
  • SVN Functions
  • Returns the contents of a file in a repository

svn_cat

(PECL svn >= 0.1.0)

svn_cat — Returns the contents of a file in a repository

Description

svn_cat ( string $repos_url [, int $revision_no ] ) : string

Returns the contents of the URL repos_url to a file in the repository, optionally at revision number revision_no.

Parameters

repos_url

String URL path to item in a repository.

revision_no

Integer revision number of item to retrieve, default is the HEAD revision.

Return Values

Returns the string contents of the item from the repository on success, and FALSE on failure.

Notes

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.

Examples

Example #1 Basic example

This example retrieves the contents of a file at revision 28:

<?php
$contents = svn_cat('http://www.example.com/svnroot/calc/gui.c', 28)
?>

See Also

  • svn_list()
  • » SVN documentation on svn cat


Checks out a working copy from the repository

  • « svn_cat
  • svn_cleanup »
  • PHP Manual
  • SVN Functions
  • Checks out a working copy from the repository

svn_checkout

(PECL svn >= 0.1.0)

svn_checkout — Checks out a working copy from the repository

Description

svn_checkout ( string $repos , string $targetpath [, int $revision [, int $flags = 0 ]] ) : bool

Checks out a working copy from the repository at repos to targetpath at revision revision.

Parameters

repos

String URL path to directory in repository to check out.

targetpath

String local path to directory to check out in to

Note: Relative paths will be resolved as if the current working directory was the one that contains the PHP binary. To use the calling script's working directory, use realpath() or dirname(__FILE__).

revision

Integer revision number of repository to check out. Default is HEAD, the most recent revision.

flags

Any combination of SVN_NON_RECURSIVE and SVN_IGNORE_EXTERNALS.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

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.

Examples

Example #1 Basic example

This example demonstrates how to check out a directory from a repository to a directory named calc:

<?php
svn_checkout('http://www.example.com/svnroot/calc/trunk', dirname(__FILE__) . '/calc');
?>

The dirname(__FILE__) call is necessary in order to convert the calc relative path into an absolute one. If calc exists, you can also use realpath() to retrieve an absolute path.

See Also

  • svn_add() - Schedules the addition of an item in a working directory
  • svn_commit() - Sends changes from the local working copy to the repository
  • svn_status() - Returns the status of working copy files and directories
  • svn_update() - Update working copy
  • » SVN documentation on svn checkout


Recursively cleanup a working copy directory, finishing incomplete operations and removing locks

  • « svn_checkout
  • svn_client_version »
  • PHP Manual
  • SVN Functions
  • Recursively cleanup a working copy directory, finishing incomplete operations and removing locks

svn_cleanup

(PECL svn >= 0.1.0)

svn_cleanup — Recursively cleanup a working copy directory, finishing incomplete operations and removing locks

Description

svn_cleanup ( string $workingdir ) : bool

Recursively cleanup working copy directory workingdir, finishing any incomplete operations and removing working copy locks. Use when a working copy is in limbo and needs to be usable again.

Parameters

workingdir

String path to local working directory to cleanup

Note: Relative paths will be resolved as if the current working directory was the one that contains the PHP binary. To use the calling script's working directory, use realpath() or dirname(__FILE__).

Return Values

Returns TRUE on success or FALSE on failure.

Notes

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.

Examples

Example #1 Basic example

This example demonstrates clean up of a working copy in a directory named help-me:

<?php
svn_cleanup(realpath('help-me'));
?>

The realpath() call is necessary due to SVN's quirky handling of relative paths.

See Also

  • update()
  • » SVN documentation on svn cleanup


Returns the version of the SVN client libraries

  • « svn_cleanup
  • svn_commit »
  • PHP Manual
  • SVN Functions
  • Returns the version of the SVN client libraries

svn_client_version

(PECL svn >= 0.1.0)

svn_client_version — Returns the version of the SVN client libraries

Description

svn_client_version ( void ) : string

Returns the version of the SVN client libraries

Return Values

String version number, usually in form of x.y.z.

Notes

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.

Examples

Example #1 Basic example

<?php
echo svn_client_version();
?>

The above example will output something similar to:

1.3.1


Sends changes from the local working copy to the repository

  • « svn_client_version
  • svn_delete »
  • PHP Manual
  • SVN Functions
  • Sends changes from the local working copy to the repository

svn_commit

(PECL svn >= 0.1.0)

svn_commit — Sends changes from the local working copy to the repository

Description

svn_commit ( string $log , array $targets [, bool $recursive = TRUE ] ) : array

Commits changes made in the local working copy files enumerated in the targets array to the repository, with the log message log. Directories in the targets array will be recursively committed unless recursive is set to FALSE.

Note: This function does not have any parameters for specifying authentication, so a username and password must be set using svn_auth_set_parameter()

Parameters

log

String log text to commit

targets

Array of local paths of files to be committed

Warning

This parameter must be an array, a string for a single target is not acceptable.

Note: Relative paths will be resolved as if the current working directory was the one that contains the PHP binary. To use the calling script's working directory, use realpath() or dirname(__FILE__).

recursive

Boolean flag to disable recursive committing of directories in the targets array. Default is TRUE.

Return Values

Returns array in form of:

array(
    0 => integer revision number of commit
    1 => string ISO 8601 date and time of commit
    2 => name of committer
)

Returns FALSE on failure.

Notes

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.

Examples

Example #1 Basic example

This example commits the calculator directory to a repository, using the username Bob and the password abc123 (hopefully, his password is stronger):

<?php
svn_auth_set_parameter(SVN_AUTH_PARAM_DEFAULT_USERNAME, 'Bob');
svn_auth_set_parameter(SVN_AUTH_PARAM_DEFAULT_PASSWORD, 'abc123');
var_dump(svn_commit('Log message of Bob\'s commit', array(realpath('calculator'))));
?>

The above example will output:

array(
  0 => 1415,
  1 => '2007-05-26T01:44:28.453125Z',
  2 => 'Bob'
)

See Also

  • svn_auth_set_parameter() - Sets an authentication parameter
  • » SVN documentation on svn commit


Delete items from a working copy or repository

  • « svn_commit
  • svn_diff »
  • PHP Manual
  • SVN Functions
  • Delete items from a working copy or repository

svn_delete

(PECL svn >= 0.4.0)

svn_delete — Delete items from a working copy or repository

Description

svn_delete ( string $path [, bool $force = FALSE ] ) : bool

Deletes the file, directory or symbolic link at path from the working directory. The item will be deleted from the repository the next time you call svn_commit() on the working copy.

Parameters

path

Path of item to delete.

Note: Relative paths will be resolved as if the current working directory was the one that contains the PHP binary. To use the calling script's working directory, use realpath() or dirname(__FILE__).

force

If TRUE, the file will be deleted even if it has local modifications. Otherwise, local modifications will result in a failure. Default is FALSE

Return Values

Returns TRUE on success or FALSE on failure.

Notes

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.

See Also

  • » SVN documentation on svn delete


Recursively diffs two paths

  • « svn_delete
  • svn_export »
  • PHP Manual
  • SVN Functions
  • Recursively diffs two paths

svn_diff

(PECL svn >= 0.1.0)

svn_diff — Recursively diffs two paths

Description

svn_diff ( string $path1 , int $rev1 , string $path2 , int $rev2 ) : array

Recursively diffs two paths, path1 and path2.

Note:

This is not a general-purpose diff utility. Only local files that are versioned may be diffed: other files will fail.

Parameters

path1

First path to diff. This can be a URL to a file/directory in an SVN repository or a local file/directory path.

Note: Relative paths will be resolved as if the current working directory was the one that contains the PHP binary. To use the calling script's working directory, use realpath() or dirname(__FILE__).

Warning

If a local file path has only backslashes and no forward slashes, this extension will fail to find the path. Always replace all backslashes with forward slashes when using this function.

rev1

First path's revision number. Use SVN_REVISION_HEAD to specify the most recent revision.

path2

Second path to diff. See path1 for description.

rev2

Second path's revision number. See rev1 for description.

Return Values

Returns an array-list consisting of two streams: the first is the diff output and the second contains error stream output. The streams can be read using fread(). Returns FALSE or NULL on error.

The diff output will, by default, be in the form of Subversion's custom unified diff format, but an » external diff engine may be used depending on Subversion's configuration.

Notes

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.

Examples

Example #1 Basic example

This example demonstrates the basic usage of this function, and the retrieval of contents from the stream:

<?php
list($diff, $errors) = svn_diff(
    'http://www.example.com/svnroot/trunk/foo', SVN_REVISION_HEAD,
    'http://www.example.com/svnroot/branches/dev/foo', SVN_REVISION_HEAD
);
if (!$diff) exit;
$contents = '';
while (!feof($diff)) {
  $contents .= fread($diff, 8192);
}
fclose($diff);
fclose($errors);
var_dump($contents);
?>

The above example will output:

Index: http://www.example.com/svnroot/trunk/foo
===================================================================
--- http://www.example.com/svnroot/trunk/foo        (.../foo) (revision 23)
+++ http://www.example.com/svnroot/branches/dev/foo (.../foo) (revision 27)
 // further diff output

Example #2 Diffing two revisions of a repository path

This example implements a wrapper function that allows a user to easily diff two revisions of the same item using an external repository path (the default syntax is somewhat verbose):

<?php
function svn_diff_same_item($path, $rev1, $rev2) {
    return svn_diff($path, $rev1, $path, $rev2);
}
?>

Example #3 Portably diffing two local files

This example implements a wrapper function that portably diffs two local files, compensating for the realpath() fix and the backslashes bug:

<?php
function svn_diff_local($path1, $rev1, $path2, $rev2) {
    $path1 = str_replace('\\', '/', realpath($path1));
    $path2 = str_replace('\\', '/', realpath($path2));
    return svn_diff($path1, $rev1, $path2, $rev2);
}
?>

See Also

  • » SVN documentation on svn diff


Export the contents of a SVN directory

  • « svn_diff
  • svn_fs_abort_txn »
  • PHP Manual
  • SVN Functions
  • Export the contents of a SVN directory

svn_export

(PECL svn >= 0.3.0)

svn_export — Export the contents of a SVN directory

Description

svn_export ( string $frompath , string $topath [, bool $working_copy = TRUE [, int $revision_no = -1 ]] ) : bool

Export the contents of either a working copy or repository into a 'clean' directory.

Parameters

frompath

The path to the current repository.

topath

The path to the new repository.

working_copy

If TRUE, it will export uncommitted files from the working copy.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 svn_export() example

<?php
$working_dir     = '../';
$new_working_dir = '/home/user/devel/foo/trunk';

svn_export($working_dir, $new_working_dir);
?>

See Also

  • svn_import() - Imports an unversioned path into a repository


Abort a transaction, returns true if everything is okay, false otherwise

  • « svn_export
  • svn_fs_apply_text »
  • PHP Manual
  • SVN Functions
  • Abort a transaction, returns true if everything is okay, false otherwise

svn_fs_abort_txn

(PECL svn >= 0.2.0)

svn_fs_abort_txn — Abort a transaction, returns true if everything is okay, false otherwise

Description

svn_fs_abort_txn ( resource $txn ) : bool
Warning

This function is currently not documented; only its argument list is available.

Abort a transaction, returns true if everything is okay, false otherwise

Notes

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.


Creates and returns a stream that will be used to replace

  • « svn_fs_abort_txn
  • svn_fs_begin_txn2 »
  • PHP Manual
  • SVN Functions
  • Creates and returns a stream that will be used to replace

svn_fs_apply_text

(PECL svn >= 0.2.0)

svn_fs_apply_text — Creates and returns a stream that will be used to replace

Description

svn_fs_apply_text ( resource $root , string $path ) : resource
Warning

This function is currently not documented; only its argument list is available.

Creates and returns a stream that will be used to replace

Notes

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.


Create a new transaction

  • « svn_fs_apply_text
  • svn_fs_change_node_prop »
  • PHP Manual
  • SVN Functions
  • Create a new transaction

svn_fs_begin_txn2

(PECL svn >= 0.2.0)

svn_fs_begin_txn2 — Create a new transaction

Description

svn_fs_begin_txn2 ( resource $repos , int $rev ) : resource
Warning

This function is currently not documented; only its argument list is available.

Create a new transaction

Notes

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.


Return true if everything is ok, false otherwise

  • « svn_fs_begin_txn2
  • svn_fs_check_path »
  • PHP Manual
  • SVN Functions
  • Return true if everything is ok, false otherwise

svn_fs_change_node_prop

(PECL svn >= 0.2.0)

svn_fs_change_node_prop — Return true if everything is ok, false otherwise

Description

svn_fs_change_node_prop ( resource $root , string $path , string $name , string $value ) : bool
Warning

This function is currently not documented; only its argument list is available.

Return true if everything is ok, false otherwise

Notes

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.


Determines what kind of item lives at path in a given repository fsroot

  • « svn_fs_change_node_prop
  • svn_fs_contents_changed »
  • PHP Manual
  • SVN Functions
  • Determines what kind of item lives at path in a given repository fsroot

svn_fs_check_path

(PECL svn >= 0.1.0)

svn_fs_check_path — Determines what kind of item lives at path in a given repository fsroot

Description

svn_fs_check_path ( resource $fsroot , string $path ) : int
Warning

This function is currently not documented; only its argument list is available.

Determines what kind of item lives at path in a given repository fsroot

Notes

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.


Return true if content is different, false otherwise

  • « svn_fs_check_path
  • svn_fs_copy »
  • PHP Manual
  • SVN Functions
  • Return true if content is different, false otherwise

svn_fs_contents_changed

(PECL svn >= 0.2.0)

svn_fs_contents_changed — Return true if content is different, false otherwise

Description

svn_fs_contents_changed ( resource $root1 , string $path1 , resource $root2 , string $path2 ) : bool
Warning

This function is currently not documented; only its argument list is available.

Return true if content is different, false otherwise

Notes

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.


Copies a file or a directory, returns true if all is ok, false otherwise

  • « svn_fs_contents_changed
  • svn_fs_delete »
  • PHP Manual
  • SVN Functions
  • Copies a file or a directory, returns true if all is ok, false otherwise

svn_fs_copy

(PECL svn >= 0.2.0)

svn_fs_copy — Copies a file or a directory, returns true if all is ok, false otherwise

Description

svn_fs_copy ( resource $from_root , string $from_path , resource $to_root , string $to_path ) : bool
Warning

This function is currently not documented; only its argument list is available.

Copies a file or a directory, returns true if all is ok, false otherwise

Notes

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.


Deletes a file or a directory, return true if all is ok, false otherwise

  • « svn_fs_copy
  • svn_fs_dir_entries »
  • PHP Manual
  • SVN Functions
  • Deletes a file or a directory, return true if all is ok, false otherwise

svn_fs_delete

(PECL svn >= 0.2.0)

svn_fs_delete — Deletes a file or a directory, return true if all is ok, false otherwise

Description

svn_fs_delete ( resource $root , string $path ) : bool
Warning

This function is currently not documented; only its argument list is available.

Deletes a file or a directory, return true if all is ok, false otherwise

Notes

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.


Enumerates the directory entries under path; returns a hash of dir names to file type

  • « svn_fs_delete
  • svn_fs_file_contents »
  • PHP Manual
  • SVN Functions
  • Enumerates the directory entries under path; returns a hash of dir names to file type

svn_fs_dir_entries

(PECL svn >= 0.1.0)

svn_fs_dir_entries — Enumerates the directory entries under path; returns a hash of dir names to file type

Description

svn_fs_dir_entries ( resource $fsroot , string $path ) : array
Warning

This function is currently not documented; only its argument list is available.

Enumerates the directory entries under path; returns a hash of dir names to file type

Notes

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.


Returns a stream to access the contents of a file from a given version of the fs

  • « svn_fs_dir_entries
  • svn_fs_file_length »
  • PHP Manual
  • SVN Functions
  • Returns a stream to access the contents of a file from a given version of the fs

svn_fs_file_contents

(PECL svn >= 0.1.0)

svn_fs_file_contents — Returns a stream to access the contents of a file from a given version of the fs

Description

svn_fs_file_contents ( resource $fsroot , string $path ) : resource
Warning

This function is currently not documented; only its argument list is available.

Returns a stream to access the contents of a file from a given version of the fs

Notes

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.


Returns the length of a file from a given version of the fs

  • « svn_fs_file_contents
  • svn_fs_is_dir »
  • PHP Manual
  • SVN Functions
  • Returns the length of a file from a given version of the fs

svn_fs_file_length

(PECL svn >= 0.1.0)

svn_fs_file_length — Returns the length of a file from a given version of the fs

Description

svn_fs_file_length ( resource $fsroot , string $path ) : int
Warning

This function is currently not documented; only its argument list is available.

Returns the length of a file from a given version of the fs

Notes

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.


Return true if the path points to a directory, false otherwise

  • « svn_fs_file_length
  • svn_fs_is_file »
  • PHP Manual
  • SVN Functions
  • Return true if the path points to a directory, false otherwise

svn_fs_is_dir

(PECL svn >= 0.2.0)

svn_fs_is_dir — Return true if the path points to a directory, false otherwise

Description

svn_fs_is_dir ( resource $root , string $path ) : bool
Warning

This function is currently not documented; only its argument list is available.

Return true if the path points to a directory, false otherwise

Notes

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.


Return true if the path points to a file, false otherwise

  • « svn_fs_is_dir
  • svn_fs_make_dir »
  • PHP Manual
  • SVN Functions
  • Return true if the path points to a file, false otherwise

svn_fs_is_file

(PECL svn >= 0.2.0)

svn_fs_is_file — Return true if the path points to a file, false otherwise

Description

svn_fs_is_file ( resource $root , string $path ) : bool
Warning

This function is currently not documented; only its argument list is available.

Return true if the path points to a file, false otherwise

Notes

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.


Creates a new empty directory, returns true if all is ok, false otherwise

  • « svn_fs_is_file
  • svn_fs_make_file »
  • PHP Manual
  • SVN Functions
  • Creates a new empty directory, returns true if all is ok, false otherwise

svn_fs_make_dir

(PECL svn >= 0.2.0)

svn_fs_make_dir — Creates a new empty directory, returns true if all is ok, false otherwise

Description

svn_fs_make_dir ( resource $root , string $path ) : bool
Warning

This function is currently not documented; only its argument list is available.

Creates a new empty directory, returns true if all is ok, false otherwise

Notes

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.


Creates a new empty file, returns true if all is ok, false otherwise

  • « svn_fs_make_dir
  • svn_fs_node_created_rev »
  • PHP Manual
  • SVN Functions
  • Creates a new empty file, returns true if all is ok, false otherwise

svn_fs_make_file

(PECL svn >= 0.2.0)

svn_fs_make_file — Creates a new empty file, returns true if all is ok, false otherwise

Description

svn_fs_make_file ( resource $root , string $path ) : bool
Warning

This function is currently not documented; only its argument list is available.

Creates a new empty file, returns true if all is ok, false otherwise

Notes

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.


Returns the revision in which path under fsroot was created

  • « svn_fs_make_file
  • svn_fs_node_prop »
  • PHP Manual
  • SVN Functions
  • Returns the revision in which path under fsroot was created

svn_fs_node_created_rev

(PECL svn >= 0.1.0)

svn_fs_node_created_rev — Returns the revision in which path under fsroot was created

Description

svn_fs_node_created_rev ( resource $fsroot , string $path ) : int
Warning

This function is currently not documented; only its argument list is available.

Returns the revision in which path under fsroot was created

Notes

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.


Returns the value of a property for a node

  • « svn_fs_node_created_rev
  • svn_fs_props_changed »
  • PHP Manual
  • SVN Functions
  • Returns the value of a property for a node

svn_fs_node_prop

(PECL svn >= 0.1.0)

svn_fs_node_prop — Returns the value of a property for a node

Description

svn_fs_node_prop ( resource $fsroot , string $path , string $propname ) : string
Warning

This function is currently not documented; only its argument list is available.

Returns the value of a property for a node

Notes

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.


Return true if props are different, false otherwise

  • « svn_fs_node_prop
  • svn_fs_revision_prop »
  • PHP Manual
  • SVN Functions
  • Return true if props are different, false otherwise

svn_fs_props_changed

(PECL svn >= 0.2.0)

svn_fs_props_changed — Return true if props are different, false otherwise

Description

svn_fs_props_changed ( resource $root1 , string $path1 , resource $root2 , string $path2 ) : bool
Warning

This function is currently not documented; only its argument list is available.

Return true if props are different, false otherwise

Notes

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.


Fetches the value of a named property

  • « svn_fs_props_changed
  • svn_fs_revision_root »
  • PHP Manual
  • SVN Functions
  • Fetches the value of a named property

svn_fs_revision_prop

(PECL svn >= 0.1.0)

svn_fs_revision_prop — Fetches the value of a named property

Description

svn_fs_revision_prop ( resource $fs , int $revnum , string $propname ) : string
Warning

This function is currently not documented; only its argument list is available.

Fetches the value of a named property

Notes

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.


Get a handle on a specific version of the repository root

  • « svn_fs_revision_prop
  • svn_fs_txn_root »
  • PHP Manual
  • SVN Functions
  • Get a handle on a specific version of the repository root

svn_fs_revision_root

(PECL svn >= 0.1.0)

svn_fs_revision_root — Get a handle on a specific version of the repository root

Description

svn_fs_revision_root ( resource $fs , int $revnum ) : resource
Warning

This function is currently not documented; only its argument list is available.

Get a handle on a specific version of the repository root

Notes

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.


Creates and returns a transaction root

  • « svn_fs_revision_root
  • svn_fs_youngest_rev »
  • PHP Manual
  • SVN Functions
  • Creates and returns a transaction root

svn_fs_txn_root

(PECL svn >= 0.2.0)

svn_fs_txn_root — Creates and returns a transaction root

Description

svn_fs_txn_root ( resource $txn ) : resource
Warning

This function is currently not documented; only its argument list is available.

Creates and returns a transaction root

Notes

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.


Returns the number of the youngest revision in the filesystem

  • « svn_fs_txn_root
  • svn_import »
  • PHP Manual
  • SVN Functions
  • Returns the number of the youngest revision in the filesystem

svn_fs_youngest_rev

(PECL svn >= 0.1.0)

svn_fs_youngest_rev — Returns the number of the youngest revision in the filesystem

Description

svn_fs_youngest_rev ( resource $fs ) : int
Warning

This function is currently not documented; only its argument list is available.

Returns the number of the youngest revision in the filesystem

Notes

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.


Imports an unversioned path into a repository

  • « svn_fs_youngest_rev
  • svn_log »
  • PHP Manual
  • SVN Functions
  • Imports an unversioned path into a repository

svn_import

(PECL svn >= 0.2.0)

svn_import — Imports an unversioned path into a repository

Description

svn_import ( string $path , string $url , bool $nonrecursive ) : bool

Commits unversioned path into repository at url. If path is a directory and nonrecursive is FALSE, the directory will be imported recursively.

Parameters

path

Path of file or directory to import.

Note: Relative paths will be resolved as if the current working directory was the one that contains the PHP binary. To use the calling script's working directory, use realpath() or dirname(__FILE__).

url

Repository URL to import into.

nonrecursive

Whether or not to refrain from recursively processing directories.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

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.

Examples

Example #1 Basic example

This example demonstrates a basic use-case of this function. To import a directory named new-files into the repository at http://www.example.com/svnroot/incoming/abc, use:

<?php
svn_import(realpath('new-files'), 'http://www.example.com/svnroot/incoming/abc', false);
?>

See Also

  • svn_add() - Schedules the addition of an item in a working directory
  • » SVN documentation for svn import


Returns the commit log messages of a repository URL

  • « svn_import
  • svn_ls »
  • PHP Manual
  • SVN Functions
  • Returns the commit log messages of a repository URL

svn_log

(PECL svn >= 0.1.0)

svn_log — Returns the commit log messages of a repository URL

Description

svn_log ( string $repos_url [, int $start_revision [, int $end_revision [, int $limit = 0 [, int $flags = SVN_DISCOVER_CHANGED_PATHS | SVN_STOP_ON_COPY ]]]] ) : array

svn_log() returns the complete history of the item at the repository URL repos_url, or the history of a specific revision if start_revision is set. This function is equivalent to svn log --verbose -r $start_revision $repos_url.

Parameters

repos_url

Repository URL of the item to retrieve log history from.

start_revision

Revision number of the first log to retrieve. Use SVN_REVISION_HEAD to retrieve the log from the most recent revision.

end_revision

Revision number of the last log to retrieve. Defaults to start_revision if specified or to SVN_REVISION_INITIAL otherwise.

limit

Number of logs to retrieve.

flags

Any combination of SVN_OMIT_MESSAGES, SVN_DISCOVER_CHANGED_PATHS and SVN_STOP_ON_COPY.

Return Values

On success, this function returns an array file listing in the format of:

[0] => Array, ordered most recent (highest) revision first
(
    [rev] => integer revision number
    [author] => string author name
    [msg] => string log message
    [date] => string date formatted per ISO 8601, i.e. date('c')
    [paths] => Array, describing changed files
        (
            [0] => Array
                (
                    [action] => string letter signifying change
                    [path] =>  absolute repository path of changed file
                )
            [1] => ...
        )
)
[1] => ...

Note:

The output will always be a numerically indexed array of arrays, even when there are none or only one log message(s).

The value of action is a subset of the » status output in the first column, where possible values are:

Actions
Letter | Description
M | Item/props was modified
A | Item was added
D | Item was deleted
R | Item was replaced

If no changes were made to the item, an empty array is returned.

Notes

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.

Examples

Example #1 svn_log() example

<?php
print_r( svn_log('http://www.example.com/', 23) );
?>

The above example will output something similar to:

Array
(
    [0] => Array
    (
        [rev] => 23
        [author] => 'joe'
        [msg] => 'Add cheese and salami to our sandwich.'
        [date] => '2007-04-06T16:00:27-04:00'
        [paths] => Array
            (
                [0] => Array
                    (
                        [action] => 'M'
                        [path] =>  '/sandwich.txt'
                    )
            )
    )
)

See Also

  • » SVN documentation on svn log


Returns list of directory contents in repository URL, optionally at revision number

  • « svn_log
  • svn_mkdir »
  • PHP Manual
  • SVN Functions
  • Returns list of directory contents in repository URL, optionally at revision number

svn_ls

(PECL svn >= 0.1.0)

svn_ls — Returns list of directory contents in repository URL, optionally at revision number

Description

svn_ls ( string $repos_url [, int $revision_no = SVN_REVISION_HEAD [, bool $recurse = FALSE [, bool $peg = FALSE ]]] ) : array

This function queries the repository URL and returns a list of files and directories, optionally from a specific revision. This is equivalent to svn list $repos_url[@$revision_no]

Note:

This function does not work with working copies. repos_url must be a repository URL.

Parameters

url

URL of the repository, eg. http://www.example.com/svnroot. To access a local Subversion repository via filesystem, use the file URI scheme, eg. file:///home/user/svn-repos

revision

Integer revision number to retrieve listing of. When omitted, the HEAD revision is used.

recurse

Enables recursion.

Return Values

On success, this function returns an array file listing in the format of:

[0] => Array
    (
        [created_rev] => integer revision number of last edit
        [last_author] => string author name of last edit
        [size] => integer byte file size of file
        [time] => string date of last edit in form 'M d H:i'
                  or 'M d Y', depending on how old the file is
        [time_t] => integer unix timestamp of last edit
        [name] => name of file/directory
        [type] => type, can be 'file' or 'dir'
    )
[1] => ...

Notes

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.

Examples

Example #1 svn_ls() example

<?php
print_r( svn_ls('http://www.example.com/svnroot/') );
?>

The above example will output something similar to:

Array
(
    [0] => Array
        (
            [created_rev] => 20
            [last_author] => Joe
            [size] => 0
            [time] => Apr 02 09:28
            [time_t] => 1175520529
            [name] => tags
            [type] => dir
        )
    [1] => Array
        (
            [created_rev] => 23
            [last_author] => Bob
            [size] => 0
            [time] => Apr 02 15:15
            [time_t] => 1175541322
            [name] => trunk
            [type] => dir
        )
)

See Also

  • » SVN documentation on svn list


Creates a directory in a working copy or repository

  • « svn_ls
  • svn_repos_create »
  • PHP Manual
  • SVN Functions
  • Creates a directory in a working copy or repository

svn_mkdir

(PECL svn >= 0.4.0)

svn_mkdir — Creates a directory in a working copy or repository

Description

svn_mkdir ( string $path [, string $log_message ] ) : bool

Creates a directory in a working copy or repository.

Parameters

path

The path to the working copy or repository.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • svn_add() - Schedules the addition of an item in a working directory
  • svn_copy()


Create a new subversion repository at path

  • « svn_mkdir
  • svn_repos_fs_begin_txn_for_commit »
  • PHP Manual
  • SVN Functions
  • Create a new subversion repository at path

svn_repos_create

(PECL svn >= 0.1.0)

svn_repos_create — Create a new subversion repository at path

Description

svn_repos_create ( string $path [, array $config [, array $fsconfig ]] ) : resource
Warning

This function is currently not documented; only its argument list is available.

Create a new subversion repository at path

Notes

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.


Create a new transaction

  • « svn_repos_create
  • svn_repos_fs_commit_txn »
  • PHP Manual
  • SVN Functions
  • Create a new transaction

svn_repos_fs_begin_txn_for_commit

(PECL svn >= 0.2.0)

svn_repos_fs_begin_txn_for_commit — Create a new transaction

Description

svn_repos_fs_begin_txn_for_commit ( resource $repos , int $rev , string $author , string $log_msg ) : resource
Warning

This function is currently not documented; only its argument list is available.

Create a new transaction

Notes

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.


Commits a transaction and returns the new revision

  • « svn_repos_fs_begin_txn_for_commit
  • svn_repos_fs »
  • PHP Manual
  • SVN Functions
  • Commits a transaction and returns the new revision

svn_repos_fs_commit_txn

(PECL svn >= 0.2.0)

svn_repos_fs_commit_txn — Commits a transaction and returns the new revision

Description

svn_repos_fs_commit_txn ( resource $txn ) : int
Warning

This function is currently not documented; only its argument list is available.

Commits a transaction and returns the new revision

Notes

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.


Gets a handle on the filesystem for a repository

  • « svn_repos_fs_commit_txn
  • svn_repos_hotcopy »
  • PHP Manual
  • SVN Functions
  • Gets a handle on the filesystem for a repository

svn_repos_fs

(PECL svn >= 0.1.0)

svn_repos_fs — Gets a handle on the filesystem for a repository

Description

svn_repos_fs ( resource $repos ) : resource
Warning

This function is currently not documented; only its argument list is available.

Gets a handle on the filesystem for a repository

Notes

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.


Make a hot-copy of the repos at repospath; copy it to destpath

  • « svn_repos_fs
  • svn_repos_open »
  • PHP Manual
  • SVN Functions
  • Make a hot-copy of the repos at repospath; copy it to destpath

svn_repos_hotcopy

(PECL svn >= 0.1.0)

svn_repos_hotcopy — Make a hot-copy of the repos at repospath; copy it to destpath

Description

svn_repos_hotcopy ( string $repospath , string $destpath , bool $cleanlogs ) : bool
Warning

This function is currently not documented; only its argument list is available.

Make a hot-copy of the repos at repospath; copy it to destpath

Notes

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.


Open a shared lock on a repository

  • « svn_repos_hotcopy
  • svn_repos_recover »
  • PHP Manual
  • SVN Functions
  • Open a shared lock on a repository

svn_repos_open

(PECL svn >= 0.1.0)

svn_repos_open — Open a shared lock on a repository

Description

svn_repos_open ( string $path ) : resource
Warning

This function is currently not documented; only its argument list is available.

Open a shared lock on a repository.

Notes

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.


Run recovery procedures on the repository located at path

  • « svn_repos_open
  • svn_revert »
  • PHP Manual
  • SVN Functions
  • Run recovery procedures on the repository located at path

svn_repos_recover

(PECL svn >= 0.1.0)

svn_repos_recover — Run recovery procedures on the repository located at path

Description

svn_repos_recover ( string $path ) : bool
Warning

This function is currently not documented; only its argument list is available.

Run recovery procedures on the repository located at path.

Notes

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.


Revert changes to the working copy

  • « svn_repos_recover
  • svn_status »
  • PHP Manual
  • SVN Functions
  • Revert changes to the working copy

svn_revert

(PECL svn >= 0.3.0)

svn_revert — Revert changes to the working copy

Description

svn_revert ( string $path [, bool $recursive = FALSE ] ) : bool

Revert any local changes to the path in a working copy.

Parameters

path

The path to the working repository.

recursive

Optionally make recursive changes.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • svn_delete() - Delete items from a working copy or repository
  • svn_export() - Export the contents of a SVN directory


Returns the status of working copy files and directories

  • « svn_revert
  • svn_update »
  • PHP Manual
  • SVN Functions
  • Returns the status of working copy files and directories

svn_status

(PECL svn >= 0.1.0)

svn_status — Returns the status of working copy files and directories

Description

svn_status ( string $path [, int $flags = 0 ] ) : array

Returns the status of working copy files and directories, giving modifications, additions, deletions and other changes to items in the working copy.

Parameters

path

Local path to file or directory to retrieve status of.

Note: Relative paths will be resolved as if the current working directory was the one that contains the PHP binary. To use the calling script's working directory, use realpath() or dirname(__FILE__).

flags

Any combination of Svn::NON_RECURSIVE, Svn::ALL (regardless of modification status), Svn::SHOW_UPDATES (entries will be added for items that are out-of-date), Svn::NO_IGNORE (disregard svn:ignore properties when scanning for new files) and Svn::IGNORE_EXTERNALS.

Return Values

Returns a numerically indexed array of associative arrays detailing the status of items in the repository:

Array (
    [0] => Array (
        // information on item
    )
    [1] => ...
)

The information on the item is an associative array that can contain the following keys:

path
String path to file/directory of this entry on local filesystem.
text_status
Status of item's text. Refer to status constants for possible values.
repos_text_status
Status of item's text in repository. Only accurate if update was set to TRUE. Refer to status constants for possible values.
prop_status
Status of item's properties. Refer to status constants for possible values.
repos_prop_status
Status of item's property in repository. Only accurate if update was set to TRUE. Refer to status constants for possible values.
locked
Whether or not the item is locked. (Only set if TRUE.)
copied
Whether or not the item was copied (scheduled for addition with history). (Only set if TRUE.)
switched
Whether or not the item was switched using the switch command. (Only set if TRUE)

These keys are only set if the item is versioned:

name
Base name of item in repository.
url
URL of item in repository.
repos
Base URL of repository.
revision
Integer revision of item in working copy.
kind
Type of item, i.e. file or directory. Refer to type constants for possible values.
schedule
Scheduled action for item, i.e. addition or deletion. Constants for these magic numbers are not available, they can be emulated by using:
<?php
if (!defined('svn_wc_schedule_normal')) {
    define('svn_wc_schedule_normal',  0); // nothing special
    define('svn_wc_schedule_add',     1); // item will be added
    define('svn_wc_schedule_delete',  2); // item will be deleted
    define('svn_wc_schedule_replace', 3); // item will be added and deleted
}
?>
deleted
Whether or not the item was deleted, but parent revision lags behind. (Only set if TRUE.)
absent
Whether or not the item is absent, that is, Subversion knows that there should be something there but there isn't. (Only set if TRUE.)
incomplete
Whether or not the entries file for a directory is incomplete. (Only set if TRUE.)
cmt_date
Integer Unix timestamp of last commit date. (Unaffected by update.)
cmt_rev
Integer revision of last commit. (Unaffected by update.)
cmt_author
String author of last commit. (Unaffected by update.)
prop_time
Integer Unix timestamp of last up-to-date time for properties
text_time
Integer Unix timestamp of last up-to-date time for text

Notes

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.

Examples

Example #1 Basic example

This example demonstrates a basic, theoretical usage of this function.

<?php
print_r(svn_status(realpath('wc')));
?>

The above example will output something similar to:

Array (
    [0] => Array (
        [path] => /home/bob/wc/sandwich.txt
        [text_status] => 8 // item was modified
        [repos_text_status] => 1 // no information available, use update
        [prop_status] => 3 // no changes
        [repos_prop_status] => 1 // no information available, use update
        [name] => sandwich.txt
        [url] => http://www.example.com/svnroot/deli/trunk/sandwich.txt
        [repos] => http://www.example.com/svnroot/
        [revision] => 123
        [kind] => 1 // file
        [schedule] => 0 // no special actions scheduled
        [cmt_date] => 1165543135
        [cmt_rev] => 120
        [cmt_author] => Alice
        [prop_time] => 1180201728
        [text_time] => 1180201729
    )
)

See Also

  • svn_update() - Update working copy
  • svn_log() - Returns the commit log messages of a repository URL
  • » SVN documentation for svn status


Update working copy

  • « svn_status
  • TCP »
  • PHP Manual
  • SVN Functions
  • Update working copy

svn_update

(PECL svn >= 0.1.0)

svn_update — Update working copy

Description

svn_update ( string $path [, int $revno = SVN_REVISION_HEAD [, bool $recurse = TRUE ]] ) : int

Update working copy at path to revision revno. If recurse is true, directories will be recursively updated.

Parameters

path

Path to local working copy.

Note: Relative paths will be resolved as if the current working directory was the one that contains the PHP binary. To use the calling script's working directory, use realpath() or dirname(__FILE__).

revno

Revision number to update to, default is SVN_REVISION_HEAD.

recurse

Whether or not to recursively update directories.

Return Values

Returns new revision number on success, returns FALSE on failure.

Notes

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.

Examples

Example #1 Basic example

This example demonstrates basic usage of this function:

<?php
echo svn_update(realpath('working-copy'));
?>

The above example will output something similar to:

234

See Also

  • svn_checkout() - Checks out a working copy from the repository
  • svn_commit() - Sends changes from the local working copy to the repository
  • » SVN documentation for svn update


TCP Wrappers

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • TCP Functions
    • tcpwrap_check — Performs a tcpwrap check


Introduction

The TCP wrappers provides a classical Unix mechanism which has been designed to check if the remote client is able to connect from the given IP address.


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/tcpwrap.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.


  • « Resource Types
  • TCP Functions »
  • PHP Manual
  • TCP
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


  • « Predefined Constants
  • tcpwrap_check »
  • PHP Manual
  • TCP
  • TCP Functions

TCP Functions

Table of Contents

  • tcpwrap_check — Performs a tcpwrap check


Performs a tcpwrap check

  • « TCP Functions
  • Varnish »
  • PHP Manual
  • TCP Functions
  • Performs a tcpwrap check

tcpwrap_check

(PECL tcpwrap >= 0.1.0)

tcpwrap_check — Performs a tcpwrap check

Description

tcpwrap_check ( string $daemon , string $address [, string $user [, bool $nodns = FALSE ]] ) : bool

This function consults the /etc/hosts.allow and /etc/hosts.deny files to check if access to service daemon should be granted or denied for a client.

Parameters

daemon

The service name.

address

The client remote address. Can be either an IP address or a domain name.

user

An optional user name.

nodns

If address looks like domain name then DNS is used to resolve it to IP address; set nodns to TRUE to avoid this.

Return Values

This function returns TRUE if access should be granted, FALSE otherwise.

Examples

Example #1 Deny all connections from localhost

If your /etc/hosts.deny file contains:

php: 127.0.0.1

And your code looks like:

<?php
if (!tcpwrap_check('php', $_SERVER['REMOTE_ADDR'])) {
  die('You are not welcome here');
}
?>

See Also

For more details please consult hosts_access(3) man page.


Varnish

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic VarnishAdmin usage
    • Basic VarnishStat usage
    • Basic VarnishLog usage
  • VarnishAdmin — The VarnishAdmin class
    • VarnishAdmin::auth — Authenticate on a varnish instance
    • VarnishAdmin::ban — Ban URLs using a VCL expression
    • VarnishAdmin::banUrl — Ban an URL using a VCL expression
    • VarnishAdmin::clearPanic — Clear varnish instance panic messages
    • VarnishAdmin::connect — Connect to a varnish instance administration interface
    • VarnishAdmin::__construct — VarnishAdmin constructor
    • VarnishAdmin::disconnect — Disconnect from a varnish instance administration interface
    • VarnishAdmin::getPanic — Get the last panic message on a varnish instance
    • VarnishAdmin::getParams — Fetch current varnish instance configuration parameters
    • VarnishAdmin::isRunning — Check if the varnish slave process is currently running
    • VarnishAdmin::setCompat — Set the class compat configuration param
    • VarnishAdmin::setHost — Set the class host configuration param
    • VarnishAdmin::setIdent — Set the class ident configuration param
    • VarnishAdmin::setParam — Set configuration param on the current varnish instance
    • VarnishAdmin::setPort — Set the class port configuration param
    • VarnishAdmin::setSecret — Set the class secret configuration param
    • VarnishAdmin::setTimeout — Set the class timeout configuration param
    • VarnishAdmin::start — Start varnish worker process
    • VarnishAdmin::stop — Stop varnish worker process
  • VarnishStat — The VarnishStat class
    • VarnishStat::__construct — VarnishStat constructor
    • VarnishStat::getSnapshot — Get the current varnish instance statistics snapshot
  • VarnishLog — The VarnishLog class
    • VarnishLog::__construct — Varnishlog constructor
    • VarnishLog::getLine — Get next log line
    • VarnishLog::getTagName — Get the log tag string representation by its index


Introduction

Varnish Cache is an open source, state of the art web application accelerator. The extension makes it possible to interact with a running varnish instance through TCP socket or shared memory.


Requirements

To use this extension, you will need Varnish Cache of the version >=3.0 installed, available on the » Varnish Cache homepage


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/varnish.

A DLL for this PECL extension is available under » http://windows.php.net/downloads/pecl/releases/varnish/.


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.

VARNISH_STATUS_SYNTAX (integer)
VARNISH_STATUS_UNKNOWN (integer)
VARNISH_STATUS_UNIMPL (integer)
VARNISH_STATUS_TOOFEW (integer)
VARNISH_STATUS_TOOMANY (integer)
VARNISH_STATUS_PARAM (integer)
VARNISH_STATUS_AUTH (integer)
VARNISH_STATUS_OK (integer)
VARNISH_STATUS_CANT (integer)
VARNISH_STATUS_COMMS (integer)
VARNISH_STATUS_CLOSE (integer)
VARNISH_CONFIG_IDENT (string)
VARNISH_CONFIG_HOST (string)
VARNISH_CONFIG_PORT (string)
VARNISH_CONFIG_TIMEOUT (string)
VARNISH_CONFIG_SECRET (string)
VARNISH_CONFIG_COMPAT (string)
VARNISH_COMPAT_2 (integer)
VARNISH_COMPAT_3 (integer)


Examples

Table of Contents

  • Basic VarnishAdmin usage
  • Basic VarnishStat usage
  • Basic VarnishLog usage


Basic VarnishAdmin usage

The example illustrates a simple usage of the ban functionality

Example #1 Ban an URL

<?php

$args = array(
    VARNISH_CONFIG_HOST    => "::1",
    VARNISH_CONFIG_PORT    => 6082,
    VARNISH_CONFIG_SECRET  => "5174826b-8595-4958-aa7a-0609632ad7ca",
    VARNISH_CONFIG_TIMEOUT => 300,
);

$va = new VarnishAdmin($args);

try {
    if(!$va->connect()) {
        throw new VarnishException("Connection failed\n");
    }
} catch (VarnishException $e) {
    echo $e->getMessage();
    exit(3);
}

try {
    if(!$va->auth()) {
        throw new VarnishException("Auth failed\n");
    }
} catch (VarnishException $e) {
    echo $e->getMessage();
    exit(3);
}

try {
    $status = $va->ban('req.url ~ "^/$"');
    if (VARNISH_STATUS_OK != $status) {
        throw new VarnishException("Ban method returned $status status\n");
    }
} catch (VarnishException $e) {
    echo $e->getMessage();
    exit(3);
}

exit(0);

?>


Basic VarnishStat usage

The example illustrates getting varnish statistic snapshot from shared memory

Example #1 Get statistic snapshot

<?php

$vs = new VarnishStat;

try {
    $data = $vs->getSnapshot();
} catch (VarnishException $e) {
    echo $e->getMessage();
    exit(3);
}

exit(0);
?>


Basic VarnishLog usage

The example illustrates reading varnish log lines from shared memory

Example #1 Read varnish shared memory log

<?php

$vl = new VarnishLog;
while(1) {
    $line = $vl->getLine();
    printf("%s %d %s", VarnishLog::getTagName($line['tag'], $line['id'],
    $line['data']);
}

exit(0);
?>


The VarnishAdmin class

(PECL varnish >= 0.3)

Introduction

Class synopsis

VarnishAdmin {
/* Methods */
public auth ( void ) : bool
public ban ( string $vcl_regex ) : int
public banUrl ( string $vcl_regex ) : int
public clearPanic ( void ) : int
public connect ( void ) : bool
public __construct ([ array $args ] )
public disconnect ( void ) : bool
public getPanic ( void ) : string
public getParams ( void ) : array
public isRunning ( void ) : bool
public setCompat ( int $compat ) : void
public setHost ( string $host ) : void
public setIdent ( string $ident ) : void
public setParam ( string $name , string|integer $value ) : int
public setPort ( int $port ) : void
public setSecret ( string $secret ) : void
public setTimeout ( int $timeout ) : void
public start ( void ) : int
public stop ( void ) : int
}

Table of Contents

  • VarnishAdmin::auth — Authenticate on a varnish instance
  • VarnishAdmin::ban — Ban URLs using a VCL expression
  • VarnishAdmin::banUrl — Ban an URL using a VCL expression
  • VarnishAdmin::clearPanic — Clear varnish instance panic messages
  • VarnishAdmin::connect — Connect to a varnish instance administration interface
  • VarnishAdmin::__construct — VarnishAdmin constructor
  • VarnishAdmin::disconnect — Disconnect from a varnish instance administration interface
  • VarnishAdmin::getPanic — Get the last panic message on a varnish instance
  • VarnishAdmin::getParams — Fetch current varnish instance configuration parameters
  • VarnishAdmin::isRunning — Check if the varnish slave process is currently running
  • VarnishAdmin::setCompat — Set the class compat configuration param
  • VarnishAdmin::setHost — Set the class host configuration param
  • VarnishAdmin::setIdent — Set the class ident configuration param
  • VarnishAdmin::setParam — Set configuration param on the current varnish instance
  • VarnishAdmin::setPort — Set the class port configuration param
  • VarnishAdmin::setSecret — Set the class secret configuration param
  • VarnishAdmin::setTimeout — Set the class timeout configuration param
  • VarnishAdmin::start — Start varnish worker process
  • VarnishAdmin::stop — Stop varnish worker process


Authenticate on a varnish instance

  • « VarnishAdmin
  • VarnishAdmin::ban »
  • PHP Manual
  • VarnishAdmin
  • Authenticate on a varnish instance

VarnishAdmin::auth

(PECL varnish >= 0.3)

VarnishAdmin::auth — Authenticate on a varnish instance

Description

public VarnishAdmin::auth ( void ) : bool

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.


Ban URLs using a VCL expression

  • « VarnishAdmin::auth
  • VarnishAdmin::banUrl »
  • PHP Manual
  • VarnishAdmin
  • Ban URLs using a VCL expression

VarnishAdmin::ban

(PECL varnish >= 0.3)

VarnishAdmin::ban — Ban URLs using a VCL expression

Description

public VarnishAdmin::ban ( string $vcl_regex ) : int

Parameters

vcl_regex

Varnish VCL expression. It's based on the varnish ban command.

Return Values

Returns the varnish command status.


Ban an URL using a VCL expression

  • « VarnishAdmin::ban
  • VarnishAdmin::clearPanic »
  • PHP Manual
  • VarnishAdmin
  • Ban an URL using a VCL expression

VarnishAdmin::banUrl

(PECL varnish >= 0.3)

VarnishAdmin::banUrl — Ban an URL using a VCL expression

Description

public VarnishAdmin::banUrl ( string $vcl_regex ) : int

Parameters

vcl_regex

URL regular expression in PCRE compatible syntax. It's based on the ban.url varnish command.

Return Values

Returns the varnish command status.


Clear varnish instance panic messages

  • « VarnishAdmin::banUrl
  • VarnishAdmin::connect »
  • PHP Manual
  • VarnishAdmin
  • Clear varnish instance panic messages

VarnishAdmin::clearPanic

(PECL varnish >= 0.4)

VarnishAdmin::clearPanic — Clear varnish instance panic messages

Description

public VarnishAdmin::clearPanic ( void ) : int

Parameters

This function has no parameters.

Return Values

Returns the varnish command status.


Connect to a varnish instance administration interface

  • « VarnishAdmin::clearPanic
  • VarnishAdmin::__construct »
  • PHP Manual
  • VarnishAdmin
  • Connect to a varnish instance administration interface

VarnishAdmin::connect

(PECL varnish >= 0.3)

VarnishAdmin::connect — Connect to a varnish instance administration interface

Description

public VarnishAdmin::connect ( void ) : bool

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.


VarnishAdmin constructor

  • « VarnishAdmin::connect
  • VarnishAdmin::disconnect »
  • PHP Manual
  • VarnishAdmin
  • VarnishAdmin constructor

VarnishAdmin::__construct

(PECL varnish >= 0.3)

VarnishAdmin::__construct — VarnishAdmin constructor

Description

public VarnishAdmin::__construct ([ array $args ] )

Parameters

args

Configuration arguments. The possible keys are:

VARNISH_CONFIG_IDENT - local varnish instance ident
VARNISH_CONFIG_HOST - varnish instance ip
VARNISH_CONFIG_PORT - varnish instance port
VARNISH_CONFIG_SECRET - varnish instance secret
VARNISH_CONFIG_TIMEOUT - connection read timeout
VARNISH_CONFIG_COMPAT - varnish major version compatibility

Return Values

Examples

Example #1 VarnishAdmin::__construct() example

<?php
    $args = array(
        VARNISH_CONFIG_HOST => "::1",
        VARNISH_CONFIG_PORT => 6082,
        VARNISH_CONFIG_SECRET => "5174826b-8595-4958-aa7a-0609632ad7ca",
        VARNISH_CONFIG_TIMEOUT => 300,
    );
    $va = new VarnishAdmin($args);
?>


Disconnect from a varnish instance administration interface

  • « VarnishAdmin::__construct
  • VarnishAdmin::getPanic »
  • PHP Manual
  • VarnishAdmin
  • Disconnect from a varnish instance administration interface

VarnishAdmin::disconnect

(PECL varnish >= 1.0.0)

VarnishAdmin::disconnect — Disconnect from a varnish instance administration interface

Description

public VarnishAdmin::disconnect ( void ) : bool

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.


Get the last panic message on a varnish instance

  • « VarnishAdmin::disconnect
  • VarnishAdmin::getParams »
  • PHP Manual
  • VarnishAdmin
  • Get the last panic message on a varnish instance

VarnishAdmin::getPanic

(PECL varnish >= 0.4)

VarnishAdmin::getPanic — Get the last panic message on a varnish instance

Description

public VarnishAdmin::getPanic ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns the last panic message on the current varnish instance.


Fetch current varnish instance configuration parameters

  • « VarnishAdmin::getPanic
  • VarnishAdmin::isRunning »
  • PHP Manual
  • VarnishAdmin
  • Fetch current varnish instance configuration parameters

VarnishAdmin::getParams

(PECL varnish >= 0.4)

VarnishAdmin::getParams — Fetch current varnish instance configuration parameters

Description

public VarnishAdmin::getParams ( void ) : array

Parameters

This function has no parameters.

Return Values

Returns an array with the varnish configuration parameters.


Check if the varnish slave process is currently running

  • « VarnishAdmin::getParams
  • VarnishAdmin::setCompat »
  • PHP Manual
  • VarnishAdmin
  • Check if the varnish slave process is currently running

VarnishAdmin::isRunning

(PECL varnish >= 0.3)

VarnishAdmin::isRunning — Check if the varnish slave process is currently running

Description

public VarnishAdmin::isRunning ( void ) : bool

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.


Set the class compat configuration param

  • « VarnishAdmin::isRunning
  • VarnishAdmin::setHost »
  • PHP Manual
  • VarnishAdmin
  • Set the class compat configuration param

VarnishAdmin::setCompat

(PECL varnish >= 0.9.2)

VarnishAdmin::setCompat — Set the class compat configuration param

Description

public VarnishAdmin::setCompat ( int $compat ) : void

Parameters

compat

Varnish compatibility option.

Return Values


Set the class host configuration param

  • « VarnishAdmin::setCompat
  • VarnishAdmin::setIdent »
  • PHP Manual
  • VarnishAdmin
  • Set the class host configuration param

VarnishAdmin::setHost

(PECL varnish >= 0.8)

VarnishAdmin::setHost — Set the class host configuration param

Description

public VarnishAdmin::setHost ( string $host ) : void

Parameters

host

Connection host configuration parameter.

Return Values


Set the class ident configuration param

  • « VarnishAdmin::setHost
  • VarnishAdmin::setParam »
  • PHP Manual
  • VarnishAdmin
  • Set the class ident configuration param

VarnishAdmin::setIdent

(PECL varnish >= 0.8)

VarnishAdmin::setIdent — Set the class ident configuration param

Description

public VarnishAdmin::setIdent ( string $ident ) : void

Parameters

ident

Connection ident configuration parameter.

Return Values


Set configuration param on the current varnish instance

  • « VarnishAdmin::setIdent
  • VarnishAdmin::setPort »
  • PHP Manual
  • VarnishAdmin
  • Set configuration param on the current varnish instance

VarnishAdmin::setParam

(PECL varnish >= 0.4)

VarnishAdmin::setParam — Set configuration param on the current varnish instance

Description

public VarnishAdmin::setParam ( string $name , string|integer $value ) : int

Parameters

name

Varnish configuration param name.

value

Varnish configuration param value.

Return Values

Returns the varnish command status.


Set the class port configuration param

  • « VarnishAdmin::setParam
  • VarnishAdmin::setSecret »
  • PHP Manual
  • VarnishAdmin
  • Set the class port configuration param

VarnishAdmin::setPort

(PECL varnish >= 0.8)

VarnishAdmin::setPort — Set the class port configuration param

Description

public VarnishAdmin::setPort ( int $port ) : void

Parameters

port

Connection port configuration parameter.

Return Values


Set the class secret configuration param

  • « VarnishAdmin::setPort
  • VarnishAdmin::setTimeout »
  • PHP Manual
  • VarnishAdmin
  • Set the class secret configuration param

VarnishAdmin::setSecret

(PECL varnish >= 0.8)

VarnishAdmin::setSecret — Set the class secret configuration param

Description

public VarnishAdmin::setSecret ( string $secret ) : void

Parameters

secret

Connection secret configuration parameter.

Return Values


Set the class timeout configuration param

  • « VarnishAdmin::setSecret
  • VarnishAdmin::start »
  • PHP Manual
  • VarnishAdmin
  • Set the class timeout configuration param

VarnishAdmin::setTimeout

(PECL varnish >= 0.8)

VarnishAdmin::setTimeout — Set the class timeout configuration param

Description

public VarnishAdmin::setTimeout ( int $timeout ) : void

Parameters

timeout

Connection timeout configuration parameter.

Return Values


Start varnish worker process

  • « VarnishAdmin::setTimeout
  • VarnishAdmin::stop »
  • PHP Manual
  • VarnishAdmin
  • Start varnish worker process

VarnishAdmin::start

(PECL varnish >= 0.3)

VarnishAdmin::start — Start varnish worker process

Description

public VarnishAdmin::start ( void ) : int

Parameters

This function has no parameters.

Return Values

Returns the varnish command status.


Stop varnish worker process

  • « VarnishAdmin::start
  • VarnishStat »
  • PHP Manual
  • VarnishAdmin
  • Stop varnish worker process

VarnishAdmin::stop

(PECL varnish >= 0.3)

VarnishAdmin::stop — Stop varnish worker process

Description

public VarnishAdmin::stop ( void ) : int

Parameters

This function has no parameters.

Return Values

Returns the varnish command status.


The VarnishStat class

(PECL varnish >= 0.3)

Introduction

Class synopsis

VarnishStat {
/* Methods */
public __construct ([ array $args ] )
public getSnapshot ( void ) : array
}

Table of Contents

  • VarnishStat::__construct — VarnishStat constructor
  • VarnishStat::getSnapshot — Get the current varnish instance statistics snapshot


VarnishStat constructor

  • « VarnishStat
  • VarnishStat::getSnapshot »
  • PHP Manual
  • VarnishStat
  • VarnishStat constructor

VarnishStat::__construct

(PECL varnish >= 0.3)

VarnishStat::__construct — VarnishStat constructor

Description

public VarnishStat::__construct ([ array $args ] )

Parameters

args

Configuration arguments. The possible keys are:

VARNISH_CONFIG_IDENT - local varnish instance ident path

Return Values


Get the current varnish instance statistics snapshot

  • « VarnishStat::__construct
  • VarnishLog »
  • PHP Manual
  • VarnishStat
  • Get the current varnish instance statistics snapshot

VarnishStat::getSnapshot

(PECL varnish >= 0.3)

VarnishStat::getSnapshot — Get the current varnish instance statistics snapshot

Description

public VarnishStat::getSnapshot ( void ) : array

Parameters

This function has no parameters.

Return Values

Array with the varnish statistic snapshot. The array keys are identical to that in the varnishstat tool.


The VarnishLog class

(PECL varnish >= 0.6)

Introduction

Class synopsis

VarnishLog {
/* Constants */
const integer TAG_Debug = 0 ;
const integer TAG_Error = 1 ;
const integer TAG_CLI = 2 ;
const integer TAG_StatSess = 3 ;
const integer TAG_ReqEnd = 4 ;
const integer TAG_SessionOpen = 5 ;
const integer TAG_SessionClose = 6 ;
const integer TAG_BackendOpen = 7 ;
const integer TAG_BackendXID = 8 ;
const integer TAG_BackendReuse = 9 ;
const integer TAG_BackendClose = 10 ;
const integer TAG_HttpGarbage = 11 ;
const integer TAG_Backend = 12 ;
const integer TAG_Length = 13 ;
const integer TAG_FetchError = 14 ;
const integer TAG_RxRequest = 15 ;
const integer TAG_RxResponse = 16 ;
const integer TAG_RxStatus = 17 ;
const integer TAG_RxURL = 18 ;
const integer TAG_RxProtocol = 19 ;
const integer TAG_RxHeader = 20 ;
const integer TAG_TxRequest = 21 ;
const integer TAG_TxResponse = 22 ;
const integer TAG_TxStatus = 23 ;
const integer TAG_TxURL = 24 ;
const integer TAG_TxProtocol = 25 ;
const integer TAG_TxHeader = 26 ;
const integer TAG_ObjRequest = 27 ;
const integer TAG_ObjResponse = 28 ;
const integer TAG_ObjStatus = 29 ;
const integer TAG_ObjURL = 30 ;
const integer TAG_ObjProtocol = 31 ;
const integer TAG_ObjHeader = 32 ;
const integer TAG_LostHeader = 33 ;
const integer TAG_TTL = 34 ;
const integer TAG_Fetch_Body = 35 ;
const integer TAG_VCL_acl = 36 ;
const integer TAG_VCL_call = 37 ;
const integer TAG_VCL_trace = 38 ;
const integer TAG_VCL_return = 39 ;
const integer TAG_VCL_error = 40 ;
const integer TAG_ReqStart = 41 ;
const integer TAG_Hit = 42 ;
const integer TAG_HitPass = 43 ;
const integer TAG_ExpBan = 44 ;
const integer TAG_ExpKill = 45 ;
const integer TAG_WorkThread = 46 ;
const integer TAG_ESI_xmlerror = 47 ;
const integer TAG_Hash = 48 ;
const integer TAG_Backend_health = 49 ;
const integer TAG_VCL_Log = 50 ;
const integer TAG_Gzip = 51 ;
/* Methods */
public __construct ([ array $args ] )
public getLine ( void ) : array
public static getTagName ( int $index ) : string
}

Predefined Constants

VarnishLog::TAG_Debug

VarnishLog::TAG_Error

VarnishLog::TAG_CLI

VarnishLog::TAG_StatSess

VarnishLog::TAG_ReqEnd

VarnishLog::TAG_SessionOpen

VarnishLog::TAG_SessionClose

VarnishLog::TAG_BackendOpen

VarnishLog::TAG_BackendXID

VarnishLog::TAG_BackendReuse

VarnishLog::TAG_BackendClose

VarnishLog::TAG_HttpGarbage

VarnishLog::TAG_Backend

VarnishLog::TAG_Length

VarnishLog::TAG_FetchError

VarnishLog::TAG_RxRequest

VarnishLog::TAG_RxResponse

VarnishLog::TAG_RxStatus

VarnishLog::TAG_RxURL

VarnishLog::TAG_RxProtocol

VarnishLog::TAG_RxHeader

VarnishLog::TAG_TxRequest

VarnishLog::TAG_TxResponse

VarnishLog::TAG_TxStatus

VarnishLog::TAG_TxURL

VarnishLog::TAG_TxProtocol

VarnishLog::TAG_TxHeader

VarnishLog::TAG_ObjRequest

VarnishLog::TAG_ObjResponse

VarnishLog::TAG_ObjStatus

VarnishLog::TAG_ObjURL

VarnishLog::TAG_ObjProtocol

VarnishLog::TAG_ObjHeader

VarnishLog::TAG_LostHeader

VarnishLog::TAG_TTL

VarnishLog::TAG_Fetch_Body

VarnishLog::TAG_VCL_acl

VarnishLog::TAG_VCL_call

VarnishLog::TAG_VCL_trace

VarnishLog::TAG_VCL_return

VarnishLog::TAG_VCL_error

VarnishLog::TAG_ReqStart

VarnishLog::TAG_Hit

VarnishLog::TAG_HitPass

VarnishLog::TAG_ExpBan

VarnishLog::TAG_ExpKill

VarnishLog::TAG_WorkThread

VarnishLog::TAG_ESI_xmlerror

VarnishLog::TAG_Hash

VarnishLog::TAG_Backend_health

VarnishLog::TAG_VCL_Log

VarnishLog::TAG_Gzip

Table of Contents

  • VarnishLog::__construct — Varnishlog constructor
  • VarnishLog::getLine — Get next log line
  • VarnishLog::getTagName — Get the log tag string representation by its index


Varnishlog constructor

  • « VarnishLog
  • VarnishLog::getLine »
  • PHP Manual
  • VarnishLog
  • Varnishlog constructor

VarnishLog::__construct

(PECL varnish >= 0.6)

VarnishLog::__construct — Varnishlog constructor

Description

public VarnishLog::__construct ([ array $args ] )

Parameters

args

Configuration arguments. The possible keys are:

VARNISH_CONFIG_IDENT - local varnish instance ident path

Return Values


Get next log line

  • « VarnishLog::__construct
  • VarnishLog::getTagName »
  • PHP Manual
  • VarnishLog
  • Get next log line

VarnishLog::getLine

(PECL varnish >= 0.6)

VarnishLog::getLine — Get next log line

Description

public VarnishLog::getLine ( void ) : array

Parameters

This function has no parameters.

Return Values

Returns an array with the log line data.


Get the log tag string representation by its index

  • « VarnishLog::getLine
  • YAZ »
  • PHP Manual
  • VarnishLog
  • Get the log tag string representation by its index

VarnishLog::getTagName

(PECL varnish >= 0.6)

VarnishLog::getTagName — Get the log tag string representation by its index

Description

public static VarnishLog::getTagName ( int $index ) : string

Parameters

index

Log tag index.

Return Values

Returns the log tag name as string.


YAZ

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • YAZ Functions
    • yaz_addinfo — Returns additional error information
    • yaz_ccl_conf — Configure CCL parser
    • yaz_ccl_parse — Invoke CCL Parser
    • yaz_close — Close YAZ connection
    • yaz_connect — Prepares for a connection to a Z39.50 server
    • yaz_database — Specifies the databases within a session
    • yaz_element — Specifies Element-Set Name for retrieval
    • yaz_errno — Returns error number
    • yaz_error — Returns error description
    • yaz_es_result — Inspects Extended Services Result
    • yaz_es — Prepares for an Extended Service Request
    • yaz_get_option — Returns value of option for connection
    • yaz_hits — Returns number of hits for last search
    • yaz_itemorder — Prepares for Z39.50 Item Order with an ILL-Request package
    • yaz_present — Prepares for retrieval (Z39.50 present)
    • yaz_range — Specifies a range of records to retrieve
    • yaz_record — Returns a record
    • yaz_scan_result — Returns Scan Response result
    • yaz_scan — Prepares for a scan
    • yaz_schema — Specifies schema for retrieval
    • yaz_search — Prepares for a search
    • yaz_set_option — Sets one or more options for connection
    • yaz_sort — Sets sorting criteria
    • yaz_syntax — Specifies the preferred record syntax for retrieval
    • yaz_wait — Wait for Z39.50 requests to complete


Introduction

This extension offers a PHP interface to the YAZ toolkit that implements the » Z39.50 Protocol for Information Retrieval. With this extension you can easily implement a Z39.50 origin (client) that searches or scans Z39.50 targets (servers) in parallel.

The module hides most of the complexity of Z39.50 so it should be fairly easy to use. It supports persistent stateless connections very similar to those offered by the various RDB APIs that are available for PHP. This means that sessions are stateless but shared among users, thus saving the connect and initialize phase steps in most cases.

YAZ is available at » http://www.indexdata.dk/yaz/. You can find news information, example scripts, etc. for this extension at » http://www.indexdata.dk/phpyaz/.

Note:

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.0.0.


Requirements

Obtain YAZ (ANSI/NISO Z39.50 support) and install it. YAZ can be fetched in source or in various prebuilt packages from the » YAZ archive. Systems such as Debian GNU/Linux, Suse Linux, FreeBSD also has YAZ as part of their distribution.


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/yaz

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Note: Information specific to Windows users

php_yaz.dll depends on yaz.dll. The yaz.dll is part of the Win32 ZIP from the PHP site. It is also part of the Windows YAZ install available from the » YAZ WIN32 area.

On windows, don't forget to add the PHP directory to the PATH, so that the yaz.dll file can be found by the system.

Warning

The IMAP, recode, YAZ and Cyrus 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.


  • « Resource Types
  • Examples »
  • PHP Manual
  • YAZ
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


Examples

PHP/YAZ keeps track of connections with targets (Z-Associations). A resource represents a connection to a target.

The script below demonstrates the parallel searching feature of the API. When invoked with no arguments it prints a query form; else (arguments are supplied) it searches the targets as given in array host.

Example #1 Parallel searching using Yaz

<?php
$host=$_REQUEST[host];
$query=$_REQUEST[query];
$num_hosts = count($host);
if (empty($query) || count($host) == 0) {
    echo '<form method="get">
    <input type="checkbox"
    name="host[]" value="bagel.indexdata.dk/gils" />
        GILS test
    <input type="checkbox"
    name="host[]" value="localhost:9999/Default" />
        local test
    <input type="checkbox" checked="checked"
    name="host[]" value="z3950.loc.gov:7090/voyager" />
        Library of Congress
    <br />
    RPN Query:
    <input type="text" size="30" name="query" />
    <input type="submit" name="action" value="Search" />
    </form>
    ';
} else {
    echo 'You searched for ' . htmlspecialchars($query) . '<br />';
    for ($i = 0; $i < $num_hosts; $i++) {
        $id[] = yaz_connect($host[$i]);
        yaz_syntax($id[$i], "usmarc");
        yaz_range($id[$i], 1, 10);
        yaz_search($id[$i], "rpn", $query);
    }
    yaz_wait();
    for ($i = 0; $i < $num_hosts; $i++) {
        echo '<hr />' . $host[$i] . ':';
        $error = yaz_error($id[$i]);
        if (!empty($error)) {
            echo "Error: $error";
        } else {
            $hits = yaz_hits($id[$i]);
            echo "Result Count $hits";
        }
        echo '<dl>';
        for ($p = 1; $p <= 10; $p++) {
            $rec = yaz_record($id[$i], $p, "string");
            if (empty($rec)) continue;
            echo "<dt><b>$p</b></dt><dd>";
            echo nl2br($rec);
            echo "</dd>";
        }
        echo '</dl>';
    }
}
?>


YAZ Functions

Table of Contents

  • yaz_addinfo — Returns additional error information
  • yaz_ccl_conf — Configure CCL parser
  • yaz_ccl_parse — Invoke CCL Parser
  • yaz_close — Close YAZ connection
  • yaz_connect — Prepares for a connection to a Z39.50 server
  • yaz_database — Specifies the databases within a session
  • yaz_element — Specifies Element-Set Name for retrieval
  • yaz_errno — Returns error number
  • yaz_error — Returns error description
  • yaz_es_result — Inspects Extended Services Result
  • yaz_es — Prepares for an Extended Service Request
  • yaz_get_option — Returns value of option for connection
  • yaz_hits — Returns number of hits for last search
  • yaz_itemorder — Prepares for Z39.50 Item Order with an ILL-Request package
  • yaz_present — Prepares for retrieval (Z39.50 present)
  • yaz_range — Specifies a range of records to retrieve
  • yaz_record — Returns a record
  • yaz_scan_result — Returns Scan Response result
  • yaz_scan — Prepares for a scan
  • yaz_schema — Specifies schema for retrieval
  • yaz_search — Prepares for a search
  • yaz_set_option — Sets one or more options for connection
  • yaz_sort — Sets sorting criteria
  • yaz_syntax — Specifies the preferred record syntax for retrieval
  • yaz_wait — Wait for Z39.50 requests to complete


Returns additional error information

  • « YAZ Functions
  • yaz_ccl_conf »
  • PHP Manual
  • YAZ Functions
  • Returns additional error information

yaz_addinfo

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_addinfo — Returns additional error information

Description

yaz_addinfo ( resource $id ) : string

Returns additional error information for the last request on the server.

With some servers, this function may return the same string as yaz_error().

Parameters

id

The connection resource returned by yaz_connect().

Return Values

A string containing additional error information or an empty string if the last operation was successful or if no additional information was provided by the server.

See Also

  • yaz_error() - Returns error description
  • yaz_errno() - Returns error number


Configure CCL parser

  • « yaz_addinfo
  • yaz_ccl_parse »
  • PHP Manual
  • YAZ Functions
  • Configure CCL parser

yaz_ccl_conf

(PHP 4 >= 4.0.5, PECL yaz >= 0.9.0)

yaz_ccl_conf — Configure CCL parser

Description

yaz_ccl_conf ( resource $id , array $config ) : void

This function configures the CCL query parser for a server with definitions of access points (CCL qualifiers) and their mapping to RPN.

To map a specific CCL query to RPN afterwards call the yaz_ccl_parse() function.

Parameters

id

The connection resource returned by yaz_connect().

config

An array of configuration. Each key of the array is the name of a CCL field and the corresponding value holds a string that specifies a mapping to RPN.

The mapping is a sequence of attribute-type, attribute-value pairs. Attribute-type and attribute-value is separated by an equal sign (=). Each pair is separated by white space.

Additional information can be found on the » CCL page.

Return Values

No value is returned.

Examples

In the example below, the CCL parser is configured to support three CCL fields: ti, au and isbn. Each field is mapped to their BIB-1 equivalent. It is assumed that variable $id is the connection ID.

Example #1 CCL configuration

<?php
$fields = array(
  "ti" => "1=4",
  "au"   => "1=1",
  "isbn" => "1=7"
);
yaz_ccl_conf($id, $fields);
?>

See Also

  • yaz_ccl_parse() - Invoke CCL Parser


Invoke CCL Parser

  • « yaz_ccl_conf
  • yaz_close »
  • PHP Manual
  • YAZ Functions
  • Invoke CCL Parser

yaz_ccl_parse

(PHP 4 >= 4.0.5, PECL yaz >= 0.9.0)

yaz_ccl_parse — Invoke CCL Parser

Description

yaz_ccl_parse ( resource $id , string $query , array &$result ) : bool

This function invokes a CCL parser. It converts a given CCL FIND query to an RPN query which may be passed to the yaz_search() function to perform a search.

To define a set of valid CCL fields call yaz_ccl_conf() prior to this function.

Parameters

id

The connection resource returned by yaz_connect().

query

The CCL FIND query.

result

If the function was executed successfully, this will be an array containing the valid RPN query under the key rpn.

Upon failure, three indexes are set in this array to indicate the cause of failure:

  • errorcode - the CCL error code (integer)

  • errorstring - the CCL error string

  • errorpos - approximate position in query of failure (integer is character position)

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 CCL Parsing

We will try to search using CCL. In the example below, $ccl is a CCL query.

<?php

yaz_ccl_conf($id, $fields);  // see example for yaz_ccl_conf
if (!yaz_ccl_parse($id, $ccl, &$cclresult)) {
    echo 'Error: ' . $cclresult["errorstring"];
} else {
    $rpn = $cclresult["rpn"];
    yaz_search($id, "rpn", $rpn);
}
?>


Close YAZ connection

  • « yaz_ccl_parse
  • yaz_connect »
  • PHP Manual
  • YAZ Functions
  • Close YAZ connection

yaz_close

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_close — Close YAZ connection

Description

yaz_close ( resource $id ) : bool

Closes the connection given by parameter id.

Note:

This function will only close a non-persistent connection opened by setting the persistent option to FALSE with yaz_connect().

Parameters

id

The connection resource returned by yaz_connect().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • yaz_connect() - Prepares for a connection to a Z39.50 server


Prepares for a connection to a Z39.50 server

  • « yaz_close
  • yaz_database »
  • PHP Manual
  • YAZ Functions
  • Prepares for a connection to a Z39.50 server

yaz_connect

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_connect — Prepares for a connection to a Z39.50 server

Description

yaz_connect ( string $zurl [, mixed $options ] ) : mixed

This function returns a connection resource on success, zero on failure.

yaz_connect() prepares for a connection to a Z39.50 server. This function is non-blocking and does not attempt to establish a connection - it merely prepares a connect to be performed later when yaz_wait() is called.

Note:

The » YAZ proxy is a freely available Z39.50 proxy.

Parameters

zurl

A string that takes the form host[:port][/database]. If port is omitted, port 210 is used. If database is omitted Default is used.

options

If given as a string, it is treated as the Z39.50 V2 authentication string (OpenAuth).

If given as an array, the contents of the array serves as options.

user

Username for authentication.

group

Group for authentication.

password

Password for authentication.

cookie

Cookie for session (YAZ proxy).

proxy

Proxy for connection (YAZ proxy).

persistent

A boolean. If TRUE the connection is persistent; If FALSE the connection is not persistent. By default connections are persistent.

Note:

If you open a persistent connection, you won't be able to close it later with yaz_close().

piggyback

A boolean. If TRUE piggyback is enabled for searches; If FALSE piggyback is disabled. By default piggyback is enabled.

Enabling piggyback is more efficient and usually saves a network-round-trip for first time fetches of records. However, a few Z39.50 servers do not support piggyback or they ignore element set names. For those, piggyback should be disabled.

charset

A string that specifies character set to be used in Z39.50 language and character set negotiation. Use strings such as: ISO-8859-1, UTF-8, UTF-16.

Most Z39.50 servers do not support this feature (and thus, this is ignored). Many servers use the ISO-8859-1 encoding for queries and messages. MARC21/USMARC records are not affected by this setting.

preferredMessageSize

An integer that specifies the maximum byte size of all records to be returned by a target during retrieval. See the » Z39.50 standard for more information.

Note:

This option is supported in PECL YAZ 1.0.5 or later.

maximumRecordSize

An integer that specifies the maximum byte size of a single record to be returned by a target during retrieval. This entity is referred to as Exceptional-record-size in the » Z39.50 standard.

Note:

This option is supported in PECL YAZ 1.0.5 or later.

Return Values

A connection resource on success, FALSE on error.

Changelog

Version | Description
4.1.0 | The parameter options was added.

See Also

  • yaz_close() - Close YAZ connection


Specifies the databases within a session

  • « yaz_connect
  • yaz_element »
  • PHP Manual
  • YAZ Functions
  • Specifies the databases within a session

yaz_database

(PHP 4 >= 4.0.6, PECL yaz >= 0.9.0)

yaz_database — Specifies the databases within a session

Description

yaz_database ( resource $id , string $databases ) : bool

This function allows you to change databases within a session by specifying one or more databases to be used in search, retrieval, etc. - overriding databases specified in call to yaz_connect().

Parameters

id

The connection resource returned by yaz_connect().

databases

A string containing one or more databases. Multiple databases are separated by a plus sign +.

Return Values

Returns TRUE on success or FALSE on failure.


Specifies Element-Set Name for retrieval

  • « yaz_database
  • yaz_errno »
  • PHP Manual
  • YAZ Functions
  • Specifies Element-Set Name for retrieval

yaz_element

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_element — Specifies Element-Set Name for retrieval

Description

yaz_element ( resource $id , string $elementset ) : bool

This function sets the element set name for retrieval.

Call this function before yaz_search() or yaz_present() to specify the element set name for records to be retrieved.

Note:

If this function appears to have no effect, see the description of the piggybacking option in yaz_connect().

Parameters

id

The connection resource returned by yaz_connect().

elementset

Most servers support F (for full records) and B (for brief records).

Return Values

Returns TRUE on success or FALSE on failure.


Returns error number

  • « yaz_element
  • yaz_error »
  • PHP Manual
  • YAZ Functions
  • Returns error number

yaz_errno

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_errno — Returns error number

Description

yaz_errno ( resource $id ) : int

Returns an error number for the server (last request) identified by id.

yaz_errno() should be called after network activity for each server - (after yaz_wait() returns) to determine the success or failure of the last operation (e.g. search).

Parameters

id

The connection resource returned by yaz_connect().

Return Values

Returns an error code. The error code is either a Z39.50 diagnostic code (usually a Bib-1 diagnostic) or a client side error code which is generated by PHP/YAZ itself, such as "Connect failed", "Init Rejected", etc.

See Also

  • yaz_error() - Returns error description
  • yaz_addinfo() - Returns additional error information


Returns error description

  • « yaz_errno
  • yaz_es_result »
  • PHP Manual
  • YAZ Functions
  • Returns error description

yaz_error

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_error — Returns error description

Description

yaz_error ( resource $id ) : string

yaz_error() returns an English text message corresponding to the last error number as returned by yaz_errno().

Parameters

id

The connection resource returned by yaz_connect().

Return Values

Returns an error text message for server (last request), identified by parameter id. An empty string is returned if the last operation was successful.

See Also

  • yaz_errno() - Returns error number
  • yaz_addinfo() - Returns additional error information


Inspects Extended Services Result

  • « yaz_error
  • yaz_es »
  • PHP Manual
  • YAZ Functions
  • Inspects Extended Services Result

yaz_es_result

(PHP 4 >= 4.2.0, PECL yaz >= 0.9.0)

yaz_es_result — Inspects Extended Services Result

Description

yaz_es_result ( resource $id ) : array

This function inspects the last returned Extended Service result from a server. An Extended Service is initiated by either yaz_item_order() or yaz_es().

Parameters

id

The connection resource returned by yaz_connect().

Return Values

Returns array with element targetReference for the reference for the extended service operation (generated and returned from the server).

See Also

  • yaz_es() - Prepares for an Extended Service Request


Prepares for an Extended Service Request

  • « yaz_es_result
  • yaz_get_option »
  • PHP Manual
  • YAZ Functions
  • Prepares for an Extended Service Request

yaz_es

(PECL yaz >= 0.9.0)

yaz_es — Prepares for an Extended Service Request

Description

yaz_es ( resource $id , string $type , array $args ) : void

This function prepares for an Extended Service Request. Extended Services is family of various Z39.50 facilities, such as Record Update, Item Order, Database administration etc.

Note:

Many Z39.50 Servers do not support Extended Services.

The yaz_es() creates an Extended Service Request packages and puts it into a queue of operations. Use yaz_wait() to send the request(s) to the server. After completion of yaz_wait() the result of the Extended Service operation should be expected with a call to yaz_es_result().

Parameters

id

The connection resource returned by yaz_connect().

type

A string which represents the type of the Extended Service: itemorder (Item Order), create (Create Database), drop (Drop Database), commit (Commit Operation), update (Update Record), xmlupdate (XML Update). Each type is specified in the following section.

args

An array with extended service options plus package specific options. The options are identical to those offered in the C API of ZOOM C. Refer to the ZOOM » Extended Services.

Return Values

No value is returned.

Examples

Example #1 Record Update

<?php
$con = yaz_connect("myhost/database");
$args = array (
    "record" => "<gils><title>some title</title></gils>",
    "syntax" => "xml",
    "action" => "specialUpdate"
);
yaz_es($con, "update", $args);
yaz_wait();
$result = yaz_es_result($id);
?>

See Also

  • yaz_es_result() - Inspects Extended Services Result


Returns value of option for connection

  • « yaz_es
  • yaz_hits »
  • PHP Manual
  • YAZ Functions
  • Returns value of option for connection

yaz_get_option

(PECL yaz >= 0.9.0)

yaz_get_option — Returns value of option for connection

Description

yaz_get_option ( resource $id , string $name ) : string

Returns the value of the option specified with name.

Parameters

id

The connection resource returned by yaz_connect().

name

The option name.

Return Values

Returns the value of the specified option or an empty string if the option wasn't set.

See Also

  • The description of yaz_set_option() - Sets one or more options for connection for available options


Returns number of hits for last search

  • « yaz_get_option
  • yaz_itemorder »
  • PHP Manual
  • YAZ Functions
  • Returns number of hits for last search

yaz_hits

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_hits — Returns number of hits for last search

Description

yaz_hits ( resource $id [, array &$searchresult ] ) : int

yaz_hits() returns the number of hits for the last search.

Parameters

id

The connection resource returned by yaz_connect().

searchresult

Result array for detailed search result information.

Return Values

Returns the number of hits for the last search or 0 if no search was performed.

The search result array (if supplied) holds information that is returned by a Z39.50 server in the SearchResult-1 format part of a search response. The SearchResult-1 format can be used to obtain information about hit counts for various parts of the query (subquery). In particular, it is possible to obtain hit counts for the individual search terms in a query. Information for first subquery is in $array[0], second subquery in $array[1], and so forth.

searchresult members
Element | Description
id | Sub query ID2 (string)
count | Result count / hits (integer)
subquery.term | Sub query term (string)
interpretation.term | Interpretated sub query term (string)
recommendation.term | Recommended sub query term (string)

Note:

The SearchResult facility requires PECL YAZ 1.0.5 or later and YAZ 2.1.9 or later.

Note:

Very few Z39.50 implementations support the SearchResult facility.


Prepares for Z39.50 Item Order with an ILL-Request package

  • « yaz_hits
  • yaz_present »
  • PHP Manual
  • YAZ Functions
  • Prepares for Z39.50 Item Order with an ILL-Request package

yaz_itemorder

(PHP 4 >= 4.0.5, PECL yaz >= 0.9.0)

yaz_itemorder — Prepares for Z39.50 Item Order with an ILL-Request package

Description

yaz_itemorder ( resource $id , array $args ) : void

This function prepares for an Extended Services request using the Profile for the Use of Z39.50 Item Order Extended Service to Transport ILL (Profile/1). See » this and the » specification.

Parameters

id

The connection resource returned by yaz_connect().

args

Must be an associative array with information about the Item Order request to be sent. The key of the hash is the name of the corresponding ASN.1 tag path. For example, the ISBN below the Item-ID has the key item-id,ISBN.

The ILL-Request parameters are:

protocol-version-num
transaction-id,initial-requester-id,person-or-institution-symbol,person
transaction-id,initial-requester-id,person-or-institution-symbol,institution
transaction-id,initial-requester-id,name-of-person-or-institution,name-of-person
transaction-id,initial-requester-id,name-of-person-or-institution,name-of-institution
transaction-id,transaction-group-qualifier
transaction-id,transaction-qualifier
transaction-id,sub-transaction-qualifier
service-date-time,this,date
service-date-time,this,time
service-date-time,original,date
service-date-time,original,time
requester-id,person-or-institution-symbol,person
requester-id,person-or-institution-symbol,institution
requester-id,name-of-person-or-institution,name-of-person
requester-id,name-of-person-or-institution,name-of-institution
responder-id,person-or-institution-symbol,person
responder-id,person-or-institution-symbol,institution
responder-id,name-of-person-or-institution,name-of-person
responder-id,name-of-person-or-institution,name-of-institution
transaction-type
delivery-address,postal-address,name-of-person-or-institution,name-of-person
delivery-address,postal-address,name-of-person-or-institution,name-of-institution
delivery-address,postal-address,extended-postal-delivery-address
delivery-address,postal-address,street-and-number
delivery-address,postal-address,post-office-box
delivery-address,postal-address,city
delivery-address,postal-address,region
delivery-address,postal-address,country
delivery-address,postal-address,postal-code
delivery-address,electronic-address,telecom-service-identifier
delivery-address,electronic-address,telecom-service-addreess
billing-address,postal-address,name-of-person-or-institution,name-of-person
billing-address,postal-address,name-of-person-or-institution,name-of-institution
billing-address,postal-address,extended-postal-delivery-address
billing-address,postal-address,street-and-number
billing-address,postal-address,post-office-box
billing-address,postal-address,city
billing-address,postal-address,region
billing-address,postal-address,country
billing-address,postal-address,postal-code
billing-address,electronic-address,telecom-service-identifier
billing-address,electronic-address,telecom-service-addreess
ill-service-type
requester-optional-messages,can-send-RECEIVED
requester-optional-messages,can-send-RETURNED
requester-optional-messages,requester-SHIPPED
requester-optional-messages,requester-CHECKED-IN
search-type,level-of-service
search-type,need-before-date
search-type,expiry-date
search-type,expiry-flag
place-on-hold
client-id,client-name
client-id,client-status
client-id,client-identifier
item-id,item-type
item-id,call-number
item-id,author
item-id,title
item-id,sub-title
item-id,sponsoring-body
item-id,place-of-publication
item-id,publisher
item-id,series-title-number
item-id,volume-issue
item-id,edition
item-id,publication-date
item-id,publication-date-of-component
item-id,author-of-article
item-id,title-of-article
item-id,pagination
item-id,ISBN
item-id,ISSN
item-id,additional-no-letters
item-id,verification-reference-source
copyright-complicance
retry-flag
forward-flag
requester-note
forward-note

There are also a few parameters that are part of the Extended Services Request package and the ItemOrder package:

package-name
user-id
contact-name
contact-phone
contact-email
itemorder-item

Return Values

No value is returned.


Prepares for retrieval (Z39.50 present)

  • « yaz_itemorder
  • yaz_range »
  • PHP Manual
  • YAZ Functions
  • Prepares for retrieval (Z39.50 present)

yaz_present

(PHP 4 >= 4.0.5, PECL yaz >= 0.9.0)

yaz_present — Prepares for retrieval (Z39.50 present)

Description

yaz_present ( resource $id ) : bool

This function prepares for retrieval of records after a successful search.

The yaz_range() function should be called prior to this function to specify the range of records to be retrieved.

Parameters

id

The connection resource returned by yaz_connect().

Return Values

Returns TRUE on success or FALSE on failure.


Specifies a range of records to retrieve

  • « yaz_present
  • yaz_record »
  • PHP Manual
  • YAZ Functions
  • Specifies a range of records to retrieve

yaz_range

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_range — Specifies a range of records to retrieve

Description

yaz_range ( resource $id , int $start , int $number ) : void

Specifies a range of records to retrieve.

This function should be called before yaz_search() or yaz_present().

Parameters

id

The connection resource returned by yaz_connect().

start

Specifies the position of the first record to be retrieved. The records numbers goes from 1 to yaz_hits().

number

Specifies the number of records to be retrieved.

Return Values

No value is returned.


Returns a record

  • « yaz_range
  • yaz_scan_result »
  • PHP Manual
  • YAZ Functions
  • Returns a record

yaz_record

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_record — Returns a record

Description

yaz_record ( resource $id , int $pos , string $type ) : string

The yaz_record() function inspects a record in the current result set at the position specified by parameter pos.

Parameters

id

The connection resource returned by yaz_connect().

pos

The record position. Records positions in a result set are numbered 1, 2, ... $hits where $hits is the count returned by yaz_hits().

type

The type specifies the form of the returned record.

Note:

It is the application which is responsible for actually ensuring that the records are returned from the Z39.50/SRW server in the proper format. The type given only specifies a conversion to take place on the client side (in PHP/YAZ).

Besides conversion of the transfer record to a string/array, PHP/YAZ it is also possible to perform a character set conversion of the record. Especially for USMARC/MARC21 that is recommended since these are typically returned in the character set MARC-8 that is not supported by browsers, etc. To specify a conversion, add ; charset=from, to where from is the original character set of the record and to is the resulting character set (as seen by PHP).

string

The record is returned as a string for simple display. In this mode, all MARC records are converted to a line-by-line format since ISO2709 is hardly readable. XML records and SUTRS are returned in their original format. GRS-1 are returned in a (ugly) line-by-line format.

This format is suitable if records are to be displayed in a quick way - for debugging - or because it is not feasible to perform proper display.

xml

The record is returned as an XML string if possible. In this mode, all MARC records are converted to » MARCXML. XML records and SUTRS are returned in their original format. GRS-1 is not supported.

This format is similar to string except that MARC records are converted to MARCXML

This format is suitable if records are processed by an XML parser or XSLT processor afterwards.

raw

The record is returned as a string in its original form. This type is suitable for MARC, XML and SUTRS. It does not work for GRS-1.

MARC records are returned as a ISO2709 string. XML and SUTRS are returned as strings.

syntax

The syntax of the record is returned as a string, i.e. USmarc, GRS-1, XML, etc.

database

The name of database associated with record at the position is returned as a string.

array

The record is returned as an array that reflects the GRS-1 structure. This type is suitable for MARC and GRS-1. XML, SUTRS are not supported and if the actual record is XML or SUTRS an empty string will be returned.

The array returned consists of a list corresponding to each leaf/internal node of GRS-1. Each list item consists a sub list with first element path and data (if data is available).

The path which is a string holds a list of each tree component (of the structured GRS-1 record) from root to leaf. Each component is a tag type, tag value pair of the form (type, value

String tags normally has a corresponding tag type 3. MARC can also be returned as an array (they are converted to GRS-1 internally).

Return Values

Returns the record at position pos or an empty string if no record exists at the given position.

If no database record exists at the given position an empty string is returned.

Examples

Example #1 Array for GRS-1 record

Consider this GRS-1 record:

(4,52)Robert M. Pirsig
(4,70)
      (4,90)
            (2,7)Transworld Publishers, ltd.
This record has two nodes at root level. First element at root level is (4,52) [tag type 4, tag value 52], and has data Robert M. Pirsig. Second element at root level (4,70) has a subtree with a single element (4,90). (4,90) has yet another sub tree (2,7) with data Transworld Publishers, ltd..

If this record is present at position $p, then

<?php

$ar = yaz_record($id, $p, "array");
print_r($ar);

?>
will output:
Array
(
    [0] => Array
        (
            [0] => (4,52)
            [1] => Robert M. Pirsig
        )
    [1] => Array
        (
            [0] => (4,70)
        )
    [2] => Array
        (
            [0] => (4,70)(4,90)
        )
    [3] => Array
        (
            [0] => (4,70)(4,90)(2,7)
            [1] => Transworld Publishers, ltd.
        )
)

Example #2 Working with MARCXML

The following PHP snippet returns a MARC21/USMARC record as MARCXML. The original record is returned in marc-8 (unknown to most XML parsers), so we convert it to UTF-8 (which all XML parsers must support).

<?php
$rec = yaz_record($id, $p, "xml; charset=marc-8,utf-8");
?>

The record $rec can be processed with the Sablotron XSLT processor as follows:

<?php

$xslfile = 'display.xsl';
$processor = xslt_create();
$parms = array('/_xml' => $rec);
$res = xslt_process($processor, 'arg:/_xml', $xslfile, NULL, $parms);
xslt_free($processor);
$res = preg_replace("'</?html[^>]*>'", '', $res);
echo $res;

?>

For PHP 5 the XSL extension must be used instead of Sablotron XSLT.


Returns Scan Response result

  • « yaz_record
  • yaz_scan »
  • PHP Manual
  • YAZ Functions
  • Returns Scan Response result

yaz_scan_result

(PHP 4 >= 4.0.5, PECL yaz >= 0.9.0)

yaz_scan_result — Returns Scan Response result

Description

yaz_scan_result ( resource $id [, array &$result ] ) : array

yaz_scan_result() returns terms and associated information as received from the server in the last performed yaz_scan().

Parameters

id

The connection resource returned by yaz_connect().

result

If given, this array will be modified to hold additional information taken from the Scan Response:

  • number - Number of entries returned

  • stepsize - Step size

  • position - Position of term

  • status - Scan status

Return Values

Returns an array (0..n-1) where n is the number of terms returned. Each value is a pair where the first item is the term, and the second item is the result-count.


Prepares for a scan

  • « yaz_scan_result
  • yaz_schema »
  • PHP Manual
  • YAZ Functions
  • Prepares for a scan

yaz_scan

(PHP 4 >= 4.0.5, PECL yaz >= 0.9.0)

yaz_scan — Prepares for a scan

Description

yaz_scan ( resource $id , string $type , string $startterm [, array $flags ] ) : void

This function prepares for a Z39.50 Scan Request on the specified connection.

To actually transfer the Scan Request to the server and receive the Scan Response, yaz_wait() must be called. Upon completion of yaz_wait() call yaz_error() and yaz_scan_result() to handle the response.

Parameters

id

The connection resource returned by yaz_connect().

type

Currently only type rpn is supported.

startterm

Starting term point for the scan.

The form in which the starting term is specified is given by parameter type.

The syntax this parameter is similar to the RPN query as described in yaz_search(). It consists of zero or more @attr-operator specifications, then followed by exactly one token.

flags

This optional parameter specifies additional information to control the behaviour of the scan request. Three indexes are currently read from the flags array: number (number of terms requested), position (preferred position of term) and stepSize (preferred step size).

Return Values

No value is returned.

Examples

Example #1 PHP function that scans titles

<?php
function scan_titles($id, $startterm)
{
  yaz_scan($id, "rpn", "@attr 1=4 " . $startterm);
  yaz_wait();
  $errno = yaz_errno($id);
  if ($errno == 0) {
    $ar = yaz_scan_result($id, $options);
    echo 'Scan ok; ';
    foreach ($options as $key => $val) {
      echo "$key = $val &nbsp;";
    }
    echo '<br /><table>';
    while (list($key, list($k, $term, $tcount)) = each($ar)) {
      if (empty($k)) continue;
      echo "<tr><td>$term</td><td>$tcount</td></tr>";
    }
    echo '</table>';
  } else {
    echo "Scan failed. Error: " . yaz_error($id) . "<br />";
  }
}
?>


Specifies schema for retrieval

  • « yaz_scan
  • yaz_search »
  • PHP Manual
  • YAZ Functions
  • Specifies schema for retrieval

yaz_schema

(PHP 4 >= 4.2.0, PECL yaz >= 0.9.0)

yaz_schema — Specifies schema for retrieval

Description

yaz_schema ( resource $id , string $schema ) : void

yaz_schema() specifies the schema for retrieval.

This function should be called before yaz_search() or yaz_present().

Parameters

id

The connection resource returned by yaz_connect().

schema

Must be specified as an OID (Object Identifier) in a raw dot-notation (like 1.2.840.10003.13.4) or as one of the known registered schemas: GILS-schema, Holdings, Zthes, ...

Return Values

No value is returned.


Prepares for a search

  • « yaz_schema
  • yaz_set_option »
  • PHP Manual
  • YAZ Functions
  • Prepares for a search

yaz_search

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_search — Prepares for a search

Description

yaz_search ( resource $id , string $type , string $query ) : bool

yaz_search() prepares for a search on the given connection.

Like yaz_connect() this function is non-blocking and only prepares for a search to be executed later when yaz_wait() is called.

Parameters

id

The connection resource returned by yaz_connect().

type

This parameter represents the query type - only "rpn" is supported now in which case the third argument specifies a Type-1 query in prefix query notation.

query

The RPN query is a textual representation of the Type-1 query as defined by the Z39.50 standard. However, in the text representation as used by YAZ a prefix notation is used, that is the operator precedes the operands. The query string is a sequence of tokens where white space is ignored unless surrounded by double quotes. Tokens beginning with an at-character (@) are considered operators, otherwise they are treated as search terms.

RPN Operators
Construct | Description
@and query1 query2 | intersection of query1 and query2
@or query1 query2 | union of query1 and query2
@not query1 query2 | query1 and not query2
@set name | result set reference
@attrset set query | specifies attribute-set for query. This construction is only allowed once - in the beginning of the whole query
@attr [set] type=value query | applies attribute to query. The type and value are integers specifying the attribute-type and attribute-value respectively. The set, if given, specifies the attribute-set.

You can find information about attributes at the » Z39.50 Maintenance Agency site.

Note:

If you would like to use a more friendly notation, use the CCL parser - functions yaz_ccl_conf() and yaz_ccl_parse().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Query Examples

You can search for simple terms, like this:

computer
which matches documents where "computer" occur. No attributes are specified.

The query

"knuth donald"
matches documents where "knuth donald" occur (provided that the server supports phrase search).

This query applies two attributes for the same phrase.

@attr 1=1003 @attr 4=1 "knuth donald"
First attribute is type 1 (Bib-1 use), attribute value is 1003 (Author). Second attribute has is type 4 (structure), value 1 (phrase), so this should match documents where Donald Knuth is author.

The query

@and @or a b @not @or c d e
would in infix notation look like (a or b) and ((c or d) not e).

Another, more complex, one:

@attrset gils @and @attr 1=4 art @attr 1=2000 company
The query as a whole uses the GILS attributeset. The query matches documents where art occur in the title (GILS,BIB-1) and in which company occur as Distributor (GILS).


Sets one or more options for connection

  • « yaz_search
  • yaz_sort »
  • PHP Manual
  • YAZ Functions
  • Sets one or more options for connection

yaz_set_option

(PECL yaz >= 0.9.0)

yaz_set_option — Sets one or more options for connection

Description

yaz_set_option ( resource $id , string $name , string $value ) : void
yaz_set_option ( resource $id , array $options ) : void

Sets one or more options on the given connection.

Parameters

id

The connection resource returned by yaz_connect().

name or options

May be either a string or an array.

If given as a string, this will be the name of the option to set. You'll need to give it's value.

If given as an array, this will be an associative array (option name => option value).

PHP/YAZ Connection Options
Name | Description
implementationName | implementation name of server
implementationVersion | implementation version of server
implementationId | implementation ID of server
schema | schema for retrieval. By default, no schema is used. Setting this option is equivalent to using function yaz_schema()
preferredRecordSyntax | record syntax for retrieval. By default, no syntax is used. Setting this option is equivalent to using function yaz_syntax()
start | offset for first record to be retrieved via yaz_search() or yaz_present(). First record is numbered has a start value of 0. Second record has start value 1. Setting this option in combination with option count has the same effect as calling yaz_range() except that records are numbered from 1 in yaz_range()
count | maximum number of records to be retrieved via yaz_search() or yaz_present().
elementSetName | element-set-name for retrieval. Setting this option is equivalent to calling yaz_element().
value

The new value of the option. Use this only if the previous argument is a string.

Return Values

No value is returned.


Sets sorting criteria

  • « yaz_set_option
  • yaz_syntax »
  • PHP Manual
  • YAZ Functions
  • Sets sorting criteria

yaz_sort

(PHP 4 >= 4.0.7, PECL yaz >= 0.9.0)

yaz_sort — Sets sorting criteria

Description

yaz_sort ( resource $id , string $criteria ) : void

This function sets sorting criteria and enables Z39.50 Sort.

Call this function before yaz_search(). Using this function alone does not have any effect. When used in conjunction with yaz_search(), a Z39.50 Sort will be sent after a search response has been received and before any records are retrieved with Z39.50 Present (yaz_present().

Parameters

id

The connection resource returned by yaz_connect().

criteria

A string that takes the form field1 flags1 field2 flags2 where field1 specifies the primary attributes for sort, field2 seconds, etc..

The field specifies either a numerical attribute combinations consisting of type=value pairs separated by comma (e.g. 1=4,2=1) ; or the field may specify a plain string criteria (e.g. title. The flags is a sequence of the following characters which may not be separated by any white space.

Sort Flags
a

Sort ascending

d

Sort descending

i

Case insensitive sorting

s

Case sensitive sorting

Return Values

No value is returned.

Examples

Example #1 Sort Criterias

To sort on Bib1 attribute title, case insensitive, and ascending you would use the following sort criteria:

1=4 ia

If the secondary sorting criteria should be author, case sensitive and ascending you would use:

1=4 ia 1=1003 sa


Specifies the preferred record syntax for retrieval

  • « yaz_sort
  • yaz_wait »
  • PHP Manual
  • YAZ Functions
  • Specifies the preferred record syntax for retrieval

yaz_syntax

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_syntax — Specifies the preferred record syntax for retrieval

Description

yaz_syntax ( resource $id , string $syntax ) : void

yaz_syntax() specifies the preferred record syntax for retrieval

This function should be called before yaz_search() or yaz_present().

Parameters

id

The connection resource returned by yaz_connect().

syntax

The syntax must be specified as an OID (Object Identifier) in a raw dot-notation (like 1.2.840.10003.5.10) or as one of the known registered record syntaxes (sutrs, usmarc, grs1, xml, etc.).

Return Values

No value is returned.


Wait for Z39.50 requests to complete

  • « yaz_syntax
  • YP/NIS »
  • PHP Manual
  • YAZ Functions
  • Wait for Z39.50 requests to complete

yaz_wait

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_wait — Wait for Z39.50 requests to complete

Description

yaz_wait ([ array &$options ] ) : mixed

This function carries out networked (blocked) activity for outstanding
requests which have been prepared by the functions
yaz_connect(), yaz_search(),
yaz_present(), yaz_scan() and
yaz_itemorder().

yaz_wait() returns when all servers have either completed all requests or aborted (in case of errors).

Parameters

options

An associative array of options:

timeout

Sets timeout in seconds. If a server has not responded within the timeout it is considered dead and yaz_wait() returns. The default value for timeout is 15 seconds.

event

A boolean.

Return Values

Returns TRUE on success or FALSE on failure. In event mode, returns resource or FALSE on failure.


YP/NIS

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • YP/NIS Functions
    • yp_all — Traverse the map and call a function on each entry
    • yp_cat — Return an array containing the entire map
    • yp_err_string — Returns the error string associated with the given error code
    • yp_errno — Returns the error code of the previous operation
    • yp_first — Returns the first key-value pair from the named map
    • yp_get_default_domain — Fetches the machine's default NIS domain
    • yp_master — Returns the machine name of the master NIS server for a map
    • yp_match — Returns the matched line
    • yp_next — Returns the next key-value pair in the named map
    • yp_order — Returns the order number for a map


Introduction

NIS (formerly called Yellow Pages) allows network management of important administrative files (e.g. the password file). For more information refer to the NIS manpage and » The Linux NIS(YP)/NYS/NIS+ HOWTO. There is also a book called » Managing NFS and NIS by Hal Stern.

Note:

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.1.0.

Note: This extension is not available on Windows platforms.


Requirements

None besides functions from standard Unix libraries which are always available (either libc or libnsl, configure will detect which one to use).


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/yp


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.

YPERR_ACCESS (integer)
access violation (this has only been added recently and is only available from PECL SVN for now)
YPERR_BADARGS (integer)
The function arguments are bad
YPERR_BADDB (integer)
YP database is bad
YPERR_BUSY (integer)
Database busy
YPERR_DOMAIN (integer)
cannot bind to server in this domain
YPERR_KEY (integer)
no such key in map
YPERR_MAP (integer)
no such map in server's domain
YPERR_NODOM (integer)
Local domain name not set
YPERR_NOMORE (integer)
No more records in map database
YPERR_PMAP (integer)
Can't communicate with portmapper
YPERR_RESRC (integer)
resource allocation failure
YPERR_RPC (integer)
RPC failure - domain has been unbound
YPERR_YPBIND (integer)
Can't communicate with ypbind
YPERR_YPERR (integer)
internal yp server or client error
YPERR_YPSERV (integer)
Can't communicate with ypserv
YPERR_VERS (integer)
YP version mismatch


YP/NIS Functions

Table of Contents

  • yp_all — Traverse the map and call a function on each entry
  • yp_cat — Return an array containing the entire map
  • yp_err_string — Returns the error string associated with the given error code
  • yp_errno — Returns the error code of the previous operation
  • yp_first — Returns the first key-value pair from the named map
  • yp_get_default_domain — Fetches the machine's default NIS domain
  • yp_master — Returns the machine name of the master NIS server for a map
  • yp_match — Returns the matched line
  • yp_next — Returns the next key-value pair in the named map
  • yp_order — Returns the order number for a map


Traverse the map and call a function on each entry

  • « YP/NIS Functions
  • yp_cat »
  • PHP Manual
  • YP/NIS Functions
  • Traverse the map and call a function on each entry

yp_all

(PHP 4 >= 4.0.6, PHP 5 < 5.1.0)

yp_all — Traverse the map and call a function on each entry

Description

yp_all ( string $domain , string $map , string $callback ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

domain

The NIS domain name.

map

The NIS map.

callback

Return Values

No value is returned.


Return an array containing the entire map

  • « yp_all
  • yp_err_string »
  • PHP Manual
  • YP/NIS Functions
  • Return an array containing the entire map

yp_cat

(PHP 4 >= 4.0.6, PHP 5 < 5.1.0)

yp_cat — Return an array containing the entire map

Description

yp_cat ( string $domain , string $map ) : array

Returns all map entries.

Parameters

domain

The NIS domain name.

map

The NIS map.

Return Values

Returns an array of all map entries, the maps key values as array indices and the maps entries as array data.


Returns the error string associated with the given error code

  • « yp_cat
  • yp_errno »
  • PHP Manual
  • YP/NIS Functions
  • Returns the error string associated with the given error code

yp_err_string

(PHP 4 >= 4.0.6, PHP 5 < 5.1.0)

yp_err_string — Returns the error string associated with the given error code

Description

yp_err_string ( int $errorcode ) : string

Returns the error message associated with the given error code. Useful to indicate what exactly went wrong.

Parameters

errorcode

The error code.

Return Values

Returns the error message, as a string.

Examples

Example #1 Example for NIS errors

<?php
echo "Error: " . yp_err_string(yp_errno());
?>

See Also

  • yp_errno() - Returns the error code of the previous operation


Returns the error code of the previous operation

  • « yp_err_string
  • yp_first »
  • PHP Manual
  • YP/NIS Functions
  • Returns the error code of the previous operation

yp_errno

(PHP 4 >= 4.0.6, PHP 5 < 5.1.0)

yp_errno — Returns the error code of the previous operation

Description

yp_errno ( void ) : int

Returns the error code of the previous operation.

Return Values

Returns one of the YPERR_XXX error constants.

See Also

  • yp_err_string() - Returns the error string associated with the given error code


Returns the first key-value pair from the named map

  • « yp_errno
  • yp_get_default_domain »
  • PHP Manual
  • YP/NIS Functions
  • Returns the first key-value pair from the named map

yp_first

(PHP 4, PHP 5 < 5.1.0)

yp_first — Returns the first key-value pair from the named map

Description

yp_first ( string $domain , string $map ) : array

Gets the first key-value pair from the named map in the named domain.

Parameters

domain

The NIS domain name.

map

The NIS map.

Return Values

Returns the first key-value pair as an array on success, or FALSE on errors.

Examples

Example #1 Example for the NIS first

<?php
$entry = yp_first($domain, "passwd.byname");

$key = key($entry);
$value = $entry[$key];

echo "First entry in this map has key " . $key . " and value " . $value;
?>

See Also

  • yp_next() - Returns the next key-value pair in the named map
  • yp_get_default_domain() - Fetches the machine's default NIS domain


Fetches the machine's default NIS domain

  • « yp_first
  • yp_master »
  • PHP Manual
  • YP/NIS Functions
  • Fetches the machine's default NIS domain

yp_get_default_domain

(PHP 4, PHP 5 < 5.1.0)

yp_get_default_domain — Fetches the machine's default NIS domain

Description

yp_get_default_domain ( void ) : string

Returns the default domain of the node. Can be used as the domain parameter for successive NIS calls.

A NIS domain can be described a group of NIS maps. Every host that needs to look up information binds itself to a certain domain. Refer to the documents mentioned at the beginning for more detailed information.

Return Values

Returns the default domain of the node or FALSE. Can be used as the domain parameter for successive NIS calls.

Examples

Example #1 Example for the default domain

<?php
$domain = yp_get_default_domain();
echo "Default NIS domain is: " . $domain;
?>


Returns the machine name of the master NIS server for a map

  • « yp_get_default_domain
  • yp_match »
  • PHP Manual
  • YP/NIS Functions
  • Returns the machine name of the master NIS server for a map

yp_master

(PHP 4, PHP 5 < 5.1.0)

yp_master — Returns the machine name of the master NIS server for a map

Description

yp_master ( string $domain , string $map ) : string

Returns the machine name of the master NIS server for a map.

Parameters

domain

The NIS domain name.

map

The NIS map.

Return Values

Examples

Example #1 Example for the NIS master

<?php
$number = yp_master($domain, $mapname);
echo "Master for this map is: " . $master;
?>

See Also

  • yp_get_default_domain() - Fetches the machine's default NIS domain


Returns the matched line

  • « yp_master
  • yp_next »
  • PHP Manual
  • YP/NIS Functions
  • Returns the matched line

yp_match

(PHP 4, PHP 5 < 5.1.0)

yp_match — Returns the matched line

Description

yp_match ( string $domain , string $map , string $key ) : string

Returns the value associated with the passed key out of the specified map.

Parameters

domain

The NIS domain name.

map

The NIS map.

key

This key must be exact.

Return Values

Returns the value, or FALSE on errors.

Examples

Example #1 Example for NIS match

<?php
$entry = yp_match($domain, "passwd.byname", "joe");
echo "Matched entry is: " . $entry;
?>

The above example will output something similar to:

joe:##joe:11111:100:Joe User:/home/j/joe:/usr/local/bin/bash

See Also

  • yp_get_default_domain() - Fetches the machine's default NIS domain


Returns the next key-value pair in the named map

  • « yp_match
  • yp_order »
  • PHP Manual
  • YP/NIS Functions
  • Returns the next key-value pair in the named map

yp_next

(PHP 4, PHP 5 < 5.1.0)

yp_next — Returns the next key-value pair in the named map

Description

yp_next ( string $domain , string $map , string $key ) : array

Returns the next key-value pair in the named map after the specified key.

Parameters

domain

map

key

Return Values

Returns the next key-value pair as an array, or FALSE on errors.

Examples

Example #1 Example for NIS next

<?php
$entry = yp_next($domain, "passwd.byname", "joe");

if (!$entry) {
    echo "No more entries found\n";
    echo "<!--" . yp_errno() . ": " . yp_err_string() . "-->";
}

$key = key($entry);

echo "The next entry after joe has key " . $key
      . " and value " . $entry[$key];
?>

See Also

  • yp_first() - Returns the first key-value pair from the named map
  • yp_get_default_domain() - Fetches the machine's default NIS domain


Returns the order number for a map

  • « yp_next
  • 0MQ messaging »
  • PHP Manual
  • YP/NIS Functions
  • Returns the order number for a map

yp_order

(PHP 4, PHP 5 < 5.1.0)

yp_order — Returns the order number for a map

Description

yp_order ( string $domain , string $map ) : int

Gets the order number for a map.

Parameters

domain

map

Return Values

Returns the order number for a map or FALSE on error.

Examples

Example #1 Example for the NIS order

<?php
    $number = yp_order($domain, $mapname);
    echo "Order number for this map is: " . $number;
?>

See Also

  • yp_get_default_domain() - Fetches the machine's default NIS domain


ZMQ

  • Introduction
  • Installing/Configuring
    • Requirements
  • ZMQ — The ZMQ class
    • ZMQ::__construct — ZMQ constructor
  • ZMQContext — The ZMQContext class
    • ZMQContext::__construct — Construct a new ZMQContext object
    • ZMQContext::getOpt — Get context option
    • ZMQContext::getSocket — Create a new socket
    • ZMQContext::isPersistent — Whether the context is persistent
    • ZMQContext::setOpt — Set a socket option
  • ZMQSocket — The ZMQSocket class
    • ZMQSocket::bind — Bind the socket
    • ZMQSocket::connect — Connect the socket
    • ZMQSocket::__construct — Construct a new ZMQSocket
    • ZMQSocket::disconnect — Disconnect a socket
    • ZMQSocket::getEndpoints — Get list of endpoints
    • ZMQSocket::getPersistentId — Get the persistent id
    • ZMQSocket::getSocketType — Get the socket type
    • ZMQSocket::getSockOpt — Get socket option
    • ZMQSocket::isPersistent — Whether the socket is persistent
    • ZMQSocket::recv — Receives a message
    • ZMQSocket::recvMulti — Receives a multipart message
    • ZMQSocket::send — Sends a message
    • ZMQSocket::sendmulti — Sends a multipart message
    • ZMQSocket::setSockOpt — Set a socket option
    • ZMQSocket::unbind — Unbind the socket
  • ZMQPoll — The ZMQPoll class
    • ZMQPoll::add — Add item to the poll set
    • ZMQPoll::clear — Clear the poll set
    • ZMQPoll::count — Count items in the poll set
    • ZMQPoll::getLastErrors — Get poll errors
    • ZMQPoll::poll — Poll the items
    • ZMQPoll::remove — Remove item from poll set
  • ZMQDevice — The ZMQDevice class
    • ZMQDevice::__construct — Construct a new device
    • ZMQDevice::getIdleTimeout — Get the idle timeout
    • ZMQDevice::getTimerTimeout — Get the timer timeout
    • ZMQDevice::run — Run the new device
    • ZMQDevice::setIdleCallback — Set the idle callback function
    • ZMQDevice::setIdleTimeout — Set the idle timeout
    • ZMQDevice::setTimerCallback — Set the timer callback function
    • ZMQDevice::setTimerTimeout — Set the timer timeout


Introduction

"ØMQ is a software library that lets you quickly design and implement a fast message-based application." --0MQ Website

For more information about 0MQ, see » http://zeromq.org/.


  • « Introduction
  • Requirements »
  • PHP Manual
  • 0MQ messaging
  • Installing/Configuring

Installing/Configuring

Table of Contents

  • Requirements


Requirements

ZMQ extension requires 0MQ version 2.0.7 or higher. 0MQ can be acquired from » http://zeromq.org/area:download.

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/zmq


The ZMQ class

(No version information available, might only be in Git)

Introduction

Class synopsis

ZMQ {
/* Constants */
const integer SOCKET_PAIR ;
const integer SOCKET_PUB ;
const integer SOCKET_SUB ;
const integer SOCKET_REQ ;
const integer SOCKET_REP ;
const integer SOCKET_XREQ ;
const integer SOCKET_XREP ;
const integer SOCKET_PUSH ;
const integer SOCKET_PULL ;
const integer SOCKET_ROUTER ;
const integer SOCKET_DEALER ;
const integer SOCKET_XPUB ;
const integer SOCKET_XSUB ;
const integer SOCKET_STREAM ;
const integer SOCKOPT_HWM ;
const integer SOCKOPT_SNDHWM ;
const integer SOCKOPT_RCVHWM ;
const integer SOCKOPT_AFFINITY ;
const integer SOCKOPT_IDENTITY ;
const integer SOCKOPT_SUBSCRIBE ;
const integer SOCKOPT_UNSUBSCRIBE ;
const integer SOCKOPT_RATE ;
const integer SOCKOPT_RECOVERY_IVL ;
const integer SOCKOPT_RECONNECT_IVL ;
const integer SOCKOPT_RECONNECT_IVL_MAX ;
const integer SOCKOPT_MCAST_LOOP ;
const integer SOCKOPT_SNDBUF ;
const integer SOCKOPT_RCVBUF ;
const integer SOCKOPT_RCVMORE ;
const integer SOCKOPT_TYPE ;
const integer SOCKOPT_LINGER ;
const integer SOCKOPT_BACKLOG ;
const integer SOCKOPT_MAXMSGSIZE ;
const integer SOCKOPT_SNDTIMEO ;
const integer SOCKOPT_RCVTIMEO ;
const integer SOCKOPT_IPV4ONLY ;
const integer SOCKOPT_LAST_ENDPOINT ;
const integer SOCKOPT_TCP_KEEPALIVE_IDLE ;
const integer SOCKOPT_TCP_KEEPALIVE_CNT ;
const integer SOCKOPT_TCP_KEEPALIVE_INTVL ;
const integer SOCKOPT_TCP_ACCEPT_FILTER ;
const integer SOCKOPT_TCP_ACCEPT_FILTER ;
const integer SOCKOPT_DELAY_ATTACH_ON_CONNECT ;
const integer SOCKOPT_XPUB_VERBOSE ;
const integer SOCKOPT_ROUTER_RAW ;
const integer SOCKOPT_IPV6 ;
const integer CTXOPT_MAX_SOCKETS ;
const integer POLL_IN ;
const integer POLL_OUT ;
const integer MODE_NOBLOCK ;
const integer MODE_DONTWAIT ;
const integer MODE_SNDMORE ;
const integer ERR_INTERNAL ;
const integer ERR_EAGAIN ;
const integer ERR_ENOTSUP ;
const integer ERR_EFSM ;
const integer ERR_ETERM ;
/* Methods */
private__construct ( void )
}

Predefined Constants

ZMQ Constant Types

ZMQ::SOCKET_PAIR

Exclusive pair pattern

ZMQ::SOCKET_PUB

Publisher socket

ZMQ::SOCKET_SUB

Subscriber socket

ZMQ::SOCKET_REQ

Request socket

ZMQ::SOCKET_REP

Reply socket

ZMQ::SOCKET_XREQ

Alias for SOCKET_DEALER

ZMQ::SOCKET_XREP

Alias for SOCKET_ROUTER

ZMQ::SOCKET_PUSH

Pipeline upstream push socket

ZMQ::SOCKET_PULL

Pipeline downstream pull socket

ZMQ::SOCKET_ROUTER

Extended REP socket that can route replies to requesters

ZMQ::SOCKET_DEALER

Extended REQ socket that load balances to all connected peers

ZMQ::SOCKET_XPUB

Similar to SOCKET_PUB, except you can receive subscriptions as messages. The subscription message is 0 (unsubscribe) or 1 (subscribe) followed by the topic.

ZMQ::SOCKET_XSUB

Similar to SOCKET_SUB, except you can send subscriptions as messages. See SOCKET_XPUB for format.

ZMQ::SOCKET_STREAM

Used to send and receive TCP data from a non-ØMQ peer. Available if compiled against ZeroMQ 4.x or higher (Value: integer).

ZMQ::SOCKOPT_HWM

The high water mark for inbound and outbound messages is a hard limit on the maximum number of outstanding messages ØMQ shall queue in memory for any single peer that the specified socket is communicating with. Setting this option on a socket will only affect connections made after the option has been set. On ZeroMQ 3.x this is a wrapper for setting both SNDHWM and RCVHWM. (Value: integer).

ZMQ::SOCKOPT_SNDHWM

The ZMQ_SNDHWM option shall set the high water mark for outbound messages on the specified socket. Available if compiled against ZeroMQ 3.x or higher (Value: integer).

ZMQ::SOCKOPT_RCVHWM

The SOCKOPT_RCVHWM option shall set the high water mark for inbound messages on the specified socket. Available if compiled against ZeroMQ 3.x or higher (Value: integer).

ZMQ::SOCKOPT_AFFINITY

Set I/O thread affinity (Value: integer)

ZMQ::SOCKOPT_IDENTITY

Set socket identity (Value: string)

ZMQ::SOCKOPT_SUBSCRIBE

Establish message filter. Valid for subscriber socket (Value: string)

ZMQ::SOCKOPT_UNSUBSCRIBE

Remove message filter. Valid for subscriber socket (Value: string)

ZMQ::SOCKOPT_RATE

Set rate for multicast sockets (pgm) (Value: integer >= 0)

ZMQ::SOCKOPT_RECOVERY_IVL

Set multicast recovery interval (Value: integer >= 0)

ZMQ::SOCKOPT_RECONNECT_IVL

Set the initial reconnection interval (Value: integer >= 0)

ZMQ::SOCKOPT_RECONNECT_IVL_MAX

Set the max reconnection interval (Value: integer >= 0)

ZMQ::SOCKOPT_MCAST_LOOP

Control multicast loopback (Value: integer >= 0)

ZMQ::SOCKOPT_SNDBUF

Set kernel transmit buffer size (Value: integer >= 0)

ZMQ::SOCKOPT_RCVBUF

Set kernel receive buffer size (Value: integer >= 0)

ZMQ::SOCKOPT_RCVMORE

Receive multi-part messages (Value: integer)

ZMQ::SOCKOPT_TYPE

Get the socket type. Valid for getSockOpt (Value: integer)

ZMQ::SOCKOPT_LINGER

The linger value of the socket. Specifies how long the socket blocks trying flush messages after it has been closed (Value: integer)

ZMQ::SOCKOPT_BACKLOG

The SOCKOPT_BACKLOG option shall set the maximum length of the queue of outstanding peer connections for the specified socket; this only applies to connection-oriented transports. (Value: integer)

ZMQ::SOCKOPT_MAXMSGSIZE

Limits the maximum size of the inbound message. Value -1 means no limit. Available if compiled against ZeroMQ 3.x or higher (Value: integer)

ZMQ::SOCKOPT_SNDTIMEO

Sets the timeout for send operation on the socket. Value -1 means no limit. Available if compiled against ZeroMQ 3.x or higher (Value: integer)

ZMQ::SOCKOPT_RCVTIMEO

Sets the timeout for receive operation on the socket. Value -1 means no limit. Available if compiled against ZeroMQ 3.x or higher (Value: integer)

ZMQ::SOCKOPT_IPV4ONLY

Disable IPV6 support if 1. Available if compiled against ZeroMQ 3.x (Value: integer)

ZMQ::SOCKOPT_LAST_ENDPOINT

Retrieve the last connected endpoint - for use with * wildcard ports. Available if compiled against ZeroMQ 3.x or higher (Value: string)

ZMQ::SOCKOPT_TCP_KEEPALIVE_IDLE

Idle time for TCP keepalive. Available if compiled against ZeroMQ 3.x or higher (Value: integer)

ZMQ::SOCKOPT_TCP_KEEPALIVE_CNT

Count time for TCP keepalive. Available if compiled against ZeroMQ 3.x or higher (Value: integer)

ZMQ::SOCKOPT_TCP_KEEPALIVE_INTVL

Interval for TCP keepalive. Available if compiled against ZeroMQ 3.x or higher (Value: integer)

ZMQ::SOCKOPT_DELAY_ATTACH_ON_CONNECT

Set a CIDR string to match against incoming TCP connections. Available if compiled against ZeroMQ 3.x or higher (Value: string)

ZMQ::SOCKOPT_TCP_ACCEPT_FILTER

Set a CIDR string to match against incoming TCP connections. Available if compiled against ZeroMQ 3.x or higher (Value: string)

ZMQ::SOCKOPT_XPUB_VERBOSE

Set the XPUB to receive an application message on each instance of a subscription. Available if compiled against ZeroMQ 3.x or higher (Value: string)

ZMQ::SOCKOPT_ROUTER_RAW

Sets the raw mode on the ROUTER, when set to 1. In raw mode when using tcp:// transport the socket will read and write without ZeroMQ framing. Available if compiled against ZeroMQ 4.0 or higher (Value: string)

ZMQ::SOCKOPT_IPV6

Enable IPV6. Available if compiled against ZeroMQ 4.0 or higher (Value: string)

ZMQ::CTXOPT_MAX_SOCKETS

The socket limit for this context. Available if compiled against ZeroMQ 3.x or higher (Value: integer)

ZMQ::POLL_IN

Poll for incoming data

ZMQ::POLL_OUT

Poll for outgoing data

ZMQ::MODE_NOBLOCK

Non-blocking operation. Deprecated, use ZMQ::MODE_DONTWAIT instead

ZMQ::MODE_DONTWAIT

Non-blocking operation

ZMQ::MODE_SNDMORE

Send multi-part message

ZMQ::DEVICE_FORWARDER

Forwarder device

ZMQ::DEVICE_QUEUE

Queue device

ZMQ::DEVICE_STREAMER

Streamer device

ZMQ::ERR_INTERNAL

ZMQ extension internal error

ZMQ::ERR_EAGAIN

Implies that the operation would block when ZMQ::MODE_DONTWAIT is used

ZMQ::ERR_ENOTSUP

The operation is not supported by the socket type

ZMQ::ERR_EFSM

The operation can not be executed because the socket is not in correct state

ZMQ::ERR_ETERM

The context has been terminated

Table of Contents

  • ZMQ::__construct — ZMQ constructor


ZMQ constructor

  • « ZMQ
  • ZMQContext »
  • PHP Manual
  • ZMQ
  • ZMQ constructor

ZMQ::__construct

(PECL zmq >= 0.5.0)

ZMQ::__construct — ZMQ constructor

Description

privateZMQ::__construct ( void )

Private constructor to prevent direct initialization. This class holds the constants for ZMQ extension.

Parameters

This function has no parameters.

Return Values


The ZMQContext class

(No version information available, might only be in Git)

Introduction

Class synopsis

ZMQContext {
/* Methods */
__construct ([ int $io_threads = 1 [, bool $is_persistent = TRUE ]] )
public getOpt ( string $key ) : mixed
public getSocket ( int $type [, string $persistent_id = NULL [, callback $on_new_socket = NULL ]] ) : ZMQSocket
public isPersistent ( void ) : bool
public setOpt ( int $key , mixed $value ) : ZMQContext
}

Table of Contents

  • ZMQContext::__construct — Construct a new ZMQContext object
  • ZMQContext::getOpt — Get context option
  • ZMQContext::getSocket — Create a new socket
  • ZMQContext::isPersistent — Whether the context is persistent
  • ZMQContext::setOpt — Set a socket option


Construct a new ZMQContext object

  • « ZMQContext
  • ZMQContext::getOpt »
  • PHP Manual
  • ZMQContext
  • Construct a new ZMQContext object

ZMQContext::__construct

(PECL zmq >= 0.5.0)

ZMQContext::__construct — Construct a new ZMQContext object

Description

ZMQContext::__construct ([ int $io_threads = 1 [, bool $is_persistent = TRUE ]] )

Constructs a new ZMQ context. The context is used to initialize sockets. A persistent context is required to initialize persistent sockets.

Parameters

io_threads

Number of io-threads in the context.

is_persistent

Whether the context is persistent. Persistent context is stored over multiple requests and is a requirement for persistent sockets.

Examples

Example #1 A ZMQContext() example

Construct a new context and allocate request socket from it

<?php
/* Allocate a new context */
$context = new ZMQContext();

/* Create a new socket */
$socket = $context->getSocket(ZMQ::SOCKET_REQ, 'my sock');

/* Connect the socket */
$socket->connect("tcp://example.com:1234");

/* Send a request */
$socket->send("Hello there");

/* Receive back the response */
$message = $socket->recv();
?>

Return Values

Throws ZMQContextException if context initialization fails.


Get context option

  • « ZMQContext::__construct
  • ZMQContext::getSocket »
  • PHP Manual
  • ZMQContext
  • Get context option

ZMQContext::getOpt

(PECL zmq >= 1.0.4)

ZMQContext::getOpt — Get context option

Description

public ZMQContext::getOpt ( string $key ) : mixed

Returns the value of a context option.

Parameters

key

An integer representing the option. See the ZMQ::CTXOPT_* constants.

Return Values

Returns either a string or an integer depending on key. Throws ZMQContextException on error.


Create a new socket

  • « ZMQContext::getOpt
  • ZMQContext::isPersistent »
  • PHP Manual
  • ZMQContext
  • Create a new socket

ZMQContext::getSocket

(PECL zmq >= 0.5.0)

ZMQContext::getSocket — Create a new socket

Description

public ZMQContext::getSocket ( int $type [, string $persistent_id = NULL [, callback $on_new_socket = NULL ]] ) : ZMQSocket

Shortcut for creating new sockets from the context. If the context is not persistent the persistent_id parameter is ignored and the socket falls back to being non-persistent. The on_new_socket is called only when a new underlying socket structure is created.

Parameters

type

ZMQ::SOCKET_* constant to specify socket type.

persistent_id

If persistent_id is specified the socket will be persisted over multiple requests.

on_new_socket

Callback function, which is executed when a new socket structure is created. This function does not get invoked if the underlying persistent connection is re-used. The callback takes ZMQSocket and persistent_id as two arguments.

Examples

Example #1 A ZMQContext() example

Basic usage

<?php
/* Allocate a new context */
$context = new ZMQContext();

/* Create a new socket */
$socket = $context->getSocket(ZMQ::SOCKET_REQ, 'my sock');

/* Connect the socket */
$socket->connect("tcp://example.com:1234");

/* Send a request */
$socket->send("Hello there");

/* Receive back the response */
$message = $socket->recv();
echo "Received message: {$message}\n";
?>

Return Values

Returns a ZMQSocket object on success. Throws ZMQSocketException on error.


Whether the context is persistent

  • « ZMQContext::getSocket
  • ZMQContext::setOpt »
  • PHP Manual
  • ZMQContext
  • Whether the context is persistent

ZMQContext::isPersistent

(PECL zmq >= 0.5.0)

ZMQContext::isPersistent — Whether the context is persistent

Description

public ZMQContext::isPersistent ( void ) : bool

Whether the context is persistent. Persistent context is needed for persistent connections as each socket is allocated from a context.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the context is persistent and FALSE if the context is non-persistent.


Set a socket option

  • « ZMQContext::isPersistent
  • ZMQSocket »
  • PHP Manual
  • ZMQContext
  • Set a socket option

ZMQContext::setOpt

(PECL zmq >= 1.0.4)

ZMQContext::setOpt — Set a socket option

Description

public ZMQContext::setOpt ( int $key , mixed $value ) : ZMQContext

Sets a ZMQ context option. The type of the value depends on the key. See ZMQ Constant Types for more information.

Parameters

key

One of the ZMQ::CTXOPT_* constants.

value

The value of the parameter.

Return Values

Returns the current object. Throws ZMQContextException on error.


The ZMQSocket class

(No version information available, might only be in Git)

Introduction

Class synopsis

ZMQSocket {
/* Methods */
public bind ( string $dsn [, bool $force = FALSE ] ) : ZMQSocket
public connect ( string $dsn [, bool $force = FALSE ] ) : ZMQSocket
__construct ( ZMQContext $context , int $type [, string $persistent_id = NULL [, callback $on_new_socket = NULL ]] )
public disconnect ( string $dsn ) : ZMQSocket
public getEndpoints ( void ) : array
public getPersistentId ( void ) : string
public getSocketType ( void ) : int
public getSockOpt ( string $key ) : mixed
public isPersistent ( void ) : bool
public recv ([ int $mode = 0 ] ) : string
public recvMulti ([ int $mode = 0 ] ) : array
public send ( string $message [, int $mode = 0 ] ) : ZMQSocket
public sendmulti ( array $message [, int $mode = 0 ] ) : ZMQSocket
public setSockOpt ( int $key , mixed $value ) : ZMQSocket
public unbind ( string $dsn ) : ZMQSocket
}

Table of Contents

  • ZMQSocket::bind — Bind the socket
  • ZMQSocket::connect — Connect the socket
  • ZMQSocket::__construct — Construct a new ZMQSocket
  • ZMQSocket::disconnect — Disconnect a socket
  • ZMQSocket::getEndpoints — Get list of endpoints
  • ZMQSocket::getPersistentId — Get the persistent id
  • ZMQSocket::getSocketType — Get the socket type
  • ZMQSocket::getSockOpt — Get socket option
  • ZMQSocket::isPersistent — Whether the socket is persistent
  • ZMQSocket::recv — Receives a message
  • ZMQSocket::recvMulti — Receives a multipart message
  • ZMQSocket::send — Sends a message
  • ZMQSocket::sendmulti — Sends a multipart message
  • ZMQSocket::setSockOpt — Set a socket option
  • ZMQSocket::unbind — Unbind the socket


Bind the socket

  • « ZMQSocket
  • ZMQSocket::connect »
  • PHP Manual
  • ZMQSocket
  • Bind the socket

ZMQSocket::bind

(PECL zmq >= 0.5.0)

ZMQSocket::bind — Bind the socket

Description

public ZMQSocket::bind ( string $dsn [, bool $force = FALSE ] ) : ZMQSocket

Bind the socket to an endpoint. The endpoint is defined in format transport://address where transport is one of the following: inproc, ipc, tcp, pgm or epgm.

Parameters

dsn

The bind dsn, for example transport://address.

force

Tries to bind even if the socket has already been bound to the given endpoint.

Return Values

Returns the current object. Throws ZMQSocketException on error.


Connect the socket

  • « ZMQSocket::bind
  • ZMQSocket::__construct »
  • PHP Manual
  • ZMQSocket
  • Connect the socket

ZMQSocket::connect

(PECL zmq >= 0.5.0)

ZMQSocket::connect — Connect the socket

Description

public ZMQSocket::connect ( string $dsn [, bool $force = FALSE ] ) : ZMQSocket

Connect the socket to a remote endpoint. The endpoint is defined in format transport://address where transport is one of the following: inproc, ipc, tcp, pgm or epgm.

Parameters

dsn

The connect dsn, for example transport://address.

force

Tries to connect even if the socket has already been connected to given endpoint.

Examples

Example #1 A ZMQContext() example

Construct a new context and allocate request socket from it

<?php
/* Server hostname */
$dsn = "tcp://127.0.0.1:5555";

/* Create a socket */
$socket = new ZMQSocket(new ZMQContext(), ZMQ::SOCKET_REQ, 'my socket');

/* Get list of connected endpoints */
$endpoints = $socket->getEndpoints();

/* Check if the socket is connected */
if (!in_array($dsn, $endpoints['connect'])) {
    echo "<p>Connecting to $dsn</p>";
    $socket->connect($dsn);
} else {
    echo "<p>Already connected to $dsn</p>";
}

/* Send and receive */
$socket->send("Hello!");
$message = $socket->recv();

echo "<p>Server said: {$message}</p>";
?>

Return Values

Returns the current object. Throws ZMQSocketException on error.


Construct a new ZMQSocket

  • « ZMQSocket::connect
  • ZMQSocket::disconnect »
  • PHP Manual
  • ZMQSocket
  • Construct a new ZMQSocket

ZMQSocket::__construct

(PECL zmq >= 0.5.0)

ZMQSocket::__construct — Construct a new ZMQSocket

Description

ZMQSocket::__construct ( ZMQContext $context , int $type [, string $persistent_id = NULL [, callback $on_new_socket = NULL ]] )

Constructs a ZMQSocket object. persistent_id parameter can be used to allocated a persistent socket. A persistent socket has to be allocated from a persistent context and it stays connected over multiple requests. The persistent_id parameter can be used to recall the same socket over multiple requests. The on_new_socket is called only when a new underlying socket structure is created.

Parameters

context

ZMQContext object.

type

The socket type. See ZMQ::SOCKET_* constants.

persistent_id

If persistent_id is specified the socket will be persisted over multiple requests. If context is not persistent the socket falls back to non-persistent mode.

on_new_socket

Callback function, which is executed when a new socket structure is created. This function does not get invoked if the underlying persistent connection is re-used.

Examples

Example #1 A ZMQSocket() example

Using callback the bind/connect socket

<?php

/*
  The socket is persistent so this function is called only on the
  first request to the script.
*/
function on_new_socket_cb(ZMQSocket $socket, $persistent_id = null)
{
    if ($persistent_id === 'server') {
        $socket->bind("tcp://localhost:12122");
    } else {
        $socket->connect("tcp://localhost:12122");
    }
}

/* Allocate a new context */
$context = new ZMQContext();

/* Create a new socket */
$socket = $context->getSocket(ZMQ::SOCKET_REP, 'server', 'on_new_socket_cb');

$message = $socket->recv();
echo "Received message: {$message}\n";
?>

The callback signature

Note:

function on_new_socket_cb(ZMQSocket $socket, string $persistent_id = null);

Return Values

Throws ZMQSocketException on error.


Disconnect a socket

  • « ZMQSocket::__construct
  • ZMQSocket::getEndpoints »
  • PHP Manual
  • ZMQSocket
  • Disconnect a socket

ZMQSocket::disconnect

(PECL zmq >= 1.0.4)

ZMQSocket::disconnect — Disconnect a socket

Description

public ZMQSocket::disconnect ( string $dsn ) : ZMQSocket

Disconnect the socket from a previously connected remote endpoint. The endpoint is defined in format transport://address where transport is one of the following: inproc, ipc, tcp, pgm or epgm.

Parameters

dsn

The connect dsn, for example transport://address.

Return Values

Returns the current object. Throws ZMQSocketException on error.


Get list of endpoints

  • « ZMQSocket::disconnect
  • ZMQSocket::getPersistentId »
  • PHP Manual
  • ZMQSocket
  • Get list of endpoints

ZMQSocket::getEndpoints

(PECL zmq >= 0.5.0)

ZMQSocket::getEndpoints — Get list of endpoints

Description

public ZMQSocket::getEndpoints ( void ) : array

Returns a list of endpoints where the socket is connected or bound to.

Parameters

This function has no parameters.

Return Values

Returns an array containing elements 'bind' and 'connect'.


Get the persistent id

  • « ZMQSocket::getEndpoints
  • ZMQSocket::getSocketType »
  • PHP Manual
  • ZMQSocket
  • Get the persistent id

ZMQSocket::getPersistentId

(PECL zmq >= 0.5.0)

ZMQSocket::getPersistentId — Get the persistent id

Description

public ZMQSocket::getPersistentId ( void ) : string

Returns the persistent id of the socket.

Parameters

This function has no parameters.

Return Values

Returns the persistent id string assigned of the object and NULL if socket is not persistent.


Get the socket type

  • « ZMQSocket::getPersistentId
  • ZMQSocket::getSockOpt »
  • PHP Manual
  • ZMQSocket
  • Get the socket type

ZMQSocket::getSocketType

(PECL zmq >= 0.5.0)

ZMQSocket::getSocketType — Get the socket type

Description

public ZMQSocket::getSocketType ( void ) : int

Gets the socket type.

Parameters

This function has no parameters.

Return Values

Returns an integer representing the socket type. The integer can be compared against ZMQ::SOCKET_* constants.


Get socket option

  • « ZMQSocket::getSocketType
  • ZMQSocket::isPersistent »
  • PHP Manual
  • ZMQSocket
  • Get socket option

ZMQSocket::getSockOpt

(PECL zmq >= 0.5.0)

ZMQSocket::getSockOpt — Get socket option

Description

public ZMQSocket::getSockOpt ( string $key ) : mixed

Returns the value of a socket option.

Parameters

key

An integer representing the option. See the ZMQ::SOCKOPT_* constants.

Return Values

Returns either a string or an integer depending on key. Throws ZMQSocketException on error.


Whether the socket is persistent

  • « ZMQSocket::getSockOpt
  • ZMQSocket::recv »
  • PHP Manual
  • ZMQSocket
  • Whether the socket is persistent

ZMQSocket::isPersistent

(PECL zmq >= 0.5.0)

ZMQSocket::isPersistent — Whether the socket is persistent

Description

public ZMQSocket::isPersistent ( void ) : bool

Check whether the socket is persistent.

Parameters

This function has no parameters.

Return Values

Returns a boolean based on whether the socket is persistent or not.


Receives a message

  • « ZMQSocket::isPersistent
  • ZMQSocket::recvMulti »
  • PHP Manual
  • ZMQSocket
  • Receives a message

ZMQSocket::recv

(PECL zmq >= 0.5.0)

ZMQSocket::recv — Receives a message

Description

public ZMQSocket::recv ([ int $mode = 0 ] ) : string

Receive a message from a socket. By default receiving will block until a message is available unless ZMQ::MODE_DONTWAIT flag is used. ZMQ::SOCKOPT_RCVMORE socket option can be used for receiving multi-part messages. See ZMQSocket::setSockOpt() for more information.

Parameters

mode

Pass mode flags to receive multipart messages or non-blocking operation. See ZMQ::MODE_* constants.

Examples

Example #1 A send/recv example

Non-blocking send / receive

<?php

/* Create new queue object, there needs to be a server at the other end */
$queue = new ZMQSocket(new ZMQContext(), ZMQ::SOCKET_REQ);
$queue->connect("tcp://127.0.0.1:5555");

/* Assign socket 1 to the queue, send and receive */
$retries = 5;
$sending = true;

/* Start a loop */
do {
    try {
        /* Try to send / receive */
        if ($sending) {
            echo "Sending message\n";
            $queue->send("This is a message", ZMQ::MODE_DONTWAIT);
            $sending = false;
        } else {
            echo "Got response: " . $queue->recv(ZMQ::MODE_DONTWAIT) . "\n";
            break;
        }
    } catch (ZMQSocketException $e) {
        /* EAGAIN means that the operation would have blocked, retry */
        if ($e->getCode() === ZMQ::ERR_EAGAIN) {
            echo " - Got EAGAIN, retrying ($retries)\n";
        } else {
            die(" - Error: " . $e->getMessage());
        }
    }
    /* Sleep a bit between operations */
    usleep(5);
} while (--$retries);
?>

The above example will output something similar to:

Sending message
 - Unable to execute operation, retrying (4)
Got response: This is a message

Return Values

Returns the message. Throws ZMQSocketException in error. If ZMQ::MODE_DONTWAIT is used and the operation would block boolean false shall be returned.


Receives a multipart message

  • « ZMQSocket::recv
  • ZMQSocket::send »
  • PHP Manual
  • ZMQSocket
  • Receives a multipart message

ZMQSocket::recvMulti

(PECL zmq >= 0.8.0)

ZMQSocket::recvMulti — Receives a multipart message

Description

public ZMQSocket::recvMulti ([ int $mode = 0 ] ) : array

Receive an array multipart message from a socket. By default receiving will block until a message is available unless ZMQ::MODE_NOBLOCK flag is used.

Parameters

mode

Pass mode flags to receive multipart messages or non-blocking operation. See ZMQ::MODE_* constants.

Return Values

Returns the array of message parts. Throws ZMQSocketException in error. If ZMQ::MODE_NOBLOCK is used and the operation would block boolean false shall be returned.


Sends a message

  • « ZMQSocket::recvMulti
  • ZMQSocket::sendmulti »
  • PHP Manual
  • ZMQSocket
  • Sends a message

ZMQSocket::send

(PECL zmq >= 0.5.0)

ZMQSocket::send — Sends a message

Description

public ZMQSocket::send ( string $message [, int $mode = 0 ] ) : ZMQSocket

Send a message using the socket. The operation can block unless ZMQ::MODE_NOBLOCK is used.

Parameters

message

The message to send.

mode

Pass mode flags to receive multipart messages or non-blocking operation. See ZMQ::MODE_* constants.

Return Values

Returns the current object. Throws ZMQSocketException on error. If ZMQ::MODE_NOBLOCK is used and the operation would block boolean false shall be returned.


Sends a multipart message

  • « ZMQSocket::send
  • ZMQSocket::setSockOpt »
  • PHP Manual
  • ZMQSocket
  • Sends a multipart message

ZMQSocket::sendmulti

(PECL zmq >= 0.8.0)

ZMQSocket::sendmulti — Sends a multipart message

Description

public ZMQSocket::sendmulti ( array $message [, int $mode = 0 ] ) : ZMQSocket

Send a multipart message using the socket. The operation can block unless ZMQ::MODE_NOBLOCK is used.

Parameters

message

The message to send - an array of strings

mode

Pass mode flags to receive multipart messages or non-blocking operation. See ZMQ::MODE_* constants.

Return Values

Returns the current object. Throws ZMQSocketException on error. If ZMQ::MODE_NOBLOCK is used and the operation would block boolean false shall be returned.


Set a socket option

  • « ZMQSocket::sendmulti
  • ZMQSocket::unbind »
  • PHP Manual
  • ZMQSocket
  • Set a socket option

ZMQSocket::setSockOpt

(PECL zmq >= 0.5.0)

ZMQSocket::setSockOpt — Set a socket option

Description

public ZMQSocket::setSockOpt ( int $key , mixed $value ) : ZMQSocket

Sets a ZMQ socket option. The type of the value depends on the key. See ZMQ Constant Types for more information.

Parameters

key

One of the ZMQ::SOCKOPT_* constants.

value

The value of the parameter.

Return Values

Returns the current object. Throws ZMQSocketException on error.


Unbind the socket

  • « ZMQSocket::setSockOpt
  • ZMQPoll »
  • PHP Manual
  • ZMQSocket
  • Unbind the socket

ZMQSocket::unbind

(PECL zmq >= 1.0.4)

ZMQSocket::unbind — Unbind the socket

Description

public ZMQSocket::unbind ( string $dsn ) : ZMQSocket

Unbind the socket from an endpoint. The endpoint is defined in format transport://address where transport is one of the following: inproc, ipc, tcp, pgm or epgm.

Parameters

dsn

The previously bound dsn, for example transport://address.

Return Values

Returns the current object. Throws ZMQSocketException on error.


The ZMQPoll class

(No version information available, might only be in Git)

Introduction

Class synopsis

ZMQPoll {
/* Methods */
public add ( mixed $entry , int $type ) : string
public clear ( void ) : ZMQPoll
public count ( void ) : int
public getLastErrors ( void ) : array
public poll ( array &$readable , array &$writable [, int $timeout = -1 ] ) : int
public remove ( mixed $item ) : bool
}

Table of Contents

  • ZMQPoll::add — Add item to the poll set
  • ZMQPoll::clear — Clear the poll set
  • ZMQPoll::count — Count items in the poll set
  • ZMQPoll::getLastErrors — Get poll errors
  • ZMQPoll::poll — Poll the items
  • ZMQPoll::remove — Remove item from poll set


Add item to the poll set

  • « ZMQPoll
  • ZMQPoll::clear »
  • PHP Manual
  • ZMQPoll
  • Add item to the poll set

ZMQPoll::add

(PECL zmq >= 0.5.0)

ZMQPoll::add — Add item to the poll set

Description

public ZMQPoll::add ( mixed $entry , int $type ) : string

Adds a new item to the poll set and returns the internal id of the added item. The item can be removed from the poll set using the returned string id.

Parameters

entry

ZMQSocket object or a PHP stream resource

type

Defines what activity the socket is polled for. See ZMQ::POLL_IN and ZMQ::POLL_OUT constants.

Return Values

Returns a string id of the added item which can be later used to remove the item. Throws ZMQPollException on error.


Clear the poll set

  • « ZMQPoll::add
  • ZMQPoll::count »
  • PHP Manual
  • ZMQPoll
  • Clear the poll set

ZMQPoll::clear

(PECL zmq >= 0.5.0)

ZMQPoll::clear — Clear the poll set

Description

public ZMQPoll::clear ( void ) : ZMQPoll

Clears all elements from the poll set.

Parameters

This function has no parameters.

Return Values

Returns the current object.


Count items in the poll set

  • « ZMQPoll::clear
  • ZMQPoll::getLastErrors »
  • PHP Manual
  • ZMQPoll
  • Count items in the poll set

ZMQPoll::count

(PECL zmq >= 0.5.0)

ZMQPoll::count — Count items in the poll set

Description

public ZMQPoll::count ( void ) : int

Count the items in the poll set.

Parameters

This function has no parameters.

Return Values

Returns an integer representing the amount of items in the poll set.


Get poll errors

  • « ZMQPoll::count
  • ZMQPoll::poll »
  • PHP Manual
  • ZMQPoll
  • Get poll errors

ZMQPoll::getLastErrors

(PECL zmq >= 0.5.0)

ZMQPoll::getLastErrors — Get poll errors

Description

public ZMQPoll::getLastErrors ( void ) : array

Returns the ids of the objects that had errors in the last poll.

Parameters

This function has no parameters.

Return Values

Returns an array containing ids for the items that had errors in the last poll. Empty array is returned if there were no errors.


Poll the items

  • « ZMQPoll::getLastErrors
  • ZMQPoll::remove »
  • PHP Manual
  • ZMQPoll
  • Poll the items

ZMQPoll::poll

(PECL zmq >= 0.5.0)

ZMQPoll::poll — Poll the items

Description

public ZMQPoll::poll ( array &$readable , array &$writable [, int $timeout = -1 ] ) : int

Polls the items in the current poll set. The readable and writable items are returned in the readable and writable parameters. ZMQPoll::getLastErrors() can be used to check if there were errors.

Parameters

readable

Array where readable ZMQSockets/PHP streams are returned. The array will be cleared at the beginning of the operation.

writable

Array where writable ZMQSockets/PHP streams are returned. The array will be cleared at the beginning of the operation.

timeout

Timeout for the operation. -1 means that poll waits until at least one item has activity. Please note that starting from version 1.0.0 the poll timeout is defined in milliseconds, rather than microseconds.

Examples

Example #1 A ZMQPoll() example

Create a simple poll server

<?php

/* Create socket, request-reply pattern (reply socket) */
$context = new ZMQContext();
$server  = $context->getSocket(ZMQ::SOCKET_REP);

/* Bind to port 5555 on 127.0.0.1 */
$server->bind("tcp://127.0.0.1:5555");

/* Create new pollset for incoming/outgoing message */
$poll = new ZMQPoll();

/* Add the object and listen for poll in/out */
$id = $poll->add($server, ZMQ::POLL_IN | ZMQ::POLL_OUT);
echo "Added object with id " . $id . "\n";

/* Initialise readable and writable arrays */
$readable = array();
$writable = array();

while (true) {
   /* Amount of events retrieved */
   $events = 0;

   try {
       /* Poll until there is something to do */
       $events = $poll->poll($readable, $writable, -1);
       $errors = $poll->getLastErrors();

       if (count($errors) > 0) {
           foreach ($errors as $error) {
               echo "Error polling object " . $error . "\n";
           }
       }
   } catch (ZMQPollException $e) {
       echo "poll failed: " . $e->getMessage() . "\n";
   }

   if ($events > 0) {
       /* Loop through readable objects and recv messages */
       foreach ($readable as $r) {
           try {
               echo "Received message: " . $r->recv() . "\n";
           } catch (ZMQException $e) {
               echo "recv failed: " . $e->getMessage() . "\n";
           }
       }

       /* Loop through writable and send back messages */
       foreach ($writable as $w) {
           try {
               $w->send("Got it!");
           } catch (ZMQException $e) {
               echo "send failed: " . $e->getMessage() . "\n";
           }
       }
   }
}
?>

Return Values

Returns an integer representing amount of items with activity. Throws ZMQPollException on error.


Remove item from poll set

  • « ZMQPoll::poll
  • ZMQDevice »
  • PHP Manual
  • ZMQPoll
  • Remove item from poll set

ZMQPoll::remove

(PECL zmq >= 0.5.0)

ZMQPoll::remove — Remove item from poll set

Description

public ZMQPoll::remove ( mixed $item ) : bool

Remove item from the poll set. The item parameter can be ZMQSocket object, a stream resource or the id returned from ZMQPoll::add() method.

Parameters

item

The ZMQSocket object, PHP stream or string id of the item.

Return Values

Returns true if the item was removed and false if the object with given id does not exist in the poll set.


The ZMQDevice class

(No version information available, might only be in Git)

Introduction

Class synopsis

ZMQDevice {
/* Methods */
__construct ( ZMQSocket $frontend , ZMQSocket $backend [, ZMQSocket $listener ] )
public getIdleTimeout ( void ) : ZMQDevice
public getTimerTimeout ( void ) : ZMQDevice
public run ( void ) : void
public setIdleCallback ( callable $cb_func , int $timeout [, mixed $user_data ] ) : ZMQDevice
public setIdleTimeout ( int $timeout ) : ZMQDevice
public setTimerCallback ( callable $cb_func , int $timeout [, mixed $user_data ] ) : ZMQDevice
public setTimerTimeout ( int $timeout ) : ZMQDevice
}

Table of Contents

  • ZMQDevice::__construct — Construct a new device
  • ZMQDevice::getIdleTimeout — Get the idle timeout
  • ZMQDevice::getTimerTimeout — Get the timer timeout
  • ZMQDevice::run — Run the new device
  • ZMQDevice::setIdleCallback — Set the idle callback function
  • ZMQDevice::setIdleTimeout — Set the idle timeout
  • ZMQDevice::setTimerCallback — Set the timer callback function
  • ZMQDevice::setTimerTimeout — Set the timer timeout


Construct a new device

  • « ZMQDevice
  • ZMQDevice::getIdleTimeout »
  • PHP Manual
  • ZMQDevice
  • Construct a new device

ZMQDevice::__construct

(PECL zmq >= 0.5.0)

ZMQDevice::__construct — Construct a new device

Description

ZMQDevice::__construct ( ZMQSocket $frontend , ZMQSocket $backend [, ZMQSocket $listener ] )

"ØMQ devices can do intermediation of addresses, services, queues, or any other abstraction you care to define above the message and socket layers." -- zguide

Parameters

frontend

Frontend parameter for the devices. Usually where there messages are coming.

backend

Backend parameter for the devices. Usually where there messages going to.

listener

Listener socket, which receives a copy of all messages going both directions. The type of this socket should be SUB, PULL or DEALER.

Return Values

Call to this method will prepare the device. Usually devices are very long running processes so running this method from interactive script is not recommended. This method throw ZMQDeviceException if the device cannot be started.


Get the idle timeout

  • « ZMQDevice::__construct
  • ZMQDevice::getTimerTimeout »
  • PHP Manual
  • ZMQDevice
  • Get the idle timeout

ZMQDevice::getIdleTimeout

(No version information available, might only be in Git)

ZMQDevice::getIdleTimeout — Get the idle timeout

Description

public ZMQDevice::getIdleTimeout ( void ) : ZMQDevice

Gets the idle callback timeout value. Added in ZMQ extension version 1.1.0.

Return Values

This method returns the idle callback timeout value.


Get the timer timeout

  • « ZMQDevice::getIdleTimeout
  • ZMQDevice::run »
  • PHP Manual
  • ZMQDevice
  • Get the timer timeout

ZMQDevice::getTimerTimeout

(No version information available, might only be in Git)

ZMQDevice::getTimerTimeout — Get the timer timeout

Description

public ZMQDevice::getTimerTimeout ( void ) : ZMQDevice

Gets the timer callback timeout value. Added in ZMQ extension version 1.1.0.

Return Values

This method returns the timer timeout value.


Run the new device

  • « ZMQDevice::getTimerTimeout
  • ZMQDevice::setIdleCallback »
  • PHP Manual
  • ZMQDevice
  • Run the new device

ZMQDevice::run

(No version information available, might only be in Git)

ZMQDevice::run — Run the new device

Description

public ZMQDevice::run ( void ) : void

Runs the device.

Parameters

This function has no parameters.

Return Values

Call to this method will block until the device is running. It is not recommended that devices are used from interactive scripts. On failure this method will throw ZMQDeviceException.


Set the idle callback function

  • « ZMQDevice::run
  • ZMQDevice::setIdleTimeout »
  • PHP Manual
  • ZMQDevice
  • Set the idle callback function

ZMQDevice::setIdleCallback

(No version information available, might only be in Git)

ZMQDevice::setIdleCallback — Set the idle callback function

Description

public ZMQDevice::setIdleCallback ( callable $cb_func , int $timeout [, mixed $user_data ] ) : ZMQDevice

Sets the idle callback function. If idle timeout is defined the idle callback function shall be called if the internal poll loop times out without events. If the callback function returns false or a value that evaluates to false the device is stopped. The callback function signature is callback (mixed $user_data).

Parameters

cb_func

Callback function to invoke when the device is idle. Returning false or a value that evaluates to false from this function will cause the device to stop.

timeout

How often to invoke the idle callback in milliseconds. The idle callback is invoked periodically when there is no activity on the device. The timeout value guarantees that there is at least this amount of milliseconds between invocations of the callback function.

user_data

Additional data to pass to the callback function.

Return Values

On success this method returns the current object.


Set the idle timeout

  • « ZMQDevice::setIdleCallback
  • ZMQDevice::setTimerCallback »
  • PHP Manual
  • ZMQDevice
  • Set the idle timeout

ZMQDevice::setIdleTimeout

(No version information available, might only be in Git)

ZMQDevice::setIdleTimeout — Set the idle timeout

Description

public ZMQDevice::setIdleTimeout ( int $timeout ) : ZMQDevice

Sets the idle callback timeout value. The idle callback is invoked periodically when the device is idle.

Parameters

timeout

The idle callback timeout value.

Return Values

On success this method returns the current object.


Set the timer callback function

  • « ZMQDevice::setIdleTimeout
  • ZMQDevice::setTimerTimeout »
  • PHP Manual
  • ZMQDevice
  • Set the timer callback function

ZMQDevice::setTimerCallback

(No version information available, might only be in Git)

ZMQDevice::setTimerCallback — Set the timer callback function

Description

public ZMQDevice::setTimerCallback ( callable $cb_func , int $timeout [, mixed $user_data ] ) : ZMQDevice

Sets the timer callback function. The timer callback will be invoked after timeout has passed. The difference between idle and timer callbacks are that idle callback is invoked only when the device is idle. The callback function signature is callback (mixed $user_data). Added in ZMQ extension version 1.1.0.

Parameters

cb_func

Callback function to invoke when the device is idle. Returning false or a value that evaluates to false from this function will cause the device to stop.

timeout

How often to invoke the idle callback in milliseconds. The idle callback is invoked periodically when there is no activity on the device. The timeout value guarantees that there is at least this amount of milliseconds between invocations of the callback function.

user_data

Additional data to pass to the callback function.

Return Values

On success this method returns the current object.


Set the timer timeout

  • « ZMQDevice::setTimerCallback
  • ZooKeeper »
  • PHP Manual
  • ZMQDevice
  • Set the timer timeout

ZMQDevice::setTimerTimeout

(No version information available, might only be in Git)

ZMQDevice::setTimerTimeout — Set the timer timeout

Description

public ZMQDevice::setTimerTimeout ( int $timeout ) : ZMQDevice

Sets the timer callback timeout value. The timer callback is invoked periodically if it's set. Added in ZMQ extension version 1.1.0.

Parameters

timeout

The timer callback timeout value.

Return Values

On success this method returns the current object.


ZooKeeper

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • ZooKeeper Functions
    • zookeeper_dispatch — Calls callbacks for pending operations
  • Zookeeper — The Zookeeper class
    • Zookeeper::addAuth — Specify application credentials
    • Zookeeper::close — Close the zookeeper handle and free up any resources
    • Zookeeper::connect — Create a handle to used communicate with zookeeper
    • Zookeeper::__construct — Create a handle to used communicate with zookeeper
    • Zookeeper::create — Create a node synchronously
    • Zookeeper::delete — Delete a node in zookeeper synchronously
    • Zookeeper::exists — Checks the existence of a node in zookeeper synchronously
    • Zookeeper::get — Gets the data associated with a node synchronously
    • Zookeeper::getAcl — Gets the acl associated with a node synchronously
    • Zookeeper::getChildren — Lists the children of a node synchronously
    • Zookeeper::getClientId — Return the client session id, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE)
    • Zookeeper::getConfig — Get instance of ZookeeperConfig
    • Zookeeper::getRecvTimeout — Return the timeout for this session, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE). This value may change after a server re-connect
    • Zookeeper::getState — Get the state of the zookeeper connection
    • Zookeeper::isRecoverable — Checks if the current zookeeper connection state can be recovered
    • Zookeeper::set — Sets the data associated with a node
    • Zookeeper::setAcl — Sets the acl associated with a node synchronously
    • Zookeeper::setDebugLevel — Sets the debugging level for the library
    • Zookeeper::setDeterministicConnOrder — Enable/disable quorum endpoint order randomization
    • Zookeeper::setLogStream — Sets the stream to be used by the library for logging
    • Zookeeper::setWatcher — Set a watcher function
  • ZookeeperConfig — The ZookeeperConfig class
    • ZookeeperConfig::add — Add servers to the ensemble
    • ZookeeperConfig::get — Gets the last committed configuration of the ZooKeeper cluster as it is known to the server to which the client is connected, synchronously
    • ZookeeperConfig::remove — Remove servers from the ensemble
    • ZookeeperConfig::set — Change ZK cluster ensemble membership and roles of ensemble peers
  • ZookeeperException — The ZookeeperException class
  • ZookeeperAuthenticationException — The ZookeeperAuthenticationException class
  • ZookeeperConnectionException — The ZookeeperConnectionException class
  • ZookeeperMarshallingException — The ZookeeperMarshallingException class
  • ZookeeperNoNodeException — The ZookeeperNoNodeException class
  • ZookeeperOperationTimeoutException — The ZookeeperOperationTimeoutException class
  • ZookeeperSessionException — The ZookeeperSessionException class


Introduction

This extension uses libzookeeper library to provide API for communicating with ZooKeeper service.

ZooKeeper is an Apache project that enables centralized service for maintaining configuration information, naming, providing distributed synchronization, and providing group services.


Requirements

This extension requires » ZooKeeper C Binding (version 3.4.1 or greater). For more information, see » ZooKeeper Programmer's Guide.

This extension requires PHP version 5.2.0 or higher. Since 0.6.0, it requires PHP version 7.0.0 or higher.


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/zookeeper.

To enable zookeeper support, configure with --with-libzookeeper-dir=DIR . DIR is the install prefix of ZooKeeper C Binding, which must contain the include/zookeeper/zookeeper.h

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Zookeeper Configure Options
Name | Default | Changeable | Changelog
zookeeper.recv_timeout | 10000 | PHP_INI_ALL |
zookeeper.session_lock | 1 | PHP_INI_SYSTEM |
zookeeper.sess_lock_wait | 150000 | PHP_INI_ALL |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

zookeeper.recv_timeout integer

Default the timeout for any ZooKeeper session.

zookeeper.session_lock integer

Enable PHP session locking.

zookeeper.sess_lock_wait integer

PHP Session spin lock retry wait time in microseconds. Be carefull when setting this value. Valid values are integers, where 0 is interpreted as the default value. Negative values result in a reduces locking to a try lock.


  • « Resource Types
  • ZooKeeper Functions »
  • PHP Manual
  • ZooKeeper
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


  • « Predefined Constants
  • zookeeper_dispatch »
  • PHP Manual
  • ZooKeeper
  • ZooKeeper Functions

ZooKeeper Functions

Table of Contents

  • zookeeper_dispatch — Calls callbacks for pending operations


Calls callbacks for pending operations

  • « ZooKeeper Functions
  • Zookeeper »
  • PHP Manual
  • ZooKeeper Functions
  • Calls callbacks for pending operations

zookeeper_dispatch

(PECL zookeeper >= 0.4.0)

zookeeper_dispatch — Calls callbacks for pending operations

Description

zookeeper_dispatch ( void ) : void

The zookeeper_dispatch() function calls the callbacks passwd by operations like Zookeeper::get() or Zookeeper::exists().

Caution

Since version 0.4.0, this function must be called manually to achieve asynchronous operations. If you want that to be done automatically, you also can declare ticks at the beginning of your program.

After PHP 7.1, you can ignore this function. This extension uses EG(vm_interrupt) to implement async dispatch.

Errors/Exceptions

This method emits PHP warning when callback could not be invoked.

Examples

Example #1 zookeeper_dispatch() example #1

Dispatch callbacks manually.

<?php
$client = new Zookeeper();
$client->connect('localhost:2181');
$client->get('/zookeeper', function() {
    echo "Callback was called".PHP_EOL;
});
while(true) {
    sleep(1);
    zookeeper_dispatch();
}
?>

Example #2 zookeeper_dispatch() example #2

Declare ticks.

<?php
declare(ticks=1);

$client = new Zookeeper();
$client->connect('localhost:2181');
$client->get('/zookeeper', function() {
    echo "Callback was called".PHP_EOL;
});
while(true) {
    sleep(1);
}
?>

See Also

  • Zookeeper::addAuth() - Specify application credentials
  • Zookeeper::connect() - Create a handle to used communicate with zookeeper
  • Zookeeper::__construct() - Create a handle to used communicate with zookeeper
  • Zookeeper::exists() - Checks the existence of a node in zookeeper synchronously
  • Zookeeper::get() - Gets the data associated with a node synchronously
  • Zookeeper::getChildren() - Lists the children of a node synchronously
  • Zookeeper::setWatcher() - Set a watcher function


The Zookeeper class

(PECL zookeeper >= 0.1.0)

Introduction

Represents ZooKeeper session.

Class synopsis

Zookeeper {
/* Methods */
public __construct ([ string $host = '' [, callable $watcher_cb = NULL [, int $recv_timeout = 10000 ]]] )
public addAuth ( string $scheme , string $cert [, callable $completion_cb = NULL ] ) : bool
public close ( void ) : void
public connect ( string $host [, callable $watcher_cb = NULL [, int $recv_timeout = 10000 ]] ) : void
public create ( string $path , string $value , array $acls [, int $flags = NULL ] ) : string
public delete ( string $path [, int $version = -1 ] ) : bool
public exists ( string $path [, callable $watcher_cb = NULL ] ) : array
public get ( string $path [, callable $watcher_cb = NULL [, array &$stat = NULL [, int $max_size = 0 ]]] ) : string
public getAcl ( string $path ) : array
public getChildren ( string $path [, callable $watcher_cb = NULL ] ) : array
public getClientId ( void ) : int
public getConfig ( void ) : ZookeeperConfig
public getRecvTimeout ( void ) : int
public getState ( void ) : int
public isRecoverable ( void ) : bool
public set ( string $path , string $value [, int $version = -1 [, array &$stat = NULL ]] ) : bool
public setAcl ( string $path , int $version , array $acl ) : bool
public static setDebugLevel ( int $logLevel ) : bool
public static setDeterministicConnOrder ( bool $yesOrNo ) : bool
public setLogStream ( resource $stream ) : bool
public setWatcher ( callable $watcher_cb ) : bool
/* Constants */
const integer PERM_READ = 1 ;
const integer PERM_WRITE = 2 ;
const integer PERM_CREATE = 4 ;
const integer PERM_DELETE = 8 ;
const integer PERM_ADMIN = 16 ;
const integer PERM_ALL = 31 ;
const integer EPHEMERAL = 1 ;
const integer SEQUENCE = 2 ;
const integer LOG_LEVEL_ERROR = 1 ;
const integer LOG_LEVEL_WARN = 2 ;
const integer LOG_LEVEL_INFO = 3 ;
const integer LOG_LEVEL_DEBUG = 4 ;
const integer EXPIRED_SESSION_STATE = -112 ;
const integer AUTH_FAILED_STATE = -113 ;
const integer CONNECTING_STATE = 1 ;
const integer ASSOCIATING_STATE = 2 ;
const integer CONNECTED_STATE = 3 ;
const integer READONLY_STATE = 5 ;
const integer NOTCONNECTED_STATE = 999 ;
const integer CREATED_EVENT = 1 ;
const integer DELETED_EVENT = 2 ;
const integer CHANGED_EVENT = 3 ;
const integer CHILD_EVENT = 4 ;
const integer SESSION_EVENT = -1 ;
const integer NOTWATCHING_EVENT = -2 ;
const integer SYSTEMERROR = -1 ;
const integer RUNTIMEINCONSISTENCY = -2 ;
const integer DATAINCONSISTENCY = -3 ;
const integer CONNECTIONLOSS = -4 ;
const integer MARSHALLINGERROR = -5 ;
const integer UNIMPLEMENTED = -6 ;
const integer OPERATIONTIMEOUT = -7 ;
const integer BADARGUMENTS = -8 ;
const integer INVALIDSTATE = -9 ;
const integer NEWCONFIGNOQUORUM = -13 ;
const integer RECONFIGINPROGRESS = -14 ;
const integer OK = 0 ;
const integer APIERROR = -100 ;
const integer NONODE = -101 ;
const integer NOAUTH = -102 ;
const integer BADVERSION = -103 ;
const integer NOCHILDRENFOREPHEMERALS = -108 ;
const integer NODEEXISTS = -110 ;
const integer NOTEMPTY = -111 ;
const integer SESSIONEXPIRED = -112 ;
const integer INVALIDCALLBACK = -113 ;
const integer INVALIDACL = -114 ;
const integer AUTHFAILED = -115 ;
const integer CLOSING = -116 ;
const integer NOTHING = -117 ;
const integer SESSIONMOVED = -118 ;
const integer NOTREADONLY = -119 ;
const integer EPHEMERALONLOCALSESSION = -120 ;
const integer NOWATCHER = -121 ;
const integer RECONFIGDISABLED = -122 ;
}

Predefined Constants

ZooKeeper Permissions

Zookeeper::PERM_READ

Can read nodes value and list its children

Zookeeper::PERM_WRITE

Can set the nodes value

Zookeeper::PERM_CREATE

Can create children

Zookeeper::PERM_DELETE

Can delete children

Zookeeper::PERM_ADMIN

Can execute set_acl()

Zookeeper::PERM_ALL

All of the above flags ORd together

ZooKeeper Create Flags

Zookeeper::EPHEMERAL

If Zookeeper::EPHEMERAL flag is set, the node will automatically get removed if the client session goes away.

Zookeeper::SEQUENCE

If the Zookeeper::SEQUENCE flag is set, a unique monotonically increasing sequence number is appended to the path name. The sequence number is always fixed length of 10 digits, 0 padded.

ZooKeeper Log Levels

Zookeeper::LOG_LEVEL_ERROR

Outputs only error mesages

Zookeeper::LOG_LEVEL_WARN

Outputs errors/warnings

Zookeeper::LOG_LEVEL_INFO

Outputs big action messages besides errors/warnings

Zookeeper::LOG_LEVEL_DEBUG

Outputs all

ZooKeeper States

Zookeeper::EXPIRED_SESSION_STATE

Connected but session expired

Zookeeper::AUTH_FAILED_STATE

Connected but auth failed

Zookeeper::CONNECTING_STATE

Connecting

Zookeeper::ASSOCIATING_STATE

Associating

Zookeeper::CONNECTED_STATE

Connected

Zookeeper::READONLY_STATE

TODO: help us improve this extension.

Zookeeper::NOTCONNECTED_STATE

Connection failed

ZooKeeper Watch Types

Zookeeper::CREATED_EVENT

A node has been created

This is only generated by watches on non-existent nodes. These watches are set using Zookeeper::exists.

Zookeeper::DELETED_EVENT

A node has been deleted

This is only generated by watches on nodes. These watches are set using Zookeeper::exists and Zookeeper::get.

Zookeeper::CHANGED_EVENT

A node has changed

This is only generated by watches on nodes. These watches are set using Zookeeper::exists and Zookeeper::get.

Zookeeper::CHILD_EVENT

A change as occurred in the list of children

This is only generated by watches on the child list of a node. These watches are set using Zookeeper::getChildren.

Zookeeper::SESSION_EVENT

A session has been lost

This is generated when a client loses contact or reconnects with a server.

Zookeeper::NOTWATCHING_EVENT

A watch has been removed

This is generated when the server for some reason, probably a resource constraint, will no longer watch a node for a client.

ZooKeeper System and Server-side Errors

Zookeeper::SYSTEMERROR

This is never thrown by the server, it shouldn't be used other than to indicate a range. Specifically error codes greater than this value, but lesser than Zookeeper::APIERROR, are system errors.

Zookeeper::RUNTIMEINCONSISTENCY

A runtime inconsistency was found.

Zookeeper::DATAINCONSISTENCY

A data inconsistency was found.

Zookeeper::CONNECTIONLOSS

Connection to the server has been lost.

Zookeeper::MARSHALLINGERROR

Error while marshalling or unmarshalling data.

Zookeeper::UNIMPLEMENTED

Operation is unimplemented.

Zookeeper::OPERATIONTIMEOUT

Operation timeout.

Zookeeper::BADARGUMENTS

Invalid arguments.

Zookeeper::INVALIDSTATE

Invliad zhandle state.

Zookeeper::NEWCONFIGNOQUORUM

No quorum of new config is connected and up-to-date with the leader of last committed config - try invoking reconfiguration after new servers are connected and synced.

Available as of ZooKeeper 3.5.0

Zookeeper::RECONFIGINPROGRESS

Reconfiguration requested while another reconfiguration is currently in progress. This is currently not supported. Please retry.

Available as of ZooKeeper 3.5.0

ZooKeeper API Errors

Zookeeper::OK

Everything is OK.

Zookeeper::APIERROR

This is never thrown by the server, it shouldn't be used other than to indicate a range. Specifically error codes greater than this value are API errors (while values less than this indicate a Zookeeper::SYSTEMERROR).

Zookeeper::NONODE

Node does not exist.

Zookeeper::NOAUTH

Not authenticated.

Zookeeper::BADVERSION

Version conflict.

Zookeeper::NOCHILDRENFOREPHEMERALS

Ephemeral nodes may not have children.

Zookeeper::NODEEXISTS

The node already exists.

Zookeeper::NOTEMPTY

The node has children.

Zookeeper::SESSIONEXPIRED

The session has been expired by the server.

Zookeeper::INVALIDCALLBACK

Invalid callback specified.

Zookeeper::INVALIDACL

Invalid ACL specified.

Zookeeper::AUTHFAILED

Client authentication failed.

Zookeeper::CLOSING

ZooKeeper is closing.

Zookeeper::NOTHING

(not error) No server responses to process.

Zookeeper::SESSIONMOVED

Session moved to another server, so operation is ignored.

Zookeeper::NOTREADONLY

State-changing request is passed to read-only server.

Zookeeper::EPHEMERALONLOCALSESSION

Attempt to create ephemeral node on a local session.

Zookeeper::NOWATCHER

The watcher couldn't be found.

Zookeeper::RECONFIGDISABLED

Attempts to perform a reconfiguration operation when reconfiguration feature is disabled.

Table of Contents

  • Zookeeper::addAuth — Specify application credentials
  • Zookeeper::close — Close the zookeeper handle and free up any resources
  • Zookeeper::connect — Create a handle to used communicate with zookeeper
  • Zookeeper::__construct — Create a handle to used communicate with zookeeper
  • Zookeeper::create — Create a node synchronously
  • Zookeeper::delete — Delete a node in zookeeper synchronously
  • Zookeeper::exists — Checks the existence of a node in zookeeper synchronously
  • Zookeeper::get — Gets the data associated with a node synchronously
  • Zookeeper::getAcl — Gets the acl associated with a node synchronously
  • Zookeeper::getChildren — Lists the children of a node synchronously
  • Zookeeper::getClientId — Return the client session id, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE)
  • Zookeeper::getConfig — Get instance of ZookeeperConfig
  • Zookeeper::getRecvTimeout — Return the timeout for this session, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE). This value may change after a server re-connect
  • Zookeeper::getState — Get the state of the zookeeper connection
  • Zookeeper::isRecoverable — Checks if the current zookeeper connection state can be recovered
  • Zookeeper::set — Sets the data associated with a node
  • Zookeeper::setAcl — Sets the acl associated with a node synchronously
  • Zookeeper::setDebugLevel — Sets the debugging level for the library
  • Zookeeper::setDeterministicConnOrder — Enable/disable quorum endpoint order randomization
  • Zookeeper::setLogStream — Sets the stream to be used by the library for logging
  • Zookeeper::setWatcher — Set a watcher function


Specify application credentials

  • « Zookeeper
  • Zookeeper::close »
  • PHP Manual
  • Zookeeper
  • Specify application credentials

Zookeeper::addAuth

(PECL zookeeper >= 0.1.0)

Zookeeper::addAuth — Specify application credentials

Description

public Zookeeper::addAuth ( string $scheme , string $cert [, callable $completion_cb = NULL ] ) : bool

The application calls this function to specify its credentials for purposes of authentication. The server will use the security provider specified by the scheme parameter to authenticate the client connection. If the authentication request has failed: - the server connection is dropped. - the watcher is called with the ZOO_AUTH_FAILED_STATE value as the state parameter.

Parameters

scheme

The id of authentication scheme. Natively supported: "digest" password-based authentication

cert

Application credentials. The actual value depends on the scheme.

completion_cb

The routine to invoke when the request completes. One of the following result codes may be passed into the completion callback: - ZOK operation completed successfully - ZAUTHFAILED authentication failed

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

This method emits PHP error/warning when parameters count or types are wrong or operation fails.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

Examples

Example #1 Zookeeper::addAuth() example

Add auth before requesting node value.

<?php
$zookeeper = new Zookeeper('locahost:2181');
$path = '/path/to/node';
$value = 'nodevalue';
$zookeeper->set($path, $value);

$zookeeper->addAuth('digest', 'user0:passwd0');
$r = $zookeeper->get($path);
if ($r)
  echo $r;
else
  echo 'ERR';
?>

The above example will output:

nodevalue

See Also

  • Zookeeper::create() - Create a node synchronously
  • Zookeeper::setAcl() - Sets the acl associated with a node synchronously
  • Zookeeper::getAcl() - Gets the acl associated with a node synchronously
  • ZooKeeper States
  • ZookeeperException


Close the zookeeper handle and free up any resources

  • « Zookeeper::addAuth
  • Zookeeper::connect »
  • PHP Manual
  • Zookeeper
  • Close the zookeeper handle and free up any resources

Zookeeper::close

(PECL zookeeper >= 0.5.0)

Zookeeper::close — Close the zookeeper handle and free up any resources

Description

public Zookeeper::close ( void ) : void

Errors/Exceptions

This method emits ZookeeperException and it's derivatives when closing an uninitialized instance.

See Also

  • Zookeeper::__construct() - Create a handle to used communicate with zookeeper
  • Zookeeper::connect() - Create a handle to used communicate with zookeeper
  • ZookeeperException


Create a handle to used communicate with zookeeper

  • « Zookeeper::close
  • Zookeeper::__construct »
  • PHP Manual
  • Zookeeper
  • Create a handle to used communicate with zookeeper

Zookeeper::connect

(PECL zookeeper >= 0.2.0)

Zookeeper::connect — Create a handle to used communicate with zookeeper

Description

public Zookeeper::connect ( string $host [, callable $watcher_cb = NULL [, int $recv_timeout = 10000 ]] ) : void

This method creates a new handle and a zookeeper session that corresponds to that handle. Session establishment is asynchronous, meaning that the session should not be considered established until (and unless) an event of state ZOO_CONNECTED_STATE is received.

Parameters

host

Comma separated host:port pairs, each corresponding to a zk server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002"

watcher_cb

The global watcher callback function. When notifications are triggered this function will be invoked.

recv_timeout

The timeout for this session, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE).

Errors/Exceptions

This method emits PHP error/warning when parameters count or types are wrong or could not init instance.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

See Also

  • Zookeeper::__construct() - Create a handle to used communicate with zookeeper
  • ZookeeperException


Create a handle to used communicate with zookeeper

  • « Zookeeper::connect
  • Zookeeper::create »
  • PHP Manual
  • Zookeeper
  • Create a handle to used communicate with zookeeper

Zookeeper::__construct

(PECL zookeeper >= 0.1.0)

Zookeeper::__construct — Create a handle to used communicate with zookeeper

Description

public Zookeeper::__construct ([ string $host = '' [, callable $watcher_cb = NULL [, int $recv_timeout = 10000 ]]] )

This method creates a new handle and a zookeeper session that corresponds to that handle. Session establishment is asynchronous, meaning that the session should not be considered established until (and unless) an event of state ZOO_CONNECTED_STATE is received.

Parameters

host

comma separated host:port pairs, each corresponding to a zk server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002"

watcher_cb

the global watcher callback function. When notifications are triggered this function will be invoked.

recv_timeout

the timeout for this session, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE).

Errors/Exceptions

This method emits PHP error/warning when parameters count or types are wrong or could not init instance.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

See Also

  • Zookeeper::connect() - Create a handle to used communicate with zookeeper
  • ZookeeperException


Create a node synchronously

  • « Zookeeper::__construct
  • Zookeeper::delete »
  • PHP Manual
  • Zookeeper
  • Create a node synchronously

Zookeeper::create

(PECL zookeeper >= 0.1.0)

Zookeeper::create — Create a node synchronously

Description

public Zookeeper::create ( string $path , string $value , array $acls [, int $flags = NULL ] ) : string

This method will create a node in ZooKeeper. A node can only be created if it does not already exists. The Create Flags affect the creation of nodes. If ZOO_EPHEMERAL flag is set, the node will automatically get removed if the client session goes away. If the ZOO_SEQUENCE flag is set, a unique monotonically increasing sequence number is appended to the path name.

Parameters

path

The name of the node. Expressed as a file name with slashes separating ancestors of the node.

value

The data to be stored in the node.

acls

The initial ACL of the node. The ACL must not be null or empty.

flags

this parameter can be set to 0 for normal create or an OR of the Create Flags

Return Values

Returns the path of the new node (this might be different than the supplied path because of the ZOO_SEQUENCE flag) on success, and false on failure.

Errors/Exceptions

This method emits PHP error/warning when parameters count or types are wrong or fail to create node.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

Examples

Example #1 Zookeeper::create() example

Create a new node.

<?php
$zookeeper = new Zookeeper('locahost:2181');
$aclArray = array(
  array(
    'perms'  => Zookeeper::PERM_ALL,
    'scheme' => 'world',
    'id'     => 'anyone',
  )
);
$path = '/path/to/newnode';
$realPath = $zookeeper->create($path, null, $aclArray);
if ($realPath)
  echo $realPath;
else
  echo 'ERR';
?>

The above example will output:

/path/to/newnode

See Also

  • Zookeeper::delete() - Delete a node in zookeeper synchronously
  • Zookeeper::getChildren() - Lists the children of a node synchronously
  • ZooKeeper Permissions
  • ZookeeperException


Delete a node in zookeeper synchronously

  • « Zookeeper::create
  • Zookeeper::exists »
  • PHP Manual
  • Zookeeper
  • Delete a node in zookeeper synchronously

Zookeeper::delete

(PECL zookeeper >= 0.2.0)

Zookeeper::delete — Delete a node in zookeeper synchronously

Description

public Zookeeper::delete ( string $path [, int $version = -1 ] ) : bool

Parameters

path

The name of the node. Expressed as a file name with slashes separating ancestors of the node.

version

The expected version of the node. The function will fail if the actual version of the node does not match the expected version. If -1 is used the version check will not take place.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

This method emits PHP error/warning when parameters count or types are wrong or fail to delete node.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

Examples

Example #1 Zookeeper::delete() example

Delete a existing node.

<?php
$zookeeper = new Zookeeper('locahost:2181');
$path = '/path/to/node';
$r = $zookeeper->delete($path);
if ($r)
  echo 'SUCCESS';
else
  echo 'ERR';
?>

The above example will output:

SUCCESS

See Also

  • Zookeeper::create() - Create a node synchronously
  • Zookeeper::getChildren() - Lists the children of a node synchronously
  • ZookeeperException


Checks the existence of a node in zookeeper synchronously

  • « Zookeeper::delete
  • Zookeeper::get »
  • PHP Manual
  • Zookeeper
  • Checks the existence of a node in zookeeper synchronously

Zookeeper::exists

(PECL zookeeper >= 0.1.0)

Zookeeper::exists — Checks the existence of a node in zookeeper synchronously

Description

public Zookeeper::exists ( string $path [, callable $watcher_cb = NULL ] ) : array

Parameters

path

The name of the node. Expressed as a file name with slashes separating ancestors of the node.

watcher_cb

if nonzero, a watch will be set at the server to notify the client if the node changes. The watch will be set even if the node does not

Return Values

Returns the value of stat for the path if the given node exists, otherwise false.

Errors/Exceptions

This method emits PHP error/warning when parameters count or types are wrong or fail to check the existence of a node.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

Examples

Example #1 Zookeeper::exists() example

Check the existence of a node.

<?php
$zookeeper = new Zookeeper('locahost:2181');
$path = '/path/to/node';
$r = $zookeeper->exists($path);
if ($r)
  echo 'EXISTS';
else
  echo 'N/A or ERR';
?>

The above example will output:

EXISTS

See Also

  • Zookeeper::get() - Gets the data associated with a node synchronously
  • ZookeeperException


Gets the data associated with a node synchronously

  • « Zookeeper::exists
  • Zookeeper::getAcl »
  • PHP Manual
  • Zookeeper
  • Gets the data associated with a node synchronously

Zookeeper::get

(PECL zookeeper >= 0.1.0)

Zookeeper::get — Gets the data associated with a node synchronously

Description

public Zookeeper::get ( string $path [, callable $watcher_cb = NULL [, array &$stat = NULL [, int $max_size = 0 ]]] ) : string

Parameters

path

The name of the node. Expressed as a file name with slashes separating ancestors of the node.

watcher_cb

If nonzero, a watch will be set at the server to notify the client if the node changes.

stat

If not NULL, will hold the value of stat for the path on return.

max_size

Max size of the data. If 0 is used, this method will return the whole data.

Return Values

Returns the data on success, and false on failure.

Errors/Exceptions

This method emits PHP error/warning when parameters count or types are wrong or fail to get value from node.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

Examples

Example #1 Zookeeper::get() example

Get value from node.

<?php
$zookeeper = new Zookeeper('locahost:2181');
$path = '/path/to/node';
$value = 'nodevalue';
$zookeeper->set($path, $value);

$r = $zookeeper->get($path);
if ($r)
  echo $r;
else
  echo 'ERR';
?>

The above example will output:

nodevalue

Example #2 Zookeeper::get() stat example

Get node stat info.

<?php
$zookeeper = new Zookeeper('localhost:2181');
$path = '/path/to/node';
$stat = [];
$zookeeper->get($path, null, $stat);
var_dump($stat);
?>

The above example will output:

array(11) {
  ["czxid"]=>
  float(0)
  ["mzxid"]=>
  float(0)
  ["ctime"]=>
  float(0)
  ["mtime"]=>
  float(0)
  ["version"]=>
  int(0)
  ["cversion"]=>
  int(-2)
  ["aversion"]=>
  int(0)
  ["ephemeralOwner"]=>
  float(0)
  ["dataLength"]=>
  int(0)
  ["numChildren"]=>
  int(2)
  ["pzxid"]=>
  float(0)
}

See Also

  • Zookeeper::set() - Sets the data associated with a node
  • ZookeeperException


Gets the acl associated with a node synchronously

  • « Zookeeper::get
  • Zookeeper::getChildren »
  • PHP Manual
  • Zookeeper
  • Gets the acl associated with a node synchronously

Zookeeper::getAcl

(PECL zookeeper >= 0.1.0)

Zookeeper::getAcl — Gets the acl associated with a node synchronously

Description

public Zookeeper::getAcl ( string $path ) : array

Parameters

path

The name of the node. Expressed as a file name with slashes separating ancestors of the node.

Return Values

Return acl array on success and false on failure.

Errors/Exceptions

This method emits PHP error/warning when parameters count or types are wrong or fail to get ACL of a node.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

Examples

Example #1 Zookeeper::getAcl() example

Get ACL of a node.

<?php
$zookeeper = new Zookeeper('locahost:2181');
$aclArray = array(
  array(
    'perms'  => Zookeeper::PERM_ALL,
    'scheme' => 'world',
    'id'     => 'anyone',
  )
);
$path = '/path/to/newnode';
$zookeeper->setAcl($path, $aclArray);

$r = $zookeeper->getAcl($path);
if ($r)
  var_dump($r);
else
  echo 'ERR';
?>

The above example will output:

array(1) {
  [0]=>
  array(3) {
    ["perms"]=>
    int(31)
    ["scheme"]=>
    string(5) "world"
    ["id"]=>
    string(6) "anyone"
  }
}

See Also

  • Zookeeper::create() - Create a node synchronously
  • Zookeeper::setAcl() - Sets the acl associated with a node synchronously
  • ZooKeeper Permissions
  • ZookeeperException


Lists the children of a node synchronously

  • « Zookeeper::getAcl
  • Zookeeper::getClientId »
  • PHP Manual
  • Zookeeper
  • Lists the children of a node synchronously

Zookeeper::getChildren

(PECL zookeeper >= 0.1.0)

Zookeeper::getChildren — Lists the children of a node synchronously

Description

public Zookeeper::getChildren ( string $path [, callable $watcher_cb = NULL ] ) : array

Parameters

path

The name of the node. Expressed as a file name with slashes separating ancestors of the node.

watcher_cb

If nonzero, a watch will be set at the server to notify the client if the node changes.

Return Values

Returns an array with children paths on success, and false on failure.

Errors/Exceptions

This method emits PHP error/warning when parameters count or types are wrong or fail to list children of a node.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

Examples

Example #1 Zookeeper::getChildren() example

Lists children of a node.

<?php
$zookeeper = new Zookeeper('locahost:2181');
$path = '/zookeeper';
$r = $zookeeper->getchildren($path);
if ($r)
  var_dump($r);
else
  echo 'ERR';
?>

The above example will output:

array(1) {
  [0]=>
  string(6) "config"
}

See Also

  • Zookeeper::create() - Create a node synchronously
  • Zookeeper::delete() - Delete a node in zookeeper synchronously
  • ZookeeperException


Return the client session id, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE)

  • « Zookeeper::getChildren
  • Zookeeper::getConfig »
  • PHP Manual
  • Zookeeper
  • Return the client session id, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE)

Zookeeper::getClientId

(PECL zookeeper >= 0.1.0)

Zookeeper::getClientId — Return the client session id, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE)

Description

public Zookeeper::getClientId ( void ) : int

Return Values

Returns the client session id on success, and false on failure.

Errors/Exceptions

This method emits PHP error/warning when it could not get client session id.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

See Also

  • Zookeeper::__construct() - Create a handle to used communicate with zookeeper
  • Zookeeper::connect() - Create a handle to used communicate with zookeeper
  • Zookeeper::getState() - Get the state of the zookeeper connection
  • ZooKeeper States
  • ZookeeperException


Get instance of ZookeeperConfig

  • « Zookeeper::getClientId
  • Zookeeper::getRecvTimeout »
  • PHP Manual
  • Zookeeper
  • Get instance of ZookeeperConfig

Zookeeper::getConfig

(PECL zookeeper >= 0.6.0, ZooKeeper >= 3.5.0)

Zookeeper::getConfig — Get instance of ZookeeperConfig

Description

public Zookeeper::getConfig ( void ) : ZookeeperConfig

Return Values

Returns instance of ZookeeperConfig.

See Also

  • ZookeeperConfig


Return the timeout for this session, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE). This value may change after a server re-connect

  • « Zookeeper::getConfig
  • Zookeeper::getState »
  • PHP Manual
  • Zookeeper
  • Return the timeout for this session, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE). This value may change after a server re-connect

Zookeeper::getRecvTimeout

(PECL zookeeper >= 0.1.0)

Zookeeper::getRecvTimeout — Return the timeout for this session, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE). This value may change after a server re-connect

Description

public Zookeeper::getRecvTimeout ( void ) : int

Return Values

Returns the timeout for this session on success, and false on failure.

Errors/Exceptions

This method emits PHP error/warning when operation fails.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

See Also

  • Zookeeper::__construct() - Create a handle to used communicate with zookeeper
  • Zookeeper::connect() - Create a handle to used communicate with zookeeper
  • ZookeeperException


Get the state of the zookeeper connection

  • « Zookeeper::getRecvTimeout
  • Zookeeper::isRecoverable »
  • PHP Manual
  • Zookeeper
  • Get the state of the zookeeper connection

Zookeeper::getState

(PECL zookeeper >= 0.1.0)

Zookeeper::getState — Get the state of the zookeeper connection

Description

public Zookeeper::getState ( void ) : int

Return Values

Returns the state of zookeeper connection on success, and false on failure.

Errors/Exceptions

This method emits PHP error/warning when it fails to get state of zookeeper connection.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

See Also

  • Zookeeper::__construct() - Create a handle to used communicate with zookeeper
  • Zookeeper::connect() - Create a handle to used communicate with zookeeper
  • Zookeeper::getClientId() - Return the client session id, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE)
  • ZooKeeper States
  • ZookeeperException


Checks if the current zookeeper connection state can be recovered

  • « Zookeeper::getState
  • Zookeeper::set »
  • PHP Manual
  • Zookeeper
  • Checks if the current zookeeper connection state can be recovered

Zookeeper::isRecoverable

(PECL zookeeper >= 0.1.0)

Zookeeper::isRecoverable — Checks if the current zookeeper connection state can be recovered

Description

public Zookeeper::isRecoverable ( void ) : bool

The application must close the handle and try to reconnect.

Return Values

Returns true/false on success, and false on failure.

Errors/Exceptions

This method emits PHP error/warning when operation fails.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

See Also

  • Zookeeper::__construct() - Create a handle to used communicate with zookeeper
  • Zookeeper::connect() - Create a handle to used communicate with zookeeper
  • Zookeeper::getClientId() - Return the client session id, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE)
  • ZooKeeper States
  • ZookeeperException


Sets the data associated with a node

  • « Zookeeper::isRecoverable
  • Zookeeper::setAcl »
  • PHP Manual
  • Zookeeper
  • Sets the data associated with a node

Zookeeper::set

(PECL zookeeper >= 0.1.0)

Zookeeper::set — Sets the data associated with a node

Description

public Zookeeper::set ( string $path , string $value [, int $version = -1 [, array &$stat = NULL ]] ) : bool

Parameters

path

The name of the node. Expressed as a file name with slashes separating ancestors of the node.

value

The data to be stored in the node.

version

The expected version of the node. The function will fail if the actual version of the node does not match the expected version. If -1 is used the version check will not take place.

stat

If not NULL, will hold the value of stat for the path on return.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

This method emits PHP error/warning when parameters count or types are wrong or fail to save value to node.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

Examples

Example #1 Zookeeper::set() example

Save value to node.

<?php
$zookeeper = new Zookeeper('locahost:2181');
$path = '/path/to/node';
$value = 'nodevalue';
$r = $zookeeper->set($path, $value);
if ($r)
  echo 'SUCCESS';
else
  echo 'ERR';
?>

The above example will output:

SUCCESS

See Also

  • Zookeeper::create() - Create a node synchronously
  • Zookeeper::get() - Gets the data associated with a node synchronously
  • ZookeeperException


Sets the acl associated with a node synchronously

  • « Zookeeper::set
  • Zookeeper::setDebugLevel »
  • PHP Manual
  • Zookeeper
  • Sets the acl associated with a node synchronously

Zookeeper::setAcl

(PECL zookeeper >= 0.1.0)

Zookeeper::setAcl — Sets the acl associated with a node synchronously

Description

public Zookeeper::setAcl ( string $path , int $version , array $acl ) : bool

Parameters

path

The name of the node. Expressed as a file name with slashes separating ancestors of the node.

version

The expected version of the path.

acl

The acl to be set on the path.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

This method emits PHP error/warning when parameters count or types are wrong or fail to set ACL for a node.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

Examples

Example #1 Zookeeper::setAcl() example

Set ACL for a node.

<?php
$zookeeper = new Zookeeper('locahost:2181');
$aclArray = array(
  array(
    'perms'  => Zookeeper::PERM_ALL,
    'scheme' => 'world',
    'id'     => 'anyone',
  )
);
$path = '/path/to/newnode';
$zookeeper->setAcl($path, $aclArray);

$r = $zookeeper->getAcl($path);
if ($r)
  var_dump($r);
else
  echo 'ERR';
?>

The above example will output:

array(1) {
  [0]=>
  array(3) {
    ["perms"]=>
    int(31)
    ["scheme"]=>
    string(5) "world"
    ["id"]=>
    string(6) "anyone"
  }
}

See Also

  • Zookeeper::create() - Create a node synchronously
  • Zookeeper::getAcl() - Gets the acl associated with a node synchronously
  • ZooKeeper Permissions
  • ZookeeperException


Sets the debugging level for the library

  • « Zookeeper::setAcl
  • Zookeeper::setDeterministicConnOrder »
  • PHP Manual
  • Zookeeper
  • Sets the debugging level for the library

Zookeeper::setDebugLevel

(PECL zookeeper >= 0.1.0)

Zookeeper::setDebugLevel — Sets the debugging level for the library

Description

public static Zookeeper::setDebugLevel ( int $logLevel ) : bool

Parameters

logLevel

ZooKeeper log level constants.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

This method emits PHP error/warning when parameters count or types are wrong or fail to set debug level.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

Examples

Example #1 Zookeeper::setDebugLevel() example

Set debugl level.

<?php
$r = Zookeeper::setDebugLevel(Zookeeper::LOG_LEVEL_WARN);
if ($r)
  echo 'SUCCESS';
else
  echo 'ERR';
?>
?>

The above example will output:

SUCCESS

See Also

  • ZooKeeper Log Levels
  • ZookeeperException


Enable/disable quorum endpoint order randomization

  • « Zookeeper::setDebugLevel
  • Zookeeper::setLogStream »
  • PHP Manual
  • Zookeeper
  • Enable/disable quorum endpoint order randomization

Zookeeper::setDeterministicConnOrder

(PECL zookeeper >= 0.1.0)

Zookeeper::setDeterministicConnOrder — Enable/disable quorum endpoint order randomization

Description

public static Zookeeper::setDeterministicConnOrder ( bool $yesOrNo ) : bool

If passed a true value, will make the client connect to quorum peers in the order as specified in the zookeeper_init() call. A false value causes zookeeper_init() to permute the peer endpoints which is good for more even client connection distribution among the quorum peers. ZooKeeper C Client uses false by default.

Parameters

yesOrNo

Disable/enable quorum endpoint order randomization.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

This method emits PHP error/warning when parameters count or types are wrong or operation fails.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

See Also

  • Zookeeper::__construct() - Create a handle to used communicate with zookeeper
  • Zookeeper::connect() - Create a handle to used communicate with zookeeper
  • ZookeeperException


Sets the stream to be used by the library for logging

  • « Zookeeper::setDeterministicConnOrder
  • Zookeeper::setWatcher »
  • PHP Manual
  • Zookeeper
  • Sets the stream to be used by the library for logging

Zookeeper::setLogStream

(PECL zookeeper >= 0.1.0)

Zookeeper::setLogStream — Sets the stream to be used by the library for logging

Description

public Zookeeper::setLogStream ( resource $stream ) : bool

The zookeeper library uses stderr as its default log stream. Application must make sure the stream is writable. Passing in NULL resets the stream to its default value (stderr).

Parameters

stream

The stream to be used by the library for logging.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

This method emits PHP error/warning when parameters count or types are wrong or operation fails.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

See Also

  • Zookeeper::setDebugLevel() - Sets the debugging level for the library
  • ZookeeperException


Set a watcher function

  • « Zookeeper::setLogStream
  • ZookeeperConfig »
  • PHP Manual
  • Zookeeper
  • Set a watcher function

Zookeeper::setWatcher

(PECL zookeeper >= 0.1.0)

Zookeeper::setWatcher — Set a watcher function

Description

public Zookeeper::setWatcher ( callable $watcher_cb ) : bool

Parameters

watcher_cb

A watch will be set at the server to notify the client if the node changes.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

This method emits PHP error/warning when parameters count or types are wrong or fail to set watcher.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

See Also

  • Zookeeper::exists() - Checks the existence of a node in zookeeper synchronously
  • Zookeeper::get() - Gets the data associated with a node synchronously
  • ZookeeperException


The ZookeeperConfig class

(PECL zookeeper >= 0.6.0, ZooKeeper >= 3.5.0)

Introduction

The ZooKeeper Config handling class.

Class synopsis

ZookeeperConfig {
/* Methods */
public add ( string $members [, int $version = -1 [, array &$stat = NULL ]] ) : void
public get ([ callable $watcher_cb = NULL [, array &$stat = NULL ]] ) : string
public remove ( string $id_list [, int $version = -1 [, array &$stat = NULL ]] ) : void
public set ( string $members [, int $version = -1 [, array &$stat = NULL ]] ) : void
}

Table of Contents

  • ZookeeperConfig::add — Add servers to the ensemble
  • ZookeeperConfig::get — Gets the last committed configuration of the ZooKeeper cluster as it is known to the server to which the client is connected, synchronously
  • ZookeeperConfig::remove — Remove servers from the ensemble
  • ZookeeperConfig::set — Change ZK cluster ensemble membership and roles of ensemble peers


Add servers to the ensemble

  • « ZookeeperConfig
  • ZookeeperConfig::get »
  • PHP Manual
  • ZookeeperConfig
  • Add servers to the ensemble

ZookeeperConfig::add

(PECL zookeeper >= 0.6.0, ZooKeeper >= 3.5.0)

ZookeeperConfig::add — Add servers to the ensemble

Description

public ZookeeperConfig::add ( string $members [, int $version = -1 [, array &$stat = NULL ]] ) : void

Parameters

members

Comma separated list of servers to be added to the ensemble. Each has a configuration line for a server to be added (as would appear in a configuration file), only for maj. quorums.

version

The expected version of the node. The function will fail if the actual version of the node does not match the expected version. If -1 is used the version check will not take place.

stat

If not NULL, will hold the value of stat for the path on return.

Errors/Exceptions

This method emits ZookeeperException and it's derivatives when parameters count or types are wrong or fail to save value to node.

Examples

Example #1 ZookeeperConfig::add() example

Add members.

<?php
$client = new Zookeeper();
$client->connect('localhost:2181');
$client->addAuth('digest', 'timandes:timandes');
$zkConfig = $client->getConfig();
$zkConfig->set("server.1=localhost:2888:3888:participant;0.0.0.0:2181");
$zkConfig->add("server.2=localhost:2889:3889:participant;0.0.0.0:2182");
$r = $zkConfig->get();
if ($r)
  echo $r;
else
  echo 'ERR';
?>

The above example will output:

server.1=localhost:2888:3888:participant;0.0.0.0:2181
server.2=localhost:2889:3889:participant;0.0.0.0:2182
version=0xca01e881a2

See Also

  • ZookeeperConfig::get() - Gets the last committed configuration of the ZooKeeper cluster as it is known to the server to which the client is connected, synchronously
  • ZookeeperConfig::set() - Change ZK cluster ensemble membership and roles of ensemble peers
  • ZookeeperConfig::remove() - Remove servers from the ensemble
  • ZookeeperException


Gets the last committed configuration of the ZooKeeper cluster as it is known to the server to which the client is connected, synchronously

  • « ZookeeperConfig::add
  • ZookeeperConfig::remove »
  • PHP Manual
  • ZookeeperConfig
  • Gets the last committed configuration of the ZooKeeper cluster as it is known to the server to which the client is connected, synchronously

ZookeeperConfig::get

(PECL zookeeper >= 0.6.0, ZooKeeper >= 3.5.0)

ZookeeperConfig::get — Gets the last committed configuration of the ZooKeeper cluster as it is known to the server to which the client is connected, synchronously

Description

public ZookeeperConfig::get ([ callable $watcher_cb = NULL [, array &$stat = NULL ]] ) : string

Parameters

watcher_cb

If nonzero, a watch will be set at the server to notify the client if the node changes.

stat

If not NULL, will hold the value of stat for the path on return.

Return Values

Returns the configuration string on success, and false on failure.

Errors/Exceptions

This method emits ZookeeperException and it's derivatives when parameters count or types are wrong or fail to get configuration.

Examples

Example #1 ZookeeperConfig::get() example

Get configuration.

<?php
$zk = new Zookeeper();
$zk->connect('localhost:2181');
$zk->addAuth('digest', 'timandes:timandes');
$zkConfig = $zk->getConfig();
$r = $zkConfig->get();
if ($r)
  echo $r;
else
  echo 'ERR';
?>

The above example will output:

server.1=localhost:2888:3888:participant;0.0.0.0:2181
version=0xca01e881a2

See Also

  • ZookeeperConfig::set() - Change ZK cluster ensemble membership and roles of ensemble peers
  • ZookeeperConfig::add() - Add servers to the ensemble
  • ZookeeperConfig::remove() - Remove servers from the ensemble
  • ZookeeperException


Remove servers from the ensemble

  • « ZookeeperConfig::get
  • ZookeeperConfig::set »
  • PHP Manual
  • ZookeeperConfig
  • Remove servers from the ensemble

ZookeeperConfig::remove

(PECL zookeeper >= 0.6.0, ZooKeeper >= 3.5.0)

ZookeeperConfig::remove — Remove servers from the ensemble

Description

public ZookeeperConfig::remove ( string $id_list [, int $version = -1 [, array &$stat = NULL ]] ) : void

Parameters

id_list

Comma separated list of server IDs to be removed from the ensemble. Each has an id of a server to be removed, only for maj. quorums.

version

The expected version of the node. The function will fail if the actual version of the node does not match the expected version. If -1 is used the version check will not take place.

stat

If not NULL, will hold the value of stat for the path on return.

Errors/Exceptions

This method emits ZookeeperException and it's derivatives when parameters count or types are wrong or fail to save value to node.

Examples

Example #1 ZookeeperConfig::remove() example

Remove members.

<?php
$client = new Zookeeper();
$client->connect('localhost:2181');
$client->addAuth('digest', 'timandes:timandes');
$zkConfig = $client->getConfig();
$zkConfig->set("server.1=localhost:2888:3888:participant;0.0.0.0:2181,server.2=localhost:2889:3889:participant;0.0.0.0:2182");
$zkConfig->remove("2");
echo $zkConfig->get();
if ($r)
  echo $r;
else
  echo 'ERR';
?>

The above example will output:

server.1=localhost:2888:3888:participant;0.0.0.0:2181
version=0xca01e881a2

See Also

  • ZookeeperConfig::get() - Gets the last committed configuration of the ZooKeeper cluster as it is known to the server to which the client is connected, synchronously
  • ZookeeperConfig::add() - Add servers to the ensemble
  • ZookeeperConfig::set() - Change ZK cluster ensemble membership and roles of ensemble peers
  • ZookeeperException


Change ZK cluster ensemble membership and roles of ensemble peers

  • « ZookeeperConfig::remove
  • ZookeeperException »
  • PHP Manual
  • ZookeeperConfig
  • Change ZK cluster ensemble membership and roles of ensemble peers

ZookeeperConfig::set

(PECL zookeeper >= 0.6.0, ZooKeeper >= 3.5.0)

ZookeeperConfig::set — Change ZK cluster ensemble membership and roles of ensemble peers

Description

public ZookeeperConfig::set ( string $members [, int $version = -1 [, array &$stat = NULL ]] ) : void

Parameters

members

Comma separated list of new membership (e.g., contents of a membership configuration file) - for use only with a non-incremental reconfiguration.

version

The expected version of the node. The function will fail if the actual version of the node does not match the expected version. If -1 is used the version check will not take place.

stat

If not NULL, will hold the value of stat for the path on return.

Errors/Exceptions

This method emits ZookeeperException and it's derivatives when parameters count or types are wrong or fail to save value to node.

Examples

Example #1 ZookeeperConfig::set() example

Reconfig.

<?php
$client = new Zookeeper();
$client->connect('localhost:2181');
$client->addAuth('digest', 'timandes:timandes');
$zkConfig = $client->getConfig();
$zkConfig->set("server.1=localhost:2888:3888:participant;0.0.0.0:2181");
?>

See Also

  • ZookeeperConfig::get() - Gets the last committed configuration of the ZooKeeper cluster as it is known to the server to which the client is connected, synchronously
  • ZookeeperConfig::add() - Add servers to the ensemble
  • ZookeeperConfig::remove() - Remove servers from the ensemble
  • ZookeeperException


The ZookeeperException class

(PECL zookeeper >= 0.3.0)

Introduction

The ZooKeeper exception handling class.

Class synopsis

ZookeeperException extends Exception {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The ZookeeperAuthenticationException class

(PECL zookeeper >= 0.3.0)

Introduction

The ZooKeeper authentication exception handling class.

Class synopsis

ZookeeperAuthenticationException extends ZookeeperException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The ZookeeperConnectionException class

(PECL zookeeper >= 0.3.0)

Introduction

The ZooKeeper connection exception handling class.

Class synopsis

ZookeeperConnectionException extends ZookeeperException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The ZookeeperMarshallingException class

(PECL zookeeper >= 0.3.0)

Introduction

The ZooKeeper exception (while marshalling or unmarshalling data) handling class.

Class synopsis

ZookeeperMarshallingException extends ZookeeperException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The ZookeeperNoNodeException class

(PECL zookeeper >= 0.3.0)

Introduction

The ZooKeeper exception (when node does not exist) handling class.

Class synopsis

ZookeeperNoNodeException extends ZookeeperException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The ZookeeperOperationTimeoutException class

(PECL zookeeper >= 0.3.0)

Introduction

The ZooKeeper operation timeout exception handling class.

Class synopsis

ZookeeperOperationTimeoutException extends ZookeeperException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The ZookeeperSessionException class

(PECL zookeeper >= 0.3.0)

Introduction

The ZooKeeper session exception handling class.

Class synopsis

ZookeeperSessionException extends ZookeeperException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


Search Engine Extensions

  • mnoGoSearch
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • mnoGoSearch Functions
  • Solr — Apache Solr
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Solr Functions
    • Examples
    • SolrUtils — The SolrUtils class
    • SolrInputDocument — The SolrInputDocument class
    • SolrDocument — The SolrDocument class
    • SolrDocumentField — The SolrDocumentField class
    • SolrObject — The SolrObject class
    • SolrClient — The SolrClient class
    • SolrResponse — The SolrResponse class
    • SolrQueryResponse — The SolrQueryResponse class
    • SolrUpdateResponse — The SolrUpdateResponse class
    • SolrPingResponse — The SolrPingResponse class
    • SolrGenericResponse — The SolrGenericResponse class
    • SolrParams — The SolrParams class
    • SolrModifiableParams — The SolrModifiableParams class
    • SolrQuery — The SolrQuery class
    • SolrDisMaxQuery — The SolrDisMaxQuery class
    • SolrCollapseFunction — The SolrCollapseFunction class
    • SolrException — The SolrException class
    • SolrClientException — The SolrClientException class
    • SolrServerException — The SolrServerException class
    • SolrIllegalArgumentException — The SolrIllegalArgumentException class
    • SolrIllegalOperationException — The SolrIllegalOperationException class
    • SolrMissingMandatoryParameterException — The SolrMissingMandatoryParameterException class
  • Sphinx — Sphinx Client
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • SphinxClient — The SphinxClient class
  • Swish — Swish Indexing
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Swish Functions


mnoGoSearch

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • mnoGoSearch Functions
    • udm_add_search_limit — Add various search limits
    • udm_alloc_agent_array — Allocate mnoGoSearch session
    • udm_alloc_agent — Allocate mnoGoSearch session
    • udm_api_version — Get mnoGoSearch API version
    • udm_cat_list — Get all the categories on the same level with the current one
    • udm_cat_path — Get the path to the current category
    • udm_check_charset — Check if the given charset is known to mnogosearch
    • udm_clear_search_limits — Clear all mnoGoSearch search restrictions
    • udm_crc32 — Return CRC32 checksum of given string
    • udm_errno — Get mnoGoSearch error number
    • udm_error — Get mnoGoSearch error message
    • udm_find — Perform search
    • udm_free_agent — Free mnoGoSearch session
    • udm_free_ispell_data — Free memory allocated for ispell data
    • udm_free_res — Free mnoGoSearch result
    • udm_get_doc_count — Get total number of documents in database
    • udm_get_res_field — Fetch a result field
    • udm_get_res_param — Get mnoGoSearch result parameters
    • udm_hash32 — Return Hash32 checksum of given string
    • udm_load_ispell_data — Load ispell data
    • udm_set_agent_param — Set mnoGoSearch agent session parameters


Introduction

These functions allow you to access the mnoGoSearch (former UdmSearch) free search engine. mnoGoSearch is a full-featured search engine software for intranet and internet servers, distributed under the GNU license. mnoGoSearch has a number of unique features, which makes it appropriate for a wide range of applications from search within your site to a specialized search system such as cooking recipes or newspaper search, FTP archive search, news articles search, etc. It offers full-text indexing and searching for HTML, PDF, and text documents. mnoGoSearch consists of two parts. The first is an indexing mechanism (indexer). The purpose of the indexer is to walk through HTTP, FTP, NEWS servers or local files, recursively grabbing all the documents and storing meta-data about that documents in an SQL database in a smart and effective manner. After every document is referenced by its corresponding URL, meta-data is collected by the indexer for later use in a search process. The search is performed via Web interface. C, CGI, PHP and Perl search front ends are included.

More information about mnoGoSearch can be found at » http://www.mnogosearch.org/.

Note:

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.1.0.

Note: This extension is not available on Windows platforms.


Requirements

Download mnoGosearch from » http://www.mnogosearch.org/ and install it on your system. You need at least version 3.1.10 of mnoGoSearch installed to use these functions.


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/mnogosearch.

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.1.0

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.

Note:

PHP contains built-in MySQL access library, which can be used to access MySQL. It is known that mnoGoSearch is not compatible with this built-in library and can work only with generic MySQL libraries. Thus, if you use mnoGoSearch with MySQL, during PHP configuration you have to indicate the directory of your MySQL installation, that was used during mnoGoSearch configuration, i.e. for example: --with-mnogosearch --with-mysql=/usr .


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.

UDM_FIELD_URLID (integer)
UDM_FIELD_URL (integer)
UDM_FIELD_CONTENT (integer)
UDM_FIELD_TITLE (integer)
UDM_FIELD_KEYWORDS (integer)
UDM_FIELD_DESC (integer)
UDM_FIELD_DESCRIPTION (integer)
UDM_FIELD_TEXT (integer)
UDM_FIELD_SIZE (integer)
UDM_FIELD_RATING (integer)
UDM_FIELD_SCORE (integer)
UDM_FIELD_MODIFIED (integer)
UDM_FIELD_ORDER (integer)
UDM_FIELD_CRC (integer)
UDM_FIELD_CATEGORY (integer)
UDM_FIELD_LANG (integer)
UDM_FIELD_CHARSET (integer)
UDM_PARAM_PAGE_SIZE (integer)
UDM_PARAM_PAGE_NUM (integer)
UDM_PARAM_SEARCH_MODE (integer)
UDM_PARAM_CACHE_MODE (integer)
UDM_PARAM_TRACK_MODE (integer)
UDM_PARAM_PHRASE_MODE (integer)
UDM_PARAM_CHARSET (integer)
UDM_PARAM_LOCAL_CHARSET (integer)
UDM_PARAM_BROWSER_CHARSET (integer)
UDM_PARAM_STOPTABLE (integer)
UDM_PARAM_STOP_TABLE (integer)
UDM_PARAM_STOPFILE (integer)
UDM_PARAM_STOP_FILE (integer)
UDM_PARAM_WEIGHT_FACTOR (integer)
UDM_PARAM_WORD_MATCH (integer)
UDM_PARAM_MAX_WORD_LEN (integer)
UDM_PARAM_MAX_WORDLEN (integer)
UDM_PARAM_MIN_WORD_LEN (integer)
UDM_PARAM_MIN_WORDLEN (integer)
UDM_PARAM_ISPELL_PREFIXES (integer)
UDM_PARAM_ISPELL_PREFIX (integer)
UDM_PARAM_PREFIXES (integer)
UDM_PARAM_PREFIX (integer)
UDM_PARAM_CROSS_WORDS (integer)
UDM_PARAM_CROSSWORDS (integer)
UDM_PARAM_VARDIR (integer)
UDM_PARAM_DATADIR (integer)
UDM_PARAM_HLBEG (integer)
UDM_PARAM_HLEND (integer)
UDM_PARAM_SYNONYM (integer)
UDM_PARAM_SEARCHD (integer)
UDM_PARAM_QSTRING (integer)
UDM_PARAM_REMOTE_ADDR (integer)
UDM_LIMIT_CAT (integer)
UDM_LIMIT_URL (integer)
UDM_LIMIT_TAG (integer)
UDM_LIMIT_LANG (integer)
UDM_LIMIT_DATE (integer)
UDM_PARAM_FOUND (integer)
UDM_PARAM_NUM_ROWS (integer)
UDM_PARAM_WORDINFO (integer)
UDM_PARAM_WORD_INFO (integer)
UDM_PARAM_SEARCHTIME (integer)
UDM_PARAM_SEARCH_TIME (integer)
UDM_PARAM_FIRST_DOC (integer)
UDM_PARAM_LAST_DOC (integer)
UDM_MODE_ALL (integer)
UDM_MODE_ANY (integer)
UDM_MODE_BOOL (integer)
UDM_MODE_PHRASE (integer)
UDM_CACHE_ENABLED (integer)
UDM_CACHE_DISABLED (integer)
UDM_TRACK_ENABLED (integer)
UDM_TRACK_DISABLED (integer)
UDM_PHRASE_ENABLED (integer)
UDM_PHRASE_DISABLED (integer)
UDM_CROSS_WORDS_ENABLED (integer)
UDM_CROSSWORDS_ENABLED (integer)
UDM_CROSS_WORDS_DISABLED (integer)
UDM_CROSSWORDS_DISABLED (integer)
UDM_PREFIXES_ENABLED (integer)
UDM_PREFIX_ENABLED (integer)
UDM_ISPELL_PREFIXES_ENABLED (integer)
UDM_ISPELL_PREFIX_ENABLED (integer)
UDM_PREFIXES_DISABLED (integer)
UDM_PREFIX_DISABLED (integer)
UDM_ISPELL_PREFIXES_DISABLED (integer)
UDM_ISPELL_PREFIX_DISABLED (integer)
UDM_ISPELL_TYPE_AFFIX (integer)
UDM_ISPELL_TYPE_SPELL (integer)
UDM_ISPELL_TYPE_DB (integer)
UDM_ISPELL_TYPE_SERVER (integer)
UDM_MATCH_WORD (integer)
UDM_MATCH_BEGIN (integer)
UDM_MATCH_SUBSTR (integer)
UDM_MATCH_END (integer)


mnoGoSearch Functions

Table of Contents

  • udm_add_search_limit — Add various search limits
  • udm_alloc_agent_array — Allocate mnoGoSearch session
  • udm_alloc_agent — Allocate mnoGoSearch session
  • udm_api_version — Get mnoGoSearch API version
  • udm_cat_list — Get all the categories on the same level with the current one
  • udm_cat_path — Get the path to the current category
  • udm_check_charset — Check if the given charset is known to mnogosearch
  • udm_clear_search_limits — Clear all mnoGoSearch search restrictions
  • udm_crc32 — Return CRC32 checksum of given string
  • udm_errno — Get mnoGoSearch error number
  • udm_error — Get mnoGoSearch error message
  • udm_find — Perform search
  • udm_free_agent — Free mnoGoSearch session
  • udm_free_ispell_data — Free memory allocated for ispell data
  • udm_free_res — Free mnoGoSearch result
  • udm_get_doc_count — Get total number of documents in database
  • udm_get_res_field — Fetch a result field
  • udm_get_res_param — Get mnoGoSearch result parameters
  • udm_hash32 — Return Hash32 checksum of given string
  • udm_load_ispell_data — Load ispell data
  • udm_set_agent_param — Set mnoGoSearch agent session parameters


Add various search limits

  • « mnoGoSearch Functions
  • udm_alloc_agent_array »
  • PHP Manual
  • mnoGoSearch Functions
  • Add various search limits

udm_add_search_limit

(PHP 4 >= 4.0.5, PHP 5 < 5.1.0, PECL mnogosearch >= 1.0.0)

udm_add_search_limit — Add various search limits

Description

udm_add_search_limit ( resource $agent , int $var , string $val ) : bool

udm_add_search_limit() adds search restrictions.

Parameters

agent

A link to Agent, received after call to udm_alloc_agent().

var

Defines the parameter, indicating limits. Possible var values:

  • UDM_LIMIT_URL - defines document URL limitations to limit the search through subsection of the database. It supports SQL % and _ LIKE wildcards, where % matches any number of characters, even zero characters, and _ matches exactly one character. E.g. http://www.example.___/catalog may stand for http://www.example.com/catalog and http://www.example.net/catalog.
  • UDM_LIMIT_TAG - defines site TAG limitations. In indexer-conf you can assign specific TAGs to various sites and parts of a site. Tags in mnoGoSearch 3.1.x are lines, that may contain metasymbols % and _. Metasymbols allow searching among groups of tags. E.g. there are links with tags ABCD and ABCE, and search restriction is by ABC_ - the search will be made among both of the tags.
  • UDM_LIMIT_LANG - defines document language limitations.
  • UDM_LIMIT_CAT - defines document category limitations. Categories are similar to tag feature, but nested. So you can have one category inside another and so on. You have to use two characters for each level. Use a hex number going from 0-F or a 36 base number going from 0-Z. Therefore a top-level category like 'Auto' would be 01. If it has a subcategory like 'Ford', then it would be 01 (the parent category) and then 'Ford' which we will give 01. Put those together and you get 0101. If 'Auto' had another subcategory named 'VW', then it's id would be 01 because it belongs to the 'Ford' category and then 02 because it's the next category. So it's id would be 0102. If VW had a sub category called 'Engine' then it's id would start at 01 again and it would get the 'VW' id 02 and 'Auto' id of 01, making it 010201. If you want to search for sites under that category then you pass it cat=010201 in the URL.

  • UDM_LIMIT_DATE - defines limitation by date the document was modified.

    Format of parameter value: a string with first character < or >, then with no space - date in unixtime format, for example:

    <?php
    udm_add_search_limit    ($udm, UDM_LIMIT_DATE, "&lt;908012006");
    ?>

    If > character is used, then the search will be restricted to those documents having a modification date greater than entered, if <, then smaller.

val

Defines the value of the current parameter.

Return Values

Returns TRUE on success or FALSE on failure.


Allocate mnoGoSearch session

  • « udm_add_search_limit
  • udm_alloc_agent »
  • PHP Manual
  • mnoGoSearch Functions
  • Allocate mnoGoSearch session

udm_alloc_agent_array

(PHP 4 >= 4.3.3, PHP 5 < 5.1.0, PECL mnogosearch >= 1.0.0)

udm_alloc_agent_array — Allocate mnoGoSearch session

Description

udm_alloc_agent_array ( array $databases ) : resource

udm_alloc_agent_array() will create an agent with multiple database connections.

Parameters

databases

The array databases must contain one database URL per element, analog to the first parameter of udm_alloc_agent().

Return Values

Returns a resource link identifier on success or FALSE on failure.

See Also

  • udm_alloc_agent() - Allocate mnoGoSearch session


Allocate mnoGoSearch session

  • « udm_alloc_agent_array
  • udm_api_version »
  • PHP Manual
  • mnoGoSearch Functions
  • Allocate mnoGoSearch session

udm_alloc_agent

(PHP 4 >= 4.0.5, PHP 5 < 5.1.0, PECL mnogosearch >= 1.0.0)

udm_alloc_agent — Allocate mnoGoSearch session

Description

udm_alloc_agent ( string $dbaddr [, string $dbmode ] ) : resource

Allocate a mnoGoSearch session.

Parameters

dbaddr

dbaddr - URL-style database description, with options (type, host, database name, port, user and password) to connect to SQL database. Do not matter for built-in text files support. Format for dbaddr: DBType:[//[DBUser[:DBPass]@]DBHost[:DBPort]]/DBName/. Currently supported DBType values are: mysql, pgsql, msql, solid, mssql, oracle, and ibase. Actually, it does not matter for native libraries support, but ODBC users should specify one of the supported values. If your database type is not supported, you may use unknown instead.

dbmode

dbmode - You may select the SQL database mode of words storage. Possible values of dbmode are: single, multi, crc, or crc-multi. When single is specified, all words are stored in the same table. If multi is selected, words will be located in different tables depending of their lengths. "multi" mode is usually faster, but requires more tables in the database. If "crc" mode is selected, mnoGoSearch will store 32 bit integer word IDs calculated by CRC32 algorithm instead of words. This mode requires less disk space and it is faster comparing with "single" and "multi" modes. crc-multi uses the same storage structure with the "crc" mode, but also stores words in different tables depending on words lengths like in "multi" mode.

Note:

dbaddr and dbmode must match those used during indexing.

Return Values

Returns a mnogosearch agent identifier on success, FALSE on failure. This function creates a session with database parameters.

Notes

Note:

In fact this function does not open a connection to the database and thus does not check the entered login and password. Establishing a connection to the database and login/password verification is done by udm_find().


Get mnoGoSearch API version

  • « udm_alloc_agent
  • udm_cat_list »
  • PHP Manual
  • mnoGoSearch Functions
  • Get mnoGoSearch API version

udm_api_version

(PHP 4 >= 4.0.5, PHP 5 < 5.1.0, PECL mnogosearch >= 1.0.0)

udm_api_version — Get mnoGoSearch API version

Description

udm_api_version ( void ) : int

Gets the mnoGoSearch API version.

This function allows the user to identify which API functions are available, e.g. udm_get_doc_count() function is only available in mnoGoSearch 3.1.11 or later.

Return Values

udm_api_version() returns the mnoGoSearch API version number. E.g. if mnoGoSearch 3.1.10 API is used, this function will return 30110.

Examples

Example #1 udm_api_version() example

<?php
if (udm_api_version() >= 30111) {
    echo  "Total number of URLs in database: " . udm_get_doc_count($udm) . "<br />\n";
}
?>


Get all the categories on the same level with the current one

  • « udm_api_version
  • udm_cat_path »
  • PHP Manual
  • mnoGoSearch Functions
  • Get all the categories on the same level with the current one

udm_cat_list

(PHP 4 >= 4.0.6, PHP 5 < 5.1.0, PECL mnogosearch >= 1.0.0)

udm_cat_list — Get all the categories on the same level with the current one

Description

udm_cat_list ( resource $agent , string $category ) : array

Gets all the categories on the same level with the current one.

The function can be useful for developing categories tree browser.

Parameters

agent

A link to Agent, received after call to udm_alloc_agent().

category

Return Values

Returns an array listing all categories of the same level as the current category in the categories tree.

The returned array consists of pairs. Elements with even index numbers contain the category paths, odd elements contain the corresponding category names.

$array[0] will contain '020300'
  $array[1] will contain 'Audi'
  $array[2] will contain '020301'
  $array[3] will contain 'BMW'
  $array[4] will contain '020302'
  $array[5] will contain 'Opel'
  ...
 etc.

Examples

Following is an example of displaying links of the current level in format:

Audi
  BMW
  Opel
  ...

Example #1 udm_cat_list()example

<?php
 $cat_list_arr = udm_cat_list($udm_agent, $cat);
 $cat_list = '';
 for ($i=0; $i<count($cat_list_arr); $i+=2) {
    $path = $cat_list_arr[$i];
    $name = $cat_list_arr[$i+1];
    $cat_list .= "<a href=\"$_SERVER[PHP_SELF]?cat=$path\">$name</a><br />";
 }
?>

See Also

  • udm_cat_path() - Get the path to the current category


Get the path to the current category

  • « udm_cat_list
  • udm_check_charset »
  • PHP Manual
  • mnoGoSearch Functions
  • Get the path to the current category

udm_cat_path

(PHP 4 >= 4.0.6, PHP 5 < 5.1.0, PECL mnogosearch >= 1.0.0)

udm_cat_path — Get the path to the current category

Description

udm_cat_path ( resource $agent , string $category ) : array

Returns an array describing the path in the categories tree from the tree root to the current one, specified by category.

Parameters

agent

A link to Agent, received after call to udm_alloc_agent().

category

Return Values

The returned array consists of pairs. Elements with even index numbers contain the category paths, odd elements contain the corresponding category names.

For example, the call $array=udm_cat_path($agent, '02031D'); may return the following array:

 $array[0] will contain ''
 $array[1] will contain 'Root'
 $array[2] will contain '02'
 $array[3] will contain 'Sport'
 $array[4] will contain '0203'
 $array[5] will contain 'Auto'
 $array[4] will contain '02031D'
 $array[5] will contain 'Ferrari'

Examples

Example #1 Specifying path to the current category in the following format: '> Root > Sport > Auto > Ferrari'

<?php
  $cat_path_arr = udm_cat_path($udm_agent, $cat);
  $cat_path = '';
  for ($i=0; $i<count($cat_path_arr); $i+=2) {
    $path = $cat_path_arr[$i];
    $name = $cat_path_arr[$i+1];
    $cat_path .= " > <a href=\"$_SERVER[PHP_SELF]?cat=$path\">$name</a> ";
  }
?>

See Also

  • udm_cat_list() - Get all the categories on the same level with the current one


Check if the given charset is known to mnogosearch

  • « udm_cat_path
  • udm_clear_search_limits »
  • PHP Manual
  • mnoGoSearch Functions
  • Check if the given charset is known to mnogosearch

udm_check_charset

(PHP 4 >= 4.2.0, PHP 5 < 5.1.0, PECL mnogosearch >= 1.0.0)

udm_check_charset — Check if the given charset is known to mnogosearch

Description

udm_check_charset ( resource $agent , string $charset ) : bool

Warning

This function is currently not documented; only its argument list is available.


Clear all mnoGoSearch search restrictions

  • « udm_check_charset
  • udm_crc32 »
  • PHP Manual
  • mnoGoSearch Functions
  • Clear all mnoGoSearch search restrictions

udm_clear_search_limits

(PHP 4 >= 4.0.5, PHP 5 < 5.1.0, PECL mnogosearch >= 1.0.0)

udm_clear_search_limits — Clear all mnoGoSearch search restrictions

Description

udm_clear_search_limits ( resource $agent ) : bool

udm_clear_search_limits() resets defined search limitations.

Parameters

agent

A link to Agent, received after call to udm_alloc_agent().

Return Values

Returns TRUE.

See Also

  • udm_add_search_limit() - Add various search limits


Return CRC32 checksum of given string

  • « udm_clear_search_limits
  • udm_errno »
  • PHP Manual
  • mnoGoSearch Functions
  • Return CRC32 checksum of given string

udm_crc32

(PHP 4 >= 4.2.0, PHP 5 < 5.1.0, PECL mnogosearch >= 1.0.0)

udm_crc32 — Return CRC32 checksum of given string

Description

udm_crc32 ( resource $agent , string $str ) : int

Warning

This function is currently not documented; only its argument list is available.


Get mnoGoSearch error number

  • « udm_crc32
  • udm_error »
  • PHP Manual
  • mnoGoSearch Functions
  • Get mnoGoSearch error number

udm_errno

(PHP 4 >= 4.0.5, PHP 5 < 5.1.0, PECL mnogosearch >= 1.0.0)

udm_errno — Get mnoGoSearch error number

Description

udm_errno ( resource $agent ) : int

Receiving numeric agent error code.

Parameters

agent

A link to Agent, received after call to udm_alloc_agent().

Return Values

Returns the mnoGoSearch error number, zero if no error.


Get mnoGoSearch error message

  • « udm_errno
  • udm_find »
  • PHP Manual
  • mnoGoSearch Functions
  • Get mnoGoSearch error message

udm_error

(PHP 4 >= 4.0.5, PHP 5 < 5.1.0, PECL mnogosearch >= 1.0.0)

udm_error — Get mnoGoSearch error message

Description

udm_error ( resource $agent ) : string

Gets the agent error message.

Parameters

agent

A link to Agent, received after call to udm_alloc_agent().

Return Values

udm_error() returns mnoGoSearch error message, empty string if no error.


Perform search

  • « udm_error
  • udm_free_agent »
  • PHP Manual
  • mnoGoSearch Functions
  • Perform search

udm_find

(PHP 4 >= 4.0.5, PHP 5 < 5.1.0, PECL mnogosearch >= 1.0.0)

udm_find — Perform search

Description

udm_find ( resource $agent , string $query ) : resource

Performs a search.

The search itself. The first argument - session, the next one - query itself. To find something just type words you want to find and press SUBMIT button. For example, "mysql odbc". You should not use quotes " in query, they are written here only to divide a query from other text. mnoGoSearch will find all documents that contain word "mysql" and/or word "odbc". Best documents having bigger weights will be displayed first. If you use search mode ALL, search will return documents that contain both (or more) words you entered. In case you use mode ANY, the search will return list of documents that contain any of the words you entered. If you want more advanced results you may use query language. You should select "bool" match mode in the search from.

Parameters

agent

A link to Agent, received after call to udm_alloc_agent().

query

mnoGoSearch understands the following boolean operators:

& - logical AND. For example, "mysql & odbc". mnoGoSearch will find any URLs that contain both "mysql" and "odbc".

| - logical OR. For example "mysql|odbc". mnoGoSearch will find any URLs, that contain word "mysql" or word "odbc".

~ - logical NOT. For example "mysql & ~odbc". mnoGoSearch will find URLs that contain word "mysql" and do not contain word "odbc" at the same time. Note that ~ just excludes given word from results. Query "~odbc" will find nothing!

() - group command to compose more complex queries. For example "(mysql | msql) & ~postgres". Query language is simple and powerful at the same time. Just consider query as usual boolean expression.

Return Values

Returns a result link identifier on success or FALSE on failure.


Free mnoGoSearch session

  • « udm_find
  • udm_free_ispell_data »
  • PHP Manual
  • mnoGoSearch Functions
  • Free mnoGoSearch session

udm_free_agent

(PHP 4 >= 4.0.5, PHP 5 < 5.1.0, PECL mnogosearch >= 1.0.0)

udm_free_agent — Free mnoGoSearch session

Description

udm_free_agent ( resource $agent ) : int

Freeing up memory allocated for agent session.

Parameters

agent

A link to Agent, received after call to udm_alloc_agent().

Return Values

Returns TRUE on success or FALSE on failure.


Free memory allocated for ispell data

  • « udm_free_agent
  • udm_free_res »
  • PHP Manual
  • mnoGoSearch Functions
  • Free memory allocated for ispell data

udm_free_ispell_data

(PHP 4 >= 4.0.5, PHP 5 < 5.1.0, PECL mnogosearch >= 1.0.0)

udm_free_ispell_data — Free memory allocated for ispell data

Description

udm_free_ispell_data ( int $agent ) : bool

Frees the memory allocated for ispell data.

Parameters

agent

A link to Agent, received after call to udm_alloc_agent().

Return Values

udm_free_ispell_data() always returns TRUE.

Notes

Note:

This function is supported beginning from version 3.1.12 of mnoGoSearch and it does not do anything in previous versions.


Free mnoGoSearch result

  • « udm_free_ispell_data
  • udm_get_doc_count »
  • PHP Manual
  • mnoGoSearch Functions
  • Free mnoGoSearch result

udm_free_res

(PHP 4 >= 4.0.5, PHP 5 < 5.1.0, PECL mnogosearch >= 1.0.0)

udm_free_res — Free mnoGoSearch result

Description

udm_free_res ( resource $res ) : bool

Freeing up memory allocated for results.

Parameters

res

A link to a result identifier, received after call to udm_find().

Return Values

Returns TRUE on success or FALSE on failure.


Get total number of documents in database

  • « udm_free_res
  • udm_get_res_field »
  • PHP Manual
  • mnoGoSearch Functions
  • Get total number of documents in database

udm_get_doc_count

(PHP 4 >= 4.0.5, PHP 5 < 5.1.0, PECL mnogosearch >= 1.0.0)

udm_get_doc_count — Get total number of documents in database

Description

udm_get_doc_count ( resource $agent ) : int

udm_get_doc_count() returns the number of documents in the database.

Parameters

agent

A link to Agent, received after call to udm_alloc_agent().

Return Values

Returns the number of documents.

Notes

Note:

This function is supported only in mnoGoSearch 3.1.11 or later.


Fetch a result field

  • « udm_get_doc_count
  • udm_get_res_param »
  • PHP Manual
  • mnoGoSearch Functions
  • Fetch a result field

udm_get_res_field

(PHP 4 >= 4.0.5, PHP 5 < 5.1.0, PECL mnogosearch >= 1.0.0)

udm_get_res_field — Fetch a result field

Description

udm_get_res_field ( resource $res , int $row , int $field ) : string

Fetch a mnoGoSearch result field.

Parameters

res

res - a link to result identifier, received after call to udm_find().

row

row - the number of the link on the current page. May have values from 0 to UDM_PARAM_NUM_ROWS-1.

field

field - field identifier, may have the following values:

  • UDM_FIELD_URL - document URL field
  • UDM_FIELD_CONTENT - document Content-type field (for example, text/html).
  • UDM_FIELD_CATEGORY - document category field. Use udm_cat_path() to get full path to current category from the categories tree root. (This parameter is available only in PHP 4.0.6 or later).
  • UDM_FIELD_TITLE - document title field.
  • UDM_FIELD_KEYWORDS - document keywords field (from META KEYWORDS tag).
  • UDM_FIELD_DESC - document description field (from META DESCRIPTION tag).
  • UDM_FIELD_TEXT - document body text (the first couple of lines to give an idea of what the document is about).
  • UDM_FIELD_SIZE - document size.
  • UDM_FIELD_URLID - unique URL ID of the link.
  • UDM_FIELD_RATING - page rating (as calculated by mnoGoSearch).
  • UDM_FIELD_MODIFIED - last-modified field in unixtime format.
  • UDM_FIELD_ORDER - the number of the current document in set of found documents.
  • UDM_FIELD_CRC - document CRC.

Return Values

udm_get_res_field() returns result field value on success, FALSE on error.


Get mnoGoSearch result parameters

  • « udm_get_res_field
  • udm_hash32 »
  • PHP Manual
  • mnoGoSearch Functions
  • Get mnoGoSearch result parameters

udm_get_res_param

(PHP 4 >= 4.0.5, PHP 5 < 5.1.0, PECL mnogosearch >= 1.0.0)

udm_get_res_param — Get mnoGoSearch result parameters

Description

udm_get_res_param ( resource $res , int $param ) : string

Gets the mnoGoSearch result parameters.

Parameters

res

res - a link to result identifier, received after call to udm_find().

param

param - parameter identifier, may have the following values:

  • UDM_PARAM_NUM_ROWS - number of received found links on the current page. It is equal to UDM_PARAM_PAGE_SIZE for all search pages, on the last page - the rest of links.
  • UDM_PARAM_FOUND - total number of results matching the query.
  • UDM_PARAM_WORDINFO - information on the words found. E.g. search for "a good book" will return "a: stopword, good:5637, book: 120"
  • UDM_PARAM_SEARCHTIME - search time in seconds.
  • UDM_PARAM_FIRST_DOC - the number of the first document displayed on current page.
  • UDM_PARAM_LAST_DOC - the number of the last document displayed on current page.

Return Values

udm_get_res_param() returns result parameter value on success, FALSE on error.


Return Hash32 checksum of given string

  • « udm_get_res_param
  • udm_load_ispell_data »
  • PHP Manual
  • mnoGoSearch Functions
  • Return Hash32 checksum of given string

udm_hash32

(PHP 4 >= 4.3.3, PHP 5 < 5.1.0, PECL mnogosearch >= 1.0.0)

udm_hash32 — Return Hash32 checksum of given string

Description

udm_hash32 ( resource $agent , string $str ) : int

udm_hash32() will take a string str and return a quite unique 32-bit hash number from it.

Parameters

agent

A link to Agent, received after call to udm_alloc_agent().

str

The input string.

Return Values

Returns a 32-bit hash number.

See Also

  • udm_alloc_agent() - Allocate mnoGoSearch session


Load ispell data

  • « udm_hash32
  • udm_set_agent_param »
  • PHP Manual
  • mnoGoSearch Functions
  • Load ispell data

udm_load_ispell_data

(PHP 4 >= 4.0.5, PHP 5 < 5.1.0, PECL mnogosearch >= 1.0.0)

udm_load_ispell_data — Load ispell data

Description

udm_load_ispell_data ( resource $agent , int $var , string $val1 , string $val2 , int $flag ) : bool

udm_load_ispell_data() loads ispell data.

After using this function to free memory allocated for ispell data, please use udm_free_ispell_data(), even if you use UDM_ISPELL_TYPE_SERVER mode.

Parameters

agent

A link to Agent, received after call to udm_alloc_agent().

var

Indicates the source for ispell data. May have the following values:

  • UDM_ISPELL_TYPE_DB - indicates that ispell data should be loaded from SQL. In this case, parameters val1 and val2 are ignored and should be left blank. flag should be equal to 1.

    Note:

    flag indicates that after loading ispell data from defined source it should be sorted (it is necessary for correct functioning of ispell). In case of loading ispell data from files there may be several calls to udm_load_ispell_data(), and there is no sense to sort data after every call, but only after the last one. Since in db mode all the data is loaded by one call, this parameter should have the value 1. In this mode in case of error, e.g. if ispell tables are absent, the function will return FALSE and code and error message will be accessible through udm_error() and udm_errno().

  • UDM_ISPELL_TYPE_AFFIX - indicates that ispell data should be loaded from file and initiates loading affixes file. In this case val1 defines double letter language code for which affixes are loaded, and val2 - file path. Please note, that if a relative path entered, the module looks for the file not in UDM_CONF_DIR, but in relation to current path, i.e. to the path where the script is executed. In case of error in this mode, e.g. if file is absent, the function will return FALSE, and an error message will be displayed. Error message text cannot be accessed through udm_error() and udm_errno(), since those functions can only return messages associated with SQL. Please, see flag parameter description in UDM_ISPELL_TYPE_DB.

    Example #1 udm_load_ispell_data() example

    <?php
    if ((! udm_load_ispell_data($udm, UDM_ISPELL_TYPE_AFFIX, 'en', '/opt/ispell/en.aff', 0)) ||
        (!     udm_load_ispell_data($udm, UDM_ISPELL_TYPE_AFFIX, 'ru', '/opt/ispell/ru.aff', 0)) ||
        (!     udm_load_ispell_data($udm, UDM_ISPELL_TYPE_SPELL, 'en', '/opt/ispell/en.dict', 0)) ||
        (!     udm_load_ispell_data($udm, UDM_ISPELL_TYPE_SPELL, 'ru', '/opt/ispell/ru.dict', 1))) {
        exit;
    }
    ?>

    Note:

    flag is equal to 1 only in the last call.

  • UDM_ISPELL_TYPE_SPELL - indicates that ispell data should be loaded from file and initiates loading of ispell dictionary file. In this case val1 defines double letter language code for which affixes are loaded, and val2 - file path. Please note, that if a relative path entered, the module looks for the file not in UDM_CONF_DIR, but in relation to current path, i.e. to the path where the script is executed. In case of error in this mode, e.g. if file is absent, the function will return FALSE, and an error message will be displayed. Error message text cannot be accessed through udm_error() and udm_errno(), since those functions can only return messages associated with SQL. Please, see flag parameter description in UDM_ISPELL_TYPE_DB.

    <?php
    if ((! udm_load_ispell_data($udm, UDM_ISPELL_TYPE_AFFIX, 'en', '/opt/ispell/en.aff', 0)) ||
       (!     udm_load_ispell_data($udm, UDM_ISPELL_TYPE_AFFIX, 'ru', '/opt/ispell/ru.aff', 0)) ||
       (!     udm_load_ispell_data($udm, UDM_ISPELL_TYPE_SPELL, 'en', '/opt/ispell/en.dict', 0)) ||
       (!     udm_load_ispell_data($udm, UDM_ISPELL_TYPE_SPELL, 'ru', '/opt/ispell/ru.dict', 1))) {
     exit;
     }
    ?>

    Note:

    flag is equal to 1 only in the last call.

  • UDM_ISPELL_TYPE_SERVER - enables spell server support. val1 parameter indicates address of the host running spell server. val2 ` is not used yet, but in future releases it is going to indicate number of port used by spell server. flag parameter in this case is not needed since ispell data is stored on spellserver already sorted.

    Spelld server reads spell-data from a separate configuration file (/usr/local/mnogosearch/etc/spelld.conf by default), sorts it and stores in memory. With clients server communicates in two ways: to indexer all the data is transferred (so that indexer starts faster), from search.cgi server receives word to normalize and then passes over to client (search.cgi) list of normalized word forms. This allows fastest, compared to db and text modes processing of search queries (by omitting loading and sorting all the spell data).

    udm_load_ispell_data() function in UDM_ISPELL_TYPE_SERVER mode does not actually load ispell data, but only defines server address. In fact, server is automatically used by udm_find() function when performing search. In case of errors, e.g. if spellserver is not running or invalid host indicated, there are no messages returned and ispell conversion does not work.

    Note:

    This function is available in mnoGoSearch 3.1.12 or later.

    Example:
    <?php
    if (!udm_load_ispell_data($udm, UDM_ISPELL_TYPE_SERVER, '', '', 1)) {
        echo     "Error loading ispell data from server<br />\n";
        exit;
    }
    ?>

The fastest mode is UDM_ISPELL_TYPE_SERVER. UDM_ISPELL_TYPE_TEXT is slower and UDM_ISPELL_TYPE_DB is the slowest. The above pattern is TRUE for mnoGoSearch 3.1.10 - 3.1.11. It is planned to speed up DB mode in future versions and it is going to be faster than TEXT mode.

val1

val2

flag

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #2 udm_load_ispell_data() example

<?php
if (! udm_load_ispell_data($udm, UDM_ISPELL_TYPE_DB, '', '', 1)) {
  printf("Error #%d: '%s'\n", udm_errno($udm), udm_error($udm));
  exit;
}
?>


Set mnoGoSearch agent session parameters

  • « udm_load_ispell_data
  • Solr »
  • PHP Manual
  • mnoGoSearch Functions
  • Set mnoGoSearch agent session parameters

udm_set_agent_param

(PHP 4 >= 4.0.5, PHP 5 < 5.1.0, PECL mnogosearch >= 1.0.0)

udm_set_agent_param — Set mnoGoSearch agent session parameters

Description

udm_set_agent_param ( resource $agent , int $var , string $val ) : bool

Defines mnoGoSearch session parameters.

Parameters

agent

A link to Agent, received after call to udm_alloc_agent().

var

The following parameters and their values are available:

  • UDM_PARAM_PAGE_NUM - used to choose search results page number (results are returned by pages beginning from 0, with UDM_PARAM_PAGE_SIZE results per page).
  • UDM_PARAM_PAGE_SIZE - number of search results displayed on one page.
  • UDM_PARAM_SEARCH_MODE - search mode. The following values available: UDM_MODE_ALL - search for all words; UDM_MODE_ANY - search for any word; UDM_MODE_PHRASE - phrase search; UDM_MODE_BOOL - boolean search. See udm_find() for details on boolean search.
  • UDM_PARAM_CACHE_MODE - turns on or off search result cache mode. When enabled, the search engine will store search results to disk. In case a similar search is performed later, the engine will take results from the cache for faster performance. Available values: UDM_CACHE_ENABLED, UDM_CACHE_DISABLED.
  • UDM_PARAM_TRACK_MODE - turns on or off trackquery mode. Since version 3.1.2 mnoGoSearch has a query tracking support. Note that tracking is implemented in SQL version only and not available in built-in database. To use tracking, you have to create tables for tracking support. For MySQL, use create/mysql/track.txt. When doing a search, front-end uses those tables to store query words, a number of found documents and current Unix timestamp in seconds. Available values: UDM_TRACK_ENABLED, UDM_TRACK_DISABLED.
  • UDM_PARAM_PHRASE_MODE - defines whether index database using phrases ("phrase" parameter in indexer.conf). Possible values: UDM_PHRASE_ENABLED and UDM_PHRASE_DISABLED. Please note, that if phrase search is enabled (UDM_PHRASE_ENABLED), it is still possible to do search in any mode (ANY, ALL, BOOL or PHRASE). In 3.1.10 version of mnoGoSearch phrase search is supported only in sql and built-in database modes, while beginning with 3.1.11 phrases are supported in cachemode as well. Examples of phrase search: "Arizona desert" - This query returns all indexed documents that contain "Arizona desert" as a phrase. Notice that you need to put double quotes around the phrase
  • UDM_PARAM_CHARSET - defines local charset. Available values: set of charsets supported by mnoGoSearch, e.g. koi8-r, cp1251, ...
  • UDM_PARAM_STOPFILE - Defines name and path to stopwords file. (There is a small difference with mnoGoSearch - while in mnoGoSearch if relative path or no path entered, it looks for this file in relation to UDM_CONF_DIR, the module looks for the file in relation to current path, i.e. to the path where the PHP script is executed.)
  • UDM_PARAM_STOPTABLE - Load stop words from the given SQL table. You may use several StopwordTable commands. This command has no effect when compiled without SQL database support.
  • UDM_PARAM_WEIGHT_FACTOR - represents weight factors for specific document parts. Currently body, title, keywords, description, url are supported. To activate this feature please use degrees of 2 in *Weight commands of the indexer.conf. Let's imagine that we have these weights:
          URLWeight     1
      BodyWeight    2
      TitleWeight   4
      KeywordWeight 8
      DescWeight    16
    As far as indexer uses bit OR operation for word weights when some word presents several time in the same document, it is possible at search time to detect word appearance in different document parts. Word which appears only in the body will have 00000010 aggregate weight (in binary notation). Word used in all document parts will have 00011111 aggregate weight. This parameter's value is a string of hex digits ABCDE. Each digit is a factor for corresponding bit in word weight. For the given above weights configuration:
           E is a factor for weight 1  (URL Weight bit)
       D is a factor for weight 2  (BodyWeight bit)
       C is a factor for weight 4  (TitleWeight bit)
       B is a factor for weight 8  (KeywordWeight bit)
       A is a factor for weight 16 (DescWeight bit)
    Examples: UDM_PARAM_WEIGHT_FACTOR=00001 will search through URLs only. UDM_PARAM_WEIGHT_FACTOR=00100 will search through Titles only. UDM_PARAM_WEIGHT_FACTOR=11100 will search through Title,Keywords,Description but not through URL and Body. UDM_PARAM_WEIGHT_FACTOR=F9421 will search through:
            Description with factor 15  (F hex)
        Keywords with factor 9
        Title with factor  4
        Body with factor 2
        URL with factor 1
    If UDM_PARAM_WEIGHT_FACTOR variable is omitted, original weight value is taken to sort results. For a given above weight configuration it means that document description has a most big weight 16.
  • UDM_PARAM_WORD_MATCH - word match. You may use this parameter to choose word match type. This feature works only in "single" and "multi" modes using SQL based and built-in database. It does not work in cachemode and other modes since they use word CRC and do not support substring search. Available values: UDM_MATCH_BEGIN - word beginning match; UDM_MATCH_END - word ending match; UDM_MATCH_WORD - whole word match; UDM_MATCH_SUBSTR - word substring match.
  • UDM_PARAM_MIN_WORD_LEN - defines minimal word length. Any word shorter this limit is considered to be a stopword. Please note that this parameter value is inclusive, i.e. if UDM_PARAM_MIN_WORD_LEN=3, a word 3 characters long will not be considered a stopword, while a word 2 characters long will be. Default value is 1.
  • UDM_PARAM_ISPELL_PREFIXES - Possible values: UDM_PREFIXES_ENABLED and UDM_PREFIXES_DISABLED, that respectively enable or disable using prefixes. E.g. if a word "tested" is in search query, also words like "test", "testing", etc. Only suffixes are supported by default. Prefixes usually change word meanings, for example if somebody is searching for the word "tested" one hardly wants "untested" to be found. Prefixes support may also be found useful for site's spelling checking purposes. In order to enable ispell, you have to load ispell data with udm_load_ispell_data().
  • UDM_PARAM_CROSS_WORDS - enables or disables crosswords support. Possible values: UDM_CROSS_WORDS_ENABLED and UDM_CROSS_WORDS_DISABLED. The crosswords feature allows to assign words between <a href="xxx"> and </a> also to a document this link leads to. It works in SQL database mode and is not supported in built-in database and Cachemode.
  • UDM_PARAM_VARDIR - specifies a custom path to directory where indexer stores data when using built-in database and in cache mode. By default /var directory of mnoGoSearch installation is used. Can have only string values.

val

Changelog

Version | Description
4.1.0 | UDM_PARAM_VARDIR was added.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: Crosswords are supported only in mnoGoSearch 3.1.11 or later.


Apache Solr

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Solr Functions
    • solr_get_version — Returns the current version of the Apache Solr extension
  • Examples
  • SolrUtils — The SolrUtils class
    • SolrUtils::digestXmlResponse — Parses an response XML string into a SolrObject
    • SolrUtils::escapeQueryChars — Escapes a lucene query string
    • SolrUtils::getSolrVersion — Returns the current version of the Solr extension
    • SolrUtils::queryPhrase — Prepares a phrase from an unescaped lucene string
  • SolrInputDocument — The SolrInputDocument class
    • SolrInputDocument::addChildDocument — Adds a child document for block indexing
    • SolrInputDocument::addChildDocuments — Adds an array of child documents
    • SolrInputDocument::addField — Adds a field to the document
    • SolrInputDocument::clear — Resets the input document
    • SolrInputDocument::__clone — Creates a copy of a SolrDocument
    • SolrInputDocument::__construct — Constructor
    • SolrInputDocument::deleteField — Removes a field from the document
    • SolrInputDocument::__destruct — Destructor
    • SolrInputDocument::fieldExists — Checks if a field exists
    • SolrInputDocument::getBoost — Retrieves the current boost value for the document
    • SolrInputDocument::getChildDocuments — Returns an array of child documents (SolrInputDocument)
    • SolrInputDocument::getChildDocumentsCount — Returns the number of child documents
    • SolrInputDocument::getField — Retrieves a field by name
    • SolrInputDocument::getFieldBoost — Retrieves the boost value for a particular field
    • SolrInputDocument::getFieldCount — Returns the number of fields in the document
    • SolrInputDocument::getFieldNames — Returns an array containing all the fields in the document
    • SolrInputDocument::hasChildDocuments — Returns true if the document has any child documents
    • SolrInputDocument::merge — Merges one input document into another
    • SolrInputDocument::reset — This is an alias of SolrInputDocument::clear
    • SolrInputDocument::setBoost — Sets the boost value for this document
    • SolrInputDocument::setFieldBoost — Sets the index-time boost value for a field
    • SolrInputDocument::sort — Sorts the fields within the document
    • SolrInputDocument::toArray — Returns an array representation of the input document
  • SolrDocument — The SolrDocument class
    • SolrDocument::addField — Adds a field to the document
    • SolrDocument::clear — Drops all the fields in the document
    • SolrDocument::__clone — Creates a copy of a SolrDocument object
    • SolrDocument::__construct — Constructor
    • SolrDocument::current — Retrieves the current field
    • SolrDocument::deleteField — Removes a field from the document
    • SolrDocument::__destruct — Destructor
    • SolrDocument::fieldExists — Checks if a field exists in the document
    • SolrDocument::__get — Access the field as a property
    • SolrDocument::getChildDocuments — Returns an array of child documents (SolrDocument)
    • SolrDocument::getChildDocumentsCount — Returns the number of child documents
    • SolrDocument::getField — Retrieves a field by name
    • SolrDocument::getFieldCount — Returns the number of fields in this document
    • SolrDocument::getFieldNames — Returns an array of fields names in the document
    • SolrDocument::getInputDocument — Returns a SolrInputDocument equivalent of the object
    • SolrDocument::hasChildDocuments — Checks whether the document has any child documents
    • SolrDocument::__isset — Checks if a field exists
    • SolrDocument::key — Retrieves the current key
    • SolrDocument::merge — Merges source to the current SolrDocument
    • SolrDocument::next — Moves the internal pointer to the next field
    • SolrDocument::offsetExists — Checks if a particular field exists
    • SolrDocument::offsetGet — Retrieves a field
    • SolrDocument::offsetSet — Adds a field to the document
    • SolrDocument::offsetUnset — Removes a field
    • SolrDocument::reset — This is an alias to SolrDocument::clear()
    • SolrDocument::rewind — Resets the internal pointer to the beginning
    • SolrDocument::serialize — Used for custom serialization
    • SolrDocument::__set — Adds another field to the document
    • SolrDocument::sort — Sorts the fields in the document
    • SolrDocument::toArray — Returns an array representation of the document
    • SolrDocument::unserialize — Custom serialization of SolrDocument objects
    • SolrDocument::__unset — Removes a field from the document
    • SolrDocument::valid — Checks if the current position internally is still valid
  • SolrDocumentField — The SolrDocumentField class
    • SolrDocumentField::__construct — Constructor
    • SolrDocumentField::__destruct — Destructor
  • SolrObject — The SolrObject class
    • SolrObject::__construct — Creates Solr object
    • SolrObject::__destruct — Destructor
    • SolrObject::getPropertyNames — Returns an array of all the names of the properties
    • SolrObject::offsetExists — Checks if the property exists
    • SolrObject::offsetGet — Used to retrieve a property
    • SolrObject::offsetSet — Sets the value for a property
    • SolrObject::offsetUnset — Unsets the value for the property
  • SolrClient — The SolrClient class
    • SolrClient::addDocument — Adds a document to the index
    • SolrClient::addDocuments — Adds a collection of SolrInputDocument instances to the index
    • SolrClient::commit — Finalizes all add/deletes made to the index
    • SolrClient::__construct — Constructor for the SolrClient object
    • SolrClient::deleteById — Delete by Id
    • SolrClient::deleteByIds — Deletes by Ids
    • SolrClient::deleteByQueries — Removes all documents matching any of the queries
    • SolrClient::deleteByQuery — Deletes all documents matching the given query
    • SolrClient::__destruct — Destructor for SolrClient
    • SolrClient::getById — Get Document By Id. Utilizes Solr Realtime Get (RTG)
    • SolrClient::getByIds — Get Documents by their Ids. Utilizes Solr Realtime Get (RTG)
    • SolrClient::getDebug — Returns the debug data for the last connection attempt
    • SolrClient::getOptions — Returns the client options set internally
    • SolrClient::optimize — Defragments the index
    • SolrClient::ping — Checks if Solr server is still up
    • SolrClient::query — Sends a query to the server
    • SolrClient::request — Sends a raw update request
    • SolrClient::rollback — Rollbacks all add/deletes made to the index since the last commit
    • SolrClient::setResponseWriter — Sets the response writer used to prepare the response from Solr
    • SolrClient::setServlet — Changes the specified servlet type to a new value
    • SolrClient::system — Retrieve Solr Server information
    • SolrClient::threads — Checks the threads status
  • SolrResponse — The SolrResponse class
    • SolrResponse::getDigestedResponse — Returns the XML response as serialized PHP data
    • SolrResponse::getHttpStatus — Returns the HTTP status of the response
    • SolrResponse::getHttpStatusMessage — Returns more details on the HTTP status
    • SolrResponse::getRawRequest — Returns the raw request sent to the Solr server
    • SolrResponse::getRawRequestHeaders — Returns the raw request headers sent to the Solr server
    • SolrResponse::getRawResponse — Returns the raw response from the server
    • SolrResponse::getRawResponseHeaders — Returns the raw response headers from the server
    • SolrResponse::getRequestUrl — Returns the full URL the request was sent to
    • SolrResponse::getResponse — Returns a SolrObject representing the XML response from the server
    • SolrResponse::setParseMode — Sets the parse mode
    • SolrResponse::success — Was the request a success
  • SolrQueryResponse — The SolrQueryResponse class
    • SolrQueryResponse::__construct — Constructor
    • SolrQueryResponse::__destruct — Destructor
  • SolrUpdateResponse — The SolrUpdateResponse class
    • SolrUpdateResponse::__construct — Constructor
    • SolrUpdateResponse::__destruct — Destructor
  • SolrPingResponse — The SolrPingResponse class
    • SolrPingResponse::__construct — Constructor
    • SolrPingResponse::__destruct — Destructor
    • SolrPingResponse::getResponse — Returns the response from the server
  • SolrGenericResponse — The SolrGenericResponse class
    • SolrGenericResponse::__construct — Constructor
    • SolrGenericResponse::__destruct — Destructor
  • SolrParams — The SolrParams class
    • SolrParams::add — This is an alias for SolrParams::addParam
    • SolrParams::addParam — Adds a parameter to the object
    • SolrParams::get — This is an alias for SolrParams::getParam
    • SolrParams::getParam — Returns a parameter value
    • SolrParams::getParams — Returns an array of non URL-encoded parameters
    • SolrParams::getPreparedParams — Returns an array of URL-encoded parameters
    • SolrParams::serialize — Used for custom serialization
    • SolrParams::set — An alias of SolrParams::setParam
    • SolrParams::setParam — Sets the parameter to the specified value
    • SolrParams::toString — Returns all the name-value pair parameters in the object
    • SolrParams::unserialize — Used for custom serialization
  • SolrModifiableParams — The SolrModifiableParams class
    • SolrModifiableParams::__construct — Constructor
    • SolrModifiableParams::__destruct — Destructor
  • SolrQuery — The SolrQuery class
    • SolrQuery::addExpandFilterQuery — Overrides main filter query, determines which documents to include in the main group
    • SolrQuery::addExpandSortField — Orders the documents within the expanded groups (expand.sort parameter)
    • SolrQuery::addFacetDateField — Maps to facet.date
    • SolrQuery::addFacetDateOther — Adds another facet.date.other parameter
    • SolrQuery::addFacetField — Adds another field to the facet
    • SolrQuery::addFacetQuery — Adds a facet query
    • SolrQuery::addField — Specifies which fields to return in the result
    • SolrQuery::addFilterQuery — Specifies a filter query
    • SolrQuery::addGroupField — Add a field to be used to group results
    • SolrQuery::addGroupFunction — Allows grouping results based on the unique values of a function query (group.func parameter)
    • SolrQuery::addGroupQuery — Allows grouping of documents that match the given query
    • SolrQuery::addGroupSortField — Add a group sort field (group.sort parameter)
    • SolrQuery::addHighlightField — Maps to hl.fl
    • SolrQuery::addMltField — Sets a field to use for similarity
    • SolrQuery::addMltQueryField — Maps to mlt.qf
    • SolrQuery::addSortField — Used to control how the results should be sorted
    • SolrQuery::addStatsFacet — Requests a return of sub results for values within the given facet
    • SolrQuery::addStatsField — Maps to stats.field parameter
    • SolrQuery::collapse — Collapses the result set to a single document per group
    • SolrQuery::__construct — Constructor
    • SolrQuery::__destruct — Destructor
    • SolrQuery::getExpand — Returns true if group expanding is enabled
    • SolrQuery::getExpandFilterQueries — Returns the expand filter queries
    • SolrQuery::getExpandQuery — Returns the expand query expand.q parameter
    • SolrQuery::getExpandRows — Returns The number of rows to display in each group (expand.rows)
    • SolrQuery::getExpandSortFields — Returns an array of fields
    • SolrQuery::getFacet — Returns the value of the facet parameter
    • SolrQuery::getFacetDateEnd — Returns the value for the facet.date.end parameter
    • SolrQuery::getFacetDateFields — Returns all the facet.date fields
    • SolrQuery::getFacetDateGap — Returns the value of the facet.date.gap parameter
    • SolrQuery::getFacetDateHardEnd — Returns the value of the facet.date.hardend parameter
    • SolrQuery::getFacetDateOther — Returns the value for the facet.date.other parameter
    • SolrQuery::getFacetDateStart — Returns the lower bound for the first date range for all date faceting on this field
    • SolrQuery::getFacetFields — Returns all the facet fields
    • SolrQuery::getFacetLimit — Returns the maximum number of constraint counts that should be returned for the facet fields
    • SolrQuery::getFacetMethod — Returns the value of the facet.method parameter
    • SolrQuery::getFacetMinCount — Returns the minimum counts for facet fields should be included in the response
    • SolrQuery::getFacetMissing — Returns the current state of the facet.missing parameter
    • SolrQuery::getFacetOffset — Returns an offset into the list of constraints to be used for pagination
    • SolrQuery::getFacetPrefix — Returns the facet prefix
    • SolrQuery::getFacetQueries — Returns all the facet queries
    • SolrQuery::getFacetSort — Returns the facet sort type
    • SolrQuery::getFields — Returns the list of fields that will be returned in the response
    • SolrQuery::getFilterQueries — Returns an array of filter queries
    • SolrQuery::getGroup — Returns true if grouping is enabled
    • SolrQuery::getGroupCachePercent — Returns group cache percent value
    • SolrQuery::getGroupFacet — Returns the group.facet parameter value
    • SolrQuery::getGroupFields — Returns group fields (group.field parameter values)
    • SolrQuery::getGroupFormat — Returns the group.format value
    • SolrQuery::getGroupFunctions — Returns group functions (group.func parameter values)
    • SolrQuery::getGroupLimit — Returns the group.limit value
    • SolrQuery::getGroupMain — Returns the group.main value
    • SolrQuery::getGroupNGroups — Returns the group.ngroups value
    • SolrQuery::getGroupOffset — Returns the group.offset value
    • SolrQuery::getGroupQueries — Returns all the group.query parameter values
    • SolrQuery::getGroupSortFields — Returns the group.sort value
    • SolrQuery::getGroupTruncate — Returns the group.truncate value
    • SolrQuery::getHighlight — Returns the state of the hl parameter
    • SolrQuery::getHighlightAlternateField — Returns the highlight field to use as backup or default
    • SolrQuery::getHighlightFields — Returns all the fields that Solr should generate highlighted snippets for
    • SolrQuery::getHighlightFormatter — Returns the formatter for the highlighted output
    • SolrQuery::getHighlightFragmenter — Returns the text snippet generator for highlighted text
    • SolrQuery::getHighlightFragsize — Returns the number of characters of fragments to consider for highlighting
    • SolrQuery::getHighlightHighlightMultiTerm — Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries
    • SolrQuery::getHighlightMaxAlternateFieldLength — Returns the maximum number of characters of the field to return
    • SolrQuery::getHighlightMaxAnalyzedChars — Returns the maximum number of characters into a document to look for suitable snippets
    • SolrQuery::getHighlightMergeContiguous — Returns whether or not the collapse contiguous fragments into a single fragment
    • SolrQuery::getHighlightRegexMaxAnalyzedChars — Returns the maximum number of characters from a field when using the regex fragmenter
    • SolrQuery::getHighlightRegexPattern — Returns the regular expression for fragmenting
    • SolrQuery::getHighlightRegexSlop — Returns the deviation factor from the ideal fragment size
    • SolrQuery::getHighlightRequireFieldMatch — Returns if a field will only be highlighted if the query matched in this particular field
    • SolrQuery::getHighlightSimplePost — Returns the text which appears after a highlighted term
    • SolrQuery::getHighlightSimplePre — Returns the text which appears before a highlighted term
    • SolrQuery::getHighlightSnippets — Returns the maximum number of highlighted snippets to generate per field
    • SolrQuery::getHighlightUsePhraseHighlighter — Returns the state of the hl.usePhraseHighlighter parameter
    • SolrQuery::getMlt — Returns whether or not MoreLikeThis results should be enabled
    • SolrQuery::getMltBoost — Returns whether or not the query will be boosted by the interesting term relevance
    • SolrQuery::getMltCount — Returns the number of similar documents to return for each result
    • SolrQuery::getMltFields — Returns all the fields to use for similarity
    • SolrQuery::getMltMaxNumQueryTerms — Returns the maximum number of query terms that will be included in any generated query
    • SolrQuery::getMltMaxNumTokens — Returns the maximum number of tokens to parse in each document field that is not stored with TermVector support
    • SolrQuery::getMltMaxWordLength — Returns the maximum word length above which words will be ignored
    • SolrQuery::getMltMinDocFrequency — Returns the treshold frequency at which words will be ignored which do not occur in at least this many docs
    • SolrQuery::getMltMinTermFrequency — Returns the frequency below which terms will be ignored in the source document
    • SolrQuery::getMltMinWordLength — Returns the minimum word length below which words will be ignored
    • SolrQuery::getMltQueryFields — Returns the query fields and their boosts
    • SolrQuery::getQuery — Returns the main query
    • SolrQuery::getRows — Returns the maximum number of documents
    • SolrQuery::getSortFields — Returns all the sort fields
    • SolrQuery::getStart — Returns the offset in the complete result set
    • SolrQuery::getStats — Returns whether or not stats is enabled
    • SolrQuery::getStatsFacets — Returns all the stats facets that were set
    • SolrQuery::getStatsFields — Returns all the statistics fields
    • SolrQuery::getTerms — Returns whether or not the TermsComponent is enabled
    • SolrQuery::getTermsField — Returns the field from which the terms are retrieved
    • SolrQuery::getTermsIncludeLowerBound — Returns whether or not to include the lower bound in the result set
    • SolrQuery::getTermsIncludeUpperBound — Returns whether or not to include the upper bound term in the result set
    • SolrQuery::getTermsLimit — Returns the maximum number of terms Solr should return
    • SolrQuery::getTermsLowerBound — Returns the term to start at
    • SolrQuery::getTermsMaxCount — Returns the maximum document frequency
    • SolrQuery::getTermsMinCount — Returns the minimum document frequency to return in order to be included
    • SolrQuery::getTermsPrefix — Returns the term prefix
    • SolrQuery::getTermsReturnRaw — Whether or not to return raw characters
    • SolrQuery::getTermsSort — Returns an integer indicating how terms are sorted
    • SolrQuery::getTermsUpperBound — Returns the term to stop at
    • SolrQuery::getTimeAllowed — Returns the time in milliseconds allowed for the query to finish
    • SolrQuery::removeExpandFilterQuery — Removes an expand filter query
    • SolrQuery::removeExpandSortField — Removes an expand sort field from the expand.sort parameter
    • SolrQuery::removeFacetDateField — Removes one of the facet date fields
    • SolrQuery::removeFacetDateOther — Removes one of the facet.date.other parameters
    • SolrQuery::removeFacetField — Removes one of the facet.date parameters
    • SolrQuery::removeFacetQuery — Removes one of the facet.query parameters
    • SolrQuery::removeField — Removes a field from the list of fields
    • SolrQuery::removeFilterQuery — Removes a filter query
    • SolrQuery::removeHighlightField — Removes one of the fields used for highlighting
    • SolrQuery::removeMltField — Removes one of the moreLikeThis fields
    • SolrQuery::removeMltQueryField — Removes one of the moreLikeThis query fields
    • SolrQuery::removeSortField — Removes one of the sort fields
    • SolrQuery::removeStatsFacet — Removes one of the stats.facet parameters
    • SolrQuery::removeStatsField — Removes one of the stats.field parameters
    • SolrQuery::setEchoHandler — Toggles the echoHandler parameter
    • SolrQuery::setEchoParams — Determines what kind of parameters to include in the response
    • SolrQuery::setExpand — Enables/Disables the Expand Component
    • SolrQuery::setExpandQuery — Sets the expand.q parameter
    • SolrQuery::setExpandRows — Sets the number of rows to display in each group (expand.rows). Server Default 5
    • SolrQuery::setExplainOther — Sets the explainOther common query parameter
    • SolrQuery::setFacet — Maps to the facet parameter. Enables or disables facetting
    • SolrQuery::setFacetDateEnd — Maps to facet.date.end
    • SolrQuery::setFacetDateGap — Maps to facet.date.gap
    • SolrQuery::setFacetDateHardEnd — Maps to facet.date.hardend
    • SolrQuery::setFacetDateStart — Maps to facet.date.start
    • SolrQuery::setFacetEnumCacheMinDefaultFrequency — Sets the minimum document frequency used for determining term count
    • SolrQuery::setFacetLimit — Maps to facet.limit
    • SolrQuery::setFacetMethod — Specifies the type of algorithm to use when faceting a field
    • SolrQuery::setFacetMinCount — Maps to facet.mincount
    • SolrQuery::setFacetMissing — Maps to facet.missing
    • SolrQuery::setFacetOffset — Sets the offset into the list of constraints to allow for pagination
    • SolrQuery::setFacetPrefix — Specifies a string prefix with which to limits the terms on which to facet
    • SolrQuery::setFacetSort — Determines the ordering of the facet field constraints
    • SolrQuery::setGroup — Enable/Disable result grouping (group parameter)
    • SolrQuery::setGroupCachePercent — Enables caching for result grouping
    • SolrQuery::setGroupFacet — Sets group.facet parameter
    • SolrQuery::setGroupFormat — Sets the group format, result structure (group.format parameter)
    • SolrQuery::setGroupLimit — Specifies the number of results to return for each group. The server default value is 1
    • SolrQuery::setGroupMain — If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
    • SolrQuery::setGroupNGroups — If true, Solr includes the number of groups that have matched the query in the results
    • SolrQuery::setGroupOffset — Sets the group.offset parameter
    • SolrQuery::setGroupTruncate — If true, facet counts are based on the most relevant document of each group matching the query
    • SolrQuery::setHighlight — Enables or disables highlighting
    • SolrQuery::setHighlightAlternateField — Specifies the backup field to use
    • SolrQuery::setHighlightFormatter — Specify a formatter for the highlight output
    • SolrQuery::setHighlightFragmenter — Sets a text snippet generator for highlighted text
    • SolrQuery::setHighlightFragsize — The size of fragments to consider for highlighting
    • SolrQuery::setHighlightHighlightMultiTerm — Use SpanScorer to highlight phrase terms
    • SolrQuery::setHighlightMaxAlternateFieldLength — Sets the maximum number of characters of the field to return
    • SolrQuery::setHighlightMaxAnalyzedChars — Specifies the number of characters into a document to look for suitable snippets
    • SolrQuery::setHighlightMergeContiguous — Whether or not to collapse contiguous fragments into a single fragment
    • SolrQuery::setHighlightRegexMaxAnalyzedChars — Specify the maximum number of characters to analyze
    • SolrQuery::setHighlightRegexPattern — Specify the regular expression for fragmenting
    • SolrQuery::setHighlightRegexSlop — Sets the factor by which the regex fragmenter can stray from the ideal fragment size
    • SolrQuery::setHighlightRequireFieldMatch — Require field matching during highlighting
    • SolrQuery::setHighlightSimplePost — Sets the text which appears after a highlighted term
    • SolrQuery::setHighlightSimplePre — Sets the text which appears before a highlighted term
    • SolrQuery::setHighlightSnippets — Sets the maximum number of highlighted snippets to generate per field
    • SolrQuery::setHighlightUsePhraseHighlighter — Whether to highlight phrase terms only when they appear within the query phrase
    • SolrQuery::setMlt — Enables or disables moreLikeThis
    • SolrQuery::setMltBoost — Set if the query will be boosted by the interesting term relevance
    • SolrQuery::setMltCount — Set the number of similar documents to return for each result
    • SolrQuery::setMltMaxNumQueryTerms — Sets the maximum number of query terms included
    • SolrQuery::setMltMaxNumTokens — Specifies the maximum number of tokens to parse
    • SolrQuery::setMltMaxWordLength — Sets the maximum word length
    • SolrQuery::setMltMinDocFrequency — Sets the mltMinDoc frequency
    • SolrQuery::setMltMinTermFrequency — Sets the frequency below which terms will be ignored in the source docs
    • SolrQuery::setMltMinWordLength — Sets the minimum word length
    • SolrQuery::setOmitHeader — Exclude the header from the returned results
    • SolrQuery::setQuery — Sets the search query
    • SolrQuery::setRows — Specifies the maximum number of rows to return in the result
    • SolrQuery::setShowDebugInfo — Flag to show debug information
    • SolrQuery::setStart — Specifies the number of rows to skip
    • SolrQuery::setStats — Enables or disables the Stats component
    • SolrQuery::setTerms — Enables or disables the TermsComponent
    • SolrQuery::setTermsField — Sets the name of the field to get the Terms from
    • SolrQuery::setTermsIncludeLowerBound — Include the lower bound term in the result set
    • SolrQuery::setTermsIncludeUpperBound — Include the upper bound term in the result set
    • SolrQuery::setTermsLimit — Sets the maximum number of terms to return
    • SolrQuery::setTermsLowerBound — Specifies the Term to start from
    • SolrQuery::setTermsMaxCount — Sets the maximum document frequency
    • SolrQuery::setTermsMinCount — Sets the minimum document frequency
    • SolrQuery::setTermsPrefix — Restrict matches to terms that start with the prefix
    • SolrQuery::setTermsReturnRaw — Return the raw characters of the indexed term
    • SolrQuery::setTermsSort — Specifies how to sort the returned terms
    • SolrQuery::setTermsUpperBound — Sets the term to stop at
    • SolrQuery::setTimeAllowed — The time allowed for search to finish
  • SolrDisMaxQuery — The SolrDisMaxQuery class
    • SolrDisMaxQuery::addBigramPhraseField — Adds a Phrase Bigram Field (pf2 parameter)
    • SolrDisMaxQuery::addBoostQuery — Adds a boost query field with value and optional boost (bq parameter)
    • SolrDisMaxQuery::addPhraseField — Adds a Phrase Field (pf parameter)
    • SolrDisMaxQuery::addQueryField — Add a query field with optional boost (qf parameter)
    • SolrDisMaxQuery::addTrigramPhraseField — Adds a Trigram Phrase Field (pf3 parameter)
    • SolrDisMaxQuery::addUserField — Adds a field to User Fields Parameter (uf)
    • SolrDisMaxQuery::__construct — Class Constructor
    • SolrDisMaxQuery::removeBigramPhraseField — Removes phrase bigram field (pf2 parameter)
    • SolrDisMaxQuery::removeBoostQuery — Removes a boost query partial by field name (bq)
    • SolrDisMaxQuery::removePhraseField — Removes a Phrase Field (pf parameter)
    • SolrDisMaxQuery::removeQueryField — Removes a Query Field (qf parameter)
    • SolrDisMaxQuery::removeTrigramPhraseField — Removes a Trigram Phrase Field (pf3 parameter)
    • SolrDisMaxQuery::removeUserField — Removes a field from The User Fields Parameter (uf)
    • SolrDisMaxQuery::setBigramPhraseFields — Sets Bigram Phrase Fields and their boosts (and slops) using pf2 parameter
    • SolrDisMaxQuery::setBigramPhraseSlop — Sets Bigram Phrase Slop (ps2 parameter)
    • SolrDisMaxQuery::setBoostFunction — Sets a Boost Function (bf parameter)
    • SolrDisMaxQuery::setBoostQuery — Directly Sets Boost Query Parameter (bq)
    • SolrDisMaxQuery::setMinimumMatch — Set Minimum "Should" Match (mm)
    • SolrDisMaxQuery::setPhraseFields — Sets Phrase Fields and their boosts (and slops) using pf2 parameter
    • SolrDisMaxQuery::setPhraseSlop — Sets the default slop on phrase queries (ps parameter)
    • SolrDisMaxQuery::setQueryAlt — Set Query Alternate (q.alt parameter)
    • SolrDisMaxQuery::setQueryPhraseSlop — Specifies the amount of slop permitted on phrase queries explicitly included in the user's query string (qf parameter)
    • SolrDisMaxQuery::setTieBreaker — Sets Tie Breaker parameter (tie parameter)
    • SolrDisMaxQuery::setTrigramPhraseFields — Directly Sets Trigram Phrase Fields (pf3 parameter)
    • SolrDisMaxQuery::setTrigramPhraseSlop — Sets Trigram Phrase Slop (ps3 parameter)
    • SolrDisMaxQuery::setUserFields — Sets User Fields parameter (uf)
    • SolrDisMaxQuery::useDisMaxQueryParser — Switch QueryParser to be DisMax Query Parser
    • SolrDisMaxQuery::useEDisMaxQueryParser — Switch QueryParser to be EDisMax
  • SolrCollapseFunction — The SolrCollapseFunction class
    • SolrCollapseFunction::__construct — Constructor
    • SolrCollapseFunction::getField — Returns the field that is being collapsed on
    • SolrCollapseFunction::getHint — Returns collapse hint
    • SolrCollapseFunction::getMax — Returns max parameter
    • SolrCollapseFunction::getMin — Returns min parameter
    • SolrCollapseFunction::getNullPolicy — Returns null policy
    • SolrCollapseFunction::getSize — Returns size parameter
    • SolrCollapseFunction::setField — Sets the field to collapse on
    • SolrCollapseFunction::setHint — Sets collapse hint
    • SolrCollapseFunction::setMax — Selects the group heads by the max value of a numeric field or function query
    • SolrCollapseFunction::setMin — Sets the initial size of the collapse data structures when collapsing on a numeric field only
    • SolrCollapseFunction::setNullPolicy — Sets the NULL Policy
    • SolrCollapseFunction::setSize — Sets the initial size of the collapse data structures when collapsing on a numeric field only
    • SolrCollapseFunction::__toString — Returns a string representing the constructed collapse function
  • SolrException — The SolrException class
    • SolrException::getInternalInfo — Returns internal information where the Exception was thrown
  • SolrClientException — The SolrClientException class
    • SolrClientException::getInternalInfo — Returns internal information where the Exception was thrown
  • SolrServerException — The SolrServerException class
    • SolrServerException::getInternalInfo — Returns internal information where the Exception was thrown
  • SolrIllegalArgumentException — The SolrIllegalArgumentException class
    • SolrIllegalArgumentException::getInternalInfo — Returns internal information where the Exception was thrown
  • SolrIllegalOperationException — The SolrIllegalOperationException class
    • SolrIllegalOperationException::getInternalInfo — Returns internal information where the Exception was thrown
  • SolrMissingMandatoryParameterException — The SolrMissingMandatoryParameterException class


Introduction

The Solr extension allows you to communicate effectively with the Apache Solr Server in PHP.

The Solr extension is an extremely fast, light-weight, feature-rich library that allows PHP developers to communicate effectively with Solr server instances.

Versions 1.x of The PECL Extension supports Apache Solr Server 1.3-3.x

Versions 2.x of The PECL Extension supports Apache Solr Server 4.0+

There are built-in tools to add documents and make updates to the solr server.

It also contains tools that allows you to build advanced queries to the server when searching for documents.


Requirements

PHP version 5.2.11 or later is required.

The libxml and curl extensions must also be enabled for the Apache Solr extension to be available.

libxml2 2.6.31 or later is required.

libcurl 7.18.0 or later is also required.

The above library versions are required and attempting to hack the code to make it compile is strongly discouraged. It will fail, possibly with errors that could be hard to debug


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/solr.

For help and support, please visit the extension google group. » Apache Solr PHP Extension

Windows binaries (DLL files) for this PECL extension are available from the PECL website.

Note:

The solr module can be compiled in debug mode by passing the --enable-solr-debug flag to configure

When building manually, be sure to include curl and libxml support within the build.


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.

SOLR_MAJOR_VERSION (integer)
SOLR_MINOR_VERSION (integer)
SOLR_PATCH_VERSION (integer)
SOLR_EXTENSION_VERSION (string)


Solr Functions

Table of Contents

  • solr_get_version — Returns the current version of the Apache Solr extension


Returns the current version of the Apache Solr extension

  • « Solr Functions
  • Examples »
  • PHP Manual
  • Solr Functions
  • Returns the current version of the Apache Solr extension

solr_get_version

(PECL solr >= 0.9.1)

solr_get_version — Returns the current version of the Apache Solr extension

Description

solr_get_version ( void ) : string

This function returns the current version of the extension as a string.

Parameters

This function has no parameters.

Return Values

It returns a string on success and FALSE on failure.

Errors/Exceptions

This function throws no errors or exceptions.

Examples

Example #1 solr_get_version() example

<?php

$solr_version = solr_get_version();

print $solr_version;

?>

The above example will output something similar to:

0.9.6

See Also

  • SolrUtils::getSolrVersion() - Returns the current version of the Solr extension


Examples

Examples of how to use the Apache Solr extension in PHP

Example #1 Contents of the BootStrap file

<?php

/* Domain name of the Solr server */
define('SOLR_SERVER_HOSTNAME', 'solr.example.com');

/* Whether or not to run in secure mode */
define('SOLR_SECURE', true);

/* HTTP Port to connection */
define('SOLR_SERVER_PORT', ((SOLR_SECURE) ? 8443 : 8983));

/* HTTP Basic Authentication Username */
define('SOLR_SERVER_USERNAME', 'admin');

/* HTTP Basic Authentication password */
define('SOLR_SERVER_PASSWORD', 'changeit');

/* HTTP connection timeout */
/* This is maximum time in seconds allowed for the http data transfer operation. Default value is 30 seconds */
define('SOLR_SERVER_TIMEOUT', 10);

/* File name to a PEM-formatted private key + private certificate (concatenated in that order) */
define('SOLR_SSL_CERT', 'certs/combo.pem');

/* File name to a PEM-formatted private certificate only */
define('SOLR_SSL_CERT_ONLY', 'certs/solr.crt');

/* File name to a PEM-formatted private key */
define('SOLR_SSL_KEY', 'certs/solr.key');

/* Password for PEM-formatted private key file */
define('SOLR_SSL_KEYPASSWORD', 'StrongAndSecurePassword');

/* Name of file holding one or more CA certificates to verify peer with*/
define('SOLR_SSL_CAINFO', 'certs/cacert.crt');

/* Name of directory holding multiple CA certificates to verify peer with */
define('SOLR_SSL_CAPATH', 'certs/');

?>

Example #2 Adding a document to the index

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$doc = new SolrInputDocument();

$doc->addField('id', 334455);
$doc->addField('cat', 'Software');
$doc->addField('cat', 'Lucene');

$updateResponse = $client->addDocument($doc);

print_r($updateResponse->getResponse());

?>

The above example will output something similar to:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 446
        )

)

Example #3 Merging one document into another document

<?php

include "bootstrap.php";

$doc = new SolrDocument();

$second_doc = new SolrDocument();

$doc->addField('id', 1123);

$doc->features = "PHP Client Side";
$doc->features = "Fast development cycles";

$doc['cat'] = 'Software';
$doc['cat'] = 'Custom Search';
$doc->cat   = 'Information Technology';

$second_doc->addField('cat', 'Lucene Search');

$second_doc->merge($doc, true);

print_r($second_doc->toArray());

?>

The above example will output something similar to:

Array
(
    [document_boost] => 0
    [field_count] => 3
    [fields] => Array
        (
            [0] => SolrDocumentField Object
                (
                    [name] => cat
                    [boost] => 0
                    [values] => Array
                        (
                            [0] => Software
                            [1] => Custom Search
                            [2] => Information Technology
                        )

                )

            [1] => SolrDocumentField Object
                (
                    [name] => id
                    [boost] => 0
                    [values] => Array
                        (
                            [0] => 1123
                        )

                )

            [2] => SolrDocumentField Object
                (
                    [name] => features
                    [boost] => 0
                    [values] => Array
                        (
                            [0] => PHP Client Side
                            [1] => Fast development cycles
                        )

                )

        )

)

Example #4 Searching for documents - SolrObject responses

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setQuery('lucene');

$query->setStart(0);

$query->setRows(50);

$query->addField('cat')->addField('features')->addField('id')->addField('timestamp');

$query_response = $client->query($query);

$response = $query_response->getResponse();

print_r($response);

?>

The above example will output something similar to:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 1
            [params] => SolrObject Object
                (
                    [wt] => xml
                    [rows] => 50
                    [start] => 0
                    [indent] => on
                    [q] => lucene
                    [fl] => cat,features,id,timestamp
                    [version] => 2.2
                )

        )

    [response] => SolrObject Object
        (
            [numFound] => 3
            [start] => 0
            [docs] => Array
                (
                    [0] => SolrObject Object
                        (
                            [cat] => Array
                                (
                                    [0] => Software
                                    [1] => Lucene
                                )

                            [id] => 334456
                        )

                    [1] => SolrObject Object
                        (
                            [cat] => Array
                                (
                                    [0] => Software
                                    [1] => Lucene
                                )

                            [id] => 334455
                        )

                    [2] => SolrObject Object
                        (
                            [cat] => Array
                                (
                                    [0] => software
                                    [1] => search
                                )

                            [features] => Array
                                (
                                    [0] => Advanced Full-Text Search Capabilities using Lucene
                                    [1] => Optimized for High Volume Web Traffic
                                    [2] => Standards Based Open Interfaces - XML and HTTP
                                    [3] => Comprehensive HTML Administration Interfaces
                                    [4] => Scalability - Efficient Replication to other Solr Search Servers
                                    [5] => Flexible and Adaptable with XML configuration and Schema
                                    [6] => Good unicode support: héllo (hello with an accent over the e)
                                )

                            [id] => SOLR1000
                            [timestamp] => 2009-09-04T20:38:55.906
                        )

                )

        )

)

Example #5 Searching for documents - SolrDocument responses

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setQuery('lucene');

$query->setStart(0);

$query->setRows(50);

$query->addField('cat')->addField('features')->addField('id')->addField('timestamp');

$query_response = $client->query($query);

$query_response->setParseMode(SolrQueryResponse::PARSE_SOLR_DOC);

$response = $query_response->getResponse();

print_r($response);

?>

The above example will output something similar to:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 1
            [params] => SolrObject Object
                (
                    [wt] => xml
                    [rows] => 50
                    [start] => 0
                    [indent] => on
                    [q] => lucene
                    [fl] => cat,features,id,timestamp
                    [version] => 2.2
                )

        )

    [response] => SolrObject Object
        (
            [numFound] => 3
            [start] => 0
            [docs] => Array
                (
                    [0] => SolrDocument Object
                        (
                            [_hashtable_index:SolrDocument:private] => 19740
                        )

                    [1] => SolrDocument Object
                        (
                            [_hashtable_index:SolrDocument:private] => 25485
                        )

                    [2] => SolrDocument Object
                        (
                            [_hashtable_index:SolrDocument:private] => 25052
                        )

                )

        )

)

Example #6 Simple TermsComponent example - basic

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setTerms(true);

$query->setTermsField('cat');

$updateResponse = $client->query($query);

print_r($updateResponse->getResponse());

?>

The above example will output something similar to:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 2
        )

    [terms] => SolrObject Object
        (
            [cat] => SolrObject Object
                (
                    [electronics] => 14
                    [Lucene] => 4
                    [Software] => 4
                    [memory] => 3
                    [card] => 2
                    [connector] => 2
                    [drive] => 2
                    [graphics] => 2
                    [hard] => 2
                    [monitor] => 2
                )

        )

)

Example #7 Simple TermsComponent example - using a prefix

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setTerms(true);

/* Return only terms starting with $prefix */
$prefix = 'c';

$query->setTermsField('cat')->setTermsPrefix($prefix);

$updateResponse = $client->query($query);

print_r($updateResponse->getResponse());

?>

The above example will output something similar to:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 1
        )

    [terms] => SolrObject Object
        (
            [cat] => SolrObject Object
                (
                    [card] => 2
                    [connector] => 2
                    [camera] => 1
                    [copier] => 1
                )

        )

)

Example #8 Simple TermsComponent example - specifying a minimum frequency

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setTerms(true);

/* Return only terms starting with $prefix */
$prefix = 'c';

/* Return only terms with a frequency of 2 or greater */
$min_frequency = 2;

$query->setTermsField('cat')->setTermsPrefix($prefix)->setTermsMinCount($min_frequency);

$updateResponse = $client->query($query);

print_r($updateResponse->getResponse());

?>

The above example will output something similar to:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 0
        )

    [terms] => SolrObject Object
        (
            [cat] => SolrObject Object
                (
                    [card] => 2
                    [connector] => 2
                )

        )

)

Example #9 Simple Facet Example

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery('*:*');

$query->setFacet(true);

$query->addFacetField('cat')->addFacetField('name')->setFacetMinCount(2);

$updateResponse = $client->query($query);

$response_array = $updateResponse->getResponse();

$facet_data = $response_array->facet_counts->facet_fields;

print_r($facet_data);

?>

The above example will output something similar to:

SolrObject Object
(
    [cat] => SolrObject Object
        (
            [electronics] => 14
            [memory] => 3
            [Lucene] => 2
            [Software] => 2
            [card] => 2
            [connector] => 2
            [drive] => 2
            [graphics] => 2
            [hard] => 2
            [monitor] => 2
            [search] => 2
            [software] => 2
        )

    [name] => SolrObject Object
        (
            [gb] => 6
            [1] => 3
            [184] => 3
            [2] => 3
            [3200] => 3
            [400] => 3
            [500] => 3
            [ddr] => 3
            [i] => 3
            [ipod] => 3
            [memori] => 3
            [pc] => 3
            [pin] => 3
            [pod] => 3
            [sdram] => 3
            [system] => 3
            [unbuff] => 3
            [canon] => 2
            [corsair] => 2
            [drive] => 2
            [hard] => 2
            [mb] => 2
            [n] => 2
            [power] => 2
            [retail] => 2
            [video] => 2
            [x] => 2
        )

)

Example #10 Simple Facet Example - with optional field override for mincount

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery('*:*');

$query->setFacet(true);

$query->addFacetField('cat')->addFacetField('name')->setFacetMinCount(2)->setFacetMinCount(4, 'name');

$updateResponse = $client->query($query);

$response_array = $updateResponse->getResponse();

$facet_data = $response_array->facet_counts->facet_fields;

print_r($facet_data);

?>

The above example will output something similar to:

SolrObject Object
(
    [cat] => SolrObject Object
        (
            [electronics] => 14
            [memory] => 3
            [Lucene] => 2
            [Software] => 2
            [card] => 2
            [connector] => 2
            [drive] => 2
            [graphics] => 2
            [hard] => 2
            [monitor] => 2
            [search] => 2
            [software] => 2
        )

    [name] => SolrObject Object
        (
            [gb] => 6
        )

)

Example #11 Facet Date Example

<?php

include "bootstrap.php";

$options = array
(
        'hostname' => SOLR_SERVER_HOSTNAME,
        'login'    => SOLR_SERVER_USERNAME,
        'password' => SOLR_SERVER_PASSWORD,
        'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery('*:*');

$query->setFacet(true);

$query->addFacetDateField('manufacturedate_dt');

$query->setFacetDateStart('2006-02-13T00:00:00Z');

$query->setFacetDateEnd('2012-02-13T00:00:00Z');

$query->setFacetDateGap('+1YEAR');

$query->setFacetDateHardEnd(1);

$query->addFacetDateOther('before');

$updateResponse = $client->query($query);

$response_array = $updateResponse->getResponse();

$facet_data = $response_array->facet_counts->facet_dates;

print_r($facet_data);

?>

The above example will output something similar to:

SolrObject Object
(
    [manufacturedate_dt] => SolrObject Object
        (
            [2006-02-13T00:00:00Z] => 9
            [2007-02-13T00:00:00Z] => 0
            [2008-02-13T00:00:00Z] => 0
            [2009-02-13T00:00:00Z] => 0
            [2010-02-13T00:00:00Z] => 0
            [2011-02-13T00:00:00Z] => 0
            [gap] => +1YEAR
            [start] => 2006-02-13T00:00:00Z
            [end] => 2012-02-13T00:00:00Z
            [before] => 2
        )

)

Example #12 Connecting to SSL-Enabled Server

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
    'timeout'  => SOLR_SERVER_TIMEOUT,
    'secure'   => SOLR_SECURE,
    'ssl_cert' => SOLR_SSL_CERT_ONLY,
    'ssl_key'  => SOLR_SSL_KEY,
    'ssl_keypassword' => SOLR_SSL_KEYPASSWORD,
    'ssl_cainfo' => SOLR_SSL_CAINFO,
);

$client = new SolrClient($options);

$query = new SolrQuery('*:*');

$query->setFacet(true);

$query->addFacetField('cat')->addFacetField('name')->setFacetMinCount(2)->setFacetMinCount(4, 'name');

$updateResponse = $client->query($query);

$response_array = $updateResponse->getResponse();

$facet_data = $response_array->facet_counts->facet_fields;

print_r($facet_data);

?>

The above example will output something similar to:

SolrObject Object
(
    [cat] => SolrObject Object
        (
            [electronics] => 14
            [memory] => 3
            [Lucene] => 2
            [Software] => 2
            [card] => 2
            [connector] => 2
            [drive] => 2
            [graphics] => 2
            [hard] => 2
            [monitor] => 2
            [search] => 2
            [software] => 2
        )

    [name] => SolrObject Object
        (
            [gb] => 6
        )

)

Example #13 Collapsing a SolrQuery

<?php
include "bootstrap.php";

$options = array
(
        'hostname' => SOLR_SERVER_HOSTNAME,
        'login'    => SOLR_SERVER_USERNAME,
        'password' => SOLR_SERVER_PASSWORD,
        'port'     => SOLR_SERVER_PORT,
        'path'     => SOLR_SERVER_PATH
);

$client = new SolrClient($options);

$query = new SolrQuery('*:*');

$collapseFunction = new SolrCollapseFunction('manu_id_s');

$collapseFunction
->setSize(2)
->setNullPolicy(SolrCollapseFunction::NULLPOLICY_IGNORE);

$query
->collapse($collapseFunction)
->setRows(4);

$queryResponse = $client->query($query);

$response = $queryResponse->getResponse();

print_r($response);
?>

The above example will output something similar to:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 1
            [params] => SolrObject Object
                (
                    [q] => *:*
                    [indent] => on
                    [fq] => {!collapse field=manu_id_s size=2 nullPolicy=ignore}
                    [rows] => 4
                    [version] => 2.2
                    [wt] => xml
                )

        )

    [response] => SolrObject Object
        (
            [numFound] => 14
            [start] => 0
            [docs] => Array
                (
                    [0] => SolrObject Object
                        (
                            [id] => SP2514N
                            [name] => Array
                                (
                                    [0] => Samsung SpinPoint P120 SP2514N - hard drive - 250 GB - ATA-133
                                )

                            [manu] => Array
                                (
                                    [0] => Samsung Electronics Co. Ltd.
                                )

                            [manu_id_s] => samsung
                            [cat] => Array
                                (
                                    [0] => electronics
                                    [1] => hard drive
                                )

                            [features] => Array
                                (
                                    [0] => 7200RPM, 8MB cache, IDE Ultra ATA-133
                                    [1] => NoiseGuard, SilentSeek technology, Fluid Dynamic Bearing (FDB) motor
                                )

                            [price] => Array
                                (
                                    [0] => 92
                                )

                            [popularity] => Array
                                (
                                    [0] => 6
                                )

                            [inStock] => Array
                                (
                                    [0] => 1
                                )

                            [manufacturedate_dt] => 2006-02-13T15:26:37Z
                            [store] => Array
                                (
                                    [0] => 35.0752,-97.032
                                )

                            [_version_] => 1510294336412057600
                        )

                    [1] => SolrObject Object
                        (
                            [id] => 6H500F0
                            [name] => Array
                                (
                                    [0] => Maxtor DiamondMax 11 - hard drive - 500 GB - SATA-300
                                )

                            [manu] => Array
                                (
                                    [0] => Maxtor Corp.
                                )

                            [manu_id_s] => maxtor
                            [cat] => Array
                                (
                                    [0] => electronics
                                    [1] => hard drive
                                )

                            [features] => Array
                                (
                                    [0] => SATA 3.0Gb/s, NCQ
                                    [1] => 8.5ms seek
                                    [2] => 16MB cache
                                )

                            [price] => Array
                                (
                                    [0] => 350
                                )

                            [popularity] => Array
                                (
                                    [0] => 6
                                )

                            [inStock] => Array
                                (
                                    [0] => 1
                                )

                            [store] => Array
                                (
                                    [0] => 45.17614,-93.87341
                                )

                            [manufacturedate_dt] => 2006-02-13T15:26:37Z
                            [_version_] => 1510294336449806336
                        )

                    [2] => SolrObject Object
                        (
                            [id] => F8V7067-APL-KIT
                            [name] => Array
                                (
                                    [0] => Belkin Mobile Power Cord for iPod w/ Dock
                                )

                            [manu] => Array
                                (
                                    [0] => Belkin
                                )

                            [manu_id_s] => belkin
                            [cat] => Array
                                (
                                    [0] => electronics
                                    [1] => connector
                                )

                            [features] => Array
                                (
                                    [0] => car power adapter, white
                                )

                            [weight] => Array
                                (
                                    [0] => 4
                                )

                            [price] => Array
                                (
                                    [0] => 19.95
                                )

                            [popularity] => Array
                                (
                                    [0] => 1
                                )

                            [inStock] => Array
                                (
                                    [0] =>
                                )

                            [store] => Array
                                (
                                    [0] => 45.18014,-93.87741
                                )

                            [manufacturedate_dt] => 2005-08-01T16:30:25Z
                            [_version_] => 1510294336458194944
                        )

                    [3] => SolrObject Object
                        (
                            [id] => MA147LL/A
                            [name] => Array
                                (
                                    [0] => Apple 60 GB iPod with Video Playback Black
                                )

                            [manu] => Array
                                (
                                    [0] => Apple Computer Inc.
                                )

                            [manu_id_s] => apple
                            [cat] => Array
                                (
                                    [0] => electronics
                                    [1] => music
                                )

                            [features] => Array
                                (
                                    [0] => iTunes, Podcasts, Audiobooks
                                    [1] => Stores up to 15,000 songs, 25,000 photos, or 150 hours of video
                                    [2] => 2.5-inch, 320x240 color TFT LCD display with LED backlight
                                    [3] => Up to 20 hours of battery life
                                    [4] => Plays AAC, MP3, WAV, AIFF, Audible, Apple Lossless, H.264 video
                                    [5] => Notes, Calendar, Phone book, Hold button, Date display, Photo wallet, Built-in games, JPEG photo playback, Upgradeable firmware, USB 2.0 compatibility, Playback speed control, Rechargeable capability, Battery level indication
                                )

                            [includes] => Array
                                (
                                    [0] => earbud headphones, USB cable
                                )

                            [weight] => Array
                                (
                                    [0] => 5.5
                                )

                            [price] => Array
                                (
                                    [0] => 399
                                )

                            [popularity] => Array
                                (
                                    [0] => 10
                                )

                            [inStock] => Array
                                (
                                    [0] => 1
                                )

                            [store] => Array
                                (
                                    [0] => 37.7752,-100.0232
                                )

                            [manufacturedate_dt] => 2005-10-12T08:00:00Z
                            [_version_] => 1510294336562003968
                        )

                )

        )

)

Example #14 Solr Real Time Get (RTG) example SolrClient::getById()

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
    'path'     => SOLR_SERVER_PATH
);

$client = new SolrClient($options);
$response = $client->getById('GB18030TEST');
print_r($response->getResponse());

?>

The above example will output something similar to:

SolrObject Object
(
    [doc] => SolrObject Object
        (
            [id] => GB18030TEST
            [name] => Array
                (
                    [0] => Test with some GB18030 encoded characters
                )

            [features] => Array
                (
                    [0] => No accents here
                    [1] => 这是一个功能
                    [2] => This is a feature (translated)
                    [3] => 这份文件是很有光泽
                    [4] => This document is very shiny (translated)
                )

            [price] => Array
                (
                    [0] => 0
                )

            [inStock] => Array
                (
                    [0] => 1
                )

            [_version_] => 1510294336239042560
        )

)


The SolrUtils class

(PECL solr >= 0.9.2)

Introduction

Contains utility methods for retrieving the current extension version and preparing query phrases.

Also contains method for escaping query strings and parsing XML responses.

Class synopsis

abstract SolrUtils {
/* Methods */
public static digestXmlResponse ( string $xmlresponse [, int $parse_mode = 0 ] ) : SolrObject
public static escapeQueryChars ( string $str ) : string
public static getSolrVersion ( void ) : string
public static queryPhrase ( string $str ) : string
}

Table of Contents

  • SolrUtils::digestXmlResponse — Parses an response XML string into a SolrObject
  • SolrUtils::escapeQueryChars — Escapes a lucene query string
  • SolrUtils::getSolrVersion — Returns the current version of the Solr extension
  • SolrUtils::queryPhrase — Prepares a phrase from an unescaped lucene string


Parses an response XML string into a SolrObject

  • « SolrUtils
  • SolrUtils::escapeQueryChars »
  • PHP Manual
  • SolrUtils
  • Parses an response XML string into a SolrObject

SolrUtils::digestXmlResponse

(PECL solr >= 0.9.2)

SolrUtils::digestXmlResponse — Parses an response XML string into a SolrObject

Description

public static SolrUtils::digestXmlResponse ( string $xmlresponse [, int $parse_mode = 0 ] ) : SolrObject

This method parses an response XML string from the Apache Solr server into a SolrObject. It throws a SolrException if there was an error.

Parameters

xmlresponse

The XML response string from the Solr server.

parse_mode

Use SolrResponse::PARSE_SOLR_OBJ or SolrResponse::PARSE_SOLR_DOC

Return Values

Returns the SolrObject representing the XML response.

If the parse_mode parameter is set to SolrResponse::PARSE_SOLR_OBJ Solr documents will be parses as SolrObject instances.

If it is set to SolrResponse::PARSE_SOLR_DOC, they will be parsed as SolrDocument instances.


Escapes a lucene query string

  • « SolrUtils::digestXmlResponse
  • SolrUtils::getSolrVersion »
  • PHP Manual
  • SolrUtils
  • Escapes a lucene query string

SolrUtils::escapeQueryChars

(PECL solr >= 0.9.2)

SolrUtils::escapeQueryChars — Escapes a lucene query string

Description

public static SolrUtils::escapeQueryChars ( string $str ) : string

Lucene supports escaping special characters that are part of the query syntax.

The current list special characters are:

+ - && || ! ( ) { } [ ] ^ " ~ * ? : \ /

These characters are part of the query syntax and must be escaped

Parameters

str

This is the query string to be escaped.

Return Values

Returns the escaped string or FALSE on failure.


Returns the current version of the Solr extension

  • « SolrUtils::escapeQueryChars
  • SolrUtils::queryPhrase »
  • PHP Manual
  • SolrUtils
  • Returns the current version of the Solr extension

SolrUtils::getSolrVersion

(PECL solr >= 0.9.2)

SolrUtils::getSolrVersion — Returns the current version of the Solr extension

Description

public static SolrUtils::getSolrVersion ( void ) : string

Returns the current Solr version.

Parameters

This function has no parameters.

Return Values

The current version of the Apache Solr extension.


Prepares a phrase from an unescaped lucene string

  • « SolrUtils::getSolrVersion
  • SolrInputDocument »
  • PHP Manual
  • SolrUtils
  • Prepares a phrase from an unescaped lucene string

SolrUtils::queryPhrase

(PECL solr >= 0.9.2)

SolrUtils::queryPhrase — Prepares a phrase from an unescaped lucene string

Description

public static SolrUtils::queryPhrase ( string $str ) : string

Prepares a phrase from an unescaped lucene string.

Parameters

str

The lucene phrase.

Return Values

Returns the phrase contained in double quotes.


The SolrInputDocument class

(PECL solr >= 0.9.2)

Introduction

This class represents a Solr document that is about to be submitted to the Solr index.

Class synopsis

final SolrInputDocument {
/* Constants */
const integer SORT_DEFAULT = 1 ;
const integer SORT_ASC = 1 ;
const integer SORT_DESC = 2 ;
const integer SORT_FIELD_NAME = 1 ;
const integer SORT_FIELD_VALUE_COUNT = 2 ;
const integer SORT_FIELD_BOOST_VALUE = 4 ;
/* Methods */
public addChildDocument ( SolrInputDocument $child ) : void
public addChildDocuments ( array &$docs ) : void
public addField ( string $fieldName , string $fieldValue [, float $fieldBoostValue = 0.0 ] ) : bool
public clear ( void ) : bool
public __clone ( void ) : void
public __construct ( void )
public deleteField ( string $fieldName ) : bool
public __destruct ( void ) : void
public fieldExists ( string $fieldName ) : bool
public getBoost ( void ) : float
public getChildDocuments ( void ) : array
public getChildDocumentsCount ( void ) : int
public getField ( string $fieldName ) : SolrDocumentField
public getFieldBoost ( string $fieldName ) : float
public getFieldCount ( void ) : int
public getFieldNames ( void ) : array
public hasChildDocuments ( void ) : bool
public merge ( SolrInputDocument $sourceDoc [, bool $overwrite = TRUE ] ) : bool
public reset ( void ) : bool
public setBoost ( float $documentBoostValue ) : bool
public setFieldBoost ( string $fieldName , float $fieldBoostValue ) : bool
public sort ( int $sortOrderBy [, int $sortDirection = SolrInputDocument::SORT_ASC ] ) : bool
public toArray ( void ) : array
}

Predefined Constants

SolrInputDocument Class Constants

SolrInputDocument::SORT_DEFAULT

Sorts the fields in ascending order.

SolrInputDocument::SORT_ASC

Sorts the fields in ascending order.

SolrInputDocument::SORT_DESC

Sorts the fields in descending order.

SolrInputDocument::SORT_FIELD_NAME

Sorts the fields by name

SolrInputDocument::SORT_FIELD_VALUE_COUNT

Sorts the fields by number of values.

SolrInputDocument::SORT_FIELD_BOOST_VALUE

Sorts the fields by boost value.

Table of Contents

  • SolrInputDocument::addChildDocument — Adds a child document for block indexing
  • SolrInputDocument::addChildDocuments — Adds an array of child documents
  • SolrInputDocument::addField — Adds a field to the document
  • SolrInputDocument::clear — Resets the input document
  • SolrInputDocument::__clone — Creates a copy of a SolrDocument
  • SolrInputDocument::__construct — Constructor
  • SolrInputDocument::deleteField — Removes a field from the document
  • SolrInputDocument::__destruct — Destructor
  • SolrInputDocument::fieldExists — Checks if a field exists
  • SolrInputDocument::getBoost — Retrieves the current boost value for the document
  • SolrInputDocument::getChildDocuments — Returns an array of child documents (SolrInputDocument)
  • SolrInputDocument::getChildDocumentsCount — Returns the number of child documents
  • SolrInputDocument::getField — Retrieves a field by name
  • SolrInputDocument::getFieldBoost — Retrieves the boost value for a particular field
  • SolrInputDocument::getFieldCount — Returns the number of fields in the document
  • SolrInputDocument::getFieldNames — Returns an array containing all the fields in the document
  • SolrInputDocument::hasChildDocuments — Returns true if the document has any child documents
  • SolrInputDocument::merge — Merges one input document into another
  • SolrInputDocument::reset — This is an alias of SolrInputDocument::clear
  • SolrInputDocument::setBoost — Sets the boost value for this document
  • SolrInputDocument::setFieldBoost — Sets the index-time boost value for a field
  • SolrInputDocument::sort — Sorts the fields within the document
  • SolrInputDocument::toArray — Returns an array representation of the input document


Adds a child document for block indexing

  • « SolrInputDocument
  • SolrInputDocument::addChildDocuments »
  • PHP Manual
  • SolrInputDocument
  • Adds a child document for block indexing

SolrInputDocument::addChildDocument

(PECL solr >= 2.3.0)

SolrInputDocument::addChildDocument — Adds a child document for block indexing

Description

public SolrInputDocument::addChildDocument ( SolrInputDocument $child ) : void

Adds a child document to construct a document block with nested documents.

Parameters

child

A SolrInputDocument object.

Errors/Exceptions

Throws SolrIllegalArgumentException on failure.

Throws SolrException on internal failure.

Return Values

Examples

Example #1 SolrInputDocument::addChildDocument() example

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
    'path'     => SOLR_SERVER_STORE_PATH,
);

$client = new SolrClient($options);

$product = new SolrInputDocument();

$product->addField('id', 'P-BLACK');
$product->addField('cat', 'tshirt');
$product->addField('cat', 'polo');
$product->addField('content_type', 'product');

$small = new SolrInputDocument();
$small->addField('id', 'TS-BLK-S');
$small->addField('content_type', 'sku');
$small->addField('size', 'S');
$small->addField('inventory', 100);

$medium = new SolrInputDocument();
$medium->addField('id', 'TS-BLK-M');
$medium->addField('content_type', 'sku');
$medium->addField('size', 'M');
$medium->addField('inventory', 200);

$large = new SolrInputDocument();
$large->addField('id', 'TS-BLK-L');
$large->addField('content_type', 'sku');
$large->addField('size', 'L');
$large->addField('inventory', 300);

// add child documents
$product->addChildDocument($small);
$product->addChildDocument($medium);
$product->addChildDocument($large);

// add product document block to the index
$updateResponse = $client->addDocument(
        $product,
        true, // overwrite if the document exists
        10000 // commit within 10 seconds
);

print_r($updateResponse->getResponse());

The above example will output something similar to:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 5
        )
)

See Also

  • SolrInputDocument::addChildDocuments() - Adds an array of child documents
  • SolrInputDocument::hasChildDocuments() - Returns true if the document has any child documents
  • SolrInputDocument::getChildDocuments() - Returns an array of child documents (SolrInputDocument)
  • SolrInputDocument::getChildDocumentsCount() - Returns the number of child documents


Adds an array of child documents

  • « SolrInputDocument::addChildDocument
  • SolrInputDocument::addField »
  • PHP Manual
  • SolrInputDocument
  • Adds an array of child documents

SolrInputDocument::addChildDocuments

(PECL solr >= 2.3.0)

SolrInputDocument::addChildDocuments — Adds an array of child documents

Description

public SolrInputDocument::addChildDocuments ( array &$docs ) : void

Adds an array of child documents to the current input document.

Parameters

docs

An array of SolrInputDocument objects.

Errors/Exceptions

Throws SolrIllegalArgumentException on failure.

Throws SolrException on internal failure.

Return Values

Examples

Example #1 SolrInputDocument::addChildDocuments() example

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
    'path'     => SOLR_SERVER_STORE_PATH,
);

$client = new SolrClient($options);

$product = new SolrInputDocument();

$product->addField('id', 'P-BLACK');
$product->addField('cat', 'tshirt');
$product->addField('cat', 'polo');
$product->addField('content_type', 'product');

$small = new SolrInputDocument();
$small->addField('id', 'TS-BLK-S');
$small->addField('content_type', 'sku');
$small->addField('size', 'S');
$small->addField('inventory', 100);

$medium = new SolrInputDocument();
$medium->addField('id', 'TS-BLK-M');
$medium->addField('content_type', 'sku');
$medium->addField('size', 'M');
$medium->addField('inventory', 200);

$large = new SolrInputDocument();
$large->addField('id', 'TS-BLK-L');
$large->addField('content_type', 'sku');
$large->addField('size', 'L');
$large->addField('inventory', 300);

// add child documents
$skus = [$small, $medium, $large];
$product->addChildDocuments($skus);

// add the product document block to the index
$updateResponse = $client->addDocument(
        $product,
        true, // overwrite if the document exists
        10000 // commit within 10 seconds
);

print_r($updateResponse->getResponse());

The above example will output something similar to:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 5
        )
)

See Also

  • SolrInputDocument::addChildDocument() - Adds a child document for block indexing
  • SolrInputDocument::hasChildDocuments() - Returns true if the document has any child documents
  • SolrInputDocument::getChildDocuments() - Returns an array of child documents (SolrInputDocument)
  • SolrInputDocument::getChildDocumentsCount() - Returns the number of child documents


Adds a field to the document

  • « SolrInputDocument::addChildDocuments
  • SolrInputDocument::clear »
  • PHP Manual
  • SolrInputDocument
  • Adds a field to the document

SolrInputDocument::addField

(PECL solr >= 0.9.2)

SolrInputDocument::addField — Adds a field to the document

Description

public SolrInputDocument::addField ( string $fieldName , string $fieldValue [, float $fieldBoostValue = 0.0 ] ) : bool

For multi-value fields, if a valid boost value is specified, the specified value will be multiplied by the current boost value for this field.

Parameters

fieldName

The name of the field

fieldValue

The value for the field.

fieldBoostValue

The index time boost for the field. Though this cannot be negative, you can still pass values less than 1.0 but they must be greater than zero.

Return Values

Returns TRUE on success or FALSE on failure.


Resets the input document

  • « SolrInputDocument::addField
  • SolrInputDocument::__clone »
  • PHP Manual
  • SolrInputDocument
  • Resets the input document

SolrInputDocument::clear

(PECL solr >= 0.9.2)

SolrInputDocument::clear — Resets the input document

Description

public SolrInputDocument::clear ( void ) : bool

Resets the document by dropping all the fields and resets the document boost to zero.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.


Creates a copy of a SolrDocument

  • « SolrInputDocument::clear
  • SolrInputDocument::__construct »
  • PHP Manual
  • SolrInputDocument
  • Creates a copy of a SolrDocument

SolrInputDocument::__clone

(PECL solr >= 0.9.2)

SolrInputDocument::__clone — Creates a copy of a SolrDocument

Description

public SolrInputDocument::__clone ( void ) : void

Should not be called directly. It is used to create a deep copy of a SolrInputDocument.

Parameters

This function has no parameters.

Return Values

Creates a new SolrInputDocument instance.


Constructor

  • « SolrInputDocument::__clone
  • SolrInputDocument::deleteField »
  • PHP Manual
  • SolrInputDocument
  • Constructor

SolrInputDocument::__construct

(PECL solr >= 0.9.2)

SolrInputDocument::__construct — Constructor

Description

public SolrInputDocument::__construct ( void )

Constructor.

Parameters

This function has no parameters.

Return Values

None.


Removes a field from the document

  • « SolrInputDocument::__construct
  • SolrInputDocument::__destruct »
  • PHP Manual
  • SolrInputDocument
  • Removes a field from the document

SolrInputDocument::deleteField

(PECL solr >= 0.9.2)

SolrInputDocument::deleteField — Removes a field from the document

Description

public SolrInputDocument::deleteField ( string $fieldName ) : bool

Removes a field from the document.

Parameters

fieldName

The name of the field.

Return Values

Returns TRUE on success or FALSE on failure.


Destructor

  • « SolrInputDocument::deleteField
  • SolrInputDocument::fieldExists »
  • PHP Manual
  • SolrInputDocument
  • Destructor

SolrInputDocument::__destruct

(PECL solr >= 0.9.2)

SolrInputDocument::__destruct — Destructor

Description

public SolrInputDocument::__destruct ( void ) : void

Destructor

Parameters

This function has no parameters.

Return Values

None.


Checks if a field exists

  • « SolrInputDocument::__destruct
  • SolrInputDocument::getBoost »
  • PHP Manual
  • SolrInputDocument
  • Checks if a field exists

SolrInputDocument::fieldExists

(PECL solr >= 0.9.2)

SolrInputDocument::fieldExists — Checks if a field exists

Description

public SolrInputDocument::fieldExists ( string $fieldName ) : bool

Checks if a field exists

Parameters

fieldName

Name of the field.

Return Values

Returns TRUE if the field was found and FALSE if it was not found.


Retrieves the current boost value for the document

  • « SolrInputDocument::fieldExists
  • SolrInputDocument::getChildDocuments »
  • PHP Manual
  • SolrInputDocument
  • Retrieves the current boost value for the document

SolrInputDocument::getBoost

(PECL solr >= 0.9.2)

SolrInputDocument::getBoost — Retrieves the current boost value for the document

Description

public SolrInputDocument::getBoost ( void ) : float

Retrieves the current boost value for the document.

Parameters

This function has no parameters.

Return Values

Returns the boost value on success and FALSE on failure.


Returns an array of child documents (SolrInputDocument)

  • « SolrInputDocument::getBoost
  • SolrInputDocument::getChildDocumentsCount »
  • PHP Manual
  • SolrInputDocument
  • Returns an array of child documents (SolrInputDocument)

SolrInputDocument::getChildDocuments

(PECL solr >= 2.3.0)

SolrInputDocument::getChildDocuments — Returns an array of child documents (SolrInputDocument)

Description

public SolrInputDocument::getChildDocuments ( void ) : array

Returns an array of child documents (SolrInputDocument)

Parameters

This function has no parameters.

Return Values

See Also

  • SolrInputDocument::addChildDocument() - Adds a child document for block indexing
  • SolrInputDocument::addChildDocuments() - Adds an array of child documents
  • SolrInputDocument::hasChildDocuments() - Returns true if the document has any child documents
  • SolrInputDocument::getChildDocumentsCount() - Returns the number of child documents


Returns the number of child documents

  • « SolrInputDocument::getChildDocuments
  • SolrInputDocument::getField »
  • PHP Manual
  • SolrInputDocument
  • Returns the number of child documents

SolrInputDocument::getChildDocumentsCount

(PECL solr >= 2.3.0)

SolrInputDocument::getChildDocumentsCount — Returns the number of child documents

Description

public SolrInputDocument::getChildDocumentsCount ( void ) : int

Returns the number of child documents

Parameters

This function has no parameters.

Return Values

See Also

  • SolrInputDocument::addChildDocument() - Adds a child document for block indexing
  • SolrInputDocument::addChildDocuments() - Adds an array of child documents
  • SolrInputDocument::hasChildDocuments() - Returns true if the document has any child documents
  • SolrInputDocument::getChildDocuments() - Returns an array of child documents (SolrInputDocument)


Retrieves a field by name

  • « SolrInputDocument::getChildDocumentsCount
  • SolrInputDocument::getFieldBoost »
  • PHP Manual
  • SolrInputDocument
  • Retrieves a field by name

SolrInputDocument::getField

(PECL solr >= 0.9.2)

SolrInputDocument::getField — Retrieves a field by name

Description

public SolrInputDocument::getField ( string $fieldName ) : SolrDocumentField

Retrieves a field in the document.

Parameters

fieldName

The name of the field.

Return Values

Returns a SolrDocumentField object on success and FALSE on failure.


Retrieves the boost value for a particular field

  • « SolrInputDocument::getField
  • SolrInputDocument::getFieldCount »
  • PHP Manual
  • SolrInputDocument
  • Retrieves the boost value for a particular field

SolrInputDocument::getFieldBoost

(PECL solr >= 0.9.2)

SolrInputDocument::getFieldBoost — Retrieves the boost value for a particular field

Description

public SolrInputDocument::getFieldBoost ( string $fieldName ) : float

Retrieves the boost value for a particular field.

Parameters

fieldName

The name of the field.

Return Values

Returns the boost value for the field or FALSE if there was an error.


Returns the number of fields in the document

  • « SolrInputDocument::getFieldBoost
  • SolrInputDocument::getFieldNames »
  • PHP Manual
  • SolrInputDocument
  • Returns the number of fields in the document

SolrInputDocument::getFieldCount

(PECL solr >= 0.9.2)

SolrInputDocument::getFieldCount — Returns the number of fields in the document

Description

public SolrInputDocument::getFieldCount ( void ) : int

Returns the number of fields in the document.

Parameters

This function has no parameters.

Return Values

Returns an integer on success or FALSE on failure.


Returns an array containing all the fields in the document

  • « SolrInputDocument::getFieldCount
  • SolrInputDocument::hasChildDocuments »
  • PHP Manual
  • SolrInputDocument
  • Returns an array containing all the fields in the document

SolrInputDocument::getFieldNames

(PECL solr >= 0.9.2)

SolrInputDocument::getFieldNames — Returns an array containing all the fields in the document

Description

public SolrInputDocument::getFieldNames ( void ) : array

Returns an array containing all the fields in the document.

Parameters

This function has no parameters.

Return Values

Returns an array on success and FALSE on failure.


Returns true if the document has any child documents

  • « SolrInputDocument::getFieldNames
  • SolrInputDocument::merge »
  • PHP Manual
  • SolrInputDocument
  • Returns true if the document has any child documents

SolrInputDocument::hasChildDocuments

(PECL solr >= 2.3.0)

SolrInputDocument::hasChildDocuments — Returns true if the document has any child documents

Description

public SolrInputDocument::hasChildDocuments ( void ) : bool

Checks whether the document has any child documents

Parameters

This function has no parameters.

Return Values

See Also

  • SolrInputDocument::addChildDocument() - Adds a child document for block indexing
  • SolrInputDocument::addChildDocuments() - Adds an array of child documents
  • SolrInputDocument::getChildDocuments() - Returns an array of child documents (SolrInputDocument)
  • SolrInputDocument::getChildDocumentsCount() - Returns the number of child documents


Merges one input document into another

  • « SolrInputDocument::hasChildDocuments
  • SolrInputDocument::reset »
  • PHP Manual
  • SolrInputDocument
  • Merges one input document into another

SolrInputDocument::merge

(PECL solr >= 0.9.2)

SolrInputDocument::merge — Merges one input document into another

Description

public SolrInputDocument::merge ( SolrInputDocument $sourceDoc [, bool $overwrite = TRUE ] ) : bool

Merges one input document into another.

Parameters

sourceDoc

The source document.

overwrite

If this is TRUE it will replace matching fields in the destination document.

Return Values

Returns TRUE on success or FALSE on failure. In the future, this will be modified to return the number of fields in the new document.


This is an alias of SolrInputDocument::clear

  • « SolrInputDocument::merge
  • SolrInputDocument::setBoost »
  • PHP Manual
  • SolrInputDocument
  • This is an alias of SolrInputDocument::clear

SolrInputDocument::reset

(PECL solr >= 0.9.2)

SolrInputDocument::reset — This is an alias of SolrInputDocument::clear

Description

public SolrInputDocument::reset ( void ) : bool

This is an alias of SolrInputDocument::clear

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.


Sets the boost value for this document

  • « SolrInputDocument::reset
  • SolrInputDocument::setFieldBoost »
  • PHP Manual
  • SolrInputDocument
  • Sets the boost value for this document

SolrInputDocument::setBoost

(PECL solr >= 0.9.2)

SolrInputDocument::setBoost — Sets the boost value for this document

Description

public SolrInputDocument::setBoost ( float $documentBoostValue ) : bool

Sets the boost value for this document.

Parameters

documentBoostValue

The index-time boost value for this document.

Return Values

Returns TRUE on success or FALSE on failure.


Sets the index-time boost value for a field

  • « SolrInputDocument::setBoost
  • SolrInputDocument::sort »
  • PHP Manual
  • SolrInputDocument
  • Sets the index-time boost value for a field

SolrInputDocument::setFieldBoost

(PECL solr >= 0.9.2)

SolrInputDocument::setFieldBoost — Sets the index-time boost value for a field

Description

public SolrInputDocument::setFieldBoost ( string $fieldName , float $fieldBoostValue ) : bool

Sets the index-time boost value for a field. This replaces the current boost value for this field.

Parameters

fieldName

The name of the field.

fieldBoostValue

The index time boost value.


Sorts the fields within the document

  • « SolrInputDocument::setFieldBoost
  • SolrInputDocument::toArray »
  • PHP Manual
  • SolrInputDocument
  • Sorts the fields within the document

SolrInputDocument::sort

(PECL solr >= 0.9.2)

SolrInputDocument::sort — Sorts the fields within the document

Description

public SolrInputDocument::sort ( int $sortOrderBy [, int $sortDirection = SolrInputDocument::SORT_ASC ] ) : bool

The fields are rearranged according to the specified criteria and sort direction

   Fields can be sorted by boost values, field names and number of values.

   The $order_by parameter must be one of :

   * SolrInputDocument::SORT_FIELD_NAME
   * SolrInputDocument::SORT_FIELD_BOOST_VALUE
   * SolrInputDocument::SORT_FIELD_VALUE_COUNT

   The sort direction can be one of :

   * SolrInputDocument::SORT_DEFAULT
   * SolrInputDocument::SORT_ASC
   * SolrInputDocument::SORT_DESC

Parameters

sortOrderBy

The sort criteria

sortDirection

The sort direction

Return Values

Returns TRUE on success or FALSE on failure.


Returns an array representation of the input document

  • « SolrInputDocument::sort
  • SolrDocument »
  • PHP Manual
  • SolrInputDocument
  • Returns an array representation of the input document

SolrInputDocument::toArray

(PECL solr >= 0.9.2)

SolrInputDocument::toArray — Returns an array representation of the input document

Description

public SolrInputDocument::toArray ( void ) : array

Returns an array representation of the input document.

Parameters

This function has no parameters.

Return Values

Returns an array containing the fields. It returns FALSE on failure.


The SolrDocument class

(PECL solr >= 0.9.2)

Introduction

Represents a Solr document retrieved from a query response.

Class synopsis

final SolrDocument implements ArrayAccess , Iterator , Serializable {
/* Constants */
const integer SORT_DEFAULT = 1 ;
const integer SORT_ASC = 1 ;
const integer SORT_DESC = 2 ;
const integer SORT_FIELD_NAME = 1 ;
const integer SORT_FIELD_VALUE_COUNT = 2 ;
const integer SORT_FIELD_BOOST_VALUE = 4 ;
/* Methods */
public addField ( string $fieldName , string $fieldValue ) : bool
public clear ( void ) : bool
public __clone ( void ) : void
public __construct ( void )
public current ( void ) : SolrDocumentField
public deleteField ( string $fieldName ) : bool
public __destruct ( void ) : void
public fieldExists ( string $fieldName ) : bool
public __get ( string $fieldName ) : SolrDocumentField
public getChildDocuments ( void ) : array
public getChildDocumentsCount ( void ) : int
public getField ( string $fieldName ) : SolrDocumentField
public getFieldCount ( void ) : int
public getFieldNames ( void ) : array
public getInputDocument ( void ) : SolrInputDocument
public hasChildDocuments ( void ) : bool
public __isset ( string $fieldName ) : bool
public key ( void ) : string
public merge ( SolrDocument $sourceDoc [, bool $overwrite = TRUE ] ) : bool
public next ( void ) : void
public offsetExists ( string $fieldName ) : bool
public offsetGet ( string $fieldName ) : SolrDocumentField
public offsetSet ( string $fieldName , string $fieldValue ) : void
public offsetUnset ( string $fieldName ) : void
public reset ( void ) : bool
public rewind ( void ) : void
public serialize ( void ) : string
public __set ( string $fieldName , string $fieldValue ) : bool
public sort ( int $sortOrderBy [, int $sortDirection = SolrDocument::SORT_ASC ] ) : bool
public toArray ( void ) : array
public unserialize ( string $serialized ) : void
public __unset ( string $fieldName ) : bool
public valid ( void ) : bool
}

Predefined Constants

SolrDocument::SORT_DEFAULT

Default mode for sorting fields within the document.

SolrDocument::SORT_ASC

Sorts the fields in ascending order

SolrDocument::SORT_DESC

Sorts the fields in descending order

SolrDocument::SORT_FIELD_NAME

Sorts the fields by field name.

SolrDocument::SORT_FIELD_VALUE_COUNT

Sorts the fields by number of values in each field.

SolrDocument::SORT_FIELD_BOOST_VALUE

Sorts the fields by thier boost values.

Table of Contents

  • SolrDocument::addField — Adds a field to the document
  • SolrDocument::clear — Drops all the fields in the document
  • SolrDocument::__clone — Creates a copy of a SolrDocument object
  • SolrDocument::__construct — Constructor
  • SolrDocument::current — Retrieves the current field
  • SolrDocument::deleteField — Removes a field from the document
  • SolrDocument::__destruct — Destructor
  • SolrDocument::fieldExists — Checks if a field exists in the document
  • SolrDocument::__get — Access the field as a property
  • SolrDocument::getChildDocuments — Returns an array of child documents (SolrDocument)
  • SolrDocument::getChildDocumentsCount — Returns the number of child documents
  • SolrDocument::getField — Retrieves a field by name
  • SolrDocument::getFieldCount — Returns the number of fields in this document
  • SolrDocument::getFieldNames — Returns an array of fields names in the document
  • SolrDocument::getInputDocument — Returns a SolrInputDocument equivalent of the object
  • SolrDocument::hasChildDocuments — Checks whether the document has any child documents
  • SolrDocument::__isset — Checks if a field exists
  • SolrDocument::key — Retrieves the current key
  • SolrDocument::merge — Merges source to the current SolrDocument
  • SolrDocument::next — Moves the internal pointer to the next field
  • SolrDocument::offsetExists — Checks if a particular field exists
  • SolrDocument::offsetGet — Retrieves a field
  • SolrDocument::offsetSet — Adds a field to the document
  • SolrDocument::offsetUnset — Removes a field
  • SolrDocument::reset — This is an alias to SolrDocument::clear()
  • SolrDocument::rewind — Resets the internal pointer to the beginning
  • SolrDocument::serialize — Used for custom serialization
  • SolrDocument::__set — Adds another field to the document
  • SolrDocument::sort — Sorts the fields in the document
  • SolrDocument::toArray — Returns an array representation of the document
  • SolrDocument::unserialize — Custom serialization of SolrDocument objects
  • SolrDocument::__unset — Removes a field from the document
  • SolrDocument::valid — Checks if the current position internally is still valid


Adds a field to the document

  • « SolrDocument
  • SolrDocument::clear »
  • PHP Manual
  • SolrDocument
  • Adds a field to the document

SolrDocument::addField

(PECL solr >= 0.9.2)

SolrDocument::addField — Adds a field to the document

Description

public SolrDocument::addField ( string $fieldName , string $fieldValue ) : bool

This method adds a field to the SolrDocument instance.

Parameters

fieldName

The name of the field

fieldValue

The value of the field.

Return Values

Returns TRUE on success or FALSE on failure.


Drops all the fields in the document

  • « SolrDocument::addField
  • SolrDocument::__clone »
  • PHP Manual
  • SolrDocument
  • Drops all the fields in the document

SolrDocument::clear

(PECL solr >= 0.9.2)

SolrDocument::clear — Drops all the fields in the document

Description

public SolrDocument::clear ( void ) : bool

Resets the current object. Discards all the fields and resets the document boost to zero.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.


Creates a copy of a SolrDocument object

  • « SolrDocument::clear
  • SolrDocument::__construct »
  • PHP Manual
  • SolrDocument
  • Creates a copy of a SolrDocument object

SolrDocument::__clone

(PECL solr >= 0.9.2)

SolrDocument::__clone — Creates a copy of a SolrDocument object

Description

public SolrDocument::__clone ( void ) : void

Creates a copy of a SolrDocument object. Not to be called directly.

Parameters

This function has no parameters.

Return Values

None.


Constructor

  • « SolrDocument::__clone
  • SolrDocument::current »
  • PHP Manual
  • SolrDocument
  • Constructor

SolrDocument::__construct

(PECL solr >= 0.9.2)

SolrDocument::__construct — Constructor

Description

public SolrDocument::__construct ( void )

Constructor for SolrDocument

Parameters

This function has no parameters.

Return Values


Retrieves the current field

  • « SolrDocument::__construct
  • SolrDocument::deleteField »
  • PHP Manual
  • SolrDocument
  • Retrieves the current field

SolrDocument::current

(PECL solr >= 0.9.2)

SolrDocument::current — Retrieves the current field

Description

public SolrDocument::current ( void ) : SolrDocumentField

Retrieves the current field

Parameters

This function has no parameters.

Return Values

Returns the field


Removes a field from the document

  • « SolrDocument::current
  • SolrDocument::__destruct »
  • PHP Manual
  • SolrDocument
  • Removes a field from the document

SolrDocument::deleteField

(PECL solr >= 0.9.2)

SolrDocument::deleteField — Removes a field from the document

Description

public SolrDocument::deleteField ( string $fieldName ) : bool

Removes a field from the document.

Parameters

fieldName

Name of the field

Return Values

Returns TRUE on success or FALSE on failure.


Destructor

  • « SolrDocument::deleteField
  • SolrDocument::fieldExists »
  • PHP Manual
  • SolrDocument
  • Destructor

SolrDocument::__destruct

(PECL solr >= 0.9.2)

SolrDocument::__destruct — Destructor

Description

public SolrDocument::__destruct ( void ) : void

Destructor for SolrDocument.

Parameters

This function has no parameters.

Return Values


Checks if a field exists in the document

  • « SolrDocument::__destruct
  • SolrDocument::__get »
  • PHP Manual
  • SolrDocument
  • Checks if a field exists in the document

SolrDocument::fieldExists

(PECL solr >= 0.9.2)

SolrDocument::fieldExists — Checks if a field exists in the document

Description

public SolrDocument::fieldExists ( string $fieldName ) : bool

Checks if the requested field as a valid fieldname in the document.

Parameters

fieldName

The name of the field.

Return Values

Returns TRUE if the field is present and FALSE if it does not.


Access the field as a property

  • « SolrDocument::fieldExists
  • SolrDocument::getChildDocuments »
  • PHP Manual
  • SolrDocument
  • Access the field as a property

SolrDocument::__get

(PECL solr >= 0.9.2)

SolrDocument::__get — Access the field as a property

Description

public SolrDocument::__get ( string $fieldName ) : SolrDocumentField

Magic method for accessing the field as a property.

Parameters

fieldName

The name of the field.

Return Values

Returns a SolrDocumentField instance.


Returns an array of child documents (SolrDocument)

  • « SolrDocument::__get
  • SolrDocument::getChildDocumentsCount »
  • PHP Manual
  • SolrDocument
  • Returns an array of child documents (SolrDocument)

SolrDocument::getChildDocuments

(PECL solr >= 2.3.0)

SolrDocument::getChildDocuments — Returns an array of child documents (SolrDocument)

Description

public SolrDocument::getChildDocuments ( void ) : array

Returns an array of child documents (SolrDocument)

Parameters

This function has no parameters.

Return Values

See Also

  • SolrDocument::hasChildDocuments() - Checks whether the document has any child documents
  • SolrDocument::getChildDocumentsCount() - Returns the number of child documents


Returns the number of child documents

  • « SolrDocument::getChildDocuments
  • SolrDocument::getField »
  • PHP Manual
  • SolrDocument
  • Returns the number of child documents

SolrDocument::getChildDocumentsCount

(PECL solr >= 2.3.0)

SolrDocument::getChildDocumentsCount — Returns the number of child documents

Description

public SolrDocument::getChildDocumentsCount ( void ) : int

Returns the number of child documents

Parameters

This function has no parameters.

Return Values

See Also

  • SolrDocument::hasChildDocuments() - Checks whether the document has any child documents
  • SolrDocument::getChildDocuments() - Returns an array of child documents (SolrDocument)


Retrieves a field by name

  • « SolrDocument::getChildDocumentsCount
  • SolrDocument::getFieldCount »
  • PHP Manual
  • SolrDocument
  • Retrieves a field by name

SolrDocument::getField

(PECL solr >= 0.9.2)

SolrDocument::getField — Retrieves a field by name

Description

public SolrDocument::getField ( string $fieldName ) : SolrDocumentField

Retrieves a field by name.

Parameters

fieldName

Name of the field.

Return Values

Returns a SolrDocumentField on success and FALSE on failure.


Returns the number of fields in this document

  • « SolrDocument::getField
  • SolrDocument::getFieldNames »
  • PHP Manual
  • SolrDocument
  • Returns the number of fields in this document

SolrDocument::getFieldCount

(PECL solr >= 0.9.2)

SolrDocument::getFieldCount — Returns the number of fields in this document

Description

public SolrDocument::getFieldCount ( void ) : int

Returns the number of fields in this document. Multi-value fields are only counted once.

Parameters

This function has no parameters.

Return Values

Returns an integer on success and FALSE on failure.


Returns an array of fields names in the document

  • « SolrDocument::getFieldCount
  • SolrDocument::getInputDocument »
  • PHP Manual
  • SolrDocument
  • Returns an array of fields names in the document

SolrDocument::getFieldNames

(PECL solr >= 0.9.2)

SolrDocument::getFieldNames — Returns an array of fields names in the document

Description

public SolrDocument::getFieldNames ( void ) : array

Returns an array of fields names in the document.

Parameters

This function has no parameters.

Return Values

Returns an array containing the names of the fields in this document.


Returns a SolrInputDocument equivalent of the object

  • « SolrDocument::getFieldNames
  • SolrDocument::hasChildDocuments »
  • PHP Manual
  • SolrDocument
  • Returns a SolrInputDocument equivalent of the object

SolrDocument::getInputDocument

(PECL solr >= 0.9.2)

SolrDocument::getInputDocument — Returns a SolrInputDocument equivalent of the object

Description

public SolrDocument::getInputDocument ( void ) : SolrInputDocument

Returns a SolrInputDocument equivalent of the object. This is useful if one wishes to resubmit/update a document retrieved from a query.

Parameters

This function has no parameters.

Return Values

Returns a SolrInputDocument on success and NULL on failure.


Checks whether the document has any child documents

  • « SolrDocument::getInputDocument
  • SolrDocument::__isset »
  • PHP Manual
  • SolrDocument
  • Checks whether the document has any child documents

SolrDocument::hasChildDocuments

(PECL solr >= 2.3.0)

SolrDocument::hasChildDocuments — Checks whether the document has any child documents

Description

public SolrDocument::hasChildDocuments ( void ) : bool

Checks whether the document has any child documents

Parameters

This function has no parameters.

Return Values

See Also

  • SolrDocument::getChildDocuments() - Returns an array of child documents (SolrDocument)
  • SolrDocument::getChildDocumentsCount() - Returns the number of child documents


Checks if a field exists

  • « SolrDocument::hasChildDocuments
  • SolrDocument::key »
  • PHP Manual
  • SolrDocument
  • Checks if a field exists

SolrDocument::__isset

(PECL solr >= 0.9.2)

SolrDocument::__isset — Checks if a field exists

Description

public SolrDocument::__isset ( string $fieldName ) : bool

Checks if a field exists

Parameters

fieldName

Name of the field.

Return Values

Returns TRUE on success or FALSE on failure.


Retrieves the current key

  • « SolrDocument::__isset
  • SolrDocument::merge »
  • PHP Manual
  • SolrDocument
  • Retrieves the current key

SolrDocument::key

(PECL solr >= 0.9.2)

SolrDocument::key — Retrieves the current key

Description

public SolrDocument::key ( void ) : string

Retrieves the current key.

Parameters

This function has no parameters.

Return Values

Returns the current key.


Merges source to the current SolrDocument

  • « SolrDocument::key
  • SolrDocument::next »
  • PHP Manual
  • SolrDocument
  • Merges source to the current SolrDocument

SolrDocument::merge

(PECL solr >= 0.9.2)

SolrDocument::merge — Merges source to the current SolrDocument

Description

public SolrDocument::merge ( SolrDocument $sourceDoc [, bool $overwrite = TRUE ] ) : bool

Merges source to the current SolrDocument.

Parameters

sourceDoc

The source document.

overwrite

If this is TRUE then fields with the same name in the destination document will be overwritten.

Return Values

Returns TRUE on success or FALSE on failure.


Moves the internal pointer to the next field

  • « SolrDocument::merge
  • SolrDocument::offsetExists »
  • PHP Manual
  • SolrDocument
  • Moves the internal pointer to the next field

SolrDocument::next

(PECL solr >= 0.9.2)

SolrDocument::next — Moves the internal pointer to the next field

Description

public SolrDocument::next ( void ) : void

Moves the internal pointer to the next field.

Parameters

This function has no parameters.

Return Values

This method has no return value.


Checks if a particular field exists

  • « SolrDocument::next
  • SolrDocument::offsetGet »
  • PHP Manual
  • SolrDocument
  • Checks if a particular field exists

SolrDocument::offsetExists

(PECL solr >= 0.9.2)

SolrDocument::offsetExists — Checks if a particular field exists

Description

public SolrDocument::offsetExists ( string $fieldName ) : bool

Checks if a particular field exists. This is used when the object is treated as an array.

Parameters

fieldName

The name of the field.

Return Values

Returns TRUE on success or FALSE on failure.


Retrieves a field

  • « SolrDocument::offsetExists
  • SolrDocument::offsetSet »
  • PHP Manual
  • SolrDocument
  • Retrieves a field

SolrDocument::offsetGet

(PECL solr >= 0.9.2)

SolrDocument::offsetGet — Retrieves a field

Description

public SolrDocument::offsetGet ( string $fieldName ) : SolrDocumentField

This is used to retrieve the field when the object is treated as an array.

Parameters

fieldName

The name of the field.

Return Values

Returns a SolrDocumentField object.


Adds a field to the document

  • « SolrDocument::offsetGet
  • SolrDocument::offsetUnset »
  • PHP Manual
  • SolrDocument
  • Adds a field to the document

SolrDocument::offsetSet

(PECL solr >= 0.9.2)

SolrDocument::offsetSet — Adds a field to the document

Description

public SolrDocument::offsetSet ( string $fieldName , string $fieldValue ) : void

Used when the object is treated as an array to add a field to the document.

Parameters

fieldName

The name of the field.

fieldValue

The value for this field.

Return Values

Returns TRUE on success or FALSE on failure.


Removes a field

  • « SolrDocument::offsetSet
  • SolrDocument::reset »
  • PHP Manual
  • SolrDocument
  • Removes a field

SolrDocument::offsetUnset

(PECL solr >= 0.9.2)

SolrDocument::offsetUnset — Removes a field

Description

public SolrDocument::offsetUnset ( string $fieldName ) : void

Removes a field from the document.

Parameters

fieldName

The name of the field.

Return Values

No return value.


This is an alias to SolrDocument::clear()

  • « SolrDocument::offsetUnset
  • SolrDocument::rewind »
  • PHP Manual
  • SolrDocument
  • This is an alias to SolrDocument::clear()

SolrDocument::reset

(PECL solr >= 0.9.2)

SolrDocument::reset — This is an alias to SolrDocument::clear()

Description

public SolrDocument::reset ( void ) : bool

This is an alias to SolrDocument::clear()

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.


Resets the internal pointer to the beginning

  • « SolrDocument::reset
  • SolrDocument::serialize »
  • PHP Manual
  • SolrDocument
  • Resets the internal pointer to the beginning

SolrDocument::rewind

(PECL solr >= 0.9.2)

SolrDocument::rewind — Resets the internal pointer to the beginning

Description

public SolrDocument::rewind ( void ) : void

Resets the internal pointer to the beginning.

Parameters

This function has no parameters.

Return Values

This method has no return value.


Used for custom serialization

  • « SolrDocument::rewind
  • SolrDocument::__set »
  • PHP Manual
  • SolrDocument
  • Used for custom serialization

SolrDocument::serialize

(PECL solr >= 0.9.2)

SolrDocument::serialize — Used for custom serialization

Description

public SolrDocument::serialize ( void ) : string

Used for custom serialization.

Parameters

This function has no parameters.

Return Values

Returns a string representing the serialized Solr document.


Adds another field to the document

  • « SolrDocument::serialize
  • SolrDocument::sort »
  • PHP Manual
  • SolrDocument
  • Adds another field to the document

SolrDocument::__set

(PECL solr >= 0.9.2)

SolrDocument::__set — Adds another field to the document

Description

public SolrDocument::__set ( string $fieldName , string $fieldValue ) : bool

Adds another field to the document. Used to set the fields as new properties.

Parameters

fieldName

Name of the field.

fieldValue

Field value.

Return Values

Returns TRUE on success or FALSE on failure.


Sorts the fields in the document

  • « SolrDocument::__set
  • SolrDocument::toArray »
  • PHP Manual
  • SolrDocument
  • Sorts the fields in the document

SolrDocument::sort

(PECL solr >= 0.9.2)

SolrDocument::sort — Sorts the fields in the document

Description

public SolrDocument::sort ( int $sortOrderBy [, int $sortDirection = SolrDocument::SORT_ASC ] ) : bool

The fields are rearranged according to the specified criteria and sort direction

   Fields can be sorted by boost values, field names and number of values.

   The sortOrderBy parameter must be one of :

   * SolrDocument::SORT_FIELD_NAME
   * SolrDocument::SORT_FIELD_BOOST_VALUE
   * SolrDocument::SORT_FIELD_VALUE_COUNT

   The sortDirection can be one of :

   * SolrDocument::SORT_DEFAULT
   * SolrDocument::SORT_ASC
   * SolrDocument::SORT_DESC

   The default way is to sort in ascending order.

Parameters

sortOrderBy

The sort criteria.

sortDirection

The sort direction.

Return Values

Returns TRUE on success or FALSE on failure.


Returns an array representation of the document

  • « SolrDocument::sort
  • SolrDocument::unserialize »
  • PHP Manual
  • SolrDocument
  • Returns an array representation of the document

SolrDocument::toArray

(PECL solr >= 0.9.2)

SolrDocument::toArray — Returns an array representation of the document

Description

public SolrDocument::toArray ( void ) : array

Returns an array representation of the document.

Parameters

This function has no parameters.

Return Values

Returns an array representation of the document.

Examples

Example #1 SolrDocument::toArray() example

<?php

$doc = new SolrDocument();

$doc->addField('id', 1123);

$doc->features = "PHP Client Side";
$doc->features = "Fast development cycles";

$doc['cat'] = 'Software';
$doc['cat'] = 'Custom Search';
$doc->cat   = 'Information Technology';

print_r($doc->toArray());

?>

The above example will output something similar to:

Array
(
    [document_boost] => 0
    [field_count] => 3
    [fields] => Array
        (
            [0] => SolrDocumentField Object
                (
                    [name] => id
                    [boost] => 0
                    [values] => Array
                        (
                            [0] => 1123
                        )

                )

            [1] => SolrDocumentField Object
                (
                    [name] => features
                    [boost] => 0
                    [values] => Array
                        (
                            [0] => PHP Client Side
                            [1] => Fast development cycles
                        )

                )

            [2] => SolrDocumentField Object
                (
                    [name] => cat
                    [boost] => 0
                    [values] => Array
                        (
                            [0] => Software
                            [1] => Custom Search
                            [2] => Information Technology
                        )

                )

        )

)


Custom serialization of SolrDocument objects

  • « SolrDocument::toArray
  • SolrDocument::__unset »
  • PHP Manual
  • SolrDocument
  • Custom serialization of SolrDocument objects

SolrDocument::unserialize

(PECL solr >= 0.9.2)

SolrDocument::unserialize — Custom serialization of SolrDocument objects

Description

public SolrDocument::unserialize ( string $serialized ) : void

Custom serialization of SolrDocument objects

Parameters

serialized

An XML representation of the document.

Return Values

None.


Removes a field from the document

  • « SolrDocument::unserialize
  • SolrDocument::valid »
  • PHP Manual
  • SolrDocument
  • Removes a field from the document

SolrDocument::__unset

(PECL solr >= 0.9.2)

SolrDocument::__unset — Removes a field from the document

Description

public SolrDocument::__unset ( string $fieldName ) : bool

Removes a field from the document when the field is access as an object property.

Parameters

fieldName

The name of the field.

Return Values

Returns TRUE on success or FALSE on failure.


Checks if the current position internally is still valid

  • « SolrDocument::__unset
  • SolrDocumentField »
  • PHP Manual
  • SolrDocument
  • Checks if the current position internally is still valid

SolrDocument::valid

(PECL solr >= 0.9.2)

SolrDocument::valid — Checks if the current position internally is still valid

Description

public SolrDocument::valid ( void ) : bool

Checks if the current position internally is still valid. It is used during foreach operations.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success and FALSE if the current position is no longer valid.


The SolrDocumentField class

(PECL solr >= 0.9.2)

Introduction

This represents a field in a Solr document. All its properties are read-only.

Class synopsis

final SolrDocumentField {
/* Properties */
readonly public string $name ;
readonly public float $boost ;
readonly public array $values ;
/* Methods */
public __construct ( void )
public __destruct ( void ) : void
}

Properties

name

The name of the field.

boost

The boost value for the field

values

An array of values for this field

Table of Contents

  • SolrDocumentField::__construct — Constructor
  • SolrDocumentField::__destruct — Destructor


Constructor

  • « SolrDocumentField
  • SolrDocumentField::__destruct »
  • PHP Manual
  • SolrDocumentField
  • Constructor

SolrDocumentField::__construct

(PECL solr >= 0.9.2)

SolrDocumentField::__construct — Constructor

Description

public SolrDocumentField::__construct ( void )

Constructor.

Parameters

This function has no parameters.

Return Values

None.


Destructor

  • « SolrDocumentField::__construct
  • SolrObject »
  • PHP Manual
  • SolrDocumentField
  • Destructor

SolrDocumentField::__destruct

(PECL solr >= 0.9.2)

SolrDocumentField::__destruct — Destructor

Description

public SolrDocumentField::__destruct ( void ) : void

Destructor.

Parameters

This function has no parameters.

Return Values

None.


The SolrObject class

(PECL solr >= 0.9.2)

Introduction

This is an object whose properties can also by accessed using the array syntax. All its properties are read-only.

Class synopsis

final SolrObject implements ArrayAccess {
/* Methods */
public __construct ( void )
public __destruct ( void ) : void
public getPropertyNames ( void ) : array
public offsetExists ( string $property_name ) : bool
public offsetGet ( string $property_name ) : mixed
public offsetSet ( string $property_name , string $property_value ) : void
public offsetUnset ( string $property_name ) : void
}

Table of Contents

  • SolrObject::__construct — Creates Solr object
  • SolrObject::__destruct — Destructor
  • SolrObject::getPropertyNames — Returns an array of all the names of the properties
  • SolrObject::offsetExists — Checks if the property exists
  • SolrObject::offsetGet — Used to retrieve a property
  • SolrObject::offsetSet — Sets the value for a property
  • SolrObject::offsetUnset — Unsets the value for the property


Creates Solr object

  • « SolrObject
  • SolrObject::__destruct »
  • PHP Manual
  • SolrObject
  • Creates Solr object

SolrObject::__construct

(PECL solr >= 0.9.2)

SolrObject::__construct — Creates Solr object

Description

public SolrObject::__construct ( void )

Creates Solr object.

Parameters

This function has no parameters.

Return Values

None

Examples

Example #1 SolrObject::__construct() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


Destructor

  • « SolrObject::__construct
  • SolrObject::getPropertyNames »
  • PHP Manual
  • SolrObject
  • Destructor

SolrObject::__destruct

(PECL solr >= 0.9.2)

SolrObject::__destruct — Destructor

Description

public SolrObject::__destruct ( void ) : void

The destructor

Parameters

This function has no parameters.

Return Values

None.


Returns an array of all the names of the properties

  • « SolrObject::__destruct
  • SolrObject::offsetExists »
  • PHP Manual
  • SolrObject
  • Returns an array of all the names of the properties

SolrObject::getPropertyNames

(PECL solr >= 0.9.2)

SolrObject::getPropertyNames — Returns an array of all the names of the properties

Description

public SolrObject::getPropertyNames ( void ) : array

Returns an array of all the names of the properties

Parameters

This function has no parameters.

Return Values

Returns an array.


Checks if the property exists

  • « SolrObject::getPropertyNames
  • SolrObject::offsetGet »
  • PHP Manual
  • SolrObject
  • Checks if the property exists

SolrObject::offsetExists

(PECL solr >= 0.9.2)

SolrObject::offsetExists — Checks if the property exists

Description

public SolrObject::offsetExists ( string $property_name ) : bool

Checks if the property exists. This is used when the object is treated as an array.

Parameters

property_name

The name of the property.

Return Values

Returns TRUE on success or FALSE on failure.


Used to retrieve a property

  • « SolrObject::offsetExists
  • SolrObject::offsetSet »
  • PHP Manual
  • SolrObject
  • Used to retrieve a property

SolrObject::offsetGet

(PECL solr >= 0.9.2)

SolrObject::offsetGet — Used to retrieve a property

Description

public SolrObject::offsetGet ( string $property_name ) : mixed

Used to get the value of a property. This is used when the object is treated as an array.

Parameters

property_name

Name of the property.

Return Values

Returns the property value.


Sets the value for a property

  • « SolrObject::offsetGet
  • SolrObject::offsetUnset »
  • PHP Manual
  • SolrObject
  • Sets the value for a property

SolrObject::offsetSet

(PECL solr >= 0.9.2)

SolrObject::offsetSet — Sets the value for a property

Description

public SolrObject::offsetSet ( string $property_name , string $property_value ) : void

Sets the value for a property. This is used when the object is treated as an array. This object is read-only. This should never be attempted.

Parameters

property_name

The name of the property.

property_value

The new value.

Return Values

None.


Unsets the value for the property

  • « SolrObject::offsetSet
  • SolrClient »
  • PHP Manual
  • SolrObject
  • Unsets the value for the property

SolrObject::offsetUnset

(PECL solr >= 0.9.2)

SolrObject::offsetUnset — Unsets the value for the property

Description

public SolrObject::offsetUnset ( string $property_name ) : void

Unsets the value for the property. This is used when the object is treated as an array. This object is read-only. This should never be attempted.

Parameters

property_name

The name of the property.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 SolrObject::offsetUnset() example

<?php
/* ... */
?>

The above example will output something similar to:

...

See Also

  • Classname::Method()


The SolrClient class

(PECL solr >= 0.9.2)

Introduction

Used to send requests to a Solr server. Currently, cloning and serialization of SolrClient instances is not supported.

Class synopsis

final SolrClient {
/* Constants */
const integer SEARCH_SERVLET_TYPE = 1 ;
const integer UPDATE_SERVLET_TYPE = 2 ;
const integer THREADS_SERVLET_TYPE = 4 ;
const integer PING_SERVLET_TYPE = 8 ;
const integer TERMS_SERVLET_TYPE = 16 ;
const integer SYSTEM_SERVLET_TYPE = 32 ;
const string DEFAULT_SEARCH_SERVLET = select ;
const string DEFAULT_UPDATE_SERVLET = update ;
const string DEFAULT_THREADS_SERVLET = admin/threads ;
const string DEFAULT_PING_SERVLET = admin/ping ;
const string DEFAULT_TERMS_SERVLET = terms ;
const string DEFAULT_SYSTEM_SERVLET = admin/system ;
/* Methods */
public addDocument ( SolrInputDocument $doc [, bool $overwrite = TRUE [, int $commitWithin = 0 ]] ) : SolrUpdateResponse
public addDocuments ( array $docs [, bool $overwrite = TRUE [, int $commitWithin = 0 ]] ) : void
public commit ([ bool $softCommit = FALSE [, bool $waitSearcher = TRUE [, bool $expungeDeletes = FALSE ]]] ) : SolrUpdateResponse
public __construct ( array $clientOptions )
public deleteById ( string $id ) : SolrUpdateResponse
public deleteByIds ( array $ids ) : SolrUpdateResponse
public deleteByQueries ( array $queries ) : SolrUpdateResponse
public deleteByQuery ( string $query ) : SolrUpdateResponse
public __destruct ( void ) : void
public getById ( string $id ) : SolrQueryResponse
public getByIds ( array $ids ) : SolrQueryResponse
public getDebug ( void ) : string
public getOptions ( void ) : array
public optimize ([ int $maxSegments = 1 [, bool $softCommit = TRUE [, bool $waitSearcher = TRUE ]]] ) : SolrUpdateResponse
public ping ( void ) : SolrPingResponse
public query ( SolrParams $query ) : SolrQueryResponse
public request ( string $raw_request ) : SolrUpdateResponse
public rollback ( void ) : SolrUpdateResponse
public setResponseWriter ( string $responseWriter ) : void
public setServlet ( int $type , string $value ) : bool
public system ( void ) : void
public threads ( void ) : void
}

Predefined Constants

SolrClient::SEARCH_SERVLET_TYPE

Used when updating the search servlet.

SolrClient::UPDATE_SERVLET_TYPE

Used when updating the update servlet.

SolrClient::THREADS_SERVLET_TYPE

Used when updating the threads servlet.

SolrClient::PING_SERVLET_TYPE

Used when updating the ping servlet.

SolrClient::TERMS_SERVLET_TYPE

Used when updating the terms servlet.

SolrClient::SYSTEM_SERVLET_TYPE

Used when retrieving system information from the system servlet.

SolrClient::DEFAULT_SEARCH_SERVLET

This is the initial value for the search servlet.

SolrClient::DEFAULT_UPDATE_SERVLET

This is the initial value for the update servlet.

SolrClient::DEFAULT_THREADS_SERVLET

This is the initial value for the threads servlet.

SolrClient::DEFAULT_PING_SERVLET

This is the initial value for the ping servlet.

SolrClient::DEFAULT_TERMS_SERVLET

This is the initial value for the terms servlet used for the TermsComponent

SolrClient::DEFAULT_SYSTEM_SERVLET

This is the initial value for the system servlet used to obtain Solr Server information

Table of Contents

  • SolrClient::addDocument — Adds a document to the index
  • SolrClient::addDocuments — Adds a collection of SolrInputDocument instances to the index
  • SolrClient::commit — Finalizes all add/deletes made to the index
  • SolrClient::__construct — Constructor for the SolrClient object
  • SolrClient::deleteById — Delete by Id
  • SolrClient::deleteByIds — Deletes by Ids
  • SolrClient::deleteByQueries — Removes all documents matching any of the queries
  • SolrClient::deleteByQuery — Deletes all documents matching the given query
  • SolrClient::__destruct — Destructor for SolrClient
  • SolrClient::getById — Get Document By Id. Utilizes Solr Realtime Get (RTG)
  • SolrClient::getByIds — Get Documents by their Ids. Utilizes Solr Realtime Get (RTG)
  • SolrClient::getDebug — Returns the debug data for the last connection attempt
  • SolrClient::getOptions — Returns the client options set internally
  • SolrClient::optimize — Defragments the index
  • SolrClient::ping — Checks if Solr server is still up
  • SolrClient::query — Sends a query to the server
  • SolrClient::request — Sends a raw update request
  • SolrClient::rollback — Rollbacks all add/deletes made to the index since the last commit
  • SolrClient::setResponseWriter — Sets the response writer used to prepare the response from Solr
  • SolrClient::setServlet — Changes the specified servlet type to a new value
  • SolrClient::system — Retrieve Solr Server information
  • SolrClient::threads — Checks the threads status


Adds a document to the index

  • « SolrClient
  • SolrClient::addDocuments »
  • PHP Manual
  • SolrClient
  • Adds a document to the index

SolrClient::addDocument

(PECL solr >= 0.9.2)

SolrClient::addDocument — Adds a document to the index

Description

public SolrClient::addDocument ( SolrInputDocument $doc [, bool $overwrite = TRUE [, int $commitWithin = 0 ]] ) : SolrUpdateResponse

This method adds a document to the index.

Parameters

doc

The SolrInputDocument instance.

overwrite

Whether to overwrite existing document or not. If FALSE there will be duplicates (several documents with the same ID).

Warning

PECL Solr < 2.0 $allowDups was used instead of $overwrite, which does the same functionality with exact opposite bool flag.

$allowDups = false is the same as $overwrite = true

commitWithin

Number of milliseconds within which to auto commit this document. Available since Solr 1.4 . Default (0) means disabled.

When this value specified, it leaves the control of when to do the commit to Solr itself, optimizing number of commits to a minimum while still fulfilling the update latency requirements, and Solr will automatically do a commit when the oldest add in the buffer is due.

Return Values

Returns a SolrUpdateResponse object or throws an Exception on failure.

Errors/Exceptions

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

Examples

Example #1 SolrClient::addDocument() example

<?php

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$doc = new SolrInputDocument();

$doc->addField('id', 334455);
$doc->addField('cat', 'Software');
$doc->addField('cat', 'Lucene');

$updateResponse = $client->addDocument($doc);

// you will have to commit changes to be written if you didn't use $commitWithin
$client->commit();

print_r($updateResponse->getResponse());

?>

The above example will output something similar to:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 1
        )

)

Example #2 SolrClient::addDocument() example 2

<?php

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$doc = new SolrInputDocument();

$doc->addField('id', 334455);
$doc->addField('cat', 'Software');
$doc->addField('cat', 'Lucene');

// No need to call commit() because $commitWithin is passed, so Solr Server will auto commit within 10 seconds
$updateResponse = $client->addDocument($doc, false, 10000);

print_r($updateResponse->getResponse());

?>

The above example will output something similar to:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 1
        )

)

See Also

  • SolrClient::addDocuments() - Adds a collection of SolrInputDocument instances to the index
  • SolrClient::commit() - Finalizes all add/deletes made to the index


Adds a collection of SolrInputDocument instances to the index

  • « SolrClient::addDocument
  • SolrClient::commit »
  • PHP Manual
  • SolrClient
  • Adds a collection of SolrInputDocument instances to the index

SolrClient::addDocuments

(PECL solr >= 0.9.2)

SolrClient::addDocuments — Adds a collection of SolrInputDocument instances to the index

Description

public SolrClient::addDocuments ( array $docs [, bool $overwrite = TRUE [, int $commitWithin = 0 ]] ) : void

Adds a collection of documents to the index.

Parameters

docs

An array containing the collection of SolrInputDocument instances. This array must be an actual variable.

overwrite

Whether to overwrite existing documents or not. If FALSE there will be duplicates (several documents with the same ID).

Warning

PECL Solr < 2.0 $allowDups was used instead of $overwrite, which does the same functionality with exact opposite bool flag.

$allowDups = false is the same as $overwrite = true

commitWithin

Number of milliseconds within which to auto commit this document. Available since Solr 1.4 . Default (0) means disabled.

When this value specified, it leaves the control of when to do the commit to Solr itself, optimizing number of commits to a minimum while still fulfilling the update latency requirements, and Solr will automatically do a commit when the oldest add in the buffer is due.

Return Values

Returns a SolrUpdateResponse object or throws an exception on failure.

Errors/Exceptions

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

Examples

Example #1 SolrClient::addDocuments() example

<?php

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$doc = new SolrInputDocument();

$doc->addField('id', 334455);
$doc->addField('cat', 'Software');
$doc->addField('cat', 'Lucene');

$doc2 = clone $doc;

$doc2->deleteField('id');
$doc2->addField('id', 334456);

$docs = array($doc, $doc2);

$updateResponse = $client->addDocuments($docs);

// no changes will be written to disk unless $commitWithin is passed or SolrClient::commit is called

print_r($updateResponse->getResponse());

?>

The above example will output something similar to:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 2
        )

)

See Also

  • SolrClient::addDocument() - Adds a document to the index
  • SolrClient::commit() - Finalizes all add/deletes made to the index


Finalizes all add/deletes made to the index

  • « SolrClient::addDocuments
  • SolrClient::__construct »
  • PHP Manual
  • SolrClient
  • Finalizes all add/deletes made to the index

SolrClient::commit

(PECL solr >= 0.9.2)

SolrClient::commit — Finalizes all add/deletes made to the index

Description

public SolrClient::commit ([ bool $softCommit = FALSE [, bool $waitSearcher = TRUE [, bool $expungeDeletes = FALSE ]]] ) : SolrUpdateResponse

This method finalizes all add/deletes made to the index.

Parameters

softCommit

This will refresh the 'view' of the index in a more performant manner, but without "on-disk" guarantees. (Solr4.0+)

A soft commit is much faster since it only makes index changes visible and does not fsync index files or write a new index descriptor. If the JVM crashes or there is a loss of power, changes that occurred after the last hard commit will be lost. Search collections that have near-real-time requirements (that want index changes to be quickly visible to searches) will want to soft commit often but hard commit less frequently.

waitSearcher

block until a new searcher is opened and registered as the main query searcher, making the changes visible.

expungeDeletes

Merge segments with deletes away. (Solr1.4+)

Return Values

Returns a SolrUpdateResponse object on success or throws an exception on failure.

Errors/Exceptions

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

Changelog

Version | Description
1.1.0, 2.0.0 | $maxSegments removed
2.0.0b | API Changed: SolrClient::commit ([ int $maxSegments = 0 [, bool $softCommit = false [, bool $waitSearcher = true[, bool $expungeDeletes = false ]]] )
0.9.2 | Signature: SolrClient::commit ([ int $maxSegments = 1 [, bool $waitFlush = true [, bool $waitSearcher = true ]]] ). $waitFlush: Block until index changes are flushed to disk.

Notes

Warning

PECL Solr >= 2.0 only supports Solr Server >= 4.0

See Also

  • SolrClient::optimize() - Defragments the index
  • SolrClient::rollback() - Rollbacks all add/deletes made to the index since the last commit


Constructor for the SolrClient object

  • « SolrClient::commit
  • SolrClient::deleteById »
  • PHP Manual
  • SolrClient
  • Constructor for the SolrClient object

SolrClient::__construct

(PECL solr >= 0.9.2)

SolrClient::__construct — Constructor for the SolrClient object

Description

public SolrClient::__construct ( array $clientOptions )

Constructor for the SolrClient object

Parameters

clientOptions

This is an array containing one of the following keys :

- secure          (Boolean value indicating whether or not to connect in secure mode)
 - hostname        (The hostname for the Solr server)
 - port            (The port number)
 - path            (The path to solr)
 - wt              (The name of the response writer e.g. xml, json)
 - login           (The username used for HTTP Authentication, if any)
 - password        (The HTTP Authentication password)
 - proxy_host      (The hostname for the proxy server, if any)
 - proxy_port      (The proxy port)
 - proxy_login     (The proxy username)
 - proxy_password  (The proxy password)
 - timeout         (This is maximum time in seconds allowed for the http data transfer operation. Default is 30 seconds)
 - ssl_cert        (File name to a PEM-formatted file containing the private key + private certificate (concatenated in that order) )
 - ssl_key         (File name to a PEM-formatted private key file only)
 - ssl_keypassword (Password for private key)
 - ssl_cainfo      (Name of file holding one or more CA certificates to verify peer with)
 - ssl_capath      (Name of directory holding multiple CA certificates to verify peer with )

 Please note the if the ssl_cert file only contains the private certificate, you have to specify a separate ssl_key file

 The ssl_keypassword option is required if the ssl_cert or ssl_key options are set.

Errors/Exceptions

Throws SolrIllegalArgumentException on failure.

Examples

Example #1 SolrClient::__construct() example

<?php

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
    'path'     => SOLR_PATH_TO_SOLR,
    'wt'       => 'xml',
);

$client = new SolrClient($options);

$doc = new SolrInputDocument();

$doc->addField('id', 334455);
$doc->addField('cat', 'Software');
$doc->addField('cat', 'Lucene');

$updateResponse = $client->addDocument($doc);

?>

The above example will output something similar to:

See Also

  • SolrClient::getOptions() - Returns the client options set internally


Delete by Id

  • « SolrClient::__construct
  • SolrClient::deleteByIds »
  • PHP Manual
  • SolrClient
  • Delete by Id

SolrClient::deleteById

(PECL solr >= 0.9.2)

SolrClient::deleteById — Delete by Id

Description

public SolrClient::deleteById ( string $id ) : SolrUpdateResponse

Deletes the document with the specified ID. Where ID is the value of the uniqueKey field declared in the schema

Parameters

id

The value of the uniqueKey field declared in the schema

Return Values

Returns a SolrUpdateResponse on success and throws an exception on failure.

Errors/Exceptions

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

See Also

  • SolrClient::deleteByIds() - Deletes by Ids
  • SolrClient::deleteByQuery() - Deletes all documents matching the given query
  • SolrClient::deleteByQueries() - Removes all documents matching any of the queries


Deletes by Ids

  • « SolrClient::deleteById
  • SolrClient::deleteByQueries »
  • PHP Manual
  • SolrClient
  • Deletes by Ids

SolrClient::deleteByIds

(PECL solr >= 0.9.2)

SolrClient::deleteByIds — Deletes by Ids

Description

public SolrClient::deleteByIds ( array $ids ) : SolrUpdateResponse

Deletes a collection of documents with the specified set of ids.

Parameters

ids

An array of IDs representing the uniqueKey field declared in the schema for each document to be deleted. This must be an actual php variable.

Return Values

Returns a SolrUpdateResponse on success and throws an exception on failure.

Errors/Exceptions

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

See Also

  • SolrClient::deleteById() - Delete by Id
  • SolrClient::deleteByQuery() - Deletes all documents matching the given query
  • SolrClient::deleteByQueries() - Removes all documents matching any of the queries


Removes all documents matching any of the queries

  • « SolrClient::deleteByIds
  • SolrClient::deleteByQuery »
  • PHP Manual
  • SolrClient
  • Removes all documents matching any of the queries

SolrClient::deleteByQueries

(PECL solr >= 0.9.2)

SolrClient::deleteByQueries — Removes all documents matching any of the queries

Description

public SolrClient::deleteByQueries ( array $queries ) : SolrUpdateResponse

Removes all documents matching any of the queries

Parameters

queries

The array of queries. This must be an actual php variable.

Return Values

Returns a SolrUpdateResponse on success and throws a SolrClientException on failure.

Errors/Exceptions

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

See Also

  • SolrClient::deleteById() - Delete by Id
  • SolrClient::deleteByIds() - Deletes by Ids
  • SolrClient::deleteByQuery() - Deletes all documents matching the given query


Deletes all documents matching the given query

  • « SolrClient::deleteByQueries
  • SolrClient::__destruct »
  • PHP Manual
  • SolrClient
  • Deletes all documents matching the given query

SolrClient::deleteByQuery

(PECL solr >= 0.9.2)

SolrClient::deleteByQuery — Deletes all documents matching the given query

Description

public SolrClient::deleteByQuery ( string $query ) : SolrUpdateResponse

Deletes all documents matching the given query.

Parameters

query

The query

Return Values

Returns a SolrUpdateResponse on success and throws an exception on failure.

Errors/Exceptions

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

Examples

Example #1 SolrQuery::deleteByQuery() example

<?php

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

//This will erase the entire index
$client->deleteByQuery("*:*");
$client->commit();

?>

See Also

  • SolrClient::deleteById() - Delete by Id
  • SolrClient::deleteByIds() - Deletes by Ids
  • SolrClient::deleteByQueries() - Removes all documents matching any of the queries


Destructor for SolrClient

  • « SolrClient::deleteByQuery
  • SolrClient::getById »
  • PHP Manual
  • SolrClient
  • Destructor for SolrClient

SolrClient::__destruct

(PECL solr >= 0.9.2)

SolrClient::__destruct — Destructor for SolrClient

Description

public SolrClient::__destruct ( void ) : void

Destructor

Parameters

This function has no parameters.

Return Values

Destructor for SolrClient

See Also

  • SolrClient::__construct() - Constructor for the SolrClient object


Get Document By Id. Utilizes Solr Realtime Get (RTG)

  • « SolrClient::__destruct
  • SolrClient::getByIds »
  • PHP Manual
  • SolrClient
  • Get Document By Id. Utilizes Solr Realtime Get (RTG)

SolrClient::getById

(PECL solr >= 2.2.0)

SolrClient::getById — Get Document By Id. Utilizes Solr Realtime Get (RTG)

Description

public SolrClient::getById ( string $id ) : SolrQueryResponse

Get Document By Id. Utilizes Solr Realtime Get (RTG).

Parameters

id

Document ID

Return Values

SolrQueryResponse

Examples

Example #1 SolrClient::getById() example

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
    'path'     => SOLR_SERVER_PATH
);

$client = new SolrClient($options);
$response = $client->getById('GB18030TEST');
print_r($response->getResponse());

?>

The above example will output something similar to:

SolrObject Object
(
    [doc] => SolrObject Object
        (
            [id] => GB18030TEST
            [name] => Array
                (
                    [0] => Test with some GB18030 encoded characters
                )

            [features] => Array
                (
                    [0] => No accents here
                    [1] => 这是一个功能
                    [2] => This is a feature (translated)
                    [3] => 这份文件是很有光泽
                    [4] => This document is very shiny (translated)
                )

            [price] => Array
                (
                    [0] => 0
                )

            [inStock] => Array
                (
                    [0] => 1
                )

            [_version_] => 1510294336239042560
        )

)

See Also

  • SolrClient::getByIds() - Get Documents by their Ids. Utilizes Solr Realtime Get (RTG)


Get Documents by their Ids. Utilizes Solr Realtime Get (RTG)

  • « SolrClient::getById
  • SolrClient::getDebug »
  • PHP Manual
  • SolrClient
  • Get Documents by their Ids. Utilizes Solr Realtime Get (RTG)

SolrClient::getByIds

(PECL solr >= 2.2.0)

SolrClient::getByIds — Get Documents by their Ids. Utilizes Solr Realtime Get (RTG)

Description

public SolrClient::getByIds ( array $ids ) : SolrQueryResponse

Get Documents by their Ids. Utilizes Solr Realtime Get (RTG).

Parameters

ids

Document ids

Return Values

SolrQueryResponse

Examples

Example #1 SolrClient::getByIds() example

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
    'path'     => SOLR_SERVER_PATH
);

$client = new SolrClient($options);
$response = $client->getByIds(['GB18030TEST', '6H500F0']);

print_r($response->getResponse());

?>

The above example will output something similar to:

SolrObject Object
(
    [response] => SolrObject Object
        (
            [numFound] => 2
            [start] => 0
            [docs] => Array
                (
                    [0] => SolrObject Object
                        (
                            [id] => GB18030TEST
                            [name] => Array
                                (
                                    [0] => Test with some GB18030 encoded characters
                                )

                            [features] => Array
                                (
                                    [0] => No accents here
                                    [1] => 这是一个功能
                                    [2] => This is a feature (translated)
                                    [3] => 这份文件是很有光泽
                                    [4] => This document is very shiny (translated)
                                )

                            [price] => Array
                                (
                                    [0] => 0
                                )

                            [inStock] => Array
                                (
                                    [0] => 1
                                )

                            [_version_] => 1510294336239042560
                        )

                    [1] => SolrObject Object
                        (
                            [id] => 6H500F0
                            [name] => Array
                                (
                                    [0] => Maxtor DiamondMax 11 - hard drive - 500 GB - SATA-300
                                )

                            [manu] => Array
                                (
                                    [0] => Maxtor Corp.
                                )

                            [manu_id_s] => maxtor
                            [cat] => Array
                                (
                                    [0] => electronics
                                    [1] => hard drive
                                )

                            [features] => Array
                                (
                                    [0] => SATA 3.0Gb/s, NCQ
                                    [1] => 8.5ms seek
                                    [2] => 16MB cache
                                )

                            [price] => Array
                                (
                                    [0] => 350
                                )

                            [popularity] => Array
                                (
                                    [0] => 6
                                )

                            [inStock] => Array
                                (
                                    [0] => 1
                                )

                            [store] => Array
                                (
                                    [0] => 45.17614,-93.87341
                                )

                            [manufacturedate_dt] => 2006-02-13T15:26:37Z
                            [_version_] => 1510294336449806336
                        )

                )

        )

)

See Also

  • SolrClient::getById() - Get Document By Id. Utilizes Solr Realtime Get (RTG)


Returns the debug data for the last connection attempt

  • « SolrClient::getByIds
  • SolrClient::getOptions »
  • PHP Manual
  • SolrClient
  • Returns the debug data for the last connection attempt

SolrClient::getDebug

(PECL solr >= 0.9.7)

SolrClient::getDebug — Returns the debug data for the last connection attempt

Description

public SolrClient::getDebug ( void ) : string

Returns the debug data for the last connection attempt

Parameters

This function has no parameters.

Return Values

Returns a string on success and null if there is nothing to return.


Returns the client options set internally

  • « SolrClient::getDebug
  • SolrClient::optimize »
  • PHP Manual
  • SolrClient
  • Returns the client options set internally

SolrClient::getOptions

(PECL solr >= 0.9.6)

SolrClient::getOptions — Returns the client options set internally

Description

public SolrClient::getOptions ( void ) : array

Returns the client options set internally. Very useful for debugging. The values returned are readonly and can only be set when the object is instantiated.

Parameters

This function has no parameters.

Return Values

Returns an array containing all the options for the SolrClient object set internally.

See Also

  • SolrClient::__construct() - Constructor for the SolrClient object


Defragments the index

  • « SolrClient::getOptions
  • SolrClient::ping »
  • PHP Manual
  • SolrClient
  • Defragments the index

SolrClient::optimize

(PECL solr >= 0.9.2)

SolrClient::optimize — Defragments the index

Description

public SolrClient::optimize ([ int $maxSegments = 1 [, bool $softCommit = TRUE [, bool $waitSearcher = TRUE ]]] ) : SolrUpdateResponse

Defragments the index for faster search performance.

Parameters

maxSegments

Optimizes down to at most this number of segments. Since Solr 1.3

softCommit

This will refresh the 'view' of the index in a more performant manner, but without "on-disk" guarantees. (Solr4.0+)

waitSearcher

Block until a new searcher is opened and registered as the main query searcher, making the changes visible.

Return Values

Returns a SolrUpdateResponse on success or throws an exception on failure.

Errors/Exceptions

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

Notes

Warning

PECL Solr >= 2.0 only supports Solr Server >= 4.0

Prior to PECL Solr 2.0 this method used to accept these arguments "int $maxSegments, bool $waitFlush, bool $waitSearcher".

See Also

  • SolrClient::commit() - Finalizes all add/deletes made to the index
  • SolrClient::rollback() - Rollbacks all add/deletes made to the index since the last commit


Checks if Solr server is still up

  • « SolrClient::optimize
  • SolrClient::query »
  • PHP Manual
  • SolrClient
  • Checks if Solr server is still up

SolrClient::ping

(PECL solr >= 0.9.2)

SolrClient::ping — Checks if Solr server is still up

Description

public SolrClient::ping ( void ) : SolrPingResponse

Checks if the Solr server is still alive. Sends a HEAD request to the Apache Solr server.

Parameters

This function has no parameters.

Return Values

Returns a SolrPingResponse object on success and throws an exception on failure.

Errors/Exceptions

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to satisfy the request.

Examples

Example #1 SolrClient::ping() example

<?php
$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$pingresponse = $client->ping();

?>

The above example will output something similar to:


Sends a query to the server

  • « SolrClient::ping
  • SolrClient::request »
  • PHP Manual
  • SolrClient
  • Sends a query to the server

SolrClient::query

(PECL solr >= 0.9.2)

SolrClient::query — Sends a query to the server

Description

public SolrClient::query ( SolrParams $query ) : SolrQueryResponse

Sends a query to the server.

Parameters

query

A SolrParams object. It is recommended to use SolrQuery for advanced queries.

Return Values

Returns a SolrQueryResponse object on success and throws an exception on failure.

Errors/Exceptions

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to satisfy the query.

Examples

Example #1 SolrClient::query() example

<?php

$options = array
(
    'hostname' => 'localhost',
    'login'    => 'username',
    'password' => 'password',
    'port'     => '8983',
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setQuery('lucene');

$query->setStart(0);

$query->setRows(50);

$query->addField('cat')->addField('features')->addField('id')->addField('timestamp');

$query_response = $client->query($query);

$response = $query_response->getResponse();

print_r($response);

?>

The above example will output something similar to:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 3
            [params] => SolrObject Object
                (
                    [fl] => cat,features,id,timestamp
                    [indent] => on
                    [start] => 0
                    [q] => lucene
                    [wt] => xml
                    [version] => 2.2
                    [rows] => 50
                )

        )

    [response] => SolrObject Object
        (
            [numFound] => 1
            [start] => 0
            [docs] => Array
                (
                    [0] => SolrObject Object
                        (
                            [id] => SOLR1000
                            [cat] => Array
                                (
                                    [0] => software
                                    [1] => search
                                )

                            [features] => Array
                                (
                                    [0] => Advanced Full-Text Search Capabilities using Lucene
                                    [1] => Optimized for High Volume Web Traffic
                                    [2] => Standards Based Open Interfaces - XML and HTTP
                                    [3] => Comprehensive HTML Administration Interfaces
                                    [4] => Scalability - Efficient Replication to other Solr Search Servers
                                    [5] => Flexible and Adaptable with XML configuration and Schema
                                    [6] => Good unicode support: héllo (hello with an accent over the e)
                                )

                        )

                )

        )

)


Sends a raw update request

  • « SolrClient::query
  • SolrClient::rollback »
  • PHP Manual
  • SolrClient
  • Sends a raw update request

SolrClient::request

(PECL solr >= 0.9.2)

SolrClient::request — Sends a raw update request

Description

public SolrClient::request ( string $raw_request ) : SolrUpdateResponse

Sends a raw XML update request to the server

Parameters

raw_request

An XML string with the raw request to the server.

Return Values

Returns a SolrUpdateResponse on success. Throws an exception on failure.

Errors/Exceptions

Throws SolrIllegalArgumentException if raw_request was an empty string

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to satisfy the query.

Examples

Example #1 SolrClient::request() example

<?php
$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$update_response = $client->request("<commit/>");

$response = $update_response->getResponse();

print_r($response);
?>

The above example will output something similar to:

...


Rollbacks all add/deletes made to the index since the last commit

  • « SolrClient::request
  • SolrClient::setResponseWriter »
  • PHP Manual
  • SolrClient
  • Rollbacks all add/deletes made to the index since the last commit

SolrClient::rollback

(PECL solr >= 0.9.2)

SolrClient::rollback — Rollbacks all add/deletes made to the index since the last commit

Description

public SolrClient::rollback ( void ) : SolrUpdateResponse

Rollbacks all add/deletes made to the index since the last commit. It neither calls any event listeners nor creates a new searcher.

Parameters

This function has no parameters.

Return Values

Returns a SolrUpdateResponse on success or throws a SolrClientException on failure.

See Also

  • SolrClient::commit() - Finalizes all add/deletes made to the index
  • SolrClient::optimize() - Defragments the index


Sets the response writer used to prepare the response from Solr

  • « SolrClient::rollback
  • SolrClient::setServlet »
  • PHP Manual
  • SolrClient
  • Sets the response writer used to prepare the response from Solr

SolrClient::setResponseWriter

(PECL solr >= 0.9.11)

SolrClient::setResponseWriter — Sets the response writer used to prepare the response from Solr

Description

public SolrClient::setResponseWriter ( string $responseWriter ) : void

Sets the response writer used to prepare the response from Solr

Parameters

responseWriter

One of the following:

  • json
  • phps
  • xml

Return Values

No value is returned.

Examples

Example #1 SolrClient::setResponseWriter() example

<?php

// This is my custom class for objects
class SolrClass
{
   public $_properties = array();

   public function __get($property_name) {

      if (property_exists($this, $property_name)) {

          return $this->$property_name;

      } else if (isset($_properties[$property_name])) {

          return $_properties[$property_name];
      }

      return null;
   }
}

$options = array
(
  'hostname' => 'localhost',
  'port' => 8983,
  'path' => '/solr/core1'
);

$client = new SolrClient($options);

$client->setResponseWriter("json");

//$response = $client->ping();

$query = new SolrQuery();

$query->setQuery("*:*");

$query->set("objectClassName", "SolrClass");

$query->set("objectPropertiesStorageMode", 1); // 0 for independent properties, 1 for combined

try
{

$response = $client->query($query);

$resp = $response->getResponse();

print_r($response);

print_r($resp);

} catch (Exception $e) {

print_r($e);

}

?>


Changes the specified servlet type to a new value

  • « SolrClient::setResponseWriter
  • SolrClient::system »
  • PHP Manual
  • SolrClient
  • Changes the specified servlet type to a new value

SolrClient::setServlet

(PECL solr >= 0.9.2)

SolrClient::setServlet — Changes the specified servlet type to a new value

Description

public SolrClient::setServlet ( int $type , string $value ) : bool

Changes the specified servlet type to a new value

Parameters

type

One of the following :

- SolrClient::SEARCH_SERVLET_TYPE
 - SolrClient::UPDATE_SERVLET_TYPE
 - SolrClient::THREADS_SERVLET_TYPE
 - SolrClient::PING_SERVLET_TYPE
 - SolrClient::TERMS_SERVLET_TYPE

value

The new value for the servlet

Return Values

Returns TRUE on success or FALSE on failure.


Retrieve Solr Server information

  • « SolrClient::setServlet
  • SolrClient::threads »
  • PHP Manual
  • SolrClient
  • Retrieve Solr Server information

SolrClient::system

(PECL solr >= 2.0.0)

SolrClient::system — Retrieve Solr Server information

Description

public SolrClient::system ( void ) : void

Retrieve Solr Server information

Parameters

This function has no parameters.

Return Values

Returns a SolrGenericResponse object on success.

Errors/Exceptions

Emits SolrClientException if the client failed, or there was a connection issue.

Emits SolrServerException if the Solr Server failed to satisfy the query.


Checks the threads status

  • « SolrClient::system
  • SolrResponse »
  • PHP Manual
  • SolrClient
  • Checks the threads status

SolrClient::threads

(PECL solr >= 0.9.2)

SolrClient::threads — Checks the threads status

Description

public SolrClient::threads ( void ) : void

Checks the threads status

Parameters

This function has no parameters.

Return Values

Returns a SolrGenericResponse object.

Errors/Exceptions

Throws SolrClientException if the client failed, or there was a connection issue.

throws SolrServerException if the Solr Server failed to process the request.


The SolrResponse class

(PECL solr >= 0.9.2)

Introduction

Represents a response from the Solr server.

Class synopsis

abstract SolrResponse {
/* Constants */
const integer PARSE_SOLR_OBJ = 0 ;
const integer PARSE_SOLR_DOC = 1 ;
/* Properties */
protected integer $http_status ;
protected integer $parser_mode ;
protected bool $success ;
protected string $http_status_message ;
protected string $http_request_url ;
protected string $http_raw_request_headers ;
protected string $http_raw_request ;
protected string $http_raw_response_headers ;
protected string $http_raw_response ;
protected string $http_digested_response ;
/* Methods */
public getDigestedResponse ( void ) : string
public getHttpStatus ( void ) : int
public getHttpStatusMessage ( void ) : string
public getRawRequest ( void ) : string
public getRawRequestHeaders ( void ) : string
public getRawResponse ( void ) : string
public getRawResponseHeaders ( void ) : string
public getRequestUrl ( void ) : string
public getResponse ( void ) : SolrObject
public setParseMode ([ int $parser_mode = 0 ] ) : bool
public success ( void ) : bool
}

Properties

http_status

The http status of the response.

parser_mode

Whether to parse the solr documents as SolrObject or SolrDocument instances.

success

Was there an error during the request

http_status_message

Detailed message on http status

http_request_url

The request URL

http_raw_request_headers

A string of raw headers sent during the request.

http_raw_request

The raw request sent to the server

http_raw_response_headers

Response headers from the Solr server.

http_raw_response

The response message from the server.

http_digested_response

The response in PHP serialized format.

Predefined Constants

SolrResponse Class Constants

SolrResponse::PARSE_SOLR_OBJ

Documents should be parsed as SolrObject instances

SolrResponse::PARSE_SOLR_DOC

Documents should be parsed as SolrDocument instances.

Table of Contents

  • SolrResponse::getDigestedResponse — Returns the XML response as serialized PHP data
  • SolrResponse::getHttpStatus — Returns the HTTP status of the response
  • SolrResponse::getHttpStatusMessage — Returns more details on the HTTP status
  • SolrResponse::getRawRequest — Returns the raw request sent to the Solr server
  • SolrResponse::getRawRequestHeaders — Returns the raw request headers sent to the Solr server
  • SolrResponse::getRawResponse — Returns the raw response from the server
  • SolrResponse::getRawResponseHeaders — Returns the raw response headers from the server
  • SolrResponse::getRequestUrl — Returns the full URL the request was sent to
  • SolrResponse::getResponse — Returns a SolrObject representing the XML response from the server
  • SolrResponse::setParseMode — Sets the parse mode
  • SolrResponse::success — Was the request a success


Returns the XML response as serialized PHP data

  • « SolrResponse
  • SolrResponse::getHttpStatus »
  • PHP Manual
  • SolrResponse
  • Returns the XML response as serialized PHP data

SolrResponse::getDigestedResponse

(PECL solr >= 0.9.2)

SolrResponse::getDigestedResponse — Returns the XML response as serialized PHP data

Description

public SolrResponse::getDigestedResponse ( void ) : string

Returns the XML response as serialized PHP data

Parameters

This function has no parameters.

Return Values

Returns the XML response as serialized PHP data


Returns the HTTP status of the response

  • « SolrResponse::getDigestedResponse
  • SolrResponse::getHttpStatusMessage »
  • PHP Manual
  • SolrResponse
  • Returns the HTTP status of the response

SolrResponse::getHttpStatus

(PECL solr >= 0.9.2)

SolrResponse::getHttpStatus — Returns the HTTP status of the response

Description

public SolrResponse::getHttpStatus ( void ) : int

Returns the HTTP status of the response.

Parameters

This function has no parameters.

Return Values

Returns the HTTP status of the response.


Returns more details on the HTTP status

  • « SolrResponse::getHttpStatus
  • SolrResponse::getRawRequest »
  • PHP Manual
  • SolrResponse
  • Returns more details on the HTTP status

SolrResponse::getHttpStatusMessage

(PECL solr >= 0.9.2)

SolrResponse::getHttpStatusMessage — Returns more details on the HTTP status

Description

public SolrResponse::getHttpStatusMessage ( void ) : string

Returns more details on the HTTP status.

Parameters

This function has no parameters.

Return Values

Returns more details on the HTTP status


Returns the raw request sent to the Solr server

  • « SolrResponse::getHttpStatusMessage
  • SolrResponse::getRawRequestHeaders »
  • PHP Manual
  • SolrResponse
  • Returns the raw request sent to the Solr server

SolrResponse::getRawRequest

(PECL solr >= 0.9.2)

SolrResponse::getRawRequest — Returns the raw request sent to the Solr server

Description

public SolrResponse::getRawRequest ( void ) : string

Returns the raw request sent to the Solr server.

Parameters

This function has no parameters.

Return Values

Returns the raw request sent to the Solr server


Returns the raw request headers sent to the Solr server

  • « SolrResponse::getRawRequest
  • SolrResponse::getRawResponse »
  • PHP Manual
  • SolrResponse
  • Returns the raw request headers sent to the Solr server

SolrResponse::getRawRequestHeaders

(PECL solr >= 0.9.2)

SolrResponse::getRawRequestHeaders — Returns the raw request headers sent to the Solr server

Description

public SolrResponse::getRawRequestHeaders ( void ) : string

Returns the raw request headers sent to the Solr server.

Parameters

This function has no parameters.

Return Values

Returns the raw request headers sent to the Solr server


Returns the raw response from the server

  • « SolrResponse::getRawRequestHeaders
  • SolrResponse::getRawResponseHeaders »
  • PHP Manual
  • SolrResponse
  • Returns the raw response from the server

SolrResponse::getRawResponse

(PECL solr >= 0.9.2)

SolrResponse::getRawResponse — Returns the raw response from the server

Description

public SolrResponse::getRawResponse ( void ) : string

Returns the raw response from the server.

Parameters

This function has no parameters.

Return Values

Returns the raw response from the server.


Returns the raw response headers from the server

  • « SolrResponse::getRawResponse
  • SolrResponse::getRequestUrl »
  • PHP Manual
  • SolrResponse
  • Returns the raw response headers from the server

SolrResponse::getRawResponseHeaders

(PECL solr >= 0.9.2)

SolrResponse::getRawResponseHeaders — Returns the raw response headers from the server

Description

public SolrResponse::getRawResponseHeaders ( void ) : string

Returns the raw response headers from the server.

Parameters

This function has no parameters.

Return Values

Returns the raw response headers from the server.


Returns the full URL the request was sent to

  • « SolrResponse::getRawResponseHeaders
  • SolrResponse::getResponse »
  • PHP Manual
  • SolrResponse
  • Returns the full URL the request was sent to

SolrResponse::getRequestUrl

(PECL solr >= 0.9.2)

SolrResponse::getRequestUrl — Returns the full URL the request was sent to

Description

public SolrResponse::getRequestUrl ( void ) : string

Returns the full URL the request was sent to.

Parameters

This function has no parameters.

Return Values

Returns the full URL the request was sent to


Returns a SolrObject representing the XML response from the server

  • « SolrResponse::getRequestUrl
  • SolrResponse::setParseMode »
  • PHP Manual
  • SolrResponse
  • Returns a SolrObject representing the XML response from the server

SolrResponse::getResponse

(PECL solr >= 0.9.2)

SolrResponse::getResponse — Returns a SolrObject representing the XML response from the server

Description

public SolrResponse::getResponse ( void ) : SolrObject

Returns a SolrObject representing the XML response from the server.

Parameters

This function has no parameters.

Return Values

Returns a SolrObject representing the XML response from the server


Sets the parse mode

  • « SolrResponse::getResponse
  • SolrResponse::success »
  • PHP Manual
  • SolrResponse
  • Sets the parse mode

SolrResponse::setParseMode

(PECL solr >= 0.9.2)

SolrResponse::setParseMode — Sets the parse mode

Description

public SolrResponse::setParseMode ([ int $parser_mode = 0 ] ) : bool

Sets the parse mode.

Parameters

parser_mode

SolrResponse::PARSE_SOLR_DOC parses documents in SolrDocument instances. SolrResponse::PARSE_SOLR_OBJ parses document into SolrObjects.

Return Values

Returns TRUE on success or FALSE on failure.


Was the request a success

  • « SolrResponse::setParseMode
  • SolrQueryResponse »
  • PHP Manual
  • SolrResponse
  • Was the request a success

SolrResponse::success

(PECL solr >= 0.9.2)

SolrResponse::success — Was the request a success

Description

public SolrResponse::success ( void ) : bool

Used to check if the request to the server was successful.

Parameters

This function has no parameters.

Return Values

Returns TRUE if it was successful and FALSE if it was not.


The SolrQueryResponse class

(PECL solr >= 0.9.2)

Introduction

Represents a response to a query request.

Class synopsis

final SolrQueryResponse extends SolrResponse {
/* Constants */
const integer PARSE_SOLR_OBJ = 0 ;
const integer PARSE_SOLR_DOC = 1 ;
/* Inherited properties */
const integer SolrResponse::PARSE_SOLR_OBJ = 0 ;
const integer SolrResponse::PARSE_SOLR_DOC = 1 ;
protected integer $http_status ;
protected integer $parser_mode ;
protected bool $success ;
protected string $http_status_message ;
protected string $http_request_url ;
protected string $http_raw_request_headers ;
protected string $http_raw_request ;
protected string $http_raw_response_headers ;
protected string $http_raw_response ;
protected string $http_digested_response ;
/* Methods */
public __construct ( void )
public __destruct ( void ) : void
/* Inherited methods */
public SolrResponse::getDigestedResponse ( void ) : string
public SolrResponse::getHttpStatus ( void ) : int
public SolrResponse::getHttpStatusMessage ( void ) : string
public SolrResponse::getRawRequest ( void ) : string
public SolrResponse::getRawRequestHeaders ( void ) : string
public SolrResponse::getRawResponse ( void ) : string
public SolrResponse::getRawResponseHeaders ( void ) : string
public SolrResponse::getRequestUrl ( void ) : string
public SolrResponse::getResponse ( void ) : SolrObject
public SolrResponse::setParseMode ([ int $parser_mode = 0 ] ) : bool
public SolrResponse::success ( void ) : bool
}

Predefined Constants

SolrQueryResponse Class constants

SolrQueryResponse::PARSE_SOLR_OBJ

Documents should be parsed as SolrObject instances

SolrQueryResponse::PARSE_SOLR_DOC

Documents should be parsed as SolrDocument instances.

Table of Contents

  • SolrQueryResponse::__construct — Constructor
  • SolrQueryResponse::__destruct — Destructor


Constructor

  • « SolrQueryResponse
  • SolrQueryResponse::__destruct »
  • PHP Manual
  • SolrQueryResponse
  • Constructor

SolrQueryResponse::__construct

(PECL solr >= 0.9.2)

SolrQueryResponse::__construct — Constructor

Description

public SolrQueryResponse::__construct ( void )

Constructor

Parameters

This function has no parameters.

Return Values

None


Destructor

  • « SolrQueryResponse::__construct
  • SolrUpdateResponse »
  • PHP Manual
  • SolrQueryResponse
  • Destructor

SolrQueryResponse::__destruct

(PECL solr >= 0.9.2)

SolrQueryResponse::__destruct — Destructor

Description

public SolrQueryResponse::__destruct ( void ) : void

Destructor.

Parameters

This function has no parameters.

Return Values

None


The SolrUpdateResponse class

(PECL solr >= 0.9.2)

Introduction

Represents a response to an update request.

Class synopsis

final SolrUpdateResponse extends SolrResponse {
/* Constants */
const integer PARSE_SOLR_OBJ = 0 ;
const integer PARSE_SOLR_DOC = 1 ;
/* Inherited properties */
const integer SolrResponse::PARSE_SOLR_OBJ = 0 ;
const integer SolrResponse::PARSE_SOLR_DOC = 1 ;
protected integer $http_status ;
protected integer $parser_mode ;
protected bool $success ;
protected string $http_status_message ;
protected string $http_request_url ;
protected string $http_raw_request_headers ;
protected string $http_raw_request ;
protected string $http_raw_response_headers ;
protected string $http_raw_response ;
protected string $http_digested_response ;
/* Methods */
public __construct ( void )
public __destruct ( void ) : void
/* Inherited methods */
public SolrResponse::getDigestedResponse ( void ) : string
public SolrResponse::getHttpStatus ( void ) : int
public SolrResponse::getHttpStatusMessage ( void ) : string
public SolrResponse::getRawRequest ( void ) : string
public SolrResponse::getRawRequestHeaders ( void ) : string
public SolrResponse::getRawResponse ( void ) : string
public SolrResponse::getRawResponseHeaders ( void ) : string
public SolrResponse::getRequestUrl ( void ) : string
public SolrResponse::getResponse ( void ) : SolrObject
public SolrResponse::setParseMode ([ int $parser_mode = 0 ] ) : bool
public SolrResponse::success ( void ) : bool
}

Predefined Constants

SolrUpdateResponse Class Constants

SolrUpdateResponse::PARSE_SOLR_OBJ

Documents should be parsed as SolrObject instances

SolrUpdateResponse::PARSE_SOLR_DOC

Documents should be parsed as SolrDocument instances.

Table of Contents

  • SolrUpdateResponse::__construct — Constructor
  • SolrUpdateResponse::__destruct — Destructor


Constructor

  • « SolrUpdateResponse
  • SolrUpdateResponse::__destruct »
  • PHP Manual
  • SolrUpdateResponse
  • Constructor

SolrUpdateResponse::__construct

(PECL solr >= 0.9.2)

SolrUpdateResponse::__construct — Constructor

Description

public SolrUpdateResponse::__construct ( void )

Constructor

Parameters

This function has no parameters.

Return Values

None


Destructor

  • « SolrUpdateResponse::__construct
  • SolrPingResponse »
  • PHP Manual
  • SolrUpdateResponse
  • Destructor

SolrUpdateResponse::__destruct

(PECL solr >= 0.9.2)

SolrUpdateResponse::__destruct — Destructor

Description

public SolrUpdateResponse::__destruct ( void ) : void

Destructor

Parameters

This function has no parameters.

Return Values

None


The SolrPingResponse class

(PECL solr >= 0.9.2)

Introduction

Represents a response to a ping request to the server

Class synopsis

final SolrPingResponse extends SolrResponse {
/* Constants */
const integer PARSE_SOLR_OBJ = 0 ;
const integer PARSE_SOLR_DOC = 1 ;
/* Properties */
/* Methods */
public __construct ( void )
public __destruct ( void ) : void
public getResponse ( void ) : string
/* Inherited methods */
public SolrResponse::getDigestedResponse ( void ) : string
public SolrResponse::getHttpStatus ( void ) : int
public SolrResponse::getHttpStatusMessage ( void ) : string
public SolrResponse::getRawRequest ( void ) : string
public SolrResponse::getRawRequestHeaders ( void ) : string
public SolrResponse::getRawResponse ( void ) : string
public SolrResponse::getRawResponseHeaders ( void ) : string
public SolrResponse::getRequestUrl ( void ) : string
public SolrResponse::getResponse ( void ) : SolrObject
public SolrResponse::setParseMode ([ int $parser_mode = 0 ] ) : bool
public SolrResponse::success ( void ) : bool
}

Properties

http_status

The http status of the response.

parser_mode

Whether to parse the solr documents as SolrObject or SolrDocument instances.

success

Was there an error during the request

http_status_message

Detailed message on http status

http_request_url

The request URL

http_raw_request_headers

A string of raw headers sent during the request

http_raw_request

The raw request sent to the server

http_raw_response_headers

Response headers from the Solr server

http_raw_response

The response message from the server

http_digested_response

The response in PHP serialized format.

Predefined Constants

SolrPingResponse Class Constants

SolrPingResponse::PARSE_SOLR_OBJ

Documents should be parsed as SolrObject instances

SolrPingResponse::PARSE_SOLR_DOC

Documents should be parsed as SolrDocument instances.

Table of Contents

  • SolrPingResponse::__construct — Constructor
  • SolrPingResponse::__destruct — Destructor
  • SolrPingResponse::getResponse — Returns the response from the server


Constructor

  • « SolrPingResponse
  • SolrPingResponse::__destruct »
  • PHP Manual
  • SolrPingResponse
  • Constructor

SolrPingResponse::__construct

(PECL solr >= 0.9.2)

SolrPingResponse::__construct — Constructor

Description

public SolrPingResponse::__construct ( void )

Constructor

Parameters

This function has no parameters.

Return Values

None


Destructor

  • « SolrPingResponse::__construct
  • SolrPingResponse::getResponse »
  • PHP Manual
  • SolrPingResponse
  • Destructor

SolrPingResponse::__destruct

(PECL solr >= 0.9.2)

SolrPingResponse::__destruct — Destructor

Description

public SolrPingResponse::__destruct ( void ) : void

Destructor

Parameters

This function has no parameters.

Return Values

None


Returns the response from the server

  • « SolrPingResponse::__destruct
  • SolrGenericResponse »
  • PHP Manual
  • SolrPingResponse
  • Returns the response from the server

SolrPingResponse::getResponse

(PECL solr >= 0.9.2)

SolrPingResponse::getResponse — Returns the response from the server

Description

public SolrPingResponse::getResponse ( void ) : string

Returns the response from the server. This should be empty because the request as a HEAD request.

Parameters

This function has no parameters.

Return Values

Returns an empty string.


The SolrGenericResponse class

(PECL solr >= 0.9.2)

Introduction

Represents a response from the solr server.

Class synopsis

final SolrGenericResponse extends SolrResponse {
/* Constants */
const integer PARSE_SOLR_OBJ = 0 ;
const integer PARSE_SOLR_DOC = 1 ;
/* Inherited properties */
const integer SolrResponse::PARSE_SOLR_OBJ = 0 ;
const integer SolrResponse::PARSE_SOLR_DOC = 1 ;
protected integer $http_status ;
protected integer $parser_mode ;
protected bool $success ;
protected string $http_status_message ;
protected string $http_request_url ;
protected string $http_raw_request_headers ;
protected string $http_raw_request ;
protected string $http_raw_response_headers ;
protected string $http_raw_response ;
protected string $http_digested_response ;
/* Methods */
public __construct ( void )
public __destruct ( void ) : void
/* Inherited methods */
public SolrResponse::getDigestedResponse ( void ) : string
public SolrResponse::getHttpStatus ( void ) : int
public SolrResponse::getHttpStatusMessage ( void ) : string
public SolrResponse::getRawRequest ( void ) : string
public SolrResponse::getRawRequestHeaders ( void ) : string
public SolrResponse::getRawResponse ( void ) : string
public SolrResponse::getRawResponseHeaders ( void ) : string
public SolrResponse::getRequestUrl ( void ) : string
public SolrResponse::getResponse ( void ) : SolrObject
public SolrResponse::setParseMode ([ int $parser_mode = 0 ] ) : bool
public SolrResponse::success ( void ) : bool
}

Predefined Constants

SolrGenericResponse Class constants

SolrGenericResponse::PARSE_SOLR_OBJ

Documents should be parsed as SolrObject instances

SolrGenericResponse::PARSE_SOLR_DOC

Documents should be parsed as SolrDocument instances.

Table of Contents

  • SolrGenericResponse::__construct — Constructor
  • SolrGenericResponse::__destruct — Destructor


Constructor

  • « SolrGenericResponse
  • SolrGenericResponse::__destruct »
  • PHP Manual
  • SolrGenericResponse
  • Constructor

SolrGenericResponse::__construct

(PECL solr >= 0.9.2)

SolrGenericResponse::__construct — Constructor

Description

public SolrGenericResponse::__construct ( void )

Constructor

Parameters

This function has no parameters.

Return Values

None


Destructor

  • « SolrGenericResponse::__construct
  • SolrParams »
  • PHP Manual
  • SolrGenericResponse
  • Destructor

SolrGenericResponse::__destruct

(PECL solr >= 0.9.2)

SolrGenericResponse::__destruct — Destructor

Description

public SolrGenericResponse::__destruct ( void ) : void

Destructor.

Parameters

This function has no parameters.

Return Values

None


The SolrParams class

(PECL solr >= 0.9.2)

Introduction

Represents a collection of name-value pairs sent to the Solr server during a request.

Class synopsis

abstract SolrParams implements Serializable {
/* Methods */
final public add ( string $name , string $value ) : SolrParams
public addParam ( string $name , string $value ) : SolrParams
final public get ( string $param_name ) : mixed
final public getParam ([ string $param_name ] ) : mixed
final public getParams ( void ) : array
final public getPreparedParams ( void ) : array
final public serialize ( void ) : string
final public set ( string $name , string $value ) : void
public setParam ( string $name , string $value ) : SolrParams
final public toString ([ bool $url_encode = FALSE ] ) : string
final public unserialize ( string $serialized ) : void
}

Table of Contents

  • SolrParams::add — This is an alias for SolrParams::addParam
  • SolrParams::addParam — Adds a parameter to the object
  • SolrParams::get — This is an alias for SolrParams::getParam
  • SolrParams::getParam — Returns a parameter value
  • SolrParams::getParams — Returns an array of non URL-encoded parameters
  • SolrParams::getPreparedParams — Returns an array of URL-encoded parameters
  • SolrParams::serialize — Used for custom serialization
  • SolrParams::set — An alias of SolrParams::setParam
  • SolrParams::setParam — Sets the parameter to the specified value
  • SolrParams::toString — Returns all the name-value pair parameters in the object
  • SolrParams::unserialize — Used for custom serialization


This is an alias for SolrParams::addParam

  • « SolrParams
  • SolrParams::addParam »
  • PHP Manual
  • SolrParams
  • This is an alias for SolrParams::addParam

SolrParams::add

(PECL solr >= 0.9.2)

SolrParams::add — This is an alias for SolrParams::addParam

Description

final public SolrParams::add ( string $name , string $value ) : SolrParams

This is an alias for SolrParams::addParam

Parameters

name

The name of the parameter

value

The value of the parameter

Return Values

Returns a SolrParams instance on success


Adds a parameter to the object

  • « SolrParams::add
  • SolrParams::get »
  • PHP Manual
  • SolrParams
  • Adds a parameter to the object

SolrParams::addParam

(PECL solr >= 0.9.2)

SolrParams::addParam — Adds a parameter to the object

Description

public SolrParams::addParam ( string $name , string $value ) : SolrParams

Adds a parameter to the object. This is used for parameters that can be specified multiple times.

Parameters

name

Name of parameter

value

Value of parameter

Return Values

Returns a SolrParam object on success and FALSE on failure.


This is an alias for SolrParams::getParam

  • « SolrParams::addParam
  • SolrParams::getParam »
  • PHP Manual
  • SolrParams
  • This is an alias for SolrParams::getParam

SolrParams::get

(PECL solr >= 0.9.2)

SolrParams::get — This is an alias for SolrParams::getParam

Description

final public SolrParams::get ( string $param_name ) : mixed

This is an alias for SolrParams::getParam

Parameters

param_name

Then name of the parameter

Return Values

Returns an array or string depending on the type of parameter


Returns a parameter value

  • « SolrParams::get
  • SolrParams::getParams »
  • PHP Manual
  • SolrParams
  • Returns a parameter value

SolrParams::getParam

(PECL solr >= 0.9.2)

SolrParams::getParam — Returns a parameter value

Description

final public SolrParams::getParam ([ string $param_name ] ) : mixed

Returns a parameter with name param_name

Parameters

param_name

The name of the parameter

Return Values

Returns a string or an array depending on the type of the parameter


Returns an array of non URL-encoded parameters

  • « SolrParams::getParam
  • SolrParams::getPreparedParams »
  • PHP Manual
  • SolrParams
  • Returns an array of non URL-encoded parameters

SolrParams::getParams

(PECL solr >= 0.9.2)

SolrParams::getParams — Returns an array of non URL-encoded parameters

Description

final public SolrParams::getParams ( void ) : array

Returns an array of non URL-encoded parameters

Parameters

This function has no parameters.

Return Values

Returns an array of non URL-encoded parameters


Returns an array of URL-encoded parameters

  • « SolrParams::getParams
  • SolrParams::serialize »
  • PHP Manual
  • SolrParams
  • Returns an array of URL-encoded parameters

SolrParams::getPreparedParams

(PECL solr >= 0.9.2)

SolrParams::getPreparedParams — Returns an array of URL-encoded parameters

Description

final public SolrParams::getPreparedParams ( void ) : array

Returns an array on URL-encoded parameters

Parameters

This function has no parameters.

Return Values

Returns an array on URL-encoded parameters


Used for custom serialization

  • « SolrParams::getPreparedParams
  • SolrParams::set »
  • PHP Manual
  • SolrParams
  • Used for custom serialization

SolrParams::serialize

(PECL solr >= 0.9.2)

SolrParams::serialize — Used for custom serialization

Description

final public SolrParams::serialize ( void ) : string

Used for custom serialization

Parameters

This function has no parameters.

Return Values

Used for custom serialization


An alias of SolrParams::setParam

  • « SolrParams::serialize
  • SolrParams::setParam »
  • PHP Manual
  • SolrParams
  • An alias of SolrParams::setParam

SolrParams::set

(PECL solr >= 0.9.2)

SolrParams::set — An alias of SolrParams::setParam

Description

final public SolrParams::set ( string $name , string $value ) : void

An alias of SolrParams::setParam

Parameters

name

Then name of the parameter

value

The parameter value

Return Values

Returns an instance of the SolrParams object on success


Sets the parameter to the specified value

  • « SolrParams::set
  • SolrParams::toString »
  • PHP Manual
  • SolrParams
  • Sets the parameter to the specified value

SolrParams::setParam

(PECL solr >= 0.9.2)

SolrParams::setParam — Sets the parameter to the specified value

Description

public SolrParams::setParam ( string $name , string $value ) : SolrParams

Sets the query parameter to the specified value. This is used for parameters that can only be specified once. Subsequent calls with the same parameter name will override the existing value

Parameters

name

Name of the parameter

value

Value of the parameter

Return Values

Returns a SolrParam object on success and FALSE on value.

Examples

Example #1 SolrParams::setParam() example

<?php

$param = new SolrParams();

$param->setParam('q', 'solr')->setParam('rows', 2);

?>

The above example will output something similar to:


Returns all the name-value pair parameters in the object

  • « SolrParams::setParam
  • SolrParams::unserialize »
  • PHP Manual
  • SolrParams
  • Returns all the name-value pair parameters in the object

SolrParams::toString

(PECL solr >= 0.9.2)

SolrParams::toString — Returns all the name-value pair parameters in the object

Description

final public SolrParams::toString ([ bool $url_encode = FALSE ] ) : string

Returns all the name-value pair parameters in the object

Parameters

url_encode

Whether to return URL-encoded values

Return Values

Returns a string on success and FALSE on failure.


Used for custom serialization

  • « SolrParams::toString
  • SolrModifiableParams »
  • PHP Manual
  • SolrParams
  • Used for custom serialization

SolrParams::unserialize

(PECL solr >= 0.9.2)

SolrParams::unserialize — Used for custom serialization

Description

final public SolrParams::unserialize ( string $serialized ) : void

Used for custom serialization

Parameters

serialized

The serialized representation of the object

Return Values

None


The SolrModifiableParams class

(PECL solr >= 0.9.2)

Introduction

Represents a collection of name-value pairs sent to the Solr server during a request.

Class synopsis

SolrModifiableParams extends SolrParams implements Serializable {
/* Methods */
public __construct ( void )
public __destruct ( void ) : void
/* Inherited methods */
final public SolrParams::add ( string $name , string $value ) : SolrParams
public SolrParams::addParam ( string $name , string $value ) : SolrParams
final public SolrParams::get ( string $param_name ) : mixed
final public SolrParams::getParam ([ string $param_name ] ) : mixed
final public SolrParams::getParams ( void ) : array
final public SolrParams::getPreparedParams ( void ) : array
final public SolrParams::serialize ( void ) : string
final public SolrParams::set ( string $name , string $value ) : void
public SolrParams::setParam ( string $name , string $value ) : SolrParams
final public SolrParams::toString ([ bool $url_encode = FALSE ] ) : string
final public SolrParams::unserialize ( string $serialized ) : void
}

Table of Contents

  • SolrModifiableParams::__construct — Constructor
  • SolrModifiableParams::__destruct — Destructor


Constructor

  • « SolrModifiableParams
  • SolrModifiableParams::__destruct »
  • PHP Manual
  • SolrModifiableParams
  • Constructor

SolrModifiableParams::__construct

(PECL solr >= 0.9.2)

SolrModifiableParams::__construct — Constructor

Description

public SolrModifiableParams::__construct ( void )

Constructor

Parameters

This function has no parameters.

Return Values

None


Destructor

  • « SolrModifiableParams::__construct
  • SolrQuery »
  • PHP Manual
  • SolrModifiableParams
  • Destructor

SolrModifiableParams::__destruct

(PECL solr >= 0.9.2)

SolrModifiableParams::__destruct — Destructor

Description

public SolrModifiableParams::__destruct ( void ) : void

Destructor

Parameters

This function has no parameters.

Return Values

None


The SolrQuery class

(PECL solr >= 0.9.2)

Introduction

Represents a collection of name-value pairs sent to the Solr server during a request.

Class synopsis

SolrQuery extends SolrModifiableParams implements Serializable {
/* Constants */
const integer ORDER_ASC = 0 ;
const integer ORDER_DESC = 1 ;
const integer FACET_SORT_INDEX = 0 ;
const integer FACET_SORT_COUNT = 1 ;
const integer TERMS_SORT_INDEX = 0 ;
const integer TERMS_SORT_COUNT = 1 ;
/* Properties */
/* Methods */
public addExpandFilterQuery ( string $fq ) : SolrQuery
public addExpandSortField ( string $field [, string $order ] ) : SolrQuery
public addFacetDateField ( string $dateField ) : SolrQuery
public addFacetDateOther ( string $value [, string $field_override ] ) : SolrQuery
public addFacetField ( string $field ) : SolrQuery
public addFacetQuery ( string $facetQuery ) : SolrQuery
public addField ( string $field ) : SolrQuery
public addFilterQuery ( string $fq ) : SolrQuery
public addGroupField ( string $value ) : SolrQuery
public addGroupFunction ( string $value ) : SolrQuery
public addGroupQuery ( string $value ) : SolrQuery
public addGroupSortField ( string $field [, int $order ] ) : SolrQuery
public addHighlightField ( string $field ) : SolrQuery
public addMltField ( string $field ) : SolrQuery
public addMltQueryField ( string $field , float $boost ) : SolrQuery
public addSortField ( string $field [, int $order = SolrQuery::ORDER_DESC ] ) : SolrQuery
public addStatsFacet ( string $field ) : SolrQuery
public addStatsField ( string $field ) : SolrQuery
public collapse ( SolrCollapseFunction $collapseFunction ) : SolrQuery
public __construct ([ string $q ] )
public __destruct ( void ) : void
public getExpand ( void ) : bool
public getExpandFilterQueries ( void ) : array
public getExpandQuery ( void ) : array
public getExpandRows ( void ) : int
public getExpandSortFields ( void ) : array
public getFacet ( void ) : bool
public getFacetDateEnd ([ string $field_override ] ) : string
public getFacetDateFields ( void ) : array
public getFacetDateGap ([ string $field_override ] ) : string
public getFacetDateHardEnd ([ string $field_override ] ) : string
public getFacetDateOther ([ string $field_override ] ) : array
public getFacetDateStart ([ string $field_override ] ) : string
public getFacetFields ( void ) : array
public getFacetLimit ([ string $field_override ] ) : int
public getFacetMethod ([ string $field_override ] ) : string
public getFacetMinCount ([ string $field_override ] ) : int
public getFacetMissing ([ string $field_override ] ) : bool
public getFacetOffset ([ string $field_override ] ) : int
public getFacetPrefix ([ string $field_override ] ) : string
public getFacetQueries ( void ) : array
public getFacetSort ([ string $field_override ] ) : int
public getFields ( void ) : array
public getFilterQueries ( void ) : array
public getGroup ( void ) : bool
public getGroupCachePercent ( void ) : int
public getGroupFacet ( void ) : bool
public getGroupFields ( void ) : array
public getGroupFormat ( void ) : string
public getGroupFunctions ( void ) : array
public getGroupLimit ( void ) : int
public getGroupMain ( void ) : bool
public getGroupNGroups ( void ) : bool
public getGroupOffset ( void ) : int
public getGroupQueries ( void ) : array
public getGroupSortFields ( void ) : array
public getGroupTruncate ( void ) : bool
public getHighlight ( void ) : bool
public getHighlightAlternateField ([ string $field_override ] ) : string
public getHighlightFields ( void ) : array
public getHighlightFormatter ([ string $field_override ] ) : string
public getHighlightFragmenter ([ string $field_override ] ) : string
public getHighlightFragsize ([ string $field_override ] ) : int
public getHighlightHighlightMultiTerm ( void ) : bool
public getHighlightMaxAlternateFieldLength ([ string $field_override ] ) : int
public getHighlightMaxAnalyzedChars ( void ) : int
public getHighlightMergeContiguous ([ string $field_override ] ) : bool
public getHighlightRegexMaxAnalyzedChars ( void ) : int
public getHighlightRegexPattern ( void ) : string
public getHighlightRegexSlop ( void ) : float
public getHighlightRequireFieldMatch ( void ) : bool
public getHighlightSimplePost ([ string $field_override ] ) : string
public getHighlightSimplePre ([ string $field_override ] ) : string
public getHighlightSnippets ([ string $field_override ] ) : int
public getHighlightUsePhraseHighlighter ( void ) : bool
public getMlt ( void ) : bool
public getMltBoost ( void ) : bool
public getMltCount ( void ) : int
public getMltFields ( void ) : array
public getMltMaxNumQueryTerms ( void ) : int
public getMltMaxNumTokens ( void ) : int
public getMltMaxWordLength ( void ) : int
public getMltMinDocFrequency ( void ) : int
public getMltMinTermFrequency ( void ) : int
public getMltMinWordLength ( void ) : int
public getMltQueryFields ( void ) : array
public getQuery ( void ) : string
public getRows ( void ) : int
public getSortFields ( void ) : array
public getStart ( void ) : int
public getStats ( void ) : bool
public getStatsFacets ( void ) : array
public getStatsFields ( void ) : array
public getTerms ( void ) : bool
public getTermsField ( void ) : string
public getTermsIncludeLowerBound ( void ) : bool
public getTermsIncludeUpperBound ( void ) : bool
public getTermsLimit ( void ) : int
public getTermsLowerBound ( void ) : string
public getTermsMaxCount ( void ) : int
public getTermsMinCount ( void ) : int
public getTermsPrefix ( void ) : string
public getTermsReturnRaw ( void ) : bool
public getTermsSort ( void ) : int
public getTermsUpperBound ( void ) : string
public getTimeAllowed ( void ) : int
public removeExpandFilterQuery ( string $fq ) : SolrQuery
public removeExpandSortField ( string $field ) : SolrQuery
public removeFacetDateField ( string $field ) : SolrQuery
public removeFacetDateOther ( string $value [, string $field_override ] ) : SolrQuery
public removeFacetField ( string $field ) : SolrQuery
public removeFacetQuery ( string $value ) : SolrQuery
public removeField ( string $field ) : SolrQuery
public removeFilterQuery ( string $fq ) : SolrQuery
public removeHighlightField ( string $field ) : SolrQuery
public removeMltField ( string $field ) : SolrQuery
public removeMltQueryField ( string $queryField ) : SolrQuery
public removeSortField ( string $field ) : SolrQuery
public removeStatsFacet ( string $value ) : SolrQuery
public removeStatsField ( string $field ) : SolrQuery
public setEchoHandler ( bool $flag ) : SolrQuery
public setEchoParams ( string $type ) : SolrQuery
public setExpand ( bool $value ) : SolrQuery
public setExpandQuery ( string $q ) : SolrQuery
public setExpandRows ( int $value ) : SolrQuery
public setExplainOther ( string $query ) : SolrQuery
public setFacet ( bool $flag ) : SolrQuery
public setFacetDateEnd ( string $value [, string $field_override ] ) : SolrQuery
public setFacetDateGap ( string $value [, string $field_override ] ) : SolrQuery
public setFacetDateHardEnd ( bool $value [, string $field_override ] ) : SolrQuery
public setFacetDateStart ( string $value [, string $field_override ] ) : SolrQuery
public setFacetEnumCacheMinDefaultFrequency ( int $frequency [, string $field_override ] ) : SolrQuery
public setFacetLimit ( int $limit [, string $field_override ] ) : SolrQuery
public setFacetMethod ( string $method [, string $field_override ] ) : SolrQuery
public setFacetMinCount ( int $mincount [, string $field_override ] ) : SolrQuery
public setFacetMissing ( bool $flag [, string $field_override ] ) : SolrQuery
public setFacetOffset ( int $offset [, string $field_override ] ) : SolrQuery
public setFacetPrefix ( string $prefix [, string $field_override ] ) : SolrQuery
public setFacetSort ( int $facetSort [, string $field_override ] ) : SolrQuery
public setGroup ( bool $value ) : SolrQuery
public setGroupCachePercent ( int $percent ) : SolrQuery
public setGroupFacet ( bool $value ) : SolrQuery
public setGroupFormat ( string $value ) : SolrQuery
public setGroupLimit ( int $value ) : SolrQuery
public setGroupMain ( string $value ) : SolrQuery
public setGroupNGroups ( bool $value ) : SolrQuery
public setGroupOffset ( int $value ) : SolrQuery
public setGroupTruncate ( bool $value ) : SolrQuery
public setHighlight ( bool $flag ) : SolrQuery
public setHighlightAlternateField ( string $field [, string $field_override ] ) : SolrQuery
public setHighlightFormatter ( string $formatter [, string $field_override ] ) : SolrQuery
public setHighlightFragmenter ( string $fragmenter [, string $field_override ] ) : SolrQuery
public setHighlightFragsize ( int $size [, string $field_override ] ) : SolrQuery
public setHighlightHighlightMultiTerm ( bool $flag ) : SolrQuery
public setHighlightMaxAlternateFieldLength ( int $fieldLength [, string $field_override ] ) : SolrQuery
public setHighlightMaxAnalyzedChars ( int $value ) : SolrQuery
public setHighlightMergeContiguous ( bool $flag [, string $field_override ] ) : SolrQuery
public setHighlightRegexMaxAnalyzedChars ( int $maxAnalyzedChars ) : SolrQuery
public setHighlightRegexPattern ( string $value ) : SolrQuery
public setHighlightRegexSlop ( float $factor ) : SolrQuery
public setHighlightRequireFieldMatch ( bool $flag ) : SolrQuery
public setHighlightSimplePost ( string $simplePost [, string $field_override ] ) : SolrQuery
public setHighlightSimplePre ( string $simplePre [, string $field_override ] ) : SolrQuery
public setHighlightSnippets ( int $value [, string $field_override ] ) : SolrQuery
public setHighlightUsePhraseHighlighter ( bool $flag ) : SolrQuery
public setMlt ( bool $flag ) : SolrQuery
public setMltBoost ( bool $flag ) : SolrQuery
public setMltCount ( int $count ) : SolrQuery
public setMltMaxNumQueryTerms ( int $value ) : SolrQuery
public setMltMaxNumTokens ( int $value ) : SolrQuery
public setMltMaxWordLength ( int $maxWordLength ) : SolrQuery
public setMltMinDocFrequency ( int $minDocFrequency ) : SolrQuery
public setMltMinTermFrequency ( int $minTermFrequency ) : SolrQuery
public setMltMinWordLength ( int $minWordLength ) : SolrQuery
public setOmitHeader ( bool $flag ) : SolrQuery
public setQuery ( string $query ) : SolrQuery
public setRows ( int $rows ) : SolrQuery
public setShowDebugInfo ( bool $flag ) : SolrQuery
public setStart ( int $start ) : SolrQuery
public setStats ( bool $flag ) : SolrQuery
public setTerms ( bool $flag ) : SolrQuery
public setTermsField ( string $fieldname ) : SolrQuery
public setTermsIncludeLowerBound ( bool $flag ) : SolrQuery
public setTermsIncludeUpperBound ( bool $flag ) : SolrQuery
public setTermsLimit ( int $limit ) : SolrQuery
public setTermsLowerBound ( string $lowerBound ) : SolrQuery
public setTermsMaxCount ( int $frequency ) : SolrQuery
public setTermsMinCount ( int $frequency ) : SolrQuery
public setTermsPrefix ( string $prefix ) : SolrQuery
public setTermsReturnRaw ( bool $flag ) : SolrQuery
public setTermsSort ( int $sortType ) : SolrQuery
public setTermsUpperBound ( string $upperBound ) : SolrQuery
public setTimeAllowed ( int $timeAllowed ) : SolrQuery
/* Inherited methods */
public SolrModifiableParams::__construct ( void )
public SolrModifiableParams::__destruct ( void ) : void
}

Predefined Constants

SolrQuery::ORDER_ASC

Used to specify that the sorting should be in acending order

SolrQuery::ORDER_DESC

Used to specify that the sorting should be in descending order

SolrQuery::FACET_SORT_INDEX

Used to specify that the facet should sort by index

SolrQuery::FACET_SORT_COUNT

Used to specify that the facet should sort by count

SolrQuery::TERMS_SORT_INDEX

Used in the TermsComponent

SolrQuery::TERMS_SORT_COUNT

Used in the TermsComponent

Table of Contents

  • SolrQuery::addExpandFilterQuery — Overrides main filter query, determines which documents to include in the main group
  • SolrQuery::addExpandSortField — Orders the documents within the expanded groups (expand.sort parameter)
  • SolrQuery::addFacetDateField — Maps to facet.date
  • SolrQuery::addFacetDateOther — Adds another facet.date.other parameter
  • SolrQuery::addFacetField — Adds another field to the facet
  • SolrQuery::addFacetQuery — Adds a facet query
  • SolrQuery::addField — Specifies which fields to return in the result
  • SolrQuery::addFilterQuery — Specifies a filter query
  • SolrQuery::addGroupField — Add a field to be used to group results
  • SolrQuery::addGroupFunction — Allows grouping results based on the unique values of a function query (group.func parameter)
  • SolrQuery::addGroupQuery — Allows grouping of documents that match the given query
  • SolrQuery::addGroupSortField — Add a group sort field (group.sort parameter)
  • SolrQuery::addHighlightField — Maps to hl.fl
  • SolrQuery::addMltField — Sets a field to use for similarity
  • SolrQuery::addMltQueryField — Maps to mlt.qf
  • SolrQuery::addSortField — Used to control how the results should be sorted
  • SolrQuery::addStatsFacet — Requests a return of sub results for values within the given facet
  • SolrQuery::addStatsField — Maps to stats.field parameter
  • SolrQuery::collapse — Collapses the result set to a single document per group
  • SolrQuery::__construct — Constructor
  • SolrQuery::__destruct — Destructor
  • SolrQuery::getExpand — Returns true if group expanding is enabled
  • SolrQuery::getExpandFilterQueries — Returns the expand filter queries
  • SolrQuery::getExpandQuery — Returns the expand query expand.q parameter
  • SolrQuery::getExpandRows — Returns The number of rows to display in each group (expand.rows)
  • SolrQuery::getExpandSortFields — Returns an array of fields
  • SolrQuery::getFacet — Returns the value of the facet parameter
  • SolrQuery::getFacetDateEnd — Returns the value for the facet.date.end parameter
  • SolrQuery::getFacetDateFields — Returns all the facet.date fields
  • SolrQuery::getFacetDateGap — Returns the value of the facet.date.gap parameter
  • SolrQuery::getFacetDateHardEnd — Returns the value of the facet.date.hardend parameter
  • SolrQuery::getFacetDateOther — Returns the value for the facet.date.other parameter
  • SolrQuery::getFacetDateStart — Returns the lower bound for the first date range for all date faceting on this field
  • SolrQuery::getFacetFields — Returns all the facet fields
  • SolrQuery::getFacetLimit — Returns the maximum number of constraint counts that should be returned for the facet fields
  • SolrQuery::getFacetMethod — Returns the value of the facet.method parameter
  • SolrQuery::getFacetMinCount — Returns the minimum counts for facet fields should be included in the response
  • SolrQuery::getFacetMissing — Returns the current state of the facet.missing parameter
  • SolrQuery::getFacetOffset — Returns an offset into the list of constraints to be used for pagination
  • SolrQuery::getFacetPrefix — Returns the facet prefix
  • SolrQuery::getFacetQueries — Returns all the facet queries
  • SolrQuery::getFacetSort — Returns the facet sort type
  • SolrQuery::getFields — Returns the list of fields that will be returned in the response
  • SolrQuery::getFilterQueries — Returns an array of filter queries
  • SolrQuery::getGroup — Returns true if grouping is enabled
  • SolrQuery::getGroupCachePercent — Returns group cache percent value
  • SolrQuery::getGroupFacet — Returns the group.facet parameter value
  • SolrQuery::getGroupFields — Returns group fields (group.field parameter values)
  • SolrQuery::getGroupFormat — Returns the group.format value
  • SolrQuery::getGroupFunctions — Returns group functions (group.func parameter values)
  • SolrQuery::getGroupLimit — Returns the group.limit value
  • SolrQuery::getGroupMain — Returns the group.main value
  • SolrQuery::getGroupNGroups — Returns the group.ngroups value
  • SolrQuery::getGroupOffset — Returns the group.offset value
  • SolrQuery::getGroupQueries — Returns all the group.query parameter values
  • SolrQuery::getGroupSortFields — Returns the group.sort value
  • SolrQuery::getGroupTruncate — Returns the group.truncate value
  • SolrQuery::getHighlight — Returns the state of the hl parameter
  • SolrQuery::getHighlightAlternateField — Returns the highlight field to use as backup or default
  • SolrQuery::getHighlightFields — Returns all the fields that Solr should generate highlighted snippets for
  • SolrQuery::getHighlightFormatter — Returns the formatter for the highlighted output
  • SolrQuery::getHighlightFragmenter — Returns the text snippet generator for highlighted text
  • SolrQuery::getHighlightFragsize — Returns the number of characters of fragments to consider for highlighting
  • SolrQuery::getHighlightHighlightMultiTerm — Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries
  • SolrQuery::getHighlightMaxAlternateFieldLength — Returns the maximum number of characters of the field to return
  • SolrQuery::getHighlightMaxAnalyzedChars — Returns the maximum number of characters into a document to look for suitable snippets
  • SolrQuery::getHighlightMergeContiguous — Returns whether or not the collapse contiguous fragments into a single fragment
  • SolrQuery::getHighlightRegexMaxAnalyzedChars — Returns the maximum number of characters from a field when using the regex fragmenter
  • SolrQuery::getHighlightRegexPattern — Returns the regular expression for fragmenting
  • SolrQuery::getHighlightRegexSlop — Returns the deviation factor from the ideal fragment size
  • SolrQuery::getHighlightRequireFieldMatch — Returns if a field will only be highlighted if the query matched in this particular field
  • SolrQuery::getHighlightSimplePost — Returns the text which appears after a highlighted term
  • SolrQuery::getHighlightSimplePre — Returns the text which appears before a highlighted term
  • SolrQuery::getHighlightSnippets — Returns the maximum number of highlighted snippets to generate per field
  • SolrQuery::getHighlightUsePhraseHighlighter — Returns the state of the hl.usePhraseHighlighter parameter
  • SolrQuery::getMlt — Returns whether or not MoreLikeThis results should be enabled
  • SolrQuery::getMltBoost — Returns whether or not the query will be boosted by the interesting term relevance
  • SolrQuery::getMltCount — Returns the number of similar documents to return for each result
  • SolrQuery::getMltFields — Returns all the fields to use for similarity
  • SolrQuery::getMltMaxNumQueryTerms — Returns the maximum number of query terms that will be included in any generated query
  • SolrQuery::getMltMaxNumTokens — Returns the maximum number of tokens to parse in each document field that is not stored with TermVector support
  • SolrQuery::getMltMaxWordLength — Returns the maximum word length above which words will be ignored
  • SolrQuery::getMltMinDocFrequency — Returns the treshold frequency at which words will be ignored which do not occur in at least this many docs
  • SolrQuery::getMltMinTermFrequency — Returns the frequency below which terms will be ignored in the source document
  • SolrQuery::getMltMinWordLength — Returns the minimum word length below which words will be ignored
  • SolrQuery::getMltQueryFields — Returns the query fields and their boosts
  • SolrQuery::getQuery — Returns the main query
  • SolrQuery::getRows — Returns the maximum number of documents
  • SolrQuery::getSortFields — Returns all the sort fields
  • SolrQuery::getStart — Returns the offset in the complete result set
  • SolrQuery::getStats — Returns whether or not stats is enabled
  • SolrQuery::getStatsFacets — Returns all the stats facets that were set
  • SolrQuery::getStatsFields — Returns all the statistics fields
  • SolrQuery::getTerms — Returns whether or not the TermsComponent is enabled
  • SolrQuery::getTermsField — Returns the field from which the terms are retrieved
  • SolrQuery::getTermsIncludeLowerBound — Returns whether or not to include the lower bound in the result set
  • SolrQuery::getTermsIncludeUpperBound — Returns whether or not to include the upper bound term in the result set
  • SolrQuery::getTermsLimit — Returns the maximum number of terms Solr should return
  • SolrQuery::getTermsLowerBound — Returns the term to start at
  • SolrQuery::getTermsMaxCount — Returns the maximum document frequency
  • SolrQuery::getTermsMinCount — Returns the minimum document frequency to return in order to be included
  • SolrQuery::getTermsPrefix — Returns the term prefix
  • SolrQuery::getTermsReturnRaw — Whether or not to return raw characters
  • SolrQuery::getTermsSort — Returns an integer indicating how terms are sorted
  • SolrQuery::getTermsUpperBound — Returns the term to stop at
  • SolrQuery::getTimeAllowed — Returns the time in milliseconds allowed for the query to finish
  • SolrQuery::removeExpandFilterQuery — Removes an expand filter query
  • SolrQuery::removeExpandSortField — Removes an expand sort field from the expand.sort parameter
  • SolrQuery::removeFacetDateField — Removes one of the facet date fields
  • SolrQuery::removeFacetDateOther — Removes one of the facet.date.other parameters
  • SolrQuery::removeFacetField — Removes one of the facet.date parameters
  • SolrQuery::removeFacetQuery — Removes one of the facet.query parameters
  • SolrQuery::removeField — Removes a field from the list of fields
  • SolrQuery::removeFilterQuery — Removes a filter query
  • SolrQuery::removeHighlightField — Removes one of the fields used for highlighting
  • SolrQuery::removeMltField — Removes one of the moreLikeThis fields
  • SolrQuery::removeMltQueryField — Removes one of the moreLikeThis query fields
  • SolrQuery::removeSortField — Removes one of the sort fields
  • SolrQuery::removeStatsFacet — Removes one of the stats.facet parameters
  • SolrQuery::removeStatsField — Removes one of the stats.field parameters
  • SolrQuery::setEchoHandler — Toggles the echoHandler parameter
  • SolrQuery::setEchoParams — Determines what kind of parameters to include in the response
  • SolrQuery::setExpand — Enables/Disables the Expand Component
  • SolrQuery::setExpandQuery — Sets the expand.q parameter
  • SolrQuery::setExpandRows — Sets the number of rows to display in each group (expand.rows). Server Default 5
  • SolrQuery::setExplainOther — Sets the explainOther common query parameter
  • SolrQuery::setFacet — Maps to the facet parameter. Enables or disables facetting
  • SolrQuery::setFacetDateEnd — Maps to facet.date.end
  • SolrQuery::setFacetDateGap — Maps to facet.date.gap
  • SolrQuery::setFacetDateHardEnd — Maps to facet.date.hardend
  • SolrQuery::setFacetDateStart — Maps to facet.date.start
  • SolrQuery::setFacetEnumCacheMinDefaultFrequency — Sets the minimum document frequency used for determining term count
  • SolrQuery::setFacetLimit — Maps to facet.limit
  • SolrQuery::setFacetMethod — Specifies the type of algorithm to use when faceting a field
  • SolrQuery::setFacetMinCount — Maps to facet.mincount
  • SolrQuery::setFacetMissing — Maps to facet.missing
  • SolrQuery::setFacetOffset — Sets the offset into the list of constraints to allow for pagination
  • SolrQuery::setFacetPrefix — Specifies a string prefix with which to limits the terms on which to facet
  • SolrQuery::setFacetSort — Determines the ordering of the facet field constraints
  • SolrQuery::setGroup — Enable/Disable result grouping (group parameter)
  • SolrQuery::setGroupCachePercent — Enables caching for result grouping
  • SolrQuery::setGroupFacet — Sets group.facet parameter
  • SolrQuery::setGroupFormat — Sets the group format, result structure (group.format parameter)
  • SolrQuery::setGroupLimit — Specifies the number of results to return for each group. The server default value is 1
  • SolrQuery::setGroupMain — If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
  • SolrQuery::setGroupNGroups — If true, Solr includes the number of groups that have matched the query in the results
  • SolrQuery::setGroupOffset — Sets the group.offset parameter
  • SolrQuery::setGroupTruncate — If true, facet counts are based on the most relevant document of each group matching the query
  • SolrQuery::setHighlight — Enables or disables highlighting
  • SolrQuery::setHighlightAlternateField — Specifies the backup field to use
  • SolrQuery::setHighlightFormatter — Specify a formatter for the highlight output
  • SolrQuery::setHighlightFragmenter — Sets a text snippet generator for highlighted text
  • SolrQuery::setHighlightFragsize — The size of fragments to consider for highlighting
  • SolrQuery::setHighlightHighlightMultiTerm — Use SpanScorer to highlight phrase terms
  • SolrQuery::setHighlightMaxAlternateFieldLength — Sets the maximum number of characters of the field to return
  • SolrQuery::setHighlightMaxAnalyzedChars — Specifies the number of characters into a document to look for suitable snippets
  • SolrQuery::setHighlightMergeContiguous — Whether or not to collapse contiguous fragments into a single fragment
  • SolrQuery::setHighlightRegexMaxAnalyzedChars — Specify the maximum number of characters to analyze
  • SolrQuery::setHighlightRegexPattern — Specify the regular expression for fragmenting
  • SolrQuery::setHighlightRegexSlop — Sets the factor by which the regex fragmenter can stray from the ideal fragment size
  • SolrQuery::setHighlightRequireFieldMatch — Require field matching during highlighting
  • SolrQuery::setHighlightSimplePost — Sets the text which appears after a highlighted term
  • SolrQuery::setHighlightSimplePre — Sets the text which appears before a highlighted term
  • SolrQuery::setHighlightSnippets — Sets the maximum number of highlighted snippets to generate per field
  • SolrQuery::setHighlightUsePhraseHighlighter — Whether to highlight phrase terms only when they appear within the query phrase
  • SolrQuery::setMlt — Enables or disables moreLikeThis
  • SolrQuery::setMltBoost — Set if the query will be boosted by the interesting term relevance
  • SolrQuery::setMltCount — Set the number of similar documents to return for each result
  • SolrQuery::setMltMaxNumQueryTerms — Sets the maximum number of query terms included
  • SolrQuery::setMltMaxNumTokens — Specifies the maximum number of tokens to parse
  • SolrQuery::setMltMaxWordLength — Sets the maximum word length
  • SolrQuery::setMltMinDocFrequency — Sets the mltMinDoc frequency
  • SolrQuery::setMltMinTermFrequency — Sets the frequency below which terms will be ignored in the source docs
  • SolrQuery::setMltMinWordLength — Sets the minimum word length
  • SolrQuery::setOmitHeader — Exclude the header from the returned results
  • SolrQuery::setQuery — Sets the search query
  • SolrQuery::setRows — Specifies the maximum number of rows to return in the result
  • SolrQuery::setShowDebugInfo — Flag to show debug information
  • SolrQuery::setStart — Specifies the number of rows to skip
  • SolrQuery::setStats — Enables or disables the Stats component
  • SolrQuery::setTerms — Enables or disables the TermsComponent
  • SolrQuery::setTermsField — Sets the name of the field to get the Terms from
  • SolrQuery::setTermsIncludeLowerBound — Include the lower bound term in the result set
  • SolrQuery::setTermsIncludeUpperBound — Include the upper bound term in the result set
  • SolrQuery::setTermsLimit — Sets the maximum number of terms to return
  • SolrQuery::setTermsLowerBound — Specifies the Term to start from
  • SolrQuery::setTermsMaxCount — Sets the maximum document frequency
  • SolrQuery::setTermsMinCount — Sets the minimum document frequency
  • SolrQuery::setTermsPrefix — Restrict matches to terms that start with the prefix
  • SolrQuery::setTermsReturnRaw — Return the raw characters of the indexed term
  • SolrQuery::setTermsSort — Specifies how to sort the returned terms
  • SolrQuery::setTermsUpperBound — Sets the term to stop at
  • SolrQuery::setTimeAllowed — The time allowed for search to finish


Overrides main filter query, determines which documents to include in the main group

  • « SolrQuery
  • SolrQuery::addExpandSortField »
  • PHP Manual
  • SolrQuery
  • Overrides main filter query, determines which documents to include in the main group

SolrQuery::addExpandFilterQuery

(PECL solr >= 2.2.0)

SolrQuery::addExpandFilterQuery — Overrides main filter query, determines which documents to include in the main group

Description

public SolrQuery::addExpandFilterQuery ( string $fq ) : SolrQuery

Overrides main filter query, determines which documents to include in the main group.

Parameters

fq

Return Values

SolrQuery

See Also

  • SolrQuery::setExpand() - Enables/Disables the Expand Component
  • SolrQuery::addExpandSortField() - Orders the documents within the expanded groups (expand.sort parameter)
  • SolrQuery::removeExpandSortField() - Removes an expand sort field from the expand.sort parameter
  • SolrQuery::setExpandRows() - Sets the number of rows to display in each group (expand.rows). Server Default 5
  • SolrQuery::setExpandQuery() - Sets the expand.q parameter
  • SolrQuery::removeExpandFilterQuery() - Removes an expand filter query


Orders the documents within the expanded groups (expand.sort parameter)

  • « SolrQuery::addExpandFilterQuery
  • SolrQuery::addFacetDateField »
  • PHP Manual
  • SolrQuery
  • Orders the documents within the expanded groups (expand.sort parameter)

SolrQuery::addExpandSortField

(PECL solr >= 2.2.0)

SolrQuery::addExpandSortField — Orders the documents within the expanded groups (expand.sort parameter)

Description

public SolrQuery::addExpandSortField ( string $field [, string $order ] ) : SolrQuery

Orders the documents within the expanded groups (expand.sort parameter).

Parameters

field

field name

order

Order ASC/DESC, utilizes SolrQuery::ORDER_* constants.

Default: SolrQuery::ORDER_DESC

Return Values

SolrQuery

See Also

  • SolrQuery::setExpand() - Enables/Disables the Expand Component
  • SolrQuery::removeExpandSortField() - Removes an expand sort field from the expand.sort parameter
  • SolrQuery::setExpandRows() - Sets the number of rows to display in each group (expand.rows). Server Default 5
  • SolrQuery::setExpandQuery() - Sets the expand.q parameter
  • SolrQuery::addExpandFilterQuery() - Overrides main filter query, determines which documents to include in the main group
  • SolrQuery::removeExpandFilterQuery() - Removes an expand filter query


Maps to facet.date

  • « SolrQuery::addExpandSortField
  • SolrQuery::addFacetDateOther »
  • PHP Manual
  • SolrQuery
  • Maps to facet.date

SolrQuery::addFacetDateField

(PECL solr >= 0.9.2)

SolrQuery::addFacetDateField — Maps to facet.date

Description

public SolrQuery::addFacetDateField ( string $dateField ) : SolrQuery

This method allows you to specify a field which should be treated as a facet.

It can be used multiple times with different field names to indicate multiple facet fields

Parameters

dateField

The name of the date field.

Return Values

Returns a SolrQuery object.


Adds another facet.date.other parameter

  • « SolrQuery::addFacetDateField
  • SolrQuery::addFacetField »
  • PHP Manual
  • SolrQuery
  • Adds another facet.date.other parameter

SolrQuery::addFacetDateOther

(PECL solr >= 0.9.2)

SolrQuery::addFacetDateOther — Adds another facet.date.other parameter

Description

public SolrQuery::addFacetDateOther ( string $value [, string $field_override ] ) : SolrQuery

Sets the facet.date.other parameter. Accepts an optional field override

Parameters

value

The value to use.

field_override

The field name for the override.

Return Values

Returns the current SolrQuery object, if the return value is used.


Adds another field to the facet

  • « SolrQuery::addFacetDateOther
  • SolrQuery::addFacetQuery »
  • PHP Manual
  • SolrQuery
  • Adds another field to the facet

SolrQuery::addFacetField

(PECL solr >= 0.9.2)

SolrQuery::addFacetField — Adds another field to the facet

Description

public SolrQuery::addFacetField ( string $field ) : SolrQuery

Adds another field to the facet

Parameters

field

The name of the field

Return Values

Returns the current SolrQuery object, if the return value is used.

Examples

Example #1 SolrQuery::addFacetField() example

<?php

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setQuery($query);

$query->addField('price')->addField('color');

$query->setFacet(true);

$query->addFacetField('price')->addFacetField('color');

$query_response = $client->query($query);

$response = $query_response->getResponse();

print_r($response['facet_counts']['facet_fields']);

?>

The above example will output something similar to:

SolrObject Object
(
    [color] => SolrObject Object
        (
            [blue] => 20
            [green] => 100
        )

)


Adds a facet query

  • « SolrQuery::addFacetField
  • SolrQuery::addField »
  • PHP Manual
  • SolrQuery
  • Adds a facet query

SolrQuery::addFacetQuery

(PECL solr >= 0.9.2)

SolrQuery::addFacetQuery — Adds a facet query

Description

public SolrQuery::addFacetQuery ( string $facetQuery ) : SolrQuery

Adds a facet query

Parameters

facetQuery

The facet query

Return Values

Returns the current SolrQuery object, if the return value is used.

Examples

Example #1 SolrQuery::addFacetField() example

<?php

$options = array
(
        'hostname' => SOLR_SERVER_HOSTNAME,
        'login'    => SOLR_SERVER_USERNAME,
        'password' => SOLR_SERVER_PASSWORD,
        'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery('*:*');

$query->setFacet(true);

$query->addFacetQuery('price:[* TO 500]')->addFacetQuery('price:[500 TO *]');

$query_response = $client->query($query);

$response = $query_response->getResponse();

print_r($response->facet_counts->facet_queries);

?>

The above example will output something similar to:

SolrObject Object
(
    [price:[* TO 500]] => 14
    [price:[500 TO *]] => 2
)


Specifies which fields to return in the result

  • « SolrQuery::addFacetQuery
  • SolrQuery::addFilterQuery »
  • PHP Manual
  • SolrQuery
  • Specifies which fields to return in the result

SolrQuery::addField

(PECL solr >= 0.9.2)

SolrQuery::addField — Specifies which fields to return in the result

Description

public SolrQuery::addField ( string $field ) : SolrQuery

This method is used to used to specify a set of fields to return, thereby restricting the amount of data returned in the response.

It should be called multiple time, once for each field name.

Parameters

field

The name of the field

Return Values

Returns the current SolrQuery object


Specifies a filter query

  • « SolrQuery::addField
  • SolrQuery::addGroupField »
  • PHP Manual
  • SolrQuery
  • Specifies a filter query

SolrQuery::addFilterQuery

(PECL solr >= 0.9.2)

SolrQuery::addFilterQuery — Specifies a filter query

Description

public SolrQuery::addFilterQuery ( string $fq ) : SolrQuery

Specifies a filter query

Parameters

fq

The filter query

Return Values

Returns the current SolrQuery object.

Examples

Example #1 SolrQuery::addFilterQuery() example

<?php

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setQuery('*:*');

$query->addFilterQuery('color:blue,green');

$query_response = $client->query($query);

$response = $query_response->getResponse();

print_r($response['facet_counts']['facet_fields']);

?>

The above example will output something similar to:

 &fq=color:blue,green


Add a field to be used to group results

  • « SolrQuery::addFilterQuery
  • SolrQuery::addGroupFunction »
  • PHP Manual
  • SolrQuery
  • Add a field to be used to group results

SolrQuery::addGroupField

(PECL solr >= 2.2.0)

SolrQuery::addGroupField — Add a field to be used to group results

Description

public SolrQuery::addGroupField ( string $value ) : SolrQuery

The name of the field by which to group results. The field must be single-valued, and either be indexed or a field type that has a value source and works in a function query, such as ExternalFileField. It must also be a string-based field, such as StrField or TextField Uses group.field parameter

Parameters

value

See Also

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter)
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter)
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter)
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping


Allows grouping results based on the unique values of a function query (group.func parameter)

  • « SolrQuery::addGroupField
  • SolrQuery::addGroupQuery »
  • PHP Manual
  • SolrQuery
  • Allows grouping results based on the unique values of a function query (group.func parameter)

SolrQuery::addGroupFunction

(PECL solr >= 2.2.0)

SolrQuery::addGroupFunction — Allows grouping results based on the unique values of a function query (group.func parameter)

Description

public SolrQuery::addGroupFunction ( string $value ) : SolrQuery

Adds a group function (group.func parameter) Allows grouping results based on the unique values of a function query.

Parameters

value

Return Values

SolrQuery

See Also

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter)
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter)
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping


Allows grouping of documents that match the given query

  • « SolrQuery::addGroupFunction
  • SolrQuery::addGroupSortField »
  • PHP Manual
  • SolrQuery
  • Allows grouping of documents that match the given query

SolrQuery::addGroupQuery

(PECL solr >= 2.2.0)

SolrQuery::addGroupQuery — Allows grouping of documents that match the given query

Description

public SolrQuery::addGroupQuery ( string $value ) : SolrQuery

Allows grouping of documents that match the given query. Adds query to the group.query parameter

Parameters

value

Return Values

SolrQuery

See Also

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter)
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter)
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter)
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping


Add a group sort field (group.sort parameter)

  • « SolrQuery::addGroupQuery
  • SolrQuery::addHighlightField »
  • PHP Manual
  • SolrQuery
  • Add a group sort field (group.sort parameter)

SolrQuery::addGroupSortField

(PECL solr >= 2.2.0)

SolrQuery::addGroupSortField — Add a group sort field (group.sort parameter)

Description

public SolrQuery::addGroupSortField ( string $field [, int $order ] ) : SolrQuery

Allow sorting group documents, using group sort field (group.sort parameter).

Parameters

field

Field name

order

Order ASC/DESC, utilizes SolrQuery::ORDER_* constants

Return Values

Examples

Example #1 SolrQuery::addGroupSortField() example

<?php

$solrQuery = new SolrQuery('*:*');
$solrQuery
    ->setGroup(true)
    ->addGroupSortField('price', SolrQuery::ORDER_ASC);

echo $solrQuery;
?>

The above example will output something similar to:

q=*:*&group=true&group.sort=price asc

See Also

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter)
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter)
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping


Maps to hl.fl

  • « SolrQuery::addGroupSortField
  • SolrQuery::addMltField »
  • PHP Manual
  • SolrQuery
  • Maps to hl.fl

SolrQuery::addHighlightField

(PECL solr >= 0.9.2)

SolrQuery::addHighlightField — Maps to hl.fl

Description

public SolrQuery::addHighlightField ( string $field ) : SolrQuery

Maps to hl.fl. This is used to specify that highlighted snippets should be generated for a particular field

Parameters

field

Name of the field

Return Values

Returns the current SolrQuery object, if the return value is used.


Sets a field to use for similarity

  • « SolrQuery::addHighlightField
  • SolrQuery::addMltQueryField »
  • PHP Manual
  • SolrQuery
  • Sets a field to use for similarity

SolrQuery::addMltField

(PECL solr >= 0.9.2)

SolrQuery::addMltField — Sets a field to use for similarity

Description

public SolrQuery::addMltField ( string $field ) : SolrQuery

Maps to mlt.fl. It specifies that a field should be used for similarity.

Parameters

field

The name of the field

Return Values

Returns the current SolrQuery object, if the return value is used.


Maps to mlt.qf

  • « SolrQuery::addMltField
  • SolrQuery::addSortField »
  • PHP Manual
  • SolrQuery
  • Maps to mlt.qf

SolrQuery::addMltQueryField

(PECL solr >= 0.9.2)

SolrQuery::addMltQueryField — Maps to mlt.qf

Description

public SolrQuery::addMltQueryField ( string $field , float $boost ) : SolrQuery

Maps to mlt.qf. It is used to specify query fields and their boosts

Parameters

field

The name of the field

boost

Its boost value

Return Values

Returns the current SolrQuery object, if the return value is used.


Used to control how the results should be sorted

  • « SolrQuery::addMltQueryField
  • SolrQuery::addStatsFacet »
  • PHP Manual
  • SolrQuery
  • Used to control how the results should be sorted

SolrQuery::addSortField

(PECL solr >= 0.9.2)

SolrQuery::addSortField — Used to control how the results should be sorted

Description

public SolrQuery::addSortField ( string $field [, int $order = SolrQuery::ORDER_DESC ] ) : SolrQuery

Used to control how the results should be sorted.

Parameters

field

The name of the field

order

The sort direction. This should be either SolrQuery::ORDER_ASC or SolrQuery::ORDER_DESC.

Return Values

Returns the current SolrQuery object.


Requests a return of sub results for values within the given facet

  • « SolrQuery::addSortField
  • SolrQuery::addStatsField »
  • PHP Manual
  • SolrQuery
  • Requests a return of sub results for values within the given facet

SolrQuery::addStatsFacet

(PECL solr >= 0.9.2)

SolrQuery::addStatsFacet — Requests a return of sub results for values within the given facet

Description

public SolrQuery::addStatsFacet ( string $field ) : SolrQuery

Requests a return of sub results for values within the given facet. Maps to the stats.facet field

Parameters

field

The name of the field

Return Values

Returns the current SolrQuery object, if the return value is used.


Maps to stats.field parameter

  • « SolrQuery::addStatsFacet
  • SolrQuery::collapse »
  • PHP Manual
  • SolrQuery
  • Maps to stats.field parameter

SolrQuery::addStatsField

(PECL solr >= 0.9.2)

SolrQuery::addStatsField — Maps to stats.field parameter

Description

public SolrQuery::addStatsField ( string $field ) : SolrQuery

Maps to stats.field parameter This methods adds another stats.field parameter.

Parameters

field

The name of the field

Return Values

Returns the current SolrQuery object, if the return value is used.


Collapses the result set to a single document per group

  • « SolrQuery::addStatsField
  • SolrQuery::__construct »
  • PHP Manual
  • SolrQuery
  • Collapses the result set to a single document per group

SolrQuery::collapse

(No version information available, might only be in Git)

SolrQuery::collapse — Collapses the result set to a single document per group

Description

public SolrQuery::collapse ( SolrCollapseFunction $collapseFunction ) : SolrQuery

Collapses the result set to a single document per group before it forwards the result set to the rest of the search components.

So all downstream components (faceting, highlighting, etc...) will work with the collapsed result set.

Parameters

collapseFunction

Return Values

Returns the current SolrQuery object

Examples

Example #1 SolrQuery::collapse() example

<?php

include "bootstrap.php";

$options = array
(
        'hostname' => SOLR_SERVER_HOSTNAME,
        'login'    => SOLR_SERVER_USERNAME,
        'password' => SOLR_SERVER_PASSWORD,
        'port'     => SOLR_SERVER_PORT,
        'path'     => SOLR_SERVER_PATH
);

$client = new SolrClient($options);

$query = new SolrQuery('*:*');

$collapseFunction = new SolrCollapseFunction('manu_id_s');

$collapseFunction
->setSize(2)
->setNullPolicy(SolrCollapseFunction::NULLPOLICY_IGNORE);

$query
->collapse($collapseFunction)
->setRows(4);

$queryResponse = $client->query($query);

$response = $queryResponse->getResponse();

print_r($response);

?>

The above example will output something similar to:

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 1
            [params] => SolrObject Object
                (
                    [q] => *:*
                    [indent] => on
                    [fq] => {!collapse field=manu_id_s size=2 nullPolicy=ignore}
                    [rows] => 4
                    [version] => 2.2
                    [wt] => xml
                )

        )

    [response] => SolrObject Object
        (
            [numFound] => 14
            [start] => 0
            [docs] => Array
                (
                    [0] => SolrObject Object
                        (
                            [id] => SP2514N
                            [name] => Array
                                (
                                    [0] => Samsung SpinPoint P120 SP2514N - hard drive - 250 GB - ATA-133
                                )

                            [manu] => Array
                                (
                                    [0] => Samsung Electronics Co. Ltd.
                                )

                            [manu_id_s] => samsung
                            [cat] => Array
                                (
                                    [0] => electronics
                                    [1] => hard drive
                                )

                            [features] => Array
                                (
                                    [0] => 7200RPM, 8MB cache, IDE Ultra ATA-133
                                    [1] => NoiseGuard, SilentSeek technology, Fluid Dynamic Bearing (FDB) motor
                                )

                            [price] => Array
                                (
                                    [0] => 92
                                )

                            [popularity] => Array
                                (
                                    [0] => 6
                                )

                            [inStock] => Array
                                (
                                    [0] => 1
                                )

                            [manufacturedate_dt] => 2006-02-13T15:26:37Z
                            [store] => Array
                                (
                                    [0] => 35.0752,-97.032
                                )

                            [_version_] => 1510294336412057600
                        )

                    [1] => SolrObject Object
                        (
                            [id] => 6H500F0
                            [name] => Array
                                (
                                    [0] => Maxtor DiamondMax 11 - hard drive - 500 GB - SATA-300
                                )

                            [manu] => Array
                                (
                                    [0] => Maxtor Corp.
                                )

                            [manu_id_s] => maxtor
                            [cat] => Array
                                (
                                    [0] => electronics
                                    [1] => hard drive
                                )

                            [features] => Array
                                (
                                    [0] => SATA 3.0Gb/s, NCQ
                                    [1] => 8.5ms seek
                                    [2] => 16MB cache
                                )

                            [price] => Array
                                (
                                    [0] => 350
                                )

                            [popularity] => Array
                                (
                                    [0] => 6
                                )

                            [inStock] => Array
                                (
                                    [0] => 1
                                )

                            [store] => Array
                                (
                                    [0] => 45.17614,-93.87341
                                )

                            [manufacturedate_dt] => 2006-02-13T15:26:37Z
                            [_version_] => 1510294336449806336
                        )

                    [2] => SolrObject Object
                        (
                            [id] => F8V7067-APL-KIT
                            [name] => Array
                                (
                                    [0] => Belkin Mobile Power Cord for iPod w/ Dock
                                )

                            [manu] => Array
                                (
                                    [0] => Belkin
                                )

                            [manu_id_s] => belkin
                            [cat] => Array
                                (
                                    [0] => electronics
                                    [1] => connector
                                )

                            [features] => Array
                                (
                                    [0] => car power adapter, white
                                )

                            [weight] => Array
                                (
                                    [0] => 4
                                )

                            [price] => Array
                                (
                                    [0] => 19.95
                                )

                            [popularity] => Array
                                (
                                    [0] => 1
                                )

                            [inStock] => Array
                                (
                                    [0] =>
                                )

                            [store] => Array
                                (
                                    [0] => 45.18014,-93.87741
                                )

                            [manufacturedate_dt] => 2005-08-01T16:30:25Z
                            [_version_] => 1510294336458194944
                        )

                    [3] => SolrObject Object
                        (
                            [id] => MA147LL/A
                            [name] => Array
                                (
                                    [0] => Apple 60 GB iPod with Video Playback Black
                                )

                            [manu] => Array
                                (
                                    [0] => Apple Computer Inc.
                                )

                            [manu_id_s] => apple
                            [cat] => Array
                                (
                                    [0] => electronics
                                    [1] => music
                                )

                            [features] => Array
                                (
                                    [0] => iTunes, Podcasts, Audiobooks
                                    [1] => Stores up to 15,000 songs, 25,000 photos, or 150 hours of video
                                    [2] => 2.5-inch, 320x240 color TFT LCD display with LED backlight
                                    [3] => Up to 20 hours of battery life
                                    [4] => Plays AAC, MP3, WAV, AIFF, Audible, Apple Lossless, H.264 video
                                    [5] => Notes, Calendar, Phone book, Hold button, Date display, Photo wallet, Built-in games, JPEG photo playback, Upgradeable firmware, USB 2.0 compatibility, Playback speed control, Rechargeable capability, Battery level indication
                                )

                            [includes] => Array
                                (
                                    [0] => earbud headphones, USB cable
                                )

                            [weight] => Array
                                (
                                    [0] => 5.5
                                )

                            [price] => Array
                                (
                                    [0] => 399
                                )

                            [popularity] => Array
                                (
                                    [0] => 10
                                )

                            [inStock] => Array
                                (
                                    [0] => 1
                                )

                            [store] => Array
                                (
                                    [0] => 37.7752,-100.0232
                                )

                            [manufacturedate_dt] => 2005-10-12T08:00:00Z
                            [_version_] => 1510294336562003968
                        )

                )

        )

)


Constructor

  • « SolrQuery::collapse
  • SolrQuery::__destruct »
  • PHP Manual
  • SolrQuery
  • Constructor

SolrQuery::__construct

(PECL solr >= 0.9.2)

SolrQuery::__construct — Constructor

Description

public SolrQuery::__construct ([ string $q ] )

Constructor.

Parameters

q

Optional search query

Return Values

None

Errors/Exceptions

Emits SolrIllegalArgumentException in case of an invalid parameter was passed.

Changelog

Version | Description
2.0.0 | If q was invalid, then a SolrIllegalArgumentException is now thrown. Previously an error was emitted.


Destructor

  • « SolrQuery::__construct
  • SolrQuery::getExpand »
  • PHP Manual
  • SolrQuery
  • Destructor

SolrQuery::__destruct

(PECL solr >= 0.9.2)

SolrQuery::__destruct — Destructor

Description

public SolrQuery::__destruct ( void ) : void

Destructor

Parameters

This function has no parameters.

Return Values

None.


Returns true if group expanding is enabled

  • « SolrQuery::__destruct
  • SolrQuery::getExpandFilterQueries »
  • PHP Manual
  • SolrQuery
  • Returns true if group expanding is enabled

SolrQuery::getExpand

(PECL solr >= 2.2.0)

SolrQuery::getExpand — Returns true if group expanding is enabled

Description

public SolrQuery::getExpand ( void ) : bool

Returns TRUE if group expanding is enabled


Returns the expand filter queries

  • « SolrQuery::getExpand
  • SolrQuery::getExpandQuery »
  • PHP Manual
  • SolrQuery
  • Returns the expand filter queries

SolrQuery::getExpandFilterQueries

(PECL solr >= 2.2.0)

SolrQuery::getExpandFilterQueries — Returns the expand filter queries

Description

public SolrQuery::getExpandFilterQueries ( void ) : array

Returns the expand filter queries


Returns the expand query expand.q parameter

  • « SolrQuery::getExpandFilterQueries
  • SolrQuery::getExpandRows »
  • PHP Manual
  • SolrQuery
  • Returns the expand query expand.q parameter

SolrQuery::getExpandQuery

(PECL solr >= 2.2.0)

SolrQuery::getExpandQuery — Returns the expand query expand.q parameter

Description

public SolrQuery::getExpandQuery ( void ) : array

Returns the expand query expand.q parameter


Returns The number of rows to display in each group (expand.rows)

  • « SolrQuery::getExpandQuery
  • SolrQuery::getExpandSortFields »
  • PHP Manual
  • SolrQuery
  • Returns The number of rows to display in each group (expand.rows)

SolrQuery::getExpandRows

(PECL solr >= 2.2.0)

SolrQuery::getExpandRows — Returns The number of rows to display in each group (expand.rows)

Description

public SolrQuery::getExpandRows ( void ) : int

Returns The number of rows to display in each group (expand.rows)


Returns an array of fields

  • « SolrQuery::getExpandRows
  • SolrQuery::getFacet »
  • PHP Manual
  • SolrQuery
  • Returns an array of fields

SolrQuery::getExpandSortFields

(PECL solr >= 2.2.0)

SolrQuery::getExpandSortFields — Returns an array of fields

Description

public SolrQuery::getExpandSortFields ( void ) : array

Returns an array of fields


Returns the value of the facet parameter

  • « SolrQuery::getExpandSortFields
  • SolrQuery::getFacetDateEnd »
  • PHP Manual
  • SolrQuery
  • Returns the value of the facet parameter

SolrQuery::getFacet

(PECL solr >= 0.9.2)

SolrQuery::getFacet — Returns the value of the facet parameter

Description

public SolrQuery::getFacet ( void ) : bool

Returns the value of the facet parameter.

Parameters

This function has no parameters.

Return Values

Returns a boolean on success and NULL if not set


Returns the value for the facet.date.end parameter

  • « SolrQuery::getFacet
  • SolrQuery::getFacetDateFields »
  • PHP Manual
  • SolrQuery
  • Returns the value for the facet.date.end parameter

SolrQuery::getFacetDateEnd

(PECL solr >= 0.9.2)

SolrQuery::getFacetDateEnd — Returns the value for the facet.date.end parameter

Description

public SolrQuery::getFacetDateEnd ([ string $field_override ] ) : string

Returns the value for the facet.date.end parameter. This method accepts an optional field override

Parameters

field_override

The name of the field

Return Values

Returns a string on success and NULL if not set


Returns all the facet.date fields

  • « SolrQuery::getFacetDateEnd
  • SolrQuery::getFacetDateGap »
  • PHP Manual
  • SolrQuery
  • Returns all the facet.date fields

SolrQuery::getFacetDateFields

(PECL solr >= 0.9.2)

SolrQuery::getFacetDateFields — Returns all the facet.date fields

Description

public SolrQuery::getFacetDateFields ( void ) : array

Returns all the facet.date fields

Parameters

This function has no parameters.

Return Values

Returns all the facet.date fields as an array or NULL if none was set


Returns the value of the facet.date.gap parameter

  • « SolrQuery::getFacetDateFields
  • SolrQuery::getFacetDateHardEnd »
  • PHP Manual
  • SolrQuery
  • Returns the value of the facet.date.gap parameter

SolrQuery::getFacetDateGap

(PECL solr >= 0.9.2)

SolrQuery::getFacetDateGap — Returns the value of the facet.date.gap parameter

Description

public SolrQuery::getFacetDateGap ([ string $field_override ] ) : string

Returns the value of the facet.date.gap parameter. It accepts an optional field override

Parameters

field_override

The name of the field

Return Values

Returns a string on success and NULL if not set


Returns the value of the facet.date.hardend parameter

  • « SolrQuery::getFacetDateGap
  • SolrQuery::getFacetDateOther »
  • PHP Manual
  • SolrQuery
  • Returns the value of the facet.date.hardend parameter

SolrQuery::getFacetDateHardEnd

(PECL solr >= 0.9.2)

SolrQuery::getFacetDateHardEnd — Returns the value of the facet.date.hardend parameter

Description

public SolrQuery::getFacetDateHardEnd ([ string $field_override ] ) : string

Returns the value of the facet.date.hardend parameter. Accepts an optional field override

Parameters

field_override

The name of the field

Return Values

Returns a string on success and NULL if not set


Returns the value for the facet.date.other parameter

  • « SolrQuery::getFacetDateHardEnd
  • SolrQuery::getFacetDateStart »
  • PHP Manual
  • SolrQuery
  • Returns the value for the facet.date.other parameter

SolrQuery::getFacetDateOther

(PECL solr >= 0.9.2)

SolrQuery::getFacetDateOther — Returns the value for the facet.date.other parameter

Description

public SolrQuery::getFacetDateOther ([ string $field_override ] ) : array

Returns the value for the facet.date.other parameter. This method accepts an optional field override.

Parameters

field_override

The name of the field

Return Values

Returns an array on success and NULL if not set.


Returns the lower bound for the first date range for all date faceting on this field

  • « SolrQuery::getFacetDateOther
  • SolrQuery::getFacetFields »
  • PHP Manual
  • SolrQuery
  • Returns the lower bound for the first date range for all date faceting on this field

SolrQuery::getFacetDateStart

(PECL solr >= 0.9.2)

SolrQuery::getFacetDateStart — Returns the lower bound for the first date range for all date faceting on this field

Description

public SolrQuery::getFacetDateStart ([ string $field_override ] ) : string

Returns the lower bound for the first date range for all date faceting on this field. Accepts an optional field override

Parameters

field_override

The name of the field

Return Values

Returns a string on success and NULL if not set


Returns all the facet fields

  • « SolrQuery::getFacetDateStart
  • SolrQuery::getFacetLimit »
  • PHP Manual
  • SolrQuery
  • Returns all the facet fields

SolrQuery::getFacetFields

(PECL solr >= 0.9.2)

SolrQuery::getFacetFields — Returns all the facet fields

Description

public SolrQuery::getFacetFields ( void ) : array

Returns all the facet fields

Parameters

This function has no parameters.

Return Values

Returns an array of all the fields and NULL if none was set


Returns the maximum number of constraint counts that should be returned for the facet fields

  • « SolrQuery::getFacetFields
  • SolrQuery::getFacetMethod »
  • PHP Manual
  • SolrQuery
  • Returns the maximum number of constraint counts that should be returned for the facet fields

SolrQuery::getFacetLimit

(PECL solr >= 0.9.2)

SolrQuery::getFacetLimit — Returns the maximum number of constraint counts that should be returned for the facet fields

Description

public SolrQuery::getFacetLimit ([ string $field_override ] ) : int

Returns the maximum number of constraint counts that should be returned for the facet fields. This method accepts an optional field override

Parameters

field_override

The name of the field to override for

Return Values

Returns an integer on success and NULL if not set


Returns the value of the facet.method parameter

  • « SolrQuery::getFacetLimit
  • SolrQuery::getFacetMinCount »
  • PHP Manual
  • SolrQuery
  • Returns the value of the facet.method parameter

SolrQuery::getFacetMethod

(PECL solr >= 0.9.2)

SolrQuery::getFacetMethod — Returns the value of the facet.method parameter

Description

public SolrQuery::getFacetMethod ([ string $field_override ] ) : string

Returns the value of the facet.method parameter. This accepts an optional field override.

Parameters

field_override

The name of the field

Return Values

Returns a string on success and NULL if not set


Returns the minimum counts for facet fields should be included in the response

  • « SolrQuery::getFacetMethod
  • SolrQuery::getFacetMissing »
  • PHP Manual
  • SolrQuery
  • Returns the minimum counts for facet fields should be included in the response

SolrQuery::getFacetMinCount

(PECL solr >= 0.9.2)

SolrQuery::getFacetMinCount — Returns the minimum counts for facet fields should be included in the response

Description

public SolrQuery::getFacetMinCount ([ string $field_override ] ) : int

Returns the minimum counts for facet fields should be included in the response. It accepts an optional field override

Parameters

field_override

The name of the field

Return Values

Returns an integer on success and NULL if not set


Returns the current state of the facet.missing parameter

  • « SolrQuery::getFacetMinCount
  • SolrQuery::getFacetOffset »
  • PHP Manual
  • SolrQuery
  • Returns the current state of the facet.missing parameter

SolrQuery::getFacetMissing

(PECL solr >= 0.9.2)

SolrQuery::getFacetMissing — Returns the current state of the facet.missing parameter

Description

public SolrQuery::getFacetMissing ([ string $field_override ] ) : bool

Returns the current state of the facet.missing parameter. This accepts an optional field override

Parameters

field_override

The name of the field

Return Values

Returns a boolean on success and NULL if not set


Returns an offset into the list of constraints to be used for pagination

  • « SolrQuery::getFacetMissing
  • SolrQuery::getFacetPrefix »
  • PHP Manual
  • SolrQuery
  • Returns an offset into the list of constraints to be used for pagination

SolrQuery::getFacetOffset

(PECL solr >= 0.9.2)

SolrQuery::getFacetOffset — Returns an offset into the list of constraints to be used for pagination

Description

public SolrQuery::getFacetOffset ([ string $field_override ] ) : int

Returns an offset into the list of constraints to be used for pagination. Accepts an optional field override

Parameters

field_override

The name of the field to override for.

Return Values

Returns an integer on success and NULL if not set


Returns the facet prefix

  • « SolrQuery::getFacetOffset
  • SolrQuery::getFacetQueries »
  • PHP Manual
  • SolrQuery
  • Returns the facet prefix

SolrQuery::getFacetPrefix

(PECL solr >= 0.9.2)

SolrQuery::getFacetPrefix — Returns the facet prefix

Description

public SolrQuery::getFacetPrefix ([ string $field_override ] ) : string

Returns the facet prefix

Parameters

field_override

The name of the field

Return Values

Returns a string on success and NULL if not set.


Returns all the facet queries

  • « SolrQuery::getFacetPrefix
  • SolrQuery::getFacetSort »
  • PHP Manual
  • SolrQuery
  • Returns all the facet queries

SolrQuery::getFacetQueries

(PECL solr >= 0.9.2)

SolrQuery::getFacetQueries — Returns all the facet queries

Description

public SolrQuery::getFacetQueries ( void ) : array

Returns all the facet queries

Parameters

This function has no parameters.

Return Values

Returns an array on success and NULL if not set.


Returns the facet sort type

  • « SolrQuery::getFacetQueries
  • SolrQuery::getFields »
  • PHP Manual
  • SolrQuery
  • Returns the facet sort type

SolrQuery::getFacetSort

(PECL solr >= 0.9.2)

SolrQuery::getFacetSort — Returns the facet sort type

Description

public SolrQuery::getFacetSort ([ string $field_override ] ) : int

Returns an integer (SolrQuery::FACET_SORT_INDEX or SolrQuery::FACET_SORT_COUNT)

Parameters

field_override

The name of the field

Return Values

Returns an integer (SolrQuery::FACET_SORT_INDEX or SolrQuery::FACET_SORT_COUNT) on success or NULL if not set.


Returns the list of fields that will be returned in the response

  • « SolrQuery::getFacetSort
  • SolrQuery::getFilterQueries »
  • PHP Manual
  • SolrQuery
  • Returns the list of fields that will be returned in the response

SolrQuery::getFields

(PECL solr >= 0.9.2)

SolrQuery::getFields — Returns the list of fields that will be returned in the response

Description

public SolrQuery::getFields ( void ) : array

Returns the list of fields that will be returned in the response

Parameters

This function has no parameters.

Return Values

Returns an array on success and NULL if not set.


Returns an array of filter queries

  • « SolrQuery::getFields
  • SolrQuery::getGroup »
  • PHP Manual
  • SolrQuery
  • Returns an array of filter queries

SolrQuery::getFilterQueries

(PECL solr >= 0.9.2)

SolrQuery::getFilterQueries — Returns an array of filter queries

Description

public SolrQuery::getFilterQueries ( void ) : array

Returns an array of filter queries. These are queries that can be used to restrict the super set of documents that can be returned, without influencing score

Parameters

This function has no parameters.

Return Values

Returns an array on success and NULL if not set.


Returns true if grouping is enabled

  • « SolrQuery::getFilterQueries
  • SolrQuery::getGroupCachePercent »
  • PHP Manual
  • SolrQuery
  • Returns true if grouping is enabled

SolrQuery::getGroup

(PECL solr >= 2.2.0)

SolrQuery::getGroup — Returns true if grouping is enabled

Description

public SolrQuery::getGroup ( void ) : bool

Returns true if grouping is enabled

Parameters

This function has no parameters.

Return Values

See Also

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)


Returns group cache percent value

  • « SolrQuery::getGroup
  • SolrQuery::getGroupFacet »
  • PHP Manual
  • SolrQuery
  • Returns group cache percent value

SolrQuery::getGroupCachePercent

(PECL solr >= 2.2.0)

SolrQuery::getGroupCachePercent — Returns group cache percent value

Description

public SolrQuery::getGroupCachePercent ( void ) : int

Returns group cache percent value

Parameters

This function has no parameters.

Return Values

See Also

  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping


Returns the group.facet parameter value

  • « SolrQuery::getGroupCachePercent
  • SolrQuery::getGroupFields »
  • PHP Manual
  • SolrQuery
  • Returns the group.facet parameter value

SolrQuery::getGroupFacet

(PECL solr >= 2.2.0)

SolrQuery::getGroupFacet — Returns the group.facet parameter value

Description

public SolrQuery::getGroupFacet ( void ) : bool

Returns the group.facet parameter value

Parameters

This function has no parameters.

Return Values

See Also

  • SolrQuery::setGroupFacet() - Sets group.facet parameter


Returns group fields (group.field parameter values)

  • « SolrQuery::getGroupFacet
  • SolrQuery::getGroupFormat »
  • PHP Manual
  • SolrQuery
  • Returns group fields (group.field parameter values)

SolrQuery::getGroupFields

(PECL solr >= 2.2.0)

SolrQuery::getGroupFields — Returns group fields (group.field parameter values)

Description

public SolrQuery::getGroupFields ( void ) : array

Returns group fields (group.field parameter values)

Parameters

This function has no parameters.

Return Values

See Also

  • SolrQuery::addGroupField() - Add a field to be used to group results


Returns the group.format value

  • « SolrQuery::getGroupFields
  • SolrQuery::getGroupFunctions »
  • PHP Manual
  • SolrQuery
  • Returns the group.format value

SolrQuery::getGroupFormat

(PECL solr >= 2.2.0)

SolrQuery::getGroupFormat — Returns the group.format value

Description

public SolrQuery::getGroupFormat ( void ) : string

Returns the group.format value

Parameters

This function has no parameters.

Return Values

See Also

  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter)


Returns group functions (group.func parameter values)

  • « SolrQuery::getGroupFormat
  • SolrQuery::getGroupLimit »
  • PHP Manual
  • SolrQuery
  • Returns group functions (group.func parameter values)

SolrQuery::getGroupFunctions

(PECL solr >= 2.2.0)

SolrQuery::getGroupFunctions — Returns group functions (group.func parameter values)

Description

public SolrQuery::getGroupFunctions ( void ) : array

Returns group functions (group.func parameter values)

Parameters

This function has no parameters.

Return Values

See Also

  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter)


Returns the group.limit value

  • « SolrQuery::getGroupFunctions
  • SolrQuery::getGroupMain »
  • PHP Manual
  • SolrQuery
  • Returns the group.limit value

SolrQuery::getGroupLimit

(PECL solr >= 2.2.0)

SolrQuery::getGroupLimit — Returns the group.limit value

Description

public SolrQuery::getGroupLimit ( void ) : int

Returns the group.limit value

Parameters

This function has no parameters.

Return Values

See Also

  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1


Returns the group.main value

  • « SolrQuery::getGroupLimit
  • SolrQuery::getGroupNGroups »
  • PHP Manual
  • SolrQuery
  • Returns the group.main value

SolrQuery::getGroupMain

(PECL solr >= 2.2.0)

SolrQuery::getGroupMain — Returns the group.main value

Description

public SolrQuery::getGroupMain ( void ) : bool

Returns the group.main value

Parameters

This function has no parameters.

Return Values

See Also

  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple


Returns the group.ngroups value

  • « SolrQuery::getGroupMain
  • SolrQuery::getGroupOffset »
  • PHP Manual
  • SolrQuery
  • Returns the group.ngroups value

SolrQuery::getGroupNGroups

(PECL solr >= 2.2.0)

SolrQuery::getGroupNGroups — Returns the group.ngroups value

Description

public SolrQuery::getGroupNGroups ( void ) : bool

Returns the group.ngroups value

Parameters

This function has no parameters.

Return Values

See Also

  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results


Returns the group.offset value

  • « SolrQuery::getGroupNGroups
  • SolrQuery::getGroupQueries »
  • PHP Manual
  • SolrQuery
  • Returns the group.offset value

SolrQuery::getGroupOffset

(PECL solr >= 2.2.0)

SolrQuery::getGroupOffset — Returns the group.offset value

Description

public SolrQuery::getGroupOffset ( void ) : int

Returns the group.offset value

Parameters

This function has no parameters.

Return Values

See Also

  • SolrQuery::setGroupOffset() - Sets the group.offset parameter


Returns all the group.query parameter values

  • « SolrQuery::getGroupOffset
  • SolrQuery::getGroupSortFields »
  • PHP Manual
  • SolrQuery
  • Returns all the group.query parameter values

SolrQuery::getGroupQueries

(PECL solr >= 2.2.0)

SolrQuery::getGroupQueries — Returns all the group.query parameter values

Description

public SolrQuery::getGroupQueries ( void ) : array

Returns all the group.query parameter values

Parameters

This function has no parameters.

Return Values

array

See Also

  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query


Returns the group.sort value

  • « SolrQuery::getGroupQueries
  • SolrQuery::getGroupTruncate »
  • PHP Manual
  • SolrQuery
  • Returns the group.sort value

SolrQuery::getGroupSortFields

(PECL solr >= 2.2.0)

SolrQuery::getGroupSortFields — Returns the group.sort value

Description

public SolrQuery::getGroupSortFields ( void ) : array

Returns the group.sort value

Parameters

This function has no parameters.

Return Values

See Also

  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter)


Returns the group.truncate value

  • « SolrQuery::getGroupSortFields
  • SolrQuery::getHighlight »
  • PHP Manual
  • SolrQuery
  • Returns the group.truncate value

SolrQuery::getGroupTruncate

(PECL solr >= 2.2.0)

SolrQuery::getGroupTruncate — Returns the group.truncate value

Description

public SolrQuery::getGroupTruncate ( void ) : bool

Returns the group.truncate value

Parameters

This function has no parameters.

Return Values

See Also

  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query


Returns the state of the hl parameter

  • « SolrQuery::getGroupTruncate
  • SolrQuery::getHighlightAlternateField »
  • PHP Manual
  • SolrQuery
  • Returns the state of the hl parameter

SolrQuery::getHighlight

(PECL solr >= 0.9.2)

SolrQuery::getHighlight — Returns the state of the hl parameter

Description

public SolrQuery::getHighlight ( void ) : bool

Returns a boolean indicating whether or not to enable highlighted snippets to be generated in the query response.

Parameters

This function has no parameters.

Return Values

Returns a boolean on success and NULL if not set.


Returns the highlight field to use as backup or default

  • « SolrQuery::getHighlight
  • SolrQuery::getHighlightFields »
  • PHP Manual
  • SolrQuery
  • Returns the highlight field to use as backup or default

SolrQuery::getHighlightAlternateField

(PECL solr >= 0.9.2)

SolrQuery::getHighlightAlternateField — Returns the highlight field to use as backup or default

Description

public SolrQuery::getHighlightAlternateField ([ string $field_override ] ) : string

Returns the highlight field to use as backup or default. It accepts an optional override.

Parameters

field_override

The name of the field

Return Values

Returns a string on success and NULL if not set.


Returns all the fields that Solr should generate highlighted snippets for

  • « SolrQuery::getHighlightAlternateField
  • SolrQuery::getHighlightFormatter »
  • PHP Manual
  • SolrQuery
  • Returns all the fields that Solr should generate highlighted snippets for

SolrQuery::getHighlightFields

(PECL solr >= 0.9.2)

SolrQuery::getHighlightFields — Returns all the fields that Solr should generate highlighted snippets for

Description

public SolrQuery::getHighlightFields ( void ) : array

Returns all the fields that Solr should generate highlighted snippets for

Parameters

This function has no parameters.

Return Values

Returns an array on success and NULL if not set.


Returns the formatter for the highlighted output

  • « SolrQuery::getHighlightFields
  • SolrQuery::getHighlightFragmenter »
  • PHP Manual
  • SolrQuery
  • Returns the formatter for the highlighted output

SolrQuery::getHighlightFormatter

(PECL solr >= 0.9.2)

SolrQuery::getHighlightFormatter — Returns the formatter for the highlighted output

Description

public SolrQuery::getHighlightFormatter ([ string $field_override ] ) : string

Returns the formatter for the highlighted output

Parameters

field_override

The name of the field

Return Values

Returns a string on success and NULL if not set.


Returns the text snippet generator for highlighted text

  • « SolrQuery::getHighlightFormatter
  • SolrQuery::getHighlightFragsize »
  • PHP Manual
  • SolrQuery
  • Returns the text snippet generator for highlighted text

SolrQuery::getHighlightFragmenter

(PECL solr >= 0.9.2)

SolrQuery::getHighlightFragmenter — Returns the text snippet generator for highlighted text

Description

public SolrQuery::getHighlightFragmenter ([ string $field_override ] ) : string

Returns the text snippet generator for highlighted text. Accepts an optional field override.

Parameters

field_override

The name of the field

Return Values

Returns a string on success and NULL if not set.


Returns the number of characters of fragments to consider for highlighting

  • « SolrQuery::getHighlightFragmenter
  • SolrQuery::getHighlightHighlightMultiTerm »
  • PHP Manual
  • SolrQuery
  • Returns the number of characters of fragments to consider for highlighting

SolrQuery::getHighlightFragsize

(PECL solr >= 0.9.2)

SolrQuery::getHighlightFragsize — Returns the number of characters of fragments to consider for highlighting

Description

public SolrQuery::getHighlightFragsize ([ string $field_override ] ) : int

Returns the number of characters of fragments to consider for highlighting. Zero implies no fragmenting. The entire field should be used.

Parameters

field_override

The name of the field

Return Values

Returns an integer on success or NULL if not set.


Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries

  • « SolrQuery::getHighlightFragsize
  • SolrQuery::getHighlightMaxAlternateFieldLength »
  • PHP Manual
  • SolrQuery
  • Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries

SolrQuery::getHighlightHighlightMultiTerm

(PECL solr >= 0.9.2)

SolrQuery::getHighlightHighlightMultiTerm — Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries

Description

public SolrQuery::getHighlightHighlightMultiTerm ( void ) : bool

Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries

Parameters

This function has no parameters.

Return Values

Returns a boolean on success and NULL if not set.


Returns the maximum number of characters of the field to return

  • « SolrQuery::getHighlightHighlightMultiTerm
  • SolrQuery::getHighlightMaxAnalyzedChars »
  • PHP Manual
  • SolrQuery
  • Returns the maximum number of characters of the field to return

SolrQuery::getHighlightMaxAlternateFieldLength

(PECL solr >= 0.9.2)

SolrQuery::getHighlightMaxAlternateFieldLength — Returns the maximum number of characters of the field to return

Description

public SolrQuery::getHighlightMaxAlternateFieldLength ([ string $field_override ] ) : int

Returns the maximum number of characters of the field to return

Parameters

field_override

The name of the field

Return Values

Returns an integer on success and NULL if not set.


Returns the maximum number of characters into a document to look for suitable snippets

  • « SolrQuery::getHighlightMaxAlternateFieldLength
  • SolrQuery::getHighlightMergeContiguous »
  • PHP Manual
  • SolrQuery
  • Returns the maximum number of characters into a document to look for suitable snippets

SolrQuery::getHighlightMaxAnalyzedChars

(PECL solr >= 0.9.2)

SolrQuery::getHighlightMaxAnalyzedChars — Returns the maximum number of characters into a document to look for suitable snippets

Description

public SolrQuery::getHighlightMaxAnalyzedChars ( void ) : int

Returns the maximum number of characters into a document to look for suitable snippets

Parameters

This function has no parameters.

Return Values

Returns an integer on success and NULL if not set.


Returns whether or not the collapse contiguous fragments into a single fragment

  • « SolrQuery::getHighlightMaxAnalyzedChars
  • SolrQuery::getHighlightRegexMaxAnalyzedChars »
  • PHP Manual
  • SolrQuery
  • Returns whether or not the collapse contiguous fragments into a single fragment

SolrQuery::getHighlightMergeContiguous

(PECL solr >= 0.9.2)

SolrQuery::getHighlightMergeContiguous — Returns whether or not the collapse contiguous fragments into a single fragment

Description

public SolrQuery::getHighlightMergeContiguous ([ string $field_override ] ) : bool

Returns whether or not the collapse contiguous fragments into a single fragment. Accepts an optional field override.

Parameters

field_override

The name of the field

Return Values

Returns a boolean on success and NULL if not set.


Returns the maximum number of characters from a field when using the regex fragmenter

  • « SolrQuery::getHighlightMergeContiguous
  • SolrQuery::getHighlightRegexPattern »
  • PHP Manual
  • SolrQuery
  • Returns the maximum number of characters from a field when using the regex fragmenter

SolrQuery::getHighlightRegexMaxAnalyzedChars

(PECL solr >= 0.9.2)

SolrQuery::getHighlightRegexMaxAnalyzedChars — Returns the maximum number of characters from a field when using the regex fragmenter

Description

public SolrQuery::getHighlightRegexMaxAnalyzedChars ( void ) : int

Returns the maximum number of characters from a field when using the regex fragmenter

Parameters

This function has no parameters.

Return Values

Returns an integer on success and NULL if not set.


Returns the regular expression for fragmenting

  • « SolrQuery::getHighlightRegexMaxAnalyzedChars
  • SolrQuery::getHighlightRegexSlop »
  • PHP Manual
  • SolrQuery
  • Returns the regular expression for fragmenting

SolrQuery::getHighlightRegexPattern

(PECL solr >= 0.9.2)

SolrQuery::getHighlightRegexPattern — Returns the regular expression for fragmenting

Description

public SolrQuery::getHighlightRegexPattern ( void ) : string

Returns the regular expression used for fragmenting

Parameters

This function has no parameters.

Return Values

Returns a string on success and NULL if not set.


Returns the deviation factor from the ideal fragment size

  • « SolrQuery::getHighlightRegexPattern
  • SolrQuery::getHighlightRequireFieldMatch »
  • PHP Manual
  • SolrQuery
  • Returns the deviation factor from the ideal fragment size

SolrQuery::getHighlightRegexSlop

(PECL solr >= 0.9.2)

SolrQuery::getHighlightRegexSlop — Returns the deviation factor from the ideal fragment size

Description

public SolrQuery::getHighlightRegexSlop ( void ) : float

Returns the factor by which the regex fragmenter can deviate from the ideal fragment size to accomodate the regular expression

Parameters

This function has no parameters.

Return Values

Returns a double on success and NULL if not set.


Returns if a field will only be highlighted if the query matched in this particular field

  • « SolrQuery::getHighlightRegexSlop
  • SolrQuery::getHighlightSimplePost »
  • PHP Manual
  • SolrQuery
  • Returns if a field will only be highlighted if the query matched in this particular field

SolrQuery::getHighlightRequireFieldMatch

(PECL solr >= 0.9.2)

SolrQuery::getHighlightRequireFieldMatch — Returns if a field will only be highlighted if the query matched in this particular field

Description

public SolrQuery::getHighlightRequireFieldMatch ( void ) : bool

Returns if a field will only be highlighted if the query matched in this particular field.

Parameters

This function has no parameters.

Return Values

Returns a boolean on success and NULL if not set.


Returns the text which appears after a highlighted term

  • « SolrQuery::getHighlightRequireFieldMatch
  • SolrQuery::getHighlightSimplePre »
  • PHP Manual
  • SolrQuery
  • Returns the text which appears after a highlighted term

SolrQuery::getHighlightSimplePost

(PECL solr >= 0.9.2)

SolrQuery::getHighlightSimplePost — Returns the text which appears after a highlighted term

Description

public SolrQuery::getHighlightSimplePost ([ string $field_override ] ) : string

Returns the text which appears after a highlighted term. Accepts an optional field override

Parameters

field_override

The name of the field

Return Values

Returns a string on success and NULL if not set.


Returns the text which appears before a highlighted term

  • « SolrQuery::getHighlightSimplePost
  • SolrQuery::getHighlightSnippets »
  • PHP Manual
  • SolrQuery
  • Returns the text which appears before a highlighted term

SolrQuery::getHighlightSimplePre

(PECL solr >= 0.9.2)

SolrQuery::getHighlightSimplePre — Returns the text which appears before a highlighted term

Description

public SolrQuery::getHighlightSimplePre ([ string $field_override ] ) : string

Returns the text which appears before a highlighted term. Accepts an optional field override

Parameters

field_override

The name of the field

Return Values

Returns a string on success and NULL if not set.


Returns the maximum number of highlighted snippets to generate per field

  • « SolrQuery::getHighlightSimplePre
  • SolrQuery::getHighlightUsePhraseHighlighter »
  • PHP Manual
  • SolrQuery
  • Returns the maximum number of highlighted snippets to generate per field

SolrQuery::getHighlightSnippets

(PECL solr >= 0.9.2)

SolrQuery::getHighlightSnippets — Returns the maximum number of highlighted snippets to generate per field

Description

public SolrQuery::getHighlightSnippets ([ string $field_override ] ) : int

Returns the maximum number of highlighted snippets to generate per field. Accepts an optional field override

Parameters

field_override

The name of the field

Return Values

Returns an integer on success and NULL if not set.


Returns the state of the hl.usePhraseHighlighter parameter

  • « SolrQuery::getHighlightSnippets
  • SolrQuery::getMlt »
  • PHP Manual
  • SolrQuery
  • Returns the state of the hl.usePhraseHighlighter parameter

SolrQuery::getHighlightUsePhraseHighlighter

(PECL solr >= 0.9.2)

SolrQuery::getHighlightUsePhraseHighlighter — Returns the state of the hl.usePhraseHighlighter parameter

Description

public SolrQuery::getHighlightUsePhraseHighlighter ( void ) : bool

Returns whether or not to use SpanScorer to highlight phrase terms only when they appear within the query phrase in the document.

Parameters

This function has no parameters.

Return Values

Returns a boolean on success and NULL if not set.


Returns whether or not MoreLikeThis results should be enabled

  • « SolrQuery::getHighlightUsePhraseHighlighter
  • SolrQuery::getMltBoost »
  • PHP Manual
  • SolrQuery
  • Returns whether or not MoreLikeThis results should be enabled

SolrQuery::getMlt

(PECL solr >= 0.9.2)

SolrQuery::getMlt — Returns whether or not MoreLikeThis results should be enabled

Description

public SolrQuery::getMlt ( void ) : bool

Returns whether or not MoreLikeThis results should be enabled

Parameters

This function has no parameters.

Return Values

Returns a boolean on success and NULL if not set.


Returns whether or not the query will be boosted by the interesting term relevance

  • « SolrQuery::getMlt
  • SolrQuery::getMltCount »
  • PHP Manual
  • SolrQuery
  • Returns whether or not the query will be boosted by the interesting term relevance

SolrQuery::getMltBoost

(PECL solr >= 0.9.2)

SolrQuery::getMltBoost — Returns whether or not the query will be boosted by the interesting term relevance

Description

public SolrQuery::getMltBoost ( void ) : bool

Returns whether or not the query will be boosted by the interesting term relevance

Parameters

This function has no parameters.

Return Values

Returns a boolean on success and NULL if not set.


Returns the number of similar documents to return for each result

  • « SolrQuery::getMltBoost
  • SolrQuery::getMltFields »
  • PHP Manual
  • SolrQuery
  • Returns the number of similar documents to return for each result

SolrQuery::getMltCount

(PECL solr >= 0.9.2)

SolrQuery::getMltCount — Returns the number of similar documents to return for each result

Description

public SolrQuery::getMltCount ( void ) : int

Returns the number of similar documents to return for each result

Parameters

This function has no parameters.

Return Values

Returns an integer on success and NULL if not set.


Returns all the fields to use for similarity

  • « SolrQuery::getMltCount
  • SolrQuery::getMltMaxNumQueryTerms »
  • PHP Manual
  • SolrQuery
  • Returns all the fields to use for similarity

SolrQuery::getMltFields

(PECL solr >= 0.9.2)

SolrQuery::getMltFields — Returns all the fields to use for similarity

Description

public SolrQuery::getMltFields ( void ) : array

Returns all the fields to use for similarity

Parameters

This function has no parameters.

Return Values

Returns an array on success and NULL if not set.


Returns the maximum number of query terms that will be included in any generated query

  • « SolrQuery::getMltFields
  • SolrQuery::getMltMaxNumTokens »
  • PHP Manual
  • SolrQuery
  • Returns the maximum number of query terms that will be included in any generated query

SolrQuery::getMltMaxNumQueryTerms

(PECL solr >= 0.9.2)

SolrQuery::getMltMaxNumQueryTerms — Returns the maximum number of query terms that will be included in any generated query

Description

public SolrQuery::getMltMaxNumQueryTerms ( void ) : int

Returns the maximum number of query terms that will be included in any generated query

Parameters

This function has no parameters.

Return Values

Returns an integer on success and NULL if not set.


Returns the maximum number of tokens to parse in each document field that is not stored with TermVector support

  • « SolrQuery::getMltMaxNumQueryTerms
  • SolrQuery::getMltMaxWordLength »
  • PHP Manual
  • SolrQuery
  • Returns the maximum number of tokens to parse in each document field that is not stored with TermVector support

SolrQuery::getMltMaxNumTokens

(PECL solr >= 0.9.2)

SolrQuery::getMltMaxNumTokens — Returns the maximum number of tokens to parse in each document field that is not stored with TermVector support

Description

public SolrQuery::getMltMaxNumTokens ( void ) : int

Returns the maximum number of tokens to parse in each document field that is not stored with TermVector support

Parameters

This function has no parameters.

Return Values

Returns an integer on success and NULL if not set.


Returns the maximum word length above which words will be ignored

  • « SolrQuery::getMltMaxNumTokens
  • SolrQuery::getMltMinDocFrequency »
  • PHP Manual
  • SolrQuery
  • Returns the maximum word length above which words will be ignored

SolrQuery::getMltMaxWordLength

(PECL solr >= 0.9.2)

SolrQuery::getMltMaxWordLength — Returns the maximum word length above which words will be ignored

Description

public SolrQuery::getMltMaxWordLength ( void ) : int

Returns the maximum word length above which words will be ignored

Parameters

This function has no parameters.

Return Values

Returns an integer on success and NULL if not set.


Returns the treshold frequency at which words will be ignored which do not occur in at least this many docs

  • « SolrQuery::getMltMaxWordLength
  • SolrQuery::getMltMinTermFrequency »
  • PHP Manual
  • SolrQuery
  • Returns the treshold frequency at which words will be ignored which do not occur in at least this many docs

SolrQuery::getMltMinDocFrequency

(PECL solr >= 0.9.2)

SolrQuery::getMltMinDocFrequency — Returns the treshold frequency at which words will be ignored which do not occur in at least this many docs

Description

public SolrQuery::getMltMinDocFrequency ( void ) : int

Returns the treshold frequency at which words will be ignored which do not occur in at least this many docs

Parameters

This function has no parameters.

Return Values

Returns an integer on success and NULL if not set.


Returns the frequency below which terms will be ignored in the source document

  • « SolrQuery::getMltMinDocFrequency
  • SolrQuery::getMltMinWordLength »
  • PHP Manual
  • SolrQuery
  • Returns the frequency below which terms will be ignored in the source document

SolrQuery::getMltMinTermFrequency

(PECL solr >= 0.9.2)

SolrQuery::getMltMinTermFrequency — Returns the frequency below which terms will be ignored in the source document

Description

public SolrQuery::getMltMinTermFrequency ( void ) : int

Returns the frequency below which terms will be ignored in the source document

Parameters

This function has no parameters.

Return Values

Returns an integer on success and NULL if not set.


Returns the minimum word length below which words will be ignored

  • « SolrQuery::getMltMinTermFrequency
  • SolrQuery::getMltQueryFields »
  • PHP Manual
  • SolrQuery
  • Returns the minimum word length below which words will be ignored

SolrQuery::getMltMinWordLength

(PECL solr >= 0.9.2)

SolrQuery::getMltMinWordLength — Returns the minimum word length below which words will be ignored

Description

public SolrQuery::getMltMinWordLength ( void ) : int

Returns the minimum word length below which words will be ignored

Parameters

This function has no parameters.

Return Values

Returns an integer on success and NULL if not set.


Returns the query fields and their boosts

  • « SolrQuery::getMltMinWordLength
  • SolrQuery::getQuery »
  • PHP Manual
  • SolrQuery
  • Returns the query fields and their boosts

SolrQuery::getMltQueryFields

(PECL solr >= 0.9.2)

SolrQuery::getMltQueryFields — Returns the query fields and their boosts

Description

public SolrQuery::getMltQueryFields ( void ) : array

Returns the query fields and their boosts

Parameters

This function has no parameters.

Return Values

Returns an array on success and NULL if not set.


Returns the main query

  • « SolrQuery::getMltQueryFields
  • SolrQuery::getRows »
  • PHP Manual
  • SolrQuery
  • Returns the main query

SolrQuery::getQuery

(PECL solr >= 0.9.2)

SolrQuery::getQuery — Returns the main query

Description

public SolrQuery::getQuery ( void ) : string

Returns the main search query

Parameters

This function has no parameters.

Return Values

Returns a string on success and NULL if not set.


Returns the maximum number of documents

  • « SolrQuery::getQuery
  • SolrQuery::getSortFields »
  • PHP Manual
  • SolrQuery
  • Returns the maximum number of documents

SolrQuery::getRows

(PECL solr >= 0.9.2)

SolrQuery::getRows — Returns the maximum number of documents

Description

public SolrQuery::getRows ( void ) : int

Returns the maximum number of documents from the complete result set to return to the client for every request

Parameters

This function has no parameters.

Return Values

Returns an integer on success and NULL if not set.


Returns all the sort fields

  • « SolrQuery::getRows
  • SolrQuery::getStart »
  • PHP Manual
  • SolrQuery
  • Returns all the sort fields

SolrQuery::getSortFields

(PECL solr >= 0.9.2)

SolrQuery::getSortFields — Returns all the sort fields

Description

public SolrQuery::getSortFields ( void ) : array

Returns all the sort fields

Parameters

This function has no parameters.

Return Values

Returns an array on success and NULL if none of the parameters was set.


Returns the offset in the complete result set

  • « SolrQuery::getSortFields
  • SolrQuery::getStats »
  • PHP Manual
  • SolrQuery
  • Returns the offset in the complete result set

SolrQuery::getStart

(PECL solr >= 0.9.2)

SolrQuery::getStart — Returns the offset in the complete result set

Description

public SolrQuery::getStart ( void ) : int

Returns the offset in the complete result set for the queries where the set of returned documents should begin.

Parameters

This function has no parameters.

Return Values

Returns an integer on success and NULL if not set.


Returns whether or not stats is enabled

  • « SolrQuery::getStart
  • SolrQuery::getStatsFacets »
  • PHP Manual
  • SolrQuery
  • Returns whether or not stats is enabled

SolrQuery::getStats

(PECL solr >= 0.9.2)

SolrQuery::getStats — Returns whether or not stats is enabled

Description

public SolrQuery::getStats ( void ) : bool

Returns whether or not stats is enabled

Parameters

This function has no parameters.

Return Values

Returns a boolean on success and NULL if not set.


Returns all the stats facets that were set

  • « SolrQuery::getStats
  • SolrQuery::getStatsFields »
  • PHP Manual
  • SolrQuery
  • Returns all the stats facets that were set

SolrQuery::getStatsFacets

(PECL solr >= 0.9.2)

SolrQuery::getStatsFacets — Returns all the stats facets that were set

Description

public SolrQuery::getStatsFacets ( void ) : array

Returns all the stats facets that were set

Parameters

This function has no parameters.

Return Values

Returns an array on success and NULL if not set.


Returns all the statistics fields

  • « SolrQuery::getStatsFacets
  • SolrQuery::getTerms »
  • PHP Manual
  • SolrQuery
  • Returns all the statistics fields

SolrQuery::getStatsFields

(PECL solr >= 0.9.2)

SolrQuery::getStatsFields — Returns all the statistics fields

Description

public SolrQuery::getStatsFields ( void ) : array

Returns all the statistics fields

Parameters

This function has no parameters.

Return Values

Returns an array on success and NULL if not set.


Returns whether or not the TermsComponent is enabled

  • « SolrQuery::getStatsFields
  • SolrQuery::getTermsField »
  • PHP Manual
  • SolrQuery
  • Returns whether or not the TermsComponent is enabled

SolrQuery::getTerms

(PECL solr >= 0.9.2)

SolrQuery::getTerms — Returns whether or not the TermsComponent is enabled

Description

public SolrQuery::getTerms ( void ) : bool

Returns whether or not the TermsComponent is enabled

Parameters

This function has no parameters.

Return Values

Returns a boolean on success and NULL if not set.


Returns the field from which the terms are retrieved

  • « SolrQuery::getTerms
  • SolrQuery::getTermsIncludeLowerBound »
  • PHP Manual
  • SolrQuery
  • Returns the field from which the terms are retrieved

SolrQuery::getTermsField

(PECL solr >= 0.9.2)

SolrQuery::getTermsField — Returns the field from which the terms are retrieved

Description

public SolrQuery::getTermsField ( void ) : string

Returns the field from which the terms are retrieved

Parameters

This function has no parameters.

Return Values

Returns a string on success and NULL if not set.


Returns whether or not to include the lower bound in the result set

  • « SolrQuery::getTermsField
  • SolrQuery::getTermsIncludeUpperBound »
  • PHP Manual
  • SolrQuery
  • Returns whether or not to include the lower bound in the result set

SolrQuery::getTermsIncludeLowerBound

(PECL solr >= 0.9.2)

SolrQuery::getTermsIncludeLowerBound — Returns whether or not to include the lower bound in the result set

Description

public SolrQuery::getTermsIncludeLowerBound ( void ) : bool

Returns whether or not to include the lower bound in the result set

Parameters

This function has no parameters.

Return Values

Returns a boolean on success and NULL if not set.


Returns whether or not to include the upper bound term in the result set

  • « SolrQuery::getTermsIncludeLowerBound
  • SolrQuery::getTermsLimit »
  • PHP Manual
  • SolrQuery
  • Returns whether or not to include the upper bound term in the result set

SolrQuery::getTermsIncludeUpperBound

(PECL solr >= 0.9.2)

SolrQuery::getTermsIncludeUpperBound — Returns whether or not to include the upper bound term in the result set

Description

public SolrQuery::getTermsIncludeUpperBound ( void ) : bool

Returns whether or not to include the upper bound term in the result set

Parameters

This function has no parameters.

Return Values

Returns a boolean on success and NULL if not set.


Returns the maximum number of terms Solr should return

  • « SolrQuery::getTermsIncludeUpperBound
  • SolrQuery::getTermsLowerBound »
  • PHP Manual
  • SolrQuery
  • Returns the maximum number of terms Solr should return

SolrQuery::getTermsLimit

(PECL solr >= 0.9.2)

SolrQuery::getTermsLimit — Returns the maximum number of terms Solr should return

Description

public SolrQuery::getTermsLimit ( void ) : int

Returns the maximum number of terms Solr should return

Parameters

This function has no parameters.

Return Values

Returns an integer on success and NULL if not set.


Returns the term to start at

  • « SolrQuery::getTermsLimit
  • SolrQuery::getTermsMaxCount »
  • PHP Manual
  • SolrQuery
  • Returns the term to start at

SolrQuery::getTermsLowerBound

(PECL solr >= 0.9.2)

SolrQuery::getTermsLowerBound — Returns the term to start at

Description

public SolrQuery::getTermsLowerBound ( void ) : string

Returns the term to start at

Parameters

This function has no parameters.

Return Values

Returns a string on success and NULL if not set.


Returns the maximum document frequency

  • « SolrQuery::getTermsLowerBound
  • SolrQuery::getTermsMinCount »
  • PHP Manual
  • SolrQuery
  • Returns the maximum document frequency

SolrQuery::getTermsMaxCount

(PECL solr >= 0.9.2)

SolrQuery::getTermsMaxCount — Returns the maximum document frequency

Description

public SolrQuery::getTermsMaxCount ( void ) : int

Returns the maximum document frequency

Parameters

This function has no parameters.

Return Values

Returns an integer on success and NULL if not set.


Returns the minimum document frequency to return in order to be included

  • « SolrQuery::getTermsMaxCount
  • SolrQuery::getTermsPrefix »
  • PHP Manual
  • SolrQuery
  • Returns the minimum document frequency to return in order to be included

SolrQuery::getTermsMinCount

(PECL solr >= 0.9.2)

SolrQuery::getTermsMinCount — Returns the minimum document frequency to return in order to be included

Description

public SolrQuery::getTermsMinCount ( void ) : int

Returns the minimum document frequency to return in order to be included

Parameters

This function has no parameters.

Return Values

Returns an integer on success and NULL if not set.


Returns the term prefix

  • « SolrQuery::getTermsMinCount
  • SolrQuery::getTermsReturnRaw »
  • PHP Manual
  • SolrQuery
  • Returns the term prefix

SolrQuery::getTermsPrefix

(PECL solr >= 0.9.2)

SolrQuery::getTermsPrefix — Returns the term prefix

Description

public SolrQuery::getTermsPrefix ( void ) : string

Returns the prefix to which matching terms must be restricted. This will restrict matches to only terms that start with the prefix

Parameters

This function has no parameters.

Return Values

Returns a string on success and NULL if not set.


Whether or not to return raw characters

  • « SolrQuery::getTermsPrefix
  • SolrQuery::getTermsSort »
  • PHP Manual
  • SolrQuery
  • Whether or not to return raw characters

SolrQuery::getTermsReturnRaw

(PECL solr >= 0.9.2)

SolrQuery::getTermsReturnRaw — Whether or not to return raw characters

Description

public SolrQuery::getTermsReturnRaw ( void ) : bool

Returns a boolean indicating whether or not to return the raw characters of the indexed term, regardless of if it is human readable

Parameters

This function has no parameters.

Return Values

Returns a boolean on success and NULL if not set.


Returns an integer indicating how terms are sorted

  • « SolrQuery::getTermsReturnRaw
  • SolrQuery::getTermsUpperBound »
  • PHP Manual
  • SolrQuery
  • Returns an integer indicating how terms are sorted

SolrQuery::getTermsSort

(PECL solr >= 0.9.2)

SolrQuery::getTermsSort — Returns an integer indicating how terms are sorted

Description

public SolrQuery::getTermsSort ( void ) : int

SolrQuery::TERMS_SORT_INDEX indicates that the terms are returned by index order. SolrQuery::TERMS_SORT_COUNT implies that the terms are sorted by term frequency (highest count first)

Parameters

This function has no parameters.

Return Values

Returns an integer on success and NULL if not set.


Returns the term to stop at

  • « SolrQuery::getTermsSort
  • SolrQuery::getTimeAllowed »
  • PHP Manual
  • SolrQuery
  • Returns the term to stop at

SolrQuery::getTermsUpperBound

(PECL solr >= 0.9.2)

SolrQuery::getTermsUpperBound — Returns the term to stop at

Description

public SolrQuery::getTermsUpperBound ( void ) : string

Returns the term to stop at

Parameters

This function has no parameters.

Return Values

Returns a string on success and NULL if not set.


Returns the time in milliseconds allowed for the query to finish

  • « SolrQuery::getTermsUpperBound
  • SolrQuery::removeExpandFilterQuery »
  • PHP Manual
  • SolrQuery
  • Returns the time in milliseconds allowed for the query to finish

SolrQuery::getTimeAllowed

(PECL solr >= 0.9.2)

SolrQuery::getTimeAllowed — Returns the time in milliseconds allowed for the query to finish

Description

public SolrQuery::getTimeAllowed ( void ) : int

Returns the time in milliseconds allowed for the query to finish.

Parameters

This function has no parameters.

Return Values

Returns and integer on success and NULL if it is not set.


Removes an expand filter query

  • « SolrQuery::getTimeAllowed
  • SolrQuery::removeExpandSortField »
  • PHP Manual
  • SolrQuery
  • Removes an expand filter query

SolrQuery::removeExpandFilterQuery

(PECL solr >= 2.2.0)

SolrQuery::removeExpandFilterQuery — Removes an expand filter query

Description

public SolrQuery::removeExpandFilterQuery ( string $fq ) : SolrQuery

Removes an expand filter query.

Parameters

fq

Return Values

SolrQuery

See Also

  • SolrQuery::setExpand() - Enables/Disables the Expand Component
  • SolrQuery::addExpandSortField() - Orders the documents within the expanded groups (expand.sort parameter)
  • SolrQuery::removeExpandSortField() - Removes an expand sort field from the expand.sort parameter
  • SolrQuery::setExpandRows() - Sets the number of rows to display in each group (expand.rows). Server Default 5
  • SolrQuery::setExpandQuery() - Sets the expand.q parameter
  • SolrQuery::addExpandFilterQuery() - Overrides main filter query, determines which documents to include in the main group


Removes an expand sort field from the expand.sort parameter

  • « SolrQuery::removeExpandFilterQuery
  • SolrQuery::removeFacetDateField »
  • PHP Manual
  • SolrQuery
  • Removes an expand sort field from the expand.sort parameter

SolrQuery::removeExpandSortField

(PECL solr >= 2.2.0)

SolrQuery::removeExpandSortField — Removes an expand sort field from the expand.sort parameter

Description

public SolrQuery::removeExpandSortField ( string $field ) : SolrQuery

Removes an expand sort field from the expand.sort parameter.

Parameters

field

field name

Return Values

SolrQuery

See Also

  • SolrQuery::setExpand() - Enables/Disables the Expand Component
  • SolrQuery::addExpandSortField() - Orders the documents within the expanded groups (expand.sort parameter)
  • SolrQuery::setExpandRows() - Sets the number of rows to display in each group (expand.rows). Server Default 5
  • SolrQuery::setExpandQuery() - Sets the expand.q parameter
  • SolrQuery::addExpandFilterQuery() - Overrides main filter query, determines which documents to include in the main group
  • SolrQuery::removeExpandFilterQuery() - Removes an expand filter query


Removes one of the facet date fields

  • « SolrQuery::removeExpandSortField
  • SolrQuery::removeFacetDateOther »
  • PHP Manual
  • SolrQuery
  • Removes one of the facet date fields

SolrQuery::removeFacetDateField

(PECL solr >= 0.9.2)

SolrQuery::removeFacetDateField — Removes one of the facet date fields

Description

public SolrQuery::removeFacetDateField ( string $field ) : SolrQuery

The name of the field

Parameters

field

The name of the date field to remove

Return Values

Returns the current SolrQuery object, if the return value is used.


Removes one of the facet.date.other parameters

  • « SolrQuery::removeFacetDateField
  • SolrQuery::removeFacetField »
  • PHP Manual
  • SolrQuery
  • Removes one of the facet.date.other parameters

SolrQuery::removeFacetDateOther

(PECL solr >= 0.9.2)

SolrQuery::removeFacetDateOther — Removes one of the facet.date.other parameters

Description

public SolrQuery::removeFacetDateOther ( string $value [, string $field_override ] ) : SolrQuery

Removes one of the facet.date.other parameters

Parameters

value

The value

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.


Removes one of the facet.date parameters

  • « SolrQuery::removeFacetDateOther
  • SolrQuery::removeFacetQuery »
  • PHP Manual
  • SolrQuery
  • Removes one of the facet.date parameters

SolrQuery::removeFacetField

(PECL solr >= 0.9.2)

SolrQuery::removeFacetField — Removes one of the facet.date parameters

Description

public SolrQuery::removeFacetField ( string $field ) : SolrQuery

Removes one of the facet.date parameters

Parameters

field

The name of the field

Return Values

Returns the current SolrQuery object, if the return value is used.


Removes one of the facet.query parameters

  • « SolrQuery::removeFacetField
  • SolrQuery::removeField »
  • PHP Manual
  • SolrQuery
  • Removes one of the facet.query parameters

SolrQuery::removeFacetQuery

(PECL solr >= 0.9.2)

SolrQuery::removeFacetQuery — Removes one of the facet.query parameters

Description

public SolrQuery::removeFacetQuery ( string $value ) : SolrQuery

Removes one of the facet.query parameters.

Parameters

value

The value

Return Values

Returns the current SolrQuery object, if the return value is used.


Removes a field from the list of fields

  • « SolrQuery::removeFacetQuery
  • SolrQuery::removeFilterQuery »
  • PHP Manual
  • SolrQuery
  • Removes a field from the list of fields

SolrQuery::removeField

(PECL solr >= 0.9.2)

SolrQuery::removeField — Removes a field from the list of fields

Description

public SolrQuery::removeField ( string $field ) : SolrQuery

Removes a field from the list of fields

Parameters

field

Name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.


Removes a filter query

  • « SolrQuery::removeField
  • SolrQuery::removeHighlightField »
  • PHP Manual
  • SolrQuery
  • Removes a filter query

SolrQuery::removeFilterQuery

(PECL solr >= 0.9.2)

SolrQuery::removeFilterQuery — Removes a filter query

Description

public SolrQuery::removeFilterQuery ( string $fq ) : SolrQuery

Removes a filter query.

Parameters

fq

The filter query to remove

Return Values

Returns the current SolrQuery object, if the return value is used.


Removes one of the fields used for highlighting

  • « SolrQuery::removeFilterQuery
  • SolrQuery::removeMltField »
  • PHP Manual
  • SolrQuery
  • Removes one of the fields used for highlighting

SolrQuery::removeHighlightField

(PECL solr >= 0.9.2)

SolrQuery::removeHighlightField — Removes one of the fields used for highlighting

Description

public SolrQuery::removeHighlightField ( string $field ) : SolrQuery

Removes one of the fields used for highlighting.

Parameters

field

The name of the field

Return Values

Returns the current SolrQuery object, if the return value is used.


Removes one of the moreLikeThis fields

  • « SolrQuery::removeHighlightField
  • SolrQuery::removeMltQueryField »
  • PHP Manual
  • SolrQuery
  • Removes one of the moreLikeThis fields

SolrQuery::removeMltField

(PECL solr >= 0.9.2)

SolrQuery::removeMltField — Removes one of the moreLikeThis fields

Description

public SolrQuery::removeMltField ( string $field ) : SolrQuery

Removes one of the moreLikeThis fields.

Parameters

field

Name of the field

Return Values

Returns the current SolrQuery object, if the return value is used.


Removes one of the moreLikeThis query fields

  • « SolrQuery::removeMltField
  • SolrQuery::removeSortField »
  • PHP Manual
  • SolrQuery
  • Removes one of the moreLikeThis query fields

SolrQuery::removeMltQueryField

(PECL solr >= 0.9.2)

SolrQuery::removeMltQueryField — Removes one of the moreLikeThis query fields

Description

public SolrQuery::removeMltQueryField ( string $queryField ) : SolrQuery

Removes one of the moreLikeThis query fields.

Parameters

queryField

The query field

Return Values

Returns the current SolrQuery object, if the return value is used.


Removes one of the sort fields

  • « SolrQuery::removeMltQueryField
  • SolrQuery::removeStatsFacet »
  • PHP Manual
  • SolrQuery
  • Removes one of the sort fields

SolrQuery::removeSortField

(PECL solr >= 0.9.2)

SolrQuery::removeSortField — Removes one of the sort fields

Description

public SolrQuery::removeSortField ( string $field ) : SolrQuery

Removes one of the sort fields

Parameters

field

The name of the field

Return Values

Returns the current SolrQuery object, if the return value is used.


Removes one of the stats.facet parameters

  • « SolrQuery::removeSortField
  • SolrQuery::removeStatsField »
  • PHP Manual
  • SolrQuery
  • Removes one of the stats.facet parameters

SolrQuery::removeStatsFacet

(PECL solr >= 0.9.2)

SolrQuery::removeStatsFacet — Removes one of the stats.facet parameters

Description

public SolrQuery::removeStatsFacet ( string $value ) : SolrQuery

Removes one of the stats.facet parameters

Parameters

value

The value

Return Values

Returns the current SolrQuery object, if the return value is used.


Removes one of the stats.field parameters

  • « SolrQuery::removeStatsFacet
  • SolrQuery::setEchoHandler »
  • PHP Manual
  • SolrQuery
  • Removes one of the stats.field parameters

SolrQuery::removeStatsField

(PECL solr >= 0.9.2)

SolrQuery::removeStatsField — Removes one of the stats.field parameters

Description

public SolrQuery::removeStatsField ( string $field ) : SolrQuery

Removes one of the stats.field parameters

Parameters

field

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.


Toggles the echoHandler parameter

  • « SolrQuery::removeStatsField
  • SolrQuery::setEchoParams »
  • PHP Manual
  • SolrQuery
  • Toggles the echoHandler parameter

SolrQuery::setEchoHandler

(PECL solr >= 0.9.2)

SolrQuery::setEchoHandler — Toggles the echoHandler parameter

Description

public SolrQuery::setEchoHandler ( bool $flag ) : SolrQuery

If set to true, Solr places the name of the handle used in the response to the client for debugging purposes.

Parameters

flag

TRUE or FALSE

Return Values

Returns the current SolrQuery object, if the return value is used.


Determines what kind of parameters to include in the response

  • « SolrQuery::setEchoHandler
  • SolrQuery::setExpand »
  • PHP Manual
  • SolrQuery
  • Determines what kind of parameters to include in the response

SolrQuery::setEchoParams

(PECL solr >= 0.9.2)

SolrQuery::setEchoParams — Determines what kind of parameters to include in the response

Description

public SolrQuery::setEchoParams ( string $type ) : SolrQuery

Instructs Solr what kinds of Request parameters should be included in the response for debugging purposes, legal values include:

- none - don't include any request parameters for debugging
- explicit - include the parameters explicitly specified by the client in the request
- all - include all parameters involved in this request, either specified explicitly by the client, or implicit because of the request handler configuration.

Parameters

type

The type of parameters to include

Return Values

Returns the current SolrQuery object, if the return value is used.


Enables/Disables the Expand Component

  • « SolrQuery::setEchoParams
  • SolrQuery::setExpandQuery »
  • PHP Manual
  • SolrQuery
  • Enables/Disables the Expand Component

SolrQuery::setExpand

(PECL solr >= 2.2.0)

SolrQuery::setExpand — Enables/Disables the Expand Component

Description

public SolrQuery::setExpand ( bool $value ) : SolrQuery

Enables/Disables the Expand Component.

Parameters

value

Bool flag

Return Values

SolrQuery

Examples

Example #1 SolrQuery::setExpand() example

<?php

$query = new SolrQuery('lucene');

$query
    ->setExpand(true)
    ->setExpandRows(50)
    ->setExpandQuery('text:product')
    ->addExpandFilterQuery('manu:apple')
    ->addExpandFilterQuery('inStock:true')
    ->addExpandSortField('score', SolrQuery::ORDER_DESC)
    ->addExpandSortField('title', SolrQuery::ORDER_ASC);

echo $query.PHP_EOL;

?>

The above example will output something similar to:

q=lucene&expand=true&expand.rows=50&expand.q=text:product&expand.fq=manu:apple&expand.fq=inStock:true&expand.sort=score desc,title asc

See Also

  • SolrQuery::addExpandSortField() - Orders the documents within the expanded groups (expand.sort parameter)
  • SolrQuery::removeExpandSortField() - Removes an expand sort field from the expand.sort parameter
  • SolrQuery::setExpandRows() - Sets the number of rows to display in each group (expand.rows). Server Default 5
  • SolrQuery::setExpandQuery() - Sets the expand.q parameter
  • SolrQuery::addExpandFilterQuery() - Overrides main filter query, determines which documents to include in the main group
  • SolrQuery::removeExpandFilterQuery() - Removes an expand filter query


Sets the expand.q parameter

  • « SolrQuery::setExpand
  • SolrQuery::setExpandRows »
  • PHP Manual
  • SolrQuery
  • Sets the expand.q parameter

SolrQuery::setExpandQuery

(PECL solr >= 2.2.0)

SolrQuery::setExpandQuery — Sets the expand.q parameter

Description

public SolrQuery::setExpandQuery ( string $q ) : SolrQuery

Sets the expand.q parameter.

Overrides the main q parameter, determines which documents to include in the main group.

Parameters

q

Return Values

SolrQuery

See Also

  • SolrQuery::setExpand() - Enables/Disables the Expand Component
  • SolrQuery::addExpandSortField() - Orders the documents within the expanded groups (expand.sort parameter)
  • SolrQuery::removeExpandSortField() - Removes an expand sort field from the expand.sort parameter
  • SolrQuery::setExpandRows() - Sets the number of rows to display in each group (expand.rows). Server Default 5
  • SolrQuery::addExpandFilterQuery() - Overrides main filter query, determines which documents to include in the main group
  • SolrQuery::removeExpandFilterQuery() - Removes an expand filter query


Sets the number of rows to display in each group (expand.rows). Server Default 5

  • « SolrQuery::setExpandQuery
  • SolrQuery::setExplainOther »
  • PHP Manual
  • SolrQuery
  • Sets the number of rows to display in each group (expand.rows). Server Default 5

SolrQuery::setExpandRows

(PECL solr >= 2.2.0)

SolrQuery::setExpandRows — Sets the number of rows to display in each group (expand.rows). Server Default 5

Description

public SolrQuery::setExpandRows ( int $value ) : SolrQuery

Sets the number of rows to display in each group (expand.rows). Server Default 5

Parameters

value

Return Values

SolrQuery

See Also

  • SolrQuery::setExpand() - Enables/Disables the Expand Component
  • SolrQuery::addExpandSortField() - Orders the documents within the expanded groups (expand.sort parameter)
  • SolrQuery::removeExpandSortField() - Removes an expand sort field from the expand.sort parameter
  • SolrQuery::setExpandQuery() - Sets the expand.q parameter
  • SolrQuery::addExpandFilterQuery() - Overrides main filter query, determines which documents to include in the main group
  • SolrQuery::removeExpandFilterQuery() - Removes an expand filter query


Sets the explainOther common query parameter

  • « SolrQuery::setExpandRows
  • SolrQuery::setFacet »
  • PHP Manual
  • SolrQuery
  • Sets the explainOther common query parameter

SolrQuery::setExplainOther

(PECL solr >= 0.9.2)

SolrQuery::setExplainOther — Sets the explainOther common query parameter

Description

public SolrQuery::setExplainOther ( string $query ) : SolrQuery

Sets the explainOther common query parameter

Parameters

query

The Lucene query to identify a set of documents

Return Values

Returns the current SolrQuery object, if the return value is used.


Maps to the facet parameter. Enables or disables facetting

  • « SolrQuery::setExplainOther
  • SolrQuery::setFacetDateEnd »
  • PHP Manual
  • SolrQuery
  • Maps to the facet parameter. Enables or disables facetting

SolrQuery::setFacet

(PECL solr >= 0.9.2)

SolrQuery::setFacet — Maps to the facet parameter. Enables or disables facetting

Description

public SolrQuery::setFacet ( bool $flag ) : SolrQuery

Enables or disables faceting.

Parameters

value

TRUE enables faceting and FALSE disables it.

Return Values

Returns the current SolrQuery object, if the return value is used.


Maps to facet.date.end

  • « SolrQuery::setFacet
  • SolrQuery::setFacetDateGap »
  • PHP Manual
  • SolrQuery
  • Maps to facet.date.end

SolrQuery::setFacetDateEnd

(PECL solr >= 0.9.2)

SolrQuery::setFacetDateEnd — Maps to facet.date.end

Description

public SolrQuery::setFacetDateEnd ( string $value [, string $field_override ] ) : SolrQuery

Maps to facet.date.end

Parameters

value

See facet.date.end

field_override

Name of the field

Return Values

Returns the current SolrQuery object, if the return value is used.


Maps to facet.date.gap

  • « SolrQuery::setFacetDateEnd
  • SolrQuery::setFacetDateHardEnd »
  • PHP Manual
  • SolrQuery
  • Maps to facet.date.gap

SolrQuery::setFacetDateGap

(PECL solr >= 0.9.2)

SolrQuery::setFacetDateGap — Maps to facet.date.gap

Description

public SolrQuery::setFacetDateGap ( string $value [, string $field_override ] ) : SolrQuery

Maps to facet.date.gap

Parameters

value

See facet.date.gap

field_override

The name of the field

Return Values

Returns the current SolrQuery object, if the return value is used.


Maps to facet.date.hardend

  • « SolrQuery::setFacetDateGap
  • SolrQuery::setFacetDateStart »
  • PHP Manual
  • SolrQuery
  • Maps to facet.date.hardend

SolrQuery::setFacetDateHardEnd

(PECL solr >= 0.9.2)

SolrQuery::setFacetDateHardEnd — Maps to facet.date.hardend

Description

public SolrQuery::setFacetDateHardEnd ( bool $value [, string $field_override ] ) : SolrQuery

Maps to facet.date.hardend

Parameters

value

See facet.date.hardend

field_override

The name of the field

Return Values

Returns the current SolrQuery object, if the return value is used.


Maps to facet.date.start

  • « SolrQuery::setFacetDateHardEnd
  • SolrQuery::setFacetEnumCacheMinDefaultFrequency »
  • PHP Manual
  • SolrQuery
  • Maps to facet.date.start

SolrQuery::setFacetDateStart

(PECL solr >= 0.9.2)

SolrQuery::setFacetDateStart — Maps to facet.date.start

Description

public SolrQuery::setFacetDateStart ( string $value [, string $field_override ] ) : SolrQuery

Maps to facet.date.start

Parameters

value

See facet.date.start

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.


Sets the minimum document frequency used for determining term count

  • « SolrQuery::setFacetDateStart
  • SolrQuery::setFacetLimit »
  • PHP Manual
  • SolrQuery
  • Sets the minimum document frequency used for determining term count

SolrQuery::setFacetEnumCacheMinDefaultFrequency

(PECL solr >= 0.9.2)

SolrQuery::setFacetEnumCacheMinDefaultFrequency — Sets the minimum document frequency used for determining term count

Description

public SolrQuery::setFacetEnumCacheMinDefaultFrequency ( int $frequency [, string $field_override ] ) : SolrQuery

Sets the minimum document frequency used for determining term count

Parameters

value

The minimum frequency

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.


Maps to facet.limit

  • « SolrQuery::setFacetEnumCacheMinDefaultFrequency
  • SolrQuery::setFacetMethod »
  • PHP Manual
  • SolrQuery
  • Maps to facet.limit

SolrQuery::setFacetLimit

(PECL solr >= 0.9.2)

SolrQuery::setFacetLimit — Maps to facet.limit

Description

public SolrQuery::setFacetLimit ( int $limit [, string $field_override ] ) : SolrQuery

Maps to facet.limit. Sets the maximum number of constraint counts that should be returned for the facet fields.

Parameters

limit

The maximum number of constraint counts

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.


Specifies the type of algorithm to use when faceting a field

  • « SolrQuery::setFacetLimit
  • SolrQuery::setFacetMinCount »
  • PHP Manual
  • SolrQuery
  • Specifies the type of algorithm to use when faceting a field

SolrQuery::setFacetMethod

(PECL solr >= 0.9.2)

SolrQuery::setFacetMethod — Specifies the type of algorithm to use when faceting a field

Description

public SolrQuery::setFacetMethod ( string $method [, string $field_override ] ) : SolrQuery

Specifies the type of algorithm to use when faceting a field. This method accepts optional field override.

Parameters

method

The method to use.

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.


Maps to facet.mincount

  • « SolrQuery::setFacetMethod
  • SolrQuery::setFacetMissing »
  • PHP Manual
  • SolrQuery
  • Maps to facet.mincount

SolrQuery::setFacetMinCount

(PECL solr >= 0.9.2)

SolrQuery::setFacetMinCount — Maps to facet.mincount

Description

public SolrQuery::setFacetMinCount ( int $mincount [, string $field_override ] ) : SolrQuery

Sets the minimum counts for facet fields that should be included in the response

Parameters

mincount

The minimum count

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.


Maps to facet.missing

  • « SolrQuery::setFacetMinCount
  • SolrQuery::setFacetOffset »
  • PHP Manual
  • SolrQuery
  • Maps to facet.missing

SolrQuery::setFacetMissing

(PECL solr >= 0.9.2)

SolrQuery::setFacetMissing — Maps to facet.missing

Description

public SolrQuery::setFacetMissing ( bool $flag [, string $field_override ] ) : SolrQuery

Used to indicate that in addition to the Term-based constraints of a facet field, a count of all matching results which have no value for the field should be computed

Parameters

flag

TRUE turns this feature on. FALSE disables it.

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.


Sets the offset into the list of constraints to allow for pagination

  • « SolrQuery::setFacetMissing
  • SolrQuery::setFacetPrefix »
  • PHP Manual
  • SolrQuery
  • Sets the offset into the list of constraints to allow for pagination

SolrQuery::setFacetOffset

(PECL solr >= 0.9.2)

SolrQuery::setFacetOffset — Sets the offset into the list of constraints to allow for pagination

Description

public SolrQuery::setFacetOffset ( int $offset [, string $field_override ] ) : SolrQuery

Sets the offset into the list of constraints to allow for pagination.

Parameters

offset

The offset

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.


Specifies a string prefix with which to limits the terms on which to facet

  • « SolrQuery::setFacetOffset
  • SolrQuery::setFacetSort »
  • PHP Manual
  • SolrQuery
  • Specifies a string prefix with which to limits the terms on which to facet

SolrQuery::setFacetPrefix

(PECL solr >= 0.9.2)

SolrQuery::setFacetPrefix — Specifies a string prefix with which to limits the terms on which to facet

Description

public SolrQuery::setFacetPrefix ( string $prefix [, string $field_override ] ) : SolrQuery

Specifies a string prefix with which to limits the terms on which to facet.

Parameters

prefix

The prefix string

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.


Determines the ordering of the facet field constraints

  • « SolrQuery::setFacetPrefix
  • SolrQuery::setGroup »
  • PHP Manual
  • SolrQuery
  • Determines the ordering of the facet field constraints

SolrQuery::setFacetSort

(PECL solr >= 0.9.2)

SolrQuery::setFacetSort — Determines the ordering of the facet field constraints

Description

public SolrQuery::setFacetSort ( int $facetSort [, string $field_override ] ) : SolrQuery

Determines the ordering of the facet field constraints

Parameters

facetSort

Use SolrQuery::FACET_SORT_INDEX for sorting by index order or SolrQuery::FACET_SORT_COUNT for sorting by count.

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.


Enable/Disable result grouping (group parameter)

  • « SolrQuery::setFacetSort
  • SolrQuery::setGroupCachePercent »
  • PHP Manual
  • SolrQuery
  • Enable/Disable result grouping (group parameter)

SolrQuery::setGroup

(PECL solr >= 2.2.0)

SolrQuery::setGroup — Enable/Disable result grouping (group parameter)

Description

public SolrQuery::setGroup ( bool $value ) : SolrQuery

Enable/Disable result grouping (group parameter)

Parameters

value

Return Values

See Also

  • SolrQuery::getGroup() - Returns true if grouping is enabled
  • SolrQuery::addGroupField() - Add a field to be used to group results
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter)
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter)
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter)
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping


Enables caching for result grouping

  • « SolrQuery::setGroup
  • SolrQuery::setGroupFacet »
  • PHP Manual
  • SolrQuery
  • Enables caching for result grouping

SolrQuery::setGroupCachePercent

(PECL solr >= 2.2.0)

SolrQuery::setGroupCachePercent — Enables caching for result grouping

Description

public SolrQuery::setGroupCachePercent ( int $percent ) : SolrQuery

Setting this parameter to a number greater than 0 enables caching for result grouping. Result Grouping executes two searches; this option caches the second search. The server default value is 0. Testing has shown that group caching only improves search time with Boolean, wildcard, and fuzzy queries. For simple queries like term or "match all" queries, group caching degrades performance. group.cache.percent parameter

Parameters

percent

Return Values

Errors/Exceptions

Emits SolrIllegalArgumentException in case of an invalid parameter was passed.

See Also

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter)
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter)
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter)


Sets group.facet parameter

  • « SolrQuery::setGroupCachePercent
  • SolrQuery::setGroupFormat »
  • PHP Manual
  • SolrQuery
  • Sets group.facet parameter

SolrQuery::setGroupFacet

(PECL solr >= 2.2.0)

SolrQuery::setGroupFacet — Sets group.facet parameter

Description

public SolrQuery::setGroupFacet ( bool $value ) : SolrQuery

Determines whether to compute grouped facets for the field facets specified in facet.field parameters. Grouped facets are computed based on the first specified group.

Parameters

value

Return Values

See Also

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter)
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter)
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter)
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping


Sets the group format, result structure (group.format parameter)

  • « SolrQuery::setGroupFacet
  • SolrQuery::setGroupLimit »
  • PHP Manual
  • SolrQuery
  • Sets the group format, result structure (group.format parameter)

SolrQuery::setGroupFormat

(PECL solr >= 2.2.0)

SolrQuery::setGroupFormat — Sets the group format, result structure (group.format parameter)

Description

public SolrQuery::setGroupFormat ( string $value ) : SolrQuery

Sets the group.format parameter. If this parameter is set to simple, the grouped documents are presented in a single flat list, and the start and rows parameters affect the numbers of documents instead of groups. Accepts: grouped/simple

Parameters

value

Return Values

See Also

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter)
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter)
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping


Specifies the number of results to return for each group. The server default value is 1

  • « SolrQuery::setGroupFormat
  • SolrQuery::setGroupMain »
  • PHP Manual
  • SolrQuery
  • Specifies the number of results to return for each group. The server default value is 1

SolrQuery::setGroupLimit

(PECL solr >= 2.2.0)

SolrQuery::setGroupLimit — Specifies the number of results to return for each group. The server default value is 1

Description

public SolrQuery::setGroupLimit ( int $value ) : SolrQuery

Specifies the number of results to return for each group. The server default value is 1.

Parameters

value

Return Values

See Also

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter)
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter)
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter)
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping


If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple

  • « SolrQuery::setGroupLimit
  • SolrQuery::setGroupNGroups »
  • PHP Manual
  • SolrQuery
  • If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple

SolrQuery::setGroupMain

(PECL solr >= 2.2.0)

SolrQuery::setGroupMain — If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple

Description

public SolrQuery::setGroupMain ( string $value ) : SolrQuery

If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple.

Parameters

value

Return Values

See Also

See Also

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter)
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter)
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter
  • SolrQuery::setGroupMain()
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter)
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping


If true, Solr includes the number of groups that have matched the query in the results

  • « SolrQuery::setGroupMain
  • SolrQuery::setGroupOffset »
  • PHP Manual
  • SolrQuery
  • If true, Solr includes the number of groups that have matched the query in the results

SolrQuery::setGroupNGroups

(PECL solr >= 2.2.0)

SolrQuery::setGroupNGroups — If true, Solr includes the number of groups that have matched the query in the results

Description

public SolrQuery::setGroupNGroups ( bool $value ) : SolrQuery

If true, Solr includes the number of groups that have matched the query in the results.

Parameters

value

Return Values

See Also

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter)
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter)
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter)
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping


Sets the group.offset parameter

  • « SolrQuery::setGroupNGroups
  • SolrQuery::setGroupTruncate »
  • PHP Manual
  • SolrQuery
  • Sets the group.offset parameter

SolrQuery::setGroupOffset

(PECL solr >= 2.2.0)

SolrQuery::setGroupOffset — Sets the group.offset parameter

Description

public SolrQuery::setGroupOffset ( int $value ) : SolrQuery

Sets the group.offset parameter.

Parameters

value

Return Values

See Also

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter)
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter)
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter)
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping


If true, facet counts are based on the most relevant document of each group matching the query

  • « SolrQuery::setGroupOffset
  • SolrQuery::setHighlight »
  • PHP Manual
  • SolrQuery
  • If true, facet counts are based on the most relevant document of each group matching the query

SolrQuery::setGroupTruncate

(PECL solr >= 2.2.0)

SolrQuery::setGroupTruncate — If true, facet counts are based on the most relevant document of each group matching the query

Description

public SolrQuery::setGroupTruncate ( bool $value ) : SolrQuery

If true, facet counts are based on the most relevant document of each group matching the query. The server default value is false. group.truncate parameter

Parameters

value

Return Values

See Also

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter)
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter)
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter)
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping


Enables or disables highlighting

  • « SolrQuery::setGroupTruncate
  • SolrQuery::setHighlightAlternateField »
  • PHP Manual
  • SolrQuery
  • Enables or disables highlighting

SolrQuery::setHighlight

(PECL solr >= 0.9.2)

SolrQuery::setHighlight — Enables or disables highlighting

Description

public SolrQuery::setHighlight ( bool $flag ) : SolrQuery

Setting it to TRUE enables highlighted snippets to be generated in the query response.

Setting it to FALSE disables highlighting

Parameters

flag

Enable or disable highlighting

Return Values

Returns the current SolrQuery object, if the return value is used.


Specifies the backup field to use

  • « SolrQuery::setHighlight
  • SolrQuery::setHighlightFormatter »
  • PHP Manual
  • SolrQuery
  • Specifies the backup field to use

SolrQuery::setHighlightAlternateField

(PECL solr >= 0.9.2)

SolrQuery::setHighlightAlternateField — Specifies the backup field to use

Description

public SolrQuery::setHighlightAlternateField ( string $field [, string $field_override ] ) : SolrQuery

If a snippet cannot be generated because there were no matching terms, one can specify a field to use as the backup or default summary

Parameters

field

The name of the backup field

field_override

The name of the field we are overriding this setting for.

Return Values

Returns the current SolrQuery object, if the return value is used.


Specify a formatter for the highlight output

  • « SolrQuery::setHighlightAlternateField
  • SolrQuery::setHighlightFragmenter »
  • PHP Manual
  • SolrQuery
  • Specify a formatter for the highlight output

SolrQuery::setHighlightFormatter

(PECL solr >= 0.9.2)

SolrQuery::setHighlightFormatter — Specify a formatter for the highlight output

Description

public SolrQuery::setHighlightFormatter ( string $formatter [, string $field_override ] ) : SolrQuery

Specify a formatter for the highlight output.

Parameters

formatter

Currently the only legal value is "simple"

field_override

The name of the field.


Sets a text snippet generator for highlighted text

  • « SolrQuery::setHighlightFormatter
  • SolrQuery::setHighlightFragsize »
  • PHP Manual
  • SolrQuery
  • Sets a text snippet generator for highlighted text

SolrQuery::setHighlightFragmenter

(PECL solr >= 0.9.2)

SolrQuery::setHighlightFragmenter — Sets a text snippet generator for highlighted text

Description

public SolrQuery::setHighlightFragmenter ( string $fragmenter [, string $field_override ] ) : SolrQuery

Specify a text snippet generator for highlighted text.

Parameters

fragmenter

The standard fragmenter is gap. Another option is regex, which tries to create fragments that resembles a certain regular expression

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.


The size of fragments to consider for highlighting

  • « SolrQuery::setHighlightFragmenter
  • SolrQuery::setHighlightHighlightMultiTerm »
  • PHP Manual
  • SolrQuery
  • The size of fragments to consider for highlighting

SolrQuery::setHighlightFragsize

(PECL solr >= 0.9.2)

SolrQuery::setHighlightFragsize — The size of fragments to consider for highlighting

Description

public SolrQuery::setHighlightFragsize ( int $size [, string $field_override ] ) : SolrQuery

Sets the size, in characters, of fragments to consider for highlighting. "0" indicates that the whole field value should be used (no fragmenting).

Parameters

size

The size, in characters, of fragments to consider for highlighting

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.


Use SpanScorer to highlight phrase terms

  • « SolrQuery::setHighlightFragsize
  • SolrQuery::setHighlightMaxAlternateFieldLength »
  • PHP Manual
  • SolrQuery
  • Use SpanScorer to highlight phrase terms

SolrQuery::setHighlightHighlightMultiTerm

(PECL solr >= 0.9.2)

SolrQuery::setHighlightHighlightMultiTerm — Use SpanScorer to highlight phrase terms

Description

public SolrQuery::setHighlightHighlightMultiTerm ( bool $flag ) : SolrQuery

Use SpanScorer to highlight phrase terms only when they appear within the query phrase in the document.

Parameters

flag

Whether or not to use SpanScorer to highlight phrase terms only when they appear within the query phrase in the document.

Return Values

Returns the current SolrQuery object, if the return value is used.


Sets the maximum number of characters of the field to return

  • « SolrQuery::setHighlightHighlightMultiTerm
  • SolrQuery::setHighlightMaxAnalyzedChars »
  • PHP Manual
  • SolrQuery
  • Sets the maximum number of characters of the field to return

SolrQuery::setHighlightMaxAlternateFieldLength

(PECL solr >= 0.9.2)

SolrQuery::setHighlightMaxAlternateFieldLength — Sets the maximum number of characters of the field to return

Description

public SolrQuery::setHighlightMaxAlternateFieldLength ( int $fieldLength [, string $field_override ] ) : SolrQuery

If SolrQuery::setHighlightAlternateField() was passed the value TRUE, this parameter specifies the maximum number of characters of the field to return

Any value less than or equal to 0 means unlimited.

Parameters

fieldLength

The length of the field

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.


Specifies the number of characters into a document to look for suitable snippets

  • « SolrQuery::setHighlightMaxAlternateFieldLength
  • SolrQuery::setHighlightMergeContiguous »
  • PHP Manual
  • SolrQuery
  • Specifies the number of characters into a document to look for suitable snippets

SolrQuery::setHighlightMaxAnalyzedChars

(PECL solr >= 0.9.2)

SolrQuery::setHighlightMaxAnalyzedChars — Specifies the number of characters into a document to look for suitable snippets

Description

public SolrQuery::setHighlightMaxAnalyzedChars ( int $value ) : SolrQuery

Specifies the number of characters into a document to look for suitable snippets

Parameters

value

The number of characters into a document to look for suitable snippets

Return Values

Returns the current SolrQuery object, if the return value is used.


Whether or not to collapse contiguous fragments into a single fragment

  • « SolrQuery::setHighlightMaxAnalyzedChars
  • SolrQuery::setHighlightRegexMaxAnalyzedChars »
  • PHP Manual
  • SolrQuery
  • Whether or not to collapse contiguous fragments into a single fragment

SolrQuery::setHighlightMergeContiguous

(PECL solr >= 0.9.2)

SolrQuery::setHighlightMergeContiguous — Whether or not to collapse contiguous fragments into a single fragment

Description

public SolrQuery::setHighlightMergeContiguous ( bool $flag [, string $field_override ] ) : SolrQuery

Whether or not to collapse contiguous fragments into a single fragment

Parameters

value

Whether or not to collapse contiguous fragments into a single fragment

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.


Specify the maximum number of characters to analyze

  • « SolrQuery::setHighlightMergeContiguous
  • SolrQuery::setHighlightRegexPattern »
  • PHP Manual
  • SolrQuery
  • Specify the maximum number of characters to analyze

SolrQuery::setHighlightRegexMaxAnalyzedChars

(PECL solr >= 0.9.2)

SolrQuery::setHighlightRegexMaxAnalyzedChars — Specify the maximum number of characters to analyze

Description

public SolrQuery::setHighlightRegexMaxAnalyzedChars ( int $maxAnalyzedChars ) : SolrQuery

Specify the maximum number of characters to analyze from a field when using the regex fragmenter

Parameters

maxAnalyzedChars

The maximum number of characters to analyze from a field when using the regex fragmenter

Return Values

Returns the current SolrQuery object, if the return value is used.


Specify the regular expression for fragmenting

  • « SolrQuery::setHighlightRegexMaxAnalyzedChars
  • SolrQuery::setHighlightRegexSlop »
  • PHP Manual
  • SolrQuery
  • Specify the regular expression for fragmenting

SolrQuery::setHighlightRegexPattern

(PECL solr >= 0.9.2)

SolrQuery::setHighlightRegexPattern — Specify the regular expression for fragmenting

Description

public SolrQuery::setHighlightRegexPattern ( string $value ) : SolrQuery

Specifies the regular expression for fragmenting. This could be used to extract sentences

Parameters

value

The regular expression for fragmenting. This could be used to extract sentences

Return Values

Returns the current SolrQuery object, if the return value is used.


Sets the factor by which the regex fragmenter can stray from the ideal fragment size

  • « SolrQuery::setHighlightRegexPattern
  • SolrQuery::setHighlightRequireFieldMatch »
  • PHP Manual
  • SolrQuery
  • Sets the factor by which the regex fragmenter can stray from the ideal fragment size

SolrQuery::setHighlightRegexSlop

(PECL solr >= 0.9.2)

SolrQuery::setHighlightRegexSlop — Sets the factor by which the regex fragmenter can stray from the ideal fragment size

Description

public SolrQuery::setHighlightRegexSlop ( float $factor ) : SolrQuery

The factor by which the regex fragmenter can stray from the ideal fragment size ( specfied by SolrQuery::setHighlightFragsize )to accommodate the regular expression

Parameters

factor

The factor by which the regex fragmenter can stray from the ideal fragment size

Return Values

Returns the current SolrQuery object, if the return value is used.


Require field matching during highlighting

  • « SolrQuery::setHighlightRegexSlop
  • SolrQuery::setHighlightSimplePost »
  • PHP Manual
  • SolrQuery
  • Require field matching during highlighting

SolrQuery::setHighlightRequireFieldMatch

(PECL solr >= 0.9.2)

SolrQuery::setHighlightRequireFieldMatch — Require field matching during highlighting

Description

public SolrQuery::setHighlightRequireFieldMatch ( bool $flag ) : SolrQuery

If TRUE, then a field will only be highlighted if the query matched in this particular field.

This will only work if SolrQuery::setHighlightUsePhraseHighlighter() was set to TRUE

Parameters

flag

TRUE or FALSE

Return Values

Returns the current SolrQuery object, if the return value is used.


Sets the text which appears after a highlighted term

  • « SolrQuery::setHighlightRequireFieldMatch
  • SolrQuery::setHighlightSimplePre »
  • PHP Manual
  • SolrQuery
  • Sets the text which appears after a highlighted term

SolrQuery::setHighlightSimplePost

(PECL solr >= 0.9.2)

SolrQuery::setHighlightSimplePost — Sets the text which appears after a highlighted term

Description

public SolrQuery::setHighlightSimplePost ( string $simplePost [, string $field_override ] ) : SolrQuery

Sets the text which appears before a highlighted term

Parameters

simplePost

Sets the text which appears after a highlighted term

The default is </em>

field_override

The name of the field.


Sets the text which appears before a highlighted term

  • « SolrQuery::setHighlightSimplePost
  • SolrQuery::setHighlightSnippets »
  • PHP Manual
  • SolrQuery
  • Sets the text which appears before a highlighted term

SolrQuery::setHighlightSimplePre

(PECL solr >= 0.9.2)

SolrQuery::setHighlightSimplePre — Sets the text which appears before a highlighted term

Description

public SolrQuery::setHighlightSimplePre ( string $simplePre [, string $field_override ] ) : SolrQuery

Sets the text which appears before a highlighted term

The default is <em>

Parameters

simplePre

The text which appears before a highlighted term

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.


Sets the maximum number of highlighted snippets to generate per field

  • « SolrQuery::setHighlightSimplePre
  • SolrQuery::setHighlightUsePhraseHighlighter »
  • PHP Manual
  • SolrQuery
  • Sets the maximum number of highlighted snippets to generate per field

SolrQuery::setHighlightSnippets

(PECL solr >= 0.9.2)

SolrQuery::setHighlightSnippets — Sets the maximum number of highlighted snippets to generate per field

Description

public SolrQuery::setHighlightSnippets ( int $value [, string $field_override ] ) : SolrQuery

Sets the maximum number of highlighted snippets to generate per field

Parameters

value

The maximum number of highlighted snippets to generate per field

field_override

The name of the field.

Return Values

Returns the current SolrQuery object, if the return value is used.


Whether to highlight phrase terms only when they appear within the query phrase

  • « SolrQuery::setHighlightSnippets
  • SolrQuery::setMlt »
  • PHP Manual
  • SolrQuery
  • Whether to highlight phrase terms only when they appear within the query phrase

SolrQuery::setHighlightUsePhraseHighlighter

(PECL solr >= 0.9.2)

SolrQuery::setHighlightUsePhraseHighlighter — Whether to highlight phrase terms only when they appear within the query phrase

Description

public SolrQuery::setHighlightUsePhraseHighlighter ( bool $flag ) : SolrQuery

Sets whether or not to use SpanScorer to highlight phrase terms only when they appear within the query phrase in the document

Parameters

value

Whether or not to use SpanScorer to highlight phrase terms only when they appear within the query phrase in the document

Return Values

Returns the current SolrQuery object, if the return value is used.


Enables or disables moreLikeThis

  • « SolrQuery::setHighlightUsePhraseHighlighter
  • SolrQuery::setMltBoost »
  • PHP Manual
  • SolrQuery
  • Enables or disables moreLikeThis

SolrQuery::setMlt

(PECL solr >= 0.9.2)

SolrQuery::setMlt — Enables or disables moreLikeThis

Description

public SolrQuery::setMlt ( bool $flag ) : SolrQuery

Enables or disables moreLikeThis

Parameters

flag

TRUE enables it and FALSE turns it off.

Return Values

Returns the current SolrQuery object, if the return value is used.


Set if the query will be boosted by the interesting term relevance

  • « SolrQuery::setMlt
  • SolrQuery::setMltCount »
  • PHP Manual
  • SolrQuery
  • Set if the query will be boosted by the interesting term relevance

SolrQuery::setMltBoost

(PECL solr >= 0.9.2)

SolrQuery::setMltBoost — Set if the query will be boosted by the interesting term relevance

Description

public SolrQuery::setMltBoost ( bool $flag ) : SolrQuery

Set if the query will be boosted by the interesting term relevance

Parameters

value

Sets to TRUE or FALSE

Return Values

Returns the current SolrQuery object, if the return value is used.


Set the number of similar documents to return for each result

  • « SolrQuery::setMltBoost
  • SolrQuery::setMltMaxNumQueryTerms »
  • PHP Manual
  • SolrQuery
  • Set the number of similar documents to return for each result

SolrQuery::setMltCount

(PECL solr >= 0.9.2)

SolrQuery::setMltCount — Set the number of similar documents to return for each result

Description

public SolrQuery::setMltCount ( int $count ) : SolrQuery

Set the number of similar documents to return for each result

Parameters

count

The number of similar documents to return for each result

Return Values

Returns the current SolrQuery object, if the return value is used.


Sets the maximum number of query terms included

  • « SolrQuery::setMltCount
  • SolrQuery::setMltMaxNumTokens »
  • PHP Manual
  • SolrQuery
  • Sets the maximum number of query terms included

SolrQuery::setMltMaxNumQueryTerms

(PECL solr >= 0.9.2)

SolrQuery::setMltMaxNumQueryTerms — Sets the maximum number of query terms included

Description

public SolrQuery::setMltMaxNumQueryTerms ( int $value ) : SolrQuery

Sets the maximum number of query terms that will be included in any generated query.

Parameters

value

The maximum number of query terms that will be included in any generated query

Return Values

Returns the current SolrQuery object, if the return value is used.


Specifies the maximum number of tokens to parse

  • « SolrQuery::setMltMaxNumQueryTerms
  • SolrQuery::setMltMaxWordLength »
  • PHP Manual
  • SolrQuery
  • Specifies the maximum number of tokens to parse

SolrQuery::setMltMaxNumTokens

(PECL solr >= 0.9.2)

SolrQuery::setMltMaxNumTokens — Specifies the maximum number of tokens to parse

Description

public SolrQuery::setMltMaxNumTokens ( int $value ) : SolrQuery

Specifies the maximum number of tokens to parse in each example doc field that is not stored with TermVector support.

Parameters

value

The maximum number of tokens to parse

Return Values

Returns the current SolrQuery object, if the return value is used.


Sets the maximum word length

  • « SolrQuery::setMltMaxNumTokens
  • SolrQuery::setMltMinDocFrequency »
  • PHP Manual
  • SolrQuery
  • Sets the maximum word length

SolrQuery::setMltMaxWordLength

(PECL solr >= 0.9.2)

SolrQuery::setMltMaxWordLength — Sets the maximum word length

Description

public SolrQuery::setMltMaxWordLength ( int $maxWordLength ) : SolrQuery

Sets the maximum word length above which words will be ignored.

Parameters

maxWordLength

The maximum word length above which words will be ignored

Return Values

Returns the current SolrQuery object, if the return value is used.


Sets the mltMinDoc frequency

  • « SolrQuery::setMltMaxWordLength
  • SolrQuery::setMltMinTermFrequency »
  • PHP Manual
  • SolrQuery
  • Sets the mltMinDoc frequency

SolrQuery::setMltMinDocFrequency

(PECL solr >= 0.9.2)

SolrQuery::setMltMinDocFrequency — Sets the mltMinDoc frequency

Description

public SolrQuery::setMltMinDocFrequency ( int $minDocFrequency ) : SolrQuery

The frequency at which words will be ignored which do not occur in at least this many docs.

Parameters

minDocFrequency

Sets the frequency at which words will be ignored which do not occur in at least this many docs.

Return Values

Returns the current SolrQuery object, if the return value is used.


Sets the frequency below which terms will be ignored in the source docs

  • « SolrQuery::setMltMinDocFrequency
  • SolrQuery::setMltMinWordLength »
  • PHP Manual
  • SolrQuery
  • Sets the frequency below which terms will be ignored in the source docs

SolrQuery::setMltMinTermFrequency

(PECL solr >= 0.9.2)

SolrQuery::setMltMinTermFrequency — Sets the frequency below which terms will be ignored in the source docs

Description

public SolrQuery::setMltMinTermFrequency ( int $minTermFrequency ) : SolrQuery

Sets the frequency below which terms will be ignored in the source docs

Parameters

minTermFrequency

The frequency below which terms will be ignored in the source docs

Return Values

Returns the current SolrQuery object, if the return value is used.


Sets the minimum word length

  • « SolrQuery::setMltMinTermFrequency
  • SolrQuery::setOmitHeader »
  • PHP Manual
  • SolrQuery
  • Sets the minimum word length

SolrQuery::setMltMinWordLength

(PECL solr >= 0.9.2)

SolrQuery::setMltMinWordLength — Sets the minimum word length

Description

public SolrQuery::setMltMinWordLength ( int $minWordLength ) : SolrQuery

Sets the minimum word length below which words will be ignored.

Parameters

minWordLength

The minimum word length below which words will be ignored

Return Values

Returns the current SolrQuery object, if the return value is used.


Exclude the header from the returned results

  • « SolrQuery::setMltMinWordLength
  • SolrQuery::setQuery »
  • PHP Manual
  • SolrQuery
  • Exclude the header from the returned results

SolrQuery::setOmitHeader

(PECL solr >= 0.9.2)

SolrQuery::setOmitHeader — Exclude the header from the returned results

Description

public SolrQuery::setOmitHeader ( bool $flag ) : SolrQuery

Exclude the header from the returned results.

Parameters

flag

TRUE excludes the header from the result.

Return Values

Returns the current SolrQuery object, if the return value is used.


Sets the search query

  • « SolrQuery::setOmitHeader
  • SolrQuery::setRows »
  • PHP Manual
  • SolrQuery
  • Sets the search query

SolrQuery::setQuery

(PECL solr >= 0.9.2)

SolrQuery::setQuery — Sets the search query

Description

public SolrQuery::setQuery ( string $query ) : SolrQuery

Sets the search query.

Parameters

query

The search query

Return Values

Returns the current SolrQuery object


Specifies the maximum number of rows to return in the result

  • « SolrQuery::setQuery
  • SolrQuery::setShowDebugInfo »
  • PHP Manual
  • SolrQuery
  • Specifies the maximum number of rows to return in the result

SolrQuery::setRows

(PECL solr >= 0.9.2)

SolrQuery::setRows — Specifies the maximum number of rows to return in the result

Description

public SolrQuery::setRows ( int $rows ) : SolrQuery

Specifies the maximum number of rows to return in the result

Parameters

rows

The maximum number of rows to return

Return Values

Returns the current SolrQuery object.


Flag to show debug information

  • « SolrQuery::setRows
  • SolrQuery::setStart »
  • PHP Manual
  • SolrQuery
  • Flag to show debug information

SolrQuery::setShowDebugInfo

(PECL solr >= 0.9.2)

SolrQuery::setShowDebugInfo — Flag to show debug information

Description

public SolrQuery::setShowDebugInfo ( bool $flag ) : SolrQuery

Whether to show debug info

Parameters

flag

Whether to show debug info. TRUE or FALSE

Return Values

Returns the current SolrQuery object, if the return value is used.


Specifies the number of rows to skip

  • « SolrQuery::setShowDebugInfo
  • SolrQuery::setStats »
  • PHP Manual
  • SolrQuery
  • Specifies the number of rows to skip

SolrQuery::setStart

(PECL solr >= 0.9.2)

SolrQuery::setStart — Specifies the number of rows to skip

Description

public SolrQuery::setStart ( int $start ) : SolrQuery

Specifies the number of rows to skip. Useful in pagination of results.

Parameters

start

The number of rows to skip.

Return Values

Returns the current SolrQuery object.


Enables or disables the Stats component

  • « SolrQuery::setStart
  • SolrQuery::setTerms »
  • PHP Manual
  • SolrQuery
  • Enables or disables the Stats component

SolrQuery::setStats

(PECL solr >= 0.9.2)

SolrQuery::setStats — Enables or disables the Stats component

Description

public SolrQuery::setStats ( bool $flag ) : SolrQuery

Enables or disables the Stats component.

Parameters

flag

TRUE turns on the stats component and FALSE disables it.

Return Values

Returns the current SolrQuery object, if the return value is used.


Enables or disables the TermsComponent

  • « SolrQuery::setStats
  • SolrQuery::setTermsField »
  • PHP Manual
  • SolrQuery
  • Enables or disables the TermsComponent

SolrQuery::setTerms

(PECL solr >= 0.9.2)

SolrQuery::setTerms — Enables or disables the TermsComponent

Description

public SolrQuery::setTerms ( bool $flag ) : SolrQuery

Enables or disables the TermsComponent

Parameters

flag

TRUE enables it. FALSE turns it off

Return Values

Returns the current SolrQuery object, if the return value is used.


Sets the name of the field to get the Terms from

  • « SolrQuery::setTerms
  • SolrQuery::setTermsIncludeLowerBound »
  • PHP Manual
  • SolrQuery
  • Sets the name of the field to get the Terms from

SolrQuery::setTermsField

(PECL solr >= 0.9.2)

SolrQuery::setTermsField — Sets the name of the field to get the Terms from

Description

public SolrQuery::setTermsField ( string $fieldname ) : SolrQuery

Sets the name of the field to get the terms from

Parameters

fieldname

The field name

Return Values

Returns the current SolrQuery object, if the return value is used.


Include the lower bound term in the result set

  • « SolrQuery::setTermsField
  • SolrQuery::setTermsIncludeUpperBound »
  • PHP Manual
  • SolrQuery
  • Include the lower bound term in the result set

SolrQuery::setTermsIncludeLowerBound

(PECL solr >= 0.9.2)

SolrQuery::setTermsIncludeLowerBound — Include the lower bound term in the result set

Description

public SolrQuery::setTermsIncludeLowerBound ( bool $flag ) : SolrQuery

Include the lower bound term in the result set.

Parameters

flag

Include the lower bound term in the result set

Return Values

Returns the current SolrQuery object, if the return value is used.


Include the upper bound term in the result set

  • « SolrQuery::setTermsIncludeLowerBound
  • SolrQuery::setTermsLimit »
  • PHP Manual
  • SolrQuery
  • Include the upper bound term in the result set

SolrQuery::setTermsIncludeUpperBound

(PECL solr >= 0.9.2)

SolrQuery::setTermsIncludeUpperBound — Include the upper bound term in the result set

Description

public SolrQuery::setTermsIncludeUpperBound ( bool $flag ) : SolrQuery

Include the upper bound term in the result set.

Parameters

flag

TRUE or FALSE

Return Values

Returns the current SolrQuery object, if the return value is used.


Sets the maximum number of terms to return

  • « SolrQuery::setTermsIncludeUpperBound
  • SolrQuery::setTermsLowerBound »
  • PHP Manual
  • SolrQuery
  • Sets the maximum number of terms to return

SolrQuery::setTermsLimit

(PECL solr >= 0.9.2)

SolrQuery::setTermsLimit — Sets the maximum number of terms to return

Description

public SolrQuery::setTermsLimit ( int $limit ) : SolrQuery

Sets the maximum number of terms to return

Parameters

limit

The maximum number of terms to return. All the terms will be returned if the limit is negative.

Return Values

Returns the current SolrQuery object, if the return value is used.


Specifies the Term to start from

  • « SolrQuery::setTermsLimit
  • SolrQuery::setTermsMaxCount »
  • PHP Manual
  • SolrQuery
  • Specifies the Term to start from

SolrQuery::setTermsLowerBound

(PECL solr >= 0.9.2)

SolrQuery::setTermsLowerBound — Specifies the Term to start from

Description

public SolrQuery::setTermsLowerBound ( string $lowerBound ) : SolrQuery

Specifies the Term to start from

Parameters

lowerBound

The lower bound Term

Return Values

Returns the current SolrQuery object, if the return value is used.


Sets the maximum document frequency

  • « SolrQuery::setTermsLowerBound
  • SolrQuery::setTermsMinCount »
  • PHP Manual
  • SolrQuery
  • Sets the maximum document frequency

SolrQuery::setTermsMaxCount

(PECL solr >= 0.9.2)

SolrQuery::setTermsMaxCount — Sets the maximum document frequency

Description

public SolrQuery::setTermsMaxCount ( int $frequency ) : SolrQuery

Sets the maximum document frequency.

Parameters

frequency

The maximum document frequency.

Return Values

Returns the current SolrQuery object, if the return value is used.


Sets the minimum document frequency

  • « SolrQuery::setTermsMaxCount
  • SolrQuery::setTermsPrefix »
  • PHP Manual
  • SolrQuery
  • Sets the minimum document frequency

SolrQuery::setTermsMinCount

(PECL solr >= 0.9.2)

SolrQuery::setTermsMinCount — Sets the minimum document frequency

Description

public SolrQuery::setTermsMinCount ( int $frequency ) : SolrQuery

Sets the minimum doc frequency to return in order to be included

Parameters

frequency

The minimum frequency

Return Values

Returns the current SolrQuery object, if the return value is used.


Restrict matches to terms that start with the prefix

  • « SolrQuery::setTermsMinCount
  • SolrQuery::setTermsReturnRaw »
  • PHP Manual
  • SolrQuery
  • Restrict matches to terms that start with the prefix

SolrQuery::setTermsPrefix

(PECL solr >= 0.9.2)

SolrQuery::setTermsPrefix — Restrict matches to terms that start with the prefix

Description

public SolrQuery::setTermsPrefix ( string $prefix ) : SolrQuery

Restrict matches to terms that start with the prefix

Parameters

prefix

Restrict matches to terms that start with the prefix

Return Values

Returns the current SolrQuery object, if the return value is used.


Return the raw characters of the indexed term

  • « SolrQuery::setTermsPrefix
  • SolrQuery::setTermsSort »
  • PHP Manual
  • SolrQuery
  • Return the raw characters of the indexed term

SolrQuery::setTermsReturnRaw

(PECL solr >= 0.9.2)

SolrQuery::setTermsReturnRaw — Return the raw characters of the indexed term

Description

public SolrQuery::setTermsReturnRaw ( bool $flag ) : SolrQuery

If true, return the raw characters of the indexed term, regardless of if it is human readable

Parameters

value

TRUE or FALSE

Return Values

Returns the current SolrQuery object, if the return value is used.


Specifies how to sort the returned terms

  • « SolrQuery::setTermsReturnRaw
  • SolrQuery::setTermsUpperBound »
  • PHP Manual
  • SolrQuery
  • Specifies how to sort the returned terms

SolrQuery::setTermsSort

(PECL solr >= 0.9.2)

SolrQuery::setTermsSort — Specifies how to sort the returned terms

Description

public SolrQuery::setTermsSort ( int $sortType ) : SolrQuery

If SolrQuery::TERMS_SORT_COUNT, sorts the terms by the term frequency (highest count first). If SolrQuery::TERMS_SORT_INDEX, returns the terms in index order

Parameters

sortType

SolrQuery::TERMS_SORT_INDEX or SolrQuery::TERMS_SORT_COUNT

Return Values

Returns the current SolrQuery object, if the return value is used.


Sets the term to stop at

  • « SolrQuery::setTermsSort
  • SolrQuery::setTimeAllowed »
  • PHP Manual
  • SolrQuery
  • Sets the term to stop at

SolrQuery::setTermsUpperBound

(PECL solr >= 0.9.2)

SolrQuery::setTermsUpperBound — Sets the term to stop at

Description

public SolrQuery::setTermsUpperBound ( string $upperBound ) : SolrQuery

Sets the term to stop at

Parameters

upperBound

The term to stop at

Return Values

Returns the current SolrQuery object, if the return value is used.


The time allowed for search to finish

  • « SolrQuery::setTermsUpperBound
  • SolrDisMaxQuery »
  • PHP Manual
  • SolrQuery
  • The time allowed for search to finish

SolrQuery::setTimeAllowed

(PECL solr >= 0.9.2)

SolrQuery::setTimeAllowed — The time allowed for search to finish

Description

public SolrQuery::setTimeAllowed ( int $timeAllowed ) : SolrQuery

The time allowed for a search to finish. This value only applies to the search and not to requests in general. Time is in milliseconds. Values less than or equal to zero implies no time restriction. Partial results may be returned, if there are any.

Parameters

timeAllowed

The time allowed for a search to finish.

Return Values

Returns the current SolrQuery object, if the return value is used.


The SolrDisMaxQuery class

(No version information available, might only be in Git)

Introduction

Class synopsis

SolrDisMaxQuery extends SolrQuery implements Serializable {
/* Inherited properties */
const integer SolrQuery::ORDER_ASC = 0 ;
const integer SolrQuery::ORDER_DESC = 1 ;
const integer SolrQuery::FACET_SORT_INDEX = 0 ;
const integer SolrQuery::FACET_SORT_COUNT = 1 ;
const integer SolrQuery::TERMS_SORT_INDEX = 0 ;
const integer SolrQuery::TERMS_SORT_COUNT = 1 ;
/* Methods */
public addBigramPhraseField ( string $field , string $boost [, string $slop ] ) : SolrDisMaxQuery
public addBoostQuery ( string $field , string $value [, string $boost ] ) : SolrDisMaxQuery
public addPhraseField ( string $field , string $boost [, string $slop ] ) : SolrDisMaxQuery
public addQueryField ( string $field [, string $boost ] ) : SolrDisMaxQuery
public addTrigramPhraseField ( string $field , string $boost [, string $slop ] ) : SolrDisMaxQuery
public addUserField ( string $field ) : SolrDisMaxQuery
public __construct ([ string $q ] )
public removeBigramPhraseField ( string $field ) : SolrDisMaxQuery
public removeBoostQuery ( string $field ) : SolrDisMaxQuery
public removePhraseField ( string $field ) : SolrDisMaxQuery
public removeQueryField ( string $field ) : SolrDisMaxQuery
public removeTrigramPhraseField ( string $field ) : SolrDisMaxQuery
public removeUserField ( string $field ) : SolrDisMaxQuery
public setBigramPhraseFields ( string $fields ) : SolrDisMaxQuery
public setBigramPhraseSlop ( string $slop ) : SolrDisMaxQuery
public setBoostFunction ( string $function ) : SolrDisMaxQuery
public setBoostQuery ( string $q ) : SolrDisMaxQuery
public setMinimumMatch ( string $value ) : SolrDisMaxQuery
public setPhraseFields ( string $fields ) : SolrDisMaxQuery
public setPhraseSlop ( string $slop ) : SolrDisMaxQuery
public setQueryAlt ( string $q ) : SolrDisMaxQuery
public setQueryPhraseSlop ( string $slop ) : SolrDisMaxQuery
public setTieBreaker ( string $tieBreaker ) : SolrDisMaxQuery
public setTrigramPhraseFields ( string $fields ) : SolrDisMaxQuery
public setTrigramPhraseSlop ( string $slop ) : SolrDisMaxQuery
public setUserFields ( string $fields ) : SolrDisMaxQuery
public useDisMaxQueryParser ( void ) : SolrDisMaxQuery
public useEDisMaxQueryParser ( void ) : SolrDisMaxQuery
/* Inherited methods */
public SolrQuery::addExpandFilterQuery ( string $fq ) : SolrQuery
public SolrQuery::addExpandSortField ( string $field [, string $order ] ) : SolrQuery
public SolrQuery::addFacetDateField ( string $dateField ) : SolrQuery
public SolrQuery::addFacetDateOther ( string $value [, string $field_override ] ) : SolrQuery
public SolrQuery::addFacetField ( string $field ) : SolrQuery
public SolrQuery::addFacetQuery ( string $facetQuery ) : SolrQuery
public SolrQuery::addField ( string $field ) : SolrQuery
public SolrQuery::addFilterQuery ( string $fq ) : SolrQuery
public SolrQuery::addGroupField ( string $value ) : SolrQuery
public SolrQuery::addGroupFunction ( string $value ) : SolrQuery
public SolrQuery::addGroupQuery ( string $value ) : SolrQuery
public SolrQuery::addGroupSortField ( string $field [, int $order ] ) : SolrQuery
public SolrQuery::addHighlightField ( string $field ) : SolrQuery
public SolrQuery::addMltField ( string $field ) : SolrQuery
public SolrQuery::addMltQueryField ( string $field , float $boost ) : SolrQuery
public SolrQuery::addSortField ( string $field [, int $order = SolrQuery::ORDER_DESC ] ) : SolrQuery
public SolrQuery::addStatsFacet ( string $field ) : SolrQuery
public SolrQuery::addStatsField ( string $field ) : SolrQuery
public SolrQuery::collapse ( SolrCollapseFunction $collapseFunction ) : SolrQuery
public SolrQuery::__construct ([ string $q ] )
public SolrQuery::__destruct ( void ) : void
public SolrQuery::getExpand ( void ) : bool
public SolrQuery::getExpandFilterQueries ( void ) : array
public SolrQuery::getExpandQuery ( void ) : array
public SolrQuery::getExpandRows ( void ) : int
public SolrQuery::getExpandSortFields ( void ) : array
public SolrQuery::getFacet ( void ) : bool
public SolrQuery::getFacetDateEnd ([ string $field_override ] ) : string
public SolrQuery::getFacetDateFields ( void ) : array
public SolrQuery::getFacetDateGap ([ string $field_override ] ) : string
public SolrQuery::getFacetDateHardEnd ([ string $field_override ] ) : string
public SolrQuery::getFacetDateOther ([ string $field_override ] ) : array
public SolrQuery::getFacetDateStart ([ string $field_override ] ) : string
public SolrQuery::getFacetFields ( void ) : array
public SolrQuery::getFacetLimit ([ string $field_override ] ) : int
public SolrQuery::getFacetMethod ([ string $field_override ] ) : string
public SolrQuery::getFacetMinCount ([ string $field_override ] ) : int
public SolrQuery::getFacetMissing ([ string $field_override ] ) : bool
public SolrQuery::getFacetOffset ([ string $field_override ] ) : int
public SolrQuery::getFacetPrefix ([ string $field_override ] ) : string
public SolrQuery::getFacetQueries ( void ) : array
public SolrQuery::getFacetSort ([ string $field_override ] ) : int
public SolrQuery::getFields ( void ) : array
public SolrQuery::getFilterQueries ( void ) : array
public SolrQuery::getGroup ( void ) : bool
public SolrQuery::getGroupCachePercent ( void ) : int
public SolrQuery::getGroupFacet ( void ) : bool
public SolrQuery::getGroupFields ( void ) : array
public SolrQuery::getGroupFormat ( void ) : string
public SolrQuery::getGroupFunctions ( void ) : array
public SolrQuery::getGroupLimit ( void ) : int
public SolrQuery::getGroupMain ( void ) : bool
public SolrQuery::getGroupNGroups ( void ) : bool
public SolrQuery::getGroupOffset ( void ) : int
public SolrQuery::getGroupQueries ( void ) : array
public SolrQuery::getGroupSortFields ( void ) : array
public SolrQuery::getGroupTruncate ( void ) : bool
public SolrQuery::getHighlight ( void ) : bool
public SolrQuery::getHighlightAlternateField ([ string $field_override ] ) : string
public SolrQuery::getHighlightFields ( void ) : array
public SolrQuery::getHighlightFormatter ([ string $field_override ] ) : string
public SolrQuery::getHighlightFragmenter ([ string $field_override ] ) : string
public SolrQuery::getHighlightFragsize ([ string $field_override ] ) : int
public SolrQuery::getHighlightHighlightMultiTerm ( void ) : bool
public SolrQuery::getHighlightMaxAlternateFieldLength ([ string $field_override ] ) : int
public SolrQuery::getHighlightMaxAnalyzedChars ( void ) : int
public SolrQuery::getHighlightMergeContiguous ([ string $field_override ] ) : bool
public SolrQuery::getHighlightRegexMaxAnalyzedChars ( void ) : int
public SolrQuery::getHighlightRegexPattern ( void ) : string
public SolrQuery::getHighlightRegexSlop ( void ) : float
public SolrQuery::getHighlightRequireFieldMatch ( void ) : bool
public SolrQuery::getHighlightSimplePost ([ string $field_override ] ) : string
public SolrQuery::getHighlightSimplePre ([ string $field_override ] ) : string
public SolrQuery::getHighlightSnippets ([ string $field_override ] ) : int
public SolrQuery::getHighlightUsePhraseHighlighter ( void ) : bool
public SolrQuery::getMlt ( void ) : bool
public SolrQuery::getMltBoost ( void ) : bool
public SolrQuery::getMltCount ( void ) : int
public SolrQuery::getMltFields ( void ) : array
public SolrQuery::getMltMaxNumQueryTerms ( void ) : int
public SolrQuery::getMltMaxNumTokens ( void ) : int
public SolrQuery::getMltMaxWordLength ( void ) : int
public SolrQuery::getMltMinDocFrequency ( void ) : int
public SolrQuery::getMltMinTermFrequency ( void ) : int
public SolrQuery::getMltMinWordLength ( void ) : int
public SolrQuery::getMltQueryFields ( void ) : array
public SolrQuery::getQuery ( void ) : string
public SolrQuery::getRows ( void ) : int
public SolrQuery::getSortFields ( void ) : array
public SolrQuery::getStart ( void ) : int
public SolrQuery::getStats ( void ) : bool
public SolrQuery::getStatsFacets ( void ) : array
public SolrQuery::getStatsFields ( void ) : array
public SolrQuery::getTerms ( void ) : bool
public SolrQuery::getTermsField ( void ) : string
public SolrQuery::getTermsIncludeLowerBound ( void ) : bool
public SolrQuery::getTermsIncludeUpperBound ( void ) : bool
public SolrQuery::getTermsLimit ( void ) : int
public SolrQuery::getTermsLowerBound ( void ) : string
public SolrQuery::getTermsMaxCount ( void ) : int
public SolrQuery::getTermsMinCount ( void ) : int
public SolrQuery::getTermsPrefix ( void ) : string
public SolrQuery::getTermsReturnRaw ( void ) : bool
public SolrQuery::getTermsSort ( void ) : int
public SolrQuery::getTermsUpperBound ( void ) : string
public SolrQuery::getTimeAllowed ( void ) : int
public SolrQuery::removeExpandFilterQuery ( string $fq ) : SolrQuery
public SolrQuery::removeExpandSortField ( string $field ) : SolrQuery
public SolrQuery::removeFacetDateField ( string $field ) : SolrQuery
public SolrQuery::removeFacetDateOther ( string $value [, string $field_override ] ) : SolrQuery
public SolrQuery::removeFacetField ( string $field ) : SolrQuery
public SolrQuery::removeFacetQuery ( string $value ) : SolrQuery
public SolrQuery::removeField ( string $field ) : SolrQuery
public SolrQuery::removeFilterQuery ( string $fq ) : SolrQuery
public SolrQuery::removeHighlightField ( string $field ) : SolrQuery
public SolrQuery::removeMltField ( string $field ) : SolrQuery
public SolrQuery::removeMltQueryField ( string $queryField ) : SolrQuery
public SolrQuery::removeSortField ( string $field ) : SolrQuery
public SolrQuery::removeStatsFacet ( string $value ) : SolrQuery
public SolrQuery::removeStatsField ( string $field ) : SolrQuery
public SolrQuery::setEchoHandler ( bool $flag ) : SolrQuery
public SolrQuery::setEchoParams ( string $type ) : SolrQuery
public SolrQuery::setExpand ( bool $value ) : SolrQuery
public SolrQuery::setExpandQuery ( string $q ) : SolrQuery
public SolrQuery::setExpandRows ( int $value ) : SolrQuery
public SolrQuery::setExplainOther ( string $query ) : SolrQuery
public SolrQuery::setFacet ( bool $flag ) : SolrQuery
public SolrQuery::setFacetDateEnd ( string $value [, string $field_override ] ) : SolrQuery
public SolrQuery::setFacetDateGap ( string $value [, string $field_override ] ) : SolrQuery
public SolrQuery::setFacetDateHardEnd ( bool $value [, string $field_override ] ) : SolrQuery
public SolrQuery::setFacetDateStart ( string $value [, string $field_override ] ) : SolrQuery
public SolrQuery::setFacetEnumCacheMinDefaultFrequency ( int $frequency [, string $field_override ] ) : SolrQuery
public SolrQuery::setFacetLimit ( int $limit [, string $field_override ] ) : SolrQuery
public SolrQuery::setFacetMethod ( string $method [, string $field_override ] ) : SolrQuery
public SolrQuery::setFacetMinCount ( int $mincount [, string $field_override ] ) : SolrQuery
public SolrQuery::setFacetMissing ( bool $flag [, string $field_override ] ) : SolrQuery
public SolrQuery::setFacetOffset ( int $offset [, string $field_override ] ) : SolrQuery
public SolrQuery::setFacetPrefix ( string $prefix [, string $field_override ] ) : SolrQuery
public SolrQuery::setFacetSort ( int $facetSort [, string $field_override ] ) : SolrQuery
public SolrQuery::setGroup ( bool $value ) : SolrQuery
public SolrQuery::setGroupCachePercent ( int $percent ) : SolrQuery
public SolrQuery::setGroupFacet ( bool $value ) : SolrQuery
public SolrQuery::setGroupFormat ( string $value ) : SolrQuery
public SolrQuery::setGroupLimit ( int $value ) : SolrQuery
public SolrQuery::setGroupMain ( string $value ) : SolrQuery
public SolrQuery::setGroupNGroups ( bool $value ) : SolrQuery
public SolrQuery::setGroupOffset ( int $value ) : SolrQuery
public SolrQuery::setGroupTruncate ( bool $value ) : SolrQuery
public SolrQuery::setHighlight ( bool $flag ) : SolrQuery
public SolrQuery::setHighlightAlternateField ( string $field [, string $field_override ] ) : SolrQuery
public SolrQuery::setHighlightFormatter ( string $formatter [, string $field_override ] ) : SolrQuery
public SolrQuery::setHighlightFragmenter ( string $fragmenter [, string $field_override ] ) : SolrQuery
public SolrQuery::setHighlightFragsize ( int $size [, string $field_override ] ) : SolrQuery
public SolrQuery::setHighlightHighlightMultiTerm ( bool $flag ) : SolrQuery
public SolrQuery::setHighlightMaxAlternateFieldLength ( int $fieldLength [, string $field_override ] ) : SolrQuery
public SolrQuery::setHighlightMaxAnalyzedChars ( int $value ) : SolrQuery
public SolrQuery::setHighlightMergeContiguous ( bool $flag [, string $field_override ] ) : SolrQuery
public SolrQuery::setHighlightRegexMaxAnalyzedChars ( int $maxAnalyzedChars ) : SolrQuery
public SolrQuery::setHighlightRegexPattern ( string $value ) : SolrQuery
public SolrQuery::setHighlightRegexSlop ( float $factor ) : SolrQuery
public SolrQuery::setHighlightRequireFieldMatch ( bool $flag ) : SolrQuery
public SolrQuery::setHighlightSimplePost ( string $simplePost [, string $field_override ] ) : SolrQuery
public SolrQuery::setHighlightSimplePre ( string $simplePre [, string $field_override ] ) : SolrQuery
public SolrQuery::setHighlightSnippets ( int $value [, string $field_override ] ) : SolrQuery
public SolrQuery::setHighlightUsePhraseHighlighter ( bool $flag ) : SolrQuery
public SolrQuery::setMlt ( bool $flag ) : SolrQuery
public SolrQuery::setMltBoost ( bool $flag ) : SolrQuery
public SolrQuery::setMltCount ( int $count ) : SolrQuery
public SolrQuery::setMltMaxNumQueryTerms ( int $value ) : SolrQuery
public SolrQuery::setMltMaxNumTokens ( int $value ) : SolrQuery
public SolrQuery::setMltMaxWordLength ( int $maxWordLength ) : SolrQuery
public SolrQuery::setMltMinDocFrequency ( int $minDocFrequency ) : SolrQuery
public SolrQuery::setMltMinTermFrequency ( int $minTermFrequency ) : SolrQuery
public SolrQuery::setMltMinWordLength ( int $minWordLength ) : SolrQuery
public SolrQuery::setOmitHeader ( bool $flag ) : SolrQuery
public SolrQuery::setQuery ( string $query ) : SolrQuery
public SolrQuery::setRows ( int $rows ) : SolrQuery
public SolrQuery::setShowDebugInfo ( bool $flag ) : SolrQuery
public SolrQuery::setStart ( int $start ) : SolrQuery
public SolrQuery::setStats ( bool $flag ) : SolrQuery
public SolrQuery::setTerms ( bool $flag ) : SolrQuery
public SolrQuery::setTermsField ( string $fieldname ) : SolrQuery
public SolrQuery::setTermsIncludeLowerBound ( bool $flag ) : SolrQuery
public SolrQuery::setTermsIncludeUpperBound ( bool $flag ) : SolrQuery
public SolrQuery::setTermsLimit ( int $limit ) : SolrQuery
public SolrQuery::setTermsLowerBound ( string $lowerBound ) : SolrQuery
public SolrQuery::setTermsMaxCount ( int $frequency ) : SolrQuery
public SolrQuery::setTermsMinCount ( int $frequency ) : SolrQuery
public SolrQuery::setTermsPrefix ( string $prefix ) : SolrQuery
public SolrQuery::setTermsReturnRaw ( bool $flag ) : SolrQuery
public SolrQuery::setTermsSort ( int $sortType ) : SolrQuery
public SolrQuery::setTermsUpperBound ( string $upperBound ) : SolrQuery
public SolrQuery::setTimeAllowed ( int $timeAllowed ) : SolrQuery
}

Predefined Constants

SolrDisMaxQuery::ORDER_ASC

Used to specify that the sorting should be in acending order (Duplicated for easier migration)

SolrDisMaxQuery::ORDER_DESC

Used to specify that the sorting should be in descending order (Duplicated for easier migration)

SolrDisMaxQuery::FACET_SORT_INDEX

Used to specify that the facet should sort by index (Duplicated for easier migration)

SolrDisMaxQuery::FACET_SORT_COUNT

Used to specify that the facet should sort by count (Duplicated for easier migration)

SolrDisMaxQuery::TERMS_SORT_INDEX

Used in the TermsComponent (Duplicated for easier migration)

SolrDisMaxQuery::TERMS_SORT_COUNT

Used in the TermsComponent (Duplicated for easier migration)

Table of Contents

  • SolrDisMaxQuery::addBigramPhraseField — Adds a Phrase Bigram Field (pf2 parameter)
  • SolrDisMaxQuery::addBoostQuery — Adds a boost query field with value and optional boost (bq parameter)
  • SolrDisMaxQuery::addPhraseField — Adds a Phrase Field (pf parameter)
  • SolrDisMaxQuery::addQueryField — Add a query field with optional boost (qf parameter)
  • SolrDisMaxQuery::addTrigramPhraseField — Adds a Trigram Phrase Field (pf3 parameter)
  • SolrDisMaxQuery::addUserField — Adds a field to User Fields Parameter (uf)
  • SolrDisMaxQuery::__construct — Class Constructor
  • SolrDisMaxQuery::removeBigramPhraseField — Removes phrase bigram field (pf2 parameter)
  • SolrDisMaxQuery::removeBoostQuery — Removes a boost query partial by field name (bq)
  • SolrDisMaxQuery::removePhraseField — Removes a Phrase Field (pf parameter)
  • SolrDisMaxQuery::removeQueryField — Removes a Query Field (qf parameter)
  • SolrDisMaxQuery::removeTrigramPhraseField — Removes a Trigram Phrase Field (pf3 parameter)
  • SolrDisMaxQuery::removeUserField — Removes a field from The User Fields Parameter (uf)
  • SolrDisMaxQuery::setBigramPhraseFields — Sets Bigram Phrase Fields and their boosts (and slops) using pf2 parameter
  • SolrDisMaxQuery::setBigramPhraseSlop — Sets Bigram Phrase Slop (ps2 parameter)
  • SolrDisMaxQuery::setBoostFunction — Sets a Boost Function (bf parameter)
  • SolrDisMaxQuery::setBoostQuery — Directly Sets Boost Query Parameter (bq)
  • SolrDisMaxQuery::setMinimumMatch — Set Minimum "Should" Match (mm)
  • SolrDisMaxQuery::setPhraseFields — Sets Phrase Fields and their boosts (and slops) using pf2 parameter
  • SolrDisMaxQuery::setPhraseSlop — Sets the default slop on phrase queries (ps parameter)
  • SolrDisMaxQuery::setQueryAlt — Set Query Alternate (q.alt parameter)
  • SolrDisMaxQuery::setQueryPhraseSlop — Specifies the amount of slop permitted on phrase queries explicitly included in the user's query string (qf parameter)
  • SolrDisMaxQuery::setTieBreaker — Sets Tie Breaker parameter (tie parameter)
  • SolrDisMaxQuery::setTrigramPhraseFields — Directly Sets Trigram Phrase Fields (pf3 parameter)
  • SolrDisMaxQuery::setTrigramPhraseSlop — Sets Trigram Phrase Slop (ps3 parameter)
  • SolrDisMaxQuery::setUserFields — Sets User Fields parameter (uf)
  • SolrDisMaxQuery::useDisMaxQueryParser — Switch QueryParser to be DisMax Query Parser
  • SolrDisMaxQuery::useEDisMaxQueryParser — Switch QueryParser to be EDisMax


Adds a Phrase Bigram Field (pf2 parameter)

  • « SolrDisMaxQuery
  • SolrDisMaxQuery::addBoostQuery »
  • PHP Manual
  • SolrDisMaxQuery
  • Adds a Phrase Bigram Field (pf2 parameter)

SolrDisMaxQuery::addBigramPhraseField

(No version information available, might only be in Git)

SolrDisMaxQuery::addBigramPhraseField — Adds a Phrase Bigram Field (pf2 parameter)

Description

public SolrDisMaxQuery::addBigramPhraseField ( string $field , string $boost [, string $slop ] ) : SolrDisMaxQuery

Adds a Phrase Bigram Field (pf2 parameter) output format: field~slop^boost OR field^boost Slop is optional

Parameters

field

boost

slop

Return Values

SolrDisMaxQuery

Examples

Example #1 SolrDisMaxQuery::addBigramPhraseField() example

<?php

$dismaxQuery = new SolrDisMaxQuery("lucene");
$dismaxQuery
    ->addBigramPhraseField('cat', 2, 5.1)
    ->addBigramPhraseField('feature', 4.5)
;
echo $dismaxQuery;

?>

The above example will output something similar to:

q=lucene&defType=edismax&pf2=cat~5.1^2 feature^4.5

See Also

  • SolrDisMaxQuery::removeBigramPhraseField() - Removes phrase bigram field (pf2 parameter)
  • SolrDisMaxQuery::setBigramPhraseFields() - Sets Bigram Phrase Fields and their boosts (and slops) using pf2 parameter
  • SolrDisMaxQuery::setBigramPhraseSlop() - Sets Bigram Phrase Slop (ps2 parameter)


Adds a boost query field with value and optional boost (bq parameter)

  • « SolrDisMaxQuery::addBigramPhraseField
  • SolrDisMaxQuery::addPhraseField »
  • PHP Manual
  • SolrDisMaxQuery
  • Adds a boost query field with value and optional boost (bq parameter)

SolrDisMaxQuery::addBoostQuery

(No version information available, might only be in Git)

SolrDisMaxQuery::addBoostQuery — Adds a boost query field with value and optional boost (bq parameter)

Description

public SolrDisMaxQuery::addBoostQuery ( string $field , string $value [, string $boost ] ) : SolrDisMaxQuery

Adds a Boost Query field with value [and boost] (bq parameter)

Parameters

field

value

boost

Return Values

SolrDisMaxQuery

Examples

Example #1 SolrDisMaxQuery::addBoostQuery() example

<?php

$dismaxQuery = new SolrDisMaxQuery("lucene");
$dismaxQuery
    ->addBoostQuery('cat', 'clothing', 2)
    ->addBoostQuery('cat', 'electronics', 5.1)
;
echo $dismaxQuery.PHP_EOL;
?>

The above example will output something similar to:

q=lucene&defType=edismax&bq=cat:clothing^2 cat:electronics^5.1

See Also

  • SolrDisMaxQuery::removeBoostQuery() - Removes a boost query partial by field name (bq)
  • SolrDisMaxQuery::setBoostQuery() - Directly Sets Boost Query Parameter (bq)


Adds a Phrase Field (pf parameter)

  • « SolrDisMaxQuery::addBoostQuery
  • SolrDisMaxQuery::addQueryField »
  • PHP Manual
  • SolrDisMaxQuery
  • Adds a Phrase Field (pf parameter)

SolrDisMaxQuery::addPhraseField

(No version information available, might only be in Git)

SolrDisMaxQuery::addPhraseField — Adds a Phrase Field (pf parameter)

Description

public SolrDisMaxQuery::addPhraseField ( string $field , string $boost [, string $slop ] ) : SolrDisMaxQuery

Adds a Phrase Field (pf parameter)

Parameters

field

field name

boost

slop

Return Values

SolrDisMaxQuery

Examples

Example #1 SolrDisMaxQuery::addPhraseField() example

<?php
$dismaxQuery = new SolrDisMaxQuery("lucene");
$dismaxQuery
    ->addPhraseField('cat', 3, 1)
    ->addPhraseField('third', 4, 2)
    ->addPhraseField('source', 55)
;
echo $dismaxQuery;
?>

The above example will output something similar to:

q=lucene&defType=edismax&pf=cat~1^3 third~2^4 source^55

See Also

  • SolrDisMaxQuery::removePhraseField() - Removes a Phrase Field (pf parameter)
  • SolrDisMaxQuery::setPhraseFields() - Sets Phrase Fields and their boosts (and slops) using pf2 parameter


Add a query field with optional boost (qf parameter)

  • « SolrDisMaxQuery::addPhraseField
  • SolrDisMaxQuery::addTrigramPhraseField »
  • PHP Manual
  • SolrDisMaxQuery
  • Add a query field with optional boost (qf parameter)

SolrDisMaxQuery::addQueryField

(No version information available, might only be in Git)

SolrDisMaxQuery::addQueryField — Add a query field with optional boost (qf parameter)

Description

public SolrDisMaxQuery::addQueryField ( string $field [, string $boost ] ) : SolrDisMaxQuery

Add a query field with optional boost (qf parameter)

Parameters

field

field name

boost

Boost value. Boosts documents with matching terms.

Return Values

SolrDisMaxQuery

Examples

Example #1 SolrDisMaxQuery::addQueryField() example

<?php

$dismaxQuery = new SolrDisMaxQuery("lucene");
$dismaxQuery
    ->addQueryField("location", 4)
    ->addQueryField("price")
    ->addQueryField("sku")
    ->addQueryField("title",3.4)
;
echo $dismaxQuery;

?>

The above example will output something similar to:

q=lucene&defType=edismax&qf=location^4 price sku title^3.4

See Also

  • SolrDisMaxQuery::removeQueryField() - Removes a Query Field (qf parameter)


Adds a Trigram Phrase Field (pf3 parameter)

  • « SolrDisMaxQuery::addQueryField
  • SolrDisMaxQuery::addUserField »
  • PHP Manual
  • SolrDisMaxQuery
  • Adds a Trigram Phrase Field (pf3 parameter)

SolrDisMaxQuery::addTrigramPhraseField

(No version information available, might only be in Git)

SolrDisMaxQuery::addTrigramPhraseField — Adds a Trigram Phrase Field (pf3 parameter)

Description

public SolrDisMaxQuery::addTrigramPhraseField ( string $field , string $boost [, string $slop ] ) : SolrDisMaxQuery

Adds a Trigram Phrase Field (pf3 parameter)

Parameters

field

Field Name

boost

Field Boost

slop

Field Slop

Return Values

SolrDisMaxQuery

Examples

Example #1 SolrDisMaxQuery::addTrigramPhraseField() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');
$dismaxQuery
->addTrigramPhraseField('cat', 2, 5.1)
->addTrigramPhraseField('feature', 4.5)
;
echo $dismaxQuery.PHP_EOL;

?>

The above example will output:

q=lucene&defType=%s&pf3=cat~5.1^2 feature^4.5

See Also

  • SolrDisMaxQuery::removeTrigramPhraseField() - Removes a Trigram Phrase Field (pf3 parameter)
  • SolrDisMaxQuery::setTrigramPhraseFields() - Directly Sets Trigram Phrase Fields (pf3 parameter)
  • SolrDisMaxQuery::setTrigramPhraseSlop() - Sets Trigram Phrase Slop (ps3 parameter)


Adds a field to User Fields Parameter (uf)

  • « SolrDisMaxQuery::addTrigramPhraseField
  • SolrDisMaxQuery::__construct »
  • PHP Manual
  • SolrDisMaxQuery
  • Adds a field to User Fields Parameter (uf)

SolrDisMaxQuery::addUserField

(No version information available, might only be in Git)

SolrDisMaxQuery::addUserField — Adds a field to User Fields Parameter (uf)

Description

public SolrDisMaxQuery::addUserField ( string $field ) : SolrDisMaxQuery

Adds a field to The User Fields Parameter (uf)

Parameters

field

Field Name

Return Values

SolrDisMaxQuery

Examples

Example #1 SolrDisMaxQuery::addUserField() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');
$dismaxQuery
->addUserField('cat')
->addUserField('text')
->addUserField('*_dt');

echo $dismaxQuery.PHP_EOL;

?>

The above example will output something similar to:

q=lucene&defType=edismax&uf=cat text *_dt

See Also

  • SolrDisMaxQuery::removeUserField() - Removes a field from The User Fields Parameter (uf)
  • SolrDisMaxQuery::setUserFields() - Sets User Fields parameter (uf)


Class Constructor

  • « SolrDisMaxQuery::addUserField
  • SolrDisMaxQuery::removeBigramPhraseField »
  • PHP Manual
  • SolrDisMaxQuery
  • Class Constructor

SolrDisMaxQuery::__construct

(No version information available, might only be in Git)

SolrDisMaxQuery::__construct — Class Constructor

Description

public SolrDisMaxQuery::__construct ([ string $q ] )

Class constructor initializes the object and sets the q parameter if passed

Parameters

q

Search Query (q parameter)

Return Values

Errors/Exceptions

Emits SolrIllegalArgumentException in case of an invalid parameter was passed.

Examples

Example #1 SolrDisMaxQuery::__construct() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');
echo $dismaxQuery;

?>

The above example will output:

q=lucene&defType=edismax

See Also


Removes phrase bigram field (pf2 parameter)

  • « SolrDisMaxQuery::__construct
  • SolrDisMaxQuery::removeBoostQuery »
  • PHP Manual
  • SolrDisMaxQuery
  • Removes phrase bigram field (pf2 parameter)

SolrDisMaxQuery::removeBigramPhraseField

(No version information available, might only be in Git)

SolrDisMaxQuery::removeBigramPhraseField — Removes phrase bigram field (pf2 parameter)

Description

public SolrDisMaxQuery::removeBigramPhraseField ( string $field ) : SolrDisMaxQuery

Removes a Bigram Phrase Field (pf2 parameter) that was previously added using SolrDisMaxQuery::addBigramPhraseField()

Parameters

field

The Field Name

Return Values

SolrDisMaxQuery

Examples

Example #1 SolrDisMaxQuery::removeBigramPhraseField() example

<?php

$dismaxQuery = new SolrDisMaxQuery("lucene");
$dismaxQuery
    ->addBigramPhraseField('cat', 2, 5.1)
    ->addBigramPhraseField('feature', 4.5)
;
echo $dismaxQuery.PHP_EOL;

// remove cat from pf2
$dismaxQuery
    ->removeBigramPhraseField('cat');
echo $dismaxQuery.PHP_EOL;

?>

The above example will output something similar to:

q=lucene&defType=edismax&pf2=cat~5.1^2 feature^4.5
q=lucene&defType=edismax&pf2=feature^4.5

See Also

  • SolrDisMaxQuery::addBigramPhraseField() - Adds a Phrase Bigram Field (pf2 parameter)
  • SolrDisMaxQuery::setBigramPhraseFields() - Sets Bigram Phrase Fields and their boosts (and slops) using pf2 parameter
  • SolrDisMaxQuery::setBigramPhraseSlop() - Sets Bigram Phrase Slop (ps2 parameter)


Removes a boost query partial by field name (bq)

  • « SolrDisMaxQuery::removeBigramPhraseField
  • SolrDisMaxQuery::removePhraseField »
  • PHP Manual
  • SolrDisMaxQuery
  • Removes a boost query partial by field name (bq)

SolrDisMaxQuery::removeBoostQuery

(No version information available, might only be in Git)

SolrDisMaxQuery::removeBoostQuery — Removes a boost query partial by field name (bq)

Description

public SolrDisMaxQuery::removeBoostQuery ( string $field ) : SolrDisMaxQuery

Removes a boost query partial from the existing query, only if SolrDisMaxQuery::addBoostQuery() was used.

Parameters

field

Field Name

Return Values

SolrDisMaxQuery

Examples

Example #1 SolrDisMaxQuery::removeBoostQuery() example

<?php

$dismaxQuery = new SolrDisMaxQuery("lucene");
$dismaxQuery
    ->addBoostQuery('cat', 'electronics', 5.1)
    ->addBoostQuery('cat', 'hard drive')
;
echo $dismaxQuery.PHP_EOL;
// now remove a query part with field 'cat'
$dismaxQuery
->removeBoostQuery('cat');
echo $dismaxQuery . PHP_EOL;

?>

The above example will output something similar to:

q=lucene&defType=edismax&bq=cat:electronics^5.1 cat:hard drive
q=lucene&defType=edismax&bq=cat:hard drive

See Also

  • SolrDisMaxQuery::addBoostQuery() - Adds a boost query field with value and optional boost (bq parameter)
  • SolrDisMaxQuery::setBoostQuery() - Directly Sets Boost Query Parameter (bq)


Removes a Phrase Field (pf parameter)

  • « SolrDisMaxQuery::removeBoostQuery
  • SolrDisMaxQuery::removeQueryField »
  • PHP Manual
  • SolrDisMaxQuery
  • Removes a Phrase Field (pf parameter)

SolrDisMaxQuery::removePhraseField

(No version information available, might only be in Git)

SolrDisMaxQuery::removePhraseField — Removes a Phrase Field (pf parameter)

Description

public SolrDisMaxQuery::removePhraseField ( string $field ) : SolrDisMaxQuery

Removes a Phrase Field (pf parameter) that was previously added using SolrDisMaxQuery::addPhraseField

Parameters

field

Field Name

Return Values

SolrDisMaxQuery

Examples

Example #1 SolrDisMaxQuery::removePhraseField() example

<?php
$dismaxQuery = new SolrDisMaxQuery('lucene');
$dismaxQuery
    ->addPhraseField('first', 3, 1)
    ->addPhraseField('second', 4, 1)
    ->addPhraseField('cat', 55);
echo $dismaxQuery . PHP_EOL;
echo $dismaxQuery->removePhraseField('second');
?>

The above example will output something similar to:

q=lucene&defType=edismax&pf=first~1^3 second~1^4 cat^55
q=lucene&defType=edismax&pf=first~1^3 cat^55

See Also

  • SolrDisMaxQuery::addPhraseField() - Adds a Phrase Field (pf parameter)
  • SolrDisMaxQuery::setPhraseFields() - Sets Phrase Fields and their boosts (and slops) using pf2 parameter


Removes a Query Field (qf parameter)

  • « SolrDisMaxQuery::removePhraseField
  • SolrDisMaxQuery::removeTrigramPhraseField »
  • PHP Manual
  • SolrDisMaxQuery
  • Removes a Query Field (qf parameter)

SolrDisMaxQuery::removeQueryField

(No version information available, might only be in Git)

SolrDisMaxQuery::removeQueryField — Removes a Query Field (qf parameter)

Description

public SolrDisMaxQuery::removeQueryField ( string $field ) : SolrDisMaxQuery

Removes a Query Field (qf parameter) from the field list added by SolrDisMaxQuery::addQueryField()

qf: When building DisjunctionMaxQueries from the user's query it specifies the fields to search in, and boosts for those fields.

Parameters

field

Field Name

Return Values

SolrDisMaxQuery

Examples

Example #1 SolrDisMaxQuery::removeQueryField() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');
$dismaxQuery
    ->addQueryField('first', 3)
    ->addQueryField('second', 0.2)
    ->addQueryField('cat');
echo $dismaxQuery . PHP_EOL;
// remove field 'second'
echo $dismaxQuery->removeQueryField('second');
?>

The above example will output something similar to:

q=lucene&defType=edismax&qf=first^3 second^0.2 cat
q=lucene&defType=edismax&qf=first^3 cat

See Also

  • SolrDisMaxQuery::addQueryField() - Add a query field with optional boost (qf parameter)


Removes a Trigram Phrase Field (pf3 parameter)

  • « SolrDisMaxQuery::removeQueryField
  • SolrDisMaxQuery::removeUserField »
  • PHP Manual
  • SolrDisMaxQuery
  • Removes a Trigram Phrase Field (pf3 parameter)

SolrDisMaxQuery::removeTrigramPhraseField

(No version information available, might only be in Git)

SolrDisMaxQuery::removeTrigramPhraseField — Removes a Trigram Phrase Field (pf3 parameter)

Description

public SolrDisMaxQuery::removeTrigramPhraseField ( string $field ) : SolrDisMaxQuery

Removes a Trigram Phrase Field (pf3 parameter)

Parameters

field

Field Name

Return Values

SolrDisMaxQuery

Examples

Example #1 SolrDisMaxQuery::removeTrigramPhraseField() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');
$dismaxQuery
->addTrigramPhraseField('cat', 2, 5.1)
->addTrigramPhraseField('feature', 4.5)
;
echo $dismaxQuery.PHP_EOL;
// reverse
$dismaxQuery
->removeTrigramPhraseField('cat');
echo $dismaxQuery.PHP_EOL;

?>

The above example will output:

q=lucene&defType=%s&pf3=cat~5.1^2 feature^4.5
q=lucene&defType=%s&pf3=feature^4.5

See Also

  • SolrDisMaxQuery::addTrigramPhraseField() - Adds a Trigram Phrase Field (pf3 parameter)
  • SolrDisMaxQuery::setTrigramPhraseFields() - Directly Sets Trigram Phrase Fields (pf3 parameter)
  • SolrDisMaxQuery::setTrigramPhraseSlop() - Sets Trigram Phrase Slop (ps3 parameter)


Removes a field from The User Fields Parameter (uf)

  • « SolrDisMaxQuery::removeTrigramPhraseField
  • SolrDisMaxQuery::setBigramPhraseFields »
  • PHP Manual
  • SolrDisMaxQuery
  • Removes a field from The User Fields Parameter (uf)

SolrDisMaxQuery::removeUserField

(No version information available, might only be in Git)

SolrDisMaxQuery::removeUserField — Removes a field from The User Fields Parameter (uf)

Description

public SolrDisMaxQuery::removeUserField ( string $field ) : SolrDisMaxQuery

Removes a field from The User Fields Parameter (uf)

Warning

This function is currently not documented; only its argument list is available.

Parameters

field

Field Name

Return Values

SolrDisMaxQuery

Examples

Example #1 SolrDisMaxQuery::removeUserField() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');
$dismaxQuery
->addUserField('cat')
->addUserField('text')
->addUserField('*_dt')
;
echo $dismaxQuery.PHP_EOL;

// remove field named 'text'
$dismaxQuery
->removeUserField('text');
echo $dismaxQuery.PHP_EOL;

?>

The above example will output something similar to:

q=lucene&defType=%s&uf=cat text *_dt
q=lucene&defType=%s&uf=cat *_dt

See Also

  • SolrDisMaxQuery::addUserField() - Adds a field to User Fields Parameter (uf)
  • SolrDisMaxQuery::setUserFields() - Sets User Fields parameter (uf)


Sets Bigram Phrase Fields and their boosts (and slops) using pf2 parameter

  • « SolrDisMaxQuery::removeUserField
  • SolrDisMaxQuery::setBigramPhraseSlop »
  • PHP Manual
  • SolrDisMaxQuery
  • Sets Bigram Phrase Fields and their boosts (and slops) using pf2 parameter

SolrDisMaxQuery::setBigramPhraseFields

(No version information available, might only be in Git)

SolrDisMaxQuery::setBigramPhraseFields — Sets Bigram Phrase Fields and their boosts (and slops) using pf2 parameter

Description

public SolrDisMaxQuery::setBigramPhraseFields ( string $fields ) : SolrDisMaxQuery

Sets Bigram Phrase Fields (pf2) and their boosts (and slops)

Parameters

fields

Fields boosts (slops)

Return Values

SolrDisMaxQuery

Examples

Example #1 SolrDisMaxQuery::setBigramPhraseFields() example

<?php
$dismaxQuery = new SolrDisMaxQuery("lucene");
$dismaxQuery->setBigramPhraseFields("cat~5.1^2 feature^4.5");
echo $dismaxQuery.PHP_EOL;

?>

The above example will output something similar to:

q=lucene&defType=edismax&pf2=cat~5.1^2 feature^4.5

See Also

  • SolrDisMaxQuery::setBigramPhraseSlop() - Sets Bigram Phrase Slop (ps2 parameter)
  • SolrDisMaxQuery::addBigramPhraseFields()
  • SolrDisMaxQuery::removeBigramPhraseField() - Removes phrase bigram field (pf2 parameter)
  • SolrDisMaxQuery::setTrigramPhraseFields() - Directly Sets Trigram Phrase Fields (pf3 parameter)


Sets Bigram Phrase Slop (ps2 parameter)

  • « SolrDisMaxQuery::setBigramPhraseFields
  • SolrDisMaxQuery::setBoostFunction »
  • PHP Manual
  • SolrDisMaxQuery
  • Sets Bigram Phrase Slop (ps2 parameter)

SolrDisMaxQuery::setBigramPhraseSlop

(No version information available, might only be in Git)

SolrDisMaxQuery::setBigramPhraseSlop — Sets Bigram Phrase Slop (ps2 parameter)

Description

public SolrDisMaxQuery::setBigramPhraseSlop ( string $slop ) : SolrDisMaxQuery

Sets Bigram Phrase Slop (ps2 parameter). A default slop for Bigram phrase fields.

Parameters

slop

Return Values

SolrDisMaxQuery

Examples

Example #1 SolrDisMaxQuery::setBigramPhraseSlop() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');

$dismaxQuery->setBigramPhraseSlop(5);
echo $dismaxQuery.PHP_EOL;

?>

The above example will output something similar to:

q=lucene&defType=edismax&ps2=5

See Also


Sets a Boost Function (bf parameter)

  • « SolrDisMaxQuery::setBigramPhraseSlop
  • SolrDisMaxQuery::setBoostQuery »
  • PHP Manual
  • SolrDisMaxQuery
  • Sets a Boost Function (bf parameter)

SolrDisMaxQuery::setBoostFunction

(No version information available, might only be in Git)

SolrDisMaxQuery::setBoostFunction — Sets a Boost Function (bf parameter)

Description

public SolrDisMaxQuery::setBoostFunction ( string $function ) : SolrDisMaxQuery

Sets Boost Function (bf parameter).

Functions (with optional boosts) that will be included in the user's query to influence the score. Any function supported natively by Solr can be used, along with a boost value. e.g.:

recip(rord(myfield),1,2,3)^1.5

Parameters

function

Return Values

SolrDisMaxQuery

Examples

Example #1 SolrDisMaxQuery::setBoostFunction() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');

$boostRecentDocsFunction = "recip(ms(NOW,mydatefield),3.16e-11,1,1)";
$dismaxQuery->setBoostFunction($boostRecentDocsFunction);

echo $dismaxQuery.PHP_EOL;

?>

The above example will output something similar to:

q=lucene&defType=edismax&bf=recip(ms(NOW,mydatefield),3.16e-11,1,1)

See Also


Directly Sets Boost Query Parameter (bq)

  • « SolrDisMaxQuery::setBoostFunction
  • SolrDisMaxQuery::setMinimumMatch »
  • PHP Manual
  • SolrDisMaxQuery
  • Directly Sets Boost Query Parameter (bq)

SolrDisMaxQuery::setBoostQuery

(No version information available, might only be in Git)

SolrDisMaxQuery::setBoostQuery — Directly Sets Boost Query Parameter (bq)

Description

public SolrDisMaxQuery::setBoostQuery ( string $q ) : SolrDisMaxQuery

Sets Boost Query Parameter (bq)

Parameters

q

query

Return Values

SolrDisMaxQuery

Examples

Example #1 SolrDisMaxQuery::setBoostQuery() example

<?php
$dismaxQuery = new SolrDisMaxQuery("lucene");

$dismaxQuery->setBoostQuery('cat:electronics manu:local^2');
echo $dismaxQuery.PHP_EOL;
?>

The above example will output something similar to:

q=lucene&defType=edismax&bq=cat:electronics manu:local^2

See Also

  • SolrDisMaxQuery::addBoostQuery() - Adds a boost query field with value and optional boost (bq parameter)
  • SolrDisMaxQuery::removeBoostQuery() - Removes a boost query partial by field name (bq)


Set Minimum "Should" Match (mm)

  • « SolrDisMaxQuery::setBoostQuery
  • SolrDisMaxQuery::setPhraseFields »
  • PHP Manual
  • SolrDisMaxQuery
  • Set Minimum "Should" Match (mm)

SolrDisMaxQuery::setMinimumMatch

(No version information available, might only be in Git)

SolrDisMaxQuery::setMinimumMatch — Set Minimum "Should" Match (mm)

Description

public SolrDisMaxQuery::setMinimumMatch ( string $value ) : SolrDisMaxQuery

Set Minimum "Should" Match parameter (mm). If the default query operator is AND then mm=100%, if the default query operator (q.op) is OR, then mm=0%.

Parameters

value

Minimum match value/expression

Return Values

SolrDisMaxQuery

Examples

Example #1 SolrDisMaxQuery::setMinimumMatch() example

<?php

$dismaxQuery = new SolrDisMaxQuery("lucene");
// 75% of the query clauses must match
$dismaxQuery->setMinimumMatch("75%");
echo $dismaxQuery . PHP_EOL;

?>

The above example will output:

q=lucene&defType=edismax&mm=75%


Sets Phrase Fields and their boosts (and slops) using pf2 parameter

  • « SolrDisMaxQuery::setMinimumMatch
  • SolrDisMaxQuery::setPhraseSlop »
  • PHP Manual
  • SolrDisMaxQuery
  • Sets Phrase Fields and their boosts (and slops) using pf2 parameter

SolrDisMaxQuery::setPhraseFields

(No version information available, might only be in Git)

SolrDisMaxQuery::setPhraseFields — Sets Phrase Fields and their boosts (and slops) using pf2 parameter

Description

public SolrDisMaxQuery::setPhraseFields ( string $fields ) : SolrDisMaxQuery

Sets Phrase Fields (pf) and their boosts (and slops)

Parameters

fields

Fields, boosts [, slops]

Return Values

SolrDisMaxQuery

Examples

Example #1 SolrDisMaxQuery::setPhraseFields() example

<?php
$dismaxQuery = new SolrDisMaxQuery("lucene");
$dismaxQuery->setPhraseFields("cat~5.1^2 feature^4.5");
echo $dismaxQuery.PHP_EOL;

?>

The above example will output something similar to:

q=lucene&defType=edismax&pf=cat~5.1^2 feature^4.5

See Also

  • SolrDisMaxQuery::addPhraseFields()
  • SolrDisMaxQuery::removePhraseField() - Removes a Phrase Field (pf parameter)


Sets the default slop on phrase queries (ps parameter)

  • « SolrDisMaxQuery::setPhraseFields
  • SolrDisMaxQuery::setQueryAlt »
  • PHP Manual
  • SolrDisMaxQuery
  • Sets the default slop on phrase queries (ps parameter)

SolrDisMaxQuery::setPhraseSlop

(No version information available, might only be in Git)

SolrDisMaxQuery::setPhraseSlop — Sets the default slop on phrase queries (ps parameter)

Description

public SolrDisMaxQuery::setPhraseSlop ( string $slop ) : SolrDisMaxQuery

Sets the default amount of slop on phrase queries built with "pf", "pf2" and/or "pf3" fields (affects boosting). "ps" parameter

Parameters

slop

Return Values

SolrDisMaxQuery

Examples

Example #1 SolrDisMaxQuery::setPhraseSlop() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');

$dismaxQuery->setPhraseSlop(4);
echo $dismaxQuery.PHP_EOL;

?>

The above example will output:

q=lucene&defType=edismax&ps=4

See Also


Set Query Alternate (q.alt parameter)

  • « SolrDisMaxQuery::setPhraseSlop
  • SolrDisMaxQuery::setQueryPhraseSlop »
  • PHP Manual
  • SolrDisMaxQuery
  • Set Query Alternate (q.alt parameter)

SolrDisMaxQuery::setQueryAlt

(No version information available, might only be in Git)

SolrDisMaxQuery::setQueryAlt — Set Query Alternate (q.alt parameter)

Description

public SolrDisMaxQuery::setQueryAlt ( string $q ) : SolrDisMaxQuery

Set Query Alternate (q.alt parameter)

When the main q parameter is not specified or is blank. The q.alt parameter is used

Parameters

q

Query String

Return Values

SolrDisMaxQuery

Examples

Example #1 SolrDisMaxQuery::setQueryAlt() example

<?php

$dismaxQuery = new DisMaxQuery();
$dismaxQuery->setQueryAlt('*:*');

?>

The above example will output something similar to:

defType=edismax&q.alt=*:*&q=


Specifies the amount of slop permitted on phrase queries explicitly included in the user's query string (qf parameter)

  • « SolrDisMaxQuery::setQueryAlt
  • SolrDisMaxQuery::setTieBreaker »
  • PHP Manual
  • SolrDisMaxQuery
  • Specifies the amount of slop permitted on phrase queries explicitly included in the user's query string (qf parameter)

SolrDisMaxQuery::setQueryPhraseSlop

(No version information available, might only be in Git)

SolrDisMaxQuery::setQueryPhraseSlop — Specifies the amount of slop permitted on phrase queries explicitly included in the user's query string (qf parameter)

Description

public SolrDisMaxQuery::setQueryPhraseSlop ( string $slop ) : SolrDisMaxQuery

The Query Phrase Slop is the amount of slop permitted on phrase queries explicitly included in the user's query string with the qf parameter.

slop refers to the number of positions one token needs to be moved in relation to another token in order to match a phrase specified in a query.

Parameters

slop

Amount of slop

Return Values

SolrDisMaxQuery

Examples

Example #1 SolrDisMaxQuery::setQueryPhraseSlop() example

<?php

$dismaxQuery = new SolrDisMaxQuery();
$dismaxQuery->setQueryPhraseSlop(3);
echo $dismaxQuery;
?>

The above example will output something similar to:

defType=edismax&qs=3


Sets Tie Breaker parameter (tie parameter)

  • « SolrDisMaxQuery::setQueryPhraseSlop
  • SolrDisMaxQuery::setTrigramPhraseFields »
  • PHP Manual
  • SolrDisMaxQuery
  • Sets Tie Breaker parameter (tie parameter)

SolrDisMaxQuery::setTieBreaker

(No version information available, might only be in Git)

SolrDisMaxQuery::setTieBreaker — Sets Tie Breaker parameter (tie parameter)

Description

public SolrDisMaxQuery::setTieBreaker ( string $tieBreaker ) : SolrDisMaxQuery

Sets Tie Breaker parameter (tie parameter)

Parameters

tieBreaker

The tie parameter specifies a float value (which should be something much less than 1) to use as tiebreaker in DisMax queries.

Return Values

SolrDisMaxQuery

Examples

Example #1 SolrDisMaxQuery::setTieBreaker() example

<?php

$dismaxQuery = new SolrDisMaxQuery();
$dismaxQuery->setTieBreaker(0.1);

echo $dismaxQuery;

?>

The above example will output:

defType=edismax&tie=0.1


Directly Sets Trigram Phrase Fields (pf3 parameter)

  • « SolrDisMaxQuery::setTieBreaker
  • SolrDisMaxQuery::setTrigramPhraseSlop »
  • PHP Manual
  • SolrDisMaxQuery
  • Directly Sets Trigram Phrase Fields (pf3 parameter)

SolrDisMaxQuery::setTrigramPhraseFields

(No version information available, might only be in Git)

SolrDisMaxQuery::setTrigramPhraseFields — Directly Sets Trigram Phrase Fields (pf3 parameter)

Description

public SolrDisMaxQuery::setTrigramPhraseFields ( string $fields ) : SolrDisMaxQuery

Directly Sets Trigram Phrase Fields (pf3 parameter)

Parameters

fields

Trigram Phrase Fields

Return Values

SolrDisMaxQuery

Examples

Example #1 SolrDisMaxQuery::setTrigramPhraseFields() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');
$dismaxQuery->setTrigramPhraseFields('cat~5.1^2 feature^4.5');
echo $dismaxQuery.PHP_EOL;

?>

The above example will output:

q=lucene&defType=edismax&pf3=cat~5.1^2 feature^4.5

See Also

  • SolrDisMaxQuery::addTrigramPhraseField() - Adds a Trigram Phrase Field (pf3 parameter)
  • SolrDisMaxQuery::removeTrigramPhraseField() - Removes a Trigram Phrase Field (pf3 parameter)
  • SolrDisMaxQuery::setTrigramPhraseSlop() - Sets Trigram Phrase Slop (ps3 parameter)


Sets Trigram Phrase Slop (ps3 parameter)

  • « SolrDisMaxQuery::setTrigramPhraseFields
  • SolrDisMaxQuery::setUserFields »
  • PHP Manual
  • SolrDisMaxQuery
  • Sets Trigram Phrase Slop (ps3 parameter)

SolrDisMaxQuery::setTrigramPhraseSlop

(No version information available, might only be in Git)

SolrDisMaxQuery::setTrigramPhraseSlop — Sets Trigram Phrase Slop (ps3 parameter)

Description

public SolrDisMaxQuery::setTrigramPhraseSlop ( string $slop ) : SolrDisMaxQuery

Sets Trigram Phrase Slop (ps3 parameter)

Parameters

slop

Phrase slop

Return Values

SolrDisMaxQuery

Examples

Example #1 SolrDisMaxQuery::setTrigramPhraseSlop() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');
$dismaxQuery->setTrigramPhraseSlop(2);
echo $dismaxQuery.PHP_EOL;

?>

The above example will output something similar to:

q=lucene&defType=edismax&ps3=2

See Also

  • SolrDisMaxQuery::addTrigramPhraseField() - Adds a Trigram Phrase Field (pf3 parameter)
  • SolrDisMaxQuery::removeTrigramPhraseField() - Removes a Trigram Phrase Field (pf3 parameter)
  • SolrDisMaxQuery::setTrigramPhraseFields() - Directly Sets Trigram Phrase Fields (pf3 parameter)


Sets User Fields parameter (uf)

  • « SolrDisMaxQuery::setTrigramPhraseSlop
  • SolrDisMaxQuery::useDisMaxQueryParser »
  • PHP Manual
  • SolrDisMaxQuery
  • Sets User Fields parameter (uf)

SolrDisMaxQuery::setUserFields

(No version information available, might only be in Git)

SolrDisMaxQuery::setUserFields — Sets User Fields parameter (uf)

Description

public SolrDisMaxQuery::setUserFields ( string $fields ) : SolrDisMaxQuery

Sets User Fields parameter (uf)

User Fields: Specifies which schema fields the end user shall be allowed to query.

Parameters

fields

Fields names separated by space

This parameter supports wildcards.

Return Values

SolrDisMaxQuery

Examples

Example #1 SolrDisMaxQuery::setUserFields() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');
$dismaxQuery->setUserFields('field1 field2 *_txt');
echo $dismaxQuery.PHP_EOL;

?>

The above example will output something similar to:

q=lucene&defType=edismax&uf=field1 field2 *_txt

See Also

  • SolrDisMaxQuery::addUserField() - Adds a field to User Fields Parameter (uf)
  • SolrDisMaxQuery::removeUserField() - Removes a field from The User Fields Parameter (uf)


Switch QueryParser to be DisMax Query Parser

  • « SolrDisMaxQuery::setUserFields
  • SolrDisMaxQuery::useEDisMaxQueryParser »
  • PHP Manual
  • SolrDisMaxQuery
  • Switch QueryParser to be DisMax Query Parser

SolrDisMaxQuery::useDisMaxQueryParser

(No version information available, might only be in Git)

SolrDisMaxQuery::useDisMaxQueryParser — Switch QueryParser to be DisMax Query Parser

Description

public SolrDisMaxQuery::useDisMaxQueryParser ( void ) : SolrDisMaxQuery

Switch QueryParser to be DisMax Query Parser

Parameters

This function has no parameters.

Return Values

SolrDisMaxQuery

Examples

Example #1 SolrDisMaxQuery::useDisMaxQueryParser() example

<?php

$dismaxQuery = new SolrDisMaxQuery();
$dismaxQuery->useDisMaxQueryParser();
echo $dismaxQuery;
?>

The above example will output something similar to:

defType=dismax

See Also

  • SolrDisMaxQuery::useDisMaxQueryParser()


Switch QueryParser to be EDisMax

  • « SolrDisMaxQuery::useDisMaxQueryParser
  • SolrCollapseFunction »
  • PHP Manual
  • SolrDisMaxQuery
  • Switch QueryParser to be EDisMax

SolrDisMaxQuery::useEDisMaxQueryParser

(No version information available, might only be in Git)

SolrDisMaxQuery::useEDisMaxQueryParser — Switch QueryParser to be EDisMax

Description

public SolrDisMaxQuery::useEDisMaxQueryParser ( void ) : SolrDisMaxQuery

Switch QueryParser to be EDisMax. By default the query builder uses edismax, if it was switched using SolrDisMaxQuery::useDisMaxQueryParser(), it can be switched back using this method.

Parameters

This function has no parameters.

Return Values

SolrDisMaxQuery

Examples

Example #1 SolrDisMaxQuery::useEDisMaxQueryParser() example

<?php

$dismaxQuery = new SolrDisMaxQuery();
$dismaxQuery->useEDisMaxQueryParser();
echo $dismaxQuery;

?>

The above example will output something similar to:

defType=edismax

See Also


The SolrCollapseFunction class

(PECL solr >= 2.2.0)

Introduction

Class synopsis

SolrCollapseFunction {
/* Constants */
const string NULLPOLICY_IGNORE = ignore ;
const string NULLPOLICY_EXPAND = expand ;
const string NULLPOLICY_COLLAPSE = collapse ;
/* Methods */
public __construct ([ string $field ] )
public getField ( void ) : string
public getHint ( void ) : string
public getMax ( void ) : string
public getMin ( void ) : string
public getNullPolicy ( void ) : string
public getSize ( void ) : int
public setField ( string $fieldName ) : SolrCollapseFunction
public setHint ( string $hint ) : SolrCollapseFunction
public setMax ( string $max ) : SolrCollapseFunction
public setMin ( string $min ) : SolrCollapseFunction
public setNullPolicy ( string $nullPolicy ) : SolrCollapseFunction
public setSize ( int $size ) : SolrCollapseFunction
public __toString ( void ) : string
}

Predefined Constants

SolrCollapseFunction::NULLPOLICY_IGNORE

SolrCollapseFunction::NULLPOLICY_EXPAND

SolrCollapseFunction::NULLPOLICY_COLLAPSE

Table of Contents

  • SolrCollapseFunction::__construct — Constructor
  • SolrCollapseFunction::getField — Returns the field that is being collapsed on
  • SolrCollapseFunction::getHint — Returns collapse hint
  • SolrCollapseFunction::getMax — Returns max parameter
  • SolrCollapseFunction::getMin — Returns min parameter
  • SolrCollapseFunction::getNullPolicy — Returns null policy
  • SolrCollapseFunction::getSize — Returns size parameter
  • SolrCollapseFunction::setField — Sets the field to collapse on
  • SolrCollapseFunction::setHint — Sets collapse hint
  • SolrCollapseFunction::setMax — Selects the group heads by the max value of a numeric field or function query
  • SolrCollapseFunction::setMin — Sets the initial size of the collapse data structures when collapsing on a numeric field only
  • SolrCollapseFunction::setNullPolicy — Sets the NULL Policy
  • SolrCollapseFunction::setSize — Sets the initial size of the collapse data structures when collapsing on a numeric field only
  • SolrCollapseFunction::__toString — Returns a string representing the constructed collapse function


Constructor

  • « SolrCollapseFunction
  • SolrCollapseFunction::getField »
  • PHP Manual
  • SolrCollapseFunction
  • Constructor

SolrCollapseFunction::__construct

(PECL solr >= 2.2.0)

SolrCollapseFunction::__construct — Constructor

Description

public SolrCollapseFunction::__construct ([ string $field ] )

Collapse Function constructor

Parameters

field

The field name to collapse on.

In order to collapse a result. The field type must be a single valued String, Int or Float.

Examples

Example #1 SolrCollapseFunction::__construct() example

<?php

include "bootstrap.php";

$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
    'path'     => SOLR_SERVER_PATH
);

$client = new SolrClient($options);

$query = new SolrQuery('*:*');

$func = new SolrCollapseFunction('field_name');

$func->setMax('sum(cscore(),field(some_other_field))');
$func->setSize(100);
$func->setNullPolicy(SolrCollapseFunction::NULLPOLICY_EXPAND);

$query->collapse($func);

$queryResponse = $client->query($query);

$response = $queryResponse->getResponse();

print_r($response);

?>

See Also

  • SolrQuery::collapse() - Collapses the result set to a single document per group


Returns the field that is being collapsed on

  • « SolrCollapseFunction::__construct
  • SolrCollapseFunction::getHint »
  • PHP Manual
  • SolrCollapseFunction
  • Returns the field that is being collapsed on

SolrCollapseFunction::getField

(PECL solr >= 2.2.0)

SolrCollapseFunction::getField — Returns the field that is being collapsed on

Description

public SolrCollapseFunction::getField ( void ) : string

Returns the field that is being collapsed on.

Parameters

This function has no parameters.

Return Values

See Also

  • SolrCollapseFunction::setField() - Sets the field to collapse on


Returns collapse hint

  • « SolrCollapseFunction::getField
  • SolrCollapseFunction::getMax »
  • PHP Manual
  • SolrCollapseFunction
  • Returns collapse hint

SolrCollapseFunction::getHint

(PECL solr >= 2.2.0)

SolrCollapseFunction::getHint — Returns collapse hint

Description

public SolrCollapseFunction::getHint ( void ) : string

Returns collapse hint

Parameters

This function has no parameters.

Return Values

See Also

  • SolrCollapseFunction::setHint() - Sets collapse hint


Returns max parameter

  • « SolrCollapseFunction::getHint
  • SolrCollapseFunction::getMin »
  • PHP Manual
  • SolrCollapseFunction
  • Returns max parameter

SolrCollapseFunction::getMax

(PECL solr >= 2.2.0)

SolrCollapseFunction::getMax — Returns max parameter

Description

public SolrCollapseFunction::getMax ( void ) : string

Returns max parameter

Parameters

This function has no parameters.

Return Values

See Also

  • SolrCollapseFunction::setMax() - Selects the group heads by the max value of a numeric field or function query


Returns min parameter

  • « SolrCollapseFunction::getMax
  • SolrCollapseFunction::getNullPolicy »
  • PHP Manual
  • SolrCollapseFunction
  • Returns min parameter

SolrCollapseFunction::getMin

(PECL solr >= 2.2.0)

SolrCollapseFunction::getMin — Returns min parameter

Description

public SolrCollapseFunction::getMin ( void ) : string

Returns min parameter

Parameters

This function has no parameters.

Return Values

See Also

  • SolrCollapseFunction::setMin() - Sets the initial size of the collapse data structures when collapsing on a numeric field only


Returns null policy

  • « SolrCollapseFunction::getMin
  • SolrCollapseFunction::getSize »
  • PHP Manual
  • SolrCollapseFunction
  • Returns null policy

SolrCollapseFunction::getNullPolicy

(PECL solr >= 2.2.0)

SolrCollapseFunction::getNullPolicy — Returns null policy

Description

public SolrCollapseFunction::getNullPolicy ( void ) : string

Returns null policy used or null

Parameters

This function has no parameters.

Return Values

See Also

  • SolrCollapseFunction::setNullPolicy() - Sets the NULL Policy


Returns size parameter

  • « SolrCollapseFunction::getNullPolicy
  • SolrCollapseFunction::setField »
  • PHP Manual
  • SolrCollapseFunction
  • Returns size parameter

SolrCollapseFunction::getSize

(PECL solr >= 2.2.0)

SolrCollapseFunction::getSize — Returns size parameter

Description

public SolrCollapseFunction::getSize ( void ) : int

Gets the initial size of the collapse data structures when collapsing on a numeric field only

Parameters

This function has no parameters.

Return Values

See Also

  • SolrCollapseFunction::setSize() - Sets the initial size of the collapse data structures when collapsing on a numeric field only


Sets the field to collapse on

  • « SolrCollapseFunction::getSize
  • SolrCollapseFunction::setHint »
  • PHP Manual
  • SolrCollapseFunction
  • Sets the field to collapse on

SolrCollapseFunction::setField

(PECL solr >= 2.2.0)

SolrCollapseFunction::setField — Sets the field to collapse on

Description

public SolrCollapseFunction::setField ( string $fieldName ) : SolrCollapseFunction

The field name to collapse on. In order to collapse a result. The field type must be a single valued String, Int or Float.

Parameters

fieldName

Return Values

SolrCollapseFunction


Sets collapse hint

  • « SolrCollapseFunction::setField
  • SolrCollapseFunction::setMax »
  • PHP Manual
  • SolrCollapseFunction
  • Sets collapse hint

SolrCollapseFunction::setHint

(PECL solr >= 2.2.0)

SolrCollapseFunction::setHint — Sets collapse hint

Description

public SolrCollapseFunction::setHint ( string $hint ) : SolrCollapseFunction

Sets collapse hint

Parameters

hint

Currently there is only one hint available "top_fc", which stands for top level FieldCache

Return Values

SolrCollapseFunction

Examples

Example #1 SolrCollapseFunction::setHint() example

<?php

/* ... */

?>

The above example will output something similar to:

...


Selects the group heads by the max value of a numeric field or function query

  • « SolrCollapseFunction::setHint
  • SolrCollapseFunction::setMin »
  • PHP Manual
  • SolrCollapseFunction
  • Selects the group heads by the max value of a numeric field or function query

SolrCollapseFunction::setMax

(PECL solr >= 2.2.0)

SolrCollapseFunction::setMax — Selects the group heads by the max value of a numeric field or function query

Description

public SolrCollapseFunction::setMax ( string $max ) : SolrCollapseFunction

Selects the group heads by the max value of a numeric field or function query.

Parameters

max

Return Values

SolrCollapseFunction

Examples

Example #1 SolrCollapseFunction::setMax() example

<?php

$func = new SolrCollapseFunction('field_name');

$func->setMax('sum(cscore(),field(some_field))');

$query = new SolrQuery('*:*');

$query->collapse($func);

?>


Sets the initial size of the collapse data structures when collapsing on a numeric field only

  • « SolrCollapseFunction::setMax
  • SolrCollapseFunction::setNullPolicy »
  • PHP Manual
  • SolrCollapseFunction
  • Sets the initial size of the collapse data structures when collapsing on a numeric field only

SolrCollapseFunction::setMin

(PECL solr >= 2.2.0)

SolrCollapseFunction::setMin — Sets the initial size of the collapse data structures when collapsing on a numeric field only

Description

public SolrCollapseFunction::setMin ( string $min ) : SolrCollapseFunction

Sets the initial size of the collapse data structures when collapsing on a numeric field only

Parameters

min

Return Values

SolrCollapseFunction


Sets the NULL Policy

  • « SolrCollapseFunction::setMin
  • SolrCollapseFunction::setSize »
  • PHP Manual
  • SolrCollapseFunction
  • Sets the NULL Policy

SolrCollapseFunction::setNullPolicy

(PECL solr >= 2.2.0)

SolrCollapseFunction::setNullPolicy — Sets the NULL Policy

Description

public SolrCollapseFunction::setNullPolicy ( string $nullPolicy ) : SolrCollapseFunction

Sets the NULL Policy. One of the 3 policies defined as class constants shall be passed. Accepts ignore, expand, or collapse policies.

Parameters

nullPolicy

Return Values

SolrCollapseFunction


Sets the initial size of the collapse data structures when collapsing on a numeric field only

  • « SolrCollapseFunction::setNullPolicy
  • SolrCollapseFunction::__toString »
  • PHP Manual
  • SolrCollapseFunction
  • Sets the initial size of the collapse data structures when collapsing on a numeric field only

SolrCollapseFunction::setSize

(PECL solr >= 2.2.0)

SolrCollapseFunction::setSize — Sets the initial size of the collapse data structures when collapsing on a numeric field only

Description

public SolrCollapseFunction::setSize ( int $size ) : SolrCollapseFunction

Sets the initial size of the collapse data structures when collapsing on a numeric field only.

Parameters

size

Return Values

SolrCollapseFunction


Returns a string representing the constructed collapse function

  • « SolrCollapseFunction::setSize
  • SolrException »
  • PHP Manual
  • SolrCollapseFunction
  • Returns a string representing the constructed collapse function

SolrCollapseFunction::__toString

(PECL solr >= 2.2.0)

SolrCollapseFunction::__toString — Returns a string representing the constructed collapse function

Description

public SolrCollapseFunction::__toString ( void ) : string

Returns a string representing the constructed collapse function

Parameters

This function has no parameters.

Return Values


The SolrException class

(PECL solr >= 0.9.2)

Introduction

This is the base class for all exception thrown by the Solr extension classes.

Class synopsis

SolrException extends Exception {
/* Properties */
protected integer $sourceline ;
protected string $sourcefile ;
protected string $zif_name ;
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Methods */
public getInternalInfo ( void ) : array
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}

Properties

sourceline

The line in c-space source file where exception was generated

sourcefile

The c-space source file where exception was generated

zif_name

The c-space function where exception was generated

Table of Contents

  • SolrException::getInternalInfo — Returns internal information where the Exception was thrown


Returns internal information where the Exception was thrown

  • « SolrException
  • SolrClientException »
  • PHP Manual
  • SolrException
  • Returns internal information where the Exception was thrown

SolrException::getInternalInfo

(PECL solr >= 0.9.2)

SolrException::getInternalInfo — Returns internal information where the Exception was thrown

Description

public SolrException::getInternalInfo ( void ) : array

Returns internal information where the Exception was thrown.

Parameters

This function has no parameters.

Return Values

Returns an array containing internal information where the error was thrown. Used only for debugging by extension developers.


The SolrClientException class

(PECL solr >= 0.9.2)

Introduction

An exception thrown when there is an error while making a request to the server from the client.

Class synopsis

SolrClientException extends SolrException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
protected integer $sourceline ;
protected string $sourcefile ;
protected string $zif_name ;
/* Methods */
public getInternalInfo ( void ) : array
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
public SolrException::getInternalInfo ( void ) : array
}

Table of Contents

  • SolrClientException::getInternalInfo — Returns internal information where the Exception was thrown


Returns internal information where the Exception was thrown

  • « SolrClientException
  • SolrServerException »
  • PHP Manual
  • SolrClientException
  • Returns internal information where the Exception was thrown

SolrClientException::getInternalInfo

(PECL solr >= 0.9.2)

SolrClientException::getInternalInfo — Returns internal information where the Exception was thrown

Description

public SolrClientException::getInternalInfo ( void ) : array

Returns internal information where the Exception was thrown.

Parameters

This function has no parameters.

Return Values

Returns an array containing internal information where the error was thrown. Used only for debugging by extension developers.


The SolrServerException class

(PECL Solr >= 1.1.0, >=2.0.0)

Introduction

An exception thrown when there is an error produced by the Solr Server itself.

Class synopsis

SolrServerException extends SolrException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
protected integer $sourceline ;
protected string $sourcefile ;
protected string $zif_name ;
/* Methods */
public getInternalInfo ( void ) : array
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
public SolrException::getInternalInfo ( void ) : array
}

Table of Contents

  • SolrServerException::getInternalInfo — Returns internal information where the Exception was thrown


Returns internal information where the Exception was thrown

  • « SolrServerException
  • SolrIllegalArgumentException »
  • PHP Manual
  • SolrServerException
  • Returns internal information where the Exception was thrown

SolrServerException::getInternalInfo

(PECL solr >= 1.1.0, >=2.0.0)

SolrServerException::getInternalInfo — Returns internal information where the Exception was thrown

Description

public SolrServerException::getInternalInfo ( void ) : array

Returns internal information where the Exception was thrown.

Parameters

This function has no parameters.

Return Values

Returns an array containing internal information where the error was thrown. Used only for debugging by extension developers.


The SolrIllegalArgumentException class

(PECL solr >= 0.9.2)

Introduction

This object is thrown when an illegal or invalid argument is passed to a method.

Class synopsis

SolrIllegalArgumentException extends SolrException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
protected integer $sourceline ;
protected string $sourcefile ;
protected string $zif_name ;
/* Methods */
public getInternalInfo ( void ) : array
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
public SolrException::getInternalInfo ( void ) : array
}

Table of Contents

  • SolrIllegalArgumentException::getInternalInfo — Returns internal information where the Exception was thrown


Returns internal information where the Exception was thrown

  • « SolrIllegalArgumentException
  • SolrIllegalOperationException »
  • PHP Manual
  • SolrIllegalArgumentException
  • Returns internal information where the Exception was thrown

SolrIllegalArgumentException::getInternalInfo

(PECL solr >= 0.9.2)

SolrIllegalArgumentException::getInternalInfo — Returns internal information where the Exception was thrown

Description

public SolrIllegalArgumentException::getInternalInfo ( void ) : array

Returns internal information where the Exception was thrown.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns an array containing internal information where the error was thrown. Used only for debugging by extension developers.


The SolrIllegalOperationException class

(PECL solr >= 0.9.2)

Introduction

This object is thrown when an illegal or unsupported operation is performed on an object.

Class synopsis

SolrIllegalOperationException extends SolrException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
protected integer $sourceline ;
protected string $sourcefile ;
protected string $zif_name ;
/* Methods */
public getInternalInfo ( void ) : array
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
public SolrException::getInternalInfo ( void ) : array
}

Table of Contents

  • SolrIllegalOperationException::getInternalInfo — Returns internal information where the Exception was thrown


Returns internal information where the Exception was thrown

  • « SolrIllegalOperationException
  • SolrMissingMandatoryParameterException »
  • PHP Manual
  • SolrIllegalOperationException
  • Returns internal information where the Exception was thrown

SolrIllegalOperationException::getInternalInfo

(PECL solr >= 0.9.2)

SolrIllegalOperationException::getInternalInfo — Returns internal information where the Exception was thrown

Description

public SolrIllegalOperationException::getInternalInfo ( void ) : array

Returns internal information where the Exception was thrown.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns an array containing internal information where the error was thrown. Used only for debugging by extension developers.


The SolrMissingMandatoryParameterException class

(No version information available, might only be in Git)

Introduction

Class synopsis

SolrMissingMandatoryParameterException extends SolrException {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
protected integer $sourceline ;
protected string $sourcefile ;
protected string $zif_name ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
public SolrException::getInternalInfo ( void ) : array
}


Sphinx Client

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • SphinxClient — The SphinxClient class
    • SphinxClient::addQuery — Add query to multi-query batch
    • SphinxClient::buildExcerpts — Build text snippets
    • SphinxClient::buildKeywords — Extract keywords from query
    • SphinxClient::close — Closes previously opened persistent connection
    • SphinxClient::__construct — Create a new SphinxClient object
    • SphinxClient::escapeString — Escape special characters
    • SphinxClient::getLastError — Get the last error message
    • SphinxClient::getLastWarning — Get the last warning
    • SphinxClient::open — Opens persistent connection to the server
    • SphinxClient::query — Execute search query
    • SphinxClient::resetFilters — Clear all filters
    • SphinxClient::resetGroupBy — Clear all group-by settings
    • SphinxClient::runQueries — Run a batch of search queries
    • SphinxClient::setArrayResult — Change the format of result set array
    • SphinxClient::setConnectTimeout — Set connection timeout
    • SphinxClient::setFieldWeights — Set field weights
    • SphinxClient::setFilter — Add new integer values set filter
    • SphinxClient::setFilterFloatRange — Add new float range filter
    • SphinxClient::setFilterRange — Add new integer range filter
    • SphinxClient::setGeoAnchor — Set anchor point for a geosphere distance calculations
    • SphinxClient::setGroupBy — Set grouping attribute
    • SphinxClient::setGroupDistinct — Set attribute name for per-group distinct values count calculations
    • SphinxClient::setIDRange — Set a range of accepted document IDs
    • SphinxClient::setIndexWeights — Set per-index weights
    • SphinxClient::setLimits — Set offset and limit of the result set
    • SphinxClient::setMatchMode — Set full-text query matching mode
    • SphinxClient::setMaxQueryTime — Set maximum query time
    • SphinxClient::setOverride — Sets temporary per-document attribute value overrides
    • SphinxClient::setRankingMode — Set ranking mode
    • SphinxClient::setRetries — Set retry count and delay
    • SphinxClient::setSelect — Set select clause
    • SphinxClient::setServer — Set searchd host and port
    • SphinxClient::setSortMode — Set matches sorting mode
    • SphinxClient::status — Queries searchd status
    • SphinxClient::updateAttributes — Update document attributes


Introduction

This extension provides bindings for Sphinx search client library. Sphinx is a standalone search engine meant to provide fast, size-efficient and relevant fulltext search functions to other applications. Sphinx was specially designed to integrate well with SQL databases and scripting languages. Both Sphinx and its client library can be obtained from the » official site


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

PECL/sphinx requires PHP 5.2.2 or newer.


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/sphinx.

If the ./configure script generated by phpize is having trouble finding the libsphinxclient files (for example, it was installed into a custom prefix directory), use ./configure --with-sphinx=$PREFIX, where $PREFIX is installation prefix of libsphinxclient.


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.

SEARCHD_OK (integer)
SEARCHD_ERROR (integer)
SEARCHD_RETRY (integer)
SEARCHD_WARNING (integer)
SPH_MATCH_ALL (integer)
SPH_MATCH_ANY (integer)
SPH_MATCH_PHRASE (integer)
SPH_MATCH_BOOLEAN (integer)
SPH_MATCH_EXTENDED (integer)
SPH_MATCH_FULLSCAN (integer)
SPH_MATCH_EXTENDED2 (integer)
SPH_RANK_PROXIMITY_BM25 (integer)
SPH_RANK_BM25 (integer)
SPH_RANK_NONE (integer)
SPH_RANK_WORDCOUNT (integer)
SPH_SORT_RELEVANCE (integer)
SPH_SORT_ATTR_DESC (integer)
SPH_SORT_ATTR_ASC (integer)
SPH_SORT_TIME_SEGMENTS (integer)
SPH_SORT_EXTENDED (integer)
SPH_SORT_EXPR (integer)
SPH_FILTER_VALUES (integer)
SPH_FILTER_RANGE (integer)
SPH_FILTER_FLOATRANGE (integer)
SPH_ATTR_INTEGER (integer)
SPH_ATTR_TIMESTAMP (integer)
SPH_ATTR_ORDINAL (integer)
SPH_ATTR_BOOL (integer)
SPH_ATTR_FLOAT (integer)
SPH_ATTR_MULTI (integer)
SPH_GROUPBY_DAY (integer)
SPH_GROUPBY_WEEK (integer)
SPH_GROUPBY_MONTH (integer)
SPH_GROUPBY_YEAR (integer)
SPH_GROUPBY_ATTR (integer)
SPH_GROUPBY_ATTRPAIR (integer)


Examples

Example #1 Basic usage example

<?php

$s = new SphinxClient;
$s->setServer("localhost", 6712);
$s->setMatchMode(SPH_MATCH_ANY);
$s->setMaxQueryTime(3);

$result = $s->query("test");

var_dump($result);

?>

The above example will output something similar to:

array(10) {
  ["error"]=>
  string(0) ""
  ["warning"]=>
  string(0) ""
  ["status"]=>
  int(0)
  ["fields"]=>
  array(3) {
    [0]=>
    string(7) "subject"
    [1]=>
    string(4) "body"
    [2]=>
    string(6) "author"
  }
  ["attrs"]=>
  array(0) {
  }
  ["matches"]=>
  array(1) {
    [3]=>
    array(2) {
      ["weight"]=>
      int(1)
      ["attrs"]=>
      array(0) {
      }
    }
  }
  ["total"]=>
  int(1)
  ["total_found"]=>
  int(1)
  ["time"]=>
  float(0)
  ["words"]=>
  array(1) {
    ["to"]=>
    array(2) {
      ["docs"]=>
      int(1)
      ["hits"]=>
      int(1)
    }
  }
}


The SphinxClient class

(PECL sphinx >= 0.1.0)

Introduction

The SphinxClient class provides object-oriented interface to Sphinx.

Class synopsis

SphinxClient {
/* Methods */
public addQuery ( string $query [, string $index = "*" [, string $comment = "" ]] ) : int
public buildExcerpts ( array $docs , string $index , string $words [, array $opts ] ) : array
public buildKeywords ( string $query , string $index , bool $hits ) : array
public close ( void ) : bool
public __construct ( void )
public escapeString ( string $string ) : string
public getLastError ( void ) : string
public getLastWarning ( void ) : string
public open ( void ) : bool
public query ( string $query [, string $index = "*" [, string $comment = "" ]] ) : array
public resetFilters ( void ) : void
public resetGroupBy ( void ) : void
public runQueries ( void ) : array
public setArrayResult ( bool $array_result = FALSE ) : bool
public setConnectTimeout ( float $timeout ) : bool
public setFieldWeights ( array $weights ) : bool
public setFilter ( string $attribute , array $values [, bool $exclude = FALSE ] ) : bool
public setFilterFloatRange ( string $attribute , float $min , float $max [, bool $exclude = FALSE ] ) : bool
public setFilterRange ( string $attribute , int $min , int $max [, bool $exclude = FALSE ] ) : bool
public setGeoAnchor ( string $attrlat , string $attrlong , float $latitude , float $longitude ) : bool
public setGroupBy ( string $attribute , int $func [, string $groupsort = "@group desc" ] ) : bool
public setGroupDistinct ( string $attribute ) : bool
public setIDRange ( int $min , int $max ) : bool
public setIndexWeights ( array $weights ) : bool
public setLimits ( int $offset , int $limit [, int $max_matches = 0 [, int $cutoff = 0 ]] ) : bool
public setMatchMode ( int $mode ) : bool
public setMaxQueryTime ( int $qtime ) : bool
public setOverride ( string $attribute , int $type , array $values ) : bool
public setRankingMode ( int $ranker ) : bool
public setRetries ( int $count [, int $delay = 0 ] ) : bool
public setSelect ( string $clause ) : bool
public setServer ( string $server , int $port ) : bool
public setSortMode ( int $mode [, string $sortby ] ) : bool
public status ( void ) : array
public updateAttributes ( string $index , array $attributes , array $values [, bool $mva = FALSE ] ) : int
}

Table of Contents

  • SphinxClient::addQuery — Add query to multi-query batch
  • SphinxClient::buildExcerpts — Build text snippets
  • SphinxClient::buildKeywords — Extract keywords from query
  • SphinxClient::close — Closes previously opened persistent connection
  • SphinxClient::__construct — Create a new SphinxClient object
  • SphinxClient::escapeString — Escape special characters
  • SphinxClient::getLastError — Get the last error message
  • SphinxClient::getLastWarning — Get the last warning
  • SphinxClient::open — Opens persistent connection to the server
  • SphinxClient::query — Execute search query
  • SphinxClient::resetFilters — Clear all filters
  • SphinxClient::resetGroupBy — Clear all group-by settings
  • SphinxClient::runQueries — Run a batch of search queries
  • SphinxClient::setArrayResult — Change the format of result set array
  • SphinxClient::setConnectTimeout — Set connection timeout
  • SphinxClient::setFieldWeights — Set field weights
  • SphinxClient::setFilter — Add new integer values set filter
  • SphinxClient::setFilterFloatRange — Add new float range filter
  • SphinxClient::setFilterRange — Add new integer range filter
  • SphinxClient::setGeoAnchor — Set anchor point for a geosphere distance calculations
  • SphinxClient::setGroupBy — Set grouping attribute
  • SphinxClient::setGroupDistinct — Set attribute name for per-group distinct values count calculations
  • SphinxClient::setIDRange — Set a range of accepted document IDs
  • SphinxClient::setIndexWeights — Set per-index weights
  • SphinxClient::setLimits — Set offset and limit of the result set
  • SphinxClient::setMatchMode — Set full-text query matching mode
  • SphinxClient::setMaxQueryTime — Set maximum query time
  • SphinxClient::setOverride — Sets temporary per-document attribute value overrides
  • SphinxClient::setRankingMode — Set ranking mode
  • SphinxClient::setRetries — Set retry count and delay
  • SphinxClient::setSelect — Set select clause
  • SphinxClient::setServer — Set searchd host and port
  • SphinxClient::setSortMode — Set matches sorting mode
  • SphinxClient::status — Queries searchd status
  • SphinxClient::updateAttributes — Update document attributes


Add query to multi-query batch

  • « SphinxClient
  • SphinxClient::buildExcerpts »
  • PHP Manual
  • SphinxClient
  • Add query to multi-query batch

SphinxClient::addQuery

(PECL sphinx >= 0.1.0)

SphinxClient::addQuery — Add query to multi-query batch

Description

public SphinxClient::addQuery ( string $query [, string $index = "*" [, string $comment = "" ]] ) : int

Adds query with the current settings to multi-query batch. This method doesn't affect current settings (sorting, filtering, grouping etc.) in any way.

Parameters

query

Query string.

index

An index name (or names).

comment

Return Values

Returns an index in an array of results that will be returned by SphinxClient::runQueries call or false on error.

See Also

  • SphinxClient::runQueries
  • SphinxClient::query


Build text snippets

  • « SphinxClient::addQuery
  • SphinxClient::buildKeywords »
  • PHP Manual
  • SphinxClient
  • Build text snippets

SphinxClient::buildExcerpts

(PECL sphinx >= 0.1.0)

SphinxClient::buildExcerpts — Build text snippets

Description

public SphinxClient::buildExcerpts ( array $docs , string $index , string $words [, array $opts ] ) : array

Connects to searchd, requests it to generate excerpts (snippets) from the given documents, and returns the results.

Parameters

docs

Array of strings with documents' contents.

index

Index name.

words

Keywords to highlight.

opts

Associative array of additional highlighting options (see below).

Highlighting options
Option | Description
"before_match" | A string to insert before a keyword match. Default is "<b>".
"after_match" | A string to insert after a keyword match. Default is "</b>".
"chunk_separator" | A string to insert between snippet chunks (passages). Default is " ... ".
"limit" | Maximum snippet size, in symbols (codepoints). Integer, default is 256.
"around" | How much words to pick around each matching keywords block. Integer, default is 5.
"exact_phrase" | Whether to highlight exact query phrase matches only instead of individual keywords. Boolean, default is FALSE.
"single_passage" | Whether to extract single best passage only. Boolean, default is FALSE.

Return Values

Returns array of snippets on success or FALSE on failure.


Extract keywords from query

  • « SphinxClient::buildExcerpts
  • SphinxClient::close »
  • PHP Manual
  • SphinxClient
  • Extract keywords from query

SphinxClient::buildKeywords

(PECL sphinx >= 0.1.0)

SphinxClient::buildKeywords — Extract keywords from query

Description

public SphinxClient::buildKeywords ( string $query , string $index , bool $hits ) : array

Extracts keywords from query using tokenizer settings for the given index, optionally with per-keyword occurrence statistics.

Parameters

query

A query to extract keywords from.

index

An index to get tokenizing settings and keyword occurrence statistics from.

hits

A boolean flag to enable/disable keyword statistics generation.

Return Values

Returns an array of associative arrays with per-keyword information.


Closes previously opened persistent connection

  • « SphinxClient::buildKeywords
  • SphinxClient::__construct »
  • PHP Manual
  • SphinxClient
  • Closes previously opened persistent connection

SphinxClient::close

(PECL sphinx >= 1.0.3)

SphinxClient::close — Closes previously opened persistent connection

Description

public SphinxClient::close ( void ) : bool

Closes previously opened persistent connection.

Parameters

This function has no parameters.

Changelog

PECL/sphinx Version | Description
1.0.3 | Added SphinxClient::close(), available only if compiled with libsphinxclient >= 0.9.9.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • SphinxClient::open


Create a new SphinxClient object

  • « SphinxClient::close
  • SphinxClient::escapeString »
  • PHP Manual
  • SphinxClient
  • Create a new SphinxClient object

SphinxClient::__construct

(PECL sphinx >= 0.1.0)

SphinxClient::__construct — Create a new SphinxClient object

Description

public SphinxClient::__construct ( void )

Creates a new SphinxClient object.

Parameters

This function has no parameters.


Escape special characters

  • « SphinxClient::__construct
  • SphinxClient::getLastError »
  • PHP Manual
  • SphinxClient
  • Escape special characters

SphinxClient::escapeString

(PECL sphinx >= 0.1.0)

SphinxClient::escapeString — Escape special characters

Description

public SphinxClient::escapeString ( string $string ) : string

Escapes characters that are treated as special operators by the query language parser.

Parameters

string

String to escape.

Return Values

Returns escaped string.


Get the last error message

  • « SphinxClient::escapeString
  • SphinxClient::getLastWarning »
  • PHP Manual
  • SphinxClient
  • Get the last error message

SphinxClient::getLastError

(PECL sphinx >= 0.1.0)

SphinxClient::getLastError — Get the last error message

Description

public SphinxClient::getLastError ( void ) : string

Returns string with the last error message. If there were no errors during the previous API call, empty string is returned. This method doesn't reset the error message, so you can safely call it several times.

Parameters

This function has no parameters.

Return Values

Returns the last error message or an empty string if there were no errors.

See Also

  • SphinxClient::getLastWarning


Get the last warning

  • « SphinxClient::getLastError
  • SphinxClient::open »
  • PHP Manual
  • SphinxClient
  • Get the last warning

SphinxClient::getLastWarning

(PECL sphinx >= 0.1.0)

SphinxClient::getLastWarning — Get the last warning

Description

public SphinxClient::getLastWarning ( void ) : string

Returns last warning message. If there were no warnings during the previous API call, empty string is returned. This method doesn't reset the warning, so you can safely call it several times.

Parameters

This function has no parameters.

Return Values

Returns the last warning message or an empty string if there were no warnings.

See Also

  • SphinxClient::getLastError


Opens persistent connection to the server

  • « SphinxClient::getLastWarning
  • SphinxClient::query »
  • PHP Manual
  • SphinxClient
  • Opens persistent connection to the server

SphinxClient::open

(PECL sphinx >= 1.0.3)

SphinxClient::open — Opens persistent connection to the server

Description

public SphinxClient::open ( void ) : bool

Opens persistent connection to the server.

Parameters

This function has no parameters.

Changelog

PECL/sphinx Version | Description
1.0.3 | Added SphinxClient::open(), available only if compiled with libsphinxclient >= 0.9.9.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • SphinxClient::close


Execute search query

  • « SphinxClient::open
  • SphinxClient::resetFilters »
  • PHP Manual
  • SphinxClient
  • Execute search query

SphinxClient::query

(PECL sphinx >= 0.1.0)

SphinxClient::query — Execute search query

Description

public SphinxClient::query ( string $query [, string $index = "*" [, string $comment = "" ]] ) : array

Connects to searchd server, runs the given search query with the current settings, obtains and returns the result set.

Parameters

query

Query string.

index

An index name (or names).

comment

Return Values

On success, SphinxClient::query() returns a list of found matches and additional per-query statistics. The result set is a hash utilize other structures instead of hash) with the following keys and values:

Result set structure
Key | Value description
"matches" | An array with found document IDs as keys and their weight and attributes values as values
"total" | Total number of matches found and retrieved (depends on your settings)
"total_found" | Total number of found documents matching the query
"words" | An array with words (case-folded and stemmed) as keys and per-word statistics as values
"error" | Query error message reported by searchd
"warning" | Query warning reported by searchd

See Also

  • SphinxClient::runQueries
  • SphinxClient::addQuery


Clear all filters

  • « SphinxClient::query
  • SphinxClient::resetGroupBy »
  • PHP Manual
  • SphinxClient
  • Clear all filters

SphinxClient::resetFilters

(PECL sphinx >= 0.1.0)

SphinxClient::resetFilters — Clear all filters

Description

public SphinxClient::resetFilters ( void ) : void

Clears all currently set filters. This call is normally required when using multi-queries. You might want to set different filters for different queries in the batch. To do that, you should call SphinxClient::resetFilters() and add new filters using the respective calls.

Return Values

No value is returned.

See Also

  • SphinxClient::resetGroupBy


Clear all group-by settings

  • « SphinxClient::resetFilters
  • SphinxClient::runQueries »
  • PHP Manual
  • SphinxClient
  • Clear all group-by settings

SphinxClient::resetGroupBy

(PECL sphinx >= 0.1.0)

SphinxClient::resetGroupBy — Clear all group-by settings

Description

public SphinxClient::resetGroupBy ( void ) : void

Clears all currently group-by settings, and disables group-by. This call is normally required only when using multi-queries.

Return Values

No value is returned.

See Also

  • SphinxClient::resetGroupBy


Run a batch of search queries

  • « SphinxClient::resetGroupBy
  • SphinxClient::setArrayResult »
  • PHP Manual
  • SphinxClient
  • Run a batch of search queries

SphinxClient::runQueries

(PECL sphinx >= 0.1.0)

SphinxClient::runQueries — Run a batch of search queries

Description

public SphinxClient::runQueries ( void ) : array

Connects to searchd, runs a batch of all queries added using SphinxClient::addQuery, obtains and returns the result sets.

Return Values

Returns FALSE on failure and array of result sets on success.

See Also

  • SphinxClient::addQuery
  • SphinxClient::query


Change the format of result set array

  • « SphinxClient::runQueries
  • SphinxClient::setConnectTimeout »
  • PHP Manual
  • SphinxClient
  • Change the format of result set array

SphinxClient::setArrayResult

(PECL sphinx >= 0.1.0)

SphinxClient::setArrayResult — Change the format of result set array

Description

public SphinxClient::setArrayResult ( bool $array_result = FALSE ) : bool

Controls the format of search results set arrays (whether matches should be returned as an array or a hash).

Parameters

array_result

If array_result is FALSE, matches are returned as a hash with document IDs as keys, and other information (weight, attributes) as values. If array_result is TRUE, matches are returned as a plain array with complete per-match information including document IDs.

Return Values

Always returns TRUE.


Set connection timeout

  • « SphinxClient::setArrayResult
  • SphinxClient::setFieldWeights »
  • PHP Manual
  • SphinxClient
  • Set connection timeout

SphinxClient::setConnectTimeout

(PECL sphinx >= 0.1.0)

SphinxClient::setConnectTimeout — Set connection timeout

Description

public SphinxClient::setConnectTimeout ( float $timeout ) : bool

Sets connection timeout (in seconds) for searchd connection.

Parameters

timeout

Timeout in seconds.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • SphinxClient::setMaxQueryTime


Set field weights

  • « SphinxClient::setConnectTimeout
  • SphinxClient::setFilter »
  • PHP Manual
  • SphinxClient
  • Set field weights

SphinxClient::setFieldWeights

(PECL sphinx >= 0.1.0)

SphinxClient::setFieldWeights — Set field weights

Description

public SphinxClient::setFieldWeights ( array $weights ) : bool

Binds per-field weights by name.

Match ranking can be affected by per-field weights. See » Sphinx documentation for an explanation on how phrase proximity ranking is affected. This call lets you specify non-default weights for full-text fields.

The weights must be positive 32-bit integers, so be careful not to hit 32-bit integer maximum. The final weight is a 32-bit integer too. Default weight value is 1. Unknown field names are silently ignored.

Parameters

weights

Associative array of field names and field weights.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • SphinxClient::setIndexWeights


Add new integer values set filter

  • « SphinxClient::setFieldWeights
  • SphinxClient::setFilterFloatRange »
  • PHP Manual
  • SphinxClient
  • Add new integer values set filter

SphinxClient::setFilter

(PECL sphinx >= 0.1.0)

SphinxClient::setFilter — Add new integer values set filter

Description

public SphinxClient::setFilter ( string $attribute , array $values [, bool $exclude = FALSE ] ) : bool

Adds new integer values set filter to the existing list of filters.

Parameters

attribute

An attribute name.

values

Plain array of integer values.

exclude

If set to TRUE, matching documents are excluded from the result set.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • SphinxClient::setFilterFloatRange
  • SphinxClient::setFilterRange
  • SphinxClient::resetFilters


Add new float range filter

  • « SphinxClient::setFilter
  • SphinxClient::setFilterRange »
  • PHP Manual
  • SphinxClient
  • Add new float range filter

SphinxClient::setFilterFloatRange

(PECL sphinx >= 0.1.0)

SphinxClient::setFilterFloatRange — Add new float range filter

Description

public SphinxClient::setFilterFloatRange ( string $attribute , float $min , float $max [, bool $exclude = FALSE ] ) : bool

Adds new float range filter to the existing list of filters. Only those documents which have attribute value stored in the index between min and max (including values that are exactly equal to min or max) will be matched (or rejected, if exclude is TRUE).

Parameters

attribute

An attribute name.

min

Minimum value.

max

Maximum value.

exclude

If set to TRUE, matching documents are excluded from the result set.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • SphinxClient::setFilterRange
  • SphinxClient::setFilter
  • SphinxClient::resetFilters


Add new integer range filter

  • « SphinxClient::setFilterFloatRange
  • SphinxClient::setGeoAnchor »
  • PHP Manual
  • SphinxClient
  • Add new integer range filter

SphinxClient::setFilterRange

(PECL sphinx >= 0.1.0)

SphinxClient::setFilterRange — Add new integer range filter

Description

public SphinxClient::setFilterRange ( string $attribute , int $min , int $max [, bool $exclude = FALSE ] ) : bool

Adds new integer range filter to the existing list of filters. Only those documents which have attribute value stored in the index between min and max (including values that are exactly equal to min or max) will be matched (or rejected, if exclude is TRUE).

Parameters

attribute

An attribute name.

min

Minimum value.

max

Maximum value.

exclude

If set to TRUE, matching documents are excluded from the result set.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • SphinxClient::setFilterFloatRange
  • SphinxClient::setFilter
  • SphinxClient::resetFilters


Set anchor point for a geosphere distance calculations

  • « SphinxClient::setFilterRange
  • SphinxClient::setGroupBy »
  • PHP Manual
  • SphinxClient
  • Set anchor point for a geosphere distance calculations

SphinxClient::setGeoAnchor

(PECL sphinx >= 0.1.0)

SphinxClient::setGeoAnchor — Set anchor point for a geosphere distance calculations

Description

public SphinxClient::setGeoAnchor ( string $attrlat , string $attrlong , float $latitude , float $longitude ) : bool

Sets anchor point for a geosphere distance (geodistance) calculations and enables them.

Once an anchor point is set, you can use magic "@geodist" attribute name in your filters and/or sorting expressions.

Parameters

attrlat

Name of a latitude attribute.

attrlong

Name of a longitude attribute.

latitude

Anchor latitude in radians.

longitude

Anchor longitude in radians.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • SphinxClient::setFilterFloatRange
  • SphinxClient::setFilterRange
  • SphinxClient::setFilter
  • SphinxClient::resetFilters


Set grouping attribute

  • « SphinxClient::setGeoAnchor
  • SphinxClient::setGroupDistinct »
  • PHP Manual
  • SphinxClient
  • Set grouping attribute

SphinxClient::setGroupBy

(PECL sphinx >= 0.1.0)

SphinxClient::setGroupBy — Set grouping attribute

Description

public SphinxClient::setGroupBy ( string $attribute , int $func [, string $groupsort = "@group desc" ] ) : bool

Sets grouping attribute, function, and group sorting mode, and enables grouping.

Grouping feature is very similar to GROUP BY clause in SQL. Results produced by this function call are going to be the same as produced by the following pseudo code: SELECT ... GROUP BY $func($attribute) ORDER BY $groupsort.

Parameters

attribute

A string containing group-by attribute name.

func

Constant, which sets a function applied to the attribute value in order to compute group-by key.

groupsort

An optional clause controlling how the groups are sorted.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • SphinxClient::resetGroupBy
  • SphinxClient::setSortMode
  • SphinxClient::setGroupDistinct


Set attribute name for per-group distinct values count calculations

  • « SphinxClient::setGroupBy
  • SphinxClient::setIDRange »
  • PHP Manual
  • SphinxClient
  • Set attribute name for per-group distinct values count calculations

SphinxClient::setGroupDistinct

(PECL sphinx >= 0.1.0)

SphinxClient::setGroupDistinct — Set attribute name for per-group distinct values count calculations

Description

public SphinxClient::setGroupDistinct ( string $attribute ) : bool

Sets attribute name for per-group distinct values count calculations. Only available for grouping queries. For each group, all values of attribute will be stored, then the amount of distinct values will be calculated and returned to the client. This feature is similar to COUNT(DISTINCT) clause in SQL.

Parameters

attribute

A string containing group-by attribute name.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • SphinxClient::setSortMode
  • SphinxClient::setGroupBy
  • SphinxClient::resetGroupBy


Set a range of accepted document IDs

  • « SphinxClient::setGroupDistinct
  • SphinxClient::setIndexWeights »
  • PHP Manual
  • SphinxClient
  • Set a range of accepted document IDs

SphinxClient::setIDRange

(PECL sphinx >= 0.1.0)

SphinxClient::setIDRange — Set a range of accepted document IDs

Description

public SphinxClient::setIDRange ( int $min , int $max ) : bool

Sets an accepted range of document IDs. Default range is from 0 to 0, i.e. no limit. Only those records that have document ID between min and max (including IDs exactly equal to min or max) will be matched.

Parameters

min

Minimum ID value.

max

Maximum ID value.

Return Values

Returns TRUE on success or FALSE on failure.


Set per-index weights

  • « SphinxClient::setIDRange
  • SphinxClient::setLimits »
  • PHP Manual
  • SphinxClient
  • Set per-index weights

SphinxClient::setIndexWeights

(PECL sphinx >= 0.1.0)

SphinxClient::setIndexWeights — Set per-index weights

Description

public SphinxClient::setIndexWeights ( array $weights ) : bool

Sets per-index weights and enables weighted summing of match weights across different indexes.

Parameters

weights

An associative array mapping string index names to integer weights. Default is empty array, i.e. weighting summing is disabled.

Return Values

Returns TRUE on success or FALSE on failure.


Set offset and limit of the result set

  • « SphinxClient::setIndexWeights
  • SphinxClient::setMatchMode »
  • PHP Manual
  • SphinxClient
  • Set offset and limit of the result set

SphinxClient::setLimits

(PECL sphinx >= 0.1.0)

SphinxClient::setLimits — Set offset and limit of the result set

Description

public SphinxClient::setLimits ( int $offset , int $limit [, int $max_matches = 0 [, int $cutoff = 0 ]] ) : bool

Sets offset into server-side result set and amount of matches to return to client starting from that offset (limit). Can additionally control maximum server-side result set size for current query (max_matches) and the threshold amount of matches to stop searching at (cutoff).

Parameters

offset

Result set offset.

limit

Amount of matches to return.

max_matches

Controls how much matches searchd will keep in RAM while searching.

cutoff

Used for advanced performance control. It tells searchd to forcibly stop search query once cutoff matches have been found and processed.

Return Values

Returns TRUE on success or FALSE on failure.


Set full-text query matching mode

  • « SphinxClient::setLimits
  • SphinxClient::setMaxQueryTime »
  • PHP Manual
  • SphinxClient
  • Set full-text query matching mode

SphinxClient::setMatchMode

(PECL sphinx >= 0.1.0)

SphinxClient::setMatchMode — Set full-text query matching mode

Description

public SphinxClient::setMatchMode ( int $mode ) : bool

Sets full-text query matching mode. mode is one of the constants listed below.

Match modes
Constant | Description
SPH_MATCH_ALL | Match all query words (default mode).
SPH_MATCH_ANY | Match any of query words.
SPH_MATCH_PHRASE | Match query as a phrase, requiring perfect match.
SPH_MATCH_BOOLEAN | Match query as a boolean expression.
SPH_MATCH_EXTENDED | Match query as an expression in Sphinx internal query language.
SPH_MATCH_FULLSCAN | Enables fullscan.
SPH_MATCH_EXTENDED2 | The same as SPH_MATCH_EXTENDED plus ranking and quorum searching support.

Parameters

mode

Matching mode.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • SphinxClient::setRankingMode
  • SphinxClient::setSortMode


Set maximum query time

  • « SphinxClient::setMatchMode
  • SphinxClient::setOverride »
  • PHP Manual
  • SphinxClient
  • Set maximum query time

SphinxClient::setMaxQueryTime

(PECL sphinx >= 0.1.0)

SphinxClient::setMaxQueryTime — Set maximum query time

Description

public SphinxClient::setMaxQueryTime ( int $qtime ) : bool

Sets maximum search query time.

Parameters

qtime

Maximum query time, in milliseconds. It must be a non-negative integer. Default value is 0, i.e. no limit.

Return Values

Returns TRUE on success or FALSE on failure.


Sets temporary per-document attribute value overrides

  • « SphinxClient::setMaxQueryTime
  • SphinxClient::setRankingMode »
  • PHP Manual
  • SphinxClient
  • Sets temporary per-document attribute value overrides

SphinxClient::setOverride

(PECL sphinx >= 1.0.3)

SphinxClient::setOverride — Sets temporary per-document attribute value overrides

Description

public SphinxClient::setOverride ( string $attribute , int $type , array $values ) : bool

Sets temporary (per-query) per-document attribute value overrides. Override feature lets you "temporary" update attribute values for some documents within a single query, leaving all other queries unaffected. This might be useful for personalized data

Parameters

attribute

An attribute name.

type

An attribute type. Only supports scalar attributes.

values

Array of attribute values that maps document IDs to overridden attribute values.

Changelog

PECL/sphinx Version | Description
1.0.3 | Added SphinxClient::setOverride(), available only if compiled with libsphinxclient >= 0.9.9.

Return Values

Returns TRUE on success or FALSE on failure.


Set ranking mode

  • « SphinxClient::setOverride
  • SphinxClient::setRetries »
  • PHP Manual
  • SphinxClient
  • Set ranking mode

SphinxClient::setRankingMode

(PECL sphinx >= 0.1.0)

SphinxClient::setRankingMode — Set ranking mode

Description

public SphinxClient::setRankingMode ( int $ranker ) : bool

Sets ranking mode. Only available in SPH_MATCH_EXTENDED2 matching mode.

Ranking modes
Constant | Description
SPH_RANK_PROXIMITY_BM25 | Default ranking mode which uses both proximity and BM25 ranking.
SPH_RANK_BM25 | Statistical ranking mode which uses BM25 ranking only (similar to most of other full-text engines). This mode is faster, but may result in worse quality on queries which contain more than 1 keyword.
SPH_RANK_NONE | Disables ranking. This mode is the fastest. It is essentially equivalent to boolean searching, a weight of 1 is assigned to all matches.

Parameters

ranker

Ranking mode.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • SphinxClient::setMatchMode


Set retry count and delay

  • « SphinxClient::setRankingMode
  • SphinxClient::setSelect »
  • PHP Manual
  • SphinxClient
  • Set retry count and delay

SphinxClient::setRetries

(PECL sphinx >= 0.1.0)

SphinxClient::setRetries — Set retry count and delay

Description

public SphinxClient::setRetries ( int $count [, int $delay = 0 ] ) : bool

Sets distributed retry count and delay.

On temporary failures searchd will attempt up to count retries per agent. delay is the delay between the retries, in milliseconds. Retries are disabled by default. Note that this call will not make the API itself retry on temporary failure; it only tells searchd to do so.

Parameters

count

Number of retries.

delay

Delay between retries, in milliseconds.

Return Values

Returns TRUE on success or FALSE on failure.


Set select clause

  • « SphinxClient::setRetries
  • SphinxClient::setServer »
  • PHP Manual
  • SphinxClient
  • Set select clause

SphinxClient::setSelect

(PECL sphinx >= 1.0.1)

SphinxClient::setSelect — Set select clause

Description

public SphinxClient::setSelect ( string $clause ) : bool

Sets the select clause, listing specific attributes to fetch, and expressions to compute and fetch.

Parameters

clause

SQL-like clause.

Changelog

PECL/sphinx Version | Description
1.0.1 | Added SphinxClient::setSelect(), available only if compiled with libsphinxclient >= 0.9.9.

Return Values

Returns TRUE on success or FALSE on failure.


Set searchd host and port

  • « SphinxClient::setSelect
  • SphinxClient::setSortMode »
  • PHP Manual
  • SphinxClient
  • Set searchd host and port

SphinxClient::setServer

(PECL sphinx >= 0.1.0)

SphinxClient::setServer — Set searchd host and port

Description

public SphinxClient::setServer ( string $server , int $port ) : bool

Sets searchd host name and TCP port. All subsequent requests will use the new host and port settings. Default host and port are 'localhost' and 3312, respectively.

Parameters

server

IP or hostname.

port

Port number.

Return Values

Returns TRUE on success or FALSE on failure.


Set matches sorting mode

  • « SphinxClient::setServer
  • SphinxClient::status »
  • PHP Manual
  • SphinxClient
  • Set matches sorting mode

SphinxClient::setSortMode

(PECL sphinx >= 0.1.0)

SphinxClient::setSortMode — Set matches sorting mode

Description

public SphinxClient::setSortMode ( int $mode [, string $sortby ] ) : bool

Sets matches sorting mode. See available modes below.

Sorting modes
Constant | Description
SPH_SORT_RELEVANCE | Sort by relevance in descending order (best matches first).
SPH_SORT_ATTR_DESC | Sort by an attribute in descending order (bigger attribute values first).
SPH_SORT_ATTR_ASC | Sort by an attribute in ascending order (smaller attribute values first).
SPH_SORT_TIME_SEGMENTS | Sort by time segments (last hour/day/week/month) in descending order, and then by relevance in descending order.
SPH_SORT_EXTENDED | Sort by SQL-like combination of columns in ASC/DESC order.
SPH_SORT_EXPR | Sort by an arithmetic expression.

Parameters

mode

Sorting mode.

sortby

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • SphinxClient::setMatchMode
  • SphinxClient::setSortMode


Queries searchd status

  • « SphinxClient::setSortMode
  • SphinxClient::updateAttributes »
  • PHP Manual
  • SphinxClient
  • Queries searchd status

SphinxClient::status

(PECL sphinx >= 1.0.3)

SphinxClient::status — Queries searchd status

Description

public SphinxClient::status ( void ) : array

Queries searchd status, and returns an array of status variable name and value pairs.

Parameters

This function has no parameters.

Changelog

PECL/sphinx Version | Description
1.0.3 | Added SphinxClient::status(), available only if compiled with libsphinxclient >= 0.9.9.

Return Values

Returns an associative array of search server statistics or FALSE on failure.


Update document attributes

  • « SphinxClient::status
  • Swish »
  • PHP Manual
  • SphinxClient
  • Update document attributes

SphinxClient::updateAttributes

(PECL sphinx >= 0.1.0)

SphinxClient::updateAttributes — Update document attributes

Description

public SphinxClient::updateAttributes ( string $index , array $attributes , array $values [, bool $mva = FALSE ] ) : int

Instantly updates given attribute values in given documents.

Parameters

index

Name of the index (or indexes) to be updated.

attributes

Array of attribute names, listing attributes that are updated.

values

Associative array containing document IDs as keys and array of attribute values as values.

Return Values

Returns number of actually updated documents (0 or more) on success, or FALSE on failure.


Swish Indexing

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
  • Swish Functions
    • Swish::__construct — Construct a Swish object
    • Swish::getMetaList — Get the list of meta entries for the index
    • Swish::getPropertyList — Get the list of properties for the index
    • Swish::prepare — Prepare a search query
    • Swish::query — Execute a query and return results object
    • SwishResult::getMetaList — Get a list of meta entries
    • SwishResult::stem — Stems the given word
    • SwishResults::getParsedWords — Get an array of parsed words
    • SwishResults::getRemovedStopwords — Get an array of stopwords removed from the query
    • SwishResults::nextResult — Get the next search result
    • SwishResults::seekResult — Set current seek pointer to the given position
    • SwishSearch::execute — Execute the search and get the results
    • SwishSearch::resetLimit — Reset the search limits
    • SwishSearch::setLimit — Set the search limits
    • SwishSearch::setPhraseDelimiter — Set the phrase delimiter
    • SwishSearch::setSort — Set the sort order
    • SwishSearch::setStructure — Set the structure flag in the search object


Introduction

The swish extension provides the bindings for Swish-e API. Swish-e stands for "Simple Web Indexing System for Humans - Enhanced" and is an open source system for indexing and search. Swish-e itself is licensed under GPL license, but uses a clause that allows applications to link against the library if every copy of the combined work is accompanied by the URL to Swish-e source code. Here it is: » http://swish-e.org.

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.


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

PECL/swish requires PHP 5.1.3 or newer.


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/swish.


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.

Swish::META_TYPE_UNDEF (integer)
Swish::META_TYPE_STRING (integer)
Swish::META_TYPE_ULONG (integer)
Swish::META_TYPE_DATE (integer)
Swish::IN_FILE_BIT (integer)
Swish::IN_TITLE_BIT (integer)
Swish::IN_HEAD_BIT (integer)
Swish::IN_BODY_BIT (integer)
Swish::IN_COMMENTS_BIT (integer)
Swish::IN_HEADER_BIT (integer)
Swish::IN_EMPHASIZED_BIT (integer)
Swish::IN_META_BIT (integer)
Swish::IN_FILE (integer)
Swish::IN_TITLE (integer)
Swish::IN_HEAD (integer)
Swish::IN_BODY (integer)
Swish::IN_COMMENTS (integer)
Swish::IN_HEADER (integer)
Swish::IN_EMPHASIZED (integer)
Swish::IN_META (integer)
Swish::IN_ALL (integer)


  • « Predefined Constants
  • Basic usage »
  • PHP Manual
  • Swish
  • Examples

Examples

Table of Contents

  • Basic usage


Basic usage

Example #1 Basic search query

<?php

try {

    $swish = new Swish("index.swish-e");
    $results = $swish->query("test OR text");

    echo "Found ", $results->hits, " results\n";
    while ($result = $results->nextResult()) {
        var_dump($result);
        break; //break after the first result
    }

} catch (SwishException $e) {
    echo "Error: ", $e->getMessage(), "\n";
}

?>

The above example will output something similar to:

Found 9 results
object(SwishResult)#3 (8) {
  ["swishreccount"]=>
  int(1)
  ["swishrank"]=>
  int(1000)
  ["swishfilenum"]=>
  int(10)
  ["swishdbfile"]=>
  string(13) "index.swish-e"
  ["swishdocpath"]=>
  string(23) "README.SUBMITTING_PATCH"
  ["swishtitle"]=>
  NULL
  ["swishdocsize"]=>
  int(4557)
  ["swishlastmodified"]=>
  int(1072136752)
}


Swish Functions

Table of Contents

  • Swish::__construct — Construct a Swish object
  • Swish::getMetaList — Get the list of meta entries for the index
  • Swish::getPropertyList — Get the list of properties for the index
  • Swish::prepare — Prepare a search query
  • Swish::query — Execute a query and return results object
  • SwishResult::getMetaList — Get a list of meta entries
  • SwishResult::stem — Stems the given word
  • SwishResults::getParsedWords — Get an array of parsed words
  • SwishResults::getRemovedStopwords — Get an array of stopwords removed from the query
  • SwishResults::nextResult — Get the next search result
  • SwishResults::seekResult — Set current seek pointer to the given position
  • SwishSearch::execute — Execute the search and get the results
  • SwishSearch::resetLimit — Reset the search limits
  • SwishSearch::setLimit — Set the search limits
  • SwishSearch::setPhraseDelimiter — Set the phrase delimiter
  • SwishSearch::setSort — Set the sort order
  • SwishSearch::setStructure — Set the structure flag in the search object


Construct a Swish object

  • « Swish Functions
  • Swish::getMetaList »
  • PHP Manual
  • Swish Functions
  • Construct a Swish object

Swish::__construct

(PECL swish >= 0.1.0)

Swish::__construct — Construct a Swish object

Description

Swish::__construct ( string $index_names ) : void
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.

Parameters

index_names

The list of index files separated by spaces.

Return Values

No value is returned.

Errors/Exceptions

Throws SwishException on error.

Examples

Example #1 A Swish::__construct() example

<?php

try {
    $swish = new Swish("index1 index2");
} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

foreach ($swish->indexes as $index) {
    var_dump($index["name"]);
    var_dump($index["headers"]["Total Words"]);
}

?>

The above example will output something similar to:

string(6) "index1"
int(1888)
string(6) "index2"
int(2429)


Get the list of meta entries for the index

  • « Swish::__construct
  • Swish::getPropertyList »
  • PHP Manual
  • Swish Functions
  • Get the list of meta entries for the index

Swish::getMetaList

(PECL swish >= 0.1.0)

Swish::getMetaList — Get the list of meta entries for the index

Description

Swish::getMetaList ( string $index_name ) : array
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.

Parameters

index_name

The name of the index file.

Return Values

Returns an array of meta entries for the given index.

Examples

Example #1 Basic Swish::getMetaList() example

<?php

try {

    $swish = new Swish("index.swish-e");
    var_dump($swish->getMetaList("index.swish-e"));

} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

The above example will output something similar to:

array(1) {
  [0]=>
  array(3) {
    ["Name"]=>
    string(12) "swishdefault"
    ["Type"]=>
    int(0)
    ["ID"]=>
    int(1)
  }
}


Get the list of properties for the index

  • « Swish::getMetaList
  • Swish::prepare »
  • PHP Manual
  • Swish Functions
  • Get the list of properties for the index

Swish::getPropertyList

(PECL swish >= 0.1.0)

Swish::getPropertyList — Get the list of properties for the index

Description

Swish::getPropertyList ( string $index_name ) : array
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.

Parameters

index_name

The name of the index file.

Return Values

Returns an array of properties for the given index.

Examples

Example #1 Basic Swish::getPropertyList() example

<?php

try {

    $swish = new Swish("index.swish-e");
    $properties = $swish->getPropertyList("index.swish-e");
    foreach ($properties as $prop) {
        echo $prop["Name"],"\n";
    }

} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

The above example will output something similar to:

swishreccount
swishrank
swishfilenum
swishdbfile
swishdocpath
swishtitle
swishdocsize
swishlastmodified


Prepare a search query

  • « Swish::getPropertyList
  • Swish::query »
  • PHP Manual
  • Swish Functions
  • Prepare a search query

Swish::prepare

(PECL swish >= 0.1.0)

Swish::prepare — Prepare a search query

Description

Swish::prepare ([ string $query ] ) : object
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.

Prepare and return a search object, which you can later use for unlimited number of queries.

Parameters

query

Optional query string. The query can be also set using SwishSearch::execute() method.

Return Values

Returns SwishSearch object.

Errors/Exceptions

Throws SwishException on error.

Examples

Example #1 Basic Swish::prepare() example

<?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish->prepare("search query");
    $results = $search->execute();
    echo "Found: ", $results->hits, " hits\n";

    $results = $search->execute("new search");

    echo "Found: ", $results->hits, " hits\n";
} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

The above example will output something similar to:

Found: 2 hits
Found: 5 hits


Execute a query and return results object

  • « Swish::prepare
  • SwishResult::getMetaList »
  • PHP Manual
  • Swish Functions
  • Execute a query and return results object

Swish::query

(PECL swish >= 0.1.0)

Swish::query — Execute a query and return results object

Description

Swish::query ( string $query ) : object
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.

A quick method to execute a search with default parameters.

Parameters

query

Query string.

Return Values

Returns SwishResults object.

Errors/Exceptions

Throws SwishException on error.

Examples

Example #1 Basic Swish::query() example

<?php

try {

    $swish = new Swish("index.swish-e");
    $results = $swish->query("test query");

    echo "Found: ", $results->hits, " hits\n";

} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

The above example will output something similar to:

Found: 1 hits


Get a list of meta entries

  • « Swish::query
  • SwishResult::stem »
  • PHP Manual
  • Swish Functions
  • Get a list of meta entries

SwishResult::getMetaList

(PECL swish >= 0.1.0)

SwishResult::getMetaList — Get a list of meta entries

Description

SwishResult::getMetaList ( void ) : array
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.

Return Values

Returns the same array as swish::getmetalist(), but uses the index file from the result handle.


Stems the given word

  • « SwishResult::getMetaList
  • SwishResults::getParsedWords »
  • PHP Manual
  • Swish Functions
  • Stems the given word

SwishResult::stem

(PECL swish >= 0.1.0)

SwishResult::stem — Stems the given word

Description

SwishResult::stem ( string $word ) : array
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.

Stems the word based on the fuzzy mode used during indexing. Each result object is linked with its index, so the results are based on this index.

Parameters

word

The word to stem.

Return Values

Returns array containing the stemmed word variants (usually just one).

Errors/Exceptions

Throws SwishException on error.

Examples

Example #1 Basic SwishResult::stem() example

<?php

try {

    $swish = new Swish("ext/swish/tests/index.swish-e");
    $results = $swish->query("testing OR others");

    if ($result = $results->nextResult()) {
        var_dump($result->stem("testing")); //the results fully depend on the stemmer used in the index
        var_dump($result->stem("others"));
    }

} catch (SwishException $e) {
    echo "Error: ", $e->getMessage(), "\n";
}

?>

The above example will output something similar to:

array(1) {
  [0]=>
  string(4) "test"
}
array(1) {
  [0]=>
  string(5) "other"
}


Get an array of parsed words

  • « SwishResult::stem
  • SwishResults::getRemovedStopwords »
  • PHP Manual
  • Swish Functions
  • Get an array of parsed words

SwishResults::getParsedWords

(PECL swish >= 0.1.0)

SwishResults::getParsedWords — Get an array of parsed words

Description

SwishResults::getParsedWords ( string $index_name ) : array
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.

Parameters

indexi_name

The name of the index used to initialize Swish object.

Return Values

An array of parsed words with stopwords removed. The list of parsed words may be useful for highlighting search terms in the results.

Examples

Example #1 Basic SwishResults::getParsedWords() example

<?php

try {

    $swish = new Swish("index.swish-e");
    $results = $swish->query("'some characters' and numbers");

    var_dump($results->getParsedWords("index.swish-e"));
    var_dump($results->indexes[0]['parsed_words']); //same result in a different way

} catch (SwishException $e) {
    echo "Error: ", $e->getMessage(), "\n";
}

?>

The above example will output something similar to:

array(4) {
  [0]=>
  string(4) "some"
  [1]=>
  string(10) "characters"
  [2]=>
  string(3) "and"
  [3]=>
  string(7) "numbers"
}
array(4) {
  [0]=>
  string(4) "some"
  [1]=>
  string(10) "characters"
  [2]=>
  string(3) "and"
  [3]=>
  string(7) "numbers"
}


Get an array of stopwords removed from the query

  • « SwishResults::getParsedWords
  • SwishResults::nextResult »
  • PHP Manual
  • Swish Functions
  • Get an array of stopwords removed from the query

SwishResults::getRemovedStopwords

(PECL swish >= 0.1.0)

SwishResults::getRemovedStopwords — Get an array of stopwords removed from the query

Description

SwishResults::getRemovedStopwords ( string $index_name ) : array
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.

Parameters

index_name

The name of the index used to initialize Swish object.

Return Values

Returns array of stopwords removed from the query.


Get the next search result

  • « SwishResults::getRemovedStopwords
  • SwishResults::seekResult »
  • PHP Manual
  • Swish Functions
  • Get the next search result

SwishResults::nextResult

(PECL swish >= 0.1.0)

SwishResults::nextResult — Get the next search result

Description

SwishResults::nextResult ( void ) : object
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.

Return Values

Returns the next SwishResult object in the result set or FALSE if there are no more results available.

Examples

Example #1 Basic SwishResults::nextResult() example

<?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish->prepare();

    $results = $search->execute("lost");
    while($result = $results->nextResult()) {
        /* do something with the result object */
    }

} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>


Set current seek pointer to the given position

  • « SwishResults::nextResult
  • SwishSearch::execute »
  • PHP Manual
  • Swish Functions
  • Set current seek pointer to the given position

SwishResults::seekResult

(PECL swish >= 0.1.0)

SwishResults::seekResult — Set current seek pointer to the given position

Description

SwishResults::seekResult ( int $position ) : int
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.

Parameters

position

Zero-based position number. Cannot be less than zero.

Return Values

Returns new position value on success.

Errors/Exceptions

Throws SwishException on error.

Examples

Example #1 Basic SwishResults::seekResult() example

<?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish->prepare();

    $results = $search->execute("lost");

    var_dump($results->seekResult(0)); //this will succeed
    var_dump($results->seekResult(100)); //this will fail

} catch (SwishException $e) {
    echo "Error: ", $e->getMessage(), "\n";
}

?>

The above example will output something similar to:

int(0)
Error: No more results


Execute the search and get the results

  • « SwishResults::seekResult
  • SwishSearch::resetLimit »
  • PHP Manual
  • Swish Functions
  • Execute the search and get the results

SwishSearch::execute

(PECL swish >= 0.1.0)

SwishSearch::execute — Execute the search and get the results

Description

SwishSearch::execute ([ string $query ] ) : object
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.

Searches the index file(s) based on the parameters set in the search object.

Parameters

query

The query string is an optional parameter, it can be also set using Swish::prepare() method. The query string is preserved between executions, so you can set it once, but execute the search multiple times.

Return Values

Returns SwishResults object.

Errors/Exceptions

Throws SwishException on error.

Examples

Example #1 Basic SwishSearch::execute() example

<?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish->prepare();

    $results = $search->execute("query");
    echo "First query found: ", $results->hits, " hits\n";

    $results = $search->execute("new OR query");
    echo "Second query found: ", $results->hits, " hits\n";

} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

The above example will output something similar to:

First query found: 2 hits
Second query found: 12 hits


Reset the search limits

  • « SwishSearch::execute
  • SwishSearch::setLimit »
  • PHP Manual
  • Swish Functions
  • Reset the search limits

SwishSearch::resetLimit

(PECL swish >= 0.1.0)

SwishSearch::resetLimit — Reset the search limits

Description

SwishSearch::resetLimit ( void ) : void
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.

Reset the search limits previous set by SwishSearch::setLimit.

Return Values

No value is returned.

Examples

Example #1 Basic SwishSearch::resetLimit() example

<?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish->prepare();

    $results = $search->execute("time");
    echo "First query found: ", $results->hits, " hits\n";

    $search->setLimit("swishdocsize", "3000", "6000"); //limit by document size, from 3000 to 6000 bytes
    $results = $search->execute("time");
    echo "Second query found: ", $results->hits, " hits\n";

    $search->resetLimit();
    $results = $search->execute("time");
    echo "Third query found: ", $results->hits, " hits\n";

} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

The above example will output something similar to:

First query found: 5 hits
Second query found: 2 hits
Third query found: 5 hits


Set the search limits

  • « SwishSearch::resetLimit
  • SwishSearch::setPhraseDelimiter »
  • PHP Manual
  • Swish Functions
  • Set the search limits

SwishSearch::setLimit

(PECL swish >= 0.1.0)

SwishSearch::setLimit — Set the search limits

Description

SwishSearch::setLimit ( string $property , string $low , string $high ) : void
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.

Parameters

property

Search result property name.

low

The lowest value of the property.

high

The highest value of the property.

Return Values

No value is returned.

Errors/Exceptions

Throws SwishException on error.

Examples

Example #1 Basic SwishSearch::setLimit() example

<?php
try {

    $swish = new Swish("index.swish-e");
    $search = $swish->prepare();

    $results = $search->execute("time");
    echo "First query found: ", $results->hits, " hits\n";

    $i = 0;
    while($result = $results->nextResult()) {
        echo "Hit #", ++$i, " - ", $result->swishdocsize, " bytes\n";
    }

    $search->setLimit("swishdocsize", "3000", "6000"); //limit by document size, from 3000 to 6000 bytes
    $results = $search->execute("time");
    echo "Second query found: ", $results->hits, " hits\n";

    $i = 0;
    while($result = $results->nextResult()) {
        echo "Hit #", ++$i, " - ", $result->swishdocsize, " bytes\n";
    }

} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

The above example will output something similar to:

First query found: 5 hits
Hit #1 - 4261 bytes
Hit #2 - 37937 bytes
Hit #3 - 7126 bytes
Hit #4 - 15427 bytes
Hit #5 - 4768 bytes
Second query found: 2 hits
Hit #1 - 4261 bytes
Hit #2 - 4768 bytes


Set the phrase delimiter

  • « SwishSearch::setLimit
  • SwishSearch::setSort »
  • PHP Manual
  • Swish Functions
  • Set the phrase delimiter

SwishSearch::setPhraseDelimiter

(PECL swish >= 0.1.0)

SwishSearch::setPhraseDelimiter — Set the phrase delimiter

Description

SwishSearch::setPhraseDelimiter ( string $delimiter ) : void
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.

Parameters

delimiter

Phrase delimiter character. The default delimiter is double-quotes.

Return Values

No value is returned.

Examples

Example #1 Basic SwishSearch::setPhraseDelimiter() example

<?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish->prepare();

    $results = $search->execute('"every time"'); //looking for "every time"
    echo "First query found: ", $results->hits, " hits\n";

    $search->setPhraseDelimiter("'");
    $results = $search->execute("'every time'"); //the same query, but using different delimiter
    echo "Second query found: ", $results->hits, " hits\n";

    $search->setPhraseDelimiter('"');
    $results = $search->execute("'every time'"); //looking for "every" and "time"
    echo "Third query found: ", $results->hits, " hits\n";

    //let's look at parsed words
    var_dump($results->getParsedWords("index.swish-e"));

} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

The above example will output something similar to:

First query found: 1 hits
Second query found: 1 hits
Third query found: 2 hits
array(2) {
  [0]=>
  string(5) "every"
  [1]=>
  string(4) "time"
}


Set the sort order

  • « SwishSearch::setPhraseDelimiter
  • SwishSearch::setStructure »
  • PHP Manual
  • Swish Functions
  • Set the sort order

SwishSearch::setSort

(PECL swish >= 0.1.0)

SwishSearch::setSort — Set the sort order

Description

SwishSearch::setSort ( string $sort ) : void
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.

Parameters

sort

Sort order of the results is a string containing name of a result property combined with sort direction ("asc" or "desc"). Examples: "swishrank desc", "swishdocpath asc", "swishtitle asc", "swishdocsize desc", "swishlastmodified desc" etc.

Return Values

No value is returned.

Examples

Example #1 Basic SwishSearch::setSort() example

<?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish->prepare();

    $results = $search->execute("time");
    echo "First query found: ", $results->hits, " hits\n";

    $i = 0;
    while($result = $results->nextResult()) {
        echo "Hit #", ++$i, " - ", $result->swishdocsize, " bytes\n";
    }

    $search->setSort("swishdocsize desc"); //sort by document size
    $results = $search->execute("time");
    echo "Second query found: ", $results->hits, " hits\n";

    $i = 0;
    while($result = $results->nextResult()) {
        echo "Hit #", ++$i, " - ", $result->swishdocsize, " bytes\n";
    }

} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

The above example will output something similar to:

First query found: 5 hits
Hit #1 - 4261 bytes
Hit #2 - 37937 bytes
Hit #3 - 7126 bytes
Hit #4 - 15427 bytes
Hit #5 - 4768 bytes
Second query found: 5 hits
Hit #1 - 37937 bytes
Hit #2 - 15427 bytes
Hit #3 - 7126 bytes
Hit #4 - 4768 bytes
Hit #5 - 4261 bytes


Set the structure flag in the search object

  • « SwishSearch::setSort
  • Server Specific Extensions »
  • PHP Manual
  • Swish Functions
  • Set the structure flag in the search object

SwishSearch::setStructure

(PECL swish >= 0.1.0)

SwishSearch::setStructure — Set the structure flag in the search object

Description

SwishSearch::setStructure ( int $structure ) : void
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.

Parameters

structure

The structure flag a bitmask is used to limit search to certain parts of HTML documents (like title, meta, body etc.). Its possible values are listed below. To combine several values use bitwise OR operator, see example below.

  • Swish::IN_FILE

  • Swish::IN_TITLE

  • Swish::IN_HEAD

  • Swish::IN_BODY

  • Swish::IN_COMMENTS

  • Swish::IN_HEADER

  • Swish::IN_EMPHASIZED

  • Swish::IN_META

Return Values

No value is returned.

Examples

Example #1 Basic SwishSearch::setStructure() example

<?php

try {

    $swish = new Swish("index.swish-e");
    $search = $swish->prepare();

    $results = $search->execute("time");
    echo "First query found: ", $results->hits, " hits\n";

    $search->setStructure(Swish::IN_TITLE|Swish::IN_HEAD); //search in title and head
    $results = $search->execute("time");
    echo "Second query found: ", $results->hits, " hits\n";

    $search->setStructure(Swish::IN_ALL); //search in whole document, the default value
    $results = $search->execute("time");
    echo "Third query found: ", $results->hits, " hits\n";

} catch (SwishException $e) {
    echo $e->getMessage(), "\n";
}

?>

The above example will output something similar to:

First query found: 5 hits
Second query found: 0 hits
Third query found: 5 hits


Server Specific Extensions

  • Apache
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Apache Functions
  • FastCGI Process Manager
    • Introduction
    • Installing/Configuring
    • FPM Functions
  • IIS — IIS Administration
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • IIS Functions
  • NSAPI
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • NSAPI Functions


Apache

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Apache Functions
    • apache_child_terminate — Terminate apache process after this request
    • apache_get_modules — Get a list of loaded Apache modules
    • apache_get_version — Fetch Apache version
    • apache_getenv — Get an Apache subprocess_env variable
    • apache_lookup_uri — Perform a partial request for the specified URI and return all info about it
    • apache_note — Get and set apache request notes
    • apache_request_headers — Fetch all HTTP request headers
    • apache_reset_timeout — Reset the Apache write timer
    • apache_response_headers — Fetch all HTTP response headers
    • apache_setenv — Set an Apache subprocess_env variable
    • getallheaders — Fetch all HTTP request headers
    • virtual — Perform an Apache sub-request


Introduction

These functions are only available when running PHP as an Apache module.


  • « Requirements
  • Runtime Configuration »
  • PHP Manual
  • Installing/Configuring
  • Installation

Installation

For PHP installation on Apache see the installation chapter.


Runtime Configuration

The behaviour of the Apache PHP module is affected by settings in php.ini. Configuration settings from php.ini may be overridden by php_flag settings in the server configuration file or local .htaccess files.

Example #1 Turning off PHP parsing for a directory using .htaccess

php_flag engine off

Apache configuration options
Name | Default | Changeable | Changelog
engine | "1" | PHP_INI_ALL |
child_terminate | "0" | PHP_INI_ALL |
last_modified | "0" | PHP_INI_ALL |
xbithack | "0" | PHP_INI_ALL |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

engine boolean

Turns PHP parsing on or off. This directive is really only useful in the Apache module version of PHP. It is used by sites that would like to turn PHP parsing on and off on a per-directory or per-virtual server basis. By putting engine off in the appropriate places in the httpd.conf file, PHP can be enabled or disabled.

child_terminate boolean

Specify whether PHP scripts may request child process termination on end of request, see also apache_child_terminate().

last_modified boolean

Send PHP scripts modification date as Last-Modified: header for this request.

xbithack boolean

Parse files with executable bit set as PHP regardless of their file ending.


  • « Resource Types
  • Apache Functions »
  • PHP Manual
  • Apache
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


Apache Functions

Table of Contents

  • apache_child_terminate — Terminate apache process after this request
  • apache_get_modules — Get a list of loaded Apache modules
  • apache_get_version — Fetch Apache version
  • apache_getenv — Get an Apache subprocess_env variable
  • apache_lookup_uri — Perform a partial request for the specified URI and return all info about it
  • apache_note — Get and set apache request notes
  • apache_request_headers — Fetch all HTTP request headers
  • apache_reset_timeout — Reset the Apache write timer
  • apache_response_headers — Fetch all HTTP response headers
  • apache_setenv — Set an Apache subprocess_env variable
  • getallheaders — Fetch all HTTP request headers
  • virtual — Perform an Apache sub-request


Terminate apache process after this request

  • « Apache Functions
  • apache_get_modules »
  • PHP Manual
  • Apache Functions
  • Terminate apache process after this request

apache_child_terminate

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

apache_child_terminate — Terminate apache process after this request

Description

apache_child_terminate ( void ) : bool

apache_child_terminate() will register the Apache process executing the current PHP request for termination once execution of PHP code is completed. It may be used to terminate a process after a script with high memory consumption has been run as memory will usually only be freed internally but not given back to the operating system.

Return Values

Returns TRUE if PHP is running as an Apache 1 module, the Apache version is non-multithreaded, and the child_terminate PHP directive is enabled (disabled by default). If these conditions are not met, FALSE is returned and an error of level E_WARNING is generated.

Changelog

Version | Description
5.4.0 | This function became available under FastCGI. Previously, it was supported only when PHP was installed as an Apache module.

Notes

Note: This function is not implemented on Windows platforms.

See Also

  • exit() - Output a message and terminate the current script


Get a list of loaded Apache modules

  • « apache_child_terminate
  • apache_get_version »
  • PHP Manual
  • Apache Functions
  • Get a list of loaded Apache modules

apache_get_modules

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

apache_get_modules — Get a list of loaded Apache modules

Description

apache_get_modules ( void ) : array

Get a list of loaded Apache modules.

Return Values

An array of loaded Apache modules.

Examples

Example #1 apache_get_modules() example

<?php
print_r(apache_get_modules());
?>

The above example will output something similar to:

Array
(
    [0] => core
    [1] => http_core
    [2] => mod_so
    [3] => sapi_apache2
    [4] => mod_mime
    [5] => mod_rewrite
)


Fetch Apache version

  • « apache_get_modules
  • apache_getenv »
  • PHP Manual
  • Apache Functions
  • Fetch Apache version

apache_get_version

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

apache_get_version — Fetch Apache version

Description

apache_get_version ( void ) : string

Fetch the Apache version.

Return Values

Returns the Apache version on success or FALSE on failure.

Examples

Example #1 apache_get_version() example

<?php
$version = apache_get_version();
echo "$version\n";
?>

The above example will output something similar to:

Apache/1.3.29 (Unix) PHP/4.3.4

See Also

  • phpinfo() - Outputs information about PHP's configuration


Get an Apache subprocess_env variable

  • « apache_get_version
  • apache_lookup_uri »
  • PHP Manual
  • Apache Functions
  • Get an Apache subprocess_env variable

apache_getenv

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

apache_getenv — Get an Apache subprocess_env variable

Description

apache_getenv ( string $variable [, bool $walk_to_top = FALSE ] ) : string

Retrieve an Apache environment variable specified by variable.

This function requires Apache 2 otherwise it's undefined.

Parameters

variable

The Apache environment variable

walk_to_top

Whether to get the top-level variable available to all Apache layers.

Return Values

The value of the Apache environment variable on success, or FALSE on failure

Examples

Example #1 apache_getenv() example

The example above shows how to retrieve the value of the Apache environment variable SERVER_ADDR.

<?php
$ret = apache_getenv("SERVER_ADDR");
echo $ret;
?>

The above example will output something similar to:

42.24.42.240

See Also

  • apache_setenv() - Set an Apache subprocess_env variable
  • getenv() - Gets the value of an environment variable
  • Superglobals


Perform a partial request for the specified URI and return all info about it

  • « apache_getenv
  • apache_note »
  • PHP Manual
  • Apache Functions
  • Perform a partial request for the specified URI and return all info about it

apache_lookup_uri

(PHP 4, PHP 5, PHP 7)

apache_lookup_uri — Perform a partial request for the specified URI and return all info about it

Description

apache_lookup_uri ( string $filename ) : object

This performs a partial request for a URI. It goes just far enough to obtain all the important information about the given resource.

This function is supported when PHP is installed as an Apache module or by the NSAPI server module in Netscape/iPlanet/SunONE webservers.

Parameters

filename

The filename (URI) that's being requested.

Return Values

An object of related URI information. The properties of this object are:

  • status
  • the_request
  • status_line
  • method
  • content_type
  • handler
  • uri
  • filename
  • path_info
  • args
  • boundary
  • no_cache
  • no_local_copy
  • allowed
  • send_bodyct
  • bytes_sent
  • byterange
  • clength
  • unparsed_uri
  • mtime
  • request_time

Examples

Example #1 apache_lookup_uri() example

<?php
$info = apache_lookup_uri('index.php?var=value');
print_r($info);

if (file_exists($info->filename)) {
    echo 'file exists!';
}
?>

The above example will output something similar to:

stdClass Object
(
    [status] => 200
    [the_request] => GET /dir/file.php HTTP/1.1
    [method] => GET
    [mtime] => 0
    [clength] => 0
    [chunked] => 0
    [content_type] => application/x-httpd-php
    [no_cache] => 0
    [no_local_copy] => 1
    [unparsed_uri] => /dir/index.php?var=value
    [uri] => /dir/index.php
    [filename] => /home/htdocs/dir/index.php
    [args] => var=value
    [allowed] => 0
    [sent_bodyct] => 0
    [bytes_sent] => 0
    [request_time] => 1074282764
)
file exists!


Get and set apache request notes

  • « apache_lookup_uri
  • apache_request_headers »
  • PHP Manual
  • Apache Functions
  • Get and set apache request notes

apache_note

(PHP 4, PHP 5, PHP 7)

apache_note — Get and set apache request notes

Description

apache_note ( string $note_name ) : string
apache_note ( string $note_name , string $note_value ) : string

This function is a wrapper for Apache's table_get and table_set. It edits the table of notes that exists during a request. The table's purpose is to allow Apache modules to communicate.

The main use for apache_note() is to pass information from one module to another within the same request.

Parameters

note_name

The name of the note.

note_value

The value of the note.

Return Values

If called with one argument, it returns the current value of note note_name. If called with two arguments, it sets the value of note note_name to note_value and returns the previous value of note note_name. If the note cannot be retrieved, FALSE is returned.

Examples

Example #1 Passing information between PHP and Perl

<?php

apache_note('name', 'Fredrik Ekengren');

// Call perl script
virtual("/perl/some_script.pl");

$result = apache_note("resultdata");
?>
# Get Apache request object
my $r = Apache->request()->main();

# Get passed data
my $name = $r->notes('name');

# some processing

# Pass result back to PHP
$r->notes('resultdata', $result);

Example #2 Logging values in access.log

<?php

apache_note('sessionID', session_id());

?>
# "%{sessionID}n" can be used in the LogFormat directive

See Also

  • virtual() - Perform an Apache sub-request


Fetch all HTTP request headers

  • « apache_note
  • apache_reset_timeout »
  • PHP Manual
  • Apache Functions
  • Fetch all HTTP request headers

apache_request_headers

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

apache_request_headers — Fetch all HTTP request headers

Description

apache_request_headers ( void ) : array

Fetches all HTTP request headers from the current request.

Return Values

An associative array of all the HTTP headers in the current request, or FALSE on failure.

Changelog

Version | Description
7.3.0 | This function became available in the FPM SAPI.
5.5.7 | This function became available in the CLI server.
5.4.0 | This function became available under FastCGI. Previously, it was supported when PHP was installed as an Apache module or by the NSAPI server module in Netscape/iPlanet/SunONE webservers.

Examples

Example #1 apache_request_headers() example

<?php
$headers = apache_request_headers();

foreach ($headers as $header => $value) {
    echo "$header: $value <br />\n";
}
?>

The above example will output something similar to:

Accept: */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0
Host: www.example.com
Connection: Keep-Alive

Notes

Note:

You can also get at the value of the common CGI variables by reading them from the environment, which works whether or not you are using PHP as an Apache module. Use phpinfo() to see a list of all of the available environment variables.

See Also

  • apache_response_headers() - Fetch all HTTP response headers


Reset the Apache write timer

  • « apache_request_headers
  • apache_response_headers »
  • PHP Manual
  • Apache Functions
  • Reset the Apache write timer

apache_reset_timeout

(PHP 5 >= 5.1.0, PHP 7)

apache_reset_timeout — Reset the Apache write timer

Description

apache_reset_timeout ( void ) : bool

apache_reset_timeout() resets the Apache write timer, which defaults to 300 seconds. With set_time_limit(0); ignore_user_abort(true) and periodic apache_reset_timeout() calls, Apache can theoretically run forever.

This function requires Apache 1.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note: This function is disabled when PHP is running in safe mode.

See Also

  • set_time_limit() - Limits the maximum execution time
  • ignore_user_abort() - Set whether a client disconnect should abort script execution


Fetch all HTTP response headers

  • « apache_reset_timeout
  • apache_setenv »
  • PHP Manual
  • Apache Functions
  • Fetch all HTTP response headers

apache_response_headers

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

apache_response_headers — Fetch all HTTP response headers

Description

apache_response_headers ( void ) : array

Fetch all HTTP response headers.

Return Values

An array of all Apache response headers on success or FALSE on failure.

Changelog

Version | Description
5.5.7 | This function became available in the CLI server.
5.4.0 | This function became available under FastCGI. Previously, it was supported when PHP was installed as an Apache module or by the NSAPI server module in Netscape/iPlanet/SunONE webservers.

Examples

Example #1 apache_response_headers() example

<?php
print_r(apache_response_headers());
?>

The above example will output something similar to:

Array
(
    [Accept-Ranges] => bytes
    [X-Powered-By] => PHP/4.3.8
)

See Also

  • apache_request_headers() - Fetch all HTTP request headers
  • headers_sent() - Checks if or where headers have been sent
  • headers_list() - Returns a list of response headers sent (or ready to send)


Set an Apache subprocess_env variable

  • « apache_response_headers
  • getallheaders »
  • PHP Manual
  • Apache Functions
  • Set an Apache subprocess_env variable

apache_setenv

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

apache_setenv — Set an Apache subprocess_env variable

Description

apache_setenv ( string $variable , string $value [, bool $walk_to_top = FALSE ] ) : bool

apache_setenv() sets the value of the Apache environment variable specified by variable.

Note:

When setting an Apache environment variable, the corresponding $_SERVER variable is not changed.

Parameters

variable

The environment variable that's being set.

value

The new variable value.

walk_to_top

Whether to set the top-level variable available to all Apache layers.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Setting an Apache environment variable using apache_setenv()

<?php
apache_setenv("EXAMPLE_VAR", "Example Value");
?>

Notes

Note:

apache_setenv() can be paired up with apache_getenv() across separate pages or for setting variables to pass to Server Side Includes (.shtml) that have been included in PHP scripts.

See Also

  • apache_getenv() - Get an Apache subprocess_env variable


Fetch all HTTP request headers

  • « apache_setenv
  • virtual »
  • PHP Manual
  • Apache Functions
  • Fetch all HTTP request headers

getallheaders

(PHP 4, PHP 5, PHP 7)

getallheaders — Fetch all HTTP request headers

Description

getallheaders ( void ) : array

Fetches all HTTP headers from the current request.

This function is an alias for apache_request_headers(). Please read the apache_request_headers() documentation for more information on how this function works.

Return Values

An associative array of all the HTTP headers in the current request, or FALSE on failure.

Changelog

Version | Description
7.3.0 | This function became available in the FPM SAPI.
5.5.7 | This function became available in the CLI server.
5.4.0 | This function became available under FastCGI. Previously, it was supported when PHP was installed as an Apache module or by the NSAPI server module in Netscape/iPlanet/SunONE webservers.

Examples

Example #1 getallheaders() example

<?php

foreach (getallheaders() as $name => $value) {
    echo "$name: $value\n";
}

?>

See Also

  • apache_response_headers() - Fetch all HTTP response headers


Perform an Apache sub-request

  • « getallheaders
  • FastCGI Process Manager »
  • PHP Manual
  • Apache Functions
  • Perform an Apache sub-request

virtual

(PHP 4, PHP 5, PHP 7)

virtual — Perform an Apache sub-request

Description

virtual ( string $filename ) : bool

virtual() is an Apache-specific function which is similar to <!--#include virtual...--> in mod_include. It performs an Apache sub-request. It is useful for including CGI scripts or .shtml files, or anything else that you would parse through Apache. Note that for a CGI script, the script must generate valid CGI headers. At the minimum that means it must generate a Content-Type header.

To run the sub-request, all buffers are terminated and flushed to the browser, pending headers are sent too.

This function is supported when PHP is installed as an Apache module or by the NSAPI server module in Netscape/iPlanet/SunONE webservers.

Parameters

filename

The file that the virtual command will be performed on.

Return Values

Performs the virtual command on success, or returns FALSE on failure.

Examples

See apache_note() for an example.

Notes

Warning

The query string can be passed to the included file but $_GET is copied from the parent script and only $_SERVER['QUERY_STRING'] is filled with the passed query string. The query string may only be passed when using Apache 2. The requested file will not be listed in the Apache access log.

Note:

Environment variables set in the requested file are not visible to the calling script.

Note:

This function may be used on PHP files. However, it is typically better to use include or require for PHP files.

See Also

  • apache_note() - Get and set apache request notes


FastCGI Process Manager

  • Introduction
  • Installing/Configuring
  • FPM Functions
    • fastcgi_finish_request — Flushes all response data to the client


Introduction

FPM (FastCGI Process Manager) is an alternative PHP FastCGI implementation with some additional features (mostly) useful for heavy-loaded sites.

This SAPI is bundled with PHP 5.3.3 and later.


Installing/Configuring

Information on installing and configuring FPM can be found in the installation and configuration section of the PHP manual.


  • « Installing/Configuring
  • fastcgi_finish_request »
  • PHP Manual
  • FastCGI Process Manager
  • FPM Functions

FPM Functions

Table of Contents

  • fastcgi_finish_request — Flushes all response data to the client


Flushes all response data to the client

  • « FPM Functions
  • IIS »
  • PHP Manual
  • FPM Functions
  • Flushes all response data to the client

fastcgi_finish_request

(PHP 5 >= 5.3.3, PHP 7)

fastcgi_finish_request — Flushes all response data to the client

Description

fastcgi_finish_request ( void ) : bool

This function flushes all response data to the client and finishes the request. This allows for time consuming tasks to be performed without leaving the connection to the client open.

Return Values

Returns TRUE on success or FALSE on failure.


IIS Administration

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • IIS Functions
    • iis_add_server — Creates a new virtual web server
    • iis_get_dir_security — Gets Directory Security
    • iis_get_script_map — Gets script mapping on a virtual directory for a specific extension
    • iis_get_server_by_comment — Return the instance number associated with the Comment
    • iis_get_server_by_path — Return the instance number associated with the Path
    • iis_get_server_rights — Gets server rights
    • iis_get_service_state — Returns the state for the service defined by ServiceId
    • iis_remove_server — Removes the virtual web server indicated by ServerInstance
    • iis_set_app_settings — Creates application scope for a virtual directory
    • iis_set_dir_security — Sets Directory Security
    • iis_set_script_map — Sets script mapping on a virtual directory
    • iis_set_server_rights — Sets server rights
    • iis_start_server — Starts the virtual web server
    • iis_start_service — Starts the service defined by ServiceId
    • iis_stop_server — Stops the virtual web server
    • iis_stop_service — Stops the service defined by ServiceId


Introduction

This extension is available for Win32 only. It provides functions to administrate Microsoft Internet Information Server (IIS). The extension includes function to create web sites and virtual directories as well as configuring security and script mapping.


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/iisfunc.


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.

IIS_READ (integer)
IIS_WRITE (integer)
IIS_EXECUTE (integer)
IIS_SCRIPT (integer)
IIS_ANONYMOUS (integer)
IIS_BASIC (integer)
IIS_NTLM (integer)
IIS_STARTING (integer)
IIS_STOPPED (integer)
IIS_PAUSED (integer)
IIS_RUNNING (integer)


IIS Functions

Table of Contents

  • iis_add_server — Creates a new virtual web server
  • iis_get_dir_security — Gets Directory Security
  • iis_get_script_map — Gets script mapping on a virtual directory for a specific extension
  • iis_get_server_by_comment — Return the instance number associated with the Comment
  • iis_get_server_by_path — Return the instance number associated with the Path
  • iis_get_server_rights — Gets server rights
  • iis_get_service_state — Returns the state for the service defined by ServiceId
  • iis_remove_server — Removes the virtual web server indicated by ServerInstance
  • iis_set_app_settings — Creates application scope for a virtual directory
  • iis_set_dir_security — Sets Directory Security
  • iis_set_script_map — Sets script mapping on a virtual directory
  • iis_set_server_rights — Sets server rights
  • iis_start_server — Starts the virtual web server
  • iis_start_service — Starts the service defined by ServiceId
  • iis_stop_server — Stops the virtual web server
  • iis_stop_service — Stops the service defined by ServiceId


Creates a new virtual web server

  • « IIS Functions
  • iis_get_dir_security »
  • PHP Manual
  • IIS Functions
  • Creates a new virtual web server

iis_add_server

(PECL iisfunc SVN)

iis_add_server — Creates a new virtual web server

Description

iis_add_server ( string $path , string $comment , string $server_ip , int $port , string $host_name , int $rights , int $start_server ) : int
Warning

This function is currently not documented; only its argument list is available.


Gets Directory Security

  • « iis_add_server
  • iis_get_script_map »
  • PHP Manual
  • IIS Functions
  • Gets Directory Security

iis_get_dir_security

(PECL iisfunc SVN)

iis_get_dir_security — Gets Directory Security

Description

iis_get_dir_security ( int $server_instance , string $virtual_path ) : int
Warning

This function is currently not documented; only its argument list is available.


Gets script mapping on a virtual directory for a specific extension

  • « iis_get_dir_security
  • iis_get_server_by_comment »
  • PHP Manual
  • IIS Functions
  • Gets script mapping on a virtual directory for a specific extension

iis_get_script_map

(PECL iisfunc SVN)

iis_get_script_map — Gets script mapping on a virtual directory for a specific extension

Description

iis_get_script_map ( int $server_instance , string $virtual_path , string $script_extension ) : string
Warning

This function is currently not documented; only its argument list is available.


Return the instance number associated with the Comment

  • « iis_get_script_map
  • iis_get_server_by_path »
  • PHP Manual
  • IIS Functions
  • Return the instance number associated with the Comment

iis_get_server_by_comment

(PECL iisfunc SVN)

iis_get_server_by_comment — Return the instance number associated with the Comment

Description

iis_get_server_by_comment ( string $comment ) : int
Warning

This function is currently not documented; only its argument list is available.


Return the instance number associated with the Path

  • « iis_get_server_by_comment
  • iis_get_server_rights »
  • PHP Manual
  • IIS Functions
  • Return the instance number associated with the Path

iis_get_server_by_path

(PECL iisfunc SVN)

iis_get_server_by_path — Return the instance number associated with the Path

Description

iis_get_server_by_path ( string $path ) : int

Each virtual server in IIS is associated with an instance number. iis_get_server_by_path() finds the instance number from the actual path to the root directory.

Parameters

path

The path to the root directory

Return Values

Returns the server instance number.


Gets server rights

  • « iis_get_server_by_path
  • iis_get_service_state »
  • PHP Manual
  • IIS Functions
  • Gets server rights

iis_get_server_rights

(PECL iisfunc SVN)

iis_get_server_rights — Gets server rights

Description

iis_get_server_rights ( int $server_instance , string $virtual_path ) : int
Warning

This function is currently not documented; only its argument list is available.


Returns the state for the service defined by ServiceId

  • « iis_get_server_rights
  • iis_remove_server »
  • PHP Manual
  • IIS Functions
  • Returns the state for the service defined by ServiceId

iis_get_service_state

(PECL iisfunc SVN)

iis_get_service_state — Returns the state for the service defined by ServiceId

Description

iis_get_service_state ( string $service_id ) : int
Warning

This function is currently not documented; only its argument list is available.


Removes the virtual web server indicated by ServerInstance

  • « iis_get_service_state
  • iis_set_app_settings »
  • PHP Manual
  • IIS Functions
  • Removes the virtual web server indicated by ServerInstance

iis_remove_server

(PECL iisfunc SVN)

iis_remove_server — Removes the virtual web server indicated by ServerInstance

Description

iis_remove_server ( int $server_instance ) : int
Warning

This function is currently not documented; only its argument list is available.


Creates application scope for a virtual directory

  • « iis_remove_server
  • iis_set_dir_security »
  • PHP Manual
  • IIS Functions
  • Creates application scope for a virtual directory

iis_set_app_settings

(PECL iisfunc SVN)

iis_set_app_settings — Creates application scope for a virtual directory

Description

iis_set_app_settings ( int $server_instance , string $virtual_path , string $application_scope ) : int
Warning

This function is currently not documented; only its argument list is available.


Sets Directory Security

  • « iis_set_app_settings
  • iis_set_script_map »
  • PHP Manual
  • IIS Functions
  • Sets Directory Security

iis_set_dir_security

(PECL iisfunc SVN)

iis_set_dir_security — Sets Directory Security

Description

iis_set_dir_security ( int $server_instance , string $virtual_path , int $directory_flags ) : int
Warning

This function is currently not documented; only its argument list is available.


Sets script mapping on a virtual directory

  • « iis_set_dir_security
  • iis_set_server_rights »
  • PHP Manual
  • IIS Functions
  • Sets script mapping on a virtual directory

iis_set_script_map

(PECL iisfunc SVN)

iis_set_script_map — Sets script mapping on a virtual directory

Description

iis_set_script_map ( int $server_instance , string $virtual_path , string $script_extension , string $engine_path , int $allow_scripting ) : int
Warning

This function is currently not documented; only its argument list is available.


Sets server rights

  • « iis_set_script_map
  • iis_start_server »
  • PHP Manual
  • IIS Functions
  • Sets server rights

iis_set_server_rights

(PECL iisfunc SVN)

iis_set_server_rights — Sets server rights

Description

iis_set_server_rights ( int $server_instance , string $virtual_path , int $directory_flags ) : int
Warning

This function is currently not documented; only its argument list is available.


Starts the virtual web server

  • « iis_set_server_rights
  • iis_start_service »
  • PHP Manual
  • IIS Functions
  • Starts the virtual web server

iis_start_server

(PECL iisfunc SVN)

iis_start_server — Starts the virtual web server

Description

iis_start_server ( int $server_instance ) : int
Warning

This function is currently not documented; only its argument list is available.


Starts the service defined by ServiceId

  • « iis_start_server
  • iis_stop_server »
  • PHP Manual
  • IIS Functions
  • Starts the service defined by ServiceId

iis_start_service

(PECL iisfunc SVN)

iis_start_service — Starts the service defined by ServiceId

Description

iis_start_service ( string $service_id ) : int
Warning

This function is currently not documented; only its argument list is available.


Stops the virtual web server

  • « iis_start_service
  • iis_stop_service »
  • PHP Manual
  • IIS Functions
  • Stops the virtual web server

iis_stop_server

(PECL iisfunc SVN)

iis_stop_server — Stops the virtual web server

Description

iis_stop_server ( int $server_instance ) : int
Warning

This function is currently not documented; only its argument list is available.


Stops the service defined by ServiceId

  • « iis_stop_server
  • NSAPI »
  • PHP Manual
  • IIS Functions
  • Stops the service defined by ServiceId

iis_stop_service

(PECL iisfunc SVN)

iis_stop_service — Stops the service defined by ServiceId

Description

iis_stop_service ( string $service_id ) : int
Warning

This function is currently not documented; only its argument list is available.


NSAPI

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • NSAPI Functions
    • nsapi_request_headers — Fetch all HTTP request headers
    • nsapi_response_headers — Fetch all HTTP response headers
    • nsapi_virtual — Perform an NSAPI sub-request


Introduction

These functions are only available when running PHP as a NSAPI module in Netscape/iPlanet/Sun webservers.


Installation

For PHP installation on Netscape/iPlanet/Sun webservers see the NSAPI section (UNIX, Windows) in the installation chapter.


Runtime Configuration

The behaviour of the NSAPI PHP module is affected by settings in php.ini. Configuration settings from php.ini may be overridden by additional parameters to the php4_execute call in obj.conf

NSAPI configuration options
Name | Default | Changeable | Changelog
nsapi.read_timeout | "60" | PHP_INI_ALL |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

nsapi.read_timeout integer

Sets the time in seconds the plugin is waiting for POST data from the client.


  • « Resource Types
  • NSAPI Functions »
  • PHP Manual
  • NSAPI
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


NSAPI Functions

See Also

NSAPI implements a subset of the functions from the Apache module for maximum compatibility.

Apache functions implemented by NSAPI
Apache function (only as alias) | NSAPI function | Description
apache_request_headers() | nsapi_request_headers() | Fetch all HTTP request headers
apache_response_headers() | nsapi_response_headers() | Fetch all HTTP response headers
getallheaders() | nsapi_request_headers() | Fetch all HTTP request headers
virtual() | nsapi_virtual() | Make NSAPI sub-request

Table of Contents

  • nsapi_request_headers — Fetch all HTTP request headers
  • nsapi_response_headers — Fetch all HTTP response headers
  • nsapi_virtual — Perform an NSAPI sub-request


Fetch all HTTP request headers

  • « NSAPI Functions
  • nsapi_response_headers »
  • PHP Manual
  • NSAPI Functions
  • Fetch all HTTP request headers

nsapi_request_headers

(PHP 4 >= 4.3.3, PHP 5, PHP 7)

nsapi_request_headers — Fetch all HTTP request headers

Description

nsapi_request_headers ( void ) : array

nsapi_request_headers() gets all the HTTP headers in the current request. This is only supported when PHP runs as a NSAPI module.

Note:

getallheaders() is an alias for nsapi_request_headers() if you use the NSAPI module.

Note:

You can also get at the value of the common CGI variables by reading them from the $_SERVER superglobal, which works whether or not you are using PHP as a NSAPI module.

Return Values

Returns an associative array with all the HTTP headers.

Examples

Example #1 nsapi_request_headers() example

<?php
$headers = nsapi_request_headers();

foreach ($headers as $header => $value) {
  echo "$header: $value <br />\n";
}
?>


Fetch all HTTP response headers

  • « nsapi_request_headers
  • nsapi_virtual »
  • PHP Manual
  • NSAPI Functions
  • Fetch all HTTP response headers

nsapi_response_headers

(PHP 4 >= 4.3.3, PHP 5, PHP 7)

nsapi_response_headers — Fetch all HTTP response headers

Description

nsapi_response_headers ( void ) : array

Gets all the NSAPI response headers.

Return Values

Returns an associative array with all the NSAPI response headers.

See Also

  • nsapi_request_headers() - Fetch all HTTP request headers
  • headers_sent() - Checks if or where headers have been sent


Perform an NSAPI sub-request

  • « nsapi_response_headers
  • Session Extensions »
  • PHP Manual
  • NSAPI Functions
  • Perform an NSAPI sub-request

nsapi_virtual

(PHP 4 >= 4.3.3, PHP 5, PHP 7)

nsapi_virtual — Perform an NSAPI sub-request

Description

nsapi_virtual ( string $uri ) : bool

nsapi_virtual() is an NSAPI-specific function which is equivalent to <!--#include virtual...--> in SSI (.shtml files). It does an NSAPI sub-request. It is useful for including CGI scripts or .shtml files, or anything else that you'd parse through webserver.

To run the sub-request, all buffers are terminated and flushed to the browser, pending headers are sent too.

You cannot make recursive requests with this function to other PHP scripts. If you want to include PHP scripts, use include or require.

Note:

This function depends on a undocumented feature of the Netscape/iPlanet/Sun webservers. Use phpinfo() to determine if it is available. In the Unix environment it should always work, in Windows it depends on the name of a ns-httpdXX.dll file.

Read the note about subrequests in the NSAPI section (UNIX, Windows) if you experience this problem.

Parameters

uri

The URI of the script.

Return Values

Returns TRUE on success or FALSE on failure.


Session Extensions

  • Msession — Mohawk Software Session Handler Functions
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Msession Functions
  • Sessions — Session Handling
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Session Upload Progress
    • Sessions and Security
    • Session Functions
    • SessionHandler — The SessionHandler class
    • SessionHandlerInterface — The SessionHandlerInterface class
    • SessionIdInterface — The SessionIdInterface interface
    • SessionUpdateTimestampHandlerInterface — The SessionUpdateTimestampHandlerInterface interface
  • Session PgSQL — PostgreSQL Session Save Handler
    • Introduction
    • Installing/Configuring
    • Table definitions
    • Predefined Constants
    • Session PgSQL Functions


Mohawk Software Session Handler Functions

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Msession Functions
    • msession_connect — Connect to msession server
    • msession_count — Get session count
    • msession_create — Create a session
    • msession_destroy — Destroy a session
    • msession_disconnect — Close connection to msession server
    • msession_find — Find all sessions with name and value
    • msession_get_array — Get array of msession variables
    • msession_get_data — Get data session unstructured data
    • msession_get — Get value from session
    • msession_inc — Increment value in session
    • msession_list — List all sessions
    • msession_listvar — List sessions with variable
    • msession_lock — Lock a session
    • msession_plugin — Call an escape function within the msession personality plugin
    • msession_randstr — Get random string
    • msession_set_array — Set msession variables from an array
    • msession_set_data — Set data session unstructured data
    • msession_set — Set value in session
    • msession_timeout — Set/get session timeout
    • msession_uniq — Get unique id
    • msession_unlock — Unlock a session


Introduction

msession is an interface to a high speed session daemon which can run either locally or remotely. It is designed to provide consistent session management for a PHP web farm. More Information about msession and the session server software itself can be found at » http://www.mohawksoft.org/?q=node/8.

Note: This extension is not available on Windows platforms.

Note:

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.1.3.


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/msession.

This extension has been moved to the » PECL repository and is no longer bundled with PHP as of PHP 5.1.3


  • « Resource Types
  • Msession Functions »
  • PHP Manual
  • Msession
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


Msession Functions

Table of Contents

  • msession_connect — Connect to msession server
  • msession_count — Get session count
  • msession_create — Create a session
  • msession_destroy — Destroy a session
  • msession_disconnect — Close connection to msession server
  • msession_find — Find all sessions with name and value
  • msession_get_array — Get array of msession variables
  • msession_get_data — Get data session unstructured data
  • msession_get — Get value from session
  • msession_inc — Increment value in session
  • msession_list — List all sessions
  • msession_listvar — List sessions with variable
  • msession_lock — Lock a session
  • msession_plugin — Call an escape function within the msession personality plugin
  • msession_randstr — Get random string
  • msession_set_array — Set msession variables from an array
  • msession_set_data — Set data session unstructured data
  • msession_set — Set value in session
  • msession_timeout — Set/get session timeout
  • msession_uniq — Get unique id
  • msession_unlock — Unlock a session


Connect to msession server

  • « Msession Functions
  • msession_count »
  • PHP Manual
  • Msession Functions
  • Connect to msession server

msession_connect

(PHP 4 >= 4.2.0, PHP 5 < 5.1.3)

msession_connect — Connect to msession server

Description

msession_connect ( string $host , string $port ) : bool
Warning

This function is currently not documented; only its argument list is available.


Get session count

  • « msession_connect
  • msession_create »
  • PHP Manual
  • Msession Functions
  • Get session count

msession_count

(PHP 4 >= 4.2.0, PHP 5 < 5.1.3)

msession_count — Get session count

Description

msession_count ( void ) : int
Warning

This function is currently not documented; only its argument list is available.


Create a session

  • « msession_count
  • msession_destroy »
  • PHP Manual
  • Msession Functions
  • Create a session

msession_create

(PHP 4 >= 4.2.0, PHP 5 < 5.1.3)

msession_create — Create a session

Description

msession_create ( string $session [, string $classname [, string $data ]] ) : bool
Warning

This function is currently not documented; only its argument list is available.


Destroy a session

  • « msession_create
  • msession_disconnect »
  • PHP Manual
  • Msession Functions
  • Destroy a session

msession_destroy

(PHP 4 >= 4.2.0, PHP 5 < 5.1.3)

msession_destroy — Destroy a session

Description

msession_destroy ( string $name ) : bool
Warning

This function is currently not documented; only its argument list is available.


Close connection to msession server

  • « msession_destroy
  • msession_find »
  • PHP Manual
  • Msession Functions
  • Close connection to msession server

msession_disconnect

(PHP 4 >= 4.2.0, PHP 5 < 5.1.3)

msession_disconnect — Close connection to msession server

Description

msession_disconnect ( void ) : void
Warning

This function is currently not documented; only its argument list is available.


Find all sessions with name and value

  • « msession_disconnect
  • msession_get_array »
  • PHP Manual
  • Msession Functions
  • Find all sessions with name and value

msession_find

(PHP 4 >= 4.2.0, PHP 5 < 5.1.3)

msession_find — Find all sessions with name and value

Description

msession_find ( string $name , string $value ) : array
Warning

This function is currently not documented; only its argument list is available.


Get array of msession variables

  • « msession_find
  • msession_get_data »
  • PHP Manual
  • Msession Functions
  • Get array of msession variables

msession_get_array

(PHP 4 >= 4.2.0, PHP 5 < 5.1.3)

msession_get_array — Get array of msession variables

Description

msession_get_array ( string $session ) : array
Warning

This function is currently not documented; only its argument list is available.


Get data session unstructured data

  • « msession_get_array
  • msession_get »
  • PHP Manual
  • Msession Functions
  • Get data session unstructured data

msession_get_data

(PHP 4 >= 4.2.0, PHP 5 < 5.1.3)

msession_get_data — Get data session unstructured data

Description

msession_get_data ( string $session ) : string
Warning

This function is currently not documented; only its argument list is available.


Get value from session

  • « msession_get_data
  • msession_inc »
  • PHP Manual
  • Msession Functions
  • Get value from session

msession_get

(PHP 4 >= 4.2.0, PHP 5 < 5.1.3)

msession_get — Get value from session

Description

msession_get ( string $session , string $name , string $value ) : string
Warning

This function is currently not documented; only its argument list is available.


Increment value in session

  • « msession_get
  • msession_list »
  • PHP Manual
  • Msession Functions
  • Increment value in session

msession_inc

(PHP 4 >= 4.2.0, PHP 5 < 5.1.3)

msession_inc — Increment value in session

Description

msession_inc ( string $session , string $name ) : string
Warning

This function is currently not documented; only its argument list is available.


List all sessions

  • « msession_inc
  • msession_listvar »
  • PHP Manual
  • Msession Functions
  • List all sessions

msession_list

(PHP 4 >= 4.2.0, PHP 5 < 5.1.3)

msession_list — List all sessions

Description

msession_list ( void ) : array
Warning

This function is currently not documented; only its argument list is available.


List sessions with variable

  • « msession_list
  • msession_lock »
  • PHP Manual
  • Msession Functions
  • List sessions with variable

msession_listvar

(PHP 4 >= 4.2.0, PHP 5 < 5.1.3)

msession_listvar — List sessions with variable

Description

msession_listvar ( string $name ) : array

Used for searching sessions with common attributes.

Parameters

name

The name being searched.

Return Values

Returns an associative array of value/session for all sessions with a variable named name.


Lock a session

  • « msession_listvar
  • msession_plugin »
  • PHP Manual
  • Msession Functions
  • Lock a session

msession_lock

(PHP 4 >= 4.2.0, PHP 5 < 5.1.3)

msession_lock — Lock a session

Description

msession_lock ( string $name ) : int
Warning

This function is currently not documented; only its argument list is available.


Call an escape function within the msession personality plugin

  • « msession_lock
  • msession_randstr »
  • PHP Manual
  • Msession Functions
  • Call an escape function within the msession personality plugin

msession_plugin

(PHP 4 >= 4.2.0, PHP 5 < 5.1.3)

msession_plugin — Call an escape function within the msession personality plugin

Description

msession_plugin ( string $session , string $val [, string $param ] ) : string
Warning

This function is currently not documented; only its argument list is available.


Get random string

  • « msession_plugin
  • msession_set_array »
  • PHP Manual
  • Msession Functions
  • Get random string

msession_randstr

(PHP 4 >= 4.2.0, PHP 5 < 5.1.3)

msession_randstr — Get random string

Description

msession_randstr ( int $param ) : string
Warning

This function is currently not documented; only its argument list is available.


Set msession variables from an array

  • « msession_randstr
  • msession_set_data »
  • PHP Manual
  • Msession Functions
  • Set msession variables from an array

msession_set_array

(PHP 4 >= 4.2.0, PHP 5 < 5.1.3)

msession_set_array — Set msession variables from an array

Description

msession_set_array ( string $session , array $tuples ) : void
Warning

This function is currently not documented; only its argument list is available.


Set data session unstructured data

  • « msession_set_array
  • msession_set »
  • PHP Manual
  • Msession Functions
  • Set data session unstructured data

msession_set_data

(PHP 4 >= 4.2.0, PHP 5 < 5.1.3)

msession_set_data — Set data session unstructured data

Description

msession_set_data ( string $session , string $value ) : bool
Warning

This function is currently not documented; only its argument list is available.


Set value in session

  • « msession_set_data
  • msession_timeout »
  • PHP Manual
  • Msession Functions
  • Set value in session

msession_set

(PHP 4 >= 4.2.0, PHP 5 < 5.1.3)

msession_set — Set value in session

Description

msession_set ( string $session , string $name , string $value ) : bool
Warning

This function is currently not documented; only its argument list is available.


Set/get session timeout

  • « msession_set
  • msession_uniq »
  • PHP Manual
  • Msession Functions
  • Set/get session timeout

msession_timeout

(PHP 4 >= 4.2.0, PHP 5 < 5.1.3)

msession_timeout — Set/get session timeout

Description

msession_timeout ( string $session [, int $param ] ) : int
Warning

This function is currently not documented; only its argument list is available.


Get unique id

  • « msession_timeout
  • msession_unlock »
  • PHP Manual
  • Msession Functions
  • Get unique id

msession_uniq

(PHP 4 >= 4.2.0, PHP 5 < 5.1.3)

msession_uniq — Get unique id

Description

msession_uniq ( int $param [, string $classname [, string $data ]] ) : string
Warning

This function is currently not documented; only its argument list is available.


Unlock a session

  • « msession_uniq
  • Sessions »
  • PHP Manual
  • Msession Functions
  • Unlock a session

msession_unlock

(PHP 4 >= 4.2.0, PHP 5 < 5.1.3)

msession_unlock — Unlock a session

Description

msession_unlock ( string $session , int $key ) : int
Warning

This function is currently not documented; only its argument list is available.


Session Handling

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic usage
    • Passing the Session ID
    • Custom Session Handlers
  • Session Upload Progress
  • Sessions and Security
    • Session Management Basics
    • Securing Session INI Settings
  • Session Functions
    • session_abort — Discard session array changes and finish session
    • session_cache_expire — Return current cache expire
    • session_cache_limiter — Get and/or set the current cache limiter
    • session_commit — Alias of session_write_close
    • session_create_id — Create new session id
    • session_decode — Decodes session data from a session encoded string
    • session_destroy — Destroys all data registered to a session
    • session_encode — Encodes the current session data as a session encoded string
    • session_gc — Perform session data garbage collection
    • session_get_cookie_params — Get the session cookie parameters
    • session_id — Get and/or set the current session id
    • session_is_registered — Find out whether a global variable is registered in a session
    • session_module_name — Get and/or set the current session module
    • session_name — Get and/or set the current session name
    • session_regenerate_id — Update the current session id with a newly generated one
    • session_register_shutdown — Session shutdown function
    • session_register — Register one or more global variables with the current session
    • session_reset — Re-initialize session array with original values
    • session_save_path — Get and/or set the current session save path
    • session_set_cookie_params — Set the session cookie parameters
    • session_set_save_handler — Sets user-level session storage functions
    • session_start — Start new or resume existing session
    • session_status — Returns the current session status
    • session_unregister — Unregister a global variable from the current session
    • session_unset — Free all session variables
    • session_write_close — Write session data and end session
  • SessionHandler — The SessionHandler class
    • SessionHandler::close — Close the session
    • SessionHandler::create_sid — Return a new session ID
    • SessionHandler::destroy — Destroy a session
    • SessionHandler::gc — Cleanup old sessions
    • SessionHandler::open — Initialize session
    • SessionHandler::read — Read session data
    • SessionHandler::write — Write session data
  • SessionHandlerInterface — The SessionHandlerInterface class
    • SessionHandlerInterface::close — Close the session
    • SessionHandlerInterface::destroy — Destroy a session
    • SessionHandlerInterface::gc — Cleanup old sessions
    • SessionHandlerInterface::open — Initialize session
    • SessionHandlerInterface::read — Read session data
    • SessionHandlerInterface::write — Write session data
  • SessionIdInterface — The SessionIdInterface interface
    • SessionIdInterface::create_sid — Create session ID
  • SessionUpdateTimestampHandlerInterface — The SessionUpdateTimestampHandlerInterface interface
    • SessionUpdateTimestampHandlerInterface::updateTimestamp — Update timestamp
    • SessionUpdateTimestampHandlerInterface::validateId — Validate ID


Introduction

Session support in PHP consists of a way to preserve certain data across subsequent accesses.

A visitor accessing your web site is assigned a unique id, the so-called session id. This is either stored in a cookie on the user side or is propagated in the URL.

The session support allows you to store data between requests in the $_SESSION superglobal array. When a visitor accesses your site, PHP will check automatically (if session.auto_start is set to 1) or on your request (explicitly through session_start()) whether a specific session id has been sent with the request. If this is the case, the prior saved environment is recreated.

Caution

If you turn on session.auto_start then the only way to put objects into your sessions is to load its class definition using auto_prepend_file in which you load the class definition else you will have to serialize() your object and unserialize() it afterwards.

$_SESSION (and all registered variables) are serialized internally by PHP using the serialization handler specified by the session.serialize_handler ini setting, after the request finishes. Registered variables which are undefined are marked as being not defined. On subsequent accesses, these are not defined by the session module unless the user defines them later.

Warning

Because session data is serialized, resource variables cannot be stored in the session.

Serialize handlers (php and php_binary) inherit register_globals limitations. Therefore, numeric index or string index contains special characters (| and !) cannot be used. Using these will end up with errors at script shutdown. php_serialize does not have such limitations. php_serialize is available from PHP 5.5.4.

Note:

Please note when working with sessions that a record of a session is not created until a variable has been registered using the session_register() function or by adding a new key to the $_SESSION superglobal array. This holds true regardless of if a session has been started using the session_start() function.

Note:

PHP 5.2.2 introduced an undocumented feature to store session files in "/tmp" even if open_basedir was enabled and "/tmp" is not explicitly added to the allowed paths list. This feature has been removed from PHP as of PHP 5.3.0.


Requirements

No external libraries are needed to build this extension.

Note:

Optionally you can use shared memory allocation (mm), developed by Ralf S. Engelschall, for session storage. You have to download » mm and install it. This option is not available for Windows platforms. Note that the session storage module for mm does not guarantee that concurrent accesses to the same session are properly locked. It might be more appropriate to use a shared memory based filesystem (such as tmpfs on Solaris/Linux, or /dev/md on BSD) to store sessions in files, because they are properly locked. Session data is stored in memory thus web server restart deletes it.


Installation

Session support is enabled in PHP by default. If you would not like to build your PHP with session support, you should specify the --disable-session option to configure. To use shared memory allocation (mm) for session storage configure PHP --with-mm[=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.

Note:

By default, all data related to a particular session will be stored in a file in the directory specified by the session.save_path INI option. A file for each session (regardless of if any data is associated with that session) will be created. This is due to the fact that a session is opened (a file is created) but no data is even written to that file. Note that this behavior is a side-effect of the limitations of working with the file system and it is possible that a custom session handler (such as one which uses a database) does not keep track of sessions which store no data.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Session configuration options
Name | Default | Changeable | Changelog
session.save_path | "" | PHP_INI_ALL |
session.name | "PHPSESSID" | PHP_INI_ALL |
session.save_handler | "files" | PHP_INI_ALL |
session.auto_start | "0" | PHP_INI_PERDIR |
session.gc_probability | "1" | PHP_INI_ALL |
session.gc_divisor | "100" | PHP_INI_ALL |
session.gc_maxlifetime | "1440" | PHP_INI_ALL |
session.serialize_handler | "php" | PHP_INI_ALL |
session.cookie_lifetime | "0" | PHP_INI_ALL |
session.cookie_path | "/" | PHP_INI_ALL |
session.cookie_domain | "" | PHP_INI_ALL |
session.cookie_secure | "" | PHP_INI_ALL |
session.cookie_httponly | "" | PHP_INI_ALL | Available since PHP 5.2.0.
session.cookie_samesite | "" | PHP_INI_ALL | Available since PHP 7.3.0.
session.use_strict_mode | "0" | PHP_INI_ALL | Available since PHP 5.5.2.
session.use_cookies | "1" | PHP_INI_ALL |
session.use_only_cookies | "1" | PHP_INI_ALL |
session.referer_check | "" | PHP_INI_ALL |
session.cache_limiter | "nocache" | PHP_INI_ALL |
session.cache_expire | "180" | PHP_INI_ALL |
session.use_trans_sid | "0" | PHP_INI_ALL |
session.trans_sid_tags | "a=href,area=href,frame=src,form=" | PHP_INI_ALL | Available since PHP 7.1.0.
session.trans_sid_hosts | $_SERVER['HTTP_HOST'] | PHP_INI_ALL | Available since PHP 7.1.0.
session.sid_length | "32" | PHP_INI_ALL | Available since PHP 7.1.0.
session.sid_bits_per_character | "4" | PHP_INI_ALL | Available since PHP 7.1.0.
session.upload_progress.enabled | "1" | PHP_INI_PERDIR | Available since PHP 5.4.0.
session.upload_progress.cleanup | "1" | PHP_INI_PERDIR | Available since PHP 5.4.0.
session.upload_progress.prefix | "upload_progress_" | PHP_INI_PERDIR | Available since PHP 5.4.0.
session.upload_progress.name | "PHP_SESSION_UPLOAD_PROGRESS" | PHP_INI_PERDIR | Available since PHP 5.4.0.
session.upload_progress.freq | "1%" | PHP_INI_PERDIR | Available since PHP 5.4.0.
session.upload_progress.min_freq | "1" | PHP_INI_PERDIR | Available since PHP 5.4.0.
session.lazy_write | "1" | PHP_INI_ALL | Available since PHP 7.0.0.
url_rewriter.tags | "a=href,area=href,frame=src,form=" | PHP_INI_ALL | Since PHP 7.1.0, this INI is no longer used by session.
session.hash_function | "0" | PHP_INI_ALL | Removed in PHP 7.1.0.
session.hash_bits_per_character | "4" | PHP_INI_ALL | Removed in PHP 7.1.0.
session.entropy_file | "" | PHP_INI_ALL | Removed in PHP 7.1.0.
session.entropy_length | "0" | PHP_INI_ALL | Removed in PHP 7.1.0
session.bug_compat_42 | "1" | PHP_INI_ALL | Removed in PHP 5.4.0.
session.bug_compat_warn | "1" | PHP_INI_ALL | Removed in PHP 5.4.0.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

The session management system supports a number of configuration options which you can place in your php.ini file. We will give a short overview.

session.save_handler string
session.save_handler defines the name of the handler which is used for storing and retrieving data associated with a session. Defaults to files. Note that individual extensions may register their own save_handlers; registered handlers can be obtained on a per-installation basis by referring to phpinfo(). See also session_set_save_handler().
session.save_path string
session.save_path defines the argument which is passed to the save handler. If you choose the default files handler, this is the path where the files are created. See also session_save_path().

There is an optional N argument to this directive that determines the number of directory levels your session files will be spread around in. For example, setting to '5;/tmp' may end up creating a session file and location like /tmp/4/b/1/e/3/sess_4b1e384ad74619bd212e236e52a5a174If . In order to use N you must create all of these directories before use. A small shell script exists in ext/session to do this, it's called mod_files.sh, with a Windows version called mod_files.bat. Also note that if N is used and greater than 0 then automatic garbage collection will not be performed, see a copy of php.ini for further information. Also, if you use N, be sure to surround session.save_path in "quotes" because the separator (;) is also used for comments in php.ini.

The file storage module creates files using mode 600 by default. This default can be changed with the optional MODE argument: N;MODE;/path where MODE is the octal representation of the mode. Setting MODE does not affect the process umask.

Warning

If you leave this set to a world-readable directory, such as /tmp (the default), other users on the server may be able to hijack sessions by getting the list of files in that directory.

Caution

When using the optional directory level argument N, as described above, note that using a value higher than 1 or 2 is inappropriate for most sites due to the large number of directories required: for example, a value of 3 implies that (2 ** session.sid_bits_per_character) ** 3 directories exist on the filesystem, which can result in a lot of wasted space and inodes.

Only use N greater than 2 if you are absolutely certain that your site is large enough to require it.

Note: Prior to PHP 4.3.6, Windows users had to change this variable in order to use PHP's session functions. A valid path must be specified, e.g.: c:/temp.

session.name string
session.name specifies the name of the session which is used as cookie name. It should only contain alphanumeric characters. Defaults to PHPSESSID. See also session_name().
session.auto_start boolean
session.auto_start specifies whether the session module starts a session automatically on request startup. Defaults to 0 (disabled).
session.serialize_handler string
session.serialize_handler defines the name of the handler which is used to serialize/deserialize data. PHP serialize format (name php_serialize), PHP internal formats (name php and php_binary) and WDDX are supported (name wddx). WDDX is only available, if PHP is compiled with WDDX support. php_serialize is available from PHP 5.5.4. php_serialize uses plain serialize/unserialize function internally and does not have limitations that php and php_binary have. Older serialize handlers cannot store numeric index nor string index contains special characters (| and !) in $_SESSION. Use php_serialize to avoid numeric index or special character errors at script shutdown. Defaults to php.
session.gc_probability integer
session.gc_probability in conjunction with session.gc_divisor is used to manage probability that the gc (garbage collection) routine is started. Defaults to 1. See session.gc_divisor for details.
session.gc_divisor integer
session.gc_divisor coupled with session.gc_probability defines the probability that the gc (garbage collection) process is started on every session initialization. The probability is calculated by using gc_probability/gc_divisor, e.g. 1/100 means there is a 1% chance that the GC process starts on each request. session.gc_divisor defaults to 100.
session.gc_maxlifetime integer
session.gc_maxlifetime specifies the number of seconds after which data will be seen as 'garbage' and potentially cleaned up. Garbage collection may occur during session start (depending on session.gc_probability and session.gc_divisor).

Note: If different scripts have different values of session.gc_maxlifetime but share the same place for storing the session data then the script with the minimum value will be cleaning the data. In this case, use this directive together with session.save_path.

session.referer_check string
session.referer_check contains the substring you want to check each HTTP Referer for. If the Referer was sent by the client and the substring was not found, the embedded session id will be marked as invalid. Defaults to the empty string.
session.entropy_file string
session.entropy_file gives a path to an external resource (file) which will be used as an additional entropy source in the session id creation process. Examples are /dev/random or /dev/urandom which are available on many Unix systems. This feature is supported on Windows since PHP 5.3.3. Setting session.entropy_length to a non zero value will make PHP use the Windows Random API as entropy source.

Note: Removed in PHP 7.1.0. As of PHP 5.4.0 session.entropy_file defaults to /dev/urandom or /dev/arandom if it is available. In PHP 5.3.0 this directive is left empty by default.

session.entropy_length integer
session.entropy_length specifies the number of bytes which will be read from the file specified above. Defaults to 32. Removed in PHP 7.1.0.
session.use_strict_mode boolean
session.use_strict_mode specifies whether the module will use strict session id mode. If this mode is enabled, the module does not accept uninitialized session ID. If uninitialized session ID is sent from browser, new session ID is sent to browser. Applications are protected from session fixation via session adoption with strict mode. Defaults to 0 (disabled).

Note: Enabling session.use_strict_mode is mandatory for general session security. All sites are advised to enable this. See session_create_id() example code for more details.

session.use_cookies boolean
session.use_cookies specifies whether the module will use cookies to store the session id on the client side. Defaults to 1 (enabled).
session.use_only_cookies boolean
session.use_only_cookies specifies whether the module will only use cookies to store the session id on the client side. Enabling this setting prevents attacks involved passing session ids in URLs. Defaults to 1 (enabled) since PHP 5.3.0.
session.cookie_lifetime integer
session.cookie_lifetime specifies the lifetime of the cookie in seconds which is sent to the browser. The value 0 means "until the browser is closed." Defaults to 0. See also session_get_cookie_params() and session_set_cookie_params().

Note: The expiration timestamp is set relative to the server time, which is not necessarily the same as the time in the client's browser.

session.cookie_path string
session.cookie_path specifies path to set in the session cookie. Defaults to /. See also session_get_cookie_params() and session_set_cookie_params().
session.cookie_domain string
session.cookie_domain specifies the domain to set in the session cookie. Default is none at all meaning the host name of the server which generated the cookie according to cookies specification. See also session_get_cookie_params() and session_set_cookie_params().
session.cookie_secure boolean
session.cookie_secure specifies whether cookies should only be sent over secure connections. Defaults to off. See also session_get_cookie_params() and session_set_cookie_params().
session.cookie_httponly boolean
Marks the cookie as accessible only through the HTTP protocol. This means that the cookie won't be accessible by scripting languages, such as JavaScript. This setting can effectively help to reduce identity theft through XSS attacks (although it is not supported by all browsers).
session.cookie_samesite string
Allows servers to assert that a cookie ought not to be sent along with cross-site requests. This assertion allows user agents to mitigate the risk of cross-origin information leakage, and provides some protection against cross-site request forgery attacks. Note that this is not supported by all browsers. An empty value means that no SameSite cookie attribute will be set. Lax and Strict mean that the cookie will not be sent cross-domain for POST requests; Lax will sent the cookie for cross-domain GET requests, while Strict will not.
session.cache_limiter string
session.cache_limiter specifies the cache control method used for session pages. It may be one of the following values: nocache, private, private_no_expire, or public. Defaults to nocache. See also the session_cache_limiter() documentation for information about what these values mean.
session.cache_expire integer
session.cache_expire specifies time-to-live for cached session pages in minutes, this has no effect for nocache limiter. Defaults to 180. See also session_cache_expire().
session.use_trans_sid boolean
session.use_trans_sid whether transparent sid support is enabled or not. Defaults to 0 (disabled).

Note: URL based session management has additional security risks compared to cookie based session management. Users may send a URL that contains an active session ID to their friends by email or users may save a URL that contains a session ID to their bookmarks and access your site with the same session ID always, for example. Since PHP 7.1.0, full URL path, e.g. https://php.net/, is handled by trans sid feature. Previous PHP handled relative URL path only. Rewrite target hosts are defined by session.trans_sid_hosts.

session.trans_sid_tags string
session.trans_sid_tags specifies which HTML tags are rewritten to include session id when transparent sid support is enabled. Defaults to a=href,area=href,frame=src,input=src,form= form is special tag. <input hidden="session_id" name="session_name"> is added as form variable.

Note: Before PHP 7.1.0, url_rewriter.tags was used for this purpose. Since PHP 7.1.0, fieldset is no longer considered as special tag.

session.trans_sid_hosts string
session.trans_sid_hosts specifies which hosts are rewritten to include session id when transparent sid support is enabled. Defaults to $_SERVER['HTTP_HOST'] Multiple hosts can be specified by ",", no space is allowed between hosts. e.g. php.net,wiki.php.net,bugs.php.net
session.bug_compat_42 boolean
PHP versions 4.2.3 and lower have an undocumented feature/bug that allows you to initialize a session variable in the global scope, albeit register_globals is disabled. PHP 4.3.0 and later will warn you, if this feature is used, and if session.bug_compat_warn is also enabled. This feature/bug can be disabled by disabling this directive.

Note: Removed in PHP 5.4.0.

session.bug_compat_warn boolean
PHP versions 4.2.3 and lower have an undocumented feature/bug that allows you to initialize a session variable in the global scope, albeit register_globals is disabled. PHP 4.3.0 and later will warn you, if this feature is used by enabling both session.bug_compat_42 and session.bug_compat_warn.

Note: Removed in PHP 5.4.0.

session.sid_length integer
session.sid_length allows you to specify the length of session ID string. Session ID length can be between 22 to 256. The default is 32. If you need compatibility you may specify 32, 40, etc. Longer session ID is harder to guess. At least 32 chars are recommended.
Tip

Compatibility Note: Use 32 instead of
session.hash_function=0 (MD5) and
session.hash_bits_per_character=4,
session.hash_function=1 (SHA1) and
session.hash_bits_per_character=6. Use 26 instead of
session.hash_function=0 (MD5) and
session.hash_bits_per_character=5. Use 22 instead of
session.hash_function=0 (MD5) and
session.hash_bits_per_character=6. You must
configure INI values to have at least 128 bits in session ID. Do
not forget to set an appropriate value for
session.sid_bits_per_character, otherwise you
will have weaker session ID.

Note: This setting is introduced in PHP 7.1.0.

session.sid_bits_per_character integer
session.sid_per_character allows you to specify the number of bits in encoded session ID character. The possible values are '4' (0-9, a-f), '5' (0-9, a-v), and '6' (0-9, a-z, A-Z, "-", ","). The default is 4. The more bits results in stronger session ID. 5 is recommended value for most environments.

Note: This setting is introduced in PHP 7.1.0.

session.hash_function mixed
session.hash_function allows you to specify the hash algorithm used to generate the session IDs. '0' means MD5 (128 bits) and '1' means SHA-1 (160 bits).

Since PHP 5.3.0 it is also possible to specify any of the algorithms provided by the hash extension (if it is available), like sha512 or whirlpool. A complete list of supported algorithms can be obtained with the hash_algos() function.

Note: This setting was introduced in PHP 5. Removed in PHP 7.1.0.

session.hash_bits_per_character integer
session.hash_bits_per_character allows you to define how many bits are stored in each character when converting the binary hash data to something readable. The possible values are '4' (0-9, a-f), '5' (0-9, a-v), and '6' (0-9, a-z, A-Z, "-", ",").

Note: Removed in PHP 7.1.0.

session.upload_progress.enabled boolean
Enables upload progress tracking, populating the $_SESSION variable. Defaults to 1, enabled.
session.upload_progress.cleanup boolean
Cleanup the progress information as soon as all POST data has been read (i.e. upload completed). Defaults to 1, enabled.

Note: It is highly recommended to keep this feature enabled.

session.upload_progress.prefix string
A prefix used for the upload progress key in the $_SESSION. This key will be concatenated with the value of $_POST[ini_get("session.upload_progress.name")] to provide a unique index. Defaults to "upload_progress_".
session.upload_progress.name string
The name of the key to be used in $_SESSION storing the progress information. See also session.upload_progress.prefix. If $_POST[ini_get("session.upload_progress.name")] is not passed or available, upload progressing will not be recorded. Defaults to "PHP_SESSION_UPLOAD_PROGRESS".
session.upload_progress.freq mixed
Defines how often the upload progress information should be updated. This can be defined in bytes (i.e. "update progress information after every 100 bytes"), or in percentages (i.e. "update progress information after receiving every 1% of the whole filesize"). Defaults to "1%".
session.upload_progress.min_freq integer
The minimum delay between updates, in seconds. Defaults to "1" (one second).
session.lazy_write boolean
session.lazy_write, when set to 1, means that session data is only rewritten if it changes. Defaults to 1, enabled.

The register_globals configuration settings influence how the session variables get stored and restored.

Upload progress will not be registered unless session.upload_progress.enabled is enabled, and the $_POST[ini_get("session.upload_progress.name")] variable is set. See Session Upload Progress for more details on this functionality.


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.

SID (string)
Constant containing either the session name and session ID in the form of "name=ID" or empty string if session ID was set in an appropriate session cookie. This is the same id as the one returned by session_id().
PHP_SESSION_DISABLED (int)
Since PHP 5.4.0. Return value of session_status() if sessions are disabled.
PHP_SESSION_NONE (int)
Since PHP 5.4.0. Return value of session_status() if sessions are enabled, but no session exists.
PHP_SESSION_ACTIVE (int)
Since PHP 5.4.0. Return value of session_status() if sessions are enabled, and a session exists.


Examples

Table of Contents

  • Basic usage
  • Passing the Session ID
  • Custom Session Handlers


Basic usage

Sessions are a simple way to store data for individual users against a unique session ID. This can be used to persist state information between page requests. Session IDs are normally sent to the browser via session cookies and the ID is used to retrieve existing session data. The absence of an ID or session cookie lets PHP know to create a new session, and generate a new session ID.

Sessions follow a simple workflow. When a session is started, PHP will either retrieve an existing session using the ID passed (usually from a session cookie) or if no session is passed it will create a new session. PHP will populate the $_SESSION superglobal with any session data after the session has started. When PHP shuts down, it will automatically take the contents of the $_SESSION superglobal, serialize it, and send it for storage using the session save handler.

By default, PHP uses the internal files save handler which is set by session.save_handler. This saves session data on the server at the location specified by the session.save_path configuration directive.

Sessions can be started manually using the session_start() function. If the session.auto_start directive is set to 1, a session will automatically start on request startup.

Sessions normally shutdown automatically when PHP is finished executing a script, but can be manually shutdown using the session_write_close() function.

Example #1 Registering a variable with $_SESSION.

<?php
session_start();
if (!isset($_SESSION['count'])) {
  $_SESSION['count'] = 0;
} else {
  $_SESSION['count']++;
}
?>

Example #2 Unregistering a variable with $_SESSION.

<?php
session_start();
unset($_SESSION['count']);
?>

Caution

Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal.

Warning

You can't use references in session variables as there is no feasible way to restore a reference to another variable.

Warning

register_globals will overwrite variables in the global scope whose names are shared with session variables. Please see Using Register Globals for details.

Note:

File based sessions (the default in PHP) lock the session file once a session is opened via session_start() or implicitly via session.auto_start. Once locked, no other script can access the same session file until it has been closed by the first script terminating or calling session_write_close().

This is most likely to be an issue on Web sites that use AJAX heavily and have multiple concurrent requests. The easiest way to deal with it is to call session_write_close() as soon as any required changes to the session have been made, preferably early in the script. Alternatively, a different session backend that does support concurrency could be used.


Passing the Session ID

There are two methods to propagate a session id:

  • Cookies
  • URL parameter

The session module supports both methods. Cookies are optimal, but because they are not always available, we also provide an alternative way. The second method embeds the session id directly into URLs.

PHP is capable of transforming links transparently. If the run-time option session.use_trans_sid is enabled, relative URIs will be changed to contain the session id automatically.

Note:

The arg_separator.output php.ini directive allows to customize the argument separator. For full XHTML conformance, specify &amp; there.

Alternatively, you can use the constant SID which is defined if the session started. If the client did not send an appropriate session cookie, it has the form session_name=session_id. Otherwise, it expands to an empty string. Thus, you can embed it unconditionally into URLs.

The following example demonstrates how to register a variable, and how to link correctly to another page using SID.

Example #1 Counting the number of hits of a single user

<?php

session_start();

if (empty($_SESSION['count'])) {
   $_SESSION['count'] = 1;
} else {
   $_SESSION['count']++;
}
?>

<p>
Hello visitor, you have seen this page <?php echo $_SESSION['count']; ?> times.
</p>

<p>
To continue, <a href="nextpage.php?<?php echo htmlspecialchars(SID); ?>">click
here</a>.
</p>

The htmlspecialchars() may be used when printing the SID in order to prevent XSS related attacks.

Printing the SID, like shown above, is not necessary if --enable-trans-sid was used to compile PHP.

Note:

Non-relative URLs are assumed to point to external sites and hence don't append the SID, as it would be a security risk to leak the SID to a different server.


Custom Session Handlers

To implement database storage, or any other storage method, you will need to use session_set_save_handler() to create a set of user-level storage functions. As of PHP 5.4.0 you may create session handlers using the SessionHandlerInterface or extend internal PHP handlers by inheriting from SessionHandler.

The callbacks specified in session_set_save_handler() are methods called by PHP during the life-cycle of a session: open, read, write and close and for the housekeeping tasks: destroy for deleting a session and gc for periodic garbage collection.

Therefore, PHP always requires session save handlers. The default is usually the internal 'files' save handler. A custom save handler can be set using session_set_save_handler(). Alternative internal save handlers are also provided by PHP extensions, such as sqlite, memcache and memcached and can be set with session.save_handler.

When the session starts, PHP will internally call the open handler followed by the read callback which should return an encoded string exactly as it was originally passed for storage. Once the read callback returns the encoded string, PHP will decode it and then populate the resulting array into the $_SESSION superglobal.

When PHP shuts down (or when session_write_close() is called), PHP will internally encode the $_SESSION superglobal and pass this along with the session ID to the write callback. After the write callback has finished, PHP will internally invoke the close callback handler.

When a session is specifically destroyed, PHP will call the destroy handler with the session ID.

PHP will call the gc callback from time to time to expire any session records according to the set max lifetime of a session. This routine should delete all records from persistent storage which were last accessed longer than the $lifetime.


Session Upload Progress

Note: This feature is available as of PHP 5.4.0.

When the session.upload_progress.enabled INI option is enabled, PHP will be able to track the upload progress of individual files being uploaded. This information isn't particularly useful for the actual upload request itself, but during the file upload an application can send a POST request to a separate endpoint (via XHR for example) to check the status.

The upload progress will be available in the $_SESSION superglobal when an upload is in progress, and when POSTing a variable of the same name as the session.upload_progress.name INI setting is set to. When PHP detects such POST requests, it will populate an array in the $_SESSION, where the index is a concatenated value of the session.upload_progress.prefix and session.upload_progress.name INI options. The key is typically retrieved by reading these INI settings, i.e.

<?php
$key = ini_get("session.upload_progress.prefix") . $_POST[ini_get("session.upload_progress.name")];
var_dump($_SESSION[$key]);
?>

It is also possible to cancel the currently in-progress file upload, by setting the $_SESSION[$key]["cancel_upload"] key to TRUE. When uploading multiple files in the same request, this will only cancel the currently in-progress file upload, and pending file uploads, but will not remove successfully completed uploads. When an upload is cancelled like this, the error key in $_FILES array will be set to UPLOAD_ERR_EXTENSION.

The session.upload_progress.freq and session.upload_progress.min_freq INI options control how frequent the upload progress information should be recalculated. With a reasonable amount for these two settings, the overhead of this feature is almost non-existent.

Example #1 Example information

Example of the structure of the progress upload array.

<form action="upload.php" method="POST" enctype="multipart/form-data">
 <input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="123" />
 <input type="file" name="file1" />
 <input type="file" name="file2" />
 <input type="submit" />
</form>

The data stored in the session will look like this:

<?php
$_SESSION["upload_progress_123"] = array(
 "start_time" => 1234567890,   // The request time
 "content_length" => 57343257, // POST content length
 "bytes_processed" => 453489,  // Amount of bytes received and processed
 "done" => false,              // true when the POST handler has finished, successfully or not
 "files" => array(
  0 => array(
   "field_name" => "file1",       // Name of the <input/> field
   // The following 3 elements equals those in $_FILES
   "name" => "foo.avi",
   "tmp_name" => "/tmp/phpxxxxxx",
   "error" => 0,
   "done" => true,                // True when the POST handler has finished handling this file
   "start_time" => 1234567890,    // When this file has started to be processed
   "bytes_processed" => 57343250, // Number of bytes received and processed for this file
  ),
  // An other file, not finished uploading, in the same request
  1 => array(
   "field_name" => "file2",
   "name" => "bar.avi",
   "tmp_name" => NULL,
   "error" => 0,
   "done" => false,
   "start_time" => 1234567899,
   "bytes_processed" => 54554,
  ),
 )
);

Warning

The web server's request buffering has to be disabled for this to work properly, else PHP may see the file upload only once fully uploaded. Servers such as Nginx are known to buffer larger requests.

Caution

The upload progress information is written to the session before any scripts are executed. Therefore changing the session name via ini_set() or session_name() will give a session without the upload progress information.


Sessions and Security

Table of Contents

  • Session Management Basics
  • Securing Session INI Settings

External links: » Session fixation

HTTP session management represents the core of web security. All possible mitigation measures SHOULD be adopted to ensure sessions are secured. Developers should also enable/use applicable security measures.


Session Management Basics

Session Security

The session module can not guarantee that the information stored in a session is only viewed by the user who created the session. Additional measures are needed to protect the confidentiality of the session, depending on the value associated with it.

The importance of the data carried in the session needs to be assessed and further protection may be deployed; this typically comes at a price, such as reduced convenience for the user. For example, to protect users from a simple social engineering tactic, session.use_only_cookies needs to be enabled. In that case, cookies must be enabled unconditionally on the client side, or sessions will not work.

There are several ways to leak an existing session ID to third parties. E.g. JavaScript injections, session IDs in URLs, packet sniffing, physical access to the device, etc. A leaked session ID enables the third party to access all resources associated with a specific ID. First, URLs carrying session IDs. If there are links to an external site or resource, the URL including the session ID might be stored in the external site's referrer logs. Second, a more active attacker might listen to network traffic. If it is unencrypted, session IDs will flow in plain text over the network. The solution is to implement SSL/TLS on the server and make it mandatory for users. HSTS should be used for improved security.

Note: Even HTTPS can not protect confidential data at all times. For example the CRIME and Beast vulnerabilities may enable an attacker to read the data. Also, note that many networks employ HTTPS MITM proxies for audit purposes. Attackers may also set up such a proxy.

Nonadaptive Session Management

PHP's session manager is adaptive by default currently. An adaptive session manager bears additional risks.

As of PHP 5.5.2, session.use_strict_mode is available. When it is enabled, and the session save handler supports it, an uninitialized session ID is rejected and a new one is created. This prevents an attack that forces users to use a known session ID. An attacker may paste links or send emails that contains the session ID. E.g. http://example.com/page.php?PHPSESSID=123456789 if session.use_trans_sid is enabled, the victim will start a session using the session ID provided by the attacker. session.use_strict_mode mitigate this risk.

Warning

User defined save handlers can also support strict session mode by implementing session ID validation. All user defined save handlers should implement session ID validation.

The session ID cookie may be set with the domain, path, httponly, secure and, as of PHP 7.3, SameSite attributes. There is precedence defined by browsers. By using the precedence, an attacker can set session ID that could be used permanently. Use of session.use_only_cookies will not solve this issue. session.use_strict_mode mitigates this risk. With session.use_strict_mode=On, the uninitialized session ID will be refused.

Note: Even though session.use_strict_mode mitigates the risk of adaptive session management, an attacker can force users to use an initialized session ID which has been created by an attacker. E.g. JavaScript injection. This attack can be mitigated by this manual's recommendations. By following this manual, developers should enable, session.use_strict_mode, use timestamp based session management, and regenerate session IDs using session_regenerate_id() with recommended procedures. If developers follow all of the above, an attacker generated session ID will eventually be deleted. When an access to an obsolete session occurs, developers should save all active session data of the user. As this information will be relevant for an ensuing investigation. The user should be forcefully logged out of all sessions, i.e. require them to reauthenticate. This prevents attackers from abusing stolen sessions.

Warning

Access to an obsolete session does not necessarily suggest an attack. An unstable network and/or immediate deletion of the active session will result in legitimate users using obsolete sessions.

As of PHP 7.1.0, session_create_id() has been added. This function may be operated to access all active sessions of a user efficiently by prefixing the session IDs with the user ID. Enabling session.use_strict_mode is vital with this setup. Otherwise, malicious users can set malicious session ID for other users.

Note: Users prior to PHP 7.1.0 SHOULD use CSPRNG, e.g. /dev/urandom, or random_bytes() and hash functions to generate a new session ID. session_create_id() has collision detection and generates a session ID according to the session's INI settings. Use of session_create_id() is preferred.

Session ID Regeneration

session.use_strict_mode is a good mitigation, however not sufficient. Developers must equally use session_regenerate_id() for session security.

Session ID regeneration reduces the risk of stolen session IDs, thus session_regenerate_id() must be called periodically. E.g. Regenerate the session ID every 15 minutes for security sensitive content. Even in the case that a session ID is stolen, both the legitimate user's and the attacker's session will expire. In other words access by the user or the attacker will generate an obsolete session access error.

Session IDs must be regenerated when user privileges are elevated, such as after authenticating. session_regenerate_id() must be called prior to setting the authentication information to $_SESSION. (As of PHP 7.0.0, session_regenerate_id() saves the current session data automatically in order to save timestamp/etc. to the current session.) Ensure only the new session contains the authenticated flag.

Developers must not rely on session ID expiration by session.gc_maxlifetime. Attackers may access a victim's session ID periodically to prevent its expiration and keep exploiting it, including an authenticated session.

Instead, developers must implement timestamp based session data management.

Warning

Although the session manager can manage timestamps transparently, this feature is not implemented. Old session data must be kept until GC. Simultaneously, developers must assure themselves obsolete session data is removed. However, developers must not remove active session data immediately. I.e. session_regenerate_id(true); and session_destroy() must never be called together for an active session. This may sound contradictory, but this is a mandatory requirement.

session_regenerate_id() does not delete outdated sessions by default. Obsolete authenticated sessions may be present for use. Developers must prevent outdated sessions to be consumed by anyone. They must prohibit access to obsolete session data by themselves using timestamps.

Warning

The sudden removal of an active session produces undesirable side effects. Sessions can vanish when there are concurrent connections to the web application and/or the network is unstable.

Potential malicious access is undetectable with the sudden removal of active sessions.

Instead of deleting outdated sessions immediately, developers must set a short-term expiration time (timestamp) in $_SESSION, and prohibit access to the session data by themselves.

Developers must not prohibit access to old session data immediately after session_regenerate_id(). It must be prohibited at a later stage. E.g. a few seconds later for stable networks, like a wired network, and a few minutes later for unstable networks such as cell phones or Wi-Fi.

If a user accesses an obsolete session (expired session), access to it should be denied. It is also recommended to remove the authenticated status from all of the user's sessions to as it is likely to represent an attack.

Proper use of session.use_only_cookies and session_regenerate_id() can cause personal DoS with undeletable cookies set by attackers. In this case, developers may invite users to remove cookies and advise them they may be affected by a security issue. Attackers may set malicious cookies via a vulnerable web application, an exposed/vicious browser plugin, a physically compromised device, etc.

Warning

Do not misunderstand the DoS risk. use_strict_mode=On is mandatory for general session ID security! All sites are advised to enable use_strict_mode.

DoS can only happen when the account is under attack. A JavaScript injection vulnerability in an application represents the most common cause.

Session Data Deletion

Obsolete session data must be inaccessible and deleted. The current session module does not handle this well.

Obsolete session data should be removed as soon as possible. However, active sessions must not be removed instantly. To satisfy those requirements, developers must implement timestamp based session data management by themselves.

Set and manage expiration timestamp in $_SESSION. Prohibit access to outdated session data. When access to obsolete session data is detected, it is advised to remove all authenticated status from the user's sessions and force them to re-authenticate. Access to obsolete session data can represent an attack. To achieve this, developers must keep track of all active sessions of every user.

Note: Access to an obsolete session can also happen because of an unstable network and/or concurrent access to the web site. E.g the server tried to set a new session ID via a cookie, but the Set-Cookie packet may not have reached the client due to loss of connection. One connection may issue a new session ID by session_regenerate_id(), but another concurrent connection may not have received the new session ID yet. Therefore, developers must prohibit access to obsolete session at a later stage. I.e. timestamp based session management is mandatory.

In summary, session data must not be destroyed with session_regenerate_id() nor session_destroy(), but timestamps must be used to control access to session data. Let session_gc() remove obsolete data from the session data storage.

Session and Locking

Session data is locked to avoid race conditions by default. Locking is mandatory to keep session data consistent across requests.

However, session-locking can be abused by attackers to perform DoS attacks. To mitigate the risk of a DoS attack by session-locking, minimize locks. Use read only sessions when session data does not need to be updated. Use the 'read_and_close' option with session_start(). session_start(['read_and_close'=>1]); Close the session as soon as possible after updating $_SESSION by using session_commit().

The current session module does not detect any modification of $_SESSION when the session is inactive. It is the developer's responsibility not to modify $_SESSION when the session is inactive.

Active Sessions

Developers should keep track of all active sessions for every user. And notify them of how many active sessions, from which IP (and area), how long it has been active, etc. PHP does not keep track of these. Developers are supposed to do so.

Various ways to implement this exist. One possible implementation is setting up a database that keeps track of the required data and stores any relevant information. Since session data is GCed, developers must take care of the GCed data to maintain the active session database consistency.

One of the simplest implementations is "User ID prefixed session ID" and store the required information in $_SESSION. Many databases posses good performance for selecting string prefix. Developers MAY use session_regenerate_id() and session_create_id() for this.

Warning

Never employ confidential data as a prefix. If the user ID is confidential, consider using hash_hmac().

Warning

Enabling session.use_strict_mode is mandatory for this setup. Ensure it is enabled. Otherwise the active session database can be compromised.

Timestamp based session management is mandatory to detect access to obsolete sessions. When access to an obsolete session is detected, authentication flags should be removed from all active sessions of the user. This prevents attackers to keep exploiting stolen sessions.

Session and Auto-login

Developers must not use long life session IDs for auto-login because it increases the risk of stolen sessions. An auto-login feature should be implemented by the developer.

Use a secure one time hash key as an auto-login key using setcookie(). Use a secure hash stronger than SHA-2. E.g. SHA-256 or greater with random data from random_bytes() or /dev/urandom.

If the user is unauthenticated, check whether the one-time auto-login key is valid or not. In the case it is valid, authenticate the user and set a new secure one-time hash key. An auto-login key must only be used once, i.e. never reuse an auto-login key, always generate a new one.

An auto-login key is a long life authentication key, it should be protected as much as possible. Use path/httponly/secure/SameSite cookie attributes to secure it. I.e. never transmit the auto-login key unless required.

Developer must implement the features that disables auto-login and removes unneeded auto-login key cookie.

CSRF (Cross-Site Request Forgeries) attacks

Sessions and authentication do not protect against CSRF attacks. Developers must implement CSRF protection by themselves.

output_add_rewrite_var() can be used for CSRF protection. Refer to the manual page for more details.

Note: PHP prior to 7.2.0 uses the same output buffer and INI setting as trans sid. Therefore, use of output_add_rewrite_var() with PHP prior to version 7.2.0 is not advised.

Most web application frameworks support CSRF protection. Refer to the web application framework manual for more details.

As of PHP 7.3 the SameSite attribute for the session cookie can be set. This is an additional measure which can mitigate CSRF vulnerabilities.


Securing Session INI Settings

By securing session related INI settings, developers can improve session security. Some important INI settings do not have any recommended settings. Developers are responsible for hardening session settings.

  • session.cookie_lifetime=0

    0 possesses a particular meaning. It informs browsers not to store the cookie to permanent storage. Therefore, when the browser is terminated, the session ID cookie is deleted immediately. If developers set this other than 0, it may allow other users to use the session ID. Most applications should use "0" for this.

    If an auto-login feature is required, developers must implement their own secure auto-login feature. Do not use long life session IDs for this. More information can be found above in the relevant section.

  • session.use_cookies=On

    session.use_only_cookies=On

    Although HTTP cookies suffer some problems, cookies remain the preferred way to manage session IDs. Only use cookies for session ID management when it is possible. Most applications should use a cookie for the session ID.

    If session.use_only_cookies=Off, the session module will use the session ID values set by GET/POST/URL provided the session ID cookie is uninitialized.

  • session.use_strict_mode=On

    Although, enabling session.use_strict_mode is mandatory for secure sessions. It is disabled by default.

    This prevents the session module to use an uninitialized session ID. Put differently, the session module only accepts valid session IDs generated by the session module. It rejects any session ID supplied by users.

    Due to the cookie specification, attackers are capable to place non removable session ID cookies by locally setting a cookie database or JavaScript injections. session.use_strict_mode can prevent an attacker initialized session ID of being used.

    Note:

    Attackers may initialize a session ID with their device and may set the session ID of the victim. They must keep the session ID active to abuse. Attackers require additional steps to perform an attack in this scenario. Therefore, session.use_strict_mode works as a mitigation.

  • session.cookie_httponly=On

    Refuses access to the session cookie from JavaScript. This setting prevents cookies snatched by a JavaScript injection.

    It is possible to use a session ID as a CSRF token, but this is not recommended. For example, HTML sources may be saved and sent to other users. Developers should not write session IDs in web pages for better security. Almost all applications must use the httponly attribute for the session ID cookie.

    Note:

    The CSRF token should be renewed periodically just like the session ID.

  • session.cookie_secure=On

    Allow access to the session ID cookie only when the protocol is HTTPS. If a website is only accessible via HTTPS, it should enable this setting.

    HSTS should be considered for websites accessible only via HTTPS.

  • session.cookie_samesite="Lax" or session.cookie_samesite="Strict"

    As of PHP 7.3 the "SameSite" attribute can be set for the session ID cookie. This attribute is a way to mitigate CSRF (Cross Site Request Forgery) attacks.

    The difference between Lax and Strict is the accessibility of the cookie in requests originating from another registrable domain employing the HTTP GET method. Cookies using Lax will be accessible in a GET request originated from another registrable domain, whereas cookies using Strict will not.

  • session.gc_maxlifetime=[choose smallest possible]

    session.gc_maxlifetime is a setting for deleting obsolete session ID. Reliance on this setting is not recommended. Developers should manage the lifetime of sessions with a timestamp by themselves.

    Session GC (garbage collection) is best performed by using session_gc(). The session_gc() function should be executed by a task managers. E.g. cron on UNIX like systems.

    GC is performed by probability by default. This setting does not guarantee that an outdated session is deleted. Although developers cannot rely on this setting, specifying it to the smallest possible value is recommended. Adjusting session.gc_probability and session.gc_divisor so that obsolete sessions are deleted at an appropriate frequency. If an auto-login feature is required, developers must implement their own secure auto-login feature, see above for more information. Never use long life session ID for this feature.

    Note:

    Some session save handler modules do not use this setting for probability based expiration. E.g. memcached, memcache. Refer to the session save handler documentation for details.

  • session.use_trans_sid=Off

    Use of a transparent session ID management is not prohibited. Developers may employ it when it is required. However, disabling transparent session ID management improves the general session ID security by eliminating the possibility of a session ID injection and/or leak.

    Note:

    Session ID may leak from bookmarked URLs, e-mailed URLs, saved HTML source, etc.

  • session.trans_sid_tags=[limited tags]

    (PHP 7.1.0 >=) Developers should not rewrite unneeded HTML tags. Default value should be sufficient for most usages. Older PHP versions use url_rewriter.tags instead.

  • session.trans_sid_hosts=[limited hosts]

    (PHP 7.1.0 >=) This INI defines whitelist hosts that allows trans sid rewrite. Never add untrusted hosts. Session module only allows $_SERVER['HTTP_HOST'] when this setting is empty.

  • session.referer_check=[originating URL]

    When session.use_trans_sid is enabled. It reduces the risk of session ID injection. If a website is http://example.com/, set http://example.com/ to it. Note that with HTTPS browsers will not send the referrer header. Browsers may not send the referrer header by configuration. Therefore, this setting is not a reliable security measure. Use of this setting is recommended.

  • session.cache_limiter=nocache

    Ensure HTTP content are uncached for authenticated sessions. Allow caching only when the content is not private. Otherwise, content may be exposed. "private" may be employed if HTTP content does not include security sensitive data. Note that "private" may transmit private data cached by shared clients. "public" must only be used when HTTP content does not contain any private data at all.

  • session.sid_length="48"

    (PHP 7.1.0 >=) Longer session IDs results in stronger session IDs. Developers should consider a session ID length of 32 characters or more. At least 26 characters are required when session.sid_bits_per_character="5".

  • session.sid_bits_per_character="6"

    (PHP 7.1.0 >=) The more bits there are in a session ID character, the stronger the session ID generated by the session module is for an identical session ID length.

  • session.hash_function="sha256"

    (PHP 7.1.0 <) A stronger hash function will generate a stronger session ID. Although hash collision is unlikely even with the MD5 hashing algorithm, developers should use SHA-2 or a stronger hashing algorithm like sha384 and sha512. Developers must ensure they feed a long enough entropy for the hashing function used.


Session Functions

Table of Contents

  • session_abort — Discard session array changes and finish session
  • session_cache_expire — Return current cache expire
  • session_cache_limiter — Get and/or set the current cache limiter
  • session_commit — Alias of session_write_close
  • session_create_id — Create new session id
  • session_decode — Decodes session data from a session encoded string
  • session_destroy — Destroys all data registered to a session
  • session_encode — Encodes the current session data as a session encoded string
  • session_gc — Perform session data garbage collection
  • session_get_cookie_params — Get the session cookie parameters
  • session_id — Get and/or set the current session id
  • session_is_registered — Find out whether a global variable is registered in a session
  • session_module_name — Get and/or set the current session module
  • session_name — Get and/or set the current session name
  • session_regenerate_id — Update the current session id with a newly generated one
  • session_register_shutdown — Session shutdown function
  • session_register — Register one or more global variables with the current session
  • session_reset — Re-initialize session array with original values
  • session_save_path — Get and/or set the current session save path
  • session_set_cookie_params — Set the session cookie parameters
  • session_set_save_handler — Sets user-level session storage functions
  • session_start — Start new or resume existing session
  • session_status — Returns the current session status
  • session_unregister — Unregister a global variable from the current session
  • session_unset — Free all session variables
  • session_write_close — Write session data and end session


Discard session array changes and finish session

  • « Session Functions
  • session_cache_expire »
  • PHP Manual
  • Session Functions
  • Discard session array changes and finish session

session_abort

(PHP 5 >= 5.6.0, PHP 7)

session_abort — Discard session array changes and finish session

Description

session_abort ( void ) : bool

session_abort() finishes session without saving data. Thus the original values in session data are kept.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.2.0 | The return type of this function is bool now. Formerly, it has been void.

See Also

  • $_SESSION
  • The session.auto_start configuration directive
  • session_start() - Start new or resume existing session
  • session_reset() - Re-initialize session array with original values
  • session_commit() - Alias of session_write_close


Return current cache expire

  • « session_abort
  • session_cache_limiter »
  • PHP Manual
  • Session Functions
  • Return current cache expire

session_cache_expire

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

session_cache_expire — Return current cache expire

Description

session_cache_expire ([ string $new_cache_expire ] ) : int

session_cache_expire() returns the current setting of session.cache_expire.

The cache expire is reset to the default value of 180 stored in session.cache_expire at request startup time. Thus, you need to call session_cache_expire() for every request (and before session_start() is called).

Parameters

new_cache_expire

If new_cache_expire is given, the current cache expire is replaced with new_cache_expire.

Note: Setting new_cache_expire is of value only, if session.cache_limiter is set to a value different from nocache.

Return Values

Returns the current setting of session.cache_expire. The value returned should be read in minutes, defaults to 180.

Examples

Example #1 session_cache_expire() example

<?php

/* set the cache limiter to 'private' */

session_cache_limiter('private');
$cache_limiter = session_cache_limiter();

/* set the cache expire to 30 minutes */
session_cache_expire(30);
$cache_expire = session_cache_expire();

/* start the session */

session_start();

echo "The cache limiter is now set to $cache_limiter<br />";
echo "The cached session pages expire after $cache_expire minutes";
?>

See Also

  • session.cache_expire
  • session.cache_limiter
  • session_cache_limiter() - Get and/or set the current cache limiter


Get and/or set the current cache limiter

  • « session_cache_expire
  • session_commit »
  • PHP Manual
  • Session Functions
  • Get and/or set the current cache limiter

session_cache_limiter

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

session_cache_limiter — Get and/or set the current cache limiter

Description

session_cache_limiter ([ string $cache_limiter ] ) : string

session_cache_limiter() returns the name of the current cache limiter.

The cache limiter defines which cache control HTTP headers are sent to the client. These headers determine the rules by which the page content may be cached by the client and intermediate proxies. Setting the cache limiter to nocache disallows any client/proxy caching. A value of public permits caching by proxies and the client, whereas private disallows caching by proxies and permits the client to cache the contents.

In private mode, the Expire header sent to the client may cause confusion for some browsers, including Mozilla. You can avoid this problem by using private_no_expire mode. The Expire header is never sent to the client in this mode.

Setting the cache limiter to '' will turn off automatic sending of cache headers entirely.

The cache limiter is reset to the default value stored in session.cache_limiter at request startup time. Thus, you need to call session_cache_limiter() for every request (and before session_start() is called).

Parameters

cache_limiter

If cache_limiter is specified, the name of the current cache limiter is changed to the new value.

Possible values
Value Headers sent
public
Expires: (sometime in the future, according session.cache_expire)
Cache-Control: public, max-age=(sometime in the future, according to session.cache_expire)
Last-Modified: (the timestamp of when the session was last saved)
private_no_expire
Cache-Control: private, max-age=(session.cache_expire in the future), pre-check=(session.cache_expire in the future)
Last-Modified: (the timestamp of when the session was last saved)
private
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: private, max-age=(session.cache_expire in the future), pre-check=(session.cache_expire in the future)
Last-Modified: (the timestamp of when the session was last saved)
nocache
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache

Return Values

Returns the name of the current cache limiter.

Examples

Example #1 session_cache_limiter() example

<?php

/* set the cache limiter to 'private' */

session_cache_limiter('private');
$cache_limiter = session_cache_limiter();

echo "The cache limiter is now set to $cache_limiter<br />";
?>

See Also

  • session.cache_limiter


Alias of session_write_close

  • « session_cache_limiter
  • session_create_id »
  • PHP Manual
  • Session Functions
  • Alias of session_write_close

session_commit

(PHP 4 >= 4.4.0, PHP 5, PHP 7)

session_commit — Alias of session_write_close()

Description

This function is an alias of: session_write_close().


Create new session id

  • « session_commit
  • session_decode »
  • PHP Manual
  • Session Functions
  • Create new session id

session_create_id

(PHP 7 >= 7.1.0)

session_create_id — Create new session id

Description

session_create_id ([ string $prefix ] ) : string

session_create_id() is used to create new session id for the current session. It returns collision free session id.

If session is not active, collision check is omitted.

Session ID is created according to php.ini settings.

It is important to use the same user ID of your web server for GC task script. Otherwise, you may have permission problems especially with files save handler.

Parameters

prefix

If prefix is specified, new session id is prefixed by prefix. Not all characters are allowed within the session id. Characters in the range a-z A-Z 0-9 , (comma) and - (minus) are allowed.

Return Values

session_create_id() returns new collision free session id for the current session. If it is used without active session, it omits collision check.

Examples

Example #1 session_create_id() example with session_regenerate_id()

<?php
// My session start function support timestamp management
function my_session_start() {
    session_start();
    // Do not allow to use too old session ID
    if (!empty($_SESSION['deleted_time']) && $_SESSION['deleted_time'] < time() - 180) {
        session_destroy();
        session_start();
    }
}

// My session regenerate id function
function my_session_regenerate_id() {
    // Call session_create_id() while session is active to
    // make sure collision free.
    if (session_status() != PHP_SESSION_ACTIVE) {
        session_start();
    }
    // WARNING: Never use confidential strings for prefix!
    $newid = session_create_id('myprefix-');
    // Set deleted timestamp. Session data must not be deleted immediately for reasons.
    $_SESSION['deleted_time'] = time();
    // Finish session
    session_commit();
    // Make sure to accept user defined session ID
    // NOTE: You must enable use_strict_mode for normal operations.
    ini_set('session.use_strict_mode', 0);
    // Set new custom session ID
    session_id($newid);
    // Start with custom session ID
    session_start();
}

// Make sure use_strict_mode is enabled.
// use_strict_mode is mandatory for security reasons.
ini_set('session.use_strict_mode', 1);
my_session_start();

// Session ID must be regenerated when
//  - User logged in
//  - User logged out
//  - Certain period has passed
my_session_regenerate_id();

// Write useful codes
?>

See Also

  • session_regenerate_id() - Update the current session id with a newly generated one
  • session_start() - Start new or resume existing session
  • session.use_strict_mode
  • SessionHandler::create_sid() - Return a new session ID


Decodes session data from a session encoded string

  • « session_create_id
  • session_destroy »
  • PHP Manual
  • Session Functions
  • Decodes session data from a session encoded string

session_decode

(PHP 4, PHP 5, PHP 7)

session_decode — Decodes session data from a session encoded string

Description

session_decode ( string $data ) : bool

session_decode() decodes the serialized session data provided in $data, and populates the $_SESSION superglobal with the result.

By default, the unserialization method used is internal to PHP, and is not the same as unserialize(). The serialization method can be set using session.serialize_handler.

Parameters

data

The encoded data to be stored.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • session_encode() - Encodes the current session data as a session encoded string
  • session.serialize_handler


Destroys all data registered to a session

  • « session_decode
  • session_encode »
  • PHP Manual
  • Session Functions
  • Destroys all data registered to a session

session_destroy

(PHP 4, PHP 5, PHP 7)

session_destroy — Destroys all data registered to a session

Description

session_destroy ( void ) : bool

session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie. To use the session variables again, session_start() has to be called.

Note: You do not have to call session_destroy() from usual code. Cleanup $_SESSION array rather than destroying session data.

In order to kill the session altogether, the session ID must also be unset. If a cookie is used to propagate the session ID (default behavior), then the session cookie must be deleted. setcookie() may be used for that.

When session.use_strict_mode is enabled. You do not have to remove obsolete session ID cookie because session module will not accept session ID cookie when there is no data associated to the session ID and set new session ID cookie. Enabling session.use_strict_mode is recommended for all sites.

Warning

Immediate session deletion may cause unwanted results. When there is concurrent requests, other connections may see sudden session data loss. e.g. Requests from JavaScript and/or requests from URL links.

Although current session module does not accept empty session ID cookie, but immediate session deletion may result in empty session ID cookie due to client(browser) side race condition. This will result that the client creates many session ID needlessly.

To avoid these, you must set deletion time-stamp to $_SESSION and reject access while later. Or make sure your application does not have concurrent requests. This applies to session_regenerate_id() also.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Destroying a session with $_SESSION

<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();

// Unset all of the session variables.
$_SESSION = array();

// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}

// Finally, destroy the session.
session_destroy();
?>

Notes

Note:

Only use session_unset() for older deprecated code that does not use $_SESSION.

See Also

  • session.use_strict_mode
  • session_reset() - Re-initialize session array with original values
  • session_regenerate_id() - Update the current session id with a newly generated one
  • unset() - Unset a given variable
  • setcookie() - Send a cookie


Encodes the current session data as a session encoded string

  • « session_destroy
  • session_gc »
  • PHP Manual
  • Session Functions
  • Encodes the current session data as a session encoded string

session_encode

(PHP 4, PHP 5, PHP 7)

session_encode — Encodes the current session data as a session encoded string

Description

session_encode ( void ) : string

session_encode() returns a serialized string of the contents of the current session data stored in the $_SESSION superglobal.

By default, the serialization method used is internal to PHP, and is not the same as serialize(). The serialization method can be set using session.serialize_handler.

Return Values

Returns the contents of the current session encoded.

Notes

Warning

Must call session_start() before using session_encode().

See Also

  • session_decode() - Decodes session data from a session encoded string
  • session.serialize_handler


Perform session data garbage collection

  • « session_encode
  • session_get_cookie_params »
  • PHP Manual
  • Session Functions
  • Perform session data garbage collection

session_gc

(PHP 7 >= 7.1.0)

session_gc — Perform session data garbage collection

Description

session_gc ( void ) : int

session_gc() is used to perform session data GC(garbage collection). PHP does probability based session GC by default.

Probability based GC works somewhat but it has few problems. 1) Low traffic sites' session data may not be deleted within the preferred duration. 2) High traffic sites' GC may be too frequent GC. 3) GC is performed on the user's request and the user will experience a GC delay.

Therefore, it is recommended to execute GC periodically for production systems using, e.g., "cron" for UNIX-like systems. Make sure to disable probability based GC by setting session.gc_probability to 0.

Return Values

session_gc() returns number of deleted session data for success, FALSE for failure.

Old save handlers do not return number of deleted session data, but only success/failure flag. If this is the case, number of deleted session data became 1 regardless of actually deleted data.

Examples

Example #1 session_gc() example for task managers like cron

<?php
// Note: This script should be executed by the same user of web server process.

// Need active session to initialize session data storage access.
session_start();

// Executes GC immediately
session_gc();

// Clean up session ID created by session_gc()
session_destroy();
?>

Example #2 session_gc() example for user accessible script

<?php
// Note: session_gc() is recommended to be used by task manager script, but
// it may be used as follows.

// Used for last GC time check
$gc_time = '/tmp/php_session_last_gc';
$gc_period = 1800;

session_start();
// Execute GC only when GC period elapsed.
// i.e. Calling session_gc() every request is waste of resources.
if (file_exists($gc_time)) {
    if (filemtime($gc_time) < time() - $gc_period) {
        session_gc();
        touch($gc_time);
    }
} else {
    touch($gc_time);
}
?>

See Also

  • session_start() - Start new or resume existing session
  • session_destroy() - Destroys all data registered to a session
  • session.gc_probability


Get the session cookie parameters

  • « session_gc
  • session_id »
  • PHP Manual
  • Session Functions
  • Get the session cookie parameters

session_get_cookie_params

(PHP 4, PHP 5, PHP 7)

session_get_cookie_params — Get the session cookie parameters

Description

session_get_cookie_params ( void ) : array

Gets the session cookie parameters.

Return Values

Returns an array with the current session cookie information, the array contains the following items:

  • "lifetime" - The lifetime of the cookie in seconds.
  • "path" - The path where information is stored.
  • "domain" - The domain of the cookie.
  • "secure" - The cookie should only be sent over secure connections.
  • "httponly" - The cookie can only be accessed through the HTTP protocol.
  • "samesite" - Controls the cross-domain sending of the cookie.

Changelog

Version | Description
7.3.0 | The "samesite" entry was added in the returned array.
5.2.0 | The "httponly" entry was added in the returned array.

See Also

  • session.cookie_lifetime
  • session.cookie_path
  • session.cookie_domain
  • session.cookie_secure
  • session.cookie_httponly
  • session.cookie_samesite
  • session_set_cookie_params() - Set the session cookie parameters


Get and/or set the current session id

  • « session_get_cookie_params
  • session_is_registered »
  • PHP Manual
  • Session Functions
  • Get and/or set the current session id

session_id

(PHP 4, PHP 5, PHP 7)

session_id — Get and/or set the current session id

Description

session_id ([ string $id ] ) : string

session_id() is used to get or set the session id for the current session.

The constant SID can also be used to retrieve the current name and session id as a string suitable for adding to URLs. See also Session handling.

Parameters

id

If id is specified, it will replace the current session id. session_id() needs to be called before session_start() for that purpose. Depending on the session handler, not all characters are allowed within the session id. For example, the file session handler only allows characters in the range a-z A-Z 0-9 , (comma) and - (minus)!

Note: When using session cookies, specifying an id for session_id() will always send a new cookie when session_start() is called, regardless if the current session id is identical to the one being set.

Return Values

session_id() returns the session id for the current session or the empty string ("") if there is no current session (no current session id exists).

See Also

  • session_regenerate_id() - Update the current session id with a newly generated one
  • session_start() - Start new or resume existing session
  • session_set_save_handler() - Sets user-level session storage functions
  • session.save_handler


Find out whether a global variable is registered in a session

  • « session_id
  • session_module_name »
  • PHP Manual
  • Session Functions
  • Find out whether a global variable is registered in a session

session_is_registered

(PHP 4, PHP 5 < 5.4.0)

session_is_registered — Find out whether a global variable is registered in a session

Description

session_is_registered ( string $name ) : bool

Finds out whether a global variable is registered in a session.

Warning

This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

Parameters

name

The variable name.

Return Values

session_is_registered() returns TRUE if there is a global variable with the name name registered in the current session, FALSE otherwise.

Notes

Note:

If $_SESSION is used, use isset() to check a variable is registered in $_SESSION.

Caution

If you are using $_SESSION
(or $HTTP_SESSION_VARS), do not use
session_register(),
session_is_registered() and
session_unregister().


Get and/or set the current session module

  • « session_is_registered
  • session_name »
  • PHP Manual
  • Session Functions
  • Get and/or set the current session module

session_module_name

(PHP 4, PHP 5, PHP 7)

session_module_name — Get and/or set the current session module

Description

session_module_name ([ string $module ] ) : string

session_module_name() gets the name of the current session module, which is also known as session.save_handler.

Parameters

module

If module is specified, that module will be used instead. Passing "user" to this parameter is forbidden. Instead session_set_save_handler() has to be called to set a user defined session handler.

Return Values

Returns the name of the current session module.

Changelog

Version | Description
7.2.0 | It is now explicitly forbidden to set the module name to "user". Formerly, this has been silently ignored.


Get and/or set the current session name

  • « session_module_name
  • session_regenerate_id »
  • PHP Manual
  • Session Functions
  • Get and/or set the current session name

session_name

(PHP 4, PHP 5, PHP 7)

session_name — Get and/or set the current session name

Description

session_name ([ string $name ] ) : string

session_name() returns the name of the current session. If name is given, session_name() will update the session name and return the old session name.

If a new session name is supplied, session_name() modifies the HTTP cookie (and output content when session.transid is enabled). Once the HTTP cookie is sent, session_name() raises error. session_name() must be called before session_start() for the session to work properly.

The session name is reset to the default value stored in session.name at request startup time. Thus, you need to call session_name() for every request (and before session_start() is called).

Parameters

name

The session name references the name of the session, which is used in cookies and URLs (e.g. PHPSESSID). It should contain only alphanumeric characters; it should be short and descriptive (i.e. for users with enabled cookie warnings). If name is specified, the name of the current session is changed to its value.

Warning

The session name can't consist of digits only, at least one letter must be present. Otherwise a new session id is generated every time.

Return Values

Returns the name of the current session. If name is given and function updates the session name, name of the old session is returned.

Examples

Example #1 session_name() example

<?php

/* set the session name to WebsiteID */

$previous_name = session_name("WebsiteID");

echo "The previous session name was $previous_name<br />";
?>

Changelog

Version | Description
7.2.0 | session_name() checks session status, previously it only checked cookie status. Therefore, older session_name() allows to call session_name() after session_start() which may crash PHP and may result in misbehaviors.

See Also

  • The session.name configuration directive


Update the current session id with a newly generated one

  • « session_name
  • session_register_shutdown »
  • PHP Manual
  • Session Functions
  • Update the current session id with a newly generated one

session_regenerate_id

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

session_regenerate_id — Update the current session id with a newly generated one

Description

session_regenerate_id ([ bool $delete_old_session = FALSE ] ) : bool

session_regenerate_id() will replace the current session id with a new one, and keep the current session information.

When session.use_trans_sid is enabled, output must be started after session_regenerate_id() call. Otherwise, old session ID is used.

Warning

Currently, session_regenerate_id does not handle an unstable network well, e.g. Mobile and WiFi network. Therefore, you may experience a lost session by calling session_regenerate_id.

You should not destroy old session data immediately, but should use destroy time-stamp and control access to old session ID. Otherwise, concurrent access to page may result in inconsistent state, or you may have lost session, or it may cause client(browser) side race condition and may create many session ID needlessly. Immediate session data deletion disables session hijack attack detection and prevention also.

Parameters

delete_old_session

Whether to delete the old associated session file or not. You should not delete old session if you need to avoid races caused by deletion or detect/avoid session hijack attacks.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.0.0 | session_regenerate_id() saves old session data before closing.
5.1.0 | Added the delete_old_session parameter.

Examples

Example #1 A session_regenerate_id() example

<?php
// NOTE: This code is not fully working code, but an example!

session_start();

// Check destroyed time-stamp
if (isset($_SESSION['destroyed'])
    && $_SESSION['destroyed'] < time() - 300) {
    // Should not happen usually. This could be attack or due to unstable network.
    // Remove all authentication status of this users session.
    remove_all_authentication_flag_from_active_sessions($_SESSION['userid']);
    throw(new DestroyedSessionAccessException);
}

$old_sessionid = session_id();

// Set destroyed timestamp
$_SESSION['destroyed'] = time(); // Since PHP 7.0.0 and up, session_regenerate_id() saves old session data

// Simply calling session_regenerate_id() may result in lost session, etc.
// See next example.
session_regenerate_id();

// New session does not need destroyed timestamp
unset($_SESSION['destroyed']);

$new_sessionid = session_id();

echo "Old Session: $old_sessionid<br />";
echo "New Session: $new_sessionid<br />";

print_r($_SESSION);
?>

Current session module does not handle unstable network well. You should manage session ID to avoid lost session by session_regenerate_id.

Example #2 Avoiding lost session by session_regenerate_id()

<?php
// NOTE: This code is not fully working code, but an example!
// my_session_start() and my_session_regenerate_id() avoid lost sessions by
// unstable network. In addition, this code may prevent exploiting stolen
// session by attackers.

function my_session_start() {
    session_start();
    if (isset($_SESSION['destroyed'])) {
       if ($_SESSION['destroyed'] < time()-300) {
           // Should not happen usually. This could be attack or due to unstable network.
           // Remove all authentication status of this users session.
           remove_all_authentication_flag_from_active_sessions($_SESSION['userid']);
           throw(new DestroyedSessionAccessException);
       }
       if (isset($_SESSION['new_session_id'])) {
           // Not fully expired yet. Could be lost cookie by unstable network.
           // Try again to set proper session ID cookie.
           // NOTE: Do not try to set session ID again if you would like to remove
           // authentication flag.
           session_commit();
           session_id($_SESSION['new_session_id']);
           // New session ID should exist
           session_start();
           return;
       }
   }
}

function my_session_regenerate_id() {
    // New session ID is required to set proper session ID
    // when session ID is not set due to unstable network.
    $new_session_id = session_create_id();
    $_SESSION['new_session_id'] = $new_session_id;

    // Set destroy timestamp
    $_SESSION['destroyed'] = time();

    // Write and close current session;
    session_commit();

    // Start session with new session ID
    session_id($new_session_id);
    ini_set('session.use_strict_mode', 0);
    session_start();
    ini_set('session.use_strict_mode', 1);

    // New session does not need them
    unset($_SESSION['destroyed']);
    unset($_SESSION['new_session_id']);
}
?>

See Also

  • session_id() - Get and/or set the current session id
  • session_create_id() - Create new session id
  • session_start() - Start new or resume existing session
  • session_destroy() - Destroys all data registered to a session
  • session_reset() - Re-initialize session array with original values
  • session_name() - Get and/or set the current session name


Session shutdown function

  • « session_regenerate_id
  • session_register »
  • PHP Manual
  • Session Functions
  • Session shutdown function

session_register_shutdown

(PHP 5 >= 5.4.0, PHP 7)

session_register_shutdown — Session shutdown function

Description

session_register_shutdown ( void ) : void

Registers session_write_close() as a shutdown function.

Parameters

This function has no parameters.

Return Values

No value is returned.

Errors/Exceptions

Emits E_WARNING if registering the shutdown function fails.


Register one or more global variables with the current session

  • « session_register_shutdown
  • session_reset »
  • PHP Manual
  • Session Functions
  • Register one or more global variables with the current session

session_register

(PHP 4, PHP 5 < 5.4.0)

session_register — Register one or more global variables with the current session

Description

session_register ( mixed $name [, mixed $... ] ) : bool

session_register() accepts a variable number of arguments, any of which can be either a string holding the name of a variable or an array consisting of variable names or other arrays. For each name, session_register() registers the global variable with that name in the current session.

You can also create a session variable by simply setting the appropriate member of the $_SESSION array.

<?php
// Use of session_register() is deprecated
$barney = "A big purple dinosaur.";
session_register("barney");

// Use of $_SESSION is preferred
$_SESSION["zim"] = "An invader from another planet.";
?>

If session_start() was not called before this function is called, an implicit call to session_start() with no parameters will be made. $_SESSION does not mimic this behavior and requires session_start() before use.

Warning

This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

Parameters

name

A string holding the name of a variable or an array consisting of variable names or other arrays.

...

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Caution

If you want your script to work regardless of register_globals, you need to instead use the $_SESSION array as $_SESSION entries are automatically registered. If your script uses session_register(), it will not work in environments where the PHP directive register_globals is disabled.

Note: register_globals: important note

As of PHP 4.2.0, the default value for the PHP directive register_globals is off. The PHP community discourages developers from relying on this directive, and encourages the use of other means, such as the superglobals.

Caution

This registers a global variable. If you want to register a session variable from within a function, you need to make sure to make it global using the global keyword or the $GLOBALS[] array, or use the special session arrays as noted below.

Caution

If you are using $_SESSION, do not use
session_register(),
session_is_registered(), and
session_unregister().

Note:

It is currently impossible to register resource variables in a session. For example, you cannot create a connection to a database and store the connection id as a session variable and expect the connection to still be valid the next time the session is restored. PHP functions that return a resource are identified by having a return type of resource in their function definition. A list of functions that return resources are available in the resource types appendix.

If $_SESSION is used, assign values to $_SESSION. For example: $_SESSION['var'] = 'ABC';

See Also

  • session_is_registered() - Find out whether a global variable is registered in a session
  • session_unregister() - Unregister a global variable from the current session
  • $_SESSION


Re-initialize session array with original values

  • « session_register
  • session_save_path »
  • PHP Manual
  • Session Functions
  • Re-initialize session array with original values

session_reset

(PHP 5 >= 5.6.0, PHP 7)

session_reset — Re-initialize session array with original values

Description

session_reset ( void ) : bool

session_reset() reinitializes a session with original values stored in session storage. This function requires an active session and discards changes in $_SESSION.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.2.0 | The return type of this function is bool now. Formerly, it has been void.

See Also

  • $_SESSION
  • The session.auto_start configuration directive
  • session_start() - Start new or resume existing session
  • session_abort() - Discard session array changes and finish session
  • session_commit() - Alias of session_write_close


Get and/or set the current session save path

  • « session_reset
  • session_set_cookie_params »
  • PHP Manual
  • Session Functions
  • Get and/or set the current session save path

session_save_path

(PHP 4, PHP 5, PHP 7)

session_save_path — Get and/or set the current session save path

Description

session_save_path ([ string $path ] ) : string

session_save_path() returns the path of the current directory used to save session data.

Parameters

path

Session data path. If specified, the path to which data is saved will be changed. session_save_path() needs to be called before session_start() for that purpose.

Note:

On some operating systems, you may want to specify a path on a filesystem that handles lots of small files efficiently. For example, on Linux, reiserfs may provide better performance than ext2fs.

Return Values

Returns the path of the current directory used for data storage.

See Also

  • The session.save_path configuration directive


Set the session cookie parameters

  • « session_save_path
  • session_set_save_handler »
  • PHP Manual
  • Session Functions
  • Set the session cookie parameters

session_set_cookie_params

(PHP 4, PHP 5, PHP 7)

session_set_cookie_params — Set the session cookie parameters

Description

session_set_cookie_params ( int $lifetime [, string $path [, string $domain [, bool $secure = FALSE [, bool $httponly = FALSE ]]]] ) : bool
session_set_cookie_params ( array $options ) : bool

Set cookie parameters defined in the php.ini file. The effect of this function only lasts for the duration of the script. Thus, you need to call session_set_cookie_params() for every request and before session_start() is called.

This function updates the runtime ini values of the corresponding PHP ini configuration keys which can be retrieved with the ini_get().

Parameters

lifetime

Lifetime of the session cookie, defined in seconds.

path

Path on the domain where the cookie will work. Use a single slash ('/') for all paths on the domain.

domain

Cookie domain, for example 'www.php.net'. To make cookies visible on all subdomains then the domain must be prefixed with a dot like '.php.net'.

secure

If TRUE cookie will only be sent over secure connections.

httponly

If set to TRUE then PHP will attempt to send the httponly flag when setting the session cookie.

options

An associative array which may have any of the keys lifetime, path, domain, secure, httponly and samesite. The values have the same meaning as described for the parameters with the same name. The value of the samesite element should be either Lax or Strict. If any of the allowed options are not given, their default values are the same as the default values of the explicit parameters. If the samesite element is omitted, no SameSite cookie attribute is set.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.3.0 | An alternative signature supporting an options array has been added. This signature supports also setting of the SameSite cookie attribute.
7.2.0 | Returns TRUE on success or FALSE on failure. Formerly the function returned void.
5.2.0 | The httponly parameter was added.

See Also

  • session.cookie_lifetime
  • session.cookie_path
  • session.cookie_domain
  • session.cookie_secure
  • session.cookie_httponly
  • session.cookie_samesite
  • session_get_cookie_params() - Get the session cookie parameters


Sets user-level session storage functions

  • « session_set_cookie_params
  • session_start »
  • PHP Manual
  • Session Functions
  • Sets user-level session storage functions

session_set_save_handler

(PHP 4, PHP 5, PHP 7)

session_set_save_handler — Sets user-level session storage functions

Description

session_set_save_handler ( callable $open , callable $close , callable $read , callable $write , callable $destroy , callable $gc [, callable $create_sid [, callable $validate_sid [, callable $update_timestamp ]]] ) : bool

Since PHP 5.4 it is possible to register the following prototype:

session_set_save_handler ( object $sessionhandler [, bool $register_shutdown = TRUE ] ) : bool

session_set_save_handler() sets the user-level session storage functions which are used for storing and retrieving data associated with a session. This is most useful when a storage method other than those supplied by PHP sessions is preferred, e.g. storing the session data in a local database.

Parameters

This function has two prototypes.

sessionhandler

An instance of a class implementing SessionHandlerInterface, SessionIdInterface, and/or SessionUpdateTimestampHandlerInterface, such as SessionHandler, to register as the session handler. Since PHP 5.4 only.

register_shutdown

Register session_write_close() as a register_shutdown_function() function.

or
open(string $savePath, string $sessionName)

The open callback works like a constructor in classes and is executed when the session is being opened. It is the first callback function executed when the session is started automatically or manually with session_start(). Return value is TRUE for success, FALSE for failure.

close()

The close callback works like a destructor in classes and is executed after the session write callback has been called. It is also invoked when session_write_close() is called. Return value should be TRUE for success, FALSE for failure.

read(string $sessionId)

The read callback must always return a session encoded (serialized) string, or an empty string if there is no data to read.

This callback is called internally by PHP when the session starts or when session_start() is called. Before this callback is invoked PHP will invoke the open callback.

The value this callback returns must be in exactly the same serialized format that was originally passed for storage to the write callback. The value returned will be unserialized automatically by PHP and used to populate the $_SESSION superglobal. While the data looks similar to serialize() please note it is a different format which is specified in the session.serialize_handler ini setting.

write(string $sessionId, string $data)

The write callback is called when the session needs to be saved and closed. This callback receives the current session ID a serialized version the $_SESSION superglobal. The serialization method used internally by PHP is specified in the session.serialize_handler ini setting.

The serialized session data passed to this callback should be stored against the passed session ID. When retrieving this data, the read callback must return the exact value that was originally passed to the write callback.

This callback is invoked when PHP shuts down or explicitly when session_write_close() is called. Note that after executing this function PHP will internally execute the close callback.

Note:

The "write" handler is not executed until after the output stream is closed. Thus, output from debugging statements in the "write" handler will never be seen in the browser. If debugging output is necessary, it is suggested that the debug output be written to a file instead.

destroy($sessionId)

This callback is executed when a session is destroyed with session_destroy() or with session_regenerate_id() with the destroy parameter set to TRUE. Return value should be TRUE for success, FALSE for failure.

gc($lifetime)

The garbage collector callback is invoked internally by PHP periodically in order to purge old session data. The frequency is controlled by session.gc_probability and session.gc_divisor. The value of lifetime which is passed to this callback can be set in session.gc_maxlifetime. Return value should be TRUE for success, FALSE for failure.

create_sid()

This callback is executed when a new session ID is required. No parameters are provided, and the return value should be a string that is a valid session ID for your handler.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.0.0 | Added the optional validate_sid and update_timestamp parameters.
5.5.1 | Added the optional create_sid parameter.
5.4.0 | Added SessionHandlerInterface for implementing session handlers and SessionHandler to expose internal PHP session handlers.

Examples

Example #1 Custom session handler: see full code in SessionHandlerInterface synopsis.

The following code is for PHP version 5.4.0 and above. We just show the invocation here, the full example can be seen in the SessionHandlerInterface synopsis linked above.

Note we use the OOP prototype with session_set_save_handler() and register the shutdown function using the function's parameter flag. This is generally advised when registering objects as session save handlers.

<?php
class MySessionHandler implements SessionHandlerInterface
{
    // implement interfaces here
}

$handler = new MySessionHandler();
session_set_save_handler($handler, true);
session_start();

// proceed to set and retrieve values by key from $_SESSION

Example #2 Custom session save handler using objects

The following code is for PHP versions less than 5.4.0.

The following example provides file based session storage similar to the PHP sessions default save handler files. This example could easily be extended to cover database storage using your favorite PHP supported database engine.

Note we additionally register the shutdown function session_write_close() using register_shutdown_function() under PHP less than 5.4.0. This is generally advised when registering objects as session save handlers under PHP less than 5.4.0.

<?php
class FileSessionHandler
{
    private $savePath;

    function open($savePath, $sessionName)
    {
        $this->savePath = $savePath;
        if (!is_dir($this->savePath)) {
            mkdir($this->savePath, 0777);
        }

        return true;
    }

    function close()
    {
        return true;
    }

    function read($id)
    {
        return (string)@file_get_contents("$this->savePath/sess_$id");
    }

    function write($id, $data)
    {
        return file_put_contents("$this->savePath/sess_$id", $data) === false ? false : true;
    }

    function destroy($id)
    {
        $file = "$this->savePath/sess_$id";
        if (file_exists($file)) {
            unlink($file);
        }

        return true;
    }

    function gc($maxlifetime)
    {
        foreach (glob("$this->savePath/sess_*") as $file) {
            if (filemtime($file) + $maxlifetime < time() && file_exists($file)) {
                unlink($file);
            }
        }

        return true;
    }
}

$handler = new FileSessionHandler();
session_set_save_handler(
    array($handler, 'open'),
    array($handler, 'close'),
    array($handler, 'read'),
    array($handler, 'write'),
    array($handler, 'destroy'),
    array($handler, 'gc')
    );

// the following prevents unexpected effects when using objects as save handlers
register_shutdown_function('session_write_close');

session_start();
// proceed to set and retrieve values by key from $_SESSION

Notes

Warning

When using objects as session save handlers, it is important to register the shutdown function with PHP to avoid unexpected side-effects from the way PHP internally destroys objects on shutdown and may prevent the write and close from being called. Typically you should register 'session_write_close' using the register_shutdown_function() function.

As of PHP 5.4.0 you can use session_register_shutdown() or simply use the 'register shutdown' flag when invoking session_set_save_handler() using the OOP method and passing an instance that implements SessionHandlerInterface.

Warning

As of PHP 5.0.5 the write and close handlers are called after object destruction and therefore cannot use objects or throw exceptions. Exceptions are not able to be caught since will not be caught nor will any exception trace be displayed and the execution will just cease unexpectedly. The object destructors can however use sessions.

It is possible to call session_write_close() from the destructor to solve this chicken and egg problem but the most reliable way is to register the shutdown function as described above.

Warning

Current working directory is changed with some SAPIs if session is closed in the script termination. It is possible to close the session earlier with session_write_close().

See Also

  • The session.save_handler configuration directive
  • The session.serialize_handler configuration directive.
  • The register_shutdown_function() - Register a function for execution on shutdown
  • The session_register_shutdown() - Session shutdown function for PHP 5.4.0+
  • Refer to » save_handler.inc for a full procedural reference implementation


Start new or resume existing session

  • « session_set_save_handler
  • session_status »
  • PHP Manual
  • Session Functions
  • Start new or resume existing session

session_start

(PHP 4, PHP 5, PHP 7)

session_start — Start new or resume existing session

Description

session_start ([ array $options = array() ] ) : bool

session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.

When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers. These will either be a built-in save handler provided by default or by PHP extensions (such as SQLite or Memcached); or can be custom handler as defined by session_set_save_handler(). The read callback will retrieve any existing session data (stored in a special serialized format) and will be unserialized and used to automatically populate the $_SESSION superglobal when the read callback returns the saved session data back to PHP session handling.

To use a named session, call session_name() before calling session_start().

When session.use_trans_sid is enabled, the session_start() function will register an internal output handler for URL rewriting.

If a user uses ob_gzhandler or similar with ob_start(), the function order is important for proper output. For example, ob_gzhandler must be registered before starting the session.

Parameters

options

If provided, this is an associative array of options that will override the currently set session configuration directives. The keys should not include the session. prefix.

In addition to the normal set of configuration directives, a read_and_close option may also be provided. If set to TRUE, this will result in the session being closed immediately after being read, thereby avoiding unnecessary locking if the session data won't be changed.

Return Values

This function returns TRUE if a session was successfully started, otherwise FALSE.

Changelog

Version | Description
7.1.0 | session_start() now returns FALSE and no longer initializes $_SESSION when it failed to start the session.
7.0.0 | The options parameter was added.
5.3.0 | If a session fails to start, then FALSE is returned. Previously TRUE was returned.

Examples

A basic session example

Example #1 page1.php

<?php
// page1.php

session_start();

echo 'Welcome to page #1';

$_SESSION['favcolor'] = 'green';
$_SESSION['animal']   = 'cat';
$_SESSION['time']     = time();

// Works if session cookie was accepted
echo '<br /><a href="page2.php">page 2</a>';

// Or maybe pass along the session id, if needed
echo '<br /><a href="page2.php?' . SID . '">page 2</a>';
?>

After viewing page1.php, the second page page2.php will magically contain the session data. Read the session reference for information on propagating session ids as it, for example, explains what the constant SID is all about.

Example #2 page2.php

<?php
// page2.php

session_start();

echo 'Welcome to page #2<br />';

echo $_SESSION['favcolor']; // green
echo $_SESSION['animal'];   // cat
echo date('Y m d H:i:s', $_SESSION['time']);

// You may want to use SID here, like we did in page1.php
echo '<br /><a href="page1.php">page 1</a>';
?>

Providing options to session_start()

Example #3 Overriding the cookie lifetime

<?php
// This sends a persistent cookie that lasts a day.
session_start([
    'cookie_lifetime' => 86400,
]);
?>

Example #4 Reading the session and closing it

<?php
// If we know we don't need to change anything in the
// session, we can just read and close rightaway to avoid
// locking the session file and blocking other pages
session_start([
    'cookie_lifetime' => 86400,
    'read_and_close'  => true,
]);

Notes

Note:

To use cookie-based sessions, session_start() must be called before outputing anything to the browser.

Note:

Use of zlib.output_compression is recommended instead of ob_gzhandler()

Note:

This function sends out several HTTP headers depending on the configuration. See session_cache_limiter() to customize these headers.

See Also

  • $_SESSION
  • The session.auto_start configuration directive
  • session_id() - Get and/or set the current session id


Returns the current session status

  • « session_start
  • session_unregister »
  • PHP Manual
  • Session Functions
  • Returns the current session status

session_status

(PHP 5 >= 5.4.0, PHP 7)

session_status — Returns the current session status

Description

session_status ( void ) : int

session_status() is used to return the current session status.

Return Values

  • PHP_SESSION_DISABLED if sessions are disabled.
  • PHP_SESSION_NONE if sessions are enabled, but none exists.
  • PHP_SESSION_ACTIVE if sessions are enabled, and one exists.

See Also

  • session_start() - Start new or resume existing session


Unregister a global variable from the current session

  • « session_status
  • session_unset »
  • PHP Manual
  • Session Functions
  • Unregister a global variable from the current session

session_unregister

(PHP 4, PHP 5 < 5.4.0)

session_unregister — Unregister a global variable from the current session

Description

session_unregister ( string $name ) : bool

session_unregister() unregisters the global variable named name from the current session.

Warning

This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

Parameters

name

The variable name.

Return Values

Returns TRUE on success or FALSE on failure.

Notes

Note:

If $_SESSION is used, use unset() to unregister a session variable. Do not unset() $_SESSION itself as this will disable the special function of the $_SESSION superglobal.

Caution

This function does not unset the corresponding global variable for name, it only prevents the variable from being saved as part of the session. You must call unset() to remove the corresponding global variable.

Caution

If you are using $_SESSION (or
$HTTP_SESSION_VARS), do not use
session_register(),
session_is_registered() and
session_unregister().


Free all session variables

  • « session_unregister
  • session_write_close »
  • PHP Manual
  • Session Functions
  • Free all session variables

session_unset

(PHP 4, PHP 5, PHP 7)

session_unset — Free all session variables

Description

session_unset ( void ) : bool

The session_unset() function frees all session variables currently registered.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.2.0 | The return type of this function is bool now. Formerly, it has been void.

Notes

Note:

If $_SESSION is used, use unset() to unregister a session variable, i.e. unset ($_SESSION['varname']);.

Caution

Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal.

Note:

Only use session_unset() for older deprecated code that does not use $_SESSION.


Write session data and end session

  • « session_unset
  • SessionHandler »
  • PHP Manual
  • Session Functions
  • Write session data and end session

session_write_close

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

session_write_close — Write session data and end session

Description

session_write_close ( void ) : bool

End the current session and store session data.

Session data is usually stored after your script terminated without the need to call session_write_close(), but as session data is locked to prevent concurrent writes only one script may operate on a session at any time. When using framesets together with sessions you will experience the frames loading one by one due to this locking. You can reduce the time needed to load all the frames by ending the session as soon as all changes to session variables are done.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.2.0 | The return type of this function is bool now. Formerly, it has been void.

See Also

  • The session_register_shutdown() - Session shutdown function


The SessionHandler class

(PHP 5 >= 5.4.0, PHP 7)

Introduction

SessionHandler is a special class that can be used to expose the current internal PHP session save handler by inheritance. There are seven methods which wrap the seven internal session save handler callbacks (open, close, read, write, destroy, gc and create_sid). By default, this class will wrap whatever internal save handler is set as defined by the session.save_handler configuration directive which is usually files by default. Other internal session save handlers are provided by PHP extensions such as SQLite (as sqlite), Memcache (as memcache), and Memcached (as memcached).

When a plain instance of SessionHandler is set as the save handler using session_set_save_handler() it will wrap the current save handlers. A class extending from SessionHandler allows you to override the methods or intercept or filter them by calls the parent class methods which ultimately wrap the internal PHP session handlers.

This allows you, for example, to intercept the read and write methods to encrypt/decrypt the session data and then pass the result to and from the parent class. Alternatively one might chose to entirely override a method like the garbage collection callback gc.

Because the SessionHandler wraps the current internal save handler methods, the above example of encryption can be applied to any internal save handler without having to know the internals of the handlers.

To use this class, first set the save handler you wish to expose using session.save_handler and then pass an instance of SessionHandler or one extending it to session_set_save_handler().

Please note the callback methods of this class are designed to be called internally by PHP and are not meant to be called from user-space code. The return values are equally processed internally by PHP. For more information on the session workflow, please refer session_set_save_handler().

Class synopsis

SessionHandler implements SessionHandlerInterface , SessionIdInterface {
/* Methods */
public close ( void ) : bool
public create_sid ( void ) : string
public destroy ( string $session_id ) : bool
public gc ( int $maxlifetime ) : int
public open ( string $save_path , string $session_name ) : bool
public read ( string $session_id ) : string
public write ( string $session_id , string $session_data ) : bool
}
Warning

This class is designed to expose the current internal PHP session save handler, if you want to write your own custom save handlers, please implement the SessionHandlerInterface interface instead of extending from SessionHandler.

Changelog

Version | Description
5.5.1 | Added SessionHandler::create_sid().

Example #1 Using SessionHandler to add encryption to internal PHP save handlers.

<?php

 /**
  * decrypt AES 256
  *
  * @param data $edata
  * @param string $password
  * @return decrypted data
  */
function decrypt($edata, $password) {
    $data = base64_decode($edata);
    $salt = substr($data, 0, 16);
    $ct = substr($data, 16);

    $rounds = 3; // depends on key length
    $data00 = $password.$salt;
    $hash = array();
    $hash[0] = hash('sha256', $data00, true);
    $result = $hash[0];
    for ($i = 1; $i < $rounds; $i++) {
        $hash[$i] = hash('sha256', $hash[$i - 1].$data00, true);
        $result .= $hash[$i];
    }
    $key = substr($result, 0, 32);
    $iv  = substr($result, 32,16);

    return openssl_decrypt($ct, 'AES-256-CBC', $key, true, $iv);
  }

/**
 * crypt AES 256
 *
 * @param data $data
 * @param string $password
 * @return base64 encrypted data
 */
function encrypt($data, $password) {
    // Set a random salt
    $salt = openssl_random_pseudo_bytes(16);

    $salted = '';
    $dx = '';
    // Salt the key(32) and iv(16) = 48
    while (strlen($salted) < 48) {
      $dx = hash('sha256', $dx.$password.$salt, true);
      $salted .= $dx;
    }

    $key = substr($salted, 0, 32);
    $iv  = substr($salted, 32,16);

    $encrypted_data = openssl_encrypt($data, 'AES-256-CBC', $key, true, $iv);
    return base64_encode($salt . $encrypted_data);
}

class EncryptedSessionHandler extends SessionHandler
{
    private $key;

    public function __construct($key)
    {
        $this->key = $key;
    }

    public function read($id)
    {
        $data = parent::read($id);

        if (!$data) {
            return "";
        } else {
            return decrypt($data, $this->key);
        }
    }

    public function write($id, $data)
    {
        $data = encrypt($data, $this->key);

        return parent::write($id, $data);
    }
}

// we'll intercept the native 'files' handler, but will equally work
// with other internal native handlers like 'sqlite', 'memcache' or 'memcached'
// which are provided by PHP extensions.
ini_set('session.save_handler', 'files');

$key = 'secret_string';
$handler = new EncryptedSessionHandler($key);
session_set_save_handler($handler, true);
session_start();

// proceed to set and retrieve values by key from $_SESSION

Note:

Since this class' methods are designed to be called internally by PHP as part of the normal session workflow, child class calls to parent methods (i.e. the actual internal native handlers) will return FALSE unless the session has actually been started (either automatically, or by explicit session_start(). This is important to consider when writing unit tests where the class methods might be invoked manually.

Table of Contents

  • SessionHandler::close — Close the session
  • SessionHandler::create_sid — Return a new session ID
  • SessionHandler::destroy — Destroy a session
  • SessionHandler::gc — Cleanup old sessions
  • SessionHandler::open — Initialize session
  • SessionHandler::read — Read session data
  • SessionHandler::write — Write session data


Close the session

  • « SessionHandler
  • SessionHandler::create_sid »
  • PHP Manual
  • SessionHandler
  • Close the session

SessionHandler::close

(PHP 5 >= 5.4.0, PHP 7)

SessionHandler::close — Close the session

Description

public SessionHandler::close ( void ) : bool

Closes the current session. This method is automatically executed internally by PHP when closing the session, or explicitly via session_write_close() (which first calls the SessionHandler::write()).

This method wraps the internal PHP save handler defined in the session.save_handler ini setting that was set before this handler was activated by session_set_save_handler().

If this class is extended by inheritiance, calling the parent close method will invoke the wrapper for this method and therefor invoke the associated internal callback. This allows the method to be overidden and or intercepted.

For more information on what this method is expected to do, please refer to the documentation at SessionHandlerInterface::close().

Parameters

This function has no parameters.

Return Values

The return value (usually TRUE on success, FALSE on failure). Note this value is returned internally to PHP for processing.


Return a new session ID

  • « SessionHandler::close
  • SessionHandler::destroy »
  • PHP Manual
  • SessionHandler
  • Return a new session ID

SessionHandler::create_sid

(PHP 5 >= 5.5.1, PHP 7)

SessionHandler::create_sid — Return a new session ID

Description

public SessionHandler::create_sid ( void ) : string

Generates and returns a new session ID.

Return Values

A session ID valid for the default session handler.

See Also

  • session_id() - Get and/or set the current session id
  • session_create_id() - Create new session id


Destroy a session

  • « SessionHandler::create_sid
  • SessionHandler::gc »
  • PHP Manual
  • SessionHandler
  • Destroy a session

SessionHandler::destroy

(PHP 5 >= 5.4.0, PHP 7)

SessionHandler::destroy — Destroy a session

Description

public SessionHandler::destroy ( string $session_id ) : bool

Destroys a session. Called internally by PHP with session_regenerate_id() (assuming the $destroy is set to TRUE, by session_destroy() or when session_decode() fails.

This method wraps the internal PHP save handler defined in the session.save_handler ini setting that was set before this handler was set by session_set_save_handler().

If this class is extended by inheritiance, calling the parent destroy method will invoke the wrapper for this method and therefor invoke the associated internal callback. This allows this method to be overidden and or intercepted and filtered.

For more information on what this method is expected to do, please refer to the documentation at SessionHandlerInterface::destroy().

Parameters

session_id

The session ID being destroyed.

Return Values

The return value (usually TRUE on success, FALSE on failure). Note this value is returned internally to PHP for processing.


Cleanup old sessions

  • « SessionHandler::destroy
  • SessionHandler::open »
  • PHP Manual
  • SessionHandler
  • Cleanup old sessions

SessionHandler::gc

(PHP 5 >= 5.4.0, PHP 7)

SessionHandler::gc — Cleanup old sessions

Description

public SessionHandler::gc ( int $maxlifetime ) : int

Cleans up expired sessions. Called randomly by PHP internally when a session starts or when session_start() is invoked. The frequency this is called is based on the session.gc_divisor and session.gc_probability configuration directives.

This method wraps the internal PHP save handler defined in the session.save_handler ini setting that was set before this handler was set by session_set_save_handler().

If this class is extended by inheritiance, calling the parent gc method will invoke the wrapper for this method and therefore invoke the associated internal callback. This allows this method to be overidden and or intercepted and filtered.

For more information on what this method is expected to do, please refer to the documentation at SessionHandlerInterface::gc().

Parameters

maxlifetime

Sessions that have not updated for the last maxlifetime seconds will be removed.

Return Values

The return value (usually TRUE on success, FALSE on failure). Note this value is returned internally to PHP for processing.


Initialize session

  • « SessionHandler::gc
  • SessionHandler::read »
  • PHP Manual
  • SessionHandler
  • Initialize session

SessionHandler::open

(PHP 5 >= 5.4.0, PHP 7)

SessionHandler::open — Initialize session

Description

public SessionHandler::open ( string $save_path , string $session_name ) : bool

Create new session, or re-initialize existing session. Called internally by PHP when a session starts either automatically or when session_start() is invoked.

This method wraps the internal PHP save handler defined in the session.save_handler ini setting that was set before this handler was set by session_set_save_handler().

If this class is extended by inheritiance, calling the parent open method will invoke the wrapper for this method and therefor invoke the associated internal callback. This allows this method to be overidden and or intercepted and filtered.

For more information on what this method is expected to do, please refer to the documentation at SessionHandlerInterface::open().

Parameters

save_path

The path where to store/retrieve the session.

session_name

The session name.

Return Values

The return value (usually TRUE on success, FALSE on failure). Note this value is returned internally to PHP for processing.

See Also

  • The session.auto-start configuration directive.


Read session data

  • « SessionHandler::open
  • SessionHandler::write »
  • PHP Manual
  • SessionHandler
  • Read session data

SessionHandler::read

(PHP 5 >= 5.4.0, PHP 7)

SessionHandler::read — Read session data

Description

public SessionHandler::read ( string $session_id ) : string

Reads the session data from the session storage, and returns the result back to PHP for internal processing. This method is called automatically by PHP when a session is started (either automatically or explicity with session_start() and is preceeded by an internal call to the SessionHandler::open().

This method wraps the internal PHP save handler defined in the session.save_handler ini setting that was set before this handler was set by session_set_save_handler().

If this class is extended by inheritance, calling the parent read method will invoke the wrapper for this method and therefor invoke the associated internal callback. This allows the method to be overidden and or intercepted and filtered (for example, decrypting $data value returned by the parent read method).

For more information on what this method is expected to do, please refer to the documentation at SessionHandlerInterface::read().

Parameters

session_id

The session id to read data for.

Return Values

Returns an encoded string of the read data. If nothing was read, it must return an empty string. Note this value is returned internally to PHP for processing.

See Also

  • The session.serialize_handler configuration directive.


Write session data

  • « SessionHandler::read
  • SessionHandlerInterface »
  • PHP Manual
  • SessionHandler
  • Write session data

SessionHandler::write

(PHP 5 >= 5.4.0, PHP 7)

SessionHandler::write — Write session data

Description

public SessionHandler::write ( string $session_id , string $session_data ) : bool

Writes the session data to the session storage. Called by normal PHP shutdown, by session_write_close(), or when session_register_shutdown() fails. PHP will call SessionHandler::close() immediately after this method returns.

This method wraps the internal PHP save handler defined in the session.save_handler ini setting that was set before this handler was set by session_set_save_handler().

If this class is extended by inheritiance, calling the parent write method will invoke the wrapper for this method and therefor invoke the associated internal callback. This allows this method to be overidden and or intercepted and filtered (for example, encrypting the $data value before sending it to the parent write method).

For more information on what this method is expected to do, please refer to the documentation at SessionHandlerInterface::write().

Parameters

session_id

The session id.

session_data

The encoded session data. This data is the result of the PHP internally encoding the $_SESSION superglobal to a serialized string and passing it as this parameter. Please note sessions use an alternative serialization method.

Return Values

The return value (usually TRUE on success, FALSE on failure). Note this value is returned internally to PHP for processing.

See Also

  • The session.serialize_handler configuration directive.


The SessionHandlerInterface class

(PHP 5 >= 5.4.0, PHP 7)

Introduction

SessionHandlerInterface is an interface which defines a prototype for creating a custom session handler. In order to pass a custom session handler to session_set_save_handler() using its OOP invocation, the class must implement this interface.

Please note the callback methods of this class are designed to be called internally by PHP and are not meant to be called from user-space code.

Class synopsis

SessionHandlerInterface {
/* Methods */
abstract public close ( void ) : bool
abstract public destroy ( string $session_id ) : bool
abstract public gc ( int $maxlifetime ) : int
abstract public open ( string $save_path , string $session_name ) : bool
abstract public read ( string $session_id ) : string
abstract public write ( string $session_id , string $session_data ) : bool
}

Example #1 Example using SessionHandlerInterface

The following example provides file based session storage similar to the PHP sessions default save handler files. This example could easily be extended to cover database storage using your favorite PHP supported database engine.

Note we use the OOP prototype with session_set_save_handler() and register the shutdown function using the function's parameter flag. This is generally advised when registering objects as session save handlers.

Caution

For brevity, this example omits input validation. However, the $id parameters are actually user supplied values which require proper validation/sanitization to avoid vulnerabilities, such as path traversal issues. So do not use this example unmodified in production environments.

<?php
class MySessionHandler implements SessionHandlerInterface
{
    private $savePath;

    public function open($savePath, $sessionName)
    {
        $this->savePath = $savePath;
        if (!is_dir($this->savePath)) {
            mkdir($this->savePath, 0777);
        }

        return true;
    }

    public function close()
    {
        return true;
    }

    public function read($id)
    {
        return (string)@file_get_contents("$this->savePath/sess_$id");
    }

    public function write($id, $data)
    {
        return file_put_contents("$this->savePath/sess_$id", $data) === false ? false : true;
    }

    public function destroy($id)
    {
        $file = "$this->savePath/sess_$id";
        if (file_exists($file)) {
            unlink($file);
        }

        return true;
    }

    public function gc($maxlifetime)
    {
        foreach (glob("$this->savePath/sess_*") as $file) {
            if (filemtime($file) + $maxlifetime < time() && file_exists($file)) {
                unlink($file);
            }
        }

        return true;
    }
}

$handler = new MySessionHandler();
session_set_save_handler($handler, true);
session_start();

// proceed to set and retrieve values by key from $_SESSION

Table of Contents

  • SessionHandlerInterface::close — Close the session
  • SessionHandlerInterface::destroy — Destroy a session
  • SessionHandlerInterface::gc — Cleanup old sessions
  • SessionHandlerInterface::open — Initialize session
  • SessionHandlerInterface::read — Read session data
  • SessionHandlerInterface::write — Write session data


Close the session

  • « SessionHandlerInterface
  • SessionHandlerInterface::destroy »
  • PHP Manual
  • SessionHandlerInterface
  • Close the session

SessionHandlerInterface::close

(PHP 5 >= 5.4.0, PHP 7)

SessionHandlerInterface::close — Close the session

Description

abstract public SessionHandlerInterface::close ( void ) : bool

Closes the current session. This function is automatically executed when closing the session, or explicitly via session_write_close().

Parameters

This function has no parameters.

Return Values

The return value (usually TRUE on success, FALSE on failure). Note this value is returned internally to PHP for processing.


Destroy a session

  • « SessionHandlerInterface::close
  • SessionHandlerInterface::gc »
  • PHP Manual
  • SessionHandlerInterface
  • Destroy a session

SessionHandlerInterface::destroy

(PHP 5 >= 5.4.0, PHP 7)

SessionHandlerInterface::destroy — Destroy a session

Description

abstract public SessionHandlerInterface::destroy ( string $session_id ) : bool

Destroys a session. Called by session_regenerate_id() (with $destroy = TRUE), session_destroy() and when session_decode() fails.

Parameters

session_id

The session ID being destroyed.

Return Values

The return value (usually TRUE on success, FALSE on failure). Note this value is returned internally to PHP for processing.


Cleanup old sessions

  • « SessionHandlerInterface::destroy
  • SessionHandlerInterface::open »
  • PHP Manual
  • SessionHandlerInterface
  • Cleanup old sessions

SessionHandlerInterface::gc

(PHP 5 >= 5.4.0, PHP 7)

SessionHandlerInterface::gc — Cleanup old sessions

Description

abstract public SessionHandlerInterface::gc ( int $maxlifetime ) : int

Cleans up expired sessions. Called by session_start(), based on session.gc_divisor, session.gc_probability and session.gc_maxlifetime settings.

Parameters

maxlifetime

Sessions that have not updated for the last maxlifetime seconds will be removed.

Return Values

The return value (usually TRUE on success, FALSE on failure). Note this value is returned internally to PHP for processing.


Initialize session

  • « SessionHandlerInterface::gc
  • SessionHandlerInterface::read »
  • PHP Manual
  • SessionHandlerInterface
  • Initialize session

SessionHandlerInterface::open

(PHP 5 >= 5.4.0, PHP 7)

SessionHandlerInterface::open — Initialize session

Description

abstract public SessionHandlerInterface::open ( string $save_path , string $session_name ) : bool

Re-initialize existing session, or creates a new one. Called when a session starts or when session_start() is invoked.

Parameters

save_path

The path where to store/retrieve the session.

session_name

The session name.

Return Values

The return value (usually TRUE on success, FALSE on failure). Note this value is returned internally to PHP for processing.

See Also

  • session_name() - Get and/or set the current session name
  • The session.auto-start configuration directive.


Read session data

  • « SessionHandlerInterface::open
  • SessionHandlerInterface::write »
  • PHP Manual
  • SessionHandlerInterface
  • Read session data

SessionHandlerInterface::read

(PHP 5 >= 5.4.0, PHP 7)

SessionHandlerInterface::read — Read session data

Description

abstract public SessionHandlerInterface::read ( string $session_id ) : string

Reads the session data from the session storage, and returns the results. Called right after the session starts or when session_start() is called. Please note that before this method is called SessionHandlerInterface::open() is invoked.

This method is called by PHP itself when the session is started. This method should retrieve the session data from storage by the session ID provided. The string returned by this method must be in the same serialized format as when originally passed to the SessionHandlerInterface::write() If the record was not found, return an empty string.

The data returned by this method will be decoded internally by PHP using the unserialization method specified in session.serialize_handler. The resulting data will be used to populate the $_SESSION superglobal.

Note that the serialization scheme is not the same as unserialize() and can be accessed by session_decode().

Parameters

session_id

The session id.

Return Values

Returns an encoded string of the read data. If nothing was read, it must return an empty string. Note this value is returned internally to PHP for processing.

See Also

  • The session.serialize_handler configuration directive.


Write session data

  • « SessionHandlerInterface::read
  • SessionIdInterface »
  • PHP Manual
  • SessionHandlerInterface
  • Write session data

SessionHandlerInterface::write

(PHP 5 >= 5.4.0, PHP 7)

SessionHandlerInterface::write — Write session data

Description

abstract public SessionHandlerInterface::write ( string $session_id , string $session_data ) : bool

Writes the session data to the session storage. Called by session_write_close(), when session_register_shutdown() fails, or during a normal shutdown. Note: SessionHandlerInterface::close() is called immediately after this function.

PHP will call this method when the session is ready to be saved and closed. It encodes the session data from the $_SESSION superglobal to a serialized string and passes this along with the session ID to this method for storage. The serialization method used is specified in the session.serialize_handler setting.

Note this method is normally called by PHP after the output buffers have been closed unless explicitly called by session_write_close()

Parameters

session_id

The session id.

session_data

The encoded session data. This data is the result of the PHP internally encoding the $_SESSION superglobal to a serialized string and passing it as this parameter. Please note sessions use an alternative serialization method.

Return Values

The return value (usually TRUE on success, FALSE on failure). Note this value is returned internally to PHP for processing.

See Also

  • The session.serialize_handler configuration directive.


The SessionIdInterface interface

(PHP 5 >= 5.5.1, PHP 7)

Introduction

Class synopsis

SessionIdInterface {
/* Methods */
abstract public create_sid ( void ) : string
}

Table of Contents

  • SessionIdInterface::create_sid — Create session ID


Create session ID

  • « SessionIdInterface
  • SessionUpdateTimestampHandlerInterface »
  • PHP Manual
  • SessionIdInterface
  • Create session ID

SessionIdInterface::create_sid

(PHP 5 >= 5.5.1, PHP 7)

SessionIdInterface::create_sid — Create session ID

Description

abstract public SessionIdInterface::create_sid ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

See Also

  • SessionHandler::create_sid() - Return a new session ID


The SessionUpdateTimestampHandlerInterface interface

(PHP 7)

Introduction

Class synopsis

SessionUpdateTimestampHandlerInterface {
/* Methods */
abstract public updateTimestamp ( string $key , string $val ) : bool
abstract public validateId ( string $key ) : bool
}

Table of Contents

  • SessionUpdateTimestampHandlerInterface::updateTimestamp — Update timestamp
  • SessionUpdateTimestampHandlerInterface::validateId — Validate ID


Update timestamp

  • « SessionUpdateTimestampHandlerInterface
  • SessionUpdateTimestampHandlerInterface::validateId »
  • PHP Manual
  • SessionUpdateTimestampHandlerInterface
  • Update timestamp

SessionUpdateTimestampHandlerInterface::updateTimestamp

(PHP 7)

SessionUpdateTimestampHandlerInterface::updateTimestamp — Update timestamp

Description

abstract public SessionUpdateTimestampHandlerInterface::updateTimestamp ( string $key , string $val ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

key

val

Return Values

Returns TRUE if the timestamp was updated, FALSE otherwise.


Validate ID

  • « SessionUpdateTimestampHandlerInterface::updateTimestamp
  • Session PgSQL »
  • PHP Manual
  • SessionUpdateTimestampHandlerInterface
  • Validate ID

SessionUpdateTimestampHandlerInterface::validateId

(PHP 7)

SessionUpdateTimestampHandlerInterface::validateId — Validate ID

Description

abstract public SessionUpdateTimestampHandlerInterface::validateId ( string $key ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

key

Return Values

Returns TRUE for valid ID, FALSE otherwise.


PostgreSQL Session Save Handler

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Table definitions
  • Predefined Constants
  • Session PgSQL Functions
    • session_pgsql_add_error — Increments error counts and sets last error message
    • session_pgsql_get_error — Returns number of errors and last error message
    • session_pgsql_get_field — Get custom field value
    • session_pgsql_reset — Reset connection to session database servers
    • session_pgsql_set_field — Set custom field value
    • session_pgsql_status — Get current save handler status


Introduction

Note: This extension is not available on Windows platforms.

This module provides an additional session save handler for the session module using » PostgreSQL as a storage system. A user-level session storage function may also be used - session_set_save_handler(), but this module is written in C and therefore could be twice as fast, compared to a session save handler written in PHP.

Session PgSQL is designed to scale any size of web sites and offers some advanced features:

  • session tables are created automatically
  • automatic session table vacuum
  • better garbage collection
  • multiple PostgreSQL servers support
  • automatic database server failover (switching)
  • automatic database server load balancing if there are multiple PostgreSQL servers.
  • short circuit UPDATE


Requirements

You need at least PHP >= 4.3.0, and PostgreSQL >=7.2.0 as database server. libpq that comes with PostgreSQL 7.2.0 or later (and header files to build) and » libmm (and header files).


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/session_pgsql.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

PostgreSQL session save handler is still under development. Refer to the README file in the source distribution for configuration details.


  • « Runtime Configuration
  • Table definitions »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

This extension has no resource types defined.


Table definitions

Session table definition

CREATE TABLE php_session (
 sess_id            text,
 sess_name          text,
 sess_data          text,
 sess_created       integer,
 sess_modified      integer,
 sess_expire        integer,
 sess_addr_created  text,
 sess_addr_modified text,
 sess_counter       integer,
 sess_error         integer,
 sess_warning       integer,
 sess_notice        integer,
 sess_err_message   text,
 sess_custom        text
);

CREATE INDEX php_session_idx ON php_session USING BTREE (sess_id);

Warning

If you use HASH for INDEX, you'll have a deadlock problem when the server load is very high. Even if it's unlikely to have a deadlock under normal operation, it can occur. Do not use HASH for INDEX.

You may change the session table as long as all fields are defined.

Application variables table definition

CREATE TABLE php_app_vars (
 app_modified       integer,
 app_name           text,
 app_vars           text
);


  • « Table definitions
  • Session PgSQL Functions »
  • PHP Manual
  • Session PgSQL
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


Session PgSQL Functions

Contact Information

I have at the moment not very much time to further develop this extension. I will implement more and more features in the near future.

If you have comments, bug fixes, enhancements or want to help developing this, you can drop me a mail at » yohgaki@php.net. Any help is very welcome.

Table of Contents

  • session_pgsql_add_error — Increments error counts and sets last error message
  • session_pgsql_get_error — Returns number of errors and last error message
  • session_pgsql_get_field — Get custom field value
  • session_pgsql_reset — Reset connection to session database servers
  • session_pgsql_set_field — Set custom field value
  • session_pgsql_status — Get current save handler status


Increments error counts and sets last error message

  • « Session PgSQL Functions
  • session_pgsql_get_error »
  • PHP Manual
  • Session PgSQL Functions
  • Increments error counts and sets last error message

session_pgsql_add_error

(PECL session_pgsql SVN)

session_pgsql_add_error — Increments error counts and sets last error message

Description

session_pgsql_add_error ( int $error_level [, string $error_message ] ) : bool
Warning

This function is currently not documented; only its argument list is available.

Parameters

error_level

error_message

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • session_pgsql_get_error() - Returns number of errors and last error message


Returns number of errors and last error message

  • « session_pgsql_add_error
  • session_pgsql_get_field »
  • PHP Manual
  • Session PgSQL Functions
  • Returns number of errors and last error message

session_pgsql_get_error

(PECL session_pgsql SVN)

session_pgsql_get_error — Returns number of errors and last error message

Description

session_pgsql_get_error ([ bool $with_error_message = FALSE ] ) : array

Get the number of errors and optional the error messages.

Parameters

with_error_message

Set to TRUE the literal error message for each error is also returned.

Return Values

The number of errors are returned as array.

See Also

  • session_pgsql_add_error() - Increments error counts and sets last error message


Get custom field value

  • « session_pgsql_get_error
  • session_pgsql_reset »
  • PHP Manual
  • Session PgSQL Functions
  • Get custom field value

session_pgsql_get_field

(PECL session_pgsql SVN)

session_pgsql_get_field — Get custom field value

Description

session_pgsql_get_field ( void ) : string
Warning

This function is currently not documented; only its argument list is available.

See Also

  • session_pgsql_set_field() - Set custom field value


Reset connection to session database servers

  • « session_pgsql_get_field
  • session_pgsql_set_field »
  • PHP Manual
  • Session PgSQL Functions
  • Reset connection to session database servers

session_pgsql_reset

(PECL session_pgsql SVN)

session_pgsql_reset — Reset connection to session database servers

Description

session_pgsql_reset ( void ) : bool

Reset the connection to the session database servers.

Return Values

Returns TRUE on success or FALSE on failure.


Set custom field value

  • « session_pgsql_reset
  • session_pgsql_status »
  • PHP Manual
  • Session PgSQL Functions
  • Set custom field value

session_pgsql_set_field

(PECL session_pgsql SVN)

session_pgsql_set_field — Set custom field value

Description

session_pgsql_set_field ( string $value ) : bool
Warning

This function is currently not documented; only its argument list is available.

Parameters

value

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • session_pgsql_get_field() - Get custom field value


Get current save handler status

  • « session_pgsql_set_field
  • Text Processing »
  • PHP Manual
  • Session PgSQL Functions
  • Get current save handler status

session_pgsql_status

(PECL session_pgsql SVN)

session_pgsql_status — Get current save handler status

Description

session_pgsql_status ( void ) : array
Warning

This function is currently not documented; only its argument list is available.


Text Processing

  • BBCode — Bulletin Board Code
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • BBCode Functions
  • CommonMark
    • Introduction
    • Installing/Configuring
    • CommonMark\Node\Document — Document concrete CommonMark\Node
    • CommonMark\Node\Heading — Heading concrete CommonMark\Node
    • CommonMark\Node\Paragraph — Paragraph concrete CommonMark\Node
    • CommonMark\Node\BlockQuote — BlockQuote concrete CommonMark\Node
    • CommonMark\Node\BulletList — BulletList concrete CommonMark\Node
    • CommonMark\Node\OrderedList — OrderedList concrete CommonMark\Node
    • CommonMark\Node\Item — Item concrete CommonMark\Node
    • CommonMark\Node\Text — Text concrete CommonMark\Node
    • CommonMark\Node\Text\Strong — Strong concrete CommonMark\Node
    • CommonMark\Node\Text\Emphasis — Emphasis concrete CommonMark\Node
    • CommonMark\Node\ThematicBreak — ThematicBreak concrete CommonMark\Node
    • CommonMark\Node\SoftBreak — SoftBreak concrete CommonMark\Node
    • CommonMark\Node\LineBreak — LineBreak concrete CommonMark\Node
    • CommonMark\Node\Code — Code concrete CommonMark\Node
    • CommonMark\Node\CodeBlock — CodeBlock concrete CommonMark\Node
    • CommonMark\Node\HTMLBlock — HTMLBlock concrete CommonMark\Node
    • CommonMark\Node\HTMLInline — HTMLInline concrete CommonMark\Node
    • CommonMark\Node\Image — Image concrete CommonMark\Node
    • CommonMark\Node\Link — Link concrete CommonMark\Node
    • CommonMark\Node\CustomBlock — CustomBlock concrete CommonMark\Node
    • CommonMark\Node\CustomInline — CustomInline concrete CommonMark\Node
    • CommonMark\Node — Abstract CommonMark\Node
    • CommonMark\Interfaces\IVisitor — The CommonMark\Interfaces\IVisitor interface
    • CommonMark\Interfaces\IVisitable — The CommonMark\Interfaces\IVisitable interface
    • CommonMark\Parser — The CommonMark\Parser class
    • CommonMark\CQL — The CommonMark\CQL class
    • CommonMark Functions
  • Parle — Parsing and lexing
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Pattern matching — Parle pattern matching
    • Examples
    • Parle\Lexer — The Parle\Lexer class
    • Parle\RLexer — The Parle\RLexer class
    • Parle\Parser — The Parle\Parser class
    • Parle\RParser — The Parle\RParser class
    • Parle\Stack — The Parle\Stack class
    • Parle\Token — The Parle\Token class
    • Parle\ErrorInfo — The Parle\ErrorInfo class
    • Parle\LexerException — The Parle\LexerException class
    • Parle\ParserException — The Parle\ParserException class
  • PCRE — Regular Expressions (Perl-Compatible)
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • PCRE Patterns
    • PCRE Functions
  • POSIX Regex — Regular Expression (POSIX Extended)
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • POSIX Regex Functions
  • ssdeep — ssdeep Fuzzy Hashing
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • ssdeep Functions
  • Strings
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • String Functions
    • Changelog


Bulletin Board Code

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • BBCode Functions
    • bbcode_add_element — Adds a bbcode element
    • bbcode_add_smiley — Adds a smiley to the parser
    • bbcode_create — Create a BBCode Resource
    • bbcode_destroy — Close BBCode_container resource
    • bbcode_parse — Parse a string following a given rule set
    • bbcode_set_arg_parser — Attach another parser in order to use another rule set for argument parsing
    • bbcode_set_flags — Set or alter parser options


Introduction

This extension aims to help parse BBCode text in order to convert it to HTML or another markup language. It uses one pass parsing and provides great speed improvement over the common approach based on regular expressions. Further more, it helps provide valid HTML by reordering open / close tags and by automatically closing unclosed tags.

Since 0.10.1 It supports argument quoting with single quotes, double quotes and HTML escaped double quotes.


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/bbcode

An alternative solution, written in PHP, is the PEAR package » HTML_BBCodeParser.


  • « Runtime Configuration
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

One resource is used in the BBCode extension: a BBCode_Container returned by bbcode_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.

BBCODE_TYPE_NOARG (integer)
This BBCode tag does not accept any arguments.
BBCODE_TYPE_SINGLE (integer)
This BBCode tag does not have a corresponding close tag.
BBCODE_TYPE_ARG (integer)
This BBCode tag need an argument.
BBCODE_TYPE_OPTARG (integer)
This BBCode tag accept an optional argument.
BBCODE_TYPE_ROOT (integer)
This BBCode tag is the special tag root (nesting level 0).
BBCODE_FLAGS_ARG_PARSING (integer)
This BBCode tag require argument sub-parsing (the argument is also parsed by the BBCode extension). As Of 0.10.2 another parser can be used as argument parser.
BBCODE_FLAGS_CDATA_NOT_ALLOWED (integer)
This BBCode Tag does not accept content (it voids it automatically).
BBCODE_FLAGS_SMILEYS_ON (integer) - since 0.10.2
This BBCode Tag accepts smileys.
BBCODE_FLAGS_SMILEYS_OFF (integer) - since 0.10.2
This BBCode Tag does not accept smileys.
BBCODE_FLAGS_ONE_OPEN_PER_LEVEL (integer) - since 0.10.2
This BBCode Tag automatically closes if another tag of the same type is found at the same nesting level.
BBCODE_FLAGS_REMOVE_IF_EMPTY (integer) - since 0.10.2
This BBCode Tag is automatically removed if content is empty it allows to produce lighter HTML.
BBCODE_FLAGS_DENY_REOPEN_CHILD (integer) - since 0.10.3
This BBCode Tag does not allow unclosed children to reopen when automatically closed.
BBCODE_ARG_DOUBLE_QUOTE (integer) - since 0.10.2
This is a parser option allowing argument quoting with double quotes (")
BBCODE_ARG_SINGLE_QUOTE (integer) - since 0.10.2
This is a parser option allowing argument quoting with single quotes (')
BBCODE_ARG_HTML_QUOTE (integer) - since 0.10.2
This is a parser option allowing argument quoting with HTML version of double quotes (&quot;)
BBCODE_ARG_QUOTE_ESCAPING (integer) - since 1.0.2
This is a parser option allowing argument quotes to be escaped this permit the quote delimiter to be found in the string escaping character is \ it can escape any quoting character or itself, if found in front of a non escapable character, it will be dropped. Default behaviour is not to use escaping.
BBCODE_AUTO_CORRECT (integer) - since 0.10.2
This is a parser option changing the way errors are treated. It automatically closes tag in the order they are opened. And treat tags with only an open tag as if there were a close tag present.
BBCODE_CORRECT_REOPEN_TAGS (integer) - since 0.10.2
This is a parser option changing the way errors are treated. It automatically reopens tag if close tags are not in the good order.
BBCODE_DISABLE_TREE_BUILD (integer) - since 0.10.2
This is a parser option disabling the BBCode parsing it can be useful if only the "smiley" replacement must be used.
BBCODE_DEFAULT_SMILEYS_ON (integer) - since 0.10.2
This is a parser option setting smileys to ON if no flag is given at tag level.
BBCODE_DEFAULT_SMILEYS_OFF (integer) - since 0.10.2
This is a parser option setting smileys to OFF if no flag is given at tag level.
BBCODE_FORCE_SMILEYS_OFF (integer) - since 0.10.2
This is a parser option disabling completely the smileys parsing.
BBCODE_SMILEYS_CASE_INSENSITIVE (integer) - since 0.10.3
Use a case insensitive Detection for smileys instead of a simple binary search.
BBCODE_SET_FLAGS_SET (integer) - since 0.10.2
This permits to SET the complete flag set on a parser.
BBCODE_SET_FLAGS_ADD (integer) - since 0.10.2
This permits to switch a flag set ON on a parser.
BBCODE_SET_FLAGS_REMOVE (integer) - since 0.10.2
This permits to switch a flag set OFF on a parser.


BBCode Functions

Table of Contents

  • bbcode_add_element — Adds a bbcode element
  • bbcode_add_smiley — Adds a smiley to the parser
  • bbcode_create — Create a BBCode Resource
  • bbcode_destroy — Close BBCode_container resource
  • bbcode_parse — Parse a string following a given rule set
  • bbcode_set_arg_parser — Attach another parser in order to use another rule set for argument parsing
  • bbcode_set_flags — Set or alter parser options


Adds a bbcode element

  • « BBCode Functions
  • bbcode_add_smiley »
  • PHP Manual
  • BBCode Functions
  • Adds a bbcode element

bbcode_add_element

(PECL bbcode >= 0.9.0)

bbcode_add_element — Adds a bbcode element

Description

bbcode_add_element ( resource $bbcode_container , string $tag_name , array $tag_rules ) : bool

Adds a tag to an existing BBCode_Container tag_set using tag_rules.

Parameters

bbcode_container

BBCode_Container resource, returned by bbcode_create().

tag_name

The new tag to add to the BBCode_Container tag_set.

tag_rules

An associative array containing the parsing rules; see bbcode_create() for the available keys.

Return Values

Returns TRUE on success or FALSE on failure.


Adds a smiley to the parser

  • « bbcode_add_element
  • bbcode_create »
  • PHP Manual
  • BBCode Functions
  • Adds a smiley to the parser

bbcode_add_smiley

(PECL bbcode >= 0.10.2)

bbcode_add_smiley — Adds a smiley to the parser

Description

bbcode_add_smiley ( resource $bbcode_container , string $smiley , string $replace_by ) : bool

Adds a smiley to the parser

Parameters

bbcode_container

BBCode_Container resource, returned by bbcode_create().

smiley

The string that will be replaced when found.

replace_by

The string that replace smiley when found.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bbcode_add_smiley() usage example

<?php
/*
 * Prepare the rule set
 */
$arrayBBCode=array(
    ''=>         array('type'=>BBCODE_TYPE_ROOT,
                       'childs'=>'!i'),
    'b'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<b>',
                       'close_tag'=>'</b>'),
    'u'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<u>',
                       'close_tag'=>'</u>',
                       'flags'=>BBCODE_FLAGS_SMILEYS_OFF),
    'i'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<i>',
                       'close_tag'=>'</i>',
                       'childs'=>'b'),
);
/*
 * Parsed Text
 */
$text=<<<EOF
[i] No parse Test [/i] :)
[b] Parsed, with smiley :( [/b]
[u] Parsed, with no smiley :D [/u]
EOF;
/*
 * Init the parser
 */
$BBHandler=bbcode_create($arrayBBCode);
/*
 * Add Smiley rules to parser
 */
bbcode_add_smiley($BBHandler, ":)", "<img src=\"smiley.gif\" alt=\":)\" />");
bbcode_add_smiley($BBHandler, ":(", "<img src=\"sad.gif\" alt=\":(\" />");
bbcode_add_smiley($BBHandler, ":D", "<img src=\"happy.gif\" alt=\":D\" />");
bbcode_add_smiley($BBHandler, ":p", "<img src=\"tong.gif\" alt=\":p\" />");
bbcode_add_smiley($BBHandler, ":|", "<img src=\"special.gif\" alt=\":|\" />");
bbcode_add_smiley($BBHandler, ":6:", "<img src=\"six.gif\" alt=\":6:\" />");
/*
 * Parse the text
 */
echo bbcode_parse($BBHandler,$text);
?>

The above example will output:

<i> No parse Test </i> <img src="smiley.gif" alt=":)" />
<b> Parsed, with smiley <img src="sad.gif" alt=":(" /> </b>
<u> Parsed, with no smiley :D </u>


Create a BBCode Resource

  • « bbcode_add_smiley
  • bbcode_destroy »
  • PHP Manual
  • BBCode Functions
  • Create a BBCode Resource

bbcode_create

(PECL bbcode >= 0.9.0)

bbcode_create — Create a BBCode Resource

Description

bbcode_create ([ array $bbcode_initial_tags = NULL ] ) : resource

This function returns a new BBCode Resource used to parse BBCode strings.

Parameters

bbcode_initial_tags

An associative array containing the tag names as keys and parameters required to correctly parse BBCode as their value. The following key/value pairs are supported:

  • flags optional - a flag set based on the BBCODE_FLAGS_* constants.
  • type required - an int indicating the type of tag. Use the BBCODE_TYPE_* constants.
  • open_tag required - the HTML replacement string for the open tag.
  • close_tag required - the HTML replacement string for the close tag.
  • default_arg optional - use this value as the default argument if none is provided and tag_type is of type OPTARG.
  • content_handling optional - Gives the callback used for modification of the content. Object Oriented Notation supported only since 0.10.1 callback prototype is string name(string $content, string $argument)
  • param_handling optional - Gives the callback used for modification of the argument. Object Oriented Notation supported only since 0.10.1 callback prototype is string name(string $content, string $argument)
  • childs optional - List of accepted children for the tag. The format of the list is a comma separated string. If the list starts with ! it will be the list of rejected children for the tag.
  • parent optional - List of accepted parents for the tag. The format of the list is a comma separated string.

Return Values

Returns a BBCode_Container

Examples

Example #1 bbcode_create() example

<?php
$arrayBBCode=array(
    ''=>         array('type'=>BBCODE_TYPE_ROOT,  'childs'=>'!i'),
    'i'=>        array('type'=>BBCODE_TYPE_NOARG, 'open_tag'=>'<i>',
                    'close_tag'=>'</i>', 'childs'=>'b'),
    'url'=>      array('type'=>BBCODE_TYPE_OPTARG,
                    'open_tag'=>'<a href="{PARAM}">', 'close_tag'=>'</a>',
                    'default_arg'=>'{CONTENT}',
                    'childs'=>'b,i'),
    'img'=>      array('type'=>BBCODE_TYPE_NOARG,
                    'open_tag'=>'<img src="', 'close_tag'=>'" />',
                    'childs'=>''),
    'b'=>        array('type'=>BBCODE_TYPE_NOARG, 'open_tag'=>'<b>',
                    'close_tag'=>'</b>'),
);
$text=<<<EOF
[b]Bold Text[/b]
[i]Italic Text[/i]
[url]http://www.php.net/[/url]
[url=http://pecl.php.net/][b]Content Text[/b][/url]
[img]http://static.php.net/www.php.net/images/php.gif[/img]
[url=http://www.php.net/]
[img]http://static.php.net/www.php.net/images/php.gif[/img]
[/url]
EOF;
$BBHandler=bbcode_create($arrayBBCode);
echo bbcode_parse($BBHandler,$text);
?>

The above example will output:

<b>Bold Text</b>
[i]Italic Text[/i]
<a href="http://www.php.net/">http://www.php.net/</a>
<a href="http://pecl.php.net/"><b>Content Text</b></a>
<img src="http://static.php.net/www.php.net/images/php.gif" />
<a href="http://www.php.net/">
[img]http://static.php.net/www.php.net/images/php.gif[/img]
</a>


Close BBCode_container resource

  • « bbcode_create
  • bbcode_parse »
  • PHP Manual
  • BBCode Functions
  • Close BBCode_container resource

bbcode_destroy

(PECL bbcode >= 0.9.0)

bbcode_destroy — Close BBCode_container resource

Description

bbcode_destroy ( resource $bbcode_container ) : bool

This function closes the resource opened by bbcode_create().

Parameters

bbcode_container

BBCode_Container resource returned by bbcode_create().

Return Values

Returns TRUE on success or FALSE on failure.


Parse a string following a given rule set

  • « bbcode_destroy
  • bbcode_set_arg_parser »
  • PHP Manual
  • BBCode Functions
  • Parse a string following a given rule set

bbcode_parse

(PECL bbcode >= 0.9.0)

bbcode_parse — Parse a string following a given rule set

Description

bbcode_parse ( resource $bbcode_container , string $to_parse ) : string

This function parse the string to_parse following the rules in the bbcode_container created by bbcode_create()

Parameters

bbcode_container

BBCode_Container resource returned by bbcode_create().

to_parse

The string we need to parse.

Return Values

Returns the parsed string, or FALSE on failure.


Attach another parser in order to use another rule set for argument parsing

  • « bbcode_parse
  • bbcode_set_flags »
  • PHP Manual
  • BBCode Functions
  • Attach another parser in order to use another rule set for argument parsing

bbcode_set_arg_parser

(PECL bbcode >= 0.10.2)

bbcode_set_arg_parser — Attach another parser in order to use another rule set for argument parsing

Description

bbcode_set_arg_parser ( resource $bbcode_container , resource $bbcode_arg_parser ) : bool

Attaches another parser to the bbcode_container. This parser is used only when arguments must be parsed. If this function is not used, the default argument parser is the parser itself.

Parameters

bbcode_container

BBCode_Container resource, returned by bbcode_create().

bbcode_arg_parser

BBCode_Container resource, returned by bbcode_create(). It will be used only for parsed arguments

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bbcode_set_arg_parser() usage example

<?php
/*
 * Generating bbcode ruleset for main parser
 */
$arrayBBCode=array(
    'quote'=>    array('type'=>BBCODE_TYPE_ARG,
                       'open_tag'=>'<quote><h4>Source: {PARAM}</h4>',
                       'close_tag'=>'</quote>',
                       'flags'=>BBCODE_FLAGS_REMOVE_IF_EMPTY|BBCODE_FLAGS_ARG_PARSING),
    'b'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<b>', 'close_tag'=>'</b>',
                       'flags'=>BBCODE_FLAGS_REMOVE_IF_EMPTY),
    'u'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<u>', 'close_tag'=>'</u>',
                       'flags'=>BBCODE_FLAGS_SMILEYS_OFF | BBCODE_FLAGS_REMOVE_IF_EMPTY | BBCODE_FLAGS_SMILEYS_OFF),
    'i'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<i>', 'close_tag'=>'</i>',
                       'flags'=>BBCODE_FLAGS_REMOVE_IF_EMPTY),
);
/*
 * Generating bbcode ruleset for argument parser
 */
$arrayBBCode_arg=array(
    'b'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<b class="sub">', 'close_tag'=>'</b>',
                       'flags'=>BBCODE_FLAGS_REMOVE_IF_EMPTY),
    'u'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<u>', 'close_tag'=>'</u>',
                       'flags'=>BBCODE_FLAGS_SMILEYS_OFF | BBCODE_FLAGS_REMOVE_IF_EMPTY | BBCODE_FLAGS_SMILEYS_OFF),
    'i'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<i>', 'close_tag'=>'</i>',
                       'flags'=>BBCODE_FLAGS_REMOVE_IF_EMPTY),
);
/*
 * Text we are going to parse
 */
$text=<<<EOF
[quote="[b]Test[/b]"]
Foo :)
[/quote]
[b]Bar example :)[/b] :)
EOF;
/*
 * Init the two parsers
 */
$BBHandler=bbcode_create($arrayBBCode);
$BBArgHandler=bbcode_create($arrayBBCode_arg);
/*
 * Setting Flags on the parsers
 */
bbcode_set_flags($BBHandler,
                 BBCODE_CORRECT_REOPEN_TAGS|BBCODE_DEFAULT_SMILEYS_ON|BBCODE_ARG_DOUBLE_QUOTE|
                 BBCODE_ARG_SINGLE_QUOTE|BBCODE_ARG_HTML_QUOTE,BBCODE_SET_FLAGS_SET);
bbcode_set_flags($BBArgHandler,
                 BBCODE_CORRECT_REOPEN_TAGS|BBCODE_DEFAULT_SMILEYS_ON|BBCODE_ARG_DOUBLE_QUOTE|
                 BBCODE_ARG_SINGLE_QUOTE|BBCODE_ARG_HTML_QUOTE,BBCODE_SET_FLAGS_SET);
/*
 * Setting $BBArgHandler as the BBHandler argument parser
 */
bbcode_set_arg_parser($BBHandler,$BBArgHandler);
/*
 * Adding Smileys handling rules to Main parser
 */
bbcode_add_smiley($BBHandler, ":)", "<img src=\"smiley.gif\" alt=\":)\" />");
/*
 * Use the main parser to parse text
 */
echo bbcode_parse($BBHandler,$text);
?>

The above example will output:

<quote><h4>Source: <b class="sub">Test</b></h4>
Foo <img src="smiley.gif" alt=":)" />
</quote>
<b>Bar example :)</b> <img src="smiley.gif" alt=":)" />


Set or alter parser options

  • « bbcode_set_arg_parser
  • CommonMark »
  • PHP Manual
  • BBCode Functions
  • Set or alter parser options

bbcode_set_flags

(PECL bbcode >= 0.10.2)

bbcode_set_flags — Set or alter parser options

Description

bbcode_set_flags ( resource $bbcode_container , int $flags [, int $mode = BBCODE_SET_FLAGS_SET ] ) : bool

Set or alter parser options

Parameters

bbcode_container

BBCode_Container resource, returned by bbcode_create().

flags

The flag set that must be applied to the bbcode_container options

mode

One of the BBCODE_SET_FLAGS_* constant to set, unset a specific flag set or to replace the flag set by flags.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 bbcode_set_flags() usage example

<?php
/*
 * Preparing RuleSet
 */
$arrayBBCode=array(
    'b'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<b>', 'close_tag'=>'</b>'),
    'u'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<u>', 'close_tag'=>'</u>'),
    'i'=>        array('type'=>BBCODE_TYPE_NOARG,
                       'open_tag'=>'<i>', 'close_tag'=>'</i>'),
);
/*
 * Paired incorrectly nested BBCode
 */
$text="[i] Parser [b] Auto Correction [/i] at work [/b]\n";
$BBHandler=bbcode_create($arrayBBCode);
echo bbcode_parse($BBHandler,$text);
// Enabling reopening of automatically closed elements
bbcode_set_flags($BBHandler,BBCODE_CORRECT_REOPEN_TAGS,
                 BBCODE_SET_FLAGS_SET);
echo bbcode_parse($BBHandler,$text);

/*
 * Unpaired incorrectly nested BBCode
 */
$text="[i] Parser [b] Auto Correction [/i] at work\n";
echo bbcode_parse($BBHandler,$text);
// Enabling automatic close of pending tags
bbcode_set_flags($BBHandler,
                 BBCODE_CORRECT_REOPEN_TAGS|BBCODE_AUTO_CORRECT,
                 BBCODE_SET_FLAGS_SET);
echo bbcode_parse($BBHandler,$text);
?>

The above example will output:

<i> Parser <b> Auto Correction </b></i> at work
<i> Parser <b> Auto Correction </b></i><b> at work </b>
<i> Parser [b] Auto Correction </i> at work
<i> Parser <b> Auto Correction </b></i><b> at work
</b>


CommonMark

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
  • CommonMark\Node\Document — Document concrete CommonMark\Node
  • CommonMark\Node\Heading — Heading concrete CommonMark\Node
    • CommonMark\Node\Heading::__construct — Heading Construction
  • CommonMark\Node\Paragraph — Paragraph concrete CommonMark\Node
  • CommonMark\Node\BlockQuote — BlockQuote concrete CommonMark\Node
  • CommonMark\Node\BulletList — BulletList concrete CommonMark\Node
    • CommonMark\Node\BulletList::__construct — BulletList Construction
  • CommonMark\Node\OrderedList — OrderedList concrete CommonMark\Node
    • CommonMark\Node\OrderedList::__construct — OrderedList Construction
  • CommonMark\Node\Item — Item concrete CommonMark\Node
  • CommonMark\Node\Text — Text concrete CommonMark\Node
    • CommonMark\Node\Text::__construct — Text Construction
  • CommonMark\Node\Text\Strong — Strong concrete CommonMark\Node
  • CommonMark\Node\Text\Emphasis — Emphasis concrete CommonMark\Node
  • CommonMark\Node\ThematicBreak — ThematicBreak concrete CommonMark\Node
  • CommonMark\Node\SoftBreak — SoftBreak concrete CommonMark\Node
  • CommonMark\Node\LineBreak — LineBreak concrete CommonMark\Node
  • CommonMark\Node\Code — Code concrete CommonMark\Node
  • CommonMark\Node\CodeBlock — CodeBlock concrete CommonMark\Node
    • CommonMark\Node\CodeBlock::__construct — CodeBlock Construction
  • CommonMark\Node\HTMLBlock — HTMLBlock concrete CommonMark\Node
  • CommonMark\Node\HTMLInline — HTMLInline concrete CommonMark\Node
  • CommonMark\Node\Image — Image concrete CommonMark\Node
    • CommonMark\Node\Image::__construct — Image Construction
  • CommonMark\Node\Link — Link concrete CommonMark\Node
    • CommonMark\Node\Link::__construct — Link Construction
  • CommonMark\Node\CustomBlock — CustomBlock concrete CommonMark\Node
  • CommonMark\Node\CustomInline — CustomInline concrete CommonMark\Node
  • CommonMark\Node — Abstract CommonMark\Node
    • CommonMark\Node::appendChild — AST Manipulation
    • CommonMark\Node::prependChild — AST Manipulation
    • CommonMark\Node::insertAfter — AST Manipulation
    • CommonMark\Node::insertBefore — AST Manipulation
    • CommonMark\Node::replace — AST Manipulation
    • CommonMark\Node::unlink — AST Manipulation
    • CommonMark\Node::accept — Visitation
  • CommonMark\Interfaces\IVisitor — The CommonMark\Interfaces\IVisitor interface
    • CommonMark\Interfaces\IVisitor::enter — Visitation
    • CommonMark\Interfaces\IVisitor::leave — Visitation
  • CommonMark\Interfaces\IVisitable — The CommonMark\Interfaces\IVisitable interface
    • CommonMark\Interfaces\IVisitable::accept — Visitation
  • CommonMark\Parser — The CommonMark\Parser class
    • CommonMark\Parser::__construct — Parsing
    • CommonMark\Parser::parse — Parsing
    • CommonMark\Parser::finish — Parsing
  • CommonMark\CQL — The CommonMark\CQL class
    • CommonMark\CQL::__construct — CQL Construction
    • CommonMark\CQL::__invoke — CQL Execution
  • CommonMark Functions
    • CommonMark\Parse — Parsing
    • CommonMark\Render — Rendering
    • CommonMark\Render\HTML — Rendering
    • CommonMark\Render\Latex — Rendering
    • CommonMark\Render\Man — Rendering
    • CommonMark\Render\XML — Rendering


Introduction

This extension provides access to the reference implementation of CommonMark, a rationalized version of Markdown syntax with a specification.

Parsing:

The CommonMark extension provides a simple parsing API:

CommonMark\Parse ( string $content [, int $options ] ) : CommonMark\Node

Rendering:

The CommonMark extension provides simple rendering API that supports multiple formats:

CommonMark\Render ( CommonMark\Node $node [, int $options [, int $width ]] ) : string
CommonMark\Render\HTML ( CommonMark\Node $node [, int $options ] ) : string
CommonMark\Render\XML ( CommonMark\Node $node [, int $options ] ) : string
CommonMark\Render\Man ( CommonMark\Node $node [, int $options [, int $width ]] ) : string
CommonMark\Render\Latex ( CommonMark\Node $node [, int $options [, int $width ]] ) : string

AST:

The CommonMark extension implements visitation for CommonMark\Node objects:

public CommonMark\Node::accept ( CommonMark\Interfaces\IVisitor $visitor ) : void

CQL:

The CommonMark extension provides an interface to CQL, CommonMark Query Language:

public CommonMark\CQL::__construct ( string $query )


  • « Introduction
  • Requirements »
  • PHP Manual
  • CommonMark
  • Installing/Configuring

Installing/Configuring

Table of Contents

  • Requirements
  • Installation


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

The CommonMark extension requires the (C) reference implementation of » cmark.


Installation

The CommonMark extension releases are hosted by PECL and source is hosted on » github, the easiest route to installation is the normal PECL route: » https://pecl.php.net/package/cmark.

Windows users can download prebuilt release binaries from the » PECL website.

Caution

Windows users need to take the additional step of adding cmark.dll (distributed with Windows releases) to their PATH.


Document concrete CommonMark\Node

(cmark >= 1.0.0)

Class synopsis

final CommonMark\Node\Document extends CommonMark\Node implements CommonMark\Interfaces\IVisitable , Traversable {
/* Inherited properties */
public readonly ?Node $parent ;
public readonly ?Node $previous ;
public readonly ?Node $next ;
public readonly ?Node $lastChild ;
public readonly ?Node $firstChild ;
public readonly int $startLine ;
public readonly int $endLine ;
public readonly int $startColumn ;
public readonly int $endColumn ;
/* Inherited methods */
public CommonMark\Node::appendChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::prependChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::insertAfter ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::insertBefore ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::replace ( CommonMark\Node $target ) : CommonMark\Node
public CommonMark\Node::unlink ( void ) : void
public CommonMark\Node::accept ( CommonMark\Interfaces\IVisitor $visitor ) : void
}


Heading concrete CommonMark\Node

(cmark >= 1.0.0)

Class synopsis

final CommonMark\Node\Heading extends CommonMark\Node implements CommonMark\Interfaces\IVisitable , Traversable {
/* Inherited properties */
public readonly ?Node $parent ;
public readonly ?Node $previous ;
public readonly ?Node $next ;
public readonly ?Node $lastChild ;
public readonly ?Node $firstChild ;
public readonly int $startLine ;
public readonly int $endLine ;
public readonly int $startColumn ;
public readonly int $endColumn ;
/* Properties */
public int $level ;
/* Constructor */
public __construct ( void )
public __construct ( int $level )
/* Inherited methods */
public CommonMark\Node::appendChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::prependChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::insertAfter ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::insertBefore ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::replace ( CommonMark\Node $target ) : CommonMark\Node
public CommonMark\Node::unlink ( void ) : void
public CommonMark\Node::accept ( CommonMark\Interfaces\IVisitor $visitor ) : void
}

Table of Contents

  • CommonMark\Node\Heading::__construct — Heading Construction


Heading Construction

  • « CommonMark\Node\Heading
  • CommonMark\Node\Paragraph »
  • PHP Manual
  • CommonMark\Node\Heading
  • Heading Construction

CommonMark\Node\Heading::__construct

(cmark >= 1.0.0)

CommonMark\Node\Heading::__construct — Heading Construction

Description

public CommonMark\Node\Heading::__construct ( void )
public CommonMark\Node\Heading::__construct ( int $level )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.


Paragraph concrete CommonMark\Node

(cmark >= 1.0.0)

Class synopsis

final CommonMark\Node\Paragraph extends CommonMark\Node implements CommonMark\Interfaces\IVisitable , Traversable {
/* Inherited properties */
public readonly ?Node $parent ;
public readonly ?Node $previous ;
public readonly ?Node $next ;
public readonly ?Node $lastChild ;
public readonly ?Node $firstChild ;
public readonly int $startLine ;
public readonly int $endLine ;
public readonly int $startColumn ;
public readonly int $endColumn ;
/* Inherited methods */
public CommonMark\Node::appendChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::prependChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::insertAfter ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::insertBefore ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::replace ( CommonMark\Node $target ) : CommonMark\Node
public CommonMark\Node::unlink ( void ) : void
public CommonMark\Node::accept ( CommonMark\Interfaces\IVisitor $visitor ) : void
}


BlockQuote concrete CommonMark\Node

(cmark >= 1.0.0)

Class synopsis

final CommonMark\Node\BlockQuote extends CommonMark\Node implements CommonMark\Interfaces\IVisitable , Traversable {
/* Inherited properties */
public readonly ?Node $parent ;
public readonly ?Node $previous ;
public readonly ?Node $next ;
public readonly ?Node $lastChild ;
public readonly ?Node $firstChild ;
public readonly int $startLine ;
public readonly int $endLine ;
public readonly int $startColumn ;
public readonly int $endColumn ;
/* Inherited methods */
public CommonMark\Node::appendChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::prependChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::insertAfter ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::insertBefore ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::replace ( CommonMark\Node $target ) : CommonMark\Node
public CommonMark\Node::unlink ( void ) : void
public CommonMark\Node::accept ( CommonMark\Interfaces\IVisitor $visitor ) : void
}


BulletList concrete CommonMark\Node

(cmark >= 1.0.0)

Class synopsis

final CommonMark\Node\BulletList extends CommonMark\Node implements CommonMark\Interfaces\IVisitable , Traversable {
/* Inherited properties */
public readonly ?Node $parent ;
public readonly ?Node $previous ;
public readonly ?Node $next ;
public readonly ?Node $lastChild ;
public readonly ?Node $firstChild ;
public readonly int $startLine ;
public readonly int $endLine ;
public readonly int $startColumn ;
public readonly int $endColumn ;
/* Properties */
public bool $tight ;
public int $delimiter ;
/* Constructor */
public __construct ( void )
public __construct ( int $tight )
public __construct ( int $tight , int $delimiter )
/* Inherited methods */
public CommonMark\Node::appendChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::prependChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::insertAfter ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::insertBefore ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::replace ( CommonMark\Node $target ) : CommonMark\Node
public CommonMark\Node::unlink ( void ) : void
public CommonMark\Node::accept ( CommonMark\Interfaces\IVisitor $visitor ) : void
}

Table of Contents

  • CommonMark\Node\BulletList::__construct — BulletList Construction


BulletList Construction

  • « CommonMark\Node\BulletList
  • CommonMark\Node\OrderedList »
  • PHP Manual
  • CommonMark\Node\BulletList
  • BulletList Construction

CommonMark\Node\BulletList::__construct

(cmark >= 1.0.0)

CommonMark\Node\BulletList::__construct — BulletList Construction

Description

public CommonMark\Node\BulletList::__construct ( void )
public CommonMark\Node\BulletList::__construct ( int $tight )
public CommonMark\Node\BulletList::__construct ( int $tight , int $delimiter )

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.


OrderedList concrete CommonMark\Node

(cmark >= 1.0.0)

Class synopsis

final CommonMark\Node\OrderedList extends CommonMark\Node implements CommonMark\Interfaces\IVisitable , Traversable {
/* Inherited properties */
public readonly ?Node $parent ;
public readonly ?Node $previous ;
public readonly ?Node $next ;
public readonly ?Node $lastChild ;
public readonly ?Node $firstChild ;
public readonly int $startLine ;
public readonly int $endLine ;
public readonly int $startColumn ;
public readonly int $endColumn ;
/* Properties */
public bool $tight ;
public int $delimiter ;
public int $start ;
/* Constructor */
public __construct ( void )
public __construct ( int $tight )
public __construct ( int $tight , int $delimiter )
public __construct ( int $tight , int $delimiter , int $start )
/* Inherited methods */
public CommonMark\Node::appendChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::prependChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::insertAfter ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::insertBefore ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::replace ( CommonMark\Node $target ) : CommonMark\Node
public CommonMark\Node::unlink ( void ) : void
public CommonMark\Node::accept ( CommonMark\Interfaces\IVisitor $visitor ) : void
}

Table of Contents

  • CommonMark\Node\OrderedList::__construct — OrderedList Construction


OrderedList Construction

  • « CommonMark\Node\OrderedList
  • CommonMark\Node\Item »
  • PHP Manual
  • CommonMark\Node\OrderedList
  • OrderedList Construction

CommonMark\Node\OrderedList::__construct

(cmark >= 1.0.0)

CommonMark\Node\OrderedList::__construct — OrderedList Construction

Description

public CommonMark\Node\OrderedList::__construct ( void )
public CommonMark\Node\OrderedList::__construct ( int $tight )
public CommonMark\Node\OrderedList::__construct ( int $tight , int $delimiter )
public CommonMark\Node\OrderedList::__construct ( int $tight , int $delimiter , int $start )

Warning

This function is currently not documented; only its argument list is available.

Parameters

tight

delimiter

start


Item concrete CommonMark\Node

(cmark >= 1.0.0)

Class synopsis

final CommonMark\Node\Item extends CommonMark\Node implements CommonMark\Interfaces\IVisitable , Traversable {
/* Inherited properties */
public readonly ?Node $parent ;
public readonly ?Node $previous ;
public readonly ?Node $next ;
public readonly ?Node $lastChild ;
public readonly ?Node $firstChild ;
public readonly int $startLine ;
public readonly int $endLine ;
public readonly int $startColumn ;
public readonly int $endColumn ;
/* Inherited methods */
public CommonMark\Node::appendChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::prependChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::insertAfter ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::insertBefore ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::replace ( CommonMark\Node $target ) : CommonMark\Node
public CommonMark\Node::unlink ( void ) : void
public CommonMark\Node::accept ( CommonMark\Interfaces\IVisitor $visitor ) : void
}


Text concrete CommonMark\Node

(cmark >= 1.0.0)

Class synopsis

final CommonMark\Node\Text extends CommonMark\Node implements CommonMark\Interfaces\IVisitable , Traversable {
/* Inherited properties */
public readonly ?Node $parent ;
public readonly ?Node $previous ;
public readonly ?Node $next ;
public readonly ?Node $lastChild ;
public readonly ?Node $firstChild ;
public readonly int $startLine ;
public readonly int $endLine ;
public readonly int $startColumn ;
public readonly int $endColumn ;
/* Properties */
public ?string $literal ;
/* Constructor */
public __construct ( void )
public __construct ( string $literal )
/* Inherited methods */
public CommonMark\Node::appendChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::prependChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::insertAfter ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::insertBefore ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::replace ( CommonMark\Node $target ) : CommonMark\Node
public CommonMark\Node::unlink ( void ) : void
public CommonMark\Node::accept ( CommonMark\Interfaces\IVisitor $visitor ) : void
}

Table of Contents

  • CommonMark\Node\Text::__construct — Text Construction


Text Construction

  • « CommonMark\Node\Text
  • CommonMark\Node\Text\Strong »
  • PHP Manual
  • CommonMark\Node\Text
  • Text Construction

CommonMark\Node\Text::__construct

(cmark >= 1.0.0)

CommonMark\Node\Text::__construct — Text Construction

Description

public CommonMark\Node\Text::__construct ( void )
public CommonMark\Node\Text::__construct ( string $literal )

Warning

This function is currently not documented; only its argument list is available.

Parameters

literal


Strong concrete CommonMark\Node

(cmark >= 1.0.0)

Class synopsis

final CommonMark\Node\Text\Strong extends CommonMark\Node implements CommonMark\Interfaces\IVisitable , Traversable {
/* Inherited properties */
public readonly ?Node $parent ;
public readonly ?Node $previous ;
public readonly ?Node $next ;
public readonly ?Node $lastChild ;
public readonly ?Node $firstChild ;
public readonly int $startLine ;
public readonly int $endLine ;
public readonly int $startColumn ;
public readonly int $endColumn ;
/* Inherited methods */
public CommonMark\Node::appendChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::prependChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::insertAfter ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::insertBefore ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::replace ( CommonMark\Node $target ) : CommonMark\Node
public CommonMark\Node::unlink ( void ) : void
public CommonMark\Node::accept ( CommonMark\Interfaces\IVisitor $visitor ) : void
}


Emphasis concrete CommonMark\Node

(cmark >= 1.0.0)

Class synopsis

final CommonMark\Node\Text\Emphasis extends CommonMark\Node implements CommonMark\Interfaces\IVisitable , Traversable {
/* Inherited properties */
public readonly ?Node $parent ;
public readonly ?Node $previous ;
public readonly ?Node $next ;
public readonly ?Node $lastChild ;
public readonly ?Node $firstChild ;
public readonly int $startLine ;
public readonly int $endLine ;
public readonly int $startColumn ;
public readonly int $endColumn ;
/* Inherited methods */
public CommonMark\Node::appendChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::prependChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::insertAfter ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::insertBefore ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::replace ( CommonMark\Node $target ) : CommonMark\Node
public CommonMark\Node::unlink ( void ) : void
public CommonMark\Node::accept ( CommonMark\Interfaces\IVisitor $visitor ) : void
}


ThematicBreak concrete CommonMark\Node

(cmark >= 1.0.0)

Class synopsis

final CommonMark\Node\ThematicBreak extends CommonMark\Node implements CommonMark\Interfaces\IVisitable , Traversable {
/* Inherited properties */
public readonly ?Node $parent ;
public readonly ?Node $previous ;
public readonly ?Node $next ;
public readonly ?Node $lastChild ;
public readonly ?Node $firstChild ;
public readonly int $startLine ;
public readonly int $endLine ;
public readonly int $startColumn ;
public readonly int $endColumn ;
/* Inherited methods */
public CommonMark\Node::appendChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::prependChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::insertAfter ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::insertBefore ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::replace ( CommonMark\Node $target ) : CommonMark\Node
public CommonMark\Node::unlink ( void ) : void
public CommonMark\Node::accept ( CommonMark\Interfaces\IVisitor $visitor ) : void
}


SoftBreak concrete CommonMark\Node

(cmark >= 1.0.0)

Class synopsis

final CommonMark\Node\SoftBreak extends CommonMark\Node implements CommonMark\Interfaces\IVisitable , Traversable {
/* Inherited properties */
public readonly ?Node $parent ;
public readonly ?Node $previous ;
public readonly ?Node $next ;
public readonly ?Node $lastChild ;
public readonly ?Node $firstChild ;
public readonly int $startLine ;
public readonly int $endLine ;
public readonly int $startColumn ;
public readonly int $endColumn ;
/* Inherited methods */
public CommonMark\Node::appendChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::prependChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::insertAfter ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::insertBefore ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::replace ( CommonMark\Node $target ) : CommonMark\Node
public CommonMark\Node::unlink ( void ) : void
public CommonMark\Node::accept ( CommonMark\Interfaces\IVisitor $visitor ) : void
}


LineBreak concrete CommonMark\Node

(cmark >= 1.0.0)

Class synopsis

final CommonMark\Node\LineBreak extends CommonMark\Node implements CommonMark\Interfaces\IVisitable , Traversable {
/* Inherited properties */
public readonly ?Node $parent ;
public readonly ?Node $previous ;
public readonly ?Node $next ;
public readonly ?Node $lastChild ;
public readonly ?Node $firstChild ;
public readonly int $startLine ;
public readonly int $endLine ;
public readonly int $startColumn ;
public readonly int $endColumn ;
/* Inherited methods */
public CommonMark\Node::appendChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::prependChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::insertAfter ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::insertBefore ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::replace ( CommonMark\Node $target ) : CommonMark\Node
public CommonMark\Node::unlink ( void ) : void
public CommonMark\Node::accept ( CommonMark\Interfaces\IVisitor $visitor ) : void
}


Code concrete CommonMark\Node

(cmark >= 1.0.0)

Class synopsis

final CommonMark\Node\Code extends CommonMark\Node\Text implements CommonMark\Interfaces\IVisitable , Traversable {
/* Inherited properties */
public readonly ?Node $parent ;
public readonly ?Node $previous ;
public readonly ?Node $next ;
public readonly ?Node $lastChild ;
public readonly ?Node $firstChild ;
public readonly int $startLine ;
public readonly int $endLine ;
public readonly int $startColumn ;
public readonly int $endColumn ;
public ?string $literal ;
/* Constructor */
public CommonMark\Node\Text::__construct ( void )
public CommonMark\Node\Text::__construct ( string $literal )
/* Inherited methods */
public CommonMark\Node::appendChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::prependChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::insertAfter ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::insertBefore ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::replace ( CommonMark\Node $target ) : CommonMark\Node
public CommonMark\Node::unlink ( void ) : void
public CommonMark\Node::accept ( CommonMark\Interfaces\IVisitor $visitor ) : void
}


CodeBlock concrete CommonMark\Node

(cmark >= 1.0.0)

Class synopsis

final CommonMark\Node\CodeBlock extends CommonMark\Node\Text implements CommonMark\Interfaces\IVisitable , Traversable {
/* Inherited properties */
public readonly ?Node $parent ;
public readonly ?Node $previous ;
public readonly ?Node $next ;
public readonly ?Node $lastChild ;
public readonly ?Node $firstChild ;
public readonly int $startLine ;
public readonly int $endLine ;
public readonly int $startColumn ;
public readonly int $endColumn ;
public ?string $literal ;
/* Properties */
public ?string $fence ;
/* Constructor */
public CommonMark\Node\Text::__construct ( void )
public CommonMark\Node\Text::__construct ( string $literal )
public __construct ( string $fence , string $literal )
/* Inherited methods */
public CommonMark\Node::appendChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::prependChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::insertAfter ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::insertBefore ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::replace ( CommonMark\Node $target ) : CommonMark\Node
public CommonMark\Node::unlink ( void ) : void
public CommonMark\Node::accept ( CommonMark\Interfaces\IVisitor $visitor ) : void
}

Table of Contents

  • CommonMark\Node\CodeBlock::__construct — CodeBlock Construction


CodeBlock Construction

  • « CommonMark\Node\CodeBlock
  • CommonMark\Node\HTMLBlock »
  • PHP Manual
  • CommonMark\Node\CodeBlock
  • CodeBlock Construction

CommonMark\Node\CodeBlock::__construct

(cmark >= 1.0.0)

CommonMark\Node\CodeBlock::__construct — CodeBlock Construction

Description

public CommonMark\Node\CodeBlock::__construct ( string $fence , string $literal )

Warning

This function is currently not documented; only its argument list is available.

Parameters

fence

literal


HTMLBlock concrete CommonMark\Node

(cmark >= 1.0.0)

Class synopsis

final CommonMark\Node\HTMLBlock extends CommonMark\Node\Text implements CommonMark\Interfaces\IVisitable , Traversable {
/* Inherited properties */
public readonly ?Node $parent ;
public readonly ?Node $previous ;
public readonly ?Node $next ;
public readonly ?Node $lastChild ;
public readonly ?Node $firstChild ;
public readonly int $startLine ;
public readonly int $endLine ;
public readonly int $startColumn ;
public readonly int $endColumn ;
public ?string $literal ;
/* Constructor */
public CommonMark\Node\Text::__construct ( void )
public CommonMark\Node\Text::__construct ( string $literal )
/* Inherited methods */
public CommonMark\Node::appendChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::prependChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::insertAfter ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::insertBefore ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::replace ( CommonMark\Node $target ) : CommonMark\Node
public CommonMark\Node::unlink ( void ) : void
public CommonMark\Node::accept ( CommonMark\Interfaces\IVisitor $visitor ) : void
}


HTMLInline concrete CommonMark\Node

(cmark >= 1.0.0)

Class synopsis

final CommonMark\Node\HTMLInline extends CommonMark\Node\Text implements CommonMark\Interfaces\IVisitable , Traversable {
/* Inherited properties */
public readonly ?Node $parent ;
public readonly ?Node $previous ;
public readonly ?Node $next ;
public readonly ?Node $lastChild ;
public readonly ?Node $firstChild ;
public readonly int $startLine ;
public readonly int $endLine ;
public readonly int $startColumn ;
public readonly int $endColumn ;
public ?string $literal ;
/* Constructor */
public CommonMark\Node\Text::__construct ( void )
public CommonMark\Node\Text::__construct ( string $literal )
/* Inherited methods */
public CommonMark\Node::appendChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::prependChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::insertAfter ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::insertBefore ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::replace ( CommonMark\Node $target ) : CommonMark\Node
public CommonMark\Node::unlink ( void ) : void
public CommonMark\Node::accept ( CommonMark\Interfaces\IVisitor $visitor ) : void
}


Image concrete CommonMark\Node

(cmark >= 1.0.0)

Class synopsis

final CommonMark\Node\Image extends CommonMark\Node implements CommonMark\Interfaces\IVisitable , Traversable {
/* Inherited properties */
public readonly ?Node $parent ;
public readonly ?Node $previous ;
public readonly ?Node $next ;
public readonly ?Node $lastChild ;
public readonly ?Node $firstChild ;
public readonly int $startLine ;
public readonly int $endLine ;
public readonly int $startColumn ;
public readonly int $endColumn ;
/* Properties */
public ?string $url ;
public ?string $title ;
/* Constructor */
public __construct ( void )
public __construct ( string $url )
public __construct ( string $url , string $title )
/* Inherited methods */
public CommonMark\Node::appendChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::prependChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::insertAfter ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::insertBefore ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::replace ( CommonMark\Node $target ) : CommonMark\Node
public CommonMark\Node::unlink ( void ) : void
public CommonMark\Node::accept ( CommonMark\Interfaces\IVisitor $visitor ) : void
}

Table of Contents

  • CommonMark\Node\Image::__construct — Image Construction


Image Construction

  • « CommonMark\Node\Image
  • CommonMark\Node\Link »
  • PHP Manual
  • CommonMark\Node\Image
  • Image Construction

CommonMark\Node\Image::__construct

(cmark >= 1.0.0)

CommonMark\Node\Image::__construct — Image Construction

Description

public CommonMark\Node\Image::__construct ( void )
public CommonMark\Node\Image::__construct ( string $url )
public CommonMark\Node\Image::__construct ( string $url , string $title )

Warning

This function is currently not documented; only its argument list is available.

Parameters

url

title


Link concrete CommonMark\Node

(cmark >= 1.0.0)

Class synopsis

final CommonMark\Node\Link extends CommonMark\Node implements CommonMark\Interfaces\IVisitable , Traversable {
/* Inherited properties */
public readonly ?Node $parent ;
public readonly ?Node $previous ;
public readonly ?Node $next ;
public readonly ?Node $lastChild ;
public readonly ?Node $firstChild ;
public readonly int $startLine ;
public readonly int $endLine ;
public readonly int $startColumn ;
public readonly int $endColumn ;
/* Properties */
public ?string $url ;
public ?string $title ;
/* Constructor */
public __construct ( void )
public __construct ( string $url )
public __construct ( string $url , string $title )
/* Inherited methods */
public CommonMark\Node::appendChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::prependChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::insertAfter ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::insertBefore ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::replace ( CommonMark\Node $target ) : CommonMark\Node
public CommonMark\Node::unlink ( void ) : void
public CommonMark\Node::accept ( CommonMark\Interfaces\IVisitor $visitor ) : void
}

Table of Contents

  • CommonMark\Node\Link::__construct — Link Construction


Link Construction

  • « CommonMark\Node\Link
  • CommonMark\Node\CustomBlock »
  • PHP Manual
  • CommonMark\Node\Link
  • Link Construction

CommonMark\Node\Link::__construct

(cmark >= 1.0.0)

CommonMark\Node\Link::__construct — Link Construction

Description

public CommonMark\Node\Link::__construct ( void )
public CommonMark\Node\Link::__construct ( string $url )
public CommonMark\Node\Link::__construct ( string $url , string $title )

Warning

This function is currently not documented; only its argument list is available.

Parameters

url

title


CustomBlock concrete CommonMark\Node

(cmark >= 1.0.0)

Class synopsis

final CommonMark\Node\CustomBlock extends CommonMark\Node implements CommonMark\Interfaces\IVisitable , Traversable {
/* Inherited properties */
public readonly ?Node $parent ;
public readonly ?Node $previous ;
public readonly ?Node $next ;
public readonly ?Node $lastChild ;
public readonly ?Node $firstChild ;
public readonly int $startLine ;
public readonly int $endLine ;
public readonly int $startColumn ;
public readonly int $endColumn ;
/* Properties */
public ?string $onEnter ;
public ?string $onLeave ;
/* Inherited methods */
public CommonMark\Node::appendChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::prependChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::insertAfter ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::insertBefore ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::replace ( CommonMark\Node $target ) : CommonMark\Node
public CommonMark\Node::unlink ( void ) : void
public CommonMark\Node::accept ( CommonMark\Interfaces\IVisitor $visitor ) : void
}


CustomInline concrete CommonMark\Node

(cmark >= 1.0.0)

Class synopsis

final CommonMark\Node\CustomInline extends CommonMark\Node implements CommonMark\Interfaces\IVisitable , Traversable {
/* Inherited properties */
public readonly ?Node $parent ;
public readonly ?Node $previous ;
public readonly ?Node $next ;
public readonly ?Node $lastChild ;
public readonly ?Node $firstChild ;
public readonly int $startLine ;
public readonly int $endLine ;
public readonly int $startColumn ;
public readonly int $endColumn ;
/* Properties */
public ?string $onEnter ;
public ?string $onLeave ;
/* Inherited methods */
public CommonMark\Node::appendChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::prependChild ( CommonMark\Node $child ) : CommonMark\Node
public CommonMark\Node::insertAfter ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::insertBefore ( CommonMark\Node $sibling ) : CommonMark\Node
public CommonMark\Node::replace ( CommonMark\Node $target ) : CommonMark\Node
public CommonMark\Node::unlink ( void ) : void
public CommonMark\Node::accept ( CommonMark\Interfaces\IVisitor $visitor ) : void
}


Abstract CommonMark\Node

(cmark >= 1.0.0)

Introduction

Represents an Abstract Node, this final abstract is not for direct use by the programmer.

Class synopsis

final abstract CommonMark\Node implements CommonMark\Interfaces\IVisitable , Traversable {
/* Properties */
public readonly ?Node $parent ;
public readonly ?Node $previous ;
public readonly ?Node $next ;
public readonly ?Node $lastChild ;
public readonly ?Node $firstChild ;
public readonly int $startLine ;
public readonly int $endLine ;
public readonly int $startColumn ;
public readonly int $endColumn ;
/* Methods */
public appendChild ( CommonMark\Node $child ) : CommonMark\Node
public prependChild ( CommonMark\Node $child ) : CommonMark\Node
public insertAfter ( CommonMark\Node $sibling ) : CommonMark\Node
public insertBefore ( CommonMark\Node $sibling ) : CommonMark\Node
public replace ( CommonMark\Node $target ) : CommonMark\Node
public unlink ( void ) : void
public accept ( CommonMark\Interfaces\IVisitor $visitor ) : void
}

Table of Contents

  • CommonMark\Node::appendChild — AST Manipulation
  • CommonMark\Node::prependChild — AST Manipulation
  • CommonMark\Node::insertAfter — AST Manipulation
  • CommonMark\Node::insertBefore — AST Manipulation
  • CommonMark\Node::replace — AST Manipulation
  • CommonMark\Node::unlink — AST Manipulation
  • CommonMark\Node::accept — Visitation


AST Manipulation

  • « CommonMark\Node
  • CommonMark\Node::prependChild »
  • PHP Manual
  • CommonMark\Node
  • AST Manipulation

CommonMark\Node::appendChild

(cmark >= 1.0.0)

CommonMark\Node::appendChild — AST Manipulation

Description

public CommonMark\Node::appendChild ( CommonMark\Node $child ) : CommonMark\Node

Warning

This function is currently not documented; only its argument list is available.

Parameters

child

Return Values


AST Manipulation

  • « CommonMark\Node::appendChild
  • CommonMark\Node::insertAfter »
  • PHP Manual
  • CommonMark\Node
  • AST Manipulation

CommonMark\Node::prependChild

(cmark >= 1.0.0)

CommonMark\Node::prependChild — AST Manipulation

Description

public CommonMark\Node::prependChild ( CommonMark\Node $child ) : CommonMark\Node

Warning

This function is currently not documented; only its argument list is available.

Parameters

child

Return Values


AST Manipulation

  • « CommonMark\Node::prependChild
  • CommonMark\Node::insertBefore »
  • PHP Manual
  • CommonMark\Node
  • AST Manipulation

CommonMark\Node::insertAfter

(cmark >= 1.0.0)

CommonMark\Node::insertAfter — AST Manipulation

Description

public CommonMark\Node::insertAfter ( CommonMark\Node $sibling ) : CommonMark\Node

Warning

This function is currently not documented; only its argument list is available.

Parameters

sibling

Return Values


AST Manipulation

  • « CommonMark\Node::insertAfter
  • CommonMark\Node::replace »
  • PHP Manual
  • CommonMark\Node
  • AST Manipulation

CommonMark\Node::insertBefore

(cmark >= 1.0.0)

CommonMark\Node::insertBefore — AST Manipulation

Description

public CommonMark\Node::insertBefore ( CommonMark\Node $sibling ) : CommonMark\Node

Warning

This function is currently not documented; only its argument list is available.

Parameters

sibling

Return Values


AST Manipulation

  • « CommonMark\Node::insertBefore
  • CommonMark\Node::unlink »
  • PHP Manual
  • CommonMark\Node
  • AST Manipulation

CommonMark\Node::replace

(cmark >= 1.0.0)

CommonMark\Node::replace — AST Manipulation

Description

public CommonMark\Node::replace ( CommonMark\Node $target ) : CommonMark\Node

Warning

This function is currently not documented; only its argument list is available.

Parameters

target

Return Values


AST Manipulation

  • « CommonMark\Node::replace
  • CommonMark\Node::accept »
  • PHP Manual
  • CommonMark\Node
  • AST Manipulation

CommonMark\Node::unlink

(cmark >= 1.0.0)

CommonMark\Node::unlink — AST Manipulation

Description

public CommonMark\Node::unlink ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Visitation

  • « CommonMark\Node::unlink
  • CommonMark\Interfaces\IVisitor »
  • PHP Manual
  • CommonMark\Node
  • Visitation

CommonMark\Node::accept

(cmark >= 1.0.0)

CommonMark\Node::accept — Visitation

Description

public CommonMark\Node::accept ( CommonMark\Interfaces\IVisitor $visitor ) : void

Parameters

visitor

An object implementing CommonMark\Interfaces\IVisitor

See Also

  • CommonMark\Interfaces\IVisitor::enter
  • CommonMark\Interfaces\IVisitor::leave


The CommonMark\Interfaces\IVisitor interface

(cmark >= 1.0.0)

Introduction

Class synopsis

final CommonMark\Interfaces\IVisitor {
/* Constants */
const integer Done ;
const integer Enter ;
const integer Leave ;
/* Methods */
abstract public enter ( IVisitable $visitable ) : ?int|IVisitable
abstract public leave ( IVisitable $visitable ) : ?int|IVisitable
}

Table of Contents

  • CommonMark\Interfaces\IVisitor::enter — Visitation
  • CommonMark\Interfaces\IVisitor::leave — Visitation


Visitation

  • « CommonMark\Interfaces\IVisitor
  • CommonMark\Interfaces\IVisitor::leave »
  • PHP Manual
  • CommonMark\Interfaces\IVisitor
  • Visitation

CommonMark\Interfaces\IVisitor::enter

(cmark >= 1.0.0)

CommonMark\Interfaces\IVisitor::enter — Visitation

Description

abstract public CommonMark\Interfaces\IVisitor::enter ( IVisitable $visitable ) : ?int|IVisitable

Parameters

visitable

The current CommonMark\Interfaces\IVisitable being entered

Return Values

Returning CommonMark\Interfaces\IVisitor::Done will cause the backing iterator to exit.

Returning CommonMark\Interfaces\IVisitor::Enter will reset the backing iterator at entering the current IVisitable

Returning CommonMark\Interfaces\IVisitor::Leave will reset the backing iterator at exiting the current IVisitable

Returning an IVisitable will reset the backing iterator at entering the given IVisitable

Returning nothing will allow the backing iterator to continue

See Also

  • CommonMark\Interfaces\IVisitable::accept


Visitation

  • « CommonMark\Interfaces\IVisitor::enter
  • CommonMark\Interfaces\IVisitable »
  • PHP Manual
  • CommonMark\Interfaces\IVisitor
  • Visitation

CommonMark\Interfaces\IVisitor::leave

(cmark >= 1.0.0)

CommonMark\Interfaces\IVisitor::leave — Visitation

Description

abstract public CommonMark\Interfaces\IVisitor::leave ( IVisitable $visitable ) : ?int|IVisitable

Parameters

visitable

The current CommonMark\Interfaces\IVisitable being exited

Return Values

Returning CommonMark\Interfaces\IVisitor::Done will cause the backing iterator to exit.

Returning CommonMark\Interfaces\IVisitor::Enter will reset the backing iterator at entering the current IVisitable

Returning CommonMark\Interfaces\IVisitor::Leave will reset the backing iterator at exiting the current IVisitable

Returning an IVisitable will reset the backing iterator at exiting the given IVisitable

Returning nothing will allow the backing iterator to continue

See Also

  • CommonMark\Interfaces\IVisitable::accept


The CommonMark\Interfaces\IVisitable interface

(cmark >= 1.0.0)

Introduction

Class synopsis

final CommonMark\Interfaces\IVisitable {
abstract public accept ( CommonMark\Interfaces\IVisitor $visitor ) : void
}

Table of Contents

  • CommonMark\Interfaces\IVisitable::accept — Visitation


Visitation

  • « CommonMark\Interfaces\IVisitable
  • CommonMark\Parser »
  • PHP Manual
  • CommonMark\Interfaces\IVisitable
  • Visitation

CommonMark\Interfaces\IVisitable::accept

(cmark >= 1.0.0)

CommonMark\Interfaces\IVisitable::accept — Visitation

Description

abstract public CommonMark\Interfaces\IVisitable::accept ( CommonMark\Interfaces\IVisitor $visitor ) : void

Parameters

visitor

An object implementing CommonMark\Interfaces\IVisitor

See Also

  • CommonMark\Interfaces\IVisitor::enter
  • CommonMark\Interfaces\IVisitor::leave


The CommonMark\Parser class

(cmark >= 1.0.0)

Introduction

Provides an incremental parser as an alternative to the simple Parsing API function

Class synopsis

final CommonMark\Parser {
/* Constructor */
public __construct ([ int $options ] )
/* Methods */
public parse ( string $buffer ) : void
public finish ( void ) : CommonMark\Node
}

Table of Contents

  • CommonMark\Parser::__construct — Parsing
  • CommonMark\Parser::parse — Parsing
  • CommonMark\Parser::finish — Parsing


Parsing

  • « CommonMark\Parser
  • CommonMark\Parser::parse »
  • PHP Manual
  • CommonMark\Parser
  • Parsing

CommonMark\Parser::__construct

(cmark >= 1.0.0)

CommonMark\Parser::__construct — Parsing

Description

public CommonMark\Parser::__construct ([ int $options ] )

Warning

This function is currently not documented; only its argument list is available.

Parameters

options

A mask of:

CommonMark\Parser\Normal (integer)
CommonMark\Parser\Normalize (integer)
CommonMark\Parser\ValidateUTF8 (integer)
CommonMark\Parser\Smart (integer)


Parsing

  • « CommonMark\Parser::__construct
  • CommonMark\Parser::finish »
  • PHP Manual
  • CommonMark\Parser
  • Parsing

CommonMark\Parser::parse

(cmark >= 1.0.0)

CommonMark\Parser::parse — Parsing

Description

public CommonMark\Parser::parse ( string $buffer ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

buffer

Return Values


Parsing

  • « CommonMark\Parser::parse
  • CommonMark\CQL »
  • PHP Manual
  • CommonMark\Parser
  • Parsing

CommonMark\Parser::finish

(cmark >= 1.0.0)

CommonMark\Parser::finish — Parsing

Description

public CommonMark\Parser::finish ( void ) : CommonMark\Node

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The CommonMark\CQL class

(cmark >= 1.1.0)

Introduction

CommonMark Query Language is a DSL for describing how to travel through a CommonMark Node tree implemented as a parser and compiler for a small set of instructions, and a virtual machine for executing those instructions.

Paths:

In it's most simplistic form, a CQL query combines the following paths and / to describe how to travel through a tree:

  • firstChild
  • lastChild
  • previous
  • next
  • parent
For example, /firstChild/lastChild would travel to the last child node of the first child node.

Loops

CQL can be instructed to loop, for example through the children of, or siblings to a particular node, by using the path children, or siblings. For example, /firstChild/children will travel to all the children of the first child node.

Subqueries

CQL can be instructed how to travel by using a subquery like [/firstChild]. For example, /firstChild/children[/firstChild] will travel to the first child node of all the children of the first child node.

Loop Constraints

While looping, CQL can be instructed to constrict the travelled path to nodes of particular type. For example /children(BlockQuote) will travel to the children of a node where the type is BlockQuote. The following types are recognized (case insensitively):

  • BlockQuote
  • List
  • Item
  • CodeBlock
  • HtmlBlock
  • CustomBlock
  • Paragraph
  • Heading
  • ThematicBreak
  • Text
  • SoftBreak
  • LineBreak
  • Code
  • HtmlInline
  • CustomInline
  • Emphasis
  • Strong
  • Link
  • Image
Types may be used as a union, for example /children(BlockQuote|List) will travel to the children of a node where the type is BlockQuote or List. Types, or unions of types, may be also negated. For example /children(~BlockQuote) will travel to the children of a node where the type is not BlockQuote, and /children(~BlockQuote|Paragraph) will travel to the children of a node where the type is not BlockQuote or Paragraph

Path Constraints

CQL can be instructed to create a loop to travel to a node of a particular type, at a particular path. For example, /firstChild(BlockQuote) will travel to the first child node where the type is BlockQuote. Note that like other loops for children and siblings, this kind of path can only be followed by a subquery.

Implementation Notes

While CQL has been implemented as part of the PHP CommonMark extension, it stands separately from PHP and does not use PHP's virtual machine or internal representation of values.

Class synopsis

CommonMark\CQL {
/* Constructor */
public __construct ( string $query )
/* Methods */
public __invoke ( \CommonMark\Node $root , callable $handler )
}

Table of Contents

  • CommonMark\CQL::__construct — CQL Construction
  • CommonMark\CQL::__invoke — CQL Execution


CQL Construction

  • « CommonMark\CQL
  • CommonMark\CQL::__invoke »
  • PHP Manual
  • CommonMark\CQL
  • CQL Construction

CommonMark\CQL::__construct

(cmark >= 1.1.0)

CommonMark\CQL::__construct — CQL Construction

Description

public CommonMark\CQL::__construct ( string $query )

Parameters

query

a CQL string


CQL Execution

  • « CommonMark\CQL::__construct
  • CommonMark Functions »
  • PHP Manual
  • CommonMark\CQL
  • CQL Execution

CommonMark\CQL::__invoke

(cmark >= 1.1.0)

CommonMark\CQL::__invoke — CQL Execution

Description

public CommonMark\CQL::__invoke ( \CommonMark\Node $root , callable $handler )

Shall invoke the current CQL function on the given root, executing the given handler on entry to a \CommonMark\Node

Parameters

root

the root node of a tree

handler

should have the prototype:

handler ( \CommonMark\Node $root , \CommonMark\Node $entering ) : ?bool
  • Should handler fail to return (void), or return null, CQL will continue executing
  • Should the handler return a truthy value, CQL will continue executing.
  • Should the handler return a falsy value, CQL will stop executing


CommonMark Functions

Table of Contents

  • CommonMark\Parse — Parsing
  • CommonMark\Render — Rendering
  • CommonMark\Render\HTML — Rendering
  • CommonMark\Render\Latex — Rendering
  • CommonMark\Render\Man — Rendering
  • CommonMark\Render\XML — Rendering


Parsing

  • « CommonMark Functions
  • CommonMark\Render »
  • PHP Manual
  • CommonMark Functions
  • Parsing

CommonMark\Parse

(cmark >= 1.0.0)

CommonMark\Parse — Parsing

Description

CommonMark\Parse ( string $content [, int $options ] ) : CommonMark\Node

Shall parse content

Parameters

content

markdown string

options

A mask of:

CommonMark\Parser\Normal (integer)
CommonMark\Parser\Normalize (integer)
CommonMark\Parser\ValidateUTF8 (integer)
CommonMark\Parser\Smart (integer)

Return Values

Shall return root CommonMark\Node


Rendering

  • « CommonMark\Parse
  • CommonMark\Render\HTML »
  • PHP Manual
  • CommonMark Functions
  • Rendering

CommonMark\Render

(cmark >= 1.0.0)

CommonMark\Render — Rendering

Description

CommonMark\Render ( CommonMark\Node $node [, int $options [, int $width ]] ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

node

options

A mask of:

CommonMark\Render\Normal (integer)
CommonMark\Render\SourcePos (integer)
CommonMark\Render\HardBreaks (integer)
CommonMark\Render\Safe (integer)
CommonMark\Render\NoBreaks (integer)
width

Return Values


Rendering

  • « CommonMark\Render
  • CommonMark\Render\Latex »
  • PHP Manual
  • CommonMark Functions
  • Rendering

CommonMark\Render\HTML

(cmark >= 1.0.0)

CommonMark\Render\HTML — Rendering

Description

CommonMark\Render\HTML ( CommonMark\Node $node [, int $options ] ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

node

options

A mask of:

CommonMark\Render\Normal (integer)
CommonMark\Render\SourcePos (integer)
CommonMark\Render\HardBreaks (integer)
CommonMark\Render\Safe (integer)
CommonMark\Render\NoBreaks (integer)

Return Values


Rendering

  • « CommonMark\Render\HTML
  • CommonMark\Render\Man »
  • PHP Manual
  • CommonMark Functions
  • Rendering

CommonMark\Render\Latex

(cmark >= 1.0.0)

CommonMark\Render\Latex — Rendering

Description

CommonMark\Render\Latex ( CommonMark\Node $node [, int $options [, int $width ]] ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

node

options

A mask of:

CommonMark\Render\Normal (integer)
CommonMark\Render\SourcePos (integer)
CommonMark\Render\HardBreaks (integer)
CommonMark\Render\Safe (integer)
CommonMark\Render\NoBreaks (integer)
width

Return Values


Rendering

  • « CommonMark\Render\Latex
  • CommonMark\Render\XML »
  • PHP Manual
  • CommonMark Functions
  • Rendering

CommonMark\Render\Man

(cmark >= 1.0.0)

CommonMark\Render\Man — Rendering

Description

CommonMark\Render\Man ( CommonMark\Node $node [, int $options [, int $width ]] ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

node

options

A mask of:

CommonMark\Render\Normal (integer)
CommonMark\Render\SourcePos (integer)
CommonMark\Render\HardBreaks (integer)
CommonMark\Render\Safe (integer)
CommonMark\Render\NoBreaks (integer)
width

Return Values


Rendering

  • « CommonMark\Render\Man
  • Parle »
  • PHP Manual
  • CommonMark Functions
  • Rendering

CommonMark\Render\XML

(cmark >= 1.0.0)

CommonMark\Render\XML — Rendering

Description

CommonMark\Render\XML ( CommonMark\Node $node [, int $options ] ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

node

options

A mask of:

CommonMark\Render\Normal (integer)
CommonMark\Render\SourcePos (integer)
CommonMark\Render\HardBreaks (integer)
CommonMark\Render\Safe (integer)
CommonMark\Render\NoBreaks (integer)

Return Values


Parsing and lexing

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
  • Predefined Constants
  • Pattern matching — Parle pattern matching
    • Character representations
    • Character classes
    • Unicode character classes
    • Alternation and repetition
    • Anchors
    • Grouping
  • Examples
    • Lexer examples
    • Parser examples
  • Parle\Lexer — The Parle\Lexer class
    • Parle\Lexer::advance — Process next lexer rule
    • Parle\Lexer::build — Finalize the lexer rule set
    • Parle\Lexer::callout — Define token callback
    • Parle\Lexer::consume — Pass the data for processing
    • Parle\Lexer::dump — Dump the state machine
    • Parle\Lexer::getToken — Retrieve the current token
    • Parle\Lexer::insertMacro — Insert regex macro
    • Parle\Lexer::push — Add a lexer rule
    • Parle\Lexer::reset — Reset lexer
  • Parle\RLexer — The Parle\RLexer class
    • Parle\RLexer::advance — Process next lexer rule
    • Parle\RLexer::build — Finalize the lexer rule set
    • Parle\RLexer::callout — Define token callback
    • Parle\RLexer::consume — Pass the data for processing
    • Parle\RLexer::dump — Dump the state machine
    • Parle\RLexer::getToken — Retrieve the current token
    • Parle\RLexer::insertMacro — Insert regex macro
    • Parle\RLexer::push — Add a lexer rule
    • Parle\RLexer::pushState — Push a new start state
    • Parle\RLexer::reset — Reset lexer
  • Parle\Parser — The Parle\Parser class
    • Parle\Parser::advance — Process next parser rule
    • Parle\Parser::build — Finalize the grammar rules
    • Parle\Parser::consume — Consume the data for processing
    • Parle\Parser::dump — Dump the grammar
    • Parle\Parser::errorInfo — Retrieve the error information
    • Parle\Parser::left — Declare a token with left-associativity
    • Parle\Parser::nonassoc — Declare a token with no associativity
    • Parle\Parser::precedence — Declare a precedence rule
    • Parle\Parser::push — Add a grammar rule
    • Parle\Parser::reset — Reset parser state
    • Parle\Parser::right — Declare a token with right-associativity
    • Parle\Parser::sigil — Retrieve a matching part of a rule
    • Parle\Parser::token — Declare a token
    • Parle\Parser::tokenId — Get token id
    • Parle\Parser::trace — Trace the parser operation
    • Parle\Parser::validate — Validate input
  • Parle\RParser — The Parle\RParser class
    • Parle\RParser::advance — Process next parser rule
    • Parle\RParser::build — Finalize the grammar rules
    • Parle\RParser::consume — Consume the data for processing
    • Parle\RParser::dump — Dump the grammar
    • Parle\RParser::errorInfo — Retrieve the error information
    • Parle\RParser::left — Declare a token with left-associativity
    • Parle\RParser::nonassoc — Declare a token with no associativity
    • Parle\RParser::precedence — Declare a precedence rule
    • Parle\RParser::push — Add a grammar rule
    • Parle\RParser::reset — Reset parser state
    • Parle\RParser::right — Declare a token with right-associativity
    • Parle\RParser::sigil — Retrieve a matching part of a rule
    • Parle\RParser::token — Declare a token
    • Parle\RParser::tokenId — Get token id
    • Parle\RParser::trace — Trace the parser operation
    • Parle\RParser::validate — Validate input
  • Parle\Stack — The Parle\Stack class
    • Parle\Stack::pop — Pop an item from the stack
    • Parle\Stack::push — Push an item into the stack
  • Parle\Token — The Parle\Token class
  • Parle\ErrorInfo — The Parle\ErrorInfo class
  • Parle\LexerException — The Parle\LexerException class
  • Parle\ParserException — The Parle\ParserException class


Introduction

The parle extension provides general purpose lexing and parsing facilities. The implementation is based on » Ben Hanson's libraries and requires a » C++14 capable compiler. The lexer is based on the regex matching, the parser is LALR(1). Lexers and parsers are generated on the fly and can be used immediately after they've been finalized. Parle deals with parsing and lexing, the appropriate data structures representation and processing are the implementer's task. Serialization and code generation are not supported by the extension, yet.

Lexer analysis is a process of splitting a character sequence into a list of lexemes. The lexeme list can be then used for the syntax analysis against a formal grammar. These operations are also known as lexing and parsing. This documentation doesn't aim to provide an exhaustive information on lexing and parsing. Good information in this regard is available on the numerous resources on the net. Several usage examples are included, to show the functionality. The extension is useful for PHP programmers both willing to learn or to utilize parsing and lexing. State machines and grammar parsing don't have to be implemented manually, these complex tasks are taken away by parle. Thanks to that, the development can be focused on the actual problem solving.

The common use case for parle is, when a data format is too complex to be handled by the regex matching with PCRE. The practical application is herewith wide. Be it a specific data format, a behavior modification of existing functions, even an own programming language and beyond. The helper methods such as Parle\Lexer::dump() to inspect the generated state machine, or Parle\Parser::dump() to inspect the generated grammar, are useful. The method Parle\Parser::trace() can also be used to track the parsing operation.


  • « Introduction
  • Requirements »
  • PHP Manual
  • Parle
  • Installing/Configuring

Installing/Configuring

Table of Contents

  • Requirements
  • Installation


Requirements

PHP 7.0 or above is supported. A C++14 capable compiler is required. A successful extension build was produced with at least clang 5.0, GCC 5.0 and Visual Studio 2015.


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/parle.

A DLL for this PECL extension is available under » http://windows.php.net/downloads/pecl/releases/parle/.

Available configure options
Option | Description
--enable-parle | Enable parle extension.
--enable-parle-utf32 | Enable internal UTF-32 support. Available since parle 0.7.2.


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.

Parle\INTERNAL_UTF32 boolean
Flag whether the internal UTF-32 support is compiled in. Available since parle 0.7.2.


Parle pattern matching

Table of Contents

  • Character representations
  • Character classes
  • Unicode character classes
  • Alternation and repetition
  • Anchors
  • Grouping

Parle supports regex matching similar to flex. Also supported are the following POSIX character sets: [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:] and [:xdigit:].

The Unicode character classes are currently not enabled by default, pass --enable-parle-utf32 to make them available. A particular encoding can be mapped with a correctly constructed regex. For example, to match the EURO symbol encoded in UTF-8, the regular expression [\xe2][\x82][\xac] can be used. The pattern for an UTF-8 encoded string could be [ -\x7f]{+}[\x80-\xbf]{+}[\xc2-\xdf]{+}[\xe0-\xef]{+}[\xf0-\xff]+.


Character representations

Character representations
Sequence | Description
\a | Alert (bell).
\b | Backspace.
\e | ESC character, \x1b.
\n | Newline.
\r | Carriage return.
\f | Form feed, \x0c.
\t | Horizontal tab, \x09.
\v | Vertical tab, \x0b.
\oct | Character specified by a three-digit octal code.
\xhex | Character specified by a hex code.
\cchar | Named control character.


Character classes

Character classes
Sequence | Description
[...] | A single character listed or contained within a listed range. Ranges can be combined with the {+} and {-} operators. For example [a-z]{+}[0-9] is the same as [0-9a-z] and [a-z]{-}[aeiou] is the same as [b-df-hj-np-tv-z].
[^...] | A single character not listed and not contained within a listed range.
. | Any character, default [^\n].
\d | Digit character, [0-9].
\D | Non-digit character, [^0-9].
\s | White space character, [ \t\n\r\f\v].
\S | Non-white space character, [^ \t\n\r\f\v].
\w | Word caracter, [a-zA-Z0-9_].
\W | Non-word caracter, [^a-zA-Z0-9_].


Unicode character classes

Unicode character classes
Sequence | Description
\p{C} | Other.
\p{Cc} | Other, control.
\p{Cf} | Other, format.
\p{Co} | Other, private use.
\p{Cs} | Other, surrogate.
\p{L} | Letter.
\p{LC} | Letter, cased.
\p{Ll} | Letter, lowercase.
\p{Lm} | Letter, modifier.
\p{Lo} | Letter, other.
\p{Lt} | Letter, titlecase.
\p{Lu} | Letter, uppercase.
\p{M} | Mark.
\p{Mc} | Mark, space combining.
\p{Me} | Mark, enclosing.
\p{Mn} | Mark, nonspacing.
\p{N} | Number.
\p{Nd} | Number, decimal digit.
\p{Nl} | Number, letter.
\p{No} | Number, other.
\p{P} | Punctuation.
\p{Pc} | Punctiation, connector.
\p{Pd} | Punctuation, dash.
\p{Pe} | Punctuation, close.
\p{Pf} | Punctuation, final quote.
\p{Pi} | Punctuation, initial quote.
\p{Po} | Punctuation, other.
\p{Ps} | Punctuation, open.
\p{S} | Symbol.
\p{Sc} | Symbol, currency.
\p{Sk} | Symbol, modifier.
\p{Sm} | Symbol, math.
\p{So} | Symbol, other.
\p{Z} | Separator.
\p{Zl} | Separator, line.
\p{Zp} | Separator, paragraph.
\p{Zs} | Separator, space.

These character clasess are only available, if the option --enable-parle-utf32 was passed at the compilation time.


Alternation and repetition

Alternation and repetition
Sequence | Greedy | Description
...|... | - | Try subpatterns in alternation.
* | yes | Match 0 or more times.
+ | yes | Match 1 or more times.
? | yes | Match 0 or 1 times.
{n} | no | Match exactly n times.
{n,} | yes | Match at least n times.
{n,m} | yes | Match at least n times but no more than m times.
*? | no | Match 0 or more times.
+? | no | Match 1 or more times.
?? | no | Match 0 or 1 times.
{n,}? | no | Match at least n times.
{n,m}? | no | Match at least n times but no more than m times.
{MACRO} | - | Include the regex MACRO in the current regex.


Anchors

Anchors
Sequence | Description
^ | Start of string or after a newline.
$ | End of string or before a newline.


Grouping

Grouping
Sequence | Description
(...) Group a regular expression to override default operator precedence.
(?r-s:pattern) Apply option r and omit option s while interpreting pattern. Options may be zero or more of the characters i, s, or x.
Options
Option | Description
i | Case insensitive.
-i | Case sensitive.
s | Alters the meaning of '.' to match any character whatsoever.
-s | "lters the meaning of '.' to match any character except '\n'.
x | Ignores comments and whitespace in patterns. Whitespace is ignored unless it is backslash-escaped, contained within ""s, or appears inside a character range.
These options can be applied globally at the rules level by passing a combination of the bit flags to the lexer.
(?# comment ) | Omit everything within (). The first ) character encountered ends the pattern. It is not possible for the comment to contain a ) character. The comment may span lines.


  • « Grouping
  • Lexer examples »
  • PHP Manual
  • Parle
  • Examples

Examples

Table of Contents

  • Lexer examples
  • Parser examples


Lexer examples

Example #1 Tokenize comma separated integer list

<?php

use Parle\Token;
use Parle\Lexer;
use Parle\LexerException;

/* name => id */
$token = array(
        "COMMA" => 1,
        "CRLF" => 2,
        "DECIMAL" => 3,
);
/* id => name */
$tokenIdToName = array_flip($token);

$lex = new Lexer;
$lex->push("[\x2c]", $token["COMMA"]);
$lex->push("[\r][\n]", $token["CRLF"]);
$lex->push("[\d]+", $token["DECIMAL"]);
$lex->build();

$in = "0,1,2\r\n3,42,5\r\n6,77,8\r\n";

$lex->consume($in);

do {
        $lex->advance();
        $tok = $lex->getToken();

        if (Token::UNKNOWN == $tok->id) {
                throw new LexerException("Unknown token '{$tok->value}' at offset {$lex->marker}.");
        }

        echo "TOKEN: ", $tokenIdToName[$tok->id], PHP_EOL;
} while (Token::EOI != $tok->id);

Example #2 Tokenize assign statement

<?php

use Parle\{Token, Lexer};

$lex = new Lexer;

$lex->push("\$[a-zA-Z_][a-zA-Z0-9_]*", 1);
$lex->push("=", 2);
$lex->push("\d+", 3);
$lex->push(";", 4);

$lex->build();

$lex->consume('$x = 42; $y = 24;');

do {
    $lex->advance();
    $tok = $lex->getToken();
    var_dump($tok);
} while (Token::EOI != $tok->id);


Parser examples

Example #1 Simple calculator

<?php

use Parle\{Parser, ParserException, Lexer, Token};

$p = new Parser;
$p->token("INTEGER");
$p->left("'+' '-' '*' '/'");

$p->push("start", "exp");
$prod_add = $p->push("exp", "exp '+' exp");
$prod_sub = $p->push("exp", "exp '-' exp");
$prod_mul = $p->push("exp", "exp '*' exp");
$prod_div = $p->push("exp", "exp '/' exp");
$p->push("exp", "INTEGER"); /* Production index unused. */

$p->build();

$lex = new Lexer;
$lex->push("[+]", $p->tokenId("'+'"));
$lex->push("[-]", $p->tokenId("'-'"));
$lex->push("[*]", $p->tokenId("'*'"));
$lex->push("[/]", $p->tokenId("'/'"));
$lex->push("\\d+", $p->tokenId("INTEGER"));
$lex->push("\\s+", Token::SKIP);

$lex->build();

$exp = array(
    "1 + 1",
    "33 / 10",
    "100 * 45",
    "17 - 45",
);

foreach ($exp as $in) {
    if (!$p->validate($in, $lex)) {
        throw new ParserException("Failed to validate input");
    }

    $p->consume($in, $lex);

    while (Parser::ACTION_ERROR != $p->action && Parser::ACTION_ACCEPT != $p->action) {
        switch ($p->action) {
            case Parser::ACTION_ERROR:
                throw new ParserException("Parser error");
                break;
            case Parser::ACTION_SHIFT:
            case Parser::ACTION_GOTO:
            case Parser::ACTION_ACCEPT:
                break;
            case Parser::ACTION_REDUCE:
                switch ($p->reduceId) {
                    case $prod_add:
                        $l = $p->sigil(0);
                        $r = $p->sigil(2);
                        echo "$l + $r = " . ($l + $r) . "\n";
                        break;
                    case $prod_sub:
                        $l = $p->sigil(0);
                        $r = $p->sigil(2);
                        echo "$l - $r = " . ($l - $r) . "\n";
                        break;
                    case $prod_mul:
                        $l = $p->sigil(0);
                        $r = $p->sigil(2);
                        echo "$l * $r = " . ($l * $r) . "\n";
                        break;
                    case $prod_div:
                        $l = $p->sigil(0);
                        $r = $p->sigil(2);
                    echo "$l / $r = " . ($l / $r) . "\n";
                        break;
            }
            break;
        }
        $p->advance();
    }
}

Example #2 Parse words out from a sentence

<?php

use Parle\{Lexer, Token, Parser, ParserException};

$p = new Parser;
$p->token("WORD");
$p->push("START", "SENTENCE");
$p->push("SENTENCE", "WORDS");
$prod_word_0 = $p->push("WORDS", "WORDS WORD");
$prod_word_1 = $p->push("WORDS", "WORD");
$p->build();

$lex = new Lexer;
$lex->push("[^\s]{-}[\.,\:\;\?]+", $p->tokenId("WORD"));
$lex->push("[\s\.,\:\;\?]+", Token::SKIP);
$lex->build();

$in = "Dis-moi où est ton papa?";
$p->consume($in, $lex);
do {
    switch ($p->action) {
    case Parser::ACTION_ERROR:
        throw new ParserException("Error");
        break;
    case Parser::ACTION_SHIFT:
    case Parser::ACTION_GOTO:
        /* var_dump($p->trace());*/
        break;
    case Parser::ACTION_REDUCE:
        $rid = $p->reduceId();
        if ($rid == $prod_word_1) {
            var_dump($p->sigil(0));
        } if ($rid == $prod_word_0) {
            var_dump($p->sigil(1));
        }
        break;
    }
    $p->advance();
} while (Parser::ACTION_ACCEPT != $p->action);


The Parle\Lexer class

(PECL parle >= 0.5.1)

Introduction

Single state lexer class. Lexemes can be defined on the fly. If the particular lexer instance is meant to be used with Parle\Parser, the token IDs need to be taken from there. Otherwise, arbitrary token IDs can be supplied. This lexer can give a certain performance advantage over Parle\RLexer, if no multiple states are required. Note, that Parle\RParser is not compatible with this lexer.

Class synopsis

Parle\Lexer {
/* Constants */
const integer ICASE = 1 ;
const integer DOT_NOT_LF = 2 ;
const integer DOT_NOT_CRLF = 4 ;
const integer SKIP_WS = 8 ;
const integer MATCH_ZERO_LEN = 16 ;
/* Properties */
public boolean $bol = FALSE ;
public integer $flags = 0 ;
public integer $state = 0 ;
public integer $marker = 0 ;
public integer $cursor = 0 ;
/* Methods */
public advance ( void ) : void
public build ( void ) : void
public callout ( int $id , callable $callback ) : void
public consume ( string $data ) : void
public dump ( void ) : void
public getToken ( void ) : Parle\Token
public insertMacro ( string $name , string $regex ) : void
public push ( string $regex , int $id ) : void
public reset ( int $pos ) : void
}

Predefined Constants

Parle\Lexer::ICASE

Parle\Lexer::DOT_NOT_LF

Parle\Lexer::DOT_NOT_CRLF

Parle\Lexer::SKIP_WS

Parle\Lexer::MATCH_ZERO_LEN

Properties

bol

Start of input flag.

flags

Lexer flags.

state

Current lexer state, readonly.

marker

Position of the latest token match, readonly.

cursor

Current input offset, readonly.

Table of Contents

  • Parle\Lexer::advance — Process next lexer rule
  • Parle\Lexer::build — Finalize the lexer rule set
  • Parle\Lexer::callout — Define token callback
  • Parle\Lexer::consume — Pass the data for processing
  • Parle\Lexer::dump — Dump the state machine
  • Parle\Lexer::getToken — Retrieve the current token
  • Parle\Lexer::insertMacro — Insert regex macro
  • Parle\Lexer::push — Add a lexer rule
  • Parle\Lexer::reset — Reset lexer


Process next lexer rule

  • « Parle\Lexer
  • Parle\Lexer::build »
  • PHP Manual
  • Parle\Lexer
  • Process next lexer rule

Parle\Lexer::advance

(PECL parle >= 0.5.1)

Parle\Lexer::advance — Process next lexer rule

Description

public Parle\Lexer::advance ( void ) : void

Processes the next rule and prepares the resulting token data.

Parameters

This function has no parameters.

Return Values

No value is returned.


Finalize the lexer rule set

  • « Parle\Lexer::advance
  • Parle\Lexer::callout »
  • PHP Manual
  • Parle\Lexer
  • Finalize the lexer rule set

Parle\Lexer::build

(PECL parle >= 0.5.1)

Parle\Lexer::build — Finalize the lexer rule set

Description

public Parle\Lexer::build ( void ) : void

Rules, previously added with Parle\Lexer::push() are finalized. This method call has to be done after all the necessary rules was pushed. The rule set becomes read only. The lexing can begin.

Parameters

This function has no parameters.

Return Values

No value is returned.


Define token callback

  • « Parle\Lexer::build
  • Parle\Lexer::consume »
  • PHP Manual
  • Parle\Lexer
  • Define token callback

Parle\Lexer::callout

(PECL parle >= 0.7.2)

Parle\Lexer::callout — Define token callback

Description

public Parle\Lexer::callout ( int $id , callable $callback ) : void

Define a callback to be invoked once lexer encounters a particular token.

Parameters

id

Token id.

callback

Callable to be invoked. The callable doesn't receive any arguments and its return value is ignored.

Return Values

No value is returned.


Pass the data for processing

  • « Parle\Lexer::callout
  • Parle\Lexer::dump »
  • PHP Manual
  • Parle\Lexer
  • Pass the data for processing

Parle\Lexer::consume

(PECL parle >= 0.5.1)

Parle\Lexer::consume — Pass the data for processing

Description

public Parle\Lexer::consume ( string $data ) : void

Consume the data for lexing.

Parameters

data

Data to be lexed.

Return Values

No value is returned.


Dump the state machine

  • « Parle\Lexer::consume
  • Parle\Lexer::getToken »
  • PHP Manual
  • Parle\Lexer
  • Dump the state machine

Parle\Lexer::dump

(PECL parle >= 0.5.1)

Parle\Lexer::dump — Dump the state machine

Description

public Parle\Lexer::dump ( void ) : void

Dump the current state machine to stdout.

Parameters

This function has no parameters.

Return Values

No value is returned.


Retrieve the current token

  • « Parle\Lexer::dump
  • Parle\Lexer::insertMacro »
  • PHP Manual
  • Parle\Lexer
  • Retrieve the current token

Parle\Lexer::getToken

(PECL parle >= 0.5.1)

Parle\Lexer::getToken — Retrieve the current token

Description

public Parle\Lexer::getToken ( void ) : Parle\Token

Retrieve the current token.

Parameters

This function has no parameters.

Return Values

Returns an instance of Parle\Token.


Insert regex macro

  • « Parle\Lexer::getToken
  • Parle\Lexer::push »
  • PHP Manual
  • Parle\Lexer
  • Insert regex macro

Parle\Lexer::insertMacro

(PECL parle >= 0.5.1)

Parle\Lexer::insertMacro — Insert regex macro

Description

public Parle\Lexer::insertMacro ( string $name , string $regex ) : void

Insert a regex macro, that can be later used as a shortcut and included in other regular expressions.

Parameters

name

Name of the macros.

regex

Regular expression.

Return Values

No value is returned.


Add a lexer rule

  • « Parle\Lexer::insertMacro
  • Parle\Lexer::reset »
  • PHP Manual
  • Parle\Lexer
  • Add a lexer rule

Parle\Lexer::push

(PECL parle >= 0.5.1)

Parle\Lexer::push — Add a lexer rule

Description

public Parle\Lexer::push ( string $regex , int $id ) : void

Push a pattern for lexeme recognition.

Parameters

regex

Regular expression used for token matching.

id

Token id. If the lexer instance is meant to be used standalone, this can be an arbitrary number. If the lexer instance is going to be passed to the parser, it has to be an id returned by Parle\Parser::tokenid().

Return Values

No value is returned.


Reset lexer

  • « Parle\Lexer::push
  • Parle\RLexer »
  • PHP Manual
  • Parle\Lexer
  • Reset lexer

Parle\Lexer::reset

(PECL parle >= 0.7.1)

Parle\Lexer::reset — Reset lexer

Description

public Parle\Lexer::reset ( int $pos ) : void

Reset lexing optionally supplying the desired offset.

Parameters

pos

Reset position.

Return Values

No value is returned.


The Parle\RLexer class

(PECL parle >= 0.5.1)

Introduction

Multistate lexer class. Lexemes can be defined on the fly. If the particular lexer instance is meant to be used with Parle\RParser, the token IDs need to be taken from there. Otherwise, arbitrary token IDs can be supplied. Note, that Parle\Parser is not compatible with this lexer.

Class synopsis

Parle\RLexer {
/* Constants */
const integer ICASE = 1 ;
const integer DOT_NOT_LF = 2 ;
const integer DOT_NOT_CRLF = 4 ;
const integer SKIP_WS = 8 ;
const integer MATCH_ZERO_LEN = 16 ;
/* Properties */
public boolean $bol = FALSE ;
public integer $flags = 0 ;
public integer $state = 0 ;
public integer $marker = 0 ;
public integer $cursor = 0 ;
/* Methods */
public advance ( void ) : void
public build ( void ) : void
public callout ( int $id , callable $callback ) : void
public consume ( string $data ) : void
public dump ( void ) : void
public getToken ( void ) : Parle\Token
public insertMacro ( string $name , string $regex ) : void
public push ( string $regex , int $id ) : void
public push ( string $state , string $regex , int $id , string $newState ) : void
public push ( string $state , string $regex , string $newState ) : void
public pushState ( string $state ) : int
public reset ( int $pos ) : void
}

Predefined Constants

Parle\RLexer::ICASE

Parle\RLexer::DOT_NOT_LF

Parle\RLexer::DOT_NOT_CRLF

Parle\RLexer::SKIP_WS

Parle\RLexer::MATCH_ZERO_LEN

Properties

bol

Start of input flag.

flags

Lexer flags.

state

Current lexer state, readonly.

marker

Position of the latest token match, readonly.

cursor

Current input offset, readonly.

Table of Contents

  • Parle\RLexer::advance — Process next lexer rule
  • Parle\RLexer::build — Finalize the lexer rule set
  • Parle\RLexer::callout — Define token callback
  • Parle\RLexer::consume — Pass the data for processing
  • Parle\RLexer::dump — Dump the state machine
  • Parle\RLexer::getToken — Retrieve the current token
  • Parle\RLexer::insertMacro — Insert regex macro
  • Parle\RLexer::push — Add a lexer rule
  • Parle\RLexer::pushState — Push a new start state
  • Parle\RLexer::reset — Reset lexer


Process next lexer rule

  • « Parle\RLexer
  • Parle\RLexer::build »
  • PHP Manual
  • Parle\RLexer
  • Process next lexer rule

Parle\RLexer::advance

(PECL parle >= 0.5.1)

Parle\RLexer::advance — Process next lexer rule

Description

public Parle\RLexer::advance ( void ) : void

Processes the next rule and prepares the resulting token data.

Parameters

This function has no parameters.

Return Values

No value is returned.


Finalize the lexer rule set

  • « Parle\RLexer::advance
  • Parle\RLexer::callout »
  • PHP Manual
  • Parle\RLexer
  • Finalize the lexer rule set

Parle\RLexer::build

(PECL parle >= 0.5.1)

Parle\RLexer::build — Finalize the lexer rule set

Description

public Parle\RLexer::build ( void ) : void

Rules, previously added with Parle\RLexer::push() are finalized. This method call has to be done after all the necessary rules was pushed. The rule set becomes read only. The lexing can begin.

Parameters

This function has no parameters.

Return Values

No value is returned.


Define token callback

  • « Parle\RLexer::build
  • Parle\RLexer::consume »
  • PHP Manual
  • Parle\RLexer
  • Define token callback

Parle\RLexer::callout

(PECL parle >= 0.7.2)

Parle\RLexer::callout — Define token callback

Description

public Parle\RLexer::callout ( int $id , callable $callback ) : void

Define a callback to be invoked once lexer encounters a particular token.

Parameters

id

Token id.

callback

Callable to be invoked. The callable doesn't receive any arguments and its return value is ignored.

Return Values

No value is returned.


Pass the data for processing

  • « Parle\RLexer::callout
  • Parle\RLexer::dump »
  • PHP Manual
  • Parle\RLexer
  • Pass the data for processing

Parle\RLexer::consume

(PECL parle >= 0.5.1)

Parle\RLexer::consume — Pass the data for processing

Description

public Parle\RLexer::consume ( string $data ) : void

Consume the data for lexing.

Parameters

data

Data to be lexed.

Return Values

No value is returned.


Dump the state machine

  • « Parle\RLexer::consume
  • Parle\RLexer::getToken »
  • PHP Manual
  • Parle\RLexer
  • Dump the state machine

Parle\RLexer::dump

(PECL parle >= 0.5.1)

Parle\RLexer::dump — Dump the state machine

Description

public Parle\RLexer::dump ( void ) : void

Dump the current state machine to stdout.

Parameters

This function has no parameters.

Return Values

No value is returned.


Retrieve the current token

  • « Parle\RLexer::dump
  • Parle\RLexer::insertMacro »
  • PHP Manual
  • Parle\RLexer
  • Retrieve the current token

Parle\RLexer::getToken

(PECL parle >= 0.5.1)

Parle\RLexer::getToken — Retrieve the current token

Description

public Parle\RLexer::getToken ( void ) : Parle\Token

Retrive the current token.

Parameters

This function has no parameters.

Return Values

Returns an instance of Parle\Token.


Insert regex macro

  • « Parle\RLexer::getToken
  • Parle\RLexer::push »
  • PHP Manual
  • Parle\RLexer
  • Insert regex macro

Parle\RLexer::insertMacro

(PECL parle >= 0.5.1)

Parle\RLexer::insertMacro — Insert regex macro

Description

public Parle\RLexer::insertMacro ( string $name , string $regex ) : void

Insert a regex macro, that can be later used as a shortcut and included in other regular expressions.

Parameters

name

Name of the macros.

regex

Regular expression.

Return Values

No value is returned.


Add a lexer rule

  • « Parle\RLexer::insertMacro
  • Parle\RLexer::pushState »
  • PHP Manual
  • Parle\RLexer
  • Add a lexer rule

Parle\RLexer::push

(PECL parle >= 0.5.1)

Parle\RLexer::push — Add a lexer rule

Description

public Parle\RLexer::push ( string $regex , int $id ) : void
public Parle\RLexer::push ( string $state , string $regex , int $id , string $newState ) : void
public Parle\RLexer::push ( string $state , string $regex , string $newState ) : void

Push a pattern for lexeme recognition.

A 'start state' and 'exit state' can be specified by using a suitable signature.

Parameters

regex

Regular expression used for token matching.

id

Token id. If the lexer instance is meant to be used standalone, this can be an arbitrary number. If the lexer instance is going to be passed to the parser, it has to be an id returned by Parle\RParser::tokenid().

state

State name. If '*' is used as start state, then the rule is applied to all lexer states.

newState

New state name, after the rule was applied.

If '.' is specified as the exit state, then the lexer state is unchanged when that rule matches. An exit state with '>' before the name means push. Use the signature without id for either continuation or to start matching, when a continuation or recursion is required.

If '<' is specified as exit state, it means pop. In that case, the signature containing the id can be used to identify the match. Note that even in the case an id is specified, the rule will finish first when all the previous pushes popped.

Return Values

No value is returned.


Push a new start state

  • « Parle\RLexer::push
  • Parle\RLexer::reset »
  • PHP Manual
  • Parle\RLexer
  • Push a new start state

Parle\RLexer::pushState

(PECL parle >= 0.5.1)

Parle\RLexer::pushState — Push a new start state

Description

public Parle\RLexer::pushState ( string $state ) : int

This lexer type can have more than one state machine. This allows you to lex different tokens depending on context, thus allowing simple parsing to take place. Once a state pushed, it can be used with a suitable Parle\RLexer::push() signature variant.

Parameters

state

Name of the state.

Return Values


Reset lexer

  • « Parle\RLexer::pushState
  • Parle\Parser »
  • PHP Manual
  • Parle\RLexer
  • Reset lexer

Parle\RLexer::reset

(PECL parle >= 0.7.1)

Parle\RLexer::reset — Reset lexer

Description

public Parle\RLexer::reset ( int $pos ) : void

Reset lexing optionally supplying the desired offset.

Parameters

pos

Reset position.

Return Values

No value is returned.


The Parle\Parser class

(PECL parle >= 0.5.1)

Introduction

Parser class. Rules can be defined on the fly. Once finalized, a Parle\Lexer instance is required to deliver the token stream.

Class synopsis

Parle\Parser {
/* Constants */
const integer ACTION_ERROR = 0 ;
const integer ACTION_SHIFT = 1 ;
const integer ACTION_REDUCE = 2 ;
const integer ACTION_GOTO = 3 ;
const integer ACTION_ACCEPT = 4 ;
const integer ERROR_SYNTAX = 0 ;
const integer ERROR_NON_ASSOCIATIVE = 1 ;
const integer ERROR_UNKNOWN_TOKEN = 2 ;
/* Properties */
public integer $action = 0 ;
public integer $reduceId = 0 ;
/* Methods */
public advance ( void ) : void
public build ( void ) : void
public consume ( string $data , Parle\Lexer $lexer ) : void
public dump ( void ) : void
public errorInfo ( void ) : Parle\ErrorInfo
public left ( string $tok ) : void
public nonassoc ( string $tok ) : void
public precedence ( string $tok ) : void
public push ( string $name , string $rule ) : int
public reset ([ int $tokenId ] ) : void
public right ( string $tok ) : void
public sigil ( int $idx ) : string
public token ( string $tok ) : void
public tokenId ( string $tok ) : int
public trace ( void ) : string
public validate ( string $data , Parle\Lexer $lexer ) : bool
}

Predefined Constants

Parle\Parser::ACTION_ERROR

Parle\Parser::ACTION_SHIFT

Parle\Parser::ACTION_REDUCE

Parle\Parser::ACTION_GOTO

Parle\Parser::ACTION_ACCEPT

Parle\Parser::ERROR_SYNTAX

Parle\Parser::ERROR_NON_ASSOCIATIVE

Parle\Parser::ERROR_UNKNOWN_TOKEN

Properties

action

Current parser action that matches one of the action class constants, readonly.

reduceId

Grammar rule id just processed in the reduce action. The value corresponds either to a token or to a production id. Readonly.

Table of Contents

  • Parle\Parser::advance — Process next parser rule
  • Parle\Parser::build — Finalize the grammar rules
  • Parle\Parser::consume — Consume the data for processing
  • Parle\Parser::dump — Dump the grammar
  • Parle\Parser::errorInfo — Retrieve the error information
  • Parle\Parser::left — Declare a token with left-associativity
  • Parle\Parser::nonassoc — Declare a token with no associativity
  • Parle\Parser::precedence — Declare a precedence rule
  • Parle\Parser::push — Add a grammar rule
  • Parle\Parser::reset — Reset parser state
  • Parle\Parser::right — Declare a token with right-associativity
  • Parle\Parser::sigil — Retrieve a matching part of a rule
  • Parle\Parser::token — Declare a token
  • Parle\Parser::tokenId — Get token id
  • Parle\Parser::trace — Trace the parser operation
  • Parle\Parser::validate — Validate input


Process next parser rule

  • « Parle\Parser
  • Parle\Parser::build »
  • PHP Manual
  • Parle\Parser
  • Process next parser rule

Parle\Parser::advance

(PECL parle >= 0.5.1)

Parle\Parser::advance — Process next parser rule

Description

public Parle\Parser::advance ( void ) : void

Process next parser rule.

Parameters

This function has no parameters.

Return Values

No value is returned.


Finalize the grammar rules

  • « Parle\Parser::advance
  • Parle\Parser::consume »
  • PHP Manual
  • Parle\Parser
  • Finalize the grammar rules

Parle\Parser::build

(PECL parle >= 0.5.1)

Parle\Parser::build — Finalize the grammar rules

Description

public Parle\Parser::build ( void ) : void

Any tokens and grammar rules previously added are finalized. The rule set becomes readonly and the parser is ready to start.

Parameters

This function has no parameters.

Return Values

No value is returned.


Consume the data for processing

  • « Parle\Parser::build
  • Parle\Parser::dump »
  • PHP Manual
  • Parle\Parser
  • Consume the data for processing

Parle\Parser::consume

(PECL parle >= 0.5.1)

Parle\Parser::consume — Consume the data for processing

Description

public Parle\Parser::consume ( string $data , Parle\Lexer $lexer ) : void

Consume the data for parsing.

Parameters

data

Data to be parsed.

lexer

A lexer object containing the lexing rules prepared for the particular grammar.

Return Values

No value is returned.


Dump the grammar

  • « Parle\Parser::consume
  • Parle\Parser::errorInfo »
  • PHP Manual
  • Parle\Parser
  • Dump the grammar

Parle\Parser::dump

(PECL parle >= 0.5.1)

Parle\Parser::dump — Dump the grammar

Description

public Parle\Parser::dump ( void ) : void

Dump the current grammar to stdout.

Parameters

This function has no parameters.

Return Values

No value is returned.


Retrieve the error information

  • « Parle\Parser::dump
  • Parle\Parser::left »
  • PHP Manual
  • Parle\Parser
  • Retrieve the error information

Parle\Parser::errorInfo

(PECL parle >= 0.5.1)

Parle\Parser::errorInfo — Retrieve the error information

Description

public Parle\Parser::errorInfo ( void ) : Parle\ErrorInfo

Retrieve the error information in case Parle\Parser::action() returned the error action.

Parameters

This function has no parameters.

Return Values

Returns an instance of Parle\ErrorInfo.


Declare a token with left-associativity

  • « Parle\Parser::errorInfo
  • Parle\Parser::nonassoc »
  • PHP Manual
  • Parle\Parser
  • Declare a token with left-associativity

Parle\Parser::left

(PECL parle >= 0.5.1)

Parle\Parser::left — Declare a token with left-associativity

Description

public Parle\Parser::left ( string $tok ) : void

Declare a terminal with left associativity.

Parameters

tok

Token name.

Return Values

No value is returned.


Declare a token with no associativity

  • « Parle\Parser::left
  • Parle\Parser::precedence »
  • PHP Manual
  • Parle\Parser
  • Declare a token with no associativity

Parle\Parser::nonassoc

(PECL parle >= 0.5.1)

Parle\Parser::nonassoc — Declare a token with no associativity

Description

public Parle\Parser::nonassoc ( string $tok ) : void

Declare a terminal, that cannot appear more than once in the row.

Parameters

tok

Token name.

Return Values

No value is returned.


Declare a precedence rule

  • « Parle\Parser::nonassoc
  • Parle\Parser::push »
  • PHP Manual
  • Parle\Parser
  • Declare a precedence rule

Parle\Parser::precedence

(PECL parle >= 0.5.1)

Parle\Parser::precedence — Declare a precedence rule

Description

public Parle\Parser::precedence ( string $tok ) : void

Declares a precedence rule for a fictitious terminal symbol. This rule can be later used in the specific grammar rules.

Parameters

tok

Token name.

Return Values

No value is returned.


Add a grammar rule

  • « Parle\Parser::precedence
  • Parle\Parser::reset »
  • PHP Manual
  • Parle\Parser
  • Add a grammar rule

Parle\Parser::push

(PECL parle >= 0.5.1)

Parle\Parser::push — Add a grammar rule

Description

public Parle\Parser::push ( string $name , string $rule ) : int

Push a grammar rule. The production id returned can be used later in the parsing process to identify the rule matched.

Parameters

name

Rule name.

rule

The rule to be added. The syntax is Bison compatible.

Return Values

Returns integer representing the rule index.


Reset parser state

  • « Parle\Parser::push
  • Parle\Parser::right »
  • PHP Manual
  • Parle\Parser
  • Reset parser state

Parle\Parser::reset

(PECL parle >= 0.7.1)

Parle\Parser::reset — Reset parser state

Description

public Parle\Parser::reset ([ int $tokenId ] ) : void

Reset parser state using the given token id.

Parameters

tokenId

Token id.

Return Values

No value is returned.


Declare a token with right-associativity

  • « Parle\Parser::reset
  • Parle\Parser::sigil »
  • PHP Manual
  • Parle\Parser
  • Declare a token with right-associativity

Parle\Parser::right

(PECL parle >= 0.5.1)

Parle\Parser::right — Declare a token with right-associativity

Description

public Parle\Parser::right ( string $tok ) : void

Declare a terminal with right associativity.

Parameters

tok

Token name.

Return Values

No value is returned.


Retrieve a matching part of a rule

  • « Parle\Parser::right
  • Parle\Parser::token »
  • PHP Manual
  • Parle\Parser
  • Retrieve a matching part of a rule

Parle\Parser::sigil

(PECL parle >= 0.5.1)

Parle\Parser::sigil — Retrieve a matching part of a rule

Description

public Parle\Parser::sigil ( int $idx ) : string

Retrieve a part of the match by a rule. This method is equivalent to the pseudo variable functionality in Bison.

Parameters

idx

Match index, zero based.

Return Values

Returns a string with the matched part.


Declare a token

  • « Parle\Parser::sigil
  • Parle\Parser::tokenId »
  • PHP Manual
  • Parle\Parser
  • Declare a token

Parle\Parser::token

(PECL parle >= 0.5.1)

Parle\Parser::token — Declare a token

Description

public Parle\Parser::token ( string $tok ) : void

Declare a terminal to be used in the grammar.

Parameters

tok

Token name.

Return Values

No value is returned.


Get token id

  • « Parle\Parser::token
  • Parle\Parser::trace »
  • PHP Manual
  • Parle\Parser
  • Get token id

Parle\Parser::tokenId

(PECL parle >= 0.5.1)

Parle\Parser::tokenId — Get token id

Description

public Parle\Parser::tokenId ( string $tok ) : int

Retrieve the id of the named token.

Parameters

tok

Name of the token as used in Parle\Parser::token().

Return Values

Returns integer representing the token id.


Trace the parser operation

  • « Parle\Parser::tokenId
  • Parle\Parser::validate »
  • PHP Manual
  • Parle\Parser
  • Trace the parser operation

Parle\Parser::trace

(PECL parle >= 0.5.1)

Parle\Parser::trace — Trace the parser operation

Description

public Parle\Parser::trace ( void ) : string

Retrieve the current parser operation description. This can be especially useful for studying the parser and to optimize the grammar.

Parameters

This function has no parameters.

Return Values

Returns a string with the trace information.


Validate input

  • « Parle\Parser::trace
  • Parle\RParser »
  • PHP Manual
  • Parle\Parser
  • Validate input

Parle\Parser::validate

(PECL parle >= 0.5.1)

Parle\Parser::validate — Validate input

Description

public Parle\Parser::validate ( string $data , Parle\Lexer $lexer ) : bool

Validate an input string. The string is parsed internally, thus this method is useful for the quick input validation.

Parameters

data

String to be validated.

lexer

A lexer object containing the lexing rules prepared for the particular grammar.

Return Values

Returns boolean witnessing whether the input chimes or not with the defined rules.


The Parle\RParser class

(PECL parle >= 0.7.0)

Introduction

Parser class. Rules can be defined on the fly. Once finalized, a Parle\RLexer instance is required to deliver the token stream.

Class synopsis

Parle\RParser {
/* Constants */
const integer ACTION_ERROR = 0 ;
const integer ACTION_SHIFT = 1 ;
const integer ACTION_REDUCE = 2 ;
const integer ACTION_GOTO = 3 ;
const integer ACTION_ACCEPT = 4 ;
const integer ERROR_SYNTAX = 0 ;
const integer ERROR_NON_ASSOCIATIVE = 1 ;
const integer ERROR_UNKNOWN_TOKEN = 2 ;
/* Properties */
public integer $action = 0 ;
public integer $reduceId = 0 ;
/* Methods */
public advance ( void ) : void
public build ( void ) : void
public consume ( string $data , Parle\RLexer $rlexer ) : void
public dump ( void ) : void
public errorInfo ( void ) : Parle\ErrorInfo
public left ( string $tok ) : void
public nonassoc ( string $tok ) : void
public precedence ( string $tok ) : void
public push ( string $name , string $rule ) : int
public reset ([ int $tokenId ] ) : void
public right ( string $tok ) : void
public sigil ([ int $idx ] ) : string
public token ( string $tok ) : void
public tokenId ( string $tok ) : int
public trace ( void ) : string
public validate ( string $data , Parle\RLexer $lexer ) : bool
}

Predefined Constants

Parle\RParser::ACTION_ERROR

Parle\RParser::ACTION_SHIFT

Parle\RParser::ACTION_REDUCE

Parle\RParser::ACTION_GOTO

Parle\RParser::ACTION_ACCEPT

Parle\RParser::ERROR_SYNTAX

Parle\RParser::ERROR_NON_ASSOCIATIVE

Parle\RParser::ERROR_UNKNOWN_TOKEN

Properties

action

Current parser action that matches one of the action class constants, readonly.

reduceId

Grammar rule id just processed in the reduce action. The value corresponds either to a token or to a production id. Readonly.

Table of Contents

  • Parle\RParser::advance — Process next parser rule
  • Parle\RParser::build — Finalize the grammar rules
  • Parle\RParser::consume — Consume the data for processing
  • Parle\RParser::dump — Dump the grammar
  • Parle\RParser::errorInfo — Retrieve the error information
  • Parle\RParser::left — Declare a token with left-associativity
  • Parle\RParser::nonassoc — Declare a token with no associativity
  • Parle\RParser::precedence — Declare a precedence rule
  • Parle\RParser::push — Add a grammar rule
  • Parle\RParser::reset — Reset parser state
  • Parle\RParser::right — Declare a token with right-associativity
  • Parle\RParser::sigil — Retrieve a matching part of a rule
  • Parle\RParser::token — Declare a token
  • Parle\RParser::tokenId — Get token id
  • Parle\RParser::trace — Trace the parser operation
  • Parle\RParser::validate — Validate input


Process next parser rule

  • « Parle\RParser
  • Parle\RParser::build »
  • PHP Manual
  • Parle\RParser
  • Process next parser rule

Parle\RParser::advance

(PECL parle >= 0.7.0)

Parle\RParser::advance — Process next parser rule

Description

public Parle\RParser::advance ( void ) : void

Prosess next parser rule.

Parameters

This function has no parameters.

Return Values

No value is returned.


Finalize the grammar rules

  • « Parle\RParser::advance
  • Parle\RParser::consume »
  • PHP Manual
  • Parle\RParser
  • Finalize the grammar rules

Parle\RParser::build

(PECL parle >= 0.7.0)

Parle\RParser::build — Finalize the grammar rules

Description

public Parle\RParser::build ( void ) : void

Any tokens and grammar rules previously added are finalized. The rule set becomes readonly and the parser is ready to start.

Parameters

This function has no parameters.

Return Values

No value is returned.


Consume the data for processing

  • « Parle\RParser::build
  • Parle\RParser::dump »
  • PHP Manual
  • Parle\RParser
  • Consume the data for processing

Parle\RParser::consume

(PECL parle >= 0.7.0)

Parle\RParser::consume — Consume the data for processing

Description

public Parle\RParser::consume ( string $data , Parle\RLexer $rlexer ) : void

Consume the data for parsing.

Parameters

data

Data to be parsed.

lexer

A lexer object containing the lexing rules prepared for the particular grammar.

Return Values

No value is returned.


Dump the grammar

  • « Parle\RParser::consume
  • Parle\RParser::errorInfo »
  • PHP Manual
  • Parle\RParser
  • Dump the grammar

Parle\RParser::dump

(PECL parle >= 0.7.0)

Parle\RParser::dump — Dump the grammar

Description

public Parle\RParser::dump ( void ) : void

Dump the current grammar to stdout.

Parameters

This function has no parameters.

Return Values

No value is returned.


Retrieve the error information

  • « Parle\RParser::dump
  • Parle\RParser::left »
  • PHP Manual
  • Parle\RParser
  • Retrieve the error information

Parle\RParser::errorInfo

(PECL parle >= 0.7.0)

Parle\RParser::errorInfo — Retrieve the error information

Description

public Parle\RParser::errorInfo ( void ) : Parle\ErrorInfo

Retrieve the error information in case Parle\RParser::action() returned the error action.

Parameters

This function has no parameters.

Return Values

Returns an instance of Parle\ErrorInfo.


Declare a token with left-associativity

  • « Parle\RParser::errorInfo
  • Parle\RParser::nonassoc »
  • PHP Manual
  • Parle\RParser
  • Declare a token with left-associativity

Parle\RParser::left

(PECL parle >= 0.7.0)

Parle\RParser::left — Declare a token with left-associativity

Description

public Parle\RParser::left ( string $tok ) : void

Declare a terminal with left associativity.

Parameters

tok

Token name.

Return Values

No value is returned.


Declare a token with no associativity

  • « Parle\RParser::left
  • Parle\RParser::precedence »
  • PHP Manual
  • Parle\RParser
  • Declare a token with no associativity

Parle\RParser::nonassoc

(PECL parle >= 0.7.0)

Parle\RParser::nonassoc — Declare a token with no associativity

Description

public Parle\RParser::nonassoc ( string $tok ) : void

Declare a terminal, that cannot appear more than once in the row.

Parameters

tok

Token name.

Return Values

No value is returned.


Declare a precedence rule

  • « Parle\RParser::nonassoc
  • Parle\RParser::push »
  • PHP Manual
  • Parle\RParser
  • Declare a precedence rule

Parle\RParser::precedence

(PECL parle >= 0.7.0)

Parle\RParser::precedence — Declare a precedence rule

Description

public Parle\RParser::precedence ( string $tok ) : void

Declares a precedence rule for a fictious terminal symbol. This rule can be later used in the specific grammar rules.

Parameters

tok

Token name.

Return Values

No value is returned.


Add a grammar rule

  • « Parle\RParser::precedence
  • Parle\RParser::reset »
  • PHP Manual
  • Parle\RParser
  • Add a grammar rule

Parle\RParser::push

(PECL parle >= 0.7.0)

Parle\RParser::push — Add a grammar rule

Description

public Parle\RParser::push ( string $name , string $rule ) : int

Push a grammar rule. The production id returned can be used later in the parsing process to identify the rule matched.

Parameters

name

Rule name.

rule

The rule to be added. The syntax is Bison compatible.

Return Values

Returns integer representing the rule index.


Reset parser state

  • « Parle\RParser::push
  • Parle\RParser::right »
  • PHP Manual
  • Parle\RParser
  • Reset parser state

Parle\RParser::reset

(PECL parle >= 0.7.1)

Parle\RParser::reset — Reset parser state

Description

public Parle\RParser::reset ([ int $tokenId ] ) : void

Reset parser state using the given token id.

Parameters

tokenId

Token id.

Return Values

No value is returned.


Declare a token with right-associativity

  • « Parle\RParser::reset
  • Parle\RParser::sigil »
  • PHP Manual
  • Parle\RParser
  • Declare a token with right-associativity

Parle\RParser::right

(PECL parle >= 0.7.0)

Parle\RParser::right — Declare a token with right-associativity

Description

public Parle\RParser::right ( string $tok ) : void

Declare a terminal with right associativity.

Parameters

tok

Token name.

Return Values

No value is returned.


Retrieve a matching part of a rule

  • « Parle\RParser::right
  • Parle\RParser::token »
  • PHP Manual
  • Parle\RParser
  • Retrieve a matching part of a rule

Parle\RParser::sigil

(PECL parle >= 0.7.0)

Parle\RParser::sigil — Retrieve a matching part of a rule

Description

public Parle\RParser::sigil ([ int $idx ] ) : string

Retrieve a part of the match by a rule. This method is equivalent to the pseudo variable functionality in Bison.

Parameters

idx

Match index, zero based.

Return Values

Returns a string with the matched part.


Declare a token

  • « Parle\RParser::sigil
  • Parle\RParser::tokenId »
  • PHP Manual
  • Parle\RParser
  • Declare a token

Parle\RParser::token

(PECL parle >= 0.7.0)

Parle\RParser::token — Declare a token

Description

public Parle\RParser::token ( string $tok ) : void

Declare a terminal to be used in the grammar.

Parameters

tok

Token name.

Return Values

No value is returned.


Get token id

  • « Parle\RParser::token
  • Parle\RParser::trace »
  • PHP Manual
  • Parle\RParser
  • Get token id

Parle\RParser::tokenId

(PECL parle >= 0.7.0)

Parle\RParser::tokenId — Get token id

Description

public Parle\RParser::tokenId ( string $tok ) : int

Retrieve the id of the named token.

Parameters

tok

Name of the token as used in Parle\RParser::token().

Return Values

Returns integer representing the token id.


Trace the parser operation

  • « Parle\RParser::tokenId
  • Parle\RParser::validate »
  • PHP Manual
  • Parle\RParser
  • Trace the parser operation

Parle\RParser::trace

(PECL parle >= 0.7.0)

Parle\RParser::trace — Trace the parser operation

Description

public Parle\RParser::trace ( void ) : string

Retrieve the current parser operation description. This can be especially useful to study the parser and to optimize the grammar.

Parameters

This function has no parameters.

Return Values

Returns a string with the trace information.


Validate input

  • « Parle\RParser::trace
  • Parle\Stack »
  • PHP Manual
  • Parle\RParser
  • Validate input

Parle\RParser::validate

(PECL parle >= 0.7.0)

Parle\RParser::validate — Validate input

Description

public Parle\RParser::validate ( string $data , Parle\RLexer $lexer ) : bool

Validate an input string. The string is parsed internally, thus this method is useful for the quick input validation.

Parameters

data

String to be validated.

lexer

A lexer object containing the lexing rules prepared for the particular grammar.

Return Values

Returns boolean whitnessing whether the input chimes or not with the defined rules.


The Parle\Stack class

(PECL parle >= 0.7.0)

Introduction

Parle\Stack is a LIFO stack. The elements are inserted and removed only from one end.

Class synopsis

Parle\Stack {
/* Properties */
public boolean $empty = TRUE ;
public integer $size = 0 ;
public mixed $top ;
/* Methods */
public pop ( void ) : void
public push ( mixed $item ) : void
}

Properties

empty

Whether the stack is empty, readonly.

size

Stack size, readonly.

top

Element on the top of the stack.

Table of Contents

  • Parle\Stack::pop — Pop an item from the stack
  • Parle\Stack::push — Push an item into the stack


Pop an item from the stack

  • « Parle\Stack
  • Parle\Stack::push »
  • PHP Manual
  • Parle\Stack
  • Pop an item from the stack

Parle\Stack::pop

(PECL parle >= 0.5.1)

Parle\Stack::pop — Pop an item from the stack

Description

public Parle\Stack::pop ( void ) : void

Parameters

This function has no parameters.

Return Values

No value is returned.


Push an item into the stack

  • « Parle\Stack::pop
  • Parle\Token »
  • PHP Manual
  • Parle\Stack
  • Push an item into the stack

Parle\Stack::push

(PECL parle >= 0.5.1)

Parle\Stack::push — Push an item into the stack

Description

public Parle\Stack::push ( mixed $item ) : void

Parameters

item

Variable to be pushed.

Return Values

No value is returned.


The Parle\Token class

(PECL parle >= 0.5.2)

Introduction

This class represents a token. Lexer returns instances of this class.

Class synopsis

Parle\Token {
/* Constants */
const integer EOI = 0 ;
const integer UNKNOWN = -1 ;
const integer SKIP = -2 ;
/* Properties */
public integer $id ;
public string $value ;
/* Methods */
}

Properties

id

Token id.

value

Token value.

Predefined Constants

Parle\Token::EOI

End of input token id.

Parle\Token::UNKNOWN

Unknown token id.

Parle\Token::SKIP

Skip token id.


The Parle\ErrorInfo class

(PECL parle >= 0.5.2)

Introduction

The class represents detailed error information as supplied by Parle\Parser::errorInfo()

Class synopsis

Parle\ErrorInfo {
/* Properties */
public integer $id ;
public integer $position ;
public mixed $token ;
/* Methods */
}

Properties

id

Error id.

position

Position in the input, where the error occurred.

token

If applicable - the Parle\Token related to the error, otherwise NULL.


The Parle\LexerException class

(PECL parle >= 0.5.1)

Introduction

Class synopsis

Parle\LexerException extends Exception implements Throwable {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Methods */
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


The Parle\ParserException class

(PECL parle >= 0.5.1)

Introduction

Class synopsis

Parle\ParserException extends Exception implements Throwable {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Methods */
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


Regular Expressions (Perl-Compatible)

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • PCRE Patterns
    • PCRE regex syntax — Pattern Syntax
    • Possible modifiers in regex patterns — Pattern Modifiers
    • Differences From Perl — Perl Differences
    • Differences from POSIX regex
  • PCRE Functions
    • preg_filter — Perform a regular expression search and replace
    • preg_grep — Return array entries that match the pattern
    • preg_last_error — Returns the error code of the last PCRE regex execution
    • preg_match_all — Perform a global regular expression match
    • preg_match — Perform a regular expression match
    • preg_quote — Quote regular expression characters
    • preg_replace_callback_array — Perform a regular expression search and replace using callbacks
    • preg_replace_callback — Perform a regular expression search and replace using a callback
    • preg_replace — Perform a regular expression search and replace
    • preg_split — Split string by a regular expression


Introduction

The syntax for patterns used in these functions closely resembles Perl. The expression must be enclosed in the delimiters, a forward slash (/), for example. Delimiters can be any non-alphanumeric, non-whitespace ASCII character except the backslash (\) and the null byte. If the delimiter character has to be used in the expression itself, it needs to be escaped by backslash. Perl-style (), {}, [], and <> matching delimiters may also be used. See Pattern Syntax for detailed explanation.

The ending delimiter may be followed by various modifiers that affect the matching. See Pattern Modifiers.

PHP also supports regular expressions using a POSIX-extended syntax using the POSIX-extended regex functions.

Note:

This extension maintains a global per-thread cache of compiled regular expressions (up to 4096).

Warning

You should be aware of some limitations of PCRE. Read » http://www.pcre.org/pcre.txt for more info.

The PCRE library is a set of functions that implement regular expression pattern matching using the same syntax and semantics as Perl 5, with just a few differences (see below). The current implementation corresponds to Perl 5.005.


Installation

The PCRE extension is a core PHP extension, so it is always enabled. By default, this extension is compiled using the bundled PCRE library. Alternatively, an external PCRE library can be used by passing in the --with-pcre-regex=DIR configuration option where DIR is the location of PCRE's include and library files. It is recommended to use PCRE 8.10 or newer for PHP 5.6 and 7.0.

As of PHP 7.0.0 PCRE's just-in-time compilation is supported by default, which can be disabled with the --without-pcre-jit configuration option as of PHP 7.0.12.

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.

Note:

Before PHP 5.3.0, this extension could be disabled by passing in the --without-pcre-regex configuration option.

PCRE is an active project and as it changes so does the PHP functionality that relies upon it. It is possible that certain parts of the PHP documentation is outdated, in that it may not cover the newest features that PCRE provides. For a list of changes, see the » PCRE library changelog and also the following bundled PCRE history:

Upgrade history of the bundled PCRE library
PHP Version | Updated PCRE Version | Notes
7.3.0 | 10.32 |
7.2.0 | 8.41 |
7.0.3 / 5.6.18 / 5.5.32 | 8.38 | See CVE-2015-8383, CVE-2015-8386, CVE-2015-8387, CVE-2015-8389, CVE-2015-8390, CVE-2015-8391, CVE-2015-8393, CVE-2015-8394
7.0.0 / 5.6.9 / 5.5.26 / 5.4.41 | 8.37 | See CVE-2015-2325, CVE-2015-2326
5.6.0 / 5.5.10 | 8.34 |
5.5.0 / 5.4.14 / 5.3.24 | 8.32 |
5.4.9 / 5.3.19 | 8.31 |
5.3.7 | 8.12 |
5.3.6 | 8.11 |
5.3.4 | 8.10 |
5.3.3 / 5.2.14 | 8.02 |
5.3.2 | 8.00 |
5.3.0 / 5.2.13 | 7.9 |
5.2.7 | 7.8 |
5.2.6 | 7.6 |
5.2.5 | 7.3 |
5.2.4 | 7.2 |
5.2.2 | 7.0 |
5.2.0 | 6.7 |
5.1.3 | 6.6 |
5.1.0 | 6.2 |
5.0.5 | 5.0 |
5.0.0 | 4.5 |


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

PCRE Configuration Options
Name | Default | Changeable | Changelog
pcre.backtrack_limit | "1000000" | PHP_INI_ALL | Available since PHP 5.2.0.
pcre.recursion_limit | "100000" | PHP_INI_ALL | Available since PHP 5.2.0.
pcre.jit | "1" | PHP_INI_ALL | Available since PHP 7.0.0.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

pcre.backtrack_limit integer

PCRE's backtracking limit. Defaults to 100000 for PHP < 5.3.7.

pcre.recursion_limit integer

PCRE's recursion limit. Please note that if you set this value to a high number you may consume all the available process stack and eventually crash PHP (due to reaching the stack size limit imposed by the Operating System).

pcre.jit boolean

Whether PCRE's just-in-time compilation is going to be used.


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.

PREG constants
Constants | Description | As of
PREG_PATTERN_ORDER | Orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on. This flag is only used with preg_match_all(). |
PREG_SET_ORDER | Orders results so that $matches[0] is an array of first set of matches, $matches[1] is an array of second set of matches, and so on. This flag is only used with preg_match_all(). |
PREG_OFFSET_CAPTURE | See the description of PREG_SPLIT_OFFSET_CAPTURE. |
PREG_SPLIT_NO_EMPTY | This flag tells preg_split() to return only non-empty pieces. |
PREG_SPLIT_DELIM_CAPTURE | This flag tells preg_split() to capture parenthesized expression in the delimiter pattern as well. |
PREG_SPLIT_OFFSET_CAPTURE | If this flag is set, for every occurring match the appendant string offset will also be returned. Note that this changes the return values in an array where every element is an array consisting of the matched string at offset 0 and its string offset within subject at offset 1. This flag is only used for preg_split(). |
PREG_UNMATCHED_AS_NULL | This flag tells preg_match() and preg_match_all() to include unmatched subpatterns in $matches as NULL values. Without this flag, unmatched subpatterns are reported as empty strings, as if they were empty matches. Setting this flag allows to distinguish between these two cases. | 7.2.0
PREG_NO_ERROR | Returned by preg_last_error() if there were no errors. | 5.2.0
PREG_INTERNAL_ERROR | Returned by preg_last_error() if there was an internal PCRE error. | 5.2.0
PREG_BACKTRACK_LIMIT_ERROR | Returned by preg_last_error() if backtrack limit was exhausted. | 5.2.0
PREG_RECURSION_LIMIT_ERROR | Returned by preg_last_error() if recursion limit was exhausted. | 5.2.0
PREG_BAD_UTF8_ERROR | Returned by preg_last_error() if the last error was caused by malformed UTF-8 data (only when running a regex in UTF-8 mode). | 5.2.0
PREG_BAD_UTF8_OFFSET_ERROR | Returned by preg_last_error() if the offset didn't correspond to the begin of a valid UTF-8 code point (only when running a regex in UTF-8 mode). | 5.3.0
PREG_JIT_STACKLIMIT_ERROR | Returned by preg_last_error() if the last PCRE function failed due to limited JIT stack space. | 7.0.0
PCRE_VERSION | PCRE version and release date (e.g. "7.0 18-Dec-2006"). | 5.2.4


Examples

Example #1 Examples of valid patterns

  • /<\/\w+>/
  • |(\d{3})-\d+|Sm
  • /^(?i)php[34]/
  • {^\s+(\s+)?$}

Example #2 Examples of invalid patterns

  • /href='(.*)' - missing ending delimiter
  • /\w+\s*\w+/J - unknown modifier 'J'
  • 1-\d3-\d3-\d4| - missing starting delimiter


PCRE Patterns

Table of Contents

  • PCRE regex syntax
  • Possible modifiers in regex patterns
  • Differences From Perl
  • Differences from POSIX regex


Pattern Syntax

Table of Contents

  • Introduction
  • Delimiters
  • Meta-characters
  • Escape sequences
  • Unicode character properties
  • Anchors
  • Dot
  • Character classes
  • Alternation
  • Internal option setting
  • Subpatterns
  • Repetition
  • Back references
  • Assertions
  • Once-only subpatterns
  • Conditional subpatterns
  • Comments
  • Recursive patterns
  • Performance


Introduction

The syntax and semantics of the regular expressions supported by PCRE are described below. Regular expressions are also described in the Perl documentation and in a number of other books, some of which have copious examples. Jeffrey Friedl's "Mastering Regular Expressions", published by O'Reilly (ISBN 1-56592-257-3), covers them in great detail. The description here is intended as reference documentation.

A regular expression is a pattern that is matched against a subject string from left to right. Most characters stand for themselves in a pattern, and match the corresponding characters in the subject. As a trivial example, the pattern The quick brown fox matches a portion of a subject string that is identical to itself.


Delimiters

When using the PCRE functions, it is required that the pattern is enclosed by delimiters. A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character.

Often used delimiters are forward slashes (/), hash signs (#) and tildes (~). The following are all examples of valid delimited patterns.

/foo bar/
#^[^0-9]$#
+php+
%[a-zA-Z0-9_-]%

It is also possible to use bracket style delimiters where the opening and closing brackets are the starting and ending delimiter, respectively. (), {}, [] and <> are all valid bracket style delimiter pairs.

(this [is] a (pattern))
{this [is] a (pattern)}
[this [is] a (pattern)]
<this [is] a (pattern)>
Bracket style delimiters do not need to be escaped when they are used as meta characters within the pattern, but as with other delimiters they must be escaped when they are used as literal characters.

If the delimiter needs to be matched inside the pattern it must be escaped using a backslash. If the delimiter appears often inside the pattern, it is a good idea to choose another delimiter in order to increase readability.

/http:\/\//
#http://#
The preg_quote() function may be used to escape a string for injection into a pattern and its optional second parameter may be used to specify the delimiter to be escaped.

You may add pattern modifiers after the ending delimiter. The following is an example of case-insensitive matching:

#[a-z]#i


Meta-characters

The power of regular expressions comes from the ability to include alternatives and repetitions in the pattern. These are encoded in the pattern by the use of meta-characters, which do not stand for themselves but instead are interpreted in some special way.

There are two different sets of meta-characters: those that are recognized anywhere in the pattern except within square brackets, and those that are recognized in square brackets. Outside square brackets, the meta-characters are as follows:

Meta-characters outside square brackets
Meta-character | Description
\ | general escape character with several uses
^ | assert start of subject (or line, in multiline mode)
$ | assert end of subject or before a terminating newline (or end of line, in multiline mode)
. | match any character except newline (by default)
[ | start character class definition
] | end character class definition
| | start of alternative branch
( | start subpattern
) | end subpattern
? | extends the meaning of (, also 0 or 1 quantifier, also makes greedy quantifiers lazy (see repetition)
* | 0 or more quantifier
+ | 1 or more quantifier
{ | start min/max quantifier
} | end min/max quantifier
Part of a pattern that is in square brackets is called a character class. In a character class the only meta-characters are:
Meta-characters inside square brackets (character classes)
Meta-character | Description
\ | general escape character
^ | negate the class, but only if the first character
- | indicates character range
The following sections describe the use of each of the meta-characters.


Escape sequences

The backslash character has several uses. Firstly, if it is followed by a non-alphanumeric character, it takes away any special meaning that character may have. This use of backslash as an escape character applies both inside and outside character classes.

For example, if you want to match a "*" character, you write "\*" in the pattern. This applies whether or not the following character would otherwise be interpreted as a meta-character, so it is always safe to precede a non-alphanumeric with "\" to specify that it stands for itself. In particular, if you want to match a backslash, you write "\\".

Note:

Single and double quoted PHP strings have special meaning of backslash. Thus if \ has to be matched with a regular expression \\, then "\\\\" or '\\\\' must be used in PHP code.

If a pattern is compiled with the PCRE_EXTENDED option, whitespace in the pattern (other than in a character class) and characters between a "#" outside a character class and the next newline character are ignored. An escaping backslash can be used to include a whitespace or "#" character as part of the pattern.

A second use of backslash provides a way of encoding non-printing characters in patterns in a visible manner. There is no restriction on the appearance of non-printing characters, apart from the binary zero that terminates a pattern, but when a pattern is being prepared by text editing, it is usually easier to use one of the following escape sequences than the binary character it represents:

\a
alarm, that is, the BEL character (hex 07)
\cx
"control-x", where x is any character
\e
escape (hex 1B)
\f
formfeed (hex 0C)
\n
newline (hex 0A)
\p{xx}
a character with the xx property, see unicode properties for more info
\P{xx}
a character without the xx property, see unicode properties for more info
\r
carriage return (hex 0D)
\R
line break: matches \n, \r and \r\n
\t
tab (hex 09)
\xhh
character with hex code hh
\ddd
character with octal code ddd, or backreference

The precise effect of "\cx" is as follows: if "x" is a lower case letter, it is converted to upper case. Then bit 6 of the character (hex 40) is inverted. Thus "\cz" becomes hex 1A, but "\c{" becomes hex 3B, while "\c;" becomes hex 7B.

After "\x", up to two hexadecimal digits are read (letters can be in upper or lower case). In UTF-8 mode, "\x{...}" is allowed, where the contents of the braces is a string of hexadecimal digits. It is interpreted as a UTF-8 character whose code number is the given hexadecimal number. The original hexadecimal escape sequence, \xhh, matches a two-byte UTF-8 character if the value is greater than 127.

After "\0" up to two further octal digits are read. In both cases, if there are fewer than two digits, just those that are present are used. Thus the sequence "\0\x\07" specifies two binary zeros followed by a BEL character. Make sure you supply two digits after the initial zero if the character that follows is itself an octal digit.

The handling of a backslash followed by a digit other than 0 is complicated. Outside a character class, PCRE reads it and any following digits as a decimal number. If the number is less than 10, or if there have been at least that many previous capturing left parentheses in the expression, the entire sequence is taken as a back reference. A description of how this works is given later, following the discussion of parenthesized subpatterns.

Inside a character class, or if the decimal number is greater than 9 and there have not been that many capturing subpatterns, PCRE re-reads up to three octal digits following the backslash, and generates a single byte from the least significant 8 bits of the value. Any subsequent digits stand for themselves. For example:

\040
is another way of writing a space
\40
is the same, provided there are fewer than 40 previous capturing subpatterns
\7
is always a back reference
\11
might be a back reference, or another way of writing a tab
\011
is always a tab
\0113
is a tab followed by the character "3"
\113
is the character with octal code 113 (since there can be no more than 99 back references)
\377
is a byte consisting entirely of 1 bits
\81
is either a back reference, or a binary zero followed by the two characters "8" and "1"

Note that octal values of 100 or greater must not be introduced by a leading zero, because no more than three octal digits are ever read.

All the sequences that define a single byte value can be used both inside and outside character classes. In addition, inside a character class, the sequence "\b" is interpreted as the backspace character (hex 08). Outside a character class it has a different meaning (see below).

The third use of backslash is for specifying generic character types:

\d
any decimal digit
\D
any character that is not a decimal digit
\h
any horizontal whitespace character (since PHP 5.2.4)
\H
any character that is not a horizontal whitespace character (since PHP 5.2.4)
\s
any whitespace character
\S
any character that is not a whitespace character
\v
any vertical whitespace character (since PHP 5.2.4)
\V
any character that is not a vertical whitespace character (since PHP 5.2.4)
\w
any "word" character
\W
any "non-word" character

Each pair of escape sequences partitions the complete set of characters into two disjoint sets. Any given character matches one, and only one, of each pair.

The "whitespace" characters are HT (9), LF (10), FF (12), CR (13), and space (32). However, if locale-specific matching is happening, characters with code points in the range 128-255 may also be considered as whitespace characters, for instance, NBSP (A0).

A "word" character is any letter or digit or the underscore character, that is, any character which can be part of a Perl "word". The definition of letters and digits is controlled by PCRE's character tables, and may vary if locale-specific matching is taking place. For example, in the "fr" (French) locale, some character codes greater than 128 are used for accented letters, and these are matched by \w.

These character type sequences can appear both inside and outside character classes. They each match one character of the appropriate type. If the current matching point is at the end of the subject string, all of them fail, since there is no character to match.

The fourth use of backslash is for certain simple assertions. An assertion specifies a condition that has to be met at a particular point in a match, without consuming any characters from the subject string. The use of subpatterns for more complicated assertions is described below. The backslashed assertions are

\b
word boundary
\B
not a word boundary
\A
start of subject (independent of multiline mode)
\Z
end of subject or newline at end (independent of multiline mode)
\z
end of subject (independent of multiline mode)
\G
first matching position in subject

These assertions may not appear in character classes (but note that "\b" has a different meaning, namely the backspace character, inside a character class).

A word boundary is a position in the subject string where the current character and the previous character do not both match \w or \W (i.e. one matches \w and the other matches \W), or the start or end of the string if the first or last character matches \w, respectively.

The \A, \Z, and \z assertions differ from the traditional circumflex and dollar (described in anchors ) in that they only ever match at the very start and end of the subject string, whatever options are set. They are not affected by the PCRE_MULTILINE or PCRE_DOLLAR_ENDONLY options. The difference between \Z and \z is that \Z matches before a newline that is the last character of the string as well as at the end of the string, whereas \z matches only at the end.

The \G assertion is true only when the current matching position is at the start point of the match, as specified by the offset argument of preg_match(). It differs from \A when the value of offset is non-zero.

\Q and \E can be used to ignore regexp metacharacters in the pattern. For example: \w+\Q.$.\E$ will match one or more word characters, followed by literals .$. and anchored at the end of the string.

\K can be used to reset the match start since PHP 5.2.4. For example, the pattern foo\Kbar matches "foobar", but reports that it has matched "bar". The use of \K does not interfere with the setting of captured substrings. For example, when the pattern (foo)\Kbar matches "foobar", the first substring is still set to "foo".


Unicode character properties

Since 5.1.0, three additional escape sequences to match generic character types are available when UTF-8 mode is selected. They are:

\p{xx}
a character with the xx property
\P{xx}
a character without the xx property
\X
an extended Unicode sequence

The property names represented by xx above are limited to the Unicode general category properties. Each character has exactly one such property, specified by a two-letter abbreviation. For compatibility with Perl, negation can be specified by including a circumflex between the opening brace and the property name. For example, \p{^Lu} is the same as \P{Lu}.

If only one letter is specified with \p or \P, it includes all the properties that start with that letter. In this case, in the absence of negation, the curly brackets in the escape sequence are optional; these two examples have the same effect:

\p{L}
\pL

Supported property codes
Property | Matches | Notes
C | Other |
Cc | Control |
Cf | Format |
Cn | Unassigned |
Co | Private use |
Cs | Surrogate |
L | Letter | Includes the following properties: Ll, Lm, Lo, Lt and Lu.
Ll | Lower case letter |
Lm | Modifier letter |
Lo | Other letter |
Lt | Title case letter |
Lu | Upper case letter |
M | Mark |
Mc | Spacing mark |
Me | Enclosing mark |
Mn | Non-spacing mark |
N | Number |
Nd | Decimal number |
Nl | Letter number |
No | Other number |
P | Punctuation |
Pc | Connector punctuation |
Pd | Dash punctuation |
Pe | Close punctuation |
Pf | Final punctuation |
Pi | Initial punctuation |
Po | Other punctuation |
Ps | Open punctuation |
S | Symbol |
Sc | Currency symbol |
Sk | Modifier symbol |
Sm | Mathematical symbol |
So | Other symbol |
Z | Separator |
Zl | Line separator |
Zp | Paragraph separator |
Zs | Space separator |

Extended properties such as InMusicalSymbols are not supported by PCRE.

Specifying case-insensitive (caseless) matching does not affect these escape sequences. For example, \p{Lu} always matches only upper case letters.

Sets of Unicode characters are defined as belonging to certain scripts. A character from one of these sets can be matched using a script name. For example:

  • \p{Greek}
  • \P{Han}

Those that are not part of an identified script are lumped together as Common. The current list of scripts is:

Supported scripts
Arabic | Armenian | Avestan | Balinese | Bamum
Batak | Bengali | Bopomofo | Brahmi | Braille
Buginese | Buhid | Canadian_Aboriginal | Carian | Chakma
Cham | Cherokee | Common | Coptic | Cuneiform
Cypriot | Cyrillic | Deseret | Devanagari | Egyptian_Hieroglyphs
Ethiopic | Georgian | Glagolitic | Gothic | Greek
Gujarati | Gurmukhi | Han | Hangul | Hanunoo
Hebrew | Hiragana | Imperial_Aramaic | Inherited | Inscriptional_Pahlavi
Inscriptional_Parthian | Javanese | Kaithi | Kannada | Katakana
Kayah_Li | Kharoshthi | Khmer | Lao | Latin
Lepcha | Limbu | Linear_B | Lisu | Lycian
Lydian | Malayalam | Mandaic | Meetei_Mayek | Meroitic_Cursive
Meroitic_Hieroglyphs | Miao | Mongolian | Myanmar | New_Tai_Lue
Nko | Ogham | Old_Italic | Old_Persian | Old_South_Arabian
Old_Turkic | Ol_Chiki | Oriya | Osmanya | Phags_Pa
Phoenician | Rejang | Runic | Samaritan | Saurashtra
Sharada | Shavian | Sinhala | Sora_Sompeng | Sundanese
Syloti_Nagri | Syriac | Tagalog | Tagbanwa | Tai_Le
Tai_Tham | Tai_Viet | Takri | Tamil | Telugu
Thaana | Thai | Tibetan | Tifinagh | Ugaritic
Vai | Yi |  |  |

The \X escape matches a Unicode extended grapheme cluster. An extended grapheme cluster is one or more Unicode characters that combine to form a single glyph. In effect, this can be thought of as the Unicode equivalent of . as it will match one composed character, regardless of how many individual characters are actually used to render it.

In versions of PCRE older than 8.32 (which corresponds to PHP versions before 5.4.14 when using the bundled PCRE library), \X is equivalent to (?>\PM\pM*). That is, it matches a character without the "mark" property, followed by zero or more characters with the "mark" property, and treats the sequence as an atomic group (see below). Characters with the "mark" property are typically accents that affect the preceding character.

Matching characters by Unicode property is not fast, because PCRE has to search a structure that contains data for over fifteen thousand characters. That is why the traditional escape sequences such as \d and \w do not use Unicode properties in PCRE.


Anchors

Outside a character class, in the default matching mode, the circumflex character (^) is an assertion which is true only if the current matching point is at the start of the subject string. Inside a character class, circumflex (^) has an entirely different meaning (see below).

Circumflex (^) need not be the first character of the pattern if a number of alternatives are involved, but it should be the first thing in each alternative in which it appears if the pattern is ever to match that branch. If all possible alternatives start with a circumflex (^), that is, if the pattern is constrained to match only at the start of the subject, it is said to be an "anchored" pattern. (There are also other constructs that can cause a pattern to be anchored.)

A dollar character ($) is an assertion which is TRUE only if the current matching point is at the end of the subject string, or immediately before a newline character that is the last character in the string (by default). Dollar ($) need not be the last character of the pattern if a number of alternatives are involved, but it should be the last item in any branch in which it appears. Dollar has no special meaning in a character class.

The meaning of dollar can be changed so that it matches only at the very end of the string, by setting the PCRE_DOLLAR_ENDONLY option at compile or matching time. This does not affect the \Z assertion.

The meanings of the circumflex and dollar characters are changed if the PCRE_MULTILINE option is set. When this is the case, they match immediately after and immediately before an internal "\n" character, respectively, in addition to matching at the start and end of the subject string. For example, the pattern /^abc$/ matches the subject string "def\nabc" in multiline mode, but not otherwise. Consequently, patterns that are anchored in single line mode because all branches start with "^" are not anchored in multiline mode. The PCRE_DOLLAR_ENDONLY option is ignored if PCRE_MULTILINE is set.

Note that the sequences \A, \Z, and \z can be used to match the start and end of the subject in both modes, and if all branches of a pattern start with \A is it always anchored, whether PCRE_MULTILINE is set or not.


Dot

Outside a character class, a dot in the pattern matches any one character in the subject, including a non-printing character, but not (by default) newline. If the PCRE_DOTALL option is set, then dots match newlines as well. The handling of dot is entirely independent of the handling of circumflex and dollar, the only relationship being that they both involve newline characters. Dot has no special meaning in a character class.

\C can be used to match single byte. It makes sense in UTF-8 mode where full stop matches the whole character which can consist of multiple bytes.


Character classes

An opening square bracket introduces a character class, terminated by a closing square bracket. A closing square bracket on its own is not special. If a closing square bracket is required as a member of the class, it should be the first data character in the class (after an initial circumflex, if present) or escaped with a backslash.

A character class matches a single character in the subject; the character must be in the set of characters defined by the class, unless the first character in the class is a circumflex, in which case the subject character must not be in the set defined by the class. If a circumflex is actually required as a member of the class, ensure it is not the first character, or escape it with a backslash.

For example, the character class [aeiou] matches any lower case vowel, while [^aeiou] matches any character that is not a lower case vowel. Note that a circumflex is just a convenient notation for specifying the characters which are in the class by enumerating those that are not. It is not an assertion: it still consumes a character from the subject string, and fails if the current pointer is at the end of the string.

When case-insensitive (caseless) matching is set, any letters in a class represent both their upper case and lower case versions, so for example, an insensitive [aeiou] matches "A" as well as "a", and an insensitive [^aeiou] does not match "A", whereas a sensitive (caseful) version would.

The newline character is never treated in any special way in character classes, whatever the setting of the PCRE_DOTALL or PCRE_MULTILINE options is. A class such as [^a] will always match a newline.

The minus (hyphen) character can be used to specify a range of characters in a character class. For example, [d-m] matches any letter between d and m, inclusive. If a minus character is required in a class, it must be escaped with a backslash or appear in a position where it cannot be interpreted as indicating a range, typically as the first or last character in the class.

It is not possible to have the literal character "]" as the end character of a range. A pattern such as [W-]46] is interpreted as a class of two characters ("W" and "-") followed by a literal string "46]", so it would match "W46]" or "-46]". However, if the "]" is escaped with a backslash it is interpreted as the end of range, so [W-\]46] is interpreted as a single class containing a range followed by two separate characters. The octal or hexadecimal representation of "]" can also be used to end a range.

Ranges operate in ASCII collating sequence. They can also be used for characters specified numerically, for example [\000-\037]. If a range that includes letters is used when case-insensitive (caseless) matching is set, it matches the letters in either case. For example, [W-c] is equivalent to [][\^_`wxyzabc], matched case-insensitively, and if character tables for the "fr" locale are in use, [\xc8-\xcb] matches accented E characters in both cases.

The character types \d, \D, \s, \S, \w, and \W may also appear in a character class, and add the characters that they match to the class. For example, [\dABCDEF] matches any hexadecimal digit. A circumflex can conveniently be used with the upper case character types to specify a more restricted set of characters than the matching lower case type. For example, the class [^\W_] matches any letter or digit, but not underscore.

All non-alphanumeric characters other than \, -, ^ (at the start) and the terminating ] are non-special in character classes, but it does no harm if they are escaped. The pattern terminator is always special and must be escaped when used within an expression.

Perl supports the POSIX notation for character classes. This uses names enclosed by [: and :] within the enclosing square brackets. PCRE also supports this notation. For example, [01[:alpha:]%] matches "0", "1", any alphabetic character, or "%". The supported class names are:

Character classes
alnum | letters and digits
alpha | letters
ascii | character codes 0 - 127
blank | space or tab only
cntrl | control characters
digit | decimal digits (same as \d)
graph | printing characters, excluding space
lower | lower case letters
print | printing characters, including space
punct | printing characters, excluding letters and digits
space | white space (not quite the same as \s)
upper | upper case letters
word | "word" characters (same as \w)
xdigit | hexadecimal digits
The space characters are HT (9), LF (10), VT (11), FF (12), CR (13), and space (32). Notice that this list includes the VT character (code 11). This makes "space" different to \s, which does not include VT (for Perl compatibility).

The name word is a Perl extension, and blank is a GNU extension from Perl 5.8. Another Perl extension is negation, which is indicated by a ^ character after the colon. For example, [12[:^digit:]] matches "1", "2", or any non-digit.

In UTF-8 mode, characters with values greater than 128 do not match any of the POSIX character classes. As of PHP 5.3.0 and libpcre 8.10 some character classes are changed to use Unicode character properties, in which case the mentioned restriction does not apply. Refer to the » PCRE(3) manual for details.

Unicode character properties can appear inside a character class. They can not be part of a range. The minus (hyphen) character after a Unicode character class will match literally. Trying to end a range with a Unicode character property will result in a warning.


Alternation

Vertical bar characters are used to separate alternative patterns. For example, the pattern gilbert|sullivan matches either "gilbert" or "sullivan". Any number of alternatives may appear, and an empty alternative is permitted (matching the empty string). The matching process tries each alternative in turn, from left to right, and the first one that succeeds is used. If the alternatives are within a subpattern (defined below), "succeeds" means matching the rest of the main pattern as well as the alternative in the subpattern.


Internal option setting

The settings of PCRE_CASELESS, PCRE_MULTILINE, PCRE_DOTALL, PCRE_UNGREEDY, PCRE_EXTRA, PCRE_EXTENDED and PCRE_DUPNAMES can be changed from within the pattern by a sequence of Perl option letters enclosed between "(?" and ")". The option letters are:

Internal option letters
i | for PCRE_CASELESS
m | for PCRE_MULTILINE
s | for PCRE_DOTALL
x | for PCRE_EXTENDED
U | for PCRE_UNGREEDY
X | for PCRE_EXTRA (no longer supported as of PHP 7.3.0)
J | for PCRE_INFO_JCHANGED

For example, (?im) sets case-insensitive (caseless), multiline matching. It is also possible to unset these options by preceding the letter with a hyphen, and a combined setting and unsetting such as (?im-sx), which sets PCRE_CASELESS and PCRE_MULTILINE while unsetting PCRE_DOTALL and PCRE_EXTENDED, is also permitted. If a letter appears both before and after the hyphen, the option is unset.

When an option change occurs at top level (that is, not inside subpattern parentheses), the change applies to the remainder of the pattern that follows. So /ab(?i)c/ matches only "abc" and "abC".

If an option change occurs inside a subpattern, the effect is different. This is a change of behaviour in Perl 5.005. An option change inside a subpattern affects only that part of the subpattern that follows it, so (a(?i)b)c matches abc and aBc and no other strings (assuming PCRE_CASELESS is not used). By this means, options can be made to have different settings in different parts of the pattern. Any changes made in one alternative do carry on into subsequent branches within the same subpattern. For example, (a(?i)b|c) matches "ab", "aB", "c", and "C", even though when matching "C" the first branch is abandoned before the option setting. This is because the effects of option settings happen at compile time. There would be some very weird behaviour otherwise.

The PCRE-specific options PCRE_UNGREEDY and PCRE_EXTRA can be changed in the same way as the Perl-compatible options by using the characters U and X respectively. The (?X) flag setting is special in that it must always occur earlier in the pattern than any of the additional features it turns on, even when it is at top level. It is best put at the start.


Subpatterns

Subpatterns are delimited by parentheses (round brackets), which can be nested. Marking part of a pattern as a subpattern does two things:

  1. It localizes a set of alternatives. For example, the pattern cat(aract|erpillar|) matches one of the words "cat", "cataract", or "caterpillar". Without the parentheses, it would match "cataract", "erpillar" or the empty string.

  2. It sets up the subpattern as a capturing subpattern (as defined above). When the whole pattern matches, that portion of the subject string that matched the subpattern is passed back to the caller via the ovector argument of pcre_exec(). Opening parentheses are counted from left to right (starting from 1) to obtain the numbers of the capturing subpatterns.

For example, if the string "the red king" is matched against the pattern the ((red|white) (king|queen)) the captured substrings are "red king", "red", and "king", and are numbered 1, 2, and 3.

The fact that plain parentheses fulfill two functions is not always helpful. There are often times when a grouping subpattern is required without a capturing requirement. If an opening parenthesis is followed by "?:", the subpattern does not do any capturing, and is not counted when computing the number of any subsequent capturing subpatterns. For example, if the string "the white queen" is matched against the pattern the ((?:red|white) (king|queen)) the captured substrings are "white queen" and "queen", and are numbered 1 and 2. The maximum number of captured substrings is 65535. It may not be possible to compile such large patterns, however, depending on the configuration options of libpcre.

As a convenient shorthand, if any option settings are required at the start of a non-capturing subpattern, the option letters may appear between the "?" and the ":". Thus the two patterns

(?i:saturday|sunday)
(?:(?i)saturday|sunday)

match exactly the same set of strings. Because alternative branches are tried from left to right, and options are not reset until the end of the subpattern is reached, an option setting in one branch does affect subsequent branches, so the above patterns match "SUNDAY" as well as "Saturday".

It is possible to name a subpattern using the syntax (?P<name>pattern). This subpattern will then be indexed in the matches array by its normal numeric position and also by name. PHP 5.2.2 introduced two alternative syntaxes (?<name>pattern) and (?'name'pattern).

Sometimes it is necessary to have multiple matching, but alternating subgroups in a regular expression. Normally, each of these would be given their own backreference number even though only one of them would ever possibly match. To overcome this, the (?| syntax allows having duplicate numbers. Consider the following regex matched against the string Sunday:

(?:(Sat)ur|(Sun))day

Here Sun is stored in backreference 2, while backreference 1 is empty. Matching yields Sat in backreference 1 while backreference 2 does not exist. Changing the pattern to use the (?| fixes this problem:

(?|(Sat)ur|(Sun))day

Using this pattern, both Sun and Sat would be stored in backreference 1.


Repetition

Repetition is specified by quantifiers, which can follow any of the following items:

  • a single character, possibly escaped
  • the . metacharacter
  • a character class
  • a back reference (see next section)
  • a parenthesized subpattern (unless it is an assertion - see below)

The general repetition quantifier specifies a minimum and maximum number of permitted matches, by giving the two numbers in curly brackets (braces), separated by a comma. The numbers must be less than 65536, and the first must be less than or equal to the second. For example: z{2,4} matches "zz", "zzz", or "zzzz". A closing brace on its own is not a special character. If the second number is omitted, but the comma is present, there is no upper limit; if the second number and the comma are both omitted, the quantifier specifies an exact number of required matches. Thus [aeiou]{3,} matches at least 3 successive vowels, but may match many more, while \d{8} matches exactly 8 digits. An opening curly bracket that appears in a position where a quantifier is not allowed, or one that does not match the syntax of a quantifier, is taken as a literal character. For example, {,6} is not a quantifier, but a literal string of four characters.

The quantifier {0} is permitted, causing the expression to behave as if the previous item and the quantifier were not present.

For convenience (and historical compatibility) the three most common quantifiers have single-character abbreviations:

Single-character quantifiers
* | equivalent to {0,}
+ | equivalent to {1,}
? | equivalent to {0,1}

It is possible to construct infinite loops by following a subpattern that can match no characters with a quantifier that has no upper limit, for example: (a?)*

Earlier versions of Perl and PCRE used to give an error at compile time for such patterns. However, because there are cases where this can be useful, such patterns are now accepted, but if any repetition of the subpattern does in fact match no characters, the loop is forcibly broken.

By default, the quantifiers are "greedy", that is, they match as much as possible (up to the maximum number of permitted times), without causing the rest of the pattern to fail. The classic example of where this gives problems is in trying to match comments in C programs. These appear between the sequences /* and */ and within the sequence, individual * and / characters may appear. An attempt to match C comments by applying the pattern /\*.*\*/ to the string /* first comment */ not comment /* second comment */ fails, because it matches the entire string due to the greediness of the .* item.

However, if a quantifier is followed by a question mark, then it becomes lazy, and instead matches the minimum number of times possible, so the pattern /\*.*?\*/ does the right thing with the C comments. The meaning of the various quantifiers is not otherwise changed, just the preferred number of matches. Do not confuse this use of question mark with its use as a quantifier in its own right. Because it has two uses, it can sometimes appear doubled, as in \d??\d which matches one digit by preference, but can match two if that is the only way the rest of the pattern matches.

If the PCRE_UNGREEDY option is set (an option which is not available in Perl) then the quantifiers are not greedy by default, but individual ones can be made greedy by following them with a question mark. In other words, it inverts the default behaviour.

Quantifiers followed by + are "possessive". They eat as many characters as possible and don't return to match the rest of the pattern. Thus .*abc matches "aabc" but .*+abc doesn't because .*+ eats the whole string. Possessive quantifiers can be used to speed up processing.

When a parenthesized subpattern is quantified with a minimum repeat count that is greater than 1 or with a limited maximum, more store is required for the compiled pattern, in proportion to the size of the minimum or maximum.

If a pattern starts with .* or .{0,} and the PCRE_DOTALL option (equivalent to Perl's /s) is set, thus allowing the . to match newlines, then the pattern is implicitly anchored, because whatever follows will be tried against every character position in the subject string, so there is no point in retrying the overall match at any position after the first. PCRE treats such a pattern as though it were preceded by \A. In cases where it is known that the subject string contains no newlines, it is worth setting PCRE_DOTALL when the pattern begins with .* in order to obtain this optimization, or alternatively using ^ to indicate anchoring explicitly.

When a capturing subpattern is repeated, the value captured is the substring that matched the final iteration. For example, after (tweedle[dume]{3}\s*)+ has matched "tweedledum tweedledee" the value of the captured substring is "tweedledee". However, if there are nested capturing subpatterns, the corresponding captured values may have been set in previous iterations. For example, after /(a|(b))+/ matches "aba" the value of the second captured substring is "b".


Back references

Outside a character class, a backslash followed by a digit greater than 0 (and possibly further digits) is a back reference to a capturing subpattern earlier (i.e. to its left) in the pattern, provided there have been that many previous capturing left parentheses.

However, if the decimal number following the backslash is less than 10, it is always taken as a back reference, and causes an error only if there are not that many capturing left parentheses in the entire pattern. In other words, the parentheses that are referenced need not be to the left of the reference for numbers less than 10. A "forward back reference" can make sense when a repetition is involved and the subpattern to the right has participated in an earlier iteration. See the section entitled "Backslash" above for further details of the handling of digits following a backslash.

A back reference matches whatever actually matched the capturing subpattern in the current subject string, rather than anything matching the subpattern itself. So the pattern (sens|respons)e and \1ibility matches "sense and sensibility" and "response and responsibility", but not "sense and responsibility". If case-sensitive (caseful) matching is in force at the time of the back reference, then the case of letters is relevant. For example, ((?i)rah)\s+\1 matches "rah rah" and "RAH RAH", but not "RAH rah", even though the original capturing subpattern is matched case-insensitively (caselessly).

There may be more than one back reference to the same subpattern. If a subpattern has not actually been used in a particular match, then any back references to it always fail. For example, the pattern (a|(bc))\2 always fails if it starts to match "a" rather than "bc". Because there may be up to 99 back references, all digits following the backslash are taken as part of a potential back reference number. If the pattern continues with a digit character, then some delimiter must be used to terminate the back reference. If the PCRE_EXTENDED option is set, this can be whitespace. Otherwise an empty comment can be used.

A back reference that occurs inside the parentheses to which it refers fails when the subpattern is first used, so, for example, (a\1) never matches. However, such references can be useful inside repeated subpatterns. For example, the pattern (a|b\1)+ matches any number of "a"s and also "aba", "ababba" etc. At each iteration of the subpattern, the back reference matches the character string corresponding to the previous iteration. In order for this to work, the pattern must be such that the first iteration does not need to match the back reference. This can be done using alternation, as in the example above, or by a quantifier with a minimum of zero.

As of PHP 5.2.2, the \g escape sequence can be used for absolute and relative referencing of subpatterns. This escape sequence must be followed by an unsigned number or a negative number, optionally enclosed in braces. The sequences \1, \g1 and \g{1} are synonymous with one another. The use of this pattern with an unsigned number can help remove the ambiguity inherent when using digits following a backslash. The sequence helps to distinguish back references from octal characters and also makes it easier to have a back reference followed by a literal number, e.g. \g{2}1.

The use of the \g sequence with a negative number signifies a relative reference. For example, (foo)(bar)\g{-1} would match the sequence "foobarbar" and (foo)(bar)\g{-2} matches "foobarfoo". This can be useful in long patterns as an alternative to keeping track of the number of subpatterns in order to reference a specific previous subpattern.

Back references to the named subpatterns can be achieved by (?P=name) or, since PHP 5.2.2, also by \k<name> or \k'name'. Additionally PHP 5.2.4 added support for \k{name} and \g{name}, and PHP 5.2.7 for \g<name> and \g'name'.


Assertions

An assertion is a test on the characters following or preceding the current matching point that does not actually consume any characters. The simple assertions coded as \b, \B, \A, \Z, \z, ^ and $ are described in escape sequences. More complicated assertions are coded as subpatterns. There are two kinds: those that look ahead of the current position in the subject string, and those that look behind it.

An assertion subpattern is matched in the normal way, except that it does not cause the current matching position to be changed. Lookahead assertions start with (?= for positive assertions and (?! for negative assertions. For example, \w+(?=;) matches a word followed by a semicolon, but does not include the semicolon in the match, and foo(?!bar) matches any occurrence of "foo" that is not followed by "bar". Note that the apparently similar pattern (?!foo)bar does not find an occurrence of "bar" that is preceded by something other than "foo"; it finds any occurrence of "bar" whatsoever, because the assertion (?!foo) is always TRUE when the next three characters are "bar". A lookbehind assertion is needed to achieve this effect.

Lookbehind assertions start with (?<= for positive assertions and (?<! for negative assertions. For example, (?<!foo)bar does find an occurrence of "bar" that is not preceded by "foo". The contents of a lookbehind assertion are restricted such that all the strings it matches must have a fixed length. However, if there are several alternatives, they do not all have to have the same fixed length. Thus (?<=bullock|donkey) is permitted, but (?<!dogs?|cats?) causes an error at compile time. Branches that match different length strings are permitted only at the top level of a lookbehind assertion. This is an extension compared with Perl 5.005, which requires all branches to match the same length of string. An assertion such as (?<=ab(c|de)) is not permitted, because its single top-level branch can match two different lengths, but it is acceptable if rewritten to use two top-level branches: (?<=abc|abde) The implementation of lookbehind assertions is, for each alternative, to temporarily move the current position back by the fixed width and then try to match. If there are insufficient characters before the current position, the match is deemed to fail. Lookbehinds in conjunction with once-only subpatterns can be particularly useful for matching at the ends of strings; an example is given at the end of the section on once-only subpatterns.

Several assertions (of any sort) may occur in succession. For example, (?<=\d{3})(?<!999)foo matches "foo" preceded by three digits that are not "999". Notice that each of the assertions is applied independently at the same point in the subject string. First there is a check that the previous three characters are all digits, then there is a check that the same three characters are not "999". This pattern does not match "foo" preceded by six characters, the first of which are digits and the last three of which are not "999". For example, it doesn't match "123abcfoo". A pattern to do that is (?<=\d{3}...)(?<!999)foo

This time the first assertion looks at the preceding six characters, checking that the first three are digits, and then the second assertion checks that the preceding three characters are not "999".

Assertions can be nested in any combination. For example, (?<=(?<!foo)bar)baz matches an occurrence of "baz" that is preceded by "bar" which in turn is not preceded by "foo", while (?<=\d{3}...(?<!999))foo is another pattern which matches "foo" preceded by three digits and any three characters that are not "999".

Assertion subpatterns are not capturing subpatterns, and may not be repeated, because it makes no sense to assert the same thing several times. If any kind of assertion contains capturing subpatterns within it, these are counted for the purposes of numbering the capturing subpatterns in the whole pattern. However, substring capturing is carried out only for positive assertions, because it does not make sense for negative assertions.

Assertions count towards the maximum of 200 parenthesized subpatterns.


Once-only subpatterns

With both maximizing and minimizing repetition, failure of what follows normally causes the repeated item to be re-evaluated to see if a different number of repeats allows the rest of the pattern to match. Sometimes it is useful to prevent this, either to change the nature of the match, or to cause it fail earlier than it otherwise might, when the author of the pattern knows there is no point in carrying on.

Consider, for example, the pattern \d+foo when applied to the subject line 123456bar

After matching all 6 digits and then failing to match "foo", the normal action of the matcher is to try again with only 5 digits matching the \d+ item, and then with 4, and so on, before ultimately failing. Once-only subpatterns provide the means for specifying that once a portion of the pattern has matched, it is not to be re-evaluated in this way, so the matcher would give up immediately on failing to match "foo" the first time. The notation is another kind of special parenthesis, starting with (?> as in this example: (?>\d+)bar

This kind of parenthesis "locks up" the part of the pattern it contains once it has matched, and a failure further into the pattern is prevented from backtracking into it. Backtracking past it to previous items, however, works as normal.

An alternative description is that a subpattern of this type matches the string of characters that an identical standalone pattern would match, if anchored at the current point in the subject string.

Once-only subpatterns are not capturing subpatterns. Simple cases such as the above example can be thought of as a maximizing repeat that must swallow everything it can. So, while both \d+ and \d+? are prepared to adjust the number of digits they match in order to make the rest of the pattern match, (?>\d+) can only match an entire sequence of digits.

This construction can of course contain arbitrarily complicated subpatterns, and it can be nested.

Once-only subpatterns can be used in conjunction with lookbehind assertions to specify efficient matching at the end of the subject string. Consider a simple pattern such as abcd$ when applied to a long string which does not match. Because matching proceeds from left to right, PCRE will look for each "a" in the subject and then see if what follows matches the rest of the pattern. If the pattern is specified as ^.*abcd$ then the initial .* matches the entire string at first, but when this fails (because there is no following "a"), it backtracks to match all but the last character, then all but the last two characters, and so on. Once again the search for "a" covers the entire string, from right to left, so we are no better off. However, if the pattern is written as ^(?>.*)(?<=abcd) then there can be no backtracking for the .* item; it can match only the entire string. The subsequent lookbehind assertion does a single test on the last four characters. If it fails, the match fails immediately. For long strings, this approach makes a significant difference to the processing time.

When a pattern contains an unlimited repeat inside a subpattern that can itself be repeated an unlimited number of times, the use of a once-only subpattern is the only way to avoid some failing matches taking a very long time indeed. The pattern (\D+|<\d+>)*[!?] matches an unlimited number of substrings that either consist of non-digits, or digits enclosed in <>, followed by either ! or ?. When it matches, it runs quickly. However, if it is applied to aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa it takes a long time before reporting failure. This is because the string can be divided between the two repeats in a large number of ways, and all have to be tried. (The example used [!?] rather than a single character at the end, because both PCRE and Perl have an optimization that allows for fast failure when a single character is used. They remember the last single character that is required for a match, and fail early if it is not present in the string.) If the pattern is changed to ((?>\D+)|<\d+>)*[!?] sequences of non-digits cannot be broken, and failure happens quickly.


Conditional subpatterns

It is possible to cause the matching process to obey a subpattern conditionally or to choose between two alternative subpatterns, depending on the result of an assertion, or whether a previous capturing subpattern matched or not. The two possible forms of conditional subpattern are

(?(condition)yes-pattern)
(?(condition)yes-pattern|no-pattern)

If the condition is satisfied, the yes-pattern is used; otherwise the no-pattern (if present) is used. If there are more than two alternatives in the subpattern, a compile-time error occurs.

There are two kinds of condition. If the text between the parentheses consists of a sequence of digits, then the condition is satisfied if the capturing subpattern of that number has previously matched. Consider the following pattern, which contains non-significant white space to make it more readable (assume the PCRE_EXTENDED option) and to divide it into three parts for ease of discussion:

( \( )?    [^()]+    (?(1) \) )

The first part matches an optional opening parenthesis, and if that character is present, sets it as the first captured substring. The second part matches one or more characters that are not parentheses. The third part is a conditional subpattern that tests whether the first set of parentheses matched or not. If they did, that is, if subject started with an opening parenthesis, the condition is TRUE, and so the yes-pattern is executed and a closing parenthesis is required. Otherwise, since no-pattern is not present, the subpattern matches nothing. In other words, this pattern matches a sequence of non-parentheses, optionally enclosed in parentheses.

If the condition is the string (R), it is satisfied if a recursive call to the pattern or subpattern has been made. At "top level", the condition is false.

If the condition is not a sequence of digits or (R), it must be an assertion. This may be a positive or negative lookahead or lookbehind assertion. Consider this pattern, again containing non-significant white space, and with the two alternatives on the second line:

(?(?=[^a-z]*[a-z])
\d{2}-[a-z]{3}-\d{2}  |  \d{2}-\d{2}-\d{2} )

The condition is a positive lookahead assertion that matches an optional sequence of non-letters followed by a letter. In other words, it tests for the presence of at least one letter in the subject. If a letter is found, the subject is matched against the first alternative; otherwise it is matched against the second. This pattern matches strings in one of the two forms dd-aaa-dd or dd-dd-dd, where aaa are letters and dd are digits.


Comments

The sequence (?# marks the start of a comment which continues up to the next closing parenthesis. Nested parentheses are not permitted. The characters that make up a comment play no part in the pattern matching at all.

If the PCRE_EXTENDED option is set, an unescaped # character outside a character class introduces a comment that continues up to the next newline character in the pattern.


Recursive patterns

Consider the problem of matching a string in parentheses, allowing for unlimited nested parentheses. Without the use of recursion, the best that can be done is to use a pattern that matches up to some fixed depth of nesting. It is not possible to handle an arbitrary nesting depth. Perl 5.6 has provided an experimental facility that allows regular expressions to recurse (among other things). The special item (?R) is provided for the specific case of recursion. This PCRE pattern solves the parentheses problem (assume the PCRE_EXTENDED option is set so that white space is ignored): \( ( (?>[^()]+) | (?R) )* \)

First it matches an opening parenthesis. Then it matches any number of substrings which can either be a sequence of non-parentheses, or a recursive match of the pattern itself (i.e. a correctly parenthesized substring). Finally there is a closing parenthesis.

This particular example pattern contains nested unlimited repeats, and so the use of a once-only subpattern for matching strings of non-parentheses is important when applying the pattern to strings that do not match. For example, when it is applied to (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa() it yields "no match" quickly. However, if a once-only subpattern is not used, the match runs for a very long time indeed because there are so many different ways the + and * repeats can carve up the subject, and all have to be tested before failure can be reported.

The values set for any capturing subpatterns are those from the outermost level of the recursion at which the subpattern value is set. If the pattern above is matched against (ab(cd)ef) the value for the capturing parentheses is "ef", which is the last value taken on at the top level. If additional parentheses are added, giving \( ( ( (?>[^()]+) | (?R) )* ) \) then the string they capture is "ab(cd)ef", the contents of the top level parentheses. If there are more than 15 capturing parentheses in a pattern, PCRE has to obtain extra memory to store data during a recursion, which it does by using pcre_malloc, freeing it via pcre_free afterwards. If no memory can be obtained, it saves data for the first 15 capturing parentheses only, as there is no way to give an out-of-memory error from within a recursion.

(?1), (?2) and so on can be used for recursive subpatterns too. It is also possible to use named subpatterns: (?P>name) or (?&name).

If the syntax for a recursive subpattern reference (either by number or by name) is used outside the parentheses to which it refers, it operates like a subroutine in a programming language. An earlier example pointed out that the pattern (sens|respons)e and \1ibility matches "sense and sensibility" and "response and responsibility", but not "sense and responsibility". If instead the pattern (sens|respons)e and (?1)ibility is used, it does match "sense and responsibility" as well as the other two strings. Such references must, however, follow the subpattern to which they refer.

The maximum length of a subject string is the largest positive number that an integer variable can hold. However, PCRE uses recursion to handle subpatterns and indefinite repetition. This means that the available stack space may limit the size of a subject string that can be processed by certain patterns.


Performance

Certain items that may appear in patterns are more efficient than others. It is more efficient to use a character class like [aeiou] than a set of alternatives such as (a|e|i|o|u). In general, the simplest construction that provides the required behaviour is usually the most efficient. Jeffrey Friedl's book contains a lot of discussion about optimizing regular expressions for efficient performance.

When a pattern begins with .* and the PCRE_DOTALL option is set, the pattern is implicitly anchored by PCRE, since it can match only at the start of a subject string. However, if PCRE_DOTALL is not set, PCRE cannot make this optimization, because the . metacharacter does not then match a newline, and if the subject string contains newlines, the pattern may match from the character immediately following one of them instead of from the very start. For example, the pattern (.*) second matches the subject "first\nand second" (where \n stands for a newline character) with the first captured substring being "and". In order to do this, PCRE has to retry the match starting after every newline in the subject.

If you are using such a pattern with subject strings that do not contain newlines, the best performance is obtained by setting PCRE_DOTALL, or starting the pattern with ^.* to indicate explicit anchoring. That saves PCRE from having to scan along the subject looking for a newline to restart at.

Beware of patterns that contain nested indefinite repeats. These can take a long time to run when applied to a string that does not match. Consider the pattern fragment (a+)*

This can match "aaaa" in 33 different ways, and this number increases very rapidly as the string gets longer. (The * repeat can match 0, 1, 2, 3, or 4 times, and for each of those cases other than 0, the + repeats can match different numbers of times.) When the remainder of the pattern is such that the entire match is going to fail, PCRE has in principle to try every possible variation, and this can take an extremely long time.

An optimization catches some of the more simple cases such as (a+)*b where a literal character follows. Before embarking on the standard matching procedure, PCRE checks that there is a "b" later in the subject string, and if there is not, it fails the match immediately. However, when there is no following literal this optimization cannot be used. You can see the difference by comparing the behaviour of (a+)*\d with the pattern above. The former gives a failure almost instantly when applied to a whole line of "a" characters, whereas the latter takes an appreciable time with strings longer than about 20 characters.


Pattern Modifiers

The current possible PCRE modifiers are listed below. The names in parentheses refer to internal PCRE names for these modifiers. Spaces and newlines are ignored in modifiers, other characters cause error.

i (PCRE_CASELESS)
If this modifier is set, letters in the pattern match both upper and lower case letters.
m (PCRE_MULTILINE)
By default, PCRE treats the subject string as consisting of a single "line" of characters (even if it actually contains several newlines). The "start of line" metacharacter (^) matches only at the start of the string, while the "end of line" metacharacter ($) matches only at the end of the string, or before a terminating newline (unless D modifier is set). This is the same as Perl. When this modifier is set, the "start of line" and "end of line" constructs match immediately following or immediately before any newline in the subject string, respectively, as well as at the very start and end. This is equivalent to Perl's /m modifier. If there are no "\n" characters in a subject string, or no occurrences of ^ or $ in a pattern, setting this modifier has no effect.
s (PCRE_DOTALL)
If this modifier is set, a dot metacharacter in the pattern matches all characters, including newlines. Without it, newlines are excluded. This modifier is equivalent to Perl's /s modifier. A negative class such as [^a] always matches a newline character, independent of the setting of this modifier.
x (PCRE_EXTENDED)
If this modifier is set, whitespace data characters in the pattern are totally ignored except when escaped or inside a character class, and characters between an unescaped # outside a character class and the next newline character, inclusive, are also ignored. This is equivalent to Perl's /x modifier, and makes it possible to include commentary inside complicated patterns. Note, however, that this applies only to data characters. Whitespace characters may never appear within special character sequences in a pattern, for example within the sequence (?( which introduces a conditional subpattern.
e (PREG_REPLACE_EVAL)
Warning

This feature was DEPRECATED in PHP 5.5.0, and REMOVED as of PHP 7.0.0.

If this deprecated modifier is set, preg_replace() does normal substitution of backreferences in the replacement string, evaluates it as PHP code, and uses the result for replacing the search string. Single quotes, double quotes, backslashes (\) and NULL chars will be escaped by backslashes in substituted backreferences.
Caution

The addslashes() function is run on each matched backreference before the substitution takes place. As such, when the backreference is used as a quoted string, escaped characters will be converted to literals. However, characters which are escaped, which would normally not be converted, will retain their slashes. This makes use of this modifier very complicated.

Caution

Make sure that replacement constitutes a valid PHP code string, otherwise PHP will complain about a parse error at the line containing preg_replace().

Caution

Use of this modifier is discouraged, as it can easily introduce remote code execution vulnerabilities. To prevent these, the preg_replace_callback() function should be used instead:

<?php
$html = $_POST['html'];

// uppercase headings
$html = preg_replace_callback(
    '(<h([1-6])>(.*?)</h\1>)',
    function ($m) {
        return "<h$m[1]>" . strtoupper($m[2]) . "</h$m[1]>";
    },
    $html
);

If the above example was written with preg_replace() and the e modifier, the code could be easily exploited by passing in a string such as <h1>{${eval($_GET[php_code])}}</h1>. This gave the attacker the ability to execute arbitrary PHP code and as such gave them nearly complete access to the server.

Note:

Only preg_replace() uses this modifier; it is ignored by other PCRE functions.

A (PCRE_ANCHORED)
If this modifier is set, the pattern is forced to be "anchored", that is, it is constrained to match only at the start of the string which is being searched (the "subject string"). This effect can also be achieved by appropriate constructs in the pattern itself, which is the only way to do it in Perl.
D (PCRE_DOLLAR_ENDONLY)
If this modifier is set, a dollar metacharacter in the pattern matches only at the end of the subject string. Without this modifier, a dollar also matches immediately before the final character if it is a newline (but not before any other newlines). This modifier is ignored if m modifier is set. There is no equivalent to this modifier in Perl.
S
When a pattern is going to be used several times, it is worth spending more time analyzing it in order to speed up the time taken for matching. If this modifier is set, then this extra analysis is performed. At present, studying a pattern is useful only for non-anchored patterns that do not have a single fixed starting character.
U (PCRE_UNGREEDY)
This modifier inverts the "greediness" of the quantifiers so that they are not greedy by default, but become greedy if followed by ?. It is not compatible with Perl. It can also be set by a (?U) modifier setting within the pattern or by a question mark behind a quantifier (e.g. .*?).

Note:

It is usually not possible to match more than pcre.backtrack_limit characters in ungreedy mode.

X (PCRE_EXTRA)
This modifier turns on additional functionality of PCRE that is incompatible with Perl. Any backslash in a pattern that is followed by a letter that has no special meaning causes an error, thus reserving these combinations for future expansion. By default, as in Perl, a backslash followed by a letter with no special meaning is treated as a literal. There are at present no other features controlled by this modifier.
J (PCRE_INFO_JCHANGED)
The (?J) internal option setting changes the local PCRE_DUPNAMES option. Allow duplicate names for subpatterns. As of PHP 7.2.0 J is supported as modifier as well.
u (PCRE_UTF8)
This modifier turns on additional functionality of PCRE that is incompatible with Perl. Pattern and subject strings are treated as UTF-8. An invalid subject will cause the preg_* function to match nothing; an invalid pattern will trigger an error of level E_WARNING. Five and six octet UTF-8 sequences are regarded as invalid since PHP 5.3.4 (resp. PCRE 7.3 2007-08-28); formerly those have been regarded as valid UTF-8.


Perl Differences

The differences described here are with respect to Perl 5.005.

  1. By default, a whitespace character is any character that the C library function isspace() recognizes, though it is possible to compile PCRE with alternative character type tables. Normally isspace() matches space, formfeed, newline, carriage return, horizontal tab, and vertical tab. Perl 5 no longer includes vertical tab in its set of whitespace characters. The \v escape that was in the Perl documentation for a long time was never in fact recognized. However, the character itself was treated as whitespace at least up to 5.002. In 5.004 and 5.005 it does not match \s.
  2. PCRE does not allow repeat quantifiers on lookahead assertions. Perl permits them, but they do not mean what you might think. For example, (?!a){3} does not assert that the next three characters are not "a". It just asserts that the next character is not "a" three times.
  3. Capturing subpatterns that occur inside negative lookahead assertions are counted, but their entries in the offsets vector are never set. Perl sets its numerical variables from any such patterns that are matched before the assertion fails to match something (thereby succeeding), but only if the negative lookahead assertion contains just one branch.
  4. Though binary zero characters are supported in the subject string, they are not allowed in a pattern string because it is passed as a normal C string, terminated by zero. The escape sequence "\x00" can be used in the pattern to represent a binary zero.
  5. The following Perl escape sequences are not supported: \l, \u, \L, \U. In fact these are implemented by Perl's general string-handling and are not part of its pattern matching engine.
  6. The Perl \G assertion is not supported as it is not relevant to single pattern matches.
  7. Fairly obviously, PCRE does not support the (?{code}) and (??{code}) construction. However, there is support for recursive patterns.
  8. There are at the time of writing some oddities in Perl 5.005_02 concerned with the settings of captured strings when part of a pattern is repeated. For example, matching "aba" against the pattern /^(a(b)?)+$/ sets $2 to the value "b", but matching "aabbaa" against /^(aa(bb)?)+$/ leaves $2 unset. However, if the pattern is changed to /^(aa(b(b))?)+$/ then $2 (and $3) get set. In Perl 5.004 $2 is set in both cases, and that is also TRUE of PCRE. If in the future Perl changes to a consistent state that is different, PCRE may change to follow.
  9. Another as yet unresolved discrepancy is that in Perl 5.005_02 the pattern /^(a)?(?(1)a|b)+$/ matches the string "a", whereas in PCRE it does not. However, in both Perl and PCRE /^(a)?a/ matched against "a" leaves $1 unset.

  10. PCRE provides some extensions to the Perl regular expression facilities:

    1. Although lookbehind assertions must match fixed length strings, each alternative branch of a lookbehind assertion can match a different length of string. Perl 5.005 requires them all to have the same length.
    2. If PCRE_DOLLAR_ENDONLY is set and PCRE_MULTILINE is not set, the $ meta-character matches only at the very end of the string.
    3. If PCRE_EXTRA is set, a backslash followed by a letter with no special meaning is faulted.
    4. If PCRE_UNGREEDY is set, the greediness of the repetition quantifiers is inverted, that is, by default they are not greedy, but if followed by a question mark they are.


Differences from POSIX regex

As of PHP 5.3.0, the POSIX Regex extension is deprecated. There are a number of differences between POSIX regex and PCRE regex. This page lists the most notable ones that are necessary to know when converting to PCRE.

  1. The PCRE functions require that the pattern is enclosed by delimiters.
  2. Unlike POSIX, the PCRE extension does not have dedicated functions for case-insensitive matching. Instead, this is supported using the i (PCRE_CASELESS) pattern modifier. Other pattern modifiers are also available for changing the matching strategy.
  3. The POSIX functions find the longest of the leftmost match, but PCRE stops on the first valid match. If the string doesn't match at all it makes no difference, but if it matches it may have dramatic effects on both the resulting match and the matching speed. To illustrate this difference, consider the following example from "Mastering Regular Expressions" by Jeffrey Friedl. Using the pattern one(self)?(selfsufficient)? on the string oneselfsufficient with PCRE will result in matching oneself, but using POSIX the result will be the full string oneselfsufficient. Both (sub)strings match the original string, but POSIX requires that the longest be the result.
  4. The POSIX definition of a "character class" differs from that of PCRE. Simple bracket expressions to match a set of explicit characters are supported in the form of PCRE character classes but POSIX collating elements, character classes and character equivalents are not supported. Supplying an expression with a character class that both starts and ends with :, . or = characters to PCRE is interpreted as an attempt to use one of these unsupported features and causes a compilation error.

Function replacements
POSIX | PCRE
ereg_replace() | preg_replace()
ereg() | preg_match()
eregi_replace() | preg_replace()
eregi() | preg_match()
split() | preg_split()
spliti() | preg_split()
sql_regcase() | No equivalent


PCRE Functions

Table of Contents

  • preg_filter — Perform a regular expression search and replace
  • preg_grep — Return array entries that match the pattern
  • preg_last_error — Returns the error code of the last PCRE regex execution
  • preg_match_all — Perform a global regular expression match
  • preg_match — Perform a regular expression match
  • preg_quote — Quote regular expression characters
  • preg_replace_callback_array — Perform a regular expression search and replace using callbacks
  • preg_replace_callback — Perform a regular expression search and replace using a callback
  • preg_replace — Perform a regular expression search and replace
  • preg_split — Split string by a regular expression


Perform a regular expression search and replace

  • « PCRE Functions
  • preg_grep »
  • PHP Manual
  • PCRE Functions
  • Perform a regular expression search and replace

preg_filter

(PHP 5 >= 5.3.0, PHP 7)

preg_filter — Perform a regular expression search and replace

Description

preg_filter ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] ) : mixed

preg_filter() is identical to preg_replace() except it only returns the (possibly transformed) subjects where there was a match. For details about how this function works, read the preg_replace() documentation.

Return Values

Returns an array if the subject parameter is an array, or a string otherwise.

If no matches are found or an error occurred, an empty array is returned when subject is an array or NULL otherwise.

Examples

Example #1 Example comparing preg_filter() with preg_replace()

<?php
$subject = array('1', 'a', '2', 'b', '3', 'A', 'B', '4');
$pattern = array('/\d/', '/[a-z]/', '/[1a]/');
$replace = array('A:$0', 'B:$0', 'C:$0');

echo "preg_filter returns\n";
print_r(preg_filter($pattern, $replace, $subject));

echo "preg_replace returns\n";
print_r(preg_replace($pattern, $replace, $subject));
?>

The above example will output:

preg_filter returns
Array
(
    [0] => A:C:1
    [1] => B:C:a
    [2] => A:2
    [3] => B:b
    [4] => A:3
    [7] => A:4
)
preg_replace returns
Array
(
    [0] => A:C:1
    [1] => B:C:a
    [2] => A:2
    [3] => B:b
    [4] => A:3
    [5] => A
    [6] => B
    [7] => A:4
)

See Also

  • PCRE Patterns
  • preg_quote() - Quote regular expression characters
  • preg_replace() - Perform a regular expression search and replace
  • preg_replace_callback() - Perform a regular expression search and replace using a callback
  • preg_grep() - Return array entries that match the pattern
  • preg_last_error() - Returns the error code of the last PCRE regex execution


Return array entries that match the pattern

  • « preg_filter
  • preg_last_error »
  • PHP Manual
  • PCRE Functions
  • Return array entries that match the pattern

preg_grep

(PHP 4, PHP 5, PHP 7)

preg_grep — Return array entries that match the pattern

Description

preg_grep ( string $pattern , array $input [, int $flags = 0 ] ) : array

Returns the array consisting of the elements of the input array that match the given pattern.

Parameters

pattern

The pattern to search for, as a string.

input

The input array.

flags

If set to PREG_GREP_INVERT, this function returns the elements of the input array that do not match the given pattern.

Return Values

Returns an array indexed using the keys from the input array.

Examples

Example #1 preg_grep() example

<?php
// return all array elements
// containing floating point numbers
$fl_array = preg_grep("/^(\d+)?\.\d+$/", $array);
?>

See Also

  • PCRE Patterns
  • preg_quote() - Quote regular expression characters
  • preg_match_all() - Perform a global regular expression match
  • preg_filter() - Perform a regular expression search and replace
  • preg_last_error() - Returns the error code of the last PCRE regex execution


Returns the error code of the last PCRE regex execution

  • « preg_grep
  • preg_match_all »
  • PHP Manual
  • PCRE Functions
  • Returns the error code of the last PCRE regex execution

preg_last_error

(PHP 5 >= 5.2.0, PHP 7)

preg_last_error — Returns the error code of the last PCRE regex execution

Description

preg_last_error ( void ) : int

Returns the error code of the last PCRE regex execution.

Example #1 preg_last_error() example

<?php

preg_match('/(?:\D+|<\d+>)*[!?]/', 'foobar foobar foobar');

if (preg_last_error() == PREG_BACKTRACK_LIMIT_ERROR) {
    print 'Backtrack limit was exhausted!';
}

?>

The above example will output:

Backtrack limit was exhausted!

Return Values

Returns one of the following constants (explained on their own page):

  • PREG_NO_ERROR
  • PREG_INTERNAL_ERROR
  • PREG_BACKTRACK_LIMIT_ERROR (see also pcre.backtrack_limit)
  • PREG_RECURSION_LIMIT_ERROR (see also pcre.recursion_limit)
  • PREG_BAD_UTF8_ERROR
  • PREG_BAD_UTF8_OFFSET_ERROR (since PHP 5.3.0)
  • PREG_JIT_STACKLIMIT_ERROR (since PHP 7.0.0)


Perform a global regular expression match

  • « preg_last_error
  • preg_match »
  • PHP Manual
  • PCRE Functions
  • Perform a global regular expression match

preg_match_all

(PHP 4, PHP 5, PHP 7)

preg_match_all — Perform a global regular expression match

Description

preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG_PATTERN_ORDER [, int $offset = 0 ]]] ) : int

Searches subject for all matches to the regular expression given in pattern and puts them in matches in the order specified by flags.

After the first match is found, the subsequent searches are continued on from end of the last match.

Parameters

pattern

The pattern to search for, as a string.

subject

The input string.

matches

Array of all matches in multi-dimensional array ordered according to flags.

flags

Can be a combination of the following flags (note that it doesn't make sense to use PREG_PATTERN_ORDER together with PREG_SET_ORDER):

PREG_PATTERN_ORDER

Orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on.

<?php
preg_match_all("|<[^>]+>(.*)</[^>]+>|U",
    "<b>example: </b><div align=left>this is a test</div>",
    $out, PREG_PATTERN_ORDER);
echo $out[0][0] . ", " . $out[0][1] . "\n";
echo $out[1][0] . ", " . $out[1][1] . "\n";
?>

The above example will output:

<b>example: </b>, <div align=left>this is a test</div>
example: , this is a test

So, $out[0] contains array of strings that matched full pattern, and $out[1] contains array of strings enclosed by tags.

If the pattern contains named subpatterns, $matches additionally contains entries for keys with the subpattern name.

If the pattern contains duplicate named subpatterns, only the rightmost subpattern is stored in $matches[NAME].

<?php
preg_match_all(
    '/(?J)(?<match>foo)|(?<match>bar)/',
    'foo bar',
    $matches,
    PREG_PATTERN_ORDER
);
print_r($matches['match']);
?>

The above example will output:

Array
(
    [0] =>
    [1] => bar
)

PREG_SET_ORDER

Orders results so that $matches[0] is an array of first set of matches, $matches[1] is an array of second set of matches, and so on.

<?php
preg_match_all("|<[^>]+>(.*)</[^>]+>|U",
    "<b>example: </b><div align=\"left\">this is a test</div>",
    $out, PREG_SET_ORDER);
echo $out[0][0] . ", " . $out[0][1] . "\n";
echo $out[1][0] . ", " . $out[1][1] . "\n";
?>

The above example will output:

<b>example: </b>, example:
<div align="left">this is a test</div>, this is a test

PREG_OFFSET_CAPTURE

If this flag is passed, for every occurring match the appendant string offset will also be returned. Note that this changes the value of matches into an array of arrays where every element is an array consisting of the matched string at offset 0 and its string offset into subject at offset 1.

<?php
preg_match_all('/(foo)(bar)(baz)/', 'foobarbaz', $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>

The above example will output:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => foobarbaz
                    [1] => 0
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [0] => foo
                    [1] => 0
                )

        )

    [2] => Array
        (
            [0] => Array
                (
                    [0] => bar
                    [1] => 3
                )

        )

    [3] => Array
        (
            [0] => Array
                (
                    [0] => baz
                    [1] => 6
                )

        )

)

PREG_UNMATCHED_AS_NULL

If this flag is passed, unmatched subpatterns are reported as NULL; otherwise they are reported as an empty string.

If no order flag is given, PREG_PATTERN_ORDER is assumed.

offset

Normally, the search starts from the beginning of the subject string. The optional parameter offset can be used to specify the alternate place from which to start the search (in bytes).

Note:

Using offset is not equivalent to passing substr($subject, $offset) to preg_match_all() in place of the subject string, because pattern can contain assertions such as ^, $ or (?<=x). See preg_match() for examples.

Return Values

Returns the number of full pattern matches (which might be zero), or FALSE if an error occurred.

Changelog

Version | Description
7.2.0 | The PREG_UNMATCHED_AS_NULL is now supported for the $flags parameter.
5.4.0 | The matches parameter became optional.
5.3.6 | Returns FALSE if offset is higher than subject length.
5.2.2 | Named subpatterns now accept the syntax (?<name>) and (?'name') as well as (?P<name>). Previous versions accepted only (?P<name>).

Examples

Example #1 Getting all phone numbers out of some text.

<?php
preg_match_all("/\(?  (\d{3})?  \)?  (?(1)  [\-\s] ) \d{3}-\d{4}/x",
                "Call 555-1212 or 1-800-555-1212", $phones);
?>

Example #2 Find matching HTML tags (greedy)

<?php
// The \\2 is an example of backreferencing. This tells pcre that
// it must match the second set of parentheses in the regular expression
// itself, which would be the ([\w]+) in this case. The extra backslash is
// required because the string is in double quotes.
$html = "<b>bold text</b><a href=howdy.html>click me</a>";

preg_match_all("/(<([\w]+)[^>]*>)(.*?)(<\/\\2>)/", $html, $matches, PREG_SET_ORDER);

foreach ($matches as $val) {
    echo "matched: " . $val[0] . "\n";
    echo "part 1: " . $val[1] . "\n";
    echo "part 2: " . $val[2] . "\n";
    echo "part 3: " . $val[3] . "\n";
    echo "part 4: " . $val[4] . "\n\n";
}
?>

The above example will output:

matched: <b>bold text</b>
part 1: <b>
part 2: b
part 3: bold text
part 4: </b>

matched: <a href=howdy.html>click me</a>
part 1: <a href=howdy.html>
part 2: a
part 3: click me
part 4: </a>

Example #3 Using named subpattern

<?php

$str = <<<FOO
a: 1
b: 2
c: 3
FOO;

preg_match_all('/(?P<name>\w+): (?P<digit>\d+)/', $str, $matches);

/* This also works in PHP 5.2.2 (PCRE 7.0) and later, however
 * the above form is recommended for backwards compatibility */
// preg_match_all('/(?<name>\w+): (?<digit>\d+)/', $str, $matches);

print_r($matches);

?>

The above example will output:

Array
(
    [0] => Array
        (
            [0] => a: 1
            [1] => b: 2
            [2] => c: 3
        )

    [name] => Array
        (
            [0] => a
            [1] => b
            [2] => c
        )

    [1] => Array
        (
            [0] => a
            [1] => b
            [2] => c
        )

    [digit] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [2] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

)

See Also

  • PCRE Patterns
  • preg_quote() - Quote regular expression characters
  • preg_match() - Perform a regular expression match
  • preg_replace() - Perform a regular expression search and replace
  • preg_split() - Split string by a regular expression
  • preg_last_error() - Returns the error code of the last PCRE regex execution


Perform a regular expression match

  • « preg_match_all
  • preg_quote »
  • PHP Manual
  • PCRE Functions
  • Perform a regular expression match

preg_match

(PHP 4, PHP 5, PHP 7)

preg_match — Perform a regular expression match

Description

preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] ) : int

Searches subject for a match to the regular expression given in pattern.

Parameters

pattern

The pattern to search for, as a string.

subject

The input string.

matches

If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.

flags

flags can be a combination of the following flags:

PREG_OFFSET_CAPTURE

If this flag is passed, for every occurring match the appendant string offset (in bytes) will also be returned. Note that this changes the value of matches into an array where every element is an array consisting of the matched string at offset 0 and its string offset into subject at offset 1.

<?php
preg_match('/(foo)(bar)(baz)/', 'foobarbaz', $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>

The above example will output:

Array
(
    [0] => Array
        (
            [0] => foobarbaz
            [1] => 0
        )

    [1] => Array
        (
            [0] => foo
            [1] => 0
        )

    [2] => Array
        (
            [0] => bar
            [1] => 3
        )

    [3] => Array
        (
            [0] => baz
            [1] => 6
        )

)

PREG_UNMATCHED_AS_NULL

If this flag is passed, unmatched subpatterns are reported as NULL; otherwise they are reported as an empty string.

<?php
preg_match('/(a)(b)*(c)/', 'ac', $matches);
var_dump($matches);
preg_match('/(a)(b)*(c)/', 'ac', $matches, PREG_UNMATCHED_AS_NULL);
var_dump($matches);
?>

The above example will output:

array(4) {
  [0]=>
  string(2) "ac"
  [1]=>
  string(1) "a"
  [2]=>
  string(0) ""
  [3]=>
  string(1) "c"
}
array(4) {
  [0]=>
  string(2) "ac"
  [1]=>
  string(1) "a"
  [2]=>
  NULL
  [3]=>
  string(1) "c"
}

offset

Normally, the search starts from the beginning of the subject string. The optional parameter offset can be used to specify the alternate place from which to start the search (in bytes).

Note:

Using offset is not equivalent to passing substr($subject, $offset) to preg_match() in place of the subject string, because pattern can contain assertions such as ^, $ or (?<=x). Compare:

<?php
$subject = "abcdef";
$pattern = '/^def/';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3);
print_r($matches);
?>

The above example will output:

Array
(
)

while this example

<?php
$subject = "abcdef";
$pattern = '/^def/';
preg_match($pattern, substr($subject,3), $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>

will produce

Array
(
    [0] => Array
        (
            [0] => def
            [1] => 0
        )

)

Alternatively, to avoid using substr(), use the \G assertion rather than the ^ anchor, or the A modifier instead, both of which work with the offset parameter.

Return Values

preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred.

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
7.2.0 | The PREG_UNMATCHED_AS_NULL is now supported for the $flags parameter.
5.3.6 | Returns FALSE if offset is higher than subject length.
5.2.2 | Named subpatterns now accept the syntax (?<name>) and (?'name') as well as (?P<name>). Previous versions accepted only (?P<name>).

Examples

Example #1 Find the string of text "php"

<?php
// The "i" after the pattern delimiter indicates a case-insensitive search
if (preg_match("/php/i", "PHP is the web scripting language of choice.")) {
    echo "A match was found.";
} else {
    echo "A match was not found.";
}
?>

Example #2 Find the word "web"

<?php
/* The \b in the pattern indicates a word boundary, so only the distinct
 * word "web" is matched, and not a word partial like "webbing" or "cobweb" */
if (preg_match("/\bweb\b/i", "PHP is the web scripting language of choice.")) {
    echo "A match was found.";
} else {
    echo "A match was not found.";
}

if (preg_match("/\bweb\b/i", "PHP is the website scripting language of choice.")) {
    echo "A match was found.";
} else {
    echo "A match was not found.";
}
?>

Example #3 Getting the domain name out of a URL

<?php
// get host name from URL
preg_match('@^(?:http://)?([^/]+)@i',
    "http://www.php.net/index.html", $matches);
$host = $matches[1];

// get last two segments of host name
preg_match('/[^.]+\.[^.]+$/', $host, $matches);
echo "domain name is: {$matches[0]}\n";
?>

The above example will output:

domain name is: php.net

Example #4 Using named subpattern

<?php

$str = 'foobar: 2008';

preg_match('/(?P<name>\w+): (?P<digit>\d+)/', $str, $matches);

/* This also works in PHP 5.2.2 (PCRE 7.0) and later, however
 * the above form is recommended for backwards compatibility */
// preg_match('/(?<name>\w+): (?<digit>\d+)/', $str, $matches);

print_r($matches);

?>

The above example will output:

Array
(
    [0] => foobar: 2008
    [name] => foobar
    [1] => foobar
    [digit] => 2008
    [2] => 2008
)

Notes

Tip

Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() instead as it will be faster.

See Also

  • PCRE Patterns
  • preg_quote() - Quote regular expression characters
  • preg_match_all() - Perform a global regular expression match
  • preg_replace() - Perform a regular expression search and replace
  • preg_split() - Split string by a regular expression
  • preg_last_error() - Returns the error code of the last PCRE regex execution


Quote regular expression characters

  • « preg_match
  • preg_replace_callback_array »
  • PHP Manual
  • PCRE Functions
  • Quote regular expression characters

preg_quote

(PHP 4, PHP 5, PHP 7)

preg_quote — Quote regular expression characters

Description

preg_quote ( string $str [, string $delimiter = NULL ] ) : string

preg_quote() takes str and puts a backslash in front of every character that is part of the regular expression syntax. This is useful if you have a run-time string that you need to match in some text and the string may contain special regex characters.

The special regular expression characters are: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : - #

Note that / is not a special regular expression character.

Note:

Note that preg_quote() is not meant to be applied to the $replacement string(s) of preg_replace() etc.

Parameters

str

The input string.

delimiter

If the optional delimiter is specified, it will also be escaped. This is useful for escaping the delimiter that is required by the PCRE functions. The / is the most commonly used delimiter.

Return Values

Returns the quoted (escaped) string.

Changelog

Version | Description
7.3.0 | The # character is now quoted
5.3.0 | The - character is now quoted

Examples

Example #1 preg_quote() example

<?php
$keywords = '$40 for a g3/400';
$keywords = preg_quote($keywords, '/');
echo $keywords; // returns \$40 for a g3\/400
?>

Example #2 Italicizing a word within some text

<?php
// In this example, preg_quote($word) is used to keep the
// asterisks from having special meaning to the regular
// expression.

$textbody = "This book is *very* difficult to find.";
$word = "*very*";
$textbody = preg_replace ("/" . preg_quote($word, '/') . "/",
                          "<i>" . $word . "</i>",
                          $textbody);
?>

Notes

Note: This function is binary-safe.

See Also

  • PCRE Patterns
  • escapeshellcmd() - Escape shell metacharacters


Perform a regular expression search and replace using callbacks

  • « preg_quote
  • preg_replace_callback »
  • PHP Manual
  • PCRE Functions
  • Perform a regular expression search and replace using callbacks

preg_replace_callback_array

(PHP 7)

preg_replace_callback_array — Perform a regular expression search and replace using callbacks

Description

preg_replace_callback_array ( array $patterns_and_callbacks , mixed $subject [, int $limit = -1 [, int &$count ]] ) : mixed

The behavior of this function is similar to preg_replace_callback(), except that callbacks are executed on a per-pattern basis.

Parameters

patterns_and_callbacks

An associative array mapping patterns (keys) to callbacks (values).

subject

The string or an array with strings to search and replace.

limit

The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit).

count

If specified, this variable will be filled with the number of replacements done.

Return Values

preg_replace_callback_array() returns an array if the subject parameter is an array, or a string otherwise. On errors the return value is NULL

If matches are found, the new subject will be returned, otherwise subject will be returned unchanged.

Examples

Example #1 preg_replace_callback_array() example

<?php
$subject = 'Aaaaaa Bbb';

preg_replace_callback_array(
    [
        '~[a]+~i' => function ($match) {
            echo strlen($match[0]), ' matches for "a" found', PHP_EOL;
        },
        '~[b]+~i' => function ($match) {
            echo strlen($match[0]), ' matches for "b" found', PHP_EOL;
        }
    ],
    $subject
);
?>

The above example will output:

6 matches for "a" found
3 matches for "b" found

See Also

  • PCRE Patterns
  • preg_replace_callback() - Perform a regular expression search and replace using a callback
  • preg_quote() - Quote regular expression characters
  • preg_replace() - Perform a regular expression search and replace
  • preg_last_error() - Returns the error code of the last PCRE regex execution
  • Anonymous functions
  • information about the callback type


Perform a regular expression search and replace using a callback

  • « preg_replace_callback_array
  • preg_replace »
  • PHP Manual
  • PCRE Functions
  • Perform a regular expression search and replace using a callback

preg_replace_callback

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

preg_replace_callback — Perform a regular expression search and replace using a callback

Description

preg_replace_callback ( mixed $pattern , callable $callback , mixed $subject [, int $limit = -1 [, int &$count ]] ) : mixed

The behavior of this function is almost identical to preg_replace(), except for the fact that instead of replacement parameter, one should specify a callback.

Parameters

pattern

The pattern to search for. It can be either a string or an array with strings.

callback

A callback that will be called and passed an array of matched elements in the subject string. The callback should return the replacement string. This is the callback signature:

handler ( array $matches ) : string

You'll often need the callback function for a preg_replace_callback() in just one place. In this case you can use an anonymous function to declare the callback within the call to preg_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.

Example #1 preg_replace_callback() and anonymous function

<?php
/* a unix-style command line filter to convert uppercase
 * letters at the beginning of paragraphs to lowercase */
$fp = fopen("php://stdin", "r") or die("can't read stdin");
while (!feof($fp)) {
    $line = fgets($fp);
    $line = preg_replace_callback(
        '|<p>\s*\w|',
        function ($matches) {
            return strtolower($matches[0]);
        },
        $line
    );
    echo $line;
}
fclose($fp);
?>

subject

The string or an array with strings to search and replace.

limit

The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit).

count

If specified, this variable will be filled with the number of replacements done.

Return Values

preg_replace_callback() returns an array if the subject parameter is an array, or a string otherwise. On errors the return value is NULL

If matches are found, the new subject will be returned, otherwise subject will be returned unchanged.

Changelog

Version | Description
5.1.0 | The count parameter was added

Examples

Example #2 preg_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 preg_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 #3 preg_replace_callback() using recursive structure to handle encapsulated BB code

<?php
$input = "plain [indent] deep [indent] deeper [/indent] deep [/indent] plain";

function parseTagsRecursive($input)
{

    $regex = '#\[indent]((?:[^[]|\[(?!/?indent])|(?R))+)\[/indent]#';

    if (is_array($input)) {
        $input = '<div style="margin-left: 10px">'.$input[1].'</div>';
    }

    return preg_replace_callback($regex, 'parseTagsRecursive', $input);
}

$output = parseTagsRecursive($input);

echo $output;
?>

See Also

  • PCRE Patterns
  • preg_replace_callback_array() - Perform a regular expression search and replace using callbacks
  • preg_quote() - Quote regular expression characters
  • preg_replace() - Perform a regular expression search and replace
  • preg_last_error() - Returns the error code of the last PCRE regex execution
  • Anonymous functions
  • information about the callback type


Perform a regular expression search and replace

  • « preg_replace_callback
  • preg_split »
  • PHP Manual
  • PCRE Functions
  • Perform a regular expression search and replace

preg_replace

(PHP 4, PHP 5, PHP 7)

preg_replace — Perform a regular expression search and replace

Description

preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] ) : mixed

Searches subject for matches to pattern and replaces them with replacement.

Parameters

pattern

The pattern to search for. It can be either a string or an array with strings.

Several PCRE modifiers are also available.

replacement

The string or an array with strings to replace. If this parameter is a string and the pattern parameter is an array, all patterns will be replaced by that string. If both pattern and replacement parameters are arrays, each pattern will be replaced by the replacement counterpart. If there are fewer elements in the replacement array than in the pattern array, any extra patterns will be replaced by an empty string.

replacement may contain references of the form \\n or $n, with the latter form being the preferred one. Every such reference will be replaced by the text captured by the n'th parenthesized pattern. n can be from 0 to 99, and \\0 or $0 refers to the text matched by the whole pattern. Opening parentheses are counted from left to right (starting from 1) to obtain the number of the capturing subpattern. To use backslash in replacement, it must be doubled ("\\\\" PHP string).

When working with a replacement pattern where a backreference is immediately followed by another number (i.e.: placing a literal number immediately after a matched pattern), you cannot use the familiar \\1 notation for your backreference. \\11, for example, would confuse preg_replace() since it does not know whether you want the \\1 backreference followed by a literal 1, or the \\11 backreference followed by nothing. In this case the solution is to use ${1}1. This creates an isolated $1 backreference, leaving the 1 as a literal.

When using the deprecated e modifier, this function escapes some characters (namely ', ", \ and NULL) in the strings that replace the backreferences. This is done to ensure that no syntax errors arise from backreference usage with either single or double quotes (e.g. 'strlen(\'$1\')+strlen("$2")'). Make sure you are aware of PHP's string syntax to know exactly how the interpreted string will look.

subject

The string or an array with strings to search and replace.

If subject is an array, then the search and replace is performed on every entry of subject, and the return value is an array as well.

limit

The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit).

count

If specified, this variable will be filled with the number of replacements done.

Return Values

preg_replace() returns an array if the subject parameter is an array, or a string otherwise.

If matches are found, the new subject will be returned, otherwise subject will be returned unchanged or NULL if an error occurred.

Errors/Exceptions

As of PHP 5.5.0 E_DEPRECATED level error is emitted when passing in the "\e" modifier. As of PHP 7.0.0 using the "\e" modifier is an error; an E_WARNING is emitted in this case.

Changelog

Version | Description
7.0.0 | Support for the /e modifier has been removed. Use preg_replace_callback() instead.
5.5.0 | The /e modifier is deprecated. Use preg_replace_callback() instead. See the PREG_REPLACE_EVAL documentation for additional information about security risks.
5.1.0 | Added the count parameter

Examples

Example #1 Using backreferences followed by numeric literals

<?php
$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1}1,$3';
echo preg_replace($pattern, $replacement, $string);
?>

The above example will output:

April1,2003

Example #2 Using indexed arrays with preg_replace()

<?php
$string = 'The quick brown fox jumps over the lazy dog.';
$patterns = array();
$patterns[0] = '/quick/';
$patterns[1] = '/brown/';
$patterns[2] = '/fox/';
$replacements = array();
$replacements[2] = 'bear';
$replacements[1] = 'black';
$replacements[0] = 'slow';
echo preg_replace($patterns, $replacements, $string);
?>

The above example will output:

The bear black slow jumps over the lazy dog.

By ksorting patterns and replacements, we should get what we wanted.

<?php
ksort($patterns);
ksort($replacements);
echo preg_replace($patterns, $replacements, $string);
?>

The above example will output:

The slow black bear jumps over the lazy dog.

Example #3 Replacing several values

<?php
$patterns = array ('/(19|20)(\d{2})-(\d{1,2})-(\d{1,2})/',
                   '/^\s*{(\w+)}\s*=/');
$replace = array ('\3/\4/\1\2', '$\1 =');
echo preg_replace($patterns, $replace, '{startDate} = 1999-5-27');
?>

The above example will output:

$startDate = 5/27/1999

Example #4 Strip whitespace

This example strips excess whitespace from a string.

<?php
$str = 'foo   o';
$str = preg_replace('/\s\s+/', ' ', $str);
// This will be 'foo o' now
echo $str;
?>

Example #5 Using the count parameter

<?php
$count = 0;

echo preg_replace(array('/\d/', '/\s/'), '*', 'xp 4 to', -1 , $count);
echo $count; //3
?>

The above example will output:

xp***to
3

Notes

Note:

When using arrays with pattern and replacement, the keys are processed in the order they appear in the array. This is not necessarily the same as the numerical index order. If you use indexes to identify which pattern should be replaced by which replacement, you should perform a ksort() on each array prior to calling preg_replace().

See Also

  • PCRE Patterns
  • preg_quote() - Quote regular expression characters
  • preg_filter() - Perform a regular expression search and replace
  • preg_match() - Perform a regular expression match
  • preg_replace_callback() - Perform a regular expression search and replace using a callback
  • preg_split() - Split string by a regular expression
  • preg_last_error() - Returns the error code of the last PCRE regex execution


Split string by a regular expression

  • « preg_replace
  • POSIX Regex »
  • PHP Manual
  • PCRE Functions
  • Split string by a regular expression

preg_split

(PHP 4, PHP 5, PHP 7)

preg_split — Split string by a regular expression

Description

preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] ) : array

Split the given string by a regular expression.

Parameters

pattern

The pattern to search for, as a string.

subject

The input string.

limit

If specified, then only substrings up to limit are returned with the rest of the string being placed in the last substring. A limit of -1 or 0 means "no limit" and, as is standard across PHP, you can use NULL to skip to the flags parameter.

flags

flags can be any combination of the following flags (combined with the | bitwise operator):

PREG_SPLIT_NO_EMPTY
If this flag is set, only non-empty pieces will be returned by preg_split().
PREG_SPLIT_DELIM_CAPTURE
If this flag is set, parenthesized expression in the delimiter pattern will be captured and returned as well.
PREG_SPLIT_OFFSET_CAPTURE

If this flag is set, for every occurring match the appendant string offset will also be returned. Note that this changes the return value in an array where every element is an array consisting of the matched string at offset 0 and its string offset into subject at offset 1.

Return Values

Returns an array containing substrings of subject split along boundaries matched by pattern, or FALSE on failure.

Examples

Example #1 preg_split() example : Get the parts of a search string

<?php
// split the phrase by any number of commas or space characters,
// which include " ", \r, \t, \n and \f
$keywords = preg_split("/[\s,]+/", "hypertext language, programming");
print_r($keywords);
?>

The above example will output:

Array
(
    [0] => hypertext
    [1] => language
    [2] => programming
)

Example #2 Splitting a string into component characters

<?php
$str = 'string';
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($chars);
?>

The above example will output:

Array
(
    [0] => s
    [1] => t
    [2] => r
    [3] => i
    [4] => n
    [5] => g
)

Example #3 Splitting a string into matches and their offsets

<?php
$str = 'hypertext language programming';
$chars = preg_split('/ /', $str, -1, PREG_SPLIT_OFFSET_CAPTURE);
print_r($chars);
?>

The above example will output:

Array
(
    [0] => Array
        (
            [0] => hypertext
            [1] => 0
        )

    [1] => Array
        (
            [0] => language
            [1] => 10
        )

    [2] => Array
        (
            [0] => programming
            [1] => 19
        )

)

Notes

Tip

If you don't need the power of regular expressions, you can choose faster (albeit simpler) alternatives like explode() or str_split().

Tip

If matching fails, an array with a single element containing the input string will be returned.

See Also

  • PCRE Patterns
  • preg_quote() - Quote regular expression characters
  • implode() - Join array elements with a string
  • preg_match() - Perform a regular expression match
  • preg_match_all() - Perform a global regular expression match
  • preg_replace() - Perform a regular expression search and replace
  • preg_last_error() - Returns the error code of the last PCRE regex execution


Regular Expression (POSIX Extended)

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • POSIX Regex Functions
    • ereg_replace — Replace regular expression
    • ereg — Regular expression match
    • eregi_replace — Replace regular expression case insensitive
    • eregi — Case insensitive regular expression match
    • split — Split string into array by regular expression
    • spliti — Split string into array by regular expression case insensitive
    • sql_regcase — Make regular expression for case insensitive match


Introduction

Warning

This feature was DEPRECATED in PHP 5.3.0, and REMOVED in PHP 7.0.0.

Alternatives to this feature include:

  • PCRE (for full regular expression support)
  • fnmatch() (for simpler shell style wildcard pattern matching)
Tip

PHP also supports regular expressions using a Perl-compatible syntax using the PCRE functions. Those functions support non-greedy matching, assertions, conditional subpatterns, and a number of other features not supported by the POSIX-extended regular expression syntax.

Warning

These regular expression functions are not binary-safe. The PCRE functions are.

Regular expressions are used for complex string manipulation. PHP uses the POSIX extended regular expressions as defined by POSIX 1003.2. For a full description of POSIX regular expressions see the » regex man pages included in the regex directory in the PHP distribution. It's in manpage format, so you'll want to do something along the lines of man /usr/local/src/regex/regex.7 in order to read it.


Installation

PHP 7

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/regex.

PHP 5

Warning

Do not change the TYPE unless you know what you are doing.

To enable regexp support configure PHP --with-regex[=TYPE] . TYPE can be one of system, apache, php. The default value is php.

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.


  • « Resource Types
  • Examples »
  • PHP Manual
  • POSIX Regex
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


Examples

Example #1 Regular Expression Examples

<?php
// Returns true if "abc" is found anywhere in $string.
ereg("abc", $string);

// Returns true if "abc" is found at the beginning of $string.
ereg("^abc", $string);

// Returns true if "abc" is found at the end of $string.
ereg("abc$", $string);

// Returns true if client browser is Netscape 2, 3 or MSIE 3.
eregi("(ozilla.[23]|MSIE.3)", $_SERVER["HTTP_USER_AGENT"]);

// Places three space separated words into $regs[1], $regs[2] and $regs[3].
ereg("([[:alnum:]]+) ([[:alnum:]]+) ([[:alnum:]]+)", $string, $regs);

// Put a <br /> tag at the beginning of $string.
$string = ereg_replace("^", "<br />", $string);

// Put a <br /> tag at the end of $string.
$string = ereg_replace("$", "<br />", $string);

// Get rid of any newline characters in $string.
$string = ereg_replace("\n", "", $string);
?>


POSIX Regex Functions

See Also

Warning

This feature was DEPRECATED in PHP 5.3.0, and REMOVED in PHP 7.0.0.

Alternatives to this feature include:

  • PCRE (for full regular expression support)
  • fnmatch() (for simpler shell style wildcard pattern matching)

Table of Contents

  • ereg_replace — Replace regular expression
  • ereg — Regular expression match
  • eregi_replace — Replace regular expression case insensitive
  • eregi — Case insensitive regular expression match
  • split — Split string into array by regular expression
  • spliti — Split string into array by regular expression case insensitive
  • sql_regcase — Make regular expression for case insensitive match


Replace regular expression

  • « POSIX Regex Functions
  • ereg »
  • PHP Manual
  • POSIX Regex Functions
  • Replace regular expression

ereg_replace

(PHP 4, PHP 5)

ereg_replace — Replace regular expression

Warning

This function was DEPRECATED in PHP 5.3.0, and REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • preg_replace()

Description

ereg_replace ( string $pattern , string $replacement , string $string ) : string

This function scans string for matches to pattern, then replaces the matched text with replacement.

Parameters

pattern

A POSIX extended regular expression.

replacement

If pattern contains parenthesized substrings, replacement may contain substrings of the form \digit, which will be replaced by the text matching the digit'th parenthesized substring; \0 will produce the entire contents of string. Up to nine substrings may be used. Parentheses may be nested, in which case they are counted by the opening parenthesis.

string

The input string.

Return Values

The modified string is returned. If no matches are found in string, then it will be returned unchanged.

Examples

For example, the following code snippet prints "This was a test" three times:

Example #1 ereg_replace() example

<?php

$string = "This is a test";
echo str_replace(" is", " was", $string);
echo ereg_replace("( )is", "\\1was", $string);
echo ereg_replace("(( )is)", "\\2was", $string);

?>

One thing to take note of is that if you use an integer value as the replacement parameter, you may not get the results you expect. This is because ereg_replace() will interpret the number as the ordinal value of a character, and apply that. For instance:

Example #2 ereg_replace() example

<?php
/* This will not work as expected. */
$num = 4;
$string = "This string has four words.";
$string = ereg_replace('four', $num, $string);
echo $string;   /* Output: 'This string has   words.' */

/* This will work. */
$num = '4';
$string = "This string has four words.";
$string = ereg_replace('four', $num, $string);
echo $string;   /* Output: 'This string has 4 words.' */
?>

Example #3 Replace URLs with links

<?php
$text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]",
                     '<a href="\\0">\\0</a>', $text);
?>

See Also

  • ereg() - Regular expression match
  • eregi() - Case insensitive regular expression match
  • eregi_replace() - Replace regular expression case insensitive
  • str_replace() - Replace all occurrences of the search string with the replacement string
  • preg_replace() - Perform a regular expression search and replace
  • quotemeta() - Quote meta characters


Regular expression match

  • « ereg_replace
  • eregi_replace »
  • PHP Manual
  • POSIX Regex Functions
  • Regular expression match

ereg

(PHP 4, PHP 5)

ereg — Regular expression match

Warning

This function was DEPRECATED in PHP 5.3.0, and REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • preg_match()

Description

ereg ( string $pattern , string $string [, array &$regs ] ) : int

Searches a string for matches to the regular expression given in pattern in a case-sensitive way.

Parameters

pattern

Case sensitive regular expression.

string

The input string.

regs

If matches are found for parenthesized substrings of pattern and the function is called with the third argument regs, the matches will be stored in the elements of the array regs.

$regs[1] will contain the substring which starts at the first left parenthesis; $regs[2] will contain the substring starting at the second, and so on. $regs[0] will contain a copy of the complete string matched.

Return Values

Returns the length of the matched string if a match for pattern was found in string, or FALSE if no matches were found or an error occurred.

If the optional parameter regs was not passed or the length of the matched string is 0, this function returns 1.

Changelog

Version | Description
4.1.0 | Up to (and including) PHP 4.1.0 $regs will be filled with exactly ten elements, even though more or fewer than ten parenthesized substrings may actually have matched. This has no effect on ereg()'s ability to match more substrings. If no matches are found, $regs will not be altered by ereg().

Examples

Example #1 ereg() example

The following code snippet takes a date in ISO format (YYYY-MM-DD) and prints it in DD.MM.YYYY format:

<?php
if (ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $date, $regs)) {
    echo "$regs[3].$regs[2].$regs[1]";
} else {
    echo "Invalid date format: $date";
}
?>

See Also

  • eregi() - Case insensitive regular expression match
  • ereg_replace() - Replace regular expression
  • eregi_replace() - Replace regular expression case insensitive
  • preg_match() - Perform a regular expression match
  • strpos() - Find the position of the first occurrence of a substring in a string
  • strstr() - Find the first occurrence of a string
  • quotemeta() - Quote meta characters


Replace regular expression case insensitive

  • « ereg
  • eregi »
  • PHP Manual
  • POSIX Regex Functions
  • Replace regular expression case insensitive

eregi_replace

(PHP 4, PHP 5)

eregi_replace — Replace regular expression case insensitive

Warning

This function was DEPRECATED in PHP 5.3.0, and REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • preg_replace() (with the i (PCRE_CASELESS) modifier)

Description

eregi_replace ( string $pattern , string $replacement , string $string ) : string

This function is identical to ereg_replace() except that this ignores case distinction when matching alphabetic characters.

Parameters

pattern

A POSIX extended regular expression.

replacement

If pattern contains parenthesized substrings, replacement may contain substrings of the form \digit, which will be replaced by the text matching the digit'th parenthesized substring; \0 will produce the entire contents of string. Up to nine substrings may be used. Parentheses may be nested, in which case they are counted by the opening parenthesis.

string

The input string.

Return Values

The modified string is returned. If no matches are found in string, then it will be returned unchanged.

Examples

Example #1 Highlight search results

<?php
$pattern = '(>[^<]*)('. quotemeta($_GET['search']) .')';
$replacement = '\\1<span class="search">\\2</span>';
$body = eregi_replace($pattern, $replacement, $body);
?>

See Also

  • ereg() - Regular expression match
  • eregi() - Case insensitive regular expression match
  • ereg_replace() - Replace regular expression
  • preg_replace() - Perform a regular expression search and replace
  • quotemeta() - Quote meta characters


Case insensitive regular expression match

  • « eregi_replace
  • split »
  • PHP Manual
  • POSIX Regex Functions
  • Case insensitive regular expression match

eregi

(PHP 4, PHP 5)

eregi — Case insensitive regular expression match

Warning

This function was DEPRECATED in PHP 5.3.0, and REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • preg_match() (with the i (PCRE_CASELESS) modifier)

Description

eregi ( string $pattern , string $string [, array &$regs ] ) : int

This function is identical to ereg() except that it ignores case distinction when matching alphabetic characters.

Parameters

pattern

Case insensitive regular expression.

string

The input string.

regs

If matches are found for parenthesized substrings of pattern and the function is called with the third argument regs, the matches will be stored in the elements of the array regs.

$regs[1] will contain the substring which starts at the first left parenthesis; $regs[2] will contain the substring starting at the second, and so on. $regs[0] will contain a copy of the complete string matched.

Return Values

Returns the length of the matched string if a match for pattern was found in string, or FALSE if no matches were found or an error occurred.

If the optional parameter regs was not passed or the length of the matched string is 0, this function returns 1.

Examples

Example #1 eregi() example

<?php
$string = 'XYZ';
if (eregi('z', $string)) {
    echo "'$string' contains a 'z' or 'Z'!";
}
?>

See Also

  • ereg() - Regular expression match
  • ereg_replace() - Replace regular expression
  • eregi_replace() - Replace regular expression case insensitive
  • preg_match() - Perform a regular expression match
  • stripos() - Find the position of the first occurrence of a case-insensitive substring in a string
  • stristr() - Case-insensitive strstr
  • quotemeta() - Quote meta characters


Split string into array by regular expression

  • « eregi
  • spliti »
  • PHP Manual
  • POSIX Regex Functions
  • Split string into array by regular expression

split

(PHP 4, PHP 5)

split — Split string into array by regular expression

Warning

This function was DEPRECATED in PHP 5.3.0, and REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • preg_split()
  • explode()
  • str_split()

Description

split ( string $pattern , string $string [, int $limit = -1 ] ) : array

Splits a string into array by regular expression.

Parameters

pattern

Case sensitive regular expression.

If you want to split on any of the characters which are considered special by regular expressions, you'll need to escape them first. If you think split() (or any other regex function, for that matter) is doing something weird, please read the file regex.7, included in the regex/ subdirectory of the PHP distribution. It's in manpage format, so you'll want to do something along the lines of man /usr/local/src/regex/regex.7 in order to read it.

string

The input string.

limit

If limit is set, the returned array will contain a maximum of limit elements with the last element containing the whole rest of string.

Return Values

Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the case-sensitive regular expression pattern.

If there are n occurrences of pattern, the returned array will contain n+1 items. For example, if there is no occurrence of pattern, an array with only one element will be returned. Of course, this is also true if string is empty. If an error occurs, split() returns FALSE.

Examples

Example #1 split() example

To split off the first four fields from a line from /etc/passwd:

<?php
list($user, $pass, $uid, $gid, $extra) =
    split(":", $passwd_line, 5);
?>

Example #2 split() example

To parse a date which may be delimited with slashes, dots, or hyphens:

<?php
// Delimiters may be slash, dot, or hyphen
$date = "04/30/1973";
list($month, $day, $year) = split('[/.-]', $date);
echo "Month: $month; Day: $day; Year: $year<br />\n";
?>

Notes

Tip

split() is deprecated as of PHP 5.3.0. preg_split() is the suggested alternative to this function. If you don't require the power of regular expressions, it is faster to use explode(), which doesn't incur the overhead of the regular expression engine.

Tip

For users looking for a way to emulate Perl's @chars = split('', $str) behaviour, please see the examples for preg_split() or str_split().

See Also

  • preg_split() - Split string by a regular expression
  • spliti() - Split string into array by regular expression case insensitive
  • str_split() - Convert a string to an array
  • explode() - Split a string by a string
  • implode() - Join array elements with a string
  • chunk_split() - Split a string into smaller chunks
  • wordwrap() - Wraps a string to a given number of characters


Split string into array by regular expression case insensitive

  • « split
  • sql_regcase »
  • PHP Manual
  • POSIX Regex Functions
  • Split string into array by regular expression case insensitive

spliti

(PHP 4 >= 4.0.1, PHP 5)

spliti — Split string into array by regular expression case insensitive

Warning

This function was DEPRECATED in PHP 5.3.0, and REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • preg_split() (with the i (PCRE_CASELESS) modifier)

Description

spliti ( string $pattern , string $string [, int $limit = -1 ] ) : array

Splits a string into array by regular expression.

This function is identical to split() except that this ignores case distinction when matching alphabetic characters.

Parameters

pattern

Case insensitive regular expression.

If you want to split on any of the characters which are considered special by regular expressions, you'll need to escape them first. If you think spliti() (or any other regex function, for that matter) is doing something weird, please read the file regex.7, included in the regex/ subdirectory of the PHP distribution. It's in manpage format, so you'll want to do something along the lines of man /usr/local/src/regex/regex.7 in order to read it.

string

The input string.

limit

If limit is set, the returned array will contain a maximum of limit elements with the last element containing the whole rest of string.

Return Values

Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the case insensitive regular expression pattern.

If there are n occurrences of pattern, the returned array will contain n+1 items. For example, if there is no occurrence of pattern, an array with only one element will be returned. Of course, this is also true if string is empty. If an error occurs, spliti() returns FALSE.

Examples

This example splits a string using 'a' as the separator :

Example #1 spliti() example

<?php
$string = "aBBBaCCCADDDaEEEaGGGA";
$chunks = spliti ("a", $string, 5);
print_r($chunks);
?>

The above example will output:

Array
(
  [0] =>
  [1] => BBB
  [2] => CCC
  [3] => DDD
  [4] => EEEaGGGA
)

See Also

  • preg_split() - Split string by a regular expression
  • split() - Split string into array by regular expression
  • explode() - Split a string by a string
  • implode() - Join array elements with a string


Make regular expression for case insensitive match

  • « spliti
  • ssdeep »
  • PHP Manual
  • POSIX Regex Functions
  • Make regular expression for case insensitive match

sql_regcase

(PHP 4, PHP 5)

sql_regcase — Make regular expression for case insensitive match

Warning

This function was DEPRECATED in PHP 5.3.0, and REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • preg_match()
  • preg_quote()

Description

sql_regcase ( string $string ) : string

Creates a regular expression for a case insensitive match.

Parameters

string

The input string.

Return Values

Returns a valid regular expression which will match string, ignoring case. This expression is string with each alphabetic character converted to a bracket expression; this bracket expression contains that character's uppercase and lowercase form. Other characters remain unchanged.

Examples

Example #1 sql_regcase() example

<?php
echo sql_regcase("Foo - bar.");
?>

The above example will output:

[Ff][Oo][Oo] - [Bb][Aa][Rr].

This can be used to achieve case insensitive pattern matching in products which support only case sensitive regular expressions.


ssdeep Fuzzy Hashing

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • ssdeep Functions
    • ssdeep_fuzzy_compare — Calculates the match score between two fuzzy hash signatures
    • ssdeep_fuzzy_hash_filename — Create a fuzzy hash from a file
    • ssdeep_fuzzy_hash — Create a fuzzy hash from a string


Introduction

ssdeep is a utility for creating and comparing fuzzy hashes or » context-triggered piecewise hashing.

Fuzzy hashing can match signatures which have "...sequences of identical bytes in the same order, although bytes in between these sequences may be different in both content and length". (» ssdeep project page)

This extension provides functions for creating and comparing fuzzy hashes.


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

This extension requires the » ssdeep library.


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/ssdeep.


  • « Resource Types
  • ssdeep Functions »
  • PHP Manual
  • ssdeep
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


ssdeep Functions

Table of Contents

  • ssdeep_fuzzy_compare — Calculates the match score between two fuzzy hash signatures
  • ssdeep_fuzzy_hash_filename — Create a fuzzy hash from a file
  • ssdeep_fuzzy_hash — Create a fuzzy hash from a string


Calculates the match score between two fuzzy hash signatures

  • « ssdeep Functions
  • ssdeep_fuzzy_hash_filename »
  • PHP Manual
  • ssdeep Functions
  • Calculates the match score between two fuzzy hash signatures

ssdeep_fuzzy_compare

(PECL ssdeep >= 1.0.0)

ssdeep_fuzzy_compare — Calculates the match score between two fuzzy hash signatures

Description

ssdeep_fuzzy_compare ( string $signature1 , string $signature2 ) : int

Calculates the match score between signature1 and signature2 using » context-triggered piecewise hashing, and returns the match score.

Parameters

signature1

The first fuzzy hash signature string.

signature2

The second fuzzy hash signature string.

Return Values

Returns an integer from 0 to 100 on success, FALSE otherwise.


Create a fuzzy hash from a file

  • « ssdeep_fuzzy_compare
  • ssdeep_fuzzy_hash »
  • PHP Manual
  • ssdeep Functions
  • Create a fuzzy hash from a file

ssdeep_fuzzy_hash_filename

(PECL ssdeep >= 1.0.0)

ssdeep_fuzzy_hash_filename — Create a fuzzy hash from a file

Description

ssdeep_fuzzy_hash_filename ( string $file_name ) : string

ssdeep_fuzzy_hash_filename() calculates the hash of the file specified by file_name using » context-triggered piecewise hashing, and returns that hash.

Parameters

file_name

The filename of the file to hash.

Return Values

Returns a string on success, FALSE otherwise.


Create a fuzzy hash from a string

  • « ssdeep_fuzzy_hash_filename
  • Strings »
  • PHP Manual
  • ssdeep Functions
  • Create a fuzzy hash from a string

ssdeep_fuzzy_hash

(PECL ssdeep >= 1.0.0)

ssdeep_fuzzy_hash — Create a fuzzy hash from a string

Description

ssdeep_fuzzy_hash ( string $to_hash ) : string

ssdeep_fuzzy_hash() calculates the hash of to_hash using » context-triggered piecewise hashing, and returns that hash.

Parameters

to_hash

The input string.

Return Values

Returns a string on success, FALSE otherwise.


Strings

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • String Functions
    • addcslashes — Quote string with slashes in a C style
    • addslashes — Quote string with slashes
    • bin2hex — Convert binary data into hexadecimal representation
    • chop — Alias of rtrim
    • chr — Generate a single-byte string from a number
    • chunk_split — Split a string into smaller chunks
    • convert_cyr_string — Convert from one Cyrillic character set to another
    • convert_uudecode — Decode a uuencoded string
    • convert_uuencode — Uuencode a string
    • count_chars — Return information about characters used in a string
    • crc32 — Calculates the crc32 polynomial of a string
    • crypt — One-way string hashing
    • echo — Output one or more strings
    • explode — Split a string by a string
    • fprintf — Write a formatted string to a stream
    • get_html_translation_table — Returns the translation table used by htmlspecialchars and htmlentities
    • hebrev — Convert logical Hebrew text to visual text
    • hebrevc — Convert logical Hebrew text to visual text with newline conversion
    • hex2bin — Decodes a hexadecimally encoded binary string
    • html_entity_decode — Convert HTML entities to their corresponding characters
    • htmlentities — Convert all applicable characters to HTML entities
    • htmlspecialchars_decode — Convert special HTML entities back to characters
    • htmlspecialchars — Convert special characters to HTML entities
    • implode — Join array elements with a string
    • join — Alias of implode
    • lcfirst — Make a string's first character lowercase
    • levenshtein — Calculate Levenshtein distance between two strings
    • localeconv — Get numeric formatting information
    • ltrim — Strip whitespace (or other characters) from the beginning of a string
    • md5_file — Calculates the md5 hash of a given file
    • md5 — Calculate the md5 hash of a string
    • metaphone — Calculate the metaphone key of a string
    • money_format — Formats a number as a currency string
    • nl_langinfo — Query language and locale information
    • nl2br — Inserts HTML line breaks before all newlines in a string
    • number_format — Format a number with grouped thousands
    • ord — Convert the first byte of a string to a value between 0 and 255
    • parse_str — Parses the string into variables
    • print — Output a string
    • printf — Output a formatted string
    • quoted_printable_decode — Convert a quoted-printable string to an 8 bit string
    • quoted_printable_encode — Convert a 8 bit string to a quoted-printable string
    • quotemeta — Quote meta characters
    • rtrim — Strip whitespace (or other characters) from the end of a string
    • setlocale — Set locale information
    • sha1_file — Calculate the sha1 hash of a file
    • sha1 — Calculate the sha1 hash of a string
    • similar_text — Calculate the similarity between two strings
    • soundex — Calculate the soundex key of a string
    • sprintf — Return a formatted string
    • sscanf — Parses input from a string according to a format
    • str_getcsv — Parse a CSV string into an array
    • str_ireplace — Case-insensitive version of str_replace
    • str_pad — Pad a string to a certain length with another string
    • str_repeat — Repeat a string
    • str_replace — Replace all occurrences of the search string with the replacement string
    • str_rot13 — Perform the rot13 transform on a string
    • str_shuffle — Randomly shuffles a string
    • str_split — Convert a string to an array
    • str_word_count — Return information about words used in a string
    • strcasecmp — Binary safe case-insensitive string comparison
    • strchr — Alias of strstr
    • strcmp — Binary safe string comparison
    • strcoll — Locale based string comparison
    • strcspn — Find length of initial segment not matching mask
    • strip_tags — Strip HTML and PHP tags from a string
    • stripcslashes — Un-quote string quoted with addcslashes
    • stripos — Find the position of the first occurrence of a case-insensitive substring in a string
    • stripslashes — Un-quotes a quoted string
    • stristr — Case-insensitive strstr
    • strlen — Get string length
    • strnatcasecmp — Case insensitive string comparisons using a "natural order" algorithm
    • strnatcmp — String comparisons using a "natural order" algorithm
    • strncasecmp — Binary safe case-insensitive string comparison of the first n characters
    • strncmp — Binary safe string comparison of the first n characters
    • strpbrk — Search a string for any of a set of characters
    • strpos — Find the position of the first occurrence of a substring in a string
    • strrchr — Find the last occurrence of a character in a string
    • strrev — Reverse a string
    • 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
    • strspn — Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask
    • strstr — Find the first occurrence of a string
    • strtok — Tokenize string
    • strtolower — Make a string lowercase
    • strtoupper — Make a string uppercase
    • strtr — Translate characters or replace substrings
    • substr_compare — Binary safe comparison of two strings from an offset, up to length characters
    • substr_count — Count the number of substring occurrences
    • substr_replace — Replace text within a portion of a string
    • substr — Return part of a string
    • trim — Strip whitespace (or other characters) from the beginning and end of a string
    • ucfirst — Make a string's first character uppercase
    • ucwords — Uppercase the first character of each word in a string
    • vfprintf — Write a formatted string to a stream
    • vprintf — Output a formatted string
    • vsprintf — Return a formatted string
    • wordwrap — Wraps a string to a given number of characters
  • Changelog


Introduction

These functions all manipulate strings in various ways. Some more specialized sections can be found in the regular expression and URL handling sections.

For information on how strings behave, especially with regard to usage of single quotes, double quotes, and escape sequences, see the Strings entry in the Types section of the manual.


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.

CRYPT_SALT_LENGTH integer
CRYPT_STD_DES integer
CRYPT_EXT_DES integer
CRYPT_MD5 integer
CRYPT_BLOWFISH integer
HTML_SPECIALCHARS (integer)
HTML_ENTITIES (integer)
ENT_COMPAT (integer)
ENT_QUOTES (integer)
ENT_NOQUOTES (integer)
ENT_IGNORE (integer)
ENT_SUBSTITUTE (integer)
ENT_DISALLOWED (integer)
ENT_HTML401 (integer)
ENT_XML1 (integer)
ENT_XHTML (integer)
ENT_HTML5 (integer)
CHAR_MAX (integer)
LC_CTYPE (integer)
LC_NUMERIC (integer)
LC_TIME (integer)
LC_COLLATE (integer)
LC_MONETARY (integer)
LC_ALL (integer)
LC_MESSAGES (integer)
STR_PAD_LEFT (integer)
STR_PAD_RIGHT (integer)
STR_PAD_BOTH (integer)


String Functions

See Also

For even more powerful string handling and manipulating functions take a look at the Perl compatible regular expression functions. For working with multibyte character encodings, take a look at the Multibyte String functions.

Table of Contents

  • addcslashes — Quote string with slashes in a C style
  • addslashes — Quote string with slashes
  • bin2hex — Convert binary data into hexadecimal representation
  • chop — Alias of rtrim
  • chr — Generate a single-byte string from a number
  • chunk_split — Split a string into smaller chunks
  • convert_cyr_string — Convert from one Cyrillic character set to another
  • convert_uudecode — Decode a uuencoded string
  • convert_uuencode — Uuencode a string
  • count_chars — Return information about characters used in a string
  • crc32 — Calculates the crc32 polynomial of a string
  • crypt — One-way string hashing
  • echo — Output one or more strings
  • explode — Split a string by a string
  • fprintf — Write a formatted string to a stream
  • get_html_translation_table — Returns the translation table used by htmlspecialchars and htmlentities
  • hebrev — Convert logical Hebrew text to visual text
  • hebrevc — Convert logical Hebrew text to visual text with newline conversion
  • hex2bin — Decodes a hexadecimally encoded binary string
  • html_entity_decode — Convert HTML entities to their corresponding characters
  • htmlentities — Convert all applicable characters to HTML entities
  • htmlspecialchars_decode — Convert special HTML entities back to characters
  • htmlspecialchars — Convert special characters to HTML entities
  • implode — Join array elements with a string
  • join — Alias of implode
  • lcfirst — Make a string's first character lowercase
  • levenshtein — Calculate Levenshtein distance between two strings
  • localeconv — Get numeric formatting information
  • ltrim — Strip whitespace (or other characters) from the beginning of a string
  • md5_file — Calculates the md5 hash of a given file
  • md5 — Calculate the md5 hash of a string
  • metaphone — Calculate the metaphone key of a string
  • money_format — Formats a number as a currency string
  • nl_langinfo — Query language and locale information
  • nl2br — Inserts HTML line breaks before all newlines in a string
  • number_format — Format a number with grouped thousands
  • ord — Convert the first byte of a string to a value between 0 and 255
  • parse_str — Parses the string into variables
  • print — Output a string
  • printf — Output a formatted string
  • quoted_printable_decode — Convert a quoted-printable string to an 8 bit string
  • quoted_printable_encode — Convert a 8 bit string to a quoted-printable string
  • quotemeta — Quote meta characters
  • rtrim — Strip whitespace (or other characters) from the end of a string
  • setlocale — Set locale information
  • sha1_file — Calculate the sha1 hash of a file
  • sha1 — Calculate the sha1 hash of a string
  • similar_text — Calculate the similarity between two strings
  • soundex — Calculate the soundex key of a string
  • sprintf — Return a formatted string
  • sscanf — Parses input from a string according to a format
  • str_getcsv — Parse a CSV string into an array
  • str_ireplace — Case-insensitive version of str_replace
  • str_pad — Pad a string to a certain length with another string
  • str_repeat — Repeat a string
  • str_replace — Replace all occurrences of the search string with the replacement string
  • str_rot13 — Perform the rot13 transform on a string
  • str_shuffle — Randomly shuffles a string
  • str_split — Convert a string to an array
  • str_word_count — Return information about words used in a string
  • strcasecmp — Binary safe case-insensitive string comparison
  • strchr — Alias of strstr
  • strcmp — Binary safe string comparison
  • strcoll — Locale based string comparison
  • strcspn — Find length of initial segment not matching mask
  • strip_tags — Strip HTML and PHP tags from a string
  • stripcslashes — Un-quote string quoted with addcslashes
  • stripos — Find the position of the first occurrence of a case-insensitive substring in a string
  • stripslashes — Un-quotes a quoted string
  • stristr — Case-insensitive strstr
  • strlen — Get string length
  • strnatcasecmp — Case insensitive string comparisons using a "natural order" algorithm
  • strnatcmp — String comparisons using a "natural order" algorithm
  • strncasecmp — Binary safe case-insensitive string comparison of the first n characters
  • strncmp — Binary safe string comparison of the first n characters
  • strpbrk — Search a string for any of a set of characters
  • strpos — Find the position of the first occurrence of a substring in a string
  • strrchr — Find the last occurrence of a character in a string
  • strrev — Reverse a string
  • 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
  • strspn — Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask
  • strstr — Find the first occurrence of a string
  • strtok — Tokenize string
  • strtolower — Make a string lowercase
  • strtoupper — Make a string uppercase
  • strtr — Translate characters or replace substrings
  • substr_compare — Binary safe comparison of two strings from an offset, up to length characters
  • substr_count — Count the number of substring occurrences
  • substr_replace — Replace text within a portion of a string
  • substr — Return part of a string
  • trim — Strip whitespace (or other characters) from the beginning and end of a string
  • ucfirst — Make a string's first character uppercase
  • ucwords — Uppercase the first character of each word in a string
  • vfprintf — Write a formatted string to a stream
  • vprintf — Output a formatted string
  • vsprintf — Return a formatted string
  • wordwrap — Wraps a string to a given number of characters


Quote string with slashes in a C style

  • « String Functions
  • addslashes »
  • PHP Manual
  • String Functions
  • Quote string with slashes in a C style

addcslashes

(PHP 4, PHP 5, PHP 7)

addcslashes — Quote string with slashes in a C style

Description

addcslashes ( string $str , string $charlist ) : string

Returns a string with backslashes before characters that are listed in charlist parameter.

Parameters

str

The string to be escaped.

charlist

A list of characters to be escaped. If charlist contains characters \n, \r etc., they are converted in C-like style, while other non-alphanumeric characters with ASCII codes lower than 32 and higher than 126 converted to octal representation.

When you define a sequence of characters in the charlist argument make sure that you know what characters come between the characters that you set as the start and end of the range.

<?php
echo addcslashes('foo[ ]', 'A..z');
// output:  \f\o\o\[ \]
// All upper and lower-case letters will be escaped
// ... but so will the [\]^_`
?>
Also, if the first character in a range has a higher ASCII value than the second character in the range, no range will be constructed. Only the start, end and period characters will be escaped. Use the ord() function to find the ASCII value for a character.
<?php
echo addcslashes("zoo['.']", 'z..A');
// output:  \zoo['\.']
?>

Be careful if you choose to escape characters 0, a, b, f, n, r, t and v. They will be converted to \0, \a, \b, \f, \n, \r, \t and \v, all of which are predefined escape sequences in C. Many of these sequences are also defined in other C-derived languages, including PHP, meaning that you may not get the desired result if you use the output of addcslashes() to generate code in those languages with these characters defined in charlist.

Return Values

Returns the escaped string.

Changelog

Version | Description
5.2.5 | The escape sequences \v and \f were added.

Examples

charlist like "\0..\37", which would escape all characters with ASCII code between 0 and 31.

Example #1 addcslashes() example

<?php
$escaped = addcslashes($not_escaped, "\0..\37!@\177..\377");
?>

See Also

  • stripcslashes() - Un-quote string quoted with addcslashes
  • stripslashes() - Un-quotes a quoted string
  • addslashes() - Quote string with slashes
  • htmlspecialchars() - Convert special characters to HTML entities
  • quotemeta() - Quote meta characters


Quote string with slashes

  • « addcslashes
  • bin2hex »
  • PHP Manual
  • String Functions
  • Quote string with slashes

addslashes

(PHP 4, PHP 5, PHP 7)

addslashes — Quote string with slashes

Description

addslashes ( string $str ) : string

Returns a string with backslashes added before characters that need to be escaped. These characters are:

  • single quote (')
  • double quote (")
  • backslash (\)
  • NUL (the NUL byte)

A use case of addslashes() is escaping the aforementioned characters in a string that is to be evaluated by PHP:

<?php
$str = "O'Reilly?";
eval("echo '" . addslashes($str) . "';");
?>

Prior to PHP 5.4.0, the PHP directive magic_quotes_gpc was on by default and it essentially ran addslashes() on all GET, POST and COOKIE data. addslashes() must not be used on strings that have already been escaped with magic_quotes_gpc, as the strings will be double escaped. get_magic_quotes_gpc() can be used to check if magic_quotes_gpc is on.

The addslashes() is sometimes incorrectly used to try to prevent SQL Injection. Instead, database-specific escaping functions and/or prepared statements should be used.

Parameters

str

The string to be escaped.

Return Values

Returns the escaped string.

Examples

Example #1 An addslashes() example

<?php
$str = "Is your name O'Reilly?";

// Outputs: Is your name O\'Reilly?
echo addslashes($str);
?>

See Also

  • stripcslashes() - Un-quote string quoted with addcslashes
  • stripslashes() - Un-quotes a quoted string
  • addcslashes() - Quote string with slashes in a C style
  • htmlspecialchars() - Convert special characters to HTML entities
  • quotemeta() - Quote meta characters
  • get_magic_quotes_gpc() - Gets the current configuration setting of magic_quotes_gpc


Convert binary data into hexadecimal representation

  • « addslashes
  • chop »
  • PHP Manual
  • String Functions
  • Convert binary data into hexadecimal representation

bin2hex

(PHP 4, PHP 5, PHP 7)

bin2hex — Convert binary data into hexadecimal representation

Description

bin2hex ( string $str ) : string

Returns an ASCII string containing the hexadecimal representation of str. The conversion is done byte-wise with the high-nibble first.

Parameters

str

A string.

Return Values

Returns the hexadecimal representation of the given string.

See Also

  • hex2bin() - Decodes a hexadecimally encoded binary string
  • pack() - Pack data into binary string


Alias of rtrim

  • « bin2hex
  • chr »
  • PHP Manual
  • String Functions
  • Alias of rtrim

chop

(PHP 4, PHP 5, PHP 7)

chop — Alias of rtrim()

Description

This function is an alias of: rtrim().

Notes

Note:

chop() is different than the Perl chop() function, which removes the last character in the string.


Generate a single-byte string from a number

  • « chop
  • chunk_split »
  • PHP Manual
  • String Functions
  • Generate a single-byte string from a number

chr

(PHP 4, PHP 5, PHP 7)

chr — Generate a single-byte string from a number

Description

chr ( int $bytevalue ) : string

Returns a one-character string containing the character specified by interpreting bytevalue as an unsigned integer.

This can be used to create a one-character string in a single-byte encoding such as ASCII, ISO-8859, or Windows 1252, by passing the position of a desired character in the encoding's mapping table. However, note that this function is not aware of any string encoding, and in particular cannot be passed a Unicode code point value to generate a string in a multibyte encoding like UTF-8 or UTF-16.

This function complements ord().

Parameters

bytevalue

An integer between 0 and 255.

Values outside the valid range (0..255) will be bitwise and'ed with 255, which is equivalent to the following algorithm:

while ($bytevalue < 0) {
    $bytevalue += 256;
}
$bytevalue %= 256;

Return Values

A single-character string containing the specified byte.

Examples

Example #1 chr() example

<?php
// Assumes the string will be used as ASCII or an ASCII-compatible encoding

$str = "The string ends in escape: ";
$str .= chr(27); /* add an escape character at the end of $str */

/* Often this is more useful */

$str = sprintf("The string ends in escape: %c", 27);
?>

Example #2 Overflow behavior

<?php
echo chr(-159), chr(833), PHP_EOL;
?>

The above example will output:

aA

Example #3 Building a UTF-8 string from individual bytes

<?php
declare(encoding='UTF-8');
$str = chr(240) . chr(159) . chr(144) . chr(152);
echo $str;
?>

The above example will output:

🐘

See Also

  • sprintf() - Return a formatted string with a format string of %c
  • ord()
  • An » ASCII-table
  • mb_chr()


Split a string into smaller chunks

  • « chr
  • convert_cyr_string »
  • PHP Manual
  • String Functions
  • Split a string into smaller chunks

chunk_split

(PHP 4, PHP 5, PHP 7)

chunk_split — Split a string into smaller chunks

Description

chunk_split ( string $body [, int $chunklen = 76 [, string $end = "\r\n" ]] ) : string

Can be used to split a string into smaller chunks which is useful for e.g. converting base64_encode() output to match RFC 2045 semantics. It inserts end every chunklen characters.

Parameters

body

The string to be chunked.

chunklen

The chunk length.

end

The line ending sequence.

Return Values

Returns the chunked string.

Examples

Example #1 chunk_split() example

<?php
// format $data using RFC 2045 semantics
$new_string = chunk_split(base64_encode($data));
?>

See Also

  • str_split() - Convert a string to an array
  • explode() - Split a string by a string
  • split() - Split string into array by regular expression
  • wordwrap() - Wraps a string to a given number of characters
  • » RFC 2045


Convert from one Cyrillic character set to another

  • « chunk_split
  • convert_uudecode »
  • PHP Manual
  • String Functions
  • Convert from one Cyrillic character set to another

convert_cyr_string

(PHP 4, PHP 5, PHP 7)

convert_cyr_string — Convert from one Cyrillic character set to another

Description

convert_cyr_string ( string $str , string $from , string $to ) : string

Converts from one Cyrillic character set to another.

Parameters

str

The string to be converted.

from

The source Cyrillic character set, as a single character.

to

The target Cyrillic character set, as a single character.

Supported characters are:

  • k - koi8-r
  • w - windows-1251
  • i - iso8859-5
  • a - x-cp866
  • d - x-cp866
  • m - x-mac-cyrillic

Return Values

Returns the converted string.

Notes

Note: This function is binary-safe.

See Also

  • mb_convert_encoding() - Convert character encoding
  • iconv() - Convert string to requested character encoding


Decode a uuencoded string

  • « convert_cyr_string
  • convert_uuencode »
  • PHP Manual
  • String Functions
  • Decode a uuencoded string

convert_uudecode

(PHP 5, PHP 7)

convert_uudecode — Decode a uuencoded string

Description

convert_uudecode ( string $data ) : string

convert_uudecode() decodes a uuencoded string.

Note: convert_uudecode() neither accepts the begin nor the end line, which are part of uuencoded files.

Parameters

data

The uuencoded data.

Return Values

Returns the decoded data as a string or FALSE on failure.

Examples

Example #1 convert_uudecode() example

<?php
echo convert_uudecode("+22!L;W9E(%!(4\"$`\n`");
?>

The above example will output:

I love PHP!

See Also

  • convert_uuencode() - Uuencode a string


Uuencode a string

  • « convert_uudecode
  • count_chars »
  • PHP Manual
  • String Functions
  • Uuencode a string

convert_uuencode

(PHP 5, PHP 7)

convert_uuencode — Uuencode a string

Description

convert_uuencode ( string $data ) : string

convert_uuencode() encodes a string using the uuencode algorithm.

Uuencode translates all strings (including binary data) into printable characters, making them safe for network transmissions. Uuencoded data is about 35% larger than the original.

Note: convert_uuencode() neither produces the begin nor the end line, which are part of uuencoded files.

Parameters

data

The data to be encoded.

Return Values

Returns the uuencoded data or FALSE on failure.

Examples

Example #1 convert_uuencode() example

<?php
$some_string = "test\ntext text\r\n";

echo convert_uuencode($some_string);
?>

The above example will output:

0=&5S=`IT97AT('1E>'0-"@``
`

See Also

  • convert_uudecode() - Decode a uuencoded string
  • base64_encode() - Encodes data with MIME base64


Return information about characters used in a string

  • « convert_uuencode
  • crc32 »
  • PHP Manual
  • String Functions
  • Return information about characters used in a string

count_chars

(PHP 4, PHP 5, PHP 7)

count_chars — Return information about characters used in a string

Description

count_chars ( string $string [, int $mode = 0 ] ) : mixed

Counts the number of occurrences of every byte-value (0..255) in string and returns it in various ways.

Parameters

string

The examined string.

mode

See return values.

Return Values

Depending on mode count_chars() returns one of the following:

  • 0 - an array with the byte-value as key and the frequency of every byte as value.
  • 1 - same as 0 but only byte-values with a frequency greater than zero are listed.
  • 2 - same as 0 but only byte-values with a frequency equal to zero are listed.
  • 3 - a string containing all unique characters is returned.
  • 4 - a string containing all not used characters is returned.

Examples

Example #1 count_chars() example

<?php
$data = "Two Ts and one F.";

foreach (count_chars($data, 1) as $i => $val) {
   echo "There were $val instance(s) of \"" , chr($i) , "\" in the string.\n";
}
?>

The above example will output:

There were 4 instance(s) of " " in the string.
There were 1 instance(s) of "." in the string.
There were 1 instance(s) of "F" in the string.
There were 2 instance(s) of "T" in the string.
There were 1 instance(s) of "a" in the string.
There were 1 instance(s) of "d" in the string.
There were 1 instance(s) of "e" in the string.
There were 2 instance(s) of "n" in the string.
There were 2 instance(s) of "o" in the string.
There were 1 instance(s) of "s" in the string.
There were 1 instance(s) of "w" in the string.

See Also

  • strpos() - Find the position of the first occurrence of a substring in a string
  • substr_count() - Count the number of substring occurrences


Calculates the crc32 polynomial of a string

  • « count_chars
  • crypt »
  • PHP Manual
  • String Functions
  • Calculates the crc32 polynomial of a string

crc32

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

crc32 — Calculates the crc32 polynomial of a string

Description

crc32 ( string $str ) : int

Generates the cyclic redundancy checksum polynomial of 32-bit lengths of the str. This is usually used to validate the integrity of data being transmitted.

Warning

Because PHP's integer type is signed many crc32 checksums will result in negative integers on 32bit platforms. On 64bit installations all crc32() results will be positive integers though.

So you need to use the "%u" formatter of sprintf() or printf() to get the string representation of the unsigned crc32() checksum in decimal format.

For a hexadecimal representation of the checksum you can either use the "%x" formatter of sprintf() or printf() or the dechex() conversion functions, both of these also take care of converting the crc32() result to an unsigned integer.

Having 64bit installations also return negative integers for higher result values was considered but would break the hexadecimal conversion as negatives would get an extra 0xFFFFFFFF######## offset then. As hexadecimal representation seems to be the most common use case we decided to not break this even if it breaks direct decimal comparisons in about 50% of the cases when moving from 32 to 64bits.

In retrospect having the function return an integer maybe wasn't the best idea and returning a hex string representation right away (as e.g. md5() does) might have been a better plan to begin with.

For a more portable solution you may also consider the generic hash(). hash("crc32b", $str) will return the same string as str_pad(dechex(crc32($str)), 8, '0', STR_PAD_LEFT).

Parameters

str

The data.

Return Values

Returns the crc32 checksum of str as an integer.

Examples

Example #1 Displaying a crc32 checksum

This example shows how to print a converted checksum with the printf() function:

<?php
$checksum = crc32("The quick brown fox jumped over the lazy dog.");
printf("%u\n", $checksum);
?>

See Also

  • hash() - Generate a hash value (message digest)
  • md5() - Calculate the md5 hash of a string
  • sha1() - Calculate the sha1 hash of a string


One-way string hashing

  • « crc32
  • echo »
  • PHP Manual
  • String Functions
  • One-way string hashing

crypt

(PHP 4, PHP 5, PHP 7)

crypt — One-way string hashing

Warning

This function is not (yet) binary safe!

Description

crypt ( string $str [, string $salt ] ) : string

crypt() will return a hashed string using the standard Unix DES-based algorithm or alternative algorithms that may be available on the system.

The salt parameter is optional. However, crypt() creates a weak hash without the salt. PHP 5.6 or later raise an E_NOTICE error without it. Make sure to specify a strong enough salt for better security.

password_hash() uses a strong hash, generates a strong salt, and applies proper rounds automatically. password_hash() is a simple crypt() wrapper and compatible with existing password hashes. Use of password_hash() is encouraged.

Some operating systems support more than one type of hash. In fact, sometimes the standard DES-based algorithm is replaced by an MD5-based algorithm. The hash type is triggered by the salt argument. Prior to 5.3, PHP would determine the available algorithms at install-time based on the system's crypt(). If no salt is provided, PHP will auto-generate either a standard two character (DES) salt, or a twelve character (MD5), depending on the availability of MD5 crypt(). PHP sets a constant named CRYPT_SALT_LENGTH which indicates the longest valid salt allowed by the available hashes.

The standard DES-based crypt() returns the salt as the first two characters of the output. It also only uses the first eight characters of str, so longer strings that start with the same eight characters will generate the same result (when the same salt is used).

On systems where the crypt() function supports multiple hash types, the following constants are set to 0 or 1 depending on whether the given type is available:

  • CRYPT_STD_DES - Standard DES-based hash with a two character salt from the alphabet "./0-9A-Za-z". Using invalid characters in the salt will cause crypt() to fail.
  • CRYPT_EXT_DES - Extended DES-based hash. The "salt" is a 9-character string consisting of an underscore followed by 4 bytes of iteration count and 4 bytes of salt. These are encoded as printable characters, 6 bits per character, least significant character first. The values 0 to 63 are encoded as "./0-9A-Za-z". Using invalid characters in the salt will cause crypt() to fail.
  • CRYPT_MD5 - MD5 hashing with a twelve character salt starting with $1$
  • CRYPT_BLOWFISH - Blowfish hashing with a salt as follows: "$2a$", "$2x$" or "$2y$", a two digit cost parameter, "$", and 22 characters from the alphabet "./0-9A-Za-z". Using characters outside of this range in the salt will cause crypt() to return a zero-length string. The two digit cost parameter is the base-2 logarithm of the iteration count for the underlying Blowfish-based hashing algorithmeter and must be in range 04-31, values outside this range will cause crypt() to fail. Versions of PHP before 5.3.7 only support "$2a$" as the salt prefix: PHP 5.3.7 introduced the new prefixes to fix a security weakness in the Blowfish implementation. Please refer to » this document for full details of the security fix, but to summarise, developers targeting only PHP 5.3.7 and later should use "$2y$" in preference to "$2a$".
  • CRYPT_SHA256 - SHA-256 hash with a sixteen character salt prefixed with $5$. If the salt string starts with 'rounds=<N>$', the numeric value of N is used to indicate how many times the hashing loop should be executed, much like the cost parameter on Blowfish. The default number of rounds is 5000, there is a minimum of 1000 and a maximum of 999,999,999. Any selection of N outside this range will be truncated to the nearest limit.
  • CRYPT_SHA512 - SHA-512 hash with a sixteen character salt prefixed with $6$. If the salt string starts with 'rounds=<N>$', the numeric value of N is used to indicate how many times the hashing loop should be executed, much like the cost parameter on Blowfish. The default number of rounds is 5000, there is a minimum of 1000 and a maximum of 999,999,999. Any selection of N outside this range will be truncated to the nearest limit.

Note:

As of PHP 5.3.0, PHP contains its own implementation and will use that if the system lacks of support for one or more of the algorithms.

Parameters

str

The string to be hashed.

Caution

Using the CRYPT_BLOWFISH algorithm, will result in the str parameter being truncated to a maximum length of 72 characters.

salt

An optional salt string to base the hashing on. If not provided, the behaviour is defined by the algorithm implementation and can lead to unexpected results.

Return Values

Returns the hashed string or a string that is shorter than 13 characters and is guaranteed to differ from the salt on failure.

Warning

When validating passwords, a string comparison function that isn't vulnerable to timing attacks should be used to compare the output of crypt() to the previously known hash. PHP 5.6 onwards provides hash_equals() for this purpose.

Changelog

Version | Description
5.6.5 | When the failure string "*0" is given as the salt, "*1" will now be returned for consistency with other crypt implementations. Prior to this version, PHP 5.6 would incorrectly return a DES hash.
5.6.0 | Raise E_NOTICE security warning if salt is omitted.
5.5.21 | When the failure string "*0" is given as the salt, "*1" will now be returned for consistency with other crypt implementations. Prior to this version, PHP 5.5 (and earlier branches) would incorrectly return a DES hash.
5.3.7 | Added $2x$ and $2y$ Blowfish modes to deal with potential high-bit attacks.
5.3.2 | Added SHA-256 and SHA-512 crypt based on Ulrich Drepper's » implementation.
5.3.2 | Fixed Blowfish behaviour on invalid rounds to return "failure" string ("*0" or "*1"), instead of falling back to DES.
5.3.0 | PHP now contains its own implementation for the MD5 crypt, Standard DES, Extended DES and the Blowfish algorithms and will use that if the system lacks of support for one or more of the algorithms.

Examples

Example #1 crypt() examples

<?php
$hashed_password = crypt('mypassword'); // let the salt be automatically generated

/* You should pass the entire results of crypt() as the salt for comparing a
   password, to avoid problems when different hashing algorithms are used. (As
   it says above, standard DES-based password hashing uses a 2-character salt,
   but MD5-based hashing uses 12.) */
if (hash_equals($hashed_password, crypt($user_input, $hashed_password))) {
   echo "Password verified!";
}
?>

Example #2 Using crypt() with htpasswd

<?php
// Set the password
$password = 'mypassword';

// Get the hash, letting the salt be automatically generated
$hash = crypt($password);
?>

Example #3 Using crypt() with different hash types

<?php
/* These salts are examples only, and should not be used verbatim in your code.
   You should generate a distinct, correctly-formatted salt for each password.
*/
if (CRYPT_STD_DES == 1) {
    echo 'Standard DES: ' . crypt('rasmuslerdorf', 'rl') . "\n";
}

if (CRYPT_EXT_DES == 1) {
    echo 'Extended DES: ' . crypt('rasmuslerdorf', '_J9..rasm') . "\n";
}

if (CRYPT_MD5 == 1) {
    echo 'MD5:          ' . crypt('rasmuslerdorf', '$1$rasmusle$') . "\n";
}

if (CRYPT_BLOWFISH == 1) {
    echo 'Blowfish:     ' . crypt('rasmuslerdorf', '$2a$07$usesomesillystringforsalt$') . "\n";
}

if (CRYPT_SHA256 == 1) {
    echo 'SHA-256:      ' . crypt('rasmuslerdorf', '$5$rounds=5000$usesomesillystringforsalt$') . "\n";
}

if (CRYPT_SHA512 == 1) {
    echo 'SHA-512:      ' . crypt('rasmuslerdorf', '$6$rounds=5000$usesomesillystringforsalt$') . "\n";
}
?>

The above example will output something similar to:

Standard DES: rl.3StKT.4T8M
Extended DES: _J9..rasmBYk8r9AiWNc
MD5:          $1$rasmusle$rISCgZzpwk3UhDidwXvin0
Blowfish:     $2a$07$usesomesillystringfore2uDLvp1Ii2e./U9C8sBjqp8I90dH6hi
SHA-256:      $5$rounds=5000$usesomesillystri$KqJWpanXZHKq2BOB43TSaYhEWsQ1Lr5QNyPCDH/Tp.6
SHA-512:      $6$rounds=5000$usesomesillystri$D4IrlXatmP7rx3P3InaxBeoomnAihCKRVQP22JZ6EY47Wc6BkroIuUUBOov1i.S5KPgErtP/EN5mcO.ChWQW21

Notes

Note: There is no decrypt function, since crypt() uses a one-way algorithm.

See Also

  • hash_equals() - Timing attack safe string comparison
  • password_hash() - Creates a password hash
  • md5() - Calculate the md5 hash of a string
  • The Mcrypt extension
  • The Unix man page for your crypt function for more information


Output one or more strings

  • « crypt
  • explode »
  • PHP Manual
  • String Functions
  • Output one or more strings

echo

(PHP 4, PHP 5, PHP 7)

echo — Output one or more strings

Description

echo ( string $arg1 [, string $... ] ) : void

Outputs all parameters. No additional newline is appended.

echo is not actually a function (it is a language construct), so you are not required to use parentheses with it. echo (unlike some other language constructs) does not behave like a function, so it cannot always be used in the context of a function. Additionally, if you want to pass more than one parameter to echo, the parameters must not be enclosed within parentheses.

echo also has a shortcut syntax, where you can immediately follow the opening tag with an equals sign. Prior to PHP 5.4.0, this short syntax only works with the short_open_tag configuration setting enabled.

I have <?=$foo?> foo.

The major differences to print are that echo accepts an argument list and doesn't have a return value.

Parameters

arg1

The parameter to output.

...

Return Values

No value is returned.

Examples

Example #1 echo examples

<?php
echo "Hello World";

// Strings can either be passed individually as multiple arguments or
// concatenated together and passed as a single argument
echo 'This ', 'string ', 'was ', 'made ', 'with multiple parameters.', chr(10);
echo 'This ' . 'string ' . 'was ' . 'made ' . 'with concatenation.' . "\n";

// Because echo does not behave like a function, the following code is invalid.
($some_var) ? echo 'true' : echo 'false';

// However, the following examples will work:
($some_var) ? print 'true' : print 'false'; // print is also a construct, but
                                            // it behaves like a function, so
                                            // it may be used in this context.

echo $some_var ? 'true': 'false'; // changing the statement around
?>

Notes

Note: Because this is a language construct and not a function, it cannot be called using variable functions.

Tip

A benefit to passing in multiple arguments over using concatenation in echo regards the precedence of the period operator in PHP. If multiple arguments are passed in, then parentheses will not be required to enforce precedence:

<?php
echo "Sum: ", 1 + 2;
echo "Hello ", isset($name) ? $name : "John Doe", "!";

With concatenation, the period operator has a higher precedence than both the addition and ternary operators, and so parentheses must be used for the correct behaviour:

<?php
echo 'Sum: ' . (1 + 2);
echo 'Hello ' . (isset($name) ? $name : 'John Doe') . '!';

See Also

  • print - Output a string
  • printf() - Output a formatted string
  • flush() - Flush system output buffer
  • Heredoc syntax


Split a string by a string

  • « echo
  • fprintf »
  • PHP Manual
  • String Functions
  • Split a string by a string

explode

(PHP 4, PHP 5, PHP 7)

explode — Split a string by a string

Description

explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ] ) : array

Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter.

Parameters

delimiter

The boundary string.

string

The input string.

limit

If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string.

If the limit parameter is negative, all components except the last -limit are returned.

If the limit parameter is zero, then this is treated as 1.

Note:

Although implode() can, for historical reasons, accept its parameters in either order, explode() cannot. You must ensure that the delimiter argument comes before the string argument.

Return Values

Returns an array of strings created by splitting the string parameter on boundaries formed by the delimiter.

If delimiter is an empty string (""), explode() will return FALSE. If delimiter contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned.

Changelog

Version | Description
5.1.0 | Support for negative limits was added

Examples

Example #1 explode() examples

<?php
// Example 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

// Example 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo $user; // foo
echo $pass; // *

?>

Example #2 explode() return examples

<?php
/*
   A string that doesn't contain the delimiter will simply
   return a one-length array of the original string.
*/
$input1 = "hello";
$input2 = "hello,there";
$input3 = ',';
var_dump( explode( ',', $input1 ) );
var_dump( explode( ',', $input2 ) );
var_dump( explode( ',', $input3 ) );

?>

The above example will output:

array(1)
(
    [0] => string(5) "hello"
)
array(2)
(
    [0] => string(5) "hello"
    [1] => string(5) "there"
)
array(2)
(
    [0] => string(0) ""
    [1] => string(0) ""
)

Example #3 limit parameter examples

<?php
$str = 'one|two|three|four';

// positive limit
print_r(explode('|', $str, 2));

// negative limit (since PHP 5.1)
print_r(explode('|', $str, -1));
?>

The above example will output:

Array
(
    [0] => one
    [1] => two|three|four
)
Array
(
    [0] => one
    [1] => two
    [2] => three
)

Notes

Note: This function is binary-safe.

See Also

  • preg_split() - Split string by a regular expression
  • str_split() - Convert a string to an array
  • mb_split() - Split multibyte string using regular expression
  • str_word_count() - Return information about words used in a string
  • strtok() - Tokenize string
  • implode() - Join array elements with a string


Write a formatted string to a stream

  • « explode
  • get_html_translation_table »
  • PHP Manual
  • String Functions
  • Write a formatted string to a stream

fprintf

(PHP 5, PHP 7)

fprintf — Write a formatted string to a stream

Description

fprintf ( resource $handle , string $format [, mixed $... ] ) : int

Write a string produced according to format to the stream resource specified by handle.

Parameters

handle

A file system pointer resource that is typically created using fopen().

format

The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result and conversion specifications, each of which results in fetching its own parameter.

A conversion specification follows this prototype: %[argnum$][flags][width][.precision]specifier.

Argnum

An integer followed by a dollar sign $, to specify which number argument to treat in the conversion.

Flags
Flag | Description
- Left-justify within the given field width; Right justification is the default
+ Prefix positive numbers with a plus sign +; Default only negative are prefixed with a negative sign.
(space) | Pads the result with spaces. This is the default.
0 | Only left-pads numbers with zeros. With s specifiers this can also right-pad with zeros.
'(char) | Pads the result with the character (char).

Width

An integer that says how many characters (minimum) this conversion should result in.

Precision

A period . followed by an integer who's meaning depends on the specifier:

  • For e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
  • For g and G specifiers: this is the maximum number of significant digits to be printed.
  • For s specifier: it acts as a cutoff point, setting a maximum character limit to the string.

Note: If the period is specified without an explicit value for precision, 0 is assumed.

Note: Attempting to use a position specifier greater than PHP_INT_MAX will generate warnings.

Specifiers
Specifier | Description
% A literal percent character. No argument is required.
b | The argument is treated as an integer and presented as a binary number.
c | The argument is treated as an integer and presented as the character with that ASCII.
d | The argument is treated as an integer and presented as a (signed) decimal number.
e | The argument is treated as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point since PHP 5.2.1. In earlier versions, it was taken as number of significant digits (one less).
E | Like the e specifier but uses uppercase letter (e.g. 1.2E+2).
f | The argument is treated as a float and presented as a floating-point number (locale aware).
F | The argument is treated as a float and presented as a floating-point number (non-locale aware). Available as of PHP 5.0.3.
g

General format.

Let P equal the precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero. Then, if a conversion with style E would have an exponent of X:

If P > X ≥ −4, the conversion is with style f and precision P − (X + 1). Otherwise, the conversion is with style e and precision P − 1.

G | Like the g specifier but uses E and F.
o | The argument is treated as an integer and presented as an octal number.
s | The argument is treated and presented as a string.
u | The argument is treated as an integer and presented as an unsigned decimal number.
x | The argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).
X | The argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).

Warning

The c type specifier ignores padding and width

Warning

Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results

Variables will be co-erced to a suitable type for the specifier:

Type Handling
Type | Specifiers
string | s
integer | d, u, c, o, x, X, b
double | g, G, e, E, f, F

...

Return Values

Returns the length of the string written.

Examples

Example #1 fprintf(): zero-padded integers

<?php
if (!($fp = fopen('date.txt', 'w'))) {
    return;
}

fprintf($fp, "%04d-%02d-%02d", $year, $month, $day);
// will write the formatted ISO date to date.txt
?>

Example #2 fprintf(): formatting currency

<?php
if (!($fp = fopen('currency.txt', 'w'))) {
    return;
}

$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
// echo $money will output "123.1";
$len = fprintf($fp, '%01.2f', $money);
// will write "123.10" to currency.txt

echo "wrote $len bytes to currency.txt";
// use the return value of fprintf to determine how many bytes we wrote
?>

See Also

  • printf() - Output a formatted string
  • sprintf() - Return a formatted string
  • vprintf() - Output a formatted string
  • vsprintf() - Return a formatted string
  • vfprintf() - Write a formatted string to a stream
  • sscanf() - Parses input from a string according to a format
  • fscanf() - Parses input from a file according to a format
  • number_format() - Format a number with grouped thousands
  • date() - Format a local time/date


Returns the translation table used by htmlspecialchars and htmlentities

  • « fprintf
  • hebrev »
  • PHP Manual
  • String Functions
  • Returns the translation table used by htmlspecialchars and htmlentities

get_html_translation_table

(PHP 4, PHP 5, PHP 7)

get_html_translation_table — Returns the translation table used by htmlspecialchars() and htmlentities()

Description

get_html_translation_table ([ int $table = HTML_SPECIALCHARS [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = "UTF-8" ]]] ) : array

get_html_translation_table() will return the translation table that is used internally for htmlspecialchars() and htmlentities().

Note:

Special characters can be encoded in several ways. E.g. " can be encoded as &quot;, &#34; or &#x22. get_html_translation_table() returns only the form used by htmlspecialchars() and htmlentities().

Parameters

table

Which table to return. Either HTML_ENTITIES or HTML_SPECIALCHARS.

flags

A bitmask of one or more of the following flags, which specify which quotes the table will contain as well as which document type the table is for. The default is ENT_COMPAT | ENT_HTML401.

Available flags constants
Constant Name | Description
ENT_COMPAT | Table will contain entities for double-quotes, but not for single-quotes.
ENT_QUOTES | Table will contain entities for both double and single quotes.
ENT_NOQUOTES | Table will neither contain entities for single quotes nor for double quotes.
ENT_HTML401 | Table for HTML 4.01.
ENT_XML1 | Table for XML 1.
ENT_XHTML | Table for XHTML.
ENT_HTML5 | Table for HTML 5.

encoding

Encoding to use. If omitted, the default value for this argument is ISO-8859-1 in versions of PHP prior to 5.4.0, and UTF-8 from PHP 5.4.0 onwards.

The following character sets are supported:

Supported charsets
Charset | Aliases | Description
ISO-8859-1 | ISO8859-1 | Western European, Latin-1.
ISO-8859-5 | ISO8859-5 | Little used cyrillic charset (Latin/Cyrillic).
ISO-8859-15 | ISO8859-15 | Western European, Latin-9. Adds the Euro sign, French and Finnish letters missing in Latin-1 (ISO-8859-1).
UTF-8 | ASCII compatible multi-byte 8-bit Unicode.
cp866 | ibm866, 866 | DOS-specific Cyrillic charset.
cp1251 | Windows-1251, win-1251, 1251 | Windows-specific Cyrillic charset.
cp1252 | Windows-1252, 1252 | Windows specific charset for Western European.
KOI8-R | koi8-ru, koi8r | Russian.
BIG5 | 950 | Traditional Chinese, mainly used in Taiwan.
GB2312 | 936 | Simplified Chinese, national standard character set.
BIG5-HKSCS | Big5 with Hong Kong extensions, Traditional Chinese.
Shift_JIS | SJIS, SJIS-win, cp932, 932 | Japanese
EUC-JP | EUCJP, eucJP-win | Japanese
MacRoman | Charset that was used by Mac OS.
'' An empty string activates detection from script encoding (Zend multibyte), default_charset and current locale (see nl_langinfo() and setlocale()), in this order. Not recommended.

Note: Any other character sets are not recognized. The default encoding will be used instead and a warning will be emitted.

Return Values

Returns the translation table as an array, with the original characters as keys and entities as values.

Changelog

Version | Description
5.4.0 | The default value for the encoding parameter was changed to UTF-8.
5.4.0 | The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
5.3.4 | The encoding parameter was added.

Examples

Example #1 Translation Table Example

<?php
var_dump(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES | ENT_HTML5));
?>

The above example will output something similar to:

array(1510) {
  ["
"]=>
  string(9) "&NewLine;"
  ["!"]=>
  string(6) "&excl;"
  ["""]=>
  string(6) "&quot;"
  ["#"]=>
  string(5) "&num;"
  ["$"]=>
  string(8) "&dollar;"
  ["%"]=>
  string(8) "&percnt;"
  ["&"]=>
  string(5) "&amp;"
  ["'"]=>
  string(6) "&apos;"
  // ...
}

See Also

  • htmlspecialchars() - Convert special characters to HTML entities
  • htmlentities() - Convert all applicable characters to HTML entities
  • html_entity_decode() - Convert HTML entities to their corresponding characters


Convert logical Hebrew text to visual text

  • « get_html_translation_table
  • hebrevc »
  • PHP Manual
  • String Functions
  • Convert logical Hebrew text to visual text

hebrev

(PHP 4, PHP 5, PHP 7)

hebrev — Convert logical Hebrew text to visual text

Description

hebrev ( string $hebrew_text [, int $max_chars_per_line = 0 ] ) : string

Converts logical Hebrew text to visual text.

The function tries to avoid breaking words.

Parameters

hebrew_text

A Hebrew input string.

max_chars_per_line

This optional parameter indicates maximum number of characters per line that will be returned.

Return Values

Returns the visual string.

See Also

  • hebrevc() - Convert logical Hebrew text to visual text with newline conversion


Convert logical Hebrew text to visual text with newline conversion

  • « hebrev
  • hex2bin »
  • PHP Manual
  • String Functions
  • Convert logical Hebrew text to visual text with newline conversion

hebrevc

(PHP 4, PHP 5, PHP 7)

hebrevc — Convert logical Hebrew text to visual text with newline conversion

Description

hebrevc ( string $hebrew_text [, int $max_chars_per_line = 0 ] ) : string

This function is similar to hebrev() with the difference that it converts newlines (\n) to "<br>\n".

The function tries to avoid breaking words.

Parameters

hebrew_text

A Hebrew input string.

max_chars_per_line

This optional parameter indicates maximum number of characters per line that will be returned.

Return Values

Returns the visual string.

See Also

  • hebrev() - Convert logical Hebrew text to visual text


Decodes a hexadecimally encoded binary string

  • « hebrevc
  • html_entity_decode »
  • PHP Manual
  • String Functions
  • Decodes a hexadecimally encoded binary string

hex2bin

(PHP 5 >= 5.4.0, PHP 7)

hex2bin — Decodes a hexadecimally encoded binary string

Description

hex2bin ( string $data ) : string

Decodes a hexadecimally encoded binary string.

Caution

This function does NOT convert a hexadecimal number to a binary number. This can be done using the base_convert() function.

Parameters

data

Hexadecimal representation of data.

Return Values

Returns the binary representation of the given data or FALSE on failure.

Errors/Exceptions

If the hexadecimal input string is of odd length or invalid hexadecimal string an E_WARNING level error is thrown.

Changelog

Version | Description
5.5.1 | A warning is thrown if the input string is invalid hexadecimal string.
5.4.4 | A warning is thrown if the input string is of odd length. In PHP 5.4.0 the string was silently accepted, but the last byte was truncated.

Examples

Example #1 hex2bin() example

<?php
$hex = hex2bin("6578616d706c65206865782064617461");
var_dump($hex);
?>

The above example will output something similar to:

string(16) "example hex data"

See Also

  • bin2hex() - Convert binary data into hexadecimal representation
  • unpack() - Unpack data from binary string


Convert HTML entities to their corresponding characters

  • « hex2bin
  • htmlentities »
  • PHP Manual
  • String Functions
  • Convert HTML entities to their corresponding characters

html_entity_decode

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

html_entity_decode — Convert HTML entities to their corresponding characters

Description

html_entity_decode ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = ini_get("default_charset") ]] ) : string

html_entity_decode() is the opposite of htmlentities() in that it converts HTML entities in the string to their corresponding characters.

More precisely, this function decodes all the entities (including all numeric entities) that a) are necessarily valid for the chosen document type — i.e., for XML, this function does not decode named entities that might be defined in some DTD — and b) whose character or characters are in the coded character set associated with the chosen encoding and are permitted in the chosen document type. All other entities are left as is.

Parameters

string

The input string.

flags

A bitmask of one or more of the following flags, which specify how to handle quotes and which document type to use. The default is ENT_COMPAT | ENT_HTML401.

Available flags constants
Constant Name | Description
ENT_COMPAT | Will convert double-quotes and leave single-quotes alone.
ENT_QUOTES | Will convert both double and single quotes.
ENT_NOQUOTES | Will leave both double and single quotes unconverted.
ENT_HTML401 | Handle code as HTML 4.01.
ENT_XML1 | Handle code as XML 1.
ENT_XHTML | Handle code as XHTML.
ENT_HTML5 | Handle code as HTML 5.

encoding

An optional argument defining the encoding used when converting characters.

If omitted, the default value of the encoding varies depending on the PHP version in use. In PHP 5.6 and later, the default_charset configuration option is used as the default value. PHP 5.4 and 5.5 will use UTF-8 as the default. Earlier versions of PHP use ISO-8859-1.

Although this argument is technically optional, you are highly encouraged to specify the correct value for your code if you are using PHP 5.5 or earlier, or if your default_charset configuration option may be set incorrectly for the given input.

The following character sets are supported:

Supported charsets
Charset | Aliases | Description
ISO-8859-1 | ISO8859-1 | Western European, Latin-1.
ISO-8859-5 | ISO8859-5 | Little used cyrillic charset (Latin/Cyrillic).
ISO-8859-15 | ISO8859-15 | Western European, Latin-9. Adds the Euro sign, French and Finnish letters missing in Latin-1 (ISO-8859-1).
UTF-8 | ASCII compatible multi-byte 8-bit Unicode.
cp866 | ibm866, 866 | DOS-specific Cyrillic charset.
cp1251 | Windows-1251, win-1251, 1251 | Windows-specific Cyrillic charset.
cp1252 | Windows-1252, 1252 | Windows specific charset for Western European.
KOI8-R | koi8-ru, koi8r | Russian.
BIG5 | 950 | Traditional Chinese, mainly used in Taiwan.
GB2312 | 936 | Simplified Chinese, national standard character set.
BIG5-HKSCS | Big5 with Hong Kong extensions, Traditional Chinese.
Shift_JIS | SJIS, SJIS-win, cp932, 932 | Japanese
EUC-JP | EUCJP, eucJP-win | Japanese
MacRoman | Charset that was used by Mac OS.
'' An empty string activates detection from script encoding (Zend multibyte), default_charset and current locale (see nl_langinfo() and setlocale()), in this order. Not recommended.

Note: Any other character sets are not recognized. The default encoding will be used instead and a warning will be emitted.

Return Values

Returns the decoded string.

Changelog

Version | Description
5.6.0 | The default value for the encoding parameter was changed to be the value of the default_charset configuration option.
5.4.0 | Default encoding changed from ISO-8859-1 to UTF-8.
5.4.0 | The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.

Examples

Example #1 Decoding HTML entities

<?php
$orig = "I'll \"walk\" the <b>dog</b> now";

$a = htmlentities($orig);

$b = html_entity_decode($a);

echo $a; // I'll &quot;walk&quot; the &lt;b&gt;dog&lt;/b&gt; now

echo $b; // I'll "walk" the <b>dog</b> now
?>

Notes

Note:

You might wonder why trim(html_entity_decode('&nbsp;')); doesn't reduce the string to an empty string, that's because the '&nbsp;' entity is not ASCII code 32 (which is stripped by trim()) but ASCII code 160 (0xa0) in the default ISO 8859-1 encoding.

See Also

  • htmlentities() - Convert all applicable characters to HTML entities
  • htmlspecialchars() - Convert special characters to HTML entities
  • get_html_translation_table() - Returns the translation table used by htmlspecialchars and htmlentities
  • urldecode() - Decodes URL-encoded string


Convert all applicable characters to HTML entities

  • « html_entity_decode
  • htmlspecialchars_decode »
  • PHP Manual
  • String Functions
  • Convert all applicable characters to HTML entities

htmlentities

(PHP 4, PHP 5, PHP 7)

htmlentities — Convert all applicable characters to HTML entities

Description

htmlentities ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = ini_get("default_charset") [, bool $double_encode = TRUE ]]] ) : string

This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.

If you want to decode instead (the reverse) you can use html_entity_decode().

Parameters

string

The input string.

flags

A bitmask of one or more of the following flags, which specify how to handle quotes, invalid code unit sequences and the used document type. The default is ENT_COMPAT | ENT_HTML401.

Available flags constants
Constant Name | Description
ENT_COMPAT | Will convert double-quotes and leave single-quotes alone.
ENT_QUOTES | Will convert both double and single quotes.
ENT_NOQUOTES | Will leave both double and single quotes unconverted.
ENT_IGNORE | Silently discard invalid code unit sequences instead of returning an empty string. Using this flag is discouraged as it » may have security implications.
ENT_SUBSTITUTE | Replace invalid code unit sequences with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD; (otherwise) instead of returning an empty string.
ENT_DISALLOWED | Replace invalid code points for the given document type with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD; (otherwise) instead of leaving them as is. This may be useful, for instance, to ensure the well-formedness of XML documents with embedded external content.
ENT_HTML401 | Handle code as HTML 4.01.
ENT_XML1 | Handle code as XML 1.
ENT_XHTML | Handle code as XHTML.
ENT_HTML5 | Handle code as HTML 5.

encoding

An optional argument defining the encoding used when converting characters.

If omitted, the default value of the encoding varies depending on the PHP version in use. In PHP 5.6 and later, the default_charset configuration option is used as the default value. PHP 5.4 and 5.5 will use UTF-8 as the default. Earlier versions of PHP use ISO-8859-1.

Although this argument is technically optional, you are highly encouraged to specify the correct value for your code if you are using PHP 5.5 or earlier, or if your default_charset configuration option may be set incorrectly for the given input.

The following character sets are supported:

Supported charsets
Charset | Aliases | Description
ISO-8859-1 | ISO8859-1 | Western European, Latin-1.
ISO-8859-5 | ISO8859-5 | Little used cyrillic charset (Latin/Cyrillic).
ISO-8859-15 | ISO8859-15 | Western European, Latin-9. Adds the Euro sign, French and Finnish letters missing in Latin-1 (ISO-8859-1).
UTF-8 | ASCII compatible multi-byte 8-bit Unicode.
cp866 | ibm866, 866 | DOS-specific Cyrillic charset.
cp1251 | Windows-1251, win-1251, 1251 | Windows-specific Cyrillic charset.
cp1252 | Windows-1252, 1252 | Windows specific charset for Western European.
KOI8-R | koi8-ru, koi8r | Russian.
BIG5 | 950 | Traditional Chinese, mainly used in Taiwan.
GB2312 | 936 | Simplified Chinese, national standard character set.
BIG5-HKSCS | Big5 with Hong Kong extensions, Traditional Chinese.
Shift_JIS | SJIS, SJIS-win, cp932, 932 | Japanese
EUC-JP | EUCJP, eucJP-win | Japanese
MacRoman | Charset that was used by Mac OS.
'' An empty string activates detection from script encoding (Zend multibyte), default_charset and current locale (see nl_langinfo() and setlocale()), in this order. Not recommended.

Note: Any other character sets are not recognized. The default encoding will be used instead and a warning will be emitted.

double_encode

When double_encode is turned off PHP will not encode existing html entities. The default is to convert everything.

Return Values

Returns the encoded string.

If the input string contains an invalid code unit sequence within the given encoding an empty string will be returned, unless either the ENT_IGNORE or ENT_SUBSTITUTE flags are set.

Changelog

Version | Description
5.6.0 | The default value for the encoding parameter was changed to be the value of the default_charset configuration option.
5.4.0 | The default value for the encoding parameter was changed to UTF-8.
5.4.0 | The constants ENT_SUBSTITUTE, ENT_DISALLOWED, ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
5.3.0 | The constant ENT_IGNORE was added.
5.2.3 | The double_encode parameter was added.

Examples

Example #1 A htmlentities() example

<?php
$str = "A 'quote' is <b>bold</b>";

// Outputs: A 'quote' is &lt;b&gt;bold&lt;/b&gt;
echo htmlentities($str);

// Outputs: A &#039;quote&#039; is &lt;b&gt;bold&lt;/b&gt;
echo htmlentities($str, ENT_QUOTES);
?>

Example #2 Usage of ENT_IGNORE

<?php
$str = "\x8F!!!";

// Outputs an empty string
echo htmlentities($str, ENT_QUOTES, "UTF-8");

// Outputs "!!!"
echo htmlentities($str, ENT_QUOTES | ENT_IGNORE, "UTF-8");
?>

See Also

  • html_entity_decode() - Convert HTML entities to their corresponding characters
  • get_html_translation_table() - Returns the translation table used by htmlspecialchars and htmlentities
  • htmlspecialchars() - Convert special characters to HTML entities
  • nl2br() - Inserts HTML line breaks before all newlines in a string
  • urlencode() - URL-encodes string


Convert special HTML entities back to characters

  • « htmlentities
  • htmlspecialchars »
  • PHP Manual
  • String Functions
  • Convert special HTML entities back to characters

htmlspecialchars_decode

(PHP 5 >= 5.1.0, PHP 7)

htmlspecialchars_decode — Convert special HTML entities back to characters

Description

htmlspecialchars_decode ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 ] ) : string

This function is the opposite of htmlspecialchars(). It converts special HTML entities back to characters.

The converted entities are: &amp;, &quot; (when ENT_NOQUOTES is not set), &#039; (when ENT_QUOTES is set), &lt; and &gt;.

Parameters

string

The string to decode.

flags

A bitmask of one or more of the following flags, which specify how to handle quotes and which document type to use. The default is ENT_COMPAT | ENT_HTML401.

Available flags constants
Constant Name | Description
ENT_COMPAT | Will convert double-quotes and leave single-quotes alone.
ENT_QUOTES | Will convert both double and single quotes.
ENT_NOQUOTES | Will leave both double and single quotes unconverted.
ENT_HTML401 | Handle code as HTML 4.01.
ENT_XML1 | Handle code as XML 1.
ENT_XHTML | Handle code as XHTML.
ENT_HTML5 | Handle code as HTML 5.

Return Values

Returns the decoded string.

Changelog

Version | Description
5.4.0 | The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.

Examples

Example #1 A htmlspecialchars_decode() example

<?php
$str = "<p>this -&gt; &quot;</p>\n";

echo htmlspecialchars_decode($str);

// note that here the quotes aren't converted
echo htmlspecialchars_decode($str, ENT_NOQUOTES);
?>

The above example will output:

<p>this -> "</p>
<p>this -> &quot;</p>

See Also

  • htmlspecialchars() - Convert special characters to HTML entities
  • html_entity_decode() - Convert HTML entities to their corresponding characters
  • get_html_translation_table() - Returns the translation table used by htmlspecialchars and htmlentities


Convert special characters to HTML entities

  • « htmlspecialchars_decode
  • implode »
  • PHP Manual
  • String Functions
  • Convert special characters to HTML entities

htmlspecialchars

(PHP 4, PHP 5, PHP 7)

htmlspecialchars — Convert special characters to HTML entities

Description

htmlspecialchars ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = ini_get("default_charset") [, bool $double_encode = TRUE ]]] ) : string

Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with these conversions made. If you require all input substrings that have associated named entities to be translated, use htmlentities() instead.

If the input string passed to this function and the final document share the same character set, this function is sufficient to prepare input for inclusion in most contexts of an HTML document. If, however, the input can represent characters that are not coded in the final document character set and you wish to retain those characters (as numeric or named entities), both this function and htmlentities() (which only encodes substrings that have named entity equivalents) may be insufficient. You may have to use mb_encode_numericentity() instead.

Performed translations
Character | Replacement
& (ampersand) | &amp;
" (double quote) | &quot;, unless ENT_NOQUOTES is set
' (single quote) | &#039; (for ENT_HTML401) or &apos; (for ENT_XML1, ENT_XHTML or ENT_HTML5), but only when ENT_QUOTES is set
< (less than) | &lt;
> (greater than) | &gt;

Parameters

string

The string being converted.

flags

A bitmask of one or more of the following flags, which specify how to handle quotes, invalid code unit sequences and the used document type. The default is ENT_COMPAT | ENT_HTML401.

Available flags constants
Constant Name | Description
ENT_COMPAT | Will convert double-quotes and leave single-quotes alone.
ENT_QUOTES | Will convert both double and single quotes.
ENT_NOQUOTES | Will leave both double and single quotes unconverted.
ENT_IGNORE | Silently discard invalid code unit sequences instead of returning an empty string. Using this flag is discouraged as it » may have security implications.
ENT_SUBSTITUTE | Replace invalid code unit sequences with a Unicode Replacement Character U+FFFD (UTF-8) or &#xFFFD; (otherwise) instead of returning an empty string.
ENT_DISALLOWED | Replace invalid code points for the given document type with a Unicode Replacement Character U+FFFD (UTF-8) or &#xFFFD; (otherwise) instead of leaving them as is. This may be useful, for instance, to ensure the well-formedness of XML documents with embedded external content.
ENT_HTML401 | Handle code as HTML 4.01.
ENT_XML1 | Handle code as XML 1.
ENT_XHTML | Handle code as XHTML.
ENT_HTML5 | Handle code as HTML 5.

encoding

An optional argument defining the encoding used when converting characters.

If omitted, the default value of the encoding varies depending on the PHP version in use. In PHP 5.6 and later, the default_charset configuration option is used as the default value. PHP 5.4 and 5.5 will use UTF-8 as the default. Earlier versions of PHP use ISO-8859-1.

Although this argument is technically optional, you are highly encouraged to specify the correct value for your code if you are using PHP 5.5 or earlier, or if your default_charset configuration option may be set incorrectly for the given input.

For the purposes of this function, the encodings ISO-8859-1, ISO-8859-15, UTF-8, cp866, cp1251, cp1252, and KOI8-R are effectively equivalent, provided the string itself is valid for the encoding, as the characters affected by htmlspecialchars() occupy the same positions in all of these encodings.

The following character sets are supported:

Supported charsets
Charset | Aliases | Description
ISO-8859-1 | ISO8859-1 | Western European, Latin-1.
ISO-8859-5 | ISO8859-5 | Little used cyrillic charset (Latin/Cyrillic).
ISO-8859-15 | ISO8859-15 | Western European, Latin-9. Adds the Euro sign, French and Finnish letters missing in Latin-1 (ISO-8859-1).
UTF-8 | ASCII compatible multi-byte 8-bit Unicode.
cp866 | ibm866, 866 | DOS-specific Cyrillic charset.
cp1251 | Windows-1251, win-1251, 1251 | Windows-specific Cyrillic charset.
cp1252 | Windows-1252, 1252 | Windows specific charset for Western European.
KOI8-R | koi8-ru, koi8r | Russian.
BIG5 | 950 | Traditional Chinese, mainly used in Taiwan.
GB2312 | 936 | Simplified Chinese, national standard character set.
BIG5-HKSCS | Big5 with Hong Kong extensions, Traditional Chinese.
Shift_JIS | SJIS, SJIS-win, cp932, 932 | Japanese
EUC-JP | EUCJP, eucJP-win | Japanese
MacRoman | Charset that was used by Mac OS.
'' An empty string activates detection from script encoding (Zend multibyte), default_charset and current locale (see nl_langinfo() and setlocale()), in this order. Not recommended.

Note: Any other character sets are not recognized. The default encoding will be used instead and a warning will be emitted.

double_encode

When double_encode is turned off PHP will not encode existing html entities, the default is to convert everything.

Return Values

The converted string.

If the input string contains an invalid code unit sequence within the given encoding an empty string will be returned, unless either the ENT_IGNORE or ENT_SUBSTITUTE flags are set.

Changelog

Version | Description
5.6.0 | The default value for the encoding parameter was changed to be the value of the default_charset configuration option.
5.4.0 | The default value for the encoding parameter was changed to UTF-8.
5.4.0 | The constants ENT_SUBSTITUTE, ENT_DISALLOWED, ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
5.3.0 | The constant ENT_IGNORE was added.
5.2.3 | The double_encode parameter was added.

Examples

Example #1 htmlspecialchars() example

<?php
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;
?>

Notes

Note:

Note that this function does not translate anything beyond what is listed above. For full entity translation, see htmlentities().

Note:

In case of an ambiguous flags value, the following rules apply:

  • When neither of ENT_COMPAT, ENT_QUOTES, ENT_NOQUOTES is present, the default is ENT_NOQUOTES.
  • When more than one of ENT_COMPAT, ENT_QUOTES, ENT_NOQUOTES is present, ENT_QUOTES takes the highest precedence, followed by ENT_COMPAT.
  • When neither of ENT_HTML401, ENT_HTML5, ENT_XHTML, ENT_XML1 is present, the default is ENT_HTML401.
  • When more than one of ENT_HTML401, ENT_HTML5, ENT_XHTML, ENT_XML1 is present, ENT_HTML5 takes the highest precedence, followed by ENT_XHTML, ENT_XML1 and ENT_HTML401.
  • When more than one of ENT_DISALLOWED, ENT_IGNORE, ENT_SUBSTITUTE are present, ENT_IGNORE takes the highest precedence, followed by ENT_SUBSTITUTE.

See Also

  • get_html_translation_table() - Returns the translation table used by htmlspecialchars and htmlentities
  • htmlspecialchars_decode() - Convert special HTML entities back to characters
  • strip_tags() - Strip HTML and PHP tags from a string
  • htmlentities() - Convert all applicable characters to HTML entities
  • nl2br() - Inserts HTML line breaks before all newlines in a string


Join array elements with a string

  • « htmlspecialchars
  • join »
  • PHP Manual
  • String Functions
  • Join array elements with a string

implode

(PHP 4, PHP 5, PHP 7)

implode — Join array elements with a string

Description

implode ( string $glue , array $pieces ) : string
implode ( array $pieces ) : string

Join array elements with a glue string.

Note:

implode() can, for historical reasons, accept its parameters in either order. For consistency with explode(), however, it is deprecated not to use the documented order of arguments.

Parameters

glue

Defaults to an empty string.

pieces

The array of strings to implode.

Return Values

Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.

Changelog

Version | Description
7.4.0 | Passing the glue after the pieces (i.e. not using the documented order of parameters) has been deprecated.

Examples

Example #1 implode() example

<?php

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);

echo $comma_separated; // lastname,email,phone

// Empty string when using an empty array:
var_dump(implode('hello', array())); // string(0) ""

?>

Notes

Note: This function is binary-safe.

See Also

  • explode() - Split a string by a string
  • preg_split() - Split string by a regular expression
  • http_build_query() - Generate URL-encoded query string


Alias of implode

  • « implode
  • lcfirst »
  • PHP Manual
  • String Functions
  • Alias of implode

join

(PHP 4, PHP 5, PHP 7)

join — Alias of implode()

Description

This function is an alias of: implode().


Make a string's first character lowercase

  • « join
  • levenshtein »
  • PHP Manual
  • String Functions
  • Make a string's first character lowercase

lcfirst

(PHP 5 >= 5.3.0, PHP 7)

lcfirst — Make a string's first character lowercase

Description

lcfirst ( string $str ) : string

Returns a string with the first character of str lowercased if that character is alphabetic.

Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a (ä) will not be converted.

Parameters

str

The input string.

Return Values

Returns the resulting string.

Examples

Example #1 lcfirst() example

<?php
$foo = 'HelloWorld';
$foo = lcfirst($foo);             // helloWorld

$bar = 'HELLO WORLD!';
$bar = lcfirst($bar);             // hELLO WORLD!
$bar = lcfirst(strtoupper($bar)); // hELLO WORLD!
?>

See Also

  • ucfirst() - Make a string's first character uppercase
  • strtolower() - Make a string lowercase
  • strtoupper() - Make a string uppercase
  • ucwords() - Uppercase the first character of each word in a string


Calculate Levenshtein distance between two strings

  • « lcfirst
  • localeconv »
  • PHP Manual
  • String Functions
  • Calculate Levenshtein distance between two strings

levenshtein

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

levenshtein — Calculate Levenshtein distance between two strings

Description

levenshtein ( string $str1 , string $str2 ) : int
levenshtein ( string $str1 , string $str2 , int $cost_ins , int $cost_rep , int $cost_del ) : int

The Levenshtein distance is defined as the minimal number of characters you have to replace, insert or delete to transform str1 into str2. The complexity of the algorithm is O(m*n), where n and m are the length of str1 and str2 (rather good when compared to similar_text(), which is O(max(n,m)**3), but still expensive).

In its simplest form the function will take only the two strings as parameter and will calculate just the number of insert, replace and delete operations needed to transform str1 into str2.

A second variant will take three additional parameters that define the cost of insert, replace and delete operations. This is more general and adaptive than variant one, but not as efficient.

Parameters

str1

One of the strings being evaluated for Levenshtein distance.

str2

One of the strings being evaluated for Levenshtein distance.

cost_ins

Defines the cost of insertion.

cost_rep

Defines the cost of replacement.

cost_del

Defines the cost of deletion.

Return Values

This function returns the Levenshtein-Distance between the two argument strings or -1, if one of the argument strings is longer than the limit of 255 characters.

Examples

Example #1 levenshtein() example

<?php
// input misspelled word
$input = 'carrrot';

// array of words to check against
$words  = array('apple','pineapple','banana','orange',
                'radish','carrot','pea','bean','potato');

// no shortest distance found, yet
$shortest = -1;

// loop through words to find the closest
foreach ($words as $word) {

    // calculate the distance between the input word,
    // and the current word
    $lev = levenshtein($input, $word);

    // check for an exact match
    if ($lev == 0) {

        // closest word is this one (exact match)
        $closest = $word;
        $shortest = 0;

        // break out of the loop; we've found an exact match
        break;
    }

    // if this distance is less than the next found shortest
    // distance, OR if a next shortest word has not yet been found
    if ($lev <= $shortest || $shortest < 0) {
        // set the closest match, and shortest distance
        $closest  = $word;
        $shortest = $lev;
    }
}

echo "Input word: $input\n";
if ($shortest == 0) {
    echo "Exact match found: $closest\n";
} else {
    echo "Did you mean: $closest?\n";
}

?>

The above example will output:

Input word: carrrot
Did you mean: carrot?

See Also

  • soundex() - Calculate the soundex key of a string
  • similar_text() - Calculate the similarity between two strings
  • metaphone() - Calculate the metaphone key of a string


Get numeric formatting information

  • « levenshtein
  • ltrim »
  • PHP Manual
  • String Functions
  • Get numeric formatting information

localeconv

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

localeconv — Get numeric formatting information

Description

localeconv ( void ) : array

Returns an associative array containing localized numeric and monetary formatting information.

Return Values

localeconv() returns data based upon the current locale as set by setlocale(). The associative array that is returned contains the following fields:

Array element | Description
decimal_point | Decimal point character
thousands_sep | Thousands separator
grouping | Array containing numeric groupings
int_curr_symbol | International currency symbol (i.e. USD)
currency_symbol | Local currency symbol (i.e. $)
mon_decimal_point | Monetary decimal point character
mon_thousands_sep | Monetary thousands separator
mon_grouping | Array containing monetary groupings
positive_sign | Sign for positive values
negative_sign | Sign for negative values
int_frac_digits | International fractional digits
frac_digits | Local fractional digits
p_cs_precedes | TRUE if currency_symbol precedes a positive value, FALSE if it succeeds one
p_sep_by_space | TRUE if a space separates currency_symbol from a positive value, FALSE otherwise
n_cs_precedes | TRUE if currency_symbol precedes a negative value, FALSE if it succeeds one
n_sep_by_space | TRUE if a space separates currency_symbol from a negative value, FALSE otherwise
p_sign_posn
  • 0 - Parentheses surround the quantity and currency_symbol
  • 1 - The sign string precedes the quantity and currency_symbol
  • 2 - The sign string succeeds the quantity and currency_symbol
  • 3 - The sign string immediately precedes the currency_symbol
  • 4 - The sign string immediately succeeds the currency_symbol
n_sign_posn
  • 0 - Parentheses surround the quantity and currency_symbol
  • 1 - The sign string precedes the quantity and currency_symbol
  • 2 - The sign string succeeds the quantity and currency_symbol
  • 3 - The sign string immediately precedes the currency_symbol
  • 4 - The sign string immediately succeeds the currency_symbol

The p_sign_posn, and n_sign_posn contain a string of formatting options. Each number representing one of the above listed conditions.

The grouping fields contain arrays that define the way numbers should be grouped. For example, the monetary grouping field for the nl_NL locale (in UTF-8 mode with the euro sign), would contain a 2 item array with the values 3 and 3. The higher the index in the array, the farther left the grouping is. If an array element is equal to CHAR_MAX, no further grouping is done. If an array element is equal to 0, the previous element should be used.

Examples

Example #1 localeconv() example

<?php
if (false !== setlocale(LC_ALL, 'nl_NL.UTF-8@euro')) {
    $locale_info = localeconv();
    print_r($locale_info);
}
?>

The above example will output:

Array
(
    [decimal_point] => .
    [thousands_sep] =>
    [int_curr_symbol] => EUR
    [currency_symbol] => €
    [mon_decimal_point] => ,
    [mon_thousands_sep] =>
    [positive_sign] =>
    [negative_sign] => -
    [int_frac_digits] => 2
    [frac_digits] => 2
    [p_cs_precedes] => 1
    [p_sep_by_space] => 1
    [n_cs_precedes] => 1
    [n_sep_by_space] => 1
    [p_sign_posn] => 1
    [n_sign_posn] => 2
    [grouping] => Array
        (
        )

    [mon_grouping] => Array
        (
            [0] => 3
            [1] => 3
        )

)

See Also

  • setlocale() - Set locale information


Strip whitespace (or other characters) from the beginning of a string

  • « localeconv
  • md5_file »
  • PHP Manual
  • String Functions
  • Strip whitespace (or other characters) from the beginning of a string

ltrim

(PHP 4, PHP 5, PHP 7)

ltrim — Strip whitespace (or other characters) from the beginning of a string

Description

ltrim ( string $str [, string $character_mask ] ) : string

Strip whitespace (or other characters) from the beginning of a string.

Parameters

str

The input string.

character_mask

You can also specify the characters you want to strip, by means of the character_mask parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

Return Values

This function returns a string with whitespace stripped from the beginning of str. Without the second parameter, ltrim() will strip these characters:

  • " " (ASCII 32 (0x20)), an ordinary space.
  • "\t" (ASCII 9 (0x09)), a tab.
  • "\n" (ASCII 10 (0x0A)), a new line (line feed).
  • "\r" (ASCII 13 (0x0D)), a carriage return.
  • "\0" (ASCII 0 (0x00)), the NUL-byte.
  • "\x0B" (ASCII 11 (0x0B)), a vertical tab.

Examples

Example #1 Usage example of ltrim()

<?php

$text = "\t\tThese are a few words :) ...  ";
$binary = "\x09Example string\x0A";
$hello  = "Hello World";
var_dump($text, $binary, $hello);

print "\n";

$trimmed = ltrim($text);
var_dump($trimmed);

$trimmed = ltrim($text, " \t.");
var_dump($trimmed);

$trimmed = ltrim($hello, "Hdle");
var_dump($trimmed);

// trim the ASCII control characters at the beginning of $binary
// (from 0 to 31 inclusive)
$clean = ltrim($binary, "\x00..\x1F");
var_dump($clean);

?>

The above example will output:

string(32) "        These are a few words :) ...  "
string(16) "    Example string
"
string(11) "Hello World"

string(30) "These are a few words :) ...  "
string(30) "These are a few words :) ...  "
string(7) "o World"
string(15) "Example string
"

See Also

  • trim() - Strip whitespace (or other characters) from the beginning and end of a string
  • rtrim() - Strip whitespace (or other characters) from the end of a string


Calculates the md5 hash of a given file

  • « ltrim
  • md5 »
  • PHP Manual
  • String Functions
  • Calculates the md5 hash of a given file

md5_file

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

md5_file — Calculates the md5 hash of a given file

Description

md5_file ( string $filename [, bool $raw_output = FALSE ] ) : string

Calculates the MD5 hash of the file specified by the filename parameter using the » RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash. The hash is a 32-character hexadecimal number.

Parameters

filename

The filename

raw_output

When TRUE, returns the digest in raw binary format with a length of 16.

Return Values

Returns a string on success, FALSE otherwise.

Changelog

Version | Description
5.1.0 | Changed the function to use the streams API. It means that you can use it with wrappers, like md5_file('http://example.com/..')

Examples

Example #1 Usage example of md5_file()

<?php
$file = 'php-5.3.0alpha2-Win32-VC9-x64.zip';

echo 'MD5 file hash of ' . $file . ': ' . md5_file($file);
?>

See Also

  • md5() - Calculate the md5 hash of a string
  • sha1_file() - Calculate the sha1 hash of a file
  • crc32() - Calculates the crc32 polynomial of a string


Calculate the md5 hash of a string

  • « md5_file
  • metaphone »
  • PHP Manual
  • String Functions
  • Calculate the md5 hash of a string

md5

(PHP 4, PHP 5, PHP 7)

md5 — Calculate the md5 hash of a string

Warning

It is not recommended to use this function to secure passwords, due to the fast nature of this hashing algorithm. See the Password Hashing FAQ for details and best practices.

Description

md5 ( string $str [, bool $raw_output = FALSE ] ) : string

Calculates the MD5 hash of str using the » RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash.

Parameters

str

The string.

raw_output

If the optional raw_output is set to TRUE, then the md5 digest is instead returned in raw binary format with a length of 16.

Return Values

Returns the hash as a 32-character hexadecimal number.

Examples

Example #1 A md5() example

<?php
$str = 'apple';

if (md5($str) === '1f3870be274f6c49b3e31a0c6728957f') {
    echo "Would you like a green or red apple?";
}
?>

See Also

  • md5_file() - Calculates the md5 hash of a given file
  • sha1_file() - Calculate the sha1 hash of a file
  • crc32() - Calculates the crc32 polynomial of a string
  • sha1() - Calculate the sha1 hash of a string
  • hash() - Generate a hash value (message digest)
  • crypt() - One-way string hashing
  • password_hash() - Creates a password hash


Calculate the metaphone key of a string

  • « md5
  • money_format »
  • PHP Manual
  • String Functions
  • Calculate the metaphone key of a string

metaphone

(PHP 4, PHP 5, PHP 7)

metaphone — Calculate the metaphone key of a string

Description

metaphone ( string $str [, int $phonemes = 0 ] ) : string

Calculates the metaphone key of str.

Similar to soundex() metaphone creates the same key for similar sounding words. It's more accurate than soundex() as it knows the basic rules of English pronunciation. The metaphone generated keys are of variable length.

Metaphone was developed by Lawrence Philips <lphilips at verity dot com>. It is described in ["Practical Algorithms for Programmers", Binstock & Rex, Addison Wesley, 1995].

Parameters

str

The input string.

phonemes

This parameter restricts the returned metaphone key to phonemes characters in length. The default value of 0 means no restriction.

Return Values

Returns the metaphone key as a string, or FALSE on failure.

Examples

Example #1 metaphone() basic example

<?php
var_dump(metaphone('programming'));
var_dump(metaphone('programmer'));
?>

The above example will output something similar to:

string(7) "PRKRMNK"
string(6) "PRKRMR"

Example #2 Using the phonemes parameter

<?php
var_dump(metaphone('programming', 5));
var_dump(metaphone('programmer', 5));
?>

The above example will output something similar to:

string(5) "PRKRM"
string(5) "PRKRM"


Formats a number as a currency string

  • « metaphone
  • nl_langinfo »
  • PHP Manual
  • String Functions
  • Formats a number as a currency string

money_format

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

money_format — Formats a number as a currency string

Description

money_format ( string $format , float $number ) : string

money_format() returns a formatted version of number. This function wraps the C library function strfmon(), with the difference that this implementation converts only one number at a time.

Parameters

format

The format specification consists of the following sequence:

  • a % character

  • optional flags

  • optional field width

  • optional left precision

  • optional right precision

  • a required conversion character

Flags

One or more of the optional flags below can be used:

=f

The character = followed by a (single byte) character f to be used as the numeric fill character. The default fill character is space.

^

Disable the use of grouping characters (as defined by the current locale).

+ or (

Specify the formatting style for positive and negative numbers. If + is used, the locale's equivalent for + and - will be used. If ( is used, negative amounts are enclosed in parenthesis. If no specification is given, the default is +.

!

Suppress the currency symbol from the output string.

-

If present, it will make all fields left-justified (padded to the right), as opposed to the default which is for the fields to be right-justified (padded to the left).

Field width

w

A decimal digit string specifying a minimum field width. Field will be right-justified unless the flag - is used. Default value is 0 (zero).

Left precision

#n

The maximum number of digits (n) expected to the left of the decimal character (e.g. the decimal point). It is used usually to keep formatted output aligned in the same columns, using the fill character if the number of digits is less than n. If the number of actual digits is bigger than n, then this specification is ignored.

If grouping has not been suppressed using the ^ flag, grouping separators will be inserted before the fill characters (if any) are added. Grouping separators will not be applied to fill characters, even if the fill character is a digit.

To ensure alignment, any characters appearing before or after the number in the formatted output such as currency or sign symbols are padded as necessary with space characters to make their positive and negative formats an equal length.

Right precision

.p

A period followed by the number of digits (p) after the decimal character. If the value of p is 0 (zero), the decimal character and the digits to its right will be omitted. If no right precision is included, the default will dictated by the current locale in use. The amount being formatted is rounded to the specified number of digits prior to formatting.

Conversion characters

i

The number is formatted according to the locale's international currency format (e.g. for the USA locale: USD 1,234.56).

n

The number is formatted according to the locale's national currency format (e.g. for the de_DE locale: EU1.234,56).

%

Returns the % character.

number

The number to be formatted.

Return Values

Returns the formatted string. Characters before and after the formatting string will be returned unchanged. Non-numeric number causes returning NULL and emitting E_WARNING.

Notes

Note:

The function money_format() is only defined if the system has strfmon capabilities. For example, Windows does not, so money_format() is undefined in Windows.

Note:

The LC_MONETARY category of the locale settings, affects the behavior of this function. Use setlocale() to set to the appropriate default locale before using this function.

Examples

Example #1 money_format() Example

We will use different locales and format specifications to illustrate the use of this function.

<?php

$number = 1234.56;

// let's print the international format for the en_US locale
setlocale(LC_MONETARY, 'en_US');
echo money_format('%i', $number) . "\n";
// USD 1,234.56

// Italian national format with 2 decimals`
setlocale(LC_MONETARY, 'it_IT');
echo money_format('%.2n', $number) . "\n";
// Eu 1.234,56

// Using a negative number
$number = -1234.5672;

// US national format, using () for negative numbers
// and 10 digits for left precision
setlocale(LC_MONETARY, 'en_US');
echo money_format('%(#10n', $number) . "\n";
// ($        1,234.57)

// Similar format as above, adding the use of 2 digits of right
// precision and '*' as a fill character
echo money_format('%=*(#10.2n', $number) . "\n";
// ($********1,234.57)

// Let's justify to the left, with 14 positions of width, 8 digits of
// left precision, 2 of right precision, without the grouping character
// and using the international format for the de_DE locale.
setlocale(LC_MONETARY, 'de_DE');
echo money_format('%=*^-14#8.2i', 1234.56) . "\n";
// Eu 1234,56****

// Let's add some blurb before and after the conversion specification
setlocale(LC_MONETARY, 'en_GB');
$fmt = 'The final value is %i (after a 10%% discount)';
echo money_format($fmt, 1234.56) . "\n";
// The final value is  GBP 1,234.56 (after a 10% discount)

?>

See Also

  • setlocale() - Set locale information
  • sscanf() - Parses input from a string according to a format
  • sprintf() - Return a formatted string
  • printf() - Output a formatted string
  • number_format() - Format a number with grouped thousands


Query language and locale information

  • « money_format
  • nl2br »
  • PHP Manual
  • String Functions
  • Query language and locale information

nl_langinfo

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

nl_langinfo — Query language and locale information

Description

nl_langinfo ( int $item ) : string

nl_langinfo() is used to access individual elements of the locale categories. Unlike localeconv(), which returns all of the elements, nl_langinfo() allows you to select any specific element.

Parameters

item

item may be an integer value of the element or the constant name of the element. The following is a list of constant names for item that may be used and their description. Some of these constants may not be defined or hold no value for certain locales.

nl_langinfo Constants
Constant | Description
LC_TIME Category Constants
ABDAY_(1-7) | Abbreviated name of n-th day of the week.
DAY_(1-7) | Name of the n-th day of the week (DAY_1 = Sunday).
ABMON_(1-12) | Abbreviated name of the n-th month of the year.
MON_(1-12) | Name of the n-th month of the year.
AM_STR | String for Ante meridian.
PM_STR | String for Post meridian.
D_T_FMT | String that can be used as the format string for strftime() to represent time and date.
D_FMT | String that can be used as the format string for strftime() to represent date.
T_FMT | String that can be used as the format string for strftime() to represent time.
T_FMT_AMPM | String that can be used as the format string for strftime() to represent time in 12-hour format with ante/post meridian.
ERA | Alternate era.
ERA_YEAR | Year in alternate era format.
ERA_D_T_FMT | Date and time in alternate era format (string can be used in strftime()).
ERA_D_FMT | Date in alternate era format (string can be used in strftime()).
ERA_T_FMT | Time in alternate era format (string can be used in strftime()).
LC_MONETARY Category Constants
INT_CURR_SYMBOL | International currency symbol.
CURRENCY_SYMBOL | Local currency symbol.
CRNCYSTR | Same value as CURRENCY_SYMBOL.
MON_DECIMAL_POINT | Decimal point character.
MON_THOUSANDS_SEP | Thousands separator (groups of three digits).
MON_GROUPING | Like "grouping" element.
POSITIVE_SIGN | Sign for positive values.
NEGATIVE_SIGN | Sign for negative values.
INT_FRAC_DIGITS | International fractional digits.
FRAC_DIGITS | Local fractional digits.
P_CS_PRECEDES | Returns 1 if CURRENCY_SYMBOL precedes a positive value.
P_SEP_BY_SPACE | Returns 1 if a space separates CURRENCY_SYMBOL from a positive value.
N_CS_PRECEDES | Returns 1 if CURRENCY_SYMBOL precedes a negative value.
N_SEP_BY_SPACE | Returns 1 if a space separates CURRENCY_SYMBOL from a negative value.
P_SIGN_POSN
  • Returns 0 if parentheses surround the quantity and CURRENCY_SYMBOL.
  • Returns 1 if the sign string precedes the quantity and CURRENCY_SYMBOL.
  • Returns 2 if the sign string follows the quantity and CURRENCY_SYMBOL.
  • Returns 3 if the sign string immediately precedes the CURRENCY_SYMBOL.
  • Returns 4 if the sign string immediately follows the CURRENCY_SYMBOL.
N_SIGN_POSN
LC_NUMERIC Category Constants
DECIMAL_POINT | Decimal point character.
RADIXCHAR | Same value as DECIMAL_POINT.
THOUSANDS_SEP | Separator character for thousands (groups of three digits).
THOUSEP | Same value as THOUSANDS_SEP.
GROUPING
LC_MESSAGES Category Constants
YESEXPR | Regex string for matching "yes" input.
NOEXPR | Regex string for matching "no" input.
YESSTR | Output string for "yes".
NOSTR | Output string for "no".
LC_CTYPE Category Constants
CODESET | Return a string with the name of the character encoding.

Return Values

Returns the element as a string, or FALSE if item is not valid.

Notes

Note: This function is not implemented on Windows platforms.

See Also

  • setlocale() - Set locale information
  • localeconv() - Get numeric formatting information


Inserts HTML line breaks before all newlines in a string

  • « nl_langinfo
  • number_format »
  • PHP Manual
  • String Functions
  • Inserts HTML line breaks before all newlines in a string

nl2br

(PHP 4, PHP 5, PHP 7)

nl2br — Inserts HTML line breaks before all newlines in a string

Description

nl2br ( string $string [, bool $is_xhtml = TRUE ] ) : string

Returns string with <br /> or <br> inserted before all newlines (\r\n, \n\r, \n and \r).

Parameters

string

The input string.

is_xhtml

Whether to use XHTML compatible line breaks or not.

Return Values

Returns the altered string.

Examples

Example #1 Using nl2br()

<?php
echo nl2br("foo isn't\n bar");
?>

The above example will output:

foo isn't<br />
 bar

Example #2 Generating valid HTML markup using the is_xhtml parameter

<?php
echo nl2br("Welcome\r\nThis is my HTML document", false);
?>

The above example will output:

Welcome<br>
This is my HTML document

Example #3 Various newline separators

<?php
$string = "This\r\nis\n\ra\nstring\r";
echo nl2br($string);
?>

The above example will output:

This<br />
is<br />
a<br />
string<br />

Changelog

Version | Description
5.3.0 | Added the optional is_xhtml parameter. Before this version '<br />' was always inserted.

See Also

  • htmlspecialchars() - Convert special characters to HTML entities
  • htmlentities() - Convert all applicable characters to HTML entities
  • wordwrap() - Wraps a string to a given number of characters
  • str_replace() - Replace all occurrences of the search string with the replacement string


Format a number with grouped thousands

  • « nl2br
  • ord »
  • PHP Manual
  • String Functions
  • Format a number with grouped thousands

number_format

(PHP 4, PHP 5, PHP 7)

number_format — Format a number with grouped thousands

Description

number_format ( float $number [, int $decimals = 0 ] ) : string
number_format ( float $number , int $decimals = 0 , string $dec_point = "." , string $thousands_sep = "," ) : string

This function accepts either one, two, or four parameters (not three):

If only one parameter is given, number will be formatted without decimals, but with a comma (",") between every group of thousands.

If two parameters are given, number will be formatted with decimals decimals with a dot (".") in front, and a comma (",") between every group of thousands.

If all four parameters are given, number will be formatted with decimals decimals, dec_point instead of a dot (".") before the decimals and thousands_sep instead of a comma (",") between every group of thousands.

Parameters

number

The number being formatted.

decimals

Sets the number of decimal points.

dec_point

Sets the separator for the decimal point.

thousands_sep

Sets the thousands separator.

Return Values

A formatted version of number.

Changelog

Version | Description
7.2.0 | number_format() was changed to not being able to return -0, previously -0 could be returned for cases like where number would be -0.01.
5.4.0 | This function now supports multiple bytes in dec_point and thousands_sep. Only the first byte of each separator was used in older versions.

Examples

Example #1 number_format() Example

For instance, French notation usually use two decimals, comma (',') as decimal separator, and space (' ') as thousand separator. The following example demonstrates various ways to format a number:

<?php

$number = 1234.56;

// english notation (default)
$english_format_number = number_format($number);
// 1,235

// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56

$number = 1234.5678;

// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57

?>

See Also

  • money_format() - Formats a number as a currency string
  • sprintf() - Return a formatted string
  • printf() - Output a formatted string
  • sscanf() - Parses input from a string according to a format


Convert the first byte of a string to a value between 0 and 255

  • « number_format
  • parse_str »
  • PHP Manual
  • String Functions
  • Convert the first byte of a string to a value between 0 and 255

ord

(PHP 4, PHP 5, PHP 7)

ord — Convert the first byte of a string to a value between 0 and 255

Description

ord ( string $string ) : int

Interprets the binary value of the first byte of string as an unsigned integer between 0 and 255.

If the string is in a single-byte encoding, such as ASCII, ISO-8859, or Windows 1252, this is equivalent to returning the position of a character in the character set's mapping table. However, note that this function is not aware of any string encoding, and in particular will never identify a Unicode code point in a multi-byte encoding such as UTF-8 or UTF-16.

This function complements chr().

Parameters

string

A character.

Return Values

An integer between 0 and 255.

Examples

Example #1 ord() example

<?php
$str = "\n";
if (ord($str) == 10) {
    echo "The first character of \$str is a line feed.\n";
}
?>

Example #2 Examining the individual bytes of a UTF-8 string

<?php
declare(encoding='UTF-8');
$str = "🐘";
for ( $pos=0; $pos < strlen($str); $pos ++ ) {
 $byte = substr($str, $pos);
 echo 'Byte ' . $pos . ' of $str has value ' . ord($byte) . PHP_EOL;
}
?>

The above example will output:

Byte 0 of $str has value 240
Byte 1 of $str has value 159
Byte 2 of $str has value 144
Byte 3 of $str has value 152

See Also

  • chr() - Generate a single-byte string from a number
  • An » ASCII-table
  • mb_ord() - Get code point of character


Parses the string into variables

  • « ord
  • print »
  • PHP Manual
  • String Functions
  • Parses the string into variables

parse_str

(PHP 4, PHP 5, PHP 7)

parse_str — Parses the string into variables

Description

parse_str ( string $encoded_string [, array &$result ] ) : void

Parses encoded_string as if it were the query string passed via a URL and sets variables in the current scope (or in the array if result is provided).

Parameters

encoded_string

The input string.

result

If the second parameter result is present, variables are stored in this variable as array elements instead.

Warning

Using this function without the result parameter is highly DISCOURAGED and DEPRECATED as of PHP 7.2.

Dynamically setting variables in function's scope suffers from exactly same problems as register_globals.

Read section on security of Using Register Globals explaining why it is dangerous.

Return Values

No value is returned.

Changelog

Version | Description
7.2.0 | Usage of parse_str() without a second parameter now emits an E_DEPRECATED notice.

Examples

Example #1 Using parse_str()

<?php
$str = "first=value&arr[]=foo+bar&arr[]=baz";

// Recommended
parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

// DISCOURAGED
parse_str($str);
echo $first;  // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz
?>

Because variables in PHP can't have dots and spaces in their names, those are converted to underscores. Same applies to naming of respective key names in case of using this function with result parameter.

Example #2 parse_str() name mangling

<?php
parse_str("My Value=Something");
echo $My_Value; // Something

parse_str("My Value=Something", $output);
echo $output['My_Value']; // Something
?>

Notes

Note:

All variables created (or values returned into array if second parameter is set) are already urldecode()d.

Note:

To get the current QUERY_STRING, you may use the variable $_SERVER['QUERY_STRING']. Also, you may want to read the section on variables from external sources.

Note:

The magic_quotes_gpc setting affects the output of this function, as parse_str() uses the same mechanism that PHP uses to populate the $_GET, $_POST, etc. variables.

See Also

  • parse_url() - Parse a URL and return its components
  • pathinfo() - Returns information about a file path
  • http_build_query() - Generate URL-encoded query string
  • urldecode() - Decodes URL-encoded string


Output a string

  • « parse_str
  • printf »
  • PHP Manual
  • String Functions
  • Output a string

print

(PHP 4, PHP 5, PHP 7)

print — Output a string

Description

print ( string $arg ) : int

Outputs arg.

print is not actually a real function (it is a language construct) so you are not required to use parentheses with its argument list.

The major differences to echo are that print only accepts a single argument and always returns 1.

Parameters

arg

The input data.

Return Values

Returns 1, always.

Examples

Example #1 print examples

<?php
print("Hello World");

print "print() also works without parentheses.";

print "This spans
multiple lines. The newlines will be
output as well";

print "This spans\nmultiple lines. The newlines will be\noutput as well.";

print "escaping characters is done \"Like this\".";

// You can use variables inside a print statement
$foo = "foobar";
$bar = "barbaz";

print "foo is $foo"; // foo is foobar

// You can also use arrays
$bar = array("value" => "foo");

print "this is {$bar['value']} !"; // this is foo !

// Using single quotes will print the variable name, not the value
print 'foo is $foo'; // foo is $foo

// If you are not using any other characters, you can just print variables
print $foo;          // foobar

print <<<END
This uses the "here document" syntax to output
multiple lines with $variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon no extra whitespace!
END;
?>

Notes

Note: Because this is a language construct and not a function, it cannot be called using variable functions.

See Also

  • echo - Output one or more strings
  • printf() - Output a formatted string
  • flush() - Flush system output buffer
  • Heredoc syntax


Output a formatted string

  • « print
  • quoted_printable_decode »
  • PHP Manual
  • String Functions
  • Output a formatted string

printf

(PHP 4, PHP 5, PHP 7)

printf — Output a formatted string

Description

printf ( string $format [, mixed $... ] ) : int

Produces output according to format.

Parameters

format

The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result and conversion specifications, each of which results in fetching its own parameter.

A conversion specification follows this prototype: %[argnum$][flags][width][.precision]specifier.

Argnum

An integer followed by a dollar sign $, to specify which number argument to treat in the conversion.

Flags
Flag | Description
- Left-justify within the given field width; Right justification is the default
+ Prefix positive numbers with a plus sign +; Default only negative are prefixed with a negative sign.
(space) | Pads the result with spaces. This is the default.
0 | Only left-pads numbers with zeros. With s specifiers this can also right-pad with zeros.
'(char) | Pads the result with the character (char).

Width

An integer that says how many characters (minimum) this conversion should result in.

Precision

A period . followed by an integer who's meaning depends on the specifier:

  • For e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
  • For g and G specifiers: this is the maximum number of significant digits to be printed.
  • For s specifier: it acts as a cutoff point, setting a maximum character limit to the string.

Note: If the period is specified without an explicit value for precision, 0 is assumed.

Note: Attempting to use a position specifier greater than PHP_INT_MAX will generate warnings.

Specifiers
Specifier | Description
% A literal percent character. No argument is required.
b | The argument is treated as an integer and presented as a binary number.
c | The argument is treated as an integer and presented as the character with that ASCII.
d | The argument is treated as an integer and presented as a (signed) decimal number.
e | The argument is treated as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point since PHP 5.2.1. In earlier versions, it was taken as number of significant digits (one less).
E | Like the e specifier but uses uppercase letter (e.g. 1.2E+2).
f | The argument is treated as a float and presented as a floating-point number (locale aware).
F | The argument is treated as a float and presented as a floating-point number (non-locale aware). Available as of PHP 5.0.3.
g

General format.

Let P equal the precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero. Then, if a conversion with style E would have an exponent of X:

If P > X ≥ −4, the conversion is with style f and precision P − (X + 1). Otherwise, the conversion is with style e and precision P − 1.

G | Like the g specifier but uses E and F.
o | The argument is treated as an integer and presented as an octal number.
s | The argument is treated and presented as a string.
u | The argument is treated as an integer and presented as an unsigned decimal number.
x | The argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).
X | The argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).

Warning

The c type specifier ignores padding and width

Warning

Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results

Variables will be co-erced to a suitable type for the specifier:

Type Handling
Type | Specifiers
string | s
integer | d, u, c, o, x, X, b
double | g, G, e, E, f, F

...

Return Values

Returns the length of the outputted string.

Examples

Example #1 printf(): various examples

<?php
$n =  43951789;
$u = -43951789;
$c = 65; // ASCII 65 is 'A'

// notice the double %%, this prints a literal '%' character
printf("%%b = '%b'\n", $n); // binary representation
printf("%%c = '%c'\n", $c); // print the ascii character, same as chr() function
printf("%%d = '%d'\n", $n); // standard integer representation
printf("%%e = '%e'\n", $n); // scientific notation
printf("%%u = '%u'\n", $n); // unsigned integer representation of a positive integer
printf("%%u = '%u'\n", $u); // unsigned integer representation of a negative integer
printf("%%f = '%f'\n", $n); // floating point representation
printf("%%o = '%o'\n", $n); // octal representation
printf("%%s = '%s'\n", $n); // string representation
printf("%%x = '%x'\n", $n); // hexadecimal representation (lower-case)
printf("%%X = '%X'\n", $n); // hexadecimal representation (upper-case)

printf("%%+d = '%+d'\n", $n); // sign specifier on a positive integer
printf("%%+d = '%+d'\n", $u); // sign specifier on a negative integer
?>

The above example will output:

%b = '10100111101010011010101101'
%c = 'A'
%d = '43951789'
%e = '4.39518e+7'
%u = '43951789'
%u = '4251015507'
%f = '43951789.000000'
%o = '247523255'
%s = '43951789'
%x = '29ea6ad'
%X = '29EA6AD'
%+d = '+43951789'
%+d = '-43951789'

Example #2 printf(): string specifiers

<?php
$s = 'monkey';
$t = 'many monkeys';

printf("[%s]\n",      $s); // standard string output
printf("[%10s]\n",    $s); // right-justification with spaces
printf("[%-10s]\n",   $s); // left-justification with spaces
printf("[%010s]\n",   $s); // zero-padding works on strings too
printf("[%'#10s]\n",  $s); // use the custom padding character '#'
printf("[%10.9s]\n", $t); // right-justification but with a cutoff of 8 characters
printf("[%-10.9s]\n", $t); // left-justification but with a cutoff of 8 characters
?>

The above example will output:

[monkey]
[    monkey]
[monkey    ]
[0000monkey]
[####monkey]
[ many monk]
[many monk ]

See Also

  • print - Output a string
  • sprintf() - Return a formatted string
  • fprintf() - Write a formatted string to a stream
  • vprintf() - Output a formatted string
  • vsprintf() - Return a formatted string
  • vfprintf() - Write a formatted string to a stream
  • sscanf() - Parses input from a string according to a format
  • fscanf() - Parses input from a file according to a format
  • number_format() - Format a number with grouped thousands
  • date() - Format a local time/date
  • flush() - Flush system output buffer


Convert a quoted-printable string to an 8 bit string

  • « printf
  • quoted_printable_encode »
  • PHP Manual
  • String Functions
  • Convert a quoted-printable string to an 8 bit string

quoted_printable_decode

(PHP 4, PHP 5, PHP 7)

quoted_printable_decode — Convert a quoted-printable string to an 8 bit string

Description

quoted_printable_decode ( string $str ) : string

This function returns an 8-bit binary string corresponding to the decoded quoted printable string (according to » RFC2045, section 6.7, not » RFC2821, section 4.5.2, so additional periods are not stripped from the beginning of line).

This function is similar to imap_qprint(), except this one does not require the IMAP module to work.

Parameters

str

The input string.

Return Values

Returns the 8-bit binary string.

See Also

  • quoted_printable_encode() - Convert a 8 bit string to a quoted-printable string


Convert a 8 bit string to a quoted-printable string

  • « quoted_printable_decode
  • quotemeta »
  • PHP Manual
  • String Functions
  • Convert a 8 bit string to a quoted-printable string

quoted_printable_encode

(PHP 5 >= 5.3.0, PHP 7)

quoted_printable_encode — Convert a 8 bit string to a quoted-printable string

Description

quoted_printable_encode ( string $str ) : string

Returns a quoted printable string created according to » RFC2045, section 6.7.

This function is similar to imap_8bit(), except this one does not require the IMAP module to work.

Parameters

str

The input string.

Return Values

Returns the encoded string.

See Also

  • quoted_printable_decode() - Convert a quoted-printable string to an 8 bit string
  • iconv_mime_encode() - Composes a MIME header field


Quote meta characters

  • « quoted_printable_encode
  • rtrim »
  • PHP Manual
  • String Functions
  • Quote meta characters

quotemeta

(PHP 4, PHP 5, PHP 7)

quotemeta — Quote meta characters

Description

quotemeta ( string $str ) : string

Returns a version of str with a backslash character (\) before every character that is among these:

. \ + * ? [ ^ ] ( $ )

Parameters

str

The input string.

Return Values

Returns the string with meta characters quoted, or FALSE if an empty string is given as str.

Notes

Note: This function is binary-safe.

See Also

  • addslashes() - Quote string with slashes
  • addcslashes() - Quote string with slashes in a C style
  • htmlentities() - Convert all applicable characters to HTML entities
  • htmlspecialchars() - Convert special characters to HTML entities
  • nl2br() - Inserts HTML line breaks before all newlines in a string
  • stripslashes() - Un-quotes a quoted string
  • stripcslashes() - Un-quote string quoted with addcslashes
  • ereg() - Regular expression match
  • preg_quote() - Quote regular expression characters


Strip whitespace (or other characters) from the end of a string

  • « quotemeta
  • setlocale »
  • PHP Manual
  • String Functions
  • Strip whitespace (or other characters) from the end of a string

rtrim

(PHP 4, PHP 5, PHP 7)

rtrim — Strip whitespace (or other characters) from the end of a string

Description

rtrim ( string $str [, string $character_mask ] ) : string

This function returns a string with whitespace (or other characters) stripped from the end of str.

Without the second parameter, rtrim() will strip these characters:

  • " " (ASCII 32 (0x20)), an ordinary space.
  • "\t" (ASCII 9 (0x09)), a tab.
  • "\n" (ASCII 10 (0x0A)), a new line (line feed).
  • "\r" (ASCII 13 (0x0D)), a carriage return.
  • "\0" (ASCII 0 (0x00)), the NULL-byte.
  • "\x0B" (ASCII 11 (0x0B)), a vertical tab.

Parameters

str

The input string.

character_mask

You can also specify the characters you want to strip, by means of the character_mask parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

Return Values

Returns the modified string.

Examples

Example #1 Usage example of rtrim()

<?php

$text = "\t\tThese are a few words :) ...  ";
$binary = "\x09Example string\x0A";
$hello  = "Hello World";
var_dump($text, $binary, $hello);

print "\n";

$trimmed = rtrim($text);
var_dump($trimmed);

$trimmed = rtrim($text, " \t.");
var_dump($trimmed);

$trimmed = rtrim($hello, "Hdle");
var_dump($trimmed);

// trim the ASCII control characters at the end of $binary
// (from 0 to 31 inclusive)
$clean = rtrim($binary, "\x00..\x1F");
var_dump($clean);

?>

The above example will output:

string(32) "        These are a few words :) ...  "
string(16) "    Example string
"
string(11) "Hello World"

string(30) "        These are a few words :) ..."
string(26) "        These are a few words :)"
string(9) "Hello Wor"
string(15) "    Example string"

See Also

  • trim() - Strip whitespace (or other characters) from the beginning and end of a string
  • ltrim() - Strip whitespace (or other characters) from the beginning of a string


Set locale information

  • « rtrim
  • sha1_file »
  • PHP Manual
  • String Functions
  • Set locale information

setlocale

(PHP 4, PHP 5, PHP 7)

setlocale — Set locale information

Description

setlocale ( int $category , string $locale [, string $... ] ) : string
setlocale ( int $category , array $locale ) : string

Sets locale information.

Warning

The locale information is maintained per process, not per thread. If you are running PHP on a multithreaded server API like IIS, HHVM or Apache on Windows, you may experience sudden changes in locale settings while a script is running, though the script itself never called setlocale(). This happens due to other scripts running in different threads of the same process at the same time, changing the process-wide locale using setlocale().

Parameters

category

category is a named constant specifying the category of the functions affected by the locale setting:

  • LC_ALL for all of the below
  • LC_COLLATE for string comparison, see strcoll()
  • LC_CTYPE for character classification and conversion, for example strtoupper()
  • LC_MONETARY for localeconv()
  • LC_NUMERIC for decimal separator (See also localeconv())
  • LC_TIME for date and time formatting with strftime()
  • LC_MESSAGES for system responses (available if PHP was compiled with libintl)

locale

If locale is NULL or the empty string "", the locale names will be set from the values of environment variables with the same names as the above categories, or from "LANG".

If locale is "0", the locale setting is not affected, only the current setting is returned.

If locale is an array or followed by additional parameters then each array element or parameter is tried to be set as new locale until success. This is useful if a locale is known under different names on different systems or for providing a fallback for a possibly not available locale.

...

(Optional string or array parameters to try as locale settings until success.)

Note:

On Windows, setlocale(LC_ALL, '') sets the locale names from the system's regional/language settings (accessible via Control Panel).

Return Values

Returns the new current locale, or FALSE if the locale functionality is not implemented on your platform, the specified locale does not exist or the category name is invalid.

An invalid category name also causes a warning message. Category/locale names can be found in » RFC 1766 and » ISO 639. Different systems have different naming schemes for locales.

Note:

The return value of setlocale() depends on the system that PHP is running. It returns exactly what the system setlocale function returns.

Changelog

Version | Description
7.0.0 | Support for the category parameter passed as a string has been removed. Only LC_* constants can be used as of this version.
5.3.0 | This function now throws an E_DEPRECATED notice if a string is passed to the category parameter instead of one of the LC_* constants.

Examples

Example #1 setlocale() Examples

<?php
/* Set locale to Dutch */
setlocale(LC_ALL, 'nl_NL');

/* Output: vrijdag 22 december 1978 */
echo strftime("%A %e %B %Y", mktime(0, 0, 0, 12, 22, 1978));

/* try different possible locale names for german */
$loc_de = setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'de', 'ge');
echo "Preferred locale for german on this system is '$loc_de'";
?>

Example #2 setlocale() Examples for Windows

<?php
/* Set locale to Dutch */
setlocale(LC_ALL, 'nld_nld');

/* Output: vrijdag 22 december 1978 */
echo strftime("%A %d %B %Y", mktime(0, 0, 0, 12, 22, 1978));

/* try different possible locale names for german */
$loc_de = setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'deu_deu');
echo "Preferred locale for german on this system is '$loc_de'";
?>

Notes

Tip

Windows users will find useful information about locale strings at Microsoft's MSDN website. Supported language strings can be found in the » language strings documentation and supported country/region strings in the » country/region strings documentation.


Calculate the sha1 hash of a file

  • « setlocale
  • sha1 »
  • PHP Manual
  • String Functions
  • Calculate the sha1 hash of a file

sha1_file

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

sha1_file — Calculate the sha1 hash of a file

Description

sha1_file ( string $filename [, bool $raw_output = FALSE ] ) : string

Calculates the sha1 hash of the file specified by filename using the » US Secure Hash Algorithm 1, and returns that hash. The hash is a 40-character hexadecimal number.

Parameters

filename

The filename of the file to hash.

raw_output

When TRUE, returns the digest in raw binary format with a length of 20.

Return Values

Returns a string on success, FALSE otherwise.

Examples

Example #1 sha1_file() example

<?php
foreach(glob('/home/Kalle/myproject/*.php') as $ent)
{
    if(is_dir($ent))
    {
        continue;
    }

    echo $ent . ' (SHA1: ' . sha1_file($ent) . ')', PHP_EOL;
}
?>

Changelog

Version | Description
5.1.0 | Changed the function to use the streams API. It means that you can use it with wrappers, like sha1_file('http://example.com/..')

See Also

  • sha1() - Calculate the sha1 hash of a string
  • md5_file() - Calculates the md5 hash of a given file
  • crc32() - Calculates the crc32 polynomial of a string


Calculate the sha1 hash of a string

  • « sha1_file
  • similar_text »
  • PHP Manual
  • String Functions
  • Calculate the sha1 hash of a string

sha1

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

sha1 — Calculate the sha1 hash of a string

Warning

It is not recommended to use this function to secure passwords, due to the fast nature of this hashing algorithm. See the Password Hashing FAQ for details and best practices.

Description

sha1 ( string $str [, bool $raw_output = FALSE ] ) : string

Calculates the sha1 hash of str using the » US Secure Hash Algorithm 1.

Parameters

str

The input string.

raw_output

If the optional raw_output is set to TRUE, then the sha1 digest is instead returned in raw binary format with a length of 20, otherwise the returned value is a 40-character hexadecimal number.

Return Values

Returns the sha1 hash as a string.

Examples

Example #1 A sha1() example

<?php
$str = 'apple';

if (sha1($str) === 'd0be2dc421be4fcd0172e5afceea3970e2f3d940') {
    echo "Would you like a green or red apple?";
}
?>

See Also

  • sha1_file() - Calculate the sha1 hash of a file
  • crc32() - Calculates the crc32 polynomial of a string
  • md5() - Calculate the md5 hash of a string
  • hash() - Generate a hash value (message digest)
  • crypt() - One-way string hashing
  • password_hash() - Creates a password hash


Calculate the similarity between two strings

  • « sha1
  • soundex »
  • PHP Manual
  • String Functions
  • Calculate the similarity between two strings

similar_text

(PHP 4, PHP 5, PHP 7)

similar_text — Calculate the similarity between two strings

Description

similar_text ( string $first , string $second [, float &$percent ] ) : int

This calculates the similarity between two strings as described in Programming Classics: Implementing the World's Best Algorithms by Oliver (ISBN 0-131-00413-1). Note that this implementation does not use a stack as in Oliver's pseudo code, but recursive calls which may or may not speed up the whole process. Note also that the complexity of this algorithm is O(N**3) where N is the length of the longest string.

Parameters

first

The first string.

second

The second string.

Note:

Swapping the first and second may yield a different result; see the example below.

percent

By passing a reference as third argument, similar_text() will calculate the similarity in percent, by dividing the result of similar_text() by the average of the lengths of the given strings times 100.

Return Values

Returns the number of matching chars in both strings.

The number of matching characters is calculated by finding the longest first common substring, and then doing this for the prefixes and the suffixes, recursively. The lengths of all found common substrings are added.

Examples

Example #1 similar_text() argument swapping example

This example shows that swapping the first and second argument may yield different results.

<?php
$sim = similar_text('bafoobar', 'barfoo', $perc);
echo "similarity: $sim ($perc %)\n";
$sim = similar_text('barfoo', 'bafoobar', $perc);
echo "similarity: $sim ($perc %)\n";

The above example will output something similar to:

similarity: 5 (71.428571428571 %)
similarity: 3 (42.857142857143 %)

See Also

  • levenshtein() - Calculate Levenshtein distance between two strings
  • soundex() - Calculate the soundex key of a string


Calculate the soundex key of a string

  • « similar_text
  • sprintf »
  • PHP Manual
  • String Functions
  • Calculate the soundex key of a string

soundex

(PHP 4, PHP 5, PHP 7)

soundex — Calculate the soundex key of a string

Description

soundex ( string $str ) : string

Calculates the soundex key of str.

Soundex keys have the property that words pronounced similarly produce the same soundex key, and can thus be used to simplify searches in databases where you know the pronunciation but not the spelling. This soundex function returns a string 4 characters long, starting with a letter.

This particular soundex function is one described by Donald Knuth in "The Art Of Computer Programming, vol. 3: Sorting And Searching", Addison-Wesley (1973), pp. 391-392.

Parameters

str

The input string.

Return Values

Returns the soundex key as a string, or FALSE on failure.

Examples

Example #1 Soundex Examples

<?php
soundex("Euler")       == soundex("Ellery");    // E460
soundex("Gauss")       == soundex("Ghosh");     // G200
soundex("Hilbert")     == soundex("Heilbronn"); // H416
soundex("Knuth")       == soundex("Kant");      // K530
soundex("Lloyd")       == soundex("Ladd");      // L300
soundex("Lukasiewicz") == soundex("Lissajous"); // L222
?>

See Also

  • levenshtein() - Calculate Levenshtein distance between two strings
  • metaphone() - Calculate the metaphone key of a string
  • similar_text() - Calculate the similarity between two strings


Return a formatted string

  • « soundex
  • sscanf »
  • PHP Manual
  • String Functions
  • Return a formatted string

sprintf

(PHP 4, PHP 5, PHP 7)

sprintf — Return a formatted string

Description

sprintf ( string $format [, mixed $... ] ) : string

Returns a string produced according to the formatting string format.

Parameters

format

The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result and conversion specifications, each of which results in fetching its own parameter.

A conversion specification follows this prototype: %[argnum$][flags][width][.precision]specifier.

Argnum

An integer followed by a dollar sign $, to specify which number argument to treat in the conversion.

Flags
Flag | Description
- Left-justify within the given field width; Right justification is the default
+ Prefix positive numbers with a plus sign +; Default only negative are prefixed with a negative sign.
(space) | Pads the result with spaces. This is the default.
0 | Only left-pads numbers with zeros. With s specifiers this can also right-pad with zeros.
'(char) | Pads the result with the character (char).

Width

An integer that says how many characters (minimum) this conversion should result in.

Precision

A period . followed by an integer who's meaning depends on the specifier:

  • For e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
  • For g and G specifiers: this is the maximum number of significant digits to be printed.
  • For s specifier: it acts as a cutoff point, setting a maximum character limit to the string.

Note: If the period is specified without an explicit value for precision, 0 is assumed.

Note: Attempting to use a position specifier greater than PHP_INT_MAX will generate warnings.

Specifiers
Specifier | Description
% A literal percent character. No argument is required.
b | The argument is treated as an integer and presented as a binary number.
c | The argument is treated as an integer and presented as the character with that ASCII.
d | The argument is treated as an integer and presented as a (signed) decimal number.
e | The argument is treated as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point since PHP 5.2.1. In earlier versions, it was taken as number of significant digits (one less).
E | Like the e specifier but uses uppercase letter (e.g. 1.2E+2).
f | The argument is treated as a float and presented as a floating-point number (locale aware).
F | The argument is treated as a float and presented as a floating-point number (non-locale aware). Available as of PHP 5.0.3.
g

General format.

Let P equal the precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero. Then, if a conversion with style E would have an exponent of X:

If P > X ≥ −4, the conversion is with style f and precision P − (X + 1). Otherwise, the conversion is with style e and precision P − 1.

G | Like the g specifier but uses E and F.
o | The argument is treated as an integer and presented as an octal number.
s | The argument is treated and presented as a string.
u | The argument is treated as an integer and presented as an unsigned decimal number.
x | The argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).
X | The argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).

Warning

The c type specifier ignores padding and width

Warning

Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results

Variables will be co-erced to a suitable type for the specifier:

Type Handling
Type | Specifiers
string | s
integer | d, u, c, o, x, X, b
double | g, G, e, E, f, F

...

Return Values

Returns a string produced according to the formatting string format, or FALSE on failure.

Examples

Example #1 Argument swapping

The format string supports argument numbering/swapping.

<?php
$num = 5;
$location = 'tree';

$format = 'There are %d monkeys in the %s';
echo sprintf($format, $num, $location);
?>

The above example will output:

There are 5 monkeys in the tree

However imagine we are creating a format string in a separate file, commonly because we would like to internationalize it and we rewrite it as:

<?php
$format = 'The %s contains %d monkeys';
echo sprintf($format, $num, $location);
?>

We now have a problem. The order of the placeholders in the format string does not match the order of the arguments in the code. We would like to leave the code as is and simply indicate in the format string which arguments the placeholders refer to. We would write the format string like this instead:

<?php
$format = 'The %2$s contains %1$d monkeys';
echo sprintf($format, $num, $location);
?>

An added benefit is that placeholders can be repeated without adding more arguments in the code.

<?php
$format = 'The %2$s contains %1$d monkeys.
           That\'s a nice %2$s full of %1$d monkeys.';
echo sprintf($format, $num, $location);
?>

When using argument swapping, the n$ position specifier must come immediately after the percent sign (%), before any other specifiers, as shown below.

Example #2 Specifying padding character

<?php
echo sprintf("%'.9d\n", 123);
echo sprintf("%'.09d\n", 123);
?>

The above example will output:

......123
000000123

Example #3 Position specifier with other specifiers

<?php
$format = 'The %2$s contains %1$04d monkeys';
echo sprintf($format, $num, $location);
?>

The above example will output:

The tree contains 0005 monkeys

Example #4 sprintf(): zero-padded integers

<?php
$isodate = sprintf("%04d-%02d-%02d", $year, $month, $day);
?>

Example #5 sprintf(): formatting currency

<?php
$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
echo $money;
echo "\n";
$formatted = sprintf("%01.2f", $money);
echo $formatted;
?>

The above example will output:

123.1
123.10

Example #6 sprintf(): scientific notation

<?php
$number = 362525200;

echo sprintf("%.3e", $number);
?>

The above example will output:

3.625e+8

See Also

  • printf() - Output a formatted string
  • fprintf() - Write a formatted string to a stream
  • vprintf() - Output a formatted string
  • vsprintf() - Return a formatted string
  • vfprintf() - Write a formatted string to a stream
  • sscanf() - Parses input from a string according to a format
  • fscanf() - Parses input from a file according to a format
  • number_format() - Format a number with grouped thousands
  • date() - Format a local time/date


Parses input from a string according to a format

  • « sprintf
  • str_getcsv »
  • PHP Manual
  • String Functions
  • Parses input from a string according to a format

sscanf

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

sscanf — Parses input from a string according to a format

Description

sscanf ( string $str , string $format [, mixed &$... ] ) : mixed

The function sscanf() is the input analog of printf(). sscanf() reads from the string str and interprets it according to the specified format, which is described in the documentation for sprintf().

Any whitespace in the format string matches any whitespace in the input string. This means that even a tab \t in the format string can match a single space character in the input string.

Parameters

str

The input string being parsed.

format

The interpreted format for str, 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.

...

Optionally pass in variables by reference that will contain the parsed 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 str, -1 will be returned.

Examples

Example #1 sscanf() Example

<?php
// getting the serial number
list($serial) = sscanf("SN/2350001", "SN/%d");
// and the date of manufacturing
$mandate = "January 01 2000";
list($month, $day, $year) = sscanf($mandate, "%s %d %d");
echo "Item $serial was manufactured on: $year-" . substr($month, 0, 3) . "-$day\n";
?>

If optional parameters are passed, the function will return the number of assigned values.

Example #2 sscanf() - using optional parameters

<?php
// get author info and generate DocBook entry
$auth = "24\tLewis Carroll";
$n = sscanf($auth, "%d\t%s %s", $id, $first, $last);
echo "<author id='$id'>
    <firstname>$first</firstname>
    <surname>$last</surname>
</author>\n";
?>

See Also

  • printf() - Output a formatted string
  • sprintf() - Return a formatted string
  • fprintf() - Write a formatted string to a stream
  • vprintf() - Output a formatted string
  • vsprintf() - Return a formatted string
  • vfprintf() - Write a formatted string to a stream
  • fscanf() - Parses input from a file according to a format
  • number_format() - Format a number with grouped thousands
  • date() - Format a local time/date


Parse a CSV string into an array

  • « sscanf
  • str_ireplace »
  • PHP Manual
  • String Functions
  • Parse a CSV string into an array

str_getcsv

(PHP 5 >= 5.3.0, PHP 7)

str_getcsv — Parse a CSV string into an array

Description

str_getcsv ( string $input [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\\" ]]] ) : array

Parses a string input for fields in CSV format and returns an array containing the fields read.

Note:

The locale settings are taken into account by this function. If LC_CTYPE is e.g. en_US.UTF-8, strings in one-byte encodings may be read wrongly by this function.

Parameters

input

The string to parse.

delimiter

Set the field delimiter (one character only).

enclosure

Set the field enclosure character (one character only).

escape

Set the escape character (at most one character). Defaults as a backslash (\) An empty string ("") disables the proprietary escape mechanism.

Note: Usually an enclosure character is escaped inside a field by doubling it; however, the escape character can be used as an alternative. So for the default parameter values "" and \" have the same meaning. Other than allowing to escape the enclosure character the escape character has no special meaning; it isn't even meant to escape itself.

Return Values

Returns an indexed array containing the fields read.

Changelog

Version | Description
7.4.0 | The escape parameter now interprets an empty string as signal to disable the proprietary escape mechanism. Formerly, an empty string was treated like the default parameter value.

See Also

  • fgetcsv() - Gets line from file pointer and parse for CSV fields


Case-insensitive version of str_replace

  • « str_getcsv
  • str_pad »
  • PHP Manual
  • String Functions
  • Case-insensitive version of str_replace

str_ireplace

(PHP 5, PHP 7)

str_ireplace — Case-insensitive version of str_replace()

Description

str_ireplace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] ) : mixed

This function returns a string or an array with all occurrences of search in subject (ignoring case) replaced with the given replace value. If you don't need fancy replacing rules, you should generally use this function instead of preg_replace() with the i modifier.

Parameters

If search and replace are arrays, then str_ireplace() takes a value from each array and uses them to search and replace on subject. If replace has fewer values than search, then an empty string is used for the rest of replacement values. If search is an array and replace is a string, then this replacement string is used for every value of search. The converse would not make sense, though.

If search or replace are arrays, their elements are processed first to last.

search

The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.

replace

The replacement value that replaces found search values. An array may be used to designate multiple replacements.

subject

The string or array being searched and replaced on, otherwise known as the haystack.

If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well.

count

If passed, this will be set to the number of replacements performed.

Return Values

Returns a string or an array of replacements.

Examples

Example #1 str_ireplace() example

<?php
$bodytag = str_ireplace("%body%", "black", "<body text=%BODY%>");
echo $bodytag; // <body text=black>
?>

Notes

Note: This function is binary-safe.

Caution

Replacement order gotcha

Because str_ireplace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. Example #2 in the str_replace() documentation demonstrates how this may affect you in practice.

See Also

  • str_replace() - Replace all occurrences of the search string with the replacement string
  • preg_replace() - Perform a regular expression search and replace
  • strtr() - Translate characters or replace substrings


Pad a string to a certain length with another string

  • « str_ireplace
  • str_repeat »
  • PHP Manual
  • String Functions
  • Pad a string to a certain length with another string

str_pad

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

str_pad — Pad a string to a certain length with another string

Description

str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] ) : string

This function returns the input string padded on the left, the right, or both sides to the specified padding length. If the optional argument pad_string is not supplied, the input is padded with spaces, otherwise it is padded with characters from pad_string up to the limit.

Parameters

input

The input string.

pad_length

If the value of pad_length is negative, less than, or equal to the length of the input string, no padding takes place, and input 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. If pad_type is not specified it is assumed to be STR_PAD_RIGHT.

Return Values

Returns the padded string.

Examples

Example #1 str_pad() example

<?php
$input = "Alien";
echo str_pad($input, 10);                      // produces "Alien     "
echo str_pad($input, 10, "-=", STR_PAD_LEFT);  // produces "-=-=-Alien"
echo str_pad($input, 10, "_", STR_PAD_BOTH);   // produces "__Alien___"
echo str_pad($input,  6, "___");               // produces "Alien_"
echo str_pad($input,  3, "*");                 // produces "Alien"
?>


Repeat a string

  • « str_pad
  • str_replace »
  • PHP Manual
  • String Functions
  • Repeat a string

str_repeat

(PHP 4, PHP 5, PHP 7)

str_repeat — Repeat a string

Description

str_repeat ( string $input , int $multiplier ) : string

Returns input repeated multiplier times.

Parameters

input

The string to be repeated.

multiplier

Number of time the input string should be repeated.

multiplier has to be greater than or equal to 0. If the multiplier is set to 0, the function will return an empty string.

Return Values

Returns the repeated string.

Examples

Example #1 str_repeat() example

<?php
echo str_repeat("-=", 10);
?>

The above example will output:

-=-=-=-=-=-=-=-=-=-=

See Also

  • for
  • str_pad() - Pad a string to a certain length with another string
  • substr_count() - Count the number of substring occurrences


Replace all occurrences of the search string with the replacement string

  • « str_repeat
  • str_rot13 »
  • PHP Manual
  • String Functions
  • Replace all occurrences of the search string with the replacement string

str_replace

(PHP 4, PHP 5, PHP 7)

str_replace — Replace all occurrences of the search string with the replacement string

Description

str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] ) : mixed

This function returns a string or an array with all occurrences of search in subject replaced with the given replace value.

If you don't need fancy replacing rules (like regular expressions), you should use this function instead of preg_replace().

Parameters

If search and replace are arrays, then str_replace() takes a value from each array and uses them to search and replace on subject. If replace has fewer values than search, then an empty string is used for the rest of replacement values. If search is an array and replace is a string, then this replacement string is used for every value of search. The converse would not make sense, though.

If search or replace are arrays, their elements are processed first to last.

search

The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.

replace

The replacement value that replaces found search values. An array may be used to designate multiple replacements.

subject

The string or array being searched and replaced on, otherwise known as the haystack.

If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well.

count

If passed, this will be set to the number of replacements performed.

Return Values

This function returns a string or an array with the replaced values.

Examples

Example #1 Basic str_replace() examples

<?php
// Provides: <body text='black'>
$bodytag = str_replace("%body%", "black", "<body text='%body%'>");

// Provides: Hll Wrld f PHP
$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");

// Provides: You should eat pizza, beer, and ice cream every day
$phrase  = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy   = array("pizza", "beer", "ice cream");

$newphrase = str_replace($healthy, $yummy, $phrase);

// Provides: 2
$str = str_replace("ll", "", "good golly miss molly!", $count);
echo $count;
?>

Example #2 Examples of potential str_replace() gotchas

<?php
// Order of replacement
$str     = "Line 1\nLine 2\rLine 3\r\nLine 4\n";
$order   = array("\r\n", "\n", "\r");
$replace = '<br />';

// Processes \r\n's first so they aren't converted twice.
$newstr = str_replace($order, $replace, $str);

// Outputs F because A is replaced with B, then B is replaced with C, and so on...
// Finally E is replaced with F, because of left to right replacements.
$search  = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';
echo str_replace($search, $replace, $subject);

// Outputs: apearpearle pear
// For the same reason mentioned above
$letters = array('a', 'p');
$fruit   = array('apple', 'pear');
$text    = 'a p';
$output  = str_replace($letters, $fruit, $text);
echo $output;
?>

Notes

Note: This function is binary-safe.

Caution

Replacement order gotcha

Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. See also the examples in this document.

Note:

This function is case-sensitive. Use str_ireplace() for case-insensitive replace.

See Also

  • str_ireplace() - Case-insensitive version of str_replace
  • substr_replace() - Replace text within a portion of a string
  • preg_replace() - Perform a regular expression search and replace
  • strtr() - Translate characters or replace substrings


Perform the rot13 transform on a string

  • « str_replace
  • str_shuffle »
  • PHP Manual
  • String Functions
  • Perform the rot13 transform on a string

str_rot13

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

str_rot13 — Perform the rot13 transform on a string

Description

str_rot13 ( string $str ) : string

Performs the ROT13 encoding on the str argument and returns the resulting string.

The ROT13 encoding simply shifts every letter by 13 places in the alphabet while leaving non-alpha characters untouched. Encoding and decoding are done by the same function, passing an encoded string as argument will return the original version.

Parameters

str

The input string.

Return Values

Returns the ROT13 version of the given string.

Examples

Example #1 str_rot13() example

<?php

echo str_rot13('PHP 4.3.0'); // CUC 4.3.0

?>


Randomly shuffles a string

  • « str_rot13
  • str_split »
  • PHP Manual
  • String Functions
  • Randomly shuffles a string

str_shuffle

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

str_shuffle — Randomly shuffles a string

Description

str_shuffle ( string $str ) : string

str_shuffle() shuffles a string. One permutation of all possible is created.

Caution

This function does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using random_int(), random_bytes(), or openssl_random_pseudo_bytes() instead.

Parameters

str

The input string.

Return Values

Returns the shuffled string.

Changelog

Version | Description
7.1.0 | The internal randomization algorithm has been changed to use the » Mersenne Twister Random Number Generator instead of the libc rand function.

Examples

Example #1 str_shuffle() example

<?php
$str = 'abcdef';
$shuffled = str_shuffle($str);

// This will echo something like: bfdaec
echo $shuffled;
?>

See Also

  • shuffle() - Shuffle an array
  • rand() - Generate a random integer


Convert a string to an array

  • « str_shuffle
  • str_word_count »
  • PHP Manual
  • String Functions
  • Convert a string to an array

str_split

(PHP 5, PHP 7)

str_split — Convert a string to an array

Description

str_split ( string $string [, int $split_length = 1 ] ) : array

Converts a string to an array.

Parameters

string

The input string.

split_length

Maximum length of the chunk.

Return Values

If the optional split_length parameter is specified, the returned array will be broken down into chunks with each being split_length in length, otherwise each chunk will be one character in length.

FALSE is returned if split_length is less than 1. If the split_length length exceeds the length of string, the entire string is returned as the first (and only) array element.

Examples

Example #1 Example uses of str_split()

<?php

$str = "Hello Friend";

$arr1 = str_split($str);
$arr2 = str_split($str, 3);

print_r($arr1);
print_r($arr2);

?>

The above example will output:

Array
(
    [0] => H
    [1] => e
    [2] => l
    [3] => l
    [4] => o
    [5] =>
    [6] => F
    [7] => r
    [8] => i
    [9] => e
    [10] => n
    [11] => d
)

Array
(
    [0] => Hel
    [1] => lo
    [2] => Fri
    [3] => end
)

Notes

Note:

str_split() will split into bytes, rather than characters when dealing with a multi-byte encoded string.

See Also

  • chunk_split() - Split a string into smaller chunks
  • preg_split() - Split string by a regular expression
  • explode() - Split a string by a string
  • count_chars() - Return information about characters used in a string
  • str_word_count() - Return information about words used in a string
  • for


Return information about words used in a string

  • « str_split
  • strcasecmp »
  • PHP Manual
  • String Functions
  • Return information about words used in a string

str_word_count

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

str_word_count — Return information about words used in a string

Description

str_word_count ( string $string [, int $format = 0 [, string $charlist ]] ) : mixed

Counts the number of words inside string. If the optional format is not specified, then the return value will be an integer representing the number of words found. In the event the format is specified, the return value will be an array, content of which is dependent on the format. The possible value for the format and the resultant outputs are listed below.

For the purpose of this function, 'word' is defined as a locale dependent string containing alphabetic characters, which also may contain, but not start with "'" and "-" characters.

Parameters

string

The string

format

Specify the return value of this function. The current supported values are:

  • 0 - returns the number of words found
  • 1 - returns an array containing all the words found inside the string
  • 2 - returns an associative array, where the key is the numeric position of the word inside the string and the value is the actual word itself

charlist

A list of additional characters which will be considered as 'word'

Return Values

Returns an array or an integer, depending on the format chosen.

Changelog

Version | Description
5.1.0 | Added the charlist parameter

Examples

Example #1 A str_word_count() example

<?php

$str = "Hello fri3nd, you're
       looking          good today!";

print_r(str_word_count($str, 1));
print_r(str_word_count($str, 2));
print_r(str_word_count($str, 1, 'àáãç3'));

echo str_word_count($str);

?>

The above example will output:

Array
(
    [0] => Hello
    [1] => fri
    [2] => nd
    [3] => you're
    [4] => looking
    [5] => good
    [6] => today
)

Array
(
    [0] => Hello
    [6] => fri
    [10] => nd
    [14] => you're
    [29] => looking
    [46] => good
    [51] => today
)

Array
(
    [0] => Hello
    [1] => fri3nd
    [2] => you're
    [3] => looking
    [4] => good
    [5] => today
)

7

See Also

  • explode() - Split a string by a string
  • preg_split() - Split string by a regular expression
  • split() - Split string into array by regular expression
  • count_chars() - Return information about characters used in a string
  • substr_count() - Count the number of substring occurrences


Binary safe case-insensitive string comparison

  • « str_word_count
  • strchr »
  • PHP Manual
  • String Functions
  • Binary safe case-insensitive string comparison

strcasecmp

(PHP 4, PHP 5, PHP 7)

strcasecmp — Binary safe case-insensitive string comparison

Description

strcasecmp ( string $str1 , string $str2 ) : int

Binary safe case-insensitive string comparison.

Parameters

str1

The first string

str2

The second string

Return Values

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Examples

Example #1 strcasecmp() example

<?php
$var1 = "Hello";
$var2 = "hello";
if (strcasecmp($var1, $var2) == 0) {
    echo '$var1 is equal to $var2 in a case-insensitive string comparison';
}
?>

See Also

  • strcmp() - Binary safe string comparison
  • preg_match() - Perform a regular expression match
  • substr_compare() - Binary safe comparison of two strings from an offset, up to length characters
  • strncasecmp() - Binary safe case-insensitive string comparison of the first n characters
  • stristr() - Case-insensitive strstr
  • substr() - Return part of a string


Alias of strstr

  • « strcasecmp
  • strcmp »
  • PHP Manual
  • String Functions
  • Alias of strstr

strchr

(PHP 4, PHP 5, PHP 7)

strchr — Alias of strstr()

Description

This function is an alias of: strstr().


Binary safe string comparison

  • « strchr
  • strcoll »
  • PHP Manual
  • String Functions
  • Binary safe string comparison

strcmp

(PHP 4, PHP 5, PHP 7)

strcmp — Binary safe string comparison

Description

strcmp ( string $str1 , string $str2 ) : int

Note that this comparison is case sensitive.

Parameters

str1

The first string.

str2

The second string.

Return Values

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Examples

Example #1 strcmp() example

<?php
$var1 = "Hello";
$var2 = "hello";
if (strcmp($var1, $var2) !== 0) {
    echo '$var1 is not equal to $var2 in a case sensitive string comparison';
}
?>

See Also

  • strcasecmp() - Binary safe case-insensitive string comparison
  • preg_match() - Perform a regular expression match
  • substr_compare() - Binary safe comparison of two strings from an offset, up to length characters
  • strncmp() - Binary safe string comparison of the first n characters
  • strstr() - Find the first occurrence of a string
  • substr() - Return part of a string


Locale based string comparison

  • « strcmp
  • strcspn »
  • PHP Manual
  • String Functions
  • Locale based string comparison

strcoll

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

strcoll — Locale based string comparison

Description

strcoll ( string $str1 , string $str2 ) : int

Note that this comparison is case sensitive, and unlike strcmp() this function is not binary safe.

strcoll() uses the current locale for doing the comparisons. If the current locale is C or POSIX, this function is equivalent to strcmp().

Parameters

str1

The first string.

str2

The second string.

Return Values

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

See Also

  • preg_match() - Perform a regular expression match
  • strcmp() - Binary safe string comparison
  • strcasecmp() - Binary safe case-insensitive string comparison
  • substr() - Return part of a string
  • stristr() - Case-insensitive strstr
  • strncasecmp() - Binary safe case-insensitive string comparison of the first n characters
  • strncmp() - Binary safe string comparison of the first n characters
  • strstr() - Find the first occurrence of a string
  • setlocale() - Set locale information


Find length of initial segment not matching mask

  • « strcoll
  • strip_tags »
  • PHP Manual
  • String Functions
  • Find length of initial segment not matching mask

strcspn

(PHP 4, PHP 5, PHP 7)

strcspn — Find length of initial segment not matching mask

Description

strcspn ( string $subject , string $mask [, int $start [, int $length ]] ) : int

Returns the length of the initial segment of subject which does not contain any of the characters in mask.

If start and length are omitted, then all of subject will be examined. If they are included, then the effect will be the same as calling strcspn(substr($subject, $start, $length), $mask) (see substr for more information).

Parameters

subject

The string to examine.

mask

The string containing every disallowed character.

start

The position in subject to start searching.

If start is given and is non-negative, then strcspn() will begin examining subject at the start'th position. 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 given and is negative, then strcspn() will begin examining subject at the start'th position from the end of subject.

length

The length of the segment from subject to examine.

If length is given and is non-negative, then subject will be examined for length characters after the starting position.

If length is given and is negative, then subject will be examined from the starting position up to length characters from the end of subject.

Return Values

Returns the length of the initial segment of subject which consists entirely of characters not in mask.

Note:

When a start parameter is set, the returned length is counted starting from this position, not from the beginning of subject.

Examples

Example #1 strcspn() example

<?php
$a = strcspn('abcd',  'apple');
$b = strcspn('abcd',  'banana');
$c = strcspn('hello', 'l');
$d = strcspn('hello', 'world');
$e = strcspn('abcdhelloabcd', 'abcd', -9);
$f = strcspn('abcdhelloabcd', 'abcd', -9, -5);

var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);
var_dump($e);
var_dump($f);
?>

The above example will output:

int(0)
int(0)
int(2)
int(2)
int(5)
int(4)

Notes

Note: This function is binary-safe.

See Also

  • strspn() - Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask


Strip HTML and PHP tags from a string

  • « strcspn
  • stripcslashes »
  • PHP Manual
  • String Functions
  • Strip HTML and PHP tags from a string

strip_tags

(PHP 4, PHP 5, PHP 7)

strip_tags — Strip HTML and PHP tags from a string

Description

strip_tags ( string $str [, string $allowable_tags ] ) : string

This function tries to return a string with all NULL bytes, HTML and PHP tags stripped from a given str. It uses the same tag stripping state machine as the fgetss() function.

Parameters

str

The input string.

allowable_tags

You can use the optional second parameter to specify tags which should not be stripped.

Note:

HTML comments and PHP tags are also stripped. This is hardcoded and can not be changed with allowable_tags.

Note:

In PHP 5.3.4 and later, self-closing XHTML tags are ignored and only non-self-closing tags should be used in allowable_tags. For example, to allow both <br> and <br/>, you should use:

<?php
strip_tags($input, '<br>');
?>

Return Values

Returns the stripped string.

Changelog

Version | Description
5.3.4 | strip_tags() ignores self-closing XHTML tags in allowable_tags.

Examples

Example #1 strip_tags() example

<?php
$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo strip_tags($text);
echo "\n";

// Allow <p> and <a>
echo strip_tags($text, '<p><a>');
?>

The above example will output:

Test paragraph. Other text
<p>Test paragraph.</p> <a href="#fragment">Other text</a>

Notes

Warning

This function should not be used to try to prevent XSS attacks. Use more appropriate functions like htmlspecialchars() or other means depending on the context of the output.

Warning

Because strip_tags() does not actually validate the HTML, partial or broken tags can result in the removal of more text/data than expected.

Warning

This function does not modify any attributes on the tags that you allow using allowable_tags, including the style and onmouseover attributes that a mischievous user may abuse when posting text that will be shown to other users.

Note:

Tag names within the input HTML that are greater than 1023 bytes in length will be treated as though they are invalid, regardless of the allowable_tags parameter.

See Also

  • htmlspecialchars() - Convert special characters to HTML entities


Un-quote string quoted with addcslashes

  • « strip_tags
  • stripos »
  • PHP Manual
  • String Functions
  • Un-quote string quoted with addcslashes

stripcslashes

(PHP 4, PHP 5, PHP 7)

stripcslashes — Un-quote string quoted with addcslashes()

Description

stripcslashes ( string $str ) : string

Returns a string with backslashes stripped off. Recognizes C-like \n, \r ..., octal and hexadecimal representation.

Parameters

str

The string to be unescaped.

Return Values

Returns the unescaped string.

See Also

  • addcslashes() - Quote string with slashes in a C style


Find the position of the first occurrence of a case-insensitive substring in a string

  • « stripcslashes
  • stripslashes »
  • PHP Manual
  • String Functions
  • Find the position of the first occurrence of a case-insensitive substring in a string

stripos

(PHP 5, PHP 7)

stripos — Find the position of the first occurrence of a case-insensitive substring in a string

Description

stripos ( string $haystack , mixed $needle [, int $offset = 0 ] ) : int

Find the numeric position of the first occurrence of needle in the haystack string.

Unlike the strpos(), stripos() is case-insensitive.

Parameters

haystack

The string to search in.

needle

Note that the needle may be a string of one or more characters.

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. This behavior is deprecated as of PHP 7.3.0, and relying on it is highly discouraged. Depending on the intended behavior, the needle should either be explicitly cast to string, or an explicit call to chr() should be performed.

offset

If specified, search will start this number of characters counted from the beginning of the string. If the offset is negative, the search will start this number of characters counted from the end of the string.

Return Values

Returns the position of where the needle exists relative to the beginnning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1.

Returns FALSE if the needle was not found.

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
7.1.0 | Support for negative offsets has been added.

Examples

Example #1 stripos() examples

<?php
$findme    = 'a';
$mystring1 = 'xyz';
$mystring2 = 'ABC';

$pos1 = stripos($mystring1, $findme);
$pos2 = stripos($mystring2, $findme);

// Nope, 'a' is certainly not in 'xyz'
if ($pos1 === false) {
    echo "The string '$findme' was not found in the string '$mystring1'";
}

// Note our use of ===.  Simply == would not work as expected
// because the position of 'a' is the 0th (first) character.
if ($pos2 !== false) {
    echo "We found '$findme' in '$mystring2' at position $pos2";
}
?>

Notes

Note: This function is binary-safe.

See Also

  • mb_stripos() - Finds position of first occurrence of a string within another, case insensitive
  • strpos() - Find the position of the first occurrence of a substring in a string
  • strrpos() - Find the position of the last occurrence of a substring in a string
  • strripos() - Find the position of the last occurrence of a case-insensitive substring in a string
  • stristr() - Case-insensitive strstr
  • substr() - Return part of a string
  • str_ireplace() - Case-insensitive version of str_replace


Un-quotes a quoted string

  • « stripos
  • stristr »
  • PHP Manual
  • String Functions
  • Un-quotes a quoted string

stripslashes

(PHP 4, PHP 5, PHP 7)

stripslashes — Un-quotes a quoted string

Description

stripslashes ( string $str ) : string

Un-quotes a quoted string.

Note:

If magic_quotes_sybase is on, no backslashes are stripped off but two apostrophes are replaced by one instead.

An example use of stripslashes() is when the PHP directive magic_quotes_gpc is on (it was on by default before PHP 5.4), and you aren't inserting this data into a place (such as a database) that requires escaping. For example, if you're simply outputting data straight from an HTML form.

Parameters

str

The input string.

Return Values

Returns a string with backslashes stripped off. (\' becomes ' and so on.) Double backslashes (\\) are made into a single backslash (\).

Examples

Example #1 A stripslashes() example

<?php
$str = "Is your name O\'reilly?";

// Outputs: Is your name O'reilly?
echo stripslashes($str);
?>

Note:

stripslashes() is not recursive. If you want to apply this function to a multi-dimensional array, you need to use a recursive function.

Example #2 Using stripslashes() on an array

<?php
function stripslashes_deep($value)
{
    $value = is_array($value) ?
                array_map('stripslashes_deep', $value) :
                stripslashes($value);

    return $value;
}

// Example
$array = array("f\\'oo", "b\\'ar", array("fo\\'o", "b\\'ar"));
$array = stripslashes_deep($array);

// Output
print_r($array);
?>

The above example will output:

Array
(
    [0] => f'oo
    [1] => b'ar
    [2] => Array
        (
            [0] => fo'o
            [1] => b'ar
        )

)

See Also

  • addslashes() - Quote string with slashes
  • get_magic_quotes_gpc() - Gets the current configuration setting of magic_quotes_gpc


Case-insensitive strstr

  • « stripslashes
  • strlen »
  • PHP Manual
  • String Functions
  • Case-insensitive strstr

stristr

(PHP 4, PHP 5, PHP 7)

stristr — Case-insensitive strstr()

Description

stristr ( string $haystack , mixed $needle [, bool $before_needle = FALSE ] ) : string

Returns all of haystack starting from and including the first occurrence of needle to the end.

Parameters

haystack

The string to search in

needle

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. This behavior is deprecated as of PHP 7.3.0, and relying on it is highly discouraged. Depending on the intended behavior, the needle should either be explicitly cast to string, or an explicit call to chr() should be performed.

before_needle

If TRUE, stristr() returns the part of the haystack before the first occurrence of the needle (excluding needle).

needle and haystack are examined in a case-insensitive manner.

Return Values

Returns the matched substring. If needle is not found, returns FALSE.

Changelog

Version | Description
5.3.0 | Added the optional parameter before_needle.

Examples

Example #1 stristr() example

<?php
  $email = 'USER@EXAMPLE.com';
  echo stristr($email, 'e'); // outputs ER@EXAMPLE.com
  echo stristr($email, 'e', true); // As of PHP 5.3.0, outputs US
?>

Example #2 Testing if a string is found or not

<?php
  $string = 'Hello World!';
  if(stristr($string, 'earth') === FALSE) {
    echo '"earth" not found in string';
  }
// outputs: "earth" not found in string
?>

Example #3 Using a non "string" needle

<?php
  $string = 'APPLE';
  echo stristr($string, 97); // 97 = lowercase a
// outputs: APPLE
?>

Notes

Note: This function is binary-safe.

See Also

  • strstr() - Find the first occurrence of a string
  • strrchr() - Find the last occurrence of a character in a string
  • stripos() - Find the position of the first occurrence of a case-insensitive substring in a string
  • strpbrk() - Search a string for any of a set of characters
  • preg_match() - Perform a regular expression match


Get string length

  • « stristr
  • strnatcasecmp »
  • PHP Manual
  • String Functions
  • Get string length

strlen

(PHP 4, PHP 5, PHP 7)

strlen — Get string length

Description

strlen ( string $string ) : int

Returns the length of the given string.

Parameters

string

The string being measured for length.

Return Values

The length of the string on success, and 0 if the string is empty.

Changelog

Version | Description
5.3.0 | Prior versions treated arrays as the string Array, thus returning a string length of 5 and emitting an E_NOTICE level error.

Examples

Example #1 A strlen() example

<?php
$str = 'abcdef';
echo strlen($str); // 6

$str = ' ab cd ';
echo strlen($str); // 7
?>

Notes

Note:

strlen() returns the number of bytes rather than the number of characters in a string.

Note:

strlen() returns NULL when executed on arrays, and an E_WARNING level error is emitted.

See Also

  • count() - Count all elements in an array, or something in an object
  • grapheme_strlen() - Get string length in grapheme units
  • iconv_strlen() - Returns the character count of string
  • mb_strlen() - Get string length


Case insensitive string comparisons using a "natural order" algorithm

  • « strlen
  • strnatcmp »
  • PHP Manual
  • String Functions
  • Case insensitive string comparisons using a "natural order" algorithm

strnatcasecmp

(PHP 4, PHP 5, PHP 7)

strnatcasecmp — Case insensitive string comparisons using a "natural order" algorithm

Description

strnatcasecmp ( string $str1 , string $str2 ) : int

This function implements a comparison algorithm that orders alphanumeric strings in the way a human being would. The behaviour of this function is similar to strnatcmp(), except that the comparison is not case sensitive. For more information see: Martin Pool's » Natural Order String Comparison page.

Parameters

str1

The first string.

str2

The second string.

Return Values

Similar to other string comparison functions, this one returns < 0 if str1 is less than str2 > 0 if str1 is greater than str2, and 0 if they are equal.

See Also

  • preg_match() - Perform a regular expression match
  • strcmp() - Binary safe string comparison
  • strcasecmp() - Binary safe case-insensitive string comparison
  • substr() - Return part of a string
  • stristr() - Case-insensitive strstr
  • strncasecmp() - Binary safe case-insensitive string comparison of the first n characters
  • strncmp() - Binary safe string comparison of the first n characters
  • strstr() - Find the first occurrence of a string
  • setlocale() - Set locale information


String comparisons using a "natural order" algorithm

  • « strnatcasecmp
  • strncasecmp »
  • PHP Manual
  • String Functions
  • String comparisons using a "natural order" algorithm

strnatcmp

(PHP 4, PHP 5, PHP 7)

strnatcmp — String comparisons using a "natural order" algorithm

Description

strnatcmp ( string $str1 , string $str2 ) : int

This function implements a comparison algorithm that orders alphanumeric strings in the way a human being would, this is described as a "natural ordering". Note that this comparison is case sensitive.

Parameters

str1

The first string.

str2

The second string.

Return Values

Similar to other string comparison functions, this one returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Examples

An example of the difference between this algorithm and the regular computer string sorting algorithms (used in strcmp()) can be seen below:

<?php
$arr1 = $arr2 = array("img12.png", "img10.png", "img2.png", "img1.png");
echo "Standard string comparison\n";
usort($arr1, "strcmp");
print_r($arr1);
echo "\nNatural order string comparison\n";
usort($arr2, "strnatcmp");
print_r($arr2);
?>

The above example will output:

Standard string comparison
Array
(
    [0] => img1.png
    [1] => img10.png
    [2] => img12.png
    [3] => img2.png
)

Natural order string comparison
Array
(
    [0] => img1.png
    [1] => img2.png
    [2] => img10.png
    [3] => img12.png
)
For more information see: Martin Pool's » Natural Order String Comparison page.

See Also

  • preg_match() - Perform a regular expression match
  • strcasecmp() - Binary safe case-insensitive string comparison
  • substr() - Return part of a string
  • stristr() - Case-insensitive strstr
  • strcmp() - Binary safe string comparison
  • strncmp() - Binary safe string comparison of the first n characters
  • strncasecmp() - Binary safe case-insensitive string comparison of the first n characters
  • strnatcasecmp() - Case insensitive string comparisons using a "natural order" algorithm
  • strstr() - Find the first occurrence of a string
  • natsort() - Sort an array using a "natural order" algorithm
  • natcasesort() - Sort an array using a case insensitive "natural order" algorithm


Binary safe case-insensitive string comparison of the first n characters

  • « strnatcmp
  • strncmp »
  • PHP Manual
  • String Functions
  • Binary safe case-insensitive string comparison of the first n characters

strncasecmp

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

strncasecmp — Binary safe case-insensitive string comparison of the first n characters

Description

strncasecmp ( string $str1 , string $str2 , int $len ) : int

This function is similar to strcasecmp(), with the difference that you can specify the (upper limit of the) number of characters from each string to be used in the comparison.

Parameters

str1

The first string.

str2

The second string.

len

The length of strings to be used in the comparison.

Return Values

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

See Also

  • strncmp() - Binary safe string comparison of the first n characters
  • preg_match() - Perform a regular expression match
  • substr_compare() - Binary safe comparison of two strings from an offset, up to length characters
  • strcasecmp() - Binary safe case-insensitive string comparison
  • stristr() - Case-insensitive strstr
  • substr() - Return part of a string


Binary safe string comparison of the first n characters

  • « strncasecmp
  • strpbrk »
  • PHP Manual
  • String Functions
  • Binary safe string comparison of the first n characters

strncmp

(PHP 4, PHP 5, PHP 7)

strncmp — Binary safe string comparison of the first n characters

Description

strncmp ( string $str1 , string $str2 , int $len ) : int

This function is similar to strcmp(), with the difference that you can specify the (upper limit of the) number of characters from each string to be used in the comparison.

Note that this comparison is case sensitive.

Parameters

str1

The first string.

str2

The second string.

len

Number of characters to use in the comparison.

Return Values

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

See Also

  • strncasecmp() - Binary safe case-insensitive string comparison of the first n characters
  • preg_match() - Perform a regular expression match
  • substr_compare() - Binary safe comparison of two strings from an offset, up to length characters
  • strcmp() - Binary safe string comparison
  • strstr() - Find the first occurrence of a string
  • substr() - Return part of a string


Search a string for any of a set of characters

  • « strncmp
  • strpos »
  • PHP Manual
  • String Functions
  • Search a string for any of a set of characters

strpbrk

(PHP 5, PHP 7)

strpbrk — Search a string for any of a set of characters

Description

strpbrk ( string $haystack , string $char_list ) : string

strpbrk() searches the haystack string for a char_list.

Parameters

haystack

The string where char_list is looked for.

char_list

This parameter is case sensitive.

Return Values

Returns a string starting from the character found, or FALSE if it is not found.

Examples

Example #1 strpbrk() example

<?php

$text = 'This is a Simple text.';

// this echoes "is is a Simple text." because 'i' is matched first
echo strpbrk($text, 'mi');

// this echoes "Simple text." because chars are case sensitive
echo strpbrk($text, 'S');
?>

See Also

  • strpos() - Find the position of the first occurrence of a substring in a string
  • strstr() - Find the first occurrence of a string
  • preg_match() - Perform a regular expression match


Find the position of the first occurrence of a substring in a string

  • « strpbrk
  • strrchr »
  • PHP Manual
  • String Functions
  • Find the position of the first occurrence of a substring in a string

strpos

(PHP 4, PHP 5, PHP 7)

strpos — Find the position of the first occurrence of a substring in a string

Description

strpos ( string $haystack , mixed $needle [, int $offset = 0 ] ) : int

Find the numeric position of the first occurrence of needle in the haystack string.

Parameters

haystack

The string to search in.

needle

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. This behavior is deprecated as of PHP 7.3.0, and relying on it is highly discouraged. Depending on the intended behavior, the needle should either be explicitly cast to string, or an explicit call to chr() should be performed.

offset

If specified, search will start this number of characters counted from the beginning of the string. If the offset is negative, the search will start this number of characters counted from the end of the string.

Return Values

Returns the position of where the needle exists relative to the beginning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1.

Returns FALSE if the needle was not found.

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
7.1.0 | Support for negative offsets has been added.

Examples

Example #1 Using ===

<?php
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// Note our use of ===.  Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
    echo "The string '$findme' was not found in the string '$mystring'";
} else {
    echo "The string '$findme' was found in the string '$mystring'";
    echo " and exists at position $pos";
}
?>

Example #2 Using !==

<?php
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// The !== operator can also be used.  Using != would not work as expected
// because the position of 'a' is 0. The statement (0 != false) evaluates
// to false.
if ($pos !== false) {
     echo "The string '$findme' was found in the string '$mystring'";
         echo " and exists at position $pos";
} else {
     echo "The string '$findme' was not found in the string '$mystring'";
}
?>

Example #3 Using an offset

<?php
// We can search for the character, ignoring anything before the offset
$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1); // $pos = 7, not 0
?>

Notes

Note: This function is binary-safe.

See Also

  • stripos() - Find the position of the first occurrence of a case-insensitive substring in a string
  • strrpos() - Find the position of the last occurrence of a substring in a string
  • strripos() - Find the position of the last occurrence of a case-insensitive substring in a string
  • strstr() - Find the first occurrence of a string
  • strpbrk() - Search a string for any of a set of characters
  • substr() - Return part of a string
  • preg_match() - Perform a regular expression match


Find the last occurrence of a character in a string

  • « strpos
  • strrev »
  • PHP Manual
  • String Functions
  • Find the last occurrence of a character in a string

strrchr

(PHP 4, PHP 5, PHP 7)

strrchr — Find the last occurrence of a character in a string

Description

strrchr ( string $haystack , mixed $needle ) : string

This function returns the portion of haystack which starts at the last occurrence of needle and goes until the end of haystack.

Parameters

haystack

The string to search in

needle

If needle contains more than one character, only the first is used. This behavior is different from that of strstr().

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. This behavior is deprecated as of PHP 7.3.0, and relying on it is highly discouraged. Depending on the intended behavior, the needle should either be explicitly cast to string, or an explicit call to chr() should be performed.

Return Values

This function returns the portion of string, or FALSE if needle is not found.

Examples

Example #1 strrchr() example

<?php
// get last directory in $PATH
$dir = substr(strrchr($PATH, ":"), 1);

// get everything after last newline
$text = "Line 1\nLine 2\nLine 3";
$last = substr(strrchr($text, 10), 1 );
?>

Notes

Note: This function is binary-safe.

See Also

  • strstr() - Find the first occurrence of a string
  • strrpos() - Find the position of the last occurrence of a substring in a string


Reverse a string

  • « strrchr
  • strripos »
  • PHP Manual
  • String Functions
  • Reverse a string

strrev

(PHP 4, PHP 5, PHP 7)

strrev — Reverse a string

Description

strrev ( string $string ) : string

Returns string, reversed.

Parameters

string

The string to be reversed.

Return Values

Returns the reversed string.

Examples

Example #1 Reversing a string with strrev()

<?php
echo strrev("Hello world!"); // outputs "!dlrow olleH"
?>


Find the position of the last occurrence of a case-insensitive substring in a string

  • « strrev
  • strrpos »
  • PHP Manual
  • String Functions
  • Find the position of the last occurrence of a case-insensitive substring in a string

strripos

(PHP 5, PHP 7)

strripos — Find the position of the last occurrence of a case-insensitive substring in a string

Description

strripos ( string $haystack , mixed $needle [, int $offset = 0 ] ) : int

Find the numeric position of the last occurrence of needle in the haystack string.

Unlike the strrpos(), strripos() is case-insensitive.

Parameters

haystack

The string to search in.

needle

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. This behavior is deprecated as of PHP 7.3.0, and relying on it is highly discouraged. Depending on the intended behavior, the needle should either be explicitly cast to string, or an explicit call to chr() should be performed.

offset

If zero or positive, the search is performed left to right skipping the first offset bytes of the haystack.

If negative, the search is performed right to left skipping the last offset bytes of the haystack and searching for the first occurrence of needle.

Note:

This is effectively looking for the last occurrence of needle before the last offset bytes.

Return Values

Returns the position where the needle exists relative to the beginnning of the haystack string (independent of search direction or offset).

Note: String positions start at 0, and not 1.

Returns FALSE if the needle was not found.

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 simple strripos() example

<?php
$haystack = 'ababcd';
$needle   = 'aB';

$pos      = strripos($haystack, $needle);

if ($pos === false) {
    echo "Sorry, we did not find ($needle) in ($haystack)";
} else {
    echo "Congratulations!\n";
    echo "We found the last ($needle) in ($haystack) at position ($pos)";
}
?>

The above example will output:

   Congratulations!
   We found the last (aB) in (ababcd) at position (2)

See Also

  • strpos() - Find the position of the first occurrence of a substring in a string
  • stripos() - Find the position of the first occurrence of a case-insensitive substring in a string
  • strrpos() - Find the position of the last occurrence of a substring in a string
  • strrchr() - Find the last occurrence of a character in a string
  • stristr() - Case-insensitive strstr
  • substr() - Return part of a string


Find the position of the last occurrence of a substring in a string

  • « strripos
  • strspn »
  • PHP Manual
  • String Functions
  • Find the position of the last occurrence of a substring in a string

strrpos

(PHP 4, PHP 5, PHP 7)

strrpos — Find the position of the last occurrence of a substring in a string

Description

strrpos ( string $haystack , mixed $needle [, int $offset = 0 ] ) : int

Find the numeric position of the last occurrence of needle in the haystack string.

Parameters

haystack

The string to search in.

needle

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. This behavior is deprecated as of PHP 7.3.0, and relying on it is highly discouraged. Depending on the intended behavior, the needle should either be explicitly cast to string, or an explicit call to chr() should be performed.

offset

If zero or positive, the search is performed left to right skipping the first offset bytes of the haystack.

If negative, the search is performed right to left skipping the last offset bytes of the haystack and searching for the first occurrence of needle.

Note:

This is effectively looking for the last occurrence of needle before the last offset bytes.

Return Values

Returns the position where the needle exists relative to the beginning of the haystack string (independent of search direction or offset).

Note: String positions start at 0, and not 1.

Returns FALSE if the needle was not found.

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 Checking if a needle is in the haystack

It is easy to mistake the return values for "character found at position 0" and "character not found". Here's how to detect the difference:

<?php

$pos = strrpos($mystring, "b");
if ($pos === false) { // note: three equal signs
    // not found...
}

?>

Example #2 Searching with offsets

<?php
$foo = "0123456789a123456789b123456789c";

// Looking for '0' from the 0th byte (from the beginning)
var_dump(strrpos($foo, '0', 0));

// Looking for '0' from the 1st byte (after byte "0")
var_dump(strrpos($foo, '0', 1));

// Looking for '7' from the 21th byte (after byte 20)
var_dump(strrpos($foo, '7', 20));

// Looking for '7' from the 29th byte (after byte 28)
var_dump(strrpos($foo, '7', 28));

// Looking for '7' right to left from the 5th byte from the end
var_dump(strrpos($foo, '7', -5));

// Looking for 'c' right to left from the 2nd byte from the end
var_dump(strrpos($foo, 'c', -2));

// Looking for '9c' right to left from the 2nd byte from the end
var_dump(strrpos($foo, '9c', -2));
?>

The above example will output:

int(0)
bool(false)
int(27)
bool(false)
int(17)
bool(false)
int(29)

See Also

  • strpos() - Find the position of the first occurrence of a substring in a string
  • stripos() - Find the position of the first occurrence of a case-insensitive substring in a string
  • strripos() - Find the position of the last occurrence of a case-insensitive substring in a string
  • strrchr() - Find the last occurrence of a character in a string
  • substr() - Return part of a string


Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask

  • « strrpos
  • strstr »
  • PHP Manual
  • String Functions
  • Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask

strspn

(PHP 4, PHP 5, PHP 7)

strspn — Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask

Description

strspn ( string $subject , string $mask [, int $start [, int $length ]] ) : int

Finds the length of the initial segment of subject that contains only characters from mask.

If start and length are omitted, then all of subject will be examined. If they are included, then the effect will be the same as calling strspn(substr($subject, $start, $length), $mask) (see substr for more information).

The line of code:

<?php
$var = strspn("42 is the answer to the 128th question.", "1234567890");
?>
will assign 2 to $var, because the string "42" is the initial segment of subject that consists only of characters contained within "1234567890".

Parameters

subject

The string to examine.

mask

The list of allowable characters.

start

The position in subject to start searching.

If start is given and is non-negative, then strspn() will begin examining subject at the start'th position. 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 given and is negative, then strspn() will begin examining subject at the start'th position from the end of subject.

length

The length of the segment from subject to examine.

If length is given and is non-negative, then subject will be examined for length characters after the starting position.

If length is given and is negative, then subject will be examined from the starting position up to length characters from the end of subject.

Return Values

Returns the length of the initial segment of subject which consists entirely of characters in mask.

Note:

When a start parameter is set, the returned length is counted starting from this position, not from the beginning of subject.

Examples

Example #1 strspn() example

<?php
// subject does not start with any characters from mask
var_dump(strspn("foo", "o"));

// examine two characters from subject starting at offset 1
var_dump(strspn("foo", "o", 1, 2));

// examine one character from subject starting at offset 1
var_dump(strspn("foo", "o", 1, 1));
?>

The above example will output:

int(0)
int(2)
int(1)

Notes

Note: This function is binary-safe.

See Also

  • strcspn() - Find length of initial segment not matching mask


Find the first occurrence of a string

  • « strspn
  • strtok »
  • PHP Manual
  • String Functions
  • Find the first occurrence of a string

strstr

(PHP 4, PHP 5, PHP 7)

strstr — Find the first occurrence of a string

Description

strstr ( string $haystack , mixed $needle [, bool $before_needle = FALSE ] ) : string

Returns part of haystack string starting from and including the first occurrence of needle to the end of haystack.

Note:

This function is case-sensitive. For case-insensitive searches, use stristr().

Note:

If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos() instead.

Parameters

haystack

The input string.

needle

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. This behavior is deprecated as of PHP 7.3.0, and relying on it is highly discouraged. Depending on the intended behavior, the needle should either be explicitly cast to string, or an explicit call to chr() should be performed.

before_needle

If TRUE, strstr() returns the part of the haystack before the first occurrence of the needle (excluding the needle).

Return Values

Returns the portion of string, or FALSE if needle is not found.

Changelog

Version | Description
5.3.0 | Added the optional parameter before_needle.

Examples

Example #1 strstr() example

<?php
$email  = 'name@example.com';
$domain = strstr($email, '@');
echo $domain; // prints @example.com

$user = strstr($email, '@', true); // As of PHP 5.3.0
echo $user; // prints name
?>

See Also

  • stristr() - Case-insensitive strstr
  • strrchr() - Find the last occurrence of a character in a string
  • strpos() - Find the position of the first occurrence of a substring in a string
  • strpbrk() - Search a string for any of a set of characters
  • preg_match() - Perform a regular expression match


Tokenize string

  • « strstr
  • strtolower »
  • PHP Manual
  • String Functions
  • Tokenize string

strtok

(PHP 4, PHP 5, PHP 7)

strtok — Tokenize string

Description

strtok ( string $str , string $token ) : string
strtok ( string $token ) : string

strtok() splits a string (str) into smaller strings (tokens), with each token being delimited by any character from token. That is, if you have a string like "This is an example string" you could tokenize this string into its individual words by using the space character as the token.

Note that only the first call to strtok uses the string argument. Every subsequent call to strtok only needs the token to use, as it keeps track of where it is in the current string. To start over, or to tokenize a new string you simply call strtok with the string argument again to initialize it. Note that you may put multiple tokens in the token parameter. The string will be tokenized when any one of the characters in the argument is found.

Parameters

str

The string being split up into smaller strings (tokens).

token

The delimiter used when splitting up str.

Return Values

A string token.

Examples

Example #1 strtok() example

<?php
$string = "This is\tan example\nstring";
/* Use tab and newline as tokenizing characters as well  */
$tok = strtok($string, " \n\t");

while ($tok !== false) {
    echo "Word=$tok<br />";
    $tok = strtok(" \n\t");
}
?>

Example #2 strtok() behavior on empty part found

<?php
$first_token  = strtok('/something', '/');
$second_token = strtok('/');
var_dump($first_token, $second_token);
?>

The above example will output:

    string(9) "something"
    bool(false)

Notes

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.

See Also

  • split() - Split string into array by regular expression
  • explode() - Split a string by a string


Make a string lowercase

  • « strtok
  • strtoupper »
  • PHP Manual
  • String Functions
  • Make a string lowercase

strtolower

(PHP 4, PHP 5, PHP 7)

strtolower — Make a string lowercase

Description

strtolower ( string $string ) : string

Returns string with all alphabetic characters converted to lowercase.

Note that 'alphabetic' is determined by the current locale. This means that e.g. in the default "C" locale, characters such as umlaut-A (Ä) will not be converted.

Parameters

string

The input string.

Return Values

Returns the lowercased string.

Examples

Example #1 strtolower() example

<?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = strtolower($str);
echo $str; // Prints mary had a little lamb and she loved it so
?>

Notes

Note: This function is binary-safe.

See Also

  • 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_strtolower() - Make a string lowercase


Make a string uppercase

  • « strtolower
  • strtr »
  • PHP Manual
  • String Functions
  • Make a string uppercase

strtoupper

(PHP 4, PHP 5, PHP 7)

strtoupper — Make a string uppercase

Description

strtoupper ( string $string ) : string

Returns string with all alphabetic characters converted to uppercase.

Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a (ä) will not be converted.

Parameters

string

The input string.

Return Values

Returns the uppercased string.

Examples

Example #1 strtoupper() example

<?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = strtoupper($str);
echo $str; // Prints MARY HAD A LITTLE LAMB AND SHE LOVED IT SO
?>

Notes

Note: This function is binary-safe.

See Also

  • strtolower() - Make a string lowercase
  • ucfirst() - Make a string's first character uppercase
  • ucwords() - Uppercase the first character of each word in a string
  • mb_strtoupper() - Make a string uppercase


Translate characters or replace substrings

  • « strtoupper
  • substr_compare »
  • PHP Manual
  • String Functions
  • Translate characters or replace substrings

strtr

(PHP 4, PHP 5, PHP 7)

strtr — Translate characters or replace substrings

Description

strtr ( string $str , string $from , string $to ) : string
strtr ( string $str , array $replace_pairs ) : string

If given three arguments, this function returns a copy of str where all occurrences of each (single-byte) character in from have been translated to the corresponding character in to, i.e., every occurrence of $from[$n] has been replaced with $to[$n], where $n is a valid offset in both arguments.

If from and to have different lengths, the extra characters in the longer of the two are ignored. The length of str will be the same as the return value's.

If given two arguments, the second should be an array in the form array('from' => 'to', ...). The return value is a string where all the occurrences of the array keys have been replaced by the corresponding values. The longest keys will be tried first. Once a substring has been replaced, its new value will not be searched again.

In this case, the keys and the values may have any length, provided that there is no empty key; additionally, the length of the return value may differ from that of str. However, this function will be the most efficient when all the keys have the same size.

Parameters

str

The string being translated.

from

The string being translated to to.

to

The string replacing from.

replace_pairs

The replace_pairs parameter may be used instead of to and from, in which case it's an array in the form array('from' => 'to', ...).

Return Values

Returns the translated string.

If replace_pairs contains a key which is an empty string (""), FALSE will be returned. If the str is not a scalar then it is not typecasted into a string, instead a warning is raised and NULL is returned.

Examples

Example #1 strtr() example

<?php
//In this form, strtr() does byte-by-byte translation
//Therefore, we are assuming a single-byte encoding here:
$addr = strtr($addr, "äåö", "aao");
?>

The next example shows the behavior of strtr() when called with only two arguments. Note the preference of the replacements ("h" is not picked because there are longer matches) and how replaced text was not searched again.

Example #2 strtr() example with two arguments

<?php
$trans = array("h" => "-", "hello" => "hi", "hi" => "hello");
echo strtr("hi all, I said hello", $trans);
?>

The above example will output:

hello all, I said hi

The two modes of behavior are substantially different. With three arguments, strtr() will replace bytes; with two, it may replace longer substrings.

Example #3 strtr() behavior comparison

<?php
echo strtr("baab", "ab", "01"),"\n";

$trans = array("ab" => "01");
echo strtr("baab", $trans);
?>

The above example will output:

1001
ba01

See Also

  • str_replace() - Replace all occurrences of the search string with the replacement string
  • preg_replace() - Perform a regular expression search and replace


Binary safe comparison of two strings from an offset, up to length characters

  • « strtr
  • substr_count »
  • PHP Manual
  • String Functions
  • Binary safe comparison of two strings from an offset, up to length characters

substr_compare

(PHP 5, PHP 7)

substr_compare — Binary safe comparison of two strings from an offset, up to length characters

Description

substr_compare ( string $main_str , string $str , int $offset [, int $length [, bool $case_insensitivity = FALSE ]] ) : int

substr_compare() compares main_str from position offset with str up to length characters.

Parameters

main_str

The main string being compared.

str

The secondary string being compared.

offset

The start position for the comparison. If negative, it starts counting from the end of the string.

length

The length of the comparison. The default value is the largest of the length of the str compared to the length of main_str minus the offset.

case_insensitivity

If case_insensitivity is TRUE, comparison is case insensitive.

Return Values

Returns < 0 if main_str from position offset is less than str, > 0 if it is greater than str, and 0 if they are equal. If offset is equal to (prior to PHP 7.2.18, 7.3.5) or greater than the length of main_str, or the length is set and is less than 0, (or, prior to PHP 5.5.11, less than 1) substr_compare() prints a warning and returns FALSE.

Changelog

Version | Description
7.2.18, 7.3.5 | offset may now be equal to the length of main_str.
5.5.11 | length may now be 0.
5.1.0 | Added the possibility to use a negative offset.

Examples

Example #1 A substr_compare() example

<?php
echo substr_compare("abcde", "bc", 1, 2); // 0
echo substr_compare("abcde", "de", -2, 2); // 0
echo substr_compare("abcde", "bcg", 1, 2); // 0
echo substr_compare("abcde", "BC", 1, 2, true); // 0
echo substr_compare("abcde", "bc", 1, 3); // 1
echo substr_compare("abcde", "cd", 1, 2); // -1
echo substr_compare("abcde", "abc", 5, 1); // warning
?>

See Also

  • strncmp() - Binary safe string comparison of the first n characters


Count the number of substring occurrences

  • « substr_compare
  • substr_replace »
  • PHP Manual
  • String Functions
  • Count the number of substring occurrences

substr_count

(PHP 4, PHP 5, PHP 7)

substr_count — Count the number of substring occurrences

Description

substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] ) : int

substr_count() returns the number of times the needle substring occurs in the haystack string. Please note that needle is case sensitive.

Note:

This function doesn't count overlapped substrings. See the example below!

Parameters

haystack

The string to search in

needle

The substring to search for

offset

The offset where to start counting. If the offset is negative, counting starts from the end of the string.

length

The maximum length after the specified offset to search for the substring. It outputs a warning if the offset plus the length is greater than the haystack length. A negative length counts from the end of haystack.

Return Values

This function returns an integer.

Changelog

Version | Description
7.1.0 | Support for negative offsets and lengths has been added. length may also be 0 now.
5.1.0 | Added the offset and the length parameters

Examples

Example #1 A substr_count() example

<?php
$text = 'This is a test';
echo strlen($text); // 14

echo substr_count($text, 'is'); // 2

// the string is reduced to 's is a test', so it prints 1
echo substr_count($text, 'is', 3);

// the text is reduced to 's i', so it prints 0
echo substr_count($text, 'is', 3, 3);

// generates a warning because 5+10 > 14
echo substr_count($text, 'is', 5, 10);

// prints only 1, because it doesn't count overlapped substrings
$text2 = 'gcdgcdgcd';
echo substr_count($text2, 'gcdgcd');
?>

See Also

  • count_chars() - Return information about characters used in a string
  • strpos() - Find the position of the first occurrence of a substring in a string
  • substr() - Return part of a string
  • strstr() - Find the first occurrence of a string


Replace text within a portion of a string

  • « substr_count
  • substr »
  • PHP Manual
  • String Functions
  • Replace text within a portion of a string

substr_replace

(PHP 4, PHP 5, PHP 7)

substr_replace — Replace text within a portion of a string

Description

substr_replace ( mixed $string , mixed $replacement , mixed $start [, mixed $length ] ) : mixed

substr_replace() replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement.

Parameters

string

The input string.

An array of strings can be provided, in which case the replacements will occur on each string in turn. In this case, the replacement, start and length parameters may be provided either as scalar values to be applied to each input string in turn, or as arrays, in which case the corresponding array element will be used for each input string.

replacement

The replacement string.

start

If start is non-negative, the replacing will begin at the start'th offset into string.

If start is negative, the replacing will begin at the start'th character from the end of string.

length

If given and is positive, it represents the length of the portion of string which is to be replaced. If it is negative, it represents the number of characters from the end of string at which to stop replacing. If it is not given, then it will default to strlen( string ); i.e. end the replacing at the end of string. Of course, if length is zero then this function will have the effect of inserting replacement into string at the given start offset.

Return Values

The result string is returned. If string is an array then array is returned.

Examples

Example #1 Simple substr_replace() examples

<?php
$var = 'ABCDEFGH:/MNRPQR/';
echo "Original: $var<hr />\n";

/* These two examples replace all of $var with 'bob'. */
echo substr_replace($var, 'bob', 0) . "<br />\n";
echo substr_replace($var, 'bob', 0, strlen($var)) . "<br />\n";

/* Insert 'bob' right at the beginning of $var. */
echo substr_replace($var, 'bob', 0, 0) . "<br />\n";

/* These next two replace 'MNRPQR' in $var with 'bob'. */
echo substr_replace($var, 'bob', 10, -1) . "<br />\n";
echo substr_replace($var, 'bob', -7, -1) . "<br />\n";

/* Delete 'MNRPQR' from $var. */
echo substr_replace($var, '', 10, -1) . "<br />\n";
?>

Example #2 Using substr_replace() to replace multiple strings at once

<?php
$input = array('A: XXX', 'B: XXX', 'C: XXX');

// A simple case: replace XXX in each string with YYY.
echo implode('; ', substr_replace($input, 'YYY', 3, 3))."\n";

// A more complicated case where each replacement is different.
$replace = array('AAA', 'BBB', 'CCC');
echo implode('; ', substr_replace($input, $replace, 3, 3))."\n";

// Replace a different number of characters each time.
$length = array(1, 2, 3);
echo implode('; ', substr_replace($input, $replace, 3, $length))."\n";
?>

The above example will output:

A: YYY; B: YYY; C: YYY
A: AAA; B: BBB; C: CCC
A: AAAXX; B: BBBX; C: CCC

Notes

Note: This function is binary-safe.

See Also

  • str_replace() - Replace all occurrences of the search string with the replacement string
  • substr() - Return part of a string
  • String access and modification by character


Return part of a string

  • « substr_replace
  • trim »
  • PHP Manual
  • String Functions
  • Return part of a string

substr

(PHP 4, PHP 5, PHP 7)

substr — Return part of a string

Description

substr ( string $string , int $start [, int $length ] ) : string

Returns the portion of string specified by the start and length parameters.

Parameters

string

The input string.

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.

If string is less than start characters long, FALSE will be returned.

Example #1 Using a negative start

<?php
$rest = substr("abcdef", -1);    // returns "f"
$rest = substr("abcdef", -2);    // returns "ef"
$rest = substr("abcdef", -3, 1); // returns "d"
?>

length

If length is given and is positive, the string returned will contain at most length characters beginning from start (depending on the length of string).

If length is given and is negative, then that many characters will be omitted from the end of string (after the start position has been calculated when a start is negative). If start denotes the position of this truncation or beyond, FALSE will be returned.

If length is given and is 0, FALSE or NULL, an empty string will be returned.

If length is omitted, the substring starting from start until the end of the string will be returned.

Example #2 Using a negative length

<?php
$rest = substr("abcdef", 0, -1);  // returns "abcde"
$rest = substr("abcdef", 2, -1);  // returns "cde"
$rest = substr("abcdef", 4, -4);  // returns false
$rest = substr("abcdef", -3, -1); // returns "de"
?>

Return Values

Returns the extracted part of string; or FALSE on failure, or an empty string.

Changelog

Version | Description
7.0.0 | If string is equal to start characters long, an empty string will be returned. Prior to this version, FALSE was returned in this case.
5.2.2 - 5.2.6 | If the start parameter indicates the position of a negative truncation or beyond, false is returned. Other versions get the string from start.

Examples

Example #3 Basic substr() usage

<?php
echo substr('abcdef', 1);     // bcdef
echo substr('abcdef', 1, 3);  // bcd
echo substr('abcdef', 0, 4);  // abcd
echo substr('abcdef', 0, 8);  // abcdef
echo substr('abcdef', -1, 1); // f

// Accessing single characters in a string
// can also be achieved using "square brackets"
$string = 'abcdef';
echo $string[0];                 // a
echo $string[3];                 // d
echo $string[strlen($string)-1]; // f

?>

Example #4 substr() casting behaviour

<?php
class apple {
    public function __toString() {
        return "green";
    }
}

echo "1) ".var_export(substr("pear", 0, 2), true).PHP_EOL;
echo "2) ".var_export(substr(54321, 0, 2), true).PHP_EOL;
echo "3) ".var_export(substr(new apple(), 0, 2), true).PHP_EOL;
echo "4) ".var_export(substr(true, 0, 1), true).PHP_EOL;
echo "5) ".var_export(substr(false, 0, 1), true).PHP_EOL;
echo "6) ".var_export(substr("", 0, 1), true).PHP_EOL;
echo "7) ".var_export(substr(1.2e3, 0, 4), true).PHP_EOL;
?>

Output of the above example in PHP 7:

1) 'pe'
2) '54'
3) 'gr'
4) '1'
5) ''
6) ''
7) '1200'

Output of the above example in PHP 5:

1) 'pe'
2) '54'
3) 'gr'
4) '1'
5) false
6) false
7) '1200'

Errors/Exceptions

Returns FALSE on error.

<?php
var_dump(substr('a', 2)); // bool(false)
?>

See Also

  • strrchr() - Find the last occurrence of a character in a string
  • substr_replace() - Replace text within a portion of a string
  • preg_match() - Perform a regular expression match
  • trim() - Strip whitespace (or other characters) from the beginning and end of a string
  • mb_substr() - Get part of string
  • wordwrap() - Wraps a string to a given number of characters
  • String access and modification by character


Strip whitespace (or other characters) from the beginning and end of a string

  • « substr
  • ucfirst »
  • PHP Manual
  • String Functions
  • Strip whitespace (or other characters) from the beginning and end of a string

trim

(PHP 4, PHP 5, PHP 7)

trim — Strip whitespace (or other characters) from the beginning and end of a string

Description

trim ( string $str [, string $character_mask = " \t\n\r\0\x0B" ] ) : string

This function returns a string with whitespace stripped from the beginning and end of str. Without the second parameter, trim() will strip these characters:

  • " " (ASCII 32 (0x20)), an ordinary space.
  • "\t" (ASCII 9 (0x09)), a tab.
  • "\n" (ASCII 10 (0x0A)), a new line (line feed).
  • "\r" (ASCII 13 (0x0D)), a carriage return.
  • "\0" (ASCII 0 (0x00)), the NUL-byte.
  • "\x0B" (ASCII 11 (0x0B)), a vertical tab.

Parameters

str

The string that will be trimmed.

character_mask

Optionally, the stripped characters can also be specified using the character_mask parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

Return Values

The trimmed string.

Examples

Example #1 Usage example of trim()

<?php

$text   = "\t\tThese are a few words :) ...  ";
$binary = "\x09Example string\x0A";
$hello  = "Hello World";
var_dump($text, $binary, $hello);

print "\n";

$trimmed = trim($text);
var_dump($trimmed);

$trimmed = trim($text, " \t.");
var_dump($trimmed);

$trimmed = trim($hello, "Hdle");
var_dump($trimmed);

$trimmed = trim($hello, 'HdWr');
var_dump($trimmed);

// trim the ASCII control characters at the beginning and end of $binary
// (from 0 to 31 inclusive)
$clean = trim($binary, "\x00..\x1F");
var_dump($clean);

?>

The above example will output:

string(32) "        These are a few words :) ...  "
string(16) "    Example string
"
string(11) "Hello World"

string(28) "These are a few words :) ..."
string(24) "These are a few words :)"
string(5) "o Wor"
string(9) "ello Worl"
string(14) "Example string"

Example #2 Trimming array values with trim()

<?php
function trim_value(&$value)
{
    $value = trim($value);
}

$fruit = array('apple','banana ', ' cranberry ');
var_dump($fruit);

array_walk($fruit, 'trim_value');
var_dump($fruit);

?>

The above example will output:

array(3) {
  [0]=>
  string(5) "apple"
  [1]=>
  string(7) "banana "
  [2]=>
  string(11) " cranberry "
}
array(3) {
  [0]=>
  string(5) "apple"
  [1]=>
  string(6) "banana"
  [2]=>
  string(9) "cranberry"
}

Notes

Note: Possible gotcha: removing middle characters

Because trim() trims characters from the beginning and end of a string, it may be confusing when characters are (or are not) removed from the middle. trim('abc', 'bad') removes both 'a' and 'b' because it trims 'a' thus moving 'b' to the beginning to also be trimmed. So, this is why it "works" whereas trim('abc', 'b') seemingly does not.

See Also

  • ltrim() - Strip whitespace (or other characters) from the beginning of a string
  • rtrim() - Strip whitespace (or other characters) from the end of a string
  • str_replace() - Replace all occurrences of the search string with the replacement string


Make a string's first character uppercase

  • « trim
  • ucwords »
  • PHP Manual
  • String Functions
  • Make a string's first character uppercase

ucfirst

(PHP 4, PHP 5, PHP 7)

ucfirst — Make a string's first character uppercase

Description

ucfirst ( string $str ) : string

Returns a string with the first character of str capitalized, if that character is alphabetic.

Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a (ä) will not be converted.

Parameters

str

The input string.

Return Values

Returns the resulting string.

Examples

Example #1 ucfirst() example

<?php
$foo = 'hello world!';
$foo = ucfirst($foo);             // Hello world!

$bar = 'HELLO WORLD!';
$bar = ucfirst($bar);             // HELLO WORLD!
$bar = ucfirst(strtolower($bar)); // Hello world!
?>

See Also

  • lcfirst() - Make a string's first character lowercase
  • strtolower() - Make a string lowercase
  • strtoupper() - Make a string uppercase
  • ucwords() - Uppercase the first character of each word in a string


Uppercase the first character of each word in a string

  • « ucfirst
  • vfprintf »
  • PHP Manual
  • String Functions
  • Uppercase the first character of each word in a string

ucwords

(PHP 4, PHP 5, PHP 7)

ucwords — Uppercase the first character of each word in a string

Description

ucwords ( string $str [, string $delimiters = " \t\r\n\f\v" ] ) : string

Returns a string with the first character of each word in str capitalized, if that character is alphabetic.

The definition of a word is any string of characters that is immediately after any character listed in the delimiters parameter (By default these are: space, form-feed, newline, carriage return, horizontal tab, and vertical tab).

Parameters

str

The input string.

delimiters

The optional delimiters contains the word separator characters.

Return Values

Returns the modified string.

Changelog

Version | Description
5.4.32, 5.5.16 | Added the delimiters parameter.

Examples

Example #1 ucwords() example

<?php
$foo = 'hello world!';
$foo = ucwords($foo);             // Hello World!

$bar = 'HELLO WORLD!';
$bar = ucwords($bar);             // HELLO WORLD!
$bar = ucwords(strtolower($bar)); // Hello World!
?>

Example #2 ucwords() example with custom delimiter

<?php
$foo = 'hello|world!';
$bar = ucwords($foo);             // Hello|world!

$baz = ucwords($foo, "|");        // Hello|World!
?>

Notes

Note: This function is binary-safe.

See Also

  • strtoupper() - Make a string uppercase
  • strtolower() - Make a string lowercase
  • ucfirst() - Make a string's first character uppercase
  • mb_convert_case() - Perform case folding on a string


Write a formatted string to a stream

  • « ucwords
  • vprintf »
  • PHP Manual
  • String Functions
  • Write a formatted string to a stream

vfprintf

(PHP 5, PHP 7)

vfprintf — Write a formatted string to a stream

Description

vfprintf ( resource $handle , string $format , array $args ) : int

Write a string produced according to format to the stream resource specified by handle.

Operates as fprintf() but accepts an array of arguments, rather than a variable number of arguments.

Parameters

handle

format

The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result and conversion specifications, each of which results in fetching its own parameter.

A conversion specification follows this prototype: %[argnum$][flags][width][.precision]specifier.

Argnum

An integer followed by a dollar sign $, to specify which number argument to treat in the conversion.

Flags
Flag | Description
- Left-justify within the given field width; Right justification is the default
+ Prefix positive numbers with a plus sign +; Default only negative are prefixed with a negative sign.
(space) | Pads the result with spaces. This is the default.
0 | Only left-pads numbers with zeros. With s specifiers this can also right-pad with zeros.
'(char) | Pads the result with the character (char).

Width

An integer that says how many characters (minimum) this conversion should result in.

Precision

A period . followed by an integer who's meaning depends on the specifier:

  • For e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
  • For g and G specifiers: this is the maximum number of significant digits to be printed.
  • For s specifier: it acts as a cutoff point, setting a maximum character limit to the string.

Note: If the period is specified without an explicit value for precision, 0 is assumed.

Note: Attempting to use a position specifier greater than PHP_INT_MAX will generate warnings.

Specifiers
Specifier | Description
% A literal percent character. No argument is required.
b | The argument is treated as an integer and presented as a binary number.
c | The argument is treated as an integer and presented as the character with that ASCII.
d | The argument is treated as an integer and presented as a (signed) decimal number.
e | The argument is treated as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point since PHP 5.2.1. In earlier versions, it was taken as number of significant digits (one less).
E | Like the e specifier but uses uppercase letter (e.g. 1.2E+2).
f | The argument is treated as a float and presented as a floating-point number (locale aware).
F | The argument is treated as a float and presented as a floating-point number (non-locale aware). Available as of PHP 5.0.3.
g

General format.

Let P equal the precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero. Then, if a conversion with style E would have an exponent of X:

If P > X ≥ −4, the conversion is with style f and precision P − (X + 1). Otherwise, the conversion is with style e and precision P − 1.

G | Like the g specifier but uses E and F.
o | The argument is treated as an integer and presented as an octal number.
s | The argument is treated and presented as a string.
u | The argument is treated as an integer and presented as an unsigned decimal number.
x | The argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).
X | The argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).

Warning

The c type specifier ignores padding and width

Warning

Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results

Variables will be co-erced to a suitable type for the specifier:

Type Handling
Type | Specifiers
string | s
integer | d, u, c, o, x, X, b
double | g, G, e, E, f, F

args

Return Values

Returns the length of the outputted string.

Examples

Example #1 vfprintf(): zero-padded integers

<?php
if (!($fp = fopen('date.txt', 'w')))
    return;

vfprintf($fp, "%04d-%02d-%02d", array($year, $month, $day));
// will write the formatted ISO date to date.txt
?>

See Also

  • printf() - Output a formatted string
  • sprintf() - Return a formatted string
  • fprintf() - Write a formatted string to a stream
  • vprintf() - Output a formatted string
  • vsprintf() - Return a formatted string
  • sscanf() - Parses input from a string according to a format
  • fscanf() - Parses input from a file according to a format
  • number_format() - Format a number with grouped thousands
  • date() - Format a local time/date


Output a formatted string

  • « vfprintf
  • vsprintf »
  • PHP Manual
  • String Functions
  • Output a formatted string

vprintf

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

vprintf — Output a formatted string

Description

vprintf ( string $format , array $args ) : int

Display array values as a formatted string according to format (which is described in the documentation for sprintf()).

Operates as printf() but accepts an array of arguments, rather than a variable number of arguments.

Parameters

format

The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result and conversion specifications, each of which results in fetching its own parameter.

A conversion specification follows this prototype: %[argnum$][flags][width][.precision]specifier.

Argnum

An integer followed by a dollar sign $, to specify which number argument to treat in the conversion.

Flags
Flag | Description
- Left-justify within the given field width; Right justification is the default
+ Prefix positive numbers with a plus sign +; Default only negative are prefixed with a negative sign.
(space) | Pads the result with spaces. This is the default.
0 | Only left-pads numbers with zeros. With s specifiers this can also right-pad with zeros.
'(char) | Pads the result with the character (char).

Width

An integer that says how many characters (minimum) this conversion should result in.

Precision

A period . followed by an integer who's meaning depends on the specifier:

  • For e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
  • For g and G specifiers: this is the maximum number of significant digits to be printed.
  • For s specifier: it acts as a cutoff point, setting a maximum character limit to the string.

Note: If the period is specified without an explicit value for precision, 0 is assumed.

Note: Attempting to use a position specifier greater than PHP_INT_MAX will generate warnings.

Specifiers
Specifier | Description
% A literal percent character. No argument is required.
b | The argument is treated as an integer and presented as a binary number.
c | The argument is treated as an integer and presented as the character with that ASCII.
d | The argument is treated as an integer and presented as a (signed) decimal number.
e | The argument is treated as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point since PHP 5.2.1. In earlier versions, it was taken as number of significant digits (one less).
E | Like the e specifier but uses uppercase letter (e.g. 1.2E+2).
f | The argument is treated as a float and presented as a floating-point number (locale aware).
F | The argument is treated as a float and presented as a floating-point number (non-locale aware). Available as of PHP 5.0.3.
g

General format.

Let P equal the precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero. Then, if a conversion with style E would have an exponent of X:

If P > X ≥ −4, the conversion is with style f and precision P − (X + 1). Otherwise, the conversion is with style e and precision P − 1.

G | Like the g specifier but uses E and F.
o | The argument is treated as an integer and presented as an octal number.
s | The argument is treated and presented as a string.
u | The argument is treated as an integer and presented as an unsigned decimal number.
x | The argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).
X | The argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).

Warning

The c type specifier ignores padding and width

Warning

Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results

Variables will be co-erced to a suitable type for the specifier:

Type Handling
Type | Specifiers
string | s
integer | d, u, c, o, x, X, b
double | g, G, e, E, f, F

args

Return Values

Returns the length of the outputted string.

Examples

Example #1 vprintf(): zero-padded integers

<?php
vprintf("%04d-%02d-%02d", explode('-', '1988-8-1'));
?>

The above example will output:

1988-08-01

See Also

  • printf() - Output a formatted string
  • sprintf() - Return a formatted string
  • fprintf() - Write a formatted string to a stream
  • vsprintf() - Return a formatted string
  • vfprintf() - Write a formatted string to a stream
  • sscanf() - Parses input from a string according to a format
  • fscanf() - Parses input from a file according to a format
  • number_format() - Format a number with grouped thousands
  • date() - Format a local time/date


Return a formatted string

  • « vprintf
  • wordwrap »
  • PHP Manual
  • String Functions
  • Return a formatted string

vsprintf

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

vsprintf — Return a formatted string

Description

vsprintf ( string $format , array $args ) : string

Operates as sprintf() but accepts an array of arguments, rather than a variable number of arguments.

Parameters

format

The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result and conversion specifications, each of which results in fetching its own parameter.

A conversion specification follows this prototype: %[argnum$][flags][width][.precision]specifier.

Argnum

An integer followed by a dollar sign $, to specify which number argument to treat in the conversion.

Flags
Flag | Description
- Left-justify within the given field width; Right justification is the default
+ Prefix positive numbers with a plus sign +; Default only negative are prefixed with a negative sign.
(space) | Pads the result with spaces. This is the default.
0 | Only left-pads numbers with zeros. With s specifiers this can also right-pad with zeros.
'(char) | Pads the result with the character (char).

Width

An integer that says how many characters (minimum) this conversion should result in.

Precision

A period . followed by an integer who's meaning depends on the specifier:

  • For e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
  • For g and G specifiers: this is the maximum number of significant digits to be printed.
  • For s specifier: it acts as a cutoff point, setting a maximum character limit to the string.

Note: If the period is specified without an explicit value for precision, 0 is assumed.

Note: Attempting to use a position specifier greater than PHP_INT_MAX will generate warnings.

Specifiers
Specifier | Description
% A literal percent character. No argument is required.
b | The argument is treated as an integer and presented as a binary number.
c | The argument is treated as an integer and presented as the character with that ASCII.
d | The argument is treated as an integer and presented as a (signed) decimal number.
e | The argument is treated as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point since PHP 5.2.1. In earlier versions, it was taken as number of significant digits (one less).
E | Like the e specifier but uses uppercase letter (e.g. 1.2E+2).
f | The argument is treated as a float and presented as a floating-point number (locale aware).
F | The argument is treated as a float and presented as a floating-point number (non-locale aware). Available as of PHP 5.0.3.
g

General format.

Let P equal the precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero. Then, if a conversion with style E would have an exponent of X:

If P > X ≥ −4, the conversion is with style f and precision P − (X + 1). Otherwise, the conversion is with style e and precision P − 1.

G | Like the g specifier but uses E and F.
o | The argument is treated as an integer and presented as an octal number.
s | The argument is treated and presented as a string.
u | The argument is treated as an integer and presented as an unsigned decimal number.
x | The argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).
X | The argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).

Warning

The c type specifier ignores padding and width

Warning

Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results

Variables will be co-erced to a suitable type for the specifier:

Type Handling
Type | Specifiers
string | s
integer | d, u, c, o, x, X, b
double | g, G, e, E, f, F

args

Return Values

Return array values as a formatted string according to format, or FALSE on failure.

Examples

Example #1 vsprintf(): zero-padded integers

<?php
print vsprintf("%04d-%02d-%02d", explode('-', '1988-8-1'));
?>

The above example will output:

1988-08-01

See Also

  • printf() - Output a formatted string
  • sprintf() - Return a formatted string
  • fprintf() - Write a formatted string to a stream
  • vprintf() - Output a formatted string
  • vfprintf() - Write a formatted string to a stream
  • sscanf() - Parses input from a string according to a format
  • fscanf() - Parses input from a file according to a format
  • number_format() - Format a number with grouped thousands
  • date() - Format a local time/date


Wraps a string to a given number of characters

  • « vsprintf
  • Changelog »
  • PHP Manual
  • String Functions
  • Wraps a string to a given number of characters

wordwrap

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

wordwrap — Wraps a string to a given number of characters

Description

wordwrap ( string $str [, int $width = 75 [, string $break = "\n" [, bool $cut = FALSE ]]] ) : string

Wraps a string to a given number of characters using a string break character.

Parameters

str

The input string.

width

The number of characters at which the string will be wrapped.

break

The line is broken using the optional break parameter.

cut

If the cut is set to TRUE, the string is always wrapped at or before the specified width. So if you have a word that is larger than the given width, it is broken apart. (See second example). When FALSE the function does not split the word even if the width is smaller than the word width.

Return Values

Returns the given string wrapped at the specified length.

Examples

Example #1 wordwrap() example

<?php
$text = "The quick brown fox jumped over the lazy dog.";
$newtext = wordwrap($text, 20, "<br />\n");

echo $newtext;
?>

The above example will output:

The quick brown fox<br />
jumped over the lazy<br />
dog.

Example #2 wordwrap() example

<?php
$text = "A very long woooooooooooord.";
$newtext = wordwrap($text, 8, "\n", true);

echo "$newtext\n";
?>

The above example will output:

A very
long
wooooooo
ooooord.

Example #3 wordwrap() example

<?php
$text = "A very long woooooooooooooooooord. and something";
$newtext = wordwrap($text, 8, "\n", false);

echo "$newtext\n";
?>

The above example will output:

A very
long
woooooooooooooooooord.
and
something

See Also

  • nl2br() - Inserts HTML line breaks before all newlines in a string
  • chunk_split() - Split a string into smaller chunks


Changelog

The following changes have been made to classes/functions/methods of this extension.

Version | Function | Description
7.4.0 | implode | Passing the glue after the pieces (i.e. not using the documented order of parameters) has been deprecated.
 | str_getcsv | The escape parameter now interprets an empty string as signal to disable the proprietary escape mechanism. Formerly, an empty string was treated like the default parameter value.
7.2.18, 7.3.5 | substr_compare | offset may now be equal to the length of main_str.
7.2.0 | number_format | number_format was changed to not being able to return -0, previously -0 could be returned for cases like where number would be -0.01.
 | parse_str | Usage of parse_str without a second parameter now emits an E_DEPRECATED notice.
7.1.0 | str_shuffle | The internal randomization algorithm has been changed to use the Mersenne Twister Random Number Generator instead of the libc rand function.
 | stripos | Support for negative offsets has been added.
 | strpos | Support for negative offsets has been added.
 | substr_count | Support for negative offsets and lengths has been added. length may also be 0 now.
7.0.0 | setlocale | Support for the category parameter passed as a string has been removed. Only LC_* constants can be used as of this version.
 | substr | If string is equal to start characters long, an empty string will be returned. Prior to this version, FALSE was returned in this case.
5.6.5 | crypt | When the failure string "*0" is given as the salt, "*1" will now be returned for consistency with other crypt implementations. Prior to this version, PHP 5.6 would incorrectly return a DES hash.
5.6.0 | crypt | Raise E_NOTICE security warning if salt is omitted.
 | html_entity_decode | The default value for the encoding parameter was changed to be the value of the default_charset configuration option.
 | htmlentities | The default value for the encoding parameter was changed to be the value of the default_charset configuration option.
 | htmlspecialchars | The default value for the encoding parameter was changed to be the value of the default_charset configuration option.
5.5.21 | crypt | When the failure string "*0" is given as the salt, "*1" will now be returned for consistency with other crypt implementations. Prior to this version, PHP 5.5 (and earlier branches) would incorrectly return a DES hash.
5.5.11 | substr_compare | length may now be 0.
5.5.1 | hex2bin | A warning is thrown if the input string is invalid hexadecimal string.
5.4.32, 5.5.16 | ucwords | Added the delimiters parameter.
5.4.4 | hex2bin | A warning is thrown if the input string is of odd length. In PHP 5.4.0 the string was silently accepted, but the last byte was truncated.
5.4.0 | get_html_translation_table | The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
 | get_html_translation_table | The default value for the encoding parameter was changed to UTF-8.
 | html_entity_decode | Default encoding changed from ISO-8859-1 to UTF-8.
 | html_entity_decode | The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
 | htmlentities | The default value for the encoding parameter was changed to UTF-8.
 | htmlentities | The constants ENT_SUBSTITUTE, ENT_DISALLOWED, ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
 | htmlspecialchars | The default value for the encoding parameter was changed to UTF-8.
 | htmlspecialchars | The constants ENT_SUBSTITUTE, ENT_DISALLOWED, ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
 | htmlspecialchars_decode | The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
 | number_format | This function now supports multiple bytes in dec_point and thousands_sep. Only the first byte of each separator was used in older versions.
5.3.7 | crypt | Added $2x$ and $2y$ Blowfish modes to deal with potential high-bit attacks.
5.3.4 | get_html_translation_table | The encoding parameter was added.
 | strip_tags | strip_tags ignores self-closing XHTML tags in allowable_tags.
5.3.2 | crypt | Fixed Blowfish behaviour on invalid rounds to return "failure" string ("*0" or "*1"), instead of falling back to DES.
 | crypt | Added SHA-256 and SHA-512 crypt based on Ulrich Drepper's implementation.
5.3.0 | crypt | PHP now contains its own implementation for the MD5 crypt, Standard DES, Extended DES and the Blowfish algorithms and will use that if the system lacks of support for one or more of the algorithms.
 | htmlentities | The constant ENT_IGNORE was added.
 | htmlspecialchars | The constant ENT_IGNORE was added.
 | nl2br | Added the optional is_xhtml parameter. Before this version '<br />' was always inserted.
 | setlocale | This function now throws an E_DEPRECATED notice if a string is passed to the category parameter instead of one of the LC_* constants.
 | stristr | Added the optional parameter before_needle.
 | strlen | Prior versions treated arrays as the string Array, thus returning a string length of 5 and emitting an E_NOTICE level error.
 | strstr | Added the optional parameter before_needle.
5.2.5 | addcslashes | The escape sequences \v and \f were added.
5.2.3 | htmlentities | The double_encode parameter was added.
 | htmlspecialchars | The double_encode parameter was added.
5.2.2 - 5.2.6 | substr | If the start parameter indicates the position of a negative truncation or beyond, false is returned. Other versions get the string from start.
5.1.0 | explode | Support for negative limits was added
 | md5_file | Changed the function to use the streams API. It means that you can use it with wrappers, like md5_file('http://example.com/..')
 | sha1_file | Changed the function to use the streams API. It means that you can use it with wrappers, like sha1_file('http://example.com/..')
 | str_word_count | Added the charlist parameter
 | substr_compare | Added the possibility to use a negative offset.
 | substr_count | Added the offset and the length parameters


Variable and Type Related Extensions

  • Arrays
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Sorting Arrays
    • Array Functions
  • Classes/Objects — Class/Object Information
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Classes/Object Functions
  • Classkit
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Classkit Functions
  • Ctype — Character type checking
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Ctype Functions
  • Filter — Data Filtering
    • Introduction
    • Installing/Configuring
    • Types of filters
    • Predefined Constants
    • Examples
    • Filter Functions
  • Function Handling
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Function handling Functions
  • Quickhash
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • QuickHashIntSet — The QuickHashIntSet class
    • QuickHashIntHash — The QuickHashIntHash class
    • QuickHashStringIntHash — The QuickHashStringIntHash class
    • QuickHashIntStringHash — The QuickHashIntStringHash class
  • Reflection
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Extending
    • Reflection — The Reflection class
    • ReflectionClass — The ReflectionClass class
    • ReflectionClassConstant — The ReflectionClassConstant class
    • ReflectionZendExtension — The ReflectionZendExtension class
    • ReflectionExtension — The ReflectionExtension class
    • ReflectionFunction — The ReflectionFunction class
    • ReflectionFunctionAbstract — The ReflectionFunctionAbstract class
    • ReflectionMethod — The ReflectionMethod class
    • ReflectionNamedType — The ReflectionNamedType class
    • ReflectionObject — The ReflectionObject class
    • ReflectionParameter — The ReflectionParameter class
    • ReflectionProperty — The ReflectionProperty class
    • ReflectionType — The ReflectionType class
    • ReflectionGenerator — The ReflectionGenerator class
    • Reflector — The Reflector interface
    • ReflectionException — The ReflectionException class
  • Variable handling
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Variable handling Functions


Arrays

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Sorting Arrays
  • Array Functions
    • array_change_key_case — Changes the case of all keys in an array
    • array_chunk — Split an array into chunks
    • array_column — Return the values from a single column in the input array
    • array_combine — Creates an array by using one array for keys and another for its values
    • array_count_values — Counts all the values of an array
    • array_diff_assoc — Computes the difference of arrays with additional index check
    • array_diff_key — Computes the difference of arrays using keys for comparison
    • array_diff_uassoc — Computes the difference of arrays with additional index check which is performed by a user supplied callback function
    • array_diff_ukey — Computes the difference of arrays using a callback function on the keys for comparison
    • array_diff — Computes the difference of arrays
    • array_fill_keys — Fill an array with values, specifying keys
    • array_fill — Fill an array with values
    • array_filter — Filters elements of an array using a callback function
    • array_flip — Exchanges all keys with their associated values in an array
    • array_intersect_assoc — Computes the intersection of arrays with additional index check
    • array_intersect_key — Computes the intersection of arrays using keys for comparison
    • array_intersect_uassoc — Computes the intersection of arrays with additional index check, compares indexes by a callback function
    • array_intersect_ukey — Computes the intersection of arrays using a callback function on the keys for comparison
    • array_intersect — Computes the intersection of arrays
    • array_key_exists — Checks if the given key or index exists in the array
    • array_key_first — Gets the first key of an array
    • array_key_last — Gets the last key of an array
    • array_keys — Return all the keys or a subset of the keys of an array
    • array_map — Applies the callback to the elements of the given arrays
    • array_merge_recursive — Merge one or more arrays recursively
    • array_merge — Merge one or more arrays
    • array_multisort — Sort multiple or multi-dimensional arrays
    • array_pad — Pad array to the specified length with a value
    • array_pop — Pop the element off the end of array
    • array_product — Calculate the product of values in an array
    • array_push — Push one or more elements onto the end of array
    • array_rand — Pick one or more random keys out of an array
    • array_reduce — Iteratively reduce the array to a single value using a callback function
    • array_replace_recursive — Replaces elements from passed arrays into the first array recursively
    • array_replace — Replaces elements from passed arrays into the first array
    • array_reverse — Return an array with elements in reverse order
    • array_search — Searches the array for a given value and returns the first corresponding key if successful
    • array_shift — Shift an element off the beginning of array
    • array_slice — Extract a slice of the array
    • array_splice — Remove a portion of the array and replace it with something else
    • array_sum — Calculate the sum of values in an array
    • array_udiff_assoc — Computes the difference of arrays with additional index check, compares data by a callback function
    • array_udiff_uassoc — Computes the difference of arrays with additional index check, compares data and indexes by a callback function
    • array_udiff — Computes the difference of arrays by using a callback function for data comparison
    • array_uintersect_assoc — Computes the intersection of arrays with additional index check, compares data by a callback function
    • array_uintersect_uassoc — Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions
    • array_uintersect — Computes the intersection of arrays, compares data by a callback function
    • array_unique — Removes duplicate values from an array
    • array_unshift — Prepend one or more elements to the beginning of an array
    • array_values — Return all the values of an array
    • array_walk_recursive — Apply a user function recursively to every member of an array
    • array_walk — Apply a user supplied function to every member of an array
    • array — Create an array
    • arsort — Sort an array in reverse order and maintain index association
    • asort — Sort an array and maintain index association
    • compact — Create array containing variables and their values
    • count — Count all elements in an array, or something in an object
    • current — Return the current element in an array
    • each — Return the current key and value pair from an array and advance the array cursor
    • end — Set the internal pointer of an array to its last element
    • extract — Import variables into the current symbol table from an array
    • in_array — Checks if a value exists in an array
    • key_exists — Alias of array_key_exists
    • key — Fetch a key from an array
    • krsort — Sort an array by key in reverse order
    • ksort — Sort an array by key
    • list — Assign variables as if they were an array
    • natcasesort — Sort an array using a case insensitive "natural order" algorithm
    • natsort — Sort an array using a "natural order" algorithm
    • next — Advance the internal pointer of an array
    • pos — Alias of current
    • prev — Rewind the internal array pointer
    • range — Create an array containing a range of elements
    • reset — Set the internal pointer of an array to its first element
    • rsort — Sort an array in reverse order
    • shuffle — Shuffle an array
    • sizeof — Alias of count
    • sort — Sort an array
    • uasort — Sort an array with a user-defined comparison function and maintain index association
    • uksort — Sort an array by keys using a user-defined comparison function
    • usort — Sort an array by values using a user-defined comparison function


Introduction

These functions allow you to interact with and manipulate arrays in various ways. Arrays are essential for storing, managing, and operating on sets of variables.

Simple and multi-dimensional arrays are supported, and may be either user created or created by another function. There are specific database handling functions for populating arrays from database queries, and several functions return arrays.

Please see the Arrays section of the manual for a detailed explanation of how arrays are implemented and used in PHP. See also Array operators for other ways how to manipulate the arrays.


Predefined Constants

The constants below are always available as part of the PHP core.

CASE_LOWER (integer)
CASE_LOWER is used with array_change_key_case() and is used to convert array keys to lower case. This is also the default case for array_change_key_case().
CASE_UPPER (integer)
CASE_UPPER is used with array_change_key_case() and is used to convert array keys to upper case.

Sorting order flags:

SORT_ASC (integer)
SORT_ASC is used with array_multisort() to sort in ascending order.
SORT_DESC (integer)
SORT_DESC is used with array_multisort() to sort in descending order.

Sorting type flags: used by various sort functions

SORT_REGULAR (integer)
SORT_REGULAR is used to compare items normally.
SORT_NUMERIC (integer)
SORT_NUMERIC is used to compare items numerically.
SORT_STRING (integer)
SORT_STRING is used to compare items as strings.
SORT_LOCALE_STRING (integer)
SORT_LOCALE_STRING is used to compare items as strings, based on the current locale. Added in PHP 5.0.2.
SORT_NATURAL (integer)
SORT_NATURAL is used to compare items as strings using "natural ordering" like natsort(). Added in PHP 5.4.0.
SORT_FLAG_CASE (integer)
SORT_FLAG_CASE can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively. Added in PHP 5.4.0.

Filter flags:

ARRAY_FILTER_USE_KEY (integer)
ARRAY_FILTER_USE_KEY is used with array_filter() to pass each key as the first argument to the given callback function. Added in PHP 5.6.0.
ARRAY_FILTER_USE_BOTH (integer)
ARRAY_FILTER_USE_BOTH is used with array_filter() to pass both value and key to the given callback function. Added in PHP 5.6.0.

COUNT_NORMAL (integer)
COUNT_RECURSIVE (integer)
EXTR_OVERWRITE (integer)
EXTR_SKIP (integer)
EXTR_PREFIX_SAME (integer)
EXTR_PREFIX_ALL (integer)
EXTR_PREFIX_INVALID (integer)
EXTR_PREFIX_IF_EXISTS (integer)
EXTR_IF_EXISTS (integer)
EXTR_REFS (integer)


Sorting Arrays

PHP has several functions that deal with sorting arrays, and this document exists to help sort it all out.

The main differences are:

  • Some sort based on the array keys, whereas others by the values: $array['key'] = 'value';
  • Whether or not the correlation between the keys and values are maintained after the sort, which may mean the keys are reset numerically (0,1,2 ...)
  • The order of the sort: alphabetical, low to high (ascending), high to low (descending), numerical, natural, random, or user defined
  • Note: All of these sort functions act directly on the array variable itself, as opposed to returning a new sorted array
  • If any of these sort functions evaluates two members as equal then the order is undefined (the sorting is not stable).

Sorting function attributes
Function name | Sorts by | Maintains key association | Order of sort | Related functions
array_multisort() | value | associative yes, numeric no | first array or sort options | array_walk()
asort() | value | yes | low to high | arsort()
arsort() | value | yes | high to low | asort()
krsort() | key | yes | high to low | ksort()
ksort() | key | yes | low to high | asort()
natcasesort() | value | yes | natural, case insensitive | natsort()
natsort() | value | yes | natural | natcasesort()
rsort() | value | no | high to low | sort()
shuffle() | value | no | random | array_rand()
sort() | value | no | low to high | rsort()
uasort() | value | yes | user defined | uksort()
uksort() | key | yes | user defined | uasort()
usort() | value | no | user defined | uasort()


Array Functions

See Also

See also is_array(), explode(),
implode(), split(),
preg_split(), and unset().

Table of Contents

  • array_change_key_case — Changes the case of all keys in an array
  • array_chunk — Split an array into chunks
  • array_column — Return the values from a single column in the input array
  • array_combine — Creates an array by using one array for keys and another for its values
  • array_count_values — Counts all the values of an array
  • array_diff_assoc — Computes the difference of arrays with additional index check
  • array_diff_key — Computes the difference of arrays using keys for comparison
  • array_diff_uassoc — Computes the difference of arrays with additional index check which is performed by a user supplied callback function
  • array_diff_ukey — Computes the difference of arrays using a callback function on the keys for comparison
  • array_diff — Computes the difference of arrays
  • array_fill_keys — Fill an array with values, specifying keys
  • array_fill — Fill an array with values
  • array_filter — Filters elements of an array using a callback function
  • array_flip — Exchanges all keys with their associated values in an array
  • array_intersect_assoc — Computes the intersection of arrays with additional index check
  • array_intersect_key — Computes the intersection of arrays using keys for comparison
  • array_intersect_uassoc — Computes the intersection of arrays with additional index check, compares indexes by a callback function
  • array_intersect_ukey — Computes the intersection of arrays using a callback function on the keys for comparison
  • array_intersect — Computes the intersection of arrays
  • array_key_exists — Checks if the given key or index exists in the array
  • array_key_first — Gets the first key of an array
  • array_key_last — Gets the last key of an array
  • array_keys — Return all the keys or a subset of the keys of an array
  • array_map — Applies the callback to the elements of the given arrays
  • array_merge_recursive — Merge one or more arrays recursively
  • array_merge — Merge one or more arrays
  • array_multisort — Sort multiple or multi-dimensional arrays
  • array_pad — Pad array to the specified length with a value
  • array_pop — Pop the element off the end of array
  • array_product — Calculate the product of values in an array
  • array_push — Push one or more elements onto the end of array
  • array_rand — Pick one or more random keys out of an array
  • array_reduce — Iteratively reduce the array to a single value using a callback function
  • array_replace_recursive — Replaces elements from passed arrays into the first array recursively
  • array_replace — Replaces elements from passed arrays into the first array
  • array_reverse — Return an array with elements in reverse order
  • array_search — Searches the array for a given value and returns the first corresponding key if successful
  • array_shift — Shift an element off the beginning of array
  • array_slice — Extract a slice of the array
  • array_splice — Remove a portion of the array and replace it with something else
  • array_sum — Calculate the sum of values in an array
  • array_udiff_assoc — Computes the difference of arrays with additional index check, compares data by a callback function
  • array_udiff_uassoc — Computes the difference of arrays with additional index check, compares data and indexes by a callback function
  • array_udiff — Computes the difference of arrays by using a callback function for data comparison
  • array_uintersect_assoc — Computes the intersection of arrays with additional index check, compares data by a callback function
  • array_uintersect_uassoc — Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions
  • array_uintersect — Computes the intersection of arrays, compares data by a callback function
  • array_unique — Removes duplicate values from an array
  • array_unshift — Prepend one or more elements to the beginning of an array
  • array_values — Return all the values of an array
  • array_walk_recursive — Apply a user function recursively to every member of an array
  • array_walk — Apply a user supplied function to every member of an array
  • array — Create an array
  • arsort — Sort an array in reverse order and maintain index association
  • asort — Sort an array and maintain index association
  • compact — Create array containing variables and their values
  • count — Count all elements in an array, or something in an object
  • current — Return the current element in an array
  • each — Return the current key and value pair from an array and advance the array cursor
  • end — Set the internal pointer of an array to its last element
  • extract — Import variables into the current symbol table from an array
  • in_array — Checks if a value exists in an array
  • key_exists — Alias of array_key_exists
  • key — Fetch a key from an array
  • krsort — Sort an array by key in reverse order
  • ksort — Sort an array by key
  • list — Assign variables as if they were an array
  • natcasesort — Sort an array using a case insensitive "natural order" algorithm
  • natsort — Sort an array using a "natural order" algorithm
  • next — Advance the internal pointer of an array
  • pos — Alias of current
  • prev — Rewind the internal array pointer
  • range — Create an array containing a range of elements
  • reset — Set the internal pointer of an array to its first element
  • rsort — Sort an array in reverse order
  • shuffle — Shuffle an array
  • sizeof — Alias of count
  • sort — Sort an array
  • uasort — Sort an array with a user-defined comparison function and maintain index association
  • uksort — Sort an array by keys using a user-defined comparison function
  • usort — Sort an array by values using a user-defined comparison function


Changes the case of all keys in an array

  • « Array Functions
  • array_chunk »
  • PHP Manual
  • Array Functions
  • Changes the case of all keys in an array

array_change_key_case

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

array_change_key_case — Changes the case of all keys in an array

Description

array_change_key_case ( array $array [, int $case = CASE_LOWER ] ) : array

Returns an array with all keys from array lowercased or uppercased. Numbered indices are left as is.

Parameters

array

The array to work on

case

Either CASE_UPPER or CASE_LOWER (default)

Return Values

Returns an array with its keys lower or uppercased, or FALSE if array is not an array.

Errors/Exceptions

Throws E_WARNING if array is not an array.

Examples

Example #1 array_change_key_case() example

<?php
$input_array = array("FirSt" => 1, "SecOnd" => 4);
print_r(array_change_key_case($input_array, CASE_UPPER));
?>

The above example will output:

Array
(
    [FIRST] => 1
    [SECOND] => 4
)

Notes

Note:

If an array has indices that will be the same once run through this function (e.g. "keY" and "kEY"), the value that is later in the array will override other indices.


Split an array into chunks

  • « array_change_key_case
  • array_column »
  • PHP Manual
  • Array Functions
  • Split an array into chunks

array_chunk

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

array_chunk — Split an array into chunks

Description

array_chunk ( array $array , int $size [, bool $preserve_keys = FALSE ] ) : array

Chunks an array into arrays with size elements. The last chunk may contain less than size elements.

Parameters

array

The array to work on

size

The size of each chunk

preserve_keys

When set to TRUE keys will be preserved. Default is FALSE which will reindex the chunk numerically

Return Values

Returns a multidimensional numerically indexed array, starting with zero, with each dimension containing size elements.

Errors/Exceptions

If size is less than 1 E_WARNING will be thrown and NULL returned.

Examples

Example #1 array_chunk() example

<?php
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
print_r(array_chunk($input_array, 2, true));
?>

The above example will output:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
        )

)
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [2] => c
            [3] => d
        )

    [2] => Array
        (
            [4] => e
        )

)

See Also

  • array_slice() - Extract a slice of the array


Return the values from a single column in the input array

  • « array_chunk
  • array_combine »
  • PHP Manual
  • Array Functions
  • Return the values from a single column in the input array

array_column

(PHP 5 >= 5.5.0, PHP 7)

array_column — Return the values from a single column in the input array

Description

array_column ( array $input , mixed $column_key [, mixed $index_key = NULL ] ) : array

array_column() returns the values from a single column of the input, identified by the column_key. Optionally, an index_key may be provided to index the values in the returned array by the values from the index_key column of the input array.

Parameters

input

A multi-dimensional array or an array of objects from which to pull a column of values from. If an array of objects is provided, then public properties can be directly pulled. In order for protected or private properties to be pulled, the class must implement both the __get() and __isset() magic methods.

column_key

The column of values to return. This value may be an integer key of the column you wish to retrieve, or it may be a string key name for an associative array or property name. It may also be NULL to return complete arrays or objects (this is useful together with index_key to reindex the array).

index_key

The column to use as the index/keys for the returned array. This value may be the integer key of the column, or it may be the string key name. The value is cast as usual for array keys (however, objects supporting conversion to string are also allowed).

Return Values

Returns an array of values representing a single column from the input array.

Changelog

Version | Description
7.0.0 | Added the ability for the input parameter to be an array of objects.

Examples

Example #1 Get the column of first names from a recordset

<?php
// Array representing a possible record set returned from a database
$records = array(
    array(
        'id' => 2135,
        'first_name' => 'John',
        'last_name' => 'Doe',
    ),
    array(
        'id' => 3245,
        'first_name' => 'Sally',
        'last_name' => 'Smith',
    ),
    array(
        'id' => 5342,
        'first_name' => 'Jane',
        'last_name' => 'Jones',
    ),
    array(
        'id' => 5623,
        'first_name' => 'Peter',
        'last_name' => 'Doe',
    )
);

$first_names = array_column($records, 'first_name');
print_r($first_names);
?>

The above example will output:

Array
(
    [0] => John
    [1] => Sally
    [2] => Jane
    [3] => Peter
)

Example #2 Get the column of last names from a recordset, indexed by the "id" column

<?php
// Using the $records array from Example #1
$last_names = array_column($records, 'last_name', 'id');
print_r($last_names);
?>

The above example will output:

Array
(
    [2135] => Doe
    [3245] => Smith
    [5342] => Jones
    [5623] => Doe
)

Example #3 Get the column of usernames from the public "username" property of an object

<?php

class User
{
    public $username;

    public function __construct(string $username)
    {
        $this->username = $username;
    }
}

$users = [
    new User('user 1'),
    new User('user 2'),
    new User('user 3'),
];

print_r(array_column($users, 'username'));
?>

The above example will output:

Array
(
    [0] => user 1
    [1] => user 2
    [2] => user 3
)

Example #4 Get the column of names from the private "name" property of an object using the magic __get() method.

<?php

class Person
{
    private $name;

    public function __construct(string $name)
    {
        $this->name = $name;
    }

    public function __get($prop)
    {
        return $this->$prop;
    }

    public function __isset($prop) : bool
    {
        return isset($this->$prop);
    }
}

$people = [
    new Person('Fred'),
    new Person('Jane'),
    new Person('John'),
];

print_r(array_column($people, 'name'));
?>

The above example will output:

Array
(
    [0] => Fred
    [1] => Jane
    [2] => John
)
If __isset() is not provided, then an empty array will be returned.

See Also

  • » Recommended userland implementation for PHP lower than 5.5


Creates an array by using one array for keys and another for its values

  • « array_column
  • array_count_values »
  • PHP Manual
  • Array Functions
  • Creates an array by using one array for keys and another for its values

array_combine

(PHP 5, PHP 7)

array_combine — Creates an array by using one array for keys and another for its values

Description

array_combine ( array $keys , array $values ) : array

Creates an array by using the values from the keys array as keys and the values from the values array as the corresponding values.

Parameters

keys

Array of keys to be used. Illegal values for key will be converted to string.

values

Array of values to be used

Return Values

Returns the combined array, FALSE if the number of elements for each array isn't equal.

Errors/Exceptions

Throws E_WARNING if the number of elements in keys and values does not match.

Changelog

Version | Description
5.4.0 | Previous versions issued E_WARNING and returned FALSE for empty arrays.

Examples

Example #1 A simple array_combine() example

<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);
?>

The above example will output:

Array
(
    [green]  => avocado
    [red]    => apple
    [yellow] => banana
)

See Also

  • array_merge() - Merge one or more arrays
  • array_walk() - Apply a user supplied function to every member of an array
  • array_values() - Return all the values of an array


Counts all the values of an array

  • « array_combine
  • array_diff_assoc »
  • PHP Manual
  • Array Functions
  • Counts all the values of an array

array_count_values

(PHP 4, PHP 5, PHP 7)

array_count_values — Counts all the values of an array

Description

array_count_values ( array $array ) : array

array_count_values() returns an array using the values of array as keys and their frequency in array as values.

Parameters

array

The array of values to count

Return Values

Returns an associative array of values from array as keys and their count as value.

Errors/Exceptions

Throws E_WARNING for every element which is not string or integer.

Examples

Example #1 array_count_values() example

<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>

The above example will output:

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)

See Also

  • count() - Count all elements in an array, or something in an object
  • array_unique() - Removes duplicate values from an array
  • array_values() - Return all the values of an array
  • count_chars() - Return information about characters used in a string


Computes the difference of arrays with additional index check

  • « array_count_values
  • array_diff_key »
  • PHP Manual
  • Array Functions
  • Computes the difference of arrays with additional index check

array_diff_assoc

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

array_diff_assoc — Computes the difference of arrays with additional index check

Description

array_diff_assoc ( array $array1 , array $array2 [, array $... ] ) : array

Compares array1 against array2 and returns the difference. Unlike array_diff() the array keys are also used in the comparison.

Parameters

array1

The array to compare from

array2

An array to compare against

...

More arrays to compare against

Return Values

Returns an array containing all the values from array1 that are not present in any of the other arrays.

Examples

Example #1 array_diff_assoc() example

In this example you see the "a" => "green" pair is present in both arrays and thus it is not in the output from the function. Unlike this, the pair 0 => "red" is in the output because in the second argument "red" has key which is 1.

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result = array_diff_assoc($array1, $array2);
print_r($result);
?>

The above example will output:

Array
(
    [b] => brown
    [c] => blue
    [0] => red
)

Example #2 array_diff_assoc() example

Two values from key => value pairs are considered equal only if (string) $elem1 === (string) $elem2 . In other words a strict check takes place so the string representations must be the same.

<?php
$array1 = array(0, 1, 2);
$array2 = array("00", "01", "2");
$result = array_diff_assoc($array1, $array2);
print_r($result);
?>

The above example will output:

Array
(
    [0] => 0
    [1] => 1
    )

Notes

Note: This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using, for example, array_diff_assoc($array1[0], $array2[0]);.

Note: Ensure you pass arguments in the correct order when comparing similar arrays with more keys. The new array should be the first in the list.

See Also

  • array_diff() - Computes the difference of arrays
  • array_diff_uassoc() - Computes the difference of arrays with additional index check which is performed by a user supplied callback function
  • array_udiff_assoc() - Computes the difference of arrays with additional index check, compares data by a callback function
  • array_udiff_uassoc() - Computes the difference of arrays with additional index check, compares data and indexes by a callback function
  • array_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check


Computes the difference of arrays using keys for comparison

  • « array_diff_assoc
  • array_diff_uassoc »
  • PHP Manual
  • Array Functions
  • Computes the difference of arrays using keys for comparison

array_diff_key

(PHP 5 >= 5.1.0, PHP 7)

array_diff_key — Computes the difference of arrays using keys for comparison

Description

array_diff_key ( array $array1 , array $array2 [, array $... ] ) : array

Compares the keys from array1 against the keys from array2 and returns the difference. This function is like array_diff() except the comparison is done on the keys instead of the values.

Parameters

array1

The array to compare from

array2

An array to compare against

...

More arrays to compare against

Return Values

Returns an array containing all the entries from array1 whose keys are absent from all of the other arrays.

Examples

Example #1 array_diff_key() example

The two keys from the key => value pairs are considered equal only if (string) $key1 === (string) $key2 . In other words a strict type check is executed so the string representation must be the same.

<?php
$array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$array2 = array('green' => 5, 'yellow' => 7, 'cyan' => 8);

var_dump(array_diff_key($array1, $array2));
?>

The above example will output:

array(3) {
  ["blue"]=>
  int(1)
  ["red"]=>
  int(2)
  ["purple"]=>
  int(4)
}
<?php
$array1 = array('blue' => 1, 'red'  => 2, 'green' => 3, 'purple' => 4);
$array2 = array('green' => 5, 'yellow' => 7, 'cyan' => 8);
$array3 = array('blue' => 6, 'yellow' => 7, 'mauve' => 8);

var_dump(array_diff_key($array1, $array2, $array3));
?>

The above example will output:

array(2) {
  ["red"]=>
  int(2)
  ["purple"]=>
  int(4)
}

Notes

Note:

This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff_key($array1[0], $array2[0]);.

See Also

  • array_diff() - Computes the difference of arrays
  • array_udiff() - Computes the difference of arrays by using a callback function for data comparison
  • array_diff_assoc() - Computes the difference of arrays with additional index check
  • array_diff_uassoc() - Computes the difference of arrays with additional index check which is performed by a user supplied callback function
  • array_udiff_assoc() - Computes the difference of arrays with additional index check, compares data by a callback function
  • array_udiff_uassoc() - Computes the difference of arrays with additional index check, compares data and indexes by a callback function
  • array_diff_ukey() - Computes the difference of arrays using a callback function on the keys for comparison
  • array_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • array_intersect_uassoc() - Computes the intersection of arrays with additional index check, compares indexes by a callback function
  • array_intersect_key() - Computes the intersection of arrays using keys for comparison
  • array_intersect_ukey() - Computes the intersection of arrays using a callback function on the keys for comparison


Computes the difference of arrays with additional index check which is performed by a user supplied callback function

  • « array_diff_key
  • array_diff_ukey »
  • PHP Manual
  • Array Functions
  • Computes the difference of arrays with additional index check which is performed by a user supplied callback function

array_diff_uassoc

(PHP 5, PHP 7)

array_diff_uassoc — Computes the difference of arrays with additional index check which is performed by a user supplied callback function

Description

array_diff_uassoc ( array $array1 , array $array2 [, array $... ], callable $key_compare_func ) : array

Compares array1 against array2 and returns the difference. Unlike array_diff() the array keys are used in the comparison.

Unlike array_diff_assoc() a user supplied callback function is used for the indices comparison, not internal function.

Parameters

array1

The array to compare from

array2

An array to compare against

...

More arrays to compare against

key_compare_func

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. Note that before PHP 7.0.0 this integer had to be in the range from -2147483648 to 2147483647.

callback ( mixed $a, mixed $b ) : int

Return Values

Returns an array containing all the entries from array1 that are not present in any of the other arrays.

Examples

Example #1 array_diff_uassoc() example

The "a" => "green" pair is present in both arrays and thus it is not in the output from the function. Unlike this, the pair 0 => "red" is in the output because in the second argument "red" has key which is 1.

<?php
function key_compare_func($a, $b)
{
    if ($a === $b) {
        return 0;
    }
    return ($a > $b)? 1:-1;
}

$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result = array_diff_uassoc($array1, $array2, "key_compare_func");
print_r($result);
?>

The above example will output:

Array
(
    [b] => brown
    [c] => blue
    [0] => red
)

The equality of 2 indices is checked by the user supplied callback function.

Notes

Note:

This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using, for example, array_diff_uassoc($array1[0], $array2[0], "key_compare_func");.

See Also

  • array_diff() - Computes the difference of arrays
  • array_diff_assoc() - Computes the difference of arrays with additional index check
  • array_udiff() - Computes the difference of arrays by using a callback function for data comparison
  • array_udiff_assoc() - Computes the difference of arrays with additional index check, compares data by a callback function
  • array_udiff_uassoc() - Computes the difference of arrays with additional index check, compares data and indexes by a callback function
  • array_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • array_uintersect() - Computes the intersection of arrays, compares data by a callback function
  • array_uintersect_assoc() - Computes the intersection of arrays with additional index check, compares data by a callback function
  • array_uintersect_uassoc() - Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions


Computes the difference of arrays using a callback function on the keys for comparison

  • « array_diff_uassoc
  • array_diff »
  • PHP Manual
  • Array Functions
  • Computes the difference of arrays using a callback function on the keys for comparison

array_diff_ukey

(PHP 5 >= 5.1.0, PHP 7)

array_diff_ukey — Computes the difference of arrays using a callback function on the keys for comparison

Description

array_diff_ukey ( array $array1 , array $array2 [, array $... ], callable $key_compare_func ) : array

Compares the keys from array1 against the keys from array2 and returns the difference. This function is like array_diff() except the comparison is done on the keys instead of the values.

Unlike array_diff_key() a user supplied callback function is used for the indices comparison, not internal function.

Parameters

array1

The array to compare from

array2

An array to compare against

...

More arrays to compare against

key_compare_func

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. Note that before PHP 7.0.0 this integer had to be in the range from -2147483648 to 2147483647.

callback ( mixed $a, mixed $b ) : int

Return Values

Returns an array containing all the entries from array1 that are not present in any of the other arrays.

Examples

Example #1 array_diff_ukey() example

<?php
function key_compare_func($key1, $key2)
{
    if ($key1 == $key2)
        return 0;
    else if ($key1 > $key2)
        return 1;
    else
        return -1;
}

$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

var_dump(array_diff_ukey($array1, $array2, 'key_compare_func'));
?>

The above example will output:

array(2) {
  ["red"]=>
  int(2)
  ["purple"]=>
  int(4)
}

Notes

Note:

This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff_ukey($array1[0], $array2[0], 'callback_func');.

See Also

  • array_diff() - Computes the difference of arrays
  • array_udiff() - Computes the difference of arrays by using a callback function for data comparison
  • array_diff_assoc() - Computes the difference of arrays with additional index check
  • array_diff_uassoc() - Computes the difference of arrays with additional index check which is performed by a user supplied callback function
  • array_udiff_assoc() - Computes the difference of arrays with additional index check, compares data by a callback function
  • array_udiff_uassoc() - Computes the difference of arrays with additional index check, compares data and indexes by a callback function
  • array_diff_key() - Computes the difference of arrays using keys for comparison
  • array_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • array_intersect_uassoc() - Computes the intersection of arrays with additional index check, compares indexes by a callback function
  • array_intersect_key() - Computes the intersection of arrays using keys for comparison
  • array_intersect_ukey() - Computes the intersection of arrays using a callback function on the keys for comparison


Computes the difference of arrays

  • « array_diff_ukey
  • array_fill_keys »
  • PHP Manual
  • Array Functions
  • Computes the difference of arrays

array_diff

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

array_diff — Computes the difference of arrays

Description

array_diff ( array $array1 , array $array2 [, array $... ] ) : array

Compares array1 against one or more other arrays and returns the values in array1 that are not present in any of the other arrays.

Parameters

array1

The array to compare from

array2

An array to compare against

...

More arrays to compare against

Return Values

Returns an array containing all the entries from array1 that are not present in any of the other arrays.

Examples

Example #1 array_diff() example

<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);

print_r($result);
?>

Multiple occurrences in $array1 are all treated the same way. This will output :

Array
(
    [1] => blue
)

Notes

Note:

Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In other words: when the string representation is the same.

Note:

This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff($array1[0], $array2[0]);.

See Also

  • array_diff_assoc() - Computes the difference of arrays with additional index check
  • array_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check


Fill an array with values, specifying keys

  • « array_diff
  • array_fill »
  • PHP Manual
  • Array Functions
  • Fill an array with values, specifying keys

array_fill_keys

(PHP 5 >= 5.2.0, PHP 7)

array_fill_keys — Fill an array with values, specifying keys

Description

array_fill_keys ( array $keys , mixed $value ) : array

Fills an array with the value of the value parameter, using the values of the keys array as keys.

Parameters

keys

Array of values that will be used as keys. Illegal values for key will be converted to string.

value

Value to use for filling

Return Values

Returns the filled array

Examples

Example #1 array_fill_keys() example

<?php
$keys = array('foo', 5, 10, 'bar');
$a = array_fill_keys($keys, 'banana');
print_r($a);
?>

The above example will output:

Array
(
    [foo] => banana
    [5] => banana
    [10] => banana
    [bar] => banana
)

See Also

  • array_fill() - Fill an array with values
  • array_combine() - Creates an array by using one array for keys and another for its values


Fill an array with values

  • « array_fill_keys
  • array_filter »
  • PHP Manual
  • Array Functions
  • Fill an array with values

array_fill

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

array_fill — Fill an array with values

Description

array_fill ( int $start_index , int $num , mixed $value ) : array

Fills an array with num entries of the value of the value parameter, keys starting at the start_index parameter.

Parameters

start_index

The first index of the returned array.

If start_index is negative, the first index of the returned array will be start_index and the following indices will start from zero (see example).

num

Number of elements to insert. Must be greater than or equal to zero.

value

Value to use for filling

Return Values

Returns the filled array

Errors/Exceptions

Throws a E_WARNING if num is less than zero.

Changelog

Version | Description
5.6.0 | num may now be zero. Previously, num was required to be greater than zero.

Examples

Example #1 array_fill() example

<?php
$a = array_fill(5, 6, 'banana');
$b = array_fill(-2, 4, 'pear');
print_r($a);
print_r($b);
?>

The above example will output:

Array
(
    [5]  => banana
    [6]  => banana
    [7]  => banana
    [8]  => banana
    [9]  => banana
    [10] => banana
)
Array
(
    [-2] => pear
    [0] => pear
    [1] => pear
    [2] => pear
)

Notes

See also the Arrays section of manual for a detailed explanation of negative keys.

See Also

  • array_fill_keys() - Fill an array with values, specifying keys
  • str_repeat() - Repeat a string
  • range() - Create an array containing a range of elements


Filters elements of an array using a callback function

  • « array_fill
  • array_flip »
  • PHP Manual
  • Array Functions
  • Filters elements of an array using a callback function

array_filter

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

array_filter — Filters elements of an array using a callback function

Description

array_filter ( array $array [, callable $callback [, int $flag = 0 ]] ) : array

Iterates over each value in the array passing them to the callback function. If the callback function returns TRUE, the current value from array is returned into the result array. Array keys are preserved.

Parameters

array

The array to iterate over

callback

The callback function to use

If no callback is supplied, all entries of array equal to FALSE (see converting to boolean) will be removed.

flag

Flag determining what arguments are sent to callback:

  • ARRAY_FILTER_USE_KEY - pass key as the only argument to callback instead of the value
  • ARRAY_FILTER_USE_BOTH - pass both value and key as arguments to callback instead of the value
Default is 0 which will pass value as the only argument to callback instead.

Return Values

Returns the filtered array.

Changelog

Version | Description
5.6.0 | Added optional flag parameter and constants ARRAY_FILTER_USE_KEY and ARRAY_FILTER_USE_BOTH

Examples

Example #1 array_filter() example

<?php
function odd($var)
{
    // returns whether the input integer is odd
    return $var & 1;
}

function even($var)
{
    // returns whether the input integer is even
    return !($var & 1);
}

$array1 = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5];
$array2 = [6, 7, 8, 9, 10, 11, 12];

echo "Odd :\n";
print_r(array_filter($array1, "odd"));
echo "Even:\n";
print_r(array_filter($array2, "even"));
?>

The above example will output:

Odd :
Array
(
    [a] => 1
    [c] => 3
    [e] => 5
)
Even:
Array
(
    [0] => 6
    [2] => 8
    [4] => 10
    [6] => 12
)

Example #2 array_filter() without callback

<?php

$entry = [
    0 => 'foo',
    1 => false,
    2 => -1,
    3 => null,
    4 => '',
    5 => '0',
    6 => 0,
];

print_r(array_filter($entry));
?>

The above example will output:

Array
(
    [0] => foo
    [2] => -1
)

Example #3 array_filter() with flag

<?php

$arr = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];

var_dump(array_filter($arr, function($k) {
    return $k == 'b';
}, ARRAY_FILTER_USE_KEY));

var_dump(array_filter($arr, function($v, $k) {
    return $k == 'b' || $v == 4;
}, ARRAY_FILTER_USE_BOTH));
?>

The above example will output:

array(1) {
  ["b"]=>
  int(2)
}
array(2) {
  ["b"]=>
  int(2)
  ["d"]=>
  int(4)
}

Notes

Caution

If the array is changed from the callback function (e.g. element added, deleted or unset) the behavior of this function is undefined.

See Also

  • array_map() - Applies the callback to the elements of the given arrays
  • array_reduce() - Iteratively reduce the array to a single value using a callback function
  • array_walk() - Apply a user supplied function to every member of an array


Exchanges all keys with their associated values in an array

  • « array_filter
  • array_intersect_assoc »
  • PHP Manual
  • Array Functions
  • Exchanges all keys with their associated values in an array

array_flip

(PHP 4, PHP 5, PHP 7)

array_flip — Exchanges all keys with their associated values in an array

Description

array_flip ( array $array ) : array

array_flip() returns an array in flip order, i.e. keys from array become values and values from array become keys.

Note that the values of array need to be valid keys, i.e. they need to be either integer or string. A warning will be emitted if a value has the wrong type, and the key/value pair in question will not be included in the result.

If a value has several occurrences, the latest key will be used as its value, and all others will be lost.

Parameters

array

An array of key/value pairs to be flipped.

Return Values

Returns the flipped array on success and NULL on failure.

Examples

Example #1 array_flip() example

<?php
$input = array("oranges", "apples", "pears");
$flipped = array_flip($input);

print_r($flipped);
?>

The above example will output:

Array
(
    [oranges] => 0
    [apples] => 1
    [pears] => 2
)

Example #2 array_flip() example : collision

<?php
$input = array("a" => 1, "b" => 1, "c" => 2);
$flipped = array_flip($input);

print_r($flipped);
?>

The above example will output:

Array
(
    [1] => b
    [2] => c
)

See Also

  • array_values() - Return all the values of an array
  • array_keys() - Return all the keys or a subset of the keys of an array
  • array_reverse() - Return an array with elements in reverse order


Computes the intersection of arrays with additional index check

  • « array_flip
  • array_intersect_key »
  • PHP Manual
  • Array Functions
  • Computes the intersection of arrays with additional index check

array_intersect_assoc

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

array_intersect_assoc — Computes the intersection of arrays with additional index check

Description

array_intersect_assoc ( array $array1 , array $array2 [, array $... ] ) : array

array_intersect_assoc() returns an array containing all the values of array1 that are present in all the arguments. Note that the keys are also used in the comparison unlike in array_intersect().

Parameters

array1

The array with master values to check.

array2

An array to compare values against.

...

A variable list of arrays to compare.

Return Values

Returns an associative array containing all the values in array1 that are present in all of the arguments.

Examples

Example #1 array_intersect_assoc() example

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "b" => "yellow", "blue", "red");
$result_array = array_intersect_assoc($array1, $array2);
print_r($result_array);
?>

The above example will output:

Array
(
    [a] => green
)

In our example you see that only the pair "a" => "green" is present in both arrays and thus is returned. The value "red" is not returned because in $array1 its key is 0 while the key of "red" in $array2 is 1, and the key "b" is not returned because its values are different in each array.

The two values from the key => value pairs are considered equal only if (string) $elem1 === (string) $elem2 . In other words a strict type check is executed so the string representation must be the same.

See Also

  • array_intersect() - Computes the intersection of arrays
  • array_uintersect_assoc() - Computes the intersection of arrays with additional index check, compares data by a callback function
  • array_intersect_uassoc() - Computes the intersection of arrays with additional index check, compares indexes by a callback function
  • array_uintersect_uassoc() - Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions
  • array_diff() - Computes the difference of arrays
  • array_diff_assoc() - Computes the difference of arrays with additional index check


Computes the intersection of arrays using keys for comparison

  • « array_intersect_assoc
  • array_intersect_uassoc »
  • PHP Manual
  • Array Functions
  • Computes the intersection of arrays using keys for comparison

array_intersect_key

(PHP 5 >= 5.1.0, PHP 7)

array_intersect_key — Computes the intersection of arrays using keys for comparison

Description

array_intersect_key ( array $array1 , array $array2 [, array $... ] ) : array

array_intersect_key() returns an array containing all the entries of array1 which have keys that are present in all the arguments.

Parameters

array1

The array with master keys to check.

array2

An array to compare keys against.

...

A variable list of arrays to compare.

Return Values

Returns an associative array containing all the entries of array1 which have keys that are present in all arguments.

Examples

Example #1 array_intersect_key() example

<?php
$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

var_dump(array_intersect_key($array1, $array2));
?>

The above example will output:

array(2) {
  ["blue"]=>
  int(1)
  ["green"]=>
  int(3)
}

In our example you see that only the keys 'blue' and 'green' are present in both arrays and thus returned. Also notice that the values for the keys 'blue' and 'green' differ between the two arrays. A match still occurs because only the keys are checked. The values returned are those of array1.

The two keys from the key => value pairs are considered equal only if (string) $key1 === (string) $key2 . In other words a strict type check is executed so the string representation must be the same.

See Also

  • array_diff() - Computes the difference of arrays
  • array_udiff() - Computes the difference of arrays by using a callback function for data comparison
  • array_diff_assoc() - Computes the difference of arrays with additional index check
  • array_diff_uassoc() - Computes the difference of arrays with additional index check which is performed by a user supplied callback function
  • array_udiff_assoc() - Computes the difference of arrays with additional index check, compares data by a callback function
  • array_udiff_uassoc() - Computes the difference of arrays with additional index check, compares data and indexes by a callback function
  • array_diff_key() - Computes the difference of arrays using keys for comparison
  • array_diff_ukey() - Computes the difference of arrays using a callback function on the keys for comparison
  • array_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • array_intersect_uassoc() - Computes the intersection of arrays with additional index check, compares indexes by a callback function
  • array_intersect_ukey() - Computes the intersection of arrays using a callback function on the keys for comparison


Computes the intersection of arrays with additional index check, compares indexes by a callback function

  • « array_intersect_key
  • array_intersect_ukey »
  • PHP Manual
  • Array Functions
  • Computes the intersection of arrays with additional index check, compares indexes by a callback function

array_intersect_uassoc

(PHP 5, PHP 7)

array_intersect_uassoc — Computes the intersection of arrays with additional index check, compares indexes by a callback function

Description

array_intersect_uassoc ( array $array1 , array $array2 [, array $... ], callable $key_compare_func ) : array

array_intersect_uassoc() returns an array containing all the values of array1 that are present in all the arguments. Note that the keys are used in the comparison unlike in array_intersect().

Parameters

array1

Initial array for comparison of the arrays.

array2

First array to compare keys against.

...

Variable list of array arguments to compare values against.

key_compare_func

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. Note that before PHP 7.0.0 this integer had to be in the range from -2147483648 to 2147483647.

callback ( mixed $a, mixed $b ) : int

Return Values

Returns the values of array1 whose values exist in all of the arguments.

Examples

Example #1 array_intersect_uassoc() example

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_intersect_uassoc($array1, $array2, "strcasecmp"));
?>

The above example will output:

Array
(
    [b] => brown
)

See Also

  • array_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • array_uintersect_assoc() - Computes the intersection of arrays with additional index check, compares data by a callback function
  • array_uintersect_uassoc() - Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions
  • array_intersect_key() - Computes the intersection of arrays using keys for comparison
  • array_intersect_ukey() - Computes the intersection of arrays using a callback function on the keys for comparison


Computes the intersection of arrays using a callback function on the keys for comparison

  • « array_intersect_uassoc
  • array_intersect »
  • PHP Manual
  • Array Functions
  • Computes the intersection of arrays using a callback function on the keys for comparison

array_intersect_ukey

(PHP 5 >= 5.1.0, PHP 7)

array_intersect_ukey — Computes the intersection of arrays using a callback function on the keys for comparison

Description

array_intersect_ukey ( array $array1 , array $array2 [, array $... ], callable $key_compare_func ) : array

array_intersect_ukey() returns an array containing all the values of array1 which have matching keys that are present in all the arguments.

Parameters

array1

Initial array for comparison of the arrays.

array2

First array to compare keys against.

...

Variable list of array arguments to compare keys against.

key_compare_func

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. Note that before PHP 7.0.0 this integer had to be in the range from -2147483648 to 2147483647.

callback ( mixed $a, mixed $b ) : int

Return Values

Returns the values of array1 whose keys exist in all the arguments.

Examples

Example #1 array_intersect_ukey() example

<?php
function key_compare_func($key1, $key2)
{
    if ($key1 == $key2)
        return 0;
    else if ($key1 > $key2)
        return 1;
    else
        return -1;
}

$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

var_dump(array_intersect_ukey($array1, $array2, 'key_compare_func'));
?>

The above example will output:

array(2) {
  ["blue"]=>
  int(1)
  ["green"]=>
  int(3)
}

In our example you see that only the keys 'blue' and 'green' are present in both arrays and thus returned. Also notice that the values for the keys 'blue' and 'green' differ between the two arrays. A match still occurs because only the keys are checked. The values returned are those of array1.

See Also

  • array_diff() - Computes the difference of arrays
  • array_udiff() - Computes the difference of arrays by using a callback function for data comparison
  • array_diff_assoc() - Computes the difference of arrays with additional index check
  • array_diff_uassoc() - Computes the difference of arrays with additional index check which is performed by a user supplied callback function
  • array_udiff_assoc() - Computes the difference of arrays with additional index check, compares data by a callback function
  • array_udiff_uassoc() - Computes the difference of arrays with additional index check, compares data and indexes by a callback function
  • array_diff_key() - Computes the difference of arrays using keys for comparison
  • array_diff_ukey() - Computes the difference of arrays using a callback function on the keys for comparison
  • array_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • array_intersect_uassoc() - Computes the intersection of arrays with additional index check, compares indexes by a callback function
  • array_intersect_key() - Computes the intersection of arrays using keys for comparison


Computes the intersection of arrays

  • « array_intersect_ukey
  • array_key_exists »
  • PHP Manual
  • Array Functions
  • Computes the intersection of arrays

array_intersect

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

array_intersect — Computes the intersection of arrays

Description

array_intersect ( array $array1 , array $array2 [, array $... ] ) : array

array_intersect() returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.

Parameters

array1

The array with master values to check.

array2

An array to compare values against.

...

A variable list of arrays to compare.

Return Values

Returns an array containing all of the values in array1 whose values exist in all of the parameters.

Examples

Example #1 array_intersect() example

<?php
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);
?>

The above example will output:

Array
(
    [a] => green
    [0] => red
)

Notes

Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.

See Also

  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • array_diff() - Computes the difference of arrays
  • array_diff_assoc() - Computes the difference of arrays with additional index check


Checks if the given key or index exists in the array

  • « array_intersect
  • array_key_first »
  • PHP Manual
  • Array Functions
  • Checks if the given key or index exists in the array

array_key_exists

(PHP 4 >= 4.0.7, PHP 5, PHP 7)

array_key_exists — Checks if the given key or index exists in the array

Description

array_key_exists ( mixed $key , array $array ) : bool

array_key_exists() returns TRUE if the given key is set in the array. key can be any value possible for an array index.

Parameters

key

Value to check.

array

An array with keys to check.

Return Values

Returns TRUE on success or FALSE on failure.

Note:

array_key_exists() will search for the keys in the first dimension only. Nested keys in multidimensional arrays will not be found.

Examples

Example #1 array_key_exists() example

<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
    echo "The 'first' element is in the array";
}
?>

Example #2 array_key_exists() vs isset()

isset() does not return TRUE for array keys that correspond to a NULL value, while array_key_exists() does.

<?php
$search_array = array('first' => null, 'second' => 4);

// returns false
isset($search_array['first']);

// returns true
array_key_exists('first', $search_array);
?>

Notes

Note:

For backward compatibility reasons, array_key_exists() will also return TRUE if key is a property defined within an object given as array. This behaviour should not be relied upon, and care should be taken to ensure that array is an array.

To check whether a property exists in an object, use property_exists().

See Also

  • isset() - Determine if a variable is declared and is different than NULL
  • array_keys() - Return all the keys or a subset of the keys of an array
  • in_array() - Checks if a value exists in an array
  • property_exists() - Checks if the object or class has a property


Gets the first key of an array

  • « array_key_exists
  • array_key_last »
  • PHP Manual
  • Array Functions
  • Gets the first key of an array

array_key_first

(PHP 7 >= 7.3.0)

array_key_first — Gets the first key of an array

Description

array_key_first ( array $array ) : mixed

Get the first key of the given array without affecting the internal array pointer.

Parameters

array

An array.

Return Values

Returns the first key of array if the array is not empty; NULL otherwise.

Examples

Example #1 Basic array_key_first() Usage

<?php
$array = ['a' => 1, 'b' => 2, 'c' => 3];

$firstKey = array_key_first($array);

var_dump($firstKey);
?>

The above example will output:

string(1) "a"

Notes

Tip

There are several ways to provide this functionality for versions prior to PHP 7.3.0. It is possible to use array_keys(), but that may be rather inefficient. It is also possible to use reset() and key(), but that may change the internal array pointer. An efficient solution, which does not change the internal array pointer, written as polyfill:

<?php
if (!function_exists('array_key_first')) {
    function array_key_first(array $arr) {
        foreach($arr as $key => $unused) {
            return $key;
        }
        return NULL;
    }
}
?>

See Also

  • array_key_last() - Gets the last key of an array
  • reset() - Set the internal pointer of an array to its first element


Gets the last key of an array

  • « array_key_first
  • array_keys »
  • PHP Manual
  • Array Functions
  • Gets the last key of an array

array_key_last

(PHP 7 >= 7.3.0)

array_key_last — Gets the last key of an array

Description

array_key_last ( array $array ) : mixed

Get the last key of the given array without affecting the internal array pointer.

Parameters

array

An array.

Return Values

Returns the last key of array if the array is not empty; NULL otherwise.

See Also

  • array_key_first() - Gets the first key of an array
  • end() - Set the internal pointer of an array to its last element


Return all the keys or a subset of the keys of an array

  • « array_key_last
  • array_map »
  • PHP Manual
  • Array Functions
  • Return all the keys or a subset of the keys of an array

array_keys

(PHP 4, PHP 5, PHP 7)

array_keys — Return all the keys or a subset of the keys of an array

Description

array_keys ( array $array ) : array
array_keys ( array $array , mixed $search_value [, bool $strict = FALSE ] ) : array

array_keys() returns the keys, numeric and string, from the array.

If a search_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.

Parameters

array

An array containing keys to return.

search_value

If specified, then only keys containing these values are returned.

strict

Determines if strict comparison (===) should be used during the search.

Return Values

Returns an array of all the keys in array.

Examples

Example #1 array_keys() example

<?php
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));

$array = array("blue", "red", "green", "blue", "blue");
print_r(array_keys($array, "blue"));

$array = array("color" => array("blue", "red", "green"),
               "size"  => array("small", "medium", "large"));
print_r(array_keys($array));
?>

The above example will output:

Array
(
    [0] => 0
    [1] => color
)
Array
(
    [0] => 0
    [1] => 3
    [2] => 4
)
Array
(
    [0] => color
    [1] => size
)

See Also

  • array_values() - Return all the values of an array
  • array_combine() - Creates an array by using one array for keys and another for its values
  • array_key_exists() - Checks if the given key or index exists in the array
  • array_search() - Searches the array for a given value and returns the first corresponding key if successful


Applies the callback to the elements of the given arrays

  • « array_keys
  • array_merge_recursive »
  • PHP Manual
  • Array Functions
  • Applies the callback to the elements of the given arrays

array_map

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

array_map — Applies the callback to the elements of the given arrays

Description

array_map ( callable $callback , array $array1 [, array $... ] ) : array

array_map() returns an array containing the results of applying the callback function to the corresponding index of array1 (and ... if more arrays are provided) used as arguments for the callback. The number of parameters that the callback function accepts should match the number of arrays passed to array_map().

Parameters

callback

Callback function to run for each element in each array.

NULL can be passed as a value to callback to perform a zip operation on multiple arrays. If only array1 is provided, array_map() will return the input array.

array1

An array to run through the callback function.

...

Supplementary variable list of array arguments to run through the callback function.

Return Values

Returns an array containing the results of applying the callback function to the corresponding index of array1 (and ... if more arrays are provided) used as arguments for the callback.

The returned array will preserve the keys of the array argument if and only if exactly one array is passed. If more than one array is passed, the returned array will have sequential integer keys.

Examples

Example #1 array_map() example

<?php
function cube($n)
{
    return ($n * $n * $n);
}

$a = [1, 2, 3, 4, 5];
$b = array_map('cube', $a);
print_r($b);
?>

This makes $b have:

Array
(
    [0] => 1
    [1] => 8
    [2] => 27
    [3] => 64
    [4] => 125
)

Example #2 array_map() using a lambda function (as of PHP 5.3.0)

<?php
$func = function($value) {
    return $value * 2;
};

print_r(array_map($func, range(1, 5)));
?>
Array
(
    [0] => 2
    [1] => 4
    [2] => 6
    [3] => 8
    [4] => 10
)

Example #3 array_map() - using more arrays

<?php
function show_Spanish($n, $m)
{
    return "The number {$n} is called {$m} in Spanish";
}

function map_Spanish($n, $m)
{
    return [$n => $m];
}

$a = [1, 2, 3, 4, 5];
$b = ['uno', 'dos', 'tres', 'cuatro', 'cinco'];

$c = array_map('show_Spanish', $a, $b);
print_r($c);

$d = array_map('map_Spanish', $a , $b);
print_r($d);
?>

The above example will output:

// printout of $c
Array
(
    [0] => The number 1 is called uno in Spanish
    [1] => The number 2 is called dos in Spanish
    [2] => The number 3 is called tres in Spanish
    [3] => The number 4 is called cuatro in Spanish
    [4] => The number 5 is called cinco in Spanish
)

// printout of $d
Array
(
    [0] => Array
        (
            [1] => uno
        )

    [1] => Array
        (
            [2] => dos
        )

    [2] => Array
        (
            [3] => tres
        )

    [3] => Array
        (
            [4] => cuatro
        )

    [4] => Array
        (
            [5] => cinco
        )

)

Usually when using two or more arrays, they should be of equal length because the callback function is applied in parallel to the corresponding elements. If the arrays are of unequal length, shorter ones will be extended with empty elements to match the length of the longest.

An interesting use of this function is to construct an array of arrays, which can be easily performed by using NULL as the name of the callback function

Example #4 Performing a zip operation of arrays

<?php
$a = [1, 2, 3, 4, 5];
$b = ['one', 'two', 'three', 'four', 'five'];
$c = ['uno', 'dos', 'tres', 'cuatro', 'cinco'];

$d = array_map(null, $a, $b, $c);
print_r($d);
?>

The above example will output:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => one
            [2] => uno
        )

    [1] => Array
        (
            [0] => 2
            [1] => two
            [2] => dos
        )

    [2] => Array
        (
            [0] => 3
            [1] => three
            [2] => tres
        )

    [3] => Array
        (
            [0] => 4
            [1] => four
            [2] => cuatro
        )

    [4] => Array
        (
            [0] => 5
            [1] => five
            [2] => cinco
        )

)

Example #5 NULL callback with only array1

<?php
$array = [1, 2, 3];
var_dump(array_map(null, $array));
?>

The above example will output:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

Example #6 array_map() - with string keys

<?php
$arr = ['stringkey' => 'value'];
function cb1($a) {
    return [$a];
}
function cb2($a, $b) {
    return [$a, $b];
}
var_dump(array_map('cb1', $arr));
var_dump(array_map('cb2', $arr, $arr));
var_dump(array_map(null,  $arr));
var_dump(array_map(null, $arr, $arr));
?>

The above example will output:

array(1) {
  ["stringkey"]=>
  array(1) {
    [0]=>
    string(5) "value"
  }
}
array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(5) "value"
    [1]=>
    string(5) "value"
  }
}
array(1) {
  ["stringkey"]=>
  string(5) "value"
}
array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(5) "value"
    [1]=>
    string(5) "value"
  }
}

See Also

  • array_filter() - Filters elements of an array using a callback function
  • array_reduce() - Iteratively reduce the array to a single value using a callback function
  • array_walk() - Apply a user supplied function to every member of an array
  • information about the callback type


Merge one or more arrays recursively

  • « array_map
  • array_merge »
  • PHP Manual
  • Array Functions
  • Merge one or more arrays recursively

array_merge_recursive

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

array_merge_recursive — Merge one or more arrays recursively

Description

array_merge_recursive ([ array $... ] ) : array

array_merge_recursive() merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.

If the input arrays have the same string keys, then the values for these keys are merged together into an array, and this is done recursively, so that if one of the values is an array itself, the function will merge it with a corresponding entry in another array too. If, however, the arrays have the same numeric key, the later value will not overwrite the original value, but will be appended.

Parameters

...

Variable list of arrays to recursively merge.

Return Values

An array of values resulted from merging the arguments together. If called without any arguments, returns an empty array.

Changelog

Version | Description
7.4.0 | This function can now be called without any parameter. Formerly, at least one parameter has been required.

Examples

Example #1 array_merge_recursive() example

<?php
$ar1 = array("color" => array("favorite" => "red"), 5);
$ar2 = array(10, "color" => array("favorite" => "green", "blue"));
$result = array_merge_recursive($ar1, $ar2);
print_r($result);
?>

The above example will output:

Array
(
    [color] => Array
        (
            [favorite] => Array
                (
                    [0] => red
                    [1] => green
                )

            [0] => blue
        )

    [0] => 5
    [1] => 10
)

See Also

  • array_merge() - Merge one or more arrays
  • array_replace_recursive() - Replaces elements from passed arrays into the first array recursively


Merge one or more arrays

  • « array_merge_recursive
  • array_multisort »
  • PHP Manual
  • Array Functions
  • Merge one or more arrays

array_merge

(PHP 4, PHP 5, PHP 7)

array_merge — Merge one or more arrays

Description

array_merge ([ array $... ] ) : array

Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

Values in the input arrays with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

Parameters

...

Variable list of arrays to merge.

Return Values

Returns the resulting array. If called without any arguments, returns an empty array.

Changelog

Version | Description
7.4.0 | This function can now be called without any parameter. Formerly, at least one parameter has been required.

Examples

Example #1 array_merge() example

<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>

The above example will output:

Array
(
    [color] => green
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)

Example #2 Simple array_merge() example

<?php
$array1 = array();
$array2 = array(1 => "data");
$result = array_merge($array1, $array2);
?>

Don't forget that numeric keys will be renumbered!

Array
(
    [0] => data
)

If you want to append array elements from the second array to the first array while not overwriting the elements from the first array and not re-indexing, use the + array union operator:

<?php
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');
$result = $array1 + $array2;
var_dump($result);
?>

The keys from the first array will be preserved. If an array key exists in both arrays, then the element from the first array will be used and the matching key's element from the second array will be ignored.

array(5) {
  [0]=>
  string(6) "zero_a"
  [2]=>
  string(5) "two_a"
  [3]=>
  string(7) "three_a"
  [1]=>
  string(5) "one_b"
  [4]=>
  string(6) "four_b"
}

Example #3 array_merge() with non-array types

<?php
$beginning = 'foo';
$end = array(1 => 'bar');
$result = array_merge((array)$beginning, (array)$end);
print_r($result);
?>

The above example will output:

    Array
    (
        [0] => foo
        [1] => bar
    )

See Also

  • array_merge_recursive() - Merge one or more arrays recursively
  • array_replace() - Replaces elements from passed arrays into the first array
  • array_combine() - Creates an array by using one array for keys and another for its values
  • array operators


Sort multiple or multi-dimensional arrays

  • « array_merge
  • array_pad »
  • PHP Manual
  • Array Functions
  • Sort multiple or multi-dimensional arrays

array_multisort

(PHP 4, PHP 5, PHP 7)

array_multisort — Sort multiple or multi-dimensional arrays

Description

array_multisort ( array &$array1 [, mixed $array1_sort_order = SORT_ASC [, mixed $array1_sort_flags = SORT_REGULAR [, mixed $... ]]] ) : bool

array_multisort() can be used to sort several arrays at once, or a multi-dimensional array by one or more dimensions.

Associative (string) keys will be maintained, but numeric keys will be re-indexed.

Note:

If two members compare as equal, their relative order in the sorted array is undefined.

Parameters

array1

An array being sorted.

array1_sort_order

The order used to sort the previous array argument. Either SORT_ASC to sort ascendingly or SORT_DESC to sort descendingly.

This argument can be swapped with array1_sort_flags or omitted entirely, in which case SORT_ASC is assumed.

array1_sort_flags

Sort options for the previous array argument:

Sorting type flags:

  • SORT_REGULAR - compare items normally (don't change types)
  • SORT_NUMERIC - compare items numerically
  • SORT_STRING - compare items as strings
  • SORT_LOCALE_STRING - compare items as strings, based on the current locale. It uses the locale, which can be changed using setlocale()
  • SORT_NATURAL - compare items as strings using "natural ordering" like natsort()
  • SORT_FLAG_CASE - can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively

This argument can be swapped with array1_sort_order or omitted entirely, in which case SORT_REGULAR is assumed.

...

More arrays, optionally followed by sort order and flags. Only elements corresponding to equivalent elements in previous arrays are compared. In other words, the sort is lexicographical.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.4.0 | The SORT_NATURAL and SORT_FLAG_CASE were added to array1_sort_flags as possible sort flags.
5.3.0 | The SORT_LOCALE_STRING was added to array1_sort_flags as possible sort flags.

Examples

Example #1 Sorting multiple arrays

<?php
$ar1 = array(10, 100, 100, 0);
$ar2 = array(1, 3, 2, 4);
array_multisort($ar1, $ar2);

var_dump($ar1);
var_dump($ar2);
?>

In this example, after sorting, the first array will contain 0, 10, 100, 100. The second array will contain 4, 1, 2, 3. The entries in the second array corresponding to the identical entries in the first array (100 and 100) were sorted as well.

array(4) {
  [0]=> int(0)
  [1]=> int(10)
  [2]=> int(100)
  [3]=> int(100)
}
array(4) {
  [0]=> int(4)
  [1]=> int(1)
  [2]=> int(2)
  [3]=> int(3)
}

Example #2 Sorting multi-dimensional array

<?php
$ar = array(
       array("10", 11, 100, 100, "a"),
       array(   1,  2, "2",   3,   1)
      );
array_multisort($ar[0], SORT_ASC, SORT_STRING,
                $ar[1], SORT_NUMERIC, SORT_DESC);
var_dump($ar);
?>

In this example, after sorting, the first array will transform to "10", 100, 100, 11, "a" (it was sorted as strings in ascending order). The second will contain 1, 3, "2", 2, 1 (sorted as numbers, in descending order).

array(2) {
  [0]=> array(5) {
    [0]=> string(2) "10"
    [1]=> int(100)
    [2]=> int(100)
    [3]=> int(11)
    [4]=> string(1) "a"
  }
  [1]=> array(5) {
    [0]=> int(1)
    [1]=> int(3)
    [2]=> string(1) "2"
    [3]=> int(2)
    [4]=> int(1)
  }
}

Example #3 Sorting database results

For this example, each element in the data array represents one row in a table. This type of dataset is typical of database records.

Example data:

volume | edition
-------+--------
    67 |       2
    86 |       1
    85 |       6
    98 |       2
    86 |       6
    67 |       7

The data as an array, called data. This would usually, for example, be obtained by looping with mysqli_fetch_assoc().

<?php
$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);
?>

In this example, we will order by volume descending, edition ascending.

We have an array of rows, but array_multisort() requires an array of columns, so we use the below code to obtain the columns, then perform the sorting.

<?php
// Obtain a list of columns
foreach ($data as $key => $row) {
    $volume[$key]  = $row['volume'];
    $edition[$key] = $row['edition'];
}

// as of PHP 5.5.0 you can use array_column() instead of the above code
$volume  = array_column($data, 'volume');
$edition = array_column($data, 'edition');

// Sort the data with volume descending, edition ascending
// Add $data as the last parameter, to sort by the common key
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
?>

The dataset is now sorted, and will look like this:

volume | edition
-------+--------
    98 |       2
    86 |       1
    86 |       6
    85 |       6
    67 |       2
    67 |       7

Example #4 Case insensitive sorting

Both SORT_STRING and SORT_REGULAR are case sensitive, strings starting with a capital letter will come before strings starting with a lowercase letter.

To perform a case insensitive sort, force the sorting order to be determined by a lowercase copy of the original array.

<?php
$array = array('Alpha', 'atomic', 'Beta', 'bank');
$array_lowercase = array_map('strtolower', $array);

array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $array);

print_r($array);
?>

The above example will output:

Array
(
    [0] => Alpha
    [1] => atomic
    [2] => bank
    [3] => Beta
)

See Also

  • usort() - Sort an array by values using a user-defined comparison function
  • The comparison of array sorting functions


Pad array to the specified length with a value

  • « array_multisort
  • array_pop »
  • PHP Manual
  • Array Functions
  • Pad array to the specified length with a value

array_pad

(PHP 4, PHP 5, PHP 7)

array_pad — Pad array to the specified length with a value

Description

array_pad ( array $array , int $size , mixed $value ) : array

array_pad() returns a copy of the array padded to size specified by size with value value. If size is positive then the array is padded on the right, if it's negative then on the left. If the absolute value of size is less than or equal to the length of the array then no padding takes place. It is possible to add at most 1048576 elements at a time.

Parameters

array

Initial array of values to pad.

size

New size of the array.

value

Value to pad if array is less than size.

Return Values

Returns a copy of the array padded to size specified by size with value value. If size is positive then the array is padded on the right, if it's negative then on the left. If the absolute value of size is less than or equal to the length of the array then no padding takes place.

Examples

Example #1 array_pad() example

<?php
$input = array(12, 10, 9);

$result = array_pad($input, 5, 0);
// result is array(12, 10, 9, 0, 0)

$result = array_pad($input, -7, -1);
// result is array(-1, -1, -1, -1, 12, 10, 9)

$result = array_pad($input, 2, "noop");
// not padded
?>

See Also

  • array_fill() - Fill an array with values
  • range() - Create an array containing a range of elements


Pop the element off the end of array

  • « array_pad
  • array_product »
  • PHP Manual
  • Array Functions
  • Pop the element off the end of array

array_pop

(PHP 4, PHP 5, PHP 7)

array_pop — Pop the element off the end of array

Description

array_pop ( array &$array ) : mixed

array_pop() pops and returns the value of the last element of array, shortening the array by one element.

Note: This function will reset() the array pointer of the input array after use.

Parameters

array

The array to get the value from.

Return Values

Returns the value of the last element of array. If array is empty (or is not an array), NULL will be returned.

Errors/Exceptions

This function will produce an error of level E_WARNING when called on a non-array.

Examples

Example #1 array_pop() example

<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_pop($stack);
print_r($stack);
?>

After this, $stack will have only 3 elements:

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
)

and raspberry will be assigned to $fruit.

See Also

  • array_push() - Push one or more elements onto the end of array
  • array_shift() - Shift an element off the beginning of array
  • array_unshift() - Prepend one or more elements to the beginning of an array


Calculate the product of values in an array

  • « array_pop
  • array_push »
  • PHP Manual
  • Array Functions
  • Calculate the product of values in an array

array_product

(PHP 5 >= 5.1.0, PHP 7)

array_product — Calculate the product of values in an array

Description

array_product ( array $array ) : number

array_product() returns the product of values in an array.

Parameters

array

The array.

Return Values

Returns the product as an integer or float.

Changelog

Version | Description
5.3.6 | The product of an empty array is now 1, when before this function would return 0 for an empty array.

Examples

Example #1 array_product() examples

<?php

$a = array(2, 4, 6, 8);
echo "product(a) = " . array_product($a) . "\n";
echo "product(array()) = " . array_product(array()) . "\n";

?>

The above example will output:

product(a) = 384
product(array()) = 1


Push one or more elements onto the end of array

  • « array_product
  • array_rand »
  • PHP Manual
  • Array Functions
  • Push one or more elements onto the end of array

array_push

(PHP 4, PHP 5, PHP 7)

array_push — Push one or more elements onto the end of array

Description

array_push ( array &$array [, mixed $... ] ) : int

array_push() treats array as a stack, and pushes the passed variables onto the end of array. The length of array increases by the number of variables pushed. Has the same effect as:

<?php
$array[] = $var;
?>
repeated for each passed value.

Note: If you use array_push() to add one element to the array, it's better to use $array[] = because in that way there is no overhead of calling a function.

Note: array_push() will raise a warning if the first argument is not an array. This differs from the $var[] behaviour where a new array is created.

Parameters

array

The input array.

...

The values to push onto the end of the array.

Return Values

Returns the new number of elements in the array.

Changelog

Version | Description
7.3.0 | This function can now be called with only one parameter. Formerly, at least two parameters have been required.

Examples

Example #1 array_push() example

<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
?>

The above example will output:

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)

See Also

  • array_pop() - Pop the element off the end of array
  • array_shift() - Shift an element off the beginning of array
  • array_unshift() - Prepend one or more elements to the beginning of an array


Pick one or more random keys out of an array

  • « array_push
  • array_reduce »
  • PHP Manual
  • Array Functions
  • Pick one or more random keys out of an array

array_rand

(PHP 4, PHP 5, PHP 7)

array_rand — Pick one or more random keys out of an array

Description

array_rand ( array $array [, int $num = 1 ] ) : mixed

Picks one or more random entries out of an array, and returns the key (or keys) of the random entries. It uses a pseudo random number generator that is not suitable for cryptographic purposes.

Parameters

array

The input array.

num

Specifies how many entries should be picked.

Return Values

When picking only one entry, array_rand() returns the key for a random entry. Otherwise, an array of keys for the random entries is returned. This is done so that random keys can be picked from the array as well as random values. Trying to pick more elements than there are in the array will result in an E_WARNING level error, and NULL will be returned.

Changelog

Version | Description
7.1.0 | The internal randomization algorithm has been changed to use the » Mersenne Twister Random Number Generator instead of the libc rand function.
5.2.10 | The resulting array of keys is no longer shuffled.

Examples

Example #1 array_rand() example

<?php
$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";
?>

See Also

  • shuffle() - Shuffle an array


Iteratively reduce the array to a single value using a callback function

  • « array_rand
  • array_replace_recursive »
  • PHP Manual
  • Array Functions
  • Iteratively reduce the array to a single value using a callback function

array_reduce

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

array_reduce — Iteratively reduce the array to a single value using a callback function

Description

array_reduce ( array $array , callable $callback [, mixed $initial = NULL ] ) : mixed

array_reduce() applies iteratively the callback function to the elements of the array, so as to reduce the array to a single value.

Parameters

array

The input array.

callback
callback ( mixed $carry , mixed $item ) : mixed
carry

Holds the return value of the previous iteration; in the case of the first iteration it instead holds the value of initial.

item

Holds the value of the current iteration.

initial

If the optional initial is available, it will be used at the beginning of the process, or as a final result in case the array is empty.

Return Values

Returns the resulting value.

If the array is empty and initial is not passed, array_reduce() returns NULL.

Changelog

Version | Description
5.3.0 | Changed initial to allow mixed, previously integer.

Examples

Example #1 array_reduce() example

<?php
function sum($carry, $item)
{
    $carry += $item;
    return $carry;
}

function product($carry, $item)
{
    $carry *= $item;
    return $carry;
}

$a = array(1, 2, 3, 4, 5);
$x = array();

var_dump(array_reduce($a, "sum")); // int(15)
var_dump(array_reduce($a, "product", 10)); // int(1200), because: 10*1*2*3*4*5
var_dump(array_reduce($x, "sum", "No data to reduce")); // string(17) "No data to reduce"
?>

See Also

  • array_filter() - Filters elements of an array using a callback function
  • array_map() - Applies the callback to the elements of the given arrays
  • array_unique() - Removes duplicate values from an array
  • array_count_values() - Counts all the values of an array


Replaces elements from passed arrays into the first array recursively

  • « array_reduce
  • array_replace »
  • PHP Manual
  • Array Functions
  • Replaces elements from passed arrays into the first array recursively

array_replace_recursive

(PHP 5 >= 5.3.0, PHP 7)

array_replace_recursive — Replaces elements from passed arrays into the first array recursively

Description

array_replace_recursive ( array $array1 [, array $... ] ) : array

array_replace_recursive() replaces the values of array1 with the same values from all the following arrays. If a key from the first array exists in the second array, its value will be replaced by the value from the second array. If the key exists in the second array, and not the first, it will be created in the first array. If a key only exists in the first array, it will be left as is. If several arrays are passed for replacement, they will be processed in order, the later array overwriting the previous values.

array_replace_recursive() is recursive : it will recurse into arrays and apply the same process to the inner value.

When the value in the first array is scalar, it will be replaced by the value in the second array, may it be scalar or array. When the value in the first array and the second array are both arrays, array_replace_recursive() will replace their respective value recursively.

Parameters

array1

The array in which elements are replaced.

...

Optional. Arrays from which elements will be extracted.

Return Values

Returns an array, or NULL if an error occurs.

Examples

Example #1 array_replace_recursive() example

<?php
$base = array('citrus' => array( "orange") , 'berries' => array("blackberry", "raspberry"), );
$replacements = array('citrus' => array('pineapple'), 'berries' => array('blueberry'));

$basket = array_replace_recursive($base, $replacements);
print_r($basket);

$basket = array_replace($base, $replacements);
print_r($basket);
?>

The above example will output:

Array
(
    [citrus] => Array
        (
            [0] => pineapple
        )

    [berries] => Array
        (
            [0] => blueberry
            [1] => raspberry
        )

)
Array
(
    [citrus] => Array
        (
            [0] => pineapple
        )

    [berries] => Array
        (
            [0] => blueberry
        )

)

Example #2 array_replace_recursive() and recursive behavior

<?php
$base = array('citrus' => array("orange") , 'berries' => array("blackberry", "raspberry"), 'others' => 'banana' );
$replacements = array('citrus' => 'pineapple', 'berries' => array('blueberry'), 'others' => array('litchis'));
$replacements2 = array('citrus' => array('pineapple'), 'berries' => array('blueberry'), 'others' => 'litchis');

$basket = array_replace_recursive($base, $replacements, $replacements2);
print_r($basket);

?>

The above example will output:

Array
(
    [citrus] => Array
        (
            [0] => pineapple
        )

    [berries] => Array
        (
            [0] => blueberry
            [1] => raspberry
        )

    [others] => litchis
)

See Also

  • array_replace() - Replaces elements from passed arrays into the first array
  • array_merge_recursive() - Merge one or more arrays recursively


Replaces elements from passed arrays into the first array

  • « array_replace_recursive
  • array_reverse »
  • PHP Manual
  • Array Functions
  • Replaces elements from passed arrays into the first array

array_replace

(PHP 5 >= 5.3.0, PHP 7)

array_replace — Replaces elements from passed arrays into the first array

Description

array_replace ( array $array1 [, array $... ] ) : array

array_replace() replaces the values of array1 with values having the same keys in each of the following arrays. If a key from the first array exists in the second array, its value will be replaced by the value from the second array. If the key exists in the second array, and not the first, it will be created in the first array. If a key only exists in the first array, it will be left as is. If several arrays are passed for replacement, they will be processed in order, the later arrays overwriting the previous values.

array_replace() is not recursive : it will replace values in the first array by whatever type is in the second array.

Parameters

array1

The array in which elements are replaced.

...

Arrays from which elements will be extracted. Values from later arrays overwrite the previous values.

Return Values

Returns an array, or NULL if an error occurs.

Examples

Example #1 array_replace() example

<?php
$base = array("orange", "banana", "apple", "raspberry");
$replacements = array(0 => "pineapple", 4 => "cherry");
$replacements2 = array(0 => "grape");

$basket = array_replace($base, $replacements, $replacements2);
print_r($basket);
?>

The above example will output:

Array
(
    [0] => grape
    [1] => banana
    [2] => apple
    [3] => raspberry
    [4] => cherry
)

See Also

  • array_replace_recursive() - Replaces elements from passed arrays into the first array recursively
  • array_merge() - Merge one or more arrays


Return an array with elements in reverse order

  • « array_replace
  • array_search »
  • PHP Manual
  • Array Functions
  • Return an array with elements in reverse order

array_reverse

(PHP 4, PHP 5, PHP 7)

array_reverse — Return an array with elements in reverse order

Description

array_reverse ( array $array [, bool $preserve_keys = FALSE ] ) : array

Takes an input array and returns a new array with the order of the elements reversed.

Parameters

array

The input array.

preserve_keys

If set to TRUE numeric keys are preserved. Non-numeric keys are not affected by this setting and will always be preserved.

Return Values

Returns the reversed array.

Examples

Example #1 array_reverse() example

<?php
$input  = array("php", 4.0, array("green", "red"));
$reversed = array_reverse($input);
$preserved = array_reverse($input, true);

print_r($input);
print_r($reversed);
print_r($preserved);
?>

The above example will output:

Array
(
    [0] => php
    [1] => 4
    [2] => Array
        (
            [0] => green
            [1] => red
        )

)
Array
(
    [0] => Array
        (
            [0] => green
            [1] => red
        )

    [1] => 4
    [2] => php
)
Array
(
    [2] => Array
        (
            [0] => green
            [1] => red
        )

    [1] => 4
    [0] => php
)

See Also

  • array_flip() - Exchanges all keys with their associated values in an array


Searches the array for a given value and returns the first corresponding key if successful

  • « array_reverse
  • array_shift »
  • PHP Manual
  • Array Functions
  • Searches the array for a given value and returns the first corresponding key if successful

array_search

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

array_search — Searches the array for a given value and returns the first corresponding key if successful

Description

array_search ( mixed $needle , array $haystack [, bool $strict = FALSE ] ) : mixed

Searches for needle in haystack.

Parameters

needle

The searched value.

Note:

If needle is a string, the comparison is done in a case-sensitive manner.

haystack

The array.

strict

If the third parameter strict is set to TRUE then the array_search() function will search for identical elements in the haystack. This means it will also perform a strict type comparison of the needle in the haystack, and objects must be the same instance.

Return Values

Returns the key for needle if it is found in the array, FALSE otherwise.

If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Changelog

Version | Description
5.3.0 | As with all internal PHP functions as of 5.3.0, array_search() returns NULL if invalid parameters are passed to it.

Examples

Example #1 array_search() example

<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;
?>

See Also

  • array_keys() - Return all the keys or a subset of the keys of an array
  • array_values() - Return all the values of an array
  • array_key_exists() - Checks if the given key or index exists in the array
  • in_array() - Checks if a value exists in an array


Shift an element off the beginning of array

  • « array_search
  • array_slice »
  • PHP Manual
  • Array Functions
  • Shift an element off the beginning of array

array_shift

(PHP 4, PHP 5, PHP 7)

array_shift — Shift an element off the beginning of array

Description

array_shift ( array &$array ) : mixed

array_shift() shifts the first value of the array off and returns it, shortening the array by one element and moving everything down. All numerical array keys will be modified to start counting from zero while literal keys won't be affected.

Note: This function will reset() the array pointer of the input array after use.

Parameters

array

The input array.

Return Values

Returns the shifted value, or NULL if array is empty or is not an array.

Examples

Example #1 array_shift() example

<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);
print_r($stack);
?>

The above example will output:

Array
(
    [0] => banana
    [1] => apple
    [2] => raspberry
)

and orange will be assigned to $fruit.

See Also

  • array_unshift() - Prepend one or more elements to the beginning of an array
  • array_push() - Push one or more elements onto the end of array
  • array_pop() - Pop the element off the end of array


Extract a slice of the array

  • « array_shift
  • array_splice »
  • PHP Manual
  • Array Functions
  • Extract a slice of the array

array_slice

(PHP 4, PHP 5, PHP 7)

array_slice — Extract a slice of the array

Description

array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = FALSE ]] ) : array

array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters.

Parameters

array

The input array.

offset

If offset is non-negative, the sequence will start at that offset in the array.

If offset is negative, the sequence will start that far from the end of the array.

Note:

The offset parameter denotes the position in the array, not the key.

length

If length is given and is positive, then the sequence will have up to that many elements in it.

If the array is shorter than the length, then only the available array elements will be present.

If length is given and is negative then the sequence will stop that many elements from the end of the array.

If it is omitted, then the sequence will have everything from offset up until the end of the array.

preserve_keys

Note:

array_slice() will reorder and reset the integer array indices by default. This behaviour can be changed by setting preserve_keys to TRUE. String keys are always preserved, regardless of this parameter.

Return Values

Returns the slice. If the offset is larger than the size of the array, an empty array is returned.

Changelog

Version | Description
5.2.4 | The default value of the length parameter was changed to NULL. A NULL length now tells the function to use the length of array. Prior to this version, a NULL length was taken to mean a zero length (nothing will be returned).
5.0.2 | The optional preserve_keys parameter was added.

Examples

Example #1 array_slice() examples

<?php
$input = array("a", "b", "c", "d", "e");

$output = array_slice($input, 2);      // returns "c", "d", and "e"
$output = array_slice($input, -2, 1);  // returns "d"
$output = array_slice($input, 0, 3);   // returns "a", "b", and "c"

// note the differences in the array keys
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));
?>

The above example will output:

Array
(
    [0] => c
    [1] => d
)
Array
(
    [2] => c
    [3] => d
)

Example #2 array_slice() and one-based array

<?php
$input = array(1 => "a", "b", "c", "d", "e");
print_r(array_slice($input, 1, 2));
?>

The above example will output:

Array
(
    [0] => b
    [1] => c
)

Example #3 array_slice() and array with mixed keys

<?php
$ar = array('a'=>'apple', 'b'=>'banana', '42'=>'pear', 'd'=>'orange');
print_r(array_slice($ar, 0, 3));
print_r(array_slice($ar, 0, 3, true));
?>

The above example will output:

Array
(
    [a] => apple
    [b] => banana
    [0] => pear
)
Array
(
    [a] => apple
    [b] => banana
    [42] => pear
)

See Also

  • array_chunk() - Split an array into chunks
  • array_splice() - Remove a portion of the array and replace it with something else
  • unset() - Unset a given variable


Remove a portion of the array and replace it with something else

  • « array_slice
  • array_sum »
  • PHP Manual
  • Array Functions
  • Remove a portion of the array and replace it with something else

array_splice

(PHP 4, PHP 5, PHP 7)

array_splice — Remove a portion of the array and replace it with something else

Description

array_splice ( array &$input , int $offset [, int $length = count($input) [, mixed $replacement = array() ]] ) : array

Removes the elements designated by offset and length from the input array, and replaces them with the elements of the replacement array, if supplied.

Note:

Numerical keys in input are not preserved.

Note: If replacement is not an array, it will be typecast to one (i.e. (array) $replacement). This may result in unexpected behavior when using an object or NULL replacement.

Parameters

input

The input array.

offset

If offset is positive then the start of the removed portion is at that offset from the beginning of the input array.

If offset is negative then the start of the removed portion is at that offset from the end of the input array.

length

If length is omitted, removes everything from offset to the end of the array.

If length is specified and is positive, then that many elements will be removed.

If length is specified and is negative, then the end of the removed portion will be that many elements from the end of the array.

If length is specified and is zero, no elements will be removed.

Tip

To remove everything from offset to the end of the array when replacement is also specified, use count($input) for length.

replacement

If replacement array is specified, then the removed elements are replaced with elements from this array.

If offset and length are such that nothing is removed, then the elements from the replacement array are inserted in the place specified by the offset.

Note:

Keys in the replacement array are not preserved.

If replacement is just one element it is not necessary to put array() or square brackets around it, unless the element is an array itself, an object or NULL.

Return Values

Returns an array consisting of the extracted elements.

Examples

Example #1 array_splice() examples

<?php
$input = array("red", "green", "blue", "yellow");
array_splice($input, 2);
var_dump($input);

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, -1);
var_dump($input);

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, count($input), "orange");
var_dump($input);

$input = array("red", "green", "blue", "yellow");
array_splice($input, -1, 1, array("black", "maroon"));
var_dump($input);
?>

The above example will output:

array(2) {
  [0]=>
  string(3) "red"
  [1]=>
  string(5) "green"
}
array(2) {
  [0]=>
  string(3) "red"
  [1]=>
  string(6) "yellow"
}
array(2) {
  [0]=>
  string(3) "red"
  [1]=>
  string(6) "orange"
}
array(5) {
  [0]=>
  string(3) "red"
  [1]=>
  string(5) "green"
  [2]=>
  string(4) "blue"
  [3]=>
  string(5) "black"
  [4]=>
  string(6) "maroon"
}

Example #2 Equivalent statements to various array_splice() examples

The following statements are equivalent:

<?php

// append two elements to $input
array_push($input, $x, $y);
array_splice($input, count($input), 0, array($x, $y));

// remove the last element of $input
array_pop($input);
array_splice($input, -1);

// remove the first element of $input
array_shift($input);
array_splice($input, 0, 1);

// insert an element at the start of $input
array_unshift($input, $x, $y);
array_splice($input, 0, 0, array($x, $y));

// replace the value in $input at index $x
$input[$x] = $y; // for arrays where key equals offset
array_splice($input, $x, 1, $y);

?>

See Also

  • array_merge() - Merge one or more arrays
  • array_slice() - Extract a slice of the array
  • unset() - Unset a given variable


Calculate the sum of values in an array

  • « array_splice
  • array_udiff_assoc »
  • PHP Manual
  • Array Functions
  • Calculate the sum of values in an array

array_sum

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

array_sum — Calculate the sum of values in an array

Description

array_sum ( array $array ) : number

array_sum() returns the sum of values in an array.

Parameters

array

The input array.

Return Values

Returns the sum of values as an integer or float; 0 if the array is empty.

Examples

Example #1 array_sum() examples

<?php
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";

$b = array("a" => 1.2, "b" => 2.3, "c" => 3.4);
echo "sum(b) = " . array_sum($b) . "\n";
?>

The above example will output:

sum(a) = 20
sum(b) = 6.9


Computes the difference of arrays with additional index check, compares data by a callback function

  • « array_sum
  • array_udiff_uassoc »
  • PHP Manual
  • Array Functions
  • Computes the difference of arrays with additional index check, compares data by a callback function

array_udiff_assoc

(PHP 5, PHP 7)

array_udiff_assoc — Computes the difference of arrays with additional index check, compares data by a callback function

Description

array_udiff_assoc ( array $array1 , array $array2 [, array $... ], callable $value_compare_func ) : array

Computes the difference of arrays with additional index check, compares data by a callback function.

Note: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using, for example, array_udiff_assoc($array1[0], $array2[0], "some_comparison_func");.

Parameters

array1

The first array.

array2

The second array.

value_compare_func

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. Note that before PHP 7.0.0 this integer had to be in the range from -2147483648 to 2147483647.

callback ( mixed $a, mixed $b ) : int

Return Values

array_udiff_assoc() returns an array containing all the values from array1 that are not present in any of the other arguments. Note that the keys are used in the comparison unlike array_diff() and array_udiff(). The comparison of arrays' data is performed by using an user-supplied callback. In this aspect the behaviour is opposite to the behaviour of array_diff_assoc() which uses internal function for comparison.

Examples

Example #1 array_udiff_assoc() example

<?php
class cr {
    private $priv_member;
    function cr($val)
    {
        $this->priv_member = $val;
    }

    static function comp_func_cr($a, $b)
    {
        if ($a->priv_member === $b->priv_member) return 0;
        return ($a->priv_member > $b->priv_member)? 1:-1;
    }
}

$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);

$result = array_udiff_assoc($a, $b, array("cr", "comp_func_cr"));
print_r($result);
?>

The above example will output:

Array
(
    [0.1] => cr Object
        (
            [priv_member:private] => 9
        )

    [0.5] => cr Object
        (
            [priv_member:private] => 12
        )

    [0] => cr Object
        (
            [priv_member:private] => 23
        )
)

In our example above you see the "1" => new cr(4) pair is present in both arrays and thus it is not in the output from the function.

See Also

  • array_diff() - Computes the difference of arrays
  • array_diff_assoc() - Computes the difference of arrays with additional index check
  • array_diff_uassoc() - Computes the difference of arrays with additional index check which is performed by a user supplied callback function
  • array_udiff() - Computes the difference of arrays by using a callback function for data comparison
  • array_udiff_uassoc() - Computes the difference of arrays with additional index check, compares data and indexes by a callback function
  • array_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • array_uintersect() - Computes the intersection of arrays, compares data by a callback function
  • array_uintersect_assoc() - Computes the intersection of arrays with additional index check, compares data by a callback function
  • array_uintersect_uassoc() - Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions


Computes the difference of arrays with additional index check, compares data and indexes by a callback function

  • « array_udiff_assoc
  • array_udiff »
  • PHP Manual
  • Array Functions
  • Computes the difference of arrays with additional index check, compares data and indexes by a callback function

array_udiff_uassoc

(PHP 5, PHP 7)

array_udiff_uassoc — Computes the difference of arrays with additional index check, compares data and indexes by a callback function

Description

array_udiff_uassoc ( array $array1 , array $array2 [, array $... ], callable $value_compare_func , callable $key_compare_func ) : array

Computes the difference of arrays with additional index check, compares data and indexes by a callback function.

Note that the keys are used in the comparison unlike array_diff() and array_udiff().

Parameters

array1

The first array.

array2

The second array.

value_compare_func

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. Note that before PHP 7.0.0 this integer had to be in the range from -2147483648 to 2147483647.

callback ( mixed $a, mixed $b ) : int
key_compare_func

The comparison of keys (indices) is done also by the callback function key_compare_func. This behaviour is unlike what array_udiff_assoc() does, since the latter compares the indices by using an internal function.

Return Values

Returns an array containing all the values from array1 that are not present in any of the other arguments.

Examples

Example #1 array_udiff_uassoc() example

<?php
class cr {
    private $priv_member;
    function cr($val)
    {
        $this->priv_member = $val;
    }

    static function comp_func_cr($a, $b)
    {
        if ($a->priv_member === $b->priv_member) return 0;
        return ($a->priv_member > $b->priv_member)? 1:-1;
    }

    static function comp_func_key($a, $b)
    {
        if ($a === $b) return 0;
        return ($a > $b)? 1:-1;
    }
}
$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);

$result = array_udiff_uassoc($a, $b, array("cr", "comp_func_cr"), array("cr", "comp_func_key"));
print_r($result);
?>

The above example will output:

Array
(
    [0.1] => cr Object
        (
            [priv_member:private] => 9
        )

    [0.5] => cr Object
        (
            [priv_member:private] => 12
        )

    [0] => cr Object
        (
            [priv_member:private] => 23
        )
)

In our example above you see the "1" => new cr(4) pair is present in both arrays and thus it is not in the output from the function. Keep in mind that you have to supply 2 callback functions.

Notes

Note: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using, for example, array_udiff_uassoc($array1[0], $array2[0], "data_compare_func", "key_compare_func");.

See Also

  • array_diff() - Computes the difference of arrays
  • array_diff_assoc() - Computes the difference of arrays with additional index check
  • array_udiff() - Computes the difference of arrays by using a callback function for data comparison
  • array_udiff_assoc() - Computes the difference of arrays with additional index check, compares data by a callback function
  • array_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • array_uintersect() - Computes the intersection of arrays, compares data by a callback function
  • array_uintersect_assoc() - Computes the intersection of arrays with additional index check, compares data by a callback function
  • array_uintersect_uassoc() - Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions


Computes the difference of arrays by using a callback function for data comparison

  • « array_udiff_uassoc
  • array_uintersect_assoc »
  • PHP Manual
  • Array Functions
  • Computes the difference of arrays by using a callback function for data comparison

array_udiff

(PHP 5, PHP 7)

array_udiff — Computes the difference of arrays by using a callback function for data comparison

Description

array_udiff ( array $array1 , array $array2 [, array $... ], callable $value_compare_func ) : array

Computes the difference of arrays by using a callback function for data comparison. This is unlike array_diff() which uses an internal function for comparing the data.

Parameters

array1

The first array.

array2

The second array.

value_compare_func

The callback comparison function.

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. Note that before PHP 7.0.0 this integer had to be in the range from -2147483648 to 2147483647.

callback ( mixed $a, mixed $b ) : int

Return Values

Returns an array containing all the values of array1 that are not present in any of the other arguments.

Examples

Example #1 array_udiff() example using stdClass Objects

<?php
// Arrays to compare
$array1 = array(new stdclass, new stdclass,
                new stdclass, new stdclass,
               );

$array2 = array(
                new stdclass, new stdclass,
               );

// Set some properties for each object
$array1[0]->width = 11; $array1[0]->height = 3;
$array1[1]->width = 7;  $array1[1]->height = 1;
$array1[2]->width = 2;  $array1[2]->height = 9;
$array1[3]->width = 5;  $array1[3]->height = 7;

$array2[0]->width = 7;  $array2[0]->height = 5;
$array2[1]->width = 9;  $array2[1]->height = 2;

function compare_by_area($a, $b) {
    $areaA = $a->width * $a->height;
    $areaB = $b->width * $b->height;

    if ($areaA < $areaB) {
        return -1;
    } elseif ($areaA > $areaB) {
        return 1;
    } else {
        return 0;
    }
}

print_r(array_udiff($array1, $array2, 'compare_by_area'));
?>

The above example will output:

Array
(
    [0] => stdClass Object
        (
            [width] => 11
            [height] => 3
        )

    [1] => stdClass Object
        (
            [width] => 7
            [height] => 1
        )

)

Example #2 array_udiff() example using DateTime Objects

<?php
class MyCalendar {
    public $free = array();
    public $booked = array();

    public function __construct($week = 'now') {
        $start = new DateTime($week);
        $start->modify('Monday this week midnight');
        $end = clone $start;
        $end->modify('Friday this week midnight');
        $interval = new DateInterval('P1D');
        foreach (new DatePeriod($start, $interval, $end) as $freeTime) {
            $this->free[] = $freeTime;
        }
    }

    public function bookAppointment(DateTime $date, $note) {
        $this->booked[] = array('date' => $date->modify('midnight'), 'note' => $note);
    }

    public function checkAvailability() {
        return array_udiff($this->free, $this->booked, array($this, 'customCompare'));
    }

    public function customCompare($free, $booked) {
        if (is_array($free)) $a = $free['date'];
        else $a = $free;
        if (is_array($booked)) $b = $booked['date'];
        else $b = $booked;
        if ($a == $b) {
            return 0;
        } elseif ($a > $b) {
            return 1;
        } else {
            return -1;
        }
    }
}

// Create a calendar for weekly appointments
$myCalendar = new MyCalendar;

// Book some appointments for this week
$myCalendar->bookAppointment(new DateTime('Monday this week'), "Cleaning GoogleGuy's apartment.");
$myCalendar->bookAppointment(new DateTime('Wednesday this week'), "Going on a snowboarding trip.");
$myCalendar->bookAppointment(new DateTime('Friday this week'), "Fixing buggy code.");

// Check availability of days by comparing $booked dates against $free dates
echo "I'm available on the following days this week...\n\n";
foreach ($myCalendar->checkAvailability() as $free) {
    echo $free->format('l'), "\n";
}
echo "\n\n";
echo "I'm busy on the following days this week...\n\n";
foreach ($myCalendar->booked as $booked) {
    echo $booked['date']->format('l'), ": ", $booked['note'], "\n";
}
?>

The above example will output:

I'm available on the following days this week...

Tuesday
Thursday

I'm busy on the following days this week...

Monday: Cleaning GoogleGuy's apartment.
Wednesday: Going on a snowboarding trip.
Friday: Fixing buggy code.

Notes

Note: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_udiff($array1[0], $array2[0], "data_compare_func");.

See Also

  • array_diff() - Computes the difference of arrays
  • array_diff_assoc() - Computes the difference of arrays with additional index check
  • array_diff_uassoc() - Computes the difference of arrays with additional index check which is performed by a user supplied callback function
  • array_udiff_assoc() - Computes the difference of arrays with additional index check, compares data by a callback function
  • array_udiff_uassoc() - Computes the difference of arrays with additional index check, compares data and indexes by a callback function
  • array_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • array_uintersect() - Computes the intersection of arrays, compares data by a callback function
  • array_uintersect_assoc() - Computes the intersection of arrays with additional index check, compares data by a callback function
  • array_uintersect_uassoc() - Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions


Computes the intersection of arrays with additional index check, compares data by a callback function

  • « array_udiff
  • array_uintersect_uassoc »
  • PHP Manual
  • Array Functions
  • Computes the intersection of arrays with additional index check, compares data by a callback function

array_uintersect_assoc

(PHP 5, PHP 7)

array_uintersect_assoc — Computes the intersection of arrays with additional index check, compares data by a callback function

Description

array_uintersect_assoc ( array $array1 , array $array2 [, array $... ], callable $value_compare_func ) : array

Computes the intersection of arrays with additional index check, compares data by a callback function.

Note that the keys are used in the comparison unlike in array_uintersect(). The data is compared by using a callback function.

Parameters

array1

The first array.

array2

The second array.

value_compare_func

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. Note that before PHP 7.0.0 this integer had to be in the range from -2147483648 to 2147483647.

callback ( mixed $a, mixed $b ) : int

Return Values

Returns an array containing all the values of array1 that are present in all the arguments.

Examples

Example #1 array_uintersect_assoc() example

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_uintersect_assoc($array1, $array2, "strcasecmp"));
?>

The above example will output:

Array
(
    [a] => green
)

See Also

  • array_uintersect() - Computes the intersection of arrays, compares data by a callback function
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • array_intersect_uassoc() - Computes the intersection of arrays with additional index check, compares indexes by a callback function
  • array_uintersect_uassoc() - Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions


Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions

  • « array_uintersect_assoc
  • array_uintersect »
  • PHP Manual
  • Array Functions
  • Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions

array_uintersect_uassoc

(PHP 5, PHP 7)

array_uintersect_uassoc — Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions

Description

array_uintersect_uassoc ( array $array1 , array $array2 [, array $... ], callable $value_compare_func , callable $key_compare_func ) : array

Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions.

Parameters

array1

The first array.

array2

The second array.

value_compare_func

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. Note that before PHP 7.0.0 this integer had to be in the range from -2147483648 to 2147483647.

callback ( mixed $a, mixed $b ) : int
key_compare_func

Key comparison callback function.

Return Values

Returns an array containing all the values of array1 that are present in all the arguments.

Examples

Example #1 array_uintersect_uassoc() example

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_uintersect_uassoc($array1, $array2, "strcasecmp", "strcasecmp"));
?>

The above example will output:

Array
(
    [a] => green
    [b] => brown
)

See Also

  • array_uintersect() - Computes the intersection of arrays, compares data by a callback function
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • array_intersect_uassoc() - Computes the intersection of arrays with additional index check, compares indexes by a callback function
  • array_uintersect_assoc() - Computes the intersection of arrays with additional index check, compares data by a callback function


Computes the intersection of arrays, compares data by a callback function

  • « array_uintersect_uassoc
  • array_unique »
  • PHP Manual
  • Array Functions
  • Computes the intersection of arrays, compares data by a callback function

array_uintersect

(PHP 5, PHP 7)

array_uintersect — Computes the intersection of arrays, compares data by a callback function

Description

array_uintersect ( array $array1 , array $array2 [, array $... ], callable $value_compare_func ) : array

Computes the intersection of arrays, compares data by a callback function.

Parameters

array1

The first array.

array2

The second array.

value_compare_func

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. Note that before PHP 7.0.0 this integer had to be in the range from -2147483648 to 2147483647.

callback ( mixed $a, mixed $b ) : int

Return Values

Returns an array containing all the values of array1 that are present in all the arguments.

Examples

Example #1 array_uintersect() example

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_uintersect($array1, $array2, "strcasecmp"));
?>

The above example will output:

Array
(
    [a] => green
    [b] => brown
    [0] => red
)

See Also

  • array_intersect() - Computes the intersection of arrays
  • array_intersect_assoc() - Computes the intersection of arrays with additional index check
  • array_uintersect_assoc() - Computes the intersection of arrays with additional index check, compares data by a callback function
  • array_uintersect_uassoc() - Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions


Removes duplicate values from an array

  • « array_uintersect
  • array_unshift »
  • PHP Manual
  • Array Functions
  • Removes duplicate values from an array

array_unique

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

array_unique — Removes duplicate values from an array

Description

array_unique ( array $array [, int $sort_flags = SORT_STRING ] ) : array

Takes an input array and returns a new array without duplicate values.

Note that keys are preserved. If multiple elements compare equal under the given sort_flags, then the key and value of the first equal element will be retained.

Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2 i.e. when the string representation is the same, the first element will be used.

Parameters

array

The input array.

sort_flags

The optional second parameter sort_flags may be used to modify the sorting behavior using these values:

Sorting type flags:

  • SORT_REGULAR - compare items normally (don't change types)
  • SORT_NUMERIC - compare items numerically
  • SORT_STRING - compare items as strings
  • SORT_LOCALE_STRING - compare items as strings, based on the current locale.

Return Values

Returns the filtered array.

Changelog

Version | Description
7.2.0 | If sort_flags is SORT_STRING, formerly array has been copied and non-unique elements have been removed (without packing the array afterwards), but now a new array is built by adding the unique elements. This can result in different numeric indexes.
5.2.10 | Changed the default value of sort_flags back to SORT_STRING.
5.2.9 | Added the optional sort_flags defaulting to SORT_REGULAR. Prior to 5.2.9, this function used to sort the array with SORT_STRING internally.

Examples

Example #1 array_unique() example

<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>

The above example will output:

Array
(
    [a] => green
    [0] => red
    [1] => blue
)

Example #2 array_unique() and types

<?php
$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);
?>

The above example will output:

array(2) {
  [0] => int(4)
  [2] => string(1) "3"
}

See Also

  • array_count_values() - Counts all the values of an array

Notes

Note: Note that array_unique() is not intended to work on multi dimensional arrays.


Prepend one or more elements to the beginning of an array

  • « array_unique
  • array_values »
  • PHP Manual
  • Array Functions
  • Prepend one or more elements to the beginning of an array

array_unshift

(PHP 4, PHP 5, PHP 7)

array_unshift — Prepend one or more elements to the beginning of an array

Description

array_unshift ( array &$array [, mixed $... ] ) : int

array_unshift() prepends passed elements to the front of the array. Note that the list of elements is prepended as a whole, so that the prepended elements stay in the same order. All numerical array keys will be modified to start counting from zero while literal keys won't be changed.

Parameters

array

The input array.

...

The values to prepend.

Return Values

Returns the new number of elements in the array.

Changelog

Version | Description
7.3.0 | This function can now be called with only one parameter. Formerly, at least two parameters have been required.

Examples

Example #1 array_unshift() example

<?php
$queue = array("orange", "banana");
array_unshift($queue, "apple", "raspberry");
print_r($queue);
?>

The above example will output:

Array
(
    [0] => apple
    [1] => raspberry
    [2] => orange
    [3] => banana
)

See Also

  • array_shift() - Shift an element off the beginning of array
  • array_push() - Push one or more elements onto the end of array
  • array_pop() - Pop the element off the end of array


Return all the values of an array

  • « array_unshift
  • array_walk_recursive »
  • PHP Manual
  • Array Functions
  • Return all the values of an array

array_values

(PHP 4, PHP 5, PHP 7)

array_values — Return all the values of an array

Description

array_values ( array $array ) : array

array_values() returns all the values from the array and indexes the array numerically.

Parameters

array

The array.

Return Values

Returns an indexed array of values.

Examples

Example #1 array_values() example

<?php
$array = array("size" => "XL", "color" => "gold");
print_r(array_values($array));
?>

The above example will output:

Array
(
    [0] => XL
    [1] => gold
)

See Also

  • array_keys() - Return all the keys or a subset of the keys of an array
  • array_combine() - Creates an array by using one array for keys and another for its values


Apply a user function recursively to every member of an array

  • « array_values
  • array_walk »
  • PHP Manual
  • Array Functions
  • Apply a user function recursively to every member of an array

array_walk_recursive

(PHP 5, PHP 7)

array_walk_recursive — Apply a user function recursively to every member of an array

Description

array_walk_recursive ( array &$array , callable $callback [, mixed $userdata = NULL ] ) : bool

Applies the user-defined callback function to each element of the array. This function will recurse into deeper arrays.

Parameters

array

The input array.

callback

Typically, callback takes on two parameters. The array parameter's value being the first, and the key/index second.

Note:

If callback needs to be working with the actual values of the array, specify the first parameter of callback as a reference. Then, any changes made to those elements will be made in the original array itself.

userdata

If the optional userdata parameter is supplied, it will be passed as the third parameter to the callback.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 array_walk_recursive() example

<?php
$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');

function test_print($item, $key)
{
    echo "$key holds $item\n";
}

array_walk_recursive($fruits, 'test_print');
?>

The above example will output:

a holds apple
b holds banana
sour holds lemon

You may notice that the key 'sweet' is never displayed. Any key that holds an array will not be passed to the function.

See Also

  • array_walk() - Apply a user supplied function to every member of an array
  • information about the callback type


Apply a user supplied function to every member of an array

  • « array_walk_recursive
  • array »
  • PHP Manual
  • Array Functions
  • Apply a user supplied function to every member of an array

array_walk

(PHP 4, PHP 5, PHP 7)

array_walk — Apply a user supplied function to every member of an array

Description

array_walk ( array &$array , callable $callback [, mixed $userdata = NULL ] ) : bool

Applies the user-defined callback function to each element of the array array.

array_walk() is not affected by the internal array pointer of array. array_walk() will walk through the entire array regardless of pointer position.

Parameters

array

The input array.

callback

Typically, callback takes on two parameters. The array parameter's value being the first, and the key/index second.

Note:

If callback needs to be working with the actual values of the array, specify the first parameter of callback as a reference. Then, any changes made to those elements will be made in the original array itself.

Note:

Many internal functions (for example strtolower()) will throw a warning if more than the expected number of argument are passed in and are not usable directly as a callback.

Only the values of the array may potentially be changed; its structure cannot be altered, i.e., the programmer cannot add, unset or reorder elements. If the callback does not respect this requirement, the behavior of this function is undefined, and unpredictable.

userdata

If the optional userdata parameter is supplied, it will be passed as the third parameter to the callback.

Return Values

Returns TRUE.

Errors/Exceptions

As of PHP 7.1.0, an ArgumentCountError will be thrown if the callback function requires more than 2 parameters (the value and key of the array member). Previously, if the callback function required more than 2 parameters, an error of level E_WARNING would be generated each time array_walk() calls callback.

Examples

Example #1 array_walk() example

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");

function test_alter(&$item1, $key, $prefix)
{
    $item1 = "$prefix: $item1";
}

function test_print($item2, $key)
{
    echo "$key. $item2<br />\n";
}

echo "Before ...:\n";
array_walk($fruits, 'test_print');

array_walk($fruits, 'test_alter', 'fruit');
echo "... and after:\n";

array_walk($fruits, 'test_print');
?>

The above example will output:

Before ...:
d. lemon
a. orange
b. banana
c. apple
... and after:
d. fruit: lemon
a. fruit: orange
b. fruit: banana
c. fruit: apple

See Also

  • array_walk_recursive() - Apply a user function recursively to every member of an array
  • iterator_apply() - Call a function for every element in an iterator
  • list() - Assign variables as if they were an array
  • each() - Return the current key and value pair from an array and advance the array cursor
  • call_user_func_array() - Call a callback with an array of parameters
  • array_map() - Applies the callback to the elements of the given arrays
  • information about the callback type
  • foreach


Create an array

  • « array_walk
  • arsort »
  • PHP Manual
  • Array Functions
  • Create an array

array

(PHP 4, PHP 5, PHP 7)

array — Create an array

Description

array ([ mixed $... ] ) : array

Creates an array. Read the section on the array type for more information on what an array is.

Parameters

...

Syntax "index => values", separated by commas, define index and values. index may be of type string or integer. When index is omitted, an integer index is automatically generated, starting at 0. If index is an integer, next generated index will be the biggest integer index + 1. Note that when two identical index are defined, the last overwrite the first.

Having a trailing comma after the last defined array entry, while unusual, is a valid syntax.

Return Values

Returns an array of the parameters. The parameters can be given an index with the => operator. Read the section on the array type for more information on what an array is.

Examples

The following example demonstrates how to create a two-dimensional array, how to specify keys for associative arrays, and how to skip-and-continue numeric indices in normal arrays.

Example #1 array() example

<?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")
);
?>

Example #2 Automatic index with array()

<?php
$array = array(1, 1, 1, 1,  1, 8 => 1,  4 => 1, 19, 3 => 13);
print_r($array);
?>

The above example will output:

Array
(
    [0] => 1
    [1] => 1
    [2] => 1
    [3] => 13
    [4] => 1
    [8] => 1
    [9] => 19
)

Note that index '3' is defined twice, and keep its final value of 13. Index 4 is defined after index 8, and next generated index (value 19) is 9, since biggest index was 8.

This example creates a 1-based array.

Example #3 1-based index with array()

<?php
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>

The above example will output:

Array
(
    [1] => January
    [2] => February
    [3] => March
)

As in Perl, you can access a value from the array inside double quotes. However, with PHP you'll need to enclose your array between curly braces.

Example #4 Accessing an array inside double quotes

<?php

$foo = array('bar' => 'baz');
echo "Hello {$foo['bar']}!"; // Hello baz!

?>

Notes

Note:

array() is a language construct used to represent literal arrays, and not a regular function.

See Also

  • array_pad() - Pad array to the specified length with a value
  • list() - Assign variables as if they were an array
  • count() - Count all elements in an array, or something in an object
  • range() - Create an array containing a range of elements
  • foreach
  • The array type


Sort an array in reverse order and maintain index association

  • « array
  • asort »
  • PHP Manual
  • Array Functions
  • Sort an array in reverse order and maintain index association

arsort

(PHP 4, PHP 5, PHP 7)

arsort — Sort an array in reverse order and maintain index association

Description

arsort ( array &$array [, int $sort_flags = 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.

Note:

If two members compare as equal, their relative order in the sorted array is undefined.

Parameters

array

The input array.

sort_flags

You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 arsort() example

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
arsort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

The above example will output:

a = orange
d = lemon
b = banana
c = apple

The fruits have been sorted in reverse alphabetical order, and the index associated with each element has been maintained.

See Also

  • asort() - Sort an array and maintain index association
  • The comparison of array sorting functions


Sort an array and maintain index association

  • « arsort
  • compact »
  • PHP Manual
  • Array Functions
  • Sort an array and maintain index association

asort

(PHP 4, PHP 5, PHP 7)

asort — Sort an array and maintain index association

Description

asort ( array &$array [, int $sort_flags = 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.

Note:

If two members compare as equal, their relative order in the sorted array is undefined.

Parameters

array

The input array.

sort_flags

You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 asort() example

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
asort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

The above example will output:

c = apple
b = banana
d = lemon
a = orange

The fruits have been sorted in alphabetical order, and the index associated with each element has been maintained.

See Also

  • arsort() - Sort an array in reverse order and maintain index association
  • The comparison of array sorting functions


Create array containing variables and their values

  • « asort
  • count »
  • PHP Manual
  • Array Functions
  • Create array containing variables and their values

compact

(PHP 4, PHP 5, PHP 7)

compact — Create array containing variables and their values

Description

compact ( mixed $varname1 [, mixed $... ] ) : array

Creates an array containing variables and their values.

For each of these, compact() looks for a variable with that name in the current symbol table and adds it to the output array such that the variable name becomes the key and the contents of the variable become the value for that key. In short, it does the opposite of extract().

Note:

Before PHP 7.3, any strings that are not set will silently be skipped.

Parameters

varname1

compact() takes a variable number of parameters. Each parameter can be either a string containing the name of the variable, or an array of variable names. The array can contain other arrays of variable names inside it; compact() handles it recursively.

Return Values

Returns the output array with all the variables added to it.

Errors/Exceptions

compact() issues an E_NOTICE level error if a given string refers to an unset variable.

Changelog

Version | Description
7.3.0 | compact() now issues an E_NOTICE level error if a given string refers to an unset variable. Formerly, such strings have been silently skipped.

Examples

Example #1 compact() example

<?php
$city  = "San Francisco";
$state = "CA";
$event = "SIGGRAPH";

$location_vars = array("city", "state");

$result = compact("event", $location_vars);
print_r($result);
?>

The above example will output:

Array
(
    [event] => SIGGRAPH
    [city] => San Francisco
    [state] => CA
)

Notes

Note: Gotcha

Because variable variables may not be used with PHP's Superglobal arrays within functions, the Superglobal arrays may not be passed into compact().

See Also

  • extract() - Import variables into the current symbol table from an array


Count all elements in an array, or something in an object

  • « compact
  • current »
  • PHP Manual
  • Array Functions
  • Count all elements in an array, or something in an object

count

(PHP 4, PHP 5, PHP 7)

count — Count all elements in an array, or something in an object

Description

count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] ) : int

Counts all elements in an array, or something in an object.

For objects, if you have SPL installed, you can hook into count() by implementing interface Countable. The interface has exactly one method, Countable::count(), which returns the return value for the count() function.

Please see the Array section of the manual for a detailed explanation of how arrays are implemented and used in PHP.

Parameters

array_or_countable

An array or Countable object.

mode

If the optional mode parameter is set to COUNT_RECURSIVE (or 1), count() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array.

Caution

count() can detect recursion to avoid an infinite loop, but will emit an E_WARNING every time it does (in case the array contains itself more than once) and return a count higher than may be expected.

Return Values

Returns the number of elements in array_or_countable. When the parameter is neither an array nor an object with implemented Countable interface, 1 will be returned. There is one exception, if array_or_countable is NULL, 0 will be returned.

Examples

Example #1 count() example

<?php
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
var_dump(count($a));

$b[0]  = 7;
$b[5]  = 9;
$b[10] = 11;
var_dump(count($b));

var_dump(count(null));

var_dump(count(false));
?>

The above example will output:

int(3)
int(3)

Warning: count(): Parameter must be an array or an object that implements Countable in … on line 12 // as of PHP 7.2
int(0)

Warning: count(): Parameter must be an array or an object that implements Countable in … on line 14 // as of PHP 7.2
int(1)

Example #2 Recursive count() example

<?php
$food = array('fruits' => array('orange', 'banana', 'apple'),
              'veggie' => array('carrot', 'collard', 'pea'));

// recursive count
echo count($food, COUNT_RECURSIVE); // output 8

// normal count
echo count($food); // output 2

?>

Changelog

Version | Description
7.2.0 | count() will now yield a warning on invalid countable types passed to the array_or_countable parameter.

See Also

  • is_array() - Finds whether a variable is an array
  • isset() - Determine if a variable is declared and is different than NULL
  • empty() - Determine whether a variable is empty
  • strlen() - Get string length
  • is_countable() - Verify that the contents of a variable is a countable value


Return the current element in an array

  • « count
  • each »
  • PHP Manual
  • Array Functions
  • Return the current element in an array

current

(PHP 4, PHP 5, PHP 7)

current — Return the current element in an array

Description

current ( array $array ) : mixed

Every array has an internal pointer to its "current" element, which is initialized to the first element inserted into the array.

Parameters

array

The array.

Return Values

The current() function simply returns the value of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, current() returns 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
7.0.0 | array is now always passed by value. Prior to this version, it was passed by reference if possible, and by value otherwise.

Examples

Example #1 Example use of current() and friends

<?php
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport);    // $mode = 'bike';
$mode = current($transport); // $mode = 'bike';
$mode = prev($transport);    // $mode = 'foot';
$mode = end($transport);     // $mode = 'plane';
$mode = current($transport); // $mode = 'plane';

$arr = array();
var_dump(current($arr)); // bool(false)

$arr = array(array());
var_dump(current($arr)); // array(0) { }
?>

Notes

Note: The end of an array and the result of calling current() on an empty array are indistinguishable from a boolean FALSE element. To properly traverse an array which may contain FALSE elements, see the foreach() function. To still use current() and properly check if the value is really an element of the array, the key() of the current() element should be checked to be strictly different from NULL.

See Also

  • end() - Set the internal pointer of an array to its last element
  • key() - Fetch a key from an array
  • each() - Return the current key and value pair from an array and advance the array cursor
  • prev() - Rewind the internal array pointer
  • reset() - Set the internal pointer of an array to its first element
  • next() - Advance the internal pointer of an array


Return the current key and value pair from an array and advance the array cursor

  • « current
  • end »
  • PHP Manual
  • Array Functions
  • Return the current key and value pair from an array and advance the array cursor

each

(PHP 4, PHP 5, PHP 7)

each — Return the current key and value pair from an array and advance the array cursor

Warning

This function has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.

Description

each ( array &$array ) : array

Return the current key and value pair from an array and advance the array cursor.

After each() has executed, the array cursor will be left on the next element of the array, or past the last element if it hits the end of the array. You have to use reset() if you want to traverse the array again using each.

Parameters

array

The input array.

Return Values

Returns the current key and value pair from the array array. This pair is returned in a four-element array, with the keys 0, 1, key, and value. Elements 0 and key contain the key name of the array element, and 1 and value contain the data.

If the internal pointer for the array points past the end of the array contents, each() returns FALSE.

Examples

Example #1 each() examples

<?php
$foo = array("bob", "fred", "jussi", "jouni", "egon", "marliese");
$bar = each($foo);
print_r($bar);
?>

$bar now contains the following key/value pairs:

Array
(
    [1] => bob
    [value] => bob
    [0] => 0
    [key] => 0
)

<?php
$foo = array("Robert" => "Bob", "Seppo" => "Sepi");
$bar = each($foo);
print_r($bar);
?>

$bar now contains the following key/value pairs:

Array
(
    [1] => Bob
    [value] => Bob
    [0] => Robert
    [key] => Robert
)

each() is typically used in conjunction with list() to traverse an array, here's an example:

Example #2 Traversing an array with each()

<?php
$fruit = array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');

reset($fruit);
while (list($key, $val) = each($fruit)) {
    echo "$key => $val\n";
}
?>

The above example will output:

a => apple
b => banana
c => cranberry

Caution

Because assigning an array to another variable resets the original array's pointer, our example above would cause an endless loop had we assigned $fruit to another variable inside the loop.

Warning

each() will also accept objects, but may return unexpected results. It's therefore not recommended to iterate though object properties with each().

See Also

  • key() - Fetch a key from an array
  • list() - Assign variables as if they were an array
  • current() - Return the current element in an array
  • reset() - Set the internal pointer of an array to its first element
  • next() - Advance the internal pointer of an array
  • prev() - Rewind the internal array pointer
  • foreach
  • Object Iteration


Set the internal pointer of an array to its last element

  • « each
  • extract »
  • PHP Manual
  • Array Functions
  • Set the internal pointer of an array to its last element

end

(PHP 4, PHP 5, PHP 7)

end — Set the internal pointer of an array to its last element

Description

end ( array &$array ) : mixed

end() advances array's internal pointer to the last element, and returns its value.

Parameters

array

The array. This array is passed by reference because it is modified by the function. This means you must pass it a real variable and not a function returning an array because only actual variables may be passed by reference.

Return Values

Returns the value of the last element or FALSE for empty array.

Examples

Example #1 end() example

<?php

$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry

?>

See Also

  • current() - Return the current element in an array
  • each() - Return the current key and value pair from an array and advance the array cursor
  • prev() - Rewind the internal array pointer
  • reset() - Set the internal pointer of an array to its first element
  • next() - Advance the internal pointer of an array
  • array_key_last() - Gets the last key of an array


Import variables into the current symbol table from an array

  • « end
  • in_array »
  • PHP Manual
  • Array Functions
  • Import variables into the current symbol table from an array

extract

(PHP 4, PHP 5, PHP 7)

extract — Import variables into the current symbol table from an array

Description

extract ( array &$array [, int $flags = EXTR_OVERWRITE [, string $prefix = NULL ]] ) : int

Import variables from an array into the current symbol table.

Checks each key to see whether it has a valid variable name. It also checks for collisions with existing variables in the symbol table.

Warning

Do not use extract() on untrusted data, like user input (e.g. $_GET, $_FILES).

Parameters

array

An associative array. This function treats keys as variable names and values as variable values. For each key/value pair it will create a variable in the current symbol table, subject to flags and prefix parameters.

You must use an associative array; a numerically indexed array will not produce results unless you use EXTR_PREFIX_ALL or EXTR_PREFIX_INVALID.

flags

The way invalid/numeric keys and collisions are treated is determined by the extraction flags. It can be one of the following values:

EXTR_OVERWRITE
If there is a collision, overwrite the existing variable.
EXTR_SKIP
If there is a collision, don't overwrite the existing variable.
EXTR_PREFIX_SAME
If there is a collision, prefix the variable name with prefix.
EXTR_PREFIX_ALL
Prefix all variable names with prefix.
EXTR_PREFIX_INVALID
Only prefix invalid/numeric variable names with prefix.
EXTR_IF_EXISTS
Only overwrite the variable if it already exists in the current symbol table, otherwise do nothing. This is useful for defining a list of valid variables and then extracting only those variables you have defined out of $_REQUEST, for example.
EXTR_PREFIX_IF_EXISTS
Only create prefixed variable names if the non-prefixed version of the same variable exists in the current symbol table.
EXTR_REFS
Extracts variables as references. This effectively means that the values of the imported variables are still referencing the values of the array parameter. You can use this flag on its own or combine it with any other flag by OR'ing the flags.

If flags is not specified, it is assumed to be EXTR_OVERWRITE.

prefix

Note that prefix is only required if flags is EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID or EXTR_PREFIX_IF_EXISTS. If the prefixed result is not a valid variable name, it is not imported into the symbol table. Prefixes are automatically separated from the array key by an underscore character.

Return Values

Returns the number of variables successfully imported into the symbol table.

Examples

Example #1 extract() example

A possible use for extract() is to import into the symbol table variables contained in an associative array returned by wddx_deserialize().

<?php

/* Suppose that $var_array is an array returned from
   wddx_deserialize */

$size = "large";
$var_array = array("color" => "blue",
                   "size"  => "medium",
                   "shape" => "sphere");
extract($var_array, EXTR_PREFIX_SAME, "wddx");

echo "$color, $size, $shape, $wddx_size\n";

?>

The above example will output:

blue, large, sphere, medium

The $size wasn't overwritten because we specified EXTR_PREFIX_SAME, which resulted in $wddx_size being created. If EXTR_SKIP was specified, then $wddx_size wouldn't even have been created. EXTR_OVERWRITE would have caused $size to have value "medium", and EXTR_PREFIX_ALL would result in new variables being named $wddx_color, $wddx_size, and $wddx_shape.

Notes

Warning

Do not use extract() on untrusted data, like user input (i.e. $_GET, $_FILES, etc.). If you do, for example if you want to temporarily run old code that relied on register_globals, make sure you use one of the non-overwriting flags values such as EXTR_SKIP and be aware that you should extract in the same order that's defined in variables_order within the php.ini.

Note:

If you still have register_globals and it is turned on, if you use extract() on $_FILES and specify EXTR_SKIP, you may be surprised at the results.

Warning

This is not recommended practice and is only documented here for completeness. The use of register_globals is deprecated and calling extract() on untrusted data such as $_FILES is, as noted above, a potential security risk. If you encounter this issue, it means that you are using at least two poor coding practices.

<?php

/* Suppose that $testfile is the name of a file upload input
   and that register_globals is turned on. */

var_dump($testfile);
extract($_FILES, EXTR_SKIP);
var_dump($testfile);
var_dump($testfile['tmp_name']);

?>
You might expect to see something like the following:
string(14) "/tmp/phpgCCPX8"
array(5) {
  ["name"]=>
  string(10) "somefile.txt"
  ["type"]=>
  string(24) "application/octet-stream"
  ["tmp_name"]=>
  string(14) "/tmp/phpgCCPX8"
  ["error"]=>
  int(0)
  ["size"]=>
  int(4208)
}
string(14) "/tmp/phpgCCPX8"
However, you would instead see something like this:
string(14) "/tmp/phpgCCPX8"
string(14) "/tmp/phpgCCPX8"
string(1) "/"

This is due to the fact that since register_globals is turned on, $testfile already exists in the global scope when extract() is called. And since EXTR_SKIP is specified, $testfile is not overwritten with the contents of the $_FILES array so $testfile remains a string. Because strings may be accessed using array syntax and the non-numeric string tmp_name is interpreted as 0, PHP sees $testfile['tmp_name'] as $testfile[0].

See Also

  • compact() - Create array containing variables and their values
  • list() - Assign variables as if they were an array


Checks if a value exists in an array

  • « extract
  • key_exists »
  • PHP Manual
  • Array Functions
  • Checks if a value exists in an array

in_array

(PHP 4, PHP 5, PHP 7)

in_array — Checks if a value exists in an array

Description

in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] ) : bool

Searches for needle in haystack using loose comparison unless strict is set.

Parameters

needle

The searched value.

Note:

If needle is a string, the comparison is done in a case-sensitive manner.

haystack

The array.

strict

If the third parameter strict is set to TRUE then the in_array() function will also check the types of the needle in the haystack.

Return Values

Returns TRUE if needle is found in the array, FALSE otherwise.

Examples

Example #1 in_array() example

<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
    echo "Got Irix";
}
if (in_array("mac", $os)) {
    echo "Got mac";
}
?>

The second condition fails because in_array() is case-sensitive, so the program above will display:

Got Irix

Example #2 in_array() with strict example

<?php
$a = array('1.10', 12.4, 1.13);

if (in_array('12.4', $a, true)) {
    echo "'12.4' found with strict check\n";
}

if (in_array(1.13, $a, true)) {
    echo "1.13 found with strict check\n";
}
?>

The above example will output:

1.13 found with strict check

Example #3 in_array() with an array as needle

<?php
$a = array(array('p', 'h'), array('p', 'r'), 'o');

if (in_array(array('p', 'h'), $a)) {
    echo "'ph' was found\n";
}

if (in_array(array('f', 'i'), $a)) {
    echo "'fi' was found\n";
}

if (in_array('o', $a)) {
    echo "'o' was found\n";
}
?>

The above example will output:

  'ph' was found
  'o' was found

See Also

  • array_search() - Searches the array for a given value and returns the first corresponding key if successful
  • isset() - Determine if a variable is declared and is different than NULL
  • array_key_exists() - Checks if the given key or index exists in the array


Alias of array_key_exists

  • « in_array
  • key »
  • PHP Manual
  • Array Functions
  • Alias of array_key_exists

key_exists

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

key_exists — Alias of array_key_exists()

Description

This function is an alias of: array_key_exists().


Fetch a key from an array

  • « key_exists
  • krsort »
  • PHP Manual
  • Array Functions
  • Fetch a key from an array

key

(PHP 4, PHP 5, PHP 7)

key — Fetch a key from an array

Description

key ( array $array ) : mixed

key() returns the index element of the current array position.

Parameters

array

The array.

Return Values

The key() function simply returns the key of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, key() returns NULL.

Changelog

Version | Description
7.0.0 | array is now always passed by value. Prior to this version, it was passed by reference if possible, and by value otherwise.

Examples

Example #1 key() example

<?php
$array = array(
    'fruit1' => 'apple',
    'fruit2' => 'orange',
    'fruit3' => 'grape',
    'fruit4' => 'apple',
    'fruit5' => 'apple');

// this cycle echoes all associative array
// key where value equals "apple"
while ($fruit_name = current($array)) {
    if ($fruit_name == 'apple') {
        echo key($array).'<br />';
    }
    next($array);
}
?>

The above example will output:

fruit1<br />
fruit4<br />
fruit5<br />

See Also

  • current() - Return the current element in an array
  • next() - Advance the internal pointer of an array
  • foreach


Sort an array by key in reverse order

  • « key
  • ksort »
  • PHP Manual
  • Array Functions
  • Sort an array by key in reverse order

krsort

(PHP 4, PHP 5, PHP 7)

krsort — Sort an array by key in reverse order

Description

krsort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) : bool

Sorts an array by key in reverse order, maintaining key to data correlations. This is useful mainly for associative arrays.

Parameters

array

The input array.

sort_flags

You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 krsort() example

<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
krsort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

The above example will output:

d = lemon
c = apple
b = banana
a = orange

See Also

  • arsort() - Sort an array in reverse order and maintain index association
  • ksort() - Sort an array by key
  • The comparison of array sorting functions


Sort an array by key

  • « krsort
  • list »
  • PHP Manual
  • Array Functions
  • Sort an array by key

ksort

(PHP 4, PHP 5, PHP 7)

ksort — Sort an array by key

Description

ksort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) : bool

Sorts an array by key, maintaining key to data correlations. This is useful mainly for associative arrays.

Parameters

array

The input array.

sort_flags

You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ksort() example

<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

The above example will output:

a = orange
b = banana
c = apple
d = lemon

See Also

  • asort() - Sort an array and maintain index association
  • The comparison of array sorting functions


Assign variables as if they were an array

  • « ksort
  • natcasesort »
  • PHP Manual
  • Array Functions
  • Assign variables as if they were an array

list

(PHP 4, PHP 5, PHP 7)

list — Assign variables as if they were an array

Description

list ( mixed $var1 [, mixed $... ] ) : array

Like array(), this is not really a function, but a language construct. list() is used to assign a list of variables in one operation.

Note:

Before PHP 7.1.0, list() only worked on numerical arrays and assumes the numerical indices start at 0.

Warning

In PHP 5, list() assigns the values starting with the right-most parameter. In PHP 7, list() starts with the left-most parameter.

If you are using plain variables, you don't have to worry about this. But if you are using arrays with indices you usually expect the order of the indices in the array the same you wrote in the list() from left to right, which is not the case in PHP 5, as it's assigned in the reverse order.

Generally speaking, it is advisable to avoid relying on a specific order of operation, as this may change again in the future.

Parameters

var1

A variable.

Return Values

Returns the assigned array.

Changelog

Version | Description
7.1.0 | It is now possible to specify keys in list(). This enables destructuring of arrays with non-integer or non-sequential keys.
7.0.0 | The order that the assignment operations are performed in has changed.
7.0.0 | list() expressions can no longer be completely empty.
7.0.0 | Strings can no longer be unpacked.

Examples

Example #1 list() examples

<?php

$info = array('coffee', 'brown', 'caffeine');

// Listing all the variables
list($drink, $color, $power) = $info;
echo "$drink is $color and $power makes it special.\n";

// Listing some of them
list($drink, , $power) = $info;
echo "$drink has $power.\n";

// Or let's skip to only the third one
list( , , $power) = $info;
echo "I need $power!\n";

// list() doesn't work with strings
list($bar) = "abcde";
var_dump($bar); // NULL
?>

Example #2 An example use of list()

<table>
 <tr>
  <th>Employee name</th>
  <th>Salary</th>
 </tr>

<?php
$result = $pdo->query("SELECT id, name, salary FROM employees");
while (list($id, $name, $salary) = $result->fetch(PDO::FETCH_NUM)) {
    echo " <tr>\n" .
          "  <td><a href=\"info.php?id=$id\">$name</a></td>\n" .
          "  <td>$salary</td>\n" .
          " </tr>\n";
}

?>

</table>

Example #3 Using nested list()

<?php

list($a, list($b, $c)) = array(1, array(2, 3));

var_dump($a, $b, $c);

?>
int(1)
int(2)
int(3)

Example #4 Using list() with array indices

<?php

$info = array('coffee', 'brown', 'caffeine');

list($a[0], $a[1], $a[2]) = $info;

var_dump($a);

?>

Gives the following output (note the order of the elements compared in which order they were written in the list() syntax):

Output of the above example in PHP 7:

array(3) {
  [0]=>
  string(6) "coffee"
  [1]=>
  string(5) "brown"
  [2]=>
  string(8) "caffeine"
}

Output of the above example in PHP 5:

array(3) {
  [2]=>
  string(8) "caffeine"
  [1]=>
  string(5) "brown"
  [0]=>
  string(6) "coffee"
}

Example #5 list() and order of index definitions

The order in which the indices of the array to be consumed by list() are defined is irrelevant.

<?php
$foo = array(2 => 'a', 'foo' => 'b', 0 => 'c');
$foo[1] = 'd';
list($x, $y, $z) = $foo;
var_dump($foo, $x, $y, $z);

Gives the following output (note the order of the elements compared in which order they were written in the list() syntax):

array(4) {
  [2]=>
  string(1) "a"
  ["foo"]=>
  string(1) "b"
  [0]=>
  string(1) "c"
  [1]=>
  string(1) "d"
}
string(1) "c"
string(1) "d"
string(1) "a"

Example #6 list() with keys

As of PHP 7.1.0 list() can now also contain explicit keys, which can be given as arbitrary expressions. Mixing of integer and string keys is allowed; however, elements with and without keys cannot be mixed.

<?php
$data = [
    ["id" => 1, "name" => 'Tom'],
    ["id" => 2, "name" => 'Fred'],
];
foreach ($data as ["id" => $id, "name" => $name]) {
    echo "id: $id, name: $name\n";
}
echo PHP_EOL;
list(1 => $second, 3 => $fourth) = [1, 2, 3, 4];
echo "$second, $fourth\n";

The above example will output:

id: 1, name: Tom
id: 2, name: Fred

2, 4

See Also

  • each() - Return the current key and value pair from an array and advance the array cursor
  • array() - Create an array
  • extract() - Import variables into the current symbol table from an array


Sort an array using a case insensitive "natural order" algorithm

  • « list
  • natsort »
  • PHP Manual
  • Array Functions
  • Sort an array using a case insensitive "natural order" algorithm

natcasesort

(PHP 4, PHP 5, PHP 7)

natcasesort — Sort an array using a case insensitive "natural order" algorithm

Description

natcasesort ( array &$array ) : bool

natcasesort() is a case insensitive version of natsort().

This function implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations. This is described as a "natural ordering".

Note:

If two members compare as equal, their relative order in the sorted array is undefined.

Parameters

array

The input array.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 natcasesort() example

<?php
$array1 = $array2 = array('IMG0.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png');

sort($array1);
echo "Standard sorting\n";
print_r($array1);

natcasesort($array2);
echo "\nNatural order sorting (case-insensitive)\n";
print_r($array2);
?>

The above example will output:

Standard sorting
Array
(
    [0] => IMG0.png
    [1] => IMG3.png
    [2] => img1.png
    [3] => img10.png
    [4] => img12.png
    [5] => img2.png
)

Natural order sorting (case-insensitive)
Array
(
    [0] => IMG0.png
    [4] => img1.png
    [3] => img2.png
    [5] => IMG3.png
    [2] => img10.png
    [1] => img12.png
)

For more information see: Martin Pool's » Natural Order String Comparison page.

See Also

  • natsort() - Sort an array using a "natural order" algorithm
  • The comparison of array sorting functions
  • strnatcmp() - String comparisons using a "natural order" algorithm
  • strnatcasecmp() - Case insensitive string comparisons using a "natural order" algorithm


Sort an array using a "natural order" algorithm

  • « natcasesort
  • next »
  • PHP Manual
  • Array Functions
  • Sort an array using a "natural order" algorithm

natsort

(PHP 4, PHP 5, PHP 7)

natsort — Sort an array using a "natural order" algorithm

Description

natsort ( array &$array ) : bool

This function implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations. This is described as a "natural ordering". An example of the difference between this algorithm and the regular computer string sorting algorithms (used in sort()) can be seen in the example below.

Note:

If two members compare as equal, their relative order in the sorted array is undefined.

Parameters

array

The input array.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.2.10 | Zero padded numeric strings (e.g., '00005') now essentially ignore the 0 padding.

Examples

Example #1 natsort() examples demonstrating basic usage

<?php
$array1 = $array2 = array("img12.png", "img10.png", "img2.png", "img1.png");

asort($array1);
echo "Standard sorting\n";
print_r($array1);

natsort($array2);
echo "\nNatural order sorting\n";
print_r($array2);
?>

The above example will output:

Standard sorting
Array
(
    [3] => img1.png
    [1] => img10.png
    [0] => img12.png
    [2] => img2.png
)

Natural order sorting
Array
(
    [3] => img1.png
    [2] => img2.png
    [1] => img10.png
    [0] => img12.png
)

For more information see: Martin Pool's » Natural Order String Comparison page.

Example #2 natsort() examples demonstrating potential gotchas

<?php
echo "Negative numbers\n";
$negative = array('-5','3','-2','0','-1000','9','1');
print_r($negative);
natsort($negative);
print_r($negative);

echo "Zero padding\n";
$zeros = array('09', '8', '10', '009', '011', '0');
print_r($zeros);
natsort($zeros);
print_r($zeros);
?>

The above example will output:

Negative numbers
Array
(
    [0] => -5
    [1] => 3
    [2] => -2
    [3] => 0
    [4] => -1000
    [5] => 9
    [6] => 1
)
Array
(
    [2] => -2
    [0] => -5
    [4] => -1000
    [3] => 0
    [6] => 1
    [1] => 3
    [5] => 9
)

Zero padding
Array
(
    [0] => 09
    [1] => 8
    [2] => 10
    [3] => 009
    [4] => 011
    [5] => 0
)
Array
(
    [5] => 0
    [1] => 8
    [3] => 009
    [0] => 09
    [2] => 10
    [4] => 011
)

See Also

  • natcasesort() - Sort an array using a case insensitive "natural order" algorithm
  • The comparison of array sorting functions
  • strnatcmp() - String comparisons using a "natural order" algorithm
  • strnatcasecmp() - Case insensitive string comparisons using a "natural order" algorithm


Advance the internal pointer of an array

  • « natsort
  • pos »
  • PHP Manual
  • Array Functions
  • Advance the internal pointer of an array

next

(PHP 4, PHP 5, PHP 7)

next — Advance the internal pointer of an array

Description

next ( array &$array ) : mixed

next() behaves like current(), with one difference. It advances the internal array pointer one place forward before returning the element value. That means it returns the next array value and advances the internal array pointer by one.

Parameters

array

The array being affected.

Return Values

Returns the array value in the next place that's pointed to by the internal array pointer, or FALSE if there are no more elements.

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 Example use of next() and friends

<?php
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport);    // $mode = 'bike';
$mode = next($transport);    // $mode = 'car';
$mode = prev($transport);    // $mode = 'bike';
$mode = end($transport);     // $mode = 'plane';
?>

Notes

Note: The end of an array is indistinguishable from a boolean FALSE element. To properly traverse an array which may contain FALSE elements, see the foreach() function. To still use next() and properly check if the end of the array has been reached, verify that the key() is NULL.

See Also

  • current() - Return the current element in an array
  • end() - Set the internal pointer of an array to its last element
  • prev() - Rewind the internal array pointer
  • reset() - Set the internal pointer of an array to its first element
  • each() - Return the current key and value pair from an array and advance the array cursor


Alias of current

  • « next
  • prev »
  • PHP Manual
  • Array Functions
  • Alias of current

pos

(PHP 4, PHP 5, PHP 7)

pos — Alias of current()

Description

This function is an alias of: current()


Rewind the internal array pointer

  • « pos
  • range »
  • PHP Manual
  • Array Functions
  • Rewind the internal array pointer

prev

(PHP 4, PHP 5, PHP 7)

prev — Rewind the internal array pointer

Description

prev ( array &$array ) : mixed

Rewind the internal array pointer.

prev() behaves just like next(), except it rewinds the internal array pointer one place instead of advancing it.

Parameters

array

The input array.

Return Values

Returns the array value in the previous place that's pointed to by the internal array pointer, or FALSE if there are no more elements.

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Examples

Example #1 Example use of prev() and friends

<?php
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport);    // $mode = 'bike';
$mode = next($transport);    // $mode = 'car';
$mode = prev($transport);    // $mode = 'bike';
$mode = end($transport);     // $mode = 'plane';
?>

Notes

Note: The beginning of an array is indistinguishable from a boolean FALSE element. To make the distinction, check that the key() of the prev() element is not NULL.

See Also

  • current() - Return the current element in an array
  • end() - Set the internal pointer of an array to its last element
  • next() - Advance the internal pointer of an array
  • reset() - Set the internal pointer of an array to its first element
  • each() - Return the current key and value pair from an array and advance the array cursor


Create an array containing a range of elements

  • « prev
  • reset »
  • PHP Manual
  • Array Functions
  • Create an array containing a range of elements

range

(PHP 4, PHP 5, PHP 7)

range — Create an array containing a range of elements

Description

range ( mixed $start , mixed $end [, number $step = 1 ] ) : array

Create an array containing a range of elements.

Parameters

start

First value of the sequence.

end

The sequence is ended upon reaching the end value.

step

If a step value is given, it will be used as the increment between elements in the sequence. step should be given as a positive number. If not specified, step will default to 1.

Return Values

Returns an array of elements from start to end, inclusive.

Examples

Example #1 range() examples

<?php
// array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
foreach (range(0, 12) as $number) {
    echo $number;
}

// The step parameter
// array(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
foreach (range(0, 100, 10) as $number) {
    echo $number;
}

// Usage of character sequences
// array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i');
foreach (range('a', 'i') as $letter) {
    echo $letter;
}
// array('c', 'b', 'a');
foreach (range('c', 'a') as $letter) {
    echo $letter;
}
?>

Notes

Note:

Character sequence values are limited to a length of one. If a length greater than one is entered, only the first character is used.

See Also

  • shuffle() - Shuffle an array
  • array_fill() - Fill an array with values
  • foreach


Set the internal pointer of an array to its first element

  • « range
  • rsort »
  • PHP Manual
  • Array Functions
  • Set the internal pointer of an array to its first element

reset

(PHP 4, PHP 5, PHP 7)

reset — Set the internal pointer of an array to its first element

Description

reset ( array &$array ) : mixed

reset() rewinds array's internal pointer to the first element and returns the value of the first array element.

Parameters

array

The input array.

Return Values

Returns the value of the first array element, or FALSE if the array is empty.

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 reset() example

<?php

$array = array('step one', 'step two', 'step three', 'step four');

// by default, the pointer is on the first element
echo current($array) . "<br />\n"; // "step one"

// skip two steps
next($array);
next($array);
echo current($array) . "<br />\n"; // "step three"

// reset pointer, start again on step one
reset($array);
echo current($array) . "<br />\n"; // "step one"

?>

Notes

Note: The return value for an empty array is indistinguishable from the return value in case of an array which has a boolean FALSE first element. To properly check the value of the first element of an array which may contain FALSE elements, first check the count() of the array, or check that key() is not NULL, after calling reset().

See Also

  • current() - Return the current element in an array
  • each() - Return the current key and value pair from an array and advance the array cursor
  • end() - Set the internal pointer of an array to its last element
  • next() - Advance the internal pointer of an array
  • prev() - Rewind the internal array pointer
  • array_key_first() - Gets the first key of an array


Sort an array in reverse order

  • « reset
  • shuffle »
  • PHP Manual
  • Array Functions
  • Sort an array in reverse order

rsort

(PHP 4, PHP 5, PHP 7)

rsort — Sort an array in reverse order

Description

rsort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) : bool

This function sorts an array in reverse order (highest to lowest).

Note:

If two members compare as equal, their relative order in the sorted array is undefined.

Parameters

array

The input array.

sort_flags

You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 rsort() example

<?php
$fruits = array("lemon", "orange", "banana", "apple");
rsort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

The above example will output:

0 = orange
1 = lemon
2 = banana
3 = apple

The fruits have been sorted in reverse alphabetical order.

Notes

Note: This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys.

See Also

  • arsort() - Sort an array in reverse order and maintain index association
  • krsort() - Sort an array by key in reverse order
  • The comparison of array sorting functions


Shuffle an array

  • « rsort
  • sizeof »
  • PHP Manual
  • Array Functions
  • Shuffle an array

shuffle

(PHP 4, PHP 5, PHP 7)

shuffle — Shuffle an array

Description

shuffle ( array &$array ) : bool

This function shuffles (randomizes the order of the elements in) an array. It uses a pseudo random number generator that is not suitable for cryptographic purposes.

Parameters

array

The array.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.1.0 | The internal randomization algorithm has been changed to use the » Mersenne Twister Random Number Generator instead of the libc rand function.

Examples

Example #1 shuffle() example

<?php
$numbers = range(1, 20);
shuffle($numbers);
foreach ($numbers as $number) {
    echo "$number ";
}
?>

Notes

Note: This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys.

See Also

  • array_rand() - Pick one or more random keys out of an array
  • The comparison of array sorting functions


Alias of count

  • « shuffle
  • sort »
  • PHP Manual
  • Array Functions
  • Alias of count

sizeof

(PHP 4, PHP 5, PHP 7)

sizeof — Alias of count()

Description

This function is an alias of: count().


Sort an array

  • « sizeof
  • uasort »
  • PHP Manual
  • Array Functions
  • Sort an array

sort

(PHP 4, PHP 5, PHP 7)

sort — Sort an array

Description

sort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) : bool

This function sorts an array. Elements will be arranged from lowest to highest when this function has completed.

Note:

If two members compare as equal, their relative order in the sorted array is undefined.

Parameters

array

The input array.

sort_flags

The optional second parameter sort_flags may be used to modify the sorting behavior using these values:

Sorting type flags:

  • SORT_REGULAR - compare items normally; the details are described in the comparison operators section
  • SORT_NUMERIC - compare items numerically
  • SORT_STRING - compare items as strings
  • SORT_LOCALE_STRING - compare items as strings, based on the current locale. It uses the locale, which can be changed using setlocale()
  • SORT_NATURAL - compare items as strings using "natural ordering" like natsort()
  • SORT_FLAG_CASE - can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.4.0 | Added support for SORT_NATURAL and SORT_FLAG_CASE as sort_flags
5.0.2 | Added SORT_LOCALE_STRING

Examples

Example #1 sort() example

<?php

$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
    echo "fruits[" . $key . "] = " . $val . "\n";
}

?>

The above example will output:

fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = orange

The fruits have been sorted in alphabetical order.

Example #2 sort() example using case-insensitive natural ordering

<?php

$fruits = array(
    "Orange1", "orange2", "Orange3", "orange20"
);
sort($fruits, SORT_NATURAL | SORT_FLAG_CASE);
foreach ($fruits as $key => $val) {
    echo "fruits[" . $key . "] = " . $val . "\n";
}

?>

The above example will output:

fruits[0] = Orange1
fruits[1] = orange2
fruits[2] = Orange3
fruits[3] = orange20

The fruits have been sorted like natcasesort().

Notes

Note: This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys.

Note: Like most PHP sorting functions, sort() uses an implementation of » Quicksort. The pivot is chosen in the middle of the partition resulting in an optimal time for already sorted arrays. This is however an implementation detail you shouldn't rely on.

Warning

Be careful when sorting arrays with mixed types values because sort() can produce unexpected results, if sort_flags is SORT_REGULAR,

See Also

  • asort() - Sort an array and maintain index association
  • rsort() - Sort an array in reverse order
  • The comparison of array sorting functions


Sort an array with a user-defined comparison function and maintain index association

  • « sort
  • uksort »
  • PHP Manual
  • Array Functions
  • Sort an array with a user-defined comparison function and maintain index association

uasort

(PHP 4, PHP 5, PHP 7)

uasort — Sort an array with a user-defined comparison function and maintain index association

Description

uasort ( array &$array , callable $value_compare_func ) : bool

This function sorts an array such that array indices maintain their correlation with the array elements they are associated with, using a user-defined comparison function.

This is used mainly when sorting associative arrays where the actual element order is significant.

Note:

If two members compare as equal, their relative order in the sorted array is undefined.

Parameters

array

The input array.

value_compare_func

See usort() and uksort() for examples of user-defined comparison functions.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Basic uasort() example

<?php
// Comparison function
function cmp($a, $b) {
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

// Array to be sorted
$array = array('a' => 4, 'b' => 8, 'c' => -1, 'd' => -9, 'e' => 2, 'f' => 5, 'g' => 3, 'h' => -4);
print_r($array);

// Sort and print the resulting array
uasort($array, 'cmp');
print_r($array);
?>

The above example will output:

Array
(
    [a] => 4
    [b] => 8
    [c] => -1
    [d] => -9
    [e] => 2
    [f] => 5
    [g] => 3
    [h] => -4
)
Array
(
    [d] => -9
    [h] => -4
    [c] => -1
    [e] => 2
    [g] => 3
    [a] => 4
    [f] => 5
    [b] => 8
)

See Also

  • usort() - Sort an array by values using a user-defined comparison function
  • The comparison of array sorting functions


Sort an array by keys using a user-defined comparison function

  • « uasort
  • usort »
  • PHP Manual
  • Array Functions
  • Sort an array by keys using a user-defined comparison function

uksort

(PHP 4, PHP 5, PHP 7)

uksort — Sort an array by keys using a user-defined comparison function

Description

uksort ( array &$array , callable $key_compare_func ) : bool

uksort() will sort the keys of an array using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.

Note:

If two members compare as equal, their relative order in the sorted array is undefined.

Parameters

array

The input array.

key_compare_func

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. Note that before PHP 7.0.0 this integer had to be in the range from -2147483648 to 2147483647.

callback ( mixed $a, mixed $b ) : int

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 uksort() example

<?php
function cmp($a, $b)
{
    $a = preg_replace('@^(a|an|the) @', '', $a);
    $b = preg_replace('@^(a|an|the) @', '', $b);
    return strcasecmp($a, $b);
}

$a = array("John" => 1, "the Earth" => 2, "an apple" => 3, "a banana" => 4);

uksort($a, "cmp");

foreach ($a as $key => $value) {
    echo "$key: $value\n";
}
?>

The above example will output:

an apple: 3
a banana: 4
the Earth: 2
John: 1

See Also

  • usort() - Sort an array by values using a user-defined comparison function
  • The comparison of array sorting functions


Sort an array by values using a user-defined comparison function

  • « uksort
  • Classes/Objects »
  • PHP Manual
  • Array Functions
  • Sort an array by values using a user-defined comparison function

usort

(PHP 4, PHP 5, PHP 7)

usort — Sort an array by values using a user-defined comparison function

Description

usort ( array &$array , callable $value_compare_func ) : bool

This function will sort an array by its values using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.

Note:

If two members compare as equal, their relative order in the sorted array is undefined.

Note: This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys.

Parameters

array

The input array.

value_compare_func

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. Note that before PHP 7.0.0 this integer had to be in the range from -2147483648 to 2147483647.

callback ( mixed $a, mixed $b ) : int
Caution

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 usort() example

<?php
function cmp($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

$a = array(3, 2, 5, 6, 1);

usort($a, "cmp");

foreach ($a as $key => $value) {
    echo "$key: $value\n";
}
?>

The above example will output:

0: 1
1: 2
2: 3
3: 5
4: 6

Note:

Obviously in this trivial case the sort() function would be more appropriate.

Example #2 usort() example using multi-dimensional array

<?php
function cmp($a, $b)
{
    return strcmp($a["fruit"], $b["fruit"]);
}

$fruits[0]["fruit"] = "lemons";
$fruits[1]["fruit"] = "apples";
$fruits[2]["fruit"] = "grapes";

usort($fruits, "cmp");

while (list($key, $value) = each($fruits)) {
    echo "\$fruits[$key]: " . $value["fruit"] . "\n";
}
?>

When sorting a multi-dimensional array, $a and $b contain references to the first index of the array.

The above example will output:

$fruits[0]: apples
$fruits[1]: grapes
$fruits[2]: lemons

Example #3 usort() example using a member function of an object

<?php
class TestObj {
    var $name;

    function TestObj($name)
    {
        $this->name = $name;
    }

    /* This is the static comparing function: */
    static function cmp_obj($a, $b)
    {
        $al = strtolower($a->name);
        $bl = strtolower($b->name);
        if ($al == $bl) {
            return 0;
        }
        return ($al > $bl) ? +1 : -1;
    }
}

$a[] = new TestObj("c");
$a[] = new TestObj("b");
$a[] = new TestObj("d");

usort($a, array("TestObj", "cmp_obj"));

foreach ($a as $item) {
    echo $item->name . "\n";
}
?>

The above example will output:

b
c
d

Example #4 usort() example using a closure to sort a multi-dimensional array

<?php
$array[0] = array('key_a' => 'z', 'key_b' => 'c');
$array[1] = array('key_a' => 'x', 'key_b' => 'b');
$array[2] = array('key_a' => 'y', 'key_b' => 'a');

function build_sorter($key) {
    return function ($a, $b) use ($key) {
        return strnatcmp($a[$key], $b[$key]);
    };
}

usort($array, build_sorter('key_b'));

foreach ($array as $item) {
    echo $item['key_a'] . ', ' . $item['key_b'] . "\n";
}
?>

The above example will output:

y, a
x, b
z, c

See Also

  • uasort() - Sort an array with a user-defined comparison function and maintain index association
  • The comparison of array sorting functions


Class/Object Information

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Classes/Object Functions
    • __autoload — Attempt to load undefined class
    • call_user_method_array — Call a user method given with an array of parameters
    • call_user_method — Call a user method on an specific object
    • class_alias — Creates an alias for a class
    • class_exists — Checks if the class has been defined
    • get_called_class — The "Late Static Binding" class name
    • get_class_methods — Gets the class methods' names
    • get_class_vars — Get the default properties of the class
    • get_class — Returns the name of the class of an object
    • get_declared_classes — Returns an array with the name of the defined classes
    • get_declared_interfaces — Returns an array of all declared interfaces
    • get_declared_traits — Returns an array of all declared traits
    • get_object_vars — Gets the properties of the given object
    • get_parent_class — Retrieves the parent class name for object or class
    • interface_exists — Checks if the interface has been defined
    • is_a — Checks if the object is of this class or has this class as one of its parents
    • is_subclass_of — Checks if the object has this class as one of its parents or implements it
    • method_exists — Checks if the class method exists
    • property_exists — Checks if the object or class has a property
    • trait_exists — Checks if the trait exists


Introduction

These functions allow you to obtain information about classes and instance objects. You can obtain the name of the class to which an object belongs, as well as its member properties and methods. Using these functions, you can find out not only the class membership of an object, but also its parentage (i.e. what class is the object class extending).

Please see the Objects section of the manual for a detailed explanation of how classes and objects are implemented and used in PHP.


  • « Resource Types
  • Examples »
  • PHP Manual
  • Classes/Objects
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


Examples

In this example, we first define a base class and an extension of the class. The base class describes a general vegetable, whether it is edible or not and what is its color. The subclass Spinach adds a method to cook it and another to find out if it is cooked.

Example #1 classes.inc

<?php

// base class with member properties and methods
class Vegetable {

   var $edible;
   var $color;

   function __construct($edible, $color="green")
   {
       $this->edible = $edible;
       $this->color = $color;
   }

   function is_edible()
   {
       return $this->edible;
   }

   function what_color()
   {
       return $this->color;
   }

} // end of class Vegetable

// extends the base class
class Spinach extends Vegetable {

   var $cooked = false;

   function __construct()
   {
       parent::__construct(true, "green");
   }

   function cook_it()
   {
       $this->cooked = true;
   }

   function is_cooked()
   {
       return $this->cooked;
   }

} // end of class Spinach

?>

We then instantiate 2 objects from these classes and print out information about them, including their class parentage. We also define some utility functions, mainly to have a nice printout of the variables.

Example #2 test_script.php

<pre>
<?php

include "classes.inc";

// utility functions

function print_vars($obj)
{
foreach (get_object_vars($obj) as $prop => $val) {
    echo "\t$prop = $val\n";
}
}

function print_methods($obj)
{
$arr = get_class_methods(get_class($obj));
foreach ($arr as $method) {
    echo "\tfunction $method()\n";
}
}

function class_parentage($obj, $class)
{
if (is_subclass_of($GLOBALS[$obj], $class)) {
    echo "Object $obj belongs to class " . get_class($GLOBALS[$obj]);
    echo ", a subclass of $class\n";
} else {
    echo "Object $obj does not belong to a subclass of $class\n";
}
}

// instantiate 2 objects

$veggie = new Vegetable(true, "blue");
$leafy = new Spinach();

// print out information about objects
echo "veggie: CLASS " . get_class($veggie) . "\n";
echo "leafy: CLASS " . get_class($leafy);
echo ", PARENT " . get_parent_class($leafy) . "\n";

// show veggie properties
echo "\nveggie: Properties\n";
print_vars($veggie);

// and leafy methods
echo "\nleafy: Methods\n";
print_methods($leafy);

echo "\nParentage:\n";
class_parentage("leafy", "Spinach");
class_parentage("leafy", "Vegetable");
?>
</pre>

One important thing to note in the example above is that the object $leafy is an instance of the class Spinach which is a subclass of Vegetable, therefore the last part of the script above will output:

   [...]
Parentage:
Object leafy does not belong to a subclass of Spinach
Object leafy belongs to class spinach, a subclass of Vegetable


Classes/Object Functions

Table of Contents

  • __autoload — Attempt to load undefined class
  • call_user_method_array — Call a user method given with an array of parameters
  • call_user_method — Call a user method on an specific object
  • class_alias — Creates an alias for a class
  • class_exists — Checks if the class has been defined
  • get_called_class — The "Late Static Binding" class name
  • get_class_methods — Gets the class methods' names
  • get_class_vars — Get the default properties of the class
  • get_class — Returns the name of the class of an object
  • get_declared_classes — Returns an array with the name of the defined classes
  • get_declared_interfaces — Returns an array of all declared interfaces
  • get_declared_traits — Returns an array of all declared traits
  • get_object_vars — Gets the properties of the given object
  • get_parent_class — Retrieves the parent class name for object or class
  • interface_exists — Checks if the interface has been defined
  • is_a — Checks if the object is of this class or has this class as one of its parents
  • is_subclass_of — Checks if the object has this class as one of its parents or implements it
  • method_exists — Checks if the class method exists
  • property_exists — Checks if the object or class has a property
  • trait_exists — Checks if the trait exists


Attempt to load undefined class

  • « Classes/Object Functions
  • call_user_method_array »
  • PHP Manual
  • Classes/Object Functions
  • Attempt to load undefined class

__autoload

(PHP 5, PHP 7)

__autoload — Attempt to load undefined class

Warning

This feature has been DEPRECATED as of PHP 7.2.0. Relying on this feature is highly discouraged.

Description

__autoload ( string $class ) : void

You can define this function to enable classes autoloading.

Parameters

class

Name of the class to load

Return Values

No value is returned.

See Also

  • spl_autoload_register() - Register given function as __autoload() implementation


Call a user method given with an array of parameters

  • « __autoload
  • call_user_method »
  • PHP Manual
  • Classes/Object Functions
  • Call a user method given with an array of parameters

call_user_method_array

(PHP 4 >= 4.0.5, PHP 5)

call_user_method_array — Call a user method given with an array of parameters

Warning

This function was DEPRECATED in PHP 4.1.0, and REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • call_user_func_array()

Description

call_user_method_array ( string $method_name , object &$obj , array $params ) : mixed

Parameters

method_name

The method name being called.

obj

The object that method_name is being called on.

params

An array of parameters.

Examples

Example #1 call_user_method_array() alternative

<?php
call_user_func_array(array($obj, $method_name), $params);
?>

See Also

  • call_user_func_array() - Call a callback with an array of parameters
  • call_user_func() - Call the callback given by the first parameter


Call a user method on an specific object

  • « call_user_method_array
  • class_alias »
  • PHP Manual
  • Classes/Object Functions
  • Call a user method on an specific object

call_user_method

(PHP 4, PHP 5)

call_user_method — Call a user method on an specific object

Warning

This function was DEPRECATED in PHP 4.1.0, and REMOVED in PHP 7.0.0.

Alternatives to this function include:

  • call_user_func()

Description

call_user_method ( string $method_name , object &$obj [, mixed $... ] ) : mixed

Parameters

method_name

The method name being called.

obj

The object that method_name is being called on.

...

The optional parameters.

Examples

Example #1 call_user_method() alternative

<?php
call_user_func(array($obj, $method_name), $parameter /* , ... */);
?>

See Also

  • call_user_func_array() - Call a callback with an array of parameters
  • call_user_func() - Call the callback given by the first parameter


Creates an alias for a class

  • « call_user_method
  • class_exists »
  • PHP Manual
  • Classes/Object Functions
  • Creates an alias for a class

class_alias

(PHP 5 >= 5.3.0, PHP 7)

class_alias — Creates an alias for a class

Description

class_alias ( string $original , string $alias [, bool $autoload = TRUE ] ) : bool

Creates an alias named alias based on the user defined class original. The aliased class is exactly the same as the original class.

Parameters

original

The original class.

alias

The alias name for the class.

autoload

Whether to autoload if the original class is not found.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 class_alias() example

<?php

class foo { }

class_alias('foo', 'bar');

$a = new foo;
$b = new bar;

// the objects are the same
var_dump($a == $b, $a === $b);
var_dump($a instanceof $b);

// the classes are the same
var_dump($a instanceof foo);
var_dump($a instanceof bar);

var_dump($b instanceof foo);
var_dump($b instanceof bar);

?>

The above example will output:

bool(true)
bool(false)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)

See Also

  • get_parent_class() - Retrieves the parent class name for object or class
  • is_subclass_of() - Checks if the object has this class as one of its parents or implements it


Checks if the class has been defined

  • « class_alias
  • get_called_class »
  • PHP Manual
  • Classes/Object Functions
  • Checks if the class has been defined

class_exists

(PHP 4, PHP 5, PHP 7)

class_exists — Checks if the class has been defined

Description

class_exists ( string $class_name [, bool $autoload = TRUE ] ) : bool

This function checks whether or not the given class has been defined.

Parameters

class_name

The class name. The name is matched in a case-insensitive manner.

autoload

Whether or not to call __autoload by default.

Return Values

Returns TRUE if class_name is a defined class, FALSE otherwise.

Changelog

Version | Description
5.0.2 | No longer returns TRUE for defined interfaces. Use interface_exists().

Examples

Example #1 class_exists() example

<?php
// Check that the class exists before trying to use it
if (class_exists('MyClass')) {
    $myclass = new MyClass();
}

?>

Example #2 autoload parameter example

<?php
function __autoload($class)
{
    include($class . '.php');

    // Check to see whether the include declared the class
    if (!class_exists($class, false)) {
        trigger_error("Unable to load class: $class", E_USER_WARNING);
    }
}

if (class_exists('MyClass')) {
    $myclass = new MyClass();
}

?>

See Also

  • function_exists() - Return TRUE if the given function has been defined
  • interface_exists() - Checks if the interface has been defined
  • get_declared_classes() - Returns an array with the name of the defined classes


The "Late Static Binding" class name

  • « class_exists
  • get_class_methods »
  • PHP Manual
  • Classes/Object Functions
  • The "Late Static Binding" class name

get_called_class

(PHP 5 >= 5.3.0, PHP 7)

get_called_class — The "Late Static Binding" class name

Description

get_called_class ( void ) : string

Gets the name of the class the static method is called in.

Return Values

Returns the class name. Returns FALSE if called from outside a class.

Examples

Example #1 Using get_called_class()

<?php

class foo {
    static public function test() {
        var_dump(get_called_class());
    }
}

class bar extends foo {
}

foo::test();
bar::test();

?>

The above example will output:

string(3) "foo"
string(3) "bar"

See Also

  • get_parent_class() - Retrieves the parent class name for object or class
  • get_class() - Returns the name of the class of an object
  • is_subclass_of() - Checks if the object has this class as one of its parents or implements it


Gets the class methods' names

  • « get_called_class
  • get_class_vars »
  • PHP Manual
  • Classes/Object Functions
  • Gets the class methods' names

get_class_methods

(PHP 4, PHP 5, PHP 7)

get_class_methods — Gets the class methods' names

Description

get_class_methods ( mixed $class_name ) : array

Gets the class methods names.

Parameters

class_name

The class name or an object instance

Return Values

Returns an array of method names defined for the class specified by class_name. In case of an error, it returns NULL.

Examples

Example #1 get_class_methods() example

<?php

class myclass {
    // constructor
    function __construct()
    {
        return(true);
    }

    // method 1
    function myfunc1()
    {
        return(true);
    }

    // method 2
    function myfunc2()
    {
        return(true);
    }
}

$class_methods = get_class_methods('myclass');
// or
$class_methods = get_class_methods(new myclass());

foreach ($class_methods as $method_name) {
    echo "$method_name\n";
}

?>

The above example will output:

myclass
myfunc1
myfunc2

See Also

  • get_class() - Returns the name of the class of an object
  • get_class_vars() - Get the default properties of the class
  • get_object_vars() - Gets the properties of the given object


Get the default properties of the class

  • « get_class_methods
  • get_class »
  • PHP Manual
  • Classes/Object Functions
  • Get the default properties of the class

get_class_vars

(PHP 4, PHP 5, PHP 7)

get_class_vars — Get the default properties of the class

Description

get_class_vars ( string $class_name ) : array

Get the default properties of the given class.

Parameters

class_name

The class name

Return Values

Returns an associative array of declared properties visible from the current scope, with their default value. The resulting array elements are in the form of varname => value. In case of an error, it returns FALSE.

Changelog

Version | Description
5.0.3 | get_class_vars() will only return the properties that can be accessed from the current scope.
5.0.2 | Calling get_class_vars() will now expose all the properties as an array, unlike previous behaviour where protected and private properties were prefixed with nul bytes.
5.0.1 | Calling get_class_vars() will expose all properties, as when converting an object to a class.

Examples

Example #1 get_class_vars() example

<?php

class myclass {

    var $var1; // this has no default value...
    var $var2 = "xyz";
    var $var3 = 100;
    private $var4;

    // constructor
    function __construct() {
        // change some properties
        $this->var1 = "foo";
        $this->var2 = "bar";
        return true;
    }

}

$my_class = new myclass();

$class_vars = get_class_vars(get_class($my_class));

foreach ($class_vars as $name => $value) {
    echo "$name : $value\n";
}

?>

The above example will output:

var1 :
var2 : xyz
var3 : 100

Example #2 get_class_vars() and scoping behaviour

<?php
function format($array)
{
    return implode('|', array_keys($array)) . "\r\n";
}

class TestCase
{
    public $a    = 1;
    protected $b = 2;
    private $c   = 3;

    public static function expose()
    {
        echo format(get_class_vars(__CLASS__));
    }
}

TestCase::expose();
echo format(get_class_vars('TestCase'));
?>

The above example will output:

// 5.0.0
a| * b| TestCase c
a| * b| TestCase c

// 5.0.1 - 5.0.2
a|b|c
a|b|c

// 5.0.3 +
a|b|c
a

See Also

  • get_class_methods() - Gets the class methods' names
  • get_object_vars() - Gets the properties of the given object


Returns the name of the class of an object

  • « get_class_vars
  • get_declared_classes »
  • PHP Manual
  • Classes/Object Functions
  • Returns the name of the class of an object

get_class

(PHP 4, PHP 5, PHP 7)

get_class — Returns the name of the class of an object

Description

get_class ([ object $object ] ) : string

Gets the name of the class of the given object.

Parameters

object

The tested object. This parameter may be omitted when inside a class.

Note: Explicitly passing NULL as the object is no longer allowed as of PHP 7.2.0. The parameter is still optional and calling get_class() without a parameter from inside a class will work, but passing NULL now emits an E_WARNING notice.

Return Values

Returns the name of the class of which object is an instance. Returns FALSE if object is not an object.

If object is omitted when inside a class, the name of that class is returned.

If the object is an instance of a class which exists in a namespace, the qualified namespaced name of that class is returned.

Errors/Exceptions

If get_class() is called with anything other than an object, an E_WARNING level error is raised.

Changelog

Version | Description
7.2.0 | NULL was removed as the default value for object, and is no longer a valid input.
5.3.0 | NULL became the default value for object, so passing NULL to object now has the same result as not passing any value.

Examples

Example #1 Using get_class()

<?php

class foo {
    function name()
    {
        echo "My name is " , get_class($this) , "\n";
    }
}

// create an object
$bar = new foo();

// external call
echo "Its name is " , get_class($bar) , "\n";

// internal call
$bar->name();

?>

The above example will output:

Its name is foo
My name is foo

Example #2 Using get_class() in superclass

<?php

abstract class bar {
    public function __construct()
    {
        var_dump(get_class($this));
        var_dump(get_class());
    }
}

class foo extends bar {
}

new foo;

?>

The above example will output:

string(3) "foo"
string(3) "bar"

Example #3 Using get_class() with namespaced classes

<?php

namespace Foo\Bar;

class Baz {
    public function __construct()
    {

    }
}

$baz = new \Foo\Bar\Baz;

var_dump(get_class($baz));
?>

The above example will output:

string(11) "Foo\Bar\Baz"

See Also

  • get_called_class() - The "Late Static Binding" class name
  • get_parent_class() - Retrieves the parent class name for object or class
  • gettype() - Get the type of a variable
  • is_subclass_of() - Checks if the object has this class as one of its parents or implements it


Returns an array with the name of the defined classes

  • « get_class
  • get_declared_interfaces »
  • PHP Manual
  • Classes/Object Functions
  • Returns an array with the name of the defined classes

get_declared_classes

(PHP 4, PHP 5, PHP 7)

get_declared_classes — Returns an array with the name of the defined classes

Description

get_declared_classes ( void ) : array

Gets the declared classes.

Return Values

Returns an array of the names of the declared classes in the current script.

Note:

Note that depending on what extensions you have compiled or loaded into PHP, additional classes could be present. This means that you will not be able to define your own classes using these names. There is a list of predefined classes in the Predefined Classes section of the appendices.

Examples

Example #1 get_declared_classes() example

<?php
print_r(get_declared_classes());
?>

The above example will output something similar to:

Array
(
    [0] => stdClass
    [1] => __PHP_Incomplete_Class
    [2] => Directory
)

See Also

  • class_exists() - Checks if the class has been defined
  • get_declared_interfaces() - Returns an array of all declared interfaces
  • get_defined_functions() - Returns an array of all defined functions


Returns an array of all declared interfaces

  • « get_declared_classes
  • get_declared_traits »
  • PHP Manual
  • Classes/Object Functions
  • Returns an array of all declared interfaces

get_declared_interfaces

(PHP 5, PHP 7)

get_declared_interfaces — Returns an array of all declared interfaces

Description

get_declared_interfaces ( void ) : array

Gets the declared interfaces.

Return Values

Returns an array of the names of the declared interfaces in the current script.

Examples

Example #1 get_declared_interfaces() example

<?php
print_r(get_declared_interfaces());
?>

The above example will output something similar to:

Array
(
    [0] => Traversable
    [1] => IteratorAggregate
    [2] => Iterator
    [3] => ArrayAccess
    [4] => reflector
    [5] => RecursiveIterator
    [6] => SeekableIterator
)

See Also

  • interface_exists() - Checks if the interface has been defined
  • get_declared_classes() - Returns an array with the name of the defined classes
  • class_implements() - Return the interfaces which are implemented by the given class or interface


Returns an array of all declared traits

  • « get_declared_interfaces
  • get_object_vars »
  • PHP Manual
  • Classes/Object Functions
  • Returns an array of all declared traits

get_declared_traits

(PHP 5 >= 5.4.0, PHP 7)

get_declared_traits — Returns an array of all declared traits

Description

get_declared_traits ( void ) : array

Parameters

This function has no parameters.

Return Values

Returns an array with names of all declared traits in values. Returns NULL in case of a failure.

See Also

  • class_uses() - Return the traits used by the given class
  • trait_exists() - Checks if the trait exists


Gets the properties of the given object

  • « get_declared_traits
  • get_parent_class »
  • PHP Manual
  • Classes/Object Functions
  • Gets the properties of the given object

get_object_vars

(PHP 4, PHP 5, PHP 7)

get_object_vars — Gets the properties of the given object

Description

get_object_vars ( object $object ) : array

Gets the accessible non-static properties of the given object according to scope.

Parameters

object

An object instance.

Return Values

Returns an associative array of defined object accessible non-static properties for the specified object in scope.

Changelog

Version | Description
5.3.0 | This function now returns NULL if the object isn't an object. Previously FALSE was returned.

Examples

Example #1 Use of get_object_vars()

<?php

class foo {
    private $a;
    public $b = 1;
    public $c;
    private $d;
    static $e;

    public function test() {
        var_dump(get_object_vars($this));
    }
}

$test = new foo;
var_dump(get_object_vars($test));

$test->test();

?>

The above example will output:

array(2) {
  ["b"]=>
  int(1)
  ["c"]=>
  NULL
}
array(4) {
  ["a"]=>
  NULL
  ["b"]=>
  int(1)
  ["c"]=>
  NULL
  ["d"]=>
  NULL
}

See Also

  • get_class_methods() - Gets the class methods' names
  • get_class_vars() - Get the default properties of the class


Retrieves the parent class name for object or class

  • « get_object_vars
  • interface_exists »
  • PHP Manual
  • Classes/Object Functions
  • Retrieves the parent class name for object or class

get_parent_class

(PHP 4, PHP 5, PHP 7)

get_parent_class — Retrieves the parent class name for object or class

Description

get_parent_class ([ mixed $object ] ) : string

Retrieves the parent class name for object or class.

Parameters

object

The tested object or class name. This parameter is optional if called from the object's method.

Return Values

Returns the name of the parent class of the class of which object is an instance or the name.

Note:

If the object does not have a parent or the class given does not exist FALSE will be returned.

If called without parameter outside object, this function returns FALSE.

Changelog

Version | Description
5.1.0 | If called without parameter outside object, this function would have returned NULL with a warning, but now returns FALSE.

Examples

Example #1 Using get_parent_class()

<?php

class dad {
    function dad()
    {
    // implements some logic
    }
}

class child extends dad {
    function child()
    {
        echo "I'm " , get_parent_class($this) , "'s son\n";
    }
}

class child2 extends dad {
    function child2()
    {
        echo "I'm " , get_parent_class('child2') , "'s son too\n";
    }
}

$foo = new child();
$bar = new child2();

?>

The above example will output:

I'm dad's son
I'm dad's son too

See Also

  • get_class() - Returns the name of the class of an object
  • is_subclass_of() - Checks if the object has this class as one of its parents or implements it
  • class_parents() - Return the parent classes of the given class


Checks if the interface has been defined

  • « get_parent_class
  • is_a »
  • PHP Manual
  • Classes/Object Functions
  • Checks if the interface has been defined

interface_exists

(PHP 5 >= 5.0.2, PHP 7)

interface_exists — Checks if the interface has been defined

Description

interface_exists ( string $interface_name [, bool $autoload = TRUE ] ) : bool

Checks if the given interface has been defined.

Parameters

interface_name

The interface name

autoload

Whether to call __autoload or not by default.

Return Values

Returns TRUE if the interface given by interface_name has been defined, FALSE otherwise.

Examples

Example #1 interface_exists() example

<?php
// Check the interface exists before trying to use it
if (interface_exists('MyInterface')) {
    class MyClass implements MyInterface
    {
        // Methods
    }
}

?>

See Also

  • get_declared_interfaces() - Returns an array of all declared interfaces
  • class_implements() - Return the interfaces which are implemented by the given class or interface
  • class_exists() - Checks if the class has been defined


Checks if the object is of this class or has this class as one of its parents

  • « interface_exists
  • is_subclass_of »
  • PHP Manual
  • Classes/Object Functions
  • Checks if the object is of this class or has this class as one of its parents

is_a

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

is_a — Checks if the object is of this class or has this class as one of its parents

Description

is_a ( mixed $object , string $class_name [, bool $allow_string = FALSE ] ) : bool

Checks if the given object is of this class or has this class as one of its parents.

Parameters

object

A class name or an object instance.

class_name

The class name

allow_string

If this parameter set to FALSE, string class name as object is not allowed. This also prevents from calling autoloader if the class doesn't exist.

Return Values

Returns TRUE if the object is of this class or has this class as one of its parents, FALSE otherwise.

Changelog

Version | Description
5.3.9 | Added allow_string parameter
5.3.0 | This function is no longer deprecated, and will therefore no longer throw E_STRICT warnings.
5.0.0 | This function became deprecated in favour of the instanceof operator. Calling this function will result in an E_STRICT warning.

Examples

Example #1 is_a() example

<?php
// define a class
class WidgetFactory
{
  var $oink = 'moo';
}

// create a new object
$WF = new WidgetFactory();

if (is_a($WF, 'WidgetFactory')) {
  echo "yes, \$WF is still a WidgetFactory\n";
}
?>

Example #2 Using the instanceof operator in PHP 5

<?php
if ($WF instanceof WidgetFactory) {
    echo 'Yes, $WF is a WidgetFactory';
}
?>

See Also

  • get_class() - Returns the name of the class of an object
  • get_parent_class() - Retrieves the parent class name for object or class
  • is_subclass_of() - Checks if the object has this class as one of its parents or implements it


Checks if the object has this class as one of its parents or implements it

  • « is_a
  • method_exists »
  • PHP Manual
  • Classes/Object Functions
  • Checks if the object has this class as one of its parents or implements it

is_subclass_of

(PHP 4, PHP 5, PHP 7)

is_subclass_of — Checks if the object has this class as one of its parents or implements it

Description

is_subclass_of ( mixed $object , string $class_name [, bool $allow_string = TRUE ] ) : bool

Checks if the given object has the class class_name as one of its parents or implements it.

Parameters

object

A class name or an object instance. No error is generated if the class does not exist.

class_name

The class name

allow_string

If this parameter set to false, string class name as object is not allowed. This also prevents from calling autoloader if the class doesn't exist.

Return Values

This function returns TRUE if the object object, belongs to a class which is a subclass of class_name, FALSE otherwise.

Changelog

Version | Description
5.3.9 | Added allow_string parameter
5.3.7 | Added support for class_name to work with interfaces
5.0.3 | You may also specify the object parameter as a string (the name of the class)

Examples

Example #1 is_subclass_of() example

<?php
// define a class
class WidgetFactory
{
  var $oink = 'moo';
}

// define a child class
class WidgetFactory_Child extends WidgetFactory
{
  var $oink = 'oink';
}

// create a new object
$WF = new WidgetFactory();
$WFC = new WidgetFactory_Child();

if (is_subclass_of($WFC, 'WidgetFactory')) {
  echo "yes, \$WFC is a subclass of WidgetFactory\n";
} else {
  echo "no, \$WFC is not a subclass of WidgetFactory\n";
}

if (is_subclass_of($WF, 'WidgetFactory')) {
  echo "yes, \$WF is a subclass of WidgetFactory\n";
} else {
  echo "no, \$WF is not a subclass of WidgetFactory\n";
}

// usable only since PHP 5.0.3
if (is_subclass_of('WidgetFactory_Child', 'WidgetFactory')) {
  echo "yes, WidgetFactory_Child is a subclass of WidgetFactory\n";
} else {
  echo "no, WidgetFactory_Child is not a subclass of WidgetFactory\n";
}
?>

The above example will output:

yes, $WFC is a subclass of WidgetFactory
no, $WF is not a subclass of WidgetFactory
yes, WidgetFactory_Child is a subclass of WidgetFactory

Example #2 is_subclass_of() using interface example

<?php
// Define the Interface
interface MyInterface
{
  public function MyFunction();
}

// Define the class implementation of the interface
class MyClass implements MyInterface
{
  public function MyFunction()
  {
    return "MyClass Implements MyInterface!";
  }
}

// Instantiate the object
$my_object = new MyClass;

// Works since 5.3.7

// Test using the object instance of the class
if (is_subclass_of($my_object, 'MyInterface')) {
  echo "Yes, \$my_object is a subclass of MyInterface\n";
} else {
  echo "No, \$my_object is not a subclass of MyInterface\n";
}

// Test using a string of the class name
if (is_subclass_of('MyClass', 'MyInterface')) {
  echo "Yes, MyClass is a subclass of MyInterface\n";
} else {
  echo "No, MyClass is not a subclass of MyInterface\n";
}
?>

The above example will output:

Yes, $my_object is a subclass of MyInterface
Yes, MyClass is a subclass of MyInterface

Notes

Note:

Using this function will use any registered autoloaders if the class is not already known.

See Also

  • get_class() - Returns the name of the class of an object
  • get_parent_class() - Retrieves the parent class name for object or class
  • is_a() - Checks if the object is of this class or has this class as one of its parents
  • class_parents() - Return the parent classes of the given class


Checks if the class method exists

  • « is_subclass_of
  • property_exists »
  • PHP Manual
  • Classes/Object Functions
  • Checks if the class method exists

method_exists

(PHP 4, PHP 5, PHP 7)

method_exists — Checks if the class method exists

Description

method_exists ( mixed $object , string $method_name ) : bool

Checks if the class method exists in the given object.

Parameters

object

An object instance or a class name

method_name

The method name

Return Values

Returns TRUE if the method given by method_name has been defined for the given object, FALSE otherwise.

Notes

Note:

Using this function will use any registered autoloaders if the class is not already known.

Examples

Example #1 method_exists() example

<?php
$directory = new Directory('.');
var_dump(method_exists($directory,'read'));
?>

The above example will output:

bool(true)

Example #2 Static method_exists() example

<?php
var_dump(method_exists('Directory','read'));
?>

The above example will output:

bool(true)

See Also

  • function_exists() - Return TRUE if the given function has been defined
  • is_callable() - Verify that the contents of a variable can be called as a function
  • class_exists() - Checks if the class has been defined


Checks if the object or class has a property

  • « method_exists
  • trait_exists »
  • PHP Manual
  • Classes/Object Functions
  • Checks if the object or class has a property

property_exists

(PHP 5 >= 5.1.0, PHP 7)

property_exists — Checks if the object or class has a property

Description

property_exists ( mixed $class , string $property ) : bool

This function checks if the given property exists in the specified class.

Note:

As opposed with isset(), property_exists() returns TRUE even if the property has the value NULL.

Parameters

class

The class name or an object of the class to test for

property

The name of the property

Return Values

Returns TRUE if the property exists, FALSE if it doesn't exist or NULL in case of an error.

Notes

Note:

Using this function will use any registered autoloaders if the class is not already known.

Note:

The property_exists() function cannot detect properties that are magically accessible using the __get magic method.

Changelog

Version | Description
5.3.0 | This function checks the existence of a property independent of accessibility.

Examples

Example #1 A property_exists() example

<?php

class myClass {
    public $mine;
    private $xpto;
    static protected $test;

    static function test() {
        var_dump(property_exists('myClass', 'xpto')); //true
    }
}

var_dump(property_exists('myClass', 'mine'));   //true
var_dump(property_exists(new myClass, 'mine')); //true
var_dump(property_exists('myClass', 'xpto'));   //true, as of PHP 5.3.0
var_dump(property_exists('myClass', 'bar'));    //false
var_dump(property_exists('myClass', 'test'));   //true, as of PHP 5.3.0
myClass::test();

?>

See Also

  • method_exists() - Checks if the class method exists


Checks if the trait exists

  • « property_exists
  • Classkit »
  • PHP Manual
  • Classes/Object Functions
  • Checks if the trait exists

trait_exists

(PHP 5 >= 5.4.0, PHP 7)

trait_exists — Checks if the trait exists

Description

trait_exists ( string $traitname [, bool $autoload ] ) : bool

Parameters

traitname

Name of the trait to check

autoload

Whether to autoload if not already loaded.

Return Values

Returns TRUE if trait exists, FALSE if not, NULL in case of an error.


Classkit

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Classkit Functions
    • classkit_import — Import new class method definitions from a file
    • classkit_method_add — Dynamically adds a new method to a given class
    • classkit_method_copy — Copies a method from class to another
    • classkit_method_redefine — Dynamically changes the code of the given method
    • classkit_method_remove — Dynamically removes the given method
    • classkit_method_rename — Dynamically changes the name of the given method


Introduction

These functions allow the dynamic manipulation of PHP classes, at runtime.

Note:

This extension has been replaced by runkit, which is not limited to class manipulation but has function manipulation, as well.


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/classkit.


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.

CLASSKIT_ACC_PRIVATE (int)
Marks the method private
CLASSKIT_ACC_PROTECTED (int)
Marks the method protected
CLASSKIT_ACC_PUBLIC (int)
Marks the method public


Classkit Functions

Table of Contents

  • classkit_import — Import new class method definitions from a file
  • classkit_method_add — Dynamically adds a new method to a given class
  • classkit_method_copy — Copies a method from class to another
  • classkit_method_redefine — Dynamically changes the code of the given method
  • classkit_method_remove — Dynamically removes the given method
  • classkit_method_rename — Dynamically changes the name of the given method


Import new class method definitions from a file

  • « Classkit Functions
  • classkit_method_add »
  • PHP Manual
  • Classkit Functions
  • Import new class method definitions from a file

classkit_import

(PECL classkit >= 0.3)

classkit_import — Import new class method definitions from a file

Description

classkit_import ( string $filename ) : array

Note: This function cannot be used to manipulate the currently running (or chained) method.

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.

Parameters

filename

The filename of the class method definitions to import

Return Values

Associative array of imported methods

Examples

Example #1 classkit_import() example

<?php
// file: newclass.php
class Example {
    function foo() {
        return "bar!\n";
    }
}
?>
<?php
// requires newclass.php (see above)
class Example {
    function foo() {
        return "foo!\n";
    }
}

$e = new Example();

// output original
echo $e->foo();

// import replacement method
classkit_import('newclass.php');

// output imported
echo $e->foo();

?>

The above example will output:

foo!
bar!

See Also

  • classkit_method_add() - Dynamically adds a new method to a given class
  • classkit_method_copy() - Copies a method from class to another


Dynamically adds a new method to a given class

  • « classkit_import
  • classkit_method_copy »
  • PHP Manual
  • Classkit Functions
  • Dynamically adds a new method to a given class

classkit_method_add

(PECL classkit >= 0.1)

classkit_method_add — Dynamically adds a new method to a given class

Description

classkit_method_add ( string $classname , string $methodname , string $args , string $code [, int $flags = CLASSKIT_ACC_PUBLIC ] ) : bool
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.

Parameters

classname

The class to which this method will be added

methodname

The name of the method to add

args

Comma-delimited list of arguments for the newly-created method

code

The code to be evaluated when methodname is called

flags

The type of method to create, can be CLASSKIT_ACC_PUBLIC, CLASSKIT_ACC_PROTECTED or CLASSKIT_ACC_PRIVATE

Note:

This parameter is only used as of PHP 5, because, prior to this, all methods were public.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 classkit_method_add() example

<?php
class Example {
    function foo() {
        echo "foo!\n";
    }
}

// create an Example object
$e = new Example();

// Add a new public method
classkit_method_add(
    'Example',
    'add',
    '$num1, $num2',
    'return $num1 + $num2;',
    CLASSKIT_ACC_PUBLIC
);

// add 12 + 4
echo $e->add(12, 4);
?>

The above example will output:

16

See Also

  • classkit_method_copy() - Copies a method from class to another
  • classkit_method_redefine() - Dynamically changes the code of the given method
  • classkit_method_remove() - Dynamically removes the given method
  • classkit_method_rename() - Dynamically changes the name of the given method
  • create_function() - Create an anonymous (lambda-style) function


Copies a method from class to another

  • « classkit_method_add
  • classkit_method_redefine »
  • PHP Manual
  • Classkit Functions
  • Copies a method from class to another

classkit_method_copy

(PECL classkit >= 0.2)

classkit_method_copy — Copies a method from class to another

Description

classkit_method_copy ( string $dClass , string $dMethod , string $sClass [, string $sMethod ] ) : bool
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.

Parameters

dClass

Destination class for copied method

dMethod

Destination method name

sClass

Source class of the method to copy

sMethod

Name of the method to copy from the source class. If this parameter is omitted, the value of dMethod is assumed.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 classkit_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()
classkit_method_copy('Bar', 'baz', 'Foo', 'example');

// output copied function
echo Bar::baz();
?>

The above example will output:

foo!

See Also

  • classkit_method_add() - Dynamically adds a new method to a given class
  • classkit_method_redefine() - Dynamically changes the code of the given method
  • classkit_method_remove() - Dynamically removes the given method
  • classkit_method_rename() - Dynamically changes the name of the given method


Dynamically changes the code of the given method

  • « classkit_method_copy
  • classkit_method_remove »
  • PHP Manual
  • Classkit Functions
  • Dynamically changes the code of the given method

classkit_method_redefine

(PECL classkit >= 0.1)

classkit_method_redefine — Dynamically changes the code of the given method

Description

classkit_method_redefine ( string $classname , string $methodname , string $args , string $code [, int $flags = CLASSKIT_ACC_PUBLIC ] ) : bool

Note: This function cannot be used to manipulate the currently running (or chained) method.

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.

Parameters

classname

The class in which to redefine the method

methodname

The name of the method to redefine

args

Comma-delimited list of arguments for the redefined method

code

The new code to be evaluated when methodname is called

flags

The redefined method can be CLASSKIT_ACC_PUBLIC, CLASSKIT_ACC_PROTECTED or CLASSKIT_ACC_PRIVATE

Note:

This parameter is only used as of PHP 5, because, prior to this, all methods were public.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 classkit_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
classkit_method_redefine(
    'Example',
    'foo',
    '',
    'return "bar!\n";',
    CLASSKIT_ACC_PUBLIC
);

// output Example::foo() (after redefine)
echo "After: " . $e->foo();
?>

The above example will output:

Before: foo!
After: bar!

See Also

  • classkit_method_add() - Dynamically adds a new method to a given class
  • classkit_method_copy() - Copies a method from class to another
  • classkit_method_remove() - Dynamically removes the given method
  • classkit_method_rename() - Dynamically changes the name of the given method


Dynamically removes the given method

  • « classkit_method_redefine
  • classkit_method_rename »
  • PHP Manual
  • Classkit Functions
  • Dynamically removes the given method

classkit_method_remove

(PECL classkit >= 0.1)

classkit_method_remove — Dynamically removes the given method

Description

classkit_method_remove ( string $classname , string $methodname ) : bool

Note: This function cannot be used to manipulate the currently running (or chained) method.

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.

Parameters

classname

The class in which to remove the method

methodname

The name of the method to remove

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 classkit_method_remove() example

<?php
class Example {
    function foo() {
        return "foo!\n";
    }

    function bar() {
        return "bar!\n";
    }
}

// Remove the 'foo' method
classkit_method_remove(
    'Example',
    'foo'
);

echo implode(' ', get_class_methods('Example'));

?>

The above example will output:

bar

See Also

  • classkit_method_add() - Dynamically adds a new method to a given class
  • classkit_method_copy() - Copies a method from class to another
  • classkit_method_redefine() - Dynamically changes the code of the given method
  • classkit_method_rename() - Dynamically changes the name of the given method


Dynamically changes the name of the given method

  • « classkit_method_remove
  • Ctype »
  • PHP Manual
  • Classkit Functions
  • Dynamically changes the name of the given method

classkit_method_rename

(PECL classkit >= 0.1)

classkit_method_rename — Dynamically changes the name of the given method

Description

classkit_method_rename ( string $classname , string $methodname , string $newname ) : bool

Note: This function cannot be used to manipulate the currently running (or chained) method.

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.

Parameters

classname

The class in which to rename the method

methodname

The name of the method to rename

newname

The new name to give to the renamed method

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 classkit_method_rename() example

<?php
class Example {
    function foo() {
        return "foo!\n";
    }
}

// Rename the 'foo' method to 'bar'
classkit_method_rename(
    'Example',
    'foo',
    'bar'
);

// output renamed function
echo Example::bar();
?>

The above example will output:

foo!

See Also

  • classkit_method_add() - Dynamically adds a new method to a given class
  • classkit_method_copy() - Copies a method from class to another
  • classkit_method_redefine() - Dynamically changes the code of the given method
  • classkit_method_remove() - Dynamically removes the given method


Character type checking

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Ctype Functions
    • ctype_alnum — Check for alphanumeric character(s)
    • ctype_alpha — Check for alphabetic character(s)
    • ctype_cntrl — Check for control character(s)
    • ctype_digit — Check for numeric character(s)
    • ctype_graph — Check for any printable character(s) except space
    • ctype_lower — Check for lowercase character(s)
    • ctype_print — Check for printable character(s)
    • ctype_punct — Check for any printable character which is not whitespace or an alphanumeric character
    • ctype_space — Check for whitespace character(s)
    • ctype_upper — Check for uppercase character(s)
    • ctype_xdigit — Check for character(s) representing a hexadecimal digit


Introduction

The functions provided by this extension check whether a character or string falls into a certain character class according to the current locale (see also setlocale()).

When called with an integer argument these functions behave exactly like their C counterparts from ctype.h. It means that if you pass an integer smaller than 256 it will use the ASCII value of it to see if it fits in the specified range (digits are in 0x30-0x39). If the number is between -128 and -1 inclusive then 256 will be added and the check will be done on that.

When called with a string argument they will check every character in the string and will only return TRUE if every character in the string matches the requested criteria. When called with an empty string the result will always be TRUE in PHP < 5.1 and FALSE since 5.1.

Passing anything else but a string or integer will return FALSE immediately.

It should be noted that ctype functions are always preferred over regular expressions, and even to some equivalent "str_*" and "is_*" functions. This is because of the fact that ctype uses a native C library and thus processes significantly faster.

Note:

These functions are not related to the Python "ctypes" library at all. The extension name stems from the ctype.h C header file that their C equivalents are defined in.

This extension also predates Python "ctypes" so any confusion caused by this naming is hardly our fault ...


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

None besides functions from the standard C library which are always available.


Installation

ctype support can be disabled with --disable-ctype .

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.


  • « Resource Types
  • Ctype Functions »
  • PHP Manual
  • Ctype
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


Ctype Functions

Table of Contents

  • ctype_alnum — Check for alphanumeric character(s)
  • ctype_alpha — Check for alphabetic character(s)
  • ctype_cntrl — Check for control character(s)
  • ctype_digit — Check for numeric character(s)
  • ctype_graph — Check for any printable character(s) except space
  • ctype_lower — Check for lowercase character(s)
  • ctype_print — Check for printable character(s)
  • ctype_punct — Check for any printable character which is not whitespace or an alphanumeric character
  • ctype_space — Check for whitespace character(s)
  • ctype_upper — Check for uppercase character(s)
  • ctype_xdigit — Check for character(s) representing a hexadecimal digit


Check for alphanumeric character(s)

  • « Ctype Functions
  • ctype_alpha »
  • PHP Manual
  • Ctype Functions
  • Check for alphanumeric character(s)

ctype_alnum

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

ctype_alnum — Check for alphanumeric character(s)

Description

ctype_alnum ( string $text ) : bool

Checks if all of the characters in the provided string, text, are alphanumeric.

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in text is either a letter or a digit, FALSE otherwise.

Examples

Example #1 A ctype_alnum() example (using the default locale)

<?php
$strings = array('AbCd1zyZ9', 'foo!#$bar');
foreach ($strings as $testcase) {
    if (ctype_alnum($testcase)) {
        echo "The string $testcase consists of all letters or digits.\n";
    } else {
        echo "The string $testcase does not consist of all letters or digits.\n";
    }
}
?>

The above example will output:

The string AbCd1zyZ9 consists of all letters or digits.
The string foo!#$bar does not consist of all letters or digits.

Notes

Note:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

See Also

  • ctype_alpha() - Check for alphabetic character(s)
  • ctype_digit() - Check for numeric character(s)
  • setlocale() - Set locale information


Check for alphabetic character(s)

  • « ctype_alnum
  • ctype_cntrl »
  • PHP Manual
  • Ctype Functions
  • Check for alphabetic character(s)

ctype_alpha

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

ctype_alpha — Check for alphabetic character(s)

Description

ctype_alpha ( string $text ) : bool

Checks if all of the characters in the provided string, text, are alphabetic. In the standard C locale letters are just [A-Za-z] and ctype_alpha() is equivalent to (ctype_upper($text) || ctype_lower($text)) if $text is just a single character, but other languages have letters that are considered neither upper nor lower case.

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in text is a letter from the current locale, FALSE otherwise.

Examples

Example #1 A ctype_alpha() example (using the default locale)

<?php
$strings = array('KjgWZC', 'arf12');
foreach ($strings as $testcase) {
    if (ctype_alpha($testcase)) {
        echo "The string $testcase consists of all letters.\n";
    } else {
        echo "The string $testcase does not consist of all letters.\n";
    }
}
?>

The above example will output:

The string KjgWZC consists of all letters.
The string arf12 does not consist of all letters.

Notes

Note:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

See Also

  • ctype_upper() - Check for uppercase character(s)
  • ctype_lower() - Check for lowercase character(s)
  • setlocale() - Set locale information


Check for control character(s)

  • « ctype_alpha
  • ctype_digit »
  • PHP Manual
  • Ctype Functions
  • Check for control character(s)

ctype_cntrl

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

ctype_cntrl — Check for control character(s)

Description

ctype_cntrl ( string $text ) : bool

Checks if all of the characters in the provided string, text, are control characters. Control characters are e.g. line feed, tab, escape.

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in text is a control character from the current locale, FALSE otherwise.

Examples

Example #1 A ctype_cntrl() example

<?php
$strings = array('string1' => "\n\r\t", 'string2' => 'arf12');
foreach ($strings as $name => $testcase) {
    if (ctype_cntrl($testcase)) {
        echo "The string '$name' consists of all control characters.\n";
    } else {
        echo "The string '$name' does not consist of all control characters.\n";
    }
}
?>

The above example will output:

The string 'string1' consists of all control characters.
The string 'string2' does not consist of all control characters.

Notes

Note:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

See Also

  • ctype_print() - Check for printable character(s)


Check for numeric character(s)

  • « ctype_cntrl
  • ctype_graph »
  • PHP Manual
  • Ctype Functions
  • Check for numeric character(s)

ctype_digit

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

ctype_digit — Check for numeric character(s)

Description

ctype_digit ( string $text ) : bool

Checks if all of the characters in the provided string, text, are numerical.

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in the string text is a decimal digit, FALSE otherwise.

Changelog

Version | Description
5.1.0 | Before PHP 5.1.0, this function returned TRUE when text was an empty string.

Examples

Example #1 A ctype_digit() example

<?php
$strings = array('1820.20', '10002', 'wsl!12');
foreach ($strings as $testcase) {
    if (ctype_digit($testcase)) {
        echo "The string $testcase consists of all digits.\n";
    } else {
        echo "The string $testcase does not consist of all digits.\n";
    }
}
?>

The above example will output:

The string 1820.20 does not consist of all digits.
The string 10002 consists of all digits.
The string wsl!12 does not consist of all digits.

Example #2 A ctype_digit() example comparing strings with integers

<?php

$numeric_string = '42';
$integer        = 42;

ctype_digit($numeric_string);  // true
ctype_digit($integer);         // false (ASCII 42 is the * character)

is_numeric($numeric_string);   // true
is_numeric($integer);          // true
?>

Notes

Note:

This function expects a string to be useful, so for example passing in an integer may not return the expected result. However, also note that HTML forms will result in numeric strings and not integers. See also the types section of the manual.

Note:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

See Also

  • ctype_alnum() - Check for alphanumeric character(s)
  • ctype_xdigit() - Check for character(s) representing a hexadecimal digit
  • is_numeric() - Finds whether a variable is a number or a numeric string
  • is_int() - Find whether the type of a variable is integer
  • is_string() - Find whether the type of a variable is string


Check for any printable character(s) except space

  • « ctype_digit
  • ctype_lower »
  • PHP Manual
  • Ctype Functions
  • Check for any printable character(s) except space

ctype_graph

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

ctype_graph — Check for any printable character(s) except space

Description

ctype_graph ( string $text ) : bool

Checks if all of the characters in the provided string, text, creates visible output.

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in text is printable and actually creates visible output (no white space), FALSE otherwise.

Examples

Example #1 A ctype_graph() example

<?php
$strings = array('string1' => "asdf\n\r\t", 'string2' => 'arf12', 'string3' => 'LKA#@%.54');
foreach ($strings as $name => $testcase) {
    if (ctype_graph($testcase)) {
        echo "The string '$name' consists of all (visibly) printable characters.\n";
    } else {
        echo "The string '$name' does not consist of all (visibly) printable characters.\n";
    }
}
?>

The above example will output:

The string 'string1' does not consist of all (visibly) printable characters.
The string 'string2' consists of all (visibly) printable characters.
The string 'string3' consists of all (visibly) printable characters.

Notes

Note:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

See Also

  • ctype_alnum() - Check for alphanumeric character(s)
  • ctype_print() - Check for printable character(s)
  • ctype_punct() - Check for any printable character which is not whitespace or an alphanumeric character


Check for lowercase character(s)

  • « ctype_graph
  • ctype_print »
  • PHP Manual
  • Ctype Functions
  • Check for lowercase character(s)

ctype_lower

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

ctype_lower — Check for lowercase character(s)

Description

ctype_lower ( string $text ) : bool

Checks if all of the characters in the provided string, text, are lowercase letters.

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in text is a lowercase letter in the current locale.

Examples

Example #1 A ctype_lower() example (using the default locale)

<?php
$strings = array('aac123', 'qiutoas', 'QASsdks');
foreach ($strings as $testcase) {
    if (ctype_lower($testcase)) {
        echo "The string $testcase consists of all lowercase letters.\n";
    } else {
        echo "The string $testcase does not consist of all lowercase letters.\n";
    }
}
?>

The above example will output:

The string aac123 does not consist of all lowercase letters.
The string qiutoas consists of all lowercase letters.
The string QASsdks does not consist of all lowercase letters.

Notes

Note:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

See Also

  • ctype_alpha() - Check for alphabetic character(s)
  • ctype_upper() - Check for uppercase character(s)
  • setlocale() - Set locale information


Check for printable character(s)

  • « ctype_lower
  • ctype_punct »
  • PHP Manual
  • Ctype Functions
  • Check for printable character(s)

ctype_print

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

ctype_print — Check for printable character(s)

Description

ctype_print ( string $text ) : bool

Checks if all of the characters in the provided string, text, are printable.

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in text will actually create output (including blanks). Returns FALSE if text contains control characters or characters that do not have any output or control function at all.

Examples

Example #1 A ctype_print() example

<?php
$strings = array('string1' => "asdf\n\r\t", 'string2' => 'arf12', 'string3' => 'LKA#@%.54');
foreach ($strings as $name => $testcase) {
    if (ctype_print($testcase)) {
        echo "The string '$name' consists of all printable characters.\n";
    } else {
        echo "The string '$name' does not consist of all printable characters.\n";
    }
}
?>

The above example will output:

The string 'string1' does not consist of all printable characters.
The string 'string2' consists of all printable characters.
The string 'string3' consists of all printable characters.

Notes

Note:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

See Also

  • ctype_cntrl() - Check for control character(s)
  • ctype_graph() - Check for any printable character(s) except space
  • ctype_punct() - Check for any printable character which is not whitespace or an alphanumeric character


Check for any printable character which is not whitespace or an alphanumeric character

  • « ctype_print
  • ctype_space »
  • PHP Manual
  • Ctype Functions
  • Check for any printable character which is not whitespace or an alphanumeric character

ctype_punct

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

ctype_punct — Check for any printable character which is not whitespace or an alphanumeric character

Description

ctype_punct ( string $text ) : bool

Checks if all of the characters in the provided string, text, are punctuation character.

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in text is printable, but neither letter, digit or blank, FALSE otherwise.

Examples

Example #1 A ctype_punct() example

<?php
$strings = array('ABasdk!@!$#', '!@ # $', '*&$()');
foreach ($strings as $testcase) {
    if (ctype_punct($testcase)) {
        echo "The string $testcase consists of all punctuation.\n";
    } else {
        echo "The string $testcase does not consist of all punctuation.\n";
    }
}
?>

The above example will output:

The string ABasdk!@!$# does not consist of all punctuation.
The string !@ # $ does not consist of all punctuation.
The string *&$() consists of all punctuation.

Notes

Note:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

See Also

  • ctype_cntrl() - Check for control character(s)
  • ctype_graph() - Check for any printable character(s) except space


Check for whitespace character(s)

  • « ctype_punct
  • ctype_upper »
  • PHP Manual
  • Ctype Functions
  • Check for whitespace character(s)

ctype_space

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

ctype_space — Check for whitespace character(s)

Description

ctype_space ( string $text ) : bool

Checks if all of the characters in the provided string, text, creates whitespace.

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in text creates some sort of white space, FALSE otherwise. Besides the blank character this also includes tab, vertical tab, line feed, carriage return and form feed characters.

Examples

Example #1 A ctype_space() example

<?php
$strings = array(
    'string1' => "\n\r\t",
    'string2' => "\narf12",
    'string3' => '\n\r\t' // note the single quotes
);
foreach ($strings as $name => $testcase) {
    if (ctype_space($testcase)) {
        echo "The string '$name' consists of whitespace characters only.\n";
    } else {
        echo "The string '$name' contains non-whitespace characters.\n";
    }
}
?>

The above example will output:

The string 'string1' consists of whitespace characters only.
The string 'string2' contains non-whitespace characters.
The string 'string3' contains non-whitespace characters.

Notes

Note:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

See Also

  • ctype_cntrl() - Check for control character(s)
  • ctype_graph() - Check for any printable character(s) except space
  • ctype_punct() - Check for any printable character which is not whitespace or an alphanumeric character


Check for uppercase character(s)

  • « ctype_space
  • ctype_xdigit »
  • PHP Manual
  • Ctype Functions
  • Check for uppercase character(s)

ctype_upper

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

ctype_upper — Check for uppercase character(s)

Description

ctype_upper ( string $text ) : bool

Checks if all of the characters in the provided string, text, are uppercase characters.

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in text is an uppercase letter in the current locale.

Examples

Example #1 A ctype_upper() example (using the default locale)

<?php
$strings = array('AKLWC139', 'LMNSDO', 'akwSKWsm');
foreach ($strings as $testcase) {
    if (ctype_upper($testcase)) {
        echo "The string $testcase consists of all uppercase letters.\n";
    } else {
        echo "The string $testcase does not consist of all uppercase letters.\n";
    }
}
?>

The above example will output:

The string AKLWC139 does not consist of all uppercase letters.
The string LMNSDO consists of all uppercase letters.
The string akwSKWsm does not consist of all uppercase letters.

Notes

Note:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

See Also

  • ctype_alpha() - Check for alphabetic character(s)
  • ctype_lower() - Check for lowercase character(s)
  • setlocale() - Set locale information


Check for character(s) representing a hexadecimal digit

  • « ctype_upper
  • Filter »
  • PHP Manual
  • Ctype Functions
  • Check for character(s) representing a hexadecimal digit

ctype_xdigit

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

ctype_xdigit — Check for character(s) representing a hexadecimal digit

Description

ctype_xdigit ( string $text ) : bool

Checks if all of the characters in the provided string, text, are hexadecimal 'digits'.

Parameters

text

The tested string.

Return Values

Returns TRUE if every character in text is a hexadecimal 'digit', that is a decimal digit or a character from [A-Fa-f] , FALSE otherwise.

Examples

Example #1 A ctype_xdigit() example

<?php
$strings = array('AB10BC99', 'AR1012', 'ab12bc99');
foreach ($strings as $testcase) {
    if (ctype_xdigit($testcase)) {
        echo "The string $testcase consists of all hexadecimal digits.\n";
    } else {
        echo "The string $testcase does not consist of all hexadecimal digits.\n";
    }
}
?>

The above example will output:

The string AB10BC99 consists of all hexadecimal digits.
The string AR1012 does not consist of all hexadecimal digits.
The string ab12bc99 consists of all hexadecimal digits.

Notes

Note:

If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

See Also

  • ctype_digit() - Check for numeric character(s)


Data Filtering

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Types of filters
    • Validate filters
    • Sanitize filters
    • Other filters
    • Filter flags
  • Predefined Constants
  • Examples
    • Validation
    • Sanitization
  • Filter Functions
    • filter_has_var — Checks if variable of specified type exists
    • filter_id — Returns the filter ID belonging to a named filter
    • filter_input_array — Gets external variables and optionally filters them
    • filter_input — Gets a specific external variable by name and optionally filters it
    • filter_list — Returns a list of all supported filters
    • filter_var_array — Gets multiple variables and optionally filters them
    • filter_var — Filters a variable with a specified filter


Introduction

This extension filters data by either validating or sanitizing it. This is especially useful when the data source contains unknown (or foreign) data, like user supplied input. For example, this data may come from an HTML form.

There are two main types of filtering: validation and sanitization.

Validation is used to validate or check if the data meets certain qualifications. For example, passing in FILTER_VALIDATE_EMAIL will determine if the data is a valid email address, but will not change the data itself.

Sanitization will sanitize the data, so it may alter it by removing undesired characters. For example, passing in FILTER_SANITIZE_EMAIL will remove characters that are inappropriate for an email address to contain. That said, it does not validate the data.

Flags are optionally used with both validation and sanitization to tweak behaviour according to need. For example, passing in FILTER_FLAG_PATH_REQUIRED while filtering an URL will require a path (like /foo in http://example.org/foo) to be present.


Installation

The filter extension is enabled by default as of PHP 5.2.0. To disable the filter extension, use --disable-filter .

Before PHP 5.2 an experimental PECL extension was used, however, the PECL version is no longer recommended or updated.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Filter Configuration Options
Name | Default | Changeable | Changelog
filter.default | "unsafe_raw" | PHP_INI_PERDIR | PHP_INI_ALL in filter <= 0.9.4. Available since PHP 5.2.0.
filter.default_flags | NULL | PHP_INI_PERDIR | PHP_INI_ALL in filter <= 0.9.4. Available since PHP 5.2.0.
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

filter.default string

Filter all $_GET, $_POST, $_COOKIE, $_REQUEST and $_SERVER data by this filter. Original data can be accessed through filter_input().

Accepts the name of the filter you like to use by default. See the existing filter list for the list of the filter names.

Note:

Be careful about the default flags for the default filters. You should explicitly set them to the value you want. For example, to configure the default filter to behave exactly like htmlspecialchars() you need to set them default flags to 0 as shown below.

Example #1 Configuring the default filter to act like htmlspecialchars

filter.default = full_special_chars
filter.default_flags = 0

filter.default_flags integer

Default flags to apply when the default filter is set. This is set to FILTER_FLAG_NO_ENCODE_QUOTES by default for backwards compatibility reasons. See the flag list for the list of all the flag names.


  • « Runtime Configuration
  • Types of filters »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

This extension has no resource types defined.


Types of filters

Table of Contents

  • Validate filters
  • Sanitize filters
  • Other filters
  • Filter flags


Validate filters

Listing of filters for validation
ID | Name | Options | Flags | Description
FILTER_VALIDATE_BOOLEAN | "boolean" | default | FILTER_NULL_ON_FAILURE | Returns TRUE for "1", "true", "on" and "yes". Returns FALSE otherwise. If FILTER_NULL_ON_FAILURE is set, FALSE is returned only for "0", "false", "off", "no", and "", and NULL is returned for all non-boolean values.
FILTER_VALIDATE_DOMAIN | "validate_domain" | default | FILTER_FLAG_HOSTNAME | Validates whether the domain name label lengths are valid. Validates domain names against RFC 1034, RFC 1035, RFC 952, RFC 1123, RFC 2732, RFC 2181, and RFC 1123. Optional flag FILTER_FLAG_HOSTNAME adds ability to specifically validate hostnames (they must start with an alphanumberic character and contain only alphanumerics or hyphens).
FILTER_VALIDATE_EMAIL | "validate_email" | default | FILTER_FLAG_EMAIL_UNICODE | Validates whether the value is a valid e-mail address. In general, this validates e-mail addresses against the syntax in RFC 822, with the exceptions that comments and whitespace folding and dotless domain names are not supported.
FILTER_VALIDATE_FLOAT | "float" | default, decimal, min_range, max_range | FILTER_FLAG_ALLOW_THOUSAND | Validates value as float, optionally from the specified range, and converts to float on success.
FILTER_VALIDATE_INT | "int" | default, min_range, max_range | FILTER_FLAG_ALLOW_OCTAL, FILTER_FLAG_ALLOW_HEX | Validates value as integer, optionally from the specified range, and converts to int on success.
FILTER_VALIDATE_IP | "validate_ip" | default | FILTER_FLAG_IPV4, FILTER_FLAG_IPV6, FILTER_FLAG_NO_PRIV_RANGE, FILTER_FLAG_NO_RES_RANGE | Validates value as IP address, optionally only IPv4 or IPv6 or not from private or reserved ranges.
FILTER_VALIDATE_MAC | "validate_mac_address" | default |  | Validates value as MAC address.
FILTER_VALIDATE_REGEXP | "validate_regexp" | default, regexp |  | Validates value against regexp, a Perl-compatible regular expression.
FILTER_VALIDATE_URL | "validate_url" | default | FILTER_FLAG_SCHEME_REQUIRED, FILTER_FLAG_HOST_REQUIRED, FILTER_FLAG_PATH_REQUIRED, FILTER_FLAG_QUERY_REQUIRED | Validates value as URL (according to » http://www.faqs.org/rfcs/rfc2396), optionally with required components. Beware a valid URL may not specify the HTTP protocol http:// so further validation may be required to determine the URL uses an expected protocol, e.g. ssh:// or mailto:. Note that the function will only find ASCII URLs to be valid; internationalized domain names (containing non-ASCII characters) will fail.

Note:

As of PHP 5.4.11, the numbers +0 and -0 validate as both integers as well as floats (using FILTER_VALIDATE_FLOAT and FILTER_VALIDATE_INT). Before PHP 5.4.11 they only validated as floats (using FILTER_VALIDATE_FLOAT).

When default is set to option, default's value is used if value is not validated.

Changelog

Version | Description
7.4.0 | Added min_range and max_range options for FILTER_VALIDATE_FLOAT.
7.0.0 | Added FILTER_FLAG_HOSTNAME
5.5.0 | Added FILTER_VALIDATE_MAC
5.2.1 | FILTER_VALIDATE_URL now implicitly uses FILTER_FLAG_SCHEME_REQUIRED and FILTER_FLAG_HOST_REQUIRED.


Sanitize filters

List of filters for sanitization
ID | Name | Flags | Description
FILTER_SANITIZE_EMAIL | "email" |  | Remove all characters except letters, digits and !#$%&'*+-=?^_`{|}~@.[].
FILTER_SANITIZE_ENCODED | "encoded" | FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_STRIP_BACKTICK, FILTER_FLAG_ENCODE_LOW, FILTER_FLAG_ENCODE_HIGH | URL-encode string, optionally strip or encode special characters.
FILTER_SANITIZE_MAGIC_QUOTES | "magic_quotes" |  | Apply addslashes().
FILTER_SANITIZE_NUMBER_FLOAT | "number_float" | FILTER_FLAG_ALLOW_FRACTION, FILTER_FLAG_ALLOW_THOUSAND, FILTER_FLAG_ALLOW_SCIENTIFIC | Remove all characters except digits, +- and optionally .,eE.
FILTER_SANITIZE_NUMBER_INT | "number_int" |  | Remove all characters except digits, plus and minus sign.
FILTER_SANITIZE_SPECIAL_CHARS | "special_chars" | FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_STRIP_BACKTICK, FILTER_FLAG_ENCODE_HIGH | HTML-escape '"<>& and characters with ASCII value less than 32, optionally strip or encode other special characters.
FILTER_SANITIZE_FULL_SPECIAL_CHARS | "full_special_chars" | FILTER_FLAG_NO_ENCODE_QUOTES, | Equivalent to calling htmlspecialchars() with ENT_QUOTES set. Encoding quotes can be disabled by setting FILTER_FLAG_NO_ENCODE_QUOTES. Like htmlspecialchars(), this filter is aware of the default_charset and if a sequence of bytes is detected that makes up an invalid character in the current character set then the entire string is rejected resulting in a 0-length string. When using this filter as a default filter, see the warning below about setting the default flags to 0.
FILTER_SANITIZE_STRING | "string" | FILTER_FLAG_NO_ENCODE_QUOTES, FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_STRIP_BACKTICK, FILTER_FLAG_ENCODE_LOW, FILTER_FLAG_ENCODE_HIGH, FILTER_FLAG_ENCODE_AMP | Strip tags, optionally strip or encode special characters.
FILTER_SANITIZE_STRIPPED | "stripped" |  | Alias of "string" filter.
FILTER_SANITIZE_URL | "url" |  | Remove all characters except letters, digits and $-_.+!*'(),{}|\\^~[]`<>#%";/?:@&=.
FILTER_UNSAFE_RAW | "unsafe_raw" | FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_STRIP_BACKTICK, FILTER_FLAG_ENCODE_LOW, FILTER_FLAG_ENCODE_HIGH, FILTER_FLAG_ENCODE_AMP | Do nothing, optionally strip or encode special characters. This filter is also aliased to FILTER_DEFAULT.

Warning

When using one of these filters as a default filter either through your ini file or through your web server's configuration, the default flags is set to FILTER_FLAG_NO_ENCODE_QUOTES. You need to explicitly set filter.default_flags to 0 to have quotes encoded by default. Like this:

Example #1 Configuring the default filter to act like htmlspecialchars

filter.default = full_special_chars
filter.default_flags = 0

Changelog

Version | Description
5.2.11/5.3.1 | Slashes (/) are removed by FILTER_SANITIZE_EMAIL. Prior they were retained.


Other filters

List of miscellaneous filters
ID | Name | Options | Flags | Description
FILTER_CALLBACK | "callback" | callable function or method | All flags are ignored | Call user-defined function to filter data.


Filter flags

List of filter flags
ID | Used with | Description
FILTER_FLAG_STRIP_LOW | FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_SANITIZE_STRING, FILTER_UNSAFE_RAW | Strips characters that have a numerical value <32.
FILTER_FLAG_STRIP_HIGH | FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_SANITIZE_STRING, FILTER_UNSAFE_RAW | Strips characters that have a numerical value >127.
FILTER_FLAG_STRIP_BACKTICK | FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_SANITIZE_STRING, FILTER_UNSAFE_RAW | Strips backtick characters.
FILTER_FLAG_ALLOW_FRACTION | FILTER_SANITIZE_NUMBER_FLOAT | Allows a period (.) as a fractional separator in numbers.
FILTER_FLAG_ALLOW_THOUSAND | FILTER_SANITIZE_NUMBER_FLOAT, FILTER_VALIDATE_FLOAT | Allows a comma (,) as a thousands separator in numbers.
FILTER_FLAG_ALLOW_SCIENTIFIC | FILTER_SANITIZE_NUMBER_FLOAT | Allows an e or E for scientific notation in numbers.
FILTER_FLAG_NO_ENCODE_QUOTES | FILTER_SANITIZE_STRING | If this flag is present, single (') and double (") quotes will not be encoded.
FILTER_FLAG_ENCODE_LOW | FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_STRING, FILTER_SANITIZE_RAW | Encodes all characters with a numerical value <32.
FILTER_FLAG_ENCODE_HIGH | FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_SANITIZE_STRING, FILTER_SANITIZE_RAW | Encodes all characters with a numerical value >127.
FILTER_FLAG_ENCODE_AMP | FILTER_SANITIZE_STRING, FILTER_SANITIZE_RAW | Encodes ampersands (&).
FILTER_NULL_ON_FAILURE | FILTER_VALIDATE_BOOLEAN | Returns NULL for unrecognized boolean values.
FILTER_FLAG_ALLOW_OCTAL | FILTER_VALIDATE_INT | Regards inputs starting with a zero (0) as octal numbers. This only allows the succeeding digits to be 0-7.
FILTER_FLAG_ALLOW_HEX | FILTER_VALIDATE_INT | Regards inputs starting with 0x or 0X as hexadecimal numbers. This only allows succeeding characters to be a-fA-F0-9.
FILTER_FLAG_EMAIL_UNICODE | FILTER_VALIDATE_EMAIL | Allows the local part of the email address to contain Unicode characters.
FILTER_FLAG_IPV4 | FILTER_VALIDATE_IP | Allows the IP address to be in IPv4 format.
FILTER_FLAG_IPV6 | FILTER_VALIDATE_IP | Allows the IP address to be in IPv6 format.
FILTER_FLAG_NO_PRIV_RANGE | FILTER_VALIDATE_IP | Fails validation for the following private IPv4 ranges: 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16. Fails validation for the IPv6 addresses starting with FD or FC.
FILTER_FLAG_NO_RES_RANGE | FILTER_VALIDATE_IP | Fails validation for the following reserved IPv4 ranges: 0.0.0.0/8, 169.254.0.0/16, 127.0.0.0/8 and 240.0.0.0/4. Fails validation for the following reserved IPv6 ranges: ::1/128, ::/128, ::ffff:0:0/96 and fe80::/10.
FILTER_FLAG_SCHEME_REQUIRED | FILTER_VALIDATE_URL | Requires the URL to contain a scheme part.
FILTER_FLAG_HOST_REQUIRED | FILTER_VALIDATE_URL | Requires the URL to contain a host part.
FILTER_FLAG_PATH_REQUIRED | FILTER_VALIDATE_URL | Requires the URL to contain a path part.
FILTER_FLAG_QUERY_REQUIRED | FILTER_VALIDATE_URL | Requires the URL to contain a query string.
FILTER_REQUIRE_SCALAR |  | Requires the value to be scalar.
FILTER_REQUIRE_ARRAY |  | Requires the value to be an array.
FILTER_FORCE_ARRAY |  | If the value is a scalar, it is treated as array with the scalar value as only element.

Changelog

Version | Description
7.3.0 | The explicit usage of FILTER_FLAG_SCHEME_REQUIRED and FILTER_FLAG_HOST_REQUIRED has been deprecated.
7.1.0 | FILTER_FLAG_EMAIL_UNICODE has been added.
5.3.2 | FILTER_FLAG_STRIP_BACKTICK has been added.
5.2.10 | FILTER_FLAG_NO_RES_RANGE supports also IPv6 addresses.


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.

INPUT_POST (integer)
POST variables.
INPUT_GET (integer)
GET variables.
INPUT_COOKIE (integer)
COOKIE variables.
INPUT_ENV (integer)
ENV variables.
INPUT_SERVER (integer)
SERVER variables.
INPUT_SESSION (integer)
SESSION variables. (not implemented yet)
INPUT_REQUEST (integer)
REQUEST variables. (not implemented yet)
FILTER_FLAG_NONE (integer)
No flags.
FILTER_REQUIRE_SCALAR (integer)
Flag used to require scalar as input
FILTER_REQUIRE_ARRAY (integer)
Require an array as input.
FILTER_FORCE_ARRAY (integer)
Always returns an array.
FILTER_NULL_ON_FAILURE (integer)
Use NULL instead of FALSE on failure.
FILTER_VALIDATE_INT (integer)
ID of "int" filter.
FILTER_VALIDATE_BOOLEAN (integer)
ID of "boolean" filter.
FILTER_VALIDATE_FLOAT (integer)
ID of "float" filter.
FILTER_VALIDATE_REGEXP (integer)
ID of "validate_regexp" filter.
FILTER_VALIDATE_URL (integer)
ID of "validate_url" filter.
FILTER_VALIDATE_EMAIL (integer)
ID of "validate_email" filter.
FILTER_VALIDATE_IP (integer)
ID of "validate_ip" filter.
FILTER_VALIDATE_MAC (integer)
ID of "validate_mac_address" filter. (Available as of PHP 5.5.0)
FILTER_DEFAULT (integer)
ID of default ("unsafe_raw") filter. This is equivalent to FILTER_UNSAFE_RAW.
FILTER_UNSAFE_RAW (integer)
ID of "unsafe_raw" filter.
FILTER_SANITIZE_STRING (integer)
ID of "string" filter.
FILTER_SANITIZE_STRIPPED (integer)
ID of "stripped" filter.
FILTER_SANITIZE_ENCODED (integer)
ID of "encoded" filter.
FILTER_SANITIZE_SPECIAL_CHARS (integer)
ID of "special_chars" filter.
FILTER_SANITIZE_EMAIL (integer)
ID of "email" filter.
FILTER_SANITIZE_URL (integer)
ID of "url" filter.
FILTER_SANITIZE_NUMBER_INT (integer)
ID of "number_int" filter.
FILTER_SANITIZE_NUMBER_FLOAT (integer)
ID of "number_float" filter.
FILTER_SANITIZE_MAGIC_QUOTES (integer)
ID of "magic_quotes" filter.
FILTER_CALLBACK (integer)
ID of "callback" filter.
FILTER_FLAG_ALLOW_OCTAL (integer)
Allow octal notation (0[0-7]+) in "int" filter.
FILTER_FLAG_ALLOW_HEX (integer)
Allow hex notation (0x[0-9a-fA-F]+) in "int" filter.
FILTER_FLAG_STRIP_LOW (integer)
Strip characters with ASCII value less than 32.
FILTER_FLAG_STRIP_HIGH (integer)
Strip characters with ASCII value greater than 127.
FILTER_FLAG_ENCODE_LOW (integer)
Encode characters with ASCII value less than 32.
FILTER_FLAG_ENCODE_HIGH (integer)
Encode characters with ASCII value greater than 127.
FILTER_FLAG_ENCODE_AMP (integer)
Encode &.
FILTER_FLAG_NO_ENCODE_QUOTES (integer)
Don't encode ' and ".
FILTER_FLAG_EMPTY_STRING_NULL (integer)
(No use for now.)
FILTER_FLAG_ALLOW_FRACTION (integer)
Allow fractional part in "number_float" filter.
FILTER_FLAG_ALLOW_THOUSAND (integer)
Allow thousand separator (,) in "number_float" filter.
FILTER_FLAG_ALLOW_SCIENTIFIC (integer)
Allow scientific notation (e, E) in "number_float" filter.
FILTER_FLAG_PATH_REQUIRED (integer)
Require path in "validate_url" filter.
FILTER_FLAG_QUERY_REQUIRED (integer)
Require query in "validate_url" filter.
FILTER_FLAG_IPV4 (integer)
Allow only IPv4 address in "validate_ip" filter.
FILTER_FLAG_IPV6 (integer)
Allow only IPv6 address in "validate_ip" filter.
FILTER_FLAG_NO_RES_RANGE (integer)
Deny reserved addresses in "validate_ip" filter.
FILTER_FLAG_NO_PRIV_RANGE (integer)
Deny private addresses in "validate_ip" filter.
FILTER_FLAG_EMAIL_UNICODE (integer)
Accepts Unicode characters in the local part in "validate_email" filter. (Available as of PHP 7.1.0)


  • « Predefined Constants
  • Validation »
  • PHP Manual
  • Filter
  • Examples

Examples

Table of Contents

  • Validation
  • Sanitization


Validation

Example #1 Validating email addresses with filter_var()

<?php
$email_a = 'joe@example.com';
$email_b = 'bogus';

if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
    echo "Email address '$email_a' is considered valid.\n";
}
if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
    echo "Email address '$email_b' is considered valid.\n";
} else {
    echo "Email address '$email_b' is considered invalid.\n";
}
?>

The above example will output:

Email address 'joe@example.com' is considered valid.
Email address 'bogus' is considered invalid.

Example #2 Validating IP addresses with filter_var()

<?php
$ip_a = '127.0.0.1';
$ip_b = '42.42';

if (filter_var($ip_a, FILTER_VALIDATE_IP)) {
    echo "IP address '$ip_a' is considered valid.";
}
if (filter_var($ip_b, FILTER_VALIDATE_IP)) {
    echo "IP address '$ip_b' is considered valid.";
}
?>

The above example will output:

IP address '127.0.0.1' is considered valid.

Example #3 Passing options to filter_var()

<?php
$int_a = '1';
$int_b = '-1';
$int_c = '4';
$options = array(
    'options' => array(
        'min_range' => 0,
        'max_range' => 3,
    )
);
if (filter_var($int_a, FILTER_VALIDATE_INT, $options) !== FALSE) {
    echo "Integer A '$int_a' is considered valid (between 0 and 3).\n";
}
if (filter_var($int_b, FILTER_VALIDATE_INT, $options) !== FALSE) {
    echo "Integer B '$int_b' is considered valid (between 0 and 3).\n";
}
if (filter_var($int_c, FILTER_VALIDATE_INT, $options) !== FALSE) {
    echo "Integer C '$int_c' is considered valid (between 0 and 3).\n";
}

$options['options']['default'] = 1;
if (($int_c = filter_var($int_c, FILTER_VALIDATE_INT, $options)) !== FALSE) {
    echo "Integer C '$int_c' is considered valid (between 0 and 3).";
}
?>

The above example will output:

Integer A '1' is considered valid (between 0 and 3).
Integer C '1' is considered valid (between 0 and 3).


Sanitization

Example #1 Sanitizing and validating email addresses

<?php
$a = 'joe@example.org';
$b = 'bogus - at - example dot org';
$c = '(bogus@example.org)';

$sanitized_a = filter_var($a, FILTER_SANITIZE_EMAIL);
if (filter_var($sanitized_a, FILTER_VALIDATE_EMAIL)) {
    echo "This (a) sanitized email address is considered valid.\n";
}

$sanitized_b = filter_var($b, FILTER_SANITIZE_EMAIL);
if (filter_var($sanitized_b, FILTER_VALIDATE_EMAIL)) {
    echo "This sanitized email address is considered valid.";
} else {
    echo "This (b) sanitized email address is considered invalid.\n";
}

$sanitized_c = filter_var($c, FILTER_SANITIZE_EMAIL);
if (filter_var($sanitized_c, FILTER_VALIDATE_EMAIL)) {
    echo "This (c) sanitized email address is considered valid.\n";
    echo "Before: $c\n";
    echo "After:  $sanitized_c\n";
}
?>

The above example will output:

This (a) sanitized email address is considered valid.
This (b) sanitized email address is considered invalid.
This (c) sanitized email address is considered valid.
Before: (bogus@example.org)
After: bogus@example.org

Example #2 Configuring a default filter

filter.default = full_special_chars
filter.default_flags = 0


Filter Functions

Table of Contents

  • filter_has_var — Checks if variable of specified type exists
  • filter_id — Returns the filter ID belonging to a named filter
  • filter_input_array — Gets external variables and optionally filters them
  • filter_input — Gets a specific external variable by name and optionally filters it
  • filter_list — Returns a list of all supported filters
  • filter_var_array — Gets multiple variables and optionally filters them
  • filter_var — Filters a variable with a specified filter


Checks if variable of specified type exists

  • « Filter Functions
  • filter_id »
  • PHP Manual
  • Filter Functions
  • Checks if variable of specified type exists

filter_has_var

(PHP 5 >= 5.2.0, PHP 7)

filter_has_var — Checks if variable of specified type exists

Description

filter_has_var ( int $type , string $variable_name ) : bool

Parameters

type

One of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV.

variable_name

Name of a variable to check.

Return Values

Returns TRUE on success or FALSE on failure.


Returns the filter ID belonging to a named filter

  • « filter_has_var
  • filter_input_array »
  • PHP Manual
  • Filter Functions
  • Returns the filter ID belonging to a named filter

filter_id

(PHP 5 >= 5.2.0, PHP 7)

filter_id — Returns the filter ID belonging to a named filter

Description

filter_id ( string $filtername ) : int

Parameters

filtername

Name of a filter to get.

Return Values

ID of a filter on success or FALSE if filter doesn't exist.

See Also

  • filter_list() - Returns a list of all supported filters


Gets external variables and optionally filters them

  • « filter_id
  • filter_input »
  • PHP Manual
  • Filter Functions
  • Gets external variables and optionally filters them

filter_input_array

(PHP 5 >= 5.2.0, PHP 7)

filter_input_array — Gets external variables and optionally filters them

Description

filter_input_array ( int $type [, mixed $definition [, bool $add_empty = TRUE ]] ) : mixed

This function is useful for retrieving many values without repetitively calling filter_input().

Parameters

type

One of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV.

definition

An array defining the arguments. A valid key is a string containing a variable name and a valid value is either a filter type, or an array optionally specifying the filter, flags and options. If the value is an array, valid keys are filter which specifies the filter type, flags which specifies any flags that apply to the filter, and options which specifies any options that apply to the filter. See the example below for a better understanding.

This parameter can be also an integer holding a filter constant. Then all values in the input array are filtered by this filter.

add_empty

Add missing keys as NULL to the return value.

Return Values

An array containing the values of the requested variables on success. If the input array designated by type is not populated, the function returns NULL if the FILTER_NULL_ON_FAILURE flag is not given, or FALSE otherwise. For other failures, FALSE is returned.

An array value will be FALSE if the filter fails, or NULL if the variable is not set. Or if the flag FILTER_NULL_ON_FAILURE is used, it returns FALSE if the variable is not set and NULL if the filter fails. If the add_empty parameter is FALSE, no array element will be added for unset variables.

Examples

Example #1 A filter_input_array() example

<?php
error_reporting(E_ALL | E_STRICT);
/* data actually came from POST
$_POST = array(
    'product_id' => 'libgd<script>',
    'component'  => array('10'),
    'version'    => '2.0.33',
    'testarray'  => array('2', '23', '10', '12'),
    'testscalar' => '2',
);
*/

$args = array(
    'product_id'   => FILTER_SANITIZE_ENCODED,
    'component'    => array('filter'    => FILTER_VALIDATE_INT,
                            'flags'     => FILTER_REQUIRE_ARRAY,
                            'options'   => array('min_range' => 1, 'max_range' => 10)
                           ),
    'version'      => FILTER_SANITIZE_ENCODED,
    'doesnotexist' => FILTER_VALIDATE_INT,
    'testscalar'   => array(
                            'filter' => FILTER_VALIDATE_INT,
                            'flags'  => FILTER_REQUIRE_SCALAR,
                           ),
    'testarray'    => array(
                            'filter' => FILTER_VALIDATE_INT,
                            'flags'  => FILTER_REQUIRE_ARRAY,
                           )

);

$myinputs = filter_input_array(INPUT_POST, $args);

var_dump($myinputs);
echo "\n";
?>

The above example will output:

array(6) {
  ["product_id"]=>
  string(17) "libgd%3Cscript%3E"
  ["component"]=>
  array(1) {
    [0]=>
    int(10)
  }
  ["version"]=>
  string(6) "2.0.33"
  ["doesnotexist"]=>
  NULL
  ["testscalar"]=>
  int(2)
  ["testarray"]=>
  array(4) {
    [0]=>
    int(2)
    [1]=>
    int(23)
    [2]=>
    int(10)
    [3]=>
    int(12)
  }
}

Changelog

Version | Description
5.4.0 | Added add_empty parameter.

Notes

Note:

There is no REQUEST_TIME key in INPUT_SERVER array because it is inserted into the $_SERVER later.

See Also

  • filter_input() - Gets a specific external variable by name and optionally filters it
  • filter_var_array() - Gets multiple variables and optionally filters them
  • Types of filters


Gets a specific external variable by name and optionally filters it

  • « filter_input_array
  • filter_list »
  • PHP Manual
  • Filter Functions
  • Gets a specific external variable by name and optionally filters it

filter_input

(PHP 5 >= 5.2.0, PHP 7)

filter_input — Gets a specific external variable by name and optionally filters it

Description

filter_input ( int $type , string $variable_name [, int $filter = FILTER_DEFAULT [, mixed $options ]] ) : mixed

Parameters

type

One of INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV.

variable_name

Name of a variable to get.

filter

The ID of the filter to apply. The Types of filters manual page lists the available filters.

If omitted, FILTER_DEFAULT will be used, which is equivalent to FILTER_UNSAFE_RAW. This will result in no filtering taking place by default.

options

Associative array of options or bitwise disjunction of flags. If filter accepts options, flags can be provided in "flags" field of array.

Return Values

Value of the requested variable on success, FALSE if the filter fails, or NULL if the variable_name variable is not set. If the flag FILTER_NULL_ON_FAILURE is used, it returns FALSE if the variable is not set and NULL if the filter fails.

Examples

Example #1 A filter_input() example

<?php
$search_html = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_SPECIAL_CHARS);
$search_url = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_ENCODED);
echo "You have searched for $search_html.\n";
echo "<a href='?search=$search_url'>Search again.</a>";
?>

The above example will output something similar to:

You have searched for Me &#38; son.
<a href='?search=Me%20%26%20son'>Search again.</a>

See Also

  • filter_var() - Filters a variable with a specified filter
  • filter_input_array() - Gets external variables and optionally filters them
  • filter_var_array() - Gets multiple variables and optionally filters them
  • Types of filters


Returns a list of all supported filters

  • « filter_input
  • filter_var_array »
  • PHP Manual
  • Filter Functions
  • Returns a list of all supported filters

filter_list

(PHP 5 >= 5.2.0, PHP 7)

filter_list — Returns a list of all supported filters

Description

filter_list ( void ) : array

Return Values

Returns an array of names of all supported filters, empty array if there are no such filters. Indexes of this array are not filter IDs, they can be obtained with filter_id() from a name instead.

Examples

Example #1 A filter_list() example

<?php
print_r(filter_list());
?>

The above example will output something similar to:

Array
(
    [0] => int
    [1] => boolean
    [2] => float
    [3] => validate_regexp
    [4] => validate_url
    [5] => validate_email
    [6] => validate_ip
    [7] => string
    [8] => stripped
    [9] => encoded
    [10] => special_chars
    [11] => unsafe_raw
    [12] => email
    [13] => url
    [14] => number_int
    [15] => number_float
    [16] => magic_quotes
    [17] => callback
)


Gets multiple variables and optionally filters them

  • « filter_list
  • filter_var »
  • PHP Manual
  • Filter Functions
  • Gets multiple variables and optionally filters them

filter_var_array

(PHP 5 >= 5.2.0, PHP 7)

filter_var_array — Gets multiple variables and optionally filters them

Description

filter_var_array ( array $data [, mixed $definition [, bool $add_empty = TRUE ]] ) : mixed

This function is useful for retrieving many values without repetitively calling filter_var().

Parameters

data

An array with string keys containing the data to filter.

definition

An array defining the arguments. A valid key is a string containing a variable name and a valid value is either a filter type, or an array optionally specifying the filter, flags and options. If the value is an array, valid keys are filter which specifies the filter type, flags which specifies any flags that apply to the filter, and options which specifies any options that apply to the filter. See the example below for a better understanding.

This parameter can be also an integer holding a filter constant. Then all values in the input array are filtered by this filter.

add_empty

Add missing keys as NULL to the return value.

Return Values

An array containing the values of the requested variables on success, or FALSE on failure. An array value will be FALSE if the filter fails, or NULL if the variable is not set.

Examples

Example #1 A filter_var_array() example

<?php
error_reporting(E_ALL | E_STRICT);
$data = array(
    'product_id'    => 'libgd<script>',
    'component'     => '10',
    'versions'      => '2.0.33',
    'testscalar'    => array('2', '23', '10', '12'),
    'testarray'     => '2',
);

$args = array(
    'product_id'   => FILTER_SANITIZE_ENCODED,
    'component'    => array('filter'    => FILTER_VALIDATE_INT,
                            'flags'     => FILTER_FORCE_ARRAY,
                            'options'   => array('min_range' => 1, 'max_range' => 10)
                           ),
    'versions'     => FILTER_SANITIZE_ENCODED,
    'doesnotexist' => FILTER_VALIDATE_INT,
    'testscalar'   => array(
                            'filter' => FILTER_VALIDATE_INT,
                            'flags'  => FILTER_REQUIRE_SCALAR,
                           ),
    'testarray'    => array(
                            'filter' => FILTER_VALIDATE_INT,
                            'flags'  => FILTER_FORCE_ARRAY,
                           )

);

$myinputs = filter_var_array($data, $args);

var_dump($myinputs);
echo "\n";
?>

The above example will output:

array(6) {
  ["product_id"]=>
  string(17) "libgd%3Cscript%3E"
  ["component"]=>
  array(1) {
    [0]=>
    int(10)
  }
  ["versions"]=>
  string(6) "2.0.33"
  ["doesnotexist"]=>
  NULL
  ["testscalar"]=>
  bool(false)
  ["testarray"]=>
  array(1) {
    [0]=>
    int(2)
  }
}

Changelog

Version | Description
5.4.0 | Added add_empty parameter.

See Also

  • filter_input_array() - Gets external variables and optionally filters them
  • filter_var() - Filters a variable with a specified filter
  • filter_input() - Gets a specific external variable by name and optionally filters it
  • Types of filters


Filters a variable with a specified filter

  • « filter_var_array
  • Function Handling »
  • PHP Manual
  • Filter Functions
  • Filters a variable with a specified filter

filter_var

(PHP 5 >= 5.2.0, PHP 7)

filter_var — Filters a variable with a specified filter

Description

filter_var ( mixed $variable [, int $filter = FILTER_DEFAULT [, mixed $options ]] ) : mixed

Parameters

variable

Value to filter. Note that scalar values are converted to string internally before they are filtered.

filter

The ID of the filter to apply. The Types of filters manual page lists the available filters.

If omitted, FILTER_DEFAULT will be used, which is equivalent to FILTER_UNSAFE_RAW. This will result in no filtering taking place by default.

options

Associative array of options or bitwise disjunction of flags. If filter accepts options, flags can be provided in "flags" field of array. For the "callback" filter, callable type should be passed. The callback must accept one argument, the value to be filtered, and return the value after filtering/sanitizing it.

<?php
// for filters that accept options, use this format
$options = array(
    'options' => array(
        'default' => 3, // value to return if the filter fails
        // other options here
        'min_range' => 0
    ),
    'flags' => FILTER_FLAG_ALLOW_OCTAL,
);
$var = filter_var('0755', FILTER_VALIDATE_INT, $options);

// for filters that only accept flags, you can pass them directly
$var = filter_var('oops', FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);

// for filters that only accept flags, you can also pass as an array
$var = filter_var('oops', FILTER_VALIDATE_BOOLEAN,
                  array('flags' => FILTER_NULL_ON_FAILURE));

// callback validate filter
function foo($value)
{
    // Expected format: Surname, GivenNames
    if (strpos($value, ", ") === false) return false;
    list($surname, $givennames) = explode(", ", $value, 2);
    $empty = (empty($surname) || empty($givennames));
    $notstrings = (!is_string($surname) || !is_string($givennames));
    if ($empty || $notstrings) {
        return false;
    } else {
        return $value;
    }
}
$var = filter_var('Doe, Jane Sue', FILTER_CALLBACK, array('options' => 'foo'));
?>

Return Values

Returns the filtered data, or FALSE if the filter fails.

Examples

Example #1 A filter_var() example

<?php
var_dump(filter_var('bob@example.com', FILTER_VALIDATE_EMAIL));
var_dump(filter_var('http://example.com', FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED));
?>

The above example will output:

string(15) "bob@example.com"
bool(false)

See Also

  • filter_var_array() - Gets multiple variables and optionally filters them
  • filter_input() - Gets a specific external variable by name and optionally filters it
  • filter_input_array() - Gets external variables and optionally filters them
  • Types of filters
  • information about the callback type


Function Handling

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Function handling Functions
    • call_user_func_array — Call a callback with an array of parameters
    • call_user_func — Call the callback given by the first parameter
    • create_function — Create an anonymous (lambda-style) function
    • forward_static_call_array — Call a static method and pass the arguments as array
    • forward_static_call — Call a static method
    • func_get_arg — Return an item from the argument list
    • func_get_args — Returns an array comprising a function's argument list
    • func_num_args — Returns the number of arguments passed to the function
    • function_exists — Return TRUE if the given function has been defined
    • get_defined_functions — Returns an array of all defined functions
    • register_shutdown_function — Register a function for execution on shutdown
    • register_tick_function — Register a function for execution on each tick
    • unregister_tick_function — De-register a function for execution on each tick


  • « Function Handling
  • Installing/Configuring »
  • PHP Manual
  • Function Handling
  • Introduction

Introduction

These functions all handle various operations involved in working with functions.


  • « Resource Types
  • Function handling Functions »
  • PHP Manual
  • Function Handling
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


Function handling Functions

Table of Contents

  • call_user_func_array — Call a callback with an array of parameters
  • call_user_func — Call the callback given by the first parameter
  • create_function — Create an anonymous (lambda-style) function
  • forward_static_call_array — Call a static method and pass the arguments as array
  • forward_static_call — Call a static method
  • func_get_arg — Return an item from the argument list
  • func_get_args — Returns an array comprising a function's argument list
  • func_num_args — Returns the number of arguments passed to the function
  • function_exists — Return TRUE if the given function has been defined
  • get_defined_functions — Returns an array of all defined functions
  • register_shutdown_function — Register a function for execution on shutdown
  • register_tick_function — Register a function for execution on each tick
  • unregister_tick_function — De-register a function for execution on each tick


Call a callback with an array of parameters

  • « Function handling Functions
  • call_user_func »
  • PHP Manual
  • Function handling Functions
  • Call a callback with an array of parameters

call_user_func_array

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

call_user_func_array — Call a callback with an array of parameters

Description

call_user_func_array ( callable $callback , array $param_arr ) : mixed

Calls the callback given by the first parameter with the parameters in param_arr.

Parameters

callback

The callable to be called.

param_arr

The parameters to be passed to the callback, as an indexed array.

Return Values

Returns the return value of the callback, or FALSE on error.

Changelog

Version | Description
5.3.0 | The interpretation of object oriented keywords like parent and self has changed. Previously, calling them using the double colon syntax would emit an E_STRICT warning because they were interpreted as static.

Examples

Example #1 call_user_func_array() example

<?php
function foobar($arg, $arg2) {
    echo __FUNCTION__, " got $arg and $arg2\n";
}
class foo {
    function bar($arg, $arg2) {
        echo __METHOD__, " got $arg and $arg2\n";
    }
}

// Call the foobar() function with 2 arguments
call_user_func_array("foobar", array("one", "two"));

// Call the $foo->bar() method with 2 arguments
$foo = new foo;
call_user_func_array(array($foo, "bar"), array("three", "four"));
?>

The above example will output something similar to:

foobar got one and two
foo::bar got three and four

Example #2 call_user_func_array() using namespace name

<?php

namespace Foobar;

class Foo {
    static public function test($name) {
        print "Hello {$name}!\n";
    }
}

// As of PHP 5.3.0
call_user_func_array(__NAMESPACE__ .'\Foo::test', array('Hannes'));

// As of PHP 5.3.0
call_user_func_array(array(__NAMESPACE__ .'\Foo', 'test'), array('Philip'));

?>

The above example will output something similar to:

Hello Hannes!
Hello Philip!

Example #3 Using lambda function

<?php

$func = function($arg1, $arg2) {
    return $arg1 * $arg2;
};

var_dump(call_user_func_array($func, array(2, 4))); /* As of PHP 5.3.0 */

?>

The above example will output:

int(8)

Example #4 Passing values by reference

<?php

function mega(&$a){
    $a = 55;
    echo "function mega \$a=$a\n";
}
$bar = 77;
call_user_func_array('mega',array(&$bar));
echo "global \$bar=$bar\n";

?>

The above example will output:

function mega $a=55
global $bar=55

Notes

Note:

Before PHP 5.4, referenced variables in param_arr are passed to the function by reference, regardless of whether the function expects the respective parameter to be passed by reference. This form of call-time pass by reference does not emit a deprecation notice, but it is nonetheless deprecated, and has been removed in PHP 5.4. Furthermore, this does not apply to internal functions, for which the function signature is honored. Passing by value when the function expects a parameter by reference results in a warning and having call_user_func() return FALSE (there is, however, an exception for passed values with reference count = 1, such as in literals, as these can be turned into references without ill effects — but also without writes to that value having any effect —; do not rely in this behavior, though, as the reference count is an implementation detail and the soundness of this behavior is questionable).

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.

See Also

  • call_user_func() - Call the callback given by the first parameter
  • information about the callback type
  • ReflectionFunction::invokeArgs() - Invokes function args
  • ReflectionMethod::invokeArgs() - Invoke args


Call the callback given by the first parameter

  • « call_user_func_array
  • create_function »
  • PHP Manual
  • Function handling Functions
  • Call the callback given by the first parameter

call_user_func

(PHP 4, PHP 5, PHP 7)

call_user_func — Call the callback given by the first parameter

Description

call_user_func ( callable $callback [, mixed $... ] ) : mixed

Calls the callback given by the first parameter and passes the remaining parameters as arguments.

Parameters

callback

The callable to be called.

...

Zero or more parameters to be passed to the callback.

Note:

Note that the parameters for call_user_func() are not passed by reference.

Example #1 call_user_func() example and references

<?php
error_reporting(E_ALL);
function increment(&$var)
{
    $var++;
}

$a = 0;
call_user_func('increment', $a);
echo $a."\n";

// You can use this instead
call_user_func_array('increment', array(&$a));
echo $a."\n";
?>

The above example will output:

Warning: Parameter 1 to increment() expected to be a reference, value given in …
0
1

Return Values

Returns the return value of the callback.

Changelog

Version | Description
5.3.0 | The interpretation of object oriented keywords like parent and self has changed. Previously, calling them using the double colon syntax would emit an E_STRICT warning because they were interpreted as static.
5.3.0 | If the called function expects a parameter to be passed by reference, an E_WARNING is now issued.

Examples

Example #2 call_user_func() example

<?php
function barber($type)
{
    echo "You wanted a $type haircut, no problem\n";
}
call_user_func('barber', "mushroom");
call_user_func('barber', "shave");
?>

The above example will output:

You wanted a mushroom haircut, no problem
You wanted a shave haircut, no problem

Example #3 call_user_func() using namespace name

<?php

namespace Foobar;

class Foo {
    static public function test() {
        print "Hello world!\n";
    }
}

call_user_func(__NAMESPACE__ .'\Foo::test'); // As of PHP 5.3.0
call_user_func(array(__NAMESPACE__ .'\Foo', 'test')); // As of PHP 5.3.0

?>

The above example will output:

Hello world!
Hello world!

Example #4 Using a class method with call_user_func()

<?php

class myclass {
    static function say_hello()
    {
        echo "Hello!\n";
    }
}

$classname = "myclass";

call_user_func(array($classname, 'say_hello'));
call_user_func($classname .'::say_hello'); // As of 5.2.3

$myobject = new myclass();

call_user_func(array($myobject, 'say_hello'));

?>

The above example will output:

Hello!
Hello!
Hello!

Example #5 Using lambda function with call_user_func()

<?php
call_user_func(function($arg) { print "[$arg]\n"; }, 'test'); /* As of PHP 5.3.0 */
?>

The above example will output:

[test]

Notes

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.

See Also

  • call_user_func_array() - Call a callback with an array of parameters
  • is_callable() - Verify that the contents of a variable can be called as a function
  • information about the callback type
  • ReflectionFunction::invoke() - Invokes function
  • ReflectionMethod::invoke() - Invoke


Create an anonymous (lambda-style) function

  • « call_user_func
  • forward_static_call_array »
  • PHP Manual
  • Function handling Functions
  • Create an anonymous (lambda-style) function

create_function

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

create_function — Create an anonymous (lambda-style) function

Warning

This function has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.

Description

create_function ( string $args , string $code ) : string

Creates an anonymous function from the parameters passed, and returns a unique name for it.

Caution

This function internally performs an eval() and as such has the same security issues as eval(). Additionally it has bad performance and memory usage characteristics.

If you are using PHP 5.3.0 or newer a native anonymous function should be used instead.

Parameters

Usually these parameters will be passed as single quote delimited strings. The reason for using single quoted strings, is to protect the variable names from parsing, otherwise, if you use double quotes there will be a need to escape the variable names, e.g. \$avar.

args

The function arguments.

code

The function code.

Return Values

Returns a unique function name as a string, or FALSE on error.

Examples

Example #1 Creating an anonymous function with create_function()

You can use this function, to (for example) create a function from information gathered at run time:

<?php
$newfunc = create_function('$a,$b', 'return "ln($a) + ln($b) = " . log($a * $b);');
echo "New anonymous function: $newfunc\n";
echo $newfunc(2, M_E) . "\n";
// outputs
// New anonymous function: lambda_1
// ln(2) + ln(2.718281828459) = 1.6931471805599
?>

Or, perhaps to have general handler function that can apply a set of operations to a list of parameters:

Example #2 Making a general processing function with create_function()

<?php
function process($var1, $var2, $farr)
{
    foreach ($farr as $f) {
        echo $f($var1, $var2) . "\n";
    }
}

// create a bunch of math functions
$f1 = 'if ($a >=0) {return "b*a^2 = ".$b*sqrt($a);} else {return false;}';
$f2 = "return \"min(b^2+a, a^2,b) = \".min(\$a*\$a+\$b,\$b*\$b+\$a);";
$f3 = 'if ($a > 0 && $b != 0) {return "ln(a)/b = ".log($a)/$b; } else { return false; }';
$farr = array(
    create_function('$x,$y', 'return "some trig: ".(sin($x) + $x*cos($y));'),
    create_function('$x,$y', 'return "a hypotenuse: ".sqrt($x*$x + $y*$y);'),
    create_function('$a,$b', $f1),
    create_function('$a,$b', $f2),
    create_function('$a,$b', $f3)
    );

echo "\nUsing the first array of anonymous functions\n";
echo "parameters: 2.3445, M_PI\n";
process(2.3445, M_PI, $farr);

// now make a bunch of string processing functions
$garr = array(
    create_function('$b,$a', 'if (strncmp($a, $b, 3) == 0) return "** \"$a\" '.
    'and \"$b\"\n** Look the same to me! (looking at the first 3 chars)";'),
    create_function('$a,$b', '; return "CRCs: " . crc32($a) . ", ".crc32($b);'),
    create_function('$a,$b', '; return "similar(a,b) = " . similar_text($a, $b, &$p) . "($p%)";')
    );
echo "\nUsing the second array of anonymous functions\n";
process("Twas brilling and the slithy toves", "Twas the night", $garr);
?>

The above example will output:

Using the first array of anonymous functions
parameters: 2.3445, M_PI
some trig: -1.6291725057799
a hypotenuse: 3.9199852871011
b*a^2 = 4.8103313314525
min(b^2+a, a^2,b) = 8.6382729035898
ln(a)/b = 0.27122299212594

Using the second array of anonymous functions
** "Twas the night" and "Twas brilling and the slithy toves"
** Look the same to me! (looking at the first 3 chars)
CRCs: -725381282, 342550513
similar(a,b) = 11(45.833333333333%)

But perhaps the most common use for of lambda-style (anonymous) functions is to create callback functions, for example when using array_walk() or usort()

Example #3 Using anonymous functions as callback functions

<?php
$av = array("the ", "a ", "that ", "this ");
array_walk($av, create_function('&$v,$k', '$v = $v . "mango";'));
print_r($av);
?>

The above example will output:

Array
(
  [0] => the mango
  [1] => a mango
  [2] => that mango
  [3] => this mango
)

an array of strings ordered from shorter to longer

<?php

$sv = array("small", "larger", "a big string", "it is a string thing");
print_r($sv);

?>

The above example will output:

Array
(
  [0] => small
  [1] => larger
  [2] => a big string
  [3] => it is a string thing
)

sort it from longer to shorter

<?php

usort($sv, create_function('$a,$b','return strlen($b) - strlen($a);'));
print_r($sv);

?>

The above example will output:

Array
(
  [0] => it is a string thing
  [1] => a big string
  [2] => larger
  [3] => small
)

See Also

  • Anonymous functions


Call a static method and pass the arguments as array

  • « create_function
  • forward_static_call »
  • PHP Manual
  • Function handling Functions
  • Call a static method and pass the arguments as array

forward_static_call_array

(PHP 5 >= 5.3.0, PHP 7)

forward_static_call_array — Call a static method and pass the arguments as array

Description

forward_static_call_array ( callable $function , array $parameters ) : mixed

Calls a user defined function or method given by the function parameter. This function must be called within a method context, it can't be used outside a class. It uses the late static binding. All arguments of the forwarded method are passed as values, and as an array, similarly to call_user_func_array().

Parameters

function

The function or method to be called. This parameter may be an array, with the name of the class, and the method, or a string, with a function name.

parameter

One parameter, gathering all the method parameter in one array.

Note:

Note that the parameters for forward_static_call_array() are not passed by reference.

Return Values

Returns the function result, or FALSE on error.

Examples

Example #1 forward_static_call_array() example

<?php

class A
{
    const NAME = 'A';
    public static function test() {
        $args = func_get_args();
        echo static::NAME, " ".join(',', $args)." \n";
    }
}

class B extends A
{
    const NAME = 'B';

    public static function test() {
        echo self::NAME, "\n";
        forward_static_call_array(array('A', 'test'), array('more', 'args'));
        forward_static_call_array( 'test', array('other', 'args'));
    }
}

B::test('foo');

function test() {
        $args = func_get_args();
        echo "C ".join(',', $args)." \n";
    }

?>

The above example will output:

B
B more,args
C other,args

See Also

  • forward_static_call() - Call a static method
  • call_user_func() - Call the callback given by the first parameter
  • call_user_func_array() - Call a callback with an array of parameters
  • is_callable() - Verify that the contents of a variable can be called as a function
  • information about the callback type


Call a static method

  • « forward_static_call_array
  • func_get_arg »
  • PHP Manual
  • Function handling Functions
  • Call a static method

forward_static_call

(PHP 5 >= 5.3.0, PHP 7)

forward_static_call — Call a static method

Description

forward_static_call ( callable $function [, mixed $... ] ) : mixed

Calls a user defined function or method given by the function parameter, with the following arguments. This function must be called within a method context, it can't be used outside a class. It uses the late static binding.

Parameters

function

The function or method to be called. This parameter may be an array, with the name of the class, and the method, or a string, with a function name.

...

Zero or more parameters to be passed to the function.

Return Values

Returns the function result, or FALSE on error.

Examples

Example #1 forward_static_call() example

<?php

class A
{
    const NAME = 'A';
    public static function test() {
        $args = func_get_args();
        echo static::NAME, " ".join(',', $args)." \n";
    }
}

class B extends A
{
    const NAME = 'B';

    public static function test() {
        echo self::NAME, "\n";
        forward_static_call(array('A', 'test'), 'more', 'args');
        forward_static_call( 'test', 'other', 'args');
    }
}

B::test('foo');

function test() {
        $args = func_get_args();
        echo "C ".join(',', $args)." \n";
    }

?>

The above example will output:

B
B more,args
C other,args

See Also

  • forward_static_call_array() - Call a static method and pass the arguments as array
  • call_user_func_array() - Call a callback with an array of parameters
  • call_user_func() - Call the callback given by the first parameter
  • is_callable() - Verify that the contents of a variable can be called as a function
  • information about the callback type


Return an item from the argument list

  • « forward_static_call
  • func_get_args »
  • PHP Manual
  • Function handling Functions
  • Return an item from the argument list

func_get_arg

(PHP 4, PHP 5, PHP 7)

func_get_arg — Return an item from the argument list

Description

func_get_arg ( int $arg_num ) : mixed

Gets the specified argument from a user-defined function's argument list.

This function may be used in conjunction with func_get_args() and func_num_args() to allow user-defined functions to accept variable-length argument lists.

Parameters

arg_num

The argument offset. Function arguments are counted starting from zero.

Return Values

Returns the specified argument, or FALSE on error.

Changelog

Version | Description
5.3.0 | This function can now be used in parameter lists.
5.3.0 | If this function is called from the outermost scope of a file which has been included by calling include or require from within a function in the calling file, it now generates a warning and returns FALSE.

Errors/Exceptions

Generates a warning if called from outside of a user-defined function, or if arg_num is greater than the number of arguments actually passed.

Examples

Example #1 func_get_arg() example

<?php
function foo()
{
     $numargs = func_num_args();
     echo "Number of arguments: $numargs\n";
     if ($numargs >= 2) {
         echo "Second argument is: " . func_get_arg(1) . "\n";
     }
}

foo(1, 2, 3);
?>

The above example will output:

Number of arguments: 3
Second argument is: 2

Example #2 func_get_arg() example before and after PHP 5.3

test.php
<?php
function foo() {
    include './fga.inc';
}

foo('First arg', 'Second arg');
?>

fga.inc
<?php

$arg = func_get_arg(1);
var_export($arg);

?>

Output previous to PHP 5.3:

'Second arg'

Output in PHP 5.3 and later:

Warning: func_get_arg():  Called from the global scope - no function
context in /home/torben/Desktop/code/ml/fga.inc on line 3
false

Example #3 func_get_arg() example of byref and byval arguments

<?php
function byVal($arg) {
    echo 'As passed     : ', var_export(func_get_arg(0)), PHP_EOL;
    $arg = 'baz';
    echo 'After change  : ', var_export(func_get_arg(0)), PHP_EOL;
}

function byRef(&$arg) {
    echo 'As passed     : ', var_export(func_get_arg(0)), PHP_EOL;
    $arg = 'baz';
    echo 'After change  : ', var_export(func_get_arg(0)), PHP_EOL;
}

$arg = 'bar';
byVal($arg);
byRef($arg);
?>

Output of the above example in PHP 7:

As passed : 'bar'
After change : 'baz'
As passed : 'bar'
After change : 'baz'

Output of the above example in PHP 5:

As passed : 'bar'
After change : 'bar'
As passed : 'bar'
After change : 'baz'

Notes

Note:

Because this function depends on the current scope to determine parameter details, it cannot be used as a function parameter in versions prior to 5.3.0. If this value must be passed, the results should be assigned to a variable, and that variable should be passed.

Note:

If the arguments are passed by reference, any changes to the arguments will be reflected in the values returned by this function. As of PHP 7 the current values will also be returned if the arguments are passed by value.

Note: This function returns a copy of the passed arguments only, and does not account for default (non-passed) arguments.

See Also

  • ... syntax in PHP 5.6+
  • func_get_args()
  • func_num_args()


Returns an array comprising a function's argument list

  • « func_get_arg
  • func_num_args »
  • PHP Manual
  • Function handling Functions
  • Returns an array comprising a function's argument list

func_get_args

(PHP 4, PHP 5, PHP 7)

func_get_args — Returns an array comprising a function's argument list

Description

func_get_args ( void ) : array

Gets an array of the function's argument list.

This function may be used in conjunction with func_get_arg() and func_num_args() to allow user-defined functions to accept variable-length argument lists.

Return Values

Returns an array in which each element is a copy of the corresponding member of the current user-defined function's argument list.

Changelog

Version | Description
5.3.0 | This function can now be used in parameter lists.
5.3.0 | If this function is called from the outermost scope of a file which has been included by calling include or require from within a function in the calling file, it now generates a warning and returns FALSE.

Errors/Exceptions

Generates a warning if called from outside of a user-defined function.

Examples

Example #1 func_get_args() example

<?php
function foo()
{
    $numargs = func_num_args();
    echo "Number of arguments: $numargs \n";
    if ($numargs >= 2) {
        echo "Second argument is: " . func_get_arg(1) . "\n";
    }
    $arg_list = func_get_args();
    for ($i = 0; $i < $numargs; $i++) {
        echo "Argument $i is: " . $arg_list[$i] . "\n";
    }
}

foo(1, 2, 3);
?>

The above example will output:

Number of arguments: 3
Second argument is: 2
Argument 0 is: 1
Argument 1 is: 2
Argument 2 is: 3

Example #2 func_get_args() example before and after PHP 5.3

test.php
<?php
function foo() {
    include './fga.inc';
}

foo('First arg', 'Second arg');
?>

fga.inc
<?php

$args = func_get_args();
var_export($args);

?>

Output previous to PHP 5.3:

array (
  0 => 'First arg',
  1 => 'Second arg',
)

Output in PHP 5.3 and later:

Warning: func_get_args():  Called from the global scope - no function
context in /home/torben/Desktop/code/ml/fga.inc on line 3
false

Example #3 func_get_args() example of byref and byval arguments

<?php
function byVal($arg) {
    echo 'As passed     : ', var_export(func_get_args()), PHP_EOL;
    $arg = 'baz';
    echo 'After change  : ', var_export(func_get_args()), PHP_EOL;
}

function byRef(&$arg) {
    echo 'As passed     : ', var_export(func_get_args()), PHP_EOL;
    $arg = 'baz';
    echo 'After change  : ', var_export(func_get_args()), PHP_EOL;
}

$arg = 'bar';
byVal($arg);
byRef($arg);
?>

Output of the above example in PHP 7:

As passed : array (
0 => 'bar',
)
After change : array (
0 => 'baz',
)
As passed : array (
0 => 'bar',
)
After change : array (
0 => 'baz',
)

Output of the above example in PHP 5:

As passed : array (
0 => 'bar',
)
After change : array (
0 => 'bar',
)
As passed : array (
0 => 'bar',
)
After change : array (
0 => 'baz',
)

Notes

Note:

Because this function depends on the current scope to determine parameter details, it cannot be used as a function parameter in versions prior to 5.3.0. If this value must be passed, the results should be assigned to a variable, and that variable should be passed.

Note:

If the arguments are passed by reference, any changes to the arguments will be reflected in the values returned by this function. As of PHP 7 the current values will also be returned if the arguments are passed by value.

Note: This function returns a copy of the passed arguments only, and does not account for default (non-passed) arguments.

See Also

  • ... syntax in PHP 5.6+
  • func_get_arg()
  • func_num_args()
  • ReflectionFunctionAbstract::getParameters()


Returns the number of arguments passed to the function

  • « func_get_args
  • function_exists »
  • PHP Manual
  • Function handling Functions
  • Returns the number of arguments passed to the function

func_num_args

(PHP 4, PHP 5, PHP 7)

func_num_args — Returns the number of arguments passed to the function

Description

func_num_args ( void ) : int

Gets the number of arguments passed to the function.

This function may be used in conjunction with func_get_arg() and func_get_args() to allow user-defined functions to accept variable-length argument lists.

Return Values

Returns the number of arguments passed into the current user-defined function.

Changelog

Version | Description
5.3.0 | This function can now be used in parameter lists.
5.3.0 | If this function is called from the outermost scope of a file which has been included by calling include or require from within a function in the calling file, it now generates a warning and returns -1.

Errors/Exceptions

Generates a warning if called from outside of a user-defined function.

Examples

Example #1 func_num_args() example

<?php
function foo()
{
    $numargs = func_num_args();
    echo "Number of arguments: $numargs\n";
}

foo(1, 2, 3);
?>

The above example will output:

Number of arguments: 3

Example #2 func_num_args() example before and after PHP 5.3

test.php
<?php
function foo() {
    include './fna.php';
}

foo('First arg', 'Second arg');
?>

fna.php
<?php

$num_args = func_num_args();
var_export($num_args);

?>

Output previous to PHP 5.3:

2

Output in PHP 5.3 and later will be something similar to:

Warning: func_num_args():  Called from the global scope - no function
context in /home/torben/Desktop/code/ml/fna.php on line 3
-1

Notes

Note:

Because this function depends on the current scope to determine parameter details, it cannot be used as a function parameter in versions prior to 5.3.0. If this value must be passed, the results should be assigned to a variable, and that variable should be passed.

See Also

  • ... syntax in PHP 5.6+
  • func_get_arg()
  • func_get_args()
  • ReflectionFunctionAbstract::getNumberOfParameters()


Return TRUE if the given function has been defined

  • « func_num_args
  • get_defined_functions »
  • PHP Manual
  • Function handling Functions
  • Return TRUE if the given function has been defined

function_exists

(PHP 4, PHP 5, PHP 7)

function_exists — Return TRUE if the given function has been defined

Description

function_exists ( string $function_name ) : bool

Checks the list of defined functions, both built-in (internal) and user-defined, for function_name.

Parameters

function_name

The function name, as a string.

Return Values

Returns TRUE if function_name exists and is a function, FALSE otherwise.

Note:

This function will return FALSE for constructs, such as include_once and echo.

Examples

Example #1 function_exists() example

<?php
if (function_exists('imap_open')) {
    echo "IMAP functions are available.<br />\n";
} else {
    echo "IMAP functions are not available.<br />\n";
}
?>

Notes

Note:

A function name may exist even if the function itself is unusable due to configuration or compiling options (with the image functions being an example).

See Also

  • method_exists() - Checks if the class method exists
  • is_callable() - Verify that the contents of a variable can be called as a function
  • get_defined_functions() - Returns an array of all defined functions
  • class_exists() - Checks if the class has been defined
  • extension_loaded() - Find out whether an extension is loaded


Returns an array of all defined functions

  • « function_exists
  • register_shutdown_function »
  • PHP Manual
  • Function handling Functions
  • Returns an array of all defined functions

get_defined_functions

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

get_defined_functions — Returns an array of all defined functions

Description

get_defined_functions ([ bool $exclude_disabled = FALSE ] ) : array

Gets an array of all defined functions.

Parameters

exclude_disabled

Whether disabled functions should be excluded from the return value.

Return Values

Returns a multidimensional array containing a list of all defined functions, both built-in (internal) and user-defined. The internal functions will be accessible via $arr["internal"], and the user defined ones using $arr["user"] (see example below).

Changelog

Version | Description
7.0.15, 7.1.1 | The exclude_disabled parameter has been added.

Examples

Example #1 get_defined_functions() example

<?php
function myrow($id, $data)
{
    return "<tr><th>$id</th><td>$data</td></tr>\n";
}

$arr = get_defined_functions();

print_r($arr);
?>

The above example will output something similar to:

Array
(
    [internal] => Array
        (
            [0] => zend_version
            [1] => func_num_args
            [2] => func_get_arg
            [3] => func_get_args
            [4] => strlen
            [5] => strcmp
            [6] => strncmp
            ...
            [750] => bcscale
            [751] => bccomp
        )

    [user] => Array
        (
            [0] => myrow
        )

)

See Also

  • function_exists() - Return TRUE if the given function has been defined
  • get_defined_vars() - Returns an array of all defined variables
  • get_defined_constants() - Returns an associative array with the names of all the constants and their values
  • get_declared_classes() - Returns an array with the name of the defined classes


Register a function for execution on shutdown

  • « get_defined_functions
  • register_tick_function »
  • PHP Manual
  • Function handling Functions
  • Register a function for execution on shutdown

register_shutdown_function

(PHP 4, PHP 5, PHP 7)

register_shutdown_function — Register a function for execution on shutdown

Description

register_shutdown_function ( callable $callback [, mixed $... ] ) : void

Registers a callback to be executed after script execution finishes or exit() is called.

Multiple calls to register_shutdown_function() can be made, and each will be called in the same order as they were registered. If you call exit() within one registered shutdown function, processing will stop completely and no other registered shutdown functions will be called.

Parameters

callback

The shutdown callback to register.

The shutdown callbacks are executed as the part of the request, so it's possible to send output from them and access output buffers.

...

It is possible to pass parameters to the shutdown function by passing additional parameters.

Return Values

No value is returned.

Errors/Exceptions

If the passed callback is not callable a E_WARNING level error will be generated.

Examples

Example #1 register_shutdown_function() example

<?php
function shutdown()
{
    // This is our shutdown function, in
    // here we can do any last operations
    // before the script is complete.

    echo 'Script executed with success', PHP_EOL;
}

register_shutdown_function('shutdown');
?>

Notes

Note:

Working directory of the script can change inside the shutdown function under some web servers, e.g. Apache.

Note:

Shutdown functions will not be executed if the process is killed with a SIGTERM or SIGKILL signal. While you cannot intercept a SIGKILL, you can use pcntl_signal() to install a handler for a SIGTERM which uses exit() to end cleanly.

See Also

  • auto_append_file
  • exit() - Output a message and terminate the current script
  • The section on connection handling


Register a function for execution on each tick

  • « register_shutdown_function
  • unregister_tick_function »
  • PHP Manual
  • Function handling Functions
  • Register a function for execution on each tick

register_tick_function

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

register_tick_function — Register a function for execution on each tick

Description

register_tick_function ( callable $function [, mixed $... ] ) : bool

Registers the given function to be executed when a tick is called.

Parameters

function

The function to register.

...

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 register_tick_function() example

<?php
declare(ticks=1);

// using a function as the callback
register_tick_function('my_function', true);

// using an object->method
$object = new my_class();
register_tick_function(array(&$object, 'my_method'), true);
?>

Changelog

Version | Description
5.3.0 | Ticks are now supported on threaded web server modules.

Notes

Warning

register_tick_function() should not be used with threaded web server modules with PHP 5.2 or lower.

See Also

  • declare
  • unregister_tick_function() - De-register a function for execution on each tick


De-register a function for execution on each tick

  • « register_tick_function
  • Quickhash »
  • PHP Manual
  • Function handling Functions
  • De-register a function for execution on each tick

unregister_tick_function

(PHP 4 >= 4.0.3, PHP 5, PHP 7)

unregister_tick_function — De-register a function for execution on each tick

Description

unregister_tick_function ( callable $function ) : void

De-registers the function function so it is no longer executed when a tick is called.

Parameters

function

The function to de-register.

Return Values

No value is returned.

See Also

  • register_tick_function() - Register a function for execution on each tick


Quickhash

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
  • Predefined Constants
  • Examples
  • QuickHashIntSet — The QuickHashIntSet class
    • QuickHashIntSet::add — This method adds a new entry to the set
    • QuickHashIntSet::__construct — Creates a new QuickHashIntSet object
    • QuickHashIntSet::delete — This method deletes an entry from the set
    • QuickHashIntSet::exists — This method checks whether a key is part of the set
    • QuickHashIntSet::getSize — Returns the number of elements in the set
    • QuickHashIntSet::loadFromFile — This factory method creates a set from a file
    • QuickHashIntSet::loadFromString — This factory method creates a set from a string
    • QuickHashIntSet::saveToFile — This method stores an in-memory set to disk
    • QuickHashIntSet::saveToString — This method returns a serialized version of the set
  • QuickHashIntHash — The QuickHashIntHash class
    • QuickHashIntHash::add — This method adds a new entry to the hash
    • QuickHashIntHash::__construct — Creates a new QuickHashIntHash object
    • QuickHashIntHash::delete — This method deletes am entry from the hash
    • QuickHashIntHash::exists — This method checks whether a key is part of the hash
    • QuickHashIntHash::get — This method retrieves a value from the hash by its key
    • QuickHashIntHash::getSize — Returns the number of elements in the hash
    • QuickHashIntHash::loadFromFile — This factory method creates a hash from a file
    • QuickHashIntHash::loadFromString — This factory method creates a hash from a string
    • QuickHashIntHash::saveToFile — This method stores an in-memory hash to disk
    • QuickHashIntHash::saveToString — This method returns a serialized version of the hash
    • QuickHashIntHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
    • QuickHashIntHash::update — This method updates an entry in the hash with a new value
  • QuickHashStringIntHash — The QuickHashStringIntHash class
    • QuickHashStringIntHash::add — This method adds a new entry to the hash
    • QuickHashStringIntHash::__construct — Creates a new QuickHashStringIntHash object
    • QuickHashStringIntHash::delete — This method deletes am entry from the hash
    • QuickHashStringIntHash::exists — This method checks whether a key is part of the hash
    • QuickHashStringIntHash::get — This method retrieves a value from the hash by its key
    • QuickHashStringIntHash::getSize — Returns the number of elements in the hash
    • QuickHashStringIntHash::loadFromFile — This factory method creates a hash from a file
    • QuickHashStringIntHash::loadFromString — This factory method creates a hash from a string
    • QuickHashStringIntHash::saveToFile — This method stores an in-memory hash to disk
    • QuickHashStringIntHash::saveToString — This method returns a serialized version of the hash
    • QuickHashStringIntHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
    • QuickHashStringIntHash::update — This method updates an entry in the hash with a new value
  • QuickHashIntStringHash — The QuickHashIntStringHash class
    • QuickHashIntStringHash::add — This method adds a new entry to the hash
    • QuickHashIntStringHash::__construct — Creates a new QuickHashIntStringHash object
    • QuickHashIntStringHash::delete — This method deletes am entry from the hash
    • QuickHashIntStringHash::exists — This method checks whether a key is part of the hash
    • QuickHashIntStringHash::get — This method retrieves a value from the hash by its key
    • QuickHashIntStringHash::getSize — Returns the number of elements in the hash
    • QuickHashIntStringHash::loadFromFile — This factory method creates a hash from a file
    • QuickHashIntStringHash::loadFromString — This factory method creates a hash from a string
    • QuickHashIntStringHash::saveToFile — This method stores an in-memory hash to disk
    • QuickHashIntStringHash::saveToString — This method returns a serialized version of the hash
    • QuickHashIntStringHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
    • QuickHashIntStringHash::update — This method updates an entry in the hash with a new value


Introduction

The quickhash extension contains a set of specific strongly-typed classes to deal with specific set and hash implementations.


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

This extension requires no additional libraries.


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/quickhash


  • « Runtime Configuration
  • Examples »
  • PHP Manual
  • Quickhash
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


Examples

Example #1 Quickhash Example

<?php
$set = new QuickHashIntSet( 1024, QuickHashIntSet::CHECK_FOR_DUPES );
$set->add( 1 );
$set->add( 3 );

var_dump( $set->exists( 3 ) );
var_dump( $set->exists( 4 ) );

$set->saveToFile( "/tmp/test-set.set" );

$newSet = QuickHashIntSet::loadFromFile(
    "/tmp/test-set.set"
);

var_dump( $newSet->exists( 3 ) );
var_dump( $newSet->exists( 4 ) );
?>

The above example will output something similar to:

bool(true)
bool(false)
bool(true)
bool(false)

Example #2 Quickhash ArrayAccess Example

<?php
$hash = new QuickHashIntHash( 64 );

// Adding and updating hash entries.
$hash[3] = 145926;
$hash[3] = 1415926;
$hash[2] = 72;

// Checking if keys exist
var_dump( isset( $hash[3] ) );

// Removing hash entries
unset( $hash[2] );

// Retrieving the value stored for a hash
echo $hash[3], "\n";
?>

The above example will output something similar to:

bool(true)
1415926

Example #3 Quickhash Iterator Example

<?php
$hash = new QuickHashIntHash( 64 );

// Adding hash entries.
$hash[1] = 145926;
$hash[2] = 1415926;
$hash[3] = 72;
$hash[4] = 712314;
$hash[5] = -4234;

foreach( $hash as $key => $value )
{
    echo $key, ' => ', $value, "\n";
}
?>

The above example will output something similar to:

5 => -4234
4 => 712314
1 => 145926
2 => 1415926
3 => 72

Example #4 Quickhash String Values Example

<?php
$hash = new QuickHashIntStringHash( 64 );

// Adding hash entries.
$hash[1] = "one million four hundred fifteen thousand nine hundred twenty six";
$hash->add( 2, "one more" );

foreach( $hash as $key => $value )
{
    echo $key, ' => ', $value, "\n";
}
?>

The above example will output something similar to:

1 => one million four hundred fifteen thousand nine hundred twenty six
2 => one more


The QuickHashIntSet class

(PECL quickhash >= Unknown)

Introduction

This class wraps around a set containing integer numbers.

Sets can also be iterated over with foreach as the Iterator interface is implemented as well. The order of which elements are returned in is not guaranteed.

Class synopsis

QuickHashIntSet {
/* Constants */
const integer CHECK_FOR_DUPES = 1 ;
const integer DO_NOT_USE_ZEND_ALLOC = 2 ;
const integer HASHER_NO_HASH = 256 ;
const integer HASHER_JENKINS1 = 512 ;
const integer HASHER_JENKINS2 = 1024 ;
/* Methods */
public add ( int $key ) : bool
public __construct ( int $size [, int $options ] )
public delete ( int $key ) : bool
public exists ( int $key ) : bool
publicgetSize ( void ) : int
public static loadFromFile ( string $filename [, int $size [, int $options ]] ) : QuickHashIntSet
public static loadFromString ( string $contents [, int $size [, int $options ]] ) : QuickHashIntSet
public saveToFile ( string $filename ) : void
public saveToString ( void ) : string
}

Predefined Constants

QuickHashIntSet::CHECK_FOR_DUPES

If enabled, adding duplicate elements to a set (through either add() or loadFromFile()) will result in those elements to be dropped from the set. This will take up extra time, so only used when it is required.

QuickHashIntSet::DO_NOT_USE_ZEND_ALLOC

Disables the use of PHP's internal memory manager for internal set structures. With this option enabled, internal allocations will not count towards the memory_limit settings.

QuickHashIntSet::HASHER_NO_HASH

Selects to not use a hashing function, but merely use a modulo to find the bucket list index. This is not faster than normal hashing, and gives more collisions.

QuickHashIntSet::HASHER_JENKINS1

This is the default hashing function to turn the integer hashes into bucket list indexes.

QuickHashIntSet::HASHER_JENKINS2

Selects a variant hashing algorithm.

Table of Contents

  • QuickHashIntSet::add — This method adds a new entry to the set
  • QuickHashIntSet::__construct — Creates a new QuickHashIntSet object
  • QuickHashIntSet::delete — This method deletes an entry from the set
  • QuickHashIntSet::exists — This method checks whether a key is part of the set
  • QuickHashIntSet::getSize — Returns the number of elements in the set
  • QuickHashIntSet::loadFromFile — This factory method creates a set from a file
  • QuickHashIntSet::loadFromString — This factory method creates a set from a string
  • QuickHashIntSet::saveToFile — This method stores an in-memory set to disk
  • QuickHashIntSet::saveToString — This method returns a serialized version of the set


This method adds a new entry to the set

  • « QuickHashIntSet
  • QuickHashIntSet::__construct »
  • PHP Manual
  • QuickHashIntSet
  • This method adds a new entry to the set

QuickHashIntSet::add

(PECL quickhash >= Unknown)

QuickHashIntSet::add — This method adds a new entry to the set

Description

public QuickHashIntSet::add ( int $key ) : bool

This method adds a new entry to the set, and returns whether the entry was added. Entries are by default always added unless QuickHashIntSet::CHECK_FOR_DUPES has been passed when the set was created.

Parameters

key

The key of the entry to add.

Return Values

TRUE when the entry was added, and FALSE if the entry was not added.

Examples

Example #1 QuickHashIntSet::add() example

<?php
echo "without dupe checking\n";
$set = new QuickHashIntSet( 1024 );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );

echo "\nwith dupe checking\n";
$set = new QuickHashIntSet( 1024, QuickHashIntSet::CHECK_FOR_DUPES );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );
?>

The above example will output something similar to:

without dupe checking
bool(false)
bool(true)
bool(true)
bool(true)

with dupe checking
bool(false)
bool(true)
bool(true)
bool(false)


Creates a new QuickHashIntSet object

  • « QuickHashIntSet::add
  • QuickHashIntSet::delete »
  • PHP Manual
  • QuickHashIntSet
  • Creates a new QuickHashIntSet object

QuickHashIntSet::__construct

(PECL quickhash >= Unknown)

QuickHashIntSet::__construct — Creates a new QuickHashIntSet object

Description

public QuickHashIntSet::__construct ( int $size [, int $options ] )

This constructor creates a new QuickHashIntSet. The size is the amount of bucket lists to create. The more lists there are, the less collisions you will have. Options are also supported.

Parameters

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 4 to 4194304.

options

The options that you can pass in are: QuickHashIntSet::CHECK_FOR_DUPES, which makes sure no duplicate entries are added to the set; QuickHashIntSet::DO_NOT_USE_ZEND_ALLOC to not use PHP's internal memory manager as well as one of QuickHashIntSet::HASHER_NO_HASH, QuickHashIntSet::HASHER_JENKINS1 or QuickHashIntSet::HASHER_JENKINS2. These last three configure which hashing algorithm to use. All options can be combined using bitmasks.

Return Values

Returns a new QuickHashIntSet object.

Examples

Example #1 QuickHashIntSet::__construct() example

<?php
var_dump( new QuickHashIntSet( 1024 ) );
var_dump( new QuickHashIntSet( 1024, QuickHashIntSet::CHECK_FOR_DUPES ) );
var_dump(
    new QuickHashIntSet(
        1024,
        QuickHashIntSet::DO_NOT_USE_ZEND_ALLOC | QuickHashIntSet::HASHER_JENKINS2
    )
);
?>


This method deletes an entry from the set

  • « QuickHashIntSet::__construct
  • QuickHashIntSet::exists »
  • PHP Manual
  • QuickHashIntSet
  • This method deletes an entry from the set

QuickHashIntSet::delete

(PECL quickhash >= Unknown)

QuickHashIntSet::delete — This method deletes an entry from the set

Description

public QuickHashIntSet::delete ( int $key ) : bool

This method deletes an entry from the set, and returns whether the entry was deleted or not. Associated memory structures will not be freed immediately, but rather when the set itself is freed.

Parameters

key

The key of the entry to delete.

Return Values

TRUE when the entry was deleted, and FALSE if the entry was not deleted.

Examples

Example #1 QuickHashIntSet::delete() example

<?php
$set = new QuickHashIntSet( 1024 );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );
var_dump( $set->delete( 4 ) );
var_dump( $set->exists( 4 ) );
var_dump( $set->delete( 4 ) );
?>

The above example will output something similar to:

bool(false)
bool(true)
bool(true)
bool(false)
bool(false)


This method checks whether a key is part of the set

  • « QuickHashIntSet::delete
  • QuickHashIntSet::getSize »
  • PHP Manual
  • QuickHashIntSet
  • This method checks whether a key is part of the set

QuickHashIntSet::exists

(PECL quickhash >= Unknown)

QuickHashIntSet::exists — This method checks whether a key is part of the set

Description

public QuickHashIntSet::exists ( int $key ) : bool

This method checks whether an entry with the provided key exists in the set.

Parameters

key

The key of the entry to check for whether it exists in the set.

Return Values

Returns TRUE when the entry was found, or FALSE when the entry is not found.

Examples

Example #1 QuickHashIntSet::exists() example

<?php
//generate 200000 elements
$array = range( 0, 199999 );
$existingEntries = array_rand( array_flip( $array ), 180000 );
$testForEntries = array_rand( array_flip( $array ), 1000 );
$foundCount = 0;

echo "Creating set: ", microtime( true ), "\n";
$set = new QuickHashIntSet( 100000 );
echo "Adding elements: ", microtime( true ), "\n";
foreach( $existingEntries as $key )
{
     $set->add( $key );
}

echo "Doing 1000 tests: ", microtime( true ), "\n";
foreach( $testForEntries as $key )
{
     $foundCount += $set->exists( $key );
}
echo "Done, $foundCount found: ", microtime( true ), "\n";
?>

The above example will output something similar to:

Creating set: 1263588703.0748
Adding elements: 1263588703.0757
Doing 1000 tests: 1263588703.7851
Done, 898 found: 1263588703.7897


Returns the number of elements in the set

  • « QuickHashIntSet::exists
  • QuickHashIntSet::loadFromFile »
  • PHP Manual
  • QuickHashIntSet
  • Returns the number of elements in the set

QuickHashIntSet::getSize

(PECL quickhash >= Unknown)

QuickHashIntSet::getSize — Returns the number of elements in the set

Description

publicQuickHashIntSet::getSize ( void ) : int

Returns the number of elements in the set.

Parameters

key

The key of the entry to add.

Return Values

The number of elements in the set.

Examples

Example #1 QuickHashIntSet::getSize() example

<?php
$set = new QuickHashIntSet( 8 );
var_dump( $set->add( 2 ) );
var_dump( $set->add( 3 ) );
var_dump( $set->getSize() );
?>

The above example will output something similar to:

bool(true)
bool(true)
int(2)


This factory method creates a set from a file

  • « QuickHashIntSet::getSize
  • QuickHashIntSet::loadFromString »
  • PHP Manual
  • QuickHashIntSet
  • This factory method creates a set from a file

QuickHashIntSet::loadFromFile

(PECL quickhash >= Unknown)

QuickHashIntSet::loadFromFile — This factory method creates a set from a file

Description

public static QuickHashIntSet::loadFromFile ( string $filename [, int $size [, int $options ]] ) : QuickHashIntSet

This factory method creates a new set from a definition file on disk. The file format consists of 32 bit signed integers packed together in the Endianness that the system that the code runs on uses.

Parameters

filename

The filename of the file to read the set from.

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 4 to 4194304.

options

The same options that the class' constructor takes; except that the size option is ignored. It is automatically calculated to be the same as the number of entries in the set, rounded up to the nearest power of two with a maximum limit of 4194304.

Return Values

Returns a new QuickHashIntSet.

Examples

Example #1 QuickHashIntSet::loadFromFile() example

<?php
$file = dirname( __FILE__ ) . "/simple.set";
$set = QuickHashIntSet::loadFromFile(
    $file,
    QuickHashIntSet::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
    printf( "Key %3d (%2x) is %s\n",
        $key, $key,
        $set->exists( $key ) ? 'set' : 'unset'
    );
}
?>

The above example will output something similar to:

Key   0 ( 0) is unset
Key   1 ( 1) is set
Key   2 ( 2) is set
Key   3 ( 3) is set
Key   4 ( 4) is unset
Key   5 ( 5) is set
Key   6 ( 6) is unset
Key   7 ( 7) is set
Key   8 ( 8) is unset
Key   9 ( 9) is unset
Key  10 ( a) is unset
Key  11 ( b) is set
Key  12 ( c) is unset
Key  13 ( d) is set
Key  14 ( e) is unset
Key  15 ( f) is unset


This factory method creates a set from a string

  • « QuickHashIntSet::loadFromFile
  • QuickHashIntSet::saveToFile »
  • PHP Manual
  • QuickHashIntSet
  • This factory method creates a set from a string

QuickHashIntSet::loadFromString

(PECL quickhash >= Unknown)

QuickHashIntSet::loadFromString — This factory method creates a set from a string

Description

public static QuickHashIntSet::loadFromString ( string $contents [, int $size [, int $options ]] ) : QuickHashIntSet

This factory method creates a new set from a definition in a string. The file format consists of 32 bit signed integers packed together in the Endianness that the system that the code runs on uses.

Parameters

contents

The string containing a serialized format of the set.

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 4 to 4194304.

options

The same options that the class' constructor takes; except that the size option is ignored. It is automatically calculated to be the same as the number of entries in the set, rounded up to the nearest power of two automatically limited from 64 to 4194304.

Return Values

Returns a new QuickHashIntSet.

Examples

Example #1 QuickHashIntSet::loadFromString() example

<?php
$contents = file_get_contents( dirname( __FILE__ ) . "/simple.set" );
$set = QuickHashIntSet::loadFromString(
    $contents,
    QuickHashIntSet::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
    printf( "Key %3d (%2x) is %s\n",
        $key, $key,
        $set->exists( $key ) ? 'set' : 'unset'
    );
}
?>

The above example will output something similar to:

Key   0 ( 0) is unset
Key   1 ( 1) is set
Key   2 ( 2) is set
Key   3 ( 3) is set
Key   4 ( 4) is unset
Key   5 ( 5) is set
Key   6 ( 6) is unset
Key   7 ( 7) is set
Key   8 ( 8) is unset
Key   9 ( 9) is unset
Key  10 ( a) is unset
Key  11 ( b) is set
Key  12 ( c) is unset
Key  13 ( d) is set
Key  14 ( e) is unset
Key  15 ( f) is unset


This method stores an in-memory set to disk

  • « QuickHashIntSet::loadFromString
  • QuickHashIntSet::saveToString »
  • PHP Manual
  • QuickHashIntSet
  • This method stores an in-memory set to disk

QuickHashIntSet::saveToFile

(PECL quickhash >= Unknown)

QuickHashIntSet::saveToFile — This method stores an in-memory set to disk

Description

public QuickHashIntSet::saveToFile ( string $filename ) : void

This method stores an existing set to a file on disk, in the same format that loadFromFile() can read.

Parameters

filename

The filename of the file to store the hash in.

Return Values

No value is returned.

Examples

Example #1 QuickHashIntSet::saveToFile() example

<?php
$set = new QuickHashIntSet( 1024 );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );

$set->saveToFile( '/tmp/test.set' );
?>


This method returns a serialized version of the set

  • « QuickHashIntSet::saveToFile
  • QuickHashIntHash »
  • PHP Manual
  • QuickHashIntSet
  • This method returns a serialized version of the set

QuickHashIntSet::saveToString

(PECL quickhash >= Unknown)

QuickHashIntSet::saveToString — This method returns a serialized version of the set

Description

public QuickHashIntSet::saveToString ( void ) : string

This method returns a serialized version of the set in the same format that loadFromString() can read.

Return Values

This method returns a string containing a serialized format of the set. Each element is stored as a four byte value in the Endianness that the current system uses.

Examples

Example #1 QuickHashIntSet::saveToString() example

<?php
$set = new QuickHashIntSet( 1024 );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );

var_dump( $set->saveToString() );
?>


The QuickHashIntHash class

(PECL quickhash >= Unknown)

Introduction

This class wraps around a hash containing integer numbers, where the values are also integer numbers. Hashes are also available as implementation of the ArrayAccess interface.

Hashes can also be iterated over with foreach as the Iterator interface is implemented as well. The order of which elements are returned in is not guaranteed.

Class synopsis

QuickHashIntHash {
/* Constants */
const integer CHECK_FOR_DUPES = 1 ;
const integer DO_NOT_USE_ZEND_ALLOC = 2 ;
const integer HASHER_NO_HASH = 256 ;
const integer HASHER_JENKINS1 = 512 ;
const integer HASHER_JENKINS2 = 1024 ;
/* Methods */
public add ( int $key [, int $value ] ) : bool
public __construct ( int $size [, int $options ] )
public delete ( int $key ) : bool
public exists ( int $key ) : bool
public get ( int $key ) : int
public getSize ( void ) : int
public static loadFromFile ( string $filename [, int $options ] ) : QuickHashIntHash
public static loadFromString ( string $contents [, int $options ] ) : QuickHashIntHash
public saveToFile ( string $filename ) : void
public saveToString ( void ) : string
public set ( int $key , int $value ) : bool
public update ( int $key , int $value ) : bool
}

Predefined Constants

QuickHashIntHash::CHECK_FOR_DUPES

If enabled, adding duplicate elements to a set (through either add() or loadFromFile()) will result in those elements to be dropped from the set. This will take up extra time, so only used when it is required.

QuickHashIntHash::DO_NOT_USE_ZEND_ALLOC

Disables the use of PHP's internal memory manager for internal set structures. With this option enabled, internal allocations will not count towards the memory_limit settings.

QuickHashIntHash::HASHER_NO_HASH

Selects to not use a hashing function, but merely use a modulo to find the bucket list index. This is not faster than normal hashing, and gives more collisions.

QuickHashIntHash::HASHER_JENKINS1

This is the default hashing function to turn the integer hashes into bucket list indexes.

QuickHashIntHash::HASHER_JENKINS2

Selects a variant hashing algorithm.

Table of Contents

  • QuickHashIntHash::add — This method adds a new entry to the hash
  • QuickHashIntHash::__construct — Creates a new QuickHashIntHash object
  • QuickHashIntHash::delete — This method deletes am entry from the hash
  • QuickHashIntHash::exists — This method checks whether a key is part of the hash
  • QuickHashIntHash::get — This method retrieves a value from the hash by its key
  • QuickHashIntHash::getSize — Returns the number of elements in the hash
  • QuickHashIntHash::loadFromFile — This factory method creates a hash from a file
  • QuickHashIntHash::loadFromString — This factory method creates a hash from a string
  • QuickHashIntHash::saveToFile — This method stores an in-memory hash to disk
  • QuickHashIntHash::saveToString — This method returns a serialized version of the hash
  • QuickHashIntHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
  • QuickHashIntHash::update — This method updates an entry in the hash with a new value


This method adds a new entry to the hash

  • « QuickHashIntHash
  • QuickHashIntHash::__construct »
  • PHP Manual
  • QuickHashIntHash
  • This method adds a new entry to the hash

QuickHashIntHash::add

(PECL quickhash >= Unknown)

QuickHashIntHash::add — This method adds a new entry to the hash

Description

public QuickHashIntHash::add ( int $key [, int $value ] ) : bool

This method adds a new entry to the hash, and returns whether the entry was added. Entries are by default always added unless QuickHashIntHash::CHECK_FOR_DUPES has been passed when the hash was created.

Parameters

key

The key of the entry to add.

value

The optional value of the entry to add. If no value is specified, 1 will be used.

Return Values

TRUE when the entry was added, and FALSE if the entry was not added.

Examples

Example #1 QuickHashIntHash::add() example

<?php
echo "without dupe checking\n";
$hash = new QuickHashIntHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, 22 ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, 12 ) );

echo "\nwith dupe checking\n";
$hash = new QuickHashIntHash( 1024, QuickHashIntHash::CHECK_FOR_DUPES );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, 78 ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, 9 ) );

echo "\ndefault value\n";
var_dump( $hash->add( 5 ) );
var_dump( $hash->get( 5 ) );
?>

The above example will output something similar to:

without dupe checking
bool(false)
bool(false)
bool(true)
bool(true)
int(22)
bool(true)

with dupe checking
bool(false)
bool(false)
bool(true)
bool(true)
int(78)
bool(false)

default value
bool(true)
int(1)


Creates a new QuickHashIntHash object

  • « QuickHashIntHash::add
  • QuickHashIntHash::delete »
  • PHP Manual
  • QuickHashIntHash
  • Creates a new QuickHashIntHash object

QuickHashIntHash::__construct

(PECL quickhash >= Unknown)

QuickHashIntHash::__construct — Creates a new QuickHashIntHash object

Description

public QuickHashIntHash::__construct ( int $size [, int $options ] )

This constructor creates a new QuickHashIntHash. The size is the amount of bucket lists to create. The more lists there are, the less collisions you will have. Options are also supported.

Parameters

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 64 to 4194304.

options

The options that you can pass in are: QuickHashIntHash::CHECK_FOR_DUPES, which makes sure no duplicate entries are added to the hash; QuickHashIntHash::DO_NOT_USE_ZEND_ALLOC to not use PHP's internal memory manager as well as one of QuickHashIntHash::HASHER_NO_HASH, QuickHashIntHash::HASHER_JENKINS1 or QuickHashIntHash::HASHER_JENKINS2. These last three configure which hashing algorithm to use. All options can be combined using bitmasks.

Return Values

Returns a new QuickHashIntHash object.

Examples

Example #1 QuickHashIntHash::__construct() example

<?php
var_dump( new QuickHashIntHash( 1024 ) );
var_dump( new QuickHashIntHash( 1024, QuickHashIntHash::CHECK_FOR_DUPES ) );
var_dump(
    new QuickHashIntHash(
        1024,
        QuickHashIntHash::DO_NOT_USE_ZEND_ALLOC | QuickHashIntHash::HASHER_JENKINS2
    )
);
?>


This method deletes am entry from the hash

  • « QuickHashIntHash::__construct
  • QuickHashIntHash::exists »
  • PHP Manual
  • QuickHashIntHash
  • This method deletes am entry from the hash

QuickHashIntHash::delete

(PECL quickhash >= Unknown)

QuickHashIntHash::delete — This method deletes am entry from the hash

Description

public QuickHashIntHash::delete ( int $key ) : bool

This method deletes an entry from the hash, and returns whether the entry was deleted or not. Associated memory structures will not be freed immediately, but rather when the hash itself is freed.

Elements can not be deleted when the hash is used in an iterator. The method will not throw an exception, but simply return FALSE like would happen with any other deletion failure.

Parameters

key

The key of the entry to delete.

Return Values

TRUE when the entry was deleted, and FALSE if the entry was not deleted.

Examples

Example #1 QuickHashIntHash::delete() example

<?php
$hash = new QuickHashIntHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, 5 ) );
var_dump( $hash->delete( 4 ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->delete( 4 ) );
?>

The above example will output something similar to:

bool(false)
bool(true)
bool(true)
bool(false)
bool(false)


This method checks whether a key is part of the hash

  • « QuickHashIntHash::delete
  • QuickHashIntHash::get »
  • PHP Manual
  • QuickHashIntHash
  • This method checks whether a key is part of the hash

QuickHashIntHash::exists

(PECL quickhash >= Unknown)

QuickHashIntHash::exists — This method checks whether a key is part of the hash

Description

public QuickHashIntHash::exists ( int $key ) : bool

This method checks whether an entry with the provided key exists in the hash.

Parameters

key

The key of the entry to check for whether it exists in the hash.

Return Values

Returns TRUE when the entry was found, or FALSE when the entry is not found.

Examples

Example #1 QuickHashIntHash::exists() example

<?php
//generate 200000 elements
$array = range( 0, 199999 );
$existingEntries = array_rand( array_flip( $array ), 180000 );
$testForEntries = array_rand( array_flip( $array ), 1000 );
$foundCount = 0;

echo "Creating hash: ", microtime( true ), "\n";
$hash = new QuickHashIntHash( 100000 );
echo "Adding elements: ", microtime( true ), "\n";
foreach( $existingEntries as $key )
{
     $hash->add( $key, 56 );
}

echo "Doing 1000 tests: ", microtime( true ), "\n";
foreach( $testForEntries as $key )
{
     $foundCount += $hash->exists( $key );
}
echo "Done, $foundCount found: ", microtime( true ), "\n";
?>

The above example will output something similar to:

Creating hash: 1263588703.0748
Adding elements: 1263588703.0757
Doing 1000 tests: 1263588703.7851
Done, 898 found: 1263588703.7897


This method retrieves a value from the hash by its key

  • « QuickHashIntHash::exists
  • QuickHashIntHash::getSize »
  • PHP Manual
  • QuickHashIntHash
  • This method retrieves a value from the hash by its key

QuickHashIntHash::get

(PECL quickhash >= Unknown)

QuickHashIntHash::get — This method retrieves a value from the hash by its key

Description

public QuickHashIntHash::get ( int $key ) : int

This method retrieves a value from the hash by its key.

Parameters

key

The key of the entry to add.

Return Values

The value if the key exists, or NULL if the key wasn't part of the hash.

Examples

Example #1 QuickHashIntHash::get() example

<?php
$hash = new QuickHashIntHash( 8 );
var_dump( $hash->get( 1 ) );

var_dump( $hash->add( 2 ) );
var_dump( $hash->get( 2 ) );

var_dump( $hash->add( 3, 5 ) );
var_dump( $hash->get( 3 ) );
?>

The above example will output something similar to:

bool(false)
bool(true)
int(1)
bool(true)
int(5)


Returns the number of elements in the hash

  • « QuickHashIntHash::get
  • QuickHashIntHash::loadFromFile »
  • PHP Manual
  • QuickHashIntHash
  • Returns the number of elements in the hash

QuickHashIntHash::getSize

(PECL quickhash >= Unknown)

QuickHashIntHash::getSize — Returns the number of elements in the hash

Description

public QuickHashIntHash::getSize ( void ) : int

Returns the number of elements in the hash.

Parameters

key

The key of the entry to add.

Return Values

The number of elements in the hash.

Examples

Example #1 QuickHashIntHash::getSize() example

<?php
$hash = new QuickHashIntHash( 8 );
var_dump( $hash->add( 2 ) );
var_dump( $hash->add( 3, 5 ) );
var_dump( $hash->getSize() );
?>

The above example will output something similar to:

bool(true)
bool(true)
int(2)


This factory method creates a hash from a file

  • « QuickHashIntHash::getSize
  • QuickHashIntHash::loadFromString »
  • PHP Manual
  • QuickHashIntHash
  • This factory method creates a hash from a file

QuickHashIntHash::loadFromFile

(PECL quickhash >= Unknown)

QuickHashIntHash::loadFromFile — This factory method creates a hash from a file

Description

public static QuickHashIntHash::loadFromFile ( string $filename [, int $options ] ) : QuickHashIntHash

This factory method creates a new hash from a definition file on disk. The file format consists of a signature 'QH\0x11\0', the number of elements as a 32 bit signed integer in system Endianness, followed by 32 bit signed integers packed together in the Endianness that the system that the code runs on uses. For each hash element there are two 32 bit signed integers stored. The first of each element is the key, and the second is the value belonging to the key. An example could be:

Example #1 QuickHash IntHash file format

00000000  51 48 11 00 02 00 00 00  01 00 00 00 01 00 00 00  |QH..............|
00000010  03 00 00 00 09 00 00 00                           |........|
00000018

Example #2 QuickHash IntHash file format

header signature ('QH'; key type: 1; value type: 1; filler: \0x00)
00000000  51 48 11 00

number of elements:
00000004  02 00 00 00

data string:
00000000  01 00 00 00 01 00 00 00  03 00 00 00 09 00 00 00

key/value 1 (key = 1, value = 1)
01 00 00 00  01 00 00 00

key/value 2 (key = 3, value = 9)
03 00 00 00  09 00 00 00

Parameters

filename

The filename of the file to read the hash from.

options

The same options that the class' constructor takes; except that the size option is ignored. It is automatically calculated to be the same as the number of entries in the hash, rounded up to the nearest power of two with a maximum limit of 4194304.

Return Values

Returns a new QuickHashIntHash.

Examples

Example #3 QuickHashIntHash::loadFromFile() example

<?php
$file = dirname( __FILE__ ) . "/simple.hash";
$hash = QuickHashIntHash::loadFromFile(
    $file,
    QuickHashIntHash::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
    printf( "Key %3d (%2x) is %s\n",
        $key, $key,
        $hash->exists( $key ) ? 'set' : 'unset'
    );
}
?>

The above example will output something similar to:

Key   0 ( 0) is unset
Key   1 ( 1) is set
Key   2 ( 2) is set
Key   3 ( 3) is set
Key   4 ( 4) is unset
Key   5 ( 5) is set
Key   6 ( 6) is unset
Key   7 ( 7) is set
Key   8 ( 8) is unset
Key   9 ( 9) is unset
Key  10 ( a) is unset
Key  11 ( b) is set
Key  12 ( c) is unset
Key  13 ( d) is set
Key  14 ( e) is unset
Key  15 ( f) is unset


This factory method creates a hash from a string

  • « QuickHashIntHash::loadFromFile
  • QuickHashIntHash::saveToFile »
  • PHP Manual
  • QuickHashIntHash
  • This factory method creates a hash from a string

QuickHashIntHash::loadFromString

(PECL quickhash >= Unknown)

QuickHashIntHash::loadFromString — This factory method creates a hash from a string

Description

public static QuickHashIntHash::loadFromString ( string $contents [, int $options ] ) : QuickHashIntHash

This factory method creates a new hash from a definition in a string. The file format consists of 32 bit signed integers packed together in the Endianness that the system that the code runs on uses. For each element there are two 32 bit signed integers stored. The first of each element is the key, and the second is the value belonging to the key.

Parameters

contents

The string containing a serialized format of the hash.

options

The same options that the class' constructor takes; except that the size option is ignored. It is automatically calculated to be the same as the number of entries in the hash, rounded up to the nearest power of two with a maximum limit of 4194304.

Return Values

Returns a new QuickHashIntHash.

Examples

Example #1 QuickHashIntHash::loadFromString() example

<?php
$contents = file_get_contents( dirname( __FILE__ ) . "/simple.hash" );
$hash = QuickHashIntHash::loadFromString(
    $contents,
    QuickHashIntHash::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
    printf( "Key %3d (%2x) is %s\n",
        $key, $key,
        $hash->exists( $key ) ? 'set' : 'unset'
    );
}
?>

The above example will output something similar to:

Key   0 ( 0) is unset
Key   1 ( 1) is set
Key   2 ( 2) is set
Key   3 ( 3) is set
Key   4 ( 4) is unset
Key   5 ( 5) is set
Key   6 ( 6) is unset
Key   7 ( 7) is set
Key   8 ( 8) is unset
Key   9 ( 9) is unset
Key  10 ( a) is unset
Key  11 ( b) is set
Key  12 ( c) is unset
Key  13 ( d) is set
Key  14 ( e) is unset
Key  15 ( f) is unset


This method stores an in-memory hash to disk

  • « QuickHashIntHash::loadFromString
  • QuickHashIntHash::saveToString »
  • PHP Manual
  • QuickHashIntHash
  • This method stores an in-memory hash to disk

QuickHashIntHash::saveToFile

(PECL quickhash >= Unknown)

QuickHashIntHash::saveToFile — This method stores an in-memory hash to disk

Description

public QuickHashIntHash::saveToFile ( string $filename ) : void

This method stores an existing hash to a file on disk, in the same format that loadFromFile() can read.

Parameters

filename

The filename of the file to store the hash in.

Return Values

No value is returned.

Examples

Example #1 QuickHashIntHash::saveToFile() example

<?php
$hash = new QuickHashIntHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, 43 ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, 52 ) );

$hash->saveToFile( '/tmp/test.hash' );
?>


This method returns a serialized version of the hash

  • « QuickHashIntHash::saveToFile
  • QuickHashIntHash::set »
  • PHP Manual
  • QuickHashIntHash
  • This method returns a serialized version of the hash

QuickHashIntHash::saveToString

(PECL quickhash >= Unknown)

QuickHashIntHash::saveToString — This method returns a serialized version of the hash

Description

public QuickHashIntHash::saveToString ( void ) : string

This method returns a serialized version of the hash in the same format that loadFromString() can read.

Return Values

This method returns a string containing a serialized format of the hash. Each element is stored as a four byte value in the Endianness that the current system uses.

Examples

Example #1 QuickHashIntHash::saveToString() example

<?php
$hash = new QuickHashIntHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, 34 ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, 55 ) );

var_dump( $hash->saveToString() );
?>


This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist

  • « QuickHashIntHash::saveToString
  • QuickHashIntHash::update »
  • PHP Manual
  • QuickHashIntHash
  • This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist

QuickHashIntHash::set

(PECL quickhash >= Unknown)

QuickHashIntHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist

Description

public QuickHashIntHash::set ( int $key , int $value ) : bool

This method tries to update an entry with a new value. In case the entry did not yet exist, it will instead add a new entry. It returns whether the entry was added or update. If there are duplicate keys, only the first found element will get an updated value. Use QuickHashIntHash::CHECK_FOR_DUPES during hash creation to prevent duplicate keys from being part of the hash.

Parameters

key

The key of the entry to add or update.

value

The new value to set the entry with.

Return Values

2 if the entry was found and updated, 1 if the entry was newly added or 0 if there was an error.

Examples

Example #1 QuickHashIntHash::set() example

<?php
$hash = new QuickHashIntHash( 1024 );

echo "Set->Add\n";
var_dump( $hash->get( 46692 ) );
var_dump( $hash->set( 46692, 16091 ) );
var_dump( $hash->get( 46692 ) );

echo "Set->Update\n";
var_dump( $hash->set( 46692, 29906 ) );
var_dump( $hash->get( 46692 ) );
?>

The above example will output something similar to:

bool(false)
int(2)
int(16091)
Set->Update
int(1)
int(29906)


This method updates an entry in the hash with a new value

  • « QuickHashIntHash::set
  • QuickHashStringIntHash »
  • PHP Manual
  • QuickHashIntHash
  • This method updates an entry in the hash with a new value

QuickHashIntHash::update

(PECL quickhash >= Unknown)

QuickHashIntHash::update — This method updates an entry in the hash with a new value

Description

public QuickHashIntHash::update ( int $key , int $value ) : bool

This method updates an entry with a new value, and returns whether the entry was update. If there are duplicate keys, only the first found element will get an updated value. Use QuickHashIntHash::CHECK_FOR_DUPES during hash creation to prevent duplicate keys from being part of the hash.

Parameters

key

The key of the entry to add.

value

The new value to update the entry with.

Return Values

TRUE when the entry was found and updated, and FALSE if the entry was not part of the hash already.

Examples

Example #1 QuickHashIntHash::update() example

<?php
$hash = new QuickHashIntHash( 1024 );

var_dump( $hash->add( 141421, 173205 ) );
var_dump( $hash->update( 141421, 223606 ) );
var_dump( $hash->get( 141421 ) );
?>

The above example will output something similar to:

bool(true)
bool(true)
int(223606)


The QuickHashStringIntHash class

(No version information available, might only be in Git)

Introduction

This class wraps around a hash containing strings, where the values are integer numbers. Hashes are also available as implementation of the ArrayAccess interface.

Hashes can also be iterated over with foreach as the Iterator interface is implemented as well. The order of which elements are returned in is not guaranteed.

Class synopsis

QuickHashStringIntHash {
/* Constants */
const integer CHECK_FOR_DUPES = 1 ;
const integer DO_NOT_USE_ZEND_ALLOC = 2 ;
/* Methods */
public add ( string $key , int $value ) : bool
public __construct ( int $size [, int $options = 0 ] )
public delete ( string $key ) : bool
public exists ( string $key ) : bool
public get ( string $key ) : mixed
public getSize ( void ) : int
public static loadFromFile ( string $filename [, int $size = 0 [, int $options = 0 ]] ) : QuickHashStringIntHash
public static loadFromString ( string $contents [, int $size = 0 [, int $options = 0 ]] ) : QuickHashStringIntHash
public saveToFile ( string $filename ) : void
public saveToString ( void ) : string
public set ( string $key , int $value ) : int
public update ( string $key , int $value ) : bool
}

Predefined Constants

QuickHashStringIntHash::CHECK_FOR_DUPES

If enabled, adding duplicate elements to a set (through either add() or loadFromFile()) will result in those elements to be dropped from the set. This will take up extra time, so only used when it is required.

QuickHashStringIntHash::DO_NOT_USE_ZEND_ALLOC

Disables the use of PHP's internal memory manager for internal set structures. With this option enabled, internal allocations will not count towards the memory_limit settings.

Table of Contents

  • QuickHashStringIntHash::add — This method adds a new entry to the hash
  • QuickHashStringIntHash::__construct — Creates a new QuickHashStringIntHash object
  • QuickHashStringIntHash::delete — This method deletes am entry from the hash
  • QuickHashStringIntHash::exists — This method checks whether a key is part of the hash
  • QuickHashStringIntHash::get — This method retrieves a value from the hash by its key
  • QuickHashStringIntHash::getSize — Returns the number of elements in the hash
  • QuickHashStringIntHash::loadFromFile — This factory method creates a hash from a file
  • QuickHashStringIntHash::loadFromString — This factory method creates a hash from a string
  • QuickHashStringIntHash::saveToFile — This method stores an in-memory hash to disk
  • QuickHashStringIntHash::saveToString — This method returns a serialized version of the hash
  • QuickHashStringIntHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
  • QuickHashStringIntHash::update — This method updates an entry in the hash with a new value


This method adds a new entry to the hash

  • « QuickHashStringIntHash
  • QuickHashStringIntHash::__construct »
  • PHP Manual
  • QuickHashStringIntHash
  • This method adds a new entry to the hash

QuickHashStringIntHash::add

(No version information available, might only be in Git)

QuickHashStringIntHash::add — This method adds a new entry to the hash

Description

public QuickHashStringIntHash::add ( string $key , int $value ) : bool

This method adds a new entry to the hash, and returns whether the entry was added. Entries are by default always added unless QuickHashStringIntHash::CHECK_FOR_DUPES has been passed when the hash was created.

Parameters

key

The key of the entry to add.

value

The value of the entry to add.

Return Values

TRUE when the entry was added, and FALSE if the entry was not added.

Examples

Example #1 QuickHashStringIntHash::add() example

<?php
echo "without dupe checking\n";
$hash = new QuickHashStringIntHash( 1024 );
var_dump( $hash );
var_dump( $hash->exists( "four" ) );
var_dump( $hash->get( "four" ) );
var_dump( $hash->add( "four", 22 ) );
var_dump( $hash->exists( "four" ) );
var_dump( $hash->get( "four" ) );
var_dump( $hash->add( "four", 12 ) );

echo "\nwith dupe checking\n";
$hash = new QuickHashStringIntHash( 1024, QuickHashStringIntHash::CHECK_FOR_DUPES );
var_dump( $hash );
var_dump( $hash->exists( "four" ) );
var_dump( $hash->get( "four" ) );
var_dump( $hash->add( "four", 78 ) );
var_dump( $hash->exists( "four" ) );
var_dump( $hash->get( "four" ) );
var_dump( $hash->add( "four", 9 ) );
?>

The above example will output something similar to:

without dupe checking
object(QuickHashStringIntHash)#1 (0) {
}
bool(false)
bool(false)
bool(true)
bool(true)
int(22)
bool(true)

with dupe checking
object(QuickHashStringIntHash)#2 (0) {
}
bool(false)
bool(false)
bool(true)
bool(true)
int(78)
bool(false)


Creates a new QuickHashStringIntHash object

  • « QuickHashStringIntHash::add
  • QuickHashStringIntHash::delete »
  • PHP Manual
  • QuickHashStringIntHash
  • Creates a new QuickHashStringIntHash object

QuickHashStringIntHash::__construct

(No version information available, might only be in Git)

QuickHashStringIntHash::__construct — Creates a new QuickHashStringIntHash object

Description

public QuickHashStringIntHash::__construct ( int $size [, int $options = 0 ] )

This constructor creates a new QuickHashStringIntHash. The size is the amount of bucket lists to create. The more lists there are, the less collisions you will have. Options are also supported.

Parameters

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 64 to 4194304.

options

The options that you can pass in are: QuickHashStringIntHash::CHECK_FOR_DUPES, which makes sure no duplicate entries are added to the hash and QuickHashStringIntHash::DO_NOT_USE_ZEND_ALLOC to not use PHP's internal memory manager.

Return Values

Returns a new QuickHashStringIntHash object.

Examples

Example #1 QuickHashStringIntHash::__construct() example

<?php
var_dump( new QuickHashStringIntHash( 1024 ) );
var_dump( new QuickHashStringIntHash( 1024, QuickHashStringIntHash::CHECK_FOR_DUPES ) );
?>


This method deletes am entry from the hash

  • « QuickHashStringIntHash::__construct
  • QuickHashStringIntHash::exists »
  • PHP Manual
  • QuickHashStringIntHash
  • This method deletes am entry from the hash

QuickHashStringIntHash::delete

(No version information available, might only be in Git)

QuickHashStringIntHash::delete — This method deletes am entry from the hash

Description

public QuickHashStringIntHash::delete ( string $key ) : bool

This method deletes an entry from the hash, and returns whether the entry was deleted or not. Associated memory structures will not be freed immediately, but rather when the hash itself is freed.

Elements can not be deleted when the hash is used in an iterator. The method will not throw an exception, but simply return FALSE like would happen with any other deletion failure.

Parameters

key

The key of the entry to delete.

Return Values

TRUE when the entry was deleted, and FALSE if the entry was not deleted.

Examples

Example #1 QuickHashStringIntHash::delete() example

<?php
$hash = new QuickHashStringIntHash( 1024 );
var_dump( $hash->exists( 'four' ) );
var_dump( $hash->add( 'four', 5 ) );
var_dump( $hash->get( 'four' ) );
var_dump( $hash->delete( 'four' ) );
var_dump( $hash->exists( 'four' ) );
var_dump( $hash->get( 'four' ) );
var_dump( $hash->delete( 'four' ) );
?>

The above example will output something similar to:

bool(false)
bool(true)
int(5)
bool(true)
bool(false)
bool(false)
bool(false)


This method checks whether a key is part of the hash

  • « QuickHashStringIntHash::delete
  • QuickHashStringIntHash::get »
  • PHP Manual
  • QuickHashStringIntHash
  • This method checks whether a key is part of the hash

QuickHashStringIntHash::exists

(No version information available, might only be in Git)

QuickHashStringIntHash::exists — This method checks whether a key is part of the hash

Description

public QuickHashStringIntHash::exists ( string $key ) : bool

This method checks whether an entry with the provided key exists in the hash.

Parameters

key

The key of the entry to check for whether it exists in the hash.

Return Values

Returns TRUE when the entry was found, or FALSE when the entry is not found.


This method retrieves a value from the hash by its key

  • « QuickHashStringIntHash::exists
  • QuickHashStringIntHash::getSize »
  • PHP Manual
  • QuickHashStringIntHash
  • This method retrieves a value from the hash by its key

QuickHashStringIntHash::get

(No version information available, might only be in Git)

QuickHashStringIntHash::get — This method retrieves a value from the hash by its key

Description

public QuickHashStringIntHash::get ( string $key ) : mixed

This method retrieves a value from the hash by its key.

Parameters

key

The key of the entry to add.

Return Values

The value if the key exists, or NULL if the key wasn't part of the hash.

Examples

Example #1 QuickHashStringIntHash::get() example

<?php
$hash = new QuickHashStringIntHash( 8 );
var_dump( $hash->get( "one" ) );

var_dump( $hash->add( "two", 2 ) );
var_dump( $hash->get( "two" ) );
?>

The above example will output something similar to:

bool(false)
bool(true)
int(2)


Returns the number of elements in the hash

  • « QuickHashStringIntHash::get
  • QuickHashStringIntHash::loadFromFile »
  • PHP Manual
  • QuickHashStringIntHash
  • Returns the number of elements in the hash

QuickHashStringIntHash::getSize

(No version information available, might only be in Git)

QuickHashStringIntHash::getSize — Returns the number of elements in the hash

Description

public QuickHashStringIntHash::getSize ( void ) : int

Returns the number of elements in the hash.

Parameters

key

The key of the entry to add.

Return Values

The number of elements in the hash.

Examples

Example #1 QuickHashStringIntHash::getSize() example

<?php
$hash = new QuickHashStringIntHash( 8 );
var_dump( $hash->add( "two", 2 ) );
var_dump( $hash->add( "three", 5 ) );
var_dump( $hash->getSize() );
?>

The above example will output something similar to:

bool(true)
bool(true)
int(2)


This factory method creates a hash from a file

  • « QuickHashStringIntHash::getSize
  • QuickHashStringIntHash::loadFromString »
  • PHP Manual
  • QuickHashStringIntHash
  • This factory method creates a hash from a file

QuickHashStringIntHash::loadFromFile

(No version information available, might only be in Git)

QuickHashStringIntHash::loadFromFile — This factory method creates a hash from a file

Description

public static QuickHashStringIntHash::loadFromFile ( string $filename [, int $size = 0 [, int $options = 0 ]] ) : QuickHashStringIntHash

This factory method creates a new hash from a definition file on disk. The file format consists of a signature 'QH\0x21\0', the number of elements as a 32 bit signed integer in system Endianness, an unsigned 32 bit integer containing the number of element data to follow in characters. This element data contains all the strings. The follows another signed 32 bit integer containing the number of bucket lists. After the header and the strings, the elements follow. They are ordered by bucket list so that the keys don't have to be hashed in order to restore the hash. For each bucket list, the following information is stored (all as 32 bit integers): the bucket list index, the number of elements in that list, and then in pairs of two unsigned 32 bit integers the elements, where the first one is the index into the string list containing the keys, and the second one the value. An example could be:

Example #1 QuickHash StringIntHash file format

00000000  51 48 21 00 02 00 00 00  09 00 00 00 40 00 00 00  |QH!.........@...|
00000010  4f 4e 45 00 4e 49 4e 45  00 07 00 00 00 01 00 00  |ONE.NINE........|
00000020  00 00 00 00 00 01 00 00  00 2f 00 00 00 01 00 00  |........./......|
00000030  00 04 00 00 00 03 00 00  00                       |.........|
00000039

Example #2 QuickHash IntHash file format

header signature ('QH'; key type: 2; value type: 1; filler: \0x00)
00000000  51 48 21 00

number of elements:
00000004  02 00 00 00

length of string values (9 characters):
00000008  09 00 00 00

number of hash bucket lists (this is configured for hashes as argument to the
constructor normally, 64 in this case):
0000000C  40 00 00 00

string values:
00000010  4f 4e 45 00 4e 49 4e 45  00

bucket lists:
  bucket list 1 (with key 7, and 1 element):
    header:
    07 00 00 00 01 00 00 00
    elements (key index: 0 ('ONE'), value = 0):
    00 00 00 00 01 00 00 00
  bucket list 2 (with key 0x2f, and 1 element):
    header:
    2f 00 00 00 01 00 00 00
    elements (key index: 4 ('NINE'), value = 3):
    04 00 00 00 03 00 00 00

Parameters

filename

The filename of the file to read the hash from.

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 4 to 4194304.

options

The same options that the class' constructor takes; except that the size option is ignored. It is read from the file format (unlike the QuickHashIntHash and QuickHashIntStringHash classes, where it is automatically calculated from the number of entries in the hash.)

Return Values

Returns a new QuickHashStringIntHash.

Examples

Example #3 QuickHashStringIntHash::loadFromFile() example

<?php
$file = dirname( __FILE__ ) . "/simple.hash.string";
$hash = QuickHashStringIntHash::loadFromFile(
    $file,
    QuickHashStringIntHash::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
    $i = 48712 + $key * 1631;
    $k = base_convert( $i, 10, 36 );
    echo $k, ' => ', $hash->get( $k ), "\n";
}
?>

The above example will output something similar to:

11l4 => 48712
12uf => 50343
143q => 51974
15d1 => 53605
16mc => 55236
17vn => 56867
194y => 58498
1ae9 => 60129
1bnk => 61760
1cwv => 63391
1e66 => 65022
1ffh => 66653
1gos => 68284
1hy3 => 69915
1j7e => 71546
1kgp => 73177


This factory method creates a hash from a string

  • « QuickHashStringIntHash::loadFromFile
  • QuickHashStringIntHash::saveToFile »
  • PHP Manual
  • QuickHashStringIntHash
  • This factory method creates a hash from a string

QuickHashStringIntHash::loadFromString

(No version information available, might only be in Git)

QuickHashStringIntHash::loadFromString — This factory method creates a hash from a string

Description

public static QuickHashStringIntHash::loadFromString ( string $contents [, int $size = 0 [, int $options = 0 ]] ) : QuickHashStringIntHash

This factory method creates a new hash from a definition in a string. The format is the same as the one used in "loadFromFile".

Parameters

contents

The string containing a serialized format of the hash.

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 4 to 4194304.

options

The same options that the class' constructor takes; except that the size option is ignored. It is automatically calculated to be the same as the number of entries in the hash, rounded up to the nearest power of two with a maximum limit of 4194304.

Return Values

Returns a new QuickHashStringIntHash.

Examples

Example #1 QuickHashStringIntHash::loadFromString() example

<?php
$contents = file_get_contents( dirname( __FILE__ ) . "/simple.hash.string" );
$hash = QuickHashStringIntHash::loadFromString(
    $contents,
    QuickHashStringIntHash::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
    $i = 48712 + $key * 1631;
    $k = base_convert( $i, 10, 36 );
    echo $k, ' => ', $hash->get( $k ), "\n";
}
?>

The above example will output something similar to:

11l4 => 48712
12uf => 50343
143q => 51974
15d1 => 53605
16mc => 55236
17vn => 56867
194y => 58498
1ae9 => 60129
1bnk => 61760
1cwv => 63391
1e66 => 65022
1ffh => 66653
1gos => 68284
1hy3 => 69915
1j7e => 71546
1kgp => 73177


This method stores an in-memory hash to disk

  • « QuickHashStringIntHash::loadFromString
  • QuickHashStringIntHash::saveToString »
  • PHP Manual
  • QuickHashStringIntHash
  • This method stores an in-memory hash to disk

QuickHashStringIntHash::saveToFile

(No version information available, might only be in Git)

QuickHashStringIntHash::saveToFile — This method stores an in-memory hash to disk

Description

public QuickHashStringIntHash::saveToFile ( string $filename ) : void

This method stores an existing hash to a file on disk, in the same format that loadFromFile() can read.

Parameters

filename

The filename of the file to store the hash in.

Return Values

No value is returned.

Examples

Example #1 QuickHashStringIntHash::saveToFile() example

<?php
$hash = new QuickHashStringIntHash( 1024 );
var_dump( $hash->add( "fourty three", 42 ) );
var_dump( $hash->add( "fifty two", 52 ) );

$hash->saveToFile( '/tmp/test.hash.string' );
?>


This method returns a serialized version of the hash

  • « QuickHashStringIntHash::saveToFile
  • QuickHashStringIntHash::set »
  • PHP Manual
  • QuickHashStringIntHash
  • This method returns a serialized version of the hash

QuickHashStringIntHash::saveToString

(No version information available, might only be in Git)

QuickHashStringIntHash::saveToString — This method returns a serialized version of the hash

Description

public QuickHashStringIntHash::saveToString ( void ) : string

This method returns a serialized version of the hash in the same format that loadFromString() can read.

Return Values

This method returns a serialized format of an existing hash, in the same format that loadFromString() can read.

Examples

Example #1 QuickHashStringIntHash::saveToString() example

<?php
$hash = new QuickHashStringIntHash( 1024 );
var_dump( $hash->add( "fourty three", 42 ) );
var_dump( $hash->add( "fifty two", 52 ) );

var_dump( $hash->saveToString() );
?>


This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist

  • « QuickHashStringIntHash::saveToString
  • QuickHashStringIntHash::update »
  • PHP Manual
  • QuickHashStringIntHash
  • This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist

QuickHashStringIntHash::set

(No version information available, might only be in Git)

QuickHashStringIntHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist

Description

public QuickHashStringIntHash::set ( string $key , int $value ) : int

This method tries to update an entry with a new value. In case the entry did not yet exist, it will instead add a new entry. It returns whether the entry was added or update. If there are duplicate keys, only the first found element will get an updated value. Use QuickHashStringIntHash::CHECK_FOR_DUPES during hash creation to prevent duplicate keys from being part of the hash.

Parameters

key

The key of the entry to add or update.

value

The value of the entry to add. If a non-string is passed, it will be converted to a string automatically if possible.

Return Values

2 if the entry was found and updated, 1 if the entry was newly added or 0 if there was an error.

Examples

Example #1 QuickHashStringIntHash::set() example

<?php
$hash = new QuickHashStringIntHash( 1024 );

echo "Set->Add\n";
var_dump( $hash->get( "fourty six thousand six hundred ninety two" ) );
var_dump( $hash->set( "fourty six thousand six hundred ninety two", 16091 ) );
var_dump( $hash->get( "fourty six thousand six hundred ninety two" ) );

echo "Set->Update\n";
var_dump( $hash->set( "fourty six thousand six hundred ninety two", 29906 ) );
var_dump( $hash->get( "fourty six thousand six hundred ninety two" ) );
?>

The above example will output something similar to:

Set->Add
bool(false)
int(2)
int(16091)
Set->Update
int(1)
int(29906)


This method updates an entry in the hash with a new value

  • « QuickHashStringIntHash::set
  • QuickHashIntStringHash »
  • PHP Manual
  • QuickHashStringIntHash
  • This method updates an entry in the hash with a new value

QuickHashStringIntHash::update

(No version information available, might only be in Git)

QuickHashStringIntHash::update — This method updates an entry in the hash with a new value

Description

public QuickHashStringIntHash::update ( string $key , int $value ) : bool

This method updates an entry with a new value, and returns whether the entry was update. If there are duplicate keys, only the first found element will get an updated value. Use QuickHashStringIntHash::CHECK_FOR_DUPES during hash creation to prevent duplicate keys from being part of the hash.

Parameters

key

The key of the entry to add.

value

The new value for the entry. If a non-string is passed, it will be converted to a string automatically if possible.

Return Values

TRUE when the entry was found and updated, and FALSE if the entry was not part of the hash already.

Examples

Example #1 QuickHashStringIntHash::update() example

<?php
$hash = new QuickHashStringIntHash( 1024 );

$hash->add( 'six', 314159265 );
$hash->add( "a lot", 314159265 );

echo $hash->get( 'six' ), "\n";
echo $hash->get( 'a lot' ), "\n";

var_dump( $hash->update( 'a lot', 314159266 ) );
var_dump( $hash->update( "a lot plus one", 314159999 ) );

echo $hash->get( 'six' ), "\n";
echo $hash->get( 'a lot' ), "\n";
?>

The above example will output something similar to:

314159265
314159265
bool(true)
bool(false)
314159265
314159266


The QuickHashIntStringHash class

(PECL quickhash >= Unknown)

Introduction

This class wraps around a hash containing integer numbers, where the values are strings. Hashes are also available as implementation of the ArrayAccess interface.

Hashes can also be iterated over with foreach as the Iterator interface is implemented as well. The order of which elements are returned in is not guaranteed.

Class synopsis

QuickHashIntStringHash {
/* Constants */
const integer CHECK_FOR_DUPES = 1 ;
const integer DO_NOT_USE_ZEND_ALLOC = 2 ;
const integer HASHER_NO_HASH = 256 ;
const integer HASHER_JENKINS1 = 512 ;
const integer HASHER_JENKINS2 = 1024 ;
/* Methods */
public add ( int $key , string $value ) : bool
public __construct ( int $size [, int $options = 0 ] )
public delete ( int $key ) : bool
public exists ( int $key ) : bool
public get ( int $key ) : mixed
public getSize ( void ) : int
public static loadFromFile ( string $filename [, int $size = 0 [, int $options = 0 ]] ) : QuickHashIntStringHash
public static loadFromString ( string $contents [, int $size = 0 [, int $options = 0 ]] ) : QuickHashIntStringHash
public saveToFile ( string $filename ) : void
public saveToString ( void ) : string
public set ( int $key , string $value ) : int
public update ( int $key , string $value ) : bool
}

Predefined Constants

QuickHashIntStringHash::CHECK_FOR_DUPES

If enabled, adding duplicate elements to a set (through either add() or loadFromFile()) will result in those elements to be dropped from the set. This will take up extra time, so only used when it is required.

QuickHashIntStringHash::DO_NOT_USE_ZEND_ALLOC

Disables the use of PHP's internal memory manager for internal set structures. With this option enabled, internal allocations will not count towards the memory_limit settings.

QuickHashIntStringHash::HASHER_NO_HASH

Selects to not use a hashing function, but merely use a modulo to find the bucket list index. This is not faster than normal hashing, and gives more collisions.

QuickHashIntStringHash::HASHER_JENKINS1

This is the default hashing function to turn the integer hashes into bucket list indexes.

QuickHashIntStringHash::HASHER_JENKINS2

Selects a variant hashing algorithm.

Table of Contents

  • QuickHashIntStringHash::add — This method adds a new entry to the hash
  • QuickHashIntStringHash::__construct — Creates a new QuickHashIntStringHash object
  • QuickHashIntStringHash::delete — This method deletes am entry from the hash
  • QuickHashIntStringHash::exists — This method checks whether a key is part of the hash
  • QuickHashIntStringHash::get — This method retrieves a value from the hash by its key
  • QuickHashIntStringHash::getSize — Returns the number of elements in the hash
  • QuickHashIntStringHash::loadFromFile — This factory method creates a hash from a file
  • QuickHashIntStringHash::loadFromString — This factory method creates a hash from a string
  • QuickHashIntStringHash::saveToFile — This method stores an in-memory hash to disk
  • QuickHashIntStringHash::saveToString — This method returns a serialized version of the hash
  • QuickHashIntStringHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
  • QuickHashIntStringHash::update — This method updates an entry in the hash with a new value


This method adds a new entry to the hash

  • « QuickHashIntStringHash
  • QuickHashIntStringHash::__construct »
  • PHP Manual
  • QuickHashIntStringHash
  • This method adds a new entry to the hash

QuickHashIntStringHash::add

(PECL quickhash >= Unknown)

QuickHashIntStringHash::add — This method adds a new entry to the hash

Description

public QuickHashIntStringHash::add ( int $key , string $value ) : bool

This method adds a new entry to the hash, and returns whether the entry was added. Entries are by default always added unless QuickHashIntStringHash::CHECK_FOR_DUPES has been passed when the hash was created.

Parameters

key

The key of the entry to add.

value

The value of the entry to add. If a non-string is passed, it will be converted to a string automatically if possible.

Return Values

TRUE when the entry was added, and FALSE if the entry was not added.

Examples

Example #1 QuickHashIntStringHash::add() example

<?php
echo "without dupe checking\n";
$hash = new QuickHashIntStringHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, "twenty two" ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, "twelve" ) );

echo "\nwith dupe checking\n";
$hash = new QuickHashIntStringHash( 1024, QuickHashIntStringHash::CHECK_FOR_DUPES );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, "seventy eight" ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, "nine" ) );
?>

The above example will output something similar to:

without dupe checking
bool(false)
bool(false)
bool(true)
bool(true)
string(10) "twenty two"
bool(true)

with dupe checking
bool(false)
bool(false)
bool(true)
bool(true)
string(13) "seventy eight"
bool(false)


Creates a new QuickHashIntStringHash object

  • « QuickHashIntStringHash::add
  • QuickHashIntStringHash::delete »
  • PHP Manual
  • QuickHashIntStringHash
  • Creates a new QuickHashIntStringHash object

QuickHashIntStringHash::__construct

(PECL quickhash >= Unknown)

QuickHashIntStringHash::__construct — Creates a new QuickHashIntStringHash object

Description

public QuickHashIntStringHash::__construct ( int $size [, int $options = 0 ] )

This constructor creates a new QuickHashIntStringHash. The size is the amount of bucket lists to create. The more lists there are, the less collisions you will have. Options are also supported.

Parameters

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 64 to 4194304.

options

The options that you can pass in are: QuickHashIntStringHash::CHECK_FOR_DUPES, which makes sure no duplicate entries are added to the hash; QuickHashIntStringHash::DO_NOT_USE_ZEND_ALLOC to not use PHP's internal memory manager as well as one of QuickHashIntStringHash::HASHER_NO_HASH, QuickHashIntStringHash::HASHER_JENKINS1 or QuickHashIntStringHash::HASHER_JENKINS2. These last three configure which hashing algorithm to use. All options can be combined using bitmasks.

Return Values

Returns a new QuickHashIntStringHash object.

Examples

Example #1 QuickHashIntStringHash::__construct() example

<?php
var_dump( new QuickHashIntStringHash( 1024 ) );
var_dump( new QuickHashIntStringHash( 1024, QuickHashIntStringHash::CHECK_FOR_DUPES ) );
var_dump(
    new QuickHashIntStringHash(
        1024,
        QuickHashIntStringHash::DO_NOT_USE_ZEND_ALLOC | QuickHashIntStringHash::HASHER_JENKINS2
    )
);
?>


This method deletes am entry from the hash

  • « QuickHashIntStringHash::__construct
  • QuickHashIntStringHash::exists »
  • PHP Manual
  • QuickHashIntStringHash
  • This method deletes am entry from the hash

QuickHashIntStringHash::delete

(PECL quickhash >= Unknown)

QuickHashIntStringHash::delete — This method deletes am entry from the hash

Description

public QuickHashIntStringHash::delete ( int $key ) : bool

This method deletes an entry from the hash, and returns whether the entry was deleted or not. Associated memory structures will not be freed immediately, but rather when the hash itself is freed.

Elements can not be deleted when the hash is used in an iterator. The method will not throw an exception, but simply return FALSE like would happen with any other deletion failure.

Parameters

key

The key of the entry to delete.

Return Values

TRUE when the entry was deleted, and FALSE if the entry was not deleted.

Examples

Example #1 QuickHashIntStringHash::delete() example

<?php
$hash = new QuickHashIntStringHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, "five" ) );
var_dump( $hash->delete( 4 ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->delete( 4 ) );
?>

The above example will output something similar to:

bool(false)
bool(true)
bool(true)
bool(false)
bool(false)


This method checks whether a key is part of the hash

  • « QuickHashIntStringHash::delete
  • QuickHashIntStringHash::get »
  • PHP Manual
  • QuickHashIntStringHash
  • This method checks whether a key is part of the hash

QuickHashIntStringHash::exists

(PECL quickhash >= Unknown)

QuickHashIntStringHash::exists — This method checks whether a key is part of the hash

Description

public QuickHashIntStringHash::exists ( int $key ) : bool

This method checks whether an entry with the provided key exists in the hash.

Parameters

key

The key of the entry to check for whether it exists in the hash.

Return Values

Returns TRUE when the entry was found, or FALSE when the entry is not found.


This method retrieves a value from the hash by its key

  • « QuickHashIntStringHash::exists
  • QuickHashIntStringHash::getSize »
  • PHP Manual
  • QuickHashIntStringHash
  • This method retrieves a value from the hash by its key

QuickHashIntStringHash::get

(PECL quickhash >= Unknown)

QuickHashIntStringHash::get — This method retrieves a value from the hash by its key

Description

public QuickHashIntStringHash::get ( int $key ) : mixed

This method retrieves a value from the hash by its key.

Parameters

key

The key of the entry to add.

Return Values

The value if the key exists, or NULL if the key wasn't part of the hash.

Examples

Example #1 QuickHashIntStringHash::get() example

<?php
$hash = new QuickHashIntStringHash( 8 );
var_dump( $hash->get( 1 ) );

var_dump( $hash->add( 2, "two" ) );
var_dump( $hash->get( 2 ) );

var_dump( $hash->add( 3, 5 ) );
var_dump( $hash->get( 3 ) );
?>

The above example will output something similar to:

bool(false)
bool(true)
string(3) "two"
bool(true)
string(1) "5"


Returns the number of elements in the hash

  • « QuickHashIntStringHash::get
  • QuickHashIntStringHash::loadFromFile »
  • PHP Manual
  • QuickHashIntStringHash
  • Returns the number of elements in the hash

QuickHashIntStringHash::getSize

(PECL quickhash >= Unknown)

QuickHashIntStringHash::getSize — Returns the number of elements in the hash

Description

public QuickHashIntStringHash::getSize ( void ) : int

Returns the number of elements in the hash.

Return Values

The number of elements in the hash.

Examples

Example #1 QuickHashIntStringHash::getSize() example

<?php
$hash = new QuickHashIntStringHash( 8 );
var_dump( $hash->add( 2, "two" ) );
var_dump( $hash->add( 3, 5 ) );
var_dump( $hash->getSize() );
?>

The above example will output something similar to:

bool(true)
bool(true)
int(2)


This factory method creates a hash from a file

  • « QuickHashIntStringHash::getSize
  • QuickHashIntStringHash::loadFromString »
  • PHP Manual
  • QuickHashIntStringHash
  • This factory method creates a hash from a file

QuickHashIntStringHash::loadFromFile

(PECL quickhash >= Unknown)

QuickHashIntStringHash::loadFromFile — This factory method creates a hash from a file

Description

public static QuickHashIntStringHash::loadFromFile ( string $filename [, int $size = 0 [, int $options = 0 ]] ) : QuickHashIntStringHash

This factory method creates a new hash from a definition file on disk. The file format consists of a signature 'QH\0x12\0', the number of elements as a 32 bit signed integer in system Endianness, an unsigned 32 bit integer containing the number of element data to follow in characters. This element data contains all the strings. After the header and the strings, the elements follow in pairs of two unsigned 32 bit integers where the first one is the key, and the second one the index in the element data string. An example could be:

Example #1 QuickHash IntString file format

00000000  51 48 12 00 02 00 00 00  09 00 00 00 4f 4e 45 00  |QH..........ONE.|
00000010  4e 49 4e 45 00 01 00 00  00 00 00 00 00 03 00 00  |NINE............|
00000020  00 04 00 00 00                                    |.....|
00000025

Example #2 QuickHash IntString file format

header signature ('QH'; key type: 1; value type: 2; filler: \0x00)
00000000  51 48 12 00

number of elements:
00000004  02 00 00 00

length of string values (9 characters):
00000008  09 00 00 00

string values:
0000000C  4f 4e 45 00 4e 49 4e 45  00

data string:
00000015  01 00 00 00 00 00 00 00  03 00 00 00 04 00 00 00

key/value 1 (key = 1, string index = 0 ("ONE")):
01 00 00 00  00 00 00 00

key/value 2 (key = 3, string index = 4 ("NINE")):
03 00 00 00  04 00 00 00

Parameters

filename

The filename of the file to read the hash from.

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 4 to 4194304.

options

The same options that the class' constructor takes; except that the size option is ignored. It is automatically calculated to be the same as the number of entries in the hash, rounded up to the nearest power of two with a maximum limit of 4194304.

Return Values

Returns a new QuickHashIntStringHash.

Examples

Example #3 QuickHashIntStringHash::loadFromFile() example

<?php
$file = dirname( __FILE__ ) . "/simple.string.hash";
$hash = QuickHashIntStringHash::loadFromFile(
    $file,
    QuickHashIntStringHash::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
    printf( "Key %3d (%2x) is %s\n",
        $key, $key,
        $hash->exists( $key ) ? 'set' : 'unset'
    );
}
?>

The above example will output something similar to:

Key   0 ( 0) is unset
Key   1 ( 1) is set
Key   2 ( 2) is set
Key   3 ( 3) is set
Key   4 ( 4) is unset
Key   5 ( 5) is set
Key   6 ( 6) is unset
Key   7 ( 7) is set
Key   8 ( 8) is unset
Key   9 ( 9) is unset
Key  10 ( a) is unset
Key  11 ( b) is set
Key  12 ( c) is unset
Key  13 ( d) is set
Key  14 ( e) is unset
Key  15 ( f) is unset


This factory method creates a hash from a string

  • « QuickHashIntStringHash::loadFromFile
  • QuickHashIntStringHash::saveToFile »
  • PHP Manual
  • QuickHashIntStringHash
  • This factory method creates a hash from a string

QuickHashIntStringHash::loadFromString

(PECL quickhash >= Unknown)

QuickHashIntStringHash::loadFromString — This factory method creates a hash from a string

Description

public static QuickHashIntStringHash::loadFromString ( string $contents [, int $size = 0 [, int $options = 0 ]] ) : QuickHashIntStringHash

This factory method creates a new hash from a definition in a string. The format is the same as the one used in "loadFromFile".

Parameters

contents

The string containing a serialized format of the hash.

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 4 to 4194304.

options

The same options that the class' constructor takes; except that the size option is ignored. It is automatically calculated to be the same as the number of entries in the hash, rounded up to the nearest power of two with a maximum limit of 4194304.

Return Values

Returns a new QuickHashIntStringHash.

Examples

Example #1 QuickHashIntStringHash::loadFromString() example

<?php
$contents = file_get_contents( dirname( __FILE__ ) . "/simple.hash" );
$hash = QuickHashIntStringHash::loadFromString(
    $contents,
    QuickHashIntStringHash::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
    printf( "Key %3d (%2x) is %s\n",
        $key, $key,
        $hash->exists( $key ) ? 'set' : 'unset'
    );
}
?>

The above example will output something similar to:

Key   0 ( 0) is unset
Key   1 ( 1) is set
Key   2 ( 2) is set
Key   3 ( 3) is set
Key   4 ( 4) is unset
Key   5 ( 5) is set
Key   6 ( 6) is unset
Key   7 ( 7) is set
Key   8 ( 8) is unset
Key   9 ( 9) is unset
Key  10 ( a) is unset
Key  11 ( b) is set
Key  12 ( c) is unset
Key  13 ( d) is set
Key  14 ( e) is unset
Key  15 ( f) is unset


This method stores an in-memory hash to disk

  • « QuickHashIntStringHash::loadFromString
  • QuickHashIntStringHash::saveToString »
  • PHP Manual
  • QuickHashIntStringHash
  • This method stores an in-memory hash to disk

QuickHashIntStringHash::saveToFile

(PECL quickhash >= Unknown)

QuickHashIntStringHash::saveToFile — This method stores an in-memory hash to disk

Description

public QuickHashIntStringHash::saveToFile ( string $filename ) : void

This method stores an existing hash to a file on disk, in the same format that loadFromFile() can read.

Parameters

filename

The filename of the file to store the hash in.

Return Values

No value is returned.

Examples

Example #1 QuickHashIntStringHash::saveToFile() example

<?php
$hash = new QuickHashIntStringHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, "fourty three" ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, "fifty two" ) );

$hash->saveToFile( '/tmp/test.string.hash' );
?>


This method returns a serialized version of the hash

  • « QuickHashIntStringHash::saveToFile
  • QuickHashIntStringHash::set »
  • PHP Manual
  • QuickHashIntStringHash
  • This method returns a serialized version of the hash

QuickHashIntStringHash::saveToString

(PECL quickhash >= Unknown)

QuickHashIntStringHash::saveToString — This method returns a serialized version of the hash

Description

public QuickHashIntStringHash::saveToString ( void ) : string

This method returns a serialized version of the hash in the same format that loadFromString() can read.

Return Values

This method returns a string containing a serialized format of the hash. Each element is stored as a four byte value in the Endianness that the current system uses.

Examples

Example #1 QuickHashIntStringHash::saveToString() example

<?php
$hash = new QuickHashIntStringHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, "thirty four" ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 5, "fifty five" ) );

var_dump( $hash->saveToString() );
?>


This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist

  • « QuickHashIntStringHash::saveToString
  • QuickHashIntStringHash::update »
  • PHP Manual
  • QuickHashIntStringHash
  • This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist

QuickHashIntStringHash::set

(PECL quickhash >= Unknown)

QuickHashIntStringHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist

Description

public QuickHashIntStringHash::set ( int $key , string $value ) : int

This method tries to update an entry with a new value. In case the entry did not yet exist, it will instead add a new entry. It returns whether the entry was added or update. If there are duplicate keys, only the first found element will get an updated value. Use QuickHashIntStringHash::CHECK_FOR_DUPES during hash creation to prevent duplicate keys from being part of the hash.

Parameters

key

The key of the entry to add or update.

value

The value of the entry to add. If a non-string is passed, it will be converted to a string automatically if possible.

Return Values

2 if the entry was found and updated, 1 if the entry was newly added or 0 if there was an error.

Examples

Example #1 QuickHashIntStringHash::set() example

<?php
$hash = new QuickHashIntStringHash( 1024 );

echo "Set->Add\n";
var_dump( $hash->get( 46692 ) );
var_dump( $hash->set( 46692, "sixteen thousand ninety one" ) );
var_dump( $hash->get( 46692 ) );

echo "Set->Update\n";
var_dump( $hash->set( 46692, "twenty nine thousand nine hundred six" ) );
var_dump( $hash->get( 46692 ) );
?>

The above example will output something similar to:

Set->Add
bool(false)
int(2)
string(27) "sixteen thousand ninety one"
Set->Update
int(1)
string(37) "twenty nine thousand nine hundred six"


This method updates an entry in the hash with a new value

  • « QuickHashIntStringHash::set
  • Reflection »
  • PHP Manual
  • QuickHashIntStringHash
  • This method updates an entry in the hash with a new value

QuickHashIntStringHash::update

(PECL quickhash >= Unknown)

QuickHashIntStringHash::update — This method updates an entry in the hash with a new value

Description

public QuickHashIntStringHash::update ( int $key , string $value ) : bool

This method updates an entry with a new value, and returns whether the entry was update. If there are duplicate keys, only the first found element will get an updated value. Use QuickHashIntStringHash::CHECK_FOR_DUPES during hash creation to prevent duplicate keys from being part of the hash.

Parameters

key

The key of the entry to add.

value

The new value for the entry. If a non-string is passed, it will be converted to a string automatically if possible.

Return Values

TRUE when the entry was found and updated, and FALSE if the entry was not part of the hash already.

Examples

Example #1 QuickHashIntStringHash::update() example

<?php
$hash->add( 161803398, "--" );
$hash->add( 314159265, "a lot" );

echo $hash->get( 161803398 ), "\n";
echo $hash->get( 314159265 ), "\n";

var_dump( $hash->update( 314159265, "a lot plus one" ) );
var_dump( $hash->update( 314159999, "a lot plus one" ) );

echo $hash->get( 161803398 ), "\n";
echo $hash->get( 314159265 ), "\n";
?>

The above example will output something similar to:

--
a lot
bool(true)
bool(false)
--
a lot plus one


Reflection

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Extending
  • Reflection — The Reflection class
    • Reflection::export — Exports
    • Reflection::getModifierNames — Gets modifier names
  • ReflectionClass — The ReflectionClass class
    • ReflectionClass::__construct — Constructs a ReflectionClass
    • ReflectionClass::export — Exports a class
    • ReflectionClass::getConstant — Gets defined constant
    • ReflectionClass::getConstants — Gets constants
    • ReflectionClass::getConstructor — Gets the constructor of the class
    • ReflectionClass::getDefaultProperties — Gets default properties
    • ReflectionClass::getDocComment — Gets doc comments
    • ReflectionClass::getEndLine — Gets end line
    • ReflectionClass::getExtension — Gets a ReflectionExtension object for the extension which defined the class
    • ReflectionClass::getExtensionName — Gets the name of the extension which defined the class
    • ReflectionClass::getFileName — Gets the filename of the file in which the class has been defined
    • ReflectionClass::getInterfaceNames — Gets the interface names
    • ReflectionClass::getInterfaces — Gets the interfaces
    • ReflectionClass::getMethod — Gets a ReflectionMethod for a class method
    • ReflectionClass::getMethods — Gets an array of methods
    • ReflectionClass::getModifiers — Gets the class modifiers
    • ReflectionClass::getName — Gets class name
    • ReflectionClass::getNamespaceName — Gets namespace name
    • ReflectionClass::getParentClass — Gets parent class
    • ReflectionClass::getProperties — Gets properties
    • ReflectionClass::getProperty — Gets a ReflectionProperty for a class's property
    • ReflectionClass::getReflectionConstant — Gets a ReflectionClassConstant for a class's constant
    • ReflectionClass::getReflectionConstants — Gets class constants
    • ReflectionClass::getShortName — Gets short name
    • ReflectionClass::getStartLine — Gets starting line number
    • ReflectionClass::getStaticProperties — Gets static properties
    • ReflectionClass::getStaticPropertyValue — Gets static property value
    • ReflectionClass::getTraitAliases — Returns an array of trait aliases
    • ReflectionClass::getTraitNames — Returns an array of names of traits used by this class
    • ReflectionClass::getTraits — Returns an array of traits used by this class
    • ReflectionClass::hasConstant — Checks if constant is defined
    • ReflectionClass::hasMethod — Checks if method is defined
    • ReflectionClass::hasProperty — Checks if property is defined
    • ReflectionClass::implementsInterface — Implements interface
    • ReflectionClass::inNamespace — Checks if in namespace
    • ReflectionClass::isAbstract — Checks if class is abstract
    • ReflectionClass::isAnonymous — Checks if class is anonymous
    • ReflectionClass::isCloneable — Returns whether this class is cloneable
    • ReflectionClass::isFinal — Checks if class is final
    • ReflectionClass::isInstance — Checks class for instance
    • ReflectionClass::isInstantiable — Checks if the class is instantiable
    • ReflectionClass::isInterface — Checks if the class is an interface
    • ReflectionClass::isInternal — Checks if class is defined internally by an extension, or the core
    • ReflectionClass::isIterable — Check whether this class is iterable
    • ReflectionClass::isIterateable — Alias of ReflectionClass::isIterable
    • ReflectionClass::isSubclassOf — Checks if a subclass
    • ReflectionClass::isTrait — Returns whether this is a trait
    • ReflectionClass::isUserDefined — Checks if user defined
    • ReflectionClass::newInstance — Creates a new class instance from given arguments
    • ReflectionClass::newInstanceArgs — Creates a new class instance from given arguments
    • ReflectionClass::newInstanceWithoutConstructor — Creates a new class instance without invoking the constructor
    • ReflectionClass::setStaticPropertyValue — Sets static property value
    • ReflectionClass::__toString — Returns the string representation of the ReflectionClass object
  • ReflectionClassConstant — The ReflectionClassConstant class
    • ReflectionClassConstant::__construct — Constructs a ReflectionClassConstant
    • ReflectionClassConstant::export — Export
    • ReflectionClassConstant::getDeclaringClass — Gets declaring class
    • ReflectionClassConstant::getDocComment — Gets doc comments
    • ReflectionClassConstant::getModifiers — Gets the class constant modifiers
    • ReflectionClassConstant::getName — Get name of the constant
    • ReflectionClassConstant::getValue — Gets value
    • ReflectionClassConstant::isPrivate — Checks if class constant is private
    • ReflectionClassConstant::isProtected — Checks if class constant is protected
    • ReflectionClassConstant::isPublic — Checks if class constant is public
    • ReflectionClassConstant::__toString — Returns the string representation of the ReflectionClassConstant object
  • ReflectionZendExtension — The ReflectionZendExtension class
    • ReflectionZendExtension::__clone — Clone handler
    • ReflectionZendExtension::__construct — Constructor
    • ReflectionZendExtension::export — Export
    • ReflectionZendExtension::getAuthor — Gets author
    • ReflectionZendExtension::getCopyright — Gets copyright
    • ReflectionZendExtension::getName — Gets name
    • ReflectionZendExtension::getURL — Gets URL
    • ReflectionZendExtension::getVersion — Gets version
    • ReflectionZendExtension::__toString — To string handler
  • ReflectionExtension — The ReflectionExtension class
    • ReflectionExtension::__clone — Clones
    • ReflectionExtension::__construct — Constructs a ReflectionExtension
    • ReflectionExtension::export — Export
    • ReflectionExtension::getClasses — Gets classes
    • ReflectionExtension::getClassNames — Gets class names
    • ReflectionExtension::getConstants — Gets constants
    • ReflectionExtension::getDependencies — Gets dependencies
    • ReflectionExtension::getFunctions — Gets extension functions
    • ReflectionExtension::getINIEntries — Gets extension ini entries
    • ReflectionExtension::getName — Gets extension name
    • ReflectionExtension::getVersion — Gets extension version
    • ReflectionExtension::info — Print extension info
    • ReflectionExtension::isPersistent — Returns whether this extension is persistent
    • ReflectionExtension::isTemporary — Returns whether this extension is temporary
    • ReflectionExtension::__toString — To string
  • ReflectionFunction — The ReflectionFunction class
    • ReflectionFunction::__construct — Constructs a ReflectionFunction object
    • ReflectionFunction::export — Exports function
    • ReflectionFunction::getClosure — Returns a dynamically created closure for the function
    • ReflectionFunction::invoke — Invokes function
    • ReflectionFunction::invokeArgs — Invokes function args
    • ReflectionFunction::isDisabled — Checks if function is disabled
    • ReflectionFunction::__toString — To string
  • ReflectionFunctionAbstract — The ReflectionFunctionAbstract class
    • ReflectionFunctionAbstract::__clone — Clones function
    • ReflectionFunctionAbstract::getClosureScopeClass — Returns the scope associated to the closure
    • ReflectionFunctionAbstract::getClosureThis — Returns this pointer bound to closure
    • ReflectionFunctionAbstract::getDocComment — Gets doc comment
    • ReflectionFunctionAbstract::getEndLine — Gets end line number
    • ReflectionFunctionAbstract::getExtension — Gets extension info
    • ReflectionFunctionAbstract::getExtensionName — Gets extension name
    • ReflectionFunctionAbstract::getFileName — Gets file name
    • ReflectionFunctionAbstract::getName — Gets function name
    • ReflectionFunctionAbstract::getNamespaceName — Gets namespace name
    • ReflectionFunctionAbstract::getNumberOfParameters — Gets number of parameters
    • ReflectionFunctionAbstract::getNumberOfRequiredParameters — Gets number of required parameters
    • ReflectionFunctionAbstract::getParameters — Gets parameters
    • ReflectionFunctionAbstract::getReturnType — Gets the specified return type of a function
    • ReflectionFunctionAbstract::getShortName — Gets function short name
    • ReflectionFunctionAbstract::getStartLine — Gets starting line number
    • ReflectionFunctionAbstract::getStaticVariables — Gets static variables
    • ReflectionFunctionAbstract::hasReturnType — Checks if the function has a specified return type
    • ReflectionFunctionAbstract::inNamespace — Checks if function in namespace
    • ReflectionFunctionAbstract::isClosure — Checks if closure
    • ReflectionFunctionAbstract::isDeprecated — Checks if deprecated
    • ReflectionFunctionAbstract::isGenerator — Returns whether this function is a generator
    • ReflectionFunctionAbstract::isInternal — Checks if is internal
    • ReflectionFunctionAbstract::isUserDefined — Checks if user defined
    • ReflectionFunctionAbstract::isVariadic — Checks if the function is variadic
    • ReflectionFunctionAbstract::returnsReference — Checks if returns reference
    • ReflectionFunctionAbstract::__toString — To string
  • ReflectionMethod — The ReflectionMethod class
    • ReflectionMethod::__construct — Constructs a ReflectionMethod
    • ReflectionMethod::export — Export a reflection method
    • ReflectionMethod::getClosure — Returns a dynamically created closure for the method
    • ReflectionMethod::getDeclaringClass — Gets declaring class for the reflected method
    • ReflectionMethod::getModifiers — Gets the method modifiers
    • ReflectionMethod::getPrototype — Gets the method prototype (if there is one)
    • ReflectionMethod::invoke — Invoke
    • ReflectionMethod::invokeArgs — Invoke args
    • ReflectionMethod::isAbstract — Checks if method is abstract
    • ReflectionMethod::isConstructor — Checks if method is a constructor
    • ReflectionMethod::isDestructor — Checks if method is a destructor
    • ReflectionMethod::isFinal — Checks if method is final
    • ReflectionMethod::isPrivate — Checks if method is private
    • ReflectionMethod::isProtected — Checks if method is protected
    • ReflectionMethod::isPublic — Checks if method is public
    • ReflectionMethod::isStatic — Checks if method is static
    • ReflectionMethod::setAccessible — Set method accessibility
    • ReflectionMethod::__toString — Returns the string representation of the Reflection method object
  • ReflectionNamedType — The ReflectionNamedType class
    • ReflectionNamedType::getName — Get the text of the type hint
  • ReflectionObject — The ReflectionObject class
    • ReflectionObject::__construct — Constructs a ReflectionObject
    • ReflectionObject::export — Export
  • ReflectionParameter — The ReflectionParameter class
    • ReflectionParameter::allowsNull — Checks if null is allowed
    • ReflectionParameter::canBePassedByValue — Returns whether this parameter can be passed by value
    • ReflectionParameter::__clone — Clone
    • ReflectionParameter::__construct — Construct
    • ReflectionParameter::export — Exports
    • ReflectionParameter::getClass — Get the type hinted class
    • ReflectionParameter::getDeclaringClass — Gets declaring class
    • ReflectionParameter::getDeclaringFunction — Gets declaring function
    • ReflectionParameter::getDefaultValue — Gets default parameter value
    • ReflectionParameter::getDefaultValueConstantName — Returns the default value's constant name if default value is constant or null
    • ReflectionParameter::getName — Gets parameter name
    • ReflectionParameter::getPosition — Gets parameter position
    • ReflectionParameter::getType — Gets a parameter's type
    • ReflectionParameter::hasType — Checks if parameter has a type
    • ReflectionParameter::isArray — Checks if parameter expects an array
    • ReflectionParameter::isCallable — Returns whether parameter MUST be callable
    • ReflectionParameter::isDefaultValueAvailable — Checks if a default value is available
    • ReflectionParameter::isDefaultValueConstant — Returns whether the default value of this parameter is a constant
    • ReflectionParameter::isOptional — Checks if optional
    • ReflectionParameter::isPassedByReference — Checks if passed by reference
    • ReflectionParameter::isVariadic — Checks if the parameter is variadic
    • ReflectionParameter::__toString — To string
  • ReflectionProperty — The ReflectionProperty class
    • ReflectionProperty::__clone — Clone
    • ReflectionProperty::__construct — Construct a ReflectionProperty object
    • ReflectionProperty::export — Export
    • ReflectionProperty::getDeclaringClass — Gets declaring class
    • ReflectionProperty::getDocComment — Gets the property doc comment
    • ReflectionProperty::getModifiers — Gets the property modifiers
    • ReflectionProperty::getName — Gets property name
    • ReflectionProperty::getType — Gets a property's type
    • ReflectionProperty::getValue — Gets value
    • ReflectionProperty::hasType — Checks if property has a type
    • ReflectionProperty::isDefault — Checks if property is a default property
    • ReflectionProperty::isInitialized — Checks whether a property is initialized
    • ReflectionProperty::isPrivate — Checks if property is private
    • ReflectionProperty::isProtected — Checks if property is protected
    • ReflectionProperty::isPublic — Checks if property is public
    • ReflectionProperty::isStatic — Checks if property is static
    • ReflectionProperty::setAccessible — Set property accessibility
    • ReflectionProperty::setValue — Set property value
    • ReflectionProperty::__toString — To string
  • ReflectionType — The ReflectionType class
    • ReflectionType::allowsNull — Checks if null is allowed
    • ReflectionType::isBuiltin — Checks if it is a built-in type
    • ReflectionType::__toString — To string
  • ReflectionGenerator — The ReflectionGenerator class
    • ReflectionGenerator::__construct — Constructs a ReflectionGenerator object
    • ReflectionGenerator::getExecutingFile — Gets the file name of the currently executing generator
    • ReflectionGenerator::getExecutingGenerator — Gets the executing Generator object
    • ReflectionGenerator::getExecutingLine — Gets the currently executing line of the generator
    • ReflectionGenerator::getFunction — Gets the function name of the generator
    • ReflectionGenerator::getThis — Gets the $this value of the generator
    • ReflectionGenerator::getTrace — Gets the trace of the executing generator
  • Reflector — The Reflector interface
    • Reflector::export — Exports
    • Reflector::__toString — To string
  • ReflectionException — The ReflectionException class


Introduction

PHP comes with a complete reflection API that adds the ability to introspect classes, interfaces, functions, methods and extensions. Additionally, the reflection API offers ways to retrieve doc comments for functions, classes and methods.

Please note that certain parts of the internal API are missing the necessary code to work with the Reflection extension. E.g., an internal PHP class might be missing reflection data for properties. These few cases are considered bugs, however, so they should be discovered and fixed.


  • « Resource Types
  • Examples »
  • PHP Manual
  • Reflection
  • Predefined Constants

Predefined Constants

Each class describes its own constants.


Examples

Many examples exist within the Reflection documentation, typically within the __construct documentation for each class.

Example #1 Reflection Example from Shell (a Terminal)

$ php --rf strlen
$ php --rc finfo
$ php --re json
$ php --ri dom

The above example will output something similar to:

Function [ <internal:Core> function strlen ] {

  - Parameters [1] {
    Parameter #0 [ <required> $str ]
  }
}

Class [ <internal:fileinfo> class finfo ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [0] {
  }

  - Methods [4] {
    Method [ <internal:fileinfo, ctor> public method finfo ] {

      - Parameters [2] {
        Parameter #0 [ <optional> $options ]
        Parameter #1 [ <optional> $arg ]
      }
    }

    Method [ <internal:fileinfo> public method set_flags ] {

      - Parameters [1] {
        Parameter #0 [ <required> $options ]
      }
    }

    Method [ <internal:fileinfo> public method file ] {

      - Parameters [3] {
        Parameter #0 [ <required> $filename ]
        Parameter #1 [ <optional> $options ]
        Parameter #2 [ <optional> $context ]
      }
    }

    Method [ <internal:fileinfo> public method buffer ] {

      - Parameters [3] {
        Parameter #0 [ <required> $string ]
        Parameter #1 [ <optional> $options ]
        Parameter #2 [ <optional> $context ]
      }
    }
  }
}

Extension [ <persistent> extension #23 json version 1.2.1 ] {

  - Constants [10] {
    Constant [ integer JSON_HEX_TAG ] { 1 }
    Constant [ integer JSON_HEX_AMP ] { 2 }
    Constant [ integer JSON_HEX_APOS ] { 4 }
    Constant [ integer JSON_HEX_QUOT ] { 8 }
    Constant [ integer JSON_FORCE_OBJECT ] { 16 }
    Constant [ integer JSON_ERROR_NONE ] { 0 }
    Constant [ integer JSON_ERROR_DEPTH ] { 1 }
    Constant [ integer JSON_ERROR_STATE_MISMATCH ] { 2 }
    Constant [ integer JSON_ERROR_CTRL_CHAR ] { 3 }
    Constant [ integer JSON_ERROR_SYNTAX ] { 4 }
  }

  - Functions {
    Function [ <internal:json> function json_encode ] {

      - Parameters [2] {
        Parameter #0 [ <required> $value ]
        Parameter #1 [ <optional> $options ]
      }
    }
    Function [ <internal:json> function json_decode ] {

      - Parameters [3] {
        Parameter #0 [ <required> $json ]
        Parameter #1 [ <optional> $assoc ]
        Parameter #2 [ <optional> $depth ]
      }
    }
    Function [ <internal:json> function json_last_error ] {

      - Parameters [0] {
      }
    }
  }
}

dom

DOM/XML => enabled
DOM/XML API Version => 20031129
libxml Version => 2.7.3
HTML Support => enabled
XPath Support => enabled
XPointer Support => enabled
Schema Support => enabled
RelaxNG Support => enabled


Extending

If you want to create specialized versions of the built-in classes (say, for creating colorized HTML when being exported, having easy-access member variables instead of methods or having utility methods), you may go ahead and extend them.

Example #1 Extending the built-in classes

<?php
/**
 * My Reflection_Method class
 */
class My_Reflection_Method extends ReflectionMethod
{
    public $visibility = array();

    public function __construct($o, $m)
    {
        parent::__construct($o, $m);
        $this->visibility = Reflection::getModifierNames($this->getModifiers());
    }
}

/**
 * Demo class #1
 *
 */
class T {
    protected function x() {}
}

/**
 * Demo class #2
 *
 */
class U extends T {
    function x() {}
}

// Print out information
var_dump(new My_Reflection_Method('U', 'x'));
?>

The above example will output something similar to:

object(My_Reflection_Method)#1 (3) {
  ["visibility"]=>
  array(1) {
    [0]=>
    string(6) "public"
  }
  ["name"]=>
  string(1) "x"
  ["class"]=>
  string(1) "U"
}
Caution

If you're overwriting the constructor, remember to call the parent's constructor before any code you insert. Failing to do so will result in the following: Fatal error: Internal error: Failed to retrieve the reflection object


The Reflection class

(PHP 5, PHP 7)

Introduction

The reflection class.

Class synopsis

Reflection {
/* Methods */
public static export ( Reflector $reflector [, bool $return = FALSE ] ) : string
public static getModifierNames ( int $modifiers ) : array
}

Table of Contents

  • Reflection::export — Exports
  • Reflection::getModifierNames — Gets modifier names


Exports

  • « Reflection
  • Reflection::getModifierNames »
  • PHP Manual
  • Reflection
  • Exports

Reflection::export

(PHP 5, PHP 7)

Reflection::export — Exports

Description

public static Reflection::export ( Reflector $reflector [, bool $return = FALSE ] ) : string

Exports a reflection.

Warning

This function is currently not documented; only its argument list is available.

Parameters

reflector

The reflection to export.

return

Setting to TRUE will return the export, as opposed to emitting it. Setting to FALSE (the default) will do the opposite.

Return Values

If the return parameter is set to TRUE, then the export is returned as a string, otherwise NULL is returned.

See Also

  • Reflection::getModifierNames() - Gets modifier names


Gets modifier names

  • « Reflection::export
  • ReflectionClass »
  • PHP Manual
  • Reflection
  • Gets modifier names

Reflection::getModifierNames

(PHP 5, PHP 7)

Reflection::getModifierNames — Gets modifier names

Description

public static Reflection::getModifierNames ( int $modifiers ) : array

Gets modifier names.

Parameters

modifiers

Bitfield of the modifiers to get.

Return Values

An array of modifier names.

Examples

Example #1 Reflection::getModifierNames() example

<?php
class Testing
{
    final public static function foo()
    {
        return;
    }

    public function bar()
    {
        return;
    }
}

$foo = new ReflectionMethod('Testing', 'foo');

echo "Modifiers for method foo():\n";
echo $foo->getModifiers() . "\n";
echo implode(' ', Reflection::getModifierNames($foo->getModifiers())) . "\n";

$bar = new ReflectionMethod('Testing', 'bar');

echo "Modifiers for method bar():\n";
echo $bar->getModifiers() . "\n";
echo implode(' ', Reflection::getModifierNames($bar->getModifiers()));

The above example will output something similar to:

Modifiers for method foo():
261
final public static
Modifiers for method bar():
65792
public

See Also

  • ReflectionClass::getModifiers() - Gets the class modifiers
  • ReflectionClassConstant::getModifiers() - Gets the class constant modifiers
  • ReflectionMethod::getModifiers() - Gets the method modifiers
  • ReflectionProperty::getModifiers() - Gets the property modifiers


The ReflectionClass class

(PHP 5, PHP 7)

Introduction

The ReflectionClass class reports information about a class.

Class synopsis

ReflectionClass implements Reflector {
/* Constants */
const integer IS_IMPLICIT_ABSTRACT = 16 ;
const integer IS_EXPLICIT_ABSTRACT = 32 ;
const integer IS_FINAL = 64 ;
/* Properties */
public $name ;
/* Methods */
public __construct ( mixed $argument )
public static export ( mixed $argument [, bool $return = FALSE ] ) : string
public getConstant ( string $name ) : mixed
public getConstants ( void ) : array
public getConstructor ( void ) : ReflectionMethod
public getDefaultProperties ( void ) : array
public getDocComment ( void ) : string
public getEndLine ( void ) : int
public getExtension ( void ) : ReflectionExtension
public getExtensionName ( void ) : string
public getFileName ( void ) : string
public getInterfaceNames ( void ) : array
public getInterfaces ( void ) : array
public getMethod ( string $name ) : ReflectionMethod
public getMethods ([ int $filter ] ) : array
public getModifiers ( void ) : int
public getName ( void ) : string
public getNamespaceName ( void ) : string
public getParentClass ( void ) : ReflectionClass
public getProperties ([ int $filter ] ) : array
public getProperty ( string $name ) : ReflectionProperty
public getReflectionConstant ( string $name ) : ReflectionClassConstant
public getReflectionConstants ( void ) : array
public getShortName ( void ) : string
public getStartLine ( void ) : int
public getStaticProperties ( void ) : array
public getStaticPropertyValue ( string $name [, mixed &$def_value ] ) : mixed
public getTraitAliases ( void ) : array
public getTraitNames ( void ) : array
public getTraits ( void ) : array
public hasConstant ( string $name ) : bool
public hasMethod ( string $name ) : bool
public hasProperty ( string $name ) : bool
public implementsInterface ( string $interface ) : bool
public inNamespace ( void ) : bool
public isAbstract ( void ) : bool
public isAnonymous ( void ) : bool
public isCloneable ( void ) : bool
public isFinal ( void ) : bool
public isInstance ( object $object ) : bool
public isInstantiable ( void ) : bool
public isInterface ( void ) : bool
public isInternal ( void ) : bool
public isIterable ( void ) : bool
public isSubclassOf ( mixed $class ) : bool
public isTrait ( void ) : bool
public isUserDefined ( void ) : bool
public newInstance ([ mixed $... ] ) : object
public newInstanceArgs ([ array $args ] ) : object
public newInstanceWithoutConstructor ( void ) : object
public setStaticPropertyValue ( string $name , mixed $value ) : void
public __toString ( void ) : string
}

Properties

name

Name of the class. Read-only, throws ReflectionException in attempt to write.

Predefined Constants

ReflectionClass Modifiers

ReflectionClass::IS_IMPLICIT_ABSTRACT

Indicates class that is abstract because it has some abstract methods.

ReflectionClass::IS_EXPLICIT_ABSTRACT

Indicates class that is abstract because of its definition.

ReflectionClass::IS_FINAL

Indicates final class.

Table of Contents

  • ReflectionClass::__construct — Constructs a ReflectionClass
  • ReflectionClass::export — Exports a class
  • ReflectionClass::getConstant — Gets defined constant
  • ReflectionClass::getConstants — Gets constants
  • ReflectionClass::getConstructor — Gets the constructor of the class
  • ReflectionClass::getDefaultProperties — Gets default properties
  • ReflectionClass::getDocComment — Gets doc comments
  • ReflectionClass::getEndLine — Gets end line
  • ReflectionClass::getExtension — Gets a ReflectionExtension object for the extension which defined the class
  • ReflectionClass::getExtensionName — Gets the name of the extension which defined the class
  • ReflectionClass::getFileName — Gets the filename of the file in which the class has been defined
  • ReflectionClass::getInterfaceNames — Gets the interface names
  • ReflectionClass::getInterfaces — Gets the interfaces
  • ReflectionClass::getMethod — Gets a ReflectionMethod for a class method
  • ReflectionClass::getMethods — Gets an array of methods
  • ReflectionClass::getModifiers — Gets the class modifiers
  • ReflectionClass::getName — Gets class name
  • ReflectionClass::getNamespaceName — Gets namespace name
  • ReflectionClass::getParentClass — Gets parent class
  • ReflectionClass::getProperties — Gets properties
  • ReflectionClass::getProperty — Gets a ReflectionProperty for a class's property
  • ReflectionClass::getReflectionConstant — Gets a ReflectionClassConstant for a class's constant
  • ReflectionClass::getReflectionConstants — Gets class constants
  • ReflectionClass::getShortName — Gets short name
  • ReflectionClass::getStartLine — Gets starting line number
  • ReflectionClass::getStaticProperties — Gets static properties
  • ReflectionClass::getStaticPropertyValue — Gets static property value
  • ReflectionClass::getTraitAliases — Returns an array of trait aliases
  • ReflectionClass::getTraitNames — Returns an array of names of traits used by this class
  • ReflectionClass::getTraits — Returns an array of traits used by this class
  • ReflectionClass::hasConstant — Checks if constant is defined
  • ReflectionClass::hasMethod — Checks if method is defined
  • ReflectionClass::hasProperty — Checks if property is defined
  • ReflectionClass::implementsInterface — Implements interface
  • ReflectionClass::inNamespace — Checks if in namespace
  • ReflectionClass::isAbstract — Checks if class is abstract
  • ReflectionClass::isAnonymous — Checks if class is anonymous
  • ReflectionClass::isCloneable — Returns whether this class is cloneable
  • ReflectionClass::isFinal — Checks if class is final
  • ReflectionClass::isInstance — Checks class for instance
  • ReflectionClass::isInstantiable — Checks if the class is instantiable
  • ReflectionClass::isInterface — Checks if the class is an interface
  • ReflectionClass::isInternal — Checks if class is defined internally by an extension, or the core
  • ReflectionClass::isIterable — Check whether this class is iterable
  • ReflectionClass::isIterateable — Alias of ReflectionClass::isIterable
  • ReflectionClass::isSubclassOf — Checks if a subclass
  • ReflectionClass::isTrait — Returns whether this is a trait
  • ReflectionClass::isUserDefined — Checks if user defined
  • ReflectionClass::newInstance — Creates a new class instance from given arguments
  • ReflectionClass::newInstanceArgs — Creates a new class instance from given arguments
  • ReflectionClass::newInstanceWithoutConstructor — Creates a new class instance without invoking the constructor
  • ReflectionClass::setStaticPropertyValue — Sets static property value
  • ReflectionClass::__toString — Returns the string representation of the ReflectionClass object


Constructs a ReflectionClass

  • « ReflectionClass
  • ReflectionClass::export »
  • PHP Manual
  • ReflectionClass
  • Constructs a ReflectionClass

ReflectionClass::__construct

(PHP 5, PHP 7)

ReflectionClass::__construct — Constructs a ReflectionClass

Description

public ReflectionClass::__construct ( mixed $argument )

Constructs a new ReflectionClass object.

Parameters

argument

Either a string containing the name of the class to reflect, or an object.

Return Values

Returns constructed ReflectionClass instance.

Errors/Exceptions

Throws ReflectionException if the class to reflect does not exist.

Examples

Example #1 Basic usage ReflectionClass

<?php
Reflection::export(new ReflectionClass('Exception'));
?>

The above example will output something similar to:

Class [ <internal:Core> class Exception ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [7] {
    Property [ <default> protected $message ]
    Property [ <default> private $string ]
    Property [ <default> protected $code ]
    Property [ <default> protected $file ]
    Property [ <default> protected $line ]
    Property [ <default> private $trace ]
    Property [ <default> private $previous ]
  }

  - Methods [10] {
    Method [ <internal:Core> final private method __clone ] {
    }

    Method [ <internal:Core, ctor> public method __construct ] {

      - Parameters [3] {
        Parameter #0 [ <optional> $message ]
        Parameter #1 [ <optional> $code ]
        Parameter #2 [ <optional> $previous ]
      }
    }

    Method [ <internal:Core> final public method getMessage ] {
    }

    Method [ <internal:Core> final public method getCode ] {
    }

    Method [ <internal:Core> final public method getFile ] {
    }

    Method [ <internal:Core> final public method getLine ] {
    }

    Method [ <internal:Core> final public method getTrace ] {
    }

    Method [ <internal:Core> final public method getPrevious ] {
    }

    Method [ <internal:Core> final public method getTraceAsString ] {
    }

    Method [ <internal:Core> public method __toString ] {
    }
  }
}

See Also

  • ReflectionObject::__construct() - Constructs a ReflectionObject
  • Constructors


Exports a class

  • « ReflectionClass::__construct
  • ReflectionClass::getConstant »
  • PHP Manual
  • ReflectionClass
  • Exports a class

ReflectionClass::export

(PHP 5, PHP 7)

ReflectionClass::export — Exports a class

Description

public static ReflectionClass::export ( mixed $argument [, bool $return = FALSE ] ) : string

Exports a reflected class.

Parameters

argument

The reflection to export.

return

Setting to TRUE will return the export, as opposed to emitting it. Setting to FALSE (the default) will do the opposite.

Return Values

If the return parameter is set to TRUE, then the export is returned as a string, otherwise NULL is returned.

Examples

Example #1 Basic usage of ReflectionClass::export()

<?php
class Apple {
    public $var1;
    public $var2 = 'Orange';

    public function type() {
        return 'Apple';
    }
}
ReflectionClass::export('Apple');
?>

The above example will output something similar to:

Class [ <user> class Apple ] {
  @@ php shell code 1-8

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [2] {
    Property [ <default> public $var1 ]
    Property [ <default> public $var2 ]
  }

  - Methods [1] {
    Method [ <user> public method type ] {
      @@ php shell code 5 - 7
    }
  }
}

See Also

  • ReflectionClass::getName() - Gets class name


Gets defined constant

  • « ReflectionClass::export
  • ReflectionClass::getConstants »
  • PHP Manual
  • ReflectionClass
  • Gets defined constant

ReflectionClass::getConstant

(PHP 5, PHP 7)

ReflectionClass::getConstant — Gets defined constant

Description

public ReflectionClass::getConstant ( string $name ) : mixed

Gets the defined constant.

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

The name of the class constant to get.

Return Values

Value of the constant with the name name. Returns FALSE if the constant was not found in the class.

Examples

Example #1 Usage of ReflectionClass::getConstant()

<?php

class Example {
    const C1 = false;
    const C2 = 'I am a constant';
}

$reflection = new ReflectionClass('Example');

var_dump($reflection->getConstant('C1'));
var_dump($reflection->getConstant('C2'));
var_dump($reflection->getConstant('C3'));
?>

The above example will output:

bool(false)
string(15) "I am a constant"
bool(false)

See Also

  • ReflectionClass::getConstants() - Gets constants


Gets constants

  • « ReflectionClass::getConstant
  • ReflectionClass::getConstructor »
  • PHP Manual
  • ReflectionClass
  • Gets constants

ReflectionClass::getConstants

(PHP 5, PHP 7)

ReflectionClass::getConstants — Gets constants

Description

public ReflectionClass::getConstants ( void ) : array

Gets all defined constants from a class, regardless of their visibility.

Parameters

This function has no parameters.

Return Values

An array of constants, where the keys hold the name and the values the value of the constants.

See Also

  • ReflectionClass::getConstant() - Gets defined constant


Gets the constructor of the class

  • « ReflectionClass::getConstants
  • ReflectionClass::getDefaultProperties »
  • PHP Manual
  • ReflectionClass
  • Gets the constructor of the class

ReflectionClass::getConstructor

(PHP 5, PHP 7)

ReflectionClass::getConstructor — Gets the constructor of the class

Description

public ReflectionClass::getConstructor ( void ) : ReflectionMethod

Gets the constructor of the reflected class.

Parameters

This function has no parameters.

Return Values

A ReflectionMethod object reflecting the class' constructor, or NULL if the class has no constructor.

Examples

Example #1 Basic usage of ReflectionClass::getConstructor()

<?php
$class = new ReflectionClass('ReflectionClass');
$constructor = $class->getConstructor();
var_dump($constructor);
?>

The above example will output:

object(ReflectionMethod)#2 (2) {
  ["name"]=>
  string(11) "__construct"
  ["class"]=>
  string(15) "ReflectionClass"
}

See Also

  • ReflectionClass::getName() - Gets class name


Gets default properties

  • « ReflectionClass::getConstructor
  • ReflectionClass::getDocComment »
  • PHP Manual
  • ReflectionClass
  • Gets default properties

ReflectionClass::getDefaultProperties

(PHP 5, PHP 7)

ReflectionClass::getDefaultProperties — Gets default properties

Description

public ReflectionClass::getDefaultProperties ( void ) : array

Gets default properties from a class (including inherited properties).

Note:

This method only works for static properties when used on internal classes. The default value of a static class property can not be tracked when using this method on user defined classes.

Parameters

This function has no parameters.

Return Values

An array of default properties, with the key being the name of the property and the value being the default value of the property or NULL if the property doesn't have a default value. The function does not distinguish between static and non static properties and does not take visibility modifiers into account.

Examples

Example #1 ReflectionClass::getDefaultProperties() example

<?php
class Bar {
    protected $inheritedProperty = 'inheritedDefault';
}

class Foo extends Bar {
    public $property = 'propertyDefault';
    private $privateProperty = 'privatePropertyDefault';
    public static $staticProperty = 'staticProperty';
    public $defaultlessProperty;
}

$reflectionClass = new ReflectionClass('Foo');
var_dump($reflectionClass->getDefaultProperties());
?>

The above example will output:

array(5) {
   ["staticProperty"]=>
   string(14) "staticProperty"
   ["property"]=>
   string(15) "propertyDefault"
   ["privateProperty"]=>
   string(22) "privatePropertyDefault"
   ["defaultlessProperty"]=>
   NULL
   ["inheritedProperty"]=>
   string(16) "inheritedDefault"
}

See Also

  • ReflectionClass::getProperties() - Gets properties
  • ReflectionClass::getStaticProperties() - Gets static properties
  • ReflectionClass::getProperty() - Gets a ReflectionProperty for a class's property


Gets doc comments

  • « ReflectionClass::getDefaultProperties
  • ReflectionClass::getEndLine »
  • PHP Manual
  • ReflectionClass
  • Gets doc comments

ReflectionClass::getDocComment

(PHP 5, PHP 7)

ReflectionClass::getDocComment — Gets doc comments

Description

public ReflectionClass::getDocComment ( void ) : string

Gets doc comments from a class. Doc comments start with /**. If there are multiple doc comments above the class definition, the one closest to the class will be taken.

Parameters

This function has no parameters.

Return Values

The doc comment if it exists, otherwise FALSE

Examples

Example #1 ReflectionClass::getDocComment() example

<?php
/**
* A test class
*
* @param  foo bar
* @return baz
*/
class TestClass { }

$rc = new ReflectionClass('TestClass');
var_dump($rc->getDocComment())
?>

The above example will output:

string(55) "/**
* A test class
*
* @param  foo bar
* @return baz
*/"

See Also

  • ReflectionClass::getName() - Gets class name


Gets end line

  • « ReflectionClass::getDocComment
  • ReflectionClass::getExtension »
  • PHP Manual
  • ReflectionClass
  • Gets end line

ReflectionClass::getEndLine

(PHP 5, PHP 7)

ReflectionClass::getEndLine — Gets end line

Description

public ReflectionClass::getEndLine ( void ) : int

Gets end line number from a user-defined class definition.

Parameters

This function has no parameters.

Return Values

The ending line number of the user defined class, or FALSE if unknown.

Examples

Example #1 ReflectionClass::getEndLine() example

<?php
// Test Class
class TestClass { }

$rc = new ReflectionClass('TestClass');

echo $rc->getEndLine();
?>

The above example will output:

3

See Also

  • ReflectionClass::getStartLine() - Gets starting line number


Gets a ReflectionExtension object for the extension which defined the class

  • « ReflectionClass::getEndLine
  • ReflectionClass::getExtensionName »
  • PHP Manual
  • ReflectionClass
  • Gets a ReflectionExtension object for the extension which defined the class

ReflectionClass::getExtension

(PHP 5, PHP 7)

ReflectionClass::getExtension — Gets a ReflectionExtension object for the extension which defined the class

Description

public ReflectionClass::getExtension ( void ) : ReflectionExtension

Gets a ReflectionExtension object for the extension which defined the class.

Parameters

This function has no parameters.

Return Values

A ReflectionExtension object representing the extension which defined the class, or NULL for user-defined classes.

Examples

Example #1 Basic usage of ReflectionClass::getExtension()

<?php
$class = new ReflectionClass('ReflectionClass');
$extension = $class->getExtension();
var_dump($extension);
?>

The above example will output:

object(ReflectionExtension)#2 (1) {
  ["name"]=>
  string(10) "Reflection"
}

See Also

  • ReflectionClass::getExtensionName() - Gets the name of the extension which defined the class


Gets the name of the extension which defined the class

  • « ReflectionClass::getExtension
  • ReflectionClass::getFileName »
  • PHP Manual
  • ReflectionClass
  • Gets the name of the extension which defined the class

ReflectionClass::getExtensionName

(PHP 5, PHP 7)

ReflectionClass::getExtensionName — Gets the name of the extension which defined the class

Description

public ReflectionClass::getExtensionName ( void ) : string

Gets the name of the extension which defined the class.

Parameters

This function has no parameters.

Return Values

The name of the extension which defined the class, or FALSE for user-defined classes.

Examples

Example #1 Basic usage of ReflectionClass::getExtensionName()

<?php
$class = new ReflectionClass('ReflectionClass');
$extension = $class->getExtensionName();
var_dump($extension);
?>

The above example will output:

string(10) "Reflection"

See Also

  • ReflectionClass::getExtension() - Gets a ReflectionExtension object for the extension which defined the class


Gets the filename of the file in which the class has been defined

  • « ReflectionClass::getExtensionName
  • ReflectionClass::getInterfaceNames »
  • PHP Manual
  • ReflectionClass
  • Gets the filename of the file in which the class has been defined

ReflectionClass::getFileName

(PHP 5, PHP 7)

ReflectionClass::getFileName — Gets the filename of the file in which the class has been defined

Description

public ReflectionClass::getFileName ( void ) : string

Gets the filename of the file in which the class has been defined.

Parameters

This function has no parameters.

Return Values

Returns the filename of the file in which the class has been defined. If the class is defined in the PHP core or in a PHP extension, FALSE is returned.

See Also

  • ReflectionClass::getExtensionName() - Gets the name of the extension which defined the class


Gets the interface names

  • « ReflectionClass::getFileName
  • ReflectionClass::getInterfaces »
  • PHP Manual
  • ReflectionClass
  • Gets the interface names

ReflectionClass::getInterfaceNames

(PHP 5 >= 5.2.0, PHP 7)

ReflectionClass::getInterfaceNames — Gets the interface names

Description

public ReflectionClass::getInterfaceNames ( void ) : array

Get the interface names.

Parameters

This function has no parameters.

Return Values

A numerical array with interface names as the values.

Examples

Example #1 ReflectionClass::getInterfaceNames() example

<?php
interface Foo { }

interface Bar { }

class Baz implements Foo, Bar { }

$rc1 = new ReflectionClass("Baz");

print_r($rc1->getInterfaceNames());
?>

The above example will output something similar to:

Array
(
    [0] => Foo
    [1] => Bar
)

See Also

  • ReflectionClass::getInterfaces() - Gets the interfaces


Gets the interfaces

  • « ReflectionClass::getInterfaceNames
  • ReflectionClass::getMethod »
  • PHP Manual
  • ReflectionClass
  • Gets the interfaces

ReflectionClass::getInterfaces

(PHP 5, PHP 7)

ReflectionClass::getInterfaces — Gets the interfaces

Description

public ReflectionClass::getInterfaces ( void ) : array

Gets the interfaces.

Parameters

This function has no parameters.

Return Values

An associative array of interfaces, with keys as interface names and the array values as ReflectionClass objects.

Examples

Example #1 ReflectionClass::getInterfaces() example

<?php
interface Foo { }

interface Bar { }

class Baz implements Foo, Bar { }

$rc1 = new ReflectionClass("Baz");

print_r($rc1->getInterfaces());
?>

The above example will output something similar to:

Array
(
    [Foo] => ReflectionClass Object
        (
            [name] => Foo
        )

    [Bar] => ReflectionClass Object
        (
            [name] => Bar
        )

)

See Also

  • ReflectionClass::getInterfaceNames() - Gets the interface names


Gets a ReflectionMethod for a class method

  • « ReflectionClass::getInterfaces
  • ReflectionClass::getMethods »
  • PHP Manual
  • ReflectionClass
  • Gets a ReflectionMethod for a class method

ReflectionClass::getMethod

(PHP 5, PHP 7)

ReflectionClass::getMethod — Gets a ReflectionMethod for a class method

Description

public ReflectionClass::getMethod ( string $name ) : ReflectionMethod

Gets a ReflectionMethod for a class method.

Parameters

name

The method name to reflect.

Return Values

A ReflectionMethod.

Errors/Exceptions

A ReflectionException if the method does not exist.

Examples

Example #1 Basic usage of ReflectionClass::getMethod()

<?php
$class = new ReflectionClass('ReflectionClass');
$method = $class->getMethod('getMethod');
var_dump($method);
?>

The above example will output:

object(ReflectionMethod)#2 (2) {
  ["name"]=>
  string(9) "getMethod"
  ["class"]=>
  string(15) "ReflectionClass"
}

See Also

  • ReflectionClass::getMethods() - Gets an array of methods


Gets an array of methods

  • « ReflectionClass::getMethod
  • ReflectionClass::getModifiers »
  • PHP Manual
  • ReflectionClass
  • Gets an array of methods

ReflectionClass::getMethods

(PHP 5, PHP 7)

ReflectionClass::getMethods — Gets an array of methods

Description

public ReflectionClass::getMethods ([ int $filter ] ) : array

Gets an array of methods for the class.

Parameters

filter

Filter the results to include only methods with certain attributes. Defaults to no filtering.

Any bitwise disjunction of ReflectionMethod::IS_STATIC,
ReflectionMethod::IS_PUBLIC,
ReflectionMethod::IS_PROTECTED,
ReflectionMethod::IS_PRIVATE,
ReflectionMethod::IS_ABSTRACT,
ReflectionMethod::IS_FINAL,
so that all methods with any of the given
attributes will be returned.

Note: Note that other bitwise operations, for instance ~ will not work as expected. In other words, it is not possible to retrieve all non-static methods, for example.

Return Values

An array of ReflectionMethod objects reflecting each method.

Examples

Example #1 Basic usage of ReflectionClass::getMethods()

<?php
class Apple {
    public function firstMethod() { }
    final protected function secondMethod() { }
    private static function thirdMethod() { }
}

$class = new ReflectionClass('Apple');
$methods = $class->getMethods();
var_dump($methods);
?>

The above example will output:

array(3) {
  [0]=>
  &object(ReflectionMethod)#2 (2) {
    ["name"]=>
    string(11) "firstMethod"
    ["class"]=>
    string(5) "Apple"
  }
  [1]=>
  &object(ReflectionMethod)#3 (2) {
    ["name"]=>
    string(12) "secondMethod"
    ["class"]=>
    string(5) "Apple"
  }
  [2]=>
  &object(ReflectionMethod)#4 (2) {
    ["name"]=>
    string(11) "thirdMethod"
    ["class"]=>
    string(5) "Apple"
  }
}

Example #2 Filtering results from ReflectionClass::getMethods()

<?php
class Apple {
    public function firstMethod() { }
    final protected function secondMethod() { }
    private static function thirdMethod() { }
}

$class = new ReflectionClass('Apple');
$methods = $class->getMethods(ReflectionMethod::IS_STATIC | ReflectionMethod::IS_FINAL);
var_dump($methods);
?>

The above example will output:

array(2) {
  [0]=>
  &object(ReflectionMethod)#2 (2) {
    ["name"]=>
    string(12) "secondMethod"
    ["class"]=>
    string(5) "Apple"
  }
  [1]=>
  &object(ReflectionMethod)#3 (2) {
    ["name"]=>
    string(11) "thirdMethod"
    ["class"]=>
    string(5) "Apple"
  }
}

See Also

  • ReflectionClass::getMethod() - Gets a ReflectionMethod for a class method
  • get_class_methods() - Gets the class methods' names


Gets the class modifiers

  • « ReflectionClass::getMethods
  • ReflectionClass::getName »
  • PHP Manual
  • ReflectionClass
  • Gets the class modifiers

ReflectionClass::getModifiers

(PHP 5, PHP 7)

ReflectionClass::getModifiers — Gets the class modifiers

Description

public ReflectionClass::getModifiers ( void ) : int

Returns a bitfield of the access modifiers for this class.

Parameters

This function has no parameters.

Return Values

Returns bitmask of modifier constants.

See Also

  • ReflectionClass::getProperties() - Gets properties
  • Reflection::getModifierNames() - Gets modifier names


Gets class name

  • « ReflectionClass::getModifiers
  • ReflectionClass::getNamespaceName »
  • PHP Manual
  • ReflectionClass
  • Gets class name

ReflectionClass::getName

(PHP 5, PHP 7)

ReflectionClass::getName — Gets class name

Description

public ReflectionClass::getName ( void ) : string

Gets the class name.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The class name.

Examples

Example #1 ReflectionClass::getName() example

<?php
namespace A\B;

class Foo { }

$function = new \ReflectionClass('stdClass');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());

$function = new \ReflectionClass('A\\B\\Foo');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());
?>

The above example will output:

bool(false)
string(8) "stdClass"
string(0) ""
string(8) "stdClass"

bool(true)
string(7) "A\B\Foo"
string(3) "A\B"
string(3) "Foo"

See Also

  • ReflectionClass::getNamespaceName() - Gets namespace name


Gets namespace name

  • « ReflectionClass::getName
  • ReflectionClass::getParentClass »
  • PHP Manual
  • ReflectionClass
  • Gets namespace name

ReflectionClass::getNamespaceName

(PHP 5 >= 5.3.0, PHP 7)

ReflectionClass::getNamespaceName — Gets namespace name

Description

public ReflectionClass::getNamespaceName ( void ) : string

Gets the namespace name.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The namespace name.

Examples

Example #1 ReflectionClass::getNamespaceName() example

<?php
namespace A\B;

class Foo { }

$class = new \ReflectionClass('stdClass');

var_dump($class->inNamespace());
var_dump($class->getName());
var_dump($class->getNamespaceName());
var_dump($class->getShortName());

$class = new \ReflectionClass('A\\B\\Foo');

var_dump($class->inNamespace());
var_dump($class->getName());
var_dump($class->getNamespaceName());
var_dump($class->getShortName());
?>

The above example will output:

bool(false)
string(8) "stdClass"
string(0) ""
string(8) "stdClass"

bool(true)
string(7) "A\B\Foo"
string(3) "A\B"
string(3) "Foo"

See Also

  • ReflectionClass::getParentClass() - Gets parent class
  • namespaces


Gets parent class

  • « ReflectionClass::getNamespaceName
  • ReflectionClass::getProperties »
  • PHP Manual
  • ReflectionClass
  • Gets parent class

ReflectionClass::getParentClass

(PHP 5, PHP 7)

ReflectionClass::getParentClass — Gets parent class

Description

public ReflectionClass::getParentClass ( void ) : ReflectionClass

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

A ReflectionClass or FALSE if there's no parent.

See Also

  • ReflectionClass::__construct() - Constructs a ReflectionClass


Gets properties

  • « ReflectionClass::getParentClass
  • ReflectionClass::getProperty »
  • PHP Manual
  • ReflectionClass
  • Gets properties

ReflectionClass::getProperties

(PHP 5, PHP 7)

ReflectionClass::getProperties — Gets properties

Description

public ReflectionClass::getProperties ([ int $filter ] ) : array

Retrieves reflected properties.

Parameters

filter

The optional filter, for filtering desired property types. It's configured using the ReflectionProperty constants, and defaults to all property types.

Return Values

An array of ReflectionProperty objects.

Examples

Example #1 ReflectionClass::getProperties() filtering example

This example demonstrates usage of the optional filter parameter, where it essentially skips private properties.

<?php
class Foo {
    public    $foo  = 1;
    protected $bar  = 2;
    private   $baz  = 3;
}

$foo = new Foo();

$reflect = new ReflectionClass($foo);
$props   = $reflect->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED);

foreach ($props as $prop) {
    print $prop->getName() . "\n";
}

var_dump($props);

?>

The above example will output something similar to:

foo
bar
array(2) {
  [0]=>
  object(ReflectionProperty)#3 (2) {
    ["name"]=>
    string(3) "foo"
    ["class"]=>
    string(3) "Foo"
  }
  [1]=>
  object(ReflectionProperty)#4 (2) {
    ["name"]=>
    string(3) "bar"
    ["class"]=>
    string(3) "Foo"
  }
}

See Also

  • ReflectionClass::getProperty() - Gets a ReflectionProperty for a class's property
  • ReflectionProperty
  • ReflectionProperty modifier constants


Gets a ReflectionProperty for a class's property

  • « ReflectionClass::getProperties
  • ReflectionClass::getReflectionConstant »
  • PHP Manual
  • ReflectionClass
  • Gets a ReflectionProperty for a class's property

ReflectionClass::getProperty

(PHP 5, PHP 7)

ReflectionClass::getProperty — Gets a ReflectionProperty for a class's property

Description

public ReflectionClass::getProperty ( string $name ) : ReflectionProperty

Gets a ReflectionProperty for a class's property.

Parameters

name

The property name.

Return Values

A ReflectionProperty.

Examples

Example #1 Basic usage of ReflectionClass::getProperty()

<?php
$class = new ReflectionClass('ReflectionClass');
$property = $class->getProperty('name');
var_dump($property);
?>

The above example will output:

object(ReflectionProperty)#2 (2) {
  ["name"]=>
  string(4) "name"
  ["class"]=>
  string(15) "ReflectionClass"
}

See Also

  • ReflectionClass::getProperties() - Gets properties


Gets a ReflectionClassConstant for a class's constant

  • « ReflectionClass::getProperty
  • ReflectionClass::getReflectionConstants »
  • PHP Manual
  • ReflectionClass
  • Gets a ReflectionClassConstant for a class's constant

ReflectionClass::getReflectionConstant

(PHP 7 >= 7.1.0)

ReflectionClass::getReflectionConstant — Gets a ReflectionClassConstant for a class's constant

Description

public ReflectionClass::getReflectionConstant ( string $name ) : ReflectionClassConstant

Gets a ReflectionClassConstant for a class's property.

Parameters

name

The class constant name.

Return Values

A ReflectionClassConstant.

See Also

  • ReflectionClass::getReflectionConstants() - Gets class constants
  • ReflectionClassConstant


Gets class constants

  • « ReflectionClass::getReflectionConstant
  • ReflectionClass::getShortName »
  • PHP Manual
  • ReflectionClass
  • Gets class constants

ReflectionClass::getReflectionConstants

(PHP 7 >= 7.1.0)

ReflectionClass::getReflectionConstants — Gets class constants

Description

public ReflectionClass::getReflectionConstants ( void ) : array

Retrieves reflected constants.

Parameters

This function has no parameters.

Return Values

An array of ReflectionClassConstant objects.

Examples

Example #1 Basic ReflectionClass::getReflectionConstants() example

<?php
class Foo {
    public    const FOO  = 1;
    protected const BAR  = 2;
    private   const BAZ  = 3;
}

$foo = new Foo();

$reflect = new ReflectionClass($foo);
$consts  = $reflect->getReflectionConstants();

foreach ($consts as $const) {
    print $const->getName() . "\n";
}

var_dump($consts);

?>

The above example will output something similar to:

FOO
BAR
BAZ
array(3) {
  [0]=>
  object(ReflectionClassConstant)#3 (2) {
    ["name"]=>
    string(3) "FOO"
    ["class"]=>
    string(3) "Foo"
  }
  [1]=>
  object(ReflectionClassConstant)#4 (2) {
    ["name"]=>
    string(3) "BAR"
    ["class"]=>
    string(3) "Foo"
  }
  [2]=>
  object(ReflectionClassConstant)#5 (2) {
    ["name"]=>
    string(3) "BAZ"
    ["class"]=>
    string(3) "Foo"
  }
}

See Also

  • ReflectionClass::getReflectionConstant() - Gets a ReflectionClassConstant for a class's constant
  • ReflectionClassConstant


Gets short name

  • « ReflectionClass::getReflectionConstants
  • ReflectionClass::getStartLine »
  • PHP Manual
  • ReflectionClass
  • Gets short name

ReflectionClass::getShortName

(PHP 5 >= 5.3.0, PHP 7)

ReflectionClass::getShortName — Gets short name

Description

public ReflectionClass::getShortName ( void ) : string

Gets the short name of the class, the part without the namespace.

Parameters

This function has no parameters.

Return Values

The class short name.

Examples

Example #1 ReflectionClass::getShortName() example

<?php
namespace A\B;

class Foo { }

$function = new \ReflectionClass('stdClass');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());

$function = new \ReflectionClass('A\\B\\Foo');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());
?>

The above example will output:

bool(false)
string(8) "stdClass"
string(0) ""
string(8) "stdClass"

bool(true)
string(7) "A\B\Foo"
string(3) "A\B"
string(3) "Foo"

See Also

  • ReflectionClass::getName() - Gets class name


Gets starting line number

  • « ReflectionClass::getShortName
  • ReflectionClass::getStaticProperties »
  • PHP Manual
  • ReflectionClass
  • Gets starting line number

ReflectionClass::getStartLine

(PHP 5, PHP 7)

ReflectionClass::getStartLine — Gets starting line number

Description

public ReflectionClass::getStartLine ( void ) : int

Get the starting line number.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The starting line number, as an integer.

See Also

  • ReflectionClass::getEndLine() - Gets end line


Gets static properties

  • « ReflectionClass::getStartLine
  • ReflectionClass::getStaticPropertyValue »
  • PHP Manual
  • ReflectionClass
  • Gets static properties

ReflectionClass::getStaticProperties

(PHP 5, PHP 7)

ReflectionClass::getStaticProperties — Gets static properties

Description

public ReflectionClass::getStaticProperties ( void ) : array

Get the static properties.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The static properties, as an array.

See Also

  • ReflectionClass::getStaticPropertyValue() - Gets static property value
  • ReflectionClass::setStaticPropertyValue() - Sets static property value


Gets static property value

  • « ReflectionClass::getStaticProperties
  • ReflectionClass::getTraitAliases »
  • PHP Manual
  • ReflectionClass
  • Gets static property value

ReflectionClass::getStaticPropertyValue

(PHP 5 >= 5.1.2, PHP 7)

ReflectionClass::getStaticPropertyValue — Gets static property value

Description

public ReflectionClass::getStaticPropertyValue ( string $name [, mixed &$def_value ] ) : mixed

Gets the value of a static property on this class.

Parameters

name

The name of the static property for which to return a value.

def_value

A default value to return in case the class does not declare a static property with the given name. If the property does not exist and this argument is omitted, a ReflectionException is thrown.

Return Values

The value of the static property.

Examples

Example #1 Basic usage of ReflectionClass::getStaticPropertyValue()

<?php
class Apple {
    public static $color = 'Red';
}

$class = new ReflectionClass('Apple');
var_dump($class->getStaticPropertyValue('color'));
?>

The above example will output:

string(3) "Red"

See Also

  • ReflectionClass::getStaticProperties() - Gets static properties
  • ReflectionClass::setStaticPropertyValue() - Sets static property value


Returns an array of trait aliases

  • « ReflectionClass::getStaticPropertyValue
  • ReflectionClass::getTraitNames »
  • PHP Manual
  • ReflectionClass
  • Returns an array of trait aliases

ReflectionClass::getTraitAliases

(PHP 5 >= 5.4.0, PHP 7)

ReflectionClass::getTraitAliases — Returns an array of trait aliases

Description

public ReflectionClass::getTraitAliases ( void ) : array

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 new method names in keys and original names (in the format "TraitName::original") in values. Returns NULL in case of an error.


Returns an array of names of traits used by this class

  • « ReflectionClass::getTraitAliases
  • ReflectionClass::getTraits »
  • PHP Manual
  • ReflectionClass
  • Returns an array of names of traits used by this class

ReflectionClass::getTraitNames

(PHP 5 >= 5.4.0, PHP 7)

ReflectionClass::getTraitNames — Returns an array of names of traits used by this class

Description

public ReflectionClass::getTraitNames ( void ) : array

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 trait names in values. Returns NULL in case of an error.


Returns an array of traits used by this class

  • « ReflectionClass::getTraitNames
  • ReflectionClass::hasConstant »
  • PHP Manual
  • ReflectionClass
  • Returns an array of traits used by this class

ReflectionClass::getTraits

(PHP 5 >= 5.4.0, PHP 7)

ReflectionClass::getTraits — Returns an array of traits used by this class

Description

public ReflectionClass::getTraits ( void ) : array

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 trait names in keys and instances of trait's ReflectionClass in values. Returns NULL in case of an error.


Checks if constant is defined

  • « ReflectionClass::getTraits
  • ReflectionClass::hasMethod »
  • PHP Manual
  • ReflectionClass
  • Checks if constant is defined

ReflectionClass::hasConstant

(PHP 5 >= 5.1.2, PHP 7)

ReflectionClass::hasConstant — Checks if constant is defined

Description

public ReflectionClass::hasConstant ( string $name ) : bool

Checks whether the class has a specific constant defined or not.

Parameters

name

The name of the constant being checked for.

Return Values

TRUE if the constant is defined, otherwise FALSE.

Examples

Example #1 ReflectionClass::hasConstant() example

<?php
class Foo {
    const c1 = 1;
}

$class = new ReflectionClass("Foo");

var_dump($class->hasConstant("c1"));
var_dump($class->hasConstant("c2"));
?>

The above example will output something similar to:

bool(true)
bool(false)

See Also

  • ReflectionClass::hasMethod() - Checks if method is defined
  • ReflectionClass::hasProperty() - Checks if property is defined


Checks if method is defined

  • « ReflectionClass::hasConstant
  • ReflectionClass::hasProperty »
  • PHP Manual
  • ReflectionClass
  • Checks if method is defined

ReflectionClass::hasMethod

(PHP 5 >= 5.1.2, PHP 7)

ReflectionClass::hasMethod — Checks if method is defined

Description

public ReflectionClass::hasMethod ( string $name ) : bool

Checks whether a specific method is defined in a class.

Parameters

name

Name of the method being checked for.

Return Values

TRUE if it has the method, otherwise FALSE

Examples

Example #1 ReflectionClass::hasMethod() example

<?php
Class C {
    public function publicFoo() {
        return true;
    }

    protected function protectedFoo() {
        return true;
    }

    private function privateFoo() {
        return true;
    }

    static function staticFoo() {
        return true;
    }
}

$rc = new ReflectionClass("C");

var_dump($rc->hasMethod('publicFoo'));

var_dump($rc->hasMethod('protectedFoo'));

var_dump($rc->hasMethod('privateFoo'));

var_dump($rc->hasMethod('staticFoo'));

// C should not have method bar
var_dump($rc->hasMethod('bar'));

// Method names are case insensitive
var_dump($rc->hasMethod('PUBLICfOO'));
?>

The above example will output:

bool(true)
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)

See Also

  • ReflectionClass::hasConstant() - Checks if constant is defined
  • ReflectionClass::hasProperty() - Checks if property is defined


Checks if property is defined

  • « ReflectionClass::hasMethod
  • ReflectionClass::implementsInterface »
  • PHP Manual
  • ReflectionClass
  • Checks if property is defined

ReflectionClass::hasProperty

(PHP 5 >= 5.1.2, PHP 7)

ReflectionClass::hasProperty — Checks if property is defined

Description

public ReflectionClass::hasProperty ( string $name ) : bool

Checks whether the specified property is defined.

Parameters

name

Name of the property being checked for.

Return Values

TRUE if it has the property, otherwise FALSE

Examples

Example #1 ReflectionClass::hasProperty() example

<?php
class Foo {
    public    $p1;
    protected $p2;
    private   $p3;

}

$obj = new ReflectionObject(new Foo());

var_dump($obj->hasProperty("p1"));
var_dump($obj->hasProperty("p2"));
var_dump($obj->hasProperty("p3"));
var_dump($obj->hasProperty("p4"));
?>

The above example will output something similar to:

bool(true)
bool(true)
bool(true)
bool(false)

See Also

  • ReflectionClass::hasConstant() - Checks if constant is defined
  • ReflectionClass::hasMethod() - Checks if method is defined


Implements interface

  • « ReflectionClass::hasProperty
  • ReflectionClass::inNamespace »
  • PHP Manual
  • ReflectionClass
  • Implements interface

ReflectionClass::implementsInterface

(PHP 5, PHP 7)

ReflectionClass::implementsInterface — Implements interface

Description

public ReflectionClass::implementsInterface ( string $interface ) : bool

Checks whether it implements an interface.

Parameters

interface

The interface name.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ReflectionClass::isInterface() - Checks if the class is an interface
  • ReflectionClass::isSubclassOf() - Checks if a subclass
  • interface_exists() - Checks if the interface has been defined
  • Object Interfaces


Checks if in namespace

  • « ReflectionClass::implementsInterface
  • ReflectionClass::isAbstract »
  • PHP Manual
  • ReflectionClass
  • Checks if in namespace

ReflectionClass::inNamespace

(PHP 5 >= 5.3.0, PHP 7)

ReflectionClass::inNamespace — Checks if in namespace

Description

public ReflectionClass::inNamespace ( void ) : bool

Checks if this class is defined in a namespace.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ReflectionClass::inNamespace() example

<?php
namespace A\B;

class Foo { }

$function = new \ReflectionClass('stdClass');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());

$function = new \ReflectionClass('A\\B\\Foo');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());
?>

The above example will output:

bool(false)
string(8) "stdClass"
string(0) ""
string(8) "stdClass"

bool(true)
string(7) "A\B\Foo"
string(3) "A\B"
string(3) "Foo"

See Also

  • ReflectionClass::getNamespaceName() - Gets namespace name
  • PHP Namespaces


Checks if class is abstract

  • « ReflectionClass::inNamespace
  • ReflectionClass::isAnonymous »
  • PHP Manual
  • ReflectionClass
  • Checks if class is abstract

ReflectionClass::isAbstract

(PHP 5, PHP 7)

ReflectionClass::isAbstract — Checks if class is abstract

Description

public ReflectionClass::isAbstract ( void ) : bool

Checks if the class is abstract.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ReflectionClass::isAbstract() example

<?php
class          TestClass { }
abstract class TestAbstractClass { }

$testClass     = new ReflectionClass('TestClass');
$abstractClass = new ReflectionClass('TestAbstractClass');

var_dump($testClass->isAbstract());
var_dump($abstractClass->isAbstract());
?>

The above example will output:

bool(false)
bool(true)

See Also

  • ReflectionClass::isInterface() - Checks if the class is an interface
  • Class Abstraction


Checks if class is anonymous

  • « ReflectionClass::isAbstract
  • ReflectionClass::isCloneable »
  • PHP Manual
  • ReflectionClass
  • Checks if class is anonymous

ReflectionClass::isAnonymous

(PHP 7)

ReflectionClass::isAnonymous — Checks if class is anonymous

Description

public ReflectionClass::isAnonymous ( void ) : bool

Checks if a class is an anonymous class.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ReflectionClass::isAnonymous() example

<?php
class TestClass {}
$anonClass = new class {};

$normalClass = new ReflectionClass('TestClass');
$anonClass  = new ReflectionClass($anonClass);

var_dump($normalClass->isAnonymous());
var_dump($anonClass->isAnonymous());

?>

The above example will output:

bool(false)
bool(true)

See Also

  • ReflectionClass::isFinal() - Checks if class is final


Returns whether this class is cloneable

  • « ReflectionClass::isAnonymous
  • ReflectionClass::isFinal »
  • PHP Manual
  • ReflectionClass
  • Returns whether this class is cloneable

ReflectionClass::isCloneable

(PHP 5 >= 5.4.0, PHP 7)

ReflectionClass::isCloneable — Returns whether this class is cloneable

Description

public ReflectionClass::isCloneable ( void ) : bool

Returns whether this class is cloneable.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the class is cloneable, FALSE otherwise.

Examples

Example #1 Basic usage of ReflectionClass::isCloneable()

<?php
class NotCloneable {
    public $var1;

    private function __clone() {
    }
}

class Cloneable {
    public $var1;
}

$notCloneable = new ReflectionClass('NotCloneable');
$cloneable = new ReflectionClass('Cloneable');

var_dump($notCloneable->isCloneable());
var_dump($cloneable->isCloneable());
?>

The above example will output:

bool(false)
bool(true)


Checks if class is final

  • « ReflectionClass::isCloneable
  • ReflectionClass::isInstance »
  • PHP Manual
  • ReflectionClass
  • Checks if class is final

ReflectionClass::isFinal

(PHP 5, PHP 7)

ReflectionClass::isFinal — Checks if class is final

Description

public ReflectionClass::isFinal ( void ) : bool

Checks if a class is final.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ReflectionClass::isFinal() example

<?php
class       TestClass { }
final class TestFinalClass { }

$normalClass = new ReflectionClass('TestClass');
$finalClass  = new ReflectionClass('TestFinalClass');

var_dump($normalClass->isFinal());
var_dump($finalClass->isFinal());

?>

The above example will output:

bool(false)
bool(true)

See Also

  • ReflectionClass::isAbstract() - Checks if class is abstract
  • Final Keyword


Checks class for instance

  • « ReflectionClass::isFinal
  • ReflectionClass::isInstantiable »
  • PHP Manual
  • ReflectionClass
  • Checks class for instance

ReflectionClass::isInstance

(PHP 5, PHP 7)

ReflectionClass::isInstance — Checks class for instance

Description

public ReflectionClass::isInstance ( object $object ) : bool

Checks if an object is an instance of a class.

Parameters

object

The object being compared to.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ReflectionClass::isInstance() related examples

<?php
// Example usage
$class = new ReflectionClass('Foo');

if ($class->isInstance($arg)) {
    echo "Yes";
}

// Equivalent to
if ($arg instanceof Foo) {
    echo "Yes";
}

// Equivalent to
if (is_a($arg, 'Foo')) {
    echo "Yes";
}
?>

The above example will output something similar to:

Yes
Yes
Yes

See Also

  • ReflectionClass::isInterface() - Checks if the class is an interface
  • Type operators (instanceof)
  • Object Interfaces
  • is_a() - Checks if the object is of this class or has this class as one of its parents


Checks if the class is instantiable

  • « ReflectionClass::isInstance
  • ReflectionClass::isInterface »
  • PHP Manual
  • ReflectionClass
  • Checks if the class is instantiable

ReflectionClass::isInstantiable

(PHP 5, PHP 7)

ReflectionClass::isInstantiable — Checks if the class is instantiable

Description

public ReflectionClass::isInstantiable ( void ) : bool

Checks if the class is instantiable.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ReflectionClass::isInstantiable() example

<?php
class C { }

interface iface {
    function f1();
}

class ifaceImpl implements iface {
    function f1() {}
}

abstract class abstractClass {
    function f1() { }
    abstract function f2();
}

class D extends abstractClass {
    function f2() { }
}

trait T {
    function f1() {}
}

class privateConstructor {
    private function __construct() { }
}

$classes = array(
    "C",
    "iface",
    "ifaceImpl",
    "abstractClass",
    "D",
    "T",
    "privateConstructor",
);

foreach($classes  as $class ) {
    $reflectionClass = new ReflectionClass($class);
    echo "Is $class instantiable?  ";
    var_dump($reflectionClass->isInstantiable());
}

?>

The above example will output:

Is C instantiable?  bool(true)
Is iface instantiable?  bool(false)
Is ifaceImpl instantiable?  bool(true)
Is abstractClass instantiable?  bool(false)
Is D instantiable?  bool(true)
Is T instantiable?  bool(false)
Is privateConstructor instantiable?  bool(false)

See Also

  • ReflectionClass::isInstance() - Checks class for instance


Checks if the class is an interface

  • « ReflectionClass::isInstantiable
  • ReflectionClass::isInternal »
  • PHP Manual
  • ReflectionClass
  • Checks if the class is an interface

ReflectionClass::isInterface

(PHP 5, PHP 7)

ReflectionClass::isInterface — Checks if the class is an interface

Description

public ReflectionClass::isInterface ( void ) : bool

Checks whether the class is an interface.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Basic usage of ReflectionClass::isInterface()

<?php
interface SomeInterface {
    public function interfaceMethod();
}

$class = new ReflectionClass('SomeInterface');
var_dump($class->isInterface());
?>

The above example will output:

bool(true)

See Also

  • ReflectionClass::isInstance() - Checks class for instance


Checks if class is defined internally by an extension, or the core

  • « ReflectionClass::isInterface
  • ReflectionClass::isIterable »
  • PHP Manual
  • ReflectionClass
  • Checks if class is defined internally by an extension, or the core

ReflectionClass::isInternal

(PHP 5, PHP 7)

ReflectionClass::isInternal — Checks if class is defined internally by an extension, or the core

Description

public ReflectionClass::isInternal ( void ) : bool

Checks if the class is defined internally by an extension, or the core, as opposed to user-defined.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Basic usage of ReflectionClass::isInternal()

<?php
$internalclass = new ReflectionClass('ReflectionClass');

class Apple {}
$userclass = new ReflectionClass('Apple');

var_dump($internalclass->isInternal());
var_dump($userclass->isInternal());
?>

The above example will output:

bool(true)
bool(false)

See Also

  • ReflectionClass::isUserDefined() - Checks if user defined


Check whether this class is iterable

  • « ReflectionClass::isInternal
  • ReflectionClass::isIterateable »
  • PHP Manual
  • ReflectionClass
  • Check whether this class is iterable

ReflectionClass::isIterable

(PHP 7 >= 7.2.0)

ReflectionClass::isIterable — Check whether this class is iterable

Description

public ReflectionClass::isIterable ( void ) : bool

Check whether this class is iterable (i.e. can be used inside foreach).

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Basic ReflectionClass::isIterable() Usage

<?php

class IteratorClass implements Iterator {
    public function __construct() { }
    public function key() { }
    public function current() { }
    function next() { }
    function valid() { }
    function rewind() { }
}
class DerivedClass extends IteratorClass { }
class NonIterator { }

function dump_iterable($class) {
    $reflection = new ReflectionClass($class);
    var_dump($reflection->isIterable());
}

$classes = array("ArrayObject", "IteratorClass", "DerivedClass", "NonIterator");

foreach ($classes as $class) {
    echo "Is $class iterable? ";
    dump_iterable($class);
}
?>

The above example will output:

Is ArrayObject iterable? bool(true)
Is IteratorClass iterable? bool(true)
Is DerivedClass iterable? bool(true)
Is NonIterator iterable? bool(false)

See Also

  • ReflectionClass::__construct() - Constructs a ReflectionClass


Alias of ReflectionClass::isIterable

  • « ReflectionClass::isIterable
  • ReflectionClass::isSubclassOf »
  • PHP Manual
  • ReflectionClass
  • Alias of ReflectionClass::isIterable

ReflectionClass::isIterateable

(PHP 5, PHP 7)

ReflectionClass::isIterateable — Alias of ReflectionClass::isIterable()

Description

Alias of ReflectionClass::isIterable()

As of PHP 7.2.0, instead of the missspelled RefectionClass::isIterateable(), ReflectionClass::isIterable() should be preferred.


Checks if a subclass

  • « ReflectionClass::isIterateable
  • ReflectionClass::isTrait »
  • PHP Manual
  • ReflectionClass
  • Checks if a subclass

ReflectionClass::isSubclassOf

(PHP 5, PHP 7)

ReflectionClass::isSubclassOf — Checks if a subclass

Description

public ReflectionClass::isSubclassOf ( mixed $class ) : bool

Checks if the class is a subclass of a specified class or implements a specified interface.

Parameters

class

Either the name of the class as string or a ReflectionClass object of the class to check against.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ReflectionClass::isInterface() - Checks if the class is an interface
  • ReflectionClass::implementsInterface() - Implements interface
  • is_subclass_of() - Checks if the object has this class as one of its parents or implements it
  • get_parent_class() - Retrieves the parent class name for object or class


Returns whether this is a trait

  • « ReflectionClass::isSubclassOf
  • ReflectionClass::isUserDefined »
  • PHP Manual
  • ReflectionClass
  • Returns whether this is a trait

ReflectionClass::isTrait

(PHP 5 >= 5.4.0, PHP 7)

ReflectionClass::isTrait — Returns whether this is a trait

Description

public ReflectionClass::isTrait ( void ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns TRUE if this is a trait, FALSE otherwise. Returns NULL in case of an error.


Checks if user defined

  • « ReflectionClass::isTrait
  • ReflectionClass::newInstance »
  • PHP Manual
  • ReflectionClass
  • Checks if user defined

ReflectionClass::isUserDefined

(PHP 5, PHP 7)

ReflectionClass::isUserDefined — Checks if user defined

Description

public ReflectionClass::isUserDefined ( void ) : bool

Checks whether the class is user-defined, as opposed to internal.

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • ReflectionClass::isInternal() - Checks if class is defined internally by an extension, or the core


Creates a new class instance from given arguments

  • « ReflectionClass::isUserDefined
  • ReflectionClass::newInstanceArgs »
  • PHP Manual
  • ReflectionClass
  • Creates a new class instance from given arguments

ReflectionClass::newInstance

(PHP 5, PHP 7)

ReflectionClass::newInstance — Creates a new class instance from given arguments

Description

public ReflectionClass::newInstance ([ mixed $... ] ) : object

Creates a new instance of the class. The given arguments are passed to the class constructor.

Parameters

...

Accepts a variable number of arguments which are passed to the class constructor, much like call_user_func().

Return Values

Errors/Exceptions

A ReflectionException if the class constructor is not public.

A ReflectionException if the class does not have a constructor and the ... parameter contains one or more parameters.

See Also

  • ReflectionClass::newInstanceArgs() - Creates a new class instance from given arguments
  • ReflectionClass::newInstanceWithoutConstructor() - Creates a new class instance without invoking the constructor


Creates a new class instance from given arguments

  • « ReflectionClass::newInstance
  • ReflectionClass::newInstanceWithoutConstructor »
  • PHP Manual
  • ReflectionClass
  • Creates a new class instance from given arguments

ReflectionClass::newInstanceArgs

(PHP 5 >= 5.1.3, PHP 7)

ReflectionClass::newInstanceArgs — Creates a new class instance from given arguments

Description

public ReflectionClass::newInstanceArgs ([ array $args ] ) : object

Creates a new instance of the class, the given arguments are passed to the class constructor.

Parameters

args

The parameters to be passed to the class constructor as an array.

Return Values

Returns a new instance of the class.

Examples

Example #1 Basic usage of ReflectionClass::newInstanceArgs()

<?php
$class = new ReflectionClass('ReflectionFunction');
$instance = $class->newInstanceArgs(array('substr'));
var_dump($instance);
?>

The above example will output:

object(ReflectionFunction)#2 (1) {
  ["name"]=>
  string(6) "substr"
}

Errors/Exceptions

A ReflectionException if the class constructor is not public.

A ReflectionException if the class does not have a constructor and the args parameter contains one or more parameters.

See Also

  • ReflectionClass::newInstance() - Creates a new class instance from given arguments
  • ReflectionClass::newInstanceWithoutConstructor() - Creates a new class instance without invoking the constructor


Creates a new class instance without invoking the constructor

  • « ReflectionClass::newInstanceArgs
  • ReflectionClass::setStaticPropertyValue »
  • PHP Manual
  • ReflectionClass
  • Creates a new class instance without invoking the constructor

ReflectionClass::newInstanceWithoutConstructor

(PHP 5 >= 5.4.0, PHP 7)

ReflectionClass::newInstanceWithoutConstructor — Creates a new class instance without invoking the constructor

Description

public ReflectionClass::newInstanceWithoutConstructor ( void ) : object

Creates a new instance of the class without invoking the constructor.

Parameters

Return Values

Changelog

Version | Description
5.6.0 | All internal classes can now be instantiated except for those declared final.

Errors/Exceptions

A ReflectionException if the class is an internal class that cannot be instantiated without invoking the constructor. In PHP 5.6.0 onwards, this exception is limited only to internal classes that are final.

See Also

  • ReflectionClass::newInstance() - Creates a new class instance from given arguments
  • ReflectionClass::newInstanceArgs() - Creates a new class instance from given arguments


Sets static property value

  • « ReflectionClass::newInstanceWithoutConstructor
  • ReflectionClass::__toString »
  • PHP Manual
  • ReflectionClass
  • Sets static property value

ReflectionClass::setStaticPropertyValue

(PHP 5 >= 5.1.2, PHP 7)

ReflectionClass::setStaticPropertyValue — Sets static property value

Description

public ReflectionClass::setStaticPropertyValue ( string $name , mixed $value ) : void

Sets static property value.

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Property name.

value

New property value.

Return Values

No value is returned.

See Also

  • ReflectionClass::getStaticPropertyValue() - Gets static property value


Returns the string representation of the ReflectionClass object

  • « ReflectionClass::setStaticPropertyValue
  • ReflectionClassConstant »
  • PHP Manual
  • ReflectionClass
  • Returns the string representation of the ReflectionClass object

ReflectionClass::__toString

(PHP 5, PHP 7)

ReflectionClass::__toString — Returns the string representation of the ReflectionClass object

Description

public ReflectionClass::__toString ( void ) : string

Returns the string representation of the ReflectionClass object.

Parameters

This function has no parameters.

Return Values

A string representation of this ReflectionClass instance.

Examples

Example #1 ReflectionClass::__toString() example

<?php
$reflectionClass = new ReflectionClass('Exception');
echo $reflectionClass->__toString();
?>

The above example will output:

Class [ <internal:Core> class Exception ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [7] {
    Property [ <default> protected $message ]
    Property [ <default> private $string ]
    Property [ <default> protected $code ]
    Property [ <default> protected $file ]
    Property [ <default> protected $line ]
    Property [ <default> private $trace ]
    Property [ <default> private $previous ]
  }

  - Methods [10] {
    Method [ <internal:Core> final private method __clone ] {
    }

    Method [ <internal:Core, ctor> public method __construct ] {

      - Parameters [3] {
        Parameter #0 [ <optional> $message ]
        Parameter #1 [ <optional> $code ]
        Parameter #2 [ <optional> $previous ]
      }
    }

    Method [ <internal:Core> final public method getMessage ] {
    }

    Method [ <internal:Core> final public method getCode ] {
    }

    Method [ <internal:Core> final public method getFile ] {
    }

    Method [ <internal:Core> final public method getLine ] {
    }

    Method [ <internal:Core> final public method getTrace ] {
    }

    Method [ <internal:Core> final public method getPrevious ] {
    }

    Method [ <internal:Core> final public method getTraceAsString ] {
    }

    Method [ <internal:Core> public method __toString ] {
    }
  }
}

See Also

  • ReflectionClass::export() - Exports a class
  • __toString()


The ReflectionClassConstant class

(PHP 7 >= 7.1.0)

Introduction

The ReflectionClassConstant class reports information about a class constant.

Class synopsis

ReflectionClassConstant implements Reflector {
/* Properties */
public $name ;
public $class ;
/* Methods */
public __construct ( mixed $class , string $name )
public static export ( mixed $class , string $name [, bool $return ] ) : string
public getDeclaringClass ( void ) : ReflectionClass
public getDocComment ( void ) : string
public getModifiers ( void ) : int
public getName ( void ) : string
public getValue ( void ) : mixed
public isPrivate ( void ) : bool
public isProtected ( void ) : bool
public isPublic ( void ) : bool
public __toString ( void ) : string
}

Properties

name

Name of the class constant. Read-only, throws ReflectionException in attempt to write.

class

Name of the class where the class constant is defined. Read-only, throws ReflectionException in attempt to write.

Table of Contents

  • ReflectionClassConstant::__construct — Constructs a ReflectionClassConstant
  • ReflectionClassConstant::export — Export
  • ReflectionClassConstant::getDeclaringClass — Gets declaring class
  • ReflectionClassConstant::getDocComment — Gets doc comments
  • ReflectionClassConstant::getModifiers — Gets the class constant modifiers
  • ReflectionClassConstant::getName — Get name of the constant
  • ReflectionClassConstant::getValue — Gets value
  • ReflectionClassConstant::isPrivate — Checks if class constant is private
  • ReflectionClassConstant::isProtected — Checks if class constant is protected
  • ReflectionClassConstant::isPublic — Checks if class constant is public
  • ReflectionClassConstant::__toString — Returns the string representation of the ReflectionClassConstant object


Constructs a ReflectionClassConstant

  • « ReflectionClassConstant
  • ReflectionClassConstant::export »
  • PHP Manual
  • ReflectionClassConstant
  • Constructs a ReflectionClassConstant

ReflectionClassConstant::__construct

(PHP 7 >= 7.1.0)

ReflectionClassConstant::__construct — Constructs a ReflectionClassConstant

Description

public ReflectionClassConstant::__construct ( mixed $class , string $name )

Constructs a new ReflectionClassConstant object.

Parameters

class

Either a string containing the name of the class to reflect, or an object.

name

The name of the class constant.

Return Values

Returns constructed ReflectionClassConstant instance.

Errors/Exceptions

Throws an Exception in case the given class constant does not exist.

See Also

  • Constructors


Export

  • « ReflectionClassConstant::__construct
  • ReflectionClassConstant::getDeclaringClass »
  • PHP Manual
  • ReflectionClassConstant
  • Export

ReflectionClassConstant::export

(PHP 7 >= 7.1.0)

ReflectionClassConstant::export — Export

Description

public static ReflectionClassConstant::export ( mixed $class , string $name [, bool $return ] ) : string

Exports a reflection.

Warning

This function is currently not documented; only its argument list is available.

Parameters

class

The reflection to export.

name

The class constant name.

return

Setting to TRUE will return the export, as opposed to emitting it. Setting to FALSE (the default) will do the opposite.

Return Values

See Also

  • ReflectionClassConstant::__toString() - Returns the string representation of the ReflectionClassConstant object


Gets declaring class

  • « ReflectionClassConstant::export
  • ReflectionClassConstant::getDocComment »
  • PHP Manual
  • ReflectionClassConstant
  • Gets declaring class

ReflectionClassConstant::getDeclaringClass

(PHP 7 >= 7.1.0)

ReflectionClassConstant::getDeclaringClass — Gets declaring class

Description

public ReflectionClassConstant::getDeclaringClass ( void ) : ReflectionClass

Gets the declaring class.

Parameters

This function has no parameters.

Return Values

A ReflectionClass object.


Gets doc comments

  • « ReflectionClassConstant::getDeclaringClass
  • ReflectionClassConstant::getModifiers »
  • PHP Manual
  • ReflectionClassConstant
  • Gets doc comments

ReflectionClassConstant::getDocComment

(PHP 7 >= 7.1.0)

ReflectionClassConstant::getDocComment — Gets doc comments

Description

public ReflectionClassConstant::getDocComment ( void ) : string

Gets doc comments from a class constant.

Parameters

This function has no parameters.

Return Values

The doc comment if it exists, otherwise FALSE


Gets the class constant modifiers

  • « ReflectionClassConstant::getDocComment
  • ReflectionClassConstant::getName »
  • PHP Manual
  • ReflectionClassConstant
  • Gets the class constant modifiers

ReflectionClassConstant::getModifiers

(PHP 7 >= 7.1.0)

ReflectionClassConstant::getModifiers — Gets the class constant modifiers

Description

public ReflectionClassConstant::getModifiers ( void ) : int

Returns a bitfield of the access modifiers for this class constant.

Parameters

This function has no parameters.

Return Values

A numeric representation of the modifiers. The actual meanings of these modifiers are described in the predefined constants.

See Also

  • Reflection::getModifierNames() - Gets modifier names


Get name of the constant

  • « ReflectionClassConstant::getModifiers
  • ReflectionClassConstant::getValue »
  • PHP Manual
  • ReflectionClassConstant
  • Get name of the constant

ReflectionClassConstant::getName

(PHP 7 >= 7.1.0)

ReflectionClassConstant::getName — Get name of the constant

Description

public ReflectionClassConstant::getName ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns the constant's name.


Gets value

  • « ReflectionClassConstant::getName
  • ReflectionClassConstant::isPrivate »
  • PHP Manual
  • ReflectionClassConstant
  • Gets value

ReflectionClassConstant::getValue

(PHP 7 >= 7.1.0)

ReflectionClassConstant::getValue — Gets value

Description

public ReflectionClassConstant::getValue ( void ) : mixed

Gets the class constant's value.

Parameters

This function has no parameters.

Return Values

The value of the class constant.


Checks if class constant is private

  • « ReflectionClassConstant::getValue
  • ReflectionClassConstant::isProtected »
  • PHP Manual
  • ReflectionClassConstant
  • Checks if class constant is private

ReflectionClassConstant::isPrivate

(PHP 7 >= 7.1.0)

ReflectionClassConstant::isPrivate — Checks if class constant is private

Description

public ReflectionClassConstant::isPrivate ( void ) : bool

Checks if the class constant is private.

Parameters

This function has no parameters.

Return Values

TRUE if the class constant is private, otherwise FALSE

See Also

  • ReflectionClassConstant::isPublic() - Checks if class constant is public
  • ReflectionClassConstant::isProtected() - Checks if class constant is protected


Checks if class constant is protected

  • « ReflectionClassConstant::isPrivate
  • ReflectionClassConstant::isPublic »
  • PHP Manual
  • ReflectionClassConstant
  • Checks if class constant is protected

ReflectionClassConstant::isProtected

(PHP 7 >= 7.1.0)

ReflectionClassConstant::isProtected — Checks if class constant is protected

Description

public ReflectionClassConstant::isProtected ( void ) : bool

Checks if the class constant is protected.

Parameters

This function has no parameters.

Return Values

TRUE if the class constant is protected, otherwise FALSE

See Also

  • ReflectionClassConstant::isPublic() - Checks if class constant is public
  • ReflectionClassConstant::isPrivate() - Checks if class constant is private


Checks if class constant is public

  • « ReflectionClassConstant::isProtected
  • ReflectionClassConstant::__toString »
  • PHP Manual
  • ReflectionClassConstant
  • Checks if class constant is public

ReflectionClassConstant::isPublic

(PHP 7 >= 7.1.0)

ReflectionClassConstant::isPublic — Checks if class constant is public

Description

public ReflectionClassConstant::isPublic ( void ) : bool

Checks if the class constant is public.

Parameters

This function has no parameters.

Return Values

TRUE if the class constant is public, otherwise FALSE

See Also

  • ReflectionClassConstant::isPrivate() - Checks if class constant is private
  • ReflectionClassConstant::isProtected() - Checks if class constant is protected


Returns the string representation of the ReflectionClassConstant object

  • « ReflectionClassConstant::isPublic
  • ReflectionZendExtension »
  • PHP Manual
  • ReflectionClassConstant
  • Returns the string representation of the ReflectionClassConstant object

ReflectionClassConstant::__toString

(PHP 7 >= 7.1.0)

ReflectionClassConstant::__toString — Returns the string representation of the ReflectionClassConstant object

Description

public ReflectionClassConstant::__toString ( void ) : string

Returns the string representation of the ReflectionClassConstant object.

Parameters

This function has no parameters.

Return Values

A string representation of this ReflectionClassConstant instance.

See Also

  • ReflectionClassConstant::export() - Export
  • __toString()


The ReflectionZendExtension class

(PHP 5 >= 5.4.0, PHP 7)

Introduction

Class synopsis

ReflectionZendExtension implements Reflector {
/* Properties */
public $name ;
/* Methods */
final private __clone ( void ) : void
public __construct ( string $name )
public static export ( string $name [, bool $return ] ) : string
public getAuthor ( void ) : string
public getCopyright ( void ) : string
public getName ( void ) : string
public getURL ( void ) : string
public getVersion ( void ) : string
public __toString ( void ) : string
}

Properties

name

Name of the extension. Read-only, throws ReflectionException in attempt to write.

Table of Contents

  • ReflectionZendExtension::__clone — Clone handler
  • ReflectionZendExtension::__construct — Constructor
  • ReflectionZendExtension::export — Export
  • ReflectionZendExtension::getAuthor — Gets author
  • ReflectionZendExtension::getCopyright — Gets copyright
  • ReflectionZendExtension::getName — Gets name
  • ReflectionZendExtension::getURL — Gets URL
  • ReflectionZendExtension::getVersion — Gets version
  • ReflectionZendExtension::__toString — To string handler


Clone handler

  • « ReflectionZendExtension
  • ReflectionZendExtension::__construct »
  • PHP Manual
  • ReflectionZendExtension
  • Clone handler

ReflectionZendExtension::__clone

(PHP 5 >= 5.4.0, PHP 7)

ReflectionZendExtension::__clone — Clone handler

Description

final private ReflectionZendExtension::__clone ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Constructor

  • « ReflectionZendExtension::__clone
  • ReflectionZendExtension::export »
  • PHP Manual
  • ReflectionZendExtension
  • Constructor

ReflectionZendExtension::__construct

(PHP 5 >= 5.4.0, PHP 7)

ReflectionZendExtension::__construct — Constructor

Description

public ReflectionZendExtension::__construct ( string $name )

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

Return Values


Export

  • « ReflectionZendExtension::__construct
  • ReflectionZendExtension::getAuthor »
  • PHP Manual
  • ReflectionZendExtension
  • Export

ReflectionZendExtension::export

(PHP 5 >= 5.4.0, PHP 7)

ReflectionZendExtension::export — Export

Description

public static ReflectionZendExtension::export ( string $name [, bool $return ] ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

name

return

Return Values


Gets author

  • « ReflectionZendExtension::export
  • ReflectionZendExtension::getCopyright »
  • PHP Manual
  • ReflectionZendExtension
  • Gets author

ReflectionZendExtension::getAuthor

(PHP 5 >= 5.4.0, PHP 7)

ReflectionZendExtension::getAuthor — Gets author

Description

public ReflectionZendExtension::getAuthor ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Gets copyright

  • « ReflectionZendExtension::getAuthor
  • ReflectionZendExtension::getName »
  • PHP Manual
  • ReflectionZendExtension
  • Gets copyright

ReflectionZendExtension::getCopyright

(PHP 5 >= 5.4.0, PHP 7)

ReflectionZendExtension::getCopyright — Gets copyright

Description

public ReflectionZendExtension::getCopyright ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Gets name

  • « ReflectionZendExtension::getCopyright
  • ReflectionZendExtension::getURL »
  • PHP Manual
  • ReflectionZendExtension
  • Gets name

ReflectionZendExtension::getName

(PHP 5 >= 5.4.0, PHP 7)

ReflectionZendExtension::getName — Gets name

Description

public ReflectionZendExtension::getName ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Gets URL

  • « ReflectionZendExtension::getName
  • ReflectionZendExtension::getVersion »
  • PHP Manual
  • ReflectionZendExtension
  • Gets URL

ReflectionZendExtension::getURL

(PHP 5 >= 5.4.0, PHP 7)

ReflectionZendExtension::getURL — Gets URL

Description

public ReflectionZendExtension::getURL ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Gets version

  • « ReflectionZendExtension::getURL
  • ReflectionZendExtension::__toString »
  • PHP Manual
  • ReflectionZendExtension
  • Gets version

ReflectionZendExtension::getVersion

(PHP 5 >= 5.4.0, PHP 7)

ReflectionZendExtension::getVersion — Gets version

Description

public ReflectionZendExtension::getVersion ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


To string handler

  • « ReflectionZendExtension::getVersion
  • ReflectionExtension »
  • PHP Manual
  • ReflectionZendExtension
  • To string handler

ReflectionZendExtension::__toString

(PHP 5 >= 5.4.0, PHP 7)

ReflectionZendExtension::__toString — To string handler

Description

public ReflectionZendExtension::__toString ( void ) : string

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


The ReflectionExtension class

(PHP 5, PHP 7)

Introduction

The ReflectionExtension class reports information about an extension.

Class synopsis

ReflectionExtension implements Reflector {
/* Properties */
public $name ;
/* Methods */
final private __clone ( void ) : void
public __construct ( string $name )
public static export ( string $name [, string $return = FALSE ] ) : string
public getClasses ( void ) : array
public getClassNames ( void ) : array
public getConstants ( void ) : array
public getDependencies ( void ) : array
public getFunctions ( void ) : array
public getINIEntries ( void ) : array
public getName ( void ) : string
public getVersion ( void ) : string
public info ( void ) : void
public isPersistent ( void ) : void
public isTemporary ( void ) : void
public __toString ( void ) : string
}

Properties

name

Name of the extension, same as calling the ReflectionExtension::getName() method.

Table of Contents

  • ReflectionExtension::__clone — Clones
  • ReflectionExtension::__construct — Constructs a ReflectionExtension
  • ReflectionExtension::export — Export
  • ReflectionExtension::getClasses — Gets classes
  • ReflectionExtension::getClassNames — Gets class names
  • ReflectionExtension::getConstants — Gets constants
  • ReflectionExtension::getDependencies — Gets dependencies
  • ReflectionExtension::getFunctions — Gets extension functions
  • ReflectionExtension::getINIEntries — Gets extension ini entries
  • ReflectionExtension::getName — Gets extension name
  • ReflectionExtension::getVersion — Gets extension version
  • ReflectionExtension::info — Print extension info
  • ReflectionExtension::isPersistent — Returns whether this extension is persistent
  • ReflectionExtension::isTemporary — Returns whether this extension is temporary
  • ReflectionExtension::__toString — To string


Clones

  • « ReflectionExtension
  • ReflectionExtension::__construct »
  • PHP Manual
  • ReflectionExtension
  • Clones

ReflectionExtension::__clone

(PHP 5, PHP 7)

ReflectionExtension::__clone — Clones

Description

final private ReflectionExtension::__clone ( void ) : void

The clone method prevents an object from being cloned. Reflection objects cannot be cloned.

Parameters

This function has no parameters.

Return Values

No value is returned, if called a fatal error will occur.

See Also

  • ReflectionExtension::__construct() - Constructs a ReflectionExtension
  • Object cloning


Constructs a ReflectionExtension

  • « ReflectionExtension::__clone
  • ReflectionExtension::export »
  • PHP Manual
  • ReflectionExtension
  • Constructs a ReflectionExtension

ReflectionExtension::__construct

(PHP 5, PHP 7)

ReflectionExtension::__construct — Constructs a ReflectionExtension

Description

public ReflectionExtension::__construct ( string $name )

Construct a ReflectionExtension object.

Parameters

name

Name of the extension.

Return Values

A ReflectionExtension object.

Examples

Example #1 ReflectionExtension example

<?php
$ext = new ReflectionExtension('Reflection');

printf('Extension: %s (version: %s)', $ext->getName(), $ext->getVersion());
?>

The above example will output something similar to:

Extension: Reflection (version: $Revision: 330543 $)

See Also

  • ReflectionExtension::info() - Print extension info
  • Constructors


Export

  • « ReflectionExtension::__construct
  • ReflectionExtension::getClasses »
  • PHP Manual
  • ReflectionExtension
  • Export

ReflectionExtension::export

(PHP 5, PHP 7)

ReflectionExtension::export — Export

Description

public static ReflectionExtension::export ( string $name [, string $return = FALSE ] ) : string

Exports a reflected extension. The output format of this function is the same as the CLI argument --re [extension].

Parameters

name

The reflection to export.

return

Setting to TRUE will return the export, as opposed to emitting it. Setting to FALSE (the default) will do the opposite.

Return Values

If the return parameter is set to TRUE, then the export is returned as a string, otherwise NULL is returned.

See Also

  • ReflectionExtension::info() - Print extension info


Gets classes

  • « ReflectionExtension::export
  • ReflectionExtension::getClassNames »
  • PHP Manual
  • ReflectionExtension
  • Gets classes

ReflectionExtension::getClasses

(PHP 5, PHP 7)

ReflectionExtension::getClasses — Gets classes

Description

public ReflectionExtension::getClasses ( void ) : array

Gets a list of classes from an extension.

Parameters

This function has no parameters.

Return Values

An array of ReflectionClass objects, one for each class within the extension. If no classes are defined, an empty array is returned.

Examples

Example #1 ReflectionExtension::getClasses() example

<?php
$ext = new ReflectionExtension('XMLWriter');
var_dump($ext->getClasses());
?>

The above example will output something similar to:

array(1) {
  ["XMLWriter"]=>
  &object(ReflectionClass)#2 (1) {
    ["name"]=>
    string(9) "XMLWriter"
  }
}

See Also

  • ReflectionExtension::getClassNames() - Gets class names


Gets class names

  • « ReflectionExtension::getClasses
  • ReflectionExtension::getConstants »
  • PHP Manual
  • ReflectionExtension
  • Gets class names

ReflectionExtension::getClassNames

(PHP 5, PHP 7)

ReflectionExtension::getClassNames — Gets class names

Description

public ReflectionExtension::getClassNames ( void ) : array

Gets a listing of class names as defined in the extension.

Parameters

This function has no parameters.

Return Values

An array of class names, as defined in the extension. If no classes are defined, an empty array is returned.

Examples

Example #1 ReflectionExtension::getClassNames() example

<?php
$ext = new ReflectionExtension('XMLWriter');
var_dump($ext->getClassNames());
?>

The above example will output something similar to:

array(1) {
  [0]=>
  string(9) "XMLWriter"
}

See Also

  • ReflectionExtension::getClasses() - Gets classes
  • ReflectionExtension::getName() - Gets extension name


Gets constants

  • « ReflectionExtension::getClassNames
  • ReflectionExtension::getDependencies »
  • PHP Manual
  • ReflectionExtension
  • Gets constants

ReflectionExtension::getConstants

(PHP 5, PHP 7)

ReflectionExtension::getConstants — Gets constants

Description

public ReflectionExtension::getConstants ( void ) : array

Get defined constants from an extension.

Parameters

This function has no parameters.

Return Values

An associative array with constant names as keys.

Examples

Example #1 ReflectionExtension::getConstants() example

<?php
$ext = new ReflectionExtension('DOM');

print_r($ext->getConstants());
?>

The above example will output something similar to:

Array
(
    [XML_ELEMENT_NODE] => 1
    [XML_ATTRIBUTE_NODE] => 2
    [XML_TEXT_NODE] => 3
    [XML_CDATA_SECTION_NODE] => 4
    [XML_ENTITY_REF_NODE] => 5
    [XML_ENTITY_NODE] => 6
    [XML_PI_NODE] => 7
    [XML_COMMENT_NODE] => 8
    [XML_DOCUMENT_NODE] => 9
    [XML_DOCUMENT_TYPE_NODE] => 10
    [XML_DOCUMENT_FRAG_NODE] => 11
    [XML_NOTATION_NODE] => 12
    [XML_HTML_DOCUMENT_NODE] => 13
    [XML_DTD_NODE] => 14
    [XML_ELEMENT_DECL_NODE] => 15
    [XML_ATTRIBUTE_DECL_NODE] => 16
    [XML_ENTITY_DECL_NODE] => 17
    [XML_NAMESPACE_DECL_NODE] => 18
    [XML_LOCAL_NAMESPACE] => 18
    [XML_ATTRIBUTE_CDATA] => 1
    [XML_ATTRIBUTE_ID] => 2
    [XML_ATTRIBUTE_IDREF] => 3
    [XML_ATTRIBUTE_IDREFS] => 4
    [XML_ATTRIBUTE_ENTITY] => 6
    [XML_ATTRIBUTE_NMTOKEN] => 7
    [XML_ATTRIBUTE_NMTOKENS] => 8
    [XML_ATTRIBUTE_ENUMERATION] => 9
    [XML_ATTRIBUTE_NOTATION] => 10
    [DOM_PHP_ERR] => 0
    [DOM_INDEX_SIZE_ERR] => 1
    [DOMSTRING_SIZE_ERR] => 2
    [DOM_HIERARCHY_REQUEST_ERR] => 3
    [DOM_WRONG_DOCUMENT_ERR] => 4
    [DOM_INVALID_CHARACTER_ERR] => 5
    [DOM_NO_DATA_ALLOWED_ERR] => 6
    [DOM_NO_MODIFICATION_ALLOWED_ERR] => 7
    [DOM_NOT_FOUND_ERR] => 8
    [DOM_NOT_SUPPORTED_ERR] => 9
    [DOM_INUSE_ATTRIBUTE_ERR] => 10
    [DOM_INVALID_STATE_ERR] => 11
    [DOM_SYNTAX_ERR] => 12
    [DOM_INVALID_MODIFICATION_ERR] => 13
    [DOM_NAMESPACE_ERR] => 14
    [DOM_INVALID_ACCESS_ERR] => 15
    [DOM_VALIDATION_ERR] => 16
)

See Also

  • ReflectionExtension::getINIEntries() - Gets extension ini entries


Gets dependencies

  • « ReflectionExtension::getConstants
  • ReflectionExtension::getFunctions »
  • PHP Manual
  • ReflectionExtension
  • Gets dependencies

ReflectionExtension::getDependencies

(PHP 5 >= 5.1.3, PHP 7)

ReflectionExtension::getDependencies — Gets dependencies

Description

public ReflectionExtension::getDependencies ( void ) : array

Gets dependencies, by listing both required and conflicting dependencies.

Parameters

This function has no parameters.

Return Values

An associative array with dependencies as keys and either Required, Optional or Conflicts as the values.

Examples

Example #1 ReflectionExtension::getDependencies() example

<?php
$dom = new ReflectionExtension('dom');

print_r($dom->getDependencies());
?>

The above example will output something similar to:

Array
(
    [libxml] => Required
    [domxml] => Conflicts
)

See Also

  • ReflectionClass::getVersion()


Gets extension functions

  • « ReflectionExtension::getDependencies
  • ReflectionExtension::getINIEntries »
  • PHP Manual
  • ReflectionExtension
  • Gets extension functions

ReflectionExtension::getFunctions

(PHP 5, PHP 7)

ReflectionExtension::getFunctions — Gets extension functions

Description

public ReflectionExtension::getFunctions ( void ) : array

Get defined functions from an extension.

Parameters

This function has no parameters.

Return Values

An associative array of ReflectionFunction objects, for each function defined in the extension with the keys being the function names. If no function are defined, an empty array is returned.

Examples

Example #1 ReflectionExtension::getFunctions() example

<?php
$dom = new ReflectionExtension('SimpleXML');

print_r($dom->getFunctions());
?>

The above example will output something similar to:

Array
(
    [simplexml_load_file] => ReflectionFunction Object
        (
            [name] => simplexml_load_file
        )

    [simplexml_load_string] => ReflectionFunction Object
        (
            [name] => simplexml_load_string
        )

    [simplexml_import_dom] => ReflectionFunction Object
        (
            [name] => simplexml_import_dom
        )

)

See Also

  • ReflectionExtension::getClasses() - Gets classes
  • get_extension_funcs() - Returns an array with the names of the functions of a module


Gets extension ini entries

  • « ReflectionExtension::getFunctions
  • ReflectionExtension::getName »
  • PHP Manual
  • ReflectionExtension
  • Gets extension ini entries

ReflectionExtension::getINIEntries

(PHP 5, PHP 7)

ReflectionExtension::getINIEntries — Gets extension ini entries

Description

public ReflectionExtension::getINIEntries ( void ) : array

Get the ini entries for an extension.

Parameters

This function has no parameters.

Return Values

An associative array with the ini entries as keys, with their defined values as values.

Examples

Example #1 ReflectionExtension::getINIEntries() example

<?php
$ext = new ReflectionExtension('mysql');

print_r($ext->getINIEntries());
?>

The above example will output something similar to:

Array
(
    [mysql.allow_persistent] => 1
    [mysql.max_persistent] => -1
    [mysql.max_links] => -1
    [mysql.default_host] =>
    [mysql.default_user] =>
    [mysql.default_password] =>
    [mysql.default_port] =>
    [mysql.default_socket] =>
    [mysql.connect_timeout] => 60
    [mysql.trace_mode] =>
    [mysql.allow_local_infile] => 1
    [mysql.cache_size] => 2000
)

See Also

  • ini_get_all() - Gets all configuration options
  • ReflectionExtension::getConstants() - Gets constants


Gets extension name

  • « ReflectionExtension::getINIEntries
  • ReflectionExtension::getVersion »
  • PHP Manual
  • ReflectionExtension
  • Gets extension name

ReflectionExtension::getName

(PHP 5, PHP 7)

ReflectionExtension::getName — Gets extension name

Description

public ReflectionExtension::getName ( void ) : string

Gets the extensions name.

Parameters

This function has no parameters.

Return Values

The extensions name.

Examples

Example #1 ReflectionExtension::getName() example

<?php
$ext = new ReflectionExtension('mysqli');
var_dump($ext->getName());
?>

The above example will output something similar to:

string(6) "mysqli"

See Also

  • ReflectionExtension::getClassNames() - Gets class names


Gets extension version

  • « ReflectionExtension::getName
  • ReflectionExtension::info »
  • PHP Manual
  • ReflectionExtension
  • Gets extension version

ReflectionExtension::getVersion

(PHP 5, PHP 7)

ReflectionExtension::getVersion — Gets extension version

Description

public ReflectionExtension::getVersion ( void ) : string

Gets the version of the extension.

Parameters

This function has no parameters.

Return Values

The version of the extension.

Examples

Example #1 ReflectionExtension::getVersion() example

<?php
$ext = new ReflectionExtension('mysqli');
var_dump($ext->getVersion());
?>

The above example will output something similar to:

string(3) "0.1"

See Also

  • ReflectionExtension::info() - Print extension info


Print extension info

  • « ReflectionExtension::getVersion
  • ReflectionExtension::isPersistent »
  • PHP Manual
  • ReflectionExtension
  • Print extension info

ReflectionExtension::info

(PHP 5 >= 5.2.4, PHP 7)

ReflectionExtension::info — Print extension info

Description

public ReflectionExtension::info ( void ) : void

Prints out the "phpinfo()" snippet for the given extension.

Parameters

This function has no parameters.

Return Values

Information about the extension.

Examples

Example #1 ReflectionExtension::info() example

<?php
$ext = new ReflectionExtension('mysqli');
$ext->info();
?>

The above example will output something similar to:

mysqli

MysqlI Support => enabled
Client API library version => mysqlnd 5.0.5-dev - 081106 - $Revision: 315808 $
Active Persistent Links => 0
Inactive Persistent Links => 0
Active Links => 0
Persistent cache => enabled
put_hits => 0
put_misses => 0
get_hits => 0
get_misses => 0
size => 2000
free_items => 2000
references => 2

Directive => Local Value => Master Value
mysqli.max_links => Unlimited => Unlimited
mysqli.max_persistent => Unlimited => Unlimited
mysqli.allow_persistent => On => On
mysqli.default_host => no value => no value
mysqli.default_user => no value => no value
mysqli.default_pw => no value => no value
mysqli.default_port => 3306 => 3306
mysqli.default_socket => no value => no value
mysqli.reconnect => Off => Off
mysqli.allow_local_infile => On => On
mysqli.cache_size => 2000 => 2000

See Also

  • ReflectionExtension::getName() - Gets extension name
  • phpinfo() - Outputs information about PHP's configuration


Returns whether this extension is persistent

  • « ReflectionExtension::info
  • ReflectionExtension::isTemporary »
  • PHP Manual
  • ReflectionExtension
  • Returns whether this extension is persistent

ReflectionExtension::isPersistent

(PHP 5 >= 5.4.0, PHP 7)

ReflectionExtension::isPersistent — Returns whether this extension is persistent

Description

public ReflectionExtension::isPersistent ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns TRUE for extensions loaded by extension, FALSE otherwise.

See Also

  • ReflectionExtension::isTemporary() - Returns whether this extension is temporary


Returns whether this extension is temporary

  • « ReflectionExtension::isPersistent
  • ReflectionExtension::__toString »
  • PHP Manual
  • ReflectionExtension
  • Returns whether this extension is temporary

ReflectionExtension::isTemporary

(PHP 5 >= 5.4.0, PHP 7)

ReflectionExtension::isTemporary — Returns whether this extension is temporary

Description

public ReflectionExtension::isTemporary ( void ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns TRUE for extensions loaded by dl(), FALSE otherwise.

See Also

  • ReflectionExtension::isPersistent() - Returns whether this extension is persistent


To string

  • « ReflectionExtension::isTemporary
  • ReflectionFunction »
  • PHP Manual
  • ReflectionExtension
  • To string

ReflectionExtension::__toString

(PHP 5, PHP 7)

ReflectionExtension::__toString — To string

Description

public ReflectionExtension::__toString ( void ) : string

Exports a reflected extension and returns it as a string. This is the same as the ReflectionExtension::export() with the return set to TRUE.

Parameters

This function has no parameters.

Return Values

Returns the exported extension as a string, in the same way as the ReflectionExtension::export().

See Also

  • ReflectionExtension::__construct() - Constructs a ReflectionExtension
  • ReflectionExtension::export() - Export
  • __toString()


The ReflectionFunction class

(PHP 5, PHP 7)

Introduction

The ReflectionFunction class reports information about a function.

Class synopsis

ReflectionFunction extends ReflectionFunctionAbstract implements Reflector {
/* Constants */
const integer IS_DEPRECATED = 262144 ;
/* Properties */
public $name ;
/* Methods */
public __construct ( mixed $name )
public static export ( string $name [, string $return ] ) : string
public getClosure ( void ) : Closure
public invoke ([ mixed $... ] ) : mixed
public invokeArgs ( array $args ) : mixed
public isDisabled ( void ) : bool
public __toString ( void ) : string
/* Inherited methods */
final private ReflectionFunctionAbstract::__clone ( void ) : void
public ReflectionFunctionAbstract::getClosureScopeClass ( void ) : ReflectionClass
public ReflectionFunctionAbstract::getClosureThis ( void ) : object
public ReflectionFunctionAbstract::getDocComment ( void ) : string
public ReflectionFunctionAbstract::getEndLine ( void ) : int
public ReflectionFunctionAbstract::getExtension ( void ) : ReflectionExtension
public ReflectionFunctionAbstract::getExtensionName ( void ) : string
public ReflectionFunctionAbstract::getFileName ( void ) : string
public ReflectionFunctionAbstract::getName ( void ) : string
public ReflectionFunctionAbstract::getNamespaceName ( void ) : string
public ReflectionFunctionAbstract::getNumberOfParameters ( void ) : int
public ReflectionFunctionAbstract::getNumberOfRequiredParameters ( void ) : int
public ReflectionFunctionAbstract::getParameters ( void ) : array
public ReflectionFunctionAbstract::getReturnType ( void ) : ReflectionType
public ReflectionFunctionAbstract::getShortName ( void ) : string
public ReflectionFunctionAbstract::getStartLine ( void ) : int
public ReflectionFunctionAbstract::getStaticVariables ( void ) : array
public ReflectionFunctionAbstract::hasReturnType ( void ) : bool
public ReflectionFunctionAbstract::inNamespace ( void ) : bool
public ReflectionFunctionAbstract::isClosure ( void ) : bool
public ReflectionFunctionAbstract::isDeprecated ( void ) : bool
public ReflectionFunctionAbstract::isGenerator ( void ) : bool
public ReflectionFunctionAbstract::isInternal ( void ) : bool
public ReflectionFunctionAbstract::isUserDefined ( void ) : bool
public ReflectionFunctionAbstract::isVariadic ( void ) : bool
public ReflectionFunctionAbstract::returnsReference ( void ) : bool
abstract public ReflectionFunctionAbstract::__toString ( void ) : void
}

Properties

name

Name of the function. Read-only, throws ReflectionException in attempt to write.

Predefined Constants

ReflectionFunction Modifiers

ReflectionFunction::IS_DEPRECATED

Indicates deprecated functions.

Table of Contents

  • ReflectionFunction::__construct — Constructs a ReflectionFunction object
  • ReflectionFunction::export — Exports function
  • ReflectionFunction::getClosure — Returns a dynamically created closure for the function
  • ReflectionFunction::invoke — Invokes function
  • ReflectionFunction::invokeArgs — Invokes function args
  • ReflectionFunction::isDisabled — Checks if function is disabled
  • ReflectionFunction::__toString — To string


Constructs a ReflectionFunction object

  • « ReflectionFunction
  • ReflectionFunction::export »
  • PHP Manual
  • ReflectionFunction
  • Constructs a ReflectionFunction object

ReflectionFunction::__construct

(PHP 5, PHP 7)

ReflectionFunction::__construct — Constructs a ReflectionFunction object

Description

public ReflectionFunction::__construct ( mixed $name )

Constructs a ReflectionFunction object.

Parameters

name

The name of the function to reflect or a closure.

Return Values

No value is returned.

Errors/Exceptions

A ReflectionException if the name parameter does not contain a valid function.

Changelog

Version | Description
5.3.0 | name can now be a closure.

Examples

Example #1 ReflectionFunction::__construct() example

<?php
/**
 * A simple counter
 *
 * @return    int
 */
function counter1()
{
    static $c = 0;
    return ++$c;
}

/**
 * Another simple counter
 *
 * @return    int
 */
$counter2 = function()
{
    static $d = 0;
    return ++$d;

};

function dumpReflectionFunction($func)
{
    // Print out basic information
    printf(
        "\n\n===> The %s function '%s'\n".
        "     declared in %s\n".
        "     lines %d to %d\n",
        $func->isInternal() ? 'internal' : 'user-defined',
        $func->getName(),
        $func->getFileName(),
        $func->getStartLine(),
        $func->getEndline()
    );

    // Print documentation comment
    printf("---> Documentation:\n %s\n", var_export($func->getDocComment(), 1));

    // Print static variables if existant
    if ($statics = $func->getStaticVariables())
    {
        printf("---> Static variables: %s\n", var_export($statics, 1));
    }
}

// Create an instance of the ReflectionFunction class
dumpReflectionFunction(new ReflectionFunction('counter1'));
dumpReflectionFunction(new ReflectionFunction($counter2));
?>

The above example will output something similar to:

===> The user-defined function 'counter1'
     declared in Z:\reflectcounter.php
     lines 7 to 11
---> Documentation:
 '/**
 * A simple counter
 *
 * @return    int
 */'
---> Static variables: array (
  'c' => 0,
)

===> The user-defined function '{closure}'
     declared in Z:\reflectcounter.php
     lines 18 to 23
---> Documentation:
 '/**
 * Another simple counter
 *
 * @return    int
 */'
---> Static variables: array (
  'd' => 0,
)

See Also

  • ReflectionMethod::__construct() - Constructs a ReflectionMethod
  • Constructors


Exports function

  • « ReflectionFunction::__construct
  • ReflectionFunction::getClosure »
  • PHP Manual
  • ReflectionFunction
  • Exports function

ReflectionFunction::export

(PHP 5, PHP 7)

ReflectionFunction::export — Exports function

Description

public static ReflectionFunction::export ( string $name [, string $return ] ) : string

Exports a Reflected function.

Parameters

name

The reflection to export.

return

Setting to TRUE will return the export, as opposed to emitting it. Setting to FALSE (the default) will do the opposite.

Return Values

If the return parameter is set to TRUE, then the export is returned as a string, otherwise NULL is returned.

See Also

  • ReflectionFunction::invoke() - Invokes function


Returns a dynamically created closure for the function

  • « ReflectionFunction::export
  • ReflectionFunction::invoke »
  • PHP Manual
  • ReflectionFunction
  • Returns a dynamically created closure for the function

ReflectionFunction::getClosure

(PHP 5 >= 5.4.0, PHP 7)

ReflectionFunction::getClosure — Returns a dynamically created closure for the function

Description

public ReflectionFunction::getClosure ( void ) : Closure

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns Closure. Returns NULL in case of an error.


Invokes function

  • « ReflectionFunction::getClosure
  • ReflectionFunction::invokeArgs »
  • PHP Manual
  • ReflectionFunction
  • Invokes function

ReflectionFunction::invoke

(PHP 5, PHP 7)

ReflectionFunction::invoke — Invokes function

Description

public ReflectionFunction::invoke ([ mixed $... ] ) : mixed

Invokes a reflected function.

Parameters

...

The passed in argument list. It accepts a variable number of arguments which are passed to the function much like call_user_func() is.

Return Values

Returns the result of the invoked function call.

Examples

Example #1 ReflectionFunction::invoke() example

<?php
function title($title, $name)
{
    return sprintf("%s. %s\r\n", $title, $name);
}

$function = new ReflectionFunction('title');

echo $function->invoke('Dr', 'Phil');
?>

The above example will output:

Dr. Phil

Notes

Note:

If the function has arguments that need to be references, then they must be references in the passed argument list.

See Also

  • ReflectionFunction::export() - Exports function
  • __invoke()
  • call_user_func() - Call the callback given by the first parameter


Invokes function args

  • « ReflectionFunction::invoke
  • ReflectionFunction::isDisabled »
  • PHP Manual
  • ReflectionFunction
  • Invokes function args

ReflectionFunction::invokeArgs

(PHP 5 >= 5.1.2, PHP 7)

ReflectionFunction::invokeArgs — Invokes function args

Description

public ReflectionFunction::invokeArgs ( array $args ) : mixed

Invokes the function and pass its arguments as array.

Parameters

args

The passed arguments to the function as an array, much like call_user_func_array() works.

Return Values

Returns the result of the invoked function

Examples

Example #1 ReflectionFunction::invokeArgs() example

<?php
function title($title, $name)
{
    return sprintf("%s. %s\r\n", $title, $name);
}

$function = new ReflectionFunction('title');

echo $function->invokeArgs(array('Dr', 'Phil'));
?>

The above example will output:

Dr. Phil

Example #2 ReflectionFunction::invokeArgs() with references example

<?php
function get_false_conditions(array $conditions, array &$false_conditions)
{
    foreach ($conditions as $condition) {
        if (!$condition) {
            $false_conditions[] = $condition;
        }
    }
}

$function_ref     = new ReflectionFunction('get_false_conditions');

$conditions       = array(true, false, -1, 0, 1);
$false_conditions = array();

$function_ref->invokeArgs(array($conditions, &$false_conditions));

var_dump($false_conditions);
?>

The above example will output:

array(2) {
  [0]=>
  bool(false)
  [1]=>
  int(0)
}

Notes

Note:

If the function has arguments that need to be references, then they must be references in the passed argument list.

See Also

  • ReflectionFunction::invoke() - Invokes function
  • ReflectionFunctionAbstract::getNumberOfParameters() - Gets number of parameters
  • __invoke()
  • call_user_func_array() - Call a callback with an array of parameters


Checks if function is disabled

  • « ReflectionFunction::invokeArgs
  • ReflectionFunction::__toString »
  • PHP Manual
  • ReflectionFunction
  • Checks if function is disabled

ReflectionFunction::isDisabled

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunction::isDisabled — Checks if function is disabled

Description

public ReflectionFunction::isDisabled ( void ) : bool

Checks if the function is disabled, via the disable_functions directive.

Parameters

This function has no parameters.

Return Values

TRUE if it's disable, otherwise FALSE

See Also

  • ReflectionFunctionAbstract::isUserDefined() - Checks if user defined
  • disable_functions directive


To string

  • « ReflectionFunction::isDisabled
  • ReflectionFunctionAbstract »
  • PHP Manual
  • ReflectionFunction
  • To string

ReflectionFunction::__toString

(PHP 5, PHP 7)

ReflectionFunction::__toString — To string

Description

public ReflectionFunction::__toString ( void ) : string

To string.

Parameters

This function has no parameters.

Return Values

Returns ReflectionFunction::export()-like output for the function.

Examples

Example #1 ReflectionFunction::__toString() example

<?php
function title($title, $name)
{
    return sprintf("%s. %s\r\n", $title, $name);
}

echo new ReflectionFunction('title');
?>

The above example will output something similar to:

Function [ <user> function title ] {
  @@ Command line code 1 - 1

  - Parameters [2] {
    Parameter #0 [ <required> $title ]
    Parameter #1 [ <required> $name ]
  }
}

See Also

  • ReflectionFunction::export() - Exports function
  • ReflectionClass::clone()
  • __toString()


The ReflectionFunctionAbstract class

(PHP 5 >= 5.2.0, PHP 7)

Introduction

A parent class to ReflectionFunction, read its description for details.

Class synopsis

ReflectionFunctionAbstract implements Reflector {
/* Properties */
public $name ;
/* Methods */
final private __clone ( void ) : void
public getClosureScopeClass ( void ) : ReflectionClass
public getClosureThis ( void ) : object
public getDocComment ( void ) : string
public getEndLine ( void ) : int
public getExtension ( void ) : ReflectionExtension
public getExtensionName ( void ) : string
public getFileName ( void ) : string
public getName ( void ) : string
public getNamespaceName ( void ) : string
public getNumberOfParameters ( void ) : int
public getNumberOfRequiredParameters ( void ) : int
public getParameters ( void ) : array
public getReturnType ( void ) : ReflectionType
public getShortName ( void ) : string
public getStartLine ( void ) : int
public getStaticVariables ( void ) : array
public hasReturnType ( void ) : bool
public inNamespace ( void ) : bool
public isClosure ( void ) : bool
public isDeprecated ( void ) : bool
public isGenerator ( void ) : bool
public isInternal ( void ) : bool
public isUserDefined ( void ) : bool
public isVariadic ( void ) : bool
public returnsReference ( void ) : bool
abstract public __toString ( void ) : void
}

Properties

name

Name of the function. Read-only, throws ReflectionException in attempt to write.

Table of Contents

  • ReflectionFunctionAbstract::__clone — Clones function
  • ReflectionFunctionAbstract::getClosureScopeClass — Returns the scope associated to the closure
  • ReflectionFunctionAbstract::getClosureThis — Returns this pointer bound to closure
  • ReflectionFunctionAbstract::getDocComment — Gets doc comment
  • ReflectionFunctionAbstract::getEndLine — Gets end line number
  • ReflectionFunctionAbstract::getExtension — Gets extension info
  • ReflectionFunctionAbstract::getExtensionName — Gets extension name
  • ReflectionFunctionAbstract::getFileName — Gets file name
  • ReflectionFunctionAbstract::getName — Gets function name
  • ReflectionFunctionAbstract::getNamespaceName — Gets namespace name
  • ReflectionFunctionAbstract::getNumberOfParameters — Gets number of parameters
  • ReflectionFunctionAbstract::getNumberOfRequiredParameters — Gets number of required parameters
  • ReflectionFunctionAbstract::getParameters — Gets parameters
  • ReflectionFunctionAbstract::getReturnType — Gets the specified return type of a function
  • ReflectionFunctionAbstract::getShortName — Gets function short name
  • ReflectionFunctionAbstract::getStartLine — Gets starting line number
  • ReflectionFunctionAbstract::getStaticVariables — Gets static variables
  • ReflectionFunctionAbstract::hasReturnType — Checks if the function has a specified return type
  • ReflectionFunctionAbstract::inNamespace — Checks if function in namespace
  • ReflectionFunctionAbstract::isClosure — Checks if closure
  • ReflectionFunctionAbstract::isDeprecated — Checks if deprecated
  • ReflectionFunctionAbstract::isGenerator — Returns whether this function is a generator
  • ReflectionFunctionAbstract::isInternal — Checks if is internal
  • ReflectionFunctionAbstract::isUserDefined — Checks if user defined
  • ReflectionFunctionAbstract::isVariadic — Checks if the function is variadic
  • ReflectionFunctionAbstract::returnsReference — Checks if returns reference
  • ReflectionFunctionAbstract::__toString — To string


Clones function

  • « ReflectionFunctionAbstract
  • ReflectionFunctionAbstract::getClosureScopeClass »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Clones function

ReflectionFunctionAbstract::__clone

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::__clone — Clones function

Description

final private ReflectionFunctionAbstract::__clone ( void ) : void

Clones a function.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

See Also

  • Object cloning


Returns the scope associated to the closure

  • « ReflectionFunctionAbstract::__clone
  • ReflectionFunctionAbstract::getClosureThis »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Returns the scope associated to the closure

ReflectionFunctionAbstract::getClosureScopeClass

(PHP 5 >= 5.4.0, PHP 7)

ReflectionFunctionAbstract::getClosureScopeClass — Returns the scope associated to the closure

Description

public ReflectionFunctionAbstract::getClosureScopeClass ( void ) : ReflectionClass

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns the class on success or NULL on failure.


Returns this pointer bound to closure

  • « ReflectionFunctionAbstract::getClosureScopeClass
  • ReflectionFunctionAbstract::getDocComment »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Returns this pointer bound to closure

ReflectionFunctionAbstract::getClosureThis

(PHP 5 >= 5.4.0, PHP 7)

ReflectionFunctionAbstract::getClosureThis — Returns this pointer bound to closure

Description

public ReflectionFunctionAbstract::getClosureThis ( void ) : object

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns $this pointer. Returns NULL in case of an error.


Gets doc comment

  • « ReflectionFunctionAbstract::getClosureThis
  • ReflectionFunctionAbstract::getEndLine »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Gets doc comment

ReflectionFunctionAbstract::getDocComment

(PHP 5 >= 5.1.0, PHP 7)

ReflectionFunctionAbstract::getDocComment — Gets doc comment

Description

public ReflectionFunctionAbstract::getDocComment ( void ) : string

Get a Doc comment from a function.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The doc comment if it exists, otherwise FALSE

See Also

  • ReflectionFunctionAbstract::getStartLine() - Gets starting line number


Gets end line number

  • « ReflectionFunctionAbstract::getDocComment
  • ReflectionFunctionAbstract::getExtension »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Gets end line number

ReflectionFunctionAbstract::getEndLine

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::getEndLine — Gets end line number

Description

public ReflectionFunctionAbstract::getEndLine ( void ) : int

Get the ending line number.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The ending line number of the user defined function, or FALSE if unknown.

See Also

  • ReflectionFunctionAbstract::getStartLine() - Gets starting line number


Gets extension info

  • « ReflectionFunctionAbstract::getEndLine
  • ReflectionFunctionAbstract::getExtensionName »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Gets extension info

ReflectionFunctionAbstract::getExtension

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::getExtension — Gets extension info

Description

public ReflectionFunctionAbstract::getExtension ( void ) : ReflectionExtension

Get the extension information of a function.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The extension information, as a ReflectionExtension object.

See Also

  • ReflectionFunctionAbstract::getExtensionName() - Gets extension name


Gets extension name

  • « ReflectionFunctionAbstract::getExtension
  • ReflectionFunctionAbstract::getFileName »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Gets extension name

ReflectionFunctionAbstract::getExtensionName

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::getExtensionName — Gets extension name

Description

public ReflectionFunctionAbstract::getExtensionName ( void ) : string

Get the extensions name.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The extensions name.

See Also

  • ReflectionFunctionAbstract::getExtension() - Gets extension info


Gets file name

  • « ReflectionFunctionAbstract::getExtensionName
  • ReflectionFunctionAbstract::getName »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Gets file name

ReflectionFunctionAbstract::getFileName

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::getFileName — Gets file name

Description

public ReflectionFunctionAbstract::getFileName ( void ) : string

Gets the file name from a user-defined function.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The file name.

See Also

  • ReflectionFunctionAbstract::getNamespaceName() - Gets namespace name


Gets function name

  • « ReflectionFunctionAbstract::getFileName
  • ReflectionFunctionAbstract::getNamespaceName »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Gets function name

ReflectionFunctionAbstract::getName

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::getName — Gets function name

Description

public ReflectionFunctionAbstract::getName ( void ) : string

Get the name of the function.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The name of the function.

See Also

  • ReflectionFunctionAbstract::getExtensionName() - Gets extension name
  • ReflectionFunctionAbstract::isUserDefined() - Checks if user defined


Gets namespace name

  • « ReflectionFunctionAbstract::getName
  • ReflectionFunctionAbstract::getNumberOfParameters »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Gets namespace name

ReflectionFunctionAbstract::getNamespaceName

(PHP 5 >= 5.3.0, PHP 7)

ReflectionFunctionAbstract::getNamespaceName — Gets namespace name

Description

public ReflectionFunctionAbstract::getNamespaceName ( void ) : string

Get the namespace name where the class is defined.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The namespace name.

See Also

  • ReflectionFunctionAbstract::getFileName() - Gets file name
  • namespaces


Gets number of parameters

  • « ReflectionFunctionAbstract::getNamespaceName
  • ReflectionFunctionAbstract::getNumberOfRequiredParameters »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Gets number of parameters

ReflectionFunctionAbstract::getNumberOfParameters

(PHP 5 >= 5.3.0, PHP 7)

ReflectionFunctionAbstract::getNumberOfParameters — Gets number of parameters

Description

public ReflectionFunctionAbstract::getNumberOfParameters ( void ) : int

Get the number of parameters that a function defines, both optional and required.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The number of parameters.

See Also

  • ReflectionFunctionAbstract::getNumberOfRequiredParameters() - Gets number of required parameters
  • func_num_args() - Returns the number of arguments passed to the function


Gets number of required parameters

  • « ReflectionFunctionAbstract::getNumberOfParameters
  • ReflectionFunctionAbstract::getParameters »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Gets number of required parameters

ReflectionFunctionAbstract::getNumberOfRequiredParameters

(PHP 5 >= 5.3.0, PHP 7)

ReflectionFunctionAbstract::getNumberOfRequiredParameters — Gets number of required parameters

Description

public ReflectionFunctionAbstract::getNumberOfRequiredParameters ( void ) : int

Get the number of required parameters that a function defines.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The number of required parameters.

See Also

  • ReflectionFunctionAbstract::getNumberOfParameters() - Gets number of parameters


Gets parameters

  • « ReflectionFunctionAbstract::getNumberOfRequiredParameters
  • ReflectionFunctionAbstract::getReturnType »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Gets parameters

ReflectionFunctionAbstract::getParameters

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::getParameters — Gets parameters

Description

public ReflectionFunctionAbstract::getParameters ( void ) : array

Get the parameters as an array of ReflectionParameter.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The parameters, as a ReflectionParameter object.

See Also

  • ReflectionFunctionAbstract::getNumberOfParameters() - Gets number of parameters
  • func_get_args() - Returns an array comprising a function's argument list


Gets the specified return type of a function

  • « ReflectionFunctionAbstract::getParameters
  • ReflectionFunctionAbstract::getShortName »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Gets the specified return type of a function

ReflectionFunctionAbstract::getReturnType

(PHP 7)

ReflectionFunctionAbstract::getReturnType — Gets the specified return type of a function

Description

public ReflectionFunctionAbstract::getReturnType ( void ) : ReflectionType

Gets the specified return type of a reflected function.

Parameters

This function has no parameters.

Return Values

Returns a ReflectionType object if a return type is specified, NULL otherwise.

Examples

Example #1 ReflectionFunctionAbstract::getReturnType() example

<?php

function to_int($param) : int {
    return (int) $param;
}

$reflection1 = new ReflectionFunction('to_int');
echo $reflection1->getReturnType();

The above example will output:

int

Example #2 Usage on built-in functions

<?php

$reflection2 = new ReflectionFunction('array_merge');

var_dump($reflection2->getReturnType());

The above example will output:

null

This is because many internal functions do not have types specified for their parameters or return values. It is therefore best to avoid using this method on built-in functions.

See Also

  • ReflectionFunctionAbstract::hasReturnType() - Checks if the function has a specified return type
  • ReflectionType::__toString() - To string


Gets function short name

  • « ReflectionFunctionAbstract::getReturnType
  • ReflectionFunctionAbstract::getStartLine »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Gets function short name

ReflectionFunctionAbstract::getShortName

(PHP 5 >= 5.3.0, PHP 7)

ReflectionFunctionAbstract::getShortName — Gets function short name

Description

public ReflectionFunctionAbstract::getShortName ( void ) : string

Get the short name of the function (without the namespace part).

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The short name of the function.

See Also

  • ReflectionFunctionAbstract::getNamespaceName() - Gets namespace name
  • namespaces


Gets starting line number

  • « ReflectionFunctionAbstract::getShortName
  • ReflectionFunctionAbstract::getStaticVariables »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Gets starting line number

ReflectionFunctionAbstract::getStartLine

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::getStartLine — Gets starting line number

Description

public ReflectionFunctionAbstract::getStartLine ( void ) : int

Gets the starting line number of the function.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The starting line number.

See Also

  • ReflectionFunctionAbstract::getEndLine() - Gets end line number


Gets static variables

  • « ReflectionFunctionAbstract::getStartLine
  • ReflectionFunctionAbstract::hasReturnType »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Gets static variables

ReflectionFunctionAbstract::getStaticVariables

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::getStaticVariables — Gets static variables

Description

public ReflectionFunctionAbstract::getStaticVariables ( void ) : array

Get the static variables.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

An array of static variables.

See Also

  • ReflectionFunctionAbstract::getParameters() - Gets parameters


Checks if the function has a specified return type

  • « ReflectionFunctionAbstract::getStaticVariables
  • ReflectionFunctionAbstract::inNamespace »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Checks if the function has a specified return type

ReflectionFunctionAbstract::hasReturnType

(PHP 7)

ReflectionFunctionAbstract::hasReturnType — Checks if the function has a specified return type

Description

public ReflectionFunctionAbstract::hasReturnType ( void ) : bool

Checks whether the reflected function has a return type specified.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the function is a specified return type, otherwise FALSE.

Examples

Example #1 ReflectionFunctionAbstract::hasReturnType() example

<?php

function to_int($param) : int {
    return (int) $param;
}

$reflection1 = new ReflectionFunction('to_int');
var_dump($reflection1->hasReturnType());

The above example will output:

bool(true)

Example #2 Usage on built-in functions

<?php

$reflection2 = new ReflectionFunction('array_merge');

var_dump($reflection2->hasReturnType());

The above example will output:

bool(false)

This is because many internal functions do not have types specified for their parameters or return values. It is therefore best to avoid using this method on built-in functions.

See Also

  • ReflectionFunctionAbstract::getReturnType() - Gets the specified return type of a function


Checks if function in namespace

  • « ReflectionFunctionAbstract::hasReturnType
  • ReflectionFunctionAbstract::isClosure »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Checks if function in namespace

ReflectionFunctionAbstract::inNamespace

(PHP 5 >= 5.3.0, PHP 7)

ReflectionFunctionAbstract::inNamespace — Checks if function in namespace

Description

public ReflectionFunctionAbstract::inNamespace ( void ) : bool

Checks whether a function is defined in a namespace.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

TRUE if it's in a namespace, otherwise FALSE

See Also

  • ReflectionFunctionAbstract::getNamespaceName() - Gets namespace name
  • namespaces


Checks if closure

  • « ReflectionFunctionAbstract::inNamespace
  • ReflectionFunctionAbstract::isDeprecated »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Checks if closure

ReflectionFunctionAbstract::isClosure

(PHP 5 >= 5.3.0, PHP 7)

ReflectionFunctionAbstract::isClosure — Checks if closure

Description

public ReflectionFunctionAbstract::isClosure ( void ) : bool

Checks whether the reflected function is a Closure.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the function is a Closure, otherwise FALSE.

Examples

Example #1 ReflectionFunctionAbstract::isClosure() example

<?php
// Non-closure
$function1 = 'str_replace';
$reflection1 = new ReflectionFunction($function1);
var_dump($reflection1->isClosure());

// Closure
$function2 = function () {};
$reflection2 = new ReflectionFunction($function2);
var_dump($reflection2->isClosure());
?>

The above example will output:

bool(false)
bool(true)

See Also

  • ReflectionFunctionAbstract::isGenerator() - Returns whether this function is a generator


Checks if deprecated

  • « ReflectionFunctionAbstract::isClosure
  • ReflectionFunctionAbstract::isGenerator »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Checks if deprecated

ReflectionFunctionAbstract::isDeprecated

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::isDeprecated — Checks if deprecated

Description

public ReflectionFunctionAbstract::isDeprecated ( void ) : bool

Checks whether the function is deprecated.

Parameters

This function has no parameters.

Return Values

TRUE if it's deprecated, otherwise FALSE

Examples

Example #1 ReflectionFunctionAbstract::isDeprecated() example

<?php
$rf = new ReflectionFunction('ereg');
var_dump($rf->isDeprecated());
?>

The above example will output:

bool(true)

See Also

  • ReflectionFunctionAbstract::getDocComment() - Gets doc comment


Returns whether this function is a generator

  • « ReflectionFunctionAbstract::isDeprecated
  • ReflectionFunctionAbstract::isInternal »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Returns whether this function is a generator

ReflectionFunctionAbstract::isGenerator

(PHP 5 >= 5.5.0, PHP 7)

ReflectionFunctionAbstract::isGenerator — Returns whether this function is a generator

Description

public ReflectionFunctionAbstract::isGenerator ( void ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the function is generator, FALSE if it is not or NULL on failure.


Checks if is internal

  • « ReflectionFunctionAbstract::isGenerator
  • ReflectionFunctionAbstract::isUserDefined »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Checks if is internal

ReflectionFunctionAbstract::isInternal

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::isInternal — Checks if is internal

Description

public ReflectionFunctionAbstract::isInternal ( void ) : bool

Checks whether the function is internal, as opposed to user-defined.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

TRUE if it's internal, otherwise FALSE

See Also

  • ReflectionFunctionAbstract::isUserDefined() - Checks if user defined


Checks if user defined

  • « ReflectionFunctionAbstract::isInternal
  • ReflectionFunctionAbstract::isVariadic »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Checks if user defined

ReflectionFunctionAbstract::isUserDefined

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::isUserDefined — Checks if user defined

Description

public ReflectionFunctionAbstract::isUserDefined ( void ) : bool

Checks whether the function is user-defined, as opposed to internal.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

TRUE if it's user-defined, otherwise false;

See Also

  • ReflectionFunctionAbstract::isInternal() - Checks if is internal


Checks if the function is variadic

  • « ReflectionFunctionAbstract::isUserDefined
  • ReflectionFunctionAbstract::returnsReference »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Checks if the function is variadic

ReflectionFunctionAbstract::isVariadic

(PHP 5 >= 5.6.0, PHP 7)

ReflectionFunctionAbstract::isVariadic — Checks if the function is variadic

Description

public ReflectionFunctionAbstract::isVariadic ( void ) : bool

Checks if the function is variadic.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the function is variadic, otherwise FALSE.


Checks if returns reference

  • « ReflectionFunctionAbstract::isVariadic
  • ReflectionFunctionAbstract::__toString »
  • PHP Manual
  • ReflectionFunctionAbstract
  • Checks if returns reference

ReflectionFunctionAbstract::returnsReference

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::returnsReference — Checks if returns reference

Description

public ReflectionFunctionAbstract::returnsReference ( void ) : bool

Checks whether the function returns a reference.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

TRUE if it returns a reference, otherwise FALSE

See Also

  • ReflectionFunctionAbstract::isClosure() - Checks if closure


To string

  • « ReflectionFunctionAbstract::returnsReference
  • ReflectionMethod »
  • PHP Manual
  • ReflectionFunctionAbstract
  • To string

ReflectionFunctionAbstract::__toString

(PHP 5 >= 5.2.0, PHP 7)

ReflectionFunctionAbstract::__toString — To string

Description

abstract public ReflectionFunctionAbstract::__toString ( void ) : void

To string.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The string.

See Also

  • ReflectionClass::clone()
  • __toString()


The ReflectionMethod class

(PHP 5, PHP 7)

Introduction

The ReflectionMethod class reports information about a method.

Class synopsis

ReflectionMethod extends ReflectionFunctionAbstract implements Reflector {
/* Constants */
const integer IS_STATIC = 1 ;
const integer IS_PUBLIC = 256 ;
const integer IS_PROTECTED = 512 ;
const integer IS_PRIVATE = 1024 ;
const integer IS_ABSTRACT = 2 ;
const integer IS_FINAL = 4 ;
/* Properties */
public $name ;
public $class ;
/* Methods */
public __construct ( mixed $class , string $name )
public static export ( string $class , string $name [, bool $return = FALSE ] ) : string
public getClosure ( object $object ) : Closure
public getDeclaringClass ( void ) : ReflectionClass
public getModifiers ( void ) : int
public getPrototype ( void ) : ReflectionMethod
public invoke ( object $object [, mixed $... ] ) : mixed
public invokeArgs ( object $object , array $args ) : mixed
public isAbstract ( void ) : bool
public isConstructor ( void ) : bool
public isDestructor ( void ) : bool
public isFinal ( void ) : bool
public isPrivate ( void ) : bool
public isProtected ( void ) : bool
public isPublic ( void ) : bool
public isStatic ( void ) : bool
public setAccessible ( bool $accessible ) : void
public __toString ( void ) : string
/* Inherited methods */
final private ReflectionFunctionAbstract::__clone ( void ) : void
public ReflectionFunctionAbstract::getClosureScopeClass ( void ) : ReflectionClass
public ReflectionFunctionAbstract::getClosureThis ( void ) : object
public ReflectionFunctionAbstract::getDocComment ( void ) : string
public ReflectionFunctionAbstract::getEndLine ( void ) : int
public ReflectionFunctionAbstract::getExtension ( void ) : ReflectionExtension
public ReflectionFunctionAbstract::getExtensionName ( void ) : string
public ReflectionFunctionAbstract::getFileName ( void ) : string
public ReflectionFunctionAbstract::getName ( void ) : string
public ReflectionFunctionAbstract::getNamespaceName ( void ) : string
public ReflectionFunctionAbstract::getNumberOfParameters ( void ) : int
public ReflectionFunctionAbstract::getNumberOfRequiredParameters ( void ) : int
public ReflectionFunctionAbstract::getParameters ( void ) : array
public ReflectionFunctionAbstract::getReturnType ( void ) : ReflectionType
public ReflectionFunctionAbstract::getShortName ( void ) : string
public ReflectionFunctionAbstract::getStartLine ( void ) : int
public ReflectionFunctionAbstract::getStaticVariables ( void ) : array
public ReflectionFunctionAbstract::hasReturnType ( void ) : bool
public ReflectionFunctionAbstract::inNamespace ( void ) : bool
public ReflectionFunctionAbstract::isClosure ( void ) : bool
public ReflectionFunctionAbstract::isDeprecated ( void ) : bool
public ReflectionFunctionAbstract::isGenerator ( void ) : bool
public ReflectionFunctionAbstract::isInternal ( void ) : bool
public ReflectionFunctionAbstract::isUserDefined ( void ) : bool
public ReflectionFunctionAbstract::isVariadic ( void ) : bool
public ReflectionFunctionAbstract::returnsReference ( void ) : bool
abstract public ReflectionFunctionAbstract::__toString ( void ) : void
}

Properties

name

Method name

class

Class name

Predefined Constants

ReflectionMethod Modifiers

ReflectionMethod::IS_STATIC

Indicates that the method is static.

ReflectionMethod::IS_PUBLIC

Indicates that the method is public.

ReflectionMethod::IS_PROTECTED

Indicates that the method is protected.

ReflectionMethod::IS_PRIVATE

Indicates that the method is private.

ReflectionMethod::IS_ABSTRACT

Indicates that the method is abstract.

ReflectionMethod::IS_FINAL

Indicates that the method is final.

Table of Contents

  • ReflectionMethod::__construct — Constructs a ReflectionMethod
  • ReflectionMethod::export — Export a reflection method
  • ReflectionMethod::getClosure — Returns a dynamically created closure for the method
  • ReflectionMethod::getDeclaringClass — Gets declaring class for the reflected method
  • ReflectionMethod::getModifiers — Gets the method modifiers
  • ReflectionMethod::getPrototype — Gets the method prototype (if there is one)
  • ReflectionMethod::invoke — Invoke
  • ReflectionMethod::invokeArgs — Invoke args
  • ReflectionMethod::isAbstract — Checks if method is abstract
  • ReflectionMethod::isConstructor — Checks if method is a constructor
  • ReflectionMethod::isDestructor — Checks if method is a destructor
  • ReflectionMethod::isFinal — Checks if method is final
  • ReflectionMethod::isPrivate — Checks if method is private
  • ReflectionMethod::isProtected — Checks if method is protected
  • ReflectionMethod::isPublic — Checks if method is public
  • ReflectionMethod::isStatic — Checks if method is static
  • ReflectionMethod::setAccessible — Set method accessibility
  • ReflectionMethod::__toString — Returns the string representation of the Reflection method object


Constructs a ReflectionMethod

  • « ReflectionMethod
  • ReflectionMethod::export »
  • PHP Manual
  • ReflectionMethod
  • Constructs a ReflectionMethod

ReflectionMethod::__construct

(PHP 5, PHP 7)

ReflectionMethod::__construct — Constructs a ReflectionMethod

Description

public ReflectionMethod::__construct ( mixed $class , string $name )
public ReflectionMethod::__construct ( string $class_method )

Constructs a new ReflectionMethod.

Parameters

class

Classname or object (instance of the class) that contains the method.

name

Name of the method.

class_method

Class name and method name delimited by ::.

Return Values

No value is returned.

Errors/Exceptions

A ReflectionException is thrown if the given method does not exist.

Examples

Example #1 ReflectionMethod::__construct() example

<?php
class Counter
{
    private static $c = 0;

    /**
     * Increment counter
     *
     * @final
     * @static
     * @access  public
     * @return  int
     */
    final public static function increment()
    {
        return ++self::$c;
    }
}

// Create an instance of the ReflectionMethod class
$method = new ReflectionMethod('Counter', 'increment');

// Print out basic information
printf(
    "===> The %s%s%s%s%s%s%s method '%s' (which is %s)\n" .
    "     declared in %s\n" .
    "     lines %d to %d\n" .
    "     having the modifiers %d[%s]\n",
        $method->isInternal() ? 'internal' : 'user-defined',
        $method->isAbstract() ? ' abstract' : '',
        $method->isFinal() ? ' final' : '',
        $method->isPublic() ? ' public' : '',
        $method->isPrivate() ? ' private' : '',
        $method->isProtected() ? ' protected' : '',
        $method->isStatic() ? ' static' : '',
        $method->getName(),
        $method->isConstructor() ? 'the constructor' : 'a regular method',
        $method->getFileName(),
        $method->getStartLine(),
        $method->getEndline(),
        $method->getModifiers(),
        implode(' ', Reflection::getModifierNames($method->getModifiers()))
);

// Print documentation comment
printf("---> Documentation:\n %s\n", var_export($method->getDocComment(), true));

// Print static variables if existant
if ($statics= $method->getStaticVariables()) {
    printf("---> Static variables: %s\n", var_export($statics, true));
}

// Invoke the method
printf("---> Invocation results in: ");
var_dump($method->invoke(NULL));
?>

The above example will output something similar to:

===> The user-defined final public static method 'increment' (which is a regular method)
     declared in /Users/philip/cvs/phpdoc/test.php
     lines 14 to 17
     having the modifiers 261[final public static]
---> Documentation:
 '/**
     * Increment counter
     *
     * @final
     * @static
     * @access  public
     * @return  int
     */'
---> Invocation results in: int(1)

See Also

  • ReflectionMethod::export() - Export a reflection method
  • Constructors


Export a reflection method

  • « ReflectionMethod::__construct
  • ReflectionMethod::getClosure »
  • PHP Manual
  • ReflectionMethod
  • Export a reflection method

ReflectionMethod::export

(PHP 5, PHP 7)

ReflectionMethod::export — Export a reflection method

Description

public static ReflectionMethod::export ( string $class , string $name [, bool $return = FALSE ] ) : string

Exports a ReflectionMethod.

Warning

This function is currently not documented; only its argument list is available.

Parameters

class

The class name.

name

The name of the method.

return

Setting to TRUE will return the export, as opposed to emitting it. Setting to FALSE (the default) will do the opposite.

Return Values

If the return parameter is set to TRUE, then the export is returned as a string, otherwise NULL is returned.

See Also

  • ReflectionMethod::__construct() - Constructs a ReflectionMethod
  • ReflectionMethod::__toString() - Returns the string representation of the Reflection method object


Returns a dynamically created closure for the method

  • « ReflectionMethod::export
  • ReflectionMethod::getDeclaringClass »
  • PHP Manual
  • ReflectionMethod
  • Returns a dynamically created closure for the method

ReflectionMethod::getClosure

(PHP 5 >= 5.4.0, PHP 7)

ReflectionMethod::getClosure — Returns a dynamically created closure for the method

Description

public ReflectionMethod::getClosure ( object $object ) : Closure
public ReflectionMethod::getClosure ( void ) : Closure

Warning

This function is currently not documented; only its argument list is available.

Parameters

object

Forbidden for static methods, required for other methods.

Return Values

Returns Closure. Returns NULL in case of an error.


Gets declaring class for the reflected method

  • « ReflectionMethod::getClosure
  • ReflectionMethod::getModifiers »
  • PHP Manual
  • ReflectionMethod
  • Gets declaring class for the reflected method

ReflectionMethod::getDeclaringClass

(PHP 5, PHP 7)

ReflectionMethod::getDeclaringClass — Gets declaring class for the reflected method

Description

public ReflectionMethod::getDeclaringClass ( void ) : ReflectionClass

Gets the declaring class for the reflected method.

Parameters

This function has no parameters.

Return Values

A ReflectionClass object of the class that the reflected method is part of.

Examples

Example #1 ReflectionMethod::getDeclaringClass() example

<?php
class HelloWorld {

    protected function sayHelloTo($name) {
        return 'Hello ' . $name;
    }

}

$reflectionMethod = new ReflectionMethod(new HelloWorld(), 'sayHelloTo');
var_dump($reflectionMethod->getDeclaringClass());
?>

The above example will output:

object(ReflectionClass)#2 (1) {
  ["name"]=>
  string(10) "HelloWorld"
}

See Also

  • ReflectionMethod::isAbstract() - Checks if method is abstract


Gets the method modifiers

  • « ReflectionMethod::getDeclaringClass
  • ReflectionMethod::getPrototype »
  • PHP Manual
  • ReflectionMethod
  • Gets the method modifiers

ReflectionMethod::getModifiers

(PHP 5, PHP 7)

ReflectionMethod::getModifiers — Gets the method modifiers

Description

public ReflectionMethod::getModifiers ( void ) : int

Returns a bitfield of the access modifiers for this method.

Parameters

This function has no parameters.

Return Values

A numeric representation of the modifiers. The modifiers are listed below. The actual meanings of these modifiers are described in the predefined constants.

Examples

Example #1 ReflectionMethod::getModifiers() example

<?php
class Testing
{
    final public static function foo()
    {
        return;
    }
    public function bar()
    {
        return;
    }
}

$foo = new ReflectionMethod('Testing', 'foo');

echo "Modifiers for method foo():\n";
echo $foo->getModifiers() . "\n";
echo implode(' ', Reflection::getModifierNames($foo->getModifiers())) . "\n";

$bar = new ReflectionMethod('Testing', 'bar');

echo "Modifiers for method bar():\n";
echo $bar->getModifiers() . "\n";
echo implode(' ', Reflection::getModifierNames($bar->getModifiers()));
?>

The above example will output something similar to:

Modifiers for method foo():
261
final public static
Modifiers for method bar():
65792
public

See Also

  • Reflection::getModifierNames() - Gets modifier names


Gets the method prototype (if there is one)

  • « ReflectionMethod::getModifiers
  • ReflectionMethod::invoke »
  • PHP Manual
  • ReflectionMethod
  • Gets the method prototype (if there is one)

ReflectionMethod::getPrototype

(PHP 5 >= 5.1.2, PHP 7)

ReflectionMethod::getPrototype — Gets the method prototype (if there is one)

Description

public ReflectionMethod::getPrototype ( void ) : ReflectionMethod

Returns the methods prototype.

Parameters

This function has no parameters.

Return Values

A ReflectionMethod instance of the method prototype.

Errors/Exceptions

A ReflectionException exception is thrown if the method does not have a prototype.

Examples

Example #1 ReflectionMethod::getPrototype() example

<?php
class Hello {

    public function sayHelloTo($name) {
        return 'Hello ' . $name;
    }

}
class HelloWorld extends Hello {

    public function sayHelloTo($name) {
        return 'Hello world: ' . $name;
    }

}

$reflectionMethod = new ReflectionMethod('HelloWorld', 'sayHelloTo');
var_dump($reflectionMethod->getPrototype());
?>

The above example will output:

object(ReflectionMethod)#2 (2) {
  ["name"]=>
  string(10) "sayHelloTo"
  ["class"]=>
  string(5) "Hello"
}

See Also

  • ReflectionMethod::getModifiers() - Gets the method modifiers


Invoke

  • « ReflectionMethod::getPrototype
  • ReflectionMethod::invokeArgs »
  • PHP Manual
  • ReflectionMethod
  • Invoke

ReflectionMethod::invoke

(PHP 5, PHP 7)

ReflectionMethod::invoke — Invoke

Description

public ReflectionMethod::invoke ( object $object [, mixed $... ] ) : mixed

Invokes a reflected method.

Parameters

object

The object to invoke the method on. For static methods, pass null to this parameter.

...

Zero or more parameters to be passed to the method. It accepts a variable number of parameters which are passed to the method.

Return Values

Returns the method result.

Errors/Exceptions

A ReflectionException if the object parameter does not contain an instance of the class that this method was declared in.

A ReflectionException if the method invocation failed.

Examples

Example #1 ReflectionMethod::invoke() example

<?php
class HelloWorld {

    public function sayHelloTo($name) {
        return 'Hello ' . $name;
    }

}

$reflectionMethod = new ReflectionMethod('HelloWorld', 'sayHelloTo');
echo $reflectionMethod->invoke(new HelloWorld(), 'Mike');
?>

The above example will output:

Hello Mike

Notes

Note:

If the function has arguments that need to be references, then they must be references in the passed argument list.

See Also

  • ReflectionMethod::invokeArgs() - Invoke args
  • __invoke()
  • call_user_func() - Call the callback given by the first parameter


Invoke args

  • « ReflectionMethod::invoke
  • ReflectionMethod::isAbstract »
  • PHP Manual
  • ReflectionMethod
  • Invoke args

ReflectionMethod::invokeArgs

(PHP 5 >= 5.1.2, PHP 7)

ReflectionMethod::invokeArgs — Invoke args

Description

public ReflectionMethod::invokeArgs ( object $object , array $args ) : mixed

Invokes the reflected method and pass its arguments as array.

Parameters

object

The object to invoke the method on. In case of static methods, you can pass null to this parameter.

args

The parameters to be passed to the function, as an array.

Return Values

Returns the method result.

Errors/Exceptions

A ReflectionException if the object parameter does not contain an instance of the class that this method was declared in.

A ReflectionException if the method invocation failed.

Examples

Example #1 ReflectionMethod::invokeArgs() example

<?php
class HelloWorld {

    public function sayHelloTo($name) {
        return 'Hello ' . $name;
    }

}

$reflectionMethod = new ReflectionMethod('HelloWorld', 'sayHelloTo');
echo $reflectionMethod->invokeArgs(new HelloWorld(), array('Mike'));
?>

The above example will output:

Hello Mike

Notes

Note:

If the function has arguments that need to be references, then they must be references in the passed argument list.

See Also

  • ReflectionMethod::invoke() - Invoke
  • __invoke()
  • call_user_func_array() - Call a callback with an array of parameters


Checks if method is abstract

  • « ReflectionMethod::invokeArgs
  • ReflectionMethod::isConstructor »
  • PHP Manual
  • ReflectionMethod
  • Checks if method is abstract

ReflectionMethod::isAbstract

(PHP 5, PHP 7)

ReflectionMethod::isAbstract — Checks if method is abstract

Description

public ReflectionMethod::isAbstract ( void ) : bool

Checks if the method is abstract.

Parameters

This function has no parameters.

Return Values

TRUE if the method is abstract, otherwise FALSE

See Also

  • ReflectionMethod::getDeclaringClass() - Gets declaring class for the reflected method


Checks if method is a constructor

  • « ReflectionMethod::isAbstract
  • ReflectionMethod::isDestructor »
  • PHP Manual
  • ReflectionMethod
  • Checks if method is a constructor

ReflectionMethod::isConstructor

(PHP 5, PHP 7)

ReflectionMethod::isConstructor — Checks if method is a constructor

Description

public ReflectionMethod::isConstructor ( void ) : bool

Checks if the method is a constructor.

Parameters

This function has no parameters.

Return Values

TRUE if the method is a constructor, otherwise FALSE

See Also

  • ReflectionMethod::__construct() - Constructs a ReflectionMethod
  • ReflectionMethod::isAbstract() - Checks if method is abstract
  • ReflectionMethod::isDestructor() - Checks if method is a destructor


Checks if method is a destructor

  • « ReflectionMethod::isConstructor
  • ReflectionMethod::isFinal »
  • PHP Manual
  • ReflectionMethod
  • Checks if method is a destructor

ReflectionMethod::isDestructor

(PHP 5, PHP 7)

ReflectionMethod::isDestructor — Checks if method is a destructor

Description

public ReflectionMethod::isDestructor ( void ) : bool

Checks if the method is a destructor.

Parameters

This function has no parameters.

Return Values

TRUE if the method is a destructor, otherwise FALSE

See Also

  • ReflectionMethod::isConstructor() - Checks if method is a constructor


Checks if method is final

  • « ReflectionMethod::isDestructor
  • ReflectionMethod::isPrivate »
  • PHP Manual
  • ReflectionMethod
  • Checks if method is final

ReflectionMethod::isFinal

(PHP 5, PHP 7)

ReflectionMethod::isFinal — Checks if method is final

Description

public ReflectionMethod::isFinal ( void ) : bool

Checks if the method is final.

Parameters

This function has no parameters.

Return Values

TRUE if the method is final, otherwise FALSE

See Also

  • ReflectionMethod::isStatic() - Checks if method is static


Checks if method is private

  • « ReflectionMethod::isFinal
  • ReflectionMethod::isProtected »
  • PHP Manual
  • ReflectionMethod
  • Checks if method is private

ReflectionMethod::isPrivate

(PHP 5, PHP 7)

ReflectionMethod::isPrivate — Checks if method is private

Description

public ReflectionMethod::isPrivate ( void ) : bool

Checks if the method is private.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

TRUE if the method is private, otherwise FALSE

See Also

  • ReflectionMethod::isPublic() - Checks if method is public


Checks if method is protected

  • « ReflectionMethod::isPrivate
  • ReflectionMethod::isPublic »
  • PHP Manual
  • ReflectionMethod
  • Checks if method is protected

ReflectionMethod::isProtected

(PHP 5, PHP 7)

ReflectionMethod::isProtected — Checks if method is protected

Description

public ReflectionMethod::isProtected ( void ) : bool

Checks if the method is protected.

Parameters

This function has no parameters.

Return Values

TRUE if the method is protected, otherwise FALSE

See Also

  • ReflectionMethod::isPrivate() - Checks if method is private


Checks if method is public

  • « ReflectionMethod::isProtected
  • ReflectionMethod::isStatic »
  • PHP Manual
  • ReflectionMethod
  • Checks if method is public

ReflectionMethod::isPublic

(PHP 5, PHP 7)

ReflectionMethod::isPublic — Checks if method is public

Description

public ReflectionMethod::isPublic ( void ) : bool

Checks if the method is public.

Parameters

This function has no parameters.

Return Values

TRUE if the method is public, otherwise FALSE

See Also

  • ReflectionMethod::isPrivate() - Checks if method is private


Checks if method is static

  • « ReflectionMethod::isPublic
  • ReflectionMethod::setAccessible »
  • PHP Manual
  • ReflectionMethod
  • Checks if method is static

ReflectionMethod::isStatic

(PHP 5, PHP 7)

ReflectionMethod::isStatic — Checks if method is static

Description

public ReflectionMethod::isStatic ( void ) : bool

Checks if the method is static.

Parameters

This function has no parameters.

Return Values

TRUE if the method is static, otherwise FALSE

See Also

  • ReflectionMethod::isFinal() - Checks if method is final


Set method accessibility

  • « ReflectionMethod::isStatic
  • ReflectionMethod::__toString »
  • PHP Manual
  • ReflectionMethod
  • Set method accessibility

ReflectionMethod::setAccessible

(PHP 5 >= 5.3.2, PHP 7)

ReflectionMethod::setAccessible — Set method accessibility

Description

public ReflectionMethod::setAccessible ( bool $accessible ) : void

Sets a method to be accessible. For example, it may allow protected and private methods to be invoked.

Parameters

accessible

TRUE to allow accessibility, or FALSE.

Return Values

No value is returned.

See Also

  • ReflectionMethod::isPrivate() - Checks if method is private
  • ReflectionMethod::isProtected() - Checks if method is protected


Returns the string representation of the Reflection method object

  • « ReflectionMethod::setAccessible
  • ReflectionNamedType »
  • PHP Manual
  • ReflectionMethod
  • Returns the string representation of the Reflection method object

ReflectionMethod::__toString

(PHP 5, PHP 7)

ReflectionMethod::__toString — Returns the string representation of the Reflection method object

Description

public ReflectionMethod::__toString ( void ) : string

Returns the string representation of the Reflection method object.

Parameters

This function has no parameters.

Return Values

A string representation of this ReflectionMethod instance.

Examples

Example #1 ReflectionMethod::__toString() example

<?php
class HelloWorld {

    public function sayHelloTo($name) {
        return 'Hello ' . $name;
    }

}

$reflectionMethod = new ReflectionMethod(new HelloWorld(), 'sayHelloTo');
echo $reflectionMethod;
?>

The above example will output:

Method [ <user> public method sayHelloTo ] {
  @@ /var/www/examples/reflection.php 16 - 18

  - Parameters [1] {
    Parameter #0 [ <required> $name ]
  }
}

See Also

  • ReflectionMethod::export() - Export a reflection method
  • __toString()


The ReflectionNamedType class

(PHP 7 >= 7.1.0)

Introduction

Class synopsis

ReflectionNamedType extends ReflectionType {
/* Methods */
public getName ( void ) : string
/* Inherited methods */
public ReflectionType::allowsNull ( void ) : bool
public ReflectionType::isBuiltin ( void ) : bool
public ReflectionType::__toString ( void ) : string
}

Table of Contents

  • ReflectionNamedType::getName — Get the text of the type hint


Get the text of the type hint

  • « ReflectionNamedType
  • ReflectionObject »
  • PHP Manual
  • ReflectionNamedType
  • Get the text of the type hint

ReflectionNamedType::getName

(PHP 7 >= 7.1.0)

ReflectionNamedType::getName — Get the text of the type hint

Description

public ReflectionNamedType::getName ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns the text of the type hint.

See Also

  • ReflectionType::__toString() - To string


The ReflectionObject class

(PHP 5, PHP 7)

Introduction

The ReflectionObject class reports information about an object.

Class synopsis

ReflectionObject extends ReflectionClass implements Reflector {
/* Inherited constants */
const integer ReflectionClass::IS_IMPLICIT_ABSTRACT = 16 ;
const integer ReflectionClass::IS_EXPLICIT_ABSTRACT = 32 ;
const integer ReflectionClass::IS_FINAL = 64 ;
/* Properties */
public $name ;
/* Methods */
public __construct ( object $argument )
public static export ( string $argument [, bool $return ] ) : string
/* Inherited methods */
public ReflectionClass::__construct ( mixed $argument )
public static ReflectionClass::export ( mixed $argument [, bool $return = FALSE ] ) : string
public ReflectionClass::getConstant ( string $name ) : mixed
public ReflectionClass::getConstants ( void ) : array
public ReflectionClass::getConstructor ( void ) : ReflectionMethod
public ReflectionClass::getDefaultProperties ( void ) : array
public ReflectionClass::getDocComment ( void ) : string
public ReflectionClass::getEndLine ( void ) : int
public ReflectionClass::getExtension ( void ) : ReflectionExtension
public ReflectionClass::getExtensionName ( void ) : string
public ReflectionClass::getFileName ( void ) : string
public ReflectionClass::getInterfaceNames ( void ) : array
public ReflectionClass::getInterfaces ( void ) : array
public ReflectionClass::getMethod ( string $name ) : ReflectionMethod
public ReflectionClass::getMethods ([ int $filter ] ) : array
public ReflectionClass::getModifiers ( void ) : int
public ReflectionClass::getName ( void ) : string
public ReflectionClass::getNamespaceName ( void ) : string
public ReflectionClass::getParentClass ( void ) : ReflectionClass
public ReflectionClass::getProperties ([ int $filter ] ) : array
public ReflectionClass::getProperty ( string $name ) : ReflectionProperty
public ReflectionClass::getReflectionConstant ( string $name ) : ReflectionClassConstant
public ReflectionClass::getReflectionConstants ( void ) : array
public ReflectionClass::getShortName ( void ) : string
public ReflectionClass::getStartLine ( void ) : int
public ReflectionClass::getStaticProperties ( void ) : array
public ReflectionClass::getStaticPropertyValue ( string $name [, mixed &$def_value ] ) : mixed
public ReflectionClass::getTraitAliases ( void ) : array
public ReflectionClass::getTraitNames ( void ) : array
public ReflectionClass::getTraits ( void ) : array
public ReflectionClass::hasConstant ( string $name ) : bool
public ReflectionClass::hasMethod ( string $name ) : bool
public ReflectionClass::hasProperty ( string $name ) : bool
public ReflectionClass::implementsInterface ( string $interface ) : bool
public ReflectionClass::inNamespace ( void ) : bool
public ReflectionClass::isAbstract ( void ) : bool
public ReflectionClass::isAnonymous ( void ) : bool
public ReflectionClass::isCloneable ( void ) : bool
public ReflectionClass::isFinal ( void ) : bool
public ReflectionClass::isInstance ( object $object ) : bool
public ReflectionClass::isInstantiable ( void ) : bool
public ReflectionClass::isInterface ( void ) : bool
public ReflectionClass::isInternal ( void ) : bool
public ReflectionClass::isIterable ( void ) : bool
public ReflectionClass::isSubclassOf ( mixed $class ) : bool
public ReflectionClass::isTrait ( void ) : bool
public ReflectionClass::isUserDefined ( void ) : bool
public ReflectionClass::newInstance ([ mixed $... ] ) : object
public ReflectionClass::newInstanceArgs ([ array $args ] ) : object
public ReflectionClass::newInstanceWithoutConstructor ( void ) : object
public ReflectionClass::setStaticPropertyValue ( string $name , mixed $value ) : void
public ReflectionClass::__toString ( void ) : string
}

Properties

name

Name of the object's class. Read-only, throws ReflectionException in attempt to write.

Table of Contents

  • ReflectionObject::__construct — Constructs a ReflectionObject
  • ReflectionObject::export — Export


Constructs a ReflectionObject

  • « ReflectionObject
  • ReflectionObject::export »
  • PHP Manual
  • ReflectionObject
  • Constructs a ReflectionObject

ReflectionObject::__construct

(PHP 5, PHP 7)

ReflectionObject::__construct — Constructs a ReflectionObject

Description

public ReflectionObject::__construct ( object $argument )

Constructs a ReflectionObject.

Warning

This function is currently not documented; only its argument list is available.

Parameters

argument

An object instance.

Return Values

No value is returned.

See Also

  • ReflectionObject::export() - Export
  • Constructors


Export

  • « ReflectionObject::__construct
  • ReflectionParameter »
  • PHP Manual
  • ReflectionObject
  • Export

ReflectionObject::export

(PHP 5, PHP 7)

ReflectionObject::export — Export

Description

public static ReflectionObject::export ( string $argument [, bool $return ] ) : string

Exports a reflection.

Warning

This function is currently not documented; only its argument list is available.

Parameters

argument

The reflection to export.

return

Setting to TRUE will return the export, as opposed to emitting it. Setting to FALSE (the default) will do the opposite.

Return Values

If the return parameter is set to TRUE, then the export is returned as a string, otherwise NULL is returned.

See Also

  • ReflectionObject::__construct() - Constructs a ReflectionObject


The ReflectionParameter class

(PHP 5, PHP 7)

Introduction

The ReflectionParameter class retrieves information about function's or method's parameters.

To introspect function parameters, first create an instance of the ReflectionFunction or ReflectionMethod classes and then use their ReflectionFunctionAbstract::getParameters() method to retrieve an array of parameters.

Class synopsis

ReflectionParameter implements Reflector {
/* Properties */
public $name ;
/* Methods */
public allowsNull ( void ) : bool
public canBePassedByValue ( void ) : bool
final private __clone ( void ) : void
public __construct ( callable $function , mixed $parameter )
public static export ( string $function , string $parameter [, bool $return ] ) : string
public getClass ( void ) : ReflectionClass
public getDeclaringClass ( void ) : ReflectionClass
public getDeclaringFunction ( void ) : ReflectionFunctionAbstract
public getDefaultValue ( void ) : mixed
public getDefaultValueConstantName ( void ) : string
public getName ( void ) : string
public getPosition ( void ) : int
public getType ( void ) : ReflectionType
public hasType ( void ) : bool
public isArray ( void ) : bool
public isCallable ( void ) : bool
public isDefaultValueAvailable ( void ) : bool
public isDefaultValueConstant ( void ) : bool
public isOptional ( void ) : bool
public isPassedByReference ( void ) : bool
public isVariadic ( void ) : bool
public __toString ( void ) : string
}

Properties

name

Name of the parameter. Read-only, throws ReflectionException in attempt to write.

Table of Contents

  • ReflectionParameter::allowsNull — Checks if null is allowed
  • ReflectionParameter::canBePassedByValue — Returns whether this parameter can be passed by value
  • ReflectionParameter::__clone — Clone
  • ReflectionParameter::__construct — Construct
  • ReflectionParameter::export — Exports
  • ReflectionParameter::getClass — Get the type hinted class
  • ReflectionParameter::getDeclaringClass — Gets declaring class
  • ReflectionParameter::getDeclaringFunction — Gets declaring function
  • ReflectionParameter::getDefaultValue — Gets default parameter value
  • ReflectionParameter::getDefaultValueConstantName — Returns the default value's constant name if default value is constant or null
  • ReflectionParameter::getName — Gets parameter name
  • ReflectionParameter::getPosition — Gets parameter position
  • ReflectionParameter::getType — Gets a parameter's type
  • ReflectionParameter::hasType — Checks if parameter has a type
  • ReflectionParameter::isArray — Checks if parameter expects an array
  • ReflectionParameter::isCallable — Returns whether parameter MUST be callable
  • ReflectionParameter::isDefaultValueAvailable — Checks if a default value is available
  • ReflectionParameter::isDefaultValueConstant — Returns whether the default value of this parameter is a constant
  • ReflectionParameter::isOptional — Checks if optional
  • ReflectionParameter::isPassedByReference — Checks if passed by reference
  • ReflectionParameter::isVariadic — Checks if the parameter is variadic
  • ReflectionParameter::__toString — To string


Checks if null is allowed

  • « ReflectionParameter
  • ReflectionParameter::canBePassedByValue »
  • PHP Manual
  • ReflectionParameter
  • Checks if null is allowed

ReflectionParameter::allowsNull

(PHP 5, PHP 7)

ReflectionParameter::allowsNull — Checks if null is allowed

Description

public ReflectionParameter::allowsNull ( void ) : bool

Checks whether the parameter allows NULL.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

TRUE if NULL is allowed, otherwise FALSE

See Also

  • ReflectionParameter::isOptional() - Checks if optional


Returns whether this parameter can be passed by value

  • « ReflectionParameter::allowsNull
  • ReflectionParameter::__clone »
  • PHP Manual
  • ReflectionParameter
  • Returns whether this parameter can be passed by value

ReflectionParameter::canBePassedByValue

(PHP 5 >= 5.4.0, PHP 7)

ReflectionParameter::canBePassedByValue — Returns whether this parameter can be passed by value

Description

public ReflectionParameter::canBePassedByValue ( void ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the parameter can be passed by value, FALSE otherwise. Returns NULL in case of an error.


Clone

  • « ReflectionParameter::canBePassedByValue
  • ReflectionParameter::__construct »
  • PHP Manual
  • ReflectionParameter
  • Clone

ReflectionParameter::__clone

(PHP 5, PHP 7)

ReflectionParameter::__clone — Clone

Description

final private ReflectionParameter::__clone ( void ) : void

Clones.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

See Also

  • ReflectionParameter::toString()
  • Object cloning


Construct

  • « ReflectionParameter::__clone
  • ReflectionParameter::export »
  • PHP Manual
  • ReflectionParameter
  • Construct

ReflectionParameter::__construct

(PHP 5, PHP 7)

ReflectionParameter::__construct — Construct

Description

public ReflectionParameter::__construct ( callable $function , mixed $parameter )

Constructs a ReflectionParameter instance.

Parameters

function

The function to reflect parameters from.

parameter

Either an integer specifying the position of the parameter (starting with zero), or a the parameter name as string.

Return Values

No value is returned.

Examples

Example #1 Using the ReflectionParameter class

<?php
function foo($a, $b, $c) { }
function bar(Exception $a, &$b, $c) { }
function baz(ReflectionFunction $a, $b = 1, $c = null) { }
function abc() { }

$reflect = new ReflectionFunction('foo');

echo $reflect;

foreach ($reflect->getParameters() as $i => $param) {
    printf(
        "-- Parameter #%d: %s {\n".
        "   Class: %s\n".
        "   Allows NULL: %s\n".
        "   Passed to by reference: %s\n".
        "   Is optional?: %s\n".
        "}\n",
        $i, // $param->getPosition() can be used from PHP 5.2.3
        $param->getName(),
        var_export($param->getClass(), 1),
        var_export($param->allowsNull(), 1),
        var_export($param->isPassedByReference(), 1),
        $param->isOptional() ? 'yes' : 'no'
    );
}
?>

The above example will output something similar to:

Function [ <user> function foo ] {
  @@ /Users/philip/cvs/phpdoc/a 2 - 2

  - Parameters [3] {
    Parameter #0 [ <required> $a ]
    Parameter #1 [ <required> $b ]
    Parameter #2 [ <required> $c ]
  }
}
-- Parameter #0: a {
   Class: NULL
   Allows NULL: true
   Passed to by reference: false
   Is optional?: no
}
-- Parameter #1: b {
   Class: NULL
   Allows NULL: true
   Passed to by reference: false
   Is optional?: no
}
-- Parameter #2: c {
   Class: NULL
   Allows NULL: true
   Passed to by reference: false
   Is optional?: no
}

See Also

  • ReflectionFunctionAbstract::getParameters() - Gets parameters
  • ReflectionFunction::__construct() - Constructs a ReflectionFunction object
  • ReflectionMethod::__construct() - Constructs a ReflectionMethod
  • Constructors


Exports

  • « ReflectionParameter::__construct
  • ReflectionParameter::getClass »
  • PHP Manual
  • ReflectionParameter
  • Exports

ReflectionParameter::export

(PHP 5, PHP 7)

ReflectionParameter::export — Exports

Description

public static ReflectionParameter::export ( string $function , string $parameter [, bool $return ] ) : string

Exports.

Warning

This function is currently not documented; only its argument list is available.

Parameters

function

The function name.

parameter

The parameter name.

return

Setting to TRUE will return the export, as opposed to emitting it. Setting to FALSE (the default) will do the opposite.

Return Values

The exported reflection.

See Also

  • ReflectionParameter::toString()


Get the type hinted class

  • « ReflectionParameter::export
  • ReflectionParameter::getDeclaringClass »
  • PHP Manual
  • ReflectionParameter
  • Get the type hinted class

ReflectionParameter::getClass

(PHP 5, PHP 7)

ReflectionParameter::getClass — Get the type hinted class

Description

public ReflectionParameter::getClass ( void ) : ReflectionClass

Gets the class type hinted for the parameter as a ReflectionClass object.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

A ReflectionClass object.

Examples

Example #1 Using the ReflectionParameter class

<?php
function foo(Exception $a) { }

$functionReflection = new ReflectionFunction('foo');
$parameters = $functionReflection->getParameters();
$aParameter = $parameters[0];

echo $aParameter->getClass()->name;
?>

The above example will output:

Exception

See Also

  • ReflectionParameter::getDeclaringClass() - Gets declaring class


Gets declaring class

  • « ReflectionParameter::getClass
  • ReflectionParameter::getDeclaringFunction »
  • PHP Manual
  • ReflectionParameter
  • Gets declaring class

ReflectionParameter::getDeclaringClass

(PHP 5 >= 5.1.3, PHP 7)

ReflectionParameter::getDeclaringClass — Gets declaring class

Description

public ReflectionParameter::getDeclaringClass ( void ) : ReflectionClass

Gets the declaring class.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

A ReflectionClass object or NULL if called on function.

Examples

Example #1 Getting the class that declared the method

<?php
class Foo
{
    public function bar(\DateTime $datetime)
    {
    }
}

class Baz extends Foo
{
}

$param = new \ReflectionParameter(['Baz', 'bar'], 0);

var_dump($param->getDeclaringClass());

The above example will output:

object(ReflectionClass)#2 (1) {
  ["name"]=>
  string(3) "Foo"
}

See Also

  • ReflectionParameter::getClass() - Get the type hinted class


Gets declaring function

  • « ReflectionParameter::getDeclaringClass
  • ReflectionParameter::getDefaultValue »
  • PHP Manual
  • ReflectionParameter
  • Gets declaring function

ReflectionParameter::getDeclaringFunction

(PHP 5 >= 5.1.3, PHP 7)

ReflectionParameter::getDeclaringFunction — Gets declaring function

Description

public ReflectionParameter::getDeclaringFunction ( void ) : ReflectionFunctionAbstract

Gets the declaring function.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

A ReflectionFunction object.

See Also

  • ReflectionParameter::getDeclaringClass() - Gets declaring class


Gets default parameter value

  • « ReflectionParameter::getDeclaringFunction
  • ReflectionParameter::getDefaultValueConstantName »
  • PHP Manual
  • ReflectionParameter
  • Gets default parameter value

ReflectionParameter::getDefaultValue

(PHP 5 >= 5.0.3, PHP 7)

ReflectionParameter::getDefaultValue — Gets default parameter value

Description

public ReflectionParameter::getDefaultValue ( void ) : mixed

Gets the default value of the parameter for a user-defined function or method. If the parameter is not optional a ReflectionException will be thrown.

Parameters

This function has no parameters.

Return Values

The parameters default value.

Examples

Example #1 Getting default values of function parameters

<?php
function foo($test, $bar = 'baz')
{
    echo $test . $bar;
}

$function = new ReflectionFunction('foo');

foreach ($function->getParameters() as $param) {
    echo 'Name: ' . $param->getName() . PHP_EOL;
    if ($param->isOptional()) {
        echo 'Default value: ' . $param->getDefaultValue() . PHP_EOL;
    }
    echo PHP_EOL;
}
?>

The above example will output:

Name: test

Name: bar
Default value: baz

Notes

Note:

Due to implementation details, it is not possible to get the default value of built-in functions or methods of built-in classes. Trying to do this will result a ReflectionException being thrown.

See Also

  • ReflectionParameter::isOptional() - Checks if optional
  • ReflectionParameter::isDefaultValueAvailable() - Checks if a default value is available
  • ReflectionParameter::getDefaultValueConstantName() - Returns the default value's constant name if default value is constant or null
  • ReflectionParameter::isPassedByReference() - Checks if passed by reference


Returns the default value's constant name if default value is constant or null

  • « ReflectionParameter::getDefaultValue
  • ReflectionParameter::getName »
  • PHP Manual
  • ReflectionParameter
  • Returns the default value's constant name if default value is constant or null

ReflectionParameter::getDefaultValueConstantName

(PHP 5 >= 5.4.6, PHP 7)

ReflectionParameter::getDefaultValueConstantName — Returns the default value's constant name if default value is constant or null

Description

public ReflectionParameter::getDefaultValueConstantName ( void ) : string

Returns the default value's constant name of the parameter of a user-defined function or method, if default value is constant or null. If the parameter is not optional a ReflectionException will be thrown.

Parameters

This function has no parameters.

Return Values

Returns string on success or NULL on failure.

Examples

Example #1 Getting default values' constant names of function parameters

<?php
function foo($test, $bar = PHP_INT_MIN)
{
    echo $test . $bar;
}

$function = new ReflectionFunction('foo');

foreach ($function->getParameters() as $param) {
    echo 'Name: ' . $param->getName() . PHP_EOL;
    if ($param->isOptional()) {
        echo 'Default value: ' . $param->getDefaultValueConstantName() . PHP_EOL;
    }
    echo PHP_EOL;
}
?>

The above example will output:

Name: test

Name: bar
Default value: PHP_INT_MIN

Notes

Note:

Due to implementation details, it is not possible to get the default value of built-in functions or methods of built-in classes. Trying to do this will result a ReflectionException being thrown.

See Also

  • ReflectionParameter::isOptional() - Checks if optional
  • ReflectionParameter::isDefaultValueConstant() - Returns whether the default value of this parameter is a constant
  • ReflectionParameter::getDefaultValue() - Gets default parameter value


Gets parameter name

  • « ReflectionParameter::getDefaultValueConstantName
  • ReflectionParameter::getPosition »
  • PHP Manual
  • ReflectionParameter
  • Gets parameter name

ReflectionParameter::getName

(PHP 5, PHP 7)

ReflectionParameter::getName — Gets parameter name

Description

public ReflectionParameter::getName ( void ) : string

Gets the name of the parameter.

Parameters

This function has no parameters.

Return Values

The name of the reflected parameter.

See Also

  • ReflectionParameter::getValue()


Gets parameter position

  • « ReflectionParameter::getName
  • ReflectionParameter::getType »
  • PHP Manual
  • ReflectionParameter
  • Gets parameter position

ReflectionParameter::getPosition

(PHP 5 >= 5.1.3, PHP 7)

ReflectionParameter::getPosition — Gets parameter position

Description

public ReflectionParameter::getPosition ( void ) : int

Gets the position of the parameter.

Parameters

This function has no parameters.

Return Values

The position of the parameter, left to right, starting at position #0.

See Also

  • ReflectionParameter::getName() - Gets parameter name


Gets a parameter's type

  • « ReflectionParameter::getPosition
  • ReflectionParameter::hasType »
  • PHP Manual
  • ReflectionParameter
  • Gets a parameter's type

ReflectionParameter::getType

(PHP 7)

ReflectionParameter::getType — Gets a parameter's type

Description

public ReflectionParameter::getType ( void ) : ReflectionType

Gets the associated type of a parameter.

Parameters

This function has no parameters.

Return Values

Returns a ReflectionType object if a parameter type is specified, NULL otherwise.

Examples

Example #1 ReflectionParameter::getType() Usage as of PHP 7.1.0

As of PHP 7.1.0, ReflectionType::__toString() is deprecated, and ReflectionParameter::getType() may return an instance of ReflectionNamedType. To get the name of the parameter type, ReflectionNamedType() is available in this case.

<?php
function someFunction(int $param, $param2) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParams = $reflectionFunc->getParameters();
$reflectionType1 = $reflectionParams[0]->getType();
$reflectionType2 = $reflectionParams[1]->getType();

assert($reflectionType1 instanceof ReflectionNamedType);
echo $reflectionType1->getName(), PHP_EOL;
var_dump($reflectionType2);
?>

The above example will output:

int
NULL

Example #2 ReflectionParameter::getType() Usage before PHP 7.1.0

<?php
function someFunction(int $param, $param2) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParams = $reflectionFunc->getParameters();
$reflectionType1 = $reflectionParams[0]->getType();
$reflectionType2 = $reflectionParams[1]->getType();

echo $reflectionType1, PHP_EOL;
var_dump($reflectionType2);
?>

Output of the above example in PHP 7.0:

int
NULL

See Also

  • ReflectionParameter::hasType() - Checks if parameter has a type
  • ReflectionType::__toString() - To string


Checks if parameter has a type

  • « ReflectionParameter::getType
  • ReflectionParameter::isArray »
  • PHP Manual
  • ReflectionParameter
  • Checks if parameter has a type

ReflectionParameter::hasType

(PHP 7)

ReflectionParameter::hasType — Checks if parameter has a type

Description

public ReflectionParameter::hasType ( void ) : bool

Checks if the parameter has a type associated with it.

Parameters

This function has no parameters.

Return Values

TRUE if a type is specified, FALSE otherwise.

Examples

Example #1 ReflectionParameter::hasType() example

<?php
function someFunction(string $param, $param2 = null) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParams = $reflectionFunc->getParameters();

var_dump($reflectionParams[0]->hasType());
var_dump($reflectionParams[1]->hasType());

The above example will output something similar to:

bool(true)
bool(false)

See Also

  • ReflectionParameter::getType() - Gets a parameter's type


Checks if parameter expects an array

  • « ReflectionParameter::hasType
  • ReflectionParameter::isCallable »
  • PHP Manual
  • ReflectionParameter
  • Checks if parameter expects an array

ReflectionParameter::isArray

(PHP 5 >= 5.1.2, PHP 7)

ReflectionParameter::isArray — Checks if parameter expects an array

Description

public ReflectionParameter::isArray ( void ) : bool

Checks if the parameter expects an array.

Parameters

This function has no parameters.

Return Values

TRUE if an array is expected, FALSE otherwise.

See Also

  • ReflectionParameter::isOptional() - Checks if optional


Returns whether parameter MUST be callable

  • « ReflectionParameter::isArray
  • ReflectionParameter::isDefaultValueAvailable »
  • PHP Manual
  • ReflectionParameter
  • Returns whether parameter MUST be callable

ReflectionParameter::isCallable

(PHP 5 >= 5.4.0, PHP 7)

ReflectionParameter::isCallable — Returns whether parameter MUST be callable

Description

public ReflectionParameter::isCallable ( void ) : bool

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the parameter is callable, FALSE if it is not or NULL on failure.


Checks if a default value is available

  • « ReflectionParameter::isCallable
  • ReflectionParameter::isDefaultValueConstant »
  • PHP Manual
  • ReflectionParameter
  • Checks if a default value is available

ReflectionParameter::isDefaultValueAvailable

(PHP 5 >= 5.0.3, PHP 7)

ReflectionParameter::isDefaultValueAvailable — Checks if a default value is available

Description

public ReflectionParameter::isDefaultValueAvailable ( void ) : bool

Checks if a default value for the parameter is available.

Parameters

This function has no parameters.

Return Values

TRUE if a default value is available, otherwise FALSE

See Also

  • ReflectionParameter::getDefaultValue() - Gets default parameter value
  • ReflectionParameter::isDefaultValueConstant() - Returns whether the default value of this parameter is a constant
  • ReflectionParameter::getName() - Gets parameter name


Returns whether the default value of this parameter is a constant

  • « ReflectionParameter::isDefaultValueAvailable
  • ReflectionParameter::isOptional »
  • PHP Manual
  • ReflectionParameter
  • Returns whether the default value of this parameter is a constant

ReflectionParameter::isDefaultValueConstant

(PHP 5 >= 5.4.6, PHP 7)

ReflectionParameter::isDefaultValueConstant — Returns whether the default value of this parameter is a constant

Description

public ReflectionParameter::isDefaultValueConstant ( void ) : bool

Returns whether the default value of this parameter is a constant.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the default value is constant, and FALSE otherwise.

See Also

  • ReflectionParameter::getDefaultValueConstantName() - Returns the default value's constant name if default value is constant or null
  • ReflectionParameter::isDefaultValueAvailable() - Checks if a default value is available


Checks if optional

  • « ReflectionParameter::isDefaultValueConstant
  • ReflectionParameter::isPassedByReference »
  • PHP Manual
  • ReflectionParameter
  • Checks if optional

ReflectionParameter::isOptional

(PHP 5 >= 5.0.3, PHP 7)

ReflectionParameter::isOptional — Checks if optional

Description

public ReflectionParameter::isOptional ( void ) : bool

Checks if the parameter is optional.

Parameters

This function has no parameters.

Return Values

TRUE if the parameter is optional, otherwise FALSE

See Also

  • ReflectionParameter::getName() - Gets parameter name


Checks if passed by reference

  • « ReflectionParameter::isOptional
  • ReflectionParameter::isVariadic »
  • PHP Manual
  • ReflectionParameter
  • Checks if passed by reference

ReflectionParameter::isPassedByReference

(PHP 5, PHP 7)

ReflectionParameter::isPassedByReference — Checks if passed by reference

Description

public ReflectionParameter::isPassedByReference ( void ) : bool

Checks if the parameter is passed in by reference.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

TRUE if the parameter is passed in by reference, otherwise FALSE

See Also

  • ReflectionParameter::getName() - Gets parameter name


Checks if the parameter is variadic

  • « ReflectionParameter::isPassedByReference
  • ReflectionParameter::__toString »
  • PHP Manual
  • ReflectionParameter
  • Checks if the parameter is variadic

ReflectionParameter::isVariadic

(PHP 5 >= 5.6.0, PHP 7)

ReflectionParameter::isVariadic — Checks if the parameter is variadic

Description

public ReflectionParameter::isVariadic ( void ) : bool

Checks if the parameter was declared as a variadic parameter.

Parameters

This function has no parameters.

Return Values

Returns TRUE if the parameter is variadic, otherwise FALSE.


To string

  • « ReflectionParameter::isVariadic
  • ReflectionProperty »
  • PHP Manual
  • ReflectionParameter
  • To string

ReflectionParameter::__toString

(PHP 5, PHP 7)

ReflectionParameter::__toString — To string

Description

public ReflectionParameter::__toString ( void ) : string

To string.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

See Also

  • ReflectionParameter::export() - Exports
  • __toString()


The ReflectionProperty class

(PHP 5, PHP 7)

Introduction

The ReflectionProperty class reports information about classes properties.

Class synopsis

ReflectionProperty implements Reflector {
/* Constants */
const integer IS_STATIC = 1 ;
const integer IS_PUBLIC = 256 ;
const integer IS_PROTECTED = 512 ;
const integer IS_PRIVATE = 1024 ;
/* Properties */
public $name ;
public $class ;
/* Methods */
final private __clone ( void ) : void
public __construct ( mixed $class , string $name )
public static export ( mixed $class , string $name [, bool $return ] ) : string
public getDeclaringClass ( void ) : ReflectionClass
public getDocComment ( void ) : string
public getModifiers ( void ) : int
public getName ( void ) : string
public getType ( void ) : ?ReflectionType
public getValue ([ object $object ] ) : mixed
public hasType ( void ) : bool
public isDefault ( void ) : bool
public isInitialized ([ object $object ] ) : bool
public isPrivate ( void ) : bool
public isProtected ( void ) : bool
public isPublic ( void ) : bool
public isStatic ( void ) : bool
public setAccessible ( bool $accessible ) : void
public setValue ( object $object , mixed $value ) : void
public __toString ( void ) : string
}

Properties

name

Name of the property. Read-only, throws ReflectionException in attempt to write.

class

Name of the class where the property is defined. Read-only, throws ReflectionException in attempt to write.

Predefined Constants

ReflectionProperty Modifiers

ReflectionProperty::IS_STATIC

Indicates static properties.

ReflectionProperty::IS_PUBLIC

Indicates public properties.

ReflectionProperty::IS_PROTECTED

Indicates protected properties.

ReflectionProperty::IS_PRIVATE

Indicates private properties.

Table of Contents

  • ReflectionProperty::__clone — Clone
  • ReflectionProperty::__construct — Construct a ReflectionProperty object
  • ReflectionProperty::export — Export
  • ReflectionProperty::getDeclaringClass — Gets declaring class
  • ReflectionProperty::getDocComment — Gets the property doc comment
  • ReflectionProperty::getModifiers — Gets the property modifiers
  • ReflectionProperty::getName — Gets property name
  • ReflectionProperty::getType — Gets a property's type
  • ReflectionProperty::getValue — Gets value
  • ReflectionProperty::hasType — Checks if property has a type
  • ReflectionProperty::isDefault — Checks if property is a default property
  • ReflectionProperty::isInitialized — Checks whether a property is initialized
  • ReflectionProperty::isPrivate — Checks if property is private
  • ReflectionProperty::isProtected — Checks if property is protected
  • ReflectionProperty::isPublic — Checks if property is public
  • ReflectionProperty::isStatic — Checks if property is static
  • ReflectionProperty::setAccessible — Set property accessibility
  • ReflectionProperty::setValue — Set property value
  • ReflectionProperty::__toString — To string


Clone

  • « ReflectionProperty
  • ReflectionProperty::__construct »
  • PHP Manual
  • ReflectionProperty
  • Clone

ReflectionProperty::__clone

(PHP 5, PHP 7)

ReflectionProperty::__clone — Clone

Description

final private ReflectionProperty::__clone ( void ) : void

Clones.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

See Also

  • ReflectionProperty::export() - Export
  • Object cloning


Construct a ReflectionProperty object

  • « ReflectionProperty::__clone
  • ReflectionProperty::export »
  • PHP Manual
  • ReflectionProperty
  • Construct a ReflectionProperty object

ReflectionProperty::__construct

(PHP 5, PHP 7)

ReflectionProperty::__construct — Construct a ReflectionProperty object

Description

public ReflectionProperty::__construct ( mixed $class , string $name )

Warning

This function is currently not documented; only its argument list is available.

Parameters

class

The class name, that contains the property.

name

The name of the property being reflected.

Return Values

No value is returned.

Errors/Exceptions

Trying to get or set private or protected class property's values will result in an exception being thrown.

Examples

Example #1 ReflectionProperty::__construct() example

<?php
class Str
{
    public $length  = 5;
}

// Create an instance of the ReflectionProperty class
$prop = new ReflectionProperty('Str', 'length');

// Print out basic information
printf(
    "===> The%s%s%s%s property '%s' (which was %s)\n" .
    "     having the modifiers %s\n",
        $prop->isPublic() ? ' public' : '',
        $prop->isPrivate() ? ' private' : '',
        $prop->isProtected() ? ' protected' : '',
        $prop->isStatic() ? ' static' : '',
        $prop->getName(),
        $prop->isDefault() ? 'declared at compile-time' : 'created at run-time',
        var_export(Reflection::getModifierNames($prop->getModifiers()), 1)
);

// Create an instance of Str
$obj= new Str();

// Get current value
printf("---> Value is: ");
var_dump($prop->getValue($obj));

// Change value
$prop->setValue($obj, 10);
printf("---> Setting value to 10, new value is: ");
var_dump($prop->getValue($obj));

// Dump object
var_dump($obj);
?>

The above example will output something similar to:

===> The public property 'length' (which was declared at compile-time)
     having the modifiers array (
  0 => 'public',
)
---> Value is: int(5)
---> Setting value to 10, new value is: int(10)
object(Str)#2 (1) {
  ["length"]=>
  int(10)
}

Example #2 Getting value from private and protected properties using ReflectionProperty class

<?php

class Foo {
    public $x = 1;
    protected $y = 2;
    private $z = 3;
}

$obj = new Foo;

$prop = new ReflectionProperty('Foo', 'y');
$prop->setAccessible(true); /* As of PHP 5.3.0 */
var_dump($prop->getValue($obj)); // int(2)

$prop = new ReflectionProperty('Foo', 'z');
$prop->setAccessible(true); /* As of PHP 5.3.0 */
var_dump($prop->getValue($obj)); // int(2)

?>

The above example will output something similar to:

int(2)
int(3)

See Also

  • ReflectionProperty::getName() - Gets property name
  • Constructors


Export

  • « ReflectionProperty::__construct
  • ReflectionProperty::getDeclaringClass »
  • PHP Manual
  • ReflectionProperty
  • Export

ReflectionProperty::export

(PHP 5, PHP 7)

ReflectionProperty::export — Export

Description

public static ReflectionProperty::export ( mixed $class , string $name [, bool $return ] ) : string

Exports a reflection.

Warning

This function is currently not documented; only its argument list is available.

Parameters

argument

The reflection to export.

name

The property name.

return

Setting to TRUE will return the export, as opposed to emitting it. Setting to FALSE (the default) will do the opposite.

Return Values

See Also

  • ReflectionProperty::toString()


Gets declaring class

  • « ReflectionProperty::export
  • ReflectionProperty::getDocComment »
  • PHP Manual
  • ReflectionProperty
  • Gets declaring class

ReflectionProperty::getDeclaringClass

(PHP 5, PHP 7)

ReflectionProperty::getDeclaringClass — Gets declaring class

Description

public ReflectionProperty::getDeclaringClass ( void ) : ReflectionClass

Gets the declaring class.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

A ReflectionClass object.

See Also

  • ReflectionProperty::getName() - Gets property name


Gets the property doc comment

  • « ReflectionProperty::getDeclaringClass
  • ReflectionProperty::getModifiers »
  • PHP Manual
  • ReflectionProperty
  • Gets the property doc comment

ReflectionProperty::getDocComment

(PHP 5 >= 5.1.0, PHP 7)

ReflectionProperty::getDocComment — Gets the property doc comment

Description

public ReflectionProperty::getDocComment ( void ) : string

Gets the doc comment for a property.

Parameters

This function has no parameters.

Return Values

The property doc comment.

Examples

Example #1 ReflectionProperty::getDocComment() example

<?php
class Str
{
    /**
     * @var int  The length of the string
     */
    public $length = 5;
}

$prop = new ReflectionProperty('Str', 'length');

var_dump($prop->getDocComment());

?>

The above example will output something similar to:

string(53) "/**
     * @var int  The length of the string
     */"

Example #2 Multiple property declarations

If multiple property declarations are preceeded by a single doc comment, the doc comment refers to the first property only.

<?php
class Foo
{
    /** @var string */
    public $a, $b;
}
$class = new \ReflectionClass('Foo');
foreach ($class->getProperties() as $property) {
    echo $property->getName() . ': ' . var_export($property->getDocComment(), true) . PHP_EOL;
}
?>

The above example will output:

a: '/** @var string */'
b: false

See Also

  • ReflectionProperty::getModifiers() - Gets the property modifiers
  • ReflectionProperty::getName() - Gets property name
  • ReflectionProperty::getValue() - Gets value


Gets the property modifiers

  • « ReflectionProperty::getDocComment
  • ReflectionProperty::getName »
  • PHP Manual
  • ReflectionProperty
  • Gets the property modifiers

ReflectionProperty::getModifiers

(PHP 5, PHP 7)

ReflectionProperty::getModifiers — Gets the property modifiers

Description

public ReflectionProperty::getModifiers ( void ) : int

Gets the modifiers.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

A numeric representation of the modifiers.

See Also

  • ReflectionProperty::isPrivate() - Checks if property is private
  • Reflection::getModifierNames() - Gets modifier names


Gets property name

  • « ReflectionProperty::getModifiers
  • ReflectionProperty::getType »
  • PHP Manual
  • ReflectionProperty
  • Gets property name

ReflectionProperty::getName

(PHP 5, PHP 7)

ReflectionProperty::getName — Gets property name

Description

public ReflectionProperty::getName ( void ) : string

Gets the properties name.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

The name of the reflected property.

See Also

  • ReflectionProperty::getValue() - Gets value


Gets a property's type

  • « ReflectionProperty::getName
  • ReflectionProperty::getValue »
  • PHP Manual
  • ReflectionProperty
  • Gets a property's type

ReflectionProperty::getType

(PHP 7 >= 7.4.0)

ReflectionProperty::getType — Gets a property's type

Description

public ReflectionProperty::getType ( void ) : ?ReflectionType

Gets the associated type of a property.

Parameters

This function has no parameters.

Return Values

Returns a ReflectionType if the property has a type, and NULL otherwise.

Examples

Example #1 ReflectionProperty::getType() example

<?php
class User
{
    public string $name;
}

$rp = new ReflectionProperty('User', 'name');
echo $rp->getType()->getName();
?>

The above example will output:

string

See Also

  • ReflectionProperty::hasType() - Checks if property has a type
  • ReflectionProperty::isInitialized() - Checks whether a property is initialized


Gets value

  • « ReflectionProperty::getType
  • ReflectionProperty::hasType »
  • PHP Manual
  • ReflectionProperty
  • Gets value

ReflectionProperty::getValue

(PHP 5, PHP 7)

ReflectionProperty::getValue — Gets value

Description

public ReflectionProperty::getValue ([ object $object ] ) : mixed

Gets the property's value.

Parameters

object

If the property is non-static an object must be provided to fetch the property from. If you want to fetch the default property without providing an object use ReflectionClass::getDefaultProperties() instead.

Return Values

The current value of the property.

Errors/Exceptions

Throws a ReflectionException if the property is inaccessible. You can make a protected or private property accessible using ReflectionProperty::setAccessible().

Examples

Example #1 ReflectionProperty::getValue() example

<?php
class Foo {
    public static $staticProperty = 'foobar';

    public $property = 'barfoo';
    protected $privateProperty = 'foofoo';
}

$reflectionClass = new ReflectionClass('Foo');

var_dump($reflectionClass->getProperty('staticProperty')->getValue());
var_dump($reflectionClass->getProperty('property')->getValue(new Foo));

$reflectionProperty = $reflectionClass->getProperty('privateProperty');
$reflectionProperty->setAccessible(true);
var_dump($reflectionProperty->getValue(new Foo));
?>

The above example will output:

string(6) "foobar"
string(6) "barfoo"
string(6) "foofoo"

See Also

  • ReflectionProperty::setValue() - Set property value
  • ReflectionProperty::setAccessible() - Set property accessibility
  • ReflectionClass::getDefaultProperties() - Gets default properties
  • ReflectionClass::getStaticPropertyValue() - Gets static property value


Checks if property has a type

  • « ReflectionProperty::getValue
  • ReflectionProperty::isDefault »
  • PHP Manual
  • ReflectionProperty
  • Checks if property has a type

ReflectionProperty::hasType

(PHP 7 >= 7.4.0)

ReflectionProperty::hasType — Checks if property has a type

Description

public ReflectionProperty::hasType ( void ) : bool

Checks if the property has a type associated with it.

Parameters

This function has no parameters.

Return Values

TRUE if a type is specified, FALSE otherwise.

Examples

Example #1 ReflectionProperty::hasType() example

<?php
class User
{
    public string $name;
}

$rp = new ReflectionProperty('User', 'name');
var_dump($rp->hasType());
?>

The above example will output:

bool(true)

See Also

  • ReflectionProperty::getType() - Gets a property's type
  • ReflectionProperty::isInitialized() - Checks whether a property is initialized


Checks if property is a default property

  • « ReflectionProperty::hasType
  • ReflectionProperty::isInitialized »
  • PHP Manual
  • ReflectionProperty
  • Checks if property is a default property

ReflectionProperty::isDefault

(PHP 5, PHP 7)

ReflectionProperty::isDefault — Checks if property is a default property

Description

public ReflectionProperty::isDefault ( void ) : bool

Checks whether the property was declared at compile-time, or whether the property was dynamically declared at run-time.

Parameters

This function has no parameters.

Return Values

TRUE if the property was declared at compile-time, or FALSE if it was created at run-time.

Examples

Example #1 ReflectionClass::isDefault() example

<?php
class Foo {
    public $bar;
}

$o = new Foo();
$o->bar = 42;
$o->baz = 42;

$ro = new ReflectionObject($o);
var_dump($ro->getProperty('bar')->isDefault());
var_dump($ro->getProperty('baz')->isDefault());
?>

The above example will output:

bool(true)
bool(false)

See Also

  • ReflectionProperty::getValue() - Gets value


Checks whether a property is initialized

  • « ReflectionProperty::isDefault
  • ReflectionProperty::isPrivate »
  • PHP Manual
  • ReflectionProperty
  • Checks whether a property is initialized

ReflectionProperty::isInitialized

(PHP 7 >= 7.4.0)

ReflectionProperty::isInitialized — Checks whether a property is initialized

Description

public ReflectionProperty::isInitialized ([ object $object ] ) : bool

Checks whether a property is initialized.

Parameters

object

If the property is non-static an object must be provided to fetch the property from.

Return Values

Returns FALSE for typed properties prior to initialization, and for properties that have been explicitly unset(). For all other properties TRUE will be returned.

Errors/Exceptions

Throws a ReflectionException if the property is inaccessible. You can make a protected or private property accessible using ReflectionProperty::setAccessible().

Examples

Example #1 ReflectionProperty::isInitialized() example

<?php
class User
{
    public string $name;
}

$rp = new ReflectionProperty('User', 'name');
$user = new User;
var_dump($rp->isInitialized($user));
$user->name = 'Nikita';
var_dump($rp->isInitialized($user));
?>

The above example will output:

bool(false)
bool(true)

See Also

  • ReflectionProperty::hasType() - Checks if property has a type


Checks if property is private

  • « ReflectionProperty::isInitialized
  • ReflectionProperty::isProtected »
  • PHP Manual
  • ReflectionProperty
  • Checks if property is private

ReflectionProperty::isPrivate

(PHP 5, PHP 7)

ReflectionProperty::isPrivate — Checks if property is private

Description

public ReflectionProperty::isPrivate ( void ) : bool

Checks whether the property is private.

Parameters

This function has no parameters.

Return Values

TRUE if the property is private, FALSE otherwise.

See Also

  • ReflectionProperty::isPublic() - Checks if property is public
  • ReflectionProperty::isProtected() - Checks if property is protected
  • ReflectionProperty::isStatic() - Checks if property is static


Checks if property is protected

  • « ReflectionProperty::isPrivate
  • ReflectionProperty::isPublic »
  • PHP Manual
  • ReflectionProperty
  • Checks if property is protected

ReflectionProperty::isProtected

(PHP 5, PHP 7)

ReflectionProperty::isProtected — Checks if property is protected

Description

public ReflectionProperty::isProtected ( void ) : bool

Checks whether the property is protected.

Parameters

This function has no parameters.

Return Values

TRUE if the property is protected, FALSE otherwise.

See Also

  • ReflectionProperty::isPublic() - Checks if property is public
  • ReflectionProperty::isPrivate() - Checks if property is private
  • ReflectionProperty::isStatic() - Checks if property is static


Checks if property is public

  • « ReflectionProperty::isProtected
  • ReflectionProperty::isStatic »
  • PHP Manual
  • ReflectionProperty
  • Checks if property is public

ReflectionProperty::isPublic

(PHP 5, PHP 7)

ReflectionProperty::isPublic — Checks if property is public

Description

public ReflectionProperty::isPublic ( void ) : bool

Checks whether the property is public.

Parameters

This function has no parameters.

Return Values

TRUE if the property is public, FALSE otherwise.

See Also

  • ReflectionProperty::isProtected() - Checks if property is protected
  • ReflectionProperty::isPrivate() - Checks if property is private
  • ReflectionProperty::isStatic() - Checks if property is static


Checks if property is static

  • « ReflectionProperty::isPublic
  • ReflectionProperty::setAccessible »
  • PHP Manual
  • ReflectionProperty
  • Checks if property is static

ReflectionProperty::isStatic

(PHP 5, PHP 7)

ReflectionProperty::isStatic — Checks if property is static

Description

public ReflectionProperty::isStatic ( void ) : bool

Checks whether the property is static.

Parameters

This function has no parameters.

Return Values

TRUE if the property is static, FALSE otherwise.

See Also

  • ReflectionProperty::isPublic() - Checks if property is public
  • ReflectionProperty::isProtected() - Checks if property is protected
  • ReflectionProperty::isPrivate() - Checks if property is private


Set property accessibility

  • « ReflectionProperty::isStatic
  • ReflectionProperty::setValue »
  • PHP Manual
  • ReflectionProperty
  • Set property accessibility

ReflectionProperty::setAccessible

(PHP 5 >= 5.3.0, PHP 7)

ReflectionProperty::setAccessible — Set property accessibility

Description

public ReflectionProperty::setAccessible ( bool $accessible ) : void

Sets a property to be accessible. For example, it may allow protected and private properties to be accessed.

Parameters

accessible

TRUE to allow accessibility, or FALSE.

Return Values

No value is returned.

See Also

  • ReflectionProperty::isPrivate() - Checks if property is private
  • ReflectionProperty::isProtected() - Checks if property is protected


Set property value

  • « ReflectionProperty::setAccessible
  • ReflectionProperty::__toString »
  • PHP Manual
  • ReflectionProperty
  • Set property value

ReflectionProperty::setValue

(PHP 5, PHP 7)

ReflectionProperty::setValue — Set property value

Description

public ReflectionProperty::setValue ( object $object , mixed $value ) : void
public ReflectionProperty::setValue ( mixed $value ) : void

Sets (changes) the property's value.

Parameters

object

If the property is non-static an object must be provided to change the property on. If the property is static this parameter is left out and only value needs to be provided.

value

The new value.

Return Values

No value is returned.

Errors/Exceptions

Throws a ReflectionException if the property is inaccessible. You can make a protected or private property accessible using ReflectionProperty::setAccessible().

Examples

Example #1 ReflectionProperty::setValue() example

<?php
class Foo {
    public static $staticProperty;

    public $property;
    protected $privateProperty;
}

$reflectionClass = new ReflectionClass('Foo');

$reflectionClass->getProperty('staticProperty')->setValue('foo');
var_dump(Foo::$staticProperty);

$foo = new Foo;

$reflectionClass->getProperty('property')->setValue($foo, 'bar');
var_dump($foo->property);

$reflectionProperty = $reflectionClass->getProperty('privateProperty');
$reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($foo, 'foobar');
var_dump($reflectionProperty->getValue($foo));
?>

The above example will output:

string(3) "foo"
string(3) "bar"
string(6) "foobar"

See Also

  • ReflectionProperty::getValue() - Gets value
  • ReflectionProperty::setAccessible() - Set property accessibility
  • ReflectionClass::setStaticPropertyValue() - Sets static property value


To string

  • « ReflectionProperty::setValue
  • ReflectionType »
  • PHP Manual
  • ReflectionProperty
  • To string

ReflectionProperty::__toString

(PHP 5, PHP 7)

ReflectionProperty::__toString — To string

Description

public ReflectionProperty::__toString ( void ) : string

To string.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

See Also

  • __toString()


The ReflectionType class

(PHP 7)

Introduction

The ReflectionType class reports information about a function's return type.

Class synopsis

ReflectionType {
/* Methods */
public allowsNull ( void ) : bool
public isBuiltin ( void ) : bool
public __toString ( void ) : string
}

Table of Contents

  • ReflectionType::allowsNull — Checks if null is allowed
  • ReflectionType::isBuiltin — Checks if it is a built-in type
  • ReflectionType::__toString — To string


Checks if null is allowed

  • « ReflectionType
  • ReflectionType::isBuiltin »
  • PHP Manual
  • ReflectionType
  • Checks if null is allowed

ReflectionType::allowsNull

(PHP 7)

ReflectionType::allowsNull — Checks if null is allowed

Description

public ReflectionType::allowsNull ( void ) : bool

Checks whether the parameter allows NULL.

Parameters

This function has no parameters.

Return Values

TRUE if NULL is allowed, otherwise FALSE

Examples

Example #1 ReflectionType::allowsNull() example

<?php
function someFunction(string $param, StdClass $param2 = null) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParams = $reflectionFunc->getParameters();

var_dump($reflectionParams[0]->getType()->allowsNull());
var_dump($reflectionParams[1]->getType()->allowsNull());

The above example will output something similar to:

bool(false)
bool(true)

See Also

  • ReflectionType::isBuiltin() - Checks if it is a built-in type
  • ReflectionType::__toString() - To string
  • ReflectionParameter::getType() - Gets a parameter's type


Checks if it is a built-in type

  • « ReflectionType::allowsNull
  • ReflectionType::__toString »
  • PHP Manual
  • ReflectionType
  • Checks if it is a built-in type

ReflectionType::isBuiltin

(PHP 7)

ReflectionType::isBuiltin — Checks if it is a built-in type

Description

public ReflectionType::isBuiltin ( void ) : bool

Checks if the type is a built-in type in PHP.

Parameters

This function has no parameters.

Return Values

TRUE if it's a built-in type, otherwise FALSE

Examples

Example #1 ReflectionType::isBuiltin() example

<?php
class SomeClass {}

function someFunction(string $param, SomeClass $param2, StdClass $param3) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParams = $reflectionFunc->getParameters();

var_dump($reflectionParams[0]->getType()->isBuiltin());
var_dump($reflectionParams[1]->getType()->isBuiltin());
var_dump($reflectionParams[2]->getType()->isBuiltin());

The above example will output something similar to:

bool(true)
bool(false)
bool(false)

Note that the ReflectionType::isBuiltin() method does not distinguish between internal and custom classes. To make this distinction, the ReflectionClass::isInternal() method should be used on the returned class name.

See Also

  • ReflectionType::allowsNull() - Checks if null is allowed
  • ReflectionType::__toString() - To string
  • ReflectionClass::isInternal() - Checks if class is defined internally by an extension, or the core
  • ReflectionParameter::getType() - Gets a parameter's type


To string

  • « ReflectionType::isBuiltin
  • ReflectionGenerator »
  • PHP Manual
  • ReflectionType
  • To string

ReflectionType::__toString

(PHP 7)

ReflectionType::__toString — To string

Warning

This function has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

Description

public ReflectionType::__toString ( void ) : string

Gets the parameter type name.

Parameters

This function has no parameters.

Return Values

Returns the type of the parameter.

Examples

Example #1 ReflectionType::__toString() example

<?php
function someFunction(string $param) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParam = $reflectionFunc->getParameters()[0];

echo $reflectionParam->getType();

The above example will output something similar to:

string

See Also

  • ReflectionNamedType::getName() - Get the text of the type hint
  • ReflectionType::allowsNull() - Checks if null is allowed
  • ReflectionType::isBuiltin() - Checks if it is a built-in type
  • ReflectionParameter::getType() - Gets a parameter's type


The ReflectionGenerator class

(PHP 7)

Introduction

The ReflectionGenerator class reports information about a generator.

Class synopsis

ReflectionGenerator {
/* Methods */
public __construct ( Generator $generator )
public getExecutingFile ( void ) : string
public getExecutingGenerator ( void ) : Generator
public getExecutingLine ( void ) : int
public getFunction ( void ) : ReflectionFunctionAbstract
public getThis ( void ) : object
public getTrace ([ int $options = DEBUG_BACKTRACE_PROVIDE_OBJECT ] ) : array
}

Table of Contents

  • ReflectionGenerator::__construct — Constructs a ReflectionGenerator object
  • ReflectionGenerator::getExecutingFile — Gets the file name of the currently executing generator
  • ReflectionGenerator::getExecutingGenerator — Gets the executing Generator object
  • ReflectionGenerator::getExecutingLine — Gets the currently executing line of the generator
  • ReflectionGenerator::getFunction — Gets the function name of the generator
  • ReflectionGenerator::getThis — Gets the $this value of the generator
  • ReflectionGenerator::getTrace — Gets the trace of the executing generator


Constructs a ReflectionGenerator object

  • « ReflectionGenerator
  • ReflectionGenerator::getExecutingFile »
  • PHP Manual
  • ReflectionGenerator
  • Constructs a ReflectionGenerator object

ReflectionGenerator::__construct

(PHP 7)

ReflectionGenerator::__construct — Constructs a ReflectionGenerator object

Description

public ReflectionGenerator::__construct ( Generator $generator )

Constructs a ReflectionGenerator object.

Parameters

generator

A generator object.

Return Values

No value is returned.

Examples

Example #1 ReflectionGenerator::__construct() example

<?php

function gen()
{
    yield 1;
}

$gen = gen();

$reflectionGen = new ReflectionGenerator($gen);

echo <<< output
{$reflectionGen->getFunction()->name}
Line: {$reflectionGen->getExecutingLine()}
File: {$reflectionGen->getExecutingFile()}
output;

The above example will output something similar to:

gen
Line: 5
File: /path/to/file/example.php

See Also

  • ReflectionGenerator::getFunction() - Gets the function name of the generator
  • ReflectionGenerator::getExecutingLine() - Gets the currently executing line of the generator
  • ReflectionGenerator::getExecutingFile() - Gets the file name of the currently executing generator


Gets the file name of the currently executing generator

  • « ReflectionGenerator::__construct
  • ReflectionGenerator::getExecutingGenerator »
  • PHP Manual
  • ReflectionGenerator
  • Gets the file name of the currently executing generator

ReflectionGenerator::getExecutingFile

(PHP 7)

ReflectionGenerator::getExecutingFile — Gets the file name of the currently executing generator

Description

public ReflectionGenerator::getExecutingFile ( void ) : string

Get the full path and file name of the currently executing generator.

Parameters

This function has no parameters.

Return Values

Returns the full path and file name of the currently executing generator.

Examples

Example #1 ReflectionGenerator::getExecutingFile() example

<?php

class GenExample
{
    public function gen()
    {
        yield 1;
    }
}

$gen = (new GenExample)->gen();

$reflectionGen = new ReflectionGenerator($gen);

echo "File: {$reflectionGen->getExecutingFile()}";

The above example will output something similar to:

File: /path/to/file/example.php

See Also

  • ReflectionGenerator::getExecutingLine() - Gets the currently executing line of the generator
  • ReflectionGenerator::getExecutingGenerator() - Gets the executing Generator object


Gets the executing Generator object

  • « ReflectionGenerator::getExecutingFile
  • ReflectionGenerator::getExecutingLine »
  • PHP Manual
  • ReflectionGenerator
  • Gets the executing Generator object

ReflectionGenerator::getExecutingGenerator

(PHP 7)

ReflectionGenerator::getExecutingGenerator — Gets the executing Generator object

Description

public ReflectionGenerator::getExecutingGenerator ( void ) : Generator

Get the executing Generator object

Parameters

This function has no parameters.

Return Values

Returns the currently executing Generator object.

Examples

Example #1 ReflectionGenerator::getExecutingGenerator() example

<?php

class GenExample
{
    public function gen()
    {
        yield 1;
    }
}

$gen = (new GenExample)->gen();

$reflectionGen = new ReflectionGenerator($gen);

$gen2 = $reflectionGen->getExecutingGenerator();

var_dump($gen2 === $gen);
var_dump($gen2->current());

The above example will output something similar to:

bool(true)
int(1);

See Also

  • ReflectionGenerator::getExecutingLine() - Gets the currently executing line of the generator
  • ReflectionGenerator::getExecutingFile() - Gets the file name of the currently executing generator


Gets the currently executing line of the generator

  • « ReflectionGenerator::getExecutingGenerator
  • ReflectionGenerator::getFunction »
  • PHP Manual
  • ReflectionGenerator
  • Gets the currently executing line of the generator

ReflectionGenerator::getExecutingLine

(PHP 7)

ReflectionGenerator::getExecutingLine — Gets the currently executing line of the generator

Description

public ReflectionGenerator::getExecutingLine ( void ) : int

Get the currently executing line number of the generator.

Parameters

This function has no parameters.

Return Values

Returns the line number of the currently executing statement in the generator.

Examples

Example #1 ReflectionGenerator::getExecutingLine() example

<?php

class GenExample
{
    public function gen()
    {
        yield 1;
    }
}

$gen = (new GenExample)->gen();

$reflectionGen = new ReflectionGenerator($gen);

echo "Line: {$reflectionGen->getExecutingLine()}";

The above example will output something similar to:

Line: 7

See Also

  • ReflectionGenerator::getExecutingGenerator() - Gets the executing Generator object
  • ReflectionGenerator::getExecutingFile() - Gets the file name of the currently executing generator


Gets the function name of the generator

  • « ReflectionGenerator::getExecutingLine
  • ReflectionGenerator::getThis »
  • PHP Manual
  • ReflectionGenerator
  • Gets the function name of the generator

ReflectionGenerator::getFunction

(PHP 7)

ReflectionGenerator::getFunction — Gets the function name of the generator

Description

public ReflectionGenerator::getFunction ( void ) : ReflectionFunctionAbstract

Enables the function name of the generator to be obtained by returning a class derived from ReflectionFunctionAbstract.

Parameters

This function has no parameters.

Return Values

Returns a ReflectionFunctionAbstract class. This will be ReflectionFunction for functions, or ReflectionMethod for methods.

Examples

Example #1 ReflectionGenerator::getFunction() example

<?php

function gen()
{
    yield 1;
}

$gen = gen();

$reflectionGen = new ReflectionGenerator($gen);

var_dump($reflectionGen->getFunction());

The above example will output something similar to:

object(ReflectionFunction)#3 (1) {
  ["name"]=>
  string(3) "gen"
}

See Also

  • ReflectionGenerator::getThis() - Gets the $this value of the generator
  • ReflectionGenerator::getTrace() - Gets the trace of the executing generator


Gets the $this value of the generator

  • « ReflectionGenerator::getFunction
  • ReflectionGenerator::getTrace »
  • PHP Manual
  • ReflectionGenerator
  • Gets the $this value of the generator

ReflectionGenerator::getThis

(PHP 7)

ReflectionGenerator::getThis — Gets the $this value of the generator

Description

public ReflectionGenerator::getThis ( void ) : object

Get the $this value that the generator has access to.

Parameters

This function has no parameters.

Return Values

Returns the $this value, or NULL if the generator was not created in a class context.

Examples

Example #1 ReflectionGenerator::getThis() example

<?php

class GenExample
{
    public function gen()
    {
        yield 1;
    }
}

$gen = (new GenExample)->gen();

$reflectionGen = new ReflectionGenerator($gen);

var_dump($reflectionGen->getThis());

The above example will output something similar to:

object(GenExample)#3 (0) {
}

See Also

  • ReflectionGenerator::getFunction() - Gets the function name of the generator
  • ReflectionGenerator::getTrace() - Gets the trace of the executing generator


Gets the trace of the executing generator

  • « ReflectionGenerator::getThis
  • Reflector »
  • PHP Manual
  • ReflectionGenerator
  • Gets the trace of the executing generator

ReflectionGenerator::getTrace

(PHP 7)

ReflectionGenerator::getTrace — Gets the trace of the executing generator

Description

public ReflectionGenerator::getTrace ([ int $options = DEBUG_BACKTRACE_PROVIDE_OBJECT ] ) : array

Get the trace of the currently executing generator.

Parameters

options

The value of options can be any of the following flags.

Available options
Option | Description
DEBUG_BACKTRACE_PROVIDE_OBJECT | Default.
DEBUG_BACKTRACE_IGNORE_ARGS | Don't include the argument information for functions in the stack trace.

Return Values

Returns the trace of the currently executing generator.

Examples

Example #1 ReflectionGenerator::getTrace() example

<?php
function foo() {
    yield 1;
}

function bar()
{
    yield from foo();
}

function baz()
{
    yield from bar();
}

$gen = baz();
$gen->valid(); // start the generator

var_dump((new ReflectionGenerator($gen))->getTrace());

The above example will output something similar to:

array(2) {
  [0]=>
  array(4) {
    ["file"]=>
    string(18) "example.php"
    ["line"]=>
    int(8)
    ["function"]=>
    string(3) "foo"
    ["args"]=>
    array(0) {
    }
  }
  [1]=>
  array(4) {
    ["file"]=>
    string(18) "example.php"
    ["line"]=>
    int(12)
    ["function"]=>
    string(3) "bar"
    ["args"]=>
    array(0) {
    }
  }
}

See Also

  • ReflectionGenerator::getFunction() - Gets the function name of the generator
  • ReflectionGenerator::getThis() - Gets the $this value of the generator


The Reflector interface

(PHP 5, PHP 7)

Introduction

Reflector is an interface implemented by all exportable Reflection classes.

Class synopsis

Reflector {
/* Methods */
public static export ( void ) : string
public __toString ( void ) : string
}

Table of Contents

  • Reflector::export — Exports
  • Reflector::__toString — To string


Exports

  • « Reflector
  • Reflector::__toString »
  • PHP Manual
  • Reflector
  • Exports

Reflector::export

(PHP 5, PHP 7)

Reflector::export — Exports

Description

public static Reflector::export ( void ) : string

Exports.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

See Also

  • Reflection::__toString()


To string

  • « Reflector::export
  • ReflectionException »
  • PHP Manual
  • Reflector
  • To string

Reflector::__toString

(PHP 5, PHP 7)

Reflector::__toString — To string

Description

public Reflector::__toString ( void ) : string

To string.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

See Also

  • ReflectionProperty::export() - Export
  • __toString()


The ReflectionException class

(PHP 5, PHP 7)

Introduction

The ReflectionException class.

Class synopsis

ReflectionException extends Exception {
/* Properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


Variable handling

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Variable handling Functions
    • boolval — Get the boolean value of a variable
    • debug_zval_dump — Dumps a string representation of an internal zend value to output
    • doubleval — Alias of floatval
    • empty — Determine whether a variable is empty
    • floatval — Get float value of a variable
    • get_defined_vars — Returns an array of all defined variables
    • get_resource_type — Returns the resource type
    • gettype — Get the type of a variable
    • import_request_variables — Import GET/POST/Cookie variables into the global scope
    • intval — Get the integer value of a variable
    • is_array — Finds whether a variable is an array
    • is_bool — Finds out whether a variable is a boolean
    • is_callable — Verify that the contents of a variable can be called as a function
    • is_countable — Verify that the contents of a variable is a countable value
    • is_double — Alias of is_float
    • is_float — Finds whether the type of a variable is float
    • is_int — Find whether the type of a variable is integer
    • is_integer — Alias of is_int
    • is_iterable — Verify that the contents of a variable is an iterable value
    • is_long — Alias of is_int
    • is_null — Finds whether a variable is NULL
    • is_numeric — Finds whether a variable is a number or a numeric string
    • is_object — Finds whether a variable is an object
    • is_real — Alias of is_float
    • is_resource — Finds whether a variable is a resource
    • is_scalar — Finds whether a variable is a scalar
    • is_string — Find whether the type of a variable is string
    • isset — Determine if a variable is declared and is different than NULL
    • print_r — Prints human-readable information about a variable
    • serialize — Generates a storable representation of a value
    • settype — Set the type of a variable
    • strval — Get string value of a variable
    • unserialize — Creates a PHP value from a stored representation
    • unset — Unset a given variable
    • var_dump — Dumps information about a variable
    • var_export — Outputs or returns a parsable string representation of a variable


Introduction

For information on how variables behave, see the Variables entry in the Language Reference section of the manual.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Variables Configuration Options
Name | Default | Changeable | Changelog
unserialize_callback_func | NULL | PHP_INI_ALL |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

unserialize_callback_func string

The callback specified is called when unserialize() attempts to use an undefined class. A warning appears if the specified callback function is not defined, or if the callback function fails to define the missing class.

See also unserialize() and Autoloading Objects.


  • « Resource Types
  • Variable handling Functions »
  • PHP Manual
  • Variable handling
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


Variable handling Functions

Table of Contents

  • boolval — Get the boolean value of a variable
  • debug_zval_dump — Dumps a string representation of an internal zend value to output
  • doubleval — Alias of floatval
  • empty — Determine whether a variable is empty
  • floatval — Get float value of a variable
  • get_defined_vars — Returns an array of all defined variables
  • get_resource_type — Returns the resource type
  • gettype — Get the type of a variable
  • import_request_variables — Import GET/POST/Cookie variables into the global scope
  • intval — Get the integer value of a variable
  • is_array — Finds whether a variable is an array
  • is_bool — Finds out whether a variable is a boolean
  • is_callable — Verify that the contents of a variable can be called as a function
  • is_countable — Verify that the contents of a variable is a countable value
  • is_double — Alias of is_float
  • is_float — Finds whether the type of a variable is float
  • is_int — Find whether the type of a variable is integer
  • is_integer — Alias of is_int
  • is_iterable — Verify that the contents of a variable is an iterable value
  • is_long — Alias of is_int
  • is_null — Finds whether a variable is NULL
  • is_numeric — Finds whether a variable is a number or a numeric string
  • is_object — Finds whether a variable is an object
  • is_real — Alias of is_float
  • is_resource — Finds whether a variable is a resource
  • is_scalar — Finds whether a variable is a scalar
  • is_string — Find whether the type of a variable is string
  • isset — Determine if a variable is declared and is different than NULL
  • print_r — Prints human-readable information about a variable
  • serialize — Generates a storable representation of a value
  • settype — Set the type of a variable
  • strval — Get string value of a variable
  • unserialize — Creates a PHP value from a stored representation
  • unset — Unset a given variable
  • var_dump — Dumps information about a variable
  • var_export — Outputs or returns a parsable string representation of a variable


Get the boolean value of a variable

  • « Variable handling Functions
  • debug_zval_dump »
  • PHP Manual
  • Variable handling Functions
  • Get the boolean value of a variable

boolval

(PHP 5 >= 5.5.0, PHP 7)

boolval — Get the boolean value of a variable

Description

boolval ( mixed $var ) : bool

Returns the boolean value of var.

Parameters

var

The scalar value being converted to a boolean.

Return Values

The boolean value of var.

Examples

Example #1 boolval() examples

<?php
echo '0:        '.(boolval(0) ? 'true' : 'false')."\n";
echo '42:       '.(boolval(42) ? 'true' : 'false')."\n";
echo '0.0:      '.(boolval(0.0) ? 'true' : 'false')."\n";
echo '4.2:      '.(boolval(4.2) ? 'true' : 'false')."\n";
echo '"":       '.(boolval("") ? 'true' : 'false')."\n";
echo '"string": '.(boolval("string") ? 'true' : 'false')."\n";
echo '"0":      '.(boolval("0") ? 'true' : 'false')."\n";
echo '"1":      '.(boolval("1") ? 'true' : 'false')."\n";
echo '[1, 2]:   '.(boolval([1, 2]) ? 'true' : 'false')."\n";
echo '[]:       '.(boolval([]) ? 'true' : 'false')."\n";
echo 'stdClass: '.(boolval(new stdClass) ? 'true' : 'false')."\n";
?>

The above example will output:

0:        false
42:       true
0.0:      false
4.2:      true
"":       false
"string": true
"0":      false
"1":      true
[1, 2]:   true
[]:       false
stdClass: true

See Also

  • floatval() - Get float value of a variable
  • intval() - Get the integer value of a variable
  • strval() - Get string value of a variable
  • settype() - Set the type of a variable
  • is_bool() - Finds out whether a variable is a boolean
  • Type juggling


Dumps a string representation of an internal zend value to output

  • « boolval
  • doubleval »
  • PHP Manual
  • Variable handling Functions
  • Dumps a string representation of an internal zend value to output

debug_zval_dump

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

debug_zval_dump — Dumps a string representation of an internal zend value to output

Description

debug_zval_dump ( mixed $variable [, mixed $... ] ) : void

Dumps a string representation of an internal zend value to output.

Parameters

variable

The variable being evaluated.

Return Values

No value is returned.

Examples

Example #1 debug_zval_dump() example

<?php
$var1 = 'Hello World';
$var2 = '';

$var2 =& $var1;

debug_zval_dump(&$var1);
?>

The above example will output:

&string(11) "Hello World" refcount(3)

Note: Beware the refcount

The refcount value returned by this function is non-obvious in certain circumstances. For example, a developer might expect the above example to indicate a refcount of 2. The third reference is created when actually calling debug_zval_dump().

This behavior is further compounded when a variable is not passed to debug_zval_dump() by reference. To illustrate, consider a slightly modified version of the above example:

<?php
$var1 = 'Hello World';
$var2 = '';

$var2 =& $var1;

debug_zval_dump($var1); // not passed by reference, this time
?>

The above example will output:

string(11) "Hello World" refcount(1)

Why refcount(1)? Because a copy of $var1 is being made, when the function is called.

This function becomes even more confusing when a variable with a refcount of 1 is passed (by copy/value):

<?php
$var1 = 'Hello World';

debug_zval_dump($var1);
?>

The above example will output:

string(11) "Hello World" refcount(2)

A refcount of 2, here, is extremely non-obvious. Especially considering the above examples. So what's happening?

When a variable has a single reference (as did $var1 before it was used as an argument to debug_zval_dump()), PHP's engine optimizes the manner in which it is passed to a function. Internally, PHP treats $var1 like a reference (in that the refcount is increased for the scope of this function), with the caveat that if the passed reference happens to be written to, a copy is made, but only at the moment of writing. This is known as "copy on write."

So, if debug_zval_dump() happened to write to its sole parameter (and it doesn't), then a copy would be made. Until then, the parameter remains a reference, causing the refcount to be incremented to 2 for the scope of the function call.

See Also

  • var_dump() - Dumps information about a variable
  • debug_backtrace() - Generates a backtrace
  • References Explained
  • » References Explained (by Derick Rethans)


Alias of floatval

  • « debug_zval_dump
  • empty »
  • PHP Manual
  • Variable handling Functions
  • Alias of floatval

doubleval

(PHP 4, PHP 5, PHP 7)

doubleval — Alias of floatval()

Description

This function is an alias of: floatval().


Determine whether a variable is empty

  • « doubleval
  • floatval »
  • PHP Manual
  • Variable handling Functions
  • Determine whether a variable is empty

empty

(PHP 4, PHP 5, PHP 7)

empty — Determine whether a variable is empty

Description

empty ( mixed $var ) : bool

Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE. empty() does not generate a warning if the variable does not exist.

Parameters

var

Variable to be checked

Note:

Prior to PHP 5.5, empty() only supports variables; anything else will result in a parse error. In other words, the following will not work: empty(trim($name)). Instead, use trim($name) == false.

No warning is generated if the variable does not exist. That means empty() is essentially the concise equivalent to !isset($var) || $var == false.

Return Values

Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.

The following values are considered to be empty:

  • "" (an empty string)
  • 0 (0 as an integer)
  • 0.0 (0 as a float)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)

Changelog

Version | Description
5.5.0 | empty() now supports expressions, rather than only variables.
5.4.0 | Checking non-numeric offsets of strings returns TRUE.

Examples

Example #1 A simple empty() / isset() comparison.

<?php
$var = 0;

// Evaluates to true because $var is empty
if (empty($var)) {
    echo '$var is either 0, empty, or not set at all';
}

// Evaluates as true because $var is set
if (isset($var)) {
    echo '$var is set even though it is empty';
}
?>

Example #2 empty() on String Offsets

PHP 5.4 changes how empty() behaves when passed string offsets.

<?php
$expected_array_got_string = 'somestring';
var_dump(empty($expected_array_got_string['some_key']));
var_dump(empty($expected_array_got_string[0]));
var_dump(empty($expected_array_got_string['0']));
var_dump(empty($expected_array_got_string[0.5]));
var_dump(empty($expected_array_got_string['0.5']));
var_dump(empty($expected_array_got_string['0 Mostel']));
?>

Output of the above example in PHP 5.3:

bool(false)
bool(false)
bool(false)
bool(false)
bool(false)
bool(false)

Output of the above example in PHP 5.4:

bool(true)
bool(false)
bool(false)
bool(false)
bool(true)
bool(true)

Notes

Note: Because this is a language construct and not a function, it cannot be called using variable functions.

Note:

When using empty() on inaccessible object properties, the __isset() overloading method will be called, if declared.

See Also

  • isset() - Determine if a variable is declared and is different than NULL
  • __isset()
  • unset() - Unset a given variable
  • array_key_exists() - Checks if the given key or index exists in the array
  • count() - Count all elements in an array, or something in an object
  • strlen() - Get string length
  • The type comparison tables


Get float value of a variable

  • « empty
  • get_defined_vars »
  • PHP Manual
  • Variable handling Functions
  • Get float value of a variable

floatval

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

floatval — Get float value of a variable

Description

floatval ( mixed $var ) : float

Gets the float value of var.

Parameters

var

May be any scalar type. floatval() should not be used on objects, as doing so will emit an E_NOTICE level error and return 1.

Return Values

The float value of the given variable. Empty arrays return 0, non-empty arrays return 1.

Strings will most likely return 0 although this depends on the leftmost characters of the string. The common rules of float casting apply.

Examples

Example #1 floatval() Example

<?php
$var = '122.34343The';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 122.34343
?>

Example #2 floatval() non-numeric leftmost characters Example

<?php
$var = 'The122.34343';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 0
?>

See Also

  • boolval() - Get the boolean value of a variable
  • intval() - Get the integer value of a variable
  • strval() - Get string value of a variable
  • settype() - Set the type of a variable
  • Type juggling


Returns an array of all defined variables

  • « floatval
  • get_resource_type »
  • PHP Manual
  • Variable handling Functions
  • Returns an array of all defined variables

get_defined_vars

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

get_defined_vars — Returns an array of all defined variables

Description

get_defined_vars ( void ) : array

This function returns a multidimensional array containing a list of all defined variables, be them environment, server or user-defined variables, within the scope that get_defined_vars() is called.

Return Values

A multidimensional array with all the variables.

Examples

Example #1 get_defined_vars() Example

<?php
$b = array(1, 1, 2, 3, 5, 8);

$arr = get_defined_vars();

// print $b
print_r($arr["b"]);

/* print path to the PHP interpreter (if used as a CGI)
 * e.g. /usr/local/bin/php */
echo $arr["_"];

// print the command-line parameters if any
print_r($arr["argv"]);

// print all the server vars
print_r($arr["_SERVER"]);

// print all the available keys for the arrays of variables
print_r(array_keys(get_defined_vars()));
?>

See Also

  • isset() - Determine if a variable is declared and is different than NULL
  • get_defined_functions() - Returns an array of all defined functions
  • get_defined_constants() - Returns an associative array with the names of all the constants and their values


Returns the resource type

  • « get_defined_vars
  • gettype »
  • PHP Manual
  • Variable handling Functions
  • Returns the resource type

get_resource_type

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

get_resource_type — Returns the resource type

Description

get_resource_type ( resource $handle ) : string

This function gets the type of the given resource.

Parameters

handle

The evaluated resource handle.

Return Values

If the given handle is a resource, this function will return a string representing its type. If the type is not identified by this function, the return value will be the string Unknown.

This function will return NULL and generate an error if handle is not a resource.

Changelog

Version | Description
5.3.0 | If handle is not a resource this functions returns NULL. Formerly, FALSE has been returned.

Examples

Example #1 get_resource_type() example

<?php
// prints: mysql link
$c = mysql_connect();
echo get_resource_type($c) . "\n";

// prints: stream
$fp = fopen("foo", "w");
echo get_resource_type($fp) . "\n";

// prints: domxml document
$doc = new_xmldoc("1.0");
echo get_resource_type($doc->doc) . "\n";
?>


Get the type of a variable

  • « get_resource_type
  • import_request_variables »
  • PHP Manual
  • Variable handling Functions
  • Get the type of a variable

gettype

(PHP 4, PHP 5, PHP 7)

gettype — Get the type of a variable

Description

gettype ( mixed $var ) : string

Returns the type of the PHP variable var. For type checking, use is_* functions.

Parameters

var

The variable being type checked.

Return Values

Possible values for the returned string are:

  • "boolean"
  • "integer"
  • "double" (for historical reasons "double" is returned in case of a float, and not simply "float")
  • "string"
  • "array"
  • "object"
  • "resource"
  • "resource (closed)" as of PHP 7.2.0
  • "NULL"
  • "unknown type"

Examples

Example #1 gettype() example

<?php

$data = array(1, 1., NULL, new stdClass, 'foo');

foreach ($data as $value) {
    echo gettype($value), "\n";
}

?>

The above example will output something similar to:

integer
double
NULL
object
string

Changelog

Version | Description
7.2.0 | Closed resources are now reported as 'resource (closed)'. Previously the returned value for closed resources were 'unknown type'.

See Also

  • settype() - Set the type of a variable
  • get_class() - Returns the name of the class of an object
  • is_array() - Finds whether a variable is an array
  • is_bool() - Finds out whether a variable is a boolean
  • is_callable() - Verify that the contents of a variable can be called as a function
  • is_float() - Finds whether the type of a variable is float
  • is_int() - Find whether the type of a variable is integer
  • is_null() - Finds whether a variable is NULL
  • is_numeric() - Finds whether a variable is a number or a numeric string
  • is_object() - Finds whether a variable is an object
  • is_resource() - Finds whether a variable is a resource
  • is_scalar() - Finds whether a variable is a scalar
  • is_string() - Find whether the type of a variable is string
  • function_exists() - Return TRUE if the given function has been defined
  • method_exists() - Checks if the class method exists


Import GET/POST/Cookie variables into the global scope

  • « gettype
  • intval »
  • PHP Manual
  • Variable handling Functions
  • Import GET/POST/Cookie variables into the global scope

import_request_variables

(PHP 4 >= 4.1.0, PHP 5 < 5.4.0)

import_request_variables — Import GET/POST/Cookie variables into the global scope

Description

import_request_variables ( string $types [, string $prefix ] ) : bool

Imports GET/POST/Cookie variables into the global scope. It is useful if you disabled register_globals, but would like to see some variables in the global scope.

If you're interested in importing other variables into the global scope, such as $_SERVER, consider using extract().

Warning

This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

Parameters

types

Using the types parameter, you can specify which request variables to import. You can use 'G', 'P' and 'C' characters respectively for GET, POST and Cookie. These characters are not case sensitive, so you can also use any combination of 'g', 'p' and 'c'. POST includes the POST uploaded file information.

Note:

Note that the order of the letters matters, as when using "GP", the POST variables will overwrite GET variables with the same name. Any other letters than GPC are discarded.

prefix

Variable name prefix, prepended before all variable's name imported into the global scope. So if you have a GET value named "userid", and provide a prefix "pref_", then you'll get a global variable named $pref_userid.

Note:

Although the prefix parameter is optional, you will get an E_NOTICE level error if you specify no prefix, or specify an empty string as a prefix. This is a possible security hazard. Notice level errors are not displayed using the default error reporting level.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 import_request_variables() example

<?php
// This will import GET and POST vars
// with an "rvar_" prefix
import_request_variables("gp", "rvar_");

echo $rvar_foo;
?>

See Also

  • $_REQUEST
  • register_globals
  • Predefined Variables
  • extract() - Import variables into the current symbol table from an array


Get the integer value of a variable

  • « import_request_variables
  • is_array »
  • PHP Manual
  • Variable handling Functions
  • Get the integer value of a variable

intval

(PHP 4, PHP 5, PHP 7)

intval — Get the integer value of a variable

Description

intval ( mixed $var [, int $base = 10 ] ) : int

Returns the integer value of var, using the specified base for the conversion (the default is base 10). intval() should not be used on objects, as doing so will emit an E_NOTICE level error and return 1.

Parameters

var

The scalar value being converted to an integer

base

The base for the conversion

Note:

If base is 0, the base used is determined by the format of var:

  • if string includes a "0x" (or "0X") prefix, the base is taken as 16 (hex); otherwise,
  • if string starts with "0", the base is taken as 8 (octal); otherwise,
  • the base is taken as 10 (decimal).

Return Values

The integer value of var on success, or 0 on failure. Empty arrays return 0, non-empty arrays return 1.

The maximum value depends on the system. 32 bit systems have a maximum signed integer range of -2147483648 to 2147483647. So for example on such a system, intval('1000000000000') will return 2147483647. The maximum signed integer value for 64 bit systems is 9223372036854775807.

Strings will most likely return 0 although this depends on the leftmost characters of the string. The common rules of integer casting apply.

Examples

Example #1 intval() examples

The following examples are based on a 32 bit system.

<?php
echo intval(42);                      // 42
echo intval(4.2);                     // 4
echo intval('42');                    // 42
echo intval('+42');                   // 42
echo intval('-42');                   // -42
echo intval(042);                     // 34
echo intval('042');                   // 42
echo intval(1e10);                    // 1410065408
echo intval('1e10');                  // 1
echo intval(0x1A);                    // 26
echo intval(42000000);                // 42000000
echo intval(420000000000000000000);   // 0
echo intval('420000000000000000000'); // 2147483647
echo intval(42, 8);                   // 42
echo intval('42', 8);                 // 34
echo intval(array());                 // 0
echo intval(array('foo', 'bar'));     // 1
echo intval(false);                   // 0
echo intval(true);                    // 1
?>

Notes

Note:

The base parameter has no effect unless the var parameter is a string.

Changelog

Version | Description
5.1.0 | Throws E_NOTICE and returns 1, when an object is passed to var.

See Also

  • boolval() - Get the boolean value of a variable
  • floatval() - Get float value of a variable
  • strval() - Get string value of a variable
  • settype() - Set the type of a variable
  • is_numeric() - Finds whether a variable is a number or a numeric string
  • Type juggling
  • BCMath Arbitrary Precision Mathematics Functions


Finds whether a variable is an array

  • « intval
  • is_bool »
  • PHP Manual
  • Variable handling Functions
  • Finds whether a variable is an array

is_array

(PHP 4, PHP 5, PHP 7)

is_array — Finds whether a variable is an array

Description

is_array ( mixed $var ) : bool

Finds whether the given variable is an array.

Parameters

var

The variable being evaluated.

Return Values

Returns TRUE if var is an array, FALSE otherwise.

Examples

Example #1 Check that variable is an array

<?php
$yes = array('this', 'is', 'an array');

echo is_array($yes) ? 'Array' : 'not an Array';
echo "\n";

$no = 'this is a string';

echo is_array($no) ? 'Array' : 'not an Array';
?>

The above example will output:

Array
not an Array

See Also

  • is_float() - Finds whether the type of a variable is float
  • is_int() - Find whether the type of a variable is integer
  • is_string() - Find whether the type of a variable is string
  • is_object() - Finds whether a variable is an object


Finds out whether a variable is a boolean

  • « is_array
  • is_callable »
  • PHP Manual
  • Variable handling Functions
  • Finds out whether a variable is a boolean

is_bool

(PHP 4, PHP 5, PHP 7)

is_bool — Finds out whether a variable is a boolean

Description

is_bool ( mixed $var ) : bool

Finds whether the given variable is a boolean.

Parameters

var

The variable being evaluated.

Return Values

Returns TRUE if var is a boolean, FALSE otherwise.

Examples

Example #1 is_bool() examples

<?php
$a = false;
$b = 0;

// Since $a is a boolean, it will return true
if (is_bool($a) === true) {
    echo "Yes, this is a boolean";
}

// Since $b is not a boolean, it will return false
if (is_bool($b) === false) {
    echo "No, this is not a boolean";
}
?>

See Also

  • is_float() - Finds whether the type of a variable is float
  • is_int() - Find whether the type of a variable is integer
  • is_string() - Find whether the type of a variable is string
  • is_object() - Finds whether a variable is an object
  • is_array() - Finds whether a variable is an array


Verify that the contents of a variable can be called as a function

  • « is_bool
  • is_countable »
  • PHP Manual
  • Variable handling Functions
  • Verify that the contents of a variable can be called as a function

is_callable

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

is_callable — Verify that the contents of a variable can be called as a function

Description

is_callable ( mixed $var [, bool $syntax_only = FALSE [, string &$callable_name ]] ) : bool

Verify that the contents of a variable can be called as a function. This can check that a simple variable contains the name of a valid function, or that an array contains a properly encoded object and function name.

Parameters

var

The value to check

syntax_only

If set to TRUE the function only verifies that var might be a function or method. It will only reject simple variables that are not strings, or an array that does not have a valid structure to be used as a callback. The valid ones are supposed to have only 2 entries, the first of which is an object or a string, and the second a string.

callable_name

Receives the "callable name". In the example below it is "someClass::someMethod". Note, however, that despite the implication that someClass::SomeMethod() is a callable static method, this is not the case.

Return Values

Returns TRUE if var is callable, FALSE otherwise.

Examples

Example #1 is_callable() example

<?php
//  How to check a variable to see if it can be called
//  as a function.

//
//  Simple variable containing a function
//

function someFunction()
{
}

$functionVariable = 'someFunction';

var_dump(is_callable($functionVariable, false, $callable_name));  // bool(true)

echo $callable_name, "\n";  // someFunction

//
//  Array containing a method
//

class someClass {

  function someMethod()
  {
  }

}

$anObject = new someClass();

$methodVariable = array($anObject, 'someMethod');

var_dump(is_callable($methodVariable, true, $callable_name));  //  bool(true)

echo $callable_name, "\n";  //  someClass::someMethod

?>

Example #2 is_callable() and constructors

As of PHP 5.3.0 is_callable() reports constructors as not being callable. This affects PHP 5 style constructors (__construct) as well as PHP 4 style constructors (i.e. methods with the same name as the class). Formerly, both cases have been considered callable.

<?php

class Foo
{
    public function __construct() {}
    public function foo() {}
}

var_dump(
    is_callable(array('Foo', '__construct')),
    is_callable(array('Foo', 'foo'))
);

The above example will output:

bool(false)
bool(false)

See Also

  • function_exists() - Return TRUE if the given function has been defined
  • method_exists() - Checks if the class method exists


Verify that the contents of a variable is a countable value

  • « is_callable
  • is_double »
  • PHP Manual
  • Variable handling Functions
  • Verify that the contents of a variable is a countable value

is_countable

(PHP 7 >= 7.3.0)

is_countable — Verify that the contents of a variable is a countable value

Description

is_countable ( mixed $var ) : bool

Verify that the contents of a variable is an array or an object implementing Countable

Parameters

var

The value to check

Return Values

Returns TRUE if var is countable, FALSE otherwise.

Changelog

Version | Description
7.3.0 | is_countable() has been added.

Examples

Example #1 is_countable() examples

<?php
var_dump(is_countable([1, 2, 3])); // bool(true)
var_dump(is_countable(new ArrayIterator(['foo', 'bar', 'baz']))); // bool(true)
var_dump(is_countable(new ArrayIterator())); // bool(true)
var_dump(is_countable(new stdClass())); // bool(false)

See Also

  • is_array() - Finds whether a variable is an array
  • is_object() - Finds whether a variable is an object
  • is_iterable() - Verify that the contents of a variable is an iterable value
  • is_bool() - Finds out whether a variable is a boolean


Alias of is_float

  • « is_countable
  • is_float »
  • PHP Manual
  • Variable handling Functions
  • Alias of is_float

is_double

(PHP 4, PHP 5, PHP 7)

is_double — Alias of is_float()

Description

This function is an alias of: is_float().


Finds whether the type of a variable is float

  • « is_double
  • is_int »
  • PHP Manual
  • Variable handling Functions
  • Finds whether the type of a variable is float

is_float

(PHP 4, PHP 5, PHP 7)

is_float — Finds whether the type of a variable is float

Description

is_float ( mixed $var ) : bool

Finds whether the type of the given variable is float.

Note:

To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric().

Parameters

var

The variable being evaluated.

Return Values

Returns TRUE if var is a float, FALSE otherwise.

Examples

Example #1 is_float() example

var_dump(is_float(27.25));
var_dump(is_float('abc'));
var_dump(is_float(23));
var_dump(is_float(23.5));
var_dump(is_float(1e7));  //Scientific Notation
var_dump(is_float(true));
?>

The above example will output:

bool(true)
bool(false)
bool(false)
bool(true)
bool(true)
bool(false)

See Also

  • is_bool() - Finds out whether a variable is a boolean
  • is_int() - Find whether the type of a variable is integer
  • is_numeric() - Finds whether a variable is a number or a numeric string
  • is_string() - Find whether the type of a variable is string
  • is_array() - Finds whether a variable is an array
  • is_object() - Finds whether a variable is an object


Find whether the type of a variable is integer

  • « is_float
  • is_integer »
  • PHP Manual
  • Variable handling Functions
  • Find whether the type of a variable is integer

is_int

(PHP 4, PHP 5, PHP 7)

is_int — Find whether the type of a variable is integer

Description

is_int ( mixed $var ) : bool

Finds whether the type of the given variable is integer.

Note:

To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric().

Parameters

var

The variable being evaluated.

Return Values

Returns TRUE if var is an integer, FALSE otherwise.

Examples

Example #1 is_int() example

<?php
$values = array(23, "23", 23.5, "23.5", null, true, false);
foreach ($values as $value) {
    echo "is_int(";
    var_export($value);
    echo ") = ";
    var_dump(is_int($value));
}
?>

The above example will output:

is_int(23) = bool(true)
is_int('23') = bool(false)
is_int(23.5) = bool(false)
is_int('23.5') = bool(false)
is_int(NULL) = bool(false)
is_int(true) = bool(false)
is_int(false) = bool(false)

See Also

  • is_bool() - Finds out whether a variable is a boolean
  • is_float() - Finds whether the type of a variable is float
  • is_numeric() - Finds whether a variable is a number or a numeric string
  • is_string() - Find whether the type of a variable is string
  • is_array() - Finds whether a variable is an array
  • is_object() - Finds whether a variable is an object


Alias of is_int

  • « is_int
  • is_iterable »
  • PHP Manual
  • Variable handling Functions
  • Alias of is_int

is_integer

(PHP 4, PHP 5, PHP 7)

is_integer — Alias of is_int()

Description

This function is an alias of: is_int().


Verify that the contents of a variable is an iterable value

  • « is_integer
  • is_long »
  • PHP Manual
  • Variable handling Functions
  • Verify that the contents of a variable is an iterable value

is_iterable

(PHP 7 >= 7.1.0)

is_iterable — Verify that the contents of a variable is an iterable value

Description

is_iterable ( mixed $var ) : bool

Verify that the contents of a variable is accepted by the iterable pseudo-type, i.e. that it is either an array or an object implementing Traversable

Parameters

var

The value to check

Return Values

Returns TRUE if var is iterable, FALSE otherwise.

Examples

Example #1 is_iterable() examples

<?php

var_dump(is_iterable([1, 2, 3]));  // bool(true)
var_dump(is_iterable(new ArrayIterator([1, 2, 3])));  // bool(true)
var_dump(is_iterable((function () { yield 1; })()));  // bool(true)
var_dump(is_iterable(1));  // bool(false)
var_dump(is_iterable(new stdClass()));  // bool(false)

?>

See Also

  • is_array() - Finds whether a variable is an array


Alias of is_int

  • « is_iterable
  • is_null »
  • PHP Manual
  • Variable handling Functions
  • Alias of is_int

is_long

(PHP 4, PHP 5, PHP 7)

is_long — Alias of is_int()

Description

This function is an alias of: is_int().


Finds whether a variable is NULL

  • « is_long
  • is_numeric »
  • PHP Manual
  • Variable handling Functions
  • Finds whether a variable is NULL

is_null

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

is_null — Finds whether a variable is NULL

Description

is_null ( mixed $var ) : bool

Finds whether the given variable is NULL.

Parameters

var

The variable being evaluated.

Return Values

Returns TRUE if var is null, FALSE otherwise.

Examples

Example #1 is_null() example

<?php

error_reporting(E_ALL);

$foo = NULL;
var_dump(is_null($inexistent), is_null($foo));

?>
Notice: Undefined variable: inexistent in ...
bool(true)
bool(true)

See Also

  • The NULL type
  • isset() - Determine if a variable is declared and is different than NULL
  • is_bool() - Finds out whether a variable is a boolean
  • is_numeric() - Finds whether a variable is a number or a numeric string
  • is_float() - Finds whether the type of a variable is float
  • is_int() - Find whether the type of a variable is integer
  • is_string() - Find whether the type of a variable is string
  • is_object() - Finds whether a variable is an object
  • is_array() - Finds whether a variable is an array


Finds whether a variable is a number or a numeric string

  • « is_null
  • is_object »
  • PHP Manual
  • Variable handling Functions
  • Finds whether a variable is a number or a numeric string

is_numeric

(PHP 4, PHP 5, PHP 7)

is_numeric — Finds whether a variable is a number or a numeric string

Description

is_numeric ( mixed $var ) : bool

Finds whether the given variable is numeric. Numeric strings consist of optional sign, any number of digits, optional decimal part and optional exponential part. Thus +0123.45e6 is a valid numeric value. Hexadecimal (e.g. 0xf4c3b00c) and binary (e.g. 0b10100111001) notation is not allowed.

Parameters

var

The variable being evaluated.

Return Values

Returns TRUE if var is a number or a numeric string, FALSE otherwise.

Examples

Example #1 is_numeric() examples

<?php
$tests = array(
    "42",
    1337,
    0x539,
    02471,
    0b10100111001,
    1337e0,
    "0x539",
    "02471",
    "0b10100111001",
    "1337e0",
    "not numeric",
    array(),
    9.1,
    null
);

foreach ($tests as $element) {
    if (is_numeric($element)) {
        echo var_export($element, true) . " is numeric", PHP_EOL;
    } else {
        echo var_export($element, true) . " is NOT numeric", PHP_EOL;
    }
}
?>

The above example will output:

'42' is numeric
1337 is numeric
1337 is numeric
1337 is numeric
1337 is numeric
1337.0 is numeric
'0x539' is NOT numeric
'02471' is numeric
'0b10100111001' is NOT numeric
'1337e0' is numeric
'not numeric' is NOT numeric
array (
) is NOT numeric
9.1 is numeric
NULL is NOT numeric

Changelog

Version | Description
7.0.0 | Strings in hexadecimal (e.g. 0xf4c3b00c) notation are no longer regarded as numeric strings, i.e. is_numeric() returns FALSE now.

See Also

  • ctype_digit() - Check for numeric character(s)
  • is_bool() - Finds out whether a variable is a boolean
  • is_null() - Finds whether a variable is NULL
  • is_float() - Finds whether the type of a variable is float
  • is_int() - Find whether the type of a variable is integer
  • is_string() - Find whether the type of a variable is string
  • is_object() - Finds whether a variable is an object
  • is_array() - Finds whether a variable is an array


Finds whether a variable is an object

  • « is_numeric
  • is_real »
  • PHP Manual
  • Variable handling Functions
  • Finds whether a variable is an object

is_object

(PHP 4, PHP 5, PHP 7)

is_object — Finds whether a variable is an object

Description

is_object ( mixed $var ) : bool

Finds whether the given variable is an object.

Parameters

var

The variable being evaluated.

Return Values

Returns TRUE if var is an object, FALSE otherwise.

Examples

Example #1 is_object() example

<?php
// Declare a simple function to return an
// array from our object
function get_students($obj)
{
    if (!is_object($obj)) {
        return false;
    }

    return $obj->students;
}

// Declare a new class instance and fill up
// some values
$obj = new stdClass();
$obj->students = array('Kalle', 'Ross', 'Felipe');

var_dump(get_students(null));
var_dump(get_students($obj));
?>

Changelog

Version | Description
7.2.0 | is_object() now returns TRUE for unserialized objects without a class definition (class of __PHP_Incomplete_Class). Previously FALSE was returned.

See Also

  • is_bool() - Finds out whether a variable is a boolean
  • is_int() - Find whether the type of a variable is integer
  • is_float() - Finds whether the type of a variable is float
  • is_string() - Find whether the type of a variable is string
  • is_array() - Finds whether a variable is an array


Alias of is_float

  • « is_object
  • is_resource »
  • PHP Manual
  • Variable handling Functions
  • Alias of is_float

is_real

(PHP 4, PHP 5, PHP 7)

is_real — Alias of is_float()

Description

This function is an alias of: is_float().


Finds whether a variable is a resource

  • « is_real
  • is_scalar »
  • PHP Manual
  • Variable handling Functions
  • Finds whether a variable is a resource

is_resource

(PHP 4, PHP 5, PHP 7)

is_resource — Finds whether a variable is a resource

Description

is_resource ( mixed $var ) : bool

Finds whether the given variable is a resource.

Parameters

var

The variable being evaluated.

Return Values

Returns TRUE if var is a resource, FALSE otherwise.

Examples

Example #1 is_resource() example

<?php

$db_link = @mysql_connect('localhost', 'mysql_user', 'mysql_pass');
if (!is_resource($db_link)) {
    die('Can\'t connect : ' . mysql_error());
}

?>

Notes

Note:

is_resource() is not a strict type-checking method: it will return FALSE if var is a resource variable that has been closed.

See Also

  • The resource-type documentation
  • get_resource_type() - Returns the resource type


Finds whether a variable is a scalar

  • « is_resource
  • is_string »
  • PHP Manual
  • Variable handling Functions
  • Finds whether a variable is a scalar

is_scalar

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

is_scalar — Finds whether a variable is a scalar

Description

is_scalar ( mixed $var ) : bool

Finds whether the given variable is a scalar.

Scalar variables are those containing an integer, float, string or boolean. Types array, object and resource are not scalar.

Note:

is_scalar() does not consider resource type values to be scalar as resources are abstract datatypes which are currently based on integers. This implementation detail should not be relied upon, as it may change.

Note:

is_scalar() does not consider NULL to be scalar.

Parameters

var

The variable being evaluated.

Return Values

Returns TRUE if var is a scalar, FALSE otherwise.

Examples

Example #1 is_scalar() example

<?php
function show_var($var)
{
    if (is_scalar($var)) {
        echo $var;
    } else {
        var_dump($var);
    }
}
$pi = 3.1416;
$proteins = array("hemoglobin", "cytochrome c oxidase", "ferredoxin");

show_var($pi);
show_var($proteins)

?>

The above example will output:

3.1416
array(3) {
  [0]=>
  string(10) "hemoglobin"
  [1]=>
  string(20) "cytochrome c oxidase"
  [2]=>
  string(10) "ferredoxin"
}

See Also

  • is_float() - Finds whether the type of a variable is float
  • is_int() - Find whether the type of a variable is integer
  • is_numeric() - Finds whether a variable is a number or a numeric string
  • is_real() - Alias of is_float
  • is_string() - Find whether the type of a variable is string
  • is_bool() - Finds out whether a variable is a boolean
  • is_object() - Finds whether a variable is an object
  • is_array() - Finds whether a variable is an array


Find whether the type of a variable is string

  • « is_scalar
  • isset »
  • PHP Manual
  • Variable handling Functions
  • Find whether the type of a variable is string

is_string

(PHP 4, PHP 5, PHP 7)

is_string — Find whether the type of a variable is string

Description

is_string ( mixed $var ) : bool

Finds whether the type of the given variable is string.

Parameters

var

The variable being evaluated.

Return Values

Returns TRUE if var is of type string, FALSE otherwise.

Examples

Example #1 is_string() example

<?php
$values = array(false, true, null, 'abc', '23', 23, '23.5', 23.5, '', ' ', '0', 0);
foreach ($values as $value) {
    echo "is_string(";
    var_export($value);
    echo ") = ";
    echo var_dump(is_string($value));
}
?>

The above example will output:

is_string(false) = bool(false)
is_string(true) = bool(false)
is_string(NULL) = bool(false)
is_string('abc') = bool(true)
is_string('23') = bool(true)
is_string(23) = bool(false)
is_string('23.5') = bool(true)
is_string(23.5) = bool(false)
is_string('') = bool(true)
is_string(' ') = bool(true)
is_string('0') = bool(true)
is_string(0) = bool(false)

See Also

  • is_float() - Finds whether the type of a variable is float
  • is_int() - Find whether the type of a variable is integer
  • is_bool() - Finds out whether a variable is a boolean
  • is_object() - Finds whether a variable is an object
  • is_array() - Finds whether a variable is an array


Determine if a variable is declared and is different than NULL

  • « is_string
  • print_r »
  • PHP Manual
  • Variable handling Functions
  • Determine if a variable is declared and is different than NULL

isset

(PHP 4, PHP 5, PHP 7)

isset — Determine if a variable is declared and is different than NULL

Description

isset ( mixed $var [, mixed $... ] ) : bool

Determine if a variable is considered set, this means if a variable is declared and is different than NULL.

If a variable has been unset with the unset() function, it is no longer considered to be set.

isset() will return FALSE when checking a variable that has been assigned to NULL. Also note that a null character ("\0") is not equivalent to the PHP NULL constant.

If multiple parameters are supplied then isset() will return TRUE only if all of the parameters are considered set. Evaluation goes from left to right and stops as soon as an unset variable is encountered.

Parameters

var

The variable to be checked.

...

Another variable ...

Return Values

Returns TRUE if var exists and has any value other than NULL. FALSE otherwise.

Changelog

Version | Description
5.4.0 | Checking non-numeric offsets of strings now returns FALSE.

Examples

Example #1 isset() Examples

<?php

$var = '';

// This will evaluate to TRUE so the text will be printed.
if (isset($var)) {
    echo "This var is set so I will print.";
}

// In the next examples we'll use var_dump to output
// the return value of isset().

$a = "test";
$b = "anothertest";

var_dump(isset($a));      // TRUE
var_dump(isset($a, $b)); // TRUE

unset ($a);

var_dump(isset($a));     // FALSE
var_dump(isset($a, $b)); // FALSE

$foo = NULL;
var_dump(isset($foo));   // FALSE

?>

This also work for elements in arrays:

<?php

$a = array ('test' => 1, 'hello' => NULL, 'pie' => array('a' => 'apple'));

var_dump(isset($a['test']));            // TRUE
var_dump(isset($a['foo']));             // FALSE
var_dump(isset($a['hello']));           // FALSE

// The key 'hello' equals NULL so is considered unset
// If you want to check for NULL key values then try:
var_dump(array_key_exists('hello', $a)); // TRUE

// Checking deeper array values
var_dump(isset($a['pie']['a']));        // TRUE
var_dump(isset($a['pie']['b']));        // FALSE
var_dump(isset($a['cake']['a']['b']));  // FALSE

?>

Example #2 isset() on String Offsets

PHP 5.4 changes how isset() behaves when passed string offsets.

<?php
$expected_array_got_string = 'somestring';
var_dump(isset($expected_array_got_string['some_key']));
var_dump(isset($expected_array_got_string[0]));
var_dump(isset($expected_array_got_string['0']));
var_dump(isset($expected_array_got_string[0.5]));
var_dump(isset($expected_array_got_string['0.5']));
var_dump(isset($expected_array_got_string['0 Mostel']));
?>

Output of the above example in PHP 5.3:

bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)

Output of the above example in PHP 5.4:

bool(false)
bool(true)
bool(true)
bool(true)
bool(false)
bool(false)

Notes

Warning

isset() only works with variables as passing anything else will result in a parse error. For checking if constants are set use the defined() function.

Note: Because this is a language construct and not a function, it cannot be called using variable functions.

Note:

When using isset() on inaccessible object properties, the __isset() overloading method will be called, if declared.

See Also

  • empty() - Determine whether a variable is empty
  • __isset()
  • unset() - Unset a given variable
  • defined() - Checks whether a given named constant exists
  • the type comparison tables
  • array_key_exists() - Checks if the given key or index exists in the array
  • is_null() - Finds whether a variable is NULL
  • the error control @ operator


Prints human-readable information about a variable

  • « isset
  • serialize »
  • PHP Manual
  • Variable handling Functions
  • Prints human-readable information about a variable

print_r

(PHP 4, PHP 5, PHP 7)

print_r — Prints human-readable information about a variable

Description

print_r ( mixed $expression [, bool $return = FALSE ] ) : mixed

print_r() displays information about a variable in a way that's readable by humans.

print_r(), var_dump() and var_export() will also show protected and private properties of objects. Static class members will not be shown.

Parameters

expression

The expression to be printed.

return

If you would like to capture the output of print_r(), use the return parameter. When this parameter is set to TRUE, print_r() will return the information rather than print it.

Return Values

If given a string, integer or float, the value itself will be printed. If given an array, values will be presented in a format that shows keys and elements. Similar notation is used for objects.

When the return parameter is TRUE, this function will return a string. Otherwise, the return value is TRUE.

Notes

Note:

When the return parameter is used, this function uses internal output buffering so it cannot be used inside an ob_start() callback function.

Examples

Example #1 print_r() example

<pre>
<?php
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
print_r ($a);
?>
</pre>

The above example will output:

<pre>
Array
(
    [a] => apple
    [b] => banana
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
        )
)
</pre>

Example #2 return parameter example

<?php
$b = array ('m' => 'monkey', 'foo' => 'bar', 'x' => array ('x', 'y', 'z'));
$results = print_r($b, true); // $results now contains output from print_r
?>

See Also

  • ob_start() - Turn on output buffering
  • var_dump() - Dumps information about a variable
  • var_export() - Outputs or returns a parsable string representation of a variable


Generates a storable representation of a value

  • « print_r
  • settype »
  • PHP Manual
  • Variable handling Functions
  • Generates a storable representation of a value

serialize

(PHP 4, PHP 5, PHP 7)

serialize — Generates a storable representation of a value

Description

serialize ( mixed $value ) : string

Generates a storable representation of a value.

This is useful for storing or passing PHP values around without losing their type and structure.

To make the serialized string into a PHP value again, use unserialize().

Parameters

value

The value to be serialized. serialize() handles all types, except the resource-type and some objects (see note below). You can even serialize() arrays that contain references to itself. Circular references inside the array/object you are serializing will also be stored. Any other reference will be lost.

When serializing objects, PHP will attempt to call the member function __sleep() prior to serialization. This is to allow the object to do any last minute clean-up, etc. prior to being serialized. Likewise, when the object is restored using unserialize() the __wakeup() member function is called.

Note:

Object's private members have the class name prepended to the member name; protected members have a '*' prepended to the member name. These prepended values have null bytes on either side.

Return Values

Returns a string containing a byte-stream representation of value that can be stored anywhere.

Note that this is a binary string which may include null bytes, and needs to be stored and handled as such. For example, serialize() output should generally be stored in a BLOB field in a database, rather than a CHAR or TEXT field.

Examples

Example #1 serialize() example

<?php
// $session_data contains a multi-dimensional array with session
// information for the current user.  We use serialize() to store
// it in a database at the end of the request.

$conn = odbc_connect("webdb", "php", "chicken");
$stmt = odbc_prepare($conn,
      "UPDATE sessions SET data = ? WHERE id = ?");
$sqldata = array (serialize($session_data), $_SERVER['PHP_AUTH_USER']);
if (!odbc_execute($stmt, $sqldata)) {
    $stmt = odbc_prepare($conn,
     "INSERT INTO sessions (id, data) VALUES(?, ?)");
    if (!odbc_execute($stmt, $sqldata)) {
        /* Something went wrong.. */
    }
}
?>

Notes

Note:

Note that many built-in PHP objects cannot be serialized. However, those with this ability either implement the Serializable interface or the magic __sleep() and __wakeup() methods. If an internal class does not fulfill any of those requirements, it cannot reliably be serialized.

There are some historical exceptions to the above rule, where some internal objects could be serialized without implementing the interface or exposing the methods. Notably, the ArrayObject prior to PHP 5.2.0.

Warning

When serialize() serializes objects, the leading backslash is not included in the class name of namespaced classes for maximum compatibility.

See Also

  • unserialize() - Creates a PHP value from a stored representation
  • var_export() - Outputs or returns a parsable string representation of a variable
  • json_encode() - Returns the JSON representation of a value
  • Serializing Objects
  • __sleep()
  • __wakeup()


Set the type of a variable

  • « serialize
  • strval »
  • PHP Manual
  • Variable handling Functions
  • Set the type of a variable

settype

(PHP 4, PHP 5, PHP 7)

settype — Set the type of a variable

Description

settype ( mixed &$var , string $type ) : bool

Set the type of variable var to type.

Parameters

var

The variable being converted.

type

Possibles values of type are:

  • "boolean" or "bool"
  • "integer" or "int"
  • "float" or "double"
  • "string"
  • "array"
  • "object"
  • "null"

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 settype() example

<?php
$foo = "5bar"; // string
$bar = true;   // boolean

settype($foo, "integer"); // $foo is now 5   (integer)
settype($bar, "string");  // $bar is now "1" (string)
?>

Notes

Note:

Maximum value for "int" is PHP_INT_MAX.

See Also

  • gettype() - Get the type of a variable
  • type-casting
  • type-juggling


Get string value of a variable

  • « settype
  • unserialize »
  • PHP Manual
  • Variable handling Functions
  • Get string value of a variable

strval

(PHP 4, PHP 5, PHP 7)

strval — Get string value of a variable

Description

strval ( mixed $var ) : string

Get the string value of a variable. See the documentation on string for more information on converting to string.

This function performs no formatting on the returned value. If you are looking for a way to format a numeric value as a string, please see sprintf() or number_format().

Parameters

var

The variable that is being converted to a string.

var may be any scalar type or an object that implements the __toString() method. You cannot use strval() on arrays or on objects that do not implement the __toString() method.

Return Values

The string value of var.

Examples

Example #1 strval() example using PHP 5's magic __toString() method.

<?php
class StrValTest
{
    public function __toString()
    {
        return __CLASS__;
    }
}

// Prints 'StrValTest'
echo strval(new StrValTest);
?>

See Also

  • boolval() - Get the boolean value of a variable
  • floatval() - Get float value of a variable
  • intval() - Get the integer value of a variable
  • settype() - Set the type of a variable
  • sprintf() - Return a formatted string
  • number_format() - Format a number with grouped thousands
  • Type juggling
  • __toString()


Creates a PHP value from a stored representation

  • « strval
  • unset »
  • PHP Manual
  • Variable handling Functions
  • Creates a PHP value from a stored representation

unserialize

(PHP 4, PHP 5, PHP 7)

unserialize — Creates a PHP value from a stored representation

Description

unserialize ( string $str [, array $options ] ) : mixed

unserialize() takes a single serialized variable and converts it back into a PHP value.

Warning

Do not pass untrusted user input to unserialize() regardless of the options value of allowed_classes. Unserialization can result in code being loaded and executed due to object instantiation and autoloading, and a malicious user may be able to exploit this. Use a safe, standard data interchange format such as JSON (via json_decode() and json_encode()) if you need to pass serialized data to the user.

If you need to unserialize externally-stored serialized data, consider using hash_hmac() for data validation. Make sure data is not modified by anyone but you.

Parameters

str

The serialized string.

If the variable being unserialized is an object, after successfully reconstructing the object PHP will automatically attempt to call the __wakeup() member function (if it exists).

Note: unserialize_callback_func directive

It's possible to set a callback-function which will be called, if an undefined class should be instantiated during unserializing. (to prevent getting an incomplete object "__PHP_Incomplete_Class".) Use your php.ini, ini_set() or .htaccess to define unserialize_callback_func. Everytime an undefined class should be instantiated, it'll be called. To disable this feature just empty this setting.

options

Any options to be provided to unserialize(), as an associative array.

Valid options
Name | Type | Description
allowed_classes | mixed | Either an array of class names which should be accepted, FALSE to accept no classes, or TRUE to accept all classes. If this option is defined and unserialize() encounters an object of a class that isn't to be accepted, then the object will be instantiated as __PHP_Incomplete_Class instead. Omitting this option is the same as defining it as TRUE: PHP will attempt to instantiate objects of any class.

Return Values

The converted value is returned, and can be a boolean, integer, float, string, array or object.

In case the passed string is not unserializeable, FALSE is returned and E_NOTICE is issued.

Changelog

Version | Description
7.1.0 | The allowed_classes element of options) is now strictly typed, i.e. if anything other than an array or a boolean is given, unserialize() returns FALSE and issues an E_WARNING.
7.0.0 | The options parameter has been added.
5.6.0 | Manipulating the serialised data by replacing C: with O: to force object instantiation without calling the constructor will now fail.

Examples

Example #1 unserialize() example

<?php
// Here, we use unserialize() to load session data to the
// $session_data array from the string selected from a database.
// This example complements the one described with serialize().

$conn = odbc_connect("webdb", "php", "chicken");
$stmt = odbc_prepare($conn, "SELECT data FROM sessions WHERE id = ?");
$sqldata = array($_SERVER['PHP_AUTH_USER']);
if (!odbc_execute($stmt, $sqldata) || !odbc_fetch_into($stmt, $tmp)) {
    // if the execute or fetch fails, initialize to empty array
    $session_data = array();
} else {
    // we should now have the serialized data in $tmp[0].
    $session_data = unserialize($tmp[0]);
    if (!is_array($session_data)) {
        // something went wrong, initialize to empty array
        $session_data = array();
    }
}
?>

Example #2 unserialize_callback_func example

<?php
$serialized_object='O:1:"a":1:{s:5:"value";s:3:"100";}';

ini_set('unserialize_callback_func', 'mycallback'); // set your callback_function

function mycallback($classname)
{
    // just include a file containing your classdefinition
    // you get $classname to figure out which classdefinition is required
}
?>

Notes

Warning

FALSE is returned both in the case of an error and if unserializing the serialized FALSE value. It is possible to catch this special case by comparing str with serialize(false) or by catching the issued E_NOTICE.

See Also

  • json_encode() - Returns the JSON representation of a value
  • json_decode() - Decodes a JSON string
  • hash_hmac() - Generate a keyed hash value using the HMAC method
  • serialize() - Generates a storable representation of a value
  • Autoloading Classes
  • unserialize_callback_func
  • __wakeup()


Unset a given variable

  • « unserialize
  • var_dump »
  • PHP Manual
  • Variable handling Functions
  • Unset a given variable

unset

(PHP 4, PHP 5, PHP 7)

unset — Unset a given variable

Description

unset ( mixed $var [, mixed $... ] ) : void

unset() destroys the specified variables.

The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy.

If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.

<?php
function destroy_foo()
{
    global $foo;
    unset($foo);
}

$foo = 'bar';
destroy_foo();
echo $foo;
?>

The above example will output:

bar

To unset() a global variable inside of a function, then use the $GLOBALS array to do so:

<?php
function foo()
{
    unset($GLOBALS['bar']);
}

$bar = "something";
foo();
?>

If a variable that is PASSED BY REFERENCE is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.

<?php
function foo(&$bar)
{
    unset($bar);
    $bar = "blah";
}

$bar = 'something';
echo "$bar\n";

foo($bar);
echo "$bar\n";
?>

The above example will output:

something
something

If a static variable is unset() inside of a function, unset() destroys the variable only in the context of the rest of a function. Following calls will restore the previous value of a variable.

<?php
function foo()
{
    static $bar;
    $bar++;
    echo "Before unset: $bar, ";
    unset($bar);
    $bar = 23;
    echo "after unset: $bar\n";
}

foo();
foo();
foo();
?>

The above example will output:

Before unset: 1, after unset: 23
Before unset: 2, after unset: 23
Before unset: 3, after unset: 23

Parameters

var

The variable to be unset.

...

Another variable ...

Return Values

No value is returned.

Examples

Example #1 unset() example

<?php
// destroy a single variable
unset($foo);

// destroy a single element of an array
unset($bar['quux']);

// destroy more than one variable
unset($foo1, $foo2, $foo3);
?>

Example #2 Using (unset) casting

(unset) casting is often confused with the unset() function. (unset) casting serves only as a NULL-type cast, for completeness. It does not alter the variable it's casting. The (unset) cast is deprecated as of PHP 7.2.0.

<?php
$name = 'Felipe';

var_dump((unset) $name);
var_dump($name);
?>

The above example will output:

NULL
string(6) "Felipe"

Notes

Note: Because this is a language construct and not a function, it cannot be called using variable functions.

Note:

It is possible to unset even object properties visible in current context.

Note:

It is not possible to unset $this inside an object method.

Note:

When using unset() on inaccessible object properties, the __unset() overloading method will be called, if declared.

See Also

  • isset() - Determine if a variable is declared and is different than NULL
  • empty() - Determine whether a variable is empty
  • __unset()
  • array_splice() - Remove a portion of the array and replace it with something else
  • (unset) casting


Dumps information about a variable

  • « unset
  • var_export »
  • PHP Manual
  • Variable handling Functions
  • Dumps information about a variable

var_dump

(PHP 4, PHP 5, PHP 7)

var_dump — Dumps information about a variable

Description

var_dump ( mixed $expression [, mixed $... ] ) : void

This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.

All public, private and protected properties of objects will be returned in the output unless the object implements a __debugInfo() method (implemented in PHP 5.6.0).

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).

Parameters

expression

The variable you want to dump.

Return Values

No value is returned.

Examples

Example #1 var_dump() example

<?php
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
?>

The above example will output:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  array(3) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
    [2]=>
    string(1) "c"
  }
}
<?php

$b = 3.1;
$c = true;
var_dump($b, $c);

?>

The above example will output:

float(3.1)
bool(true)

See Also

  • print_r() - Prints human-readable information about a variable
  • debug_zval_dump() - Dumps a string representation of an internal zend value to output
  • var_export() - Outputs or returns a parsable string representation of a variable
  • __debugInfo()


Outputs or returns a parsable string representation of a variable

  • « var_dump
  • Web Services »
  • PHP Manual
  • Variable handling Functions
  • Outputs or returns a parsable string representation of a variable

var_export

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

var_export — Outputs or returns a parsable string representation of a variable

Description

var_export ( mixed $expression [, bool $return = FALSE ] ) : mixed

var_export() gets structured information about the given variable. It is similar to var_dump() with one exception: the returned representation is valid PHP code.

Parameters

expression

The variable you want to export.

return

If used and set to TRUE, var_export() will return the variable representation instead of outputting it.

Return Values

Returns the variable representation when the return parameter is used and evaluates to TRUE. Otherwise, this function will return NULL.

Notes

Note:

When the return parameter is used, this function uses internal output buffering so it cannot be used inside an ob_start() callback function.

Changelog

Version | Description
5.1.0 | Possibility to export classes and arrays containing classes using the __set_state() magic method.

Examples

Example #1 var_export() Examples

<?php
$a = array (1, 2, array ("a", "b", "c"));
var_export($a);
?>

The above example will output:

array (
  0 => 1,
  1 => 2,
  2 =>
  array (
    0 => 'a',
    1 => 'b',
    2 => 'c',
  ),
)
<?php

$b = 3.1;
$v = var_export($b, true);
echo $v;

?>

The above example will output:

3.1

Example #2 Exporting classes since PHP 5.1.0

<?php
class A { public $var; }
$a = new A;
$a->var = 5;
var_export($a);
?>

The above example will output:

A::__set_state(array(
   'var' => 5,
))

Example #3 Using __set_state() (since PHP 5.1.0)

<?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';

eval('$b = ' . var_export($a, true) . ';'); // $b = A::__set_state(array(
                                            //    'var1' => 5,
                                            //    'var2' => 'foo',
                                            // ));
var_dump($b);
?>

The above example will output:

object(A)#2 (2) {
  ["var1"]=>
  int(5)
  ["var2"]=>
  string(3) "foo"
}

Notes

Note:

Variables of type resource couldn't be exported by this function.

Note:

var_export() does not handle circular references as it would be close to impossible to generate parsable PHP code for that. If you want to do something with the full representation of an array or object, use serialize().

Warning

When var_export() exports objects, the leading backslash is not included in the class name of namespaced classes for maximum compatibility.

Note:

To be able to evaluate the PHP generated by var_export(), all processed objects must implement the magic __set_state method. Note that StdClass does not implement __set_state().

See Also

  • print_r() - Prints human-readable information about a variable
  • serialize() - Generates a storable representation of a value
  • var_dump() - Dumps information about a variable


Web Services

  • OAuth
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • OAuth Functions
    • OAuth — The OAuth class
    • OAuthProvider — The OAuthProvider class
    • OAuthException — OAuthException class
  • SCA
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • SCA Functions
  • SOAP
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • SOAP Functions
    • SoapClient — The SoapClient class
    • SoapServer — The SoapServer class
    • SoapFault — The SoapFault class
    • SoapHeader — The SoapHeader class
    • SoapParam — The SoapParam class
    • SoapVar — The SoapVar class
  • Yar — Yet Another RPC Framework
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Yar_Server — The Yar_Server class
    • Yar_Client — The Yar_Client class
    • Yar_Concurrent_Client — The Yar_Concurrent_Client class
    • Yar_Server_Exception — The Yar_Server_Exception class
    • Yar_Client_Exception — The Yar_Client_Exception class
  • XML-RPC
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • XML-RPC Functions


OAuth

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • FireEagle
  • OAuth Functions
    • oauth_get_sbs — Generate a Signature Base String
    • oauth_urlencode — Encode a URI to RFC 3986
  • OAuth — The OAuth class
    • OAuth::__construct — Create a new OAuth object
    • OAuth::__destruct — The destructor
    • OAuth::disableDebug — Turn off verbose debugging
    • OAuth::disableRedirects — Turn off redirects
    • OAuth::disableSSLChecks — Turn off SSL checks
    • OAuth::enableDebug — Turn on verbose debugging
    • OAuth::enableRedirects — Turn on redirects
    • OAuth::enableSSLChecks — Turn on SSL checks
    • OAuth::fetch — Fetch an OAuth protected resource
    • OAuth::generateSignature — Generate a signature
    • OAuth::getAccessToken — Fetch an access token
    • OAuth::getCAPath — Gets CA information
    • OAuth::getLastResponse — Get the last response
    • OAuth::getLastResponseHeaders — Get headers for last response
    • OAuth::getLastResponseInfo — Get HTTP information about the last response
    • OAuth::getRequestHeader — Generate OAuth header string signature
    • OAuth::getRequestToken — Fetch a request token
    • OAuth::setAuthType — Set authorization type
    • OAuth::setCAPath — Set CA path and info
    • OAuth::setNonce — Set the nonce for subsequent requests
    • OAuth::setRequestEngine — The setRequestEngine purpose
    • OAuth::setRSACertificate — Set the RSA certificate
    • OAuth::setSSLChecks — Tweak specific SSL checks for requests
    • OAuth::setTimestamp — Set the timestamp
    • OAuth::setToken — Sets the token and secret
    • OAuth::setVersion — Set the OAuth version
  • OAuthProvider — The OAuthProvider class
    • OAuthProvider::addRequiredParameter — Add required parameters
    • OAuthProvider::callconsumerHandler — Calls the consumerNonceHandler callback
    • OAuthProvider::callTimestampNonceHandler — Calls the timestampNonceHandler callback
    • OAuthProvider::calltokenHandler — Calls the tokenNonceHandler callback
    • OAuthProvider::checkOAuthRequest — Check an oauth request
    • OAuthProvider::__construct — Constructs a new OAuthProvider object
    • OAuthProvider::consumerHandler — Set the consumerHandler handler callback
    • OAuthProvider::generateToken — Generate a random token
    • OAuthProvider::is2LeggedEndpoint — is2LeggedEndpoint
    • OAuthProvider::isRequestTokenEndpoint — Sets isRequestTokenEndpoint
    • OAuthProvider::removeRequiredParameter — Remove a required parameter
    • OAuthProvider::reportProblem — Report a problem
    • OAuthProvider::setParam — Set a parameter
    • OAuthProvider::setRequestTokenPath — Set request token path
    • OAuthProvider::timestampNonceHandler — Set the timestampNonceHandler handler callback
    • OAuthProvider::tokenHandler — Set the tokenHandler handler callback
  • OAuthException — OAuthException class


Introduction

This extension provides OAuth 1.0a consumer and provider bindings. OAuth is an authorization protocol built on top of HTTP which allows applications to securely access data without having to store usernames and passwords.


Requirements

PECL/oauth requires PHP 5.1 or newer, ext/hash and ext/pcre.

PECL/oauth may optionally require libcurl if selected at build time. If configured with libcurl, it must be built with HTTPS 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://pear.php.net/package/oauth


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.

Most of these constants involve problems, which are also described within the official OAuth » Problem Reporting documentation. Note however, that these constant names are specific to PHP, although the naming scheme is similar.

OAUTH_SIG_METHOD_RSASHA1 (string)
OAuth RSA-SHA1 signature method.
OAUTH_SIG_METHOD_HMACSHA1 (string)

OAuth HMAC-SHA1 signature method.

OAUTH_SIG_METHOD_HMACSHA256 (string)
OAuth HMAC-SHA256 signature method.
OAUTH_AUTH_TYPE_AUTHORIZATION (string)

This constant represents putting OAuth parameters in the Authorization header.

OAUTH_AUTH_TYPE_NONE (string)

This constant indicates a NoAuth OAuth request.

OAUTH_AUTH_TYPE_URI (string)

This constant represents putting OAuth parameters in the request URI.

OAUTH_AUTH_TYPE_FORM (string)

This constant represents putting OAuth parameters as part of the HTTP POST body.

OAUTH_HTTP_METHOD_GET (string)

Use the GET method for the OAuth request.

OAUTH_HTTP_METHOD_POST (string)

Use the POST method for the OAuth request.

OAUTH_HTTP_METHOD_PUT (string)

Use the PUT method for the OAuth request.

OAUTH_HTTP_METHOD_HEAD (string)

Use the HEAD method for the OAuth request.

OAUTH_HTTP_METHOD_DELETE (string)
Use the DELETE method for the OAuth request.
OAUTH_REQENGINE_STREAMS (integer)
Used by OAuth::setRequestEngine() to set the engine to PHP streams, as opposed to OAUTH_REQENGINE_CURL for Curl.
OAUTH_REQENGINE_CURL (integer)
Used by OAuth::setRequestEngine() to set the engine to Curl, as opposed to OAUTH_REQENGINE_STREAMS for PHP streams.
OAUTH_OK (integer)
Life is good.
OAUTH_BAD_NONCE (integer)
The oauth_nonce value was used in a previous request, therefore it cannot be used now.
OAUTH_BAD_TIMESTAMP (integer)
The oauth_timestamp value was not accepted by the service provider. In this case, the response should also contain the oauth_acceptable_timestamps parameter.
OAUTH_CONSUMER_KEY_UNKNOWN (integer)
The oauth_consumer_key is temporarily unacceptable to the service provider. For example, the service provider may be throttling the consumer.
OAUTH_CONSUMER_KEY_REFUSED (integer)
The consumer key was refused.
OAUTH_INVALID_SIGNATURE (integer)
The oauth_signature is invalid, as it does not match the signature computed by the service provider.
OAUTH_TOKEN_USED (integer)
The oauth_token has been consumed. It can no longer be used because it has already been used in the previous request(s).
OAUTH_TOKEN_EXPIRED (integer)
The oauth_token has expired.
OAUTH_TOKEN_REVOKED (integer)
The oauth_token has been revoked, and will never be accepted.
OAUTH_TOKEN_REJECTED (integer)
The oauth_token was not accepted by the service provider. The reason is not known, but it might be because the token was never issued, already consumed, expired, and/or forgotten by the service provider.
OAUTH_VERIFIER_INVALID (integer)
The oauth_verifier is incorrect.
OAUTH_PARAMETER_ABSENT (integer)
A required parameter was not received. In this case, the response should also contain the oauth_parameters_absent parameter.
OAUTH_SIGNATURE_METHOD_REJECTED (integer)
The oauth_signature_method was not accepted by service provider.


  • « Predefined Constants
  • FireEagle »
  • PHP Manual
  • OAuth
  • Examples

Examples

Table of Contents

  • FireEagle


FireEagle

<?php
$req_url = 'https://fireeagle.yahooapis.com/oauth/request_token';
$authurl = 'https://fireeagle.yahoo.net/oauth/authorize';
$acc_url = 'https://fireeagle.yahooapis.com/oauth/access_token';
$api_url = 'https://fireeagle.yahooapis.com/api/0.1';
$conskey = 'your_consumer_key';
$conssec = 'your_consumer_secret';

session_start();

// In state=1 the next request should include an oauth_token.
// If it doesn't go back to 0
if(!isset($_GET['oauth_token']) && $_SESSION['state']==1) $_SESSION['state'] = 0;
try {
  $oauth = new OAuth($conskey,$conssec,OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_URI);
  $oauth->enableDebug();
  if(!isset($_GET['oauth_token']) && !$_SESSION['state']) {
    $request_token_info = $oauth->getRequestToken($req_url);
    $_SESSION['secret'] = $request_token_info['oauth_token_secret'];
    $_SESSION['state'] = 1;
    header('Location: '.$authurl.'?oauth_token='.$request_token_info['oauth_token']);
    exit;
  } else if($_SESSION['state']==1) {
    $oauth->setToken($_GET['oauth_token'],$_SESSION['secret']);
    $access_token_info = $oauth->getAccessToken($acc_url);
    $_SESSION['state'] = 2;
    $_SESSION['token'] = $access_token_info['oauth_token'];
    $_SESSION['secret'] = $access_token_info['oauth_token_secret'];
  }
  $oauth->setToken($_SESSION['token'],$_SESSION['secret']);
  $oauth->fetch("$api_url/user.json");
  $json = json_decode($oauth->getLastResponse());
  print_r($json);
} catch(OAuthException $E) {
  print_r($E);
}
?>


OAuth Functions

Table of Contents

  • oauth_get_sbs — Generate a Signature Base String
  • oauth_urlencode — Encode a URI to RFC 3986


Generate a Signature Base String

  • « OAuth Functions
  • oauth_urlencode »
  • PHP Manual
  • OAuth Functions
  • Generate a Signature Base String

oauth_get_sbs

(PECL OAuth >=0.99.7)

oauth_get_sbs — Generate a Signature Base String

Description

oauth_get_sbs ( string $http_method , string $uri [, array $request_parameters ] ) : string

Generates a Signature Base String according to pecl/oauth.

Parameters

http_method

The HTTP method.

uri

URI to encode.

request_parameters

Array of request parameters.

Return Values

Returns a Signature Base String.


Encode a URI to RFC 3986

  • « oauth_get_sbs
  • OAuth »
  • PHP Manual
  • OAuth Functions
  • Encode a URI to RFC 3986

oauth_urlencode

(PECL OAuth >=0.99.2)

oauth_urlencode — Encode a URI to RFC 3986

Description

oauth_urlencode ( string $uri ) : string

Encodes a URI to » RFC 3986.

Parameters

uri

URI to encode.

Return Values

Returns an » RFC 3986 encoded string.


The OAuth class

(PECL OAuth >= 0.99.1)

Introduction

The OAuth extension provides a simple interface to interact with data providers using the OAuth HTTP specification to protect private resources.

Class synopsis

OAuth {
/* Properties */
public $debug ;
public $sslChecks ;
public $debugInfo ;
/* Methods */
public __construct ( string $consumer_key , string $consumer_secret [, string $signature_method = OAUTH_SIG_METHOD_HMACSHA1 [, int $auth_type = 0 ]] )
public __destruct ( void ) : void
public disableDebug ( void ) : bool
public disableRedirects ( void ) : bool
public disableSSLChecks ( void ) : bool
public enableDebug ( void ) : bool
public enableRedirects ( void ) : bool
public enableSSLChecks ( void ) : bool
public fetch ( string $protected_resource_url [, array $extra_parameters [, string $http_method [, array $http_headers ]]] ) : mixed
public generateSignature ( string $http_method , string $url [, mixed $extra_parameters ] ) : string
public getAccessToken ( string $access_token_url [, string $auth_session_handle [, string $verifier_token [, string $http_method ]]] ) : array
public getCAPath ( void ) : array
public getLastResponse ( void ) : string
public getLastResponseHeaders ( void ) : string
public getLastResponseInfo ( void ) : array
public getRequestHeader ( string $http_method , string $url [, mixed $extra_parameters ] ) : string
public getRequestToken ( string $request_token_url [, string $callback_url [, string $http_method ]] ) : array
public setAuthType ( int $auth_type ) : bool
public setCAPath ([ string $ca_path [, string $ca_info ]] ) : mixed
public setNonce ( string $nonce ) : mixed
public setRequestEngine ( int $reqengine ) : void
public setRSACertificate ( string $cert ) : mixed
public setSSLChecks ( int $sslcheck ) : bool
public setTimestamp ( string $timestamp ) : mixed
public setToken ( string $token , string $token_secret ) : bool
public setVersion ( string $version ) : bool
}

Properties

debug

sslChecks

debugInfo

Table of Contents

  • OAuth::__construct — Create a new OAuth object
  • OAuth::__destruct — The destructor
  • OAuth::disableDebug — Turn off verbose debugging
  • OAuth::disableRedirects — Turn off redirects
  • OAuth::disableSSLChecks — Turn off SSL checks
  • OAuth::enableDebug — Turn on verbose debugging
  • OAuth::enableRedirects — Turn on redirects
  • OAuth::enableSSLChecks — Turn on SSL checks
  • OAuth::fetch — Fetch an OAuth protected resource
  • OAuth::generateSignature — Generate a signature
  • OAuth::getAccessToken — Fetch an access token
  • OAuth::getCAPath — Gets CA information
  • OAuth::getLastResponse — Get the last response
  • OAuth::getLastResponseHeaders — Get headers for last response
  • OAuth::getLastResponseInfo — Get HTTP information about the last response
  • OAuth::getRequestHeader — Generate OAuth header string signature
  • OAuth::getRequestToken — Fetch a request token
  • OAuth::setAuthType — Set authorization type
  • OAuth::setCAPath — Set CA path and info
  • OAuth::setNonce — Set the nonce for subsequent requests
  • OAuth::setRequestEngine — The setRequestEngine purpose
  • OAuth::setRSACertificate — Set the RSA certificate
  • OAuth::setSSLChecks — Tweak specific SSL checks for requests
  • OAuth::setTimestamp — Set the timestamp
  • OAuth::setToken — Sets the token and secret
  • OAuth::setVersion — Set the OAuth version


Create a new OAuth object

  • « OAuth
  • OAuth::__destruct »
  • PHP Manual
  • OAuth
  • Create a new OAuth object

OAuth::__construct

(PECL OAuth >= 0.99.1)

OAuth::__construct — Create a new OAuth object

Description

public OAuth::__construct ( string $consumer_key , string $consumer_secret [, string $signature_method = OAUTH_SIG_METHOD_HMACSHA1 [, int $auth_type = 0 ]] )

Creates a new OAuth object

Parameters

consumer_key

The consumer key provided by the service provider.

consumer_secret

The consumer secret provided by the service provider.

signature_method

This optional parameter defines which signature method to use, by default it is OAUTH_SIG_METHOD_HMACSHA1 (HMAC-SHA1).

auth_type

This optional parameter defines how to pass the OAuth parameters to a consumer, by default it is OAUTH_AUTH_TYPE_AUTHORIZATION (in the Authorization header).


The destructor

  • « OAuth::__construct
  • OAuth::disableDebug »
  • PHP Manual
  • OAuth
  • The destructor

OAuth::__destruct

(PECL OAuth >= 0.99.9)

OAuth::__destruct — The destructor

Description

public OAuth::__destruct ( void ) : void

The destructor.

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.

See Also

  • OAuth::__construct() - Create a new OAuth object


Turn off verbose debugging

  • « OAuth::__destruct
  • OAuth::disableRedirects »
  • PHP Manual
  • OAuth
  • Turn off verbose debugging

OAuth::disableDebug

(PECL OAuth >= 0.99.3)

OAuth::disableDebug — Turn off verbose debugging

Description

public OAuth::disableDebug ( void ) : bool

Turns off verbose request information (off by default). Alternatively, the debug property can be set to a FALSE value to turn debug off.

Parameters

This function has no parameters.

Return Values

TRUE

Changelog

Version | Description
0.99.8 | The related debug property was added.

See Also

  • OAuth::enableDebug() - Turn on verbose debugging


Turn off redirects

  • « OAuth::disableDebug
  • OAuth::disableSSLChecks »
  • PHP Manual
  • OAuth
  • Turn off redirects

OAuth::disableRedirects

(PECL OAuth >= 0.99.9)

OAuth::disableRedirects — Turn off redirects

Description

public OAuth::disableRedirects ( void ) : bool

Disable redirects from being followed automatically, thus allowing the request to be manually redirected.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

TRUE

See Also

  • OAuth::enableRedirects() - Turn on redirects


Turn off SSL checks

  • « OAuth::disableRedirects
  • OAuth::enableDebug »
  • PHP Manual
  • OAuth
  • Turn off SSL checks

OAuth::disableSSLChecks

(PECL OAuth >= 0.99.5)

OAuth::disableSSLChecks — Turn off SSL checks

Description

public OAuth::disableSSLChecks ( void ) : bool

Turns off the usual SSL peer certificate and host checks, this is not for production environments. Alternatively, the sslChecks member can be set to FALSE to turn SSL checks off.

Parameters

This function has no parameters.

Return Values

TRUE

Changelog

Version | Description
0.99.8 | The sslChecks member was added

See Also

  • OAuth::enableSSLChecks() - Turn on SSL checks


Turn on verbose debugging

  • « OAuth::disableSSLChecks
  • OAuth::enableRedirects »
  • PHP Manual
  • OAuth
  • Turn on verbose debugging

OAuth::enableDebug

(PECL OAuth >= 0.99.3)

OAuth::enableDebug — Turn on verbose debugging

Description

public OAuth::enableDebug ( void ) : bool

Turns on verbose request information useful for debugging, the debug information is stored in the debugInfo member. Alternatively, the debug member can be set to a non-FALSE value to turn debug on.

Parameters

This function has no parameters.

Return Values

TRUE

Changelog

Version | Description
0.99.8 | The debug and debugInfo members were added

See Also

  • OAuth::disableDebug() - Turn off verbose debugging


Turn on redirects

  • « OAuth::enableDebug
  • OAuth::enableSSLChecks »
  • PHP Manual
  • OAuth
  • Turn on redirects

OAuth::enableRedirects

(PECL OAuth >= 0.99.9)

OAuth::enableRedirects — Turn on redirects

Description

public OAuth::enableRedirects ( void ) : bool

Follow and sign redirects automatically, which is enabled by default.

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

TRUE

See Also

  • OAuth::disableRedirects() - Turn off redirects


Turn on SSL checks

  • « OAuth::enableRedirects
  • OAuth::fetch »
  • PHP Manual
  • OAuth
  • Turn on SSL checks

OAuth::enableSSLChecks

(PECL OAuth >= 0.99.5)

OAuth::enableSSLChecks — Turn on SSL checks

Description

public OAuth::enableSSLChecks ( void ) : bool

Turns on the usual SSL peer certificate and host checks (enabled by default). Alternatively, the sslChecks member can be set to a non-FALSE value to turn SSL checks off.

Parameters

This function has no parameters.

Return Values

TRUE

Changelog

Version | Description
0.99.8 | The sslChecks member was added

See Also

  • OAuth::disableSSLChecks() - Turn off SSL checks


Fetch an OAuth protected resource

  • « OAuth::enableSSLChecks
  • OAuth::generateSignature »
  • PHP Manual
  • OAuth
  • Fetch an OAuth protected resource

OAuth::fetch

(PECL OAuth >= 0.99.1)

OAuth::fetch — Fetch an OAuth protected resource

Description

public OAuth::fetch ( string $protected_resource_url [, array $extra_parameters [, string $http_method [, array $http_headers ]]] ) : mixed

Fetch a resource.

Parameters

protected_resource_url

URL to the OAuth protected resource.

extra_parameters

Extra parameters to send with the request for the resource.

http_method

One of the OAUTH_HTTP_METHOD_* OAUTH constants, which includes GET, POST, PUT, HEAD, or DELETE.

HEAD (OAUTH_HTTP_METHOD_HEAD) can be useful for discovering information prior to the request (if OAuth credentials are in the Authorization header).

http_headers

HTTP client headers (such as User-Agent, Accept, etc.)

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
1.0.0 | Previously returned NULL on failure, instead of FALSE.
0.99.5 | The http_method parameter was added
0.99.8 | The http_headers parameter was added

Examples

Example #1 OAuth::fetch() example

<?php
try {
    $oauth = new OAuth("consumer_key","consumer_secret",OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_AUTHORIZATION);
    $oauth->setToken("access_token","access_token_secret");

    $oauth->fetch("http://photos.example.net/photo?file=vacation.jpg");

    $response_info = $oauth->getLastResponseInfo();
    header("Content-Type: {$response_info["content_type"]}");
    echo $oauth->getLastResponse();
} catch(OAuthException $E) {
    echo "Exception caught!\n";
    echo "Response: ". $E->lastResponse . "\n";
}
?>

See Also

  • OAuth::getLastResponse() - Get the last response
  • OAuth::getLastResponseInfo() - Get HTTP information about the last response
  • OAuth::setToken() - Sets the token and secret


Generate a signature

  • « OAuth::fetch
  • OAuth::getAccessToken »
  • PHP Manual
  • OAuth
  • Generate a signature

OAuth::generateSignature

(No version information available, might only be in Git)

OAuth::generateSignature — Generate a signature

Description

public OAuth::generateSignature ( string $http_method , string $url [, mixed $extra_parameters ] ) : string

Generate a signature based on the final HTTP method, URL and a string/array of parameters.

Parameters

http_method

HTTP method for request

url

URL for request

extra_parameters

String or array of additional parameters.

Return Values

A string containing the generated signature or FALSE on failure


Fetch an access token

  • « OAuth::generateSignature
  • OAuth::getCAPath »
  • PHP Manual
  • OAuth
  • Fetch an access token

OAuth::getAccessToken

(PECL OAuth >= 0.99.1)

OAuth::getAccessToken — Fetch an access token

Description

public OAuth::getAccessToken ( string $access_token_url [, string $auth_session_handle [, string $verifier_token [, string $http_method ]]] ) : array

Fetch an access token, secret and any additional response parameters from the service provider.

Parameters

access_token_url

URL to the access token API.

auth_session_handle

Authorization session handle, this parameter does not have any citation in the core OAuth 1.0 specification but may be implemented by large providers. » See ScalableOAuth for more information.

verifier_token

For service providers which support 1.0a, a verifier_token must be passed while exchanging the request token for the access token. If the verifier_token is present in $_GET or $_POST it is passed automatically and the caller does not need to specify a verifier_token (usually if the access token is exchanged at the oauth_callback URL). » See ScalableOAuth for more information.

http_method

HTTP method to use, e.g. GET or POST.

Return Values

Returns an array containing the parsed OAuth response on success or FALSE on failure.

Changelog

Version | Description
1.0.0 | Previously returned NULL on failure, instead of FALSE.
0.99.9 | The verifier_token parameter was added

Examples

Example #1 OAuth::getAccessToken() example

<?php
try {
    $oauth = new OAuth(OAUTH_CONSUMER_KEY,OAUTH_CONSUMER_SECRET);
    $oauth->setToken($request_token,$request_token_secret);
    $access_token_info = $oauth->getAccessToken("https://example.com/oauth/access_token");
    if(!empty($access_token_info)) {
        print_r($access_token_info);
    } else {
        print "Failed fetching access token, response was: " . $oauth->getLastResponse();
    }
} catch(OAuthException $E) {
    echo "Response: ". $E->lastResponse . "\n";
}
?>

The above example will output something similar to:

Array
(
    [oauth_token] => some_token
    [oauth_token_secret] => some_token_secret
)

See Also

  • OAuth::getLastResponse() - Get the last response
  • OAuth::getLastResponseInfo() - Get HTTP information about the last response
  • OAuth::setToken() - Sets the token and secret


Gets CA information

  • « OAuth::getAccessToken
  • OAuth::getLastResponse »
  • PHP Manual
  • OAuth
  • Gets CA information

OAuth::getCAPath

(PECL OAuth >= 0.99.8)

OAuth::getCAPath — Gets CA information

Description

public OAuth::getCAPath ( void ) : array

Gets the Certificate Authority information, which includes the ca_path and ca_info set by OAuth::setCaPath().

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values

An array of Certificate Authority information, specifically as ca_path and ca_info keys within the returned associative array.

See Also

  • OAuth::setCAPath() - Set CA path and info
  • OAuth::getLastResponseInfo() - Get HTTP information about the last response


Get the last response

  • « OAuth::getCAPath
  • OAuth::getLastResponseHeaders »
  • PHP Manual
  • OAuth
  • Get the last response

OAuth::getLastResponse

(PECL OAuth >= 0.99.1)

OAuth::getLastResponse — Get the last response

Description

public OAuth::getLastResponse ( void ) : string

Get the raw response of the most recent request.

Parameters

This function has no parameters.

Return Values

Returns a string containing the last response.

See Also

  • OAuth::getLastResponseInfo() - Get HTTP information about the last response
  • OAuth::fetch() - Fetch an OAuth protected resource


Get headers for last response

  • « OAuth::getLastResponse
  • OAuth::getLastResponseInfo »
  • PHP Manual
  • OAuth
  • Get headers for last response

OAuth::getLastResponseHeaders

(No version information available, might only be in Git)

OAuth::getLastResponseHeaders — Get headers for last response

Description

public OAuth::getLastResponseHeaders ( void ) : string

Get headers for last response.

Parameters

This function has no parameters.

Return Values

A string containing the last response's headers or FALSE on failure


Get HTTP information about the last response

  • « OAuth::getLastResponseHeaders
  • OAuth::getRequestHeader »
  • PHP Manual
  • OAuth
  • Get HTTP information about the last response

OAuth::getLastResponseInfo

(PECL OAuth >= 0.99.1)

OAuth::getLastResponseInfo — Get HTTP information about the last response

Description

public OAuth::getLastResponseInfo ( void ) : array

Get HTTP information about the last response.

Parameters

This function has no parameters.

Return Values

Returns an array containing the response information for the last request. Constants from curl_getinfo() may be used.

See Also

  • OAuth::fetch() - Fetch an OAuth protected resource
  • OAuth::getLastResponse() - Get the last response


Generate OAuth header string signature

  • « OAuth::getLastResponseInfo
  • OAuth::getRequestToken »
  • PHP Manual
  • OAuth
  • Generate OAuth header string signature

OAuth::getRequestHeader

(No version information available, might only be in Git)

OAuth::getRequestHeader — Generate OAuth header string signature

Description

public OAuth::getRequestHeader ( string $http_method , string $url [, mixed $extra_parameters ] ) : string

Generate OAuth header string signature based on the final HTTP method, URL and a string/array of parameters

Parameters

http_method

HTTP method for request.

url

URL for request.

extra_parameters

String or array of additional parameters.

Return Values

A string containing the generated request header or FALSE on failure


Fetch a request token

  • « OAuth::getRequestHeader
  • OAuth::setAuthType »
  • PHP Manual
  • OAuth
  • Fetch a request token

OAuth::getRequestToken

(PECL OAuth >= 0.99.1)

OAuth::getRequestToken — Fetch a request token

Description

public OAuth::getRequestToken ( string $request_token_url [, string $callback_url [, string $http_method ]] ) : array

Fetch a request token, secret and any additional response parameters from the service provider.

Parameters

request_token_url

URL to the request token API.

callback_url

OAuth callback URL. If callback_url is passed and is an empty value, it is set to "oob" to address the OAuth 2009.1 advisory.

http_method

HTTP method to use, e.g. GET or POST.

Return Values

Returns an array containing the parsed OAuth response on success or FALSE on failure.

Changelog

Version | Description
1.0.0 | Previously returned NULL on failure, instead of FALSE.
0.99.9 | The callback_url parameter was added

Examples

Example #1 OAuth::getRequestToken() example

<?php
try {
    $oauth = new OAuth(OAUTH_CONSUMER_KEY,OAUTH_CONSUMER_SECRET);
    $request_token_info = $oauth->getRequestToken("https://example.com/oauth/request_token");
    if(!empty($request_token_info)) {
        print_r($request_token_info);
    } else {
        print "Failed fetching request token, response was: " . $oauth->getLastResponse();
    }
} catch(OAuthException $E) {
    echo "Response: ". $E->lastResponse . "\n";
}
?>

The above example will output something similar to:

Array
(
    [oauth_token] => some_token
    [oauth_token_secret] => some_token_secret
)

See Also

  • OAuth::getLastResponse() - Get the last response
  • OAuth::getLastResponseInfo() - Get HTTP information about the last response


Set authorization type

  • « OAuth::getRequestToken
  • OAuth::setCAPath »
  • PHP Manual
  • OAuth
  • Set authorization type

OAuth::setAuthType

(PECL OAuth >= 0.99.1)

OAuth::setAuthType — Set authorization type

Description

public OAuth::setAuthType ( int $auth_type ) : bool

Set where the OAuth parameters should be passed.

Parameters

auth_type

auth_type can be one of the following flags (in order of decreasing preference as per OAuth 1.0 section 5.2):

OAUTH_AUTH_TYPE_AUTHORIZATION
Pass the OAuth parameters in the HTTP Authorization header.
OAUTH_AUTH_TYPE_FORM
Append the OAuth parameters to the HTTP POST request body.
OAUTH_AUTH_TYPE_URI
Append the OAuth parameters to the request URI.
OAUTH_AUTH_TYPE_NONE
None.

Return Values

Returns TRUE if a parameter is correctly set, otherwise FALSE (e.g., if an invalid auth_type is passed in.)

Changelog

Version | Description
1.0.0 | Previously returned NULL on failure, instead of FALSE.


Set CA path and info

  • « OAuth::setAuthType
  • OAuth::setNonce »
  • PHP Manual
  • OAuth
  • Set CA path and info

OAuth::setCAPath

(PECL OAuth >= 0.99.8)

OAuth::setCAPath — Set CA path and info

Description

public OAuth::setCAPath ([ string $ca_path [, string $ca_info ]] ) : mixed

Sets the Certificate Authority (CA), both for path and info.

Warning

This function is currently not documented; only its argument list is available.

Parameters

ca_path

The CA Path being set.

ca_info

The CA Info being set.

Return Values

Returns TRUE on success, or FALSE if either ca_path or ca_info are considered invalid.

Changelog

Version | Description
1.0.0 | Previously returned NULL on failure, instead of FALSE.

See Also

  • OAuth::getCaPath() - Gets CA information


Set the nonce for subsequent requests

  • « OAuth::setCAPath
  • OAuth::setRequestEngine »
  • PHP Manual
  • OAuth
  • Set the nonce for subsequent requests

OAuth::setNonce

(PECL OAuth >= 0.99.1)

OAuth::setNonce — Set the nonce for subsequent requests

Description

public OAuth::setNonce ( string $nonce ) : mixed

Sets the nonce for all subsequent requests.

Parameters

nonce

The value for oauth_nonce.

Return Values

Returns TRUE on success, or FALSE if the nonce is considered invalid.

Changelog

Version | Description
1.0.0 | Previously returned NULL on failure, instead of FALSE.

See Also

  • OAuth::setToken() - Sets the token and secret
  • OAuth::setAuthType() - Set authorization type
  • OAuth::setVersion() - Set the OAuth version


The setRequestEngine purpose

  • « OAuth::setNonce
  • OAuth::setRSACertificate »
  • PHP Manual
  • OAuth
  • The setRequestEngine purpose

OAuth::setRequestEngine

(PECL OAuth >= 1.0.0)

OAuth::setRequestEngine — The setRequestEngine purpose

Description

public OAuth::setRequestEngine ( int $reqengine ) : void

Sets the Request Engine, that will be sending the HTTP requests.

Warning

This function is currently not documented; only its argument list is available.

Parameters

reqengine

The desired request engine. Set to OAUTH_REQENGINE_STREAMS to use PHP Streams, or OAUTH_REQENGINE_CURL to use Curl.

Return Values

No value is returned.

Errors/Exceptions

Emits an OAuthException exception if an invalid request engine is chosen.

Examples

Example #1 OAuth::setRequestEngine() example

<?php
$consumer = new OAuth();

$consumer->setRequestEngine(OAUTH_REQENGINE_STREAMS);
?>

See Also

  • Curl
  • PHP streams
  • OAuthException


Set the RSA certificate

  • « OAuth::setRequestEngine
  • OAuth::setSSLChecks »
  • PHP Manual
  • OAuth
  • Set the RSA certificate

OAuth::setRSACertificate

(PECL OAuth >= 1.0.0)

OAuth::setRSACertificate — Set the RSA certificate

Description

public OAuth::setRSACertificate ( string $cert ) : mixed

Sets the RSA certificate.

Warning

This function is currently not documented; only its argument list is available.

Parameters

cert

The RSA certificate.

Return Values

Returns TRUE on success, or FALSE on failure (e.g., the RSA certificate cannot be parsed.)

Changelog

Version | Description
1.0.0 | Previously returned NULL on failure, instead of FALSE.

Examples

Example #1 An OAuth::setRsaCertificate() example

<?php
$consume = new OAuth('1234', '', OAUTH_SIG_METHOD_RSASHA1);

$consume->setRSACertificate(file_get_contents('test.pem'));
?>

See Also

  • OAuth::setCaPath() - Set CA path and info


Tweak specific SSL checks for requests

  • « OAuth::setRSACertificate
  • OAuth::setTimestamp »
  • PHP Manual
  • OAuth
  • Tweak specific SSL checks for requests

OAuth::setSSLChecks

(No version information available, might only be in Git)

OAuth::setSSLChecks — Tweak specific SSL checks for requests

Description

public OAuth::setSSLChecks ( int $sslcheck ) : bool

Tweak specific SSL checks for requests.

Warning

This function is currently not documented; only its argument list is available.

Parameters

sslcheck

Return Values

Returns TRUE on success or FALSE on failure.


Set the timestamp

  • « OAuth::setSSLChecks
  • OAuth::setToken »
  • PHP Manual
  • OAuth
  • Set the timestamp

OAuth::setTimestamp

(PECL OAuth >= 1.0.0)

OAuth::setTimestamp — Set the timestamp

Description

public OAuth::setTimestamp ( string $timestamp ) : mixed

Sets the OAuth timestamp for subsequent requests.

Warning

This function is currently not documented; only its argument list is available.

Parameters

timestamp

The timestamp.

Return Values

Returns TRUE, unless the timestamp is invalid, in which case FALSE is returned.

Changelog

Version | Description
1.0.0 | Previously returned NULL on failure, instead of FALSE.

See Also

  • OAuth::setNonce() - Set the nonce for subsequent requests


Sets the token and secret

  • « OAuth::setTimestamp
  • OAuth::setVersion »
  • PHP Manual
  • OAuth
  • Sets the token and secret

OAuth::setToken

(PECL OAuth >= 0.99.1)

OAuth::setToken — Sets the token and secret

Description

public OAuth::setToken ( string $token , string $token_secret ) : bool

Set the token and secret for subsequent requests.

Parameters

token

The OAuth token.

token_secret

The OAuth token secret.

Return Values

TRUE

Examples

Example #1 OAuth::setToken() example

<?php
$oauth = new OAuth(OAUTH_CONSUMER_KEY,OAUTH_CONSUMER_SECRET);
$oauth->setToken("token","token-secret");
?>


Set the OAuth version

  • « OAuth::setToken
  • OAuthProvider »
  • PHP Manual
  • OAuth
  • Set the OAuth version

OAuth::setVersion

(PECL OAuth >= 0.99.1)

OAuth::setVersion — Set the OAuth version

Description

public OAuth::setVersion ( string $version ) : bool

Sets the OAuth version for subsequent requests

Parameters

version

OAuth version, default value is always "1.0"

Return Values

Returns TRUE on success or FALSE on failure.


The OAuthProvider class

(PECL OAuth >= 1.0.0)

Introduction

Manages an OAuth provider class.

See also an external in-depth tutorial titled » Writing an OAuth Provider Service, which takes a hands-on approach to providing this service. There are also » OAuth provider examples within the OAuth extensions sources.

Class synopsis

OAuthProvider {
/* Methods */
final public addRequiredParameter ( string $req_params ) : bool
public callconsumerHandler ( void ) : void
public callTimestampNonceHandler ( void ) : void
public calltokenHandler ( void ) : void
public checkOAuthRequest ([ string $uri [, string $method ]] ) : void
public __construct ([ array $params_array ] )
public consumerHandler ( callable $callback_function ) : void
final public static generateToken ( int $size [, bool $strong = FALSE ] ) : string
public is2LeggedEndpoint ( mixed $params_array ) : void
public isRequestTokenEndpoint ( bool $will_issue_request_token ) : void
final public removeRequiredParameter ( string $req_params ) : bool
final public static reportProblem ( string $oauthexception [, bool $send_headers = TRUE ] ) : string
final public setParam ( string $param_key [, mixed $param_val ] ) : bool
final public setRequestTokenPath ( string $path ) : bool
public timestampNonceHandler ( callable $callback_function ) : void
public tokenHandler ( callable $callback_function ) : void
}

Table of Contents

  • OAuthProvider::addRequiredParameter — Add required parameters
  • OAuthProvider::callconsumerHandler — Calls the consumerNonceHandler callback
  • OAuthProvider::callTimestampNonceHandler — Calls the timestampNonceHandler callback
  • OAuthProvider::calltokenHandler — Calls the tokenNonceHandler callback
  • OAuthProvider::checkOAuthRequest — Check an oauth request
  • OAuthProvider::__construct — Constructs a new OAuthProvider object
  • OAuthProvider::consumerHandler — Set the consumerHandler handler callback
  • OAuthProvider::generateToken — Generate a random token
  • OAuthProvider::is2LeggedEndpoint — is2LeggedEndpoint
  • OAuthProvider::isRequestTokenEndpoint — Sets isRequestTokenEndpoint
  • OAuthProvider::removeRequiredParameter — Remove a required parameter
  • OAuthProvider::reportProblem — Report a problem
  • OAuthProvider::setParam — Set a parameter
  • OAuthProvider::setRequestTokenPath — Set request token path
  • OAuthProvider::timestampNonceHandler — Set the timestampNonceHandler handler callback
  • OAuthProvider::tokenHandler — Set the tokenHandler handler callback


Add required parameters

  • « OAuthProvider
  • OAuthProvider::callconsumerHandler »
  • PHP Manual
  • OAuthProvider
  • Add required parameters

OAuthProvider::addRequiredParameter

(PECL OAuth >= 1.0.0)

OAuthProvider::addRequiredParameter — Add required parameters

Description

final public OAuthProvider::addRequiredParameter ( string $req_params ) : bool

Add required oauth provider parameters.

Warning

This function is currently not documented; only its argument list is available.

Parameters

req_params

The required parameters.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • OAuthProvider::removeRequiredParameter() - Remove a required parameter


Calls the consumerNonceHandler callback

  • « OAuthProvider::addRequiredParameter
  • OAuthProvider::callTimestampNonceHandler »
  • PHP Manual
  • OAuthProvider
  • Calls the consumerNonceHandler callback

OAuthProvider::callconsumerHandler

(No version information available, might only be in Git)

OAuthProvider::callconsumerHandler — Calls the consumerNonceHandler callback

Description

public OAuthProvider::callconsumerHandler ( void ) : void

Calls the registered consumer handler callback function, which is set with OAuthProvider::consumerHandler().

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.

Errors/Exceptions

Emits an E_ERROR level error if the callback function cannot be called, or was not specified.

See Also

  • OAuthProvider::consumerHandler() - Set the consumerHandler handler callback


Calls the timestampNonceHandler callback

  • « OAuthProvider::callconsumerHandler
  • OAuthProvider::calltokenHandler »
  • PHP Manual
  • OAuthProvider
  • Calls the timestampNonceHandler callback

OAuthProvider::callTimestampNonceHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::callTimestampNonceHandler — Calls the timestampNonceHandler callback

Description

public OAuthProvider::callTimestampNonceHandler ( void ) : void

Calls the registered timestamp handler callback function, which is set with OAuthProvider::timestampNonceHandler().

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.

Errors/Exceptions

Emits an E_ERROR level error if the callback function cannot be called, or was not specified.

See Also

  • OAuthProvider::timestampNonceHandler() - Set the timestampNonceHandler handler callback


Calls the tokenNonceHandler callback

  • « OAuthProvider::callTimestampNonceHandler
  • OAuthProvider::checkOAuthRequest »
  • PHP Manual
  • OAuthProvider
  • Calls the tokenNonceHandler callback

OAuthProvider::calltokenHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::calltokenHandler — Calls the tokenNonceHandler callback

Description

public OAuthProvider::calltokenHandler ( void ) : void

Calls the registered token handler callback function, which is set with OAuthProvider::tokenHandler().

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.

Errors/Exceptions

Emits an E_ERROR level error if the callback function cannot be called, or was not specified.

See Also

  • OAuthProvider::tokenHandler() - Set the tokenHandler handler callback


Check an oauth request

  • « OAuthProvider::calltokenHandler
  • OAuthProvider::__construct »
  • PHP Manual
  • OAuthProvider
  • Check an oauth request

OAuthProvider::checkOAuthRequest

(PECL OAuth >= 1.0.0)

OAuthProvider::checkOAuthRequest — Check an oauth request

Description

public OAuthProvider::checkOAuthRequest ([ string $uri [, string $method ]] ) : void

Checks an OAuth request.

Warning

This function is currently not documented; only its argument list is available.

Parameters

uri

The optional URI, or endpoint.

method

The HTTP method. Optionally pass in one of the OAUTH_HTTP_METHOD_* OAuth constants.

Return Values

No value is returned.

Errors/Exceptions

Emits an E_ERROR level error if the HTTP method cannot be detected.

See Also

  • OAuthProvider::reportProblem() - Report a problem


Constructs a new OAuthProvider object

  • « OAuthProvider::checkOAuthRequest
  • OAuthProvider::consumerHandler »
  • PHP Manual
  • OAuthProvider
  • Constructs a new OAuthProvider object

OAuthProvider::__construct

(PECL OAuth >= 1.0.0)

OAuthProvider::__construct — Constructs a new OAuthProvider object

Description

public OAuthProvider::__construct ([ array $params_array ] )

Initiates a new OAuthProvider object.

Warning

This function is currently not documented; only its argument list is available.

Parameters

params_array

Setting these optional parameters is limited to the CLI SAPI.

Return Values

An OAuthProvider object.

Examples

Example #1 OAuthProvider::__construct() example

<?php
try {

    $op = new OAuthProvider();

    // Uses user-defined callback functions
    $op->consumerHandler(array($this, 'lookupConsumer'));
    $op->timestampNonceHandler(array($this, 'timestampNonceChecker'));
    $op->tokenHandler(array($this, 'myTokenHandler'));

    // Ignore the foo_uri parameter
    $op->setParam('foo_uri', NULL);

    // No token needed for this end point
    $op->setRequestTokenPath('/v1/oauth/request_token');

    $op->checkOAuthRequest();

} catch (OAuthException $e) {

    echo OAuthProvider::reportProblem($e);
}
?>

See Also

  • OAuthProvider::setParam() - Set a parameter


Set the consumerHandler handler callback

  • « OAuthProvider::__construct
  • OAuthProvider::generateToken »
  • PHP Manual
  • OAuthProvider
  • Set the consumerHandler handler callback

OAuthProvider::consumerHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::consumerHandler — Set the consumerHandler handler callback

Description

public OAuthProvider::consumerHandler ( callable $callback_function ) : void

Sets the consumer handler callback, which will later be called with OAuthProvider::callConsumerHandler().

Warning

This function is currently not documented; only its argument list is available.

Parameters

callback_function

The callable functions name.

Return Values

No value is returned.

Examples

Example #1 Example OAuthProvider::consumerHandler() callback

<?php
function lookupConsumer($provider) {

    if ($provider->consumer_key === 'unknown') {
        return OAUTH_CONSUMER_KEY_UNKNOWN;
    } else if($provider->consumer_key == 'blacklisted' || $provider->consumer_key === 'throttled') {
        return OAUTH_CONSUMER_KEY_REFUSED;
    }

    $provider->consumer_secret = "the_consumers_secret";

    return OAUTH_OK;
}
?>

See Also

  • OAuthProvider::callConsumerHandler() - Calls the consumerNonceHandler callback


Generate a random token

  • « OAuthProvider::consumerHandler
  • OAuthProvider::is2LeggedEndpoint »
  • PHP Manual
  • OAuthProvider
  • Generate a random token

OAuthProvider::generateToken

(PECL OAuth >= 1.0.0)

OAuthProvider::generateToken — Generate a random token

Description

final public static OAuthProvider::generateToken ( int $size [, bool $strong = FALSE ] ) : string

Generates a string of pseudo-random bytes.

Parameters

size

The desired token length, in terms of bytes.

strong

Setting to TRUE means /dev/random will be used for entropy, as otherwise the non-blocking /dev/urandom is used. This parameter is ignored on Windows.

Return Values

The generated token, as a string of bytes.

Errors/Exceptions

If the strong parameter is TRUE, then an E_WARNING level error will be emitted when the fallback rand() implementation is used to fill the remaining random bytes (e.g., when not enough random data was found, initially).

Examples

Example #1 OAuthProvider::generateToken() example

<?php
$p = new OAuthProvider();

$t = $p->generateToken(4);

echo strlen($t),  PHP_EOL;
echo bin2hex($t), PHP_EOL;

?>

The above example will output something similar to:

4
b6a82c27

Notes

Note:

When not enough random data is available to the system, this function will fill the remaining random bytes using the internal PHP rand() implementation.

See Also

  • openssl_random_pseudo_bytes() - Generate a pseudo-random string of bytes
  • mcrypt_create_iv() - Creates an initialization vector (IV) from a random source


is2LeggedEndpoint

  • « OAuthProvider::generateToken
  • OAuthProvider::isRequestTokenEndpoint »
  • PHP Manual
  • OAuthProvider
  • is2LeggedEndpoint

OAuthProvider::is2LeggedEndpoint

(PECL OAuth >= 1.0.0)

OAuthProvider::is2LeggedEndpoint — is2LeggedEndpoint

Description

public OAuthProvider::is2LeggedEndpoint ( mixed $params_array ) : void

The 2-legged flow, or request signing. It does not require a token.

Warning

This function is currently not documented; only its argument list is available.

Parameters

params_array

Return Values

An OAuthProvider object.

Examples

Example #1 OAuthProvider::is2LeggedEndpoint() example

<?php

$provider = new OAuthProvider();

$provider->is2LeggedEndpoint(true);

?>

See Also

  • OAuthProvider::__construct() - Constructs a new OAuthProvider object


Sets isRequestTokenEndpoint

  • « OAuthProvider::is2LeggedEndpoint
  • OAuthProvider::removeRequiredParameter »
  • PHP Manual
  • OAuthProvider
  • Sets isRequestTokenEndpoint

OAuthProvider::isRequestTokenEndpoint

(PECL OAuth >= 1.0.0)

OAuthProvider::isRequestTokenEndpoint — Sets isRequestTokenEndpoint

Description

public OAuthProvider::isRequestTokenEndpoint ( bool $will_issue_request_token ) : void

Warning

This function is currently not documented; only its argument list is available.

Parameters

will_issue_request_token

Sets whether or not it will issue a request token, thus determining if OAuthProvider::tokenHandler() needs to be called.

Return Values

No value is returned.

See Also

  • OAuthProvider::setRequestTokenPath() - Set request token path
  • OAuthProvider::reportProblem() - Report a problem


Remove a required parameter

  • « OAuthProvider::isRequestTokenEndpoint
  • OAuthProvider::reportProblem »
  • PHP Manual
  • OAuthProvider
  • Remove a required parameter

OAuthProvider::removeRequiredParameter

(PECL OAuth >= 1.0.0)

OAuthProvider::removeRequiredParameter — Remove a required parameter

Description

final public OAuthProvider::removeRequiredParameter ( string $req_params ) : bool

Removes a required parameter.

Warning

This function is currently not documented; only its argument list is available.

Parameters

req_params

The required parameter to be removed.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • OAuthProvider::setParam() - Set a parameter
  • OAuthProvider::addRequiredParameter() - Add required parameters


Report a problem

  • « OAuthProvider::removeRequiredParameter
  • OAuthProvider::setParam »
  • PHP Manual
  • OAuthProvider
  • Report a problem

OAuthProvider::reportProblem

(PECL OAuth >= 1.0.0)

OAuthProvider::reportProblem — Report a problem

Description

final public static OAuthProvider::reportProblem ( string $oauthexception [, bool $send_headers = TRUE ] ) : string

Pass in a problem as an OAuthException, with possible problems listed in the OAuth constants section.

Warning

This function is currently not documented; only its argument list is available.

Parameters

oauthexception

The OAuthException.

Return Values

No value is returned.

See Also

  • OAuthProvider::checkOAuthRequest() - Check an oauth request
  • OAuthProvider::isRequestTokenEndpoint() - Sets isRequestTokenEndpoint


Set a parameter

  • « OAuthProvider::reportProblem
  • OAuthProvider::setRequestTokenPath »
  • PHP Manual
  • OAuthProvider
  • Set a parameter

OAuthProvider::setParam

(PECL OAuth >= 1.0.0)

OAuthProvider::setParam — Set a parameter

Description

final public OAuthProvider::setParam ( string $param_key [, mixed $param_val ] ) : bool

Sets a parameter.

Warning

This function is currently not documented; only its argument list is available.

Parameters

param_key

The parameter key.

param_val

The optional parameter value.

To exclude a parameter from signature verification, set its value to NULL.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • OAuthProvider::addRequiredParameter() - Add required parameters


Set request token path

  • « OAuthProvider::setParam
  • OAuthProvider::timestampNonceHandler »
  • PHP Manual
  • OAuthProvider
  • Set request token path

OAuthProvider::setRequestTokenPath

(PECL OAuth >= 1.0.0)

OAuthProvider::setRequestTokenPath — Set request token path

Description

final public OAuthProvider::setRequestTokenPath ( string $path ) : bool

Sets the request tokens path.

Warning

This function is currently not documented; only its argument list is available.

Parameters

path

The path.

Return Values

TRUE

See Also

  • OAuthProvider::tokenHandler() - Set the tokenHandler handler callback


Set the timestampNonceHandler handler callback

  • « OAuthProvider::setRequestTokenPath
  • OAuthProvider::tokenHandler »
  • PHP Manual
  • OAuthProvider
  • Set the timestampNonceHandler handler callback

OAuthProvider::timestampNonceHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::timestampNonceHandler — Set the timestampNonceHandler handler callback

Description

public OAuthProvider::timestampNonceHandler ( callable $callback_function ) : void

Sets the timestamp nonce handler callback, which will later be called with OAuthProvider::callTimestampNonceHandler(). Errors related to timestamp/nonce are thrown to this callback.

Warning

This function is currently not documented; only its argument list is available.

Parameters

callback_function

The callable functions name.

Return Values

No value is returned.

Examples

Example #1 Example OAuthProvider::timestampNonceHandler() callback

<?php
function timestampNonceChecker($provider) {

    if ($provider->nonce === 'bad') {
        return OAUTH_BAD_NONCE;
    } elseif ($provider->timestamp == '0') {
        return OAUTH_BAD_TIMESTAMP;
    }

    return OAUTH_OK;
}
?>

See Also

  • OAuthProvider::callTimestampNonceHandler() - Calls the timestampNonceHandler callback


Set the tokenHandler handler callback

  • « OAuthProvider::timestampNonceHandler
  • OAuthException »
  • PHP Manual
  • OAuthProvider
  • Set the tokenHandler handler callback

OAuthProvider::tokenHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::tokenHandler — Set the tokenHandler handler callback

Description

public OAuthProvider::tokenHandler ( callable $callback_function ) : void

Sets the token handler callback, which will later be called with OAuthProvider::callTokenHandler().

Warning

This function is currently not documented; only its argument list is available.

Parameters

callback_function

The callable functions name.

Return Values

No value is returned.

Examples

Example #1 Example OAuthProvider::tokenHandler() callback

<?php
function tokenHandler($provider) {

    if ($provider->token === 'rejected') {
        return OAUTH_TOKEN_REJECTED;
    } elseif ($provider->token === 'revoked') {
        return OAUTH_TOKEN_REVOKED;
    }

    $provider->token_secret = "the_tokens_secret";
    return OAUTH_OK;
}
?>

See Also

  • OAuthProvider::callTokenHandler() - Calls the tokenNonceHandler callback


OAuthException class

(PECL OAuth >= 0.99.1)

Introduction

This exception is thrown when exceptional errors occur while using the OAuth extension and contains useful debugging information.

Class synopsis

OAuthException extends Exception {
/* Properties */
public $lastResponse ;
public $debugInfo ;
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}

Properties

lastResponse

The response of the exception which occurred, if any

debugInfo


SCA

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • The structure of a Service Component
    • Obtaining a proxy for another Service Component
    • Calling another Service Component
    • Locating and calling services from a script which is not an SCA Component
    • Exposing a Service Component as a Web service
    • Deploying an SCA component
    • Obtaining the WSDL for an SCA component offering a Service as a Web service
    • Understanding how the WSDL is generated
    • Working with Data Structures
    • Error handling
  • SCA Functions
    • SCA::createDataObject — Create an SDO
    • SCA::getService — Obtain a proxy for a service
    • SCA_LocalProxy::createDataObject — Create an SDO
    • SCA_SoapProxy::createDataObject — Create an SDO


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.

SCA for PHP makes it possible for a PHP programmer to write reusable components, which can be called in a variety of ways, with an identical interface and with a minimum of fuss. At present components can call each other either locally or via Web services, but in the future it is expected that other ways will be possible. It provides the programmer with a way of doing this which will look as natural as possible in PHP.

SCA components use phpDocumentor-style (see http://www.phpdoc.org/) annotations to declare dependencies on other SCA components or Web services. The SCA for PHP runtime resolves these dependencies at runtime on behalf of the components, and thus allows the PHP programmer to focus on the business logic rather than on locating and obtaining references to dependencies.

The SCA for PHP programming model can be extended to support a number of service types, such as REST and Atompub. However, Web services (more accurately, WSDL defined, SOAP/HTTP services), are the only type currently specified.

Components also use annotations to define the interface which they expose as a service. The SCA for PHP runtime will automatically generate WSDL from these annotations, so that an SCA component is easily exposed as a web service. These annotations are a natural extension to those provided by phpDocumentor. Deploying a Web service can be as simple as placing a PHP component under the document root of a web server.

Components also use annotations to specify data structures (expressed using XML schema complex types) which are then handled using Service Data Objects (SDOs).

A PHP script which is not an SCA component and which contains no annotations can use the services of an SCA component. A PHP script or component can make calls to a web service that is not an SCA component, but using the same system of calls or annotations to obtain a reference.

First we show a single SCA component, ConvertedStockQuote which illustrates many of the features of SCA for PHP. It has one method, getQuote(), which given a stock "ticker" obtains a price quote for that stock, converted to a given currency. We shall be using this example as a basis for explaining the SCA for PHP throughout the rest of this document.

Example #1 A sample SCA component

<?php

include "SCA/SCA.php";

/**
 * Calculate a stock price for a given ticker symbol in a given currency.
 *
 * @service
 * @binding.soap
 */
class ConvertedStockQuote {

    /**
     * The currency exchange rate service to use.
     *
     * @reference
     * @binding.php ../ExchangeRate/ExchangeRate.php
     */
    public $exchange_rate;

    /**
     * The stock quote service to use.
     *
     * @reference
     * @binding.soap ../StockQuote/StockQuote.wsdl
     */
    public $stock_quote;

    /**
     * Get a stock quote for a given ticker symbol in a given currency.
     *
     * @param string $ticker The ticker symbol.
     * @param string $currency What currency to convert the value to.
     * @return float The stock value is the target currency.
     */
    function getQuote($ticker, $currency)
    {
        $quote  = $this->stock_quote->getQuote($ticker);
        $rate   = $this->exchange_rate->getRate($currency);
        return  $rate * $quote;
    }
}
?>

In this example, we see that an SCA component is implemented by a script containing a PHP class and includes SCA.php. The class contains a mixture of business logic and references to other components or services. In the illustrated getQuote() method there is only business logic, but it relies on the instance variables $stock_quote and $exchange_rate having been initialized. These refer to two other components and will be initialized by the SCA runtime with proxies for these two services, whenever this component executes. The annotations for these two services show one to be a local component, which will be called within the same PHP runtime, and one to be a remote component which will be called via a SOAP request. This component also exposes the getQuote() method both locally and as a web service, so it in turn can be called either locally or remotely.


Requirements

If you want to use SCA to consume or produce Web services then you need PHP 5.2.0 or later, built with the soap extension enabled. If you just want to use local components, and do not wish to use the Web service bindings, then this version of SCA for PHP will also run with PHP 5.1.6.

SCA is packaged along with SDO in one combined package on PECL. See http://www.php.net/sdo#sdo.installation for installing the SCA_SDO package from PECL. The SCA code must be on the include path of your PHP installation, for example if it is installed as /usr/local/lib/php/SCA, the include_path directive must include /usr/local/lib/php


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/sca.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.


  • « Resource Types
  • Examples »
  • PHP Manual
  • SCA
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


Examples

Table of Contents

  • The structure of a Service Component
  • Obtaining a proxy for another Service Component
  • Calling another Service Component
  • Locating and calling services from a script which is not an SCA Component
  • Exposing a Service Component as a Web service
  • Deploying an SCA component
  • Obtaining the WSDL for an SCA component offering a Service as a Web service
  • Understanding how the WSDL is generated
  • Working with Data Structures
  • Error handling

The examples in the subsequent sections illustrate the following aspects of PHP for SCA:

  • How PHP annotations are used to define PHP classes as SCA components, and how annotations are used to define the services.

  • How an SCA component can be exposed as a Web service

  • How an SCA component can consume a Web service, whether provided by another SCA component or by some other service which knows nothing of SCA

  • How an SCA component can call another SCA component locally (within the same process and on the same call stack)

  • How a client script which is not an SCA component can use the getService call to obtain a proxy for an SCA component.

  • How data structures such as Addresses, or Puchase Orders, are represented as Service Data Objects, and handled.

  • How SCA components are deployed, and in particular how and when WSDL is generated for a service.

  • How parameters are always passed by value (and not by reference) between components, even when the calls are local. This ensures that the semantics of a call do not change depending on the location of a component.

  • How positional parameters to a service are supported, even when the underlying WSDL is document literal wrapped, and naturally supports only named parameters.

  • How business and runtime exceptions are handled.


The structure of a Service Component

A service component is implemented by a class. To identify it as a service component, it contains an @service annotation. The SCA runtime will use the file name of the script to determine the component name, by convention. The class and script file must therefore share the same name.

PHP SCA components always expose a service, and there is no way for a component to be invoked other than to be called as a result of a Web service request, or called directly from another component or from a script. For this reason a valid PHP SCA component will always contain an @service annotation and at least one public method.

Each SCA Component requires that the SCA.php script is included. As well as containing the definition of the SCA class, this script contains executable PHP code that will run whenever the script is called, and which will be responsible for making the component behave as needed.

Caution

It is very important that if your file contains other includes, they come before the include for SCA.php. If there are includes after the include for SCA.php, they will not have been processed when the SCA runtime runs your class.

The example below illustrates this overall structure

Example #1 The structure of an SCA for PHP component

<?php

// any includes

include "SCA/SCA.php";

/**
 * @service
 */

class ConvertedStockQuote {

       // instance variables, business logic, including at least one public method

}
?>


Obtaining a proxy for another Service Component

One SCA component can call the service provided by another SCA component. The service a component provides is made up of all of its public methods. SCA for PHP currently provides two ways for one component to call another: either locally (i.e. within the same PHP run-time, and on the same call stack) or remotely if the called component exposes a Web service binding.

In order for one component to call another, the calling component needs a proxy for the called component. This proxy is usually provided as an instance variable in the calling component, though proxies can also be obtained with the SCA::getService() call, as we shall see later. When a component is constructed, proxies are constructed for any instance variable which refer to another component, and these proxies are "injected" into the instance variables. Proxies are always used, whether the component is local or remote, in order to provide identical calling behavior between remote and local calls (for example, local calls are made to always pass data by-value). The proxies know how to locate the required component and to pass the calls made on to them.

Instance variables which are intended to hold proxies for services are indicated by the two PHPDocumentor-style annotations, @reference and @binding. Both annotations are placed in the documentation section for a class instance variable, as shown by the code below.

The @reference annotation before an instance variable indicates that the instance variable is to be initialized with a proxy to a component.

The @binding annotation has two forms @binding.php and @binding.soap, and indicates that the proxy is either for a local component or for a Web service respectively. For both @binding.php and @binding.soap, the annotation gives a target URI.

At the moment, with the annotation-based method of specifying dependencies, the only way to alter the intended target of a reference is to alter the annotation within the component.

In our ConvertedStockQuote example, the $exchange_rate instance variable will be initialized with a proxy to the local ExchangeRate component whenever an instance of the ConvertedStockQuote is constructed.

Example #1 Obtaining a proxy for a local PHP class

<?php
   /**
     * The currency exchange rate service to use.
     *
     * @reference
     * @binding.php ../ExchangeRate/ExchangeRate.php
     */
    public $exchange_rate;
?>

For @binding.php, the URI identifies the location of the script containing the implementation of the component. The component will be called locally. The service provided is the set of public methods of the component. The URI must be a simple pathname, either absolute or relative. The component will be loaded with the PHP include directive, after testing to see if it is already loaded with class_exists(). If the URI is a relative path, it is resolved relative to the component containing the annotation. Note that this is different from the normal PHP behaviour where scripts would be looked for along the PHP include_path, This is intended to provide some location-independence for cross-component references.

If this ExchangeRate service were remote and to be called as a Web service, only the @binding line changes. Instead of giving the location of a PHP class, it gives the location of the WSDL describing the web service. In our example component, this is illustrated by the second reference:

Example #2 Obtaining a proxy for a web service

<?php
/**
     * The stock quote service to use.
     *
     * @reference
     * @binding.soap ../StockQuote/StockQuote.wsdl
     */
    public $stock_quote;
?>

The StockQuote component will be called via a Web service request. In this case the URI for the WSDL can be a simple pathname, or may contain a PHP wrapper and begin, for example, with file:// or http://. In the event that it is a simple pathname, it can be absolute or relative, and if relative will be resolved relative to the component containing the annotation. Note that this is like the behaviour for @binding.php, and different from the normal PHP behaviour where the file would be looked for relative to the PHP current working directory, which would usually be the location of the first script to be called. This behaviour is intended to give consistency across the different bindings and to provide some location-independence for references between components.


Calling another Service Component

The ConvertedStockQuote example also calls the proxies for the two components to which it refers.

Example #1 Calling services

<?php
$quote  = $this->stock_quote->getQuote($ticker);
$rate   = $this->exchange_rate->getRate($currency);
?>

The call to the StockQuote service is a call to a local service; the call to the ExchangeRate service is a call to a remote service. Note that the way the call is made looks the same regardless of whether the call is to a local service or a remote one.

The proxies which have been injected ensure that the way calls to components look and behave are the same way regardless of whether they are to a local or remote service, so that components are not sensitive to whether a call is to a local or a remote service. For example, the proxy for a local service takes copies of the arguments and passes only those copies, to ensure that calls are made to be pass-by-value, as they would be for a remote call. Also, the proxy for a remote service takes the arguments from a positional parameter list and ensures they are packaged properly in a SOAP request and converted back to a positional parameter list at the far end.

In the example above, the $ticker and $currency are clearly PHP scalar types. Components can pass the PHP scalar types string, integer, float and boolean, but data structures on service calls are always passed as Service Data Objects (SDOs). A later section describes how a component can create an SDO to pass on a local or Web service call, or how a component can create an SDO to return. The PHP SDO project documentation describes how to work with the SDO APIs (see the SDO pages).


Locating and calling services from a script which is not an SCA Component

SCA components obtain proxies for other components or services as instance variables annotated with @reference, but this is not possible for a script that is not itself also a component. A client script which is not a component must use the SCA::getService() static method to obtain a proxy for a service, whether local or remote. The getService() method takes a URI as the argument. Typically this is the location of a local PHP script containing a component, or of a wsdl file, and is used in exactly the same way as the targets of the @binding annotations described in the previous section: that is, relative URIs are resolved against the location of the client script and not against the PHP include_path or current working directory.

For example, a script that needed to obtain proxies for the ExchangeRate and StockQuote services but was not a component would use the getService() method as follows:

Example #1 Obtaining a proxy using getService

<?php
$exchange_rate = SCA::getService('../ExchangeRate/ExchangeRate.php');
$stock_quote   = SCA::getService('../StockQuote/StockQuote.wsdl');
?>

Methods on services can then be called on the returned proxy, just as they can in a component.

Example #2 Making calls on the proxy

<?php
$quote  = $stock_quote->getQuote($ticker);
$rate   = $exchange_rate->getRate($currency);
?>


Exposing a Service Component as a Web service

SCA for PHP can generate WSDL from the annotations within a service component, so that it can be easily deployed and exposed as a Web service. To provide SCA with the information it needs to generate the WSDL, it is necessary to add the annotation @binding.soap under the @service annotation and to specify the parameters and return values of the methods using the @param and @return annotations. These annotations will be read when WSDL is generated, and the order and types of the parameters determine the contents of the <schema> section of the WSDL.

SCA for PHP always generates document/literal wrapped WSDL for components that are exposing a Web service. Note that this does not stop components from consuming Web services which are not SCA components and which are documented with WSDL written in a different style.

The scalar types which can be used in the @param annotation are the four common PHP scalar types: boolean, integer, float and string. These are simply mapped to the XML schema types of the same name in the WSDL. The example below, which is a trivial implementation of the StockQuote service that the ConvertedStockQuote component calls, illustrates string and float types.

Example #1 StockQuote Service

<?php

include "SCA/SCA.php";

/**
 * Scaffold implementation for a remote StockQuote Web service.
 *
 * @service
 * @binding.soap
 *
 */
class StockQuote {

    /**
     * Get a stock quote for a given ticker symbol.
     *
     * @param string $ticker The ticker symbol.
     * @return float The stock quote.
     */
    function getQuote($ticker) {
        return 80.9;
  }
}
?>

WSDL much like the following (though with a service location other than 'localhost', probably) would be generated from this service:

Example #2 Generated WSDL

<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://schemas.xmlsoap.org/wsdl/" xsi:type="tDefinitions"
    xmlns:tns2="http://StockQuote" xmlns:tns="http://schemas.xmlsoap.org/wsdl/"
    xmlns:tns3="http://schemas.xmlsoap.org/wsdl/soap/"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" targetNamespace="http://StockQuote">
  <types>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
      targetNamespace="http://StockQuote">
      <xs:element name="getQuote">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="ticker" type="xs:string"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="getQuoteResponse">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="getQuoteReturn" type="xs:float"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:schema>
  </types>

  <message name="getQuoteRequest">
    <part name="getQuoteRequest" element="tns2:getQuote"/>
  </message>
  <message name="getQuoteResponse">
    <part name="return" element="tns2:getQuoteResponse"/>
  </message>
  <portType name="StockQuotePortType">
    <operation name="getQuote">
      <input message="tns2:getQuoteRequest"/>
      <output message="tns2:getQuoteResponse"/>
    </operation>
  </portType>
  <binding name="StockQuoteBinding" type="tns2:StockQuotePortType">
    <operation name="getQuote">
      <input>
        <tns3:body xsi:type="tBody" use="literal"/>
      </input>
      <output>
        <tns3:body xsi:type="tBody" use="literal"/>
      </output>
      <tns3:operation xsi:type="tOperation" soapAction=""/>
    </operation>
    <tns3:binding xsi:type="tBinding" transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
  </binding>
  <service name="StockQuoteService">
    <port name="StockQuotePort" binding="tns2:StockQuoteBinding">
      <tns3:address xsi:type="tAddress" location="http://localhost/StockQuote/StockQuote.php"/>
    </port>
  </service>
</definitions>

<!-- this line identifies this file as WSDL generated by SCA for PHP. Do not remove -->


Deploying an SCA component

There are no special steps needed to deploy a PHP SCA component. It is sufficient to place the component PHP script in its proper place under the web server document root, just like any other PHP script. It is the SCA::initComponent() executable line within each component that will be executed whenever the script is called, and which will be responsible for making the component respond appropriately to Web service calls, local calls, or requests for WSDL.


Obtaining the WSDL for an SCA component offering a Service as a Web service

SCA components that expose a Web service interface (i.e. have an @binding.soap annotation) will return their WSDL definition in response to an HTTP request with a get parameter of "wsdl". The usual way to obtain this is with "?wsdl" on the end of a URL. The example below uses file_get_contents() to obtain WSDL from a service and writes it to a temporary file before then obtaining a proxy for the service in the usual way. You could of course also obtain the WSDL in a browser, or by some other means, and save the file yourself.

Example #1 Generated WSDL

<?php
$wsdl = file_get_contents('http://www.example.com/Services/Example.php?wsdl');
file_put_contents("service.wsdl",$wsdl); //write the wsdl to a file
$service = SCA::getService('service.wsdl');
?>

NOTE: If the wsdl requires imported xsds, these will need to be fetched separately.


Understanding how the WSDL is generated

SCA for PHP generates WSDL for components which contain an @binding.soap annotation after the @service annotation. To generate WSDL, the SCA runtime reflects on the component and examines the @param and @return annotations for each public method, as well as any @types annotations within the component. The information from the @param and @return annotations is used to build the <types> section of the WSDL. Any @types annotations which specify a separate schema file will result in an <import> element for that schema within the WSDL.

Location attribute of the <service> element

At the bottom of the WSDL is the <service> element which uses the location attribute to identify the URL of the service. For example this might look as follows:

Example #1 location attribute

<service name="ConvertedStockQuote"
...
location="http://localhost/ConvertedStockQuote/ConvertedStockQuote.php"/>

Note that this location is relative to the document root of the web server, and cannot be worked out in advance. It can only be worked out once the component is in its proper place under a running web server, when the hostname and port can be known and placed in the WSDL. Detail from the URL that requests the WSDL is used, so for example if the WSDL is generated in response to a request to http://www.example.com:1111/ConvertedStockQuote/ConvertedStockQuote.php?wsdl, a location of http://www.example.com:1111/ConvertedStockQuote/ConvertedStockQuote.php is what will be inserted into the location attribute in the WSDL.

Document/literal wrapped WSDL and positional parameters

SCA for PHP generates WSDL in the document/literal wrapped style. This style encloses the parameters and return types of a method in 'wrappers' which are named after the corresponding method. The <types> element at the top of the WSDL defines each of these wrappers. If we consider the getQuote() method of the ConvertedStockQuote example:

Example #2 method with two arguments

<?php
   /**
     * Get a stock quote for a given ticker symbol in a given currency.
     *
     * @param string $ticker The ticker symbol.
     * @param string $currency What currency to convert the value to.
     * @return float The stock value is the target currency.
     */
    function getQuote($ticker, $currency)
    {
        $quote  = $this->stock_quote->getQuote($ticker);
        $rate   = $this->exchange_rate->getRate($currency);
        return  $rate * $quote;
    }
?>

The WSDL generated to define this method will name both the method and the parameters, and give an XML schema type for the parameters. The types section of the WSDL looks like this:

Example #3 types section illustrating named parameters

<types>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
      targetNamespace="http://ConvertedStockQuote">
      <xs:element name="getQuote">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="ticker" type="xs:string"/>
            <xs:element name="currency" type="xs:string"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="getQuoteResponse">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="getQuoteReturn" type="xs:float"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:schema>
  </types>

The SCA run-time has special processing to handle how positional parameter lists in the interface are converted to XML containing named parameters in the soap request, and then back to positional parameter lists again. To see why this matters, consider how a PHP script which used a different interface to make a SOAP call would need to construct the parameter list. A PHP script using the PHP SoapClient, for example, would need to pass the SoapClient a single parameter giving the values for "ticker" and "currency", perhaps as an associative array. To insist that SCA components construct parameter lists to make Web service calls in this way would be to make local and remote calls look different, so a different approach is needed.

When SCA generates WSDL for an SCA component it includes a comment in the WSDL which marks that WSDL as being the interface for an SCA component. In this case, when one SCA component calls another through a Web service, the SCA runtime on the calling end takes the positional parameter list from the call and assigns the values one by one to the named elements in the soap message. For example a call to the getQuote() method defined above that passes the values 'IBM' and 'USD' and looks like this:

<?php
  $quote = $remote_service->getQuote('IBM','USD');
?>

will result in a soap message containing the following:

<getQuote>
  <ticker>IBM</ticker>
  <currency>USD</currency>
</getQuote>

On the service-providing end, the SCA run-time takes the parameters one by one from the soap message and forms a positional parameter list from them, re-forming the argument list ('IBM','USD').

Caution

At both ends the SCA runtime relies on the order in which the parameters appear in the soap message being the same as that in the target method's parameter list. This is ultimately determined by the order of the @param annotations: this determines the order in which the parameters appear in the WSDL and thereby the order in which they appear in the soap message. Therefore it is essential that the order of the @param annotations matches that of the parameters in the method's parameter list.


Working with Data Structures

SCA components can pass and return the four PHP scalar types boolean, integer, float and string, but to pass or return data structures, SCA components use Service Data Objects (SDOs). SDOs are described in much more detail in the SDO pages of this manual. Readers familiar with SDOs will know that they are suitable for representing the sort of structured and semi-structured data that is frequently modeled in XML, and that they serialize very naturally for passing between remote components, or in Web services. SDOs are presently the only supported way to pass and return data structures. It is not possible to pass or return PHP objects, or PHP arrays.

The SCA runtime always assures data is passed by-value, even for local calls. To do this, the SCA runtime copies any SDOs in the parameter list before passing them on, just as it does for scalar types.

How data structures are defined to SCA components

Currently the only mechanism for specifying the location of a data structure definition is by specifying the types in an XML schema file. However, in the future it may be possible to define types in other ways, such as based on PHP classes or interfaces, or based on definitions expressed as associative arrays.

To illustrate the use of SDOs we introduce a new component. The PortfolioMangement service below returns an SDO representing a stock portfolio for a given customer.

Example #1 A Component that uses Data Structures

<?php

include "SCA/SCA.php";

/**
 * Manage the portfolio for a customer.
 *
 * @service
 * @binding.soap
 *
 * @types http://www.example.org/Portfolio PortfolioTypes.xsd
 *
 */
class PortfolioManagement {

    /**
     * Get the stock portfolio for a given customer.
     *
     * @param integer $customer_id The id for the customer
     * @return Portfolio http://www.example.org/Portfolio The stock portfolio (symbols and quantities)
     */
    function getPortfolio($customer_id) {
        // Pretend we just got this from a database
        $portfolio = SCA::createDataObject('http://www.example.org/Portfolio', 'Portfolio');
        $holding = $portfolio->createDataObject('holding');
        $holding->ticker = 'AAPL';
        $holding->number = 100.5;
        $holding = $portfolio->createDataObject('holding');
        $holding->ticker = 'INTL';
        $holding->number = 100.5;
        $holding = $portfolio->createDataObject('holding');
        $holding->ticker = 'IBM';
        $holding->number = 100.5;
        return $portfolio;
    }

}
?>

The @types annotation:

<?php
@types http://www.example.org/Portfolio PortfolioTypes.xsd
?>

indicates that types in the namespace http://www.example.org/Portfolio will be found in the schema file located by the URI PortfolioTypes.xsd. The generated WSDL would reproduce this information with an import statement as follows:

<xs:import schemaLocation="PortfolioTypes.xsd"
                      namespace="http://www.example.org/Portfolio"/>

so the URI, absolute or relative, must be one that can be resolved when included in the schemaLocation attribute.

Creating SDOs

Readers familiar with SDOs will know that they are always created according to a description of the permitted structure (sometimes referred to as the 'schema' or 'model') and that, rather than creating them directly using 'new', some form of data factory is needed. Often, an existing data object can be used as the data factory, but sometimes, and especially in order to get the first data object, something else must act as the data factory.

In SCA, either the SCA runtime class or the proxies for services, whether local or remote, can act as the data factories for SDOs. The choice of which to use, and when, is described in the next two sections.

We switch to a new example in order to illustrate the creation of SDOs, both to pass to a service, and to be returned from a service.

Creating an SDO to pass to a service

A caller of a service which requires a data structure to be passed in to it uses the proxy to the service as the data factory for the corresponding SDOs. For example, suppose a component makes use of a proxy for a service provided by a local AddressBook component.

<?php
/**
 * @reference
 * @binding.local AddressBook.php
 */
$address_book;
?>

The AddressBook component that it wishes to call is defined as follows:

<?php
/**
* @service
* @binding.soap
* @types http://addressbook ../AddressBook/AddressBook.xsd
*/
class AddressBook {

    /**
     * @param personType $person http://addressbook (a person object)
     * @return addressType http://addressbook (the address object for the person object)
     */
    function lookupAddress($person)  {
        ...
    }
}
?>

The AddressBook component provides a service method called lookupAddress() which uses types from the http://addressbook namespace. The lookupAddress method takes a personType data structure and returns an addressType. Both types are defined in the schema file addressbook.xsd.

Once the component that wishes to use the AddressBook component has been constructed, so that the $address_book instance variable contains a proxy for the service, the calling component can use the proxy in $address_book to create the person SDO, as shown below:

<?php
$william_shakespeare        = $address_book->createDataObject('http://addressbook','personType');
$william_shakespeare ->name = "William Shakespeare";
$address                    = $address_book->lookupAddress($william_shakespeare);
?>

Note, the use of the proxy as the means to create the SDO is not limited to SCA components. If a service is being called from a general PHP script, and the proxy was obtained with getService() then the same approach is used.

<?php
$address_book = SCA::getService('AddressBook.php');
$william_shakespeare = $address_book->createDataObject('http://addressbook','personType');
?>

Creating an SDO to return from a component

A component that needs to create a data object for return to a caller will not have a proxy to use as a data object, In this case it uses the createDataObject() static method on SCA.php. Hence if the AddressBook component described above needed to create an object of type addressType within the namespace http://addressbook, it might do so as follows:

<?php
$address = SCA::createDataObject('http://addressbook','addressType');
?>


Error handling

This section describes how errors are handled. There are two types of errors:

  • SCA runtime exceptions are those that signal problems in the management of the execution of components, and in the interaction with remote services. These might occur due to network or configuration problems.

  • Business exceptions are those that are defined by the programmer. They extend the PHP Exception class, and are thrown and caught deliberately as part of the business logic.

Handling of Runtime exceptions

There are two types of SCA runtime exception:

  • SCA_RuntimeException - signals a problem found by or perhaps occurring within the SCA runtime. This can be thrown for a variety of reasons, many of which can occur regardless of whether a connection is being made to a local or a remote service: an error in one of the annotations within a component, a missing WSDL or php file, and so on. In the case of Web services, an SCA_RuntimeException can also be thrown if a SoapFault is received from a remote Web service and the fault code in the SoapFault indicates that a retry is unlikely to be successful.

  • SCA_ServiceUnavailableException - this is a subclass of SCA_RuntimeException and signals a problem in connecting to or using a remote service, but one which might succeed if retried. In the case of Web services, this exception is thrown if a SoapFault is received with a fault code that indicates that a retry might be successful.

Handling of Business exceptions

Business exceptions may be defined and thrown by a component in the normal way, regardless of whether the component has been called locally or remotely. The SCA runtime does not catch business exceptions that have been thrown by a component called locally, so they will be returned to a caller in the normal way. If a component has been called via a Web service, on the other hand, the SCA runtime on the service providing end does catch business exceptions, and will ensure these are passed back to the calling end and re-thrown. Assuming that the calling end has a definition of the exception (that is, is able to include a file containing the PHP class defining the exception) the re-thrown exception will contain the same details as the original, so that the getLine() and getFile() methods for example will contain the location where the exception was thrown within the business logic. The exception will be passed in the detail field of a soap fault with a fault code of "Client".


SCA Functions

Predefined Classes

Most of the interface to SCA is through the annotations within SCA components so there are few public classes and methods. The only SCA classes that scripts or components can call are the SCA class itself, and the proxy classes SCA_LocalProxy and SCA_SoapProxy.

SCA

Much of the work of the SCA class is performed when the file SCA.php is included within an SCA component. However, a PHP script may include SCA.php and call the getService() method on the SCA class in order to obtain a proxy for a service. A component will not need to do this as proxies are obtained instead by defining an instance variable with the @reference annotation.

Components that need to create an SDO to return to a caller will need a data factory to call. For this purpose the SCA class supports the createDataObject() method, which will create an SDO according to the model defined by the component's @types annotations. The arguments to createDataObject() are the same as those to SDO's XML Data Access Service.

Methods

  • getService - obtain a proxy for a service

  • createDataObject - create an SDO

SCA_LocalProxy

When getService() is called with the target of a local PHP component, a local proxy is returned. A local proxy is also injected into the instance variables of a component that are defined with an @reference and an @binding.php anotation. When the script or component makes calls on the local proxy, they are passed on to the target component itself.

Components that need to create an SDO to pass to a component will need a data factory to call. For this purpose the SCA_LocalProxy class supports the createDataObject() method, which will create an SDO according to the model defined by the components' @types annotations. The arguments to the createDataObject() are the same as those to SDO's XML Data Access Service.

Methods

  • createDataObject - create an SDO

SCA_SoapProxy

When getService() is called with the target of a WSDL file, a SOAP proxy is returned. A SOAP proxy is also injected into the instance variables of a component that are defined with an @reference and an @binding.soap anotations. When the script or component makes calls on the SOAP proxy, they are formed into Web service SOAP requests and passed on to the target component, with the help of the PHP Soap extension.

Components that need to create an SDO to pass to a component will need a data factory to call. For this purpose the SCA_SoapProxy class supports the createDataObject() method, which will create an SDO according to the model defined within the target WSDL. The arguments to the createDataObject() are the same as those to SDO's XML Data Access Service.

Methods

  • createDataObject - create an SDO

Table of Contents

  • SCA::createDataObject — Create an SDO
  • SCA::getService — Obtain a proxy for a service
  • SCA_LocalProxy::createDataObject — Create an SDO
  • SCA_SoapProxy::createDataObject — Create an SDO


Create an SDO

  • « SCA Functions
  • SCA::getService »
  • PHP Manual
  • SCA Functions
  • Create an SDO

SCA::createDataObject

(PECL SDO >= 0.5.0)

SCA::createDataObject — Create an SDO

Description

SCA::createDataObject ( string $type_namespace_uri , string $type_name ) : SDO_DataObject
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.

This method is used inside an SCA component that needs to create an SDO to return. The parameters are the desired SDO's namespace URI and type name. The namespace and type must be defined in one of the schema files which are specified on the @types annotation within the component.

Parameters

type_namespace_uri

The namespace of the type.

type_name

The name of the type.

Return Values

Returns the newly created SDO_DataObject.

Errors/Exceptions

SDO_TypeNotFoundException

Thrown if the namespaceURI and typeName do not correspond to a type in any of the schema files specified in the @types annotations.


Obtain a proxy for a service

  • « SCA::createDataObject
  • SCA_LocalProxy::createDataObject »
  • PHP Manual
  • SCA Functions
  • Obtain a proxy for a service

SCA::getService

(PECL SDO >= 0.5.0)

SCA::getService — Obtain a proxy for a service

Description

SCA::getService ( string $target [, string $binding [, array $config ]] ) : mixed
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.

Examine the target and initialize and return a proxy of the appropriate sort. If the target is for a local PHP component the returned proxy will be an SCA_LocalProxy. If the target is for a WSDL file, the returned proxy will be a SCA_SoapProxy.

Parameters

target

An absolute or relative path to the target service or service description (e.g. a URL to a json-rpc service description, a PHP component, a WSDL file, and so on.). A relative path, if specified, is resolved relative to the location of the script issuing the getService() call, and not against the include_path or current working directory.

binding

The binding (i.e. protocol) to use to communicate with the service (e.g binding.jsonrpc for a json-rpc service). Note, some service types can be deduced from the target parameter (e.g. if the target parameter ends in .wsdl then SCA will assume binding.soap). Any binding which can be specified in an annotation can be specified here. For example 'binding.soap' is equivalent to the '@binding.soap' annotation.

config

Any additional configuration properties for the binding (e.g. array('location' => 'http://example.org')). Any binding configuration which can be specified in an annotation can be specified here. For example, 'location' is equivalent to the '@location' annotation to configure the location of a target soap service.

Return Values

The SCA_LocalProxy or SCA_SoapProxy.

Examples

Example #1 An SCA::getService() example

This example shows how to get a proxy to an email soap service described by EmailService.wsdl and located at http://example.org.

<?php
include 'SCA/SCA.php';
$service = SCA::getService('EmailService.wsdl', 'binding.soap', array('location' => 'http://example.org'));
$service->send(...);
?>

The above example will output:


Create an SDO

  • « SCA::getService
  • SCA_SoapProxy::createDataObject »
  • PHP Manual
  • SCA Functions
  • Create an SDO

SCA_LocalProxy::createDataObject

(PECL SDO >= 0.5.0)

SCA_LocalProxy::createDataObject — Create an SDO

Description

SCA_LocalProxy::createDataObject ( string $type_namespace_uri , string $type_name ) : SDO_DataObject
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.

This method is used inside either an ordinary PHP script or an SCA component that needs to create an SDO to pass to a local service. The parameters are the desired SDO's namespace URI and type name. The namespace and type must be defined in the interface of the component that is to be called, so the namespace and type must be defined in one of the schema files which are specified on the @types annotation within the component for which the SCA_LocalProxy object is a proxy.

Parameters

type_namespace_uri

The namespace of the type.

type_name

The name of the type.

Return Values

Returns the newly created SDO_DataObject.

Errors/Exceptions

SDO_TypeNotFoundException

Thrown if the namespaceURI and typeName do not correspond to a type in any of the schema files specified in the @types annotations within the component for which the SCA_LocalProxy object is a proxy..


Create an SDO

  • « SCA_LocalProxy::createDataObject
  • SOAP »
  • PHP Manual
  • SCA Functions
  • Create an SDO

SCA_SoapProxy::createDataObject

(PECL SDO >= 0.5.0)

SCA_SoapProxy::createDataObject — Create an SDO

Description

SCA_SoapProxy::createDataObject ( string $type_namespace_uri , string $type_name ) : SDO_DataObject
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.

This method is used inside either an ordinary PHP script or an SCA component that needs to create an SDO to pass to a web service. The parameters are the desired SDO's namespace URI and type name. The namespace and type must be defined in the interface of the component that is to be called, so the namespace and type must be defined within the WSDL for the web service. If the web service is also an SCA component then the types will have been defined within one of the schema files which are specified on the @types annotation within the component for which the SCA_SoapProxy object is a proxy.

Parameters

type_namespace_uri

The namespace of the type.

type_name

The name of the type.

Return Values

Returns the newly created SDO_DataObject.

Errors/Exceptions

SDO_TypeNotFoundException

Thrown if the namespaceURI and typeName do not correspond to a type found in the WSDL that was used to initialise this SCA_SoapProxy.


SOAP

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • SOAP Functions
    • is_soap_fault — Checks if a SOAP call has failed
    • use_soap_error_handler — Set whether to use the SOAP error handler
  • SoapClient — The SoapClient class
    • SoapClient::__call — Calls a SOAP function (deprecated)
    • SoapClient::__construct — SoapClient constructor
    • SoapClient::__doRequest — Performs a SOAP request
    • SoapClient::__getCookies — Get list of cookies
    • SoapClient::__getFunctions — Returns list of available SOAP functions
    • SoapClient::__getLastRequest — Returns last SOAP request
    • SoapClient::__getLastRequestHeaders — Returns the SOAP headers from the last request
    • SoapClient::__getLastResponse — Returns last SOAP response
    • SoapClient::__getLastResponseHeaders — Returns the SOAP headers from the last response
    • SoapClient::__getTypes — Returns a list of SOAP types
    • SoapClient::__setCookie — The __setCookie purpose
    • SoapClient::__setLocation — Sets the location of the Web service to use
    • SoapClient::__setSoapHeaders — Sets SOAP headers for subsequent calls
    • SoapClient::__soapCall — Calls a SOAP function
    • SoapClient::SoapClient — SoapClient constructor
  • SoapServer — The SoapServer class
    • SoapServer::addFunction — Adds one or more functions to handle SOAP requests
    • SoapServer::addSoapHeader — Add a SOAP header to the response
    • SoapServer::__construct — SoapServer constructor
    • SoapServer::fault — Issue SoapServer fault indicating an error
    • SoapServer::getFunctions — Returns list of defined functions
    • SoapServer::handle — Handles a SOAP request
    • SoapServer::setClass — Sets the class which handles SOAP requests
    • SoapServer::setObject — Sets the object which will be used to handle SOAP requests
    • SoapServer::setPersistence — Sets SoapServer persistence mode
    • SoapServer::SoapServer — SoapServer constructor
  • SoapFault — The SoapFault class
    • SoapFault::__construct — SoapFault constructor
    • SoapFault::SoapFault — SoapFault constructor
    • SoapFault::__toString — Obtain a string representation of a SoapFault
  • SoapHeader — The SoapHeader class
    • SoapHeader::__construct — SoapHeader constructor
    • SoapHeader::SoapHeader — SoapHeader constructor
  • SoapParam — The SoapParam class
    • SoapParam::__construct — SoapParam constructor
    • SoapParam::SoapParam — SoapParam constructor
  • SoapVar — The SoapVar class
    • SoapVar::__construct — SoapVar constructor
    • SoapVar::SoapVar — SoapVar constructor


Introduction

The SOAP extension can be used to write SOAP Servers and Clients. It supports subsets of » SOAP 1.1, » SOAP 1.2 and » WSDL 1.1 specifications.


Requirements

This extension requires the libxml PHP extension. This means that passing in --enable-libxml is also required, although this is implicitly accomplished because libxml is enabled by default.


  • « Requirements
  • Runtime Configuration »
  • PHP Manual
  • Installing/Configuring
  • Installation

Installation

To enable SOAP support, configure PHP with --enable-soap .


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

SOAP Configure Options
Name | Default | Changeable | Changelog
soap.wsdl_cache_enabled | 1 | PHP_INI_ALL |
soap.wsdl_cache_dir | /tmp | PHP_INI_ALL |
soap.wsdl_cache_ttl | 86400 | PHP_INI_ALL |
soap.wsdl_cache | 1 | PHP_INI_ALL |
soap.wsdl_cache_limit | 5 | PHP_INI_ALL |

Here's a short explanation of the configuration directives.

soap.wsdl_cache_enabled integer

Enables or disables the WSDL caching feature.

soap.wsdl_cache_dir string

Sets the directory name where the SOAP extension will put cache files.

soap.wsdl_cache_ttl integer

Sets the number of seconds (time to live) that cached files will be used instead of the originals.

soap.wsdl_cache integer

If soap.wsdl_cache_enabled is on, this setting determines the type of caching. It can be any of: WSDL_CACHE_NONE (0), WSDL_CACHE_DISK (1), WSDL_CACHE_MEMORY (2) or WSDL_CACHE_BOTH (3). This can also be set via the options array in the SoapClient or SoapServer constructor.

soap.wsdl_cache_limit integer

Maximum number of in-memory cached WSDL files. Adding further files into a full memory cache will delete the oldest files from it.


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.

SOAP constants
Constant | Value | Description
SOAP_1_1 (integer) | 1 |
SOAP_1_2 (integer) | 2 |
SOAP_PERSISTENCE_SESSION (integer) | 1 |
SOAP_PERSISTENCE_REQUEST (integer) | 2 |
SOAP_FUNCTIONS_ALL (integer) | 999 |
SOAP_ENCODED (integer) | 1 |
SOAP_LITERAL (integer) | 2 |
SOAP_RPC (integer) | 1 |
SOAP_DOCUMENT (integer) | 2 |
SOAP_ACTOR_NEXT (integer) | 1 |
SOAP_ACTOR_NONE (integer) | 2 |
SOAP_ACTOR_UNLIMATERECEIVER (integer) | 3 |
SOAP_COMPRESSION_ACCEPT (integer) | 32 |
SOAP_COMPRESSION_GZIP (integer) | 0 |
SOAP_COMPRESSION_DEFLATE (integer) | 16 |
SOAP_AUTHENTICATION_BASIC (integer) | 0 |
SOAP_AUTHENTICATION_DIGEST (integer) | 1 |
SOAP_SSL_METHOD_TLS (integer) | 0 | Since PHP 5.5.0.
SOAP_SSL_METHOD_SSLv2 (integer) | 1 | Since PHP 5.5.0.
SOAP_SSL_METHOD_SSLv3 (integer) | 2 | Since PHP 5.5.0.
SOAP_SSL_METHOD_SSLv23 (integer) | 3 | Since PHP 5.5.0.
UNKNOWN_TYPE (integer) | 999998 |
XSD_STRING (integer) | 101 |
XSD_BOOLEAN (integer) | 102 |
XSD_DECIMAL (integer) | 103 |
XSD_FLOAT (integer) | 104 |
XSD_DOUBLE (integer) | 105 |
XSD_DURATION (integer) | 106 |
XSD_DATETIME (integer) | 107 |
XSD_TIME (integer) | 108 |
XSD_DATE (integer) | 109 |
XSD_GYEARMONTH (integer) | 110 |
XSD_GYEAR (integer) | 111 |
XSD_GMONTHDAY (integer) | 112 |
XSD_GDAY (integer) | 113 |
XSD_GMONTH (integer) | 114 |
XSD_HEXBINARY (integer) | 115 |
XSD_BASE64BINARY (integer) | 116 |
XSD_ANYURI (integer) | 117 |
XSD_QNAME (integer) | 118 |
XSD_NOTATION (integer) | 119 |
XSD_NORMALIZEDSTRING (integer) | 120 |
XSD_TOKEN (integer) | 121 |
XSD_LANGUAGE (integer) | 122 |
XSD_NMTOKEN (integer) | 123 |
XSD_NAME (integer) | 124 |
XSD_NCNAME (integer) | 125 |
XSD_ID (integer) | 126 |
XSD_IDREF (integer) | 127 |
XSD_IDREFS (integer) | 128 |
XSD_ENTITY (integer) | 129 |
XSD_ENTITIES (integer) | 130 |
XSD_INTEGER (integer) | 131 |
XSD_NONPOSITIVEINTEGER (integer) | 132 |
XSD_NEGATIVEINTEGER (integer) | 133 |
XSD_LONG (integer) | 134 |
XSD_INT (integer) | 135 |
XSD_SHORT (integer) | 136 |
XSD_BYTE (integer) | 137 |
XSD_NONNEGATIVEINTEGER (integer) | 138 |
XSD_UNSIGNEDLONG (integer) | 139 |
XSD_UNSIGNEDINT (integer) | 140 |
XSD_UNSIGNEDSHORT (integer) | 141 |
XSD_UNSIGNEDBYTE (integer) | 142 |
XSD_POSITIVEINTEGER (integer) | 143 |
XSD_NMTOKENS (integer) | 144 |
XSD_ANYTYPE (integer) | 145 |
XSD_ANYXML (integer) | 147 |
APACHE_MAP (integer) | 200 |
SOAP_ENC_OBJECT (integer) | 301 |
SOAP_ENC_ARRAY (integer) | 300 |
XSD_1999_TIMEINSTANT (integer) | 401 |
XSD_NAMESPACE (integer) | http://www.w3.org/2001/XMLSchema |
XSD_1999_NAMESPACE (integer) | http://www.w3.org/1999/XMLSchema |
SOAP_SINGLE_ELEMENT_ARRAYS (integer) | 1 |
SOAP_WAIT_ONE_WAY_CALLS (integer) | 2 |
SOAP_USE_XSI_ARRAY_TYPE (integer) | 4 |
WSDL_CACHE_NONE (integer) | 0 |
WSDL_CACHE_DISK (integer) | 1 |
WSDL_CACHE_MEMORY (integer) | 2 |
WSDL_CACHE_BOTH (integer) | 3 |


SOAP Functions

Table of Contents

  • is_soap_fault — Checks if a SOAP call has failed
  • use_soap_error_handler — Set whether to use the SOAP error handler


Checks if a SOAP call has failed

  • « SOAP Functions
  • use_soap_error_handler »
  • PHP Manual
  • SOAP Functions
  • Checks if a SOAP call has failed

is_soap_fault

(PHP 5, PHP 7)

is_soap_fault — Checks if a SOAP call has failed

Description

is_soap_fault ( mixed $object ) : bool

This function is useful to check if the SOAP call failed, but without using exceptions. To use it, create a SoapClient object with the exceptions option set to zero or FALSE. In this case, the SOAP method will return a special SoapFault object which encapsulates the fault details (faultcode, faultstring, faultactor and faultdetails).

If exceptions is not set then SOAP call will throw an exception on error. is_soap_fault() checks if the given parameter is a SoapFault object.

Parameters

object

The object to test.

Return Values

This will return TRUE on error, and FALSE otherwise.

Examples

Example #1 is_soap_fault() example

<?php
$client = new SoapClient("some.wsdl", array('exceptions' => 0));
$result = $client->SomeFunction();
if (is_soap_fault($result)) {
    trigger_error("SOAP Fault: (faultcode: {$result->faultcode}, faultstring: {$result->faultstring})", E_USER_ERROR);
}
?>

Example #2 SOAP's standard method for error reporting is exceptions

<?php
try {
    $client = new SoapClient("some.wsdl");
    $result = $client->SomeFunction(/* ... */);
} catch (SoapFault $fault) {
    trigger_error("SOAP Fault: (faultcode: {$fault->faultcode}, faultstring: {$fault->faultstring})", E_USER_ERROR);
}
?>

See Also

  • SoapClient::SoapClient() - SoapClient constructor
  • SoapFault::SoapFault() - SoapFault constructor


Set whether to use the SOAP error handler

  • « is_soap_fault
  • SoapClient »
  • PHP Manual
  • SOAP Functions
  • Set whether to use the SOAP error handler

use_soap_error_handler

(PHP 5, PHP 7)

use_soap_error_handler — Set whether to use the SOAP error handler

Description

use_soap_error_handler ([ bool $handler = TRUE ] ) : bool

This function sets whether or not to use the SOAP error handler in the SOAP server. It will return the previous value. If set to TRUE, details of errors in a SoapServer application will be sent to the client as a SOAP fault message. If FALSE, the standard PHP error handler is used. The default is to send error to the client as SOAP fault message.

Parameters

handler

Set to TRUE to send error details to clients.

Return Values

Returns the original value.

See Also

  • set_error_handler() - Sets a user-defined error handler function
  • set_exception_handler() - Sets a user-defined exception handler function


The SoapClient class

(PHP 5, PHP 7)

Introduction

The SoapClient class provides a client for » SOAP 1.1, » SOAP 1.2 servers. It can be used in WSDL or non-WSDL mode.

Class synopsis

SoapClient {
/* Methods */
public __call ( string $function_name , array $arguments ) : mixed
public __construct ( mixed $wsdl [, array $options ] )
public __doRequest ( string $request , string $location , string $action , int $version [, int $one_way = 0 ] ) : string
public __getCookies ( void ) : array
public __getFunctions ( void ) : array
public __getLastRequest ( void ) : string
public __getLastRequestHeaders ( void ) : string
public __getLastResponse ( void ) : string
public __getLastResponseHeaders ( void ) : string
public __getTypes ( void ) : array
public __setCookie ( string $name [, string $value ] ) : void
public __setLocation ([ string $new_location ] ) : string
public __setSoapHeaders ([ mixed $soapheaders ] ) : bool
public __soapCall ( string $function_name , array $arguments [, array $options [, mixed $input_headers [, array &$output_headers ]]] ) : mixed
public SoapClient ( mixed $wsdl [, array $options ] )
}

Table of Contents

  • SoapClient::__call — Calls a SOAP function (deprecated)
  • SoapClient::__construct — SoapClient constructor
  • SoapClient::__doRequest — Performs a SOAP request
  • SoapClient::__getCookies — Get list of cookies
  • SoapClient::__getFunctions — Returns list of available SOAP functions
  • SoapClient::__getLastRequest — Returns last SOAP request
  • SoapClient::__getLastRequestHeaders — Returns the SOAP headers from the last request
  • SoapClient::__getLastResponse — Returns last SOAP response
  • SoapClient::__getLastResponseHeaders — Returns the SOAP headers from the last response
  • SoapClient::__getTypes — Returns a list of SOAP types
  • SoapClient::__setCookie — The __setCookie purpose
  • SoapClient::__setLocation — Sets the location of the Web service to use
  • SoapClient::__setSoapHeaders — Sets SOAP headers for subsequent calls
  • SoapClient::__soapCall — Calls a SOAP function
  • SoapClient::SoapClient — SoapClient constructor


Calls a SOAP function (deprecated)

  • « SoapClient
  • SoapClient::__construct »
  • PHP Manual
  • SoapClient
  • Calls a SOAP function (deprecated)

SoapClient::__call

(PHP 5, PHP 7)

SoapClient::__call — Calls a SOAP function (deprecated)

Description

public SoapClient::__call ( string $function_name , array $arguments ) : mixed

Calling this method directly is deprecated. Usually, SOAP functions can be called as methods of the SoapClient object; in situations where this is not possible or additional options are needed, use SoapClient::__soapCall().


SoapClient constructor

  • « SoapClient::__call
  • SoapClient::__doRequest »
  • PHP Manual
  • SoapClient
  • SoapClient constructor

SoapClient::__construct

(PHP 5, PHP 7)

SoapClient::__construct — SoapClient constructor

Description

public SoapClient::__construct ( mixed $wsdl [, array $options ] )

This function is an alias of: SoapClient::SoapClient()


Performs a SOAP request

  • « SoapClient::__construct
  • SoapClient::__getCookies »
  • PHP Manual
  • SoapClient
  • Performs a SOAP request

SoapClient::__doRequest

(PHP 5, PHP 7)

SoapClient::__doRequest — Performs a SOAP request

Description

public SoapClient::__doRequest ( string $request , string $location , string $action , int $version [, int $one_way = 0 ] ) : string

Performs SOAP request over HTTP.

This method can be overridden in subclasses to implement different transport layers, perform additional XML processing or other purpose.

Parameters

request

The XML SOAP request.

location

The URL to request.

action

The SOAP action.

version

The SOAP version.

one_way

If one_way is set to 1, this method returns nothing. Use this where a response is not expected.

Return Values

The XML SOAP response.

Changelog

Version | Description
5.1.3 | The one_way parameter was added.

Examples

Example #1 SoapClient::__doRequest() example

<?php
function Add($x,$y) {
  return $x+$y;
}

class LocalSoapClient extends SoapClient {

  function __construct($wsdl, $options) {
    parent::__construct($wsdl, $options);
    $this->server = new SoapServer($wsdl, $options);
    $this->server->addFunction('Add');
  }

  function __doRequest($request, $location, $action, $version, $one_way = 0) {
    ob_start();
    $this->server->handle($request);
    $response = ob_get_contents();
    ob_end_clean();
    return $response;
  }

}

$x = new LocalSoapClient(NULL,array('location'=>'test://',
                                   'uri'=>'http://testuri.org'));
var_dump($x->Add(3,4));
?>


Get list of cookies

  • « SoapClient::__doRequest
  • SoapClient::__getFunctions »
  • PHP Manual
  • SoapClient
  • Get list of cookies

SoapClient::__getCookies

(PHP 5 >= 5.4.30, PHP 7)

SoapClient::__getCookies — Get list of cookies

Description

public SoapClient::__getCookies ( void ) : array

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Returns list of available SOAP functions

  • « SoapClient::__getCookies
  • SoapClient::__getLastRequest »
  • PHP Manual
  • SoapClient
  • Returns list of available SOAP functions

SoapClient::__getFunctions

(PHP 5, PHP 7)

SoapClient::__getFunctions — Returns list of available SOAP functions

Description

public SoapClient::__getFunctions ( void ) : array

Returns an array of functions described in the WSDL for the Web service.

Note:

This function only works in WSDL mode.

Parameters

This function has no parameters.

Return Values

The array of SOAP function prototypes, detailing the return type, the function name and type-hinted parameters.

Examples

Example #1 SoapClient::__getFunctions() example

<?php
$client = new SoapClient('http://soap.amazon.com/schemas3/AmazonWebServices.wsdl');
var_dump($client->__getFunctions());
?>

The above example will output:

array(26) {
  [0]=>
  string(70) "ProductInfo KeywordSearchRequest(KeywordRequest $KeywordSearchRequest)"
  [1]=>
  string(79) "ProductInfo TextStreamSearchRequest(TextStreamRequest $TextStreamSearchRequest)"
  [2]=>
  string(64) "ProductInfo PowerSearchRequest(PowerRequest $PowerSearchRequest)"
...
  [23]=>
  string(107) "ShoppingCart RemoveShoppingCartItemsRequest(RemoveShoppingCartItemsRequest $RemoveShoppingCartItemsRequest)"
  [24]=>
  string(107) "ShoppingCart ModifyShoppingCartItemsRequest(ModifyShoppingCartItemsRequest $ModifyShoppingCartItemsRequest)"
  [25]=>
  string(118) "GetTransactionDetailsResponse GetTransactionDetailsRequest(GetTransactionDetailsRequest $GetTransactionDetailsRequest)"
}

See Also

  • SoapClient::SoapClient() - SoapClient constructor


Returns last SOAP request

  • « SoapClient::__getFunctions
  • SoapClient::__getLastRequestHeaders »
  • PHP Manual
  • SoapClient
  • Returns last SOAP request

SoapClient::__getLastRequest

(PHP 5, PHP 7)

SoapClient::__getLastRequest — Returns last SOAP request

Description

public SoapClient::__getLastRequest ( void ) : string

Returns the XML sent in the last SOAP request.

Note:

This method works only if the SoapClient object was created with the trace option set to TRUE.

Parameters

This function has no parameters.

Return Values

The last SOAP request, as an XML string.

Examples

Example #1 SoapClient::__getLastRequest() example

<?php
$client = new SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "REQUEST:\n" . $client->__getLastRequest() . "\n";
?>

See Also

  • SoapClient::__getLastRequestHeaders() - Returns the SOAP headers from the last request
  • SoapClient::__getLastResponse() - Returns last SOAP response
  • SoapClient::__getLastResponseHeaders() - Returns the SOAP headers from the last response


Returns the SOAP headers from the last request

  • « SoapClient::__getLastRequest
  • SoapClient::__getLastResponse »
  • PHP Manual
  • SoapClient
  • Returns the SOAP headers from the last request

SoapClient::__getLastRequestHeaders

(PHP 5, PHP 7)

SoapClient::__getLastRequestHeaders — Returns the SOAP headers from the last request

Description

public SoapClient::__getLastRequestHeaders ( void ) : string

Returns the SOAP headers from the last request.

Note:

This function only works if the SoapClient object was created with the trace option set to TRUE.

Parameters

This function has no parameters.

Return Values

The last SOAP request headers.

Examples

Example #1 SoapClient::__getLastRequestHeaders() example

<?php
$client = SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "REQUEST HEADERS:\n" . $client->__getLastRequestHeaders() . "\n";
?>

See Also

  • SoapClient::__getLastResponseHeaders() - Returns the SOAP headers from the last response
  • SoapClient::__getLastRequest() - Returns last SOAP request
  • SoapClient::__getLastResponse() - Returns last SOAP response


Returns last SOAP response

  • « SoapClient::__getLastRequestHeaders
  • SoapClient::__getLastResponseHeaders »
  • PHP Manual
  • SoapClient
  • Returns last SOAP response

SoapClient::__getLastResponse

(PHP 5, PHP 7)

SoapClient::__getLastResponse — Returns last SOAP response

Description

public SoapClient::__getLastResponse ( void ) : string

Returns the XML received in the last SOAP response.

Note:

This method works only if the SoapClient object was created with the trace option set to TRUE.

Parameters

This function has no parameters.

Return Values

The last SOAP response, as an XML string.

Examples

Example #1 SoapClient::__getLastResponse() example

<?php
$client = SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "Response:\n" . $client->__getLastResponse() . "\n";
?>

See Also

  • SoapClient::__getLastResponseHeaders() - Returns the SOAP headers from the last response
  • SoapClient::__getLastRequest() - Returns last SOAP request
  • SoapClient::__getLastRequestHeaders() - Returns the SOAP headers from the last request


Returns the SOAP headers from the last response

  • « SoapClient::__getLastResponse
  • SoapClient::__getTypes »
  • PHP Manual
  • SoapClient
  • Returns the SOAP headers from the last response

SoapClient::__getLastResponseHeaders

(PHP 5, PHP 7)

SoapClient::__getLastResponseHeaders — Returns the SOAP headers from the last response

Description

public SoapClient::__getLastResponseHeaders ( void ) : string

Returns the SOAP headers from the last response.

Note:

This function only works if the SoapClient object was created with the trace option set to TRUE.

Parameters

This function has no parameters.

Return Values

The last SOAP response headers.

Examples

Example #1 SoapClient::__getLastResponse() example

<?php
$client = SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "RESPONSE HEADERS:\n" . $client->__getLastResponseHeaders() . "\n";
?>

See Also

  • SoapClient::__getLastRequestHeaders() - Returns the SOAP headers from the last request
  • SoapClient::__getLastRequest() - Returns last SOAP request
  • SoapClient::__getLastResponse() - Returns last SOAP response


Returns a list of SOAP types

  • « SoapClient::__getLastResponseHeaders
  • SoapClient::__setCookie »
  • PHP Manual
  • SoapClient
  • Returns a list of SOAP types

SoapClient::__getTypes

(PHP 5, PHP 7)

SoapClient::__getTypes — Returns a list of SOAP types

Description

public SoapClient::__getTypes ( void ) : array

Returns an array of types described in the WSDL for the Web service.

Note:

This function only works in WSDL mode.

Parameters

This function has no parameters.

Return Values

The array of SOAP types, detailing all structures and types.

Examples

Example #1 SoapClient::__getTypes() example

<?php
$client = new SoapClient('http://soap.amazon.com/schemas3/AmazonWebServices.wsdl');
var_dump($client->__getTypes());
?>

The above example will output:

array(88) {
  [0]=>
  string(30) "ProductLine ProductLineArray[]"
  [1]=>
  string(85) "struct ProductLine {
 string Mode;
 string RelevanceRank;
 ProductInfo ProductInfo;
}"
  [2]=>
  string(105) "struct ProductInfo {
 string TotalResults;
 string TotalPages;
 string ListName;
 DetailsArray Details;
}"
...
  [85]=>
  string(32) "ShortSummary ShortSummaryArray[]"
  [86]=>
  string(121) "struct GetTransactionDetailsRequest {
 string tag;
 string devtag;
 string key;
 OrderIdArray OrderIds;
 string locale;
}"
  [87]=>
  string(75) "struct GetTransactionDetailsResponse {
 ShortSummaryArray ShortSummaries;
}"
}

See Also

  • SoapClient::SoapClient() - SoapClient constructor


The __setCookie purpose

  • « SoapClient::__getTypes
  • SoapClient::__setLocation »
  • PHP Manual
  • SoapClient
  • The __setCookie purpose

SoapClient::__setCookie

(PHP 5 >= 5.0.4, PHP 7)

SoapClient::__setCookie — The __setCookie purpose

Description

public SoapClient::__setCookie ( string $name [, string $value ] ) : void

Defines a cookie to be sent along with the SOAP requests.

Note:

Calling this method will affect all following calls to SoapClient methods.

Parameters

name

The name of the cookie.

value

The value of the cookie. If not specified, the cookie will be deleted.

Return Values

No value is returned.


Sets the location of the Web service to use

  • « SoapClient::__setCookie
  • SoapClient::__setSoapHeaders »
  • PHP Manual
  • SoapClient
  • Sets the location of the Web service to use

SoapClient::__setLocation

(PHP 5 >= 5.0.4, PHP 7)

SoapClient::__setLocation — Sets the location of the Web service to use

Description

public SoapClient::__setLocation ([ string $new_location ] ) : string

Sets the endpoint URL that will be touched by following SOAP requests. This is equivalent to specifying the location option when constructing the SoapClient.

Note:

Calling this method is optional. The SoapClient uses the endpoint from the WSDL file by default.

Parameters

new_location

The new endpoint URL.

Return Values

The old endpoint URL.

Examples

Example #1 SoapClient::__setLocation() example

<?php
$client = new SoapClient('http://example.com/webservice.php?wsdl');

$client->__setLocation('http://www.somethirdparty.com');

$old_location = $client->__setLocation(); // unsets the location option

echo $old_location;

?>

The above example will output something similar to:

http://www.somethirdparty.com

See Also

  • SoapClient::SoapClient() - SoapClient constructor


Sets SOAP headers for subsequent calls

  • « SoapClient::__setLocation
  • SoapClient::__soapCall »
  • PHP Manual
  • SoapClient
  • Sets SOAP headers for subsequent calls

SoapClient::__setSoapHeaders

(PHP 5 >= 5.0.5, PHP 7)

SoapClient::__setSoapHeaders — Sets SOAP headers for subsequent calls

Description

public SoapClient::__setSoapHeaders ([ mixed $soapheaders ] ) : bool

Defines headers to be sent along with the SOAP requests.

Note:

Calling this method will replace any previous values.

Parameters

soapheaders

The headers to be set. It could be SoapHeader object or array of SoapHeader objects. If not specified or set to NULL, the headers will be deleted.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 SoapClient::__setSoapHeaders() example

<?php

$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/"));
$header = new SoapHeader('http://soapinterop.org/echoheader/',
                            'echoMeStringRequest',
                            'hello world');

$client->__setSoapHeaders($header);

$client->__soapCall("echoVoid", null);
?>

Example #2 Set Multiple Headers

<?php

$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/"));
$headers = array();

$headers[] = new SoapHeader('http://soapinterop.org/echoheader/',
                            'echoMeStringRequest',
                            'hello world');

$headers[] = new SoapHeader('http://soapinterop.org/echoheader/',
                            'echoMeStringRequest',
                            'hello world again');

$client->__setSoapHeaders($headers);

$client->__soapCall("echoVoid", null);
?>


Calls a SOAP function

  • « SoapClient::__setSoapHeaders
  • SoapClient::SoapClient »
  • PHP Manual
  • SoapClient
  • Calls a SOAP function

SoapClient::__soapCall

(PHP 5, PHP 7)

SoapClient::__soapCall — Calls a SOAP function

Description

public SoapClient::__soapCall ( string $function_name , array $arguments [, array $options [, mixed $input_headers [, array &$output_headers ]]] ) : mixed

This is a low level API function that is used to make a SOAP call. Usually, in WSDL mode, SOAP functions can be called as methods of the SoapClient object. This method is useful in non-WSDL mode when soapaction is unknown, uri differs from the default or when sending and/or receiving SOAP Headers.

On error, a call to a SOAP function can cause PHP to throw exceptions or return a SoapFault object if exceptions are disabled. To check if the function call failed to catch the SoapFault exceptions, check the result with is_soap_fault().

Parameters

function_name

The name of the SOAP function to call.

arguments

An array of the arguments to pass to the function. This can be either an ordered or an associative array. Note that most SOAP servers require parameter names to be provided, in which case this must be an associative array.

options

An associative array of options to pass to the client.

The location option is the URL of the remote Web service.

The uri option is the target namespace of the SOAP service.

The soapaction option is the action to call.

input_headers

An array of headers to be sent along with the SOAP request.

output_headers

If supplied, this array will be filled with the headers from the SOAP response.

Return Values

SOAP functions may return one, or multiple values. If only one value is returned by the SOAP function, the return value of __soapCall will be a simple value (e.g. an integer, a string, etc). If multiple values are returned, __soapCall will return an associative array of named output parameters.

On error, if the SoapClient object was constructed with the exceptions option set to FALSE, a SoapFault object will be returned.

Examples

Example #1 SoapClient::__soapCall() example

<?php

$client = new SoapClient("some.wsdl");
$client->SomeFunction($a, $b, $c);

$client->__soapCall("SomeFunction", array($a, $b, $c));
$client->__soapCall("SomeFunction", array($a, $b, $c), NULL,
                    new SoapHeader(), $output_headers);

$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/"));
$client->SomeFunction($a, $b, $c);
$client->__soapCall("SomeFunction", array($a, $b, $c));
$client->__soapCall("SomeFunction", array($a, $b, $c),
                    array('soapaction' => 'some_action',
                          'uri'        => 'some_uri'));
?>

See Also

  • SoapClient::SoapClient() - SoapClient constructor
  • SoapParam::SoapParam() - SoapParam constructor
  • SoapVar::SoapVar() - SoapVar constructor
  • SoapHeader::SoapHeader() - SoapHeader constructor
  • SoapFault::SoapFault() - SoapFault constructor
  • is_soap_fault() - Checks if a SOAP call has failed


SoapClient constructor

  • « SoapClient::__soapCall
  • SoapServer »
  • PHP Manual
  • SoapClient
  • SoapClient constructor

SoapClient::SoapClient

(PHP 5, PHP 7)

SoapClient::SoapClient — SoapClient constructor

Description

public SoapClient::SoapClient ( mixed $wsdl [, array $options ] )

This constructor creates SoapClient objects in WSDL or non-WSDL mode.

Parameters

wsdl

URI of the WSDL file or NULL if working in non-WSDL mode.

Note:

During development, WSDL caching may be disabled by the use of the soap.wsdl_cache_ttl php.ini setting otherwise changes made to the WSDL file will have no effect until soap.wsdl_cache_ttl is expired.

options

An array of options. If working in WSDL mode, this parameter is optional. If working in non-WSDL mode, the location and uri options must be set, where location is the URL of the SOAP server to send the request to, and uri is the target namespace of the SOAP service.

The style and use options only work in non-WSDL mode. In WSDL mode, they come from the WSDL file.

The soap_version option should be one of either SOAP_1_1 or SOAP_1_2 to select SOAP 1.1 or 1.2, respectively. If omitted, 1.1 is used.

For HTTP authentication, the login and password options can be used to supply credentials. For making an HTTP connection through a proxy server, the options proxy_host, proxy_port, proxy_login and proxy_password are also available. For HTTPS client certificate authentication use local_cert and passphrase options. An authentication may be supplied in the authentication option. The authentication method may be either SOAP_AUTHENTICATION_BASIC (default) or SOAP_AUTHENTICATION_DIGEST.

The compression option allows to use compression of HTTP SOAP requests and responses.

The encoding option defines internal character encoding. This option does not change the encoding of SOAP requests (it is always utf-8), but converts strings into it.

The trace option enables tracing of request so faults can be backtraced. This defaults to FALSE

The classmap option can be used to map some WSDL types to PHP classes. This option must be an array with WSDL types as keys and names of PHP classes as values.

Setting the boolean trace option enables use of the
methods
SoapClient->__getLastRequest,

SoapClient->__getLastRequestHeaders,

SoapClient->__getLastResponse and

SoapClient->__getLastResponseHeaders.

The exceptions option is a boolean value defining whether soap errors throw exceptions of type SoapFault.

The connection_timeout option defines a timeout in seconds for the connection to the SOAP service. This option does not define a timeout for services with slow responses. To limit the time to wait for calls to finish the default_socket_timeout setting is available.

The typemap option is an array of type mappings. Type mapping is an array with keys type_name, type_ns (namespace URI), from_xml (callback accepting one string parameter) and to_xml (callback accepting one object parameter).

The cache_wsdl option is one of WSDL_CACHE_NONE, WSDL_CACHE_DISK, WSDL_CACHE_MEMORY or WSDL_CACHE_BOTH.

The user_agent option specifies string to use in User-Agent header.

The stream_context option is a resource for context.

The features option is a bitmask of SOAP_SINGLE_ELEMENT_ARRAYS, SOAP_USE_XSI_ARRAY_TYPE, SOAP_WAIT_ONE_WAY_CALLS.

The keep_alive option is a boolean value defining whether to send the Connection: Keep-Alive header or Connection: close.

The ssl_method option is one of SOAP_SSL_METHOD_TLS, SOAP_SSL_METHOD_SSLv2, SOAP_SSL_METHOD_SSLv3 or SOAP_SSL_METHOD_SSLv23.

Errors/Exceptions

SoapClient::SoapClient() will generate an E_ERROR error if the location and uri options aren't provided in non-WSDL mode.

A SoapFault exception will be thrown if the wsdl URI cannot be loaded.

Changelog

Version | Description
5.5.0 | New ssl_method option.
5.4.0 | New keep_alive option.

Examples

Example #1 SoapClient::SoapClient() example

<?php

$client = new SoapClient("some.wsdl");

$client = new SoapClient("some.wsdl", array('soap_version'   => SOAP_1_2));

$client = new SoapClient("some.wsdl", array('login'          => "some_name",
                                            'password'       => "some_password"));

$client = new SoapClient("some.wsdl", array('proxy_host'     => "localhost",
                                            'proxy_port'     => 8080));

$client = new SoapClient("some.wsdl", array('proxy_host'     => "localhost",
                                            'proxy_port'     => 8080,
                                            'proxy_login'    => "some_name",
                                            'proxy_password' => "some_password"));

$client = new SoapClient("some.wsdl", array('local_cert'     => "cert_key.pem"));

$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/"));

$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/",
                                     'style'    => SOAP_DOCUMENT,
                                     'use'      => SOAP_LITERAL));

$client = new SoapClient("some.wsdl",
  array('compression' => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP));

$client = new SoapClient("some.wsdl", array('encoding'=>'ISO-8859-1'));

class MyBook {
    public $title;
    public $author;
}

$client = new SoapClient("books.wsdl", array('classmap' => array('book' => "MyBook")));

?>


The SoapServer class

(PHP 5, PHP 7)

Introduction

The SoapServer class provides a server for the » SOAP 1.1 and » SOAP 1.2 protocols. It can be used with or without a WSDL service description.

Class synopsis

SoapServer {
/* Methods */
public addFunction ( mixed $functions ) : void
public addSoapHeader ( SoapHeader $object ) : void
public __construct ( mixed $wsdl [, array $options ] )
public fault ( string $code , string $string [, string $actor [, string $details [, string $name ]]] ) : void
public getFunctions ( void ) : array
public handle ([ string $soap_request ] ) : void
public setClass ( string $class_name [, mixed $... ] ) : void
public setObject ( object $object ) : void
public setPersistence ( int $mode ) : void
public SoapServer ( mixed $wsdl [, array $options ] )
}

Table of Contents

  • SoapServer::addFunction — Adds one or more functions to handle SOAP requests
  • SoapServer::addSoapHeader — Add a SOAP header to the response
  • SoapServer::__construct — SoapServer constructor
  • SoapServer::fault — Issue SoapServer fault indicating an error
  • SoapServer::getFunctions — Returns list of defined functions
  • SoapServer::handle — Handles a SOAP request
  • SoapServer::setClass — Sets the class which handles SOAP requests
  • SoapServer::setObject — Sets the object which will be used to handle SOAP requests
  • SoapServer::setPersistence — Sets SoapServer persistence mode
  • SoapServer::SoapServer — SoapServer constructor


Adds one or more functions to handle SOAP requests

  • « SoapServer
  • SoapServer::addSoapHeader »
  • PHP Manual
  • SoapServer
  • Adds one or more functions to handle SOAP requests

SoapServer::addFunction

(PHP 5, PHP 7)

SoapServer::addFunction — Adds one or more functions to handle SOAP requests

Description

public SoapServer::addFunction ( mixed $functions ) : void

Exports one or more functions for remote clients

Parameters

functions

To export one function, pass the function name into this parameter as a string.

To export several functions, pass an array of function names.

To export all the functions, pass a special constant SOAP_FUNCTIONS_ALL.

Note:

functions must receive all input arguments in the same order as defined in the WSDL file (They should not receive any output parameters as arguments) and return one or more values. To return several values they must return an array with named output parameters.

Return Values

No value is returned.

Examples

Example #1 SoapServer::addFunction() example

<?php

function echoString($inputString)
{
    return $inputString;
}

$server->addFunction("echoString");

function echoTwoStrings($inputString1, $inputString2)
{
    return array("outputString1" => $inputString1,
                 "outputString2" => $inputString2);
}
$server->addFunction(array("echoString", "echoTwoStrings"));

$server->addFunction(SOAP_FUNCTIONS_ALL);

?>

See Also

  • SoapServer::SoapServer() - SoapServer constructor
  • SoapServer::setClass() - Sets the class which handles SOAP requests


Add a SOAP header to the response

  • « SoapServer::addFunction
  • SoapServer::__construct »
  • PHP Manual
  • SoapServer
  • Add a SOAP header to the response

SoapServer::addSoapHeader

(PHP 5 >= 5.1.3, PHP 7)

SoapServer::addSoapHeader — Add a SOAP header to the response

Description

public SoapServer::addSoapHeader ( SoapHeader $object ) : void

Adds a SOAP header to be returned with the response to the current request.

Parameters

object

The header to be returned.

Return Values

No value is returned.


SoapServer constructor

  • « SoapServer::addSoapHeader
  • SoapServer::fault »
  • PHP Manual
  • SoapServer
  • SoapServer constructor

SoapServer::__construct

(PHP 5, PHP 7)

SoapServer::__construct — SoapServer constructor

Description

public SoapServer::__construct ( mixed $wsdl [, array $options ] )

This function is an alias of: SoapServer::SoapServer()


Issue SoapServer fault indicating an error

  • « SoapServer::__construct
  • SoapServer::getFunctions »
  • PHP Manual
  • SoapServer
  • Issue SoapServer fault indicating an error

SoapServer::fault

(PHP 5, PHP 7)

SoapServer::fault — Issue SoapServer fault indicating an error

Description

public SoapServer::fault ( string $code , string $string [, string $actor [, string $details [, string $name ]]] ) : void

Sends a response to the client of the current request indicating an error.

Note:

This can only be called when handling a request.

Parameters

code

The error code to return

string

A brief description of the error

actor

A string identifying the actor that caused the fault.

details

More details of the fault

name

The name of the fault. This can be used to select a name from a WSDL file.

Return Values

No value is returned.

See Also

  • SoapFault::SoapFault() - SoapFault constructor


Returns list of defined functions

  • « SoapServer::fault
  • SoapServer::handle »
  • PHP Manual
  • SoapServer
  • Returns list of defined functions

SoapServer::getFunctions

(PHP 5, PHP 7)

SoapServer::getFunctions — Returns list of defined functions

Description

public SoapServer::getFunctions ( void ) : array

Returns a list of the defined functions in the SoapServer object. This method returns the list of all functions added by SoapServer::addFunction() or SoapServer::setClass().

Parameters

This function has no parameters.

Return Values

An array of the defined functions.

Examples

Example #1 SoapServer::getFunctions() example

<?php
$server = new SoapServer(NULL, array("uri" => "http://test-uri"));
$server->addFunction(SOAP_FUNCTIONS_ALL);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $server->handle();
} else {
  echo "This SOAP server can handle following functions: ";
  $functions = $server->getFunctions();
  foreach($functions as $func) {
    echo $func . "\n";
  }
}
?>

See Also

  • SoapServer::SoapServer() - SoapServer constructor
  • SoapServer::addFunction() - Adds one or more functions to handle SOAP requests
  • SoapServer::setClass() - Sets the class which handles SOAP requests


Handles a SOAP request

  • « SoapServer::getFunctions
  • SoapServer::setClass »
  • PHP Manual
  • SoapServer
  • Handles a SOAP request

SoapServer::handle

(PHP 5, PHP 7)

SoapServer::handle — Handles a SOAP request

Description

public SoapServer::handle ([ string $soap_request ] ) : void

Processes a SOAP request, calls necessary functions, and sends a response back.

Parameters

soap_request

The SOAP request. If this argument is omitted, the request is assumed to be in the raw POST data of the HTTP request.

Return Values

No value is returned.

Examples

Example #1 SoapServer::handle() example

<?php
function test($x)
{
    return $x;
}

$server = new SoapServer(null, array('uri' => "http://test-uri/"));
$server->addFunction("test");
$server->handle();
?>

See Also

  • SoapServer::SoapServer() - SoapServer constructor


Sets the class which handles SOAP requests

  • « SoapServer::handle
  • SoapServer::setObject »
  • PHP Manual
  • SoapServer
  • Sets the class which handles SOAP requests

SoapServer::setClass

(PHP 5, PHP 7)

SoapServer::setClass — Sets the class which handles SOAP requests

Description

public SoapServer::setClass ( string $class_name [, mixed $... ] ) : void

Exports all methods from specified class.

The object can be made persistent across request for a given PHP session with the SoapServer::setPersistence() method.

Parameters

class_name

The name of the exported class.

...

These optional parameters will be passed to the default class constructor during object creation.

Return Values

No value is returned.

See Also

  • SoapServer::SoapServer() - SoapServer constructor
  • SoapServer::addFunction() - Adds one or more functions to handle SOAP requests
  • SoapServer::setPersistence() - Sets SoapServer persistence mode


Sets the object which will be used to handle SOAP requests

  • « SoapServer::setClass
  • SoapServer::setPersistence »
  • PHP Manual
  • SoapServer
  • Sets the object which will be used to handle SOAP requests

SoapServer::setObject

(PHP 5 >= 5.2.0, PHP 7)

SoapServer::setObject — Sets the object which will be used to handle SOAP requests

Description

public SoapServer::setObject ( object $object ) : void

This sets a specific object as the handler for SOAP requests, rather than just a class as in SoapServer::setClass().

Parameters

object

The object to handle the requests.

Return Values

No value is returned.

See Also

  • SoapServer::setClass() - Sets the class which handles SOAP requests


Sets SoapServer persistence mode

  • « SoapServer::setObject
  • SoapServer::SoapServer »
  • PHP Manual
  • SoapServer
  • Sets SoapServer persistence mode

SoapServer::setPersistence

(PHP 5, PHP 7)

SoapServer::setPersistence — Sets SoapServer persistence mode

Description

public SoapServer::setPersistence ( int $mode ) : void

This function allows changing the persistence state of a SoapServer object between requests. This function allows saving data between requests utilizing PHP sessions. This method only has an affect on a SoapServer after it has exported functions utilizing SoapServer::setClass().

Note:

The persistence of SOAP_PERSISTENCE_SESSION makes only objects of the given class persistent, but not the class static data. In this case, use $this->bar instead of self::$bar.

Note:

SOAP_PERSISTENCE_SESSION serializes data on the class object between requests. In order to properly utilize resources (e.g. PDO), __wakeup() and __sleep() magic methods should be utilized.

Parameters

mode

One of the SOAP_PERSISTENCE_XXX constants.

SOAP_PERSISTENCE_REQUEST - SoapServer data does not persist between requests. This is the default behavior of any SoapServer object after setClass is called.

SOAP_PERSISTENCE_SESSION - SoapServer data persists between requests. This is accomplished by serializing the SoapServer class data into $_SESSION['_bogus_session_name'], because of this session_start() must be called before this persistence mode is set.

Return Values

No value is returned.

Examples

Example #1 SoapServer::setPersistence() example

<?php
 class MyFirstPersistentSoapServer {
     private $resource; // (Such as PDO, mysqli, etc..)
     public $myvar1;
     public $myvar2;

     public function __construct() {
         $this->__wakeup(); // We're calling our wakeup to handle starting our resource
     }

     public function __wakeup() {
         $this->resource = CodeToStartOurResourceUp();
     }

     public function __sleep() {
         // We make sure to leave out $resource here, so our session data remains persistent
         // Failure to do so will result in the failure during the unserialization of data
         // on the next request; thus, our SoapObject would not be persistent across requests.
         return array('myvar1','myvar2');
     }
 }

 try {
     session_start();
     $server = new SoapServer(null, array('uri' => $_SERVER['REQUEST_URI']));
     $server->setClass('MyFirstPersistentSoapServer');
     // setPersistence MUST be called after setClass, because setClass's
     // behavior sets SESSION_PERSISTENCE_REQUEST upon enacting the method.
     $server->setPersistence(SOAP_PERSISTENCE_SESSION);
     $server->handle();
 } catch(SoapFault $e) {
     error_log("SOAP ERROR: ". $e->getMessage());
 }
?>

See Also

  • SoapServer::setClass() - Sets the class which handles SOAP requests


SoapServer constructor

  • « SoapServer::setPersistence
  • SoapFault »
  • PHP Manual
  • SoapServer
  • SoapServer constructor

SoapServer::SoapServer

(PHP 5, PHP 7)

SoapServer::SoapServer — SoapServer constructor

Description

public SoapServer::SoapServer ( mixed $wsdl [, array $options ] )

This constructor allows the creation of SoapServer objects in WSDL or non-WSDL mode.

Parameters

wsdl

To use the SoapServer in WSDL mode, pass the URI of a WSDL file. Otherwise, pass NULL and set the uri option to the target namespace for the server.

options

Allow setting a default SOAP version (soap_version), internal character encoding (encoding), and actor URI (actor).

The classmap option can be used to map some WSDL types to PHP classes. This option must be an array with WSDL types as keys and names of PHP classes as values.

The typemap option is an array of type mappings. Type mapping is an array with keys type_name, type_ns (namespace URI), from_xml (callback accepting one string parameter) and to_xml (callback accepting one object parameter).

The cache_wsdl option is one of WSDL_CACHE_NONE, WSDL_CACHE_DISK, WSDL_CACHE_MEMORY or WSDL_CACHE_BOTH.

There is also a features option which can be set to SOAP_WAIT_ONE_WAY_CALLS, SOAP_SINGLE_ELEMENT_ARRAYS, SOAP_USE_XSI_ARRAY_TYPE.

The send_errors option can be set to FALSE to sent a generic error message ("Internal error") instead of the specific error message sent otherwise.

Examples

Example #1 SoapServer::SoapServer() example

<?php

$server = new SoapServer("some.wsdl");

$server = new SoapServer("some.wsdl", array('soap_version' => SOAP_1_2));

$server = new SoapServer("some.wsdl", array('actor' => "http://example.org/ts-tests/C"));

$server = new SoapServer("some.wsdl", array('encoding'=>'ISO-8859-1'));

$server = new SoapServer(null, array('uri' => "http://test-uri/"));

class MyBook {
    public $title;
    public $author;
}

$server = new SoapServer("books.wsdl", array('classmap' => array('book' => "MyBook")));

?>

Changelog

Version | Description
5.2.0 | Added the typemap option.

See Also

  • SoapClient::SoapClient() - SoapClient constructor


The SoapFault class

(PHP 5, PHP 7)

Introduction

Represents a SOAP fault.

Class synopsis

SoapFault extends Exception {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Methods */
__construct ( string $faultcode , string $faultstring [, string $faultactor [, string $detail [, string $faultname [, string $headerfault ]]]] )
SoapFault ( string $faultcode , string $faultstring [, string $faultactor [, string $detail [, string $faultname [, string $headerfault ]]]] )
public __toString ( void ) : string
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}

Table of Contents

  • SoapFault::__construct — SoapFault constructor
  • SoapFault::SoapFault — SoapFault constructor
  • SoapFault::__toString — Obtain a string representation of a SoapFault


SoapFault constructor

  • « SoapFault
  • SoapFault::SoapFault »
  • PHP Manual
  • SoapFault
  • SoapFault constructor

SoapFault::__construct

(PHP 5, PHP 7)

SoapFault::__construct — SoapFault constructor

Description

SoapFault::__construct ( string $faultcode , string $faultstring [, string $faultactor [, string $detail [, string $faultname [, string $headerfault ]]]] )

This function is an alias of: SoapFault::SoapFault()


SoapFault constructor

  • « SoapFault::__construct
  • SoapFault::__toString »
  • PHP Manual
  • SoapFault
  • SoapFault constructor

SoapFault::SoapFault

(PHP 5, PHP 7)

SoapFault::SoapFault — SoapFault constructor

Description

SoapFault::SoapFault ( string $faultcode , string $faultstring [, string $faultactor [, string $detail [, string $faultname [, string $headerfault ]]]] )

This class is used to send SOAP fault responses from the PHP handler. faultcode, faultstring, faultactor and detail are standard elements of a SOAP Fault.

Parameters

faultcode

The error code of the SoapFault.

faultstring

The error message of the SoapFault.

faultactor

A string identifying the actor that caused the error.

detail

More details about the cause of the error.

faultname

Can be used to select the proper fault encoding from WSDL.

headerfault

Can be used during SOAP header handling to report an error in the response header.

Examples

Example #1 Some examples

<?php
function test($x)
{
    return new SoapFault("Server", "Some error message");
}

$server = new SoapServer(null, array('uri' => "http://test-uri/"));
$server->addFunction("test");
$server->handle();
?>

It is possible to use PHP exception mechanism to throw SOAP Fault.

Example #2 Some examples

<?php
function test($x)
{
    throw new SoapFault("Server", "Some error message");
}

$server = new SoapServer(null, array('uri' => "http://test-uri/"));
$server->addFunction("test");
$server->handle();
?>

See Also

  • SoapServer::fault() - Issue SoapServer fault indicating an error
  • is_soap_fault() - Checks if a SOAP call has failed


Obtain a string representation of a SoapFault

  • « SoapFault::SoapFault
  • SoapHeader »
  • PHP Manual
  • SoapFault
  • Obtain a string representation of a SoapFault

SoapFault::__toString

(PHP 5, PHP 7)

SoapFault::__toString — Obtain a string representation of a SoapFault

Description

public SoapFault::__toString ( void ) : string

Returns a string representation of the SoapFault.

Parameters

This function has no parameters.

Return Values

A string describing the SoapFault.


The SoapHeader class

(PHP 5, PHP 7)

Introduction

Represents a SOAP header.

Class synopsis

SoapHeader {
/* Methods */
__construct ( string $namespace , string $name [, mixed $data [, bool $mustunderstand [, string $actor ]]] )
SoapHeader ( string $namespace , string $name [, mixed $data [, bool $mustunderstand = FALSE [, string $actor ]]] )
}

Table of Contents

  • SoapHeader::__construct — SoapHeader constructor
  • SoapHeader::SoapHeader — SoapHeader constructor


SoapHeader constructor

  • « SoapHeader
  • SoapHeader::SoapHeader »
  • PHP Manual
  • SoapHeader
  • SoapHeader constructor

SoapHeader::__construct

(PHP 5, PHP 7)

SoapHeader::__construct — SoapHeader constructor

Description

SoapHeader::__construct ( string $namespace , string $name [, mixed $data [, bool $mustunderstand [, string $actor ]]] )

This function is an alias of: SoapHeader::SoapHeader()


SoapHeader constructor

  • « SoapHeader::__construct
  • SoapParam »
  • PHP Manual
  • SoapHeader
  • SoapHeader constructor

SoapHeader::SoapHeader

(PHP 5, PHP 7)

SoapHeader::SoapHeader — SoapHeader constructor

Description

SoapHeader::SoapHeader ( string $namespace , string $name [, mixed $data [, bool $mustunderstand = FALSE [, string $actor ]]] )

Constructs a new SoapHeader object.

Parameters

namespace

The namespace of the SOAP header element.

name

The name of the SoapHeader object.

data

A SOAP header's content. It can be a PHP value or a SoapVar object.

mustUnderstand

Value of the mustUnderstand attribute of the SOAP header element.

actor

Value of the actor attribute of the SOAP header element.

Examples

Example #1 SoapHeader::SoapHeader() example

<?php
$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/"));
$client->__soapCall("echoVoid", null, null,
                new SoapHeader('http://soapinterop.org/echoheader/',
                               'echoMeStringRequest',
                               'hello world'));
?>

See Also

  • SoapClient::__soapCall() - Calls a SOAP function
  • SoapVar::SoapVar() - SoapVar constructor
  • SoapParam::SoapParam() - SoapParam constructor
  • SoapServer::addSoapHeader() - Add a SOAP header to the response


The SoapParam class

(PHP 5, PHP 7)

Introduction

Represents parameter to a SOAP call.

Class synopsis

SoapParam {
/* Methods */
__construct ( mixed $data , string $name )
SoapParam ( mixed $data , string $name )
}

Table of Contents

  • SoapParam::__construct — SoapParam constructor
  • SoapParam::SoapParam — SoapParam constructor


SoapParam constructor

  • « SoapParam
  • SoapParam::SoapParam »
  • PHP Manual
  • SoapParam
  • SoapParam constructor

SoapParam::__construct

(PHP 5, PHP 7)

SoapParam::__construct — SoapParam constructor

Description

SoapParam::__construct ( mixed $data , string $name )

This function is an alias of: SoapParam::SoapParam()


SoapParam constructor

  • « SoapParam::__construct
  • SoapVar »
  • PHP Manual
  • SoapParam
  • SoapParam constructor

SoapParam::SoapParam

(PHP 5, PHP 7)

SoapParam::SoapParam — SoapParam constructor

Description

SoapParam::SoapParam ( mixed $data , string $name )

Constructs a new SoapParam object.

Parameters

data

The data to pass or return. This parameter can be passed directly as PHP value, but in this case it will be named as paramN and the SOAP service may not understand it.

name

The parameter name.

Examples

Example #1 SoapParam::SoapParam() example

<?php
$client = new SoapClient(null,array('location' => "http://localhost/soap.php",
                                    'uri'      => "http://test-uri/"));
$client->SomeFunction(new SoapParam($a, "a"),
                      new SoapParam($b, "b"),
                      new SoapParam($c, "c"));
?>

See Also

  • SoapClient::__soapCall() - Calls a SOAP function
  • SoapVar::SoapVar() - SoapVar constructor


The SoapVar class

(PHP 5, PHP 7)

Introduction

A class representing a variable or object for use with SOAP services.

Class synopsis

SoapVar {
/* Methods */
__construct ( mixed $data , string $encoding [, string $type_name [, string $type_namespace [, string $node_name [, string $node_namespace ]]]] )
SoapVar ( mixed $data , string $encoding [, string $type_name [, string $type_namespace [, string $node_name [, string $node_namespace ]]]] )
}

Table of Contents

  • SoapVar::__construct — SoapVar constructor
  • SoapVar::SoapVar — SoapVar constructor


SoapVar constructor

  • « SoapVar
  • SoapVar::SoapVar »
  • PHP Manual
  • SoapVar
  • SoapVar constructor

SoapVar::__construct

(PHP 5, PHP 7)

SoapVar::__construct — SoapVar constructor

Description

SoapVar::__construct ( mixed $data , string $encoding [, string $type_name [, string $type_namespace [, string $node_name [, string $node_namespace ]]]] )

This function is an alias of: SoapVar::SoapVar()


SoapVar constructor

  • « SoapVar::__construct
  • Yar »
  • PHP Manual
  • SoapVar
  • SoapVar constructor

SoapVar::SoapVar

(PHP 5, PHP 7)

SoapVar::SoapVar — SoapVar constructor

Description

SoapVar::SoapVar ( mixed $data , string $encoding [, string $type_name [, string $type_namespace [, string $node_name [, string $node_namespace ]]]] )

Constructs a new SoapVar object.

Parameters

data

The data to pass or return.

encoding

The encoding ID, one of the XSD_... constants.

type_name

The type name.

type_namespace

The type namespace.

node_name

The XML node name.

node_namespace

The XML node namespace.

Examples

Example #1 SoapVar::SoapVar() example

<?php
class SOAPStruct {
    function SOAPStruct($s, $i, $f)
    {
        $this->varString = $s;
        $this->varInt = $i;
        $this->varFloat = $f;
    }
}
$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
                                     'uri'      => "http://test-uri/"));
$struct = new SOAPStruct('arg', 34, 325.325);
$soapstruct = new SoapVar($struct, SOAP_ENC_OBJECT, "SOAPStruct", "http://soapinterop.org/xsd");
$client->echoStruct(new SoapParam($soapstruct, "inputStruct"));
?>

See Also

  • SoapClient::__soapCall() - Calls a SOAP function
  • SoapParam::SoapParam() - SoapParam constructor


Yet Another RPC Framework

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • Yar_Server — The Yar_Server class
    • Yar_Server::__construct — Register a server
    • Yar_Server::handle — Start RPC Server
  • Yar_Client — The Yar_Client class
    • Yar_Client::__call — Call service
    • Yar_Client::__construct — Create a client
    • Yar_Client::setOpt — Set calling contexts
  • Yar_Concurrent_Client — The Yar_Concurrent_Client class
    • Yar_Concurrent_Client::call — Register a concurrent call
    • Yar_Concurrent_Client::loop — Send all calls
    • Yar_Concurrent_Client::reset — Clean all registered calls
  • Yar_Server_Exception — The Yar_Server_Exception class
    • Yar_Server_Exception::getType — Retrieve exception's type
  • Yar_Client_Exception — The Yar_Client_Exception class
    • Yar_Client_Exception::getType — Retrieve exception's type


Introduction

Yar is a RPC framework which aims to provide a simple and easy way to do communication between PHP applications It has the ability to concurrently call multiple remote services.


Requirements

if you want to use msgpack as packager, you need compile Yar by your self with ./configure --enable-msgpack


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/yar.

A DLL for this PECL extension is currently unavailable. See also the building on Windows section.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Yar Configure Options
Name | Default | Changeable | Changelog
yar.packager | php | PHP_INI_SYSTEM |
yar.debug | Off | PHP_INI_ALL |
yar.connect_timeout | 1000 | PHP_INI_ALL |
yar.timeout | 5000 | PHP_INI_ALL |
yar.expose_info | On | PHP_INI_SYSTEM |

Here's a short explanation of the configuration directives.

yar.packager string

it could be php, json, and msgpack(require built with msgpack support)

yar.debug string

yar.connect_timeout integer

timeout in ms

yar.timeout integer

timeout in ms

yar.expose_info bool

whether expose the service info(when access the server via GET)


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.

YAR_VERSION (string)
YAR_CLIENT_PROTOCOL_HTTP (integer)
YAR_OPT_PACKAGER (integer)
YAR_OPT_TIMEOUT (integer)
YAR_OPT_CONNECT_TIMEOUT (integer)
YAR_OPT_HEADER (array)
Since 2.0.4
YAR_PACKAGER_PHP (string)
YAR_PACKAGER_JSON (string)
YAR_ERR_OKEY (integer)
YAR_ERR_OUTPUT (integer)
YAR_ERR_TRANSPORT (integer)
YAR_ERR_REQUEST (integer)
YAR_ERR_PROTOCOL (integer)
YAR_ERR_PACKAGER (integer)
YAR_ERR_EXCEPTION (integer)


Examples

Example #1 Yar Server Example

<?php

/* assume this page can be accessed by http://example.com/operator.php */

class Operator {

    /**
     * Add two operands
     * @param interge
     * @return interge
     */
    public function add($a, $b) {
        return $this->_add($a, $b);
    }

    /**
     * Sub
     */
    public function sub($a, $b) {
        return $a - $b;
    }

    /**
     * Mul
     */
    public function mul($a, $b) {
        return $a * $b;
    }

    /**
     * Protected methods will not be exposed
     * @param interge
     * @return interge
     */
    protected function _add($a, $b) {
        return $a + $b;
    }
}

$server = new Yar_Server(new Operator());
$server->handle();
?>

Example #2 Access the server in borwser(GET request)

The above example will output something similar to:

Yar Server Info

Example #3 Yar Client Example

<?php
$client = new yar_client("http://example.com/operator.php");

/* call directly */
var_dump($client->add(1, 2));

/* call via call */
var_dump($client->call("add", array(3, 2)));

/* __add can not be called */
var_dump($client->_add(1, 2));
?>

The above example will output something similar to:

int(3)
int(5)
PHP Fatal error:  Uncaught exception 'Yar_Server_Exception' with message 'call to api Operator::_add() failed' in *

Example #4 Yar Concurrent Client Example

<?php
function callback($ret, $callinfo) {
    echo $callinfo['method'] , " result: ", $ret , "\n";
}

/* register async call to remote services */
Yar_Concurrent_Client::call("http://example.com/operator.php", "add", array(1, 2), "callback");
Yar_Concurrent_Client::call("http://example.com/operator.php", "sub", array(2, 1), "callback");
Yar_Concurrent_Client::call("http://example.com/operator.php", "mul", array(2, 2), "callback");

/* sent all request and wait for response */
Yar_Concurrent_Client::loop();
?>

The above example will output something similar to:

mul result: 4
sub result: 1
add result: 3


The Yar_Server class

(No version information available, might only be in Git)

Introduction

Class synopsis

Yar_Server {
/* Properties */
protected $_executor ;
/* Methods */
final public __construct ( Object $obj )
public handle ( void ) : bool
}

Properties

_executor

Table of Contents

  • Yar_Server::__construct — Register a server
  • Yar_Server::handle — Start RPC Server


Register a server

  • « Yar_Server
  • Yar_Server::handle »
  • PHP Manual
  • Yar_Server
  • Register a server

Yar_Server::__construct

(PECL yar >= 1.0.0)

Yar_Server::__construct — Register a server

Description

final public Yar_Server::__construct ( Object $obj )

Set up a Yar HTTP RPC Server, All the public methods of $obj will be register as a RPC service.

Parameters

obj

An Object, all public methods of its will be registered as RPC services.

Return Values

An instance of Yar_Server.

Examples

Example #1 Yar_Server::__construct() example

<?php
class API {
    /**
     * the doc info will be generated automatically into service info page.
     * @params
     * @return
     */
    public function some_method($parameter, $option = "foo") {
         return "some_method";
    }

    protected function client_can_not_see() {
    }
}

$service = new Yar_Server(new API());
$service->handle();
?>

The above example will output something similar to:

See Also

  • Yar_Server::handle() - Start RPC Server
    •


Start RPC Server

  • « Yar_Server::__construct
  • Yar_Client »
  • PHP Manual
  • Yar_Server
  • Start RPC Server

Yar_Server::handle

(PECL yar >= 1.0.0)

Yar_Server::handle — Start RPC Server

Description

public Yar_Server::handle ( void ) : bool

Start a RPC HTTP server, and ready for accpet RPC requests.

Note:

Usual RPC calls will be issued as HTTP POST requests. If a HTTP GET request is issued to the uri, the service information (commented section above) will be printed on the page

Parameters

This function has no parameters.

Return Values

boolean

Examples

Example #1 Yar_Server::handle() example

<?php
class API {
    /**
     * the doc info will be generated automatically into service info page.
     * @params
     * @return
     */
    public function some_method($parameter, $option = "foo") {
    }

    protected function client_can_not_see() {
    }
}

$service = new Yar_Server(new API());
$service->handle();
?>

The above example will output something similar to:

See Also

  • Yar_Server::__construct() - Register a server
    •


The Yar_Client class

(No version information available, might only be in Git)

Introduction

Class synopsis

Yar_Client {
/* Properties */
protected $_protocol ;
protected $_uri ;
protected $_options ;
protected $_running ;
/* Methods */
public __call ( string $method , array $parameters ) : void
final public __construct ( string $url [, array $options ] )
public setOpt ( int $name , mixed $value ) : Yar_Client
}

Properties

_protocol

_uri

_options

_running

Table of Contents

  • Yar_Client::__call — Call service
  • Yar_Client::__construct — Create a client
  • Yar_Client::setOpt — Set calling contexts


Call service

  • « Yar_Client
  • Yar_Client::__construct »
  • PHP Manual
  • Yar_Client
  • Call service

Yar_Client::__call

(PECL yar >= 1.0.0)

Yar_Client::__call — Call service

Description

public Yar_Client::__call ( string $method , array $parameters ) : void

Issue a call to remote RPC method.

Parameters

method

Remote RPC method name.

parameters

Parameters.

Return Values

Examples

Example #1 Yar_Client::__call() example

<?php

$client = new Yar_Client("http://host/api/");

/* call remote service */
$result = $client->some_method("parameter");
?>

The above example will output something similar to:

See Also

  • Yar_Client::setOpt() - Set calling contexts
    •


Create a client

  • « Yar_Client::__call
  • Yar_Client::setOpt »
  • PHP Manual
  • Yar_Client
  • Create a client

Yar_Client::__construct

(PECL yar >= 1.0.0)

Yar_Client::__construct — Create a client

Description

final public Yar_Client::__construct ( string $url [, array $options ] )

Create a Yar_Client to a Yar_Server.

Parameters

url

Yar Server URL.

Return Values

Yar_Client instance.

Examples

Example #1 Yar_Client::__construct() example

<?php
$client = new Yar_Client("http://host/api/");
?>

The above example will output something similar to:

See Also

  • Yar_Client::__call() - Call service
    •

  • Yar_Client::setOpt() - Set calling contexts
    •


Set calling contexts

  • « Yar_Client::__construct
  • Yar_Concurrent_Client »
  • PHP Manual
  • Yar_Client
  • Set calling contexts

Yar_Client::setOpt

(PECL yar >= 1.0.0)

Yar_Client::setOpt — Set calling contexts

Description

public Yar_Client::setOpt ( int $name , mixed $value ) : Yar_Client

Parameters

name

it can be: YAR_OPT_PACKAGER, YAR_OPT_PERSISTENT (Need server support), YAR_OPT_TIMEOUT, YAR_OPT_CONNECT_TIMEOUT YAR_OPT_HEADER (Since 2.0.4)

value

Return Values

Returns $this on success or FALSE on failure.

Examples

Example #1 Yar_Client::setOpt() example

<?php

$cient = new Yar_Client("http://host/api/");

//Set timeout to 1s
$client->SetOpt(YAR_OPT_CONNECT_TIMEOUT, 1000);

//Set packager to JSON
$client->SetOpt(YAR_OPT_PACKAGER, "json");

//Set Custom headers
$client->SetOpt(YAR_OPT_HEADER, array("hr1: val1", "hd2: val2"));

/* call remote service */
$result = $client->some_method("parameter");
?>

The above example will output something similar to:

See Also

  • Yar_Client::__call() - Call service
    •


The Yar_Concurrent_Client class

(No version information available, might only be in Git)

Introduction

Class synopsis

Yar_Concurrent_Client {
/* Properties */
static $_callstack ;
static $_callback ;
static $_error_callback ;
/* Methods */
public static call ( string $uri , string $method [, array $parameters [, callable $callback [, callable $error_callback [, array $options ]]]] ) : int
public static loop ([ callable $callback [, callable $error_callback ]] ) : bool
public static reset ( void ) : bool
}

Properties

_callstack

_callback

_error_callback

Table of Contents

  • Yar_Concurrent_Client::call — Register a concurrent call
  • Yar_Concurrent_Client::loop — Send all calls
  • Yar_Concurrent_Client::reset — Clean all registered calls


Register a concurrent call

  • « Yar_Concurrent_Client
  • Yar_Concurrent_Client::loop »
  • PHP Manual
  • Yar_Concurrent_Client
  • Register a concurrent call

Yar_Concurrent_Client::call

(PECL yar >= 1.0.0)

Yar_Concurrent_Client::call — Register a concurrent call

Description

public static Yar_Concurrent_Client::call ( string $uri , string $method [, array $parameters [, callable $callback [, callable $error_callback [, array $options ]]]] ) : int

Register a RPC call, but won't sent it immediately, it will be send while further call to Yar_Concurrent_Client::loop()

Parameters

uri

The RPC server URI(http, tcp)

method

Service name(aka the method name)

parameters

Parameters

callback

A function callback, which will be called while the response return.

Return Values

An unique id, can be used to identified which call it is.

Examples

Example #1 Yar_Concurrent_Client::call() example

<?php
function callback($retval, $callinfo) {
     var_dump($retval);
}

function error_callback($type, $error, $callinfo) {
    error_log($error);
}

Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback");
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"));   // if the callback is not specificed,
                                                                               // callback in loop will be used
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback", NULL, array(YAR_OPT_PACKAGER => "json"));
                                                                               //this server accept json packager
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback", NULL, array(YAR_OPT_TIMEOUT=>1));
                                                                               //custom timeout

//The requests are not sent yet
?>

The above example will output something similar to:

See Also

  • Yar_Concurrent_Client::loop() - Send all calls
    •

  • Yar_Concurrent_Client::reset() - Clean all registered calls
    •

  • Yar_Server::__construct() - Register a server
    •

  • Yar_Server::handle() - Start RPC Server
    •


Send all calls

  • « Yar_Concurrent_Client::call
  • Yar_Concurrent_Client::reset »
  • PHP Manual
  • Yar_Concurrent_Client
  • Send all calls

Yar_Concurrent_Client::loop

(PECL yar >= 1.0.0)

Yar_Concurrent_Client::loop — Send all calls

Description

public static Yar_Concurrent_Client::loop ([ callable $callback [, callable $error_callback ]] ) : bool

Send all registed remote RPC calls.

Parameters

callback

If this callback is set, then Yar will call this callback after all calls are sent and before any response return, with a $callinfo NULL.

Then, if user didn't specify callback when registering concurrent call, this callback will be used to handle response, otherwise, the callback specified while registering will be used.

error_callback

If this callback is set, then Yar will call this callback while error occurred.

Return Values

Examples

Example #1 Yar_Concurrent_Client::loop() example

<?php
function callback($retval, $callinfo) {
     if ($callinfo == NULL) {
        echo "Now, all requests are sent, and no any response available\n";
     } else {
        echo "This is a remote call response, the method name is", $callinfo["method"],
             ". calling sequence is " , $callinfo["sequence"] , "\n";
        var_dump($retval);
     }
}

function error_callback($type, $error, $callinfo) {
    error_log($error);
}

Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback");
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"));   // if the callback is not specificed,
                                                                               // callback in loop will be used
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback", NULL, array(YAR_OPT_PACKAGER => "json"));
                                                                               //this server accept json packager
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback", NULL, array(YAR_OPT_TIMEOUT=>1));
                                                                               //custom timeout

Yar_Concurrent_Client::loop("callback", "error_callback"); //send the requests,
                                                           //the error_callback is optional
?>

The above example will output something similar to:

Now, all requests are sent, and no any response available
This is a remote call response, the method name issome_method. calling sequence is 4
string(11) "some_method"
This is a remote call response, the method name issome_method. calling sequence is 1
string(11) "some_method"
This is a remote call response, the method name issome_method. calling sequence is 2
string(11) "some_method"
This is a remote call response, the method name issome_method. calling sequence is 3
string(11) "some_method"

See Also

  • Yar_Concurrent_Client::call() - Register a concurrent call
  • Yar_Concurrent_Client::reset() - Clean all registered calls
  • Yar_Server::__construct() - Register a server
  • Yar_Server::handle() - Start RPC Server


Clean all registered calls

  • « Yar_Concurrent_Client::loop
  • Yar_Server_Exception »
  • PHP Manual
  • Yar_Concurrent_Client
  • Clean all registered calls

Yar_Concurrent_Client::reset

(PECL yar >= 1.2.4)

Yar_Concurrent_Client::reset — Clean all registered calls

Description

public static Yar_Concurrent_Client::reset ( void ) : bool

Clean all registered calls

Parameters

Return Values

Examples

Example #1 Yar_Concurrent_Client::reset() example

The above example will output something similar to:

See Also

  • Yar_Concurrent_Client::call() - Register a concurrent call
    •

  • Yar_Concurrent_Client::loop() - Send all calls
    •

  • Yar_Server::__construct() - Register a server
    •

  • Yar_Server::handle() - Start RPC Server
    •


The Yar_Server_Exception class

(No version information available, might only be in Git)

Introduction

If service threw exceptions, A Yar_Server_Exception will be threw in client side.

Class synopsis

Yar_Server_Exception extends Exception {
/* Properties */
protected $_type ;
/* Methods */
public getType ( void ) : string
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}

Properties

message

code

file

line

_type

Table of Contents

  • Yar_Server_Exception::getType — Retrieve exception's type


Retrieve exception's type

  • « Yar_Server_Exception
  • Yar_Client_Exception »
  • PHP Manual
  • Yar_Server_Exception
  • Retrieve exception's type

Yar_Server_Exception::getType

(PECL yar >= 1.0.0)

Yar_Server_Exception::getType — Retrieve exception's type

Description

public Yar_Server_Exception::getType ( void ) : string

Get the exception original type threw by server

Parameters

This function has no parameters.

Return Values

string

Examples

Example #1 Yar_Server_Exception::getType() example

//Server.php
<?php
class Custom_Exception extends Exception {};

class API {
    public function throw_exception($name) {
        throw new Custom_Exception($name);
    }
}

$service = new Yar_Server(new API());
$service->handle();
?>

//Client.php
<?php
$client = new Yar_Client("http://host/api.php");

try {
    $client->throw_exception("client");
} catch (Yar_Server_Exception $e) {
    var_dump($e->getType());
    var_dump($e->getMessage());
}

The above example will output something similar to:

string(16) "Custom_Exception"
string(6) "client"

See Also


The Yar_Client_Exception class

(No version information available, might only be in Git)

Introduction

Class synopsis

Yar_Client_Exception extends Exception {
/* Properties */
/* Methods */
public getType ( void ) : string
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}

Properties

message

code

file

line

Table of Contents

  • Yar_Client_Exception::getType — Retrieve exception's type


Retrieve exception's type

  • « Yar_Client_Exception
  • XML-RPC »
  • PHP Manual
  • Yar_Client_Exception
  • Retrieve exception's type

Yar_Client_Exception::getType

(PECL yar >= 1.0.0)

Yar_Client_Exception::getType — Retrieve exception's type

Description

public Yar_Client_Exception::getType ( void ) : string

Parameters

This function has no parameters.

Return Values

Returns "Yar_Exception_Client".

Examples

Example #1 Yar_Client_Exception::getType() example

<?php

/* ... */

?>

The above example will output something similar to:

...

See Also

  • Yaf_Server_Exception::getType()


XML-RPC

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • XML-RPC Functions
    • xmlrpc_decode_request — Decodes XML into native PHP types
    • xmlrpc_decode — Decodes XML into native PHP types
    • xmlrpc_encode_request — Generates XML for a method request
    • xmlrpc_encode — Generates XML for a PHP value
    • xmlrpc_get_type — Gets xmlrpc type for a PHP value
    • xmlrpc_is_fault — Determines if an array value represents an XMLRPC fault
    • xmlrpc_parse_method_descriptions — Decodes XML into a list of method descriptions
    • xmlrpc_server_add_introspection_data — Adds introspection documentation
    • xmlrpc_server_call_method — Parses XML requests and call methods
    • xmlrpc_server_create — Creates an xmlrpc server
    • xmlrpc_server_destroy — Destroys server resources
    • xmlrpc_server_register_introspection_callback — Register a PHP function to generate documentation
    • xmlrpc_server_register_method — Register a PHP function to resource method matching method_name
    • xmlrpc_set_type — Sets xmlrpc type, base64 or datetime, for a PHP string value


Introduction

These functions can be used to write XML-RPC servers and clients. You can find more information about XML-RPC at » http://www.xmlrpc.com/, and more documentation on this extension and its functions at » http://xmlrpc-epi.sourceforge.net/.

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.


Installation

XML-RPC support in PHP is not enabled by default. You will need to use the --with-xmlrpc[=DIR] configuration option when compiling PHP to enable XML-RPC support.


  • « Runtime Configuration
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

This extension defines a XML-RPC server resource returned by xmlrpc_server_create().


  • « Resource Types
  • XML-RPC Functions »
  • PHP Manual
  • XML-RPC
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


XML-RPC Functions

Table of Contents

  • xmlrpc_decode_request — Decodes XML into native PHP types
  • xmlrpc_decode — Decodes XML into native PHP types
  • xmlrpc_encode_request — Generates XML for a method request
  • xmlrpc_encode — Generates XML for a PHP value
  • xmlrpc_get_type — Gets xmlrpc type for a PHP value
  • xmlrpc_is_fault — Determines if an array value represents an XMLRPC fault
  • xmlrpc_parse_method_descriptions — Decodes XML into a list of method descriptions
  • xmlrpc_server_add_introspection_data — Adds introspection documentation
  • xmlrpc_server_call_method — Parses XML requests and call methods
  • xmlrpc_server_create — Creates an xmlrpc server
  • xmlrpc_server_destroy — Destroys server resources
  • xmlrpc_server_register_introspection_callback — Register a PHP function to generate documentation
  • xmlrpc_server_register_method — Register a PHP function to resource method matching method_name
  • xmlrpc_set_type — Sets xmlrpc type, base64 or datetime, for a PHP string value


Decodes XML into native PHP types

  • « XML-RPC Functions
  • xmlrpc_decode »
  • PHP Manual
  • XML-RPC Functions
  • Decodes XML into native PHP types

xmlrpc_decode_request

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_decode_request — Decodes XML into native PHP types

Description

xmlrpc_decode_request ( string $xml , string &$method [, string $encoding ] ) : mixed
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.

Warning

This function is currently not documented; only its argument list is available.


Decodes XML into native PHP types

  • « xmlrpc_decode_request
  • xmlrpc_encode_request »
  • PHP Manual
  • XML-RPC Functions
  • Decodes XML into native PHP types

xmlrpc_decode

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_decode — Decodes XML into native PHP types

Description

xmlrpc_decode ( string $xml [, string $encoding = "iso-8859-1" ] ) : mixed
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.

Parameters

xml

XML response returned by XMLRPC method.

encoding

Input encoding supported by iconv.

Return Values

Returns either an array, or an integer, or a string, or a boolean according to the response returned by the XMLRPC method.

Examples

See example by xmlrpc_encode_request().

See Also

  • xmlrpc_encode_request() - Generates XML for a method request
  • xmlrpc_is_fault() - Determines if an array value represents an XMLRPC fault


Generates XML for a method request

  • « xmlrpc_decode
  • xmlrpc_encode »
  • PHP Manual
  • XML-RPC Functions
  • Generates XML for a method request

xmlrpc_encode_request

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_encode_request — Generates XML for a method request

Description

xmlrpc_encode_request ( string $method , mixed $params [, array $output_options ] ) : string
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.

Parameters

method

Name of the method to call.

params

Method parameters compatible with method signature.

output_options

Array specifying output options may contain (default values are emphasised):

  • output_type: php, xml

  • verbosity: no_white_space, newlines_only, pretty

  • escaping: cdata, non-ascii, non-print, markup (may be a string with one value or an array with multiple values)

  • version: simple, xmlrpc, soap 1.1, auto

  • encoding: iso-8859-1, other character set supported by iconv

Return Values

Returns a string containing the XML representation of the request.

Examples

Example #1 XMLRPC client functions example

<?php
$request = xmlrpc_encode_request("method", array(1, 2, 3));
$context = stream_context_create(array('http' => array(
    'method' => "POST",
    'header' => "Content-Type: text/xml",
    'content' => $request
)));
$file = file_get_contents("http://www.example.com/xmlrpc", false, $context);
$response = xmlrpc_decode($file);
if ($response && xmlrpc_is_fault($response)) {
    trigger_error("xmlrpc: $response[faultString] ($response[faultCode])");
} else {
    print_r($response);
}
?>

See Also

  • stream_context_create() - Creates a stream context
  • file_get_contents() - Reads entire file into a string
  • xmlrpc_decode() - Decodes XML into native PHP types


Generates XML for a PHP value

  • « xmlrpc_encode_request
  • xmlrpc_get_type »
  • PHP Manual
  • XML-RPC Functions
  • Generates XML for a PHP value

xmlrpc_encode

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_encode — Generates XML for a PHP value

Description

xmlrpc_encode ( mixed $value ) : string
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.

Warning

This function is currently not documented; only its argument list is available.


Gets xmlrpc type for a PHP value

  • « xmlrpc_encode
  • xmlrpc_is_fault »
  • PHP Manual
  • XML-RPC Functions
  • Gets xmlrpc type for a PHP value

xmlrpc_get_type

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_get_type — Gets xmlrpc type for a PHP value

Description

xmlrpc_get_type ( mixed $value ) : string
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.

This function is especially useful for base64 and datetime strings.

Parameters

value

PHP value

Return Values

Returns the XML-RPC type.

Examples

Example #1 XML-RPC type example

<?php
echo xmlrpc_get_type(null) . "\n"; // base64
echo xmlrpc_get_type(false) . "\n"; // boolean
echo xmlrpc_get_type(1) . "\n"; // int
echo xmlrpc_get_type(1.0) . "\n"; // double
echo xmlrpc_get_type("") . "\n"; // string
echo xmlrpc_get_type(array()) . "\n"; // array
echo xmlrpc_get_type(new stdClass) . "\n"; // array
echo xmlrpc_get_type(STDIN) . "\n"; // int
?>

See Also

  • xmlrpc_set_type() - Sets xmlrpc type, base64 or datetime, for a PHP string value


Determines if an array value represents an XMLRPC fault

  • « xmlrpc_get_type
  • xmlrpc_parse_method_descriptions »
  • PHP Manual
  • XML-RPC Functions
  • Determines if an array value represents an XMLRPC fault

xmlrpc_is_fault

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

xmlrpc_is_fault — Determines if an array value represents an XMLRPC fault

Description

xmlrpc_is_fault ( array $arg ) : bool
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.

Parameters

arg

Array returned by xmlrpc_decode().

Return Values

Returns TRUE if the argument means fault, FALSE otherwise. Fault description is available in $arg["faultString"], fault code is in $arg["faultCode"].

Examples

See example by xmlrpc_encode_request().

See Also

  • xmlrpc_decode() - Decodes XML into native PHP types


Decodes XML into a list of method descriptions

  • « xmlrpc_is_fault
  • xmlrpc_server_add_introspection_data »
  • PHP Manual
  • XML-RPC Functions
  • Decodes XML into a list of method descriptions

xmlrpc_parse_method_descriptions

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_parse_method_descriptions — Decodes XML into a list of method descriptions

Description

xmlrpc_parse_method_descriptions ( string $xml ) : array
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.

Warning

This function is currently not documented; only its argument list is available.


Adds introspection documentation

  • « xmlrpc_parse_method_descriptions
  • xmlrpc_server_call_method »
  • PHP Manual
  • XML-RPC Functions
  • Adds introspection documentation

xmlrpc_server_add_introspection_data

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_add_introspection_data — Adds introspection documentation

Description

xmlrpc_server_add_introspection_data ( resource $server , array $desc ) : int
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.

Warning

This function is currently not documented; only its argument list is available.


Parses XML requests and call methods

  • « xmlrpc_server_add_introspection_data
  • xmlrpc_server_create »
  • PHP Manual
  • XML-RPC Functions
  • Parses XML requests and call methods

xmlrpc_server_call_method

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_call_method — Parses XML requests and call methods

Description

xmlrpc_server_call_method ( resource $server , string $xml , mixed $user_data [, array $output_options ] ) : string
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.

Warning

This function is currently not documented; only its argument list is available.


Creates an xmlrpc server

  • « xmlrpc_server_call_method
  • xmlrpc_server_destroy »
  • PHP Manual
  • XML-RPC Functions
  • Creates an xmlrpc server

xmlrpc_server_create

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_create — Creates an xmlrpc server

Description

xmlrpc_server_create ( void ) : resource
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.

Warning

This function is currently not documented; only its argument list is available.


Destroys server resources

  • « xmlrpc_server_create
  • xmlrpc_server_register_introspection_callback »
  • PHP Manual
  • XML-RPC Functions
  • Destroys server resources

xmlrpc_server_destroy

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_destroy — Destroys server resources

Description

xmlrpc_server_destroy ( resource $server ) : bool
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.

Warning

This function is currently not documented; only its argument list is available.


Register a PHP function to generate documentation

  • « xmlrpc_server_destroy
  • xmlrpc_server_register_method »
  • PHP Manual
  • XML-RPC Functions
  • Register a PHP function to generate documentation

xmlrpc_server_register_introspection_callback

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_register_introspection_callback — Register a PHP function to generate documentation

Description

xmlrpc_server_register_introspection_callback ( resource $server , string $function ) : bool
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.

Warning

This function is currently not documented; only its argument list is available.


Register a PHP function to resource method matching method_name

  • « xmlrpc_server_register_introspection_callback
  • xmlrpc_set_type »
  • PHP Manual
  • XML-RPC Functions
  • Register a PHP function to resource method matching method_name

xmlrpc_server_register_method

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_register_method — Register a PHP function to resource method matching method_name

Description

xmlrpc_server_register_method ( resource $server , string $method_name , string $function ) : bool
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.

Warning

This function is currently not documented; only its argument list is available.


Sets xmlrpc type, base64 or datetime, for a PHP string value

  • « xmlrpc_server_register_method
  • Windows Only Extensions »
  • PHP Manual
  • XML-RPC Functions
  • Sets xmlrpc type, base64 or datetime, for a PHP string value

xmlrpc_set_type

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_set_type — Sets xmlrpc type, base64 or datetime, for a PHP string value

Description

xmlrpc_set_type ( string &$value , string $type ) : bool

Sets xmlrpc type, base64 or datetime, for a PHP string value.

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.

Parameters

value

Value to set the type

type

'base64' or 'datetime'

Return Values

Returns TRUE on success or FALSE on failure. If successful, value is converted to an object.

Examples

Example #1 A xmlrpc_set_type() example

<?php

$params = date("Ymd\TH:i:s", time());
xmlrpc_set_type($params, 'datetime');
echo xmlrpc_encode($params);

?>

The above example will output something similar to:

<?xml version="1.0" encoding="utf-8"?>
<params>
<param>
 <value>
  <dateTime.iso8601>20090322T23:43:03</dateTime.iso8601>
 </value>
</param>
</params>

Errors/Exceptions

Issues E_WARNING with type unsupported by XMLRPC.


Windows Only Extensions

  • COM — COM and .Net (Windows)
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Errors and error handling
    • Examples
    • COM — The COM class
    • DOTNET — The DOTNET class
    • VARIANT — VARIANT class
    • com_exception — The com_exception class
    • COM Functions
  • win32ps
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • win32ps Functions
  • win32service
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • win32service Functions


COM and .Net (Windows)

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Errors and error handling
  • Examples
    • For Each
    • Arrays and Array-style COM properties
  • COM — The COM class
    • COM::__construct — COM class constructor
  • DOTNET — The DOTNET class
    • DOTNET::__construct — DOTNET class constructor
  • VARIANT — VARIANT class
    • VARIANT::__construct — VARIANT class constructor
  • com_exception — The com_exception class
  • COM Functions
    • com_create_guid — Generate a globally unique identifier (GUID)
    • com_event_sink — Connect events from a COM object to a PHP object
    • com_get_active_object — Returns a handle to an already running instance of a COM object
    • com_load_typelib — Loads a Typelib
    • com_message_pump — Process COM messages, sleeping for up to timeoutms milliseconds
    • com_print_typeinfo — Print out a PHP class definition for a dispatchable interface
    • variant_abs — Returns the absolute value of a variant
    • variant_add — "Adds" two variant values together and returns the result
    • variant_and — Performs a bitwise AND operation between two variants
    • variant_cast — Convert a variant into a new variant object of another type
    • variant_cat — Concatenates two variant values together and returns the result
    • variant_cmp — Compares two variants
    • variant_date_from_timestamp — Returns a variant date representation of a Unix timestamp
    • variant_date_to_timestamp — Converts a variant date/time value to Unix timestamp
    • variant_div — Returns the result from dividing two variants
    • variant_eqv — Performs a bitwise equivalence on two variants
    • variant_fix — Returns the integer portion of a variant
    • variant_get_type — Returns the type of a variant object
    • variant_idiv — Converts variants to integers and then returns the result from dividing them
    • variant_imp — Performs a bitwise implication on two variants
    • variant_int — Returns the integer portion of a variant
    • variant_mod — Divides two variants and returns only the remainder
    • variant_mul — Multiplies the values of the two variants
    • variant_neg — Performs logical negation on a variant
    • variant_not — Performs bitwise not negation on a variant
    • variant_or — Performs a logical disjunction on two variants
    • variant_pow — Returns the result of performing the power function with two variants
    • variant_round — Rounds a variant to the specified number of decimal places
    • variant_set_type — Convert a variant into another type "in-place"
    • variant_set — Assigns a new value for a variant object
    • variant_sub — Subtracts the value of the right variant from the left variant value
    • variant_xor — Performs a logical exclusion on two variants


Introduction

COM is an acronym for Component Object Model; it is an object orientated layer (and associated services) on top of DCE RPC (an open standard) and defines a common calling convention that enables code written in any language to call and interoperate with code written in any other language (provided those languages are COM aware). Not only can the code be written in any language, but it need not even be part of the same executable; the code can be loaded from a DLL, be found in another process running on the same machine, or, with DCOM (Distributed COM), be found in another process on a remote machine, all without your code even needing to know where a component resides.

There is a subset of COM known as OLE Automation which comprises a set of COM interfaces that allow loose binding to COM objects, so that they can be introspected and called at run-time without compile-time knowledge of how the object works. The PHP COM extension utilizes the OLE Automation interfaces to allow you to create and call compatible objects from your scripts. Technically speaking, this should really be called the "OLE Automation Extension for PHP", since not all COM objects are OLE compatible.

Now, why would or should you use COM? COM is one of the main ways to glue applications and components together on the Windows platform; using COM you can launch Microsoft Word, fill in a document template and save the result as a Word document and send it to a visitor of your web site. You can also use COM to perform administrative tasks for your network and to configure your IIS; these are just the most common uses; you can do much more with COM.

Additionally, we support the instantiation and creation of .Net assemblies using the COM interoperability layer provided by Microsoft.


Requirements

COM functions are only available for the Windows version of PHP.

.Net support requires the .Net runtime.


Installation

As of PHP 5.3.15 / 5.4.5, this extension requires php_com_dotnet.dll to be enabled inside of php.ini in order to use these functions. Previous versions of PHP enabled these extensions by default.

You are responsible for installing support for the various COM objects that you intend to use (such as MS Word); we don't and can't bundle all of those with PHP.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Com configuration options
Name | Default | Changeable | Changelog
com.allow_dcom | "0" | PHP_INI_SYSTEM |
com.autoregister_typelib | "0" | PHP_INI_ALL |
com.autoregister_verbose | "0" | PHP_INI_ALL |
com.autoregister_casesensitive | "1" | PHP_INI_ALL |
com.code_page | "" | PHP_INI_ALL |
com.typelib_file | "" | PHP_INI_SYSTEM |
For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

Here's a short explanation of the configuration directives.

com.allow_dcom

When this is turned on, PHP will be allowed to operate as a D-COM (Distributed COM) client and will allow the PHP script to instantiate COM objects on a remote server.

com.autoregister_typelib

When this is turned on, PHP will attempt to register constants from the typelibrary of COM objects that it instantiates, if those objects implement the interfaces required to obtain that information. The case sensitivity of the constants it registers is controlled by the configuration directive.

com.autoregister_verbose

When this is turned on, any problems with loading a typelibrary during object instantiation will be reported using the PHP error mechanism. The default is off, which does not emit any indication if there was an error finding or loading the type library.

com.autoregister_casesensitive

When this is turned on (the default), constants found in auto-loaded type libraries when instatiating COM objects will be registered case sensitively. See com_load_typelib() for more details.

com.code_page

It controls the default character set code-page to use when passing strings to and from COM objects. If set to an empty string, PHP will assume that you want CP_ACP, which is the default system ANSI code page.

If the text in your scripts is encoded using a different encoding/character set by default, setting this directive will save you from having to pass the code page as a parameter to the COM class constructor. Please note that by using this directive (as with any PHP configuration directive), your PHP script becomes less portable; you should use the COM constructor parameter whenever possible.

com.typelib_file

When set, this should hold the path to a file that contains a list of typelibraries that should be loaded on startup. Each line of the file will be treated as the type library name and loaded as though you had called com_load_typelib(). The constants will be registered persistently, so that the library only needs to be loaded once. If a type library name ends with the string #cis or #case_insensitive, then the constants from that library will be registered case insensitively.


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.

COM constants
Constant | Value | Description | Notes
CLSCTX_INPROC_SERVER (integer) | 1 | The code that creates and manages objects of this class is a DLL that runs in the same process as the caller of the function specifying the class context. |
CLSCTX_INPROC_HANDLER (integer) | 2 | The code that manages objects of this class is an in-process handler. This is a DLL that runs in the client process and implements client-side structures of this class when instances of the class are accessed remotely. |
CLSCTX_LOCAL_SERVER (integer) | 4 | The EXE code that creates and manages objects of this class runs on same machine but is loaded in a separate process space. |
CLSCTX_REMOTE_SERVER (integer) | 16 | A remote context. The code that creates and manages objects of this class is run on a different computer. |
CLSCTX_SERVER (integer) | 21 | Indicates server code, whether in-process, local, or remote. This definition ORs CLSCTX_INPROC_SERVER, CLSCTX_LOCAL_SERVER, and CLSCTX_REMOTE_SERVER. |
CLSCTX_ALL (integer) | 23 | Indicates all class contexts. This definition ORs CLSCTX_INPROC_HANDLER and CLSCTX_SERVER. |
VT_NULL (integer) | 1 | NULL pointer reference. |
VT_EMPTY (integer) | 0 | A property with a type indicator of VT_EMPTY has no data associated with it; that is, the size of the value is zero. |
VT_UI1 (integer) | 17 | 1-byte unsigned integer. |
VT_I2 (integer) | 2 | Two bytes representing a 2-byte signed integer value. |
VT_I4 (integer) | 3 | 4-byte signed integer value. |
VT_I8 (integer) | 3 | 8-byte signed integer value. | Available as of PHP 7.0.0 (x64 only).
VT_R4 (integer) | 4 | 32-bit IEEE floating point value. |
VT_R8 (integer) | 5 | 64-bit IEEE floating point value. |
VT_BOOL (integer) | 11 | Boolean value. |
VT_ERROR (integer) | 10 | Error code; containing the status code associated with the error. |
VT_CY (integer) | 6 | 8-byte two's complement integer (scaled by 10,000). |
VT_DATE (integer) | 7 | A 64-bit floating point number representing the number of days (not seconds) since December 31, 1899. For example, January 1, 1900, is 2.0, January 2, 1900, is 3.0, and so on). This is stored in the same representation as VT_R8. |
VT_BSTR (integer) | 8 | Pointer to a null-terminated Unicode string. |
VT_DECIMAL (integer) | 14 | A decimal structure. |
VT_UNKNOWN (integer) | 13 | A pointer to an object that implements the IUnknown interface. |
VT_DISPATCH (integer) | 9 | A pointer to a pointer to an object was specified. |
VT_VARIANT (integer) | 12 | A type indicator followed by the corresponding value. VT_VARIANT can be used only with VT_BYREF. |
VT_I1 (integer) | 16 | 1-byte signed integer. |
VT_UI2 (integer) | 18 | 2-byte unsigned integer. |
VT_UI4 (integer) | 19 | 4-byte unsigned integer. |
VT_UI8 (integer) | 19 | 8-byte unsigned integer. | Available as of PHP 7.0.0 (x64 only).
VT_INT (integer) | 22 | 4-byte signed integer value (equivalent to VT_I4). |
VT_UINT (integer) | 23 | 4-byte unsigned integer (equivalent to VT_UI4). |
VT_ARRAY (integer) | 8192 | If the type indicator is combined with VT_ARRAY by an OR operator, the value is a pointer to a SAFEARRAY. VT_ARRAY can use the OR with the following data types: VT_I1, VT_UI1, VT_I2, VT_UI2, VT_I4, VT_UI4, VT_INT, VT_UINT, VT_R4, VT_R8, VT_BOOL, VT_DECIMAL, VT_ERROR, VT_CY, VT_DATE, VT_BSTR, VT_DISPATCH, VT_UNKNOWN and VT_VARIANT. |
VT_BYREF (integer) | 16384 | If the type indicator is combined with VT_BYREF by an OR operator, the value is a reference. Reference types are interpreted as a reference to data, similar to the reference type in C++. |
CP_ACP (integer) | 0 | Default to ANSI code page. |
CP_MACCP (integer) | 2 | Macintosh code page. |
CP_OEMCP (integer) | 1 | Default to OEM code page. |
CP_UTF7 (integer) | 65000 | Unicode (UTF-7). |
CP_UTF8 (integer) | 65001 | Unicode (UTF-8). |
CP_SYMBOL (integer) | 42 | SYMBOL translations. |
CP_THREAD_ACP (integer) | 3 | Current thread's ANSI code page |
VARCMP_LT (integer) | 0 | The left bstr is less than right bstr. |
VARCMP_EQ (integer) | 1 | The two parameters are equal. |
VARCMP_GT (integer) | 2 | The left bstr is greater than right bstr. |
VARCMP_NULL (integer) | 3 | Either expression is NULL. |
NORM_IGNORECASE (integer) | 1 | Ignore case sensitivity. |
NORM_IGNORENONSPACE (integer) | 2 | Ignore nonspacing characters. |
NORM_IGNORESYMBOLS (integer) | 4 | Ignore symbols. |
NORM_IGNOREWIDTH (integer) | 131072 | Ignore string width. |
NORM_IGNOREKANATYPE (integer) | 65536 | Ignore Kana type. |
NORM_IGNOREKASHIDA (integer) | 262144 | Ignore Arabic kashida characters. | Availability is dependent upon under lying library.
DISP_E_DIVBYZERO (integer) | -2147352558 | A return error that indicates a divide by zero error. | As of PHP 7.0.0, the value is 2147614738 on x64.
DISP_E_OVERFLOW (integer) | -2147352566 | An error that indicates that a value could not be coerced to its expected representation. | As of PHP 7.0.0, the value is 2147614730 on x64.
DISP_E_BADINDEX (integer) | -2147352565 | An error that indicates that an array index does not exist. | As of PHP 7.0.0, the value is 2147614731 on x64.
MK_E_UNAVAILABLE (integer) | -2147221021 | iMoniker COM status code, return on errors where the function call failed due to unavailability. | As of PHP 7.0.0, the value is 2147746275 on x64.


Errors and error handling

This extension will throw instances of the class com_exception whenever there is a potentially fatal error reported by COM. All COM exceptions have a well-defined code property that corresponds to the HRESULT return value from the various COM operations. You may use this code to make programmatic decisions on how to handle the exception.


  • « Errors and error handling
  • For Each »
  • PHP Manual
  • COM
  • Examples

Examples

Table of Contents

  • For Each
  • Arrays and Array-style COM properties


For Each

You may use PHP's own foreach statement to iterate over the contents of a standard COM/OLE IEnumVariant. In layman's terms, this means that you can use foreach in places where you would have used For Each in VB/ASP code.

Example #1 For Each in ASP

<%
Set domainObject = GetObject("WinNT://Domain")
For Each obj in domainObject
  Response.Write obj.Name & "<br />"
Next
%>

Example #2 foreach in PHP

<?php
$domainObject = new COM("WinNT://Domain");
foreach ($domainObject as $obj) {
   echo $obj->Name . "<br />";
}
?>


Arrays and Array-style COM properties

Many COM objects expose their properties as arrays, or using array-style access.

You can:

  • Access multi-dimensional arrays, or COM properties that require multiple parameters using PHP array syntax. You can also write or set properties using this technique.

  • Iterate SafeArrays ("true" arrays) using the foreach control structure. This works because SafeArrays include information about their size. If an array-style property implements IEnumVariant then you can also use foreach for that property too; take a look at For Each for more information on this topic.


The COM class

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

Introduction

The COM class allows you to instantiate an OLE compatible COM object and call its methods and access its properties.

Class synopsis

COM extends VARIANT {
/* Methods */
__construct ( string $module_name [, mixed $server_name = NULL [, int $codepage = CP_ACP [, string $typelib ]]] )
}

Overloaded Methods

The returned object is an overloaded object, which means that PHP does not see any fixed methods as it does with regular classes; instead, any property or method accesses are passed through to COM.

PHP will automatically detect methods that accept parameters by reference, and will automatically convert regular PHP variables to a form that can be passed by reference. This means that you can call the method very naturally; you needn't go to any extra effort in your code.

COM examples

Example #1 COM example (1)

<?php
// starting word
$word = new COM("word.application") or die("Unable to instantiate Word");
echo "Loaded Word, version {$word->Version}\n";

//bring it to front
$word->Visible = 1;

//open an empty document
$word->Documents->Add();

//do some weird stuff
$word->Selection->TypeText("This is a test...");
$word->Documents[1]->SaveAs("Useless test.doc");

//closing word
$word->Quit();

//free the object
$word = null;
?>

Example #2 COM example (2)

<?php

$conn = new COM("ADODB.Connection") or die("Cannot start ADO");
$conn->Open("Provider=SQLOLEDB; Data Source=localhost;
Initial Catalog=database; User ID=user; Password=password");

$rs = $conn->Execute("SELECT * FROM sometable");    // Recordset

$num_columns = $rs->Fields->Count();
echo $num_columns . "\n";

for ($i=0; $i < $num_columns; $i++) {
    $fld[$i] = $rs->Fields($i);
}

$rowcount = 0;
while (!$rs->EOF) {
    for ($i=0; $i < $num_columns; $i++) {
        echo $fld[$i]->value . "\t";
    }
    echo "\n";
    $rowcount++;            // increments rowcount
    $rs->MoveNext();
}

$rs->Close();
$conn->Close();

$rs = null;
$conn = null;

?>

Table of Contents

  • COM::__construct — COM class constructor


COM class constructor

  • « COM
  • DOTNET »
  • PHP Manual
  • COM
  • COM class constructor

COM::__construct

(PHP 4 > 4.1.0, PHP 5, PHP 7)

COM::__construct — COM class constructor

Description

COM::__construct ( string $module_name [, mixed $server_name = NULL [, int $codepage = CP_ACP [, string $typelib ]]] )

Constructs a new COM object.

Parameters

module_name
Can be a ProgID, Class ID or Moniker that names the component to load. A ProgID is typically the application or DLL name, followed by a period, followed by the object name. e.g: Word.Application. A Class ID is the UUID that uniquely identifies a given class. A Moniker is a special form of naming, similar in concept to a URL scheme, that identifies a resource and specifies how it should be loaded. As an example, you could load up Word and get an object representing a word document by specifying the full path to the word document as the module name, or you can use LDAP: as a moniker to use the ADSI interface to LDAP.
server_name
The name of the DCOM server on which the component should be loaded and run. If NULL, the object is run using the default for the application. The default is typically to run it on the local machine, although the administrator might have configured the application to launch on a different machine. If you specify a non-NULL value for server, PHP will refuse to load the object unless the configuration option is set to TRUE.

If server_name is an array, it should contain the following elements (case sensitive!). Note that they are all optional (although you need to specify both Username and Password together); if you omit the Server setting, the default server will be used (as mentioned above), and the instantiation of the object will not be affected by the directive.

DCOM server name
key | type | description
Server | string | The name of the server.
Username | string | The username to connect as.
Password | string | The password for Username.
Flags | integer | One or more of the following constants, logically OR'd together: CLSCTX_INPROC_SERVER, CLSCTX_INPROC_HANDLER, CLSCTX_LOCAL_SERVER, CLSCTX_REMOTE_SERVER, CLSCTX_SERVER and CLSCTX_ALL. The default value if not specified here is CLSCTX_SERVER if you also omit Server, or CLSCTX_REMOTE_SERVER if you do specify a server. You should consult the Microsoft documentation for CoCreateInstance for more information on the meaning of these constants; you will typically never have to use them.

codepage
Specifies the codepage that is used to convert strings to unicode-strings and vice versa. The conversion is applied whenever a PHP string is passed as a parameter or returned from a method of this COM object. The code page is sticky, which means that it will propagate to objects and variants returned from the object. Possible values are CP_ACP (use system default ANSI code page - the default if this parameter is omitted), CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP (use codepage/locale set for the current executing thread), CP_UTF7 and CP_UTF8. You may also use the number for a given codepage; consult the Microsoft documentation for more details on codepages and their numeric values.


The DOTNET class

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

Introduction

The DOTNET class allows you to instantiate a class from a .Net assembly and call its methods and access its properties, if the class and the methods and properties are » visible to COM.

Note:

You need to install the .Net runtime on your web server to take advantage of this feature.

Class synopsis

DOTNET extends VARIANT {
/* Methods */
__construct ( string $assembly_name , string $class_name [, int $codepage = CP_ACP ] )
}

Overloaded Methods

The returned object is an overloaded object, which means that PHP does not see any fixed methods as it does with regular classes; instead, any property or method accesses are passed through to COM and from there to DOTNET. In other words, the .Net object is mapped through the COM interoperability layer provided by the .Net runtime.

Once you have created a DOTNET object, PHP treats it identically to any other COM object; all the same rules apply.

DOTNET examples

Example #1 DOTNET example

<?php
$stack = new DOTNET("mscorlib", "System.Collections.Stack");
$stack->Push(".Net");
$stack->Push("Hello ");
echo $stack->Pop() . $stack->Pop();
?>

Table of Contents

  • DOTNET::__construct — DOTNET class constructor


DOTNET class constructor

  • « DOTNET
  • VARIANT »
  • PHP Manual
  • DOTNET
  • DOTNET class constructor

DOTNET::__construct

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

DOTNET::__construct — DOTNET class constructor

Description

DOTNET::__construct ( string $assembly_name , string $class_name [, int $codepage = CP_ACP ] )

Constructs a new DOTNET object.

Parameters

assembly_name
Specifies which assembly should be loaded.
class_name
Specifices which class in that assembly to instantiate.
codepage
Codepage to use for unicode string transformations; see the COM class for more details on code pages.


VARIANT class

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

Introduction

The VARIANT is COM's equivalent of the PHP zval; it is a structure that can contain a value with a range of different possible types. The VARIANT class provided by the COM extension allows you to have more control over the way that PHP passes values to and from COM.

Class synopsis

VARIANT {
/* Methods */
__construct ([ mixed $value = NULL [, int $type = VT_EMPTY [, int $codepage = CP_ACP ]]] )
}

VARIANT examples

Example #1 Variant example

<?php
$v = new VARIANT(42);
print "The type is " . variant_get_type($v) . "<br/>";
print "The value is " . $v . "<br/>";
?>

Note:

When returning a value or fetching a variant property, the variant is converted to a PHP value only when there is a direct mapping between the types that would not result in a loss of information. In all other cases, the result is returned as an instance of the VARIANT class. You can force PHP to convert or evaluate the variant as a PHP native type by using a casting operator explicitly, or implicitly casting to a string by printing it. You may use the wide range of variant functions to perform arithmetic operations on variants without forcing a conversion or risking a loss of data.

See also variant_get_type().

Table of Contents

  • VARIANT::__construct — VARIANT class constructor


VARIANT class constructor

  • « VARIANT
  • com_exception »
  • PHP Manual
  • VARIANT
  • VARIANT class constructor

VARIANT::__construct

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

VARIANT::__construct — VARIANT class constructor

Description

VARIANT::__construct ([ mixed $value = NULL [, int $type = VT_EMPTY [, int $codepage = CP_ACP ]]] )

Constructs a new VARIANT object.

Parameters

value
Initial value. If omitted, or set to NULL an VT_EMPTY object is created.
type
Specifies the content type of the VARIANT object. Possible values are one of the VT_XXX Predefined Constants. PHP can detect parameters passed by reference automatically; they do not even need to be passed as VARIANT objects. Consult the MSDN library for additional information on the VARIANT type.
codepage
Specifies the codepage that is used to convert strings to unicode. See the parameter of the same name in the COM class for more information.


The com_exception class

(PHP 5, PHP 7)

Introduction

Class synopsis

com_exception extends Exception implements Throwable {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


COM Functions

See Also

For further information on COM read the » COM specification. You might find some additional useful information in our FAQ for PHP and COM. If you're thinking of using MS Office applications on the server side, you should read the information here: » Considerations for Server-Side Automation of Office.

Table of Contents

  • com_create_guid — Generate a globally unique identifier (GUID)
  • com_event_sink — Connect events from a COM object to a PHP object
  • com_get_active_object — Returns a handle to an already running instance of a COM object
  • com_load_typelib — Loads a Typelib
  • com_message_pump — Process COM messages, sleeping for up to timeoutms milliseconds
  • com_print_typeinfo — Print out a PHP class definition for a dispatchable interface
  • variant_abs — Returns the absolute value of a variant
  • variant_add — "Adds" two variant values together and returns the result
  • variant_and — Performs a bitwise AND operation between two variants
  • variant_cast — Convert a variant into a new variant object of another type
  • variant_cat — Concatenates two variant values together and returns the result
  • variant_cmp — Compares two variants
  • variant_date_from_timestamp — Returns a variant date representation of a Unix timestamp
  • variant_date_to_timestamp — Converts a variant date/time value to Unix timestamp
  • variant_div — Returns the result from dividing two variants
  • variant_eqv — Performs a bitwise equivalence on two variants
  • variant_fix — Returns the integer portion of a variant
  • variant_get_type — Returns the type of a variant object
  • variant_idiv — Converts variants to integers and then returns the result from dividing them
  • variant_imp — Performs a bitwise implication on two variants
  • variant_int — Returns the integer portion of a variant
  • variant_mod — Divides two variants and returns only the remainder
  • variant_mul — Multiplies the values of the two variants
  • variant_neg — Performs logical negation on a variant
  • variant_not — Performs bitwise not negation on a variant
  • variant_or — Performs a logical disjunction on two variants
  • variant_pow — Returns the result of performing the power function with two variants
  • variant_round — Rounds a variant to the specified number of decimal places
  • variant_set_type — Convert a variant into another type "in-place"
  • variant_set — Assigns a new value for a variant object
  • variant_sub — Subtracts the value of the right variant from the left variant value
  • variant_xor — Performs a logical exclusion on two variants


Generate a globally unique identifier (GUID)

  • « COM Functions
  • com_event_sink »
  • PHP Manual
  • COM Functions
  • Generate a globally unique identifier (GUID)

com_create_guid

(PHP 5, PHP 7)

com_create_guid — Generate a globally unique identifier (GUID)

Description

com_create_guid ( void ) : string

Generates a Globally Unique Identifier (GUID).

A GUID is generated in the same way as DCE UUID's, except that the Microsoft convention is to enclose a GUID in curly braces.

Return Values

Returns the GUID as a string.

See Also

  • uuid_create() in the PECL uuid extension


Connect events from a COM object to a PHP object

  • « com_create_guid
  • com_get_active_object »
  • PHP Manual
  • COM Functions
  • Connect events from a COM object to a PHP object

com_event_sink

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

com_event_sink — Connect events from a COM object to a PHP object

Description

com_event_sink ( variant $comobject , object $sinkobject [, mixed $sinkinterface ] ) : bool

Instructs COM to sink events generated by comobject into the PHP object sinkobject.

Be careful how you use this feature; if you are doing something similar to the example below, then it doesn't really make sense to run it in a web server context.

Parameters

comobject

sinkobject

sinkobject should be an instance of a class with methods named after those of the desired dispinterface; you may use com_print_typeinfo() to help generate a template class for this purpose.

sinkinterface

PHP will attempt to use the default dispinterface type specified by the typelibrary associated with comobject, but you may override this choice by setting sinkinterface to the name of the dispinterface that you want to use.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 COM event sink example

<?php
class IEEventSinker {
    var $terminated = false;

   function ProgressChange($progress, $progressmax) {
      echo "Download progress: $progress / $progressmax\n";
    }

    function DocumentComplete(&$dom, $url) {
      echo "Document $url complete\n";
    }

    function OnQuit() {
      echo "Quit!\n";
      $this->terminated = true;
    }
}
$ie = new COM("InternetExplorer.Application");
// note that you don't need the & for PHP 5!
$sink = new IEEventSinker();
com_event_sink($ie, $sink, "DWebBrowserEvents2");
$ie->Visible = true;
$ie->Navigate("http://www.example.org");
while(!$sink->terminated) {
  com_message_pump(4000);
}
$ie = null;
?>

See Also

  • com_print_typeinfo() - Print out a PHP class definition for a dispatchable interface
  • com_message_pump() - Process COM messages, sleeping for up to timeoutms milliseconds


Returns a handle to an already running instance of a COM object

  • « com_event_sink
  • com_load_typelib »
  • PHP Manual
  • COM Functions
  • Returns a handle to an already running instance of a COM object

com_get_active_object

(PHP 5, PHP 7)

com_get_active_object — Returns a handle to an already running instance of a COM object

Description

com_get_active_object ( string $progid [, int $code_page ] ) : variant

com_get_active_object() is similar to creating a new instance of a COM object, except that it will only return an object to your script if the object is already running. OLE applications use something known as the "Running Object Table" to allow well-known applications to be launched only once; this function exposes the COM library function GetActiveObject() to get a handle on a running instance.

Parameters

progid

progid must be either the ProgID or CLSID for the object that you want to access (for example Word.Application).

code_page

Acts in precisely the same way that it does for the COM class.

Return Values

If the requested object is running, it will be returned to your script just like any other COM object.

Errors/Exceptions

There are a variety of reasons why this function might fail, the most common being that the object is not already running. In that situation, the exception error code will be MK_E_UNAVAILABLE; you can use the getCode method of the exception object to check the exception code.

Notes

Warning

Using com_get_active_object() in a web server context is not always a smart idea. Most COM/OLE applications are not designed to handle more than one client concurrently, even (or especially!) Microsoft Office. You should read » Considerations for Server-Side Automation of Office for more information on the general issues involved.


Loads a Typelib

  • « com_get_active_object
  • com_message_pump »
  • PHP Manual
  • COM Functions
  • Loads a Typelib

com_load_typelib

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

com_load_typelib — Loads a Typelib

Description

com_load_typelib ( string $typelib_name [, bool $case_sensitive = TRUE ] ) : bool

Loads a type-library and registers its constants in the engine, as though they were defined using define().

Note that it is much more efficient to use the configuration setting to pre-load and register the constants, although not so flexible.

If you have turned on , then PHP will attempt to automatically register the constants associated with a COM object when you instantiate it. This depends on the interfaces provided by the COM object itself, and may not always be possible.

Parameters

typelib_name

typelib_name can be one of the following:

  • The filename of a .tlb file or the executable module that contains the type library.

  • The type library GUID, followed by its version number, for example {00000200-0000-0010-8000-00AA006D2EA4},2,0.

  • The type library name, e.g. Microsoft OLE DB ActiveX Data Objects 1.0 Library.

PHP will attempt to resolve the type library in this order, as the process gets more and more expensive as you progress down the list; searching for the type library by name is handled by physically enumerating the registry until we find a match.

case_sensitive

The case_sensitive behaves inversely to the parameter $case_insensitive in the define() function.

Return Values

Returns TRUE on success or FALSE on failure.


Process COM messages, sleeping for up to timeoutms milliseconds

  • « com_load_typelib
  • com_print_typeinfo »
  • PHP Manual
  • COM Functions
  • Process COM messages, sleeping for up to timeoutms milliseconds

com_message_pump

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

com_message_pump — Process COM messages, sleeping for up to timeoutms milliseconds

Description

com_message_pump ([ int $timeoutms = 0 ] ) : bool

This function will sleep for up to timeoutms milliseconds, or until a message arrives in the queue.

The purpose of this function is to route COM calls between apartments and handle various synchronization issues. This allows your script to wait efficiently for events to be triggered, while still handling other events or running other code in the background. You should use it in a loop, as demonstrated by the example in the com_event_sink() function, until you are finished using event bound COM objects.

Parameters

timeoutms

The timeout, in milliseconds.

If you do not specify a value for timeoutms, then 0 will be assumed. A 0 value means that no waiting will be performed; if there are messages pending they will be dispatched as before; if there are no messages pending, the function will return FALSE immediately without sleeping.

Return Values

If a message or messages arrives before the timeout, they will be dispatched, and the function will return TRUE. If the timeout occurs and no messages were processed, the return value will be FALSE.


Print out a PHP class definition for a dispatchable interface

  • « com_message_pump
  • variant_abs »
  • PHP Manual
  • COM Functions
  • Print out a PHP class definition for a dispatchable interface

com_print_typeinfo

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

com_print_typeinfo — Print out a PHP class definition for a dispatchable interface

Description

com_print_typeinfo ( object $comobject [, string $dispinterface = NULL [, bool $wantsink = FALSE ]] ) : bool

The purpose of this function is to help generate a skeleton class for use as an event sink. You may also use it to generate a dump of any COM object, provided that it supports enough of the introspection interfaces, and that you know the name of the interface you want to display.

Parameters

comobject

comobject should be either an instance of a COM object, or be the name of a typelibrary (which will be resolved according to the rules set out in com_load_typelib()).

dispinterface

The name of an IDispatch descendant interface that you want to display.

wantsink

If set to TRUE, the corresponding sink interface will be displayed instead.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • com_event_sink() - Connect events from a COM object to a PHP object
  • com_load_typelib() - Loads a Typelib


Returns the absolute value of a variant

  • « com_print_typeinfo
  • variant_add »
  • PHP Manual
  • COM Functions
  • Returns the absolute value of a variant

variant_abs

(PHP 5, PHP 7)

variant_abs — Returns the absolute value of a variant

Description

variant_abs ( mixed $val ) : variant

Returns the absolute value of a variant.

Parameters

val

The variant.

Note:

As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

Return Values

Returns the absolute value of val.

Errors/Exceptions

Throws a com_exception on failure.

See Also

  • abs() - Absolute value


"Adds" two variant values together and returns the result

  • « variant_abs
  • variant_and »
  • PHP Manual
  • COM Functions
  • "Adds" two variant values together and returns the result

variant_add

(PHP 5, PHP 7)

variant_add — "Adds" two variant values together and returns the result

Description

variant_add ( mixed $left , mixed $right ) : variant

Adds left to right using the following rules (taken from the MSDN library), which correspond to those of Visual Basic:

Variant Addition Rules
If | Then
Both expressions are of the string type | Concatenation
One expression is a string type and the other a character | Addition
One expression is numeric and the other is a string | Addition
Both expressions are numeric | Addition
Either expression is NULL | NULL is returned
Both expressions are empty | Integer subtype is returned

Parameters

left

The left operand.

right

The right operand.

Note:

As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

Return Values

Returns the result.

Errors/Exceptions

Throws a com_exception on failure.

See Also

  • variant_sub() - Subtracts the value of the right variant from the left variant value


Performs a bitwise AND operation between two variants

  • « variant_add
  • variant_cast »
  • PHP Manual
  • COM Functions
  • Performs a bitwise AND operation between two variants

variant_and

(PHP 5, PHP 7)

variant_and — Performs a bitwise AND operation between two variants

Description

variant_and ( mixed $left , mixed $right ) : variant

Performs a bitwise AND operation. Note that this is slightly different from a regular AND operation.

Parameters

left

The left operand.

right

The right operand.

Note:

As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

Return Values

Variant AND Rules
If left is | If right is | then the result is
TRUE | TRUE | TRUE
TRUE | FALSE | FALSE
TRUE | NULL | NULL
FALSE | TRUE | FALSE
FALSE | FALSE | FALSE
FALSE | NULL | FALSE
NULL | TRUE | NULL
NULL | FALSE | FALSE
NULL | NULL | NULL

Errors/Exceptions

Throws a com_exception on failure.

See Also

  • variant_or() - Performs a logical disjunction on two variants


Convert a variant into a new variant object of another type

  • « variant_and
  • variant_cat »
  • PHP Manual
  • COM Functions
  • Convert a variant into a new variant object of another type

variant_cast

(PHP 5, PHP 7)

variant_cast — Convert a variant into a new variant object of another type

Description

variant_cast ( variant $variant , int $type ) : variant

This function makes a copy of variant and then performs a variant cast operation to force the copy to have the type given by type.

This function wraps VariantChangeType() in the COM library; consult MSDN for more information.

Parameters

variant

The variant.

type

type should be one of the VT_XXX constants.

Return Values

Returns a variant of given type.

See Also

  • variant_set_type() - Convert a variant into another type "in-place"


Concatenates two variant values together and returns the result

  • « variant_cast
  • variant_cmp »
  • PHP Manual
  • COM Functions
  • Concatenates two variant values together and returns the result

variant_cat

(PHP 5, PHP 7)

variant_cat — Concatenates two variant values together and returns the result

Description

variant_cat ( mixed $left , mixed $right ) : variant

Concatenates left with right and returns the result.

This function is notionally equivalent to $left . $right.

Parameters

left

The left operand.

right

The right operand.

Note:

As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

Return Values

Returns the result of the concatenation.

Errors/Exceptions

Throws a com_exception on failure.

See Also

  • String Operators for the string concatenation operator


Compares two variants

  • « variant_cat
  • variant_date_from_timestamp »
  • PHP Manual
  • COM Functions
  • Compares two variants

variant_cmp

(PHP 5, PHP 7)

variant_cmp — Compares two variants

Description

variant_cmp ( mixed $left , mixed $right [, int $lcid [, int $flags ]] ) : int

Compares left with right.

This function will only compare scalar values, not arrays or variant records.

Parameters

left

The left operand.

right

The right operand.

lcid

A valid Locale Identifier to use when comparing strings (this affects string collation).

flags

flags can be one or more of the following values OR'd together, and affects string comparisons:

Variant Comparision Flags
value | meaning
NORM_IGNORECASE | Compare case insensitively
NORM_IGNORENONSPACE | Ignore nonspacing characters
NORM_IGNORESYMBOLS | Ignore symbols
NORM_IGNOREWIDTH | Ignore string width
NORM_IGNOREKANATYPE | Ignore Kana type
NORM_IGNOREKASHIDA | Ignore Arabic kashida characters

Note:

As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

Return Values

Returns one of the following:

Variant Comparision Results
value | meaning
VARCMP_LT | left is less than right
VARCMP_EQ | left is equal to right
VARCMP_GT | left is greater than right
VARCMP_NULL | Either left, right or both are NULL


Returns a variant date representation of a Unix timestamp

  • « variant_cmp
  • variant_date_to_timestamp »
  • PHP Manual
  • COM Functions
  • Returns a variant date representation of a Unix timestamp

variant_date_from_timestamp

(PHP 5, PHP 7)

variant_date_from_timestamp — Returns a variant date representation of a Unix timestamp

Description

variant_date_from_timestamp ( int $timestamp ) : variant

Converts timestamp from a unix timestamp value into a variant of type VT_DATE. This allows easier interopability between the unix-ish parts of PHP and COM.

Parameters

timestamp

A unix timestamp.

Return Values

Returns a VT_DATE variant.

See Also

  • variant_date_to_timestamp() - Converts a variant date/time value to Unix timestamp
  • mktime() - Get Unix timestamp for a date
  • time() - Return current Unix timestamp


Converts a variant date/time value to Unix timestamp

  • « variant_date_from_timestamp
  • variant_div »
  • PHP Manual
  • COM Functions
  • Converts a variant date/time value to Unix timestamp

variant_date_to_timestamp

(PHP 5, PHP 7)

variant_date_to_timestamp — Converts a variant date/time value to Unix timestamp

Description

variant_date_to_timestamp ( variant $variant ) : int

Converts variant from a VT_DATE (or similar) value into a Unix timestamp. This allows easier interopability between the Unix-ish parts of PHP and COM.

Parameters

variant

The variant.

Return Values

Returns a unix timestamp.

See Also

  • variant_date_from_timestamp() - Returns a variant date representation of a Unix timestamp
  • date() - Format a local time/date
  • strftime() - Format a local time/date according to locale settings


Returns the result from dividing two variants

  • « variant_date_to_timestamp
  • variant_eqv »
  • PHP Manual
  • COM Functions
  • Returns the result from dividing two variants

variant_div

(PHP 5, PHP 7)

variant_div — Returns the result from dividing two variants

Description

variant_div ( mixed $left , mixed $right ) : variant

Divides left by right and returns the result.

Parameters

left

The left operand.

right

The right operand.

Note:

As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

Return Values

Variant Division Rules
If | Then
Both expressions are of the string, date, character, boolean type | Double is returned
One expression is a string type and the other a character | Division and a double is returned
One expression is numeric and the other is a string | Division and a double is returned.
Both expressions are numeric | Division and a double is returned
Either expression is NULL | NULL is returned
right is empty and left is anything but empty | A com_exception with code DISP_E_DIVBYZERO is thrown
left is empty and right is anything but empty. | 0 as type double is returned
Both expressions are empty | A com_exception with code DISP_E_OVERFLOW is thrown

Errors/Exceptions

Throws a com_exception on failure.

See Also

  • variant_idiv() - Converts variants to integers and then returns the result from dividing them


Performs a bitwise equivalence on two variants

  • « variant_div
  • variant_fix »
  • PHP Manual
  • COM Functions
  • Performs a bitwise equivalence on two variants

variant_eqv

(PHP 5, PHP 7)

variant_eqv — Performs a bitwise equivalence on two variants

Description

variant_eqv ( mixed $left , mixed $right ) : variant

Performs a bitwise equivalence on two variants.

Parameters

left

The left operand.

right

The right operand.

Note:

As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

Return Values

If each bit in left is equal to the corresponding bit in right then TRUE is returned, otherwise FALSE is returned.

Errors/Exceptions

Throws a com_exception on failure.


Returns the integer portion of a variant

  • « variant_eqv
  • variant_get_type »
  • PHP Manual
  • COM Functions
  • Returns the integer portion of a variant

variant_fix

(PHP 5, PHP 7)

variant_fix — Returns the integer portion of a variant

Description

variant_fix ( mixed $variant ) : variant

Gets the integer portion of a variant.

Parameters

variant

The variant.

Note:

As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

Return Values

If variant is negative, then the first negative integer greater than or equal to the variant is returned, otherwise returns the integer portion of the value of variant.

Errors/Exceptions

Throws a com_exception on failure.

Notes

Warning

This documentation is based on the MSDN documentation; it appears that this function is either the same as variant_int(), or that there is an error in the MSDN documentation.

See Also

  • variant_int() - Returns the integer portion of a variant
  • variant_round() - Rounds a variant to the specified number of decimal places
  • floor() - Round fractions down
  • ceil() - Round fractions up
  • round() - Rounds a float


Returns the type of a variant object

  • « variant_fix
  • variant_idiv »
  • PHP Manual
  • COM Functions
  • Returns the type of a variant object

variant_get_type

(PHP 5, PHP 7)

variant_get_type — Returns the type of a variant object

Description

variant_get_type ( variant $variant ) : int

Returns the type of a variant object.

Parameters

variant

The variant object.

Return Values

This function returns an integer value that indicates the type of variant, which can be an instance of COM, DOTNET or VARIANT classes. The return value can be compared to one of the VT_XXX constants.

The return value for COM and DOTNET objects will usually be VT_DISPATCH; the only reason this function works for those classes is because COM and DOTNET are descendants of VARIANT.

See Also

  • variant_set_type() - Convert a variant into another type "in-place"


Converts variants to integers and then returns the result from dividing them

  • « variant_get_type
  • variant_imp »
  • PHP Manual
  • COM Functions
  • Converts variants to integers and then returns the result from dividing them

variant_idiv

(PHP 5, PHP 7)

variant_idiv — Converts variants to integers and then returns the result from dividing them

Description

variant_idiv ( mixed $left , mixed $right ) : variant

Converts left and right to integer values, and then performs integer division.

Parameters

left

The left operand.

right

The right operand.

Note:

As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

Return Values

Variant Integer Division Rules
If | Then
Both expressions are of the string, date, character, boolean type | Division and integer is returned
One expression is a string type and the other a character | Division
One expression is numeric and the other is a string | Division
Both expressions are numeric | Division
Either expression is NULL | NULL is returned
Both expressions are empty | A com_exception with code DISP_E_DIVBYZERO is thrown

Errors/Exceptions

Throws a com_exception on failure.

See Also

  • variant_div() - Returns the result from dividing two variants


Performs a bitwise implication on two variants

  • « variant_idiv
  • variant_int »
  • PHP Manual
  • COM Functions
  • Performs a bitwise implication on two variants

variant_imp

(PHP 5, PHP 7)

variant_imp — Performs a bitwise implication on two variants

Description

variant_imp ( mixed $left , mixed $right ) : variant

Performs a bitwise implication operation.

Parameters

left

The left operand.

right

The right operand.

Note:

As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

Return Values

Variant Implication Table
If left is | If right is | then the result is
TRUE | TRUE | TRUE
TRUE | FALSE | FALSE
TRUE | NULL | TRUE
FALSE | TRUE | TRUE
FALSE | FALSE | TRUE
FALSE | NULL | TRUE
NULL | TRUE | TRUE
NULL | FALSE | NULL
NULL | NULL | NULL

Errors/Exceptions

Throws a com_exception on failure.


Returns the integer portion of a variant

  • « variant_imp
  • variant_mod »
  • PHP Manual
  • COM Functions
  • Returns the integer portion of a variant

variant_int

(PHP 5, PHP 7)

variant_int — Returns the integer portion of a variant

Description

variant_int ( mixed $variant ) : variant

Gets the integer portion of a variant.

Parameters

variant

The variant.

Note:

As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

Return Values

If variant is negative, then the first negative integer greater than or equal to the variant is returned, otherwise returns the integer portion of the value of variant.

Errors/Exceptions

Throws a com_exception on failure.

See Also

  • variant_fix() - Returns the integer portion of a variant
  • variant_round() - Rounds a variant to the specified number of decimal places
  • floor() - Round fractions down
  • ceil() - Round fractions up
  • round() - Rounds a float


Divides two variants and returns only the remainder

  • « variant_int
  • variant_mul »
  • PHP Manual
  • COM Functions
  • Divides two variants and returns only the remainder

variant_mod

(PHP 5, PHP 7)

variant_mod — Divides two variants and returns only the remainder

Description

variant_mod ( mixed $left , mixed $right ) : variant

Divides left by right and returns the remainder.

Parameters

left

The left operand.

right

The right operand.

Note:

As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

Return Values

Returns the remainder of the division.

Errors/Exceptions

Throws a com_exception on failure.

See Also

  • variant_div() - Returns the result from dividing two variants
  • variant_idiv() - Converts variants to integers and then returns the result from dividing them


Multiplies the values of the two variants

  • « variant_mod
  • variant_neg »
  • PHP Manual
  • COM Functions
  • Multiplies the values of the two variants

variant_mul

(PHP 5, PHP 7)

variant_mul — Multiplies the values of the two variants

Description

variant_mul ( mixed $left , mixed $right ) : variant

Multiplies left by right.

Parameters

left

The left operand.

right

The right operand.

Boolean values are converted to -1 for FALSE and 0 for TRUE.

Note:

As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

Return Values

Variant Multiplication Rules
If | Then
Both expressions are of the string, date, character, boolean type | Multiplication
One expression is a string type and the other a character | Multiplication
One expression is numeric and the other is a string | Multiplication
Both expressions are numeric | Multiplication
Either expression is NULL | NULL is returned
Both expressions are empty | Empty string is returned

Errors/Exceptions

Throws a com_exception on failure.

See Also

  • variant_div() - Returns the result from dividing two variants
  • variant_idiv() - Converts variants to integers and then returns the result from dividing them


Performs logical negation on a variant

  • « variant_mul
  • variant_not »
  • PHP Manual
  • COM Functions
  • Performs logical negation on a variant

variant_neg

(PHP 5, PHP 7)

variant_neg — Performs logical negation on a variant

Description

variant_neg ( mixed $variant ) : variant

Performs logical negation of variant.

Parameters

variant

The variant.

Note:

As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

Return Values

Returns the result of the logical negation.

Errors/Exceptions

Throws a com_exception on failure.


Performs bitwise not negation on a variant

  • « variant_neg
  • variant_or »
  • PHP Manual
  • COM Functions
  • Performs bitwise not negation on a variant

variant_not

(PHP 5, PHP 7)

variant_not — Performs bitwise not negation on a variant

Description

variant_not ( mixed $variant ) : variant

Performs bitwise not negation on variant and returns the result.

Parameters

variant

The variant.

Note:

As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

Return Values

Returns the bitwise not negation. If variant is NULL, the result will also be NULL.

Errors/Exceptions

Throws a com_exception on failure.


Performs a logical disjunction on two variants

  • « variant_not
  • variant_pow »
  • PHP Manual
  • COM Functions
  • Performs a logical disjunction on two variants

variant_or

(PHP 5, PHP 7)

variant_or — Performs a logical disjunction on two variants

Description

variant_or ( mixed $left , mixed $right ) : variant

Performs a bitwise OR operation. Note that this is slightly different from a regular OR operation.

Parameters

left

The left operand.

right

The right operand.

Note:

As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

Return Values

Variant OR Rules
If left is | If right is | then the result is
TRUE | TRUE | TRUE
TRUE | FALSE | TRUE
TRUE | NULL | TRUE
FALSE | TRUE | TRUE
FALSE | FALSE | FALSE
FALSE | NULL | NULL
NULL | TRUE | TRUE
NULL | FALSE | NULL
NULL | NULL | NULL

Errors/Exceptions

Throws a com_exception on failure.

See Also

  • variant_and() - Performs a bitwise AND operation between two variants
  • variant_xor() - Performs a logical exclusion on two variants


Returns the result of performing the power function with two variants

  • « variant_or
  • variant_round »
  • PHP Manual
  • COM Functions
  • Returns the result of performing the power function with two variants

variant_pow

(PHP 5, PHP 7)

variant_pow — Returns the result of performing the power function with two variants

Description

variant_pow ( mixed $left , mixed $right ) : variant

Returns the result of left to the power of right.

Parameters

left

The left operand.

right

The right operand.

Note:

As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

Return Values

Returns the result of left to the power of right.

Errors/Exceptions

Throws a com_exception on failure.

See Also

  • pow() - Exponential expression


Rounds a variant to the specified number of decimal places

  • « variant_pow
  • variant_set_type »
  • PHP Manual
  • COM Functions
  • Rounds a variant to the specified number of decimal places

variant_round

(PHP 5, PHP 7)

variant_round — Rounds a variant to the specified number of decimal places

Description

variant_round ( mixed $variant , int $decimals ) : mixed

Returns the value of variant rounded to decimals decimal places.

Parameters

variant

The variant.

decimals

Number of decimal places.

Note:

As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

Return Values

Returns the rounded value.

See Also

  • round() - Rounds a float


Convert a variant into another type "in-place"

  • « variant_round
  • variant_set »
  • PHP Manual
  • COM Functions
  • Convert a variant into another type "in-place"

variant_set_type

(PHP 5, PHP 7)

variant_set_type — Convert a variant into another type "in-place"

Description

variant_set_type ( variant $variant , int $type ) : void

This function is similar to variant_cast() except that the variant is modified "in-place"; no new variant is created. The parameters for this function have identical meaning to those of variant_cast().

Parameters

variant

The variant.

type

Return Values

No value is returned.

See Also

  • variant_cast() - Convert a variant into a new variant object of another type
  • variant_get_type() - Returns the type of a variant object


Assigns a new value for a variant object

  • « variant_set_type
  • variant_sub »
  • PHP Manual
  • COM Functions
  • Assigns a new value for a variant object

variant_set

(PHP 5, PHP 7)

variant_set — Assigns a new value for a variant object

Description

variant_set ( variant $variant , mixed $value ) : void

Converts value to a variant and assigns it to the variant object; no new variant object is created, and the old value of variant is freed/released.

Parameters

variant

The variant.

value

Return Values

No value is returned.


Subtracts the value of the right variant from the left variant value

  • « variant_set
  • variant_xor »
  • PHP Manual
  • COM Functions
  • Subtracts the value of the right variant from the left variant value

variant_sub

(PHP 5, PHP 7)

variant_sub — Subtracts the value of the right variant from the left variant value

Description

variant_sub ( mixed $left , mixed $right ) : variant

Subtracts right from left.

Parameters

left

The left operand.

right

The right operand.

Note:

As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

Return Values

Variant Subtraction Rules
If | Then
Both expressions are of the string type | Subtraction
One expression is a string type and the other a character | Subtraction
One expression is numeric and the other is a string | Subtraction.
Both expressions are numeric | Subtraction
Either expression is NULL | NULL is returned
Both expressions are empty | Empty string is returned

Errors/Exceptions

Throws a com_exception on failure.

See Also

  • variant_add() - "Adds" two variant values together and returns the result


Performs a logical exclusion on two variants

  • « variant_sub
  • win32ps »
  • PHP Manual
  • COM Functions
  • Performs a logical exclusion on two variants

variant_xor

(PHP 5, PHP 7)

variant_xor — Performs a logical exclusion on two variants

Description

variant_xor ( mixed $left , mixed $right ) : variant

Performs a logical exclusion.

Parameters

left

The left operand.

right

The right operand.

Note:

As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.

The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.

Return Values

Variant XOR Rules
If left is | If right is | then the result is
TRUE | TRUE | FALSE
TRUE | FALSE | TRUE
FALSE | TRUE | TRUE
FALSE | FALSE | FALSE
NULL | NULL | NULL

Errors/Exceptions

Throws a com_exception on failure.

See Also

  • variant_or() - Performs a logical disjunction on two variants
  • variant_and() - Performs a bitwise AND operation between two variants


win32ps

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Win32ps examples
  • win32ps Functions
    • win32_ps_list_procs — List running processes
    • win32_ps_stat_mem — Stat memory utilization
    • win32_ps_stat_proc — Stat process


Introduction

The win32ps extension is a Windows specific extension that allows PHP retrieve statistics about process and memory utilization.


Requirements

Windows NT, Windows 2000, Windows XP or Windows Server 2003. Any version of Windows derived from Windows NT should be compatible.


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/win32ps.


  • « Resource Types
  • Examples »
  • PHP Manual
  • win32ps
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


  • « Predefined Constants
  • Win32ps examples »
  • PHP Manual
  • win32ps
  • Examples

Examples

Table of Contents

  • Win32ps examples


Win32ps examples

Example #1 Statistics about the current PHP process

<?php
print_r(win32_ps_stat_proc());
/*
    Array
    (
        [pid] => 936
        [exe] => D:\Daten\Source\php-5.1\Debug_TS\php.exe
        [mem] => Array
            (
                [page_fault_count] => 2062
                [peak_working_set_size] => 8396800
                [working_set_size] => 8396800
                [quota_peak_paged_pool_usage] => 32080
                [quota_paged_pool_usage] => 31876
                [quota_peak_non_paged_pool_usage] => 4240
                [quota_non_paged_pool_usage] => 3888
                [pagefile_usage] => 5865472
                [peak_pagefile_usage] => 5865472
            )

        [tms] => Array
            (
                [created] => 0.093
                [kernel] => 0.015
                [user] => 0.062
            )

    )
*/
?>

Example #2 Statistics about global memory utilization

<?php
print_r(win32_ps_stat_mem());
/*
    Array
    (
        [load] => 37
        [unit] => 1024
        [total_phys] => 1048096
        [avail_phys] => 649960
        [total_pagefile] => 2521368
        [avail_pagefile] => 2237940
        [total_virtual] => 2097024
        [avail_virtual] => 2057848
    )
*/
?>


win32ps Functions

Table of Contents

  • win32_ps_list_procs — List running processes
  • win32_ps_stat_mem — Stat memory utilization
  • win32_ps_stat_proc — Stat process


List running processes

  • « win32ps Functions
  • win32_ps_stat_mem »
  • PHP Manual
  • win32ps Functions
  • List running processes

win32_ps_list_procs

(PECL win32ps >= 1.0.1)

win32_ps_list_procs — List running processes

Description

win32_ps_list_procs ( void ) : array

Retrieves statistics about all running processes.

Return Values

Returns FALSE on failure, or an array consisting of process statistics like win32_ps_stat_proc() returns for all running processes on success.

See Also

  • win32_ps_stat_proc() - Stat process


Stat memory utilization

  • « win32_ps_list_procs
  • win32_ps_stat_proc »
  • PHP Manual
  • win32ps Functions
  • Stat memory utilization

win32_ps_stat_mem

(PECL win32ps >= 1.0.1)

win32_ps_stat_mem — Stat memory utilization

Description

win32_ps_stat_mem ( void ) : array

Retrieves statistics about the global memory utilization.

Return Values

Returns FALSE on failure, or an array consisting of the following information on success:

load

The current memory load in percent of physical memory.

unit

This is always 1024, and indicates that the following values are the count of 1024 bytes.

total_phys

The amount of total physical memory.

avail_phys

The amount of still available physical memory.

total_pagefile

The amount of total pageable memory (physical memory + paging file).

avail_pagefile

The amount of still available pageable memory (physical memory + paging file).

total_virtual

The amount of total virtual memory for a process.

avail_virtual

The amount of still available virtual memory for a process.


Stat process

  • « win32_ps_stat_mem
  • win32service »
  • PHP Manual
  • win32ps Functions
  • Stat process

win32_ps_stat_proc

(PECL win32ps >= 1.0.1)

win32_ps_stat_proc — Stat process

Description

win32_ps_stat_proc ([ int $pid = 0 ] ) : array

Retrieves statistics about the process with the process id pid.

Parameters

pid

The process id of the process to stat. If omitted, the id of the current process.

Return Values

Returns FALSE on failure, or an array consisting of the following information on success:

pid

The process id.

exe

The path to the executable image.

mem

An array containing information about the following memory utilization indicators: page_fault_count, peak_working_set_size, working_set_size, quota_peak_paged_pool_usage, quota_paged_pool_usage, quota_peak_non_paged_pool_usage, quota_non_paged_pool_usage, pagefile_usage and peak_pagefile_usage.

tms

An array containing information about the following CPU time utilization indicators: created, kernel and user.

See Also

  • win32_ps_list_procs() - List running processes


win32service

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
    • Security consideration
  • Predefined Constants
    • Win32Service Service Type Bitmasks
    • Win32Service Service Status Constants
    • Win32Service Service Control Message Constants
    • Win32Service Service Control Message Accepted Bitmasks
    • Win32Service Service Start Type Constants
    • Win32Service Service Error Control Constants
    • Win32Service Service Flag Constants
    • Win32 Error Codes
    • Win32 Base Priority Classes
    • Win32 Recovery action
    • Win32 Service informations
  • Examples
  • win32service Functions
    • win32_continue_service — Resumes a paused service
    • win32_create_service — Creates a new service entry in the SCM database
    • win32_delete_service — Deletes a service entry from the SCM database
    • win32_get_last_control_message — Returns the last control message that was sent to this service
    • win32_pause_service — Pauses a service
    • win32_query_service_status — Queries the status of a service
    • win32_send_custom_control — Send a custom control to the service
    • win32_set_service_exit_code — Define or return the exit code for the current running service
    • win32_set_service_exit_mode — Define or return the exit mode for the current running service
    • win32_set_service_status — Update the service status
    • win32_start_service_ctrl_dispatcher — Registers the script with the SCM, so that it can act as the service with the given name
    • win32_start_service — Starts a service
    • win32_stop_service — Stops a service


Introduction

The win32service extension is a Windows specific extension that allows PHP to communicate with the Service Control Manager to start, stop, register and unregister services, and even allows your PHP scripts to run as a service.


Installing/Configuring

Table of Contents

  • Requirements
  • Installation
  • Runtime Configuration
  • Resource Types
  • Security consideration


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/win32service


  • « Runtime Configuration
  • Security consideration »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

This extension has no resource types defined.


Security consideration

This extension needs administrator privileges for some actions such as create, delete, start, stop, pause and continue. This requirement can cause an elevation of privileges if the service control is available from the web interface or remote control.

You can set the ACL on the service after adding it into SCM to delegate the current administration tasks to an non administrator account or service account. For further instructions, see the » Microsoft Knowledge Base.


Predefined Constants

Table of Contents

  • Win32Service Service Type Bitmasks
  • Win32Service Service Status Constants
  • Win32Service Service Control Message Constants
  • Win32Service Service Control Message Accepted Bitmasks
  • Win32Service Service Start Type Constants
  • Win32Service Service Error Control Constants
  • Win32Service Service Flag Constants
  • Win32 Error Codes
  • Win32 Base Priority Classes
  • Win32 Recovery action
  • Win32 Service informations

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.


Win32Service Service Type Bitmasks

  • « Predefined Constants
  • Win32Service Service Status Constants »
  • PHP Manual
  • Predefined Constants
  • Win32Service Service Type Bitmasks
Win32Service Service Type Bitmasks
Constant | Value | Description
WIN32_SERVICE_WIN32_OWN_PROCESS | 0x00000010 | The service runs in its own process.
WIN32_SERVICE_INTERACTIVE_PROCESS | 0x00000100 | The service can interact with the desktop. This option is not available on Windows Vista or later.
WIN32_SERVICE_WIN32_OWN_PROCESS_INTERACTIVE | 0x00000110 | The service runs in its own process and can interact with the desktop. This option is not available on Windows Vista or later.


Win32Service Service Status Constants

  • « Win32Service Service Type Bitmasks
  • Win32Service Service Control Message Constants »
  • PHP Manual
  • Predefined Constants
  • Win32Service Service Status Constants
Win32Service Service Status Constants
Constant | Value | Description
WIN32_SERVICE_CONTINUE_PENDING | 0x00000005 | The service continue is pending.
WIN32_SERVICE_PAUSE_PENDING | 0x00000006 | The service pause is pending.
WIN32_SERVICE_PAUSED | 0x00000007 | The service is paused.
WIN32_SERVICE_RUNNING | 0x00000004 | The service is running.
WIN32_SERVICE_START_PENDING | 0x00000002 | The service is starting.
WIN32_SERVICE_STOP_PENDING | 0x00000003 | The service is stopping.
WIN32_SERVICE_STOPPED | 0x00000001 | The service is not running.


Win32Service Service Control Message Constants

  • « Win32Service Service Status Constants
  • Win32Service Service Control Message Accepted Bitmasks »
  • PHP Manual
  • Predefined Constants
  • Win32Service Service Control Message Constants
Win32Service Service Control Message Constants
Constant | Value | Description
WIN32_SERVICE_CONTROL_CONTINUE | 0x00000003 | Notifies a paused service that it should resume.
WIN32_SERVICE_CONTROL_DEVICEEVENT | 0x0000000B |
WIN32_SERVICE_CONTROL_HARDWAREPROFILECHANGE | 0x0000000C |
WIN32_SERVICE_CONTROL_INTERROGATE | 0x00000004 | Notifies a service that it should report its current status information to the service control manager.
WIN32_SERVICE_CONTROL_NETBINDADD | 0x00000007 | Notifies a network service that there is a new component for binding.
WIN32_SERVICE_CONTROL_NETBINDDISABLE | 0x0000000A | Notifies a network service that one of its bindings has been disabled.
WIN32_SERVICE_CONTROL_NETBINDENABLE | 0x00000009 | Notifies a network service that a disabled binding has been enabled.
WIN32_SERVICE_CONTROL_NETBINDREMOVE | 0x00000008 | Notifies a network service that a component for binding has been removed.
WIN32_SERVICE_CONTROL_PARAMCHANGE | 0x00000006 | Notifies a service that its startup parameters have changed.
WIN32_SERVICE_CONTROL_PAUSE | 0x00000002 | Notifies a service that it should pause.
WIN32_SERVICE_CONTROL_POWEREVENT | 0x0000000D |
WIN32_SERVICE_CONTROL_PRESHUTDOWN | 0x0000000F | Notifies a service that the system will be shutting down. A service that handles this notification blocks system shutdown until the service stops or the preshutdown time-out interval expires. This value is not supported by Windows Server 2003 and Windows XP/2000.
WIN32_SERVICE_CONTROL_SESSIONCHANGE | 0x0000000E |
WIN32_SERVICE_CONTROL_SHUTDOWN | 0x00000005 | Notifies a service that the system is shutting down so the service can perform cleanup tasks. If a service accepts this control code, it must stop after it performs its cleanup tasks. After the SCM sends this control code, it will not send other control codes to the service.
WIN32_SERVICE_CONTROL_STOP | 0x00000001 | Notifies a service that it should stop.


Win32Service Service Control Message Accepted Bitmasks

  • « Win32Service Service Control Message Constants
  • Win32Service Service Start Type Constants »
  • PHP Manual
  • Predefined Constants
  • Win32Service Service Control Message Accepted Bitmasks
Win32Service Service Control Message Accepted Bitmasks
Constant | Value | Description
WIN32_SERVICE_ACCEPT_HARDWAREPROFILECHANGE | 0x00000020 | The service is notified when the computer's hardware profile has changed. This enables the system to send WIN32_SERVICE_CONTROL_HARDWAREPROFILECHANGE notifications to the service.
WIN32_SERVICE_ACCEPT_NETBINDCHANGE | 0x00000010 | The service is a network component that can accept changes in its binding without being stopped and restarted. This control code allows the service to receive WIN32_SERVICE_CONTROL_NETBINDADD, WIN32_SERVICE_CONTROL_NETBINDREMOVE, WIN32_SERVICE_CONTROL_NETBINDENABLE, and WIN32_SERVICE_CONTROL_NETBINDDISABLE notifications.
WIN32_SERVICE_ACCEPT_PARAMCHANGE | 0x00000008 | The service can reread its startup parameters without being stopped and restarted. This control code allows the service to receive WIN32_SERVICE_CONTROL_PARAMCHANGE notifications.
WIN32_SERVICE_ACCEPT_PAUSE_CONTINUE | 0x00000002 | The service can be paused and continued. This control code allows the service to receive WIN32_SERVICE_CONTROL_PAUSE and WIN32_SERVICE_CONTROL_CONTINUE notifications.
WIN32_SERVICE_ACCEPT_POWEREVENT | 0x00000040 | The service is notified when the computer's power status has changed. This enables the system to send WIN32_SERVICE_CONTROL_POWEREVENT notifications to the service.
WIN32_SERVICE_ACCEPT_PRESHUTDOWN | 0x00000100 | The service can perform preshutdown tasks. This control code enables the service to receive WIN32_SERVICE_CONTROL_PRESHUTDOWN notifications. This value is not supported by Windows Server 2003 and Windows XP/2000.
WIN32_SERVICE_ACCEPT_SESSIONCHANGE | 0x00000080 | The service is notified when the computer's session status has changed. This enables the system to send WIN32_SERVICE_CONTROL_SESSIONCHANGE notifications to the service. Windows 2000: This value is not supported
WIN32_SERVICE_ACCEPT_SHUTDOWN | 0x00000004 | The service is notified when system shutdown occurs. This control code allows the service to receive WIN32_SERVICE_CONTROL_SHUTDOWN notifications.
WIN32_SERVICE_ACCEPT_STOP | 0x00000001 | The service can be stopped. This control code allows the service to receive WIN32_SERVICE_CONTROL_STOP notifications.
WIN32_SERVICE_ACCEPT_TIMECHANGE | 0x00000200 | The service is notified when the system time has changed. This enables the system to send WIN32_SERVICE_CONTROL_TIMECHANGE notifications to the service. Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP/2000: This control code is not supported.
WIN32_SERVICE_ACCEPT_TRIGGEREVENT | 0x00000400 | The service is notified when an event for which the service has registered occurs. This enables the system to send WIN32_SERVICE_CONTROL_TRIGGEREVENT notifications to the service. Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP/2000: This control code is not supported.


Win32Service Service Start Type Constants

  • « Win32Service Service Control Message Accepted Bitmasks
  • Win32Service Service Error Control Constants »
  • PHP Manual
  • Predefined Constants
  • Win32Service Service Start Type Constants
Win32Service Service Start Type Constants
Constant | Value | Description
WIN32_SERVICE_BOOT_START | 0x00000000 | A device driver started by the system loader. This value is valid only for driver services.
WIN32_SERVICE_SYSTEM_START | 0x00000001 | A device driver started by the IoInitSystem function. This value is valid only for driver services.
WIN32_SERVICE_AUTO_START | 0x00000002 | A service started automatically by the service control manager during system startup.
WIN32_SERVICE_DEMAND_START | 0x00000003 | A service started by the service control manager when a process calls the StartService function.
WIN32_SERVICE_DISABLED | 0x00000004 | A service that cannot be started. Attempts to start the service result in the error code WIN32_ERROR_SERVICE_DISABLED.


Win32Service Service Error Control Constants

  • « Win32Service Service Start Type Constants
  • Win32Service Service Flag Constants »
  • PHP Manual
  • Predefined Constants
  • Win32Service Service Error Control Constants
Win32Service Service Error Control Constants
Constant | Value | Description
WIN32_SERVICE_ERROR_IGNORE | 0x00000000 | The startup program ignores the error and continues the startup operation.
WIN32_SERVICE_ERROR_NORMAL | 0x00000001 | The startup program logs the error in the event log but continues the startup operation.
WIN32_SERVICE_ERROR_SEVERE | 0x00000002 | The startup program logs the error in the event log. If the last-known-good configuration is being started, the startup operation continues. Otherwise, the system is restarted with the last-known-good configuration.
WIN32_SERVICE_ERROR_CRITICAL | 0x00000003 | The startup program logs the error in the event log, if possible. If the last-known-good configuration is being started, the startup operation fails. Otherwise, the system is restarted with the last-known good configuration.


Win32Service Service Flag Constants

  • « Win32Service Service Error Control Constants
  • Win32 Error Codes »
  • PHP Manual
  • Predefined Constants
  • Win32Service Service Flag Constants
Win32Service Service Flag Constants
Constant | Value | Description
WIN32_SERVICE_RUNS_IN_SYSTEM_PROCESS | 0x00000001 | The service runs in a system process that must always be running.


Win32 Error Codes

  • « Win32Service Service Flag Constants
  • Win32 Base Priority Classes »
  • PHP Manual
  • Predefined Constants
  • Win32 Error Codes
Win32 Error Codes
Constant | Value | Description
WIN32_ERROR_ACCESS_DENIED | 0x00000005 | The handle to the SCM database does not have the appropriate access rights.
WIN32_ERROR_CIRCULAR_DEPENDENCY | 0x00000423 | A circular service dependency was specified.
WIN32_ERROR_DATABASE_DOES_NOT_EXIST | 0x00000429 | The specified database does not exist.
WIN32_ERROR_DEPENDENT_SERVICES_RUNNING | 0x0000041B | The service cannot be stopped because other running services are dependent on it.
WIN32_ERROR_DUPLICATE_SERVICE_NAME | 0x00000436 | The display name already exists in the service control manager database either as a service name or as another display name.
WIN32_ERROR_FAILED_SERVICE_CONTROLLER_CONNECT | 0x00000427 | This error is returned if the program is being run as a console application rather than as a service. If the program will be run as a console application for debugging purposes, structure it such that service-specific code is not called.
WIN32_ERROR_INSUFFICIENT_BUFFER | 0x0000007A | The buffer is too small for the service status structure. Nothing was written to the structure.
WIN32_ERROR_INVALID_DATA | 0x0000000D | The specified service status structure is invalid.
WIN32_ERROR_INVALID_HANDLE | 0x00000006 | The handle to the specified service control manager database is invalid.
WIN32_ERROR_INVALID_LEVEL | 0x0000007C | The InfoLevel parameter contains an unsupported value.
WIN32_ERROR_INVALID_NAME | 0x0000007B | The specified service name is invalid.
WIN32_ERROR_INVALID_PARAMETER | 0x00000057 | A parameter that was specified is invalid.
WIN32_ERROR_INVALID_SERVICE_ACCOUNT | 0x00000421 | The user account name specified in the user parameter does not exist. See win32_create_service().
WIN32_ERROR_INVALID_SERVICE_CONTROL | 0x0000041C | The requested control code is not valid, or it is unacceptable to the service.
WIN32_ERROR_PATH_NOT_FOUND | 0x00000003 | The service binary file could not be found.
WIN32_ERROR_SERVICE_ALREADY_RUNNING | 0x00000420 | An instance of the service is already running.
WIN32_ERROR_SERVICE_CANNOT_ACCEPT_CTRL | 0x00000425 | The requested control code cannot be sent to the service because the state of the service is WIN32_SERVICE_STOPPED, WIN32_SERVICE_START_PENDING, or WIN32_SERVICE_STOP_PENDING.
WIN32_ERROR_SERVICE_DATABASE_LOCKED | 0x0000041F | The database is locked.
WIN32_ERROR_SERVICE_DEPENDENCY_DELETED | 0x00000433 | The service depends on a service that does not exist or has been marked for deletion.
WIN32_ERROR_SERVICE_DEPENDENCY_FAIL | 0x0000042C | The service depends on another service that has failed to start.
WIN32_ERROR_SERVICE_DISABLED | 0x00000422 | The service has been disabled.
WIN32_ERROR_SERVICE_DOES_NOT_EXIST | 0x00000424 | The specified service does not exist as an installed service.
WIN32_ERROR_SERVICE_EXISTS | 0x00000431 | The specified service already exists in this database.
WIN32_ERROR_SERVICE_LOGON_FAILED | 0x0000042D | The service did not start due to a logon failure. This error occurs if the service is configured to run under an account that does not have the "Log on as a service" right.
WIN32_ERROR_SERVICE_MARKED_FOR_DELETE | 0x00000430 | The specified service has already been marked for deletion.
WIN32_ERROR_SERVICE_NO_THREAD | 0x0000041E | A thread could not be created for the service.
WIN32_ERROR_SERVICE_NOT_ACTIVE | 0x00000426 | The service has not been started.
WIN32_ERROR_SERVICE_REQUEST_TIMEOUT | 0x0000041D | The process for the service was started, but it did not call StartServiceCtrlDispatcher, or the thread that called StartServiceCtrlDispatcher may be blocked in a control handler function.
WIN32_ERROR_SHUTDOWN_IN_PROGRESS | 0x0000045B | The system is shutting down; this function cannot be called.
WIN32_ERROR_SERVICE_SPECIFIC_ERROR | 0x0000042A | The service has returned a service-specific error code.
WIN32_NO_ERROR | 0x00000000 | No error.


Win32 Base Priority Classes

  • « Win32 Error Codes
  • Win32 Recovery action »
  • PHP Manual
  • Predefined Constants
  • Win32 Base Priority Classes
Win32 Base Priority Classes
Constant | Value | Description
WIN32_ABOVE_NORMAL_PRIORITY_CLASS | 0x00008000 | Process that has priority above WIN32_NORMAL_PRIORITY_CLASS but below WIN32_HIGH_PRIORITY_CLASS.
WIN32_BELOW_NORMAL_PRIORITY_CLASS | 0x00004000 | Process that has priority above WIN32_IDLE_PRIORITY_CLASS but below WIN32_NORMAL_PRIORITY_CLASS.
WIN32_HIGH_PRIORITY_CLASS | 0x00000080 | Process that performs time-critical tasks that must be executed immediately. The threads of the process preempt the threads of normal or idle priority class processes. An example is the Task List, which must respond quickly when called by the user, regardless of the load on the operating system. Use extreme care when using the high-priority class, because a high-priority class application can use nearly all available CPU time.
WIN32_IDLE_PRIORITY_CLASS | 0x00000040 | Process whose threads run only when the system is idle. The threads of the process are preempted by the threads of any process running in a higher priority class. An example is a screen saver. The idle-priority class is inherited by child processes.
WIN32_NORMAL_PRIORITY_CLASS | 0x00000020 | Process with no special scheduling needs.
WIN32_REALTIME_PRIORITY_CLASS | 0x00000100 | Process that has the highest possible priority. The threads of the process preempt the threads of all other processes, including operating system processes performing important tasks. For example, a real-time process that executes for more than a very brief interval can cause disk caches not to flush or cause the mouse to be unresponsive.


Win32 Recovery action

  • « Win32 Base Priority Classes
  • Win32 Service informations »
  • PHP Manual
  • Predefined Constants
  • Win32 Recovery action
Win32 Recovery action
Constant | Value | Description
WIN32_SC_ACTION_NONE | 0x00000000 | No action.
WIN32_SC_ACTION_REBOOT | 0x00000001 | Restart the server.
WIN32_SC_ACTION_RESTART | 0x00000002 | Restart the service.
WIN32_SC_ACTION_RUN_COMMAND | 0x00000003 | Run a command.


Win32 Service informations

  • « Win32 Recovery action
  • Examples »
  • PHP Manual
  • Predefined Constants
  • Win32 Service informations
Win32 Service informations
Constant | Value | Description
WIN32_INFO_SERVICE | "service" |
WIN32_INFO_DISPLAY | "display" |
WIN32_INFO_USER | "user" |
WIN32_INFO_PASSWORD | "password" |
WIN32_INFO_PATH | "path" |
WIN32_INFO_PARAMS | "params" |
WIN32_INFO_DESCRIPTION | "description" |
WIN32_INFO_START_TYPE | "start_type" |
INFO_LOAD_ORDER | "load_order" |
INFO_SVC_TYPE | "svc_type" |
INFO_ERROR_CONTROL | "error_control" |
INFO_DELAYED_START | "delayed_start" |
INFO_BASE_PRIORITY | "base_priority" |
INFO_DEPENDENCIES | "dependencies" |
INFO_RECOVERY_DELAY | "recovery_delay" |
INFO_RECOVERY_ACTION_1 | "recovery_action_1" |
INFO_RECOVERY_ACTION_2 | "recovery_action_2" |
INFO_RECOVERY_ACTION_3 | "recovery_action_3" |
INFO_RECOVERY_RESET_PERIOD | "recovery_reset_period" |
INFO_RECOVERY_ENABLED | "recovery_enabled" |
INFO_RECOVERY_REBOOT_MSG | "recovery_reboot_msg" |
INFO_RECOVERY_COMMAND | "recovery_command" |


Examples

Example #1 Registering a PHP script to run as a service

<?php
win32_create_service(array(
    'service'     => 'dummyphp',                                           # the name of your service
    'display'     => 'sample dummy PHP service',                           # short description
    'description' => 'This is a dummy Windows service created using PHP.', # long description
    'params'      => '"' . __FILE__ . '"  run',                            # path to the script and parameters
));
?>

Example #2 Unregistering a service

<?php
win32_delete_service('dummyphp');
?>

Example #3 Running as a service

<?php
if ($argv[1] == 'run') {
  win32_start_service_ctrl_dispatcher('dummyphp');

  while (WIN32_SERVICE_CONTROL_STOP != win32_get_last_control_message()) {
    # do your work here.
    # try not to take up more than 30 seconds before going around the loop
    # again
  }
}
?>


win32service Functions

Table of Contents

  • win32_continue_service — Resumes a paused service
  • win32_create_service — Creates a new service entry in the SCM database
  • win32_delete_service — Deletes a service entry from the SCM database
  • win32_get_last_control_message — Returns the last control message that was sent to this service
  • win32_pause_service — Pauses a service
  • win32_query_service_status — Queries the status of a service
  • win32_send_custom_control — Send a custom control to the service
  • win32_set_service_exit_code — Define or return the exit code for the current running service
  • win32_set_service_exit_mode — Define or return the exit mode for the current running service
  • win32_set_service_status — Update the service status
  • win32_start_service_ctrl_dispatcher — Registers the script with the SCM, so that it can act as the service with the given name
  • win32_start_service — Starts a service
  • win32_stop_service — Stops a service


Resumes a paused service

  • « win32service Functions
  • win32_create_service »
  • PHP Manual
  • win32service Functions
  • Resumes a paused service

win32_continue_service

(PECL win32service >=0.1.0)

win32_continue_service — Resumes a paused service

Description

win32_continue_service ( string $servicename [, string $machine ] ) : int

Resumes a paused, named service. Requires administrative privileges or an account with appropriate rights set in the service's ACL.

Parameters

servicename

The short name of the service.

machine

Optional machine name. If omitted, the local machine is used.

Return Values

Returns WIN32_NO_ERROR on success, FALSE if there is a problem with the parameters or a Win32 Error Code on failure.

Changelog

Version | Description
0.3.0 | This function does not longer require an administrator account if ACL is set for another account.

See Also

  • win32_start_service() - Starts a service
  • win32_stop_service() - Stops a service
  • win32_pause_service() - Pauses a service
  • win32_send_custom_control() - Send a custom control to the service
  • Win32 Error Codes


Creates a new service entry in the SCM database

  • « win32_continue_service
  • win32_delete_service »
  • PHP Manual
  • win32service Functions
  • Creates a new service entry in the SCM database

win32_create_service

(PECL win32service >=0.1.0)

win32_create_service — Creates a new service entry in the SCM database

Description

win32_create_service ( array $details [, string $machine ] ) : mixed

Attempts to add a service into the SCM database. Administrative privileges are required for this to succeed.

Parameters

details

An array of service details:

service

The short name of the service. This is the name that you will use to control the service using the net command. The service must be unique (no two services can share the same name), and, ideally, should avoid having spaces in the name.

display

The display name of the service. This is the name that you will see in the Services Applet.

description

The long description of the service. This is the description that you will see in the Services Applet.

user

The name of the user account under which you want the service to run. If omitted, the service will run as the LocalSystem account. If the username is specified, you must also provide a password.

password

The password that corresponds to the user.

path

The full path to the executable module that will be launched when the service is started. If omitted, the path to the current PHP process will be used.

params

Command line parameters to pass to the service when it starts. If you want to run a PHP script as the service, then the first parameter should be the full path to the PHP script that you intend to run. If the script name or path contains spaces, then wrap the full path to the PHP script with ".

load_order

Controls the load_order. This is not yet fully supported.

svc_type

Sets the service type. If omitted, the default value is WIN32_SERVICE_WIN32_OWN_PROCESS. Don't change this unless you know what you're doing.

start_type

Specifies how the service should be started. The default is WIN32_SERVICE_AUTO_START which means the service will be launched when the machine starts up.

error_control

Informs the SCM what it should do when it detects a problem with the service. The default is WIN32_SERVER_ERROR_IGNORE. Changing this value is not yet fully supported.

delayed_start

If delayed_start is set to TRUE, then this will inform the SCM that this service should be started after other auto-start services are started plus a short delay.

Any service can be marked as a delayed auto-start service; however, this setting has no effect unless the service's start_type is WIN32_SERVICE_AUTO_START.

This setting is only applicable on Windows Vista and Windows Server 2008 or greater.

base_priority

To reduce the impact on processor utilisation, it may be necessary to set a base priority lower than normal.

The base_priority can be set to one of the constants define in Win32 Base Priority Classes.

dependencies

To define the dependencies for your service, it may be necessary to set this parameter to the list of the services names in an array.

recovery_delay

This parameter defines the delay between the fail and the execution of recovery action. The value is in milliseconds.

The default value is 60000.

recovery_action_1

The action will be executed on first failure. The default value is WIN32_SC_ACTION_NONE.

The recovery_action_1 can be set to one of the constants defined in Win32 Recovery action.

recovery_action_2

The action will be executed on second failure. The default value is WIN32_SC_ACTION_NONE.

The recovery_action_2 can be set to one of the constants defined in Win32 Recovery action.

recovery_action_3

The action will be executed on next failures. The default value is WIN32_SC_ACTION_NONE.

The recovery_action_3 can be set to one of the constants defined in Win32 Recovery action.

recovery_reset_period

The failure count will be reset after the delay defined in the parameter. The delay is expirement in seconds.

The default value is 86400.

recovery_enabled

Set this parameter at TRUE to enable the recovery settings, FALSE to disable.

The default value is FALSE

recovery_reboot_msg

Set this parameter to define the message saved into the Windows Event Log before the reboot. Used only if one action is set to WIN32_SC_ACTION_REBOOT.

recovery_command

Set this parameter to define the command executed when one action is defined on WIN32_SC_ACTION_RUN_COMMAND.

machine

The optional machine name on which you want to create a service. If omitted, it will use the local machine.

Return Values

Returns WIN32_NO_ERROR on success, FALSE if there is a problem with the parameters or a Win32 Error Code on failure.

Examples

Example #1 A win32_create_service() example

Create a service with the short name 'dummyphp'.

<?php
$x = win32_create_service(array(
    'service'     => 'dummyphp',                                           // the name of your service
    'display'     => 'sample dummy PHP service',                           // short description
    'description' => 'This is a dummy Windows service created using PHP.', // long description
    'params'      => '"' . __FILE__ . '"  run',                            // path to the script and parameters
));
debug_zval_dump($x);
?>

Example #2 A win32_create_service() example with dependencies

Create a service with the short name 'dummyphp' and dependencies.

<?php
$x = win32_create_service(array(
    'service'      => 'dummyphp',                                           // the name of your service
    'display'      => 'sample dummy PHP service',                           // short description
    'description'  => 'This is a dummy Windows service created using PHP.', // long description
    'params'       => '"' . __FILE__ . '"  run',                            // path to the script and parameters
    'dependencies' => array("Netman"),                                      // The list of the dependencies
));
debug_zval_dump($x);
?>

Example #3 A win32_create_service() example with recovery

Create a service with the short name 'dummyphp' and recovery settings.

<?php
$x = win32_create_service(array(
    'service'               => 'dummyphp',                                           // the name of your service
    'display'               => 'sample dummy PHP service',                           // short description
    'description'           => 'This is a dummy Windows service created using PHP.', // long description
    'params'                => '"' . __FILE__ . '"  run',                            // path to the script and parameters
    'recovery_delay'        => 120000,                                               // Recovery action is executed after 2 minutes
    'recovery_action_1'     => WIN32_SC_ACTION_RESTART,                              // On first failure, restart the service
    'recovery_action_2'     => WIN32_SC_ACTION_RUN_COMMAND,                          // On second failure, execute the commmand
    'recovery_action_3'     => WIN32_SC_ACTION_NONE,                                 // On other failure, do nothing
    'recovery_reset_period' => 86400,                                                // Reset the fail counter after 1 day
    'recovery_enabled'      => true,                                                 // Enable the recovery parameter
    'recovery_reboot_msg'   => null,                                                 // Do not define a reboot message, it's not needed here
    'recovery_command'      => "c:\clean-service.bat",                               // When the action is WIN32_SC_ACTION_RUN_COMMAND, execute this command
));
debug_zval_dump($x);
?>

Changelog

Version | Description
0.4.0 | The dependencies, recovery_delay, recovery_action_1, recovery_action_2, recovery_action_3, recovery_reset_period, recovery_enabled, recovery_reboot_msg and recovery_command parameters have been added.

See Also

  • win32_delete_service() - Deletes a service entry from the SCM database
  • Win32 Base Priority Classes
  • Win32 Recovery action
  • Win32 Error Codes


Deletes a service entry from the SCM database

  • « win32_create_service
  • win32_get_last_control_message »
  • PHP Manual
  • win32service Functions
  • Deletes a service entry from the SCM database

win32_delete_service

(PECL win32service >=0.1.0)

win32_delete_service — Deletes a service entry from the SCM database

Description

win32_delete_service ( string $servicename [, string $machine ] ) : mixed

Attempts to delete a service from the SCM database. Administrative privileges are required for this to succeed.

This function really just marks the service for deletion. If other processes (such as the Services Applet) are open, then the deletion will be deferred until those applications are closed. If a service is marked for deletion, further attempts to delete it will fail, and attempts to create a new service with that name will also fail.

Parameters

servicename

The short name of the service.

machine

The optional machine name. If omitted, the local machine will be used.

Return Values

Returns WIN32_NO_ERROR on success, FALSE if there is a problem with the parameters or a Win32 Error Code on failure.

Examples

Example #1 A win32_delete_service() example

Deletes the dummyphp service.

<?php
win32_delete_service('dummyphp');
?>

See Also

  • win32_create_service() - Creates a new service entry in the SCM database
  • Win32 Error Codes


Returns the last control message that was sent to this service

  • « win32_delete_service
  • win32_pause_service »
  • PHP Manual
  • win32service Functions
  • Returns the last control message that was sent to this service

win32_get_last_control_message

(PECL win32service >=0.1.0)

win32_get_last_control_message — Returns the last control message that was sent to this service

Description

win32_get_last_control_message ( void ) : int

Returns the control code that was last sent to this service process. When running as a service you should periodically check this to determine if your service needs to stop running.

Caution

Since version 0.2.0, this function work only in "cli" SAPI. On other SAPI this function is disabled.

Return Values

Returns a control constant which will be one of the Win32Service Service Control Message Constants: WIN32_SERVICE_CONTROL_CONTINUE, WIN32_SERVICE_CONTROL_INTERROGATE, WIN32_SERVICE_CONTROL_PAUSE, WIN32_SERVICE_CONTROL_PRESHUTDOWN, WIN32_SERVICE_CONTROL_SHUTDOWN, WIN32_SERVICE_CONTROL_STOP.

Errors/Exceptions

If SAPI is not "cli", this function emits an E_ERROR level error.

Changelog

Version | Description
0.2.0 | This function works only in the "cli" SAPI.

See Also

  • win32_start_service_ctrl_dispatcher() - Registers the script with the SCM, so that it can act as the service with the given name
  • win32_set_service_status() - Update the service status
  • win32_set_service_exit_mode() - Define or return the exit mode for the current running service
  • win32_set_service_exit_code() - Define or return the exit code for the current running service
  • Win32Service Service Control Message Constants


Pauses a service

  • « win32_get_last_control_message
  • win32_query_service_status »
  • PHP Manual
  • win32service Functions
  • Pauses a service

win32_pause_service

(PECL win32service >=0.1.0)

win32_pause_service — Pauses a service

Description

win32_pause_service ( string $servicename [, string $machine ] ) : int

Pauses a named service. Requires administrative privileges or an account with appropriate rights set in the service's ACL.

Parameters

servicename

The short name of the service.

machine

Optional machine name. If omitted, the local machine is used.

Return Values

Returns WIN32_NO_ERROR on success, FALSE if there is a problem with the parameters or a Win32 Error Code on failure.

Changelog

Version | Description
0.3.0 | This function does not longer require an administrator account if ACL is set for another account.

See Also

  • win32_start_service() - Starts a service
  • win32_stop_service() - Stops a service
  • win32_continue_service() - Resumes a paused service
  • win32_send_custom_control() - Send a custom control to the service
  • Win32 Error Codes


Queries the status of a service

  • « win32_pause_service
  • win32_send_custom_control »
  • PHP Manual
  • win32service Functions
  • Queries the status of a service

win32_query_service_status

(PECL win32service >=0.1.0)

win32_query_service_status — Queries the status of a service

Description

win32_query_service_status ( string $servicename [, string $machine ] ) : mixed

Queries the current status for a service, returning an array of information.

Parameters

servicename

The short name of the service.

machine

The optional machine name. If omitted, the local machine will be used.

Return Values

Returns an array consisting of the following information on success, FALSE if there is a problem with the parameters or a Win32 Error Code on failure.

ServiceType

The dwServiceType. See Win32Service Service Type Bitmasks.

CurrentState

The dwCurrentState. See Win32Service Service Status Constants.

ControlsAccepted

Which service controls are accepted by the service. See Win32Service Service Control Message Accepted Bitmasks.

Win32ExitCode

If the service exited, the return code from the process. This value is equal to WIN32_ERROR_SERVICE_SPECIFIC_ERROR if the exit mode is not gracefuly. See Win32Service error codes and win32_set_service_exit_mode()

ServiceSpecificExitCode

If the service exited with an error condition, the service specific code that is logged in the event log is visible here. This value is equal to the value defined by win32_set_service_exit_code()

CheckPoint

If the service is shutting down, holds the current check point number. This is used by the SCM as a kind of heart-beat to detect a wedged service process. The value of the check point is best interpreted in conjunction with the WaitHint value.

WaitHint

If the service is shutting down it will set WaitHint to a checkpoint value that will indicate 100% completion. This can be used to implement a progress indicator.

ProcessId

The Windows process identifier. If 0, the process is not running.

ServiceFlags

The dwServiceFlags. See Win32Service Service Service Flag Constants.

See Also

  • Win32Service Predefined Constants


Send a custom control to the service

  • « win32_query_service_status
  • win32_set_service_exit_code »
  • PHP Manual
  • win32service Functions
  • Send a custom control to the service

win32_send_custom_control

(PECL win32service >=0.4.0)

win32_send_custom_control — Send a custom control to the service

Description

win32_send_custom_control ( string $servicename , int $control [, string $machine ] ) : int

See » Microsoft ControlService function for more details

Parameters

servicename

The short name of the service.

control

The custom contole value between 128 and 255.

machine

Optional machine name. If omitted, the local machine is used.

Return Values

Returns WIN32_NO_ERROR on success, FALSE if there is a problem with the parameters or a Win32 Error Code on failure.

Errors/Exceptions

If the control value is not between 128 and 255, this function emits an E_ERROR level error.

See Also

  • win32_start_service() - Starts a service
  • win32_stop_service() - Stops a service
  • win32_pause_service() - Pauses a service
  • win32_continue_service() - Resumes a paused service
  • Win32 Error Codes


Define or return the exit code for the current running service

  • « win32_send_custom_control
  • win32_set_service_exit_mode »
  • PHP Manual
  • win32service Functions
  • Define or return the exit code for the current running service

win32_set_service_exit_code

(PECL win32service >=0.4.0)

win32_set_service_exit_code — Define or return the exit code for the current running service

Description

win32_set_service_exit_code ([ int $exitCode = 1 ] ) : int

Change or return the exit code. The exit code is used only if the exit mode is not graceful. If the value is not zero, the recovery configuration can be used after service fail. See » Microsoft system error codes for more details

Caution

This function work only in "cli" SAPI. On other SAPI this function is disabled.

Parameters

exitCode

The return code used on exit.

Return Values

Return the current or old exit code.

Errors/Exceptions

If SAPI is not "cli", this function emits an E_ERROR level error.

See Also

  • win32_start_service_ctrl_dispatcher() - Registers the script with the SCM, so that it can act as the service with the given name
  • win32_set_service_status() - Update the service status
  • win32_set_service_exit_mode() - Define or return the exit mode for the current running service


Define or return the exit mode for the current running service

  • « win32_set_service_exit_code
  • win32_set_service_status »
  • PHP Manual
  • win32service Functions
  • Define or return the exit mode for the current running service

win32_set_service_exit_mode

(PECL win32service >=0.4.0)

win32_set_service_exit_mode — Define or return the exit mode for the current running service

Description

win32_set_service_exit_mode ([ bool $gracefulMode = true ] ) : bool

If gracefulMode parameter is provided, the exit mode is changed. When the exit mode is not gracefuly, the exit code used can be set with the win32_set_service_exit_code() function.

Caution

This function work only in "cli" SAPI. On other SAPI this function is disabled.

Parameters

gracefulMode

TRUE for exit graceful. FALSE for exit with error.

Return Values

Return the current or old exit mode.

Errors/Exceptions

If SAPI is not "cli", this function emits an E_ERROR level error.

See Also

  • win32_start_service_ctrl_dispatcher() - Registers the script with the SCM, so that it can act as the service with the given name
  • win32_set_service_status() - Update the service status
  • win32_set_service_exit_code() - Define or return the exit code for the current running service


Update the service status

  • « win32_set_service_exit_mode
  • win32_start_service_ctrl_dispatcher »
  • PHP Manual
  • win32service Functions
  • Update the service status

win32_set_service_status

(PECL win32service >=0.1.0)

win32_set_service_status — Update the service status

Description

win32_set_service_status ( int $status [, int $checkpoint = 0 ] ) : bool

Informs the SCM of the current status of a running service. This call is only valid for a running service process.

Caution

Since version 0.2.0, this function work only in "cli" SAPI. On other SAPI this function is disabled.

Parameters

status

The service status code, one of WIN32_SERVICE_RUNNING, WIN32_SERVICE_STOPPED, WIN32_SERVICE_STOP_PENDING, WIN32_SERVICE_START_PENDING, WIN32_SERVICE_CONTINUE_PENDING, WIN32_SERVICE_PAUSE_PENDING, WIN32_SERVICE_PAUSED.

checkpoint

The checkpoint value the service increments periodically to report its progress during a lengthy start, stop, pause, or continue operation. For example, the service should increment this value as it completes each step of its initialization when it is starting up.

The checkpoint is only valid when the status is one of WIN32_SERVICE_STOP_PENDING, WIN32_SERVICE_START_PENDING, WIN32_SERVICE_CONTINUE_PENDING or WIN32_SERVICE_PAUSE_PENDING.

Return Values

Returns TRUE on success, FALSE if there is a problem with the parameters or a Win32 Error Code on failure.

Errors/Exceptions

If SAPI is not "cli", this function emits an E_ERROR level error.

Changelog

Version | Description
0.2.0 | This function works only in the "cli" SAPI.

See Also

  • win32_start_service_ctrl_dispatcher() - Registers the script with the SCM, so that it can act as the service with the given name
  • win32_get_last_control_message() - Returns the last control message that was sent to this service
  • win32_set_service_exit_mode() - Define or return the exit mode for the current running service
  • win32_set_service_exit_code() - Define or return the exit code for the current running service
  • Win32Service Service Status Constants


Registers the script with the SCM, so that it can act as the service with the given name

  • « win32_set_service_status
  • win32_start_service »
  • PHP Manual
  • win32service Functions
  • Registers the script with the SCM, so that it can act as the service with the given name

win32_start_service_ctrl_dispatcher

(PECL win32service >=0.1.0)

win32_start_service_ctrl_dispatcher — Registers the script with the SCM, so that it can act as the service with the given name

Description

win32_start_service_ctrl_dispatcher ( string $name [, bool $gracefulMode = true ] ) : mixed

When launched via the Service Control Manager, a service process is required to "check-in" with it to establish service monitoring and communication facilities. This function performs the check-in by spawning a thread to handle the lower-level communication with the service control manager.

Once started, the service process should do 2 things. The first is to tell the Service Control Manager that the service is running. This is achieved by calling win32_set_service_status() with the WIN32_SERVICE_RUNNING constant. If you need to perform some lengthy process before the service is actually running, then you can use the WIN32_SERVICE_START_PENDING constant. The second is to continue to check-in with the service control manager so that it can determine if it should terminate. This is achieved by periodically calling win32_get_last_control_message() and handling the return code appropriately.

Caution

Since version 0.2.0, this function work only in "cli" SAPI. On other SAPI this function is disabled.

Parameters

name

The short-name of the service, as registered by win32_create_service().

gracefulMode

TRUE for exit graceful. FALSE for exit with error. See win32_set_service_exit_mode() for more details.

Return Values

Returns TRUE on success, FALSE if there is a problem with the parameters or a Win32 Error Code on failure.

Errors/Exceptions

If SAPI is not "cli", this function emits an E_ERROR level error.

Examples

Example #1 A win32_start_service_ctrl_dispatcher() example

Check if the service is runnig under the SCM.

<?php
if (!win32_start_service_ctrl_dispatcher('dummyphp')) {
  die("I'm probably not running under the service control manager");
}

win32_set_service_status(WIN32_SERVICE_START_PENDING);

// Some lengthy process to get this service up and running.

win32_set_service_status(WIN32_SERVICE_RUNNING);

while (WIN32_SERVICE_CONTROL_STOP != win32_get_last_control_message()) {
  # do some work here, trying not to take more than around 30 seconds
  # before coming back into the loop again
}
?>

Changelog

Version | Description
0.4.0 | The parameter gracefulMode has been added.
0.2.0 | This function works only in the "cli" SAPI.

See Also

  • win32_set_service_status() - Update the service status
  • win32_get_last_control_message() - Returns the last control message that was sent to this service
  • win32_set_service_exit_mode() - Define or return the exit mode for the current running service
  • win32_set_service_exit_code() - Define or return the exit code for the current running service
  • Win32 Error Codes


Starts a service

  • « win32_start_service_ctrl_dispatcher
  • win32_stop_service »
  • PHP Manual
  • win32service Functions
  • Starts a service

win32_start_service

(PECL win32service >=0.1.0)

win32_start_service — Starts a service

Description

win32_start_service ( string $servicename [, string $machine ] ) : int

Attempts to start the named service. Requires administrative privileges or an account with appropriate rights set in the service's ACL.

Parameters

servicename

The short name of the service.

machine

Optional machine name. If omitted, the local machine is used.

Return Values

Returns WIN32_NO_ERROR on success, FALSE if there is a problem with the parameters or a Win32 Error Code on failure.

Changelog

Version | Description
0.3.0 | This function does not longer require an administrator account if ACL is set for another account.

See Also

  • win32_stop_service() - Stops a service
  • win32_pause_service() - Pauses a service
  • win32_continue_service() - Resumes a paused service
  • win32_send_custom_control() - Send a custom control to the service
  • Win32 Error Codes


Stops a service

  • « win32_start_service
  • XML Manipulation »
  • PHP Manual
  • win32service Functions
  • Stops a service

win32_stop_service

(PECL win32service >=0.1.0)

win32_stop_service — Stops a service

Description

win32_stop_service ( string $servicename [, string $machine ] ) : int

Stops a named service. Requires administrative privileges or an account with appropriate rights set in the service's ACL.

Parameters

servicename

The short name of the service.

machine

Optional machine name. If omitted, the local machine is used.

Return Values

Returns WIN32_NO_ERROR on success, FALSE if there is a problem with the parameters or a Win32 Error Code on failure.

Changelog

Version | Description
0.3.0 | This function does not longer require an administrator account if ACL is set for another account.

See Also

  • win32_start_service() - Starts a service
  • win32_pause_service() - Pauses a service
  • win32_continue_service() - Resumes a paused service
  • win32_send_custom_control() - Send a custom control to the service
  • Win32 Error Codes


XML Manipulation

  • DOM — Document Object Model
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • DOMAttr — The DOMAttr class
    • DOMCdataSection — The DOMCdataSection class
    • DOMCharacterData — The DOMCharacterData class
    • DOMComment — The DOMComment class
    • DOMDocument — The DOMDocument class
    • DOMDocumentFragment — The DOMDocumentFragment class
    • DOMDocumentType — The DOMDocumentType class
    • DOMElement — The DOMElement class
    • DOMEntity — The DOMEntity class
    • DOMEntityReference — The DOMEntityReference class
    • DOMException — The DOMException class
    • DOMImplementation — The DOMImplementation class
    • DOMNamedNodeMap — The DOMNamedNodeMap class
    • DOMNode — The DOMNode class
    • DOMNodeList — The DOMNodeList class
    • DOMNotation — The DOMNotation class
    • DOMProcessingInstruction — The DOMProcessingInstruction class
    • DOMText — The DOMText class
    • DOMXPath — The DOMXPath class
    • DOM Functions
  • libxml
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • libXMLError — The libXMLError class
    • libxml Functions
  • SDO — Service Data Objects
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Limitations
    • Examples
    • SDO Functions
  • SDO-DAS-Relational — SDO Relational Data Access Service
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Limitations
    • SDO-DAS-Relational Functions
  • SDO DAS XML — SDO XML Data Access Service
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • SDO DAS XML Functions
  • SimpleXML
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • SimpleXMLElement — The SimpleXMLElement class
    • SimpleXMLIterator — The SimpleXMLIterator class
    • SimpleXML Functions
  • WDDX
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • WDDX Functions
  • XMLDiff — XML diff and merge
    • Introduction
    • Installing/Configuring
    • XMLDiff\Base — The XMLDiff\Base class
    • XMLDiff\DOM — The XMLDiff\DOM class
    • XMLDiff\Memory — The XMLDiff\Memory class
    • XMLDiff\File — The XMLDiff\File class
  • XML Parser
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Event Handlers
    • Case Folding
    • Error Codes
    • Character Encoding
    • Examples
    • XML Parser Functions
  • XMLReader
    • Introduction
    • Installing/Configuring
    • XMLReader — The XMLReader class
  • XMLWriter
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • XMLWriter Functions
  • XSL
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • XSLTProcessor — The XSLTProcessor class


Document Object Model

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • DOMAttr — The DOMAttr class
    • DOMAttr::__construct — Creates a new DOMAttr object
    • DOMAttr::isId — Checks if attribute is a defined ID
  • DOMCdataSection — The DOMCdataSection class
    • DOMCdataSection::__construct — Constructs a new DOMCdataSection object
  • DOMCharacterData — The DOMCharacterData class
    • DOMCharacterData::appendData — Append the string to the end of the character data of the node
    • DOMCharacterData::deleteData — Remove a range of characters from the node
    • DOMCharacterData::insertData — Insert a string at the specified 16-bit unit offset
    • DOMCharacterData::replaceData — Replace a substring within the DOMCharacterData node
    • DOMCharacterData::substringData — Extracts a range of data from the node
  • DOMComment — The DOMComment class
    • DOMComment::__construct — Creates a new DOMComment object
  • DOMDocument — The DOMDocument class
    • DOMDocument::__construct — Creates a new DOMDocument object
    • DOMDocument::createAttribute — Create new attribute
    • DOMDocument::createAttributeNS — Create new attribute node with an associated namespace
    • DOMDocument::createCDATASection — Create new cdata node
    • DOMDocument::createComment — Create new comment node
    • DOMDocument::createDocumentFragment — Create new document fragment
    • DOMDocument::createElement — Create new element node
    • DOMDocument::createElementNS — Create new element node with an associated namespace
    • DOMDocument::createEntityReference — Create new entity reference node
    • DOMDocument::createProcessingInstruction — Creates new PI node
    • DOMDocument::createTextNode — Create new text node
    • DOMDocument::getElementById — Searches for an element with a certain id
    • DOMDocument::getElementsByTagName — Searches for all elements with given local tag name
    • DOMDocument::getElementsByTagNameNS — Searches for all elements with given tag name in specified namespace
    • DOMDocument::importNode — Import node into current document
    • DOMDocument::load — Load XML from a file
    • DOMDocument::loadHTML — Load HTML from a string
    • DOMDocument::loadHTMLFile — Load HTML from a file
    • DOMDocument::loadXML — Load XML from a string
    • DOMDocument::normalizeDocument — Normalizes the document
    • DOMDocument::registerNodeClass — Register extended class used to create base node type
    • DOMDocument::relaxNGValidate — Performs relaxNG validation on the document
    • DOMDocument::relaxNGValidateSource — Performs relaxNG validation on the document
    • DOMDocument::save — Dumps the internal XML tree back into a file
    • DOMDocument::saveHTML — Dumps the internal document into a string using HTML formatting
    • DOMDocument::saveHTMLFile — Dumps the internal document into a file using HTML formatting
    • DOMDocument::saveXML — Dumps the internal XML tree back into a string
    • DOMDocument::schemaValidate — Validates a document based on a schema
    • DOMDocument::schemaValidateSource — Validates a document based on a schema
    • DOMDocument::validate — Validates the document based on its DTD
    • DOMDocument::xinclude — Substitutes XIncludes in a DOMDocument Object
  • DOMDocumentFragment — The DOMDocumentFragment class
    • DOMDocumentFragment::appendXML — Append raw XML data
  • DOMDocumentType — The DOMDocumentType class
  • DOMElement — The DOMElement class
    • DOMElement::__construct — Creates a new DOMElement object
    • DOMElement::getAttribute — Returns value of attribute
    • DOMElement::getAttributeNode — Returns attribute node
    • DOMElement::getAttributeNodeNS — Returns attribute node
    • DOMElement::getAttributeNS — Returns value of attribute
    • DOMElement::getElementsByTagName — Gets elements by tagname
    • DOMElement::getElementsByTagNameNS — Get elements by namespaceURI and localName
    • DOMElement::hasAttribute — Checks to see if attribute exists
    • DOMElement::hasAttributeNS — Checks to see if attribute exists
    • DOMElement::removeAttribute — Removes attribute
    • DOMElement::removeAttributeNode — Removes attribute
    • DOMElement::removeAttributeNS — Removes attribute
    • DOMElement::setAttribute — Adds new attribute
    • DOMElement::setAttributeNode — Adds new attribute node to element
    • DOMElement::setAttributeNodeNS — Adds new attribute node to element
    • DOMElement::setAttributeNS — Adds new attribute
    • DOMElement::setIdAttribute — Declares the attribute specified by name to be of type ID
    • DOMElement::setIdAttributeNode — Declares the attribute specified by node to be of type ID
    • DOMElement::setIdAttributeNS — Declares the attribute specified by local name and namespace URI to be of type ID
  • DOMEntity — The DOMEntity class
  • DOMEntityReference — The DOMEntityReference class
    • DOMEntityReference::__construct — Creates a new DOMEntityReference object
  • DOMException — The DOMException class
  • DOMImplementation — The DOMImplementation class
    • DOMImplementation::__construct — Creates a new DOMImplementation object
    • DOMImplementation::createDocument — Creates a DOMDocument object of the specified type with its document element
    • DOMImplementation::createDocumentType — Creates an empty DOMDocumentType object
    • DOMImplementation::hasFeature — Test if the DOM implementation implements a specific feature
  • DOMNamedNodeMap — The DOMNamedNodeMap class
    • DOMNamedNodeMap::count — Get number of nodes in the map
    • DOMNamedNodeMap::getNamedItem — Retrieves a node specified by name
    • DOMNamedNodeMap::getNamedItemNS — Retrieves a node specified by local name and namespace URI
    • DOMNamedNodeMap::item — Retrieves a node specified by index
  • DOMNode — The DOMNode class
    • DOMNode::appendChild — Adds new child at the end of the children
    • DOMNode::C14N — Canonicalize nodes to a string
    • DOMNode::C14NFile — Canonicalize nodes to a file
    • DOMNode::cloneNode — Clones a node
    • DOMNode::getLineNo — Get line number for a node
    • DOMNode::getNodePath — Get an XPath for a node
    • DOMNode::hasAttributes — Checks if node has attributes
    • DOMNode::hasChildNodes — Checks if node has children
    • DOMNode::insertBefore — Adds a new child before a reference node
    • DOMNode::isDefaultNamespace — Checks if the specified namespaceURI is the default namespace or not
    • DOMNode::isSameNode — Indicates if two nodes are the same node
    • DOMNode::isSupported — Checks if feature is supported for specified version
    • DOMNode::lookupNamespaceUri — Gets the namespace URI of the node based on the prefix
    • DOMNode::lookupPrefix — Gets the namespace prefix of the node based on the namespace URI
    • DOMNode::normalize — Normalizes the node
    • DOMNode::removeChild — Removes child from list of children
    • DOMNode::replaceChild — Replaces a child
  • DOMNodeList — The DOMNodeList class
    • DOMNodeList::count — Get number of nodes in the list
    • DOMNodeList::item — Retrieves a node specified by index
  • DOMNotation — The DOMNotation class
  • DOMProcessingInstruction — The DOMProcessingInstruction class
    • DOMProcessingInstruction::__construct — Creates a new DOMProcessingInstruction object
  • DOMText — The DOMText class
    • DOMText::__construct — Creates a new DOMText object
    • DOMText::isElementContentWhitespace — Returns whether this text node contains whitespace in element content
    • DOMText::isWhitespaceInElementContent — Indicates whether this text node contains whitespace
    • DOMText::splitText — Breaks this node into two nodes at the specified offset
  • DOMXPath — The DOMXPath class
    • DOMXPath::__construct — Creates a new DOMXPath object
    • DOMXPath::evaluate — Evaluates the given XPath expression and returns a typed result if possible
    • DOMXPath::query — Evaluates the given XPath expression
    • DOMXPath::registerNamespace — Registers the namespace with the DOMXPath object
    • DOMXPath::registerPhpFunctions — Register PHP functions as XPath functions
  • DOM Functions
    • dom_import_simplexml — Gets a DOMElement object from a SimpleXMLElement object


Introduction

The DOM extension allows you to operate on XML documents through the DOM API with PHP.

Note:

The DOM extension uses UTF-8 encoding. Use utf8_encode() and utf8_decode() to work with texts in ISO-8859-1 encoding or iconv for other encodings.


Installation

This extension is enabled by default. It may be disabled by using the following option at compile time: --disable-dom


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.

XML constants
Constant | Value | Description
XML_ELEMENT_NODE (integer) | 1 | Node is a DOMElement
XML_ATTRIBUTE_NODE (integer) | 2 | Node is a DOMAttr
XML_TEXT_NODE (integer) | 3 | Node is a DOMText
XML_CDATA_SECTION_NODE (integer) | 4 | Node is a DOMCharacterData
XML_ENTITY_REF_NODE (integer) | 5 | Node is a DOMEntityReference
XML_ENTITY_NODE (integer) | 6 | Node is a DOMEntity
XML_PI_NODE (integer) | 7 | Node is a DOMProcessingInstruction
XML_COMMENT_NODE (integer) | 8 | Node is a DOMComment
XML_DOCUMENT_NODE (integer) | 9 | Node is a DOMDocument
XML_DOCUMENT_TYPE_NODE (integer) | 10 | Node is a DOMDocumentType
XML_DOCUMENT_FRAG_NODE (integer) | 11 | Node is a DOMDocumentFragment
XML_NOTATION_NODE (integer) | 12 | Node is a DOMNotation
XML_HTML_DOCUMENT_NODE (integer) | 13 |
XML_DTD_NODE (integer) | 14 |
XML_ELEMENT_DECL_NODE (integer) | 15 |
XML_ATTRIBUTE_DECL_NODE (integer) | 16 |
XML_ENTITY_DECL_NODE (integer) | 17 |
XML_NAMESPACE_DECL_NODE (integer) | 18 |
XML_ATTRIBUTE_CDATA (integer) | 1 |
XML_ATTRIBUTE_ID (integer) | 2 |
XML_ATTRIBUTE_IDREF (integer) | 3 |
XML_ATTRIBUTE_IDREFS (integer) | 4 |
XML_ATTRIBUTE_ENTITY (integer) | 5 |
XML_ATTRIBUTE_NMTOKEN (integer) | 7 |
XML_ATTRIBUTE_NMTOKENS (integer) | 8 |
XML_ATTRIBUTE_ENUMERATION (integer) | 9 |
XML_ATTRIBUTE_NOTATION (integer) | 10 |
DOMException constants
Constant | Value | Description
DOM_PHP_ERR (integer) | 0 | Error code not part of the DOM specification. Meant for PHP errors.
DOM_INDEX_SIZE_ERR (integer) | 1 | If index or size is negative, or greater than the allowed value.
DOMSTRING_SIZE_ERR (integer) | 2 | If the specified range of text does not fit into a DOMString.
DOM_HIERARCHY_REQUEST_ERR (integer) | 3 | If any node is inserted somewhere it doesn't belong
DOM_WRONG_DOCUMENT_ERR (integer) | 4 | If a node is used in a different document than the one that created it.
DOM_INVALID_CHARACTER_ERR (integer) | 5 | If an invalid or illegal character is specified, such as in a name.
DOM_NO_DATA_ALLOWED_ERR (integer) | 6 | If data is specified for a node which does not support data.
DOM_NO_MODIFICATION_ALLOWED_ERR (integer) | 7 | If an attempt is made to modify an object where modifications are not allowed.
DOM_NOT_FOUND_ERR (integer) | 8 | If an attempt is made to reference a node in a context where it does not exist.
DOM_NOT_SUPPORTED_ERR (integer) | 9 | If the implementation does not support the requested type of object or operation.
DOM_INUSE_ATTRIBUTE_ERR (integer) | 10 | If an attempt is made to add an attribute that is already in use elsewhere.
DOM_INVALID_STATE_ERR (integer) | 11 | If an attempt is made to use an object that is not, or is no longer, usable.
DOM_SYNTAX_ERR (integer) | 12 | If an invalid or illegal string is specified.
DOM_INVALID_MODIFICATION_ERR (integer) | 13 | If an attempt is made to modify the type of the underlying object.
DOM_NAMESPACE_ERR (integer) | 14 | If an attempt is made to create or change an object in a way which is incorrect with regard to namespaces.
DOM_INVALID_ACCESS_ERR (integer) | 15 | If a parameter or an operation is not supported by the underlying object.
DOM_VALIDATION_ERR (integer) | 16 | If a call to a method such as insertBefore or removeChild would make the Node invalid with respect to "partial validity", this exception would be raised and the operation would not be done.


Examples

Many examples in this reference require an XML file. We will use book.xml that contains the following:

Example #1 book.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
 "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd" [
]>
<book id="listing">
 <title>My lists</title>
 <chapter id="books">
  <title>My books</title>
  <para>
   <informaltable>
    <tgroup cols="4">
     <thead>
      <row>
       <entry>Title</entry>
       <entry>Author</entry>
       <entry>Language</entry>
       <entry>ISBN</entry>
      </row>
     </thead>
     <tbody>
      <row>
       <entry>The Grapes of Wrath</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>0140186409</entry>
      </row>
      <row>
       <entry>The Pearl</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>014017737X</entry>
      </row>
      <row>
       <entry>Samarcande</entry>
       <entry>Amine Maalouf</entry>
       <entry>fr</entry>
       <entry>2253051209</entry>
      </row>
      <!-- TODO: I have a lot of remaining books to add.. -->
     </tbody>
    </tgroup>
   </informaltable>
  </para>
 </chapter>
</book>


The DOMAttr class

(PHP 5, PHP 7)

Introduction

DOMAttr represents an attribute in the DOMElement object.

Class synopsis

DOMAttr extends DOMNode {
/* Properties */
public readonly string $name ;
public readonly DOMElement $ownerElement ;
public readonly bool $schemaTypeInfo ;
public readonly bool $specified ;
public string $value ;
/* Inherited properties */
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode $parentNode ;
public readonly DOMNodeList $childNodes ;
public readonly DOMNode $firstChild ;
public readonly DOMNode $lastChild ;
public readonly DOMNode $previousSibling ;
public readonly DOMNode $nextSibling ;
public readonly DOMNamedNodeMap $attributes ;
public readonly DOMDocument $ownerDocument ;
public readonly string $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string $baseURI ;
public string $textContent ;
/* Methods */
public __construct ( string $name [, string $value ] )
public isId ( void ) : bool
/* Inherited methods */
public DOMNode::appendChild ( DOMNode $newnode ) : DOMNode
public DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] ) : string
public DOMNode::C14NFile ( string $uri [, bool $exclusive = FALSE [, bool $with_comments = FALSE [, array $xpath [, array $ns_prefixes ]]]] ) : int
public DOMNode::cloneNode ([ bool $deep ] ) : DOMNode
public DOMNode::getLineNo ( void ) : int
public DOMNode::getNodePath ( void ) : string
public DOMNode::hasAttributes ( void ) : bool
public DOMNode::hasChildNodes ( void ) : bool
public DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] ) : DOMNode
public DOMNode::isDefaultNamespace ( string $namespaceURI ) : bool
public DOMNode::isSameNode ( DOMNode $node ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespaceURI ) : string
public DOMNode::normalize ( void ) : void
public DOMNode::removeChild ( DOMNode $oldnode ) : DOMNode
public DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode ) : DOMNode
}

Properties

name

The name of the attribute

ownerElement

The element which contains the attribute

schemaTypeInfo

Not implemented yet, always is NULL

specified

Not implemented yet, always is NULL

value

The value of the attribute

See Also

  • » W3C specification of Attr

Table of Contents

  • DOMAttr::__construct — Creates a new DOMAttr object
  • DOMAttr::isId — Checks if attribute is a defined ID


Creates a new DOMAttr object

  • « DOMAttr
  • DOMAttr::isId »
  • PHP Manual
  • DOMAttr
  • Creates a new DOMAttr object

DOMAttr::__construct

(PHP 5, PHP 7)

DOMAttr::__construct — Creates a new DOMAttr object

Description

public DOMAttr::__construct ( string $name [, string $value ] )

Creates a new DOMAttr object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writable node, use DOMDocument::createAttribute.

Parameters

name

The tag name of the attribute.

value

The value of the attribute.

Examples

Example #1 Creating a new DOMAttr object

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$attr = $element->setAttributeNode(new DOMAttr('attr', 'attrvalue'));
echo $dom->saveXML();

?>

The above example will output:

<?xml version="1.0" encoding="utf-8"?>
<root attr="attrvalue" />

See Also

  • DOMDocument::createAttribute() - Create new attribute


Checks if attribute is a defined ID

  • « DOMAttr::__construct
  • DOMCdataSection »
  • PHP Manual
  • DOMAttr
  • Checks if attribute is a defined ID

DOMAttr::isId

(PHP 5, PHP 7)

DOMAttr::isId — Checks if attribute is a defined ID

Description

public DOMAttr::isId ( void ) : bool

This function checks if the attribute is a defined ID.

According to the DOM standard this requires a DTD which defines the attribute ID to be of type ID. You need to validate your document with DOMDocument::validate or DOMDocument::validateOnParse before using this function.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 DOMAttr::isId() Example

<?php

$doc = new DomDocument;

// We need to validate our document before refering to the id
$doc->validateOnParse = true;
$doc->Load('book.xml');

// We retrieve the attribute named id of the chapter element
$attr = $doc->getElementsByTagName('chapter')->item(0)->getAttributeNode('id');

var_dump($attr->isId()); // bool(true)

?>


The DOMCdataSection class

(PHP 5, PHP 7)

Introduction

The DOMCdataSection inherits from DOMText for textural representation of CData constructs.

Class synopsis

DOMCdataSection extends DOMText {
/* Inherited properties */
readonly public string $wholeText ;
public string $data ;
readonly public int $length ;
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode $parentNode ;
public readonly DOMNodeList $childNodes ;
public readonly DOMNode $firstChild ;
public readonly DOMNode $lastChild ;
public readonly DOMNode $previousSibling ;
public readonly DOMNode $nextSibling ;
public readonly DOMNamedNodeMap $attributes ;
public readonly DOMDocument $ownerDocument ;
public readonly string $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string $baseURI ;
public string $textContent ;
/* Methods */
public __construct ( string $value )
/* Inherited methods */
public DOMText::isElementContentWhitespace ( void ) : bool
public DOMText::isWhitespaceInElementContent ( void ) : bool
public DOMText::splitText ( int $offset ) : DOMText
public DOMCharacterData::appendData ( string $data ) : void
public DOMCharacterData::deleteData ( int $offset , int $count ) : void
public DOMCharacterData::insertData ( int $offset , string $data ) : void
public DOMCharacterData::replaceData ( int $offset , int $count , string $data ) : void
public DOMCharacterData::substringData ( int $offset , int $count ) : string
public DOMNode::appendChild ( DOMNode $newnode ) : DOMNode
public DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] ) : string
public DOMNode::C14NFile ( string $uri [, bool $exclusive = FALSE [, bool $with_comments = FALSE [, array $xpath [, array $ns_prefixes ]]]] ) : int
public DOMNode::cloneNode ([ bool $deep ] ) : DOMNode
public DOMNode::getLineNo ( void ) : int
public DOMNode::getNodePath ( void ) : string
public DOMNode::hasAttributes ( void ) : bool
public DOMNode::hasChildNodes ( void ) : bool
public DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] ) : DOMNode
public DOMNode::isDefaultNamespace ( string $namespaceURI ) : bool
public DOMNode::isSameNode ( DOMNode $node ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespaceURI ) : string
public DOMNode::normalize ( void ) : void
public DOMNode::removeChild ( DOMNode $oldnode ) : DOMNode
public DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode ) : DOMNode
}

Table of Contents

  • DOMCdataSection::__construct — Constructs a new DOMCdataSection object


Constructs a new DOMCdataSection object

  • « DOMCdataSection
  • DOMCharacterData »
  • PHP Manual
  • DOMCdataSection
  • Constructs a new DOMCdataSection object

DOMCdataSection::__construct

(PHP 5, PHP 7)

DOMCdataSection::__construct — Constructs a new DOMCdataSection object

Description

public DOMCdataSection::__construct ( string $value )

Constructs a new CDATA node. This works like the DOMText class.

Parameters

value

The value of the CDATA node. If not supplied, an empty CDATA node is created.

Examples

Example #1 Creating a new DOMCdataSection object

<?php

$dom = new DOMDocument('1.0', 'utf-8');
$element = $dom->appendChild(new DOMElement('root'));
$text = $element->appendChild(new DOMCdataSection('root value'));
echo $dom->saveXML();

?>

The above example will output:

<?xml version="1.0" encoding="utf-8"?>
<root><![CDATA[root value]]></root>

See Also

  • DOMText::__construct() - Creates a new DOMText object
  • DOMDocument::createTextNode() - Create new text node


The DOMCharacterData class

(PHP 5, PHP 7)

Introduction

Represents nodes with character data. No nodes directly correspond to this class, but other nodes do inherit from it.

Class synopsis

DOMCharacterData extends DOMNode {
/* Properties */
public string $data ;
readonly public int $length ;
/* Inherited properties */
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode $parentNode ;
public readonly DOMNodeList $childNodes ;
public readonly DOMNode $firstChild ;
public readonly DOMNode $lastChild ;
public readonly DOMNode $previousSibling ;
public readonly DOMNode $nextSibling ;
public readonly DOMNamedNodeMap $attributes ;
public readonly DOMDocument $ownerDocument ;
public readonly string $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string $baseURI ;
public string $textContent ;
/* Methods */
public appendData ( string $data ) : void
public deleteData ( int $offset , int $count ) : void
public insertData ( int $offset , string $data ) : void
public replaceData ( int $offset , int $count , string $data ) : void
public substringData ( int $offset , int $count ) : string
/* Inherited methods */
public DOMNode::appendChild ( DOMNode $newnode ) : DOMNode
public DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] ) : string
public DOMNode::C14NFile ( string $uri [, bool $exclusive = FALSE [, bool $with_comments = FALSE [, array $xpath [, array $ns_prefixes ]]]] ) : int
public DOMNode::cloneNode ([ bool $deep ] ) : DOMNode
public DOMNode::getLineNo ( void ) : int
public DOMNode::getNodePath ( void ) : string
public DOMNode::hasAttributes ( void ) : bool
public DOMNode::hasChildNodes ( void ) : bool
public DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] ) : DOMNode
public DOMNode::isDefaultNamespace ( string $namespaceURI ) : bool
public DOMNode::isSameNode ( DOMNode $node ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespaceURI ) : string
public DOMNode::normalize ( void ) : void
public DOMNode::removeChild ( DOMNode $oldnode ) : DOMNode
public DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode ) : DOMNode
}

Properties

data

The contents of the node.

length

The length of the contents.

See Also

  • » W3C specification of CharacterData

Table of Contents

  • DOMCharacterData::appendData — Append the string to the end of the character data of the node
  • DOMCharacterData::deleteData — Remove a range of characters from the node
  • DOMCharacterData::insertData — Insert a string at the specified 16-bit unit offset
  • DOMCharacterData::replaceData — Replace a substring within the DOMCharacterData node
  • DOMCharacterData::substringData — Extracts a range of data from the node


Append the string to the end of the character data of the node

  • « DOMCharacterData
  • DOMCharacterData::deleteData »
  • PHP Manual
  • DOMCharacterData
  • Append the string to the end of the character data of the node

DOMCharacterData::appendData

(PHP 5, PHP 7)

DOMCharacterData::appendData — Append the string to the end of the character data of the node

Description

public DOMCharacterData::appendData ( string $data ) : void

Append the string data to the end of the character data of the node.

Parameters

data

The string to append.

Return Values

No value is returned.

See Also

  • DOMCharacterData::deleteData() - Remove a range of characters from the node
  • DOMCharacterData::insertData() - Insert a string at the specified 16-bit unit offset
  • DOMCharacterData::replaceData() - Replace a substring within the DOMCharacterData node
  • DOMCharacterData::substringData() - Extracts a range of data from the node


Remove a range of characters from the node

  • « DOMCharacterData::appendData
  • DOMCharacterData::insertData »
  • PHP Manual
  • DOMCharacterData
  • Remove a range of characters from the node

DOMCharacterData::deleteData

(PHP 5, PHP 7)

DOMCharacterData::deleteData — Remove a range of characters from the node

Description

public DOMCharacterData::deleteData ( int $offset , int $count ) : void

Deletes count characters starting from position offset.

Parameters

offset

The offset from which to start removing.

count

The number of characters to delete. If the sum of offset and count exceeds the length, then all characters to the end of the data are deleted.

Return Values

No value is returned.

Errors/Exceptions

DOM_INDEX_SIZE_ERR

Raised if offset is negative or greater than the number of 16-bit units in data, or if count is negative.

See Also

  • DOMCharacterData::appendData() - Append the string to the end of the character data of the node
  • DOMCharacterData::insertData() - Insert a string at the specified 16-bit unit offset
  • DOMCharacterData::replaceData() - Replace a substring within the DOMCharacterData node
  • DOMCharacterData::substringData() - Extracts a range of data from the node


Insert a string at the specified 16-bit unit offset

  • « DOMCharacterData::deleteData
  • DOMCharacterData::replaceData »
  • PHP Manual
  • DOMCharacterData
  • Insert a string at the specified 16-bit unit offset

DOMCharacterData::insertData

(PHP 5, PHP 7)

DOMCharacterData::insertData — Insert a string at the specified 16-bit unit offset

Description

public DOMCharacterData::insertData ( int $offset , string $data ) : void

Inserts string data at position offset.

Parameters

offset

The character offset at which to insert.

data

The string to insert.

Return Values

No value is returned.

Errors/Exceptions

DOM_INDEX_SIZE_ERR

Raised if offset is negative or greater than the number of 16-bit units in data.

See Also

  • DOMCharacterData::appendData() - Append the string to the end of the character data of the node
  • DOMCharacterData::deleteData() - Remove a range of characters from the node
  • DOMCharacterData::replaceData() - Replace a substring within the DOMCharacterData node
  • DOMCharacterData::substringData() - Extracts a range of data from the node


Replace a substring within the DOMCharacterData node

  • « DOMCharacterData::insertData
  • DOMCharacterData::substringData »
  • PHP Manual
  • DOMCharacterData
  • Replace a substring within the DOMCharacterData node

DOMCharacterData::replaceData

(PHP 5, PHP 7)

DOMCharacterData::replaceData — Replace a substring within the DOMCharacterData node

Description

public DOMCharacterData::replaceData ( int $offset , int $count , string $data ) : void

Replace count characters starting from position offset with data.

Parameters

offset

The offset from which to start replacing.

count

The number of characters to replace. If the sum of offset and count exceeds the length, then all characters to the end of the data are replaced.

data

The string with which the range must be replaced.

Return Values

No value is returned.

Errors/Exceptions

DOM_INDEX_SIZE_ERR

Raised if offset is negative or greater than the number of 16-bit units in data, or if count is negative.

See Also

  • DOMCharacterData::appendData() - Append the string to the end of the character data of the node
  • DOMCharacterData::deleteData() - Remove a range of characters from the node
  • DOMCharacterData::insertData() - Insert a string at the specified 16-bit unit offset
  • DOMCharacterData::substringData() - Extracts a range of data from the node


Extracts a range of data from the node

  • « DOMCharacterData::replaceData
  • DOMComment »
  • PHP Manual
  • DOMCharacterData
  • Extracts a range of data from the node

DOMCharacterData::substringData

(PHP 5, PHP 7)

DOMCharacterData::substringData — Extracts a range of data from the node

Description

public DOMCharacterData::substringData ( int $offset , int $count ) : string

Returns the specified substring.

Parameters

offset

Start offset of substring to extract.

count

The number of characters to extract.

Return Values

The specified substring. If the sum of offset and count exceeds the length, then all 16-bit units to the end of the data are returned.

Errors/Exceptions

DOM_INDEX_SIZE_ERR

Raised if offset is negative or greater than the number of 16-bit units in data, or if count is negative.

See Also

  • DOMCharacterData::appendData() - Append the string to the end of the character data of the node
  • DOMCharacterData::deleteData() - Remove a range of characters from the node
  • DOMCharacterData::insertData() - Insert a string at the specified 16-bit unit offset
  • DOMCharacterData::replaceData() - Replace a substring within the DOMCharacterData node


The DOMComment class

(PHP 5, PHP 7)

Introduction

Represents comment nodes, characters delimited by <!-- and -->.

Class synopsis

DOMComment extends DOMCharacterData {
/* Inherited properties */
public string $data ;
readonly public int $length ;
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode $parentNode ;
public readonly DOMNodeList $childNodes ;
public readonly DOMNode $firstChild ;
public readonly DOMNode $lastChild ;
public readonly DOMNode $previousSibling ;
public readonly DOMNode $nextSibling ;
public readonly DOMNamedNodeMap $attributes ;
public readonly DOMDocument $ownerDocument ;
public readonly string $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string $baseURI ;
public string $textContent ;
/* Methods */
public __construct ([ string $value ] )
/* Inherited methods */
public DOMCharacterData::appendData ( string $data ) : void
public DOMCharacterData::deleteData ( int $offset , int $count ) : void
public DOMCharacterData::insertData ( int $offset , string $data ) : void
public DOMCharacterData::replaceData ( int $offset , int $count , string $data ) : void
public DOMCharacterData::substringData ( int $offset , int $count ) : string
public DOMNode::appendChild ( DOMNode $newnode ) : DOMNode
public DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] ) : string
public DOMNode::C14NFile ( string $uri [, bool $exclusive = FALSE [, bool $with_comments = FALSE [, array $xpath [, array $ns_prefixes ]]]] ) : int
public DOMNode::cloneNode ([ bool $deep ] ) : DOMNode
public DOMNode::getLineNo ( void ) : int
public DOMNode::getNodePath ( void ) : string
public DOMNode::hasAttributes ( void ) : bool
public DOMNode::hasChildNodes ( void ) : bool
public DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] ) : DOMNode
public DOMNode::isDefaultNamespace ( string $namespaceURI ) : bool
public DOMNode::isSameNode ( DOMNode $node ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespaceURI ) : string
public DOMNode::normalize ( void ) : void
public DOMNode::removeChild ( DOMNode $oldnode ) : DOMNode
public DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode ) : DOMNode
}

See Also

  • » W3C specification of Comment

Table of Contents

  • DOMComment::__construct — Creates a new DOMComment object


Creates a new DOMComment object

  • « DOMComment
  • DOMDocument »
  • PHP Manual
  • DOMComment
  • Creates a new DOMComment object

DOMComment::__construct

(PHP 5, PHP 7)

DOMComment::__construct — Creates a new DOMComment object

Description

public DOMComment::__construct ([ string $value ] )

Creates a new DOMComment object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writeable node, use DOMDocument::createComment.

Parameters

value

The value of the comment.

Examples

Example #1 Creating a new DOMComment

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$comment = $element->appendChild(new DOMComment('root comment'));
echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?><root><!--root comment--></root> */

?>

See Also

  • DOMDocument::createComment() - Create new comment node


The DOMDocument class

(PHP 5, PHP 7)

Introduction

Represents an entire HTML or XML document; serves as the root of the document tree.

Class synopsis

DOMDocument extends DOMNode {
/* Properties */
readonly public string $actualEncoding ;
readonly public DOMConfiguration $config ;
readonly public DOMDocumentType $doctype ;
readonly public DOMElement $documentElement ;
public string $documentURI ;
public string $encoding ;
public bool $formatOutput ;
readonly public DOMImplementation $implementation ;
public bool $preserveWhiteSpace = TRUE ;
public bool $recover ;
public bool $resolveExternals ;
public bool $standalone ;
public bool $strictErrorChecking = TRUE ;
public bool $substituteEntities ;
public bool $validateOnParse = FALSE ;
public string $version ;
readonly public string $xmlEncoding ;
public bool $xmlStandalone ;
public string $xmlVersion ;
/* Inherited properties */
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode $parentNode ;
public readonly DOMNodeList $childNodes ;
public readonly DOMNode $firstChild ;
public readonly DOMNode $lastChild ;
public readonly DOMNode $previousSibling ;
public readonly DOMNode $nextSibling ;
public readonly DOMNamedNodeMap $attributes ;
public readonly DOMDocument $ownerDocument ;
public readonly string $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string $baseURI ;
public string $textContent ;
/* Methods */
public __construct ([ string $version [, string $encoding ]] )
public createAttribute ( string $name ) : DOMAttr
public createAttributeNS ( string $namespaceURI , string $qualifiedName ) : DOMAttr
public createCDATASection ( string $data ) : DOMCDATASection
public createComment ( string $data ) : DOMComment
public createDocumentFragment ( void ) : DOMDocumentFragment
public createElement ( string $name [, string $value ] ) : DOMElement
public createElementNS ( string $namespaceURI , string $qualifiedName [, string $value ] ) : DOMElement
public createEntityReference ( string $name ) : DOMEntityReference
public createProcessingInstruction ( string $target [, string $data ] ) : DOMProcessingInstruction
public createTextNode ( string $content ) : DOMText
public getElementById ( string $elementId ) : DOMElement
public getElementsByTagName ( string $name ) : DOMNodeList
public getElementsByTagNameNS ( string $namespaceURI , string $localName ) : DOMNodeList
public importNode ( DOMNode $importedNode [, bool $deep = FALSE ] ) : DOMNode
public load ( string $filename [, int $options = 0 ] ) : mixed
public loadHTML ( string $source [, int $options = 0 ] ) : bool
public loadHTMLFile ( string $filename [, int $options = 0 ] ) : bool
public loadXML ( string $source [, int $options = 0 ] ) : mixed
public normalizeDocument ( void ) : void
public registerNodeClass ( string $baseclass , string $extendedclass ) : bool
public relaxNGValidate ( string $filename ) : bool
public relaxNGValidateSource ( string $source ) : bool
public save ( string $filename [, int $options = 0 ] ) : int
public saveHTML ([ DOMNode $node = NULL ] ) : string
public saveHTMLFile ( string $filename ) : int
public saveXML ([ DOMNode $node [, int $options = 0 ]] ) : string
public schemaValidate ( string $filename [, int $flags = 0 ] ) : bool
public schemaValidateSource ( string $source [, int $flags ] ) : bool
public validate ( void ) : bool
public xinclude ([ int $options = 0 ] ) : int
/* Inherited methods */
public DOMNode::appendChild ( DOMNode $newnode ) : DOMNode
public DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] ) : string
public DOMNode::C14NFile ( string $uri [, bool $exclusive = FALSE [, bool $with_comments = FALSE [, array $xpath [, array $ns_prefixes ]]]] ) : int
public DOMNode::cloneNode ([ bool $deep ] ) : DOMNode
public DOMNode::getLineNo ( void ) : int
public DOMNode::getNodePath ( void ) : string
public DOMNode::hasAttributes ( void ) : bool
public DOMNode::hasChildNodes ( void ) : bool
public DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] ) : DOMNode
public DOMNode::isDefaultNamespace ( string $namespaceURI ) : bool
public DOMNode::isSameNode ( DOMNode $node ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespaceURI ) : string
public DOMNode::normalize ( void ) : void
public DOMNode::removeChild ( DOMNode $oldnode ) : DOMNode
public DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode ) : DOMNode
}

Properties

actualEncoding

Deprecated. Actual encoding of the document, is a readonly equivalent to encoding.

config

Deprecated. Configuration used when DOMDocument::normalizeDocument() is invoked.

doctype

The Document Type Declaration associated with this document.

documentElement

This is a convenience attribute that allows direct access to the child node that is the document element of the document.

documentURI

The location of the document or NULL if undefined.

encoding

Encoding of the document, as specified by the XML declaration. This attribute is not present in the final DOM Level 3 specification, but is the only way of manipulating XML document encoding in this implementation.

formatOutput

Nicely formats output with indentation and extra space.

implementation

The DOMImplementation object that handles this document.

preserveWhiteSpace

Do not remove redundant white space. Default to TRUE.

recover

Proprietary. Enables recovery mode, i.e. trying to parse non-well formed documents. This attribute is not part of the DOM specification and is specific to libxml.

resolveExternals

Set it to TRUE to load external entities from a doctype declaration. This is useful for including character entities in your XML document.

standalone

Deprecated. Whether or not the document is standalone, as specified by the XML declaration, corresponds to xmlStandalone.

strictErrorChecking

Throws DOMException on errors. Default to TRUE.

substituteEntities

Proprietary. Whether or not to substitute entities. This attribute is not part of the DOM specification and is specific to libxml.

validateOnParse

Loads and validates against the DTD. Default to FALSE.

version

Deprecated. Version of XML, corresponds to xmlVersion.

xmlEncoding

An attribute specifying, as part of the XML declaration, the encoding of this document. This is NULL when unspecified or when it is not known, such as when the Document was created in memory.

xmlStandalone

An attribute specifying, as part of the XML declaration, whether this document is standalone. This is FALSE when unspecified.

xmlVersion

An attribute specifying, as part of the XML declaration, the version number of this document. If there is no declaration and if this document supports the "XML" feature, the value is "1.0".

Notes

Note:

The DOM extension uses UTF-8 encoding. Use utf8_encode() and utf8_decode() to work with texts in ISO-8859-1 encoding or iconv for other encodings.

See Also

  • » W3C specification for Document

Table of Contents

  • DOMDocument::__construct — Creates a new DOMDocument object
  • DOMDocument::createAttribute — Create new attribute
  • DOMDocument::createAttributeNS — Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection — Create new cdata node
  • DOMDocument::createComment — Create new comment node
  • DOMDocument::createDocumentFragment — Create new document fragment
  • DOMDocument::createElement — Create new element node
  • DOMDocument::createElementNS — Create new element node with an associated namespace
  • DOMDocument::createEntityReference — Create new entity reference node
  • DOMDocument::createProcessingInstruction — Creates new PI node
  • DOMDocument::createTextNode — Create new text node
  • DOMDocument::getElementById — Searches for an element with a certain id
  • DOMDocument::getElementsByTagName — Searches for all elements with given local tag name
  • DOMDocument::getElementsByTagNameNS — Searches for all elements with given tag name in specified namespace
  • DOMDocument::importNode — Import node into current document
  • DOMDocument::load — Load XML from a file
  • DOMDocument::loadHTML — Load HTML from a string
  • DOMDocument::loadHTMLFile — Load HTML from a file
  • DOMDocument::loadXML — Load XML from a string
  • DOMDocument::normalizeDocument — Normalizes the document
  • DOMDocument::registerNodeClass — Register extended class used to create base node type
  • DOMDocument::relaxNGValidate — Performs relaxNG validation on the document
  • DOMDocument::relaxNGValidateSource — Performs relaxNG validation on the document
  • DOMDocument::save — Dumps the internal XML tree back into a file
  • DOMDocument::saveHTML — Dumps the internal document into a string using HTML formatting
  • DOMDocument::saveHTMLFile — Dumps the internal document into a file using HTML formatting
  • DOMDocument::saveXML — Dumps the internal XML tree back into a string
  • DOMDocument::schemaValidate — Validates a document based on a schema
  • DOMDocument::schemaValidateSource — Validates a document based on a schema
  • DOMDocument::validate — Validates the document based on its DTD
  • DOMDocument::xinclude — Substitutes XIncludes in a DOMDocument Object


Creates a new DOMDocument object

  • « DOMDocument
  • DOMDocument::createAttribute »
  • PHP Manual
  • DOMDocument
  • Creates a new DOMDocument object

DOMDocument::__construct

(PHP 5, PHP 7)

DOMDocument::__construct — Creates a new DOMDocument object

Description

public DOMDocument::__construct ([ string $version [, string $encoding ]] )

Creates a new DOMDocument object.

Parameters

version

The version number of the document as part of the XML declaration.

encoding

The encoding of the document as part of the XML declaration.

Examples

Example #1 Creating a new DOMDocument

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');

echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?> */

?>

See Also

  • DOMImplementation::createDocument() - Creates a DOMDocument object of the specified type with its document element


Create new attribute

  • « DOMDocument::__construct
  • DOMDocument::createAttributeNS »
  • PHP Manual
  • DOMDocument
  • Create new attribute

DOMDocument::createAttribute

(PHP 5, PHP 7)

DOMDocument::createAttribute — Create new attribute

Description

public DOMDocument::createAttribute ( string $name ) : DOMAttr

This function creates a new instance of class DOMAttr. This node will not show up in the document unless it is inserted with (e.g.) DOMNode::appendChild().

Parameters

name

The name of the attribute.

Return Values

The new DOMAttr or FALSE if an error occurred.

Errors/Exceptions

DOM_INVALID_CHARACTER_ERR

Raised if name contains an invalid character.

See Also

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node


Create new attribute node with an associated namespace

  • « DOMDocument::createAttribute
  • DOMDocument::createCDATASection »
  • PHP Manual
  • DOMDocument
  • Create new attribute node with an associated namespace

DOMDocument::createAttributeNS

(PHP 5, PHP 7)

DOMDocument::createAttributeNS — Create new attribute node with an associated namespace

Description

public DOMDocument::createAttributeNS ( string $namespaceURI , string $qualifiedName ) : DOMAttr

This function creates a new instance of class DOMAttr. This node will not show up in the document unless it is inserted with (e.g.) DOMNode::appendChild().

Parameters

namespaceURI

The URI of the namespace.

qualifiedName

The tag name and prefix of the attribute, as prefix:tagname.

Return Values

The new DOMAttr or FALSE if an error occurred.

Errors/Exceptions

DOM_INVALID_CHARACTER_ERR

Raised if qualifiedName contains an invalid character.

DOM_NAMESPACE_ERR

Raised if qualifiedName is a malformed qualified name, or if qualifiedName has a prefix and namespaceURI is NULL.

See Also

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node


Create new cdata node

  • « DOMDocument::createAttributeNS
  • DOMDocument::createComment »
  • PHP Manual
  • DOMDocument
  • Create new cdata node

DOMDocument::createCDATASection

(PHP 5, PHP 7)

DOMDocument::createCDATASection — Create new cdata node

Description

public DOMDocument::createCDATASection ( string $data ) : DOMCDATASection

This function creates a new instance of class DOMCDATASection. This node will not show up in the document unless it is inserted with (e.g.) DOMNode::appendChild().

Parameters

data

The content of the cdata.

Return Values

The new DOMCDATASection or FALSE if an error occurred.

See Also

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node


Create new comment node

  • « DOMDocument::createCDATASection
  • DOMDocument::createDocumentFragment »
  • PHP Manual
  • DOMDocument
  • Create new comment node

DOMDocument::createComment

(PHP 5, PHP 7)

DOMDocument::createComment — Create new comment node

Description

public DOMDocument::createComment ( string $data ) : DOMComment

This function creates a new instance of class DOMComment. This node will not show up in the document unless it is inserted with (e.g.) DOMNode::appendChild().

Parameters

data

The content of the comment.

Return Values

The new DOMComment or FALSE if an error occurred.

See Also

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node


Create new document fragment

  • « DOMDocument::createComment
  • DOMDocument::createElement »
  • PHP Manual
  • DOMDocument
  • Create new document fragment

DOMDocument::createDocumentFragment

(PHP 5, PHP 7)

DOMDocument::createDocumentFragment — Create new document fragment

Description

public DOMDocument::createDocumentFragment ( void ) : DOMDocumentFragment

This function creates a new instance of class DOMDocumentFragment. This node will not show up in the document unless it is inserted with (e.g.) DOMNode::appendChild().

Return Values

The new DOMDocumentFragment or FALSE if an error occurred.

See Also

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node


Create new element node

  • « DOMDocument::createDocumentFragment
  • DOMDocument::createElementNS »
  • PHP Manual
  • DOMDocument
  • Create new element node

DOMDocument::createElement

(PHP 5, PHP 7)

DOMDocument::createElement — Create new element node

Description

public DOMDocument::createElement ( string $name [, string $value ] ) : DOMElement

This function creates a new instance of class DOMElement. This node will not show up in the document unless it is inserted with (e.g.) DOMNode::appendChild().

Parameters

name

The tag name of the element.

value

The value of the element. By default, an empty element will be created. The value can also be set later with DOMElement::$nodeValue.

The value is used verbatim except that the < and > entity references will escaped. Note that & has to be manually escaped; otherwise it is regarded as starting an entity reference. Also " won't be escaped.

Return Values

Returns a new instance of class DOMElement or FALSE if an error occurred.

Errors/Exceptions

DOM_INVALID_CHARACTER_ERR

Raised if name contains an invalid character.

Examples

Example #1 Creating a new element and inserting it as root

<?php

$dom = new DOMDocument('1.0', 'utf-8');

$element = $dom->createElement('test', 'This is the root element!');

// We insert the new element as root (child of the document)
$dom->appendChild($element);

echo $dom->saveXML();
?>

The above example will output:

<?xml version="1.0" encoding="utf-8"?>
<test>This is the root element!</test>

Example #2 Passing text containing an unescaped & as value

<?php
$dom = new DOMDocument('1.0', 'utf-8');
$element = $dom->createElement('foo', 'me & you');
$dom->appendChild($element);
echo $dom->saveXML();
?>

The above example will output something similar to:

Warning: DOMDocument::createElement(): unterminated entity reference             you in /in/BjTCg on line 4
<?xml version="1.0" encoding="utf-8"?>
<foo/>

Notes

Note:

The value will not be escaped. Use DOMDocument::createTextNode() to create a text node with escaping support.

See Also

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node


Create new element node with an associated namespace

  • « DOMDocument::createElement
  • DOMDocument::createEntityReference »
  • PHP Manual
  • DOMDocument
  • Create new element node with an associated namespace

DOMDocument::createElementNS

(PHP 5, PHP 7)

DOMDocument::createElementNS — Create new element node with an associated namespace

Description

public DOMDocument::createElementNS ( string $namespaceURI , string $qualifiedName [, string $value ] ) : DOMElement

This function creates a new element node with an associated namespace. This node will not show up in the document unless it is inserted with (e.g.) DOMNode::appendChild().

Parameters

namespaceURI

The URI of the namespace.

qualifiedName

The qualified name of the element, as prefix:tagname.

value

The value of the element. By default, an empty element will be created. You can also set the value later with DOMElement::$nodeValue.

Return Values

The new DOMElement or FALSE if an error occurred.

Errors/Exceptions

DOM_INVALID_CHARACTER_ERR

Raised if qualifiedName contains an invalid character.

DOM_NAMESPACE_ERR

Raised if qualifiedName is a maformed qualified name.

Examples

Example #1 Creating a new element and inserting it as root

<?php

$dom = new DOMDocument('1.0', 'utf-8');

$element = $dom->createElementNS('http://www.example.com/XFoo', 'xfoo:test', 'This is the root element!');

// We insert the new element as root (child of the document)
$dom->appendChild($element);

echo $dom->saveXML();
?>

The above example will output:

<?xml version="1.0" encoding="utf-8"?>
<xfoo:test xmlns:xfoo="http://www.example.com/XFoo">This is the root element!</xfoo:test>

Example #2 A namespace prefix example

<?php
$doc  = new DOMDocument('1.0', 'utf-8');
$doc->formatOutput = true;
$root = $doc->createElementNS('http://www.w3.org/2005/Atom', 'element');
$doc->appendChild($root);
$root->setAttributeNS('http://www.w3.org/2000/xmlns/' ,'xmlns:g', 'http://base.google.com/ns/1.0');
$item = $doc->createElementNS('http://base.google.com/ns/1.0', 'g:item_type', 'house');
$root->appendChild($item);

echo $doc->saveXML(), "\n";

echo $item->namespaceURI, "\n"; // Outputs: http://base.google.com/ns/1.0
echo $item->prefix, "\n";       // Outputs: g
echo $item->localName, "\n";    // Outputs: item_type
?>

The above example will output:

<?xml version="1.0" encoding="utf-8"?>
<element xmlns="http://www.w3.org/2005/Atom" xmlns:g="http://base.google.com/ns/1.0">
  <g:item_type>house</g:item_type>
</element>

http://base.google.com/ns/1.0
g
item_type

See Also

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node


Create new entity reference node

  • « DOMDocument::createElementNS
  • DOMDocument::createProcessingInstruction »
  • PHP Manual
  • DOMDocument
  • Create new entity reference node

DOMDocument::createEntityReference

(PHP 5, PHP 7)

DOMDocument::createEntityReference — Create new entity reference node

Description

public DOMDocument::createEntityReference ( string $name ) : DOMEntityReference

This function creates a new instance of class DOMEntityReference. This node will not show up in the document unless it is inserted with (e.g.) DOMNode::appendChild().

Parameters

name

The content of the entity reference, e.g. the entity reference minus the leading & and the trailing ; characters.

Return Values

The new DOMEntityReference or FALSE if an error occurred.

Errors/Exceptions

DOM_INVALID_CHARACTER_ERR

Raised if name contains an invalid character.

See Also

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node


Creates new PI node

  • « DOMDocument::createEntityReference
  • DOMDocument::createTextNode »
  • PHP Manual
  • DOMDocument
  • Creates new PI node

DOMDocument::createProcessingInstruction

(PHP 5, PHP 7)

DOMDocument::createProcessingInstruction — Creates new PI node

Description

public DOMDocument::createProcessingInstruction ( string $target [, string $data ] ) : DOMProcessingInstruction

This function creates a new instance of class DOMProcessingInstruction. This node will not show up in the document unless it is inserted with (e.g.) DOMNode::appendChild().

Parameters

target

The target of the processing instruction.

data

The content of the processing instruction.

Return Values

The new DOMProcessingInstruction or FALSE if an error occurred.

Errors/Exceptions

DOM_INVALID_CHARACTER_ERR

Raised if target contains an invalid character.

See Also

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createTextNode() - Create new text node


Create new text node

  • « DOMDocument::createProcessingInstruction
  • DOMDocument::getElementById »
  • PHP Manual
  • DOMDocument
  • Create new text node

DOMDocument::createTextNode

(PHP 5, PHP 7)

DOMDocument::createTextNode — Create new text node

Description

public DOMDocument::createTextNode ( string $content ) : DOMText

This function creates a new instance of class DOMText. This node will not show up in the document unless it is inserted with (e.g.) DOMNode::appendChild().

Parameters

content

The content of the text.

Return Values

The new DOMText or FALSE if an error occurred.

See Also

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node


Searches for an element with a certain id

  • « DOMDocument::createTextNode
  • DOMDocument::getElementsByTagName »
  • PHP Manual
  • DOMDocument
  • Searches for an element with a certain id

DOMDocument::getElementById

(PHP 5, PHP 7)

DOMDocument::getElementById — Searches for an element with a certain id

Description

public DOMDocument::getElementById ( string $elementId ) : DOMElement

This function is similar to DOMDocument::getElementsByTagName but searches for an element with a given id.

For this function to work, you will need either to set some ID attributes with DOMElement::setIdAttribute or a DTD which defines an attribute to be of type ID. In the later case, you will need to validate your document with DOMDocument::validate or DOMDocument::$validateOnParse before using this function.

Parameters

elementId

The unique id value for an element.

Return Values

Returns the DOMElement or NULL if the element is not found.

Examples

Example #1 DOMDocument::getElementById() Example

The following examples use book.xml which contains the following:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE books [
  <!ELEMENT books   (book+)>
  <!ELEMENT book    (title, author+, xhtml:blurb?)>
  <!ELEMENT title   (#PCDATA)>
  <!ELEMENT blurb   (#PCDATA)>
  <!ELEMENT author  (#PCDATA)>
  <!ATTLIST books   xmlns        CDATA  #IMPLIED>
  <!ATTLIST books   xmlns:xhtml  CDATA  #IMPLIED>
  <!ATTLIST book    id           ID     #IMPLIED>
  <!ATTLIST author  email        CDATA  #IMPLIED>
]>
<?xml-stylesheet type="text/xsl" href="style.xsl"?>
<books xmlns="http://books.php/" xmlns:xhtml="http://www.w3.org/1999/xhtml">
  <book id="php-basics">
    <title>PHP Basics</title>
    <author email="jim.smith@basics.php">Jim Smith</author>
    <author email="jane.smith@basics.php">Jane Smith</author>
    <xhtml:blurb><![CDATA[
<p><em>PHP Basics</em> provides an introduction to PHP.</p>
]]></xhtml:blurb>
  </book>
  <book id="php-advanced">
    <title>PHP Advanced Programming</title>
    <author email="jon.doe@advanced.php">Jon Doe</author>
  </book>
</books>
<?php

$doc = new DomDocument;

// We need to validate our document before refering to the id
$doc->validateOnParse = true;
$doc->Load('book.xml');

echo "The element whose id is 'php-basics' is: " . $doc->getElementById('php-basics')->tagName . "\n";

?>

The above example will output:

The element whose id is 'php-basics' is: book

See Also

  • DOMDocument::getElementsByTagName() - Searches for all elements with given local tag name


Searches for all elements with given local tag name

  • « DOMDocument::getElementById
  • DOMDocument::getElementsByTagNameNS »
  • PHP Manual
  • DOMDocument
  • Searches for all elements with given local tag name

DOMDocument::getElementsByTagName

(PHP 5, PHP 7)

DOMDocument::getElementsByTagName — Searches for all elements with given local tag name

Description

public DOMDocument::getElementsByTagName ( string $name ) : DOMNodeList

This function returns a new instance of class DOMNodeList containing all the elements with a given local tag name.

Parameters

name

The local name (without namespace) of the tag to match on. The special value * matches all tags.

Return Values

A new DOMNodeList object containing all the matched elements.

Examples

Example #1 Basic Usage Example

<?php
$xml = <<< XML
<?xml version="1.0" encoding="utf-8"?>
<books>
 <book>Patterns of Enterprise Application Architecture</book>
 <book>Design Patterns: Elements of Reusable Software Design</book>
 <book>Clean Code</book>
</books>
XML;

$dom = new DOMDocument;
$dom->loadXML($xml);
$books = $dom->getElementsByTagName('book');
foreach ($books as $book) {
    echo $book->nodeValue, PHP_EOL;
}
?>

The above example will output:

Patterns of Enterprise Application Architecture
Design Patterns: Elements of Reusable Software Design
Clean Code

See Also

  • DOMDocument::getElementsByTagNameNS() - Searches for all elements with given tag name in specified namespace


Searches for all elements with given tag name in specified namespace

  • « DOMDocument::getElementsByTagName
  • DOMDocument::importNode »
  • PHP Manual
  • DOMDocument
  • Searches for all elements with given tag name in specified namespace

DOMDocument::getElementsByTagNameNS

(PHP 5, PHP 7)

DOMDocument::getElementsByTagNameNS — Searches for all elements with given tag name in specified namespace

Description

public DOMDocument::getElementsByTagNameNS ( string $namespaceURI , string $localName ) : DOMNodeList

Returns a DOMNodeList of all elements with a given local name and a namespace URI.

Parameters

namespaceURI

The namespace URI of the elements to match on. The special value * matches all namespaces.

localName

The local name of the elements to match on. The special value * matches all local names.

Return Values

A new DOMNodeList object containing all the matched elements.

Examples

Example #1 Get all the XInclude elements

<?php

$xml = <<<EOD
<?xml version="1.0" ?>
<chapter xmlns:xi="http://www.w3.org/2001/XInclude">
<title>Books of the other guy..</title>
<para>
 <xi:include href="book.xml">
  <xi:fallback>
   <error>xinclude: book.xml not found</error>
  </xi:fallback>
 </xi:include>
 <include>
  This is another namespace
 </include>
</para>
</chapter>
EOD;
$dom = new DOMDocument;

// load the XML string defined above
$dom->loadXML($xml);

foreach ($dom->getElementsByTagNameNS('http://www.w3.org/2001/XInclude', '*') as $element) {
    echo 'local name: ', $element->localName, ', prefix: ', $element->prefix, "\n";
}
?>

The above example will output:

local name: include, prefix: xi
local name: fallback, prefix: xi

See Also

  • DOMDocument::getElementsByTagName() - Searches for all elements with given local tag name


Import node into current document

  • « DOMDocument::getElementsByTagNameNS
  • DOMDocument::load »
  • PHP Manual
  • DOMDocument
  • Import node into current document

DOMDocument::importNode

(PHP 5, PHP 7)

DOMDocument::importNode — Import node into current document

Description

public DOMDocument::importNode ( DOMNode $importedNode [, bool $deep = FALSE ] ) : DOMNode

This function returns a copy of the node to import and associates it with the current document.

Parameters

importedNode

The node to import.

deep

If set to TRUE, this method will recursively import the subtree under the importedNode.

Note:

To copy the nodes attributes deep needs to be set to TRUE

Return Values

The copied node or FALSE, if it cannot be copied.

Errors/Exceptions

DOMException is thrown if node cannot be imported.

Examples

Example #1 DOMDocument::importNode() example

Copying nodes between documents.

<?php

$orgdoc = new DOMDocument;
$orgdoc->loadXML("<root><element><child>text in child</child></element></root>");

// The node we want to import to a new document
$node = $orgdoc->getElementsByTagName("element")->item(0);

// Create a new document
$newdoc = new DOMDocument;
$newdoc->formatOutput = true;

// Add some markup
$newdoc->loadXML("<root><someelement>text in some element</someelement></root>");

echo "The 'new document' before copying nodes into it:\n";
echo $newdoc->saveXML();

// Import the node, and all its children, to the document
$node = $newdoc->importNode($node, true);
// And then append it to the "<root>" node
$newdoc->documentElement->appendChild($node);

echo "\nThe 'new document' after copying the nodes into it:\n";
echo $newdoc->saveXML();
?>

The above example will output:

The 'new document' before copying nodes into it:
<?xml version="1.0"?>
<root>
  <someelement>text in some element</someelement>
</root>

The 'new document' after copying the nodes into it:
<?xml version="1.0"?>
<root>
  <someelement>text in some element</someelement>
  <element>
    <child>text in child</child>
  </element>
</root>


Load XML from a file

  • « DOMDocument::importNode
  • DOMDocument::loadHTML »
  • PHP Manual
  • DOMDocument
  • Load XML from a file

DOMDocument::load

(PHP 5, PHP 7)

DOMDocument::load — Load XML from a file

Description

public DOMDocument::load ( string $filename [, int $options = 0 ] ) : mixed

Loads an XML document from a file.

Warning

Unix style paths with forward slashes can cause significant performance degradation on Windows systems; be sure to call realpath() in such a case.

Parameters

filename

The path to the XML document.

options

Bitwise OR of the libxml option constants.

Return Values

Returns TRUE on success or FALSE on failure. If called statically, returns a DOMDocument or FALSE on failure.

Errors/Exceptions

If an empty string is passed as the filename or an empty file is named, a warning will be generated. This warning is not generated by libxml and cannot be handled using libxml's error handling functions.

This method may be called statically, but will issue an E_STRICT error.

Examples

Example #1 Creating a Document

<?php
$doc = new DOMDocument();
$doc->load('book.xml');
echo $doc->saveXML();
?>

See Also

  • DOMDocument::loadXML() - Load XML from a string
  • DOMDocument::save() - Dumps the internal XML tree back into a file
  • DOMDocument::saveXML() - Dumps the internal XML tree back into a string


Load HTML from a string

  • « DOMDocument::load
  • DOMDocument::loadHTMLFile »
  • PHP Manual
  • DOMDocument
  • Load HTML from a string

DOMDocument::loadHTML

(PHP 5, PHP 7)

DOMDocument::loadHTML — Load HTML from a string

Description

public DOMDocument::loadHTML ( string $source [, int $options = 0 ] ) : bool

The function parses the HTML contained in the string source. Unlike loading XML, HTML does not have to be well-formed to load. This function may also be called statically to load and create a DOMDocument object. The static invocation may be used when no DOMDocument properties need to be set prior to loading.

Parameters

source

The HTML string.

options

Since PHP 5.4.0 and Libxml 2.6.0, you may also use the options parameter to specify additional Libxml parameters.

Return Values

Returns TRUE on success or FALSE on failure. If called statically, returns a DOMDocument or FALSE on failure.

Errors/Exceptions

If an empty string is passed as the source, a warning will be generated. This warning is not generated by libxml and cannot be handled using libxml's error handling functions.

This method may be called statically, but will issue an E_STRICT error.

While malformed HTML should load successfully, this function may generate E_WARNING errors when it encounters bad markup. libxml's error handling functions may be used to handle these errors.

Examples

Example #1 Creating a Document

<?php
$doc = new DOMDocument();
$doc->loadHTML("<html><body>Test<br></body></html>");
echo $doc->saveHTML();
?>

Changelog

Version | Description
5.4.0 | Added options parameter.

See Also

  • DOMDocument::loadHTMLFile() - Load HTML from a file
  • DOMDocument::saveHTML() - Dumps the internal document into a string using HTML formatting
  • DOMDocument::saveHTMLFile() - Dumps the internal document into a file using HTML formatting


Load HTML from a file

  • « DOMDocument::loadHTML
  • DOMDocument::loadXML »
  • PHP Manual
  • DOMDocument
  • Load HTML from a file

DOMDocument::loadHTMLFile

(PHP 5, PHP 7)

DOMDocument::loadHTMLFile — Load HTML from a file

Description

public DOMDocument::loadHTMLFile ( string $filename [, int $options = 0 ] ) : bool

The function parses the HTML document in the file named filename. Unlike loading XML, HTML does not have to be well-formed to load.

Parameters

filename

The path to the HTML file.

options

Since PHP 5.4.0 and Libxml 2.6.0, you may also use the options parameter to specify additional Libxml parameters.

Return Values

Returns TRUE on success or FALSE on failure. If called statically, returns a DOMDocument or FALSE on failure.

Errors/Exceptions

If an empty string is passed as the filename or an empty file is named, a warning will be generated. This warning is not generated by libxml and cannot be handled using libxml's error handling functions.

This method may be called statically, but will issue an E_STRICT error.

While malformed HTML should load successfully, this function may generate E_WARNING errors when it encounters bad markup. libxml's error handling functions may be used to handle these errors.

Examples

Example #1 Creating a Document

<?php
$doc = new DOMDocument();
$doc->loadHTMLFile("filename.html");
echo $doc->saveHTML();
?>

Changelog

Version | Description
5.4.0 | Added options parameter.

See Also

  • DOMDocument::loadHTML() - Load HTML from a string
  • DOMDocument::saveHTML() - Dumps the internal document into a string using HTML formatting
  • DOMDocument::saveHTMLFile() - Dumps the internal document into a file using HTML formatting


Load XML from a string

  • « DOMDocument::loadHTMLFile
  • DOMDocument::normalizeDocument »
  • PHP Manual
  • DOMDocument
  • Load XML from a string

DOMDocument::loadXML

(PHP 5, PHP 7)

DOMDocument::loadXML — Load XML from a string

Description

public DOMDocument::loadXML ( string $source [, int $options = 0 ] ) : mixed

Loads an XML document from a string.

Parameters

source

The string containing the XML.

options

Bitwise OR of the libxml option constants.

Return Values

Returns TRUE on success or FALSE on failure. If called statically, returns a DOMDocument or FALSE on failure.

Errors/Exceptions

If an empty string is passed as the source, a warning will be generated. This warning is not generated by libxml and cannot be handled using libxml's error handling functions.

This method may be called statically, but will issue an E_STRICT error.

Examples

Example #1 Creating a Document

<?php
$doc = new DOMDocument();
$doc->loadXML('<root><node/></root>');
echo $doc->saveXML();
?>

Example #2 Static invocation of loadXML

<?php
// Issues an E_STRICT error
$doc = DOMDocument::loadXML('<root><node/></root>');
echo $doc->saveXML();
?>

See Also

  • DOMDocument::load() - Load XML from a file
  • DOMDocument::save() - Dumps the internal XML tree back into a file
  • DOMDocument::saveXML() - Dumps the internal XML tree back into a string


Normalizes the document

  • « DOMDocument::loadXML
  • DOMDocument::registerNodeClass »
  • PHP Manual
  • DOMDocument
  • Normalizes the document

DOMDocument::normalizeDocument

(PHP 5, PHP 7)

DOMDocument::normalizeDocument — Normalizes the document

Description

public DOMDocument::normalizeDocument ( void ) : void

This method acts as if you saved and then loaded the document, putting the document in a "normal" form.

Return Values

No value is returned.

See Also

  • » The DOM Specification
  • DOMNode::normalize() - Normalizes the node


Register extended class used to create base node type

  • « DOMDocument::normalizeDocument
  • DOMDocument::relaxNGValidate »
  • PHP Manual
  • DOMDocument
  • Register extended class used to create base node type

DOMDocument::registerNodeClass

(PHP 5 >= 5.2.0, PHP 7)

DOMDocument::registerNodeClass — Register extended class used to create base node type

Description

public DOMDocument::registerNodeClass ( string $baseclass , string $extendedclass ) : bool

This method allows you to register your own extended DOM class to be used afterward by the PHP DOM extension.

This method is not part of the DOM standard.

Parameters

baseclass

The DOM class that you want to extend. You can find a list of these classes in the chapter introduction.

extendedclass

Your extended class name. If NULL is provided, any previously registered class extending baseclass will be removed.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.2.2 | Prior to 5.2.2, a previously registered extendedclass had to be unregistered before being able to register a new class extending the same baseclass.

Examples

Example #1 Adding a new method to DOMElement to ease our code

<?php

class myElement extends DOMElement {
   function appendElement($name) {
      return $this->appendChild(new myElement($name));
   }
}

class myDocument extends DOMDocument {
   function setRoot($name) {
      return $this->appendChild(new myElement($name));
   }
}

$doc = new myDocument();
$doc->registerNodeClass('DOMElement', 'myElement');

// From now on, adding an element to another costs only one method call !
$root = $doc->setRoot('root');
$child = $root->appendElement('child');
$child->setAttribute('foo', 'bar');

echo $doc->saveXML();

?>

The above example will output:

<?xml version="1.0"?>
<root><child foo="bar"/></root>

Example #2 Retrieving elements as custom class

<?php
class myElement extends DOMElement {
    public function __toString() {
        return $this->nodeValue;
    }
}

$doc = new DOMDocument;
$doc->loadXML("<root><element><child>text in child</child></element></root>");
$doc->registerNodeClass("DOMElement", "myElement");

$element = $doc->getElementsByTagName("child")->item(0);
var_dump(get_class($element));

// And take advantage of the __toString method..
echo $element;
?>

The above example will output:

string(9) "myElement"
text in child

Example #3 Retrieving owner document

When instantiating a custom DOMDocument the ownerDocument property will refer to the instantiated class, meaning there is no need (and in fact not possible) to use DOMDocument::registerNodeClass() with DOMDocument

<?php
class myDOMDocument extends DOMDocument {
}

class myOtherDOMDocument extends DOMDocument {
}

// Create myDOMDocument with some XML
$doc = new myDOMDocument;
$doc->loadXML("<root><element><child>text in child</child></element></root>");

$child = $doc->getElementsByTagName("child")->item(0);

// The current owner of the node is myDOMDocument
var_dump(get_class($child->ownerDocument));

// Import a node from myDOMDocument
$newdoc = new myOtherDOMDocument;
$child = $newdoc->importNode($child);

// The new owner of the node has changed to myOtherDOMDocument
var_dump(get_class($child->ownerDocument));
?>

The above example will output:

string(13) "myDOMDocument"
string(18) "myOtherDOMDocument"


Performs relaxNG validation on the document

  • « DOMDocument::registerNodeClass
  • DOMDocument::relaxNGValidateSource »
  • PHP Manual
  • DOMDocument
  • Performs relaxNG validation on the document

DOMDocument::relaxNGValidate

(PHP 5, PHP 7)

DOMDocument::relaxNGValidate — Performs relaxNG validation on the document

Description

public DOMDocument::relaxNGValidate ( string $filename ) : bool

Performs » relaxNG validation on the document based on the given RNG schema.

Parameters

filename

The RNG file.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • DOMDocument::relaxNGValidateSource() - Performs relaxNG validation on the document
  • DOMDocument::schemaValidate() - Validates a document based on a schema
  • DOMDocument::schemaValidateSource() - Validates a document based on a schema
  • DOMDocument::validate() - Validates the document based on its DTD


Performs relaxNG validation on the document

  • « DOMDocument::relaxNGValidate
  • DOMDocument::save »
  • PHP Manual
  • DOMDocument
  • Performs relaxNG validation on the document

DOMDocument::relaxNGValidateSource

(PHP 5, PHP 7)

DOMDocument::relaxNGValidateSource — Performs relaxNG validation on the document

Description

public DOMDocument::relaxNGValidateSource ( string $source ) : bool

Performs » relaxNG validation on the document based on the given RNG source.

Parameters

source

A string containing the RNG schema.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • DOMDocument::relaxNGValidate() - Performs relaxNG validation on the document
  • DOMDocument::schemaValidate() - Validates a document based on a schema
  • DOMDocument::schemaValidateSource() - Validates a document based on a schema
  • DOMDocument::validate() - Validates the document based on its DTD


Dumps the internal XML tree back into a file

  • « DOMDocument::relaxNGValidateSource
  • DOMDocument::saveHTML »
  • PHP Manual
  • DOMDocument
  • Dumps the internal XML tree back into a file

DOMDocument::save

(PHP 5, PHP 7)

DOMDocument::save — Dumps the internal XML tree back into a file

Description

public DOMDocument::save ( string $filename [, int $options = 0 ] ) : int

Creates an XML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.

Parameters

filename

The path to the saved XML document.

options

Additional Options. Currently only LIBXML_NOEMPTYTAG is supported.

Return Values

Returns the number of bytes written or FALSE if an error occurred.

Changelog

Version | Description
5.1.0 | Added the options parameter

Examples

Example #1 Saving a DOM tree into a file

<?php

$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;

$root = $doc->createElement('book');
$root = $doc->appendChild($root);

$title = $doc->createElement('title');
$title = $root->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo 'Wrote: ' . $doc->save("/tmp/test.xml") . ' bytes'; // Wrote: 72 bytes

?>

See Also

  • DOMDocument::saveXML() - Dumps the internal XML tree back into a string
  • DOMDocument::load() - Load XML from a file
  • DOMDocument::loadXML() - Load XML from a string


Dumps the internal document into a string using HTML formatting

  • « DOMDocument::save
  • DOMDocument::saveHTMLFile »
  • PHP Manual
  • DOMDocument
  • Dumps the internal document into a string using HTML formatting

DOMDocument::saveHTML

(PHP 5, PHP 7)

DOMDocument::saveHTML — Dumps the internal document into a string using HTML formatting

Description

public DOMDocument::saveHTML ([ DOMNode $node = NULL ] ) : string

Creates an HTML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.

Parameters

node

Optional parameter to output a subset of the document.

Return Values

Returns the HTML, or FALSE if an error occurred.

Changelog

Version | Description
5.3.6 | The node parameter was added.

Examples

Example #1 Saving a HTML tree into a string

<?php

$doc = new DOMDocument('1.0');

$root = $doc->createElement('html');
$root = $doc->appendChild($root);

$head = $doc->createElement('head');
$head = $root->appendChild($head);

$title = $doc->createElement('title');
$title = $head->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo $doc->saveHTML();

?>

See Also

  • DOMDocument::saveHTMLFile() - Dumps the internal document into a file using HTML formatting
  • DOMDocument::loadHTML() - Load HTML from a string
  • DOMDocument::loadHTMLFile() - Load HTML from a file


Dumps the internal document into a file using HTML formatting

  • « DOMDocument::saveHTML
  • DOMDocument::saveXML »
  • PHP Manual
  • DOMDocument
  • Dumps the internal document into a file using HTML formatting

DOMDocument::saveHTMLFile

(PHP 5, PHP 7)

DOMDocument::saveHTMLFile — Dumps the internal document into a file using HTML formatting

Description

public DOMDocument::saveHTMLFile ( string $filename ) : int

Creates an HTML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.

Parameters

filename

The path to the saved HTML document.

Return Values

Returns the number of bytes written or FALSE if an error occurred.

Examples

Example #1 Saving a HTML tree into a file

<?php

$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;

$root = $doc->createElement('html');
$root = $doc->appendChild($root);

$head = $doc->createElement('head');
$head = $root->appendChild($head);

$title = $doc->createElement('title');
$title = $head->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo 'Wrote: ' . $doc->saveHTMLFile("/tmp/test.html") . ' bytes'; // Wrote: 129 bytes

?>

See Also

  • DOMDocument::saveHTML() - Dumps the internal document into a string using HTML formatting
  • DOMDocument::loadHTML() - Load HTML from a string
  • DOMDocument::loadHTMLFile() - Load HTML from a file


Dumps the internal XML tree back into a string

  • « DOMDocument::saveHTMLFile
  • DOMDocument::schemaValidate »
  • PHP Manual
  • DOMDocument
  • Dumps the internal XML tree back into a string

DOMDocument::saveXML

(PHP 5, PHP 7)

DOMDocument::saveXML — Dumps the internal XML tree back into a string

Description

public DOMDocument::saveXML ([ DOMNode $node [, int $options = 0 ]] ) : string

Creates an XML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.

Parameters

node

Use this parameter to output only a specific node without XML declaration rather than the entire document.

options

Additional Options. Currently only LIBXML_NOEMPTYTAG is supported.

Return Values

Returns the XML, or FALSE if an error occurred.

Errors/Exceptions

DOM_WRONG_DOCUMENT_ERR

Raised if node is from another document.

Changelog

Version | Description
5.1.0 | Added the options parameter

Examples

Example #1 Saving a DOM tree into a string

<?php

$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;

$root = $doc->createElement('book');
$root = $doc->appendChild($root);

$title = $doc->createElement('title');
$title = $root->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo "Saving all the document:\n";
echo $doc->saveXML() . "\n";

echo "Saving only the title part:\n";
echo $doc->saveXML($title);

?>

The above example will output:

Saving all the document:
<?xml version="1.0"?>
<book>
  <title>This is the title</title>
</book>

Saving only the title part:
<title>This is the title</title>

See Also

  • DOMDocument::save() - Dumps the internal XML tree back into a file
  • DOMDocument::load() - Load XML from a file
  • DOMDocument::loadXML() - Load XML from a string


Validates a document based on a schema

  • « DOMDocument::saveXML
  • DOMDocument::schemaValidateSource »
  • PHP Manual
  • DOMDocument
  • Validates a document based on a schema

DOMDocument::schemaValidate

(PHP 5, PHP 7)

DOMDocument::schemaValidate — Validates a document based on a schema

Description

public DOMDocument::schemaValidate ( string $filename [, int $flags = 0 ] ) : bool

Validates a document based on the given schema file.

Parameters

filename

The path to the schema.

flags

A bitmask of Libxml schema validation flags. Currently the only supported value is LIBXML_SCHEMA_CREATE. Available since PHP 5.5.2 and Libxml 2.6.14.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.5.2 | Added the flags parameter

See Also

  • DOMDocument::schemaValidateSource() - Validates a document based on a schema
  • DOMDocument::relaxNGValidate() - Performs relaxNG validation on the document
  • DOMDocument::relaxNGValidateSource() - Performs relaxNG validation on the document
  • DOMDocument::validate() - Validates the document based on its DTD


Validates a document based on a schema

  • « DOMDocument::schemaValidate
  • DOMDocument::validate »
  • PHP Manual
  • DOMDocument
  • Validates a document based on a schema

DOMDocument::schemaValidateSource

(PHP 5, PHP 7)

DOMDocument::schemaValidateSource — Validates a document based on a schema

Description

public DOMDocument::schemaValidateSource ( string $source [, int $flags ] ) : bool

Validates a document based on a schema defined in the given string.

Parameters

source

A string containing the schema.

flags

A bitmask of Libxml schema validation flags. Currently the only supported value is LIBXML_SCHEMA_CREATE. Available since PHP 5.5.2 and Libxml 2.6.14.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.5.2 | Added the flags parameter

See Also

  • DOMDocument::schemaValidate() - Validates a document based on a schema
  • DOMDocument::relaxNGValidate() - Performs relaxNG validation on the document
  • DOMDocument::relaxNGValidateSource() - Performs relaxNG validation on the document
  • DOMDocument::validate() - Validates the document based on its DTD


Validates the document based on its DTD

  • « DOMDocument::schemaValidateSource
  • DOMDocument::xinclude »
  • PHP Manual
  • DOMDocument
  • Validates the document based on its DTD

DOMDocument::validate

(PHP 5, PHP 7)

DOMDocument::validate — Validates the document based on its DTD

Description

public DOMDocument::validate ( void ) : bool

Validates the document based on its DTD.

You can also use the validateOnParse property of DOMDocument to make a DTD validation.

Return Values

Returns TRUE on success or FALSE on failure. If the document has no DTD attached, this method will return FALSE.

Examples

Example #1 Example of DTD validation

<?php
$dom = new DOMDocument;
$dom->load('book.xml');
if ($dom->validate()) {
    echo "This document is valid!\n";
}
?>

You can also validate your XML file while loading it:

<?php
$dom = new DOMDocument;
$dom->validateOnParse = true;
$dom->load('book.xml');
?>

See Also

  • DOMDocument::schemaValidate() - Validates a document based on a schema
  • DOMDocument::schemaValidateSource() - Validates a document based on a schema
  • DOMDocument::relaxNGValidate() - Performs relaxNG validation on the document
  • DOMDocument::relaxNGValidateSource() - Performs relaxNG validation on the document


Substitutes XIncludes in a DOMDocument Object

  • « DOMDocument::validate
  • DOMDocumentFragment »
  • PHP Manual
  • DOMDocument
  • Substitutes XIncludes in a DOMDocument Object

DOMDocument::xinclude

(PHP 5, PHP 7)

DOMDocument::xinclude — Substitutes XIncludes in a DOMDocument Object

Description

public DOMDocument::xinclude ([ int $options = 0 ] ) : int

This method substitutes » XIncludes in a DOMDocument object.

Note:

Due to libxml2 automatically resolving entities, this method will produce unexpected results if the included XML file have an attached DTD.

Parameters

options

libxml parameters. Available since PHP 5.1.0 and Libxml 2.6.7.

Return Values

Returns the number of XIncludes in the document, -1 if some processing failed, or FALSE if there were no substitutions.

Examples

Example #1 DOMDocument::xinclude() example

<?php

$xml = <<<EOD
<?xml version="1.0" ?>
<chapter xmlns:xi="http://www.w3.org/2001/XInclude">
 <title>Books of the other guy..</title>
 <para>
  <xi:include href="book.xml">
   <xi:fallback>
    <error>xinclude: book.xml not found</error>
   </xi:fallback>
  </xi:include>
 </para>
</chapter>
EOD;

$dom = new DOMDocument;

// let's have a nice output
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;

// load the XML string defined above
$dom->loadXML($xml);

// substitute xincludes
$dom->xinclude();

echo $dom->saveXML();

?>

The above example will output something similar to:

<?xml version="1.0"?>
<chapter xmlns:xi="http://www.w3.org/2001/XInclude">
  <title>Books of the other guy..</title>
  <para>
    <row xml:base="/home/didou/book.xml">
       <entry>The Grapes of Wrath</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>0140186409</entry>
      </row>
    <row xml:base="/home/didou/book.xml">
       <entry>The Pearl</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>014017737X</entry>
      </row>
    <row xml:base="/home/didou/book.xml">
       <entry>Samarcande</entry>
       <entry>Amine Maalouf</entry>
       <entry>fr</entry>
       <entry>2253051209</entry>
      </row>
  </para>
</chapter>


The DOMDocumentFragment class

(PHP 5, PHP 7)

Class synopsis

DOMDocumentFragment extends DOMNode {
/* Properties */
/* Inherited properties */
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode $parentNode ;
public readonly DOMNodeList $childNodes ;
public readonly DOMNode $firstChild ;
public readonly DOMNode $lastChild ;
public readonly DOMNode $previousSibling ;
public readonly DOMNode $nextSibling ;
public readonly DOMNamedNodeMap $attributes ;
public readonly DOMDocument $ownerDocument ;
public readonly string $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string $baseURI ;
public string $textContent ;
/* Methods */
public appendXML ( string $data ) : bool
/* Inherited methods */
public DOMNode::appendChild ( DOMNode $newnode ) : DOMNode
public DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] ) : string
public DOMNode::C14NFile ( string $uri [, bool $exclusive = FALSE [, bool $with_comments = FALSE [, array $xpath [, array $ns_prefixes ]]]] ) : int
public DOMNode::cloneNode ([ bool $deep ] ) : DOMNode
public DOMNode::getLineNo ( void ) : int
public DOMNode::getNodePath ( void ) : string
public DOMNode::hasAttributes ( void ) : bool
public DOMNode::hasChildNodes ( void ) : bool
public DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] ) : DOMNode
public DOMNode::isDefaultNamespace ( string $namespaceURI ) : bool
public DOMNode::isSameNode ( DOMNode $node ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespaceURI ) : string
public DOMNode::normalize ( void ) : void
public DOMNode::removeChild ( DOMNode $oldnode ) : DOMNode
public DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode ) : DOMNode
}

Table of Contents

  • DOMDocumentFragment::appendXML — Append raw XML data


Append raw XML data

  • « DOMDocumentFragment
  • DOMDocumentType »
  • PHP Manual
  • DOMDocumentFragment
  • Append raw XML data

DOMDocumentFragment::appendXML

(PHP 5 >= 5.1.0, PHP 7)

DOMDocumentFragment::appendXML — Append raw XML data

Description

public DOMDocumentFragment::appendXML ( string $data ) : bool

Appends raw XML data to a DOMDocumentFragment.

This method is not part of the DOM standard. It was created as a simpler approach for appending an XML DocumentFragment in a DOMDocument.

If you want to stick to the standards, you will have to create a temporary DOMDocument with a dummy root and then loop through the child nodes of the root of your XML data to append them.

Parameters

data

XML to append.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Appending XML data to your document

<?php
$doc = new DOMDocument();
$doc->loadXML("<root/>");
$f = $doc->createDocumentFragment();
$f->appendXML("<foo>text</foo><bar>text2</bar>");
$doc->documentElement->appendChild($f);
echo $doc->saveXML();
?>

The above example will output:

<?xml version="1.0"?>
<root><foo>text</foo><bar>text2</bar></root>


The DOMDocumentType class

(PHP 5, PHP 7)

Introduction

Each DOMDocument has a doctype attribute whose value is either NULL or a DOMDocumentType object.

Class synopsis

DOMDocumentType extends DOMNode {
/* Properties */
readonly public string $publicId ;
readonly public string $systemId ;
readonly public string $name ;
readonly public DOMNamedNodeMap $entities ;
readonly public DOMNamedNodeMap $notations ;
readonly public string $internalSubset ;
/* Inherited properties */
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode $parentNode ;
public readonly DOMNodeList $childNodes ;
public readonly DOMNode $firstChild ;
public readonly DOMNode $lastChild ;
public readonly DOMNode $previousSibling ;
public readonly DOMNode $nextSibling ;
public readonly DOMNamedNodeMap $attributes ;
public readonly DOMDocument $ownerDocument ;
public readonly string $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string $baseURI ;
public string $textContent ;
/* Inherited methods */
public DOMNode::appendChild ( DOMNode $newnode ) : DOMNode
public DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] ) : string
public DOMNode::C14NFile ( string $uri [, bool $exclusive = FALSE [, bool $with_comments = FALSE [, array $xpath [, array $ns_prefixes ]]]] ) : int
public DOMNode::cloneNode ([ bool $deep ] ) : DOMNode
public DOMNode::getLineNo ( void ) : int
public DOMNode::getNodePath ( void ) : string
public DOMNode::hasAttributes ( void ) : bool
public DOMNode::hasChildNodes ( void ) : bool
public DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] ) : DOMNode
public DOMNode::isDefaultNamespace ( string $namespaceURI ) : bool
public DOMNode::isSameNode ( DOMNode $node ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespaceURI ) : string
public DOMNode::normalize ( void ) : void
public DOMNode::removeChild ( DOMNode $oldnode ) : DOMNode
public DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode ) : DOMNode
}

Properties

publicId

The public identifier of the external subset.

systemId

The system identifier of the external subset. This may be an absolute URI or not.

name

The name of DTD; i.e., the name immediately following the DOCTYPE keyword.

entities

A DOMNamedNodeMap containing the general entities, both external and internal, declared in the DTD.

notations

A DOMNamedNodeMap containing the notations declared in the DTD.

internalSubset

The internal subset as a string, or null if there is none. This does not contain the delimiting square brackets.


The DOMElement class

(PHP 5, PHP 7)

Class synopsis

DOMElement extends DOMNode {
/* Properties */
readonly public bool $schemaTypeInfo ;
readonly public string $tagName ;
/* Inherited properties */
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode $parentNode ;
public readonly DOMNodeList $childNodes ;
public readonly DOMNode $firstChild ;
public readonly DOMNode $lastChild ;
public readonly DOMNode $previousSibling ;
public readonly DOMNode $nextSibling ;
public readonly DOMNamedNodeMap $attributes ;
public readonly DOMDocument $ownerDocument ;
public readonly string $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string $baseURI ;
public string $textContent ;
/* Methods */
public __construct ( string $name [, string $value [, string $namespaceURI ]] )
public getAttribute ( string $name ) : string
public getAttributeNode ( string $name ) : DOMAttr
public getAttributeNodeNS ( string $namespaceURI , string $localName ) : DOMAttr
public getAttributeNS ( string $namespaceURI , string $localName ) : string
public getElementsByTagName ( string $name ) : DOMNodeList
public getElementsByTagNameNS ( string $namespaceURI , string $localName ) : DOMNodeList
public hasAttribute ( string $name ) : bool
public hasAttributeNS ( string $namespaceURI , string $localName ) : bool
public removeAttribute ( string $name ) : bool
public removeAttributeNode ( DOMAttr $oldnode ) : bool
public removeAttributeNS ( string $namespaceURI , string $localName ) : bool
public setAttribute ( string $name , string $value ) : DOMAttr
public setAttributeNode ( DOMAttr $attr ) : DOMAttr
public setAttributeNodeNS ( DOMAttr $attr ) : DOMAttr
public setAttributeNS ( string $namespaceURI , string $qualifiedName , string $value ) : void
public setIdAttribute ( string $name , bool $isId ) : void
public setIdAttributeNode ( DOMAttr $attr , bool $isId ) : void
public setIdAttributeNS ( string $namespaceURI , string $localName , bool $isId ) : void
/* Inherited methods */
public DOMNode::appendChild ( DOMNode $newnode ) : DOMNode
public DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] ) : string
public DOMNode::C14NFile ( string $uri [, bool $exclusive = FALSE [, bool $with_comments = FALSE [, array $xpath [, array $ns_prefixes ]]]] ) : int
public DOMNode::cloneNode ([ bool $deep ] ) : DOMNode
public DOMNode::getLineNo ( void ) : int
public DOMNode::getNodePath ( void ) : string
public DOMNode::hasAttributes ( void ) : bool
public DOMNode::hasChildNodes ( void ) : bool
public DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] ) : DOMNode
public DOMNode::isDefaultNamespace ( string $namespaceURI ) : bool
public DOMNode::isSameNode ( DOMNode $node ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespaceURI ) : string
public DOMNode::normalize ( void ) : void
public DOMNode::removeChild ( DOMNode $oldnode ) : DOMNode
public DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode ) : DOMNode
}

Properties

schemaTypeInfo

Not implemented yet, always return NULL

tagName

The element name

Notes

Note:

The DOM extension uses UTF-8 encoding. Use utf8_encode() and utf8_decode() to work with texts in ISO-8859-1 encoding or iconv for other encodings.

Table of Contents

  • DOMElement::__construct — Creates a new DOMElement object
  • DOMElement::getAttribute — Returns value of attribute
  • DOMElement::getAttributeNode — Returns attribute node
  • DOMElement::getAttributeNodeNS — Returns attribute node
  • DOMElement::getAttributeNS — Returns value of attribute
  • DOMElement::getElementsByTagName — Gets elements by tagname
  • DOMElement::getElementsByTagNameNS — Get elements by namespaceURI and localName
  • DOMElement::hasAttribute — Checks to see if attribute exists
  • DOMElement::hasAttributeNS — Checks to see if attribute exists
  • DOMElement::removeAttribute — Removes attribute
  • DOMElement::removeAttributeNode — Removes attribute
  • DOMElement::removeAttributeNS — Removes attribute
  • DOMElement::setAttribute — Adds new attribute
  • DOMElement::setAttributeNode — Adds new attribute node to element
  • DOMElement::setAttributeNodeNS — Adds new attribute node to element
  • DOMElement::setAttributeNS — Adds new attribute
  • DOMElement::setIdAttribute — Declares the attribute specified by name to be of type ID
  • DOMElement::setIdAttributeNode — Declares the attribute specified by node to be of type ID
  • DOMElement::setIdAttributeNS — Declares the attribute specified by local name and namespace URI to be of type ID


Creates a new DOMElement object

  • « DOMElement
  • DOMElement::getAttribute »
  • PHP Manual
  • DOMElement
  • Creates a new DOMElement object

DOMElement::__construct

(PHP 5, PHP 7)

DOMElement::__construct — Creates a new DOMElement object

Description

public DOMElement::__construct ( string $name [, string $value [, string $namespaceURI ]] )

Creates a new DOMElement object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writeable node, use DOMDocument::createElement or DOMDocument::createElementNS.

Parameters

name

The tag name of the element. When also passing in namespaceURI, the element name may take a prefix to be associated with the URI.

value

The value of the element.

namespaceURI

A namespace URI to create the element within a specific namespace.

Examples

Example #1 Creating a new DOMElement

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$element_ns = new DOMElement('pr:node1', 'thisvalue', 'http://xyz');
$element->appendChild($element_ns);
echo $dom->saveXML(); /* <?xml version="1.0" encoding="utf-8"?>
<root><pr:node1 xmlns:pr="http://xyz">thisvalue</pr:node1></root> */

?>

See Also

  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace


Returns value of attribute

  • « DOMElement::__construct
  • DOMElement::getAttributeNode »
  • PHP Manual
  • DOMElement
  • Returns value of attribute

DOMElement::getAttribute

(PHP 5, PHP 7)

DOMElement::getAttribute — Returns value of attribute

Description

public DOMElement::getAttribute ( string $name ) : string

Gets the value of the attribute with name name for the current node.

Parameters

name

The name of the attribute.

Return Values

The value of the attribute, or an empty string if no attribute with the given name is found.

See Also

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::setAttribute() - Adds new attribute
  • DOMElement::removeAttribute() - Removes attribute


Returns attribute node

  • « DOMElement::getAttribute
  • DOMElement::getAttributeNodeNS »
  • PHP Manual
  • DOMElement
  • Returns attribute node

DOMElement::getAttributeNode

(PHP 5, PHP 7)

DOMElement::getAttributeNode — Returns attribute node

Description

public DOMElement::getAttributeNode ( string $name ) : DOMAttr

Returns the attribute node with name name for the current element.

Parameters

name

The name of the attribute.

Return Values

The attribute node. Note that for XML namespace declarations (xmlns and xmlns:* attributes) an instance of DOMNameSpaceNode is returned instead of a DOMAttr.

See Also

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::setAttributeNode() - Adds new attribute node to element
  • DOMElement::removeAttributeNode() - Removes attribute


Returns attribute node

  • « DOMElement::getAttributeNode
  • DOMElement::getAttributeNS »
  • PHP Manual
  • DOMElement
  • Returns attribute node

DOMElement::getAttributeNodeNS

(PHP 5, PHP 7)

DOMElement::getAttributeNodeNS — Returns attribute node

Description

public DOMElement::getAttributeNodeNS ( string $namespaceURI , string $localName ) : DOMAttr

Returns the attribute node in namespace namespaceURI with local name localName for the current node.

Parameters

namespaceURI

The namespace URI.

localName

The local name.

Return Values

The attribute node. Note that for XML namespace declarations (xmlns and xmlns:* attributes) an instance of DOMNameSpaceNode is returned instead of a DOMAttr object.

See Also

  • DOMElement::hasAttributeNS() - Checks to see if attribute exists
  • DOMElement::setAttributeNodeNS() - Adds new attribute node to element
  • DOMElement::removeAttributeNode() - Removes attribute


Returns value of attribute

  • « DOMElement::getAttributeNodeNS
  • DOMElement::getElementsByTagName »
  • PHP Manual
  • DOMElement
  • Returns value of attribute

DOMElement::getAttributeNS

(PHP 5, PHP 7)

DOMElement::getAttributeNS — Returns value of attribute

Description

public DOMElement::getAttributeNS ( string $namespaceURI , string $localName ) : string

Gets the value of the attribute in namespace namespaceURI with local name localName for the current node.

Parameters

namespaceURI

The namespace URI.

localName

The local name.

Return Values

The value of the attribute, or an empty string if no attribute with the given localName and namespaceURI is found.

See Also

  • DOMElement::hasAttributeNS() - Checks to see if attribute exists
  • DOMElement::setAttributeNS() - Adds new attribute
  • DOMElement::removeAttributeNS() - Removes attribute


Gets elements by tagname

  • « DOMElement::getAttributeNS
  • DOMElement::getElementsByTagNameNS »
  • PHP Manual
  • DOMElement
  • Gets elements by tagname

DOMElement::getElementsByTagName

(PHP 5, PHP 7)

DOMElement::getElementsByTagName — Gets elements by tagname

Description

public DOMElement::getElementsByTagName ( string $name ) : DOMNodeList

This function returns a new instance of the class DOMNodeList of all descendant elements with a given tag name, in the order in which they are encountered in a preorder traversal of this element tree.

Parameters

name

The tag name. Use * to return all elements within the element tree.

Return Values

This function returns a new instance of the class DOMNodeList of all matched elements.

See Also

  • DOMElement::getElementsByTagNameNS() - Get elements by namespaceURI and localName


Get elements by namespaceURI and localName

  • « DOMElement::getElementsByTagName
  • DOMElement::hasAttribute »
  • PHP Manual
  • DOMElement
  • Get elements by namespaceURI and localName

DOMElement::getElementsByTagNameNS

(PHP 5, PHP 7)

DOMElement::getElementsByTagNameNS — Get elements by namespaceURI and localName

Description

public DOMElement::getElementsByTagNameNS ( string $namespaceURI , string $localName ) : DOMNodeList

This function fetch all the descendant elements with a given localName and namespaceURI.

Parameters

namespaceURI

The namespace URI.

localName

The local name. Use * to return all elements within the element tree.

Return Values

This function returns a new instance of the class DOMNodeList of all matched elements in the order in which they are encountered in a preorder traversal of this element tree.

See Also

  • DOMElement::getElementsByTagName() - Gets elements by tagname


Checks to see if attribute exists

  • « DOMElement::getElementsByTagNameNS
  • DOMElement::hasAttributeNS »
  • PHP Manual
  • DOMElement
  • Checks to see if attribute exists

DOMElement::hasAttribute

(PHP 5, PHP 7)

DOMElement::hasAttribute — Checks to see if attribute exists

Description

public DOMElement::hasAttribute ( string $name ) : bool

Indicates whether attribute named name exists as a member of the element.

Parameters

name

The attribute name.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • DOMElement::hasAttributeNS() - Checks to see if attribute exists
  • DOMElement::getAttribute() - Returns value of attribute
  • DOMElement::setAttribute() - Adds new attribute
  • DOMElement::removeAttribute() - Removes attribute


Checks to see if attribute exists

  • « DOMElement::hasAttribute
  • DOMElement::removeAttribute »
  • PHP Manual
  • DOMElement
  • Checks to see if attribute exists

DOMElement::hasAttributeNS

(PHP 5, PHP 7)

DOMElement::hasAttributeNS — Checks to see if attribute exists

Description

public DOMElement::hasAttributeNS ( string $namespaceURI , string $localName ) : bool

Indicates whether attribute in namespace namespaceURI named localName exists as a member of the element.

Parameters

namespaceURI

The namespace URI.

localName

The local name.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::getAttributeNS() - Returns value of attribute
  • DOMElement::setAttributeNS() - Adds new attribute
  • DOMElement::removeAttributeNS() - Removes attribute


Removes attribute

  • « DOMElement::hasAttributeNS
  • DOMElement::removeAttributeNode »
  • PHP Manual
  • DOMElement
  • Removes attribute

DOMElement::removeAttribute

(PHP 5, PHP 7)

DOMElement::removeAttribute — Removes attribute

Description

public DOMElement::removeAttribute ( string $name ) : bool

Removes attribute named name from the element.

Parameters

name

The name of the attribute.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

See Also

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::getAttribute() - Returns value of attribute
  • DOMElement::setAttribute() - Adds new attribute


Removes attribute

  • « DOMElement::removeAttribute
  • DOMElement::removeAttributeNS »
  • PHP Manual
  • DOMElement
  • Removes attribute

DOMElement::removeAttributeNode

(PHP 5, PHP 7)

DOMElement::removeAttributeNode — Removes attribute

Description

public DOMElement::removeAttributeNode ( DOMAttr $oldnode ) : bool

Removes attribute oldnode from the element.

Parameters

oldnode

The attribute node.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND_ERROR

Raised if oldnode is not an attribute of the element.

See Also

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::getAttributeNode() - Returns attribute node
  • DOMElement::setAttributeNode() - Adds new attribute node to element


Removes attribute

  • « DOMElement::removeAttributeNode
  • DOMElement::setAttribute »
  • PHP Manual
  • DOMElement
  • Removes attribute

DOMElement::removeAttributeNS

(PHP 5, PHP 7)

DOMElement::removeAttributeNS — Removes attribute

Description

public DOMElement::removeAttributeNS ( string $namespaceURI , string $localName ) : bool

Removes attribute localName in namespace namespaceURI from the element.

Parameters

namespaceURI

The namespace URI.

localName

The local name.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

See Also

  • DOMElement::hasAttributeNS() - Checks to see if attribute exists
  • DOMElement::getAttributeNS() - Returns value of attribute
  • DOMElement::setAttributeNS() - Adds new attribute


Adds new attribute

  • « DOMElement::removeAttributeNS
  • DOMElement::setAttributeNode »
  • PHP Manual
  • DOMElement
  • Adds new attribute

DOMElement::setAttribute

(PHP 5, PHP 7)

DOMElement::setAttribute — Adds new attribute

Description

public DOMElement::setAttribute ( string $name , string $value ) : DOMAttr

Sets an attribute with name name to the given value. If the attribute does not exist, it will be created.

Parameters

name

The name of the attribute.

value

The value of the attribute.

Return Values

The new DOMAttr or FALSE if an error occurred.

Errors/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

Examples

Example #1 Setting an attribute

<?php
$doc = new DOMDocument("1.0");
$node = $doc->createElement("para");
$newnode = $doc->appendChild($node);
$newnode->setAttribute("align", "left");
?>

See Also

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::getAttribute() - Returns value of attribute
  • DOMElement::removeAttribute() - Removes attribute


Adds new attribute node to element

  • « DOMElement::setAttribute
  • DOMElement::setAttributeNodeNS »
  • PHP Manual
  • DOMElement
  • Adds new attribute node to element

DOMElement::setAttributeNode

(PHP 5, PHP 7)

DOMElement::setAttributeNode — Adds new attribute node to element

Description

public DOMElement::setAttributeNode ( DOMAttr $attr ) : DOMAttr

Adds new attribute node attr to element.

Parameters

attr

The attribute node.

Return Values

Returns old node if the attribute has been replaced or NULL.

Errors/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

See Also

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::getAttributeNode() - Returns attribute node
  • DOMElement::removeAttributeNode() - Removes attribute


Adds new attribute node to element

  • « DOMElement::setAttributeNode
  • DOMElement::setAttributeNS »
  • PHP Manual
  • DOMElement
  • Adds new attribute node to element

DOMElement::setAttributeNodeNS

(PHP 5, PHP 7)

DOMElement::setAttributeNodeNS — Adds new attribute node to element

Description

public DOMElement::setAttributeNodeNS ( DOMAttr $attr ) : DOMAttr

Adds new attribute node attr to element.

Parameters

attr

The attribute node.

Return Values

Returns the old node if the attribute has been replaced.

Errors/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

See Also

  • DOMElement::hasAttributeNS() - Checks to see if attribute exists
  • DOMElement::getAttributeNodeNS() - Returns attribute node
  • DOMElement::removeAttributeNode() - Removes attribute


Adds new attribute

  • « DOMElement::setAttributeNodeNS
  • DOMElement::setIdAttribute »
  • PHP Manual
  • DOMElement
  • Adds new attribute

DOMElement::setAttributeNS

(PHP 5, PHP 7)

DOMElement::setAttributeNS — Adds new attribute

Description

public DOMElement::setAttributeNS ( string $namespaceURI , string $qualifiedName , string $value ) : void

Sets an attribute with namespace namespaceURI and name name to the given value. If the attribute does not exist, it will be created.

Parameters

namespaceURI

The namespace URI.

qualifiedName

The qualified name of the attribute, as prefix:tagname.

value

The value of the attribute.

Return Values

No value is returned.

Errors/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NAMESPACE_ERR

Raised if qualifiedName is a malformed qualified name, or if qualifiedName has a prefix and namespaceURI is NULL.

See Also

  • DOMElement::hasAttributeNS() - Checks to see if attribute exists
  • DOMElement::getAttributeNS() - Returns value of attribute
  • DOMElement::removeAttributeNS() - Removes attribute


Declares the attribute specified by name to be of type ID

  • « DOMElement::setAttributeNS
  • DOMElement::setIdAttributeNode »
  • PHP Manual
  • DOMElement
  • Declares the attribute specified by name to be of type ID

DOMElement::setIdAttribute

(PHP 5, PHP 7)

DOMElement::setIdAttribute — Declares the attribute specified by name to be of type ID

Description

public DOMElement::setIdAttribute ( string $name , bool $isId ) : void

Declares the attribute name to be of type ID.

Parameters

name

The name of the attribute.

isId

Set it to TRUE if you want name to be of type ID, FALSE otherwise.

Return Values

No value is returned.

Errors/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND

Raised if name is not an attribute of this element.

See Also

  • DOMDocument::getElementById() - Searches for an element with a certain id
  • DOMElement::setIdAttributeNode() - Declares the attribute specified by node to be of type ID
  • DOMElement::setIdAttributeNS() - Declares the attribute specified by local name and namespace URI to be of type ID


Declares the attribute specified by node to be of type ID

  • « DOMElement::setIdAttribute
  • DOMElement::setIdAttributeNS »
  • PHP Manual
  • DOMElement
  • Declares the attribute specified by node to be of type ID

DOMElement::setIdAttributeNode

(PHP 5, PHP 7)

DOMElement::setIdAttributeNode — Declares the attribute specified by node to be of type ID

Description

public DOMElement::setIdAttributeNode ( DOMAttr $attr , bool $isId ) : void

Declares the attribute specified by attr to be of type ID.

Parameters

attr

The attribute node.

isId

Set it to TRUE if you want name to be of type ID, FALSE otherwise.

Return Values

No value is returned.

Errors/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND

Raised if name is not an attribute of this element.

See Also

  • DOMDocument::getElementById() - Searches for an element with a certain id
  • DOMElement::setIdAttribute() - Declares the attribute specified by name to be of type ID
  • DOMElement::setIdAttributeNS() - Declares the attribute specified by local name and namespace URI to be of type ID


Declares the attribute specified by local name and namespace URI to be of type ID

  • « DOMElement::setIdAttributeNode
  • DOMEntity »
  • PHP Manual
  • DOMElement
  • Declares the attribute specified by local name and namespace URI to be of type ID

DOMElement::setIdAttributeNS

(PHP 5, PHP 7)

DOMElement::setIdAttributeNS — Declares the attribute specified by local name and namespace URI to be of type ID

Description

public DOMElement::setIdAttributeNS ( string $namespaceURI , string $localName , bool $isId ) : void

Declares the attribute specified by localName and namespaceURI to be of type ID.

Parameters

namespaceURI

The namespace URI of the attribute.

localName

The local name of the attribute, as prefix:tagname.

isId

Set it to TRUE if you want name to be of type ID, FALSE otherwise.

Return Values

No value is returned.

Errors/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND

Raised if name is not an attribute of this element.

See Also

  • DOMDocument::getElementById() - Searches for an element with a certain id
  • DOMElement::setIdAttribute() - Declares the attribute specified by name to be of type ID
  • DOMElement::setIdAttributeNode() - Declares the attribute specified by node to be of type ID


The DOMEntity class

(PHP 5, PHP 7)

Introduction

This interface represents a known entity, either parsed or unparsed, in an XML document.

Class synopsis

DOMEntity extends DOMNode {
/* Properties */
readonly public string $publicId ;
readonly public string $systemId ;
readonly public string $notationName ;
public string $actualEncoding ;
readonly public string $encoding ;
readonly public string $version ;
/* Inherited properties */
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode $parentNode ;
public readonly DOMNodeList $childNodes ;
public readonly DOMNode $firstChild ;
public readonly DOMNode $lastChild ;
public readonly DOMNode $previousSibling ;
public readonly DOMNode $nextSibling ;
public readonly DOMNamedNodeMap $attributes ;
public readonly DOMDocument $ownerDocument ;
public readonly string $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string $baseURI ;
public string $textContent ;
/* Inherited methods */
public DOMNode::appendChild ( DOMNode $newnode ) : DOMNode
public DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] ) : string
public DOMNode::C14NFile ( string $uri [, bool $exclusive = FALSE [, bool $with_comments = FALSE [, array $xpath [, array $ns_prefixes ]]]] ) : int
public DOMNode::cloneNode ([ bool $deep ] ) : DOMNode
public DOMNode::getLineNo ( void ) : int
public DOMNode::getNodePath ( void ) : string
public DOMNode::hasAttributes ( void ) : bool
public DOMNode::hasChildNodes ( void ) : bool
public DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] ) : DOMNode
public DOMNode::isDefaultNamespace ( string $namespaceURI ) : bool
public DOMNode::isSameNode ( DOMNode $node ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespaceURI ) : string
public DOMNode::normalize ( void ) : void
public DOMNode::removeChild ( DOMNode $oldnode ) : DOMNode
public DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode ) : DOMNode
}

Properties

publicId

The public identifier associated with the entity if specified, and NULL otherwise.

systemId

The system identifier associated with the entity if specified, and NULL otherwise. This may be an absolute URI or not.

notationName

For unparsed entities, the name of the notation for the entity. For parsed entities, this is NULL.

actualEncoding

An attribute specifying the encoding used for this entity at the time of parsing, when it is an external parsed entity. This is NULL if it an entity from the internal subset or if it is not known.

encoding

An attribute specifying, as part of the text declaration, the encoding of this entity, when it is an external parsed entity. This is NULL otherwise.

version

An attribute specifying, as part of the text declaration, the version number of this entity, when it is an external parsed entity. This is NULL otherwise.


The DOMEntityReference class

(PHP 5, PHP 7)

Class synopsis

DOMEntityReference extends DOMNode {
/* Inherited properties */
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode $parentNode ;
public readonly DOMNodeList $childNodes ;
public readonly DOMNode $firstChild ;
public readonly DOMNode $lastChild ;
public readonly DOMNode $previousSibling ;
public readonly DOMNode $nextSibling ;
public readonly DOMNamedNodeMap $attributes ;
public readonly DOMDocument $ownerDocument ;
public readonly string $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string $baseURI ;
public string $textContent ;
/* Methods */
public __construct ( string $name )
/* Inherited methods */
public DOMNode::appendChild ( DOMNode $newnode ) : DOMNode
public DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] ) : string
public DOMNode::C14NFile ( string $uri [, bool $exclusive = FALSE [, bool $with_comments = FALSE [, array $xpath [, array $ns_prefixes ]]]] ) : int
public DOMNode::cloneNode ([ bool $deep ] ) : DOMNode
public DOMNode::getLineNo ( void ) : int
public DOMNode::getNodePath ( void ) : string
public DOMNode::hasAttributes ( void ) : bool
public DOMNode::hasChildNodes ( void ) : bool
public DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] ) : DOMNode
public DOMNode::isDefaultNamespace ( string $namespaceURI ) : bool
public DOMNode::isSameNode ( DOMNode $node ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespaceURI ) : string
public DOMNode::normalize ( void ) : void
public DOMNode::removeChild ( DOMNode $oldnode ) : DOMNode
public DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode ) : DOMNode
}

Table of Contents

  • DOMEntityReference::__construct — Creates a new DOMEntityReference object


Creates a new DOMEntityReference object

  • « DOMEntityReference
  • DOMException »
  • PHP Manual
  • DOMEntityReference
  • Creates a new DOMEntityReference object

DOMEntityReference::__construct

(PHP 5, PHP 7)

DOMEntityReference::__construct — Creates a new DOMEntityReference object

Description

public DOMEntityReference::__construct ( string $name )

Creates a new DOMEntityReference object.

Parameters

name

The name of the entity reference.

Examples

Example #1 Creating a new DOMEntityReference

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$entity = $element->appendChild(new DOMEntityReference('nbsp'));
echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?><root>&nbsp;</root> */

?>

See Also

  • DOMDocument::createEntityReference() - Create new entity reference node


The DOMException class

(PHP 5, PHP 7)

Introduction

DOM operations raise exceptions under particular circumstances, i.e., when an operation is impossible to perform for logical reasons.

See also Exceptions.

Class synopsis

DOMException extends Exception {
/* Properties */
readonly public int $code ;
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}

Properties

code

An integer indicating the type of error generated


The DOMImplementation class

(PHP 5, PHP 7)

Introduction

The DOMImplementation interface provides a number of methods for performing operations that are independent of any particular instance of the document object model.

Class synopsis

DOMImplementation {
/* Properties */
/* Methods */
__construct ( void )
public createDocument ([ string $namespaceURI = NULL [, string $qualifiedName = NULL [, DOMDocumentType $doctype = NULL ]]] ) : DOMDocument
public createDocumentType ([ string $qualifiedName = NULL [, string $publicId = NULL [, string $systemId = NULL ]]] ) : DOMDocumentType
public hasFeature ( string $feature , string $version ) : bool
}

Table of Contents

  • DOMImplementation::__construct — Creates a new DOMImplementation object
  • DOMImplementation::createDocument — Creates a DOMDocument object of the specified type with its document element
  • DOMImplementation::createDocumentType — Creates an empty DOMDocumentType object
  • DOMImplementation::hasFeature — Test if the DOM implementation implements a specific feature


Creates a new DOMImplementation object

  • « DOMImplementation
  • DOMImplementation::createDocument »
  • PHP Manual
  • DOMImplementation
  • Creates a new DOMImplementation object

DOMImplementation::__construct

(PHP 5, PHP 7)

DOMImplementation::__construct — Creates a new DOMImplementation object

Description

DOMImplementation::__construct ( void )

Creates a new DOMImplementation object.


Creates a DOMDocument object of the specified type with its document element

  • « DOMImplementation::__construct
  • DOMImplementation::createDocumentType »
  • PHP Manual
  • DOMImplementation
  • Creates a DOMDocument object of the specified type with its document element

DOMImplementation::createDocument

(PHP 5, PHP 7)

DOMImplementation::createDocument — Creates a DOMDocument object of the specified type with its document element

Description

public DOMImplementation::createDocument ([ string $namespaceURI = NULL [, string $qualifiedName = NULL [, DOMDocumentType $doctype = NULL ]]] ) : DOMDocument

Creates a DOMDocument object of the specified type with its document element.

Parameters

namespaceURI

The namespace URI of the document element to create.

qualifiedName

The qualified name of the document element to create.

doctype

The type of document to create or NULL.

Return Values

A new DOMDocument object. If namespaceURI, qualifiedName, and doctype are null, the returned DOMDocument is empty with no document element

Errors/Exceptions

DOM_WRONG_DOCUMENT_ERR

Raised if doctype has already been used with a different document or was created from a different implementation.

DOM_NAMESPACE_ERR

Raised if there is an error with the namespace, as determined by namespaceURI and qualifiedName.

This method may be called statically, but will issue an E_STRICT error.

See Also

  • DOMDocument::__construct() - Creates a new DOMDocument object
  • DOMImplementation::createDocumentType() - Creates an empty DOMDocumentType object


Creates an empty DOMDocumentType object

  • « DOMImplementation::createDocument
  • DOMImplementation::hasFeature »
  • PHP Manual
  • DOMImplementation
  • Creates an empty DOMDocumentType object

DOMImplementation::createDocumentType

(PHP 5, PHP 7)

DOMImplementation::createDocumentType — Creates an empty DOMDocumentType object

Description

public DOMImplementation::createDocumentType ([ string $qualifiedName = NULL [, string $publicId = NULL [, string $systemId = NULL ]]] ) : DOMDocumentType

Creates an empty DOMDocumentType object. Entity declarations and notations are not made available. Entity reference expansions and default attribute additions do not occur.

Parameters

qualifiedName

The qualified name of the document type to create.

publicId

The external subset public identifier.

systemId

The external subset system identifier.

Return Values

A new DOMDocumentType node with its ownerDocument set to NULL.

Errors/Exceptions

DOM_NAMESPACE_ERR

Raised if there is an error with the namespace, as determined by qualifiedName.

This method may be called statically, but will issue an E_STRICT error.

Examples

Example #1 Creating a document with an attached DTD

<?php

// Creates an instance of the DOMImplementation class
$imp = new DOMImplementation;

// Creates a DOMDocumentType instance
$dtd = $imp->createDocumentType('graph', '', 'graph.dtd');

// Creates a DOMDocument instance
$dom = $imp->createDocument("", "", $dtd);

// Set other properties
$dom->encoding = 'UTF-8';
$dom->standalone = false;

// Create an empty element
$element = $dom->createElement('graph');

// Append the element
$dom->appendChild($element);

// Retrieve and print the document
echo $dom->saveXML();

?>

The above example will output:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE graph SYSTEM "graph.dtd">
<graph/>

See Also

  • DOMImplementation::createDocument() - Creates a DOMDocument object of the specified type with its document element


Test if the DOM implementation implements a specific feature

  • « DOMImplementation::createDocumentType
  • DOMNamedNodeMap »
  • PHP Manual
  • DOMImplementation
  • Test if the DOM implementation implements a specific feature

DOMImplementation::hasFeature

(PHP 5, PHP 7)

DOMImplementation::hasFeature — Test if the DOM implementation implements a specific feature

Description

public DOMImplementation::hasFeature ( string $feature , string $version ) : bool

Test if the DOM implementation implements a specific feature.

You can find a list of all features in the » Conformance section of the DOM specification.

Parameters

feature

The feature to test.

version

The version number of the feature to test. In level 2, this can be either 2.0 or 1.0.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

This method may be called statically, but will issue an E_STRICT error.

Examples

Example #1 Testing your DOM Implementation

<?php

$features = array(
  'Core'           => 'Core module',
  'XML'            => 'XML module',
  'HTML'           => 'HTML module',
  'Views'          => 'Views module',
  'Stylesheets'    => 'Style Sheets module',
  'CSS'            => 'CSS module',
  'CSS2'           => 'CSS2 module',
  'Events'         => 'Events module',
  'UIEvents'       => 'User interface Events module',
  'MouseEvents'    => 'Mouse Events module',
  'MutationEvents' => 'Mutation Events module',
  'HTMLEvents'     => 'HTML Events module',
  'Range'          => 'Range module',
  'Traversal'      => 'Traversal module'
);

foreach ($features as $key => $name) {
  if (DOMImplementation::hasFeature($key, '2.0')) {
    echo "Has feature $name\n";
  } else {
    echo "Missing feature $name\n";
  }
}

?>

See Also

  • DOMNode::isSupported() - Checks if feature is supported for specified version


The DOMNamedNodeMap class

(PHP 5, PHP 7)

Class synopsis

DOMNamedNodeMap implements Traversable , Countable {
/* Properties */
readonly public int $length ;
/* Methods */
public count ( void ) : int
getNamedItem ( string $name ) : DOMNode
getNamedItemNS ( string $namespaceURI , string $localName ) : DOMNode
item ( int $index ) : DOMNode
}

Properties

length

The number of nodes in the map. The range of valid child node indices is 0 to length - 1 inclusive.

Table of Contents

  • DOMNamedNodeMap::count — Get number of nodes in the map
  • DOMNamedNodeMap::getNamedItem — Retrieves a node specified by name
  • DOMNamedNodeMap::getNamedItemNS — Retrieves a node specified by local name and namespace URI
  • DOMNamedNodeMap::item — Retrieves a node specified by index


Get number of nodes in the map

  • « DOMNamedNodeMap
  • DOMNamedNodeMap::getNamedItem »
  • PHP Manual
  • DOMNamedNodeMap
  • Get number of nodes in the map

DOMNamedNodeMap::count

(PHP 7 >= 7.2.0)

DOMNamedNodeMap::count — Get number of nodes in the map

Description

public DOMNamedNodeMap::count ( void ) : int

Gets the number of nodes in the map.

Parameters

This function has no parameters.

Return Values

Returns the number of nodes in the map, which is identical to the length property.


Retrieves a node specified by name

  • « DOMNamedNodeMap::count
  • DOMNamedNodeMap::getNamedItemNS »
  • PHP Manual
  • DOMNamedNodeMap
  • Retrieves a node specified by name

DOMNamedNodeMap::getNamedItem

(PHP 5, PHP 7)

DOMNamedNodeMap::getNamedItem — Retrieves a node specified by name

Description

DOMNamedNodeMap::getNamedItem ( string $name ) : DOMNode

Retrieves a node specified by its nodeName.

Parameters

name

The nodeName of the node to retrieve.

Return Values

A node (of any type) with the specified nodeName, or NULL if no node is found.

See Also

  • DOMNamedNodeMap::getNamedItemNS() - Retrieves a node specified by local name and namespace URI


Retrieves a node specified by local name and namespace URI

  • « DOMNamedNodeMap::getNamedItem
  • DOMNamedNodeMap::item »
  • PHP Manual
  • DOMNamedNodeMap
  • Retrieves a node specified by local name and namespace URI

DOMNamedNodeMap::getNamedItemNS

(PHP 5, PHP 7)

DOMNamedNodeMap::getNamedItemNS — Retrieves a node specified by local name and namespace URI

Description

DOMNamedNodeMap::getNamedItemNS ( string $namespaceURI , string $localName ) : DOMNode

Retrieves a node specified by localName and namespaceURI.

Parameters

namespaceURI

The namespace URI of the node to retrieve.

localName

The local name of the node to retrieve.

Return Values

A node (of any type) with the specified local name and namespace URI, or NULL if no node is found.

See Also

  • DOMNamedNodeMap::getNamedItem() - Retrieves a node specified by name


Retrieves a node specified by index

  • « DOMNamedNodeMap::getNamedItemNS
  • DOMNode »
  • PHP Manual
  • DOMNamedNodeMap
  • Retrieves a node specified by index

DOMNamedNodeMap::item

(PHP 5, PHP 7)

DOMNamedNodeMap::item — Retrieves a node specified by index

Description

DOMNamedNodeMap::item ( int $index ) : DOMNode

Retrieves a node specified by index within the DOMNamedNodeMap object.

Parameters

index

Index into this map.

Return Values

The node at the indexth position in the map, or NULL if that is not a valid index (greater than or equal to the number of nodes in this map).


The DOMNode class

(PHP 5, PHP 7)

Class synopsis

DOMNode {
/* Properties */
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode $parentNode ;
public readonly DOMNodeList $childNodes ;
public readonly DOMNode $firstChild ;
public readonly DOMNode $lastChild ;
public readonly DOMNode $previousSibling ;
public readonly DOMNode $nextSibling ;
public readonly DOMNamedNodeMap $attributes ;
public readonly DOMDocument $ownerDocument ;
public readonly string $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string $baseURI ;
public string $textContent ;
/* Methods */
public appendChild ( DOMNode $newnode ) : DOMNode
public C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] ) : string
public C14NFile ( string $uri [, bool $exclusive = FALSE [, bool $with_comments = FALSE [, array $xpath [, array $ns_prefixes ]]]] ) : int
public cloneNode ([ bool $deep ] ) : DOMNode
public getLineNo ( void ) : int
public getNodePath ( void ) : string
public hasAttributes ( void ) : bool
public hasChildNodes ( void ) : bool
public insertBefore ( DOMNode $newnode [, DOMNode $refnode ] ) : DOMNode
public isDefaultNamespace ( string $namespaceURI ) : bool
public isSameNode ( DOMNode $node ) : bool
public isSupported ( string $feature , string $version ) : bool
public lookupNamespaceUri ( string $prefix ) : string
public lookupPrefix ( string $namespaceURI ) : string
public normalize ( void ) : void
public removeChild ( DOMNode $oldnode ) : DOMNode
public replaceChild ( DOMNode $newnode , DOMNode $oldnode ) : DOMNode
}

Properties

nodeName

Returns the most accurate name for the current node type

nodeValue

The value of this node, depending on its type. Contrary to the W3C specification, the node value of DOMElement nodes is equal to DOMNode::textContent instead of NULL.

nodeType

Gets the type of the node. One of the predefined XML_xxx_NODE constants

parentNode

The parent of this node. If there is no such node, this returns NULL.

childNodes

A DOMNodeList that contains all children of this node. If there are no children, this is an empty DOMNodeList.

firstChild

The first child of this node. If there is no such node, this returns NULL.

lastChild

The last child of this node. If there is no such node, this returns NULL.

previousSibling

The node immediately preceding this node. If there is no such node, this returns NULL.

nextSibling

The node immediately following this node. If there is no such node, this returns NULL.

attributes

A DOMNamedNodeMap containing the attributes of this node (if it is a DOMElement) or NULL otherwise.

ownerDocument

The DOMDocument object associated with this node, or NULL if this node is a DOMDOcument

namespaceURI

The namespace URI of this node, or NULL if it is unspecified.

prefix

The namespace prefix of this node, or NULL if it is unspecified.

localName

Returns the local part of the qualified name of this node.

baseURI

The absolute base URI of this node or NULL if the implementation wasn't able to obtain an absolute URI.

textContent

The text content of this node and its descendants.

Notes

Note:

The DOM extension uses UTF-8 encoding. Use utf8_encode() and utf8_decode() to work with texts in ISO-8859-1 encoding or iconv for other encodings.

Changelog

Version | Description
5.6.1 | The textContent property has been made writable (formerly it has been readonly).

See Also

  • » W3C specification of Node

Table of Contents

  • DOMNode::appendChild — Adds new child at the end of the children
  • DOMNode::C14N — Canonicalize nodes to a string
  • DOMNode::C14NFile — Canonicalize nodes to a file
  • DOMNode::cloneNode — Clones a node
  • DOMNode::getLineNo — Get line number for a node
  • DOMNode::getNodePath — Get an XPath for a node
  • DOMNode::hasAttributes — Checks if node has attributes
  • DOMNode::hasChildNodes — Checks if node has children
  • DOMNode::insertBefore — Adds a new child before a reference node
  • DOMNode::isDefaultNamespace — Checks if the specified namespaceURI is the default namespace or not
  • DOMNode::isSameNode — Indicates if two nodes are the same node
  • DOMNode::isSupported — Checks if feature is supported for specified version
  • DOMNode::lookupNamespaceUri — Gets the namespace URI of the node based on the prefix
  • DOMNode::lookupPrefix — Gets the namespace prefix of the node based on the namespace URI
  • DOMNode::normalize — Normalizes the node
  • DOMNode::removeChild — Removes child from list of children
  • DOMNode::replaceChild — Replaces a child


Adds new child at the end of the children

  • « DOMNode
  • DOMNode::C14N »
  • PHP Manual
  • DOMNode
  • Adds new child at the end of the children

DOMNode::appendChild

(PHP 5, PHP 7)

DOMNode::appendChild — Adds new child at the end of the children

Description

public DOMNode::appendChild ( DOMNode $newnode ) : DOMNode

This function appends a child to an existing list of children or creates a new list of children. The child can be created with e.g. DOMDocument::createElement(), DOMDocument::createTextNode() etc. or simply by using any other node.

Parameters

newnode

The appended child.

Return Values

The node added.

Errors/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if this node is readonly or if the previous parent of the node being inserted is readonly.

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of the newnode node, or if the node to append is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if newnode was created from a different document than the one that created this node.

Examples

The following example will add a new element node to a fresh document.

Example #1 Adding a child

<?php

$doc = new DOMDocument;

$node = $doc->createElement("para");
$newnode = $doc->appendChild($node);

echo $doc->saveXML();
?>

Example #2 Nested children

<?php

$doc = new DOMDocument;

$headNode = $doc->createElement("head");
$doc->appendChild($headNode);

$titleNode = $doc->createElement("title");
$headNode->appendChild($titleNode);

echo $doc->saveXML();
?>

See Also

  • DOMNode::insertBefore() - Adds a new child before a reference node
  • DOMNode::removeChild() - Removes child from list of children
  • DOMNode::replaceChild() - Replaces a child


Canonicalize nodes to a string

  • « DOMNode::appendChild
  • DOMNode::C14NFile »
  • PHP Manual
  • DOMNode
  • Canonicalize nodes to a string

DOMNode::C14N

(PHP 5 >= 5.2.0, PHP 7)

DOMNode::C14N — Canonicalize nodes to a string

Description

public DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] ) : string

Canonicalize nodes to a string

Parameters

exclusive

Enable exclusive parsing of only the nodes matched by the provided xpath or namespace prefixes.

with_comments

Retain comments in output.

xpath

An array of xpaths to filter the nodes by.

ns_prefixes

An array of namespace prefixes to filter the nodes by.

Return Values

Returns canonicalized nodes as a string or FALSE on failure

See Also

  • DOMNode::C14NFile() - Canonicalize nodes to a file


Canonicalize nodes to a file

  • « DOMNode::C14N
  • DOMNode::cloneNode »
  • PHP Manual
  • DOMNode
  • Canonicalize nodes to a file

DOMNode::C14NFile

(PHP 5 >= 5.2.0, PHP 7)

DOMNode::C14NFile — Canonicalize nodes to a file

Description

public DOMNode::C14NFile ( string $uri [, bool $exclusive = FALSE [, bool $with_comments = FALSE [, array $xpath [, array $ns_prefixes ]]]] ) : int

Canonicalize nodes to a file.

Parameters

uri

Path to write the output to.

exclusive

Enable exclusive parsing of only the nodes matched by the provided xpath or namespace prefixes.

with_comments

Retain comments in output.

xpath

An array of xpaths to filter the nodes by.

ns_prefixes

An array of namespace prefixes to filter the nodes by.

Return Values

Number of bytes written or FALSE on failure

See Also

  • DOMNode::C14N() - Canonicalize nodes to a string


Clones a node

  • « DOMNode::C14NFile
  • DOMNode::getLineNo »
  • PHP Manual
  • DOMNode
  • Clones a node

DOMNode::cloneNode

(PHP 5, PHP 7)

DOMNode::cloneNode — Clones a node

Description

public DOMNode::cloneNode ([ bool $deep ] ) : DOMNode

Creates a copy of the node.

Parameters

deep

Indicates whether to copy all descendant nodes. This parameter is defaulted to FALSE.

Return Values

The cloned node.


Get line number for a node

  • « DOMNode::cloneNode
  • DOMNode::getNodePath »
  • PHP Manual
  • DOMNode
  • Get line number for a node

DOMNode::getLineNo

(PHP 5 >= 5.3.0, PHP 7)

DOMNode::getLineNo — Get line number for a node

Description

public DOMNode::getLineNo ( void ) : int

Gets line number for where the node is defined.

Parameters

This function has no parameters.

Return Values

Always returns the line number where the node was defined in.

Examples

Example #1 DOMNode::getLineNo() example

<?php
// XML dump for below example
$xml = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<root>
    <node />
</root>
XML;

// Create a new DOMDocument instance
$dom = new DOMDocument;

// Load the XML
$dom->loadXML($xml);

// Print where the line where the 'node' element was defined in
printf('The <node> tag is defined on line %d', $dom->getElementsByTagName('node')->item(0)->getLineNo());
?>

The above example will output:

The <node> tag is defined in line 3


Get an XPath for a node

  • « DOMNode::getLineNo
  • DOMNode::hasAttributes »
  • PHP Manual
  • DOMNode
  • Get an XPath for a node

DOMNode::getNodePath

(PHP 5 >= 5.2.0, PHP 7)

DOMNode::getNodePath — Get an XPath for a node

Description

public DOMNode::getNodePath ( void ) : string

Gets an XPath location path for the node.

Parameters

This function has no parameters.

Return Values

Returns a string containing the XPath, or NULL in case of an error.

Examples

Example #1 DOMNode::getNodePath() example

<?php
// Create a new DOMDocument instance
$dom = new DOMDocument;

// Load the XML
$dom->loadXML('
<fruits>
 <apples>
  <apple>braeburn</apple>
  <apple>granny smith</apple>
 </apples>
 <pears>
  <pear>conference</pear>
 </pears>
</fruits>
');

// Print XPath for each element
foreach ($dom->getElementsByTagName('*') as $node) {
    echo $node->getNodePath() . "\n";
}
?>

The above example will output:

/fruits
/fruits/apples
/fruits/apples/apple[1]
/fruits/apples/apple[2]
/fruits/pears
/fruits/pears/pear

See Also

  • DOMXPath


Checks if node has attributes

  • « DOMNode::getNodePath
  • DOMNode::hasChildNodes »
  • PHP Manual
  • DOMNode
  • Checks if node has attributes

DOMNode::hasAttributes

(PHP 5, PHP 7)

DOMNode::hasAttributes — Checks if node has attributes

Description

public DOMNode::hasAttributes ( void ) : bool

This method checks if the node has attributes. The tested node has to be an XML_ELEMENT_NODE.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • DOMNode::hasChildNodes() - Checks if node has children


Checks if node has children

  • « DOMNode::hasAttributes
  • DOMNode::insertBefore »
  • PHP Manual
  • DOMNode
  • Checks if node has children

DOMNode::hasChildNodes

(PHP 5, PHP 7)

DOMNode::hasChildNodes — Checks if node has children

Description

public DOMNode::hasChildNodes ( void ) : bool

This function checks if the node has children.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • DOMNode::hasAttributes() - Checks if node has attributes


Adds a new child before a reference node

  • « DOMNode::hasChildNodes
  • DOMNode::isDefaultNamespace »
  • PHP Manual
  • DOMNode
  • Adds a new child before a reference node

DOMNode::insertBefore

(PHP 5, PHP 7)

DOMNode::insertBefore — Adds a new child before a reference node

Description

public DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] ) : DOMNode

This function inserts a new node right before the reference node. If you plan to do further modifications on the appended child you must use the returned node.

Parameters

newnode

The new node.

refnode

The reference node. If not supplied, newnode is appended to the children.

Return Values

The inserted node.

Errors/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if this node is readonly or if the previous parent of the node being inserted is readonly.

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of the newnode node, or if the node to append is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if newnode was created from a different document than the one that created this node.

DOM_NOT_FOUND

Raised if refnode is not a child of this node.

See Also

  • DOMNode::appendChild() - Adds new child at the end of the children


Checks if the specified namespaceURI is the default namespace or not

  • « DOMNode::insertBefore
  • DOMNode::isSameNode »
  • PHP Manual
  • DOMNode
  • Checks if the specified namespaceURI is the default namespace or not

DOMNode::isDefaultNamespace

(PHP 5, PHP 7)

DOMNode::isDefaultNamespace — Checks if the specified namespaceURI is the default namespace or not

Description

public DOMNode::isDefaultNamespace ( string $namespaceURI ) : bool

Tells whether namespaceURI is the default namespace.

Parameters

namespaceURI

The namespace URI to look for.

Return Values

Return TRUE if namespaceURI is the default namespace, FALSE otherwise.


Indicates if two nodes are the same node

  • « DOMNode::isDefaultNamespace
  • DOMNode::isSupported »
  • PHP Manual
  • DOMNode
  • Indicates if two nodes are the same node

DOMNode::isSameNode

(PHP 5, PHP 7)

DOMNode::isSameNode — Indicates if two nodes are the same node

Description

public DOMNode::isSameNode ( DOMNode $node ) : bool

This function indicates if two nodes are the same node. The comparison is not based on content

Parameters

node

The compared node.

Return Values

Returns TRUE on success or FALSE on failure.


Checks if feature is supported for specified version

  • « DOMNode::isSameNode
  • DOMNode::lookupNamespaceUri »
  • PHP Manual
  • DOMNode
  • Checks if feature is supported for specified version

DOMNode::isSupported

(PHP 5, PHP 7)

DOMNode::isSupported — Checks if feature is supported for specified version

Description

public DOMNode::isSupported ( string $feature , string $version ) : bool

Checks if the asked feature is supported for the specified version.

Parameters

feature

The feature to test. See the example of DOMImplementation::hasFeature() for a list of features.

version

The version number of the feature to test.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • DOMImplementation::hasFeature() - Test if the DOM implementation implements a specific feature


Gets the namespace URI of the node based on the prefix

  • « DOMNode::isSupported
  • DOMNode::lookupPrefix »
  • PHP Manual
  • DOMNode
  • Gets the namespace URI of the node based on the prefix

DOMNode::lookupNamespaceUri

(PHP 5, PHP 7)

DOMNode::lookupNamespaceUri — Gets the namespace URI of the node based on the prefix

Description

public DOMNode::lookupNamespaceUri ( string $prefix ) : string

Gets the namespace URI of the node based on the prefix.

Parameters

prefix

The prefix of the namespace.

Return Values

The namespace URI of the node.

See Also

  • DOMNode::lookupPrefix() - Gets the namespace prefix of the node based on the namespace URI


Gets the namespace prefix of the node based on the namespace URI

  • « DOMNode::lookupNamespaceUri
  • DOMNode::normalize »
  • PHP Manual
  • DOMNode
  • Gets the namespace prefix of the node based on the namespace URI

DOMNode::lookupPrefix

(PHP 5, PHP 7)

DOMNode::lookupPrefix — Gets the namespace prefix of the node based on the namespace URI

Description

public DOMNode::lookupPrefix ( string $namespaceURI ) : string

Gets the namespace prefix of the node based on the namespace URI.

Parameters

namespaceURI

The namespace URI.

Return Values

The prefix of the namespace.

See Also

  • DOMNode::lookupNamespaceUri() - Gets the namespace URI of the node based on the prefix


Normalizes the node

  • « DOMNode::lookupPrefix
  • DOMNode::removeChild »
  • PHP Manual
  • DOMNode
  • Normalizes the node

DOMNode::normalize

(PHP 5, PHP 7)

DOMNode::normalize — Normalizes the node

Description

public DOMNode::normalize ( void ) : void

Remove empty text nodes and merge adjacent text nodes in this node and all its children.

Return Values

No value is returned.

See Also

  • » The DOM Specification
  • DOMDocument::normalizeDocument() - Normalizes the document


Removes child from list of children

  • « DOMNode::normalize
  • DOMNode::replaceChild »
  • PHP Manual
  • DOMNode
  • Removes child from list of children

DOMNode::removeChild

(PHP 5, PHP 7)

DOMNode::removeChild — Removes child from list of children

Description

public DOMNode::removeChild ( DOMNode $oldnode ) : DOMNode

This functions removes a child from a list of children.

Parameters

oldnode

The removed child.

Return Values

If the child could be removed the function returns the old child.

Errors/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if this node is readonly.

DOM_NOT_FOUND

Raised if oldnode is not a child of this node.

Examples

The following example will delete the chapter element of our XML document.

Example #1 Removing a child

<?php

$doc = new DOMDocument;
$doc->load('book.xml');

$book = $doc->documentElement;

// we retrieve the chapter and remove it from the book
$chapter = $book->getElementsByTagName('chapter')->item(0);
$oldchapter = $book->removeChild($chapter);

echo $doc->saveXML();
?>

The above example will output:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
          "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd">
<book id="listing">
 <title>My lists</title>

</book>

See Also

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMNode::replaceChild() - Replaces a child


Replaces a child

  • « DOMNode::removeChild
  • DOMNodeList »
  • PHP Manual
  • DOMNode
  • Replaces a child

DOMNode::replaceChild

(PHP 5, PHP 7)

DOMNode::replaceChild — Replaces a child

Description

public DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode ) : DOMNode

This function replaces the child oldnode with the passed new node. If the newnode is already a child it will not be added a second time. If the replacement succeeds the old node is returned.

Parameters

newnode

The new node. It must be a member of the target document, i.e. created by one of the DOMDocument->createXXX() methods or imported in the document by DOMDocument::importNode.

oldnode

The old node.

Return Values

The old node or FALSE if an error occur.

Errors/Exceptions

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if this node is readonly or if the previous parent of the node being inserted is readonly.

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of the newnode node, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if newnode was created from a different document than the one that created this node.

DOM_NOT_FOUND

Raised if oldnode is not a child of this node.

See Also

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMNode::removeChild() - Removes child from list of children


The DOMNodeList class

(PHP 5, PHP 7)

Class synopsis

DOMNodeList implements Traversable , Countable {
/* Properties */
readonly public int $length ;
/* Methods */
public count ( void ) : int
item ( int $index ) : DOMNode
}

Properties

length

The number of nodes in the list. The range of valid child node indices is 0 to length - 1 inclusive.

Changelog

Version | Description
7.2.0 | The Countable interface is implemented and returns the value of the length property.

See Also

  • » W3C specification of NodeList

Table of Contents

  • DOMNodeList::count — Get number of nodes in the list
  • DOMNodeList::item — Retrieves a node specified by index


Get number of nodes in the list

  • « DOMNodeList
  • DOMNodeList::item »
  • PHP Manual
  • DOMNodeList
  • Get number of nodes in the list

DOMNodeList::count

(PHP 7 >= 7.2.0)

DOMNodeList::count — Get number of nodes in the list

Description

public DOMNodeList::count ( void ) : int

Gets the number of nodes in the list.

Parameters

This function has no parameters.

Return Values

Returns the number of nodes in the list, which is identical to the length property.


Retrieves a node specified by index

  • « DOMNodeList::count
  • DOMNotation »
  • PHP Manual
  • DOMNodeList
  • Retrieves a node specified by index

DOMNodeList::item

(PHP 5, PHP 7)

DOMNodeList::item — Retrieves a node specified by index

Description

DOMNodeList::item ( int $index ) : DOMNode

Retrieves a node specified by index within the DOMNodeList object.

Tip

If you need to know the number of nodes in the collection, use the length property of the DOMNodeList object.

Parameters

index

Index of the node into the collection.

Return Values

The node at the indexth position in the DOMNodeList, or NULL if that is not a valid index.

Examples

Example #1 Traversing all the entries of the table

<?php

$doc = new DOMDocument;
$doc->load('book.xml');

$items = $doc->getElementsByTagName('entry');

for ($i = 0; $i < $items->length; $i++) {
    echo $items->item($i)->nodeValue . "\n";
}

?>

Alternatively, you can use foreach, which is a much more convenient way:

<?php

foreach ($items as $item) {
    echo $item->nodeValue . "\n";
}

?>

The above example will output:

Title
Author
Language
ISBN
The Grapes of Wrath
John Steinbeck
en
0140186409
The Pearl
John Steinbeck
en
014017737X
Samarcande
Amine Maalouf
fr
2253051209


The DOMNotation class

(PHP 5, PHP 7)

Class synopsis

DOMNotation extends DOMNode {
/* Properties */
readonly public string $publicId ;
readonly public string $systemId ;
/* Inherited properties */
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode $parentNode ;
public readonly DOMNodeList $childNodes ;
public readonly DOMNode $firstChild ;
public readonly DOMNode $lastChild ;
public readonly DOMNode $previousSibling ;
public readonly DOMNode $nextSibling ;
public readonly DOMNamedNodeMap $attributes ;
public readonly DOMDocument $ownerDocument ;
public readonly string $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string $baseURI ;
public string $textContent ;
/* Inherited methods */
public DOMNode::appendChild ( DOMNode $newnode ) : DOMNode
public DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] ) : string
public DOMNode::C14NFile ( string $uri [, bool $exclusive = FALSE [, bool $with_comments = FALSE [, array $xpath [, array $ns_prefixes ]]]] ) : int
public DOMNode::cloneNode ([ bool $deep ] ) : DOMNode
public DOMNode::getLineNo ( void ) : int
public DOMNode::getNodePath ( void ) : string
public DOMNode::hasAttributes ( void ) : bool
public DOMNode::hasChildNodes ( void ) : bool
public DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] ) : DOMNode
public DOMNode::isDefaultNamespace ( string $namespaceURI ) : bool
public DOMNode::isSameNode ( DOMNode $node ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespaceURI ) : string
public DOMNode::normalize ( void ) : void
public DOMNode::removeChild ( DOMNode $oldnode ) : DOMNode
public DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode ) : DOMNode
}

Properties

publicId

systemId


The DOMProcessingInstruction class

(PHP 5, PHP 7)

Class synopsis

DOMProcessingInstruction extends DOMNode {
/* Properties */
readonly public string $target ;
public string $data ;
/* Inherited properties */
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode $parentNode ;
public readonly DOMNodeList $childNodes ;
public readonly DOMNode $firstChild ;
public readonly DOMNode $lastChild ;
public readonly DOMNode $previousSibling ;
public readonly DOMNode $nextSibling ;
public readonly DOMNamedNodeMap $attributes ;
public readonly DOMDocument $ownerDocument ;
public readonly string $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string $baseURI ;
public string $textContent ;
/* Methods */
public __construct ( string $name [, string $value ] )
/* Inherited methods */
public DOMNode::appendChild ( DOMNode $newnode ) : DOMNode
public DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] ) : string
public DOMNode::C14NFile ( string $uri [, bool $exclusive = FALSE [, bool $with_comments = FALSE [, array $xpath [, array $ns_prefixes ]]]] ) : int
public DOMNode::cloneNode ([ bool $deep ] ) : DOMNode
public DOMNode::getLineNo ( void ) : int
public DOMNode::getNodePath ( void ) : string
public DOMNode::hasAttributes ( void ) : bool
public DOMNode::hasChildNodes ( void ) : bool
public DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] ) : DOMNode
public DOMNode::isDefaultNamespace ( string $namespaceURI ) : bool
public DOMNode::isSameNode ( DOMNode $node ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespaceURI ) : string
public DOMNode::normalize ( void ) : void
public DOMNode::removeChild ( DOMNode $oldnode ) : DOMNode
public DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode ) : DOMNode
}

Properties

target

data

Table of Contents

  • DOMProcessingInstruction::__construct — Creates a new DOMProcessingInstruction object


Creates a new DOMProcessingInstruction object

  • « DOMProcessingInstruction
  • DOMText »
  • PHP Manual
  • DOMProcessingInstruction
  • Creates a new DOMProcessingInstruction object

DOMProcessingInstruction::__construct

(PHP 5, PHP 7)

DOMProcessingInstruction::__construct — Creates a new DOMProcessingInstruction object

Description

public DOMProcessingInstruction::__construct ( string $name [, string $value ] )

Creates a new DOMProcessingInstruction object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writeable node, use DOMDocument::createProcessingInstruction.

Parameters

name

The tag name of the processing instruction.

value

The value of the processing instruction.

Examples

Example #1 Creating a new DOMProcessingInstruction object

<?php

$dom = new DOMDocument('1.0', 'UTF-8');
$html = $dom->appendChild(new DOMElement('html'));
$body = $html->appendChild(new DOMElement('body'));
$pinode = new DOMProcessingInstruction('php', 'echo "Hello World"; ');
$body->appendChild($pinode);
echo $dom->saveXML();

?>

The above example will output:

<?xml version="1.0" encoding="UTF-8"?>
<html><body><?php echo "Hello World"; ?></body></html>

See Also

  • DOMDocument::createProcessingInstruction() - Creates new PI node


The DOMText class

(PHP 5, PHP 7)

Introduction

The DOMText class inherits from DOMCharacterData and represents the textual content of a DOMElement or DOMAttr.

Class synopsis

DOMText extends DOMCharacterData {
/* Properties */
readonly public string $wholeText ;
/* Inherited properties */
public string $data ;
readonly public int $length ;
public readonly string $nodeName ;
public string $nodeValue ;
public readonly int $nodeType ;
public readonly DOMNode $parentNode ;
public readonly DOMNodeList $childNodes ;
public readonly DOMNode $firstChild ;
public readonly DOMNode $lastChild ;
public readonly DOMNode $previousSibling ;
public readonly DOMNode $nextSibling ;
public readonly DOMNamedNodeMap $attributes ;
public readonly DOMDocument $ownerDocument ;
public readonly string $namespaceURI ;
public string $prefix ;
public readonly string $localName ;
public readonly string $baseURI ;
public string $textContent ;
/* Methods */
public __construct ([ string $value ] )
public isElementContentWhitespace ( void ) : bool
public isWhitespaceInElementContent ( void ) : bool
public splitText ( int $offset ) : DOMText
/* Inherited methods */
public DOMCharacterData::appendData ( string $data ) : void
public DOMCharacterData::deleteData ( int $offset , int $count ) : void
public DOMCharacterData::insertData ( int $offset , string $data ) : void
public DOMCharacterData::replaceData ( int $offset , int $count , string $data ) : void
public DOMCharacterData::substringData ( int $offset , int $count ) : string
public DOMNode::appendChild ( DOMNode $newnode ) : DOMNode
public DOMNode::C14N ([ bool $exclusive [, bool $with_comments [, array $xpath [, array $ns_prefixes ]]]] ) : string
public DOMNode::C14NFile ( string $uri [, bool $exclusive = FALSE [, bool $with_comments = FALSE [, array $xpath [, array $ns_prefixes ]]]] ) : int
public DOMNode::cloneNode ([ bool $deep ] ) : DOMNode
public DOMNode::getLineNo ( void ) : int
public DOMNode::getNodePath ( void ) : string
public DOMNode::hasAttributes ( void ) : bool
public DOMNode::hasChildNodes ( void ) : bool
public DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] ) : DOMNode
public DOMNode::isDefaultNamespace ( string $namespaceURI ) : bool
public DOMNode::isSameNode ( DOMNode $node ) : bool
public DOMNode::isSupported ( string $feature , string $version ) : bool
public DOMNode::lookupNamespaceUri ( string $prefix ) : string
public DOMNode::lookupPrefix ( string $namespaceURI ) : string
public DOMNode::normalize ( void ) : void
public DOMNode::removeChild ( DOMNode $oldnode ) : DOMNode
public DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode ) : DOMNode
}

Properties

wholeText

Holds all the text of logically-adjacent (not separated by Element, Comment or Processing Instruction) Text nodes.

Table of Contents

  • DOMText::__construct — Creates a new DOMText object
  • DOMText::isElementContentWhitespace — Returns whether this text node contains whitespace in element content
  • DOMText::isWhitespaceInElementContent — Indicates whether this text node contains whitespace
  • DOMText::splitText — Breaks this node into two nodes at the specified offset


Creates a new DOMText object

  • « DOMText
  • DOMText::isElementContentWhitespace »
  • PHP Manual
  • DOMText
  • Creates a new DOMText object

DOMText::__construct

(PHP 5, PHP 7)

DOMText::__construct — Creates a new DOMText object

Description

public DOMText::__construct ([ string $value ] )

Creates a new DOMText object.

Parameters

value

The value of the text node. If not supplied an empty text node is created.

Examples

Example #1 Creating a new DOMText

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$text = $element->appendChild(new DOMText('root value'));
echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?><root>root value</root> */

?>

See Also

  • DOMDocument::createTextNode() - Create new text node


Returns whether this text node contains whitespace in element content

  • « DOMText::__construct
  • DOMText::isWhitespaceInElementContent »
  • PHP Manual
  • DOMText
  • Returns whether this text node contains whitespace in element content

DOMText::isElementContentWhitespace

(No version information available, might only be in Git)

DOMText::isElementContentWhitespace — Returns whether this text node contains whitespace in element content

Description

public DOMText::isElementContentWhitespace ( void ) : bool

Parameters

This function has no parameters.

Return Values

Returns TRUE on success or FALSE on failure.


Indicates whether this text node contains whitespace

  • « DOMText::isElementContentWhitespace
  • DOMText::splitText »
  • PHP Manual
  • DOMText
  • Indicates whether this text node contains whitespace

DOMText::isWhitespaceInElementContent

(PHP 5, PHP 7)

DOMText::isWhitespaceInElementContent — Indicates whether this text node contains whitespace

Description

public DOMText::isWhitespaceInElementContent ( void ) : bool

Indicates whether this text node contains only whitespace or it is empty. The text node is determined to contain whitespace in element content during the load of the document.

Return Values

Returns TRUE if node contains zero or more whitespace characters and nothing else. Returns FALSE otherwise.


Breaks this node into two nodes at the specified offset

  • « DOMText::isWhitespaceInElementContent
  • DOMXPath »
  • PHP Manual
  • DOMText
  • Breaks this node into two nodes at the specified offset

DOMText::splitText

(PHP 5, PHP 7)

DOMText::splitText — Breaks this node into two nodes at the specified offset

Description

public DOMText::splitText ( int $offset ) : DOMText

Breaks this node into two nodes at the specified offset, keeping both in the tree as siblings.

After being split, this node will contain all the content up to the offset. If the original node had a parent node, the new node is inserted as the next sibling of the original node. When the offset is equal to the length of this node, the new node has no data.

Parameters

offset

The offset at which to split, starting from 0.

Return Values

The new node of the same type, which contains all the content at and after the offset.


The DOMXPath class

(PHP 5, PHP 7)

Introduction

Supports XPath 1.0

Class synopsis

DOMXPath {
/* Properties */
public DOMDocument $document ;
/* Methods */
public __construct ( DOMDocument $doc )
public evaluate ( string $expression [, DOMNode $contextnode [, bool $registerNodeNS = TRUE ]] ) : mixed
public query ( string $expression [, DOMNode $contextnode [, bool $registerNodeNS = TRUE ]] ) : DOMNodeList
public registerNamespace ( string $prefix , string $namespaceURI ) : bool
public registerPhpFunctions ([ mixed $restrict ] ) : void
}

Properties

document

Table of Contents

  • DOMXPath::__construct — Creates a new DOMXPath object
  • DOMXPath::evaluate — Evaluates the given XPath expression and returns a typed result if possible
  • DOMXPath::query — Evaluates the given XPath expression
  • DOMXPath::registerNamespace — Registers the namespace with the DOMXPath object
  • DOMXPath::registerPhpFunctions — Register PHP functions as XPath functions


Creates a new DOMXPath object

  • « DOMXPath
  • DOMXPath::evaluate »
  • PHP Manual
  • DOMXPath
  • Creates a new DOMXPath object

DOMXPath::__construct

(PHP 5, PHP 7)

DOMXPath::__construct — Creates a new DOMXPath object

Description

public DOMXPath::__construct ( DOMDocument $doc )

Creates a new DOMXPath object.

Parameters

doc

The DOMDocument associated with the DOMXPath.


Evaluates the given XPath expression and returns a typed result if possible

  • « DOMXPath::__construct
  • DOMXPath::query »
  • PHP Manual
  • DOMXPath
  • Evaluates the given XPath expression and returns a typed result if possible

DOMXPath::evaluate

(PHP 5 >= 5.1.0, PHP 7)

DOMXPath::evaluate — Evaluates the given XPath expression and returns a typed result if possible

Description

public DOMXPath::evaluate ( string $expression [, DOMNode $contextnode [, bool $registerNodeNS = TRUE ]] ) : mixed

Executes the given XPath expression and returns a typed result if possible.

Parameters

expression

The XPath expression to execute.

contextnode

The optional contextnode can be specified for doing relative XPath queries. By default, the queries are relative to the root element.

registerNodeNS

The optional registerNodeNS can be specified to disable automatic registration of the context node.

Return Values

Returns a typed result if possible or a DOMNodeList containing all nodes matching the given XPath expression.

If the expression is malformed or the contextnode is invalid, DOMXPath::evaluate() returns FALSE.

Changelog

Version | Description
5.3.3 | The registerNodeNS parameter was added.

Examples

Example #1 Getting the count of all the english books

<?php

$doc = new DOMDocument;

$doc->load('book.xml');

$xpath = new DOMXPath($doc);

$tbody = $doc->getElementsByTagName('tbody')->item(0);

// our query is relative to the tbody node
$query = 'count(row/entry[. = "en"])';

$entries = $xpath->evaluate($query, $tbody);
echo "There are $entries english books\n";

?>

The above example will output:

There are 2 english books

See Also

  • DOMXPath::query() - Evaluates the given XPath expression


Evaluates the given XPath expression

  • « DOMXPath::evaluate
  • DOMXPath::registerNamespace »
  • PHP Manual
  • DOMXPath
  • Evaluates the given XPath expression

DOMXPath::query

(PHP 5, PHP 7)

DOMXPath::query — Evaluates the given XPath expression

Description

public DOMXPath::query ( string $expression [, DOMNode $contextnode [, bool $registerNodeNS = TRUE ]] ) : DOMNodeList

Executes the given XPath expression.

Parameters

expression

The XPath expression to execute.

contextnode

The optional contextnode can be specified for doing relative XPath queries. By default, the queries are relative to the root element.

registerNodeNS

The optional registerNodeNS can be specified to disable automatic registration of the context node.

Return Values

Returns a DOMNodeList containing all nodes matching the given XPath expression. Any expression which does not return nodes will return an empty DOMNodeList.

If the expression is malformed or the contextnode is invalid, DOMXPath::query() returns FALSE.

Changelog

Version | Description
5.3.3 | The registerNodeNS parameter was added.

Examples

Example #1 Getting all the english books

<?php

$doc = new DOMDocument;

// We don't want to bother with white spaces
$doc->preserveWhiteSpace = false;

$doc->load('book.xml');

$xpath = new DOMXPath($doc);

// We starts from the root element
$query = '//book/chapter/para/informaltable/tgroup/tbody/row/entry[. = "en"]';

$entries = $xpath->query($query);

foreach ($entries as $entry) {
    echo "Found {$entry->previousSibling->previousSibling->nodeValue}," .
         " by {$entry->previousSibling->nodeValue}\n";
}
?>

The above example will output:

Found The Grapes of Wrath, by John Steinbeck
Found The Pearl, by John Steinbeck

We can also use the contextnode parameter to shorten our expression:

<?php

$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;

$doc->load('book.xml');

$xpath = new DOMXPath($doc);

$tbody = $doc->getElementsByTagName('tbody')->item(0);

// our query is relative to the tbody node
$query = 'row/entry[. = "en"]';

$entries = $xpath->query($query, $tbody);

foreach ($entries as $entry) {
    echo "Found {$entry->previousSibling->previousSibling->nodeValue}," .
         " by {$entry->previousSibling->nodeValue}\n";
}
?>

See Also

  • DOMXPath::evaluate() - Evaluates the given XPath expression and returns a typed result if possible


Registers the namespace with the DOMXPath object

  • « DOMXPath::query
  • DOMXPath::registerPhpFunctions »
  • PHP Manual
  • DOMXPath
  • Registers the namespace with the DOMXPath object

DOMXPath::registerNamespace

(PHP 5, PHP 7)

DOMXPath::registerNamespace — Registers the namespace with the DOMXPath object

Description

public DOMXPath::registerNamespace ( string $prefix , string $namespaceURI ) : bool

Registers the namespaceURI and prefix with the DOMXPath object.

Parameters

prefix

The prefix.

namespaceURI

The URI of the namespace.

Return Values

Returns TRUE on success or FALSE on failure.


Register PHP functions as XPath functions

  • « DOMXPath::registerNamespace
  • DOM Functions »
  • PHP Manual
  • DOMXPath
  • Register PHP functions as XPath functions

DOMXPath::registerPhpFunctions

(PHP 5 >= 5.3.0, PHP 7)

DOMXPath::registerPhpFunctions — Register PHP functions as XPath functions

Description

public DOMXPath::registerPhpFunctions ([ mixed $restrict ] ) : void

This method enables the ability to use PHP functions within XPath expressions.

Parameters

restrict

Use this parameter to only allow certain functions to be called from XPath.

This parameter can be either a string (a function name) or an array of function names.

Return Values

No value is returned.

Examples

The following examples use book.xml which contains the following:

Example #1 book.xml

<?xml version="1.0" encoding="UTF-8"?>
<books>
 <book>
  <title>PHP Basics</title>
  <author>Jim Smith</author>
  <author>Jane Smith</author>
 </book>
 <book>
  <title>PHP Secrets</title>
  <author>Jenny Smythe</author>
 </book>
 <book>
  <title>XML basics</title>
  <author>Joe Black</author>
 </book>
</books>

Example #2 DOMXPath::registerPHPFunctions() with php:functionString

<?php
$doc = new DOMDocument;
$doc->load('book.xml');

$xpath = new DOMXPath($doc);

// Register the php: namespace (required)
$xpath->registerNamespace("php", "http://php.net/xpath");

// Register PHP functions (no restrictions)
$xpath->registerPHPFunctions();

// Call substr function on the book title
$nodes = $xpath->query('//book[php:functionString("substr", title, 0, 3) = "PHP"]');

echo "Found {$nodes->length} books starting with 'PHP':\n";
foreach ($nodes as $node) {
    $title  = $node->getElementsByTagName("title")->item(0)->nodeValue;
    $author = $node->getElementsByTagName("author")->item(0)->nodeValue;
    echo "$title by $author\n";
}

?>

The above example will output something similar to:

Found 2 books starting with 'PHP':
PHP Basics by Jim Smith
PHP Secrets by Jenny Smythe

Example #3 DOMXPath::registerPHPFunctions() with php:function

<?php
$doc = new DOMDocument;
$doc->load('book.xml');

$xpath = new DOMXPath($doc);

// Register the php: namespace (required)
$xpath->registerNamespace("php", "http://php.net/xpath");

// Register PHP functions (has_multiple only)
$xpath->registerPHPFunctions("has_multiple");

function has_multiple($nodes) {
    // Return true if more than one author
    return count($nodes) > 1;
}
// Filter books with multiple authors
$books = $xpath->query('//book[php:function("has_multiple", author)]');

echo "Books with multiple authors:\n";
foreach ($books as $book) {
    echo $book->getElementsByTagName("title")->item(0)->nodeValue . "\n";
}

?>

The above example will output something similar to:

Books with multiple authors:
PHP Basics

See Also

  • DOMXPath::registerNamespace() - Registers the namespace with the DOMXPath object
  • DOMXPath::query() - Evaluates the given XPath expression
  • DOMXPath::evaluate() - Evaluates the given XPath expression and returns a typed result if possible


DOM Functions

Table of Contents

  • dom_import_simplexml — Gets a DOMElement object from a SimpleXMLElement object


Gets a DOMElement object from a SimpleXMLElement object

  • « DOM Functions
  • libxml »
  • PHP Manual
  • DOM Functions
  • Gets a DOMElement object from a SimpleXMLElement object

dom_import_simplexml

(PHP 5, PHP 7)

dom_import_simplexml — Gets a DOMElement object from a SimpleXMLElement object

Description

dom_import_simplexml ( SimpleXMLElement $node ) : DOMElement

This function takes the node node of class SimpleXML and makes it into a DOMElement node. This new object can then be used as a native DOMElement node.

Parameters

node

The SimpleXMLElement node.

Return Values

The DOMElement node added or FALSE if any errors occur.

Examples

Example #1 Import SimpleXML into DOM with dom_import_simplexml()

<?php

$sxe = simplexml_load_string('<books><book><title>blah</title></book></books>');

if ($sxe === false) {
    echo 'Error while parsing the document';
    exit;
}

$dom_sxe = dom_import_simplexml($sxe);
if (!$dom_sxe) {
    echo 'Error while converting XML';
    exit;
}

$dom = new DOMDocument('1.0');
$dom_sxe = $dom->importNode($dom_sxe, true);
$dom_sxe = $dom->appendChild($dom_sxe);

echo $dom->saveXML();

?>

See Also

  • simplexml_import_dom() - Get a SimpleXMLElement object from a DOM node


libxml

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • libXMLError — The libXMLError class
  • libxml Functions
    • libxml_clear_errors — Clear libxml error buffer
    • libxml_disable_entity_loader — Disable the ability to load external entities
    • libxml_get_errors — Retrieve array of errors
    • libxml_get_last_error — Retrieve last error from libxml
    • libxml_set_external_entity_loader — Changes the default external entity loader
    • libxml_set_streams_context — Set the streams context for the next libxml document load or write
    • libxml_use_internal_errors — Disable libxml errors and allow user to fetch error information as needed


Introduction

These functions/constants are available as of PHP 5.1.0, and the following core extensions rely on this libxml extension: DOM, libxml, SimpleXML, SOAP, WDDX, XSL, XML, XMLReader, XMLRPC and XMLWriter.


  • « Installing/Configuring
  • Installation »
  • PHP Manual
  • Installing/Configuring
  • Requirements

Requirements

This extension requires » libxml >= 2.6.0.


Installation

The libxml extension is enabled by default, although it may be disabled with --disable-libxml .

The optional --with-libxml-dir directive is used to specify the location of libxml on the system that PHP is being compiled on, otherwise only the default locations are scanned. The configure process checks for libxml (specifically, xml2-config) in the following order:

  1. The location ([DIR]) specified with --with-libxml-dir ([DIR]=/bin/xml2-config)

  2. /usr/local/bin/xml2-config

  3. /usr/bin/xml2-config

If configure cannot find xml2-config in the directory specified by --with-libxml-dir , then it'll continue on and check the default locations.


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.

LIBXML_BIGLINES (integer)
Allows line numbers greater than 65535 to be reported correctly.

Note:

Only available as of PHP 7.0.0 with Libxml >= 2.9.0

LIBXML_COMPACT (integer)
Activate small nodes allocation optimization. This may speed up your application without needing to change the code.

Note:

Only available in Libxml >= 2.6.21

LIBXML_DTDATTR (integer)
Default DTD attributes
LIBXML_DTDLOAD (integer)
Load the external subset
LIBXML_DTDVALID (integer)
Validate with the DTD
LIBXML_HTML_NOIMPLIED (integer)
Sets HTML_PARSE_NOIMPLIED flag, which turns off the automatic adding of implied html/body... elements.

Note:

Only available in Libxml >= 2.7.7 (as of PHP >= 5.4.0)

LIBXML_HTML_NODEFDTD (integer)
Sets HTML_PARSE_NODEFDTD flag, which prevents a default doctype being added when one is not found.

Note:

Only available in Libxml >= 2.7.8 (as of PHP >= 5.4.0)

LIBXML_NOBLANKS (integer)
Remove blank nodes
LIBXML_NOCDATA (integer)
Merge CDATA as text nodes
LIBXML_NOEMPTYTAG (integer)
Expand empty tags (e.g. <br/> to <br></br>)

Note:

This option is currently just available in the DOMDocument::save and DOMDocument::saveXML functions.

LIBXML_NOENT (integer)
Substitute entities
LIBXML_NOERROR (integer)
Suppress error reports
LIBXML_NONET (integer)
Disable network access when loading documents
LIBXML_NOWARNING (integer)
Suppress warning reports
LIBXML_NOXMLDECL (integer)
Drop the XML declaration when saving a document

Note:

Only available in Libxml >= 2.6.21

LIBXML_NSCLEAN (integer)
Remove redundant namespace declarations
LIBXML_PARSEHUGE (integer)
Sets XML_PARSE_HUGE flag, which relaxes any hardcoded limit from the parser. This affects limits like maximum depth of a document or the entity recursion, as well as limits of the size of text nodes.

Note:

Only available in Libxml >= 2.7.0 (as of PHP >= 5.3.2 and PHP >= 5.2.12)

LIBXML_PEDANTIC (integer)
Sets XML_PARSE_PEDANTIC flag, which enables pedantic error reporting.

Note:

Available as of PHP >= 5.4.0

LIBXML_XINCLUDE (integer)
Implement XInclude substitution
LIBXML_ERR_ERROR (integer)
A recoverable error
LIBXML_ERR_FATAL (integer)
A fatal error
LIBXML_ERR_NONE (integer)
No errors
LIBXML_ERR_WARNING (integer)
A simple warning
LIBXML_VERSION (integer)
libxml version like 20605 or 20617
LIBXML_DOTTED_VERSION (string)
libxml version like 2.6.5 or 2.6.17
LIBXML_SCHEMA_CREATE (integer)
Create default/fixed value nodes during XSD schema validation

Note:

Only available in Libxml >= 2.6.14 (as of PHP >= 5.5.2)


The libXMLError class

(PHP 5 >= 5.1.0, PHP 7)

Introduction

Contains various information about errors thrown by libxml. The error codes are described within the official » xmlError API documentation.

Class synopsis

libXMLError {
/* Properties */
public int $level ;
public int $code ;
public int $column ;
public string $message ;
public string $file ;
public int $line ;
}

Properties

level

the severity of the error (one of the following constants: LIBXML_ERR_WARNING, LIBXML_ERR_ERROR or LIBXML_ERR_FATAL)

code

The error's code.

column

The column where the error occurred.

Note:

This property isn't entirely implemented in libxml and therefore 0 is often returned.

message

The error message, if any.

file

The filename, or empty if the XML was loaded from a string.

line

The line where the error occurred.


libxml Functions

Table of Contents

  • libxml_clear_errors — Clear libxml error buffer
  • libxml_disable_entity_loader — Disable the ability to load external entities
  • libxml_get_errors — Retrieve array of errors
  • libxml_get_last_error — Retrieve last error from libxml
  • libxml_set_external_entity_loader — Changes the default external entity loader
  • libxml_set_streams_context — Set the streams context for the next libxml document load or write
  • libxml_use_internal_errors — Disable libxml errors and allow user to fetch error information as needed


Clear libxml error buffer

  • « libxml Functions
  • libxml_disable_entity_loader »
  • PHP Manual
  • libxml Functions
  • Clear libxml error buffer

libxml_clear_errors

(PHP 5 >= 5.1.0, PHP 7)

libxml_clear_errors — Clear libxml error buffer

Description

libxml_clear_errors ( void ) : void

libxml_clear_errors() clears the libxml error buffer.

Return Values

No value is returned.

See Also

  • libxml_get_errors() - Retrieve array of errors
  • libxml_get_last_error() - Retrieve last error from libxml


Disable the ability to load external entities

  • « libxml_clear_errors
  • libxml_get_errors »
  • PHP Manual
  • libxml Functions
  • Disable the ability to load external entities

libxml_disable_entity_loader

(PHP 5 >= 5.2.11, PHP 7)

libxml_disable_entity_loader — Disable the ability to load external entities

Description

libxml_disable_entity_loader ([ bool $disable = TRUE ] ) : bool

Disable/enable the ability to load external entities.

Parameters

disable

Disable (TRUE) or enable (FALSE) libxml extensions (such as DOM, XMLWriter and XMLReader) to load external entities.

Return Values

Returns the previous value.

See Also

  • libxml_use_internal_errors() - Disable libxml errors and allow user to fetch error information as needed
  • The LIBXML_NONET constant


Retrieve array of errors

  • « libxml_disable_entity_loader
  • libxml_get_last_error »
  • PHP Manual
  • libxml Functions
  • Retrieve array of errors

libxml_get_errors

(PHP 5 >= 5.1.0, PHP 7)

libxml_get_errors — Retrieve array of errors

Description

libxml_get_errors ( void ) : array

Retrieve array of errors.

Return Values

Returns an array with LibXMLError objects if there are any errors in the buffer, or an empty array otherwise.

Examples

Example #1 A libxml_get_errors() example

This example demonstrates how to build a simple libxml error handler.

<?php

libxml_use_internal_errors(true);

$xmlstr = <<< XML
<?xml version='1.0' standalone='yes'?>
<movies>
 <movie>
  <titles>PHP: Behind the Parser</title>
 </movie>
</movies>
XML;

$doc = simplexml_load_string($xmlstr);
$xml = explode("\n", $xmlstr);

if ($doc === false) {
    $errors = libxml_get_errors();

    foreach ($errors as $error) {
        echo display_xml_error($error, $xml);
    }

    libxml_clear_errors();
}

function display_xml_error($error, $xml)
{
    $return  = $xml[$error->line - 1] . "\n";
    $return .= str_repeat('-', $error->column) . "^\n";

    switch ($error->level) {
        case LIBXML_ERR_WARNING:
            $return .= "Warning $error->code: ";
            break;
         case LIBXML_ERR_ERROR:
            $return .= "Error $error->code: ";
            break;
        case LIBXML_ERR_FATAL:
            $return .= "Fatal Error $error->code: ";
            break;
    }

    $return .= trim($error->message) .
               "\n  Line: $error->line" .
               "\n  Column: $error->column";

    if ($error->file) {
        $return .= "\n  File: $error->file";
    }

    return "$return\n\n--------------------------------------------\n\n";
}

?>

The above example will output:

  <titles>PHP: Behind the Parser</title>
----------------------------------------------^
Fatal Error 76: Opening and ending tag mismatch: titles line 4 and title
  Line: 4
  Column: 46

--------------------------------------------

See Also

  • libxml_get_last_error() - Retrieve last error from libxml
  • libxml_clear_errors() - Clear libxml error buffer


Retrieve last error from libxml

  • « libxml_get_errors
  • libxml_set_external_entity_loader »
  • PHP Manual
  • libxml Functions
  • Retrieve last error from libxml

libxml_get_last_error

(PHP 5 >= 5.1.0, PHP 7)

libxml_get_last_error — Retrieve last error from libxml

Description

libxml_get_last_error ( void ) : LibXMLError

Retrieve last error from libxml.

Return Values

Returns a LibXMLError object if there is any error in the buffer, FALSE otherwise.

See Also

  • libxml_get_errors() - Retrieve array of errors
  • libxml_clear_errors() - Clear libxml error buffer


Changes the default external entity loader

  • « libxml_get_last_error
  • libxml_set_streams_context »
  • PHP Manual
  • libxml Functions
  • Changes the default external entity loader

libxml_set_external_entity_loader

(PHP 5 >= 5.4.0, PHP 7)

libxml_set_external_entity_loader — Changes the default external entity loader

Description

libxml_set_external_entity_loader ( callable $resolver_function ) : bool

Changes the default external entity loader.

Parameters

resolver_function

A callable that takes three arguments. Two strings, a public id and system id, and a context (an array with four keys) as the third argument. This callback should return a resource, a string from which a resource can be opened, or NULL.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 libxml_set_external_entity_loader() example

<?php
$xml = <<<XML
<!DOCTYPE foo PUBLIC "-//FOO/BAR" "http://example.com/foobar">
<foo>bar</foo>
XML;

$dtd = <<<DTD
<!ELEMENT foo (#PCDATA)>
DTD;

libxml_set_external_entity_loader(
    function ($public, $system, $context) use($dtd) {
        var_dump($public);
        var_dump($system);
        var_dump($context);
        $f = fopen("php://temp", "r+");
        fwrite($f, $dtd);
        rewind($f);
        return $f;
    }
);

$dd = new DOMDocument;
$r  = $dd->loadXML($xml);

var_dump($dd->validate());
?>

The above example will output:

string(10) "-//FOO/BAR"
string(25) "http://example.com/foobar"
array(4) {
    ["directory"]    => NULL
    ["intSubName"]   => NULL
    ["extSubURI"]    => NULL
    ["extSubSystem"] => NULL
}
bool(true)

See Also

  • libxml_disable_entity_loader() - Disable the ability to load external entities


Set the streams context for the next libxml document load or write

  • « libxml_set_external_entity_loader
  • libxml_use_internal_errors »
  • PHP Manual
  • libxml Functions
  • Set the streams context for the next libxml document load or write

libxml_set_streams_context

(PHP 5, PHP 7)

libxml_set_streams_context — Set the streams context for the next libxml document load or write

Description

libxml_set_streams_context ( resource $streams_context ) : void

Sets the streams context for the next libxml document load or write.

Parameters

streams_context

The stream context resource (created with stream_context_create())

Return Values

No value is returned.

Examples

Example #1 A libxml_set_streams_context() example

<?php

$opts = array(
    'http' => array(
        'user_agent' => 'PHP libxml agent',
    )
);

$context = stream_context_create($opts);
libxml_set_streams_context($context);

// request a file through HTTP
$doc = DOMDocument::load('http://www.example.com/file.xml');

?>

See Also

  • stream_context_create() - Creates a stream context


Disable libxml errors and allow user to fetch error information as needed

  • « libxml_set_streams_context
  • SDO »
  • PHP Manual
  • libxml Functions
  • Disable libxml errors and allow user to fetch error information as needed

libxml_use_internal_errors

(PHP 5 >= 5.1.0, PHP 7)

libxml_use_internal_errors — Disable libxml errors and allow user to fetch error information as needed

Description

libxml_use_internal_errors ([ bool $use_errors = FALSE ] ) : bool

libxml_use_internal_errors() allows you to disable standard libxml errors and enable user error handling.

Parameters

use_errors

Enable (TRUE) user error handling or disable (FALSE) user error handling. Disabling will also clear any existing libxml errors.

Return Values

This function returns the previous value of use_errors.

Examples

Example #1 A libxml_use_internal_errors() example

This example demonstrates the basic usage of libxml errors and the value returned by this function.

<?php

// enable user error handling
var_dump(libxml_use_internal_errors(true));

// load the document
$doc = new DOMDocument;

if (!$doc->load('file.xml')) {
    foreach (libxml_get_errors() as $error) {
        // handle errors here
    }

    libxml_clear_errors();
}

?>

The above example will output:

bool(false)

See Also

  • libxml_clear_errors() - Clear libxml error buffer
  • libxml_get_errors() - Retrieve array of errors


Service Data Objects

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Limitations
  • Examples
    • Basic usage
    • Setting and Getting Property Values
    • Working with Sequenced Data Objects
    • Reflecting on Service Data Objects
  • SDO Functions
    • SDO_DAS_ChangeSummary::beginLogging — Begin change logging
    • SDO_DAS_ChangeSummary::endLogging — End change logging
    • SDO_DAS_ChangeSummary::getChangeType — Get the type of change made to an SDO_DataObject
    • SDO_DAS_ChangeSummary::getChangedDataObjects — Get the changed data objects from a change summary
    • SDO_DAS_ChangeSummary::getOldContainer — Get the old container for a deleted SDO_DataObject
    • SDO_DAS_ChangeSummary::getOldValues — Get the old values for a given changed SDO_DataObject
    • SDO_DAS_ChangeSummary::isLogging — Test to see whether change logging is switched on
    • SDO_DAS_DataFactory::addPropertyToType — Adds a property to a type
    • SDO_DAS_DataFactory::addType — Add a new type to a model
    • SDO_DAS_DataFactory::getDataFactory — Get a data factory instance
    • SDO_DAS_DataObject::getChangeSummary — Get a data object's change summary
    • SDO_DAS_Setting::getListIndex — Get the list index for a changed many-valued property
    • SDO_DAS_Setting::getPropertyIndex — Get the property index for a changed property
    • SDO_DAS_Setting::getPropertyName — Get the property name for a changed property
    • SDO_DAS_Setting::getValue — Get the old value for the changed property
    • SDO_DAS_Setting::isSet — Test whether a property was set prior to being modified
    • SDO_DataFactory::create — Create an SDO_DataObject
    • SDO_DataObject::clear — Clear an SDO_DataObject's properties
    • SDO_DataObject::createDataObject — Create a child SDO_DataObject
    • SDO_DataObject::getContainer — Get a data object's container
    • SDO_DataObject::getSequence — Get the sequence for a data object
    • SDO_DataObject::getTypeName — Return the name of the type for a data object
    • SDO_DataObject::getTypeNamespaceURI — Return the namespace URI of the type for a data object
    • SDO_Exception::getCause — Get the cause of the exception
    • SDO_List::insert — Insert into a list
    • SDO_Model_Property::getContainingType — Get the SDO_Model_Type which contains this property
    • SDO_Model_Property::getDefault — Get the default value for the property
    • SDO_Model_Property::getName — Get the name of the SDO_Model_Property
    • SDO_Model_Property::getType — Get the SDO_Model_Type of the property
    • SDO_Model_Property::isContainment — Test to see if the property defines a containment relationship
    • SDO_Model_Property::isMany — Test to see if the property is many-valued
    • SDO_Model_ReflectionDataObject::__construct — Construct an SDO_Model_ReflectionDataObject
    • SDO_Model_ReflectionDataObject::export — Get a string describing the SDO_DataObject
    • SDO_Model_ReflectionDataObject::getContainmentProperty — Get the property which defines the containment relationship to the data object
    • SDO_Model_ReflectionDataObject::getInstanceProperties — Get the instance properties of the SDO_DataObject
    • SDO_Model_ReflectionDataObject::getType — Get the SDO_Model_Type for the SDO_DataObject
    • SDO_Model_Type::getBaseType — Get the base type for this type
    • SDO_Model_Type::getName — Get the name of the type
    • SDO_Model_Type::getNamespaceURI — Get the namespace URI of the type
    • SDO_Model_Type::getProperties — Get the SDO_Model_Property objects defined for the type
    • SDO_Model_Type::getProperty — Get an SDO_Model_Property of the type
    • SDO_Model_Type::isAbstractType — Test to see if this SDO_Model_Type is an abstract data type
    • SDO_Model_Type::isDataType — Test to see if this SDO_Model_Type is a primitive data type
    • SDO_Model_Type::isInstance — Test for an SDO_DataObject being an instance of this SDO_Model_Type
    • SDO_Model_Type::isOpenType — Test to see if this type is an open type
    • SDO_Model_Type::isSequencedType — Test to see if this is a sequenced type
    • SDO_Sequence::getProperty — Return the property for the specified sequence index
    • SDO_Sequence::insert — Insert into a sequence
    • SDO_Sequence::move — Move an item to another sequence position


Introduction

Service Data Objects (SDOs) enable PHP applications to work with data from different sources (like a database query, an XML file, and a spreadsheet) using a single interface.

Each different kind of data source requires a Data Access Service (DAS) to provide access to the data in the data source. In your PHP application, you use a DAS to create an SDO instance that represents some data in the data source. You can then set and get values in the SDO instance using the standard SDO interface. Finally, you use a DAS to write the modified data back to a data source, typically the same one.

See the list of Data Access Services for details on those currently available. In addition to the provided DASs, SDO also provides interfaces to enable others to be implemented (see the section on SDO Data Access Services Interface for more details).

This extension is derived from concepts taken from the » Service Data Objects specification. It includes a version of the » Apache Tuscany SDO for C++ project.

The Structure of a Service Data Object

A Service Data Object instance is made up of a tree of data objects. The tree is defined by containment relationships between the data objects. For example, a Company data object might consist of a number of Department data objects and therefore the Company would have a containment relationship to the Departments.

An SDO may also have non-containment references between data objects in the tree. For example, one Employee data object might reference another Employee to identify a career mentor.

As well as data objects referencing each other, they can also have primitive properties. For example, the Company data object might have a property called "name" of type string, for holding the name of the company (for example, "Acme").

Each of these properties of a data object - containment relationships, non-containment references, or primitive properties - may be many-valued or single-valued. In the above examples, Departments is many-valued and the Company name is single-valued.

In PHP, each SDO data object is represented as a PHP object. The properties of the data object can be accessed using either object syntax or associative array syntax. We'll see some examples of this later.


Requirements

The SDO extension requires PHP 5.1.0 or higher. It also requires the libxml2 library. Normally libxml2 will already be installed, but if not, it can be downloaded from » http://www.xmlsoft.org/.


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/sca_sdo.

Note:

Earlier versions of the SDO extension required a separate shared library for the XML DAS. This is now obsolete and any references to php_sdo_das_xml.dll or sdo_das_xml.so should be removed from your php.ini.

Unix systems

  1. The three SDO components - the SDO core, the XML DAS and the Relational DAS - are packaged together with Service Component Architecture (SCA) into one PECL project, SCA_SDO, so you can download SCA and all three parts of SDO with the command:

    pecl install SCA_SDO

    This command will build the SDO shared library as well as installing the PHP files that make up SCA and the SDO Relational DAS.

    If you want to use the latest beta version, then instead run:

    pecl install SCA_SDO-beta

  2. The pecl command automatically installs the SDO module into your PHP extensions directory. To enable the SDO extension you must add the following line to php.ini:

    extension=sdo.so

    For more information about building PECL packages, consult the PECL installation section of the manual.

Building SDO on Linux

This section describes how to build the SDO core and XML DAS on Linux. You would only need to know how to do this if you wish to build a recent version that you have checked out of SVN.

  1. Change to the main extension directory: cd < wherever your sdo code is >

  2. Run phpize, which will set up the environment to compile SDO.

  3. Next, run ./configure; make; make install. Please note, you may need to login as root to install the extension.

  4. Make sure that the module is loaded by PHP, by adding extension=sdo.so to your php.ini 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.

SDO_DAS_ChangeSummary::NONE=0 (integer)
Represents a change type of 'none'.
SDO_DAS_ChangeSummary::MODIFICATION=1 (integer)
Represents a change type of 'modification'.
SDO_DAS_ChangeSummary::ADDITION=2 (integer)
Represents a change type of 'addition'.
SDO_DAS_ChangeSummary::DELETION=3 (integer)
Represents a change type of 'deletion'.


Limitations

Implementation Limitations

The following are limitations in the current SDO implementation:

  1. There is no support for multi-byte character sets. This will be considered, depending on community requirements, in a Unicode-enabled version of PHP.

SDO Limitations

The following SDO 2.0 concepts are not supported in the current PHP implementation. It is not necessarily the case that these will all be added over time. Their inclusion will depend on community requirements.

  1. Bi-directional relationships.

  2. Type and property alias names.

  3. Read-only properties.

  4. The Helper classes defined in SDO 2.0 are not directly implemented. However equivalent function is provided in a more natural way for PHP. For example the function of CopyHelper::copy() is provided by applying the PHP clone keyword to a data object.


Examples

Table of Contents

  • Basic usage
  • Setting and Getting Property Values
  • Working with Sequenced Data Objects
  • Reflecting on Service Data Objects


Basic usage

The examples below assume an SDO created with the schema and instance information shown below, using the XML Data Access Service.

The instance document below describes a single company, called 'MegaCorp', which contains a single department, called 'Advanced Technologies'. The Advanced Technologies department contains three employees. The company employeeOfTheMonth is referencing the second employee, 'Jane Doe'.

<?xml version="1.0" encoding="UTF-8" ?>
<company xmlns="companyNS" name="MegaCorp"
  employeeOfTheMonth="E0003">
  <departments name="Advanced Technologies" location="NY" number="123">
    <employees name="John Jones" SN="E0001"/>
    <employees name="Jane Doe" SN="E0003"/>
    <employees name="Al Smith" SN="E0004" manager="true"/>
  </departments>
</company>

The root element of the schema is a company. The company contains departments, and each department contains employees. Each element has a number of attributes to store things like name, serial number, and so on. Finally, the company also has an IDREF attribute which identifies one of the employees as the 'employeeOfTheMonth'.

<xsd:schema
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:sdo="commonj.sdo"
  xmlns:sdoxml="commonj.sdo/xml"
  xmlns:company="companyNS"
  targetNamespace="companyNS">
  <xsd:element name="company" type="company:CompanyType"/>
  <xsd:complexType name="CompanyType">
    <xsd:sequence>
      <xsd:element name="departments" type="company:DepartmentType"
        maxOccurs="unbounded"/>
    </xsd:sequence>
    <xsd:attribute name="name" type="xsd:string"/>
    <xsd:attribute name="employeeOfTheMonth" type="xsd:IDREF"
      sdoxml:propertyType="company:EmployeeType"/>
  </xsd:complexType>
  <xsd:complexType name="DepartmentType">
    <xsd:sequence>
      <xsd:element name="employees" type="company:EmployeeType"
        maxOccurs="unbounded"/>
    </xsd:sequence>
    <xsd:attribute name="name" type="xsd:string"/>
    <xsd:attribute name="location" type="xsd:string"/>
    <xsd:attribute name="number" type="xsd:int"/>
  </xsd:complexType>
  <xsd:complexType name="EmployeeType">
    <xsd:attribute name="name" type="xsd:string"/>
    <xsd:attribute name="SN" type="xsd:ID"/>
    <xsd:attribute name="manager" type="xsd:boolean"/>
  </xsd:complexType>
</xsd:schema>

The XML Data Access Service maps the schema to an SDO. Attributes such as "name" become primitive properties, the sequence of employees becomes a many-valued containment relationship, and so on. Note that the containment relationships are expressed as one complex type within another, whereas non-containment references are expressed in terms of ID and IDREF, with a special sdoxml:propertyType attribute specifying the type of the non-containment reference.


Setting and Getting Property Values

The following examples assume $company is the root of a tree of data objects created from the schema and instance document shown above.

Example #1 Access via property name

Data object properties can be accessed using the object property access syntax. The following sets the company name to 'Acme'.

<?php
$company->name = 'Acme';
?>

Example #2 Access via property name as array index

We can also access properties using associative array syntax. The simplest form of this uses the property name as the array index. For example, the following sets the company name and gets the employeeOfTheMonth.

<?php
$company['name'] = 'UltraCorp';
$eotm = $company['employeeOfTheMonth'];
?>

Example #3 Data Object iteration

We can iterate over the properties of a data object using foreach. The following iterates over the properties of the employee of the month.

<?php
  $eotm = $company->employeeOfTheMonth;
  foreach ($eotm as $name => $value) {
      echo "$name: $value\n";
  }
?>

which will output:

name: Jane Doe
SN: E0003

The 'manager' property is not output, because it has not been set.

Example #4 Access many-valued property by name

Many-valued data object properties can also be accessed using the object property name syntax. The following gets the list of departments.

<?php
$departments = $company->departments;
?>

Example #5 Many-valued element access

We can access individual elements of many-valued properties using array syntax. The following accesses the first department in the company.

<?php
$ad_tech_dept = $company->departments[0];
?>

Example #6 Many-valued property iteration

Many-valued properties can also be iterated over using foreach. The following iterates over the company's departments.

<?php
  foreach ($company->departments as $department) {
    // ...
  }
?>

Each iteration will assign the next department in the list to the variable $department.

Example #7 Chained property access

We can chain property references on a single line. The following sets and gets the name of the first department.

<?php
  $company->departments[0]->name = 'Emerging Technologies';
  $dept_name = $company->departments[0]->name;
?>

Using the associative array syntax, this is equivalent to

<?php
  $company['departments'][0]['name'] = 'Emerging Technologies';
  $dept_name = $company['departments'][0]['name'];
?>

In either case, the dept_name variable is set to 'Emerging Technologies'.

Example #8 XPath navigation

The associative array index can be an XPath-like expression. Valid expressions are defined by an augmented sub-set of XPath.

Two forms of indexing into many-valued properties are supported. The first is the standard XPath array syntax with the indexing starting at one, the second is an SDO extension to XPath with an index starting at zero. The standard syntax is:

<?php
  $jane_doe = $company["departments[1]/employees[2]"];
?>

and the SDO XPath extension syntax is:

<?php
  $jane_doe = $company["departments.0/employees.1"];
?>

Both these examples get the second employee from the first department.

Example #9 XPath querying

We can use XPath to query and identify parts of a data object based on instance data. The following retrieves the manager from the 'Advanced Technologies' department.

<?php
 $ad_tech_mgr =
  $company["departments[name='Advanced Technologies']/employees[manager=true]"];
?>

Example #10 Creating child data objects

A data object can be a factory for its child data objects. A child data object is automatically part of the data graph. The following add a new employee to the 'Advanced Technologies' department.

<?php
  $ad_tech_dept = $company["departments[name='Advanced Technologies']"];
  $new_hire = $ad_tech_dept->createDataObject('employees');
  $new_hire->name = 'John Johnson';
  $new_hire->SN = 'E0005';
  $new_hire->manager = false;
?>

Example #11 Unset a primitive property

We can use the isset() and unset() functions to test and remove items from the data object.

The following clears the name of the first department.

<?php
  unset($company->departments[0]->name);
?>

Example #12 Unset a data object

unset can also be used to remove a data object from the tree. The following example shows John Jones leaving the company.

<?php
  unset($company->departments[0]->employees[0]);
?>

Example #13 Unset a referenced data object

The following removes the 'employeeOfTheMonth' from the company. If this were a containment relationship then the employee would be removed from the company (probably not a good idea to sack your best employee each month!), but since this is a non-containment reference, the employee being referenced will remain in the department in the company, but will no longer be accessible via the employeeOfTheMonth property.

<?php
  if (isset($company->employeeOfTheMonth)) {
    unset($company->employeeOfTheMonth);
  }
?>

Example #14 Access via property index

Data object properties can be accessed via their property index using array syntax. The property index is the position at which the property's definition appears in the model (in this case the xml schema). We can see from the schema listing above that the company name attribute is the second company property (the SDO interface makes no distinction between XML attributes and elements). The following sets the company name to 'Acme', with the same result as Access via property name

<?php
  $company[1] = 'Acme';
?>

Using the index directly in this way is likely to be fragile. Normally the property name syntax should be preferred, but the property index may be required in special cases.


Working with Sequenced Data Objects

Sequenced data objects are SDOs which can track property ordering across the properties of a data object. They can also contain unstructured text elements (text element which do not belong to any of the SDO's properties). Sequenced data objects are useful for working with XML documents which allow unstructured text (i.e. mixed=true) or if the elements can be interleaved (

<A/><B/><A/>
). This can occur for example when the schema defines maxOccurs>1 on a element which is a complexType with a choice order indicator.

The examples below assume an SDO created with the following schema and instance information, using the XML Data Access Service.

The schema below describes the format of a letter. The letter can optionally contain three properties; date, firstName, and lastName. The schema states mixed="true" which means that unstructured text can be interspersed between the three properties.

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:letter="http://letterSchema"
  targetNamespace="http://letterSchema">
  <xsd:element name="letters" type="letter:FormLetter"/>
  <xsd:complexType name="FormLetter" mixed="true">
    <xsd:sequence>
      <xsd:element name="date" minOccurs="0" type="xsd:string"/>
      <xsd:element name="firstName" minOccurs="0" type="xsd:string"/>
      <xsd:element name="lastName" minOccurs="0" type="xsd:string"/>
    </xsd:sequence>
  </xsd:complexType>
</xsd:schema>

The following is an instance letter document. It contains the three letter properties; date, firstName and lastName, and has unstructured text elements for the address and letter body.

<letter:letters xmlns:letter="http://letterSchema">
  <date>March 1, 2005</date>
  Mutual of Omaha
  Wild Kingdom, USA
  Dear
  <firstName>Casy</firstName>
  <lastName>Crocodile</lastName>
  Please buy more shark repellent.
  Your premium is past due.
</letter:letters>

When loaded, the letter data object will have the sequence and property indices shown in the table below:

Sequence Index | Property Index:Name | Value
0 | 0:date | March 1, 2005
1 | - | Mutual of Omaha
2 | - | Wild Kingdom, USA
3 | - | Dear
4 | 1:firstName | Casy
5 | 2:lastName | Crocodile
6 | - | Please buy more shark repellent.
7 | - | Your premium is past due.

To ensure sequence indices are maintained, sequenced data objects should be manipulated through the SDO_Sequence interface. This allows the data object's instance data to be manipulated in terms of the sequence index as opposed to the property index (shown in the table above). The following examples assume the letter instance has been loaded into a data object referenced by the variable $letter.

Example #1 Getting the SDO_Sequence interface

We obtain a data object's sequence using the getSequence() method. The follow gets the sequence for the letter data object.

<?php
  $letter_seq = $letter->getSequence();
?>

All subsequent examples assume that the $letter_seq variable has been assigned the sequence for the letter data object.

Example #2 Get/set sequence values

We can get and set individual values (including unstructured text) using the sequence index. The following sets the firstName to 'Snappy' and gets the last sequence values (the unstructured text, 'Your premium is past due.').

<?php
  $letter_seq[4] = 'Snappy';
  $text = $letter_seq[count($letter_seq) - 1];
?>

Example #3 Sequence iteration

We can iterate through the individual sequence values using foreach. The following runs through the individual values in sequence order.

<?php
foreach ($letter->getSequence() as $value) {
    // ...
}
?>

Example #4 Sequence versus Data Object

Setting values through the data object interface may result in the value not being part of the sequence. A value set through the data object will only be accessible through the sequence if the property was already part of the sequence. The following example sets the lastName through the data object and gets it through the sequence. This is fine because lastName already exists in the sequence. If it had not previously been set, then lastName would be set to 'Smith', but would not be part of the sequence.

<?php
  $letter[2] = 'Smith';
  $last_name = $letter_seq[5];
?>

Example #5 Adding to a sequence

We can add new values to a sequence using the SDO_Sequence::insert() method. The following examples assume that the 'firstName' and 'lastName' properties are initially unset.

<?php
  // Append a firstName value to the sequence
  // value: 'Smith'
  // sequence index: NULL (append)
  // propertyIdentifier: 1 (firtName property index)
  $letter_seq->insert('Smith', NULL, 1);

  // Append a lastName value to the sequence
  // value: 'Jones'
  // sequence index: NULL (append)
  // propertyIdentifier: 'lastName' (lastName property name)
  $letter_seq->insert('Jones', NULL, 'lastName');

  // Append unstructured text
  // value: 'Cancel Subscription.'
  // sequence index: absent (append)
  // propertyIdentifier: absent (unstructured text)
  $letter_seq->insert('Cancel Subscription.');

  // Insert new unstructured text.  Subsequent sequence values
  // are shifted up.
  // value: 'Care of:'
  // sequence index: 1 (insert as second element)
  // propertyIdentifier: absent (unstructured text)
  $letter_seq->insert('Care of:', 1);
?>

Example #6 Removing from a sequence

We can use the isset() and unset() functions to test and remove items from the sequence (Note: unset() currently leaves the values in the data object, but this behaviour is likely to change to also remove the data from the data object). A sequence behaves like a contiguous list; therefore, removing items from the middle will shift entries at higher indices down. The following example tests to see if the first sequence element is set and unsets it if is.

<?php
  if (isset($letter_seq[0])) {
    unset($letter_seq[0]);
  }
?>


Reflecting on Service Data Objects

SDOs have a knowledge of the structure they have been created to represent (the model). For example, a Company SDO created using the Company XML schema above would only be permitted to contain DepartmentType data objects which in turn could only contain EmployeeType data objects.

Sometimes it is useful to be able to access this model information at runtime. For example, this could be used to automatically generate a user interface for populating a data object. The model information is accessed using reflection.

Example #1 Reflecting on a Data Object

The following example shows how we can reflect on an empty Employee data object.

<?php
  // Create the employee data object (e.g. from an XML Data Access Service)
  $employee = ...;
  $reflection = new SDO_Model_ReflectionDataObject($employee);
  print($reflection);
?>

The above example will output:

object(SDO_Model_ReflectionDataObject)#4 { - ROOT OBJECT - Type {
companyNS:EmployeeType[3] { commonj.sdo:String $name;
commonj.sdo:String $SN; commonj.sdo:Boolean $manager; } }

Using print on the SDO_Model_ReflectionDataObject writes out the data object's model. We can see from the output how the type companyNS:EmployeeType has three properties and we can see the names of the properties along with their types. Note, the primitive types are listed as SDO types (e.g. commonj.sdo namespace, String type). It is worth noting that this is the SDO model and when these are surfaced to an application they can be treated as the PHP equivalent types (e.g. string and boolean).

Example #2 Accessing the type information

We can query the type information of a data object using reflection. The following example checks the type corresponds to a data object rather than a primitive and then iterates through the properties of the type, writing out the name of each property ($type and $property are SDO_Model_Type and SDO_Model_Property objects, respectively).

<?php
    // Create the employee data object (e.g. from an XML Data Access Service)
    $employee = ...;
    $reflection = new SDO_Model_ReflectionDataObject($employee);
    $type = $reflection->getType();
    if (! $type->isDataType()) {
        foreach ($type->getProperties() as $property) {
            print $property->getName() . "\n";
        }
    }
?>

The above example will output:

name
SN
manager


SDO Functions

Data Access Services

The table below lists the currently provided SDO Data Access Services:

DAS Name | Description
SDO_DAS_XML | An XML Data Access Service supporting reading/writing SDOs as XML documents.
SDO_DAS_Relational | A PDO-based Data Access Service supporting reading/writing SDO to relational databases. Implements an optimistic concurrency policy for updates.

Predefined Classes

SDO consists of three sets of interfaces. The first set covers those interfaces for use by typical SDO applications. These are identified by the package prefix 'SDO_'. The second set is those used to reflect on, and work with, the model of a data object. These are identified by the package prefix 'SDO_Model_'. Finally, the third set are those use by Data Access Service implementations and are identified by the package prefix 'SDO_DAS_'. The majority of SDO users will not need to use or understand the 'SDO_Model_' and 'SDO_DAS_' interfaces.

SDO Application Programmer Interface

SDO_DataObject

The main interface through which data objects are manipulated. In addition to the methods below, SDO_DataObject extends the ArrayAccess, SDO_PropertyAccess (defines __get() / __set() methods for property access overloading), Iterator, and Countable interfaces.

Methods

  • getSequence - get the sequence for the data object

  • createDataObject - create a child data object

  • clear - unset the properties of a data object

  • getContainer - get the container (also known as 'parent') of this data object

  • getTypeName - get the name of the type for this data object

  • getTypeNamespaceURI - get the namespace URI of the type for this data object

SDO_Sequence

The interface through which sequenced data objects can be accessed to preserve ordering across a data object's properties and to allow unstructured text. SDO_Sequence preserves contiguous indices and therefore inserting or removing elements may shift other elements up or down. In addition to the methods below, SDO_Sequence extends the ArrayAccess, Iterator and Countable interface.

Methods

  • getProperty - get the property for a given sequence index

  • move - move an element from one property index to another

  • insert - insert a new value into the sequence

SDO_List

The interface through which many-valued properties are manipulated. In addition to the method defined below, SDO_List extends ArrayAccess, Iterator and Countable. SDO_List preserves contiguous indices and therefore inserting or removing elements may shift other elements up or down.

Methods

  • insert - insert a new value into the list

SDO_DataFactory

The interface through which data objects can be created. A Data Access Service is responsible for populating the model (i.e. configuring the data factory with the type and structure information for the data objects it can create.) for the factory and can then optionally return an instance of, or implement, the SDO_DataFactory interface.

Methods

  • create - create a new data object

SDO_Exception

An SDO_Exception is thrown when the caller's request cannot be completed. The subclasses of SDO_Exception are:

  • SDO_PropertyNotSetException - the property specified exists but has not been set or does not have a default value

  • SDO_PropertyNotFoundException - the property specified is not part of the data object's type

  • SDO_TypeNotFoundException - the specified namespace URI or type name is unknown

  • SDO_InvalidConversionException - conversion between the types of the assignment is not possible

  • SDO_IndexOutOfBoundsException - the numeric index into a data object, sequence or list is not in the valid range

  • SDO_UnsupportedOperationException - the request cannot be completed because it is not allowed, for example an attempt to set a read-only property.

Methods

One method is added to those inherited from the built in Exception class:

  • getCause - get the cause of this SDO_Exception

SDO Reflection Application Programmer Interfaces

SDO_Model_ReflectionDataObject

The main interface used to reflect on a data object instance to obtain its model type and property information. It is designed to follow the reflection pattern introduced in PHP 5.

Constructor

  • __construct - construct a new SDO_Model_ReflectionDataObject.

Methods

  • export - get a string describing the data object.

  • getType - get the SDO_Model_Type for the data object.

  • getInstanceProperties - get the instance properties of the data object.

  • getContainmentProperty - get the property which defines the containment relationship to the data object.

SDO_Model_Type

The interface through which a data object's type information can be retrieved. This interface can be used to find out the type name and namespace URI of the type, whether the type allow open content, and so on.

Methods

  • getName - get the name of the type.

  • getNamespaceURI - get the namespace URI of the type.

  • isInstance - test for a data object being an instance of the type.

  • getProperties - get the properties of the type.

  • getProperty - get a property of the type.

  • isDataType - test to see if this type is a primitive scalar type.

  • isSequencedType - test to see if this is a sequenced type.

  • isOpenType - test to see if this is an open type.

  • isAbstractType - test to see if this is an abstract type.

  • getBaseType - get the base type of this type (if one exists).

SDO_Model_Property

The interface through which a data object's property information can be retrieved. This interface can be used to find out the type of a property, whether a property has a default value, whether the property is contained or reference by its parent, its cardinality, and so on.

Methods

  • getName - get the name of the property.

  • getType - get the type of the property.

  • isMany - test to see if the property is many-valued.

  • isContainment - test to see if the property describes a containment relationship.

  • getContainingType - get the type which contains this property.

  • getDefault - get the default value for a property.

SDO Data Access Service Developer Interfaces

SDO_DAS_DataObject

The interface through which a Data Access Service can access a data object's SDO_DAS_ChangeSummary. The change summary is used by the Data Access Service to check for conflicts when applying changes back to a data source.

Methods

  • getChangeSummary - get the change summary for a data object

SDO_DAS_ChangeSummary

The interface through which the change history of a data object is accessed. The change summary holds information for any modifications on a data object which occurred since logging was activated. In the case of deletions and modifications, the old values are also held in the change summary.

If logging is no longer active then the change summary only holds changes made up to the point when logging was deactivated. Reactivating logging clears the change summary. This is useful when a set of changes have been written out by a DAS and the data object is to be reused.

Methods

  • beginLogging - begin logging changes made to a data object

  • endLogging - end logging changes made to a data object

  • isLogging - test to see if change logging is on

  • getChangedDataObjects - get a list of the data objects which have been changed

  • getChangeType - get the type of change which has been made to a data object

  • getOldValues - get a list of old values for a data object

  • getOldContainer - get the old container data object for a deleted data object

SDO_DAS_Setting

The interface through which the old value for a property is accessed. A list of settings is returned by the change summary method getOldValues.

Methods

  • getPropertyIndex - get the property index for the changed property

  • getPropertyName - get the property name for the changed property

  • getValue - get the old value for the changed property

  • getListIndex - get the list index for the old value if it was part of a many-valued property

  • isSet - test to see if the property was set prior to being modified

SDO_DAS_DataFactory

The interface for constructing the model for an SDO_DataObject. The SDO_DAS_DataFactory is an abstract class providing a static method which returns a concrete data factory implementation. The implementation is used by Data Access Services to create an SDO model from their model. For example, a Relational Data Access Service might create and populate an SDO_DAS_DataFactory model based on a schema for a relational database.

Methods

  • getDataFactory - static methods for getting a concrete data factory instance

  • addType - add a new type to the SDO model

  • addPropertyToType - add a new property to a type definition in the SDO model

Table of Contents

  • SDO_DAS_ChangeSummary::beginLogging — Begin change logging
  • SDO_DAS_ChangeSummary::endLogging — End change logging
  • SDO_DAS_ChangeSummary::getChangeType — Get the type of change made to an SDO_DataObject
  • SDO_DAS_ChangeSummary::getChangedDataObjects — Get the changed data objects from a change summary
  • SDO_DAS_ChangeSummary::getOldContainer — Get the old container for a deleted SDO_DataObject
  • SDO_DAS_ChangeSummary::getOldValues — Get the old values for a given changed SDO_DataObject
  • SDO_DAS_ChangeSummary::isLogging — Test to see whether change logging is switched on
  • SDO_DAS_DataFactory::addPropertyToType — Adds a property to a type
  • SDO_DAS_DataFactory::addType — Add a new type to a model
  • SDO_DAS_DataFactory::getDataFactory — Get a data factory instance
  • SDO_DAS_DataObject::getChangeSummary — Get a data object's change summary
  • SDO_DAS_Setting::getListIndex — Get the list index for a changed many-valued property
  • SDO_DAS_Setting::getPropertyIndex — Get the property index for a changed property
  • SDO_DAS_Setting::getPropertyName — Get the property name for a changed property
  • SDO_DAS_Setting::getValue — Get the old value for the changed property
  • SDO_DAS_Setting::isSet — Test whether a property was set prior to being modified
  • SDO_DataFactory::create — Create an SDO_DataObject
  • SDO_DataObject::clear — Clear an SDO_DataObject's properties
  • SDO_DataObject::createDataObject — Create a child SDO_DataObject
  • SDO_DataObject::getContainer — Get a data object's container
  • SDO_DataObject::getSequence — Get the sequence for a data object
  • SDO_DataObject::getTypeName — Return the name of the type for a data object
  • SDO_DataObject::getTypeNamespaceURI — Return the namespace URI of the type for a data object
  • SDO_Exception::getCause — Get the cause of the exception
  • SDO_List::insert — Insert into a list
  • SDO_Model_Property::getContainingType — Get the SDO_Model_Type which contains this property
  • SDO_Model_Property::getDefault — Get the default value for the property
  • SDO_Model_Property::getName — Get the name of the SDO_Model_Property
  • SDO_Model_Property::getType — Get the SDO_Model_Type of the property
  • SDO_Model_Property::isContainment — Test to see if the property defines a containment relationship
  • SDO_Model_Property::isMany — Test to see if the property is many-valued
  • SDO_Model_ReflectionDataObject::__construct — Construct an SDO_Model_ReflectionDataObject
  • SDO_Model_ReflectionDataObject::export — Get a string describing the SDO_DataObject
  • SDO_Model_ReflectionDataObject::getContainmentProperty — Get the property which defines the containment relationship to the data object
  • SDO_Model_ReflectionDataObject::getInstanceProperties — Get the instance properties of the SDO_DataObject
  • SDO_Model_ReflectionDataObject::getType — Get the SDO_Model_Type for the SDO_DataObject
  • SDO_Model_Type::getBaseType — Get the base type for this type
  • SDO_Model_Type::getName — Get the name of the type
  • SDO_Model_Type::getNamespaceURI — Get the namespace URI of the type
  • SDO_Model_Type::getProperties — Get the SDO_Model_Property objects defined for the type
  • SDO_Model_Type::getProperty — Get an SDO_Model_Property of the type
  • SDO_Model_Type::isAbstractType — Test to see if this SDO_Model_Type is an abstract data type
  • SDO_Model_Type::isDataType — Test to see if this SDO_Model_Type is a primitive data type
  • SDO_Model_Type::isInstance — Test for an SDO_DataObject being an instance of this SDO_Model_Type
  • SDO_Model_Type::isOpenType — Test to see if this type is an open type
  • SDO_Model_Type::isSequencedType — Test to see if this is a sequenced type
  • SDO_Sequence::getProperty — Return the property for the specified sequence index
  • SDO_Sequence::insert — Insert into a sequence
  • SDO_Sequence::move — Move an item to another sequence position


Begin change logging

  • « SDO Functions
  • SDO_DAS_ChangeSummary::endLogging »
  • PHP Manual
  • SDO Functions
  • Begin change logging

SDO_DAS_ChangeSummary::beginLogging

(^)

SDO_DAS_ChangeSummary::beginLogging — Begin change logging

Description

SDO_DAS_ChangeSummary::beginLogging ( void ) : void
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.

Begin logging changes made to the SDO_DataObject.

Parameters

None.

Return Values

None.


End change logging

  • « SDO_DAS_ChangeSummary::beginLogging
  • SDO_DAS_ChangeSummary::getChangeType »
  • PHP Manual
  • SDO Functions
  • End change logging

SDO_DAS_ChangeSummary::endLogging

(^)

SDO_DAS_ChangeSummary::endLogging — End change logging

Description

SDO_DAS_ChangeSummary::endLogging ( void ) : void
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.

End logging changes made to an SDO_DataObject.

Parameters

None.

Return Values

None.


Get the type of change made to an SDO_DataObject

  • « SDO_DAS_ChangeSummary::endLogging
  • SDO_DAS_ChangeSummary::getChangedDataObjects »
  • PHP Manual
  • SDO Functions
  • Get the type of change made to an SDO_DataObject

SDO_DAS_ChangeSummary::getChangeType

(^)

SDO_DAS_ChangeSummary::getChangeType — Get the type of change made to an SDO_DataObject

Description

SDO_DAS_ChangeSummary::getChangeType ( SDO_DataObject $dataObject ) : int
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.

Get the type of change which has been made to the supplied SDO_DataObject.

Parameters

dataObject

The SDO_DataObject which has been changed.

Return Values

The type of change which has been made. The change type is expressed as an enumeration and will be one of the following four values:

  • SDO_DAS_ChangeSummary::NONE

  • SDO_DAS_ChangeSummary::MODIFICATION

  • SDO_DAS_ChangeSummary::ADDITION

  • SDO_DAS_ChangeSummary::DELETION


Get the changed data objects from a change summary

  • « SDO_DAS_ChangeSummary::getChangeType
  • SDO_DAS_ChangeSummary::getOldContainer »
  • PHP Manual
  • SDO Functions
  • Get the changed data objects from a change summary

SDO_DAS_ChangeSummary::getChangedDataObjects

(^)

SDO_DAS_ChangeSummary::getChangedDataObjects — Get the changed data objects from a change summary

Description

SDO_DAS_ChangeSummary::getChangedDataObjects ( void ) : SDO_List
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.

Get an SDO_List of the SDO_DataObjects which have been changed. These data objects can then be used to identify the types of change made to each, along with the old values.

Parameters

None.

Return Values

Returns an SDO_List of SDO_DataObjects.


Get the old container for a deleted SDO_DataObject

  • « SDO_DAS_ChangeSummary::getChangedDataObjects
  • SDO_DAS_ChangeSummary::getOldValues »
  • PHP Manual
  • SDO Functions
  • Get the old container for a deleted SDO_DataObject

SDO_DAS_ChangeSummary::getOldContainer

(^)

SDO_DAS_ChangeSummary::getOldContainer — Get the old container for a deleted SDO_DataObject

Description

SDO_DAS_ChangeSummary::getOldContainer ( SDO_DataObject $data_object ) : SDO_DataObject
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.

Get the old container (SDO_DataObject) for a deleted SDO_DataObject.

Parameters

data_object

The SDO_DataObject which has been deleted and whose container we wish to identify.

Return Values

The old containing data object of the deleted SDO_DataObject.


Get the old values for a given changed SDO_DataObject

  • « SDO_DAS_ChangeSummary::getOldContainer
  • SDO_DAS_ChangeSummary::isLogging »
  • PHP Manual
  • SDO Functions
  • Get the old values for a given changed SDO_DataObject

SDO_DAS_ChangeSummary::getOldValues

(^)

SDO_DAS_ChangeSummary::getOldValues — Get the old values for a given changed SDO_DataObject

Description

SDO_DAS_ChangeSummary::getOldValues ( SDO_DataObject $data_object ) : SDO_List
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.

Get a list of the old values for a given changed SDO_DataObject. Returns a list of SDO_DAS_Settings describing the old values for the changed properties of the SDO_DataObject.

Parameters

data_object

The data object which has been changed.

Return Values

A list of SDO_DAS_Settings describing the old values for the changed properties of the SDO_DataObject. If the change type is SDO_DAS_ChangeSummary::ADDITION, this list is empty.


Test to see whether change logging is switched on

  • « SDO_DAS_ChangeSummary::getOldValues
  • SDO_DAS_DataFactory::addPropertyToType »
  • PHP Manual
  • SDO Functions
  • Test to see whether change logging is switched on

SDO_DAS_ChangeSummary::isLogging

(^)

SDO_DAS_ChangeSummary::isLogging — Test to see whether change logging is switched on

Description

SDO_DAS_ChangeSummary::isLogging ( void ) : bool
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.

Test to see whether change logging is switched on.

Parameters

None.

Return Values

Returns TRUE if change logging is on, otherwise returns FALSE.


Adds a property to a type

  • « SDO_DAS_ChangeSummary::isLogging
  • SDO_DAS_DataFactory::addType »
  • PHP Manual
  • SDO Functions
  • Adds a property to a type

SDO_DAS_DataFactory::addPropertyToType

(^)

SDO_DAS_DataFactory::addPropertyToType — Adds a property to a type

Description

SDO_DAS_DataFactory::addPropertyToType ( string $parent_type_namespace_uri , string $parent_type_name , string $property_name , string $type_namespace_uri , string $type_name [, array $options ] ) : void
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.

Adds a property to a type. The type must already be known to the SDO_DAS_DataFactory (i.e. have been added using addType()). The property becomes a property of the type. This is how the graph model for the structure of an SDO_DataObject is built.

Parameters

parent_type_namespace_uri

The namespace URI for the parent type.

parent_type_name

The type name for the parent type.

property_name

The name by which the property will be known in the parent type.

type_namespace_uri

The namespace URI for the type of the property.

type_name

The type name for the type of the property

options

This array holds one or more key=>value pairs to set attribute values for the property. The optional keywords are:

many

A flag to say whether the property is many-valued. A value of 'true' adds the property as a many-valued property (default is 'false').

readOnly

A flag to say whether the property is read-only. A value of 'true' means the property value cannot be modified through the SDO application APIs (default is 'false').

containment

A flag to say whether the property is contained by the parent. A value of 'true' means the property is contained by the parent. A value of 'false' results in a non-containment reference (default is 'true'). This flag is only interpreted when adding properties which are data object types, otherwise it is ignored.

default

A default value for the property. Omitting this key means that the property does not have a default value. A property can only have a default value if it is a single-valued data type (primitive).

Return Values

None.

Changelog

Version | Description
0.5.2 | Optional parameters many, readOnly, and containment deprecated in favour of the options array.

Examples

Example #1 A SDO_DAS_DataFactory::addPropertyToType() example

The following adds an 'addressline' property to a Person type. The person type is identified by its namespace, 'PersonNS', and type name, 'PersonType'. The type of the 'addressline' property is a many-valued SDO data type (primitive) with namespace 'commonj.sdo' and type name 'String'.

<?php
  $df->addPropertyToType('PersonNS', 'PersonType',
    'addressline', 'commonj.sdo', 'String', array('many'=>true));
?>


Add a new type to a model

  • « SDO_DAS_DataFactory::addPropertyToType
  • SDO_DAS_DataFactory::getDataFactory »
  • PHP Manual
  • SDO Functions
  • Add a new type to a model

SDO_DAS_DataFactory::addType

(^)

SDO_DAS_DataFactory::addType — Add a new type to a model

Description

SDO_DAS_DataFactory::addType ( string $type_namespace_uri , string $type_name [, array $options ] ) : void
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.

Add a new type to the SDO_DAS_DataFactory, defined by its namespace and type name. The type becomes part of the model of data objects that the data factory can create.

Parameters

type_namespace_uri

The namespace of the type.

type_name

The name of the type.

options

This array holds one or more key=>value pairs to set attribute values for the type. The optional keywords are:

open

A flag to say whether the type is open. An SDO_DataObject whose type is open can have properties added to them which are not described by the type. This capability is used to support working with XML documents whose schema support open content such as that described by an <xsd:any> element. The default value is 'false'.

sequenced

A flag to say whether the type is sequenced. Sequenced types can have the ordering across properties preserved and can contain unstructured text. The default value is 'false'. For more information on sequenced types see the section on Working with Sequenced Data Objects.

basetype

If specified, an array of namespace URI and type name strings for the type from which this type is derived. An example of the use of base types is when a type derived in an XML schema inherits from another type by using <extension base="...">.

Return Values

None.

Examples

Example #1 A SDO_DAS_DataFactory::addType() example

The following adds a new data object type of 'CompanyType' where that type belongs to the namespace 'CompanyNS'.

<?php
  $df->addType('CompanyNS', 'CompanyType');
?>


Get a data factory instance

  • « SDO_DAS_DataFactory::addType
  • SDO_DAS_DataObject::getChangeSummary »
  • PHP Manual
  • SDO Functions
  • Get a data factory instance

SDO_DAS_DataFactory::getDataFactory

(^)

SDO_DAS_DataFactory::getDataFactory — Get a data factory instance

Description

SDO_DAS_DataFactory::getDataFactory ( void ) : SDO_DAS_DataFactory
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.

Static method to get an instance of an SDO_DAS_DataFactory. This instance is initially only configured with the basic SDO types. A Data Access Service is responsible for populating the data factory model and then allowing PHP applications to create SDOs based on the model through the SDO_DataFactory interface. PHP applications should always obtain a data factory from a configured Data Access Service, not through this interface.

Parameters

None.

Return Values

Returns an SDO_DAS_DataFactory.


Get a data object's change summary

  • « SDO_DAS_DataFactory::getDataFactory
  • SDO_DAS_Setting::getListIndex »
  • PHP Manual
  • SDO Functions
  • Get a data object's change summary

SDO_DAS_DataObject::getChangeSummary

(^)

SDO_DAS_DataObject::getChangeSummary — Get a data object's change summary

Description

SDO_DAS_DataObject::getChangeSummary ( void ) : SDO_DAS_ChangeSummary
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.

Get the SDO_DAS_ChangeSummary for an SDO_DAS_DataObject, or NULL if it does not have one.

Parameters

None.

Return Values

Returns the SDO_DAS_ChangeSummary for an SDO_DAS_DataObject, or NULL if it does not have one.


Get the list index for a changed many-valued property

  • « SDO_DAS_DataObject::getChangeSummary
  • SDO_DAS_Setting::getPropertyIndex »
  • PHP Manual
  • SDO Functions
  • Get the list index for a changed many-valued property

SDO_DAS_Setting::getListIndex

(^)

SDO_DAS_Setting::getListIndex — Get the list index for a changed many-valued property

Description

SDO_DAS_Setting::getListIndex ( void ) : int
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.

Get the list index for a modification made to an element of a many-valued property. For example, if we modified the third element of a many-valued property we could obtain an SDO_DAS_Setting from the change summary corresponding to that modification. A call to getListIndex() on that setting would return the value 2 (lists are indexed from zero).

Parameters

None.

Return Values

The list index for the element of the many-valued property which has been changed.


Get the property index for a changed property

  • « SDO_DAS_Setting::getListIndex
  • SDO_DAS_Setting::getPropertyName »
  • PHP Manual
  • SDO Functions
  • Get the property index for a changed property

SDO_DAS_Setting::getPropertyIndex

(^)

SDO_DAS_Setting::getPropertyIndex — Get the property index for a changed property

Description

SDO_DAS_Setting::getPropertyIndex ( void ) : int
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.

Returns the property index for the changed property. This index identifies the property which was modified in data object.

Parameters

None.

Return Values

The property index for a changed property.


Get the property name for a changed property

  • « SDO_DAS_Setting::getPropertyIndex
  • SDO_DAS_Setting::getValue »
  • PHP Manual
  • SDO Functions
  • Get the property name for a changed property

SDO_DAS_Setting::getPropertyName

(^)

SDO_DAS_Setting::getPropertyName — Get the property name for a changed property

Description

SDO_DAS_Setting::getPropertyName ( void ) : string
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.

Returns the property name for the changed property. This name identifies the property which was modified in data object.

Parameters

None.

Return Values

The property name for a changed property.


Get the old value for the changed property

  • « SDO_DAS_Setting::getPropertyName
  • SDO_DAS_Setting::isSet »
  • PHP Manual
  • SDO Functions
  • Get the old value for the changed property

SDO_DAS_Setting::getValue

(^)

SDO_DAS_Setting::getValue — Get the old value for the changed property

Description

SDO_DAS_Setting::getValue ( void ) : mixed
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.

Returns the old value for the changed property. This can be used by a Data Access Service when writing updates to a data source. The DAS uses the old value to detect conflicts by comparing it with the current value in the data source. If they do not match, then the data source has been updated since the data object was originally populated, and therefore writing any new updates risks compromising the integrity of the data.

Parameters

None.

Return Values

Returns the old value of the changed property.


Test whether a property was set prior to being modified

  • « SDO_DAS_Setting::getValue
  • SDO_DataFactory::create »
  • PHP Manual
  • SDO Functions
  • Test whether a property was set prior to being modified

SDO_DAS_Setting::isSet

(^)

SDO_DAS_Setting::isSet — Test whether a property was set prior to being modified

Description

SDO_DAS_Setting::isSet ( void ) : bool
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.

Test whether a property was set prior to being modified. If it was set prior to being modified then the SDO_DAS_Setting will also contain the old value.

Parameters

None.

Return Values

Returns TRUE if the property was set prior to being modified, otherwise returns FALSE.


Create an SDO_DataObject

  • « SDO_DAS_Setting::isSet
  • SDO_DataObject::clear »
  • PHP Manual
  • SDO Functions
  • Create an SDO_DataObject

SDO_DataFactory::create

(^)

SDO_DataFactory::create — Create an SDO_DataObject

Description

SDO_DataFactory::create ( string $type_namespace_uri , string $type_name ) : void
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.

Create a new SDO_DataObject given the data object's namespace URI and type name.

Parameters

type_namespace_uri

The namespace of the type.

type_name

The name of the type.

Return Values

Returns the newly created SDO_DataObject.

Errors/Exceptions

SDO_TypeNotFoundException

Thrown if the namespaceURI and typeName do not correspond to a type known to this data factory.


Clear an SDO_DataObject's properties

  • « SDO_DataFactory::create
  • SDO_DataObject::createDataObject »
  • PHP Manual
  • SDO Functions
  • Clear an SDO_DataObject's properties

SDO_DataObject::clear

(^)

SDO_DataObject::clear — Clear an SDO_DataObject's properties

Description

SDO_DataObject::clear ( void ) : void
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.

Clear an SDO_DataObject's properties. Read-only properties are unaffected. Subsequent calls to isset() for the data object will return FALSE.

Parameters

None.

Return Values

No return values.


Create a child SDO_DataObject

  • « SDO_DataObject::clear
  • SDO_DataObject::getContainer »
  • PHP Manual
  • SDO Functions
  • Create a child SDO_DataObject

SDO_DataObject::createDataObject

(^)

SDO_DataObject::createDataObject — Create a child SDO_DataObject

Description

SDO_DataObject::createDataObject ( mixed $identifier ) : SDO_DataObject
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.

Create a child SDO_DataObject of the default type for the property identified. The data object is automatically inserted into the tree and a reference to it is returned.

Parameters

identifier

Identifies the property for the data object type to be created. Can be either a property name (string), a property index (int), or an SDO_Model_Property.

Return Values

Returns the newly created SDO_DataObject.

Errors/Exceptions

SDO_PropertyNotFoundException

Thrown if the identifier does not correspond to a property of the data object.


Get a data object's container

  • « SDO_DataObject::createDataObject
  • SDO_DataObject::getSequence »
  • PHP Manual
  • SDO Functions
  • Get a data object's container

SDO_DataObject::getContainer

(^)

SDO_DataObject::getContainer — Get a data object's container

Description

SDO_DataObject::getContainer ( void ) : SDO_DataObject
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.

Get the data object which contains this data object.

Parameters

None.

Return Values

Returns the SDO_DataObject which contains this SDO_DataObject, or returns NULL if this is a root SDO_DataObject (i.e. it has no container).


Get the sequence for a data object

  • « SDO_DataObject::getContainer
  • SDO_DataObject::getTypeName »
  • PHP Manual
  • SDO Functions
  • Get the sequence for a data object

SDO_DataObject::getSequence

(^)

SDO_DataObject::getSequence — Get the sequence for a data object

Description

SDO_DataObject::getSequence ( void ) : SDO_Sequence
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.

Return the SDO_Sequence for this SDO_DataObject. Accessing the SDO_DataObject through the SDO_Sequence interface acts on the same SDO_DataObject instance data, but preserves ordering across properties.

Parameters

None.

Return Values

The SDO_Sequence for this SDO_DataObject, or returns NULL if the SDO_DataObject is not of a type which can have a sequence.


Return the name of the type for a data object

  • « SDO_DataObject::getSequence
  • SDO_DataObject::getTypeNamespaceURI »
  • PHP Manual
  • SDO Functions
  • Return the name of the type for a data object

SDO_DataObject::getTypeName

(^)

SDO_DataObject::getTypeName — Return the name of the type for a data object

Description

SDO_DataObject::getTypeName ( void ) : string
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.

Return the name of the type for a data object. A convenience method corresponding to SDO_Model_ReflectionDataObject::getType().getName().

Parameters

None.

Return Values

The name of the type for the data object.


Return the namespace URI of the type for a data object

  • « SDO_DataObject::getTypeName
  • SDO_Exception::getCause »
  • PHP Manual
  • SDO Functions
  • Return the namespace URI of the type for a data object

SDO_DataObject::getTypeNamespaceURI

(^)

SDO_DataObject::getTypeNamespaceURI — Return the namespace URI of the type for a data object

Description

SDO_DataObject::getTypeNamespaceURI ( void ) : string
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.

Return the namespace URI of the type for a data object. A convenience method corresponding to SDO_Model_ReflectionDataObject::getType().getNamespaceURI().

Parameters

None.

Return Values

The namespace URI of the type for the data object.


Get the cause of the exception

  • « SDO_DataObject::getTypeNamespaceURI
  • SDO_List::insert »
  • PHP Manual
  • SDO Functions
  • Get the cause of the exception

SDO_Exception::getCause

(^)

SDO_Exception::getCause — Get the cause of the exception

Description

SDO_Exception::getCause ( void ) : mixed
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.

Returns the cause of this exception or NULL if the cause is nonexistent or unknown. Typically the cause will be an SDO_CPPException object, which may be used to obtain additional diagnostic information.

Parameters

None.

Return Values

Returns the cause of this exception or NULL if the cause is nonexistent or unknown.


Insert into a list

  • « SDO_Exception::getCause
  • SDO_Model_Property::getContainingType »
  • PHP Manual
  • SDO Functions
  • Insert into a list

SDO_List::insert

(^)

SDO_List::insert — Insert into a list

Description

SDO_List::insert ( mixed $value [, int $index ] ) : void
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.

Insert a new element at a specified position in the list. All subsequent list items are moved up.

Parameters

value

The new value to be inserted. This can be either a primitive or an SDO_DataObject.

index

The position at which to insert the new element. If this argument is not specified then the new value will be appended.

Return Values

None.

Errors/Exceptions

SDO_IndexOutOfBoundsException

Thrown if the list index is less than zero or greater than the size of the list.

SDO_InvalidConversionException

Thrown if the type of the new value does not match the type for the list (e.g. the type of the many-valued property that the list represents).


Get the SDO_Model_Type which contains this property

  • « SDO_List::insert
  • SDO_Model_Property::getDefault »
  • PHP Manual
  • SDO Functions
  • Get the SDO_Model_Type which contains this property

SDO_Model_Property::getContainingType

(^)

SDO_Model_Property::getContainingType — Get the SDO_Model_Type which contains this property

Description

SDO_Model_Property::getContainingType ( void ) : SDO_Model_Type
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.

Returns the SDO_Model_Type which contains this property.

Parameters

None.

Return Values

Returns the SDO_Model_Type which contains this property.


Get the default value for the property

  • « SDO_Model_Property::getContainingType
  • SDO_Model_Property::getName »
  • PHP Manual
  • SDO Functions
  • Get the default value for the property

SDO_Model_Property::getDefault

(^)

SDO_Model_Property::getDefault — Get the default value for the property

Description

SDO_Model_Property::getDefault ( void ) : mixed
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.

Returns the default value for the property. Only primitive data type properties can have default values.

Parameters

None.

Return Values

Returns the default value for the property.


Get the name of the SDO_Model_Property

  • « SDO_Model_Property::getDefault
  • SDO_Model_Property::getType »
  • PHP Manual
  • SDO Functions
  • Get the name of the SDO_Model_Property

SDO_Model_Property::getName

(^)

SDO_Model_Property::getName — Get the name of the SDO_Model_Property

Description

SDO_Model_Property::getName ( void ) : string
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.

Returns the name of the SDO_Model_Property.

Parameters

None.

Return Values

Returns the name of the SDO_Model_Property.


Get the SDO_Model_Type of the property

  • « SDO_Model_Property::getName
  • SDO_Model_Property::isContainment »
  • PHP Manual
  • SDO Functions
  • Get the SDO_Model_Type of the property

SDO_Model_Property::getType

(^)

SDO_Model_Property::getType — Get the SDO_Model_Type of the property

Description

SDO_Model_Property::getType ( void ) : SDO_Model_Type
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.

Get the SDO_Model_Type of the property. The SDO_Model_Type describes the type information for the property, such as its type name, namespace URI, whether it is a primitive data type, and so on.

Parameters

None.

Return Values

Returns the SDO_Model_Type describing the property's type information.


Test to see if the property defines a containment relationship

  • « SDO_Model_Property::getType
  • SDO_Model_Property::isMany »
  • PHP Manual
  • SDO Functions
  • Test to see if the property defines a containment relationship

SDO_Model_Property::isContainment

(^)

SDO_Model_Property::isContainment — Test to see if the property defines a containment relationship

Description

SDO_Model_Property::isContainment ( void ) : bool
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.

Test to see if the property corresponds to a containment relationship. Returns TRUE if the property defines a containment relationship, or FALSE if it is reference.

Parameters

None.

Return Values

Returns TRUE if the property defines a containment relationship, or FALSE if it is reference.


Test to see if the property is many-valued

  • « SDO_Model_Property::isContainment
  • SDO_Model_ReflectionDataObject::__construct »
  • PHP Manual
  • SDO Functions
  • Test to see if the property is many-valued

SDO_Model_Property::isMany

(^)

SDO_Model_Property::isMany — Test to see if the property is many-valued

Description

SDO_Model_Property::isMany ( void ) : bool
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.

Test to see if the property is many-valued. Returns TRUE if this is a many-valued property, otherwise returns FALSE.

Parameters

None.

Return Values

Returns TRUE if this is a many-valued property, otherwise returns FALSE.


Construct an SDO_Model_ReflectionDataObject

  • « SDO_Model_Property::isMany
  • SDO_Model_ReflectionDataObject::export »
  • PHP Manual
  • SDO Functions
  • Construct an SDO_Model_ReflectionDataObject

SDO_Model_ReflectionDataObject::__construct

(^)

SDO_Model_ReflectionDataObject::__construct — Construct an SDO_Model_ReflectionDataObject

Description

SDO_Model_ReflectionDataObject::__construct ( SDO_DataObject $data_object )
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.

Construct an SDO_Model_ReflectionDataObject to reflect on an SDO_DataObject. Reflecting on an SDO_DataObject gives access to information about its model. The model contains information such as the data object's type, and whether that type is sequenced (preserves ordering across properties) or open (each instance can have its model extended). The model also holds information about the data object's properties, any default values they may have, and so on.

Parameters

data_object

The SDO_DataObject being reflected upon.

Return Values

None.


Get a string describing the SDO_DataObject

  • « SDO_Model_ReflectionDataObject::__construct
  • SDO_Model_ReflectionDataObject::getContainmentProperty »
  • PHP Manual
  • SDO Functions
  • Get a string describing the SDO_DataObject

SDO_Model_ReflectionDataObject::export

(^)

SDO_Model_ReflectionDataObject::export — Get a string describing the SDO_DataObject

Description

SDO_Model_ReflectionDataObject::export ( SDO_Model_ReflectionDataObject $rdo [, bool $return ] ) : mixed
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.

Get a string describing the SDO_DataObject. The default behaviour is to print the output, but if TRUE is specified for return, it is returned as a string.

Parameters

rdo

An SDO_Model_ReflectionDataObject.

return

If TRUE, return the output as a string, otherwise print it.

Return Values

Returns the output if TRUE is specified for return, otherwise NULL.


Get the property which defines the containment relationship to the data object

  • « SDO_Model_ReflectionDataObject::export
  • SDO_Model_ReflectionDataObject::getInstanceProperties »
  • PHP Manual
  • SDO Functions
  • Get the property which defines the containment relationship to the data object

SDO_Model_ReflectionDataObject::getContainmentProperty

(^)

SDO_Model_ReflectionDataObject::getContainmentProperty — Get the property which defines the containment relationship to the data object

Description

SDO_Model_ReflectionDataObject::getContainmentProperty ( void ) : SDO_Model_Property
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.

Get the SDO_Model_Property that contains the SDO_DataObject. This method is used to navigate up to the parent's property which contains the data object which has been reflected upon.

Parameters

None.

Return Values

Returns the container's SDO_Model_Property which references the SDO_DataObject, or NULL if it is a root SDO_DataObject.


Get the instance properties of the SDO_DataObject

  • « SDO_Model_ReflectionDataObject::getContainmentProperty
  • SDO_Model_ReflectionDataObject::getType »
  • PHP Manual
  • SDO Functions
  • Get the instance properties of the SDO_DataObject

SDO_Model_ReflectionDataObject::getInstanceProperties

(^)

SDO_Model_ReflectionDataObject::getInstanceProperties — Get the instance properties of the SDO_DataObject

Description

SDO_Model_ReflectionDataObject::getInstanceProperties ( void ) : array
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.

Get the instance properties for the SDO_DataObject. The instance properties consist of all the properties defined on the data object's type, plus any instance properties from open content (if the data object is an open type).

Parameters

None.

Return Values

An array of SDO_Model_Property objects.


Get the SDO_Model_Type for the SDO_DataObject

  • « SDO_Model_ReflectionDataObject::getInstanceProperties
  • SDO_Model_Type::getBaseType »
  • PHP Manual
  • SDO Functions
  • Get the SDO_Model_Type for the SDO_DataObject

SDO_Model_ReflectionDataObject::getType

(^)

SDO_Model_ReflectionDataObject::getType — Get the SDO_Model_Type for the SDO_DataObject

Description

SDO_Model_ReflectionDataObject::getType ( void ) : SDO_Model_Type
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.

Returns the SDO_Model_Type for the SDO_DataObject. The SDO_Model_Type holds all the information about the data object's type, such as namespace URI, type name, whether it is a primitive data type, and so on.

Parameters

None.

Return Values

Returns the SDO_Model_Type for the SDO_DataObject.


Get the base type for this type

  • « SDO_Model_ReflectionDataObject::getType
  • SDO_Model_Type::getName »
  • PHP Manual
  • SDO Functions
  • Get the base type for this type

SDO_Model_Type::getBaseType

(^)

SDO_Model_Type::getBaseType — Get the base type for this type

Description

SDO_Model_Type::getBaseType ( void ) : SDO_Model_Type
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.

Get the base type for this type. Returns the SDO_Model_Type for the base type if this type inherits from another, otherwise returns NULL. An example of when base types occur is when a type defined in XML schema inherits from another type by using

<extension base="...">
.

Parameters

None.

Return Values

Returns the SDO_Model_Type for the base type if this type inherits from another, otherwise returns NULL.


Get the name of the type

  • « SDO_Model_Type::getBaseType
  • SDO_Model_Type::getNamespaceURI »
  • PHP Manual
  • SDO Functions
  • Get the name of the type

SDO_Model_Type::getName

(^)

SDO_Model_Type::getName — Get the name of the type

Description

SDO_Model_Type::getName ( void ) : string
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.

Returns the name of the type. The combination of type name and namespace URI is used to uniquely identify the type.

Parameters

None.

Return Values

Returns the name of the type.


Get the namespace URI of the type

  • « SDO_Model_Type::getName
  • SDO_Model_Type::getProperties »
  • PHP Manual
  • SDO Functions
  • Get the namespace URI of the type

SDO_Model_Type::getNamespaceURI

(^)

SDO_Model_Type::getNamespaceURI — Get the namespace URI of the type

Description

SDO_Model_Type::getNamespaceURI ( void ) : string
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.

Returns the namespace URI of the type. The combination of namespace URI and type name is used to uniquely identify the type.

Parameters

None.

Return Values

Returns the namespace URI of the type.


Get the SDO_Model_Property objects defined for the type

  • « SDO_Model_Type::getNamespaceURI
  • SDO_Model_Type::getProperty »
  • PHP Manual
  • SDO Functions
  • Get the SDO_Model_Property objects defined for the type

SDO_Model_Type::getProperties

(^)

SDO_Model_Type::getProperties — Get the SDO_Model_Property objects defined for the type

Description

SDO_Model_Type::getProperties ( void ) : array
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.

Get an array of SDO_Model_Property objects describing the properties defined for the SDO_Model_Type. Each SDO_Model_Property holds information such as the property name, default value, and so on.

Parameters

None.

Return Values

Returns an array of SDO_Model_Property objects.


Get an SDO_Model_Property of the type

  • « SDO_Model_Type::getProperties
  • SDO_Model_Type::isAbstractType »
  • PHP Manual
  • SDO Functions
  • Get an SDO_Model_Property of the type

SDO_Model_Type::getProperty

(^)

SDO_Model_Type::getProperty — Get an SDO_Model_Property of the type

Description

SDO_Model_Type::getProperty ( mixed $identifier ) : SDO_Model_Property
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.

Get an SDO_Model_Property of the type, identified by its property index or property name.

Parameters

identifier

The property index or property name.

Return Values

Returns the SDO_Model_Property.


Test to see if this SDO_Model_Type is an abstract data type

  • « SDO_Model_Type::getProperty
  • SDO_Model_Type::isDataType »
  • PHP Manual
  • SDO Functions
  • Test to see if this SDO_Model_Type is an abstract data type

SDO_Model_Type::isAbstractType

(^)

SDO_Model_Type::isAbstractType — Test to see if this SDO_Model_Type is an abstract data type

Description

SDO_Model_Type::isAbstractType ( void ) : bool
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.

Test to see if this SDO_Model_Type is an abstract data type. Returns TRUE if this type is abstract, that is, no SDO_DataObject of this type can be instantiated, though other types may inherit from it.

Parameters

None.

Return Values

Returns TRUE if this type is an abstract data type, otherwise returns FALSE.


Test to see if this SDO_Model_Type is a primitive data type

  • « SDO_Model_Type::isAbstractType
  • SDO_Model_Type::isInstance »
  • PHP Manual
  • SDO Functions
  • Test to see if this SDO_Model_Type is a primitive data type

SDO_Model_Type::isDataType

(^)

SDO_Model_Type::isDataType — Test to see if this SDO_Model_Type is a primitive data type

Description

SDO_Model_Type::isDataType ( void ) : bool
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.

Test to see if this SDO_Model_Type is a primitive data type. Returns TRUE if this type is a primitive data type, otherwise returns FALSE.

Parameters

None.

Return Values

Returns TRUE if this type is a primitive data type, otherwise returns FALSE.


Test for an SDO_DataObject being an instance of this SDO_Model_Type

  • « SDO_Model_Type::isDataType
  • SDO_Model_Type::isOpenType »
  • PHP Manual
  • SDO Functions
  • Test for an SDO_DataObject being an instance of this SDO_Model_Type

SDO_Model_Type::isInstance

(^)

SDO_Model_Type::isInstance — Test for an SDO_DataObject being an instance of this SDO_Model_Type

Description

SDO_Model_Type::isInstance ( SDO_DataObject $data_object ) : bool
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.

Test for an SDO_DataObject being an instance of this SDO_Model_Type. Returns TRUE if the SDO_DataObject provided is an instance of this SDO_Model_Type, or a derived type, otherwise returns FALSE.

Parameters

data_object

The SDO_DataObject to be tested.

Return Values

Returns TRUE if the SDO_DataObject provided is an instance of this SDO_Model_Type, or a derived type, otherwise returns FALSE.


Test to see if this type is an open type

  • « SDO_Model_Type::isInstance
  • SDO_Model_Type::isSequencedType »
  • PHP Manual
  • SDO Functions
  • Test to see if this type is an open type

SDO_Model_Type::isOpenType

(^)

SDO_Model_Type::isOpenType — Test to see if this type is an open type

Description

SDO_Model_Type::isOpenType ( void ) : bool
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.

Test to see if this type is open. Returns TRUE if this type is open, otherwise returns FALSE. An SDO_DataObject whose type is open can have properties added to them which are not described by the type. This capability is used to support working with XML documents whose schema support open content, such as that defined by an

<xsd:any>
element.

Parameters

None.

Return Values

Returns TRUE if this type is open, otherwise returns FALSE.


Test to see if this is a sequenced type

  • « SDO_Model_Type::isOpenType
  • SDO_Sequence::getProperty »
  • PHP Manual
  • SDO Functions
  • Test to see if this is a sequenced type

SDO_Model_Type::isSequencedType

(^)

SDO_Model_Type::isSequencedType — Test to see if this is a sequenced type

Description

SDO_Model_Type::isSequencedType ( void ) : bool
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.

Test to see if this is a sequenced type. Returns TRUE if this type is sequence, otherwise returns FALSE. Sequenced types can have the ordering across properties preserved and can contain unstructured text. For more information on sequenced types see the section on Working with Sequenced Data Objects.

Parameters

None.

Return Values

Returns TRUE if this type is sequence, otherwise return FALSE.


Return the property for the specified sequence index

  • « SDO_Model_Type::isSequencedType
  • SDO_Sequence::insert »
  • PHP Manual
  • SDO Functions
  • Return the property for the specified sequence index

SDO_Sequence::getProperty

(^)

SDO_Sequence::getProperty — Return the property for the specified sequence index

Description

SDO_Sequence::getProperty ( int $sequence_index ) : SDO_Model_Property
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.

Return the property for the specified sequence index.

Parameters

sequence_index

The position of the element in the sequence.

Return Values

An SDO_Model_Property. A return value of NULL means the sequence element does not belong to a property and must therefore be unstructured text.

Errors/Exceptions

SDO_IndexOutOfBoundsException

Thrown if the sequence index is less than zero or greater than the size of the sequence.


Insert into a sequence

  • « SDO_Sequence::getProperty
  • SDO_Sequence::move »
  • PHP Manual
  • SDO Functions
  • Insert into a sequence

SDO_Sequence::insert

(^)

SDO_Sequence::insert — Insert into a sequence

Description

SDO_Sequence::insert ( mixed $value [, int $sequenceIndex [, mixed $propertyIdentifier ]] ) : void
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.

Insert a new element at a specified position in the sequence. All subsequent sequence items are moved up.

Parameters

value

The new value to be inserted. This can be either a primitive or an SDO_DataObject.

sequenceIndex

The position at which to insert the new element. Default is NULL, which results in the new value being appended to the sequence.

propertyIdentifier

Either a property index, a property name, or an SDO_Model_Property, used to identify a property in the sequence's corresponding SDO_DataObject. A value of NULL signifies unstructured text.

Return Values

None.

Errors/Exceptions

SDO_IndexOutOfBoundsException

Thrown if the sequence index is less than zero or greater than the size of the sequence.

SDO_InvalidConversionException

Thrown if the type of the new value cannot be juggled to match the type for the specified data object property.


Move an item to another sequence position

  • « SDO_Sequence::insert
  • SDO-DAS-Relational »
  • PHP Manual
  • SDO Functions
  • Move an item to another sequence position

SDO_Sequence::move

(^)

SDO_Sequence::move — Move an item to another sequence position

Description

SDO_Sequence::move ( int $toIndex, int $fromIndex ) : void
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.

Modify the position of the item in the sequence, without altering the value of the property in the SDO_DataObject.

Parameters

toIndex

The destination sequence index. If this index is less than zero or greater than the size of the sequence then the value is appended.

fromIndex

The source sequence index.

Return Values

None.

Errors/Exceptions

SDO_IndexOutOfBoundsException

Thrown if the fromIndex sequence index is less than zero or greater than the size of the sequence.


SDO Relational Data Access Service

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Creating, retrieving, updating and deleting data
    • Specifying the metadata
    • One-table examples
    • Two-table examples
    • Three-table example
  • Limitations
  • SDO-DAS-Relational Functions
    • SDO_DAS_Relational::applyChanges — Applies the changes made to a data graph back to the database
    • SDO_DAS_Relational::__construct — Creates an instance of a Relational Data Access Service
    • SDO_DAS_Relational::createRootDataObject — Returns the special root object in an otherwise empty data graph. Used when creating a data graph from scratch
    • SDO_DAS_Relational::executePreparedQuery — Executes an SQL query passed as a prepared statement, with a list of values to substitute for placeholders, and return the results as a normalised data graph
    • SDO_DAS_Relational::executeQuery — Executes a given SQL query against a relational database and returns the results as a normalised data graph


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.

In order to use the Relational Data Access Service for Service Data Objects, you will need to understand some of the concepts behind SDO: the data graph, the data object, the disconnected way of working, the change summary, XPath and property expressions, and so on. If you are not familiar with these ideas, you might want to look first at the section on SDO. In addition, the Relational DAS makes use of the PDO extension to isolate itself from specifics of different back-end relational databases. In order to use the Relational DAS you will need to be able to create and pass a PDO database connection; for this reason you might also want to take a look at the section on PDO.

The job of the Relational DAS is to move data between the application and a relational database. In order to do this it needs to be told the mapping between the database entities - tables, columns, primary keys and foreign keys - and the elements of the SDO model - types, properties, containment relationships and so on. You specify this information as metadata when you construct the Relational DAS.

Overview of Operation

  1. The first step is to call the Relational DAS's constructor, passing the metadata that defines the mapping between database and SDO model. There are examples of this below.

  2. The next step might be to call the executeQuery() or executePreparedQuery() methods on the Relational DAS, passing either a literal SQL statement for the DAS to prepare and execute, or a prepared statement with placeholders and a list of values to be inserted. You may also need to specify a small amount of metadata about the query itself, so that the Relational DAS knows exactly what columns will be returned from the database and in what order. You will also need to pass a PDO database connection.

    The return value from executeQuery() or executePreparedQuery() is a normalised data graph containing all the data from the result set. For a query that returns data obtained from a number of tables, this graph will contain a number of data objects, linked by SDO containment relationships. There may also be SDO non-containment references within the data.

    Once the query has been executed and the data graph constructed, there is no need for either that instance of the Relational DAS or the database connection. There are no locks held on the database. Both the Relational DAS and the PDO database connection can be garbage collected.

  3. Quite possibly the data in the data graph will go through a number of modifications. The data graph can be serialised into the PHP session and so may have a lifetime beyond just one client-server interaction. Data objects can be created and added to the graph, the data objects already in the graph can be deleted, and data objects in the graph can be modified.

  4. Finally, the changes made to the data graph can be applied back to the database using the applyChanges() method of the Relational DAS. For this, another instance of the Relational DAS must be constructed, using the same metadata, and another connection to the database obtained. The connection and the data graph are passed to applyChanges(). At this point the Relational DAS examines the change summary and generates the necessary INSERT, UPDATE and DELETE SQL statements to apply the changes. Any UPDATE and DELETE statements are qualified with the original values of the data so that should the data have changed in the database in the meantime this will be detected. Assuming no such collisions have occurred the changes will be committed to the database. The application can then continue to work with the data graph, make more changes and apply them, or can discard it.

There are other ways of working with the data in the database: it is possible to just create data objects and write them to the database without a preliminary call to executeQuery(), for example. This scenario and others are explored in the Examples section below.


Requirements

The Relational DAS requires that the SDO extension be installed. The SDO extension requires a version of PHP 5.1, and the Relational DAS requires a recent version that contains an important fix for PDO. The most up-to-date information about required levels of PHP should be found in the changelog for the package on PECL. At the time of writing, though, the Relational DAS requires the most recent beta level of PHP 5.1, that is PHP 5.1.0.

The Relational DAS uses PDO to access the relational database, and so should run with a variety of different relational databases. At the time of writing it has been tested in the following configurations

  • MySQL 4.1.14, on Windows. The Relational DAS operates correctly with the php_pdo_mysql driver that comes with the pre-built binaries for PHP 5.1.0.

  • MySQL 4.1.13, on Linux. It is necessary to have the most up-to-date PDO driver for MySQL, which comes built in to PHP 5.1.0. It may be necessary to uninstall the usual driver that would have come from PECL using pear uninstall pdo_mysql. You will need to configure PHP with the --with-pdo-mysql option.

  • DB2 8.2 Personal Edition, on Windows. The Relational DAS operates correctly with the php_pdo_odbc driver that comes with the pre-built binaries for PHP 5.1.0.

  • DB2 8.2 Personal Developer's Edition, on Linux. The Developer's Edition is needed because it contains the include files needed when PHP is configured and built. You will need to configure PHP with the --with-pdo-odbc=ibm-db2 option.

The Relational DAS applies changes to the database within a user-delimited transaction: that is, it issues a call to PDO::beginTransaction() before beginning to apply changes, and PDO::commit() or PDO::rollback() on completion. Whichever database is chosen, the database and the PDO driver for the database must support these calls.


Installation

The installation instructions for all the SDO components are in the SDO install section of the SDO documentation.

In any case, the essential facts are that the Relational DAS is written in PHP and it should be placed somewhere on the PHP include_path.

Your application will of course need to include the Relational DAS with a statement like this:

<?php
require_once 'SDO/DAS/Relational.php';
?>


Runtime Configuration

This extension has no configuration directives defined in php.ini.

Tracing

You may be interested in seeing the SQL statements that are generated in order to apply changes back to the database. At the top of the SDO/DAS/Relational.php you will find a number of constants which control whether the process of constructing and executing the SQL statements is to be traced. Try setting DEBUG_EXECUTE_PLAN to TRUE to see the generated SQL statements.


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 Relational DAS introduces no predefined constants.


Examples

Table of Contents

  • Creating, retrieving, updating and deleting data
  • Specifying the metadata
  • One-table examples
  • Two-table examples
  • Three-table example


Creating, retrieving, updating and deleting data

This section illustrates how the Relational DAS can be used to create, retrieve, update and delete data in a relational database. Many of the examples are illustrated with a three-table database that contains companies, departments within those companies, and employees that work in those departments. This example is used in a number of places within the SDO literature. See the examples section of the » Service Data Objects specification or the Examples section of the documentation for the SDO extension.

The Relational DAS is constructed with metadata that defines the relational database and how it should be mapped to SDO. The long section that follows describes this metadata and how to construct the Relational DAS. The examples that follow it all assume that this metadata is in an included php file.

The examples below and others can all be found in the Scenarios directory in the Relational DAS package.

The Relational DAS throws exceptions in the event that it finds errors in the metadata or errors when executing SQL statements against the database. For brevity the examples below all omit the use of try/catch blocks around the calls to the Relational DAS.

These examples all differ from the expected use of SDO in two important respects.

First, they show all interactions with the database completed within one script. In this respect these scenarios are not realistic but are chosen to illustrate just the use of the Relational DAS. It is expected that interactions with the database will be separated in time and the data graph serialized and deserialized into the PHP session one or more times as the application interacts with an end user.

Second, all queries executed against the database use hard-coded queries with no variables substituted. In this case it is safe to use the simple executeQuery() call, and this is what the examples illustrate. In practice, though, it is unlikely that the SQL statement is known entirely ahead of time. In order to allow variables to be safely substituted into the SQL queries, without running the risk of injecting SQL with unknown effects, it is safer to use the executePreparedQuery() which takes a prepared SQL statement containing placeholders and a list of values to be substituted.


Specifying the metadata

This first long section describes in detail how the metadata describing the database and the required SDO model is supplied to the Relational DAS.

When the constructor for the Relational DAS is invoked, it needs to be passed several pieces of information. The bulk of the information, passed as an associative array in the first argument to the constructor, tells the Relational DAS what it needs to know about the relational database. It describes the names of the tables, columns, primary keys and foreign keys. It should be fairly easy to understand what is required, and once written it can be placed in a php file and included when needed. The remainder of the information, passed in the second and third arguments to the constructor, tells the Relational DAS what it needs to know about the relationships between objects and the shape of the data graph; it ultimately determines how the data from the database is to be normalized into a graph.

Database metadata

The first argument to the constructor describes the target relational database.

Each table is described by an associative array with up to four keys.

Key | Value
name | The name of the table.
columns | An array listing the names of the columns, in any order.
PK | The name of the column containing the primary key.
FK | An array with two entries, 'from' and 'to', which define a column containing a foreign key, and a table to which the foreign key points. If there are no foreign keys in the table then the 'FK' entry does not need to be specified. Only one foreign key can be specified. Only a foreign key pointing to the primary key of a table can be specified.

<?php
/*****************************************************************
* METADATA DEFINING THE DATABASE
******************************************************************/
$company_table = array (
  'name' => 'company',
  'columns' => array('id', 'name',  'employee_of_the_month'),
  'PK' => 'id',
  'FK' => array (
      'from' => 'employee_of_the_month',
      'to' => 'employee',
      ),
  );
$department_table = array (
  'name' => 'department',
  'columns' => array('id', 'name', 'location', 'number', 'co_id'),
  'PK' => 'id',
  'FK' => array (
      'from' => 'co_id',
      'to' => 'company',
      )
  );
$employee_table = array (
  'name' => 'employee',
  'columns' => array('id', 'name', 'SN', 'manager', 'dept_id'),
  'PK' => 'id',
  'FK' => array (
      'from' => 'dept_id',
      'to' => 'department',
      )
  );
$database_metadata = array($company_table, $department_table, $employee_table);
?>

This metadata corresponds to a relational database that might have been defined to MySQL as:

create table company (
 id integer auto_increment,
 name char(20),
 employee_of_the_month integer,
 primary key(id)
);
create table department (
 id integer auto_increment,
 name char(20),
 location char(10),
 number integer(3),
 co_id integer,
 primary key(id)
);
create table employee (
 id integer auto_increment,
 name char(20),
 SN char(4),
 manager tinyint(1),
 dept_id integer,
 primary key(id)
);

or to DB2 as:

create table company ( \
  id integer not null generated by default as identity,  \
  name varchar(20), \
  employee_of_the_month integer, \
  primary key(id) )
create table department ( \
  id integer not null generated by default as identity, \
  name varchar(20), \
  location varchar(10), \
  number integer, \
  co_id integer, \
  primary key(id) )
create table employee ( \
  id integer not null generated by default as identity, \
  name varchar(20), \
  SN char(4), \
  manager smallint, \
  dept_id integer, \
  primary key(id) )

Note that although in this example there are no foreign keys specified to the database and so the database is not expected to enforce referential integrity, the intention behind the co_id column on the department table and the dept_id column on the employee table is they should contain the primary key of their containing company or department record, respectively. So these two columns are acting as foreign keys.

There is a third foreign key in this example, that from the employee_of_the_month column of the company record to a single row of the employee table. Note the difference in intent between this foreign key and the other two. The employee_of_the_month column represents a single-valued relationship: there can be only one employee of the month for a given company. The co_id and dept_id columns represent multi-valued relationships: a company can contain many departments and a department can contain many employees. This distinction will become evident when the remainder of the metadata picks out the company-department and department-employee relationships as containment relationships.

There are a few simple rules to be followed when constructing the database metadata:

  • All tables must have primary keys, and the primary keys must be specified in the metadata. Without primary keys it is not possible to keep track of object identities. As you can see from the SQL statements that create the tables, primary keys can be auto-generated, that is, generated and assigned by the database when a record is inserted. In this case the auto-generated primary key is obtained from the database and inserted into the data object immediately after the row is inserted into the database.

  • It is not necessary to specify in the metadata all the columns that exist in the database, only those that will be used. For example, if the company table had another column that the application did not want to access with SDO, this need not be specified in the metadata. On the other hand it would have done no harm to specify it: if specified in the metadata but never retrieved, or assigned to by the application, then the unused column will not affect anything.

  • In the database metadata note that the foreign key definitions identify not the destination column in the table which is pointed to, but the table name itself. Strictly, the relational model permits the destination of a foreign key to be a non-primary key. Only foreign keys that point to a primary key are useful for constructing the SDO model, so the metadata specifies the table name. It is understood that the foreign key points to the primary key of the given table.

Given these rules, and given the SQL statements that define the database, the database metadata should be easy to construct.

What the Relational DAS does with the metadata

The Relational DAS uses the database metadata to form most of the SDO model. For each table in the database metadata, an SDO type is defined. Each column which can represent a primitive value (columns which are not defined as foreign keys) are added as properties to the SDO type.

All primitive properties are given a type of string in the SDO model, regardless of their SQL type. When writing values back to the database the Relational DAS will create SQL statements that treat the values as strings, and the database will convert them to the appropriate type.

Foreign keys are interpreted in one of two ways, depending on the metadata in the third argument to the constructor that defines the SDO containment relationships. A discussion of this is therefore deferred until the section on SDO containment relationships below.

Specifying the application root type

The second argument to the constructor is the application root type. The true root of each data graph is an object of a special root type and all application data objects come somewhere below that. Of the various application types in the SDO model, one has to be the application type immediately below the root of the data graph. If there is only one table in the database metadata, the application root type can be inferred, and this argument can be omitted.

Specifying the SDO containment relationships

The third argument to the constructor defines how the types in the model are to be linked together to form a graph. It identifies the parent-child relationships between the types which collectively form a graph. The relationships need to be supported by foreign keys to be found in the data, in a way shortly to be described.

The metadata is an array containing one or more associative arrays, each of which identifies a parent and a child. The example below shows a parent-child relationship from company to department, and another from department to employee. Each of these will become an SDO property defining a multi-valued containment relationship in the SDO model.

<?php
$department_containment = array( 'parent' => 'company', 'child' => 'department');
$employee_containment = array( 'parent' => 'department', 'child' => 'employee');

$SDO_containment_metadata = array($department_containment, $employee_containment);
?>

Foreign keys in the database metadata are interpreted as properties with either multi-valued containment relationships or single-valued non-containment references, depending on whether they have a corresponding SDO containment relationship specified in the metadata. In the example here, the foreign keys from department to company (the co_id column in the department table) and from employee to department (the dept_id column in the employee table) are interpreted as supporting the SDO containment relationships. Each containment relationship mentioned in the SDO containment relationships metadata must have a corresponding foreign key present in the database and defined in the database metadata. The values of the foreign key columns for containment relationships do not appear in the data objects, instead each is represented by a containment relationship from the parent to the child. So the co_id column in the department row in the database, for example, does not appear as a property on the department type, but instead as a containment relationship called department on the company type. Note that the foreign key and the parent-child relationship appear to have opposite senses: the foreign key points from the department to the company, but the parent-child relationship points from company to department.

The third foreign key in this example, the employee_of_the_month , is handled differently. This is not mentioned in the SDO containment relationships metadata. As a consequence this is interpreted in the second way: it becomes a single-valued non-containment reference on the company object, to which can be assigned references to SDO data objects of the employee type. It does appear as a property on the company type. The way to assign a value to it in the SDO data graph is to have a graph that contains an employee object through the containment relationships, and to assign the object to it. This is illustrated in the later examples below.


One-table examples

The following set of examples all use the Relational DAS to work with a data graph containing just one application data object, a single company and the data just to be found the company table. These examples do not exercise the power of SDO or the Relational DAS and of course the same result could be achieved more economically with direct SQL statements but they are intended to illustrate how to work with the Relational DAS.

For this very simple scenario it would be possible to simplify the database metadata to include just the company table - if that were done the second and third arguments to the constructor and the column specifier used in the query example would become optional.

Example #1 Creating a data object

The simplest example is that of creating a single data object and writing it to the database. In this example a single company object is created, its name is set to 'Acme', and the Relational DAS is called to write the changes to the database. The company name is set here using the property name method. See the Examples section on the SDO extension for other ways of accessing the properties of an object.

Data objects can only be created when you have a data object to start with, however. It is for that reason that the first call to the Relational DAS here is to obtain a root object. This is in effect how to ask for an empty data graph - the special root object is the true root of the tree. The company data object is then created with a call to createDataObject() on the root object. This creates the company data object and inserts it in the graph by inserting into a multi-valued containment property on the root object called 'company'.

When the Relational DAS is called to apply the changes a simple insert statement 'INSERT INTO company (name) VALUES ("Acme");' will be constructed and executed. The auto-generated primary key will be set into the data object and the change summary will be reset, so that it would be possible to continue working with the same data object, modify it, and apply the newer changes a second time.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
* Construct the DAS with the metadata
***************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);

/**************************************************************
* Obtain a root object and create a company object underneath.
* Make a simple change to the data object.
***************************************************************/
$root = $das  -> createRootDataObject();
$acme = $root -> createDataObject('company');

$acme->name = "Acme";

/**************************************************************
* Get a database connection and write the object to the database
***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);
$das -> applyChanges($dbh, $root);
?>

Example #2 Retrieving a data object

In this example a single data object is retrieved from the database - or possibly more than one if there is more than one company called 'Acme'. For each company returned, the name and id properties are echoed.

In this example the third argument to executeQuery(), the column specifier is needed as there are other tables in the metadata with column names of name and id. If there were no possible ambiguity it could be omitted.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
* Construct the DAS with the metadata
***************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);

/**************************************************************
* Get a database connection
***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

/**************************************************************
* Issue a query to obtain a company object - possibly more if they exist
***************************************************************/
$root = $das->executeQuery($dbh,
         'select name, id from company where name="Acme"',
          array('company.name', 'company.id') );

/**************************************************************
* Echo name and id
***************************************************************/
foreach ($root['company'] as $company) {
  echo "Company obtained from the database has name = " .
  $company['name'] . " and id " . $company['id'] . "\n";
}
?>

Example #3 Updating a data object

This example combines the previous two, in the sense that in order to be updated the object must first be retrieved. The application code reverses the company name (so 'Acme' becomes 'emcA') and then the changes are written back to the database in the same way that they were when the object was created. Because the query searches for the name both ways round the program can be run repeatedly to find the company and reverse its name each time.

In this example the same instance of the Relational DAS is reused for the applyChanges(), as is the PDO database handle. This is quite alright; it also alright to allow the previous instances to be garbage collected and to obtain new instances. No state data regarding the graph is held the Relational DAS once it has returned a data graph to the application. All necessary data is either within the graph itself, or can be reconstructed from the metadata.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
* Construct the DAS with the metadata
***************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);

/**************************************************************
* Get a database connection
***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

/**************************************************************
* Issue a query to obtain a company object - possibly more if they exist
***************************************************************/
$root = $das->executeQuery($dbh,
  'select name, id from company where name="Acme" or name="emcA"',
  array('company.name', 'company.id') );

/**************************************************************
* Alter the name of just the first company
***************************************************************/
$company = $root['company'][0];
echo "obtained a company with name of " . $company->name . "\n";
$company->name = strrev($company->name);

/**************************************************************
* Write the change back
***************************************************************/
$das->applyChanges($dbh,$root);
?>

Example #4 Deleting a data object

Any companies called 'Acme' or its reverse 'emcA' are retrieved. They are then all deleted from the graph with unset.

In this example they are all deleted in one go by unsetting the containing property (the property defining the containment relationship). It is also possible to delete them individually.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
* Construct the DAS with the metadata
***************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);

/**************************************************************
* Get a database connection
***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

/**************************************************************
* Issue a query to obtain a company object - possibly more if they exist
***************************************************************/
$root = $das->executeQuery($dbh,
  'select name, id from company where name="Acme" or name="emcA"',
  array('company.name', 'company.id') );

/**************************************************************
* Delete any companies found from the data graph
***************************************************************/
unset($root['company']);

/**************************************************************
* Write the change(s) back
***************************************************************/
$das->applyChanges($dbh,$root);
?>


Two-table examples

The following set of examples all use two tables from the company database: the company and department tables. These examples exercise more of the function of the Relational DAS.

In this series of examples a company and department are created, retrieved, updated, and finally deleted. This illustrates the lifecycle for a data graph containing more than one object. Note that this example clears out the company and department tables at the start so that the exact results of the queries can be known.

You can find these examples combined into one script called 1cd-CRUD in the Scenarios directory in the Relational DAS package.

Example #1 One company, one department - Create

As in the earlier example of creating just one company data object, the first action after constructing the Relational DAS is to call createRootDataObject() to obtain the special root object of the otherwise empty data graph. The company object is then created as a child of the root object, and the department object as a child of the company object.

When it comes to applying the changes, the Relational DAS has to perform special processing to maintain the foreign keys that support the containment relationships, especially if auto-generated primary keys are involved. In this example, the relationship between the auto-generated primary key id in the company table and the co_id column in the department table must be maintained. When inserting a company and department for the first time the Relational DAS has to first insert the company row, then call PDO's getLastInsertId() method to obtain the auto-generated primary key, then add that as the value of the co_id column when inserting the department row.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/*************************************************************************************
* Empty out the two tables
*************************************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);
$pdo_stmt = $dbh->prepare('DELETE FROM COMPANY;');
$rows_affected = $pdo_stmt->execute();
$pdo_stmt = $dbh->prepare('DELETE FROM DEPARTMENT;');
$rows_affected = $pdo_stmt->execute();

/**************************************************************
* Create a company with name Acme and one department, the Shoe department
***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);

$root = $das -> createRootDataObject();

$acme = $root -> createDataObject('company');
$acme -> name = "Acme";

$shoe = $acme->createDataObject('department');
$shoe->name = 'Shoe';

$das -> applyChanges($dbh, $root);

?>

Example #2 One company, one department - Retrieve and Update

In this case the SQL query passed to executeQuery() performs an inner join to join the data from the company and department tables. Primary keys for both the company and department tables must be included in the query. The result set is re-normalised to form a normalised data graph. Note that a column specifier is passed as the third argument to the executeQuery() call enabling the Relational DAS to know which column is which in the result set.

Note that the co_id column although used in the query is not needed in the result set. In order to understand what the Relational DAS is doing when it builds the data graph it may be helpful to visualise what the result set looks like. Although the data in the database is normalised, so that multiple department rows can point through their foreign key to one company row, the data in the result set is non-normalised: that is, if there is one company and multiple departments, the values for the company are repeated in each row. The Relational DAS has to reverse this process and turn the result set back into a normalised data graph, with just one company object.

In this example the Relational DAS will examine the result set and column specifier, find data for both the company and department tables, find primary keys for both, and interpret each row as containing data for a department and its parent company. If it has not seen data for that company before (it uses the primary key to check) it creates a company object and then a department object underneath it. If it has seen data for that company before and has already created the company object it just creates the department object underneath.

In this way the Relational DAS can retrieve and renormalise data for multiple companies and multiple departments underneath them.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
* Retrieve the company and Shoe department, then delete Shoe and add IT
***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);

$root = $das->executeQuery($dbh,
'select c.id, c.name, d.id, d.name from company c, department d where d.co_id = c.id',
array('company.id','company.name','department.id','department.name'));

$acme = $root['company'][0];            // get the first company - will be 'Acme'
$shoe = $acme['department'][0];         // get the first department underneath - will be 'Shoe'

unset($acme['department'][0]);

$it = $acme->createDataObject('department');
$it->name = 'IT';

$das -> applyChanges($dbh, $root);
?>

Example #3 One company, two departments - Retrieve and Delete

In this example the company and department are retrieved and then deleted. It is not necessary to delete them individually (although that would be possible) - deleting the company object from the data graph also deletes any departments underneath it.

Note the way that the company object is actually deleted using the PHP unset call. The unset has to be performed on the containing property which in this case is the company property on the special root object. You must use:

<?php
unset($root['company'][0]);
?>
and not:
<?php
unset($acme); //WRONG
?>
Simply unsetting $acme would destroy the variable but leave the data in the data graph untouched.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
* Retrieve the company and IT department, then delete the whole company
***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);

$root = $das->executeQuery($dbh,
'select c.id, c.name, d.id, d.name from company c, department d where d.co_id = c.id',
array('company.id','company.name','department.id','department.name'));

$acme = $root['company'][0];
$it = $acme['department'][0];

unset($root['company'][0]);

$das -> applyChanges($dbh, $root);

?>


Three-table example

The following examples use all three tables from the company database: the company, department, and employee tables. These introduce the final piece of function not exercised by the examples above: the non-containment reference employee_of_the_month.

Like the examples above for company and department, this set of examples is intended to illustrate the full lifecycle of such a data graph.

Example #1 One company, one department, one employee - Create

In this example a company is created containing one department and just one employee. Note that this example clears out all three tables at the start so that the exact results of the queries can be known.

Note how once the company, department and employee have been created, the employee_of_the_month property of the company can be made to point at the new employee. As this is a non-containment reference, this cannot be done until the employee object has been created within the graph. Non-containment references need to be managed carefully. For example if the employee were now deleted from under the department, it would not be correct to try to save the graph without first clearing or re-assigning the employee_of_the_month property. The closure rule for SDO data graphs requires that any object pointed at by a non-containment reference must also be reachable by containment relationships.

When it comes to inserting the graph into the database, the procedure is similar to the example of inserting the company and department, but employee_of_the_month introduces an extra complexity. The Relational DAS needs to insert the objects working down the tree formed by containment relationships, so company, then department, then employee. This is necessary so that it always has the auto-generated primary key of a parent on hand to include in a child row. But when the company row is inserted the employee who is employee of the month has not yet been inserted and the primary key is not known. The procedure is that after the employee record is inserted and its primary key known, a final step is performed in which the company record is updated with the employee's primary key.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/*************************************************************************************
* Empty out the three tables
*************************************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);
$pdo_stmt = $dbh->prepare('DELETE FROM COMPANY;');
$rows_affected = $pdo_stmt->execute();
$pdo_stmt = $dbh->prepare('DELETE FROM DEPARTMENT;');
$rows_affected = $pdo_stmt->execute();
$pdo_stmt = $dbh->prepare('DELETE FROM EMPLOYEE;');
$rows_affected = $pdo_stmt->execute();

/*************************************************************************************
* Create a tiny but complete company.
* The company name is Acme.
* There is one department, Shoe.
* There is one employee, Sue.
* The employee of the month is Sue.
*************************************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

$root             = $das  -> createRootDataObject();
$acme             = $root -> createDataObject('company');
$acme -> name     = "Acme";
$shoe             = $acme -> createDataObject('department');
$shoe -> name     = 'Shoe';
$shoe -> location = 'A-block';
$sue              = $shoe -> createDataObject('employee');
$sue -> name      = 'Sue';
$acme -> employee_of_the_month = $sue;

$das -> applyChanges($dbh, $root);

echo "Wrote back Acme with one department and one employee\n";
?>

Example #2 One company, one department, one employee - Retrieve and update

The SQL statement passed to the Relational DAS is this time an inner join that retrieves data from all three tables. Otherwise this example introduces nothing that has not appeared in a previous example.

The graph is updated by the addition of a new department and employee and some alterations to the name properties of the existing objects in the graph. The combined changes are then written back. The Relational DAS will process and apply an arbitrary mixture of additions, modifications and deletions to and from the data graph.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/*************************************************************************************
* Find the company again and change various aspects.
* Change the name of the company, department and employee.
* Add a second department and a new employee.
* Change the employee of the month.
*************************************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

$root = $das->executeQuery($dbh,
  "select c.id, c.name, c.employee_of_the_month, d.id, d.name, e.id, e.name " .
  "from company c, department d, employee e " .
  "where e.dept_id = d.id and d.co_id = c.id and c.name='Acme'",
   array('company.id','company.name','company.employee_of_the_month',
   'department.id','department.name','employee.id','employee.name'));
$acme         = $root['company'][0];

$shoe         = $acme->department[0];
$sue          = $shoe -> employee[0];

$it           = $acme->createDataObject('department');
$it->name     = 'IT';
$it->location = 'G-block';
$billy        = $it->createDataObject('employee');
$billy->name  = 'Billy';

$acme->name   = 'MegaCorp';
$shoe->name   = 'Footwear';
$sue->name    = 'Susan';

$acme->employee_of_the_month = $billy;
$das -> applyChanges($dbh, $root);
echo "Wrote back company with extra department and employee and all the names changed (Megacorp/Footwear/Susan)\n";

?>

Example #3 One company, two departments, two employees - Retrieve and delete

The company is retrieved as a complete data graph containing five data objects - the company, two departments and two employees. They are all deleted by deleting the company object. Deleting an object from the graph deletes all the object beneath it in the graph. Five SQL DELETE statements will be generated and executed. As always they will be qualified with a WHERE clause that contains all of the fields that were retrieved, so that any updates to the data in the database in the meantime by another process will be detected.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/*************************************************************************************
* Now read it one more time and delete it.
* You can delete part, apply the changes, then carry on working with the same graph but
* care is needed to keep closure - you cannot delete the employee who is eotm without
* reassigning. For safety here we delete the company all in one go.
*************************************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_containment_metadata);
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

$root = $das->executeQuery($dbh,
  "select c.id, c.name, c.employee_of_the_month, d.id, d.name, e.id, e.name " .
  "from company c, department d, employee e " .
  "where e.dept_id = d.id and d.co_id = c.id and c.name='MegaCorp';",
   array('company.id','company.name','company.employee_of_the_month',
   'department.id','department.name','employee.id','employee.name'));
$megacorp = $root['company'][0];

unset($root['company']);
$das -> applyChanges($dbh, $root);

echo "Deleted the company, departments and employees all in one go.\n";

?>


Limitations

There are the following limitations in the current release of the Relational DAS:

  • No support for nulls. There is no support for SQL NULL type. It is not legal to assign PHP NULL to a data object property and the Relational DAS will not write that back as a NULL to the database. If nulls are found in the database on a query, the property will remain unset.

  • Only two types of SDO relationship. The metadata described below allows the Relational DAS to model just two types of SDO relationship: multi-valued containment relationships and single-valued non-containment references. In SDO, whether a property describes a single- or multi-valued relationship, and whether it is containment or non-containment, are independent. The full range of possibilities that SDO allows cannot all be defined. There may be relationships that it would be useful to model but which the current implementation cannot manage. One example is a single-valued containment relationship.

  • No support for the full range of SDO data types. The Relational DAS defines all primitive properties in the SDO model as being of type string. SDO defines a richer set of types containing various integer, float, boolean and data and time types. String is adequate for the purposes of the Relational DAS since the combination of PHP, PDO and the database will ensure that values passed as strings will be converted to the proper type before being put in the database. This does affect some scenarios in which the Relational DAS has to work with a data graph that has come from or will go to a different DAS.

  • Only one foreign key per table. The metadata only provides the means to specify one foreign key per table. This foreign key may be mapped to one of the two types of SDO relationship supported. Obviously there are some scenarios that cannot be described under this limitation - it is not possible to have two non-containment references from one table to another for example.


SDO-DAS-Relational Functions

Predefined Classes

The Relational DAS provides two classes: the Relational DAS itself and the subclass of Exception that can be thrown. The Relational DAS has four publicly useful calls: the constructor, the createRootDataObject() call to obtain the root object of an empty data graph, the executeQuery() call to obtain a data graph containing data from a relational database, and the applyChanges() call to write changes made to a data graph back to the relational database.

SDO_DAS_Relational

The only object other than an SDO_DAS_Relational_Exception with which the application is expected to interact.

Methods

  • __construct - construct the Relational DAS with a model derived from the passed metadata

  • createRootDataObject - obtain an otherwise empty data graph containing just the special root object

  • executeQuery - execute an SQL query passed as a literal string and return the results as a normalised data graph

  • executePreparedQuery - execute an SQL query passed as a prepared statement, with a list of values to substitute for placeholders, and return the results as a normalised data graph

  • applyChanges - examine the change summary in the data graph and apply those changes back to the database, subject to an assumption of optimistic concurrency

SDO_DAS_Relational_Exception

Is a subclass of PHP's Exception. It adds no behaviour to Exception. Thrown, with useful descriptive text, to signal errors in the metadata or unexpected failures to perform SQL operations.

Table of Contents

  • SDO_DAS_Relational::applyChanges — Applies the changes made to a data graph back to the database
  • SDO_DAS_Relational::__construct — Creates an instance of a Relational Data Access Service
  • SDO_DAS_Relational::createRootDataObject — Returns the special root object in an otherwise empty data graph. Used when creating a data graph from scratch
  • SDO_DAS_Relational::executePreparedQuery — Executes an SQL query passed as a prepared statement, with a list of values to substitute for placeholders, and return the results as a normalised data graph
  • SDO_DAS_Relational::executeQuery — Executes a given SQL query against a relational database and returns the results as a normalised data graph


Applies the changes made to a data graph back to the database

  • « SDO-DAS-Relational Functions
  • SDO_DAS_Relational::__construct »
  • PHP Manual
  • SDO-DAS-Relational Functions
  • Applies the changes made to a data graph back to the database

SDO_DAS_Relational::applyChanges

(^)

SDO_DAS_Relational::applyChanges — Applies the changes made to a data graph back to the database

Description

SDO_DAS_Relational::applyChanges ( PDO $database_handle , SDODataObject $root_data_object ) : void
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.

Given a PDO database handle and the special root object of a data graph, examine the change summary in the datagraph and applies the changes to the database. The changes that it can apply can be creations of data objects, deletes of data objects, and modifications to properties of data objects.

Parameters

PDO_database_handle

Constructed using the PDO extension. A typical line to construct a PDO database handle might look like this:

$dbh = new PDO("mysql:dbname=COMPANYDB;host=localhost",DATABASE_USER,DATABASE_PASSWORD);

root_data_object

The special root object which is at the top of every SDO data graph.

Return Values

None. Note however that the datagraph that was passed is still intact and usable. Furthermore, if data objects were created and written back to a table with autogenerated primary keys, then those primary keys will now be set in the data objects. If the changes were successfully written, then the change summary associated with the datagraph will have been cleared, so that it is possible to now make further changes to the data graph and apply those changes in turn. In this way it is possible to work with the same data graph and apply changes repeatedly.

Errors/Exceptions

SDO_DAS_Relational::applyChanges() can throw an SDO_DAS_Relational_Exception if it is unable to apply all the changes correctly.

The Relational DAS starts a database transaction before beginning to apply the changes and will commit the transaction only if they are all successful. The Relational DAS generates qualified update and delete statements which contain a where clause that specifies that the row to be updated or deleted must contain the same values that it did when the data was first retrieved. This is how the optimistic concurrency is implemented. If any of the qualified update or delete statements fails to update or delete their target row, it may be because the data has been altered in the database in the meantime. In any event, if any update fails for any reason, the transaction is rolled back and an exception thrown. The exception will contain the generated SQL statement that failed.

The Relational DAS also catches any PDO exceptions and obtains PDO diagnostic information which it includes in an SDO_DAS_Relational_Exception which it then throws.

Examples

Please see the Examples section in the general information about the Relational DAS for many examples of calling this method. Please see also the section on Tracing to see how you can see what SQL statements are generated by the Relational DAS.


Creates an instance of a Relational Data Access Service

  • « SDO_DAS_Relational::applyChanges
  • SDO_DAS_Relational::createRootDataObject »
  • PHP Manual
  • SDO-DAS-Relational Functions
  • Creates an instance of a Relational Data Access Service

SDO_DAS_Relational::__construct

(^)

SDO_DAS_Relational::__construct — Creates an instance of a Relational Data Access Service

Description

SDO_DAS_Relational::__construct ( array $database_metadata [, string $application_root_type [, array $SDO_containment_references_metadata ]] )
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.

Constructs an instance of a Relational Data Access Service from the passed metadata.

Parameters

database_metadata

An array containing one or more table definitions, each of which is an associative array containing the keys name, columns, PK, and optionally, FK. For a full discussion of the metadata, see the metadata section in the general information about the Relational DAS.

application_root_type

The root of each data graph is an object of a special root type and the application data objects come below that. Of the various application types in the SDO model, one has to be the application type immediately below the root of the data graph. If there is only one table in the database metadata, so the application root type can be inferred, this argument can be omitted.

SDO_containment_references_metadata

An array containing one or more definitions of a containment relation, each of which is an associative array containing the keys parent and child. The containment relations describe how the types in the model are connected to form a tree. The type specified as the application root type must be present as one of the parent types in the containment references. If the application only needs to work with one table at a time, and there are no containment relations in the model, this argument can be omitted. For a full discussion of the metadata, see the metadata section in the general information about the Relational DAS.

Return Values

Returns an SDO_DAS_Relational object on success.

Errors/Exceptions

SDO_DAS_Relational::__construct() throws a SDO_DAS_Relational_Exception if any problems are found in the metadata.

Examples

For a full discussion of the metadata, see the metadata section in the general information about the Relational DAS.


Returns the special root object in an otherwise empty data graph. Used when creating a data graph from scratch

  • « SDO_DAS_Relational::__construct
  • SDO_DAS_Relational::executePreparedQuery »
  • PHP Manual
  • SDO-DAS-Relational Functions
  • Returns the special root object in an otherwise empty data graph. Used when creating a data graph from scratch

SDO_DAS_Relational::createRootDataObject

(^)

SDO_DAS_Relational::createRootDataObject — Returns the special root object in an otherwise empty data graph. Used when creating a data graph from scratch

Description

SDO_DAS_Relational::createRootDataObject ( void ) : SDODataObject
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.

Returns the special root object at the top of an otherwise empty data graph. This call is used when the application wants to create a data graph from scratch, without having called executeQuery() to create a data graph.

The special root object has one multi-valued containment property, with a name of the application root type that was passed when the Relational DAS was constructed. The property can take values of only that type. The only thing that the application can usefully do with the root type is to call createDataObject() on it, passing the name of the application root type, in order to create a data object of their own application type.

Parameters

None.

Return Values

The root object.

Errors/Exceptions

None.

Examples

Please see the Examples section in the general information about the Relational DAS for many examples of calling this method.


Executes an SQL query passed as a prepared statement, with a list of values to substitute for placeholders, and return the results as a normalised data graph

  • « SDO_DAS_Relational::createRootDataObject
  • SDO_DAS_Relational::executeQuery »
  • PHP Manual
  • SDO-DAS-Relational Functions
  • Executes an SQL query passed as a prepared statement, with a list of values to substitute for placeholders, and return the results as a normalised data graph

SDO_DAS_Relational::executePreparedQuery

(^)

SDO_DAS_Relational::executePreparedQuery — Executes an SQL query passed as a prepared statement, with a list of values to substitute for placeholders, and return the results as a normalised data graph

Description

SDO_DAS_Relational::executePreparedQuery ( PDO $database_handle , PDOStatement $prepared_statement , array $value_list [, array $column_specifier ] ) : SDODataObject
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.

Executes a given query against the relational database, using the supplied PDO database handle. Differs from the simpler executeQuery() in that it takes a prepared statement and a list of values. This is the appropriate call to use either when the statement is to executed a number of times with different arguments, and there is therefore a performance benefit to be had from preparing the statement only once, or when the SQL statement is to contain varying values taken from a source that cannot be completely trusted. In this latter case it may be unsafe to construct the SQL statement by simply concatenating the parts of the statement together, since the values may contain pieces of SQL. To guard against this, a so-called SQL injection attack, it is safer to prepare the SQL statement with placeholders (also known as parameter markers, denoted by '?') and supply a list of the values to be substituted as a separate argument. Otherwise this function is the same as executeQuery() in that it uses the model that it built from the metadata to interpret the result set and returns a data graph.

Parameters

PDO_database_handle

Constructed using the PDO extension. A typical line to construct a PDO database handle might look like this:

$dbh = new PDO("mysql:dbname=COMPANYDB;host=localhost",DATABASE_USER,DATABASE_PASSWORD);

prepared_statement

A prepared SQL statement to be executed against the database. This will have been prepared by PDO's prepare() method.

value_list

An array of the values to be substituted into the SQL statement in place of the placeholders. In the event that there are no placeholders or parameter markers in the SQL statement then this argument can be specified as NULL or as an empty array;

column_specifier

The Relational DAS needs to examine the result set and for every column, know which table and which column of that table it came from. In some circumstances it can find this information for itself, but sometimes it cannot. In these cases a column specifier is needed, which is an array that identifies the columns. Each entry in the array is simply a string in the form table-name.column_name.

The column specifier is needed when there are duplicate column names in the database metadata, For example, in the database used within the examples, all the tables have both a id and a name column. When the Relational DAS fetches the result set from PDO it can do so with the PDO_FETCH_ASSOC attribute, which will cause the columns in the results set to be labelled with the column name, but will not distinguish duplicates. So this will only work when there are no duplicates possible in the results set.

To summarise, specify a column specifier array whenever there is any uncertainty about which column could be from which table and only omit it when every column name in the database metadata is unique.

All of the examples in the Examples use a column specifier. There is one example in the Scenarios directory of the installation that does not: that which works with just the employee table, and because it works with just one table, there can not exist duplicate column names.

Return Values

Returns a data graph. Specifically, it returns a root object of a special type. Under this root object will be the data from the result set. The root object will have a multi-valued containment property with the same name as the application root type specified on the constructor, and that property will contain one or more data objects of the application root type.

In the event that the query returns no data, the special root object will still be returned but the containment property for the application root type will be empty.

Errors/Exceptions

SDO_DAS_Relational::executePreparedQuery() can throw an SDO_DAS_Relational_Exception if it is unable to construct the data graph correctly. This can occur for a number of reasons: for example if it finds that it does not have primary keys in the result set for all the objects. It also catches any PDO exceptions and obtains PDO diagnostic information which it includes in an SDO_DAS_Relational_Exception which it then throws.

Examples

Example #1 Retrieving a data object using executePreparedQuery()

In this example a single data object is retrieved from the database - or possibly more than one if there is more than one company called 'Acme'. For each company returned, the name and id properties are echoed.

Other examples of the use of executePreparedQuery() can be found in the example code supplied in sdo/DAS/Relational/Scenarios.

<?php
require_once 'SDO/DAS/Relational.php';
require_once 'company_metadata.inc.php';

/**************************************************************
 * Construct the DAS with the metadata
 ***************************************************************/
$das = new SDO_DAS_Relational ($database_metadata,'company',$SDO_reference_metadata);

/**************************************************************
 * Get a database connection
 ***************************************************************/
$dbh = new PDO(PDO_DSN,DATABASE_USER,DATABASE_PASSWORD);

/**************************************************************
 * Issue a query to obtain a company object - possibly more if they exist
 * Use a prepared query with a placeholder.
 ***************************************************************/
$name = 'Acme';
$pdo_stmt = $dbh->prepare('select name, id from company where name=?');
$root = $das->executePreparedQuery(
    $dbh,
    $pdo_stmt,
    array($name),
    array('company.name', 'company.id'));

/**************************************************************
 * Echo name and id
 ***************************************************************/
foreach ($root['company'] as $company) {
    echo "Company obtained from the database has name = " .
    $company['name'] . " and id " . $company['id'] . "\n";
}
?>


Executes a given SQL query against a relational database and returns the results as a normalised data graph

  • « SDO_DAS_Relational::executePreparedQuery
  • SDO DAS XML »
  • PHP Manual
  • SDO-DAS-Relational Functions
  • Executes a given SQL query against a relational database and returns the results as a normalised data graph

SDO_DAS_Relational::executeQuery

(^)

SDO_DAS_Relational::executeQuery — Executes a given SQL query against a relational database and returns the results as a normalised data graph

Description

SDO_DAS_Relational::executeQuery ( PDO $database_handle , string $SQL_statement [, array $column_specifier ] ) : SDODataObject
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.

Executes a given query against the relational database, using the supplied PDO database handle. Uses the model that it built from the metadata to interpret the result set. Returns a data graph.

Parameters

PDO_database_handle

Constructed using the PDO extension. A typical line to construct a PDO database handle might look like this:

$dbh = new PDO("mysql:dbname=COMPANYDB;host=localhost",DATABASE_USER,DATABASE_PASSWORD);

SQL_statement

The SQL statement to be executed against the database.

column_specifier

The Relational DAS needs to examine the result set and for every column, know which table and which column of that table it came from. In some circumstances it can find this information for itself, but sometimes it cannot. In these cases a column specifier is needed, which is an array that identifies the columns. Each entry in the array is simply a string in the form table-name.column_name.

The column specifier is needed when there are duplicate column names in the database metadata. For example, in the database used within the examples, all the tables have both a id and a name column. When the Relational DAS fetches the result set from PDO it can do so with the PDO_FETCH_ASSOC attribute, which will cause the columns in the results set to be labelled with the column name, but will not distinguish duplicates. So this will only work when there are no duplicates possible in the results set.

To summarise, specify a column specifier array whenever there is any uncertainty about which column could be from which table and only omit it when every column name in the database metadata is unique.

All of the examples in the Examples use a column specifier. There is one example in the Scenarios directory of the installation that does not: that which works with just the employee table, and because it works with just one table, there can not exist duplicate column names.

Return Values

Returns a data graph. Specifically, it returns a root object of a special type. Under this root object will be the data from the result set. The root object will have a multi-valued containment property with the same name as the application root type specified on the constructor, and that property will contain one or more data objects of the application root type.

In the event that the query returns no data, the special root object will still be returned but the containment property for the application root type will be empty.

Errors/Exceptions

SDO_DAS_Relational::executeQuery() can throw an SDO_DAS_Relational_Exception if it is unable to construct the data graph correctly. This can occur for a number of reasons: for example if it finds that it does not have primary keys in the result set for all the objects. It also catches any PDO exceptions and obtains PDO diagnostic information which it includes in an SDO_DAS_Relational_Exception which it then throws.

Examples

Please see the Examples section in the general information about the Relational DAS for many examples of calling this method.


SDO XML Data Access Service

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
  • SDO DAS XML Functions
    • SDO_DAS_XML::addTypes — To load a second or subsequent schema file to a SDO_DAS_XML object
    • SDO_DAS_XML::create — To create SDO_DAS_XML object for a given schema file
    • SDO_DAS_XML::createDataObject — Creates SDO_DataObject for a given namespace URI and type name
    • SDO_DAS_XML::createDocument — Creates an XML Document object from scratch, without the need to load a document from a file or string
    • SDO_DAS_XML::loadFile — Returns SDO_DAS_XML_Document object for a given path to xml instance document
    • SDO_DAS_XML::loadString — Returns SDO_DAS_XML_Document for a given xml instance string
    • SDO_DAS_XML::saveFile — Saves the SDO_DAS_XML_Document object to a file
    • SDO_DAS_XML::saveString — Saves the SDO_DAS_XML_Document object to a string
    • SDO_DAS_XML_Document::getRootDataObject — Returns the root SDO_DataObject
    • SDO_DAS_XML_Document::getRootElementName — Returns root element's name
    • SDO_DAS_XML_Document::getRootElementURI — Returns root element's URI string
    • SDO_DAS_XML_Document::setEncoding — Sets the given string as encoding
    • SDO_DAS_XML_Document::setXMLDeclaration — Sets the xml declaration
    • SDO_DAS_XML_Document::setXMLVersion — Sets the given string as xml version


Introduction

In order to use the XML Data Access Service for Service Data Objects, you will need to understand some of the concepts behind SDO: the data graph, the data object, XPath and property expressions, and so on. If you are not familiar with these ideas, you might want to look first at the section on SDO.

The job of the XML DAS is to move data between the application and an XML data source, which can be either a file or a URL. SDOs are always created and maintained according to a model which defines type names and what property names each type may have. For data which is from XML, this SDO model is built from a schema file written in XML schema language (an xsd file). This schema file is usually passed to the create method when the XMLDAS is initialised. The » SDO 2.0 specification defines the mapping between XML types and SDO types. There are a number of small limitations in the PHP support - not everything which is in the specification can be done - and these limitations are summarised in a later section.


Requirements

The SDO XML Data Access Service requires PHP 5.1.0 or higher. It is packaged with the SDO extension and requires SDO to have been installed. See the SDO installation instructions for the details of how to do this.


Installation

The XML Data Access Service is packaged and installed as part of the SDO extension. Please Refer SDO installation instructions.


  • « Resource Types
  • Examples »
  • PHP Manual
  • SDO DAS XML
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


Examples

Several of the following examples are based on the letter example described in the SDO documentation. The examples assume the XML Schema for the letter is contained in a file letter.xsd and the letter instance is in the file letter.xml. These two files are reproduced here:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:letter="http://letterSchema"
  targetNamespace="http://letterSchema">
  <xsd:element name="letters" type="letter:FormLetter"/>
  <xsd:complexType name="FormLetter" mixed="true">
    <xsd:sequence>
      <xsd:element name="date" minOccurs="0" type="xsd:string"/>
      <xsd:element name="firstName" minOccurs="0" type="xsd:string"/>
      <xsd:element name="lastName" minOccurs="0" type="xsd:string"/>
    </xsd:sequence>
  </xsd:complexType>
</xsd:schema>

<letter:letters xmlns:letter="http://letterSchema">
  <date>March 1, 2005</date>
  Mutual of Omaha
  Wild Kingdom, USA
  Dear
  <firstName>Casy</firstName>
  <lastName>Crocodile</lastName>
  Please buy more shark repellent.
  Your premium is past due.
</letter:letters>

Example #1 Loading, altering, and saving an XML document

The following example shows how an XML document can be loaded from a file, altered, and written back.

<?php
/**
 * Load, update, and save an XML document
 */
try {
   $xmldas = SDO_DAS_XML::create("letter.xsd");
   $document = $xmldas->loadFile("letter.xml");
   $root_data_object = $document->getRootDataObject();
   $root_data_object->date = "September 03, 2004";
   $root_data_object->firstName = "Anantoju";
   $root_data_object->lastName = "Madhu";
   $xmldas->saveFile($document, "letter-out.xml");
   echo "New file has been written:\n";
   print file_get_contents("letter-out.xml");
} catch (SDO_Exception $e) {
   print($e->getMessage());
}
?>

An instance of the XML DAS is first obtained from the SDO_DAS_XML::create() method, which is a static method of the SDO_DAS_XML class. The location of the xsd is passed as a parameter. Once we have an instance of the XML DAS initialised with a given schema, we can use it to load the instance document using the loadFile() method. There is also a loadString() method if you want to load an XML instance document from a string. If the instance document loads successfully, you will be returned an object of type SDO_DAS_XML_Document, on which you can call the getRootDataObject() method to get the SDO data object which is the root of the SDO data graph. You can then use SDO operations to change the graph. In this example we alter the date, firstName, and lastName properties. Then we use the saveFile() method to write the changed document back to the file system. The saveFile method has an optional extra integer argument which if specified will cause the XML DAS to format the XML, using the integer as the amount to indent by at each change in level on the document.

This will write the following to letter-out.xml.

<?xml version="1.0" encoding="UTF-8"?>
<FormLetter xmlns="http://letterSchema" xsi:type="FormLetter" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <date>September 03, 2004</date>
  Mutual of Omaha
  Wild Kingdom, USA
  Dear
  <firstName>Anantoju</firstName>
  <lastName>Madhu</lastName>
  Please buy more shark repellent.
  Your premium is past due.
</FormLetter>

Example #2 Creating a new XML document

The previous example loaded the document from a file. This example shows how to create an SDO data graph in memory. In this example it is then saved to an XML string. Furthermore, because the letter contains both structured and unstructured content, it uses the Sequence API as well assignments to properties to construct the data graph.

<?php
/**
 * Create an XML document from scratch
 */
try {
   $xmldas = SDO_DAS_XML::create("letter.xsd");
   try {
       $doc = $xmldas->createDocument();
       $rdo = $doc->getRootDataObject();
       $seq = $rdo->getSequence();
       $seq->insert("April 09, 2005", NULL, 'date');
       $seq->insert("Acme Inc. ", NULL, NULL);
       $seq->insert("United Kingdom. ");
       $seq->insert("Dear", NULL, NULL);
       $seq->insert("Tarun", NULL, "firstName");
       $seq->insert("Nayaraaa", NULL, "lastName");
       $rdo->lastName = "Nayar";
       $seq->insert("Please note that your order number ");
       $seq->insert(12345);
       $seq->insert(" has been dispatched today. Thanks for your business with us.");
       print($xmldas->saveString($doc));
   } catch (SDO_Exception $e) {
       print($e);
   }
} catch (SDO_Exception $e) {
   print("Problem creating an XML document: " . $e->getMessage());
}
?>

The createDocument() method on the XML DAS returns a document object with a single root data object corresponding to an empty document element. The element name of the document element is known from the schema file. If there is any ambiguity about what the document element is, as there can be when more than one schema has been loaded into the same XML DAS, the element name and the namespace URI can be passed to the createDocument() method.

This will emit the following output (line breaks have been inserted for readability):

<?xml version="1.0" encoding="UTF-8"?>
<FormLetter xmlns="http://letterSchema" xsi:type="FormLetter"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<date>April 09, 2005</date>
Acme Inc. United Kingdom.
Dear
<firstName>Tarun</firstName>
<lastName>Nayar</lastName>
Please note that your order number 12345 has been
dispatched today. Thanks for your business with us.
</FormLetter>

Example #3 Setting XML document properties

This third example shows you how to set the XML version and encoding on the document object. These will be used when the XML is written out. If no XML declaration is wanted at all (perhaps you want to generate the XML as a string to embed in something) then you can use the setXMLDeclaration() method to suppress it.

<?php
/**
 * Illustrate the calls that control the XML declaration
 */
   $xmldas = SDO_DAS_XML::create("letter.xsd");
   $document = $xmldas->loadFile("letter.xml");
   $document->setXMLVersion("1.1");
   $document->setEncoding("ISO-8859-1");
   print($xmldas->saveString($document));
?>

The XML version and encoding are set in the XML declaration at the top of the XML document.

<?xml version="1.1" encoding="utf-8"?>
.../...

Example #4 Using an open type

This fourth example illustrates the use of an SDO open type and the use of the createDataObject() method. For this example we use the following two schema:

<schema
  xmlns="http://www.w3.org/2001/XMLSchema">

  <element name="jungle">
    <complexType>
      <sequence>
        <any minOccurs="0" maxOccurs="unbounded"/>
      </sequence>
    </complexType>
  </element>

</schema>

Note the presence of the any element in the definition. This first schema defines the jungle complex type as containing a sequence of any other type. The other types that the example will use are defined in a second schema file:

<schema xmlns= "http://www.w3.org/2001/XMLSchema">

   <complexType name="snakeType">
     <sequence>
       <element name= "name" type="string"/>
       <element name= "length" type="positiveInteger" />
     </sequence>
   </complexType>

   <complexType name="bearType">
     <sequence>
       <element name= "name" type="string"/>
       <element name= "weight" type="positiveInteger" />
     </sequence>
   </complexType>

   <complexType name="pantherType">
     <sequence>
       <element name= "name" type="string"/>
       <element name= "colour" type="string" />
     </sequence>
   </complexType>

</schema>

Here is the example PHP code that uses these two schema files:

<?php

/**
 * Illustrate open types and the use of the addTypes() method
 */

$xmldas = SDO_DAS_XML::create();
$xmldas->addTypes("jungle.xsd"); // this is an open type i.e. the xsd specifies it can contain "any" type
$xmldas->addTypes('animalTypes.xsd');

$baloo            = $xmldas->createDataObject('','bearType');
$baloo->name      = "Baloo";
$baloo->weight    = 800;

$bagheera         = $xmldas->createDataObject('','pantherType');
$bagheera->name   = "Bagheera";
$bagheera->colour = 'inky black';

$kaa              = $xmldas->createDataObject('','snakeType');
$kaa->name        = "Kaa";
$kaa->length      = 25;

$document         = $xmldas->createDocument();
$do               = $document->getRootDataObject();
$do->bear         = $baloo;
$do->panther      = $bagheera;
$do->snake        = $kaa;

print($xmldas->saveString($document,2));

?>

These two schema files are loaded into the XML DAS with first the create() and addTypes() methods. The createDataObject() method is used to create three separate data objects. In each case the namespaceURI and typename of the type are passed to the createDataObject() method: in this example the namespace URI is blank because no namespace is used in the schema. Once the three data objects - representing a bear, a panther and a snake - have been created, a document object is created with the createDocument() method. In this case there is no ambiguity about what the document element of the document should be - as the second schema file only defines complex types, the document element can only be the global jungle element defined in the first schema. This document will have a single root data object corresponding to an empty document element jungle. As this is an open type, properties can be added at will. When the first assignment is made to $do->bear, a property bear is added to the root data object: likewise for the next two assignments. When the document is written out by the saveString() method, the resulting document is:

<?xml version="1.0" encoding="UTF-8"?>
<jungle xsi:type="jungle" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <bear xsi:type="bearType">
    <name>Baloo</name>
    <weight>800</weight>
  </bear>
  <panther xsi:type="pantherType">
    <name>Bagheera</name>
    <colour>inky black</colour>
  </panther>
  <snake xsi:type="snakeType">
    <name>Kaa</name>
    <length>25</length>
  </snake>
</jungle>

Example #5 Finding out what you can from the document

This example is intended to illustrate how you can find the element name and namespace of the document element from the XML Document object, and the SDO type and namespace from the root data object of the XML data object, and how they relate to one another. This can be difficult to understand because there are four method calls: two can be made against the Document object, and two that can be made against any data object including the root data object. Because of the rules that define how the SDO model is derived from the XML model, when the data object concerned is the root object that represents the document object for the document, only three possible values can come back from these four method calls.

The two method calls that can be made against the document are getRootElementName() and getRootEelementURI(). These return the element name and namespace of the document element, respectively.

The two method calls that can be made against any data object are getTypeName() and getTypeNamespaceURI(). These return the SDO type name and type namespace of the data object, respectively.

Always, calling getRootElementURI() on the document object will return the same value as calling getNamespaceURI() on the root data object. Essentially, the information is all derived from the first few lines of the schema file, where there are three distinct pieces of information. For illustration, here again are the first few lines of the letter.xsd that we used above.

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlns:letter="http://letterSchema"
            targetNamespace="http://letterSchema">

  <xsd:element name="letters" type="letter:FormLetter"/>

  <xsd:complexType name="FormLetter" mixed="true">
    .../...

The three important values are:

  • letters, the name of the document element

  • FormLetter, the name of the complex type of the document element. This is also the name of the SDO type of the root data object.

  • http://letterSchema, the namespace to which the document element belongs. This is also the namespaceURI of the SDO type of the root data object.

It is part of the XML-SDO mapping rules that when the SDO model is built from the schema file, the typename and namespaceURI of the SDO types for the root element are taken from those of the complex type of the document element, where it exists. Hence in this example the typename of the root data object is FormLetter. In the event that there is no separate complex type definition for the document element, when the type is defined inline and is anonymous, the SDO type name will be the same as the element name.

The following program loads the letter document and checks the return values from each of the four calls.

<?php
/**
 * Finding out what you can about the document and document element
 * This can be quite hard to understand because there are four calls
 * Two calls are made against the document
 * Two calls are made against the root data object and its model
 * Because of the SDO-XML mapping rules and how the SDO model is derived
 * from the XML model, only three possible values can come back from these four calls.
 * Always, $document->getRootElementURI() == (type of root data object)->namespaceURI
 * Essentially, it all comes form the first few lines of the xsd:
 * <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
 *   xmlns:letter="http://letterSchema"
 *   targetNamespace="http://letterSchema">
 *   <xsd:element name="letters" type="letter:FormLetter"/>
 */

$xmldas = SDO_DAS_XML::create("letter.xsd");
$document = $xmldas->loadFile("letter.xml");
$root_do = $document->getRootDataObject();

/**
 * The "root element name" is the element name of the document element
 * in this case 'letters'
 * This matches the 'name' attribute of the document element in the xsd and matches
 * the element name from the xml
 */
echo "The document element name is " . $document->getRootElementName() . "\n";
assert($document->getRootElementName() == 'letters'); // a property of the document

/**
 * The "root element URI" is the namespace part of the element name of the document element
 * in this case 'http://letterSchema' since 'letters' is in that namespace
 * This is taken from the xsd and matches the namespace picked up from the xml
 */
echo "The document element is in the namespace " . $document->getRootElementURI() . "\n";
assert($document->getRootElementURI() == 'http://letterSchema'); // a property of the document

/**
 * The type name is taken from the SDO model
 * The XML-SDO mapping rules make this either:
 *   The name of the complexType if there is one (in this case there is)
 *   The document element name if there no complexType
 * This is taken from the xsd
 */
echo "The type name of the root data object is " . $root_do->getTypeName() . "\n";
assert($root_do->getTypeName() == 'FormLetter');

/**
 * The type's namespaceURI is taken from the SDO model
 * The XML-SDO mapping rules ensure that this will always be the same as
 * the namepace URI of the document element
 */
echo "The namespaceURI of the root data object is " . $root_do->getTypeNamespaceURI() . "\n";
assert($root_do->getTypeNamespaceURI() == 'http://letterSchema');

?>

The output from this program is as follows:

The document element name is letters
The document element is in the namespace http://letterSchema
The type name of the root data object is FormLetter
The namespaceURI of the root data object is http://letterSchema

Example #6 Printing the SDO model

The XML DAS provides a simple means to see what types and properties have been loaded. The php "print" or "echo" instruction will print out the types and properties.

<?php
/**
 * Illustrate printing out the model
 */

$xmldas = SDO_DAS_XML::create("letter.xsd");
print $xmldas;

?>

The output from this program is as follows:

object(SDO_XML_DAS)#1 {
18 types have been defined. The types and their properties are::
1. commonj.sdo:BigDecimal
2. commonj.sdo:BigInteger
3. commonj.sdo:Boolean
4. commonj.sdo:Byte
5. commonj.sdo:Bytes
6. commonj.sdo:ChangeSummary
7. commonj.sdo:Character
8. commonj.sdo:DataObject
9. commonj.sdo:Date
10. commonj.sdo:Double
11. commonj.sdo:Float
12. commonj.sdo:Integer
13. commonj.sdo:Long
14. commonj.sdo:Short
15. commonj.sdo:String
16. commonj.sdo:URI
17. http://letterSchema:FormLetter
    - date (commonj.sdo:String)
    - firstName (commonj.sdo:String)
    - lastName (commonj.sdo:String)
18. http://letterSchema:RootType
    - letters (http://letterSchema:FormLetter)


SDO DAS XML Functions

Predefined Classes

The XML DAS provides two main classes. The first is SDO_DAS_XML which is the main class used to fetch the data from the XML source and used to write the data back. The second is the SDO_DAS_XML_Document class, which represents the data in the XML document.

There are also some exception classes which can be thrown if errors are found when looking for or parsing the xsd or xml files.

SDO_DAS_XML

This is the main class of the XML DAS, which is used fetch the data from the xml source and also used to write the data back. Other than the methods to load and save xml files,

Methods

  • create This is a static method available in the SDO_DAS_XML class. Used to construct an SDO_DAS_XML object.

  • addTypes Works in much the same way as create() but used to add the contents of a second or subsequent schema file to an XML DAS that has already been created.

  • createDataObject Can be used to construct an SDO data object of a given type.

  • createDocument Can be used to construct an XML Document object from scratch.

  • loadFile Loads the xml instance document from a file. This file can be at local file system or it can be on a remote host.

  • loadString same as the above method. Loads the xml instance which is available as string.

  • saveFile save SDO_DAS_XML_Document object as a xml file.

  • saveString save SDO_DAS_XML_Document object as a xml string.

SDO_DAS_XML_Document

This class can be used to get to the name and namespace of the document element, and to get to the root data object of the document. Lastly, it can also be used to set the XML version and encoding of a document on output.

Methods

  • getRootDataObject gets the root DataObject.

  • getRootElementName gets the root DataObject's name.

  • getRootElementURI gets the root DataObject's URI.

  • setEncoding sets the encoding string with the given value.

  • setXMLDeclaraion to set/unset the xml declaration.

  • setXMLVersion sets the xml version with the given value.

SDO_DAS_XML_ParserException

Is a subclass of SDO_Exception. Thrown for any parser errors while loading the xsd/xml file.

SDO_DAS_XML_FileException

Is a subclass of SDO_Exception. Thrown by any of the methods that load data from a file, when the file cannot be found.

Limitations compared with SDO 2.0 specification

The » SDO 2.0 specification defines the mapping between XML types and SDO types. With Java SDO, this mapping is implemented by the XMLHelper. With SDO for PHP, this mapping is implemented by the XML Data Access Service. The XML DAS implements the mapping described in the SDO 2.0 specification with some restrictions. A detailed list is of the limitations is:

XML Simple Types

  1. Simple Type with sdoJava:instanceClass - no PHP equivalent provided.

  2. Simple Type with sdoJava:extendedInstanceClass - no PHP equivalent provided.

  3. Simple Type with list of itemType.

  4. Simple Type with union.

XML Complex Types

  1. Complex Type with sdo:aliasName - no PHP support for SDO Type aliases.

XSD Attribute

  1. Attribute with sdo:aliasName - no PHP support for SDO property aliases.

  2. Attribute with default value - no PHP support for SDO property defaults.

  3. Attribute with fixed value - no PHP support for SDO read-only properties or default values.

  4. Attribute referencing a DataObject with sdo:propertyType - no support for sdo:propertyType="...".

  5. Attribute with bi-directional property to a DataObject with sdo:oppositeProperty and sdo:propertyType - no PHP support for SDO opposite.

XSD Elements

  1. Element with sdo:aliasName - no PHP support for SDO property aliases.

  2. Element with substitution group.

XSD Elements with Simple Type

  1. Element of SimpleType with default - no PHP support for SDO defaults

  2. Element of SimpleType with fixed value - no PHP support for SDO read-only properties or default values.

  3. Element of SimpleType with sdo:string - no support for sdo:string="true".

  4. Element referencing a DataObject with sdo:propertyType - no support for sdo:propertyType="..."

  5. Element with bi-directional reference to a DataObject with sdo:oppositeProperty and sdo:propertyType - no PHP support for SDO opposite.

Table of Contents

  • SDO_DAS_XML::addTypes — To load a second or subsequent schema file to a SDO_DAS_XML object
  • SDO_DAS_XML::create — To create SDO_DAS_XML object for a given schema file
  • SDO_DAS_XML::createDataObject — Creates SDO_DataObject for a given namespace URI and type name
  • SDO_DAS_XML::createDocument — Creates an XML Document object from scratch, without the need to load a document from a file or string
  • SDO_DAS_XML::loadFile — Returns SDO_DAS_XML_Document object for a given path to xml instance document
  • SDO_DAS_XML::loadString — Returns SDO_DAS_XML_Document for a given xml instance string
  • SDO_DAS_XML::saveFile — Saves the SDO_DAS_XML_Document object to a file
  • SDO_DAS_XML::saveString — Saves the SDO_DAS_XML_Document object to a string
  • SDO_DAS_XML_Document::getRootDataObject — Returns the root SDO_DataObject
  • SDO_DAS_XML_Document::getRootElementName — Returns root element's name
  • SDO_DAS_XML_Document::getRootElementURI — Returns root element's URI string
  • SDO_DAS_XML_Document::setEncoding — Sets the given string as encoding
  • SDO_DAS_XML_Document::setXMLDeclaration — Sets the xml declaration
  • SDO_DAS_XML_Document::setXMLVersion — Sets the given string as xml version


To load a second or subsequent schema file to a SDO_DAS_XML object

  • « SDO DAS XML Functions
  • SDO_DAS_XML::create »
  • PHP Manual
  • SDO DAS XML Functions
  • To load a second or subsequent schema file to a SDO_DAS_XML object

SDO_DAS_XML::addTypes

(^)

SDO_DAS_XML::addTypes — To load a second or subsequent schema file to a SDO_DAS_XML object

Description

SDO_DAS_XML::addTypes ( string $xsd_file ) : void

Load a second or subsequent schema file to an XML DAS that has already been created with the static method create(). Although the file may be any valid schema file, a likely reason for using this method is to add a schema file containing definitions of extra complex types, hence the name. See Example 4 of the parent document for an example.

Parameters

xsd_file

Path to XSD Schema file.

Return Values

None if successful, otherwise throws an exception as described below.

Errors/Exceptions

SDO_TypeNotFoundException

Thrown if a type is not defined in the underlying model.

SDO_DAS_XML_ParserException

Thrown for any problems while parsing the given XSD File.

SDO_DAS_XML_FileException

Thrown if the specified file cannot be found.


To create SDO_DAS_XML object for a given schema file

  • « SDO_DAS_XML::addTypes
  • SDO_DAS_XML::createDataObject »
  • PHP Manual
  • SDO DAS XML Functions
  • To create SDO_DAS_XML object for a given schema file

SDO_DAS_XML::create

(^)

SDO_DAS_XML::create — To create SDO_DAS_XML object for a given schema file

Description

SDO_DAS_XML::create ([ mixed $xsd_file [, string $key ]] ) : SDO_DAS_XML

This is the only static method of SDO_DAS_XML class. Used to instantiate SDO_DAS_XML object.

Parameters

xsd_file

Path to XSD Schema file. This is optional. If omitted a DAS will be created that only has the SDO base types defined. Schema files can then be loaded with the addTypes() method. Can be string or array of values.

key

Return Values

Returns SDO_DAS_XML object on success otherwise throws an exception as described below.

Errors/Exceptions

SDO_TypeNotFoundException

Thrown if a type is not defined in the underlying model.

SDO_DAS_XML_ParserException

Thrown for any problems while parsing the given XSD File.

SDO_DAS_XML_FileException

Thrown if the specified file cannot be found.


Creates SDO_DataObject for a given namespace URI and type name

  • « SDO_DAS_XML::create
  • SDO_DAS_XML::createDocument »
  • PHP Manual
  • SDO DAS XML Functions
  • Creates SDO_DataObject for a given namespace URI and type name

SDO_DAS_XML::createDataObject

(^)

SDO_DAS_XML::createDataObject — Creates SDO_DataObject for a given namespace URI and type name

Description

SDO_DAS_XML::createDataObject ( string $namespace_uri , string $type_name ) : SDO_DataObject

Creates SDO_DataObject for a given namespace URI and type name. The type should be defined in the underlying model otherwise SDO_TypeNotFoundException will be thrown.

Parameters

namespace_uri

Namespace URI of the type name.

type_name

Type Name.

Return Values

Returns SDO_DataObject on success.

Errors/Exceptions

SDO_TypeNotFoundException

Thrown if a type is not defined in the underlying model.


Creates an XML Document object from scratch, without the need to load a document from a file or string

  • « SDO_DAS_XML::createDataObject
  • SDO_DAS_XML::loadFile »
  • PHP Manual
  • SDO DAS XML Functions
  • Creates an XML Document object from scratch, without the need to load a document from a file or string

SDO_DAS_XML::createDocument

(^)

SDO_DAS_XML::createDocument — Creates an XML Document object from scratch, without the need to load a document from a file or string

Description

SDO_DAS_XML::createDocument ([ string $document_element_name ] ) : SDO_DAS_XML_Document
SDO_DAS_XML::createDocument ( string $document_element_namespace_URI , string $document_element_name [, SDO_DataObject $dataobject ] ) : SDO_DAS_XML_Document

Creates an XML Document object. This will contain just one empty root element on which none of the properties will have been set. The purpose of this call is to allow an application to create an XML document from scratch without the need to load a document from a file or string. The document that is created will be as if a document had been loaded that contained just a single empty document element with no attributes set or elements within it.

createDocument() may need to be told what the document element is. This will not be necessary in simple cases. When there is no ambiguity then no parameter need be passed to the method. However it is possible to load more than one schema file into the same XML DAS and in this case there may be more than one possible document element defined: furthermore it is even possible that there are two possible document elements that differ only in the namespace. To cope with these cases it is possible to specify either the document element name, or both the document element name and namespace to the method.

Parameters

document_element_name

The name of the document element. Only needed if there is more than one possibility.

document_element_namespace_URI

The namespace part of the document element name. Only needed if there is more than one possible document element with the same name.

dataobject

Return Values

Returns an SDO_XML_DAS_Document object on success.

Errors/Exceptions

SDO_UnsupportedOperationException

Thrown if an element name or element name and namespace URI is passed, but not found in the underlying model.


Returns SDO_DAS_XML_Document object for a given path to xml instance document

  • « SDO_DAS_XML::createDocument
  • SDO_DAS_XML::loadString »
  • PHP Manual
  • SDO DAS XML Functions
  • Returns SDO_DAS_XML_Document object for a given path to xml instance document

SDO_DAS_XML::loadFile

(^)

SDO_DAS_XML::loadFile — Returns SDO_DAS_XML_Document object for a given path to xml instance document

Description

SDO_DAS_XML::loadFile ( string $xml_file ) : SDO_XMLDocument

Constructs the tree of SDO_DataObjects from the given address to xml instance document. Returns SDO_DAS_XML_Document Object. Use SDO_DAS_XML_Document::getRootDataObject method to get root data object.

Parameters

xml_file

Path to Instance document. This can be a path to a local file or it can be a URL.

Return Values

Returns SDO_DAS_XML_Document object on Success or throws exception as described.

Errors/Exceptions

SDO_TypeNotFoundException

Thrown if a type is not defined by the underlying model.

SDO_PropertyNotFoundException

Thrown if a property within a type is not defined in the underlying model.

SDO_DAS_XML_ParserException

Thrown for any problems while parsing the given XSD File.

SDO_DAS_XML_FileException

Thrown if the specified file cannot be found.


Returns SDO_DAS_XML_Document for a given xml instance string

  • « SDO_DAS_XML::loadFile
  • SDO_DAS_XML::saveFile »
  • PHP Manual
  • SDO DAS XML Functions
  • Returns SDO_DAS_XML_Document for a given xml instance string

SDO_DAS_XML::loadString

(^)

SDO_DAS_XML::loadString — Returns SDO_DAS_XML_Document for a given xml instance string

Description

SDO_DAS_XML::loadString ( string $xml_string ) : SDO_DAS_XML_Document

Constructs the tree of SDO_DataObjects from the given xml instance string. Returns SDO_DAS_XML_Document Object. Use SDO_DAS_XML_Document::getRootDataObject method to get root data object.

Parameters

xml_string

xml string.

Return Values

Returns SDO_DAS_XML_Document object on Success or throws exception as described.

Errors/Exceptions

SDO_TypeNotFoundException

Thrown if a type is not defined by the underlying model.

SDO_PropertyNotFoundException

Thrown if the a property within a type is not defined in the underlying model.

SDO_DAS_XML_ParserException

Thrown for any problems while parsing the given XSD File.


Saves the SDO_DAS_XML_Document object to a file

  • « SDO_DAS_XML::loadString
  • SDO_DAS_XML::saveString »
  • PHP Manual
  • SDO DAS XML Functions
  • Saves the SDO_DAS_XML_Document object to a file

SDO_DAS_XML::saveFile

(^)

SDO_DAS_XML::saveFile — Saves the SDO_DAS_XML_Document object to a file

Description

SDO_DAS_XML::saveFile ( SDO_XMLDocument $xdoc , string $xml_file [, int $indent ] ) : void

Saves the SDO_DAS_XML_Document object to a file.

Parameters

xdoc

SDO_DAS_XML_Document object.

xml_file

xml file.

indent

Optional argument to specify that the xml should be formatted. A non-negative integer is the amount to indent each level of the xml. So, the integer 2, for example, will indent the xml so that each contained element is two spaces further to the right than its containing element. The integer 0 will cause the xml to be completely left-aligned. The integer -1 means no formatting - the xml will come out on one long line.

Return Values

None.

Errors/Exceptions

SDO_DAS_XML_FileException

Thrown if the specified file cannot be found.


Saves the SDO_DAS_XML_Document object to a string

  • « SDO_DAS_XML::saveFile
  • SDO_DAS_XML_Document::getRootDataObject »
  • PHP Manual
  • SDO DAS XML Functions
  • Saves the SDO_DAS_XML_Document object to a string

SDO_DAS_XML::saveString

(^)

SDO_DAS_XML::saveString — Saves the SDO_DAS_XML_Document object to a string

Description

SDO_DAS_XML::saveString ( SDO_XMLDocument $xdoc [, int $indent ] ) : string

Saves the SDO_DAS_XML_Document object to string.

Parameters

xdoc

SDO_DAS_XML_Document object.

indent

Optional argument to specify that the xml should be formatted. A non-negative integer is the amount to indent each level of the xml. So, the integer 2, for example, will indent the xml so that each contained element is two spaces further to the right than its containing element. The integer 0 will cause the xml to be completely left-aligned. The integer -1 means no formatting - the xml will come out on one long line.

Return Values

xml string.


Returns the root SDO_DataObject

  • « SDO_DAS_XML::saveString
  • SDO_DAS_XML_Document::getRootElementName »
  • PHP Manual
  • SDO DAS XML Functions
  • Returns the root SDO_DataObject

SDO_DAS_XML_Document::getRootDataObject

(^)

SDO_DAS_XML_Document::getRootDataObject — Returns the root SDO_DataObject

Description

SDO_DAS_XML_Document::getRootDataObject ( void ) : SDO_DataObject

Returns the root SDO_DataObject.

Parameters

Return Values

Returns the root SDO_DataObject.


Returns root element's name

  • « SDO_DAS_XML_Document::getRootDataObject
  • SDO_DAS_XML_Document::getRootElementURI »
  • PHP Manual
  • SDO DAS XML Functions
  • Returns root element's name

SDO_DAS_XML_Document::getRootElementName

(^)

SDO_DAS_XML_Document::getRootElementName — Returns root element's name

Description

SDO_DAS_XML_Document::getRootElementName ( void ) : string

Returns root element's name.

Parameters

Return Values

Returns root element's name.


Returns root element's URI string

  • « SDO_DAS_XML_Document::getRootElementName
  • SDO_DAS_XML_Document::setEncoding »
  • PHP Manual
  • SDO DAS XML Functions
  • Returns root element's URI string

SDO_DAS_XML_Document::getRootElementURI

(^)

SDO_DAS_XML_Document::getRootElementURI — Returns root element's URI string

Description

SDO_DAS_XML_Document::getRootElementURI ( void ) : string

Returns root element's URI string.

Parameters

Return Values

Returns root element's URI string.


Sets the given string as encoding

  • « SDO_DAS_XML_Document::getRootElementURI
  • SDO_DAS_XML_Document::setXMLDeclaration »
  • PHP Manual
  • SDO DAS XML Functions
  • Sets the given string as encoding

SDO_DAS_XML_Document::setEncoding

(^)

SDO_DAS_XML_Document::setEncoding — Sets the given string as encoding

Description

SDO_DAS_XML_Document::setEncoding ( string $encoding ) : void

Sets the given string as encoding.

Parameters

encoding

Encoding string.

Return Values

None.


Sets the xml declaration

  • « SDO_DAS_XML_Document::setEncoding
  • SDO_DAS_XML_Document::setXMLVersion »
  • PHP Manual
  • SDO DAS XML Functions
  • Sets the xml declaration

SDO_DAS_XML_Document::setXMLDeclaration

(^)

SDO_DAS_XML_Document::setXMLDeclaration — Sets the xml declaration

Description

SDO_DAS_XML_Document::setXMLDeclaration ( bool $xmlDeclatation ) : void

Controls whether an XML declaration will be generated at the start of the XML document. Set to TRUE to generate the XML declaration, or FALSE to suppress it.

Parameters

xmlDeclatation

Boolean value to set the XML declaration.

Return Values

None.


Sets the given string as xml version

  • « SDO_DAS_XML_Document::setXMLDeclaration
  • SimpleXML »
  • PHP Manual
  • SDO DAS XML Functions
  • Sets the given string as xml version

SDO_DAS_XML_Document::setXMLVersion

(^)

SDO_DAS_XML_Document::setXMLVersion — Sets the given string as xml version

Description

SDO_DAS_XML_Document::setXMLVersion ( string $xmlVersion ) : void

Sets the given string as xml version.

Parameters

xmlVersion

xml version string.

Return Values

None.


SimpleXML

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Basic SimpleXML usage
    • Dealing with XML errors
  • SimpleXMLElement — The SimpleXMLElement class
    • SimpleXMLElement::addAttribute — Adds an attribute to the SimpleXML element
    • SimpleXMLElement::addChild — Adds a child element to the XML node
    • SimpleXMLElement::asXML — Return a well-formed XML string based on SimpleXML element
    • SimpleXMLElement::attributes — Identifies an element's attributes
    • SimpleXMLElement::children — Finds children of given node
    • SimpleXMLElement::__construct — Creates a new SimpleXMLElement object
    • SimpleXMLElement::count — Counts the children of an element
    • SimpleXMLElement::getDocNamespaces — Returns namespaces declared in document
    • SimpleXMLElement::getName — Gets the name of the XML element
    • SimpleXMLElement::getNamespaces — Returns namespaces used in document
    • SimpleXMLElement::registerXPathNamespace — Creates a prefix/ns context for the next XPath query
    • SimpleXMLElement::saveXML — Alias of SimpleXMLElement::asXML
    • SimpleXMLElement::__toString — Returns the string content
    • SimpleXMLElement::xpath — Runs XPath query on XML data
  • SimpleXMLIterator — The SimpleXMLIterator class
    • SimpleXMLIterator::current — Returns the current element
    • SimpleXMLIterator::getChildren — Returns the sub-elements of the current element
    • SimpleXMLIterator::hasChildren — Checks whether the current element has sub elements
    • SimpleXMLIterator::key — Return current key
    • SimpleXMLIterator::next — Move to next element
    • SimpleXMLIterator::rewind — Rewind to the first element
    • SimpleXMLIterator::valid — Check whether the current element is valid
  • SimpleXML Functions
    • simplexml_import_dom — Get a SimpleXMLElement object from a DOM node
    • simplexml_load_file — Interprets an XML file into an object
    • simplexml_load_string — Interprets a string of XML into an object


Introduction

The SimpleXML extension provides a very simple and easily usable toolset to convert XML to an object that can be processed with normal property selectors and array iterators.


Requirements

This extension requires the libxml PHP extension. This means that passing in --enable-libxml is also required, although this is implicitly accomplished because libxml is enabled by default.

The SimpleXML extension requires PHP 5.


Installation

This extension is enabled by default. It may be disabled by using the following option at compile time: --disable-simplexml

Note: Before PHP 5.1.2, --enable-simplexml is required to enable this extension.


  • « Resource Types
  • Examples »
  • PHP Manual
  • SimpleXML
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


  • « Predefined Constants
  • Basic SimpleXML usage »
  • PHP Manual
  • SimpleXML
  • Examples

Examples

Table of Contents

  • Basic SimpleXML usage
  • Dealing with XML errors


Basic SimpleXML usage

Many examples in this reference require an XML string. Instead of repeating this string in every example, we put it into a file which we include in each example. This included file is shown in the following example section. Alternatively, you could create an XML document and read it with simplexml_load_file().

Example #1 Include file example.php with XML string

<?php
$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<movies>
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#211;r</actor>
   </character>
  </characters>
  <plot>
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
</movies>
XML;
?>

The simplicity of SimpleXML appears most clearly when one extracts a string or number from a basic XML document.

Example #2 Getting <plot>

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

echo $movies->movie[0]->plot;
?>

The above example will output:

   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.

Accessing elements within an XML document that contain characters not permitted under PHP's naming convention (e.g. the hyphen) can be accomplished by encapsulating the element name within braces and the apostrophe.

Example #3 Getting <line>

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

echo $movies->movie->{'great-lines'}->line;
?>

The above example will output:

PHP solves all my web problems

Example #4 Accessing non-unique elements in SimpleXML

When multiple instances of an element exist as children of a single parent element, normal iteration techniques apply.

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

/* For each <character> node, we echo a separate <name>. */
foreach ($movies->movie->characters->character as $character) {
   echo $character->name, ' played by ', $character->actor, PHP_EOL;
}

?>

The above example will output:

Ms. Coder played by Onlivia Actora
Mr. Coder played by El ActÓr

Note:

Properties ($movies->movie in previous example) are not arrays. They are iterable and accessible objects.

Example #5 Using attributes

So far, we have only covered the work of reading element names and their values. SimpleXML can also access element attributes. Access attributes of an element just as you would elements of an array.

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

/* Access the <rating> nodes of the first movie.
 * Output the rating scale, too. */
foreach ($movies->movie[0]->rating as $rating) {
    switch((string) $rating['type']) { // Get attributes as element indices
    case 'thumbs':
        echo $rating, ' thumbs up';
        break;
    case 'stars':
        echo $rating, ' stars';
        break;
    }
}
?>

The above example will output:

7 thumbs up5 stars

Example #6 Comparing Elements and Attributes with Text

To compare an element or attribute with a string or pass it into a function that requires a string, you must cast it to a string using (string). Otherwise, PHP treats the element as an object.

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

if ((string) $movies->movie->title == 'PHP: Behind the Parser') {
    print 'My favorite movie.';
}

echo htmlentities((string) $movies->movie->title);
?>

The above example will output:

My favorite movie.PHP: Behind the Parser

Example #7 Comparing Two Elements

Two SimpleXMLElements are considered different even if they point to the same element since PHP 5.2.0.

<?php
include 'example.php';

$movies1 = new SimpleXMLElement($xmlstr);
$movies2 = new SimpleXMLElement($xmlstr);
var_dump($movies1 == $movies2); // false since PHP 5.2.0
?>

The above example will output:

bool(false)

Example #8 Using XPath

SimpleXML includes built-in XPath support. To find all <character> elements:

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

foreach ($movies->xpath('//character') as $character) {
    echo $character->name, ' played by ', $character->actor, PHP_EOL;
}
?>

'//' serves as a wildcard. To specify absolute paths, omit one of the slashes.

The above example will output:

Ms. Coder played by Onlivia Actora
Mr. Coder played by El ActÓr

Example #9 Setting values

Data in SimpleXML doesn't have to be constant. The object allows for manipulation of all of its elements.

<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);

$movies->movie[0]->characters->character[0]->name = 'Miss Coder';

echo $movies->asXML();
?>

The above example will output:

<?xml version="1.0" standalone="yes"?>
<movies>
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Miss Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#xD3;r</actor>
   </character>
  </characters>
  <plot>
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
</movies>

Example #10 Adding elements and attributes

Since PHP 5.1.3, SimpleXML has had the ability to easily add children and attributes.

<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);

$character = $movies->movie[0]->characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');

$rating = $movies->movie[0]->addChild('rating', 'PG');
$rating->addAttribute('type', 'mpaa');

echo $movies->asXML();
?>

The above example will output:

<?xml version="1.0" standalone="yes"?>
<movies>
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#xD3;r</actor>
   </character>
  <character><name>Mr. Parser</name><actor>John Doe</actor></character></characters>
  <plot>
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 <rating type="mpaa">PG</rating></movie>
</movies>

Example #11 DOM Interoperability

PHP has a mechanism to convert XML nodes between SimpleXML and DOM formats. This example shows how one might change a DOM element to SimpleXML.

<?php
$dom = new DOMDocument;
$dom->loadXML('<books><book><title>blah</title></book></books>');
if (!$dom) {
    echo 'Error while parsing the document';
    exit;
}

$books = simplexml_import_dom($dom);

echo $books->book[0]->title;
?>

The above example will output:

blah


Dealing with XML errors

Dealing with XML errors when loading documents is a very simple task. Using the libxml functionality it is possible to suppress all XML errors when loading the document and then iterate over the errors.

The libXMLError object, returned by libxml_get_errors(), contains several properties including the message, line and column (position) of the error.

Example #1 Loading broken XML string

<?php
libxml_use_internal_errors(true);
$sxe = simplexml_load_string("<?xml version='1.0'><broken><xml></broken>");
if ($sxe === false) {
    echo "Failed loading XML\n";
    foreach(libxml_get_errors() as $error) {
        echo "\t", $error->message;
    }
}
?>

The above example will output:

Failed loading XML
    Blank needed here
    parsing XML declaration: '?>' expected
    Opening and ending tag mismatch: xml line 1 and broken
    Premature end of data in tag broken line 1

See Also

  • libxml_use_internal_errors()
  • libxml_get_errors()
  • libXMLError


The SimpleXMLElement class

(PHP 5, PHP 7)

Introduction

Represents an element in an XML document.

Class synopsis

SimpleXMLElement implements Traversable {
/* Methods */
final public __construct ( string $data [, int $options = 0 [, bool $data_is_url = FALSE [, string $ns = "" [, bool $is_prefix = FALSE ]]]] )
public addAttribute ( string $name [, string $value [, string $namespace ]] ) : void
public addChild ( string $name [, string $value [, string $namespace ]] ) : SimpleXMLElement
public asXML ([ string $filename ] ) : mixed
public attributes ([ string $ns = NULL [, bool $is_prefix = FALSE ]] ) : SimpleXMLElement
public children ([ string $ns [, bool $is_prefix = FALSE ]] ) : SimpleXMLElement
public count ( void ) : int
public getDocNamespaces ([ bool $recursive = FALSE [, bool $from_root = TRUE ]] ) : array
public getName ( void ) : string
public getNamespaces ([ bool $recursive = FALSE ] ) : array
public registerXPathNamespace ( string $prefix , string $ns ) : bool
public __toString ( void ) : string
public xpath ( string $path ) : array
}

Table of Contents

  • SimpleXMLElement::addAttribute — Adds an attribute to the SimpleXML element
  • SimpleXMLElement::addChild — Adds a child element to the XML node
  • SimpleXMLElement::asXML — Return a well-formed XML string based on SimpleXML element
  • SimpleXMLElement::attributes — Identifies an element's attributes
  • SimpleXMLElement::children — Finds children of given node
  • SimpleXMLElement::__construct — Creates a new SimpleXMLElement object
  • SimpleXMLElement::count — Counts the children of an element
  • SimpleXMLElement::getDocNamespaces — Returns namespaces declared in document
  • SimpleXMLElement::getName — Gets the name of the XML element
  • SimpleXMLElement::getNamespaces — Returns namespaces used in document
  • SimpleXMLElement::registerXPathNamespace — Creates a prefix/ns context for the next XPath query
  • SimpleXMLElement::saveXML — Alias of SimpleXMLElement::asXML
  • SimpleXMLElement::__toString — Returns the string content
  • SimpleXMLElement::xpath — Runs XPath query on XML data


Adds an attribute to the SimpleXML element

  • « SimpleXMLElement
  • SimpleXMLElement::addChild »
  • PHP Manual
  • SimpleXMLElement
  • Adds an attribute to the SimpleXML element

SimpleXMLElement::addAttribute

(PHP 5 >= 5.1.3, PHP 7)

SimpleXMLElement::addAttribute — Adds an attribute to the SimpleXML element

Description

public SimpleXMLElement::addAttribute ( string $name [, string $value [, string $namespace ]] ) : void

Adds an attribute to the SimpleXML element.

Parameters

name

The name of the attribute to add.

value

The value of the attribute.

namespace

If specified, the namespace to which the attribute belongs.

Return Values

No value is returned.

Examples

Note:

Listed examples may include example.php, which refers to the XML string found in the first example of the basic usage guide.

Example #1 Add attributes and children to a SimpleXML element

<?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
$sxe->addAttribute('type', 'documentary');

$movie = $sxe->addChild('movie');
$movie->addChild('title', 'PHP2: More Parser Stories');
$movie->addChild('plot', 'This is all about the people who make it work.');

$characters = $movie->addChild('characters');
$character  = $characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');

$rating = $movie->addChild('rating', '5');
$rating->addAttribute('type', 'stars');

echo $sxe->asXML();

?>

The above example will output something similar to:

<?xml version="1.0" standalone="yes"?>
<movies type="documentary">
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#xD3;r</actor>
   </character>
  </characters>
  <plot>
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
 <movie>
  <title>PHP2: More Parser Stories</title>
  <plot>This is all about the people who make it work.</plot>
  <characters>
   <character>
    <name>Mr. Parser</name>
    <actor>John Doe</actor>
   </character>
  </characters>
  <rating type="stars">5</rating>
 </movie>
</movies>

See Also

  • SimpleXMLElement::addChild() - Adds a child element to the XML node
  • Basic SimpleXML usage


Adds a child element to the XML node

  • « SimpleXMLElement::addAttribute
  • SimpleXMLElement::asXML »
  • PHP Manual
  • SimpleXMLElement
  • Adds a child element to the XML node

SimpleXMLElement::addChild

(PHP 5 >= 5.1.3, PHP 7)

SimpleXMLElement::addChild — Adds a child element to the XML node

Description

public SimpleXMLElement::addChild ( string $name [, string $value [, string $namespace ]] ) : SimpleXMLElement

Adds a child element to the node and returns a SimpleXMLElement of the child.

Parameters

name

The name of the child element to add.

value

If specified, the value of the child element.

namespace

If specified, the namespace to which the child element belongs.

Return Values

The addChild method returns a SimpleXMLElement object representing the child added to the XML node.

Examples

Note:

Listed examples may include example.php, which refers to the XML string found in the first example of the basic usage guide.

Example #1 Add attributes and children to a SimpleXML element

<?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
$sxe->addAttribute('type', 'documentary');

$movie = $sxe->addChild('movie');
$movie->addChild('title', 'PHP2: More Parser Stories');
$movie->addChild('plot', 'This is all about the people who make it work.');

$characters = $movie->addChild('characters');
$character  = $characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');

$rating = $movie->addChild('rating', '5');
$rating->addAttribute('type', 'stars');

echo $sxe->asXML();

?>

The above example will output something similar to:

<?xml version="1.0" standalone="yes"?>
<movies type="documentary">
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#xD3;r</actor>
   </character>
  </characters>
  <plot>
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
 <movie>
  <title>PHP2: More Parser Stories</title>
  <plot>This is all about the people who make it work.</plot>
  <characters>
   <character>
    <name>Mr. Parser</name>
    <actor>John Doe</actor>
   </character>
  </characters>
  <rating type="stars">5</rating>
 </movie>
</movies>

See Also

  • SimpleXMLElement::addAttribute() - Adds an attribute to the SimpleXML element
  • Basic SimpleXML usage


Return a well-formed XML string based on SimpleXML element

  • « SimpleXMLElement::addChild
  • SimpleXMLElement::attributes »
  • PHP Manual
  • SimpleXMLElement
  • Return a well-formed XML string based on SimpleXML element

SimpleXMLElement::asXML

(PHP 5, PHP 7)

SimpleXMLElement::asXML — Return a well-formed XML string based on SimpleXML element

Description

public SimpleXMLElement::asXML ([ string $filename ] ) : mixed

The asXML method formats the parent object's data in XML version 1.0.

Parameters

filename

If specified, the function writes the data to the file rather than returning it.

Return Values

If the filename isn't specified, this function returns a string on success and FALSE on error. If the parameter is specified, it returns TRUE if the file was written successfully and FALSE otherwise.

Examples

Example #1 Get XML

<?php
$string = <<<XML
<a>
 <b>
  <c>text</c>
  <c>stuff</c>
 </b>
 <d>
  <c>code</c>
 </d>
</a>
XML;

$xml = new SimpleXMLElement($string);

echo $xml->asXML();

?>

The above example will output:

<?xml version="1.0"?>
<a>
 <b>
  <c>text</c>
  <c>stuff</c>
 </b>
 <d>
  <c>code</c>
 </d>
</a>

asXML also works on Xpath results:

Example #2 Using asXML() on SimpleXMLElement::xpath() results

<?php
// Continued from example XML above.

/* Search for <a><b><c> */
$result = $xml->xpath('/a/b/c');

foreach ($result as $node) {
    echo $node->asXML();
}
?>

The above example will output:

<c>text</c><c>stuff</c>

See Also

  • SimpleXMLElement::__toString() - Returns the string content
  • Basic SimpleXML usage


Identifies an element's attributes

  • « SimpleXMLElement::asXML
  • SimpleXMLElement::children »
  • PHP Manual
  • SimpleXMLElement
  • Identifies an element's attributes

SimpleXMLElement::attributes

(PHP 5, PHP 7)

SimpleXMLElement::attributes — Identifies an element's attributes

Description

public SimpleXMLElement::attributes ([ string $ns = NULL [, bool $is_prefix = FALSE ]] ) : SimpleXMLElement

This function provides the attributes and values defined within an xml tag.

Note: SimpleXML has made a rule of adding iterative properties to most methods. They cannot be viewed using var_dump() or anything else which can examine objects.

Parameters

ns

An optional namespace for the retrieved attributes

is_prefix

Default to FALSE

Return Values

Returns a SimpleXMLElement object that can be iterated over to loop through the attributes on the tag.

Returns NULL if called on a SimpleXMLElement object that already represents an attribute and not a tag.

Examples

Example #1 Interpret an XML string

<?php
$string = <<<XML
<a>
 <foo name="one" game="lonely">1</foo>
</a>
XML;

$xml = simplexml_load_string($string);
foreach($xml->foo[0]->attributes() as $a => $b) {
    echo $a,'="',$b,"\"\n";
}
?>

The above example will output:

name="one"
game="lonely"

See Also

  • Basic SimpleXML usage


Finds children of given node

  • « SimpleXMLElement::attributes
  • SimpleXMLElement::__construct »
  • PHP Manual
  • SimpleXMLElement
  • Finds children of given node

SimpleXMLElement::children

(PHP 5, PHP 7)

SimpleXMLElement::children — Finds children of given node

Description

public SimpleXMLElement::children ([ string $ns [, bool $is_prefix = FALSE ]] ) : SimpleXMLElement

This method finds the children of an element. The result follows normal iteration rules.

Note: SimpleXML has made a rule of adding iterative properties to most methods. They cannot be viewed using var_dump() or anything else which can examine objects.

Parameters

ns

An XML namespace.

is_prefix

If is_prefix is TRUE, ns will be regarded as a prefix. If FALSE, ns will be regarded as a namespace URL.

Return Values

Returns a SimpleXMLElement element, whether the node has children or not.

Changelog

Version | Description
5.2.0 | The optional parameter is_prefix was added.

Examples

Example #1 Traversing a children() pseudo-array

<?php
$xml = new SimpleXMLElement(
'<person>
 <child role="son">
  <child role="daughter"/>
 </child>
 <child role="daughter">
  <child role="son">
   <child role="son"/>
  </child>
 </child>
</person>');

foreach ($xml->children() as $second_gen) {
    echo ' The person begot a ' . $second_gen['role'];

    foreach ($second_gen->children() as $third_gen) {
        echo ' who begot a ' . $third_gen['role'] . ';';

        foreach ($third_gen->children() as $fourth_gen) {
            echo ' and that ' . $third_gen['role'] .
                ' begot a ' . $fourth_gen['role'];
        }
    }
}
?>

The above example will output:

The person begot a son who begot a daughter; The person
begot a daughter who begot a son; and that son begot a son

Example #2 Using namespaces

<?php
$xml = '<example xmlns:foo="my.foo.urn">
  <foo:a>Apple</foo:a>
  <foo:b>Banana</foo:b>
  <c>Cherry</c>
</example>';

$sxe = new SimpleXMLElement($xml);

$kids = $sxe->children('foo');
var_dump(count($kids));

$kids = $sxe->children('foo', TRUE);
var_dump(count($kids));

$kids = $sxe->children('my.foo.urn');
var_dump(count($kids));

$kids = $sxe->children('my.foo.urn', TRUE);
var_dump(count($kids));

$kids = $sxe->children();
var_dump(count($kids));
?>
int(0)
int(2)
int(2)
int(0)
int(1)

Notes

SimpleXMLElement::children() returns a node object no matter if the current node has children or not. Use count() on the return value to see if there are any children. As of PHP 5.3.0, SimpleXMLElement::count() may be used instead.

See Also

  • SimpleXMLElement::count() - Counts the children of an element
  • count() - Count all elements in an array, or something in an object


Creates a new SimpleXMLElement object

  • « SimpleXMLElement::children
  • SimpleXMLElement::count »
  • PHP Manual
  • SimpleXMLElement
  • Creates a new SimpleXMLElement object

SimpleXMLElement::__construct

(PHP 5, PHP 7)

SimpleXMLElement::__construct — Creates a new SimpleXMLElement object

Description

final public SimpleXMLElement::__construct ( string $data [, int $options = 0 [, bool $data_is_url = FALSE [, string $ns = "" [, bool $is_prefix = FALSE ]]]] )

Creates a new SimpleXMLElement object.

Parameters

data

A well-formed XML string or the path or URL to an XML document if data_is_url is TRUE.

options

Optionally used to specify additional Libxml parameters.

Note:

It may be necessary to pass LIBXML_PARSEHUGE to be able to process deeply nested XML or very large text nodes.

data_is_url

By default, data_is_url is FALSE. Use TRUE to specify that data is a path or URL to an XML document instead of string data.

ns

Namespace prefix or URI.

is_prefix

TRUE if ns is a prefix, FALSE if it's a URI; defaults to FALSE.

Return Values

Returns a SimpleXMLElement object representing data.

Errors/Exceptions

Produces an E_WARNING error message for each error found in the XML data and additionally throws an Exception if the XML data could not be parsed.

Tip

Use libxml_use_internal_errors() to suppress all XML errors, and libxml_get_errors() to iterate over them afterwards.

Examples

Note:

Listed examples may include example.php, which refers to the XML string found in the first example of the basic usage guide.

Example #1 Create a SimpleXMLElement object

<?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
echo $sxe->movie[0]->title;

?>

The above example will output:

PHP: Behind the Parser

Example #2 Create a SimpleXMLElement object from a URL

<?php

$sxe = new SimpleXMLElement('http://example.org/document.xml', NULL, TRUE);
echo $sxe->asXML();

?>

Changelog

Version | Description
5.2.0 | Added the ns and is_prefix parameters.
5.1.2 | Added the options and data_is_url parameters.

See Also

  • Basic SimpleXML usage
  • simplexml_load_string() - Interprets a string of XML into an object
  • simplexml_load_file() - Interprets an XML file into an object
  • Dealing with XML errors
  • libxml_use_internal_errors() - Disable libxml errors and allow user to fetch error information as needed


Counts the children of an element

  • « SimpleXMLElement::__construct
  • SimpleXMLElement::getDocNamespaces »
  • PHP Manual
  • SimpleXMLElement
  • Counts the children of an element

SimpleXMLElement::count

(PHP 5 >= 5.3.0, PHP 7)

SimpleXMLElement::count — Counts the children of an element

Description

public SimpleXMLElement::count ( void ) : int

This method counts the number of children of an element.

Return Values

Returns the number of elements of an element.

Examples

Example #1 Counting the number of children

<?php
$xml = <<<EOF
<people>
 <person name="Person 1">
  <child/>
  <child/>
  <child/>
 </person>
 <person name="Person 2">
  <child/>
  <child/>
  <child/>
  <child/>
  <child/>
 </person>
</people>
EOF;

$elem = new SimpleXMLElement($xml);

foreach ($elem as $person) {
    printf("%s has got %d children.\n", $person['name'], $person->count());
}
?>

The above example will output:

Person 1 has got 3 children.
Person 2 has got 5 children.

See Also

  • SimpleXMLElement::children() - Finds children of given node


Returns namespaces declared in document

  • « SimpleXMLElement::count
  • SimpleXMLElement::getName »
  • PHP Manual
  • SimpleXMLElement
  • Returns namespaces declared in document

SimpleXMLElement::getDocNamespaces

(PHP 5 >= 5.1.2, PHP 7)

SimpleXMLElement::getDocNamespaces — Returns namespaces declared in document

Description

public SimpleXMLElement::getDocNamespaces ([ bool $recursive = FALSE [, bool $from_root = TRUE ]] ) : array

Returns namespaces declared in document

Parameters

recursive

If specified, returns all namespaces declared in parent and child nodes. Otherwise, returns only namespaces declared in root node.

from_root

Allows you to recursively check namespaces under a child node instead of from the root of the XML doc.

Return Values

The getDocNamespaces method returns an array of namespace names with their associated URIs.

Examples

Example #1 Get document namespaces

<?php

$xml = <<<XML
<?xml version="1.0" standalone="yes"?>
<people xmlns:p="http://example.org/ns">
    <p:person id="1">John Doe</p:person>
    <p:person id="2">Susie Q. Public</p:person>
</people>
XML;

$sxe = new SimpleXMLElement($xml);

$namespaces = $sxe->getDocNamespaces();
var_dump($namespaces);

?>

The above example will output:

array(1) {
   ["p"]=>
   string(21) "http://example.org/ns"
}

Example #2 Working with multiple namespaces

<?php

$xml = <<<XML
<?xml version="1.0" standalone="yes"?>
<people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">
    <p:person t:id="1">John Doe</p:person>
    <p:person t:id="2" a:addr="123 Street" xmlns:a="http://example.org/addr">
        Susie Q. Public
    </p:person>
</people>
XML;

$sxe = new SimpleXMLElement($xml);

$namespaces = $sxe->getDocNamespaces(TRUE);
var_dump($namespaces);

?>

The above example will output:

array(3) {
  ["p"]=>
  string(21) "http://example.org/ns"
  ["t"]=>
  string(23) "http://example.org/test"
  ["a"]=>
  string(23) "http://example.org/addr"
}

Changelog

Version | Description
5.4.0 | Added from_root parameter.

See Also

  • SimpleXMLElement::getNamespaces() - Returns namespaces used in document
  • SimpleXMLElement::registerXPathNamespace() - Creates a prefix/ns context for the next XPath query


Gets the name of the XML element

  • « SimpleXMLElement::getDocNamespaces
  • SimpleXMLElement::getNamespaces »
  • PHP Manual
  • SimpleXMLElement
  • Gets the name of the XML element

SimpleXMLElement::getName

(PHP 5 >= 5.1.3, PHP 7)

SimpleXMLElement::getName — Gets the name of the XML element

Description

public SimpleXMLElement::getName ( void ) : string

Gets the name of the XML element.

Return Values

The getName method returns as a string the name of the XML tag referenced by the SimpleXMLElement object.

Examples

Note:

Listed examples may include example.php, which refers to the XML string found in the first example of the basic usage guide.

Example #1 Get XML element names

<?php
include 'example.php';
$sxe = new SimpleXMLElement($xmlstr);

echo $sxe->getName() . "\n";

foreach ($sxe->children() as $child)
{
    echo $child->getName() . "\n";
}

?>

The above example will output:

movies
movie


Returns namespaces used in document

  • « SimpleXMLElement::getName
  • SimpleXMLElement::registerXPathNamespace »
  • PHP Manual
  • SimpleXMLElement
  • Returns namespaces used in document

SimpleXMLElement::getNamespaces

(PHP 5 >= 5.1.2, PHP 7)

SimpleXMLElement::getNamespaces — Returns namespaces used in document

Description

public SimpleXMLElement::getNamespaces ([ bool $recursive = FALSE ] ) : array

Returns namespaces used in document

Parameters

recursive

If specified, returns all namespaces used in parent and child nodes. Otherwise, returns only namespaces used in root node.

Return Values

The getNamespaces method returns an array of namespace names with their associated URIs.

Examples

Example #1 Get document namespaces in use

<?php

$xml = <<<XML
<?xml version="1.0" standalone="yes"?>
<people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">
    <p:person id="1">John Doe</p:person>
    <p:person id="2">Susie Q. Public</p:person>
</people>
XML;

$sxe = new SimpleXMLElement($xml);

$namespaces = $sxe->getNamespaces(true);
var_dump($namespaces);

?>

The above example will output:

array(1) {
  ["p"]=>
  string(21) "http://example.org/ns"
}

See Also

  • SimpleXMLElement::getDocNamespaces() - Returns namespaces declared in document
  • SimpleXMLElement::registerXPathNamespace() - Creates a prefix/ns context for the next XPath query


Creates a prefix/ns context for the next XPath query

  • « SimpleXMLElement::getNamespaces
  • SimpleXMLElement::saveXML »
  • PHP Manual
  • SimpleXMLElement
  • Creates a prefix/ns context for the next XPath query

SimpleXMLElement::registerXPathNamespace

(PHP 5 >= 5.1.0, PHP 7)

SimpleXMLElement::registerXPathNamespace — Creates a prefix/ns context for the next XPath query

Description

public SimpleXMLElement::registerXPathNamespace ( string $prefix , string $ns ) : bool

Creates a prefix/ns context for the next XPath query. In particular, this is helpful if the provider of the given XML document alters the namespace prefixes. registerXPathNamespace will create a prefix for the associated namespace, allowing one to access nodes in that namespace without the need to change code to allow for the new prefixes dictated by the provider.

Parameters

prefix

The namespace prefix to use in the XPath query for the namespace given in ns.

ns

The namespace to use for the XPath query. This must match a namespace in use by the XML document or the XPath query using prefix will not return any results.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Setting a namespace prefix to use in an XPath query

<?php

$xml = <<<EOD
<book xmlns:chap="http://example.org/chapter-title">
    <title>My Book</title>
    <chapter id="1">
        <chap:title>Chapter 1</chap:title>
        <para>Donec velit. Nullam eget tellus vitae tortor gravida scelerisque.
            In orci lorem, cursus imperdiet, ultricies non, hendrerit et, orci.
            Nulla facilisi. Nullam velit nisl, laoreet id, condimentum ut,
            ultricies id, mauris.</para>
    </chapter>
    <chapter id="2">
        <chap:title>Chapter 2</chap:title>
        <para>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Proin
            gravida. Phasellus tincidunt massa vel urna. Proin adipiscing quam
            vitae odio. Sed dictum. Ut tincidunt lorem ac lorem. Duis eros
            tellus, pharetra id, faucibus eu, dapibus dictum, odio.</para>
    </chapter>
</book>
EOD;

$sxe = new SimpleXMLElement($xml);

$sxe->registerXPathNamespace('c', 'http://example.org/chapter-title');
$result = $sxe->xpath('//c:title');

foreach ($result as $title) {
  echo $title . "\n";
}

?>

The above example will output:

Chapter 1
Chapter 2

Notice how the XML document shown in the example sets a namespace with a prefix of chap. Imagine that this document (or another one like it) may have used a prefix of c in the past for the same namespace. Since it has changed, the XPath query will no longer return the proper results and the query will require modification. Using registerXPathNamespace avoids future modification of the query even if the provider changes the namespace prefix.

See Also

  • SimpleXMLElement::xpath() - Runs XPath query on XML data
  • SimpleXMLElement::getDocNamespaces() - Returns namespaces declared in document
  • SimpleXMLElement::getNamespaces() - Returns namespaces used in document


Alias of SimpleXMLElement::asXML

  • « SimpleXMLElement::registerXPathNamespace
  • SimpleXMLElement::__toString »
  • PHP Manual
  • SimpleXMLElement
  • Alias of SimpleXMLElement::asXML

SimpleXMLElement::saveXML

(PHP 5 >= 5.2.0, PHP 7)

SimpleXMLElement::saveXML — Alias of SimpleXMLElement::asXML()

Description

This method is an alias of: SimpleXMLElement::asXML()


Returns the string content

  • « SimpleXMLElement::saveXML
  • SimpleXMLElement::xpath »
  • PHP Manual
  • SimpleXMLElement
  • Returns the string content

SimpleXMLElement::__toString

(PHP 5 >= 5.3.0, PHP 7)

SimpleXMLElement::__toString — Returns the string content

Description

public SimpleXMLElement::__toString ( void ) : string

Returns text content that is directly in this element. Does not return text content that is inside this element's children.

Parameters

This function has no parameters.

Return Values

Returns the string content on success or an empty string on failure.

Examples

Example #1 Get string content

<?php
$xml = new SimpleXMLElement('<a>1 <b>2 </b>3</a>');
echo $xml;
?>

The above example will output:

1 3

See Also

  • SimpleXMLElement::asXML() - Return a well-formed XML string based on SimpleXML element


Runs XPath query on XML data

  • « SimpleXMLElement::__toString
  • SimpleXMLIterator »
  • PHP Manual
  • SimpleXMLElement
  • Runs XPath query on XML data

SimpleXMLElement::xpath

(PHP 5, PHP 7)

SimpleXMLElement::xpath — Runs XPath query on XML data

Description

public SimpleXMLElement::xpath ( string $path ) : array

The xpath method searches the SimpleXML node for children matching the XPath path.

Parameters

path

An XPath path

Return Values

Returns an array of SimpleXMLElement objects or FALSE in case of an error.

Examples

Example #1 Xpath

<?php
$string = <<<XML
<a>
 <b>
  <c>text</c>
  <c>stuff</c>
 </b>
 <d>
  <c>code</c>
 </d>
</a>
XML;

$xml = new SimpleXMLElement($string);

/* Search for <a><b><c> */
$result = $xml->xpath('/a/b/c');

while(list( , $node) = each($result)) {
    echo '/a/b/c: ',$node,"\n";
}

/* Relative paths also work... */
$result = $xml->xpath('b/c');

while(list( , $node) = each($result)) {
    echo 'b/c: ',$node,"\n";
}
?>

The above example will output:

/a/b/c: text
/a/b/c: stuff
b/c: text
b/c: stuff

Notice that the two results are equal.

See Also

  • SimpleXMLElement::registerXPathNamespace() - Creates a prefix/ns context for the next XPath query
  • SimpleXMLElement::getDocNamespaces() - Returns namespaces declared in document
  • SimpleXMLElement::getNamespaces() - Returns namespaces used in document
  • Basic SimpleXML usage


The SimpleXMLIterator class

(PHP 5 >= 5.1.3, PHP 7)

Introduction

The SimpleXMLIterator provides recursive iteration over all nodes of a SimpleXMLElement object.

Class synopsis

SimpleXMLIterator extends SimpleXMLElement implements RecursiveIterator , Countable {
/* Methods */
public current ( void ) : mixed
public getChildren ( void ) : SimpleXMLIterator
public hasChildren ( void ) : bool
public key ( void ) : mixed
public next ( void ) : void
public rewind ( void ) : void
public valid ( void ) : bool
/* Inherited methods */
final public SimpleXMLElement::__construct ( string $data [, int $options = 0 [, bool $data_is_url = FALSE [, string $ns = "" [, bool $is_prefix = FALSE ]]]] )
public SimpleXMLElement::addAttribute ( string $name [, string $value [, string $namespace ]] ) : void
public SimpleXMLElement::addChild ( string $name [, string $value [, string $namespace ]] ) : SimpleXMLElement
public SimpleXMLElement::asXML ([ string $filename ] ) : mixed
public SimpleXMLElement::attributes ([ string $ns = NULL [, bool $is_prefix = FALSE ]] ) : SimpleXMLElement
public SimpleXMLElement::children ([ string $ns [, bool $is_prefix = FALSE ]] ) : SimpleXMLElement
public SimpleXMLElement::count ( void ) : int
public SimpleXMLElement::getDocNamespaces ([ bool $recursive = FALSE [, bool $from_root = TRUE ]] ) : array
public SimpleXMLElement::getName ( void ) : string
public SimpleXMLElement::getNamespaces ([ bool $recursive = FALSE ] ) : array
public SimpleXMLElement::registerXPathNamespace ( string $prefix , string $ns ) : bool
public SimpleXMLElement::__toString ( void ) : string
public SimpleXMLElement::xpath ( string $path ) : array
}

Table of Contents

  • SimpleXMLIterator::current — Returns the current element
  • SimpleXMLIterator::getChildren — Returns the sub-elements of the current element
  • SimpleXMLIterator::hasChildren — Checks whether the current element has sub elements
  • SimpleXMLIterator::key — Return current key
  • SimpleXMLIterator::next — Move to next element
  • SimpleXMLIterator::rewind — Rewind to the first element
  • SimpleXMLIterator::valid — Check whether the current element is valid


Returns the current element

  • « SimpleXMLIterator
  • SimpleXMLIterator::getChildren »
  • PHP Manual
  • SimpleXMLIterator
  • Returns the current element

SimpleXMLIterator::current

(PHP 5, PHP 7)

SimpleXMLIterator::current — Returns the current element

Description

public SimpleXMLIterator::current ( void ) : mixed

This method returns the current element as a SimpleXMLIterator object or NULL.

Parameters

This function has no parameters.

Return Values

Returns the current element as a SimpleXMLIterator object or NULL on failure.

Examples

Example #1 Return the current element

<?php
$xmlIterator = new SimpleXMLIterator('<books><book>PHP basics</book><book>XML basics</book></books>');
var_dump($xmlIterator->current());

$xmlIterator->rewind(); // rewind to first element
var_dump($xmlIterator->current());
?>

The above example will output:

NULL
object(SimpleXMLIterator)#2 (1) {
  [0]=>
  string(10) "PHP basics"
}

See Also

  • SimpleXMLIterator::key() - Return current key
  • SimpleXMLIterator::next() - Move to next element
  • SimpleXMLIterator::rewind() - Rewind to the first element
  • SimpleXMLIterator::valid() - Check whether the current element is valid
  • SimpleXMLElement


Returns the sub-elements of the current element

  • « SimpleXMLIterator::current
  • SimpleXMLIterator::hasChildren »
  • PHP Manual
  • SimpleXMLIterator
  • Returns the sub-elements of the current element

SimpleXMLIterator::getChildren

(PHP 5, PHP 7)

SimpleXMLIterator::getChildren — Returns the sub-elements of the current element

Description

public SimpleXMLIterator::getChildren ( void ) : SimpleXMLIterator

This method returns a SimpleXMLIterator object containing sub-elements of the current SimpleXMLIterator element.

Parameters

This function has no parameters.

Return Values

Returns a SimpleXMLIterator object containing the sub-elements of the current element.

Examples

Example #1 Return the sub-elements of the current element

<?php
$xml = <<<XML
<books>
    <book>
        <title>PHP Basics</title>
        <author>Jim Smith</author>
    </book>
    <book>XML basics</book>
</books>
XML;

$xmlIterator = new SimpleXMLIterator($xml);
for( $xmlIterator->rewind(); $xmlIterator->valid(); $xmlIterator->next() ) {
    foreach($xmlIterator->getChildren() as $name => $data) {
    echo "The $name is '$data' from the class " . get_class($data) . "\n";
    }
}
?>

The above example will output:

The title is 'PHP Basics' from the class SimpleXMLIterator
The author is 'Jim Smith' from the class SimpleXMLIterator


Checks whether the current element has sub elements

  • « SimpleXMLIterator::getChildren
  • SimpleXMLIterator::key »
  • PHP Manual
  • SimpleXMLIterator
  • Checks whether the current element has sub elements

SimpleXMLIterator::hasChildren

(PHP 5, PHP 7)

SimpleXMLIterator::hasChildren — Checks whether the current element has sub elements

Description

public SimpleXMLIterator::hasChildren ( void ) : bool

This method checks whether the current SimpleXMLIterator element has sub-elements.

Parameters

This function has no parameters.

Return Values

TRUE if the current element has sub-elements, otherwise FALSE

Examples

Example #1 Check whether the current element has sub-elements

<?php
$xml = <<<XML
<books>
    <book>
        <title>PHP Basics</title>
        <author>Jim Smith</author>
    </book>
    <book>XML basics</book>
</books>
XML;

$xmlIterator = new SimpleXMLIterator( $xml );
for( $xmlIterator->rewind(); $xmlIterator->valid(); $xmlIterator->next() ) {
    if($xmlIterator->hasChildren()) {
        var_dump($xmlIterator->current());
    }
}
?>

The above example will output:

object(SimpleXMLIterator)#2 (2) {
  ["title"]=>
  string(10) "PHP Basics"
  ["author"]=>
  string(9) "Jim Smith"
}


Return current key

  • « SimpleXMLIterator::hasChildren
  • SimpleXMLIterator::next »
  • PHP Manual
  • SimpleXMLIterator
  • Return current key

SimpleXMLIterator::key

(PHP 5, PHP 7)

SimpleXMLIterator::key — Return current key

Description

public SimpleXMLIterator::key ( void ) : mixed

This method gets the XML tag name of the current element.

Parameters

This function has no parameters.

Return Values

Returns the XML tag name of the element referenced by the current SimpleXMLIterator object or FALSE

Examples

Example #1 Get the current XML tag key

<?php
$xmlIterator = new SimpleXMLIterator('<books><book>PHP basics</book><book>XML basics</book></books>');

echo var_dump($xmlIterator->key());
$xmlIterator->rewind(); // rewind to the first element
echo var_dump($xmlIterator->key());

?>

The above example will output:

bool(false)
string(4) "book"


Move to next element

  • « SimpleXMLIterator::key
  • SimpleXMLIterator::rewind »
  • PHP Manual
  • SimpleXMLIterator
  • Move to next element

SimpleXMLIterator::next

(PHP 5, PHP 7)

SimpleXMLIterator::next — Move to next element

Description

public SimpleXMLIterator::next ( void ) : void

This method moves the SimpleXMLIterator to the next element.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 Move to the next element

<?php
$xmlIterator = new SimpleXMLIterator('<books><book>PHP Basics</book><book>XML basics</book></books>');
$xmlIterator->rewind(); // rewind to the first element
$xmlIterator->next();

var_dump($xmlIterator->current());
?>

The above example will output:

object(SimpleXMLIterator)#2 (1) {
  [0]=>
  string(10) "XML basics"
}


Rewind to the first element

  • « SimpleXMLIterator::next
  • SimpleXMLIterator::valid »
  • PHP Manual
  • SimpleXMLIterator
  • Rewind to the first element

SimpleXMLIterator::rewind

(PHP 5, PHP 7)

SimpleXMLIterator::rewind — Rewind to the first element

Description

public SimpleXMLIterator::rewind ( void ) : void

This method rewinds the SimpleXMLIterator to the first element.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 Rewind to the first element

<?php
$xmlIterator = new SimpleXMLIterator('<books><book>PHP Basics</book><book>XML Basics</book></books>');
$xmlIterator->rewind();

var_dump($xmlIterator->current());
?>

The above example will output:

object(SimpleXMLIterator)#2 (1) {
  [0]=>
  string(10) "PHP Basics"
}


Check whether the current element is valid

  • « SimpleXMLIterator::rewind
  • SimpleXML Functions »
  • PHP Manual
  • SimpleXMLIterator
  • Check whether the current element is valid

SimpleXMLIterator::valid

(PHP 5, PHP 7)

SimpleXMLIterator::valid — Check whether the current element is valid

Description

public SimpleXMLIterator::valid ( void ) : bool

This method checks if the current element is valid after calls to SimpleXMLIterator::rewind() or SimpleXMLIterator::next().

Parameters

This function has no parameters.

Return Values

Returns TRUE if the current element is valid, otherwise FALSE

Examples

Example #1 Check whether the current element is valid

<?php
$xmlIterator = new SimpleXMLIterator('<books><book>SQL Basics</book></books>');

$xmlIterator->rewind(); // rewind to the first element
echo var_dump($xmlIterator->valid()); // bool(true)

$xmlIterator->next(); // advance to the next element
echo var_dump($xmlIterator->valid()); // bool(false) because there is only one element
?>


SimpleXML Functions

Table of Contents

  • simplexml_import_dom — Get a SimpleXMLElement object from a DOM node
  • simplexml_load_file — Interprets an XML file into an object
  • simplexml_load_string — Interprets a string of XML into an object


Get a SimpleXMLElement object from a DOM node

  • « SimpleXML Functions
  • simplexml_load_file »
  • PHP Manual
  • SimpleXML Functions
  • Get a SimpleXMLElement object from a DOM node

simplexml_import_dom

(PHP 5, PHP 7)

simplexml_import_dom — Get a SimpleXMLElement object from a DOM node

Description

simplexml_import_dom ( DOMNode $node [, string $class_name = "SimpleXMLElement" ] ) : SimpleXMLElement

This function takes a node of a DOM document and makes it into a SimpleXML node. This new object can then be used as a native SimpleXML element.

Parameters

node

A DOM Element node

class_name

You may use this optional parameter so that simplexml_import_dom() will return an object of the specified class. That class should extend the SimpleXMLElement class.

Return Values

Returns a SimpleXMLElement 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 Importing DOM

<?php
$dom = new DOMDocument;
$dom->loadXML('<books><book><title>blah</title></book></books>');
if (!$dom) {
    echo 'Error while parsing the document';
    exit;
}

$s = simplexml_import_dom($dom);

echo $s->book[0]->title;
?>

The above example will output:

blah

See Also

  • dom_import_simplexml() - Gets a DOMElement object from a SimpleXMLElement object
  • Basic SimpleXML usage


Interprets an XML file into an object

  • « simplexml_import_dom
  • simplexml_load_string »
  • PHP Manual
  • SimpleXML Functions
  • Interprets an XML file into an object

simplexml_load_file

(PHP 5, PHP 7)

simplexml_load_file — Interprets an XML file into an object

Description

simplexml_load_file ( string $filename [, string $class_name = "SimpleXMLElement" [, int $options = 0 [, string $ns = "" [, bool $is_prefix = FALSE ]]]] ) : SimpleXMLElement

Convert the well-formed XML document in the given file to an object.

Parameters

filename

Path to the XML file

Note:

Libxml 2 unescapes the URI, so if you want to pass e.g. b&c as the URI parameter a, you have to call simplexml_load_file(rawurlencode('http://example.com/?a=' . urlencode('b&c'))). Since PHP 5.1.0 you don't need to do this because PHP will do it for you.

class_name

You may use this optional parameter so that simplexml_load_file() will return an object of the specified class. That class should extend the SimpleXMLElement class.

options

Since PHP 5.1.0 and Libxml 2.6.0, you may also use the options parameter to specify additional Libxml parameters.

ns

Namespace prefix or URI.

is_prefix

TRUE if ns is a prefix, FALSE if it's a URI; defaults to FALSE.

Return Values

Returns an object of class SimpleXMLElement with properties containing the data held within the XML document, 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

Produces an E_WARNING error message for each error found in the XML data.

Tip

Use libxml_use_internal_errors() to suppress all XML errors, and libxml_get_errors() to iterate over them afterwards.

Examples

Example #1 Interpret an XML document

<?php
// The file test.xml contains an XML document with a root element
// and at least an element /[root]/title.

if (file_exists('test.xml')) {
    $xml = simplexml_load_file('test.xml');

    print_r($xml);
} else {
    exit('Failed to open test.xml.');
}
?>

This script will display, on success:

SimpleXMLElement Object
(
  [title] => Example Title
  ...
)

At this point, you can go about using $xml->title and any other elements.

See Also

  • simplexml_load_string() - Interprets a string of XML into an object
  • SimpleXMLElement::__construct() - Creates a new SimpleXMLElement object
  • Dealing with XML errors
  • libxml_use_internal_errors() - Disable libxml errors and allow user to fetch error information as needed
  • Basic SimpleXML usage


Interprets a string of XML into an object

  • « simplexml_load_file
  • WDDX »
  • PHP Manual
  • SimpleXML Functions
  • Interprets a string of XML into an object

simplexml_load_string

(PHP 5, PHP 7)

simplexml_load_string — Interprets a string of XML into an object

Description

simplexml_load_string ( string $data [, string $class_name = "SimpleXMLElement" [, int $options = 0 [, string $ns = "" [, bool $is_prefix = FALSE ]]]] ) : SimpleXMLElement

Takes a well-formed XML string and returns it as an object.

Parameters

data

A well-formed XML string

class_name

You may use this optional parameter so that simplexml_load_string() will return an object of the specified class. That class should extend the SimpleXMLElement class.

options

Since PHP 5.1.0 and Libxml 2.6.0, you may also use the options parameter to specify additional Libxml parameters.

ns

Namespace prefix or URI.

is_prefix

TRUE if ns is a prefix, FALSE if it's a URI; defaults to FALSE.

Return Values

Returns an object of class SimpleXMLElement with properties containing the data held within the xml document, 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

Produces an E_WARNING error message for each error found in the XML data.

Tip

Use libxml_use_internal_errors() to suppress all XML errors, and libxml_get_errors() to iterate over them afterwards.

Examples

Example #1 Interpret an XML string

<?php
$string = <<<XML
<?xml version='1.0'?>
<document>
 <title>Forty What?</title>
 <from>Joe</from>
 <to>Jane</to>
 <body>
  I know that's the answer -- but what's the question?
 </body>
</document>
XML;

$xml = simplexml_load_string($string);

print_r($xml);
?>

The above example will output:

SimpleXMLElement Object
(
  [title] => Forty What?
  [from] => Joe
  [to] => Jane
  [body] =>
   I know that's the answer -- but what's the question?
)

At this point, you can go about using $xml->body and such.

See Also

  • simplexml_load_file() - Interprets an XML file into an object
  • SimpleXMLElement::__construct() - Creates a new SimpleXMLElement object
  • Dealing with XML errors
  • libxml_use_internal_errors() - Disable libxml errors and allow user to fetch error information as needed
  • Basic SimpleXML usage


WDDX

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • wddx examples
  • WDDX Functions
    • wddx_add_vars — Add variables to a WDDX packet with the specified ID
    • wddx_deserialize — Unserializes a WDDX packet
    • wddx_packet_end — Ends a WDDX packet with the specified ID
    • wddx_packet_start — Starts a new WDDX packet with structure inside it
    • wddx_serialize_value — Serialize a single value into a WDDX packet
    • wddx_serialize_vars — Serialize variables into a WDDX packet


Introduction

Warning

This extension is DEPRECATED and UNBUNDLED as of PHP 7.4.0.

These functions are intended for work with » WDDX.

Warning

Do not pass untrusted user input to wddx_deserialize(). Unserialization can result in code being loaded and executed due to object instantiation and autoloading, and a malicious user may be able to exploit this. Use a safe, standard data interchange format such as JSON (via json_decode() and json_encode()) if you need to pass serialized data to the user.


Requirements

This extension requires the libxml PHP extension. This means that passing in --enable-libxml is also required, although this is implicitly accomplished because libxml is enabled by default.

In order to use WDDX, you will need to install the expat library (which comes with Apache 1.3.7 or higher).


Installation

After installing the required expat library, compile PHP with --enable-wddx , and use --with-libexpat-dir for expat.

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
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

This extension defines a WDDX packet identifier returned by wddx_packet_start().


  • « Resource Types
  • Examples »
  • PHP Manual
  • WDDX
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


  • « Predefined Constants
  • wddx examples »
  • PHP Manual
  • WDDX
  • Examples

Examples

Table of Contents

  • wddx examples


wddx examples

All the functions that serialize variables use the first element of an array to determine whether the array is to be serialized into an array or structure. If the first element has string key, then it is serialized into a structure, otherwise, into an array.

Example #1 Serializing a single value with WDDX

<?php
echo wddx_serialize_value("PHP to WDDX packet example", "PHP packet");
?>

This example will produce:

<wddxPacket version='1.0'><header comment='PHP packet'/><data>
<string>PHP to WDDX packet example</string></data></wddxPacket>

Example #2 Using incremental packets with WDDX

<?php
$pi = 3.1415926;
$packet_id = wddx_packet_start("PHP");
wddx_add_vars($packet_id, "pi");

/* Suppose $cities came from database */
$cities = array("Austin", "Novato", "Seattle");
wddx_add_vars($packet_id, "cities");

$packet = wddx_packet_end($packet_id);
echo $packet;
?>

This example will produce:

<wddxPacket version='1.0'><header comment='PHP'/><data><struct>
<var name='pi'><number>3.1415926</number></var><var name='cities'>
<array length='3'><string>Austin</string><string>Novato</string>
<string>Seattle</string></array></var></struct></data></wddxPacket>

Note:

If you want to serialize non-ASCII characters you have to convert your data to UTF-8 first (see utf8_encode() and iconv()).


WDDX Functions

Table of Contents

  • wddx_add_vars — Add variables to a WDDX packet with the specified ID
  • wddx_deserialize — Unserializes a WDDX packet
  • wddx_packet_end — Ends a WDDX packet with the specified ID
  • wddx_packet_start — Starts a new WDDX packet with structure inside it
  • wddx_serialize_value — Serialize a single value into a WDDX packet
  • wddx_serialize_vars — Serialize variables into a WDDX packet


Add variables to a WDDX packet with the specified ID

  • « WDDX Functions
  • wddx_deserialize »
  • PHP Manual
  • WDDX Functions
  • Add variables to a WDDX packet with the specified ID

wddx_add_vars

(PHP 4, PHP 5, PHP 7)

wddx_add_vars — Add variables to a WDDX packet with the specified ID

Warning

This function was REMOVED in PHP 7.4.0.

Description

wddx_add_vars ( resource $packet_id , mixed $var_name [, mixed $... ] ) : bool

Serializes the passed variables and add the result to the given packet.

Parameters

This function takes a variable number of parameters.

packet_id

A WDDX packet, returned by wddx_packet_start().

var_name

Can be either a string naming a variable or an array containing strings naming the variables or another array, etc.

...

Return Values

Returns TRUE on success or FALSE on failure.


Unserializes a WDDX packet

  • « wddx_add_vars
  • wddx_packet_end »
  • PHP Manual
  • WDDX Functions
  • Unserializes a WDDX packet

wddx_deserialize

(PHP 4, PHP 5, PHP 7)

wddx_deserialize — Unserializes a WDDX packet

Warning

This function was REMOVED in PHP 7.4.0.

Description

wddx_deserialize ( string $packet ) : mixed

Unserializes a WDDX packet.

Warning

Do not pass untrusted user input to wddx_deserialize(). Unserialization can result in code being loaded and executed due to object instantiation and autoloading, and a malicious user may be able to exploit this. Use a safe, standard data interchange format such as JSON (via json_decode() and json_encode()) if you need to pass serialized data to the user.

Parameters

packet

A WDDX packet, as a string or stream.

Return Values

Returns the deserialized value which can be a string, a number or an array. Note that structures are deserialized into associative arrays.


Ends a WDDX packet with the specified ID

  • « wddx_deserialize
  • wddx_packet_start »
  • PHP Manual
  • WDDX Functions
  • Ends a WDDX packet with the specified ID

wddx_packet_end

(PHP 4, PHP 5, PHP 7)

wddx_packet_end — Ends a WDDX packet with the specified ID

Warning

This function was REMOVED in PHP 7.4.0.

Description

wddx_packet_end ( resource $packet_id ) : string

Ends and returns the given WDDX packet.

Parameters

packet_id

A WDDX packet, returned by wddx_packet_start().

Return Values

Returns the string containing the WDDX packet.


Starts a new WDDX packet with structure inside it

  • « wddx_packet_end
  • wddx_serialize_value »
  • PHP Manual
  • WDDX Functions
  • Starts a new WDDX packet with structure inside it

wddx_packet_start

(PHP 4, PHP 5, PHP 7)

wddx_packet_start — Starts a new WDDX packet with structure inside it

Warning

This function was REMOVED in PHP 7.4.0.

Description

wddx_packet_start ([ string $comment ] ) : resource

Start a new WDDX packet for incremental addition of variables. It automatically creates a structure definition inside the packet to contain the variables.

Parameters

comment

An optional comment string.

Return Values

Returns a packet ID for use in later functions, or FALSE on error.


Serialize a single value into a WDDX packet

  • « wddx_packet_start
  • wddx_serialize_vars »
  • PHP Manual
  • WDDX Functions
  • Serialize a single value into a WDDX packet

wddx_serialize_value

(PHP 4, PHP 5, PHP 7)

wddx_serialize_value — Serialize a single value into a WDDX packet

Warning

This function was REMOVED in PHP 7.4.0.

Description

wddx_serialize_value ( mixed $var [, string $comment ] ) : string

Creates a WDDX packet from a single given value.

Parameters

var

The value to be serialized

comment

An optional comment string that appears in the packet header.

Return Values

Returns the WDDX packet, or FALSE on error.


Serialize variables into a WDDX packet

  • « wddx_serialize_value
  • XMLDiff »
  • PHP Manual
  • WDDX Functions
  • Serialize variables into a WDDX packet

wddx_serialize_vars

(PHP 4, PHP 5, PHP 7)

wddx_serialize_vars — Serialize variables into a WDDX packet

Warning

This function was REMOVED in PHP 7.4.0.

Description

wddx_serialize_vars ( mixed $var_name [, mixed $... ] ) : string

Creates a WDDX packet with a structure that contains the serialized representation of the passed variables.

Parameters

This function takes a variable number of parameters.

var_name

Can be either a string naming a variable or an array containing strings naming the variables or another array, etc.

...

Return Values

Returns the WDDX packet, or FALSE on error.

Examples

Example #1 wddx_serialize_vars() example

<?php
$a = 1;
$b = 5.5;
$c = array("blue", "orange", "violet");
$d = "colors";

$clvars = array("c", "d");
echo wddx_serialize_vars("a", "b", $clvars);
?>

The above example will output:

<wddxPacket version='1.0'><header/><data><struct><var name='a'><number>1</number></var>
<var name='b'><number>5.5</number></var><var name='c'><array length='3'>
<string>blue</string><string>orange</string><string>violet</string></array></var>
<var name='d'><string>colors</string></var></struct></data></wddxPacket>


XML diff and merge

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
  • XMLDiff\Base — The XMLDiff\Base class
    • XMLDiff\Base::__construct — Constructor
    • XMLDiff\Base::diff — Produce diff of two XML documents
    • XMLDiff\Base::merge — Produce new XML document based on diff
  • XMLDiff\DOM — The XMLDiff\DOM class
    • XMLDiff\DOM::diff — Diff two DOMDocument objects
    • XMLDiff\DOM::merge — Produce merged DOMDocument
  • XMLDiff\Memory — The XMLDiff\Memory class
    • XMLDiff\Memory::diff — Diff two XML documents
    • XMLDiff\Memory::merge — Produce merged XML document
  • XMLDiff\File — The XMLDiff\File class
    • XMLDiff\File::diff — Diff two XML files
    • XMLDiff\File::merge — Produce merged XML document


Introduction

The extension is able to produce diffs of two XML documents and then to apply the difference to the source document. The diff is a XML document containing copy/insert/delete instruction nodes in human readable format. DOMDocument objects, local files and strings in memory can be processed.


  • « Introduction
  • Requirements »
  • PHP Manual
  • XMLDiff
  • Installing/Configuring

Installing/Configuring

Table of Contents

  • Requirements
  • Installation


Requirements

libdiffmark - version 0.10 is bundled with the extension. If diffmark is available from your system packages, its usage is strongly encouraged.

libxml extension

DOM extension


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/xmldiff.

A DLL for this PECL extension is available under » http://windows.php.net/downloads/pecl/releases/xmldiff/.


The XMLDiff\Base class

(PECL xmldiff >= 0.8.0)

Introduction

Base abstract class for all the comparsion classes in the extension.

Class synopsis

XMLDiff\Base {
/* Methods */
public __construct ( string $nsname )
abstract public diff ( mixed $from , mixed $to ) : mixed
abstract public merge ( mixed $src , mixed $diff ) : mixed
}

Table of Contents

  • XMLDiff\Base::__construct — Constructor
  • XMLDiff\Base::diff — Produce diff of two XML documents
  • XMLDiff\Base::merge — Produce new XML document based on diff


Constructor

  • « XMLDiff\Base
  • XMLDiff\Base::diff »
  • PHP Manual
  • XMLDiff\Base
  • Constructor

XMLDiff\Base::__construct

(PECL xmldiff >= 0.8.0)

XMLDiff\Base::__construct — Constructor

Description

public XMLDiff\Base::__construct ( string $nsname )

Base constructor for all the worker classes in the xmldiff extension.

Parameters

nsname

Custom namespace name for the diff document. The default namespace is http://www.locus.cz/diffmark and that's enough to avoid namespace conflicts. Use this parameter if you want to change it for some reason.

Return Values


Produce diff of two XML documents

  • « XMLDiff\Base::__construct
  • XMLDiff\Base::merge »
  • PHP Manual
  • XMLDiff\Base
  • Produce diff of two XML documents

XMLDiff\Base::diff

(PECL xmldiff >= 0.8.0)

XMLDiff\Base::diff — Produce diff of two XML documents

Description

abstract public XMLDiff\Base::diff ( mixed $from , mixed $to ) : mixed

Abstract diff method to be implemented by inheriting classes.

The basic purpose of this method is to produce diff of the two documents. The param order matters and will produce different output.

Parameters

from

Source XML document.

to

Target XML document.

Return Values

Implementation dependent.


Produce new XML document based on diff

  • « XMLDiff\Base::diff
  • XMLDiff\DOM »
  • PHP Manual
  • XMLDiff\Base
  • Produce new XML document based on diff

XMLDiff\Base::merge

(PECL xmldiff >= 0.8.0)

XMLDiff\Base::merge — Produce new XML document based on diff

Description

abstract public XMLDiff\Base::merge ( mixed $src , mixed $diff ) : mixed

Abstract merge method to be implemented by inheriting classes.

Basically the method purpose is to produce a new XML document based on the diff information.

Parameters

src

Source XML document.

diff

Document produced by the diff method.

Return Values

Implementation dependent.


The XMLDiff\DOM class

(PECL xmldiff >= 0.8.0)

Introduction

Class synopsis

XMLDiff\DOM extends XMLDiff\Base {
/* Methods */
public diff ( DOMDocument $from , DOMDocument $to ) : DOMDocument
public merge ( DOMDocument $src , DOMDocument $diff ) : DOMDocument
/* Inherited methods */
public XMLDiff\Base::__construct ( string $nsname )
abstract public XMLDiff\Base::diff ( mixed $from , mixed $to ) : mixed
abstract public XMLDiff\Base::merge ( mixed $src , mixed $diff ) : mixed
}

Table of Contents

  • XMLDiff\DOM::diff — Diff two DOMDocument objects
  • XMLDiff\DOM::merge — Produce merged DOMDocument


Diff two DOMDocument objects

  • « XMLDiff\DOM
  • XMLDiff\DOM::merge »
  • PHP Manual
  • XMLDiff\DOM
  • Diff two DOMDocument objects

XMLDiff\DOM::diff

(PECL xmldiff >= 0.8.0)

XMLDiff\DOM::diff — Diff two DOMDocument objects

Description

public XMLDiff\DOM::diff ( DOMDocument $from , DOMDocument $to ) : DOMDocument

Diff two DOMDocument instances and produce the new one containing the diff information.

Parameters

from

Source DOMDocument object.

to

Target DOMDocument object.

Return Values

DOMDocument with the diff information or NULL.


Produce merged DOMDocument

  • « XMLDiff\DOM::diff
  • XMLDiff\Memory »
  • PHP Manual
  • XMLDiff\DOM
  • Produce merged DOMDocument

XMLDiff\DOM::merge

(PECL xmldiff >= 0.8.0)

XMLDiff\DOM::merge — Produce merged DOMDocument

Description

public XMLDiff\DOM::merge ( DOMDocument $src , DOMDocument $diff ) : DOMDocument

Create new DOMDocument based on the diff.

Parameters

src

Source DOMDocument object.

diff

DOMDocument object containing the diff information.

Return Values

Merged DOMDocument or NULL.


The XMLDiff\Memory class

(PECL xmldiff >= 0.8.0)

Introduction

Class synopsis

XMLDiff\Memory extends XMLDiff\Base {
/* Methods */
public diff ( string $from , string $to ) : string
public merge ( string $src , string $diff ) : string
/* Inherited methods */
public XMLDiff\Base::__construct ( string $nsname )
abstract public XMLDiff\Base::diff ( mixed $from , mixed $to ) : mixed
abstract public XMLDiff\Base::merge ( mixed $src , mixed $diff ) : mixed
}

Table of Contents

  • XMLDiff\Memory::diff — Diff two XML documents
  • XMLDiff\Memory::merge — Produce merged XML document


Diff two XML documents

  • « XMLDiff\Memory
  • XMLDiff\Memory::merge »
  • PHP Manual
  • XMLDiff\Memory
  • Diff two XML documents

XMLDiff\Memory::diff

(PECL xmldiff >= 0.8.0)

XMLDiff\Memory::diff — Diff two XML documents

Description

public XMLDiff\Memory::diff ( string $from , string $to ) : string

Diff two strings containing XML documents and produce the diff information.

Parameters

from

Source XML document.

to

Target XML document.

Return Values

String with the XML document containing the diff information or NULL.


Produce merged XML document

  • « XMLDiff\Memory::diff
  • XMLDiff\File »
  • PHP Manual
  • XMLDiff\Memory
  • Produce merged XML document

XMLDiff\Memory::merge

(PECL xmldiff >= 0.8.0)

XMLDiff\Memory::merge — Produce merged XML document

Description

public XMLDiff\Memory::merge ( string $src , string $diff ) : string

Create new XML document based on diffs and source document.

Parameters

src

Source XML document.

diff

XML document containing diff information.

Return Values

String with the new XML document or NULL.


The XMLDiff\File class

(PECL xmldiff >= 0.8.0)

Introduction

Class synopsis

XMLDiff\File extends XMLDiff\Base {
/* Methods */
public diff ( string $from , string $to ) : string
public merge ( string $src , string $diff ) : string
/* Inherited methods */
public XMLDiff\Base::__construct ( string $nsname )
abstract public XMLDiff\Base::diff ( mixed $from , mixed $to ) : mixed
abstract public XMLDiff\Base::merge ( mixed $src , mixed $diff ) : mixed
}

Table of Contents

  • XMLDiff\File::diff — Diff two XML files
  • XMLDiff\File::merge — Produce merged XML document


Diff two XML files

  • « XMLDiff\File
  • XMLDiff\File::merge »
  • PHP Manual
  • XMLDiff\File
  • Diff two XML files

XMLDiff\File::diff

(PECL xmldiff >= 0.8.0)

XMLDiff\File::diff — Diff two XML files

Description

public XMLDiff\File::diff ( string $from , string $to ) : string

Diff two local XML files and produce string with the diff information.

Parameters

from

Path to the source document.

to

Path to the target document.

Return Values

String with the XML document containing the diff information or NULL.


Produce merged XML document

  • « XMLDiff\File::diff
  • XML Parser »
  • PHP Manual
  • XMLDiff\File
  • Produce merged XML document

XMLDiff\File::merge

(PECL xmldiff >= 0.8.0)

XMLDiff\File::merge — Produce merged XML document

Description

public XMLDiff\File::merge ( string $src , string $diff ) : string

Create new XML document based on diffs and source document.

Parameters

src

Path to the source XML document.

diff

Path to the XML document with the diff information.

Return Values

String with the new XML document or NULL.


XML Parser

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Event Handlers
  • Case Folding
  • Error Codes
  • Character Encoding
  • Examples
    • XML Element Structure Example
    • XML Tag Mapping Example
    • XML External Entity Example
  • XML Parser Functions
    • utf8_decode — Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1
    • utf8_encode — Encodes an ISO-8859-1 string to UTF-8
    • xml_error_string — Get XML parser error string
    • xml_get_current_byte_index — Get current byte index for an XML parser
    • xml_get_current_column_number — Get current column number for an XML parser
    • xml_get_current_line_number — Get current line number for an XML parser
    • xml_get_error_code — Get XML parser error code
    • xml_parse_into_struct — Parse XML data into an array structure
    • xml_parse — Start parsing an XML document
    • xml_parser_create_ns — Create an XML parser with namespace support
    • xml_parser_create — Create an XML parser
    • xml_parser_free — Free an XML parser
    • xml_parser_get_option — Get options from an XML parser
    • xml_parser_set_option — Set options in an XML parser
    • xml_set_character_data_handler — Set up character data handler
    • xml_set_default_handler — Set up default handler
    • xml_set_element_handler — Set up start and end element handlers
    • xml_set_end_namespace_decl_handler — Set up end namespace declaration handler
    • xml_set_external_entity_ref_handler — Set up external entity reference handler
    • xml_set_notation_decl_handler — Set up notation declaration handler
    • xml_set_object — Use XML Parser within an object
    • xml_set_processing_instruction_handler — Set up processing instruction (PI) handler
    • xml_set_start_namespace_decl_handler — Set up start namespace declaration handler
    • xml_set_unparsed_entity_decl_handler — Set up unparsed entity declaration handler


Introduction

XML (eXtensible Markup Language) is a data format for structured document interchange on the Web. It is a standard defined by The World Wide Web consortium (W3C). Information about XML and related technologies can be found at » http://www.w3.org/XML/.

This PHP extension implements support for James Clark's expat in PHP. This toolkit lets you parse, but not validate, XML documents. It supports three source character encodings also provided by PHP: US-ASCII, ISO-8859-1 and UTF-8. UTF-16 is not supported.

This extension lets you create XML parsers and then define handlers for different XML events. Each XML parser also has a few parameters you can adjust.


Requirements

This extension requires the libxml PHP extension. This means that passing in --enable-libxml is also required, although this is implicitly accomplished because libxml is enabled by default.

This extension uses an expat compat layer by default. It can use also expat, which can be found at » http://www.jclark.com/xml/expat.html. The Makefile that comes with expat does not build a library by default, you can use this make rule for that:

libexpat.a: $(OBJS)
    ar -rc $@ $(OBJS)
    ranlib $@
A source RPM package of expat can be found at » http://sourceforge.net/projects/expat/.


Installation

This extension is enabled by default. It may be disabled by using the following option at compile time: --disable-xml

These functions are enabled by default, using the bundled expat library. You can disable XML support with --disable-xml . If you compile PHP as a module for Apache 1.3.9 or later, PHP will automatically use the bundled expat library from Apache. If you don't want to use the bundled expat library, configure PHP with --with-expat-dir=DIR , where DIR should point to the base installation directory of expat.

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.


Resource Types

The xml resource as returned by xml_parser_create() and xml_parser_create_ns() references an xml parser instance to be used with the functions provided by this extension.


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.

XML_ERROR_NONE (integer)
XML_ERROR_NO_MEMORY (integer)
XML_ERROR_SYNTAX (integer)
XML_ERROR_NO_ELEMENTS (integer)
XML_ERROR_INVALID_TOKEN (integer)
XML_ERROR_UNCLOSED_TOKEN (integer)
XML_ERROR_PARTIAL_CHAR (integer)
XML_ERROR_TAG_MISMATCH (integer)
XML_ERROR_DUPLICATE_ATTRIBUTE (integer)
XML_ERROR_JUNK_AFTER_DOC_ELEMENT (integer)
XML_ERROR_PARAM_ENTITY_REF (integer)
XML_ERROR_UNDEFINED_ENTITY (integer)
XML_ERROR_RECURSIVE_ENTITY_REF (integer)
XML_ERROR_ASYNC_ENTITY (integer)
XML_ERROR_BAD_CHAR_REF (integer)
XML_ERROR_BINARY_ENTITY_REF (integer)
XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF (integer)
XML_ERROR_MISPLACED_XML_PI (integer)
XML_ERROR_UNKNOWN_ENCODING (integer)
XML_ERROR_INCORRECT_ENCODING (integer)
XML_ERROR_UNCLOSED_CDATA_SECTION (integer)
XML_ERROR_EXTERNAL_ENTITY_HANDLING (integer)
XML_OPTION_CASE_FOLDING (integer)
XML_OPTION_TARGET_ENCODING (integer)
XML_OPTION_SKIP_TAGSTART (integer)
XML_OPTION_SKIP_WHITE (integer)
XML_SAX_IMPL (string)
Holds the SAX implementation method. Can be libxml or expat.


Event Handlers

The XML event handlers defined are:

Supported XML handlers
PHP function to set handler | Event description
xml_set_element_handler() | Element events are issued whenever the XML parser encounters start or end tags. There are separate handlers for start tags and end tags.
xml_set_character_data_handler() | Character data is roughly all the non-markup contents of XML documents, including whitespace between tags. Note that the XML parser does not add or remove any whitespace, it is up to the application (you) to decide whether whitespace is significant.
xml_set_processing_instruction_handler() | PHP programmers should be familiar with processing instructions (PIs) already. <?php ?> is a processing instruction, where php is called the "PI target". The handling of these are application-specific, except that all PI targets starting with "XML" are reserved.
xml_set_default_handler() | What goes not to another handler goes to the default handler. You will get things like the XML and document type declarations in the default handler.
xml_set_unparsed_entity_decl_handler() | This handler will be called for declaration of an unparsed (NDATA) entity.
xml_set_notation_decl_handler() | This handler is called for declaration of a notation.
xml_set_external_entity_ref_handler() | This handler is called when the XML parser finds a reference to an external parsed general entity. This can be a reference to a file or URL, for example. See the external entity example for a demonstration.
xml_set_start_namespace_decl_handler() | This handler is called for the start of a namespace declaration.
xml_set_end_namespace_decl_handler() | This handler is called for the end of a namespace declaration. Note that this event is not triggered by libXML.


Case Folding

The element handler functions may get their element names case-folded. Case-folding is defined as "a process applied to a sequence of characters, in which those identified as non-uppercase are replaced by their uppercase equivalents". In other words, when it comes to XML, case-folding simply means uppercasing.

By default, all the element names that are passed to the handler functions are case-folded. This behaviour can be queried and controlled per XML parser with the xml_parser_get_option() and xml_parser_set_option() functions, respectively.


Error Codes

The following constants are defined for XML error codes (as returned by xml_parse()):

  • XML_ERROR_NONE
  • XML_ERROR_NO_MEMORY
  • XML_ERROR_SYNTAX
  • XML_ERROR_NO_ELEMENTS
  • XML_ERROR_INVALID_TOKEN
  • XML_ERROR_UNCLOSED_TOKEN
  • XML_ERROR_PARTIAL_CHAR
  • XML_ERROR_TAG_MISMATCH
  • XML_ERROR_DUPLICATE_ATTRIBUTE
  • XML_ERROR_JUNK_AFTER_DOC_ELEMENT
  • XML_ERROR_PARAM_ENTITY_REF
  • XML_ERROR_UNDEFINED_ENTITY
  • XML_ERROR_RECURSIVE_ENTITY_REF
  • XML_ERROR_ASYNC_ENTITY
  • XML_ERROR_BAD_CHAR_REF
  • XML_ERROR_BINARY_ENTITY_REF
  • XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF
  • XML_ERROR_MISPLACED_XML_PI
  • XML_ERROR_UNKNOWN_ENCODING
  • XML_ERROR_INCORRECT_ENCODING
  • XML_ERROR_UNCLOSED_CDATA_SECTION
  • XML_ERROR_EXTERNAL_ENTITY_HANDLING


Character Encoding

PHP's XML extension supports the » Unicode character set through different character encodings. There are two types of character encodings, source encoding and target encoding. PHP's internal representation of the document is always encoded with UTF-8.

Source encoding is done when an XML document is parsed. Upon creating an XML parser, a source encoding can be specified (this encoding can not be changed later in the XML parser's lifetime). The supported source encodings are ISO-8859-1, US-ASCII and UTF-8. The former two are single-byte encodings, which means that each character is represented by a single byte. UTF-8 can encode characters composed by a variable number of bits (up to 21) in one to four bytes. The default source encoding used by PHP is ISO-8859-1.

Target encoding is done when PHP passes data to XML handler functions. When an XML parser is created, the target encoding is set to the same as the source encoding, but this may be changed at any point. The target encoding will affect character data as well as tag names and processing instruction targets.

If the XML parser encounters characters outside the range that its source encoding is capable of representing, it will return an error.

If PHP encounters characters in the parsed XML document that can not be represented in the chosen target encoding, the problem characters will be "demoted". Currently, this means that such characters are replaced by a question mark.


Examples

Table of Contents

  • XML Element Structure Example
  • XML Tag Mapping Example
  • XML External Entity Example


XML Element Structure Example

This first example displays the structure of the start elements in a document with indentation.

Example #1 Show XML Element Structure

<?php
$file = "data.xml";
$depth = array();

function startElement($parser, $name, $attrs)
{
    global $depth;

    if (!isset($depth[$parser])) {
        $depth[$parser] = 0;
    }

    for ($i = 0; $i < $depth[$parser]; $i++) {
        echo "  ";
    }
    echo "$name\n";
    $depth[$parser]++;
}

function endElement($parser, $name)
{
    global $depth;
    $depth[$parser]--;
}

$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
        die(sprintf("XML error: %s at line %d",
                    xml_error_string(xml_get_error_code($xml_parser)),
                    xml_get_current_line_number($xml_parser)));
    }
}
xml_parser_free($xml_parser);
?>


XML Tag Mapping Example

Example #1 Map XML to HTML

This example maps tags in an XML document directly to HTML tags. Elements not found in the "map array" are ignored. Of course, this example will only work with a specific XML document type.

<?php
$file = "data.xml";
$map_array = array(
    "BOLD"     => "B",
    "EMPHASIS" => "I",
    "LITERAL"  => "TT"
);

function startElement($parser, $name, $attrs)
{
    global $map_array;
    if (isset($map_array[$name])) {
        echo "<$map_array[$name]>";
    }
}

function endElement($parser, $name)
{
    global $map_array;
    if (isset($map_array[$name])) {
        echo "</$map_array[$name]>";
    }
}

function characterData($parser, $data)
{
    echo $data;
}

$xml_parser = xml_parser_create();
// use case-folding so we are sure to find the tag in $map_array
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, true);
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
        die(sprintf("XML error: %s at line %d",
                    xml_error_string(xml_get_error_code($xml_parser)),
                    xml_get_current_line_number($xml_parser)));
    }
}
xml_parser_free($xml_parser);
?>


XML External Entity Example

This example highlights XML code. It illustrates how to use an external entity reference handler to include and parse other documents, as well as how PIs can be processed, and a way of determining "trust" for PIs containing code.

XML documents that can be used for this example are found below the example (xmltest.xml and xmltest2.xml.)

Example #1 External Entity Example

<?php
$file = "xmltest.xml";

function trustedFile($file)
{
    // only trust local files owned by ourselves
    if (!preg_match("@^([a-z][a-z0-9+.-]*)\:\/\/@i", $file)
        && fileowner($file) == getmyuid()) {
            return true;
    }
    return false;
}

function startElement($parser, $name, $attribs)
{
    echo "&lt;<font color=\"#0000cc\">$name</font>";
    if (count($attribs)) {
        foreach ($attribs as $k => $v) {
            echo " <font color=\"#009900\">$k</font>=\"<font
                   color=\"#990000\">$v</font>\"";
        }
    }
    echo "&gt;";
}

function endElement($parser, $name)
{
    echo "&lt;/<font color=\"#0000cc\">$name</font>&gt;";
}

function characterData($parser, $data)
{
    echo "<b>$data</b>";
}

function PIHandler($parser, $target, $data)
{
    switch (strtolower($target)) {
        case "php":
            global $parser_file;
            // If the parsed document is "trusted", we say it is safe
            // to execute PHP code inside it.  If not, display the code
            // instead.
            if (trustedFile($parser_file[$parser])) {
                eval($data);
            } else {
                printf("Untrusted PHP code: <i>%s</i>",
                        htmlspecialchars($data));
            }
            break;
    }
}

function defaultHandler($parser, $data)
{
    if (substr($data, 0, 1) == "&" && substr($data, -1, 1) == ";") {
        printf('<font color="#aa00aa">%s</font>',
                htmlspecialchars($data));
    } else {
        printf('<font size="-1">%s</font>',
                htmlspecialchars($data));
    }
}

function externalEntityRefHandler($parser, $openEntityNames, $base, $systemId,
                                  $publicId) {
    if ($systemId) {
        if (!list($parser, $fp) = new_xml_parser($systemId)) {
            printf("Could not open entity %s at %s\n", $openEntityNames,
                   $systemId);
            return false;
        }
        while ($data = fread($fp, 4096)) {
            if (!xml_parse($parser, $data, feof($fp))) {
                printf("XML error: %s at line %d while parsing entity %s\n",
                       xml_error_string(xml_get_error_code($parser)),
                       xml_get_current_line_number($parser), $openEntityNames);
                xml_parser_free($parser);
                return false;
            }
        }
        xml_parser_free($parser);
        return true;
    }
    return false;
}

function new_xml_parser($file)
{
    global $parser_file;

    $xml_parser = xml_parser_create();
    xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 1);
    xml_set_element_handler($xml_parser, "startElement", "endElement");
    xml_set_character_data_handler($xml_parser, "characterData");
    xml_set_processing_instruction_handler($xml_parser, "PIHandler");
    xml_set_default_handler($xml_parser, "defaultHandler");
    xml_set_external_entity_ref_handler($xml_parser, "externalEntityRefHandler");

    if (!($fp = @fopen($file, "r"))) {
        return false;
    }
    if (!is_array($parser_file)) {
        settype($parser_file, "array");
    }
    $parser_file[$xml_parser] = $file;
    return array($xml_parser, $fp);
}

if (!(list($xml_parser, $fp) = new_xml_parser($file))) {
    die("could not open XML input");
}

echo "<pre>";
while ($data = fread($fp, 4096)) {
    if (!xml_parse($xml_parser, $data, feof($fp))) {
        die(sprintf("XML error: %s at line %d\n",
                    xml_error_string(xml_get_error_code($xml_parser)),
                    xml_get_current_line_number($xml_parser)));
    }
}
echo "</pre>";
echo "parse complete\n";
xml_parser_free($xml_parser);

?>

Example #2 xmltest.xml

<?xml version='1.0'?>
<!DOCTYPE chapter SYSTEM "/just/a/test.dtd" [
<!ENTITY plainEntity "FOO entity">
<!ENTITY systemEntity SYSTEM "xmltest2.xml">
]>
<chapter>
 <TITLE>Title &plainEntity;</TITLE>
 <para>
  <informaltable>
   <tgroup cols="3">
    <tbody>
     <row><entry>a1</entry><entry morerows="1">b1</entry><entry>c1</entry></row>
     <row><entry>a2</entry><entry>c2</entry></row>
     <row><entry>a3</entry><entry>b3</entry><entry>c3</entry></row>
    </tbody>
   </tgroup>
  </informaltable>
 </para>
 &systemEntity;
 <section id="about">
  <title>About this Document</title>
  <para>
   <!-- this is a comment -->
   <?php echo 'Hi!  This is PHP version ' . phpversion(); ?>
  </para>
 </section>
</chapter>

This file is included from xmltest.xml:

Example #3 xmltest2.xml

<?xml version="1.0"?>
<!DOCTYPE foo [
<!ENTITY testEnt "test entity">
]>
<foo>
   <element attrib="value"/>
   &testEnt;
   <?php echo "This is some more PHP code being executed."; ?>
</foo>


XML Parser Functions

Table of Contents

  • utf8_decode — Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1
  • utf8_encode — Encodes an ISO-8859-1 string to UTF-8
  • xml_error_string — Get XML parser error string
  • xml_get_current_byte_index — Get current byte index for an XML parser
  • xml_get_current_column_number — Get current column number for an XML parser
  • xml_get_current_line_number — Get current line number for an XML parser
  • xml_get_error_code — Get XML parser error code
  • xml_parse_into_struct — Parse XML data into an array structure
  • xml_parse — Start parsing an XML document
  • xml_parser_create_ns — Create an XML parser with namespace support
  • xml_parser_create — Create an XML parser
  • xml_parser_free — Free an XML parser
  • xml_parser_get_option — Get options from an XML parser
  • xml_parser_set_option — Set options in an XML parser
  • xml_set_character_data_handler — Set up character data handler
  • xml_set_default_handler — Set up default handler
  • xml_set_element_handler — Set up start and end element handlers
  • xml_set_end_namespace_decl_handler — Set up end namespace declaration handler
  • xml_set_external_entity_ref_handler — Set up external entity reference handler
  • xml_set_notation_decl_handler — Set up notation declaration handler
  • xml_set_object — Use XML Parser within an object
  • xml_set_processing_instruction_handler — Set up processing instruction (PI) handler
  • xml_set_start_namespace_decl_handler — Set up start namespace declaration handler
  • xml_set_unparsed_entity_decl_handler — Set up unparsed entity declaration handler


Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1

  • « XML Parser Functions
  • utf8_encode »
  • PHP Manual
  • XML Parser Functions
  • Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1

utf8_decode

(PHP 4, PHP 5, PHP 7)

utf8_decode — Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1

Description

utf8_decode ( string $data ) : string

This function converts the string data from the UTF-8 encoding to ISO-8859-1. Bytes in the string which are not valid UTF-8, and UTF-8 characters which do not exist in ISO-8859-1 (that is, characters above U+00FF) are replaced with ?.

Note:

Many web pages marked as using the ISO-8859-1 character encoding actually use the similar Windows-1252 encoding, and web browsers will interpret ISO-8859-1 web pages as Windows-1252. Windows-1252 features additional printable characters, such as the Euro sign (€) and curly quotes (“ ”), instead of certain ISO-8859-1 control characters. This function will not convert such Windows-1252 characters correctly. Use a different function if Windows-1252 conversion is required.

Parameters

data

A UTF-8 encoded string.

Return Values

Returns the ISO-8859-1 translation of data.

Changelog

Version | Description
7.2.0 | This function has been moved to the core of PHP, and therefore lifting the requirement on the XML extension for this function to be available.

See Also

  • utf8_encode() - Encodes an ISO-8859-1 string to UTF-8 - Performs the reverse conversion
  • mb_convert_encoding() - Convert character encoding - Converts between various character encodings, including UTF-8, ISO-8859-1 and Windows-1252
  • iconv() - Convert string to requested character encoding - Converts between various character encodings
  • recode_string() - Recode a string according to a recode request - Converts between various character encodings


Encodes an ISO-8859-1 string to UTF-8

  • « utf8_decode
  • xml_error_string »
  • PHP Manual
  • XML Parser Functions
  • Encodes an ISO-8859-1 string to UTF-8

utf8_encode

(PHP 4, PHP 5, PHP 7)

utf8_encode — Encodes an ISO-8859-1 string to UTF-8

Description

utf8_encode ( string $data ) : string

This function converts the string data from the ISO-8859-1 encoding to UTF-8.

Note:

Many web pages marked as using the ISO-8859-1 character encoding actually use the similar Windows-1252 encoding, and web browsers will interpret ISO-8859-1 web pages as Windows-1252. Windows-1252 features additional printable characters, such as the Euro sign (€) and curly quotes (“ ”), instead of certain ISO-8859-1 control characters. This function will not convert such Windows-1252 characters correctly. Use a different function if Windows-1252 conversion is required.

Parameters

data

An ISO-8859-1 string.

Return Values

Returns the UTF-8 translation of data.

Changelog

Version | Description
7.2.0 | This function has been moved to the core of PHP, and therefore lifting the requirement on the XML extension for this function to be available.

See Also

  • utf8_decode() - Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1 - Performs the reverse conversion
  • mb_convert_encoding() - Convert character encoding - Converts between various character encodings, including UTF-8, ISO-8859-1 and Windows-1252
  • iconv() - Convert string to requested character encoding - Converts between various character encodings
  • recode_string() - Recode a string according to a recode request - Converts between various character encodings


Get XML parser error string

  • « utf8_encode
  • xml_get_current_byte_index »
  • PHP Manual
  • XML Parser Functions
  • Get XML parser error string

xml_error_string

(PHP 4, PHP 5, PHP 7)

xml_error_string — Get XML parser error string

Description

xml_error_string ( int $code ) : string

Gets the XML parser error string associated with the given code.

Parameters

code

An error code from xml_get_error_code().

Return Values

Returns a string with a textual description of the error code, or FALSE if no description was found.

See Also

  • xml_get_error_code() - Get XML parser error code


Get current byte index for an XML parser

  • « xml_error_string
  • xml_get_current_column_number »
  • PHP Manual
  • XML Parser Functions
  • Get current byte index for an XML parser

xml_get_current_byte_index

(PHP 4, PHP 5, PHP 7)

xml_get_current_byte_index — Get current byte index for an XML parser

Description

xml_get_current_byte_index ( resource $parser ) : int

Gets the current byte index of the given XML parser.

Parameters

parser

A reference to the XML parser to get byte index from.

Return Values

This function returns FALSE if parser does not refer to a valid parser, or else it returns which byte index the parser is currently at in its data buffer (starting at 0).

Notes

Warning

This function returns byte index according to UTF-8 encoded text disregarding if input is in another encoding.

See Also

  • xml_get_current_column_number() - Get current column number for an XML parser
  • xml_get_current_line_number() - Get current line number for an XML parser


Get current column number for an XML parser

  • « xml_get_current_byte_index
  • xml_get_current_line_number »
  • PHP Manual
  • XML Parser Functions
  • Get current column number for an XML parser

xml_get_current_column_number

(PHP 4, PHP 5, PHP 7)

xml_get_current_column_number — Get current column number for an XML parser

Description

xml_get_current_column_number ( resource $parser ) : int

Gets the current column number of the given XML parser.

Parameters

parser

A reference to the XML parser to get column number from.

Return Values

This function returns FALSE if parser does not refer to a valid parser, or else it returns which column on the current line (as given by xml_get_current_line_number()) the parser is currently at.

See Also

  • xml_get_current_byte_index() - Get current byte index for an XML parser
  • xml_get_current_line_number() - Get current line number for an XML parser


Get current line number for an XML parser

  • « xml_get_current_column_number
  • xml_get_error_code »
  • PHP Manual
  • XML Parser Functions
  • Get current line number for an XML parser

xml_get_current_line_number

(PHP 4, PHP 5, PHP 7)

xml_get_current_line_number — Get current line number for an XML parser

Description

xml_get_current_line_number ( resource $parser ) : int

Gets the current line number for the given XML parser.

Parameters

parser

A reference to the XML parser to get line number from.

Return Values

This function returns FALSE if parser does not refer to a valid parser, or else it returns which line the parser is currently at in its data buffer.

See Also

  • xml_get_current_column_number() - Get current column number for an XML parser
  • xml_get_current_byte_index() - Get current byte index for an XML parser


Get XML parser error code

  • « xml_get_current_line_number
  • xml_parse_into_struct »
  • PHP Manual
  • XML Parser Functions
  • Get XML parser error code

xml_get_error_code

(PHP 4, PHP 5, PHP 7)

xml_get_error_code — Get XML parser error code

Description

xml_get_error_code ( resource $parser ) : int

Gets the XML parser error code.

Parameters

parser

A reference to the XML parser to get error code from.

Return Values

This function returns FALSE if parser does not refer to a valid parser, or else it returns one of the error codes listed in the error codes section.

See Also

  • xml_error_string() - Get XML parser error string


Parse XML data into an array structure

  • « xml_get_error_code
  • xml_parse »
  • PHP Manual
  • XML Parser Functions
  • Parse XML data into an array structure

xml_parse_into_struct

(PHP 4, PHP 5, PHP 7)

xml_parse_into_struct — Parse XML data into an array structure

Description

xml_parse_into_struct ( resource $parser , string $data , array &$values [, array &$index ] ) : int

This function parses an XML string into 2 parallel array structures, one (index) containing pointers to the location of the appropriate values in the values array. These last two parameters must be passed by reference.

Parameters

parser

A reference to the XML parser.

data

A string containing the XML data.

values

An array containing the values of the XML data

index

An array containing pointers to the location of the appropriate values in the $values.

Return Values

xml_parse_into_struct() returns 0 for failure and 1 for success. This is not the same as FALSE and TRUE, be careful with operators such as ===.

Examples

Below is an example that illustrates the internal structure of the arrays being generated by the function. We use a simple note tag embedded inside a para tag, and then we parse this and print out the structures generated:

Example #1 xml_parse_into_struct() example

<?php
$simple = "<para><note>simple note</note></para>";
$p = xml_parser_create();
xml_parse_into_struct($p, $simple, $vals, $index);
xml_parser_free($p);
echo "Index array\n";
print_r($index);
echo "\nVals array\n";
print_r($vals);
?>

When we run that code, the output will be:

Index array
Array
(
    [PARA] => Array
        (
            [0] => 0
            [1] => 2
        )

    [NOTE] => Array
        (
            [0] => 1
        )

)

Vals array
Array
(
    [0] => Array
        (
            [tag] => PARA
            [type] => open
            [level] => 1
        )

    [1] => Array
        (
            [tag] => NOTE
            [type] => complete
            [level] => 2
            [value] => simple note
        )

    [2] => Array
        (
            [tag] => PARA
            [type] => close
            [level] => 1
        )

)

Event-driven parsing (based on the expat library) can get complicated when you have an XML document that is complex. This function does not produce a DOM style object, but it generates structures amenable of being transversed in a tree fashion. Thus, we can create objects representing the data in the XML file easily. Let's consider the following XML file representing a small database of aminoacids information:

Example #2 moldb.xml - small database of molecular information

<?xml version="1.0"?>
<moldb>

  <molecule>
      <name>Alanine</name>
      <symbol>ala</symbol>
      <code>A</code>
      <type>hydrophobic</type>
  </molecule>

  <molecule>
      <name>Lysine</name>
      <symbol>lys</symbol>
      <code>K</code>
      <type>charged</type>
  </molecule>

</moldb>
And some code to parse the document and generate the appropriate objects:

Example #3 parsemoldb.php - parses moldb.xml into an array of molecular objects

<?php

class AminoAcid {
    var $name;  // aa name
    var $symbol;    // three letter symbol
    var $code;  // one letter code
    var $type;  // hydrophobic, charged or neutral

    function __construct ($aa)
    {
        foreach ($aa as $k=>$v)
            $this->$k = $aa[$k];
    }
}

function readDatabase($filename)
{
    // read the XML database of aminoacids
    $data = implode("", file($filename));
    $parser = xml_parser_create();
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($parser, $data, $values, $tags);
    xml_parser_free($parser);

    // loop through the structures
    foreach ($tags as $key=>$val) {
        if ($key == "molecule") {
            $molranges = $val;
            // each contiguous pair of array entries are the
            // lower and upper range for each molecule definition
            for ($i=0; $i < count($molranges); $i+=2) {
                $offset = $molranges[$i] + 1;
                $len = $molranges[$i + 1] - $offset;
                $tdb[] = parseMol(array_slice($values, $offset, $len));
            }
        } else {
            continue;
        }
    }
    return $tdb;
}

function parseMol($mvalues)
{
    for ($i=0; $i < count($mvalues); $i++) {
        $mol[$mvalues[$i]["tag"]] = $mvalues[$i]["value"];
    }
    return new AminoAcid($mol);
}

$db = readDatabase("moldb.xml");
echo "** Database of AminoAcid objects:\n";
print_r($db);

?>
After executing parsemoldb.php, the variable $db contains an array of AminoAcid objects, and the output of the script confirms that:
** Database of AminoAcid objects:
Array
(
    [0] => aminoacid Object
        (
            [name] => Alanine
            [symbol] => ala
            [code] => A
            [type] => hydrophobic
        )

    [1] => aminoacid Object
        (
            [name] => Lysine
            [symbol] => lys
            [code] => K
            [type] => charged
        )

)


Start parsing an XML document

  • « xml_parse_into_struct
  • xml_parser_create_ns »
  • PHP Manual
  • XML Parser Functions
  • Start parsing an XML document

xml_parse

(PHP 4, PHP 5, PHP 7)

xml_parse — Start parsing an XML document

Description

xml_parse ( resource $parser , string $data [, bool $is_final = FALSE ] ) : int

xml_parse() parses an XML document. The handlers for the configured events are called as many times as necessary.

Parameters

parser

A reference to the XML parser to use.

data

Chunk of data to parse. A document may be parsed piece-wise by calling xml_parse() several times with new data, as long as the is_final parameter is set and TRUE when the last data is parsed.

is_final

If set and TRUE, data is the last piece of data sent in this parse.

Return Values

Returns 1 on success or 0 on failure.

For unsuccessful parses, error information can be retrieved with
xml_get_error_code(),
xml_error_string(),
xml_get_current_line_number(),
xml_get_current_column_number() and
xml_get_current_byte_index().

Note:

Some errors (such as entity errors) are reported at the end of the data, thus only if is_final is set and TRUE.

Examples

Example #1 Chunked parsing of large XML documents

This example shows how large XML documents can be read and parsed in chunks, so that it not necessary to keep the whole document in memory. Error handling is omitted for brevity.

<?php
$stream = fopen('large.xml', 'r');
$parser = xml_parser_create();
// set up the handlers here
while (($data = fread($stream, 16384))) {
    xml_parse($parser, $data); // parse the current chunk
}
xml_parse($parser, '', true); // finalize parsing
xml_parser_free($parser);
fclose($stream);


Create an XML parser with namespace support

  • « xml_parse
  • xml_parser_create »
  • PHP Manual
  • XML Parser Functions
  • Create an XML parser with namespace support

xml_parser_create_ns

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

xml_parser_create_ns — Create an XML parser with namespace support

Description

xml_parser_create_ns ([ string $encoding [, string $separator = ":" ]] ) : resource

xml_parser_create_ns() creates a new XML parser with XML namespace support and returns a resource handle referencing it to be used by the other XML functions.

Parameters

encoding

The input encoding is automatically detected, so that the encoding parameter specifies only the output encoding. In PHP 5.0.0 and 5.0.1, the default output charset is ISO-8859-1, while in PHP 5.0.2 and upper is UTF-8. The supported encodings are ISO-8859-1, UTF-8 and US-ASCII.

separator

With a namespace aware parser tag parameters passed to the various handler functions will consist of namespace and tag name separated by the string specified in separator.

Return Values

Returns a resource handle for the new XML parser, or FALSE on failure.

See Also

  • xml_parser_create() - Create an XML parser
  • xml_parser_free() - Free an XML parser


Create an XML parser

  • « xml_parser_create_ns
  • xml_parser_free »
  • PHP Manual
  • XML Parser Functions
  • Create an XML parser

xml_parser_create

(PHP 4, PHP 5, PHP 7)

xml_parser_create — Create an XML parser

Description

xml_parser_create ([ string $encoding ] ) : resource

xml_parser_create() creates a new XML parser and returns a resource handle referencing it to be used by the other XML functions.

Parameters

encoding

The optional encoding specifies the character encoding for the input/output in PHP 4. Starting from PHP 5, the input encoding is automatically detected, so that the encoding parameter specifies only the output encoding. In PHP 4, the default output encoding is the same as the input charset. If empty string is passed, the parser attempts to identify which encoding the document is encoded in by looking at the heading 3 or 4 bytes. In PHP 5.0.0 and 5.0.1, the default output charset is ISO-8859-1, while in PHP 5.0.2 and upper is UTF-8. The supported encodings are ISO-8859-1, UTF-8 and US-ASCII.

Return Values

Returns a resource handle for the new XML parser, or FALSE on failure.

See Also

  • xml_parser_create_ns() - Create an XML parser with namespace support
  • xml_parser_free() - Free an XML parser


Free an XML parser

  • « xml_parser_create
  • xml_parser_get_option »
  • PHP Manual
  • XML Parser Functions
  • Free an XML parser

xml_parser_free

(PHP 4, PHP 5, PHP 7)

xml_parser_free — Free an XML parser

Description

xml_parser_free ( resource $parser ) : bool

Frees the given XML parser.

Caution

In addition to calling xml_parser_free() when the parsing is finished, as of PHP 7.0.0 it is necessary to also explicitly unset the reference to parser to avoid memory leaks, if the parser resource is referenced from an object, and this object references that parser resource.

Parameters

parser
A reference to the XML parser to free.

Return Values

This function returns FALSE if parser does not refer to a valid parser, or else it frees the parser and returns TRUE.


Get options from an XML parser

  • « xml_parser_free
  • xml_parser_set_option »
  • PHP Manual
  • XML Parser Functions
  • Get options from an XML parser

xml_parser_get_option

(PHP 4, PHP 5, PHP 7)

xml_parser_get_option — Get options from an XML parser

Description

xml_parser_get_option ( resource $parser , int $option ) : mixed

Gets an option value from an XML parser.

Parameters

parser
A reference to the XML parser to get an option from.
option
Which option to fetch. XML_OPTION_CASE_FOLDING, XML_OPTION_SKIP_TAGSTART, XML_OPTION_SKIP_WHITE and XML_OPTION_TARGET_ENCODING are available. See xml_parser_set_option() for their description.

Return Values

This function returns FALSE if parser does not refer to a valid parser or if option isn't valid (generates also a E_WARNING). Else the option's value is returned.

Changelog

Version | Description
7.1.24, 7.2.12, 7.3.0 | options now supports XML_OPTION_SKIP_TAGSTART and XML_OPTION_SKIP_WHITE.


Set options in an XML parser

  • « xml_parser_get_option
  • xml_set_character_data_handler »
  • PHP Manual
  • XML Parser Functions
  • Set options in an XML parser

xml_parser_set_option

(PHP 4, PHP 5, PHP 7)

xml_parser_set_option — Set options in an XML parser

Description

xml_parser_set_option ( resource $parser , int $option , mixed $value ) : bool

Sets an option in an XML parser.

Parameters

parser

A reference to the XML parser to set an option in.

option

Which option to set. See below.

The following options are available:

XML parser options
Option constant | Data type | Description
XML_OPTION_CASE_FOLDING | integer | Controls whether case-folding is enabled for this XML parser. Enabled by default.
XML_OPTION_SKIP_TAGSTART | integer | Specify how many characters should be skipped in the beginning of a tag name.
XML_OPTION_SKIP_WHITE | integer | Whether to skip values consisting of whitespace characters.
XML_OPTION_TARGET_ENCODING | string | Sets which target encoding to use in this XML parser.By default, it is set to the same as the source encoding used by xml_parser_create(). Supported target encodings are ISO-8859-1, US-ASCII and UTF-8.

value

The option's new value.

Return Values

This function returns FALSE if parser does not refer to a valid parser, or if the option could not be set. Else the option is set and TRUE is returned.


Set up character data handler

  • « xml_parser_set_option
  • xml_set_default_handler »
  • PHP Manual
  • XML Parser Functions
  • Set up character data handler

xml_set_character_data_handler

(PHP 4, PHP 5, PHP 7)

xml_set_character_data_handler — Set up character data handler

Description

xml_set_character_data_handler ( resource $parser , callable $handler ) : bool

Sets the character data handler function for the XML parser parser.

Parameters

parser

A reference to the XML parser to set up character data handler function.

handler

handler is a string containing the name of a function that must exist when xml_parse() is called for parser.

The function named by handler must accept two parameters:

handler ( resource $parser , string $data )
parser
The first parameter, parser, is a reference to the XML parser calling the handler.
data
The second parameter, data, contains the character data as a string.

Character data handler is called for every piece of a text in the XML document. It can be called multiple times inside each fragment (e.g. for non-ASCII strings).

If a handler function is set to an empty string, or FALSE, the handler in question is disabled.

Note: Instead of a function name, an array containing an object reference and a method name can also be supplied.

Return Values

Returns TRUE on success or FALSE on failure.


Set up default handler

  • « xml_set_character_data_handler
  • xml_set_element_handler »
  • PHP Manual
  • XML Parser Functions
  • Set up default handler

xml_set_default_handler

(PHP 4, PHP 5, PHP 7)

xml_set_default_handler — Set up default handler

Description

xml_set_default_handler ( resource $parser , callable $handler ) : bool

Sets the default handler function for the XML parser parser.

Parameters

parser

A reference to the XML parser to set up default handler function.

handler

handler is a string containing the name of a function that must exist when xml_parse() is called for parser.

The function named by handler must accept two parameters:

handler ( resource $parser , string $data )
parser
The first parameter, parser, is a reference to the XML parser calling the handler.
data
The second parameter, data, contains the character data.This may be the XML declaration, document type declaration, entities or other data for which no other handler exists.

If a handler function is set to an empty string, or FALSE, the handler in question is disabled.

Note: Instead of a function name, an array containing an object reference and a method name can also be supplied.

Return Values

Returns TRUE on success or FALSE on failure.


Set up start and end element handlers

  • « xml_set_default_handler
  • xml_set_end_namespace_decl_handler »
  • PHP Manual
  • XML Parser Functions
  • Set up start and end element handlers

xml_set_element_handler

(PHP 4, PHP 5, PHP 7)

xml_set_element_handler — Set up start and end element handlers

Description

xml_set_element_handler ( resource $parser , callable $start_element_handler , callable $end_element_handler ) : bool

Sets the element handler functions for the XML parser. start_element_handler and end_element_handler are strings containing the names of functions that must exist when xml_parse() is called for parser.

Parameters

parser

A reference to the XML parser to set up start and end element handler functions.

start_element_handler

The function named by start_element_handler must accept three parameters:

start_element_handler ( resource $parser , string $name , array $attribs )
parser
The first parameter, parser, is a reference to the XML parser calling the handler.
name
The second parameter, name, contains the name of the element for which this handler is called.If case-folding is in effect for this parser, the element name will be in uppercase letters.
attribs
The third parameter, attribs, contains an associative array with the element's attributes (if any).The keys of this array are the attribute names, the values are the attribute values.Attribute names are case-folded on the same criteria as element names.Attribute values are not case-folded. The original order of the attributes can be retrieved by walking through attribs the normal way, using each().The first key in the array was the first attribute, and so on.

Note: Instead of a function name, an array containing an object reference and a method name can also be supplied.

end_element_handler

The function named by end_element_handler must accept two parameters:

end_element_handler ( resource $parser , string $name )
parser
The first parameter, parser, is a reference to the XML parser calling the handler.
name
The second parameter, name, contains the name of the element for which this handler is called.If case-folding is in effect for this parser, the element name will be in uppercase letters.

If a handler function is set to an empty string, or FALSE, the handler in question is disabled.

Return Values

Returns TRUE on success or FALSE on failure.


Set up end namespace declaration handler

  • « xml_set_element_handler
  • xml_set_external_entity_ref_handler »
  • PHP Manual
  • XML Parser Functions
  • Set up end namespace declaration handler

xml_set_end_namespace_decl_handler

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

xml_set_end_namespace_decl_handler — Set up end namespace declaration handler

Description

xml_set_end_namespace_decl_handler ( resource $parser , callable $handler ) : bool

Set a handler to be called when leaving the scope of a namespace declaration. This will be called, for each namespace declaration, after the handler for the end tag of the element in which the namespace was declared.

Caution

This event is not supported under libXML, so a registered handler wouldn't be called.

Parameters

parser

A reference to the XML parser.

handler

handler is a string containing the name of a function that must exist when xml_parse() is called for parser.

The function named by handler must accept two parameters, and should return an integer value. If the value returned from the handler is FALSE (which it will be if no value is returned), the XML parser will stop parsing and xml_get_error_code() will return XML_ERROR_EXTERNAL_ENTITY_HANDLING.

handler ( resource $parser , string $prefix )
parser
The first parameter, parser, is a reference to the XML parser calling the handler.
prefix
The prefix is a string used to reference the namespace within an XML object.

If a handler function is set to an empty string, or FALSE, the handler in question is disabled.

Note: Instead of a function name, an array containing an object reference and a method name can also be supplied.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • xml_set_start_namespace_decl_handler() - Set up start namespace declaration handler


Set up external entity reference handler

  • « xml_set_end_namespace_decl_handler
  • xml_set_notation_decl_handler »
  • PHP Manual
  • XML Parser Functions
  • Set up external entity reference handler

xml_set_external_entity_ref_handler

(PHP 4, PHP 5, PHP 7)

xml_set_external_entity_ref_handler — Set up external entity reference handler

Description

xml_set_external_entity_ref_handler ( resource $parser , callable $handler ) : bool

Sets the external entity reference handler function for the XML parser parser.

Parameters

parser

A reference to the XML parser to set up external entity reference handler function.

handler

handler is a string containing the name of a function that must exist when xml_parse() is called for parser.

The function named by handler must accept five parameters, and should return an integer value.If the value returned from the handler is FALSE (which it will be if no value is returned), the XML parser will stop parsing and xml_get_error_code() will return XML_ERROR_EXTERNAL_ENTITY_HANDLING.

handler ( resource $parser , string $open_entity_names , string $base , string $system_id , string $public_id )
parser
The first parameter, parser, is a reference to the XML parser calling the handler.
open_entity_names
The second parameter, open_entity_names, is a space-separated list of the names of the entities that are open for the parse of this entity (including the name of the referenced entity).
base
This is the base for resolving the system identifier (system_id) of the external entity.Currently this parameter will always be set to an empty string.
system_id
The fourth parameter, system_id, is the system identifier as specified in the entity declaration.
public_id
The fifth parameter, public_id, is the public identifier as specified in the entity declaration, or an empty string if none was specified; the whitespace in the public identifier will have been normalized as required by the XML spec.

If a handler function is set to an empty string, or FALSE, the handler in question is disabled.

Note: Instead of a function name, an array containing an object reference and a method name can also be supplied.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
7.3.0 | The return value of the handler is no longer ignored if the extension has been built against libxml. Formerly, the return value has been ignored, and parsing did never stop.


Set up notation declaration handler

  • « xml_set_external_entity_ref_handler
  • xml_set_object »
  • PHP Manual
  • XML Parser Functions
  • Set up notation declaration handler

xml_set_notation_decl_handler

(PHP 4, PHP 5, PHP 7)

xml_set_notation_decl_handler — Set up notation declaration handler

Description

xml_set_notation_decl_handler ( resource $parser , callable $handler ) : bool

Sets the notation declaration handler function for the XML parser parser.

A notation declaration is part of the document's DTD and has the following format:

<!NOTATION <parameter>name</parameter>
{ <parameter>systemId</parameter> | <parameter>publicId</parameter>?>
See » section 4.7 of the XML 1.0 spec for the definition of notation declarations.

Parameters

parser

A reference to the XML parser to set up notation declaration handler function.

handler

handler is a string containing the name of a function that must exist when xml_parse() is called for parser.

The function named by handler must accept five parameters:

handler ( resource $parser , string $notation_name , string $base , string $system_id , string $public_id )
parser
The first parameter, parser, is a reference to the XML parser calling the handler.
notation_name
This is the notation's name, as per the notation format described above.
base
This is the base for resolving the system identifier (system_id) of the notation declaration. Currently this parameter will always be set to an empty string.
system_id
System identifier of the external notation declaration.
public_id
Public identifier of the external notation declaration.

If a handler function is set to an empty string, or FALSE, the handler in question is disabled.

Note: Instead of a function name, an array containing an object reference and a method name can also be supplied.

Return Values

Returns TRUE on success or FALSE on failure.


Use XML Parser within an object

  • « xml_set_notation_decl_handler
  • xml_set_processing_instruction_handler »
  • PHP Manual
  • XML Parser Functions
  • Use XML Parser within an object

xml_set_object

(PHP 4, PHP 5, PHP 7)

xml_set_object — Use XML Parser within an object

Description

xml_set_object ( resource $parser , object &$object ) : bool

This function allows to use parser inside object. All callback functions could be set with xml_set_element_handler() etc and assumed to be methods of object.

Parameters

parser

A reference to the XML parser to use inside the object.

object

The object where to use the XML parser.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 xml_set_object() example

<?php
class XMLParser
{
    private $parser;

    function __construct()
    {
        $this->parser = xml_parser_create();

        xml_set_object($this->parser, $this);
        xml_set_element_handler($this->parser, "tag_open", "tag_close");
        xml_set_character_data_handler($this->parser, "cdata");
    }

    function __destruct()
    {
        xml_parser_free($this->parser);
        unset($this->parser);
    }

    function parse($data)
    {
        xml_parse($this->parser, $data);
    }

    function tag_open($parser, $tag, $attributes)
    {
        var_dump($tag, $attributes);
    }

    function cdata($parser, $cdata)
    {
        var_dump($cdata);
    }

    function tag_close($parser, $tag)
    {
        var_dump($tag);
    }
}

$xml_parser = new XMLParser();
$xml_parser->parse("<A ID='hallo'>PHP</A>");
?>

The above example will output:

string(1) "A"
array(1) {
  ["ID"]=>
  string(5) "hallo"
}
string(3) "PHP"
string(1) "A"


Set up processing instruction (PI) handler

  • « xml_set_object
  • xml_set_start_namespace_decl_handler »
  • PHP Manual
  • XML Parser Functions
  • Set up processing instruction (PI) handler

xml_set_processing_instruction_handler

(PHP 4, PHP 5, PHP 7)

xml_set_processing_instruction_handler — Set up processing instruction (PI) handler

Description

xml_set_processing_instruction_handler ( resource $parser , callable $handler ) : bool

Sets the processing instruction (PI) handler function for the XML parser parser.

A processing instruction has the following format:

<?
target data
?>
You can put PHP code into such a tag, but be aware of one limitation: in an XML PI, the PI end tag (?>) can not be quoted, so this character sequence should not appear in the PHP code you embed with PIs in XML documents.If it does, the rest of the PHP code, as well as the "real" PI end tag, will be treated as character data.

Parameters

parser

A reference to the XML parser to set up processing instruction (PI) handler function.

handler

handler is a string containing the name of a function that must exist when xml_parse() is called for parser.

The function named by handler must accept three parameters:

handler ( resource $parser , string $target , string $data )
parser
The first parameter, parser, is a reference to the XML parser calling the handler.
target
The second parameter, target, contains the PI target.
data
The third parameter, data, contains the PI data.

If a handler function is set to an empty string, or FALSE, the handler in question is disabled.

Note: Instead of a function name, an array containing an object reference and a method name can also be supplied.

Return Values

Returns TRUE on success or FALSE on failure.


Set up start namespace declaration handler

  • « xml_set_processing_instruction_handler
  • xml_set_unparsed_entity_decl_handler »
  • PHP Manual
  • XML Parser Functions
  • Set up start namespace declaration handler

xml_set_start_namespace_decl_handler

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

xml_set_start_namespace_decl_handler — Set up start namespace declaration handler

Description

xml_set_start_namespace_decl_handler ( resource $parser , callable $handler ) : bool

Set a handler to be called when a namespace is declared. Namespace declarations occur inside start tags. But the namespace declaration start handler is called before the start tag handler for each namespace declared in that start tag.

Parameters

parser

A reference to the XML parser.

handler

handler is a string containing the name of a function that must exist when xml_parse() is called for parser.

The function named by handler must accept three parameters, and should return an integer value. If the value returned from the handler is FALSE (which it will be if no value is returned), the XML parser will stop parsing and xml_get_error_code() will return XML_ERROR_EXTERNAL_ENTITY_HANDLING.

handler ( resource $parser , string $prefix , string $uri )
parser
The first parameter, parser, is a reference to the XML parser calling the handler.
prefix
The prefix is a string used to reference the namespace within an XML object.
uri
Uniform Resource Identifier (URI) of namespace.

If a handler function is set to an empty string, or FALSE, the handler in question is disabled.

Note: Instead of a function name, an array containing an object reference and a method name can also be supplied.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • xml_set_end_namespace_decl_handler() - Set up end namespace declaration handler


Set up unparsed entity declaration handler

  • « xml_set_start_namespace_decl_handler
  • XMLReader »
  • PHP Manual
  • XML Parser Functions
  • Set up unparsed entity declaration handler

xml_set_unparsed_entity_decl_handler

(PHP 4, PHP 5, PHP 7)

xml_set_unparsed_entity_decl_handler — Set up unparsed entity declaration handler

Description

xml_set_unparsed_entity_decl_handler ( resource $parser , callable $handler ) : bool

Sets the unparsed entity declaration handler function for the XML parser parser.

The handler will be called if the XML parser encounters an external entity declaration with an NDATA declaration, like the following:

<!ENTITY <parameter>name</parameter> {<parameter>publicId</parameter> | <parameter>systemId</parameter>}
        NDATA <parameter>notationName</parameter>

See » section 4.2.2 of the XML 1.0 spec for the definition of notation declared external entities.

Parameters

parser

A reference to the XML parser to set up unparsed entity declaration handler function.

handler

handler is a string containing the name of a function that must exist when xml_parse() is called for parser.

The function named by handler must accept six parameters:

handler ( resource $parser , string $entity_name , string $base , string $system_id , string $public_id , string $notation_name )
parser
The first parameter, parser, is a reference to the XML parser calling the handler.
entity_name
The name of the entity that is about to be defined.
base
This is the base for resolving the system identifier (systemId) of the external entity.Currently this parameter will always be set to an empty string.
system_id
System identifier for the external entity.
public_id
Public identifier for the external entity.
notation_name
Name of the notation of this entity (see xml_set_notation_decl_handler()).

If a handler function is set to an empty string, or FALSE, the handler in question is disabled.

Note: Instead of a function name, an array containing an object reference and a method name can also be supplied.

Return Values

Returns TRUE on success or FALSE on failure.


XMLReader

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • XMLReader — The XMLReader class
    • XMLReader::close — Close the XMLReader input
    • XMLReader::expand — Returns a copy of the current node as a DOM object
    • XMLReader::getAttribute — Get the value of a named attribute
    • XMLReader::getAttributeNo — Get the value of an attribute by index
    • XMLReader::getAttributeNs — Get the value of an attribute by localname and URI
    • XMLReader::getParserProperty — Indicates if specified property has been set
    • XMLReader::isValid — Indicates if the parsed document is valid
    • XMLReader::lookupNamespace — Lookup namespace for a prefix
    • XMLReader::moveToAttribute — Move cursor to a named attribute
    • XMLReader::moveToAttributeNo — Move cursor to an attribute by index
    • XMLReader::moveToAttributeNs — Move cursor to a named attribute
    • XMLReader::moveToElement — Position cursor on the parent Element of current Attribute
    • XMLReader::moveToFirstAttribute — Position cursor on the first Attribute
    • XMLReader::moveToNextAttribute — Position cursor on the next Attribute
    • XMLReader::next — Move cursor to next node skipping all subtrees
    • XMLReader::open — Set the URI containing the XML to parse
    • XMLReader::read — Move to next node in document
    • XMLReader::readInnerXml — Retrieve XML from current node
    • XMLReader::readOuterXml — Retrieve XML from current node, including itself
    • XMLReader::readString — Reads the contents of the current node as a string
    • XMLReader::setParserProperty — Set parser options
    • XMLReader::setRelaxNGSchema — Set the filename or URI for a RelaxNG Schema
    • XMLReader::setRelaxNGSchemaSource — Set the data containing a RelaxNG Schema
    • XMLReader::setSchema — Validate document against XSD
    • XMLReader::XML — Set the data containing the XML to parse


Introduction

The XMLReader extension is an XML Pull parser. The reader acts as a cursor going forward on the document stream and stopping at each node on the way.

Encoding

It is important to note that internally, libxml uses the UTF-8 encoding and as such, the encoding of the retrieved contents will always be in UTF-8 encoding.


Installation

The XMLReader extension was initially a PECL extension for PHP 5. It was later moved to the PHP source (bundled) as of PHP 5.1.0, and later enabled by default as of PHP 5.1.2.

This extension is enabled by default. It may be disabled by using the following option at compile time: --disable-xmlreader


  • « Runtime Configuration
  • XMLReader »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

This extension has no resource types defined.


The XMLReader class

(PHP 5 >= 5.1.0, PHP 7)

Introduction

The XMLReader extension is an XML Pull parser. The reader acts as a cursor going forward on the document stream and stopping at each node on the way.

Class synopsis

XMLReader {
/* Constants */
const int NONE = 0 ;
const int ELEMENT = 1 ;
const int ATTRIBUTE = 2 ;
const int TEXT = 3 ;
const int CDATA = 4 ;
const int ENTITY_REF = 5 ;
const int ENTITY = 6 ;
const int PI = 7 ;
const int COMMENT = 8 ;
const int DOC = 9 ;
const int DOC_TYPE = 10 ;
const int DOC_FRAGMENT = 11 ;
const int NOTATION = 12 ;
const int WHITESPACE = 13 ;
const int SIGNIFICANT_WHITESPACE = 14 ;
const int END_ELEMENT = 15 ;
const int END_ENTITY = 16 ;
const int XML_DECLARATION = 17 ;
const int LOADDTD = 1 ;
const int DEFAULTATTRS = 2 ;
const int VALIDATE = 3 ;
const int SUBST_ENTITIES = 4 ;
/* Properties */
public readonly int $attributeCount ;
public readonly string $baseURI ;
public readonly int $depth ;
public readonly bool $hasAttributes ;
public readonly bool $hasValue ;
public readonly bool $isDefault ;
public readonly bool $isEmptyElement ;
public readonly string $localName ;
public readonly string $name ;
public readonly string $namespaceURI ;
public readonly int $nodeType ;
public readonly string $prefix ;
public readonly string $value ;
public readonly string $xmlLang ;
/* Methods */
public close ( void ) : bool
public expand ([ DOMNode $basenode ] ) : DOMNode
public getAttribute ( string $name ) : string
public getAttributeNo ( int $index ) : string
public getAttributeNs ( string $localName , string $namespaceURI ) : string
public getParserProperty ( int $property ) : bool
public isValid ( void ) : bool
public lookupNamespace ( string $prefix ) : string
public moveToAttribute ( string $name ) : bool
public moveToAttributeNo ( int $index ) : bool
public moveToAttributeNs ( string $localName , string $namespaceURI ) : bool
public moveToElement ( void ) : bool
public moveToFirstAttribute ( void ) : bool
public moveToNextAttribute ( void ) : bool
public next ([ string $localname ] ) : bool
public open ( string $URI [, string $encoding [, int $options = 0 ]] ) : bool
public read ( void ) : bool
public readInnerXml ( void ) : string
public readOuterXml ( void ) : string
public readString ( void ) : string
public setParserProperty ( int $property , bool $value ) : bool
public setRelaxNGSchema ( string $filename ) : bool
public setRelaxNGSchemaSource ( string $source ) : bool
public setSchema ( string $filename ) : bool
public xml ( string $source [, string $encoding [, int $options = 0 ]] ) : bool
}

Properties

attributeCount

The number of attributes on the node

baseURI

The base URI of the node

depth

Depth of the node in the tree, starting at 0

hasAttributes

Indicates if node has attributes

hasValue

Indicates if node has a text value

isDefault

Indicates if attribute is defaulted from DTD

isEmptyElement

Indicates if node is an empty element tag

localName

The local name of the node

name

The qualified name of the node

namespaceURI

The URI of the namespace associated with the node

nodeType

The node type for the node

prefix

The prefix of the namespace associated with the node

value

The text value of the node

xmlLang

The xml:lang scope which the node resides

Predefined Constants

XMLReader Node Types

XMLReader::NONE

No node type

XMLReader::ELEMENT

Start element

XMLReader::ATTRIBUTE

Attribute node

XMLReader::TEXT

Text node

XMLReader::CDATA

CDATA node

XMLReader::ENTITY_REF

Entity Reference node

XMLReader::ENTITY

Entity Declaration node

XMLReader::PI

Processing Instruction node

XMLReader::COMMENT

Comment node

XMLReader::DOC

Document node

XMLReader::DOC_TYPE

Document Type node

XMLReader::DOC_FRAGMENT

Document Fragment node

XMLReader::NOTATION

Notation node

XMLReader::WHITESPACE

Whitespace node

XMLReader::SIGNIFICANT_WHITESPACE

Significant Whitespace node

XMLReader::END_ELEMENT

End Element

XMLReader::END_ENTITY

End Entity

XMLReader::XML_DECLARATION

XML Declaration node

XMLReader Parser Options

XMLReader::LOADDTD

Load DTD but do not validate

XMLReader::DEFAULTATTRS

Load DTD and default attributes but do not validate

XMLReader::VALIDATE

Load DTD and validate while parsing

XMLReader::SUBST_ENTITIES

Substitute entities and expand references

Table of Contents

  • XMLReader::close — Close the XMLReader input
  • XMLReader::expand — Returns a copy of the current node as a DOM object
  • XMLReader::getAttribute — Get the value of a named attribute
  • XMLReader::getAttributeNo — Get the value of an attribute by index
  • XMLReader::getAttributeNs — Get the value of an attribute by localname and URI
  • XMLReader::getParserProperty — Indicates if specified property has been set
  • XMLReader::isValid — Indicates if the parsed document is valid
  • XMLReader::lookupNamespace — Lookup namespace for a prefix
  • XMLReader::moveToAttribute — Move cursor to a named attribute
  • XMLReader::moveToAttributeNo — Move cursor to an attribute by index
  • XMLReader::moveToAttributeNs — Move cursor to a named attribute
  • XMLReader::moveToElement — Position cursor on the parent Element of current Attribute
  • XMLReader::moveToFirstAttribute — Position cursor on the first Attribute
  • XMLReader::moveToNextAttribute — Position cursor on the next Attribute
  • XMLReader::next — Move cursor to next node skipping all subtrees
  • XMLReader::open — Set the URI containing the XML to parse
  • XMLReader::read — Move to next node in document
  • XMLReader::readInnerXml — Retrieve XML from current node
  • XMLReader::readOuterXml — Retrieve XML from current node, including itself
  • XMLReader::readString — Reads the contents of the current node as a string
  • XMLReader::setParserProperty — Set parser options
  • XMLReader::setRelaxNGSchema — Set the filename or URI for a RelaxNG Schema
  • XMLReader::setRelaxNGSchemaSource — Set the data containing a RelaxNG Schema
  • XMLReader::setSchema — Validate document against XSD
  • XMLReader::XML — Set the data containing the XML to parse


Close the XMLReader input

  • « XMLReader
  • XMLReader::expand »
  • PHP Manual
  • XMLReader
  • Close the XMLReader input

XMLReader::close

(PHP 5 >= 5.1.0, PHP 7)

XMLReader::close — Close the XMLReader input

Description

public XMLReader::close ( void ) : bool

Closes the input the XMLReader object is currently parsing.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLReader::open() - Set the URI containing the XML to parse
  • XMLReader::xml() - Set the data containing the XML to parse


Returns a copy of the current node as a DOM object

  • « XMLReader::close
  • XMLReader::getAttribute »
  • PHP Manual
  • XMLReader
  • Returns a copy of the current node as a DOM object

XMLReader::expand

(PHP 5 >= 5.1.0, PHP 7)

XMLReader::expand — Returns a copy of the current node as a DOM object

Description

public XMLReader::expand ([ DOMNode $basenode ] ) : DOMNode

This method copies the current node and returns the appropriate DOM object.

Parameters

basenode

A DOMNode defining the target DOMDocument for the created DOM object.

Return Values

The resulting DOMNode or FALSE on error.

Changelog

Version | Description
5.3.0 | The parameter basenode was added.


Get the value of a named attribute

  • « XMLReader::expand
  • XMLReader::getAttributeNo »
  • PHP Manual
  • XMLReader
  • Get the value of a named attribute

XMLReader::getAttribute

(PHP 5 >= 5.1.0, PHP 7)

XMLReader::getAttribute — Get the value of a named attribute

Description

public XMLReader::getAttribute ( string $name ) : string

Returns the value of a named attribute or NULL if the attribute does not exist or not positioned on an element node.

Parameters

name

The name of the attribute.

Return Values

The value of the attribute, or NULL if no attribute with the given name is found or not positioned on an element node.

Changelog

Version | Description
5.1.3 | Return NULL if no attribute found. Previously, returned an empty string.

See Also

  • XMLReader::getAttributeNo() - Get the value of an attribute by index
  • XMLReader::getAttributeNs() - Get the value of an attribute by localname and URI


Get the value of an attribute by index

  • « XMLReader::getAttribute
  • XMLReader::getAttributeNs »
  • PHP Manual
  • XMLReader
  • Get the value of an attribute by index

XMLReader::getAttributeNo

(PHP 5 >= 5.1.0, PHP 7)

XMLReader::getAttributeNo — Get the value of an attribute by index

Description

public XMLReader::getAttributeNo ( int $index ) : string

Returns the value of an attribute based on its position or an empty string if attribute does not exist or not positioned on an element node.

Parameters

index

The position of the attribute.

Return Values

The value of the attribute, or an empty string (before PHP 5.6) or NULL (from PHP 5.6 onwards) if no attribute exists at index or is not positioned on the element.

Changelog

Version | Description
5.6.0 | XMLReader::getAttributeNo() now returns NULL if the attribute doesn't exist.

See Also

  • XMLReader::getAttribute() - Get the value of a named attribute
  • XMLReader::getAttributeNs() - Get the value of an attribute by localname and URI


Get the value of an attribute by localname and URI

  • « XMLReader::getAttributeNo
  • XMLReader::getParserProperty »
  • PHP Manual
  • XMLReader
  • Get the value of an attribute by localname and URI

XMLReader::getAttributeNs

(PHP 5 >= 5.1.0, PHP 7)

XMLReader::getAttributeNs — Get the value of an attribute by localname and URI

Description

public XMLReader::getAttributeNs ( string $localName , string $namespaceURI ) : string

Returns the value of an attribute by name and namespace URI or an empty string if attribute does not exist or not positioned on an element node.

Parameters

localName

The local name.

namespaceURI

The namespace URI.

Return Values

The value of the attribute, or an empty string (before PHP 5.6) or NULL (from PHP 5.6 onwards) if no attribute with the given localName and namespaceURI is found or not positioned of element.

Changelog

Version | Description
5.6.0 | XMLReader::getAttributeNS() now returns NULL if the attribute doesn't exist.

See Also

  • XMLReader::getAttribute() - Get the value of a named attribute
  • XMLReader::getAttributeNo() - Get the value of an attribute by index


Indicates if specified property has been set

  • « XMLReader::getAttributeNs
  • XMLReader::isValid »
  • PHP Manual
  • XMLReader
  • Indicates if specified property has been set

XMLReader::getParserProperty

(PHP 5 >= 5.1.0, PHP 7)

XMLReader::getParserProperty — Indicates if specified property has been set

Description

public XMLReader::getParserProperty ( int $property ) : bool

Indicates if specified property has been set.

Parameters

property

One of the parser option constants.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLReader::setParserProperty() - Set parser options


Indicates if the parsed document is valid

  • « XMLReader::getParserProperty
  • XMLReader::lookupNamespace »
  • PHP Manual
  • XMLReader
  • Indicates if the parsed document is valid

XMLReader::isValid

(PHP 5 >= 5.1.0, PHP 7)

XMLReader::isValid — Indicates if the parsed document is valid

Description

public XMLReader::isValid ( void ) : bool

Returns a boolean indicating if the document being parsed is currently valid.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Validating XML

<?php
$xml = XMLReader::open('test.xml');

// The validate parser option must be enabled for
// this method to work properly
$xml->setParserProperty(XMLReader::VALIDATE, true);

var_dump($xml->isValid());
?>

Notes

Note: This checks the current node, not the entire document.

See Also

  • XMLReader::setParserProperty() - Set parser options
  • XMLReader::setRelaxNGSchema() - Set the filename or URI for a RelaxNG Schema
  • XMLReader::setRelaxNGSchemaSource() - Set the data containing a RelaxNG Schema
  • XMLReader::setSchema() - Validate document against XSD


Lookup namespace for a prefix

  • « XMLReader::isValid
  • XMLReader::moveToAttribute »
  • PHP Manual
  • XMLReader
  • Lookup namespace for a prefix

XMLReader::lookupNamespace

(PHP 5 >= 5.1.0, PHP 7)

XMLReader::lookupNamespace — Lookup namespace for a prefix

Description

public XMLReader::lookupNamespace ( string $prefix ) : string

Lookup in scope namespace for a given prefix.

Parameters

prefix

String containing the prefix.

Return Values

Returns TRUE on success or FALSE on failure.


Move cursor to a named attribute

  • « XMLReader::lookupNamespace
  • XMLReader::moveToAttributeNo »
  • PHP Manual
  • XMLReader
  • Move cursor to a named attribute

XMLReader::moveToAttribute

(PHP 5 >= 5.1.0, PHP 7)

XMLReader::moveToAttribute — Move cursor to a named attribute

Description

public XMLReader::moveToAttribute ( string $name ) : bool

Positions cursor on the named attribute.

Parameters

name

The name of the attribute.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttributeNo() - Move cursor to an attribute by index
  • XMLReader::moveToAttributeNs() - Move cursor to a named attribute
  • XMLReader::moveToFirstAttribute() - Position cursor on the first Attribute


Move cursor to an attribute by index

  • « XMLReader::moveToAttribute
  • XMLReader::moveToAttributeNs »
  • PHP Manual
  • XMLReader
  • Move cursor to an attribute by index

XMLReader::moveToAttributeNo

(PHP 5 >= 5.1.0, PHP 7)

XMLReader::moveToAttributeNo — Move cursor to an attribute by index

Description

public XMLReader::moveToAttributeNo ( int $index ) : bool

Positions cursor on attribute based on its position.

Parameters

index

The position of the attribute.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttribute() - Move cursor to a named attribute
  • XMLReader::moveToAttributeNs() - Move cursor to a named attribute
  • XMLReader::moveToFirstAttribute() - Position cursor on the first Attribute


Move cursor to a named attribute

  • « XMLReader::moveToAttributeNo
  • XMLReader::moveToElement »
  • PHP Manual
  • XMLReader
  • Move cursor to a named attribute

XMLReader::moveToAttributeNs

(PHP 5 >= 5.1.0, PHP 7)

XMLReader::moveToAttributeNs — Move cursor to a named attribute

Description

public XMLReader::moveToAttributeNs ( string $localName , string $namespaceURI ) : bool

Positions cursor on the named attribute in specified namespace.

Parameters

localName

The local name.

namespaceURI

The namespace URI.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttribute() - Move cursor to a named attribute
  • XMLReader::moveToAttributeNo() - Move cursor to an attribute by index
  • XMLReader::moveToFirstAttribute() - Position cursor on the first Attribute


Position cursor on the parent Element of current Attribute

  • « XMLReader::moveToAttributeNs
  • XMLReader::moveToFirstAttribute »
  • PHP Manual
  • XMLReader
  • Position cursor on the parent Element of current Attribute

XMLReader::moveToElement

(PHP 5 >= 5.1.0, PHP 7)

XMLReader::moveToElement — Position cursor on the parent Element of current Attribute

Description

public XMLReader::moveToElement ( void ) : bool

Moves cursor to the parent Element of current Attribute.

Return Values

Returns TRUE if successful and FALSE if it fails or not positioned on Attribute when this method is called.

See Also

  • XMLReader::moveToAttribute() - Move cursor to a named attribute
  • XMLReader::moveToAttributeNo() - Move cursor to an attribute by index
  • XMLReader::moveToAttributeNs() - Move cursor to a named attribute
  • XMLReader::moveToFirstAttribute() - Position cursor on the first Attribute


Position cursor on the first Attribute

  • « XMLReader::moveToElement
  • XMLReader::moveToNextAttribute »
  • PHP Manual
  • XMLReader
  • Position cursor on the first Attribute

XMLReader::moveToFirstAttribute

(PHP 5 >= 5.1.0, PHP 7)

XMLReader::moveToFirstAttribute — Position cursor on the first Attribute

Description

public XMLReader::moveToFirstAttribute ( void ) : bool

Moves cursor to the first Attribute.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttribute() - Move cursor to a named attribute
  • XMLReader::moveToAttributeNo() - Move cursor to an attribute by index
  • XMLReader::moveToAttributeNs() - Move cursor to a named attribute
  • XMLReader::moveToNextAttribute() - Position cursor on the next Attribute


Position cursor on the next Attribute

  • « XMLReader::moveToFirstAttribute
  • XMLReader::next »
  • PHP Manual
  • XMLReader
  • Position cursor on the next Attribute

XMLReader::moveToNextAttribute

(PHP 5 >= 5.1.0, PHP 7)

XMLReader::moveToNextAttribute — Position cursor on the next Attribute

Description

public XMLReader::moveToNextAttribute ( void ) : bool

Moves cursor to the next Attribute if positioned on an Attribute or moves to first attribute if positioned on an Element.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttribute() - Move cursor to a named attribute
  • XMLReader::moveToAttributeNo() - Move cursor to an attribute by index
  • XMLReader::moveToAttributeNs() - Move cursor to a named attribute
  • XMLReader::moveToFirstAttribute() - Position cursor on the first Attribute


Move cursor to next node skipping all subtrees

  • « XMLReader::moveToNextAttribute
  • XMLReader::open »
  • PHP Manual
  • XMLReader
  • Move cursor to next node skipping all subtrees

XMLReader::next

(PHP 5 >= 5.1.0, PHP 7)

XMLReader::next — Move cursor to next node skipping all subtrees

Description

public XMLReader::next ([ string $localname ] ) : bool

Positions cursor on the next node skipping all subtrees.

Parameters

localname

The name of the next node to move to.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLReader::moveToNextAttribute() - Position cursor on the next Attribute
  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttribute() - Move cursor to a named attribute


Set the URI containing the XML to parse

  • « XMLReader::next
  • XMLReader::read »
  • PHP Manual
  • XMLReader
  • Set the URI containing the XML to parse

XMLReader::open

(PHP 5 >= 5.1.0, PHP 7)

XMLReader::open — Set the URI containing the XML to parse

Description

public XMLReader::open ( string $URI [, string $encoding [, int $options = 0 ]] ) : bool

Set the URI containing the XML document to be parsed.

Parameters

URI

URI pointing to the document.

encoding

The document encoding or NULL.

options

A bitmask of the LIBXML_* constants.

Return Values

Returns TRUE on success or FALSE on failure. If called statically, returns an XMLReader or FALSE on failure.

Errors/Exceptions

This method may be called statically, but will issue an E_STRICT error.

Changelog

Version | Description
5.2.0 | encoding and options were added.

See Also

  • XMLReader::xml() - Set the data containing the XML to parse
  • XMLReader::close() - Close the XMLReader input


Move to next node in document

  • « XMLReader::open
  • XMLReader::readInnerXml »
  • PHP Manual
  • XMLReader
  • Move to next node in document

XMLReader::read

(PHP 5 >= 5.1.0, PHP 7)

XMLReader::read — Move to next node in document

Description

public XMLReader::read ( void ) : bool

Moves cursor to the next node in the document.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLReader::moveToElement() - Position cursor on the parent Element of current Attribute
  • XMLReader::moveToAttribute() - Move cursor to a named attribute
  • XMLReader::next() - Move cursor to next node skipping all subtrees


Retrieve XML from current node

  • « XMLReader::read
  • XMLReader::readOuterXml »
  • PHP Manual
  • XMLReader
  • Retrieve XML from current node

XMLReader::readInnerXml

(PHP 5 >= 5.2.0, PHP 7)

XMLReader::readInnerXml — Retrieve XML from current node

Description

public XMLReader::readInnerXml ( void ) : string

Reads the contents of the current node, including child nodes and markup.

Parameters

This function has no parameters.

Return Values

Returns the contents of the current node as a string. Empty string on failure.

Notes

Caution

This function is only available when PHP is compiled against libxml 20620 or later.

See Also

  • XMLReader::readString() - Reads the contents of the current node as a string
  • XMLReader::readOuterXml() - Retrieve XML from current node, including itself
  • XMLReader::expand() - Returns a copy of the current node as a DOM object


Retrieve XML from current node, including itself

  • « XMLReader::readInnerXml
  • XMLReader::readString »
  • PHP Manual
  • XMLReader
  • Retrieve XML from current node, including itself

XMLReader::readOuterXml

(PHP 5 >= 5.2.0, PHP 7)

XMLReader::readOuterXml — Retrieve XML from current node, including itself

Description

public XMLReader::readOuterXml ( void ) : string

Reads the contents of the current node, including the node itself.

Parameters

This function has no parameters.

Return Values

Returns the contents of current node, including itself, as a string. Empty string on failure.

Notes

Caution

This function is only available when PHP is compiled against libxml 20620 or later.

See Also

  • XMLReader::readString() - Reads the contents of the current node as a string
  • XMLReader::readInnerXml() - Retrieve XML from current node
  • XMLReader::expand() - Returns a copy of the current node as a DOM object


Reads the contents of the current node as a string

  • « XMLReader::readOuterXml
  • XMLReader::setParserProperty »
  • PHP Manual
  • XMLReader
  • Reads the contents of the current node as a string

XMLReader::readString

(PHP 5 >= 5.2.0, PHP 7)

XMLReader::readString — Reads the contents of the current node as a string

Description

public XMLReader::readString ( void ) : string

Reads the contents of the current node as a string.

Parameters

This function has no parameters.

Return Values

Returns the content of the current node as a string. Empty string on failure.

Notes

Caution

This function is only available when PHP is compiled against libxml 20620 or later.

See Also

  • XMLReader::readOuterXml() - Retrieve XML from current node, including itself
  • XMLReader::readInnerXml() - Retrieve XML from current node
  • XMLReader::expand() - Returns a copy of the current node as a DOM object


Set parser options

  • « XMLReader::readString
  • XMLReader::setRelaxNGSchema »
  • PHP Manual
  • XMLReader
  • Set parser options

XMLReader::setParserProperty

(PHP 5 >= 5.1.0, PHP 7)

XMLReader::setParserProperty — Set parser options

Description

public XMLReader::setParserProperty ( int $property , bool $value ) : bool

Set parser options. The options must be set after
XMLReader::open() or
XMLReader::xml() are called and before
the first XMLReader::read() call.

Parameters

property

One of the parser option constants.

value

If set to TRUE the option will be enabled otherwise will be disabled.

Return Values

Returns TRUE on success or FALSE on failure.


Set the filename or URI for a RelaxNG Schema

  • « XMLReader::setParserProperty
  • XMLReader::setRelaxNGSchemaSource »
  • PHP Manual
  • XMLReader
  • Set the filename or URI for a RelaxNG Schema

XMLReader::setRelaxNGSchema

(PHP 5 >= 5.1.0, PHP 7)

XMLReader::setRelaxNGSchema — Set the filename or URI for a RelaxNG Schema

Description

public XMLReader::setRelaxNGSchema ( string $filename ) : bool

Set the filename or URI for the RelaxNG Schema to use for validation.

Parameters

filename

filename or URI pointing to a RelaxNG Schema.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLReader::setRelaxNGSchemaSource() - Set the data containing a RelaxNG Schema
  • XMLReader::setSchema() - Validate document against XSD
  • XMLReader::isValid() - Indicates if the parsed document is valid


Set the data containing a RelaxNG Schema

  • « XMLReader::setRelaxNGSchema
  • XMLReader::setSchema »
  • PHP Manual
  • XMLReader
  • Set the data containing a RelaxNG Schema

XMLReader::setRelaxNGSchemaSource

(PHP 5 >= 5.1.0, PHP 7)

XMLReader::setRelaxNGSchemaSource — Set the data containing a RelaxNG Schema

Description

public XMLReader::setRelaxNGSchemaSource ( string $source ) : bool

Set the data containing a RelaxNG Schema to use for validation.

Parameters

source

String containing the RelaxNG Schema.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLReader::setRelaxNGSchema() - Set the filename or URI for a RelaxNG Schema
  • XMLReader::setSchema() - Validate document against XSD
  • XMLReader::isValid() - Indicates if the parsed document is valid


Validate document against XSD

  • « XMLReader::setRelaxNGSchemaSource
  • XMLReader::XML »
  • PHP Manual
  • XMLReader
  • Validate document against XSD

XMLReader::setSchema

(PHP 5 >= 5.2.0, PHP 7)

XMLReader::setSchema — Validate document against XSD

Description

public XMLReader::setSchema ( string $filename ) : bool

Use W3C XSD schema to validate the document as it is processed. Activation is only possible before the first Read().

Parameters

filename

The filename of the XSD schema.

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Issues E_WARNING if libxml was built without schema support, the schema contains errors or if XMLReader::read() has already been called.

Notes

Caution

This function is only available when PHP is compiled against libxml 20620 or later.

See Also

  • XMLReader::setRelaxNGSchema() - Set the filename or URI for a RelaxNG Schema
  • XMLReader::setRelaxNGSchemaSource() - Set the data containing a RelaxNG Schema
  • XMLReader::isValid() - Indicates if the parsed document is valid


Set the data containing the XML to parse

  • « XMLReader::setSchema
  • XMLWriter »
  • PHP Manual
  • XMLReader
  • Set the data containing the XML to parse

XMLReader::XML

(PHP 5 >= 5.1.0, PHP 7)

XMLReader::XML — Set the data containing the XML to parse

Description

public XMLReader::xml ( string $source [, string $encoding [, int $options = 0 ]] ) : bool

Set the data containing the XML to parse.

Parameters

source

String containing the XML to be parsed.

encoding

The document encoding or NULL.

options

A bitmask of the LIBXML_* constants.

Return Values

Returns TRUE on success or FALSE on failure. If called statically, returns an XMLReader or FALSE on failure.

Errors/Exceptions

This method may be called statically, but will issue an E_STRICT error.

Changelog

Version | Description
5.2.0 | encoding and options were added.

See Also

  • XMLReader::open() - Set the URI containing the XML to parse
  • XMLReader::close() - Close the XMLReader input


XMLWriter

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Creating a simple XML document
    • Working with XML namespaces
    • Working with the OO API
  • XMLWriter Functions
    • XMLWriter::endAttribute — End attribute
    • XMLWriter::endCdata — End current CDATA
    • XMLWriter::endComment — Create end comment
    • XMLWriter::endDocument — End current document
    • XMLWriter::endDtdAttlist — End current DTD AttList
    • XMLWriter::endDtdElement — End current DTD element
    • XMLWriter::endDtdEntity — End current DTD Entity
    • XMLWriter::endDtd — End current DTD
    • XMLWriter::endElement — End current element
    • XMLWriter::endPi — End current PI
    • XMLWriter::flush — Flush current buffer
    • XMLWriter::fullEndElement — End current element
    • XMLWriter::openMemory — Create new xmlwriter using memory for string output
    • XMLWriter::openUri — Create new xmlwriter using source uri for output
    • XMLWriter::outputMemory — Returns current buffer
    • XMLWriter::setIndentString — Set string used for indenting
    • XMLWriter::setIndent — Toggle indentation on/off
    • XMLWriter::startAttributeNs — Create start namespaced attribute
    • XMLWriter::startAttribute — Create start attribute
    • XMLWriter::startCdata — Create start CDATA tag
    • XMLWriter::startComment — Create start comment
    • XMLWriter::startDocument — Create document tag
    • XMLWriter::startDtdAttlist — Create start DTD AttList
    • XMLWriter::startDtdElement — Create start DTD element
    • XMLWriter::startDtdEntity — Create start DTD Entity
    • XMLWriter::startDtd — Create start DTD tag
    • XMLWriter::startElementNs — Create start namespaced element tag
    • XMLWriter::startElement — Create start element tag
    • XMLWriter::startPi — Create start PI tag
    • XMLWriter::text — Write text
    • XMLWriter::writeAttributeNs — Write full namespaced attribute
    • XMLWriter::writeAttribute — Write full attribute
    • XMLWriter::writeCdata — Write full CDATA tag
    • XMLWriter::writeComment — Write full comment tag
    • XMLWriter::writeDtdAttlist — Write full DTD AttList tag
    • XMLWriter::writeDtdElement — Write full DTD element tag
    • XMLWriter::writeDtdEntity — Write full DTD Entity tag
    • XMLWriter::writeDtd — Write full DTD tag
    • XMLWriter::writeElementNs — Write full namespaced element tag
    • XMLWriter::writeElement — Write full element tag
    • XMLWriter::writePi — Writes a PI
    • XMLWriter::writeRaw — Write a raw XML text


Introduction

This is the XMLWriter extension. It wraps the libxml xmlWriter API.

This extension represents a writer that provides a non-cached, forward-only means of generating streams or files containing XML data.

This extension can be used in an object oriented style or a procedural one. Every method documented describes the alternative procedural call.


Installation

The XMLWriter extension was initially a PECL extension for PHP 5. It was later added to the PHP source (bundled) as of PHP 5.1.2. This extension is enabled by default.

This extension is enabled by default. It may be disabled by using the following option at compile time: --disable-xmlwriter


Resource Types

There is one resource used by the procedural version of the XMLWriter extension: returned by xmlwriter_open_memory() or xmlwriter_open_uri().


  • « Resource Types
  • Examples »
  • PHP Manual
  • XMLWriter
  • Predefined Constants

Predefined Constants

This extension has no constants defined.


Examples

Table of Contents

  • Creating a simple XML document
  • Working with XML namespaces
  • Working with the OO API


Creating a simple XML document

This example shows how to use XMLWriter to create a XML document in memory.

Example #1 Creating a simple XML document

<?php

$xw = xmlwriter_open_memory();
xmlwriter_set_indent($xw, 1);
$res = xmlwriter_set_indent_string($xw, ' ');

xmlwriter_start_document($xw, '1.0', 'UTF-8');

// A first element
xmlwriter_start_element($xw, 'tag1');

// Attribute 'att1' for element 'tag1'
xmlwriter_start_attribute($xw, 'att1');
xmlwriter_text($xw, 'valueofatt1');
xmlwriter_end_attribute($xw);

xmlwriter_write_comment($xw, 'this is a comment.');

// Start a child element
xmlwriter_start_element($xw, 'tag11');
xmlwriter_text($xw, 'This is a sample text, ä');
xmlwriter_end_element($xw); // tag11

xmlwriter_end_element($xw); // tag1

// CDATA
xmlwriter_start_element($xw, 'testc');
xmlwriter_write_cdata($xw, "This is cdata content");
xmlwriter_end_element($xw); // testc

xmlwriter_start_element($xw, 'testc');
xmlwriter_start_cdata($xw);
xmlwriter_text($xw, "test cdata2");
xmlwriter_end_cdata($xw);
xmlwriter_end_element($xw); // testc

// A processing instruction
xmlwriter_start_pi($xw, 'php');
xmlwriter_text($xw, '$foo=2;echo $foo;');
xmlwriter_end_pi($xw);

xmlwriter_end_document($xw);

echo xmlwriter_output_memory($xw);

The above example will output:

<?xml version="1.0" encoding="UTF-8"?>
<tag1 att1="valueofatt1">
 <!--this is a comment.-->
 <tag11>This is a sample text, ä</tag11>
</tag1>
<testc><![CDATA[This is cdata content]]></testc>
<testc><![CDATA[test cdata2]]></testc>
<?php $foo=2;echo $foo;?>


Working with XML namespaces

This example shows how to create namespaced XML elements.

Example #1 Working with XML namespaces

<?php

$xw = xmlwriter_open_memory();
xmlwriter_set_indent($xw, 1);
$res = xmlwriter_set_indent_string($xw, ' ');

xmlwriter_start_document($xw, '1.0', 'UTF-8');
// A first element
xmlwriter_start_element_ns($xw,'prefix', 'books', 'uri');
xmlwriter_start_attribute($xw, 'isbn');

xmlwriter_start_attribute_ns($xw, 'prefix', 'isbn', 'uri');
xmlwriter_end_attribute($xw);

xmlwriter_end_attribute($xw);

xmlwriter_text($xw, 'book1');
xmlwriter_end_element($xw);

xmlwriter_end_document($xw);

echo xmlwriter_output_memory($xw);

The above example will output:

<?xml version="1.0" encoding="UTF-8"?>
<prefix:books isbn="" prefix:isbn="" xmlns:prefix="uri">book1</prefix:books>


Working with the OO API

This example shows how to work with XMLWriter's object oriented API.

Example #1 Working with the OO API

<?php

$xw = new XMLWriter();
$xw->openMemory();
$xw->startDocument("1.0");
$xw->startElement("book");
$xw->text("example");
$xw->endElement();
$xw->endDocument();
echo $xw->outputMemory();

The above example will output:

<?xml version="1.0"?>
<book>example</book>


XMLWriter Functions

Table of Contents

  • XMLWriter::endAttribute — End attribute
  • XMLWriter::endCdata — End current CDATA
  • XMLWriter::endComment — Create end comment
  • XMLWriter::endDocument — End current document
  • XMLWriter::endDtdAttlist — End current DTD AttList
  • XMLWriter::endDtdElement — End current DTD element
  • XMLWriter::endDtdEntity — End current DTD Entity
  • XMLWriter::endDtd — End current DTD
  • XMLWriter::endElement — End current element
  • XMLWriter::endPi — End current PI
  • XMLWriter::flush — Flush current buffer
  • XMLWriter::fullEndElement — End current element
  • XMLWriter::openMemory — Create new xmlwriter using memory for string output
  • XMLWriter::openUri — Create new xmlwriter using source uri for output
  • XMLWriter::outputMemory — Returns current buffer
  • XMLWriter::setIndentString — Set string used for indenting
  • XMLWriter::setIndent — Toggle indentation on/off
  • XMLWriter::startAttributeNs — Create start namespaced attribute
  • XMLWriter::startAttribute — Create start attribute
  • XMLWriter::startCdata — Create start CDATA tag
  • XMLWriter::startComment — Create start comment
  • XMLWriter::startDocument — Create document tag
  • XMLWriter::startDtdAttlist — Create start DTD AttList
  • XMLWriter::startDtdElement — Create start DTD element
  • XMLWriter::startDtdEntity — Create start DTD Entity
  • XMLWriter::startDtd — Create start DTD tag
  • XMLWriter::startElementNs — Create start namespaced element tag
  • XMLWriter::startElement — Create start element tag
  • XMLWriter::startPi — Create start PI tag
  • XMLWriter::text — Write text
  • XMLWriter::writeAttributeNs — Write full namespaced attribute
  • XMLWriter::writeAttribute — Write full attribute
  • XMLWriter::writeCdata — Write full CDATA tag
  • XMLWriter::writeComment — Write full comment tag
  • XMLWriter::writeDtdAttlist — Write full DTD AttList tag
  • XMLWriter::writeDtdElement — Write full DTD element tag
  • XMLWriter::writeDtdEntity — Write full DTD Entity tag
  • XMLWriter::writeDtd — Write full DTD tag
  • XMLWriter::writeElementNs — Write full namespaced element tag
  • XMLWriter::writeElement — Write full element tag
  • XMLWriter::writePi — Writes a PI
  • XMLWriter::writeRaw — Write a raw XML text


End attribute

  • « XMLWriter Functions
  • XMLWriter::endCdata »
  • PHP Manual
  • XMLWriter Functions
  • End attribute

XMLWriter::endAttribute

xmlwriter_end_attribute

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::endAttribute -- xmlwriter_end_attribute — End attribute

Description

Object oriented style

XMLWriter::endAttribute ( void ) : bool

Procedural style

xmlwriter_end_attribute ( resource $xmlwriter ) : bool

Ends the current attribute.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::startAttribute() - Create start attribute
  • XMLWriter::startAttributeNs() - Create start namespaced attribute
  • XMLWriter::writeAttribute() - Write full attribute
  • XMLWriter::writeAttributeNs() - Write full namespaced attribute


End current CDATA

  • « XMLWriter::endAttribute
  • XMLWriter::endComment »
  • PHP Manual
  • XMLWriter Functions
  • End current CDATA

XMLWriter::endCdata

xmlwriter_end_cdata

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::endCdata -- xmlwriter_end_cdata — End current CDATA

Description

Object oriented style

XMLWriter::endCdata ( void ) : bool

Procedural style

xmlwriter_end_cdata ( resource $xmlwriter ) : bool

Ends the current CDATA section.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::startCdata() - Create start CDATA tag
  • XMLWriter::writeCdata() - Write full CDATA tag


Create end comment

  • « XMLWriter::endCdata
  • XMLWriter::endDocument »
  • PHP Manual
  • XMLWriter Functions
  • Create end comment

XMLWriter::endComment

xmlwriter_end_comment

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 1.0.0)

XMLWriter::endComment -- xmlwriter_end_comment — Create end comment

Description

Object oriented style

XMLWriter::endComment ( void ) : bool

Procedural style

xmlwriter_end_comment ( resource $xmlwriter ) : bool

Ends the current comment.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::startComment() - Create start comment
  • XMLWriter::writeComment() - Write full comment tag


End current document

  • « XMLWriter::endComment
  • XMLWriter::endDtdAttlist »
  • PHP Manual
  • XMLWriter Functions
  • End current document

XMLWriter::endDocument

xmlwriter_end_document

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::endDocument -- xmlwriter_end_document — End current document

Description

Object oriented style

XMLWriter::endDocument ( void ) : bool

Procedural style

xmlwriter_end_document ( resource $xmlwriter ) : bool

Ends the current document.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::startDocument() - Create document tag


End current DTD AttList

  • « XMLWriter::endDocument
  • XMLWriter::endDtdElement »
  • PHP Manual
  • XMLWriter Functions
  • End current DTD AttList

XMLWriter::endDtdAttlist

xmlwriter_end_dtd_attlist

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::endDtdAttlist -- xmlwriter_end_dtd_attlist — End current DTD AttList

Description

Object oriented style

XMLWriter::endDtdAttlist ( void ) : bool

Procedural style

xmlwriter_end_dtd_attlist ( resource $xmlwriter ) : bool

Ends the current DTD attribute list.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::startDtdAttlist() - Create start DTD AttList
  • XMLWriter::writeDtdAttlist() - Write full DTD AttList tag


End current DTD element

  • « XMLWriter::endDtdAttlist
  • XMLWriter::endDtdEntity »
  • PHP Manual
  • XMLWriter Functions
  • End current DTD element

XMLWriter::endDtdElement

xmlwriter_end_dtd_element

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::endDtdElement -- xmlwriter_end_dtd_element — End current DTD element

Description

Object oriented style

XMLWriter::endDtdElement ( void ) : bool

Procedural style

xmlwriter_end_dtd_element ( resource $xmlwriter ) : bool

Ends the current DTD element.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::startDtdElement() - Create start DTD element
  • XMLWriter::writeDtdElement() - Write full DTD element tag


End current DTD Entity

  • « XMLWriter::endDtdElement
  • XMLWriter::endDtd »
  • PHP Manual
  • XMLWriter Functions
  • End current DTD Entity

XMLWriter::endDtdEntity

xmlwriter_end_dtd_entity

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::endDtdEntity -- xmlwriter_end_dtd_entity — End current DTD Entity

Description

Object oriented style

XMLWriter::endDtdEntity ( void ) : bool

Procedural style

xmlwriter_end_dtd_entity ( resource $xmlwriter ) : bool

Ends the current DTD entity.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::startDtdEntity() - Create start DTD Entity
  • XMLWriter::writeDtdEntity() - Write full DTD Entity tag


End current DTD

  • « XMLWriter::endDtdEntity
  • XMLWriter::endElement »
  • PHP Manual
  • XMLWriter Functions
  • End current DTD

XMLWriter::endDtd

xmlwriter_end_dtd

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::endDtd -- xmlwriter_end_dtd — End current DTD

Description

Object oriented style

XMLWriter::endDtd ( void ) : bool

Procedural style

xmlwriter_end_dtd ( resource $xmlwriter ) : bool

Ends the DTD of the document.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::startDtd() - Create start DTD tag
  • XMLWriter::writeDtd() - Write full DTD tag


End current element

  • « XMLWriter::endDtd
  • XMLWriter::endPi »
  • PHP Manual
  • XMLWriter Functions
  • End current element

XMLWriter::endElement

xmlwriter_end_element

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::endElement -- xmlwriter_end_element — End current element

Description

Object oriented style

XMLWriter::endElement ( void ) : bool

Procedural style

xmlwriter_end_element ( resource $xmlwriter ) : bool

Ends the current element.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::startElement() - Create start element tag
  • XMLWriter::writeElement() - Write full element tag


End current PI

  • « XMLWriter::endElement
  • XMLWriter::flush »
  • PHP Manual
  • XMLWriter Functions
  • End current PI

XMLWriter::endPi

xmlwriter_end_pi

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::endPi -- xmlwriter_end_pi — End current PI

Description

Object oriented style

XMLWriter::endPi ( void ) : bool

Procedural style

xmlwriter_end_pi ( resource $xmlwriter ) : bool

Ends the current processing instruction.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::startPi() - Create start PI tag
  • XMLWriter::writePi() - Writes a PI


Flush current buffer

  • « XMLWriter::endPi
  • XMLWriter::fullEndElement »
  • PHP Manual
  • XMLWriter Functions
  • Flush current buffer

XMLWriter::flush

xmlwriter_flush

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 1.0.0)

XMLWriter::flush -- xmlwriter_flush — Flush current buffer

Description

Object oriented style

XMLWriter::flush ([ bool $empty = TRUE ] ) : mixed

Procedural style

xmlwriter_flush ( resource $xmlwriter [, bool $empty = TRUE ] ) : mixed

Flushes the current buffer.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

empty

Whether to empty the buffer or not. Default is TRUE.

Return Values

If you opened the writer in memory, this function returns the generated XML buffer, Else, if using URI, this function will write the buffer and return the number of written bytes.


End current element

  • « XMLWriter::flush
  • XMLWriter::openMemory »
  • PHP Manual
  • XMLWriter Functions
  • End current element

XMLWriter::fullEndElement

xmlwriter_full_end_element

(PHP 5 >= 5.2.0, PHP 7, PECL xmlwriter >= 2.0.4)

XMLWriter::fullEndElement -- xmlwriter_full_end_element — End current element

Description

Object oriented style

XMLWriter::fullEndElement ( void ) : bool

Procedural style

xmlwriter_full_end_element ( resource $xmlwriter ) : bool

End the current xml element. Writes an end tag even if the element is empty.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::endElement() - End current element


Create new xmlwriter using memory for string output

  • « XMLWriter::fullEndElement
  • XMLWriter::openUri »
  • PHP Manual
  • XMLWriter Functions
  • Create new xmlwriter using memory for string output

XMLWriter::openMemory

xmlwriter_open_memory

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::openMemory -- xmlwriter_open_memory — Create new xmlwriter using memory for string output

Description

Object oriented style

XMLWriter::openMemory ( void ) : bool

Procedural style

xmlwriter_open_memory ( void ) : resource

Creates a new XMLWriter using memory for string output.

Parameters

Return Values

Object oriented style: Returns TRUE on success or FALSE on failure.

Procedural style: Returns a new xmlwriter resource for later use with the xmlwriter functions on success, FALSE on error.

See Also

  • XMLWriter::openUri() - Create new xmlwriter using source uri for output


Create new xmlwriter using source uri for output

  • « XMLWriter::openMemory
  • XMLWriter::outputMemory »
  • PHP Manual
  • XMLWriter Functions
  • Create new xmlwriter using source uri for output

XMLWriter::openUri

xmlwriter_open_uri

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::openUri -- xmlwriter_open_uri — Create new xmlwriter using source uri for output

Description

Object oriented style

XMLWriter::openUri ( string $uri ) : bool

Procedural style

xmlwriter_open_uri ( string $uri ) : resource

Creates a new XMLWriter using uri for the output.

Parameters

uri

The URI of the resource for the output.

Return Values

Object oriented style: Returns TRUE on success or FALSE on failure.

Procedural style: Returns a new xmlwriter resource for later use with the xmlwriter functions on success, FALSE on error.

See Also

  • XMLWriter::openMemory() - Create new xmlwriter using memory for string output


Returns current buffer

  • « XMLWriter::openUri
  • XMLWriter::setIndentString »
  • PHP Manual
  • XMLWriter Functions
  • Returns current buffer

XMLWriter::outputMemory

xmlwriter_output_memory

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::outputMemory -- xmlwriter_output_memory — Returns current buffer

Description

Object oriented style

XMLWriter::outputMemory ([ bool $flush = TRUE ] ) : string

Procedural style

xmlwriter_output_memory ( resource $xmlwriter [, bool $flush = TRUE ] ) : string

Returns the current buffer.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

flush

Whether to flush the output buffer or not. Default is TRUE.

Return Values

Returns the current buffer as a string.

See Also

  • XMLWriter::flush() - Flush current buffer


Set string used for indenting

  • « XMLWriter::outputMemory
  • XMLWriter::setIndent »
  • PHP Manual
  • XMLWriter Functions
  • Set string used for indenting

XMLWriter::setIndentString

xmlwriter_set_indent_string

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::setIndentString -- xmlwriter_set_indent_string — Set string used for indenting

Description

Object oriented style

XMLWriter::setIndentString ( string $indentString ) : bool

Procedural style

xmlwriter_set_indent_string ( resource $xmlwriter , string $indentString ) : bool

Sets the string which will be used to indent each element/attribute of the resulting xml.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

indentString

The indentation string.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::setIndent() - Toggle indentation on/off


Toggle indentation on/off

  • « XMLWriter::setIndentString
  • XMLWriter::startAttributeNs »
  • PHP Manual
  • XMLWriter Functions
  • Toggle indentation on/off

XMLWriter::setIndent

xmlwriter_set_indent

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::setIndent -- xmlwriter_set_indent — Toggle indentation on/off

Description

Object oriented style

XMLWriter::setIndent ( bool $indent ) : bool

Procedural style

xmlwriter_set_indent ( resource $xmlwriter , bool $indent ) : bool

Toggles indentation on or off.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

indent

Whether indentation is enabled.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::setIndentString() - Set string used for indenting


Create start namespaced attribute

  • « XMLWriter::setIndent
  • XMLWriter::startAttribute »
  • PHP Manual
  • XMLWriter Functions
  • Create start namespaced attribute

XMLWriter::startAttributeNs

xmlwriter_start_attribute_ns

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::startAttributeNs -- xmlwriter_start_attribute_ns — Create start namespaced attribute

Description

Object oriented style

XMLWriter::startAttributeNs ( string $prefix , string $name , string $uri ) : bool

Procedural style

xmlwriter_start_attribute_ns ( resource $xmlwriter , string $prefix , string $name , string $uri ) : bool

Starts a namespaced attribute.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

prefix

The namespace prefix.

name

The attribute name.

uri

The namespace URI.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::startAttribute() - Create start attribute
  • XMLWriter::endAttribute() - End attribute
  • XMLWriter::writeAttribute() - Write full attribute
  • XMLWriter::writeAttributeNs() - Write full namespaced attribute


Create start attribute

  • « XMLWriter::startAttributeNs
  • XMLWriter::startCdata »
  • PHP Manual
  • XMLWriter Functions
  • Create start attribute

XMLWriter::startAttribute

xmlwriter_start_attribute

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::startAttribute -- xmlwriter_start_attribute — Create start attribute

Description

Object oriented style

XMLWriter::startAttribute ( string $name ) : bool

Procedural style

xmlwriter_start_attribute ( resource $xmlwriter , string $name ) : bool

Starts an attribute.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

name

The attribute name.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::startAttributeNs() - Create start namespaced attribute
  • XMLWriter::endAttribute() - End attribute
  • XMLWriter::writeAttribute() - Write full attribute
  • XMLWriter::writeAttributeNs() - Write full namespaced attribute


Create start CDATA tag

  • « XMLWriter::startAttribute
  • XMLWriter::startComment »
  • PHP Manual
  • XMLWriter Functions
  • Create start CDATA tag

XMLWriter::startCdata

xmlwriter_start_cdata

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::startCdata -- xmlwriter_start_cdata — Create start CDATA tag

Description

Object oriented style

XMLWriter::startCdata ( void ) : bool

Procedural style

xmlwriter_start_cdata ( resource $xmlwriter ) : bool

Starts a CDATA.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::endCdata() - End current CDATA
  • XMLWriter::writeCdata() - Write full CDATA tag


Create start comment

  • « XMLWriter::startCdata
  • XMLWriter::startDocument »
  • PHP Manual
  • XMLWriter Functions
  • Create start comment

XMLWriter::startComment

xmlwriter_start_comment

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 1.0.0)

XMLWriter::startComment -- xmlwriter_start_comment — Create start comment

Description

Object oriented style

XMLWriter::startComment ( void ) : bool

Procedural style

xmlwriter_start_comment ( resource $xmlwriter ) : bool

Starts a comment.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::endComment() - Create end comment
  • XMLWriter::writeComment() - Write full comment tag


Create document tag

  • « XMLWriter::startComment
  • XMLWriter::startDtdAttlist »
  • PHP Manual
  • XMLWriter Functions
  • Create document tag

XMLWriter::startDocument

xmlwriter_start_document

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::startDocument -- xmlwriter_start_document — Create document tag

Description

Object oriented style

XMLWriter::startDocument ([ string $version = 1.0 [, string $encoding = NULL [, string $standalone ]]] ) : bool

Procedural style

xmlwriter_start_document ( resource $xmlwriter [, string $version = 1.0 [, string $encoding = NULL [, string $standalone ]]] ) : bool

Starts a document.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

version

The version number of the document as part of the XML declaration.

encoding

The encoding of the document as part of the XML declaration.

standalone

yes or no.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::endDocument() - End current document


Create start DTD AttList

  • « XMLWriter::startDocument
  • XMLWriter::startDtdElement »
  • PHP Manual
  • XMLWriter Functions
  • Create start DTD AttList

XMLWriter::startDtdAttlist

xmlwriter_start_dtd_attlist

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::startDtdAttlist -- xmlwriter_start_dtd_attlist — Create start DTD AttList

Description

Object oriented style

XMLWriter::startDtdAttlist ( string $name ) : bool

Procedural style

xmlwriter_start_dtd_attlist ( resource $xmlwriter , string $name ) : bool

Starts a DTD attribute list.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

name

The attribute list name.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::endDtdAttlist() - End current DTD AttList
  • XMLWriter::writeDtdAttlist() - Write full DTD AttList tag


Create start DTD element

  • « XMLWriter::startDtdAttlist
  • XMLWriter::startDtdEntity »
  • PHP Manual
  • XMLWriter Functions
  • Create start DTD element

XMLWriter::startDtdElement

xmlwriter_start_dtd_element

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::startDtdElement -- xmlwriter_start_dtd_element — Create start DTD element

Description

Object oriented style

XMLWriter::startDtdElement ( string $qualifiedName ) : bool

Procedural style

xmlwriter_start_dtd_element ( resource $xmlwriter , string $qualifiedName ) : bool

Starts a DTD element.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

qualifiedName

The qualified name of the document type to create.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::endDtdElement() - End current DTD element
  • XMLWriter::writeDtdElement() - Write full DTD element tag


Create start DTD Entity

  • « XMLWriter::startDtdElement
  • XMLWriter::startDtd »
  • PHP Manual
  • XMLWriter Functions
  • Create start DTD Entity

XMLWriter::startDtdEntity

xmlwriter_start_dtd_entity

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::startDtdEntity -- xmlwriter_start_dtd_entity — Create start DTD Entity

Description

Object oriented style

XMLWriter::startDtdEntity ( string $name , bool $isparam ) : bool

Procedural style

xmlwriter_start_dtd_entity ( resource $xmlwriter , string $name , bool $isparam ) : bool

Starts a DTD entity.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

name

The name of the entity.

isparam

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::endDtdEntity() - End current DTD Entity
  • XMLWriter::writeDtdEntity() - Write full DTD Entity tag


Create start DTD tag

  • « XMLWriter::startDtdEntity
  • XMLWriter::startElementNs »
  • PHP Manual
  • XMLWriter Functions
  • Create start DTD tag

XMLWriter::startDtd

xmlwriter_start_dtd

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::startDtd -- xmlwriter_start_dtd — Create start DTD tag

Description

Object oriented style

XMLWriter::startDtd ( string $qualifiedName [, string $publicId [, string $systemId ]] ) : bool

Procedural style

xmlwriter_start_dtd ( resource $xmlwriter , string $qualifiedName [, string $publicId [, string $systemId ]] ) : bool

Starts a DTD.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

qualifiedName

The qualified name of the document type to create.

publicId

The external subset public identifier.

systemId

The external subset system identifier.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::endDtd() - End current DTD
  • XMLWriter::writeDtd() - Write full DTD tag


Create start namespaced element tag

  • « XMLWriter::startDtd
  • XMLWriter::startElement »
  • PHP Manual
  • XMLWriter Functions
  • Create start namespaced element tag

XMLWriter::startElementNs

xmlwriter_start_element_ns

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::startElementNs -- xmlwriter_start_element_ns — Create start namespaced element tag

Description

Object oriented style

XMLWriter::startElementNs ( string $prefix , string $name , string $uri ) : bool

Procedural style

xmlwriter_start_element_ns ( resource $xmlwriter , string $prefix , string $name , string $uri ) : bool

Starts a namespaced element.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

prefix

The namespace prefix.

name

The element name.

uri

The namespace URI.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::endElement() - End current element
  • XMLWriter::writeElementNs() - Write full namespaced element tag


Create start element tag

  • « XMLWriter::startElementNs
  • XMLWriter::startPi »
  • PHP Manual
  • XMLWriter Functions
  • Create start element tag

XMLWriter::startElement

xmlwriter_start_element

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::startElement -- xmlwriter_start_element — Create start element tag

Description

Object oriented style

XMLWriter::startElement ( string $name ) : bool

Procedural style

xmlwriter_start_element ( resource $xmlwriter , string $name ) : bool

Starts an element.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

name

The element name.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::endElement() - End current element
  • XMLWriter::writeElement() - Write full element tag


Create start PI tag

  • « XMLWriter::startElement
  • XMLWriter::text »
  • PHP Manual
  • XMLWriter Functions
  • Create start PI tag

XMLWriter::startPi

xmlwriter_start_pi

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::startPi -- xmlwriter_start_pi — Create start PI tag

Description

Object oriented style

XMLWriter::startPi ( string $target ) : bool

Procedural style

xmlwriter_start_pi ( resource $xmlwriter , string $target ) : bool

Starts a processing instruction tag.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

target

The target of the processing instruction.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::endPi() - End current PI
  • XMLWriter::writePi() - Writes a PI


Write text

  • « XMLWriter::startPi
  • XMLWriter::writeAttributeNs »
  • PHP Manual
  • XMLWriter Functions
  • Write text

XMLWriter::text

xmlwriter_text

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::text -- xmlwriter_text — Write text

Description

Object oriented style

XMLWriter::text ( string $content ) : bool

Procedural style

xmlwriter_text ( resource $xmlwriter , string $content ) : bool

Writes a text.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

content

The contents of the text.

Return Values

Returns TRUE on success or FALSE on failure.


Write full namespaced attribute

  • « XMLWriter::text
  • XMLWriter::writeAttribute »
  • PHP Manual
  • XMLWriter Functions
  • Write full namespaced attribute

XMLWriter::writeAttributeNs

xmlwriter_write_attribute_ns

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::writeAttributeNs -- xmlwriter_write_attribute_ns — Write full namespaced attribute

Description

Object oriented style

XMLWriter::writeAttributeNs ( string $prefix , string $name , string $uri , string $content ) : bool

Procedural style

xmlwriter_write_attribute_ns ( resource $xmlwriter , string $prefix , string $name , string $uri , string $content ) : bool

Writes a full namespaced attribute.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

prefix

The namespace prefix.

name

The attribute name.

uri

The namespace URI.

content

The attribute value.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::writeAttribute() - Write full attribute
  • XMLWriter::startAttribute() - Create start attribute
  • XMLWriter::startAttributeNs() - Create start namespaced attribute
  • XMLWriter::endAttribute() - End attribute


Write full attribute

  • « XMLWriter::writeAttributeNs
  • XMLWriter::writeCdata »
  • PHP Manual
  • XMLWriter Functions
  • Write full attribute

XMLWriter::writeAttribute

xmlwriter_write_attribute

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::writeAttribute -- xmlwriter_write_attribute — Write full attribute

Description

Object oriented style

XMLWriter::writeAttribute ( string $name , string $value ) : bool

Procedural style

xmlwriter_write_attribute ( resource $xmlwriter , string $name , string $value ) : bool

Writes a full attribute.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

name

The name of the attribute.

value

The value of the attribute.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::writeAttributeNs() - Write full namespaced attribute
  • XMLWriter::startAttribute() - Create start attribute
  • XMLWriter::startAttributeNs() - Create start namespaced attribute
  • XMLWriter::endAttribute() - End attribute


Write full CDATA tag

  • « XMLWriter::writeAttribute
  • XMLWriter::writeComment »
  • PHP Manual
  • XMLWriter Functions
  • Write full CDATA tag

XMLWriter::writeCdata

xmlwriter_write_cdata

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::writeCdata -- xmlwriter_write_cdata — Write full CDATA tag

Description

Object oriented style

XMLWriter::writeCdata ( string $content ) : bool

Procedural style

xmlwriter_write_cdata ( resource $xmlwriter , string $content ) : bool

Writes a full CDATA.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

content

The contents of the CDATA.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::startCdata() - Create start CDATA tag
  • XMLWriter::endCdata() - End current CDATA


Write full comment tag

  • « XMLWriter::writeCdata
  • XMLWriter::writeDtdAttlist »
  • PHP Manual
  • XMLWriter Functions
  • Write full comment tag

XMLWriter::writeComment

xmlwriter_write_comment

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::writeComment -- xmlwriter_write_comment — Write full comment tag

Description

Object oriented style

XMLWriter::writeComment ( string $content ) : bool

Procedural style

xmlwriter_write_comment ( resource $xmlwriter , string $content ) : bool

Writes a full comment.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

content

The contents of the comment.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::startComment() - Create start comment
  • XMLWriter::endComment() - Create end comment


Write full DTD AttList tag

  • « XMLWriter::writeComment
  • XMLWriter::writeDtdElement »
  • PHP Manual
  • XMLWriter Functions
  • Write full DTD AttList tag

XMLWriter::writeDtdAttlist

xmlwriter_write_dtd_attlist

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDtdAttlist -- xmlwriter_write_dtd_attlist — Write full DTD AttList tag

Description

Object oriented style

XMLWriter::writeDtdAttlist ( string $name , string $content ) : bool

Procedural style

xmlwriter_write_dtd_attlist ( resource $xmlwriter , string $name , string $content ) : bool

Writes a DTD attribute list.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

name

The name of the DTD attribute list.

content

The content of the DTD attribute list.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::startDtdAttlist() - Create start DTD AttList
  • XMLWriter::endDtdAttlist() - End current DTD AttList


Write full DTD element tag

  • « XMLWriter::writeDtdAttlist
  • XMLWriter::writeDtdEntity »
  • PHP Manual
  • XMLWriter Functions
  • Write full DTD element tag

XMLWriter::writeDtdElement

xmlwriter_write_dtd_element

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDtdElement -- xmlwriter_write_dtd_element — Write full DTD element tag

Description

Object oriented style

XMLWriter::writeDtdElement ( string $name , string $content ) : bool

Procedural style

xmlwriter_write_dtd_element ( resource $xmlwriter , string $name , string $content ) : bool

Writes a full DTD element.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

name

The name of the DTD element.

content

The content of the element.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::startDtdElement() - Create start DTD element
  • XMLWriter::endDtdElement() - End current DTD element


Write full DTD Entity tag

  • « XMLWriter::writeDtdElement
  • XMLWriter::writeDtd »
  • PHP Manual
  • XMLWriter Functions
  • Write full DTD Entity tag

XMLWriter::writeDtdEntity

xmlwriter_write_dtd_entity

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDtdEntity -- xmlwriter_write_dtd_entity — Write full DTD Entity tag

Description

Object oriented style

XMLWriter::writeDtdEntity ( string $name , string $content , bool $pe , string $pubid , string $sysid , string $ndataid ) : bool

Procedural style

xmlwriter_write_dtd_entity ( resource $xmlwriter , string $name , string $content , bool $pe , string $pubid , string $sysid , string $ndataid ) : bool

Writes a full DTD entity.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

name

The name of the entity.

content

The content of the entity.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::startDtdEntity() - Create start DTD Entity
  • XMLWriter::endDtdEntity() - End current DTD Entity


Write full DTD tag

  • « XMLWriter::writeDtdEntity
  • XMLWriter::writeElementNs »
  • PHP Manual
  • XMLWriter Functions
  • Write full DTD tag

XMLWriter::writeDtd

xmlwriter_write_dtd

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::writeDtd -- xmlwriter_write_dtd — Write full DTD tag

Description

Object oriented style

XMLWriter::writeDtd ( string $name [, string $publicId [, string $systemId [, string $subset ]]] ) : bool

Procedural style

xmlwriter_write_dtd ( resource $xmlwriter , string $name [, string $publicId [, string $systemId [, string $subset ]]] ) : bool

Writes a full DTD.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

name

The DTD name.

publicId

The external subset public identifier.

systemId

The external subset system identifier.

subset

The content of the DTD.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::startDtd() - Create start DTD tag
  • XMLWriter::endDtd() - End current DTD


Write full namespaced element tag

  • « XMLWriter::writeDtd
  • XMLWriter::writeElement »
  • PHP Manual
  • XMLWriter Functions
  • Write full namespaced element tag

XMLWriter::writeElementNs

xmlwriter_write_element_ns

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::writeElementNs -- xmlwriter_write_element_ns — Write full namespaced element tag

Description

Object oriented style

XMLWriter::writeElementNs ( string $prefix , string $name , string $uri [, string $content ] ) : bool

Procedural style

xmlwriter_write_element_ns ( resource $xmlwriter , string $prefix , string $name , string $uri [, string $content ] ) : bool

Writes a full namespaced element tag.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

prefix

The namespace prefix.

name

The element name.

uri

The namespace URI.

content

The element contents.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.2.3 | The content parameter became optional.

See Also

  • XMLWriter::startElementNs() - Create start namespaced element tag
  • XMLWriter::endElement() - End current element
  • XMLWriter::writeElement() - Write full element tag


Write full element tag

  • « XMLWriter::writeElementNs
  • XMLWriter::writePi »
  • PHP Manual
  • XMLWriter Functions
  • Write full element tag

XMLWriter::writeElement

xmlwriter_write_element

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::writeElement -- xmlwriter_write_element — Write full element tag

Description

Object oriented style

XMLWriter::writeElement ( string $name [, string $content ] ) : bool

Procedural style

xmlwriter_write_element ( resource $xmlwriter , string $name [, string $content ] ) : bool

Writes a full element tag.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

name

The element name.

content

The element contents.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.2.3 | The content parameter became optional.

See Also

  • XMLWriter::startElement() - Create start element tag
  • XMLWriter::endElement() - End current element
  • XMLWriter::writeElementNs() - Write full namespaced element tag


Writes a PI

  • « XMLWriter::writeElement
  • XMLWriter::writeRaw »
  • PHP Manual
  • XMLWriter Functions
  • Writes a PI

XMLWriter::writePi

xmlwriter_write_pi

(PHP 5 >= 5.1.2, PHP 7, PECL xmlwriter >= 0.1.0)

XMLWriter::writePi -- xmlwriter_write_pi — Writes a PI

Description

Object oriented style

XMLWriter::writePi ( string $target , string $content ) : bool

Procedural style

xmlwriter_write_pi ( resource $xmlwriter , string $target , string $content ) : bool

Writes a processing instruction.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

target

The target of the processing instruction.

content

The content of the processing instruction.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::startPi() - Create start PI tag
  • XMLWriter::endPi() - End current PI


Write a raw XML text

  • « XMLWriter::writePi
  • XSL »
  • PHP Manual
  • XMLWriter Functions
  • Write a raw XML text

XMLWriter::writeRaw

xmlwriter_write_raw

(PHP 5 >= 5.2.0, PHP 7, PECL xmlwriter >= 2.0.4)

XMLWriter::writeRaw -- xmlwriter_write_raw — Write a raw XML text

Description

Object oriented style

XMLWriter::writeRaw ( string $content ) : bool

Procedural style

xmlwriter_write_raw ( resource $xmlwriter , string $content ) : bool

Writes a raw xml text.

Parameters

xmlwriter

Only for procedural calls. The XMLWriter resource that is being modified. This resource comes from a call to xmlwriter_open_uri() or xmlwriter_open_memory().

content

The text string to write.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XMLWriter::text() - Write text


XSL

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
    • Runtime Configuration
    • Resource Types
  • Predefined Constants
  • Examples
    • Example collection.xml and collection.xsl files
    • Error handling with libxml error handling functions
  • XSLTProcessor — The XSLTProcessor class
    • XSLTProcessor::__construct — Creates a new XSLTProcessor object
    • XSLTProcessor::getParameter — Get value of a parameter
    • XSLTProcessor::getSecurityPrefs — Get security preferences
    • XSLTProcessor::hasExsltSupport — Determine if PHP has EXSLT support
    • XSLTProcessor::importStylesheet — Import stylesheet
    • XSLTProcessor::registerPHPFunctions — Enables the ability to use PHP functions as XSLT functions
    • XSLTProcessor::removeParameter — Remove parameter
    • XSLTProcessor::setParameter — Set value for a parameter
    • XSLTProcessor::setProfiling — Sets profiling output file
    • XSLTProcessor::setSecurityPrefs — Set security preferences
    • XSLTProcessor::transformToDoc — Transform to a DOMDocument
    • XSLTProcessor::transformToUri — Transform to URI
    • XSLTProcessor::transformToXml — Transform to XML


Introduction

The XSL extension implements the XSL standard, performing » XSLT transformations using the » libxslt library


Requirements

This extension requires the libxml PHP extension. This means that passing in --enable-libxml is also required, although this is implicitly accomplished because libxml is enabled by default.

This extension uses libxslt which can be found at » http://xmlsoft.org/XSLT/. libxslt version 1.1.0 or greater is required.


Installation

PHP 5 includes the XSL extension by default and can be enabled by adding the argument --with-xsl[=DIR] to your configure line (DIR being the libxslt installation directory).


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.

XSL_CLONE_AUTO (integer)
XSL_CLONE_NEVER (integer)
XSL_CLONE_ALWAYS (integer)
LIBXSLT_VERSION (integer)
libxslt version like 10117. Available as of PHP 5.1.2.
LIBXSLT_DOTTED_VERSION (string)
libxslt version like 1.1.17. Available as of PHP 5.1.2.
LIBEXSLT_VERSION (integer)
libexslt version like 813. Available as of PHP 5.1.2.
LIBEXSLT_DOTTED_VERSION (string)
libexslt version like 1.1.17. Available as of PHP 5.1.2.
XSL_SECPREF_NONE (integer)
Deactivate all security restrictions.
XSL_SECPREF_READ_FILE (integer)
Disallows reading files.
XSL_SECPREF_WRITE_FILE (integer)
Disallows writing files.
XSL_SECPREF_CREATE_DIRECTORY (integer)
Disallows creating directories.
XSL_SECPREF_READ_NETWORK (integer)
Disallows reading network files.
XSL_SECPREF_WRITE_NETWORK (integer)
Disallows writing network files.
XSL_SECPREF_DEFAULT (integer)
Disallows all write access, i.e. a bitmask of XSL_SECPREF_WRITE_NETWORK | XSL_SECPREF_CREATE_DIRECTORY | XSL_SECPREF_WRITE_FILE.


Examples

Table of Contents

  • Example collection.xml and collection.xsl files
  • Error handling with libxml error handling functions


Example collection.xml and collection.xsl files

Many examples in this reference require both an XML and an XSL file. We will use collection.xml and collection.xsl that contains the following:

Example #1 collection.xml

<collection>
 <cd>
  <title>Fight for your mind</title>
  <artist>Ben Harper</artist>
  <year>1995</year>
 </cd>
 <cd>
  <title>Electric Ladyland</title>
  <artist>Jimi Hendrix</artist>
  <year>1997</year>
 </cd>
</collection>

Example #2 collection.xsl

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:param name="owner" select="'Nicolas Eliaszewicz'"/>
 <xsl:output method="html" encoding="iso-8859-1" indent="no"/>
 <xsl:template match="collection">
  Hey! Welcome to <xsl:value-of select="$owner"/>'s sweet CD collection!
  <xsl:apply-templates/>
 </xsl:template>
 <xsl:template match="cd">
  <h1><xsl:value-of select="title"/></h1>
  <h2>by <xsl:value-of select="artist"/> - <xsl:value-of select="year"/></h2>
  <hr />
 </xsl:template>
</xsl:stylesheet>


Error handling with libxml error handling functions

libxml offers a number of functions for handling errors, which can be employed to capture and deal with errors in XSLT processing.

Example #1 fruits.xml

A valid XML file.

<fruits>
 <fruit>Apple</fruit>
 <fruit>Banana</fruit>
 <fruit>Cherry</fruit>
</fruits>

Example #2 fruits.xsl

Contains an invalid select expression.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="html" encoding="utf-8" indent="no"/>
 <xsl:template match="fruits">
  <ul>
   <xsl:apply-templates/>
  </ul>
 </xsl:template>
 <xsl:template match="fruit">
  <li><xsl:value-of select="THIS IS A DELIBERATE ERROR!"/></li>
 </xsl:template>
</xsl:stylesheet>

Example #3 Collating and printing errors

The example below captures and displays libxml errors raised when calling XSLTProcessor::importStyleSheet() with a stylesheet containing an error.

<?php

$xmldoc = new DOMDocument();
$xsldoc = new DOMDocument();
$xsl = new XSLTProcessor();

$xmldoc->loadXML('fruits.xml');
$xsldoc->loadXML('fruits.xsl');

libxml_use_internal_errors(true);
$result = $xsl->importStyleSheet($xsldoc);
if (!$result) {
    foreach (libxml_get_errors() as $error) {
        echo "Libxml error: {$error->message}\n";
    }
}
libxml_use_internal_errors(false);

if ($result) {
    echo $xsl->transformToXML($xmldoc);
}

?>

The above example will output something similar to:

Libxml error: Invalid expression

Libxml error: compilation error: file fruits.xsl line 9 element value-of
Libxml error: xsl:value-of : could not compile select expression 'THIS IS A DELIBERATE ERROR!'


The XSLTProcessor class

(PHP 5, PHP 7)

Introduction

Class synopsis

XSLTProcessor {
/* Methods */
getParameter ( string $namespaceURI , string $localName ) : string
public getSecurityPrefs ( void ) : int
hasExsltSupport ( void ) : bool
public importStylesheet ( object $stylesheet ) : bool
registerPHPFunctions ([ mixed $restrict ] ) : void
removeParameter ( string $namespaceURI , string $localName ) : bool
setParameter ( string $namespace , string $name , string $value ) : bool
setProfiling ( string $filename ) : bool
public setSecurityPrefs ( int $securityPrefs ) : int
transformToDoc ( DOMNode $doc ) : DOMDocument
transformToURI ( DOMDocument $doc , string $uri ) : int
transformToXml ( object $doc ) : string
}

Table of Contents

  • XSLTProcessor::__construct — Creates a new XSLTProcessor object
  • XSLTProcessor::getParameter — Get value of a parameter
  • XSLTProcessor::getSecurityPrefs — Get security preferences
  • XSLTProcessor::hasExsltSupport — Determine if PHP has EXSLT support
  • XSLTProcessor::importStylesheet — Import stylesheet
  • XSLTProcessor::registerPHPFunctions — Enables the ability to use PHP functions as XSLT functions
  • XSLTProcessor::removeParameter — Remove parameter
  • XSLTProcessor::setParameter — Set value for a parameter
  • XSLTProcessor::setProfiling — Sets profiling output file
  • XSLTProcessor::setSecurityPrefs — Set security preferences
  • XSLTProcessor::transformToDoc — Transform to a DOMDocument
  • XSLTProcessor::transformToUri — Transform to URI
  • XSLTProcessor::transformToXml — Transform to XML


Creates a new XSLTProcessor object

  • « XSLTProcessor
  • XSLTProcessor::getParameter »
  • PHP Manual
  • XSLTProcessor
  • Creates a new XSLTProcessor object

XSLTProcessor::__construct

(PHP 5, PHP 7)

XSLTProcessor::__construct — Creates a new XSLTProcessor object

Description

XSLTProcessor::__construct ( void )

Creates a new XSLTProcessor object.

Parameters

This function has no parameters.

Return Values

No value is returned.

Examples

Example #1 Creating an XSLTProcessor

<?php

$xsldoc = new DOMDocument();
$xsldoc->load($xsl_filename);

$xmldoc = new DOMDocument();
$xmldoc->load($xml_filename);

$xsl = new XSLTProcessor();
$xsl->importStyleSheet($xsldoc);
echo $xsl->transformToXML($xmldoc);

?>


Get value of a parameter

  • « XSLTProcessor::__construct
  • XSLTProcessor::getSecurityPrefs »
  • PHP Manual
  • XSLTProcessor
  • Get value of a parameter

XSLTProcessor::getParameter

(PHP 5, PHP 7)

XSLTProcessor::getParameter — Get value of a parameter

Description

XSLTProcessor::getParameter ( string $namespaceURI , string $localName ) : string

Gets a parameter if previously set by XSLTProcessor::setParameter().

Parameters

namespaceURI

The namespace URI of the XSLT parameter.

localName

The local name of the XSLT parameter.

Return Values

The value of the parameter (as a string), or FALSE if it's not set.

See Also

  • XSLTProcessor::setParameter() - Set value for a parameter
  • XSLTProcessor::removeParameter() - Remove parameter


Get security preferences

  • « XSLTProcessor::getParameter
  • XSLTProcessor::hasExsltSupport »
  • PHP Manual
  • XSLTProcessor
  • Get security preferences

XSLTProcessor::getSecurityPrefs

(PHP >= 5.4.0)

XSLTProcessor::getSecurityPrefs — Get security preferences

Description

public XSLTProcessor::getSecurityPrefs ( void ) : int

Gets the security preferences.

Parameters

This function has no parameters.

Return Values

A bitmask consisting of XSL_SECPREF_READ_FILE, XSL_SECPREF_WRITE_FILE, XSL_SECPREF_CREATE_DIRECTORY, XSL_SECPREF_READ_NETWORK, XSL_SECPREF_WRITE_NETWORK.


Determine if PHP has EXSLT support

  • « XSLTProcessor::getSecurityPrefs
  • XSLTProcessor::importStylesheet »
  • PHP Manual
  • XSLTProcessor
  • Determine if PHP has EXSLT support

XSLTProcessor::hasExsltSupport

(PHP 5 >= 5.0.4, PHP 7)

XSLTProcessor::hasExsltSupport — Determine if PHP has EXSLT support

Description

XSLTProcessor::hasExsltSupport ( void ) : bool

This method determines if PHP was built with the » EXSLT library.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Testing EXSLT support

<?php

$proc = new XSLTProcessor;
if (!$proc->hasExsltSupport()) {
    die('EXSLT support not available');
}

// do EXSLT stuff here ..

?>


Import stylesheet

  • « XSLTProcessor::hasExsltSupport
  • XSLTProcessor::registerPHPFunctions »
  • PHP Manual
  • XSLTProcessor
  • Import stylesheet

XSLTProcessor::importStylesheet

(PHP 5, PHP 7)

XSLTProcessor::importStylesheet — Import stylesheet

Description

public XSLTProcessor::importStylesheet ( object $stylesheet ) : bool

This method imports the stylesheet into the XSLTProcessor for transformations.

Parameters

stylesheet

The imported style sheet as a DOMDocument or SimpleXMLElement object.

Return Values

Returns TRUE on success or FALSE on failure.

Changelog

Version | Description
5.2.8 | Accepts SimpleXMLElement again which was broken since PHP 5.2.6.


Enables the ability to use PHP functions as XSLT functions

  • « XSLTProcessor::importStylesheet
  • XSLTProcessor::removeParameter »
  • PHP Manual
  • XSLTProcessor
  • Enables the ability to use PHP functions as XSLT functions

XSLTProcessor::registerPHPFunctions

(PHP 5 >= 5.0.4, PHP 7)

XSLTProcessor::registerPHPFunctions — Enables the ability to use PHP functions as XSLT functions

Description

XSLTProcessor::registerPHPFunctions ([ mixed $restrict ] ) : void

This method enables the ability to use PHP functions as XSLT functions within XSL stylesheets.

Parameters

restrict

Use this parameter to only allow certain functions to be called from XSLT.

This parameter can be either a string (a function name) or an array of functions.

Return Values

No value is returned.

Examples

Example #1 Simple PHP Function call from a stylesheet

<?php
$xml = <<<EOB
<allusers>
 <user>
  <uid>bob</uid>
 </user>
 <user>
  <uid>joe</uid>
 </user>
</allusers>
EOB;
$xsl = <<<EOB
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
     xmlns:php="http://php.net/xsl">
<xsl:output method="html" encoding="utf-8" indent="yes"/>
 <xsl:template match="allusers">
  <html><body>
    <h2>Users</h2>
    <table>
    <xsl:for-each select="user">
      <tr><td>
        <xsl:value-of
             select="php:function('ucfirst',string(uid))"/>
      </td></tr>
    </xsl:for-each>
    </table>
  </body></html>
 </xsl:template>
</xsl:stylesheet>
EOB;
$xmldoc = DOMDocument::loadXML($xml);
$xsldoc = DOMDocument::loadXML($xsl);

$proc = new XSLTProcessor();
$proc->registerPHPFunctions();
$proc->importStyleSheet($xsldoc);
echo $proc->transformToXML($xmldoc);
?>

Changelog

Version | Description
5.1.0 | The restrict parameter was added.


Remove parameter

  • « XSLTProcessor::registerPHPFunctions
  • XSLTProcessor::setParameter »
  • PHP Manual
  • XSLTProcessor
  • Remove parameter

XSLTProcessor::removeParameter

(PHP 5, PHP 7)

XSLTProcessor::removeParameter — Remove parameter

Description

XSLTProcessor::removeParameter ( string $namespaceURI , string $localName ) : bool

Removes a parameter, if set. This will make the processor use the default value for the parameter as specified in the stylesheet.

Parameters

namespaceURI

The namespace URI of the XSLT parameter.

localName

The local name of the XSLT parameter.

Return Values

Returns TRUE on success or FALSE on failure.

See Also

  • XSLTProcessor::setParameter() - Set value for a parameter
  • XSLTProcessor::getParameter() - Get value of a parameter


Set value for a parameter

  • « XSLTProcessor::removeParameter
  • XSLTProcessor::setProfiling »
  • PHP Manual
  • XSLTProcessor
  • Set value for a parameter

XSLTProcessor::setParameter

(PHP 5, PHP 7)

XSLTProcessor::setParameter — Set value for a parameter

Description

XSLTProcessor::setParameter ( string $namespace , string $name , string $value ) : bool
XSLTProcessor::setParameter ( string $namespace , array $options ) : bool

Sets the value of one or more parameters to be used in subsequent transformations with XSLTProcessor. If the parameter doesn't exist in the stylesheet it will be ignored.

Parameters

namespace

The namespace URI of the XSLT parameter.

name

The local name of the XSLT parameter.

value

The new value of the XSLT parameter.

options

An array of name => value pairs. This syntax is available since PHP 5.1.0.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Changing the owner before the transformation

<?php

$collections = array(
    'Marc Rutkowski' => 'marc',
    'Olivier Parmentier' => 'olivier'
);

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attach the xsl rules

foreach ($collections as $name => $file) {
    // Load the XML source
    $xml = new DOMDocument;
    $xml->load('collection_' . $file . '.xml');

    $proc->setParameter('', 'owner', $name);
    $proc->transformToURI($xml, 'file:///tmp/' . $file . '.html');
}

?>

See Also

  • XSLTProcessor::getParameter() - Get value of a parameter
  • XSLTProcessor::removeParameter() - Remove parameter


Sets profiling output file

  • « XSLTProcessor::setParameter
  • XSLTProcessor::setSecurityPrefs »
  • PHP Manual
  • XSLTProcessor
  • Sets profiling output file

XSLTProcessor::setProfiling

(PHP >= 5.3.0)

XSLTProcessor::setProfiling — Sets profiling output file

Description

XSLTProcessor::setProfiling ( string $filename ) : bool

Sets the file to output profiling information when processing a stylesheet.

Parameters

filename

Path to the file to dump profiling information.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Example profiling output

<?php
// Load the XML source
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->setProfiling('profiling.txt');
$proc->importStyleSheet($xsl); // attach the xsl rules

echo trim($proc->transformToDoc($xml)->firstChild->wholeText);
?>

The above code will produce the following information in the profiling file:

number               match                name      mode  Calls Tot 100us Avg

    0                   cd                                    2      3      1
    1           collection                                    1      1      1

                         Total                                3      4


Set security preferences

  • « XSLTProcessor::setProfiling
  • XSLTProcessor::transformToDoc »
  • PHP Manual
  • XSLTProcessor
  • Set security preferences

XSLTProcessor::setSecurityPrefs

(PHP >= 5.4.0)

XSLTProcessor::setSecurityPrefs — Set security preferences

Description

public XSLTProcessor::setSecurityPrefs ( int $securityPrefs ) : int

Sets the security preferences.

Parameters

securityPrefs

The new security preferences. The following constants can be ORed: XSL_SECPREF_READ_FILE, XSL_SECPREF_WRITE_FILE, XSL_SECPREF_CREATE_DIRECTORY, XSL_SECPREF_READ_NETWORK, XSL_SECPREF_WRITE_NETWORK. Alternatively, XSL_SECPREF_NONE or XSL_SECPREF_DEFAULT can be passed.

Return Values

Returns the old security preferences.


Transform to a DOMDocument

  • « XSLTProcessor::setSecurityPrefs
  • XSLTProcessor::transformToUri »
  • PHP Manual
  • XSLTProcessor
  • Transform to a DOMDocument

XSLTProcessor::transformToDoc

(PHP 5, PHP 7)

XSLTProcessor::transformToDoc — Transform to a DOMDocument

Description

XSLTProcessor::transformToDoc ( DOMNode $doc ) : DOMDocument

Transforms the source node to a DOMDocument applying the stylesheet given by the XSLTProcessor::importStylesheet() method.

Parameters

doc

The node to be transformed.

Return Values

The resulting DOMDocument or FALSE on error.

Examples

Example #1 Transforming to a DOMDocument

<?php

// Load the XML source
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attach the xsl rules

echo trim($proc->transformToDoc($xml)->firstChild->wholeText);

?>

The above example will output:

Hey! Welcome to Nicolas Eliaszewicz's sweet CD collection!

See Also

  • XSLTProcessor::transformToUri() - Transform to URI
  • XSLTProcessor::transformToXml() - Transform to XML


Transform to URI

  • « XSLTProcessor::transformToDoc
  • XSLTProcessor::transformToXml »
  • PHP Manual
  • XSLTProcessor
  • Transform to URI

XSLTProcessor::transformToUri

(PHP 5, PHP 7)

XSLTProcessor::transformToUri — Transform to URI

Description

XSLTProcessor::transformToURI ( DOMDocument $doc , string $uri ) : int

Transforms the source node to an URI applying the stylesheet given by the XSLTProcessor::importStylesheet() method.

Parameters

doc

The document to transform.

uri

The target URI for the transformation.

Return Values

Returns the number of bytes written or FALSE if an error occurred.

Examples

Example #1 Transforming to a HTML file

<?php

// Load the XML source
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attach the xsl rules

$proc->transformToURI($xml, 'file:///tmp/out.html');

?>

See Also

  • XSLTProcessor::transformToDoc() - Transform to a DOMDocument
  • XSLTProcessor::transformToXml() - Transform to XML


Transform to XML

  • « XSLTProcessor::transformToUri
  • GUI Extensions »
  • PHP Manual
  • XSLTProcessor
  • Transform to XML

XSLTProcessor::transformToXml

(PHP 5, PHP 7)

XSLTProcessor::transformToXml — Transform to XML

Description

XSLTProcessor::transformToXml ( object $doc ) : string

Transforms the source node to a string applying the stylesheet given by the xsltprocessor::importStylesheet() method.

Parameters

doc

The DOMDocument or SimpleXMLElement object to be transformed.

Return Values

The result of the transformation as a string or FALSE on error.

Examples

Example #1 Transforming to a string

<?php

// Load the XML source
$xml = new DOMDocument;
$xml->load('collection.xml');

$xsl = new DOMDocument;
$xsl->load('collection.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attach the xsl rules

echo $proc->transformToXML($xml);

?>

The above example will output:

Hey! Welcome to Nicolas Eliaszewicz's sweet CD collection!

<h1>Fight for your mind</h1><h2>by Ben Harper - 1995</h2><hr>
<h1>Electric Ladyland</h1><h2>by Jimi Hendrix - 1997</h2><hr>

See Also

  • XSLTProcessor::transformToDoc() - Transform to a DOMDocument
  • XSLTProcessor::transformToUri() - Transform to URI


GUI Extensions

  • UI
    • Introduction
    • Installing/Configuring
    • UI\Point — Represents a position (x,y)
    • UI\Size — Represents dimenstions (width, height)
    • UI\Window — Window
    • UI\Control — Control
    • UI\Menu — Menu
    • UI\MenuItem — Menu Item
    • UI\Area — Area
    • UI\Executor — Execution Scheduler
    • UI\Controls\Tab — Tab Control
    • UI\Controls\Check — Check Control
    • UI\Controls\Button — Button Control
    • UI\Controls\ColorButton — ColorButton Control
    • UI\Controls\Label — Label Control
    • UI\Controls\Entry — Entry Control
    • UI\Controls\MultilineEntry — MultilineEntry Control
    • UI\Controls\Spin — Spin Control
    • UI\Controls\Slider — Slider Control
    • UI\Controls\Progress — Progress Control
    • UI\Controls\Separator — Control Separator
    • UI\Controls\Combo — Combo Control
    • UI\Controls\EditableCombo — EdiableCombo Control
    • UI\Controls\Radio — Radio Control
    • UI\Controls\Picker — Picker Control
    • UI\Controls\Form — Control Form (Arrangement)
    • UI\Controls\Grid — Control Grid (Arrangement)
    • UI\Controls\Group — Control Group (Arrangement)
    • UI\Controls\Box — Control Box (Arrangement)
    • UI\Draw\Pen — Draw Pen
    • UI\Draw\Path — Draw Path
    • UI\Draw\Matrix — Draw Matrix
    • UI\Draw\Color — Color Representation
    • UI\Draw\Stroke — Draw Stroke
    • UI\Draw\Brush — Brushes
    • UI\Draw\Brush\Gradient — Gradient Brushes
    • UI\Draw\Brush\LinearGradient — Linear Gradient
    • UI\Draw\Brush\RadialGradient — Radial Gradient
    • UI\Draw\Text\Layout — Represents Text Layout
    • UI\Draw\Text\Font — Represents a Font
    • UI\Draw\Text\Font\Descriptor — Font Descriptor
    • UI Functions
    • UI\Draw\Text\Font\Weight — Font Weight Settings
    • UI\Draw\Text\Font\Italic — Italic Font Settings
    • UI\Draw\Text\Font\Stretch — Font Stretch Settings
    • UI\Draw\Line\Cap — Line Cap Settings
    • UI\Draw\Line\Join — Line Join Settings
    • UI\Key — Key Identifiers
    • UI\Exception\InvalidArgumentException — InvalidArgumentException
    • UI\Exception\RuntimeException — RuntimeException


UI

  • Introduction
  • Installing/Configuring
    • Requirements
    • Installation
  • UI\Point — Represents a position (x,y)
    • UI\Point::at — Size Coercion
    • UI\Point::__construct — Construct a new Point
    • UI\Point::getX — Retrieves X
    • UI\Point::getY — Retrieves Y
    • UI\Point::setX — Set X
    • UI\Point::setY — Set Y
  • UI\Size — Represents dimenstions (width, height)
    • UI\Size::__construct — Construct a new Size
    • UI\Size::getHeight — Retrieves Height
    • UI\Size::getWidth — Retrives Width
    • UI\Size::of — Point Coercion
    • UI\Size::setHeight — Set Height
    • UI\Size::setWidth — Set Width
  • UI\Window — Window
    • UI\Window::add — Add a Control
    • UI\Window::__construct — Construct a new Window
    • UI\Window::error — Show Error Box
    • UI\Window::getSize — Get Window Size
    • UI\Window::getTitle — Get Title
    • UI\Window::hasBorders — Border Detection
    • UI\Window::hasMargin — Margin Detection
    • UI\Window::isFullScreen — Full Screen Detection
    • UI\Window::msg — Show Message Box
    • UI\Window::onClosing — Closing Callback
    • UI\Window::open — Open Dialog
    • UI\Window::save — Save Dialog
    • UI\Window::setBorders — Border Use
    • UI\Window::setFullScreen — Full Screen Use
    • UI\Window::setMargin — Margin Use
    • UI\Window::setSize — Set Size
    • UI\Window::setTitle — Window Title
  • UI\Control — Control
    • UI\Control::destroy — Destroy Control
    • UI\Control::disable — Disable Control
    • UI\Control::enable — Enable Control
    • UI\Control::getParent — Get Parent Control
    • UI\Control::getTopLevel — Get Top Level
    • UI\Control::hide — Hide Control
    • UI\Control::isEnabled — Determine if Control is enabled
    • UI\Control::isVisible — Determine if Control is visible
    • UI\Control::setParent — Set Parent Control
    • UI\Control::show — Control Show
  • UI\Menu — Menu
    • UI\Menu::append — Append Menu Item
    • UI\Menu::appendAbout — Append About Menu Item
    • UI\Menu::appendCheck — Append Checkable Menu Item
    • UI\Menu::appendPreferences — Append Preferences Menu Item
    • UI\Menu::appendQuit — Append Quit Menu Item
    • UI\Menu::appendSeparator — Append Menu Item Separator
    • UI\Menu::__construct — Construct a new Menu
  • UI\MenuItem — Menu Item
    • UI\MenuItem::disable — Disable Menu Item
    • UI\MenuItem::enable — Enable Menu Item
    • UI\MenuItem::isChecked — Detect Checked
    • UI\MenuItem::onClick — On Click Callback
    • UI\MenuItem::setChecked — Set Checked
  • UI\Area — Area
    • UI\Area::onDraw — Draw Callback
    • UI\Area::onKey — Key Callback
    • UI\Area::onMouse — Mouse Callback
    • UI\Area::redraw — Redraw Area
    • UI\Area::scrollTo — Area Scroll
    • UI\Area::setSize — Set Size
  • UI\Executor — Execution Scheduler
    • UI\Executor::__construct — Construct a new Executor
    • UI\Executor::kill — Stop Executor
    • UI\Executor::onExecute — Execution Callback
    • UI\Executor::setInterval — Interval Manipulation
  • UI\Controls\Tab — Tab Control
    • UI\Controls\Tab::append — Append Page
    • UI\Controls\Tab::delete — Delete Page
    • UI\Controls\Tab::hasMargin — Margin Detection
    • UI\Controls\Tab::insertAt — Insert Page
    • UI\Controls\Tab::pages — Page Count
    • UI\Controls\Tab::setMargin — Set Margin
  • UI\Controls\Check — Check Control
    • UI\Controls\Check::__construct — Construct a new Check
    • UI\Controls\Check::getText — Get Text
    • UI\Controls\Check::isChecked — Checked Detection
    • UI\Controls\Check::onToggle — Toggle Callback
    • UI\Controls\Check::setChecked — Set Checked
    • UI\Controls\Check::setText — Set Text
  • UI\Controls\Button — Button Control
    • UI\Controls\Button::__construct — Construct a new Button
    • UI\Controls\Button::getText — Get Text
    • UI\Controls\Button::onClick — Click Handler
    • UI\Controls\Button::setText — Set Text
  • UI\Controls\ColorButton — ColorButton Control
    • UI\Controls\ColorButton::getColor — Get Color
    • UI\Controls\ColorButton::onChange — Change Handler
    • UI\Controls\ColorButton::setColor — Set Color
  • UI\Controls\Label — Label Control
    • UI\Controls\Label::__construct — Construct a new Label
    • UI\Controls\Label::getText — Get Text
    • UI\Controls\Label::setText — Set Text
  • UI\Controls\Entry — Entry Control
    • UI\Controls\Entry::__construct — Construct a new Entry
    • UI\Controls\Entry::getText — Get Text
    • UI\Controls\Entry::isReadOnly — Detect Read Only
    • UI\Controls\Entry::onChange — Change Handler
    • UI\Controls\Entry::setReadOnly — Set Read Only
    • UI\Controls\Entry::setText — Set Text
  • UI\Controls\MultilineEntry — MultilineEntry Control
    • UI\Controls\MultilineEntry::append — Append Text
    • UI\Controls\MultilineEntry::__construct — Construct a new Multiline Entry
    • UI\Controls\MultilineEntry::getText — Get Text
    • UI\Controls\MultilineEntry::isReadOnly — Read Only Detection
    • UI\Controls\MultilineEntry::onChange — Change Handler
    • UI\Controls\MultilineEntry::setReadOnly — Set Read Only
    • UI\Controls\MultilineEntry::setText — Set Text
  • UI\Controls\Spin — Spin Control
    • UI\Controls\Spin::__construct — Construct a new Spin
    • UI\Controls\Spin::getValue — Get Value
    • UI\Controls\Spin::onChange — Change Handler
    • UI\Controls\Spin::setValue — Set Value
  • UI\Controls\Slider — Slider Control
    • UI\Controls\Slider::__construct — Construct a new Slider
    • UI\Controls\Slider::getValue — Get Value
    • UI\Controls\Slider::onChange — Change Handler
    • UI\Controls\Slider::setValue — Set Value
  • UI\Controls\Progress — Progress Control
    • UI\Controls\Progress::getValue — Get Value
    • UI\Controls\Progress::setValue — Set Value
  • UI\Controls\Separator — Control Separator
    • UI\Controls\Separator::__construct — Construct a new Separator
  • UI\Controls\Combo — Combo Control
    • UI\Controls\Combo::append — Append Option
    • UI\Controls\Combo::getSelected — Get Selected Option
    • UI\Controls\Combo::onSelected — Selected Handler
    • UI\Controls\Combo::setSelected — Set Selected Option
  • UI\Controls\EditableCombo — EdiableCombo Control
    • UI\Controls\EditableCombo::append — Append Option
    • UI\Controls\EditableCombo::getText — Get Text
    • UI\Controls\EditableCombo::onChange — Change Handler
    • UI\Controls\EditableCombo::setText — Set Text
  • UI\Controls\Radio — Radio Control
    • UI\Controls\Radio::append — Append Option
    • UI\Controls\Radio::getSelected — Get Selected Option
    • UI\Controls\Radio::onSelected — Selected Handler
    • UI\Controls\Radio::setSelected — Set Selected Option
  • UI\Controls\Picker — Picker Control
    • UI\Controls\Picker::__construct — Construct a new Picker
  • UI\Controls\Form — Control Form (Arrangement)
    • UI\Controls\Form::append — Append Control
    • UI\Controls\Form::delete — Delete Control
    • UI\Controls\Form::isPadded — Padding Detection
    • UI\Controls\Form::setPadded — Set Padding
  • UI\Controls\Grid — Control Grid (Arrangement)
    • UI\Controls\Grid::append — Append Control
    • UI\Controls\Grid::isPadded — Padding Detection
    • UI\Controls\Grid::setPadded — Set Padding
  • UI\Controls\Group — Control Group (Arrangement)
    • UI\Controls\Group::append — Append Control
    • UI\Controls\Group::__construct — Construct a new Group
    • UI\Controls\Group::getTitle — Get Title
    • UI\Controls\Group::hasMargin — Margin Detection
    • UI\Controls\Group::setMargin — Set Margin
    • UI\Controls\Group::setTitle — Set Title
  • UI\Controls\Box — Control Box (Arrangement)
    • UI\Controls\Box::append — Append Control
    • UI\Controls\Box::__construct — Construct a new Box
    • UI\Controls\Box::delete — Delete Control
    • UI\Controls\Box::getOrientation — Get Orientation
    • UI\Controls\Box::isPadded — Padding Detection
    • UI\Controls\Box::setPadded — Set Padding
  • UI\Draw\Pen — Draw Pen
    • UI\Draw\Pen::clip — Clip a Path
    • UI\Draw\Pen::fill — Fill a Path
    • UI\Draw\Pen::restore — Restore
    • UI\Draw\Pen::save — Save
    • UI\Draw\Pen::stroke — Stroke a Path
    • UI\Draw\Pen::transform — Matrix Transform
    • UI\Draw\Pen::write — Draw Text at Point
  • UI\Draw\Path — Draw Path
    • UI\Draw\Path::addRectangle — Draw a Rectangle
    • UI\Draw\Path::arcTo — Draw an Arc
    • UI\Draw\Path::bezierTo — Draw Bezier Curve
    • UI\Draw\Path::closeFigure — Close Figure
    • UI\Draw\Path::__construct — Construct a new Path
    • UI\Draw\Path::end — Finalize Path
    • UI\Draw\Path::lineTo — Draw a Line
    • UI\Draw\Path::newFigure — Draw Figure
    • UI\Draw\Path::newFigureWithArc — Draw Figure with Arc
  • UI\Draw\Matrix — Draw Matrix
    • UI\Draw\Matrix::invert — Invert Matrix
    • UI\Draw\Matrix::isInvertible — Invertible Detection
    • UI\Draw\Matrix::multiply — Multiply Matrix
    • UI\Draw\Matrix::rotate — Rotate Matrix
    • UI\Draw\Matrix::scale — Scale Matrix
    • UI\Draw\Matrix::skew — Skew Matrix
    • UI\Draw\Matrix::translate — Translate Matrix
  • UI\Draw\Color — Color Representation
    • UI\Draw\Color::__construct — Construct new Color
    • UI\Draw\Color::getChannel — Color Manipulation
    • UI\Draw\Color::setChannel — Color Manipulation
  • UI\Draw\Stroke — Draw Stroke
    • UI\Draw\Stroke::__construct — Construct a new Stroke
    • UI\Draw\Stroke::getCap — Get Line Cap
    • UI\Draw\Stroke::getJoin — Get Line Join
    • UI\Draw\Stroke::getMiterLimit — Get Miter Limit
    • UI\Draw\Stroke::getThickness — Get Thickness
    • UI\Draw\Stroke::setCap — Set Line Cap
    • UI\Draw\Stroke::setJoin — Set Line Join
    • UI\Draw\Stroke::setMiterLimit — Set Miter Limit
    • UI\Draw\Stroke::setThickness — Set Thickness
  • UI\Draw\Brush — Brushes
    • UI\Draw\Brush::__construct — Construct a new Brush
    • UI\Draw\Brush::getColor — Get Color
    • UI\Draw\Brush::setColor — Set Color
  • UI\Draw\Brush\Gradient — Gradient Brushes
    • UI\Draw\Brush\Gradient::addStop — Stop Manipulation
    • UI\Draw\Brush\Gradient::delStop — Stop Manipulation
    • UI\Draw\Brush\Gradient::setStop — Stop Manipulation
  • UI\Draw\Brush\LinearGradient — Linear Gradient
    • UI\Draw\Brush\LinearGradient::__construct — Construct a Linear Gradient
  • UI\Draw\Brush\RadialGradient — Radial Gradient
    • UI\Draw\Brush\RadialGradient::__construct — Construct a new Radial Gradient
  • UI\Draw\Text\Layout — Represents Text Layout
    • UI\Draw\Text\Layout::__construct — Construct a new Text Layout
    • UI\Draw\Text\Layout::setColor — Set Color
    • UI\Draw\Text\Layout::setWidth — Set Width
  • UI\Draw\Text\Font — Represents a Font
    • UI\Draw\Text\Font::__construct — Construct a new Font
    • UI\Draw\Text\Font::getAscent — Font Metrics
    • UI\Draw\Text\Font::getDescent — Font Metrics
    • UI\Draw\Text\Font::getLeading — Font Metrics
    • UI\Draw\Text\Font::getUnderlinePosition — Font Metrics
    • UI\Draw\Text\Font::getUnderlineThickness — Font Metrics
  • UI\Draw\Text\Font\Descriptor — Font Descriptor
    • UI\Draw\Text\Font\Descriptor::__construct — Construct a new Font Descriptor
    • UI\Draw\Text\Font\Descriptor::getFamily — Get Font Family
    • UI\Draw\Text\Font\Descriptor::getItalic — Style Detection
    • UI\Draw\Text\Font\Descriptor::getSize — Size Detection
    • UI\Draw\Text\Font\Descriptor::getStretch — Style Detection
    • UI\Draw\Text\Font\Descriptor::getWeight — Weight Detection
  • UI Functions
    • UI\Draw\Text\Font\fontFamilies — Retrieve Font Families
    • UI\quit — Quit UI Loop
    • UI\run — Enter UI Loop
  • UI\Draw\Text\Font\Weight — Font Weight Settings
  • UI\Draw\Text\Font\Italic — Italic Font Settings
  • UI\Draw\Text\Font\Stretch — Font Stretch Settings
  • UI\Draw\Line\Cap — Line Cap Settings
  • UI\Draw\Line\Join — Line Join Settings
  • UI\Key — Key Identifiers
  • UI\Exception\InvalidArgumentException — InvalidArgumentException
  • UI\Exception\RuntimeException — RuntimeException


Introduction

This extension wraps libui to provide an OO API for the cross platform development of native look-and-feel user interfaces .


  • « Introduction
  • Requirements »
  • PHP Manual
  • UI
  • Installing/Configuring

Installing/Configuring

Table of Contents

  • Requirements
  • Installation


Requirements

Installation requires the libui library, and PHP 7 or newer.

This extension requires the » libui library version 0.1.0 or higher to be installed. See the libui documentation for a list of prerequisites.


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/ui.

Windows binaries (DLL files) for this PECL extension are available from the PECL website.


Represents a position (x,y)

(PHP 7, UI 0.9.9)

Introduction

Points are used throughout UI to represent co-ordinates on a screen, control, or area.

Class synopsis

final UI\Point {
/* Properties */
public $x ;
public $y ;
/* Constructor */
public __construct ( float $x , float $y )
/* Methods */
public static at ( float $point ) : UI\Point
public static at ( UI\Size $size ) : UI\Point
public getX ( void ) : float
public getY ( void ) : float
public setX ( float $point )
public setY ( float $point )
}

Properties

x

Holds the X co-ordinate, can be read/written directly

y

Holds the Y co-ordinate, can be read/written directly

Table of Contents

  • UI\Point::at — Size Coercion
  • UI\Point::__construct — Construct a new Point
  • UI\Point::getX — Retrieves X
  • UI\Point::getY — Retrieves Y
  • UI\Point::setX — Set X
  • UI\Point::setY — Set Y


Size Coercion

  • « UI\Point
  • UI\Point::__construct »
  • PHP Manual
  • UI\Point
  • Size Coercion

UI\Point::at

(PHP 7, UI 1.0.2)

UI\Point::at — Size Coercion

Description

public static UI\Point::at ( float $point ) : UI\Point
public static UI\Point::at ( UI\Size $size ) : UI\Point

Shall return a UI\Point object where x and y are equal to those supplied, either in float or UI\Size form

Parameters

point

The value for x and y

size

The Size to convert

Return Values

The resulting Point


Construct a new Point

  • « UI\Point::at
  • UI\Point::getX »
  • PHP Manual
  • UI\Point
  • Construct a new Point

UI\Point::__construct

(PHP 7, UI 0.9.9)

UI\Point::__construct — Construct a new Point

Description

public UI\Point::__construct ( float $x , float $y )

Construct a new Point using new co-ordinates

Parameters

x

The new X co-ordinate

y

The new Y co-ordinate


Retrieves X

  • « UI\Point::__construct
  • UI\Point::getY »
  • PHP Manual
  • UI\Point
  • Retrieves X

UI\Point::getX

(PHP 7, UI 0.9.9)

UI\Point::getX — Retrieves X

Description

public UI\Point::getX ( void ) : float

Retrieves the X co-ordinate

Parameters

This function has no parameters.

Return Values

The current X co-ordinate


Retrieves Y

  • « UI\Point::getX
  • UI\Point::setX »
  • PHP Manual
  • UI\Point
  • Retrieves Y

UI\Point::getY

(PHP 7, UI 0.9.9)

UI\Point::getY — Retrieves Y

Description

public UI\Point::getY ( void ) : float

Retrieves the Y co-ordinate

Parameters

This function has no parameters.

Return Values

The current Y co-ordinate


Set X

  • « UI\Point::getY
  • UI\Point::setY »
  • PHP Manual
  • UI\Point
  • Set X

UI\Point::setX

(PHP 7, UI 0.9.9)

UI\Point::setX — Set X

Description

public UI\Point::setX ( float $point )

Set the X co-ordinate

Parameters

point

The new X co-ordinate

Return Values


Set Y

  • « UI\Point::setX
  • UI\Size »
  • PHP Manual
  • UI\Point
  • Set Y

UI\Point::setY

(PHP 7, UI 0.9.9)

UI\Point::setY — Set Y

Description

public UI\Point::setY ( float $point )

Set the Y co-ordinate

Parameters

point

The new Y co-ordinate

Return Values


Represents dimenstions (width, height)

(PHP 7, UI 0.9.9)

Introduction

Sizes are used throughout UI to represent the size of a screen, control, or area.

Class synopsis

final UI\Size {
/* Properties */
public $width ;
public $height ;
/* Constructor */
public __construct ( float $width , float $height )
/* Methods */
public getHeight ( void ) : float
public getWidth ( void ) : float
public static of ( float $size ) : UI\Size
public static of ( UI\Point $point ) : UI\Size
public setHeight ( float $size )
public setWidth ( float $size )
}

Properties

width

Holds the width, can be read/written directly

height

Holds the height, can be read/written directly

Table of Contents

  • UI\Size::__construct — Construct a new Size
  • UI\Size::getHeight — Retrieves Height
  • UI\Size::getWidth — Retrives Width
  • UI\Size::of — Point Coercion
  • UI\Size::setHeight — Set Height
  • UI\Size::setWidth — Set Width


Construct a new Size

  • « UI\Size
  • UI\Size::getHeight »
  • PHP Manual
  • UI\Size
  • Construct a new Size

UI\Size::__construct

(PHP 7, UI 0.9.9)

UI\Size::__construct — Construct a new Size

Description

public UI\Size::__construct ( float $width , float $height )

Construct a new Size using new width and height

Parameters

width

The new width

height

The new height


Retrieves Height

  • « UI\Size::__construct
  • UI\Size::getWidth »
  • PHP Manual
  • UI\Size
  • Retrieves Height

UI\Size::getHeight

(PHP 7, UI 0.9.9)

UI\Size::getHeight — Retrieves Height

Description

public UI\Size::getHeight ( void ) : float

Retrieves the Height

Parameters

This function has no parameters.

Return Values

The current Height


Retrives Width

  • « UI\Size::getHeight
  • UI\Size::of »
  • PHP Manual
  • UI\Size
  • Retrives Width

UI\Size::getWidth

(PHP 7, UI 0.9.9)

UI\Size::getWidth — Retrives Width

Description

public UI\Size::getWidth ( void ) : float

Retrieves the Width

Parameters

This function has no parameters.

Return Values

The current Width


Point Coercion

  • « UI\Size::getWidth
  • UI\Size::setHeight »
  • PHP Manual
  • UI\Size
  • Point Coercion

UI\Size::of

(PHP 7, UI 1.0.2)

UI\Size::of — Point Coercion

Description

public static UI\Size::of ( float $size ) : UI\Size
public static UI\Size::of ( UI\Point $point ) : UI\Size

Shall return a UI\Size object where width and height are equal to those supplied, either in float or UI\Point form

Parameters

size

The value for width and height

point

The Point to convert

Return Values

The resulting Size


Set Height

  • « UI\Size::of
  • UI\Size::setWidth »
  • PHP Manual
  • UI\Size
  • Set Height

UI\Size::setHeight

(PHP 7, UI 0.9.9)

UI\Size::setHeight — Set Height

Description

public UI\Size::setHeight ( float $size )

Set new Height

Parameters

size

The new Height

Return Values


Set Width

  • « UI\Size::setHeight
  • UI\Window »
  • PHP Manual
  • UI\Size
  • Set Width

UI\Size::setWidth

(PHP 7, UI 0.9.9)

UI\Size::setWidth — Set Width

Description

public UI\Size::setWidth ( float $size )

Set new Width

Parameters

size

The new Width

Return Values


Window

(PHP 7, UI 0.9.9)

Introduction

Represents a UI Window

Class synopsis

UI\Window extends UI\Control {
/* Properties */
protected $controls ;
/* Constructor */
public __construct ( string $title , Size $size [, bool $menu = FALSE ] )
/* Methods */
public add ( UI\Control $control )
public error ( string $title , string $msg )
public getSize ( void ) : UI\Size
public getTitle ( void ) : string
public hasBorders ( void ) : bool
public hasMargin ( void ) : bool
public isFullScreen ( void ) : bool
public msg ( string $title , string $msg )
protected onClosing ( void ) : int
public open ( void ) : string
public save ( void ) : string
public setBorders ( bool $borders )
public setFullScreen ( bool $full )
public setMargin ( bool $margin )
public setSize ( UI\Size $size )
public setTitle ( string $title )
/* Inherited methods */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control::getParent ( void ) : UI\Control
public UI\Control::getTopLevel ( void ) : int
public UI\Control::hide ( void )
public UI\Control::isEnabled ( void ) : bool
public UI\Control::isVisible ( void ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Properties

controls

Contains controls, should not be manipulated directly

Table of Contents

  • UI\Window::add — Add a Control
  • UI\Window::__construct — Construct a new Window
  • UI\Window::error — Show Error Box
  • UI\Window::getSize — Get Window Size
  • UI\Window::getTitle — Get Title
  • UI\Window::hasBorders — Border Detection
  • UI\Window::hasMargin — Margin Detection
  • UI\Window::isFullScreen — Full Screen Detection
  • UI\Window::msg — Show Message Box
  • UI\Window::onClosing — Closing Callback
  • UI\Window::open — Open Dialog
  • UI\Window::save — Save Dialog
  • UI\Window::setBorders — Border Use
  • UI\Window::setFullScreen — Full Screen Use
  • UI\Window::setMargin — Margin Use
  • UI\Window::setSize — Set Size
  • UI\Window::setTitle — Window Title


Add a Control

  • « UI\Window
  • UI\Window::__construct »
  • PHP Manual
  • UI\Window
  • Add a Control

UI\Window::add

(PHP 7, UI 0.9.9)

UI\Window::add — Add a Control

Description

public UI\Window::add ( UI\Control $control )

Shall add a Control to this Window

Parameters

control

The Control to add

Return Values


Construct a new Window

  • « UI\Window::add
  • UI\Window::error »
  • PHP Manual
  • UI\Window
  • Construct a new Window

UI\Window::__construct

(PHP 7, UI 0.9.9)

UI\Window::__construct — Construct a new Window

Description

public UI\Window::__construct ( string $title , Size $size [, bool $menu = FALSE ] )

Shall construct a new Window

Parameters

title

The title of the Window

size

The size of the Window

menu

Menu switch


Show Error Box

  • « UI\Window::__construct
  • UI\Window::getSize »
  • PHP Manual
  • UI\Window
  • Show Error Box

UI\Window::error

(PHP 7, UI 0.9.9)

UI\Window::error — Show Error Box

Description

public UI\Window::error ( string $title , string $msg )

Shall show an error box

Parameters

title

The title of the error box

msg

The message for the error box


Get Window Size

  • « UI\Window::error
  • UI\Window::getTitle »
  • PHP Manual
  • UI\Window
  • Get Window Size

UI\Window::getSize

(PHP 7, UI 0.9.9)

UI\Window::getSize — Get Window Size

Description

public UI\Window::getSize ( void ) : UI\Size

Shall return the size of this Window

Parameters

This function has no parameters.

Return Values


Get Title

  • « UI\Window::getSize
  • UI\Window::hasBorders »
  • PHP Manual
  • UI\Window
  • Get Title

UI\Window::getTitle

(PHP 7, UI 0.9.9)

UI\Window::getTitle — Get Title

Description

public UI\Window::getTitle ( void ) : string

Shall retrieve the title of this Window

Parameters

This function has no parameters.

Return Values


Border Detection

  • « UI\Window::getTitle
  • UI\Window::hasMargin »
  • PHP Manual
  • UI\Window
  • Border Detection

UI\Window::hasBorders

(PHP 7, UI 0.9.9)

UI\Window::hasBorders — Border Detection

Description

public UI\Window::hasBorders ( void ) : bool

Shall detect if borders are used on this Window

Parameters

This function has no parameters.

Return Values


Margin Detection

  • « UI\Window::hasBorders
  • UI\Window::isFullScreen »
  • PHP Manual
  • UI\Window
  • Margin Detection

UI\Window::hasMargin

(PHP 7, UI 0.9.9)

UI\Window::hasMargin — Margin Detection

Description

public UI\Window::hasMargin ( void ) : bool

Shall detect if margins are used on this Window

Parameters

This function has no parameters.

Return Values


Full Screen Detection

  • « UI\Window::hasMargin
  • UI\Window::msg »
  • PHP Manual
  • UI\Window
  • Full Screen Detection

UI\Window::isFullScreen

(PHP 7, UI 0.9.9)

UI\Window::isFullScreen — Full Screen Detection

Description

public UI\Window::isFullScreen ( void ) : bool

Shall detect if this Window us using the whole screen

Parameters

This function has no parameters.

Return Values


Show Message Box

  • « UI\Window::isFullScreen
  • UI\Window::onClosing »
  • PHP Manual
  • UI\Window
  • Show Message Box

UI\Window::msg

(PHP 7, UI 0.9.9)

UI\Window::msg — Show Message Box

Description

public UI\Window::msg ( string $title , string $msg )

Shall show a message box

Parameters

title

The title of the message box

msg

The message


Closing Callback

  • « UI\Window::msg
  • UI\Window::open »
  • PHP Manual
  • UI\Window
  • Closing Callback

UI\Window::onClosing

(PHP 7, UI 0.9.9)

UI\Window::onClosing — Closing Callback

Description

protected UI\Window::onClosing ( void ) : int

Should gracefully destroy this Window

Parameters

This function has no parameters.

Return Values


Open Dialog

  • « UI\Window::onClosing
  • UI\Window::save »
  • PHP Manual
  • UI\Window
  • Open Dialog

UI\Window::open

(PHP 7, UI 0.9.9)

UI\Window::open — Open Dialog

Description

public UI\Window::open ( void ) : string

Shall show an open file dialog

Parameters

This function has no parameters.

Return Values

Returns the name of the file selected for opening


Save Dialog

  • « UI\Window::open
  • UI\Window::setBorders »
  • PHP Manual
  • UI\Window
  • Save Dialog

UI\Window::save

(PHP 7, UI 0.9.9)

UI\Window::save — Save Dialog

Description

public UI\Window::save ( void ) : string

Shall show a save dialog

Parameters

This function has no parameters.

Return Values

Returns the file name selecting for saving


Border Use

  • « UI\Window::save
  • UI\Window::setFullScreen »
  • PHP Manual
  • UI\Window
  • Border Use

UI\Window::setBorders

(PHP 7, UI 0.9.9)

UI\Window::setBorders — Border Use

Description

public UI\Window::setBorders ( bool $borders )

Shall enable or disable the use of borders on this Window

Parameters

borders


Full Screen Use

  • « UI\Window::setBorders
  • UI\Window::setMargin »
  • PHP Manual
  • UI\Window
  • Full Screen Use

UI\Window::setFullScreen

(PHP 7, UI 0.9.9)

UI\Window::setFullScreen — Full Screen Use

Description

public UI\Window::setFullScreen ( bool $full )

Shall enable or disable the use of the full screen for this Window

Warning

This function is currently not documented; only its argument list is available.

Parameters

full


Margin Use

  • « UI\Window::setFullScreen
  • UI\Window::setSize »
  • PHP Manual
  • UI\Window
  • Margin Use

UI\Window::setMargin

(PHP 7, UI 0.9.9)

UI\Window::setMargin — Margin Use

Description

public UI\Window::setMargin ( bool $margin )

Shall enable or disable the use of margins for this Window

Parameters

margin


Set Size

  • « UI\Window::setMargin
  • UI\Window::setTitle »
  • PHP Manual
  • UI\Window
  • Set Size

UI\Window::setSize

(PHP 7, UI 0.9.9)

UI\Window::setSize — Set Size

Description

public UI\Window::setSize ( UI\Size $size )

Shall set the size of this Window

Parameters

size

Return Values


Window Title

  • « UI\Window::setSize
  • UI\Control »
  • PHP Manual
  • UI\Window
  • Window Title

UI\Window::setTitle

(PHP 7, UI 0.9.9)

UI\Window::setTitle — Window Title

Description

public UI\Window::setTitle ( string $title )

Shall set the title for this Window

Parameters

title

The new title


Control

(PHP 7, UI 0.9.9)

Introduction

This is the closed base class for all UI Controls.

Class synopsis

final UI\Control {
/* Methods */
public destroy ( void )
public disable ( void )
public enable ( void )
public getParent ( void ) : UI\Control
public getTopLevel ( void ) : int
public hide ( void )
public isEnabled ( void ) : bool
public isVisible ( void ) : bool
public setParent ( UI\Control $parent )
public show ( void )
}

Table of Contents

  • UI\Control::destroy — Destroy Control
  • UI\Control::disable — Disable Control
  • UI\Control::enable — Enable Control
  • UI\Control::getParent — Get Parent Control
  • UI\Control::getTopLevel — Get Top Level
  • UI\Control::hide — Hide Control
  • UI\Control::isEnabled — Determine if Control is enabled
  • UI\Control::isVisible — Determine if Control is visible
  • UI\Control::setParent — Set Parent Control
  • UI\Control::show — Control Show


Destroy Control

  • « UI\Control
  • UI\Control::disable »
  • PHP Manual
  • UI\Control
  • Destroy Control

UI\Control::destroy

(PHP 7, UI 0.9.9)

UI\Control::destroy — Destroy Control

Description

public UI\Control::destroy ( void )

Shall destroy this Control

Parameters

This function has no parameters.

Return Values


Disable Control

  • « UI\Control::destroy
  • UI\Control::enable »
  • PHP Manual
  • UI\Control
  • Disable Control

UI\Control::disable

(PHP 7, UI 0.9.9)

UI\Control::disable — Disable Control

Description

public UI\Control::disable ( void )

Shall disable this Control

Parameters

This function has no parameters.

Return Values


Enable Control

  • « UI\Control::disable
  • UI\Control::getParent »
  • PHP Manual
  • UI\Control
  • Enable Control

UI\Control::enable

(PHP 7, UI 0.9.9)

UI\Control::enable — Enable Control

Description

public UI\Control::enable ( void )

Shall enable this Control

Parameters

This function has no parameters.

Return Values


Get Parent Control

  • « UI\Control::enable
  • UI\Control::getTopLevel »
  • PHP Manual
  • UI\Control
  • Get Parent Control

UI\Control::getParent

(PHP 7, UI 0.9.9)

UI\Control::getParent — Get Parent Control

Description

public UI\Control::getParent ( void ) : UI\Control

Shall return the parent Control

Parameters

This function has no parameters.

Return Values


Get Top Level

  • « UI\Control::getParent
  • UI\Control::hide »
  • PHP Manual
  • UI\Control
  • Get Top Level

UI\Control::getTopLevel

(PHP 7, UI 0.9.9)

UI\Control::getTopLevel — Get Top Level

Description

public UI\Control::getTopLevel ( void ) : int

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Hide Control

  • « UI\Control::getTopLevel
  • UI\Control::isEnabled »
  • PHP Manual
  • UI\Control
  • Hide Control

UI\Control::hide

(PHP 7, UI 0.9.9)

UI\Control::hide — Hide Control

Description

public UI\Control::hide ( void )

Shall hide this Control

Parameters

This function has no parameters.

Return Values


Determine if Control is enabled

  • « UI\Control::hide
  • UI\Control::isVisible »
  • PHP Manual
  • UI\Control
  • Determine if Control is enabled

UI\Control::isEnabled

(PHP 7, UI 0.9.9)

UI\Control::isEnabled — Determine if Control is enabled

Description

public UI\Control::isEnabled ( void ) : bool

Shall detect if this Control is enabled

Parameters

This function has no parameters.

Return Values


Determine if Control is visible

  • « UI\Control::isEnabled
  • UI\Control::setParent »
  • PHP Manual
  • UI\Control
  • Determine if Control is visible

UI\Control::isVisible

(PHP 7, UI 0.9.9)

UI\Control::isVisible — Determine if Control is visible

Description

public UI\Control::isVisible ( void ) : bool

Shall detect if this Control is visible

Parameters

This function has no parameters.

Return Values


Set Parent Control

  • « UI\Control::isVisible
  • UI\Control::show »
  • PHP Manual
  • UI\Control
  • Set Parent Control

UI\Control::setParent

(PHP 7, UI 0.9.9)

UI\Control::setParent — Set Parent Control

Description

public UI\Control::setParent ( UI\Control $parent )

Shall set the parent Control of this Control

Parameters

parent

The parent Control

Return Values


Control Show

  • « UI\Control::setParent
  • UI\Menu »
  • PHP Manual
  • UI\Control
  • Control Show

UI\Control::show

(PHP 7, UI 0.9.9)

UI\Control::show — Control Show

Description

public UI\Control::show ( void )

Shall show this Control

Parameters

This function has no parameters.

Return Values


Menu

(PHP 7, UI 0.9.9)

Introduction

Menus must be constructed before the first Window, and can be shown on any Window

Class synopsis

UI\Menu {
/* Constructor */
public __construct ( string $name )
/* Methods */
public append ( string $name [, string $type = UI\MenuItem::class ] ) : UI\MenuItem
public appendAbout ([ string $type = UI\MenuItem::class ] ) : UI\MenuItem
public appendCheck ( string $name [, string $type = UI\MenuItem::class ] ) : UI\MenuItem
public appendPreferences ([ string $type = UI\MenuItem::class ] ) : UI\MenuItem
public appendQuit ([ string $type = UI\MenuItem::class ] ) : UI\MenuItem
public appendSeparator ( void )
}

Table of Contents

  • UI\Menu::append — Append Menu Item
  • UI\Menu::appendAbout — Append About Menu Item
  • UI\Menu::appendCheck — Append Checkable Menu Item
  • UI\Menu::appendPreferences — Append Preferences Menu Item
  • UI\Menu::appendQuit — Append Quit Menu Item
  • UI\Menu::appendSeparator — Append Menu Item Separator
  • UI\Menu::__construct — Construct a new Menu


Append Menu Item

  • « UI\Menu
  • UI\Menu::appendAbout »
  • PHP Manual
  • UI\Menu
  • Append Menu Item

UI\Menu::append

(PHP 7, UI 0.9.9)

UI\Menu::append — Append Menu Item

Description

public UI\Menu::append ( string $name [, string $type = UI\MenuItem::class ] ) : UI\MenuItem

Shall append a new Menu Item

Parameters

name

The name (text) for the new item

type

The type for the new item

Return Values

A constructed object of the given type


Append About Menu Item

  • « UI\Menu::append
  • UI\Menu::appendCheck »
  • PHP Manual
  • UI\Menu
  • Append About Menu Item

UI\Menu::appendAbout

(PHP 7, UI 0.9.9)

UI\Menu::appendAbout — Append About Menu Item

Description

public UI\Menu::appendAbout ([ string $type = UI\MenuItem::class ] ) : UI\MenuItem

Shall append an About menu item

Parameters

type

The type for the new item

Return Values

A constructed About menu item of the given type


Append Checkable Menu Item

  • « UI\Menu::appendAbout
  • UI\Menu::appendPreferences »
  • PHP Manual
  • UI\Menu
  • Append Checkable Menu Item

UI\Menu::appendCheck

(PHP 7, UI 0.9.9)

UI\Menu::appendCheck — Append Checkable Menu Item

Description

public UI\Menu::appendCheck ( string $name [, string $type = UI\MenuItem::class ] ) : UI\MenuItem

Shall append a checkable menu item

Parameters

name

The name (text) for the new item

type

The type for the new item

Return Values

A constructed checkable menu item of the given type


Append Preferences Menu Item

  • « UI\Menu::appendCheck
  • UI\Menu::appendQuit »
  • PHP Manual
  • UI\Menu
  • Append Preferences Menu Item

UI\Menu::appendPreferences

(PHP 7, UI 0.9.9)

UI\Menu::appendPreferences — Append Preferences Menu Item

Description

public UI\Menu::appendPreferences ([ string $type = UI\MenuItem::class ] ) : UI\MenuItem

Shall append a Preferences menu item

Parameters

type

The type for the new item

Return Values

A constructed Preferences menu item of the given type


Append Quit Menu Item

  • « UI\Menu::appendPreferences
  • UI\Menu::appendSeparator »
  • PHP Manual
  • UI\Menu
  • Append Quit Menu Item

UI\Menu::appendQuit

(PHP 7, UI 0.9.9)

UI\Menu::appendQuit — Append Quit Menu Item

Description

public UI\Menu::appendQuit ([ string $type = UI\MenuItem::class ] ) : UI\MenuItem

Shall append a Quit menu item

Parameters

type

The type for the new item

Return Values

A constructed Quit menu item of the given type


Append Menu Item Separator

  • « UI\Menu::appendQuit
  • UI\Menu::__construct »
  • PHP Manual
  • UI\Menu
  • Append Menu Item Separator

UI\Menu::appendSeparator

(PHP 7, UI 0.9.9)

UI\Menu::appendSeparator — Append Menu Item Separator

Description

public UI\Menu::appendSeparator ( void )

Shall append a separator

Parameters

This function has no parameters.


Construct a new Menu

  • « UI\Menu::appendSeparator
  • UI\MenuItem »
  • PHP Manual
  • UI\Menu
  • Construct a new Menu

UI\Menu::__construct

(PHP 7, UI 0.9.9)

UI\Menu::__construct — Construct a new Menu

Description

public UI\Menu::__construct ( string $name )

Shall construct a new Menu

Parameters

name

The name (text) for the menu


Menu Item

(PHP 7, UI 0.9.9)

Introduction

Menu Items should only be created by the Menu

Class synopsis

UI\MenuItem {
/* Methods */
public disable ( void )
public enable ( void )
public isChecked ( void ) : bool
protected onClick ( void )
public setChecked ( bool $checked )
}

Table of Contents

  • UI\MenuItem::disable — Disable Menu Item
  • UI\MenuItem::enable — Enable Menu Item
  • UI\MenuItem::isChecked — Detect Checked
  • UI\MenuItem::onClick — On Click Callback
  • UI\MenuItem::setChecked — Set Checked


Disable Menu Item

  • « UI\MenuItem
  • UI\MenuItem::enable »
  • PHP Manual
  • UI\MenuItem
  • Disable Menu Item

UI\MenuItem::disable

(PHP 7, UI 0.9.9)

UI\MenuItem::disable — Disable Menu Item

Description

public UI\MenuItem::disable ( void )

Shall disable this Menu Item

Parameters

This function has no parameters.


Enable Menu Item

  • « UI\MenuItem::disable
  • UI\MenuItem::isChecked »
  • PHP Manual
  • UI\MenuItem
  • Enable Menu Item

UI\MenuItem::enable

(PHP 7, UI 0.9.9)

UI\MenuItem::enable — Enable Menu Item

Description

public UI\MenuItem::enable ( void )

Shall enable this Menu Item

Parameters

This function has no parameters.


Detect Checked

  • « UI\MenuItem::enable
  • UI\MenuItem::onClick »
  • PHP Manual
  • UI\MenuItem
  • Detect Checked

UI\MenuItem::isChecked

(PHP 7, UI 0.9.9)

UI\MenuItem::isChecked — Detect Checked

Description

public UI\MenuItem::isChecked ( void ) : bool

Shall detect if this Menu Item is checked

Parameters

This function has no parameters.


On Click Callback

  • « UI\MenuItem::isChecked
  • UI\MenuItem::setChecked »
  • PHP Manual
  • UI\MenuItem
  • On Click Callback

UI\MenuItem::onClick

(PHP 7, UI 0.9.9)

UI\MenuItem::onClick — On Click Callback

Description

protected UI\MenuItem::onClick ( void )

Shall be executed when this Menu Item is clicked

Parameters

This function has no parameters.


Set Checked

  • « UI\MenuItem::onClick
  • UI\Area »
  • PHP Manual
  • UI\MenuItem
  • Set Checked

UI\MenuItem::setChecked

(PHP 7, UI 0.9.9)

UI\MenuItem::setChecked — Set Checked

Description

public UI\MenuItem::setChecked ( bool $checked )

Shall set the checked status of this Menu Item

Parameters

checked

The new status


Area

(PHP 7, UI 0.9.9)

Introduction

An Area represents a canvas which can be used to draw, and respond to mouse and key events.

Class synopsis

UI\Area extends UI\Control {
/* Constants */
const integer Ctrl ;
const integer Alt ;
const integer Shift ;
const integer Super ;
const integer Down ;
const integer Up ;
/* Methods */
protected onDraw ( UI\Draw\Pen $pen , UI\Size $areaSize , UI\Point $clipPoint , UI\Size $clipSize )
protected onKey ( string $key , int $ext , int $flags )
protected onMouse ( UI\Point $areaPoint , UI\Size $areaSize , int $flags )
public redraw ( void )
public scrollTo ( UI\Point $point , UI\Size $size )
public setSize ( UI\Size $size )
/* Inherited methods */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control::getParent ( void ) : UI\Control
public UI\Control::getTopLevel ( void ) : int
public UI\Control::hide ( void )
public UI\Control::isEnabled ( void ) : bool
public UI\Control::isVisible ( void ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Predefined Constants

UI\Area::Ctrl

Shall be set in the modifiers passed to key and mouse events when the CTRL key is active

UI\Area::Alt

Shall be set in the modifiers passed to key and mouse events when the ALT key is active

UI\Area::Shift

Shall be set in the modifiers passed to key and mouse events when the SHIFT key is active

UI\Area::Super

UI\Area::Down

Shall be set in the modifiers passed to key and mouse events

UI\Area::Up

Shall be set in the modifiers passed to key and mouse events

Table of Contents

  • UI\Area::onDraw — Draw Callback
  • UI\Area::onKey — Key Callback
  • UI\Area::onMouse — Mouse Callback
  • UI\Area::redraw — Redraw Area
  • UI\Area::scrollTo — Area Scroll
  • UI\Area::setSize — Set Size


Draw Callback

  • « UI\Area
  • UI\Area::onKey »
  • PHP Manual
  • UI\Area
  • Draw Callback

UI\Area::onDraw

(PHP 7, UI 0.9.9)

UI\Area::onDraw — Draw Callback

Description

protected UI\Area::onDraw ( UI\Draw\Pen $pen , UI\Size $areaSize , UI\Point $clipPoint , UI\Size $clipSize )

Shall be invoked when this Area requires redrawing

Parameters

pen

A Pen suitable for drawing in this Area

areaSize

The size of the Area

clipPoint

The clip point of the Area

clipSize

The clip size of the Area


Key Callback

  • « UI\Area::onDraw
  • UI\Area::onMouse »
  • PHP Manual
  • UI\Area
  • Key Callback

UI\Area::onKey

(PHP 7, UI 0.9.9)

UI\Area::onKey — Key Callback

Description

protected UI\Area::onKey ( string $key , int $ext , int $flags )

Shall be executed on key events

Parameters

key

The key pressed

ext

The extended key pressed

flags

Event modifiers

Return Values


Mouse Callback

  • « UI\Area::onKey
  • UI\Area::redraw »
  • PHP Manual
  • UI\Area
  • Mouse Callback

UI\Area::onMouse

(PHP 7, UI 0.9.9)

UI\Area::onMouse — Mouse Callback

Description

protected UI\Area::onMouse ( UI\Point $areaPoint , UI\Size $areaSize , int $flags )

Shall be executed on mouse events

Parameters

areaPoint

The co-ordinates of the event

areaSize

The size of the area of the event

flags

Event modifiers


Redraw Area

  • « UI\Area::onMouse
  • UI\Area::scrollTo »
  • PHP Manual
  • UI\Area
  • Redraw Area

UI\Area::redraw

(PHP 7, UI 0.9.9)

UI\Area::redraw — Redraw Area

Description

public UI\Area::redraw ( void )

Requests that this Area is redrawn

Parameters

This function has no parameters.

Return Values


Area Scroll

  • « UI\Area::redraw
  • UI\Area::setSize »
  • PHP Manual
  • UI\Area
  • Area Scroll

UI\Area::scrollTo

(PHP 7, UI 0.9.9)

UI\Area::scrollTo — Area Scroll

Description

public UI\Area::scrollTo ( UI\Point $point , UI\Size $size )

Scroll this Area

Parameters

point

The point to scroll to

size

The size of the scroll pane


Set Size

  • « UI\Area::scrollTo
  • UI\Executor »
  • PHP Manual
  • UI\Area
  • Set Size

UI\Area::setSize

(PHP 7, UI 0.9.9)

UI\Area::setSize — Set Size

Description

public UI\Area::setSize ( UI\Size $size )

Sets the size of this Area

Parameters

size

The new size


Execution Scheduler

(PHP 7, UI 2.0.0)

Introduction

This facility schedules repetitive execution of a callback, useful for animations and other such activities.

Class synopsis

abstract UI\Executor {
/* Constructor */
public __construct ( void )
public __construct ( int $microseconds )
public __construct ( int $seconds , int $microseconds )
/* Methods */
public kill ( void ) : void
abstract protected onExecute ( void ) : void
public setInterval ( int $microseconds ) : bool
public setInterval ( int $seconds , int $microseconds ) : bool
}

Table of Contents

  • UI\Executor::__construct — Construct a new Executor
  • UI\Executor::kill — Stop Executor
  • UI\Executor::onExecute — Execution Callback
  • UI\Executor::setInterval — Interval Manipulation


Construct a new Executor

  • « UI\Executor
  • UI\Executor::kill »
  • PHP Manual
  • UI\Executor
  • Construct a new Executor

UI\Executor::__construct

(PHP 7, UI 2.0.0)

UI\Executor::__construct — Construct a new Executor

Description

public UI\Executor::__construct ( void )
public UI\Executor::__construct ( int $microseconds )
public UI\Executor::__construct ( int $seconds , int $microseconds )

Shall construct an executor with the given interval, will not start executing until main loop is entered

Parameters

seconds

Seconds between executions

microseconds

Microseconds between executions


Stop Executor

  • « UI\Executor::__construct
  • UI\Executor::onExecute »
  • PHP Manual
  • UI\Executor
  • Stop Executor

UI\Executor::kill

(PHP 7, UI 2.0.0)

UI\Executor::kill — Stop Executor

Description

public UI\Executor::kill ( void ) : void

Shall stop an executor, the executor cannot be restarted

Parameters

This function has no parameters.

Return Values


Execution Callback

  • « UI\Executor::kill
  • UI\Executor::setInterval »
  • PHP Manual
  • UI\Executor
  • Execution Callback

UI\Executor::onExecute

(PHP 7, UI 2.0.0)

UI\Executor::onExecute — Execution Callback

Description

abstract protected UI\Executor::onExecute ( void ) : void

Shall be repetitively queued for execution in the main thread

Parameters

This function has no parameters.

Return Values


Interval Manipulation

  • « UI\Executor::onExecute
  • UI\Controls\Tab »
  • PHP Manual
  • UI\Executor
  • Interval Manipulation

UI\Executor::setInterval

(PHP 7, UI 2.0.0)

UI\Executor::setInterval — Interval Manipulation

Description

public UI\Executor::setInterval ( int $microseconds ) : bool
public UI\Executor::setInterval ( int $seconds , int $microseconds ) : bool

Shall set the new interval. An interval of 0 will pause the executor until a new interval has been set

Parameters

seconds

microseconds

Return Values

Indication of success


Tab Control

(PHP 7, UI 0.9.9)

Introduction

A Tab can contain many pages of Controls, each with a title, each selectable by the user.

Class synopsis

UI\Controls\Tab extends UI\Control {
/* Properties */
protected $controls ;
/* Methods */
public append ( string $name , UI\Control $control ) : int
public delete ( int $index ) : bool
public hasMargin ( int $page ) : bool
public insertAt ( string $name , int $page , UI\Control $control )
public pages ( void ) : int
public setMargin ( int $page , bool $margin )
/* Inherited methods */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control::getParent ( void ) : UI\Control
public UI\Control::getTopLevel ( void ) : int
public UI\Control::hide ( void )
public UI\Control::isEnabled ( void ) : bool
public UI\Control::isVisible ( void ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Properties

controls

Contains controls, should not be manipulated directly

Table of Contents

  • UI\Controls\Tab::append — Append Page
  • UI\Controls\Tab::delete — Delete Page
  • UI\Controls\Tab::hasMargin — Margin Detection
  • UI\Controls\Tab::insertAt — Insert Page
  • UI\Controls\Tab::pages — Page Count
  • UI\Controls\Tab::setMargin — Set Margin


Append Page

  • « UI\Controls\Tab
  • UI\Controls\Tab::delete »
  • PHP Manual
  • UI\Controls\Tab
  • Append Page

UI\Controls\Tab::append

(PHP 7, UI 0.9.9)

UI\Controls\Tab::append — Append Page

Description

public UI\Controls\Tab::append ( string $name , UI\Control $control ) : int

Append a new page to this Tab

Parameters

name

The name for the new page

control

The control for the new page

Return Values

Shall return the index of the appended control, may be 0


Delete Page

  • « UI\Controls\Tab::append
  • UI\Controls\Tab::hasMargin »
  • PHP Manual
  • UI\Controls\Tab
  • Delete Page

UI\Controls\Tab::delete

(PHP 7, UI 0.9.9)

UI\Controls\Tab::delete — Delete Page

Description

public UI\Controls\Tab::delete ( int $index ) : bool

Shall remove the selected page from this Tab

Parameters

index

The index of the page to remove

Return Values

Indication of success


Margin Detection

  • « UI\Controls\Tab::delete
  • UI\Controls\Tab::insertAt »
  • PHP Manual
  • UI\Controls\Tab
  • Margin Detection

UI\Controls\Tab::hasMargin

(PHP 7, UI 0.9.9)

UI\Controls\Tab::hasMargin — Margin Detection

Description

public UI\Controls\Tab::hasMargin ( int $page ) : bool

Shall detect if the given page has a margin.

Parameters

page

The index of the page

Return Values


Insert Page

  • « UI\Controls\Tab::hasMargin
  • UI\Controls\Tab::pages »
  • PHP Manual
  • UI\Controls\Tab
  • Insert Page

UI\Controls\Tab::insertAt

(PHP 7, UI 0.9.9)

UI\Controls\Tab::insertAt — Insert Page

Description

public UI\Controls\Tab::insertAt ( string $name , int $page , UI\Control $control )

Shall insert a new page into this Tab

Parameters

name

The name for the new page

page

The index to perform the insertion before

control

The control for the new page


Page Count

  • « UI\Controls\Tab::insertAt
  • UI\Controls\Tab::setMargin »
  • PHP Manual
  • UI\Controls\Tab
  • Page Count

UI\Controls\Tab::pages

(PHP 7, UI 0.9.9)

UI\Controls\Tab::pages — Page Count

Description

public UI\Controls\Tab::pages ( void ) : int

Shall return the number of pages in this Tab

Parameters

This function has no parameters.

Return Values

The number of pages in this Tab


Set Margin

  • « UI\Controls\Tab::pages
  • UI\Controls\Check »
  • PHP Manual
  • UI\Controls\Tab
  • Set Margin

UI\Controls\Tab::setMargin

(PHP 7, UI 0.9.9)

UI\Controls\Tab::setMargin — Set Margin

Description

public UI\Controls\Tab::setMargin ( int $page , bool $margin )

Shall enable or disable margins on the selected page

Parameters

page

The page to select

margin

Margin switch


Check Control

(PHP 7, UI 0.9.9)

Introduction

A Check is a labelled checkable box

Class synopsis

UI\Controls\Check extends UI\Control {
/* Constructor */
public __construct ( string $text )
/* Methods */
public getText ( void ) : string
public isChecked ( void ) : bool
protected onToggle ( void )
public setChecked ( bool $checked )
public setText ( string $text )
/* Inherited methods */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control::getParent ( void ) : UI\Control
public UI\Control::getTopLevel ( void ) : int
public UI\Control::hide ( void )
public UI\Control::isEnabled ( void ) : bool
public UI\Control::isVisible ( void ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Table of Contents

  • UI\Controls\Check::__construct — Construct a new Check
  • UI\Controls\Check::getText — Get Text
  • UI\Controls\Check::isChecked — Checked Detection
  • UI\Controls\Check::onToggle — Toggle Callback
  • UI\Controls\Check::setChecked — Set Checked
  • UI\Controls\Check::setText — Set Text


Construct a new Check

  • « UI\Controls\Check
  • UI\Controls\Check::getText »
  • PHP Manual
  • UI\Controls\Check
  • Construct a new Check

UI\Controls\Check::__construct

(PHP 7, UI 0.9.9)

UI\Controls\Check::__construct — Construct a new Check

Description

public UI\Controls\Check::__construct ( string $text )

Shall construct a new Check

Parameters

text

The text (label) for the Check box


Get Text

  • « UI\Controls\Check::__construct
  • UI\Controls\Check::isChecked »
  • PHP Manual
  • UI\Controls\Check
  • Get Text

UI\Controls\Check::getText

(PHP 7, UI 0.9.9)

UI\Controls\Check::getText — Get Text

Description

public UI\Controls\Check::getText ( void ) : string

Shall return the text (label) for this Check

Parameters

This function has no parameters.

Return Values

The current text (label)


Checked Detection

  • « UI\Controls\Check::getText
  • UI\Controls\Check::onToggle »
  • PHP Manual
  • UI\Controls\Check
  • Checked Detection

UI\Controls\Check::isChecked

(PHP 7, UI 0.9.9)

UI\Controls\Check::isChecked — Checked Detection

Description

public UI\Controls\Check::isChecked ( void ) : bool

Shall detect the status of this Check

Parameters

This function has no parameters.


Toggle Callback

  • « UI\Controls\Check::isChecked
  • UI\Controls\Check::setChecked »
  • PHP Manual
  • UI\Controls\Check
  • Toggle Callback

UI\Controls\Check::onToggle

(PHP 7, UI 0.9.9)

UI\Controls\Check::onToggle — Toggle Callback

Description

protected UI\Controls\Check::onToggle ( void )

Shall be executed when the status of this Check is changed

Parameters

This function has no parameters.


Set Checked

  • « UI\Controls\Check::onToggle
  • UI\Controls\Check::setText »
  • PHP Manual
  • UI\Controls\Check
  • Set Checked

UI\Controls\Check::setChecked

(PHP 7, UI 0.9.9)

UI\Controls\Check::setChecked — Set Checked

Description

public UI\Controls\Check::setChecked ( bool $checked )

Shall change the status of this Check

Parameters

checked

The new status


Set Text

  • « UI\Controls\Check::setChecked
  • UI\Controls\Button »
  • PHP Manual
  • UI\Controls\Check
  • Set Text

UI\Controls\Check::setText

(PHP 7, UI 0.9.9)

UI\Controls\Check::setText — Set Text

Description

public UI\Controls\Check::setText ( string $text )

Shall set the text (label) for this Check

Parameters

text

The new text (label)


Button Control

(PHP 7, UI 0.9.9)

Introduction

Represents a labelled clickable button

Class synopsis

UI\Controls\Button extends UI\Control {
/* Constructor */
public __construct ( string $text )
/* Methods */
public getText ( void ) : string
protected onClick ( void )
public setText ( string $text )
/* Inherited methods */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control::getParent ( void ) : UI\Control
public UI\Control::getTopLevel ( void ) : int
public UI\Control::hide ( void )
public UI\Control::isEnabled ( void ) : bool
public UI\Control::isVisible ( void ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Table of Contents

  • UI\Controls\Button::__construct — Construct a new Button
  • UI\Controls\Button::getText — Get Text
  • UI\Controls\Button::onClick — Click Handler
  • UI\Controls\Button::setText — Set Text


Construct a new Button

  • « UI\Controls\Button
  • UI\Controls\Button::getText »
  • PHP Manual
  • UI\Controls\Button
  • Construct a new Button

UI\Controls\Button::__construct

(PHP 7, UI 0.9.9)

UI\Controls\Button::__construct — Construct a new Button

Description

public UI\Controls\Button::__construct ( string $text )

Shall construct a new Button

Parameters

text

The text (label) for this Button


Get Text

  • « UI\Controls\Button::__construct
  • UI\Controls\Button::onClick »
  • PHP Manual
  • UI\Controls\Button
  • Get Text

UI\Controls\Button::getText

(PHP 7, UI 0.9.9)

UI\Controls\Button::getText — Get Text

Description

public UI\Controls\Button::getText ( void ) : string

Shall retrieve the text (label) for this Button

Parameters

This function has no parameters.

Return Values

The current text (label)


Click Handler

  • « UI\Controls\Button::getText
  • UI\Controls\Button::setText »
  • PHP Manual
  • UI\Controls\Button
  • Click Handler

UI\Controls\Button::onClick

(PHP 7, UI 0.9.9)

UI\Controls\Button::onClick — Click Handler

Description

protected UI\Controls\Button::onClick ( void )

Shall be executed when this Button is clicked

Parameters

This function has no parameters.


Set Text

  • « UI\Controls\Button::onClick
  • UI\Controls\ColorButton »
  • PHP Manual
  • UI\Controls\Button
  • Set Text

UI\Controls\Button::setText

(PHP 7, UI 0.9.9)

UI\Controls\Button::setText — Set Text

Description

public UI\Controls\Button::setText ( string $text )

Shall set the text (label) for this Button

Parameters

text

The new text (label)


ColorButton Control

(PHP 7, UI 0.9.9)

Introduction

A Color Button is a button which displays a color picker when clicked

Class synopsis

UI\Controls\ColorButton extends UI\Control {
/* Methods */
public getColor ( void ) : UI\Color
protected onChange ( void )
public setColor ( UI\Draw\Color $color )
public setColor ( int $color )
/* Inherited methods */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control::getParent ( void ) : UI\Control
public UI\Control::getTopLevel ( void ) : int
public UI\Control::hide ( void )
public UI\Control::isEnabled ( void ) : bool
public UI\Control::isVisible ( void ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Table of Contents

  • UI\Controls\ColorButton::getColor — Get Color
  • UI\Controls\ColorButton::onChange — Change Handler
  • UI\Controls\ColorButton::setColor — Set Color


Get Color

  • « UI\Controls\ColorButton
  • UI\Controls\ColorButton::onChange »
  • PHP Manual
  • UI\Controls\ColorButton
  • Get Color

UI\Controls\ColorButton::getColor

(PHP 7, UI 0.9.9)

UI\Controls\ColorButton::getColor — Get Color

Description

public UI\Controls\ColorButton::getColor ( void ) : UI\Color

Shall retrieve the currently selected Color

Parameters

This function has no parameters.

Return Values


Change Handler

  • « UI\Controls\ColorButton::getColor
  • UI\Controls\ColorButton::setColor »
  • PHP Manual
  • UI\Controls\ColorButton
  • Change Handler

UI\Controls\ColorButton::onChange

(PHP 7, UI 0.9.9)

UI\Controls\ColorButton::onChange — Change Handler

Description

protected UI\Controls\ColorButton::onChange ( void )

Shall be executed when the selected Color is changed

Parameters

This function has no parameters.


Set Color

  • « UI\Controls\ColorButton::onChange
  • UI\Controls\Label »
  • PHP Manual
  • UI\Controls\ColorButton
  • Set Color

UI\Controls\ColorButton::setColor

(PHP 7, UI 0.9.9)

UI\Controls\ColorButton::setColor — Set Color

Description

public UI\Controls\ColorButton::setColor ( UI\Draw\Color $color )
public UI\Controls\ColorButton::setColor ( int $color )

Shall set the currently selected Color

Parameters

color

The new color


Label Control

(PHP 7, UI 0.9.9)

Introduction

A Label is a single line of text, meant to identify, for the user, some element of the interface.

Class synopsis

UI\Controls\Label extends UI\Control {
/* Constructor */
public __construct ( string $text )
/* Methods */
public getText ( void ) : string
public setText ( string $text )
/* Inherited methods */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control::getParent ( void ) : UI\Control
public UI\Control::getTopLevel ( void ) : int
public UI\Control::hide ( void )
public UI\Control::isEnabled ( void ) : bool
public UI\Control::isVisible ( void ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Table of Contents

  • UI\Controls\Label::__construct — Construct a new Label
  • UI\Controls\Label::getText — Get Text
  • UI\Controls\Label::setText — Set Text


Construct a new Label

  • « UI\Controls\Label
  • UI\Controls\Label::getText »
  • PHP Manual
  • UI\Controls\Label
  • Construct a new Label

UI\Controls\Label::__construct

(PHP 7, UI 0.9.9)

UI\Controls\Label::__construct — Construct a new Label

Description

public UI\Controls\Label::__construct ( string $text )

Shall construct a new Label

Parameters

text

The text for this label


Get Text

  • « UI\Controls\Label::__construct
  • UI\Controls\Label::setText »
  • PHP Manual
  • UI\Controls\Label
  • Get Text

UI\Controls\Label::getText

(PHP 7, UI 0.9.9)

UI\Controls\Label::getText — Get Text

Description

public UI\Controls\Label::getText ( void ) : string

Shall return the current text for this Label

Warning

This function is currently not documented; only its argument list is available.

Parameters

This function has no parameters.

Return Values


Set Text

  • « UI\Controls\Label::getText
  • UI\Controls\Entry »
  • PHP Manual
  • UI\Controls\Label
  • Set Text

UI\Controls\Label::setText

(PHP 7, UI 0.9.9)

UI\Controls\Label::setText — Set Text

Description

public UI\Controls\Label::setText ( string $text )

Shall set the text for this Label

Parameters

text

The new text


Entry Control

(PHP 7, UI 0.9.9)

Introduction

An Entry is a text entry control, suitable for entering plain text, passwords, or search terms.

Class synopsis

UI\Controls\Entry extends UI\Control {
/* Constants */
const integer Normal ;
const integer Password ;
const integer Search ;
/* Constructor */
public __construct ([ int $type = UI\Controls\Entry::Normal ] )
/* Methods */
public getText ( void ) : string
public isReadOnly ( void ) : bool
protected onChange ( void )
public setReadOnly ( bool $readOnly )
public setText ( string $text )
/* Inherited methods */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control::getParent ( void ) : UI\Control
public UI\Control::getTopLevel ( void ) : int
public UI\Control::hide ( void )
public UI\Control::isEnabled ( void ) : bool
public UI\Control::isVisible ( void ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Predefined Constants

UI\Controls\Entry::Normal

A normal single line entry

UI\Controls\Entry::Password

A password entry

UI\Controls\Entry::Search

A search entry

Table of Contents

  • UI\Controls\Entry::__construct — Construct a new Entry
  • UI\Controls\Entry::getText — Get Text
  • UI\Controls\Entry::isReadOnly — Detect Read Only
  • UI\Controls\Entry::onChange — Change Handler
  • UI\Controls\Entry::setReadOnly — Set Read Only
  • UI\Controls\Entry::setText — Set Text


Construct a new Entry

  • « UI\Controls\Entry
  • UI\Controls\Entry::getText »
  • PHP Manual
  • UI\Controls\Entry
  • Construct a new Entry

UI\Controls\Entry::__construct

(PHP 7, UI 0.9.9)

UI\Controls\Entry::__construct — Construct a new Entry

Description

public UI\Controls\Entry::__construct ([ int $type = UI\Controls\Entry::Normal ] )

Construct a new entry of the given type

Parameters

type

Entry::Normal, Entry::Password, or Entry::Search


Get Text

  • « UI\Controls\Entry::__construct
  • UI\Controls\Entry::isReadOnly »
  • PHP Manual
  • UI\Controls\Entry
  • Get Text

UI\Controls\Entry::getText

(PHP 7, UI 0.9.9)

UI\Controls\Entry::getText — Get Text

Description

public UI\Controls\Entry::getText ( void ) : string

Shall return the current text from this Entry

Parameters

This function has no parameters.

Return Values

The current text


Detect Read Only

  • « UI\Controls\Entry::getText
  • UI\Controls\Entry::onChange »
  • PHP Manual
  • UI\Controls\Entry
  • Detect Read Only

UI\Controls\Entry::isReadOnly

(PHP 7, UI 0.9.9)

UI\Controls\Entry::isReadOnly — Detect Read Only

Description

public UI\Controls\Entry::isReadOnly ( void ) : bool

Shall detect if this Entry is read only

Parameters

This function has no parameters.

Return Values


Change Handler

  • « UI\Controls\Entry::isReadOnly
  • UI\Controls\Entry::setReadOnly »
  • PHP Manual
  • UI\Controls\Entry
  • Change Handler

UI\Controls\Entry::onChange

(PHP 7, UI 0.9.9)

UI\Controls\Entry::onChange — Change Handler

Description

protected UI\Controls\Entry::onChange ( void )

Shall be executed when the text in this Entry changes

Parameters

This function has no parameters.


Set Read Only

  • « UI\Controls\Entry::onChange
  • UI\Controls\Entry::setText »
  • PHP Manual
  • UI\Controls\Entry
  • Set Read Only

UI\Controls\Entry::setReadOnly

(PHP 7, UI 0.9.9)

UI\Controls\Entry::setReadOnly — Set Read Only

Description

public UI\Controls\Entry::setReadOnly ( bool $readOnly )

Shall enable or disable read only for this Entry

Parameters

readOnly


Set Text

  • « UI\Controls\Entry::setReadOnly
  • UI\Controls\MultilineEntry »
  • PHP Manual
  • UI\Controls\Entry
  • Set Text

UI\Controls\Entry::setText

(PHP 7, UI 0.9.9)

UI\Controls\Entry::setText — Set Text

Description

public UI\Controls\Entry::setText ( string $text )

Shall set the text for this Entry

Parameters

text

The new text


MultilineEntry Control

(PHP 7, UI 0.9.9)

Introduction

A Multiline Entry is a text entry control able to hold multiple lines of text, with or without wrapping.

Class synopsis

UI\Controls\MultilineEntry extends UI\Control {
/* Constants */
const integer Wrap ;
const integer NoWrap ;
/* Constructor */
public __construct ([ int $type ] )
/* Methods */
public append ( string $text )
public getText ( void ) : string
public isReadOnly ( void ) : bool
protected onChange ( void )
public setReadOnly ( bool $readOnly )
public setText ( string $text )
/* Inherited methods */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control::getParent ( void ) : UI\Control
public UI\Control::getTopLevel ( void ) : int
public UI\Control::hide ( void )
public UI\Control::isEnabled ( void ) : bool
public UI\Control::isVisible ( void ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Predefined Constants

UI\Controls\MultilineEntry::Wrap

Allow lines to wrap

UI\Controls\MultilineEntry::NoWrap

Do not allow lines to wrap

Table of Contents

  • UI\Controls\MultilineEntry::append — Append Text
  • UI\Controls\MultilineEntry::__construct — Construct a new Multiline Entry
  • UI\Controls\MultilineEntry::getText — Get Text
  • UI\Controls\MultilineEntry::isReadOnly — Read Only Detection
  • UI\Controls\MultilineEntry::onChange — Change Handler
  • UI\Controls\MultilineEntry::setReadOnly — Set Read Only
  • UI\Controls\MultilineEntry::setText — Set Text


Append Text

  • « UI\Controls\MultilineEntry
  • UI\Controls\MultilineEntry::__construct »
  • PHP Manual
  • UI\Controls\MultilineEntry
  • Append Text

UI\Controls\MultilineEntry::append

(PHP 7, UI 0.9.9)

UI\Controls\MultilineEntry::append — Append Text

Description

public UI\Controls\MultilineEntry::append ( string $text )

Shall append the given text to the text in this Multiline Entry

Parameters

text

The text to append


Construct a new Multiline Entry

  • « UI\Controls\MultilineEntry::append
  • UI\Controls\MultilineEntry::getText »
  • PHP Manual
  • UI\Controls\MultilineEntry
  • Construct a new Multiline Entry

UI\Controls\MultilineEntry::__construct

(PHP 7, UI 0.9.9)

UI\Controls\MultilineEntry::__construct — Construct a new Multiline Entry

Description

public UI\Controls\MultilineEntry::__construct ([ int $type ] )

Shall construct a new Multiline Entry of the given type

Parameters

type

MultilineEntry::Wrap or MultilineEntry::NoWrap


Get Text

  • « UI\Controls\MultilineEntry::__construct
  • UI\Controls\MultilineEntry::isReadOnly »
  • PHP Manual
  • UI\Controls\MultilineEntry
  • Get Text

UI\Controls\MultilineEntry::getText

(PHP 7, UI 0.9.9)

UI\Controls\MultilineEntry::getText — Get Text

Description

public UI\Controls\MultilineEntry::getText ( void ) : string

Shall return the text in this Multiline Entry

Parameters

This function has no parameters.


Read Only Detection

  • « UI\Controls\MultilineEntry::getText
  • UI\Controls\MultilineEntry::onChange »
  • PHP Manual
  • UI\Controls\MultilineEntry
  • Read Only Detection

UI\Controls\MultilineEntry::isReadOnly

(PHP 7, UI 0.9.9)

UI\Controls\MultilineEntry::isReadOnly — Read Only Detection

Description

public UI\Controls\MultilineEntry::isReadOnly ( void ) : bool

Shall detect if this Multiline Entry is read only

Parameters

This function has no parameters.


Change Handler

  • « UI\Controls\MultilineEntry::isReadOnly
  • UI\Controls\MultilineEntry::setReadOnly »
  • PHP Manual
  • UI\Controls\MultilineEntry
  • Change Handler

UI\Controls\MultilineEntry::onChange

(PHP 7, UI 0.9.9)

UI\Controls\MultilineEntry::onChange — Change Handler

Description

protected UI\Controls\MultilineEntry::onChange ( void )

Shall be executed when the text in this Multiline Entry is changed

Parameters

This function has no parameters.


Set Read Only

  • « UI\Controls\MultilineEntry::onChange
  • UI\Controls\MultilineEntry::setText »
  • PHP Manual
  • UI\Controls\MultilineEntry
  • Set Read Only

UI\Controls\MultilineEntry::setReadOnly

(PHP 7, UI 0.9.9)

UI\Controls\MultilineEntry::setReadOnly — Set Read Only

Description

public UI\Controls\MultilineEntry::setReadOnly ( bool $readOnly )

Shall enable or disable read only on this Multiline Entry

Parameters

readOnly


Set Text

  • « UI\Controls\MultilineEntry::setReadOnly
  • UI\Controls\Spin »
  • PHP Manual
  • UI\Controls\MultilineEntry
  • Set Text

UI\Controls\MultilineEntry::setText

(PHP 7, UI 0.9.9)

UI\Controls\MultilineEntry::setText — Set Text

Description

public UI\Controls\MultilineEntry::setText ( string $text )

Shall set the text in this Multiline Entry

Parameters

text

The new text


Spin Control

(PHP 7, UI 0.9.9)

Introduction

A Spin box is a text box with an up-down control which changes the integer value in the box, within a defined range

Class synopsis

UI\Controls\Spin extends UI\Control {
/* Constructor */
public __construct ( int $min , int $max )
/* Methods */
public getValue ( void ) : int
protected onChange ( void )
public setValue ( int $value )
/* Inherited methods */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control::getParent ( void ) : UI\Control
public UI\Control::getTopLevel ( void ) : int
public UI\Control::hide ( void )
public UI\Control::isEnabled ( void ) : bool
public UI\Control::isVisible ( void ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Table of Contents

  • UI\Controls\Spin::__construct — Construct a new Spin
  • UI\Controls\Spin::getValue — Get Value
  • UI\Controls\Spin::onChange — Change Handler
  • UI\Controls\Spin::setValue — Set Value


Construct a new Spin

  • « UI\Controls\Spin
  • UI\Controls\Spin::getValue »
  • PHP Manual
  • UI\Controls\Spin
  • Construct a new Spin

UI\Controls\Spin::__construct

(PHP 7, UI 0.9.9)

UI\Controls\Spin::__construct — Construct a new Spin

Description

public UI\Controls\Spin::__construct ( int $min , int $max )

Constructs a new Spin with the given range

Parameters

min

The minimum value allowed

max

The maximum value allowed


Get Value

  • « UI\Controls\Spin::__construct
  • UI\Controls\Spin::onChange »
  • PHP Manual
  • UI\Controls\Spin
  • Get Value

UI\Controls\Spin::getValue

(PHP 7, UI 0.9.9)

UI\Controls\Spin::getValue — Get Value

Description

public UI\Controls\Spin::getValue ( void ) : int

Get the value in this Spin

Parameters

This function has no parameters.


Change Handler

  • « UI\Controls\Spin::getValue
  • UI\Controls\Spin::setValue »
  • PHP Manual
  • UI\Controls\Spin
  • Change Handler

UI\Controls\Spin::onChange

(PHP 7, UI 0.9.9)

UI\Controls\Spin::onChange — Change Handler

Description

protected UI\Controls\Spin::onChange ( void )

Shall be executed when the value in this Spin changes

Parameters

This function has no parameters.


Set Value

  • « UI\Controls\Spin::onChange
  • UI\Controls\Slider »
  • PHP Manual
  • UI\Controls\Spin
  • Set Value

UI\Controls\Spin::setValue

(PHP 7, UI 0.9.9)

UI\Controls\Spin::setValue — Set Value

Description

public UI\Controls\Spin::setValue ( int $value )

Set the value in this Spin

Parameters

value

The new value


Slider Control

(PHP 7, UI 0.9.9)

Introduction

A Slider is a control which represents a range, and a current value in the range. The sliding element of the control (sometimes called the "thumb") reflects the value, and can be adjusted within the range.

Class synopsis

UI\Controls\Slider extends UI\Control {
/* Constructor */
public __construct ( int $min , int $max )
/* Methods */
public getValue ( void ) : int
protected onChange ( void )
public setValue ( int $value )
/* Inherited methods */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control::getParent ( void ) : UI\Control
public UI\Control::getTopLevel ( void ) : int
public UI\Control::hide ( void )
public UI\Control::isEnabled ( void ) : bool
public UI\Control::isVisible ( void ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Table of Contents

  • UI\Controls\Slider::__construct — Construct a new Slider
  • UI\Controls\Slider::getValue — Get Value
  • UI\Controls\Slider::onChange — Change Handler
  • UI\Controls\Slider::setValue — Set Value


Construct a new Slider

  • « UI\Controls\Slider
  • UI\Controls\Slider::getValue »
  • PHP Manual
  • UI\Controls\Slider
  • Construct a new Slider

UI\Controls\Slider::__construct

(PHP 7, UI 0.9.9)

UI\Controls\Slider::__construct — Construct a new Slider

Description

public UI\Controls\Slider::__construct ( int $min , int $max )

Construct a new Slider with the given range

Parameters

min

The minimum allowed value

max

The maximum allowed value


Get Value

  • « UI\Controls\Slider::__construct
  • UI\Controls\Slider::onChange »
  • PHP Manual
  • UI\Controls\Slider
  • Get Value

UI\Controls\Slider::getValue

(PHP 7, UI 0.9.9)

UI\Controls\Slider::getValue — Get Value

Description

public UI\Controls\Slider::getValue ( void ) : int

Get the value from this Slider

Parameters

This function has no parameters.


Change Handler

  • « UI\Controls\Slider::getValue
  • UI\Controls\Slider::setValue »
  • PHP Manual
  • UI\Controls\Slider
  • Change Handler

UI\Controls\Slider::onChange

(PHP 7, UI 0.9.9)

UI\Controls\Slider::onChange — Change Handler

Description

protected UI\Controls\Slider::onChange ( void )

Shall be executed when the value of this Slider changes

Parameters

This function has no parameters.


Set Value

  • « UI\Controls\Slider::onChange
  • UI\Controls\Progress »
  • PHP Manual
  • UI\Controls\Slider
  • Set Value

UI\Controls\Slider::setValue

(PHP 7, UI 0.9.9)

UI\Controls\Slider::setValue — Set Value

Description

public UI\Controls\Slider::setValue ( int $value )

Shall set the value for this Slider

Parameters

value

The new value


Progress Control

(PHP 7, UI 0.9.9)

Introduction

A Progress control is a familiar Progress bar: It represents progress as a percentage, with a possible range of 0 to 100 (inclusive).

Class synopsis

UI\Controls\Progress extends UI\Control {
/* Methods */
public getValue ( void ) : int
public setValue ( int $value )
/* Inherited methods */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control::getParent ( void ) : UI\Control
public UI\Control::getTopLevel ( void ) : int
public UI\Control::hide ( void )
public UI\Control::isEnabled ( void ) : bool
public UI\Control::isVisible ( void ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Table of Contents

  • UI\Controls\Progress::getValue — Get Value
  • UI\Controls\Progress::setValue — Set Value


Get Value

  • « UI\Controls\Progress
  • UI\Controls\Progress::setValue »
  • PHP Manual
  • UI\Controls\Progress
  • Get Value

UI\Controls\Progress::getValue

(PHP 7, UI 0.9.9)

UI\Controls\Progress::getValue — Get Value

Description

public UI\Controls\Progress::getValue ( void ) : int

Shall retrieve the current value of this Progress bar

Parameters

This function has no parameters.


Set Value

  • « UI\Controls\Progress::getValue
  • UI\Controls\Separator »
  • PHP Manual
  • UI\Controls\Progress
  • Set Value

UI\Controls\Progress::setValue

(PHP 7, UI 0.9.9)

UI\Controls\Progress::setValue — Set Value

Description

public UI\Controls\Progress::setValue ( int $value )

Shall set the value for this Progress bar

Parameters

value

An integer between 0 and 100 (inclusive)


Control Separator

(PHP 7, UI 0.9.9)

Introduction

A Separator represents a control separator, it has no other function.

Class synopsis

UI\Controls\Separator extends UI\Control {
/* Constants */
const integer Horizontal ;
const integer Vertical ;
/* Constructor */
public __construct ([ int $type = UI\Controls\Separator::Horizontal ] )
/* Inherited methods */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control::getParent ( void ) : UI\Control
public UI\Control::getTopLevel ( void ) : int
public UI\Control::hide ( void )
public UI\Control::isEnabled ( void ) : bool
public UI\Control::isVisible ( void ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Predefined Constants

UI\Controls\Separator::Horizontal

A Horizontal Separator

UI\Controls\Separator::Vertical

A Vertical Separator

Table of Contents

  • UI\Controls\Separator::__construct — Construct a new Separator


Construct a new Separator

  • « UI\Controls\Separator
  • UI\Controls\Combo »
  • PHP Manual
  • UI\Controls\Separator
  • Construct a new Separator

UI\Controls\Separator::__construct

(PHP 7, UI 0.9.9)

UI\Controls\Separator::__construct — Construct a new Separator

Description

public UI\Controls\Separator::__construct ([ int $type = UI\Controls\Separator::Horizontal ] )

Shall construct a new Separator of the given type

Parameters

type

Separator::Horizonal or Separator::Vertical


Combo Control

(PHP 7, UI 0.9.9)

Introduction

A Combo control represents a list of options, like the familiar select HTML element.

Class synopsis

UI\Controls\Combo extends UI\Control {
/* Methods */
public append ( string $text )
public getSelected ( void ) : int
protected onSelected ( void )
public setSelected ( int $index )
/* Inherited methods */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control::getParent ( void ) : UI\Control
public UI\Control::getTopLevel ( void ) : int
public UI\Control::hide ( void )
public UI\Control::isEnabled ( void ) : bool
public UI\Control::isVisible ( void ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Table of Contents

  • UI\Controls\Combo::append — Append Option
  • UI\Controls\Combo::getSelected — Get Selected Option
  • UI\Controls\Combo::onSelected — Selected Handler
  • UI\Controls\Combo::setSelected — Set Selected Option


Append Option

  • « UI\Controls\Combo
  • UI\Controls\Combo::getSelected »
  • PHP Manual
  • UI\Controls\Combo
  • Append Option

UI\Controls\Combo::append

(PHP 7, UI 0.9.9)

UI\Controls\Combo::append — Append Option

Description

public UI\Controls\Combo::append ( string $text )

Append an option to this Combo

Parameters

text

The text for the new option


Get Selected Option

  • « UI\Controls\Combo::append
  • UI\Controls\Combo::onSelected »
  • PHP Manual
  • UI\Controls\Combo
  • Get Selected Option

UI\Controls\Combo::getSelected

(PHP 7, UI 0.9.9)

UI\Controls\Combo::getSelected — Get Selected Option

Description

public UI\Controls\Combo::getSelected ( void ) : int

Shall retrieve the index of the option selected in this Combo

Parameters

This function has no parameters.


Selected Handler

  • « UI\Controls\Combo::getSelected
  • UI\Controls\Combo::setSelected »
  • PHP Manual
  • UI\Controls\Combo
  • Selected Handler

UI\Controls\Combo::onSelected

(PHP 7, UI 0.9.9)

UI\Controls\Combo::onSelected — Selected Handler

Description

protected UI\Controls\Combo::onSelected ( void )

Shall be executed when an option is selected in this Combo

Parameters

This function has no parameters.


Set Selected Option

  • « UI\Controls\Combo::onSelected
  • UI\Controls\EditableCombo »
  • PHP Manual
  • UI\Controls\Combo
  • Set Selected Option

UI\Controls\Combo::setSelected

(PHP 7, UI 0.9.9)

UI\Controls\Combo::setSelected — Set Selected Option

Description

public UI\Controls\Combo::setSelected ( int $index )

Shall set the currently selected option in this Combo

Parameters

index

The index of the option to select


EdiableCombo Control

(PHP 7, UI 0.9.9)

Introduction

An Editable Combo is a Combo which allows the user to enter custom options

Class synopsis

UI\Controls\EditableCombo extends UI\Control {
/* Methods */
public append ( string $text )
public getText ( void ) : string
protected onChange ( void )
public setText ( string $text )
/* Inherited methods */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control::getParent ( void ) : UI\Control
public UI\Control::getTopLevel ( void ) : int
public UI\Control::hide ( void )
public UI\Control::isEnabled ( void ) : bool
public UI\Control::isVisible ( void ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Table of Contents

  • UI\Controls\EditableCombo::append — Append Option
  • UI\Controls\EditableCombo::getText — Get Text
  • UI\Controls\EditableCombo::onChange — Change Handler
  • UI\Controls\EditableCombo::setText — Set Text


Append Option

  • « UI\Controls\EditableCombo
  • UI\Controls\EditableCombo::getText »
  • PHP Manual
  • UI\Controls\EditableCombo
  • Append Option

UI\Controls\EditableCombo::append

(PHP 7, UI 0.9.9)

UI\Controls\EditableCombo::append — Append Option

Description

public UI\Controls\EditableCombo::append ( string $text )

Shall append a new option to this Editable Combo

Parameters

text

The text for the new option


Get Text

  • « UI\Controls\EditableCombo::append
  • UI\Controls\EditableCombo::onChange »
  • PHP Manual
  • UI\Controls\EditableCombo
  • Get Text

UI\Controls\EditableCombo::getText

(PHP 7, UI 0.9.9)

UI\Controls\EditableCombo::getText — Get Text

Description

public UI\Controls\EditableCombo::getText ( void ) : string

Get the value of the currently selected option in this Editable Combo

Parameters

This function has no parameters.


Change Handler

  • « UI\Controls\EditableCombo::getText
  • UI\Controls\EditableCombo::setText »
  • PHP Manual
  • UI\Controls\EditableCombo
  • Change Handler

UI\Controls\EditableCombo::onChange

(PHP 7, UI 0.9.9)

UI\Controls\EditableCombo::onChange — Change Handler

Description

protected UI\Controls\EditableCombo::onChange ( void )

Shall be executed when the value of this Editable Combobox changes

Parameters

This function has no parameters.


Set Text

  • « UI\Controls\EditableCombo::onChange
  • UI\Controls\Radio »
  • PHP Manual
  • UI\Controls\EditableCombo
  • Set Text

UI\Controls\EditableCombo::setText

(PHP 7, UI 0.9.9)

UI\Controls\EditableCombo::setText — Set Text

Description

public UI\Controls\EditableCombo::setText ( string $text )

Shall set the text of the currently selected option in this Editable Combo

Parameters

text

The new text


Radio Control

(PHP 7, UI 0.9.9)

Introduction

A Radio is similar to the radio input type familiar from HTML

Class synopsis

UI\Controls\Radio extends UI\Control {
/* Methods */
public append ( string $text )
public getSelected ( void ) : int
protected onSelected ( void )
public setSelected ( int $index )
/* Inherited methods */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control::getParent ( void ) : UI\Control
public UI\Control::getTopLevel ( void ) : int
public UI\Control::hide ( void )
public UI\Control::isEnabled ( void ) : bool
public UI\Control::isVisible ( void ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Table of Contents

  • UI\Controls\Radio::append — Append Option
  • UI\Controls\Radio::getSelected — Get Selected Option
  • UI\Controls\Radio::onSelected — Selected Handler
  • UI\Controls\Radio::setSelected — Set Selected Option


Append Option

  • « UI\Controls\Radio
  • UI\Controls\Radio::getSelected »
  • PHP Manual
  • UI\Controls\Radio
  • Append Option

UI\Controls\Radio::append

(PHP 7, UI 0.9.9)

UI\Controls\Radio::append — Append Option

Description

public UI\Controls\Radio::append ( string $text )

Shall append a new option to this Radio

Parameters

text

The text (label) for the option


Get Selected Option

  • « UI\Controls\Radio::append
  • UI\Controls\Radio::onSelected »
  • PHP Manual
  • UI\Controls\Radio
  • Get Selected Option

UI\Controls\Radio::getSelected

(PHP 7, UI 0.9.9)

UI\Controls\Radio::getSelected — Get Selected Option

Description

public UI\Controls\Radio::getSelected ( void ) : int

Shall retrieve the index of the currently selected option in this Radio

Parameters

This function has no parameters.


Selected Handler

  • « UI\Controls\Radio::getSelected
  • UI\Controls\Radio::setSelected »
  • PHP Manual
  • UI\Controls\Radio
  • Selected Handler

UI\Controls\Radio::onSelected

(PHP 7, UI 0.9.9)

UI\Controls\Radio::onSelected — Selected Handler

Description

protected UI\Controls\Radio::onSelected ( void )

Shall be executed when the option selected in this Radio changes

Parameters

This function has no parameters.


Set Selected Option

  • « UI\Controls\Radio::onSelected
  • UI\Controls\Picker »
  • PHP Manual
  • UI\Controls\Radio
  • Set Selected Option

UI\Controls\Radio::setSelected

(PHP 7, UI 0.9.9)

UI\Controls\Radio::setSelected — Set Selected Option

Description

public UI\Controls\Radio::setSelected ( int $index )

Shall set the currently selected option in this Radio

Parameters

index

The index of the option to select


Picker Control

(PHP 7, UI 0.9.9)

Introduction

A Picker represents a button which when clicked presents a native Date/Time/DateTime Picker interface to the user.

Class synopsis

UI\Controls\Picker extends UI\Control {
/* Constants */
const integer Date ;
const integer Time ;
const integer DateTime ;
/* Constructor */
public __construct ([ int $type = UI\Controls\Picker::Date ] )
/* Inherited methods */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control::getParent ( void ) : UI\Control
public UI\Control::getTopLevel ( void ) : int
public UI\Control::hide ( void )
public UI\Control::isEnabled ( void ) : bool
public UI\Control::isVisible ( void ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Predefined Constants

UI\Controls\Picker::Date

A Date Picker

UI\Controls\Picker::Time

A Time Picker

UI\Controls\Picker::DateTime

A Date and Time Picker

Table of Contents

  • UI\Controls\Picker::__construct — Construct a new Picker


Construct a new Picker

  • « UI\Controls\Picker
  • UI\Controls\Form »
  • PHP Manual
  • UI\Controls\Picker
  • Construct a new Picker

UI\Controls\Picker::__construct

(PHP 7, UI 0.9.9)

UI\Controls\Picker::__construct — Construct a new Picker

Description

public UI\Controls\Picker::__construct ([ int $type = UI\Controls\Picker::Date ] )

Construct a new Picker of the given type

Parameters

type

Picker::Date, Picker::Time, or Picker::DateTime


Control Form (Arrangement)

(PHP 7, UI 0.9.9)

Introduction

A Form is a control which allows the arrangement of other controls into a familiar layout (the form).

Class synopsis

UI\Controls\Form extends UI\Control {
/* Properties */
protected $controls ;
/* Methods */
public append ( string $label , UI\Control $control [, bool $stretchy = FALSE ] ) : int
public delete ( int $index ) : bool
public isPadded ( void ) : bool
public setPadded ( bool $padded )
/* Inherited methods */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control::getParent ( void ) : UI\Control
public UI\Control::getTopLevel ( void ) : int
public UI\Control::hide ( void )
public UI\Control::isEnabled ( void ) : bool
public UI\Control::isVisible ( void ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Properties

controls

Contains controls, should not be manipulated directly

Table of Contents

  • UI\Controls\Form::append — Append Control
  • UI\Controls\Form::delete — Delete Control
  • UI\Controls\Form::isPadded — Padding Detection
  • UI\Controls\Form::setPadded — Set Padding


Append Control

  • « UI\Controls\Form
  • UI\Controls\Form::delete »
  • PHP Manual
  • UI\Controls\Form
  • Append Control

UI\Controls\Form::append

(PHP 7, UI 0.9.9)

UI\Controls\Form::append — Append Control

Description

public UI\Controls\Form::append ( string $label , UI\Control $control [, bool $stretchy = FALSE ] ) : int

Shall append the control to the form, and set the label

Parameters

label

The text for the label

control

A control

stretchy

Should be set true to stretch the control

Return Values

Shall return the index of the appended control, may be 0


Delete Control

  • « UI\Controls\Form::append
  • UI\Controls\Form::isPadded »
  • PHP Manual
  • UI\Controls\Form
  • Delete Control

UI\Controls\Form::delete

(PHP 7, UI 0.9.9)

UI\Controls\Form::delete — Delete Control

Description

public UI\Controls\Form::delete ( int $index ) : bool

Shall delete the control at the given index in this Form

Parameters

index

The index of the control to remove

Return Values

Indication of succcess


Padding Detection

  • « UI\Controls\Form::delete
  • UI\Controls\Form::setPadded »
  • PHP Manual
  • UI\Controls\Form
  • Padding Detection

UI\Controls\Form::isPadded

(PHP 7, UI 0.9.9)

UI\Controls\Form::isPadded — Padding Detection

Description

public UI\Controls\Form::isPadded ( void ) : bool

Shall detect if padding is enabled on this Form

Parameters

This function has no parameters.


Set Padding

  • « UI\Controls\Form::isPadded
  • UI\Controls\Grid »
  • PHP Manual
  • UI\Controls\Form
  • Set Padding

UI\Controls\Form::setPadded

(PHP 7, UI 0.9.9)

UI\Controls\Form::setPadded — Set Padding

Description

public UI\Controls\Form::setPadded ( bool $padded )

Shall enable or disable padding on this Form

Parameters

padded


Control Grid (Arrangement)

(PHP 7, UI 0.9.9)

Introduction

A Grid is a control which is allows the arrangement of children into a grid

Class synopsis

UI\Controls\Grid extends UI\Control {
/* Constants */
const integer Fill ;
const integer Start ;
const integer Center ;
const integer End ;
const integer Leading ;
const integer Top ;
const integer Trailing ;
const integer Bottom ;
/* Properties */
protected $controls ;
/* Methods */
public append ( UI\Control $control , int $left , int $top , int $xspan , int $yspan , bool $hexpand , int $halign , bool $vexpand , int $valign )
public isPadded ( void ) : bool
public setPadded ( bool $padding )
/* Inherited methods */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control::getParent ( void ) : UI\Control
public UI\Control::getTopLevel ( void ) : int
public UI\Control::hide ( void )
public UI\Control::isEnabled ( void ) : bool
public UI\Control::isVisible ( void ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Predefined Constants

UI\Controls\Grid::Fill

UI\Controls\Grid::Start

UI\Controls\Grid::Center

UI\Controls\Grid::End

UI\Controls\Grid::Leading

UI\Controls\Grid::Top

UI\Controls\Grid::Trailing

UI\Controls\Grid::Bottom

Properties

controls

Contains controls, should not be manipulated directly

Table of Contents

  • UI\Controls\Grid::append — Append Control
  • UI\Controls\Grid::isPadded — Padding Detection
  • UI\Controls\Grid::setPadded — Set Padding


Append Control

  • « UI\Controls\Grid
  • UI\Controls\Grid::isPadded »
  • PHP Manual
  • UI\Controls\Grid
  • Append Control

UI\Controls\Grid::append

(PHP 7, UI 0.9.9)

UI\Controls\Grid::append — Append Control

Description

public UI\Controls\Grid::append ( UI\Control $control , int $left , int $top , int $xspan , int $yspan , bool $hexpand , int $halign , bool $vexpand , int $valign )

Warning

This function is currently not documented; only its argument list is available.

Parameters

control

The Control to append

left

top

xspan

yspan

hexpand

halign

vexpand

valign

Return Values


Padding Detection

  • « UI\Controls\Grid::append
  • UI\Controls\Grid::setPadded »
  • PHP Manual
  • UI\Controls\Grid
  • Padding Detection

UI\Controls\Grid::isPadded

(PHP 7, UI 0.9.9)

UI\Controls\Grid::isPadded — Padding Detection

Description

public UI\Controls\Grid::isPadded ( void ) : bool

Shall detect if padding is enabled on this Grid

Parameters

This function has no parameters.


Set Padding

  • « UI\Controls\Grid::isPadded
  • UI\Controls\Group »
  • PHP Manual
  • UI\Controls\Grid
  • Set Padding

UI\Controls\Grid::setPadded

(PHP 7, UI 0.9.9)

UI\Controls\Grid::setPadded — Set Padding

Description

public UI\Controls\Grid::setPadded ( bool $padding )

Shall enable or disable padding for this Grid

Parameters

padding


Control Group (Arrangement)

(PHP 7, UI 0.9.9)

Introduction

A Group is a titled container for child controls

Class synopsis

UI\Controls\Group extends UI\Control {
/* Properties */
protected $controls ;
/* Constructor */
public __construct ( string $title )
/* Methods */
public append ( UI\Control $control )
public getTitle ( void ) : string
public hasMargin ( void ) : bool
public setMargin ( bool $margin )
public setTitle ( string $title )
/* Inherited methods */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control::getParent ( void ) : UI\Control
public UI\Control::getTopLevel ( void ) : int
public UI\Control::hide ( void )
public UI\Control::isEnabled ( void ) : bool
public UI\Control::isVisible ( void ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Properties

controls

Contains controls, should not be manipulated directly

Table of Contents

  • UI\Controls\Group::append — Append Control
  • UI\Controls\Group::__construct — Construct a new Group
  • UI\Controls\Group::getTitle — Get Title
  • UI\Controls\Group::hasMargin — Margin Detection
  • UI\Controls\Group::setMargin — Set Margin
  • UI\Controls\Group::setTitle — Set Title


Append Control

  • « UI\Controls\Group
  • UI\Controls\Group::__construct »
  • PHP Manual
  • UI\Controls\Group
  • Append Control

UI\Controls\Group::append

(No version information available, might only be in Git)

UI\Controls\Group::append — Append Control

Description

public UI\Controls\Group::append ( UI\Control $control )

Shall append a control to this Group

Parameters

control

The control to append


Construct a new Group

  • « UI\Controls\Group::append
  • UI\Controls\Group::getTitle »
  • PHP Manual
  • UI\Controls\Group
  • Construct a new Group

UI\Controls\Group::__construct

(PHP 7, UI 0.9.9)

UI\Controls\Group::__construct — Construct a new Group

Description

public UI\Controls\Group::__construct ( string $title )

Shall construct a new Group with the given title

Parameters

title

The text for the title label


Get Title

  • « UI\Controls\Group::__construct
  • UI\Controls\Group::hasMargin »
  • PHP Manual
  • UI\Controls\Group
  • Get Title

UI\Controls\Group::getTitle

(PHP 7, UI 0.9.9)

UI\Controls\Group::getTitle — Get Title

Description

public UI\Controls\Group::getTitle ( void ) : string

Shall return the current title for this Group

Parameters

This function has no parameters.

Return Values

The current title


Margin Detection

  • « UI\Controls\Group::getTitle
  • UI\Controls\Group::setMargin »
  • PHP Manual
  • UI\Controls\Group
  • Margin Detection

UI\Controls\Group::hasMargin

(PHP 7, UI 0.9.9)

UI\Controls\Group::hasMargin — Margin Detection

Description

public UI\Controls\Group::hasMargin ( void ) : bool

Shall detect if this Group has a margin

Parameters

This function has no parameters.


Set Margin

  • « UI\Controls\Group::hasMargin
  • UI\Controls\Group::setTitle »
  • PHP Manual
  • UI\Controls\Group
  • Set Margin

UI\Controls\Group::setMargin

(PHP 7, UI 0.9.9)

UI\Controls\Group::setMargin — Set Margin

Description

public UI\Controls\Group::setMargin ( bool $margin )

Shall enable or disable margins for this Group

Parameters

margin


Set Title

  • « UI\Controls\Group::setMargin
  • UI\Controls\Box »
  • PHP Manual
  • UI\Controls\Group
  • Set Title

UI\Controls\Group::setTitle

(PHP 7, UI 0.9.9)

UI\Controls\Group::setTitle — Set Title

Description

public UI\Controls\Group::setTitle ( string $title )

Shall set the title for this Group

Parameters

title

The text for the new title


Control Box (Arrangement)

(PHP 7, UI 0.9.9)

Introduction

A Box allows the arrangement of other controls

Class synopsis

UI\Controls\Box extends UI\Control {
/* Constants */
const integer Vertical ;
const integer Horizontal ;
/* Properties */
protected $controls ;
/* Constructor */
public __construct ([ int $orientation = UI\Controls\Box::Horizontal ] )
/* Methods */
public append ( Control $control [, bool $stretchy = FALSE ] ) : int
public delete ( int $index ) : bool
public getOrientation ( void ) : int
public isPadded ( void ) : bool
public setPadded ( bool $padded )
/* Inherited methods */
public UI\Control::destroy ( void )
public UI\Control::disable ( void )
public UI\Control::enable ( void )
public UI\Control::getParent ( void ) : UI\Control
public UI\Control::getTopLevel ( void ) : int
public UI\Control::hide ( void )
public UI\Control::isEnabled ( void ) : bool
public UI\Control::isVisible ( void ) : bool
public UI\Control::setParent ( UI\Control $parent )
public UI\Control::show ( void )
}

Properties

controls

Contains controls, should not be manipulated directly

Predefined Constants

UI\Controls\Box::Vertical

UI\Controls\Box::Horizontal

Table of Contents

  • UI\Controls\Box::append — Append Control
  • UI\Controls\Box::__construct — Construct a new Box
  • UI\Controls\Box::delete — Delete Control
  • UI\Controls\Box::getOrientation — Get Orientation
  • UI\Controls\Box::isPadded — Padding Detection
  • UI\Controls\Box::setPadded — Set Padding


Append Control

  • « UI\Controls\Box
  • UI\Controls\Box::__construct »
  • PHP Manual
  • UI\Controls\Box
  • Append Control

UI\Controls\Box::append

(PHP 7, UI 0.9.9)

UI\Controls\Box::append — Append Control

Description

public UI\Controls\Box::append ( Control $control [, bool $stretchy = FALSE ] ) : int

Shall append the given control to this Box

Parameters

control

The control to append

stretchy

Set true to stretch the control

Return Values

Shall return the index of the appended control, may be 0


Construct a new Box

  • « UI\Controls\Box::append
  • UI\Controls\Box::delete »
  • PHP Manual
  • UI\Controls\Box
  • Construct a new Box

UI\Controls\Box::__construct

(PHP 7, UI 0.9.9)

UI\Controls\Box::__construct — Construct a new Box

Description

public UI\Controls\Box::__construct ([ int $orientation = UI\Controls\Box::Horizontal ] )

Shall construct a new box

Parameters

orientation

Box::Horizontal or Box::Vertical


Delete Control

  • « UI\Controls\Box::__construct
  • UI\Controls\Box::getOrientation »
  • PHP Manual
  • UI\Controls\Box
  • Delete Control

UI\Controls\Box::delete

(PHP 7, UI 0.9.9)

UI\Controls\Box::delete — Delete Control

Description

public UI\Controls\Box::delete ( int $index ) : bool

Shall delete the control at the given index from this Box

Parameters

index

The index of the control to delete

Return Values

Indication of success


Get Orientation

  • « UI\Controls\Box::delete
  • UI\Controls\Box::isPadded »
  • PHP Manual
  • UI\Controls\Box
  • Get Orientation

UI\Controls\Box::getOrientation

(PHP 7, UI 0.9.9)

UI\Controls\Box::getOrientation — Get Orientation

Description

public UI\Controls\Box::getOrientation ( void ) : int

Shall retrieve the orientation of this Box

Parameters

This function has no parameters.


Padding Detection

  • « UI\Controls\Box::getOrientation
  • UI\Controls\Box::setPadded »
  • PHP Manual
  • UI\Controls\Box
  • Padding Detection

UI\Controls\Box::isPadded

(PHP 7, UI 0.9.9)

UI\Controls\Box::isPadded — Padding Detection

Description

public UI\Controls\Box::isPadded ( void ) : bool

Shall detect if padding is enabled on this Box

Parameters

This function has no parameters.


Set Padding

  • « UI\Controls\Box::isPadded
  • UI\Draw\Pen »
  • PHP Manual
  • UI\Controls\Box
  • Set Padding

UI\Controls\Box::setPadded

(PHP 7, UI 0.9.9)

UI\Controls\Box::setPadded — Set Padding

Description

public UI\Controls\Box::setPadded ( bool $padded )

Shall enable or disable padding on this Box

Parameters

padded


Draw Pen

(PHP 7, UI 0.9.9)

Introduction

The Pen is passed to the Area Draw event handler, it is used for clipping, filling, stroking, and writing to Draw Paths.

Class synopsis

final UI\Draw\Pen {
/* Methods */
public clip ( UI\Draw\Path $path )
public fill ( UI\Draw\Path $path , UI\Draw\Brush $with )
public fill ( UI\Draw\Path $path , UI\Draw\Color $with )
public fill ( UI\Draw\Path $path , int $with )
public restore ( void )
public save ( void )
public stroke ( UI\Draw\Path $path , UI\Draw\Brush $with , UI\Draw\Stroke $stroke )
public stroke ( UI\Draw\Path $path , UI\Draw\Color $with , UI\Draw\Stroke $stroke )
public stroke ( UI\Draw\Path $path , int $with , UI\Draw\Stroke $stroke )
public transform ( UI\Draw\Matrix $matrix )
public write ( UI\Point $point , UI\Draw\Text\Layout $layout )
}

Table of Contents

  • UI\Draw\Pen::clip — Clip a Path
  • UI\Draw\Pen::fill — Fill a Path
  • UI\Draw\Pen::restore — Restore
  • UI\Draw\Pen::save — Save
  • UI\Draw\Pen::stroke — Stroke a Path
  • UI\Draw\Pen::transform — Matrix Transform
  • UI\Draw\Pen::write — Draw Text at Point


Clip a Path

  • « UI\Draw\Pen
  • UI\Draw\Pen::fill »
  • PHP Manual
  • UI\Draw\Pen
  • Clip a Path

UI\Draw\Pen::clip

(PHP 7, UI 0.9.9)

UI\Draw\Pen::clip — Clip a Path

Description

public UI\Draw\Pen::clip ( UI\Draw\Path $path )

Shall clip the given Path

Parameters

path

The path to clip


Fill a Path

  • « UI\Draw\Pen::clip
  • UI\Draw\Pen::restore »
  • PHP Manual
  • UI\Draw\Pen
  • Fill a Path

UI\Draw\Pen::fill

(PHP 7, UI 0.9.9)

UI\Draw\Pen::fill — Fill a Path

Description

public UI\Draw\Pen::fill ( UI\Draw\Path $path , UI\Draw\Brush $with )
public UI\Draw\Pen::fill ( UI\Draw\Path $path , UI\Draw\Color $with )
public UI\Draw\Pen::fill ( UI\Draw\Path $path , int $with )

Shall fill the given path

Parameters

path

The path to fill

with

The color or brush to fill with


Restore

  • « UI\Draw\Pen::fill
  • UI\Draw\Pen::save »
  • PHP Manual
  • UI\Draw\Pen
  • Restore

UI\Draw\Pen::restore

(PHP 7, UI 0.9.9)

UI\Draw\Pen::restore — Restore

Description

public UI\Draw\Pen::restore ( void )

Shall restore a previously saved Pen

Parameters

This function has no parameters.


Save

  • « UI\Draw\Pen::restore
  • UI\Draw\Pen::stroke »
  • PHP Manual
  • UI\Draw\Pen
  • Save

UI\Draw\Pen::save

(PHP 7, UI 0.9.9)

UI\Draw\Pen::save — Save

Description

public UI\Draw\Pen::save ( void )

Shall save the Pen

Parameters

This function has no parameters.


Stroke a Path

  • « UI\Draw\Pen::save
  • UI\Draw\Pen::transform »
  • PHP Manual
  • UI\Draw\Pen
  • Stroke a Path

UI\Draw\Pen::stroke

(PHP 7, UI 0.9.9)

UI\Draw\Pen::stroke — Stroke a Path

Description

public UI\Draw\Pen::stroke ( UI\Draw\Path $path , UI\Draw\Brush $with , UI\Draw\Stroke $stroke )
public UI\Draw\Pen::stroke ( UI\Draw\Path $path , UI\Draw\Color $with , UI\Draw\Stroke $stroke )
public UI\Draw\Pen::stroke ( UI\Draw\Path $path , int $with , UI\Draw\Stroke $stroke )

Shall stroke the given path

Parameters

path

The path to stroke

with

The color or brush to stroke with

stroke

The configuration of the stroke


Matrix Transform

  • « UI\Draw\Pen::stroke
  • UI\Draw\Pen::write »
  • PHP Manual
  • UI\Draw\Pen
  • Matrix Transform

UI\Draw\Pen::transform

(PHP 7, UI 0.9.9)

UI\Draw\Pen::transform — Matrix Transform

Description

public UI\Draw\Pen::transform ( UI\Draw\Matrix $matrix )

Shall perform matrix transformation

Parameters

matrix

The matrix to use


Draw Text at Point

  • « UI\Draw\Pen::transform
  • UI\Draw\Path »
  • PHP Manual
  • UI\Draw\Pen
  • Draw Text at Point

UI\Draw\Pen::write

(PHP 7, UI 0.9.9)

UI\Draw\Pen::write — Draw Text at Point

Description

public UI\Draw\Pen::write ( UI\Point $point , UI\Draw\Text\Layout $layout )

Shall draw the given text layout at the given point

Parameters

point

The point to perform the drawing

layout

The layout of the text to draw


Draw Path

(PHP 7, UI 0.9.9)

Introduction

A Draw Path guides a Draw Pen, telling the Pen where to draw on an Area.

Class synopsis

UI\Draw\Path {
/* Constants */
const integer Winding ;
const integer Alternate ;
/* Constructor */
public __construct ([ int $mode = UI\Draw\Path::Winding ] )
/* Methods */
public addRectangle ( UI\Point $point , UI\Size $size )
public arcTo ( UI\Point $point , float $radius , float $angle , float $sweep , float $negative )
public bezierTo ( UI\Point $point , float $radius , float $angle , float $sweep , float $negative )
public closeFigure ( void )
public end ( void )
public lineTo ( UI\Point $point , float $radius , float $angle , float $sweep , float $negative )
public newFigure ( UI\Point $point )
public newFigureWithArc ( UI\Point $point , float $radius , float $angle , float $sweep , float $negative )
}

Predefined Constants

UI\Draw\Path::Winding

This is the default draw path mode

UI\Draw\Path::Alternate

This is the alternate draw path mode

Table of Contents

  • UI\Draw\Path::addRectangle — Draw a Rectangle
  • UI\Draw\Path::arcTo — Draw an Arc
  • UI\Draw\Path::bezierTo — Draw Bezier Curve
  • UI\Draw\Path::closeFigure — Close Figure
  • UI\Draw\Path::__construct — Construct a new Path
  • UI\Draw\Path::end — Finalize Path
  • UI\Draw\Path::lineTo — Draw a Line
  • UI\Draw\Path::newFigure — Draw Figure
  • UI\Draw\Path::newFigureWithArc — Draw Figure with Arc


Draw a Rectangle

  • « UI\Draw\Path
  • UI\Draw\Path::arcTo »
  • PHP Manual
  • UI\Draw\Path
  • Draw a Rectangle

UI\Draw\Path::addRectangle

(PHP 7, UI 0.9.9)

UI\Draw\Path::addRectangle — Draw a Rectangle

Description

public UI\Draw\Path::addRectangle ( UI\Point $point , UI\Size $size )

Shall map the path of a rectangle of the given size, at the given point

Parameters

point

The point to begin the shape

size

The size of the rectangle


Draw an Arc

  • « UI\Draw\Path::addRectangle
  • UI\Draw\Path::bezierTo »
  • PHP Manual
  • UI\Draw\Path
  • Draw an Arc

UI\Draw\Path::arcTo

(PHP 7, UI 0.9.9)

UI\Draw\Path::arcTo — Draw an Arc

Description

public UI\Draw\Path::arcTo ( UI\Point $point , float $radius , float $angle , float $sweep , float $negative )

Shall map the path for an arc

Parameters

point

The point to begin mapping

radius

The radius of the arc

angle

The angle of the arc

sweep

The sweep of the arc

negative

Return Values


Draw Bezier Curve

  • « UI\Draw\Path::arcTo
  • UI\Draw\Path::closeFigure »
  • PHP Manual
  • UI\Draw\Path
  • Draw Bezier Curve

UI\Draw\Path::bezierTo

(PHP 7, UI 0.9.9)

UI\Draw\Path::bezierTo — Draw Bezier Curve

Description

public UI\Draw\Path::bezierTo ( UI\Point $point , float $radius , float $angle , float $sweep , float $negative )

Shall draw a bezier curve

Parameters

point

The point at which to begin mapping

radius

The radius of the curve

angle

The angle of the curve

sweep

The sweep of the curve

negative


Close Figure

  • « UI\Draw\Path::bezierTo
  • UI\Draw\Path::__construct »
  • PHP Manual
  • UI\Draw\Path
  • Close Figure

UI\Draw\Path::closeFigure

(PHP 7, UI 0.9.9)

UI\Draw\Path::closeFigure — Close Figure

Description

public UI\Draw\Path::closeFigure ( void )

Shall close the current figure

Parameters

This function has no parameters.


Construct a new Path

  • « UI\Draw\Path::closeFigure
  • UI\Draw\Path::end »
  • PHP Manual
  • UI\Draw\Path
  • Construct a new Path

UI\Draw\Path::__construct

(PHP 7, UI 0.9.9)

UI\Draw\Path::__construct — Construct a new Path

Description

public UI\Draw\Path::__construct ([ int $mode = UI\Draw\Path::Winding ] )

Shall construct a new path in the given mode

Parameters

mode

Path::Winding or Path::Alternate


Finalize Path

  • « UI\Draw\Path::__construct
  • UI\Draw\Path::lineTo »
  • PHP Manual
  • UI\Draw\Path
  • Finalize Path

UI\Draw\Path::end

(PHP 7, UI 0.9.9)

UI\Draw\Path::end — Finalize Path

Description

public UI\Draw\Path::end ( void )

Shall finalize this Path

Parameters

This function has no parameters.


Draw a Line

  • « UI\Draw\Path::end
  • UI\Draw\Path::newFigure »
  • PHP Manual
  • UI\Draw\Path
  • Draw a Line

UI\Draw\Path::lineTo

(PHP 7, UI 0.9.9)

UI\Draw\Path::lineTo — Draw a Line

Description

public UI\Draw\Path::lineTo ( UI\Point $point , float $radius , float $angle , float $sweep , float $negative )

Shall map the path for a line

Parameters

point

The point to begin mapping

radius

angle

sweep

negative

Return Values


Draw Figure

  • « UI\Draw\Path::lineTo
  • UI\Draw\Path::newFigureWithArc »
  • PHP Manual
  • UI\Draw\Path
  • Draw Figure

UI\Draw\Path::newFigure

(PHP 7, UI 0.9.9)

UI\Draw\Path::newFigure — Draw Figure

Description

public UI\Draw\Path::newFigure ( UI\Point $point )

Shall map a new figure at the given point

Parameters

point

The point to begin mapping


Draw Figure with Arc

  • « UI\Draw\Path::newFigure
  • UI\Draw\Matrix »
  • PHP Manual
  • UI\Draw\Path
  • Draw Figure with Arc

UI\Draw\Path::newFigureWithArc

(PHP 7, UI 0.9.9)

UI\Draw\Path::newFigureWithArc — Draw Figure with Arc

Description

public UI\Draw\Path::newFigureWithArc ( UI\Point $point , float $radius , float $angle , float $sweep , float $negative )

Parameters

point

radius

angle

sweep

negative

Return Values


Draw Matrix

(PHP 7, UI 0.9.9)

Introduction

Class synopsis

UI\Draw\Matrix {
/* Methods */
public invert ( void )
public isInvertible ( void ) : bool
public multiply ( UI\Draw\Matrix $matrix ) : UI\Draw\Matrix
public rotate ( UI\Point $point , float $amount )
public scale ( UI\Point $center , UI\Point $point )
public skew ( UI\Point $point , UI\Point $amount )
public translate ( UI\Point $point )
}

Table of Contents

  • UI\Draw\Matrix::invert — Invert Matrix
  • UI\Draw\Matrix::isInvertible — Invertible Detection
  • UI\Draw\Matrix::multiply — Multiply Matrix
  • UI\Draw\Matrix::rotate — Rotate Matrix
  • UI\Draw\Matrix::scale — Scale Matrix
  • UI\Draw\Matrix::skew — Skew Matrix
  • UI\Draw\Matrix::translate — Translate Matrix


Invert Matrix

  • « UI\Draw\Matrix
  • UI\Draw\Matrix::isInvertible »
  • PHP Manual
  • UI\Draw\Matrix
  • Invert Matrix

UI\Draw\Matrix::invert

(PHP 7, UI 0.9.9)

UI\Draw\Matrix::invert — Invert Matrix

Description

public UI\Draw\Matrix::invert ( void )

Shall invert this matrix

Parameters

This function has no parameters.


Invertible Detection

  • « UI\Draw\Matrix::invert
  • UI\Draw\Matrix::multiply »
  • PHP Manual
  • UI\Draw\Matrix
  • Invertible Detection

UI\Draw\Matrix::isInvertible

(PHP 7, UI 0.9.9)

UI\Draw\Matrix::isInvertible — Invertible Detection

Description

public UI\Draw\Matrix::isInvertible ( void ) : bool

Shall detect if this Matrix may be inverted

Parameters

This function has no parameters.


Multiply Matrix

  • « UI\Draw\Matrix::isInvertible
  • UI\Draw\Matrix::rotate »
  • PHP Manual
  • UI\Draw\Matrix
  • Multiply Matrix

UI\Draw\Matrix::multiply

(PHP 7, UI 0.9.9)

UI\Draw\Matrix::multiply — Multiply Matrix

Description

public UI\Draw\Matrix::multiply ( UI\Draw\Matrix $matrix ) : UI\Draw\Matrix

Shall multiply this matrix with the given matrix

Parameters

This function has no parameters.

Return Values

The new Matrix


Rotate Matrix

  • « UI\Draw\Matrix::multiply
  • UI\Draw\Matrix::scale »
  • PHP Manual
  • UI\Draw\Matrix
  • Rotate Matrix

UI\Draw\Matrix::rotate

(PHP 7, UI 0.9.9)

UI\Draw\Matrix::rotate — Rotate Matrix

Description

public UI\Draw\Matrix::rotate ( UI\Point $point , float $amount )

Shall rotate this Matrix

Parameters

point

amount


Scale Matrix

  • « UI\Draw\Matrix::rotate
  • UI\Draw\Matrix::skew »
  • PHP Manual
  • UI\Draw\Matrix
  • Scale Matrix

UI\Draw\Matrix::scale

(PHP 7, UI 0.9.9)

UI\Draw\Matrix::scale — Scale Matrix

Description

public UI\Draw\Matrix::scale ( UI\Point $center , UI\Point $point )

Shall scale this Matrix

Parameters

center

point


Skew Matrix

  • « UI\Draw\Matrix::scale
  • UI\Draw\Matrix::translate »
  • PHP Manual
  • UI\Draw\Matrix
  • Skew Matrix

UI\Draw\Matrix::skew

(PHP 7, UI 0.9.9)

UI\Draw\Matrix::skew — Skew Matrix

Description

public UI\Draw\Matrix::skew ( UI\Point $point , UI\Point $amount )

Shall skew this Matrix

Parameters

point

amount


Translate Matrix

  • « UI\Draw\Matrix::skew
  • UI\Draw\Color »
  • PHP Manual
  • UI\Draw\Matrix
  • Translate Matrix

UI\Draw\Matrix::translate

(PHP 7, UI 0.9.9)

UI\Draw\Matrix::translate — Translate Matrix

Description

public UI\Draw\Matrix::translate ( UI\Point $point )

Shall translate this Matrix

Parameters

point


Color Representation

(PHP 7, UI 0.9.9)

Introduction

Represents RGBA colours, individual channels are accessible via public properties.

Class synopsis

UI\Draw\Color {
/* Constants */
const integer Red ;
const integer Green ;
const integer Blue ;
const integer Alpha ;
/* Properties */
public $r ;
public $g ;
public $b ;
public $a ;
/* Constructor */
public __construct ([ UI\Draw\Color $color ] )
public __construct ([ int $color ] )
/* Methods */
public getChannel ( int $channel ) : float
public setChannel ( int $channel , float $value ) : void
}

Properties

r

Provides access to the red channel

g

Provides access to the green channel

b

Provides access to the blue channel

a

Provides access to the alpha channel

Predefined Constants

UI\Draw\Color::Red

Identifies the red channel

UI\Draw\Color::Green

Identifies the green channel

UI\Draw\Color::Blue

Identifies the blue channel

UI\Draw\Color::Alpha

Identifies the alpha channel

Table of Contents

  • UI\Draw\Color::__construct — Construct new Color
  • UI\Draw\Color::getChannel — Color Manipulation
  • UI\Draw\Color::setChannel — Color Manipulation


Construct new Color

  • « UI\Draw\Color
  • UI\Draw\Color::getChannel »
  • PHP Manual
  • UI\Draw\Color
  • Construct new Color

UI\Draw\Color::__construct

(PHP 7, UI 0.9.9)

UI\Draw\Color::__construct — Construct new Color

Description

public UI\Draw\Color::__construct ([ UI\Draw\Color $color ] )
public UI\Draw\Color::__construct ([ int $color ] )

Shall construct a new color

Parameters

color

May be UI\Draw\Color or RRGGBBAA


Color Manipulation

  • « UI\Draw\Color::__construct
  • UI\Draw\Color::setChannel »
  • PHP Manual
  • UI\Draw\Color
  • Color Manipulation

UI\Draw\Color::getChannel

(PHP 7, UI 0.9.9)

UI\Draw\Color::getChannel — Color Manipulation

Description

public UI\Draw\Color::getChannel ( int $channel ) : float

Shall retrieve the value for a channel

Parameters

channel

Constant channel identity

Return Values

The current value of the requested channel


Color Manipulation

  • « UI\Draw\Color::getChannel
  • UI\Draw\Stroke »
  • PHP Manual
  • UI\Draw\Color
  • Color Manipulation

UI\Draw\Color::setChannel

(PHP 7, UI 0.9.9)

UI\Draw\Color::setChannel — Color Manipulation

Description

public UI\Draw\Color::setChannel ( int $channel , float $value ) : void

Shall set the selected channel to the given value

Parameters

channel

Constant channel identity

value

The new value for the selected channel

Return Values


Draw Stroke

(PHP 7, UI 0.9.9)

Introduction

Holds the configuration for the Pen to perform a stroke

Class synopsis

UI\Draw\Stroke {
/* Constructor */
public __construct ([ int $cap = UI\Draw\Line\Cap::Flat [, int $join = UI\Draw\Line\Join::Miter [, float $thickness = 1 [, float $miterLimit = 10 ]]]] )
/* Methods */
public getCap ( void ) : int
public getJoin ( void ) : int
public getMiterLimit ( void ) : float
public getThickness ( void ) : float
public setCap ( int $cap )
public setJoin ( int $join )
public setMiterLimit ( float $limit )
public setThickness ( float $thickness )
}

Table of Contents

  • UI\Draw\Stroke::__construct — Construct a new Stroke
  • UI\Draw\Stroke::getCap — Get Line Cap
  • UI\Draw\Stroke::getJoin — Get Line Join
  • UI\Draw\Stroke::getMiterLimit — Get Miter Limit
  • UI\Draw\Stroke::getThickness — Get Thickness
  • UI\Draw\Stroke::setCap — Set Line Cap
  • UI\Draw\Stroke::setJoin — Set Line Join
  • UI\Draw\Stroke::setMiterLimit — Set Miter Limit
  • UI\Draw\Stroke::setThickness — Set Thickness


Construct a new Stroke

  • « UI\Draw\Stroke
  • UI\Draw\Stroke::getCap »
  • PHP Manual
  • UI\Draw\Stroke
  • Construct a new Stroke

UI\Draw\Stroke::__construct

(PHP 7, UI 0.9.9)

UI\Draw\Stroke::__construct — Construct a new Stroke

Description

public UI\Draw\Stroke::__construct ([ int $cap = UI\Draw\Line\Cap::Flat [, int $join = UI\Draw\Line\Join::Miter [, float $thickness = 1 [, float $miterLimit = 10 ]]]] )

Shall construct a new Stroke

Parameters

cap

UI\Draw\Line\Cap::Flat, UI\Draw\Line\Cap::Round, or UI\Draw\Line\Cap::Square

join

UI\Draw\Line\Join::Miter, UI\Draw\Line\Join::Round, or UI\Draw\Line\Join::Bevel

thickness

The thickness of the stroke

miterLimit

Miter limit (default is sensible for all supported platforms)


Get Line Cap

  • « UI\Draw\Stroke::__construct
  • UI\Draw\Stroke::getJoin »
  • PHP Manual
  • UI\Draw\Stroke
  • Get Line Cap

UI\Draw\Stroke::getCap

(PHP 7, UI 0.9.9)

UI\Draw\Stroke::getCap — Get Line Cap

Description

public UI\Draw\Stroke::getCap ( void ) : int

Shall retrieve the line cap setting of this Stroke

Parameters

This function has no parameters.

Return Values

UI\Draw\Line\Cap::Flat, UI\Draw\Line\Cap::Round, or UI\Draw\Line\Cap::Square


Get Line Join

  • « UI\Draw\Stroke::getCap
  • UI\Draw\Stroke::getMiterLimit »
  • PHP Manual
  • UI\Draw\Stroke
  • Get Line Join

UI\Draw\Stroke::getJoin

(PHP 7, UI 0.9.9)

UI\Draw\Stroke::getJoin — Get Line Join

Description

public UI\Draw\Stroke::getJoin ( void ) : int

Shall retrieve the line join setting of this Stroke

Parameters

This function has no parameters.

Return Values

UI\Draw\Line\Join::Miter, UI\Draw\Line\Join::Round, or UI\Draw\Line\Join::Bevel


Get Miter Limit

  • « UI\Draw\Stroke::getJoin
  • UI\Draw\Stroke::getThickness »
  • PHP Manual
  • UI\Draw\Stroke
  • Get Miter Limit

UI\Draw\Stroke::getMiterLimit

(PHP 7, UI 0.9.9)

UI\Draw\Stroke::getMiterLimit — Get Miter Limit

Description

public UI\Draw\Stroke::getMiterLimit ( void ) : float

Shall retrieve the miter limit of this Stroke

Parameters

This function has no parameters.

Return Values

The current miter limit


Get Thickness

  • « UI\Draw\Stroke::getMiterLimit
  • UI\Draw\Stroke::setCap »
  • PHP Manual
  • UI\Draw\Stroke
  • Get Thickness

UI\Draw\Stroke::getThickness

(PHP 7, UI 0.9.9)

UI\Draw\Stroke::getThickness — Get Thickness

Description

public UI\Draw\Stroke::getThickness ( void ) : float

Shall retrieve the thickness of this Stroke

Parameters

This function has no parameters.

Return Values

The current thickness


Set Line Cap

  • « UI\Draw\Stroke::getThickness
  • UI\Draw\Stroke::setJoin »
  • PHP Manual
  • UI\Draw\Stroke
  • Set Line Cap

UI\Draw\Stroke::setCap

(PHP 7, UI 0.9.9)

UI\Draw\Stroke::setCap — Set Line Cap

Description

public UI\Draw\Stroke::setCap ( int $cap )

Shall set the line cap setting for this Stroke

Parameters

cap

UI\Draw\Line\Cap::Flat, UI\Draw\Line\Cap::Round, or UI\Draw\Line\Cap::Square


Set Line Join

  • « UI\Draw\Stroke::setCap
  • UI\Draw\Stroke::setMiterLimit »
  • PHP Manual
  • UI\Draw\Stroke
  • Set Line Join

UI\Draw\Stroke::setJoin

(PHP 7, UI 0.9.9)

UI\Draw\Stroke::setJoin — Set Line Join

Description

public UI\Draw\Stroke::setJoin ( int $join )

Shall set the line join setting for this Stroke

Parameters

join

UI\Draw\Line\Join::Miter, UI\Draw\Line\Join::Round, or UI\Draw\Line\Join::Bevel

Return Values


Set Miter Limit

  • « UI\Draw\Stroke::setJoin
  • UI\Draw\Stroke::setThickness »
  • PHP Manual
  • UI\Draw\Stroke
  • Set Miter Limit

UI\Draw\Stroke::setMiterLimit

(PHP 7, UI 0.9.9)

UI\Draw\Stroke::setMiterLimit — Set Miter Limit

Description

public UI\Draw\Stroke::setMiterLimit ( float $limit )

Set the miter limit for this Stroke

Parameters

limit

The new limit


Set Thickness

  • « UI\Draw\Stroke::setMiterLimit
  • UI\Draw\Brush »
  • PHP Manual
  • UI\Draw\Stroke
  • Set Thickness

UI\Draw\Stroke::setThickness

(PHP 7, UI 0.9.9)

UI\Draw\Stroke::setThickness — Set Thickness

Description

public UI\Draw\Stroke::setThickness ( float $thickness )

Shall set the thickness for this Stroke

Parameters

thickness

The new thickness


Brushes

(PHP 7, UI 0.9.9)

Introduction

Represents a solid color brush

Class synopsis

UI\Draw\Brush {
/* Constructor */
public __construct ( UI\Draw\Color $color )
public __construct ( int $color )
/* Methods */
public getColor ( void ) : UI\Draw\Color
public setColor ( UI\Draw\Color $color ) : void
public setColor ( int $color ) : void
}

Table of Contents

  • UI\Draw\Brush::__construct — Construct a new Brush
  • UI\Draw\Brush::getColor — Get Color
  • UI\Draw\Brush::setColor — Set Color


Construct a new Brush

  • « UI\Draw\Brush
  • UI\Draw\Brush::getColor »
  • PHP Manual
  • UI\Draw\Brush
  • Construct a new Brush

UI\Draw\Brush::__construct

(PHP 7, UI 0.9.9)

UI\Draw\Brush::__construct — Construct a new Brush

Description

public UI\Draw\Brush::__construct ( UI\Draw\Color $color )
public UI\Draw\Brush::__construct ( int $color )

Shall construct a solid brush using the given color

Parameters

color

Can be a UI\Draw\Color or RRGGBBAA


Get Color

  • « UI\Draw\Brush::__construct
  • UI\Draw\Brush::setColor »
  • PHP Manual
  • UI\Draw\Brush
  • Get Color

UI\Draw\Brush::getColor

(PHP 7, UI 0.9.9)

UI\Draw\Brush::getColor — Get Color

Description

public UI\Draw\Brush::getColor ( void ) : UI\Draw\Color

Shall return a UI\Draw\Color for this brush

Parameters

This function has no parameters.

Return Values

The current color of the brush


Set Color

  • « UI\Draw\Brush::getColor
  • UI\Draw\Brush\Gradient »
  • PHP Manual
  • UI\Draw\Brush
  • Set Color

UI\Draw\Brush::setColor

(PHP 7, UI 0.9.9)

UI\Draw\Brush::setColor — Set Color

Description

public UI\Draw\Brush::setColor ( UI\Draw\Color $color ) : void
public UI\Draw\Brush::setColor ( int $color ) : void

Shall set the color of this brush to the color provided

Parameters

color

Can be a UI\Draw\Color or RRGGBBAA

Return Values


Gradient Brushes

(PHP 7, UI 2.0.0)

Introduction

Abstract for gradient brushes

Class synopsis

abstract UI\Draw\Brush\Gradient extends UI\Draw\Brush {
/* Methods */
public addStop ( float $position , UI\Draw\Color $color ) : int
public addStop ( float $position , int $color ) : int
public delStop ( int $index ) : int
public setStop ( int $index , float $position , UI\Draw\Color $color ) : bool
public setStop ( int $index , float $position , int $color ) : bool
/* Inherited methods */
public UI\Draw\Brush::getColor ( void ) : UI\Draw\Color
public UI\Draw\Brush::setColor ( UI\Draw\Color $color ) : void
public UI\Draw\Brush::setColor ( int $color ) : void
}

Table of Contents

  • UI\Draw\Brush\Gradient::addStop — Stop Manipulation
  • UI\Draw\Brush\Gradient::delStop — Stop Manipulation
  • UI\Draw\Brush\Gradient::setStop — Stop Manipulation


Stop Manipulation

  • « UI\Draw\Brush\Gradient
  • UI\Draw\Brush\Gradient::delStop »
  • PHP Manual
  • UI\Draw\Brush\Gradient
  • Stop Manipulation

UI\Draw\Brush\Gradient::addStop

(PHP 7, UI 2.0.0)

UI\Draw\Brush\Gradient::addStop — Stop Manipulation

Description

public UI\Draw\Brush\Gradient::addStop ( float $position , UI\Draw\Color $color ) : int
public UI\Draw\Brush\Gradient::addStop ( float $position , int $color ) : int

Shall at a stop of the given color at the given position

Parameters

position

The position for the new stop

color

The color for the new stop, may be UI\Draw\Color or RRGGBBAA

Return Values

Total number of stops


Stop Manipulation

  • « UI\Draw\Brush\Gradient::addStop
  • UI\Draw\Brush\Gradient::setStop »
  • PHP Manual
  • UI\Draw\Brush\Gradient
  • Stop Manipulation

UI\Draw\Brush\Gradient::delStop

(PHP 7, UI 2.0.0)

UI\Draw\Brush\Gradient::delStop — Stop Manipulation

Description

public UI\Draw\Brush\Gradient::delStop ( int $index ) : int

Warning

This function is currently not documented; only its argument list is available.

Parameters

index

Return Values

Total number of stops


Stop Manipulation

  • « UI\Draw\Brush\Gradient::delStop
  • UI\Draw\Brush\LinearGradient »
  • PHP Manual
  • UI\Draw\Brush\Gradient
  • Stop Manipulation

UI\Draw\Brush\Gradient::setStop

(PHP 7, UI 2.0.0)

UI\Draw\Brush\Gradient::setStop — Stop Manipulation

Description

public UI\Draw\Brush\Gradient::setStop ( int $index , float $position , UI\Draw\Color $color ) : bool
public UI\Draw\Brush\Gradient::setStop ( int $index , float $position , int $color ) : bool

Parameters

index

The index of the stop to set

position

The position for the stop

color

The color for the stop, may be UI\Draw\Color or RRGGBBAA

Return Values

Indication of success


Linear Gradient

(PHP 7, UI 2.0.0)

Introduction

Class synopsis

UI\Draw\Brush\LinearGradient extends UI\Draw\Brush\Gradient {
/* Constructor */
public __construct ( UI\Point $start , UI\Point $end )
/* Inherited methods */
public UI\Draw\Brush\Gradient::addStop ( float $position , UI\Draw\Color $color ) : int
public UI\Draw\Brush\Gradient::addStop ( float $position , int $color ) : int
public UI\Draw\Brush\Gradient::delStop ( int $index ) : int
public UI\Draw\Brush\Gradient::setStop ( int $index , float $position , UI\Draw\Color $color ) : bool
public UI\Draw\Brush\Gradient::setStop ( int $index , float $position , int $color ) : bool
}

Table of Contents

  • UI\Draw\Brush\LinearGradient::__construct — Construct a Linear Gradient


Construct a Linear Gradient

  • « UI\Draw\Brush\LinearGradient
  • UI\Draw\Brush\RadialGradient »
  • PHP Manual
  • UI\Draw\Brush\LinearGradient
  • Construct a Linear Gradient

UI\Draw\Brush\LinearGradient::__construct

(PHP 7, UI 2.0.0)

UI\Draw\Brush\LinearGradient::__construct — Construct a Linear Gradient

Description

public UI\Draw\Brush\LinearGradient::__construct ( UI\Point $start , UI\Point $end )

Shall construct a new linear gradient

Parameters

start

end


Radial Gradient

(PHP 7, UI 2.0.0)

Introduction

Class synopsis

UI\Draw\Brush\RadialGradient extends UI\Draw\Brush\Gradient {
/* Constructor */
public __construct ( UI\Point $start , UI\Point $outer , float $radius )
/* Inherited methods */
public UI\Draw\Brush\Gradient::addStop ( float $position , UI\Draw\Color $color ) : int
public UI\Draw\Brush\Gradient::addStop ( float $position , int $color ) : int
public UI\Draw\Brush\Gradient::delStop ( int $index ) : int
public UI\Draw\Brush\Gradient::setStop ( int $index , float $position , UI\Draw\Color $color ) : bool
public UI\Draw\Brush\Gradient::setStop ( int $index , float $position , int $color ) : bool
}

Table of Contents

  • UI\Draw\Brush\RadialGradient::__construct — Construct a new Radial Gradient


Construct a new Radial Gradient

  • « UI\Draw\Brush\RadialGradient
  • UI\Draw\Text\Layout »
  • PHP Manual
  • UI\Draw\Brush\RadialGradient
  • Construct a new Radial Gradient

UI\Draw\Brush\RadialGradient::__construct

(PHP 7, UI 2.0.0)

UI\Draw\Brush\RadialGradient::__construct — Construct a new Radial Gradient

Description

public UI\Draw\Brush\RadialGradient::__construct ( UI\Point $start , UI\Point $outer , float $radius )

Shall construct a new radial gradient

Parameters

start

outer

radius


Represents Text Layout

(PHP 7, UI 0.9.9)

Introduction

A Text Layout represents the layout of text which will be drawn by the Pen

Class synopsis

UI\Draw\Text\Layout {
/* Constructor */
public __construct ( string $text , UI\Draw\Text\Font $font , float $width )
/* Methods */
public setColor ( UI\Draw\Color $color [, int $start = 0 [, int $end ]] )
public setColor ( int $color [, int $start = 0 [, int $end ]] )
public setWidth ( float $width )
}

Table of Contents

  • UI\Draw\Text\Layout::__construct — Construct a new Text Layout
  • UI\Draw\Text\Layout::setColor — Set Color
  • UI\Draw\Text\Layout::setWidth — Set Width


Construct a new Text Layout

  • « UI\Draw\Text\Layout
  • UI\Draw\Text\Layout::setColor »
  • PHP Manual
  • UI\Draw\Text\Layout
  • Construct a new Text Layout

UI\Draw\Text\Layout::__construct

(PHP 7, UI 0.9.9)

UI\Draw\Text\Layout::__construct — Construct a new Text Layout

Description

public UI\Draw\Text\Layout::__construct ( string $text , UI\Draw\Text\Font $font , float $width )

Shall construct a new Text Layout

Parameters

text

The text for the layout

font

The font to use for writing

width

The width of the layout


Set Color

  • « UI\Draw\Text\Layout::__construct
  • UI\Draw\Text\Layout::setWidth »
  • PHP Manual
  • UI\Draw\Text\Layout
  • Set Color

UI\Draw\Text\Layout::setColor

(PHP 7, UI 0.9.9)

UI\Draw\Text\Layout::setColor — Set Color

Description

public UI\Draw\Text\Layout::setColor ( UI\Draw\Color $color [, int $start = 0 [, int $end ]] )
public UI\Draw\Text\Layout::setColor ( int $color [, int $start = 0 [, int $end ]] )

Shall set the Color for all of, or a range of the text in the Layout

Parameters

color

The color to use

start

The starting character

end

The ending character, by default the end of the string


Set Width

  • « UI\Draw\Text\Layout::setColor
  • UI\Draw\Text\Font »
  • PHP Manual
  • UI\Draw\Text\Layout
  • Set Width

UI\Draw\Text\Layout::setWidth

(PHP 7, UI 0.9.9)

UI\Draw\Text\Layout::setWidth — Set Width

Description

public UI\Draw\Text\Layout::setWidth ( float $width )

Shall set the width of this Text Layout

Parameters

width

The new width


Represents a Font

(PHP 7, UI 0.9.9)

Introduction

Loads a described font

Class synopsis

UI\Draw\Text\Font {
/* Constructor */
public __construct ( UI\Draw\Text\Font\Descriptor $descriptor )
/* Methods */
public getAscent ( void ) : float
public getDescent ( void ) : float
public getLeading ( void ) : float
public getUnderlinePosition ( void ) : float
public getUnderlineThickness ( void ) : float
}

Table of Contents

  • UI\Draw\Text\Font::__construct — Construct a new Font
  • UI\Draw\Text\Font::getAscent — Font Metrics
  • UI\Draw\Text\Font::getDescent — Font Metrics
  • UI\Draw\Text\Font::getLeading — Font Metrics
  • UI\Draw\Text\Font::getUnderlinePosition — Font Metrics
  • UI\Draw\Text\Font::getUnderlineThickness — Font Metrics


Construct a new Font

  • « UI\Draw\Text\Font
  • UI\Draw\Text\Font::getAscent »
  • PHP Manual
  • UI\Draw\Text\Font
  • Construct a new Font

UI\Draw\Text\Font::__construct

(PHP 7, UI 0.9.9)

UI\Draw\Text\Font::__construct — Construct a new Font

Description

public UI\Draw\Text\Font::__construct ( UI\Draw\Text\Font\Descriptor $descriptor )

Shall construct a new Font using the given descriptor

Parameters

descriptor

The descriptor for the Font


Font Metrics

  • « UI\Draw\Text\Font::__construct
  • UI\Draw\Text\Font::getDescent »
  • PHP Manual
  • UI\Draw\Text\Font
  • Font Metrics

UI\Draw\Text\Font::getAscent

(PHP 7, UI 1.0.3)

UI\Draw\Text\Font::getAscent — Font Metrics

Description

public UI\Draw\Text\Font::getAscent ( void ) : float

Parameters

This function has no parameters.

Return Values


Font Metrics

  • « UI\Draw\Text\Font::getAscent
  • UI\Draw\Text\Font::getLeading »
  • PHP Manual
  • UI\Draw\Text\Font
  • Font Metrics

UI\Draw\Text\Font::getDescent

(PHP 7, UI 1.0.3)

UI\Draw\Text\Font::getDescent — Font Metrics

Description

public UI\Draw\Text\Font::getDescent ( void ) : float

Parameters

This function has no parameters.

Return Values


Font Metrics

  • « UI\Draw\Text\Font::getDescent
  • UI\Draw\Text\Font::getUnderlinePosition »
  • PHP Manual
  • UI\Draw\Text\Font
  • Font Metrics

UI\Draw\Text\Font::getLeading

(PHP 7, UI 1.0.3)

UI\Draw\Text\Font::getLeading — Font Metrics

Description

public UI\Draw\Text\Font::getLeading ( void ) : float

Parameters

This function has no parameters.

Return Values


Font Metrics

  • « UI\Draw\Text\Font::getLeading
  • UI\Draw\Text\Font::getUnderlineThickness »
  • PHP Manual
  • UI\Draw\Text\Font
  • Font Metrics

UI\Draw\Text\Font::getUnderlinePosition

(PHP 7, UI 1.0.3)

UI\Draw\Text\Font::getUnderlinePosition — Font Metrics

Description

public UI\Draw\Text\Font::getUnderlinePosition ( void ) : float

Parameters

This function has no parameters.

Return Values


Font Metrics

  • « UI\Draw\Text\Font::getUnderlinePosition
  • UI\Draw\Text\Font\Descriptor »
  • PHP Manual
  • UI\Draw\Text\Font
  • Font Metrics

UI\Draw\Text\Font::getUnderlineThickness

(PHP 7, UI 1.0.3)

UI\Draw\Text\Font::getUnderlineThickness — Font Metrics

Description

public UI\Draw\Text\Font::getUnderlineThickness ( void ) : float

Parameters

This function has no parameters.

Return Values


Font Descriptor

(PHP 7, UI 0.9.9)

Introduction

Describes a font

Class synopsis

UI\Draw\Text\Font\Descriptor {
/* Constructor */
public __construct ( string $family , float $size [, int $weight = UI\Draw\Text\Font\Weight::Normal [, int $italic = UI\Draw\Text\Font\Italic::Normal [, int $stretch = UI\Draw\Text\Font\Stretch::Normal ]]] )
/* Methods */
public getFamily ( void ) : string
public getItalic ( void ) : int
public getSize ( void ) : float
public getStretch ( void ) : int
public getWeight ( void ) : int
}

Table of Contents

  • UI\Draw\Text\Font\Descriptor::__construct — Construct a new Font Descriptor
  • UI\Draw\Text\Font\Descriptor::getFamily — Get Font Family
  • UI\Draw\Text\Font\Descriptor::getItalic — Style Detection
  • UI\Draw\Text\Font\Descriptor::getSize — Size Detection
  • UI\Draw\Text\Font\Descriptor::getStretch — Style Detection
  • UI\Draw\Text\Font\Descriptor::getWeight — Weight Detection


Construct a new Font Descriptor

  • « UI\Draw\Text\Font\Descriptor
  • UI\Draw\Text\Font\Descriptor::getFamily »
  • PHP Manual
  • UI\Draw\Text\Font\Descriptor
  • Construct a new Font Descriptor

UI\Draw\Text\Font\Descriptor::__construct

(PHP 7, UI 0.9.9)

UI\Draw\Text\Font\Descriptor::__construct — Construct a new Font Descriptor

Description

public UI\Draw\Text\Font\Descriptor::__construct ( string $family , float $size [, int $weight = UI\Draw\Text\Font\Weight::Normal [, int $italic = UI\Draw\Text\Font\Italic::Normal [, int $stretch = UI\Draw\Text\Font\Stretch::Normal ]]] )

Shall construct a new Font Descriptor

Parameters

family

The name of a valid family of fonts

size

The preferred size

weight

UI\Draw\Text\Font\Weight constant

italic

UI\Draw\Text\Font\Italic constant

stretch

UI\Draw\Text\Font\Stretch constant


Get Font Family

  • « UI\Draw\Text\Font\Descriptor::__construct
  • UI\Draw\Text\Font\Descriptor::getItalic »
  • PHP Manual
  • UI\Draw\Text\Font\Descriptor
  • Get Font Family

UI\Draw\Text\Font\Descriptor::getFamily

(PHP 7, UI 1.0.3)

UI\Draw\Text\Font\Descriptor::getFamily — Get Font Family

Description

public UI\Draw\Text\Font\Descriptor::getFamily ( void ) : string

Shall return the requested font family

Parameters

This function has no parameters.

Return Values


Style Detection

  • « UI\Draw\Text\Font\Descriptor::getFamily
  • UI\Draw\Text\Font\Descriptor::getSize »
  • PHP Manual
  • UI\Draw\Text\Font\Descriptor
  • Style Detection

UI\Draw\Text\Font\Descriptor::getItalic

(PHP 7, UI 1.0.3)

UI\Draw\Text\Font\Descriptor::getItalic — Style Detection

Description

public UI\Draw\Text\Font\Descriptor::getItalic ( void ) : int

Shall return constant setting

Parameters

This function has no parameters.

Return Values


Size Detection

  • « UI\Draw\Text\Font\Descriptor::getItalic
  • UI\Draw\Text\Font\Descriptor::getStretch »
  • PHP Manual
  • UI\Draw\Text\Font\Descriptor
  • Size Detection

UI\Draw\Text\Font\Descriptor::getSize

(PHP 7, UI 1.0.3)

UI\Draw\Text\Font\Descriptor::getSize — Size Detection

Description

public UI\Draw\Text\Font\Descriptor::getSize ( void ) : float

Shall return the requested size

Parameters

This function has no parameters.

Return Values


Style Detection

  • « UI\Draw\Text\Font\Descriptor::getSize
  • UI\Draw\Text\Font\Descriptor::getWeight »
  • PHP Manual
  • UI\Draw\Text\Font\Descriptor
  • Style Detection

UI\Draw\Text\Font\Descriptor::getStretch

(PHP 7, UI 1.0.3)

UI\Draw\Text\Font\Descriptor::getStretch — Style Detection

Description

public UI\Draw\Text\Font\Descriptor::getStretch ( void ) : int

Shall return requested stretch

Parameters

This function has no parameters.

Return Values


Weight Detection

  • « UI\Draw\Text\Font\Descriptor::getStretch
  • UI Functions »
  • PHP Manual
  • UI\Draw\Text\Font\Descriptor
  • Weight Detection

UI\Draw\Text\Font\Descriptor::getWeight

(PHP 7, UI 1.0.3)

UI\Draw\Text\Font\Descriptor::getWeight — Weight Detection

Description

public UI\Draw\Text\Font\Descriptor::getWeight ( void ) : int

Shall return requested weight

Parameters

This function has no parameters.

Return Values


UI Functions

Table of Contents

  • UI\Draw\Text\Font\fontFamilies — Retrieve Font Families
  • UI\quit — Quit UI Loop
  • UI\run — Enter UI Loop


Retrieve Font Families

  • « UI Functions
  • UI\quit »
  • PHP Manual
  • UI Functions
  • Retrieve Font Families

UI\Draw\Text\Font\fontFamilies

(PHP 7, UI 0.9.9)

UI\Draw\Text\Font\fontFamilies — Retrieve Font Families

Description

UI\Draw\Text\Font\fontFamilies ( void ) : array

Returns an array of valid font families for the current system

Parameters

This function has no parameters.


Quit UI Loop

  • « UI\Draw\Text\Font\fontFamilies
  • UI\run »
  • PHP Manual
  • UI Functions
  • Quit UI Loop

UI\quit

(PHP 7, UI 2.0.0)

UI\quit — Quit UI Loop

Description

UI\quit ( void ) : void

Shall cause the main loop to be exited

Parameters

This function has no parameters.

Return Values


Enter UI Loop

  • « UI\quit
  • UI\Draw\Text\Font\Weight »
  • PHP Manual
  • UI Functions
  • Enter UI Loop

UI\run

(PHP 7, UI 2.0.0)

UI\run — Enter UI Loop

Description

UI\run ([ int $flags ] ) : void

Shall cause PHP to enter into the main loop, by default control will not be returned to the caller

Parameters

flags

Set UI\Loop to return control, and UI\Wait to return control after waiting

Return Values


Font Weight Settings

(PHP 7, UI 0.9.9)

Introduction

Class synopsis

final UI\Draw\Text\Font\Weight {
/* Constants */
const integer Thin ;
const integer UltraLight ;
const integer Light ;
const integer Book ;
const integer Normal ;
const integer Medium ;
const integer SemiBold ;
const integer Bold ;
const integer UltraBold ;
const integer Heavy ;
const integer UltraHeavy ;
}


Italic Font Settings

(PHP 7, UI 0.9.9)

Introduction

Class synopsis

final UI\Draw\Text\Font\Italic {
/* Constants */
const integer Normal = 0 ;
const integer Oblique = 1 ;
const integer Italic = 2 ;
}


Font Stretch Settings

(PHP 7, UI 0.9.9)

Introduction

Class synopsis

final UI\Draw\Text\Font\Stretch {
/* Constants */
const integer UltraCondensed = 0 ;
const integer ExtraCondensed = 1 ;
const integer Condensed = 2 ;
const integer SemiCondensed = 3 ;
const integer Normal = 4 ;
const integer SemiExpanded = 5 ;
const integer Expanded = 6 ;
const integer ExtraExpanded = 7 ;
const integer UltraExpanded = 8 ;
}


Line Cap Settings

(PHP 7, UI 0.9.9)

Introduction

Class synopsis

final UI\Draw\Line\Cap {
/* Constants */
const integer Flat ;
const integer Round ;
const integer Square ;
}


Line Join Settings

(PHP 7, UI 0.9.9)

Introduction

Class synopsis

final UI\Draw\Line\Join {
/* Constants */
const integer Miter ;
const integer Round ;
const integer Bevel ;
}


Key Identifiers

(PHP 7, UI 1.0.0)

Introduction

Class synopsis

final UI\Key {
/* Constants */
const integer Escape ;
const integer Insert ;
const integer Delete ;
const integer Home ;
const integer End ;
const integer PageUp ;
const integer PageDown ;
const integer Up ;
const integer Down ;
const integer Left ;
const integer Right ;
const integer F1 ;
const integer F2 ;
const integer F3 ;
const integer F4 ;
const integer F5 ;
const integer F6 ;
const integer F7 ;
const integer F8 ;
const integer F9 ;
const integer F10 ;
const integer F11 ;
const integer F12 ;
const integer N0 ;
const integer N1 ;
const integer N2 ;
const integer N3 ;
const integer N4 ;
const integer N5 ;
const integer N6 ;
const integer N7 ;
const integer N8 ;
const integer N9 ;
const integer NDot ;
const integer NEnter ;
const integer NAdd ;
const integer NSubtract ;
const integer NMultiply ;
const integer NDivide ;
}


InvalidArgumentException

(PHP 7, UI 1.0.3)

Introduction

Class synopsis

UI\Exception\InvalidArgumentException extends InvalidArgumentException implements Throwable {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


RuntimeException

(PHP 7, UI 1.0.3)

Introduction

Class synopsis

UI\Exception\RuntimeException extends RuntimeException implements Throwable {
/* Inherited properties */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Inherited methods */
final public Exception::getMessage ( void ) : string
final public Exception::getPrevious ( void ) : Throwable
final public Exception::getCode ( void ) : mixed
final public Exception::getFile ( void ) : string
final public Exception::getLine ( void ) : int
final public Exception::getTrace ( void ) : array
final public Exception::getTraceAsString ( void ) : string
public Exception::__toString ( void ) : string
final private Exception::__clone ( void ) : void
}


PHP at the Core: A Hacker's Guide

  • Preface
  • Memory management
    • Basic memory management
    • Data persistence
    • Thread-Safe Resource Manager
  • Working with Variables
    • Introduction to Variables
    • Working with Arrays
    • Working with HashTable
    • Working with Objects
  • Writing Functions
  • Writing Classes
  • Working with Resources
  • Working with INI settings
  • Working with streams
  • The "counter" Extension - A Continuing Example
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Counter — The Counter class
    • Basic — The basic interface
    • Extended — The extended interface
  • The PHP 5 build system
    • Building PHP for extension development
    • The ext_skel script
    • Talking to the UNIX build system: config.m4
    • Talking to the Windows build system: config.w32
  • Extension structure
    • Files which make up an extension
    • Basic constructs
    • The zend_module structure
    • Extension globals
    • Life cycle of an extension
    • Testing an extension
  • PDO Driver How-To
    • Prerequisites
    • Preparation and Housekeeping
    • Fleshing out your skeleton
    • Building
    • Testing
    • Packaging and distribution
    • pdo_dbh_t definition
    • pdo_stmt_t definition
    • Constants
    • Error handling
  • Extension FAQs
  • Zend Engine 2 API reference
  • Zend Engine 2 Opcodes
    • Opcode Descriptions and Examples
  • Zend Engine 1
    • Old introduction
    • Streams API for PHP Extension Authors
    • Zend API: Hacking the Core of PHP
    • TSRM API


Preface

This section of the manual is written for the Hacker: someone thinking about getting their hands dirty, someone who wants an understanding of internals in order to advance their PHP skills, or maybe someone looking to write the next best extension. Whatever the reason, this section will seek to provide a good understanding of the internals of PHP, how to write extensions, how to understand existing code containing mystical macros. All of the important internal functionality is documented here, enough anyway to convince you to read the source.

Out of necessity, this section assumes the reader has a working knowledge of the C programming language, and associated tools, like compilers and terminal emulators and the like. You don't need to be the next Alan Turing, but a working knowledge is none the less essential for this section to be of any use. With just that working knowledge, this section should be enough to get you well on the way to earning the title Hacker, and you do have to earn it.

The documentation in this section is current as of PHP 5.3.3, deviations in API functionality are duly noted in the appropriate sections.

Warning

This documentation is still under development. The original Zend documentation is preserved in its entirety in the Zend Engine 1 section for those who need it before this documentation is completed.


Memory management

Table of Contents

  • Basic memory management
  • Data persistence
  • Thread-Safe Resource Manager

Memory management in the Zend Engine is deceptively simple. There are some APIs to learn, and some concepts behind them to understand, but that's about all.


Basic memory management

The engine's memory management is implemented with features important to a system like PHP. The exact functionality of the engine's memory management and the optimizations performed are out of the scope of this document. However, a good understanding of its functionality provides a basis for a good understanding of the rest of the Hacker's Guide, and introduce you to terminology and functionality used throughout PHP.

The most important of its features for the Hacker, and the first thing to mention is tracking allocations. Tracking allocations allow the memory manager to avoid leaks, a thorn in the side of most Hackers. When PHP is built in debug mode (--enable-debug), detected leaks are reported, in a perfect world they would never get to deployment.

While tracking allocations is an important, and highly useful feature, the Hacker should not become lazy! Always attempt to resolve leaks before deploying your code, a memory leak in a SAPI environment can become a very big problem, very quickly.

Another, perhaps more incidental but still noteworthy, feature is that the memory manager is the part that allows a hard limit on memory usage for each instance of PHP. As we all know, there is no such thing as unlimited. If some code is running out of memory, it is likely to be written wrong, either by the Hacker, or the programmer of PHP. Limiting the memory therefore is not a restriction on the language that is supposed to be experienced in production, it is simply a way from stopping development environments from spiraling out of control when mistakes are made, and equally, when bugs are found in production.

From the Hacker's perspective, the memory management API looks very much like libc's (or whoever the Hacker prefers !) malloc implementation.

Main memory APIs
Prototype | Description
void *emalloc(size_t size) | Allocate size bytes of memory.
void *ecalloc(size_t nmemb, size_t size) | Allocate a buffer for nmemb elements of size bytes and makes sure it is initialized with zeros.
void *erealloc(void *ptr, size_t size) | Resize the buffer ptr, which was allocated using emalloc to hold size bytes of memory.
void efree(void *ptr) | Free the buffer pointed by ptr. The buffer had to be allocated by emalloc.
void *safe_emalloc(size_t nmemb, size_t size, size_t offset) | Allocate a buffer for holding nmemb blocks of each size bytes and an additional offset bytes. This is similar to emalloc(nmemb * size + offset) but adds a special protection against overflows.
char *estrdup(const char *s) | Allocate a buffer that can hold the NULL-terminated string s and copy the s into that buffer.
char *estrndup(const char *s, unsigned int length) | Similar to estrdup while the length of the NULL-terminated string is already known.

Note: The engine's memory management functions do not return NULL upon failure, if memory cannot be allocated at runtime, the engine bails and raises an error.

Caution

Always use valgrind before deploying code and as a normal part of the Hacker's process. The engine can only report and detect leaks where it has allocated the memory. All of PHP is only a thin wrapper around third parties, those third parties do not use the engines memory management. Additionally, valgrind will catch errors that do not always halt or even have an apparent effect at execution time, it is just as important that there should be no errors, as it is important that avoidable leaks should be avoided.

Note: Some leaks are unavoidable, some libraries rely on the end of a process to free some of their structures, this is normal under some circumstances and acceptable where it is out of the Hacker's control.

While executing in a debug environment, configured with --enable-debug and --enable-zend-test, the leak function used in the next example is actually implemented by the engine and is available to call in userland.

Example #1 Leak Detection in Action

ZEND_FUNCTION(zend_leak_bytes)
{
    zend_long leakbytes = 3;

    if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l", &leakbytes) == FAILURE) {
        return;
    }

    emalloc(leakbytes);
}

The above example will output something similar to:

$ sapi/cli/php -r 'zend_leak_bytes();'
[Mon Apr 23 17:43:42 2018]  Script:  'Standard input code'
/home/mbaynton/projects/php-src/ext/zend_test/test.c(106) :  Freeing 0x00007f3203c92050 (3 bytes), script=Standard input code
=== Total 1 memory leaks detected ===

Note: USE_ZEND_ALLOC=0 in the environment will stop the memory manager from functioning, all allocations fall back on the default system allocators which can be useful for debugging leaks, and should only be used for this purpose.


Data persistence

In this context, data persistence is taken to mean any data that is intended to survive the current request. The memory management within the engine is very focused on request bound allocations, but this is not always practical or appropriate. Persistent memory is sometimes required in order to satisfy requirements of external libraries, it can also be useful while Hacking.

A common use of persistent memory is to enable persistent SQL server connections, though this practice is frowned upon, it is none the less the most common use of this feature.

Note: All of the following functions take the additional persistent parameter, should this be false, the engine will use its regular allocators (emalloc) and the memory should not be considered persistent. Where memory is allocated as persistent, system allocators are invoked, under most circumstances they are still not able to return NULL pointers just as the Main memory APIs.

Persistent memory APIs
Prototype | Description
void *pemalloc(size_t size, zend_bool persistent) | Allocate size bytes of memory.
void *pecalloc(size_t nmemb, size_t size, zend_bool persistent) | Allocate a buffer for nmemb elements of size bytes and makes sure it is initialized with zeros.
void *perealloc(void *ptr, size_t size, zend_bool persistent) | Resize the buffer ptr, which was allocated using emalloc to hold size bytes of memory.
void pefree(void *ptr, zend_bool persistent) | Free the buffer pointed by ptr. The buffer had to be allocated by pemalloc.
void *safe_pemalloc(size_t nmemb, size_t size, size_t offset, zend_bool persistent) | Allocate a buffer for holding nmemb blocks of each size bytes and an additional offset bytes. This is similar to pemalloc(nmemb * size + offset) but adds a special protection against overflows.
char *pestrdup(const char *s, zend_bool persistent) | Allocate a buffer that can hold the NULL-terminated string s and copy the s into that buffer.
char *pestrndup(const char *s, unsigned int length, zend_bool persistent) | Similar to pestrdup while the length of the NULL-terminated string is already known.
Caution

It is important to remember that memory allocated to be persistent is not optimized or tracked by the engine; it is not subject to memory_limit, additionally, all variables that are created by the Hacker for the engine must not use persistent memory.


Thread-Safe Resource Manager

When PHP is built with Thread Safety enabled, the engine requires a way to isolate contexts from one another, such that the threads of a process may service individual requests without interference. TSRM is omnipotent within PHP, extension authors have to do very little in order to make sure their extensions can function in both a Thread Safe and Non Thread Safe architecture.

Example #1 Accessor macros for per-module globals

#ifdef ZTS
#define COUNTER_G(v) TSRMG(counter_globals_id, zend_counter_globals *, v)
#else
#define COUNTER_G(v) (counter_globals.v)
#endif

The snippet above shows how an extension author is expected to define their global accessors. The TSRMG macro takes an identifier, type cast and element name. The identifier is assigned by TSRM during initialization of the module. Declaring global accessors in this way ensures that an extension can operate safely in a Thread Safe and Non Thread Safe architecture using the same logic.

TSRM manages the isolation and safety of all global structures within PHP, from executor globals to extension globals, a pointer to the isolated storage is also passed around with most, or many of the API functions. The macros TSRMLS_C and TSRMLS_CC translate to "thread safe local storage" and "thread safe local storage prefixed with a comma" respectively.

If a function requires a pointer to TSRM, it is declared with the macro TSRMLS_D or TSRMLS_DC in it's prototype, which translates to "thread safe local storage only" and "thread safe local storage prefixed with a comma" respectively. Many macros within the engine reference TSRM, so it is a good idea to declare most things to accept TSRM, such that if they need to call upon TSRM they do not have to fetch a pointer during execution.

Because TSRM is thread local, and some functions (for compatibility reasons) are not able to accept TSRM directly, the macro TSRMLS_FETCH exists, which requests that TSRM fetches the pointer to the thread local storage. This should be avoided wherever it can be, as it is not without cost in a Thread Safe setup.

Note: While developing extensions, build errors that contain "tsrm_ls is undefined" or errors to that effect stem from the fact that TSRMLS is undefined in the current scope, to fix this, declare the function to accept TSRMLS with the appropriate macro, if the prototype of the function in question cannot be changed, you must call TSRMLS_FETCH within the function body.

The functionality documented hereafter is aimed at advanced use of TSRM. It is not ordinary for extensions to have to interact with TSRM directly, the pecl programmer should use API's above TSRM such as the Module Globals API.

TSRM Internals
Prototype | Description
typedef int ts_rsrc_id | The type definition to represent a resource by numeric identifiers
int tsrm_startup(int expected_threads, int expected_resources, int debug_level, char *debug_filename) | expected_threads and expected_resources are not hard limits. debug_level and debug_filename only have an effect on windows in Debug mode or when TSRM_DEBUG is defined. Called once per process in ZTS mode during server startup.
void tsrm_shutdown(void) | Should be the last thing called in the process to destroy and free all storage TSRM storage in ZTS mode.
ts_rsrc_id ts_allocate_id(ts_rsrc_id *rsrc_id, size_t size, ts_allocate_ctor ctor, ts_allocate_dtor dtor) | Allocates and thread safe pointer of size bytes, calling ctor on the pointer, assigning (and returning) the id to rsrc_id, the dtor is called when the resource is free'd. Module globals are isolated in ZTS mode using this API.
void *ts_resource_ex(ts_rsrc_id id, THREAD_T *th_id) | Fetches a resource by previously allocated id from the entries created by the specified thread identifed by th_id.
void *ts_resource(ts_rsrc_id id) | Fetches a resource by previously allocated id from the entries created by the calling thread.
void ts_free_thread(void) | Destroys and frees the entries for the calling thread, currently this API is only used by ISAPI module.
void ts_free_id(ts_rsrc_id id) | Destroys the resource identified by previously allocated id. Module globals are cleaned up in ZTS mode using this API.

Note: There are more TSRM API functions to enable the creation and destruction of interpreter contexts, the usage of such functionality is out of the scope of this documentation, please see TSRM/TSRM.h for more information.

TSRM Mutex API
Prototype | Description
MUTEX_T tsrm_mutex_alloc(void) | Allocates and returns a suitable MUTEX_T for the environment.
int tsrm_mutex_lock(MUTEX_T mutexp) | Locks mutexp for the calling thread.
int tsrm_mutex_unlock(MUTEX_T mutexp) | Unlocks mutexp for the calling thread.
void tsrm_mutex_free(MUTEX_T mutexp); | Destroys and frees the (unlocked) and previously allocated mutexp.

Note: The mutex API is exposed by TSRM. However, its internal usage is far too wide to document usefully here, none the less, basic functionality and prototypes are documented here.


  • « Thread-Safe Resource Manager
  • Introduction to Variables »
  • PHP Manual
  • PHP at the Core: A Hacker's Guide
  • Working with Variables

Working with Variables

Table of Contents

  • Introduction to Variables
  • Working with Arrays
  • Working with HashTable
  • Working with Objects


Introduction to Variables

A good understanding of how variables are stored and manipulated is essential to becoming a Hacker. The engine attempts to cover up the complexity of the concept of a variable that can be any type by providing a uniform and intuitive set of macros for accessing the structures various fields. As the Hacker works through this chapter, they should become comfortable with the terminology and concepts involved with Variables in PHP.

Note:

PHP is a dynamic, loosely typed language, that uses copy-on-write and reference counting.

To clarify what exactly is meant by the statement above: PHP is a high level language, weak typing is implicit of the engines preference to convert, or coerce variables into the required type at execution time. Reference counting is the means by which the engine can deduce when a variable no longer has any references in the users code, and so is able to free the structures associated with the variable.

All variables in PHP are represented by one structure, the zval:

typedef struct _zval_struct {
    zvalue_value value;        /* variable value */
    zend_uint refcount__gc;    /* reference counter */
    zend_uchar type;           /* value type */
    zend_uchar is_ref__gc;     /* reference flag */
} zval;

The zval_value is a union which can represent all types a variable may hold:

typedef union _zvalue_value {
    long lval;                 /* long value */
    double dval;               /* double value */
    struct {
        char *val;
        int len;               /* this will always be set for strings */
    } str;                     /* string (always has length) */
    HashTable *ht;             /* an array */
    zend_object_value obj;     /* stores an object store handle, and handlers */
} zvalue_value;

It should be clear from the structures above that a variable can be of one type, the variable data is represented by the appropriate field in the zval_value union. The zval itself holds the type, reference count and a flag to indicate if a variable is a reference.

Native Type Constants
Constant | Mapping
IS_NULL | no value is set in this case
IS_LONG | lval
IS_DOUBLE | dval
IS_BOOL | lval
IS_RESOURCE | lval
IS_STRING | str
IS_ARRAY | ht
IS_OBJECT | obj

Note:

There are additional constants that help to identify internal types such as constant arrays and callable objects, their usage is outside the scope of this part of the documentation.

The following table defines the macros exposed by the engine for working with zval values:

Accessor Macros
Prototype | Accesses | Description
zend_uchar Z_TYPE(zval zv) | type | returns the type of the value
long Z_LVAL(zval zv) | value.lval |
zend_bool Z_BVAL(zval zv) | value.lval | cast long value to zend_bool
double Z_DVAL(zval zv) | value.dval |
long Z_RESVAL(zval zv) | value.lval | returns the resource list identifier for value
char* Z_STRVAL(zval zv) | value.str.val | return the string value
int Z_STRLEN(zval zv) | value.str.len | return the length of the string value
HashTable* Z_ARRVAL(zval zv) | value.ht | return the HashTable (array) value
zend_object_value Z_OBJVAL(zval zv) | value.obj | returns object value
uint Z_OBJ_HANDLE(zval zv) | value.obj.handle | returns the object handle for object value
zend_object_handlers* Z_OBJ_HT_P(zval zv) | value.obj.handlers | returns the handler table for object value
zend_class_entry* Z_OBJCE(zval zv) | value.obj | returns the class entry for object value
HashTable* Z_OBJPROP(zval zv) | value.obj | returns the properties of object value
HashTable* Z_OBJPROP(zval zv) | value.obj | returns the properties of object value
HashTable* Z_OBJDEBUG(zval zv) | value.obj | if an object has the get_debug_info handler set, it is called, else Z_OBJPROP is called

Please check the Reference Counting Basics chapter for details how reference counting and references work in detail.

Reference Count Manipulation
Prototype | Description
zend_uint Z_REFCOUNT(zval zv) | returns the reference count of the value
zend_uint Z_SET_REFCOUNT(zval zv) | sets the reference count of the value, returning it
zend_uint Z_ADDREF(zval zv) | pre-increments the reference count of value, returning it
zend_uint Z_DELREF(zval zv) | pre-decrements the reference count of value, returning it
zend_bool Z_ISREF(zval zv) | tells if the zval is a reference
void Z_UNSET_ISREF(zval zv) | set is_ref__gc to 0
void Z_SET_ISREF(zval zv) | set is_ref__gc to 1
void Z_SET_ISREF_TO(zval zv, zend_uchar to) | set is_ref__gc to to

Note:

The Z_* macros above all take a zval, they are all defined again suffixed with _P to take a pointer to a zval, for example zend_uchar Z_TYPE_P(zval* pzv), and again suffixed with _PP to take a pointer to a pointer to a zval, for example zend_uchar Z_TYPE_PP(zval** ppzv)

Creation, Destruction, Separation and Copying
Prototype | Description
ALLOC_ZVAL(zval* pzval) | emallocs pzval
ALLOC_INIT_ZVAL(zval* pzval) | emallocs pzval, and points pzval at a null typed zval for sanity
MAKE_STD_ZVAL(zval* pzval) | emallocs pzval, setting the refcount to 1
ZVAL_COPY_VALUE(zval* dst, zval* src) | sets the value and type of dst from the value and type of src
INIT_PZVAL_COPY(zval* dst, zval*dst) | performs ZVAL_COPY_VALUE, setting refcount of dst to 1, and setting is_ref__gc to 0
SEPARATE_ZVAL(zval** ppzval) | if the refcount of ppzval is >1, redirects *ppzval to a newly emalloc'd, copied, and constructed zval of the same type and value
SEPARATE_ZVAL_IF_NOT_REF(zval** ppzval) | if *ppzval is not a reference, will perform SEPARATE_ZVAL on ppzval
SEPARATE_ZVAL_TO_MAKE_IS_REF(zval** ppzval) | if *ppzval is not a reference, performs SEPARATE_ZVAL then Z_SET_ISREF_PP on ppzval
COPY_PZVAL_TO_ZVAL(zval dst, zval** src) | results in dst being a copy of src without affecting the refcount of src
MAKE_COPY_ZVAL(zval** src, zval* dst) | performs INIT_PZVAL_COPY, then zval_copy_ctor on the new zval
void zval_copy_ctor(zval** pzval) | performs maintenance of reference counts, used widely throughout the engine
void zval_ptr_dtor(zval* pzval) | decrements the refcount for the variable, if no refcounts remain the variable is destroyed
FREE_ZVAL(zval* pzval) | efrees pzval

Note:

Objects and Resources have a reference count as part of their respective structures, when zval_ptr_dtor is called on either, their appropriate del_ref method is executed. See Working with Objects and Working with Resources for more information.

If the Hacker only has room to remember two more functions, they should be zval_copy_ctor and zval_ptr_dtor, these are at the basis of the engines reference counting mechanisms and it is important to note that zval_copy_ctor does not actually result in any copying occuring under normal circumstances, it simply increases the reference count. By the same token, zval_ptr_dtor only really destroys a variable when there are no references remaining to it and the refcount is at 0.

PHP is weakly typed, as such the engine provides API functions for converting variables from one type to another.

Type Conversion
Prototype
void convert_to_long(zval* pzval)
void convert_to_double(zval* pzval)
void convert_to_long_base(zval* pzval, int base)
void convert_to_null(zval* pzval)
void convert_to_boolean(zval* pzval)
void convert_to_array(zval* pzval)
void convert_to_object(zval* pzval)
void convert_object_to_type(zval* pzval, convert_func_t converter)

Note:

convert_func_t functions should have the prototype (void) (zval* pzval)

By now you should have a good understanding of: the types that are native to the engine, how to detect types and read zval values, how to manipulate refcounts, and other zval flags


Working with Arrays

Arrays are stored in HashTable strucures, and have the zval type IS_ARRAY. The API functions for creating, destroying and manipulating these structures as variables are documented here and can be found in Zend/zend_API.h

HashTable as Variable API
Prototype | Description
void array_init(zval* pzval) | initializes the variable as a HashTable, setting type and appropriate destructor function for the HashTable
void array_init_size(zval* pzval) | initializes the variable as array_init with a minimum of size buckets

Note:

Do not squint too hard looking for array_destroy: to destroy a variable array you should call zval_ptr_dtor on the variable, if there are no other references to the variable it will result in the array being destroyed.

Indexed Arrays API
Prototype
int add_index_long(zval* pzval, ulong index, long value)
int add_index_null(zval* pzval, ulong index)
int add_index_bool(zval* pzval, ulong index, zend_bool value)
int add_index_bool(zval* pzval, ulong index, zend_bool value)
int add_index_resource(zval* pzval, ulong index, uint value)
int add_index_double(zval* pzval, ulong index, double value)
int add_index_string(zval* pzval, ulong index, char* string, zend_bool duplicate)
int add_index_stringl(zval* pzval, ulong index, char* string, uint length, zend_bool duplicate)
int add_index_zval(zval* pzval, ulong index, zval* value)
int add_next_index_long(zval* pzval, long value)
int add_next_index_null(zval* pzval)
int add_next_index_bool(zval* pzval, zend_bool value)
int add_next_index_resource(zval* pzval, uint value)
int add_next_index_double(zval* pzval, double value)
int add_next_index_string(zval* pzval, const char* string, zend_bool dulpicate)
int add_next_index_stringl(zval* pzval, const char* string, uint length, zend_bool duplicate)
int add_next_index_zval(zval* pzval, zval* value)
Associative Arrays API
Prototype
int add_assoc_long(zval* pzval, const char* key, long value)
int add_assoc_long_ex(zval* pzval, const char* key, uint klen, long value)
int add_assoc_null(zval* pzval, const char* key)
int add_assoc_null_ex(zval* pzval, const char* key, uint klen)
int add_assoc_bool(zval* pzval, const char* key, zend_bool value)
int add_assoc_bool(zval* pzval, const char* key, zend_bool value)
int add_assoc_bool_ex(zval* pzval, const char* key, uint klen, zend_bool value)
int add_assoc_resource(zval* pzval, const char* key, uint value)
int add_assoc_resource_ex(zval* pzval, const char* key, uint klen, uint value)
int add_assoc_double(zval* pzval, const char* key, double value)
int add_assoc_double_ex(zval* pzval, const char* key, uint klen, double value)
int add_assoc_string(zval* pzval, const char* key, const char* value)
int add_assoc_string_ex(zval* pzval, const char* key, uint klen, const char* value)
int add_assoc_stringl(zval* pzval, const char* key, const char* value, uint vlen, zend_bool duplicate)
int add_assoc_stringl_ex(zval* pzval, const char* key, uint klen, const char* value, uint vlen, zend_bool duplicate)
int add_assoc_zval(zval* pzval, const char* key, zval* value)
int add_assoc_zval_ex(zval* pzval, const char* key, uint klen, zval* value)

Note:

add_*_string functions that accept a parameter named duplicate, will duplicate the string with estrndup when duplicate is true

Note:

add_*_zval functions do not adjust the refcount of the value parameter

To perform more advanced operations on array variables we must use the HashTable API directly.


Working with HashTable

The HashTable structure serves many purposes in PHP and can be found everywhere, a good understanding of it's functionality is a prerequisite of being a good Hacker.

The HashTable implemented by the engine is a standard HashTable, that is to say, a key => value based store, where the keys are always strings, whose hashes are calculated with a built in hashing algorithm zend_inline_hash_func(const char* key, uint length), which results in good distribution, and reasonable usage.

The internal structure and exact operation of HashTable is out of the scope of this document, this document serves to inform you of the API's available and how best to use them. For a more detailed picture of the HashTable see Zend/zend_hash.h.

Unless otherwise stated, these functions all return FAILURE if the requested operation fails for any reason, otherwise SUCCESS is returned.

Note:

It is important to remember that ordinarily HashTable API functions expect key lengths to be the length of the null terminated string, including the null termination, in other words they expect strlen(key) + 1

Below are some typedefs you should know when interacting with HashTable. They are mostly self explanitory and will allow the Hacker to fully understand the prototypes below properly.

typedef ulong (*hash_func_t)(const char *arKey, uint nKeyLength); /* mostly redundant */
typedef int  (*compare_func_t)(const void *, const void * TSRMLS_DC); /* comparison function */
typedef void (*sort_func_t)(void *, size_t, register size_t, compare_func_t TSRMLS_DC); /* sorting function */
typedef void (*dtor_func_t)(void *pDest); /* destructor function */
typedef void (*copy_ctor_func_t)(void *pElement); /* copy constructor */
typedef void (*copy_ctor_param_func_t)(void *pElement, void *pParam); /* copy with argument constructor */
typedef int (*apply_func_t)(void *pDest TSRMLS_DC); /* apply function */
typedef int (*apply_func_arg_t)(void *pDest, void *argument TSRMLS_DC); /* apply with argument function */
typedef int (*apply_func_args_t)(void *pDest TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key); /* apply with multiple arguments function */
HashTable API
int zend_hash_init(HashTable* ht, uint size, hash_func_t hash, dtor_func_t destructor, zend_bool persistent)
Initializes the hash table to hold at least size elements, hash exists for historical reasons and is always ignored, zend_inline_hash_func is always used as the hashing function. destructor may be NULL.
int zend_hash_add(HashTable* ht, const char* key, uint klen, void* data, uint dlen, void** dest)
adds data to the table using the specified key, where the key is length bytes long (and will be copied from key to the table). If the key is set FAILURE will be returned.
int zend_hash_update(HashTable* ht, const char* key, uint klen, void* data, uint dlen, void** dest)
adds data to the table using the specified key, where the key is length bytes long (and will be copied from key to the table). If the key has been set previously the old data has dtor_func_t called on it and the existing data is replaced with data
int zend_hash_find(HashTable* ht, const char* key, uint klen, void** data)
searches the table for key, setting *data and returning SUCCESS if it is found.
zend_bool zend_hash_exists(HashTable* ht, const char* key, uint klen)
returns positively if key is found in ht
int zend_hash_del(HashTable* ht, const char* key, uint klen)
removes the entry identified by key from the table if found
int zend_hash_index_update(HashTable* ht, ulong index, void* data, uint dsize, void** dest)
updates the entry at index in ht, with the data at data
int zend_hash_index_del(HashTable* ht, ulong index)
deletes the entry at index from ht
int zend_hash_index_find(HashTable* ht, ulong index, void** data)
redirects *data to the data identified by index in ht
int zend_hash_index_exists(HashTable* ht, ulong index)
returns positively if index is found in ht
ulong zend_hash_next_free_element(HashTable* ht)
returns the index of the next free element in ht
Caution

zend_hash_* functions that accept void* data should normally cast it to (void**) (ie, (void**) &data)

Traversing the HashTable is often necessary, to do this you provide a pointer to a HashTable, with an optional HashPosition - a structure internal to the HashTable API that allows traversal not to affect the internal position of HashTable. The following traversal functions are provided, and an example usage found below.

HashTable Traversal API
int zend_hash_internal_pointer_reset(HashTable* ht)
resets the internal pointer of ht to the start
int zend_hash_internal_pointer_reset_ex(HashTable* ht, HashPosition position)
sets position to the start of ht
int zend_hash_get_current_data(HashTable* ht, void* data)
gets the data at the current position in ht, data should be cast to void**, ie: (void**) &data
int zend_hash_get_current_data_ex(HashTable* ht, void* data, HashPosition position)
sets data to the data at position in ht
int zend_hash_get_current_key(HashTable* ht, void* data, char**key, uint klen, ulong index, zend_bool duplicate)
sets key, klen, and index from the key information at the current position. The possible return values HASH_KEY_IS_STRING and HASH_KEY_IS_LONG are indicative of the kind of key found at the current posision.
int zend_hash_get_current_key_ex(HashTable* ht, void* data, char**key, uint klen, ulong index, zend_bool duplicate, HashPosition position)
sets key, klen, and index from the key information at position. The possible return values HASH_KEY_IS_STRING and HASH_KEY_IS_LONG are indicative of the kind of key found at position.
int zend_hash_move_forward(HashTable* ht)
moves the internal pointer of ht to the next entry in ht
int zend_hash_move_forward_ex(HashTable* ht, HashPosition position)
moves position to the next entry in ht

The functions above allow traversal over a HashTable to be much like a normal loop, which will look something like:

HashPosition position;
zval **data = NULL;

for (zend_hash_internal_pointer_reset_ex(ht, &position);
     zend_hash_get_current_data_ex(ht, (void**) &data, &position) == SUCCESS;
     zend_hash_move_forward_ex(ht, &position)) {

     /* by now we have data set and can use Z_ macros for accessing type and variable data */

     char *key = NULL;
     uint  klen;
     ulong index;

     if (zend_hash_get_current_key_ex(ht, &key, &klen, &index, 0, &position) == HASH_KEY_IS_STRING) {
         /* the key is a string, key and klen will be set */
     } else {
         /* we assume the key to be long, index will be set */
     }
}

Note:

If a HashTable has been passed into the engine, it is a good idea to use the zend_hash_*_ex API to avoid unexpected behaviour in userland.

Note:

If a duplicate of the key is requested and HAS_KEY_IS_STRING is returned the caller must efree the duplicated key

In addition to traversal, the engine provides API functions for merging, copying, and comparing HashTables. These are all concepts that the Hacker should be familiar with. A concept possibly not in the repertoire of the Hacker is applying, which is lamens terms is functionality of the HashTable API allowing the Hacker to pass a callback function to be executed on every entry in a HashTable.

Copying, Merging and Sorting
void zend_hash_copy(HashTable *target, HashTable *source, copy_ctor_func_t pCopyConstructor, void *tmp, uint size)
Copies the contents of source to target. tmp should be an unallocated temporary pointer of the appropriate type, used during copying. size is the size of each element.
void zend_hash_merge(HashTable *target, HashTable *source, copy_ctor_func_t pCopyConstructor, void *tmp, uint size, zend_bool overwrite)
Merges the contents of source into destination, replacing existing entries only where overwrite is true.
void int zend_hash_sort(HashTable *ht, sort_func_t sort_func, compare_func_t compare_func, int renumber TSRMLS_DC)
renumber controls if indexes should be preserved, see the typedefs at the start of this section for more information

Note:

When a function accepts a copy_ctor_func_t pCopyConstructor, the function passed with be executed upon creation of every new entry in the HashTable. The most common copy constructor used within the engine is a wrapper around zval_copy_ctor, the macro ZVAL_COPY_CTOR.


  • « Working with HashTable
  • Writing Functions »
  • PHP Manual
  • Working with Variables
  • Working with Objects

Working with Objects


Writing Functions

Functions and Methods in PHP take much the same form, a method is simply a function with a specific scope; the scope of their class entry. The Hacker will read about class entries in other sections of the Hacker's guide. The purpose of this section is to introduce the Hacker to the anatomy of a function or method; the Hacker will learn how to define functions, how to accept variables and how to return variables to the programmer of PHP.

The anatomy of a function could not be simpler:

PHP_FUNCTION(hackers_function) {
  /* your accepted arguments here */
  long number;

  /* accepting arguments */
  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &number) != SUCCESS) {
      return;
  }

  /* do some work on the input */
  number *= 2;

  /* set return value */
  RETURN_LONG(number);
}

The PHP_FUNCTION(hackers_function) preprocessor instruction will result in the following declaration:

void zif_hackers_function(INTERNAL_FUNCTION_PARAMETERS)

INTERNAL_FUNCTION_PARAMETERS is defined as a macro and explained in the following table:

INTERNAL_FUNCTION_PARAMETERS
Name and type | Description | Access macros
int ht | Number of actual parameters passed by user | ZEND_NUM_ARGS()
zval *return_value | Pointer to a PHP variable that can be filled with the return value passed to the user. The default type is IS_NULL. | RETVAL_*, RETURN_*
zval **return_value_ptr | When returning references to PHP set this to a pointer to your variable. It is not suggested to return references. |
zval *this_ptr | If this is a method call, points to the PHP variable holding the $this object. | getThis()
int return_value_used | Flag indicating whether the returned value will be used by the caller. |

For clarity, the fully expanded declaration for PHP_FUNCTION(hackers_function) looks like:

void zif_hackers_function(int ht, zval* return_value, zval** return_value_ptr, zval* this_ptr, int return_value_used)

The presence of this_ptr may be confusing, classes are covered in detail in later sections, suffice to say that PHP_METHOD(MyClass, hackersFunction) would result in the following declaration:

void zim_MyClass_hackersFunction(INTERNAL_FUNCTION_PARAMETERS)

hackers_function doesn't do anything useful, it accepts a number using the zend_parse_parameters API, doubles it, and returns it to the engine. It is obvious that a normal function would have to do something more complex than double the input, for the purposes of education we are keeping it simple. On entry to the function return_value is allocated and initialized to null, making null the default return value of any function in PHP.

If zend_parse_parameters does not recieve what is specified by the Hacker as the correct arguments, and the arguments recieved cannot be converted to conform with type_spec an error will be raised, and by convention, the Hacker should return immediately.

Note:

Arrays, Objects, and Resources cannot be converted.

Parsing Parameters Prototypes
int zend_parse_parameters(int num_args TSRMLS_DC, char *type_spec, ...)
int zend_parse_parameters_ex(int flags, int num_args TSRMLS_DC, char *type_spec, ...)
int zend_parse_parameter(int flags, int arg_num TSRMLS_DC, zval **arg, const char *spec, ...)

Note:

zend_parse_parameter is available from version 5.5, it behaves like zend_parse_parameters_ex except that instead of reading the arguments from the stack, it receives a single zval to convert, which may be changed in place.

Note:

flags is intended to be a mask, currently only ZEND_PARSE_PARAMS_QUIET will have any impact (supress warnings)

The variable arguments recieved by these API functions are expected to be the address of C variables, and should be considered the output of the zend_parse_parameters API functions.

Type Specifiers
Spec | Type | Locals
a | array | zval*
A | array or object | zval*
b | boolean | zend_bool
C | class | zend_class_entry*
d | double | double
f | function | zend_fcall_info*, zend_fcall_info_cache*
h | array | HashTable*
H | array or object | HashTable*
l | long | long
L | long (limits out-of-range LONG_MAX/LONG_MIN) | long
o | object | zval*
O | object (of specified zend_class_entry) | zval*, zend_class_entry*
p | string (a valid path) | char*, int
r | resource | zval*
s | string | char*, int
z | mixed | zval*
Z | mixed | zval**

Note:

Where the type specifier is O, the local zend_class_entry* is to be considered input (part of the type spec) to zend_parse_parameter

Advanced Type Specifiers
Spec | Description
* | a variable number of argument of the preceeding type, 0 or more
+ | a variable number of argument of the preceeding type, 1 or more
| | indicates that the remaining parameters are optional
/ | SEPARATE_ZVAL_IF_NOT_REF on the parameter it follows
! | the preceeding parameter can be of the specified type or null For 'b', 'l' and 'd', an extra argument of type zend_bool* must be passed after the corresponding bool*, long* or double* addresses which will be set true if null is recieved.

Note:

Consult README.PARAMETER_PARSING_API included in source distributions for more information on parsing parameters

Once the Hacker's function has executed whatever it was implemented to execute, it is time to set the return_value for the engine. The RETURN_ and RETVAL_ macros are just wrappers around Z_*_P macros that work with return_value.

Note:

RETURN_ macros cause execution to leave the function immediately (ie: return;), while RETVAL_ macros allow execution to continue after return_value has been set.

The Hacker should now have a reasonable understanding of the anatomy of a function, and to some degree, the anatomy of a method.


  • « Writing Functions
  • Working with Resources »
  • PHP Manual
  • PHP at the Core: A Hacker's Guide
  • Writing Classes

Writing Classes


  • « Writing Classes
  • Working with INI settings »
  • PHP Manual
  • PHP at the Core: A Hacker's Guide
  • Working with Resources

Working with Resources

This section will serve to introduce the Hacker to the concept and usage of Resources in PHP.


  • « Working with Resources
  • Working with streams »
  • PHP Manual
  • PHP at the Core: A Hacker's Guide
  • Working with INI settings

Working with INI settings


  • « Working with INI settings
  • The "counter" Extension - A Continuing Example »
  • PHP Manual
  • PHP at the Core: A Hacker's Guide
  • Working with streams

Working with streams

Note:

Information on using streams within the PHP source code can be found in the Streams API for PHP Extension Authors reference.


The "counter" Extension - A Continuing Example

Table of Contents

  • Installing/Configuring
  • Predefined Constants
  • Examples
  • Counter
  • Basic
  • Extended

Preface

Throughout this Zend documentation, references are made to an example module in order to illustrate various concepts. The "counter" extension is this example, a fictional yet functional Zend module which strives to use as much of the Zend API as is reasonably possible. This short chapter describes the userland interface to the completed extension.

Note: "counter" serves no practical purpose whatsoever, as the functionality it provides is far more effectively implemented by appropriate userland code.


  • « The "counter" Extension - A Continuing Example
  • Introduction »
  • PHP Manual
  • The "counter" Extension - A Continuing Example
  • Installing/Configuring

Installing/Configuring

Table of Contents

  • Introduction
  • Runtime Configuration
  • Resource Types


Introduction

The "counter" extension provides any number of counters to PHP code using it which reset at times determined by the caller.

There are three interfaces to "counter": basic, extended, and objective. The basic interface provides a single counter controlled by INI settings and function calls. The extended interface provides an arbitrary number of named counter resources which may optionally persist beyond the lifetime of a single PHP request. The objective interface combines both the basic and extended interfaces into a Counter class.


Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Counter configuration options
Name | Default | Changeable | Changelog
counter.reset_time | COUNTER_RESET_PER_REQUEST | PHP_INI_ALL |
counter.save_path | "" | PHP_INI_ALL |
counter.initial_value | "0" | PHP_INI_ALL |

For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set.

counter.reset_time integer
counter.reset_time tells "counter" to reset the counter used by the basic interface. It may be any of the COUNTER_RESET_* constants (see below).
counter.save_path string
Tells "counter" where to save data that has to persist between invocations of PHP (i.e. any counter that has COUNTER_RESET_NEVER or COUNTER_FLAG_SAVE). A file will be created at this path, which must be readable and writable to whatever user PHP is running as.
counter.initial_value integer
Sets the initial value of the counter used by the basic interface whenever it is reset.


  • « Runtime Configuration
  • Predefined Constants »
  • PHP Manual
  • Installing/Configuring
  • Resource Types

Resource Types

The "counter" extension defines one resource type: a counter.


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.

COUNTER_FLAG_PERSIST (integer)
A counter with this flag will be created as a persistent resource.
COUNTER_FLAG_SAVE (integer)
A counter with this flag will be saved between invocations of PHP.
COUNTER_FLAG_NO_OVERWRITE (integer)
This flag causes counter_create() to avoid overwriting an existing named counter with a new one.
COUNTER_META_NAME (string)
Pass this constant to get the name of a counter resource or object.
COUNTER_META_IS_PERISTENT (string)
Pass this constant to determine whether a counter resource or object is persistent (has the COUNTER_FLAG_PERSIST flag).
COUNTER_RESET_NEVER (integer)
The counter will never be reset.
COUNTER_RESET_PER_LOAD (integer)
The counter will be reset on each invocation of PHP.
COUNTER_RESET_PER_REQUEST (integer)
The counter will be reset on each request.


  • « Predefined Constants
  • Basic interface »
  • PHP Manual
  • The "counter" Extension - A Continuing Example
  • Examples

Examples

Table of Contents

  • Basic interface
  • Extended interface
  • Objective interface


Basic interface

The basic interface provides three simple functions, illustrated here:

Example #1 "counter"'s basic interface

<?php
$starting_counter_value = counter_get();
counter_bump(1);
$second_counter_value = counter_get();
counter_reset();
$final_counter_value = counter_get();
printf("%3d %3d %3d", $starting_counter_value, $second_counter_value, $final_counter_value);
?>

The above example will output:

  0   1   0

The basic interface also provides a number of INI settings.


Extended interface

The extended interface provides a small suite of functions that allow the user to define an arbitrary number of named counters with unique settings. The basic interface can be used in parallel with the extended interface.

Example #1 "counter"'s extended interface

<?php
function print_counter_info($counter)
{
    if (is_resource($counter)) {
        printf("Counter's name is '%s' and is%s persistent. Its current value is %d.\n",
            counter_get_meta($counter, COUNTER_META_NAME),
            counter_get_meta($counter, COUNTER_META_IS_PERSISTENT) ? '' : ' not',
            counter_get_value($counter));
    } else {
      print "Not a valid counter!\n";
    }
}

if (($counter_one = counter_get_named("one")) === NULL) {
    $counter_one = counter_create("one", 0, COUNTER_FLAG_PERSIST);
}
counter_bump_value($counter_one, 2);
$counter_two = counter_create("two", 5);
$counter_three = counter_get_named("three");
$counter_four = counter_create("four", 2, COUNTER_FLAG_PERSIST | COUNTER_FLAG_SAVE | COUNTER_FLAG_NO_OVERWRITE);
counter_bump_value($counter_four, 1);

print_counter_info($counter_one);
print_counter_info($counter_two);
print_counter_info($counter_three);
print_counter_info($counter_four);
?>

When run once, the above example outputs:

Counter's name is 'one' and is persistent. Its current value is 2.
Counter's name is 'two' and is not persistent. Its current value is 5.
Not a valid counter!
Counter's name is 'four' and is persistent. Its current value is 3.

If run a second time within the same instance of PHP, it outputs:

Counter's name is 'one' and is persistent. Its current value is 4.
Counter's name is 'two' and is not persistent. Its current value is 5.
Not a valid counter!
Counter's name is 'four' and is persistent. Its current value is 4.

If then run a third time in a different instance of PHP, it outputs:

Counter's name is 'one' and is persistent. Its current value is 2.
Counter's name is 'two' and is not persistent. Its current value is 5.
Not a valid counter!
Counter's name is 'four' and is persistent. Its current value is 5.


Objective interface

The objective interface provides an object-oriented way to access the extended interfaces. The following example shows how the above one would be implemented using the objective interface. The output of this example is exactly the same, except that instead of printing "Not a valid counter!", this will instead issue a PHP warning that the variable $counter_three is not an object. This example shows that it is possible to subclass the Counter class defined by the extension, as well as that the counter's value is maintained using an instance variable rather than method access.

Example #1 "counter"'s objective interface

<?php
class MyCounter extends Counter
{
    public function printCounterInfo() {
        printf("Counter's name is '%s' and is%s persistent. Its current value is %d.\n",
            $this->getMeta(COUNTER_META_NAME),
            $this->getMeta(COUNTER_META_IS_PERSISTENT) ? '' : ' not',
            $this->value);
    }
}

Counter::setCounterClass("MyCounter");
if (($counter_one = Counter::getNamed("one")) === NULL) {
    $counter_one = new Counter("one", 0, COUNTER_FLAG_PERSIST);
}
$counter_one->bumpValue(2); // we aren't allowed to "set" the value directly
$counter_two = new Counter("two", 5);
$counter_three = Counter::getNamed("three");
$counter_four = new Counter("four", 2, COUNTER_FLAG_PERSIST | COUNTER_FLAG_SAVE | COUNTER_FLAG_NO_OVERWRITE);
$counter_four->bumpValue(1);

$counter_one->printCounterInfo();
$counter_two->printCounterInfo();
$counter_three->printCounterInfo();
$counter_four->printCounterInfo();
?>


The Counter class

Introduction

Represents a single counter object.

Class synopsis

Counter {
__construct ( string $name [, int $initial_value [, int $flags ]] )
getValue ( void ) : int
bumpValue ( int $offset )
resetValue ( void ) : void
getMeta ( int $attribute ) : mixed
static getNamed ( string $name ) : Counter
static setCounterClass ( string $name ) : void
}

Table of Contents

  • Counter::__construct — Creates an instance of a Counter which maintains a single numeric value
  • Counter::getValue — Get the current value of a counter
  • Counter::bumpValue — Change the current value of a counter
  • Counter::resetValue — Reset the current value of a counter
  • Counter::getMeta — Return a piece of metainformation about a counter
  • Counter::getNamed — Retrieve an existing named counter
  • Counter::setCounterClass — Set the class returned by Counter::getNamed


Creates an instance of a Counter which maintains a single numeric value

  • « Counter
  • Counter::getValue »
  • PHP Manual
  • Counter
  • Creates an instance of a Counter which maintains a single numeric value

Counter::__construct

Counter::__construct — Creates an instance of a Counter which maintains a single numeric value

Description

Counter::__construct ( string $name [, int $initial_value [, int $flags ]] )

Creates an instance of a Counter which maintains a single numeric value.

Parameters

name
The new counter's name.
initial_value
The initial value of the counter. Defaults to zero (0).
flags
Flags for the new counter, chosen from the COUNTER_FLAG_* constants.

Return Values

Returns a Counter object on success.

Errors/Exceptions

Counter::__construct() throws an Exception if something goes wrong.


Get the current value of a counter

  • « Counter::__construct
  • Counter::bumpValue »
  • PHP Manual
  • Counter
  • Get the current value of a counter

Counter::getValue

Counter::getValue — Get the current value of a counter

Description

Counter::getValue ( void ) : int

Counter::getValue() returns the current value of a counter.

Return Values

Counter::getValue() returns an integer.

See Also

  • Counter::bumpValue() - Change the current value of a counter
  • Counter::resetValue() - Reset the current value of a counter


Change the current value of a counter

  • « Counter::getValue
  • Counter::resetValue »
  • PHP Manual
  • Counter
  • Change the current value of a counter

Counter::bumpValue

Counter::bumpValue — Change the current value of a counter

Description

Counter::bumpValue ( int $offset )

Counter::bumpValue() updates the current value of a counter.

Parameters

offset
The amount by which to change the counter's value. Can be negative.

See Also

  • Counter::getValue() - Get the current value of a counter
  • Counter::resetValue() - Reset the current value of a counter


Reset the current value of a counter

  • « Counter::bumpValue
  • Counter::getMeta »
  • PHP Manual
  • Counter
  • Reset the current value of a counter

Counter::resetValue

Counter::resetValue — Reset the current value of a counter

Description

Counter::resetValue ( void ) : void

Counter::resetValue() resets the current value of a counter to its original initial value.

See Also

  • Counter::getValue() - Get the current value of a counter
  • Counter::bumpValue() - Change the current value of a counter


Return a piece of metainformation about a counter

  • « Counter::resetValue
  • Counter::getNamed »
  • PHP Manual
  • Counter
  • Return a piece of metainformation about a counter

Counter::getMeta

Counter::getMeta — Return a piece of metainformation about a counter

Description

Counter::getMeta ( int $attribute ) : mixed

Counter::getMeta() returns metainformation about a counter.

Parameters

attribute
The metainformation to retrieve.

Return Values

Counter::getMeta() returns values of varying types based on which metainformation was requested.


Retrieve an existing named counter

  • « Counter::getMeta
  • Counter::setCounterClass »
  • PHP Manual
  • Counter
  • Retrieve an existing named counter

Counter::getNamed

Counter::getNamed — Retrieve an existing named counter

Description

static Counter::getNamed ( string $name ) : Counter

Counter::getNamed() returns an existing counter by name if that name exists, or NULL otherwise. This is a static function.

Parameters

name
The counter name to search for.

Return Values

Counter::getNamed() returns an existing counter by name if that name exists, or NULL otherwise.


Set the class returned by Counter::getNamed

  • « Counter::getNamed
  • Basic »
  • PHP Manual
  • Counter
  • Set the class returned by Counter::getNamed

Counter::setCounterClass

Counter::setCounterClass — Set the class returned by Counter::getNamed()

Description

static Counter::setCounterClass ( string $name ) : void

Counter::setCounterClass() changes the class of objects returned by Counter::getNamed(). The class being set must not have a public constructor and must be a subclass of Counter. If these conditions are not met, a fatal error is raised. This is a static function.

Parameters

name
The name of the class to use.


The basic interface

Table of Contents

  • counter_get — Get the current value of the basic counter
  • counter_bump — Update the current value of the basic counter
  • counter_reset — Reset the current value of the basic counter


Get the current value of the basic counter

  • « Basic
  • counter_bump »
  • PHP Manual
  • Basic
  • Get the current value of the basic counter

counter_get

counter_get — Get the current value of the basic counter

Description

counter_get ( void ) : int

counter_get() returns the current value of the basic interface's counter.

Return Values

counter_get() returns an integer.

See Also

  • counter_bump() - Update the current value of the basic counter
  • counter_reset() - Reset the current value of the basic counter


Update the current value of the basic counter

  • « counter_get
  • counter_reset »
  • PHP Manual
  • Basic
  • Update the current value of the basic counter

counter_bump

counter_bump — Update the current value of the basic counter

Description

counter_bump ( int $offset ) : void

counter_bump() updates the current value of the basic interface's counter.

Parameters

offset
The amount by which to change the counter's value. Can be negative.

See Also

  • counter_get() - Get the current value of the basic counter
  • counter_reset() - Reset the current value of the basic counter


Reset the current value of the basic counter

  • « counter_bump
  • Extended »
  • PHP Manual
  • Basic
  • Reset the current value of the basic counter

counter_reset

counter_reset — Reset the current value of the basic counter

Description

counter_reset ( void ) : void

counter_reset() resets the current value of the basic interface's counter to its original initial value.

See Also

  • counter_get() - Get the current value of the basic counter
  • counter_bump() - Update the current value of the basic counter


The extended interface

Table of Contents

  • counter_create — Creates a counter which maintains a single numeric value
  • counter_get_value — Get the current value of a counter resource
  • counter_bump_value — Change the current value of a counter resource
  • counter_reset_value — Reset the current value of a counter resource
  • counter_get_meta — Return a piece of metainformation about a counter resource
  • counter_get_named — Retrieve an existing named counter as a resource


Creates a counter which maintains a single numeric value

  • « Extended
  • counter_get_value »
  • PHP Manual
  • Extended
  • Creates a counter which maintains a single numeric value

counter_create

counter_create — Creates a counter which maintains a single numeric value

Description

counter_create ( string $name [, int $initial_value [, int $flags ]] ) : resource

Creates a counter which maintains a single numeric value.

Parameters

name
The new counter's name.
initial_value
The initial value of the counter. Defaults to zero (0).
flags
Flags for the new counter, chosen from the COUNTER_FLAG_* constants.

Return Values

Returns a counter resource.


Get the current value of a counter resource

  • « counter_create
  • counter_bump_value »
  • PHP Manual
  • Extended
  • Get the current value of a counter resource

counter_get_value

counter_get_value — Get the current value of a counter resource

Description

counter_get_value ( resource $counter ) : int

counter_get_value() returns the current value of a counter resource.

Parameters

counter
The counter resource to operate on.

Return Values

counter_get_value() returns an integer.

See Also

  • counter_bump_value() - Change the current value of a counter resource
  • counter_reset_value() - Reset the current value of a counter resource


Change the current value of a counter resource

  • « counter_get_value
  • counter_reset_value »
  • PHP Manual
  • Extended
  • Change the current value of a counter resource

counter_bump_value

counter_bump_value — Change the current value of a counter resource

Description

counter_bump_value ( resource $counter , int $offset ) : void

counter_bump_value() updates the current value of a counter resource.

Parameters

counter
The counter resource to operate on.
offset
The amount by which to change the counter's value. Can be negative.

See Also

  • counter_get_value() - Get the current value of a counter resource
  • counter_reset_value() - Reset the current value of a counter resource


Reset the current value of a counter resource

  • « counter_bump_value
  • counter_get_meta »
  • PHP Manual
  • Extended
  • Reset the current value of a counter resource

counter_reset_value

counter_reset_value — Reset the current value of a counter resource

Description

counter_reset_value ( resource $counter ) : void

counter_reset_value() resets the current value of a counter resource to its original initial value.

Parameters

counter
The counter resource to operate on.

See Also

  • counter_get_value() - Get the current value of a counter resource
  • counter_bump_value() - Change the current value of a counter resource


Return a piece of metainformation about a counter resource

  • « counter_reset_value
  • counter_get_named »
  • PHP Manual
  • Extended
  • Return a piece of metainformation about a counter resource

counter_get_meta

counter_get_meta — Return a piece of metainformation about a counter resource

Description

counter_get_meta ( resource $counter , int $attribute ) : mixed

counter_get_meta() returns metainformation about a counter resource.

Parameters

counter
The counter resource to operate on.
attribute
The metainformation to retrieve.

Return Values

counter_get_meta() returns values of varying types based on which metainformation was requested.


Retrieve an existing named counter as a resource

  • « counter_get_meta
  • The PHP 5 build system »
  • PHP Manual
  • Extended
  • Retrieve an existing named counter as a resource

counter_get_named

counter_get_named — Retrieve an existing named counter as a resource

Description

Counter::getNamed ( string $name ) : resource

counter_get_named() returns an existing counter by name if that name exists, or NULL otherwise.

Parameters

name
The counter name to search for.

Return Values

counter_get_name() returns an existing counter by name if that name exists, or NULL otherwise.


The PHP 5 build system

Table of Contents

  • Building PHP for extension development
  • The ext_skel script
  • Talking to the UNIX build system: config.m4
  • Talking to the Windows build system: config.w32

With all the functionality and flexibility available in PHP 5, it is no surprise that it consists of several thousand files and over one million lines of source code. Equally unsurprising is the necessity of a build system to manage so much data. This section describes how to set PHP up for extension development, the layout of an extension within the PHP source tree, and how to interface your extension with the build system.


Building PHP for extension development

In a typical PHP installation, the need for high performance almost always results in optimization at the cost of debugging facilities. This is a reasonable tradeoff for production use, but when developing an extension it falls short. What we need is a build of PHP which will give us some hints what has gone wrong when something does.

The Zend Engine provides a memory manager which is capable of tracking memory leaks in extensions and providing detailed debugging information. This tracking is disabled by default, as is thread-safety. To turn them on, pass the --enable-debug and --enable-maintainer-zts options to configure, along with whatever options you typically use. For instructions on building PHP from source, see the instructions at General Installation Considerations. A typical configure line might look like this:

$ ./configure --prefix=/where/to/install/php --enable-debug --enable-maintainer-zts --enable-cgi --enable-cli --with-mysql=/path/to/mysql


The ext_skel script

A PHP extension is composed of several files common to all extensions. As the details of many of those files are similar from extension to extension, it can be laborious to duplicate the content for each one. Fortunately, there is a script which can do all of the initial setup for you. It's called ext_skel, and it's been distributed with PHP since 4.0.

Running ext_skel with no parameters produces this output in PHP 5.2.2:

php-5.2.2/ext$ ./ext_skel
./ext_skel --extname=module [--proto=file] [--stubs=file] [--xml[=file]]
           [--skel=dir] [--full-xml] [--no-help]

  --extname=module   module is the name of your extension
  --proto=file       file contains prototypes of functions to create
  --stubs=file       generate only function stubs in file
  --xml              generate xml documentation to be added to phpdoc-cvs
  --skel=dir         path to the skeleton directory
  --full-xml         generate xml documentation for a self-contained extension
                     (not yet implemented)
  --no-help          don't try to be nice and create comments in the code
                     and helper functions to test if the module compiled
Generally, when developing a new extension the only parameters you will be interested in are --extname and --no-help. Unless you are already experienced with the structure of an extension, you will not want to use --no-help; specifying it causes ext_skel to leave out many helpful comments in the files it generates.

This leaves you with --extname, which tells ext_skel what the name of your extension is. This "name" is an all-lowercase identifier containing only letters and underscores which is unique among everything in the ext/ folder of your PHP distribution.

The --proto option is intended to allow the developer to specify a header file from which a set of PHP functions will be created, ostensibly for the purpose of developing an extension based on a library, but it often functions poorly with most modern header files. A test run on the zlib.h header resulted in a very large number of empty and nonsense prototypes in the ext_skel output files. The --xml and --full-xml options are entirely nonfunctional thus far. The --skel option can be used to specify a modified set of skeleton files to work from, a topic which is beyond the scope of this section.


Talking to the UNIX build system: config.m4

The config.m4 file for an extension tells the UNIX build system what configure options your extension supports, what external libraries and includes you require, and what source files are to be compiled as part of it. A reference to all the commonly used autoconf macros, both PHP-specific and those built into autoconf, is given in the Zend Engine 2 API reference section.

Tip

The version of autoconf you have installed makes a difference when developing an extension. For PHP 5.3 and earlier, you will have the best results with autoconf version 2.13 but versions up to and including 2.59 will work. For PHP 5.4 and later the oldest autoconf version you can use is 2.59 and you will have better results with later versions.

Example #1 An example config.m4 file

dnl $Id$
dnl config.m4 for extension example
PHP_ARG_WITH(example, for example support,
[  --with-example[=FILE]       Include example support. File is the optional path to example-config])
PHP_ARG_ENABLE(example-debug, whether to enable debugging support in example,
[  --enable-example-debug        example: Enable debugging support in example], no, no)
PHP_ARG_WITH(example-extra, for extra libraries for example,
[  --with-example-extra=DIR      example: Location of extra libraries for example], no, no)

dnl Check whether the extension is enabled at all
if test "$PHP_EXAMPLE" != "no"; then

  dnl Check for example-config. First try any path that was given to us, then look in $PATH
  AC_MSG_CHECKING([for example-config])
  EXAMPLE_CONFIG="example-config"
  if test "$PHP_EXAMPLE" != "yes"; then
    EXAMPLE_PATH=$PHP_EXAMPLE
  else
    EXAMPLE_PATH=`$php_shtool path $EXAMPLE_CONFIG`
  fi

  dnl If a usable example-config was found, use it
  if test -f "$EXAMPLE_PATH" && test -x "$EXAMPLE_PATH" && $EXAMPLE_PATH --version > /dev/null 2>&1; then
    AC_MSG_RESULT([$EXAMPLE_PATH])
    EXAMPLE_LIB_NAME=`$EXAMPLE_PATH --libname`
    EXAMPLE_INCDIRS=`$EXAMPLE_PATH --incdirs`
    EXAMPLE_LIBS=`$EXAMPLE_PATH --libs`

    dnl Check that the library works properly
    PHP_CHECK_LIBRARY($EXAMPLE_LIB_NAME, example_critical_function,
    [
      dnl Add the necessary include dirs
      PHP_EVAL_INCLINE($EXAMPLE_INCDIRS)
      dnl Add the necessary libraries and library dirs
      PHP_EVAL_LIBLINE($EXAMPLE_LIBS, EXAMPLE_SHARED_LIBADD)
    ],[
      dnl Bail out
      AC_MSG_ERROR([example library not found. Check config.log for more information.])
    ],[$EXAMPLE_LIBS]
    )
  else
    dnl No usable example-config, bail
    AC_MSG_RESULT([not found])
    AC_MSG_ERROR([Please check your example installation.])
  fi

  dnl Check whether to enable debugging
  if test "$PHP_EXAMPLE_DEBUG" != "no"; then
    dnl Yes, so set the C macro
    AC_DEFINE(USE_EXAMPLE_DEBUG,1,[Include debugging support in example])
  fi

  dnl Check for the extra support
  if test "$PHP_EXAMPLE_EXTRA" != "no"; then
    if test "$PHP_EXAMPLE_EXTRA" == "yes"; then
      AC_MSG_ERROR([You must specify a path when using --with-example-extra])
    fi

    PHP_CHECK_LIBRARY(example-extra, example_critical_extra_function,
    [
      dnl Add the neccessary paths
      PHP_ADD_INCLUDE($PHP_EXAMPLE_EXTRA/include)
      PHP_ADD_LIBRARY_WITH_PATH(example-extra, $PHP_EXAMPLE_EXTRA/lib, EXAMPLE_SHARED_LIBADD)
      AC_DEFINE(HAVE_EXAMPLEEXTRALIB,1,[Whether example-extra support is present and requested])
      EXAMPLE_SOURCES="$EXAMPLE_SOURCES example_extra.c"
    ],[
      AC_MSG_ERROR([example-extra lib not found. See config.log for more information.])
    ],[-L$PHP_EXAMPLE_EXTRA/lib]
    )
  fi

  dnl Finally, tell the build system about the extension and what files are needed
  PHP_NEW_EXTENSION(example, example.c $EXAMPLE_SOURCES, $ext_shared)
  PHP_SUBST(EXAMPLE_SHARED_LIBADD)
fi

A short introduction to autoconf syntax

config.m4 files are written using the GNU autoconf syntax. It can be described in a nutshell as shell scripting augmented by a powerful macro language. Comments are delimited by the string dnl, and strings are quoted using left and right brackets (e.g. [ and ]). Quoting of strings can be nested as many times as needed. A full reference to the syntax can be found in the autoconf manual at » http://www.gnu.org/software/autoconf/manual/.

PHP_ARG_*: Giving users the option

The very first thing seen in the example config.m4 above, aside from a couple of comments, are three lines using PHP_ARG_WITH() and PHP_ARG_ENABLE(). These provide configure with the options and help text seen when running ./configure --help. As the names suggest, the difference between the two is whether they create a --with-* option or an --enable-* option. Every extension should provide at least one or the other with the extension name, so that users can choose whether or not to build the extension into PHP. By convention, PHP_ARG_WITH() is used for an option which takes a parameter, such as the location of a library or program required by an extension, while PHP_ARG_ENABLE() is used for an option which represents a simple flag.

Example #2 Sample configure output

$ ./configure --help
...
  --with-example[=FILE]       Include example support. FILE is the optional path to example-config
  --enable-example-debug        example: Enable debugging support in example
  --with-example-extra=DIR      example: Location of extra libraries for example
...

$ ./configure --with-example=/some/library/path/example-config --disable-example-debug --with-example-extra=/another/library/path
...
checking for example support... yes
checking whether to enable debugging support in example... no
checking for extra libraries for example... /another/library/path
...

Note:

Regardless of the order in which options are specified on the command line when configure is called, the checks will be run in the order they are specified in config.m4.

Processing the user's choices

Now that config.m4 can provide the user with some choices of what to do, it's time to act upon those choices. In the example above, the obvious default for all three options, if any of them are unspecified, is "no". As a matter of convention, it is best to use this as the default for the option which enables the extension, as it will be overridden by phpize for extensions built separately, and should not clutter the extension space by default when being built into PHP. The code to process the three options is by far the most complicated.

Handling the --with-example[=FILE] option

The first check made of the --with-example[=FILE] option is whether it was set at all. As this option controls the inclusion of the entire extension, if it was unspecified, given in the negative form (--without-example ), or given the value "no", nothing else is done at all. In the example above, it is specified with the value /some/library/path/example-config, so the first test succeeds.

Next, the code calls AC_MSG_CHECKING(), an autoconf macro which outputs a standard "checking for something" line, and checks whether the user gave an explicit path to the fictional example-config. In this example, PHP_EXAMPLE got the value /some/library/path/example-config, which is now copied into the EXAMPLE_PATH variable. Had the user specified only --with-example , the code would have executed $php_shtool path $EXAMPLE_CONFIG, which would try to guess the location of example-config using the user's current PATH. Either way, the next step is to check whether the chosen EXAMPLE_PATH is a regular file, is executable, and can be run successfully. If so, AC_MSG_RESULT() is called, which completes the output line started by AC_MSG_CHECKING(). Otherwise, AC_MSG_ERROR() is called, which prints the given message and halts configure immediately.

The code now determines some site-specific configuration information by running example-config several times. The next call is to PHP_CHECK_LIBRARY(), a macro provided by the PHP buildsystem as a wrapper around autoconf's AC_CHECK_LIB(). PHP_CHECK_LIBRARY() attempts to compile, link, and run a program which calls the symbol specified by the second parameter in the library specified by the first, using the string given in the fifth as extra linker options. If the attempt succeeds, the script given in the third parameter is run. This script tells the PHP buildsystem to extract include paths, library paths, and library names from the raw option strings example-config provided. If the attempt fails, the script in the fourth parameter is run instead. In this case, AC_MSG_ERROR() is called to stop processing.

Handling the --enable-example-debug option

Processing the --enable-example-debug is much simpler. A simple check for its truth value is performed. If that check succeeds, AC_DEFINE() is called to make the C macro USE_EXAMPLE_DEBUG available to the source of the extension. The third parameter is a comment string for config.h; it is safe to leave this empty, and often is.

Handling the --with-example-extra=DIR option

For the sake of this example, the fictional "extra" functionality requested by the --with-example-extra=DIR option does not share the fictional example-config program, nor does it have any default paths to search. Therefore, the user is required to provide the installation prefix of the necessary library. This setup is somewhat unlikely in a real-world extension, but is considered illustrative.

The code begins in a now-familiar way by checking the truth value of PHP_EXAMPLE_EXTRA. If a negative form was provided, no further processing is done; the user did not request extra functionality. If a positive form was provided without a parameter, AC_MSG_ERROR() is called to halt processing. The next step is another invocation of PHP_CHECK_LIBRARY(). This time, since there is no set of predefined compiler options provided, PHP_ADD_INCLUDE() and PHP_ADD_LIBRARY_WITH_PATH() are used to construct the necessary include paths, library paths, and library flags for the extra functionality. AC_DEFINE() is also called to indicate to the code that the extra functionality was both requested and available, and a variable is set to tell later code that there are extra source files to build. If the check fails, the familiar AC_MSG_ERROR() is called. A different way to handle the failure would have been to call AC_MSG_WARNING() instead, e.g.:

AC_MSG_WARNING([example-extra lib not found. example will be built without extra functionality.])

In this case, configure would print a warning message rather than an error, and continue processing. Which way such failures are handled is a design decision left to the extension developer.

Telling the buildsystem what was decided

With all the necessary includes and libraries specified, with all the options processed and macros defined, one more thing remains to be done: The build system must be told to build the extension itself, and which files are to be used for that. To do this, the PHP_NEW_EXTENSION() macro is called. The first parameter is the name of the extension, which is the same as the name of the directory containing it. The second parameter is the list of all source files which are part of the extension. See PHP_ADD_BUILD_DIR() for information about adding source files in subdirectories to the build process. The third parameter should always be $ext_shared, a value which was determined by configure when PHP_ARG_WITH() was called for --with-example[=FILE] . The fourth parameter specifies a "SAPI class", and is only useful for extensions which require the CGI or CLI SAPIs specifically. It should be left empty in all other cases. The fifth parameter specifies a list of flags to be added to CFLAGS while building the extension; the sixth is a boolean value which, if "yes", will force the entire extension to be built using $CXX instead of $CC. All parameters after the third are optional. Finally, PHP_SUBST() is called to enable shared builds of the extension. See Extension FAQs for more information on disabling support for building an extension in shared mode.

The counter extension's config.m4 file

The counter extension previously documented has a much simpler config.m4 file than that described above, as it doesn't make use of many buildsystem features. This is a preferred method of operation for any extension that doesn't use an external or bundled library.

Example #3 counter's config.m4 file

dnl
$
Id$
dnl config.m4 for extension counter

PHP_ARG_ENABLE(counter, for counter support,
[  --enable-counter            Include counter support])

dnl Check whether the extension is enabled at all
if test "$PHP_COUNTER" != "no"; then
  dnl Finally, tell the build system about the extension and what files are needed
  PHP_NEW_EXTENSION(counter, counter.c counter_util.c, $ext_shared)
  PHP_SUBST(COUNTER_SHARED_LIBADD)
fi


Talking to the Windows build system: config.w32

An extension's config.w32 file is similar in usage to the config.m4 file, with two critical differences: first, it is used for Windows builds, and second, it is written in JavaScript. This section makes no attempt to cover JavaScript syntax. For the moment, this section is incomplete in lieu of a Win32 testbed, and an experimental-only port of the example config.m4 is the only example provided.

Example #1 An example config.w32 file

// $Id$
// vim:ft=javascript
ARG_WITH("example", "for example support", "no");
ARG_ENABLE("example-debug", "for debugging support in example", "no")
ARG_WITH("example-extra", "for extra functionality in example", "no")
if (PHP_EXAMPLE != "no") {
    if (CHECK_LIB("libexample.lib", "example", PHP_EXAMPLE) &&
        CHECK_HEADER_ADD_INCLUDE("example.h", "CFLAGS_EXAMPLE", PHP_EXAMPLE + "\\include")) {

        if (PHP_EXAMPLE_DEBUG != "no") {
            AC_DEFINE('USE_EXAMPLE_DEBUG', 1, 'Debug support in example');
        }

        if (PHP_EXAMPLE_EXTRA != "no" &&
            CHECK_LIB("libexample-extra.lib", "example", PHP_EXAMPLE) &&
            CHECK_HEADER_ADD_INCLUDE("example-extra.h", "CFLAGS_EXAMPLE", PHP_EXAMPLE + ";" + PHP_PHP_BUILD + "\\include") {
            AC_DEFINE('HAVE_EXAMPLEEXTRA', 1, 'Extra functionality in example');
            HAVE_EXTRA = 1;
        } else {
            WARNING( "extra example functionality not enabled, lib not found" );
        }

        EXTENSION("example", "example.c");
        if (HAVE_EXTRA == 1) {
            ADD_SOURCES("example-extra.c");
        }
    } else {
        WARNING( "example not enabled; libraries not found" );
    }
}

The counter extension's config.w32 file

The counter extension previously documented has a much simpler config.w32 file than that described above, as it doesn't make use of many buildsystem features.

Example #2 counter's config.w32 file

// $Id$
// vim:ft=javascript
ARG_ENABLE("counter", "for counter support", "no");
if (PHP_COUNTER != "no") {
    EXTENSION("counter", "counter.c");
    ADD_SOURCE("counter-util.c");
}


Extension structure

Table of Contents

  • Files which make up an extension
  • Basic constructs
  • The zend_module structure
  • Extension globals
  • Life cycle of an extension
  • Testing an extension

Many extension-writing guides focus on simple examples first and ignore the requirements of more complex implementations until later. Often such guides must repeat themselves over and over in order to describe these new features. This section describes extension structure from the perspective of a mature, practical implementation, in order to prepare users for needs and issues they will almost always encounter in the process of extension development.


Files which make up an extension

Whether created by hand, using ext_skel, or by an alternate extension generator, such as » CodeGen, all extensions will have at least four files:

config.m4

UNIX build system configuration (see Talking to the UNIX build system: config.m4)

config.w32

Windows buildsystem configuration (see Talking to the Windows build system: config.w32)

php_counter.h

When building an extension as static module into the PHP binary the build system expects a header file with php_ prepended to the extension name which includes a declaration for a pointer to the extension's module structure. This file usually contains additional macros, prototypes, and globals, just like any header.

counter.c

Main extension source file. By convention, the name of this file is the extension name, but this is not a requirement. This file contains the module structure declaration, INI entries, management functions, userspace functions, and other requirements of an extension.

The buildsystem files are discussed elsewhere; this section concentrates on the rest. These four files make up the bare minimum for an extension, which may also contain any number of headers, source files, unit tests, and other support files. The list of files in the counter extension might look like this:

Example #1 Files in the counter extension, in no particular order

ext/
 counter/
  .svnignore
  config.m4
  config.w32
  counter_util.h
  counter_util.c
  php_counter.h
  counter.c
  package.xml
  CREDITS
  tests/
   critical_function_001.phpt
   critical_function_002.phpt
   optional_function_001.phpt
   optional_function_002.phpt

Non-source files

The .svnignore file is used for extensions which are checked into the PHP Subversion repository (usually » PECL); the one generated by ext_skel contains:

.deps
*.lo
*.la

These lines tell Subversion to ignore interim files generated by the PHP buildsystem. This is only a convenience, and can be omitted completely without ill effect.

The CREDITS file lists the contributors and/or maintainers of the extension in plain text format. The main purpose of this file is generating the credits information for bundled extensions as used by phpcredits(). By convention the first line of the file should hold the name of the extension, the second a comma separated list of contributors. The contributors are usually ordered by the chronological order of their contributions. In a » PECL package, this information is already maintained in package.xml, for example. This is another file which can be omitted without ill effect.

The package.xml file is specific to » PECL-based extensions; it is a metainformation file which gives details about an extension's dependencies, authors, installation requirements, and other tidbits. In an extension not being hosted in » PECL, this file is extraneous.


Basic constructs

C is a very low-level language by modern definitions. This means that it has no built-in support for many features that PHP takes for granted, such as reflection, dynamic module loading, bounds checking, threadsafe data management and various useful data structures including linked lists and hash tables. At the same time, C is a common denominator of language support and functionality. Given enough work, none of these concepts are impossible; the Zend Engine uses them all.

A lot of effort has gone into making the Zend API both extensible and understandable, but C forces certain necessary declarations upon any extension that to an inexperienced eye seem redundant or plain unnecessary. All of those constructs, detailed in this section, are "write once and forget" in Zend Engine 2 and 3. Here are some excerpts from the pre-generated php_counter.h and counter.c files created by PHP 5.3's ext_skel, showing the pre-generated declarations:

Note: The astute reader will notice that there are several declarations in the real files that aren't shown here. Those declarations are specific to various Zend subsystems and are discussed elsewhere as appropriate.

extern zend_module_entry counter_module_entry;
#define phpext_counter_ptr &counter_module_entry

#ifdef PHP_WIN32
#    define PHP_COUNTER_API __declspec(dllexport)
#elif defined(__GNUC__) && __GNUC__ >= 4
#    define PHP_COUNTER_API __attribute__ ((visibility("default")))
#else
#    define PHP_COUNTER_API
#endif

#ifdef ZTS
#include "TSRM.h"
#endif

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "php_counter.h"

/* ... */

#ifdef COMPILE_DL_COUNTER
ZEND_GET_MODULE(counter)
#endif
  • The lines concerning counter_module_entry declare a global variable, and a macroed pointer to it, which contains the zend_module_entry for the extension. Despite the later discussion regarding the drawbacks of "true" globals, this usage is intentional; Zend takes precautions to avoid misusing this variable.
  • PHP_COUNTER_API is declared for use by non-PHP functions the module intends to export for the use of other modules. The counter extension doesn't declare any of these, and in the final version of the header file, this macro has been removed. The PHPAPI macro is declared identically elsewhere and is used by the standard extension to make the phpinfo() utility functions available to other extensions.
  • The include of TSRM.h is skipped if PHP, or the extension, isn't being compiled with thread-safety, since in that case TSRM isn't used.
  • A standard list of includes, especially the extension's own php_counter.h, is given. config.h gives the extension access to determinations made by configure. php.h is the gateway to the entire PHP and Zend APIs. php_ini.h adds the APIs for runtime configuration (INI) entries. Not all extensions will use this. Finally, ext/standard/info.h imports the aforementioned phpinfo() utility API.
  • COMPILE_DL_COUNTER will only be defined by configure if the counter extension is both enabled and wants to be built as a dynamically loadable module instead of being statically linked into PHP. ZEND_GET_MODULE defines a tiny function which Zend can use to get the extension's zend_module_entry at runtime.

    Note: The astute reader who has peeked into main/php_config.h after trying to build with the counter module enabled statically may have noticed that there is also a HAVE_COUNTER constant defined that the source code doesn't check for. There's a simple reason this check isn't done: It's unnecessary. If the extension isn't enabled, the source file will never be compiled.


The zend_module structure

The main source file of a PHP extension contains several new constructs for a C programmer. The most important of these, the one touched first when starting a new extension, is the zend_module structure. This structure contains a wealth of information that tells the Zend Engine about the extension's dependencies, version, callbacks, and other critical data. The structure has mutated considerably over time; this section will focus on the structure as it has appeared since PHP 5.2, and will identify the very few parts which have changed in PHP 5.3.

The zend_module declaration from counter.c looks like this before any code has been written. The example file was generated by ext_skel --extname=counter, with some obsolete constructs removed:

Example #1 zend_module declaration in the counter extension

/* {{{ counter_module_entry
 */
zend_module_entry counter_module_entry = {
    STANDARD_MODULE_HEADER,
    "counter",
    counter_functions,
    PHP_MINIT(counter),
    PHP_MSHUTDOWN(counter),
    PHP_RINIT(counter),        /* Replace with NULL if there's nothing to do at request start */
    PHP_RSHUTDOWN(counter),    /* Replace with NULL if there's nothing to do at request end */
    PHP_MINFO(counter),
    "0.1", /* Replace with version number for your extension */
    STANDARD_MODULE_PROPERTIES
};
/* }}} */

This may look a bit daunting at first glance, but most of it is very simple to understand. Here's the declaration of zend_module from zend_modules.h in PHP 5.3:

Example #2 zend_module definition in PHP 5.3

struct _zend_module_entry {
    unsigned short size;
    unsigned int zend_api;
    unsigned char zend_debug;
    unsigned char zts;
    const struct _zend_ini_entry *ini_entry;
    const struct _zend_module_dep *deps;
    const char *name;
    const struct _zend_function_entry *functions;
    int (*module_startup_func)(INIT_FUNC_ARGS);
    int (*module_shutdown_func)(SHUTDOWN_FUNC_ARGS);
    int (*request_startup_func)(INIT_FUNC_ARGS);
    int (*request_shutdown_func)(SHUTDOWN_FUNC_ARGS);
    void (*info_func)(ZEND_MODULE_INFO_FUNC_ARGS);
    const char *version;
    size_t globals_size;
#ifdef ZTS
    ts_rsrc_id* globals_id_ptr;
#else
    void* globals_ptr;
#endif
    void (*globals_ctor)(void *global TSRMLS_DC);
    void (*globals_dtor)(void *global TSRMLS_DC);
    int (*post_deactivate_func)(void);
    int module_started;
    unsigned char type;
    void *handle;
    int module_number;
};

Many of these fields will never be touched by an extension writer. There are a number of standard macros that set them to their proper values automatically. The macro STANDARD_MODULE_HEADER fills in everything up to the deps field. Alternatively, the STANDARD_MODULE_HEADER_EX will leave the deps field empty for the developer's use. The developer is always responsible for everything from name to version. After that, the STANDARD_MODULE_PROPERTIES macro will fill in the rest of the structure, or the STANDARD_MODULE_PROPERTIES_EX macro can be used to leave the extension globals and post-deactivation function fields unfilled. Most modern extensions will make use of module globals.

Note:

This table gives the values that each field would have if the developer were to fill in the structure entirely by hand, without recourse to any of the shortcut macros. This is not recommended. The "correct" values for many fields may change. Use the macros whenever possible.

Module structure field values
Field | Value | Description
size [1] [2] [3] | sizeof(zend_module_entry) | The size in bytes of the structure.
zend_api [1] [2] [3] | ZEND_MODULE_API_NO | The version of the Zend API this module was compiled against.
zend_debug [1] [2] [3] | ZEND_DEBUG | A flag indicating whether the module was compiled with debugging turned on.
zts [1] [2] [3] | USING_ZTS | A flag indicating whether the module was compiled with ZTS (TSRM) enabled (see Memory management).
ini_entry [1] [3] | NULL | This pointer is used internally by Zend to keep a non-local reference to any INI entries declared for the module.
deps [3] | NULL | A pointer to a list of dependencies for the module.
name | "mymodule" | The name of the module. This is the short name, such as "spl" or "standard".
functions | mymodule_functions | A pointer to the module's function table, which Zend uses to expose functions in the module to user space.
module_startup_func | PHP_MINIT(mymodule) | A callback function that Zend will call the first time a module is loaded into a particular instance of PHP.
module_shutdown_func | PHP_MSHUTDOWN(mymodule) | A callback function that Zend will call the when a module is unloaded from a particular instance of PHP, typically during final shutdown.
request_startup_func | PHP_RINIT(mymodule) | A callback function that Zend will call at the beginning of each request. This should be as short as possible or NULL as calling this has costs on every request.
request_shutdown_func | PHP_RSHUTDOWN(mymodule) | A callback function that Zend will call at the end of each request. This should be as short as possible or NULL as calling this has costs on every request.
info_func | PHP_MINFO(mymodule) | A callback function that Zend will call when the phpinfo() function is called.
version | NO_VERSION_YET | A string giving the version of the module, as specified by the module developer. It is recommended that the version number be either in the format expected by version_compare() (e.g. "1.0.5-dev"), or a CVS or SVN revision number (e.g. "$Rev: 322138 $").
globals_size [1] [4] [5] [6] | sizeof(zend_mymodule_globals) | The size of the data structure containing the module's globals, if any.
globals_id_ptr [1] [4] [5] [6] [7] | &mymodule_globals_id | Only one of these two fields will exist, depending upon whether the USING_ZTS constant is TRUE. The former is an index into TSRM's allocation table for the module's globals, and the latter is a pointer directly to the globals.
globals_ptr [1] [4] [5] [6] [8] | &mymodule_globals
globals_ctor [4] [5] [6] | PHP_GINIT(mymodule) | This funtion is called to initialize a module's globals before any module_startup_func.
globals_dtor [4] [5] [6] | PHP_GSHUTDOWN(mymodule) | This funtion is called to deallocate a module's globals after any module_shutdown_func.
post_deactivate_func [4] | ZEND_MODULE_POST_ZEND_DEACTIVATE_N(mymodule) | This function is called by Zend after request shutdown. It is rarely used.
module_started [1] [9] [4] | 0 | These fields are used for Zend's internal tracking information.
type [1] [9] [4] | 0
handle [1] [9] [4] | NULL
module_number [1] [9] [4] | 0
[1] This field is not intended for use by module developers. [2] This field is filled in by STANDARD_MODULE_HEADER_EX. [3] This field is filled in by STANDARD_MODULE_HEADER. [4] This field is filled in by STANDARD_MODULE_PROPERTIES. [5] This field is filled in by NO_MODULE_GLOBALS. [6] This field is filled in by PHP_MODULE_GLOBALS. [7] This field only exists when USING_ZTS is TRUE. [8] This field only exists when USING_ZTS is FALSE. [9] This field is filled in by STANDARD_MODULE_PROPERTIES_EX.

Filling in the structure in a practical situation

With all these fields to play with, it can be confusing to know which to use for what purpose. Here is the zend_module definition from the "counter" example extension after updating it to its final form.

Example #3 Counter extension module definition

/* {{{ counter_module_entry
 */
zend_module_entry counter_module_entry = {
    STANDARD_MODULE_HEADER,
    "counter",
    counter_functions,
    PHP_MINIT(counter),
    PHP_MSHUTDOWN(counter),
    PHP_RINIT(counter),
    PHP_RSHUTDOWN(counter),
    PHP_MINFO(counter),
    NO_VERSION_YET,
    PHP_MODULE_GLOBALS(counter),
    PHP_GINIT(counter),
    PHP_GSHUTDOWN(counter),
    NULL,
    STANDARD_MODULE_PROPERTIES_EX
};
/* }}} */
  • STANDARD_MODULE_HEADER is used since this module doesn't define any dependencies.
  • "counter" is the extension's name, and is used to define the various callback functions the module passes to Zend. "counter" uses module, globals, and request functions at startup and shutdown times, and provides information to phpinfo(), so all seven callbacks are defined.
  • It is assumed that there is a variable of type zend_function_entry * named counter_functions earlier in the file that contains the module definition, listing the functions the module exports to userspace.
  • NO_VERSION_YET is a particularly nice way of telling Zend the module doesn't have a version. It might have been more correct to place "1.0" here instead in a real module.
  • "counter" uses per-module globals, so PHP_MODULE_GLOBALS is used
  • This module has no post-deactivate function, so NULL is used.
  • Since this module does use globals, STANDARD_MODULE_PROPERTIES_EX is used to finish the structure.

What's changed between 5.2 and 5.3?

Nothing. The only differences in the zend_module structure between PHP 5.2 and PHP 5.3 are a few const keywords.


Extension globals

Introduction to globals in a PHP extension

In a language such as C, a "global" variable is a variable that can be accessed from any function without any extra declaration. These traditional globals have a few drawbacks:

  • Barring any special options passed to the compiler, a global variable can be accessed and changed by any piece of code anywhere in the program, whether or not that code should be doing so.
  • A typical global variable is not thread safe.
  • The names of global variables are as global as the variables themselves.

A PHP extension's globals are more properly called the "extension state", since most modules must remember what they're doing between function calls. The "counter" extension is a perfect example of this need: The basic interface calls for a counter with a persistent value. A programmer new to Zend and PHP might do something like this in counter.c to store that value:

Example #1 The wrong way to store the basic counter interface's value

/* ... */
static long basic_counter_value;

/* ... */

PHP_FUNCTION(counter_get)
{
    RETURN_LONG(basic_counter_value);
}

On the surface this appears a viable solution, and indeed in a simple test it would function correctly. However, there are a number of situations in which more than one copy of PHP is running in the same thread, which means more than one instance of the counter module. Suddenly these multiple threads are sharing the same counter value, which is clearly undesirable. Another problem shows itself when considering that another extension might someday happen to have a global with the same name, and due to the rules of C scoping, this has the potential to cause a compile failure, or worse, a runtime error. Something more elaborate is needed, and so exists Zend's support for thread-safe per-module globals.

Declaring module globals

Whether a module uses only a single global or dozens, they must be defined in a structure, and that structure must be declared. There are some macros that assist with doing so in a way that avoids name conflicts between modules: ZEND_BEGIN_MODULE_GLOBALS(), ZEND_END_MODULE_GLOBALS(), and ZEND_DECLARE_MODULE_GLOBALS(). All three take as a parameter the short name of the module, which in the case of the counter module is simply "counter". Here is the global structure declaration from php_counter.h:

Example #2 The counter module's globals

ZEND_BEGIN_MODULE_GLOBALS(counter)
    long        basic_counter_value;
ZEND_END_MODULE_GLOBALS(counter)

And this is the declaration from counter.c:

Example #3 The counter module's global structure declaration

ZEND_DECLARE_MODULE_GLOBALS(counter)

Accessing module globals

As discussed above, per-module globals are declared inside a C structure whose name is obscured by Zend macros. As a result, the ideal way to access members of this structure is by the use of further macros. Accordingly, most if not all extensions which have globals have a declaration like this somewhere in their header file:

Example #4 Accessor macros for per-module globals

#ifdef ZTS
#define COUNTER_G(v) TSRMG(counter_globals_id, zend_counter_globals *, v)
#else
#define COUNTER_G(v) (counter_globals.v)
#endif

Note: This could have been generalized into a macro of its own by the Zend API, but as of PHP 5.3 (and PHP 6 at the time of this writing), that hasn't happened. The global accessor construct is written into the header by ext_skel and thus is generally left alone by extension writers, unless they wish to change the name of the accessor macro.

Note: COUNTER_G was the name given to the macro by ext_skel, but it's not necessary for it to have that name and could just as easily be called FOO instead.

Any code in the counter extension that accesses a global must thus wrap it in the macro COUNTER_G.

Warning

Any function which accesses globals must either be declared by Zend macros, have TSRMLS_DC as its last argument, or call the macro TSRMLS_FETCH before accessing the globals. See the TSRM documentation for more information.

So with all of that in mind, here is our new version of the counter_get():

Example #5 The right way to store the basic counter interface's value

/* php_counter.h */
ZEND_BEGIN_MODULE_GLOBALS(counter)
    long        basic_counter_value;
ZEND_END_MODULE_GLOBALS(counter)

#ifdef ZTS
#define COUNTER_G(v) TSRMG(counter_globals_id, zend_counter_globals *, v)
#else
#define COUNTER_G(v) (counter_globals.v)
#endif

/* counter.c */
ZEND_DECLARE_MODULE_GLOBALS(counter)

/* ... */

PHP_FUNCTION(counter_get)
{
    RETURN_LONG(COUNTER_G(basic_counter_value));
}

This is a correct implementation. It is not, however, a complete one. The section Life cycle of an extension explains why.


Life cycle of an extension

A PHP extension goes through several phases during its lifetime. All of these phases are opportunities for the developer to perform various initialization, termination, or informational functions. The Zend API allows for hooks into five separate phases of an extension's existence, apart from calls by PHP functions.

Loading, unloading, and requests

As the Zend engine runs, it processes one or more "requests" from its client. In the traditional CGI implementation, this corresponds to one execution of a process. However, many other implementations, most notably the Apache module, can map many requests onto a single PHP process. A PHP extension may thus see many requests in its lifetime.

Overview

  • In the Zend API, a module is loaded into memory only once when the associated PHP process starts up. Each module receives a call to the "module initialization" function specified in its zend_module structure as it is loaded.
  • Whenever the associated PHP process starts to handle a request from its client - i.e. whenever the PHP interpreter is told to start working - each module receives a call to the "request initialization" function specified in its zend_module structure.
  • Whenever the associated PHP process is done handling a request, each module receives a call to the "request termination" function specified in its zend_module structure.
  • A given module is unloaded from memory when its associated PHP process is shut down in an orderly manner. The module receives a call to the "module termination" function specified in its zend_module structure at this time.

What to do, and when to do it

There are many tasks that might be performed at any of these four points. This table details where many common initialization and termination tasks belong.

What to do, and when to do it
Module initialization/termination | Request initialization/termination
Allocate/deallocate and initialize module global variables | Allocate/deallocate and initialize request-specific variables
Register/unregister class entries |
Register/unregister INI entries |
Register constants |

The phpinfo() callback

Aside from globals initialization and certain rarely-used callbacks, there is one more part of a module's lifecycle to examine: A call to phpinfo(). The output a user sees from this call, whether text or HTML or anything else, is generated by each individual extension that is loaded into the PHP interpreter at the time the call is made.

To provide for format-neutral output, the header "ext/standard/info.h" provides an array of functions to produce standardized display elements. Specifically, several functions which create the familiar tables exist:

php_info_print_table_start()
Open a table in phpinfo() output. Takes no parameters.
php_info_print_table_header()
Print a table header in phpinfo() output. Takes one parameter, the number of columns, plus the same number of char * parameters which are the texts for each column heading.
php_info_print_table_row()
Print a table row in phpinfo() output. Takes one parameter, the number of columns, plus the same number of char * parameters which are the texts for each column content.
php_info_print_table_end()
Close a table formerly opened by php_info_print_table_start(). Takes no parameters.

Using these four functions, it is possible to produce status information for nearly any combination of features in an extension. Here is the information callback from the counter extension:

Example #1 counter's PHP_MINFO function

/* {{{ PHP_MINFO(counter) */
PHP_MINFO_FUNCTION(counter)
{
    char        buf[10];

    php_info_print_table_start();
    php_info_print_table_row(2, "counter support", "enabled");
    snprintf(buf, sizeof(buf), "%ld", COUNTER_G(basic_counter_value));
    php_info_print_table_row(2, "Basic counter value", buf);
    php_info_print_table_end();
}
/* }}} */


Testing an extension

One of the accepted requirements of good programming is testing. PHP provides a test harness for unit regression tests, in the form of a script called run-tests.php.

Tests for a particular module are stored in the tests/ subdirectory of the module's folder, and have a .phpt extension. For details of the PHPT format, see » https://qa.php.net/.


PDO Driver How-To

Table of Contents

  • Prerequisites
  • Preparation and Housekeeping
  • Fleshing out your skeleton
  • Building
  • Testing
  • Packaging and distribution
  • pdo_dbh_t definition
  • pdo_stmt_t definition
  • Constants
  • Error handling

The purpose of this How-To is to provide a basic understanding of the steps required to write a database driver that interfaces with the PDO layer. Please note that this is still an evolving API and as such, subject to change. This document was prepared based on version 0.3 of PDO. The learning curve is steep; expect to spend a lot of time on the prerequisites.


Prerequisites

The following is list of prerequisites and assumptions needed for writing a PDO database driver:

  1. A working target database, examples, demos, etc. working as per vendor specifications;

  2. A working development environment:

    1. Linux: standard development tools, gcc, ld, make, autoconf, automake, etc., versions dependent on distribution;

    2. Other Unix: standard development tools supplied by vendor plus the GNU development tool set;

    3. Win32: Visual Studio compiler suite;

  3. A working PHP environment version 5.0.3 or higher with a working PEAR extension version 1.3.5 or higher;

  4. A working PDO environment (can be installed using 'sudo pecl install PDO'), including the headers which will be needed to access the PDO type definitions and function declarations;

  5. A good working knowledge of the C programming language;

  6. A good working knowledge of the way to write a PHP extension; George Schlossnagle's Advanced PHP Programming (published by Developer's Library, chapters 21 and 22) is recommended;

  7. Finally, a familiarity with the Zend API that forms the heart of PHP, in particular paying attention to the memory management aspects.


Preparation and Housekeeping

Source directory layout

The source directory for a typical PDO driver is laid out as follows, where SKEL represents a shortened form of the name of the database that the driver is going to connect to. Even though SKEL is presented here in uppercase (for clarity), the convention is to use lowercase characters.

pdo_SKEL/
  config.m4                  # unix build script
  config.w32                 # win32 build script
  CREDITS
  package.xml                # meta information about the package
  pdo_SKEL.c                 # standard PHP extension glue
  php_pdo_SKEL.h
  php_pdo_SKEL_int.h         # driver private header
  SKEL_dbh.c                 # contains the implementation of the PDO driver interface
  SKEL_stmt.c                # contains the implementation of the PDO statement interface
  tests/

The contents of these files are defined later in this document.

Creating a skeleton

The easiest way to get started is to use the ext_skel shell script found in the PHP build tree in the ext directory. This will build a skeleton directory containing a lot of the files listed above. It can be build by executing the following command from within the ext directory:

./ext_skel --extname=pdo_SKEL

This will generate a directory called pdo_SKEL containing the skeleton files that you can then modify. This directory should then be moved out of the php extension directory. PDO is a PECL extension and should not be included in the standard extension directory. As long as you have PHP and PDO installed, you should be able to build from any directory.

Standard Includes

Build Specific Headers

The header file config.h is generated by the configure process for the platform for the which the driver is being built. If this header is present, the HAVE_CONFIG_H compiler variable is set. This variable should be tested for and if set, the file config.h should be included in the compilation unit.

PHP Headers

The following standard public php headers should be included in each source module:

  1. php.h

  2. php_ini.h

  3. ext/standard/info.h

PDO Interface Headers

The following standard public PDO header files are also included in each source module:

pdo/php_pdo.h

This header file contains definitions of the initialization and shutdown functions in the main driver as well as definitions of global PDO variables.

pdo/php_pdo_driver.h

This header contains the types and API contracts that are used to write a PDO driver. It also contains method signature for calling back into the PDO layer and registering/unregistering your driver with PDO. Most importantly, this header file contains the type definitions for PDO database handles and statements. The two main structures a driver has to deal with, pdo_dbh_t and pdo_stmt_t, are described in more detail in Appendix A and B.

Driver Specific Headers

The typical PDO driver has two header files that are specific to the database implementation. This does not preclude the use of more depending on the implementation. The following two headers are, by convention, standard:

php_pdo_SKEL.h

This header file is virtually an exact duplicate in functionality and content of the previously defined pdo/php_pdo.h that has been specifically tailored for your database. If your driver requires the use of global variables they should be defined using the ZEND_BEGIN_MODULE_GLOBALS and ZEND_END_MODULE_GLOBALS macros. Macros are then used to access these variables. This macro is usually named PDO_SKEL_G(v) where v is global variable to be accessed. Consult the Zend programmer documentation for more information.

php_pdo_SKEL_int.h

This header file typically contains type definitions and function declarations specific to the driver implementation. It also should contain the db specific definitions of a pdo_SKEL_handle and pdo_SKEL_stmt structures. These are the names of the private data structures that are then referenced by the driver_data members of the handle and statement structures.

Optional Headers

Depending on the implementation details for a particular driver it may be necessary to include the following header:

#include <zend_exceptions.h>


Fleshing out your skeleton

Major Structures and Attributes

The major structures, pdo_dbh_t and pdo_stmt_t are defined and explained in Appendix A and B respectively. Database and Statement attributes are defined in Appendix C. Error handling is explained in Appendix D.

pdo_SKEL.c: PHP extension glue

function entries

static function_entry pdo_SKEL_functions[] = {
  { NULL, NULL, NULL }
};

This structure is used to register functions into the global php function namespace. PDO drivers should try to avoid doing this, so it is recommended that you leave this structure initialized to NULL, as shown in the synopsis above.

Module entry

/* {{{ pdo_SKEL_module_entry */
#if ZEND_EXTENSION_API_NO >= 220050617
static zend_module_dep pdo_SKEL_deps[] = {
    ZEND_MOD_REQUIRED("pdo")
    {NULL, NULL, NULL}
};
#endif
/* }}} */

zend_module_entry pdo_SKEL_module_entry = {
#if ZEND_EXTENSION_API_NO >= 220050617
    STANDARD_MODULE_HEADER_EX, NULL,
    pdo_SKEL_deps,
#else
    STANDARD_MODULE_HEADER,
#endif
    "pdo_SKEL",
    pdo_SKEL_functions,
    PHP_MINIT(pdo_SKEL),
    PHP_MSHUTDOWN(pdo_SKEL),
    NULL,
    NULL,
    PHP_MINFO(pdo_SKEL),
    PHP_PDO_<DB>_MODULE_VERSION,
    STANDARD_MODULE_PROPERTIES
};
/* }}} */

#ifdef COMPILE_DL_PDO_<DB>
ZEND_GET_MODULE(pdo_db)
#endif

A structure of type zend_module_entry called pdo_SKEL_module_entry must be declared and should include reference to the pdo_SKEL_functions table defined previously.

Standard PHP Module Extension Functions

PHP_MINIT_FUNCTION
/* {{{ PHP_MINIT_FUNCTION */
PHP_MINIT_FUNCTION(pdo_SKEL)
{
    return php_pdo_register_driver(&pdo_SKEL_driver);
}
/* }}} */

This standard PHP extension function should be used to register your driver with the PDO layer. This is done by calling the php_pdo_register_driver() function passing a pointer to a structure of type pdo_driver_t typically named pdo_SKEL_driver. A pdo_driver_t contains a header that is generated using the PDO_DRIVER_HEADER(SKEL) macro and pdo_SKEL_handle_factory() function pointer. The actual function is described during the discussion of the SKEL_dbh.c unit.

PHP_MSHUTDOWN_FUNCTION
/* {{{ PHP_MSHUTDOWN_FUNCTION */
PHP_MSHUTDOWN_FUNCTION(pdo_SKEL)
{
    php_pdo_unregister_driver(&pdo_SKEL_driver);
    return SUCCESS;
}
/* }}} */

This standard PHP extension function is used to unregister your driver from the PDO layer. This is done by calling the php_pdo_unregister_driver() function, passing the same pdo_SKEL_driver structure that was passed in the init function above.

PHP_MINFO_FUNCTION

This is again a standard PHP extension function. Its purpose is to display information regarding the module when the phpinfo() is called from a script. The convention is to display the version of the module and also what version of the db you are dependent on, along with any other configuration style information that might be relevant.

SKEL_driver.c: Driver implementation

This unit implements all of the database handling methods that support the PDO database handle object. It also contains the error fetching routines. All of these functions will typically need to access the global variable pool. Therefore, it is necessary to use the Zend macro TSRMLS_DC macro at the end of each of these statements. Consult the Zend programmer documentation for more information on this macro.

pdo_SKEL_error

static int pdo_SKEL_error(pdo_dbh_t *dbh,
  pdo_stmt_t *stmt, const char *file, int line TSRMLS_DC)

The purpose of this function is to be used as a generic error handling function within the driver. It is called by the driver when an error occurs within the driver. If an error occurs that is not related to SQLSTATE, the driver should set either dbh->error_code or stmt->error_code to an SQLSTATE that most closely matches the error or the generic SQLSTATE error HY000. The file pdo_sqlstate.c in the PDO source contains a table of commonly used SQLSTATE codes that the PDO code explicitly recognizes. This setting of the error code should be done prior to calling this function.; This function should set the global pdo_err variable to the error found in either the dbh or the stmt (if the variable stmt is not NULL).

dbh

Pointer to the database handle initialized by the handle factory

stmt

Pointer to the current statement or NULL. If NULL, the error is derived by error code found in the dbh.

file

The source file where the error occurred or NULL if not available.

line

The line number within the source file if available.

If the dbh member methods is NULL (which implies that the error is being raised from within the PDO constructor), this function should call the zend_throw_exception_ex() function otherwise it should return the error code. This function is usually called using a helper macro that customizes the calling sequence for either database handling errors or statement handling errors.

Example #1 Example macros for invoking pdo_SKEL_error

#define pdo_SKEL_drv_error(what) \
    pdo_SKEL_error(dbh, NULL, what, __FILE__, __LINE__ TSRMLS_CC)
#define pdo_SKEL_drv_error(what) \
    pdo_SKEL_error(dbh, NULL, what, __FILE__, __LINE__ TSRMLS_CC)

For more info on error handling, see Error handling.

Note:

Despite being documented here, the PDO driver interface does not specify that this function be present; it is merely a convenient way to handle errors, and it just happens to be equally convenient for the majority of database client library APIs to structure your driver implementation in this way.

pdo_SKEL_fetch_error_func

static int pdo_SKEL_fetch_error_func(pdo_dbh_t *dbh, pdo_stmt_t *stmt,
    zval *info TSRMLS_DC)

The purpose of this function is to obtain additional information about the last error that was triggered. This includes the driver specific error code and a human readable string. It may also include additional information if appropriate. This function is called as a result of the PHP script calling the PDO::errorInfo() method.

dbh

Pointer to the database handle initialized by the handle factory

stmt

Pointer to the most current statement or NULL. If NULL, the error translated is derived by error code found in the dbh.

info

A hash table containing error codes and messages.

The error_func should return two pieces of information as successive array elements. The first item is expected to be a numeric error code, the second item is a descriptive string. The best way to set this item is by using add_next_index. Note that the type of the first argument need not be long; use whichever type most closely matches the error code returned by the underlying database API.

/* now add the error information. */
/* These need to be added in a specific order */
add_next_index_long(info, error_code);   /* driver specific error code */
add_next_index_string(info, message, 0); /* readable error message */

This function should return 1 if information is available, 0 if the driver does not have additional info.

SKEL_handle_closer

static int SKEL_handle_closer(pdo_dbh_t *dbh TSRMLS_DC)

This function will be called by PDO to close an open database.

dbh

Pointer to the database handle initialized by the handle factory

This should do whatever database specific activity that needs to be accomplished to close the open database. PDO ignores the return value from this function.

SKEL_handle_preparer

static int SKEL_handle_preparer(pdo_dbh_t *dbh, const char *sql,
long sql_len, pdo_stmt_t *stmt, zval *driver_options TSRMLS_DC)

This function will be called by PDO in response to PDO::query() and PDO::prepare() calls from the PHP script. The purpose of the function is to prepare raw SQL for execution, storing whatever state is appropriate into the stmt that is passed in.

dbh

Pointer to the database handle initialized by the handle factory

sql

Pointer to a character string containing the SQL statement to be prepared.

sql_len

The length of the SQL statement.

Stmt

Pointer to the returned statement or NULL if an error occurs.

driver_options

Any driver specific/defined options.

This function is essentially the constructor for a stmt object. This function is responsible for processing statement options, and setting driver-specific option fields in the pdo_stmt_t structure.

PDO does not process any statement options on the driver's behalf before calling the preparer function. It is your responsibility to process them before you return, raising an error for any unknown options that are passed.

One very important responsibility of this function is the processing of SQL statement parameters. At the time of this call, PDO does not know if your driver supports binding parameters into prepared statements, nor does it know if it supports named or positional parameter naming conventions.

Your driver is responsible for setting stmt->supports_placeholders as appropriate for the underlying database. This may involve some run-time determination on the part of your driver, if this setting depends on the version of the database server to which it is connected. If your driver doesn't directly support both named and positional parameter conventions, you should use the pdo_parse_params() API to have PDO rewrite the query to take advantage of the support provided by your database.

Example #2 Using pdo_parse_params

int ret;
    char *nsql = NULL;
    int nsql_len = 0;

    /* before we prepare, we need to peek at the query; if it uses named parameters,
     * we want PDO to rewrite them for us */
    stmt->supports_placeholders = PDO_PLACEHOLDER_POSITIONAL;
    ret = pdo_parse_params(stmt, (char*)sql, sql_len, &nsql, &nsql_len TSRMLS_CC);

    if (ret == 1) {
        /* query was re-written */
        sql = nsql;
    } else if (ret == -1) {
        /* couldn't grok it */
        strcpy(dbh->error_code, stmt->error_code);
        return 0;
    }

    /* now proceed to prepare the query in "sql" */

Possible values for supports_placeholders are: PDO_PLACEHOLDER_NAMED, PDO_PLACEHOLDER_POSITIONAL and PDO_PLACEHOLDER_NONE. If the driver doesn't support prepare statements at all, then this function should simply allocate any state that it might need, and then return:

Example #3 Implementing preparer for drivers that don't support native prepared statements

static int SKEL_handle_preparer(pdo_dbh_t *dbh, const char *sql,
    long sql_len, pdo_stmt_t *stmt, zval *driver_options TSRMLS_DC)
{
    pdo_SKEL_db_handle *H = (pdo_SKEL_db_handle *)dbh->driver_data;
    pdo_SKEL_stmt *S = ecalloc(1, sizeof(pdo_SKEL_stmt));

    S->H = H;
    stmt->driver_data = S;
    stmt->methods = &SKEL_stmt_methods;
    stmt->supports_placeholders = PDO_PLACEHOLDER_NONE;

    return 1;
}

This function returns 1 on success or 0 on failure.

SKEL_handle_doer

static long SKEL_handle_doer(pdo_dbh_t *dbh, const char *sql, long sql_len TSRMLS_DC)

This function will be called by PDO to execute a raw SQL statement. No pdo_stmt_t is created.

dbh

Pointer to the database handle initialized by the handle factory

sql

Pointer to a character string containing the SQL statement to be prepared.

sql_len

The length of the SQL statement.

This function returns 1 on success or 0 on failure.

SKEL_handle_quoter

static int SKEL_handle_quoter(pdo_dbh_t *dbh, const char *unquoted,
  int unquoted_len, char **quoted, int quoted_len, enum pdo_param_type param_type TSRMLS_DC)

This function will be called by PDO to turn an unquoted string into a quoted string for use in a query.

dbh

Pointer to the database handle initialized by the handle factory

unquoted

Pointer to a character string containing the string to be quoted.

unquoted_len

The length of the string to be quoted.

quoted

Pointer to the address where a pointer to the newly quoted string will be returned.

quoted_len

The length of the new string.

param_type

A driver specific hint for driver that have alternate quoting styles

This function is called in response to a call to PDO::quote() or when the driver has set supports_placeholder to PDO_PLACEHOLDER_NONE. The purpose is to quote a parameter when building SQL statements.

If your driver does not support native prepared statements, implementation of this function is required.

This function returns 1 if the quoting process reformatted the string, and 0 if it was not necessary to change the string. The original string will be used unchanged with a 0 return.

SKEL_handle_begin

static int SKEL_handle_begin(pdo_dbh_t *dbh TSRMLS_DC)

This function will be called by PDO to begin a database transaction.

dbh

Pointer to the database handle initialized by the handle factory

This should do whatever database specific activity that needs to be accomplished to begin a transaction. This function returns 1 for success or 0 if an error occurred.

SKEL_handle_commit

static int SKEL_handle_commit(pdo_dbh_t *dbh TSRMLS_DC)

This function will be called by PDO to end a database transaction.

dbh

Pointer to the database handle initialized by the handle factory

This should do whatever database specific activity that needs to be accomplished to commit a transaction. This function returns 1 for success or 0 if an error occurred.

SKEL_handle_rollback

static int SKEL_handle_rollback( pdo_dbh_t *dbh TSRMLS_DC)

This function will be called by PDO to rollback a database transaction.

dbh

Pointer to the database handle initialized by the handle factory

This should do whatever database specific activity that needs to be accomplished to rollback a transaction. This function returns 1 for success or 0 if an error occurred.

SKEL_handle_get_attribute

static int SKEL_handle_get_attribute(pdo_dbh_t *dbh, long attr, zval *return_value TSRMLS_DC)

This function will be called by PDO to retrieve a database attribute.

dbh

Pointer to the database handle initialized by the handle factory

attr

long value of one of the PDO_ATTR_xxxx types. See Database and Statement Attributes Table for valid attributes.

return_value

The returned value for the attribute.

It is up to the driver to decide which attributes will be supported for a particular implementation. It is not necessary for a driver to supply this function. PDO driver handles the PDO_ATTR_PERSISTENT, PDO_ATTR_CASE, PDO_ATTR_ORACLE_NULLS, and PDO_ATTR_ERRMODE attributes directly.

This function returns 1 on success or 0 on failure.

SKEL_handle_set_attribute

static int SKEL_handle_set_attribute(pdo_dbh_t *dbh, long attr, zval *val TSRMLS_DC)

This function will be called by PDO to set a database attribute, usually in response to a script calling PDO::setAttribute().

dbh

Pointer to the database handle initialized by the handle factory

attr

long value of one of the PDO_ATTR_xxxx types. See Database and Statement Attributes Table for valid attributes.

val

The new value for the attribute.

It is up to the driver to decide which attributes will be supported for a particular implementation. It is not necessary for a driver to provide this function if it does not need to support additional attributes. The PDO driver handles the PDO_ATTR_CASE, PDO_ATTR_ORACLE_NULLS, and PDO_ATTR_ERRMODE attributes directly.

This function returns 1 on success or 0 on failure.

SKEL_handle_last_id

static char * SKEL_handle_last_id(pdo_dbh_t *dbh, const char *name, unsigned int len TSRMLS_DC)

This function will be called by PDO to retrieve the ID of the last inserted row.

dbh

Pointer to the database handle initialized by the handle factory

name

string representing a table or sequence name.

len

the length of the name parameter.

This function returns a character string containing the id of the last inserted row on success or NULL on failure. This is an optional function.

SKEL_check_liveness

static int SKEL_check_liveness(pdo_dbh_t *dbh TSRMLS_DC)

This function will be called by PDO to test whether or not a persistent connection to a database is alive and ready for use.

dbh

Pointer to the database handle initialized by the handle factory

This function returns 1 if the database connection is alive and ready for use, otherwise it should return 0 to indicate failure or lack of support.

Note:

This is an optional function.

SKEL_get_driver_methods

static function_entry *SKEL_get_driver_methods(pdo_dbh_t *dbh, int kind TSRMLS_DC)

This function will be called by PDO in response to a call to any method that is not a part of either the PDO or PDOStatement classes. It's purpose is to allow the driver to provide additional driver specific methods to those classes.

dbh

Pointer to the database handle initialized by the handle factory

kind

One of the following:

PDO_DBH_DRIVER_METHOD_KIND_DBH

Set when the method call was attempted on an instance of the PDO class. The driver should return a pointer a function_entry table for any methods it wants to add to that class, or NULL if there are none.

PDO_DBH_DRIVER_METHOD_KIND_STMT

Set when the method call was attempted on an instance of the PDOStatement class. The driver should return a pointer to a function_entry table for any methods it wants to add to that class, or NULL if there are none.

This function returns a pointer to the function_entry table requested, or NULL there are no driver specific methods.

SKEL_handle_factory

static int SKEL_handle_factory(pdo_dbh_t *dbh, zval *driver_options TSRMLS_DC)

This function will be called by PDO to create a database handle. For most databases this involves establishing a connection to the database. In some cases, a persistent connection may be requested, in other cases connection pooling may be requested. All of these are database/driver dependent.

dbh

Pointer to the database handle initialized by the handle factory

driver_options

An array of driver options, keyed by integer option number. See Database and Statement Attributes Table for a list of possible attributes.

This function should fill in the passed database handle structure with its driver specific information on success and return 1, otherwise it should return 0 to indicate failure.

PDO processes the AUTOCOMMIT and PERSISTENT driver options before calling the handle_factory. It is the handle factory's responsibility to process other options.

Driver method table

A static structure of type pdo_dbh_methods named SKEL_methods must be declared and initialized to the function pointers for each defined function. If a function is not supported or not implemented the value for that function pointer should be set to NULL.

pdo_SKEL_driver

A structure of type pdo_driver_t named pdo_SKEL_driver should be declared. The PDO_DRIVER_HEADER(SKEL) macro should be used to declare the header and the function pointer to the handle factory function should set.

SKEL_statement.c: Statement implementation

This unit implements all of the database statement handling methods that support the PDO statement object.

SKEL_stmt_dtor

static int SKEL_stmt_dtor(pdo_stmt_t *stmt TSRMLS_DC)

This function will be called by PDO to destroy a previously constructed statement object.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

This should do whatever is necessary to free up any driver specific storage allocated for the statement. The return value from this function is ignored.

SKEL_stmt_execute

static int SKEL_stmt_execute(pdo_stmt_t *stmt TSRMLS_DC)

This function will be called by PDO to execute the prepared SQL statement in the passed statement object.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

This function returns 1 for success or 0 in the event of failure.

SKEL_stmt_fetch

static int SKEL_stmt_fetch(pdo_stmt_t *stmt, enum pdo_fetch_orientation ori,
   long offset TSRMLS_DC)

This function will be called by PDO to fetch a row from a previously executed statement object.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

ori

One of PDO_FETCH_ORI_xxx which will determine which row will be fetched.

offset

If ori is set to PDO_FETCH_ORI_ABS or PDO_FETCH_ORI_REL, offset represents the row desired or the row relative to the current position, respectively. Otherwise, this value is ignored.

The results of this fetch are driver dependent and the data is usually stored in the driver_data member of the pdo_stmt_t object. The ori and offset parameters are only meaningful if the statement represents a scrollable cursor. This function returns 1 for success or 0 in the event of failure.

SKEL_stmt_param_hook

static int SKEL_stmt_param_hook(pdo_stmt_t *stmt,
  struct pdo_bound_param_data *param, enum pdo_param_event event_type TSRMLS_DC)

This function will be called by PDO for handling of both bound parameters and bound columns.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

param

The structure describing either a statement parameter or a bound column.

event_type

The type of event to occur for this parameter, one of the following:

PDO_PARAM_EVT_ALLOC

Called when PDO allocates the binding. Occurs as part of PDOStatement::bindParam(), PDOStatement::bindValue() or as part of an implicit bind when calling PDOStatement::execute(). This is your opportunity to take some action at this point; drivers that implement native prepared statements will typically want to query the parameter information, reconcile the type with that requested by the script, allocate an appropriately sized buffer and then bind the parameter to that buffer. You should not rely on the type or value of the zval at param->parameter at this point in time.

PDO_PARAM_EVT_FREE

Called once per parameter as part of cleanup. You should release any resources associated with that parameter now.

PDO_PARAM_EXEC_PRE

Called once for each parameter immediately before calling SKEL_stmt_execute; take this opportunity to make any final adjustments ready for execution. In particular, you should note that variables bound via PDOStatement::bindParam() are only legal to touch now, and not any sooner.

PDO_PARAM_EXEC_POST

Called once for each parameter immediately after calling SKEL_stmt_execute; take this opportunity to make any post-execution actions that might be required by your driver.

PDO_PARAM_FETCH_PRE

Called once for each parameter immediately prior to calling SKEL_stmt_fetch.

PDO_PARAM_FETCH_POST

Called once for each parameter immediately after calling SKEL_stmt_fetch.

This hook will be called for each bound parameter and bound column in the statement. For ALLOC and FREE events, a single call will be made for each parameter or column. The param structure contains a driver_data field that the driver can use to store implementation specific information about each of the parameters.

For all other events, PDO may call you multiple times as the script issues PDOStatement::execute() and PDOStatement::fetch() calls.

If this is a bound parameter, the is_param flag in the param structure is set, otherwise the param structure refers to a bound column.

This function returns 1 for success or 0 in the event of failure.

SKEL_stmt_describe_col

static int SKEL_stmt_describe_col(pdo_stmt_t *stmt, int colno TSRMLS_DC)

This function will be called by PDO to query information about a particular column.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

colno

The column number to be queried.

The driver should populate the pdo_stmt_t member columns(colno) with the appropriate information. This function returns 1 for success or 0 in the event of failure.

SKEL_stmt_get_col_data

static int SKEL_stmt_get_col_data(pdo_stmt_t *stmt, int colno,
  char **ptr, unsigned long *len, int *caller_frees TSRMLS_DC)

This function will be called by PDO to retrieve data from the specified column.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

colno

The column number to be queried.

ptr

Pointer to the retrieved data.

len

The length of the data pointed to by ptr.

caller_frees

If set, ptr should point to emalloc'd memory and the main PDO driver will free it as soon as it is done with it. Otherwise, it will be the responsibility of the driver to free any allocated memory as a result of this call.

The driver should return the resultant data and length of that data in the ptr and len variables respectively. It should be noted that the main PDO driver expects the driver to manage the lifetime of the data. This function returns 1 for success or 0 in the event of failure.

SKEL_stmt_set_attr

static int SKEL_stmt_set_attr(pdo_stmt_t *stmt, long attr, zval *val TSRMLS_DC)

This function will be called by PDO to allow the setting of driver specific attributes for a statement object.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

attr

long value of one of the PDO_ATTR_xxxx types. See Database and Statement Attributes Table for valid attributes.

val

The new value for the attribute.

This function is driver dependent and allows the driver the capability to set database specific attributes for a statement. This function returns 1 for success or 0 in the event of failure. This is an optional function. If the driver does not support additional settable attributes, it can be NULLed in the method table. The PDO driver does not handle any settable attributes on the database driver's behalf.

SKEL_stmt_get_attr

static int SKEL_stmt_get_attr(pdo_stmt_t *stmt, long attr, zval
   *return_value TSRMLS_DC)

This function will be called by PDO to allow the retrieval of driver specific attributes for a statement object.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

attr

long value of one of the PDO_ATTR_xxxx types. See Database and Statement Attributes Table for valid attributes.

return_value

The returned value for the attribute.

This function is driver dependent and allows the driver the capability to retrieve a previously set database specific attribute for a statement. This function returns 1 for success or 0 in the event of failure. This is an optional function. If the driver does not support additional gettable attributes, it can be NULLed in the method table. The PDO driver does not handle any settable attributes on the database driver's behalf.

SKEL_stmt_get_col_meta

static int SKEL_stmt_get_col_meta(pdo_stmt_t *stmt, int colno,
   zval *return_value TSRMLS_DC)
Warning

This function is not well defined and is subject to change.

This function will be called by PDO to retrieve meta data from the specified column.

stmt

Pointer to the statement structure initialized by SKEL_handle_preparer.

colno

The column number for which data is to be retrieved.

return_value

Holds the returned meta data.

The driver author should consult the documentation for this function that can be found in the php_pdo_driver.h header as this will be the most current. This function returns 1 for success or 0 in the event of failure. The database driver does not need to provide this function.

Statement handling method table

A static structure of type pdo_stmt_methods named SKEL_stmt_methods should be declared and initialized to the function pointers for each defined function. If a function is not supported or not implemented the value for that function pointer should be set to NULL.


Building

The build process is designed to work with PEAR (see » https://pear.php.net/ for more information about PEAR). There are two files that are used to assist in configuring your package for building. The first is config.m4 which is the autoconf configuration file for all platforms except Win32. The second is config.w32 which is a build configuration file for use on Win32. Skeleton files for these are built for you when you first set up your project. You then need to customize them to fit the needs of your project. Once you've customized your config files, you can build your driver using the following sequence of commands:

Before first build:

$ sudo pecl install PDO

For each build:

$ cd pdo_SKEL
$ phpize
$ ./configure
$ make
$ sudo make install

The process can then be repeated as necessary during the development process.


Testing

PDO has a set of "core" tests that all drivers should pass before being released. They're designed to run from the PHP source distribution, so running the tests for your driver requires moving things around a bit. The suggested procedure is to obtain the latest PHP 5.1 snapshot and perform the following step:

$ cp -r pdo_SKEL /path/to/php-5.1/ext

This will allow the test harness to run your tests. The next thing you need to do is create a test that will redirect into the PDO common core tests. The convention is to name this file common.phpt; it should be placed in the tests subdirectory that was created by ext_skel when you created your extension skeleton. The content of this file should look something like the following:

--TEST--
SKEL
--SKIPIF--
<?php # vim:ft=php
if (!extension_loaded('pdo_SKEL')) print 'skip'; ?>
--REDIRECTTEST--
if (false !== getenv('PDO_SKEL_TEST_DSN')) {
# user set them from their shell
   $config['ENV']['PDOTEST_DSN'] = getenv('PDO_SKEL_TEST_DSN');
   $config['ENV']['PDOTEST_USER'] = getenv('PDO_SKEL_TEST_USER');
   $config['ENV']['PDOTEST_PASS'] = getenv('PDO_SKEL_TEST_PASS');
   if (false !== getenv('PDO_SKEL_TEST_ATTR')) {
      $config['ENV']['PDOTEST_ATTR'] = getenv('PDO_SKEL_TEST_ATTR');
   }
   return $config;
}
return array(
   'ENV' => array(
           'PDOTEST_DSN' => 'SKEL:dsn',
           'PDOTEST_USER' => 'username',
           'PDOTEST_PASS' => 'password'
       ),
   'TESTS' => 'ext/pdo/tests'
   );

This will cause the common core tests to be run, passing the values of PDOTEST_DSN, PDOTEST_USER and PDOTEST_PASS to the PDO constructor as the dsn, username and password parameters. It will first check the environment, so that appropriate values can be passed in when the test harness is run, rather than hard-coding the database credentials into the test file.

The test harness can be invoked as follows:

$ cd /path/to/php-5.1
$ make TESTS=ext/pdo_SKEL/tests PDO_SKEL_TEST_DSN="skel:dsn" \
 PDO_SKEL_TEST_USER=user PDO_SKEL_TEST_PASS=pass test


Packaging and distribution

Creating a package

PDO drivers are released via PECL; all the usual rules for PECL extensions apply. Packaging is accomplished by creating a valid package.xml file and then running:

$ pecl package

This will create a tarball named PDO_SKEL-X.Y.Z.tgz.

Before releasing the package, you should test that it builds correctly; if you've made a mistake in your config.m4 or package.xml files, the package may not function correctly. You can test the build, without installing anything, using the following invocation:

$ pecl build package.xml

Once this is proven to work, you can test installation:

$ pecl package
$ sudo pecl install PDO_SKEL-X.Y.X.tgz

Full details about package.xml can be found in the PEAR Programmer's documentation (» https://pear.php.net/manual/).

Releasing the package

A PDO driver is released via the PHP Extension Community Library (PECL). Information about PECL can be found at » https://pecl.php.net/.


pdo_dbh_t definition

All fields should be treated as read-only by the driver, unless explicitly stated otherwise.

pdo_dbh_t

/* represents a connection to a database */
struct _pdo_dbh_t {
    /* driver specific methods */
    struct pdo_dbh_methods *methods;
*
/* driver specific data */
    void *driver_data;
**
/* credentials */
    char *username, *password;
***
/* if true, then data stored and pointed at by this handle must all be
     * persistently allocated */
    unsigned is_persistent:1;
****
/* if true, driver should act as though a COMMIT were executed between
     * each executed statement; otherwise, COMMIT must be carried out manually
     * */
    unsigned auto_commit:1;
*****
/* if true, the driver requires that memory be allocated explicitly for
     * the columns that are returned */
    unsigned alloc_own_columns:1;
******
/* if true, commit or rollBack is allowed to be called */
    unsigned in_txn:1;

    /* max length a single character can become after correct quoting */
    unsigned max_escaped_char_length:3;
*******
/* data source string used to open this handle */
    const char *data_source;
********
unsigned long data_source_len;

    /* the global error code. */
    pdo_error_type error_code;
*********
enum pdo_case_conversion native_case
**********
, desired_case;
};
*

The driver must set this during SKEL_handle_factory().

**

This item is for use by the driver; the intended usage is to store a pointer (during SKEL_handle_factory()) to whatever instance data is required to maintain a connection to the database.

***

The username and password that were passed into the PDO constructor. The driver should use these values when it initiates a connection to the database.

****

If this is set to 1, then any data that is referenced by the dbh, including whatever structure your driver allocates, MUST be allocated persistently. This is easy to achieve; rather than using the usual emalloc() simply use pemalloc() and pass the value of this flag as the last parameter. Failure to use the appropriate kind of memory can lead to serious memory faults, resulting (in the best case) a hard crash, and in the worst case, an exploitable memory problem.

If, for whatever reason, your driver is not suitable to run persistently, you MUST check this flag in your SKEL_handle_factory() and raise an appropriate error.

*****

You should check this value in your SKEL_handle_doer() and SKEL_stmt_execute() functions; if it evaluates to true, you must attempt to commit the query now. Most database implementations offer an auto-commit mode that handles this automatically.

******

If your database client library API operates by fetching data into a caller-supplied buffer, you should set this flag to 1 during your SKEL_handle_factory(). When set, PDO will call your SKEL_stmt_describer() earlier than it would otherwise. This early call allows you to determine those buffer sizes and issue appropriate calls to the database client library.

If your database client library API simply returns pointers to its own internal buffers for you to copy after each fetch call, you should leave this value set to 0.

*******

If your driver doesn't support native prepared statements (supports_placeholders is set to PDO_PLACEHOLDER_NONE), you must set this value to the maximum length that can be taken up by a single character when it is quoted by your SKEL_handle_quoter() function. This value is used to calculate the amount of buffer space required when PDO executes the statement.

********

This holds the value of the DSN that was passed into the PDO constructor. If your driver implementation needed to modify the DSN for whatever reason, it should update this member during SKEL_handle_factory(). Modifying this member should be avoided. If you do change it, you must ensure that data_source_len is also correct.

*********

Whenever an error occurs during a call to one of your driver methods, you should set this member to the SQLSTATE code that best describes the error and return an error. In this HOW-TO, the suggested practice is to call SKEL_handle_error() when an error is detected, and have it set the error code.

**********

Your driver should set this during SKEL_handle_factory(); the value should reflect how the database returns the names of the columns in result sets. If the name matches the case that was used in the query, set it to PDO_CASE_NATURAL (this is actually the default). If the column names are always returned in upper case, set it to PDO_CASE_UPPER. If the column names are always returned in lower case, set it to PDO_CASE_LOWER. The value you set is used to determine if PDO should perform case folding when the user sets the PDO_ATTR_CASE attribute.


pdo_stmt_t definition

All fields should be treated as read-only unless explicitly stated otherwise.

pdo_stmt_t

/* represents a prepared statement */
struct _pdo_stmt_t {
    /* driver specifics */
    struct pdo_stmt_methods *methods;
*
void *driver_data;
**
/* if true, we've already successfully executed this statement at least
     * once */
    unsigned executed:1;
***
/* if true, the statement supports placeholders and can implement
     * bindParam() for its prepared statements, if false, PDO should
     * emulate prepare and bind on its behalf */
    unsigned supports_placeholders:2;
****
/* the number of columns in the result set; not valid until after
     * the statement has been executed at least once.  In some cases, might
     * not be valid until fetch (at the driver level) has been called at least once.
     * */
    int column_count;
*****
struct pdo_column_data *columns;
******
/* points at the dbh that this statement was prepared on */
    pdo_dbh_t *dbh;

    /* keep track of bound input parameters.  Some drivers support
     * input/output parameters, but you can't rely on that working */
    HashTable *bound_params;
    /* When rewriting from named to positional, this maps positions to names */
    HashTable *bound_param_map;
    /* keep track of PHP variables bound to named (or positional) columns
     * in the result set */
    HashTable *bound_columns;

    /* not always meaningful */
    long row_count;

    /* used to hold the statement's current query */
    char *query_string;
    int query_stringlen;

    /* the copy of the query with expanded binds ONLY for emulated-prepare drivers */
    char *active_query_string;
    int active_query_stringlen;

    /* the cursor specific error code. */
    pdo_error_type error_code;

    /* used by the query parser for driver specific
     * parameter naming (see pgsql driver for example) */
    const char *named_rewrite_template;
};
* | The driver must set this during SKEL_handle_preparer().
** | This item is for use by the driver; the intended usage is to store a pointer (during SKEL_handle_factory()) to whatever instance data is required to maintain a connection to the database.
*** | This is set by PDO after the statement has been executed for the first time. Your driver can inspect this value to determine if it can skip one-time actions as an optimization.
**** | Discussed in more detail in SKEL_handle_preparer.
***** | Your driver is responsible for setting this field to the number of columns available in a result set. This is usually set during SKEL_stmt_execute() but with some database implementations, the column count may not be available until SKEL_stmt_fetch() has been called at least once. Drivers that implement SKEL_stmt_next_rowset() should update the column count when a new rowset is available.
****** | PDO will allocate this field based on the value that you set for the column count. You are responsible for populating each column during SKEL_stmt_describe(). You must set the precision, maxlen, name, namelen and param_type members for each column. The name is expected to be allocated using emalloc(); PDO will call efree() at the appropriate time.


Constants

Database and Statement Attributes Table

Attribute

Valid value(s)

PDO_ATTR_AUTOCOMMIT

BOOL

TRUE if autocommit is set, FALSE otherwise.

dbh->auto_commit contains value. Processed by PDO directly.

PDO_ATTR_PREFETCH

LONG

Value of the prefetch size in drivers that support it.

PDO_ATTR_TIMEOUT

LONG

How long to wait for a db operation before timing out.

PDO_ATTR_ERRMODE

LONG

Processed and handled by PDO

PDO_ATTR_SERVER_VERSION

STRING

The human-readable string representing the Server/Version this driver is currently connected to.

PDO_ATTR_CLIENT_VERSION

STRING

The human-readable string representing the Client/Version this driver supports.

PDO_ATTR_SERVER_INFO

STRING

The human-readable description of the Server.

PDO_ATTR_CONNECTION_STATUS

LONG

Values not yet defined

PDO_ATTR_CASE

LONG

Processed and handled by PDO.

PDO_ATTR_CURSOR_NAME

STRING

String representing the name for a database cursor for use in where current in <name> SQL statements.

PDO_ATTR_CURSOR

LONG

PDO_CURSOR_FWDONLY

Forward only cursor

PDO_CURSOR_SCROLL

Scrollable cursor

The values for the attributes above are all defined in terms of the Zend API. The Zend API contains macros that can be used to convert a *zval to a value. These macros are defined in the Zend header file, zend_API.h in the Zend directory of your PHP build directory. Some of these attributes can be used with the statement attribute handlers such as the PDO_ATTR_CURSOR and PDO_ATTR_CURSOR_NAME. See the statement attribute handling functions for more information.


Error handling

Error handling is implemented using a hand-shaking protocol between PDO and the database driver code. The database driver code signals PDO that an error has occurred via a failure (0) return from any of the interface functions. If a zero is returned, set the field error_code in the control block appropriate to the context (either the pdo_dbh_t or pdo_stmt_t block). In practice, it is probably a good idea to set the field in both blocks to the same value to ensure the correct one is getting used.

The error_mode field is a six-byte field containing a 5 character ASCIIZ SQLSTATE identifier code. This code drives the error message process. The SQLSTATE code is used to look up an error message in the internal PDO error message table (see pdo_sqlstate.c for a list of error codes and their messages). If the code is not known to PDO, a default Unknown Message value will be used.

In addition to the SQLSTATE code and error message, PDO will call the driver-specific fetch_err() routine to obtain supplemental data for the particular error condition. This routine is passed an array into which the driver may place additional information. This array has slot positions assigned to particular types of supplemental info:

  1. A native error code. This will frequently be an error code obtained from the database API.

  2. A descriptive string. This string can contain any additional information related to the failure. Database drivers typically include information such as an error message, code location of the failure, and any additional descriptive information the driver developer feels worthy of inclusion. It is generally a good idea to include all diagnostic information obtainable from the database interface at the time of the failure. For driver-detected errors (such as memory allocation problems), the driver developer can define whatever error information that seems appropriate.


  • « Error handling
  • Zend Engine 2 API reference »
  • PHP Manual
  • PHP at the Core: A Hacker's Guide
  • Extension FAQs

Extension FAQs


  • « Extension FAQs
  • Zend Engine 2 Opcodes »
  • PHP Manual
  • PHP at the Core: A Hacker's Guide
  • Zend Engine 2 API reference

Zend Engine 2 API reference


Zend Engine 2 Opcodes

Table of Contents

  • Opcode Descriptions and Examples

When parsing PHP files, Zend Engine 2 generates a series of operation codes, commonly known as "opcodes", representing the function of the code. This part of the manual details those opcodes and their behaviour.

Opcodes may be dumped for a given PHP file using the vld extension (see » https://pecl.php.net/package/vld).

Opcode List
Number | Name | Has sample code?
0 | NOP | yes
1 | ADD | yes
2 | SUB | yes
3 | MUL | yes
4 | DIV | yes
5 | MOD | yes
6 | SL | yes
7 | SR | yes
8 | CONCAT | yes
9 | BW_OR | yes
10 | BW_AND | yes
11 | BW_XOR | yes
12 | BW_NOT | yes
13 | BOOL_NOT | yes
14 | BOOL_XOR | yes
15 | IS_IDENTICAL | yes
16 | IS_NOT_IDENTICAL | yes
17 | IS_EQUAL | yes
18 | IS_NOT_EQUAL | yes
19 | IS_SMALLER | yes
20 | IS_SMALLER_OR_EQUAL | yes
21 | CAST | yes
22 | QM_ASSIGN | yes
23 | ASSIGN_ADD | yes
24 | ASSIGN_SUB | yes
25 | ASSIGN_MUL | yes
26 | ASSIGN_DIV | yes
27 | ASSIGN_MOD | yes
28 | ASSIGN_SL | yes
29 | ASSIGN_SR | yes
30 | ASSIGN_CONCAT | yes
31 | ASSIGN_BW_OR | yes
32 | ASSIGN_BW_AND | yes
33 | ASSIGN_BW_XOR | yes
34 | PRE_INC | yes
35 | PRE_DEC | yes
36 | POST_INC | yes
37 | POST_DEC | yes
38 | ASSIGN | yes
39 | ASSIGN_REF | yes
40 | ECHO | yes
41 | PRINT | yes
42 | JMP | yes
43 | JMPZ | yes
44 | JMPNZ | yes
45 | JMPZNZ | yes
46 | JMPZ_EX | yes
47 | JMPNZ_EX | yes
48 | CASE | yes
49 | SWITCH_FREE | yes
50 | BRK | yes
51 | CONT | yes
52 | BOOL | yes
53 | INIT_STRING | yes
54 | ADD_CHAR | yes
55 | ADD_STRING | yes
56 | ADD_VAR | yes
57 | BEGIN_SILENCE | yes
58 | END_SILENCE | yes
59 | INIT_FCALL_BY_NAME | yes
60 | DO_FCALL | yes
61 | DO_FCALL_BY_NAME | yes
62 | RETURN | yes
63 | RECV | yes
64 | RECV_INIT | yes
65 | SEND_VAL | yes
66 | SEND_VAR | yes
67 | SEND_REF | yes
68 | NEW | yes
69 | INIT_NS_FCALL_BY_NAME | no
70 | FREE | yes
71 | INIT_ARRAY | yes
72 | ADD_ARRAY_ELEMENT | yes
73 | INCLUDE_OR_EVAL | yes
74 | UNSET_VAR | yes
75 | UNSET_DIM | yes
76 | UNSET_OBJ | yes
77 | FE_RESET | yes
78 | FE_FETCH | yes
79 | EXIT | yes
80 | FETCH_R | yes
81 | FETCH_DIM_R | yes
82 | FETCH_OBJ_R | yes
83 | FETCH_W | yes
84 | FETCH_DIM_W | yes
85 | FETCH_OBJ_W | yes
86 | FETCH_RW | yes
87 | FETCH_DIM_RW | yes
88 | FETCH_OBJ_RW | yes
89 | FETCH_IS | yes
90 | FETCH_DIM_IS | no
91 | FETCH_OBJ_IS | no
92 | FETCH_FUNC_ARG | yes
93 | FETCH_DIM_FUNC_ARG | yes
94 | FETCH_OBJ_FUNC_ARG | yes
95 | FETCH_UNSET | no
96 | FETCH_DIM_UNSET | no
97 | FETCH_OBJ_UNSET | no
98 | FETCH_DIM_TMP_VAR | yes
99 | FETCH_CONSTANT | yes
100 | GOTO | no
101 | EXT_STMT | yes
102 | EXT_FCALL_BEGIN | no
103 | EXT_FCALL_END | no
104 | EXT_NOP | no
105 | TICKS | yes
106 | SEND_VAR_NO_REF | no
107 | CATCH | yes
108 | THROW | yes
109 | FETCH_CLASS | yes
110 | CLONE | yes
111 | RETURN_BY_REF | no
112 | INIT_METHOD_CALL | yes
113 | INIT_STATIC_METHOD_CALL | yes
114 | ISSET_ISEMPTY_VAR | yes
115 | ISSET_ISEMPTY_DIM_OBJ | yes
116 | ZEND_SEND_VAL_EX | no
117 | ZEND_SEND_VAR | no
118 | ZEND_INIT_USER_CALL | no
119 | ZEND_SEND_ARRAY | no
120 | ZEND_SEND_USER | no
121 | ZEND_STRLEN | no
122 | ZEND_DEFINED | no
123 | ZEND_TYPE_CHECK | no
124 | ZEND_VERIFY_RETURN_TYPE | no
125 | ZEND_FE_RESET_RW | no
126 | ZEND_FE_FETCH_RW | no
127 | ZEND_FE_FREE | no
128 | ZEND_INIT_DYNAMIC_CALL | no
129 | ZEND_DO_ICALL | no
130 | ZEND_DO_UCALL | no
131 | ZEND_DO_FCALL_BY_NAME | no
132 | PRE_INC_OBJ | yes
133 | PRE_DEC_OBJ | yes
134 | POST_INC_OBJ | yes
135 | POST_DEC_OBJ | yes
136 | ASSIGN_OBJ | yes
137 | ZEND_OP_DATA | no
138 | INSTANCEOF | yes
139 | DECLARE_CLASS | yes
140 | DECLARE_INHERITED_CLASS | yes
141 | DECLARE_FUNCTION | yes
142 | RAISE_ABSTRACT_ERROR | yes
143 | DECLARE_CONST | no
144 | ADD_INTERFACE | no
145 | DECLARE_INHERITED_CLASS_DELAYED | no
146 | VERIFY_ABSTRACT_CLASS | no
147 | ASSIGN_DIM | yes
148 | ISSET_ISEMPTY_PROP_OBJ | yes
149 | HANDLE_EXCEPTION | yes
150 | USER_OPCODE | no
151 | ZEND_ASSERT_CHECK | no
152 | ZEND_JMP_SET | no
153 | ZEND_DECLARE_LAMBDA_FUNCTION | no
154 | ZEND_ADD_TRAIT | no
155 | ZEND_BIND_TRAITS | no
156 | ZEND_SEPARATE | no
157 | ZEND_FETCH_CLASS_NAME | no
158 | ZEND_CALL_TRAMPOLINE | no
159 | ZEND_DISCARD_EXCEPTION | no
160 | ZEND_YIELD | no
161 | ZEND_GENERATOR_RETURN | no
162 | ZEND_FAST_CALL | no
163 | ZEND_FAST_RET | no
164 | ZEND_RECV_VARIADIC | no
165 | ZEND_SEND_UNPACK | no
166 | ZEND_POW | no
167 | ZEND_ASSIGN_POW | no
168 | ZEND_BIND_GLOBAL | no
169 | ZEND_COALESCE | no
170 | ZEND_SPACESHIP | no
171 | ZEND_DECLARE_ANON_CLASS | no
172 | ZEND_DECLARE_ANON_INHERITED_CLASS | no
173 | ZEND_FETCH_STATIC_PROP_R | no
174 | ZEND_FETCH_STATIC_PROP_W | no
175 | ZEND_FETCH_STATIC_PROP_RW | no
176 | ZEND_FETCH_STATIC_PROP_IS | no
177 | ZEND_FETCH_STATIC_PROP_FUNC_ARG | no
178 | ZEND_FETCH_STATIC_PROP_UNSET | no
179 | ZEND_UNSET_STATIC_PROP | no
180 | ZEND_ISSET_ISEMPTY_STATIC_PROP | no
181 | ZEND_FETCH_CLASS_CONSTANT | no
182 | ZEND_BIND_LEXICAL | no
183 | ZEND_BIND_STATIC | no
184 | ZEND_FETCH_THIS | no
185 | ZEND_SEND_FUNC_ARG | no
186 | ZEND_ISSET_ISEMPTY_THIS | no
187 | ZEND_SWITCH_LONG | no
188 | ZEND_SWITCH_STRING | no
189 | ZEND_IN_ARRAY | no
190 | ZEND_COUNT | no
191 | ZEND_GET_CLASS | no
192 | ZEND_GET_CALLED_CLASS | no
193 | ZEND_GET_TYPE | no
194 | ZEND_FUNC_NUM_ARGS | no
195 | ZEND_FUNC_GET_ARGS | no
196 | ZEND_UNSET_CV | no
197 | ZEND_ISSET_ISEMPTY_CV | no

Pseudo-opcodes that are used only temporarily during compilation.

Pseudo-opcodes List
Number | Name | Has sample code?
253 | ZEND_GOTO | no
254 | ZEND_BRK | no
255 | ZEND_CONT | no


Opcode Descriptions and Examples

Table of Contents

  • ADD
  • ADD_ARRAY_ELEMENT
  • ADD_CHAR
  • ADD_INTERFACE
  • ADD_STRING
  • ADD_VAR
  • ASSIGN
  • ASSIGN_ADD
  • ASSIGN_BW_AND
  • ASSIGN_BW_OR
  • ASSIGN_BW_XOR
  • ASSIGN_CONCAT
  • ASSIGN_DIM
  • ASSIGN_DIV
  • ASSIGN_MOD
  • ASSIGN_MUL
  • ASSIGN_OBJ
  • ASSIGN_REF
  • ASSIGN_SL
  • ASSIGN_SR
  • ASSIGN_SUB
  • BEGIN_SILENCE
  • BOOL
  • BOOL_NOT
  • BOOL_XOR
  • BRK
  • BW_AND
  • BW_NOT
  • BW_OR
  • BW_XOR
  • CASE
  • CAST
  • CATCH
  • CLONE
  • CONCAT
  • CONT
  • DECLARE_CLASS
  • DECLARE_CONST
  • DECLARE_FUNCTION
  • DECLARE_INHERITED_CLASS
  • DECLARE_INHERITED_CLASS_DELAYED
  • DIV
  • DO_FCALL
  • DO_FCALL_BY_NAME
  • ECHO
  • END_SILENCE
  • EXIT
  • EXT_FCALL_BEGIN
  • EXT_FCALL_END
  • EXT_NOP
  • EXT_STMT
  • FE_FETCH
  • FE_RESET
  • FETCH_CLASS
  • FETCH_CONSTANT
  • FETCH_DIM_FUNC_ARG
  • FETCH_DIM_IS
  • FETCH_DIM_R
  • FETCH_DIM_RW
  • FETCH_DIM_TMP_VAR
  • FETCH_DIM_UNSET
  • FETCH_DIM_W
  • FETCH_FUNC_ARG
  • FETCH_IS
  • FETCH_OBJ_FUNC_ARG
  • FETCH_OBJ_IS
  • FETCH_OBJ_R
  • FETCH_OBJ_RW
  • FETCH_OBJ_UNSET
  • FETCH_OBJ_W
  • FETCH_R
  • FETCH_RW
  • FETCH_UNSET
  • FETCH_W
  • FREE
  • GOTO
  • HANDLE_EXCEPTION
  • INCLUDE_OR_EVAL
  • INIT_ARRAY
  • INIT_FCALL_BY_NAME
  • INIT_METHOD_CALL
  • INIT_NS_FCALL_BY_NAME
  • INIT_STATIC_METHOD_CALL
  • INIT_STRING
  • INSTANCEOF
  • IS_EQUAL
  • IS_IDENTICAL
  • IS_NOT_EQUAL
  • IS_NOT_IDENTICAL
  • IS_SMALLER
  • IS_SMALLER_OR_EQUAL
  • ISSET_ISEMPTY_DIM_OBJ
  • ISSET_ISEMPTY_PROP_OBJ
  • ISSET_ISEMPTY_VAR
  • JMP
  • JMPNZ
  • JMPNZ_EX
  • JMPZ
  • JMPZ_EX
  • JMPZNZ
  • MOD
  • MUL
  • NEW
  • NOP
  • POST_DEC
  • POST_DEC_OBJ
  • POST_INC
  • POST_INC_OBJ
  • PRE_DEC
  • PRE_DEC_OBJ
  • PRE_INC
  • PRE_INC_OBJ
  • PRINT
  • QM_ASSIGN
  • RAISE_ABSTRACT_ERROR
  • RECV
  • RECV_INIT
  • RETURN
  • RETURN_BY_REF
  • SEND_REF
  • SEND_VAL
  • SEND_VAR
  • SEND_VAR_NO_REF
  • SL
  • SR
  • SUB
  • SWITCH_FREE
  • THROW
  • TICKS
  • UNSET_DIM
  • UNSET_OBJ
  • UNSET_VAR
  • USER_OPCODE
  • VERIFY_ABSTRACT_CLASS
  • ZEND_DECLARE_LAMBDA_FUNCTION
  • ZEND_JMP_SET


ADD

PHP code

<?php
/*
 * Adds "value1" to "value2" and stores the result into "result".
 * opcode number: 1
 */
echo 1 + 2;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | ADD |  |  | ~0 | 1,2
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1


ADD_ARRAY_ELEMENT

PHP code

<?php
/*
 * Add elem-value as an element to array-value
 * opcode number: 72
 */
$a = array(1,2,3);
print_r($a);
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | INIT_ARRAY |  |  | ~0 | 1
 | 1 | ADD_ARRAY_ELEMENT |  |  | ~0 | 2
 | 2 | ADD_ARRAY_ELEMENT |  |  | ~0 | 3
 | 3 | ASSIGN |  |  |  | !0,~0
7 | 4 | SEND_VAR |  |  |  | !0
 | 5 | DO_FCALL |  | 1 |  | 'print_r'
8 | 6 | RETURN |  |  |  | 1


ADD_CHAR

PHP code

<?php
/*
 * add regular characters in encapsed string
 * opcode number: 54
 */
echo "$a ";
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ADD_VAR |  |  |  | !0
 | 1 | ADD_CHAR |  |  |  | 32
 | 2 | ECHO |  |  |  |
 | 3 | RETURN |  |  |  | 1


ADD_INTERFACE

PHP code

<?php
/*
 * adds an implemented interface to a class declaration
 * opcode number: 144
 */
interface iA {
}

class A implements iA {
}
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
 | 1 | DECLARE_CLASS |  |  |  | 'a'
 | 2 | ADD_INTERFACE |  |  |  | 'iA'
 | 3 | VERIFY_ABSTRACT_CLASS |  |  |  |
 | 3 | RETURN |  |  |  | 1


ADD_STRING

PHP code

<?php
/*
 * add string value2 to string value2 and store in result
 * opcode number: 55
 */
echo "hello$a world";
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ADD_STRING |  |  | ~0 | 'hello'
 | 1 | ADD_VAR |  |  | ~0 | ~0,!0
 | 2 | ADD_STRING |  |  | ~0 | ~0,'+world'
 | 3 | ECHO |  |  |  | ~0
7 | 4 | RETURN |  |  |  | 1


ADD_VAR

PHP code

<?php
/*
 * add contents of variable in value2 to string value1 and store in result
 * opcode number: 56
 */
echo "hello$a world";
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ADD_STRING |  |  | ~0 | 'hello'
 | 1 | ADD_VAR |  |  | ~0 | ~0,!0
 | 2 | ADD_STRING |  |  | ~0 | ~0,'+world'
 | 3 | ECHO |  |  |  | ~0
7 | 4 | RETURN |  |  |  | 1


ASSIGN

PHP code

<?php
/*
 * assigns value1 to result
 * opcode number: 38
 */
$a=1;
$a='a';
$a=new A();
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,1
7 | 1 | ASSIGN |  |  |  | !0,'a'
8 | 2 | ZEND_FETCH_CLASS |  |  | :2 | 'A'
 | 3 | NEW |  |  | $3 | :2
 | 4 | DO_FCALL_BY_NAME |  | 0 |  |
 | 5 | ASSIGN |  |  |  | !0,$3
9 | 6 | RETURN |  |  |  | 1


ASSIGN_ADD

PHP code

<?php
/*
 * Add value1 to value2 and store in variable indicated by value1
 * opcode number: 23
 */
$a+=3;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_ADD |  |  |  | !0,3
7 | 1 | RETURN |  |  |  | 1


ASSIGN_BW_AND

PHP code

<?php
/*
 * Performs binary AND on result and value1 and stores in variable indicated by result.
 * opcode number: 32
 */
$a &= 64;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_BW_AND |  |  |  | !0,64
7 | 1 | RETURN |  |  |  | 1


ASSIGN_BW_OR

PHP code

<?php
/*
 * Performs binary OR on result and value1 and stores in variable indicated by result.
 * opcode number: 31
 */
$a |= 64;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_BW_OR |  |  |  | !0,64
7 | 1 | RETURN |  |  |  | 1


ASSIGN_BW_XOR

PHP code

<?php
/*
 * Performs binary XOR on result and value1and stores in variable indicated by result.
 * opcode number: 33
 */
$a ^= 64;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_BW_XOR |  |  |  | !0,64
7 | 1 | RETURN |  |  |  | 1


ASSIGN_CONCAT

PHP code

<?php
/*
 * Concats string values result and value1 and store in variable indicated by result
 * opcode number: 30
 */
$a .= 'z';
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_CONCAT |  |  |  | !0,'z'
7 | 1 | RETURN |  |  |  | 1


ASSIGN_DIM

PHP code

<?php
/*
 *
 * opcode number: 147
 */
$b = 1;
$a[1][2] = $b;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$b, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,1
7 | 1 | FETCH_DIM_W |  |  | $1 | !1,1
 | 2 | ZEND_ASSIGN_DIM |  |  |  | $1,2
 | 3 | ZEND_OP_DATA |  |  |  | !0,$3
8 | 4 | RETURN |  |  |  | 1


ASSIGN_DIV

PHP code

<?php
/*
 * Divide result by value1and store in variable indicated by result.
 * opcode number: 26
 */
$a/=3;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_DIV |  |  |  | !0,3
7 | 1 | RETURN |  |  |  | 1


ASSIGN_MOD

PHP code

<?php
/*
 * Perform result mod value1 and store in variable indicated by result
 * opcode number: 27
 */
$a %= 3;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_MOD |  |  |  | !0,3
7 | 1 | RETURN |  |  |  | 1


ASSIGN_MUL

PHP code

<?php
/*
 * Multiply result by value1 and store in variable indicated by result
 * opcode number: 25
 */
$a*=3;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_MUL |  |  |  | !0,3
7 | 1 | RETURN |  |  |  | 1


ASSIGN_OBJ

PHP code

<?php
/*
 *
 * opcode number: 136
 */
$obj->a = $otherobj;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj, !1=$otherobj

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_ASSIGN_OBJ |  |  |  | !0,'a'
 | 1 | ZEND_OP_DATA |  |  |  | !1
7 | 2 | RETURN |  |  |  | 1


ASSIGN_REF

PHP code

<?php
/*
 * indicates that variable indicated by value1 is to be treated in the global scope for the remainder of the current scope.
 * opcode number: 39
 */
global $a;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | FETCH_W | globallock |  | $0 | 'a'
 | 1 | ASSIGN_REF |  |  |  | !0,$0
7 | 2 | RETURN |  |  |  | 1


ASSIGN_SL

PHP code

<?php
/*
 * Shift result by value1 bits to left and store in variable indicated by result
 * opcode number: 28
 */
$a <<= 3;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_SL |  |  |  | !0,3
7 | 1 | RETURN |  |  |  | 1


ASSIGN_SR

PHP code

<?php
/*
 * Shift result by value1 bits to right and store in variable indicated by result
 * opcode number: 29
 */
$a >>= 3;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_SR |  |  |  | !0,3
7 | 1 | RETURN |  |  |  | 1


ASSIGN_SUB

PHP code

<?php
/*
 * Subtract value1 from value2 and store in variable indicated by value1
 * opcode number: 24
 */
$a-=3;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN_SUB |  |  |  | !0,3
7 | 1 | RETURN |  |  |  | 1


BEGIN_SILENCE

PHP code

<?php
/*
 * prepare to perform function call without displaying error messages
 * opcode number: 57
 */
/* Intentional file error */
$my_file = @file ('non_existent_file') or
   die ("error:'$php_errormsg'");
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$my_file, !1=$php_errormsg

line | # | op | fetch | ext | return | operands
7 | 0 | BEGIN_SILENCE |  |  | ~0 |
 | 1 | SEND_VAL |  |  |  | 'non_existent_file'
 | 2 | DO_FCALL |  | 1 |  | 'file'
 | 3 | END_SILENCE |  |  |  | ~0
 | 4 | ASSIGN |  |  | $2 | !0,$1
 | 5 | JMPNZ_EX |  |  | ~3 | $2,->11
8 | 6 | ADD_STRING |  |  | ~4 | 'error%3A%27'
 | 7 | ADD_VAR |  |  | ~4 | ~4,!1
 | 8 | ADD_CHAR |  |  | ~4 | ~4,39
 | 9 | EXIT |  |  |  | ~4
 | 10 | BOOL |  |  | ~3 | true
 | 11 | FREE |  |  |  | ~3
9 | 12 | RETURN |  |  |  | 1


BOOL

PHP code

<?php
/*
 * convert value1 to boolean and store in result??????????
 * opcode number: 52
 */
if (1 || 2 || 1) echo "foo";
//$a = true;
//if($a) echo "foo";
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | JMPNZ_EX |  |  | ~0 | 1,->2
 | 1 | BOOL |  |  | ~0 | 2
 | 2 | JMPNZ_EX |  |  | ~0 | ~0,->4
 | 3 | BOOL |  |  | ~0 | 1
 | 4 | JMPZ |  |  |  | ~0,->7
 | 5 | ECHO |  |  |  | 'foo'
 | 6 | JMP |  |  |  | ->7
9 | 7 | RETURN |  |  |  | 1


BOOL_NOT

PHP code

<?php
/*
 * Boolean (logical) not of "value"
 * opcode number: 13
 */
echo !1;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | BOOL_NOT |  |  | ~0 | 1
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1


BOOL_XOR

PHP code

<?php
/*
 * Boolean (logical) xor of value1
 * opcode number: 14
 */
echo 1 xor 2;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | BOOL_XOR |  |  | ~0 | 1,2
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1


BRK

PHP code

<?php
/*
 * ???  End of a case block exists the current switch block.  Followed by JMP?
 * opcode number: 50
 */
$x = 0;
while(1) {
    if($x == 0) break;
}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,0
7 | 1 | JMPZ |  |  |  | 1,->7
8 | 2 | IS_EQUAL |  |  | ~1 | !0,0
 | 3 | JMPZ |  |  |  | ~1,->6
 | 4 | BRK |  |  |  | 1
 | 5 | JMP |  |  |  | ->6
9 | 6 | JMP |  |  |  | ->1
10 | 7 | RETURN |  |  |  | 1


BW_AND

PHP code

<?php
/*
 * Bit-wise and of value1 and value2
 * opcode number: 10
 */
echo 1&2;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | BW_AND |  |  | ~0 | 1,2
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1


BW_NOT

PHP code

<?php
/*
 * Bit-wise not of "value"
 * opcode number: 12
 */
echo ~15;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | BW_NOT |  |  | ~0 | 15
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1


BW_OR

PHP code

<?php
/*
 * Bit-wise or of value1 and value2
 * opcode number: 9
 */
echo 1|2;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | BW_OR |  |  | ~0 | 1,2
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1


BW_XOR

PHP code

<?php
/*
 * Bit-wise xor of value1 and value2
 * opcode number: 11
 */
echo 1^2;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | BW_XOR |  |  | ~0 | 1,2
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1


CASE

PHP code

<?php
/*
 * Set result to true if value1 equals value2.  The value2 must be a constant value?
 * opcode number: 48
 */
$i=0;
switch ($i) {
   case 0:
         echo "i=0";
         break;
   case 1:
         echo "i=1";
         break;
   case 2:
         echo "i=2";
         break;
}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$i

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,0
8 | 1 | CASE |  |  | ~1 | !0,0
 | 2 | JMPZ |  |  |  | ~1,->6
9 | 3 | ECHO |  |  |  | 'i%3D0'
10 | 4 | BRK |  |  |  | 1
11 | 5 | JMP |  |  |  | ->8
 | 6 | CASE |  |  | ~1 | !0,1
 | 7 | JMPZ |  |  |  | ~1,->11
12 | 8 | ECHO |  |  |  | 'i%3D1'
13 | 9 | BRK |  |  |  | 1
14 | 10 | JMP |  |  |  | ->13
 | 11 | CASE |  |  | ~1 | !0,2
 | 12 | JMPZ |  |  |  | ~1,->16
15 | 13 | ECHO |  |  |  | 'i%3D2'
16 | 14 | BRK |  |  |  | 1
17 | 15 | JMP |  |  |  | ->16
18 | 16 | RETURN |  |  |  | 1


CAST

PHP code

<?php
/*
 * casts value1 as type value2 (type in extended_value)
 * opcode number: 21
 */
echo (int)1;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | CAST |  | 4 | ~0 | 1
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1


CATCH

PHP code

<?php
/*
 *
 * opcode number: 107
 */
try {
    $error = 'Always throw this error';
    throw new Exception($error);

    // Code following an exception is not executed.
    echo 'Never executed';

} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

// Continue execution
echo 'Hello World';
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$error, !1=$e

line | # | op | fetch | ext | return | operands
7 | 0 | ASSIGN |  |  |  | !0,'Always+throw+this+error'
8 | 1 | ZEND_FETCH_CLASS |  |  | :1 | 'Exception'
 | 2 | NEW |  |  | $2 | :1
 | 3 | SEND_VAR |  |  |  | !0
 | 4 | DO_FCALL_BY_NAME |  | 1 |  |
 | 5 | ZEND_THROW |  | 0 |  | $2
11 | 6 | ECHO |  |  |  | 'Never+executed'
13 | 7 | JMP |  |  |  | ->15
 | 8 | ZEND_FETCH_CLASS |  |  | :4 | 'Exception'
 | 9 | ZEND_CATCH |  | 15 |  | $4,!1
14 | 10 | ECHO |  |  |  | 'Caught+exception%3A+'
 | 11 | ZEND_INIT_METHOD_CALL |  |  |  | !1,'getMessage'
 | 12 | DO_FCALL_BY_NAME |  | 0 |  |
 | 13 | ECHO |  |  |  | $6
 | 14 | ECHO |  |  |  | '%0A'
18 | 15 | ECHO |  |  |  | 'Hello+World'
19 | 16 | RETURN |  |  |  | 1


CLONE

PHP code

<?php
/*
 *
 * opcode number: 110
 */
$obj = new A();
$copy = clone $obj;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj, !1=$copy

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | ZEND_CLONE |  |  | $4 | !0
 | 5 | ASSIGN |  |  |  | !1,$4
8 | 6 | RETURN |  |  |  | 1


CONCAT

PHP code

<?php
/*
 * Concats string values string1 and string2
 * opcode number: 8
 */
echo "hello" . "world";
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | CONCAT |  |  | ~0 | 'hello','world'
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1


CONT

PHP code

<?php
/*
 * Continue next iteration of current loop level
 * opcode number: 51
 */
$foo = false;
while(!$foo) {
    $foo = true;
    continue;
}
?>

PHP opcodes

Function name: (null)

compiled vars: !0 = $foo

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0, false
7 | 1 | BOOL_NOT |  |  | ~1 | !0
 | 2 | JMPZ |  |  |  | ~1, ->5
8 | 3 | ASSIGN |  |  |  | !0, true
9 | 4 | CONT |  |  |  | 1
10 | 5 | JMP |  |  |  | ->1
12 | 6 | RETURN |  |  |  | 1


DECLARE_CLASS

PHP code

<?php
/*
 * Declare a class with the name of class-name as the implementation specified by ID.
 * opcode number: 139
 */
class A {
    function methodA(){
        echo "hello world";
    }
}
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
11 | 1 | RETURN |  |  |  | 1

Function name: methodA

Compiled variables: none

line | # | op | fetch | ext | return | operands
8 | 0 | ECHO |  |  |  | 'hello+world'
9 | 1 | RETURN |  |  |  | null


  • « DECLARE_CLASS
  • DECLARE_FUNCTION »
  • PHP Manual
  • Opcode Descriptions and Examples
  • DECLARE_CONST

DECLARE_CONST

PHP code

<?php
/*
 *
 * opcode number: 143
 * No sample PHP yet */
?>


DECLARE_FUNCTION

PHP code

<?php
/*
 *
 * opcode number: 141
 */
class A{
 function funcA(){
 }
}
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
10 | 1 | RETURN |  |  |  | 1

Function name: funcA

Compiled variables: none

line | # | op | fetch | ext | return | operands
8 | 0 | RETURN |  |  |  | null


DECLARE_INHERITED_CLASS

PHP code

<?php
/*
 *
 * opcode number: 140
 */
 if($b){
 class Foo {
  public static $my_static = 'foo';
  public function staticValue() {
    return self::$my_static;
  }
 }

 class Bar extends Foo {
  public function fooStatic() {
     echo parent::$my_static;
  }
 }
}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$b

line | # | op | fetch | ext | return | operands
6 | 0 | JMPZ |  |  |  | !0,->5
7 | 1 | ZEND_DECLARE_CLASS |  |  | $0 | '%00foo%2Fmnt%2Fworkspace%2Fws_phpscripts%2FPHPopcodes%2Fphpsamples%2FDECLARE_INHERITED_CLASS.php0xb7be503b','foo'
14 | 2 | ZEND_FETCH_CLASS |  |  | :1 | 'Foo'
 | 3 | ZEND_DECLARE_INHERITED_CLASS |  |  | $2 | '%00bar%2Fmnt%2Fworkspace%2Fws_phpscripts%2FPHPopcodes%2Fphpsamples%2FDECLARE_INHERITED_CLASS.php0xb7be50bc','bar'
19 | 4 | JMP |  |  |  | ->5
20 | 5 | RETURN |  |  |  | 1

Function name: staticValue

Compiled variables: !0=$my_static

line | # | op | fetch | ext | return | operands
10 | 0 | ZEND_FETCH_CLASS |  |  |  |
 | 1 | FETCH_R | staticmember |  | $1 | 'my_static'
 | 2 | RETURN |  |  |  | $1
11 | 3 | RETURN |  |  |  | null

Function name: fooStatic

Compiled variables: !0=$my_static

line | # | op | fetch | ext | return | operands
16 | 0 | ZEND_FETCH_CLASS |  |  | :0 |
 | 1 | FETCH_R | staticmember |  | $1 | 'my_static'
 | 2 | ECHO |  |  |  | $1
17 | 3 | RETURN |  |  |  | null


  • « DECLARE_INHERITED_CLASS
  • DIV »
  • PHP Manual
  • Opcode Descriptions and Examples
  • DECLARE_INHERITED_CLASS_DELAYED

DECLARE_INHERITED_CLASS_DELAYED

PHP code

<?php
/*
 *
 * opcode number: 145
 * No sample PHP yet */
?>


DIV

PHP code

<?php
/*
 * Divides "value1" by "value2" and stores the result into "result".
 * opcode number: 4
 */
echo 6/3;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | DIV |  |  | ~0 | 6,3
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1


DO_FCALL

PHP code

<?php
/*
 * Call a function.  Following multiple SEND_VAL, SEND_VAR or SEND_REF.
 * opcode number: 60
 */
$a = phpinfo();
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | DO_FCALL |  | 0 |  | 'phpinfo'
 | 1 | ASSIGN |  |  |  | !0,$0
7 | 2 | RETURN |  |  |  | 1


DO_FCALL_BY_NAME

PHP code

<?php
/*
 * Call a function by name.  Following INIT_FCALL_BY_NAME and multiple SEND_VAL, SEND_VAR or SEND_REF.
 * opcode number: 61
 */
$x = 'phpinfo';
$a = $x();
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,'phpinfo'
7 | 1 | INIT_FCALL_BY_NAME |  |  |  | !0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !1,$1
8 | 4 | RETURN |  |  |  | 1


ECHO

PHP code

<?php
/*
 * Dump text
 * opcode number: 40
 */
echo "hello world";
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | ECHO |  |  |  | 'hello+world'
7 | 1 | RETURN |  |  |  | 1


END_SILENCE

PHP code

<?php
/*
 * no longer surpress error messages
 * opcode number: 58
 */
$my_file = @file ('non_existent_file') or
   die ("error:'$php_errormsg'");
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$my_file, !1=$php_errormsg

line | # | op | fetch | ext | return | operands
6 | 0 | BEGIN_SILENCE |  |  | ~0 |
 | 1 | SEND_VAL |  |  |  | 'non_existent_file'
 | 2 | DO_FCALL |  | 1 |  | 'file'
 | 3 | END_SILENCE |  |  |  | ~0
 | 4 | ASSIGN |  |  | $2 | !0,$1
 | 5 | JMPNZ_EX |  |  | ~3 | $2,->11
7 | 6 | ADD_STRING |  |  | ~4 | 'error%3A%27'
 | 7 | ADD_VAR |  |  | ~4 | ~4,!1
 | 8 | ADD_CHAR |  |  | ~4 | ~4,39
 | 9 | EXIT |  |  |  | ~4
 | 10 | BOOL |  |  | ~3 | true
 | 11 | FREE |  |  |  | ~3
8 | 12 | RETURN |  |  |  | 1


EXIT

PHP code

<?php
/*
 * Exit running after dumping "message".
 * opcode number: 79
 */
die("foobar");
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | EXIT |  |  |  | 'foobar'
7 | 1 | RETURN |  |  |  | 1


  • « EXIT
  • EXT_FCALL_END »
  • PHP Manual
  • Opcode Descriptions and Examples
  • EXT_FCALL_BEGIN

EXT_FCALL_BEGIN

PHP code

<?php
/*
 *
 * opcode number: 102
 * No sample PHP yet */
?>


  • « EXT_FCALL_BEGIN
  • EXT_NOP »
  • PHP Manual
  • Opcode Descriptions and Examples
  • EXT_FCALL_END

EXT_FCALL_END

PHP code

<?php
/*
 *
 * opcode number: 103
 * No sample PHP yet */
?>


  • « EXT_FCALL_END
  • EXT_STMT »
  • PHP Manual
  • Opcode Descriptions and Examples
  • EXT_NOP

EXT_NOP

PHP code

<?php
/*
 *
 * opcode number: 104
 * No sample PHP yet */
?>


EXT_STMT

PHP code

<?php
/*
 *
 * opcode number: 101
 */
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
7 | 0 | EXT_STMT |  |  |  |
8 | 1 | RETURN |  |  |  | 1


FE_FETCH

PHP code

<?php
/*
 * Fetch an element from iterator.  If no element is available, jump to address.  Followed by OP_DATA?
 * opcode number: 78
 */
$a = array(1,2,3);
foreach($a as $num){
    print $num;
}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a, !1=$num

line | # | op | fetch | ext | return | operands
6 | 0 | INIT_ARRAY |  |  | ~0 | 1
 | 1 | ADD_ARRAY_ELEMENT |  |  | ~0 | 2
 | 2 | ADD_ARRAY_ELEMENT |  |  | ~0 | 3
 | 3 | ASSIGN |  |  |  | !0,~0
7 | 4 | FE_RESET |  |  | $2 | !0,->11
 | 5 | FE_FETCH |  |  | $3 | $2,->11
 | 6 | ZEND_OP_DATA |  |  |  |
 | 7 | ASSIGN |  |  |  | !1,$3
8 | 8 | PRINT |  |  | ~5 | !1
 | 9 | FREE |  |  |  | ~5
9 | 10 | JMP |  |  |  | ->5
 | 11 | SWITCH_FREE |  |  |  | $2
10 | 12 | RETURN |  |  |  | 1


FE_RESET

PHP code

<?php
/*
 * Initialize an iterator on array-value.  If the array is empty, jump to address.  Followed by FE_FETCH.
 * opcode number: 77
 */
$a = array(1,2,3);
foreach($a as $num){
    print $num;
}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a, !1=$num

line | # | op | fetch | ext | return | operands
6 | 0 | INIT_ARRAY |  |  | ~0 | 1
 | 1 | ADD_ARRAY_ELEMENT |  |  | ~0 | 2
 | 2 | ADD_ARRAY_ELEMENT |  |  | ~0 | 3
 | 3 | ASSIGN |  |  |  | !0,~0
7 | 4 | FE_RESET |  |  | $2 | !0,->11
 | 5 | FE_FETCH |  |  | $3 | $2,->11
 | 6 | ZEND_OP_DATA |  |  |  |
 | 7 | ASSIGN |  |  |  | !1,$3
8 | 8 | PRINT |  |  | ~5 | !1
 | 9 | FREE |  |  |  | ~5
9 | 10 | JMP |  |  |  | ->5
 | 11 | SWITCH_FREE |  |  |  | $2
10 | 12 | RETURN |  |  |  | 1


FETCH_CLASS

PHP code

<?php
/*
 *
 * opcode number: 109
 */
$obj = new A();
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | RETURN |  |  |  | 1


FETCH_CONSTANT

PHP code

<?php
/*
 * Fetch the constant value bound to the specified name (name) and stores it into a variable (result).
 * opcode number: 99
 */
define("FOO", "something");
echo FOO;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | SEND_VAL |  |  |  | 'FOO'
 | 1 | SEND_VAL |  |  |  | 'something'
 | 2 | DO_FCALL |  | 2 |  | 'define'
7 | 3 | FETCH_CONSTANT |  |  | ~1 | 'FOO'
 | 4 | ECHO |  |  |  | ~1
8 | 5 | RETURN |  |  |  | 1


FETCH_DIM_FUNC_ARG

PHP code

<?php
/*
 *
 * opcode number: 93
 */

function foo(&$x)
{
  print($x);
}

$x = array(0, 1, 2, 3, 4, 5);
$z = "foo";

$z($x[0]);

?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$z

line | # | op | fetch | ext | return | operands
7 | 0 | NOP |  |  |  |
12 | 1 | INIT_ARRAY |  |  | ~0 | 0
 | 2 | ADD_ARRAY_ELEMENT |  |  | ~0 | 1
 | 3 | ADD_ARRAY_ELEMENT |  |  | ~0 | 2
 | 4 | ADD_ARRAY_ELEMENT |  |  | ~0 | 3
 | 5 | ADD_ARRAY_ELEMENT |  |  | ~0 | 4
 | 6 | ADD_ARRAY_ELEMENT |  |  | ~0 | 5
 | 7 | ASSIGN |  |  |  | !0,~0
13 | 8 | ASSIGN |  |  |  | !1,'foo'
15 | 9 | INIT_FCALL_BY_NAME |  |  |  | !1
 | 10 | FETCH_DIM_FUNC_ARG |  |  | $3 | !0,0
 | 11 | SEND_VAR |  |  |  | $3
 | 12 | DO_FCALL_BY_NAME |  | 1 |  |
17 | 13 | RETURN |  |  |  | 1

Function name: foo

Compiled variables: !0=$x

line | # | op | fetch | ext | return | operands
7 | 0 | RECV |  |  |  | 1
9 | 1 | PRINT |  |  | ~0 | !0
 | 2 | FREE |  |  |  | ~0
10 | 3 | RETURN |  |  |  | null


  • « FETCH_DIM_FUNC_ARG
  • FETCH_DIM_R »
  • PHP Manual
  • Opcode Descriptions and Examples
  • FETCH_DIM_IS

FETCH_DIM_IS

PHP code

<?php
/*
 *
 * opcode number: 90
 * No sample PHP yet */
?>


FETCH_DIM_R

PHP code

<?php
/*
 * Fetch the value of the element at "index" in "array-value" to store it in "result".  Read-only?
 * opcode number: 81
 */
$x = array(1,2,3);
$a = 'x';
echo $$a[0];
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | INIT_ARRAY |  |  | ~0 | 1
 | 1 | ADD_ARRAY_ELEMENT |  |  | ~0 | 2
 | 2 | ADD_ARRAY_ELEMENT |  |  | ~0 | 3
 | 3 | ASSIGN |  |  |  | !0,~0
7 | 4 | ASSIGN |  |  |  | !1,'x'
8 | 5 | FETCH_DIM_R |  |  | $3 | !1,0
 | 6 | FETCH_R | local |  | $4 | $3
 | 7 | ECHO |  |  |  | $4
9 | 8 | RETURN |  |  |  | 1


FETCH_DIM_RW

PHP code

<?php
/*
 * Fetch the value of the element at "index" in "array-value" to store it in "result".
 * opcode number: 87
 */
$x = array(1,2,3);
$a = 'x';
$$a[0]++;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | INIT_ARRAY |  |  | ~0 | 1
 | 1 | ADD_ARRAY_ELEMENT |  |  | ~0 | 2
 | 2 | ADD_ARRAY_ELEMENT |  |  | ~0 | 3
 | 3 | ASSIGN |  |  |  | !0,~0
7 | 4 | ASSIGN |  |  |  | !1,'x'
8 | 5 | FETCH_DIM_R |  |  | $3 | !1,0
 | 6 | FETCH_RW | local |  | $4 | $3
 | 7 | POST_INC |  |  | ~5 | $4
 | 8 | FREE |  |  |  | ~5
9 | 9 | RETURN |  |  |  | 1


FETCH_DIM_TMP_VAR

PHP code

<?php
/*
 * Fetch an entry of an array from a temporal variable?
 * opcode number: 98
 */
list($x) = array("X");
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x

line | # | op | fetch | ext | return | operands
6 | 0 | INIT_ARRAY |  |  | ~0 | 'X'
 | 1 | FETCH_DIM_TMP_VAR |  |  | $1 | ~0,0
 | 2 | ASSIGN |  |  |  | !0,$1
 | 3 | FREE |  |  |  | ~0
7 | 4 | RETURN |  |  |  | 1


FETCH_DIM_UNSET

PHP code

<?php
/*
 * Fetch an entry of an array variable for the purpose of unset() operation.
 * opcode number: 96
 * No sample PHP yet */
?>


FETCH_DIM_W

PHP code

<?php
/*
 * Fetch the value of the element at "index" in "array-value" to store it in "result".  Write-only?
 * opcode number: 84
 */
$a = 1;
while($a > 0){
    $a = 0;
}
/*$input =array(1,2,3);
while (list($var,) = @each($input)){
    unset($$var);
}*/
/*$a = array(1,2,3);
$x = 'a';
$$x[0] = 1;*/

/*while ($b = each($a)) {
  print $b;
}*/

?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,1
7 | 1 | IS_SMALLER |  |  | ~1 | 0,!0
 | 2 | JMPZ |  |  |  | ~1,->5
8 | 3 | ASSIGN |  |  |  | !0,0
9 | 4 | JMP |  |  |  | ->1
23 | 5 | RETURN |  |  |  | 1


FETCH_FUNC_ARG

PHP code

<?php
/*
 *
 * opcode number: 92
 */
function foo($x)
{
}

$x = 1;
$y = "x";
$z = "foo";

$z($$y);

?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$y, !2=$z

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
10 | 1 | ASSIGN |  |  |  | !0,1
11 | 2 | ASSIGN |  |  |  | !1,'x'
12 | 3 | ASSIGN |  |  |  | !2,'foo'
14 | 4 | INIT_FCALL_BY_NAME |  |  |  | !2
 | 5 | FETCH_FUNC_ARG | local |  | $3 | !1
 | 6 | SEND_VAR |  |  |  | $3
 | 7 | DO_FCALL_BY_NAME |  | 1 |  |
16 | 8 | RETURN |  |  |  | 1

Function name: foo

Compiled variables: !0=$x

line | # | op | fetch | ext | return | operands
6 | 0 | RECV |  |  |  | 1
8 | 1 | RETURN |  |  |  | null


FETCH_IS

PHP code

<?php
/*
 * Fetch the value from variable which is to be used to test if it is set or not, through isset()/isempty().
 * opcode number: 89
 */
echo isset($_SESSION['userid']);
echo isset($_SESSION['userid'][1]);
echo isset($_SESSION->prop->prop);
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | FETCH_IS |  |  | $0 | '_SESSION'
 | 1 | ZEND_ISSET_ISEMPTY_DIM_OBJ |  | 1 | ~1 | $0,'userid'
 | 2 | ECHO |  |  |  | ~1
7 | 3 | FETCH_IS |  |  | $2 | '_SESSION'
 | 4 | FETCH_DIM_IS |  |  | $3 | $2,'userid'
 | 5 | ZEND_ISSET_ISEMPTY_DIM_OBJ |  | 1 | ~4 | $3,1
 | 6 | ECHO |  |  |  | ~4
8 | 7 | FETCH_IS |  |  | $5 | '_SESSION'
 | 8 | FETCH_OBJ_IS |  |  | $6 | $5,'prop'
 | 9 | ZEND_ISSET_ISEMPTY_PROP_OBJ |  |  | ~7 | $6,'prop'
 | 10 | ECHO |  |  |  | ~7
9 | 11 | RETURN |  |  |  | 1


FETCH_OBJ_FUNC_ARG

PHP code

<?php
/*
 *
 * opcode number: 94
 */
include './classA.php';

function foo(&$x)
{
  print($x);
}

$z = "foo";

$obj = new A();
print $obj->num;
$z($obj->num);

?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$z, !1=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | INCLUDE_OR_EVAL |  |  |  | '.%2FclassA.php',INCLUDE
8 | 1 | NOP |  |  |  |
13 | 2 | ASSIGN |  |  |  | !0,'foo'
15 | 3 | ZEND_FETCH_CLASS |  |  | :2 | 'A'
 | 4 | NEW |  |  | $3 | :2
 | 5 | DO_FCALL_BY_NAME |  | 0 |  |
 | 6 | ASSIGN |  |  |  | !1,$3
16 | 7 | FETCH_OBJ_R |  |  | $6 | !1,'num'
 | 8 | PRINT |  |  | ~7 | $6
 | 9 | FREE |  |  |  | ~7
17 | 10 | INIT_FCALL_BY_NAME |  |  |  | !0
 | 11 | FETCH_OBJ_FUNC_ARG |  |  | $8 | !1,'num'
 | 12 | SEND_VAR |  |  |  | $8
 | 13 | DO_FCALL_BY_NAME |  | 1 |  |
19 | 14 | RETURN |  |  |  | 1

Function name: foo

Compiled variables: !0=$x

line | # | op | fetch | ext | return | operands
8 | 0 | RECV |  |  |  | 1
10 | 1 | PRINT |  |  | ~0 | !0
 | 2 | FREE |  |  |  | ~0
11 | 3 | RETURN |  |  |  | null

Function name: foo

Compiled variables: !0=$x

line | # | op | fetch | ext | return | operands
8 | 0 | RECV |  |  |  | 1
10 | 1 | PRINT |  |  | ~0 | !0
 | 2 | FREE |  |  |  | ~0
11 | 3 | RETURN |  |  |  | null


  • « FETCH_OBJ_FUNC_ARG
  • FETCH_OBJ_R »
  • PHP Manual
  • Opcode Descriptions and Examples
  • FETCH_OBJ_IS

FETCH_OBJ_IS

PHP code

<?php
/*
 *
 * opcode number: 91
 * No sample PHP yet */
?>


FETCH_OBJ_R

PHP code

<?php
/*
 * Fetch the "prop-name" property value of this object.  Read-only?
 * opcode number: 82
 */
$x = new A();
$a = 'x';
echo $$a->num;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | ASSIGN |  |  |  | !1,'x'
8 | 5 | FETCH_R | local |  | $5 | !1
 | 6 | FETCH_OBJ_R |  |  | $6 | $5,'num'
 | 7 | ECHO |  |  |  | $6
9 | 8 | RETURN |  |  |  | 1


FETCH_OBJ_RW

PHP code

<?php
/*
 * Fetch the "prop-name" property value of this object.
 * opcode number: 88
 */
$x = new A();
$a = 'x';
$$a->num++;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | ASSIGN |  |  |  | !1,'x'
8 | 5 | FETCH_RW | local |  | $5 | !1
 | 6 | ZEND_POST_INC_OBJ |  |  | ~7 | $5,'num'
 | 7 | FREE |  |  |  | ~7
9 | 8 | RETURN |  |  |  | 1


FETCH_OBJ_UNSET

PHP code

<?php
/*
 * Fetch a property of an object variable for the purpose of unset() operation.
 * opcode number: 97
 * No sample PHP yet */
?>


FETCH_OBJ_W

PHP code

<?php
/*
 * Fetch an object from the property of this object and write to the property of the fectched object.
 * opcode number: 85
 */
$foo = new stdclass;
$foo->bar = new stdclass;
$foo->bar->baz = 'quix';
?>

PHP opcodes

Function name: (null)

Compiled variables: !0 = $foo

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  | 4 | :0 | 'stdclass'
 | 1 | NEW |  |  |  | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0
7 | 4 | ZEND_FETCH_CLASS |  | 4 | :5 | 'stdclass'
 | 5 | NEW |  |  |  | :5
 | 6 | DO_FCALL_BY_NAME |  | 0 |  |
 | 7 | ZEND_ASSIGN_OBJ |  |  |  | !0, 'bar'
 | 8 | ZEND_OP_DATA |  |  |  |
8 | 9 | FETCH_OBJ_W |  |  |  | !0, 'bar'
 | 10 | ZEND_ASSIGN_OBJ |  |  |  | 'baz'
 | 11 | ZEND_OP_DATA |  |  |  | 'quix'
9 | 12 | RETURN |  |  |  | 1


FETCH_R

PHP code

<?php
/*
 * Fetch the value of the varible of "name" to assign it to a variable?  Read-only?
 * opcode number: 80
 */
$x = 1;
$a = 'x';
echo $$a;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,1
7 | 1 | ASSIGN |  |  |  | !1,'x'
8 | 2 | FETCH_R | local |  | $2 | !1
 | 3 | ECHO |  |  |  | $2
9 | 4 | RETURN |  |  |  | 1


FETCH_RW

PHP code

<?php
/*
 * Fetch the value of the varible of "name" to assign it to a variable?
 * opcode number: 86
 */
$x = 1;
$a = 'x';
$$a++;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,1
7 | 1 | ASSIGN |  |  |  | !1,'x'
8 | 2 | FETCH_RW | local |  | $2 | !1
 | 3 | POST_INC |  |  | ~3 | $2
 | 4 | FREE |  |  |  | ~3
9 | 5 | RETURN |  |  |  | 1


FETCH_UNSET

PHP code

<?php
/*
 * Fetch a variable for the purpose of unset() operation.
 * opcode number: 95
 * No sample PHP yet */
?>


FETCH_W

PHP code

<?php
/*
 * Fetch the value of the varible of "name" to assign it to a variable?  Write-only?
 * opcode number: 83
 */
$x = 1;
$a = 'x';
$$a = 2;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,1
7 | 1 | ASSIGN |  |  |  | !1,'x'
8 | 2 | FETCH_W | local |  | $2 | !1
 | 3 | ASSIGN |  |  |  | $2,2
9 | 4 | RETURN |  |  |  | 1


FREE

PHP code

<?php
/*
 * Release the allocated space of the value.
 * opcode number: 70
 */
 print "Hello World";
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | PRINT |  |  | ~0 | 'Hello+World'
 | 1 | FREE |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1


  • « FREE
  • HANDLE_EXCEPTION »
  • PHP Manual
  • Opcode Descriptions and Examples
  • GOTO

GOTO

PHP code

<?php
/*
 *
 * opcode number: 100
 * No sample PHP yet */
?>


HANDLE_EXCEPTION

PHP code

<?php
/*
 *
 * opcode number: 149
 */
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | RETURN |  |  |  | 1


INCLUDE_OR_EVAL

PHP code

<?php
/*
 * Include the file specified by filename and eval it.
 * opcode number: 73
 */
include("test.php");
eval("test.php");
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | INCLUDE_OR_EVAL |  |  |  | 'test.php',INCLUDE
7 | 1 | INCLUDE_OR_EVAL |  |  |  | 'test.php',EVAL
8 | 2 | RETURN |  |  |  | 1

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
2 | 0 | DO_FCALL |  | 0 |  | 'phpinfo'
3 | 1 | RETURN |  |  |  | 1


INIT_ARRAY

PHP code

<?php
/*
 * Allocate a new array with elem-value as the first element of the array.  Followed by ADD_ARRAY_ELEMENT.
 * opcode number: 71
 */
$a = array(1,2,3);
print_r($a);
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | INIT_ARRAY |  |  | ~0 | 1
 | 1 | ADD_ARRAY_ELEMENT |  |  | ~0 | 2
 | 2 | ADD_ARRAY_ELEMENT |  |  | ~0 | 3
 | 3 | ASSIGN |  |  |  | !0,~0
7 | 4 | SEND_VAR |  |  |  | !0
 | 5 | DO_FCALL |  | 1 |  | 'print_r'
8 | 6 | RETURN |  |  |  | 1


INIT_FCALL_BY_NAME

PHP code

<?php
/*
 * prepare for a function call to function value1
 * opcode number: 59
 */
$x = 'phpinfo';
$a = $x();
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,'phpinfo'
7 | 1 | INIT_FCALL_BY_NAME |  |  |  | !0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !1,$1
8 | 4 | RETURN |  |  |  | 1


INIT_METHOD_CALL

PHP code

<?php
/*
 * Prepare for a method call.  Followed by DO_FCALL.
 * opcode number: 112
 */
class A {
  var $num;
    function incrementNum(){
    $num++;
  }
}

$obj = new A();
$obj->incrementNum();

?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
13 | 1 | ZEND_FETCH_CLASS |  |  | :1 | 'A'
 | 2 | NEW |  |  | $2 | :1
 | 3 | DO_FCALL_BY_NAME |  | 0 |  |
 | 4 | ASSIGN |  |  |  | !0,$2
14 | 5 | ZEND_INIT_METHOD_CALL |  |  |  | !0,'incrementNum'
 | 6 | DO_FCALL_BY_NAME |  | 0 |  |
16 | 7 | RETURN |  |  |  | 1

Function name: incrementNum

Compiled variables: !0=$num

line | # | op | fetch | ext | return | operands
9 | 0 | POST_INC |  |  | ~0 | !0
 | 1 | FREE |  |  |  | ~0
10 | 2 | RETURN |  |  |  | null


  • « INIT_METHOD_CALL
  • INIT_STATIC_METHOD_CALL »
  • PHP Manual
  • Opcode Descriptions and Examples
  • INIT_NS_FCALL_BY_NAME

INIT_NS_FCALL_BY_NAME

PHP code

<?php
/*
 *
 * opcode number: 69
 * No sample PHP yet */
?>


INIT_STATIC_METHOD_CALL

PHP code

<?php
/*
 *
 * opcode number: 113
 */
class Foo {
    public static function aStaticMethod() {
            echo "hello world\n";
    }
}

Foo::aStaticMethod();
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
12 | 1 | ZEND_INIT_STATIC_METHOD_CALL |  |  |  | 'Foo','aStaticMethod'
 | 2 | ZEND_OP_DATA |  |  |  | 'foo%3A%3Aastaticmethod'
 | 3 | DO_FCALL_BY_NAME |  | 0 |  |
13 | 4 | RETURN |  |  |  | 1

Function name: aStaticMethod

Compiled variables: none

line | # | op | fetch | ext | return | operands
8 | 0 | ECHO |  |  |  | 'hello+world%0A'
9 | 1 | RETURN |  |  |  | null


INIT_STRING

PHP code

<?php
/*
 * appears to create a string variable in result
 * opcode number: 53
 */
echo "hello$a world";
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ADD_STRING |  |  | ~0 | 'hello'
 | 1 | ADD_VAR |  |  | ~0 | ~0,!0
 | 2 | ADD_STRING |  |  | ~0 | ~0,'+world'
 | 3 | ECHO |  |  |  | ~0
7 | 4 | RETURN |  |  |  | 1


INSTANCEOF

PHP code

<?php
/*
 *
 * opcode number: 138
 */
$obj = new A();

if ($obj instanceof A) {
   echo 'A';
}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
8 | 4 | ZEND_FETCH_CLASS |  |  | :4 | 'A'
 | 5 | ZEND_INSTANCEOF |  |  | ~5 | !0,$4
 | 6 | JMPZ |  |  |  | ~5,->9
9 | 7 | ECHO |  |  |  | 'A'
10 | 8 | JMP |  |  |  | ->9
11 | 9 | RETURN |  |  |  | 1


IS_EQUAL

PHP code

<?php
/*
 * compares if value1 and value2 are equal
 * opcode number: 17
 */
echo (1 == 1);
echo (1 == 'c');
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | IS_EQUAL |  |  | ~0 | 1,1
 | 1 | ECHO |  |  |  | ~0
7 | 2 | IS_EQUAL |  |  | ~1 | 1,'c'
 | 3 | ECHO |  |  |  | ~1
8 | 4 | RETURN |  |  |  | 1


IS_IDENTICAL

PHP code

<?php
/*
 * Compares value1 and value2 to see if they are equal AND have the same type
 * opcode number: 15
 */
echo (1===1);
echo (1==='a');
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | IS_IDENTICAL |  |  | ~0 | 1,1
 | 1 | ECHO |  |  |  | ~0
7 | 2 | IS_IDENTICAL |  |  | ~1 | 1,'a'
 | 3 | ECHO |  |  |  | ~1
8 | 4 | RETURN |  |  |  | 1


IS_NOT_EQUAL

PHP code

<?php
/*
 * compares if value1 and value2 are not equal
 * opcode number: 18
 */
echo (1 != 1);
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | IS_NOT_EQUAL |  |  | ~0 | 1,1
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1


IS_NOT_IDENTICAL

PHP code

<?php
/*
 * compares value1 and value2 to see if they are unequal or of different types
 * opcode number: 16
 */
echo (1 !== 1);
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | IS_NOT_IDENTICAL |  |  | ~0 | 1,1
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1


IS_SMALLER

PHP code

<?php
/*
 * compares if value1 is less than value2
 * opcode number: 19
 */
echo (1 < 2);
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | IS_SMALLER |  |  | ~0 | 1,2
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1


IS_SMALLER_OR_EQUAL

PHP code

<?php
/*
 * compares if value1 is less than or equal to value2
 * opcode number: 20
 */
echo (2 <= 1);
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | IS_SMALLER_OR_EQUAL |  |  | ~0 | 2,1
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1


ISSET_ISEMPTY_DIM_OBJ

PHP code

<?php
/*
 * Tests if the entry of an array is set or not.
 * opcode number: 115
 */
if(isset($a[0])) return 0;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_ISSET_ISEMPTY_DIM_OBJ |  | 1 | ~0 | !0,0
 | 1 | JMPZ |  |  |  | ~0,->4
 | 2 | RETURN |  |  |  | 0
 | 3 | JMP |  |  |  | ->4
7 | 4 | RETURN |  |  |  | 1


ISSET_ISEMPTY_PROP_OBJ

PHP code

<?php
/*
 *
 * opcode number: 148
 */
$obj = new A();
if(empty($obj->num)) return 0;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | ZEND_ISSET_ISEMPTY_PROP_OBJ |  |  | ~4 | !0,'num'
 | 5 | JMPZ |  |  |  | ~4,->8
 | 6 | RETURN |  |  |  | 0
 | 7 | JMP |  |  |  | ->8
8 | 8 | RETURN |  |  |  | 1


ISSET_ISEMPTY_VAR

PHP code

<?php
/*
 * Tests if the value of a variable is set or not.
 * opcode number: 114
 */
if(isset($a)){ return 0;}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_ISSET_ISEMPTY_VAR |  | 5 | ~0 | !0
 | 1 | JMPZ |  |  |  | ~0,->4
 | 2 | RETURN |  |  |  | 0
 | 3 | JMP |  |  |  | ->4
7 | 4 | RETURN |  |  |  | 1


JMP

PHP code

<?php
/*
 * Unconditonally jump to the address
 * opcode number: 42
 */
$foo = false;
while(!$foo) {
    $foo = true;
}
?>

PHP opcodes

Function name: (null)

compiled vars: !0 = $foo

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0, false
7 | 1 | BOOL_NOT |  |  | ~1 | !0
 | 2 | JMPZ |  |  |  | ~1, ->5
8 | 3 | ASSIGN |  |  |  | !0, true
9 | 4 | JMP |  |  |  | ->1
11 | 5 | RETURN |  |  |  | 1


JMPNZ

PHP code

<?php
/*
 * Jump to the address if the value is not zero
 * opcode number: 44
 */
for($i=0; $i<3; $i++){
    echo "hi";
}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$i

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,0
 | 1 | IS_SMALLER |  |  | ~1 | !0,3
 | 2 | JMPZNZ |  | 6 |  | ~1,->8
 | 3 | POST_INC |  |  | ~2 | !0
 | 4 | FREE |  |  |  | ~2
 | 5 | JMP |  |  |  | ->1
7 | 6 | ECHO |  |  |  | 'hi'
8 | 7 | JMP |  |  |  | ->3
9 | 8 | RETURN |  |  |  | 1


JMPNZ_EX

PHP code

<?php
/*
 * Jump to the address if the xor of value1 and value2 is zero .. ???
 * opcode number: 47
 */
if(1^2) return;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | BW_XOR |  |  | ~0 | 1,2
 | 1 | JMPZ |  |  |  | ~0,->4
 | 2 | RETURN |  |  |  | null
 | 3 | JMP |  |  |  | ->4
7 | 4 | RETURN |  |  |  | 1


JMPZ

PHP code

<?php
/*
 * Jump to the address if the value is zero
 * opcode number: 43
 */
if($a != 0) echo "foo";
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | IS_NOT_EQUAL |  |  | ~0 | !0,0
 | 1 | JMPZ |  |  |  | ~0,->4
 | 2 | ECHO |  |  |  | 'foo'
 | 3 | JMP |  |  |  | ->4
7 | 4 | RETURN |  |  |  | 1


JMPZ_EX

PHP code

<?php
/*
 * Jump to the address if the xor of value1 and value2 is zero .. ???
 * opcode number: 46
 */

?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
7 | 0 | RETURN |  |  |  | 1


JMPZNZ

PHP code

<?php
/*
 * Jump to the address given in the operands if the value is zero;
 * jump to the address given in extended data if nonzero.
 * opcode number: 45
 */
for($i=0; $i<3; $i++){
    echo "hi";
}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$i

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,0
 | 1 | IS_SMALLER |  |  | ~1 | !0,3
 | 2 | JMPZNZ |  | 6 |  | ~1,->8
 | 3 | POST_INC |  |  | ~2 | !0
 | 4 | FREE |  |  |  | ~2
 | 5 | JMP |  |  |  | ->1
7 | 6 | ECHO |  |  |  | 'hi'
8 | 7 | JMP |  |  |  | ->3
9 | 8 | RETURN |  |  |  | 1


MOD

PHP code

<?php
/*
 * Makes the value of "result" congruent to "value1" modulo "value2".
 * opcode number: 5
 */
echo 6 % 3;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | MOD |  |  | ~0 | 6,3
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1


MUL

PHP code

<?php
/*
 * Multiplys "value1" by "value2" and stores the result into "result".
 * opcode number: 3
 */
echo 2*3;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | MUL |  |  | ~0 | 2,3
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1


NEW

PHP code

<?php
/*
 * Construct an instance of "type" and store the reference to the object into "result".
 * opcode number: 68
 */
$obj = new A();
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | RETURN |  |  |  | 1


NOP

PHP code

<?php
/*
 * no operation
 * opcode number: 0
 */
function A(){};
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
7 | 1 | RETURN |  |  |  | 1

Function name: A

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | RETURN |  |  |  | null


POST_DEC

PHP code

<?php
/*
 * decrements variable indicated by value1 by 1 (after performing other operations) and stores in result
 * opcode number: 37
 */
$a--;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | POST_DEC |  |  | ~0 | !0
 | 1 | FREE |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1


POST_DEC_OBJ

PHP code

<?php
/*
 *
 * opcode number: 135
 */
$obj = new A();
$obj->num--;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | ZEND_POST_DEC_OBJ |  |  | ~5 | !0,'num'
 | 5 | FREE |  |  |  | ~5
8 | 6 | RETURN |  |  |  | 1


POST_INC

PHP code

<?php
/*
 * increments variable indicated by value1 by 1 (after performing other operations) and stores in result
 * opcode number: 36
 */
$a++;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | POST_INC |  |  | ~0 | !0
 | 1 | FREE |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1


POST_INC_OBJ

PHP code

<?php
/*
 * Increment the property value specified by prop-name and store the original value into result.
 * opcode number: 134
 */
$obj = new A();
$obj->num++;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | ZEND_POST_INC_OBJ |  |  | ~5 | !0,'num'
 | 5 | FREE |  |  |  | ~5
8 | 6 | RETURN |  |  |  | 1


PRE_DEC

PHP code

<?php
/*
 * decrements variable indicated by value1 by 1 (before performing other operations) and stores in results
 * opcode number: 35
 */
--$a;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | PRE_DEC |  |  |  | !0
7 | 1 | RETURN |  |  |  | 1


PRE_DEC_OBJ

PHP code

<?php
/*
 *
 * opcode number: 133
 */
$obj = new A();
--$obj->num;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | ZEND_PRE_DEC_OBJ |  |  |  | !0,'num'
8 | 5 | RETURN |  |  |  | 1


PRE_INC

PHP code

<?php
/*
 * increments variable indicated by value1 by 1 (before performing other operations) and stores in result
 * opcode number: 34
 */
++$a;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | PRE_INC |  |  |  | !0
7 | 1 | RETURN |  |  |  | 1


PRE_INC_OBJ

PHP code

<?php
/*
 *
 * opcode number: 132
 */
$obj = new A();
++$obj->num;
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | ZEND_PRE_INC_OBJ |  |  |  | !0,'num'
8 | 5 | RETURN |  |  |  | 1


PRINT

PHP code

<?php
/*
 *
 * opcode number: 41
 */
print "Hello World";
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | PRINT |  |  | ~0 | 'Hello+World'
 | 1 | FREE |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1


QM_ASSIGN

PHP code

<?php
/*
 * Question Mark Assign, used twice inside a question mark assign to temporarily assign result as value1  (this is followed up with an ASSIGN bytecode)
 * opcode number: 22
 */
function A(){
 echo 1?2:3;
}

function B(){
 $b = 0;
 $a = $b > 1 ? 10: 11;
}
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
10 | 1 | NOP |  |  |  |
14 | 2 | RETURN |  |  |  | 1

Function name: A

Compiled variables: none

line | # | op | fetch | ext | return | operands
7 | 0 | JMPZ |  |  |  | 1,->3
 | 1 | QM_ASSIGN |  |  | ~0 | 2
 | 2 | JMP |  |  |  | ->4
 | 3 | QM_ASSIGN |  |  | ~0 | 3
 | 4 | ECHO |  |  |  | ~0
8 | 5 | RETURN |  |  |  | null

Function name: B

Compiled variables: !0=$b, !1=$a

line | # | op | fetch | ext | return | operands
11 | 0 | ASSIGN |  |  |  | !0,0
12 | 1 | IS_SMALLER |  |  | ~1 | 1,!0
 | 2 | JMPZ |  |  |  | ~1,->5
 | 3 | QM_ASSIGN |  |  | ~2 | 10
 | 4 | JMP |  |  |  | ->6
 | 5 | QM_ASSIGN |  |  | ~2 | 11
 | 6 | ASSIGN |  |  |  | !1,~2
13 | 7 | RETURN |  |  |  | null


RAISE_ABSTRACT_ERROR

PHP code

<?php
/*
 *
 * opcode number: 142
 */

abstract class fail {
    abstract function show();
}

class pass extends fail {
    function show() {
        echo "Call to function show()\n";
    }
}

$t2 = new pass();
$t2->show();

$t = new fail();
$t->show();

echo "Done\n"; // shouldn't be displayed
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$t2, !1=$t

line | # | op | fetch | ext | return | operands
7 | 0 | NOP |  |  |  |
11 | 1 | NOP |  |  |  |
 | 2 | NOP |  |  |  |
17 | 3 | ZEND_FETCH_CLASS |  |  | :3 | 'pass'
 | 4 | NEW |  |  | $4 | :3
 | 5 | DO_FCALL_BY_NAME |  | 0 |  |
 | 6 | ASSIGN |  |  |  | !0,$4
18 | 7 | ZEND_INIT_METHOD_CALL |  |  |  | !0,'show'
 | 8 | DO_FCALL_BY_NAME |  | 0 |  |
20 | 9 | ZEND_FETCH_CLASS |  |  | :9 | 'fail'
 | 10 | NEW |  |  | $10 | :9
 | 11 | DO_FCALL_BY_NAME |  | 0 |  |
 | 12 | ASSIGN |  |  |  | !1,$10
21 | 13 | ZEND_INIT_METHOD_CALL |  |  |  | !1,'show'
 | 14 | DO_FCALL_BY_NAME |  | 0 |  |
23 | 15 | ECHO |  |  |  | 'Done%0A'
24 | 16 | RETURN |  |  |  | 1

Function name: show

Compiled variables: none

line | # | op | fetch | ext | return | operands
8 | 0 | ZEND_RAISE_ABSTRACT_ERROR |  |  |  |
 | 1 | RETURN |  |  |  | null

Function name: show

Compiled variables: none

line | # | op | fetch | ext | return | operands
13 | 0 | ECHO |  |  |  | 'Call+to+function+show%28%29%0A'
14 | 1 | RETURN |  |  |  | null


RECV

PHP code

<?php
/*
 * Receive a functoin argument of "argument-number" and store the argument value into a variable of "argument-number".  (e.g. $1 for 1)
 * opcode number: 63
 */
function hello($a){}
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
7 | 1 | RETURN |  |  |  | 1

Function name: hello

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | RECV |  |  |  | 1
 | 1 | RETURN |  |  |  | null


RECV_INIT

PHP code

<?php
/*
 * Initialize a function argument with "value" if not received from caller.  Otherwise same as RECV.
 * opcode number: 64
 */
function hello($a=5){}
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
7 | 1 | RETURN |  |  |  | 1

Function name: hello

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | RECV_INIT |  |  |  | 1,5
 | 1 | RETURN |  |  |  | null


RETURN

PHP code

<?php
/*
 * Return value from a funciton.
 * opcode number: 62
 */
return 1;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | RETURN |  |  |  | 1
7 | 1 | RETURN |  |  |  | 1


  • « RETURN
  • SEND_REF »
  • PHP Manual
  • Opcode Descriptions and Examples
  • RETURN_BY_REF

RETURN_BY_REF

PHP code

<?php
/*
 *
 * opcode number: 111
 * No sample PHP yet */
?>


SEND_REF

PHP code

<?php
/*
 * Pass the reference value as an actual parameter to a function.  DO_FCALL follows.
 * opcode number: 67
 */
@each($input);
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | BEGIN_SILENCE |  |  | ~0 |
 | 1 | FETCH_W | local |  | $1 | 'input'
 | 2 | SEND_REF |  |  |  | $1
 | 3 | DO_FCALL |  | 1 |  | 'each'
 | 4 | END_SILENCE |  |  |  | ~0
7 | 5 | RETURN |  |  |  | 1


SEND_VAL

PHP code

<?php
/*
 * Pass the constant value as an actual parameter to a function.  DO_FCALL follows.
 * opcode number: 65
 */
function funcA($msg){
    print $msg;
}

funcA('HELLO');

defined('IN_PHPBB');
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | NOP |  |  |  |
10 | 1 | SEND_VAL |  |  |  | 'HELLO'
 | 2 | DO_FCALL |  | 1 |  | 'funca'
12 | 3 | SEND_VAL |  |  |  | 'IN_PHPBB'
 | 4 | DO_FCALL |  | 1 |  | 'defined'
13 | 5 | RETURN |  |  |  | 1

Function name: funcA

Compiled variables: !0=$msg

line | # | op | fetch | ext | return | operands
6 | 0 | RECV |  |  |  | 1
7 | 1 | PRINT |  |  | ~0 | !0
 | 2 | FREE |  |  |  | ~0
8 | 3 | RETURN |  |  |  | null


SEND_VAR

PHP code

<?php
/*
 * Pass the variable value as an actual parameter to a function.  DO_FCALL follows.
 * opcode number: 66
 */
$a = array(1,2,3);
if(is_array($a)){ return 0; }
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | INIT_ARRAY |  |  | ~0 | 1
 | 1 | ADD_ARRAY_ELEMENT |  |  | ~0 | 2
 | 2 | ADD_ARRAY_ELEMENT |  |  | ~0 | 3
 | 3 | ASSIGN |  |  |  | !0,~0
7 | 4 | SEND_VAR |  |  |  | !0
 | 5 | DO_FCALL |  | 1 |  | 'is_array'
 | 6 | JMPZ |  |  |  | $2,->9
 | 7 | RETURN |  |  |  | 0
 | 8 | JMP |  |  |  | ->9
8 | 9 | RETURN |  |  |  | 1


  • « SEND_VAR
  • SL »
  • PHP Manual
  • Opcode Descriptions and Examples
  • SEND_VAR_NO_REF

SEND_VAR_NO_REF

PHP code

<?php
/*
 *
 * opcode number: 106
 * No sample PHP yet */
?>


SL

PHP code

<?php
/*
 * Shift bits of value1 to the left value2 steps (each step means "multiply by two")
 * opcode number: 6
 */
echo 8 << 2;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | SL |  |  | ~0 | 8,2
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1


SR

PHP code

<?php
/*
 * Shift bits of value1 to the right value2 steps (each step means "divide by two")
 * opcode number: 7
 */
echo 8 >> 2;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | SR |  |  | ~0 | 8,2
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1


SUB

PHP code

<?php
/*
 * Subtracts "value2" from "value1" and stores the result into "result".
 * opcode number: 2
 */
echo 1-2;
?>

PHP opcodes

Function name: (null)

Compiled variables: none

line | # | op | fetch | ext | return | operands
6 | 0 | SUB |  |  | ~0 | 1,2
 | 1 | ECHO |  |  |  | ~0
7 | 2 | RETURN |  |  |  | 1


SWITCH_FREE

PHP code

<?php
/*
 * Release the allocated space of "value"?
 * opcode number: 49
 */
$a = array(1,2,3);
foreach($a as $num){
    print $num;
}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a, !1=$num

line | # | op | fetch | ext | return | operands
6 | 0 | INIT_ARRAY |  |  | ~0 | 1
 | 1 | ADD_ARRAY_ELEMENT |  |  | ~0 | 2
 | 2 | ADD_ARRAY_ELEMENT |  |  | ~0 | 3
 | 3 | ASSIGN |  |  |  | !0,~0
7 | 4 | FE_RESET |  |  | $2 | !0,->11
 | 5 | FE_FETCH |  |  | $3 | $2,->11
 | 6 | ZEND_OP_DATA |  |  |  |
 | 7 | ASSIGN |  |  |  | !1,$3
8 | 8 | PRINT |  |  | ~5 | !1
 | 9 | FREE |  |  |  | ~5
9 | 10 | JMP |  |  |  | ->5
 | 11 | SWITCH_FREE |  |  |  | $2
10 | 12 | RETURN |  |  |  | 1


THROW

PHP code

<?php
/*
 *
 * opcode number: 108
 */
try {
    $error = 'Always throw this error';
    throw new Exception($error);

    // Code following an exception is not executed.
    echo 'Never executed';

} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

// Continue execution
echo 'Hello World';
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$error, !1=$e

line | # | op | fetch | ext | return | operands
7 | 0 | ASSIGN |  |  |  | !0,'Always+throw+this+error'
8 | 1 | ZEND_FETCH_CLASS |  |  | :1 | 'Exception'
 | 2 | NEW |  |  | $2 | :1
 | 3 | SEND_VAR |  |  |  | !0
 | 4 | DO_FCALL_BY_NAME |  | 1 |  |
 | 5 | ZEND_THROW |  | 0 |  | $2
11 | 6 | ECHO |  |  |  | 'Never+executed'
13 | 7 | JMP |  |  |  | ->15
 | 8 | ZEND_FETCH_CLASS |  |  | :4 | 'Exception'
 | 9 | ZEND_CATCH |  | 15 |  | $4,!1
14 | 10 | ECHO |  |  |  | 'Caught+exception%3A+'
 | 11 | ZEND_INIT_METHOD_CALL |  |  |  | !1,'getMessage'
 | 12 | DO_FCALL_BY_NAME |  | 0 |  |
 | 13 | ECHO |  |  |  | $6
 | 14 | ECHO |  |  |  | '%0A'
18 | 15 | ECHO |  |  |  | 'Hello+World'
19 | 16 | RETURN |  |  |  | 1


TICKS

PHP code

<?php
/*
 *
 * opcode number: 105
 */
// A function that records the time when it is called
function profile()
{
   echo "profile function is called\n";
}

// Set up a tick handler
register_tick_function("profile");

// Initialize the function before the declare block
profile();

// Run a block of code, throw a tick every 2nd statement
declare(ticks=2) {
   for ($x = 0; $x < 10; ++$x) {
         echo "hello world\n";
   }
}
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x

line | # | op | fetch | ext | return | operands
7 | 0 | NOP |  |  |  |
13 | 1 | SEND_VAL |  |  |  | 'profile'
 | 2 | DO_FCALL |  | 1 |  | 'register_tick_function'
16 | 3 | DO_FCALL |  | 0 |  | 'profile'
20 | 4 | ASSIGN |  |  |  | !0,0
 | 5 | IS_SMALLER |  |  | ~3 | !0,10
 | 6 | JMPZNZ |  | 9 |  | ~3,->13
 | 7 | PRE_INC |  |  |  | !0
 | 8 | JMP |  |  |  | ->5
21 | 9 | ECHO |  |  |  | 'hello+world%0A'
 | 10 | TICKS |  |  |  | 2
22 | 11 | TICKS |  |  |  | 2
 | 12 | JMP |  |  |  | ->7
 | 13 | TICKS |  |  |  | 2
23 | 14 | TICKS |  |  |  | 2
24 | 15 | RETURN |  |  |  | 1

Function name: profile

Compiled variables: none

line | # | op | fetch | ext | return | operands
9 | 0 | ECHO |  |  |  | 'profile+function+is+called%0A'
10 | 1 | RETURN |  |  |  | null


UNSET_DIM

PHP code

<?php
/*
 * Unset the entry of array-value, which is specified by index, and store the original element value into "result".
 * opcode number: 75
 */
$a = array(1,2,3);
unset($a[0]);
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$a

line | # | op | fetch | ext | return | operands
6 | 0 | INIT_ARRAY |  |  | ~0 | 1
 | 1 | ADD_ARRAY_ELEMENT |  |  | ~0 | 2
 | 2 | ADD_ARRAY_ELEMENT |  |  | ~0 | 3
 | 3 | ASSIGN |  |  |  | !0,~0
7 | 4 | UNSET_DIM |  |  | $2 | !0,0
8 | 5 | RETURN |  |  |  | 1


UNSET_OBJ

PHP code

<?php
/*
 * Unset the property of the current object (this) and store the original value into "result".
 * opcode number: 76
 */
$obj = new A();
unset($obj->num);
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$obj

line | # | op | fetch | ext | return | operands
6 | 0 | ZEND_FETCH_CLASS |  |  | :0 | 'A'
 | 1 | NEW |  |  | $1 | :0
 | 2 | DO_FCALL_BY_NAME |  | 0 |  |
 | 3 | ASSIGN |  |  |  | !0,$1
7 | 4 | UNSET_OBJ |  |  | $4 | !0,'num'
8 | 5 | RETURN |  |  |  | 1


UNSET_VAR

PHP code

<?php
/*
 * Unset the variable and store the original value into "result".
 * opcode number: 74
 */
$x = 1;
$a='x';
unset($$a);
?>

PHP opcodes

Function name: (null)

Compiled variables: !0=$x, !1=$a

line | # | op | fetch | ext | return | operands
6 | 0 | ASSIGN |  |  |  | !0,1
7 | 1 | ASSIGN |  |  |  | !1,'x'
8 | 2 | UNSET_VAR |  |  | $2 | !1
9 | 3 | RETURN |  |  |  | 1


  • « UNSET_VAR
  • VERIFY_ABSTRACT_CLASS »
  • PHP Manual
  • Opcode Descriptions and Examples
  • USER_OPCODE

USER_OPCODE

PHP code

<?php
/*
 *
 * opcode number: 150
 * No sample PHP yet */
?>


  • « USER_OPCODE
  • ZEND_DECLARE_LAMBDA_FUNCTION »
  • PHP Manual
  • Opcode Descriptions and Examples
  • VERIFY_ABSTRACT_CLASS

VERIFY_ABSTRACT_CLASS

PHP code

<?php
/*
 *
 * opcode number: 146
 * No sample PHP yet */
?>


  • « VERIFY_ABSTRACT_CLASS
  • ZEND_JMP_SET »
  • PHP Manual
  • Opcode Descriptions and Examples
  • ZEND_DECLARE_LAMBDA_FUNCTION

ZEND_DECLARE_LAMBDA_FUNCTION

PHP code

<?php
/*
 *
 * opcode number: 153
 * No sample PHP yet */
?>


  • « ZEND_DECLARE_LAMBDA_FUNCTION
  • Zend Engine 1 »
  • PHP Manual
  • Opcode Descriptions and Examples
  • ZEND_JMP_SET

ZEND_JMP_SET

PHP code

<?php
/*
 *
 * opcode number: 152
 * No sample PHP yet */
?>


Zend Engine 1

Table of Contents

  • Old introduction
  • Streams API for PHP Extension Authors
  • Zend API: Hacking the Core of PHP
  • TSRM API

Zend Engine 1 is the internal engine used by PHP for the entire version 4 release line. It is no longer considered active, but the old ZE1 documentation is preserved here exactly as it was.


Old introduction

If you are about to begin developing PHP or Zend extensions, you need to prepare yourself for the programming environment provided by the various APIs. This part of the documentation tries to introduce the APIs provided by the different PHP and Zend Engine versions available. Since most of the information available here is somewhat outdated, you'll want to read various files found in the PHP source, files such as README.SELF-CONTAINED-EXTENSIONS and README.EXT_SKEL in addition to the manual.


Streams API for PHP Extension Authors

Note:

The functions in this chapter are for use in the PHP source code and are not PHP functions. Information on userland stream functions can be found in the Stream Reference.

Overview

The PHP Streams API introduces a unified approach to the handling of files and sockets in PHP extension. Using a single API with standard functions for common operations, the streams API allows your extension to access files, sockets, URLs, memory and script-defined objects. Streams is a run-time extensible API that allows dynamically loaded modules (and scripts!) to register new streams.

The aim of the Streams API is to make it comfortable for developers to open files, URLs and other streamable data sources with a unified API that is easy to understand. The API is more or less based on the ANSI C stdio family of functions (with identical semantics for most of the main functions), so C programmers will have a feeling of familiarity with streams.

The streams API operates on a couple of different levels: at the base level, the API defines php_stream objects to represent streamable data sources. On a slightly higher level, the API defines php_stream_wrapper objects which "wrap" around the lower level API to provide support for retrieving data and meta-data from URLs. An additional context parameter, accepted by most stream creation functions, is passed to the wrapper's stream_opener method to fine-tune the behavior of the wrapper.

Any stream, once opened, can also have any number of filters applied to it, which process data as it is read from/written to the stream.

Streams can be cast (converted) into other types of file-handles, so that they can be used with third-party libraries without a great deal of trouble. This allows those libraries to access data directly from URL sources. If your system has the fopencookie() or funopen() function, you can even pass any PHP stream to any library that uses ANSI stdio!

Streams Basics

Using streams is very much like using ANSI stdio functions. The main difference is in how you obtain the stream handle to begin with. In most cases, you will use php_stream_open_wrapper() to obtain the stream handle. This function works very much like fopen, as can be seen from the example below:

Example #1 simple stream example that displays the PHP home page

php_stream * stream = php_stream_open_wrapper("http://www.php.net", "rb", REPORT_ERRORS, NULL);
if (stream) {
    while(!php_stream_eof(stream)) {
        char buf[1024];

        if (php_stream_gets(stream, buf, sizeof(buf))) {
            printf(buf);
        } else {
            break;
        }
    }
    php_stream_close(stream);
}

The table below shows the Streams equivalents of the more common ANSI stdio functions. Unless noted otherwise, the semantics of the functions are identical.

ANSI stdio equivalent functions in the Streams API
ANSI Stdio Function | PHP Streams Function | Notes
fopen | php_stream_open_wrapper | Streams includes additional parameters
fclose | php_stream_close |
fgets | php_stream_gets |
fread | php_stream_read | The nmemb parameter is assumed to have a value of 1, so the prototype looks more like read(2)
fwrite | php_stream_write | The nmemb parameter is assumed to have a value of 1, so the prototype looks more like write(2)
fseek | php_stream_seek |
ftell | php_stream_tell |
rewind | php_stream_rewind |
feof | php_stream_eof |
fgetc | php_stream_getc |
fputc | php_stream_putc |
fflush | php_stream_flush |
puts | php_stream_puts | Same semantics as puts, NOT fputs
fstat | php_stream_stat | Streams has a richer stat structure

Streams as Resources

All streams are registered as resources when they are created. This ensures that they will be properly cleaned up even if there is some fatal error. All of the filesystem functions in PHP operate on streams resources - that means that your extensions can accept regular PHP file pointers as parameters to, and return streams from their functions. The streams API makes this process as painless as possible:

Example #2 How to accept a stream as a parameter

PHP_FUNCTION(example_write_hello)
{
    zval *zstream;
    php_stream *stream;

    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zstream))
        return;

    php_stream_from_zval(stream, &zstream);

    /* you can now use the stream.  However, you do not "own" the
        stream, the script does.  That means you MUST NOT close the
        stream, because it will cause PHP to crash! */

    php_stream_write(stream, "hello\n");

    RETURN_TRUE();
}

Example #3 How to return a stream from a function

PHP_FUNCTION(example_open_php_home_page)
{
    php_stream *stream;

    stream = php_stream_open_wrapper("http://www.php.net", "rb", REPORT_ERRORS, NULL);

    php_stream_to_zval(stream, return_value);

    /* after this point, the stream is "owned" by the script.
        If you close it now, you will crash PHP! */
}

Since streams are automatically cleaned up, it's tempting to think that we can get away with being sloppy programmers and not bother to close the streams when we are done with them. Although such an approach might work, it is not a good idea for a number of reasons: streams hold locks on system resources while they are open, so leaving a file open after you have finished with it could prevent other processes from accessing it. If a script deals with a large number of files, the accumulation of the resources used, both in terms of memory and the sheer number of open files, can cause web server requests to fail. Sounds bad, doesn't it? The streams API includes some magic that helps you to keep your code clean - if a stream is not closed by your code when it should be, you will find some helpful debugging information in you web server error log.

Note: Always use a debug build of PHP when developing an extension (--enable-debug when running configure), as a lot of effort has been made to warn you about memory and stream leaks.

In some cases, it is useful to keep a stream open for the duration of a request, to act as a log or trace file for example. Writing the code to safely clean up such a stream is not difficult, but it's several lines of code that are not strictly needed. To save yourself the trouble of writing the code, you can mark a stream as being OK for auto cleanup. What this means is that the streams API will not emit a warning when it is time to auto-cleanup a stream. To do this, you can use php_stream_auto_cleanup().

Streams open options

These constants affect the operation of stream factory functions.

IGNORE_PATH
This is the default option for streams; it requests that the include_path is not to be searched for the requested file.
USE_PATH
Requests that the include_path is to be searched for the requested file.
IGNORE_URL
Requests that registered URL wrappers are to be ignored when opening the stream. Other non-URL wrappers will be taken into consideration when decoding the path. There is no opposite form for this flag; the streams API will use all registered wrappers by default.
IGNORE_URL_WIN
On Windows systems, this is equivalent to IGNORE_URL. On all other systems, this flag has no effect.
ENFORCE_SAFE_MODE
Requests that the underlying stream implementation perform safe_mode checks on the file before opening the file. Omitting this flag will skip safe_mode checks and allow opening of any file that the PHP process has rights to access.
REPORT_ERRORS
If this flag is set, and there was an error during the opening of the file or URL, the streams API will call the php_error function for you. This is useful because the path may contain username/password information that should not be displayed in the browser output (it would be a security risk to do so). When the streams API raises the error, it first strips username/password information from the path, making the error message safe to display in the browser.
STREAM_MUST_SEEK
This flag is useful when your extension really must be able to randomly seek around in a stream. Some streams may not be seekable in their native form, so this flag asks the streams API to check to see if the stream does support seeking. If it does not, it will copy the stream into temporary storage (which may be a temporary file or a memory stream) which does support seeking. Please note that this flag is not useful when you want to seek the stream and write to it, because the stream you are accessing might not be bound to the actual resource you requested.

Note: If the requested resource is network based, this flag will cause the opener to block until the whole contents have been downloaded.

STREAM_WILL_CAST
If your extension is using a third-party library that expects a FILE* or file descriptor, you can use this flag to request the streams API to open the resource but avoid buffering. You can then use php_stream_cast() to retrieve the FILE* or file descriptor that the library requires. The is particularly useful when accessing HTTP URLs where the start of the actual stream data is found after an indeterminate offset into the stream. Since this option disables buffering at the streams API level, you may experience lower performance when using streams functions on the stream; this is deemed acceptable because you have told streams that you will be using the functions to match the underlying stream implementation. Only use this option when you are sure you need it.


Zend API: Hacking the Core of PHP

Introduction

Those who know don't talk.

Those who talk don't know.

Sometimes, PHP "as is" simply isn't enough. Although these cases are rare for the average user, professional applications will soon lead PHP to the edge of its capabilities, in terms of either speed or functionality. New functionality cannot always be implemented natively due to language restrictions and inconveniences that arise when having to carry around a huge library of default code appended to every single script, so another method needs to be found for overcoming these eventual lacks in PHP.

As soon as this point is reached, it's time to touch the heart of PHP and take a look at its core, the C code that makes PHP go.

Warning

This information is currently rather outdated, parts of it only cover early stages of the ZendEngine 1.0 API as it was used in early versions of PHP 4.

More recent information may be found in the various README files that come with the PHP source and the » Internals section on the Zend website.

Overview

"Extending PHP" is easier said than done. PHP has evolved to a full-fledged tool consisting of a few megabytes of source code, and to hack a system like this quite a few things have to be learned and considered. When structuring this chapter, we finally decided on the "learn by doing" approach. This is not the most scientific and professional approach, but the method that's the most fun and gives the best end results. In the following sections, you'll learn quickly how to get the most basic extensions to work almost instantly. After that, you'll learn about Zend's advanced API functionality. The alternative would have been to try to impart the functionality, design, tips, tricks, etc. as a whole, all at once, thus giving a complete look at the big picture before doing anything practical. Although this is the "better" method, as no dirty hacks have to be made, it can be very frustrating as well as energy- and time-consuming, which is why we've decided on the direct approach.

Note that even though this chapter tries to impart as much knowledge as possible about the inner workings of PHP, it's impossible to really give a complete guide to extending PHP that works 100% of the time in all cases. PHP is such a huge and complex package that its inner workings can only be understood if you make yourself familiar with it by practicing, so we encourage you to work with the source.

What Is Zend? and What Is PHP?

The name Zend refers to the language engine, PHP's core. The term PHP refers to the complete system as it appears from the outside. This might sound a bit confusing at first, but it's not that complicated ( see below). To implement a Web script interpreter, you need three parts:

  1. The interpreter part analyzes the input code, translates it, and executes it.

  2. The functionality part implements the functionality of the language (its functions, etc.).

  3. The interface part talks to the Web server, etc.

Zend takes part 1 completely and a bit of part 2; PHP takes parts 2 and 3. Together they form the complete PHP package. Zend itself really forms only the language core, implementing PHP at its very basics with some predefined functions. PHP contains all the modules that actually create the language's outstanding capabilities.
The internal structure of PHP.

The following sections discuss where PHP can be extended and how it's done.

Extension Possibilities

As shown above, PHP can be extended primarily at three points: external modules, built-in modules, and the Zend engine. The following sections discuss these options.

External Modules

External modules can be loaded at script runtime using the function dl(). This function loads a shared object from disk and makes its functionality available to the script to which it's being bound. After the script is terminated, the external module is discarded from memory. This method has both advantages and disadvantages, as described in the following table:

Advantages | Disadvantages
External modules don't require recompiling of PHP. | The shared objects need to be loaded every time a script is being executed (every hit), which is very slow.
The size of PHP remains small by "outsourcing" certain functionality. | External additional files clutter up the disk.
 |  | Every script that wants to use an external module's functionality has to specifically include a call to dl(), or the extension tag in php.ini needs to be modified (which is not always a suitable solution).
To sum up, external modules are great for third-party products, small additions to PHP that are rarely used, or just for testing purposes. To develop additional functionality quickly, external modules provide the best results. For frequent usage, larger implementations, and complex code, the disadvantages outweigh the advantages.

Third parties might consider using the extension tag in php.ini to create additional external modules to PHP. These external modules are completely detached from the main package, which is a very handy feature in commercial environments. Commercial distributors can simply ship disks or archives containing only their additional modules, without the need to create fixed and solid PHP binaries that don't allow other modules to be bound to them.

Built-in Modules

Built-in modules are compiled directly into PHP and carried around with every PHP process; their functionality is instantly available to every script that's being run. Like external modules, built-in modules have advantages and disadvantages, as described in the following table:

Advantages | Disadvantages
No need to load the module specifically; the functionality is instantly available. | Changes to built-in modules require recompiling of PHP.
No external files clutter up the disk; everything resides in the PHP binary. | The PHP binary grows and consumes more memory.
Built-in modules are best when you have a solid library of functions that remains relatively unchanged, requires better than poor-to-average performance, or is used frequently by many scripts on your site. The need to recompile PHP is quickly compensated by the benefit in speed and ease of use. However, built-in modules are not ideal when rapid development of small additions is required.

The Zend Engine

Of course, extensions can also be implemented directly in the Zend engine. This strategy is good if you need a change in the language behavior or require special functions to be built directly into the language core. In general, however, modifications to the Zend engine should be avoided. Changes here result in incompatibilities with the rest of the world, and hardly anyone will ever adapt to specially patched Zend engines. Modifications can't be detached from the main PHP sources and are overridden with the next update using the "official" source repositories. Therefore, this method is generally considered bad practice and, due to its rarity, is not covered in this book.

Source Layout

Note:

Prior to working through the rest of this chapter, you should retrieve clean, unmodified source trees of your favorite Web server. We're working with Apache (available at » http://httpd.apache.org/) and, of course, with PHP (available at » https://www.php.net/ - does it need to be said?).

Make sure that you can compile a working PHP environment by yourself! We won't go into this issue here, however, as you should already have this most basic ability when studying this chapter.

Before we start discussing code issues, you should familiarize yourself with the source tree to be able to quickly navigate through PHP's files. This is a must-have ability to implement and debug extensions.

The following table describes the contents of the major directories.

Directory | Contents
php-src | Main PHP source files and main header files; here you'll find all of PHP's API definitions, macros, etc. (important). Everything else is below this directory.
php-src/ext | Repository for dynamic and built-in modules; by default, these are the "official" PHP modules that have been integrated into the main source tree. From PHP 4.0, it's possible to compile these standard extensions as dynamic loadable modules (at least, those that support it).
php-src/main | This directory contains the main php macros and definitions. (important)
php-src/pear | Directory for the PHP Extension and Application Repository. This directory contains core PEAR files.
php-src/sapi | Contains the code for the different server abstraction layers.
TSRM | Location of the "Thread Safe Resource Manager" (TSRM) for Zend and PHP.
ZendEngine2 | Location of the Zend Engine files; here you'll find all of Zend's API definitions, macros, etc. (important).

Discussing all the files included in the PHP package is beyond the scope of this chapter. However, you should take a close look at the following files:

  • php-src/main/php.h, located in the main PHP directory. This file contains most of PHP's macro and API definitions.

  • php-src/Zend/zend.h, located in the main Zend directory. This file contains most of Zend's macros and definitions.

  • php-src/Zend/zend_API.h, also located in the Zend directory, which defines Zend's API.

You should also follow some sub-inclusions from these files; for example, the ones relating to the Zend executor, the PHP initialization file support, and such. After reading these files, take the time to navigate around the package a little to see the interdependencies of all files and modules - how they relate to each other and especially how they make use of each other. This also helps you to adapt to the coding style in which PHP is authored. To extend PHP, you should quickly adapt to this style.

Extension Conventions

Zend is built using certain conventions; to avoid breaking its standards, you should follow the rules described in the following sections.

Macros

For almost every important task, Zend ships predefined macros that are extremely handy. The tables and figures in the following sections describe most of the basic functions, structures, and macros. The macro definitions can be found mainly in zend.h and zend_API.h. We suggest that you take a close look at these files after having studied this chapter. (Although you can go ahead and read them now, not everything will make sense to you yet.)

Memory Management

Resource management is a crucial issue, especially in server software. One of the most valuable resources is memory, and memory management should be handled with extreme care. Memory management has been partially abstracted in Zend, and you should stick to this abstraction for obvious reasons: Due to the abstraction, Zend gets full control over all memory allocations. Zend is able to determine whether a block is in use, automatically freeing unused blocks and blocks with lost references, and thus prevent memory leaks. The functions to be used are described in the following table:

Function | Description
emalloc() | Serves as replacement for malloc().
efree() | Serves as replacement for free().
estrdup() | Serves as replacement for strdup().
estrndup() | Serves as replacement for strndup(). Faster than estrdup() and binary-safe. This is the recommended function to use if you know the string length prior to duplicating it.
ecalloc() | Serves as replacement for calloc().
erealloc() | Serves as replacement for realloc().
emalloc(), estrdup(), estrndup(), ecalloc(), and erealloc() allocate internal memory; efree() frees these previously allocated blocks. Memory handled by the e*() functions is considered local to the current process and is discarded as soon as the script executed by this process is terminated.
Warning

To allocate resident memory that survives termination of the current script, you can use malloc() and free(). This should only be done with extreme care, however, and only in conjunction with demands of the Zend API; otherwise, you risk memory leaks.

Zend also features a thread-safe resource manager to provide better native support for multithreaded Web servers. This requires you to allocate local structures for all of your global variables to allow concurrent threads to be run. Because the thread-safe mode of Zend was not finished back when this was written, it is not yet extensively covered here.

Directory and File Functions

The following directory and file functions should be used in Zend modules. They behave exactly like their C counterparts, but provide virtual working directory support on the thread level.

Zend Function | Regular C Function
V_GETCWD() | getcwd()
V_FOPEN() | fopen()
V_OPEN() | open()
V_CHDIR() | chdir()
V_GETWD() | getwd()
V_CHDIR_FILE() | Takes a file path as an argument and changes the current working directory to that file's directory.
V_STAT() | stat()
V_LSTAT() | lstat()

String Handling

Strings are handled a bit differently by the Zend engine than other values such as integers, Booleans, etc., which don't require additional memory allocation for storing their values. If you want to return a string from a function, introduce a new string variable to the symbol table, or do something similar, you have to make sure that the memory the string will be occupying has previously been allocated, using the aforementioned e*() functions for allocation. (This might not make much sense to you yet; just keep it somewhere in your head for now - we'll get back to it shortly.)

Complex Types

Complex types such as arrays and objects require different treatment. Zend features a single API for these types - they're stored using hash tables.

Note:

To reduce complexity in the following source examples, we're only working with simple types such as integers at first. A discussion about creating more advanced types follows later in this chapter.

PHP's Automatic Build System

PHP 4 features an automatic build system that's very flexible. All modules reside in a subdirectory of the ext directory. In addition to its own sources, each module consists of a config.m4 file, for extension configuration. (for example, see » http://www.gnu.org/software/m4/)

All these stub files are generated automatically, along with .cvsignore, by a little shell script named ext_skel that resides in the ext directory. As argument it takes the name of the module that you want to create. The shell script then creates a directory of the same name, along with the appropriate stub files.

Step by step, the process looks like this:

:~/cvs/php4/ext:> ./ext_skel --extname=my_module
Creating directory my_module
Creating basic files: config.m4 .cvsignore my_module.c php_my_module.h CREDITS EXPERIMENTAL tests/001.phpt my_module.php [done].

To use your new extension, you will have to execute the following steps:

1.  $ cd ..
2.  $ vi ext/my_module/config.m4
3.  $ ./buildconf
4.  $ ./configure --[with|enable]-my_module
5.  $ make
6.  $ ./php -f ext/my_module/my_module.php
7.  $ vi ext/my_module/my_module.c
8.  $ make

Repeat steps 3-6 until you are satisfied with ext/my_module/config.m4 and
step 6 confirms that your module is compiled into PHP. Then, start writing
code and repeat the last two steps as often as necessary.
This instruction creates the aforementioned files. To include the new module in the automatic configuration and build process, you have to run buildconf, which regenerates the configure script by searching through the ext directory and including all found config.m4 files.

The default config.m4 shown in The default config.m4. is a bit more complex:

Example #1 The default config.m4.

dnl config.m4 for extension my_module

dnl Comments in this file start with the string 'dnl'.
dnl Remove where necessary. This file will not work
dnl without editing.

dnl If your extension references something external, use with:

dnl PHP_ARG_WITH(my_module, for my_module support,
dnl Make sure that the comment is aligned:
dnl [  --with-my_module             Include my_module support])

dnl Otherwise use enable:

dnl PHP_ARG_ENABLE(my_module, whether to enable my_module support,
dnl Make sure that the comment is aligned:
dnl [  --enable-my_module           Enable my_module support])

if test "$PHP_MY_MODULE" != "no"; then
  dnl Write more examples of tests here...

  dnl # --with-my_module -> check with-path
  dnl SEARCH_PATH="/usr/local /usr"     # you might want to change this
  dnl SEARCH_FOR="/include/my_module.h"  # you most likely want to change this
  dnl if test -r $PHP_MY_MODULE/; then # path given as parameter
  dnl   MY_MODULE_DIR=$PHP_MY_MODULE
  dnl else # search default path list
  dnl   AC_MSG_CHECKING([for my_module files in default path])
  dnl   for i in $SEARCH_PATH ; do
  dnl     if test -r $i/$SEARCH_FOR; then
  dnl       MY_MODULE_DIR=$i
  dnl       AC_MSG_RESULT(found in $i)
  dnl     fi
  dnl   done
  dnl fi
  dnl
  dnl if test -z "$MY_MODULE_DIR"; then
  dnl   AC_MSG_RESULT([not found])
  dnl   AC_MSG_ERROR([Please reinstall the my_module distribution])
  dnl fi

  dnl # --with-my_module -> add include path
  dnl PHP_ADD_INCLUDE($MY_MODULE_DIR/include)

  dnl # --with-my_module -> chech for lib and symbol presence
  dnl LIBNAME=my_module # you may want to change this
  dnl LIBSYMBOL=my_module # you most likely want to change this

  dnl PHP_CHECK_LIBRARY($LIBNAME,$LIBSYMBOL,
  dnl [
  dnl   PHP_ADD_LIBRARY_WITH_PATH($LIBNAME, $MY_MODULE_DIR/lib, MY_MODULE_SHARED_LIBADD)
  dnl   AC_DEFINE(HAVE_MY_MODULELIB,1,[ ])
  dnl ],[
  dnl   AC_MSG_ERROR([wrong my_module lib version or lib not found])
  dnl ],[
  dnl   -L$MY_MODULE_DIR/lib -lm -ldl
  dnl ])
  dnl
  dnl PHP_SUBST(MY_MODULE_SHARED_LIBADD)

  PHP_NEW_EXTENSION(my_module, my_module.c, $ext_shared)
fi

If you're unfamiliar with M4 files (now is certainly a good time to get familiar), this might be a bit confusing at first; but it's actually quite easy.

Note: Everything prefixed with dnl is treated as a comment and is not parsed.

The config.m4 file is responsible for parsing the command-line options passed to configure at configuration time. This means that it has to check for required external files and do similar configuration and setup tasks.

The default file creates two configuration directives in the configure script: --with-my_module and --enable-my_module. Use the first option when referring external files (such as the --with-apache directive that refers to the Apache directory). Use the second option when the user simply has to decide whether to enable your extension. Regardless of which option you use, you should uncomment the other, unnecessary one; that is, if you're using --enable-my_module, you should remove support for --with-my_module, and vice versa.

By default, the config.m4 file created by ext_skel accepts both directives and automatically enables your extension. Enabling the extension is done by using the PHP_EXTENSION macro. To change the default behavior to include your module into the PHP binary when desired by the user (by explicitly specifying --enable-my_module or --with-my_module), change the test for $PHP_MY_MODULE to == "yes":

if test "$PHP_MY_MODULE" == "yes"; then dnl
    Action.. PHP_EXTENSION(my_module, $ext_shared)
    fi
This would require you to use --enable-my_module each time when reconfiguring and recompiling PHP.

Note: Be sure to run buildconf every time you change config.m4!

We'll go into more details on the M4 macros available to your configuration scripts later in this chapter. For now, we'll simply use the default files.

Creating Extensions

We'll start with the creation of a very simple extension at first, which basically does nothing more than implement a function that returns the integer it receives as parameter. A simple extension. shows the source.

Example #2 A simple extension.

/* include standard header */
#include "php.h"

/* declaration of functions to be exported */
ZEND_FUNCTION(first_module);

/* compiled function list so Zend knows what's in this module */
zend_function_entry firstmod_functions[] =
{
    ZEND_FE(first_module, NULL)
    ZEND_FE_END
};

/* compiled module information */
zend_module_entry firstmod_module_entry =
{
    STANDARD_MODULE_HEADER,
    "First Module",
    firstmod_functions,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NO_VERSION_YET,
    STANDARD_MODULE_PROPERTIES
};

/* implement standard "stub" routine to introduce ourselves to Zend */
#if COMPILE_DL_FIRST_MODULE
ZEND_GET_MODULE(firstmod)
#endif

/* implement function that is meant to be made available to PHP */
ZEND_FUNCTION(first_module)
{
    long parameter;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &parameter) == FAILURE) {
        return;
    }

    RETURN_LONG(parameter);
}

This code contains a complete PHP module. We'll explain the source code in detail shortly, but first we'd like to discuss the build process. (This will allow the impatient to experiment before we dive into API discussions.)

Note:

The example source makes use of some features introduced with the Zend version used in PHP 4.1.0 and above, it won't compile with older PHP 4.0.x versions.

Compiling Modules

There are basically two ways to compile modules:

  • Use the provided "make" mechanism in the ext directory, which also allows building of dynamic loadable modules.

  • Compile the sources manually.

The first method should definitely be favored, since, as of PHP 4.0, this has been standardized into a sophisticated build process. The fact that it is so sophisticated is also its drawback, unfortunately - it's hard to understand at first. We'll provide a more detailed introduction to this later in the chapter, but first let's work with the default files.

The second method is good for those who (for some reason) don't have the full PHP source tree available, don't have access to all files, or just like to juggle with their keyboard. These cases should be extremely rare, but for the sake of completeness we'll also describe this method.

Compiling Using Make

To compile the sample sources using the standard mechanism, copy all their subdirectories to the ext directory of your PHP source tree. Then run buildconf, which will create an updated configure script containing appropriate options for the new extension. By default, all the sample sources are disabled, so you don't have to fear breaking your build process.

After you run buildconf, configure --help shows the following additional modules:

  --enable-array_experiments   BOOK: Enables array experiments
  --enable-call_userland       BOOK: Enables userland module
  --enable-cross_conversion    BOOK: Enables cross-conversion module
  --enable-first_module        BOOK: Enables first module
  --enable-infoprint           BOOK: Enables infoprint module
  --enable-reference_test      BOOK: Enables reference test module
  --enable-resource_test       BOOK: Enables resource test module
  --enable-variable_creation   BOOK: Enables variable-creation module

The module shown earlier in A simple extension. can be enabled with --enable-first_module or --enable-first_module=yes.

Compiling Manually

To compile your modules manually, you need the following commands:

Action | Command
Compiling | cc -fpic -DCOMPILE_DL_FIRST_MODULE=1 -I/usr/local/include -I. -I.. -I../Zend -c -o <your_object_file> <your_c_file>
Linking | cc -shared -L/usr/local/lib -rdynamic -o <your_module_file> <your_object_file(s)>
The command to compile the module simply instructs the compiler to generate position-independent code (-fpic shouldn't be omitted) and additionally defines the constant COMPILE_DL_FIRST_MODULE to tell the module code that it's compiled as a dynamically loadable module (the test module above checks for this; we'll discuss it shortly). After these options, it specifies a number of standard include paths that should be used as the minimal set to compile the source files.

Note: All include paths in the example are relative to the directory ext. If you're compiling from another directory, change the pathnames accordingly. Required items are the PHP directory, the Zend directory, and (if necessary), the directory in which your module resides.

The link command is also a plain vanilla command instructing linkage as a dynamic module.

You can include optimization options in the compilation command, although these have been omitted in this example (but some are included in the makefile template described in an earlier section).

Note: Compiling and linking manually as a static module into the PHP binary involves very long instructions and thus is not discussed here. (It's not very efficient to type all those commands.)

Using Extensions

Depending on the build process you selected, you should either end up with a new PHP binary to be linked into your Web server (or run as CGI), or with an .so (shared object) file. If you compiled the example file first_module.c as a shared object, your result file should be first_module.so. To use it, you first have to copy it to a place from which it's accessible to PHP. For a simple test procedure, you can copy it to your htdocs directory and try it with the source in A test file for first_module.so.. If you compiled it into the PHP binary, omit the call to dl(), as the module's functionality is instantly available to your scripts.

Warning

For security reasons, you should not put your dynamic modules into publicly accessible directories. Even though it can be done and it simplifies testing, you should put them into a separate directory in production environments.

Example #3 A test file for first_module.so.

<?php

// remove next comment if necessary
// dl("first_module.so");

$param = 2;
$return = first_module($param);

print("We sent '$param' and got '$return'");

?>

Calling this PHP file should output the following:

We sent '2' and got '2'

If required, the dynamic loadable module is loaded by calling the dl() function. This function looks for the specified shared object, loads it, and makes its functions available to PHP. The module exports the function first_module(), which accepts a single parameter, converts it to an integer, and returns the result of the conversion.

If you've gotten this far, congratulations! You just built your first extension to PHP.

Troubleshooting

Actually, not much troubleshooting can be done when compiling static or dynamic modules. The only problem that could arise is that the compiler will complain about missing definitions or something similar. In this case, make sure that all header files are available and that you specified their path correctly in the compilation command. To be sure that everything is located correctly, extract a clean PHP source tree and use the automatic build in the ext directory with the fresh files; this will guarantee a safe compilation environment. If this fails, try manual compilation.

PHP might also complain about missing functions in your module. (This shouldn't happen with the sample sources if you didn't modify them.) If the names of external functions you're trying to access from your module are misspelled, they'll remain as "unlinked symbols" in the symbol table. During dynamic loading and linkage by PHP, they won't resolve because of the typing errors - there are no corresponding symbols in the main binary. Look for incorrect declarations in your module file or incorrectly written external references. Note that this problem is specific to dynamic loadable modules; it doesn't occur with static modules. Errors in static modules show up at compile time.

Source Discussion

Now that you've got a safe build environment and you're able to include the modules into PHP files, it's time to discuss how everything works.

Module Structure

All PHP modules follow a common structure:

  • Header file inclusions (to include all required macros, API definitions, etc.)

  • C declaration of exported functions (required to declare the Zend function block)

  • Declaration of the Zend function block

  • Declaration of the Zend module block

  • Implementation of get_module()

  • Implementation of all exported functions

Header File Inclusions

The only header file you really have to include for your modules is php.h, located in the PHP directory. This file makes all macros and API definitions required to build new modules available to your code.

Tip: It's good practice to create a separate header file for your module that contains module-specific definitions. This header file should contain all the forward definitions for exported functions and include php.h. If you created your module using ext_skel you already have such a header file prepared.

Declaring Exported Functions

To declare functions that are to be exported (i.e., made available to PHP as new native functions), Zend provides a set of macros. A sample declaration looks like this:

ZEND_FUNCTION ( my_function );

ZEND_FUNCTION declares a new C function that complies with Zend's internal API. This means that the function is of type void and accepts INTERNAL_FUNCTION_PARAMETERS (another macro) as parameters. Additionally, it prefixes the function name with zif. The immediately expanded version of the above definitions would look like this:

void zif_my_function ( INTERNAL_FUNCTION_PARAMETERS );
Expanding INTERNAL_FUNCTION_PARAMETERS results in the following:
void zif_my_function( int ht
                    , zval * return_value
                    , zval * this_ptr
                    , int return_value_used
                    , zend_executor_globals * executor_globals
                    );

Since the interpreter and executor core have been separated from the main PHP package, a second API defining macros and function sets has evolved: the Zend API. As the Zend API now handles quite a few of the responsibilities that previously belonged to PHP, a lot of PHP functions have been reduced to macros aliasing to calls into the Zend API. The recommended practice is to use the Zend API wherever possible, as the old API is only preserved for compatibility reasons. For example, the types zval and pval are identical. zval is Zend's definition; pval is PHP's definition (actually, pval is an alias for zval now). As the macro INTERNAL_FUNCTION_PARAMETERS is a Zend macro, the above declaration contains zval. When writing code, you should always use zval to conform to the new Zend API.

The parameter list of this declaration is very important; you should keep these parameters in mind (see Zend's Parameters to Functions Called from PHP for descriptions).

Zend's Parameters to Functions Called from PHP
Parameter | Description
ht | The number of arguments passed to the Zend function. You should not touch this directly, but instead use ZEND_NUM_ARGS() to obtain the value.
return_value | This variable is used to pass any return values of your function back to PHP. Access to this variable is best done using the predefined macros. For a description of these see below.
this_ptr | Using this variable, you can gain access to the object in which your function is contained, if it's used within an object. Use the function getThis() to obtain this pointer.
return_value_used | This flag indicates whether an eventual return value from this function will actually be used by the calling script. 0 indicates that the return value is not used; 1 indicates that the caller expects a return value. Evaluation of this flag can be done to verify correct usage of the function as well as speed optimizations in case returning a value requires expensive operations (for an example, see how array.c makes use of this).
executor_globals | This variable points to global settings of the Zend engine. You'll find this useful when creating new variables, for example (more about this later). The executor globals can also be introduced to your function by using the macro TSRMLS_FETCH().

Declaration of the Zend Function Block

Now that you have declared the functions to be exported, you also have to introduce them to Zend. Introducing the list of functions is done by using an array of zend_function_entry. This array consecutively contains all functions that are to be made available externally, with the function's name as it should appear in PHP and its name as defined in the C source. Internally, zend_function_entry is defined as shown in Internal declaration of zend_function_entry..

Example #4 Internal declaration of zend_function_entry.

typedef struct _zend_function_entry {
    char *fname;
    void (*handler)(INTERNAL_FUNCTION_PARAMETERS);
    unsigned char *func_arg_types;
} zend_function_entry;
Entry | Description
fname | Denotes the function name as seen in PHP (for example, fopen, mysql_connect, or, in our example, first_module).
handler | Pointer to the C function responsible for handling calls to this function. For example, see the standard macro INTERNAL_FUNCTION_PARAMETERS discussed earlier.
func_arg_types | Allows you to mark certain parameters so that they're forced to be passed by reference. You usually should set this to NULL.
In the example above, the declaration looks like this:
zend_function_entry firstmod_functions[] =
{
    ZEND_FE(first_module, NULL)
    ZEND_FE_END
};
You can see that the last entry in the list always has to be ZEND_FE_END. This marker has to be set for Zend to know when the end of the list of exported functions is reached.

The macro ZEND_FE (short for 'Zend Function Entry') simply expands to a structure entry in zend_function_entry. Note that these macros introduce a special naming scheme to your functions - your C functions will be prefixed with zif_, meaning that ZEND_FE(first_module) will refer to a C function zif_first_module(). If you want to mix macro usage with hand-coded entries (not a good practice), keep this in mind.

Tip: Compilation errors that refer to functions named zif_*() relate to functions defined with ZEND_FE.

Macros for Defining Functions shows a list of all the macros that you can use to define functions.

Macros for Defining Functions
Macro Name | Description
ZEND_FE(name, arg_types) | Defines a function entry of the name name in zend_function_entry. Requires a corresponding C function. arg_types needs to be set to NULL. This function uses automatic C function name generation by prefixing the PHP function name with zif_. For example, ZEND_FE("first_module", NULL) introduces a function first_module() to PHP and links it to the C function zif_first_module(). Use in conjunction with ZEND_FUNCTION.
ZEND_NAMED_FE(php_name, name, arg_types) | Defines a function that will be available to PHP by the name php_name and links it to the corresponding C function name. arg_types needs to be set to NULL. Use this function if you don't want the automatic name prefixing introduced by ZEND_FE. Use in conjunction with ZEND_NAMED_FUNCTION.
ZEND_FALIAS(name, alias, arg_types) | Defines an alias named alias for name. arg_types needs to be set to NULL. Doesn't require a corresponding C function; refers to the alias target instead.
PHP_FE(name, arg_types) | Old PHP API equivalent of ZEND_FE.
PHP_NAMED_FE(runtime_name, name, arg_types) | Old PHP API equivalent of ZEND_NAMED_FE.

Note: You can't use ZEND_FE in conjunction with PHP_FUNCTION, or PHP_FE in conjunction with ZEND_FUNCTION. However, it's perfectly legal to mix ZEND_FE and ZEND_FUNCTION with PHP_FE and PHP_FUNCTION when staying with the same macro set for each function to be declared. But mixing is not recommended; instead, you're advised to use the ZEND_* macros only.

Declaration of the Zend Module Block

This block is stored in the structure zend_module_entry and contains all necessary information to describe the contents of this module to Zend. You can see the internal definition of this module in Internal declaration of zend_module_entry..

Example #5 Internal declaration of zend_module_entry.

typedef struct _zend_module_entry zend_module_entry;

    struct _zend_module_entry {
    unsigned short size;
    unsigned int zend_api;
    unsigned char zend_debug;
    unsigned char zts;
    char *name;
    zend_function_entry *functions;
    int (*module_startup_func)(INIT_FUNC_ARGS);
    int (*module_shutdown_func)(SHUTDOWN_FUNC_ARGS);
    int (*request_startup_func)(INIT_FUNC_ARGS);
    int (*request_shutdown_func)(SHUTDOWN_FUNC_ARGS);
    void (*info_func)(ZEND_MODULE_INFO_FUNC_ARGS);
    char *version;

[ Rest of the structure is not interesting here ]

};
Entry | Description
size, zend_api, zend_debug and zts | Usually filled with the "STANDARD_MODULE_HEADER", which fills these four members with the size of the whole zend_module_entry, the ZEND_MODULE_API_NO, whether it is a debug build or normal build (ZEND_DEBUG) and if ZTS is enabled (USING_ZTS).
name | Contains the module name (for example, "File functions", "Socket functions", "Crypt", etc.). This name will show up in phpinfo(), in the section "Additional Modules."
functions | Points to the Zend function block, discussed in the preceding section.
module_startup_func | This function is called once upon module initialization and can be used to do one-time initialization steps (such as initial memory allocation, etc.). To indicate a failure during initialization, return FAILURE; otherwise, SUCCESS. To mark this field as unused, use NULL. To declare a function, use the macro ZEND_MINIT.
module_shutdown_func | This function is called once upon module shutdown and can be used to do one-time deinitialization steps (such as memory deallocation). This is the counterpart to module_startup_func(). To indicate a failure during deinitialization, return FAILURE; otherwise, SUCCESS. To mark this field as unused, use NULL. To declare a function, use the macro ZEND_MSHUTDOWN.
request_startup_func | This function is called once upon every page request and can be used to do one-time initialization steps that are required to process a request. To indicate a failure here, return FAILURE; otherwise, SUCCESS. Note: As dynamic loadable modules are loaded only on page requests, the request startup function is called right after the module startup function (both initialization events happen at the same time). To mark this field as unused, use NULL. To declare a function, use the macro ZEND_RINIT.
request_shutdown_func | This function is called once after every page request and works as counterpart to request_startup_func(). To indicate a failure here, return FAILURE; otherwise, SUCCESS. Note: As dynamic loadable modules are loaded only on page requests, the request shutdown function is immediately followed by a call to the module shutdown handler (both deinitialization events happen at the same time). To mark this field as unused, use NULL. To declare a function, use the macro ZEND_RSHUTDOWN.
info_func | When phpinfo() is called in a script, Zend cycles through all loaded modules and calls this function. Every module then has the chance to print its own "footprint" into the output page. Generally this is used to dump environmental or statistical information. To mark this field as unused, use NULL. To declare a function, use the macro ZEND_MINFO.
version | The version of the module. You can use NO_VERSION_YET if you don't want to give the module a version number yet, but we really recommend that you add a version string here. Such a version string can look like this (in chronological order): "2.5-dev", "2.5RC1", "2.5" or "2.5pl3".
Remaining structure elements | These are used internally and can be prefilled by using the macro STANDARD_MODULE_PROPERTIES_EX. You should not assign any values to them. Use STANDARD_MODULE_PROPERTIES_EX only if you use global startup and shutdown functions; otherwise, use STANDARD_MODULE_PROPERTIES directly.

In our example, this structure is implemented as follows:

zend_module_entry firstmod_module_entry =
{
    STANDARD_MODULE_HEADER,
    "First Module",
    firstmod_functions,
    NULL, NULL, NULL, NULL, NULL,
    NO_VERSION_YET,
    STANDARD_MODULE_PROPERTIES,
};
This is basically the easiest and most minimal set of values you could ever use. The module name is set to First Module, then the function list is referenced, after which all startup and shutdown functions are marked as being unused.

For reference purposes, you can find a list of the macros involved in declared startup and shutdown functions in Macros to Declare Startup and Shutdown Functions. These are not used in our basic example yet, but will be demonstrated later on. You should make use of these macros to declare your startup and shutdown functions, as these require special arguments to be passed (INIT_FUNC_ARGS and SHUTDOWN_FUNC_ARGS), which are automatically included into the function declaration when using the predefined macros. If you declare your functions manually and the PHP developers decide that a change in the argument list is necessary, you'll have to change your module sources to remain compatible.

Macros to Declare Startup and Shutdown Functions
Macro | Description
ZEND_MINIT(module) | Declares a function for module startup. The generated name will be zend_minit_<module> (for example, zend_minit_first_module). Use in conjunction with ZEND_MINIT_FUNCTION.
ZEND_MSHUTDOWN(module) | Declares a function for module shutdown. The generated name will be zend_mshutdown_<module> (for example, zend_mshutdown_first_module). Use in conjunction with ZEND_MSHUTDOWN_FUNCTION.
ZEND_RINIT(module) | Declares a function for request startup. The generated name will be zend_rinit_<module> (for example, zend_rinit_first_module). Use in conjunction with ZEND_RINIT_FUNCTION.
ZEND_RSHUTDOWN(module) | Declares a function for request shutdown. The generated name will be zend_rshutdown_<module> (for example, zend_rshutdown_first_module). Use in conjunction with ZEND_RSHUTDOWN_FUNCTION.
ZEND_MINFO(module) | Declares a function for printing module information, used when phpinfo() is called. The generated name will be zend_info_<module> (for example, zend_info_first_module). Use in conjunction with ZEND_MINFO_FUNCTION.

Creation of get_module()

This function is special to all dynamic loadable modules. Take a look at the creation via the ZEND_GET_MODULE macro first:

#if COMPILE_DL_FIRSTMOD
     ZEND_GET_MODULE(firstmod)
#endif

The function implementation is surrounded by a conditional compilation statement. This is needed since the function get_module() is only required if your module is built as a dynamic extension. By specifying a definition of COMPILE_DL_FIRSTMOD in the compiler command (see above for a discussion of the compilation instructions required to build a dynamic extension), you can instruct your module whether you intend to build it as a dynamic extension or as a built-in module. If you want a built-in module, the implementation of get_module() is simply left out.

get_module() is called by Zend at load time of the module. You can think of it as being invoked by the dl() call in your script. Its purpose is to pass the module information block back to Zend in order to inform the engine about the module contents.

If you don't implement a get_module() function in your dynamic loadable module, Zend will compliment you with an error message when trying to access it.

Implementation of All Exported Functions

Implementing the exported functions is the final step. The example function in first_module looks like this:

ZEND_FUNCTION(first_module)
{
    long parameter;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &parameter) == FAILURE) {
        return;
    }

    RETURN_LONG(parameter);
}
The function declaration is done using ZEND_FUNCTION, which corresponds to ZEND_FE in the function entry table (discussed earlier).

After the declaration, code for checking and retrieving the function's arguments, argument conversion, and return value generation follows (more on this later).

Summary

That's it, basically - there's nothing more to implementing PHP modules. Built-in modules are structured similarly to dynamic modules, so, equipped with the information presented in the previous sections, you'll be able to fight the odds when encountering PHP module source files.

Now, in the following sections, read on about how to make use of PHP's internals to build powerful extensions.

Accepting Arguments

One of the most important issues for language extensions is accepting and dealing with data passed via arguments. Most extensions are built to deal with specific input data (or require parameters to perform their specific actions), and function arguments are the only real way to exchange data between the PHP level and the C level. Of course, there's also the possibility of exchanging data using predefined global values (which is also discussed later), but this should be avoided by all means, as it's extremely bad practice.

PHP doesn't make use of any formal function declarations; this is why call syntax is always completely dynamic and never checked for errors. Checking for correct call syntax is left to the user code. For example, it's possible to call a function using only one argument at one time and four arguments the next time - both invocations are syntactically absolutely correct.

Determining the Number of Arguments

Since PHP doesn't have formal function definitions with support for call syntax checking, and since PHP features variable arguments, sometimes you need to find out with how many arguments your function has been called. You can use the ZEND_NUM_ARGS macro in this case. In previous versions of PHP, this macro retrieved the number of arguments with which the function has been called based on the function's hash table entry, ht, which is passed in the INTERNAL_FUNCTION_PARAMETERS list. As ht itself now contains the number of arguments that have been passed to the function, ZEND_NUM_ARGS has been stripped down to a dummy macro (see its definition in zend_API.h). But it's still good practice to use it, to remain compatible with future changes in the call interface. Note: The old PHP equivalent of this macro is ARG_COUNT.

The following code checks for the correct number of arguments:

if(ZEND_NUM_ARGS() != 2) WRONG_PARAM_COUNT;
If the function is not called with two arguments, it exits with an error message. The code snippet above makes use of the tool macro WRONG_PARAM_COUNT, which can be used to generate a standard error message like:
"Warning: Wrong parameter count for firstmodule() in /home/www/htdocs/firstmod.php on line 5"

This macro prints a default error message and then returns to the caller. Its definition can also be found in zend_API.h and looks like this:

ZEND_API void wrong_param_count(void);

#define WRONG_PARAM_COUNT { wrong_param_count(); return; }
As you can see, it calls an internal function named wrong_param_count() that's responsible for printing the warning. For details on generating customized error messages, see the later section "Printing Information."

Retrieving Arguments

Note: New parameter parsing API

This chapter documents the new Zend parameter parsing API introduced by Andrei Zmievski. It was introduced in the development stage between PHP 4.0.6 and 4.1.0.

Parsing parameters is a very common operation and it may get a bit tedious. It would also be nice to have standardized error checking and error messages. Since PHP 4.1.0, there is a way to do just that by using the new parameter parsing API. It greatly simplifies the process of receiving parameters, but it has a drawback in that it can't be used for functions that expect variable number of parameters. But since the vast majority of functions do not fall into those categories, this parsing API is recommended as the new standard way.

The prototype for parameter parsing function looks like this:

int zend_parse_parameters(int num_args TSRMLS_DC, char *type_spec, ...);
The first argument to this function is supposed to be the number of actual parameters passed to your function, so ZEND_NUM_ARGS() can be used for that. The second parameter should always be TSRMLS_CC macro. The third argument is a string that specifies the number and types of arguments your function is expecting, similar to how printf format string specifies the number and format of the output values it should operate on. And finally the rest of the arguments are pointers to variables which should receive the values from the parameters.

zend_parse_parameters() also performs type conversions whenever possible, so that you always receive the data in the format you asked for. Any type of scalar can be converted to another one, but conversions between complex types (arrays, objects, and resources) and scalar types are not allowed.

If the parameters could be obtained successfully and there were no errors during type conversion, the function will return SUCCESS, otherwise it will return FAILURE. The function will output informative error messages, if the number of received parameters does not match the requested number, or if type conversion could not be performed.

Here are some sample error messages:

Warning - ini_get_all() requires at most 1 parameter, 2 given
Warning - wddx_deserialize() expects parameter 1 to be string, array given
Of course each error message is accompanied by the filename and line number on which it occurs.

Here is the full list of type specifiers:

  • l - long

  • d - double

  • s - string (with possible null bytes) and its length

  • b - boolean

  • r - resource, stored in zval*

  • a - array, stored in zval*

  • o - object (of any class), stored in zval*

  • O - object (of class specified by class entry), stored in zval*

  • z - the actual zval*

The following characters also have a meaning in the specifier string:

  • | - indicates that the remaining parameters are optional. The storage variables corresponding to these parameters should be initialized to default values by the extension, since they will not be touched by the parsing function if the parameters are not passed.

  • / - the parsing function will call SEPARATE_ZVAL_IF_NOT_REF() on the parameter it follows, to provide a copy of the parameter, unless it's a reference.

  • ! - the parameter it follows can be of specified type or NULL (only applies to a, o, O, r, and z). If NULL value is passed by the user, the storage pointer will be set to NULL.

The best way to illustrate the usage of this function is through examples:

/* Gets a long, a string and its length, and a zval. */
long l;
char *s;
int s_len;
zval *param;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC,
                          "lsz", &l, &s, &s_len, &param) == FAILURE) {
    return;
}

/* Gets an object of class specified by my_ce, and an optional double. */
zval *obj;
double d = 0.5;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC,
                          "O|d", &obj, my_ce, &d) == FAILURE) {
    return;
}

/* Gets an object or null, and an array.
   If null is passed for object, obj will be set to NULL. */
zval *obj;
zval *arr;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O!a", &obj, &arr) == FAILURE) {
    return;
}

/* Gets a separated array. */
zval *arr;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a/", &arr) == FAILURE) {
    return;
}

/* Get only the first three parameters (useful for varargs functions). */
zval *z;
zend_bool b;
zval *r;
if (zend_parse_parameters(3, "zbr!", &z, &b, &r) == FAILURE) {
    return;
}

Note that in the last example we pass 3 for the number of received parameters, instead of ZEND_NUM_ARGS(). What this lets us do is receive the least number of parameters if our function expects a variable number of them. Of course, if you want to operate on the rest of the parameters, you will have to use zend_get_parameters_array_ex() to obtain them.

The parsing function has an extended version that allows for an additional flags argument that controls its actions.

int zend_parse_parameters_ex(int flags, int num_args TSRMLS_DC, char *type_spec, ...);

The only flag you can pass currently is ZEND_PARSE_PARAMS_QUIET, which instructs the function to not output any error messages during its operation. This is useful for functions that expect several sets of completely different arguments, but you will have to output your own error messages.

For example, here is how you would get either a set of three longs or a string:

long l1, l2, l3;
char *s;
if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET,
                             ZEND_NUM_ARGS() TSRMLS_CC,
                             "lll", &l1, &l2, &l3) == SUCCESS) {
    /* manipulate longs */
} else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET,
                                    ZEND_NUM_ARGS(), "s", &s, &s_len) == SUCCESS) {
    /* manipulate string */
} else {
    php_error(E_WARNING, "%s() takes either three long values or a string as argument",
              get_active_function_name(TSRMLS_C));
    return;
}

With all the abovementioned ways of receiving function parameters you should have a good handle on this process. For even more example, look through the source code for extensions that are shipped with PHP - they illustrate every conceivable situation.

Old way of retrieving arguments (deprecated)

Note: Deprecated parameter parsing API

This API is deprecated and superseded by the new ZEND parameter parsing API.

After having checked the number of arguments, you need to get access to the arguments themselves. This is done with the help of zend_get_parameters_ex():

zval **parameter;

if(zend_get_parameters_ex(1, &parameter) != SUCCESS)
  WRONG_PARAM_COUNT;
All arguments are stored in a zval container, which needs to be pointed to twice. The snippet above tries to retrieve one argument and make it available to us via the parameter pointer.

zend_get_parameters_ex() accepts at least two arguments. The first argument is the number of arguments to retrieve (which should match the number of arguments with which the function has been called; this is why it's important to check for correct call syntax). The second argument (and all following arguments) are pointers to pointers to pointers to zvals. (Confusing, isn't it?) All these pointers are required because Zend works internally with **zval; to adjust a local **zval in our function,zend_get_parameters_ex() requires a pointer to it.

The return value of zend_get_parameters_ex() can either be SUCCESS or FAILURE, indicating (unsurprisingly) success or failure of the argument processing. A failure is most likely related to an incorrect number of arguments being specified, in which case you should exit with WRONG_PARAM_COUNT.

To retrieve more than one argument, you can use a similar snippet:

zval **param1, **param2, **param3, **param4;

if(zend_get_parameters_ex(4, &param1, &param2, &param3, &param4) != SUCCESS)
    WRONG_PARAM_COUNT;

zend_get_parameters_ex() only checks whether you're trying to retrieve too many parameters. If the function is called with five arguments, but you're only retrieving three of them with zend_get_parameters_ex(), you won't get an error but will get the first three parameters instead. Subsequent calls of zend_get_parameters_ex() won't retrieve the remaining arguments, but will get the same arguments again.

Dealing with a Variable Number of Arguments/Optional Parameters

If your function is meant to accept a variable number of arguments, the snippets just described are sometimes suboptimal solutions. You have to create a line calling zend_get_parameters_ex() for every possible number of arguments, which is often unsatisfying.

For this case, you can use the function zend_get_parameters_array_ex(), which accepts the number of parameters to retrieve and an array in which to store them:

zval **parameter_array[4];

/* get the number of arguments */
argument_count = ZEND_NUM_ARGS();

/* see if it satisfies our minimal request (2 arguments) */
/* and our maximal acceptance (4 arguments) */
if(argument_count < 2 || argument_count > 4)
    WRONG_PARAM_COUNT;

/* argument count is correct, now retrieve arguments */
if(zend_get_parameters_array_ex(argument_count, parameter_array) != SUCCESS)
    WRONG_PARAM_COUNT;
First, the number of arguments is checked to make sure that it's in the accepted range. After that, zend_get_parameters_array_ex() is used to fill parameter_array with valid pointers to the argument values.

A very clever implementation of this can be found in the code handling PHP's fsockopen() located in ext/standard/fsock.c, as shown in PHP's implementation of variable arguments in fsockopen().. Don't worry if you don't know all the functions used in this source yet; we'll get to them shortly.

Example #6 PHP's implementation of variable arguments in fsockopen().

pval **args[5];
int *sock=emalloc(sizeof(int));
int *sockp;
int arg_count=ARG_COUNT(ht);
int socketd = -1;
unsigned char udp = 0;
struct timeval timeout = { 60, 0 };
unsigned short portno;
unsigned long conv;
char *key = NULL;
FLS_FETCH();

if (arg_count > 5 || arg_count < 2 || zend_get_parameters_array_ex(arg_count,args)==FAILURE) {
    CLOSE_SOCK(1);
    WRONG_PARAM_COUNT;
}

switch(arg_count) {
    case 5:
        convert_to_double_ex(args[4]);
        conv = (unsigned long) (Z_DVAL_PP(args[4]) * 1000000.0);
        timeout.tv_sec = conv / 1000000;
        timeout.tv_usec = conv % 1000000;
        /* fall-through */
    case 4:
        if (!PZVAL_IS_REF(*args[3])) {
            php_error(E_WARNING,"error string argument to fsockopen not passed by reference");
        }
        pval_copy_constructor(*args[3]);
        ZVAL_EMPTY_STRING(*args[3]);
        /* fall-through */
    case 3:
        if (!PZVAL_IS_REF(*args[2])) {
            php_error(E_WARNING,"error argument to fsockopen not passed by reference");
            return;
        }
        ZVAL_LONG(*args[2], 0);
        break;
}

convert_to_string_ex(args[0]);
convert_to_long_ex(args[1]);
portno = (unsigned short) Z_LVAL_P(args[1]);

key = emalloc(Z_STRLEN_P(args[0]) + 10);

fsockopen() accepts two, three, four, or five parameters. After the obligatory variable declarations, the function checks for the correct range of arguments. Then it uses a fall-through mechanism in a switch() statement to deal with all arguments. The switch() statement starts with the maximum number of arguments being passed (five). After that, it automatically processes the case of four arguments being passed, then three, by omitting the otherwise obligatory break keyword in all stages. After having processed the last case, it exits the switch() statement and does the minimal argument processing needed if the function is invoked with only two arguments.

This multiple-stage type of processing, similar to a stairway, allows convenient processing of a variable number of arguments.

Accessing Arguments

To access arguments, it's necessary for each argument to have a clearly defined type. Again, PHP's extremely dynamic nature introduces some quirks. Because PHP never does any kind of type checking, it's possible for a caller to pass any kind of data to your functions, whether you want it or not. If you expect an integer, for example, the caller might pass an array, and vice versa - PHP simply won't notice.

To work around this, you have to use a set of API functions to force a type conversion on every argument that's being passed (see Argument Conversion Functions).

Note: All conversion functions expect a **zval as parameter.

Argument Conversion Functions
Function | Description
convert_to_boolean_ex() | Forces conversion to a Boolean type. Boolean values remain untouched. Longs, doubles, and strings containing 0 as well as NULL values will result in Boolean 0 (FALSE). Arrays and objects are converted based on the number of entries or properties, respectively, that they have. Empty arrays and objects are converted to FALSE; otherwise, to TRUE. All other values result in a Boolean 1 (TRUE).
convert_to_long_ex() | Forces conversion to a long, the default integer type. NULL values, Booleans, resources, and of course longs remain untouched. Doubles are truncated. Strings containing an integer are converted to their corresponding numeric representation, otherwise resulting in 0. Arrays and objects are converted to 0 if empty, 1 otherwise.
convert_to_double_ex() | Forces conversion to a double, the default floating-point type. NULL values, Booleans, resources, longs, and of course doubles remain untouched. Strings containing a number are converted to their corresponding numeric representation, otherwise resulting in 0.0. Arrays and objects are converted to 0.0 if empty, 1.0 otherwise.
convert_to_string_ex() | Forces conversion to a string. Strings remain untouched. NULL values are converted to an empty string. Booleans containing TRUE are converted to "1", otherwise resulting in an empty string. Longs and doubles are converted to their corresponding string representation. Arrays are converted to the string "Array" and objects to the string "Object".
convert_to_array_ex(value) | Forces conversion to an array. Arrays remain untouched. Objects are converted to an array by assigning all their properties to the array table. All property names are used as keys, property contents as values. NULL values are converted to an empty array. All other values are converted to an array that contains the specific source value in the element with the key 0.
convert_to_object_ex(value) | Forces conversion to an object. Objects remain untouched. NULL values are converted to an empty object. Arrays are converted to objects by introducing their keys as properties into the objects and their values as corresponding property contents in the object. All other types result in an object with the property scalar , having the corresponding source value as content.
convert_to_null_ex(value) | Forces the type to become a NULL value, meaning empty.

Note:

You can find a demonstration of the behavior in cross_conversion.php on the accompanying CD-ROM.

Cross-conversion behavior of PHP.

Using these functions on your arguments will ensure type safety for all data that's passed to you. If the supplied type doesn't match the required type, PHP forces dummy contents on the resulting value (empty strings, arrays, or objects, 0 for numeric values, FALSE for Booleans) to ensure a defined state.

Following is a quote from the sample module discussed previously, which makes use of the conversion functions:

zval **parameter;

if((ZEND_NUM_ARGS() != 1) || (zend_get_parameters_ex(1, &parameter) != SUCCESS))
{
    WRONG_PARAM_COUNT;
}

convert_to_long_ex(parameter);

RETURN_LONG(Z_LVAL_P(parameter));
After retrieving the parameter pointer, the parameter value is converted to a long (an integer), which also forms the return value of this function. Understanding access to the contents of the value requires a short discussion of the zval type, whose definition is shown in PHP/Zend zval type definition..

Example #7 PHP/Zend zval type definition.

typedef pval zval;

typedef struct _zval_struct zval;

typedef union _zvalue_value {
    long lval;                 /* long value */
    double dval;               /* double value */
    struct {
        char *val;
        int len;
    } str;
    HashTable *ht;             /* hash table value */
    struct {
        zend_class_entry *ce;
        HashTable *properties;
    } obj;
} zvalue_value;

struct _zval_struct {
    /* Variable information */
    zvalue_value value;        /* value */
    unsigned char type;        /* active type */
    unsigned char is_ref;
    short refcount;
};

Actually, pval (defined in php.h) is only an alias of zval (defined in zend.h), which in turn refers to _zval_struct. This is a most interesting structure. _zval_struct is the "master" structure, containing the value structure, type, and reference information. The substructure zvalue_value is a union that contains the variable's contents. Depending on the variable's type, you'll have to access different members of this union. For a description of both structures, see Zend zval Structure, Zend zvalue_value Structure and Zend Variable Type Constants.

Zend zval Structure
Entry | Description
value | Union containing this variable's contents. See Zend zvalue_value Structure for a description.
type | Contains this variable's type. For a list of available types, see Zend Variable Type Constants.
is_ref | 0 means that this variable is not a reference; 1 means that this variable is a reference to another variable.
refcount | The number of references that exist for this variable. For every new reference to the value stored in this variable, this counter is increased by 1. For every lost reference, this counter is decreased by 1. When the reference counter reaches 0, no references exist to this value anymore, which causes automatic freeing of the value.
Zend zvalue_value Structure
Entry | Description
lval | Use this property if the variable is of the type IS_LONG, IS_BOOLEAN, or IS_RESOURCE.
dval | Use this property if the variable is of the type IS_DOUBLE.
str | This structure can be used to access variables of the type IS_STRING. The member len contains the string length; the member val points to the string itself. Zend uses C strings; thus, the string length contains a trailing 0x00.
ht | This entry points to the variable's hash table entry if the variable is an array.
obj | Use this property if the variable is of the type IS_OBJECT.
Zend Variable Type Constants
Constant | Description
IS_NULL | Denotes a NULL (empty) value.
IS_LONG | A long (integer) value.
IS_DOUBLE | A double (floating point) value.
IS_STRING | A string.
IS_ARRAY | Denotes an array.
IS_OBJECT | An object.
IS_BOOL | A Boolean value.
IS_RESOURCE | A resource (for a discussion of resources, see the appropriate section below).
IS_CONSTANT | A constant (defined) value.

To access a long you access zval.value.lval, to access a double you use zval.value.dval, and so on. Because all values are stored in a union, trying to access data with incorrect union members results in meaningless output.

Accessing arrays and objects is a bit more complicated and is discussed later.

Dealing with Arguments Passed by Reference

If your function accepts arguments passed by reference that you intend to modify, you need to take some precautions.

What we didn't say yet is that under the circumstances presented so far, you don't have write access to any zval containers designating function parameters that have been passed to you. Of course, you can change any zval containers that you created within your function, but you mustn't change any zvals that refer to Zend-internal data!

We've only discussed the so-called *_ex() API so far. You may have noticed that the API functions we've used are called zend_get_parameters_ex() instead of zend_get_parameters(), convert_to_long_ex() instead of convert_to_long(), etc. The *_ex() functions form the so-called new "extended" Zend API. They give a minor speed increase over the old API, but as a tradeoff are only meant for providing read-only access.

Because Zend works internally with references, different variables may reference the same value. Write access to a zval container requires this container to contain an isolated value, meaning a value that's not referenced by any other containers. If a zval container were referenced by other containers and you changed the referenced zval, you would automatically change the contents of the other containers referencing this zval (because they'd simply point to the changed value and thus change their own value as well).

zend_get_parameters_ex() doesn't care about this situation, but simply returns a pointer to the desired zval containers, whether they consist of references or not. Its corresponding function in the traditional API, zend_get_parameters(), immediately checks for referenced values. If it finds a reference, it creates a new, isolated zval container; copies the referenced data into this newly allocated space; and then returns a pointer to the new, isolated value.

This action is called zval separation (or pval separation). Because the *_ex() API doesn't perform zval separation, it's considerably faster, while at the same time disabling write access.

To change parameters, however, write access is required. Zend deals with this situation in a special way: Whenever a parameter to a function is passed by reference, it performs automatic zval separation. This means that whenever you're calling a function like this in PHP, Zend will automatically ensure that $parameter is being passed as an isolated value, rendering it to a write-safe state:

my_function(&$parameter);

But this is not the case with regular parameters! All other parameters that are not passed by reference are in a read-only state.

This requires you to make sure that you're really working with a reference - otherwise you might produce unwanted results. To check for a parameter being passed by reference, you can use the macro PZVAL_IS_REF. This macro accepts a zval* to check if it is a reference or not. Examples are given in in Testing for referenced parameter passing..

Example #8 Testing for referenced parameter passing.

zval *parameter;

if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &parameter) == FAILURE)
    return;

/* check for parameter being passed by reference */
if (!PZVAL_IS_REF(parameter)) {
{
    zend_error(E_WARNING, "Parameter wasn't passed by reference");
    RETURN_NULL();
}

/* make changes to the parameter */
ZVAL_LONG(parameter, 10);
Testing for referenced parameter passing

Assuring Write Safety for Other Parameters

You might run into a situation in which you need write access to a parameter that's retrieved with zend_get_parameters_ex() but not passed by reference. For this case, you can use the macro SEPARATE_ZVAL, which does a zval separation on the provided container. The newly generated zval is detached from internal data and has only a local scope, meaning that it can be changed or destroyed without implying global changes in the script context:

zval **parameter;

/* retrieve parameter */
zend_get_parameters_ex(1, &parameter);

/* at this stage, <parameter> still is connected */
/* to Zend's internal data buffers */

/* make <parameter> write-safe */
SEPARATE_ZVAL(parameter);

/* now we can safely modify <parameter> */
/* without implying global changes */
SEPARATE_ZVAL uses emalloc() to allocate the new zval container, which means that even if you don't deallocate this memory yourself, it will be destroyed automatically upon script termination. However, doing a lot of calls to this macro without freeing the resulting containers will clutter up your RAM.

Note: As you can easily work around the lack of write access in the "traditional" API (with zend_get_parameters() and so on), this API seems to be obsolete, and is not discussed further in this chapter.

Creating Variables

When exchanging data from your own extensions with PHP scripts, one of the most important issues is the creation of variables. This section shows you how to deal with the variable types that PHP supports.

Overview

To create new variables that can be seen "from the outside" by the executing script, you need to allocate a new zval container, fill this container with meaningful values, and then introduce it to Zend's internal symbol table. This basic process is common to all variable creations:

zval *new_variable;

/* allocate and initialize new container */
MAKE_STD_ZVAL(new_variable);

/* set type and variable contents here, see the following sections */

/* introduce this variable by the name "new_variable_name" into the symbol table */
ZEND_SET_SYMBOL(EG(active_symbol_table), "new_variable_name", new_variable);

/* the variable is now accessible to the script by using $new_variable_name */

The macro MAKE_STD_ZVAL allocates a new zval container using ALLOC_ZVAL and initializes it using INIT_ZVAL. As implemented in Zend at the time of this writing, initializing means setting the reference count to 1 and clearing the is_ref flag, but this process could be extended later - this is why it's a good idea to keep using MAKE_STD_ZVAL instead of only using ALLOC_ZVAL. If you want to optimize for speed (and you don't have to explicitly initialize the zval container here), you can use ALLOC_ZVAL, but this isn't recommended because it doesn't ensure data integrity.

ZEND_SET_SYMBOL takes care of introducing the new variable to Zend's symbol table. This macro checks whether the value already exists in the symbol table and converts the new symbol to a reference if so (with automatic deallocation of the old zval container). This is the preferred method if speed is not a crucial issue and you'd like to keep memory usage low.

Note that ZEND_SET_SYMBOL makes use of the Zend executor globals via the macro EG. By specifying EG(active_symbol_table), you get access to the currently active symbol table, dealing with the active, local scope. The local scope may differ depending on whether the function was invoked from within a function.

If you need to optimize for speed and don't care about optimal memory usage, you can omit the check for an existing variable with the same value and instead force insertion into the symbol table by using zend_hash_update():

zval *new_variable;

/* allocate and initialize new container */
MAKE_STD_ZVAL(new_variable);

/* set type and variable contents here, see the following sections */

/* introduce this variable by the name "new_variable_name" into the symbol table */
zend_hash_update(
    EG(active_symbol_table),
    "new_variable_name",
    strlen("new_variable_name") + 1,
    &new_variable,
    sizeof(zval *),
    NULL
);
This is actually the standard method used in most modules.

The variables generated with the snippet above will always be of local scope, so they reside in the context in which the function has been called. To create new variables in the global scope, use the same method but refer to another symbol table:

zval *new_variable;

// allocate and initialize new container
MAKE_STD_ZVAL(new_variable);

//
// set type and variable contents here
//

// introduce this variable by the name "new_variable_name" into the global symbol table
ZEND_SET_SYMBOL(&EG(symbol_table), "new_variable_name", new_variable);
The macro ZEND_SET_SYMBOL is now being called with a reference to the main, global symbol table by referring EG(symbol_table).

Note: The active_symbol_table variable is a pointer, but symbol_table is not. This is why you have to use EG(active_symbol_table) and &EG(symbol_table) as parameters to ZEND_SET_SYMBOL - it requires a pointer.

Similarly, to get a more efficient version, you can hardcode the symbol table update:

zval *new_variable;

// allocate and initialize new container
MAKE_STD_ZVAL(new_variable);

//
// set type and variable contents here
//

// introduce this variable by the name "new_variable_name" into the global symbol table
zend_hash_update(
    &EG(symbol_table),
    "new_variable_name",
    strlen("new_variable_name") + 1,
    &new_variable,
    sizeof(zval *),
    NULL
);
Creating variables with different scopes. shows a sample source that creates two variables - local_variable with a local scope and global_variable with a global scope (see Figure 9.7). The full example can be found on the CD-ROM.

Note: You can see that the global variable is actually not accessible from within the function. This is because it's not imported into the local scope using global $global_variable; in the PHP source.

Example #9 Creating variables with different scopes.

ZEND_FUNCTION(variable_creation)
{
    zval *new_var1, *new_var2;

    MAKE_STD_ZVAL(new_var1);
    MAKE_STD_ZVAL(new_var2);

    ZVAL_LONG(new_var1, 10);
    ZVAL_LONG(new_var2, 5);

    ZEND_SET_SYMBOL(EG(active_symbol_table), "local_variable", new_var1);
    ZEND_SET_SYMBOL(&EG(symbol_table), "global_variable", new_var2);

    RETURN_NULL();

}
Creating variables with different scopes

Longs (Integers)

Now let's get to the assignment of data to variables, starting with longs. Longs are PHP's integers and are very simple to store. Looking at the zval.value container structure discussed earlier in this chapter, you can see that the long data type is directly contained in the union, namely in the lval field. The corresponding type value for longs is IS_LONG (see Creation of a long.).

Example #10 Creation of a long.

zval *new_long;

MAKE_STD_ZVAL(new_long);

new_long-&gt;type = IS_LONG;
new_long-&gt;value.lval = 10;
Alternatively, you can use the macro ZVAL_LONG:
zval *new_long;

MAKE_STD_ZVAL(new_long);
ZVAL_LONG(new_long, 10);

Doubles (Floats)

Doubles are PHP's floats and are as easy to assign as longs, because their value is also contained directly in the union. The member in the zval.value container is dval; the corresponding type is IS_DOUBLE.

zval *new_double;

MAKE_STD_ZVAL(new_double);

new_double-&gt;type = IS_DOUBLE;
new_double-&gt;value.dval = 3.45;
Alternatively, you can use the macro ZVAL_DOUBLE:
zval *new_double;

MAKE_STD_ZVAL(new_double);
ZVAL_DOUBLE(new_double, 3.45);

Strings

Strings need slightly more effort. As mentioned earlier, all strings that will be associated with Zend's internal data structures need to be allocated using Zend's own memory-management functions. Referencing of static strings or strings allocated with standard routines is not allowed. To assign strings, you have to access the structure str in the zval.value container. The corresponding type is IS_STRING:

zval *new_string;
char *string_contents = "This is a new string variable";

MAKE_STD_ZVAL(new_string);

new_string-&gt;type = IS_STRING;
new_string-&gt;value.str.len = strlen(string_contents);
new_string-&gt;value.str.val = estrdup(string_contents);
Note the usage of Zend's estrdup() here. Of course, you can also use the predefined macro ZVAL_STRING:
zval *new_string;
char *string_contents = "This is a new string variable";

MAKE_STD_ZVAL(new_string);
ZVAL_STRING(new_string, string_contents, 1);
ZVAL_STRING accepts a third parameter that indicates whether the supplied string contents should be duplicated (using estrdup()). Setting this parameter to 1 causes the string to be duplicated; 0 simply uses the supplied pointer for the variable contents. This is most useful if you want to create a new variable referring to a string that's already allocated in Zend internal memory.

If you want to truncate the string at a certain position or you already know its length, you can use ZVAL_STRINGL(zval, string, length, duplicate), which accepts an explicit string length to be set for the new string. This macro is faster than ZVAL_STRING and also binary-safe.

To create empty strings, set the string length to 0 and use empty_string as contents:

new_string-&gt;type = IS_STRING;
new_string-&gt;value.str.len = 0;
new_string-&gt;value.str.val = empty_string;
Of course, there's a macro for this as well (ZVAL_EMPTY_STRING):
MAKE_STD_ZVAL(new_string);
ZVAL_EMPTY_STRING(new_string);

Booleans

Booleans are created just like longs, but have the type IS_BOOL. Allowed values in lval are 0 and 1:

zval *new_bool;

MAKE_STD_ZVAL(new_bool);

new_bool-&gt;type = IS_BOOL;
new_bool-&gt;value.lval = 1;
The corresponding macros for this type are ZVAL_BOOL (allowing specification of the value) as well as ZVAL_TRUE and ZVAL_FALSE (which explicitly set the value to TRUE and FALSE, respectively).

Arrays

Arrays are stored using Zend's internal hash tables, which can be accessed using the zend_hash_*() API. For every array that you want to create, you need a new hash table handle, which will be stored in the ht member of the zval.value container.

There's a whole API solely for the creation of arrays, which is extremely handy. To start a new array, you call array_init().

zval *new_array;

MAKE_STD_ZVAL(new_array);

array_init(new_array);
array_init() always returns SUCCESS.

To add new elements to the array, you can use numerous functions, depending on what you want to do. Zend's API for Associative Arrays, Zend's API for Indexed Arrays, Part 1 and Zend's API for Indexed Arrays, Part 2 describe these functions. All functions return FAILURE on failure and SUCCESS on success.

Zend's API for Associative Arrays
Function | Description
add_assoc_long(zval *array, char *key, long n);() | Adds an element of type long.
add_assoc_unset(zval *array, char *key);() | Adds an unset element.
add_assoc_bool(zval *array, char *key, int b);() | Adds a Boolean element.
add_assoc_resource(zval *array, char *key, int r);() | Adds a resource to the array.
add_assoc_double(zval *array, char *key, double d);() | Adds a floating-point value.
add_assoc_string(zval *array, char *key, char *str, int duplicate);() | Adds a string to the array. The flag duplicate specifies whether the string contents have to be copied to Zend internal memory.
add_assoc_stringl(zval *array, char *key, char *str, uint length, int duplicate); () | Adds a string with the desired length length to the array. Otherwise, behaves like add_assoc_string().
add_assoc_zval(zval *array, char *key, zval *value);() | Adds a zval to the array. Useful for adding other arrays, objects, streams, etc...
Zend's API for Indexed Arrays, Part 1
Function | Description
add_index_long(zval *array, uint idx, long n);() | Adds an element of type long.
add_index_unset(zval *array, uint idx);() | Adds an unset element.
add_index_bool(zval *array, uint idx, int b);() | Adds a Boolean element.
add_index_resource(zval *array, uint idx, int r);() | Adds a resource to the array.
add_index_double(zval *array, uint idx, double d);() | Adds a floating-point value.
add_index_string(zval *array, uint idx, char *str, int duplicate);() | Adds a string to the array. The flag duplicate specifies whether the string contents have to be copied to Zend internal memory.
add_index_stringl(zval *array, uint idx, char *str, uint length, int duplicate);() | Adds a string with the desired length length to the array. This function is faster and binary-safe. Otherwise, behaves like add_index_string().
add_index_zval(zval *array, uint idx, zval *value);() | Adds a zval to the array. Useful for adding other arrays, objects, streams, etc...
Zend's API for Indexed Arrays, Part 2
Function | Description
add_next_index_long(zval *array, long n);() | Adds an element of type long.
add_next_index_unset(zval *array);() | Adds an unset element.
add_next_index_bool(zval *array, int b);() | Adds a Boolean element.
add_next_index_resource(zval *array, int r);() | Adds a resource to the array.
add_next_index_double(zval *array, double d);() | Adds a floating-point value.
add_next_index_string(zval *array, char *str, int duplicate);() | Adds a string to the array. The flag duplicate specifies whether the string contents have to be copied to Zend internal memory.
add_next_index_stringl(zval *array, char *str, uint length, int duplicate);() | Adds a string with the desired length length to the array. This function is faster and binary-safe. Otherwise, behaves like add_index_string().
add_next_index_zval(zval *array, zval *value);() | Adds a zval to the array. Useful for adding other arrays, objects, streams, etc...

All these functions provide a handy abstraction to Zend's internal hash API. Of course, you can also use the hash functions directly - for example, if you already have a zval container allocated that you want to insert into an array. This is done using zend_hash_update() for associative arrays (see Adding an element to an associative array.) and zend_hash_index_update() for indexed arrays (see Adding an element to an indexed array.):

Example #11 Adding an element to an associative array.

zval *new_array, *new_element;
char *key = "element_key";

MAKE_STD_ZVAL(new_array);
MAKE_STD_ZVAL(new_element);

array_init(new_array);

ZVAL_LONG(new_element, 10);

if(zend_hash_update(new_array-&gt;value.ht, key, strlen(key) + 1, (void *)&new_element, sizeof(zval *), NULL) == FAILURE)
{
    // do error handling here
}

Example #12 Adding an element to an indexed array.

zval *new_array, *new_element;
int key = 2;

MAKE_STD_ZVAL(new_array);
MAKE_STD_ZVAL(new_element);

array_init(new_array);

ZVAL_LONG(new_element, 10);

if(zend_hash_index_update(new_array-&gt;value.ht, key, (void *)&new_element, sizeof(zval *), NULL) == FAILURE)
{
    // do error handling here
}

To emulate the functionality of add_next_index_*(), you can use this:

zend_hash_next_index_insert(ht, zval **new_element, sizeof(zval *), NULL)

Note: To return arrays from a function, use array_init() and all following actions on the predefined variable return_value (given as argument to your exported function; see the earlier discussion of the call interface). You do not have to use MAKE_STD_ZVAL on this.

Tip: To avoid having to write new_array->value.ht every time, you can use HASH_OF(new_array), which is also recommended for compatibility and style reasons.

Objects

Since objects can be converted to arrays (and vice versa), you might have already guessed that they have a lot of similarities to arrays in PHP. Objects are maintained with the same hash functions, but there's a different API for creating them.

To initialize an object, you use the function object_init():

zval *new_object;

MAKE_STD_ZVAL(new_object);

if(object_init(new_object) != SUCCESS)
{
    // do error handling here
}
You can use the functions described in Zend's API for Object Creation to add members to your object.

Zend's API for Object Creation
Function | Description
add_property_long(zval *object, char *key, long l);() | Adds a long to the object.
add_property_unset(zval *object, char *key);() | Adds an unset property to the object.
add_property_bool(zval *object, char *key, int b);() | Adds a Boolean to the object.
add_property_resource(zval *object, char *key, long r);() | Adds a resource to the object.
add_property_double(zval *object, char *key, double d);() | Adds a double to the object.
add_property_string(zval *object, char *key, char *str, int duplicate);() | Adds a string to the object.
add_property_stringl(zval *object, char *key, char *str, uint length, int duplicate);() | Adds a string of the specified length to the object. This function is faster than add_property_string() and also binary-safe.
add_property_zval(zval *obect, char *key, zval *container):() | Adds a zval container to the object. This is useful if you have to add properties which aren't simple types like integers or strings but arrays or other objects.

Resources

Resources are a special kind of data type in PHP. The term resources doesn't really refer to any special kind of data, but to an abstraction method for maintaining any kind of information. Resources are kept in a special resource list within Zend. Each entry in the list has a correspondending type definition that denotes the kind of resource to which it refers. Zend then internally manages all references to this resource. Access to a resource is never possible directly - only via a provided API. As soon as all references to a specific resource are lost, a corresponding shutdown function is called.

For example, resources are used to store database links and file descriptors. The de facto standard implementation can be found in the MySQL module, but other modules such as the Oracle module also make use of resources.

Note:

In fact, a resource can be a pointer to anything you need to handle in your functions (e.g. pointer to a structure) and the user only has to pass a single resource variable to your function.

To create a new resource you need to register a resource destruction handler for it. Since you can store any kind of data as a resource, Zend needs to know how to free this resource if its not longer needed. This works by registering your own resource destruction handler to Zend which in turn gets called by Zend whenever your resource can be freed (whether manually or automatically). Registering your resource handler within Zend returns you the resource type handle for that resource. This handle is needed whenever you want to access a resource of this type later and is most of time stored in a global static variable within your extension. There is no need to worry about thread safety here because you only register your resource handler once during module initialization.

The Zend function to register your resource handler is defined as:

ZEND_API int zend_register_list_destructors_ex(rsrc_dtor_func_t ld, rsrc_dtor_func_t pld, char *type_name, int module_number);

There are two different kinds of resource destruction handlers you can pass to this function: a handler for normal resources and a handler for persistent resources. Persistent resources are for example used for database connection. When registering a resource, either of these handlers must be given. For the other handler just pass NULL.

zend_register_list_destructors_ex() accepts the following parameters:

ld | Normal resource destruction handler callback
pld | Pesistent resource destruction handler callback
type_name | A string specifying the name of your resource. It's always a good thing to specify a unique name within PHP for the resource type so when the user for example calls var_dump($resource); he also gets the name of the resource.
module_number | The module_number is automatically available in your PHP_MINIT_FUNCTION function and therefore you just pass it over.
The return value is a unique integer ID for your resource type.

The resource destruction handler (either normal or persistent resources) has the following prototype:

void resource_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC);
The passed rsrc is a pointer to the following structure:
typedef struct _zend_rsrc_list_entry {

    void *ptr;
    int type;
    int refcount;

} zend_rsrc_list_entry;
The member void *ptr is the actual pointer to your resource.

Now we know how to start things, we define our own resource we want register within Zend. It is only a simple structure with two integer members:

typedef struct {

    int resource_link;
    int resource_type;

} my_resource;
Our resource destruction handler is probably going to look something like this:
void my_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC) {

    // You most likely cast the void pointer to your structure type

    my_resource *my_rsrc = (my_resource *) rsrc->ptr;

    // Now do whatever needs to be done with you resource. Closing
    // Files, Sockets, freeing additional memory, etc.
    // Also, don't forget to actually free the memory for your resource too!

    do_whatever_needs_to_be_done_with_the_resource(my_rsrc);
}

Note:

One important thing to mention: If your resource is a rather complex structure which also contains pointers to memory you allocated during runtime you have to free them before freeing the resource itself!

Now that we have defined

  1. what our resource is and

  2. our resource destruction handler

we can go on and do the rest of the steps:

  1. create a global variable within the extension holding the resource ID so it can be accessed from every function which needs it

  2. define the resource name

  3. write the resource destruction handler

  4. and finally register the handler

// Somewhere in your extension, define the variable for your registered resources.
    // If you wondered what 'le' stands for: it simply means 'list entry'.
    static int le_myresource;

    // It's nice to define your resource name somewhere
    #define le_myresource_name  "My type of resource"

    [...]

    // Now actually define our resource destruction handler
    void my_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC) {

        my_resource *my_rsrc = (my_resource *) rsrc->ptr;
        do_whatever_needs_to_be_done_with_the_resource(my_rsrc);
    }

    [...]

    PHP_MINIT_FUNCTION(my_extension) {

        // Note that 'module_number' is already provided through the
        // PHP_MINIT_FUNCTION() function definition.

        le_myresource = zend_register_list_destructors_ex(my_destruction_handler, NULL, le_myresource_name, module_number);

        // You can register additional resources, initialize
        // your global vars, constants, whatever.
    }

To actually register a new resource you use can either use the zend_register_resource() function or the ZEND_REGISTER_RESOURE() macro, both defined in zend_list.h. Although the arguments for both map 1:1 it's a good idea to always use macros to be upwards compatible:

int ZEND_REGISTER_RESOURCE(zval *rsrc_result, void *rsrc_pointer, int rsrc_type);
rsrc_result | This is an already initialized zval * container.
rsrc_pointer | Your resource pointer you want to store.
rsrc_type | The type which you received when you registered the resource destruction handler. If you followed the naming scheme this would be le_myresource.
The return value is a unique integer identifier for that resource.

What is really going on when you register a new resource is it gets inserted in an internal list in Zend and the result is just stored in the given zval * container:

rsrc_id = zend_list_insert(rsrc_pointer, rsrc_type);

    if (rsrc_result) {
        rsrc_result->value.lval = rsrc_id;
        rsrc_result->type = IS_RESOURCE;
    }

    return rsrc_id;
The returned rsrc_id uniquely identifies the newly registered resource. You can use the macro RETURN_RESOURE to return it to the user:
    RETURN_RESOURCE(rsrc_id)

Note:

It is common practice that if you want to return the resource immediately to the user you specify the return_value as the zval * container.

Zend now keeps track of all references to this resource. As soon as all references to the resource are lost, the destructor that you previously registered for this resource is called. The nice thing about this setup is that you don't have to worry about memory leakages introduced by allocations in your module - just register all memory allocations that your calling script will refer to as resources. As soon as the script decides it doesn't need them anymore, Zend will find out and tell you.

Now that the user got his resource, at some point he is passing it back to one of your functions. The value.lval inside the zval * container contains the key to your resource and thus can be used to fetch the resource with the following macro: ZEND_FETCH_RESOURCE:

ZEND_FETCH_RESOURCE(rsrc, rsrc_type, rsrc_id, default_rsrc_id, resource_type_name, resource_type)
rsrc | This is your pointer which will point to your previously registered resource.
rsrc_type | This is the typecast argument for your pointer, e.g. myresource *.
rsrc_id | This is the address of the zval *container the user passed to your function, e.g. &z_resource if zval *z_resource is given.
default_rsrc_id | This integer specifies the default resource ID if no resource could be fetched or -1.
resource_type_name | This is the name of the requested resource. It's a string and is used when the resource can't be found or is invalid to form a meaningful error message.
resource_type | The resource_type you got back when registering the resource destruction handler. In our example this was le_myresource.
This macro has no return value. It is for the developers convenience and takes care of TSRMLS arguments passing and also does check if the resource could be fetched. It throws a warning message and returns the current PHP function with NULL if there was a problem retrieving the resource.

To force removal of a resource from the list, use the function zend_list_delete(). You can also force the reference count to increase if you know that you're creating another reference for a previously allocated value (for example, if you're automatically reusing a default database link). For this case, use the function zend_list_addref(). To search for previously allocated resource entries, use zend_list_find(). The complete API can be found in zend_list.h.

Macros for Automatic Global Variable Creation

In addition to the macros discussed earlier, a few macros allow easy creation of simple global variables. These are nice to know in case you want to introduce global flags, for example. This is somewhat bad practice, but Table Macros for Global Variable Creation describes macros that do exactly this task. They don't need any zval allocation; you simply have to supply a variable name and value.

Macros for Global Variable Creation
Macro | Description
SET_VAR_STRING(name, value) | Creates a new string.
SET_VAR_STRINGL(name, value, length) | Creates a new string of the specified length. This macro is faster than SET_VAR_STRING and also binary-safe.
SET_VAR_LONG(name, value) | Creates a new long.
SET_VAR_DOUBLE(name, value) | Creates a new double.

Creating Constants

Zend supports the creation of true constants (as opposed to regular variables). Constants are accessed without the typical dollar sign ($) prefix and are available in all scopes. Examples include TRUE and FALSE, to name just two.

To create your own constants, you can use the macros in Macros for Creating Constants. All the macros create a constant with the specified name and value.

You can also specify flags for each constant:

  • CONST_CS - This constant's name is to be treated as case sensitive.

  • CONST_PERSISTENT - This constant is persistent and won't be "forgotten" when the current process carrying this constant shuts down.

To use the flags, combine them using a inary OR:
 // register a new constant of type "long"
     REGISTER_LONG_CONSTANT("NEW_MEANINGFUL_CONSTANT", 324, CONST_CS |
     CONST_PERSISTENT);
There are two types of macros - REGISTER_*_CONSTANT andREGISTER_MAIN_*_CONSTANT. The first type creates constants bound to the current module. These constants are dumped from the symbol table as soon as the module that registered the constant is unloaded from memory. The second type creates constants that remain in the symbol table independently of the module.

Macros for Creating Constants
Macro | Description
REGISTER_LONG_CONSTANT(name, value, flags) REGISTER_MAIN_LONG_CONSTANT(name, value, flags) | Registers a new constant of type long.
REGISTER_DOUBLE_CONSTANT(name, value, flags) REGISTER_MAIN_DOUBLE_CONSTANT(name, value, flags) | Registers a new constant of type double.
REGISTER_STRING_CONSTANT(name, value, flags) REGISTER_MAIN_STRING_CONSTANT(name, value, flags) | Registers a new constant of type string. The specified string must reside in Zend's internal memory.
REGISTER_STRINGL_CONSTANT(name, value, length, flags) REGISTER_MAIN_STRINGL_CONSTANT(name, value, length, flags) | Registers a new constant of type string. The string length is explicitly set to length. The specified string must reside in Zend's internal memory.

Duplicating Variable Contents: The Copy Constructor

Sooner or later, you may need to assign the contents of one zval container to another. This is easier said than done, since the zval container doesn't contain only type information, but also references to places in Zend's internal data. For example, depending on their size, arrays and objects may be nested with lots of hash table entries. By assigning one zval to another, you avoid duplicating the hash table entries, using only a reference to them (at most).

To copy this complex kind of data, use the copy constructor. Copy constructors are typically defined in languages that support operator overloading, with the express purpose of copying complex types. If you define an object in such a language, you have the possibility of overloading the "=" operator, which is usually responsible for assigning the contents of the rvalue (result of the evaluation of the right side of the operator) to the lvalue (same for the left side).

Overloading means assigning a different meaning to this operator, and is usually used to assign a function call to an operator. Whenever this operator would be used on such an object in a program, this function would be called with the lvalue and rvalue as parameters. Equipped with that information, it can perform the operation it intends the "=" operator to have (usually an extended form of copying).

This same form of "extended copying" is also necessary for PHP's zval containers. Again, in the case of an array, this extended copying would imply re-creation of all hash table entries relating to this array. For strings, proper memory allocation would have to be assured, and so on.

Zend ships with such a function, called zend_copy_ctor() (the previous PHP equivalent was pval_copy_constructor()).

A most useful demonstration is a function that accepts a complex type as argument, modifies it, and then returns the argument:

zval *parameter;

if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &parameter) == FAILURE)
   return;
}

// do modifications to the parameter here

// now we want to return the modified container:
*return_value = *parameter;
zval_copy_ctor(return_value);

The first part of the function is plain-vanilla argument retrieval. After the (left out) modifications, however, it gets interesting: The container of parameter is assigned to the (predefined) return_value container. Now, in order to effectively duplicate its contents, the copy constructor is called. The copy constructor works directly with the supplied argument, and the standard return values are FAILURE on failure and SUCCESS on success.

If you omit the call to the copy constructor in this example, both parameter and return_value would point to the same internal data, meaning that return_value would be an illegal additional reference to the same data structures. Whenever changes occurred in the data that parameter points to, return_value might be affected. Thus, in order to create separate copies, the copy constructor must be used.

The copy constructor's counterpart in the Zend API, the destructor zval_dtor(), does the opposite of the constructor.

Returning Values

Returning values from your functions to PHP was described briefly in an earlier section; this section gives the details. Return values are passed via the return_value variable, which is passed to your functions as argument. The return_value argument consists of a zval container (see the earlier discussion of the call interface) that you can freely modify. The container itself is already allocated, so you don't have to run MAKE_STD_ZVAL on it. Instead, you can access its members directly.

To make returning values from functions easier and to prevent hassles with accessing the internal structures of the zval container, a set of predefined macros is available (as usual). These macros automatically set the correspondent type and value, as described in Predefined Macros for Returning Values from a Function and Predefined Macros for Setting the Return Value of a Function.

Note:

The macros in Predefined Macros for Returning Values from a Function automatically return from your function, those in Predefined Macros for Setting the Return Value of a Function only set the return value; they don't return from your function.

Predefined Macros for Returning Values from a Function
Macro | Description
RETURN_RESOURCE(resource) | Returns a resource.
RETURN_BOOL(bool) | Returns a Boolean.
RETURN_NULL() | Returns nothing (a NULL value).
RETURN_LONG(long) | Returns a long.
RETURN_DOUBLE(double) | Returns a double.
RETURN_STRING(string, duplicate) | Returns a string. The duplicate flag indicates whether the string should be duplicated using estrdup().
RETURN_STRINGL(string, length, duplicate) | Returns a string of the specified length; otherwise, behaves like RETURN_STRING. This macro is faster and binary-safe, however.
RETURN_EMPTY_STRING() | Returns an empty string.
RETURN_FALSE | Returns Boolean false.
RETURN_TRUE | Returns Boolean true.
Predefined Macros for Setting the Return Value of a Function
Macro | Description
RETVAL_RESOURCE(resource) | Sets the return value to the specified resource.
RETVAL_BOOL(bool) | Sets the return value to the specified Boolean value.
RETVAL_NULL | Sets the return value to NULL.
RETVAL_LONG(long) | Sets the return value to the specified long.
RETVAL_DOUBLE(double) | Sets the return value to the specified double.
RETVAL_STRING(string, duplicate) | Sets the return value to the specified string and duplicates it to Zend internal memory if desired (see also RETURN_STRING).
RETVAL_STRINGL(string, length, duplicate) | Sets the return value to the specified string and forces the length to become length (see also RETVAL_STRING). This macro is faster and binary-safe, and should be used whenever the string length is known.
RETVAL_EMPTY_STRING | Sets the return value to an empty string.
RETVAL_FALSE | Sets the return value to Boolean false.
RETVAL_TRUE | Sets the return value to Boolean true.

Complex types such as arrays and objects can be returned by using array_init() and object_init(), as well as the corresponding hash functions on return_value. Since these types cannot be constructed of trivial information, there are no predefined macros for them.

Printing Information

Often it's necessary to print messages to the output stream from your module, just as print would be used within a script. PHP offers functions for most generic tasks, such as printing warning messages, generating output for phpinfo(), and so on. The following sections provide more details. Examples of these functions can be found on the CD-ROM.

zend_printf()

zend_printf() works like the standard printf(), except that it prints to Zend's output stream.

zend_error()

zend_error() can be used to generate error messages. This function accepts two arguments; the first is the error type (see zend_errors.h), and the second is the error message.

zend_error(E_WARNING, "This function has been called with empty arguments");
Zend's Predefined Error Messages. shows a list of possible values (see below). These values are also referred to in php.ini. Depending on which error type you choose, your messages will be logged.
Zend's Predefined Error Messages.
Error | Description
E_ERROR | Signals an error and terminates execution of the script immediately.
E_WARNING | Signals a generic warning. Execution continues.
E_PARSE | Signals a parser error. Execution continues.
E_NOTICE | Signals a notice. Execution continues. Note that by default the display of this type of error messages is turned off in php.ini.
E_CORE_ERROR | Internal error by the core; shouldn't be used by user-written modules.
E_COMPILE_ERROR | Internal error by the compiler; shouldn't be used by user-written modules.
E_COMPILE_WARNING | Internal warning by the compiler; shouldn't be used by user-written modules.
Display of warning messages in the browser.

Including Output in phpinfo()

After creating a real module, you'll want to show information about the module in phpinfo() (in addition to the module name, which appears in the module list by default). PHP allows you to create your own section in the phpinfo() output with the ZEND_MINFO() function. This function should be placed in the module descriptor block (discussed earlier) and is always called whenever a script calls phpinfo().

PHP automatically prints a section in phpinfo() for you if you specify the ZEND_MINFO function, including the module name in the heading. Everything else must be formatted and printed by you.

Typically, you can print an HTML table header using php_info_print_table_start() and then use the standard functions php_info_print_table_header() and php_info_print_table_row(). As arguments, both take the number of columns (as integers) and the column contents (as strings). Source code and screenshot for output in phpinfo. shows a source example and its output. To print the table footer, use php_info_print_table_end().

Example #13 Source code and screenshot for output in phpinfo().

php_info_print_table_start();
php_info_print_table_header(2, "First column", "Second column");
php_info_print_table_row(2, "Entry in first row", "Another entry");
php_info_print_table_row(2, "Just to fill", "another row here");
php_info_print_table_end();
Output of phpinfo()

Execution Information

You can also print execution information, such as the current file being executed. The name of the function currently being executed can be retrieved using the function get_active_function_name(). This function returns a pointer to the function name and doesn't accept any arguments. To retrieve the name of the file currently being executed, use zend_get_executed_filename(). This function accesses the executor globals, which are passed to it using the TSRMLS_C macro. The executor globals are automatically available to every function that's called directly by Zend (they're part of the INTERNAL_FUNCTION_PARAMETERS described earlier in this chapter). If you want to access the executor globals in another function that doesn't have them available automatically, call the macro TSRMLS_FETCH() once in that function; this will introduce them to your local scope.

Finally, the line number currently being executed can be retrieved using the function zend_get_executed_lineno(). This function also requires the executor globals as arguments. For examples of these functions, see Printing execution information..

Example #14 Printing execution information.

zend_printf("The name of the current function is %s&lt;br&gt;", get_active_function_name(TSRMLS_C));
zend_printf("The file currently executed is %s&lt;br&gt;", zend_get_executed_filename(TSRMLS_C));
zend_printf("The current line being executed is %i&lt;br&gt;", zend_get_executed_lineno(TSRMLS_C));
Printing execution information

Startup and Shutdown Functions

Startup and shutdown functions can be used for one-time initialization and deinitialization of your modules. As discussed earlier in this chapter (see the description of the Zend module descriptor block), there are module, and request startup and shutdown events.

The module startup and shutdown functions are called whenever a module is loaded and needs initialization; the request startup and shutdown functions are called every time a request is processed (meaning that a file is being executed).

For dynamic extensions, module and request startup/shutdown events happen at the same time.

Declaration and implementation of these functions can be done with macros; see the earlier section "Declaration of the Zend Module Block" for details.

Calling User Functions

You can call user functions from your own modules, which is very handy when implementing callbacks; for example, for array walking, searching, or simply for event-based programs.

User functions can be called with the function call_user_function_ex(). It requires a hash value for the function table you want to access, a pointer to an object (if you want to call a method), the function name, return value, number of arguments, argument array, and a flag indicating whether you want to perform zval separation.

ZEND_API int call_user_function_ex(HashTable *function_table, zval *object,
zval *function_name, zval **retval_ptr_ptr,
int param_count, zval **params[],
int no_separation);

Note that you don't have to specify both function_table and object; either will do. If you want to call a method, you have to supply the object that contains this method, in which case call_user_function()automatically sets the function table to this object's function table. Otherwise, you only need to specify function_table and can set object to NULL.

Usually, the default function table is the "root" function table containing all function entries. This function table is part of the compiler globals and can be accessed using the macro CG. To introduce the compiler globals to your function, call the macro TSRMLS_FETCH once.

The function name is specified in a zval container. This might be a bit surprising at first, but is quite a logical step, since most of the time you'll accept function names as parameters from calling functions within your script, which in turn are contained in zval containers again. Thus, you only have to pass your arguments through to this function. This zval must be of type IS_STRING.

The next argument consists of a pointer to the return value. You don't have to allocate memory for this container; the function will do so by itself. However, you have to destroy this container (using zval_dtor()) afterward!

Next is the parameter count as integer and an array containing all necessary parameters. The last argument specifies whether the function should perform zval separation - this should always be set to 0. If set to 1, the function consumes less memory but fails if any of the parameters need separation.

Calling user functions. shows a small demonstration of calling a user function. The code calls a function that's supplied to it as argument and directly passes this function's return value through as its own return value. Note the use of the constructor and destructor calls at the end - it might not be necessary to do it this way here (since they should be separate values, the assignment might be safe), but this is bulletproof.

Example #15 Calling user functions.

zval **function_name;
zval *retval;

if((ZEND_NUM_ARGS() != 1) || (zend_get_parameters_ex(1, &function_name) != SUCCESS))
{
    WRONG_PARAM_COUNT;
}

if((*function_name)->type != IS_STRING)
{
    zend_error(E_ERROR, "Function requires string argument");
}

TSRMSLS_FETCH();

if(call_user_function_ex(CG(function_table), NULL, *function_name, &retval, 0, NULL, 0) != SUCCESS)
{
    zend_error(E_ERROR, "Function call failed");
}

zend_printf("We have %i as type\n", retval->type);

*return_value = *retval;
zval_copy_ctor(return_value);
zval_ptr_dtor(&retval);

<?php

dl("call_userland.so");

function test_function()
{
    echo "We are in the test function!\n";
    return 'hello';
}

$return_value = call_userland("test_function");

echo "Return value: '$return_value'";
?>

The above example will output:

We are in the test function!
We have 3 as type
Return value: 'hello'

Initialization File Support

PHP 4 features a redesigned initialization file support. It's now possible to specify default initialization entries directly in your code, read and change these values at runtime, and create message handlers for change notifications.

To create an .ini section in your own module, use the macros PHP_INI_BEGIN() to mark the beginning of such a section and PHP_INI_END() to mark its end. In between you can use PHP_INI_ENTRY() to create entries.

PHP_INI_BEGIN()
PHP_INI_ENTRY("first_ini_entry",  "has_string_value", PHP_INI_ALL, NULL)
PHP_INI_ENTRY("second_ini_entry", "2",                PHP_INI_SYSTEM, OnChangeSecond)
PHP_INI_ENTRY("third_ini_entry",  "xyz",              PHP_INI_USER, NULL)
PHP_INI_END()
The PHP_INI_ENTRY() macro accepts four parameters: the entry name, the entry value, its change permissions, and a pointer to a change-notification handler. Both entry name and value must be specified as strings, regardless of whether they really are strings or integers.

The permissions are grouped into three sections:PHP_INI_SYSTEM allows a change only directly in the php.ini file; PHP_INI_USER allows a change to be overridden by a user at runtime using additional configuration files, such as .htaccess; and PHP_INI_ALL allows changes to be made without restrictions. There's also a fourth level, PHP_INI_PERDIR, for which we couldn't verify its behavior yet.

The fourth parameter consists of a pointer to a change-notification handler. Whenever one of these initialization entries is changed, this handler is called. Such a handler can be declared using the PHP_INI_MH macro:

PHP_INI_MH(OnChangeSecond);             // handler for ini-entry "second_ini_entry"

// specify ini-entries here

PHP_INI_MH(OnChangeSecond)
{

    zend_printf("Message caught, our ini entry has been changed to %s&lt;br&gt;", new_value);

    return(SUCCESS);

}
The new value is given to the change handler as string in the variable new_value. When looking at the definition of PHP_INI_MH, you actually have a few parameters to use:
#define PHP_INI_MH(name) int name(php_ini_entry *entry, char *new_value,
                                  uint new_value_length, void *mh_arg1,
                                  void *mh_arg2, void *mh_arg3)
All these definitions can be found in php_ini.h. Your message handler will have access to a structure that contains the full entry, the new value, its length, and three optional arguments. These optional arguments can be specified with the additional macros PHP_INI_ENTRY1 (allowing one additional argument), PHP_INI_ENTRY2 (allowing two additional arguments), and PHP_INI_ENTRY3 (allowing three additional arguments).

The change-notification handlers should be used to cache initialization entries locally for faster access or to perform certain tasks that are required if a value changes. For example, if a constant connection to a certain host is required by a module and someone changes the hostname, automatically terminate the old connection and attempt a new one.

Access to initialization entries can also be handled with the macros shown in Macros to Access Initialization Entries in PHP.

Macros to Access Initialization Entries in PHP
Macro | Description
INI_INT(name) | Returns the current value of entry name as integer (long).
INI_FLT(name) | Returns the current value of entry name as float (double).
INI_STR(name) | Returns the current value of entry name as string. Note: This string is not duplicated, but instead points to internal data. Further access requires duplication to local memory.
INI_BOOL(name) | Returns the current value of entry name as Boolean (defined as zend_bool, which currently means unsigned char).
INI_ORIG_INT(name) | Returns the original value of entry name as integer (long).
INI_ORIG_FLT(name) | Returns the original value of entry name as float (double).
INI_ORIG_STR(name) | Returns the original value of entry name as string. Note: This string is not duplicated, but instead points to internal data. Further access requires duplication to local memory.
INI_ORIG_BOOL(name) | Returns the original value of entry name as Boolean (defined as zend_bool, which currently means unsigned char).

Finally, you have to introduce your initialization entries to PHP. This can be done in the module startup and shutdown functions, using the macros REGISTER_INI_ENTRIES() and UNREGISTER_INI_ENTRIES():

ZEND_MINIT_FUNCTION(mymodule)
{

    REGISTER_INI_ENTRIES();

}

ZEND_MSHUTDOWN_FUNCTION(mymodule)
{

    UNREGISTER_INI_ENTRIES();

}

Where to Go from Here

You've learned a lot about PHP. You now know how to create dynamic loadable modules and statically linked extensions. You've learned how PHP and Zend deal with internal storage of variables and how you can create and access these variables. You know quite a set of tool functions that do a lot of routine tasks such as printing informational texts, automatically introducing variables to the symbol table, and so on.

Even though this chapter often had a mostly "referential" character, we hope that it gave you insight on how to start writing your own extensions. For the sake of space, we had to leave out a lot; we suggest that you take the time to study the header files and some modules (especially the ones in the ext/standard directory and the MySQL module, as these implement commonly known functionality). This will give you an idea of how other people have used the API functions - particularly those that didn't make it into this chapter.

Reference: Some Configuration Macros

config.m4

The file config.m4 is processed by buildconf and must contain all the instructions to be executed during configuration. For example, these can include tests for required external files, such as header files, libraries, and so on. PHP defines a set of macros that can be used in this process, the most useful of which are described in M4 Macros for config.m4.

M4 Macros for config.m4
Macro | Description
AC_MSG_CHECKING(message) | Prints a "checking <message>" text during configure.
AC_MSG_RESULT(value) | Gives the result to AC_MSG_CHECKING; should specify either yes or no as value.
AC_MSG_ERROR(message) | Prints message as error message during configure and aborts the script.
AC_DEFINE(name,value,description) | Adds #define to php_config.h with the value of value and a comment that says description (this is useful for conditional compilation of your module).
AC_ADD_INCLUDE(path) | Adds a compiler include path; for example, used if the module needs to add search paths for header files.
AC_ADD_LIBRARY_WITH_PATH(libraryname,librarypath) | Specifies an additional library to link.
AC_ARG_WITH(modulename,description,unconditionaltest,conditionaltest) | Quite a powerful macro, adding the module with description to the configure --help output. PHP checks whether the option --with-<modulename> is given to the configure script. If so, it runs the script unconditionaltest (for example, --with-myext=yes), in which case the value of the option is contained in the variable $withval. Otherwise, it executes conditionaltest.
PHP_EXTENSION(modulename, [shared]) | This macro is a must to call for PHP to configure your extension. You can supply a second argument in addition to your module name, indicating whether you intend compilation as a shared module. This will result in a definition at compile time for your source as COMPILE_DL_<modulename>.

API Macros

A set of macros was introduced into Zend's API that simplify access to zval containers (see API Macros for Accessing zval Containers).

API Macros for Accessing zval Containers
Macro | Refers to
Z_LVAL(zval) | (zval).value.lval
Z_DVAL(zval) | (zval).value.dval
Z_STRVAL(zval) | (zval).value.str.val
Z_STRLEN(zval) | (zval).value.str.len
Z_ARRVAL(zval) | (zval).value.ht
Z_LVAL_P(zval) | (*zval).value.lval
Z_DVAL_P(zval) | (*zval).value.dval
Z_STRVAL_P(zval_p) | (*zval).value.str.val
Z_STRLEN_P(zval_p) | (*zval).value.str.len
Z_ARRVAL_P(zval_p) | (*zval).value.ht
Z_LVAL_PP(zval_pp) | (**zval).value.lval
Z_DVAL_PP(zval_pp) | (**zval).value.dval
Z_STRVAL_PP(zval_pp) | (**zval).value.str.val
Z_STRLEN_PP(zval_pp) | (**zval).value.str.len
Z_ARRVAL_PP(zval_pp) | (**zval).value.ht


  • « Zend API: Hacking the Core of PHP
  • FAQ »
  • PHP Manual
  • Zend Engine 1
  • TSRM API

TSRM API


FAQ: Frequently Asked Questions

  • General Information
  • Mailing lists
  • Obtaining PHP
  • Database issues
  • Installation
  • Build Problems
  • Using PHP
  • Password Hashing — Safe Password Hashing
  • PHP and HTML
  • PHP and COM
  • Miscellaneous Questions


General Information

This section holds the most general questions about PHP: what it is and what it does.

  1. What is PHP?
  2. What does PHP stand for?
  3. What is the relation between the versions?
  4. Can I run several versions of PHP at the same time?
  5. I think I found a bug! Who should I tell?
What is PHP?

From the preface of the manual:

PHP is an HTML-embedded scripting language. Much of its syntax is borrowed from C, Java and Perl with a couple of unique PHP-specific features thrown in. The goal of the language is to allow web developers to write dynamically generated pages quickly.

What does PHP stand for?

PHP stands for PHP: Hypertext Preprocessor. This confuses many people because the first word of the acronym is the acronym. This type of acronym is called a recursive acronym. For more information, the curious can visit » Free On-Line Dictionary of Computing or the » Wikipedia entry on recursive acronyms.

What is the relation between the versions?

PHP/FI 2.0 is an early and no longer supported version of PHP. PHP 3 is the successor to PHP/FI 2.0 and is a lot nicer. PHP 7 is the current generation of PHP, which uses the Zend engine 3 which, among other things, offers many additional OOP features.

Can I run several versions of PHP at the same time?

Yes. See the INSTALL file that is included in the PHP source distribution.

I think I found a bug! Who should I tell?

You should go to the PHP Bug Database and make sure the bug isn't a known bug. If you don't see it in the database, use the reporting form to report the bug. It is important to use the bug database instead of just sending an email to one of the mailing lists because the bug will have a tracking number assigned and it will then be possible for you to go back later and check on the status of the bug. The bug database can be found at » https://bugs.php.net/.


Mailing lists

This section holds questions about how to get in touch with the PHP community. The best way is the mailing lists.

  1. Are there any PHP mailing lists?
  2. Are there any other communities?
  3. Can I start my own PHP mailing list?
  4. Help! I can't seem to subscribe to/unsubscribe from one of the mailing lists!
  5. Is there an archive of the mailing lists anywhere?
  6. What can I ask the mailing list?
  7. What information should I include when posting to the mailing list?
Are there any PHP mailing lists?

Of course! There are many mailing lists for several subjects. The most common community mailing lists can be found on our » mailing list page.

The most general mailing list is php-general. To subscribe, send a blank email message to » php-general-subscribe@lists.php.net. To unsubscribe, send a blank email to » php-general-unsubscribe@lists.php.net.

You can also subscribe and unsubscribe using the web interface on our » mailing list page, and unsubscribe instructions are included in the footer of every mailing list message.

Are there any other communities?

There are countless PHP-centric communities around the world, and we have links to some of these resources (and information on how to learn more) on our » Support page.

Can I start my own PHP mailing list?

Absolutely! In fact, we not only freely allow it, we encourage it! Helping others by sharing your knowledge and experience with PHP helps to foster the growth and development of the global PHP community and the language itself.

Help! I can't seem to subscribe to/unsubscribe from one of the mailing lists!

If you have problems subscribing to or unsubscribing from a mailing list, it may be because the mailing list software can't figure out the correct mailing address to use. If your email address is joeblow@example.com, and you are trying to subscribe to php-general, you can send your subscription request to php-general-subscribe-joeblow=example.com@lists.php.net, or your unsubscription request to php-general-unsubscribe-joeblow=example.com@lists.php.net. Use similar addresses for the other mailing lists.

The most common reason folks have a hard time unsubscribing from our mailing lists is due to the use of mail forwarders. For example, if your email address is danbrown@example.com, but you subscribed to the mailing list with the forwarder php-lists@example.com and forward that to danbrown@example.com, attempting to unsubscribe danbrown@example.com will not work, as that address is not even known to our systems. Instead, you will need to unsubscribe the address to which the mail is being sent - in this example, php-lists@example.com.

Is there an archive of the mailing lists anywhere?

Yes, you will find links to some of the archive sites on the » mailing list page. You will also find dozens of sites that archive and/or syndicate our mailing list content by using your favorite Internet search engine and searching for "php mailing list archives".

All mailing list articles are also archived as news messages. You can access the news server at » news://news.php.net/ with a news client. There is also an experimental web interface for the news server at » http://news.php.net/

What can I ask the mailing list?

Since PHP is growing more and more popular by the day, the traffic on the php-general mailing list can be very heavy, ranging from 75 to 200 or more posts per day. Because of this, it is in everyone's interest that you use the list as a last resort, when you have exhausted all other avenues.

Before you post to the list please have a look in this FAQ and the manual to see if you can find the help there. If there is nothing to be found there try out the mailing list archives (see above). If you're having problem with installing or configuring PHP, please read through all included documentation and README's. If you still can't find any information that helps you out, you're more than welcome to use the appropriate mailing list.

To ensure that you receive the best responses (and to reduce the likelihood of frustrating your fellow developers), please be sure to post your question to the appropriate list. For example, if you are having difficulties installing PHP, you should send your question to the php-install mailing list. A caveat: some lists have similar names and completely different uses; a question regarding PHP scripts on Windows should be directed to the Windows PHP users list, not to the Windows Internals list.

Before asking questions, you may want to read the paper on » How To Ask Questions The Smart Way as this is a good idea for everyone.

What information should I include when posting to the mailing list?

Posts like "I can't get PHP up and running! Help me! What is wrong?" are of absolutely no use to anyone. If you're having problems getting PHP up and running you must include the operating system being used, the version of PHP you're trying to use, how you got it (pre-compiled, Git, RPM, and so on), what you have done so far, and the exact error message or present result.

This goes for any other problem as well: you must include an explanation of what you have done, what you're trying to do, and any error messages encountered in the process. If you're having problems with your source code, you should include the part of the code that isn't working, indicating which line is the problem by an appropriately-placed code comment. Do not include more code than necessary though! It makes the post difficult to read, causing many to ignore your request. If you're unsure about how much information should be included, post what you believe is immediately relevant to your present issue, and be prepared to provide more information upon request.

Another important thing to remember is to summarize your problem on the subject line. A subject like "HELP MEEEE!!!" or "What is the problem here?" will be ignored by the majority of the readers.

And lastly, you're encouraged to read the paper on » How To Ask Questions The Smart Way as this will be a great help for everyone, especially yourself.


Obtaining PHP

This section has details about PHP download locations, and OS issues.

  1. Where can I obtain PHP?
  2. Are pre-compiled binary versions available?
  3. Where can I get libraries needed to compile some of the optional PHP extensions?
  4. How do I get these libraries to work?
  5. I got the latest version of the PHP source code from the Git repository on my Windows machine, what do I need to compile it?
  6. Where do I find the Browser Capabilities File?
  7. What does thread safety mean when downloading PHP?
Where can I obtain PHP?

You can download PHP from any of the members of the PHP network of sites. These can be found at » https://www.php.net/. You can also use anonymous Git to get the absolute latest version of the source. For more information, go to » https://www.php.net/git.php.

Are pre-compiled binary versions available?

We only distribute precompiled binaries for Windows systems, as we are not able to compile PHP for every major Linux/Unix platform with every extension combination. Also note, that many Linux distributions come with PHP built in these days. Windows binaries can be downloaded from our » Downloads page, for Linux binaries, please visit your distribution's website.

Where can I get libraries needed to compile some of the optional PHP extensions?

Note: Those marked with a * are to the best of our knowledge not thread safe; they are not recommended for use in a multi-threaded environment.

  • » LDAP (Unix).
  • » LDAP (Unix/Win) : Mozilla Directory (LDAP) SDK
  • » free LDAP server.
  • » Berkeley DB2 (Unix/Win) : http://www.sleepycat.com/.
  • » SNMP* (Unix): .
  • » GD (Unix/Win).
  • » mSQL* (Unix).
  • » PostgreSQL (Unix).
  • » IMAP* (Win/Unix).
  • » Sybase-CT* (Linux, libc5) : Available locally.
  • » FreeType (libttf):.
  • » ZLib (Unix/Win32).
  • » expat XML parser (Unix/Win32).
  • » PDFLib.
  • » mcrypt.
  • » mhash.
  • » t1lib.
  • » dmalloc.
  • » aspell.
  • » readline.

How do I get these libraries to work?

You will need to follow instructions provided with the library. Some of these libraries are detected automatically when you run the 'configure' script of PHP (such as the GD library), and others you will have to enable using '--with-EXTENSION' options to 'configure'. Run 'configure --help' for a listing of these.

I got the latest version of the PHP source code from the Git repository on my Windows machine, what do I need to compile it?

See the PHP Wiki for the latest instructions: » Step by Step Build Instructions

Where do I find the Browser Capabilities File?

You can find a browscap.ini file at » http://browscap.org/.

What does thread safety mean when downloading PHP?

Thread Safety means that binary can work in a multithreaded webserver context, such as Apache 2 on Windows. Thread Safety works by creating a local storage copy in each thread, so that the data won't collide with another thread.

So what do I choose? If you choose to run PHP as a CGI binary, then you won't need thread safety, because the binary is invoked at each request. For multithreaded webservers, such as IIS5 and IIS6, you should use the threaded version of PHP.


Database issues

This section holds common questions about relation between PHP and databases. Yes, PHP can access virtually any database available today.

  1. I heard it's possible to access Microsoft SQL Server from PHP. How?
  2. Can I access Microsoft Access databases?
  3. Why is the MySQL extension (ext/mysql) that I've been using for over 10 years discouraged from use? Is it deprecated? What do I use instead? How can I migrate?
  4. Why do I get an error that looks something like this: "Warning: 0 is not a MySQL result index in <file> on line <x>" or "Warning: Supplied argument is not a valid MySQL result resource in <file> on line <x>"?
I heard it's possible to access Microsoft SQL Server from PHP. How?

On Unix machines you can use PDO_ODBC or the Unified ODBC API.

On Windows machines you can also use PDO_SQLSRV or SQLSRV.

Also see the answer to the next question.

Can I access Microsoft Access databases?

Yes. You already have all the tools you need if you are running entirely under Windows 9x/Me, or NT/2000, where you can use ODBC and Microsoft's ODBC drivers for Microsoft Access databases.

If you are running PHP on a Unix box and want to talk to MS Access on a Windows box you will need Unix ODBC drivers. » OpenLink Software has Unix-based ODBC drivers that can do this.

Another alternative is to use an SQL server that has Windows ODBC drivers and use that to store the data, which you can then access from Microsoft Access (using ODBC) and PHP (using the built in drivers), or to use an intermediary file format that Access and PHP both understand, such as flat files or dBase databases. On this point Tim Hayes from OpenLink software writes:

Using another database as an intermediary is not a good idea, when you can use ODBC from PHP straight to your database - i.e. with OpenLink's drivers. If you do need to use an intermediary file format, OpenLink have now released Virtuoso (a virtual database engine) for NT, Linux and other Unix platforms. Please visit our » website for a free download.

One option that has proved successful is to use MySQL and its MyODBC drivers on Windows and synchronizing the databases. Steve Lawrence writes:

  • Install MySQL on your platform according to instructions with MySQL. Latest available from » http://www.mysql.com/ No special configuration required except when you set up a database, and configure the user account, you should put % in the host field, or the host name of the Windows computer you wish to access MySQL with. Make a note of your server name, username, and password.
  • Download the MyODBC for Windows driver from the MySQL site. Install it on your Windows machine. You can test the operation with the utilities included with this program.
  • Create a user or system dsn in your ODBC administrator, located in the control panel. Make up a dsn name, enter your hostname, user name, password, port, etc for you MySQL database configured in step 1.
  • Install Access with a full install, this makes sure you get the proper add-ins... at the least you will need ODBC support and the linked table manager.
  • Now the fun part! Create a new access database. In the table window right click and select Link Tables, or under the file menu option, select Get External Data and then Link Tables. When the file browser box comes up, select files of type: ODBC. Select System dsn and the name of your dsn created in step 3. Select the table to link, press OK, and presto! You can now open the table and add/delete/edit data on your MySQL server! You can also build queries, import/export tables to MySQL, build forms and reports, etc.

Tips and Tricks:

  • You can construct your tables in Access and export them to MySQL, then link them back in. That makes table creation quick.
  • When creating tables in Access, you must have a primary key defined in order to have write access to the table in access. Make sure you create a primary key in MySQL before linking in access
  • If you change a table in MySQL, you have to re-link it in Access. Go to tools>add-ins>linked table manager, cruise to your ODBC DSN, and select the table to re-link from there. you can also move your dsn source around there, just hit the always prompt for new location checkbox before pressing OK.

Why is the MySQL extension (ext/mysql) that I've been using for over 10 years discouraged from use? Is it deprecated? What do I use instead? How can I migrate?

There are three MySQL extensions, as described under the Choosing a MySQL API section. The old API should not be used, it is deprecated as of PHP 5.5.0 and has been moved to PECL as of PHP 7.0.0. You are strongly encouraged to write all new code with either mysqli or PDO_MySQL.

Migration scripts are not available at this time, although the mysqli API contains both a procedural and OOP API, with the procedural version being similar to ext/mysql.

It is not possible to mix the extensions. So, for example, passing a mysqli connection to PDO_MySQL or ext/mysql will not work.

Why do I get an error that looks something like this: "Warning: 0 is not a MySQL result index in <file> on line <x>" or "Warning: Supplied argument is not a valid MySQL result resource in <file> on line <x>"?

You are trying to use a result identifier that is 0. The 0 indicates that your query failed for some reason. You need to check for errors after submitting a query and before you attempt to use the returned result identifier. The proper way to do this is with code similar to the following:

<?php

$result = mysql_query("SELECT * FROM tables_priv");
if (!$result) {
    echo mysql_error();
    exit;
}
?>
or
<?php

$result = mysql_query("SELECT * FROM tables_priv")
    or die("Bad query: " . mysql_error());
?>


Installation

This section holds common questions about the way to install PHP. PHP is available for almost any OS, and almost any web server.

To install PHP, follow the instructions in Installation and Configuration.

  1. Why shouldn't I use Apache2 with a threaded MPM in a production environment?
  2. Unix/Windows: Where should my php.ini file be located?
  3. Unix: I installed PHP, but every time I load a document, I get the message 'Document Contains No Data'! What's going on here?
  4. Unix: I installed PHP using RPMS, but Apache isn't processing the PHP pages! What's going on here?
  5. Unix: I patched Apache with the FrontPage extensions patch, and suddenly PHP stopped working. Is PHP incompatible with the Apache FrontPage extensions?
  6. Unix/Windows: I have installed PHP, but when I try to access a PHP script file via my browser, I get a blank screen.
  7. Unix/Windows: I have installed PHP, but when try to access a PHP script file via my browser, I get a server 500 error.
  8. Some operating systems: I have installed PHP without errors, but when I try to start Apache I get undefined symbol errors: [mybox:user /src/php5] root# apachectl configtest apachectl: /usr/local/apache/bin/httpd Undefined symbols: _compress _uncompress
  9. Windows: I have installed PHP, but when I try to access a PHP script file via my browser, I get the error: cgi error: The specified CGI application misbehaved by not returning a complete set of HTTP headers. The headers it did return are:
  10. Windows: I've followed all the instructions, but still can't get PHP and IIS to work together!
  11. When running PHP as CGI with IIS, PWS, OmniHTTPD or Xitami, I get the following error: Security Alert! PHP CGI cannot be accessed directly..
  12. How do I know if my php.ini is being found and read? It seems like it isn't as my changes aren't being implemented.
  13. How do I add my PHP directory to the PATH on Windows?
  14. How do I make the php.ini file available to PHP on windows?
  15. Is it possible to use Apache content negotiation (MultiViews option) with PHP?
  16. Is PHP limited to process GET and POST request methods only?
Why shouldn't I use Apache2 with a threaded MPM in a production environment?

PHP is glue. It is the glue used to build cool web applications by sticking dozens of 3rd-party libraries together and making it all appear as one coherent entity through an intuitive and easy to learn language interface. The flexibility and power of PHP relies on the stability and robustness of the underlying platform. It needs a working OS, a working web server and working 3rd-party libraries to glue together. When any of these stop working PHP needs ways to identify the problems and fix them quickly. When you make the underlying framework more complex by not having completely separate execution threads, completely separate memory segments and a strong sandbox for each request to play in, further weaknesses are introduced into PHP's system.

If you want to use a threaded MPM, look at a FastCGI configuration where PHP is running in its own memory space.

Unix/Windows: Where should my php.ini file be located?

By default on Unix it should be in /usr/local/lib which is <install-path>/lib. Most people will want to change this at compile-time with the --with-config-file-path flag. You would, for example, set it with something like:

--with-config-file-path=/etc
And then you would copy php.ini-development from the distribution to /etc/php.ini and edit it to make any local changes you want.

--with-config-file-scan-dir=PATH

On Windows the default path for the php.ini file is the Windows directory. If you're using the Apache webserver, php.ini is first searched in the Apaches install directory, e.g. c:\program files\apache group\apache. This way you can have different php.ini files for different versions of Apache on the same machine.

See also the chapter about the configuration file.

Unix: I installed PHP, but every time I load a document, I get the message 'Document Contains No Data'! What's going on here?

This probably means that PHP is having some sort of problem and is core-dumping. Look in your server error log to see if this is the case, and then try to reproduce the problem with a small test case. If you know how to use 'gdb', it is very helpful when you can provide a backtrace with your bug report to help the developers pinpoint the problem. If you are using PHP as an Apache module try something like:

  • Stop your httpd processes

  • gdb httpd

  • Stop your httpd processes

  • > run -X -f /path/to/httpd.conf

  • Then fetch the URL causing the problem with your browser

  • > run -X -f /path/to/httpd.conf

  • If you are getting a core dump, gdb should inform you of this now

  • type: bt

  • You should include your backtrace in your bug report. This should be submitted to » https://bugs.php.net/

If your script uses the regular expression functions (preg_match() and friends), you should make sure that you compiled PHP and Apache with the same regular expression package. This should happen automatically with PHP and Apache 1.3.x

Unix: I installed PHP using RPMS, but Apache isn't processing the PHP pages! What's going on here?

Assuming you installed both Apache and PHP from RPM packages, you need to uncomment or add some or all of the following lines in your httpd.conf file:

# Extra Modules
AddModule mod_php.c
AddModule mod_perl.c

# Extra Modules
LoadModule php_module         modules/mod_php.so
LoadModule php5_module        modules/libphp5.so
LoadModule perl_module        modules/libperl.so
And add:
AddType application/x-httpd-php .php
... to the global properties, or to the properties of the VirtualDomain you want to have PHP support added to.

Unix: I patched Apache with the FrontPage extensions patch, and suddenly PHP stopped working. Is PHP incompatible with the Apache FrontPage extensions?

No, PHP works fine with the FrontPage extensions. The problem is that the FrontPage patch modifies several Apache structures, that PHP relies on. Recompiling PHP (using 'make clean ; make') after the FP patch is applied would solve the problem.

Unix/Windows: I have installed PHP, but when I try to access a PHP script file via my browser, I get a blank screen.

Do a 'view source' in the web browser and you will probably find that you can see the source code of your PHP script. This means that the web server did not send the script to PHP for interpretation. Something is wrong with the server configuration - double check the server configuration against the PHP installation instructions.

Unix/Windows: I have installed PHP, but when try to access a PHP script file via my browser, I get a server 500 error.

Something went wrong when the server tried to run PHP. To get to see a sensible error message, from the command line, change to the directory containing the PHP executable (php.exe on Windows) and run php -i. If PHP has any problems running, then a suitable error message will be displayed which will give you a clue as to what needs to be done next. If you get a screen full of HTML codes (the output of the phpinfo() function) then PHP is working, and your problem may be related to your server configuration which you should double check.

Some operating systems: I have installed PHP without errors, but when I try to start Apache I get undefined symbol errors:
[mybox:user /src/php5] root# apachectl configtest
 apachectl: /usr/local/apache/bin/httpd Undefined symbols:
  _compress
  _uncompress

This has actually nothing to do with PHP, but with the MySQL client libraries. Some need --with-zlib , others do not. This is also covered in the MySQL FAQ.

Windows: I have installed PHP, but when I try to access a PHP script file via my browser, I get the error:
cgi error:
 The specified CGI application misbehaved by not
 returning a complete set of HTTP headers.
 The headers it did return are:

This error message means that PHP failed to output anything at all. To get to see a sensible error message, from the command line, change to the directory containing the PHP executable (php.exe on Windows) and run php -i. If PHP has any problems running, then a suitable error message will be displayed which will give you a clue as to what needs to be done next. If you get a screen full of HTML codes (the output of the phpinfo() function) then PHP is working.

Once PHP is working at the command line, try accessing the script via the browser again. If it still fails then it could be one of the following:

  • File permissions on your PHP script, php.exe, php5ts.dll, php.ini or any PHP extensions you are trying to load are such that the anonymous internet user ISUR_<machinename> cannot access them.
  • The script file does not exist (or possibly isn't where you think it is relative to your web root directory). Note that for IIS you can trap this error by ticking the 'check file exists' box when setting up the script mappings in the Internet Services Manager. If a script file does not exist then the server will return a 404 error instead. There is also the additional benefit that IIS will do any authentication required for you based on the NTLanMan permissions on your script file.
Windows: I've followed all the instructions, but still can't get PHP and IIS to work together!

Make sure any user who needs to run a PHP script has the rights to run php.exe! IIS uses an anonymous user which is added at the time IIS is installed. This user needs rights to php.exe. Also, any authenticated user will also need rights to execute php.exe. And for IIS4 you need to tell it that PHP is a script engine. Also, you will want to read this faq.

When running PHP as CGI with IIS, PWS, OmniHTTPD or Xitami, I get the following error: Security Alert! PHP CGI cannot be accessed directly..

You must set the cgi.force_redirect directive to 0. It defaults to 1 so be sure the directive isn't commented out (with a ;). Like all directives, this is set in php.ini

Because the default is 1, it's critical that you're 100% sure that the correct php.ini file is being read. Read this faq for details.

How do I know if my php.ini is being found and read? It seems like it isn't as my changes aren't being implemented.

To be sure your php.ini is being read by PHP, make a call to phpinfo(). Near the top, there will be a listing called Configuration File (php.ini). This will tell you where PHP is looking for php.ini and whether or not it's being read. If just a directory PATH exists, then it's not being read, and you should put your php.ini in that directory. If php.ini is included within the PATH, it is being read.

If php.ini is being read and you're running PHP as a module, then be sure to restart your web server after making changes to php.ini

See also php_ini_loaded_file().

How do I add my PHP directory to the PATH on Windows?

On Windows 7, XP, Vista, 2008, 2012 and up:

  • Go to Control Panel and open the System icon (Start → Control Panel)

  • Go to the Advanced tab

  • Click on the 'Environment Variables' button

  • Look into the 'System Variables' pane

  • Find the Path entry (you may need to scroll to find it)

  • Double click on the Path entry

  • Enter your PHP directory at the end, including ';' before (e.g. ;C:\php)

  • Press OK

On Windows 98/Me you need to edit the autoexec.bat file:

  • Open the Notepad (Start → Run and enter notepad)

  • Open the C:\autoexec.bat file

  • Locate the line with PATH=C:\WINDOWS;C:\WINDOWS\COMMAND;..... and add: ;C:\php to the end of the line

  • Save the file and restart your computer

Note: Be sure to reboot after following the steps above to ensure that the PATH changes are applied.

The PHP manual used to promote the copying of files into the Windows system directory, this is because this directory (C:\Windows, C:\WINNT, etc.) is by default in the system's PATH. Copying files into the Windows system directory has long since been deprecated and may cause problems.

How do I make the php.ini file available to PHP on windows?

There are several ways of doing this. If you are using Apache, read their installation specific instructions (Apache 1, Apache 2), otherwise you must set the PHPRC environment variable:

On Windows:

  • Go to Control Panel and open the System icon (Start → Settings → Control Panel → System, or just Start → Control Panel → System)

  • Go to the Advanced tab

  • Click on the 'Environment Variables' button

  • Look into the 'System variables' pane

  • Click on 'New' and enter 'PHPRC' as the variable name and the directory where php.ini is located as the variable value (e.g. C:\php)

  • Press OK and restart your computer

On Windows 98/Me you need to edit the autoexec.bat file:

  • Open the Notepad (Start → Run and enter notepad)

  • Open the C:\autoexec.bat file

  • Add a new line to the end of the file: set PHPRC=C:\php (replace C:\php with the directory where php.ini is located). Please note that the path cannot contain spaces. For instance, if you have installed PHP in C:\Program Files\PHP, you would enter C:\PROGRA~1\PHP instead.

  • Save the file and restart your computer

Is it possible to use Apache content negotiation (MultiViews option) with PHP?

If links to PHP files include extension, everything works perfect. This FAQ is only for the case when links to PHP files don't include extension and you want to use content negotiation to choose PHP files from URL with no extension. In this case, replace the line AddType application/x-httpd-php .php with:

AddHandler php5-script php
AddType text/html php
This solution doesn't work for Apache 1 as PHP module doesn't catch php-script.

Is PHP limited to process GET and POST request methods only?

No, it is possible to handle any request method, e.g. CONNECT. Proper response status can be sent with header(). If only GET and POST methods should be handled, it can be achieved with this Apache configuration:

<LimitExcept GET POST>
Deny from all
</LimitExcept>


Build Problems

This section gathers most common errors that occur at build time.

  1. I got the latest version of PHP using the anonymous Git service, but there's no configure script!
  2. I'm having problems configuring PHP to work with Apache. It says it can't find httpd.h, but it's right where I said it is!
  3. While configuring PHP (./configure), you come across an error similar to the following: checking lex output file root... ./configure: lex: command not found configure: error: cannot find output from lex; giving up
  4. When I try to start Apache, I get the following message: fatal: relocation error: file /path/to/libphp4.so: symbol ap_block_alarms: referenced symbol not found
  5. When I run configure, it says that it can't find the include files or library for GD, gdbm, or some other package!
  6. When it is compiling the file language-parser.tab.c, it gives me errors that say yytname undeclared.
  7. When I run make, it seems to run fine but then fails when it tries to link the final application complaining that it can't find some files.
  8. When linking PHP, it complains about a number of undefined references.
  9. I can't figure out how to build PHP with Apache 1.3.
  10. I have followed all the steps to install the Apache module version on Unix, and my PHP scripts show up in my browser or I am being asked to save the file.
  11. It says to use: --activate-module=src/modules/php4/libphp4.a, but that file doesn't exist, so I changed it to --activate-module=src/modules/php4/libmodphp4.a and it doesn't work!? What's going on?
  12. When I try to build Apache with PHP as a static module using --activate-module=src/modules/php4/libphp4.a it tells me that my compiler is not ANSI compliant.
  13. When I try to build PHP using --with-apxs I get strange error messages.
  14. During make, I get errors in microtime, and a lot of RUSAGE_ stuff.
  15. When compiling PHP with MySQL, configure runs fine but during make I get an error similar to the following: ext/mysql/libmysqlclient/my_tempnam.o(.text+0x46): In function my_tempnam': /php4/ext/mysql/libmysqlclient/my_tempnam.c:103: the use of tempnam' is dangerous, better use mkstemp', what's wrong?
  16. I want to upgrade my PHP. Where can I find the ./configure line that was used to build my current PHP installation?
  17. When building PHP with the GD library it either gives strange compile errors or segfaults on execution.
  18. When compiling PHP I seemingly get random errors, like it hangs. I'm using Solaris if that matters.
I got the latest version of PHP using the anonymous Git service, but there's no configure script!

You have to have the GNU autoconf package installed so you can generate the configure script from configure.in. Just run ./buildconf in the top-level directory after getting the sources from the Git server. (Also, unless you run configure with the --enable-maintainer-mode option, the configure script will not automatically get rebuilt when the configure.in file is updated, so you should make sure to do that manually when you notice configure.in has changed. One symptom of this is finding things like @VARIABLE@ in your Makefile after configure or config.status is run.)

I'm having problems configuring PHP to work with Apache. It says it can't find httpd.h, but it's right where I said it is!

You need to tell the configure/setup script the location of the top-level of your Apache source tree. This means that you want to specify --with-apache=/path/to/apache and not --with-apache=/path/to/apache/src .

While configuring PHP (./configure), you come across an error similar to the following:

checking lex output file root... ./configure: lex: command not found
configure: error: cannot find output from lex; giving up

Be sure to read the installation instructions carefully and note that you need both flex and bison installed to compile PHP. Depending on your setup you will install bison and flex from either source or a package, such as a RPM.

When I try to start Apache, I get the following message:

fatal: relocation error: file /path/to/libphp4.so:
symbol ap_block_alarms: referenced symbol not found

This error usually comes up when one compiles the Apache core program as a DSO library for shared usage. Try to reconfigure apache, making sure to use at least the following flags:

--enable-shared=max --enable-rule=SHARED_CORE

For more information, read the top-level Apache INSTALL file or the Apache » DSO manual page.

When I run configure, it says that it can't find the include files or library for GD, gdbm, or some other package!

You can make the configure script look for header files and libraries in non-standard locations by specifying additional flags to pass to the C preprocessor and linker, such as:

    CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure
If you're using a csh-variant for your login shell (why?), it would be:
    env CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure

When it is compiling the file language-parser.tab.c, it gives me errors that say yytname undeclared.

You need to update your version of Bison. You can find the latest version at » http://www.gnu.org/software/bison/bison.html.

When I run make, it seems to run fine but then fails when it tries to link the final application complaining that it can't find some files.

Some old versions of make that don't correctly put the compiled versions of the files in the functions directory into that same directory. Try running cp *.o functions and then re-running make to see if that helps. If it does, you should really upgrade to a recent version of GNU make.

When linking PHP, it complains about a number of undefined references.

Take a look at the link line and make sure that all of the appropriate libraries are being included at the end. Common ones that you might have missed are '-ldl' and any libraries required for any database support you included.

Some people have also reported that they had to add '-ldl' immediately following libphp4.a when linking with Apache.

I can't figure out how to build PHP with Apache 1.3.

This is actually quite easy. Follow these steps carefully:

  • Grab the latest Apache 1.3 distribution from » http://httpd.apache.org/download.cgi.
  • Ungzip and untar it somewhere, for example /usr/local/src/apache-1.3.
  • Compile PHP by first running ./configure --with-apache=/<path>/apache-1.3 (substitute <path> for the actual path to your apache-1.3 directory).
  • Type make followed by make install to build PHP and copy the necessary files to the Apache distribution tree.
  • Change directories into to your /<path>/apache-1.3/src directory and edit the Configuration file. Add to the file: AddModule modules/php4/libphp4.a.
  • Type: ./configure followed by make.
  • You should now have a PHP-enabled httpd binary!

Note: You can also use the new Apache ./configure script. See the instructions in the README.configure file which is part of your Apache distribution. Also have a look at the INSTALL file in the PHP distribution.

I have followed all the steps to install the Apache module version on Unix, and my PHP scripts show up in my browser or I am being asked to save the file.

This means that the PHP module is not getting invoked for some reason. Three things to check before asking for further help:

  • Make sure that the httpd binary you are running is the actual new httpd binary you just built. To do this, try running: /path/to/binary/httpd -l If you don't see mod_php4.c listed then you are not running the right binary. Find and install the correct binary.
  • Make sure you have added the correct Mime Type to one of your Apache .conf files. It should be: AddType application/x-httpd-php .php Also make sure that this AddType line is not hidden away inside a <Virtualhost> or <Directory> block which would prevent it from applying to the location of your test script.
  • Finally, the default location of the Apache configuration files changed between Apache 1.2 and Apache 1.3. You should check to make sure that the configuration file you are adding the AddType line to is actually being read. You can put an obvious syntax error into your httpd.conf file or some other obvious change that will tell you if the file is being read correctly.

It says to use: --activate-module=src/modules/php4/libphp4.a, but that file doesn't exist, so I changed it to --activate-module=src/modules/php4/libmodphp4.a and it doesn't work!? What's going on?

Note that the libphp4.a file is not supposed to exist. The apache process will create it!

When I try to build Apache with PHP as a static module using --activate-module=src/modules/php4/libphp4.a it tells me that my compiler is not ANSI compliant.

This is a misleading error message from Apache that has been fixed in more recent versions.

When I try to build PHP using --with-apxs I get strange error messages.

There are three things to check here. First, for some reason when Apache builds the apxs Perl script, it sometimes ends up getting built without the proper compiler and flags variables. Find your apxs script (try the command which apxs), it's sometimes found in /usr/local/apache/bin/apxs or /usr/sbin/apxs. Open it and check for lines similar to these:

my $CFG_CFLAGS_SHLIB  = ' ';          # substituted via Makefile.tmpl
my $CFG_LD_SHLIB      = ' ';          # substituted via Makefile.tmpl
my $CFG_LDFLAGS_SHLIB = ' ';          # substituted via Makefile.tmpl
If this is what you see, you have found your problem. They may contain just spaces or other incorrect values, such as 'q()'. Change these lines to say:
my $CFG_CFLAGS_SHLIB  = '-fpic -DSHARED_MODULE'; # substituted via Makefile.tmpl
my $CFG_LD_SHLIB      = 'gcc';                   # substituted via Makefile.tmpl
my $CFG_LDFLAGS_SHLIB = q(-shared);              # substituted via Makefile.tmpl
The second possible problem should only be an issue on Red Hat 6.1 and 6.2. The apxs script Red Hat ships is broken. Look for this line:
my $CFG_LIBEXECDIR    = 'modules';         # substituted via APACI install
If you see the above line, change it to this:
my $CFG_LIBEXECDIR    = '/usr/lib/apache'; # substituted via APACI install
Last, if you reconfigure/reinstall Apache, add a make clean to the process after ./configure and before make.

During make, I get errors in microtime, and a lot of RUSAGE_ stuff.

During the make portion of installation, if you encounter problems that look similar to this:

microtime.c: In function `php_if_getrusage':
microtime.c:94: storage size of `usg' isn't known
microtime.c:97: `RUSAGE_SELF' undeclared (first use in this function)
microtime.c:97: (Each undeclared identifier is reported only once
microtime.c:97: for each function it appears in.)
microtime.c:103: `RUSAGE_CHILDREN' undeclared (first use in this function)
make[3]: *** [microtime.lo] Error 1
make[3]: Leaving directory `/home/master/php-4.0.1/ext/standard'
make[2]: *** [all-recursive] Error 1
make[2]: Leaving directory `/home/master/php-4.0.1/ext/standard'
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory `/home/master/php-4.0.1/ext'
make: *** [all-recursive] Error 1

Your system is broken. You need to fix your /usr/include files by installing a glibc-devel package that matches your glibc. This has absolutely nothing to do with PHP. To prove this to yourself, try this simple test:

$ cat >test.c <<X
#include <sys/resource.h>
X
$ gcc -E test.c >/dev/null
If that spews out errors, you know your include files are messed up.

When compiling PHP with MySQL, configure runs fine but during make I get an error similar to the following: ext/mysql/libmysqlclient/my_tempnam.o(.text+0x46): In function my_tempnam': /php4/ext/mysql/libmysqlclient/my_tempnam.c:103: the use of tempnam' is dangerous, better use mkstemp', what's wrong?

First, it's important to realize that this is a Warning and not a fatal error. Because this is often the last output seen during make, it may seem like a fatal error but it's not. Of course, if you set your compiler to die on Warnings, it will. Also keep in mind that MySQL support is enabled by default.

Note:

As of PHP 4.3.2, you'll also see the following text after the build (make) completes:

Build complete.
(It is safe to ignore warnings about tempnam and tmpnam).

I want to upgrade my PHP. Where can I find the ./configure line that was used to build my current PHP installation?

Either you look at config.nice file, in the source tree of your current PHP installation or, if this is not available, you simply run a

<?php phpinfo(); ?>
script. On top of the output the ./configure line, that was used to build this PHP installation is shown.

When building PHP with the GD library it either gives strange compile errors or segfaults on execution.

Make sure your GD library and PHP are linked against the same depending libraries (e.g. libpng).

When compiling PHP I seemingly get random errors, like it hangs. I'm using Solaris if that matters.

Using non-GNU utilities while compiling PHP may cause problems. Be sure to use GNU tools in order to be certain that compiling PHP will work. For example, on Solaris, using either the SunOS BSD-compatible or Solaris versions of sed will not work, but using the GNU or Sun POSIX (xpg4) versions of sed will work. Links: » GNU sed, » GNU flex, and » GNU bison.


Using PHP

This section gathers many common errors that you may face while writing PHP scripts.

  1. I cannot remember the parameter order of PHP functions, are they random?
  2. I would like to write a generic PHP script that can handle data coming from any form. How do I know which POST method variables are available?
  3. I need to convert all single-quotes (') to a backslash followed by a single-quote (\'). How can I do this with a regular expression? I'd also like to convert " to \" and \ to \\.
  4. All my " turn into \" and my ' turn into \', how do I get rid of all these unwanted backslashes? How and why did they get there?
  5. How does the PHP directive register_globals affect me?
  6. When I do the following, the output is printed in the wrong order: <?php function myfunc($argument) { echo $argument + 10; } $variable = 10; echo "myfunc($variable) = " . myfunc($variable); ?> what's going on?
  7. Hey, what happened to my newlines? <pre> <?php echo "This should be the first line."; ?> <?php echo "This should show up after the new line above."; ?> </pre>
  8. I get the message 'Warning: Cannot send session cookie - headers already sent...' or 'Cannot add header information - headers already sent...'.
  9. I need to access information in the request header directly. How can I do this?
  10. When I try to use authentication with IIS I get 'No Input file specified'.
  11. Windows: I can't access files shared on another computer using IIS
  12. How am I supposed to mix XML and PHP? It complains about my <?xml tags!
  13. Where can I find a complete list of variables are available to me in PHP?
  14. How can I generate PDF files without using the non-free and commercial libraries like PDFLib? I'd like something that's free and doesn't require external PDF libraries.
  15. I'm trying to access one of the standard CGI variables (such as $DOCUMENT_ROOT or $HTTP_REFERER) in a user-defined function, and it can't seem to find it. What's wrong?
  16. A few PHP directives may also take on shorthand byte values, as opposed to only integer byte values. What are all the available shorthand byte options?
  17. Windows: I keep getting connection timeouts when using localhost, whereas "127.0.0.1" works?
I cannot remember the parameter order of PHP functions, are they random?

PHP is a glue that brings together hundreds of external libraries, so sometimes this gets messy. However, a simple rule of thumb is as follows:

Array function parameters are ordered as "needle, haystack" whereas String functions are the opposite, so "haystack, needle".

I would like to write a generic PHP script that can handle data coming from any form. How do I know which POST method variables are available?

PHP offers many predefined variables, like the superglobal $_POST. You may loop through $_POST as it's an associate array of all POSTed values. For example, let's simply loop through it with foreach, check for empty() values, and print them out.

<?php
$empty = $post = array();
foreach ($_POST as $varname => $varvalue) {
    if (empty($varvalue)) {
        $empty[$varname] = $varvalue;
    } else {
        $post[$varname] = $varvalue;
    }
}

print "<pre>";
if (empty($empty)) {
    print "None of the POSTed values are empty, posted:\n";
    var_dump($post);
} else {
    print "We have " . count($empty) . " empty values\n";
    print "Posted:\n"; var_dump($post);
    print "Empty:\n";  var_dump($empty);
    exit;
}
?>

I need to convert all single-quotes (') to a backslash followed by a single-quote (\'). How can I do this with a regular expression? I'd also like to convert " to \" and \ to \\.

Assuming this is for a database, use the escaping mechanism that comes with the database. For example, use mysql_real_escape_string() with MySQL and pg_escape_string() with PostgreSQL. There is also the generic addslashes() and stripslashes() functions, that are more common with older PHP code.

Note: directive note: magic_quotes_gpc

The magic_quotes_gpc directive defaults to on. It essentially runs addslashes() on all GET, POST, and COOKIE data. stripslashes() may be used to remove them.

All my " turn into \" and my ' turn into \', how do I get rid of all these unwanted backslashes? How and why did they get there?

Most likely the backslashes magically exist because the PHP directive magic_quotes_gpc is on. This is an old feature of PHP, and should be disabled and not relied upon. Also, the PHP function stripslashes() may be used to strip the backslashes from the string.

Note: directive note: magic_quotes_gpc

The magic_quotes_gpc directive defaults to on. It essentially runs addslashes() on all GET, POST, and COOKIE data. stripslashes() may be used to remove them.

How does the PHP directive register_globals affect me?
Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

First, an explanation about what this ini setting does. Let's say the following URL is used: http://example.com/foo.php?animal=cat and in foo.php we might have the following PHP code:

<?php
// Using $_GET here is preferred
echo $_GET['animal'];

// For $animal to exist, register_globals must be on
// DO NOT DO THIS
echo $animal;

// This applies to all variables, so $_SERVER too
echo $_SERVER['PHP_SELF'];

// Again, for $PHP_SELF to exist, register_globals must be on
// DO NOT DO THIS
echo $PHP_SELF;
?>

The code above demonstrates how register_globals creates a lot of variables. For years this type of coding has been frowned upon, and for years it's been disabled by default. So although most web hosts disable register_globals, there are still outdated articles, tutorials, and books that require it to be on. Plan accordingly.

See also the following resources for additional information:

  • The register_globals directive
  • The security chapter about register globals
  • Handling external variables
  • Use superglobals instead

Note:

In the example above, we used an URL that contained a QUERY_STRING. Passing information like this is done through a GET HTTP Request, so this is why the superglobal $_GET was used.

When I do the following, the output is printed in the wrong order:
<?php
function myfunc($argument)
{
    echo $argument + 10;
}
$variable = 10;
echo "myfunc($variable) = " . myfunc($variable);
?>
what's going on?

To be able to use the results of your function in an expression (such as concatenating it with other strings in the example above), you need to return the value, not echo it.

Hey, what happened to my newlines?
<pre>
<?php echo "This should be the first line."; ?>
<?php echo "This should show up after the new line above."; ?>
</pre>

In PHP, the ending for a block of code is either "?>" or "?>\n" (where \n means a newline). So in the example above, the echoed sentences will be on one line, because PHP omits the newlines after the block ending. This means that you need to insert an extra newline after each block of PHP code to make it print out one newline.

Why does PHP do this? Because when formatting normal HTML, this usually makes your life easier because you don't want that newline, but you'd have to create extremely long lines or otherwise make the raw page source unreadable to achieve that effect.

I get the message 'Warning: Cannot send session cookie - headers already sent...' or 'Cannot add header information - headers already sent...'.

The functions header(), setcookie(), and the session functions need to add headers to the output stream but headers can only be sent before all other content. There can be no output before using these functions, output such as HTML. The function headers_sent() will check if your script has already sent headers and see also the Output Control functions.

I need to access information in the request header directly. How can I do this?

The getallheaders() function will do this if you are running PHP as an Apache module. So, the following bit of code will show you all the request headers:

<?php
$headers = getallheaders();
foreach ($headers as $name => $content) {
    echo "headers[$name] = $content<br />\n";
}
?>

See also
apache_lookup_uri(),
apache_response_headers(), and
fsockopen()

When I try to use authentication with IIS I get 'No Input file specified'.

The security model of IIS is at fault here. This is a problem common to all CGI programs running under IIS. A workaround is to create a plain HTML file (not parsed by PHP) as the entry page into an authenticated directory. Then use a META tag to redirect to the PHP page, or have a link to the PHP page. PHP will then recognize the authentication correctly. With the ISAPI module, this is not a problem. This should not affect other NT web servers. For more information, see: » http://support.microsoft.com/kb/q160422/ and the manual section on HTTP Authentication .

Windows: I can't access files shared on another computer using IIS

You have to change the Go to Internet Information Services. Locate your PHP file and go to its properties. Go to the File Security tab, Edit -< Anonymous access and authentication control.

You can fix the problem either by unticking Anonymous Access and leaving Integrated Window Authentication ticked, or, by ticking Anonymous Access and editing the user as he may not have the access right.

How am I supposed to mix XML and PHP? It complains about my <?xml tags!

In order to embed <?xml straight into your PHP code, you'll have to turn off short tags by having the PHP directive short_open_tags set to 0. You cannot set this directive with ini_set(). Regardless of short_open_tags being on or off, you can do something like: <?php echo '<?xml'; ?>. The default for this directive is On.

Where can I find a complete list of variables are available to me in PHP?

Read the manual page on predefined variables as it includes a partial list of predefined variables available to your script. A complete list of available variables (and much more information) can be seen by calling the phpinfo() function. Be sure to read the manual section on variables from outside of PHP as it describes common scenarios for external variables, like from a HTML form, a Cookie, and the URL.

Note: register_globals: important note

As of PHP 4.2.0, the default value for the PHP directive register_globals is off. The PHP community discourages developers from relying on this directive, and encourages the use of other means, such as the superglobals.

How can I generate PDF files without using the non-free and commercial libraries like PDFLib? I'd like something that's free and doesn't require external PDF libraries.

There are a few alternatives written in PHP such as » FPDF and » TCPDF.

There is also the Haru extension that uses the free libHaru external library.

I'm trying to access one of the standard CGI variables (such as $DOCUMENT_ROOT or $HTTP_REFERER) in a user-defined function, and it can't seem to find it. What's wrong?

It's important to realize that the PHP directive register_globals also affects server and environment variables. When register_globals = off (the default is off since PHP 4.2.0), $DOCUMENT_ROOT will not exist. Instead, use $_SERVER['DOCUMENT_ROOT'] . If register_globals = on then the variables $DOCUMENT_ROOT and $GLOBALS['DOCUMENT_ROOT'] will also exist.

If you're sure register_globals = on and wonder why $DOCUMENT_ROOT isn't available inside functions, it's because these are like any other variables and would require global $DOCUMENT_ROOT inside the function. See also the manual page on variable scope. It's preferred to code with register_globals = off.

A few PHP directives may also take on shorthand byte values, as opposed to only integer byte values. What are all the available shorthand byte options?

The available options are K (for Kilobytes), M (for Megabytes) and G (for Gigabytes; available since PHP 5.1.0), and are all case-insensitive. Anything else assumes bytes. 1M equals one Megabyte or 1048576 bytes. 1K equals one Kilobyte or 1024 bytes. These shorthand notations may be used in php.ini and in the ini_set() function. Note that the numeric value is cast to integer; for instance, 0.5M is interpreted as 0.

Note: kilobyte versus kibibyte

The PHP notation describes one kilobyte as equalling 1024 bytes, whereas the IEC standard considers this to be a kibibyte instead. Summary: k and K = 1024 bytes.

Windows: I keep getting connection timeouts when using localhost, whereas "127.0.0.1" works?

Prior to PHP 5.3.4, there was a bug in the network resolving code inside PHP that caused localhost in all stream related situations to fail if IPv6 was enabled. To work around this issue you can either use "127.0.0.1" or disable IPv6 resolving in the hosts file.


Safe Password Hashing

This section explains the reasons behind using hashing functions to secure passwords, as well as how to do so effectively.

  1. Why should I hash passwords supplied by users of my application?
  2. Why are common hashing functions such as md5 and sha1 unsuitable for passwords?
  3. How should I hash my passwords, if the common hash functions are not suitable?
  4. What is a salt?
  5. How do I store my salts?
Why should I hash passwords supplied by users of my application?

Password hashing is one of the most basic security considerations that must be made when designing any application that accepts passwords from users. Without hashing, any passwords that are stored in your application's database can be stolen if the database is compromised, and then immediately used to compromise not only your application, but also the accounts of your users on other services, if they do not use unique passwords.

By applying a hashing algorithm to your user's passwords before storing them in your database, you make it implausible for any attacker to determine the original password, while still being able to compare the resulting hash to the original password in the future.

It is important to note, however, that hashing passwords only protects them from being compromised in your data store, but does not necessarily protect them from being intercepted by malicious code injected into your application itself.

Why are common hashing functions such as md5() and sha1() unsuitable for passwords?

Hashing algorithms such as MD5, SHA1 and SHA256 are designed to be very fast and efficient. With modern techniques and computer equipment, it has become trivial to "brute force" the output of these algorithms, in order to determine the original input.

Because of how quickly a modern computer can "reverse" these hashing algorithms, many security professionals strongly suggest against their use for password hashing.

How should I hash my passwords, if the common hash functions are not suitable?

When hashing passwords, the two most important considerations are the computational expense, and the salt. The more computationally expensive the hashing algorithm, the longer it will take to brute force its output.

PHP 5.5 provides a native password hashing API that safely handles both hashing and verifying passwords in a secure manner. There is also » a pure PHP compatibility library available for PHP 5.3.7 and later.

Another option is the crypt() function, which supports several hashing algorithms in PHP 5.3 and later. When using this function, you are guaranteed that the algorithm you select is available, as PHP contains native implementations of each supported algorithm, in case one or more are not supported by your system.

The suggested algorithm to use when hashing passwords is Blowfish, which is also the default used by the password hashing API, as it is significantly more computationally expensive than MD5 or SHA1, while still being scalable.

Note that if you are using crypt() to verify a password, you will need to take care to prevent timing attacks by using a constant time string comparison. Neither PHP's == and === operators nor strcmp() perform constant time string comparisons. As password_verify() will do this for you, you are strongly encouraged to use the native password hashing API whenever possible.

What is a salt?

A cryptographic salt is data which is applied during the hashing process in order to eliminate the possibility of the output being looked up in a list of pre-calculated pairs of hashes and their input, known as a rainbow table.

In more simple terms, a salt is a bit of additional data which makes your hashes significantly more difficult to crack. There are a number of services online which provide extensive lists of pre-computed hashes, as well as the original input for those hashes. The use of a salt makes it implausible or impossible to find the resulting hash in one of these lists.

password_hash() will create a random salt if one isn't provided, and this is generally the easiest and most secure approach.

How do I store my salts?

When using password_hash() or crypt(), the return value includes the salt as part of the generated hash. This value should be stored verbatim in your database, as it includes information about the hash function that was used and can then be given directly to password_verify() or crypt() when verifying passwords.

The following diagram shows the format of a return value from crypt() or password_hash(). As you can see, they are self-contained, with all the information on the algorithm and salt required for future password verification.

The components of the value returned by password_hash and crypt: in order, the chosen algorithm, the algorithm's options, the salt used, and the hashed password.


PHP and HTML

PHP and HTML interact a lot: PHP can generate HTML, and HTML can pass information to PHP. Before reading these faqs, it's important you learn how to retrieve variables from external sources. The manual page on this topic includes many examples as well.

  1. What encoding/decoding do I need when I pass a value through a form/URL?
  2. I'm trying to use an <input type="image"> tag, but the $foo.x and $foo.y variables aren't available. $_GET['foo.x'] isn't existing either. Where are they?
  3. How do I create arrays in a HTML <form>?
  4. How do I get all the results from a select multiple HTML tag?
  5. How can I pass a variable from Javascript to PHP?
What encoding/decoding do I need when I pass a value through a form/URL?

There are several stages for which encoding is important. Assuming that you have a string $data, which contains the string you want to pass on in a non-encoded way, these are the relevant stages:

  • HTML interpretation. In order to specify a random string, you must include it in double quotes, and htmlspecialchars() the whole value.

  • URL: A URL consists of several parts. If you want your data to be interpreted as one item, you must encode it with urlencode().

Example #1 A hidden HTML form element

<?php
    echo '<input type="hidden" value="' . htmlspecialchars($data) . '" />'."\n";
?>

Note: It is wrong to urlencode() $data, because it's the browsers responsibility to urlencode() the data. All popular browsers do that correctly. Note that this will happen regardless of the method (i.e., GET or POST). You'll only notice this in case of GET request though, because POST requests are usually hidden.

Example #2 Data to be edited by the user

<?php
    echo "<textarea name='mydata'>\n";
    echo htmlspecialchars($data)."\n";
    echo "</textarea>";
?>

Note: The data is shown in the browser as intended, because the browser will interpret the HTML escaped symbols. Upon submitting, either via GET or POST, the data will be urlencoded by the browser for transferring, and directly urldecoded by PHP. So in the end, you don't need to do any urlencoding/urldecoding yourself, everything is handled automagically.

Example #3 In a URL

<?php
    echo '<a href="' . htmlspecialchars("/nextpage.php?stage=23&data=" .
        urlencode($data)) . '">'."\n";
?>

Note: In fact you are faking a HTML GET request, therefore it's necessary to manually urlencode() the data.

Note: You need to htmlspecialchars() the whole URL, because the URL occurs as value of an HTML-attribute. In this case, the browser will first un-htmlspecialchars() the value, and then pass the URL on. PHP will understand the URL correctly, because you urlencode()d the data. You'll notice that the & in the URL is replaced by &amp;. Although most browsers will recover if you forget this, this isn't always possible. So even if your URL is not dynamic, you need to htmlspecialchars() the URL.

I'm trying to use an <input type="image"> tag, but the $foo.x and $foo.y variables aren't available. $_GET['foo.x'] isn't existing either. Where are they?

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="foo" />
When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables: foo.x and foo.y.

Because foo.x and foo.y would make invalid variable names in PHP, they are automagically converted to foo_x and foo_y. That is, the periods are replaced with underscores. So, you'd access these variables like any other described within the section on retrieving variables from external sources. For example, $_GET['foo_x'].

Note:

Spaces in request variable names are converted to underscores.

How do I create arrays in a HTML <form>?

To get your <form> result sent as an array to your PHP script you name the <input>, <select> or <textarea> elements like this:

<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyArray[]" />
Notice the square brackets after the variable name, that's what makes it an array. You can group the elements into different arrays by assigning the same name to different elements:
<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyOtherArray[]" />
<input name="MyOtherArray[]" />
This produces two arrays, MyArray and MyOtherArray, that gets sent to the PHP script. It's also possible to assign specific keys to your arrays:
<input name="AnotherArray[]" />
<input name="AnotherArray[]" />
<input name="AnotherArray[email]" />
<input name="AnotherArray[phone]" />
The AnotherArray array will now contain the keys 0, 1, email and phone.

Note:

Specifying array keys is optional in HTML. If you do not specify the keys, the array gets filled in the order the elements appear in the form. Our first example will contain keys 0, 1, 2 and 3.

See also Array Functions and Variables From External Sources.

How do I get all the results from a select multiple HTML tag?

The select multiple tag in an HTML construct allows users to select multiple items from a list. These items are then passed to the action handler for the form. The problem is that they are all passed with the same widget name. I.e.

<select name="var" multiple="yes">
Each selected option will arrive at the action handler as:
var=option1
var=option2
var=option3
Each option will overwrite the contents of the previous $var variable. The solution is to use PHP's "array from form element" feature. The following should be used:
<select name="var[]" multiple="yes">
This tells PHP to treat $var as an array and each assignment of a value to var[] adds an item to the array. The first item becomes $var[0], the next $var[1], etc. The count() function can be used to determine how many options were selected, and the sort() function can be used to sort the option array if necessary.

Note that if you are using JavaScript the [] on the element name might cause you problems when you try to refer to the element by name. Use it's numerical form element ID instead, or enclose the variable name in single quotes and use that as the index to the elements array, for example:

variable = document.forms[0].elements['var[]'];

How can I pass a variable from Javascript to PHP?

Since Javascript is (usually) a client-side technology, and PHP is (usually) a server-side technology, and since HTTP is a "stateless" protocol, the two languages cannot directly share variables.

It is, however, possible to pass variables between the two. One way of accomplishing this is to generate Javascript code with PHP, and have the browser refresh itself, passing specific variables back to the PHP script. The example below shows precisely how to do this -- it allows PHP code to capture screen height and width, something that is normally only possible on the client side.

Example #4 Generating Javascript with PHP

<?php
if (isset($_GET['width']) AND isset($_GET['height'])) {
  // output the geometry variables
  echo "Screen width is: ". $_GET['width'] ."<br />\n";
  echo "Screen height is: ". $_GET['height'] ."<br />\n";
} else {
  // pass the geometry variables
  // (preserve the original query string
  //   -- post variables will need to handled differently)

  echo "<script language='javascript'>\n";
  echo "  location.href=\"${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}"
            . "&width=\" + screen.width + \"&height=\" + screen.height;\n";
  echo "</script>\n";
  exit();
}
?>


PHP and COM

PHP can be used to access COM and DCOM objects on Win32 platforms.

  1. I have built a DLL to calculate something. Is there any way to run this DLL under PHP ?
  2. What does 'Unsupported variant type: xxxx (0xxxxx)' mean ?
  3. Is it possible manipulate visual objects in PHP ?
  4. Can I store a COM object in a session ?
  5. How can I trap COM errors?
  6. Can I generate DLL files from PHP scripts like I can in Perl ?
  7. What does 'Unable to obtain IDispatch interface for CLSID {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}' mean ?
  8. How can I run COM object from remote server ?
  9. I get 'DCOM is disabled in C:\path...\scriptname.php on line 6', what can I do ?
  10. Is it possible to load/manipulate an ActiveX object in a page with PHP ?
  11. Is it possible to get a running instance of a component ?
  12. Is there a way to handle an event sent from COM object ?
  13. I'm having problems when trying to invoke a method of a COM object which exposes more than one interface. What can I do ?
  14. So PHP works with COM, how about COM+ ?
  15. If PHP can manipulate COM objects, can we imagine to use MTS to manage components resources, in conjunction with PHP ?
I have built a DLL to calculate something. Is there any way to run this DLL under PHP ?

If this is a simple DLL there is no way yet to run it from PHP. If the DLL contains a COM server you may be able to access it if it implements the IDispatch interface.

What does 'Unsupported variant type: xxxx (0xxxxx)' mean ?

There are dozens of VARIANT types and combinations of them. Most of them are already supported but a few still have to be implemented. Arrays are not completely supported. Only single dimensional indexed only arrays can be passed between PHP and COM. If you find other types that aren't supported, please report them as a bug (if not already reported) and provide as much information as available.

Is it possible manipulate visual objects in PHP ?

Generally it is, but as PHP is mostly used as a web scripting language it runs in the web servers context, thus visual objects will never appear on the servers desktop. If you use PHP for application scripting e.g. in conjunction with PHP-GTK there is no limitation in accessing and manipulating visual objects through COM.

Can I store a COM object in a session ?

No, you can't. COM instances are treated as resources and therefore they are only available in a single script's context.

How can I trap COM errors?

The COM extension throws com_exception exceptions, which you can catch and then inspect the code member to determine what to do next.

Can I generate DLL files from PHP scripts like I can in Perl ?

No, unfortunately there is no such tool available for PHP.

What does 'Unable to obtain IDispatch interface for CLSID {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}' mean ?

This error can have multiple reasons:

  • the CLSID is wrong
  • the requested DLL is missing
  • the requested component doesn't implement the IDispatch interface

How can I run COM object from remote server ?

Exactly like you run local objects. You only have to pass the IP of the remote machine as second parameter to the COM constructor.

Make sure that you have set com.allow_dcom =TRUE in your php.ini.

I get 'DCOM is disabled in C:\path...\scriptname.php on line 6', what can I do ?

Edit your php.ini and set com.allow_dcom =TRUE.

Is it possible to load/manipulate an ActiveX object in a page with PHP ?

This has nothing to do with PHP. ActiveX objects are loaded on client side if they are requested by the HTML document. There is no relation to the PHP script and therefore there is no direct server side interaction possible.

Is it possible to get a running instance of a component ?

This is possible with the help of monikers. If you want to get multiple references to the same word instance you can create that instance like shown:

<?php
$word = new COM("C:\docs\word.doc");
?>

This will create a new instance if there is no running instance available or it will return a handle to the running instance, if available.

Is there a way to handle an event sent from COM object ?

You can define an event sink and bind it using com_event_sink(). You can use com_print_typeinfo() to have PHP generate a skeleton for the event sink class.

I'm having problems when trying to invoke a method of a COM object which exposes more than one interface. What can I do ?

The answer is as simple as unsatisfying. I don't know exactly but i think you can do nothing. If someone has specific information about this, please let » me know :)

So PHP works with COM, how about COM+ ?

COM+ extends COM by a framework for managing components through MTS and MSMQ but there is nothing special that PHP has to support to use such components.

If PHP can manipulate COM objects, can we imagine to use MTS to manage components resources, in conjunction with PHP ?

PHP itself doesn't handle transactions yet. Thus if an error occurs no rollback is initiated. If you use components that support transactions you will have to implement the transaction management yourself.


Miscellaneous Questions

There can be some questions we can't put into other categories. Here you can find them.

  1. How can I handle the bz2 compressed manuals on Windows?
  2. What does & beside argument mean in function declaration of e.g. asort?
  3. How do I deal with register_globals?
How can I handle the bz2 compressed manuals on Windows?

If you don't have an archiver-tool to handle bz2 files » download the command line tool from Redhat (please find further information below).

If you would not like to use a command line tool, you can try free tools like » Stuffit Expander, » UltimateZip, » 7-Zip, or » Quick Zip. If you have tools like » WinRAR or » Power Archiver, you can easily decompress the bz2 files with it. If you use Total Commander (formerly Windows Commander), a bz2 plugin for that program is available freely from the » Total Commander site.

The bzip2 command line tool from Redhat:

Win2k Sp2 users grab the latest version 1.0.2, all other Windows user should grab version 1.00. After downloading rename the executable to bzip2.exe. For convenience put it into a directory in your path, e.g. C:\Windows where C represents your Windows installation drive.

Note: lang stands for your language and x for the desired format, e.g.: pdf. To uncompress the php_manual_lang.x.bz2 follow these simple instructions:

  • open a command prompt window
  • cd to the folder where you stored the downloaded php_manual_lang.x.bz2
  • invoke bzip2 -d php_manual_lang.x.bz2, extracting php_manual_lang.x in the same folder

In case you downloaded the php_manual_lang.tar.bz2 with many html-files in it, the procedure is the same. The only difference is that you got a file php_manual_lang.tar. The tar format is known to be treated with most common archivers on Windows like e.g. » WinZip.

What does & beside argument mean in function declaration of e.g. asort()?

It means that the argument is passed by reference and the function will likely modify it corresponding to the documentation. You can pass only variables this way and you don't need to pass them with & in function call (it's even deprecated).

How do I deal with register_globals?

For information about the security implications of register_globals, read the security chapter on Using register_globals.

It's preferred to use superglobals, rather than relying upon register_globals being on.

If you are on a shared host with register_globals turned off and need to use some legacy applications, which require this option to be turned on, or you are on some hosting server, where this feature is turned on, but you would like to eliminate security risks, you might need to emulate the opposite setting with PHP. It is always a good idea to first ask if it would be possible to change the option somehow in PHP's configuration, but if it is not possible, then you can use these compatibility snippets.

Example #1 Emulating Register Globals

This will emulate register_globals On. If you altered your variables_order directive, consider changing the $superglobals accordingly.

<?php
// Emulate register_globals on
if (!ini_get('register_globals')) {
    $superglobals = array($_SERVER, $_ENV,
        $_FILES, $_COOKIE, $_POST, $_GET);
    if (isset($_SESSION)) {
        array_unshift($superglobals, $_SESSION);
    }
    foreach ($superglobals as $superglobal) {
        extract($superglobal, EXTR_SKIP);
    }
}
?>

This will emulate register_globals Off. Keep in mind, that this code should be called at the very beginning of your script, or after session_start() if you use it to start your session.

<?php
// Emulate register_globals off
function unregister_GLOBALS()
{
    if (!ini_get('register_globals')) {
        return;
    }

    // Might want to change this perhaps to a nicer error
    if (isset($_REQUEST['GLOBALS']) || isset($_FILES['GLOBALS'])) {
        die('GLOBALS overwrite attempt detected');
    }

    // Variables that shouldn't be unset
    $noUnset = array('GLOBALS',  '_GET',
                     '_POST',    '_COOKIE',
                     '_REQUEST', '_SERVER',
                     '_ENV',     '_FILES');

    $input = array_merge($_GET,    $_POST,
                         $_COOKIE, $_SERVER,
                         $_ENV,    $_FILES,
                         isset($_SESSION) && is_array($_SESSION) ? $_SESSION : array());

    foreach ($input as $k => $v) {
        if (!in_array($k, $noUnset) && isset($GLOBALS[$k])) {
            unset($GLOBALS[$k]);
        }
    }
}

unregister_GLOBALS();

?>


Appendices

  • History of PHP and Related Projects
    • History of PHP
    • History of PHP related projects
    • Books about PHP
    • Publications about PHP
  • Migrating from PHP 7.3.x to PHP 7.4.x
    • New Features
    • New Classes and Interfaces
    • New Functions
    • New Global Constants
    • Backward Incompatible Changes
    • Deprecated Features
    • Removed Extensions
    • Other Changes
    • Windows Support
  • Migrating from PHP 7.2.x to PHP 7.3.x
    • New Features
    • New Functions
    • New Global Constants
    • Backward Incompatible Changes
    • Deprecated Features
    • Other Changes
    • Windows Support
  • Migrating from PHP 7.1.x to PHP 7.2.x
    • New features
    • New functions
    • New global constants
    • Backward incompatible changes
    • Deprecated features in PHP 7.2.x
    • Other changes
  • Migrating from PHP 7.0.x to PHP 7.1.x
    • New features
    • New functions
    • New global constants
    • Backward incompatible changes
    • Deprecated features in PHP 7.1.x
    • Changed functions
    • Other changes
    • Windows Support
  • Migrating from PHP 5.6.x to PHP 7.0.x
    • Backward incompatible changes
    • New features
    • Deprecated features in PHP 7.0.x
    • Changed functions
    • New functions
    • New Classes and Interfaces
    • New Global Constants
    • Changes in SAPI Modules
    • Removed Extensions and SAPIs
    • Other Changes
  • Migrating from PHP 5.5.x to PHP 5.6.x
    • Backward incompatible changes
    • New features
    • Deprecated features in PHP 5.6.x
    • Changed functions
    • New functions
    • OpenSSL changes in PHP 5.6.x
    • Other changes to extensions
    • New global constants
  • Migrating from PHP 5.4.x to PHP 5.5.x
    • What has changed in PHP 5.5.x
    • Backward Incompatible Changes
    • New features
    • Deprecated features in PHP 5.5.x
    • Changed Functions
    • New Functions
    • New Classes and Interfaces
    • New Methods
    • Other changes to extensions
    • New Global Constants
    • Changes to INI file handling
    • Changes to PHP Internals
  • Migrating from PHP 5.3.x to PHP 5.4.x
    • What has changed in PHP 5.4.x
    • Backward Incompatible Changes
    • New features
    • Changes in SAPI modules
    • Deprecated features in PHP 5.4.x
    • Changed Functions
    • New Functions
    • New Classes and Interfaces
    • New Methods
    • Removed Extensions
    • Other changes to extensions
    • New Global Constants
    • Changes to INI file handling
    • Other changes
  • Migrating from PHP 5.2.x to PHP 5.3.x
    • What has changed in PHP 5.3.x
    • Backward Incompatible Changes
    • New features
    • Changes made to Windows support
    • Changes in SAPI modules
    • Deprecated features in PHP 5.3.x
    • Undeprecated features in PHP 5.3.x
    • New Parameters
    • New Functions
    • New stream wrappers
    • New stream filters
    • New Class Constants
    • New Methods
    • New Extensions
    • Removed Extensions
    • Other changes to extensions
    • New Classes
    • New Global Constants
    • Changes to INI file handling
    • Other changes
  • Migrating from PHP 5.1.x to PHP 5.2.x
    • What has changed in PHP 5.2.x
    • Backward Incompatible Changes
    • New Error Messages
    • Changes in PHP datetime support
    • New Parameters
    • New Functions
    • New Methods
    • Removed Extensions
    • New Extensions
    • New Classes
    • New Global Constants
    • New Class Constants
    • New INI Configuration Directives
    • Error Reporting
    • Other Enhancements
  • Migrating from PHP 5.0.x to PHP 5.1.x
    • Key PHP 5.1.x features
    • Changes in reference handling
    • Reading []
    • Integer values in function parameters
    • Class and object changes
    • Extensions
    • Date/time support
    • Changes in database support
    • Checking for E_STRICT
  • Migrating from PHP 4 to PHP 5.0.x
    • What has changed in PHP 5.0.x
    • Backward Incompatible Changes
    • CLI and CGI
    • Migrating Configuration Files
    • New Functions
    • New Directives
    • Databases
    • New Object Model
    • Error Reporting
  • Debugging in PHP
    • About debugging in PHP
  • Configure options
    • List of core configure options
  • php.ini directives
    • List of php.ini directives
    • List of php.ini sections
    • Description of core php.ini directives
  • Extension List/Categorization
    • Alphabetical
    • Membership
    • State
  • List of Function Aliases
  • List of Reserved Words
    • List of Keywords
    • Predefined Classes
    • Predefined Constants
    • List of other reserved words
  • List of Resource Types
  • List of Available Filters
    • String Filters
    • Conversion Filters
    • Compression Filters
    • Encryption Filters
  • List of Supported Socket Transports
    • Internet Domain: TCP, UDP, SSL, and TLS
    • Unix Domain: Unix and UDG
  • PHP type comparison tables
  • List of Parser Tokens
  • Userland Naming Guide
    • Global Namespace
    • Rules
    • Tips
  • About the manual
    • Formats
    • About user notes
    • How to read a function definition (prototype)
    • PHP versions documented in this manual
    • How to find more information about PHP
    • How to help improve the documentation
    • How we generate the formats
    • Translations
  • Creative Commons Attribution 3.0
  • Index listing
    • Function and Method listing
    • Example listing
  • Changelog


History of PHP and Related Projects

Table of Contents

  • History of PHP
  • History of PHP related projects
  • Books about PHP
  • Publications about PHP

PHP has come a long way since its birth in the mid-1990's. From humble beginnings to becoming one of the most prominent languages powering the web, the evolution of PHP is a geek's fairy tale. Mind you, such explosive growth was no easy task. Those of you interested in briefly seeing how PHP grew to become what it is today, read on. If you'd like to touch a piece of Internet history, you can find old releases of PHP in the » PHP Museum.


History of PHP

PHP Tools, FI, Construction Kit, and PHP/FI

PHP as it's known today is actually the successor to a product named PHP/FI. Created in 1994 by Rasmus Lerdorf, the very first incarnation of PHP was a simple set of Common Gateway Interface (CGI) binaries written in the C programming language. Originally used for tracking visits to his online resume, he named the suite of scripts "Personal Home Page Tools," more frequently referenced as "PHP Tools." Over time, more functionality was desired, and Rasmus rewrote PHP Tools, producing a much larger and richer implementation. This new model was capable of database interaction and more, providing a framework upon which users could develop simple dynamic web applications such as guestbooks. In June of 1995, Rasmus » released the source code for PHP Tools to the public, which allowed developers to use it as they saw fit. This also permitted - and encouraged - users to provide fixes for bugs in the code, and to generally improve upon it.

In September of that year, Rasmus expanded upon PHP and - for a short time - actually dropped the PHP name. Now referring to the tools as FI (short for "Forms Interpreter"), the new implementation included some of the basic functionality of PHP as we know it today. It had Perl-like variables, automatic interpretation of form variables, and HTML embedded syntax. The syntax itself was similar to that of Perl, albeit much more limited, simple, and somewhat inconsistent. In fact, to embed the code into an HTML file, developers had to use HTML comments. Though this method was not entirely well-received, FI continued to enjoy growth and acceptance as a CGI tool --- but still not quite as a language. However, this began to change the following month; in October, 1995, Rasmus released a complete rewrite of the code. Bringing back the PHP name, it was now (briefly) named "Personal Home Page Construction Kit," and was the first release to boast what was, at the time, considered an advanced scripting interface. The language was deliberately designed to resemble C in structure, making it an easy adoption for developers familiar with C, Perl, and similar languages. Having been thus far limited to UNIX and POSIX-compliant systems, the potential for a Windows NT implementation was being explored.

The code got another complete makeover, and in April of 1996, combining the names of past releases, Rasmus introduced PHP/FI. This second-generation implementation began to truly evolve PHP from a suite of tools into a programming language in its own right. It included built-in support for DBM, mSQL, and Postgres95 databases, cookies, user-defined function support, and much more. That June, PHP/FI was given a version 2.0 status. An interesting fact about this, however, is that there was only one single full version of PHP 2.0. When it finally graduated from beta status in November, 1997, the underlying parsing engine was already being entirely rewritten.

Though it lived a short development life, it continued to enjoy a growing popularity in still-young world of web development. In 1997 and 1998, PHP/FI had a cult of several thousand users around the world. A Netcraft survey as of May, 1998, indicated that nearly 60,000 domains reported having headers containing "PHP", indicating that the host server did indeed have it installed. This number equated to approximately 1% of all domains on the Internet at the time. Despite these impressive figures, the maturation of PHP/FI was doomed to limitations; while there were several minor contributors, it was still primarily developed by an individual.

Example #1 Example PHP/FI Code

<!--include /text/header.html-->

<!--getenv HTTP_USER_AGENT-->
<!--ifsubstr $exec_result Mozilla-->
  Hey, you are using Netscape!<p>
<!--endif-->

<!--sql database select * from table where user='$username'-->
<!--ifless $numentries 1-->
  Sorry, that record does not exist<p>
<!--endif exit-->
  Welcome <!--$user-->!<p>
  You have <!--$index:0--> credits left in your account.<p>

<!--include /text/footer.html-->

PHP 3

PHP 3.0 was the first version that closely resembles PHP as it exists today. Finding PHP/FI 2.0 still inefficient and lacking features they needed to power an eCommerce application they were developing for a university project, Andi Gutmans and Zeev Suraski of Tel Aviv, Israel, began yet another complete rewrite of the underlying parser in 1997. Approaching Rasmus online, they discussed various aspects of the current implementation and their redevelopment of PHP. In an effort to improve the engine and start building upon PHP/FI's existing user base, Andi, Rasmus, and Zeev decided to collaborate in the development of a new, independent programming language. This entirely new language was released under a new name, that removed the implication of limited personal use that the PHP/FI 2.0 name held. It was renamed simply 'PHP', with the meaning becoming a recursive acronym - PHP: Hypertext Preprocessor.

One of the biggest strengths of PHP 3.0 was its strong extensibility features. In addition to providing end users with a mature interface for multiple databases, protocols, and APIs, the ease of extending the language itself attracted dozens of developers who submitted a variety of modules. Arguably, this was the key to PHP 3.0's tremendous success. Other key features introduced in PHP 3.0 included object-oriented programming support and a far more powerful and consistent language syntax.

In June, 1998, with many new developers from around the world joining the effort, PHP 3.0 was announced by the new PHP Development Team as the official successor to PHP/FI 2.0. Active development of PHP/FI 2.0, which had all-but ceased as of November of the previous year, was now officially ended. After roughly nine months of open public testing, when the announcement of the official release of PHP 3.0 came, it was already installed on over 70,000 domains around the world, and was no longer limited to POSIX-compliant operating systems. A relatively small share of the domains reporting PHP as installed were hosted on servers running Windows 95, 98, and NT, and Macintosh. At its peak, PHP 3.0 was installed on approximately 10% of the web servers on the Internet.

PHP 4

By the winter of 1998, shortly after PHP 3.0 was officially released, Andi Gutmans and Zeev Suraski had begun working on a rewrite of PHP's core. The design goals were to improve performance of complex applications, and improve the modularity of PHP's code base. Such applications were made possible by PHP 3.0's new features and support for a wide variety of third party databases and APIs, but PHP 3.0 was not designed to handle such complex applications efficiently.

The new engine, dubbed 'Zend Engine' (comprised of their first names, Zeev and Andi), met these design goals successfully, and was first introduced in mid 1999. PHP 4.0, based on this engine, and coupled with a wide range of additional new features, was officially released in May 2000, almost two years after its predecessor. In addition to the highly improved performance of this version, PHP 4.0 included other key features such as support for many more web servers, HTTP sessions, output buffering, more secure ways of handling user input and several new language constructs.

PHP 5

PHP 5 was released in July 2004 after long development and several pre-releases. It is mainly driven by its core, the Zend Engine 2.0 with a new object model and dozens of other new features.

PHP's development team includes dozens of developers, as well as dozens others working on PHP-related and supporting projects, such as PEAR, PECL, and documentation, and an underlying network infrastructure of well over one-hundred individual web servers on six of the seven continents of the world. Though only an estimate based upon statistics from previous years, it is safe to presume PHP is now installed on tens or even perhaps hundreds of millions of domains around the world.


History of PHP related projects

PEAR

» PEAR, the PHP Extension and Application Repository (originally, PHP Extension and Add-on Repository) is PHP's version of foundation classes, and may grow in the future to be one of the key ways to distribute PHP extensions among developers.

PEAR was born in discussions held in the PHP Developers' Meeting (PDM) held in January 2000 in Tel Aviv. It was created by Stig S. Bakken, and is dedicated to his first-born daughter, Malin Bakken.

Since early 2000, PEAR has grown to be a big, significant project with a large number of developers working on implementing common, reusable functionality for the benefit of the entire PHP community. PEAR today includes a wide variety of infrastructure foundation classes for database access, content caching, mathematical calculations, eCommerce and much more.

More information about PEAR can be found in » the manual.

PHP Quality Assurance Initiative

The » PHP Quality Assurance Initiative was set up in the summer of 2000 in response to criticism that PHP releases were not being tested well enough for production environments. The team now consists of a core group of developers with a good understanding of the PHP code base. These developers spend a lot of their time localizing and fixing bugs within PHP. In addition there are many other team members who test and provide feedback on these fixes using a wide variety of platforms.

PHP-GTK

» PHP-GTK is the PHP solution for writing client side GUI applications. Andrei Zmievski remembers the planing and creation process of PHP-GTK:

GUI programming has always been of my interests, and I found that Gtk+ is a very nice toolkit, except that programming with it in C is somewhat tedious. After witnessing PyGtk and GTK-Perl implementations, I decided to see if PHP could be made to interface with Gtk+, even minimally. Starting in August of 2000, I began to have a bit more free time so that is when I started experimenting. My main guideline was the PyGtk implementation as it was fairly feature complete and had a nice object-oriented interface. James Henstridge, the author of PyGtk, provided very helpful advice during those initial stages.

Hand-writing the interfaces to all the Gtk+ functions was out of the question, so I seized upon the idea of code-generator, similar to how PyGtk did it. The code generator is a PHP program that reads a set of .defs file containing the Gtk+ classes, constants, and methods information and generates C code that interfaces PHP with them. What cannot be generated automatically can be written by hand in .overrides file.

Working on the code generator and the infrastructure took some time, because I could spend little time on PHP-GTK during the fall of 2000. After I showed PHP-GTK to Frank Kromann, he got interested and started helping me out with code generator work and Win32 implementation. When we wrote the first Hello World program and fired it up, it was extremely exciting. It took a couple more months to get the project to a presentable condition and the initial version was released on March 1, 2001. The story promptly hit SlashDot.

Sensing that PHP-GTK might be extensive, I set up separate mailing lists and CVS repositories for it, as well as the gtk.php.net website with the help of Colin Viebrock. The documentation would also need to be done and James Moore came in to help with that.

Since its release PHP-GTK has been gaining popularity. We have our own documentation team, the manual keeps improving, people start writing extensions for PHP-GTK, and more and more exciting applications with it.


Books about PHP

As PHP grew, it began to be recognized as a world-wide popular development platform. One of the most interesting ways of seeing this trend was by observing the books about PHP that came out throughout the years.

To the best of our knowledge, the first book dedicated to PHP was 'PHP - tvorba interaktivních internetových aplikací' (PHP - Creating Interactive Internet Applications) - a Czech book published in April 1999, authored by Jirka Kosek. Next month followed a German book authored by Egon Schmid, Christian Cartus and Richard Blume. The first book in English about PHP was published shortly afterwards, and was 'Core PHP Programming' by Leon Atkinson. These books covered PHP 3.0.

While these books were the first of their kind - they were followed by a large number of books from a host of authors and publishers. There are over 400 books in English, over 100 books in German, and over 50 books in French or Spanish! In addition, you can find books about PHP in many other languages, including Korean, Japanese and Hebrew.

Clearly, this large number of books, written by different authors, published by many publishers, and their availability in so many languages - are a strong testimony for PHP's world-wide success.


Publications about PHP

To the best of our knowledge, the first article about PHP in a hard-copy magazine was published in the Czech mutation of Computerworld in the spring of 1998, and covered PHP 3.0. As with books, this was the first in a series of many articles published about PHP in various prominent magazines.

Articles about PHP appeared in Dr. Dobbs, Linux Enterprise, Linux Magazine and many more. Articles about migrating ASP-based applications to PHP under Windows even appear on Microsoft's very own MSDN!


Migrating from PHP 7.3.x to PHP 7.4.x

Table of Contents

  • New Features
  • New Classes and Interfaces
  • New Functions
  • New Global Constants
  • Backward Incompatible Changes
  • Deprecated Features
  • Removed Extensions
  • Other Changes
  • Windows Support

This new minor version brings with it a number of new features and a few incompatibilities that should be tested for before switching PHP versions in production environments.

See also the migration guides for PHP versions 7.0.x, 7.1.x, 7.2.x and 7.3.x.


New Features

PHP Core

Typed properties

Class properties now support type declarations.

<?php
class User {
    public int $id;
    public string $name;
}
?>
The above example will enforce that $user->id can only be assigned integer values and $user->name can only be assigned string values.

Arrow functions

Arrow functions provide a shorthand syntax for defining functions with implicit by-value scope binding.

<?php
$factor = 10;
$nums = array_map(fn($n) => $n * $factor, [1, 2, 3, 4]);
// $nums = array(10, 20, 30, 40);
?>

Limited return type covariance and argument type contravariance

The following code will now work:

<?php
class A {}
class B extends A {}

class Producer {
    public function method(): A {}
}
class ChildProducer extends Producer {
    public function method(): B {}
}
?>
Full variance support is only available if autoloading is used. Inside a single file only non-cyclic type references are possible, because all classes need to be available before they are referenced.

Null coalescing assignment operator

<?php
$array['key'] ??= computeDefault();
// is roughly equivalent to
if (!isset($array['key'])) {
    $array['key'] = computeDefault();
}
?>

Unpacking inside arrays

<?php
$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
// ['banana', 'orange', 'apple', 'pear', 'watermelon'];
?>

Numeric literal separator

Numeric literals can contain underscores between digits.

<?php
6.674_083e-11; // float
299_792_458;   // decimal
0xCAFE_F00D;   // hexadecimal
0b0101_1111;   // binary
?>

Weak references

Weak references allow the programmer to retain a reference to an object that does not prevent the object from being destroyed.

Allow exceptions from __toString()

Throwing exceptions from __toString() is now permitted. Previously this resulted in a fatal error. Existing recoverable fatal errors in string conversions have been converted to Error exceptions.

CURL

CURLFile now supports stream wrappers in addition to plain file names, if the extension has been built against libcurl >= 7.56.0.

Filter

The FILTER_VALIDATE_FLOAT filter now supports the min_range and max_range options, with the same semantics as FILTER_VALIDATE_INT.

FFI

FFI is a new extension, which provides a simple way to call native functions, access native variables, and create/access data structures defined in C libraries.

GD

Added the IMG_FILTER_SCATTER image filter to apply a scatter filter to images.

Hash

Added crc32c hash using Castagnoli's polynomial. This CRC32 variant is used by storage systems, such as iSCSI, SCTP, Btrfs and ext4.

Multibyte String

Added the mb_str_split() function, which provides the same functionality as str_split(), but operating on code points rather than bytes.

OPcache

Support for preloading code has been added.

Regular Expressions (Perl-Compatible)

The preg_replace_callback() and preg_replace_callback_array() functions now accept an additional flags argument, with support for the PREG_OFFSET_CAPTURE and PREG_UNMATCHED_AS_NULL flags. This influences the format of the matches array passed to to the callback function.

PDO

The username and password can now be specified as part of the PDO DSN for the mysql, mssql, sybase, dblib, firebird and oci drivers. Previously this was only supported by the pgsql driver. If a username/password is specified both in the constructor and the DSN, the constructor takes precedence.

It is now possible to escape question marks in SQL queries to avoid them being interpreted as parameter placeholders. Writing ?? allows sending a single question mark to the database and e.g. use the PostgreSQL JSON key exists (?) operator.

PDO_OCI

PDOStatement::getColumnMeta() is now available.

PDO_SQLite

PDOStatement::getAttribute(PDO::SQLITE_ATTR_READONLY_STATEMENT) allows checking whether the statement is read-only, i.e. if it doesn't modify the database.

PDO::setAttribute(PDO::SQLITE_ATTR_EXTENDED_RESULT_CODES, true) enables the use of SQLite3 extended result codes in PDO::errorInfo() and PDOStatement::errorInfo().

SQLite3

Added SQLite3::lastExtendedErrorCode() to fetch the last extended result code.

Added SQLite3::enableExtendedResultCodes($enable = true), which will make SQLite3::lastErrorCode() return extended result codes.

Standard

strip_tags() with array of tag names

strip_tags() now also accepts an array of allowed tags: instead of strip_tags($str, '<a><p>') you can now write strip_tags($str, ['a', 'p']).

Custom object serialization

A new mechanism for custom object serialization has been added, which uses two new magic methods: __serialize and __unserialize.

<?php
// Returns array containing all the necessary state of the object.
public function __serialize(): array;

// Restores the object state from the given data array.
public function __unserialize(array $data): void;
?>
The new serialization mechanism supersedes the Serializable interface, which will be deprecated in the future.

Array merge functions without arguments

array_merge() and array_merge_recursive() may now be called without any arguments, in which case they will return an empty array. This is useful in conjunction with the spread operator, e.g. array_merge(...$arrays).

proc_open() function

proc_open() now accepts an array instead of a string for the command. In this case the process will be opened directly (without going through a shell) and PHP will take care of any necessary argument escaping.

<?php
proc_open(['php', '-r', 'echo "Hello World\n";'], $descriptors, $pipes);
?>

proc_open() now supports redirect and null descriptors.

<?php
// Like 2>&1 on the shell
proc_open($cmd, [1 => ['pipe', 'w'], 2 => ['redirect', 1]], $pipes);
// Like 2>/dev/null or 2>nul on the shell
proc_open($cmd, [1 => ['pipe', 'w'], 2 => ['null']], $pipes);
?>

argon2i(d) without libargon

password_hash() now has the argon2i and argon2id implementations from the sodium extension when PHP is built without libargon.


  • « New Features
  • New Functions »
  • PHP Manual
  • Migrating from PHP 7.3.x to PHP 7.4.x
  • New Classes and Interfaces

New Classes and Interfaces

Reflection

  • ReflectionReference


New Functions

PHP Core

  • get_mangled_object_vars()
  • password_algos()
  • sapi_windows_set_ctrl_handler()

GD

  • imagecreatefromtga()

OpenSSL

  • openssl_x509_verify()

Process Control

  • pcntl_unshare()

SQLite3

  • SQLite3::backup()
  • SQLite3Stmt::getSQL()


New Global Constants

PHP Core

  • PHP_WINDOWS_EVENT_CTRL_C
  • PHP_WINDOWS_EVENT_CTRL_BREAK

Multibyte String

  • MB_ONIGURUMA_VERSION

Sockets

Added the following FreeBSD-specific socket options:

  • SO_LABEL
  • SO_PEERLABEL
  • SO_LISTENQLIMIT
  • SO_LISTENQLEN
  • SO_USER_COOKIE

Tidy

  • TIDY_TAG_ARTICLE
  • TIDY_TAG_ASIDE
  • TIDY_TAG_AUDIO
  • TIDY_TAG_BDI
  • TIDY_TAG_CANVAS
  • TIDY_TAG_COMMAND
  • TIDY_TAG_DATALIST
  • TIDY_TAG_DETAILS
  • TIDY_TAG_DIALOG
  • TIDY_TAG_FIGCAPTION
  • TIDY_TAG_FIGURE
  • TIDY_TAG_FOOTER
  • TIDY_TAG_HEADER
  • TIDY_TAG_HGROUP
  • TIDY_TAG_MAIN
  • TIDY_TAG_MARK
  • TIDY_TAG_MENUITEM
  • TIDY_TAG_METER
  • TIDY_TAG_NAV
  • TIDY_TAG_OUTPUT
  • TIDY_TAG_PROGRESS
  • TIDY_TAG_SECTION
  • TIDY_TAG_SOURCE
  • TIDY_TAG_SUMMARY
  • TIDY_TAG_TEMPLATE
  • TIDY_TAG_TIME
  • TIDY_TAG_TRACK
  • TIDY_TAG_VIDEO


Backward Incompatible Changes

PHP Core

Array-style access of non-arrays

Trying to use values of type null, bool, int, float or resource as an array (such as $null["key"]) will now generate a notice.

get_declared_classes() function

The get_declared_classes() function no longer returns anonymous classes that have not been instantiated yet.

fn keyword

fn is now a reserved keyword. In particular, it can no longer be used as a function or class name. It can still be used as a method or class constant name.

<?php tag at end of file

<?php at the end of the file (without trailing newline) will now be interpreted as an opening PHP tag. Previously it was interpreted either as a short opening tag followed by literal php and resulted in a syntax error (with short_open_tag=1) or was interpreted as a literal <?php string (with short_open_tag=0).

Stream wrappers

When using include/require on a stream, streamWrapper::stream_set_option() will be invoked with the STREAM_OPTION_READ_BUFFER option. Custom stream wrapper implementations may need to implement the streamWrapper::stream_set_option() method to avoid a warning (always returning FALSE is a sufficient implementation).

Serialization

The o serialization format has been removed. As it is never produced by PHP, this may only break unserialization of manually crafted strings.

Password algorithm constants

Password hashing algorithm identifiers are now nullable strings rather than integers.

  • PASSWORD_DEFAULT was int 1; now is NULL
  • PASSWORD_BCRYPT was int 1; now is string '2y'
  • PASSWORD_ARGON2I was int 2; now is string 'argon2i'
  • PASSWORD_ARGON2ID was int 3; now is string 'argon2id'

Applications correctly using the constants PASSWORD_DEFAULT, PASSWORD_BCRYPT, PASSWORD_ARGON2I, and PASSWORD_ARGON2ID will continue to function correctly.

htmlentities() function

htmlentities() will now raise a notice (instead of a strict standards warning) if it is used with an encoding for which only basic entity substitution is supported, in which case it is equivalent to htmlspecialchars().

fread() and fwrite() function

fread() and fwrite() will now return FALSE if the operation failed. Previously an empty string or 0 was returned. EAGAIN/EWOULDBLOCK are not considered failures.

These functions now also raise a notice on failure, such as when trying to write to a read-only file resource.

BCMath Arbitrary Precision Mathematics

BCMath functions will now warn if a non well-formed number is passed, such as "32foo". The argument will be interpreted as zero, as before.

CURL

Attempting to serialize a CURLFile class will now generate an exception. Previously the exception was only thrown on unserialization.

Using CURLPIPE_HTTP1 is deprecated, and is no longer supported as of cURL 7.62.0.

The $version parameter of curl_version() is deprecated. If any value not equal to the default CURLVERSION_NOW is passed, a warning is raised and the parameter is ignored.

Date and Time

Calling var_dump() or similar on a DateTime or DateTimeImmutable instance will no longer leave behind accessible properties on the object.

Comparison of DateInterval objects (using ==, <, and so on) will now generate a warning and always return FALSE. Previously all DateInterval objects were considered equal, unless they had properties.

Intl

The default parameter value of idn_to_ascii() and idn_to_utf8() is now INTL_IDNA_VARIANT_UTS46 instead of the deprecated INTL_IDNA_VARIANT_2003.

MySQLi

The embedded server functionality has been removed. It was broken since at least PHP 7.0.

The undocumented mysqli::$stat property has been removed in favor of mysqli::stat().

OpenSSL

The openssl_random_pseudo_bytes() function will now throw an exception in error situations, similar to random_bytes(). In particular, an Error is thrown if the number of requested bytes is less than or equal to zero, and an Exception is thrown if sufficient randomness cannot be gathered. The $crypto_strong output argument is guaranteed to always be TRUE if the function does not throw, so explicitly checking it is not necessary.

Regular Expressions (Perl-Compatible)

When PREG_UNMATCHED_AS_NULL mode is used, trailing unmatched capturing groups will now also be set to NULL (or [null, -1] if offset capture is enabled). This means that the size of the $matches will always be the same.

PHP Data Objects

Attempting to serialize a PDO or PDOStatement instance will now generate an Exception rather than a PDOException, consistent with other internal classes which do not support serialization.

Reflection

Reflection objects will now generate an exception if an attempt is made to serialize them. Serialization for reflection objects was never supported and resulted in corrupted reflection objects. It has been explicitly prohibited now.

Standard PHP Library (SPL)

Calling get_object_vars() on an ArrayObject instance will now always return the properties of the ArrayObject itself (or a subclass). Previously it returned the values of the wrapped array/object unless the ArrayObject::STD_PROP_LIST flag was specified.

Other affected operations are:

  • ReflectionObject::getProperties()
  • reset(), current(), etc. Use Iterator methods instead.
  • Potentially others working on object properties as a list.

(array) casts are not affected. They will continue to return either the wrapped array, or the ArrayObject properties, depending on whether the ArrayObject::STD_PROP_LIST flag is used.

SplPriorityQueue::setExtractFlags() will throw an exception if zero is passed. Previously this would generate a recoverable fatal error on the next extraction operation.

ArrayObject, ArrayIterator, SplDoublyLinkedList and SplObjectStorage now support the __serialize() and __unserialize() mechanism in addition to the Serializable interface. This means that serialization payloads created on older PHP versions can still be unserialized, but new payloads created by PHP 7.4 will not be understood by older versions.

Tokenizer

token_get_all() will now emit a T_BAD_CHARACTER token for unexpected characters instead of leaving behind holes in the token stream.


Deprecated Features

PHP Core

Nested ternary operators without explicit parentheses

Nested ternary operations must explicitly use parentheses to dictate the order of the operations. Previously, when used without parentheses, the left-associativity would not result in the expected behaviour in most cases.

<?php
1 ? 2 : 3 ? 4 : 5;   // deprecated
(1 ? 2 : 3) ? 4 : 5; // ok
1 ? 2 : (3 ? 4 : 5); // ok
?>

Array and string offset access using curly braces

The array and string offset access syntax using curly braces is deprecated. Use $var[$idx] instead of $var{$idx}.

(real) cast and is_real() function

The (real) cast is deprecated, use (float) instead.

The is_real() function is also deprecated, use is_float() instead.

Unbinding $this when $this is used

Unbinding $this of a non-static closure that uses $this is deprecated.

parent keyword without parent class

Using parent inside a class without a parent is deprecated, and will throw a compile-time error in the future. Currently an error will only be generated if/when the parent is accessed at run-time.

allow_url_include INI option

The allow_url_include ini directive is deprecated. Enabling it will generate a deprecation notice at startup.

Invalid characters in base conversion functions

Passing invalid characters to base_convert(), bindec(), octdec() and hexdec() will now generate a deprecation notice. The result will still be computed as if the invalid characters did not exist. Leading and trailing whitespace, as well as prefixes of type 0x (depending on base) continue to be allowed.

Using array_key_exists() on objects

Using array_key_exists() on objects is deprecated. Instead either isset() or property_exists() should be used.

Magic quotes functions

The get_magic_quotes_gpc() and get_magic_quotes_runtime() functions are deprecated. They always return FALSE.

hebrevc() function

The hebrevc() function is deprecated. It can be replaced with nl2br(hebrev($str)) or, preferably, the use of Unicode RTL support.

convert_cyr_string() function

The convert_cyr_string() function is deprecated. It can be replaced by one of mb_convert_string(), iconv() or UConverter.

money_format() function

The money_format() function is deprecated. It can be replaced by the intl NumberFormatter functionality.

ezmlm_hash() function

The ezmlm_hash() function is deprecated.

restore_include_path() function

The restore_include_path() function is deprecated. It can be replaced by ini_restore('include_path').

Implode with historical parameter order

Passing parameters to implode() in reverse order is deprecated, use implode($glue, $parts) instead of implode($parts, $glue).

COM

Importing type libraries with case-insensitive constant registering has been deprecated.

Filter

FILTER_SANITIZE_MAGIC_QUOTES is deprecated, use FILTER_SANITIZE_ADD_SLASHES instead.

Multibyte String

Passing a non-string pattern to mb_ereg_replace() is deprecated. Currently, non-string patterns are interpreted as ASCII codepoints. In PHP 8, the pattern will be interpreted as a string instead.

Passing the encoding as 3rd parameter to mb_strrpos() is deprecated. Instead pass a 0 offset, and encoding as 4th parameter.

Lightweight Directory Access Protocol

ldap_control_paged_result_response() and ldap_control_paged_result() are deprecated. Pagination controls can be sent along with ldap_search() instead.

Reflection

Calls to ReflectionType::__toString() now generate a deprecation notice. This method has been deprecated in favor of ReflectionNamedType::getName() in the documentation since PHP 7.1, but did not throw a deprecation notice for technical reasons.

The export() methods on all Reflection classes are deprecated. Construct a Reflection object and convert it to string instead:

<?php
// ReflectionClass::export(Foo::class, false) is:
echo new ReflectionClass(Foo::class), "\n";

// $str = ReflectionClass::export(Foo::class, true) is:
$str = (string) new ReflectionClass(Foo::class);
?>

Socket

The AI_IDN_ALLOW_UNASSIGNED and AI_IDN_USE_STD3_ASCII_RULES flags for socket_addrinfo_lookup() are deprecated, due to an upstream deprecation in glibc.


Removed Extensions

These extensions have been moved to PECL and are no longer part of the PHP distribution. The PECL package versions of these extensions will be created according to user demand.

  • Firebird/Interbase - access to an InterBase and/or Firebird based database is still available with the PDO Firebird driver.
  • Recode
  • WDDX


Other Changes

Performance Improvements

PHP Core

A specialized VM opcode for the array_key_exists() function has been added, which improves performance of this function if it can be statically resolved. In namespaced code, this may require writing \array_key_exists() or explicitly importing the function.

Regular Expressions (Perl-Compatible)

When preg_match() in UTF-8 mode ("u" modifier) is repeatedly called on the same string (but possibly different offsets), it will only be checked for UTF-8 validity once.

Changes to INI File Handling

zend.exception_ignore_args is a new INI directive for including or excluding arguments from stack traces generated from exceptions.

opcache.preload_user is a new INI directive for specifying the user account under which preloading code is execute if it would otherwise be run as root (which is not allowed for security reasons).

Migration to pkg-config

A number of extensions have been migrated to exclusively use pkg-config for the detection of library dependencies. Generally, this means that instead of using --with-foo-dir=DIR or similar only --with-foo is used. Custom library paths can be specified either by adding additional directories to PKG_CONFIG_PATH or by explicitly specifying compilation options through FOO_CFLAGS and FOO_LIBS.

The following extensions and SAPIs are affected:

  • CURL:
    • --with-curl no longer accepts a directory.
  • Enchant:
    • --with-enchant no longer accepts a directory.
  • FPM:
    • --with-fpm-systemd now uses only pkg-config for libsystem checks. The libsystemd minimum required version is 209.
  • GD:
    • --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).
    • --with-png-dir has been removed. libpng is required.
    • --with-zlib-dir has been removed. zlib is required.
    • --with-freetype-dir becomes --with-freetype
    • --with-jpeg-dir becomes --with-jpeg
    • --with-webp-dir becomes --with-webp
    • --with-xpm-dir becomes --with-xpm
  • IMAP:
    • --with-kerberos-systemd no longer accepts a directory.
  • Intl:
    • --with-icu-dir has been removed. If --enable-intl is passed, then libicu is always required.
  • LDAP:
    • --with-ldap-sasl no longer accepts a directory.
  • Libxml:
    • --with-libxml-dir has been removed.
    • --enable-libxml becomes --with-libxml .
    • --with-libexpat-dir has been renamed to --with-expat and no longer accepts a directory.
  • Litespeed:
    • --with-litespeed becomes --enable-litespeed .
  • Mbstring:
    • --with-onig has been removed. Unless --disable-mbregex has been passed, libonig is required.
  • ODBC:
    • --with-iodbc no longer accepts a directory.
    • --with-unixODBC without a directory now uses pkg-config (preferred). Directory is still accepted for old versions without libodbc.pc.
  • OpenSSL:
    • --with-openssl no longer accepts a directory.
  • PCRE:
    • --with-pcre-regex has been removed. Instead --with-external-pcre is provided to opt into using an external PCRE library, rather than the bundled one.
  • PDO_SQLite:
    • --with-pdo-sqlite no longer accepts a directory.
  • Readline:
    • --with-libedit no longer accepts a directory.
  • Sodium:
    • --with-sodium no longer accepts a directory.
  • SQLite3:
    • --with-sqlite3 no longer accepts a directory.
  • XSL:
    • --with-xsl no longer accepts a directory.
  • Zip:
    • --with-libzip has been removed.
    • --enable-zip becomes --with-zip .

CSV escaping

fputcsv(),
fgetcsv(),
SplFileObject::fputcsv(),
SplFileObject::fgetcsv(), and
SplFileObject::setCsvControl()
now accept an empty string as $escape argument,
which disables the proprietary PHP escaping mechanism.

The behavior of str_getcsv() has been adjusted accordingly (formerly, an empty string was identical to using the default).

SplFileObject::getCsvControl() now may also return an empty string for the third array element, accordingly.

Data Filtering

The filter extension no longer exposes --with-pcre-dir for Unix builds and can now reliably be built as shared when using ./configure

GD

The behavior of imagecropauto() in the bundled libgd has been synced with that of system libgd:

  • IMG_CROP_DEFAULT is no longer falling back to IMG_CROP_SIDES
  • Threshold-cropping now uses the algorithm of system libgd

The default $mode parameter of imagecropauto() has been changed to IMG_CROP_DEFAULT; passing -1 is now deprecated.

imagescale() now supports aspect ratio preserving scaling to a fixed height by passing -1 as $new_width.

HASH Message Digest Framework

The hash extension cannot be disabled anymore and is always an integral part of any PHP build, similar to the date extension.

Intl

The intl extension now requires at least ICU 50.1.

ResourceBundle now implements Countable.

Lightweight Directory Access Protocol

Support for nsldap and umich_ldap has been removed.

Libxml

All libxml-based extensions now require libxml 2.7.6 or newer.

Multibyte String

The oniguruma library is no longer bundled with PHP, instead libonig needs to be available on the system. Alternatively --disable-mbregex can be used to disable the mbregex component.

OPcache

The --disable-opcache-file and --enable-opcache-file configure options have been removed in favor of the opcache.file_cache INI directive.

Password Hashing

The password_hash() and functions now accept nullable string and integer for $algo argument.

PEAR

Installation of PEAR (including PECL) is no longer enabled by default. It can be explicitly enabled using --with-pear . This option is deprecated and may be removed in the future.

Reflection

The numeric values of the modifier constants (IS_ABSTRACT, IS_DEPRECATED, IS_EXPLICIT_ABSTRACT, IS_FINAL, IS_IMPLICIT_ABSTRACT, IS_PRIVATE, IS_PROTECTED, IS_PUBLIC, and IS_STATIC) on the ReflectionClass, ReflectionFunction, ReflectionMethod, ReflectionObject, and ReflectionProperty classes have changed.

SimpleXML

SimpleXMLElement now implements Countable.

SQLite3

The bundled libsqlite has been removed. To build the SQLite3 extension a system libsqlite3 ≥ 3.7.4 is now required. To build the PDO_SQLite extension a system libsqlite3 ≥ 3.5.0 is now required.

Serialization and unserialization of SQLite3, SQLite3Stmt and SQLite3Result is now explicitly forbidden. Formerly, serialization of instances of these classes was possible, but unserialization yielded unusable objects.

The @param notation can now also be used to denote SQL query parameters.

Zip

The bundled libzip library has been removed. A system libzip >= 0.11 is now necessary to build the zip extension.


Windows Support

configure flags

configure now regards additional CFLAGS and LDFLAGS set as environment variables.

CTRL handling

CTRL+C and CTRL+BREAK on console can be caught by setting a handler function with sapi_windows_set_ctrl_handler().

proc_open() on Windows can be passed a "create_process_group" option. It is required if the child process is supposed to handle CTRL events.

OPcache

OPcache now supports an arbitrary number of separate caches per user via the the INI directive opcache.cache_id. All processes with the same cache ID and user share an OPcache instance.

stat

The stat implementation has been refactored.

  • An inode number is delivered and is based on the NTFS file index.
  • The device number is now based on the volume serial number.

Note that both values are derived from the system and provided as-is on 64-bit systems. On 32-bit systems, these values might overflow the 32-bit integer in PHP, so they're fake.

libsqlite3

libsqlite3 is no longer compiled statically into php_sqlite3.dll and php_pdo_sqlite.dll, but rather available as libsqlite3.dll. Refer to the installation instructions for SQLite3 and PDO_SQLITE, respectively.


Migrating from PHP 7.2.x to PHP 7.3.x

Table of Contents

  • New Features
  • New Functions
  • New Global Constants
  • Backward Incompatible Changes
  • Deprecated Features
  • Other Changes
  • Windows Support

This new minor version brings with it a number of new features and a few incompatibilities that should be tested for before switching PHP versions in production environments.

See also the migration guides for PHP versions 5.0.x, 5.1.x, 5.2.x, 5.3.x, 5.4.x, 5.5.x, 5.6.x, 7.0.x, 7.1.x and 7.2.x.


New Features

PHP Core

More Flexible Heredoc and Nowdoc Syntax

The closing marker for doc strings is no longer required to be followed by a semicolon or newline. Additionally the closing marker may be indented, in which case the indentation will be stripped from all lines in the doc string.

Array Destructuring supports Reference Assignments

Array destructuring now supports reference assignments using the syntax [&$a, [$b, &$c]] = $d. The same is also supported for list().

Instanceof Operator accepts Literals

instanceof now allows literals as the first operand, in which case the result is always FALSE.

CompileError Exception instead of some Compilation Errors

A new CompileError exception has been added, from which ParseError inherits. A small number of compilation errors will now throw a CompileError instead of generating a fatal error. Currently this only affects compilation errors that may be thrown by token_get_all() in TOKEN_PARSE mode, but more errors may be converted in the future.

Trailing Commas are allowed in Calls

Trailing commas in function and method calls are now allowed.

Argon2id Support

The --with-password-argon2[=dir] configure argument now provides support for both Argon2i and Argon2id hashes in the password_hash(), password_verify(), password_get_info(), and password_needs_rehash() functions. Passwords may be hashed and verified using the PASSWORD_ARGON2ID constant. Support for both Argon2i and Argon2id in the password_*() functions now requires PHP be linked against libargon2 reference library ≥ 20161029.

FastCGI Process Manager

New options have been added to customize the FPM logging:

log_limit
This global option can be used for setting the log limit for the logged line which allows to log messages longer than 1024 characters without wrapping. It also fixes various wrapping issues.
log_buffering
This global option allows an experimental logging without extra buffering.
decorate_workers_output
This pool option allows to disable the output decoration for workers output when catch_workers_output is enabled.

BC Math Functions

bcscale() can now also be used as getter to retrieve the current scale in use.

Lightweight Directory Access Protocol

Full support for LDAP Controls has been added to the LDAP querying functions and ldap_parse_result():

  • A $serverctrls parameter to send controls to the
server in ldap_add(),
ldap_mod_replace(), ldap_mod_add(),
ldap_mod_del(), ldap_rename(),
ldap_compare(), ldap_delete(),
ldap_modify_batch(),
ldap_search(), ldap_list() and
ldap_read() has been added.
  • The out parameter $serverctrls to get controls from the server in ldap_parse_result() has been added.
  • Support for LDAP_OPT_SERVER_CONTROLS and LDAP_OPT_CLIENT_CONTROLS in ldap_get_option() and ldap_set_option() has been fixed.

Multibyte String Functions

Full Case-Mapping and Case-Folding Support

Support for full case-mapping and case-folding has been added. Unlike simple case-mapping, full case-mapping may change the length of the string. For example:

<?php
mb_strtoupper("Straße");
// Produces STRAßE on PHP 7.2
// Produces STRASSE on PHP 7.3
?>
The different casing mapping and folding modes are available through mb_convert_case():
  • MB_CASE_LOWER (used by mb_strtolower())
  • MB_CASE_UPPER (used by mb_strtoupper())
  • MB_CASE_TITLE
  • MB_CASE_FOLD
  • MB_CASE_LOWER_SIMPLE
  • MB_CASE_UPPER_SIMPLE
  • MB_CASE_TITLE_SIMPLE
  • MB_CASE_FOLD_SIMPLE (used by case-insensitive operations)
Only unconditional, language agnostic full case-mapping is performed.

Case-Insensitive String Operations use Case-Folding

Case-insensitive string operations now use case-folding instead of case- mapping during comparisons. This means that more characters will be considered (case insensitively) equal now.

MB_CASE_TITLE performs Title-Case Conversion

mb_convert_case() with MB_CASE_TITLE now performs title-case conversion based on the Cased and CaseIgnorable derived Unicode properties. In particular this also improves handling of quotes and apostrophes.

Unicode 11 Support

The Multibyte String data tables have been updated for Unicode 11.

Long String Support

The Multibyte String Functions now correctly support strings larger than 2GB.

Performance Improvements

Performance of the Multibyte String extension has been significantly improved across the board. The largest improvements are in case conversion functions.

Named Captures Support

The mb_ereg_* functions now support named captures. Matching functions like mb_ereg() will now return named captures both using their group number and their name, similar to PCRE:

<?php
mb_ereg('(?<word>\w+)', '国', $matches);
// => [0 => "国", 1 => "国", "word" => "国"];
?>
Additionally, mb_ereg_replace() now supports the \k<> and \k'' notations to reference named captures in the replacement string:
<?php
mb_ereg_replace('\s*(?<word>\w+)\s*', "_\k<word>_\k'word'_", ' foo ');
// => "_foo_foo_"
?>
\k<> and \k'' can also be used for numbered references, which also works with group numbers greater than 9.

Readline

Support for the completion_append_character and completion_suppress_append options has been added to readline_info(). These options are only available if PHP is linked against libreadline (rather than libedit).


New Functions

PHP Core

  • array_key_first()
  • array_key_last()
  • gc_status()
  • hrtime()
  • is_countable()
  • net_get_interfaces()

FastCGI Process Manager

  • fpm_get_status()

Date and Time

  • DateTime::createFromImmutable()

GNU Multiple Precision

  • gmp_binomial()
  • gmp_kronecker()
  • gmp_lcm()
  • gmp_perfect_power()

Internationalization Functions

  • Normalizer::getRawDecomposition()
  • normalizer_get_raw_decomposition()
  • Spoofchecker::setRestrictionLevel()

Lightweight Directory Access Protocol

  • ldap_add_ext()
  • ldap_bind_ext()
  • ldap_delete_ext()
  • ldap_exop_refresh()
  • ldap_mod_add_ext()
  • ldap_mod_replace_ext()
  • ldap_mod_del_ext()
  • ldap_rename_ext()

OpenSSL

  • openssl_pkey_derive()

Sockets

  • socket_wsaprotocol_info_export()
  • socket_wsaprotocol_info_import()
  • socket_wsaprotocol_info_release()


New Global Constants

PHP Core

  • PASSWORD_ARGON2ID

Client URL Library

  • CURLAUTH_BEARER
  • CURLAUTH_GSSAPI
  • CURLE_WEIRD_SERVER_REPLY
  • CURLINFO_APPCONNECT_TIME_T
  • CURLINFO_CONNECT_TIME_T
  • CURLINFO_CONTENT_LENGTH_DOWNLOAD_T
  • CURLINFO_CONTENT_LENGTH_UPLOAD_T
  • CURLINFO_FILETIME_T
  • CURLINFO_HTTP_VERSION
  • CURLINFO_NAMELOOKUP_TIME_T
  • CURLINFO_PRETRANSFER_TIME_T
  • CURLINFO_PROTOCOL
  • CURLINFO_PROXY_SSL_VERIFYRESULT
  • CURLINFO_REDIRECT_TIME_T
  • CURLINFO_SCHEME
  • CURLINFO_SIZE_DOWNLOAD_T
  • CURLINFO_SIZE_UPLOAD_T
  • CURLINFO_SPEED_DOWNLOAD_T
  • CURLINFO_SPEED_UPLOAD_T
  • CURLINFO_STARTTRANSFER_TIME_T
  • CURLINFO_TOTAL_TIME_T
  • CURL_LOCK_DATA_CONNECT
  • CURL_LOCK_DATA_PSL
  • CURL_MAX_READ_SIZE
  • CURLOPT_ABSTRACT_UNIX_SOCKET
  • CURLOPT_DISALLOW_USERNAME_IN_URL
  • CURLOPT_DNS_SHUFFLE_ADDRESSES
  • CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS
  • CURLOPT_HAPROXYPROTOCOL
  • CURLOPT_KEEP_SENDING_ON_ERROR
  • CURLOPT_PRE_PROXY
  • CURLOPT_PROXY_CAINFO
  • CURLOPT_PROXY_CAPATH
  • CURLOPT_PROXY_CRLFILE
  • CURLOPT_PROXY_KEYPASSWD
  • CURLOPT_PROXY_PINNEDPUBLICKEY
  • CURLOPT_PROXY_SSLCERT
  • CURLOPT_PROXY_SSLCERTTYPE
  • CURLOPT_PROXY_SSL_CIPHER_LIST
  • CURLOPT_PROXY_SSLKEY
  • CURLOPT_PROXY_SSLKEYTYPE
  • CURLOPT_PROXY_SSL_OPTIONS
  • CURLOPT_PROXY_SSL_VERIFYHOST
  • CURLOPT_PROXY_SSL_VERIFYPEER
  • CURLOPT_PROXY_SSLVERSION
  • CURLOPT_PROXY_TLS13_CIPHERS
  • CURLOPT_PROXY_TLSAUTH_PASSWORD
  • CURLOPT_PROXY_TLSAUTH_TYPE
  • CURLOPT_PROXY_TLSAUTH_USERNAME
  • CURLOPT_REQUEST_TARGET
  • CURLOPT_SOCKS5_AUTH
  • CURLOPT_SSH_COMPRESSION
  • CURLOPT_SUPPRESS_CONNECT_HEADERS
  • CURLOPT_TIMEVALUE_LARGE
  • CURLOPT_TLS13_CIPHERS
  • CURLPROXY_HTTPS
  • CURLSSH_AUTH_GSSAPI
  • CURL_SSLVERSION_MAX_DEFAULT
  • CURL_SSLVERSION_MAX_NONE
  • CURL_SSLVERSION_MAX_TLSv1_0
  • CURL_SSLVERSION_MAX_TLSv1_1
  • CURL_SSLVERSION_MAX_TLSv1_2
  • CURL_SSLVERSION_MAX_TLSv1_3
  • CURL_SSLVERSION_TLSv1_3
  • CURL_VERSION_ALTSVC (as of PHP 7.3.6)
  • CURL_VERSION_ASYNCHDNS
  • CURL_VERSION_BROTLI
  • CURL_VERSION_CONV
  • CURL_VERSION_CURLDEBUG (as of PHP 7.3.6)
  • CURL_VERSION_DEBUG
  • CURL_VERSION_GSSAPI
  • CURL_VERSION_GSSNEGOTIATE
  • CURL_VERSION_HTTPS_PROXY
  • CURL_VERSION_IDN
  • CURL_VERSION_LARGEFILE
  • CURL_VERSION_MULTI_SSL
  • CURL_VERSION_NTLM
  • CURL_VERSION_NTLM_WB
  • CURL_VERSION_PSL (as of PHP 7.3.6)
  • CURL_VERSION_SPNEGO
  • CURL_VERSION_SSPI
  • CURL_VERSION_TLSAUTH_SRP

Data Filtering

  • FILTER_SANITIZE_ADD_SLASHES

JavaScript Object Notation

  • JSON_THROW_ON_ERROR

Lightweight Directory Access Protocol

  • LDAP_CONTROL_ASSERT
  • LDAP_CONTROL_MANAGEDSAIT
  • LDAP_CONTROL_PROXY_AUTHZ
  • LDAP_CONTROL_SUBENTRIES
  • LDAP_CONTROL_VALUESRETURNFILTER
  • LDAP_CONTROL_PRE_READ
  • LDAP_CONTROL_POST_READ
  • LDAP_CONTROL_SORTREQUEST
  • LDAP_CONTROL_SORTRESPONSE
  • LDAP_CONTROL_PAGEDRESULTS
  • LDAP_CONTROL_AUTHZID_REQUEST
  • LDAP_CONTROL_AUTHZID_RESPONSE
  • LDAP_CONTROL_SYNC
  • LDAP_CONTROL_SYNC_STATE
  • LDAP_CONTROL_SYNC_DONE
  • LDAP_CONTROL_DONTUSECOPY
  • LDAP_CONTROL_PASSWORDPOLICYREQUEST
  • LDAP_CONTROL_PASSWORDPOLICYRESPONSE
  • LDAP_CONTROL_X_INCREMENTAL_VALUES
  • LDAP_CONTROL_X_DOMAIN_SCOPE
  • LDAP_CONTROL_X_PERMISSIVE_MODIFY
  • LDAP_CONTROL_X_SEARCH_OPTIONS
  • LDAP_CONTROL_X_TREE_DELETE
  • LDAP_CONTROL_X_EXTENDED_DN
  • LDAP_CONTROL_VLVREQUEST
  • LDAP_CONTROL_VLVRESPONSE

Multibyte String

  • MB_CASE_FOLD
  • MB_CASE_LOWER_SIMPLE
  • MB_CASE_UPPER_SIMPLE
  • MB_CASE_TITLE_SIMPLE
  • MB_CASE_FOLD_SIMPLE

OpenSSL

  • STREAM_CRYPTO_PROTO_SSLv3
  • STREAM_CRYPTO_PROTO_TLSv1_0
  • STREAM_CRYPTO_PROTO_TLSv1_1
  • STREAM_CRYPTO_PROTO_TLSv1_2

PostgreSQL

  • PGSQL_DIAG_SCHEMA_NAME
  • PGSQL_DIAG_TABLE_NAME
  • PGSQL_DIAG_COLUMN_NAME
  • PGSQL_DIAG_DATATYPE_NAME
  • PGSQL_DIAG_CONSTRAINT_NAME
  • PGSQL_DIAG_SEVERITY_NONLOCALIZED


Backward Incompatible Changes

PHP Core

Heredoc/Nowdoc Ending Label Interpretation

Due to the introduction of flexible heredoc/nowdoc syntax, doc strings that contain the ending label inside their body may cause syntax errors or change in interpretation. For example in:

<?php
$str = <<<FOO
abcdefg
   FOO
FOO;
?>
the indented occurrence of FOO did not previously have any special meaning. Now it will be interpreted as the end of the heredoc string and the following FOO; will cause a syntax error. This issue can always be resolved by choosing an ending label that does not occur within the contents of the string.

Continue Targeting Switch issues Warning

continue statements targeting switch control flow structures will now generate a warning. In PHP such continue statements are equivalent to break, while they behave as continue 2 in other languages.

<?php
while ($foo) {
    switch ($bar) {
      case "baz":
         continue;
         // Warning: "continue" targeting switch is equivalent to
         //          "break". Did you mean to use "continue 2"?
   }
}
?>

Strict Interpretation of Integer String Keys on ArrayAccess

Array accesses of type $obj["123"], where $obj implements ArrayAccess and "123" is an integer string literal will no longer result in an implicit conversion to integer, i.e., $obj->offsetGet("123") will be called instead of $obj->offsetGet(123). This matches existing behavior for non-literals. The behavior of arrays is not affected in any way, they continue to implicitly convert integeral string keys to integers.

Static Properties no longer separated by Reference Assignment

In PHP, static properties are shared between inheriting classes, unless the static property is explicitly overridden in a child class. However, due to an implementation artifact it was possible to separate the static properties by assigning a reference. This loophole has been fixed.

<?php
class Test {
    public static $x = 0;
}
class Test2 extends Test { }

Test2::$x = &$x;
$x = 1;

var_dump(Test::$x, Test2::$x);
// Previously: int(0), int(1)
// Now:        int(1), int(1)
?>

References returned by Array and Property Accesses are immediately unwrapped

References returned by array and property accesses are now unwrapped as part of the access. This means that it is no longer possible to modify the reference between the access and the use of the accessed value:

<?php
$arr = [1];
$ref =& $arr[0];
var_dump($arr[0] + ($arr[0] = 2));
// Previously: int(4), Now: int(3)
?>
This makes the behavior of references and non-references consistent. Please note that reading and writing a value inside a single expression remains undefined behavior and may change again in the future.

Argument Unpacking of Traversables with non-Integer Keys no longer supported

Argument unpacking stopped working with Traversables with non-integer keys. The following code worked in PHP 5.6-7.2 by accident.

<?php
function foo(...$args) {
    var_dump($args);
}
function gen() {
    yield 1.23 => 123;
}
foo(...gen());
?>

Miscellaneous

The ext_skel utility has been completely redesigned with new options and some old options removed. This is now written in PHP and has no external dependencies.

Support for BeOS has been dropped.

Exceptions thrown due to automatic conversion of warnings into exceptions in EH_THROW mode (e.g. some DateTime exceptions) no longer populate error_get_last() state. As such, they now work the same way as manually thrown exceptions.

TypeError now reports wrong types as int and bool instead of integer and boolean, respectively.

Undefined variables passed to compact() will now be reported as a notice.

getimagesize() and related functions now report the mime type of BMP images as image/bmp instead of image/x-ms-bmp, since the former has been registered with the IANA (see » RFC 7903).

stream_socket_get_name() will now return IPv6 addresses wrapped in brackets. For example "[::1]:1337" will be returned instead of "::1:1337".

BCMath Arbitrary Precision Mathematics

All warnings thrown by BCMath functions are now using PHP's error handling. Formerly some warnings have directly been written to stderr.

bcmul() and bcpow() now return numbers with the requested scale. Formerly, the returned numbers may have omitted trailing decimal zeroes.

IMAP, POP3 and NNTP

rsh/ssh logins are disabled by default. Use imap.enable_insecure_rsh if you want to enable them. Note that the IMAP library does not filter mailbox names before passing them to the rsh/ssh command, thus passing untrusted data to this function with rsh/ssh enabled is insecure.

Multibyte String

Due to added support for named captures, mb_ereg_*() patterns using named captures will behave differently. In particular named captures will be part of matches and mb_ereg_replace() will interpret additional syntax. See Named Captures for more information.

MySQL Improved Extension

Prepared statements now properly report the fractional seconds for DATETIME, TIME and TIMESTAMP columns with decimals specifier (e.g. TIMESTAMP(6) when using microseconds). Formerly, the fractional seconds part was simply omitted from the returned values.

MySQL Functions (PDO_MYSQL)

Prepared statements now properly report the fractional seconds for DATETIME, TIME and TIMESTAMP columns with decimals specifier (e.g. TIMESTAMP(6) when using microseconds). Formerly, the fractional seconds part was simply omitted from the returned values. Please note that this only affects the usage of PDO_MYSQL with emulated prepares turned off (e.g. using the native preparation functionality). Statements using connections having PDO::ATTR_EMULATE_PREPARES=TRUE (which is the default) were not affected by the bug fixed and have already been getting the proper fractional seconds values from the engine.

Reflection

Reflection export to string now uses int and bool instead of integer and boolean, respectively.

Standard PHP Library (SPL)

If an SPL autoloader throws an exception, following autoloaders will not be executed. Previously all autoloaders were executed and exceptions were chained.

SimpleXML

Mathematic operations involving SimpleXML objects will now treat the text as an integer or float, whichever is more appropriate. Previously values were treated as integers unconditionally.


Deprecated Features

PHP Core

Case-Insensitive Constants

The declaration of case-insensitive constants has been deprecated. Passing TRUE as the third argument to define() will now generate a deprecation warning. The use of case-insensitive constants with a case that differs from the declaration is also deprecated.

Namespaced assert()

Declaring a function called assert() inside a namespace is deprecated. The assert() function is subject to special handling by the engine, which may lead to inconsistent behavior when defining a namespaced function with the same name.

Searching Strings for non-string Needle

Passing a non-string needle to string search functions is deprecated. In the future the needle will be interpreted as a string instead of an ASCII codepoint. Depending on the intended behavior, you should either explicitly cast the needle to string or perform an explicit call to chr(). The following functions are affected:

  • strpos()
  • strrpos()
  • stripos()
  • strripos()
  • strstr()
  • strchr()
  • strrchr()
  • stristr()

Strip-Tags Streaming

The fgetss() function and the string.strip_tags stream filter have been deprecated. This also affects the SplFileObject::fgetss() method and gzgetss() function.

Data Filtering

The explicit usage of the constants FILTER_FLAG_SCHEME_REQUIRED and FILTER_FLAG_HOST_REQUIRED is now deprecated; both are implied for FILTER_VALIDATE_URL anyway.

Image Processing and GD

image2wbmp() has been deprecated.

Internationalization Functions

Usage of the Normalizer::NONE form throws a deprecation warning, if PHP is linked with ICU ≥ 56.

Multibyte String

The following undocumented mbereg_*() aliases have been deprecated. Use the corresponding mb_ereg_*() variants instead.

  • mbregex_encoding()
  • mbereg()
  • mberegi()
  • mbereg_replace()
  • mberegi_replace()
  • mbsplit()
  • mbereg_match()
  • mbereg_search()
  • mbereg_search_pos()
  • mbereg_search_regs()
  • mbereg_search_init()
  • mbereg_search_getregs()
  • mbereg_search_getpos()
  • mbereg_search_setpos()

ODBC and DB2 Functions (PDO_ODBC)

The pdo_odbc.db2_instance_name ini setting has been formally deprecated. It is deprecated in the documentation as of PHP 5.1.1.


Other Changes

PHP Core

Set(raw)cookie accepts $option Argument

setcookie() and setrawcookie() now also support the following signature:

setcookie ( string $name [, string $value = "" [, array $options = [] ]] ) : bool
where $options is an associative array which may have any of the keys "expires", "path", "domain", "secure", "httponly" and "samesite".

New Syslog ini Directives

The following ini Directives have been added to customize logging, if error_log is set to syslog:

syslog.facility
Specifies what type of program is logging the message.
syslog.filter
Specifies the filter type to filter the logged messages. There are three supported filter types - all, no-ctrl and ascii.
syslog.ident
Specifies the ident string which is prepended to every message.

Garbage Collection

The cyclic GC has been enhanced, which may result in considerable performance improvements.

Miscellaneous

var_export() now exports stdClass objects as an array cast to an object ((object) array( ... )), rather than using the nonexistent method stdClass::__setState().

debug_zval_dump() was changed to display recursive arrays and objects in the same way as var_dump(). Now, it doesn't display them twice.

array_push() and array_unshift() can now also be called with a single argument, which is particularly convenient wrt. the spread operator.

Interactive PHP Debugger

The unused constants PHPDBG_FILE, PHPDBG_METHOD, PHPDBG_LINENO and PHPDBG_FUNC have been removed.

FastCGI Process Manager

The getallheaders() function is now also available.

Client URL Library

libcurl ≥ 7.15.5 is now required.

Data Filtering

FILTER_VALIDATE_FLOAT now also supports a thousand option, which defines the set of allowed thousand separator chars. The default ("',.") is fully backward compatible with former PHP versions.

FILTER_SANITIZE_ADD_SLASHES has been added as an alias of the magic_quotes filter (FILTER_SANITIZE_MAGIC_QUOTES). The magic_quotes filter is subject to removal in future versions of PHP.

FTP

The default transfer mode has been changed to binary.

Internationalization Functions

Normalizer::NONE is deprecated, when PHP is linked with ICU ≥ 56.

Introduced Normalizer::FORM_KC_CF as Normalizer::normalize() argument for NFKC_Casefold normalization; available when linked with ICU ≥ 56.

JavaScript Object Notation

A new flag has been added, JSON_THROW_ON_ERROR, which can be used with json_decode() or json_encode() and causes these functions to throw the new JsonException upon an error, instead of setting the global error state that is retrieved with json_last_error() and json_last_error_msg(). JSON_PARTIAL_OUTPUT_ON_ERROR takes precedence over JSON_THROW_ON_ERROR.

Multibyte String

The configuration option --with-libmbfl is no longer available.

ODBC (Unified)

Support for ODBCRouter and Birdstep including the birdstep.max_links ini directive has been removed.

OPcache

The opcache.inherited_hack ini directive has been removed. The value has already been ignored since PHP 5.3.0.

OpenSSL

The min_proto_version and max_proto_version ssl stream options as well as related constants for possible TLS protocol values have been added.

Regular Expressions (Perl-Compatible)

The PCRE extension has been upgraded to PCRE2, which may cause minor behavioral changes (for instance, character ranges in classes are now more strictly interpreted), and augments the existing regular expression syntax.

preg_quote() now also escapes the '#' character.

Microsoft SQL Server and Sybase Functions (PDO_DBLIB)

The attribute PDO::DBLIB_ATTR_SKIP_EMPTY_ROWSETS to enable automatic skipping of empty rowsets has been added.

The PDO::DBLIB_ATTR_TDS_VERSION attribute which exposes the TDS version has been added.

DATETIME2 columns are now treated like DATETIME columns.

SQLite Functions (PDO_SQLITE)

SQLite3 databases can now be opened in read-only mode by setting the new PDO::SQLITE_ATTR_OPEN_FLAGS attribute to PDO::SQLITE_READONLY.

Session Handling

session_set_cookie_params() now also supports the following signature:

session_set_cookie_params ( array $options ) : bool
where $options is an associative array which may have any of the keys "lifetime", "path", "domain", "secure", "httponly" and "samesite". Accordingly, the return value of session_get_cookie_params() now also has an element with the key "samesite". Furthermore, the new session.cookie_samesite ini option to set the default of the SameSite directive for cookies has been added. It defaults to "" (empty string), so no SameSite directive is set. Can be set to "Lax" or "Strict", which sets the respective SameSite directive.

Tidy

Building against » tidyp is now also supported transparently. Since tidyp offers no API to get the release date, tidy_get_release() and tidy::getRelease() return 'unknown' in this case.

XML Parser

The return value of the xml_set_external_entity_ref_handler() callback is no longer ignored if the extension has been built against libxml. Formerly, the return value has been ignored, and parsing did never stop.

Zip

Building against the bundled libzip is discouraged, but still possible by adding --without-libzip to the configuration.

Zlib Compression

The zlib/level context option for the compress.zlib wrapper to facilitate setting the desired compression level has been added.


Windows Support

PHP Core

More POSIX Conforming File Deletion

File descriptors are opened in shared read/write/delete mode by default. This effectively maps the POSIX semantics and allows to delete files with handles in use. It is not 100% same, some platform differences still persist. After the deletion, the filename entry is blocked, until all the opened handles to it are closed.


Migrating from PHP 7.1.x to PHP 7.2.x

Table of Contents

  • New features
  • New functions
  • New global constants
  • Backward incompatible changes
  • Deprecated features in PHP 7.2.x
  • Other changes

This new minor version brings with it a number of new features and a few incompatibilities that should be tested for before switching PHP versions in production environments.

See also the migration guides for PHP versions 5.0.x, 5.1.x, 5.2.x, 5.3.x, 5.4.x, 5.5.x, 5.6.x, 7.0.x and 7.1.x.


New features

New object type

A new type, object, has been introduced that can be used for (contravariant) parameter typing and (covariant) return typing of any objects.

<?php

function test(object $obj) : object
{
    return new SplQueue();
}

test(new StdClass());

Extension loading by name

Shared extensions no longer require their file extension (.so for Unix or .dll for Windows) to be specified. This is enabled in the php.ini file, as well as in the dl() function.

Abstract method overriding

Abstract methods can now be overridden when an abstract class extends another abstract class.

<?php

abstract class A
{
    abstract function test(string $s);
}
abstract class B extends A
{
    // overridden - still maintaining contravariance for parameters and covariance for return
    abstract function test($s) : int;
}

Sodium is now a core extension

The modern Sodium cryptography library has now become a core extension in PHP.

For a complete function reference, see the Sodium chapter.

Password hashing with Argon2

Argon2 has been added to the password hashing API, where the following constants have been exposed:

  • PASSWORD_ARGON2I
  • PASSWORD_ARGON2_DEFAULT_MEMORY_COST
  • PASSWORD_ARGON2_DEFAULT_TIME_COST
  • PASSWORD_ARGON2_DEFAULT_THREADS

Extended string types for PDO

PDO's string type has been extended to support the national character type when emulating prepares. This has been done with the following constants:

  • PDO::PARAM_STR_NATL
  • PDO::PARAM_STR_CHAR
  • PDO::ATTR_DEFAULT_STR_PARAM

These constants are utilised by bitwise OR'ing them with PDO::PARAM_STR:

<?php

$db->quote('über', PDO::PARAM_STR | PDO::PARAM_STR_NATL);

Additional emulated prepares debugging information for PDO

The PDOStatement::debugDumpParams() method has been updated to include the SQL being sent to the DB, where the full, raw query (including the replaced placeholders with their bounded values) will be shown. This has been added to aid with debugging emulated prepares (and so it will only be available when emulated prepares are turned on).

Support for extended operations in LDAP

Support for EXOP has been added to the LDAP extension. This has been done by exposing the following functions and constants:

  • ldap_parse_exop()
  • ldap_exop()
  • ldap_exop_passwd()
  • ldap_exop_whoami()
  • LDAP_EXOP_START_TLS
  • LDAP_EXOP_MODIFY_PASSWD
  • LDAP_EXOP_REFRESH
  • LDAP_EXOP_WHO_AM_I
  • LDAP_EXOP_TURN

Address Information additions to the Sockets extension

The sockets extension now has the ability to lookup address information, as well as connect to it, bind to it, and explain it. The following four functions have been added for this:

  • socket_addrinfo_lookup()
  • socket_addrinfo_connect()
  • socket_addrinfo_bind()
  • socket_addrinfo_explain()

Parameter type widening

Parameter types from overridden methods and from interface implementations may now be omitted. This is still in compliance with LSP, since parameters types are contravariant.

<?php

interface A
{
    public function Test(array $input);
}

class B implements A
{
    public function Test($input){} // type omitted for $input
}

Allow a trailing comma for grouped namespaces

A trailing comma can now be added to the group-use syntax introduced in PHP 7.0.

<?php

use Foo\Bar\{
    Foo,
    Bar,
    Baz,
};

proc_nice() support on Windows

The proc_nice() function is now supported on Windows.

pack() and unpack() endian support

The pack() and unpack() functions now support float and double in both little and big endian.

Enhancements to the EXIF extension

The EXIF extension has been updated to support a much larger range of formats. This means that their format specific tags are now properly translated when parsing images with the exif_read_data() function. The following new formats are now supported:

  • Samsung
  • DJI
  • Panasonic
  • Sony
  • Pentax
  • Minolta
  • Sigma/Foveon
  • AGFA
  • Kyocera
  • Ricoh
  • Epson

The EXIF functions exif_read_data() and exif_thumbnail() now support passing streams as their first argument.

New features in PCRE

  • The J modifier for setting PCRE_DUPNAMES has been added.

SQLite3 allows writing BLOBs

SQLite3::openBlob() now allows to open BLOB fields in write mode; formerly only read mode was supported.

Oracle OCI8 Transparent Application Failover Callbacks

Support for Oracle Database Transparent Application Failover (TAF) callbacks has been added. TAF allows PHP OCI8 applications to automatically reconnect to a preconfigured database when a connection is broken. The new TAF callback support allows PHP applications to monitor and control reconnection during failover.

Enhancements to the ZIP extension

Read and write support for encrypted archives has been added (requires libzip 1.2.0).

The ZipArchive class now implements the Countable interface.

The zip:// stream now accepts a 'password' context option.


New functions

PHP Core

  • stream_isatty()
  • sapi_windows_vt100_support()

SPL

  • spl_object_id()

DOM

  • DomNodeList::count()
  • DOMNamedNodeMap::count()

FTP

  • ftp_append()

GD

  • imagesetclip()
  • imagegetclip()
  • imageopenpolygon()
  • imageresolution()
  • imagecreatefrombmp()
  • imagebmp()

Hash

  • hash_hmac_algos()

LDAP

  • ldap_parse_exop()
  • ldap_exop()
  • ldap_exop_passwd()
  • ldap_exop_whoami()

Multibyte String

  • mb_chr()
  • mb_ord()
  • mb_scrub()

Oracle OCI8

  • oci_register_taf_callback()
  • oci_unregister_taf_callback()

Sockets

  • socket_addrinfo_lookup()
  • socket_addrinfo_connect()
  • socket_addrinfo_bind()
  • socket_addrinfo_explain()

Sodium

  • sodium_add()
  • sodium_bin2hex()
  • sodium_compare()
  • sodium_crypto_aead_aes256gcm_decrypt()
  • sodium_crypto_aead_aes256gcm_encrypt()
  • sodium_crypto_aead_aes256gcm_is_available()
  • sodium_crypto_aead_aes256gcm_keygen()
  • sodium_crypto_aead_chacha20poly1305_decrypt()
  • sodium_crypto_aead_chacha20poly1305_encrypt()
  • sodium_crypto_aead_chacha20poly1305_ietf_decrypt()
  • sodium_crypto_aead_chacha20poly1305_ietf_encrypt()
  • sodium_crypto_aead_chacha20poly1305_ietf_keygen()
  • sodium_crypto_aead_chacha20poly1305_keygen()
  • sodium_crypto_auth_keygen()
  • sodium_crypto_auth_verify()
  • sodium_crypto_auth()
  • sodium_crypto_box_keypair_from_secretkey_and_publickey()
  • sodium_crypto_box_keypair()
  • sodium_crypto_box_open()
  • sodium_crypto_box_publickey_from_secretkey()
  • sodium_crypto_box_publickey()
  • sodium_crypto_box_seal_open()
  • sodium_crypto_box_seal()
  • sodium_crypto_box_secretkey()
  • sodium_crypto_box_seed_keypair()
  • sodium_crypto_box()
  • sodium_crypto_generichash_final()
  • sodium_crypto_generichash_init()
  • sodium_crypto_generichash_keygen()
  • sodium_crypto_generichash_update()
  • sodium_crypto_generichash()
  • sodium_crypto_kdf_derive_from_key()
  • sodium_crypto_kdf_keygen()
  • sodium_crypto_kx_client_session_keys()
  • sodium_crypto_kx_keypair()
  • sodium_crypto_kx_publickey()
  • sodium_crypto_kx_secretkey()
  • sodium_crypto_kx_seed_keypair()
  • sodium_crypto_kx_server_session_keys()
  • sodium_crypto_pwhash_scryptsalsa208sha256_str_verify()
  • sodium_crypto_pwhash_scryptsalsa208sha256_str()
  • sodium_crypto_pwhash_scryptsalsa208sha256()
  • sodium_crypto_pwhash_str_verify()
  • sodium_crypto_pwhash_str()
  • sodium_crypto_pwhash()
  • sodium_crypto_scalarmult_base()
  • sodium_crypto_scalarmult()
  • sodium_crypto_secretbox_keygen()
  • sodium_crypto_secretbox_open()
  • sodium_crypto_secretbox()
  • sodium_crypto_shorthash_keygen()
  • sodium_crypto_shorthash()
  • sodium_crypto_sign_detached()
  • sodium_crypto_sign_ed25519_pk_to_curve25519()
  • sodium_crypto_sign_ed25519_sk_to_curve25519()
  • sodium_crypto_sign_keypair_from_secretkey_and_publickey()
  • sodium_crypto_sign_keypair()
  • sodium_crypto_sign_open()
  • sodium_crypto_sign_publickey_from_secretkey()
  • sodium_crypto_sign_publickey()
  • sodium_crypto_sign_secretkey()
  • sodium_crypto_sign_seed_keypair()
  • sodium_crypto_sign_verify_detached()
  • sodium_crypto_sign()
  • sodium_crypto_stream_keygen()
  • sodium_crypto_stream_xor()
  • sodium_crypto_stream()
  • sodium_hex2bin()
  • sodium_increment()
  • sodium_memcmp()
  • sodium_memzero()
  • sodium_pad()
  • sodium_unpad()

ZIP

  • ZipArchive::count()
  • ZipArchive::setEncryptionName()
  • ZipArchive::setEncryptionIndex()


New global constants

PHP Core

  • PHP_FLOAT_DIG
  • PHP_FLOAT_EPSILON
  • PHP_FLOAT_MIN
  • PHP_FLOAT_MAX
  • PHP_OS_FAMILY

File Information

  • FILEINFO_EXTENSION

JSON

  • JSON_INVALID_UTF8_IGNORE
  • JSON_INVALID_UTF8_SUBSTITUTE

GD

  • IMG_EFFECT_MULTIPLY
  • IMG_BMP

LDAP

  • LDAP_EXOP_START_TLS
  • LDAP_EXOP_MODIFY_PASSWD
  • LDAP_EXOP_REFRESH
  • LDAP_EXOP_WHO_AM_I
  • LDAP_EXOP_TURN

Password Hashing

  • PASSWORD_ARGON2I
  • PASSWORD_ARGON2_DEFAULT_MEMORY_COST
  • PASSWORD_ARGON2_DEFAULT_TIME_COST
  • PASSWORD_ARGON2_DEFAULT_THREADS

PCRE

  • PREG_UNMATCHED_AS_NULL

PDO

  • PDO::PARAM_STR_NATL
  • PDO::PARAM_STR_CHAR
  • PDO::ATTR_DEFAULT_STR_PARAM

Sodium

  • SODIUM_LIBRARY_VERSION
  • SODIUM_LIBRARY_MAJOR_VERSION
  • SODIUM_LIBRARY_MINOR_VERSION
  • SODIUM_CRYPTO_AEAD_AES256GCM_KEYBYTES
  • SODIUM_CRYPTO_AEAD_AES256GCM_NSECBYTES
  • SODIUM_CRYPTO_AEAD_AES256GCM_NPUBBYTES
  • SODIUM_CRYPTO_AEAD_AES256GCM_ABYTES
  • SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES
  • SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_NSECBYTES
  • SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES
  • SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_ABYTES
  • SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_KEYBYTES
  • SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_NSECBYTES
  • SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES
  • SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_ABYTES
  • SODIUM_CRYPTO_AUTH_BYTES
  • SODIUM_CRYPTO_AUTH_KEYBYTES
  • SODIUM_CRYPTO_BOX_SEALBYTES
  • SODIUM_CRYPTO_BOX_SECRETKEYBYTES
  • SODIUM_CRYPTO_BOX_PUBLICKEYBYTES
  • SODIUM_CRYPTO_BOX_KEYPAIRBYTES
  • SODIUM_CRYPTO_BOX_MACBYTES
  • SODIUM_CRYPTO_BOX_NONCEBYTES
  • SODIUM_CRYPTO_BOX_SEEDBYTES
  • SODIUM_CRYPTO_KDF_BYTES_MIN
  • SODIUM_CRYPTO_KDF_BYTES_MAX
  • SODIUM_CRYPTO_KDF_CONTEXTBYTES
  • SODIUM_CRYPTO_KDF_KEYBYTES
  • SODIUM_CRYPTO_KX_SEEDBYTES
  • SODIUM_CRYPTO_KX_SESSIONKEYBYTES
  • SODIUM_CRYPTO_KX_PUBLICKEYBYTES
  • SODIUM_CRYPTO_KX_SECRETKEYBYTES
  • SODIUM_CRYPTO_KX_KEYPAIRBYTES
  • SODIUM_CRYPTO_GENERICHASH_BYTES
  • SODIUM_CRYPTO_GENERICHASH_BYTES_MIN
  • SODIUM_CRYPTO_GENERICHASH_BYTES_MAX
  • SODIUM_CRYPTO_GENERICHASH_KEYBYTES
  • SODIUM_CRYPTO_GENERICHASH_KEYBYTES_MIN
  • SODIUM_CRYPTO_GENERICHASH_KEYBYTES_MAX
  • SODIUM_CRYPTO_PWHASH_ALG_ARGON2I13
  • SODIUM_CRYPTO_PWHASH_ALG_DEFAULT
  • SODIUM_CRYPTO_PWHASH_SALTBYTES
  • SODIUM_CRYPTO_PWHASH_STRPREFIX
  • SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE
  • SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE
  • SODIUM_CRYPTO_PWHASH_OPSLIMIT_MODERATE
  • SODIUM_CRYPTO_PWHASH_MEMLIMIT_MODERATE
  • SODIUM_CRYPTO_PWHASH_OPSLIMIT_SENSITIVE
  • SODIUM_CRYPTO_PWHASH_MEMLIMIT_SENSITIVE
  • SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_SALTBYTES
  • SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_STRPREFIX
  • SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_INTERACTIVE
  • SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_INTERACTIVE
  • SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_SENSITIVE
  • SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_SENSITIVE
  • SODIUM_CRYPTO_SCALARMULT_BYTES
  • SODIUM_CRYPTO_SCALARMULT_SCALARBYTES
  • SODIUM_CRYPTO_SHORTHASH_BYTES
  • SODIUM_CRYPTO_SHORTHASH_KEYBYTES
  • SODIUM_CRYPTO_SECRETBOX_KEYBYTES
  • SODIUM_CRYPTO_SECRETBOX_MACBYTES
  • SODIUM_CRYPTO_SECRETBOX_NONCEBYTES
  • SODIUM_CRYPTO_SIGN_BYTES
  • SODIUM_CRYPTO_SIGN_SEEDBYTES
  • SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES
  • SODIUM_CRYPTO_SIGN_SECRETKEYBYTES
  • SODIUM_CRYPTO_SIGN_KEYPAIRBYTES
  • SODIUM_CRYPTO_STREAM_NONCEBYTES
  • SODIUM_CRYPTO_STREAM_KEYBYTES

Zip

  • ZipArchive::EM_NONE
  • ZipArchive::EM_AES_128
  • ZipArchive::EM_AES_192
  • ZipArchive::EM_AES_256


Backward incompatible changes

Prevent number_format() from returning negative zero

Previously, it was possible for the number_format() function to return -0. Whilst this is perfectly valid according to the IEEE 754 floating point specification, this oddity was not desirable for displaying formatted numbers in a human-readable form.

<?php

var_dump(number_format(-0.01)); // now outputs string(1) "0" instead of string(2) "-0"

Convert numeric keys in object and array casts

Numeric keys are now better handled when casting arrays to objects and objects to arrays (either from explicit casting or by settype()).

This means that integer (or stringy integer) keys from arrays being casted to objects are now accessible:

<?php

// array to object
$arr = [0 => 1];
$obj = (object)$arr;
var_dump(
    $obj,
    $obj->{'0'}, // now accessible
    $obj->{0} // now accessible
);

The above example will output:

object(stdClass)#1 (1) {
  ["0"]=>    // string key now, rather than integer key
  int(1)
}
int(1)
int(1)

And integer (or stringy integer) keys from objects being casted to arrays are now accessible:

<?php

// object to array
$obj = new class {
    public function __construct()
    {
        $this->{0} = 1;
    }
};
$arr = (array)$obj;
var_dump(
    $arr,
    $arr[0], // now accessible
    $arr['0'] // now accessible
);

The above example will output:

array(1) {
  [0]=>    // integer key now, rather than string key
  int(1)
}
int(1)
int(1)

Disallow passing NULL to get_class()

Previously, passing NULL to the get_class() function would output the name of the enclosing class. This behaviour has now been removed, where an E_WARNING will be output instead. To achieve the same behaviour as before, the argument should simply be omitted.

Warn when counting non-countable types

An E_WARNING will now be emitted when attempting to count() non-countable types (this includes the sizeof() alias function).

<?php

var_dump(
    count(null), // NULL is not countable
    count(1), // integers are not countable
    count('abc'), // strings are not countable
    count(new stdclass), // objects not implementing the Countable interface are not countable
    count([1,2]) // arrays are countable
);

The above example will output:

Warning: count(): Parameter must be an array or an object that implements Countable in %s on line %d

Warning: count(): Parameter must be an array or an object that implements Countable in %s on line %d

Warning: count(): Parameter must be an array or an object that implements Countable in %s on line %d

Warning: count(): Parameter must be an array or an object that implements Countable in %s on line %d
int(0)
int(1)
int(1)
int(1)
int(2)

Move ext/hash from resources to objects

As part of the long-term migration away from resources, the Hash extension has been updated to use objects instead of resources. The change should be seamless for PHP developers, except for where is_resource() checks have been made (which will need updating to is_object() instead).

Improve SSL/TLS defaults

The following changes to the defaults have been made:

  • tls:// now defaults to TLSv1.0 or TLSv1.1 or TLSv1.2
  • ssl:// an alias of tls://
  • STREAM_CRYPTO_METHOD_TLS_* constants default to TLSv1.0 or TLSv1.1 + TLSv1.2, instead of TLSv1.0 only

gettype() return value on closed resources

Previously, using gettype() on a closed resource would return a string of "unknown type". Now, a string of "resource (closed)" will be returned.

is_object() and __PHP_Incomplete_Class

Previously, using is_object() on the __PHP_Incomplete_Class class would return FALSE. Now, TRUE will be returned.

Promote the error level of undefined constants

Unqualified references to undefined constants will now generate an E_WARNING (instead of an E_NOTICE). In the next major version of PHP, they will generate Error exceptions.

Windows support

The officially supported, minimum Windows versions are now Windows 7/Server 2008 R2.

Checks on default property values of traits

Compatibility checks upon default trait property values will no longer perform casting.

object for class names

The object name was previously soft-reserved in PHP 7.0. This is now hard-reserved, prohibiting it from being used as a class, trait, or interface name.

NetWare support

Support for NetWare has now been removed.

array_unique() with SORT_STRING

While array_unique() with SORT_STRING formerly copied the array and removed non-unique elements (without packing the array afterwards), now a new array is built by adding the unique elements. This can result in different numeric indexes.

bcmod() changes with floats

The bcmod() function no longer truncates fractional numbers to integers. As such, its behavior now follows fmod(), rather than the % operator. For example bcmod('4', '3.5') now returns 0.5 instead of 1.

Hashing functions and non-cryptographic hashes

The hash_hmac(), hash_hmac_file(), hash_pbkdf2(), and hash_init() (with HASH_HMAC) functions no longer accept non-cryptographic hashes.

json_decode() function options

The json_decode() function option, JSON_OBJECT_AS_ARRAY, is now used if the second parameter (assoc) is NULL. Previously, JSON_OBJECT_AS_ARRAY was always ignored.

rand() and mt_rand() output

Sequences generated by rand() and mt_rand() for a specific seed may differ from PHP 7.1 on 64-bit machines (due to the fixing of a modulo bias bug in the implementation).

Removal of sql.safe_mode ini setting

The sql.safe_mode ini setting has now been removed.

Changes to date_parse() and date_parse_from_format()

The zone element of the array returned by date_parse() and date_parse_from_format() represents seconds instead of minutes now, and its sign is inverted. For instance -120 is now 7200.


Deprecated features in PHP 7.2.x

Unquoted strings

Unquoted strings that are non-existent global constants are taken to be strings of themselves. This behaviour used to emit an E_NOTICE, but will now emit an E_WARNING. In the next major version of PHP, an Error exception will be thrown instead.

<?php

var_dump(NONEXISTENT);

/* Output:
Warning: Use of undefined constant NONEXISTENT - assumed 'NONEXISTENT' (this will throw an Error in a future version of PHP) in %s on line %d
string(11) "NONEXISTENT"
*/

png2wbmp() and jpeg2wbmp()

The png2wbmp() and jpeg2wbmp() functions from the GD extension have now been deprecated and will be removed in the next major version of PHP.

INTL_IDNA_VARIANT_2003 variant

The Intl extension has deprecated the INTL_IDNA_VARIANT_2003 variant, which is currently being used as the default for idn_to_ascii() and idn_to_utf8(). PHP 7.4 will see these defaults changed to INTL_IDNA_VARIANT_UTS46, and the next major version of PHP will remove INTL_IDNA_VARIANT_2003 altogether.

__autoload() method

The __autoload() method has been deprecated because it is inferior to spl_autoload_register() (due to it not being able to chain autoloaders), and there is no interoperability between the two autoloading styles.

track_errors ini setting and $php_errormsg variable

When the track_errors ini setting is enabled, a $php_errormsg variable is created in the local scope when a non-fatal error occurs. Given that the preferred way of retrieving such error information is by using error_get_last(), this feature has been deprecated.

create_function() function

Given the security issues of this function (being a thin wrapper around eval()), this dated function has now been deprecated. The preferred alternative is to use anonymous functions.

mbstring.func_overload ini setting

Given the interoperability problems of string-based functions being used in environments with this setting enabled, it has now been deprecated.

(unset) cast

Casting any expression to this type will always result in NULL, and so this superfluous casting type has now been deprecated.

parse_str() without a second argument

Without the second argument to parse_str(), the query string parameters would populate the local symbol table. Given the security implications of this, using parse_str() without a second argument has now been deprecated. The function should always be used with two arguments, as the second argument causes the query string to be parsed into an array.

gmp_random() function

This function generates a random number based upon a range that is calculated by an unexposed, platform-specific limb size. Because of this, the function has now been deprecated. The preferred way of generating a random number using the GMP extension is by gmp_random_bits() and gmp_random_range().

each() function

This function is far slower at iteration than a normal foreach, and causes implementation issues for some language changes. It has therefore been deprecated.

assert() with a string argument

Using assert() with a string argument required the string to be eval()'ed. Given the potential for remote code execution, using assert() with a string argument has now been deprecated in favour of using boolean expressions.

$errcontext argument of error handlers

The $errcontext argument contains all local variables of the error site. Given its rare usage, and the problems it causes with internal optimisations, it has now been deprecated. Instead, a debugger should be used to retrieve information on local variables at the error site.

read_exif_data() function

The read_exif_data() alias has been deprecated. The exif_read_data() function should be used instead.


Other changes

Moving of utf8_encode() and utf8_decode()

The utf8_encode() and utf8_decode() functions have now been moved to the standard extension as string functions, whereas before the XML extension was required for them to be available.

Changes to mail() and mb_sendmail()

The $additional_headers parameter of mail() and mb_sendmail() now also accepts an array instead of a string.

LMDB support

The DBA extension now has support for LMDB.

Changes to the PHP build system

  • Unix: Autoconf 2.64 or greater is now required to build PHP.
  • Unix: --with-pdo-oci configure argument no longer needs the version number of the Oracle Instant Client.
  • Unix: --enable-gd-native-ttf configure argument has been removed. This was not used since PHP 5.5.0.
  • Windows: --with-config-profile configure argument has been added. This can be used to save specific configures, much like the magical config.nice.bat file.

Changes to GD

  • imageantialias() is now also available if compiled with a system libgd.
  • imagegd() stores truecolor images as real truecolor images. Formerly, they have been converted to palette.

Moving MCrypt to PECL

The MCrypt extension has now been moved out of the core to PECL. Given the mcrypt library has not seen any updates since 2007, its usage is highly discouraged. Instead, either the OpenSSL or Sodium extension should be used.

session_module_name()

Passing "user" to session_module_name() now raises an error of level E_RECOVERABLE_ERROR. Formerly, this has been silently ignored.


Migrating from PHP 7.0.x to PHP 7.1.x

Table of Contents

  • New features
  • New functions
  • New global constants
  • Backward incompatible changes
  • Deprecated features in PHP 7.1.x
  • Changed functions
  • Other changes
  • Windows Support

This new minor version brings with it a number of new features and a few incompatibilities that should be tested for before switching PHP versions in production environments.

See also the migration guides for PHP versions 5.0.x, 5.1.x, 5.2.x, 5.3.x, 5.4.x, 5.5.x, 5.6.x and 7.0.x.


New features

Nullable types

Type declarations for parameters and return values can now be marked as nullable by prefixing the type name with a question mark. This signifies that as well as the specified type, NULL can be passed as an argument, or returned as a value, respectively.

<?php

function testReturn(): ?string
{
    return 'elePHPant';
}

var_dump(testReturn());

function testReturn(): ?string
{
    return null;
}

var_dump(testReturn());

function test(?string $name)
{
    var_dump($name);
}

test('elePHPant');
test(null);
test();

The above example will output:

string(10) "elePHPant"
NULL
string(10) "elePHPant"
NULL
Uncaught Error: Too few arguments to function test(), 0 passed in...

Void functions

A void return type has been introduced. Functions declared with void as their return type must either omit their return statement altogether, or use an empty return statement. NULL is not a valid return value for a void function.

<?php
function swap(&$left, &$right): void
{
    if ($left === $right) {
        return;
    }

    $tmp = $left;
    $left = $right;
    $right = $tmp;
}

$a = 1;
$b = 2;
var_dump(swap($a, $b), $a, $b);

The above example will output:

null
int(2)
int(1)

Attempting to use a void function's return value simply evaluates to NULL, with no warnings emitted. The reason for this is because warnings would implicate the use of generic higher order functions.

Symmetric array destructuring

The shorthand array syntax ([]) may now be used to destructure arrays for assignments (including within foreach), as an alternative to the existing list() syntax, which is still supported.

<?php
$data = [
    [1, 'Tom'],
    [2, 'Fred'],
];

// list() style
list($id1, $name1) = $data[0];

// [] style
[$id1, $name1] = $data[0];

// list() style
foreach ($data as list($id, $name)) {
    // logic here with $id and $name
}

// [] style
foreach ($data as [$id, $name]) {
    // logic here with $id and $name
}

Class constant visibility

Support for specifying the visibility of class constants has been added.

<?php
class ConstDemo
{
    const PUBLIC_CONST_A = 1;
    public const PUBLIC_CONST_B = 2;
    protected const PROTECTED_CONST = 3;
    private const PRIVATE_CONST = 4;
}

iterable pseudo-type

A new pseudo-type (similar to callable) called iterable has been introduced. It may be used in parameter and return types, where it accepts either arrays or objects that implement the Traversable interface. With respect to subtyping, parameter types of child classes may broaden a parent's declaration of array or Traversable to iterable. With return types, child classes may narrow a parent's return type of iterable to array or an object that implements Traversable.

<?php
function iterator(iterable $iter)
{
    foreach ($iter as $val) {
        //
    }
}

Multi catch exception handling

Multiple exceptions per catch block may now be specified using the pipe character (|). This is useful for when different exceptions from different class hierarchies are handled the same.

<?php
try {
    // some code
} catch (FirstException | SecondException $e) {
    // handle first and second exceptions
}

Support for keys in list()

You can now specify keys in list(), or its new shorthand [] syntax. This enables destructuring of arrays with non-integer or non-sequential keys.

<?php
$data = [
    ["id" => 1, "name" => 'Tom'],
    ["id" => 2, "name" => 'Fred'],
];

// list() style
list("id" => $id1, "name" => $name1) = $data[0];

// [] style
["id" => $id1, "name" => $name1] = $data[0];

// list() style
foreach ($data as list("id" => $id, "name" => $name)) {
    // logic here with $id and $name
}

// [] style
foreach ($data as ["id" => $id, "name" => $name]) {
    // logic here with $id and $name
}

Support for negative string offsets

Support for negative string offsets has been added to the string manipulation functions accepting offsets, as well as to string indexing with [] or {}. In such cases, a negative offset is interpreted as being an offset from the end of the string.

<?php
var_dump("abcdef"[-2]);
var_dump(strpos("aabbcc", "b", -3));

The above example will output:

string (1) "e"
int(3)

Negative string and array offsets are now also supported in the simple variable parsing syntax inside of strings.

<?php
$string = 'bar';
echo "The last character of '$string' is '$string[-1]'.\n";
?>

The above example will output:

The last character of 'bar' is 'r'.

Support for AEAD in ext/openssl

Support for AEAD (modes GCM and CCM) have been added by extending the openssl_encrypt() and openssl_decrypt() functions with additional parameters.

Convert callables to Closures with Closure::fromCallable()

A new static method has been introduced to the Closure class to allow for callables to be easily converted into Closure objects.

<?php
class Test
{
    public function exposeFunction()
    {
        return Closure::fromCallable([$this, 'privateFunction']);
    }

    private function privateFunction($param)
    {
        var_dump($param);
    }
}

$privFunc = (new Test)->exposeFunction();
$privFunc('some value');

The above example will output:

string(10) "some value"

Asynchronous signal handling

A new function called pcntl_async_signals() has been introduced to enable asynchronous signal handling without using ticks (which introduce a lot of overhead).

<?php
pcntl_async_signals(true); // turn on async signals

pcntl_signal(SIGHUP,  function($sig) {
    echo "SIGHUP\n";
});

posix_kill(posix_getpid(), SIGHUP);

The above example will output:

SIGHUP

HTTP/2 server push support in ext/curl

Support for server push has been added to the CURL extension (requires version 7.46 and above). This can be leveraged through the curl_multi_setopt() function with the new CURLMOPT_PUSHFUNCTION constant. The constants CURL_PUSH_OK and CURL_PUSH_DENY have also been added so that the execution of the server push callback can either be approved or denied.

Stream Context Options

The tcp_nodelay stream context option has been added.


New functions

PHP Core

  • sapi_windows_cp_get()
  • sapi_windows_cp_set()
  • sapi_windows_cp_conv()
  • sapi_windows_cp_is_utf8()

Closure

  • Closure::fromCallable()

CURL

  • curl_multi_errno()
  • curl_share_errno()
  • curl_share_strerror()

OpenSSL

  • openssl_get_curve_names()

Session

  • session_create_id()
  • session_gc()

SPL

  • is_iterable()

PCNTL

  • pcntl_async_signals()
  • pcntl_signal_get_handler()


New global constants

Core Predefined Constants

  • PHP_FD_SETSIZE

CURL

  • CURLMOPT_PUSHFUNCTION
  • CURL_PUSH_OK
  • CURL_PUSH_DENY

Data Filtering

  • FILTER_FLAG_EMAIL_UNICODE

Image Processing and GD

  • IMAGETYPE_WEBP

JSON

  • JSON_UNESCAPED_LINE_TERMINATORS

LDAP

  • LDAP_OPT_X_SASL_NOCANON
  • LDAP_OPT_X_SASL_USERNAME
  • LDAP_OPT_X_TLS_CACERTDIR
  • LDAP_OPT_X_TLS_CACERTFILE
  • LDAP_OPT_X_TLS_CERTFILE
  • LDAP_OPT_X_TLS_CIPHER_SUITE
  • LDAP_OPT_X_TLS_KEYFILE
  • LDAP_OPT_X_TLS_RANDOM_FILE
  • LDAP_OPT_X_TLS_CRLCHECK
  • LDAP_OPT_X_TLS_CRL_NONE
  • LDAP_OPT_X_TLS_CRL_PEER
  • LDAP_OPT_X_TLS_CRL_ALL
  • LDAP_OPT_X_TLS_DHFILE
  • LDAP_OPT_X_TLS_CRLFILE
  • LDAP_OPT_X_TLS_PROTOCOL_MIN
  • LDAP_OPT_X_TLS_PROTOCOL_SSL2
  • LDAP_OPT_X_TLS_PROTOCOL_SSL3
  • LDAP_OPT_X_TLS_PROTOCOL_TLS1_0
  • LDAP_OPT_X_TLS_PROTOCOL_TLS1_1
  • LDAP_OPT_X_TLS_PROTOCOL_TLS1_2
  • LDAP_OPT_X_TLS_PACKAGE
  • LDAP_OPT_X_KEEPALIVE_IDLE
  • LDAP_OPT_X_KEEPALIVE_PROBES
  • LDAP_OPT_X_KEEPALIVE_INTERVAL

PostgreSQL

  • PGSQL_NOTICE_LAST
  • PGSQL_NOTICE_ALL
  • PGSQL_NOTICE_CLEAR

SPL

  • MT_RAND_PHP


Backward incompatible changes

Throw on passing too few function arguments

Previously, a warning would be emitted for invoking user-defined functions with too few arguments. Now, this warning has been promoted to an Error exception. This change only applies to user-defined functions, not internal functions. For example:

<?php
function test($param){}
test();

The above example will output something similar to:

Fatal error: Uncaught ArgumentCountError: Too few arguments to function test(), 0 passed in %s on line %d and exactly 1 expected in %s:%d

Forbid dynamic calls to scope introspection functions

Dynamic calls for certain functions have been forbidden (in the form of $func() or array_map('extract', ...), etc). These functions either inspect or modify another scope, and present with them ambiguous and unreliable behavior. The functions are as follows:

  • assert() - with a string as the first argument
  • compact()
  • extract()
  • func_get_args()
  • func_get_arg()
  • func_num_args()
  • get_defined_vars()
  • mb_parse_str() - with one arg
  • parse_str() - with one arg
<?php
(function () {
    $func = 'func_num_args';
    $func();
})();

The above example will output:

Warning: Cannot call func_num_args() dynamically in %s on line %d

Invalid class, interface, and trait names

The following names cannot be used to name classes, interfaces, or traits:

  • void
  • iterable

Numerical string conversions now respect scientific notation

Integer operations and conversions on numerical strings now respect scientific notation. This also includes the (int) cast operation, and the following functions: intval() (where the base is 10), settype(), decbin(), decoct(), and dechex().

Fixes to mt_rand() algorithm

mt_rand() will now default to using the fixed version of the Mersenne Twister algorithm. If deterministic output from mt_srand() was relied upon, then the MT_RAND_PHP with the ability to preserve the old (incorrect) implementation via an additional optional second parameter to mt_srand().

rand() aliased to mt_rand() and srand() aliased to mt_srand()

rand() and srand() have now been made aliases to mt_rand() and mt_srand(), respectively. This means that the output for the following functions have changed: rand(), shuffle(), str_shuffle(), and array_rand().

Disallow the ASCII delete control character in identifiers

The ASCII delete control character (0x7F) can no longer be used in identifiers that are not quoted.

error_log changes with syslog value

If the error_log ini setting is set to syslog, the PHP error levels are mapped to the syslog error levels. This brings finer differentiation in the error logs in contrary to the previous approach where all the errors are logged with the notice level only.

Do not call destructors on incomplete objects

Destructors are now never called for objects that throw an exception during the execution of their constructor. In previous versions this behavior depended on whether the object was referenced outside the constructor (e.g. by an exception backtrace).

call_user_func() handling of reference arguments

call_user_func() will now always generate a warning upon calls to functions that expect references as arguments. Previously this depended on whether the call was fully qualified.

Additionally, call_user_func() and call_user_func_array() will no longer abort the function call in this case. The "expected reference" warning will be emitted, but the call will proceed as usual.

The empty index operator is not supported for strings anymore

Applying the empty index operator to a string (e.g. $str[] = $x) throws a fatal error instead of converting silently to array.

Assignment via string index access on an empty string

String modification by character on an empty string now works like for non-empty strings, i.e. writing to an out of range offset pads the string with spaces, where non-integer types are converted to integer, and only the first character of the assigned string is used. Formerly, empty strings where silently treated like an empty array.

<?php
$a = '';
$a[10] = 'foo';
var_dump($a);
?>

Output of the above example in PHP 7.0:

array(1) {
  [10]=>
  string(3) "foo"
}

Output of the above example in PHP 7.1:

string(11) "          f"

Removed ini directives

The following ini directives have been removed:

  • session.entropy_file
  • session.entropy_length
  • session.hash_function
  • session.hash_bits_per_character

Array ordering when elements are automatically created during by reference assignments has changed

The order of the elements in an array has changed when those elements have been automatically created by referencing them in a by reference assignment. For example:

<?php
$array = [];
$array["a"] =& $array["b"];
$array["b"] = 1;
var_dump($array);
?>

Output of the above example in PHP 7.0:

array(2) {
  ["a"]=>
  &int(1)
  ["b"]=>
  &int(1)
}

Output of the above example in PHP 7.1:

array(2) {
  ["b"]=>
  &int(1)
  ["a"]=>
  &int(1)
}

Sort order of equal elements

The internal sorting algorithm has been improved, what may result in different sort order of elements, which compare as equal, than before.

Note:

Don't rely on the order of elements which compare as equal; it might change anytime.

Error message for E_RECOVERABLE errors

The error message for E_RECOVERABLE errors has been changed from "Catchable fatal error" to "Recoverable fatal error".

$options parameter of unserialize()

The allowed_classes element of the $options parameter of unserialize() is now strictly typed, i.e. if anything other than an array or a boolean is given, unserialize() returns FALSE and issues an E_WARNING.

DateTime constructor incorporates microseconds

DateTime and DateTimeImmutable now properly incorporate microseconds when constructed from the current time, either explicitly or with a relative string (e.g. "first day of next month"). This means that naive comparisons of two newly created instances will now more likely return FALSE instead of TRUE:

<?php
new DateTime() == new DateTime();
?>

Fatal errors to Error exceptions conversions

In the Date extension, invalid serialization data for DateTime or DatePeriod classes, or timezone initialization failure from serialized data, will now throw an Error exception from the __wakeup() or __set_state() methods, instead of resulting in a fatal error.

In the DBA extension, data modification functions (such as dba_insert()) will now throw an Error exception instead of triggering a catchable fatal error if the key does not contain exactly two elements.

In the DOM extension, invalid schema or RelaxNG validation contexts will now throw an Error exception instead of resulting in a fatal error. Similarly, attempting to register a node class that does not extend the appropriate base class, or attempting to read an invalid property or write to a readonly property, will also now throw an Error exception.

In the IMAP extension, email addresses longer than 16385 bytes will throw an Error exception instead of resulting in a fatal error.

In the Intl extension, failing to call the parent constructor in a class extending Collator before invoking the parent methods will now throw an Error instead of resulting in a recoverable fatal error. Also, cloning a Transliterator object will now throw an Error exception on failure to clone the internal transliterator instead of resulting in a fatal error.

In the LDAP extension, providing an unknown modification type to ldap_batch_modify() will now throw an Error exception instead of resulting in a fatal error.

In the mbstring extension, the mb_ereg() and mb_eregi() functions will now throw a ParseError exception if an invalid PHP expression is provided and the 'e' option is used.

In the Mcrypt extension, the mcrypt_encrypt() and mcrypt_decrypt() will now throw an Error exception instead of resulting in a fatal error if mcrypt cannot be initialized.

In the mysqli extension, attempting to read an invalid property or write to a readonly property will now throw an Error exception instead of resulting in a fatal error.

In the Reflection extension, failing to retrieve a reflection object or retrieve an object property will now throw an Error exception instead of resulting in a fatal error.

In the Session extension, custom session handlers that do not return strings for session IDs will now throw an Error exception instead of resulting in a fatal error when a function is called that must generate a session ID.

In the SimpleXML extension, creating an unnamed or duplicate attribute will now throw an Error exception instead of resulting in a fatal error.

In the SPL extension, attempting to clone an SplDirectory object will now throw an Error exception instead of resulting in a fatal error. Similarly, calling ArrayIterator::append() when iterating over an object will also now throw an Error exception.

In the standard extension, the assert() function, when provided with a string argument as its first parameter, will now throw a ParseError exception instead of resulting in a catchable fatal error if the PHP code is invalid. Similarly, calling forward_static_call() outside of a class scope will now throw an Error exception.

In the Tidy extension, creating a tidyNode manually will now throw an Error exception instead of resulting in a fatal error.

In the WDDX extension, a circular reference when serializing will now throw an Error exception instead of resulting in a fatal error.

In the XML-RPC extension, a circular reference when serializing will now throw an instance of Error exception instead of resulting in a fatal error.

In the Zip extension, the ZipArchive::addGlob() method will now throw an Error exception instead of resulting in a fatal error if glob support is not available.

Lexically bound variables cannot reuse names

Variables bound to a closure via the use construct cannot use the same name as any superglobals, $this, or any parameter. For example, all of these function definition will result in a fatal error:

<?php
$f = function () use ($_SERVER) {};
$f = function () use ($this) {};
$f = function ($param) use ($param) {};

long2ip() parameter type change

long2ip() now expects an int instead of a string.

JSON encoding and decoding

The serialize_precision ini setting now controls the serialization precision when encoding doubles.

Decoding an empty key now results in an empty property name, rather than _empty_ as a property name.

<?php
var_dump(json_decode(json_encode(['' => 1])));

The above example will output something similar to:

object(stdClass)#1 (1) {
  [""]=>
  int(1)
}

When supplying the JSON_UNESCAPED_UNICODE flag to json_encode(), the sequences U+2028 and U+2029 are now escaped.

Changes to mb_ereg() and mb_eregi() parameter semantics

The third parameter to the mb_ereg() and mb_eregi() functions (regs) will now be set to an empty array if nothing was matched. Formerly, the parameter would not have been modified.

Drop support for the sslv2 stream

The sslv2 stream has now been dropped in OpenSSL.


Deprecated features in PHP 7.1.x

ext/mcrypt

The mcrypt extension has been abandonware for nearly a decade now, and was also fairly complex to use. It has therefore been deprecated in favour of OpenSSL, where it will be removed from the core and into PECL in PHP 7.2.

Eval option for mb_ereg_replace() and mb_eregi_replace()

The e pattern modifier has been deprecated for the mb_ereg_replace() and mb_eregi_replace() functions.


Changed functions

PHP Core

  • getopt() has an optional third parameter that exposes the index of the next element in the argument vector list to be processed. This is done via a by-ref parameter.
  • getenv() no longer requires its parameter. If the parameter is omitted, then the current environment variables will be returned as an associative array.
  • get_headers() now has an additional parameter to enable for the passing of custom stream contexts.
  • output_reset_rewrite_vars() no longer resets session URL rewrite variables.
  • parse_url() is now more restrictive and supports RFC3986.
  • unpack() now accepts an optional third parameter to specify the offset to begin unpacking from.

File System

  • file_get_contents() now accepts a negative seek offset if the stream is seekable.
  • tempnam() now emits a notice when falling back to the system's temp directory.

JSON

  • json_encode() now accepts a new option, JSON_UNESCAPED_LINE_TERMINATORS, to disable the escaping of U+2028 and U+2029 characters when JSON_UNESCAPED_UNICODE is supplied.

Multibyte String

  • mb_ereg() now rejects illegal byte sequences.
  • mb_ereg_replace() now rejects illegal byte sequences.

PDO

  • PDO::lastInsertId() for PostgreSQL will now trigger an error when nextval has not been called for the current session (the postgres connection).

PostgreSQL

  • pg_last_notice() now accepts an optional parameter to specify an operation. This can be done with one of the following new constants: PGSQL_NOTICE_LAST, PGSQL_NOTICE_ALL, or PGSQL_NOTICE_CLEAR.
  • pg_fetch_all() now accepts an optional second parameter to specify the result type (similar to the third parameter of pg_fetch_array()).
  • pg_select() now accepts an optional fourth parameter to specify the result type (similar to the third parameter of pg_fetch_array()).

Session

  • session_start() now returns FALSE and no longer initializes $_SESSION when it failed to start the session.


Other changes

Notices and warnings on arithmetic with invalid strings

New E_WARNING and E_NOTICE errors have been introduced when invalid strings are coerced using operators expecting numbers (+ - * / ** % << >> | & ^) or their assignment equivalents. An E_NOTICE is emitted when the string begins with a numeric value but contains trailing non-numeric characters, and an E_WARNING is emitted when the string does not contain a numeric value.

<?php
'1b' + 'something';

The above example will output:

Notice: A non well formed numeric value encountered in %s on line %d
Warning: A non-numeric value encountered in %s on line %d

Warn on octal escape sequence overflow

Previously, 3-octet octal string escape sequences would overflow silently. Now, they will still overflow, but E_WARNING will be emitted.

<?php
var_dump("\500");

The above example will output:

Warning: Octal escape sequence overflow \500 is greater than \377 in %s on line %d
string(1) "@"

Inconsistency fixes to $this

Whilst $this is considered a special variable in PHP, it lacked proper checks to ensure it wasn't used as a variable name or reassigned. This has now been rectified to ensure that $this cannot be a user-defined variable, reassigned to a different value, or be globalised.

Session ID generation without hashing

Session IDs will no longer be hashed upon generation. With this change brings about the removal of the following four ini settings:

  • session.entropy_file
  • session.entropy_length
  • session.hash_function
  • session.hash_bits_per_character

And the addition of the following two ini settings:

  • session.sid_length - defines the length of the session ID, defaulting to 32 characters for backwards compatibility)
  • session.sid_bits_per_character - defines the number of bits to be stored per character (i.e. increases the range of characters that can be used in the session ID), defaulting to 4 for backwards compatibility

Changes to INI file handling

precision

If the value is set to -1, then the dtoa mode 0 is used. The default value is still 14.

serialize_precision

If the value is set to -1, then the dtoa mode 0 is used. The value -1 is now used by default.

gd.jpeg_ignore_warning

The default of this php.ini setting has been changed to 1, so by default libjpeg warnings are ignored.

opcache.enable_cli

The default of this php.ini setting has been changed to 1 (enabled) in PHP 7.1.2, and back to 0 (disabled) in PHP 7.1.7.

Session ID generation with a CSPRNG only

Session IDs will now only be generated with a CSPRNG.

More informative TypeError messages when NULL is allowed

TypeError exceptions for arg_info type checks will now provide more informative error messages. If the parameter type or return type accepts NULL (by either having a default value of NULL or being a nullable type), then the error message will now mention this with a message of "must be ... or null" or "must ... or be null."


Windows Support

Support for long and UTF-8 path

If a web application is UTF-8 conform, no further action is required. For applications depending on paths in non UTF-8 encodings for I/O, an explicit INI directive has to be set. The encoding INI settings check relies on the order in the core:

  • internal_encoding
  • default_charset
  • zend.multibyte

Several functions for codepage handling were introduced:

  • sapi_windows_cp_set() to set the default codepage
  • sapi_windows_cp_get() to retrieve the current codepage
  • sapi_windows_cp_is_utf8()
  • sapi_windows_cp_conv() to convert between codepages, using iconv() compatible signature

These functions are thread safe.

The console output codepage is adjusted depending on the encoding used in PHP. Depending on the concrete system OEM codepage, the visible output might or might be not correct. For example, in the default cmd.exe and on a system with the OEM codepage 437, outputs in codepages 1251, 1252, 1253 and some others can be shown correctly when using UTF-8. On the same system, chars in codepage like 20932 probably won't be shown correctly. This refers to the particular system rules for codepage, font compatibility and the particular console program used. PHP automatically sets the console codepage according to the encoding rules from php.ini. Using alternative consoles instead of cmd.exe directly might bring better experience in some cases.

Nevertheless be aware, runtime codepage switch after the request start might bring unexpected side effects on CLI. The preferable way is php.ini, When PHP CLI is used in a console emulator, that doesn't support Unicode, it might possibly be required, to avoid changing the console codepage. The best way to achieve it is by setting the default or internal encoding to correspond the ANSI codepage. Another method is to set the INI directives output_encoding and input_encoding to the required codepage, in which case however the difference between internal and I/O codepage is likely to cause mojibake. In rare cases, if PHP happens to crash gracefully, the original console codepage might be not restored. In this case, the chcp command can be used, to restore it manually.

Special awareness for the DBCS systems - the codepage switch on runtime using ini_set() is likely to cause display issues. The difference to the non DBCS systems is, that the extended characters require two console cells to be displayed. In certain case, only the mapping of the characters into the glyph set of the font could happen, no actual font change. This is the nature of DBCS systems, the most simple way to prevent display issues is to avoid usage of ini_set() for the codepage change.

As a result of UTF-8 support in the streams, PHP scripts are not limited to ASCII or ANSI filenames anymore. This is supported out of the box on CLI. For other SAPI, the documentation for the corresponding server is useful.

Long paths support is transparent. Paths longer than 260 bytes get automatically prefixed with \\?\. The max path length is limited to 2048 bytes. Be aware, that the path segment limit (basename length) still persists.

For the best portability, it is strongely recommended to handle filenames, I/O and other related topics UTF-8. Additionally, for the console applications, the usage of a TrueType font is preferable and the usage of ini_set() for the codepage change is discouraged.

readline

The readline extension is supported through the » WinEditLine library. Thereby, the interactive CLI shell is supported as well (php.exe -a).

PHP_FCGI_CHILDREN

PHP_FCGI_CHILDREN is now respected. If this environment variable is defined, the first php-cgi.exe process will exec the specified number of children. These will share the same TCP socket.

ftok()

Added support for ftok()


Migrating from PHP 5.6.x to PHP 7.0.x

Table of Contents

  • Backward incompatible changes
  • New features
  • Deprecated features in PHP 7.0.x
  • Changed functions
  • New functions
  • New Classes and Interfaces
  • New Global Constants
  • Changes in SAPI Modules
  • Removed Extensions and SAPIs
  • Other Changes

Despite the fact that PHP 7.0 is a new major version, efforts have been made to make migration as painless as possible. This release focuses mainly on removing functionality deprecated in previous versions and improving language consistency.

There are a few incompatibilities and new features that should be considered, and code should be tested before switching PHP versions in production environments.

See also the migration guides for PHP versions 5.0.x, 5.1.x, 5.2.x, 5.3.x, 5.4.x, 5.5.x and 5.6.x.


Backward incompatible changes

Changes to error and exception handling

Many fatal and recoverable fatal errors have been converted to exceptions in PHP 7. These error exceptions inherit from the Error class, which itself implements the Throwable interface (the new base interface all exceptions inherit).

This means that custom error handlers may no longer be triggered because exceptions may be thrown instead (causing new fatal errors for uncaught Error exceptions).

A fuller description of how errors operate in PHP 7 can be found on the PHP 7 errors page. This migration guide will merely enumerate the changes that affect backward compatibility.

set_exception_handler() is no longer guaranteed to receive Exception objects

Code that implements an exception handler registered with set_exception_handler() using a type declaration of Exception will cause a fatal error when an Error object is thrown.

If the handler needs to work on both PHP 5 and 7, you should remove the type declaration from the handler, while code that is being migrated to work on PHP 7 exclusively can simply replace the Exception type declaration with Throwable instead.

<?php
// PHP 5 era code that will break.
function handler(Exception $e) { ... }
set_exception_handler('handler');

// PHP 5 and 7 compatible.
function handler($e) { ... }

// PHP 7 only.
function handler(Throwable $e) { ... }
?>

Internal constructors always throw exceptions on failure

Previously, some internal classes would return NULL or an unusable object when the constructor failed. All internal classes will now throw an Exception in this case in the same way that user classes already had to.

Parse errors throw ParseError

Parser errors now throw a ParseError object. Error handling for eval() should now include a catch block that can handle this error.

E_STRICT notices severity changes

All of the E_STRICT notices have been reclassified to other levels. E_STRICT constant is retained, so calls like error_reporting(E_ALL|E_STRICT) will not cause an error.

E_STRICT notices severity changes
Situation | New level/behaviour
Indexing by a resource | E_NOTICE
Abstract static methods | Notice removed, triggers no error
"Redefining" a constructor | Notice removed, triggers no error
Signature mismatch during inheritance | E_WARNING
Same (compatible) property in two used traits | Notice removed, triggers no error
Accessing static property non-statically | E_NOTICE
Only variables should be assigned by reference | E_NOTICE
Only variables should be passed by reference | E_NOTICE
Calling non-static methods statically | E_DEPRECATED

Changes to variable handling

PHP 7 now uses an abstract syntax tree when parsing source files. This has permitted many improvements to the language which were previously impossible due to limitations in the parser used in earlier versions of PHP, but has resulted in the removal of a few special cases for consistency reasons, which has resulted in backward compatibility breaks. These cases are detailed in this section.

Changes to the handling of indirect variables, properties, and methods

Indirect access to variables, properties, and methods will now be evaluated strictly in left-to-right order, as opposed to the previous mix of special cases. The table below shows how the order of evaluation has changed.

Old and new evaluation of indirect expressions
Expression | PHP 5 interpretation | PHP 7 interpretation
$$foo['bar']['baz'] | ${$foo['bar']['baz']} | ($$foo)['bar']['baz']
$foo->$bar['baz'] | $foo->{$bar['baz']} | ($foo->$bar)['baz']
$foo->$bar['baz']() | $foo->{$bar['baz']}() | ($foo->$bar)['baz']()
Foo::$bar['baz']() | Foo::{$bar['baz']}() | (Foo::$bar)['baz']()

Code that used the old right-to-left evaluation order must be rewritten to explicitly use that evaluation order with curly braces (see the above middle column). This will make the code both forwards compatible with PHP 7.x and backwards compatible with PHP 5.x.

This also affects the global keyword. The curly brace syntax can be used to emulate the previous behaviour if required:

<?php
function f() {
    // Valid in PHP 5 only.
    global $$foo->bar;

    // Valid in PHP 5 and 7.
    global ${$foo->bar};
}
?>

Changes to list() handling

list() no longer assigns variables in reverse order

list() will now assign values to variables in the order they are defined, rather than reverse order. In general, this only affects the case where list() is being used in conjunction with the array [] operator, as shown below:

<?php
list($a[], $a[], $a[]) = [1, 2, 3];
var_dump($a);
?>

Output of the above example in PHP 5:

array(3) {
  [0]=>
  int(3)
  [1]=>
  int(2)
  [2]=>
  int(1)
}

Output of the above example in PHP 7:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

In general, it is recommended not to rely on the order in which list() assignments occur, as this is an implementation detail that may change again in the future.

Empty list() assignments have been removed

list() constructs can no longer be empty. The following are no longer allowed:

<?php
list() = $a;
list(,,) = $a;
list($x, list(), $y) = $a;
?>
list() cannot unpack strings

list() can no longer unpack string variables. str_split() should be used instead.

Array ordering when elements are automatically created during by reference assignments has changed

The order of the elements in an array has changed when those elements have been automatically created by referencing them in a by reference assignment. For example:

<?php
$array = [];
$array["a"] =& $array["b"];
$array["b"] = 1;
var_dump($array);
?>

Output of the above example in PHP 5:

array(2) {
  ["b"]=>
  &int(1)
  ["a"]=>
  &int(1)
}

Output of the above example in PHP 7:

array(2) {
  ["a"]=>
  &int(1)
  ["b"]=>
  &int(1)
}

Parentheses around function arguments no longer affect behaviour

In PHP 5, using redundant parentheses around a function argument could quiet strict standards warnings when the function argument was passed by reference. The warning will now always be issued.

<?php
function getArray() {
    return [1, 2, 3];
}

function squareArray(array &$a) {
    foreach ($a as &$v) {
        $v **= 2;
    }
}

// Generates a warning in PHP 7.
squareArray((getArray()));
?>

The above example will output:

Notice: Only variables should be passed by reference in /tmp/test.php on line 13

Changes to foreach

Minor changes have been made to the behaviour of the foreach control structure, primarily around the handling of the internal array pointer and modification of the array being iterated over.

foreach no longer changes the internal array pointer

Prior to PHP 7, the internal array pointer was modified while an array was being iterated over with foreach. This is no longer the case, as shown in the following example:

<?php
$array = [0, 1, 2];
foreach ($array as &$val) {
    var_dump(current($array));
}
?>

Output of the above example in PHP 5:

int(1)
int(2)
bool(false)

Output of the above example in PHP 7:

int(0)
int(0)
int(0)

foreach by-value operates on a copy of the array

When used in the default by-value mode, foreach will now operate on a copy of the array being iterated rather than the array itself. This means that changes to the array made during iteration will not affect the values that are iterated.

foreach by-reference has improved iteration behaviour

When iterating by-reference, foreach will now do a better job of tracking changes to the array made during iteration. For example, appending to an array while iterating will now result in the appended values being iterated over as well:

<?php
$array = [0];
foreach ($array as &$val) {
    var_dump($val);
    $array[1] = 1;
}
?>

Output of the above example in PHP 5:

int(0)

Output of the above example in PHP 7:

int(0)
int(1)

Iteration of non-Traversable objects

Iterating over a non-Traversable object will now have the same behaviour as iterating over by-reference arrays. This results in the improved behaviour when modifying an array during iteration also being applied when properties are added to or removed from the object.

Changes to integer handling

Invalid octal literals

Previously, octal literals that contained invalid numbers were silently truncated (0128 was taken as 012). Now, an invalid octal literal will cause a parse error.

Negative bitshifts

Bitwise shifts by negative numbers will now throw an ArithmeticError:

<?php
var_dump(1 >> -1);
?>

Output of the above example in PHP 5:

int(0)

Output of the above example in PHP 7:

Fatal error: Uncaught ArithmeticError: Bit shift by negative number in /tmp/test.php:2
Stack trace:
#0 {main}
  thrown in /tmp/test.php on line 2

Out of range bitshifts

Bitwise shifts (in either direction) beyond the bit width of an integer will always result in 0. Previously, the behaviour of such shifts was architecture dependent.

Changes to Division By Zero

Previously, when 0 was used as the divisor for either the divide (/) or modulus (%) operators, an E_WARNING would be emitted and false would be returned. Now, the divide operator returns a float as either +INF, -INF, or NAN, as specified by IEEE 754. The modulus operator E_WARNING has been removed and will throw a DivisionByZeroError exception.

<?php
var_dump(3/0);
var_dump(0/0);
var_dump(0%0);
?>

Output of the above example in PHP 5:

Warning: Division by zero in %s on line %d
bool(false)

Warning: Division by zero in %s on line %d
bool(false)

Warning: Division by zero in %s on line %d
bool(false)

Output of the above example in PHP 7:

Warning: Division by zero in %s on line %d
float(INF)

Warning: Division by zero in %s on line %d
float(NAN)

PHP Fatal error:  Uncaught DivisionByZeroError: Modulo by zero in %s line %d

Changes to string handling

Hexadecimal strings are no longer considered numeric

Strings containing hexadecimal numbers are no longer considered to be numeric. For example:

<?php
var_dump("0x123" == "291");
var_dump(is_numeric("0x123"));
var_dump("0xe" + "0x1");
var_dump(substr("foo", "0x1"));
?>

Output of the above example in PHP 5:

bool(true)
bool(true)
int(15)
string(2) "oo"

Output of the above example in PHP 7:

bool(false)
bool(false)
int(0)

Notice: A non well formed numeric value encountered in /tmp/test.php on line 5
string(3) "foo"

filter_var() can be used to check if a string contains a hexadecimal number, and also to convert a string of that type to an integer:

<?php
$str = "0xffff";
$int = filter_var($str, FILTER_VALIDATE_INT, FILTER_FLAG_ALLOW_HEX);
if (false === $int) {
    throw new Exception("Invalid integer!");
}
var_dump($int); // int(65535)
?>

\u{ may cause errors

Due to the addition of the new Unicode codepoint escape syntax, strings containing a literal \u{ followed by an invalid sequence will cause a fatal error. To avoid this, the leading backslash should be escaped.

Removed functions

call_user_method() and call_user_method_array()

These functions were deprecated in PHP 4.1.0 in favour of call_user_func() and call_user_func_array(). You may also want to consider using variable functions and/or the ... operator.

All ereg* functions

All ereg functions were removed. PCRE is a recommended alternative.

mcrypt aliases

The deprecated mcrypt_generic_end() function has been removed in favour of mcrypt_generic_deinit().

Additionally, the deprecated mcrypt_ecb(), mcrypt_cbc(), mcrypt_cfb() and mcrypt_ofb() functions have been removed in favour of using mcrypt_decrypt() with the appropriate MCRYPT_MODE_* constant.

All ext/mysql functions

All ext/mysql functions were removed. For details about choosing a different MySQL API, see Choosing a MySQL API.

All ext/mssql functions

All ext/mssql functions were removed. For a list of alternatives, see the MSSQL Introduction.

intl aliases

The deprecated datefmt_set_timezone_id() and
IntlDateFormatter::setTimeZoneID() aliases have been
removed in favour of datefmt_set_timezone() and
IntlDateFormatter::setTimeZone(), respectively.

set_magic_quotes_runtime()

set_magic_quotes_runtime(), along with its alias magic_quotes_runtime(), have been removed. They were deprecated in PHP 5.3.0, and became effectively non-functional with the removal of magic quotes in PHP 5.4.0.

set_socket_blocking()

The deprecated set_socket_blocking() alias has been removed in favour of stream_set_blocking().

dl() in PHP-FPM

dl() can no longer be used in PHP-FPM. It remains functional in the CLI and embed SAPIs.

GD Type1 functions

Support for PostScript Type1 fonts has been removed from the GD extension, resulting in the removal of the following functions:

  • imagepsbbox()
  • imagepsencodefont()
  • imagepsextendfont()
  • imagepsfreefont()
  • imagepsloadfont()
  • imagepsslantfont()
  • imagepstext()

Using TrueType fonts and their associated functions is recommended instead.

Removed INI directives

Removed features

The following INI directives have been removed as their associated features have also been removed:

  • always_populate_raw_post_data
  • asp_tags

xsl.security_prefs

The xsl.security_prefs directive has been removed. Instead, the XsltProcessor::setSecurityPrefs() method should be called to control the security preferences on a per-processor basis.

Other backward incompatible changes

New objects cannot be assigned by reference

The result of the new statement can no longer be assigned to a variable by reference:

<?php
class C {}
$c =& new C;
?>

Output of the above example in PHP 5:

Deprecated: Assigning the return value of new by reference is deprecated in /tmp/test.php on line 3

Output of the above example in PHP 7:

Parse error: syntax error, unexpected 'new' (T_NEW) in /tmp/test.php on line 3

Invalid class, interface and trait names

The following names cannot be used to name classes, interfaces or traits:

  • bool
  • int
  • float
  • string
  • NULL
  • TRUE
  • FALSE

Furthermore, the following names should not be used. Although they will not generate an error in PHP 7.0, they are reserved for future use and should be considered deprecated.

  • resource
  • object
  • mixed
  • numeric

ASP and script PHP tags removed

Support for using ASP and script tags to delimit PHP code has been removed. The affected tags are:

Removed ASP and script tags
Opening tag | Closing tag
<% | %>
<%= | %>
<script language="php"> | </script>

Calls from incompatible context removed

Previously deprecated in PHP 5.6, static calls made to a non-static method with an incompatible context will now result in the called method having an undefined $this variable and a deprecation warning being issued.

<?php
class A {
    public function test() { var_dump($this); }
}

// Note: Does NOT extend A
class B {
    public function callNonStaticMethodOfA() { A::test(); }
}

(new B)->callNonStaticMethodOfA();
?>

Output of the above example in PHP 5.6:

Deprecated: Non-static method A::test() should not be called statically, assuming $this from incompatible context in /tmp/test.php on line 8
object(B)#1 (0) {
}

Output of the above example in PHP 7:

Deprecated: Non-static method A::test() should not be called statically in /tmp/test.php on line 8

Notice: Undefined variable: this in /tmp/test.php on line 3
NULL

yield is now a right associative operator

The yield construct no longer requires parentheses, and has been changed to a right associative operator with precedence between print and =>. This can result in changed behaviour:

<?php
echo yield -1;
// Was previously interpreted as
echo (yield) - 1;
// And is now interpreted as
echo yield (-1);

yield $foo or die;
// Was previously interpreted as
yield ($foo or die);
// And is now interpreted as
(yield $foo) or die;
?>

Parentheses can be used to disambiguate those cases.

Functions cannot have multiple parameters with the same name

It is no longer possible to define two or more function parameters with the same name. For example, the following function will trigger an E_COMPILE_ERROR:

<?php
function foo($a, $b, $unused, $unused) {
    //
}
?>

Functions inspecting arguments report the current parameter value

func_get_arg(), func_get_args(), debug_backtrace() and exception backtraces will no longer report the original value that was passed to a parameter, but will instead provide the current value (which might have been modified).

<?php
function foo($x) {
    $x++;
    var_dump(func_get_arg(0));
}
foo(1);?>

Output of the above example in PHP 5:

1

Output of the above example in PHP 7:

2

Switch statements cannot have multiple default blocks

It is no longer possible to define two or more default blocks in a switch statement. For example, the following switch statement will trigger an E_COMPILE_ERROR:

<?php
switch (1) {
    default:
    break;
    default:
    break;
}
?>

$HTTP_RAW_POST_DATA removed

$HTTP_RAW_POST_DATA is no longer available. The php://input stream should be used instead.

# comments in INI files removed

Support for prefixing comments with # in INI files has been removed. ; (semi-colon) should be used instead. This change applies to php.ini, as well as files handled by parse_ini_file() and parse_ini_string().

JSON extension replaced with JSOND

The JSON extension has been replaced with JSOND, causing three minor BC breaks. Firstly, a number must not end in a decimal point (i.e. 34. must be changed to either 34.0 or 34). Secondly, when using scientific notation, the e exponent must not immediately follow a decimal point (i.e. 3.e3 must be changed to either 3.0e3 or 3e3). Finally, an empty string is no longer considered valid JSON.

Internal function failure on overflow

Previously, internal functions would silently truncate numbers produced from float-to-integer coercions when the float was too large to represent as an integer. Now, an E_WARNING will be emitted and NULL will be returned.

Fixes to custom session handler return values

Any predicate functions implemented by custom session handlers that return either FALSE or -1 will be fatal errors. If any value from these functions other than a boolean, -1, or 0 is returned, then it will fail and an E_WARNING will be emitted.

Sort order of equal elements

The internal sorting algorithm has been improved, what may result in different sort order of elements, which compare as equal, than before.

Note:

Don't rely on the order of elements which compare as equal; it might change anytime.

Misplaced break and switch statements

break and continue statements outside of a loop or switch control structure are now detected at compile-time instead of run-time as before, and trigger an E_COMPILE_ERROR.

Mhash is not an extension anymore

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.

declare(ticks)

The declare(ticks) directive does no longer leak into different compilation units.


New features

Scalar type declarations

Scalar type declarations come in two flavours: coercive (default) and strict. The following types for parameters can now be enforced (either coercively or strictly): strings (string), integers (int), floating-point numbers (float), and booleans (bool). They augment the other types introduced in PHP 5: class names, interfaces, array and callable.

<?php
// Coercive mode
function sumOfInts(int ...$ints)
{
    return array_sum($ints);
}

var_dump(sumOfInts(2, '3', 4.1));

The above example will output:

int(9)

To enable strict mode, a single declare directive must be placed at the top of the file. This means that the strictness of typing for scalars is configured on a per-file basis. This directive not only affects the type declarations of parameters, but also a function's return type (see return type declarations, built-in PHP functions, and functions from loaded extensions.

Full documentation and examples of scalar type declarations can be found in the type declaration reference.

Return type declarations

PHP 7 adds support for return type declarations. Similarly to argument type declarations, return type declarations specify the type of the value that will be returned from a function. The same types are available for return type declarations as are available for argument type declarations.

<?php

function arraysSum(array ...$arrays): array
{
    return array_map(function(array $array): int {
        return array_sum($array);
    }, $arrays);
}

print_r(arraysSum([1,2,3], [4,5,6], [7,8,9]));

The above example will output:

Array
(
    [0] => 6
    [1] => 15
    [2] => 24
)

Full documentation and examples of return type declarations can be found in the return type declarations. reference.

Null coalescing operator

The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

<?php
// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

// Coalescing can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
?>

Spaceship operator

The spaceship operator is used for comparing two expressions. It returns -1, 0 or 1 when $a is respectively less than, equal to, or greater than $b. Comparisons are performed according to PHP's usual type comparison rules.

<?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
?>

Constant arrays using define()

Array constants can now be defined with define(). In PHP 5.6, they could only be defined with const.

<?php
define('ANIMALS', [
    'dog',
    'cat',
    'bird'
]);

echo ANIMALS[1]; // outputs "cat"
?>

Anonymous classes

Support for anonymous classes has been added via new class. These can be used in place of full class definitions for throwaway objects:

<?php
interface Logger {
    public function log(string $msg);
}

class Application {
    private $logger;

    public function getLogger(): Logger {
         return $this->logger;
    }

    public function setLogger(Logger $logger) {
         $this->logger = $logger;
    }
}

$app = new Application;
$app->setLogger(new class implements Logger {
    public function log(string $msg) {
        echo $msg;
    }
});

var_dump($app->getLogger());
?>

The above example will output:

object(class@anonymous)#2 (0) {
}

Full documentation can be found in the anonymous class reference.

Unicode codepoint escape syntax

This takes a Unicode codepoint in hexadecimal form, and outputs that codepoint in UTF-8 to a double-quoted string or a heredoc. Any valid codepoint is accepted, with leading 0's being optional.

echo "\u{aa}";
echo "\u{0000aa}";
echo "\u{9999}";

The above example will output:

ª
ª (same as before but with optional leading 0's)
香

Closure::call()

Closure::call() is a more performant, shorthand way of temporarily binding an object scope to a closure and invoking it.

<?php
class A {private $x = 1;}

// Pre PHP 7 code
$getX = function() {return $this->x;};
$getXCB = $getX->bindTo(new A, 'A'); // intermediate closure
echo $getXCB();

// PHP 7+ code
$getX = function() {return $this->x;};
echo $getX->call(new A);

The above example will output:

1
1

Filtered unserialize()

This feature seeks to provide better security when unserializing objects on untrusted data. It prevents possible code injections by enabling the developer to whitelist classes that can be unserialized.

<?php

// converts all objects into __PHP_Incomplete_Class object
$data = unserialize($foo, ["allowed_classes" => false]);

// converts all objects into __PHP_Incomplete_Class object except those of MyClass and MyClass2
$data = unserialize($foo, ["allowed_classes" => ["MyClass", "MyClass2"]]);

// default behaviour (same as omitting the second argument) that accepts all classes
$data = unserialize($foo, ["allowed_classes" => true]);

IntlChar

The new IntlChar class seeks to expose additional ICU functionality. The class itself defines a number of static methods and constants that can be used to manipulate unicode characters.

<?php

printf('%x', IntlChar::CODEPOINT_MAX);
echo IntlChar::charName('@');
var_dump(IntlChar::ispunct('!'));

The above example will output:

10ffff
COMMERCIAL AT
bool(true)

In order to use this class, the Intl extension must be installed.

Expectations

Expectations are a backwards compatible enhancement to the older assert() function. They allow for zero-cost assertions in production code, and provide the ability to throw custom exceptions when the assertion fails.

While the old API continues to be maintained for compatibility, assert() is now a language construct, allowing the first parameter to be an expression rather than just a string to be evaluated or a boolean value to be tested.

<?php
ini_set('assert.exception', 1);

class CustomError extends AssertionError {}

assert(false, new CustomError('Some error message'));
?>

The above example will output:

Fatal error: Uncaught CustomError: Some error message

Full details on this feature, including how to configure it in both development and production environments, can be found in the expectations section of the assert() reference.

Group use declarations

Classes, functions and constants being imported from the same namespace can now be grouped together in a single use statement.

<?php
// Pre PHP 7 code
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;

// PHP 7+ code
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};
?>

Generator Return Expressions

This feature builds upon the generator functionality introduced into PHP 5.5. It enables for a return statement to be used within a generator to enable for a final expression to be returned (return by reference is not allowed). This value can be fetched using the new Generator::getReturn() method, which may only be used once the generator has finished yielding values.

<?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

Being able to explicitly return a final value from a generator is a handy ability to have. This is because it enables for a final value to be returned by a generator (from perhaps some form of coroutine computation) that can be specifically handled by the client code executing the generator. This is far simpler than forcing the client code to firstly check whether the final value has been yielded, and then if so, to handle that value specifically.

Generator delegation

Generators can now delegate to another generator, Traversable object or array automatically, without needing to write boilerplate in the outermost generator by using the yield from construct.

<?php
function gen()
{
    yield 1;
    yield 2;
    yield from gen2();
}

function gen2()
{
    yield 3;
    yield 4;
}

foreach (gen() as $val)
{
    echo $val, PHP_EOL;
}
?>

The above example will output:

1
2
3
4

Integer division with intdiv()

The new intdiv() function performs an integer division of its operands and returns it.

<?php
var_dump(intdiv(10, 3));
?>

The above example will output:

int(3)

Session options

session_start() now accepts an array of options that override the session configuration directives normally set in php.ini.

These options have also been expanded to support session.lazy_write, which is on by default and causes PHP to only overwrite any session file if the session data has changed, and read_and_close, which is an option that can only be passed to session_start() to indicate that the session data should be read and then the session should immediately be closed unchanged.

For example, to set session.cache_limiter to private and immediately close the session after reading it:

<?php
session_start([
    'cache_limiter' => 'private',
    'read_and_close' => true,
]);
?>

preg_replace_callback_array()

The new preg_replace_callback_array() function enables code to be written more cleanly when using the preg_replace_callback() function. Prior to PHP 7, callbacks that needed to be executed per regular expression required the callback function to be polluted with lots of branching.

Now, callbacks can be registered to each regular expression using an associative array, where the key is a regular expression and the value is a callback.

CSPRNG Functions

Two new functions have been added to generate cryptographically secure integers and strings in a cross platform way: random_bytes() and random_int().

list() can always unpack objects implementing ArrayAccess

Previously, list() was not guaranteed to operate correctly with objects implementing ArrayAccess. This has been fixed.

Other Features

  • Class member access on cloning has been added, e.g. (clone $foo)->bar().


Deprecated features in PHP 7.0.x

PHP 4 style constructors

PHP 4 style constructors (methods that have the same name as the class they are defined in) are deprecated, and will be removed in the future. PHP 7 will emit E_DEPRECATED if a PHP 4 constructor is the only constructor defined within a class. Classes that implement a __construct() method are unaffected.

<?php
class foo {
    function foo() {
        echo 'I am the constructor';
    }
}
?>

The above example will output:

Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; foo has a deprecated constructor in example.php on line 3

Static calls to non-static methods

Static calls to methods that are not declared static are deprecated, and may be removed in the future.

<?php
class foo {
    function bar() {
        echo 'I am not static!';
    }
}

foo::bar();
?>

The above example will output:

Deprecated: Non-static method foo::bar() should not be called statically in - on line 8
I am not static!

password_hash() salt option

The salt option for the password_hash() function has been deprecated to prevent developers from generating their own (usually insecure) salts. The function itself generates a cryptographically secure salt when no salt is provided by the developer - therefore custom salt generation should not be needed.

capture_session_meta SSL context option

The capture_session_meta SSL context option has been deprecated. SSL metadata is now available through the stream_get_meta_data() function.

LDAP deprecations

The following function has been deprecated:

  • ldap_sort()


Changed functions

PHP Core

  • debug_zval_dump() now prints "int" instead of "long", and "float" instead of "double"
  • dirname() now optionally takes a second parameter, depth, to get the name of the directory depth levels up from the current directory.
  • getrusage() is now supported on Windows.
  • mktime() and gmmktime() functions no longer accept is_dst parameter.
  • preg_replace() function no longer supports "\e" (PREG_REPLACE_EVAL). preg_replace_callback() should be used instead.
  • setlocale() function no longer accepts category passed as string. LC_* constants must be used instead.
  • exec(), system() and passthru() functions have NULL byte protection now.
  • shmop_open() now returns a resource instead of an int, which has to be passed to shmop_size(), shmop_write(), shmop_read(), shmop_close() and shmop_delete().
  • substr() and iconv_substr() now return an empty string, if string is equal to start characters long.
  • xml_parser_free() is no longer sufficient to free the parser resource, if it references an object and this object references that parser resource. In this case it is necessary to additionally unset the $parser.


New functions

Closure

  • Closure::call()

CSPRNG

  • random_bytes()
  • random_int()

Error Handling and Logging

  • error_clear_last()

Generator

  • Generator::getReturn()

GNU Multiple Precision

  • gmp_random_seed()

Math

  • intdiv()

PCRE

  • preg_replace_callback_array()

PHP Options/Info

  • gc_mem_caches()
  • get_resources()

POSIX

  • posix_setrlimit()

Reflection

  • ReflectionParameter::getType()
  • ReflectionParameter::hasType()
  • ReflectionFunctionAbstract::getReturnType()
  • ReflectionFunctionAbstract::hasReturnType()

Zip

  • ZipArchive::setCompressionIndex()
  • ZipArchive::setCompressionName()

Zlib Compression

  • inflate_add()
  • deflate_add()
  • inflate_init()
  • deflate_init()


New Classes and Interfaces

Intl

  • IntlChar

Reflection

  • ReflectionGenerator
  • ReflectionType

Session Handling

  • SessionUpdateTimestampHandlerInterface

Exception Hierarchy

  • Throwable
  • Error
  • TypeError
  • ParseError
  • AssertionError
  • ArithmeticError
  • DivisionByZeroError


New Global Constants

Core Predefined Constants

  • PHP_INT_MIN

GD

  • IMG_WEBP (as of PHP 7.0.10)

JSON

  • JSON_ERROR_INVALID_PROPERTY_NAME
  • JSON_ERROR_UTF16

LibXML

  • LIBXML_BIGLINES

PCRE

  • PREG_JIT_STACKLIMIT_ERROR

POSIX

  • POSIX_RLIMIT_AS
  • POSIX_RLIMIT_CORE
  • POSIX_RLIMIT_CPU
  • POSIX_RLIMIT_DATA
  • POSIX_RLIMIT_FSIZE
  • POSIX_RLIMIT_LOCKS
  • POSIX_RLIMIT_MEMLOCK
  • POSIX_RLIMIT_MSGQUEUE
  • POSIX_RLIMIT_NICE
  • POSIX_RLIMIT_NOFILE
  • POSIX_RLIMIT_NPROC
  • POSIX_RLIMIT_RSS
  • POSIX_RLIMIT_RTPRIO
  • POSIX_RLIMIT_RTTIME
  • POSIX_RLIMIT_SIGPENDING
  • POSIX_RLIMIT_STACK
  • POSIX_RLIMIT_INFINITY

Zlib

  • ZLIB_ENCODING_RAW
  • ZLIB_ENCODING_DEFLATE
  • ZLIB_ENCODING_GZIP
  • ZLIB_FILTERED
  • ZLIB_HUFFMAN_ONLY
  • ZLIB_FIXED
  • ZLIB_RLE
  • ZLIB_DEFAULT_STRATEGY
  • ZLIB_BLOCK
  • ZLIB_FINISH
  • ZLIB_FULL_FLUSH
  • ZLIB_NO_FLUSH
  • ZLIB_PARTIAL_FLUSH
  • ZLIB_SYNC_FLUSH


Changes in SAPI Modules

FPM

Unqualified listen ports now listen on both IPv4 and IPv6

In PHP 5, a listen directive with only a port number would listen on all interfaces, but only on IPv4. PHP 7 will now accept requests made via both IPv4 and IPv6.

This does not affect directives which include specific IP addresses; these will continue to only listen on that address and protocol.


Removed Extensions and SAPIs

Removed Extensions

  • ereg
  • mssql
  • mysql
  • sybase_ct

Removed SAPIs

  • aolserver
  • apache
  • apache_hooks
  • apache2filter
  • caudium
  • continuity
  • isapi
  • milter
  • nsapi
  • phttpd
  • pi3web
  • roxen
  • thttpd
  • tux
  • webjames


Other Changes

Loosening Reserved Word Restrictions

Globally reserved words as property, constant, and method names within classes, interfaces, and traits are now allowed. This reduces the surface of BC breaks when new keywords are introduced and avoids naming restrictions on APIs.

This is particularly useful when creating internal DSLs with fluent interfaces:

<?php
// 'new', 'private', and 'for' were previously unusable
Project::new('Project Name')->private()->for('purpose here')->with('username here');
?>

The only limitation is that the class keyword still cannot be used as a constant name, otherwise it would conflict with the class name resolution syntax (ClassName::class).

Removal of date.timezone Warning

Previously, a warning was emitted if the date.timezone INI setting had not been set prior to using any date- or time-based functions. Now, this warning has been removed (with date.timezone still defaulting to UTC).


Migrating from PHP 5.5.x to PHP 5.6.x

Table of Contents

  • Backward incompatible changes
  • New features
  • Deprecated features in PHP 5.6.x
  • Changed functions
  • New functions
  • OpenSSL changes in PHP 5.6.x
  • Other changes to extensions
  • New global constants

Most improvements in PHP 5.6.x have no impact on existing code. There are a few incompatibilities and new features that should be considered, and code should be tested before switching PHP versions in production environments.

See also the migration guides for PHP versions 5.0.x, 5.1.x, 5.2.x, 5.3.x, 5.4.x and 5.5.x.


Backward incompatible changes

Although most existing PHP 5 code should work without changes, please take note of some backward incompatible changes:

Array keys won't be overwritten when defining an array as a property of a class via an array literal

Previously, arrays declared as class properties which mixed explicit and implicit keys could have array elements silently overwritten if an explicit key was the same as a sequential implicit key. For example:

<?php
class C {
    const ONE = 1;
    public $array = [
        self::ONE => 'foo',
        'bar',
        'quux',
    ];
}

var_dump((new C)->array);
?>

Output of the above example in PHP 5.5:

array(2) {
  [0]=>
  string(3) "bar"
  [1]=>
  string(4) "quux"
}

Output of the above example in PHP 5.6:

array(3) {
  [1]=>
  string(3) "foo"
  [2]=>
  string(3) "bar"
  [3]=>
  string(4) "quux"
}

json_decode() strictness

json_decode() now rejects non-lowercase variants of the JSON literals true, false and null at all times, as per the JSON specification, and sets json_last_error() accordingly. Previously, inputs to json_decode() that consisted solely of one of these values in upper or mixed case were accepted.

This change will only affect cases where invalid JSON was being passed to json_decode(): valid JSON input is unaffected and will continue to be parsed normally.

Stream wrappers now verify peer certificates and host names by default when using SSL/TLS

All encrypted client streams now enable peer verification by default. By default, this will use OpenSSL's default CA bundle to verify the peer certificate. In most cases, no changes will need to be made to communicate with servers with valid SSL certificates, as distributors generally configure OpenSSL to use known good CA bundles.

The default CA bundle may be overridden on a global basis by setting either the openssl.cafile or openssl.capath configuration setting, or on a per request basis by using the cafile or capath context options.

While not recommended in general, it is possible to disable peer certificate verification for a request by setting the verify_peer context option to FALSE, and to disable peer name validation by setting the verify_peer_name context option to FALSE.

GMP resources are now objects

GMP resources are now objects. The functional API implemented in the GMP extension has not changed, and code should run unmodified unless it checks explicitly for a resource using is_resource() or similar.

Mcrypt functions now require valid keys and IVs

mcrypt_encrypt(), mcrypt_decrypt(), mcrypt_cbc(), mcrypt_cfb(), mcrypt_ecb(), mcrypt_generic() and mcrypt_ofb() will no longer accept keys or IVs with incorrect sizes, and block cipher modes that require IVs will now fail if an IV isn't provided.

cURL file uploads

Uploads using the @file syntax now require CURLOPT_SAFE_UPLOAD to be set to FALSE. CURLFile should be used instead.


New features

Constant expressions

It is now possible to provide a scalar expression involving numeric and string literals and/or constants in contexts where PHP previously expected a static value, such as constant and property declarations and default function arguments.

<?php
const ONE = 1;
const TWO = ONE * 2;

class C {
    const THREE = TWO + 1;
    const ONE_THIRD = ONE / self::THREE;
    const SENTENCE = 'The value of THREE is '.self::THREE;

    public function f($a = ONE + self::THREE) {
        return $a;
    }
}

echo (new C)->f()."\n";
echo C::SENTENCE;
?>

The above example will output:

4
The value of THREE is 3

It is also now possible to define a constant array using the const keyword:

<?php
const ARR = ['a', 'b'];

echo ARR[0];
?>

The above example will output:

a

Variadic functions via ...

Variadic functions can now be implemented using the ... operator, instead of relying on func_get_args().

<?php
function f($req, $opt = null, ...$params) {
    // $params is an array containing the remaining arguments.
    printf('$req: %d; $opt: %d; number of params: %d'."\n",
           $req, $opt, count($params));
}

f(1);
f(1, 2);
f(1, 2, 3);
f(1, 2, 3, 4);
f(1, 2, 3, 4, 5);
?>

The above example will output:

$req: 1; $opt: 0; number of params: 0
$req: 1; $opt: 2; number of params: 0
$req: 1; $opt: 2; number of params: 1
$req: 1; $opt: 2; number of params: 2
$req: 1; $opt: 2; number of params: 3

Argument unpacking via ...

Arrays and Traversable objects can be unpacked into argument lists when calling functions by using the ... operator. This is also known as the splat operator in other languages, including Ruby.

<?php
function add($a, $b, $c) {
    return $a + $b + $c;
}

$operators = [2, 3];
echo add(1, ...$operators);
?>

The above example will output:

6

Exponentiation via **

A right associative ** operator has been added to support exponentiation, along with a **= shorthand assignment operator.

<?php
printf("2 ** 3 ==      %d\n", 2 ** 3);
printf("2 ** 3 ** 2 == %d\n", 2 ** 3 ** 2);

$a = 2;
$a **= 3;
printf("a ==           %d\n", $a);
?>

The above example will output:

2 ** 3 ==      8
2 ** 3 ** 2 == 512
a ==           8

use function and use const

The use operator has been extended to support importing functions and constants in addition to classes. This is achieved via the use function and use const constructs, respectively.

<?php
namespace Name\Space {
    const FOO = 42;
    function f() { echo __FUNCTION__."\n"; }
}

namespace {
    use const Name\Space\FOO;
    use function Name\Space\f;

    echo FOO."\n";
    f();
}
?>

The above example will output:

42
Name\Space\f

phpdbg

PHP now includes an interactive debugger called phpdbg implemented as a SAPI module. For more information, please visit the phpdbg documentation.

Default character encoding

default_charset is now used as the default character set for the htmlentities(), html_entity_decode() and htmlspecialchars() functions. Note that if the (now deprecated) iconv and mbstring encoding settings are set, they will take precedence over default_charset for iconv and mbstring functions, respectively.

The default value for this setting is UTF-8.

php://input is reusable

php://input may now be reopened and read as many times as required. This work has also resulted in a major reduction in the amount of memory required to deal with POST data.

Large file uploads

Files larger than 2 gigabytes in size are now accepted.

GMP supports operator overloading

GMP objects now support operator overloading and casting to scalar types. This allows for more expressive code using GMP:

<?php
$a = gmp_init(42);
$b = gmp_init(17);

if (version_compare(PHP_VERSION, '5.6', '<')) {
    echo gmp_intval(gmp_add($a, $b)), PHP_EOL;
    echo gmp_intval(gmp_add($a, 17)), PHP_EOL;
    echo gmp_intval(gmp_add(42, $b)), PHP_EOL;
} else {
    echo $a + $b, PHP_EOL;
    echo $a + 17, PHP_EOL;
    echo 42 + $b, PHP_EOL;
}
?>

The above example will output:

59
59
59

hash_equals() for timing attack safe string comparison

The hash_equals() function has been added to compare two strings in constant time. This should be used to mitigate timing attacks; for instance, when testing crypt() password hashes (assuming that you are unable to use password_hash() and password_verify(), which aren't susceptible to timing attacks).

<?php
$expected  = crypt('12345', '$2a$07$usesomesillystringforsalt$');
$correct   = crypt('12345', '$2a$07$usesomesillystringforsalt$');
$incorrect = crypt('1234',  '$2a$07$usesomesillystringforsalt$');

var_dump(hash_equals($expected, $correct));
var_dump(hash_equals($expected, $incorrect));
?>

The above example will output:

bool(true)
bool(false)

__debugInfo()

The __debugInfo() magic method has been added to allow objects to change the properties and values that are shown when the object is output using var_dump().

<?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)
}

gost-crypto hash algorithm

The gost-crypto hash algorithm has been added. This implements the GOST hash function using the CryptoPro S-box tables as specified by » RFC 4357, section 11.2.

SSL/TLS improvements

A wide range of improvements have been made to the SSL/TLS support in PHP 5.6. These include enabling peer verification by default, supporting certificate fingerprint matching, mitigating against TLS renegotiation attacks, and many new SSL context options to allow more fine grained control over protocol and verification settings when using encrypted streams.

These changes are described in more detail in the OpenSSL changes in PHP 5.6.x section of this migration guide.

pgsql async support

The pgsql extension now supports asynchronous connections and queries, thereby enabling non-blocking behaviour when interacting with PostgreSQL databases. Asynchronous connections may be established via the PGSQL_CONNECT_ASYNC constant, and the new pg_connect_poll(), pg_socket(), pg_consume_input() and pg_flush() functions may be used to handle asynchronous connections and queries.


Deprecated features in PHP 5.6.x

Calls from incompatible context

Methods called from an incompatible context are now deprecated, and will generate E_DEPRECATED errors when invoked instead of E_STRICT. Support for these calls will be removed in a future version of PHP.

An example of such a call is:

<?php
class A {
    function f() { echo get_class($this); }
}

class B {
    function f() { A::f(); }
}

(new B)->f();
?>

The above example will output:

Deprecated: Non-static method A::f() should not be called statically, assuming $this from incompatible context in - on line 7
B

$HTTP_RAW_POST_DATA and always_populate_raw_post_data

always_populate_raw_post_data will now generate an E_DEPRECATED error when $HTTP_RAW_POST_DATA is populated. New code should use php://input instead of $HTTP_RAW_POST_DATA, which will be removed in a future release. You can opt in for the new behaviour (in which $HTTP_RAW_POST_DATA is never defined hence no E_DEPRECATED error will be generated) by setting always_populate_raw_post_data to -1.

iconv and mbstring encoding settings

The iconv and mbstring configuration options related to encoding have been deprecated in favour of default_charset. The deprecated options are:

  • iconv.input_encoding
  • iconv.output_encoding
  • iconv.internal_encoding
  • mbstring.http_input
  • mbstring.http_output
  • mbstring.internal_encoding


Changed functions

PHP Core

  • crypt() will now raise an E_NOTICE error if the salt parameter is omitted.
  • substr_compare() will now accept 0 for its length parameter.
  • unserialize() will now fail if passed serialised data that has been manipulated to attempt to instantiate an object without calling its constructor.

cURL

  • Uploads using the @file syntax are now only supported if the CURLOPT_SAFE_UPLOAD option is set to FALSE. CURLFile should be used instead.

Mcrypt

  • The source parameter of mcrypt_create_iv() now defaults to MCRYPT_DEV_URANDOM instead of MCRYPT_DEV_RANDOM.

OpenSSL

  • stream_socket_enable_crypto() now allows the crypto_type parameter to be optional if the stream's SSL context includes the new crypto_type option.

PostgreSQL

  • pg_insert(), pg_select(), pg_update() and pg_delete() are no longer experimental.
  • pg_send_execute(), pg_send_prepare(), pg_send_query() and pg_send_query_params() will no longer block until query write completion if the underlying socket stream for the database connection is set to non-blocking mode.

Reflection

  • ReflectionClass::newInstanceWithoutConstructor() now allows non-final internal classes to be instantiated.

XMLReader

  • XMLReader::getAttributeNs() and XMLReader::getAttributeNo() now return NULL if the attribute could not be found, like XMLReader::getAttribute().


New functions

Date and Time

  • DateTimeImmutable::createFromMutable()

GMP

  • gmp_root()
  • gmp_rootrem()

Hash

  • hash_equals()

LDAP

  • ldap_escape()
  • ldap_modify_batch()

MySQLi

  • mysqli_get_links_stats()

OCI8

  • oci_get_implicit_resultset()

OpenSSL

  • openssl_get_cert_locations()
  • openssl_x509_fingerprint()
  • openssl_spki_new()
  • openssl_spki_verify()
  • openssl_spki_export_challenge()
  • openssl_spki_export()

PostgreSQL

  • pg_connect_poll()
  • pg_consume_input()
  • pg_flush()
  • pg_socket()

PDO_PGSQL

  • PDO::pgsqlGetNotify()
  • PDO::pgsqlGetPid()

Session

  • session_abort()
  • session_reset()

Zip

  • ZipArchive::setPassword()


OpenSSL changes in PHP 5.6.x

Stream wrappers now verify peer certificates and host names by default when using SSL/TLS

All encrypted client streams now enable peer verification by default. By default, this will use OpenSSL's default CA bundle to verify the peer certificate. In most cases, no changes will need to be made to communicate with servers with valid SSL certificates, as distributors generally configure OpenSSL to use known good CA bundles.

The default CA bundle may be overridden on a global basis by setting either the openssl.cafile or openssl.capath configuration setting, or on a per request basis by using the cafile or capath context options.

While not recommended in general, it is possible to disable peer certificate verification for a request by setting the verify_peer context option to FALSE, and to disable peer name validation by setting the verify_peer_name context option to FALSE.

Certificate fingerprints

Support has been added for extracting and verifying certificate fingerprints. openssl_x509_fingerprint() has been added to extract a fingerprint from an X.509 certificate, and two SSL stream context options have been added: capture_peer_cert to capture the peer's X.509 certificate, and peer_fingerprint to assert that the peer's certificate should match the given fingerprint.

Default ciphers updated

The default ciphers used by PHP have been updated to a more secure list based on the » Mozilla cipher recommendations, with two additional exclusions: anonymous Diffie-Hellman ciphers, and RC4.

This list can be accessed via the new OPENSSL_DEFAULT_STREAM_CIPHERS constant, and can be overridden (as in previous PHP versions) by setting the ciphers context option.

Compression disabled by default

SSL/TLS compression has been disabled by default to mitigate the CRIME attack. PHP 5.4.13 added a disable_compression context option to allow compression to be disabled: this is now set to TRUE (that is, compression is disabled) by default.

Allow servers to prefer their cipher order

The honor_cipher_order SSL context option has been added to allow encrypted stream servers to mitigate BEAST vulnerabilities by preferring the server's ciphers to the client's.

Access the negotiated protocol and cipher

The protocol and cipher that were negotiated for an encrypted stream can now be accessed via stream_get_meta_data() or stream_context_get_options() when the capture_session_meta SSL context option is set to TRUE.

<?php
$ctx = stream_context_create(['ssl' => [
    'capture_session_meta' => TRUE
]]);

$html = file_get_contents('https://google.com/', FALSE, $ctx);
$meta = stream_context_get_options($ctx)['ssl']['session_meta'];
var_dump($meta);
?>

The above example will output:

array(4) {
  ["protocol"]=>
  string(5) "TLSv1"
  ["cipher_name"]=>
  string(20) "ECDHE-RSA-AES128-SHA"
  ["cipher_bits"]=>
  int(128)
  ["cipher_version"]=>
  string(11) "TLSv1/SSLv3"
}

New options for perfect forward secrecy in encrypted stream servers

Encrypted client streams already support perfect forward secrecy, as it is generally controlled by the server. PHP encrypted server streams using certificates capable of perfect forward secrecy do not need to take any additional action to enable PFS; however a number of new SSL context options have been added to allow more control over PFS and deal with any compatibility issues that may arise.

ecdh_curve

This option allows the selection of a specific curve for use with ECDH ciphers. If not specified, prime256v1 will be used.

dh_param

A path to a file containing parametrs for Diffie-Hellman key exchange, such as that created by the following command:

openssl dhparam -out /path/to/my/certs/dh-2048.pem 2048
single_dh_use

If set to TRUE, a new key pair will be created when using Diffie-Hellman parameters, thereby improving forward secrecy.

single_ecdh_use

If set to TRUE, a new key pair will always be generated when ECDH cipher suites are negotiated. This improves forward secrecy.

SSL/TLS version selection

It is now possible to select specific versions of SSL and TLS via the crypto_method SSL context option or by specifying a specific transport when creating a stream wrapper (for example, by calling stream_socket_client() or stream_socket_server()).

The crypto_method SSL context option accepts a bitmask enumerating the protocols that are permitted, as does the crypto_type of stream_socket_enable_crypto().

Selected protocol versions and corresponding options
Protocol(s) | Client flag | Server flag | Transport
Any TLS or SSL version | STREAM_CRYPTO_METHOD_ANY_CLIENT | STREAM_CRYPTO_METHOD_ANY_SERVER | ssl://
Any TLS version | STREAM_CRYPTO_METHOD_TLS_CLIENT | STREAM_CRYPTO_METHOD_TLS_SERVER | tls://
TLS 1.0 | STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_0_SERVER | tlsv1.0://
TLS 1.1 | STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_1_SERVER | tlsv1.1://
TLS 1.2 | STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT | STREAM_CRYPTO_METHOD_TLSv1_2_SERVER | tlsv1.2://
SSL 3 | STREAM_CRYPTO_METHOD_SSLv3_CLIENT | STREAM_CRYPTO_METHOD_SSLv3_SERVER | sslv3://
<?php

// Requiring TLS 1.0 or better when using file_get_contents():
$ctx = stream_context_create([
    'ssl' => [
        'crypto_method' => STREAM_CRYPTO_METHOD_TLS_CLIENT,
    ],
]);
$html = file_get_contents('https://google.com/', false, $ctx);

// Requiring TLS 1.1 or 1.2:
$ctx = stream_context_create([
    'ssl' => [
        'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT |
                           STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT,
    ],
]);
$html = file_get_contents('https://google.com/', false, $ctx);

// Connecting using the tlsv1.2:// stream socket transport.
$sock = stream_socket_client('tlsv1.2://google.com:443/');

?>

openssl_get_cert_locations() added

The openssl_get_cert_locations() function has been added: it returns the default locations PHP will search when looking for CA bundles.

<?php
var_dump(openssl_get_cert_locations());
?>

The above example will output:

array(8) {
  ["default_cert_file"]=>
  string(21) "/etc/pki/tls/cert.pem"
  ["default_cert_file_env"]=>
  string(13) "SSL_CERT_FILE"
  ["default_cert_dir"]=>
  string(18) "/etc/pki/tls/certs"
  ["default_cert_dir_env"]=>
  string(12) "SSL_CERT_DIR"
  ["default_private_dir"]=>
  string(20) "/etc/pki/tls/private"
  ["default_default_cert_area"]=>
  string(12) "/etc/pki/tls"
  ["ini_cafile"]=>
  string(0) ""
  ["ini_capath"]=>
  string(0) ""
}

SPKI support

Support has been added for generating, extracting and verifying signed public key and challenges (SPKAC). openssl_spki_new(), openssl_spki_verify(), openssl_spki_export_challenge(), and openssl_spki_export() have been added to create, verify export PEM public key and associated challenge from SPKAC's generated from a KeyGen HTML5 element.

openssl_spki_new

Generates a new SPKAC using private key, challenge string and hashing algorithm.

<?php
$pkey = openssl_pkey_new();
openssl_pkey_export($pkey, 'secret passphrase');

$spkac = openssl_spki_new($pkey, 'challenge string');
?>

The above example will output:

SPKAC=MIIBXjCByDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA3L0IfUijj7+A8CPC8EmhcdNoe5fUAog7OrBdhn7EkxFButUp40P7+LiYiygYG1TmoI/a5EgsLU3s9twEz3hmgY9mYIqb/rb+SF8qlD/K6KVyUORC7Wlz1Df4L8O3DuRGzx6/+3jIW6cPBpfgH1sVuYS1vDBsP/gMMIxwTsKJ4P0CAwEAARYkYjViMzYxMTktNjY5YS00ZDljLWEyYzctMGZjNGFhMjVlMmE2MA0GCSqGSIb3DQEBAwUAA4GBAF7hu0ifzmjonhAak2FhhBRsKFDzXdKIkrWxVNe8e0bZzMrWOxFM/rqBgeH3/gtOUDRS5Fnzyq425UsTYbjfiKzxGeCYCQJb1KJ2V5Ij/mIJHZr53WYEXHQTNMGR8RPm7IxwVXVSHIgAfXsXZ9IXNbFbcaLRiSTr9/N4U+MXUWL7
openssl_spki_verify

Verifies provided SPKAC.

<?php
$pkey = openssl_pkey_new();
openssl_pkey_export($pkey, 'secret passphrase');

$spkac = openssl_spki_new($pkey, 'challenge string');
var_dump(openssl_spki_verify($spkac));
?>
openssl_spki_export_challenge

Exports associated challenge from provided SPKAC.

<?php
$pkey = openssl_pkey_new();
openssl_pkey_export($pkey, 'secret passphrase');

$spkac = openssl_spki_new($pkey, 'challenge string');
$challenge = openssl_spki_export_challenge($spkac):
echo $challenge;
?>

The above example will output:

challenge string
openssl_spki_export

Exports the PEM formatted RSA public key from SPKAC.

<?php
$pkey = openssl_pkey_new();
openssl_pkey_export($pkey, 'secret passphrase');

$spkac = openssl_spki_new($pkey, 'challenge string');
echo openssl_spki_export($spkac);
?>

The above example will output:

-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDcvQh9SKOPv4DwI8LwSaFx02h7
l9QCiDs6sF2GfsSTEUG61SnjQ/v4uJiLKBgbVOagj9rkSCwtTez23ATPeGaBj2Zg
ipv+tv5IXyqUP8ropXJQ5ELtbXPUN/gvw7cO5EbPHr/7eMhbpw8Gl+AfWxW5hLW8
MGw/+AwwjHBOwong/QIDAQAB
-----END PUBLIC KEY-----


Other changes to extensions

cURL

A number of constants marked obsolete in the cURL library have now been removed:

  • CURLOPT_CLOSEPOLICY
  • CURLCLOSEPOLICY_CALLBACK
  • CURLCLOSEPOLICY_LEAST_RECENTLY_USED
  • CURLCLOSEPOLICY_LEAST_TRAFFIC
  • CURLCLOSEPOLICY_OLDEST
  • CURLCLOSEPOLICY_SLOWEST

OCI8

  • Support for implicit result sets for Oracle Database 12c has been added via the new oci_get_implicit_resultset() function.
  • Using oci_execute($s, OCI_NO_AUTO_COMMIT) for a SELECT no longer unnecessarily initiates an internal ROLLBACK during connection close.
  • Added DTrace probes controlled by the --enable-dtrace configure option.
  • oci_internal_debug() is now a no-op.
  • The phpinfo() output format for OCI8 has changed.

Zip

A --with-libzip configure option has been added to use a system libzip installation. libzip version 0.11 is required, with 0.11.2 or later recommended.

MySQLi

A new mysqli.rollback_on_cached_plink option was added, which controls the rollback behavior of persistent connections.


New global constants

GD

  • IMG_WEBP (as of PHP 5.6.25)

LDAP

  • LDAP_ESCAPE_DN
  • LDAP_ESCAPE_FILTER

OpenSSL

  • OPENSSL_DEFAULT_STREAM_CIPHERS
  • STREAM_CRYPTO_METHOD_ANY_CLIENT
  • STREAM_CRYPTO_METHOD_ANY_SERVER
  • STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT
  • STREAM_CRYPTO_METHOD_TLSv1_0_SERVER
  • STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT
  • STREAM_CRYPTO_METHOD_TLSv1_1_SERVER
  • STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
  • STREAM_CRYPTO_METHOD_TLSv1_2_SERVER

PostgreSQL

  • PGSQL_CONNECT_ASYNC
  • PGSQL_CONNECTION_AUTH_OK
  • PGSQL_CONNECTION_AWAITING_RESPONSE
  • PGSQL_CONNECTION_MADE
  • PGSQL_CONNECTION_SETENV
  • PGSQL_CONNECTION_SSL_STARTUP
  • PGSQL_CONNECTION_STARTED
  • PGSQL_DML_ESCAPE
  • PGSQL_POLLING_ACTIVE
  • PGSQL_POLLING_FAILED
  • PGSQL_POLLING_OK
  • PGSQL_POLLING_READING
  • PGSQL_POLLING_WRITING


Migrating from PHP 5.4.x to PHP 5.5.x

Table of Contents

  • What has changed in PHP 5.5.x
  • Backward Incompatible Changes
  • New features
  • Deprecated features in PHP 5.5.x
  • Changed Functions
  • New Functions
  • New Classes and Interfaces
  • New Methods
  • Other changes to extensions
  • New Global Constants
  • Changes to INI file handling
  • Changes to PHP Internals

See also the migration guides for PHP versions 5.0.x, 5.1.x, 5.2.x, 5.3.x, 5.4.x, 5.6.x, and 7.0.x.


What has changed in PHP 5.5.x

Most improvements in PHP 5.5.x have no impact on existing code. There are a few incompatibilities and new features that should be considered, and code should be tested before switching PHP versions in production environments.

For systems being upgraded from an older version of PHP, the relevant documentation is available at:

  • Upgrade Notes for PHP 5.4.x.
  • Upgrade Notes for PHP 5.3.x.
  • Upgrade Notes for PHP 5.2.x.
  • Upgrade Notes for PHP 5.1.x.
  • Migrating from PHP 4 to PHP 5.


Backward Incompatible Changes

Although most existing PHP 5 code should work without changes, please take note of some backward incompatible changes:

Windows XP and 2003 support dropped

Support for Windows XP and 2003 has been dropped. Windows builds of PHP now require Windows Vista or newer.

Case insensitivity no longer locale specific

All case insensitive matching for function, class and constant names is now performed in a locale independent manner according to ASCII rules. This improves support for languages using the Latin alphabet with unusual collating rules, such as Turkish and Azeri.

This may cause issues for code that uses case insensitive matches for non-ASCII characters in multibyte character sets (including UTF-8), such as accented characters in many European languages. If you have a non-English, non-ASCII code base, then you will need to test that you are not inadvertently relying on this behaviour before deploying PHP 5.5 to production systems.

pack() and unpack() changes

Changes were made to pack() and unpack() to make them more compatible with Perl:

  • pack() now supports the "Z" format code, which behaves identically to "a".
  • unpack() now support the "Z" format code for NULL padded strings, and behaves as "a" did in previous versions: it will strip trailing NULL bytes.
  • unpack() now keeps trailing NULL bytes when the "a" format code is used.
  • unpack() now strips all trailing ASCII whitespace when the "A" format code is used.

Writing backward compatible code that uses the "a" format code with unpack() requires the use of version_compare(), due to the backward compatibility break.

For example:

<?php
// Old code:
$data = unpack('a5', $packed);

// New code:
if (version_compare(PHP_VERSION, '5.5.0-dev', '>=')) {
  $data = unpack('Z5', $packed);
} else {
  $data = unpack('a5', $packed);
}
?>

self, parent and static are now always case insensitive

Prior to PHP 5.5, cases existed where the self, parent, and static keywords were treated in a case sensitive fashion. These have now been resolved, and these keywords are always handled case insensitively: SELF::CONSTANT is now treated identically to self::CONSTANT.

PHP logo GUIDs removed

The GUIDs that previously resulted in PHP outputting various logos have been removed. This includes the removal of the functions to return those GUIDs. The removed functions are:

  • php_logo_guid()
  • php_egg_logo_guid()
  • php_real_logo_guid()
  • zend_logo_guid()

Internal execution changes

Extension authors should note that the zend_execute() function can no longer be overridden, and that numerous changes have been made to the execute_data struct and related function and method handling opcodes.

Most extension authors are unlikely to be affected, but those writing extensions that hook deeply into the Zend Engine should read the notes on these changes.


New features

Generators added

Support for generators has been added via the yield keyword. Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the Iterator interface.

A simple example that reimplements the range() function as a generator (at least for positive step values):

<?php
function xrange($start, $limit, $step = 1) {
    for ($i = $start; $i <= $limit; $i += $step) {
        yield $i;
    }
}

echo 'Single digit odd numbers: ';

/*
 * Note that an array is never created or returned,
 * which saves memory.
 */
foreach (xrange(1, 9, 2) as $number) {
    echo "$number ";
}

echo "\n";
?>

The above example will output:

Single digit odd numbers: 1 3 5 7 9

finally keyword added

try-catch blocks now support a finally block for code that should be run regardless of whether an exception has been thrown or not.

New password hashing API

A new password hashing API that makes it easier to securely hash and manage passwords using the same underlying library as crypt() in PHP has been added. See the documentation for password_hash() for more detail.

foreach now supports list()

The foreach control structure now supports unpacking nested arrays into separate variables via the list() construct. For example:

<?php
$array = [
    [1, 2],
    [3, 4],
];

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

Further documentation is available on the foreach manual page.

empty() supports arbitrary expressions

Passing an arbitrary expression instead of a variable to empty() is now supported. For example:

<?php
function always_false() {
    return false;
}

if (empty(always_false())) {
    echo "This will be printed.\n";
}

if (empty(true)) {
    echo "This will not be printed.\n";
}
?>

The above example will output:

This will be printed.

array and string literal dereferencing

Array and string literals can now be dereferenced directly to access individual elements and characters:

<?php
echo 'Array dereferencing: ';
echo [1, 2, 3][0];
echo "\n";

echo 'String dereferencing: ';
echo 'PHP'[0];
echo "\n";
?>

The above example will output:

Array dereferencing: 1
String dereferencing: P

Class name resolution via ::class

It is possible to use ClassName::class to get a fully qualified name of class ClassName. For example:

<?php
namespace Name\Space;
class ClassName {}

echo ClassName::class;

echo "\n";
?>

The above example will output:

Name\Space\ClassName

OPcache extension added

The Zend Optimiser+ opcode cache has been added to PHP as the new OPcache extension. 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. See the installation instructions for more detail on enabling and using OPcache.

foreach now supports non-scalar keys

foreach now supports keys of any type. While non-scalar keys cannot occur in native PHP arrays, it is possible for Iterator::key() to return a value of any type, and this will now be handled correctly.

Apache 2.4 handler supported on Windows

The Apache 2.4 handler SAPI is now supported on Windows.

Improvements to GD

Various improvements have been made to the GD extension, these include:

  • Flipping support using the new imageflip() function.
  • Advanced cropping support using the imagecrop() & imagecropauto() functions.


Deprecated features in PHP 5.5.x

ext/mysql deprecation

The original MySQL extension is now deprecated, and will generate E_DEPRECATED errors when connecting to a database. Instead, use the MySQLi or PDO_MySQL extensions.

preg_replace() /e modifier

The preg_replace() /e modifier is now deprecated. Instead, use the preg_replace_callback() function.

intl deprecations

IntlDateFormatter::setTimeZoneID() and
datefmt_set_timezone_id() are now deprecated. Instead,
use the IntlDateFormatter::setTimeZone() method and
datefmt_set_timezone() function, respectively.

mcrypt deprecations

The following functions have been deprecated:

  • mcrypt_cbc()
  • mcrypt_cfb()
  • mcrypt_ecb()
  • mcrypt_ofb()


Changed Functions

PHP Core

  • set_error_handler() can now be called with NULL as an argument to reset the error handler.
  • When called with NULL, set_error_handler() and set_exception_handler() now return the previous error or exception handler, respectively.
  • json_encode() now accepts depth parameter.
  • The behaviour of pack() and unpack() with the "a" and "A" format codes has changed. Detailed notes on these changes are available.

intl

  • MessageFormatter::format() and related functions now accept named arguments and mixed numeric and named arguments when PHP is linked to ICU 4.8 or later.
  • MessageFormatter::format() and related functions no longer error when an insufficient number of arguments have been provided. Instead, the placeholders will not be substituted.
  • MessageFormatter::format() and MessageFormatter::parse() are no longer limited to second precision when dealing with times.
  • IntlDateFormatter::__construct() and datefmt_create() now accept IntlTimeZone and DateTimeZone objects for the timezone argument, and IntlCalendar objects for the calendar argument. Furthermore, if the time zone is omitted and the calendar doesn't specify a time zone, PHP's default time zone from date_default_timezone_get() is now used instead of the default ICU time zone.
  • IntlDateFormatter::getCalendar() and datefmt_get_calendar() return false if the IntlDateFormatter object was created with an IntlCalendar instance instead of one of the IntlDateFormatter constants.
  • IntlDateFormatter::setCalendar() and datefmt_set_calendar() now accept IntlCalendar objects in addition to the IntlDateFormatter constants.
  • IntlDateFormatter::format() and datefmt_format() now accept IntlCalendar objects.


New Functions

PHP Core

  • array_column()
  • boolval()
  • json_last_error_msg()
  • password_get_info()
  • password_hash()
  • password_needs_rehash()
  • password_verify()

Hash

  • hash_pbkdf2()

OpenSSL

  • openssl_pbkdf2()

cURL

  • curl_escape()
  • curl_file_create()
  • curl_multi_setopt()
  • curl_multi_strerror()
  • curl_pause()
  • curl_reset()
  • curl_share_close()
  • curl_share_init()
  • curl_share_setopt()
  • curl_strerror()
  • curl_unescape()

GD

  • imageaffinematrixconcat()
  • imageaffinematrixget()
  • imagecrop()
  • imagecropauto()
  • imageflip()
  • imagepalettetotruecolor()
  • imagescale()

MySQLi

  • mysqli_begin_transaction()
  • mysqli_release_savepoint()
  • mysqli_savepoint()

PostgreSQL

  • pg_escape_literal()
  • pg_escape_identifier()

Sockets

  • socket_sendmsg()
  • socket_recvmsg()
  • socket_cmsg_space()

CLI

  • cli_get_process_title()
  • cli_set_process_title()

Intl

  • datefmt_format_object()
  • datefmt_get_calendar_object()
  • datefmt_get_timezone()
  • datefmt_set_timezone()
  • datefmt_get_calendar_object()
  • intlcal_create_instance()
  • intlcal_get_keyword_values_for_locale()
  • intlcal_get_now()
  • intlcal_get_available_locales()
  • intlcal_get()
  • intlcal_get_time()
  • intlcal_set_time()
  • intlcal_add()
  • intlcal_set_time_zone()
  • intlcal_after()
  • intlcal_before()
  • intlcal_set()
  • intlcal_roll()
  • intlcal_clear()
  • intlcal_field_difference()
  • intlcal_get_actual_maximum()
  • intlcal_get_actual_minimum()
  • intlcal_get_day_of_week_type()
  • intlcal_get_first_day_of_week()
  • intlcal_get_greatest_minimum()
  • intlcal_get_least_maximum()
  • intlcal_get_locale()
  • intlcal_get_maximum()
  • intlcal_get_minimal_days_in_first_week()
  • intlcal_get_minimum()
  • intlcal_get_time_zone()
  • intlcal_get_type()
  • intlcal_get_weekend_transition()
  • intlcal_in_daylight_time()
  • intlcal_is_equivalent_to()
  • intlcal_is_lenient()
  • intlcal_is_set()
  • intlcal_is_weekend()
  • intlcal_set_first_day_of_week()
  • intlcal_set_lenient()
  • intlcal_equals()
  • intlcal_get_repeated_wall_time_option()
  • intlcal_get_skipped_wall_time_option()
  • intlcal_set_repeated_wall_time_option()
  • intlcal_set_skipped_wall_time_option()
  • intlcal_from_date_time()
  • intlcal_to_date_time()
  • intlcal_get_error_code()
  • intlcal_get_error_message()
  • intlgregcal_create_instance()
  • intlgregcal_set_gregorian_change()
  • intlgregcal_get_gregorian_change()
  • intlgregcal_is_leap_year()
  • intltz_create_time_zone()
  • intltz_create_default()
  • intltz_get_id()
  • intltz_get_gmt()
  • intltz_get_unknown()
  • intltz_create_enumeration()
  • intltz_count_equivalent_ids()
  • intltz_create_time_zone_id_enumeration()
  • intltz_get_canonical_id()
  • intltz_get_region()
  • intltz_get_tz_data_version()
  • intltz_get_equivalent_id()
  • intltz_use_daylight_time()
  • intltz_get_offset()
  • intltz_get_raw_offset()
  • intltz_has_same_rules()
  • intltz_get_display_name()
  • intltz_get_dst_savings()
  • intltz_from_date_time_zone()
  • intltz_to_date_time_zone()
  • intltz_get_error_code()
  • intltz_get_error_message()

SPL

  • SplFixedArray::__wakeup()


New Classes and Interfaces

cURL

  • CURLFile

Date and Time

  • DateTimeImmutable
  • DateTimeInterface

Intl

  • IntlCalendar
  • IntlGregorianCalendar
  • IntlTimeZone
  • IntlBreakIterator
  • IntlRuleBasedBreakIterator
  • IntlCodePointBreakIterator


New Methods

MySQLi

  • mysqli::begin_transaction()
  • mysqli::release_savepoint()
  • mysqli::savepoint()

Intl

  • IntlDateFormatter::formatObject()
  • IntlDateFormatter::getCalendarObject()
  • IntlDateFormatter::getTimeZone()
  • IntlDateFormatter::setTimeZone()


  • « New Methods
  • New Global Constants »
  • PHP Manual
  • Migrating from PHP 5.4.x to PHP 5.5.x
  • Other changes to extensions

Other changes to extensions

Intl

The intl extension now requires ICU 4.0 or later.


New Global Constants

GD

  • IMG_AFFINE_TRANSLATE
  • IMG_AFFINE_SCALE
  • IMG_AFFINE_ROTATE
  • IMG_AFFINE_SHEAR_HORIZONTAL
  • IMG_AFFINE_SHEAR_VERTICAL
  • IMG_CROP_DEFAULT
  • IMG_CROP_TRANSPARENT
  • IMG_CROP_BLACK
  • IMG_CROP_WHITE
  • IMG_CROP_SIDES
  • IMG_FLIP_BOTH
  • IMG_FLIP_HORIZONTAL
  • IMG_FLIP_VERTICAL
  • IMG_BELL
  • IMG_BESSEL
  • IMG_BICUBIC
  • IMG_BICUBIC_FIXED
  • IMG_BLACKMAN
  • IMG_BOX
  • IMG_BSPLINE
  • IMG_CATMULLROM
  • IMG_GAUSSIAN
  • IMG_GENERALIZED_CUBIC
  • IMG_HERMITE
  • IMG_HAMMING
  • IMG_HANNING
  • IMG_MITCHELL
  • IMG_POWER
  • IMG_QUADRATIC
  • IMG_SINC
  • IMG_NEAREST_NEIGHBOUR
  • IMG_WEIGHTED4
  • IMG_TRIANGLE

JSON

  • JSON_ERROR_RECURSION
  • JSON_ERROR_INF_OR_NAN
  • JSON_ERROR_UNSUPPORTED_TYPE

MySQLi

The MYSQLI_SERVER_PUBLIC_KEY option has been added for use with mysqli_options().


Changes to INI file handling

Intl

The intl.use_exceptions configuration directive has been added, which controls the behaviour of intl when global errors occur in conjunction with the already extant intl.error_level configuration directive.

MySQLnd

The mysqlnd.sha256_server_public_key configuration directive has been added to allow mysqli to use the new MySQL authentication protocol.


Changes to PHP Internals

  • Extensions cannot override zend_execute() any more and should override zend_execute_ex() instead. EG(current_execute_data) is already initialized in zend_execute_ex(), so for compatibility extensions may need to use EG(current_execute_data)->prev_execute_data instead.
  • Removed EG(arg_types_stack), EX(fbc), EX(called_scope) and EX(current_object).
  • Added op_array->nested_calls, which is calculated at compile time.
  • Added EX(call_slots), which is an array to store information about syntaticaly nested calls (e.g. foo(bar())) and is preallocated together with execute_data.
  • Added EX(call), which is a pointer to a current calling function, and is an element of EX(call_slots).
  • Opcodes INIT_METHOD_CALL, ZEND_INIT_STATIC_METHOD_CALL, ZEND_INIT_FCALL_BY_NAME and ZEND_INIT_NS_FCALL_BY_NAME use result.num as an index in EX(call_slots).
  • Opcode ZEND_NEW uses extended_value as an index in EX(call_slots).
  • Opcodes ZEND_DO_FCALL and ZEND_DO_FCALL_BY_NAME use op2.num as an index in EX(call_slots).
  • Added op_array->used_stack, which is calculated at compile time; the corresponding stack space is preallocated together with execute_data. As a result, the ZEND_SEND* and ZEND_DO_FCALL* opcodes no longer need to check for stack overflow.
  • Removed execute_data->Ts field. The VM temporary variables are always allocated immediately before the execute_data structure, and are now accessed by their offset from the execute_data base pointer instead of via execute_data->Ts. The compiler stores new offsets in op_array->opcodes[*].op?.num. The EX_TMP_VAR() and EX_TMP_VAR_NUM() macros can be used to access temporary variables by offset or number. You can convert the number to an offset using EX_TMP_VAR_NUM(0, num) or offset to number using (EX_TMP_VAR_NUM(0,0)-EX_TMP_VAR(0,offset)).
  • Removed the execute_data->CVs field. The VM compiled variables are always allocated immediately after the execute_data structure, and are now accessed by the offset from the execute_data base pointer instead of via execute_data->CVs. You can use the EX_CV_NUM() macro to access compiled variables by number.


Migrating from PHP 5.3.x to PHP 5.4.x

Table of Contents

  • What has changed in PHP 5.4.x
  • Backward Incompatible Changes
  • New features
  • Changes in SAPI modules
  • Deprecated features in PHP 5.4.x
  • Changed Functions
  • New Functions
  • New Classes and Interfaces
  • New Methods
  • Removed Extensions
  • Other changes to extensions
  • New Global Constants
  • Changes to INI file handling
  • Other changes

See also the migration guides for PHP versions 5.0.x, 5.1.x, 5.2.x, 5.3.x, 5.5.x and 5.6.x.


What has changed in PHP 5.4.x

Most improvements in PHP 5.4.x have no impact on existing code. There are a few incompatibilities and new features that should be considered, and code should be tested before switching PHP versions in production environments.

For systems being upgraded from an older version of PHP, the relevant documentation is available at:

  • Upgrade Notes for PHP 5.3.x.
  • Upgrade Notes for PHP 5.2.x.
  • Upgrade Notes for PHP 5.1.x.
  • Migrating from PHP 4 to PHP 5.


Backward Incompatible Changes

Although most existing PHP 5 code should work without changes, please take note of some backward incompatible changes:

  • Safe mode is no longer supported. Any applications that rely on safe mode may need adjustment, in terms of security.
  • Magic quotes has been removed. Applications relying on this feature may need to be updated, to avoid security issues. get_magic_quotes_gpc() and get_magic_quotes_runtime() now always return FALSE. set_magic_quotes_runtime() raises an E_CORE_ERROR level error on trying to enable Magic quotes.
  • The register_globals and register_long_arrays php.ini directives have been removed.
  • The mbstring.script_encoding directive has been removed. Use zend.script_encoding instead.
  • Call-time pass by reference has been removed.
  • The break and continue statements no longer accept variable arguments (e.g., break 1 + foo() * $bar;). Static arguments still work, such as break 2;. As a side effect of this change break 0; and continue 0; are no longer allowed.
  • In the date and time extension, the timezone can no longer be set using the TZ environment variable. Instead you have to specify a timezone using the date.timezone php.ini option or date_default_timezone_set() function. PHP will no longer attempt to guess the timezone, and will instead fall back to "UTC" and issue a E_WARNING.
  • Non-numeric string offsets - e.g. $a['foo'] where $a is a string - now return false on isset() and true on empty(), and produce a E_WARNING if you try to use them. Offsets of types double, bool and null produce a E_NOTICE. Numeric strings (e.g. $a['2']) still work as before. Note that offsets like '12.3' and '5 foobar' are considered non-numeric and produce a E_WARNING, but are converted to 12 and 5 respectively, for backward compatibility reasons. Note: Following code returns different result. $str='abc';var_dump(isset($str['x'])); // false for PHP 5.4 or later, but true for 5.3 or less
  • Converting an array to a string will now generate an E_NOTICE level error, but the result of the cast will still be the string "Array".
  • Turning NULL, FALSE, or an empty string into an object by adding a property will now emit an E_WARNING level error, instead of E_STRICT.
  • Parameter names that shadow super globals now cause a fatal error. This prohibits code like function foo($_GET, $_POST) {}.
  • The Salsa10 and Salsa20 hash algorithms have been removed.
  • The Tiger hash algorithm now uses big-endian byte ordering. Please follow this example to write code that is compatible with both PHP 5.3 and 5.4.
  • array_combine() now returns array() instead of FALSE when two empty arrays are provided as parameters.
  • If you use htmlentities() with asian character sets, it works like htmlspecialchars() - this has always been the case in previous versions of PHP, but now an E_STRICT level error is emitted.
  • The third parameter of ob_start() has changed from boolean erase to integer flags. Note that code that explicitly set erase to FALSE will no longer behave as expected in PHP 5.4: please follow this example to write code that is compatible with PHP 5.3 and 5.4.

The following keywords are now reserved, and may not be used as names by functions, classes, etc.

  • trait
  • callable
  • insteadof

The following functions have been removed from PHP:

  • define_syslog_variables()
  • import_request_variables()
  • session_is_registered(), session_register() and session_unregister().
  • The aliases
mysqli_bind_param(), mysqli_bind_result(),
mysqli_client_encoding(), mysqli_fetch(),
mysqli_param_count(), mysqli_get_metadata(),
mysqli_send_long_data(), mysqli::client_encoding() and mysqli_stmt::stmt().


New features

PHP 5.4.0 offers a wide range of new features:

  • Support for traits has been added.
  • Short array syntax has been added, e.g. $a = [1, 2, 3, 4]; or $a = ['one' => 1, 'two' => 2, 'three' => 3, 'four' => 4];.
  • Function array dereferencing has been added, e.g. foo()[0].
  • Closures now support $this.
  • <?= is now always available, regardless of the short_open_tag php.ini option.
  • Class member access on instantiation has been added, e.g. (new Foo)->bar().
  • Class::{expr}() syntax is now supported.
  • Binary number format has been added, e.g. 0b001001101.
  • Improved parse error messages and improved incompatible arguments warnings.
  • The session extension can now track the upload progress of files.
  • Built-in development web server in CLI mode.
  • The GD extension now supports reading and writing of WebP images via imagecreatefromwebp() and imagewebp(), respectively.


Changes in SAPI modules

  • A new SAPI module named cli-server is now available.
  • Added CLI option --rz which shows information of the named Zend extension.
  • Added shortcut #inisetting=value to change php.ini settings at run-time in interactive readline CLI
  • Added apache compatible functions: apache_child_terminate(),
getallheaders(), apache_request_headers()
and apache_response_headers() for FastCGI SAPI.
  • PHP-FPM: Added the process.max setting, to control the number of processes that FPM can fork.


  • « Changes in SAPI modules
  • Changed Functions »
  • PHP Manual
  • Migrating from PHP 5.3.x to PHP 5.4.x
  • Deprecated features in PHP 5.4.x

Deprecated features in PHP 5.4.x

Deprecated functions:

  • mysql_list_dbs()


Changed Functions

Several functions were given new, optional parameters in PHP 5.4:

PHP Core:

  • Added the optional limit parameter to debug_backtrace() and debug_print_backtrace(), to limit the amount of stack frames returned.
  • is_link() now works properly for symbolic links on Windows Vista or later. Earlier systems do not support symbolic links.
  • parse_url() now recognizes the host when a scheme is omitted, and a leading component separator is present. As of PHP 5.4.7.

OpenSSL:

  • Added a no padding option to the openssl_encrypt() and openssl_decrypt() functions.

Intl:

  • idn_to_ascii() and idn_to_utf8() now take two extra parameters, one indicating the variant (IDNA 2003 or UTS #46) and another, passed by reference, to return details about the operation in case UTS #46 is chosen.


New Functions

PHP 5.4 introduced some new functions:

PHP Core:

  • hex2bin()
  • http_response_code()
  • get_declared_traits()
  • getimagesizefromstring()
  • stream_set_chunk_size()
  • socket_import_stream()
  • trait_exists()
  • header_register_callback()

SPL:

  • class_uses()

Session:

  • session_status()
  • session_register_shutdown()

Mysqli:

  • mysqli_error_list()
  • mysqli_stmt_error_list()

Libxml:

  • libxml_set_external_entity_loader()

LDAP:

  • ldap_control_paged_result()
  • ldap_control_paged_result_response()

Intl:

  • transliterator_create()
  • transliterator_create_from_rules()
  • transliterator_create_inverse()
  • transliterator_get_error_code()
  • transliterator_get_error_message()
  • transliterator_list_ids()
  • transliterator_transliterate()

Zlib:

  • zlib_decode()
  • zlib_encode()


New Classes and Interfaces

The following classes were introduced in PHP 5.4.0:

SPL:

  • CallbackFilterIterator
  • RecursiveCallbackFilterIterator

Reflection:

  • ReflectionZendExtension

Json:

  • JsonSerializable

Session:

  • SessionHandler
  • SessionHandlerInterface

Snmp:

  • SNMP

Intl:

  • Transliterator
  • Spoofchecker


New Methods

Several new methods were introduced in 5.4.0:

XSL:

  • XsltProcessor::setSecurityPrefs()
  • XsltProcessor::getSecurityPrefs()

SPL:

  • RegexIterator::getRegex()
  • SplObjectStorage::getHash()
  • DirectoryIterator::getExtension()
  • SplDoublyLinkedList::serialize()
  • SplDoublyLinkedList::unserialize()
  • SplFileInfo::getExtension()
  • SplFileObject::fputcsv()
  • SplQueue::serialize()
  • SplQueue::unserialize()
  • SplStack::serialize()
  • SplStack::unserialize()
  • SplTempFileObject::fputcsv()

Reflection:

  • ReflectionExtension::isPersistent()
  • ReflectionExtension::isTemporary()
  • ReflectionClass::isCloneable()

Closure:

  • Closure::bind()
  • Closure::bindTo()

PDO_dblib:

  • PDO::newRowset()

StreamWrapper:

  • StreamWrapper::stream_metadata()
  • StreamWrapper::stream_truncate()


Removed Extensions

These extensions have been moved to PECL and are no longer part of the PHP distribution. The PECL package versions of these extensions will be created according to user demand.

  • sqlite - Note that ext/sqlite3 and ext/pdo_sqlite are not affected


Other changes to extensions

Changes in extension behavior, and new features:

  • mysqli - mysqli_result now implements Traversable
  • pdo_mysql - Removed support for linking with MySQL client libraries older than 4.1
  • The MySQL extensions mysql, mysqli and PDO_mysql use mysqlnd as the default library now. It is still possible to use libmysqlclient by specifying a path to the configure options.
  • mysqlnd - Added named pipes support


New Global Constants

PHP Core:

  • ENT_DISALLOWED
  • ENT_HTML401
  • ENT_HTML5
  • ENT_SUBSTITUTE
  • ENT_XML1
  • ENT_XHTML
  • IPPROTO_IP
  • IPPROTO_IPV6
  • IPV6_MULTICAST_HOPS
  • IPV6_MULTICAST_IF
  • IPV6_MULTICAST_LOOP
  • IP_MULTICAST_IF
  • IP_MULTICAST_LOOP
  • IP_MULTICAST_TTL
  • MCAST_JOIN_GROUP
  • MCAST_LEAVE_GROUP
  • MCAST_BLOCK_SOURCE
  • MCAST_UNBLOCK_SOURCE
  • MCAST_JOIN_SOURCE_GROUP
  • MCAST_LEAVE_SOURCE_GROUP

Curl:

  • CURLOPT_MAX_RECV_SPEED_LARGE
  • CURLOPT_MAX_SEND_SPEED_LARGE

LibXML:

  • LIBXML_HTML_NODEFDTD
  • LIBXML_HTML_NOIMPLIED
  • LIBXML_PEDANTIC

OpenSSL:

  • OPENSSL_CIPHER_AES_128_CBC
  • OPENSSL_CIPHER_AES_192_CBC
  • OPENSSL_CIPHER_AES_256_CBC
  • OPENSSL_RAW_DATA
  • OPENSSL_ZERO_PADDING

Output buffering:

  • PHP_OUTPUT_HANDLER_CLEAN
  • PHP_OUTPUT_HANDLER_CLEANABLE
  • PHP_OUTPUT_HANDLER_DISABLED
  • PHP_OUTPUT_HANDLER_FINAL
  • PHP_OUTPUT_HANDLER_FLUSH
  • PHP_OUTPUT_HANDLER_FLUSHABLE
  • PHP_OUTPUT_HANDLER_REMOVABLE
  • PHP_OUTPUT_HANDLER_STARTED
  • PHP_OUTPUT_HANDLER_STDFLAGS
  • PHP_OUTPUT_HANDLER_WRITE

Sessions:

  • PHP_SESSION_ACTIVE
  • PHP_SESSION_DISABLED
  • PHP_SESSION_NONE

Streams:

  • STREAM_META_ACCESS
  • STREAM_META_GROUP
  • STREAM_META_GROUP_NAME
  • STREAM_META_OWNER
  • STREAM_META_OWNER_NAME
  • STREAM_META_TOUCH

Zlib:

  • ZLIB_ENCODING_DEFLATE
  • ZLIB_ENCODING_GZIP
  • ZLIB_ENCODING_RAW

Intl:

  • U_IDNA_DOMAIN_NAME_TOO_LONG_ERROR
  • IDNA_CHECK_BIDI
  • IDNA_CHECK_CONTEXTJ
  • IDNA_NONTRANSITIONAL_TO_ASCII
  • IDNA_NONTRANSITIONAL_TO_UNICODE
  • INTL_IDNA_VARIANT_2003
  • INTL_IDNA_VARIANT_UTS46
  • IDNA_ERROR_EMPTY_LABEL
  • IDNA_ERROR_LABEL_TOO_LONG
  • IDNA_ERROR_DOMAIN_NAME_TOO_LONG
  • IDNA_ERROR_LEADING_HYPHEN
  • IDNA_ERROR_TRAILING_HYPHEN
  • IDNA_ERROR_HYPHEN_3_4
  • IDNA_ERROR_LEADING_COMBINING_MARK
  • IDNA_ERROR_DISALLOWED
  • IDNA_ERROR_PUNYCODE
  • IDNA_ERROR_LABEL_HAS_DOT
  • IDNA_ERROR_INVALID_ACE_LABEL
  • IDNA_ERROR_BIDI
  • IDNA_ERROR_CONTEXTJ

Json:

  • JSON_PRETTY_PRINT
  • JSON_UNESCAPED_SLASHES
  • JSON_NUMERIC_CHECK
  • JSON_UNESCAPED_UNICODE
  • JSON_BIGINT_AS_STRING


Changes to INI file handling

The following php.ini directives have been removed:

  • register_globals and register_long_arrays
  • magic_quotes_gpc, magic_quotes_runtime, and magic_quotes_sybase
  • allow_call_time_pass_reference
  • define_syslog_variables
  • highlight.bg
  • session.bug_compat_42 and session.bug_compat_warn
  • mbstring.script_encoding
  • y2k_compliance
  • safe_mode, safe_mode_gid, safe_mode_include_dir, safe_mode_exec_dir, safe_mode_allowed_env_vars, and safe_mode_protected_env_vars

The following php.ini directives have been added:

  • cli.pager and cli.prompt for CLI SAPI using readline in interactive mode.
  • cli_server.color to enable the built-in development web server to use ANSI color coding in terminal output.
  • max_input_vars - specifies how many GET/POST/COOKIE input variables may be accepted.
  • zend.multibyte - to control the new multibyte support.
  • zend.script_encoding - This value will be used unless a "declare(encoding=...)" directive appears at the top of the script.
  • zend.signal_check - to check for replaced signal handlers on shutdown.
  • session.upload_progress.enabled, session.upload_progress.cleanup, session.upload_progress.prefix, session.upload_progress.name, session.upload_progress.freq, session.upload_progress.min_freq
  • enable_post_data_reading - When it's disabled, the POST data is not read (and processed)
  • windows_show_crt_warning - This directive shows the Windows CRT warnings when enabled. These warnings were displayed by default until now.

The following php.ini directives have been changed:

  • session.entropy_file now defaults to /dev/random or /dev/urandom depending on what has been guessed at compile time.
  • session.entropy_length now defaults to 32.


Other changes

  • The default character set for htmlspecialchars(), htmlentities() and html_entity_decode() is now UTF-8, instead of ISO-8859-1. Note that changing your output charset via the default_charset configuration setting does not affect htmlspecialchars/htmlentities unless you are passing "" (an empty string) as the encoding parameter to your htmlspecialchars()/htmlentities()/html_entity_decode() calls. Generally we do not recommend doing this because you should be able to change your output charset without affecting the runtime charset used by these functions. The safest approach is to explicitly set the charset on each call to htmlspecialchars(), htmlentities() and html_entity_decode().
  • E_ALL now includes E_STRICT level errors in the error_reporting configuration directive.
  • SNMP now has an OOP API. Functions now return FALSE on every error condition including SNMP-related (no such instance, end of MIB, etc). Thus, in particular, breaks previous behavior of get/walk functions returning an empty string on SNMP-related errors. Multi OID get/getnext/set queries are now supported. Dropped UCD-SNMP compatibility code, consider upgrading to net-snmp v5.3+, Net-SNMP v5.4+ is required for Windows version. In sake of adding support for IPv6 DNS name resolution of remote SNMP agent (peer) is done by extension now, not by Net-SNMP library anymore.
  • OpenSSL now supports AES.
  • CLI SAPI doesn't terminate any more on fatal errors when using interactive mode with readline support.
  • $_SERVER['REQUEST_TIME_FLOAT'] has been added to include microsecond precision.
  • Added new hash algorithms: fnv132, fnv164, joaat
  • Chained string offsets - e.g. $a[0][0] where $a is a string - now work.
  • Arrays cast from SimpleXMLElement now always contain all nodes instead of just the first matching node. All SimpleXMLElement children are now always printed when using var_dump(), var_export() and print_r().
  • It's now possible to enforce the class' __construct arguments in an abstract constructor in the base class.


Migrating from PHP 5.2.x to PHP 5.3.x

Table of Contents

  • What has changed in PHP 5.3.x
  • Backward Incompatible Changes
  • New features
  • Changes made to Windows support
  • Changes in SAPI modules
  • Deprecated features in PHP 5.3.x
  • Undeprecated features in PHP 5.3.x
  • New Parameters
  • New Functions
  • New stream wrappers
  • New stream filters
  • New Class Constants
  • New Methods
  • New Extensions
  • Removed Extensions
  • Other changes to extensions
  • New Classes
  • New Global Constants
  • Changes to INI file handling
  • Other changes

See also the migration guides for PHP versions 5.0.x, 5.1.x, 5.2.x, 5.4.x, 5.5.x and 5.6.x.


What has changed in PHP 5.3.x

Most improvements in PHP 5.3.x have no impact on existing code. There are a few incompatibilities and new features that should be considered, and code should be tested before switching PHP versions in production environments.

For systems being upgraded from an older version of PHP, the relevant documentation is available at:

  • Upgrade Notes for PHP 5.2.x.
  • Upgrade Notes for PHP 5.1.x.
  • Migrating from PHP 4 to PHP 5.


Backward Incompatible Changes

Although most existing PHP 5 code should work without changes, please take note of some backward incompatible changes:

  • The newer internal parameter parsing API has been applied across all the extensions bundled with PHP 5.3.x. This parameter parsing API causes functions to return NULL when passed incompatible parameters. There are some exceptions to this rule, such as the get_class() function, which will continue to return FALSE on error.
  • clearstatcache() no longer clears the realpath cache by default.
  • realpath() is now fully platform-independent. Consequence of this is that invalid relative paths such as __FILE__ . "/../x" do not work anymore.
  • The call_user_func() family of functions now propagate $this even if the callee is a parent class.
  • The array functions natsort(),
natcasesort(), usort(),
uasort(), uksort(),
array_flip(), and array_unique() no
longer accept objects passed as arguments. To apply these functions to an
object, cast the object to an array first.
  • The behaviour of functions with by-reference parameters called by value has changed. Where previously the function would accept the by-value argument, a fatal error is now emitted. Any previous code passing constants or literals to functions expecting references, will need altering to assign the value to a variable before calling the function.
  • The new mysqlnd library necessitates the use of MySQL 4.1's newer 41-byte password format. Continued use of the old 16-byte passwords will cause mysql_connect() and similar functions to emit the error, "mysqlnd cannot connect to MySQL 4.1+ using old authentication."
  • The new mysqlnd library does not read mysql configuration files (my.cnf/my.ini), as the older libmysqlclient library does. If your code relies on settings in the configuration file, you can load it explicitly with the mysqli_options() function. Note that this means the PDO specific constants PDO::MYSQL_ATTR_READ_DEFAULT_FILE and PDO::MYSQL_ATTR_READ_DEFAULT_GROUP are not defined if MySQL support in PDO is compiled with mysqlnd.
  • The trailing / has been removed from the SplFileInfo class and other related directory classes.
  • The __toString() magic method can no longer accept arguments.
  • The magic methods
__get(),
__set(),
__isset(),
__unset(), and
__call() must always
be public and can no longer be static. Method signatures are now enforced.
  • The __call() magic method is now invoked on access to private and protected methods.
  • func_get_arg(), func_get_args() and func_num_args() can no longer be called from the outermost scope of a file that has been included by calling include or require from within a function in the calling file.
  • An emulation layer for the MHASH extension to wrap around the Hash extension have been added. However not all the algorithms are covered, notable the s2k hashing algorithm. This means that s2k hashing is no longer available as of PHP 5.3.0.

The following keywords are now reserved and may not be used in function, class, etc. names.

  • goto
  • namespace


New features

PHP 5.3.0 offers a wide range of new features:

  • Support for namespaces has been added.
  • Support for Late Static Bindings has been added.
  • Support for jump labels (limited goto) has been added.
  • Support for native Closures (Lambda/Anonymous functions) has been added.
  • There are two new magic methods, __callStatic() and __invoke().
  • Nowdoc syntax is now supported, similar to Heredoc syntax, but with single quotes.
  • It is now possible to use Heredocs to initialize static variables and class properties/constants.
  • Heredocs may now be declared using double quotes, complementing the Nowdoc syntax.
  • Constants can now be declared outside a class using the const keyword.
  • The ternary operator now has a shorthand form: ?:.
  • The HTTP stream wrapper now considers all status codes from 200 to 399 to be successful.
  • Dynamic access to static methods is now possible:
    <?php
    class C {
       public static     $foo = 123;
    }

    $a = "C";
    echo     $a::$foo;
    ?>

    The above example will output:

    123
  • Exceptions can now be nested:
    <?php
    class MyCustomException extends Exception {}

    try {
        throw new     MyCustomException("Exceptional", 112);
    } catch (    Exception $e) {
            /* Note the use of the third parameter to pass $e
         * into the RuntimeException. */
            throw new RuntimeException("Rethrowing", 911, $e);
    }
    ?>
  • A garbage collector for circular references has been added, and is enabled by default.
  • The mail() function now supports logging of sent email via the mail.log configuration directive. (Note: This only applies to email sent through this function.)


Changes made to Windows support

Changes to the Windows releases:

  • The minimum Windows version is now Windows XP SP3; Windows 98, ME, 2000 and NT4 are no longer supported.
  • Windows binaries now target i586 and later. i386 and i486 are not supported.
  • There is now experimental support for x64 versions of PHP on Windows.
  • There is now compiler support for Visual C++ 9 (VC9), using Visual Studio 2008. Snapshots and releases will now also be available for VC9. Old binaries using VC6 are still supported and released in the line with VC9.
  • The PDO_OCI php_pdo_oci8.dll library (for use with Oracle version 8 client libraries) is no longer being built. Instead, use php_pdo_oci.dll (note no '8') with Oracle 10 or 11 client libraries. Connection to other database versions is still supported.
  • For the OCI8 extension, a new library php_oci8_11g.dll is available in addition to php_oci8.dll. Only one can be enabled at any time. Use php_oci8.dll with Oracle 10.2 client libraries. Use php_oci8_11g.dll with Oracle 11 or later client libraries. Connection to other database versions is still supported.

Windows support has been added for the following functions:

  • checkdnsrr()
  • dns_get_record()
  • fnmatch()
  • getmxrr()
  • getopt()
  • imagecolorclosesthwb()
  • inet_ntop()
  • inet_pton()
  • link()
  • linkinfo()
  • mcrypt_create_iv()
  • readlink()
  • socket_create_pair() - This function was previously available on Windows, but was disabled as of PHP 4.3.0 due to a bug.
  • stream_socket_pair()
  • symlink()
  • time_nanosleep()
  • time_sleep_until()

Other changes:

  • Improved portability of the stat(), touch(), filemtime(), filesize() functions, and other related functions (100% portable for the available data).
  • It is now possible to create hard links on Windows using the link() function, and symbolic links using the symlink() function. Hard links are available as of Windows 2000, and symbolic links as of Windows Vista.
  • The Windows version of PHP now exposes a set of constants prefixed PHP_WINDOWS_*. A list of these constants and their usage can be found at Predefined Constants.
Warning

Support for the ISAPI module has been dropped. Use the improved FastCGI SAPI module instead.

Note: A new dedicated site for PHP on Windows is now available, including downloads, release candidates, and snapshots in various flavors (thread-safe/not-thread-safe, VC6/VC9, x86/x64). The URL of this site is » https://windows.php.net/.


Changes in SAPI modules

  • A new SAPI module named litespeed is now available.
  • FastCGI support in the CGI SAPI is now always enabled and can not be disabled. See sapi/cgi/CHANGES for more details.
  • A new CGI SAPI option, -T, can be used to measure repeated execution time of a script.
  • CGI/FastCGI now has support for .htaccess-style user-defined php.ini files.
  • The dl() function is now disabled by default, and is now available only under the CLI, CGI, and embed SAPIs.


Deprecated features in PHP 5.3.x

PHP 5.3.0 introduces two new error levels: E_DEPRECATED and E_USER_DEPRECATED. The E_DEPRECATED error level is used to indicate that a function or feature has been deprecated. The E_USER_DEPRECATED level is intended for indicating deprecated features in user code, similarly to the E_USER_ERROR and E_USER_WARNING levels.

The following is a list of deprecated INI directives. Use of any of these INI directives will cause an E_DEPRECATED error to be thrown at startup.

  • define_syslog_variables
  • register_globals
  • register_long_arrays
  • safe_mode
  • magic_quotes_gpc
  • magic_quotes_runtime
  • magic_quotes_sybase
  • Comments starting with '#' are now deprecated in .INI files.

Deprecated functions:

  • call_user_method() (use call_user_func() instead)
  • call_user_method_array() (use call_user_func_array() instead)
  • define_syslog_variables()
  • dl()
  • ereg() (use preg_match() instead)
  • ereg_replace() (use preg_replace() instead)
  • eregi() (use preg_match() with the 'i' modifier instead)
  • eregi_replace() (use preg_replace() with the 'i' modifier instead)
  • mcrypt_generic_end()
  • set_magic_quotes_runtime() and its alias, magic_quotes_runtime()
  • session_register() (use the $_SESSION superglobal instead)
  • session_unregister() (use the $_SESSION superglobal instead)
  • session_is_registered() (use the $_SESSION superglobal instead)
  • set_socket_blocking() (use stream_set_blocking() instead)
  • split() (use preg_split() instead)
  • spliti() (use preg_split() with the 'i' modifier instead)
  • sql_regcase()
  • mysql_db_query() (use mysql_select_db() and mysql_query() instead)
  • mysql_escape_string() (use mysql_real_escape_string() instead)
  • Passing locale category names as strings is now deprecated. Use the LC_* family of constants instead.
  • The is_dst parameter to mktime(). Use the new timezone handling functions instead.

Deprecated features:

  • Assigning the return value of new by reference is now deprecated.
  • Call-time pass-by-reference is now deprecated.


  • « Deprecated features in PHP 5.3.x
  • New Parameters »
  • PHP Manual
  • Migrating from PHP 5.2.x to PHP 5.3.x
  • Undeprecated features in PHP 5.3.x

Undeprecated features in PHP 5.3.x

The is_a() function has been undeprecated by popular request; it will no longer issue an E_STRICT error.


New Parameters

Several functions were given new, optional parameters in PHP 5.3:

PHP Core:

  • clearstatcache() - Added clear_realpath_cache and filename.
  • copy() - Added a stream context parameter, context.
  • fgetcsv() - Added escape.
  • ini_get_all() - Added details.
  • nl2br() - Added is_xhtml.
  • parse_ini_file() - Added scanner_mode.
  • round() - Added mode.
  • stream_context_create() - Added params.
  • strstr() and stristr() - Added before_needle.

json:

  • json_encode() - Added options.
  • json_decode() - Added depth.

Streams:

  • stream_select(),
stream_set_blocking(),
stream_set_timeout(), and
stream_set_write_buffer() now work with user-space
stream wrappers.

sybase_ct:

  • sybase_connect() - Added new.

New method parameters in PHP 5.3.0:

PHP Core:

  • Exception::__construct() - Added previous.


New Functions

PHP 5.3 introduced some new functions:

PHP Core:

  • array_replace() - Replaces elements from passed arrays into one array.
  • array_replace_recursive() - Recursively replaces elements from passed arrays into one array.
  • class_alias() - Creates an alias for a user defined class.
  • forward_static_call() - Call a user function from a method context.
  • forward_static_call_array() - Call a user function from a method context, with the arguments contained in an array.
  • 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 the status of the circular reference collector.
  • get_called_class() - Return the name of the class a static method is called in.
  • gethostname() - Return the current host name for the local machine.
  • header_remove() - Removes an HTTP header previously set using the header() function.
  • lcfirst() - Make a string's first character lowercase.
  • parse_ini_string() - Parse a configuration string.
  • quoted_printable_encode() - Convert an 8 bit string to a quoted-printable string.
  • str_getcsv() - Parse a CSV string into an array.
  • stream_context_set_default() - Set the default stream context.
  • stream_supports_lock() - Return TRUE if the stream supports locking.
  • stream_context_get_params() - Retrieve parameters from a stream context.
  • streamWrapper::stream_cast() - Retrieve the underlying stream resource.
  • streamWrapper::stream_set_option() - Change stream options

Date/Time:

  • date_add() - Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object.
  • date_create_from_format() - Returns a new DateTime object formatted according to the given format.
  • date_diff() - Returns the difference between two DateTime objects.
  • date_get_last_errors() - Returns the warnings and errors from the last date/time operation.
  • date_parse_from_format() - Get information about a given date.
  • date_sub() - Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object.
  • timezone_version_get() - Returns the version of the timezonedb.

GMP:

  • gmp_testbit() - Tests whether a bit is set.

Hash:

  • hash_copy() - Copy hashing context.

IMAP:

  • imap_gc() - Clears IMAP cache.
  • imap_utf8_to_mutf7() - Encode a UTF-8 string to modified UTF-7.
  • imap_mutf7_to_utf8() - Decode a modified UTF-7 string to UTF-8.

JSON:

  • json_last_error() - Returns the last JSON error that occurred.

MySQL Improved:

  • mysqli_fetch_all() - Fetches all result rows as an associative array, a numeric array, or both.
  • mysqli_get_connection_stats() - Returns statistics about the client connection.
  • mysqli_poll() - Poll connections.
  • mysqli_reap_async_query() - Get result from async query.

OpenSSL:

  • openssl_random_pseudo_bytes() - Returns a string of the given length specified, filled with pseudo-random bytes.

PCNTL:

  • pcntl_signal_dispatch() - Calls signal handlers for pending signals.
  • pcntl_sigprocmask() - Sets and retrieves blocked signals.
  • pcntl_sigtimedwait() - Wait for signals with a timeout.
  • pcntl_sigwaitinfo() - Wait for signals.

PCRE:

  • preg_filter() - Perform a regular expression search and replace, returning only results which matched the pattern.

Semaphore:

  • msg_queue_exists() - Check whether a message queue exists.
  • shm_has_var() - Checks whether a specific key exists inside a shared memory segment.

The following functions are now natively implemented, making them available on all operating systems which can run PHP:

  • acosh()
  • asinh()
  • atanh()
  • expm1()
  • log1p()


  • « New Functions
  • New stream filters »
  • PHP Manual
  • Migrating from PHP 5.2.x to PHP 5.3.x
  • New stream wrappers

New stream wrappers

The following stream wrappers were introduced in 5.3.0:

  • glob://
  • phar://


New stream filters

The following stream filters were introduced in 5.3.0:

  • dechunk (reverses HTTP chunked encoding)
  • The bz2.decompress filter now supports concatenation.


New Class Constants

Several new class constants were introduced in 5.3.0:

PDO_FIREBIRD:

  • PDO::FB_ATTR_DATE_FORMAT - Sets the format for dates.
  • PDO::FB_ATTR_TIME_FORMAT - Sets the format for time.
  • PDO::FB_ATTR_TIMESTAMP_FORMAT - Sets the format for timestamps.


New Methods

Several new methods were introduced in 5.3.0:

Date/Time:

  • DateTime::add() - Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object.
  • DateTime::createFromFormat() - Returns a new DateTime object formatted according to the given format.
  • DateTime::diff() - Returns the difference between two DateTime objects.
  • DateTime::getLastErrors() - Returns the warnings and errors from the last date/time operation.
  • DateTime::sub() - Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object.

Exception:

  • Exception::getPrevious() - Retrieves the previous exception.

DOM:

  • DOMNode::getLineNo() - Get the line number of a parsed node.

PDO_FIREBIRD:

  • PDO::setAttribute() - Sets an attribute.

Reflection:

  • ReflectionClass::getNamespaceName() - Returns the name of namespace where this class is defined.
  • ReflectionClass::getShortName() - Returns the short name of this class (without namespace part).
  • ReflectionClass::inNamespace() - Returns whether this class is defined in a namespace.
  • ReflectionFunction::getNamespaceName() - Returns the name of namespace where this function is defined.
  • ReflectionFunction::getShortName() - Returns the short name of the function (without namespace part).
  • ReflectionFunction::inNamespace() - Returns whether this function is defined in a namespace.
  • ReflectionProperty::setAccessible() - Sets whether non-public properties can be requested.

SPL:

  • SplObjectStorage::addAll() - Add all elements from another SplObjectStorage object.
  • SplObjectStorage::removeAll() - Remove all elements from another SplObjectStorage object.

XSL:

  • XSLTProcessor::setProfiling() - Sets the profiling output file.


New Extensions

The following new extensions are added (by default) as of PHP 5.3.0:

  • Enchant - An abstraction layer above various spelling libraries
  • Fileinfo - An improved and more solid replacement, featuring full BC, for the Mimetype extension, which has been removed.
  • INTL - Internationalization extension. INTL is a wrapper around the » ICU library.
  • Phar - Implementation of PHP-Archive files.
  • SQLite3 - Support for SQLite version 3 databases.

mysqlnd is a new core library shipped with PHP. It is a PHP-specific replacement for libmysqlclient. mysqlnd will be used to build the mysql, mysqli and PDO_MySQL extensions if libmysqlclient isn't found on the system. It may also be used instead of libmysqlclient even when libmysqlclient is present. mysqlnd is recommended for all PHP installations for performance reasons.


Removed Extensions

These extensions have been moved to PECL and are no longer part of the PHP distribution. The PECL package versions of these extensions will be created according to user demand.

  • dbase - No longer maintained
  • fbsql - No longer maintained
  • fdf - Maintained
  • ming - Maintained
  • msql - No longer maintained
  • ncurses - Maintained
  • sybase - Discontinued; use the sybase_ct extension instead
  • mhash - Discontinued; use the hash extension instead. hash has full mhash compatibility; all existing applications using the old functions will continue to work.


Other changes to extensions

The following extensions can no longer be disabled during build configuration:

  • PCRE
  • Reflection
  • SPL

Changes in extension behaviour, and new features:

  • Date and Time - The TZ environment variable is no longer used to guess the timezone
  • cURL - cURL now supports SSH
  • Network - dns_check_record() now returns an extra "entries" index, containing the TXT elements.
  • Hash - The SHA-224 and salsa hash algorithms are now supported.
  • mbstring - Now supports CP850 encoding.
  • OCI8 - A call to oci_close() on a persistent connection, or a variable referencing a persistent connection going out of scope, will now roll back any uncommitted transaction. To avoid unexpected behavior, explicitly issue a commit or roll back as needed. The old behavior can be enabled with the INI directive oci8.old_oci_close_semantics. Database Resident Connection Pooling (DRCP) and Fast Application Notification (FAN) are now supported. Oracle External Authentication is now supported (except on Windows). The oci_bind_by_name() function now supports SQLT_AFC (aka the CHAR datatype).
  • OpenSSL - OpenSSL digest and cipher functions are now supported. It is also now possible to access the internal values of DSA, RSA and DH keys.
  • Session - Sessions will no longer store session-files in "/tmp" when open_basedir restrictions apply, unless "/tmp" is explicitly added to the list of allowed paths.
  • SOAP Now supports sending user supplied HTTP headers.
  • MySQLi Now supports persistent connections, by prepending the hostname with "p:".
  • Image Processing and GD The "JPG Support" index returned from gd_info() has been renamed to "JPEG Support".


New Classes

The following classes were introduced in PHP 5.3.0:

Date/Time:

  • DateInterval
  • DatePeriod

Phar:

  • Phar
  • PharData
  • PharException
  • PharFileInfo

SPL:

  • FilesystemIterator
  • GlobIterator
  • MultipleIterator
  • RecursiveTreeIterator
  • SplDoublyLinkedList
  • SplFixedArray
  • SplHeap
  • SplMaxHeap
  • SplMinHeap
  • SplPriorityQueue
  • SplQueue
  • SplStack


New Global Constants

PHP Core:

  • __DIR__
  • __NAMESPACE__
  • E_DEPRECATED
  • E_USER_DEPRECATED
  • INI_SCANNER_NORMAL
  • INI_SCANNER_RAW
  • PHP_MAXPATHLEN
  • PHP_WINDOWS_NT_DOMAIN_CONTROLLER
  • PHP_WINDOWS_NT_SERVER
  • PHP_WINDOWS_NT_WORKSTATION
  • PHP_WINDOWS_VERSION_BUILD
  • PHP_WINDOWS_VERSION_MAJOR
  • PHP_WINDOWS_VERSION_MINOR
  • PHP_WINDOWS_VERSION_PLATFORM
  • PHP_WINDOWS_VERSION_PRODUCTTYPE
  • PHP_WINDOWS_VERSION_SP_MAJOR
  • PHP_WINDOWS_VERSION_SP_MINOR
  • PHP_WINDOWS_VERSION_SUITEMASK

cURL:

  • CURLOPT_PROGRESSFUNCTION

GD:

  • IMG_FILTER_PIXELATE

JSON:

  • JSON_ERROR_CTRL_CHAR
  • JSON_ERROR_DEPTH
  • JSON_ERROR_NONE
  • JSON_ERROR_STATE_MISMATCH
  • JSON_ERROR_SYNTAX
  • JSON_FORCE_OBJECT
  • JSON_HEX_TAG
  • JSON_HEX_AMP
  • JSON_HEX_APOS
  • JSON_HEX_QUOT

LDAP:

  • LDAP_OPT_NETWORK_TIMEOUT

libxml:

  • LIBXML_LOADED_VERSION

PCRE:

  • PREG_BAD_UTF8_OFFSET_ERROR

PCNTL:

  • BUS_ADRALN
  • BUS_ADRERR
  • BUS_OBJERR
  • CLD_CONTIUNED
  • CLD_DUMPED
  • CLD_EXITED
  • CLD_KILLED
  • CLD_STOPPED
  • CLD_TRAPPED
  • FPE_FLTDIV
  • FPE_FLTINV
  • FPE_FLTOVF
  • FPE_FLTRES
  • FPE_FLTSUB
  • FPE_FLTUND
  • FPE_INTDIV
  • FPE_INTOVF
  • ILL_BADSTK
  • ILL_COPROC
  • ILL_ILLADR
  • ILL_ILLOPC
  • ILL_ILLOPN
  • ILL_ILLTRP
  • ILL_PRVOPC
  • ILL_PRVREG
  • POLL_ERR
  • POLL_HUP
  • POLL_IN
  • POLL_MSG
  • POLL_OUT
  • POLL_PRI
  • SEGV_ACCERR
  • SEGV_MAPERR
  • SI_ASYNCIO
  • SI_KERNEL
  • SI_MESGQ
  • SI_NOINFO
  • SI_QUEUE
  • SI_SIGIO
  • SI_TIMER
  • SI_TKILL
  • SI_USER
  • SIG_BLOCK
  • SIG_SETMASK
  • SIG_UNBLOCK
  • TRAP_BRKPT
  • TRAP_TRACE


Changes to INI file handling

PHP 5.3.0 has significantly improved performance and parsing of INI files, and adds several new syntax features.

  • The standard php.ini files have been re-organized and renamed. php.ini-development contains settings recommded for use in development environments. php.ini-production contains settings recommended for use in production environments.
  • There is now support for two special sections: [PATH=/opt/httpd/www.example.com/] and [HOST=www.example.com]. Directives set in these sections cannot be overridden by user-defined INI files or at runtime. More information about these sections can be found here.
  • zend_extension_debug, zend_extension_debug_ts and zend_extension_ts have been removed. Use the zend_extension directive to load all Zend Extensions.
  • zend.ze1_compatibility_mode has been removed. If this INI directive is set to On, an E_ERROR error is emitted at startup.
  • It is now possible to use the full path to load modules using the extension directive.
  • "ini-variables" can now be used almost anywhere in a php.ini file.
  • open_basedir restrictions may now be tighted at runtime, and the directive is now PHP_INI_ALL.
  • It is now possible to use alphanumeric or variable indices in INI option arrays.
  • get_cfg_var() is now able to return "array" INI options.
  • Two new mail directives: mail.add_x_header and mail.log, have been added.

The following new ini directives have been added:

  • user_ini.filename and user_ini.cache_ttl have been added to control the use of user INI files.
  • exit_on_timeout has been added to force Apache 1.x children to exit if a PHP execution timeout occurs.
  • Added mbstring.http_output_conv_mimetype. This directive specifies the regex pattern of content types for which mb_output_handler() is activated.
  • Added request_order. Allows controlling which external variables will be available in $_REQUEST.

The following ini directives have new default values:

  • session.use_only_cookies is now set to "1" (enabled) by default.
  • oci8.default_prefetch has changed from "10" to "100".


Other changes

  • SplFileInfo::getpathinfo() now returns information about the path name.
  • SplObjectStorage now has ArrayAccess support. It is now also possible to store associative information with objects in SplObjectStorage.
  • In the GD extension, there is now pixelation support available through the imagefilter() function.
  • var_dump() output now includes private object properties.
  • session_start() now returns FALSE when session startup fails.
  • property_exists() now checks the existence of a property independent of accessibility (like method_exists()).
  • Stream wrappers can now be used by include_path.
  • The initial parameter for array_reduce() can now be of any type.
  • The directory functions opendir(), scandir(), and dir() now use the default stream context if no explicit context is passed.
  • crypt() now has Blowfish and extended DES support, and crypt() features are now 100% portable. PHP has its own internal crypt implementation which drops into place when support for crypt or crypt_r is not found.
  • getopt() now accepts "long options" on all platforms. Optional values and = as a separator for short options are now supported.
  • fopen() has a new mode option (n), which passes O_NONBLOCK to the underlying open() system call. Note that this mode is not currently supported on Windows.
  • getimagesize() now supports icon files (.ico).
  • The mhash extension have moved to PECL, but the Hash extension have been modified to support mhash if PHP is compiled with --with-mhash. Note that the Hash extension does not require the mhash library to be available whether or not the mhash emulation is enabled.


Migrating from PHP 5.1.x to PHP 5.2.x

Table of Contents

  • What has changed in PHP 5.2.x
  • Backward Incompatible Changes
  • New Error Messages
  • Changes in PHP datetime support
  • New Parameters
  • New Functions
  • New Methods
  • Removed Extensions
  • New Extensions
  • New Classes
  • New Global Constants
  • New Class Constants
  • New INI Configuration Directives
  • Error Reporting
  • Other Enhancements

See also the migration guides for PHP versions 5.0.x, 5.1.x, 5.3.x, 5.4.x, 5.5.x and 5.6.x.


What has changed in PHP 5.2.x

Most improvements in PHP 5.2.x have no impact on existing code. There are a few incompatibilities and new error messages that should be considered, and code should be tested before switching PHP versions in production environments.

If the system is being upgraded from PHP 5.0.x, the manual section titled Upgrade Notes for PHP 5.1.x should also be read.

Similarly, if the system is being upgraded from PHP 4, the manual section titled Migrating from PHP 4 to PHP 5 should be read as well.


Backward Incompatible Changes

Although most existing PHP 5 code should work without changes, you should pay attention to the following backward incompatible changes:

  • getrusage() returns NULL when passed incompatible arguments as of PHP 5.2.1.
  • ZipArchive::setCommentName() returns TRUE on success as of PHP 5.2.1.
  • ZipArchive::setCommentIndex() returns TRUE on success as of PHP 5.2.1.
  • SplFileObject::getFilename() returns the filename, not relative/path/to/file, as of PHP 5.2.1.
  • Changed priority of PHPRC environment variable on Win32 The PHPRC environment variable now takes priority over the path stored in the Windows registry.
  • CLI SAPI no longer checks cwd for php.ini or the php-cli.ini file In PHP 5.1.x an undocumented feature was added that made the CLI binary check the current working directory for a PHP configuration file, potentially leading to unpredictable behavior if an unexpected configuration file were read. This functionality was removed in 5.2.0, and PHP will no longer search CWD for the presence of php.ini or php-cli.ini files. See also the command line section of the manual.
  • Added a warning when performing modulus 0 operations In earlier versions of PHP, performing integer % 0 did not emit any warning messages, instead returning an unexpected return value of FALSE. As of PHP 5.2.0, this operation will emit an E_WARNING, as is the case in all other instances where division by zero is performed.
    <?php
    print 10 % 0;
    /* Warning:  Division by zero in filename on line n */
    ?>
  • Changed __toString() to be called wherever applicable. The magic method __toString() will now be called in a string context, that is, anywhere an object is used as a string. The fallback of returning a string that contains the object identifier was dropped in PHP 5.2.0. It became problematic because an object identifier cannot be considered unique. This change will mean that your application is flawed if you have relied on the object identifier as a return value. An attempt to use that value as a string will now result in a catchable fatal error.
    <?php
    class foo {}
    $foo = new foo;
    print     $foo;
    /* Catchable fatal error:  Object of class foo could
       not be converted to string in filename on line n */
    ?>
    Even with __toString(), objects cannot be used as array indices or keys. We may add built-in hash support for this at a later date, but as of PHP 5.2.x you will need to either provide your own hashing or use the new SPL function spl_object_hash(). Exceptions can not be thrown from __toString() methods.
    <?php
    class foo {
        public function     __toString() {
            throw new     Exception;
        }
    }

    try {
        print new     foo;
            /* Fatal error:  Method foo::__toString() must
           not throw an exception in filename on line n */
    } catch(Exception $e) {}
    ?>
  • Dropped abstract static class functions. Due to an oversight, PHP 5.0.x and 5.1.x allowed abstract static functions in classes. As of PHP 5.2.x, only interfaces can have them.
    <?php
    abstract class foo {
        abstract static function     bar();
            /* Strict Standards:  Static function foo::bar()
           should not be abstract in filename on line n */
    }
    ?>
  • Oracle extension requires at least Oracle 10 on Windows.
  • Added RFC2397 (data: stream) support. The introduction of the 'data' URL scheme has the potential to lead to a change of behavior under Windows. If you are working with a NTFS file system and making use of meta streams in your application, and if you just happen to be using a file with the name 'data:' that is accessed without any path information - it won't work any more. The fix is to use the 'file:' protocol when accessing it. See also » RFC 2397
    <?php
    /* when allow_url_include is OFF (default) */
    include "data:;base64,PD9waHAgcGhwaW5mbygpOz8+";
    /* Warning:  include(): URL file-access is disabled
       in the server configuration in filename on line n */
    ?>
  • Regression in glob() patterns In version 5.2.4 a security fix caused a regression for patterns of the form "/foo/*/bar/*". Since version 5.2.5 instead of raising a warning the glob() function will return FALSE when openbase_dir restrictions are violated.


New Error Messages

Below are the new error messages that have not been discussed elsewhere in this document.

Example #1 In PHP Core

<?php
echo " ";
session_regenerate_id();
/*  Warning:  session_regenerate_id(): Cannot regenerate
    session id - headers already sent in filename on line n */

str_word_count("string", 4);
/* Warning:  str_word_count(): Invalid format value 4
   in filename on line n */

strripos("foo", "f", 4);
/* Notice:  strripos(): Offset is greater than the
   length of haystack string in filename on line n */

strrpos("foo", "f", 4);
/* Notice:  strrpos(): Offset is greater than the
   length of haystack string in filename on line n */

/* As of PHP 5.2.1, when allow_url_include is OFF (default) */
include "php://input";
/* Warning:  include(): URL file-access is disabled
   in the server configuration in filename on line n */
?>

Example #2 Object Oriented Code in PHP Core

<?php
interface foo {
}
class bar implements foo, foo {
}
/* Fatal error: Class bar cannot implement previously
   implemented interface foo in filename on line n */

class foo {
    public $bar;
    function __get($var)
    {
        return $this->bar;
    }
}

$foo = new foo;
$bar =& $foo->prop;
/* Notice: Indirect modification of overloaded property
   foo::$prop has no effect in filename on line n */

class foo implements iterator {
    public function current() {
    }
    public function next() {
    }
    public function key() {
    }
    public function valid() {
    }
    public function rewind() {
    }
}

$foo = new foo();
foreach($foo as &$ref) {}
/* Fatal error: An iterator cannot be used with foreach
   by reference in filename on line n */

class foo {
    private function __construct() {
    }
}
class bar extends foo {
    public function __construct() {
        parent::__construct();
        /* Fatal error:  Cannot call private
           foo::__construct() in filename on line n */
    }
}
new bar;

stream_filter_register("", "class");
/* Warning:  stream_filter_register(): Filter name
   cannot be empty in filename on line n */

stream_filter_register("filter", "");
/* Warning:  stream_filter_register(): Class name
   cannot be empty in filename on line n */
?>

Example #3 In the bzip2 Extension

<?php
bzopen("", "w");
/* Warning:  bzopen(): filename cannot be empty
   in filename on line n */

bzopen("foo", "a");
/* Warning:  bzopen(): 'a' is not a valid mode for
   bzopen(). Only 'w' and 'r' are supported in
   filename on line n */

$fp = fopen("foo", "w");
bzopen($fp, "r");
/* Warning:  bzopen(): cannot read from a stream
   opened in write only mode in filename on line n */
?>

Example #4 In the datetime Extension

<?php
strtotime("today", "now");
/* Warning:  strtotime() expects parameter 2 to be
   long, string given in filename on line n */

/* As of PHP 5.2.1 */
new DateTime(new stdclass);
/* Fatal error: Uncaught exception 'Exception' with
   message 'DateTime::__construct() expects parameter
   1 to be string, object given' in filename:n */
?>

Example #5 In the dBase Extension

<?php
dbase_open("foo", -1);
/* Warning: Invalid access mode -1 in filename on line n */

/* As of PHP 5.2.1 */
dbase_open("foo", null);
/* Warning: The filename cannot be empty in filename on line n */
?>

Example #6 In the mcrypt Extension

<?php
$key = "this is a secret key";
$td = mcrypt_module_open('tripledes', '', 'ecb', '');
$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td),
                        MCRYPT_RAND);
mcrypt_generic_init($td, $key, $iv);
$encrypted_data = mcrypt_generic($td, "");
/* Warning: mcrypt_generic(): An empty string was
   passed in filename on line n */
?>

Example #7 In the oci8 Extension

<?php
oci_connect("user", "pass", "db", "bogus_charset");
/* Warning: Invalid character set name:
   bogus_charset in filename on line n */

$oci = oci_connect("user", "pass", "db");
oci_password_change($oci, "", "old", "new");
/* Warning: username cannot be empty in filename
   on line n */

oci_password_change($oci, "user", "", "new");
/* Warning: old password cannot be empty in filename
   on line n */

oci_password_change($oci, "user", "old", "");
/* Warning: new password cannot be empty in filename
   on line n */
?>

Example #8 In the SPL Extension

<?php
$obj = new SplFileObject(__FILE__);
$obj->fgetcsv("foo");
/* Warning:  SplFileObject::fgetcsv(): delimiter must
   be a character in filename on line n */

$obj->fgetcsv(",", "foo");
/* Warning:  SplFileObject::fgetcsv(): enclosure must
   be a character in filename on line n */
?>

Example #9 In the Semaphore (sysvmsg) extension

<?php
/* Warning:  maximum size of the message has to be
   greater then zero in filename on line n */
?>

Example #10 A 5.2.1+ Zip Example

<?php
$obj = new ZipArchive();
$obj->open('archive.zip');
$obj->setCommentName('', 'comment');
/* Notice:  ZipArchive::setCommentName(): Empty string
   as entry name in filename on line n */

/* As of PHP 5.2.1 */
$obj->getCommentName('');
/* Notice:  ZipArchive::getCommentName(): Empty string
   as entry name in filename on line n */
?>


Changes in PHP datetime support

Since PHP 5.1.0, there has been an extension named date in the PHP core. This is the new implementation of PHP's datetime support. Although it will attempt to guess your system's timezone setting, you should set the timezone manually. You can do this in any of three ways:

  • in your php.ini using the date.timezone INI directive
  • on your system using the TZ environmental variable
  • from your script using the convenience function date_default_timezone_set()

All supported timezones are listed in the PHP Manual.

With the advent of PHP 5.2.x, there are object representations of the date and timezone, named DateTime and DateTimeZone respectively. The methods map to existing procedural date functions.


New Parameters

Some functions were given new, optional, parameters in PHP 5.2.x:

PHP Core:

  • htmlentities() - added double_encode in PHP 5.2.3.
  • htmlspecialchars() - added double_encode in PHP 5.2.3.
  • base64_decode() - added strict
  • setcookie() - added httponly
  • setrawcookie() - added httponly
  • session_set_cookie_params() - added httponly
  • memory_get_usage() - added real_usage
  • get_loaded_extensions() - added zend_extensions in PHP 5.2.4

curl:

  • curl_multi_info_read() - added msgs_in_queue

datetime

  • date() - added "u" (milliseconds) format character in PHP 5.2.2

imap:

  • imap_open() - added n_retries
  • imap_reopen() - added n_retries

mbstring:

  • mb_strrpos() - added offset
    Warning

    The offset parameter was put in the position the encoding parameter used to be. Backward compatibility has been provided by allowing encoding to be specified as the third parameter. Using this backward compatibility mode is not recommended because it will be removed in a future release of PHP.

ming:

  • SWFMovie::streamMP3() - added skip in PHP 5.2.1

openssl:

  • openssl_verify() - added signature_algo

pgsql:

  • pg_escape_bytea() - added connection
  • pg_escape_string() - added connection

simplexml:

  • SimpleXMLElement::__construct() - added is_prefix
  • SimpleXMLElement::attributes() - added is_prefix
  • SimpleXMLElement::children() - added is_prefix
  • simplexml_load_file() - added is_prefix
  • simplexml_load_string() - added is_prefix

spl:

  • array iterator_to_array(Traversable it [, bool use_keys = true]) - added use_keys in PHP 5.2.1

xmlreader:

  • XMLReader::open() - added encoding and options
  • XMLReader::XML() - added encoding and options

XMLWriter:

  • xmlwriter_write_element() - the content became optional in PHP 5.2.3
  • xmlwriter_write_element_ns() - the content became optional in PHP 5.2.3


New Functions

PHP 5.2.x introduced some new functions:

PHP Core:

  • array_fill_keys() - Create an array using the elements of the first parameter as keys, each initialized to val
  • error_get_last() - Get the last occurred error as associative array. Returns NULL if there hasn't been an error yet
  • image_type_to_extension() - Get file extension for image-type returned by getimagesize(), exif_read_data(), exif_thumbnail(), exif_imagetype()
  • memory_get_peak_usage() - Returns the peak allocated by PHP memory
  • sys_get_temp_dir() - Returns directory path used for temporary files. (Added in 5.2.1)
  • timezone_abbreviations_list() - Returns associative array containing DST, offset and the timezone name
  • timezone_identifiers_list() - Returns numerically indexed array with all timezone identifiers
  • timezone_name_from_abbr() - Returns the timezone name from abbreviation
  • stream_socket_shutdown() - Causes all or part of a full-duplex connection on the socket associated with stream to be shut down. As of PHP 5.2.1.

Image:

  • imagegrabscreen() - Grabs a screenshot of the whole screen. As of PHP 5.2.2.
  • imagegrabwindow() - Captures a window. As of PHP 5.2.2.

libXML:

  • libxml_disable_entity_loader() - Disable the ability to load external entities. As of PHP 5.2.11.

mbstring:

  • 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_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_strstr() - Finds first occurrence of a string within another

ming (As of PHP 5.2.1):

  • void ming_setSWFCompression(int num) - Sets output compression
  • void swfmovie::namedanchor(string name) - Creates anchor
  • void swfmovie::protect([string password]) - Protects

openssl:

  • openssl_csr_get_public_key() - Extracts public key from a CERT and prepares it for use
  • openssl_csr_get_subject() - Returns the subject of a CERT
  • openssl_pkey_get_details() - Returns an array with the key details (bits, pkey, type)

spl:

  • spl_object_hash() - Return hash id for given object
  • int iterator_apply(Traversable it, mixed function [, mixed params]) - Calls a function for every element in an iterator

pcre:

  • preg_last_error() - Returns the error code of the last regex execution

pgsql:

  • pg_field_table() - Returns the name of the table field belongs to, or table's oid if oid_only is TRUE

posix:

  • posix_initgroups() - Calculate the group access list for the user specified in name

gmp:

  • gmp_nextprime() - Finds next prime number

xmlwriter:

  • xmlwriter_full_end_element() - End current element - returns FALSE on error
  • xmlwriter_write_raw() - Write text - returns FALSE on error
  • xmlwriter_start_dtd_entity() - Create start DTD Entity - returns FALSE on error
  • xmlwriter_end_dtd_entity() - End current DTD Entity - returns FALSE on error
  • xmlwriter_write_dtd_entity() - Write full DTD Entity tag - returns FALSE on error


New Methods

New methods were introduced in 5.2.0:

dom:

  • DOMDocument::registerNodeClass() - Register extended class used to create base node type
  • DOMElement::setIDAttribute() - Declares the attribute specified by name to be of type ID
  • DOMElement::setIDAttributeNode() - Declares the attribute specified by node to be of type ID
  • DOMElement::setIDAttributeNS() - Declares the attribute specified by local name and namespace URI to be of type ID
  • DOMNode::C14N()([bool exclusive [, bool with_comments [, array xpath [, array ns_prefixes]]]]) - Canonicalize nodes to a string
  • DOMNode::C14NFile()(string uri [, bool exclusive [, bool with_comments [, array xpath [, array ns_prefixes]]]]) - Canonicalize nodes to a file
  • DOMNode::getNodePath()() - Gets an xpath for a node

soap:

  • SoapServer::setObject()(object obj) - Sets object which will handle SOAP requests

spl:

  • int ArrayObject::asort()(void) - Sort the entries by values
  • int ArrayObject::ksort()(void) - Sort the entries by key
  • int ArrayObject::natcasesort()(void) - Sort the entries by key using case insensitive "natural order" algorithm.
  • int ArrayObject::natsort()(void) - Sort the entries by values using "natural order" algorithm.
  • int ArrayObject::uasort()(callback cmp_function) - Sort the entries by values using a user defined function
  • int ArrayObject::uksort()(callback cmp_function) - Sort the entries by key using a user defined function.
  • ArrayIterator AppendIterator::getArrayIterator()() - Get access to inner ArrayIterator
  • int AppendIterator::getIteratorIndex()() - Get index of iterator
  • bool CachingIterator::getCache()() - Return the cache
  • int CachingIterator::getFlags()() - Return the internal flags
  • bool CachingIterator::offsetExists()(mixed index) - Returns TRUE if the requested index exists
  • string CachingIterator::offsetGet()(mixed index) - Return the internal cache if used
  • void CachingIterator::offsetSet()(mixed index, mixed newval) - Set given index in cache
  • void CachingIterator::offsetUnset()(mixed index) - Unset given index in cache
  • void CachingIterator::setFlags()() - Set the internal flags
  • array("delimiter" =>, "enclosure" =>) SplFileObject::getCsvControl()(void) - Get the delimiter and enclosure character used in fgetcsv()
  • void SplFileObject::setCsvControl()([string delimiter = ',' [, string enclosure = '"']]) - Set the delimiter and enclosure character used in fgetcsv()

Tidy

  • tidyNode tidyNode::getParent()() - Returns the parent node of the current node (Added in PHP 5.2.2)

XMLReader

  • boolean XMLReader::setSchema() - Use W3C XSD schema to validate the document as it is processed. Activation is only possible before the first XMLReader::read()

zip:

  • ZipArchive::addEmptyDir()() - Creates an empty directory in the archive


Removed Extensions

These extensions have been moved to PECL and are no longer part of the PHP distribution. The PECL package version of these extensions will be created according to user demand.

  • filePro
  • Hyperwave API


New Extensions

The following are new extensions added (by default) as of PHP 5.2.0:

  • Filter - validates and filters data, and is designed for use with insecure data such as user input. This extension is enabled by default; the default mode RAW does not impact input data in any way.
  • JSON - implements the JavaScript Object Notation (JSON) data interchange format. This extension is enabled by default.
  • Zip - enables you to transparently read or write ZIP compressed archives and the files inside them.


New Classes

The following classes were introduced in PHP 5.2.0:

  • DateTime
  • DateTimeZone
  • RegexIterator - extends FilterIterator; implements Iterator, Traversable, OuterIterator Constants:
    • RegexIterator::ALL_MATCHES
    • RegexIterator::GET_MATCH
    • RegexIterator::MATCH
    • RegexIterator::REPLACE
    • RegexIterator::SPLIT
    • RegexIterator::USE_KEY
    Properties:
    • public replacement
    Methods:
    • RegexIterator::__construct(Iterator it, string regex [, int mode [, int flags [, int preg_flags]]]) - Create an RegexIterator from another iterator and a regular expression
    • bool RegexIterator::accept() - Match (string)current() against regular expression
    • bool RegexIterator::getFlags() - Returns current operation flags
    • bool RegexIterator::getMode() - Returns current operation mode
    • bool RegexIterator::getPregFlags() - Returns current PREG flags (if in use or NULL)
    • bool RegexIterator::setFlags(int new_flags) - Set operation flags
    • bool RegexIterator::setMode(int new_mode) - Set new operation mode
    • bool RegexIterator::setPregFlags(int new_flags) - Set PREG flags
  • RecursiveRegexIterator Constants:
    • RecursiveRegexIterator::ALL_MATCHES
    • RecursiveRegexIterator::GET_MATCH
    • RecursiveRegexIterator::MATCH
    • RecursiveRegexIterator::REPLACE
    • RecursiveRegexIterator::SPLIT
    • RecursiveRegexIterator::USE_KEY
    Methods:
    • RecursiveRegexIterator::__construct(RecursiveIterator it, string regex [, int mode [, int flags [, int preg_flags]]]) - Create an RecursiveRegexIterator from another recursive iterator and a regular expression
    • RecursiveRegexIterator RecursiveRegexIterator::getChildren() - Return the inner iterator's children contained in a RecursiveRegexIterator
    • bool RecursiveRegexIterator::hasChildren() - Check whether the inner iterator's current element has children


New Global Constants

PHP Core:

  • M_EULER
  • M_LNPI
  • M_SQRT3
  • M_SQRTPI
  • PATHINFO_FILENAME
  • PREG_BACKTRACK_LIMIT_ERROR
  • PREG_BAD_UTF8_ERROR
  • PREG_INTERNAL_ERROR
  • PREG_NO_ERROR
  • PREG_RECURSION_LIMIT_ERROR
  • UPLOAD_ERR_EXTENSION
  • STREAM_SHUT_RD
  • STREAM_SHUT_WR
  • STREAM_SHUT_RDWR

curl:

  • CURLE_FILESIZE_EXCEEDED
  • CURLE_FTP_SSL_FAILED
  • CURLE_LDAP_INVALID_URL
  • CURLFTPAUTH_DEFAULT
  • CURLFTPAUTH_SSL
  • CURLFTPAUTH_TLS
  • CURLFTPSSL_ALL
  • CURLFTPSSL_CONTROL
  • CURLFTPSSL_NONE
  • CURLFTPSSL_TRY
  • CURLOPT_FTP_SSL
  • CURLOPT_FTPSSLAUTH
  • CURLOPT_TCP_NODELAY Added in PHP 5.2.1.
  • CURLOPT_TIMEOUT_MS Added in PHP 5.2.3
  • CURLOPT_CONNECTTIMEOUT_MS Added in PHP 5.2.3

GMP:

  • GMP_VERSION Added in PHP 5.2.2.

ming:

  • SWFTEXTFIELD_USEFONT
  • SWFTEXTFIELD_AUTOSIZE
  • SWF_SOUND_NOT_COMPRESSED
  • SWF_SOUND_ADPCM_COMPRESSED
  • SWF_SOUND_MP3_COMPRESSED
  • SWF_SOUND_NOT_COMPRESSED_LE
  • SWF_SOUND_NELLY_COMPRESSED
  • SWF_SOUND_5KHZ
  • SWF_SOUND_11KHZ
  • SWF_SOUND_22KHZ
  • SWF_SOUND_44KHZ
  • SWF_SOUND_8BITS
  • SWF_SOUND_16BITS
  • SWF_SOUND_MONO
  • SWF_SOUND_STEREO

openssl:

  • OPENSSL_VERSION_NUMBER
  • OPENSSL_VERSION_TEXT

snmp:

  • SNMP_OID_OUTPUT_FULL
  • SNMP_OID_OUTPUT_NUMERIC

Semaphore:

  • MSG_EAGAIN
  • MSG_ENOMSG


New Class Constants

pdo:

  • PDO::ATTR_DEFAULT_FETCH_MODE
  • PDO::FETCH_PROPS_LATE
  • PDO::FETCH_KEY_PAIR Fetches a 2 column result set into an associated array. (Added in PHP 5.2.3)

spl:

  • CachingIterator::FULL_CACHE
  • CachingIterator::TOSTRING_USE_INNER
  • SplFileObject::READ_AHEAD
  • SplFileObject::READ_CSV
  • SplFileObject::SKIP_EMPTY


New INI Configuration Directives

New php.ini directives introduced in PHP 5.2.0:

  • allow_url_include This useful option makes it possible to differentiate between standard file operations on remote files, and the inclusion of remote files. While the former is usually desirable, the latter can be a security risk if used naively. Starting with PHP 5.2.0, you can allow remote file operations while disallowing the inclusion of remote files in local scripts. In fact, this is the default configuration.
  • pcre.backtrack_limit PCRE's backtracking limit.
  • pcre.recursion_limit PCRE's recursion limit. Please note that if you set this value to a high number you may consume all the available process stack and eventually crash PHP (due to reaching the stack size limit imposed by the Operating System).
  • session.cookie_httponly Marks the cookie as accessible only through the HTTP protocol. This means that the cookie won't be accessible by scripting languages, such as JavaScript. This setting can effectively help to reduce identity theft through XSS attacks (although it is not supported by all browsers).

New directives in PHP 5.2.2:

  • max_input_nesting_level Limits how deep input variables can be nested, default is 64.


Error Reporting

Some of the existing E_ERROR conditions have been converted to something that can be caught with a user-defined error handler. If an E_RECOVERABLE_ERROR is not handled, it will behave in the same way as E_ERROR behaves in all versions of PHP. Errors of this type are logged as Catchable fatal error.

This change means that the value of the E_ALL error_reporting constant is now 6143, where the previous value was 2047. Because PHP constants have no meaning outside of PHP, in some cases the integer value is used instead so these will need to be adjusted. So for example by setting the error_reporting mode from either the httpd.conf or the .htaccess files, the value has to be changed accordingly. The same applies when the numeric values are used rather than the constants in PHP scripts.

As a side-effect of a change made to prevent duplicate error messages when track_errors is On, it is now necessary to return FALSE from user defined error handlers in order to populate $php_errormsg. This provides a fine-grain control over the levels of messages stored.


Other Enhancements

  • Improved memory manager and increased default memory limit. The new memory manager allocates less memory and works faster than the previous incarnation. It allocates memory from the system in large blocks, and then manages the heap by itself. The memory_limit value in php.ini is checked, not for each emalloc() call (as before), but for actual blocks requested from the system. This means that memory_limit is far more accurate than it used to be, since the old memory manager didn't calculate all the memory overhead used by the malloc library. Thanks to this new-found accuracy memory usage may appear to have increased, although actually it has not. To accommodate this apparent increase, the default memory_limit setting was also increased - from 8 to 16 megabytes.
  • Added support for constructors in interfaces to force constructor signature checks in implementations. Starting with PHP 5.2.0, interfaces can have constructors. However, if you choose to declare a constructor in an interface, each class implementing that interface MUST include a constructor with a signature matching that of the base interface constructor. By 'signature' we mean the parameter and return type definitions, including any type hints and including whether the data is passed by reference or by value.


Migrating from PHP 5.0.x to PHP 5.1.x

Table of Contents

  • Key PHP 5.1.x features
  • Changes in reference handling
  • Reading []
  • Integer values in function parameters
  • Class and object changes
  • Extensions
  • Date/time support
  • Changes in database support
  • Checking for E_STRICT

See also the migration guides for PHP versions 5.0.x, 5.2.x, 5.3.x, 5.4.x, 5.5.x and 5.6.x.


Key PHP 5.1.x features

Some of the key features of PHP 5.1.x include:

  • A complete rewrite of date handling code, with improved timezone support.

  • Significant performance improvements compared to PHP 5.0.X.

  • PDO extension is now enabled by default.

  • Over 30 new functions in various extensions and built-in functionality.

  • Over 400 various bug fixes.


Changes in reference handling

  • Overview

  • Code that worked under PHP 4.3.x, but now fails

  • Code that worked under PHP 4.3.x, but now throws an error

  • Code that failed under PHP 4.3.x, but now works

  • Code that should have worked under PHP 5.0.x

  • Warnings that came and went

Overview

From the PHP script writer's point of view, the change most likely to impact legacy code is in the way that references are handled in all PHP versions post-dating the PHP 4.4.0 release.

Until and including PHP 4.3, it was possible to send, assign or return variables by reference that should really be returned by value, such as a constant, a temporary value (e.g. the result of an expression), or the result of a function that had itself been returned by value, as here:

<?php
$foo = "123";

function return_value() {
    global $foo;
    return $foo;
}

$bar = &return_value();
?>

Although this code would usually work as expected under PHP 4.3, in the general case the result is undefined. The Zend Engine could not act correctly on these values as references. This bug could and did lead to various hard-to-reproduce memory corruption problems, particularly where the code base was large.

In PHP 4.4.0, PHP 5.0.4 and all subsequent PHP releases, the Engine was fixed to 'know' when the reference operation is being used on a value that should not be referenced. The actual value is now used in such cases, and a warning is emitted. The warning takes the form of an E_NOTICE in PHP 4.4.0 and up, and E_STRICT in PHP 5.0.4 and up.

Code that could potentially produce memory corruption can no longer do so. However, some legacy code might work differently as a result.

Code that worked under PHP 4.3, but now fails

<?php
function func(&$arraykey) {
    return $arraykey; // function returns by value!
}

$array = array('a', 'b', 'c');
foreach (array_keys($array) as $key) {
    $y = &func($array[$key]);
    $z[] =& $y;
}

var_dump($z);
?>
<

Running the above script under any version of PHP that pre-dates the reference fix would produce this output:

array(3) {
  [0]=>
  &string(1) "a"
  [1]=>
  &string(1) "b"
  [2]=>
  &string(1) "c"
}

Following the reference fix, the same code would result in:

array(3) {
  [0]=>
  &string(1) "c"
  [1]=>
  &string(1) "c"
  [2]=>
  &string(1) "c"
}

This is because, following the changes, func() assigns by value. The value of $y is re-assigned, and reference-binding is preserved from $z. Prior to the fix, the value was assigned by reference, leading $y to be re-bound on each assignment. The attempt to bind to a temporary value by reference was the cause of the memory corruption.

Such code can be made to work identically in both the pre-fix and the post-fix PHP versions. The signature of func() can be altered to return by reference, or the reference assignment can be removed from the result of func().

<?php
function func() {
    return 'function return';
}

$x = 'original value';
$y =& $x;
$y = &func();
echo $x;
?>

In PHP 4.3 $x would be 'original value', whereas after the changes it would be 'function return' - remember that where the function does not return by reference, the reference assignment is converted to a regular assignment. Again, this can be brought to a common base, either by forcing func() to return by reference or by eliminating the by-reference assignment.

Code that worked under PHP 4.3.x, but now throws an error

<?php
class Foo {

    function getThis() {
        return $this;
    }

    function destroyThis() {
        $baz =& $this->getThis();
    }
}

$bar = new Foo();
$bar->destroyThis();
var_dump($bar);
?>

In PHP 5.0.3, $bar evaluated to NULL instead of returning an object. That happened because getThis() returns by value, but the value here is assigned by reference. Although it now works in the expected way, this is actually invalid code which will throw an E_NOTICE under PHP 4.4 or an E_STRICT under PHP 5.0.4 and up.

Code that failed under PHP 4.3.x, but now works

<?php
function &f() {
    $x = "foo";
    var_dump($x);
    print "$x\n";
    return($a);
}

for ($i = 0; $i < 3; $i++) {
    $h = &f();
}
?>

In PHP 4.3 the third call to var_dump() produces NULL, due to the memory corruption caused by returning an uninitialized value by reference. This is valid code in PHP 5.0.4 and up, but threw errors in earlier releases of PHP.

<?php
$arr = array('a1' => array('alfa' => 'ok'));
$arr =& $arr['a1'];
echo '-'.$arr['alfa']."-\n";
?>

Until PHP 5.0.5, it wasn't possible to assign an array element by reference in this way. It now is.

Code that should have worked under PHP 5.0.x

There are a couple of instances of bugs reported under PHP 5.0 prior to the reference fixes which now 'work'. However, in both cases errors are thrown by PHP 5.1.x, because the code was invalid in the first place. Returning values by reference using self:: now works in the general case but throws an E_STRICT warning, and although your mileage may vary when assigning by reference to an overloaded object, you will still see an E_ERROR when you try it, even where the assignment itself appears to work.

Warnings that came and went

Nested calls to functions returning by reference are valid code under both PHP 4.3.x and PHP 5.1.x, but threw an unwarranted E_NOTICE or E_STRICT under the intervening PHP releases.

<?php
function & foo() {
    $var = 'ok';
    return $var;
}

function & bar() {
    return foo();
}

$a =& bar();
echo "$a\n";
?>


Reading []

<?php
class XmlTest {

    function test_ref(&$test) {
        $test = "ok";
    }

    function test($test) { }

    function run() {
        $ar = array();
        $this->test_ref($ar[]);
        var_dump($ar);
        $this->test($ar[]);
    }
}

$o = new XmlTest();
$o->run();
?>

This should always have thrown a fatal E_ERROR, because [] cannot be used for reading in PHP. It is invalid code in PHP 4.4.2 and PHP 5.0.5 upward.


Integer values in function parameters

With the advent of PHP 5.0.x, a new parameter parsing API was introduced which is used by a large number of PHP functions. In all versions of PHP between 5.0.x and 5.1.x, the handling of integer values was very strict and would reject non-well formed numeric values when a PHP function expected an integer. These checks have now been relaxed to support non-well formed numeric strings such as " 123" and "123 ", and will no longer fail as they did under PHP 5.0.x. However, to promote code safety and input validation, PHP functions will now emit an E_NOTICE when such strings are passed as integers.


Class and object changes

  • instanceof, is_a(), is_subclass_of() and catch

  • Abstract private methods

  • Access modifiers in interfaces

  • Changes in inheritance rules

  • Class constants

instanceof, is_a(), is_subclass_of() and catch

In PHP 5.0, is_a() was deprecated and replaced by the instanceof operator. There were some issues with the initial implementation of instanceof, which relied on __autoload() to search for missing classes. If the class was not present, instanceof would throw a fatal E_ERROR due to the failure of __autoload() to discover that class. The same behaviour occurred in the catch operator and the is_subclass_of() function, for the same reason.

None of these functions or operators call __autoload() in PHP 5.1.x, and the class_exists() workarounds used in code written for PHP 5.0.x, while not problematic in any way, are no longer necessary.

Abstract private methods

Abstract private methods were supported between PHP 5.0.0 and PHP 5.0.4, but were then disallowed on the grounds that the behaviours of private and abstract are mutually exclusive.

Access modifiers in interfaces

Under PHP 5.0, function declarations in interfaces were treated in exactly the same way as function declarations in classes. This has not been the case since October 2004, at which point only the public access modifier was allowed in interface function declarations. Since April 2005 - which pre-dates the PHP 5.0b1 release - the static modifier has also been allowed. However, the protected and private modifiers will now throw an E_ERROR, as will abstract. Note that this change should not affect your existing code, as none of these modifiers makes sense in the context of interfaces anyway.

Changes in inheritance rules

Under PHP 5.0, it was possible to have a function declaration in a derived class that did not match the declaration of the same function in the base class, e.g.

This code will cause an E_STRICT error to be emitted under PHP 5.1.x.

<?php
class Base {
    function &return_by_ref() {
        $r = 1;
        return $r;
    }
}

class Derived extends Base {
    function return_by_ref() {
        return 1;
    }
}
?>

Class constants

Under PHP 5.0.x, the following code was valid:

Under PHP 5.1.x, redefinition of a class constant will throw a fatal E_ERROR.

<?php
class test {
    const foobar = 'foo';
    const foobar = 'bar';
}

?>


Extensions

  • Extensions that are gone from the PHP core

  • Class constants in new PHP 5.1.x extensions

Extensions that are gone from the PHP core

One of the first things you're likely to notice when you download PHP 5.1.x is that several of the older extensions have disappeared. Those extensions that are still actively maintained are available in the PHP Extension Community Library (PECL), at » https://pecl.php.net/.

Removed extensions
Extension | Alternative/Status
ext/cpdf | pecl/pdflib
ext/dbx | pecl/dbx
ext/dio | pecl/dio
ext/fam | Not actively maintained
ext/ingres_ii | pecl/ingres
ext/ircg | Not actively maintained
ext/mcve | pecl/mcve
ext/mnogosearch | Not actively maintained
ext/oracle | ext/oci8 or ext/pdo_oci
ext/ovrimos | Not actively maintained
ext/pfpro | Not actively maintained
ext/w32api | » pecl/ffi
ext/yp | Not actively maintained
ext/activescript | » pecl/activescript

Modules in PECL that are not actively maintained (i.e. have not been supported for some time, have no active maintainer working on them currently, and do not have any PECL package releases), are still available in SVN at » https://svn.php.net/viewvc/pecl. However, unreleased PHP modules are by their nature unsupported, and your mileage may vary when attempting to install or use them.

Class constants in new PHP 5.1.x extensions

The Zend Engine 2.1 API allows extension developers to declare class constants in object oriented extensions. New extensions written for PHP 5.1.x, including SPL, PDO, XMLReader and date, have their constants in the format PDO::CLASS_CONSTANT rather than in the C format PDO_CLASS_CONSTANT in order to minimise pollution of the global namespace in PHP.


Date/time support

Date/time support has been fully rewritten in PHP 5.1.x, and no longer uses the system settings to 'know' the timezone in operation. It will instead utilize, in the following order:

  • The timezone set using the date_default_timezone_set() function (if any)

  • The TZ environment variable (if non empty)

  • "magical" guess (if the operating system supports it)

  • If none of the above options succeeds, UTC

To ensure accuracy (and avoid an E_STRICT warning), you will need to define your timezone in your php.ini using the following format:

date.timezone = Europe/London

The supported timezones are listed, in this format, in the timezones appendix.

Also note that strtotime() now returns FALSE on failure, instead of -1.


Changes in database support

  • PDO overview

  • Changes in MySQL support

  • Changes in SQLite support

PDO overview

PHP Data Objects (PDO) were introduced as a PECL extension under PHP 5.0, and became part of the core PHP distribution in PHP 5.1.x. The PDO extension provides a consistent interface for database access, and is used alongside database-specific PDO drivers. Each driver may also have database-specific functions of its own, but basic data access functionality such as issuing queries and fetching data is covered by PDO functions, using the driver named in PDO::__construct().

Note that the PDO extension, and its drivers, are intended to be built as shared extensions. This will enable straightforward driver upgrades from PECL, without forcing you to rebuild all of PHP.

At the point of the PHP 5.1.x release, PDO is more than ready for widespread testing and could be adopted in most situations. However, it is important to understand that PDO and its drivers are comparatively young and may be missing certain database-specific features; evaluate PDO carefully before you use it in new projects.

Legacy code will generally rely on the pre-existing database extensions, which are still maintained.

Changes in MySQL support

In PHP 4, MySQL 3 support was built-in. With the release of PHP 5.0 there were two MySQL extensions, named 'mysql' and 'mysqli', which were designed to support MySQL < 4.1 and MySQL 4.1 and up, respectively. With the introduction of PDO, which provides a very fast interface to all the database APIs supported by PHP, the PDO_MYSQL driver can support any of the current versions (MySQL 3, 4 or 5) in PHP code written for PDO, depending on the MySQL library version used during compilation. The older MySQL extensions remain in place for reasons of back compatibility, but are not enabled by default.

Changes in SQLite support

In PHP 5.0.x, SQLite 2 support was provided by the built-in sqlite extension, which was also available as a PECL extension in PHP 4.3 and PHP 4.4. With the introduction of PDO, the sqlite extension doubles up to act as a 'sqlite2' driver for PDO; it is due to this that the sqlite extension in PHP 5.1.x has a dependency upon the PDO extension.

PHP 5.1.x ships with a number of alternative interfaces to sqlite:

The sqlite extension provides the "classic" sqlite procedural/OO API that you may have used in prior versions of PHP. It also provides the PDO 'sqlite2' driver, which allows you to access legacy SQLite 2 databases using the PDO API.

PDO_SQLITE provides the 'sqlite' version 3 driver. SQLite version 3 is vastly superior to SQLite version 2, but the file formats of the two versions are not compatible.

If your SQLite-based project is already written and working against earlier PHP versions, then you can continue to use ext/sqlite without problems, but will need to explicitly enable both PDO and sqlite. New projects should use PDO and the 'sqlite' (version 3) driver, as this is faster than SQLite 2, has improved locking concurrency, and supports both prepared statements and binary columns natively.

You must enable PDO to use the SQLite extension. If you want to build the PDO extension as a shared extension, then the SQLite extension must also be built shared. The same holds true for any extension that provides a PDO driver


Checking for E_STRICT

If you only have a single script to check, you can pick up E_STRICT errors using PHP's commandline lint facility:

php -d error_reporting=4095 -l script_to_check.php

For larger projects, the shell script below will achieve the same task:

#!/bin/sh

directory=$1

shift

# These extensions are checked
extensions="php inc"

check_file ()
{
  echo -ne "Doing PHP syntax check on $1 ..."

  # Options:
  ERRORS=`/www/php/bin/php -d display_errors=1 -d html_errors=0 -d error_prepend_string=" " -d error_append_string=" " -d error_reporting=4095 -l $1 | grep -v "No syntax errors detected"`

  if test -z "$ERRORS"; then
    echo -ne "OK."
  else
    echo -e "Errors found!\n$ERRORS"
  fi

  echo
}

# loop over remaining file args
for FILE in "$@" ; do
  for ext in $extensions; do
     if echo $FILE | grep "\.$ext$" > /dev/null; then
       if test -f $FILE; then
         check_file "$FILE"
       fi
     fi
  done
done


Migrating from PHP 4 to PHP 5.0.x

Table of Contents

  • What has changed in PHP 5.0.x
  • Backward Incompatible Changes
  • CLI and CGI
  • Migrating Configuration Files
  • New Functions
  • New Directives
  • Databases
  • New Object Model
  • Error Reporting

See also the migration guides for PHP versions 5.1.x, 5.2.x, 5.3.x, 5.4.x, 5.5.x and 5.6.x.


What has changed in PHP 5.0.x

PHP 5 and the integrated Zend Engine 2 have greatly improved PHP's performance and capabilities, but great care has been taken to break as little existing code as possible. So migrating your code from PHP 4 to 5 should be very easy. Most existing PHP 4 code should be ready to run without changes, but you should still know about the few differences and take care to test your code before switching versions in production environments.


Backward Incompatible Changes

Although most existing PHP 4 code should work without changes, you should pay attention to the following backward incompatible changes:

  • There are some new reserved keywords.
  • strrpos() and strripos() now use the entire string as a needle.
  • Illegal use of string offsets causes E_ERROR instead of E_WARNING. An example illegal use is: $str = 'abc'; unset($str[0]);.
  • array_merge() was changed to accept only arrays. If a non-array variable is passed, a E_WARNING will be thrown for every such parameter. Be careful because your code may start emitting E_WARNING out of the blue.
  • PATH_TRANSLATED server variable is no longer set implicitly under Apache2 SAPI in contrast to the situation in PHP 4, where it is set to the same value as the SCRIPT_FILENAME server variable when it is not populated by Apache. This change was made to comply with the » CGI/1.1 specification. Please refer to » bug #23610 for further information, and see also the $_SERVER['PATH_TRANSLATED'] description in the manual. This issue also affects PHP versions >= 4.3.2.
  • The T_ML_COMMENT constant is no longer defined by the Tokenizer extension. If error_reporting is set to E_ALL, PHP will generate a notice. Although the T_ML_COMMENT was never used at all, it was defined in PHP 4. In both PHP 4 and PHP 5 // and /* */ are resolved as the T_COMMENT constant. However the PHPDoc style comments /** */, which starting PHP 5 are parsed by PHP, are recognized as T_DOC_COMMENT.
  • $_SERVER should be populated with argc and argv if variables_order includes "S". If you have specifically configured your system to not create $_SERVER, then of course it shouldn't be there. The change was to always make argc and argv available in the CLI version regardless of the variables_order setting. As in, the CLI version will now always populate the global $argc and $argv variables.
  • An object with no properties is no longer considered "empty".
  • In some cases classes must be declared before use. It only happens if some of the new features of PHP 5 (such as interfaces) are used. Otherwise the behaviour is the old.
  • get_class(), get_parent_class() and get_class_methods() now return the name of the classes/methods as they were declared (case-sensitive) which may lead to problems in older scripts that rely on the previous behaviour (the class/method name was always returned lowercased). A possible solution is to search for those functions in all your scripts and use strtolower(). This case sensitivity change also applies to the magical predefined constants __CLASS__, __METHOD__, and __FUNCTION__. The values are returned exactly as they're declared (case-sensitive).
  • ip2long() now returns FALSE when an invalid IP address is passed as argument to the function, and no longer -1.
  • If there are functions defined in the included file, they can be used in the main file independent if they are before return or after. If the file is included twice, PHP 5 issues fatal error because functions were already declared, while PHP 4 doesn't complain about it. It is recommended to use include_once instead of checking if the file was already included and conditionally return inside the included file.
  • include_once and require_once first normalize the path of included file on Windows so that including A.php and a.php include the file just once.
  • Passing an array to a function by value no longer resets the array's internal pointer for array accesses made within the function. In other words, in PHP 4 when you passed an array to a function, its internal pointer inside the function would be reset, while in PHP 5, when you pass an array to a function, its array pointer within the function will be wherever it was when the array was passed to the function.

Example #1 strrpos() and strripos() now use the entire string as a needle

<?php
var_dump(strrpos('ABCDEF','DEF')); //int(3)

var_dump(strrpos('ABCDEF','DAF')); //bool(false)
?>

Example #2 An object with no properties is no longer considered "empty"

<?php
class test { }
$t = new test();

var_dump(empty($t)); // echo bool(false)

if ($t) {
    // Will be executed
}
?>

Example #3 In some cases classes must be declared before used

<?php

//works with no errors:
$a = new a();
class a {
}

//throws an error:
$a = new b();

interface c{
}
class b implements c {
}

?>


CLI and CGI

In PHP 5 there were some changes in CLI and CGI filenames. In PHP 5, the CGI version was renamed to php-cgi.exe (previously php.exe) and the CLI version now sits in the main directory (previously cli/php.exe).

In PHP 5 it was also introduced a new mode: php-win.exe. This is equal to the CLI version, except that php-win doesn't output anything and thus provides no console (no "dos box" appears on the screen). This behavior is similar to php-gtk.

In PHP 5, the CLI version will always populate the global $argv and $argc variables regardless of any php.ini directive setting. Even having register_argc_argv set to off will have no affect in CLI.

See also the command line reference.


Migrating Configuration Files

Since the ISAPI modules changed their names, from php4xxx to php5xxx, you need to make some changes in the configuration files. There were also changes in the CLI and CGI filenames. Please refer to the corresponding section for more information.

Migrating the Apache configuration is extremely easy. See the example below to check the change you need to do:

Example #1 Migrating Apache configuration files for PHP 5

# change this line:
LoadModule php4_module /php/sapi/php4apache2.dll

# with this one:
LoadModule php5_module /php/php5apache2.dll

If your web server is running PHP in CGI mode, you should note that the CGI version has changed its name from php.exe to php-cgi.exe. In Apache, you should do something like this:

Example #2 Migrating Apache configuration files for PHP 5, CGI mode

# change this line:
Action application/x-httpd-php "/php/php.exe"

# with this one:
Action application/x-httpd-php "/php/php-cgi.exe"

In other web servers you need to change either the CGI or the ISAPI module filenames.


New Functions

In PHP 5 there are some new functions. Here is the list of them:

Arrays:

  • array_combine() - Creates an array by using one array for keys and another for its values
  • array_diff_uassoc() - Computes the difference of arrays with additional index check which is performed by a user supplied callback function
  • array_udiff() - Computes the difference of arrays by using a callback function for data comparison
  • array_udiff_assoc() - Computes the difference of arrays with additional index check. The data is compared by using a callback function
  • array_udiff_uassoc() - Computes the difference of arrays with additional index check. The data is compared by using a callback function. The index check is done by a callback function also
  • array_walk_recursive() - Apply a user function recursively to every member of an array
  • array_uintersect_assoc() - Computes the intersection of arrays with additional index check. The data is compared by using a callback function
  • array_uintersect_uassoc() - Computes the intersection of arrays with additional index check. Both the data and the indexes are compared by using separate callback functions
  • array_uintersect() - Computes the intersection of arrays. The data is compared by using a callback function

InterBase:

  • 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_commit_ret() - Commit a transaction without closing it
  • ibase_db_info() - Request statistics about a database
  • ibase_drop_db() - Drops a database
  • ibase_errcode() - Return an error code
  • ibase_free_event_handler() - Cancels a registered event handler
  • ibase_gen_id() - Increments the named generator and returns its new value
  • ibase_maintain_db() - Execute a maintenance command on the database server
  • ibase_name_result() - Assigns a name to 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_restore() - Initiates a restore task in the service manager and returns immediately
  • ibase_rollback_ret() - Rollback transaction and retain the transaction context
  • ibase_server_info() - Request statistics 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_wait_event() - Wait for an event to be posted by the database

iconv:

  • 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_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

Streams:

  • stream_copy_to_stream() - Copies data from one stream to another
  • stream_get_line() - Gets line from stream resource up to a given delimiter
  • stream_socket_accept() - Accept a connection on a socket created by stream_socket_server()
  • stream_socket_client() - Open Internet or Unix domain socket connection
  • stream_socket_get_name() - Retrieve the name of the local or remote sockets
  • stream_socket_recvfrom() - Receives data from a socket, connected or not
  • stream_socket_sendto() - Sends a message to a socket, whether it is connected or not
  • stream_socket_server() - Create an Internet or Unix domain server socket

Date and time related:

  • idate() - Format a local time/date as integer
  • date_sunset() - Time of sunset for a given day and location
  • date_sunrise() - Time of sunrise for a given day and location
  • time_nanosleep() - Delay for a number of seconds and nanoseconds

Strings:

  • str_split() - Convert a string to an array
  • strpbrk() - Search a string for any of a set of characters
  • substr_compare() - Binary safe optionally case insensitive comparison of two strings from an offset, up to length characters

Other:

  • convert_uudecode() - decode a uuencoded string
  • convert_uuencode() - uuencode a string
  • curl_copy_handle() - Copy a cURL handle along with all of its preferences
  • dba_key_split() - Splits a key in string representation into array representation
  • dbase_get_header_info() - Get the header info of a dBase database
  • dbx_fetch_row() - Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set
  • fbsql_set_password() - Change the password for a given user
  • file_put_contents() - Write a string to a file
  • ftp_alloc() - Allocates space for a file to be uploaded
  • get_declared_interfaces() - Returns an array of all declared interfaces
  • get_headers() - Fetches all the headers sent by the server in response to a HTTP request
  • headers_list() - Returns a list of response headers sent (or ready to send)
  • http_build_query() - Generate URL-encoded query string
  • image_type_to_extension() - Get file extension for
image-type returned by getimagesize(),
exif_read_data(),
exif_thumbnail(),
exif_imagetype()
  • imagefilter() - Applies a filter to an image using custom arguments
  • imap_getacl() - Gets the ACL for a given mailbox
  • ldap_sasl_bind() - Bind to LDAP directory using SASL
  • mb_list_encodings() - Returns an array of all supported encodings
  • pcntl_getpriority() - Get the priority of any process
  • pcntl_wait() - Waits on or returns the status of a forked child as defined by the waitpid() system call
  • pg_version() - Returns an array with client, protocol and server version (when available)
  • php_check_syntax() - Check the syntax of the specified file
  • php_strip_whitespace() - Return source with stripped comments and whitespace
  • proc_nice() - Change the priority of the current process
  • pspell_config_data_dir() - Change location of language data files
  • pspell_config_dict_dir() - Change location of the main word list
  • setrawcookie() - Send a cookie without URL-encoding the value
  • scandir() - List files and directories inside the specified path
  • snmp_read_mib() - Reads and parses a MIB file into the active MIB tree
  • sqlite_fetch_column_types() - Return an array of column types from a particular table

Note:

The Tidy extension has also changed its API completely.


New Directives

There were some new php.ini directives introduced in PHP 5. Here is a list of them:

  • mail.force_extra_parameters - 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(), even in safe mode
  • register_long_arrays - allow/disallow PHP to register the deprecated long $HTTP_*_VARS
  • session.hash_function - select a hash function (MD5 or SHA-1)
  • session.hash_bits_per_character - define how many bits are stored in each character when converting the binary hash data to something readable (from 4 to 6)
  • zend.ze1_compatibility_mode - Enable compatibility mode with Zend Engine 1 (PHP 4)


Databases

There were some changes in PHP 5 regarding databases (MySQL and SQLite).

In PHP 5 the MySQL client libraries are not bundled, because of license and maintenance problems. MySQL is supported with the only change being that MySQL support is no longer enabled by default in PHP 5. This essentially means that PHP doesn't include the --with-mysql option in the configure line so that you must now manually do this when compiling PHP. Windows users will need to edit php.ini and enable the php_mysql.dll DLL as in PHP 4 no such DLL existed, it was simply built into your Windows PHP binaries.

There is also a new extension, MySQLi (Improved MySQL), which is designed to work with MySQL 4.1 and above.

Since PHP 5, the SQLite extension is built-in PHP. SQLite is an embeddable SQL database engine and is not a client library used to connect to a big database server (like MySQL or PostgreSQL). The SQLite library reads and writes directly to and from the database files on disk.


New Object Model

In PHP 5 there is a new Object Model. PHP's handling of objects has been completely rewritten, allowing for better performance and more features. In previous versions of PHP, objects were handled like primitive types (for instance integers and strings). The drawback of this method was that semantically the whole object was copied when a variable was assigned, or passed as a parameter to a method. In the new approach, objects are referenced by handle, and not by value (one can think of a handle as an object's identifier).

Many PHP programmers aren't even aware of the copying quirks of the old object model and, therefore, the majority of PHP applications will work out of the box, or with very few modifications.

The new Object Model is documented at the Language Reference.

In PHP 5, function with the name of a class is called as a constructor only if defined in the same class. In PHP 4, it is called also if defined in the parent class.

See also the zend.ze1_compatibility_mode directive for compatibility with PHP 4.


Error Reporting

As of PHP 5 the error reporting constant E_STRICT is available, with the value 2048. When enabled, messages will be issued to warn you about code usage which is deprecated or which may not be future-proof.

Note: E_ALL does not include E_STRICT, so it's not enabled by default. You must explicitly set the error reporting level to include E_STRICT in order to see these messages.

See Predefined Constants for more information.


  • « Error Reporting
  • About debugging in PHP »
  • PHP Manual
  • Appendices
  • Debugging in PHP

Debugging in PHP

Table of Contents

  • About debugging in PHP


About debugging in PHP

PHP 5.6 is shipped with the phpdbg interactive debugger. PHP versions below 5.6 do not have an internal debugging facility though. You can use one of the external debuggers though. The » Zend IDE includes a debugger, and there are also some free debugger extensions like DBG at » http://www.php-debugger.com/dbg/, the » Advanced PHP Debugger (APD) or » Xdebug.


  • « About debugging in PHP
  • List of core configure options »
  • PHP Manual
  • Appendices
  • Configure options

Configure options

Table of Contents

  • List of core configure options


List of core configure options

Below is a partial list of configure options used by the PHP configure scripts when compiling in Unix-like environments. Most configure options are listed in their appropriate locations on the extension reference pages and not here. For a complete up-to-date list of configure options, run ./configure --help in your PHP source directory after running autoconf (see also the Installation chapter). You may also be interested in reading the » GNU configure documentation for information on additional configure options such as --prefix=PREFIX.

Note:

These are only used at compile time. If you want to alter PHP's runtime configuration, please see the chapter on Runtime Configuration.

  • Miscellaneous
  • PHP Behaviour
  • Server

Configure Options in PHP

Misc options

--enable-debug

Compile with debugging symbols.

--with-layout=TYPE

Sets how installed files will be laid out. Type is one of PHP (default) or GNU.

--with-pear=DIR

Install PEAR in DIR (default PREFIX/lib/php).

--without-pear

Do not install PEAR.

--enable-sigchild

Enable PHP's own SIGCHLD handler.

--disable-rpath

Disable passing additional runtime library search paths.

--enable-libgcc

Enable explicitly linking against libgcc.

--enable-php-streams

Include experimental PHP streams. Do not use unless you are testing the code!

--with-zlib-dir[=DIR]

Define the location of zlib install directory.

--with-tsrm-pthreads

Use POSIX threads (default).

--enable-shared[=PKGS]

Build shared libraries [default=yes].

--enable-static[=PKGS]

Build static libraries [default=yes].

--enable-fast-install[=PKGS]

Optimize for fast installation [default=yes].

--with-gnu-ld

Assume the C compiler uses GNU ld [default=no].

--disable-libtool-lock

Avoid locking (might break parallel builds).

--with-pic

Try to use only PIC/non-PIC objects [default=use both].

--enable-memory-limit

Compile with memory limit support. (not available since PHP 5.2.1 - always enabled)

--disable-url-fopen-wrapper

Disable the URL-aware fopen wrapper that allows accessing files via HTTP or FTP. (not available since PHP 5.2.5)

--enable-versioning

Export only required symbols. See INSTALL for more information.

PHP options

--enable-maintainer-mode

Enable make rules and dependencies not useful (and sometimes confusing) to the casual installer.

--with-config-file-path=PATH

Sets the path in which to look for php.ini, defaults to PREFIX/lib.

--enable-safe-mode

Enable safe mode by default.

Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

--with-exec-dir[=DIR]

Only allow executables in DIR when in safe mode defaults to /usr/local/php/bin.

Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

--enable-magic-quotes

Enable magic quotes by default.

Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

--disable-short-tags

Disable the short-form <? start tag by default.

--enable-zend-multibyte

Enables multibyte code in the language parser and scanner to be executed. When PHP is compiled with this option, it also enables the encoding directive in the declare construct.

Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

--with-libdir

Specifies the directory where the libraries to build PHP exist on a Unix system. For 64bit systems, its needed to specify this argument to the lib64 directory like: --with-libdir=lib64.

SAPI options

The following list contains the available SAPI&s (Server Application Programming Interface) for PHP.

--with-aolserver=DIR

Specify path to the installed AOLserver.

--with-apxs[=FILE]

Build shared Apache module. FILE is the optional pathname to the Apache apxs tool; defaults to apxs. Make sure you specify the version of apxs that is actually installed on your system and NOT the one that is in the apache source tarball.

--with-apache[=DIR]

Build a static Apache module. DIR is the top-level Apache build directory, defaults to /usr/local/apache.

--with-mod_charset

Enable transfer tables for mod_charset (Russian Apache).

--with-apxs2[=FILE]

Build shared Apache 2.0 module. FILE is the optional pathname to the Apache apxs tool; defaults to apxs.

--with-caudium=DIR

Build PHP as a Pike module for use with Caudium. DIR is the Caudium server dir, with the default value /usr/local/caudium/server.

--disable-cli

Disable building the CLI version of PHP (this forces --without-pear). More information is available in the section about Using PHP from the command line.

--enable-phpdbg

Enable phpdbg interactive debugger SAPI module support in PHP 5.6.x or later.

--enable-embed[=TYPE]

Enable building of the embedded SAPI library. TYPE is either shared or static, which defaults to shared.

--with-isapi=DIR

Build PHP as an ISAPI module for use with Zeus.

--with-nsapi=DIR

Specify path to the installed Netscape/iPlanet/SunONE Webserver.

--with-phttpd=DIR

No information yet.

--with-pi3web=DIR

Build PHP as a module for use with Pi3Web.

--with-roxen=DIR

Build PHP as a Pike module. DIR is the base Roxen directory, normally /usr/local/roxen/server.

--enable-roxen-zts

Build the Roxen module using Zend Thread Safety.

--with-servlet[=DIR]

Include servlet support. DIR is the base install directory for the JSDK. This SAPI requires the java extension must be built as a shared dl.

--with-thttpd=SRCDIR

Build PHP as thttpd module.

--with-tux=MODULEDIR

Build PHP as a TUX module (Linux only).

--with-webjames=SRCDIR

Build PHP as a WebJames module (RISC OS only)

--disable-cgi

Disable building CGI version of PHP.

As of PHP 5.3.0 this argument enables FastCGI which previously had to be enabled using --enable-fastcgi.

--enable-force-cgi-redirect

Enable the security check for internal server redirects. You should use this if you are running the CGI version with Apache.

As of PHP 5.3.0 this argument is enabled by default and no longer exists. To disable this, the cgi.force_redirect ini directive should be set to 0.

--enable-discard-path

If this is enabled, the PHP CGI binary can safely be placed outside of the web tree and people will not be able to circumvent .htaccess security.

As of PHP 5.3.0 this argument is disabled by default and no longer exists. To enable this feature the cgi.discard_path ini directive must be set to 1.

--enable-fastcgi

If this is enabled, the CGI module will be built with support for FastCGI also.

As of PHP 5.3.0 this argument no longer exists and is enabled by --enable-cgi instead.

--disable-path-info-check

If this is disabled, paths such as /info.php/test?a=b will fail to work. For more information see the » Apache Manual.

As of PHP 5.3.0 this argument is enabled by default and no longer exists. To disable this feature the cgi.fix_pathinfo ini directive must be set to 0.


php.ini directives

Table of Contents

  • List of php.ini directives
  • List of php.ini sections
  • Description of core php.ini directives


List of php.ini directives

This list includes the php.ini directives you can set to configure your PHP setup.

The "Changeable" column shows the modes determining when and where a directive may be set. See the Changeable mode values section for their definitions.

Configuration options
Name | Default | Changeable | Changelog
allow_call_time_pass_reference | "1" | PHP_INI_PERDIR | Removed in PHP 5.4.0.
allow_url_fopen | "1" | PHP_INI_SYSTEM |
allow_url_include | "0" | PHP_INI_SYSTEM | Available since PHP 5.2.0. Deprecated as of PHP 7.4.0.
always_populate_raw_post_data | "0" | PHP_INI_PERDIR |
apc.cache_by_default | "1" | PHP_INI_ALL | PHP_INI_SYSTEM in APC <= 3.0.12. Available since APC 3.0.0.
apc.enabled | "1" | PHP_INI_SYSTEM | PHP_INI_SYSTEM in APC 2. PHP_INI_ALL in APC <= 3.0.12.
apc.enable_cli | "0" | PHP_INI_SYSTEM | Available since APC 3.0.7.
apc.file_update_protection | "2" | PHP_INI_SYSTEM | Available since APC 3.0.6.
apc.filters | NULL | PHP_INI_SYSTEM |
apc.gc_ttl | "3600" | PHP_INI_SYSTEM |
apc.include_once_override | "0" | PHP_INI_SYSTEM | Available since APC 3.0.12.
apc.localcache | "0" | PHP_INI_SYSTEM | Available since APC 3.0.14.
apc.localcache.size | "512" | PHP_INI_SYSTEM | Available since APC 3.0.14.
apc.max_file_size | "1M" | PHP_INI_SYSTEM | Available since APC 3.0.7.
apc.mmap_file_mask | NULL | PHP_INI_SYSTEM |
apc.num_files_hint | "1000" | PHP_INI_SYSTEM |
apc.optimization | "0" | PHP_INI_ALL | PHP_INI_SYSTEM in APC 2. Removed in APC 3.0.13.
apc.report_autofilter | "0" | PHP_INI_SYSTEM | Available since APC 3.0.11.
apc.rfc1867 | "0" | PHP_INI_SYSTEM | Available since APC 3.0.13.
apc.rfc1867_freq | "0" | PHP_INI_SYSTEM |
apc.rfc1867_name | "APC_UPLOAD_PROGRESS" | PHP_INI_SYSTEM |
apc.rfc1867_prefix | "upload_" | PHP_INI_SYSTEM |
apc.shm_segments | "1" | PHP_INI_SYSTEM |
apc.shm_size | "30" | PHP_INI_SYSTEM |
apc.slam_defense | "0" | PHP_INI_SYSTEM | Available since APC 3.0.0.
apc.stat | "1" | PHP_INI_SYSTEM | Available since APC 3.0.10.
apc.stat_ctime | "0" | PHP_INI_SYSTEM | Available since APC 3.0.13.
apc.ttl | "0" | PHP_INI_SYSTEM | Available since APC 3.0.0.
apc.user_entries_hint | "4096" | PHP_INI_SYSTEM | Available since APC 3.0.0.
apc.user_ttl | "0" | PHP_INI_SYSTEM | Available since APC 3.0.0.
apc.write_lock | "1" | PHP_INI_SYSTEM | Available since APC 3.0.11.
apd.bitmask | "0" | PHP_INI_ALL | Removed in apd 0.9.
apd.dumpdir | NULL | PHP_INI_ALL |
apd.statement_tracing | "0" | PHP_INI_ALL | Available since apd 0.9.
arg_separator.input | "&" | PHP_INI_PERDIR |
arg_separator.output | "&" | PHP_INI_ALL |
asp_tags | "0" | PHP_INI_PERDIR | Removed in PHP 7.0.0.
assert.active | "1" | PHP_INI_ALL |
assert.bail | "0" | PHP_INI_ALL |
assert.callback | NULL | PHP_INI_ALL |
assert.exception | "0" | PHP_INI_ALL | Available since PHP 7.0.0.
assert.quiet_eval | "0" | PHP_INI_ALL |
assert.warning | "1" | PHP_INI_ALL |
auto_append_file | NULL | PHP_INI_PERDIR |
auto_detect_line_endings | "0" | PHP_INI_ALL |
auto_globals_jit | "1" | PHP_INI_PERDIR |
auto_prepend_file | NULL | PHP_INI_PERDIR |
axis2.client_home | "~/work/axisc/c/deply" | PHP_INI_ALL |
axis2.enable_exception | "1" | PHP_INI_ALL |
axis2.enable_trace | "1" | PHP_INI_ALL |
axis2.log_path | "/tmp" | PHP_INI_ALL |
bcmath.scale | "0" | PHP_INI_ALL |
bcompiler.enabled | "1" | PHP_INI_ALL | Available since bcompiler 0.8.
blenc.key_file | "/usr/local/etc/blenckeys" | PHP_INI_ALL |
browscap | NULL | PHP_INI_SYSTEM |
cgi.check_shebang_line | "1" | PHP_INI_SYSTEM | Available since PHP 5.2.1.
cgi.discard_path | "0" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
cgi.fix_pathinfo | "1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 5.2.0.
cgi.force_redirect | "1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 5.2.0.
cgi.nph | "0" | PHP_INI_ALL |
cgi.redirect_status_env | NULL | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 5.2.0.
cgi.rfc2616_headers | "0" | PHP_INI_ALL |
child_terminate | "0" | PHP_INI_ALL |
cli.pager | "" | PHP_INI_ALL | Available since PHP 5.4.0.
cli.prompt | "\\b \\> " | PHP_INI_ALL | Available since PHP 5.4.0.
cli_server.color | "0" | PHP_INI_ALL | Available since PHP 5.4.0.
coin_acceptor.autoreset | "On" | PHP_INI_ALL | Removed in coin_acceptor 0.2.
coin_acceptor.auto_initialize | "Off" | PHP_INI_ALL | Available since coin_acceptor 0.2.
coin_acceptor.auto_reset | "On" | PHP_INI_ALL | Available since coin_acceptor 0.2.
coin_acceptor.command_function | "Off" | PHP_INI_ALL | Available since coin_acceptor 0.3.
coin_acceptor.delay | "53132" | PHP_INI_ALL | Removed in coin_acceptor 0.2.
coin_acceptor.delay_coins | "53132" | PHP_INI_ALL | Available since coin_acceptor 0.2.
coin_acceptor.delay_prom | "55748" | PHP_INI_ALL | Available since coin_acceptor 0.2.
coin_acceptor.device | "/dev/ttyS1" | PHP_INI_ALL | Removed in coin_acceptor 0.2.
coin_acceptor.lock_on_close | "Off" | PHP_INI_ALL | Available since coin_acceptor 0.2.
coin_acceptor.start_unlocked | "On" | PHP_INI_ALL | Available since coin_acceptor 0.2.
com.allow_dcom | "0" | PHP_INI_SYSTEM |
com.autoregister_casesensitive | "1" | PHP_INI_ALL |
com.autoregister_typelib | "0" | PHP_INI_ALL |
com.autoregister_verbose | "0" | PHP_INI_ALL |
com.code_page | "" | PHP_INI_ALL |
com.typelib_file | "" | PHP_INI_SYSTEM |
curl.cainfo | NULL | PHP_INI_SYSTEM | Available since PHP 5.3.7.
daffodildb.default_host | "localhost" | PHP_INI_ALL |
daffodildb.default_password | "daffodil" | PHP_INI_ALL |
daffodildb.default_socket | NULL | PHP_INI_ALL |
daffodildb.default_user | "DAFFODIL" | PHP_INI_ALL |
daffodildb.port | "3456" | PHP_INI_ALL |
date.default_latitude | "31.7667" | PHP_INI_ALL |
date.default_longitude | "35.2333" | PHP_INI_ALL |
date.sunrise_zenith | "90.583333" | PHP_INI_ALL |
date.sunset_zenith | "90.583333" | PHP_INI_ALL |
date.timezone | "" | PHP_INI_ALL | Available since PHP 5.1.0.
dba.default_handler | "" | PHP_INI_ALL |
dbx.colnames_case | "unchanged" | PHP_INI_SYSTEM | Removed in PHP 5.1.0.
default_charset | "UTF-8" | PHP_INI_ALL | Default to "UTF-8" since PHP >= 5.6.0, empty for PHP < 5.6.0.
default_mimetype | "text/html" | PHP_INI_ALL |
default_socket_timeout | "60" | PHP_INI_ALL |
define_syslog_variables | "0" | PHP_INI_ALL | Removed in PHP 5.4.0.
detect_unicode | "1" | PHP_INI_ALL | Available since PHP 5.1.0. Renamed to zend.detect_unicode since PHP 5.4.0.
disable_classes | "" | php.ini only |
disable_functions | "" | php.ini only |
display_errors | "1" | PHP_INI_ALL |
display_startup_errors | "0" | PHP_INI_ALL |
docref_ext | "" | PHP_INI_ALL |
docref_root | "" | PHP_INI_ALL |
doc_root | NULL | PHP_INI_SYSTEM |
enable_dl | "1" | PHP_INI_SYSTEM | This deprecated feature will certainly be removed in the future.
enable_post_data_reading | On | PHP_INI_PERDIR | Available since PHP 5.4.0.
engine | "1" | PHP_INI_ALL |
error_append_string | NULL | PHP_INI_ALL |
error_log | NULL | PHP_INI_ALL |
error_prepend_string | NULL | PHP_INI_ALL |
error_reporting | NULL | PHP_INI_ALL |
exif.decode_jis_intel | "JIS" | PHP_INI_ALL |
exif.decode_jis_motorola | "JIS" | PHP_INI_ALL |
exif.decode_unicode_intel | "UCS-2LE" | PHP_INI_ALL |
exif.decode_unicode_motorola | "UCS-2BE" | PHP_INI_ALL |
exif.encode_jis | "" | PHP_INI_ALL |
exif.encode_unicode | "ISO-8859-15" | PHP_INI_ALL |
exit_on_timeout | "" | PHP_INI_ALL | Available since PHP 5.3.0
expect.logfile | "" | PHP_INI_ALL |
expect.loguser | "1" | PHP_INI_ALL |
expect.timeout | "10" | PHP_INI_ALL |
expose_php | "1" | php.ini only |
extension | NULL | php.ini only |
extension_dir | "/path/to/php" | PHP_INI_SYSTEM |
fastcgi.impersonate | "0" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 5.2.0.
fastcgi.logging | "1" | PHP_INI_SYSTEM | PHP_INI_ALL in PHP <= 5.2.0.
fbsql.allow_persistent | "1" | PHP_INI_SYSTEM |
fbsql.autocommit | "1" | PHP_INI_SYSTEM |
fbsql.batchSize | "1000" | PHP_INI_SYSTEM | Removed in PHP 5.1.0.
fbsql.batchsize | "1000" | PHP_INI_ALL | Available since PHP 5.1.0.
fbsql.default_database | "" | PHP_INI_SYSTEM |
fbsql.default_database_password | "" | PHP_INI_SYSTEM |
fbsql.default_host | NULL | PHP_INI_SYSTEM |
fbsql.default_password | "" | PHP_INI_SYSTEM |
fbsql.default_user | "_SYSTEM" | PHP_INI_SYSTEM |
fbsql.generate_warnings | "0" | PHP_INI_SYSTEM |
fbsql.max_connections | "128" | PHP_INI_SYSTEM |
fbsql.max_links | "128" | PHP_INI_SYSTEM |
fbsql.max_persistent | "-1" | PHP_INI_SYSTEM |
fbsql.max_results | "128" | PHP_INI_SYSTEM |
fbsql.show_timestamp_decimals | "0" | PHP_INI_SYSTEM | Available since PHP 5.1.5.
file_uploads | "1" | PHP_INI_SYSTEM |
filter.default | "unsafe_raw" | PHP_INI_PERDIR | PHP_INI_ALL in filter <= 0.9.4. Available since PHP 5.2.0.
filter.default_flags | NULL | PHP_INI_PERDIR | PHP_INI_ALL in filter <= 0.9.4. Available since PHP 5.2.0.
from | "" | PHP_INI_ALL |
gd.jpeg_ignore_warning | "1" | PHP_INI_ALL | Available since PHP 5.1.3.
geoip.custom_directory | NULL | PHP_INI_ALL | Available since geoip 1.0.1.
geoip.database_standard | "GeoIP.dat" | PHP_INI_ALL | Removed in geoip 1.0.1.
hard_timeout | "2" | PHP_INI_SYSTEM | Available since PHP 7.1.0.
hidef.ini_path | (char*)default_ini_path | PHP_INI_SYSTEM |
highlight.bg | "#FFFFFF" | PHP_INI_ALL | Removed in PHP 5.4.0.
highlight.comment | "#FF8000" | PHP_INI_ALL |
highlight.default | "#0000BB" | PHP_INI_ALL |
highlight.html | "#000000" | PHP_INI_ALL |
highlight.keyword | "#007700" | PHP_INI_ALL |
highlight.string | "#DD0000" | PHP_INI_ALL |
html_errors | "1" | PHP_INI_ALL |
htscanner.config_file | ".htaccess" | PHP_INI_SYSTEM |
htscanner.default_docroot | "/" | PHP_INI_SYSTEM |
htscanner.default_ttl | "300" | PHP_INI_SYSTEM | Available since htscanner 0.6.0.
htscanner.stop_on_error | "0" | PHP_INI_SYSTEM | Available since htscanner 0.7.0.
http.allowed_methods | "" | PHP_INI_ALL | Available since pecl_http 0.4.0. Removed in pecl_http 1.0.0.
http.allowed_methods_log | "" | PHP_INI_ALL | Available since pecl_http 0.12.0. Removed in pecl_http 1.0.0.
http.cache_log | "" | PHP_INI_ALL | Available since pecl_http 0.8.0. Removed in pecl_http 1.0.0.
http.composite_log | "" | PHP_INI_ALL | Available since pecl_http 0.12.0. Removed in pecl_http 1.0.0.
http.etag.mode | "MD5" | PHP_INI_ALL | Available since pecl_http 1.0.0.
http.etag_mode | "MD5" | PHP_INI_ALL | Available since pecl_http 0.12.0. Removed in pecl_http 1.0.0.
http.force_exit | "1" | PHP_INI_ALL | Available since pecl_http 0.18.0.
http.log.allowed_methods | "" | PHP_INI_ALL | Available since pecl_http 1.0.0.
http.log.cache | "" | PHP_INI_ALL | Available since pecl_http 1.0.0.
http.log.composite | "" | PHP_INI_ALL | Available since pecl_http 1.0.0.
http.log.not_found | "" | PHP_INI_ALL | Available since pecl_http 1.0.0.
http.log.redirect | "" | PHP_INI_ALL | Available since pecl_http 1.0.0.
http.ob_deflate_auto | "0" | PHP_INI_PERDIR | Available since pecl_http 0.21.0. Removed in pecl_http 1.0.0.
http.ob_deflate_flags | "0" | PHP_INI_ALL | Available since pecl_http 0.21.0. Removed in pecl_http 1.0.0.
http.ob_inflate_auto | "0" | PHP_INI_PERDIR | Available since pecl_http 0.21.0. Removed in pecl_http 1.0.0.
http.ob_inflate_flags | "0" | PHP_INI_ALL | Available since pecl_http 0.21.0. Removed in pecl_http 1.0.0.
http.only_exceptions | "0" | PHP_INI_ALL | Available since pecl_http 0.11.0.
http.persistent.handles.ident | "GLOBAL" | PHP_INI_ALL | Available since pecl_http 1.5.0.
http.persistent.handles.limit | "-1" | PHP_INI_SYSTEM | Available since pecl_http 1.5.0.
http.redirect_log | "" | PHP_INI_ALL | Available since pecl_http 0.12.0. Removed in pecl_http 1.0.0.
http.request.datashare.connect | "0" | PHP_INI_SYSTEM | Available since pecl_http 1.3.0.
http.request.datashare.cookie | "0" | PHP_INI_SYSTEM | Available since pecl_http 1.3.0.
http.request.datashare.dns | "1" | PHP_INI_SYSTEM | Available since pecl_http 1.3.0.
http.request.datashare.ssl | "0" | PHP_INI_SYSTEM | Available since pecl_http 1.3.0.
http.request.methods.allowed | "" | PHP_INI_ALL | Available since pecl_http 1.0.0.
http.request.methods.custom | "" | PHP_INI_PERDIR | Available since pecl_http 1.0.0.
http.send.deflate.start_auto | "0" | PHP_INI_PERDIR | Available since pecl_http 1.0.0.
http.send.deflate.start_flags | "0" | PHP_INI_ALL | Available since pecl_http 1.0.0.
http.send.inflate.start_auto | "0" | PHP_INI_PERDIR | Available since pecl_http 1.0.0.
http.send.inflate.start_flags | "0" | PHP_INI_ALL | Available since pecl_http 1.0.0.
http.send.not_found_404 | "1" | PHP_INI_ALL | Available since pecl_http 1.0.0.
ibase.allow_persistent | "1" | PHP_INI_SYSTEM |
ibase.dateformat | "%Y-%m-%d" | PHP_INI_ALL |
ibase.default_charset | NULL | PHP_INI_ALL |
ibase.default_db | NULL | PHP_INI_SYSTEM |
ibase.default_password | NULL | PHP_INI_ALL |
ibase.default_user | NULL | PHP_INI_ALL |
ibase.max_links | "-1" | PHP_INI_SYSTEM |
ibase.max_persistent | "-1" | PHP_INI_SYSTEM |
ibase.timeformat | "%H:%M:%S" | PHP_INI_ALL |
ibase.timestampformat | "%Y-%m-%d %H:%M:%S" | PHP_INI_ALL |
ibm_db2.binmode | "1" | PHP_INI_ALL |
ibm_db2.i5_all_pconnect | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.6.5.
ibm_db2.i5_allow_commit | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.4.9.
ibm_db2.i5_dbcs_alloc | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.5.0.
ibm_db2.instance_name | NULL | PHP_INI_SYSTEM | Available since ibm_db2 1.0.2.
ibm_db2.i5_ignore_userid | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.8.0.
iconv.input_encoding | "ISO-8859-1" | PHP_INI_ALL |
iconv.internal_encoding | "ISO-8859-1" | PHP_INI_ALL |
iconv.output_encoding | "ISO-8859-1" | PHP_INI_ALL |
ifx.allow_persistent | "1" | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.blobinfile | "1" | PHP_INI_ALL | Removed in PHP 5.2.1.
ifx.byteasvarchar | "0" | PHP_INI_ALL | Removed in PHP 5.2.1.
ifx.charasvarchar | "0" | PHP_INI_ALL | Removed in PHP 5.2.1.
ifx.default_host | NULL | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.default_password | NULL | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.default_user | NULL | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.max_links | "-1" | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.max_persistent | "-1" | PHP_INI_SYSTEM | Removed in PHP 5.2.1.
ifx.nullformat | "0" | PHP_INI_ALL | Removed in PHP 5.2.1.
ifx.textasvarchar | "0" | PHP_INI_ALL | Removed in PHP 5.2.1.
ignore_repeated_errors | "0" | PHP_INI_ALL |
ignore_repeated_source | "0" | PHP_INI_ALL |
ignore_user_abort | "0" | PHP_INI_ALL |
imlib2.font_cache_max_size | "524288" | PHP_INI_ALL |
imlib2.font_path | "/usr/share/php/fonts/" | PHP_INI_ALL |
implicit_flush | "0" | PHP_INI_ALL |
include_path | ".;/path/to/php/pear" | PHP_INI_ALL |
intl.default_locale | "" | PHP_INI_ALL | Available since PHP 5.3.0.
intl.error_level | "0" | PHP_INI_ALL | Available since PHP 5.3.0.
intl.use_exceptions | "0" | PHP_INI_ALL | Available since PHP 5.5.0.
ingres.allow_persistent | "1" | PHP_INI_SYSTEM | Available since ingres 1.0.0
ingres.array_index_start | "1" | PHP_INI_ALL | Available since ingres 1.4.0.
ingres.auto | "1" | PHP_INI_ALL | Available since ingres 2.0.0.
ingres.blob_segment_length | "4096" | PHP_INI_ALL | Available since ingres 1.2.0.
ingres.cursor_mode | "0" | PHP_INI_ALL | Available since ingres 1.1.0.
ingres.default_database | NULL | PHP_INI_ALL | Available since ingres 1.0.0
ingres.default_password | NULL | PHP_INI_ALL | Available since ingres 1.0.0
ingres.default_user | NULL | PHP_INI_ALL | Available since ingres 1.0.0
ingres.describe | 1 | PHP_INI_ALL | Available since ingres 2.1.0
ingres.fetch_buffer_size | 100 | PHP_INI_ALL | Available since ingres 2.1.0
ingres.max_links | "-1" | PHP_INI_SYSTEM | Available since ingres 1.0.0
ingres.max_persistent | "-1" | PHP_INI_SYSTEM | Available since ingres 1.0.0
ingres.reuse_connection | "1" | PHP_INI_ALL | Available since ingres 2.0.0
ingres.scrollable | "1" | PHP_INI_ALL | Available since ingres 2.0.0.
ingres.trace | "0" | PHP_INI_ALL | Available since ingres 2.0.0.
ingres.trace_connect | "0" | PHP_INI_ALL | Available since ingres 1.2.1.
ingres.utf8 | "1" | PHP_INI_ALL | Available since ingres 2.0.0.
last_modified | "0" | PHP_INI_ALL |
ldap.max_links | "-1" | PHP_INI_SYSTEM |
log_errors | "0" | PHP_INI_ALL |
log_errors_max_len | "1024" | PHP_INI_ALL |
magic_quotes_gpc | "1" | PHP_INI_PERDIR | Deprecated in PHP 5.3.0. Removed in PHP 5.4.0.
magic_quotes_runtime | "0" | PHP_INI_ALL | Removed in PHP 5.4.0.
magic_quotes_sybase | "0" | PHP_INI_ALL | Removed in PHP 5.4.0.
mail.add_x_header | "0" | PHP_INI_PERDIR | Available since PHP 5.3.0.
mail.force_extra_parameters | NULL | php.ini only |
mail.log | "" | PHP_INI_PERDIR | Available since PHP 5.3.0 (PHP_INI_SYSTEM|PHP_INI_PERDIR)
maxdb.default_db | NULL | PHP_INI_ALL |
maxdb.default_host | NULL | PHP_INI_ALL |
maxdb.default_pw | NULL | PHP_INI_ALL |
maxdb.default_user | NULL | PHP_INI_ALL |
maxdb.long_readlen | "200" | PHP_INI_ALL |
max_execution_time | "30" | PHP_INI_ALL |
max_input_nesting_level | "64" | PHP_INI_PERDIR | Available since PHP 5.2.3.
max_input_vars | 1000 | PHP_INI_PERDIR | Available since PHP 5.3.9.
max_input_time | "-1" | PHP_INI_PERDIR |
mbstring.detect_order | NULL | PHP_INI_ALL |
mbstring.encoding_translation | "0" | PHP_INI_PERDIR |
mbstring.func_overload | "0" | PHP_INI_SYSTEM | PHP_INI_SYSTEM | PHP_INI_PERDIR PHP <= 5.2.6
mbstring.http_input | "pass" | PHP_INI_ALL |
mbstring.http_output | "pass" | PHP_INI_ALL |
mbstring.internal_encoding | NULL | PHP_INI_ALL |
mbstring.language | "neutral" | PHP_INI_ALL | PHP_INI_PERDIR in PHP <= 5.2.6
mbstring.script_encoding | NULL | PHP_INI_ALL | Removed in PHP 5.4.0. Use zend.script_encoding instead.
mbstring.http_output_conv_mimetypes | "^(text/|application/xhtml\+xml)" | PHP_INI_ALL | Available since PHP 5.3.0.
mbstring.strict_detection | "0" | PHP_INI_ALL | Available since PHP 5.1.2.
mbstring.substitute_character | NULL | PHP_INI_ALL |
mcrypt.algorithms_dir | NULL | PHP_INI_ALL |
mcrypt.modes_dir | NULL | PHP_INI_ALL |
memcache.allow_failover | "1" | PHP_INI_ALL | Available since memcache 2.0.2.
memcache.chunk_size | "8192" | PHP_INI_ALL | Available since memcache 2.0.2.
memcache.default_port | "11211" | PHP_INI_ALL | Available since memcache 2.0.2.
memcache.hash_function | "crc32" | PHP_INI_ALL | Available since memcache 2.2.0.
memcache.hash_strategy | "standard" | PHP_INI_ALL | Available since memcache 2.2.0.
memcache.max_failover_attempts | "20" | PHP_INI_ALL | Available since memcache 2.1.0.
memory_limit | "128M" | PHP_INI_ALL |
mime_magic.debug | "0" | PHP_INI_SYSTEM |
mime_magic.magicfile | "/path/to/php/magic.mime" | PHP_INI_SYSTEM |
mongo.allow_empty_keys | 0 | PHP_INI_ALL |
mongo.allow_persistent | 1 | PHP_INI_ALL | Removed in 1.2.0
mongo.chunk_size | 262144 | PHP_INI_ALL |
mongo.cmd | "$" | PHP_INI_ALL |
mongo.default_host | "localhost" | PHP_INI_ALL |
mongo.default_port | 27017 | PHP_INI_ALL |
mongo.is_master_interval | 15 | PHP_INI_ALL | Added in 1.2.10, before 1.3.0 the default value was 60.
mongo.long_as_object | 0 | PHP_INI_ALL |
mongo.native_long | 1 | PHP_INI_ALL | Before 1.5.0, the default value was 0.
mongo.ping_interval | 5 | PHP_INI_ALL | Added in 1.2.10
mongo.utf8 | 1 | PHP_INI_ALL |
msql.allow_persistent | "1" | PHP_INI_ALL |
msql.max_links | "-1" | PHP_INI_ALL |
msql.max_persistent | "-1" | PHP_INI_ALL |
mssql.allow_persistent | "1" | PHP_INI_SYSTEM |
mssql.batchsize | "0" | PHP_INI_ALL |
mssql.charset | "" | PHP_INI_ALL | Available since PHP 5.1.2.
mssql.compatability_mode | "0" | PHP_INI_ALL |
mssql.connect_timeout | "5" | PHP_INI_ALL |
mssql.datetimeconvert | "1" | PHP_INI_ALL |
mssql.max_links | "-1" | PHP_INI_SYSTEM |
mssql.max_persistent | "-1" | PHP_INI_SYSTEM |
mssql.max_procs | "-1" | PHP_INI_ALL |
mssql.min_error_severity | "10" | PHP_INI_ALL |
mssql.min_message_severity | "10" | PHP_INI_ALL |
mssql.secure_connection | "0" | PHP_INI_SYSTEM |
mssql.textlimit | "-1" | PHP_INI_ALL |
mssql.textsize | "-1" | PHP_INI_ALL |
mssql.timeout | "60" | PHP_INI_ALL |
mysql.allow_local_infile | "1" | PHP_INI_SYSTEM |
mysql.allow_persistent | "1" | PHP_INI_SYSTEM |
mysql.max_persistent | "-1" | PHP_INI_SYSTEM |
mysql.max_links | "-1" | PHP_INI_SYSTEM |
mysql.trace_mode | "0" | PHP_INI_ALL |
mysql.default_port | NULL | PHP_INI_ALL |
mysql.default_socket | NULL | PHP_INI_ALL |
mysql.default_host | NULL | PHP_INI_ALL |
mysql.default_user | NULL | PHP_INI_ALL |
mysql.default_password | NULL | PHP_INI_ALL |
mysql.connect_timeout | "60" | PHP_INI_ALL |
mysqli.allow_local_infile | "0" | PHP_INI_SYSTEM | Available as of PHP 5.2.4. Before PHP 7.2.16 and 7.3.3 the default was "1".
mysqli.allow_persistent | "1" | PHP_INI_SYSTEM | Available as of PHP 5.3.0.
mysqli.max_persistent | "-1" | PHP_INI_SYSTEM | Available as of PHP 5.3.0.
mysqli.max_links | "-1" | PHP_INI_SYSTEM |
mysqli.default_port | "3306" | PHP_INI_ALL |
mysqli.default_socket | NULL | PHP_INI_ALL |
mysqli.default_host | NULL | PHP_INI_ALL |
mysqli.default_user | NULL | PHP_INI_ALL |
mysqli.default_pw | NULL | PHP_INI_ALL |
mysqli.reconnect | "0" | PHP_INI_SYSTEM |
mysqli.rollback_on_cached_plink | TRUE | PHP_INI_SYSTEM | Available as of PHP 5.6.0.
mysqlnd.collect_memory_statistics | "0" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
mysqlnd.collect_statistics | "1" | PHP_INI_ALL | Available since PHP 5.3.0.
mysqlnd.debug | "" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
mysqlnd.log_mask | "0" | PHP_INI_ALL | Available since PHP 5.4.0.
mysqlnd.mempool_default_size | "16000" | PHP_INI_ALL | Available since PHP 5.4.0.
mysqlnd.net_cmd_buffer_size | "4096" | PHP_INI_ALL | Available since PHP 5.4.0.
mysqlnd.net_read_buffer_size | "32768" | PHP_INI_ALL | Available since PHP 5.3.0.
mysqlnd.net_read_timeout | "31536000" | PHP_INI_SYSTEM | Available since PHP 5.4.0.
mysqlnd.sha256_server_public_key | "" | PHP_INI_PERDIR | Available since PHP 5.5.0.
mysqlnd.trace_alloc | "" | PHP_INI_SYSTEM | Available since PHP 5.5.0.
mysqlnd_memcache.enable | 1 | PHP_INI_SYSTEM | Available since 1.0.0
mysqlnd_ms.enable | 0 | PHP_INI_SYSTEM |
mysqlnd_ms.force_config_usage | 0 | PHP_INI_SYSTEM |
mysqlnd_ms.ini_file | "" | PHP_INI_SYSTEM |
mysqlnd_ms.config_file | "" | PHP_INI_SYSTEM |
mysqlnd_ms.collect_statistics | 0 | PHP_INI_SYSTEM |
mysqlnd_ms.multi_master | 0 | PHP_INI_SYSTEM |
mysqlnd_ms.disable_rw_split | 0 | PHP_INI_SYSTEM |
mysqlnd_mux.enable | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.enable_qc | 1 | PHP_INI_SYSTEM |
mysqlnd_qc.ttl | 30 | PHP_INI_ALL |
mysqlnd_qc.cache_by_default | 0 | PHP_INI_ALL |
mysqlnd_qc.cache_no_table | 0 | PHP_INI_ALL |
mysqlnd_qc.use_request_time | 0 | PHP_INI_ALL |
mysqlnd_qc.time_statistics | 1 | PHP_INI_ALL |
mysqlnd_qc.collect_statistics | 0 | PHP_INI_ALL |
mysqlnd_qc.collect_statistics_log_file | /tmp/mysqlnd_qc.stats | PHP_INI_SYSTEM |
mysqlnd_qc.collect_query_trace | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.query_trace_bt_depth | 3 | PHP_INI_SYSTEM |
mysqlnd_qc.collect_normalized_query_trace | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.ignore_sql_comments | 1 | PHP_INI_ALL |
mysqlnd_qc.slam_defense | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.slam_defense_ttl | 30 | PHP_INI_SYSTEM |
mysqlnd_qc.std_data_copy | 0 | PHP_INI_SYSTEM |
mysqlnd_qc.apc_prefix | qc_ | PHP_INI_ALL |
mysqlnd_qc.memc_server | 127.0.0.1 | PHP_INI_ALL |
mysqlnd_qc.memc_port | 11211 | PHP_INI_ALL |
mysqlnd_qc.sqlite_data_file | :memory: | PHP_INI_ALL |
mysqlnd_uh.enable | 1 | PHP_INI_SYSTEM |
mysqlnd_uh.report_wrong_types | 1 | PHP_INI_ALL |
nsapi.read_timeout | "60" | PHP_INI_ALL |
oci8.connection_class | "" | PHP_INI_ALL | Available since PHP 5.3 (PECL OCI8 1.3).
oci8.default_prefetch | "10" | PHP_INI_SYSTEM | Available since PHP 5.1.2.
oci8.events | Off | PHP_INI_SYSTEM | Available since PHP 5.3 (PECL OCI8 1.3).
oci8.max_persistent | "-1" | PHP_INI_SYSTEM | Available since PHP 5.1.2.
oci8.old_oci_close_semantics | "0" | PHP_INI_SYSTEM | Available since PHP 5.1.2.
oci8.persistent_timeout | "-1" | PHP_INI_SYSTEM | Available since PHP 5.1.2.
oci8.ping_interval | "60" | PHP_INI_SYSTEM | Available since PHP 5.1.2.
oci8.privileged_connect | "0" | PHP_INI_SYSTEM | Available since PHP 5.1.2.
oci8.statement_cache_size | "20" | PHP_INI_SYSTEM | Available since PHP 5.1.2.
odbc.allow_persistent | "1" | PHP_INI_SYSTEM |
odbc.check_persistent | "1" | PHP_INI_SYSTEM |
odbc.defaultbinmode | "1" | PHP_INI_ALL |
odbc.defaultlrl | "4096" | PHP_INI_ALL |
odbc.default_db | NULL | PHP_INI_ALL |
odbc.default_cursortype | "3" | PHP_INI_ALL | Available since PHP 5.3.0.
odbc.default_pw | NULL | PHP_INI_ALL |
odbc.default_user | NULL | PHP_INI_ALL |
odbc.max_links | "-1" | PHP_INI_SYSTEM |
odbc.max_persistent | "-1" | PHP_INI_SYSTEM |
odbtp.datetime_format | "object" | PHP_INI_ALL |
odbtp.detach_default_queries | "0" | PHP_INI_ALL |
odbtp.guid_format | "string" | PHP_INI_ALL | Available since odbtp 1.1.3.
odbtp.interface_file | "/usr/local/share/odbtp.conf" | PHP_INI_ALL |
odbtp.truncation_errors | "1" | PHP_INI_ALL |
opcache.enable | "1" | PHP_INI_ALL |
opcache.enable_cli | "0" | PHP_INI_SYSTEM | Between PHP 7.1.2 and 7.1.6 inclusive, the default was "1"
opcache.memory_consumption | "128" | PHP_INI_SYSTEM | Before PHP 7.0.0 the default was "64"
opcache.interned_strings_buffer | "8" | PHP_INI_SYSTEM | Before PHP 7.0.0 the default was "4"
opcache.max_accelerated_files | "10000" | PHP_INI_SYSTEM | Before PHP 7.0.0 the default was "2000"
opcache.max_wasted_percentage | "5" | PHP_INI_SYSTEM |
opcache.use_cwd | "1" | PHP_INI_SYSTEM |
opcache.validate_timestamps | "1" | PHP_INI_ALL |
opcache.revalidate_freq | "2" | PHP_INI_ALL |
opcache.revalidate_path | "0" | PHP_INI_ALL |
opcache.save_comments | "1" | PHP_INI_SYSTEM |
opcache.load_comments | "1" | PHP_INI_ALL | Removed in PHP 7.0.0.
opcache.fast_shutdown | "0" | PHP_INI_SYSTEM | Removed in PHP 7.2.0
opcache.enable_file_override | "0" | PHP_INI_SYSTEM |
opcache.optimization_level | "0x7FFEBFFF" | PHP_INI_SYSTEM | Changed from 0x7FFFBFFF in PHP 7.3.0, and from 0xFFFFFFFF in PHP 5.6.18
opcache.inherited_hack | "1" | PHP_INI_SYSTEM | Removed in PHP 7.3.0
opcache.dups_fix | "0" | PHP_INI_ALL |
opcache.blacklist_filename | "" | PHP_INI_SYSTEM |
opcache.max_file_size | "0" | PHP_INI_SYSTEM |
opcache.consistency_checks | "0" | PHP_INI_ALL |
opcache.force_restart_timeout | "180" | PHP_INI_SYSTEM |
opcache.error_log | "" | PHP_INI_SYSTEM |
opcache.log_verbosity_level | "1" | PHP_INI_SYSTEM |
opcache.preferred_memory_model | "" | PHP_INI_SYSTEM |
opcache.protect_memory | "0" | PHP_INI_SYSTEM |
opcache.mmap_base | NULL | PHP_INI_SYSTEM |
opcache.restrict_api | "" | PHP_INI_SYSTEM |
opcache.file_update_protection | "2" | PHP_INI_ALL |
opcache.huge_code_pages | "0" | PHP_INI_SYSTEM |
opcache.lockfile_path | "/tmp" | PHP_INI_SYSTEM |
opcache.opt_debug_level | "0" | PHP_INI_SYSTEM |
opcache.file_cache | NULL | PHP_INI_SYSTEM | Available as of PHP 7.0.0
opcache.file_cache_only | "0" | PHP_INI_SYSTEM | Available as of PHP 7.0.0
opcache.file_cache_consistency_checks | "1" | PHP_INI_SYSTEM | Available as of PHP 7.0.0
opcache.file_cache_fallback | "1" | PHP_INI_SYSTEM | Windows only. Available as of PHP 7.0.0
opcache.validate_permission | "0" | PHP_INI_SYSTEM | Available as of PHP 7.0.14
opcache.validate_root | "0" | PHP_INI_SYSTEM | Available as of PHP 7.0.14
opcache.preload | "" | PHP_INI_SYSTEM | Available as of PHP 7.4.0
opcache.preload_user | "" | PHP_INI_SYSTEM | Available as of PHP 7.4.0
opcache.cache_id | "1" | PHP_INI_SYSTEM | Windows only. Available as of PHP 7.4.0
opendirectory.default_separator | "/" | PHP_INI_ALL | Removed in opendirectory 0.2.2.
opendirectory.max_refs | "-1" | PHP_INI_ALL |
opendirectory.separator | "/" | PHP_INI_ALL | Available since opendirectory 0.2.2.
open_basedir | NULL | PHP_INI_ALL | PHP_INI_SYSTEM in PHP < 5.2.3.
oracle.allow_persistent | "-1" | PHP_INI_ALL | Removed in PHP 5.1.0.
oracle.max_links | "-1" | PHP_INI_ALL | Removed in PHP 5.1.0.
oracle.max_persistent | "-1" | PHP_INI_ALL | Removed in PHP 5.1.0.
output_buffering | "0" | PHP_INI_PERDIR |
output_handler | NULL | PHP_INI_PERDIR |
pam.servicename | "php" | PHP_INI_ALL |
pcre.backtrack_limit | "1000000" | PHP_INI_ALL | Available since PHP 5.2.0.
pcre.recursion_limit | "100000" | PHP_INI_ALL | Available since PHP 5.2.0.
pcre.jit | "1" | PHP_INI_ALL | Available since PHP 7.0.0.
pdo.dsn.* |  | php.ini only | Available since PHP 5.1.0.
pdo_odbc.connection_pooling | "strict" | PHP_INI_ALL | Available since PHP 5.1.0.
pdo_odbc.db2_instance_name | NULL | PHP_INI_SYSTEM | Available since PHP 5.1.1. This deprecated feature will certainly be removed in the future.
pfpro.defaulthost | "test-payflow.verisign.com" | PHP_INI_ALL | Removed in PHP 5.1.0.
pfpro.defaultport | "443" | PHP_INI_ALL | Removed in PHP 5.1.0.
pfpro.defaulttimeout | "30" | PHP_INI_ALL | Removed in PHP 5.1.0.
pfpro.proxyaddress | "" | PHP_INI_ALL | Removed in PHP 5.1.0.
pfpro.proxylogon | "" | PHP_INI_ALL | Removed in PHP 5.1.0.
pfpro.proxypassword | "" | PHP_INI_ALL | Removed in PHP 5.1.0.
pfpro.proxyport | "" | PHP_INI_ALL | Removed in PHP 5.1.0.
pgsql.allow_persistent | "1" | PHP_INI_SYSTEM |
pgsql.auto_reset_persistent | "0" | PHP_INI_SYSTEM |
pgsql.ignore_notice | "0" | PHP_INI_ALL |
pgsql.log_notice | "0" | PHP_INI_ALL |
pgsql.max_links | "-1" | PHP_INI_SYSTEM |
pgsql.max_persistent | "-1" | PHP_INI_SYSTEM |
phar.cache_list | "" | PHP_INI_SYSTEM | Available since PHP 5.4.0.
phar.extract_list | "" | PHP_INI_ALL | Available since phar 1.1.0.
phar.readonly | "1" | PHP_INI_ALL |
phar.require_hash | "1" | PHP_INI_ALL |
post_max_size | "8M" | PHP_INI_PERDIR |
precision | "14" | PHP_INI_ALL |
python.append_path | "" | PHP_INI_ALL |
python.prepend_path | "." | PHP_INI_ALL |
realpath_cache_size | "16K" | PHP_INI_SYSTEM | Available since PHP 5.1.0.
realpath_cache_ttl | "120" | PHP_INI_SYSTEM | Available since PHP 5.1.0.
register_argc_argv | "1" | PHP_INI_PERDIR |
register_globals | "0" | PHP_INI_PERDIR | Deprecated in PHP 5.3.0. Removed in PHP 5.4.0.
register_long_arrays | "1" | PHP_INI_PERDIR | Deprecated in PHP 5.3.0. Removed in PHP 5.4.0.
report_memleaks | "1" | PHP_INI_ALL |
report_zend_debug | "1" | PHP_INI_ALL |
request_order | "" | PHP_INI_PERDIR | Added in PHP 5.3.0
runkit.internal_override | "0" | PHP_INI_SYSTEM |
runkit.superglobal | "" | PHP_INI_PERDIR |
safe_mode | "0" | PHP_INI_SYSTEM | Removed in PHP 5.4.0.
safe_mode_allowed_env_vars | "PHP_" | PHP_INI_SYSTEM | Removed in PHP 5.4.0.
safe_mode_exec_dir | "" | PHP_INI_SYSTEM | Removed in PHP 5.4.0.
safe_mode_gid | "0" | PHP_INI_SYSTEM | Removed in PHP 5.4.0.
safe_mode_include_dir | NULL | PHP_INI_SYSTEM | Removed in PHP 5.4.0.
safe_mode_protected_env_vars | "LD_LIBRARY_PATH" | PHP_INI_SYSTEM | Removed in PHP 5.4.0.
sendmail_from | NULL | PHP_INI_ALL |
sendmail_path | "/usr/sbin/sendmail -t -i" | PHP_INI_SYSTEM |
serialize_precision | "-1" | PHP_INI_ALL | Before PHP 5.3.6, the default value was 100. Before PHP 7.1.0, the default value was 17.
session.auto_start | "0" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 5.4.19 and in PHP <= 5.5.1.
session.bug_compat_42 | "1" | PHP_INI_ALL | Removed in PHP 5.4.0.
session.bug_compat_warn | "1" | PHP_INI_ALL | Removed in PHP 5.4.0.
session.cache_expire | "180" | PHP_INI_ALL |
session.cache_limiter | "nocache" | PHP_INI_ALL |
session.cookie_domain | "" | PHP_INI_ALL |
session.cookie_httponly | "" | PHP_INI_ALL | Available since PHP 5.2.0.
session.cookie_lifetime | "0" | PHP_INI_ALL |
session.cookie_path | "/" | PHP_INI_ALL |
session.cookie_secure | "" | PHP_INI_ALL |
session.entropy_file | "" | PHP_INI_ALL | Removed in PHP 7.1.0.
session.entropy_length | "0" | PHP_INI_ALL | Removed in PHP 7.1.0.
session.gc_divisor | "100" | PHP_INI_ALL |
session.gc_maxlifetime | "1440" | PHP_INI_ALL |
session.gc_probability | "1" | PHP_INI_ALL |
session.sid_bits_per_character | "4" | PHP_INI_ALL | Available since PHP 7.1.0.
session.sid_length | "32" | PHP_INI_ALL | Available since PHP 7.1.0.
session.hash_bits_per_character | "5" | PHP_INI_ALL | Removed in PHP 7.1.0.
session.hash_function | "0" | PHP_INI_ALL | Removed in PHP 7.1.0.
session.lazy_write | "1" | PHP_INI_ALL | Available since PHP 7.0.0.
session.name | "PHPSESSID" | PHP_INI_ALL |
session.referer_check | "" | PHP_INI_ALL |
session.save_handler | "files" | PHP_INI_ALL |
session.save_path | "" | PHP_INI_ALL |
session.serialize_handler | "php" | PHP_INI_ALL |
session.upload_progress.cleanup | "1" | PHP_INI_PERDIR | Available since PHP 5.4.0.
session.upload_progress.enabled | "1" | PHP_INI_PERDIR | Available since PHP 5.4.0.
session.upload_progress.freq | "1%" | PHP_INI_PERDIR | Available since PHP 5.4.0.
session.upload_progress.min_freq | "1" | PHP_INI_PERDIR | Available since PHP 5.4.0.
session.upload_progress.name | "PHP_SESSION_UPLOAD_PROGRESS" | PHP_INI_PERDIR | Available since PHP 5.4.0.
session.upload_progress.prefix | "upload_progress_" | PHP_INI_PERDIR | Available since PHP 5.4.0.
session.use_strict_mode | "0" | PHP_INI_ALL | Available since PHP 5.5.2.
session.use_cookies | "1" | PHP_INI_ALL |
session.use_only_cookies | "1" | PHP_INI_ALL |
session.use_trans_sid | "0" | PHP_INI_ALL |
session_pgsql.create_table | "1" | PHP_INI_SYSTEM |
session_pgsql.db | "host=localhost dbname=php_session user=nobody" | PHP_INI_SYSTEM |
session_pgsql.disable | "0" | PHP_INI_SYSTEM |
session_pgsql.failover_mode | "0" | PHP_INI_SYSTEM |
session_pgsql.gc_interval | "3600" | PHP_INI_SYSTEM |
session_pgsql.keep_expired | "0" | PHP_INI_SYSTEM |
session_pgsql.sem_file_name | "/tmp/php_session_pgsql" | PHP_INI_SYSTEM |
session_pgsql.serializable | "0" | PHP_INI_SYSTEM |
session_pgsql.short_circuit | "0" | PHP_INI_SYSTEM |
session_pgsql.use_app_vars | "0" | PHP_INI_SYSTEM |
session_pgsql.vacuum_interval | "21600" | PHP_INI_SYSTEM |
short_open_tag | "1" | PHP_INI_PERDIR |
SMTP | "localhost" | PHP_INI_ALL |
smtp_port | "25" | PHP_INI_ALL |
soap.wsdl_cache | "1" | PHP_INI_ALL | Available since PHP 5.1.5.
soap.wsdl_cache_dir | "/tmp" | PHP_INI_ALL |
soap.wsdl_cache_enabled | "1" | PHP_INI_ALL |
soap.wsdl_cache_limit | "5" | PHP_INI_ALL | Available since PHP 5.1.5.
soap.wsdl_cache_ttl | "86400" | PHP_INI_ALL |
sql.safe_mode | "0" | PHP_INI_SYSTEM |
sqlite.assoc_case | "0" | PHP_INI_ALL |
sqlite3.extension_dir | "" | PHP_INI_SYSTEM | Available as of PHP 5.3.11.
sqlite3.defensive | 1 | PHP_INI_SYSTEM | Available as of PHP 7.2.17 and 7.3.4 for libsqlite ≥ 3.26.0.
sybase.allow_persistent | "1" | PHP_INI_ALL |
sybase.interface_file | "" | PHP_INI_ALL |
sybase.max_links | "-1" | PHP_INI_ALL |
sybase.max_persistent | "-1" | PHP_INI_ALL |
sybase.min_error_severity | "10" | PHP_INI_ALL |
sybase.min_message_severity | "10" | PHP_INI_ALL |
sybct.deadlock_retry_count | "0" | PHP_INI_ALL |
sybct.login_timeout | "-1" | PHP_INI_ALL |
sybct.packet_size | "0" | PHP_INI_ALL |
sybct.timeout | "0" | PHP_INI_ALL |
syslog.facility | "LOG_USER" | PHP_INI_SYSTEM | Available as of PHP 7.3.0.
syslog.filter | "no-ctrl" | PHP_INI_ALL | Available as of PHP 7.3.0.
syslog.ident | "php" | PHP_INI_SYSTEM | Available as of PHP 7.3.0.
sys_temp_dir | "" | PHP_INI_SYSTEM | Available since PHP 5.5.0.
sysvshm.init_mem | "10000" | PHP_INI_ALL |
tidy.clean_output | "0" | PHP_INI_USER | PHP_INI_PERDIR in PHP 5.
tidy.default_config | "" | PHP_INI_SYSTEM |
track_errors | "0" | PHP_INI_ALL | Deprecated as of PHP 7.2.0.
unserialize_callback_func | NULL | PHP_INI_ALL |
uploadprogress.file.filename_template | "/tmp/upt_%s.txt" | PHP_INI_ALL |
upload_max_filesize | "2M" | PHP_INI_PERDIR |
max_file_uploads | 20 | PHP_INI_SYSTEM | Available since PHP 5.2.12.
upload_tmp_dir | NULL | PHP_INI_SYSTEM |
url_rewriter.tags | "a=href,area=href,frame=src,form=,fieldset=" | PHP_INI_ALL |
user_agent | NULL | PHP_INI_ALL |
user_dir | NULL | PHP_INI_SYSTEM |
user_ini.cache_ttl | "300" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
user_ini.filename | ".user.ini" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
uopz.disable | "0" | PHP_INI_SYSTEM | Available as of uopz 5.0.2
uopz.exit | "0" | PHP_INI_SYSTEM | Available as of uopz 6.0.1
valkyrie.auto_validate | "0" | PHP_INI_ALL |
valkyrie.config_path | NULL | PHP_INI_ALL |
variables_order | "EGPCS" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 5.0.5.
vld.active | "0" | PHP_INI_SYSTEM |
vld.execute | "1" | PHP_INI_SYSTEM | Available since vld 0.8.0.
vld.skip_append | "0" | PHP_INI_SYSTEM | Available since vld 0.8.0.
vld.skip_prepend | "0" | PHP_INI_SYSTEM | Available since vld 0.8.0.
windows.show_crt_warning | "0" | PHP_INI_ALL | Available since PHP 5.4.0.
xbithack | "0" | PHP_INI_ALL |
xdebug.auto_profile | "0" | PHP_INI_ALL | Removed in Xdebug 2.0.0.
xdebug.auto_profile_mode | "0" | PHP_INI_ALL | Removed in Xdebug 2.0.0.
xdebug.auto_trace | "0" | PHP_INI_ALL |
xdebug.collect_includes | "1" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.collect_params | "0" | PHP_INI_ALL |
xdebug.collect_return | "0" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.collect_vars | "0" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.default_enable | "1" | PHP_INI_ALL | PHP_INI_SYSTEM in Xdebug 1.
xdebug.dump.COOKIE | NULL | PHP_INI_ALL |
xdebug.dump.ENV | NULL | PHP_INI_ALL |
xdebug.dump.FILES | NULL | PHP_INI_ALL |
xdebug.dump.GET | NULL | PHP_INI_ALL |
xdebug.dump.POST | NULL | PHP_INI_ALL |
xdebug.dump.REQUEST | NULL | PHP_INI_ALL |
xdebug.dump.SERVER | NULL | PHP_INI_ALL |
xdebug.dump.SESSION | NULL | PHP_INI_ALL |
xdebug.dump_globals | "1" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.dump_once | "1" | PHP_INI_ALL |
xdebug.dump_undefined | "0" | PHP_INI_ALL |
xdebug.extended_info | "1" | PHP_INI_SYSTEM | Available since Xdebug 2.0.0.
xdebug.idekey | "" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.manual_url | "http://www.php.net" | PHP_INI_ALL |
xdebug.max_nesting_level | "100" | PHP_INI_ALL |
xdebug.output_dir | "/tmp" | PHP_INI_PERDIR | PHP_INI_SYSTEM in Xdebug <= 1.2.0. Removed in Xdebug 2.0.0.
xdebug.profiler_aggregate | "0" | PHP_INI_PERDIR | Available since Xdebug 2.0.0.
xdebug.profiler_append | "0" | PHP_INI_PERDIR | Available since Xdebug 2.0.0.
xdebug.profiler_enable | "0" | PHP_INI_PERDIR | Available since Xdebug 2.0.0.
xdebug.profiler_enable_trigger | "0" | PHP_INI_PERDIR | Available since Xdebug 2.0.0.
xdebug.profiler_output_dir | "/tmp" | PHP_INI_PERDIR | Available since Xdebug 2.0.0.
xdebug.profiler_output_name | "cachegrind.out.%p" | PHP_INI_PERDIR | Available since Xdebug 2.0.0.
xdebug.remote_autostart | "0" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.remote_enable | "0" | PHP_INI_PERDIR |
xdebug.remote_handler | "dbgp" | PHP_INI_ALL |
xdebug.remote_host | "localhost" | PHP_INI_ALL |
xdebug.remote_log | "" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.remote_mode | "req" | PHP_INI_ALL |
xdebug.remote_port | "9000" | PHP_INI_ALL |
xdebug.show_exception_trace | "0" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.show_local_vars | "0" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.show_mem_delta | "0" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.trace_format | "0" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.trace_options | "0" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.trace_output_dir | "/tmp" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.trace_output_name | "trace.%c" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.var_display_max_children | "128" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.var_display_max_data | "512" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xdebug.var_display_max_depth | "3" | PHP_INI_ALL | Available since Xdebug 2.0.0.
xmlrpc_errors | "0" | PHP_INI_SYSTEM |
xmlrpc_error_number | "0" | PHP_INI_ALL |
xmms.path | "/usr/bin/xmms" | PHP_INI_ALL |
xmms.session | "0" | PHP_INI_ALL |
xsl.security_prefs | "44" | PHP_INI_ALL | Available since PHP 5.5.0.
y2k_compliance | "1" | PHP_INI_ALL | Removed in PHP 5.4.0.
yami.response.timeout | "5" | PHP_INI_ALL | Available since yami 1.0.1.
yaz.keepalive | "120" | PHP_INI_ALL |
yaz.log_mask | NULL | PHP_INI_ALL | Available since yaz 1.0.3.
zend.assertions | "1" | PHP_INI_ALL | Available since PHP 7.0.0.
zend.detect_unicode | "1" | PHP_INI_ALL | Available since PHP 5.4.0.
zend.enable_gc | "1" | PHP_INI_ALL | Available since PHP 5.3.0.
zend.multibyte | "0" | PHP_INI_PERDIR | Available since PHP 5.4.0.
zend.script_encoding | NULL | PHP_INI_ALL | Available since PHP 5.4.0
zend.signal_check | "0" | PHP_INI_SYSTEM | Available since PHP 5.4.0
zend.ze1_compatibility_mode | "0" | PHP_INI_ALL | Available since PHP 5.0.0. Removed in PHP 5.3.0.
zend_extension | NULL | php.ini only |
zend_extension_debug | NULL | php.ini only |
zend_extension_debug_ts | NULL | php.ini only |
zend_extension_ts | NULL | php.ini only |
zlib.output_compression | "0" | PHP_INI_ALL |
zlib.output_compression_level | "-1" | PHP_INI_ALL |
zlib.output_handler | "" | PHP_INI_ALL |


List of php.ini sections

This list includes the php.ini sections you can set to configure your PHP setup on a per Host or Path basis. These sections are optional.

These sections don't directly affect PHP. They are used to group other php.ini directives together and to get them to act upon a particular host or on a particular path.

These sections are used only in CGI/FastCGI mode and they can not set extension and zend_extension directives.

Sections
Name | Changeable | Changelog
[HOST=] | PHP_INI_SYSTEM | Added in PHP 5.3.0.
[PATH=] | PHP_INI_SYSTEM | Added in PHP 5.3.0.

Here's a short explanation of the configuration directives.

[HOST=<host>]

This section allows you to define a set of php.ini directives that will take effect on the named host.

Example #1 Activate full on-screen error reporting for dev. domain

[HOST=dev.site.com]
error_reporting = E_ALL
display_errors = On

[PATH=<path>]

This section allows you to define a set of php.ini directives that will take effect when a script runs from the named path.

Example #2 Add security script for protected areas

[PATH=/home/site/public/secure]
auto_prepend_file=security.php


Description of core php.ini directives

This list includes the core php.ini directives you can set to configure your PHP setup. Directives handled by extensions are listed and detailed at the extension documentation pages respectively; Information on the session directives for example can be found at the sessions page.

Note:

The defaults listed here are used when php.ini is not loaded; the values for the production and development php.ini may vary.

Language Options

Language and Misc Configuration Options
Name | Default | Changeable | Changelog
short_open_tag | "1" | PHP_INI_PERDIR |
asp_tags | "0" | PHP_INI_PERDIR | Removed in PHP 7.0.0.
precision | "14" | PHP_INI_ALL |
serialize_precision | "-1" | PHP_INI_ALL | Before PHP 5.3.6, the default value was 100. Before PHP 7.1.0, the default value was 17.
y2k_compliance | "1" | PHP_INI_ALL | Removed in PHP 5.4.0.
allow_call_time_pass_reference | "1" | PHP_INI_PERDIR | Removed in PHP 5.4.0.
disable_functions | "" | PHP_INI_SYSTEM only |
disable_classes | "" | php.ini only |
exit_on_timeout | "" | PHP_INI_ALL | Available since PHP 5.3.0.
expose_php | "1" | php.ini only |
hard_timeout | "2" | PHP_INI_SYSTEM | Available since PHP 7.1.0.
zend.multibyte | "0" | PHP_INI_ALL | Available since PHP 5.4.0
zend.script_encoding | NULL | PHP_INI_ALL | Available since PHP 5.4.0
zend.detect-unicode | NULL | PHP_INI_ALL | Available since PHP 5.4.0
zend.signal_check | "0" | PHP_INI_SYSTEM | Available since PHP 5.4.0
zend.assertions | "1" | PHP_INI_ALL with restrictions | Available since PHP 7.0.0.
zend.ze1_compatibility_mode | "0" | PHP_INI_ALL | Removed in PHP 5.3.0
detect_unicode | "1" | PHP_INI_ALL | Available since PHP 5.1.0. Renamed to zend.detect-unicode from PHP 5.4.0.

Here's a short explanation of the configuration directives.

short_open_tag boolean

Tells PHP whether the short form (<? ?>) of PHP's open tag should be allowed. If you want to use PHP in combination with XML, you can disable this option in order to use <?xml ?> inline. Otherwise, you can print it with PHP, for example: <?php echo '<?xml version="1.0"?>'; ?>. Also, if disabled, you must use the long form of the PHP open tag (<?php ?>).

Note:

This directive also affected the shorthand <?= before PHP 5.4.0, which is identical to <? echo. Use of this shortcut required short_open_tag to be on. Since PHP 5.4.0, <?= is always available.

asp_tags boolean
Enables the use of ASP-like <% %> tags in addition to the usual <?php ?> tags. This includes the variable-value printing shorthand of <%= $value %>. For more information, see Escaping from HTML.

Changelog for asp_tags
Version | Description
7.0.0 | Removed from PHP.

precision integer
The number of significant digits displayed in floating point numbers. -1 means that an enhanced algorithm for rounding such numbers will be used.
serialize_precision integer
The number of significant digits stored while serializing floating point numbers. -1 means that an enhanced algorithm for rounding such numbers will be used.
y2k_compliance boolean
Enforce year 2000 compliance (will cause problems with non-compliant browsers)
allow_call_time_pass_reference boolean

Whether to warn when arguments are passed by reference at function call time. The encouraged method of specifying which arguments should be passed by reference is in the function declaration. You're encouraged to try and turn this option Off and make sure your scripts work properly with it in order to ensure they will work with future versions of the language (you will receive a warning each time you use this feature).

Passing arguments by reference at function call time was deprecated for code-cleanliness reasons. A function can modify its arguments in an undocumented way if it didn't declare that the argument shall be passed by reference. To prevent side-effects it's better to specify which arguments are passed by reference in the function declaration only.

See also References Explained.

Changelog for allow_call_time_pass_reference
Version | Description
5.4.0 | Removed from PHP.
5.3.0 | Emits an E_DEPRECATED level error.
5.0.0 | Deprecated, and generates an E_COMPILE_WARNING level error.

expose_php boolean

Exposes to the world that PHP is installed on the server, which includes the PHP version within the HTTP header (e.g., X-Powered-By: PHP/5.3.7). Prior to PHP 5.5.0 the PHP logo guids are also exposed, thus appending them to the URL of your PHP script would display the appropriate logo (e.g., » https://www.php.net/?=PHPE9568F34-D428-11d2-A769-00AA001ACF42). This also affected the output of phpinfo(), as when disabled, the PHP logo and credits information would not be displayed.

Note:

Since PHP 5.5.0 these guids and the php_logo_guid() function have been removed from PHP and the guids are replaced with data URIs instead. Thus accessing the PHP logo via appending the guid to the URL no longer works. Similarly, turning expose_php off will not affect seeing the PHP logo in phpinfo().

See also php_logo_guid() and phpcredits().

disable_functions string

This directive allows you to disable certain functions. It takes on a comma-delimited list of function names.

Only internal functions can be disabled using this directive. User-defined functions are unaffected.

This directive must be set in php.ini For example, you cannot set this in httpd.conf.

disable_classes string
This directive allows you to disable certain classes. It takes on a comma-delimited list of class names. This directive must be set in php.ini For example, you cannot set this in httpd.conf.
zend.assertions integer
When set to 1, assertion code will be generated and executed (development mode). When set to 0, assertion code will be generated but it will be skipped (not executed) at runtime. When set to -1, assertion code will not be generated, making the assertions zero-cost (production mode).

Note:

If a process is started in production mode, zend.assertions cannot be changed at runtime, since the code for assertions was not generated.

If a process is started in development mode, zend.assertions cannot be set to -1 at runtime.

zend.ze1_compatibility_mode boolean

Enable compatibility mode with Zend Engine 1 (PHP 4). It affects the cloning, casting (objects with no properties cast to FALSE or 0), and comparing of objects. In this mode, objects are passed by value instead of reference by default.

See also the section titled Migrating from PHP 4 to PHP 5.

Warning

This feature has been DEPRECATED and REMOVED as of PHP 5.3.0.

hard_timeout integer

zend.multibyte boolean

Enables parsing of source files in multibyte encodings. Enabling zend.multibyte is required to use character encodings like SJIS, BIG5, etc that contain special characters in multibyte string data. ISO-8859-1 compatible encodings like UTF-8, EUC, etc do not require this option.

Enabling zend.multibyte requires the mbstring extension to be available.

zend.script_encoding string

This value will be used unless a declare(encoding=...) directive appears at the top of the script. When ISO-8859-1 incompatible encoding is used, both zend.multibyte and zend.script_encoding must be used.

Literal strings will be transliterated from zend.script_enconding to mbstring.internal_encoding, as if mb_convert_encoding() would have been called.

zend.detect_unicode boolean

Check for BOM (Byte Order Mark) and see if the file contains valid multibyte characters. This detection is performed before processing of __halt_compiler(). Available only in Zend Multibyte mode.

zend.signal_check boolean

To check for replaced signal handlers on shutdown.

exit_on_timeout boolean

This is an Apache1 mod_php-only directive that forces an Apache child to exit if a PHP execution timeout occurred. Such a timeout causes an internal longjmp() call in Apache1 which can leave some extensions in an inconsistent state. By terminating the process any outstanding locks or memory will be cleaned up.

Resource Limits

Resource Limits
Name | Default | Changeable | Changelog
memory_limit | "128M" | PHP_INI_ALL | "8M" before PHP 5.2.0, "16M" in PHP 5.2.0

Here's a short explanation of the configuration directives.

memory_limit integer

This sets the maximum amount of memory in bytes that a script is allowed to allocate. This helps prevent poorly written scripts for eating up all available memory on a server. Note that to have no memory limit, set this directive to -1.

Prior to PHP 5.2.1, in order to use this directive it had to be enabled at compile time by using --enable-memory-limit in the configure line. This compile-time flag was also required to define the functions memory_get_usage() and memory_get_peak_usage() prior to 5.2.1.

When an integer is used, the value is measured in bytes. Shorthand notation, as described in this FAQ, may also be used.

See also: max_execution_time.

Performance Tuning

Performance Tuning
Name | Default | Changeable | Changelog
realpath_cache_size | "4M" | PHP_INI_SYSTEM | Available since PHP 5.1.0. Prior to PHP 7.0.16 and 7.1.2, the default was "16K"
realpath_cache_ttl | "120" | PHP_INI_SYSTEM | Available since PHP 5.1.0.

Note:

Using open_basedir will disable the realpath cache.

Here's a short explanation of the configuration directives.

realpath_cache_size integer

Determines the size of the realpath cache to be used by PHP. This value should be increased on systems where PHP opens many files, to reflect the quantity of the file operations performed.

The size represents the total number of bytes in the path strings stored, plus the size of the data associated with the cache entry. This means that in order to store longer paths in the cache, the cache size must be larger. This value does not directly control the number of distinct paths that can be cached.

The size required for the cache entry data is system dependent.

realpath_cache_ttl integer

Duration of time (in seconds) for which to cache realpath information for a given file or directory. For systems with rarely changing files, consider increasing the value.

Data Handling

Data Handling Configuration Options
Name | Default | Changeable | Changelog
arg_separator.output | "&" | PHP_INI_ALL |
arg_separator.input | "&" | PHP_INI_PERDIR |
variables_order | "EGPCS" | PHP_INI_PERDIR | PHP_INI_ALL in PHP <= 5.0.5.
request_order | "" | PHP_INI_PERDIR | Available since PHP 5.3.0
auto_globals_jit | "1" | PHP_INI_PERDIR | Available since PHP 5.0.0.
register_globals | "0" | PHP_INI_PERDIR | Removed in PHP 5.4.0.
register_argc_argv | "1" | PHP_INI_PERDIR |
register_long_arrays | "1" | PHP_INI_PERDIR | Deprecated in PHP 5.3.0. Removed in PHP 5.4.0.
enable_post_data_reading | "1" | PHP_INI_PERDIR | Available since PHP 5.4.0
post_max_size | "8M" | PHP_INI_PERDIR |
auto_prepend_file | NULL | PHP_INI_PERDIR |
auto_append_file | NULL | PHP_INI_PERDIR |
default_mimetype | "text/html" | PHP_INI_ALL |
default_charset | "UTF-8" | PHP_INI_ALL | Defaults to "UTF-8" since PHP >= 5.6.0; empty for PHP < 5.6.0.
always_populate_raw_post_data | "0" | PHP_INI_PERDIR | Removed in PHP 7.0.0.

Here's a short explanation of the configuration directives.

arg_separator.output string

The separator used in PHP generated URLs to separate arguments.

arg_separator.input string

List of separator(s) used by PHP to parse input URLs into variables.

Note:

Every character in this directive is considered as separator!

variables_order string

Sets the order of the EGPCS (Environment, Get, Post, Cookie, and Server) variable parsing. For example, if variables_order is set to "SP" then PHP will create the superglobals $_SERVER and $_POST, but not create $_ENV, $_GET, and $_COOKIE. Setting to "" means no superglobals will be set.

If the deprecated register_globals directive is on, then variables_order also configures the order the ENV, GET, POST, COOKIE and SERVER variables are populated in global scope. So for example if variables_order is set to "EGPCS", register_globals is enabled, and both $_GET['action'] and $_POST['action'] are set, then $action will contain the value of $_POST['action'] as P comes after G in our example directive value.

Warning

In both the CGI and FastCGI SAPIs, $_SERVER is also populated by values from the environment; S is always equivalent to ES regardless of the placement of E elsewhere in this directive.

Note:

The content and order of $_REQUEST is also affected by this directive.

request_order string

This directive describes the order in which PHP registers GET, POST and Cookie variables into the _REQUEST array. Registration is done from left to right, newer values override older values.

If this directive is not set, variables_order is used for $_REQUEST contents.

Note that the default distribution php.ini files does not contain the 'C' for cookies, due to security concerns.

auto_globals_jit boolean

When enabled, the SERVER, REQUEST, and ENV variables are created when they're first used (Just In Time) instead of when the script starts. If these variables are not used within a script, having this directive on will result in a performance gain.

The PHP directives register_globals, register_long_arrays, and register_argc_argv must be disabled for this directive to have any affect. Since PHP 5.1.3 it is not necessary to have register_argc_argv disabled.

Warning

Usage of SERVER, REQUEST, and ENV variables is checked during the compile time so using them through e.g. variable variables will not cause their initialization.

register_globals boolean

Whether or not to register the EGPCS (Environment, GET, POST, Cookie, Server) variables as global variables.

As of » PHP 4.2.0, this directive defaults to off.

Please read the security chapter on Using register_globals for related information.

Please note that register_globals cannot be set at runtime (ini_set()). Although, you can use .htaccess if your host allows it as described above. An example .htaccess entry: php_flag register_globals off.

Note:

register_globals is affected by the variables_order directive.

Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

register_argc_argv boolean
Tells PHP whether to declare the argv & argc variables (that would contain the GET information). See also command line.
register_long_arrays boolean
Tells PHP whether or not to register the deprecated long $HTTP_*_VARS type predefined variables. When On (default), long predefined PHP variables like $HTTP_GET_VARS will be defined. If you're not using them, it's recommended to turn them off, for performance reasons. Instead, use the superglobal arrays, like $_GET. This directive became available in PHP 5.0.0.
Warning

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

enable_post_data_reading boolean
Disabling this option causes $_POST and $_FILES not to be populated. The only way to read postdata will then be through the php://input stream wrapper. This can be useful to proxy requests or to process the POST data in a memory efficient fashion.
post_max_size integer
Sets max size of post data allowed. This setting also affects file upload. To upload large files, this value must be larger than upload_max_filesize. Generally speaking, memory_limit should be larger than post_max_size. When an integer is used, the value is measured in bytes. Shorthand notation, as described in this FAQ, may also be used. If the size of post data is greater than post_max_size, the $_POST and $_FILES superglobals are empty. This can be tracked in various ways, e.g. by passing the $_GET variable to the script processing the data, i.e. <form action="edit.php?processed=1">, and then checking if $_GET['processed'] is set.

Note:

PHP allows shortcuts for byte values, including K (kilo), M (mega) and G (giga). PHP will do the conversions automatically if you use any of these. Be careful not to exceed the 32 bit signed integer limit (if you're using 32bit versions) as it will cause your script to fail.

Changelog for post_max_size
Version | Description
5.3.4 | post_max_size = 0 will not disable the limit when the content type is application/x-www-form-urlencoded or is not registered with PHP.
5.3.2 , 5.2.12 | Allow unlimited post size by setting post_max_size to 0.

auto_prepend_file string

Specifies the name of a file that is automatically parsed before the main file. The file is included as if it was called with the require function, so include_path is used.

The special value none disables auto-prepending.

auto_append_file string

Specifies the name of a file that is automatically parsed after the main file. The file is included as if it was called with the require function, so include_path is used.

The special value none disables auto-appending.

Note: If the script is terminated with exit(), auto-append will not occur.

default_mimetype string

By default, PHP will output a media type using the Content-Type header. To disable this, simply set it to be empty.

PHP's built-in default media type is set to text/html.

default_charset string

In PHP 5.6 onwards, "UTF-8" is the default value and its value is used as the default character encoding for htmlentities(), html_entity_decode() and htmlspecialchars() if the encoding parameter is omitted. The value of default_charset will also be used to set the default character set for iconv functions if the iconv.input_encoding, iconv.output_encoding and iconv.internal_encoding configuration options are unset, and for mbstring functions if the mbstring.http_input mbstring.http_output mbstring.internal_encoding configuration option is unset.

All versions of PHP will use this value as the charset within the default Content-Type header sent by PHP if the header isn't overridden by a call to header().

Setting default_charset to an empty value is not recommended.

input_encoding string

Available from PHP 5.6.0. This setting is used for multibyte modules such as mbstring and iconv. Default is empty.

output_encoding string

Available from PHP 5.6.0. This setting is used for multibyte modules such as mbstring and iconv. Default is empty.

internal_encoding string

Available from PHP 5.6.0. This setting is used for multibyte modules such as mbstring and iconv. Default is empty. If empty, default_charset is used.

always_populate_raw_post_data mixed
Warning

This feature was DEPRECATED in PHP 5.6.0, and REMOVED as of PHP 7.0.0.

If set to TRUE, PHP will always populate the $HTTP_RAW_POST_DATA containing the raw POST data. Otherwise, the variable is populated only when the MIME type of the data is unrecognised.

The preferred method for accessing raw POST data is php://input, and $HTTP_RAW_POST_DATA is deprecated in PHP 5.6.0 onwards. Setting always_populate_raw_post_data to -1 will opt into the new behaviour that will be implemented in a future version of PHP, in which $HTTP_RAW_POST_DATA is never defined.

Regardless of the setting, $HTTP_RAW_POST_DATA is not available with enctype="multipart/form-data".

See also: magic_quotes_gpc, magic_quotes_runtime, and magic_quotes_sybase.

Paths and Directories

Paths and Directories Configuration Options
Name | Default | Changeable | Changelog
include_path | ".;/path/to/php/pear" | PHP_INI_ALL |
open_basedir | NULL | PHP_INI_ALL | PHP_INI_SYSTEM in PHP < 5.3.0
doc_root | NULL | PHP_INI_SYSTEM |
user_dir | NULL | PHP_INI_SYSTEM |
user_ini.cache_ttl | "300" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
user_ini.filename | ".user.ini" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
extension_dir | "/path/to/php" | PHP_INI_SYSTEM |
extension | NULL | php.ini only |
zend_extension | NULL | php.ini only |
zend_extension_debug | NULL | php.ini only | Available before PHP 5.3.0.
zend_extension_debug_ts | NULL | php.ini only | Available before PHP 5.3.0.
zend_extension_ts | NULL | php.ini only | Available before PHP 5.3.0.
cgi.check_shebang_line | "1" | PHP_INI_SYSTEM | Available since PHP 5.2.0.
cgi.discard_path | "0" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
cgi.fix_pathinfo | "1" | PHP_INI_SYSTEM | PHP_INI_ALL prior to PHP 5.2.1.
cgi.force_redirect | "1" | PHP_INI_SYSTEM | PHP_INI_ALL prior to PHP 5.2.1.
cgi.nph | "0" | PHP_INI_SYSTEM | Available since PHP 5.3.0.
cgi.redirect_status_env | NULL | PHP_INI_SYSTEM | PHP_INI_ALL prior to PHP 5.2.1.
cgi.rfc2616_headers | "0" | PHP_INI_ALL |
fastcgi.impersonate | "0" | PHP_INI_SYSTEM | PHP_INI_ALL prior to PHP 5.2.1.
fastcgi.logging | "1" | PHP_INI_SYSTEM | PHP_INI_ALL prior to PHP 5.2.1.

Here's a short explanation of the configuration directives.

include_path string

Specifies a list of directories where the require, include, fopen(), file(), readfile() and file_get_contents() functions look for files. The format is like the system's PATH environment variable: a list of directories separated with a colon in Unix or semicolon in Windows.

PHP considers each entry in the include path separately when looking for files to include. It will check the first path, and if it doesn't find it, check the next path, until it either locates the included file or returns with a warning or an error. You may modify or set your include path at runtime using set_include_path().

Example #1 Unix include_path

include_path=".:/php/includes"

Example #2 Windows include_path

include_path=".;c:\php\includes"

Using a . in the include path allows for relative includes as it means the current directory. However, it is more efficient to explicitly use include './file' than having PHP always check the current directory for every include.

Note:

ENV variables are also accessible in .ini files. As such it is possible to reference the home directory using ${LOGIN} and ${USER}.

Environment variables may vary between Server APIs as those environments may be different.

Example #3 Unix include_path using ${USER} env variable

include_path = ".:${USER}/pear/php"

open_basedir string

Limit the files that can be accessed by PHP to the specified directory-tree, including the file itself. This directive is NOT affected by whether Safe Mode is turned On or Off.

When a script tries to access the filesystem, for example using include, or fopen(), the location of the file is checked. When the file is outside the specified directory-tree, PHP will refuse to access it. All symbolic links are resolved, so it's not possible to avoid this restriction with a symlink. If the file doesn't exist then the symlink couldn't be resolved and the filename is compared to (a resolved) open_basedir .

open_basedir can affect more than just filesystem functions; for example if MySQL is configured to use mysqlnd drivers, LOAD DATA INFILE will be affected by open_basedir . Much of the extended functionality of PHP uses open_basedir in this way.

The special value . indicates that the working directory of the script will be used as the base-directory. This is, however, a little dangerous as the working directory of the script can easily be changed with chdir().

In httpd.conf, open_basedir can be turned off (e.g. for some virtual hosts) the same way as any other configuration directive with "php_admin_value open_basedir none".

Under Windows, separate the directories with a semicolon. On all other systems, separate the directories with a colon. As an Apache module, open_basedir paths from parent directories are now automatically inherited.

The restriction specified with open_basedir is a directory name since PHP 5.2.16 and 5.3.4. Previous versions used it as a prefix. This means that "open_basedir = /dir/incl" also allowed access to "/dir/include" and "/dir/incls" if they exist. When you want to restrict access to only the specified directory, end with a slash. For example: open_basedir = /dir/incl/

The default is to allow all files to be opened.

Note:

As of PHP 5.3.0 open_basedir can be tightened at run-time. This means that if open_basedir is set to /www/ in php.ini a script can tighten the configuration to /www/tmp/ at run-time with ini_set(). When listing several directories, you can use the PATH_SEPARATOR constant as a separator regardless of the operating system.

Note:

Using open_basedir will set realpath_cache_size to 0 and thus disable the realpath cache.

doc_root string

PHP's "root directory" on the server. Only used if non-empty. If PHP is configured with safe mode, no files outside this directory are served. If PHP was not compiled with FORCE_REDIRECT, you should set doc_root if you are running PHP as a CGI under any web server (other than IIS). The alternative is to use the cgi.force_redirect configuration below.

user_ini.cache_ttl integer

user_ini.filename string

user_dir string

The base name of the directory used on a user's home directory for PHP files, for example public_html .

extension_dir string

In what directory PHP should look for dynamically loadable extensions. See also: enable_dl, and dl().

extension string

Which dynamically loadable extensions to load when PHP starts up.

zend_extension string

Name of dynamically loadable Zend extension (for example APD) to load when PHP starts up.

zend_extension_debug string

Variant of zend_extension for extensions compiled with debug info prior to PHP 5.3.0.

zend_extension_debug_ts string

Variant of zend_extension for extensions compiled with debug info and thread safety prior to PHP 5.3.0.

zend_extension_ts string

Variant of zend_extension for extensions compiled with thread safety prior to PHP 5.3.0.

cgi.check_shebang_line boolean

Controls whether CGI PHP checks for line starting with #! (shebang) at the top of the running script. This line might be needed if the script support running both as stand-alone script and via PHP CGI. PHP in CGI mode skips this line and ignores its content if this directive is turned on.

cgi.discard_path boolean

If this is enabled, the PHP CGI binary can safely be placed outside of the web tree and people will not be able to circumvent .htaccess security.

cgi.fix_pathinfo boolean

Provides real PATH_INFO/ PATH_TRANSLATED support for CGI. PHP's previous behaviour was to set PATH_TRANSLATED to SCRIPT_FILENAME, and to not grok what PATH_INFO is. For more information on PATH_INFO, see the CGI specs. Setting this to 1 will cause PHP CGI to fix its paths to conform to the spec. A setting of zero causes PHP to behave as before. It is turned on by default. You should fix your scripts to use SCRIPT_FILENAME rather than PATH_TRANSLATED.

cgi.force_redirect boolean

cgi.force_redirect is necessary to provide security running PHP as a CGI under most web servers. Left undefined, PHP turns this on by default. You can turn it off at your own risk.

Note:

Windows Users: When using IIS this option must be turned off. For OmniHTTPD or Xitami the same applies.

cgi.nph boolean

If cgi.nph is enabled it will force cgi to always sent Status: 200 with every request.

cgi.redirect_status_env string

If cgi.force_redirect is turned on, and you are not running under Apache or Netscape (iPlanet) web servers, you may need to set an environment variable name that PHP will look for to know it is OK to continue execution.

Note:

Setting this variable may cause security issues, know what you are doing first.

cgi.rfc2616_headers int

Tells PHP what type of headers to use when sending HTTP response code. If it's set to 0, PHP sends a » RFC 3875 "Status:" header that is supported by Apache and other web servers. When this option is set to 1, PHP will send » RFC 2616 compliant headers.

If this option is enabled, and you are running PHP in a CGI environment (e.g. PHP-FPM) you should not use standard RFC 2616 style HTTP status response headers, you should instead use their RFC 3875 equivalent e.g. instead of header("HTTP/1.0 404 Not found"); you should use header("Status: 404 Not Found");

Leave it set to 0 unless you know what you're doing.

fastcgi.impersonate string

FastCGI under IIS (on WINNT based OS) supports the ability to impersonate security tokens of the calling client. This allows IIS to define the security context that the request runs under. mod_fastcgi under Apache does not currently support this feature (03/17/2002) Set to 1 if running under IIS. Default is zero.

fastcgi.logging boolean

Turns on SAPI logging when using FastCGI. Default is to enable logging.

File Uploads

File Uploads Configuration Options
Name | Default | Changeable | Changelog
file_uploads | "1" | PHP_INI_SYSTEM |
upload_tmp_dir | NULL | PHP_INI_SYSTEM |
max_input_nesting_level | 64 | PHP_INI_PERDIR | Available since PHP 5.3.9.
max_input_vars | 1000 | PHP_INI_PERDIR | Available since PHP 5.3.9.
upload_max_filesize | "2M" | PHP_INI_PERDIR |
max_file_uploads | 20 | PHP_INI_SYSTEM | Available since PHP 5.2.12.

Here's a short explanation of the configuration directives.

file_uploads boolean

Whether or not to allow HTTP file uploads. See also the upload_max_filesize, upload_tmp_dir, and post_max_size directives.

upload_tmp_dir string

The temporary directory used for storing files when doing file upload. Must be writable by whatever user PHP is running as. If not specified PHP will use the system's default.

If the directory specified here is not writable, PHP falls back to the system default temporary directory. If open_basedir is on, then the system default directory must be allowed for an upload to succeed.

upload_max_filesize integer

The maximum size of an uploaded file.

When an integer is used, the value is measured in bytes. Shorthand notation, as described in this FAQ, may also be used.
max_file_uploads integer

The maximum number of files allowed to be uploaded simultaneously. Starting with PHP 5.3.4, upload fields left blank on submission do not count towards this limit.

General SQL

General SQL Configuration Options
Name | Default | Changeable | Changelog
sql.safe_mode | "0" | PHP_INI_SYSTEM | Removed in PHP 7.2.0

Here's a short explanation of the configuration directives.

sql.safe_mode boolean

If turned on, database connection functions that specify default values will use those values in place of any user-supplied arguments. For details on the default values, see the documentation for the relevant connection functions.

Warning

This feature has been REMOVED as of PHP 7.2.0.

Windows Specific

Windows Specific Configuration Options
Name | Default | Changeable | Changelog
windows.show_crt_warning | "0" | PHP_INI_ALL | Available since PHP 5.4.0.

Here's a short explanation of the configuration directives.

windows.show_crt_warning boolean

This directive shows the Windows CRT warnings when enabled. These warnings were displayed by default until PHP 5.4.0.


Extension List/Categorization

Table of Contents

  • Alphabetical
  • Membership
  • State

This appendix categorizes more than 150 extensions documented in the PHP Manual by several criteria.


Alphabetical

  • Apache
  • APC
  • APCu
  • APD
  • Arrays
  • BBCode
  • BC Math
  • bcompiler
  • BLENC
  • BLENC
  • Bzip2
  • Cairo
  • Calendar
  • chdb
  • Classkit
  • Classes/Objects
  • COM
  • Crack
  • CSPRNG
  • Ctype
  • CUBRID
  • cURL
  • Cyrus
  • Date/Time
  • DBA
  • dBase
  • DB++
  • dbx
  • Direct IO
  • Directories
  • DOM
  • Data Structures
  • Eio
  • Enchant
  • Error Handling
  • Ev
  • Event
  • Program execution
  • Exif
  • Expect
  • FAM
  • FANN
  • FANN
  • FrontBase
  • FDF
  • Fileinfo
  • filePro
  • Filesystem
  • Filter
  • FastCGI Process Manager
  • FriBiDi
  • FTP
  • Function Handling
  • Gearman
  • Gender
  • GeoIP
  • Gettext
  • Gmagick
  • GMP
  • GnuPG
  • Gupnp
  • haru
  • Hash
  • HRTime
  • htscanner
  • Hyperwave API
  • Firebird/InterBase
  • IBM DB2
  • iconv
  • ID3
  • Informix
  • IIS
  • GD
  • ImageMagick
  • IMAP
  • inclued
  • PHP Options/Info
  • Ingres
  • Inotify
  • intl
  • JSON
  • Judy
  • KADM5
  • KTaglib
  • Lapack
  • LDAP
  • Libevent
  • libxml
  • Lua
  • LZF
  • Mail
  • Mailparse
  • Math
  • MaxDB
  • Multibyte String
  • Mcrypt
  • MCVE
  • Memcache
  • Memcached
  • Memtrack
  • Mhash
  • Mimetype
  • Ming
  • Misc.
  • mnoGoSearch
  • Mongo
  • MongoDB\BSON
  • MongoDB\Driver
  • mqseries
  • Msession
  • mSQL
  • Mssql
  • MySQL (Original)
  • MySQLi
  • Mysqlnd
  • mysqlnd_memcache
  • mysqlnd_ms
  • mysqlnd_mux
  • mysqlnd_qc
  • mysqlnd_uh
  • Ncurses
  • Gopher
  • Network
  • Newt
  • YP/NIS
  • NSAPI
  • OAuth
  • OCI8
  • oggvorbis
  • OPcache
  • OpenAL
  • OpenSSL
  • Output Control
  • Paradox
  • Parle
  • Parsekit
  • Password Hashing
  • PCNTL
  • PCRE
  • PDF
  • PDO
  • 4D (PDO)
  • CUBRID (PDO)
  • MS SQL Server (PDO)
  • Firebird (PDO)
  • IBM (PDO)
  • Informix (PDO)
  • MySQL (PDO)
  • Oracle (PDO)
  • ODBC and DB2 (PDO)
  • PostgreSQL (PDO)
  • SQLite (PDO)
  • MS SQL Server (PDO)
  • PostgreSQL
  • Phar
  • Phdfs
  • POSIX
  • Proctitle
  • PS
  • Pspell
  • pthreads
  • Quickhash
  • Radius
  • Rar
  • Readline
  • Recode
  • Reflection
  • POSIX Regex
  • RPM Reader
  • RRD
  • runkit
  • SAM
  • SCA
  • ScoutAPM
  • scream
  • SDO
  • SDO DAS XML
  • SDO-DAS-Relational
  • Seaslog
  • Semaphore
  • Sessions
  • Session PgSQL
  • Shared Memory
  • SimpleXML
  • SNMP
  • SOAP
  • Sockets
  • Sodium
  • Solr
  • Sphinx
  • SPL
  • SPL Types
  • SQLite
  • SQLite3
  • SQLSRV
  • ssdeep
  • SSH2
  • Statistics
  • Stomp
  • Streams
  • Strings
  • SVM
  • SVN
  • Swish
  • Swoole
  • Sybase
  • Sync
  • Taint
  • TCP
  • Tidy
  • Tokenizer
  • tokyo_tyrant
  • Trader
  • UI
  • ODBC
  • uopz
  • URLs
  • V8js
  • Variable handling
  • Varnish
  • vpopmail
  • WDDX
  • Weakref
  • win32ps
  • win32service
  • WinCache
  • wkhtmltox
  • xattr
  • xdiff
  • Xhprof
  • XML Parser
  • XMLDiff
  • XMLReader
  • XML-RPC
  • XMLWriter
  • XSL
  • Yaconf
  • Yaf
  • Yaml
  • Yar
  • YAZ
  • Zip
  • Zlib
  • 0MQ messaging
  • ZooKeeper


Membership

Core Extensions

These are not actual extensions. They are part of the PHP core and cannot be left out of a PHP binary with compilation options.

  • Arrays

  • Classes/Objects

  • CSPRNG

  • Date/Time

  • Directories

  • Error Handling

  • Program execution

  • Filesystem

  • Filter

  • Function Handling

  • Hash

  • PHP Options/Info

  • Mail

  • Math

  • Misc.

  • Network

  • Output Control

  • Password Hashing

  • Phar

  • Reflection

  • POSIX Regex

  • Sessions

  • SPL

  • Streams

  • Strings

  • Tokenizer

  • URLs

  • Variable handling

Bundled Extensions

These extensions are bundled with PHP.

  • Apache

  • BC Math

  • Calendar

  • COM

  • Ctype

  • DBA

  • Exif

  • Fileinfo

  • FTP

  • iconv

  • GD

  • intl

  • JSON

  • Multibyte String

  • NSAPI

  • OPcache

  • PCNTL

  • PCRE

  • PDO

  • POSIX

  • Semaphore

  • Shared Memory

  • Sockets

  • SQLite3

  • XML-RPC

  • Zlib

External Extensions

These extensions are bundled with PHP but in order to compile them, external libraries will be needed.

  • Bzip2

  • cURL

  • dBase

  • DOM

  • Enchant

  • FrontBase

  • Gettext

  • GMP

  • Firebird/InterBase

  • Informix

  • IMAP

  • LDAP

  • libxml

  • Mcrypt

  • Mhash

  • mSQL

  • Mssql

  • MySQL (Original)

  • MySQLi

  • Mysqlnd

  • OCI8

  • OpenSSL

  • MS SQL Server (PDO)

  • Firebird (PDO)

  • MySQL (PDO)

  • Oracle (PDO)

  • ODBC and DB2 (PDO)

  • PostgreSQL (PDO)

  • SQLite (PDO)

  • PostgreSQL

  • Pspell

  • Readline

  • Recode

  • SimpleXML

  • SNMP

  • SOAP

  • Sodium

  • Sybase

  • Tidy

  • ODBC

  • WDDX

  • XML Parser

  • XMLReader

  • XMLWriter

  • XSL

  • Zip

PECL Extensions

These extensions are available from » PECL. They may require external libraries. More PECL extensions exist but they are not documented in the PHP manual yet.

  • APC

  • APD

  • BBCode

  • bcompiler

  • Cairo

  • chdb

  • Classkit

  • Crack

  • CUBRID

  • Cyrus

  • DB++

  • dbx

  • Direct IO

  • Eio

  • Ev

  • Event

  • Expect

  • FAM

  • FDF

  • filePro

  • FriBiDi

  • Gearman

  • Gender

  • GeoIP

  • Gmagick

  • GnuPG

  • Gupnp

  • haru

  • htscanner

  • Hyperwave API

  • IBM DB2

  • ID3

  • IIS

  • ImageMagick

  • inclued

  • Ingres

  • Inotify

  • Judy

  • KADM5

  • KTaglib

  • Lapack

  • Libevent

  • Lua

  • LuaSandbox

  • LZF

  • Mailparse

  • MaxDB

  • MCVE

  • Memcache

  • Memcached

  • Memtrack

  • Mimetype

  • Ming

  • mnoGoSearch

  • Mongo

  • mqseries

  • Msession

  • mysqlnd_memcache

  • mysqlnd_ms

  • mysqlnd_mux

  • mysqlnd_qc

  • mysqlnd_uh

  • Ncurses

  • Gopher

  • Newt

  • YP/NIS

  • OAuth

  • oggvorbis

  • OpenAL

  • Paradox

  • Parsekit

  • PDF

  • 4D (PDO)

  • CUBRID (PDO)

  • IBM (PDO)

  • Informix (PDO)

  • MS SQL Server (PDO)

  • Proctitle

  • PS

  • pthreads

  • Quickhash

  • Radius

  • Rar

  • RPM Reader

  • RRD

  • runkit

  • SAM

  • SCA

  • ScoutAPM

  • scream

  • SDO

  • SDO DAS XML

  • SDO-DAS-Relational

  • Seaslog

  • Session PgSQL

  • Solr

  • Sphinx

  • SPL Types

  • SQLite

  • SQLSRV

  • ssdeep

  • SSH2

  • Statistics

  • Stomp

  • Swoole

  • SVM

  • SVN

  • Swish

  • Taint

  • TCP

  • tokyo_tyrant

  • Trader

  • V8js

  • Varnish

  • vpopmail

  • Weakref

  • win32ps

  • win32service

  • WinCache

  • xattr

  • xdiff

  • Xhprof

  • Yaf

  • Yaml

  • YAZ

  • ZooKeeper


State

This part lists extensions not intended for the production use - they are either too "old" (deprecated) or "new" (experimental).

Deprecated Extensions

These extensions have been deprecated usually in the favor of some other extensions.

  • Memtrack

  • Mimetype

Experimental Extensions

The behaviour of these extensions - including the names of their functions and anything else documented about these extensions - may change without notice in a future release of PHP. Use these extensions at your own risk.

  • bcompiler

  • DB++

  • haru

  • Hash

  • ImageMagick

  • Ming

  • Ncurses

  • Newt

  • Paradox

  • MS SQL Server (PDO)

  • Firebird (PDO)

  • Oracle (PDO)

  • PS

  • SCA

  • SDO-DAS-Relational

  • Swish

  • vpopmail

  • XML-RPC


List of Function Aliases

There are quite a few functions in PHP which you can call with more than one name. In some cases there is no preferred name among the multiple ones, is_int() and is_integer() are equally good for example. However there are functions which changed names because of an API cleanup or some other reason and the old names are only kept as aliases for backward compatibility. It is usually a bad idea to use these kind of aliases, as they may be bound to obsolescence or renaming, which will lead to unportable script. This list is provided to help those who want to upgrade their old scripts to newer syntax.

Aliases
Alias | Master function | Extension used
_ | gettext() | Gettext
add | swfmovie_add() | Ming (flash)
add | swfsprite_add() | Ming (flash)
addaction | swfbutton_addAction() | Ming (flash)
addcolor | swfdisplayitem_addColor() | Ming (flash)
addentry | swfgradient_addEntry() | Ming (flash)
addfill | swfshape_addfill() | Ming (flash)
addshape | swfbutton_addShape() | Ming (flash)
addstring | swftext_addString() | Ming (flash)
addstring | swftextfield_addString() | Ming (flash)
align | swftextfield_align() | Ming (flash)
chop | rtrim() | Base syntax
close | closedir() | Base syntax
com_get | com_propget() | COM
com_propset | com_propput() | COM
com_set | com_propput() | COM
die | exit() | Miscellaneous functions
diskfreespace | disk_free_space() | Filesystem
doubleval | floatval() | Base syntax
drawarc | swfshape_drawarc() | Ming (flash)
drawcircle | swfshape_drawcircle() | Ming (flash)
drawcubic | swfshape_drawcubic() | Ming (flash)
drawcubicto | swfshape_drawcubicto() | Ming (flash)
drawcurve | swfshape_drawcurve() | Ming (flash)
drawcurveto | swfshape_drawcurveto() | Ming (flash)
drawglyph | swfshape_drawglyph() | Ming (flash)
drawline | swfshape_drawline() | Ming (flash)
drawlineto | swfshape_drawlineto() | Ming (flash)
fbsql | fbsql_db_query() | FrontBase
fputs | fwrite() | Base syntax
getascent | swffont_getAscent() | Ming (flash)
getascent | swftext_getAscent() | Ming (flash)
getdescent | swffont_getDescent() | Ming (flash)
getdescent | swftext_getDescent() | Ming (flash)
getheight | swfbitmap_getHeight() | Ming (flash)
getleading | swffont_getLeading() | Ming (flash)
getleading | swftext_getLeading() | Ming (flash)
getshape1 | swfmorph_getShape1() | Ming (flash)
getshape2 | swfmorph_getShape2() | Ming (flash)
getwidth | swfbitmap_getWidth() | Ming (flash)
getwidth | swffont_getWidth() | Ming (flash)
getwidth | swftext_getWidth() | Ming (flash)
gzputs | gzwrite() | Zlib
i18n_convert | mb_convert_encoding() | Multi-bytes Strings
i18n_discover_encoding | mb_detect_encoding() | Multi-bytes Strings
i18n_http_input | mb_http_input() | Multi-bytes Strings
i18n_http_output | mb_http_output() | Multi-bytes Strings
i18n_internal_encoding | mb_internal_encoding() | Multi-bytes Strings
i18n_ja_jp_hantozen | mb_convert_kana() | Multi-bytes Strings
i18n_mime_header_decode | mb_decode_mimeheader() | Multi-bytes Strings
i18n_mime_header_encode | mb_encode_mimeheader() | Multi-bytes Strings
imap_create | imap_createmailbox() | IMAP
imap_fetchtext | imap_body() | IMAP
imap_getmailboxes | imap_list_full() | IMAP
imap_getsubscribed | imap_lsub_full() | IMAP
imap_header | imap_headerinfo() | IMAP
imap_listmailbox | imap_list() | IMAP
imap_listsubscribed | imap_lsub() | IMAP
imap_rename | imap_renamemailbox() | IMAP
imap_scan | imap_listscan() | IMAP
imap_scanmailbox | imap_listscan() | IMAP
ini_alter | ini_set() | Base syntax
is_double | is_float() | Base syntax
is_integer | is_int() | Base syntax
is_long | is_int() | Base syntax
is_real | is_float() | Base syntax
is_writeable | is_writable() | Base syntax
join | implode() | Base syntax
key_exists | array_key_exists() | Base syntax
labelframe | swfmovie_labelFrame() | Ming (flash)
labelframe | swfsprite_labelFrame() | Ming (flash)
ldap_close | ldap_unbind() | LDAP
magic_quotes_runtime | set_magic_quotes_runtime() | Base syntax
mbstrcut | mb_strcut() | Multi-bytes Strings
mbstrlen | mb_strlen() | Multi-bytes Strings
mbstrpos | mb_strpos() | Multi-bytes Strings
mbstrrpos | mb_strrpos() | Multi-bytes Strings
mbsubstr | mb_substr() | Multi-bytes Strings
ming_setcubicthreshold | ming_setCubicThreshold() | Ming (flash)
ming_setscale | ming_setScale() | Ming (flash)
move | swfdisplayitem_move() | Ming (flash)
movepen | swfshape_movepen() | Ming (flash)
movepento | swfshape_movepento() | Ming (flash)
moveto | swfdisplayitem_moveTo() | Ming (flash)
moveto | swffill_moveTo() | Ming (flash)
moveto | swftext_moveTo() | Ming (flash)
msql | msql_db_query() | mSQL
msql_createdb | msql_create_db() | mSQL
msql_dbname | msql_result() | mSQL
msql_dropdb | msql_drop_db() | mSQL
msql_fieldflags | msql_field_flags() | mSQL
msql_fieldlen | msql_field_len() | mSQL
msql_fieldname | msql_field_name() | mSQL
msql_fieldtable | msql_field_table() | mSQL
msql_fieldtype | msql_field_type() | mSQL
msql_freeresult | msql_free_result() | mSQL
msql_listdbs | msql_list_dbs() | mSQL
msql_listfields | msql_list_fields() | mSQL
msql_listtables | msql_list_tables() | mSQL
msql_numfields | msql_num_fields() | mSQL
msql_numrows | msql_num_rows() | mSQL
msql_regcase | sql_regcase() | mSQL
msql_selectdb | msql_select_db() | mSQL
msql_tablename | msql_result() | mSQL
mssql_affected_rows | sybase_affected_rows() | Sybase
mssql_affected_rows | sybase_affected_rows() | Sybase
mssql_close | sybase_close() | Sybase
mssql_close | sybase_close() | Sybase
mssql_connect | sybase_connect() | Sybase
mssql_connect | sybase_connect() | Sybase
mssql_data_seek | sybase_data_seek() | Sybase
mssql_data_seek | sybase_data_seek() | Sybase
mssql_fetch_array | sybase_fetch_array() | Sybase
mssql_fetch_array | sybase_fetch_array() | Sybase
mssql_fetch_field | sybase_fetch_field() | Sybase
mssql_fetch_field | sybase_fetch_field() | Sybase
mssql_fetch_object | sybase_fetch_object() | Sybase
mssql_fetch_object | sybase_fetch_object() | Sybase
mssql_fetch_row | sybase_fetch_row() | Sybase
mssql_fetch_row | sybase_fetch_row() | Sybase
mssql_field_seek | sybase_field_seek() | Sybase
mssql_field_seek | sybase_field_seek() | Sybase
mssql_free_result | sybase_free_result() | Sybase
mssql_free_result | sybase_free_result() | Sybase
mssql_get_last_message | sybase_get_last_message() | Sybase
mssql_get_last_message | sybase_get_last_message() | Sybase
mssql_min_client_severity | sybase_min_client_severity() | Sybase
mssql_min_error_severity | sybase_min_error_severity() | Sybase
mssql_min_message_severity | sybase_min_message_severity() | Sybase
mssql_min_server_severity | sybase_min_server_severity() | Sybase
mssql_num_fields | sybase_num_fields() | Sybase
mssql_num_fields | sybase_num_fields() | Sybase
mssql_num_rows | sybase_num_rows() | Sybase
mssql_num_rows | sybase_num_rows() | Sybase
mssql_pconnect | sybase_pconnect() | Sybase
mssql_pconnect | sybase_pconnect() | Sybase
mssql_query | sybase_query() | Sybase
mssql_query | sybase_query() | Sybase
mssql_result | sybase_result() | Sybase
mssql_result | sybase_result() | Sybase
mssql_select_db | sybase_select_db() | Sybase
mssql_select_db | sybase_select_db() | Sybase
multcolor | swfdisplayitem_multColor() | Ming (flash)
mysql | mysql_db_query() | MySQL
mysql_createdb | mysql_create_db() | MySQL
mysql_db_name | mysql_result() | MySQL
mysql_dbname | mysql_result() | MySQL
mysql_dropdb | mysql_drop_db() | MySQL
mysql_fieldflags | mysql_field_flags() | MySQL
mysql_fieldlen | mysql_field_len() | MySQL
mysql_fieldname | mysql_field_name() | MySQL
mysql_fieldtable | mysql_field_table() | MySQL
mysql_fieldtype | mysql_field_type() | MySQL
mysql_freeresult | mysql_free_result() | MySQL
mysql_listdbs | mysql_list_dbs() | MySQL
mysql_listfields | mysql_list_fields() | MySQL
mysql_listtables | mysql_list_tables() | MySQL
mysql_numfields | mysql_num_fields() | MySQL
mysql_numrows | mysql_num_rows() | MySQL
mysql_selectdb | mysql_select_db() | MySQL
mysql_tablename | mysql_result() | MySQL
nextframe | swfmovie_nextFrame() | Ming (flash)
nextframe | swfsprite_nextFrame() | Ming (flash)
ociassignelem | OCI-Collection::assignElem | OCI8
ocibindbyname | oci_bind_by_name() | OCI8
ocicancel | oci_cancel() | OCI8
ocicloselob | OCI-Lob::close | OCI8
ocicollappend | OCI-Collection::append | OCI8
ocicollassign | OCI-Collection::assign | OCI8
ocicollmax | OCI-Collection::max | OCI8
ocicollsize | OCI-Collection::size | OCI8
ocicolltrim | OCI-Collection::trim | OCI8
ocicolumnisnull | oci_field_is_null() | OCI8
ocicolumnname | oci_field_name() | OCI8
ocicolumnprecision | oci_field_precision() | OCI8
ocicolumnscale | oci_field_scale() | OCI8
ocicolumnsize | oci_field_size() | OCI8
ocicolumntype | oci_field_type() | OCI8
ocicolumntyperaw | oci_field_type_raw() | OCI8
ocicommit | oci_commit() | OCI8
ocidefinebyname | oci_define_by_name() | OCI8
ocierror | oci_error() | OCI8
ociexecute | oci_execute() | OCI8
ocifetch | oci_fetch() | OCI8
ocifetchinto | oci_fetch_array(), oci_fetch_row(), oci_fetch_assoc(), oci_fetch_object() | OCI8
ocifetchstatement | oci_fetch_all() | OCI8
ocifreecollection | OCI-Collection::free | OCI8
ocifreecursor | oci_free_statement() | OCI8
ocifreedesc | oci_free_descriptor() | OCI8
ocifreestatement | oci_free_statement() | OCI8
ocigetelem | OCI-Collection::getElem | OCI8
ociinternaldebug | oci_internal_debug() | OCI8
ociloadlob | OCI-Lob::load | OCI8
ocilogon | oci_connect() | OCI8
ocinewcollection | oci_new_collection() | OCI8
ocinewcursor | oci_new_cursor() | OCI8
ocinewdescriptor | oci_new_descriptor() | OCI8
ocinlogon | oci_new_connect() | OCI8
ocinumcols | oci_num_fields() | OCI8
ociparse | oci_parse() | OCI8
ocipasswordchange | oci_password_change() | OCI8
ociplogon | oci_pconnect() | OCI8
ociresult | oci_result() | OCI8
ocirollback | oci_rollback() | OCI8
ocisavelob | OCI-Lob::save | OCI8
ocisavelobfile | OCI-Lob::import | OCI8
ociserverversion | oci_server_version() | OCI8
ocisetprefetch | oci_set_prefetch() | OCI8
ocistatementtype | oci_statement_type() | OCI8
ociwritelobtofile | OCI-Lob::export | OCI8
ociwritetemporarylob | OCI-Lob::writeTemporary | OCI8
odbc_do | odbc_exec() | ODBC
odbc_field_precision | odbc_field_len() | ODBC
output | swfmovie_output() | Ming (flash)
pdf_add_outline | pdf_add_bookmark() | PDF
pg_clientencoding | pg_client_encoding() | PostgreSQL
pg_setclientencoding | pg_set_client_encoding() | PostgreSQL
pos | current() | Base syntax
recode | recode_string() | Recode
remove | swfmovie_remove() | Ming (flash)
remove | swfsprite_remove() | Ming (flash)
rotate | swfdisplayitem_rotate() | Ming (flash)
rotateto | swfdisplayitem_rotateTo() | Ming (flash)
rotateto | swffill_rotateTo() | Ming (flash)
save | swfmovie_save() | Ming (flash)
savetofile | swfmovie_saveToFile() | Ming (flash)
scale | swfdisplayitem_scale() | Ming (flash)
scaleto | swfdisplayitem_scaleTo() | Ming (flash)
scaleto | swffill_scaleTo() | Ming (flash)
setaction | swfbutton_setAction() | Ming (flash)
setbackground | swfmovie_setBackground() | Ming (flash)
setbounds | swftextfield_setBounds() | Ming (flash)
setcolor | swftext_setColor() | Ming (flash)
setcolor | swftextfield_setColor() | Ming (flash)
setdepth | swfdisplayitem_setDepth() | Ming (flash)
setdimension | swfmovie_setDimension() | Ming (flash)
setdown | swfbutton_setDown() | Ming (flash)
setfont | swftext_setFont() | Ming (flash)
setfont | swftextfield_setFont() | Ming (flash)
setframes | swfmovie_setFrames() | Ming (flash)
setframes | swfsprite_setFrames() | Ming (flash)
setheight | swftext_setHeight() | Ming (flash)
setheight | swftextfield_setHeight() | Ming (flash)
sethit | swfbutton_setHit() | Ming (flash)
setindentation | swftextfield_setIndentation() | Ming (flash)
setleftfill | swfshape_setleftfill() | Ming (flash)
setleftmargin | swftextfield_setLeftMargin() | Ming (flash)
setline | swfshape_setline() | Ming (flash)
setlinespacing | swftextfield_setLineSpacing() | Ming (flash)
setmargins | swftextfield_setMargins() | Ming (flash)
setmatrix | swfdisplayitem_setMatrix() | Ming (flash)
setname | swfdisplayitem_setName() | Ming (flash)
setname | swftextfield_setName() | Ming (flash)
setover | swfbutton_setOver() | Ming (flash)
setrate | swfmovie_setRate() | Ming (flash)
setratio | swfdisplayitem_setRatio() | Ming (flash)
setrightfill | swfshape_setrightfill() | Ming (flash)
setrightmargin | swftextfield_setRightMargin() | Ming (flash)
setspacing | swftext_setSpacing() | Ming (flash)
setup | swfbutton_setUp() | Ming (flash)
show_source | highlight_file() | Base syntax
sizeof | count() | Base syntax
skewx | swfdisplayitem_skewX() | Ming (flash)
skewxto | swfdisplayitem_skewXTo() | Ming (flash)
skewxto | swffill_skewXTo() | Ming (flash)
skewy | swfdisplayitem_skewY() | Ming (flash)
skewyto | swfdisplayitem_skewYTo() | Ming (flash)
skewyto | swffill_skewYTo() | Ming (flash)
snmpwalkoid | snmprealwalk() | SNMP
strchr | strstr() | Base syntax
streammp3 | swfmovie_streamMp3() | Ming (flash)
swfaction | swfaction_init() | Ming (flash)
swfbitmap | swfbitmap_init() | Ming (flash)
swfbutton | swfbutton_init() | Ming (flash)
swffill | swffill_init() | Ming (flash)
swffont | swffont_init() | Ming (flash)
swfgradient | swfgradient_init() | Ming (flash)
swfmorph | swfmorph_init() | Ming (flash)
swfmovie | swfmovie_init() | Ming (flash)
swfshape | swfshape_init() | Ming (flash)
swfsprite | swfsprite_init() | Ming (flash)
swftext | swftext_init() | Ming (flash)
swftextfield | swftextfield_init() | Ming (flash)
xptr_new_context | xpath_new_context() |


List of Reserved Words

Table of Contents

  • List of Keywords
  • Predefined Classes
  • Predefined Constants
  • List of other reserved words

The following is a listing of predefined identifiers in PHP. None of the identifiers listed here should be used as identifiers in any of your scripts unless explicitly noted otherwise. These lists include keywords and predefined variables, constant, and class names. These lists are neither exhaustive nor complete.


List of Keywords

These words have special meaning in PHP. Some of them represent things which look like functions, some look like constants, and so on - but they're not, really: they are language constructs. You cannot use any of the following words as constants, class names, function or method names. Using them as variable names is generally OK, but could lead to confusion.

As of PHP 7.0.0 these keywords are allowed as property, constant, and method names of classes, interfaces and traits, except that class may not be used as constant name.

PHP Keywords
__halt_compiler() | abstract | and | array() | as
break | callable (as of PHP 5.4) | case | catch | class
clone | const | continue | declare | default
die() | do | echo | else | elseif
empty() | enddeclare | endfor | endforeach | endif
endswitch | endwhile | eval() | exit() | extends
final | finally (as of PHP 5.5) | for | foreach | function
global | goto (as of PHP 5.3) | if | implements | include
include_once | instanceof | insteadof (as of PHP 5.4) | interface | isset()
list() | namespace (as of PHP 5.3) | new | or | print
private | protected | public | require | require_once
return | static | switch | throw | trait (as of PHP 5.4)
try | unset() | use | var | while
xor | yield (as of PHP 5.5) | yield from (as of PHP 7.0) |  |
Compile-time constants
__CLASS__ | __DIR__ (as of PHP 5.3) | __FILE__ | __FUNCTION__ | __LINE__ | __METHOD__
__NAMESPACE__ (as of PHP 5.3) | __TRAIT__ (as of PHP 5.4) |  |  |  |


Predefined Classes

This section lists standard predefined classes. Miscellaneous extensions define other classes which are described in their reference.

Standard Defined Classes

These classes are defined in the standard set of functions included in the PHP build.

Directory
Created by dir().
stdClass
Created by typecasting to object.
__PHP_Incomplete_Class
Possibly created by unserialize().

Predefined classes as of PHP 5

These additional predefined classes were introduced in PHP 5.0.0.

Exception
ErrorException
Available since PHP 5.1.0.
php_user_filter

Closure

The predefined final class Closure was introduced in PHP 5.3.0. It is used for representing anonymous functions.

For more information, see its class page.

Generator

The predefined final class Generator was introduced in PHP 5.5.0. It is used for representing generators.

For more information, see its class page.

Predefined interfaces and classes as of PHP 7

These additional predefined interfaces and classes were introduced in PHP 7.0.0.

ArithmeticError
AssertionError
DivisionByZeroError
Error
Throwable
ParseError
TypeError

Special classes

Following identifiers may not be used as a class name as they have special purpose.

self
Current class.
static
Current class in runtime.
parent
Parent class.


Predefined Constants

Core Predefined Constants

These constants are defined by the PHP core. This includes PHP, the Zend engine, and SAPI modules.

PHP_VERSION (string)
The current PHP version as a string in "major.minor.release[extra]" notation.
PHP_MAJOR_VERSION (integer)
The current PHP "major" version as an integer (e.g., int(5) from version "5.2.7-extra"). Available since PHP 5.2.7.
PHP_MINOR_VERSION (integer)
The current PHP "minor" version as an integer (e.g., int(2) from version "5.2.7-extra"). Available since PHP 5.2.7.
PHP_RELEASE_VERSION (integer)
The current PHP "release" version as an integer (e.g., int(7) from version "5.2.7-extra"). Available since PHP 5.2.7.
PHP_VERSION_ID (integer)
The current PHP version as an integer, useful for version comparisons (e.g., int(50207) from version "5.2.7-extra"). Available since PHP 5.2.7.
PHP_EXTRA_VERSION (string)
The current PHP "extra" version as a string (e.g., '-extra' from version "5.2.7-extra"). Often used by distribution vendors to indicate a package version. Available since PHP 5.2.7.
PHP_ZTS (integer)
Available since PHP 5.2.7.
PHP_DEBUG (integer)
Available since PHP 5.2.7.
PHP_MAXPATHLEN (integer)
The maximum length of filenames (including path) supported by this build of PHP. Available since PHP 5.3.0.
PHP_OS (string)
The operating system PHP was built for.
PHP_OS_FAMILY (string)
The operating system family PHP was built for. One of 'Windows', 'BSD', 'Darwin', 'Solaris', 'Linux' or 'Unknown'. Available as of PHP 7.2.0.
PHP_SAPI (string)
The Server API for this build of PHP. See also php_sapi_name().
PHP_EOL (string)
The correct 'End Of Line' symbol for this platform. Available since PHP 5.0.2
PHP_INT_MAX (integer)
The largest integer supported in this build of PHP. Usually int(2147483647) in 32 bit systems and int(9223372036854775807) in 64 bit systems. Available since PHP 5.0.5
PHP_INT_MIN (integer)
The smallest integer supported in this build of PHP. Usually int(-2147483648) in 32 bit systems and int(-9223372036854775808) in 64 bit systems. Available since PHP 7.0.0. Usually, PHP_INT_MIN === ~PHP_INT_MAX.
PHP_INT_SIZE (integer)
The size of an integer in bytes in this build of PHP. Available since PHP 5.0.5
PHP_FLOAT_DIG (integer)
Number of decimal digits that can be rounded into a float and back without precision loss. Available as of PHP 7.2.0.
PHP_FLOAT_EPSILON (float)
Smallest representable positive number x, so that x + 1.0 != 1.0. Available as of PHP 7.2.0.
PHP_FLOAT_MIN (float)
Smallest representable positive floating point number. If you need the smallest representable negative floating point number, use - PHP_FLOAT_MAX. Available as of PHP 7.2.0.
PHP_FLOAT_MAX (float)
Largest representable floating point number. Available as of PHP 7.2.0.
DEFAULT_INCLUDE_PATH (string)
PEAR_INSTALL_DIR (string)
PEAR_EXTENSION_DIR (string)
PHP_EXTENSION_DIR (string)
PHP_PREFIX (string)
The value "--prefix" was set to at configure.
PHP_BINDIR (string)
Specifies where the binaries were installed into.
PHP_BINARY (string)
Specifies the PHP binary path during script execution. Available since PHP 5.4.
PHP_MANDIR (string)
Specifies where the manpages were installed into. Available since PHP 5.3.7.
PHP_LIBDIR (string)
PHP_DATADIR (string)
PHP_SYSCONFDIR (string)
PHP_LOCALSTATEDIR (string)
PHP_CONFIG_FILE_PATH (string)
PHP_CONFIG_FILE_SCAN_DIR (string)
PHP_SHLIB_SUFFIX (string)
The build-platform's shared library suffix, such as "so" (most Unixes) or "dll" (Windows).
PHP_FD_SETSIZE (string)
The maximum number of file descriptors for select system calls. Available as of PHP 7.1.0.
E_ERROR (integer)
Error reporting constant
E_WARNING (integer)
Error reporting constant
E_PARSE (integer)
Error reporting constant
E_NOTICE (integer)
Error reporting constant
E_CORE_ERROR (integer)
Error reporting constant
E_CORE_WARNING (integer)
Error reporting constant
E_COMPILE_ERROR (integer)
Error reporting constant
E_COMPILE_WARNING (integer)
Error reporting constant
E_USER_ERROR (integer)
Error reporting constant
E_USER_WARNING (integer)
Error reporting constant
E_USER_NOTICE (integer)
Error reporting constant
E_RECOVERABLE_ERROR (integer)
Error reporting constant. Available since PHP 5.2.0
E_DEPRECATED (integer)
Error reporting constant. Available since PHP 5.3.0
E_USER_DEPRECATED (integer)
Error reporting constant. Available since PHP 5.3.0
E_ALL (integer)
Error reporting constant
E_STRICT (integer)
Error reporting constant
__COMPILER_HALT_OFFSET__ (integer)
Available since PHP 5.1.0
TRUE (boolean)
See Booleans.
FALSE (boolean)
See Booleans.
NULL (null)
See Null.
PHP_WINDOWS_EVENT_CTRL_C (integer)
A Windows CTRL+C event. Available as of PHP 7.4.0 (Windows only).
PHP_WINDOWS_EVENT_CTRL_BREAK (integer)
A Windows CTRL+BREAK event. Available as of PHP 7.4.0 (Windows only).

See also: Magic constants.

Standard Predefined Constants

All constants from core extensions are defined in PHP by default.


List of other reserved words

The following words cannot be used to name a class, interface or trait, and they are also prohibited from being used in namespaces.

Reserved words
int (as of PHP 7) | float (as of PHP 7) | bool (as of PHP 7) | string (as of PHP 7)
true (as of PHP 7) | false (as of PHP 7) | null (as of PHP 7) | void (as of PHP 7.1)
iterable (as of PHP 7.1) | object (as of PHP 7.2)

The following list of words have had soft reservations placed on them. Whilst they may still be used as class, interface, and trait names (as well as in namespaces), usage of them is highly discouraged since they may be used in future versions of PHP.

Soft reserved words
resource (as of PHP 7) mixed (as of PHP 7) numeric (as of PHP 7)


List of Resource Types

The following is a list of functions which create, use or destroy PHP resources. The function is_resource() can be used to determine if a variable is a resource and get_resource_type() will return the type of resource it is.

Resource Types
Resource Type Name | Created By | Used By | Destroyed By | Definition
bzip2 | bzopen() | bzerrno(), bzerror(), bzerrstr(), bzflush(), bzread(), bzwrite() | bzclose() | Bzip2 file
cubrid connection | cubrid_connect() cubrid_connect_with_url() | cubrid_col_get() cubrid_col_size() cubrid_commit() cubrid_drop() cubrid_execute() cubrid_get_autocommit() cubrid_get_charset() cubrid_get_class_name() cubrid_get_db_parameter() cubrid_get_server_info() cubrid_get() cubrid_insert_id() cubrid_is_instance() cubrid_lob_export() cubrid_lob_get() cubrid_lob_send() cubrid_lock_read() cubrid_lock_write() cubrid_prepare() cubrid_put() cubrid_rollback() cubrid_schema() cubrid_seq_drop() cubrid_seq_insert() cubrid_seq_put() cubrid_set_add() cubrid_set_autocommit() cubrid_set_db_parameter() cubrid_set_drop() cubrid_affected_rows() cubrid_client_encoding() cubrid_errno() cubrid_error() cubrid_list_dbs() cubrid_ping() cubrid_query() cubrid_real_escape_string() | cubrid_close() cubrid_disconnect() | Connection to CUBRID database
persistent cubrid connection | cubrid_pconnect() cubrid_pconnect_with_url() | cubrid_col_get() cubrid_col_size() cubrid_commit() cubrid_drop() cubrid_execute() cubrid_get_autocommit() cubrid_get_charset() cubrid_get_class_name() cubrid_get_db_parameter() cubrid_get_server_info() cubrid_get() cubrid_insert_id() cubrid_is_instance() cubrid_lob_export() cubrid_lob_get() cubrid_lob_send() cubrid_lock_read() cubrid_lock_write() cubrid_prepare() cubrid_put() cubrid_rollback() cubrid_schema() cubrid_seq_drop() cubrid_seq_insert() cubrid_seq_put() cubrid_set_add() cubrid_set_autocommit() cubrid_set_db_parameter() cubrid_set_drop() cubrid_affected_rows() cubrid_client_encoding() cubrid_errno() cubrid_error() cubrid_list_dbs() cubrid_ping() cubrid_query() cubrid_real_escape_string() cubrid_lob2_new() | Persistent connection to CUBRID database
cubrid request | cubrid_prepare() cubrid_execute() cubrid_query() cubrid_unbuffered_query() | cubrid_bind() cubrid_column_names() cubrid_column_types() cubrid_current_oid() cubrid_execute() cubrid_free_result() cubrid_get_query_timeout() cubrid_move_cursor() cubrid_next_result() cubrid_num_cols() cubrid_num_rows() cubrid_set_query_timeout() cubrid_data_seek() cubrid_fetch_array() cubrid_fetch_assoc() cubrid_fetch_field() cubrid_fetch_lengths() cubrid_fetch_object() cubrid_fetch_row() cubrid_field_flags() cubrid_field_len() cubrid_field_name() cubrid_field_seek() cubrid_field_table() cubrid_field_type() cubrid_num_fields() cubrid_result() cubrid_lob2_bind() | cubrid_close_prepare() cubrid_close_request() | CUBRID request
cubrid lob | cubrid_lob_get() | cubrid_lob_export() cubrid_lob_send() cubrid_lob_size() | cubrid_lob_close() | None
cubrid lob2 | cubrid_lob2_new() cubrid_fetch() cubrid_fetch_row() cubrid_fetch_array() cubrid_fetch_assoc() cubrid_fetch_object() | cubrid_lob2_export() cubrid_lob2_import() cubrid_lob2_read() cubrid_lob2_write() cubrid_lob2_tell() cubrid_lob2_tell64() cubrid_lob2_seek() cubrid_lob2_seek64() cubrid_lob2_size() cubrid_lob2_size64() | cubrid_lob2_close() | None
curl | curl_copy_handle(), curl_init() | curl_copy_handle(), curl_errno(), curl_error(), curl_exec(), curl_getinfo(), curl_setopt() | curl_close() | Curl session
dba | dba_open() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | dba_close() | Link to DBA database
dba persistent | dba_popen() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | None | Persistent link to DBA database
dbase | dbase_open() | dbase_pack(), dbase_add_record(), dbase_replace_record(), dbase_delete_record(), dbase_get_record(), dbase_get_record_with_names(), dbase_numfields(), dbase_numrecords() | dbase_close() | Link to Dbase database
dbx_link_object | dbx_connect() | dbx_query() | dbx_close() | dbx connection
dbx_result_object | dbx_query() | None | dbx result
xpath context
xpath object
fbsql link | fbsql_change_user(), fbsql_connect() | fbsql_autocommit(), fbsql_blob_size(), fbsql_clob_size(), fbsql_commit(), fbsql_change_user(), fbsql_create_blob(), fbsql_create_db(), fbsql_create_clob(), fbsql_data_seek(), fbsql_database_password(), fbsql_database(), fbsql_db_query(), fbsql_db_status(), fbsql_drop_db(), fbsql_errno(), fbsql_error(), fbsql_get_autostart_info(), fbsql_hostname(), fbsql_insert_id(), fbsql_list_dbs(), fbsql_password(), fbsql_read_blob(), fbsql_read_clob(), fbsql_rollback(), fbsql_select_db(), fbsql_set_password(), fbsql_set_transaction(), fbsql_start_db(), fbsql_stop_db(), fbsql_username() | fbsql_close() | Link to fbsql database
fbsql plink | fbsql_change_user(), fbsql_pconnect() | fbsql_autocommit(), fbsql_change_user(), fbsql_create_db(), fbsql_data_seek(), fbsql_db_query(), fbsql_drop_db(), fbsql_select_db(), fbsql_errno(), fbsql_error(), fbsql_insert_id(), fbsql_list_dbs() | None | Persistent link to fbsql database
fbsql result | fbsql_db_query(), fbsql_list_dbs(), fbsql_query(), fbsql_list_fields(), fbsql_list_tables(), fbsql_tablename() | fbsql_affected_rows(), fbsql_fetch_array(), fbsql_fetch_assoc(), fbsql_fetch_field(), fbsql_fetch_lengths(), fbsql_fetch_object(), fbsql_fetch_row(), fbsql_field_flags(), fbsql_field_name(), fbsql_field_len(), fbsql_field_seek(), fbsql_field_table(), fbsql_field_type(), fbsql_next_result(), fbsql_num_fields(), fbsql_num_rows(), fbsql_result(), fbsql_num_rows() | fbsql_free_result() | fbsql result
fdf | fdf_open() | fdf_create(), fdf_save(), fdf_get_value(), fdf_set_value(), fdf_next_field_name(), fdf_set_ap(), fdf_set_status(), fdf_get_status(), fdf_set_file(), fdf_get_file(), fdf_set_flags(), fdf_set_opt(), fdf_set_submit_form_action(), fdf_set_javascript_action() | fdf_close() | FDF File
ftp | ftp_connect(), ftp_ssl_connect() | ftp_login(), ftp_pwd(), ftp_cdup(), ftp_chdir(), ftp_mkdir(), ftp_rmdir(), ftp_nlist(), ftp_rawlist(), ftp_systype(), ftp_pasv(), ftp_get(), ftp_fget(), ftp_put(), ftp_fput(), ftp_size(), ftp_mdtm(), ftp_rename(), ftp_delete(), ftp_site(), ftp_alloc(), ftp_chmod(), ftp_exec(), ftp_get_option(), ftp_nb_continue(), ftp_nb_fget(), ftp_nb_fput(), ftp_nb_get(), ftp_nb_put(), ftp_raw(), ftp_set_option() | ftp_close() | FTP stream
gd | imagecreate(), imagecreatefromgd(), imagecreatefromgd2(), imagecreatefromgd2part(), imagecreatefromgif(), imagecreatefromjpeg(), imagecreatefrompng(), imagecreatefromwbmp(), imagecreatefromstring(), imagecreatefromxbm(), imagecreatefromxpm(), imagecreatetruecolor(), imagerotate() | imagearc(), imagechar(), imagecharup(), imagecolorallocate(), imagecolorat(), imagecolorclosest(), imagecolorexact(), imagecolorresolve(), imagegammacorrect(), imagegammacorrect(), imagecolorset(), imagecolorsforindex(), imagecolorstotal(), imagecolortransparent(), imagecopy(), imagecopyresized(), imagedashedline(), imagefill(), imagefilledpolygon(), imagefilledrectangle(), imagefilltoborder(), imagegif(), imagepng(), imagejpeg(), imagewbmp(), imageinterlace(), imageline(), imagepolygon(), imagepstext(), imagerectangle(), imagerotate(), imagesetpixel(), imagestring(), imagestringup(), imagesx(), imagesy(), imagettftext(), imagefilledarc(), imageellipse(), imagefilledellipse(), imagecolorclosestalpha(), imagecolorexactalpha(), imagecolorresolvealpha(), imagecopymerge(), imagecopymergegray(), imagecopyresampled(), imagetruecolortopalette(), imagesetbrush(), imagesettile(), imagesetthickness(), image2wbmp(), imagealphablending(), imageantialias(), imagecolorallocatealpha(), imagecolorclosesthwb(), imagecolordeallocate(), imagecolormatch(), imagefilter(), imagefttext(), imagegd(), imagegd2(), imageistruecolor(), imagelayereffect(), imagepalettecopy(), imagesavealpha(), imagesetstyle(), imagexbm() | imagedestroy() | GD Image
gd font | imageloadfont() | imagechar(), imagecharup(), imagefontheight() | None | Font for GD
gd PS encoding
gd PS font | imagepsloadfont() | imagepstext(), imagepsslantfont(), imagepsextendfont(), imagepsencodefont(), imagepsbbox() | imagepsfreefont() | PS font for GD
GMP integer | gmp_init() | gmp_intval(), gmp_strval(), gmp_add(), gmp_sub(), gmp_mul(), gmp_div_q(), gmp_div_r(), gmp_div_qr(), gmp_div(), gmp_mod(), gmp_divexact(), gmp_cmp(), gmp_neg(), gmp_abs(), gmp_sign(), gmp_fact(), gmp_sqrt(), gmp_sqrtrm(), gmp_perfect_square(), gmp_pow(), gmp_powm(), gmp_prob_prime(), gmp_gcd(), gmp_gcdext(), gmp_invert(), gmp_legendre(), gmp_jacobi(), gmp_random(), gmp_and(), gmp_or(), gmp_xor(), gmp_setbit(), gmp_clrbit(), gmp_scan0(), gmp_scan1(), gmp_popcount(), gmp_hamdist() | None | GMP Number
imap | imap_open() | imap_append(), imap_body(), imap_check(), imap_createmailbox(), imap_delete(), imap_deletemailbox(), imap_expunge(), imap_fetchbody(), imap_fetchstructure(), imap_headerinfo(), imap_header(), imap_headers(), imap_listmailbox(), imap_getmailboxes(), imap_get_quota(), imap_status(), imap_listsubscribed(), imap_set_quota(), imap_set_quota(), imap_getsubscribed(), imap_mail_copy(), imap_mail_move(), imap_num_msg(), imap_num_recent(), imap_ping(), imap_renamemailbox(), imap_reopen(), imap_subscribe(), imap_undelete(), imap_unsubscribe(), imap_scanmailbox(), imap_mailboxmsginfo(), imap_fetchheader(), imap_uid(), imap_msgno(), imap_search(), imap_fetch_overview() | imap_close() | Link to IMAP, POP3 server
ingres | ingres_connect() | ingres_query(), ingres_num_rows(), ingres_num_fields(), ingres_field_name(), ingres_field_type(), ingres_field_nullable(), ingres_field_length(), ingres_field_precision(), ingres_field_scale(), ingres_fetch_array(), ingres_fetch_row(), ingres_fetch_object(), ingres_rollback(), ingres_commit(), ingres_autocommit() | ingres_close() | Link to ingresII base
ingres persistent | ingres_pconnect() | ingres_query(), ingres_num_rows(), ingres_num_fields(), ingres_field_name(), ingres_field_type(), ingres_field_nullable(), ingres_field_length(), ingres_field_precision(), ingres_field_scale(), ingres_fetch_array(), ingres_fetch_row(), ingres_fetch_object(), ingres_rollback(), ingres_commit(), ingres_autocommit() | None | Persistent link to ingresII base
interbase blob
interbase link | ibase_connect() | ibase_query(), ibase_prepare(), ibase_trans() | ibase_close() | Link to Interbase database
interbase link persistent | ibase_pconnect() | ibase_query(), ibase_prepare(), ibase_trans() | None | Persistent link to Interbase database
interbase query | ibase_prepare() | ibase_execute() | ibase_free_query() | Interbase query
interbase result | ibase_query() | ibase_fetch_row(), ibase_fetch_object(), ibase_field_info(), ibase_num_fields() | ibase_free_result() | Interbase Result
interbase transaction | ibase_trans() | ibase_commit() | ibase_rollback() | Interbase transaction
ldap link | ldap_connect(), ldap_search() | ldap_count_entries(), ldap_first_attribute(), ldap_first_entry(), ldap_get_attributes(), ldap_get_dn(), ldap_get_entries(), ldap_get_values(), ldap_get_values_len(), ldap_next_attribute(), ldap_next_entry() | ldap_close() | ldap connection
ldap result | ldap_read() | ldap_add(), ldap_compare(), ldap_bind(), ldap_count_entries(), ldap_delete(), ldap_errno(), ldap_error(), ldap_first_attribute(), ldap_first_entry(), ldap_get_attributes(), ldap_get_dn(), ldap_get_entries(), ldap_get_values(), ldap_get_values_len(), ldap_get_option(), ldap_list(), ldap_modify(), ldap_mod_add(), ldap_mod_replace(), ldap_next_attribute(), ldap_next_entry(), ldap_mod_del(), ldap_set_option(), ldap_unbind() | ldap_free_result() | ldap search result
ldap result entry
SWFAction
SWFBitmap
SWFButton
SWFDisplayItem
SWFFill
SWFFont
SWFGradient
SWFMorph
SWFMovie
SWFShape
SWFSprite
SWFText
SWFTextField
mnogosearch agent
mnogosearch result
msql link | msql_connect() | msql(), msql_create_db(), msql_createdb(), msql_drop_db(), msql_drop_db(), msql_select_db(), msql_select_db() | msql_close() | Link to mSQL database
msql link persistent | msql_pconnect() | msql(), msql_create_db(), msql_createdb(), msql_drop_db(), msql_drop_db(), msql_select_db(), msql_select_db() | None | Persistent link to mSQL
msql query | msql_db_query(), msql_list_dbs(), msql_list_fields(), msql_list_tables(), msql_query() | msql(), msql_affected_rows(), msql_data_seek(), msql_dbname(), msql_fetch_array(), msql_fetch_field(), msql_fetch_object(), msql_fetch_row(), msql_field_seek(), msql_field_table(), msql_field_flags(), msql_field_len(), msql_field_name(), msql_field_type(), msql_num_fields(), msql_num_rows(), msql_numfields(), msql_numrows(), msql_result() | msql_free_result(), msql_free_result() | mSQL result
mssql link | mssql_connect() | mssql_query(), mssql_select_db() | mssql_close() | Link to Microsoft SQL Server database
mssql link persistent | mssql_pconnect() | mssql_query(), mssql_select_db() | None | Persistent link to Microsoft SQL Server
mssql result | mssql_query() | mssql_data_seek(), mssql_fetch_array(), mssql_fetch_field(), mssql_fetch_object(), mssql_fetch_row(), mssql_field_length(), mssql_field_name(), mssql_field_seek(), mssql_field_type(), mssql_num_fields(), mssql_num_rows(), mssql_result() | mssql_free_result() | Microsoft SQL Server result
mysql link | mysql_connect() | mysql_affected_rows(), mysql_change_user(), mysql_create_db(), mysql_data_seek(), mysql_db_name(), mysql_db_query(), mysql_drop_db(), mysql_errno(), mysql_error(), mysql_insert_id(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query(), mysql_result(), mysql_select_db(), mysql_tablename(), mysql_get_host_info(), mysql_get_proto_info(), mysql_get_server_info() | mysql_close() | Link to MySQL database
mysql link persistent | mysql_pconnect() | mysql_affected_rows(), mysql_change_user(), mysql_create_db(), mysql_data_seek(), mysql_db_name(), mysql_db_query(), mysql_drop_db(), mysql_errno(), mysql_error(), mysql_insert_id(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query(), mysql_result(), mysql_select_db(), mysql_tablename(), mysql_get_host_info(), mysql_get_proto_info(), mysql_get_server_info() | None | Persistent link to MySQL database
mysql result | mysql_db_query(), mysql_list_dbs(), mysql_list_fields(), mysql_list_processes(), mysql_list_tables(), mysql_query(), mysql_unbuffered_query() | mysql_data_seek(), mysql_db_name(), mysql_fetch_array(), mysql_fetch_assoc(), mysql_fetch_field(), mysql_fetch_lengths(), mysql_fetch_object(), mysql_fetch_row(), mysql_fetch_row(), mysql_field_flags(), mysql_field_name(), mysql_field_len(), mysql_field_seek(), mysql_field_table(), mysql_field_type(), mysql_num_fields(), mysql_num_rows(), mysql_result(), mysql_tablename() | mysql_free_result() | MySQL result
oci8 collection | oci_new_collection() | OCI-Collection::append(), OCI-Collection::assign(), OCI-Collection::assignElem(), OCI-Collection::getElem(), OCI-Collection::max(), OCI-Collection::size(), OCI-Collection::trim() | OCI-Collection::free() | Oracle Collection
oci8 connection | oci_connect(), oci_pconnect(), oci_new_connect() | oci_commit(), oci_error(), oci_new_cursor(), oci_parse(), oci_password_change(), oci_rollback(), oci_server_version(), oci_set_action(), oci_set_client_identifier(), oci_set_client_info(), oci_set_module_name() | oci_close() | Connection to Oracle Database
oci8 lob | oci_new_descriptor() | OCI-Lob::append(), OCI-Lob::close(), OCI-Lob::eof(), OCI-Lob::erase(), OCI-Lob::export(), OCI-Lob::flush(), OCI-Lob::getBuffering(), OCI-Lob::import(), OCI-Lob::load(), OCI-Lob::read(), OCI-Lob::rewind(), OCI-Lob::save(), OCI-Lob::saveFile(), OCI-Lob::seek(), OCI-Lob::setBuffering(), OCI-Lob::size(), OCI-Lob::tell(), OCI-Lob::truncate(), OCI-Lob::write(), OCI-Lob::writeTemporary(), OCI-Lob::writeToFile(), oci_lob_copy(), oci_lob_is_equal() | OCI-Lob::free() | Oracle large objects
oci8 statement | oci_parse(), oci_new_cursor() | oci_bind_array_by_name(), oci_bind_by_name(), oci_cancel(), oci_define_by_name(), oci_error() oci_execute(), oci_fetch_all(), oci_fetch_array(), oci_fetch_assoc(), oci_fetch_object(), oci_fetch_row(), oci_fetch(), oci_field_is_null(), oci_field_name(), oci_field_precision(), oci_field_scale(), oci_field_size(), oci_field_type_raw(), oci_field_type(), oci_num_fields(), oci_num_rows(), oci_result(), oci_set_prefetch(), oci_statement_type() | oci_free_statement() | Oracle cursor
odbc link | odbc_connect() | odbc_autocommit(), odbc_commit(), odbc_error(), odbc_errormsg(), odbc_exec(), odbc_tables(), odbc_tableprivileges(), odbc_do(), odbc_prepare(), odbc_columns(), odbc_columnprivileges(), odbc_procedurecolumns(), odbc_specialcolumns(), odbc_rollback(), odbc_setoption(), odbc_gettypeinfo(), odbc_primarykeys(), odbc_foreignkeys(), odbc_procedures(), odbc_statistics() | odbc_close() | Link to ODBC database
odbc link persistent | odbc_pconnect() | odbc_autocommit(), odbc_commit(), odbc_error(), odbc_errormsg(), odbc_exec(), odbc_tables(), odbc_tableprivileges(), odbc_do(), odbc_prepare(), odbc_columns(), odbc_columnprivileges(), odbc_procedurecolumns(), odbc_specialcolumns(), odbc_rollback(), odbc_setoption(), odbc_gettypeinfo(), odbc_primarykeys(), odbc_foreignkeys(), odbc_procedures(), odbc_statistics() | None | Persistent link to ODBC database
odbc result | odbc_prepare() | odbc_binmode(), odbc_cursor(), odbc_execute(), odbc_fetch_into(), odbc_fetch_row(), odbc_field_name(), odbc_field_num(), odbc_field_type(), odbc_field_len(), odbc_field_precision(), odbc_field_scale(), odbc_longreadlen(), odbc_num_fields(), odbc_num_rows(), odbc_result(), odbc_result_all(), odbc_setoption() | odbc_free_result() | ODBC result
birdstep link
birdstep result
OpenSSL key | openssl_get_privatekey(), openssl_get_publickey() | openssl_sign(), openssl_seal(), openssl_open(), openssl_verify() | openssl_free_key() | OpenSSL key
OpenSSL X.509 | openssl_x509_read() | openssl_x509_parse(), openssl_x509_checkpurpose() | openssl_x509_free() | Public Key
pdf document | pdf_new() | pdf_add_bookmark(), pdf_add_launchlink(), pdf_add_locallink(), pdf_add_note(), pdf_add_pdflink(), pdf_add_weblink(), pdf_arc(), pdf_attach_file(), pdf_begin_page(), pdf_circle(), pdf_clip(), pdf_closepath(), pdf_closepath_fill_stroke(), pdf_closepath_stroke(), pdf_concat(), pdf_continue_text(), pdf_curveto(), pdf_end_page(), pdf_endpath(), pdf_fill(), pdf_fill_stroke(), pdf_findfont(), pdf_get_buffer(), pdf_get_image_height(), pdf_get_image_width(), pdf_get_parameter(), pdf_get_value(), pdf_lineto(), pdf_moveto(), pdf_open_ccitt(), pdf_open_file(), pdf_open_image_file(), pdf_place_image(), pdf_rect(), pdf_restore(), pdf_rotate(), pdf_save(), pdf_scale(), pdf_setdash(), pdf_setflat(), pdf_setfont(), pdf_setgray(), pdf_setgray_fill(), pdf_setgray_stroke(), pdf_setlinecap(), pdf_setlinejoin(), pdf_setlinewidth(), pdf_setmiterlimit(), pdf_setpolydash(), pdf_setrgbcolor(), pdf_setrgbcolor_fill(), pdf_setrgbcolor_stroke(), pdf_set_border_color(), pdf_set_border_dash(), pdf_set_border_style(), pdf_set_char_spacing(), pdf_set_duration(), pdf_set_font(), pdf_set_horiz_scaling(), pdf_set_parameter(), pdf_set_text_pos(), pdf_set_text_rendering(), pdf_set_value(), pdf_set_word_spacing(), pdf_show(), pdf_show_boxed(), pdf_show_xy(), pdf_skew(), pdf_stringwidth(), pdf_stroke(), pdf_translate(), pdf_add_thumbnail(), pdf_arcn(), pdf_begin_pattern(), pdf_begin_template(), pdf_end_pattern(), pdf_end_template(), pdf_initgraphics(), pdf_makespotcolor(), pdf_set_info(), pdf_setcolor(), pdf_setmatrix(), pdf_open_memory_image() | pdf_close(), pdf_delete() | PDF document
pdf image | pdf_open_image(), pdf_open_image_file(), pdf_open_memory_image() | pdf_get_image_height(), pdf_get_image_width(), pdf_open_CCITT(), pdf_place_image() | pdf_close_image() | Image in PDF file
pdf object
pdf outline
pgsql large object | pg_lo_open() | pg_lo_open(), pg_lo_create(), pg_lo_read(), pg_lo_read_all(), pg_lo_seek(), pg_lo_tell(), pg_lo_unlink(), pg_lo_write() | pg_lo_close() | PostgreSQL Large Object
pgsql link | pg_connect() | pg_affected_rows(), pg_query(), pg_send_query(), pg_get_result(), pg_connection_busy(), pg_connection_reset(), pg_connection_status(), pg_last_error(), pg_last_notice(), pg_lo_create(), pg_lo_export(), pg_lo_import(), pg_lo_open(), pg_lo_unlink(), pg_host(), pg_port(), pg_dbname(), pg_options(), pg_copy_from(), pg_copy_to(), pg_end_copy(), pg_put_line(), pg_tty(), pg_trace(), pg_untrace(), pg_set_client_encoding(), pg_client_encoding(), pg_metadata(), pg_convert(), pg_insert(), pg_select(), pg_delete(), pg_update() | pg_close() | Link to PostgreSQL database
pgsql link persistent | pg_pconnect() | pg_affected_rows(), pg_query(), pg_send_query(), pg_get_result(), pg_connection_busy(), pg_connection_reset(), pg_connection_status(), pg_last_error(), pg_last_notice(), pg_lo_create(), pg_lo_export(), pg_lo_import(), pg_lo_open(), pg_lo_unlink(), pg_host(), pg_port(), pg_dbname(), pg_options(), pg_copy_from(), pg_copy_to(), pg_end_copy(), pg_put_line(), pg_tty(), pg_trace(), pg_untrace(), pg_set_client_encoding(), pg_client_encoding(), pg_metadata(), pg_convert(), pg_insert(), pg_select(), pg_delete(), pg_update() | None | Persistent link to PostgreSQL database
pgsql result | pg_execute(), pg_query(), pg_query_params(), pg_get_result() | pg_fetch_array(), pg_fetch_object(), pg_fetch_result(), pg_fetch_row(), pg_field_is_null(), pg_field_name(), pg_field_num(), pg_field_prtlen(), pg_field_size(), pg_field_type(), pg_last_oid(), pg_num_fields(), pg_num_rows(), pg_result_error(), pg_result_status() | pg_free_result() | PostgreSQL result
pgsql string
printer
printer brush
printer font
printer pen
pspell | pspell_new(), pspell_new_config(), pspell_new_personal() | pspell_add_to_personal(), pspell_add_to_session(), pspell_check(), pspell_clear_session(), pspell_config_ignore(), pspell_config_mode(), pspell_config_personal(), pspell_config_repl(), pspell_config_runtogether(), pspell_config_save_repl(), pspell_save_wordlist(), pspell_store_replacement(), pspell_suggest() | None | pspell dictionary
pspell config | pspell_config_create() | pspell_new_config() | None | pspell configuration
shmop | shmop_open() | shmop_read(), shmop_write(), shmop_size(), shmop_delete() | shmop_close() | Shared memory block handle (as of PHP 7.0.0)
sockets file descriptor set | socket() | accept_connect(), bind(), connect(), listen(), read(), write() | close() | Socket
sockets i/o vector
stream | opendir() | readdir(), rewinddir() | closedir() | Dir handle
stream | fopen(), tmpfile() | feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), flock(), fpassthru(), fputs(), fwrite(), fread(), fseek(), ftell(), fstat(), ftruncate(), set_file_buffer(), rewind() | fclose() | File handle
stream | popen(), fsockopen(), pfsockopen() | feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() | pclose() | Process handle
socket | fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() | fclose() | Socket handle
sybase-db link | sybase_connect() | sybase_query(), sybase_select_db() | sybase_close() | Link to Sybase database using DB library
sybase-db link persistent | sybase_pconnect() | sybase_query(), sybase_select_db() | None | Persistent link to Sybase database using DB library
sybase-db result | sybase_query(), sybase_unbuffered_query() | sybase_data_seek(), sybase_fetch_array(), sybase_fetch_field(), sybase_fetch_object(), sybase_fetch_row(), sybase_field_seek(), sybase_num_fields(), sybase_num_rows(), sybase_result() | sybase_free_result() | Sybase result using DB library
sybase-ct link | sybase_connect() | sybase_affected_rows(), sybase_query(), sybase_select_db() | sybase_close() | Link to Sybase database using CT library
sybase-ct link persistent | sybase_pconnect() | sybase_affected_rows(), sybase_query(), sybase_select_db() | None | Persistent link to Sybase database using CT library
sybase-ct result | sybase_query() | sybase_data_seek(), sybase_fetch_array(), sybase_fetch_field(), sybase_fetch_object(), sybase_fetch_row(), sybase_field_seek(), sybase_num_fields(), sybase_num_rows(), sybase_result() | sybase_free_result() | Sybase result using CT library
sysvsem | sem_get() | sem_acquire() | sem_release() | System V Semaphore
sysvshm | shm_attach() | shm_remove(), shm_put_var(), shm_get_var(), shm_remove_var() | shm_detach() | System V Shared Memory
wddx | wddx_packet_start() | wddx_add_vars() | wddx_packet_end() | WDDX packet
xml | xml_parser_create(), xml_parser_create_ns() | xml_set_object(), xml_set_element_handler(), xml_set_character_data_handler(), xml_set_processing_instruction_handler(), xml_set_default_handler(), xml_set_unparsed_entity_decl_handler(), xml_set_notation_decl_handler(), xml_set_external_entity_ref_handler(), xml_parse(), xml_get_error_code(), xml_error_string(), xml_get_current_line_number(), xml_get_current_column_number(), xml_get_current_byte_index(), xml_parse_into_struct(), xml_parser_set_option(), xml_parser_get_option() | xml_parser_free() | XML parser
zlib | gzopen() | gzeof(), gzgetc(), gzgets(), gzgetss(), gzpassthru(), gzputs(), gzread(), gzrewind(), gzseek(), gztell(), gzwrite() | gzclose() | gz-compressed file
zlib.deflate | deflate_init() | deflate_add() | None() | incremental deflate context
zlib.inflate | inflate_init() | inflate_add() | None() | incremental inflate context


List of Available Filters

Table of Contents

  • String Filters
  • Conversion Filters
  • Compression Filters
  • Encryption Filters

The following is a list of a few built-in stream filters for use with stream_filter_append(). Your version of PHP may have more filters (or fewer) than those listed here.

It is worth noting a slight asymmetry between stream_filter_append() and stream_filter_prepend(). Every PHP stream contains a small read buffer where it stores blocks of data retrieved from the filesystem or other resource in order to process data in the most efficient manner. As soon as data is pulled from the resource into the stream's internal buffer, it is immediately processed through any attached filters whether the PHP application is actually ready for the data or not. If data is sitting in the read buffer when a filter is appended, this data will be immediately processed through that filter making the fact that it was sitting in the buffer seem transparent. However, if data is sitting in the read buffer when a filter is prepended, this data will NOT be processed through that filter. It will instead wait until the next block of data is retrieved from the resource.

For a list of filters installed in your version of PHP use stream_get_filters().


String Filters

Each of these filters does precisely what their name implies and correspond to the behavior of a built-in php string handling function. For more information on a given filter, refer to the manual page for the corresponding function.

string.rot13

Use of this filter is equivalent to processing all stream data through the str_rot13() function.

Example #1 string.rot13

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.rot13');
fwrite($fp, "This is a test.\n");
/* Outputs:  Guvf vf n grfg.   */
?>

string.toupper

Use of this filter is equivalent to processing all stream data through the strtoupper() function.

Example #2 string.toupper

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.toupper');
fwrite($fp, "This is a test.\n");
/* Outputs:  THIS IS A TEST.   */
?>

string.tolower

Use of this filter is equivalent to processing all stream data through the strtolower() function.

Example #3 string.tolower

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.tolower');
fwrite($fp, "This is a test.\n");
/* Outputs:  this is a test.   */
?>

string.strip_tags

Use of this filter is equivalent to processing all stream data through the strip_tags() function. It accepts parameters in one of two forms: Either as a string containing a list of tags similar to the second parameter of the strip_tags() function, or as an array of tag names.

Warning

This feature has been DEPRECATED as of PHP 7.3.0. Relying on this feature is highly discouraged.

Example #4 string.strip_tags

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.strip_tags', STREAM_FILTER_WRITE, "<b><i><u>");
fwrite($fp, "<b>bolded text</b> enlarged to a <h1>level 1 heading</h1>\n");
fclose($fp);
/* Outputs:  <b>bolded text</b> enlarged to a level 1 heading   */

$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.strip_tags', STREAM_FILTER_WRITE, array('b','i','u'));
fwrite($fp, "<b>bolded text</b> enlarged to a <h1>level 1 heading</h1>\n");
fclose($fp);
/* Outputs:  <b>bolded text</b> enlarged to a level 1 heading   */
?>


Conversion Filters

Like the string.* filters, the convert.* filters perform actions similar to their names. For more information on a given filter, refer to the manual page for the corresponding function.

convert.base64-encode and convert.base64-decode

Use of these filters are equivalent to processing all stream data through the base64_encode() and base64_decode() functions respectively. convert.base64-encode supports parameters given as an associative array. If line-length is given, the base64 output will be split into chunks of line-length characters each. If line-break-chars is given, each chunk will be delimited by the characters given. These parameters give the same effect as using base64_encode() with chunk_split().

Example #1 convert.base64-encode & convert.base64-decode

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-encode');
fwrite($fp, "This is a test.\n");
fclose($fp);
/* Outputs:  VGhpcyBpcyBhIHRlc3QuCg==  */

$param = array('line-length' => 8, 'line-break-chars' => "\r\n");
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-encode', STREAM_FILTER_WRITE, $param);
fwrite($fp, "This is a test.\n");
fclose($fp);
/* Outputs:  VGhpcyBp
          :  cyBhIHRl
          :  c3QuCg==  */

$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-decode');
fwrite($fp, "VGhpcyBpcyBhIHRlc3QuCg==");
fclose($fp);
/* Outputs:  This is a test.  */
?>

convert.quoted-printable-encode and convert.quoted-printable-decode

Use of the decode version of this filter is equivalent to processing all stream data through the quoted_printable_decode() functions. There is no function equivalent to convert.quoted-printable-encode. convert.quoted-printable-encode supports parameters given as an associative array. In addition to the parameters supported by convert.base64-encode, convert.quoted-printable-encode also supports boolean arguments binary and force-encode-first. convert.base64-decode only supports the line-break-chars parameter as a type-hint for stripping from the encoded payload.

Example #2 convert.quoted-printable-encode & convert.quoted-printable-decode

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.quoted-printable-encode');
fwrite($fp, "This is a test.\n");
/* Outputs:  =This is a test.=0A  */
?>

convert.iconv.*

The convert.iconv.* filters are available, if iconv support is enabled, and their use is equivalent to processing all stream data with iconv(). These filters do not support parameters, but instead expect the input and output encodings to be given as part of the filter name, i.e. either as convert.iconv.<input-encoding>.<output-encoding> or convert.iconv.<input-encoding>/<output-encoding> (both notations are semantically equivalent).

Example #3 convert.iconv.*

<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.iconv.utf-16le.utf-8');
fwrite($fp, "T\0h\0i\0s\0 \0i\0s\0 \0a\0 \0t\0e\0s\0t\0.\0\n\0");
fclose($fp);
/* Outputs: This is a test. */
?>


Compression Filters

While the Compression Wrappers provide a way of creating gzip and bz2 compatible files on the local filesystem, they do not provide a means for generalized compression over network streams, nor do they provide a means to begin with a non-compressed stream and transition to a compressed one. For this, a compression filter may be applied to any stream resource at any time.

Note: Compression filters do not generate headers and trailers used by command line utilities such as gzip. They only compress and decompress the payload portions of compressed data streams.

zlib.deflate and zlib.inflate

zlib.deflate (compression) and zlib.inflate (decompression) are implementations of the compression methods described in » RFC 1951. The deflate filter takes up to three parameters passed as an associative array. level describes the compression strength to use (1-9). Higher numbers will generally yield smaller payloads at the cost of additional processing time. Two special compression levels also exist: 0 (for no compression at all), and -1 (zlib internal default -- currently 6). window is the base-2 log of the compression loopback window size. Higher values (up to 15 -- 32768 bytes) yield better compression at a cost of memory, while lower values (down to 9 -- 512 bytes) yield worse compression in a smaller memory footprint. Default window size is currently 15. memory is a scale indicating how much work memory should be allocated. Valid values range from 1 (minimal allocation) to 9 (maximum allocation). This memory allocation affects speed only and does not impact the size of the generated payload.

Note: Because compression level is the most commonly used parameter, it may be alternatively provided as a simple integer value (rather than an array element).

zlib.* compression filters are available with PHP as of version 5.1.0 if zlib support is enabled. They are also available as a backport in version 5.0.x by installing the » zlib_filter package from » PECL.

Example #1 zlib.deflate and zlib.inflate

<?php
$params = array('level' => 6, 'window' => 15, 'memory' => 9);

$original_text = "This is a test.\nThis is only a test.\nThis is not an important string.\n";
echo "The original text is " . strlen($original_text) . " characters long.\n";

$fp = fopen('test.deflated', 'w');
stream_filter_append($fp, 'zlib.deflate', STREAM_FILTER_WRITE, $params);
fwrite($fp, $original_text);
fclose($fp);

echo "The compressed file is " . filesize('test.deflated') . " bytes long.\n";
echo "The original text was:\n";
/* Use readfile and zlib.inflate to decompress on the fly */
readfile('php://filter/zlib.inflate/resource=test.deflated');

/* Generates output:

The original text is 70 characters long.
The compressed file is 56 bytes long.
The original text was:
This is a test.
This is only a test.
This is not an important string.

 */
?>

Example #2 zlib.deflate simple

<?php
$original_text = "This is a test.\nThis is only a test.\nThis is not an important string.\n";
echo "The original text is " . strlen($original_text) . " characters long.\n";

$fp = fopen('test.deflated', 'w');
/* Here "6" indicates compression level 6 */
stream_filter_append($fp, 'zlib.deflate', STREAM_FILTER_WRITE, 6);
fwrite($fp, $original_text);
fclose($fp);

echo "The compressed file is " . filesize('test.deflated') . " bytes long.\n";

/* Generates output:

The original text is 70 characters long.
The compressed file is 56 bytes long.

 */
?>

bzip2.compress and bzip2.decompress

bzip2.compress and bzip2.decompress work in the same manner as the zlib filters described above. The bzip2.compress filter accepts up to two parameters given as elements of an associative array: blocks is an integer value from 1 to 9 specifying the number of 100kbyte blocks of memory to allocate for workspace. work is also an integer value ranging from 0 to 250 indicating how much effort to expend using the normal compression method before falling back on a slower, but more reliable method. Tuning this parameter effects only compression speed. Neither size of compressed output nor memory usage are changed by this setting. A work factor of 0 instructs the bzip library to use an internal default. The bzip2.decompress filter only accepts one parameter, which can be passed as either an ordinary boolean value, or as the small element of an associative array. small, when set to a TRUE value, instructs the bzip library to perform decompression in a minimal memory footprint at the cost of speed.

bzip2.* compression filters are available with PHP as of version 5.1.0 if bz2 support is enabled. They are also available as a backport in version 5.0.x by installing the » bz2_filter package from » PECL.

Example #3 bzip2.compress and bzip2.decompress

<?php
$param = array('blocks' => 9, 'work' => 0);

echo "The original file is " . filesize('LICENSE') . " bytes long.\n";

$fp = fopen('LICENSE.compressed', 'w');
stream_filter_append($fp, 'bzip2.compress', STREAM_FILTER_WRITE, $param);
fwrite($fp, file_get_contents('LICENSE'));
fclose($fp);

echo "The compressed file is " . filesize('LICENSE.compressed') . " bytes long.\n";

/* Generates output:

The original text is 3288 characters long.
The compressed file is 1488 bytes long.

 */
?>


Encryption Filters

Encryption filters are especially useful for file/stream encryption.

mcrypt.* and mdecrypt.*

Warning

This feature has been DEPRECATED as of PHP 7.1.0. Relying on this feature is highly discouraged.

mcrypt.* and mdecrypt.* provide symmetric encryption and decryption using libmcrypt. Both sets of filters support the same algorithms available to mcrypt extension in the form of mcrypt.ciphername where ciphername is the name of the cipher as it would be passed to mcrypt_module_open(). The following five filter parameters are also available:

mcrypt filter parameters
Parameter | Required? | Default | Sample Values
mode | Optional | cbc | cbc, cfb, ecb, nofb, ofb, stream
algorithms_dir | Optional | ini_get('mcrypt.algorithms_dir') | Location of algorithms modules
modes_dir | Optional | ini_get('mcrypt.modes_dir') | Location of modes modules
iv | Required | N/A | Typically 8, 16, or 32 bytes of binary data. Depends on cipher
key | Required | N/A | Typically 8, 16, or 32 bytes of binary data. Depends on cipher

Example #1 Encrypt/Decrypt with Blowfish

<?php
//$key assumed to be previously generated
$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM);
$fp = fopen('encrypted-file.enc', 'wb');
fwrite($fp, $iv);
$opts = array('mode'=>'cbc','iv'=>$iv, 'key'=>$key);
stream_filter_append($fp, 'mcrypt.blowfish', STREAM_FILTER_WRITE, $opts);
fwrite($fp, 'message to encrypt');
fclose($fp);

//decrypt...
$fp = fopen('encrypted-file.enc', 'rb');
$iv = fread($fp, $iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_CBC));
$opts = array('mode'=>'cbc','iv'=>$iv, 'key'=>$key)
stream_filter_append($fp, 'mdecrypt.blowfish', STREAM_FILTER_READ, $opts);
$data = rtrim(stream_get_contents($fp));//trims off null padding
fclose($fp);
echo $data;
?>

Example #2 Encrypt file using AES-128 CBC with SHA256 HMAC in PHP 5.5+

<?php
AES_CBC::encryptFile($password, "plaintext.txt", "encrypted.enc");
AES_CBC::decryptFile($password, "encrypted.enc", "decrypted.txt");

class AES_CBC
{
   protected static $KEY_SIZES = array('AES-128'=>16,'AES-192'=>24,'AES-256'=>32);
   protected static function key_size() { return self::$KEY_SIZES['AES-128']; } //default AES-128
   public static function encryptFile($password, $input_stream, $aes_filename){
      $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
      $fin = fopen($input_stream, "rb");
      $fc = fopen($aes_filename, "wb+");
      if (!empty($fin) && !empty($fc)) {
         fwrite($fc, str_repeat("_", 32) );//placeholder, SHA256 HMAC will go here later
         fwrite($fc, $hmac_salt = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM));
         fwrite($fc, $esalt = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM));
         fwrite($fc, $iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM));
         $ekey = hash_pbkdf2("sha256", $password, $esalt, $it=1000, self::key_size(), $raw=true);
         $opts = array('mode'=>'cbc', 'iv'=>$iv, 'key'=>$ekey);
         stream_filter_append($fc, 'mcrypt.rijndael-128', STREAM_FILTER_WRITE, $opts);
         $infilesize = 0;
         while (!feof($fin)) {
            $block = fread($fin, 8192);
            $infilesize+=strlen($block);
            fwrite($fc, $block);
         }
         $block_size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
         $padding = $block_size - ($infilesize % $block_size);//$padding is a number from 1-16
         fwrite($fc, str_repeat(chr($padding), $padding) );//perform PKCS7 padding
         fclose($fin);
         fclose($fc);
         $hmac_raw = self::calculate_hmac_after_32bytes($password, $hmac_salt, $aes_filename);
         $fc = fopen($aes_filename, "rb+");
         fwrite($fc, $hmac_raw);//overwrite placeholder
         fclose($fc);
      }
   }
   public static function decryptFile($password, $aes_filename, $out_stream) {
      $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
      $hmac_raw = file_get_contents($aes_filename, false, NULL,  0, 32);
      $hmac_salt = file_get_contents($aes_filename, false, NULL, 32, $iv_size);
      $hmac_calc = self::calculate_hmac_after_32bytes($password, $hmac_salt, $aes_filename);
      $fc = fopen($aes_filename, "rb");
      $fout = fopen($out_stream, 'wb');
      if (!empty($fout) && !empty($fc) && self::hash_equals($hmac_raw,$hmac_calc)) {
         fread($fc, 32+$iv_size);//skip sha256 hmac and salt
         $esalt = fread($fc, $iv_size);
         $iv    = fread($fc, $iv_size);
         $ekey = hash_pbkdf2("sha256", $password, $esalt, $it=1000, self::key_size(), $raw=true);
         $opts = array('mode'=>'cbc', 'iv'=>$iv, 'key'=>$ekey);
         stream_filter_append($fc, 'mdecrypt.rijndael-128', STREAM_FILTER_READ, $opts);
         while (!feof($fc)) {
            $block = fread($fc, 8192);
            if (feof($fc)) {
               $padding = ord($block[strlen($block) - 1]);//assume PKCS7 padding
               $block = substr($block, 0, 0-$padding);
            }
            fwrite($fout, $block);
         }
         fclose($fout);
         fclose($fc);
      }
   }
   private static function hash_equals($str1, $str2) {
      if(strlen($str1) == strlen($str2)) {
         $res = $str1 ^ $str2;
         for($ret=0,$i = strlen($res) - 1; $i >= 0; $i--) $ret |= ord($res[$i]);
         return !$ret;
      }
      return false;
   }
   private static function calculate_hmac_after_32bytes($password, $hsalt, $filename) {
      static $init=0;
      $init or $init = stream_filter_register("user-filter.skipfirst32bytes", "FileSkip32Bytes");
      $stream = 'php://filter/read=user-filter.skipfirst32bytes/resource=' . $filename;
      $hkey = hash_pbkdf2("sha256", $password, $hsalt, $iterations=1000, 24, $raw=true);
      return hash_hmac_file('sha256', $stream, $hkey, $raw=true);
   }
}
class FileSkip32Bytes extends php_user_filter
{
   private $skipped=0;
   function filter($in, $out, &$consumed, $closing)  {
      while ($bucket = stream_bucket_make_writeable($in)) {
         $outlen = $bucket->datalen;
         if ($this->skipped<32){
            $outlen = min($bucket->datalen,32-$this->skipped);
            $bucket->data = substr($bucket->data, $outlen);
            $bucket->datalen = $bucket->datalen-$outlen;
            $this->skipped+=$outlen;
         }
         $consumed += $outlen;
         stream_bucket_append($out, $bucket);
      }
      return PSFS_PASS_ON;
   }
}
class AES_128_CBC extends AES_CBC {
   protected static function key_size() { return self::$KEY_SIZES['AES-128']; }
}
class AES_192_CBC extends AES_CBC {
   protected static function key_size() { return self::$KEY_SIZES['AES-192']; }
}
class AES_256_CBC extends AES_CBC {
   protected static function key_size() { return self::$KEY_SIZES['AES-256']; }
}


List of Supported Socket Transports

Table of Contents

  • Internet Domain: TCP, UDP, SSL, and TLS
  • Unix Domain: Unix and UDG

The following is a list of the various URL style socket transports that PHP has built-in for use with the streams based socket functions such as fsockopen(), and stream_socket_client(). These transports do not apply to the Sockets Extension.

For a list of transports installed in your version of PHP use stream_get_transports().


Internet Domain: TCP, UDP, SSL, and TLS

PHP 4, PHP 5. ssl:// & tls:// since PHP 4.3.0 sslv2:// & sslv3:// since PHP 5.0.2

Note: If no transport is specified, tcp:// will be assumed.

  • 127.0.0.1
  • fe80::1
  • www.example.com
  • tcp://127.0.0.1
  • tcp://fe80::1
  • tcp://www.example.com
  • udp://www.example.com
  • ssl://www.example.com
  • sslv2://www.example.com
  • sslv3://www.example.com
  • tls://www.example.com

Internet Domain sockets expect a port number in addition to a target address. In the case of fsockopen() this is specified in a second parameter and therefore does not impact the formatting of transport URL. With stream_socket_client() and related functions as with traditional URLs however, the port number is specified as a suffix of the transport URL delimited by a colon.

  • tcp://127.0.0.1:80
  • tcp://[fe80::1]:80
  • tcp://www.example.com:80

Note: IPv6 numeric addresses with port numbers
In the second example above, while the IPv4 and hostname examples are left untouched apart from the addition of their colon and portnumber, the IPv6 address is wrapped in square brackets: [fe80::1]. This is to distinguish between the colons used in an IPv6 address and the colon used to delimit the portnumber.

The ssl:// and tls:// transports (available only when openssl support is compiled into PHP) are extensions of the tcp:// transport which include SSL encryption. Since PHP 4.3.0 OpenSSL support must be statically compiled into PHP, since PHP 5.0.0 it may be compiled as a module or statically.

ssl:// will attempt to negotiate an SSL V2, or SSL V3 connection depending on the capabilities and preferences of the remote host. sslv2:// and sslv3:// will select the SSL V2 or SSL V3 protocol explicitly.


Unix Domain: Unix and UDG

unix:// and udg:// (udg:// since PHP 5).

  • unix:///tmp/mysock
  • udg:///tmp/mysock

unix:// provides access to a socket stream connection in the Unix domain. udg:// provides an alternate transport to a Unix domain socket using the user datagram protocol.

Unix domain sockets, unlike Internet domain sockets, do not expect a port number. In the case of fsockopen() the portno parameter should be set to 0.


PHP type comparison tables

The following tables demonstrate behaviors of PHP types and comparison operators, for both loose and strict comparisons. This supplemental is also related to the manual section on type juggling. Inspiration was provided by various user comments and by the work over at » BlueShoes.

Before utilizing these tables, it's important to understand types and their meanings. For example, "42" is a string while 42 is an integer. FALSE is a boolean while "false" is a string.

Note:

HTML Forms do not pass integers, floats, or booleans; they pass strings. To find out if a string is numeric, you may use is_numeric().

Note:

Simply doing if ($x) while $x is undefined will generate an error of level E_NOTICE. Instead, consider using empty() or isset() and/or initialize your variables.

Note:

Some numeric operations can result in a value represented by the constant NAN. Any loose or strict comparisons of this value against any other value, including itself, but except TRUE, will have a result of FALSE. (i.e. NAN != NAN and NAN !== NAN) Examples of operations that produce NAN include sqrt(-1), asin(2), and acosh(0).

Comparisons of $x with PHP functions
Expression | gettype() | empty() | is_null() | isset() | boolean : if($x)
$x = ""; | string | TRUE | FALSE | TRUE | FALSE
$x = null; | NULL | TRUE | TRUE | FALSE | FALSE
var $x; | NULL | TRUE | TRUE | FALSE | FALSE
$x is undefined | NULL | TRUE | TRUE | FALSE | FALSE
$x = array(); | array | TRUE | FALSE | TRUE | FALSE
$x = array('a', 'b'); | array | FALSE | FALSE | TRUE | TRUE
$x = false; | boolean | TRUE | FALSE | TRUE | FALSE
$x = true; | boolean | FALSE | FALSE | TRUE | TRUE
$x = 1; | integer | FALSE | FALSE | TRUE | TRUE
$x = 42; | integer | FALSE | FALSE | TRUE | TRUE
$x = 0; | integer | TRUE | FALSE | TRUE | FALSE
$x = -1; | integer | FALSE | FALSE | TRUE | TRUE
$x = "1"; | string | FALSE | FALSE | TRUE | TRUE
$x = "0"; | string | TRUE | FALSE | TRUE | FALSE
$x = "-1"; | string | FALSE | FALSE | TRUE | TRUE
$x = "php"; | string | FALSE | FALSE | TRUE | TRUE
$x = "true"; | string | FALSE | FALSE | TRUE | TRUE
$x = "false"; | string | FALSE | FALSE | TRUE | TRUE

Loose comparisons with ==
 | TRUE | FALSE | 1 | 0 | -1 | "1" | "0" | "-1" | NULL | array() | "php" | ""
TRUE | TRUE | FALSE | TRUE | FALSE | TRUE | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE
FALSE | FALSE | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | TRUE | TRUE | FALSE | TRUE
1 | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
0 | FALSE | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | TRUE | FALSE | TRUE | TRUE
-1 | TRUE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE
"1" | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
"0" | FALSE | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE
"-1" | TRUE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE
NULL | FALSE | TRUE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | TRUE | TRUE | FALSE | TRUE
array() | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | TRUE | FALSE | FALSE
"php" | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE
"" | FALSE | TRUE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | TRUE

Strict comparisons with ===
 | TRUE | FALSE | 1 | 0 | -1 | "1" | "0" | "-1" | NULL | array() | "php" | ""
TRUE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
1 | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
0 | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
-1 | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
"1" | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE
"0" | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE
"-1" | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE
NULL | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE
array() | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE
"php" | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE
"" | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE


List of Parser Tokens

Various parts of the PHP language are represented internally by types like T_SR. PHP outputs identifiers like this one in parse errors, like "Parse error: unexpected T_SR, expecting ',' or ';' in script.php on line 10."

You're supposed to know what T_SR means. For everybody who doesn't know that, here is a table with those identifiers, PHP-syntax and references to the appropriate places in the manual.

Note: Usage of T_* constants

All tokens listed below are also defined as PHP constants. Their value is automatically generated based on PHP's underlying parser infrastructure. This means that the concrete value of a token may change between two PHP versions. For example the T_FILE constant is 365 in PHP 5.3, while the same value refers now to T_TRAIT in PHP 5.4 and the value of T_FILE is 369. This means that your code should never rely directly on the original T_* values taken from PHP version X.Y.Z, to provide some compatibility across multiple PHP versions. Instead your code should utilize custom values (using big numbers like 10000) and an appropriate strategy that will work with both PHP versions and T_* values.

Tokens
Token | Syntax | Reference
T_ABSTRACT | abstract | Class Abstraction
T_AND_EQUAL | &= | assignment operators
T_ARRAY | array() | array(), array syntax
T_ARRAY_CAST | (array) | type-casting
T_AS | as | foreach
T_BAD_CHARACTER |  | anything below ASCII 32 except \t (0x09), \n (0x0a) and \r (0x0d)
T_BOOLEAN_AND | && | logical operators
T_BOOLEAN_OR | || | logical operators
T_BOOL_CAST | (bool) or (boolean) | type-casting
T_BREAK | break | break
T_CALLABLE | callable | callable
T_CASE | case | switch
T_CATCH | catch | Exceptions
T_CHARACTER |  | not used anymore
T_CLASS | class | classes and objects
T_CLASS_C | __CLASS__ | magic constants
T_CLONE | clone | classes and objects
T_CLOSE_TAG | ?> or %> | escaping from HTML
T_COALESCE | ?? | comparison operators (available since PHP 7.0.0)
T_COMMENT | // or #, and /* */ | comments
T_CONCAT_EQUAL | .= | assignment operators
T_CONST | const | class constants
T_CONSTANT_ENCAPSED_STRING | "foo" or 'bar' | string syntax
T_CONTINUE | continue | continue
T_CURLY_OPEN | {$ | complex variable parsed syntax
T_DEC | -- | incrementing/decrementing operators
T_DECLARE | declare | declare
T_DEFAULT | default | switch
T_DIR | __DIR__ | magic constants (available since PHP 5.3.0)
T_DIV_EQUAL | /= | assignment operators
T_DNUMBER | 0.12, etc. | floating point numbers
T_DOC_COMMENT | /** */ | PHPDoc style comments
T_DO | do | do..while
T_DOLLAR_OPEN_CURLY_BRACES | ${ | complex variable parsed syntax
T_DOUBLE_ARROW | => | array syntax
T_DOUBLE_CAST | (real), (double) or (float) | type-casting
T_DOUBLE_COLON | :: | see T_PAAMAYIM_NEKUDOTAYIM below
T_ECHO | echo | echo
T_ELLIPSIS | ... | function arguments (available since PHP 5.6.0)
T_ELSE | else | else
T_ELSEIF | elseif | elseif
T_EMPTY | empty | empty()
T_ENCAPSED_AND_WHITESPACE | " $a" | constant part of string with variables
T_ENDDECLARE | enddeclare | declare, alternative syntax
T_ENDFOR | endfor | for, alternative syntax
T_ENDFOREACH | endforeach | foreach, alternative syntax
T_ENDIF | endif | if, alternative syntax
T_ENDSWITCH | endswitch | switch, alternative syntax
T_ENDWHILE | endwhile | while, alternative syntax
T_END_HEREDOC |  | heredoc syntax
T_EVAL | eval() | eval()
T_EXIT | exit or die | exit(), die()
T_EXTENDS | extends | extends, classes and objects
T_FILE | __FILE__ | magic constants
T_FINAL | final | Final Keyword
T_FINALLY | finally | Exceptions (available since PHP 5.5.0)
T_FOR | for | for
T_FOREACH | foreach | foreach
T_FUNCTION | function or cfunction | functions
T_FUNC_C | __FUNCTION__ | magic constants
T_GLOBAL | global | variable scope
T_GOTO | goto | goto (available since PHP 5.3.0)
T_HALT_COMPILER | __halt_compiler() | __halt_compiler (available since PHP 5.1.0)
T_IF | if | if
T_IMPLEMENTS | implements | Object Interfaces
T_INC | ++ | incrementing/decrementing operators
T_INCLUDE | include() | include
T_INCLUDE_ONCE | include_once() | include_once
T_INLINE_HTML |  | text outside PHP
T_INSTANCEOF | instanceof | type operators
T_INSTEADOF | insteadof | Traits (available since PHP 5.4.0)
T_INT_CAST | (int) or (integer) | type-casting
T_INTERFACE | interface | Object Interfaces
T_ISSET | isset() | isset()
T_IS_EQUAL | == | comparison operators
T_IS_GREATER_OR_EQUAL | >= | comparison operators
T_IS_IDENTICAL | === | comparison operators
T_IS_NOT_EQUAL | != or <> | comparison operators
T_IS_NOT_IDENTICAL | !== | comparison operators
T_IS_SMALLER_OR_EQUAL | <= | comparison operators
T_SPACESHIP | <=> | comparison operators (available since PHP 7.0.0)
T_LINE | __LINE__ | magic constants
T_LIST | list() | list()
T_LNUMBER | 123, 012, 0x1ac, etc. | integers
T_LOGICAL_AND | and | logical operators
T_LOGICAL_OR | or | logical operators
T_LOGICAL_XOR | xor | logical operators
T_METHOD_C | __METHOD__ | magic constants
T_MINUS_EQUAL | -= | assignment operators
T_MOD_EQUAL | %= | assignment operators
T_MUL_EQUAL | *= | assignment operators
T_NAMESPACE | namespace | namespaces (available since PHP 5.3.0)
T_NS_C | __NAMESPACE__ | namespaces (available since PHP 5.3.0)
T_NS_SEPARATOR | \ | namespaces (available since PHP 5.3.0)
T_NEW | new | classes and objects
T_NUM_STRING | "$a[0]" | numeric array index inside string
T_OBJECT_CAST | (object) | type-casting
T_OBJECT_OPERATOR | -> | classes and objects
T_OPEN_TAG | <?php, <? or <% | escaping from HTML
T_OPEN_TAG_WITH_ECHO | <?= or <%= | escaping from HTML
T_OR_EQUAL | |= | assignment operators
T_PAAMAYIM_NEKUDOTAYIM | :: | ::. Also defined as T_DOUBLE_COLON.
T_PLUS_EQUAL | += | assignment operators
T_POW | ** | arithmetic operators (available since PHP 5.6.0)
T_POW_EQUAL | **= | assignment operators (available since PHP 5.6.0)
T_PRINT | print() | print
T_PRIVATE | private | classes and objects
T_PUBLIC | public | classes and objects
T_PROTECTED | protected | classes and objects
T_REQUIRE | require() | require
T_REQUIRE_ONCE | require_once() | require_once
T_RETURN | return | returning values
T_SL | << | bitwise operators
T_SL_EQUAL | <<= | assignment operators
T_SR | >> | bitwise operators
T_SR_EQUAL | >>= | assignment operators
T_START_HEREDOC | <<< | heredoc syntax
T_STATIC | static | variable scope
T_STRING | parent, self, etc. | identifiers, e.g. keywords like parent and self, function names, class names and more are matched. See also T_CONSTANT_ENCAPSED_STRING.
T_STRING_CAST | (string) | type-casting
T_STRING_VARNAME | "${a | complex variable parsed syntax
T_SWITCH | switch | switch
T_THROW | throw | Exceptions
T_TRAIT | trait | Traits (available since PHP 5.4.0)
T_TRAIT_C | __TRAIT__ | __TRAIT__ (available since PHP 5.4.0)
T_TRY | try | Exceptions
T_UNSET | unset() | unset()
T_UNSET_CAST | (unset) | type-casting
T_USE | use | namespaces (available since PHP 5.3.0)
T_VAR | var | classes and objects
T_VARIABLE | $foo | variables
T_WHILE | while | while, do..while
T_WHITESPACE | \t \r\n |
T_XOR_EQUAL | ^= | assignment operators
T_YIELD | yield | generators (available since PHP 5.5.0)
T_YIELD_FROM | yield from | generators (available since PHP 7.0.0)

See also token_name().


Userland Naming Guide

Table of Contents

  • Global Namespace
  • Rules
  • Tips

The following is a guide for how to best choose names for identifiers in userland PHP code. When choosing names for any code that creates symbols in the global namespace, it is important to take into account the following guidelines to prevent future versions of PHP from clashing with your symbols.


Global Namespace

Here is an overview of code constructs that go into the global namespace:

  • functions

  • classes

  • interfaces

  • constants (not class constants)

  • variables defined outside of functions/methods


Rules

The following list gives an overview of which rights the PHP project reserves for itself, when choosing names for new internal identifiers. The definitive guide is the official » CODING STANDARDS:

  • PHP owns the top-level namespace but tries to find decent descriptive names and avoid any obvious clashes.

  • Function names use underscores between words, while class names use both the camelCase and PascalCase rules.

  • PHP will prefix any global symbols of an extension with the name of the extension. (In the past, there have been numerous exceptions to this rule.) Examples:

    • curl_close()

    • mysql_query()

    • PREG_SPLIT_DELIM_CAPTURE

    • new DOMDocument()

    • strpos() (example of a past mistake)

    • new SplFileObject()

  • Iterators and Exceptions are however simply postfixed with "Iterator" and "Exception." Examples:

    • ArrayIterator

    • LogicException

  • PHP reserves all symbols starting with __ as magical. It is recommended that you do not create symbols starting with __ in PHP unless you want to use documented magical functionality. Examples:

    • __get()

    • __autoload()


Tips

In order to write future-proof code, it is recommended that you don't place many variables, functions or classes in the global namespace. This will prevent naming conflicts with 3rd party code as well as possible future additions to the language.

One common way to prevent naming conflicts of functions and classes is to add them to their own dedicated namespace.

<?php

namespace MyProject;

function my_function() {
    return true;
}

\MyProject\my_function();

This still needs you to keep track of already used namespaces, but once you have decided on a namespace you will be using you can add all functions and classes to it without having to think about conflicts again.

It is considered best practice to limit the number of variables added to the global scope in order to prevent naming conflicts with 3rd party code.

Note: Variable scoping

Because of PHP's scoping rules variables defined inside functions and methods are not in the global scope and as such cannot conflict with other variables defined in the global scope.


About the manual

Table of Contents

  • Formats
  • About user notes
  • How to read a function definition (prototype)
  • PHP versions documented in this manual
  • How to find more information about PHP
  • How to help improve the documentation
  • How we generate the formats
  • Translations


Formats

The PHP manual is provided in several formats. These formats can be divided into two groups: online readable formats, and downloadable packages.

Note:

Some publishers have made available printed versions of this manual. We cannot recommend any of those, as they tend to become out-of-date very quickly.

The manual can be read online at the » PHP.net website, and on the numerous mirror sites. For best performance, choose the closest mirror. The online version of the PHP manual has currently two CSS stylesheets, web friendly and a printer-friendly stylesheet.

Two notable advantages of the online manual over most of the offline formats is the integration of user-contributed notes and the » URL shortcuts that may be used to get to the desired manual parts quickly. An obvious disadvantage is the requirement to be online to view this edition of the manual.

There are several offline formats of the manual, and the most appropriate format for depends on the operating system, and personal reading style. For information on how the manual is generated in so many formats, read the 'How we generate the formats' section of this appendix.

The most cross-platform format of the manual is the HTML version. This is provided both as a single HTML file and as a package of individual files for each section (which results in a collection of several thousand files). We provide these versions compressed, so a decompression utility is required to retrieve the files contained within the archives.

For Windows platforms, the Windows HTML Help version of the manual enhances the HTML format for use with the Windows HTML Help application. This version provides full-text search, a full index, and bookmarking. Many popular Windows PHP development environments also integrate with this version of the documentation to provide easy access. CHM viewers for Linux desktops are also available. Check out » xCHM or » GnoCHM.

There is also an » extended CHM version available, which is updated less frequently, but provides many additional features. It will only work on Microsoft Windows though, because of the technologies used to build the help pages.


About user notes

The user-contributed notes play an important role in the development of this manual. By allowing readers of the manual to contribute examples, caveats, and further clarifications from their browser, we are able to incorporate that feedback into the main text of the manual. And until the notes have been incorporated, they may be viewed in their submitted form online, and in some of the offline formats.

Note:

The user-contributed notes are not moderated before they appear online, so the quality of the writing or code examples, and even the veracity of the contribution, cannot be guaranteed. (Not that there is any guarantee of the quality or accuracy of the manual text itself.)

Note:

For the purposes of license coverage the user-contributed notes are considered part of the PHP manual, and are therefore covered by the same license that covers this documentation (Creative Commons Attribution at the moment). For more details see the Manual's Copyright page.


How to read a function definition (prototype)

Each function in the manual is documented for quick reference. Knowing how to read and understand the text will make learning PHP much easier. Rather than relying on examples or cut/paste, everyone should know how to read function definitions (prototypes). Let's begin:

Note: Prerequisite: Basic understanding of types

Although PHP is a loosely typed language, it's important to have a basic understanding of types as they have important meaning.

Function definitions tell us what type of value is returned. Let's use the definition for strlen() as our first example:

strlen

(PHP 4, PHP 5)
strlen -- Get string length

Description
strlen ( string $string ) : int

Returns the length of given string.

Explanation of a function definition
Part | Description
strlen | The function name.
(PHP 4, PHP 5) | strlen() has been around in all versions of PHP 4 and PHP 5
( string $string ) | The first (and in this case the only) parameter/argument for this function is named string, and it's a string.
int | Type of value this function returns, which is an integer (i.e. the length of a string is measured in numbers).

We could rewrite the above function definition in a generic way:

      function name    ( parameter type   parameter name ) : returned type

Many functions take on multiple parameters, such as in_array(). Its prototype is as follows:

      in_array ( mixed $needle, array $haystack [, bool $strict = FALSE ] ) : bool

What does this mean? in_array() returns a boolean value, TRUE on success (if the needle was found in the haystack) or FALSE on failure (if the needle was not found in the haystack). The first parameter is named needle and it can be of many different types, so we call it "mixed". This mixed needle (what we're looking for) can be either a scalar value (string, integer, or float), or an array. haystack (the array we're searching in) is the second parameter. The third optional parameter is named strict. All optional parameters are seen in [ brackets ]. The manual states that the strict parameter defaults to boolean FALSE. See the manual page on each function for details on how they work.

In addition the & (ampersand) symbol prepended to a function parameter allows the parameter to be passed by reference, as seen below:

       preg_match ( string $pattern , string $subject [, array &$matches
      [, int $flags = 0 [, int $offset = 0 ]]] ) : int

In this example, we can see the third optional parameter &$matches will be passed as reference.

There are also functions with more complex PHP version information. Take html_entity_decode() as an example:

(PHP 4 >= 4.3.0, PHP 5)

This means that this function has only been available in a released version since PHP 4.3.0.


PHP versions documented in this manual

The manual contains information about past, current, and future versions of PHP. Changes in behaviour are documented as notes, changelogs, and inline text within the manual pages. The earliest documented version is PHP 5.0.0.

When documentation exists for the latest (unreleased) developmental versions of PHP, it will be labeled as either "available in Git" or "development version." And while these changes should be planned for, in rare cases they may change.

All development takes place in Git and may be checked out as described within the » anonymous Git access page.

And to clarify, the manual will refer to major, minor and point PHP releases. Using PHP 5.3.1 as an example, the 5 refers to the major version, 3 to minor, and 1 is the point release. Typically PHP only adds new features to major and minor releases, and fixes bugs in point releases. However, this convention is not always true.

Also note that the PHP manual is written in present tense, not future tense, even for documented features that are not yet available. The reason for this is so the manual can stand the test of time, thus not require tedious grammar updates with every PHP release.

Many times the PHP manual lists "Default Values" for PHP directives. These values are based on how PHP behaves without a php.ini configuration file, so this may differ from values found in the distributed php.ini-development and php.ini-production files. They also refer to the latest version of PHP, although changelog entries do mention past values. See the PHP directive appendix for details regarding these values and changes.


How to find more information about PHP

This manual does not attempt to provide instruction about general programming practices. First-time - or even just beginning - programmers may find it difficult to learn how to program in PHP using this manual exclusively. Instead, seek out a text more oriented towards beginners.

There are a number of active mailing lists for discussion on all aspects of programming with PHP. If stuck with a problem, consider using these lists. For support options, including mailing lists, view » the PHP.net support page.


How to help improve the documentation

There are three ways everyone can help improve this documentation.

If an error is found in this manual, in any language, please report them using the bug system at » https://bugs.php.net/. Classify the bug as "Documentation Problem". All documentation related problems, including those about manual formats, should be submitted as bug reports.

Note:

Please don't abuse the bug system by submitting requests for help. Instead, use one of the many » support options.

By contributing notes, users may provide additional examples, caveats, and clarifications for other readers. But please do not submit bug reports using the annotation system. For details, see the section titled 'About user notes'.

The PHP manual is translated into many languages. Knowing English and a foreign language allows for another way to help improve the PHP manual by working with a translation team. For information about starting a new translation, or helping a currently translated version, please read » http://doc.php.net/tutorial/.

The PHP Documentation Project also has an IRC channel where many manual authors hang out. Stop by #php.doc on irc.efnet.org and discuss ways to improve the PHP documentation.


How we generate the formats

This manual is written in XML using the » DocBook XML DTD, using » PhD (The [PH]P based [D]ocBook renderer) for maintenance and formatting.

Using XML as a source format gives the ability to generate many output formats from the source files, while only maintaining one source document for all formats. The tool used for formatting the online manual is » PhD. We use » Microsoft HTML Help Workshop to generate the Windows HTML Help format of the manual, and of course PHP itself to do some additional conversions and formatting.

The PHP manual is generated in various languages and formats, see » https://www.php.net/docs.php for additional details. The XML source code may be downloaded from SVN and viewed at » https://svn.php.net/viewvc/. The documentation is stored in the phpdoc module.


Translations

The PHP manual is available not only in various formats, but also in various languages. The text of the manual is first written in English, then teams of people across the world take care of translating it to their native languages. If a translation for a specified function or chapter has not yet been made, the manual's build system falls back to the English version of it.

People involved in the translations start from the XML source code available from » https://svn.php.net/viewvc/ and from it they translate to their mother language. They do not use the generated versions (like HTML or plain text) as it's the build system that takes care of the conversions from XML to human readable formats.

Note:

To help translate the documentation, please get in touch with the translation/documentation team by subscribing to the phpdoc mailing list: send an empty mail to » phpdoc-subscribe@lists.php.net. The mailing list address is phpdoc@lists.php.net. State in the message an interest in translating the manual and someone will reply with feedback on moving forward by helping start a new language translation, or by contacting the existing team for the desired language.

At the moment the manual is available, partly or not, in over 10 languages.

They may all be downloaded here: » https://www.php.net/docs.php.


Creative Commons Attribution 3.0

THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.

BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.

1. Definitions

  1. "Adaptation" means a work based upon the Work, or upon the Work and other pre-existing works, such as a translation, adaptation, derivative work, arrangement of music or other alterations of a literary or artistic work, or phonogram or performance and includes cinematographic adaptations or any other form in which the Work may be recast, transformed, or adapted including in any form recognizably derived from the original, except that a work that constitutes a Collection will not be considered an Adaptation for the purpose of this License. For the avoidance of doubt, where the Work is a musical work, performance or phonogram, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered an Adaptation for the purpose of this License.
  2. "Collection" means a collection of literary or artistic works, such as encyclopedias and anthologies, or performances, phonograms or broadcasts, or other works or subject matter other than works listed in Section 1(f) below, which, by reason of the selection and arrangement of their contents, constitute intellectual creations, in which the Work is included in its entirety in unmodified form along with one or more other contributions, each constituting separate and independent works in themselves, which together are assembled into a collective whole. A work that constitutes a Collection will not be considered an Adaptation (as defined above) for the purposes of this License.
  3. "Distribute" means to make available to the public the original and copies of the Work or Adaptation, as appropriate, through sale or other transfer of ownership.
  4. "Licensor" means the individual, individuals, entity or entities that offer(s) the Work under the terms of this License.
  5. "Work" means the literary and/or artistic work offered under the terms of this License including without limitation any production in the literary, scientific and artistic domain, whatever may be the mode or form of its expression including digital form, such as a book, pamphlet and other writing; a lecture, address, sermon or other work of the same nature; a dramatic or dramatico-musical work; a choreographic work or entertainment in dumb show; a musical composition with or without words; a cinematographic work to which are assimilated works expressed by a process analogous to cinematography; a work of drawing, painting, architecture, sculpture, engraving or lithography; a photographic work to which are assimilated works expressed by a process analogous to photography; a work of applied art; an illustration, map, plan, sketch or three-dimensional work relative to geography, topography, architecture or science; a performance; a broadcast; a phonogram; a compilation of data to the extent it is protected as a copyrightable work; or a work performed by a variety or circus performer to the extent it is not otherwise considered a literary or artistic work.
  6. "You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation.
  7. "Publicly Perform" means to perform public recitations of the Work and to communicate to the public those public recitations, by any means or process, including by wire or wireless means or public digital performances; to make available to the public Works in such a way that members of the public may access these Works from a place and at a place individually chosen by them; to perform the Work to the public by any means or process and the communication to the public of the performances of the Work, including by public digital performance; to broadcast and rebroadcast the Work by any means including signs, sounds or images.
  8. "Reproduce" means to make copies of the Work by any means including without limitation by sound or visual recordings and the right of fixation and reproducing fixations of the Work, including storage of a protected performance or phonogram in digital form or other electronic medium.

2. Fair Dealing Rights. Nothing in this License is intended to reduce, limit, or restrict any uses free from copyright or rights arising from limitations or exceptions that are provided for in connection with the copyright protection under copyright law or other applicable laws.

3. License Grant. Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below:

  1. to Reproduce the Work, to incorporate the Work into one or more Collections, and to Reproduce the Work as incorporated in the Collections;
  2. to create and Reproduce Adaptations provided that any such Adaptation, including any translation in any medium, takes reasonable steps to clearly label, demarcate or otherwise identify that changes were made to the original Work. For example, a translation could be marked "The original work was translated from English to Spanish," or a modification could indicate "The original work has been modified.";
  3. to Distribute and Publicly Perform the Work including as incorporated in Collections; and,
  4. to Distribute and Publicly Perform Adaptations.

  5. For the avoidance of doubt:

    1. Non-waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme cannot be waived, the Licensor reserves the exclusive right to collect such royalties for any exercise by You of the rights granted under this License;
    2. Waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme can be waived, the Licensor waives the exclusive right to collect such royalties for any exercise by You of the rights granted under this License; and,
    3. Voluntary License Schemes. The Licensor waives the right to collect royalties, whether individually or, in the event that the Licensor is a member of a collecting society that administers voluntary licensing schemes, via that society, from any exercise by You of the rights granted under this License.

The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. Subject to Section 8(f), all rights not expressly granted by Licensor are hereby reserved.

4. Restrictions. The license granted in Section 3 above is expressly made subject to and limited by the following restrictions:

  1. You may Distribute or Publicly Perform the Work only under the terms of this License. You must include a copy of, or the Uniform Resource Identifier (URI) for, this License with every copy of the Work You Distribute or Publicly Perform. You may not offer or impose any terms on the Work that restrict the terms of this License or the ability of the recipient of the Work to exercise the rights granted to that recipient under the terms of the License. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties with every copy of the Work You Distribute or Publicly Perform. When You Distribute or Publicly Perform the Work, You may not impose any effective technological measures on the Work that restrict the ability of a recipient of the Work from You to exercise the rights granted to that recipient under the terms of the License. This Section 4(a) applies to the Work as incorporated in a Collection, but this does not require the Collection apart from the Work itself to be made subject to the terms of this License. If You create a Collection, upon notice from any Licensor You must, to the extent practicable, remove from the Collection any credit as required by Section 4(b), as requested. If You create an Adaptation, upon notice from any Licensor You must, to the extent practicable, remove from the Adaptation any credit as required by Section 4(b), as requested.
  2. If You Distribute, or Publicly Perform the Work or any Adaptations or Collections, You must, unless a request has been made pursuant to Section 4(a), keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or if the Original Author and/or Licensor designate another party or parties (e.g., a sponsor institute, publishing entity, journal) for attribution ("Attribution Parties") in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; (ii) the title of the Work if supplied; (iii) to the extent reasonably practicable, the URI, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and (iv) , consistent with Section 3(b), in the case of an Adaptation, a credit identifying the use of the Work in the Adaptation (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). The credit required by this Section 4 (b) may be implemented in any reasonable manner; provided, however, that in the case of a Adaptation or Collection, at a minimum such credit will appear, if a credit for all contributing authors of the Adaptation or Collection appears, then as part of these credits and in a manner at least as prominent as the credits for the other contributing authors. For the avoidance of doubt, You may only use the credit required by this Section for the purpose of attribution in the manner set out above and, by exercising Your rights under this License, You may not implicitly or explicitly assert or imply any connection with, sponsorship or endorsement by the Original Author, Licensor and/or Attribution Parties, as appropriate, of You or Your use of the Work, without the separate, express prior written permission of the Original Author, Licensor and/or Attribution Parties.
  3. Except as otherwise agreed in writing by the Licensor or as may be otherwise permitted by applicable law, if You Reproduce, Distribute or Publicly Perform the Work either by itself or as part of any Adaptations or Collections, You must not distort, mutilate, modify or take other derogatory action in relation to the Work which would be prejudicial to the Original Author's honor or reputation. Licensor agrees that in those jurisdictions (e.g. Japan), in which any exercise of the right granted in Section 3(b) of this License (the right to make Adaptations) would be deemed to be a distortion, mutilation, modification or other derogatory action prejudicial to the Original Author's honor and reputation, the Licensor will waive or not assert, as appropriate, this Section, to the fullest extent permitted by the applicable national law, to enable You to reasonably exercise Your right under Section 3(b) of this License (right to make Adaptations) but not otherwise.

5. Representations, Warranties and Disclaimer

UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.

6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

7. Termination.

  1. This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Adaptations or Collections from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License.
  2. Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above.

8. Miscellaneous

  1. Each time You Distribute or Publicly Perform the Work or a Collection, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License.
  2. Each time You Distribute or Publicly Perform an Adaptation, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License.
  3. If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
  4. No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent
  5. This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You.
  6. The rights granted under, and the subject matter referenced, in this License were drafted utilizing the terminology of the Berne Convention for the Protection of Literary and Artistic Works (as amended on September 28, 1979), the Rome Convention of 1961, the WIPO Copyright Treaty of 1996, the WIPO Performances and Phonograms Treaty of 1996 and the Universal Copyright Convention (as revised on July 24, 1971). These rights and subject matter take effect in the relevant jurisdiction in which the License terms are sought to be enforced according to the corresponding provisions of the implementation of those treaty provisions in the applicable national law. If the standard suite of rights granted under applicable copyright law includes additional rights not granted under this License, such additional rights are deemed to be included in the License; this License is not intended to restrict the license of any rights under applicable law.


  • « Creative Commons Attribution 3.0
  • Function and Method listing »
  • PHP Manual
  • Appendices
  • Index listing

Index listing

Table of Contents

  • Function and Method listing
  • Example listing


Function and Method listing

List of all the functions and methods in the manual

a b c d e f g h i j k l m n o p q r s t u v w x y z _

  • a
    • abs - Absolute value
    • acos - Arc cosine
    • acosh - Inverse hyperbolic cosine
    • addcslashes - Quote string with slashes in a C style
    • addslashes - Quote string with slashes
    • apache_child_terminate - Terminate apache process after this request
    • apache_getenv - Get an Apache subprocess_env variable
    • apache_get_modules - Get a list of loaded Apache modules
    • apache_get_version - Fetch Apache version
    • apache_lookup_uri - Perform a partial request for the specified URI and return all info about it
    • apache_note - Get and set apache request notes
    • apache_request_headers - Fetch all HTTP request headers
    • apache_reset_timeout - Reset the Apache write timer
    • apache_response_headers - Fetch all HTTP response headers
    • apache_setenv - Set an Apache subprocess_env variable
    • APCIterator::current - Get current item
    • APCIterator::getTotalCount - Get total count
    • APCIterator::getTotalHits - Get total cache hits
    • APCIterator::getTotalSize - Get total cache size
    • APCIterator::key - Get iterator key
    • APCIterator::next - Move pointer to next item
    • APCIterator::rewind - Rewinds iterator
    • APCIterator::valid - Checks if current position is valid
    • APCIterator::__construct - Constructs an APCIterator 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
    • APCUIterator::__construct - Constructs an APCUIterator iterator object
    • 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_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_sma_info - Retrieves APCu Shared Memory Allocation information
    • apcu_store - Cache a variable in the data store
    • apc_add - Cache a new variable in the data store
    • apc_bin_dump - Get a binary dump of the given files and user variables
    • apc_bin_dumpfile - Output a binary dump of cached files and user variables to a file
    • apc_bin_load - Load a binary dump into the APC file/user cache
    • apc_bin_loadfile - Load a binary dump from a file into the APC file/user cache
    • apc_cache_info - Retrieves cached information from APC's data store
    • apc_cas - Updates an old value with a new value
    • apc_clear_cache - Clears the APC cache
    • apc_compile_file - Stores a file in the bytecode cache, bypassing all filters
    • apc_dec - Decrease a stored number
    • apc_define_constants - Defines a set of constants for retrieval and mass-definition
    • apc_delete - Removes a stored variable from the cache
    • apc_delete_file - Deletes files from the opcode cache
    • apc_exists - Checks if APC key exists
    • apc_fetch - Fetch a stored variable from the cache
    • apc_inc - Increase a stored number
    • apc_load_constants - Loads a set of constants from the cache
    • apc_sma_info - Retrieves APC's Shared Memory Allocation information
    • apc_store - Cache a variable in the data store
    • apd_breakpoint - Stops the interpreter and waits on a CR from the socket
    • apd_callstack - Returns the current call stack as an array
    • apd_clunk - Throw a warning and a callstack
    • apd_continue - Restarts the interpreter
    • apd_croak - Throw an error, a callstack and then exit
    • apd_dump_function_table - Outputs the current function table
    • apd_dump_persistent_resources - Return all persistent resources as an array
    • apd_dump_regular_resources - Return all current regular resources as an array
    • apd_echo - Echo to the debugging socket
    • apd_get_active_symbols - Get an array of the current variables names in the local scope
    • apd_set_pprof_trace - Starts the session debugging
    • apd_set_session - Changes or sets the current debugging level
    • apd_set_session_trace - Starts the session debugging
    • apd_set_session_trace_socket - Starts the remote session debugging
    • AppendIterator::append - Appends an iterator
    • AppendIterator::current - Gets the current value
    • AppendIterator::getArrayIterator - Gets the ArrayIterator
    • AppendIterator::getInnerIterator - Gets the inner iterator
    • AppendIterator::getIteratorIndex - Gets an index of iterators
    • AppendIterator::key - Gets the current key
    • AppendIterator::next - Moves to the next element
    • AppendIterator::rewind - Rewinds the Iterator
    • AppendIterator::valid - Checks validity of the current element
    • AppendIterator::__construct - Constructs an AppendIterator
    • array - Create an array
    • 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
    • ArrayIterator::append - Append an element
    • ArrayIterator::asort - Sort array by values
    • ArrayIterator::count - Count elements
    • ArrayIterator::current - Return current array entry
    • ArrayIterator::getArrayCopy - Get array copy
    • ArrayIterator::getFlags - Get behavior flags
    • ArrayIterator::key - Return current array key
    • ArrayIterator::ksort - Sort array by keys
    • ArrayIterator::natcasesort - Sort an array naturally, case insensitive
    • ArrayIterator::natsort - Sort an array naturally
    • ArrayIterator::next - Move to next entry
    • ArrayIterator::offsetExists - Check if offset exists
    • ArrayIterator::offsetGet - Get value for an offset
    • ArrayIterator::offsetSet - Set value for an offset
    • ArrayIterator::offsetUnset - Unset value for an offset
    • ArrayIterator::rewind - Rewind array back to the start
    • ArrayIterator::seek - Seek to position
    • ArrayIterator::serialize - Serialize
    • ArrayIterator::setFlags - Set behaviour flags
    • ArrayIterator::uasort - Sort with a user-defined comparison function and maintain index association
    • ArrayIterator::uksort - Sort by keys using a user-defined comparison function
    • ArrayIterator::unserialize - Unserialize
    • ArrayIterator::valid - Check whether array contains more entries
    • ArrayIterator::__construct - Construct an ArrayIterator
    • ArrayObject::append - Appends the value
    • ArrayObject::asort - Sort the entries by value
    • ArrayObject::count - Get the number of public properties in the ArrayObject
    • ArrayObject::exchangeArray - Exchange the array for another one
    • ArrayObject::getArrayCopy - Creates a copy of the ArrayObject
    • ArrayObject::getFlags - Gets the behavior flags
    • ArrayObject::getIterator - Create a new iterator from an ArrayObject instance
    • ArrayObject::getIteratorClass - Gets the iterator classname for the ArrayObject
    • ArrayObject::ksort - Sort the entries by key
    • ArrayObject::natcasesort - Sort an array using a case insensitive "natural order" algorithm
    • ArrayObject::natsort - Sort entries using a "natural order" algorithm
    • ArrayObject::offsetExists - Returns whether the requested index exists
    • ArrayObject::offsetGet - Returns the value at the specified index
    • ArrayObject::offsetSet - Sets the value at the specified index to newval
    • ArrayObject::offsetUnset - Unsets the value at the specified index
    • ArrayObject::serialize - Serialize an ArrayObject
    • ArrayObject::setFlags - Sets the behavior flags
    • ArrayObject::setIteratorClass - Sets the iterator classname for the ArrayObject
    • ArrayObject::uasort - Sort the entries with a user-defined comparison function and maintain key association
    • ArrayObject::uksort - Sort the entries by keys using a user-defined comparison function
    • ArrayObject::unserialize - Unserialize an ArrayObject
    • ArrayObject::__construct - Construct a new array object
    • array_change_key_case - Changes the case of all keys in an array
    • array_chunk - Split an array into chunks
    • array_column - Return the values from a single column in the input array
    • array_combine - Creates an array by using one array for keys and another for its values
    • array_count_values - Counts all the values of an array
    • array_diff - Computes the difference of arrays
    • array_diff_assoc - Computes the difference of arrays with additional index check
    • array_diff_key - Computes the difference of arrays using keys for comparison
    • array_diff_uassoc - Computes the difference of arrays with additional index check which is performed by a user supplied callback function
    • array_diff_ukey - Computes the difference of arrays using a callback function on the keys for comparison
    • array_fill - Fill an array with values
    • array_fill_keys - Fill an array with values, specifying keys
    • array_filter - Filters elements of an array using a callback function
    • array_flip - Exchanges all keys with their associated values in an array
    • array_intersect - Computes the intersection of arrays
    • array_intersect_assoc - Computes the intersection of arrays with additional index check
    • array_intersect_key - Computes the intersection of arrays using keys for comparison
    • array_intersect_uassoc - Computes the intersection of arrays with additional index check, compares indexes by a callback function
    • array_intersect_ukey - Computes the intersection of arrays using a callback function on the keys for comparison
    • array_keys - Return all the keys or a subset of the keys of an array
    • array_key_exists - Checks if the given key or index exists in the array
    • array_key_first - Gets the first key of an array
    • array_key_last - Gets the last key of an array
    • array_map - Applies the callback to the elements of the given arrays
    • array_merge - Merge one or more arrays
    • array_merge_recursive - Merge one or more arrays recursively
    • array_multisort - Sort multiple or multi-dimensional arrays
    • array_pad - Pad array to the specified length with a value
    • array_pop - Pop the element off the end of array
    • array_product - Calculate the product of values in an array
    • array_push - Push one or more elements onto the end of array
    • array_rand - Pick one or more random keys out of an array
    • array_reduce - Iteratively reduce the array to a single value using a callback function
    • array_replace - Replaces elements from passed arrays into the first array
    • array_replace_recursive - Replaces elements from passed arrays into the first array recursively
    • array_reverse - Return an array with elements in reverse order
    • array_search - Searches the array for a given value and returns the first corresponding key if successful
    • array_shift - Shift an element off the beginning of array
    • array_slice - Extract a slice of the array
    • array_splice - Remove a portion of the array and replace it with something else
    • array_sum - Calculate the sum of values in an array
    • array_udiff - Computes the difference of arrays by using a callback function for data comparison
    • array_udiff_assoc - Computes the difference of arrays with additional index check, compares data by a callback function
    • array_udiff_uassoc - Computes the difference of arrays with additional index check, compares data and indexes by a callback function
    • array_uintersect - Computes the intersection of arrays, compares data by a callback function
    • array_uintersect_assoc - Computes the intersection of arrays with additional index check, compares data by a callback function
    • array_uintersect_uassoc - Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions
    • array_unique - Removes duplicate values from an array
    • array_unshift - Prepend one or more elements to the beginning of an array
    • array_values - Return all the values of an array
    • array_walk - Apply a user supplied function to every member of an array
    • array_walk_recursive - Apply a user function recursively to every member of an array
    • arsort - Sort an array in reverse order and maintain index association
    • asin - Arc sine
    • asinh - Inverse hyperbolic sine
    • asort - Sort an array and maintain index association
    • assert - Checks if assertion is FALSE
    • assert_options - Set/get the various assert flags
    • atan - Arc tangent
    • atan2 - Arc tangent of two variables
    • atanh - Inverse hyperbolic tangent
  • b
    • base64_decode - Decodes data encoded with MIME base64
    • base64_encode - Encodes data with MIME base64
    • basename - Returns trailing name component of path
    • BaseResult::getWarnings - Fetch warnings from last operation
    • BaseResult::getWarningsCount - Fetch warning count from last operation
    • base_convert - Convert a number between arbitrary bases
    • bbcode_add_element - Adds a bbcode element
    • bbcode_add_smiley - Adds a smiley to the parser
    • bbcode_create - Create a BBCode Resource
    • bbcode_destroy - Close BBCode_container resource
    • bbcode_parse - Parse a string following a given rule set
    • bbcode_set_arg_parser - Attach another parser in order to use another rule set for argument parsing
    • bbcode_set_flags - Set or alter parser options
    • bcadd - Add two arbitrary precision numbers
    • bccomp - Compare two arbitrary precision numbers
    • bcdiv - Divide two arbitrary precision numbers
    • bcmod - Get modulus of an arbitrary precision number
    • bcmul - Multiply two arbitrary precision numbers
    • bcompiler_load - Reads and creates classes from a bz compressed file
    • bcompiler_load_exe - Reads and creates classes from a bcompiler exe file
    • bcompiler_parse_class - Reads the bytecodes of a class and calls back to a user function
    • bcompiler_read - Reads and creates classes from a filehandle
    • bcompiler_write_class - Writes a defined class as bytecodes
    • bcompiler_write_constant - Writes a defined constant as bytecodes
    • bcompiler_write_exe_footer - Writes the start pos, and sig to the end of a exe type file
    • bcompiler_write_file - Writes a php source file as bytecodes
    • bcompiler_write_footer - Writes the single character \x00 to indicate End of compiled data
    • bcompiler_write_function - Writes a defined function as bytecodes
    • bcompiler_write_functions_from_file - Writes all functions defined in a file as bytecodes
    • bcompiler_write_header - Writes the bcompiler header
    • bcompiler_write_included_filename - Writes an included file as bytecodes
    • bcpow - Raise an arbitrary precision number to another
    • bcpowmod - Raise an arbitrary precision number to another, reduced by a specified modulus
    • 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
    • bin2hex - Convert binary data into hexadecimal representation
    • bindec - Binary to decimal
    • bindtextdomain - Sets the path for a domain
    • bind_textdomain_codeset - Specify the character encoding in which the messages from the DOMAIN message catalog will be returned
    • blenc_encrypt - Encrypt a PHP script with BLENC
    • boolval - Get the boolean value of a variable
    • bson_decode - Deserializes a BSON object into a PHP array
    • bson_encode - Serializes a PHP variable into a BSON string
    • 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 - Force a write of all buffered data
    • bzopen - Opens a bzip2 compressed file
    • bzread - Binary safe bzip2 file read
    • bzwrite - Binary safe bzip2 file write
  • c
    • CachingIterator::count - The number of elements in the iterator
    • CachingIterator::current - Return the current element
    • CachingIterator::getCache - Retrieve the contents of the cache
    • CachingIterator::getFlags - Get flags used
    • CachingIterator::getInnerIterator - Returns the inner iterator
    • CachingIterator::hasNext - Check whether the inner iterator has a valid next element
    • CachingIterator::key - Return the key for the current element
    • CachingIterator::next - Move the iterator forward
    • CachingIterator::offsetExists - The offsetExists purpose
    • CachingIterator::offsetGet - The offsetGet purpose
    • CachingIterator::offsetSet - The offsetSet purpose
    • CachingIterator::offsetUnset - The offsetUnset purpose
    • CachingIterator::rewind - Rewind the iterator
    • CachingIterator::setFlags - The setFlags purpose
    • CachingIterator::valid - Check whether the current element is valid
    • CachingIterator::__construct - Construct a new CachingIterator object for the iterator
    • CachingIterator::__toString - Return the string representation of the current element
    • Cairo::availableFonts - Retrieves the availables font types
    • Cairo::availableSurfaces - Retrieves all available surfaces
    • Cairo::statusToString - Retrieves the current status as string
    • Cairo::version - Retrieves cairo's library version
    • Cairo::versionString - Retrieves cairo version as string
    • CairoContext::appendPath - Appends a path to current path
    • CairoContext::arc - Adds a circular arc
    • CairoContext::arcNegative - Adds a negative arc
    • CairoContext::clip - Establishes a new clip region
    • CairoContext::clipExtents - Computes the area inside the current clip
    • CairoContext::clipPreserve - Establishes a new clip region from the current clip
    • CairoContext::clipRectangleList - Retrieves the current clip as a list of rectangles
    • CairoContext::closePath - Closes the current path
    • CairoContext::copyPage - Emits the current page
    • CairoContext::copyPath - Creates a copy of the current path
    • CairoContext::copyPathFlat - Gets a flattened copy of the current path
    • CairoContext::curveTo - Adds a curve
    • CairoContext::deviceToUser - Transform a coordinate
    • CairoContext::deviceToUserDistance - Transform a distance
    • CairoContext::fill - Fills the current path
    • CairoContext::fillExtents - Computes the filled area
    • CairoContext::fillPreserve - Fills and preserve the current path
    • CairoContext::fontExtents - Get the font extents
    • CairoContext::getAntialias - Retrieves the current antialias mode
    • CairoContext::getCurrentPoint - The getCurrentPoint purpose
    • CairoContext::getDash - The getDash purpose
    • CairoContext::getDashCount - The getDashCount purpose
    • CairoContext::getFillRule - The getFillRule purpose
    • CairoContext::getFontFace - The getFontFace purpose
    • CairoContext::getFontMatrix - The getFontMatrix purpose
    • CairoContext::getFontOptions - The getFontOptions purpose
    • CairoContext::getGroupTarget - The getGroupTarget purpose
    • CairoContext::getLineCap - The getLineCap purpose
    • CairoContext::getLineJoin - The getLineJoin purpose
    • CairoContext::getLineWidth - The getLineWidth purpose
    • CairoContext::getMatrix - The getMatrix purpose
    • CairoContext::getMiterLimit - The getMiterLimit purpose
    • CairoContext::getOperator - The getOperator purpose
    • CairoContext::getScaledFont - The getScaledFont purpose
    • CairoContext::getSource - The getSource purpose
    • CairoContext::getTarget - The getTarget purpose
    • CairoContext::getTolerance - The getTolerance purpose
    • CairoContext::glyphPath - The glyphPath purpose
    • CairoContext::hasCurrentPoint - The hasCurrentPoint purpose
    • CairoContext::identityMatrix - The identityMatrix purpose
    • CairoContext::inFill - The inFill purpose
    • CairoContext::inStroke - The inStroke purpose
    • CairoContext::lineTo - The lineTo purpose
    • CairoContext::mask - The mask purpose
    • CairoContext::maskSurface - The maskSurface purpose
    • CairoContext::moveTo - The moveTo purpose
    • CairoContext::newPath - The newPath purpose
    • CairoContext::newSubPath - The newSubPath purpose
    • CairoContext::paint - The paint purpose
    • CairoContext::paintWithAlpha - The paintWithAlpha purpose
    • CairoContext::pathExtents - The pathExtents purpose
    • CairoContext::popGroup - The popGroup purpose
    • CairoContext::popGroupToSource - The popGroupToSource purpose
    • CairoContext::pushGroup - The pushGroup purpose
    • CairoContext::pushGroupWithContent - The pushGroupWithContent purpose
    • CairoContext::rectangle - The rectangle purpose
    • CairoContext::relCurveTo - The relCurveTo purpose
    • CairoContext::relLineTo - The relLineTo purpose
    • CairoContext::relMoveTo - The relMoveTo purpose
    • CairoContext::resetClip - The resetClip purpose
    • CairoContext::restore - The restore purpose
    • CairoContext::rotate - The rotate purpose
    • CairoContext::save - The save purpose
    • CairoContext::scale - The scale purpose
    • CairoContext::selectFontFace - The selectFontFace purpose
    • CairoContext::setAntialias - The setAntialias purpose
    • CairoContext::setDash - The setDash purpose
    • CairoContext::setFillRule - The setFillRule purpose
    • CairoContext::setFontFace - The setFontFace purpose
    • CairoContext::setFontMatrix - The setFontMatrix purpose
    • CairoContext::setFontOptions - The setFontOptions purpose
    • CairoContext::setFontSize - The setFontSize purpose
    • CairoContext::setLineCap - The setLineCap purpose
    • CairoContext::setLineJoin - The setLineJoin purpose
    • CairoContext::setLineWidth - The setLineWidth purpose
    • CairoContext::setMatrix - The setMatrix purpose
    • CairoContext::setMiterLimit - The setMiterLimit purpose
    • CairoContext::setOperator - The setOperator purpose
    • CairoContext::setScaledFont - The setScaledFont purpose
    • CairoContext::setSource - The setSource purpose
    • CairoContext::setSourceRGB - The setSourceRGB purpose
    • CairoContext::setSourceRGBA - The setSourceRGBA purpose
    • CairoContext::setSourceSurface - The setSourceSurface purpose
    • CairoContext::setTolerance - The setTolerance purpose
    • CairoContext::showPage - The showPage purpose
    • CairoContext::showText - The showText purpose
    • CairoContext::status - The status purpose
    • CairoContext::stroke - The stroke purpose
    • CairoContext::strokeExtents - The strokeExtents purpose
    • CairoContext::strokePreserve - The strokePreserve purpose
    • CairoContext::textExtents - The textExtents purpose
    • CairoContext::textPath - The textPath purpose
    • CairoContext::transform - The transform purpose
    • CairoContext::translate - The translate purpose
    • CairoContext::userToDevice - The userToDevice purpose
    • CairoContext::userToDeviceDistance - The userToDeviceDistance purpose
    • CairoContext::__construct - Creates a new CairoContext
    • CairoFontFace::getType - Retrieves the font face type
    • CairoFontFace::status - Check for CairoFontFace errors
    • CairoFontFace::__construct - Creates a new CairoFontFace object
    • CairoFontOptions::equal - The equal purpose
    • CairoFontOptions::getAntialias - The getAntialias purpose
    • CairoFontOptions::getHintMetrics - The getHintMetrics purpose
    • CairoFontOptions::getHintStyle - The getHintStyle purpose
    • CairoFontOptions::getSubpixelOrder - The getSubpixelOrder purpose
    • CairoFontOptions::hash - The hash purpose
    • CairoFontOptions::merge - The merge purpose
    • CairoFontOptions::setAntialias - The setAntialias purpose
    • CairoFontOptions::setHintMetrics - The setHintMetrics purpose
    • CairoFontOptions::setHintStyle - The setHintStyle purpose
    • CairoFontOptions::setSubpixelOrder - The setSubpixelOrder purpose
    • CairoFontOptions::status - The status purpose
    • CairoFontOptions::__construct - The __construct purpose
    • CairoFormat::strideForWidth - Provides an appropriate stride to use
    • CairoGradientPattern::addColorStopRgb - The addColorStopRgb purpose
    • CairoGradientPattern::addColorStopRgba - The addColorStopRgba purpose
    • CairoGradientPattern::getColorStopCount - The getColorStopCount purpose
    • CairoGradientPattern::getColorStopRgba - The getColorStopRgba purpose
    • CairoGradientPattern::getExtend - The getExtend purpose
    • CairoGradientPattern::setExtend - The setExtend purpose
    • CairoImageSurface::createForData - The createForData purpose
    • CairoImageSurface::createFromPng - Creates a new CairoImageSurface form a png image file
    • CairoImageSurface::getData - Gets the image data as string
    • CairoImageSurface::getFormat - Get the image format
    • CairoImageSurface::getHeight - Retrieves the height of the CairoImageSurface
    • CairoImageSurface::getStride - The getStride purpose
    • CairoImageSurface::getWidth - Retrieves the width of the CairoImageSurface
    • CairoImageSurface::__construct - Creates a new CairoImageSurface
    • CairoLinearGradient::getPoints - The getPoints purpose
    • CairoLinearGradient::__construct - The __construct purpose
    • CairoMatrix::initIdentity - Creates a new identity matrix
    • CairoMatrix::initRotate - Creates a new rotated matrix
    • CairoMatrix::initScale - Creates a new scaling matrix
    • CairoMatrix::initTranslate - Creates a new translation matrix
    • CairoMatrix::invert - The invert purpose
    • CairoMatrix::multiply - The multiply purpose
    • CairoMatrix::rotate - The rotate purpose
    • CairoMatrix::scale - Applies scaling to a matrix
    • CairoMatrix::transformDistance - The transformDistance purpose
    • CairoMatrix::transformPoint - The transformPoint purpose
    • CairoMatrix::translate - The translate purpose
    • CairoMatrix::__construct - Creates a new CairoMatrix object
    • CairoPattern::getMatrix - The getMatrix purpose
    • CairoPattern::getType - The getType purpose
    • CairoPattern::setMatrix - The setMatrix purpose
    • CairoPattern::status - The status purpose
    • CairoPattern::__construct - The __construct purpose
    • CairoPdfSurface::setSize - The setSize purpose
    • CairoPdfSurface::__construct - The __construct purpose
    • CairoPsSurface::dscBeginPageSetup - The dscBeginPageSetup purpose
    • CairoPsSurface::dscBeginSetup - The dscBeginSetup purpose
    • CairoPsSurface::dscComment - The dscComment purpose
    • CairoPsSurface::getEps - The getEps purpose
    • CairoPsSurface::getLevels - The getLevels purpose
    • CairoPsSurface::levelToString - The levelToString purpose
    • CairoPsSurface::restrictToLevel - The restrictToLevel purpose
    • CairoPsSurface::setEps - The setEps purpose
    • CairoPsSurface::setSize - The setSize purpose
    • CairoPsSurface::__construct - The __construct purpose
    • CairoRadialGradient::getCircles - The getCircles purpose
    • CairoRadialGradient::__construct - The __construct purpose
    • CairoScaledFont::extents - The extents purpose
    • CairoScaledFont::getCtm - The getCtm purpose
    • CairoScaledFont::getFontFace - The getFontFace purpose
    • CairoScaledFont::getFontMatrix - The getFontMatrix purpose
    • CairoScaledFont::getFontOptions - The getFontOptions purpose
    • CairoScaledFont::getScaleMatrix - The getScaleMatrix purpose
    • CairoScaledFont::getType - The getType purpose
    • CairoScaledFont::glyphExtents - The glyphExtents purpose
    • CairoScaledFont::status - The status purpose
    • CairoScaledFont::textExtents - The textExtents purpose
    • CairoScaledFont::__construct - The __construct purpose
    • CairoSolidPattern::getRgba - The getRgba purpose
    • CairoSolidPattern::__construct - The __construct purpose
    • CairoSurface::copyPage - The copyPage purpose
    • CairoSurface::createSimilar - The createSimilar purpose
    • CairoSurface::finish - The finish purpose
    • CairoSurface::flush - The flush purpose
    • CairoSurface::getContent - The getContent purpose
    • CairoSurface::getDeviceOffset - The getDeviceOffset purpose
    • CairoSurface::getFontOptions - The getFontOptions purpose
    • CairoSurface::getType - The getType purpose
    • CairoSurface::markDirty - The markDirty purpose
    • CairoSurface::markDirtyRectangle - The markDirtyRectangle purpose
    • CairoSurface::setDeviceOffset - The setDeviceOffset purpose
    • CairoSurface::setFallbackResolution - The setFallbackResolution purpose
    • CairoSurface::showPage - The showPage purpose
    • CairoSurface::status - The status purpose
    • CairoSurface::writeToPng - The writeToPng purpose
    • CairoSurface::__construct - The __construct purpose
    • CairoSurfacePattern::getExtend - The getExtend purpose
    • CairoSurfacePattern::getFilter - The getFilter purpose
    • CairoSurfacePattern::getSurface - The getSurface purpose
    • CairoSurfacePattern::setExtend - The setExtend purpose
    • CairoSurfacePattern::setFilter - The setFilter purpose
    • CairoSurfacePattern::__construct - The __construct purpose
    • CairoSvgSurface::getVersions - Used to retrieve a list of supported SVG versions
    • CairoSvgSurface::restrictToVersion - The restrictToVersion purpose
    • CairoSvgSurface::versionToString - The versionToString purpose
    • CairoSvgSurface::__construct - The __construct purpose
    • cairo_create - Returns a new CairoContext object on the requested surface
    • cairo_font_options_create - Description
    • cairo_font_options_equal - Description
    • cairo_font_options_get_antialias - Description
    • cairo_font_options_get_hint_metrics - Description
    • cairo_font_options_get_hint_style - Description
    • cairo_font_options_get_subpixel_order - Description
    • cairo_font_options_hash - Description
    • cairo_font_options_merge - Description
    • cairo_font_options_set_antialias - Description
    • cairo_font_options_set_hint_metrics - Description
    • cairo_font_options_set_hint_style - Description
    • cairo_font_options_set_subpixel_order - Description
    • cairo_font_options_status - Description
    • cairo_format_stride_for_width - Description
    • cairo_image_surface_create - Description
    • cairo_image_surface_create_for_data - Description
    • cairo_image_surface_create_from_png - Description
    • cairo_image_surface_get_data - Description
    • cairo_image_surface_get_format - Description
    • cairo_image_surface_get_height - Description
    • cairo_image_surface_get_stride - Description
    • cairo_image_surface_get_width - Description
    • cairo_matrix_create_scale - Alias of CairoMatrix::initScale
    • cairo_matrix_create_translate - Alias of CairoMatrix::initTranslate
    • cairo_matrix_invert - Description
    • cairo_matrix_multiply - Description
    • cairo_matrix_transform_distance - Description
    • cairo_matrix_transform_point - Description
    • cairo_matrix_translate - Description
    • cairo_pattern_add_color_stop_rgb - Description
    • cairo_pattern_add_color_stop_rgba - Description
    • cairo_pattern_create_for_surface - Description
    • cairo_pattern_create_linear - Description
    • cairo_pattern_create_radial - Description
    • cairo_pattern_create_rgb - Description
    • cairo_pattern_create_rgba - Description
    • cairo_pattern_get_color_stop_count - Description
    • cairo_pattern_get_color_stop_rgba - Description
    • cairo_pattern_get_extend - Description
    • cairo_pattern_get_filter - Description
    • cairo_pattern_get_linear_points - Description
    • cairo_pattern_get_matrix - Description
    • cairo_pattern_get_radial_circles - Description
    • cairo_pattern_get_rgba - Description
    • cairo_pattern_get_surface - Description
    • cairo_pattern_get_type - Description
    • cairo_pattern_set_extend - Description
    • cairo_pattern_set_filter - Description
    • cairo_pattern_set_matrix - Description
    • cairo_pattern_status - Description
    • cairo_pdf_surface_create - Description
    • cairo_pdf_surface_set_size - Description
    • cairo_ps_get_levels - Description
    • cairo_ps_level_to_string - Description
    • cairo_ps_surface_create - Description
    • cairo_ps_surface_dsc_begin_page_setup - Description
    • cairo_ps_surface_dsc_begin_setup - Description
    • cairo_ps_surface_dsc_comment - Description
    • cairo_ps_surface_get_eps - Description
    • cairo_ps_surface_restrict_to_level - Description
    • cairo_ps_surface_set_eps - Description
    • cairo_ps_surface_set_size - Description
    • cairo_scaled_font_create - Description
    • cairo_scaled_font_extents - Description
    • cairo_scaled_font_get_ctm - Description
    • cairo_scaled_font_get_font_face - Description
    • cairo_scaled_font_get_font_matrix - Description
    • cairo_scaled_font_get_font_options - Description
    • cairo_scaled_font_get_scale_matrix - Description
    • cairo_scaled_font_get_type - Description
    • cairo_scaled_font_glyph_extents - Description
    • cairo_scaled_font_status - Description
    • cairo_scaled_font_text_extents - Description
    • cairo_surface_copy_page - Description
    • cairo_surface_create_similar - Description
    • cairo_surface_finish - Description
    • cairo_surface_flush - Description
    • cairo_surface_get_content - Description
    • cairo_surface_get_device_offset - Description
    • cairo_surface_get_font_options - Description
    • cairo_surface_get_type - Description
    • cairo_surface_mark_dirty - Description
    • cairo_surface_mark_dirty_rectangle - Description
    • cairo_surface_set_device_offset - Description
    • cairo_surface_set_fallback_resolution - Description
    • cairo_surface_show_page - Description
    • cairo_surface_status - Description
    • cairo_surface_write_to_png - Description
    • cairo_svg_surface_create - Description
    • cairo_svg_surface_restrict_to_version - Description
    • cairo_svg_version_to_string - Description
    • CallbackFilterIterator::accept - Calls the callback with the current value, the current key and the inner iterator as arguments
    • CallbackFilterIterator::__construct - Create a filtered iterator from another iterator
    • call_user_func - Call the callback given by the first parameter
    • call_user_func_array - Call a callback with an array of parameters
    • call_user_method - Call a user method on an specific object
    • call_user_method_array - Call a user method given with an array of parameters
    • 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
    • ceil - Round fractions up
    • chdb::get - Gets the value associated with a key
    • chdb::__construct - Creates a chdb instance
    • chdb_create - Creates a chdb file
    • chdir - Change directory
    • checkdate - Validate a Gregorian date
    • checkdnsrr - Check DNS records corresponding to a given Internet host name or IP address
    • chgrp - Changes file group
    • chmod - Changes file mode
    • chop - Alias of rtrim
    • chown - Changes file owner
    • chr - Generate a single-byte string from a number
    • chroot - Change the root directory
    • chunk_split - Split a string into smaller chunks
    • classkit_import - Import new class method definitions from a file
    • classkit_method_add - Dynamically adds a new method to a given class
    • classkit_method_copy - Copies a method from class to another
    • classkit_method_redefine - Dynamically changes the code of the given method
    • classkit_method_remove - Dynamically removes the given method
    • classkit_method_rename - Dynamically changes the name of the given method
    • class_alias - Creates an alias for a class
    • class_exists - Checks if the class has been defined
    • class_implements - Return the interfaces which are implemented by the given class or interface
    • class_parents - Return the parent classes of the given class
    • class_uses - Return the traits used by the given class
    • clearstatcache - Clears file status cache
    • Client::getClient - Get client session
    • Client::__construct - Client constructor
    • cli_get_process_title - Returns the current process title
    • cli_set_process_title - Sets the process title
    • closedir - Close directory handle
    • closelog - Close connection to system logger
    • 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::__construct - Constructor that disallows instantiation
    • Collator::asort - Sort array maintaining index association
    • Collator::compare - Compare two Unicode strings
    • 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
    • Collator::__construct - Create a collator
    • Collectable::isGarbage - Determine whether an object has been marked as garbage
    • Collectable::setGarbage - Mark an object as garbage
    • Collection::add - Add collection document
    • Collection::addOrReplaceOne - Add or replace collection document
    • 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
    • Collection::__construct - Collection constructor
    • CollectionAdd::execute - Execute the statement
    • CollectionAdd::__construct - CollectionAdd constructor
    • CollectionFind::bind - Bind value to query placeholder
    • 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
    • CollectionFind::__construct - CollectionFind constructor
    • CollectionModify::arrayAppend - Append element to an array field
    • CollectionModify::arrayInsert - Insert element into an array field
    • CollectionModify::bind - Bind value to query placeholder
    • 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
    • CollectionModify::__construct - CollectionModify constructor
    • CollectionRemove::bind - Bind value to placeholder
    • CollectionRemove::execute - Execute remove operation
    • CollectionRemove::limit - Limit number of documents to remove
    • CollectionRemove::sort - Set the sorting criteria
    • CollectionRemove::__construct - CollectionRemove 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
    • ColumnResult::__construct - ColumnResult constructor
    • COM::__construct - COM class constructor
    • CommonMark\CQL::__construct - CQL Construction
    • CommonMark\CQL::__invoke - CQL Execution
    • CommonMark\Interfaces\IVisitable::accept - Visitation
    • CommonMark\Interfaces\IVisitor::enter - Visitation
    • CommonMark\Interfaces\IVisitor::leave - Visitation
    • CommonMark\Node::accept - Visitation
    • CommonMark\Node::appendChild - AST Manipulation
    • CommonMark\Node::insertAfter - AST Manipulation
    • CommonMark\Node::insertBefore - AST Manipulation
    • CommonMark\Node::prependChild - AST Manipulation
    • CommonMark\Node::replace - AST Manipulation
    • CommonMark\Node::unlink - AST Manipulation
    • CommonMark\Node\BulletList::__construct - BulletList Construction
    • CommonMark\Node\CodeBlock::__construct - CodeBlock Construction
    • CommonMark\Node\Heading::__construct - Heading Construction
    • CommonMark\Node\Image::__construct - Image Construction
    • CommonMark\Node\Link::__construct - Link Construction
    • CommonMark\Node\OrderedList::__construct - OrderedList Construction
    • CommonMark\Node\Text::__construct - Text Construction
    • CommonMark\Parse - Parsing
    • CommonMark\Parser::finish - Parsing
    • CommonMark\Parser::parse - Parsing
    • CommonMark\Parser::__construct - Parsing
    • CommonMark\Render - Rendering
    • CommonMark\Render\HTML - Rendering
    • CommonMark\Render\Latex - Rendering
    • CommonMark\Render\Man - Rendering
    • CommonMark\Render\XML - Rendering
    • compact - Create array containing variables and their values
    • Componere\Abstract\Definition::addInterface - Add Interface
    • Componere\Abstract\Definition::addMethod - Add Method
    • Componere\Abstract\Definition::addTrait - Add Trait
    • Componere\Abstract\Definition::getReflector - Reflection
    • Componere\cast - Casting
    • Componere\cast_by_ref - Casting
    • Componere\Definition::addConstant - Add Constant
    • Componere\Definition::addProperty - Add Property
    • Componere\Definition::getClosure - Get Closure
    • Componere\Definition::getClosures - Get Closures
    • Componere\Definition::isRegistered - State Detection
    • Componere\Definition::register - Registration
    • Componere\Definition::__construct - Definition Construction
    • Componere\Method::getReflector - Reflection
    • Componere\Method::setPrivate - Accessibility Modification
    • Componere\Method::setProtected - Accessibility Modification
    • Componere\Method::setStatic - Accessibility Modification
    • Componere\Method::__construct - Method Construction
    • Componere\Patch::apply - Application
    • Componere\Patch::derive - Patch Derivation
    • Componere\Patch::getClosure - Get Closure
    • Componere\Patch::getClosures - Get Closures
    • Componere\Patch::isApplied - State Detection
    • Componere\Patch::revert - Reversal
    • Componere\Patch::__construct - Patch Construction
    • Componere\Value::hasDefault - Value Interaction
    • Componere\Value::isPrivate - Accessibility Detection
    • Componere\Value::isProtected - Accessibility Detection
    • Componere\Value::isStatic - Accessibility Detection
    • Componere\Value::setPrivate - Accessibility Modification
    • Componere\Value::setProtected - Accessibility Modification
    • Componere\Value::setStatic - Accessibility Modification
    • Componere\Value::__construct - Value Construction
    • com_create_guid - Generate a globally unique identifier (GUID)
    • com_event_sink - Connect events from a COM object to a PHP object
    • com_get_active_object - Returns a handle to an already running instance of a COM object
    • com_load_typelib - Loads a Typelib
    • com_message_pump - Process COM messages, sleeping for up to timeoutms milliseconds
    • com_print_typeinfo - Print out a PHP class definition for a dispatchable interface
    • Cond::broadcast - Broadcast a Condition
    • Cond::create - Create a Condition
    • Cond::destroy - Destroy a Condition
    • Cond::signal - Signal a Condition
    • Cond::wait - Wait for Condition
    • connection_aborted - Check whether client disconnected
    • connection_status - Returns connection status bitfield
    • constant - Returns the value of a constant
    • Constants for PDO_4D - Constants for PDO_4D
    • Context parameters - Context parameter listing
    • convert_cyr_string - Convert from one Cyrillic character set to another
    • convert_uudecode - Decode a uuencoded string
    • convert_uuencode - Uuencode a string
    • copy - Copies file
    • cos - Cosine
    • cosh - Hyperbolic cosine
    • count - Count all elements in an array, or something in an object
    • Countable::count - Count elements of an object
    • Counter::bumpValue - Change the current value of a counter
    • Counter::getMeta - Return a piece of metainformation about a counter
    • Counter::getNamed - Retrieve an existing named counter
    • Counter::getValue - Get the current value of a counter
    • Counter::resetValue - Reset the current value of a counter
    • Counter::setCounterClass - Set the class returned by Counter::getNamed
    • Counter::__construct - Creates an instance of a Counter which maintains a single numeric value
    • counter_bump - Update the current value of the basic counter
    • counter_bump_value - Change the current value of a counter resource
    • counter_create - Creates a counter which maintains a single numeric value
    • counter_get - Get the current value of the basic counter
    • counter_get_meta - Return a piece of metainformation about a counter resource
    • counter_get_named - Retrieve an existing named counter as a resource
    • counter_get_value - Get the current value of a counter resource
    • counter_reset - Reset the current value of the basic counter
    • counter_reset_value - Reset the current value of a counter resource
    • count_chars - Return information about characters used in a string
    • crack_check - Performs an obscure check with the given password
    • crack_closedict - Closes an open CrackLib dictionary
    • crack_getlastmessage - Returns the message from the last obscure check
    • crack_opendict - Opens a new CrackLib dictionary
    • crc32 - Calculates the crc32 polynomial of a string
    • create_function - Create an anonymous (lambda-style) function
    • CrudOperationBindable::bind - Bind value to placeholder
    • CrudOperationLimitable::limit - Set result limit
    • CrudOperationSkippable::skip - Number of operations to skip
    • CrudOperationSortable::sort - Sort results
    • crypt - One-way string hashing
    • ctype_alnum - Check for alphanumeric character(s)
    • ctype_alpha - Check for alphabetic character(s)
    • ctype_cntrl - Check for control character(s)
    • ctype_digit - Check for numeric character(s)
    • ctype_graph - Check for any printable character(s) except space
    • ctype_lower - Check for lowercase character(s)
    • ctype_print - Check for printable character(s)
    • ctype_punct - Check for any printable character which is not whitespace or an alphanumeric character
    • ctype_space - Check for whitespace character(s)
    • ctype_upper - Check for uppercase character(s)
    • ctype_xdigit - Check for character(s) representing a hexadecimal digit
    • cubrid_affected_rows - Return the number of rows affected by the last SQL statement
    • cubrid_bind - Bind variables to a prepared statement as parameters
    • cubrid_client_encoding - Return the current CUBRID connection charset
    • cubrid_close - Close CUBRID connection
    • cubrid_close_prepare - Close the request handle
    • cubrid_close_request - Close the request handle
    • cubrid_column_names - Get the column names in result
    • cubrid_column_types - Get column types in result
    • 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_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_data_seek - Move the internal row pointer of the CUBRID result
    • cubrid_db_name - Get db name from results of cubrid_list_dbs
    • cubrid_disconnect - Close a database connection
    • cubrid_drop - Delete an instance using OID
    • cubrid_errno - Return the numerical value of the error message from previous CUBRID operation
    • cubrid_error - Get the error message
    • 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_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_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_list_dbs - Return an array with the list of all existing CUBRID databases
    • cubrid_load_from_glo - Read data from a GLO instance and save it in a file
    • 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_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_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_new_glo - Create a glo instance
    • 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_fields - 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_ping - Ping a server connection or reconnect if there is no connection
    • cubrid_prepare - Prepare a SQL statement for execution
    • cubrid_put - Update a column using OID
    • 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_rollback - Roll back a transaction
    • cubrid_save_to_glo - Save requested file in a GLO instance
    • cubrid_schema - Get the requested schema information
    • cubrid_send_glo - Read data from glo and send it to std output
    • 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_unbuffered_query - Perform a query without fetching the results into memory
    • cubrid_version - Get the CUBRID PHP module's version
    • CURL context options - CURL context option listing
    • CURLFile::getFilename - Get file name
    • CURLFile::getMimeType - Get MIME type
    • CURLFile::getPostFilename - Get file name for POST
    • CURLFile::setMimeType - Set MIME type
    • CURLFile::setPostFilename - Set file name for POST
    • CURLFile::__construct - Create a CURLFile object
    • CURLFile::__wakeup - Unserialization handler
    • curl_close - Close a cURL session
    • curl_copy_handle - Copy a cURL handle along with all of its preferences
    • curl_errno - Return the last error number
    • curl_error - Return a string containing the last error for the current session
    • curl_escape - URL encodes the given string
    • curl_exec - Perform a cURL session
    • curl_getinfo - Get information regarding a specific transfer
    • curl_init - Initialize a cURL session
    • curl_multi_add_handle - Add a normal cURL handle to a cURL multi handle
    • curl_multi_close - Close a set of cURL handles
    • curl_multi_errno - Return the last multi curl error number
    • curl_multi_exec - Run the sub-connections of the current cURL handle
    • curl_multi_getcontent - Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set
    • curl_multi_info_read - Get information about the current transfers
    • curl_multi_init - Returns a new cURL multi handle
    • curl_multi_remove_handle - Remove a multi handle from a set of cURL handles
    • curl_multi_select - Wait for activity on any curl_multi connection
    • curl_multi_setopt - Set an option for the cURL multi handle
    • curl_multi_strerror - Return string describing error code
    • curl_pause - Pause and unpause a connection
    • curl_reset - Reset all options of a libcurl session handle
    • curl_setopt - Set an option for a cURL transfer
    • curl_setopt_array - Set multiple options for a cURL transfer
    • curl_share_close - Close a cURL share handle
    • curl_share_errno - Return the last share curl error number
    • curl_share_init - Initialize a cURL share handle
    • curl_share_setopt - Set an option for a cURL share handle
    • curl_share_strerror - Return string describing the given error code
    • curl_strerror - Return string describing the given error code
    • curl_unescape - Decodes the given URL encoded string
    • curl_version - Gets cURL version information
    • current - Return the current element in an array
    • cyrus_authenticate - Authenticate against a Cyrus IMAP server
    • cyrus_bind - Bind callbacks to a Cyrus IMAP connection
    • cyrus_close - Close connection to a Cyrus IMAP server
    • cyrus_connect - Connect to a Cyrus IMAP server
    • cyrus_query - Send a query to a Cyrus IMAP server
    • cyrus_unbind - Unbind ...
  • d
    • data:// - Data (RFC 2397)
    • DatabaseObject::existsInDatabase - Check if object exists in database
    • DatabaseObject::getName - Get object name
    • DatabaseObject::getSession - Get session name
    • date - Format a local time/date
    • DateInterval::createFromDateString - Sets up a DateInterval from the relative parts of the string
    • DateInterval::format - Formats the interval
    • DateInterval::__construct - Creates a new DateInterval object
    • DatePeriod::getDateInterval - Gets the interval
    • DatePeriod::getEndDate - Gets the end date
    • DatePeriod::getRecurrences - Gets the number of recurrences
    • DatePeriod::getStartDate - Gets the start date
    • DatePeriod::__construct - Creates a new DatePeriod object
    • DateTime::add - Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
    • DateTime::createFromFormat - Parses a time string according to a specified format
    • DateTime::createFromImmutable - Returns new DateTime object encapsulating the given DateTimeImmutable object
    • DateTime::diff - Returns the difference between two DateTime objects
    • DateTime::format - Returns date formatted according to given format
    • DateTime::getLastErrors - Returns the warnings and errors
    • DateTime::getOffset - Returns the timezone offset
    • DateTime::getTimestamp - Gets the Unix timestamp
    • DateTime::getTimezone - Return time zone relative to given DateTime
    • DateTime::modify - Alters the timestamp
    • 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
    • DateTime::__construct - Returns new DateTime object
    • DateTime::__set_state - The __set_state handler
    • DateTime::__wakeup - The __wakeup handler
    • DateTimeImmutable::add - Adds an amount of days, months, years, hours, minutes and seconds
    • DateTimeImmutable::createFromFormat - Parses a time string according to a specified format
    • DateTimeImmutable::createFromMutable - Returns new DateTimeImmutable object encapsulating the given DateTime object
    • DateTimeImmutable::getLastErrors - Returns the warnings and errors
    • DateTimeImmutable::modify - Creates a new object with modified timestamp
    • 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
    • DateTimeImmutable::__construct - Returns new DateTimeImmutable object
    • DateTimeImmutable::__set_state - The __set_state handler
    • 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
    • DateTimeZone::__construct - Creates new DateTimeZone object
    • date_add - Alias of DateTime::add
    • date_create - Alias of DateTime::__construct
    • date_create_from_format - Alias of DateTime::createFromFormat
    • date_create_immutable - Alias of DateTimeImmutable::__construct
    • 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 DateTime::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
    • date_parse_from_format - Get info about given date formatted according to the specified format
    • date_sub - Alias of DateTime::sub
    • 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_sun_info - Returns an array with information about sunset/sunrise and twilight begin/end
    • 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
    • date_time_set - Alias of DateTime::setTime
    • 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_columns - Returns a result set listing the columns and associated metadata for a table
    • db2_column_privileges - Returns a result set listing the columns and associated privileges for a table
    • db2_commit - Commits a transaction
    • db2_connect - Returns a connection to a database
    • 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_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_procedures - Returns a result set listing the stored procedures registered in a database
    • db2_procedure_columns - Returns a result set listing stored procedure parameters
    • 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_tables - Returns a result set listing the tables and associated metadata in a database
    • db2_table_privileges - Returns a result set listing the tables and associated privileges in a database
    • 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
    • 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
    • dbplus_add - Add a tuple to a relation
    • dbplus_aql - Perform AQL query
    • dbplus_chdir - Get/Set database virtual current directory
    • dbplus_close - Close a relation
    • dbplus_curr - Get current tuple from relation
    • dbplus_errcode - Get error string for given errorcode or last error
    • dbplus_errno - Get error code for last operation
    • dbplus_find - Set a constraint on a relation
    • dbplus_first - Get first tuple from relation
    • dbplus_flush - Flush all changes made on a relation
    • dbplus_freealllocks - Free all locks held by this client
    • dbplus_freelock - Release write lock on tuple
    • dbplus_freerlocks - Free all tuple locks on given relation
    • dbplus_getlock - Get a write lock on a tuple
    • dbplus_getunique - Get an id number unique to a relation
    • dbplus_info - Get information about a relation
    • dbplus_last - Get last tuple from relation
    • dbplus_lockrel - Request write lock on relation
    • dbplus_next - Get next tuple from relation
    • dbplus_open - Open relation file
    • dbplus_prev - Get previous tuple from relation
    • dbplus_rchperm - Change relation permissions
    • dbplus_rcreate - Creates a new DB++ relation
    • dbplus_rcrtexact - Creates an exact but empty copy of a relation including indices
    • dbplus_rcrtlike - Creates an empty copy of a relation with default indices
    • dbplus_resolve - Resolve host information for relation
    • dbplus_restorepos - Restore position
    • dbplus_rkeys - Specify new primary key for a relation
    • dbplus_ropen - Open relation file local
    • dbplus_rquery - Perform local (raw) AQL query
    • dbplus_rrename - Rename a relation
    • dbplus_rsecindex - Create a new secondary index for a relation
    • dbplus_runlink - Remove relation from filesystem
    • dbplus_rzap - Remove all tuples from relation
    • dbplus_savepos - Save position
    • dbplus_setindex - Set index
    • dbplus_setindexbynumber - Set index by number
    • dbplus_sql - Perform SQL query
    • dbplus_tcl - Execute TCL code on server side
    • dbplus_tremove - Remove tuple and return new current tuple
    • dbplus_undo - Undo
    • dbplus_undoprepare - Prepare undo
    • dbplus_unlockrel - Give up write lock on relation
    • dbplus_unselect - Remove a constraint from relation
    • dbplus_update - Update specified tuple in relation
    • dbplus_xlockrel - Request exclusive lock on relation
    • dbplus_xunlockrel - Free exclusive lock on relation
    • dbx_close - Close an open connection/database
    • dbx_compare - Compare two rows for sorting purposes
    • dbx_connect - Open a connection/database
    • dbx_error - Report the error message of the latest function call in the module
    • dbx_escape_string - Escape a string so it can safely be used in an sql-statement
    • dbx_fetch_row - Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag set
    • dbx_query - Send a query and fetch all results (if any)
    • dbx_sort - Sort a result from a dbx_query by a custom sort function
    • dcgettext - Overrides the domain for a single lookup
    • dcngettext - Plural version of dcgettext
    • debug_backtrace - Generates a backtrace
    • debug_print_backtrace - Prints a backtrace
    • debug_zval_dump - Dumps a string representation of an internal zend value to output
    • decbin - Decimal to binary
    • dechex - Decimal to hexadecimal
    • decoct - Decimal to octal
    • define - Defines a named constant
    • defined - Checks whether a given named constant exists
    • define_syslog_variables - Initializes all syslog related variables
    • deflate_add - Incrementally deflate data
    • deflate_init - Initialize an incremental deflate context
    • deg2rad - Converts the number in degrees to the radian equivalent
    • delete - See unlink or unset
    • dgettext - Override the current domain
    • die - Equivalent to exit
    • 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/ouput 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
    • dir - Return an instance of the Directory class
    • Directory::close - Close directory handle
    • Directory::read - Read entry from directory handle
    • Directory::rewind - Rewind directory handle
    • DirectoryIterator::current - Return the current DirectoryIterator item
    • DirectoryIterator::getATime - Get last access time of the current DirectoryIterator item
    • DirectoryIterator::getBasename - Get base name of current DirectoryIterator item
    • DirectoryIterator::getCTime - Get inode change time of the current DirectoryIterator item
    • DirectoryIterator::getExtension - Gets the file extension
    • DirectoryIterator::getFilename - Return file name of current DirectoryIterator item
    • DirectoryIterator::getGroup - Get group for the current DirectoryIterator item
    • DirectoryIterator::getInode - Get inode for the current DirectoryIterator item
    • DirectoryIterator::getMTime - Get last modification time of current DirectoryIterator item
    • DirectoryIterator::getOwner - Get owner of current DirectoryIterator item
    • DirectoryIterator::getPath - Get path of current Iterator item without filename
    • DirectoryIterator::getPathname - Return path and file name of current DirectoryIterator item
    • DirectoryIterator::getPerms - Get the permissions of current DirectoryIterator item
    • DirectoryIterator::getSize - Get size of current DirectoryIterator item
    • DirectoryIterator::getType - Determine the type of the current DirectoryIterator item
    • DirectoryIterator::isDir - Determine if current DirectoryIterator item is a directory
    • DirectoryIterator::isDot - Determine if current DirectoryIterator item is '.' or '..'
    • DirectoryIterator::isExecutable - Determine if current DirectoryIterator item is executable
    • DirectoryIterator::isFile - Determine if current DirectoryIterator item is a regular file
    • DirectoryIterator::isLink - Determine if current DirectoryIterator item is a symbolic link
    • DirectoryIterator::isReadable - Determine if current DirectoryIterator item can be read
    • DirectoryIterator::isWritable - Determine if current DirectoryIterator item can be written to
    • DirectoryIterator::key - Return the key for the current DirectoryIterator item
    • DirectoryIterator::next - Move forward to next DirectoryIterator item
    • DirectoryIterator::rewind - Rewind the DirectoryIterator back to the start
    • DirectoryIterator::seek - Seek to a DirectoryIterator item
    • DirectoryIterator::valid - Check whether current DirectoryIterator position is a valid file
    • DirectoryIterator::__construct - Constructs a new directory iterator from a path
    • DirectoryIterator::__toString - Get file name as a string
    • dirname - Returns a parent directory's path
    • diskfreespace - Alias of disk_free_space
    • disk_free_space - Returns available space on filesystem or disk partition
    • disk_total_space - Returns the total size of a filesystem or disk partition
    • dl - Loads a PHP extension at runtime
    • dngettext - Plural version of dgettext
    • dns_check_record - Alias of checkdnsrr
    • dns_get_mx - Alias of getmxrr
    • dns_get_record - Fetch DNS Resource Records associated with a hostname
    • 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
    • DocResult::__construct - DocResult constructor
    • DOMAttr::isId - Checks if attribute is a defined ID
    • DOMAttr::__construct - Creates a new DOMAttr object
    • DOMCdataSection::__construct - Constructs a new DOMCdataSection object
    • DOMCharacterData::appendData - Append the string to the end of the character data of the node
    • DOMCharacterData::deleteData - Remove a range of characters from the node
    • DOMCharacterData::insertData - Insert a string at the specified 16-bit unit offset
    • DOMCharacterData::replaceData - Replace a substring within the DOMCharacterData node
    • DOMCharacterData::substringData - Extracts a range of data from the node
    • DOMComment::__construct - Creates a new DOMComment object
    • DOMDocument::createAttribute - Create new attribute
    • DOMDocument::createAttributeNS - Create new attribute node with an associated namespace
    • DOMDocument::createCDATASection - Create new cdata node
    • DOMDocument::createComment - Create new comment node
    • DOMDocument::createDocumentFragment - Create new document fragment
    • DOMDocument::createElement - Create new element node
    • DOMDocument::createElementNS - Create new element node with an associated namespace
    • DOMDocument::createEntityReference - Create new entity reference node
    • DOMDocument::createProcessingInstruction - Creates new PI node
    • DOMDocument::createTextNode - Create new text node
    • DOMDocument::getElementById - Searches for an element with a certain id
    • DOMDocument::getElementsByTagName - Searches for all elements with given local tag name
    • DOMDocument::getElementsByTagNameNS - Searches for all elements with given tag name in specified namespace
    • DOMDocument::importNode - Import node into current document
    • DOMDocument::load - Load XML from a file
    • DOMDocument::loadHTML - Load HTML from a string
    • DOMDocument::loadHTMLFile - Load HTML from a file
    • DOMDocument::loadXML - Load XML from a string
    • DOMDocument::normalizeDocument - Normalizes the document
    • DOMDocument::registerNodeClass - Register extended class used to create base node type
    • DOMDocument::relaxNGValidate - Performs relaxNG validation on the document
    • DOMDocument::relaxNGValidateSource - Performs relaxNG validation on the document
    • DOMDocument::save - Dumps the internal XML tree back into a file
    • DOMDocument::saveHTML - Dumps the internal document into a string using HTML formatting
    • DOMDocument::saveHTMLFile - Dumps the internal document into a file using HTML formatting
    • DOMDocument::saveXML - Dumps the internal XML tree back into a string
    • DOMDocument::schemaValidate - Validates a document based on a schema
    • DOMDocument::schemaValidateSource - Validates a document based on a schema
    • DOMDocument::validate - Validates the document based on its DTD
    • DOMDocument::xinclude - Substitutes XIncludes in a DOMDocument Object
    • DOMDocument::__construct - Creates a new DOMDocument object
    • DOMDocumentFragment::appendXML - Append raw XML data
    • DOMElement::getAttribute - Returns value of attribute
    • DOMElement::getAttributeNode - Returns attribute node
    • DOMElement::getAttributeNodeNS - Returns attribute node
    • DOMElement::getAttributeNS - Returns value of attribute
    • DOMElement::getElementsByTagName - Gets elements by tagname
    • DOMElement::getElementsByTagNameNS - Get elements by namespaceURI and localName
    • DOMElement::hasAttribute - Checks to see if attribute exists
    • DOMElement::hasAttributeNS - Checks to see if attribute exists
    • DOMElement::removeAttribute - Removes attribute
    • DOMElement::removeAttributeNode - Removes attribute
    • DOMElement::removeAttributeNS - Removes attribute
    • DOMElement::setAttribute - Adds new attribute
    • DOMElement::setAttributeNode - Adds new attribute node to element
    • DOMElement::setAttributeNodeNS - Adds new attribute node to element
    • DOMElement::setAttributeNS - Adds new attribute
    • DOMElement::setIdAttribute - Declares the attribute specified by name to be of type ID
    • DOMElement::setIdAttributeNode - Declares the attribute specified by node to be of type ID
    • DOMElement::setIdAttributeNS - Declares the attribute specified by local name and namespace URI to be of type ID
    • DOMElement::__construct - Creates a new DOMElement object
    • DOMEntityReference::__construct - Creates a new DOMEntityReference object
    • DOMImplementation::createDocument - Creates a DOMDocument object of the specified type with its document element
    • DOMImplementation::createDocumentType - Creates an empty DOMDocumentType object
    • DOMImplementation::hasFeature - Test if the DOM implementation implements a specific feature
    • DOMImplementation::__construct - Creates a new DOMImplementation object
    • DOMNamedNodeMap::count - Get number of nodes in the map
    • DOMNamedNodeMap::getNamedItem - Retrieves a node specified by name
    • DOMNamedNodeMap::getNamedItemNS - Retrieves a node specified by local name and namespace URI
    • DOMNamedNodeMap::item - Retrieves a node specified by index
    • DOMNode::appendChild - Adds new child at the end of the children
    • DOMNode::C14N - Canonicalize nodes to a string
    • DOMNode::C14NFile - Canonicalize nodes to a file
    • DOMNode::cloneNode - Clones a node
    • DOMNode::getLineNo - Get line number for a node
    • DOMNode::getNodePath - Get an XPath for a node
    • DOMNode::hasAttributes - Checks if node has attributes
    • DOMNode::hasChildNodes - Checks if node has children
    • DOMNode::insertBefore - Adds a new child before a reference node
    • DOMNode::isDefaultNamespace - Checks if the specified namespaceURI is the default namespace or not
    • DOMNode::isSameNode - Indicates if two nodes are the same node
    • DOMNode::isSupported - Checks if feature is supported for specified version
    • DOMNode::lookupNamespaceUri - Gets the namespace URI of the node based on the prefix
    • DOMNode::lookupPrefix - Gets the namespace prefix of the node based on the namespace URI
    • DOMNode::normalize - Normalizes the node
    • DOMNode::removeChild - Removes child from list of children
    • DOMNode::replaceChild - Replaces a child
    • DOMNodeList::count - Get number of nodes in the list
    • DOMNodeList::item - Retrieves a node specified by index
    • DOMProcessingInstruction::__construct - Creates a new DOMProcessingInstruction object
    • DOMText::isElementContentWhitespace - Returns whether this text node contains whitespace in element content
    • DOMText::isWhitespaceInElementContent - Indicates whether this text node contains whitespace
    • DOMText::splitText - Breaks this node into two nodes at the specified offset
    • DOMText::__construct - Creates a new DOMText object
    • DOMXPath::evaluate - Evaluates the given XPath expression and returns a typed result if possible
    • DOMXPath::query - Evaluates the given XPath expression
    • DOMXPath::registerNamespace - Registers the namespace with the DOMXPath object
    • DOMXPath::registerPhpFunctions - Register PHP functions as XPath functions
    • DOMXPath::__construct - Creates a new DOMXPath object
    • dom_import_simplexml - Gets a DOMElement object from a SimpleXMLElement object
    • DOTNET::__construct - DOTNET class constructor
    • doubleval - Alias of floatval
    • Ds\Collection::clear - Removes all values
    • Ds\Collection::copy - Returns a shallow copy of the collection
    • Ds\Collection::isEmpty - Returns whether the collection is empty
    • Ds\Collection::toArray - Converts the collection to an array
    • Ds\Deque::allocate - Allocates enough memory for a required capacity
    • Ds\Deque::apply - Updates all values by applying a callback function to each value
    • Ds\Deque::capacity - Returns the current capacity
    • Ds\Deque::clear - Removes all values from the deque
    • Ds\Deque::contains - Determines if the deque contains given values
    • Ds\Deque::copy - Returns a shallow copy of the deque
    • Ds\Deque::count - Returns the number of values in the collection
    • Ds\Deque::filter - Creates a new deque using a callable to determine which values to include
    • Ds\Deque::find - Attempts to find a value's index
    • Ds\Deque::first - Returns the first value in the deque
    • Ds\Deque::get - Returns the value at a given index
    • Ds\Deque::insert - Inserts values at a given index
    • Ds\Deque::isEmpty - Returns whether the deque is empty
    • Ds\Deque::join - Joins all values together as a string
    • Ds\Deque::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Deque::last - Returns the last value
    • Ds\Deque::map - Returns the result of applying a callback to each value
    • Ds\Deque::merge - Returns the result of adding all given values to the deque
    • Ds\Deque::pop - Removes and returns the last value
    • Ds\Deque::push - Adds values to the end of the deque
    • Ds\Deque::reduce - Reduces the deque to a single value using a callback function
    • Ds\Deque::remove - Removes and returns a value by index
    • Ds\Deque::reverse - Reverses the deque in-place
    • Ds\Deque::reversed - Returns a reversed copy
    • Ds\Deque::rotate - Rotates the deque by a given number of rotations
    • Ds\Deque::set - Updates a value at a given index
    • Ds\Deque::shift - Removes and returns the first value
    • Ds\Deque::slice - Returns a sub-deque of a given range
    • Ds\Deque::sort - Sorts the deque in-place
    • Ds\Deque::sorted - Returns a sorted copy
    • Ds\Deque::sum - Returns the sum of all values in the deque
    • Ds\Deque::toArray - Converts the deque to an array
    • Ds\Deque::unshift - Adds values to the front of the deque
    • Ds\Deque::__construct - Creates a new instance
    • Ds\Hashable::equals - Determines whether an object is equal to the current instance
    • Ds\Hashable::hash - Returns a scalar value to be used as a hash value
    • Ds\Map::allocate - Allocates enough memory for a required capacity
    • Ds\Map::apply - Updates all values by applying a callback function to each value
    • Ds\Map::capacity - Returns the current capacity
    • Ds\Map::clear - Removes all values
    • Ds\Map::copy - Returns a shallow copy of the map
    • Ds\Map::count - Returns the number of values in the map
    • Ds\Map::diff - Creates a new map using keys that aren't in another map
    • Ds\Map::filter - Creates a new map using a callable to determine which pairs to include
    • Ds\Map::first - Returns the first pair in the map
    • Ds\Map::get - Returns the value for a given key
    • Ds\Map::hasKey - Determines whether the map contains a given key
    • Ds\Map::hasValue - Determines whether the map contains a given value
    • Ds\Map::intersect - Creates a new map by intersecting keys with another map
    • Ds\Map::isEmpty - Returns whether the map is empty
    • Ds\Map::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Map::keys - Returns a set of the map's keys
    • Ds\Map::ksort - Sorts the map in-place by key
    • Ds\Map::ksorted - Returns a copy, sorted by key
    • Ds\Map::last - Returns the last pair of the map
    • Ds\Map::map - Returns the result of applying a callback to each value
    • Ds\Map::merge - Returns the result of adding all given associations
    • Ds\Map::pairs - Returns a sequence containing all the pairs of the map
    • Ds\Map::put - Associates a key with a value
    • Ds\Map::putAll - Associates all key-value pairs of a traversable object or array
    • Ds\Map::reduce - Reduces the map to a single value using a callback function
    • Ds\Map::remove - Removes and returns a value by key
    • Ds\Map::reverse - Reverses the map in-place
    • Ds\Map::reversed - Returns a reversed copy
    • Ds\Map::skip - Returns the pair at a given positional index
    • Ds\Map::slice - Returns a subset of the map defined by a starting index and length
    • Ds\Map::sort - Sorts the map in-place by value
    • Ds\Map::sorted - Returns a copy, sorted by value
    • Ds\Map::sum - Returns the sum of all values in the map
    • Ds\Map::toArray - Converts the map to an array
    • Ds\Map::union - Creates a new map using values from the current instance and another map
    • Ds\Map::values - Returns a sequence of the map's values
    • Ds\Map::xor - Creates a new map using keys of either the current instance or of another map, but not of both
    • Ds\Map::__construct - Creates a new instance
    • Ds\Pair::clear - Removes all values
    • Ds\Pair::copy - Returns a shallow copy of the pair
    • Ds\Pair::isEmpty - Returns whether the pair is empty
    • Ds\Pair::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Pair::toArray - Converts the pair to an array
    • Ds\Pair::__construct - Creates a new instance
    • Ds\PriorityQueue::allocate - Allocates enough memory for a required capacity
    • Ds\PriorityQueue::capacity - Returns the current capacity
    • Ds\PriorityQueue::clear - Removes all values
    • Ds\PriorityQueue::copy - Returns a shallow copy of the queue
    • Ds\PriorityQueue::count - Returns the number of values in the queue
    • Ds\PriorityQueue::isEmpty - Returns whether the queue is empty
    • Ds\PriorityQueue::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\PriorityQueue::peek - Returns the value at the front of the queue
    • Ds\PriorityQueue::pop - Removes and returns the value with the highest priority
    • Ds\PriorityQueue::push - Pushes values into the queue
    • Ds\PriorityQueue::toArray - Converts the queue to an array
    • Ds\PriorityQueue::__construct - Creates a new instance
    • Ds\Queue::allocate - Allocates enough memory for a required capacity
    • Ds\Queue::capacity - Returns the current capacity
    • Ds\Queue::clear - Removes all values
    • Ds\Queue::copy - Returns a shallow copy of the queue
    • Ds\Queue::count - Returns the number of values in the queue
    • Ds\Queue::isEmpty - Returns whether the queue is empty
    • Ds\Queue::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Queue::peek - Returns the value at the front of the queue
    • Ds\Queue::pop - Removes and returns the value at the front of the queue
    • Ds\Queue::push - Pushes values into the queue
    • Ds\Queue::toArray - Converts the queue to an array
    • Ds\Queue::__construct - Creates a new instance
    • Ds\Sequence::allocate - Allocates enough memory for a required capacity
    • Ds\Sequence::apply - Updates all values by applying a callback function to each value
    • Ds\Sequence::capacity - Returns the current capacity
    • Ds\Sequence::contains - Determines if the sequence contains given values
    • Ds\Sequence::filter - Creates a new sequence using a callable to determine which values to include
    • Ds\Sequence::find - Attempts to find a value's index
    • Ds\Sequence::first - Returns the first value in the sequence
    • Ds\Sequence::get - Returns the value at a given index
    • Ds\Sequence::insert - Inserts values at a given index
    • Ds\Sequence::join - Joins all values together as a string
    • Ds\Sequence::last - Returns the last value
    • Ds\Sequence::map - Returns the result of applying a callback to each value
    • Ds\Sequence::merge - Returns the result of adding all given values to the sequence
    • Ds\Sequence::pop - Removes and returns the last value
    • Ds\Sequence::push - Adds values to the end of the sequence
    • Ds\Sequence::reduce - Reduces the sequence to a single value using a callback function
    • Ds\Sequence::remove - Removes and returns a value by index
    • Ds\Sequence::reverse - Reverses the sequence in-place
    • Ds\Sequence::reversed - Returns a reversed copy
    • Ds\Sequence::rotate - Rotates the sequence by a given number of rotations
    • Ds\Sequence::set - Updates a value at a given index
    • Ds\Sequence::shift - Removes and returns the first value
    • Ds\Sequence::slice - Returns a sub-sequence of a given range
    • Ds\Sequence::sort - Sorts the sequence in-place
    • Ds\Sequence::sorted - Returns a sorted copy
    • Ds\Sequence::sum - Returns the sum of all values in the sequence
    • Ds\Sequence::unshift - Adds values to the front of the sequence
    • Ds\Set::add - Adds values to the set
    • Ds\Set::allocate - Allocates enough memory for a required capacity
    • Ds\Set::capacity - Returns the current capacity
    • Ds\Set::clear - Removes all values
    • Ds\Set::contains - Determines if the set contains all values
    • Ds\Set::copy - Returns a shallow copy of the set
    • Ds\Set::count - Returns the number of values in the set
    • Ds\Set::diff - Creates a new set using values that aren't in another set
    • Ds\Set::filter - Creates a new set using a callable to determine which values to include
    • Ds\Set::first - Returns the first value in the set
    • Ds\Set::get - Returns the value at a given index
    • Ds\Set::intersect - Creates a new set by intersecting values with another set
    • Ds\Set::isEmpty - Returns whether the set is empty
    • Ds\Set::join - Joins all values together as a string
    • Ds\Set::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Set::last - Returns the last value in the set
    • Ds\Set::merge - Returns the result of adding all given values to the set
    • Ds\Set::reduce - Reduces the set to a single value using a callback function
    • Ds\Set::remove - Removes all given values from the set
    • Ds\Set::reverse - Reverses the set in-place
    • Ds\Set::reversed - Returns a reversed copy
    • Ds\Set::slice - Returns a sub-set of a given range
    • Ds\Set::sort - Sorts the set in-place
    • Ds\Set::sorted - Returns a sorted copy
    • Ds\Set::sum - Returns the sum of all values in the set
    • Ds\Set::toArray - Converts the set to an array
    • Ds\Set::union - Creates a new set using values from the current instance and another set
    • Ds\Set::xor - Creates a new set using values in either the current instance or in another set, but not in both
    • Ds\Set::__construct - Creates a new instance
    • Ds\Stack::allocate - Allocates enough memory for a required capacity
    • Ds\Stack::capacity - Returns the current capacity
    • Ds\Stack::clear - Removes all values
    • Ds\Stack::copy - Returns a shallow copy of the stack
    • Ds\Stack::count - Returns the number of values in the stack
    • Ds\Stack::isEmpty - Returns whether the stack is empty
    • Ds\Stack::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Stack::peek - Returns the value at the top of the stack
    • Ds\Stack::pop - Removes and returns the value at the top of the stack
    • Ds\Stack::push - Pushes values onto the stack
    • Ds\Stack::toArray - Converts the stack to an array
    • Ds\Stack::__construct - Creates a new instance
    • Ds\Vector::allocate - Allocates enough memory for a required capacity
    • Ds\Vector::apply - Updates all values by applying a callback function to each value
    • Ds\Vector::capacity - Returns the current capacity
    • Ds\Vector::clear - Removes all values
    • Ds\Vector::contains - Determines if the vector contains given values
    • Ds\Vector::copy - Returns a shallow copy of the vector
    • Ds\Vector::count - Returns the number of values in the collection
    • Ds\Vector::filter - Creates a new vector using a callable to determine which values to include
    • Ds\Vector::find - Attempts to find a value's index
    • Ds\Vector::first - Returns the first value in the vector
    • Ds\Vector::get - Returns the value at a given index
    • Ds\Vector::insert - Inserts values at a given index
    • Ds\Vector::isEmpty - Returns whether the vector is empty
    • Ds\Vector::join - Joins all values together as a string
    • Ds\Vector::jsonSerialize - Returns a representation that can be converted to JSON
    • Ds\Vector::last - Returns the last value
    • Ds\Vector::map - Returns the result of applying a callback to each value
    • Ds\Vector::merge - Returns the result of adding all given values to the vector
    • Ds\Vector::pop - Removes and returns the last value
    • Ds\Vector::push - Adds values to the end of the vector
    • Ds\Vector::reduce - Reduces the vector to a single value using a callback function
    • Ds\Vector::remove - Removes and returns a value by index
    • Ds\Vector::reverse - Reverses the vector in-place
    • Ds\Vector::reversed - Returns a reversed copy
    • Ds\Vector::rotate - Rotates the vector by a given number of rotations
    • Ds\Vector::set - Updates a value at a given index
    • Ds\Vector::shift - Removes and returns the first value
    • Ds\Vector::slice - Returns a sub-vector of a given range
    • Ds\Vector::sort - Sorts the vector in-place
    • Ds\Vector::sorted - Returns a sorted copy
    • Ds\Vector::sum - Returns the sum of all values in the vector
    • Ds\Vector::toArray - Converts the vector to an array
    • Ds\Vector::unshift - Adds values to the front of the vector
    • Ds\Vector::__construct - Creates a new instance
  • e
    • each - Return the current key and value pair from an array and advance the array cursor
    • easter_date - Get Unix timestamp for midnight on Easter of a given year
    • easter_days - Get number of days after March 21 on which Easter falls for a given year
    • echo - Output one or more strings
    • 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 - Repositions the offset of the open file associated with the fd argument to the argument offset according to the directive whence
    • 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_syncfs - Calls Linux' syncfs syscall, if available
    • eio_sync_file_range - Sync a file segment with disk
    • 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
    • empty - Determine whether a variable is empty
    • EmptyIterator::current - The current() method
    • EmptyIterator::key - The key() method
    • EmptyIterator::next - The next() method
    • EmptyIterator::rewind - The rewind() method
    • EmptyIterator::valid - The valid() method
    • 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 dictionnaries
    • 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_to_personal - Add a word to personal word list
    • 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_in_session - Whether or not 'word' exists in this spelling-session
    • 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
    • end - Set the internal pointer of an array to its last element
    • ereg - Regular expression match
    • eregi - Case insensitive regular expression match
    • eregi_replace - Replace regular expression case insensitive
    • ereg_replace - Replace regular expression
    • 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::getMessage - Gets the error message
    • Error::getPrevious - Returns previous Throwable
    • Error::getTrace - Gets the stack trace
    • Error::getTraceAsString - Gets the stack trace as a string
    • Error::__clone - Clone the error
    • Error::__construct - Construct the error object
    • Error::__toString - String representation of the error
    • ErrorException::getSeverity - Gets the exception severity
    • ErrorException::__construct - Constructs the exception
    • 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
    • escapeshellarg - Escape a string to be used as a shell argument
    • escapeshellcmd - Escape shell metacharacters
    • 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)
    • eval - Evaluate a string as PHP code
    • EvCheck::createStopped - Create instance of a stopped EvCheck watcher
    • EvCheck::__construct - Constructs the EvCheck watcher object
    • EvChild::createStopped - Create instance of a stopped EvCheck watcher
    • EvChild::set - Configures the watcher
    • EvChild::__construct - Constructs the EvChild watcher 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
    • EvEmbed::__construct - Constructs the EvEmbed object
    • Event::add - Makes event pending
    • Event::addSignal - Makes signal event pending
    • Event::addTimer - Makes timer event pending
    • Event::del - Makes event non-pending
    • Event::delSignal - Makes signal event non-pending
    • Event::delTimer - Makes timer event non-pending
    • Event::free - Make event non-pending and free resources allocated for this event
    • Event::getSupportedMethods - Returns array with of the names of the methods supported in this version of Libevent
    • Event::pending - Detects whether event is pending or scheduled
    • Event::set - Re-configures event
    • Event::setPriority - Set event priority
    • Event::setTimer - Re-configures timer event
    • Event::signal - Constructs signal event object
    • Event::timer - Constructs timer event object
    • Event::__construct - Constructs Event object
    • EventBase::dispatch - Dispatch pending events
    • EventBase::exit - Stop dispatching events
    • EventBase::free - Free resources allocated for this event base
    • EventBase::getFeatures - Returns bitmask of features supported
    • EventBase::getMethod - Returns event method in use
    • EventBase::getTimeOfDayCached - Returns the current event base time
    • EventBase::gotExit - Checks if the event loop was told to exit
    • EventBase::gotStop - Checks if the event loop was told to exit
    • EventBase::loop - Dispatch pending events
    • EventBase::priorityInit - Sets number of priorities per event base
    • EventBase::reInit - Re-initialize event base(after a fork)
    • EventBase::stop - Tells event_base to stop dispatching events
    • EventBase::__construct - Constructs EventBase object
    • EventBuffer::add - Append data to the end of an event buffer
    • EventBuffer::addBuffer - Move all data from a buffer provided to the current instance of EventBuffer
    • EventBuffer::appendFrom - Moves the specified number of bytes from a source buffer to the end of the current buffer
    • EventBuffer::copyout - Copies out specified number of bytes from the front of the buffer
    • EventBuffer::drain - Removes specified number of bytes from the front of the buffer without copying it anywhere
    • EventBuffer::enableLocking - Description
    • EventBuffer::expand - Reserves space in buffer
    • EventBuffer::freeze - Prevent calls that modify an event buffer from succeeding
    • EventBuffer::lock - Acquires a lock on buffer
    • EventBuffer::prepend - Prepend data to the front of the buffer
    • EventBuffer::prependBuffer - Moves all data from source buffer to the front of current buffer
    • EventBuffer::pullup - Linearizes data within buffer and returns it's contents as a string
    • EventBuffer::read - Read data from an evbuffer and drain the bytes read
    • EventBuffer::readFrom - Read data from a file onto the end of the buffer
    • EventBuffer::readLine - Extracts a line from the front of the buffer
    • EventBuffer::search - Scans the buffer for an occurrence of a string
    • EventBuffer::searchEol - Scans the buffer for an occurrence of an end of line
    • EventBuffer::substr - Substracts a portion of the buffer data
    • EventBuffer::unfreeze - Re-enable calls that modify an event buffer
    • EventBuffer::unlock - Releases lock acquired by EventBuffer::lock
    • EventBuffer::write - Write contents of the buffer to a file or socket
    • EventBuffer::__construct - Constructs EventBuffer object
    • EventBufferEvent::close - Closes file descriptor associated with the current buffer event
    • EventBufferEvent::connect - Connect buffer event's file descriptor to given address or UNIX socket
    • EventBufferEvent::connectHost - Connects to a hostname with optionally asyncronous DNS resolving
    • EventBufferEvent::createPair - Creates two buffer events connected to each other
    • EventBufferEvent::disable - Disable events read, write, or both on a buffer event
    • EventBufferEvent::enable - Enable events read, write, or both on a buffer event
    • EventBufferEvent::free - Free a buffer event
    • EventBufferEvent::getDnsErrorString - Returns string describing the last failed DNS lookup attempt
    • EventBufferEvent::getEnabled - Returns bitmask of events currently enabled on the buffer event
    • EventBufferEvent::getInput - Returns underlying input buffer associated with current buffer event
    • EventBufferEvent::getOutput - Returns underlying output buffer associated with current buffer event
    • EventBufferEvent::read - Read buffer's data
    • EventBufferEvent::readBuffer - Drains the entire contents of the input buffer and places them into buf
    • EventBufferEvent::setCallbacks - Assigns read, write and event(status) callbacks
    • EventBufferEvent::setPriority - Assign a priority to a bufferevent
    • EventBufferEvent::setTimeouts - Set the read and write timeout for a buffer event
    • EventBufferEvent::setWatermark - Adjusts read and/or write watermarks
    • EventBufferEvent::sslError - Returns most recent OpenSSL error reported on the buffer event
    • EventBufferEvent::sslFilter - Create a new SSL buffer event to send its data over another buffer event
    • EventBufferEvent::sslGetCipherInfo - Returns a textual description of the cipher
    • EventBufferEvent::sslGetCipherName - Returns the current cipher name of the SSL connection
    • EventBufferEvent::sslGetCipherVersion - Returns version of cipher used by current SSL connection
    • EventBufferEvent::sslGetProtocol - Returns the name of the protocol used for current SSL connection
    • EventBufferEvent::sslRenegotiate - Tells a bufferevent to begin SSL renegotiation
    • EventBufferEvent::sslSocket - Creates a new SSL buffer event to send its data over an SSL on a socket
    • EventBufferEvent::write - Adds data to a buffer event's output buffer
    • EventBufferEvent::writeBuffer - Adds contents of the entire buffer to a buffer event's output buffer
    • EventBufferEvent::__construct - Constructs EventBufferEvent object
    • EventConfig::avoidMethod - Tells libevent to avoid specific event method
    • EventConfig::requireFeatures - Enters a required event method feature that the application demands
    • EventConfig::setMaxDispatchInterval - Prevents priority inversion
    • EventConfig::__construct - Constructs EventConfig object
    • EventDnsBase::addNameserverIp - Adds a nameserver to the DNS base
    • EventDnsBase::addSearch - Adds a domain to the list of search domains
    • EventDnsBase::clearSearch - Removes all current search suffixes
    • EventDnsBase::countNameservers - Gets the number of configured nameservers
    • EventDnsBase::loadHosts - Loads a hosts file (in the same format as /etc/hosts) from hosts file
    • EventDnsBase::parseResolvConf - Scans the resolv.conf-formatted file
    • EventDnsBase::setOption - Set the value of a configuration option
    • EventDnsBase::setSearchNdots - Set the 'ndots' parameter for searches
    • EventDnsBase::__construct - Constructs EventDnsBase object
    • EventHttp::accept - Makes an HTTP server accept connections on the specified socket stream or resource
    • EventHttp::addServerAlias - Adds a server alias to the HTTP server object
    • EventHttp::bind - Binds an HTTP server on the specified address and port
    • EventHttp::removeServerAlias - Removes server alias
    • EventHttp::setAllowedMethods - Sets the what HTTP methods are supported in requests accepted by this server, and passed to user callbacks
    • EventHttp::setCallback - Sets a callback for specified URI
    • EventHttp::setDefaultCallback - Sets default callback to handle requests that are not caught by specific callbacks
    • EventHttp::setMaxBodySize - Sets maximum request body size
    • EventHttp::setMaxHeadersSize - Sets maximum HTTP header size
    • EventHttp::setTimeout - Sets the timeout for an HTTP request
    • EventHttp::__construct - Constructs EventHttp object(the HTTP server)
    • EventHttpConnection::getBase - Returns event base associated with the connection
    • EventHttpConnection::getPeer - Gets the remote address and port associated with the connection
    • EventHttpConnection::makeRequest - Makes an HTTP request over the specified connection
    • EventHttpConnection::setCloseCallback - Set callback for connection close
    • EventHttpConnection::setLocalAddress - Sets the IP address from which HTTP connections are made
    • EventHttpConnection::setLocalPort - Sets the local port from which connections are made
    • EventHttpConnection::setMaxBodySize - Sets maximum body size for the connection
    • EventHttpConnection::setMaxHeadersSize - Sets maximum header size
    • EventHttpConnection::setRetries - Sets the retry limit for the connection
    • EventHttpConnection::setTimeout - Sets the timeout for the connection
    • EventHttpConnection::__construct - Constructs EventHttpConnection object
    • EventHttpRequest::addHeader - Adds an HTTP header to the headers of the request
    • EventHttpRequest::cancel - Cancels a pending HTTP request
    • EventHttpRequest::clearHeaders - Removes all output headers from the header list of the request
    • EventHttpRequest::closeConnection - Closes associated HTTP connection
    • EventHttpRequest::findHeader - Finds the value belonging a header
    • EventHttpRequest::free - Frees the object and removes associated events
    • EventHttpRequest::getBufferEvent - Returns EventBufferEvent object
    • EventHttpRequest::getCommand - Returns the request command(method)
    • EventHttpRequest::getConnection - Returns EventHttpConnection object
    • EventHttpRequest::getHost - Returns the request host
    • EventHttpRequest::getInputBuffer - Returns the input buffer
    • EventHttpRequest::getInputHeaders - Returns associative array of the input headers
    • EventHttpRequest::getOutputBuffer - Returns the output buffer of the request
    • EventHttpRequest::getOutputHeaders - Returns associative array of the output headers
    • EventHttpRequest::getResponseCode - Returns the response code
    • EventHttpRequest::getUri - Returns the request URI
    • EventHttpRequest::removeHeader - Removes an HTTP header from the headers of the request
    • EventHttpRequest::sendError - Send an HTML error message to the client
    • EventHttpRequest::sendReply - Send an HTML reply to the client
    • EventHttpRequest::sendReplyChunk - Send another data chunk as part of an ongoing chunked reply
    • EventHttpRequest::sendReplyEnd - Complete a chunked reply, freeing the request as appropriate
    • EventHttpRequest::sendReplyStart - Initiate a chunked reply
    • EventHttpRequest::__construct - Constructs EventHttpRequest object
    • EventListener::disable - Disables an event connect listener object
    • EventListener::enable - Enables an event connect listener object
    • EventListener::getBase - Returns event base associated with the event listener
    • EventListener::getSocketName - Retreives the current address to which the listener's socket is bound
    • EventListener::setCallback - The setCallback purpose
    • EventListener::setErrorCallback - Set event listener's error callback
    • EventListener::__construct - Creates new connection listener associated with an event base
    • EventSslContext::__construct - Constructs an OpenSSL context for use with Event classes
    • EventUtil::getLastSocketErrno - Returns the most recent socket error number
    • EventUtil::getLastSocketError - Returns the most recent socket error
    • EventUtil::getSocketFd - Returns numeric file descriptor of a socket, or stream
    • EventUtil::getSocketName - Retreives the current address to which the socket is bound
    • EventUtil::setSocketOption - Sets socket options
    • EventUtil::sslRandPoll - Generates entropy by means of OpenSSL's RAND_poll()
    • EventUtil::__construct - The abstract constructor
    • event_base_free - Destroy event base
    • event_base_loop - Handle events
    • event_base_loopbreak - Abort event loop
    • event_base_loopexit - Exit loop after a time
    • event_base_new - Create and initialize new event base
    • event_base_priority_init - Set the number of event priority levels
    • event_base_reinit - Reinitialize the event base after a fork
    • event_base_set - Associate event base with an event
    • event_buffer_base_set - Associate buffered event with an event base
    • event_buffer_disable - Disable a buffered event
    • event_buffer_enable - Enable a buffered event
    • event_buffer_fd_set - Change a buffered event file descriptor
    • event_buffer_free - Destroy buffered event
    • event_buffer_new - Create new buffered event
    • event_buffer_priority_set - Assign a priority to a buffered event
    • event_buffer_read - Read data from a buffered event
    • event_buffer_set_callback - Set or reset callbacks for a buffered event
    • event_buffer_timeout_set - Set read and write timeouts for a buffered event
    • event_buffer_watermark_set - Set the watermarks for read and write events
    • event_buffer_write - Write data to a buffered event
    • event_new - Create new event
    • event_priority_set - Assign a priority to an event
    • event_timer_add - Alias of event_add
    • event_timer_del - Alias of event_del
    • event_timer_new - Alias of event_new
    • event_timer_set - Prepare a timer event
    • EvFork::createStopped - Creates a stopped instance of EvFork watcher class
    • EvFork::__construct - Constructs the EvFork watcher object
    • EvIdle::createStopped - Creates instance of a stopped EvIdle watcher object
    • EvIdle::__construct - Constructs the EvIdle watcher object
    • EvIo::createStopped - Create stopped EvIo watcher object
    • EvIo::set - Configures the watcher
    • EvIo::__construct - Constructs EvIo watcher object
    • 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::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)
    • EvLoop::__construct - Constructs the event loop object
    • 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::createStopped - Create a stopped EvPeriodic watcher
    • EvPeriodic::set - Configures the watcher
    • EvPeriodic::__construct - Constructs EvPeriodic watcher object
    • EvPrepare::createStopped - Creates a stopped instance of EvPrepare watcher
    • EvPrepare::__construct - Constructs EvPrepare watcher object
    • EvSignal::createStopped - Create stopped EvSignal watcher object
    • EvSignal::set - Configures the watcher
    • EvSignal::__construct - Constructs EvSignal watcher object
    • EvStat::attr - Returns the values most recently detected by Ev
    • EvStat::createStopped - Create a stopped EvStat watcher object
    • EvStat::prev - Returns the previous set of values returned by EvStat::attr
    • EvStat::set - Configures the watcher
    • EvStat::stat - Initiates the stat call
    • EvStat::__construct - Constructs EvStat watcher object
    • EvTimer::again - Restarts the timer watcher
    • EvTimer::createStopped - Creates EvTimer stopped watcher object
    • EvTimer::set - Configures the watcher
    • EvTimer::__construct - Constructs an EvTimer watcher object
    • EvWatcher::clear - Clear watcher pending status
    • EvWatcher::feed - Feeds the given revents set into the event loop
    • EvWatcher::getLoop - Returns the loop responsible for the watcher
    • EvWatcher::invoke - Invokes the watcher callback with the given received events bit mask
    • EvWatcher::keepalive - Configures whether to keep the loop from returning
    • EvWatcher::setCallback - Sets new callback for the watcher
    • EvWatcher::start - Starts the watcher
    • EvWatcher::stop - Stops the watcher
    • EvWatcher::__construct - Abstract constructor of a watcher object
    • Examples with PDO_4D - Examples PDO_4D
    • 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::getMessage - Gets the Exception message
    • Exception::getPrevious - Returns previous Exception
    • Exception::getTrace - Gets the stack trace
    • Exception::getTraceAsString - Gets the stack trace as a string
    • Exception::__clone - Clone the exception
    • Exception::__construct - Construct the exception
    • Exception::__toString - String representation of the exception
    • exec - Execute an external program
    • Executable::execute - Execute statement
    • ExecutionStatus::__construct - ExecutionStatus constructor
    • 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
    • exit - Output a message and terminate the current script
    • exp - Calculates the exponent of e
    • expect:// - Process Interaction Streams
    • expect_expectl - Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen
    • expect_popen - Execute command via Bourne shell, and open the PTY stream to the process
    • explode - Split a string by a string
    • expm1 - Returns exp(number) - 1, computed in a way that is accurate even when the value of number is close to zero
    • expression - Bind prepared statement variables as parameters
    • Expression::__construct - Expression constructor
    • extension_loaded - Find out whether an extension is loaded
    • extract - Import variables into the current symbol table from an array
    • ezmlm_hash - Calculate the hash value needed by EZMLM
  • f
    • fam_cancel_monitor - Terminate monitoring
    • fam_close - Close FAM connection
    • fam_monitor_collection - Monitor a collection of files in a directory for changes
    • fam_monitor_directory - Monitor a directory for changes
    • fam_monitor_file - Monitor a regular file for changes
    • fam_next_event - Get next pending FAM event
    • fam_open - Open connection to FAM daemon
    • fam_pending - Check for pending FAM events
    • fam_resume_monitor - Resume suspended monitoring
    • fam_suspend_monitor - Temporarily suspend monitoring
    • FANNConnection::getFromNeuron - Returns the postions of starting neuron
    • FANNConnection::getToNeuron - Returns the postions of terminating neuron
    • FANNConnection::getWeight - Returns the connection weight
    • FANNConnection::setWeight - Sets the connections weight
    • FANNConnection::__construct - The connection constructor
    • fann_cascadetrain_on_data - Trains on an entire dataset, for a period of time using the Cascade2 training algorithm
    • fann_cascadetrain_on_file - Trains on an entire dataset read from file, for a period of time using the Cascade2 training algorithm
    • fann_clear_scaling_params - Clears scaling parameters
    • fann_copy - Creates a copy of a fann structure
    • fann_create_from_file - Constructs a backpropagation neural network from a configuration file
    • fann_create_shortcut - Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections
    • fann_create_shortcut_array - Creates a standard backpropagation neural network which is not fully connectected and has shortcut connections
    • fann_create_sparse - Creates a standard backpropagation neural network, which is not fully connected
    • fann_create_sparse_array - Creates a standard backpropagation neural network, which is not fully connected using an array of layer sizes
    • fann_create_standard - Creates a standard fully connected backpropagation neural network
    • fann_create_standard_array - Creates a standard fully connected backpropagation neural network using an array of layer sizes
    • fann_create_train - Creates an empty training data struct
    • fann_create_train_from_callback - Creates the training data struct from a user supplied function
    • fann_descale_input - Scale data in input vector after get it from ann based on previously calculated parameters
    • fann_descale_output - Scale data in output vector after get it from ann based on previously calculated parameters
    • fann_descale_train - Descale input and output data based on previously calculated parameters
    • fann_destroy - Destroys the entire network and properly freeing all the associated memory
    • fann_destroy_train - Destructs the training data
    • fann_duplicate_train_data - Returns an exact copy of a fann train data
    • fann_get_activation_function - Returns the activation function
    • fann_get_activation_steepness - Returns the activation steepness for supplied neuron and layer number
    • fann_get_bias_array - Get the number of bias in each layer in the network
    • fann_get_bit_fail - The number of fail bits
    • fann_get_bit_fail_limit - Returns the bit fail limit used during training
    • fann_get_cascade_activation_functions - Returns the cascade activation functions
    • fann_get_cascade_activation_functions_count - Returns the number of cascade activation functions
    • fann_get_cascade_activation_steepnesses - Returns the cascade activation steepnesses
    • fann_get_cascade_activation_steepnesses_count - The number of activation steepnesses
    • fann_get_cascade_candidate_change_fraction - Returns the cascade candidate change fraction
    • fann_get_cascade_candidate_limit - Return the candidate limit
    • fann_get_cascade_candidate_stagnation_epochs - Returns the number of cascade candidate stagnation epochs
    • fann_get_cascade_max_cand_epochs - Returns the maximum candidate epochs
    • fann_get_cascade_max_out_epochs - Returns the maximum out epochs
    • fann_get_cascade_min_cand_epochs - Returns the minimum candidate epochs
    • fann_get_cascade_min_out_epochs - Returns the minimum out epochs
    • fann_get_cascade_num_candidates - Returns the number of candidates used during training
    • fann_get_cascade_num_candidate_groups - Returns the number of candidate groups
    • fann_get_cascade_output_change_fraction - Returns the cascade output change fraction
    • fann_get_cascade_output_stagnation_epochs - Returns the number of cascade output stagnation epochs
    • fann_get_cascade_weight_multiplier - Returns the weight multiplier
    • fann_get_connection_array - Get connections in the network
    • fann_get_connection_rate - Get the connection rate used when the network was created
    • fann_get_errno - Returns the last error number
    • fann_get_errstr - Returns the last errstr
    • fann_get_layer_array - Get the number of neurons in each layer in the network
    • fann_get_learning_momentum - Returns the learning momentum
    • fann_get_learning_rate - Returns the learning rate
    • fann_get_MSE - Reads the mean square error from the network
    • fann_get_network_type - Get the type of neural network it was created as
    • fann_get_num_input - Get the number of input neurons
    • fann_get_num_layers - Get the number of layers in the neural network
    • fann_get_num_output - Get the number of output neurons
    • fann_get_quickprop_decay - Returns the decay which is a factor that weights should decrease in each iteration during quickprop training
    • fann_get_quickprop_mu - Returns the mu factor
    • fann_get_rprop_decrease_factor - Returns the increase factor used during RPROP training
    • fann_get_rprop_delta_max - Returns the maximum step-size
    • fann_get_rprop_delta_min - Returns the minimum step-size
    • fann_get_rprop_delta_zero - Returns the initial step-size
    • fann_get_rprop_increase_factor - Returns the increase factor used during RPROP training
    • fann_get_sarprop_step_error_shift - Returns the sarprop step error shift
    • fann_get_sarprop_step_error_threshold_factor - Returns the sarprop step error threshold factor
    • fann_get_sarprop_temperature - Returns the sarprop temperature
    • fann_get_sarprop_weight_decay_shift - Returns the sarprop weight decay shift
    • fann_get_total_connections - Get the total number of connections in the entire network
    • fann_get_total_neurons - Get the total number of neurons in the entire network
    • fann_get_training_algorithm - Returns the training algorithm
    • fann_get_train_error_function - Returns the error function used during training
    • fann_get_train_stop_function - Returns the stop function used during training
    • fann_init_weights - Initialize the weights using Widrow + Nguyen’s algorithm
    • fann_length_train_data - Returns the number of training patterns in the train data
    • fann_merge_train_data - Merges the train data
    • fann_num_input_train_data - Returns the number of inputs in each of the training patterns in the train data
    • fann_num_output_train_data - Returns the number of outputs in each of the training patterns in the train data
    • fann_print_error - Prints the error string
    • fann_randomize_weights - Give each connection a random weight between min_weight and max_weight
    • fann_read_train_from_file - Reads a file that stores training data
    • fann_reset_errno - Resets the last error number
    • fann_reset_errstr - Resets the last error string
    • fann_reset_MSE - Resets the mean square error from the network
    • fann_run - Will run input through the neural network
    • fann_save - Saves the entire network to a configuration file
    • fann_save_train - Save the training structure to a file
    • fann_scale_input - Scale data in input vector before feed it to ann based on previously calculated parameters
    • fann_scale_input_train_data - Scales the inputs in the training data to the specified range
    • fann_scale_output - Scale data in output vector before feed it to ann based on previously calculated parameters
    • fann_scale_output_train_data - Scales the outputs in the training data to the specified range
    • fann_scale_train - Scale input and output data based on previously calculated parameters
    • fann_scale_train_data - Scales the inputs and outputs in the training data to the specified range
    • fann_set_activation_function - Sets the activation function for supplied neuron and layer
    • fann_set_activation_function_hidden - Sets the activation function for all of the hidden layers
    • fann_set_activation_function_layer - Sets the activation function for all the neurons in the supplied layer
    • fann_set_activation_function_output - Sets the activation function for the output layer
    • fann_set_activation_steepness - Sets the activation steepness for supplied neuron and layer number
    • fann_set_activation_steepness_hidden - Sets the steepness of the activation steepness for all neurons in the all hidden layers
    • fann_set_activation_steepness_layer - Sets the activation steepness for all of the neurons in the supplied layer number
    • fann_set_activation_steepness_output - Sets the steepness of the activation steepness in the output layer
    • fann_set_bit_fail_limit - Set the bit fail limit used during training
    • fann_set_callback - Sets the callback function for use during training
    • fann_set_cascade_activation_functions - Sets the array of cascade candidate activation functions
    • fann_set_cascade_activation_steepnesses - Sets the array of cascade candidate activation steepnesses
    • fann_set_cascade_candidate_change_fraction - Sets the cascade candidate change fraction
    • fann_set_cascade_candidate_limit - Sets the candidate limit
    • fann_set_cascade_candidate_stagnation_epochs - Sets the number of cascade candidate stagnation epochs
    • fann_set_cascade_max_cand_epochs - Sets the max candidate epochs
    • fann_set_cascade_max_out_epochs - Sets the maximum out epochs
    • fann_set_cascade_min_cand_epochs - Sets the min candidate epochs
    • fann_set_cascade_min_out_epochs - Sets the minimum out epochs
    • fann_set_cascade_num_candidate_groups - Sets the number of candidate groups
    • fann_set_cascade_output_change_fraction - Sets the cascade output change fraction
    • fann_set_cascade_output_stagnation_epochs - Sets the number of cascade output stagnation epochs
    • fann_set_cascade_weight_multiplier - Sets the weight multiplier
    • fann_set_error_log - Sets where the errors are logged to
    • fann_set_input_scaling_params - Calculate input scaling parameters for future use based on training data
    • fann_set_learning_momentum - Sets the learning momentum
    • fann_set_learning_rate - Sets the learning rate
    • fann_set_output_scaling_params - Calculate output scaling parameters for future use based on training data
    • fann_set_quickprop_decay - Sets the quickprop decay factor
    • fann_set_quickprop_mu - Sets the quickprop mu factor
    • fann_set_rprop_decrease_factor - Sets the decrease factor used during RPROP training
    • fann_set_rprop_delta_max - Sets the maximum step-size
    • fann_set_rprop_delta_min - Sets the minimum step-size
    • fann_set_rprop_delta_zero - Sets the initial step-size
    • fann_set_rprop_increase_factor - Sets the increase factor used during RPROP training
    • fann_set_sarprop_step_error_shift - Sets the sarprop step error shift
    • fann_set_sarprop_step_error_threshold_factor - Sets the sarprop step error threshold factor
    • fann_set_sarprop_temperature - Sets the sarprop temperature
    • fann_set_sarprop_weight_decay_shift - Sets the sarprop weight decay shift
    • fann_set_scaling_params - Calculate input and output scaling parameters for future use based on training data
    • fann_set_training_algorithm - Sets the training algorithm
    • fann_set_train_error_function - Sets the error function used during training
    • fann_set_train_stop_function - Sets the stop function used during training
    • fann_set_weight - Set a connection in the network
    • fann_set_weight_array - Set connections in the network
    • fann_shuffle_train_data - Shuffles training data, randomizing the order
    • fann_subset_train_data - Returns an copy of a subset of the train data
    • fann_test - Test with a set of inputs, and a set of desired outputs
    • fann_test_data - Test a set of training data and calculates the MSE for the training data
    • fann_train - Train one iteration with a set of inputs, and a set of desired outputs
    • fann_train_epoch - Train one epoch with a set of training data
    • fann_train_on_data - Trains on an entire dataset for a period of time
    • fann_train_on_file - Trains on an entire dataset, which is read from file, for a period of time
    • fastcgi_finish_request - Flushes all response data to the client
    • 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
    • fbsql_affected_rows - Get number of affected rows in previous FrontBase operation
    • fbsql_autocommit - Enable or disable autocommit
    • fbsql_blob_size - Get the size of a BLOB
    • fbsql_change_user - Change logged in user of the active connection
    • fbsql_clob_size - Get the size of a CLOB
    • fbsql_close - Close FrontBase connection
    • fbsql_commit - Commits a transaction to the database
    • fbsql_connect - Open a connection to a FrontBase Server
    • fbsql_create_blob - Create a BLOB
    • fbsql_create_clob - Create a CLOB
    • fbsql_create_db - Create a FrontBase database
    • fbsql_database - Get or set the database name used with a connection
    • fbsql_database_password - Sets or retrieves the password for a FrontBase database
    • fbsql_data_seek - Move internal result pointer
    • fbsql_db_query - Send a FrontBase query
    • fbsql_db_status - Get the status for a given database
    • fbsql_drop_db - Drop (delete) a FrontBase database
    • fbsql_errno - Returns the error number from previous operation
    • fbsql_error - Returns the error message from previous operation
    • fbsql_fetch_array - Fetch a result row as an associative array, a numeric array, or both
    • fbsql_fetch_assoc - Fetch a result row as an associative array
    • fbsql_fetch_field - Get column information from a result and return as an object
    • fbsql_fetch_lengths - Get the length of each output in a result
    • fbsql_fetch_object - Fetch a result row as an object
    • fbsql_fetch_row - Get a result row as an enumerated array
    • fbsql_field_flags - Get the flags associated with the specified field in a result
    • fbsql_field_len - Returns the length of the specified field
    • fbsql_field_name - Get the name of the specified field in a result
    • fbsql_field_seek - Set result pointer to a specified field offset
    • fbsql_field_table - Get name of the table the specified field is in
    • fbsql_field_type - Get the type of the specified field in a result
    • fbsql_free_result - Free result memory
    • fbsql_get_autostart_info - Description
    • fbsql_hostname - Get or set the host name used with a connection
    • fbsql_insert_id - Get the id generated from the previous INSERT operation
    • fbsql_list_dbs - List databases available on a FrontBase server
    • fbsql_list_fields - List FrontBase result fields
    • fbsql_list_tables - List tables in a FrontBase database
    • fbsql_next_result - Move the internal result pointer to the next result
    • fbsql_num_fields - Get number of fields in result
    • fbsql_num_rows - Get number of rows in result
    • fbsql_password - Get or set the user password used with a connection
    • fbsql_pconnect - Open a persistent connection to a FrontBase Server
    • fbsql_query - Send a FrontBase query
    • fbsql_read_blob - Read a BLOB from the database
    • fbsql_read_clob - Read a CLOB from the database
    • fbsql_result - Get result data
    • fbsql_rollback - Rollback a transaction to the database
    • fbsql_rows_fetched - Get the number of rows affected by the last statement
    • fbsql_select_db - Select a FrontBase database
    • fbsql_set_characterset - Change input/output character set
    • fbsql_set_lob_mode - Set the LOB retrieve mode for a FrontBase result set
    • fbsql_set_password - Change the password for a given user
    • fbsql_set_transaction - Set the transaction locking and isolation
    • fbsql_start_db - Start a database on local or remote server
    • fbsql_stop_db - Stop a database on local or remote server
    • fbsql_tablename - Alias of fbsql_table_name
    • fbsql_table_name - Get table name of field
    • fbsql_username - Get or set the username for the connection
    • fbsql_warnings - Enable or disable FrontBase warnings
    • fclose - Closes an open file pointer
    • 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
    • feof - Tests for end-of-file on a file pointer
    • 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
    • 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:// - Accessing local filesystem
    • 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
    • filepro - Read and verify the map file
    • filepro_fieldcount - Find out how many fields are in a filePro database
    • filepro_fieldname - Gets the name of a field
    • filepro_fieldtype - Gets the type of a field
    • filepro_fieldwidth - Gets the width of a field
    • filepro_retrieve - Retrieves data from a filePro database
    • filepro_rowcount - Find out how many rows are in a filePro database
    • filesize - Gets file size
    • FilesystemIterator::current - The current file
    • FilesystemIterator::getFlags - Get the handling flags
    • FilesystemIterator::key - Retrieve the key for the current file
    • FilesystemIterator::next - Move to the next file
    • FilesystemIterator::rewind - Rewinds back to the beginning
    • FilesystemIterator::setFlags - Sets handling flags
    • FilesystemIterator::__construct - Constructs a new filesystem iterator
    • filetype - Gets file type
    • 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
    • FilterIterator::accept - Check whether the current element of the iterator is acceptable
    • FilterIterator::current - Get the current element value
    • FilterIterator::getInnerIterator - Get the inner iterator
    • FilterIterator::key - Get the current key
    • FilterIterator::next - Move the iterator forward
    • FilterIterator::rewind - Rewind the iterator
    • FilterIterator::valid - Check whether the current element is valid
    • FilterIterator::__construct - Construct a filterIterator
    • filter_has_var - Checks if variable of specified type exists
    • filter_id - Returns the filter ID belonging to a named filter
    • filter_input - Gets a specific external variable by name and optionally filters it
    • filter_input_array - Gets external variables and optionally filters them
    • filter_list - Returns a list of all supported filters
    • filter_var - Filters a variable with a specified filter
    • filter_var_array - Gets multiple variables and optionally filters them
    • finfo::buffer - Alias of finfo_buffer()
    • finfo::file - Alias of finfo_file()
    • finfo::set_flags - Alias of finfo_set_flags()
    • finfo::__construct - Alias of finfo_open
    • finfo_close - Close fileinfo resource
    • finfo_open - Create a new fileinfo resource
    • floatval - Get float value of a variable
    • flock - Portable advisory file locking
    • floor - Round fractions down
    • flush - Flush system output buffer
    • fmod - Returns the floating point remainder (modulo) of the division of the arguments
    • fnmatch - Match filename against a pattern
    • fopen - Opens file or URL
    • forward_static_call - Call a static method
    • forward_static_call_array - Call a static method and pass the arguments as array
    • fpassthru - Output all remaining data on a file pointer
    • fprintf - Write a formatted string to a stream
    • fputcsv - Format line as CSV and write to file pointer
    • fputs - Alias of fwrite
    • fread - Binary-safe file read
    • frenchtojd - Converts a date from the French Republican Calendar to a Julian Day Count
    • fribidi_log2vis - Convert a logical string to a visual one
    • fscanf - Parses input from a file according to a format
    • fseek - Seeks on a file pointer
    • fsockopen - Open Internet or Unix domain socket connection
    • fstat - Gets information about a file using an open file pointer
    • ftell - Returns the current position of the file read/write pointer
    • ftok - Convert a pathname and a project identifier to a System V IPC key
    • ftp:// - Accessing FTP(s) URLs
    • FTP context options - FTP context option listing
    • ftp_alloc - Allocates space for a file to be uploaded
    • ftp_append - Append the contents of a file to another file on the FTP server
    • ftp_cdup - Changes to the parent directory
    • ftp_chdir - Changes the current directory on a FTP server
    • ftp_chmod - Set permissions on a file via FTP
    • ftp_close - Closes an FTP connection
    • ftp_connect - Opens an FTP connection
    • ftp_delete - Deletes a file on the FTP server
    • ftp_exec - Requests execution of a command on the FTP server
    • ftp_fget - Downloads a file from the FTP server and saves to an open file
    • ftp_fput - Uploads from an open file to the FTP server
    • ftp_get - Downloads a file from the FTP server
    • ftp_get_option - Retrieves various runtime behaviours of the current FTP stream
    • ftp_login - Logs in to an FTP connection
    • ftp_mdtm - Returns the last modified time of the given file
    • ftp_mkdir - Creates a directory
    • ftp_mlsd - Returns a list of files in the given directory
    • ftp_nb_continue - Continues retrieving/sending a file (non-blocking)
    • ftp_nb_fget - Retrieves a file from the FTP server and writes it to an open file (non-blocking)
    • ftp_nb_fput - Stores a file from an open file to the FTP server (non-blocking)
    • ftp_nb_get - Retrieves a file from the FTP server and writes it to a local file (non-blocking)
    • ftp_nb_put - Stores a file on the FTP server (non-blocking)
    • ftp_nlist - Returns a list of files in the given directory
    • ftp_pasv - Turns passive mode on or off
    • ftp_put - Uploads a file to the FTP server
    • ftp_pwd - Returns the current directory name
    • ftp_quit - Alias of ftp_close
    • ftp_raw - Sends an arbitrary command to an FTP server
    • ftp_rawlist - Returns a detailed list of files in the given directory
    • ftp_rename - Renames a file or a directory on the FTP server
    • ftp_rmdir - Removes a directory
    • ftp_set_option - Set miscellaneous runtime FTP options
    • ftp_site - Sends a SITE command to the server
    • ftp_size - Returns the size of the given file
    • ftp_ssl_connect - Opens a Secure SSL-FTP connection
    • ftp_systype - Returns the system type identifier of the remote FTP server
    • ftruncate - Truncates a file to a given length
    • function_exists - Return TRUE if the given function has been defined
    • func_get_arg - Return an item from the argument list
    • func_get_args - Returns an array comprising a function's argument list
    • func_num_args - Returns the number of arguments passed to the function
    • fwrite - Binary-safe file write
  • g
    • 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
    • gd_info - Retrieve information about the currently installed GD library
    • GearmanClient::addOptions - Add client options
    • GearmanClient::addServer - Add a job server to the client
    • GearmanClient::addServers - Add a list of job servers to the client
    • GearmanClient::addTask - Add a task to be run in parallel
    • GearmanClient::addTaskBackground - Add a background task to be run in parallel
    • GearmanClient::addTaskHigh - Add a high priority task to run in parallel
    • GearmanClient::addTaskHighBackground - Add a high priority background task to be run in parallel
    • GearmanClient::addTaskLow - Add a low priority task to run in parallel
    • GearmanClient::addTaskLowBackground - Add a low priority background task to be run in parallel
    • GearmanClient::addTaskStatus - Add a task to get status
    • GearmanClient::clearCallbacks - Clear all task callback functions
    • GearmanClient::clone - Create a copy of a GearmanClient object
    • GearmanClient::context - Get the application context
    • GearmanClient::data - Get the application data (deprecated)
    • GearmanClient::do - Run a single task and return a result [deprecated]
    • GearmanClient::doBackground - Run a task in the background
    • GearmanClient::doHigh - Run a single high priority task
    • GearmanClient::doHighBackground - Run a high priority task in the background
    • GearmanClient::doJobHandle - Get the job handle for the running task
    • GearmanClient::doLow - Run a single low priority task
    • GearmanClient::doLowBackground - Run a low priority task in the background
    • GearmanClient::doNormal - Run a single task and return a result
    • GearmanClient::doStatus - Get the status for the running task
    • GearmanClient::echo - Send data to all job servers to see if they echo it back [deprecated]
    • GearmanClient::error - Returns an error string for the last error encountered
    • GearmanClient::getErrno - Get an errno value
    • GearmanClient::jobStatus - Get the status of a background job
    • GearmanClient::ping - Send data to all job servers to see if they echo it back
    • GearmanClient::removeOptions - Remove client options
    • GearmanClient::returnCode - Get the last Gearman return code
    • GearmanClient::runTasks - Run a list of tasks in parallel
    • GearmanClient::setClientCallback - Callback function when there is a data packet for a task (deprecated)
    • GearmanClient::setCompleteCallback - Set a function to be called on task completion
    • GearmanClient::setContext - Set application context
    • GearmanClient::setCreatedCallback - Set a callback for when a task is queued
    • GearmanClient::setData - Set application data (deprecated)
    • GearmanClient::setDataCallback - Callback function when there is a data packet for a task
    • GearmanClient::setExceptionCallback - Set a callback for worker exceptions
    • GearmanClient::setFailCallback - Set callback for job failure
    • GearmanClient::setOptions - Set client options
    • GearmanClient::setStatusCallback - Set a callback for collecting task status
    • GearmanClient::setTimeout - Set socket I/O activity timeout
    • GearmanClient::setWarningCallback - Set a callback for worker warnings
    • GearmanClient::setWorkloadCallback - Set a callback for accepting incremental data updates
    • GearmanClient::timeout - Get current socket I/O activity timeout value
    • GearmanClient::__construct - Create a GearmanClient instance
    • GearmanJob::complete - Send the result and complete status (deprecated)
    • GearmanJob::data - Send data for a running job (deprecated)
    • GearmanJob::exception - Send exception for running job (deprecated)
    • GearmanJob::fail - Send fail status (deprecated)
    • GearmanJob::functionName - Get function name
    • GearmanJob::handle - Get the job handle
    • GearmanJob::returnCode - Get last return code
    • GearmanJob::sendComplete - Send the result and complete status
    • GearmanJob::sendData - Send data for a running job
    • GearmanJob::sendException - Send exception for running job (exception)
    • GearmanJob::sendFail - Send fail status
    • GearmanJob::sendStatus - Send status
    • GearmanJob::sendWarning - Send a warning
    • GearmanJob::setReturn - Set a return value
    • GearmanJob::status - Send status (deprecated)
    • GearmanJob::unique - Get the unique identifier
    • GearmanJob::warning - Send a warning (deprecated)
    • GearmanJob::workload - Get workload
    • GearmanJob::workloadSize - Get size of work load
    • GearmanJob::__construct - Create a GearmanJob instance
    • GearmanTask::create - Create a task (deprecated)
    • GearmanTask::data - Get data returned for a task
    • GearmanTask::dataSize - Get the size of returned data
    • GearmanTask::function - Get associated function name (deprecated)
    • GearmanTask::functionName - Get associated function name
    • GearmanTask::isKnown - Determine if task is known
    • GearmanTask::isRunning - Test whether the task is currently running
    • GearmanTask::jobHandle - Get the job handle
    • GearmanTask::recvData - Read work or result data into a buffer for a task
    • GearmanTask::returnCode - Get the last return code
    • GearmanTask::sendData - Send data for a task (deprecated)
    • GearmanTask::sendWorkload - Send data for a task
    • GearmanTask::taskDenominator - Get completion percentage denominator
    • GearmanTask::taskNumerator - Get completion percentage numerator
    • GearmanTask::unique - Get the unique identifier for a task
    • GearmanTask::uuid - Get the unique identifier for a task (deprecated)
    • GearmanTask::__construct - Create a GearmanTask instance
    • GearmanWorker::addFunction - Register and add callback function
    • GearmanWorker::addOptions - Add worker options
    • GearmanWorker::addServer - Add a job server
    • GearmanWorker::addServers - Add job servers
    • GearmanWorker::clone - Create a copy of the worker
    • GearmanWorker::echo - Test job server response
    • GearmanWorker::error - Get the last error encountered
    • GearmanWorker::getErrno - Get errno
    • GearmanWorker::options - Get worker options
    • GearmanWorker::register - Register a function with the job server
    • GearmanWorker::removeOptions - Remove worker options
    • GearmanWorker::returnCode - Get last Gearman return code
    • GearmanWorker::setId - Give the worker an identifier so it can be tracked when asking gearmand for the list of available workers
    • GearmanWorker::setOptions - Set worker options
    • GearmanWorker::setTimeout - Set socket I/O activity timeout
    • GearmanWorker::timeout - Get socket I/O activity timeout
    • GearmanWorker::unregister - Unregister a function name with the job servers
    • GearmanWorker::unregisterAll - Unregister all function names with the job servers
    • GearmanWorker::wait - Wait for activity from one of the job servers
    • GearmanWorker::work - Wait for and perform jobs
    • GearmanWorker::__construct - Create a GearmanWorker instance
    • Gender\Gender::connect - Connect to an external name dictionary
    • 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
    • Gender\Gender::__construct - Construct the Gender object
    • 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 - Rewind the iterator
    • 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
    • geoip_asnum_by_name - Get the Autonomous System Numbers (ASN)
    • geoip_continent_code_by_name - Get the two letter continent code
    • geoip_country_code3_by_name - Get the three letter country code
    • geoip_country_code_by_name - Get the two letter country code
    • geoip_country_name_by_name - Get the full country name
    • geoip_database_info - Get GeoIP Database information
    • geoip_db_avail - Determine if GeoIP Database is available
    • geoip_db_filename - Returns the filename of the corresponding GeoIP Database
    • geoip_db_get_all_info - Returns detailed information about all GeoIP database types
    • geoip_domain_by_name - Get the second level domain name
    • geoip_id_by_name - Get the Internet connection type
    • geoip_isp_by_name - Get the Internet Service Provider (ISP) name
    • geoip_netspeedcell_by_name - Get the Internet connection speed
    • geoip_org_by_name - Get the organization name
    • geoip_record_by_name - Returns the detailed City information found in the GeoIP Database
    • geoip_region_by_name - Get the country code and region
    • geoip_region_name_by_code - Returns the region name for some country and region code combo
    • geoip_setup_custom_directory - Set a custom directory for the GeoIP database
    • geoip_time_zone_by_country_and_region - Returns the time zone for some country and region code combo
    • getallheaders - Fetch all HTTP request headers
    • getcwd - Gets the current working directory
    • getdate - Get date/time information
    • getenv - Gets the value of an environment variable
    • gethostbyaddr - Get the Internet host name corresponding to a given IP address
    • gethostbyname - Get the IPv4 address corresponding to a given Internet host name
    • gethostbynamel - Get a list of IPv4 addresses corresponding to a given Internet host name
    • gethostname - Gets the host name
    • getimagesize - Get the size of an image
    • getimagesizefromstring - Get the size of an image from a string
    • getlastmod - Gets time of last page modification
    • getmxrr - Get MX records corresponding to a given Internet host name
    • 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
    • getprotobyname - Get protocol number associated with protocol name
    • getprotobynumber - Get protocol name associated with protocol number
    • getrandmax - Show largest possible random value
    • getrusage - Gets the current resource usages
    • getservbyname - Get port number associated with an Internet service and protocol
    • getservbyport - Get Internet service which corresponds to port and protocol
    • getSession - Connect to a MySQL server
    • gettext - Lookup a message in the current domain
    • gettimeofday - Get current time
    • gettype - Get the type of a variable
    • get_browser - Tells what the user's browser is capable of
    • get_called_class - The "Late Static Binding" class name
    • get_cfg_var - Gets the value of a PHP configuration option
    • get_class - Returns the name of the class of an object
    • get_class_methods - Gets the class methods' names
    • get_class_vars - Get the default properties of the class
    • get_current_user - Gets the name of the owner of the current PHP script
    • get_declared_classes - Returns an array with the name of the defined classes
    • get_declared_interfaces - Returns an array of all declared interfaces
    • get_declared_traits - Returns an array of all declared traits
    • 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
    • get_extension_funcs - Returns an array with the names of the functions of a module
    • get_headers - Fetches all the headers sent by the server in response to an HTTP request
    • get_html_translation_table - Returns the translation table used by htmlspecialchars and htmlentities
    • get_included_files - Returns an array with the names of included or required files
    • get_include_path - Gets the current include_path configuration option
    • 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_meta_tags - Extracts all meta tag content attributes from a file and returns an array
    • get_object_vars - Gets the properties of the given object
    • get_parent_class - Retrieves the parent class name for object or class
    • get_required_files - Alias of get_included_files
    • get_resources - Returns active resources
    • get_resource_type - Returns the resource type
    • glob - Find pathnames matching a pattern
    • glob:// - Find pathnames matching pattern
    • GlobIterator::count - Get the number of directories and files
    • GlobIterator::__construct - Construct a directory using glob
    • 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::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 - The flopimage purpose
    • 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
    • Gmagick::__construct - The Gmagick constructor
    • 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 - The line purpose
    • 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::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
    • GmagickPixel::__construct - The GmagickPixel constructor
    • gmdate - Format a GMT/UTC date/time
    • gmmktime - Get Unix timestamp for a GMT date
    • 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_divexact - Exact division of numbers
    • 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_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 - Random number
    • 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
    • gmstrftime - Format a GMT/UTC time/date according to locale settings
    • 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_encrypt - Encrypts a given text
    • gnupg_encryptsign - Encrypts and signs a given text
    • gnupg_export - Exports a key
    • gnupg_geterror - Returns the errortext, if a function fails
    • gnupg_getprotocol - Returns the currently active protocol for all operations
    • 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_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
    • gopher_parsedir - Translate a gopher formatted directory entry into an associative array
    • grapheme_extract - Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8
    • 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
    • gregoriantojd - Converts a Gregorian date to Julian Day Count
    • gupnp_context_get_host_ip - Get the IP address
    • gupnp_context_get_port - Get the port
    • gupnp_context_get_subscription_timeout - Get the event subscription timeout
    • gupnp_context_host_path - Start hosting
    • gupnp_context_new - Create a new context
    • gupnp_context_set_subscription_timeout - Sets the event subscription timeout
    • gupnp_context_timeout_add - Sets a function to be called at regular intervals
    • gupnp_context_unhost_path - Stop hosting
    • gupnp_control_point_browse_start - Start browsing
    • gupnp_control_point_browse_stop - Stop browsing
    • gupnp_control_point_callback_set - Set control point callback
    • gupnp_control_point_new - Create a new control point
    • gupnp_device_action_callback_set - Set device callback function
    • gupnp_device_info_get - Get info of root device
    • gupnp_device_info_get_service - Get the service with type
    • gupnp_root_device_get_available - Check whether root device is available
    • gupnp_root_device_get_relative_location - Get the relative location of root device
    • gupnp_root_device_new - Create a new root device
    • gupnp_root_device_set_available - Set whether or not root_device is available
    • gupnp_root_device_start - Start main loop
    • gupnp_root_device_stop - Stop main loop
    • gupnp_service_action_get - Retrieves the specified action arguments
    • gupnp_service_action_return - Return successfully
    • gupnp_service_action_return_error - Return error code
    • gupnp_service_action_set - Sets the specified action return values
    • gupnp_service_freeze_notify - Freeze new notifications
    • gupnp_service_info_get - Get full info of service
    • gupnp_service_info_get_introspection - Get resource introspection of service
    • gupnp_service_introspection_get_state_variable - Returns the state variable data
    • gupnp_service_notify - Notifies listening clients
    • gupnp_service_proxy_action_get - Send action to the service and get value
    • gupnp_service_proxy_action_set - Send action to the service and set value
    • gupnp_service_proxy_add_notify - Sets up callback for variable change notification
    • gupnp_service_proxy_callback_set - Set service proxy callback for signal
    • gupnp_service_proxy_get_subscribed - Check whether subscription is valid to the service
    • gupnp_service_proxy_remove_notify - Cancels the variable change notification
    • gupnp_service_proxy_send_action - Send action with multiple parameters synchronously
    • gupnp_service_proxy_set_subscribed - (Un)subscribes to the service
    • gupnp_service_thaw_notify - Sends out any pending notifications and stops queuing of new ones
    • 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
  • h
    • HaruAnnotation::setBorderStyle - Set the border style of the annotation
    • HaruAnnotation::setHighlightMode - Set the highlighting mode of the annotation
    • HaruAnnotation::setIcon - Set the icon style of the annotation
    • HaruAnnotation::setOpened - Set the initial state of the annotation
    • HaruDestination::setFit - Set the appearance of the page to fit the window
    • HaruDestination::setFitB - Set the appearance of the page to fit the bounding box of the page within the window
    • HaruDestination::setFitBH - Set the appearance of the page to fit the width of the bounding box
    • HaruDestination::setFitBV - Set the appearance of the page to fit the height of the boudning box
    • HaruDestination::setFitH - Set the appearance of the page to fit the window width
    • HaruDestination::setFitR - Set the appearance of the page to fit the specified rectangle
    • HaruDestination::setFitV - Set the appearance of the page to fit the window height
    • HaruDestination::setXYZ - Set the appearance of the page
    • HaruDoc::addPage - Add new page to the document
    • HaruDoc::addPageLabel - Set the numbering style for the specified range of pages
    • HaruDoc::createOutline - Create a HaruOutline instance
    • HaruDoc::getCurrentEncoder - Get HaruEncoder currently used in the document
    • HaruDoc::getCurrentPage - Return current page of the document
    • HaruDoc::getEncoder - Get HaruEncoder instance for the specified encoding
    • HaruDoc::getFont - Get HaruFont instance
    • HaruDoc::getInfoAttr - Get current value of the specified document attribute
    • HaruDoc::getPageLayout - Get current page layout
    • HaruDoc::getPageMode - Get current page mode
    • HaruDoc::getStreamSize - Get the size of the temporary stream
    • HaruDoc::insertPage - Insert new page just before the specified page
    • HaruDoc::loadJPEG - Load a JPEG image
    • HaruDoc::loadPNG - Load PNG image and return HaruImage instance
    • HaruDoc::loadRaw - Load a RAW image
    • HaruDoc::loadTTC - Load the font with the specified index from TTC file
    • HaruDoc::loadTTF - Load TTF font file
    • HaruDoc::loadType1 - Load Type1 font
    • HaruDoc::output - Write the document data to the output buffer
    • HaruDoc::readFromStream - Read data from the temporary stream
    • HaruDoc::resetError - Reset error state of the document handle
    • HaruDoc::resetStream - Rewind the temporary stream
    • HaruDoc::save - Save the document into the specified file
    • HaruDoc::saveToStream - Save the document into a temporary stream
    • HaruDoc::setCompressionMode - Set compression mode for the document
    • HaruDoc::setCurrentEncoder - Set the current encoder for the document
    • HaruDoc::setEncryptionMode - Set encryption mode for the document
    • HaruDoc::setInfoAttr - Set the info attribute of the document
    • HaruDoc::setInfoDateAttr - Set the datetime info attributes of the document
    • HaruDoc::setOpenAction - Define which page is shown when the document is opened
    • HaruDoc::setPageLayout - Set how pages should be displayed
    • HaruDoc::setPageMode - Set how the document should be displayed
    • HaruDoc::setPagesConfiguration - Set the number of pages per set of pages
    • HaruDoc::setPassword - Set owner and user passwords for the document
    • HaruDoc::setPermission - Set permissions for the document
    • HaruDoc::useCNSEncodings - Enable Chinese simplified encodings
    • HaruDoc::useCNSFonts - Enable builtin Chinese simplified fonts
    • HaruDoc::useCNTEncodings - Enable Chinese traditional encodings
    • HaruDoc::useCNTFonts - Enable builtin Chinese traditional fonts
    • HaruDoc::useJPEncodings - Enable Japanese encodings
    • HaruDoc::useJPFonts - Enable builtin Japanese fonts
    • HaruDoc::useKREncodings - Enable Korean encodings
    • HaruDoc::useKRFonts - Enable builtin Korean fonts
    • HaruDoc::__construct - Construct new HaruDoc instance
    • HaruEncoder::getByteType - Get the type of the byte in the text
    • HaruEncoder::getType - Get the type of the encoder
    • HaruEncoder::getUnicode - Convert the specified character to unicode
    • HaruEncoder::getWritingMode - Get the writing mode of the encoder
    • HaruFont::getAscent - Get the vertical ascent of the font
    • HaruFont::getCapHeight - Get the distance from the baseline of uppercase letters
    • HaruFont::getDescent - Get the vertical descent of the font
    • HaruFont::getEncodingName - Get the name of the encoding
    • HaruFont::getFontName - Get the name of the font
    • HaruFont::getTextWidth - Get the total width of the text, number of characters, number of words and number of spaces
    • HaruFont::getUnicodeWidth - Get the width of the character in the font
    • HaruFont::getXHeight - Get the distance from the baseline of lowercase letters
    • HaruFont::measureText - Calculate the number of characters which can be included within the specified width
    • HaruImage::getBitsPerComponent - Get the number of bits used to describe each color component of the image
    • HaruImage::getColorSpace - Get the name of the color space
    • HaruImage::getHeight - Get the height of the image
    • HaruImage::getSize - Get size of the image
    • HaruImage::getWidth - Get the width of the image
    • HaruImage::setColorMask - Set the color mask of the image
    • HaruImage::setMaskImage - Set the image mask
    • HaruOutline::setDestination - Set the destination for the outline
    • HaruOutline::setOpened - Set the initial state of the outline
    • HaruPage::arc - Append an arc to the current path
    • HaruPage::beginText - Begin a text object and set the current text position to (0,0)
    • HaruPage::circle - Append a circle to the current path
    • HaruPage::closePath - Append a straight line from the current point to the start point of the path
    • HaruPage::concat - Concatenate current transformation matrix of the page and the specified matrix
    • HaruPage::createDestination - Create new HaruDestination instance
    • HaruPage::createLinkAnnotation - Create new HaruAnnotation instance
    • HaruPage::createTextAnnotation - Create new HaruAnnotation instance
    • HaruPage::createURLAnnotation - Create and return new HaruAnnotation instance
    • HaruPage::curveTo - Append a Bezier curve to the current path
    • HaruPage::curveTo2 - Append a Bezier curve to the current path
    • HaruPage::curveTo3 - Append a Bezier curve to the current path
    • HaruPage::drawImage - Show image at the page
    • HaruPage::ellipse - Append an ellipse to the current path
    • HaruPage::endPath - End current path object without filling and painting operations
    • HaruPage::endText - End current text object
    • HaruPage::eofill - Fill current path using even-odd rule
    • HaruPage::eoFillStroke - Fill current path using even-odd rule, then paint the path
    • HaruPage::fill - Fill current path using nonzero winding number rule
    • HaruPage::fillStroke - Fill current path using nonzero winding number rule, then paint the path
    • HaruPage::getCharSpace - Get the current value of character spacing
    • HaruPage::getCMYKFill - Get the current filling color
    • HaruPage::getCMYKStroke - Get the current stroking color
    • HaruPage::getCurrentFont - Get the currently used font
    • HaruPage::getCurrentFontSize - Get the current font size
    • HaruPage::getCurrentPos - Get the current position for path painting
    • HaruPage::getCurrentTextPos - Get the current position for text printing
    • HaruPage::getDash - Get the current dash pattern
    • HaruPage::getFillingColorSpace - Get the current filling color space
    • HaruPage::getFlatness - Get the flatness of the page
    • HaruPage::getGMode - Get the current graphics mode
    • HaruPage::getGrayFill - Get the current filling color
    • HaruPage::getGrayStroke - Get the current stroking color
    • HaruPage::getHeight - Get the height of the page
    • HaruPage::getHorizontalScaling - Get the current value of horizontal scaling
    • HaruPage::getLineCap - Get the current line cap style
    • HaruPage::getLineJoin - Get the current line join style
    • HaruPage::getLineWidth - Get the current line width
    • HaruPage::getMiterLimit - Get the value of miter limit
    • HaruPage::getRGBFill - Get the current filling color
    • HaruPage::getRGBStroke - Get the current stroking color
    • HaruPage::getStrokingColorSpace - Get the current stroking color space
    • HaruPage::getTextLeading - Get the current value of line spacing
    • HaruPage::getTextMatrix - Get the current text transformation matrix of the page
    • HaruPage::getTextRenderingMode - Get the current text rendering mode
    • HaruPage::getTextRise - Get the current value of text rising
    • HaruPage::getTextWidth - Get the width of the text using current fontsize, character spacing and word spacing
    • HaruPage::getTransMatrix - Get the current transformation matrix of the page
    • HaruPage::getWidth - Get the width of the page
    • HaruPage::getWordSpace - Get the current value of word spacing
    • HaruPage::lineTo - Draw a line from the current point to the specified point
    • HaruPage::measureText - Calculate the byte length of characters which can be included on one line of the specified width
    • HaruPage::moveTextPos - Move text position to the specified offset
    • HaruPage::moveTo - Set starting point for new drawing path
    • HaruPage::moveToNextLine - Move text position to the start of the next line
    • HaruPage::rectangle - Append a rectangle to the current path
    • HaruPage::setCharSpace - Set character spacing for the page
    • HaruPage::setCMYKFill - Set filling color for the page
    • HaruPage::setCMYKStroke - Set stroking color for the page
    • HaruPage::setDash - Set the dash pattern for the page
    • HaruPage::setFlatness - Set flatness for the page
    • HaruPage::setFontAndSize - Set font and fontsize for the page
    • HaruPage::setGrayFill - Set filling color for the page
    • HaruPage::setGrayStroke - Sets stroking color for the page
    • HaruPage::setHeight - Set height of the page
    • HaruPage::setHorizontalScaling - Set horizontal scaling for the page
    • HaruPage::setLineCap - Set the shape to be used at the ends of lines
    • HaruPage::setLineJoin - Set line join style for the page
    • HaruPage::setLineWidth - Set line width for the page
    • HaruPage::setMiterLimit - Set the current value of the miter limit of the page
    • HaruPage::setRGBFill - Set filling color for the page
    • HaruPage::setRGBStroke - Set stroking color for the page
    • HaruPage::setRotate - Set rotation angle of the page
    • HaruPage::setSize - Set size and direction of the page
    • HaruPage::setSlideShow - Set transition style for the page
    • HaruPage::setTextLeading - Set text leading (line spacing) for the page
    • HaruPage::setTextMatrix - Set the current text transformation matrix of the page
    • HaruPage::setTextRenderingMode - Set text rendering mode for the page
    • HaruPage::setTextRise - Set the current value of text rising
    • HaruPage::setWidth - Set width of the page
    • HaruPage::setWordSpace - Set word spacing for the page
    • HaruPage::showText - Print text at the current position of the page
    • HaruPage::showTextNextLine - Move the current position to the start of the next line and print the text
    • HaruPage::stroke - Paint current path
    • HaruPage::textOut - Print the text on the specified position
    • HaruPage::textRect - Print the text inside the specified region
    • hash - Generate a hash value (message digest)
    • HashContext::__construct - Private constructor to disallow direct instantiation
    • 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
    • header - Send a raw HTTP header
    • headers_list - Returns a list of response headers sent (or ready to send)
    • headers_sent - Checks if or where headers have been sent
    • header_register_callback - Call a header function
    • header_remove - Remove previously set headers
    • hebrev - Convert logical Hebrew text to visual text
    • hebrevc - Convert logical Hebrew text to visual text with newline conversion
    • hex2bin - Decodes a hexadecimally encoded binary string
    • hexdec - Hexadecimal to decimal
    • highlight_file - Syntax highlighting of a file
    • highlight_string - Syntax highlighting of a string
    • hrtime - Get the system's high resolution time
    • 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::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
    • htmlentities - Convert all applicable characters to HTML entities
    • htmlspecialchars - Convert special characters to HTML entities
    • htmlspecialchars_decode - Convert special HTML entities back to characters
    • html_entity_decode - Convert HTML entities to their corresponding characters
    • http:// - Accessing HTTP(s) URLs
    • HTTP context options - HTTP context option listing
    • http_build_query - Generate URL-encoded query string
    • http_response_code - Get or Set the HTTP response code
    • hwapi_attribute_new - Creates instance of class hw_api_attribute
    • hwapi_content_new - Create new instance of class hw_api_content
    • hwapi_hgcsp - Returns object of class hw_api
    • hwapi_object_new - Creates a new instance of class hwapi_object_new
    • hw_api::checkin - Checks in an object
    • hw_api::checkout - Checks out an object
    • hw_api::children - Returns children of an object
    • hw_api::content - Returns content of an object
    • hw_api::copy - Copies physically
    • hw_api::dbstat - Returns statistics about database server
    • hw_api::dcstat - Returns statistics about document cache server
    • hw_api::dstanchors - Returns a list of all destination anchors
    • hw_api::dstofsrcanchor - Returns destination of a source anchor
    • hw_api::find - Search for objects
    • hw_api::ftstat - Returns statistics about fulltext server
    • hw_api::hwstat - Returns statistics about Hyperwave server
    • hw_api::identify - Log into Hyperwave Server
    • hw_api::info - Returns information about server configuration
    • hw_api::insert - Inserts a new object
    • hw_api::insertanchor - Inserts a new object of type anchor
    • hw_api::insertcollection - Inserts a new object of type collection
    • hw_api::insertdocument - Inserts a new object of type document
    • hw_api::link - Creates a link to an object
    • hw_api::lock - Locks an object
    • hw_api::move - Moves object between collections
    • hw_api::object - Retrieve attribute information
    • hw_api::objectbyanchor - Returns the object an anchor belongs to
    • hw_api::parents - Returns parents of an object
    • hw_api::remove - Delete an object
    • hw_api::replace - Replaces an object
    • hw_api::setcommittedversion - Commits version other than last version
    • hw_api::srcanchors - Returns a list of all source anchors
    • hw_api::srcsofdst - Returns source of a destination object
    • hw_api::unlock - Unlocks a locked object
    • hw_api::user - Returns the own user object
    • hw_api::userlist - Returns a list of all logged in users
    • hw_api_attribute::key - Returns key of the attribute
    • hw_api_attribute::langdepvalue - Returns value for a given language
    • hw_api_attribute::value - Returns value of the attribute
    • hw_api_attribute::values - Returns all values of the attribute
    • hw_api_content::mimetype - Returns mimetype
    • hw_api_content::read - Read content
    • hw_api_error::count - Returns number of reasons
    • hw_api_error::reason - Returns reason of error
    • hw_api_object::assign - Clones object
    • hw_api_object::attreditable - Checks whether an attribute is editable
    • hw_api_object::count - Returns number of attributes
    • hw_api_object::insert - Inserts new attribute
    • hw_api_object::remove - Removes attribute
    • hw_api_object::title - Returns the title attribute
    • hw_api_object::value - Returns value of attribute
    • hw_api_reason::description - Returns description of reason
    • hw_api_reason::type - Returns type of reason
    • hypot - Calculate the length of the hypotenuse of a right-angle triangle
  • i
    • 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
    • iconv - Convert string to requested character encoding
    • 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
    • id3_get_frame_long_name - Get the long name of an ID3v2 frame
    • id3_get_frame_short_name - Get the short name of an ID3v2 frame
    • id3_get_genre_id - Get the id for a genre
    • id3_get_genre_list - Get all possible genre values
    • id3_get_genre_name - Get the name for a genre id
    • id3_get_tag - Get all information stored in an ID3 tag
    • id3_get_version - Get version of an ID3 tag
    • id3_remove_tag - Remove an existing ID3 tag
    • id3_set_tag - Update information stored in an ID3 tag
    • idate - Format a local time/date as integer
    • idn_to_ascii - Convert domain name to IDNA ASCII form
    • idn_to_utf8 - Convert domain name from IDNA ASCII to Unicode
    • ifxus_close_slob - Deletes the slob object
    • ifxus_create_slob - Creates an slob object and opens it
    • ifxus_free_slob - Deletes the slob object
    • ifxus_open_slob - Opens an slob object
    • ifxus_read_slob - Reads nbytes of the slob object
    • ifxus_seek_slob - Sets the current file or seek position
    • ifxus_tell_slob - Returns the current file or seek position
    • ifxus_write_slob - Writes a string into the slob object
    • ifx_affected_rows - Get number of rows affected by a query
    • ifx_blobinfile_mode - Set the default blob mode for all select queries
    • ifx_byteasvarchar - Set the default byte mode
    • ifx_close - Close Informix connection
    • ifx_connect - Open Informix server connection
    • ifx_copy_blob - Duplicates the given blob object
    • ifx_create_blob - Creates an blob object
    • ifx_create_char - Creates an char object
    • ifx_do - Execute a previously prepared SQL-statement
    • ifx_error - Returns error code of last Informix call
    • ifx_errormsg - Returns error message of last Informix call
    • ifx_fetch_row - Get row as an associative array
    • ifx_fieldproperties - List of SQL fieldproperties
    • ifx_fieldtypes - List of Informix SQL fields
    • ifx_free_blob - Deletes the blob object
    • ifx_free_char - Deletes the char object
    • ifx_free_result - Releases resources for the query
    • ifx_getsqlca - Get the contents of sqlca.sqlerrd[0..5] after a query
    • ifx_get_blob - Return the content of a blob object
    • ifx_get_char - Return the content of the char object
    • ifx_htmltbl_result - Formats all rows of a query into a HTML table
    • ifx_nullformat - Sets the default return value on a fetch row
    • ifx_num_fields - Returns the number of columns in the query
    • ifx_num_rows - Count the rows already fetched from a query
    • ifx_pconnect - Open persistent Informix connection
    • ifx_prepare - Prepare an SQL-statement for execution
    • ifx_query - Send Informix query
    • ifx_textasvarchar - Set the default text mode
    • ifx_update_blob - Updates the content of the blob object
    • ifx_update_char - Updates the content of the char object
    • ignore_user_abort - Set whether a client disconnect should abort script execution
    • iis_add_server - Creates a new virtual web server
    • iis_get_dir_security - Gets Directory Security
    • iis_get_script_map - Gets script mapping on a virtual directory for a specific extension
    • iis_get_server_by_comment - Return the instance number associated with the Comment
    • iis_get_server_by_path - Return the instance number associated with the Path
    • iis_get_server_rights - Gets server rights
    • iis_get_service_state - Returns the state for the service defined by ServiceId
    • iis_remove_server - Removes the virtual web server indicated by ServerInstance
    • iis_set_app_settings - Creates application scope for a virtual directory
    • iis_set_dir_security - Sets Directory Security
    • iis_set_script_map - Sets script mapping on a virtual directory
    • iis_set_server_rights - Sets server rights
    • iis_start_server - Starts the virtual web server
    • iis_start_service - Starts the service defined by ServiceId
    • iis_stop_server - Stops the virtual web server
    • iis_stop_service - Stops the service defined by ServiceId
    • 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
    • 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
    • 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
    • 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
    • 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
    • imagepsbbox - Give the bounding box of a text rectangle using PostScript Type1 fonts
    • imagepsencodefont - Change the character encoding vector of a font
    • imagepsextendfont - Extend or condense a font
    • imagepsfreefont - Free memory used by a PostScript Type 1 font
    • imagepsloadfont - Load a PostScript Type 1 font from file
    • imagepsslantfont - Slant a font
    • imagepstext - Draws a text over an image using PostScript Type1 fonts
    • 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 PNG 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
    • 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
    • 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 - Description
    • Imagick::averageImages - Average a set of images
    • Imagick::blackThresholdImage - Forces all pixels below the threshold into black
    • Imagick::blueShiftImage - Description
    • Imagick::blurImage - Adds blur filter to image
    • Imagick::borderImage - Surrounds the image with a border
    • Imagick::brightnessContrastImage - Description
    • Imagick::charcoalImage - Simulates a charcoal drawing
    • Imagick::chopImage - Removes a region of an image and trims
    • Imagick::clampImage - Description
    • Imagick::clear - Clears all resources associated to Imagick object
    • Imagick::clipImage - Clips along the first path from the 8BIM profile
    • Imagick::clipImagePath - Description
    • 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 - Description
    • 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::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 - Description
    • 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 - Description
    • 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 vertical mirror image
    • Imagick::forwardFourierTransformImage - Description
    • 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 - Gets the image alpha channel
    • Imagick::getImageArtifact - Get image artifact
    • Imagick::getImageAttribute - Description
    • 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::getImageMagickLicense - Returns a string containing the ImageMagick license
    • Imagick::getImageMatte - Return if the image has a matte channel
    • Imagick::getImageMatteColor - Returns the image matte color
    • Imagick::getImageMimeType - Description
    • 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 - Description
    • Imagick::getQuantumDepth - Gets the quantum depth
    • Imagick::getQuantumRange - Returns the Imagick quantum range
    • Imagick::getRegistry - Description
    • 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 - Description
    • Imagick::identifyImage - Identifies an image and fetches attributes
    • Imagick::implodeImage - Creates a new image as a copy
    • Imagick::importImagePixels - Imports image pixels
    • Imagick::inverseFourierTransformImage - Description
    • 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 - Description
    • 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 - Description
    • 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 - Description
    • 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 - Description
    • 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 - Description
    • 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 - Description
    • Imagick::setImageBackgroundColor - Sets the image background color
    • Imagick::setImageBias - Sets the image bias for any method that convolves an image
    • Imagick::setImageBiasQuantum - Description
    • 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 - Description
    • Imagick::setRegistry - Description
    • 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 - Description
    • 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 - Description
    • 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 - Description
    • 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::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
    • Imagick::__construct - The Imagick constructor
    • Imagick::__toString - Returns the image as a string
    • 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::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 - Description
    • 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 - Description
    • ImagickDraw::getTextInterwordSpacing - Description
    • ImagickDraw::getTextKerning - Description
    • 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 - Description
    • 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 - Description
    • 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 - Description
    • ImagickDraw::setTextInterwordSpacing - Description
    • ImagickDraw::setTextKerning - Description
    • 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
    • ImagickDraw::__construct - The ImagickDraw constructor
    • ImagickKernel::addKernel - Description
    • ImagickKernel::addUnityKernel - Description
    • ImagickKernel::fromBuiltIn - Description
    • ImagickKernel::fromMatrix - Description
    • ImagickKernel::getMatrix - Description
    • ImagickKernel::scale - Description
    • ImagickKernel::separate - Description
    • ImagickPixel::clear - Clears resources associated with this object
    • 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 - Description
    • ImagickPixel::getColorValue - Gets the normalized value of the provided color channel
    • ImagickPixel::getColorValueQuantum - Description
    • ImagickPixel::getHSL - Returns the normalized HSL color of the ImagickPixel object
    • ImagickPixel::getIndex - Description
    • ImagickPixel::isPixelSimilar - Check the distance between this color and another
    • ImagickPixel::isPixelSimilarQuantum - Description
    • ImagickPixel::isSimilar - Check the distance between this color and another
    • ImagickPixel::setColor - Sets the color
    • ImagickPixel::setColorCount - Description
    • ImagickPixel::setColorValue - Sets the normalized value of one of the channels
    • ImagickPixel::setColorValueQuantum - Description
    • ImagickPixel::setHSL - Sets the normalized HSL color
    • ImagickPixel::setIndex - Description
    • ImagickPixel::__construct - The ImagickPixel constructor
    • ImagickPixelIterator::clear - Clear resources associated with a PixelIterator
    • 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
    • ImagickPixelIterator::__construct - The ImagickPixelIterator constructor
    • 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_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_fetch_overview - Read an overview of the information in the headers of the given message
    • imap_gc - Clears IMAP cache
    • 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_get_quota - Retrieve the quota level settings, and usage statics per mailbox
    • imap_get_quotaroot - Retrieve the quota settings per user
    • 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_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_mailboxmsginfo - Get information about the current mailbox
    • 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_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_setacl - Sets the ACL for a given mailbox
    • imap_setflag_full - Sets flags on messages
    • imap_set_quota - Sets a quota for a given mailbox
    • 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
    • implode - Join array elements with a string
    • import_request_variables - Import GET/POST/Cookie variables into the global scope
    • inclued_get_data - Get the inclued data
    • inet_ntop - Converts a packed internet address to a human readable representation
    • inet_pton - Converts a human readable IP address to its packed in_addr representation
    • InfiniteIterator::next - Moves the inner Iterator forward or rewinds it
    • InfiniteIterator::__construct - Constructs an InfiniteIterator
    • 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
    • ingres_autocommit - Switch autocommit on or off
    • ingres_autocommit_state - Test if the connection is using autocommit
    • ingres_charset - Returns the installation character set
    • ingres_close - Close an Ingres database connection
    • ingres_commit - Commit a transaction
    • ingres_connect - Open a connection to an Ingres database
    • ingres_cursor - Get a cursor name for a given result resource
    • ingres_errno - Get the last Ingres error number generated
    • ingres_error - Get a meaningful error message for the last error generated
    • ingres_errsqlstate - Get the last SQLSTATE error code generated
    • ingres_escape_string - Escape special characters for use in a query
    • ingres_execute - Execute a prepared query
    • ingres_fetch_array - Fetch a row of result into an array
    • ingres_fetch_assoc - Fetch a row of result into an associative array
    • ingres_fetch_object - Fetch a row of result into an object
    • ingres_fetch_proc_return - Get the return value from a procedure call
    • ingres_fetch_row - Fetch a row of result into an enumerated array
    • ingres_field_length - Get the length of a field
    • ingres_field_name - Get the name of a field in a query result
    • ingres_field_nullable - Test if a field is nullable
    • ingres_field_precision - Get the precision of a field
    • ingres_field_scale - Get the scale of a field
    • ingres_field_type - Get the type of a field in a query result
    • ingres_free_result - Free the resources associated with a result identifier
    • ingres_next_error - Get the next Ingres error
    • ingres_num_fields - Get the number of fields returned by the last query
    • ingres_num_rows - Get the number of rows affected or returned by a query
    • ingres_pconnect - Open a persistent connection to an Ingres database
    • ingres_prepare - Prepare a query for later execution
    • ingres_query - Send an SQL query to Ingres
    • ingres_result_seek - Set the row position before fetching data
    • ingres_rollback - Roll back a transaction
    • ingres_set_environment - Set environment features controlling output options
    • ingres_unbuffered_query - Send an unbuffered SQL query to Ingres
    • ini_alter - Alias of ini_set
    • 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
    • ini_set - Sets the value of a configuration option
    • 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
    • intdiv - Integer division
    • interface_exists - Checks if the interface has been defined
    • 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
    • IntlBreakIterator::__construct - Private constructor for disallowing instantiation
    • 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::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::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
    • IntlCalendar::__construct - Private constructor for disallowing instantiation
    • 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
    • IntlCodePointBreakIterator::getLastCodePoint - Get last code point passed over after advancing or receding the iterator
    • 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::getCalendarObject - Get copy of formatterʼs calendar object
    • 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::getTimeZone - Get formatterʼs timezone
    • IntlDateFormatter::getTimeZoneId - Get the timezone-id used for the IntlDateFormatter
    • 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
    • IntlDateFormatter::setTimeZoneId - Sets the time zone to use
    • 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
    • IntlGregorianCalendar::__construct - Create the Gregorian Calendar 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
    • IntlPartsIterator::getBreakIterator - Get IntlBreakIterator backing this parts iterator
    • 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
    • IntlRuleBasedBreakIterator::__construct - Create iterator from ruleset
    • 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
    • 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
    • intval - Get the integer value of a variable
    • in_array - Checks if a value exists in an array
    • ip2long - Converts a string containing an (IPv4) Internet Protocol dotted address into a long integer
    • iptcembed - Embeds binary IPTC data into a JPEG image
    • iptcparse - Parse a binary IPTC block into single tags
    • isset - Determine if a variable is declared and is different than NULL
    • is_a - Checks if the object is of this class or has this class as one of its parents
    • is_array - Finds whether a variable is an array
    • is_bool - Finds out whether a variable is a boolean
    • is_callable - Verify that the contents of a variable can be called as a function
    • is_countable - Verify that the contents of a variable is a countable value
    • is_dir - Tells whether the filename is a directory
    • is_double - Alias of is_float
    • is_executable - Tells whether the filename is executable
    • is_file - Tells whether the filename is a regular file
    • is_finite - Finds whether a value is a legal finite number
    • is_float - Finds whether the type of a variable is float
    • is_infinite - Finds whether a value is infinite
    • is_int - Find whether the type of a variable is integer
    • is_integer - Alias of is_int
    • is_iterable - Verify that the contents of a variable is an iterable value
    • is_link - Tells whether the filename is a symbolic link
    • is_long - Alias of is_int
    • is_nan - Finds whether a value is not a number
    • is_null - Finds whether a variable is NULL
    • is_numeric - Finds whether a variable is a number or a numeric string
    • is_object - Finds whether a variable is an object
    • is_readable - Tells whether a file exists and is readable
    • is_real - Alias of is_float
    • is_resource - Finds whether a variable is a resource
    • is_scalar - Finds whether a variable is a scalar
    • is_soap_fault - Checks if a SOAP call has failed
    • is_string - Find whether the type of a variable is string
    • is_subclass_of - Checks if the object has this class as one of its parents or implements it
    • is_tainted - Checks whether a string is tainted
    • 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
    • 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
    • IteratorAggregate::getIterator - Retrieve an external iterator
    • IteratorIterator::current - Get the current value
    • IteratorIterator::getInnerIterator - Get the inner iterator
    • IteratorIterator::key - Get the key of the current element
    • IteratorIterator::next - Forward to the next element
    • IteratorIterator::rewind - Rewind to the first element
    • IteratorIterator::valid - Checks if the iterator is valid
    • IteratorIterator::__construct - Create an iterator from anything that is traversable
    • iterator_apply - Call a function for every element in an iterator
    • iterator_count - Count the elements in an iterator
    • iterator_to_array - Copy the iterator into an array
  • j
    • 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
    • join - Alias of implode
    • jpeg2wbmp - Convert JPEG image file to WBMP image file
    • JsonSerializable::jsonSerialize - Specify data which should be serialized to JSON
    • json_decode - Decodes a JSON string
    • json_encode - Returns the JSON representation of a value
    • json_last_error - Returns the last error occurred
    • json_last_error_msg - Returns the error string of the last json_encode() or json_decode() call
    • Judy::byCount - Locate the Nth index present in the Judy array
    • Judy::count - Count the number of elements in the Judy array
    • Judy::first - Search for the first index in the Judy array
    • Judy::firstEmpty - Search for the first absent index in the Judy array
    • Judy::free - Free the entire Judy array
    • Judy::getType - Return the type of the current Judy array
    • Judy::last - Search for the last index in the Judy array
    • Judy::lastEmpty - Search for the last absent index in the Judy array
    • Judy::memoryUsage - Return the memory used by the Judy array
    • Judy::next - Search for the next index in the Judy array
    • Judy::nextEmpty - Search for the next absent index in the Judy array
    • Judy::offsetExists - Whether a offset exists
    • Judy::offsetGet - Offset to retrieve
    • Judy::offsetSet - Offset to set
    • Judy::offsetUnset - Offset to unset
    • Judy::prev - Search for the previous index in the Judy array
    • Judy::prevEmpty - Search for the previous absent index in the Judy array
    • Judy::size - Return the size of the current Judy array
    • Judy::__construct - Construct a new Judy object
    • Judy::__destruct - Destruct a Judy object
    • judy_type - Return the type of a Judy array
    • judy_version - Return or print the current PHP Judy version
    • juliantojd - Converts a Julian Calendar date to Julian Day Count
  • k
    • kadm5_chpass_principal - Changes the principal's password
    • kadm5_create_principal - Creates a kerberos principal with the given parameters
    • kadm5_delete_principal - Deletes a kerberos principal
    • kadm5_destroy - Closes the connection to the admin server and releases all related resources
    • kadm5_flush - Flush all changes to the Kerberos database
    • kadm5_get_policies - Gets all policies from the Kerberos database
    • kadm5_get_principal - Gets the principal's entries from the Kerberos database
    • kadm5_get_principals - Gets all principals from the Kerberos database
    • kadm5_init_with_password - Opens a connection to the KADM5 library
    • kadm5_modify_principal - Modifies a kerberos principal with the given parameters
    • key - Fetch a key from an array
    • key_exists - Alias of array_key_exists
    • krsort - Sort an array by key in reverse order
    • ksort - Sort an array by key
    • KTaglib_ID3v2_AttachedPictureFrame::getDescription - Returns a description for the picture in a picture frame
    • KTaglib_ID3v2_AttachedPictureFrame::getMimeType - Returns the mime type of the picture
    • KTaglib_ID3v2_AttachedPictureFrame::getType - Returns the type of the image
    • KTaglib_ID3v2_AttachedPictureFrame::savePicture - Saves the picture to a file
    • KTaglib_ID3v2_AttachedPictureFrame::setMimeType - Set's the mime type of the picture
    • KTaglib_ID3v2_AttachedPictureFrame::setPicture - Sets the frame picture to the given image
    • KTaglib_ID3v2_AttachedPictureFrame::setType - Set the type of the image
    • KTaglib_ID3v2_Frame::getSize - Returns the size of the frame in bytes
    • KTaglib_ID3v2_Frame::__toString - Returns a string representation of the frame
    • KTaglib_ID3v2_Tag::addFrame - Add a frame to the ID3v2 tag
    • KTaglib_ID3v2_Tag::getFrameList - Returns an array of ID3v2 frames, associated with the ID3v2 tag
    • KTaglib_MPEG_AudioProperties::getBitrate - Returns the bitrate of the MPEG file
    • KTaglib_MPEG_AudioProperties::getChannels - Returns the amount of channels of a MPEG file
    • KTaglib_MPEG_AudioProperties::getLayer - Returns the layer of a MPEG file
    • KTaglib_MPEG_AudioProperties::getLength - Returns the length of a MPEG file
    • KTaglib_MPEG_AudioProperties::getSampleBitrate - Returns the sample bitrate of a MPEG file
    • KTaglib_MPEG_AudioProperties::getVersion - Returns the version of a MPEG file
    • KTaglib_MPEG_AudioProperties::isCopyrighted - Returns the copyright status of an MPEG file
    • KTaglib_MPEG_AudioProperties::isOriginal - Returns if the file is marked as the original file
    • KTaglib_MPEG_AudioProperties::isProtectionEnabled - Returns if protection mechanisms of an MPEG file are enabled
    • KTaglib_MPEG_File::getAudioProperties - Returns an object that provides access to the audio properties
    • KTaglib_MPEG_File::getID3v1Tag - Returns an object representing an ID3v1 tag
    • KTaglib_MPEG_File::getID3v2Tag - Returns a ID3v2 object
    • KTaglib_MPEG_File::__construct - Opens a new file
    • KTaglib_Tag::getAlbum - Returns the album string from a ID3 tag
    • KTaglib_Tag::getArtist - Returns the artist string from a ID3 tag
    • KTaglib_Tag::getComment - Returns the comment from a ID3 tag
    • KTaglib_Tag::getGenre - Returns the genre from a ID3 tag
    • KTaglib_Tag::getTitle - Returns the title string from a ID3 tag
    • KTaglib_Tag::getTrack - Returns the track number from a ID3 tag
    • KTaglib_Tag::getYear - Returns the year from a ID3 tag
    • KTaglib_Tag::isEmpty - Returns true if the tag is empty
  • l
    • Lapack::eigenValues - This function returns the eigenvalues for a given square matrix
    • Lapack::identity - Return an identity matrix
    • Lapack::leastSquaresByFactorisation - Calculate the linear least squares solution of a matrix using QR factorisation
    • Lapack::leastSquaresBySVD - Solve the linear least squares problem, using SVD
    • Lapack::pseudoInverse - Calculate the inverse of a matrix
    • Lapack::singularValues - Calculated the singular values of a matrix
    • Lapack::solveLinearEquation - Solve a system of linear equations
    • lcfirst - Make a string's first character lowercase
    • lcg_value - Combined linear congruential generator
    • lchgrp - Changes group ownership of symlink
    • lchown - Changes user ownership of symlink
    • ldap_8859_to_t61 - Translate 8859 characters to t61 characters
    • ldap_add - Add entries to LDAP directory
    • ldap_add_ext - Add entries to LDAP directory
    • ldap_bind - Bind to LDAP directory
    • ldap_bind_ext - Bind to LDAP directory
    • ldap_close - Alias of ldap_unbind
    • ldap_compare - Compare value of attribute found in entry specified with DN
    • ldap_connect - Connect to an LDAP server
    • ldap_control_paged_result - Send LDAP pagination control
    • ldap_control_paged_result_response - Retrieve the LDAP pagination cookie
    • ldap_count_entries - Count the number of entries in a search
    • ldap_delete - Delete an entry from a directory
    • ldap_delete_ext - Delete an entry from a directory
    • ldap_dn2ufn - Convert DN to User Friendly Naming format
    • ldap_err2str - Convert LDAP error number into string error message
    • ldap_errno - Return the LDAP error number of the last LDAP command
    • ldap_error - Return the LDAP error message of the last LDAP command
    • ldap_escape - Escape a string for use in an LDAP filter or DN
    • ldap_exop - Performs an extended operation
    • ldap_exop_passwd - PASSWD extended operation helper
    • ldap_exop_refresh - Refresh extended operation helper
    • ldap_exop_whoami - WHOAMI extended operation helper
    • ldap_explode_dn - Splits DN into its component parts
    • ldap_first_attribute - Return first attribute
    • ldap_first_entry - Return first result id
    • ldap_first_reference - Return first reference
    • ldap_free_result - Free result memory
    • ldap_get_attributes - Get attributes from a search result entry
    • ldap_get_dn - Get the DN of a result entry
    • ldap_get_entries - Get all result entries
    • ldap_get_option - Get the current value for given option
    • ldap_get_values - Get all values from a result entry
    • ldap_get_values_len - Get all binary values from a result entry
    • ldap_list - Single-level search
    • ldap_modify - Alias of ldap_mod_replace
    • ldap_modify_batch - Batch and execute modifications on an LDAP entry
    • ldap_mod_add - Add attribute values to current attributes
    • ldap_mod_add_ext - Add attribute values to current attributes
    • ldap_mod_del - Delete attribute values from current attributes
    • ldap_mod_del_ext - Delete attribute values from current attributes
    • ldap_mod_replace - Replace attribute values with new ones
    • ldap_mod_replace_ext - Replace attribute values with new ones
    • ldap_next_attribute - Get the next attribute in result
    • ldap_next_entry - Get next result entry
    • ldap_next_reference - Get next reference
    • ldap_parse_exop - Parse result object from an LDAP extended operation
    • ldap_parse_reference - Extract information from reference entry
    • ldap_parse_result - Extract information from result
    • ldap_read - Read an entry
    • ldap_rename - Modify the name of an entry
    • ldap_rename_ext - Modify the name of an entry
    • ldap_sasl_bind - Bind to LDAP directory using SASL
    • ldap_search - Search LDAP tree
    • ldap_set_option - Set the value of the given option
    • ldap_set_rebind_proc - Set a callback function to do re-binds on referral chasing
    • ldap_sort - Sort LDAP result entries on the client side
    • ldap_start_tls - Start TLS
    • ldap_t61_to_8859 - Translate t61 characters to 8859 characters
    • ldap_unbind - Unbind from LDAP directory
    • levenshtein - Calculate Levenshtein distance between two strings
    • libxml_clear_errors - Clear libxml error buffer
    • libxml_disable_entity_loader - Disable the ability to load external entities
    • libxml_get_errors - Retrieve array of errors
    • libxml_get_last_error - Retrieve last error from libxml
    • libxml_set_external_entity_loader - Changes the default external entity loader
    • libxml_set_streams_context - Set the streams context for the next libxml document load or write
    • libxml_use_internal_errors - Disable libxml errors and allow user to fetch error information as needed
    • LimitIterator::current - Get current element
    • LimitIterator::getInnerIterator - Get inner iterator
    • LimitIterator::getPosition - Return the current position
    • LimitIterator::key - Get current key
    • LimitIterator::next - Move the iterator forward
    • LimitIterator::rewind - Rewind the iterator to the specified starting offset
    • LimitIterator::seek - Seek to the given position
    • LimitIterator::valid - Check whether the current element is valid
    • LimitIterator::__construct - Construct a LimitIterator
    • link - Create a hard link
    • linkinfo - Gets information about a link
    • list - Assign variables as if they were an array
    • 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::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
    • localeconv - Get numeric formatting information
    • localtime - Get the local time
    • log - Natural logarithm
    • log1p - Returns log(1 + number), computed in a way that is accurate even when the value of number is close to zero
    • log10 - Base-10 logarithm
    • log_cmd_delete - Callback When Deleting Documents
    • log_cmd_insert - Callback When Inserting Documents
    • log_cmd_update - Callback When Updating Documents
    • log_getmore - Callback When Retrieving Next Cursor Batch
    • log_killcursor - Callback When Executing KILLCURSOR operations
    • log_reply - Callback When Reading the MongoDB reply
    • log_write_batch - Callback When Writing Batches
    • long2ip - Converts an long integer address into a string in (IPv4) Internet standard dotted format
    • lstat - Gives information about a file or symbolic link
    • ltrim - Strip whitespace (or other characters) from the beginning of a string
    • Lua::assign - Assign a PHP variable to Lua
    • Lua::call - Call Lua functions
    • Lua::eval - Evaluate a string as Lua code
    • Lua::getVersion - The getversion purpose
    • Lua::include - Parse a Lua script file
    • Lua::registerCallback - Register a PHP function to Lua
    • Lua::__construct - Lua constructor
    • LuaClosure::__invoke - Invoke luaclosure
    • LuaSandbox::callFunction - Call a function in a Lua global variable
    • LuaSandbox::disableProfiler - Disable the profiler
    • LuaSandbox::enableProfiler - Enable the profiler.
    • LuaSandbox::getCPUUsage - Fetch the current CPU time usage of the Lua environment
    • LuaSandbox::getMemoryUsage - Fetch the current memory usage of the Lua environment
    • LuaSandbox::getPeakMemoryUsage - Fetch the peak memory usage of the Lua environment
    • LuaSandbox::getProfilerFunctionReport - Fetch profiler data
    • LuaSandbox::getVersionInfo - Return the versions of LuaSandbox and Lua
    • LuaSandbox::loadBinary - Load a precompiled binary chunk into the Lua environment
    • LuaSandbox::loadString - Load Lua code into the Lua environment
    • LuaSandbox::pauseUsageTimer - Pause the CPU usage timer
    • LuaSandbox::registerLibrary - Register a set of PHP functions as a Lua library
    • LuaSandbox::setCPULimit - Set the CPU time limit for the Lua environment
    • LuaSandbox::setMemoryLimit - Set the memory limit for the Lua environment
    • LuaSandbox::unpauseUsageTimer - Unpause the timer paused by LuaSandbox::pauseUsageTimer
    • LuaSandbox::wrapPhpFunction - Wrap a PHP callable in a LuaSandboxFunction
    • LuaSandboxFunction::call - Call a Lua function
    • LuaSandboxFunction::dump - Dump the function as a binary blob
    • LuaSandboxFunction::__construct - Unused
    • lzf_compress - LZF compression
    • lzf_decompress - LZF decompression
    • lzf_optimized_for - Determines what LZF extension was optimized for
  • m
    • magic_quotes_runtime - Alias of set_magic_quotes_runtime
    • mail - Send mail
    • 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
    • main - Dummy for main
    • max - Find highest value
    • maxdb_affected_rows - Gets the number of affected rows in a previous MaxDB operation
    • maxdb_autocommit - Turns on or off auto-commiting database modifications
    • maxdb_bind_param - Alias of maxdb_stmt_bind_param
    • maxdb_bind_result - Alias of maxdb_stmt_bind_result
    • maxdb_change_user - Changes the user of the specified database connection
    • maxdb_character_set_name - Returns the default character set for the database connection
    • maxdb_client_encoding - Alias of maxdb_character_set_name
    • maxdb_close - Closes a previously opened database connection
    • maxdb_close_long_data - Alias of maxdb_stmt_close_long_data
    • maxdb_commit - Commits the current transaction
    • maxdb_connect - Open a new connection to the MaxDB server
    • maxdb_connect_errno - Returns the error code from last connect call
    • maxdb_connect_error - Returns a string description of the last connect error
    • maxdb_data_seek - Adjusts the result pointer to an arbitary row in the result
    • maxdb_debug - Performs debugging operations
    • maxdb_disable_reads_from_master - Disable reads from master
    • maxdb_disable_rpl_parse - Disable RPL parse
    • maxdb_dump_debug_info - Dump debugging information into the log
    • maxdb_embedded_connect - Open a connection to an embedded MaxDB server
    • maxdb_enable_reads_from_master - Enable reads from master
    • maxdb_enable_rpl_parse - Enable RPL parse
    • maxdb_errno - Returns the error code for the most recent function call
    • maxdb_error - Returns a string description of the last error
    • maxdb_escape_string - Alias of maxdb_real_escape_string
    • maxdb_execute - Alias of maxdb_stmt_execute
    • maxdb_fetch - Alias of maxdb_stmt_fetch
    • maxdb_fetch_array - Fetch a result row as an associative, a numeric array, or both
    • maxdb_fetch_assoc - Fetch a result row as an associative array
    • maxdb_fetch_field - Returns the next field in the result set
    • maxdb_fetch_fields - Returns an array of resources representing the fields in a result set
    • maxdb_fetch_field_direct - Fetch meta-data for a single field
    • maxdb_fetch_lengths - Returns the lengths of the columns of the current row in the result set
    • maxdb_fetch_object - Returns the current row of a result set as an object
    • maxdb_fetch_row - Get a result row as an enumerated array
    • maxdb_field_count - Returns the number of columns for the most recent query
    • maxdb_field_seek - Set result pointer to a specified field offset
    • maxdb_field_tell - Get current field offset of a result pointer
    • maxdb_free_result - Frees the memory associated with a result
    • maxdb_get_client_info - Returns the MaxDB client version as a string
    • maxdb_get_client_version - Get MaxDB client info
    • maxdb_get_host_info - Returns a string representing the type of connection used
    • maxdb_get_metadata - Alias of maxdb_stmt_result_metadata
    • maxdb_get_proto_info - Returns the version of the MaxDB protocol used
    • maxdb_get_server_info - Returns the version of the MaxDB server
    • maxdb_get_server_version - Returns the version of the MaxDB server as an integer
    • maxdb_info - Retrieves information about the most recently executed query
    • maxdb_init - Initializes MaxDB and returns an resource for use with maxdb_real_connect
    • maxdb_insert_id - Returns the auto generated id used in the last query
    • maxdb_kill - Disconnects from a MaxDB server
    • maxdb_master_query - Enforce execution of a query on the master in a master/slave setup
    • maxdb_more_results - Check if there any more query results from a multi query
    • maxdb_multi_query - Performs a query on the database
    • maxdb_next_result - Prepare next result from multi_query
    • maxdb_num_fields - Get the number of fields in a result
    • maxdb_num_rows - Gets the number of rows in a result
    • maxdb_options - Set options
    • maxdb_param_count - Alias of maxdb_stmt_param_count
    • maxdb_ping - Pings a server connection, or tries to reconnect if the connection has gone down
    • maxdb_prepare - Prepare an SQL statement for execution
    • maxdb_query - Performs a query on the database
    • maxdb_real_connect - Opens a connection to a MaxDB server
    • maxdb_real_escape_string - Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
    • maxdb_real_query - Execute an SQL query
    • maxdb_report - Enables or disables internal report functions
    • maxdb_rollback - Rolls back current transaction
    • maxdb_rpl_parse_enabled - Check if RPL parse is enabled
    • maxdb_rpl_probe - RPL probe
    • maxdb_rpl_query_type - Returns RPL query type
    • maxdb_select_db - Selects the default database for database queries
    • maxdb_send_long_data - Alias of maxdb_stmt_send_long_data
    • maxdb_send_query - Send the query and return
    • maxdb_server_end - Shut down the embedded server
    • maxdb_server_init - Initialize embedded server
    • maxdb_set_opt - Alias of maxdb_options
    • maxdb_sqlstate - Returns the SQLSTATE error from previous MaxDB operation
    • maxdb_ssl_set - Used for establishing secure connections using SSL
    • maxdb_stat - Gets the current system status
    • maxdb_stmt_affected_rows - Returns the total number of rows changed, deleted, or inserted by the last executed statement
    • maxdb_stmt_bind_param - Binds variables to a prepared statement as parameters
    • maxdb_stmt_bind_result - Binds variables to a prepared statement for result storage
    • maxdb_stmt_close - Closes a prepared statement
    • maxdb_stmt_close_long_data - Ends a sequence of maxdb_stmt_send_long_data
    • maxdb_stmt_data_seek - Seeks to an arbitray row in statement result set
    • maxdb_stmt_errno - Returns the error code for the most recent statement call
    • maxdb_stmt_error - Returns a string description for last statement error
    • maxdb_stmt_execute - Executes a prepared Query
    • maxdb_stmt_fetch - Fetch results from a prepared statement into the bound variables
    • maxdb_stmt_free_result - Frees stored result memory for the given statement handle
    • maxdb_stmt_init - Initializes a statement and returns an resource for use with maxdb_stmt_prepare
    • maxdb_stmt_num_rows - Return the number of rows in statements result set
    • maxdb_stmt_param_count - Returns the number of parameter for the given statement
    • maxdb_stmt_prepare - Prepare an SQL statement for execution
    • maxdb_stmt_reset - Resets a prepared statement
    • maxdb_stmt_result_metadata - Returns result set metadata from a prepared statement
    • maxdb_stmt_send_long_data - Send data in blocks
    • maxdb_stmt_sqlstate - Returns SQLSTATE error from previous statement operation
    • maxdb_stmt_store_result - Transfers a result set from a prepared statement
    • maxdb_store_result - Transfers a result set from the last query
    • maxdb_thread_id - Returns the thread ID for the current connection
    • maxdb_thread_safe - Returns whether thread safety is given or not
    • maxdb_use_result - Initiate a result set retrieval
    • maxdb_warning_count - Returns the number of warnings from the last query for the given link
    • mb_check_encoding - Check if strings are valid for the specified encoding
    • mb_chr - Get a specific character
    • mb_convert_case - Perform case folding on a string
    • mb_convert_encoding - Convert character encoding
    • 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_eregi - Regular expression match ignoring case with multibyte support
    • mb_eregi_replace - Replace regular expression with multibyte support ignoring case
    • 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_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_list_encodings - Returns an array of all supported encodings
    • mb_ord - Get 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_scrub - Description
    • mb_send_mail - Send encoded mail
    • mb_split - Split multibyte string using regular expression
    • 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
    • mcrypt_cbc - Encrypts/decrypts data in CBC mode
    • mcrypt_cfb - Encrypts/decrypts data in CFB mode
    • mcrypt_create_iv - Creates an initialization vector (IV) from a random source
    • mcrypt_decrypt - Decrypts crypttext with given parameters
    • mcrypt_ecb - Deprecated: Encrypts/decrypts data in ECB mode
    • mcrypt_encrypt - Encrypts plaintext 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_generic - This function encrypts data
    • mcrypt_generic_deinit - This function deinitializes an encryption module
    • mcrypt_generic_end - This function terminates encryption
    • 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
    • mcrypt_ofb - Encrypts/decrypts data in OFB mode
    • md5 - Calculate the md5 hash of a string
    • md5_file - Calculates the md5 hash of a given file
    • mdecrypt_generic - Decrypts data
    • Memcache::add - Add an item to the server
    • Memcache::addServer - Add a memcached server to connection pool
    • Memcache::close - Close memcached server connection
    • Memcache::connect - Open memcached server connection
    • Memcache::decrement - Decrement item's value
    • Memcache::delete - Delete item from the server
    • Memcache::flush - Flush all existing items at the server
    • Memcache::get - Retrieve item from the server
    • Memcache::getExtendedStats - Get statistics from all servers in pool
    • Memcache::getServerStatus - Returns server status
    • Memcache::getStats - Get statistics of the server
    • Memcache::getVersion - Return version of the server
    • Memcache::increment - Increment item's value
    • Memcache::pconnect - Open memcached server persistent connection
    • Memcache::replace - Replace value of the existing item
    • Memcache::set - Store data at the server
    • Memcache::setCompressThreshold - Enable automatic compression of large values
    • Memcache::setServerParams - Changes server parameters and status at runtime
    • Memcached::add - Add an item under a new key
    • Memcached::addByKey - Add an item under a new key on a specific server
    • Memcached::addServer - Add a server to the server pool
    • Memcached::addServers - Add multiple servers to the server pool
    • Memcached::append - Append data to an existing item
    • Memcached::appendByKey - Append data to an existing item on a specific server
    • Memcached::cas - Compare and swap an item
    • Memcached::casByKey - Compare and swap an item on a specific server
    • Memcached::decrement - Decrement numeric item's value
    • Memcached::decrementByKey - Decrement numeric item's value, stored on a specific server
    • Memcached::delete - Delete an item
    • Memcached::deleteByKey - Delete an item from a specific server
    • Memcached::deleteMulti - Delete multiple items
    • Memcached::deleteMultiByKey - Delete multiple items from a specific server
    • Memcached::fetch - Fetch the next result
    • Memcached::fetchAll - Fetch all the remaining results
    • Memcached::flush - Invalidate all items in the cache
    • Memcached::get - Retrieve an item
    • Memcached::getAllKeys - Gets the keys stored on all the servers
    • Memcached::getByKey - Retrieve an item from a specific server
    • Memcached::getDelayed - Request multiple items
    • Memcached::getDelayedByKey - Request multiple items from a specific server
    • Memcached::getMulti - Retrieve multiple items
    • Memcached::getMultiByKey - Retrieve multiple items from a specific server
    • Memcached::getOption - Retrieve a Memcached option value
    • Memcached::getResultCode - Return the result code of the last operation
    • Memcached::getResultMessage - Return the message describing the result of the last operation
    • Memcached::getServerByKey - Map a key to a server
    • Memcached::getServerList - Get the list of the servers in the pool
    • Memcached::getStats - Get server pool statistics
    • Memcached::getVersion - Get server pool version info
    • Memcached::increment - Increment numeric item's value
    • Memcached::incrementByKey - Increment numeric item's value, stored on a specific server
    • Memcached::isPersistent - Check if a persitent connection to memcache is being used
    • Memcached::isPristine - Check if the instance was recently created
    • Memcached::prepend - Prepend data to an existing item
    • Memcached::prependByKey - Prepend data to an existing item on a specific server
    • Memcached::quit - Close any open connections
    • Memcached::replace - Replace the item under an existing key
    • Memcached::replaceByKey - Replace the item under an existing key on a specific server
    • Memcached::resetServerList - Clears all servers from the server list
    • Memcached::set - Store an item
    • Memcached::setByKey - Store an item on a specific server
    • Memcached::setMulti - Store multiple items
    • Memcached::setMultiByKey - Store multiple items on a specific server
    • Memcached::setOption - Set a Memcached option
    • Memcached::setOptions - Set Memcached options
    • Memcached::setSaslAuthData - Set the credentials to use for authentication
    • Memcached::touch - Set a new expiration on an item
    • Memcached::touchByKey - Set a new expiration on an item on a specific server
    • Memcached::__construct - Create a Memcached instance
    • memcache_debug - Turn debug output on/off
    • memory_get_peak_usage - Returns the peak of memory allocated by PHP
    • memory_get_usage - Returns the amount of memory allocated to PHP
    • 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
    • metaphone - Calculate the metaphone key of a string
    • method_exists - Checks if the class method exists
    • 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
    • microtime - Return current Unix timestamp with microseconds
    • mime_content_type - Detect MIME Content-type for a file
    • min - Find lowest value
    • ming_keypress - Returns the action flag for keyPress(char)
    • ming_setcubicthreshold - Set cubic threshold
    • ming_setscale - Set the global scaling factor
    • ming_setswfcompression - Sets the SWF output compression
    • ming_useconstants - Use constant pool
    • ming_useswfversion - Sets the SWF version
    • mkdir - Makes directory
    • mktime - Get Unix timestamp for a date
    • money_format - Formats a number as a currency string
    • Mongo::connectUtil - Connects with a database server
    • Mongo::getPoolSize - Get pool size for connection pools
    • Mongo::getSlave - Returns the address being used by this for slaveOkay reads
    • Mongo::getSlaveOkay - Get slaveOkay setting for this connection
    • Mongo::poolDebug - Returns information about all connection pools
    • Mongo::setPoolSize - Set the size for future connection pools
    • Mongo::setSlaveOkay - Change slaveOkay setting for this connection
    • Mongo::switchSlave - Choose a new secondary for slaveOkay reads
    • Mongo::__construct - The __construct purpose
    • MongoBinData::__construct - Creates a new binary data object
    • MongoBinData::__toString - The string representation of this binary data object
    • MongoClient::close - Closes this connection
    • MongoClient::connect - Connects to a database server
    • MongoClient::dropDB - Drops a database [deprecated]
    • MongoClient::getConnections - Return info about all open connections
    • MongoClient::getHosts - Updates status for all associated hosts
    • MongoClient::getReadPreference - Get the read preference for this connection
    • MongoClient::getWriteConcern - Get the write concern for this connection
    • MongoClient::killCursor - Kills a specific cursor on the server
    • MongoClient::listDBs - Lists all of the databases available
    • MongoClient::selectCollection - Gets a database collection
    • MongoClient::selectDB - Gets a database
    • MongoClient::setReadPreference - Set the read preference for this connection
    • MongoClient::setWriteConcern - Set the write concern for this connection
    • MongoClient::__construct - Creates a new database connection object
    • MongoClient::__get - Gets a database
    • MongoClient::__toString - String representation of this connection
    • MongoCode::__construct - Creates a new code object
    • MongoCode::__toString - Returns this code as a string
    • MongoCollection::aggregate - Perform an aggregation using the aggregation framework
    • MongoCollection::aggregateCursor - Execute an aggregation pipeline command and retrieve results through a cursor
    • MongoCollection::batchInsert - Inserts multiple documents into this collection
    • MongoCollection::count - Counts the number of documents in this collection
    • MongoCollection::createDBRef - Creates a database reference
    • MongoCollection::createIndex - Creates an index on the specified field(s) if it does not already exist
    • MongoCollection::deleteIndex - Deletes an index from this collection
    • MongoCollection::deleteIndexes - Delete all indices for this collection
    • MongoCollection::distinct - Retrieve a list of distinct values for the given key across a collection
    • MongoCollection::drop - Drops this collection
    • MongoCollection::ensureIndex - Creates an index on the specified field(s) if it does not already exist
    • MongoCollection::find - Queries this collection, returning a MongoCursor for the result set
    • MongoCollection::findAndModify - Update a document and return it
    • MongoCollection::findOne - Queries this collection, returning a single element
    • MongoCollection::getDBRef - Fetches the document pointed to by a database reference
    • MongoCollection::getIndexInfo - Returns information about indexes on this collection
    • MongoCollection::getName - Returns this collection's name
    • MongoCollection::getReadPreference - Get the read preference for this collection
    • MongoCollection::getSlaveOkay - Get slaveOkay setting for this collection
    • MongoCollection::getWriteConcern - Get the write concern for this collection
    • MongoCollection::group - Performs an operation similar to SQL's GROUP BY command
    • MongoCollection::insert - Inserts a document into the collection
    • MongoCollection::parallelCollectionScan - Returns an array of cursors to iterator over a full collection in parallel
    • MongoCollection::remove - Remove records from this collection
    • MongoCollection::save - Saves a document to this collection
    • MongoCollection::setReadPreference - Set the read preference for this collection
    • MongoCollection::setSlaveOkay - Change slaveOkay setting for this collection
    • MongoCollection::setWriteConcern - Set the write concern for this database
    • MongoCollection::toIndexString - Converts keys specifying an index to its identifying string
    • MongoCollection::update - Update records based on a given criteria
    • MongoCollection::validate - Validates this collection
    • MongoCollection::__construct - Creates a new collection
    • MongoCollection::__get - Gets a collection
    • MongoCollection::__toString - String representation of this collection
    • MongoCommandCursor::batchSize - Limits the number of elements returned in one batch
    • MongoCommandCursor::createFromDocument - Create a new command cursor from an existing command response document
    • MongoCommandCursor::current - Returns the current element
    • MongoCommandCursor::dead - Checks if there are results that have not yet been sent from the database
    • MongoCommandCursor::getReadPreference - Get the read preference for this command
    • MongoCommandCursor::info - Gets information about the cursor's creation and iteration
    • MongoCommandCursor::key - Returns the current result's index within the result set
    • MongoCommandCursor::next - Advances the cursor to the next result
    • MongoCommandCursor::rewind - Executes the command and resets the cursor to the start of the result set
    • MongoCommandCursor::setReadPreference - Set the read preference for this command
    • MongoCommandCursor::timeout - Sets a client-side timeout for this command
    • MongoCommandCursor::valid - Checks if the cursor is reading a valid result
    • MongoCommandCursor::__construct - Create a new command cursor
    • MongoCursor::addOption - Adds a top-level key/value pair to a query
    • MongoCursor::awaitData - Sets whether this cursor will wait for a while for a tailable cursor to return more data
    • MongoCursor::batchSize - Limits the number of elements returned in one batch
    • MongoCursor::count - Counts the number of results for this query
    • MongoCursor::current - Returns the current element
    • MongoCursor::dead - Checks if there are results that have not yet been sent from the database
    • MongoCursor::doQuery - Execute the query
    • MongoCursor::explain - Return an explanation of the query, often useful for optimization and debugging
    • MongoCursor::fields - Sets the fields for a query
    • MongoCursor::getNext - Advances the cursor to the next result, and returns that result
    • MongoCursor::getReadPreference - Get the read preference for this query
    • MongoCursor::hasNext - Checks if there are any more elements in this cursor
    • MongoCursor::hint - Gives the database a hint about the query
    • MongoCursor::immortal - Sets whether this cursor will timeout
    • MongoCursor::info - Gets information about the cursor's creation and iteration
    • MongoCursor::key - Returns the current result's _id, or its index within the result set
    • MongoCursor::limit - Limits the number of results returned
    • MongoCursor::maxTimeMS - Sets a server-side timeout for this query
    • MongoCursor::next - Advances the cursor to the next result, and returns that result
    • MongoCursor::partial - If this query should fetch partial results from mongos if a shard is down
    • MongoCursor::reset - Clears the cursor
    • MongoCursor::rewind - Returns the cursor to the beginning of the result set
    • MongoCursor::setFlag - Sets arbitrary flags in case there is no method available the specific flag
    • MongoCursor::setReadPreference - Set the read preference for this query
    • MongoCursor::skip - Skips a number of results
    • MongoCursor::slaveOkay - Sets whether this query can be done on a secondary [deprecated]
    • MongoCursor::snapshot - Use snapshot mode for the query
    • MongoCursor::sort - Sorts the results by given fields
    • MongoCursor::tailable - Sets whether this cursor will be left open after fetching the last results
    • MongoCursor::timeout - Sets a client-side timeout for this query
    • MongoCursor::valid - Checks if the cursor is reading a valid result
    • MongoCursor::__construct - Create a new cursor
    • MongoCursorException::getHost - The hostname of the server that encountered the error
    • MongoCursorInterface::batchSize - Limits the number of elements returned in one batch
    • MongoCursorInterface::dead - Checks if there are results that have not yet been sent from the database
    • MongoCursorInterface::getReadPreference - Get the read preference for this query
    • MongoCursorInterface::info - Gets information about the cursor's creation and iteration
    • MongoCursorInterface::setReadPreference - Set the read preference for this query
    • MongoCursorInterface::timeout - Sets a client-side timeout for this query
    • MongoDate::toDateTime - Returns a DateTime object representing this date
    • MongoDate::__construct - Creates a new date
    • MongoDate::__toString - Returns a string representation of this date
    • MongoDB::authenticate - Log in to this database
    • MongoDB::command - Execute a database command
    • MongoDB::createCollection - Creates a collection
    • MongoDB::createDBRef - Creates a database reference
    • MongoDB::drop - Drops this database
    • MongoDB::dropCollection - Drops a collection [deprecated]
    • MongoDB::execute - Runs JavaScript code on the database server [deprecated]
    • MongoDB::forceError - Creates a database error
    • MongoDB::getCollectionInfo - Returns information about collections in this database
    • MongoDB::getCollectionNames - Gets an array of names for all collections in this database
    • MongoDB::getDBRef - Fetches the document pointed to by a database reference
    • MongoDB::getGridFS - Fetches toolkit for dealing with files stored in this database
    • MongoDB::getProfilingLevel - Gets this database's profiling level
    • MongoDB::getReadPreference - Get the read preference for this database
    • MongoDB::getSlaveOkay - Get slaveOkay setting for this database
    • MongoDB::getWriteConcern - Get the write concern for this database
    • MongoDB::lastError - Check if there was an error on the most recent db operation performed
    • MongoDB::listCollections - Gets an array of MongoCollection objects for all collections in this database
    • MongoDB::prevError - Checks for the last error thrown during a database operation
    • MongoDB::repair - Repairs and compacts this database
    • MongoDB::resetError - Clears any flagged errors on the database
    • MongoDB::selectCollection - Gets a collection
    • MongoDB::setProfilingLevel - Sets this database's profiling level
    • MongoDB::setReadPreference - Set the read preference for this database
    • MongoDB::setSlaveOkay - Change slaveOkay setting for this database
    • MongoDB::setWriteConcern - Set the write concern for this database
    • MongoDB::__construct - Creates a new database
    • MongoDB::__get - Gets a collection
    • MongoDB::__toString - The name of this database
    • MongoDB context options - MongoDB context option listing
    • MongoDBRef::create - Creates a new database reference
    • MongoDBRef::get - Fetches the object pointed to by a reference
    • MongoDBRef::isRef - Checks if an array is a database reference
    • MongoDB\BSON\Binary::getData - Returns the Binary's data
    • MongoDB\BSON\Binary::getType - Returns the Binary's type
    • MongoDB\BSON\Binary::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\Binary::serialize - Serialize a Binary
    • MongoDB\BSON\Binary::unserialize - Unserialize a Binary
    • MongoDB\BSON\Binary::__construct - Construct a new Binary
    • MongoDB\BSON\Binary::__toString - Returns the Binary's data
    • 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
    • MongoDB\BSON\DBPointer::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\DBPointer::serialize - Serialize a DBPointer
    • MongoDB\BSON\DBPointer::unserialize - Unserialize a DBPointer
    • MongoDB\BSON\DBPointer::__construct - Construct a new DBPointer (unused)
    • MongoDB\BSON\DBPointer::__toString - Returns an empty string
    • MongoDB\BSON\Decimal128::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\Decimal128::serialize - Serialize a Decimal128
    • MongoDB\BSON\Decimal128::unserialize - Unserialize a Decimal128
    • MongoDB\BSON\Decimal128::__construct - Construct a new Decimal128
    • MongoDB\BSON\Decimal128::__toString - Returns the string representation of this Decimal128
    • MongoDB\BSON\Decimal128Interface::__toString - Returns the string representation of this Decimal128Interface
    • MongoDB\BSON\fromJSON - Returns the BSON representation of a JSON value
    • MongoDB\BSON\fromPHP - Returns the BSON representation of a PHP value
    • MongoDB\BSON\Int64::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\Int64::serialize - Serialize an Int64
    • MongoDB\BSON\Int64::unserialize - Unserialize an Int64
    • MongoDB\BSON\Int64::__construct - Construct a new Int64 (unused)
    • MongoDB\BSON\Int64::__toString - Returns the string representation of this Int64
    • 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::serialize - Serialize a Javascript
    • MongoDB\BSON\Javascript::unserialize - Unserialize a Javascript
    • MongoDB\BSON\Javascript::__construct - Construct a new Javascript
    • MongoDB\BSON\Javascript::__toString - Returns the Javascript's code
    • 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
    • MongoDB\BSON\MaxKey::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\MaxKey::serialize - Serialize a MaxKey
    • MongoDB\BSON\MaxKey::unserialize - Unserialize a MaxKey
    • MongoDB\BSON\MaxKey::__construct - Construct a new MaxKey
    • MongoDB\BSON\MinKey::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\MinKey::serialize - Serialize a MinKey
    • MongoDB\BSON\MinKey::unserialize - Unserialize a MinKey
    • MongoDB\BSON\MinKey::__construct - Construct a new MinKey
    • 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::serialize - Serialize an ObjectId
    • MongoDB\BSON\ObjectId::unserialize - Unserialize an ObjectId
    • MongoDB\BSON\ObjectId::__construct - Construct a new ObjectId
    • MongoDB\BSON\ObjectId::__toString - Returns the hexidecimal representation of this ObjectId
    • MongoDB\BSON\ObjectIdInterface::getTimestamp - Returns the timestamp component of this ObjectIdInterface
    • MongoDB\BSON\ObjectIdInterface::__toString - Returns the hexidecimal representation of this ObjectIdInterface
    • 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::serialize - Serialize a Regex
    • MongoDB\BSON\Regex::unserialize - Unserialize a Regex
    • MongoDB\BSON\Regex::__construct - Construct a new Regex
    • MongoDB\BSON\Regex::__toString - Returns the string representation of this Regex
    • 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
    • MongoDB\BSON\Serializable::bsonSerialize - Provides an array or document to serialize as BSON
    • MongoDB\BSON\Symbol::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\Symbol::serialize - Serialize a Symbol
    • MongoDB\BSON\Symbol::unserialize - Unserialize a Symbol
    • MongoDB\BSON\Symbol::__construct - Construct a new Symbol (unused)
    • MongoDB\BSON\Symbol::__toString - Returns the Symbol as a string
    • 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::serialize - Serialize a Timestamp
    • MongoDB\BSON\Timestamp::unserialize - Unserialize a Timestamp
    • MongoDB\BSON\Timestamp::__construct - Construct a new Timestamp
    • MongoDB\BSON\Timestamp::__toString - Returns the string representation of this Timestamp
    • 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
    • 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
    • MongoDB\BSON\Undefined::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\Undefined::serialize - Serialize a Undefined
    • MongoDB\BSON\Undefined::unserialize - Unserialize a Undefined
    • MongoDB\BSON\Undefined::__construct - Construct a new Undefined (unused)
    • MongoDB\BSON\Undefined::__toString - Returns an empty string
    • MongoDB\BSON\Unserializable::bsonUnserialize - Constructs the object from a BSON array or document
    • MongoDB\BSON\UTCDateTime::jsonSerialize - Returns a representation that can be converted to JSON
    • MongoDB\BSON\UTCDateTime::serialize - Serialize a UTCDateTime
    • MongoDB\BSON\UTCDateTime::toDateTime - Returns the DateTime representation of this UTCDateTime
    • MongoDB\BSON\UTCDateTime::unserialize - Unserialize a UTCDateTime
    • MongoDB\BSON\UTCDateTime::__construct - Construct a new UTCDateTime
    • MongoDB\BSON\UTCDateTime::__toString - Returns the string representation of this UTCDateTime
    • MongoDB\BSON\UTCDateTimeInterface::toDateTime - Returns the DateTime representation of this UTCDateTimeInterface
    • MongoDB\BSON\UTCDateTimeInterface::__toString - Returns the string representation of this UTCDateTimeInterface
    • 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
    • MongoDB\Driver\BulkWrite::__construct - Create a new BulkWrite
    • MongoDB\Driver\ClientEncryption::createDataKey - Create a new encryption data key
    • MongoDB\Driver\ClientEncryption::decrypt - Decrypt a value
    • MongoDB\Driver\ClientEncryption::encrypt - Encrypt a value
    • MongoDB\Driver\Command::__construct - Create a new Command
    • 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::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::__construct - Create a new Cursor (not used)
    • MongoDB\Driver\CursorId::serialize - Serialize a CursorId
    • MongoDB\Driver\CursorId::unserialize - Unserialize a CursorId
    • MongoDB\Driver\CursorId::__construct - Create a new CursorId (not used)
    • MongoDB\Driver\CursorId::__toString - String representation of the cursor ID
    • 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
    • MongoDB\Driver\Exception\CommandException::getResultDocument - Returns the result document for the failed command
    • MongoDB\Driver\Exception\RuntimeException::hasErrorLabel - Returns whether an error label is associated with an exception
    • MongoDB\Driver\Exception\WriteException::getWriteResult - Returns the WriteResult for the failed write operation
    • MongoDB\Driver\Manager::createClientEncryption - Create a new ClientEncryption object
    • MongoDB\Driver\Manager::executeBulkWrite - Execute one or more write operations
    • 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::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::selectServer - Select a server matching a read preference
    • MongoDB\Driver\Manager::startSession - Start a new client session for use with this client
    • MongoDB\Driver\Manager::__construct - Create new MongoDB Manager
    • MongoDB\Driver\Monitoring\addSubscriber - Registers a new monitoring event subscriber
    • MongoDB\Driver\Monitoring\CommandFailedEvent::getCommandName - Returns the command name
    • 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::getOperationId - Returns the command's operation ID
    • 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\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::getOperationId - Returns the command's operation ID
    • 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\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
    • MongoDB\Driver\Monitoring\CommandSucceededEvent::getCommandName - Returns the command name
    • MongoDB\Driver\Monitoring\CommandSucceededEvent::getDurationMicros - Returns the command's duration in microseconds
    • MongoDB\Driver\Monitoring\CommandSucceededEvent::getOperationId - Returns the command's operation ID
    • 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\removeSubscriber - Unregisters an existing monitoring event subscriber
    • MongoDB\Driver\Query::__construct - Create a new Query
    • MongoDB\Driver\ReadConcern::bsonSerialize - Returns an object for BSON serialization
    • MongoDB\Driver\ReadConcern::getLevel - Returns the ReadConcern's "level" option
    • MongoDB\Driver\ReadConcern::isDefault - Checks if this is the default read concern
    • MongoDB\Driver\ReadConcern::serialize - Serialize a ReadConcern
    • MongoDB\Driver\ReadConcern::unserialize - Unserialize a ReadConcern
    • MongoDB\Driver\ReadConcern::__construct - Create a new ReadConcern
    • MongoDB\Driver\ReadPreference::bsonSerialize - Returns an object for BSON serialization
    • 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 as a string
    • MongoDB\Driver\ReadPreference::getTagSets - Returns the ReadPreference's "tagSets" option
    • MongoDB\Driver\ReadPreference::serialize - Serialize a ReadPreference
    • MongoDB\Driver\ReadPreference::unserialize - Unserialize a ReadPreference
    • MongoDB\Driver\ReadPreference::__construct - Create a new ReadPreference
    • MongoDB\Driver\Server::executeBulkWrite - Execute one or more write operations on this server
    • 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 about this server
    • MongoDB\Driver\Server::getLatency - Returns the latency of this server
    • MongoDB\Driver\Server::getPort - Returns the port on which this server is listening
    • 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
    • MongoDB\Driver\Server::__construct - Create a new Server (not used)
    • 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::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::isInTransaction - Returns whether a multi-document transaction is in progress
    • MongoDB\Driver\Session::startTransaction - Starts a transaction
    • MongoDB\Driver\Session::__construct - Create a new Session (not used)
    • MongoDB\Driver\WriteConcern::bsonSerialize - Returns an object for BSON serialization
    • 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
    • MongoDB\Driver\WriteConcern::serialize - Serialize a WriteConcern
    • MongoDB\Driver\WriteConcern::unserialize - Unserialize a WriteConcern
    • MongoDB\Driver\WriteConcern::__construct - Create a new WriteConcern
    • MongoDB\Driver\WriteConcernError::getCode - Returns the WriteConcernError's error code
    • MongoDB\Driver\WriteConcernError::getInfo - Returns additional metadata for the WriteConcernError
    • MongoDB\Driver\WriteConcernError::getMessage - Returns the WriteConcernError's error message
    • 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 additional metadata for the WriteError
    • MongoDB\Driver\WriteError::getMessage - Returns the WriteError's error message
    • 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
    • MongoDeleteBatch::__construct - Description
    • MongoGridFS::delete - Remove a file and its chunks from the database
    • MongoGridFS::drop - Drops the files and chunks collections
    • MongoGridFS::find - Queries for files
    • MongoGridFS::findOne - Returns a single file matching the criteria
    • MongoGridFS::get - Retrieve a file from the database
    • MongoGridFS::put - Stores a file in the database
    • MongoGridFS::remove - Remove files and their chunks from the database
    • MongoGridFS::storeBytes - Stores a string of bytes in the database
    • MongoGridFS::storeFile - Stores a file in the database
    • MongoGridFS::storeUpload - Stores an uploaded file in the database
    • MongoGridFS::__construct - Creates new file collections
    • MongoGridFSCursor::current - Returns the current file
    • MongoGridFSCursor::getNext - Return the next file to which this cursor points, and advance the cursor
    • MongoGridFSCursor::key - Returns the current result's filename
    • MongoGridFSCursor::__construct - Create a new cursor
    • MongoGridFSFile::getBytes - Returns this file's contents as a string of bytes
    • MongoGridFSFile::getFilename - Returns this file's filename
    • MongoGridFSFile::getResource - Returns a resource that can be used to read the stored file
    • MongoGridFSFile::getSize - Returns this file's size
    • MongoGridFSFile::write - Writes this file to the filesystem
    • MongoGridfsFile::__construct - Create a new GridFS file
    • MongoId::getHostname - Gets the hostname being used for this machine's ids
    • MongoId::getInc - Gets the incremented value to create this id
    • MongoId::getPID - Gets the process ID
    • MongoId::getTimestamp - Gets the number of seconds since the epoch that this id was created
    • MongoId::isValid - Check if a value is a valid ObjectId
    • MongoId::__construct - Creates a new id
    • MongoId::__set_state - Create a dummy MongoId
    • MongoId::__toString - Returns a hexidecimal representation of this id
    • MongoInsertBatch::__construct - Description
    • MongoInt32::__construct - Creates a new 32-bit integer
    • MongoInt32::__toString - Returns the string representation of this 32-bit integer
    • MongoInt64::__construct - Creates a new 64-bit integer
    • MongoInt64::__toString - Returns the string representation of this 64-bit integer
    • MongoLog::getCallback - Gets the previously set callback function
    • MongoLog::getLevel - Gets the level(s) currently being logged
    • MongoLog::getModule - Gets the module(s) currently being logged
    • MongoLog::setCallback - Sets a callback function to be invoked for events
    • MongoLog::setLevel - Sets the level(s) to be logged
    • MongoLog::setModule - Sets the module(s) to be logged
    • MongoPool::getSize - Get pool size for connection pools
    • MongoPool::info - Returns information about all connection pools
    • MongoPool::setSize - Set the size for future connection pools
    • MongoRegex::__construct - Creates a new regular expression
    • MongoRegex::__toString - A string representation of this regular expression
    • MongoResultException::getDocument - Retrieve the full result document
    • MongoTimestamp::__construct - Creates a new timestamp
    • MongoTimestamp::__toString - Returns a string representation of this timestamp
    • MongoUpdateBatch::__construct - Description
    • MongoWriteBatch::add - Adds a write operation to a batch
    • MongoWriteBatch::execute - Executes a batch of write operations
    • MongoWriteBatch::__construct - Creates a new batch of write operations
    • MongoWriteConcernException::getDocument - Get the error document
    • move_uploaded_file - Moves an uploaded file to a new location
    • mqseries_back - MQSeries MQBACK
    • mqseries_begin - MQseries MQBEGIN
    • mqseries_close - MQSeries MQCLOSE
    • mqseries_cmit - MQSeries MQCMIT
    • mqseries_conn - MQSeries MQCONN
    • mqseries_connx - MQSeries MQCONNX
    • mqseries_disc - MQSeries MQDISC
    • mqseries_get - MQSeries MQGET
    • mqseries_inq - MQSeries MQINQ
    • mqseries_open - MQSeries MQOPEN
    • mqseries_put - MQSeries MQPUT
    • mqseries_put1 - MQSeries MQPUT1
    • mqseries_set - MQSeries MQSET
    • mqseries_strerror - Returns the error message corresponding to a result code (MQRC)
    • msession_connect - Connect to msession server
    • msession_count - Get session count
    • msession_create - Create a session
    • msession_destroy - Destroy a session
    • msession_disconnect - Close connection to msession server
    • msession_find - Find all sessions with name and value
    • msession_get - Get value from session
    • msession_get_array - Get array of msession variables
    • msession_get_data - Get data session unstructured data
    • msession_inc - Increment value in session
    • msession_list - List all sessions
    • msession_listvar - List sessions with variable
    • msession_lock - Lock a session
    • msession_plugin - Call an escape function within the msession personality plugin
    • msession_randstr - Get random string
    • msession_set - Set value in session
    • msession_set_array - Set msession variables from an array
    • msession_set_data - Set data session unstructured data
    • msession_timeout - Set/get session timeout
    • msession_uniq - Get unique id
    • msession_unlock - Unlock a session
    • msg_get_queue - Create or attach to a message queue
    • msg_queue_exists - Check whether a message queue exists
    • msg_receive - Receive a message from a message queue
    • msg_remove_queue - Destroy a message queue
    • msg_send - Send a message to a message queue
    • msg_set_queue - Set information in the message queue data structure
    • msg_stat_queue - Returns information from the message queue data structure
    • msql - Alias of msql_db_query
    • msql_affected_rows - Returns number of affected rows
    • msql_close - Close mSQL connection
    • msql_connect - Open mSQL connection
    • msql_createdb - Alias of msql_create_db
    • msql_create_db - Create mSQL database
    • msql_data_seek - Move internal row pointer
    • msql_dbname - Alias of msql_result
    • msql_db_query - Send mSQL query
    • msql_drop_db - Drop (delete) mSQL database
    • msql_error - Returns error message of last msql call
    • msql_fetch_array - Fetch row as array
    • msql_fetch_field - Get field information
    • msql_fetch_object - Fetch row as object
    • msql_fetch_row - Get row as enumerated array
    • msql_fieldflags - Alias of msql_field_flags
    • msql_fieldlen - Alias of msql_field_len
    • msql_fieldname - Alias of msql_field_name
    • msql_fieldtable - Alias of msql_field_table
    • msql_fieldtype - Alias of msql_field_type
    • msql_field_flags - Get field flags
    • msql_field_len - Get field length
    • msql_field_name - Get the name of the specified field in a result
    • msql_field_seek - Set field offset
    • msql_field_table - Get table name for field
    • msql_field_type - Get field type
    • msql_free_result - Free result memory
    • msql_list_dbs - List mSQL databases on server
    • msql_list_fields - List result fields
    • msql_list_tables - List tables in an mSQL database
    • msql_numfields - Alias of msql_num_fields
    • msql_numrows - Alias of msql_num_rows
    • msql_num_fields - Get number of fields in result
    • msql_num_rows - Get number of rows in result
    • msql_pconnect - Open persistent mSQL connection
    • msql_query - Send mSQL query
    • msql_regcase - Alias of sql_regcase
    • msql_result - Get result data
    • msql_select_db - Select mSQL database
    • msql_tablename - Alias of msql_result
    • mssql_bind - Adds a parameter to a stored procedure or a remote stored procedure
    • mssql_close - Close MS SQL Server connection
    • mssql_connect - Open MS SQL server connection
    • mssql_data_seek - Moves internal row pointer
    • mssql_execute - Executes a stored procedure on a MS SQL server database
    • mssql_fetch_array - Fetch a result row as an associative array, a numeric array, or both
    • mssql_fetch_assoc - Returns an associative array of the current row in the result
    • mssql_fetch_batch - Returns the next batch of records
    • mssql_fetch_field - Get field information
    • mssql_fetch_object - Fetch row as object
    • mssql_fetch_row - Get row as enumerated array
    • mssql_field_length - Get the length of a field
    • mssql_field_name - Get the name of a field
    • mssql_field_seek - Seeks to the specified field offset
    • mssql_field_type - Gets the type of a field
    • mssql_free_result - Free result memory
    • mssql_free_statement - Free statement memory
    • mssql_get_last_message - Returns the last message from the server
    • mssql_guid_string - Converts a 16 byte binary GUID to a string
    • mssql_init - Initializes a stored procedure or a remote stored procedure
    • mssql_min_error_severity - Sets the minimum error severity
    • mssql_min_message_severity - Sets the minimum message severity
    • mssql_next_result - Move the internal result pointer to the next result
    • mssql_num_fields - Gets the number of fields in result
    • mssql_num_rows - Gets the number of rows in result
    • mssql_pconnect - Open persistent MS SQL connection
    • mssql_query - Send MS SQL query
    • mssql_result - Get result data
    • mssql_rows_affected - Returns the number of records affected by the query
    • mssql_select_db - Select MS SQL database
    • mt_getrandmax - Show largest possible random value
    • mt_rand - Generate a random value via the Mersenne Twister Random Number Generator
    • mt_srand - Seeds the Mersenne Twister Random Number Generator
    • MultipleIterator::attachIterator - Attaches iterator information
    • MultipleIterator::containsIterator - Checks if an iterator is attached
    • MultipleIterator::countIterators - Gets the number of attached iterator instances
    • MultipleIterator::current - Gets the registered iterator instances
    • MultipleIterator::detachIterator - Detaches an iterator
    • MultipleIterator::getFlags - Gets the flag information
    • MultipleIterator::key - Gets the registered iterator instances
    • MultipleIterator::next - Moves all attached iterator instances forward
    • MultipleIterator::rewind - Rewinds all attached iterator instances
    • MultipleIterator::setFlags - Sets flags
    • MultipleIterator::valid - Checks the validity of sub iterators
    • MultipleIterator::__construct - Constructs a new MultipleIterator
    • Mutex::create - Create a Mutex
    • Mutex::destroy - Destroy Mutex
    • Mutex::lock - Acquire Mutex
    • Mutex::trylock - Attempt to Acquire Mutex
    • Mutex::unlock - Release Mutex
    • mysqli::$affected_rows - Gets the number of affected rows in a previous MySQL operation
    • mysqli::$client_info - Get MySQL client info
    • mysqli::$client_version - Returns the MySQL client version as an integer
    • mysqli::$connect_errno - Returns the error code from last connect call
    • mysqli::$connect_error - Returns a string description of the last connect error
    • 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::$field_count - Returns the number of columns for the most recent query
    • mysqli::$host_info - Returns a string representing the type of connection used
    • mysqli::$info - Retrieves information about the most recently executed query
    • mysqli::$insert_id - Returns the auto generated id used in the latest query
    • 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::$sqlstate - Returns the SQLSTATE error from previous MySQL operation
    • mysqli::$thread_id - Returns the thread ID for the current connection
    • mysqli::$warning_count - Returns the number of warnings from the last query for the given link
    • mysqli::autocommit - Turns on or off auto-committing database modifications
    • mysqli::begin_transaction - Starts a transaction
    • mysqli::change_user - Changes the user of the specified database connection
    • mysqli::character_set_name - Returns the default character set for the database connection
    • mysqli::close - Closes a previously opened database connection
    • mysqli::commit - Commits the current transaction
    • mysqli::debug - Performs debugging operations
    • mysqli::disable_reads_from_master - Disable reads from master
    • mysqli::dump_debug_info - Dump debugging information into the log
    • mysqli::get_charset - Returns a character set object
    • mysqli::get_connection_stats - Returns statistics about the client connection
    • mysqli::get_warnings - Get result of SHOW WARNINGS
    • mysqli::init - Initializes MySQLi and returns a resource for use with mysqli_real_connect()
    • 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 a query 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 - Prepare an SQL statement for execution
    • mysqli::query - Performs a query on the database
    • mysqli::real_connect - Opens a connection to a 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::rpl_query_type - Returns RPL query type
    • mysqli::savepoint - Set a named transaction savepoint
    • mysqli::select_db - Selects the default database for database queries
    • mysqli::send_query - Send the query and return
    • mysqli::set_charset - Sets the default client character set
    • mysqli::set_local_infile_default - Unsets user defined handler for load local infile command
    • mysqli::set_local_infile_handler - Set callback function for LOAD DATA LOCAL INFILE command
    • mysqli::set_opt - Alias of mysqli_options
    • 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_safe - Returns whether thread safety is given or not
    • mysqli::use_result - Initiate a result set retrieval
    • mysqli::__construct - Open a new connection to the MySQL server
    • mysqli_bind_param - Alias for mysqli_stmt_bind_param
    • mysqli_bind_result - Alias for mysqli_stmt_bind_result
    • mysqli_client_encoding - Alias of mysqli_character_set_name
    • mysqli_connect - Alias of mysqli::__construct
    • mysqli_disable_rpl_parse - Disable RPL parse
    • mysqli_driver::$report_mode - Enables or disables internal report functions
    • mysqli_driver::embedded_server_end - Stop embedded server
    • mysqli_driver::embedded_server_start - Initialize and start embedded server
    • mysqli_enable_reads_from_master - Enable reads from master
    • mysqli_enable_rpl_parse - Enable RPL parse
    • mysqli_escape_string - Alias of mysqli_real_escape_string
    • mysqli_execute - Alias for mysqli_stmt_execute
    • mysqli_fetch - Alias for mysqli_stmt_fetch
    • mysqli_get_cache_stats - Returns client Zval cache statistics
    • mysqli_get_client_stats - Returns client per-process statistics
    • mysqli_get_links_stats - Return information about open and cached links
    • mysqli_get_metadata - Alias for mysqli_stmt_result_metadata
    • mysqli_master_query - Enforce execution of a query on the master in a master/slave setup
    • mysqli_param_count - Alias for mysqli_stmt_param_count
    • mysqli_report - Alias of mysqli_driver->report_mode
    • mysqli_result::$current_field - Get current field offset of a result pointer
    • mysqli_result::$field_count - Get the number of fields in a result
    • 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 a result
    • mysqli_result::data_seek - Adjusts the result pointer to an arbitrary row in the result
    • mysqli_result::fetch_all - Fetches all result rows as an associative array, a numeric array, or both
    • mysqli_result::fetch_array - Fetch a result row as an associative, a numeric array, or both
    • mysqli_result::fetch_assoc - Fetch a result row as an associative array
    • mysqli_result::fetch_field - Returns the next field in the result set
    • mysqli_result::fetch_fields - Returns an array of objects representing the fields in a result set
    • mysqli_result::fetch_field_direct - Fetch meta-data for a single field
    • mysqli_result::fetch_object - Returns the current row of a result set as an object
    • mysqli_result::fetch_row - Get a result row as an enumerated array
    • mysqli_result::field_seek - Set result pointer to a specified field offset
    • mysqli_result::free - Frees the memory associated with a result
    • mysqli_rpl_parse_enabled - Check if RPL parse is enabled
    • mysqli_rpl_probe - RPL probe
    • mysqli_send_long_data - Alias for mysqli_stmt_send_long_data
    • mysqli_slave_query - Force execution of a query on a slave in a master/slave setup
    • mysqli_stmt::$affected_rows - Returns the total number of rows changed, deleted, or inserted by the last executed statement
    • 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::$field_count - Returns the number of field in the given statement
    • mysqli_stmt::$insert_id - Get the ID generated from the previous INSERT operation
    • mysqli_stmt::$num_rows - Return the number of rows in statements result set
    • mysqli_stmt::$param_count - Returns the number of parameter for the given statement
    • mysqli_stmt::$sqlstate - Returns SQLSTATE error from previous statement operation
    • 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::data_seek - Seeks to an arbitrary row in statement result set
    • mysqli_stmt::execute - Executes a prepared Query
    • mysqli_stmt::fetch - Fetch results from a prepared statement into the bound variables
    • 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
    • mysqli_stmt::get_warnings - Get result of SHOW WARNINGS
    • 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::prepare - Prepare 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::store_result - Transfers a result set from a prepared statement
    • mysqli_stmt::__construct - Constructs a new mysqli_stmt object
    • mysqli_warning::next - Fetch next warning
    • mysqli_warning::__construct - The __construct purpose
    • MysqlndUhConnection::changeUser - Changes the user of the specified mysqlnd database connection
    • MysqlndUhConnection::charsetName - Returns the default character set for the database connection
    • MysqlndUhConnection::close - Closes a previously opened database connection
    • MysqlndUhConnection::connect - Open a new connection to the MySQL server
    • MysqlndUhConnection::endPSession - End a persistent connection
    • MysqlndUhConnection::escapeString - Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
    • MysqlndUhConnection::getAffectedRows - Gets the number of affected rows in a previous MySQL operation
    • MysqlndUhConnection::getErrorNumber - Returns the error code for the most recent function call
    • MysqlndUhConnection::getErrorString - Returns a string description of the last error
    • MysqlndUhConnection::getFieldCount - Returns the number of columns for the most recent query
    • MysqlndUhConnection::getHostInformation - Returns a string representing the type of connection used
    • MysqlndUhConnection::getLastInsertId - Returns the auto generated id used in the last query
    • MysqlndUhConnection::getLastMessage - Retrieves information about the most recently executed query
    • MysqlndUhConnection::getProtocolInformation - Returns the version of the MySQL protocol used
    • MysqlndUhConnection::getServerInformation - Returns the version of the MySQL server
    • MysqlndUhConnection::getServerStatistics - Gets the current system status
    • MysqlndUhConnection::getServerVersion - Returns the version of the MySQL server as an integer
    • MysqlndUhConnection::getSqlstate - Returns the SQLSTATE error from previous MySQL operation
    • MysqlndUhConnection::getStatistics - Returns statistics about the client connection
    • MysqlndUhConnection::getThreadId - Returns the thread ID for the current connection
    • MysqlndUhConnection::getWarningCount - Returns the number of warnings from the last query for the given link
    • MysqlndUhConnection::init - Initialize mysqlnd connection
    • MysqlndUhConnection::killConnection - Asks the server to kill a MySQL thread
    • MysqlndUhConnection::listFields - List MySQL table fields
    • MysqlndUhConnection::listMethod - Wrapper for assorted list commands
    • MysqlndUhConnection::moreResults - Check if there are any more query results from a multi query
    • MysqlndUhConnection::nextResult - Prepare next result from multi_query
    • MysqlndUhConnection::ping - Pings a server connection, or tries to reconnect if the connection has gone down
    • MysqlndUhConnection::query - Performs a query on the database
    • MysqlndUhConnection::queryReadResultsetHeader - Read a result set header
    • MysqlndUhConnection::reapQuery - Get result from async query
    • MysqlndUhConnection::refreshServer - Flush or reset tables and caches
    • MysqlndUhConnection::restartPSession - Restart a persistent mysqlnd connection
    • MysqlndUhConnection::selectDb - Selects the default database for database queries
    • MysqlndUhConnection::sendClose - Sends a close command to MySQL
    • MysqlndUhConnection::sendQuery - Sends a query to MySQL
    • MysqlndUhConnection::serverDumpDebugInformation - Dump debugging information into the log for the MySQL server
    • MysqlndUhConnection::setAutocommit - Turns on or off auto-committing database modifications
    • MysqlndUhConnection::setCharset - Sets the default client character set
    • MysqlndUhConnection::setClientOption - Sets a client option
    • MysqlndUhConnection::setServerOption - Sets a server option
    • MysqlndUhConnection::shutdownServer - The shutdownServer purpose
    • MysqlndUhConnection::simpleCommand - Sends a basic COM_* command
    • MysqlndUhConnection::simpleCommandHandleResponse - Process a response for a basic COM_* command send to the client
    • MysqlndUhConnection::sslSet - Used for establishing secure connections using SSL
    • MysqlndUhConnection::stmtInit - Initializes a statement and returns a resource for use with mysqli_statement::prepare
    • MysqlndUhConnection::storeResult - Transfers a result set from the last query
    • MysqlndUhConnection::txCommit - Commits the current transaction
    • MysqlndUhConnection::txRollback - Rolls back current transaction
    • MysqlndUhConnection::useResult - Initiate a result set retrieval
    • MysqlndUhConnection::__construct - The __construct purpose
    • MysqlndUhPreparedStatement::execute - Executes a prepared Query
    • MysqlndUhPreparedStatement::prepare - Prepare an SQL statement for execution
    • MysqlndUhPreparedStatement::__construct - The __construct purpose
    • mysqlnd_memcache_get_config - Returns information about the plugin configuration
    • mysqlnd_memcache_set - Associate a MySQL connection with a Memcache connection
    • mysqlnd_ms_dump_servers - Returns a list of currently configured servers
    • mysqlnd_ms_fabric_select_global - Switch to global sharding server for a given table
    • mysqlnd_ms_fabric_select_shard - Switch to shard
    • mysqlnd_ms_get_last_gtid - Returns the latest global transaction ID
    • mysqlnd_ms_get_last_used_connection - Returns an array which describes the last used connection
    • mysqlnd_ms_get_stats - Returns query distribution and connection statistics
    • mysqlnd_ms_match_wild - Finds whether a table name matches a wildcard pattern or not
    • mysqlnd_ms_query_is_select - Find whether to send the query to the master, the slave or the last used MySQL server
    • mysqlnd_ms_set_qos - Sets the quality of service needed from the cluster
    • mysqlnd_ms_set_user_pick_server - Sets a callback for user-defined read/write splitting
    • mysqlnd_ms_xa_begin - Starts a distributed/XA transaction among MySQL servers
    • mysqlnd_ms_xa_commit - Commits a distributed/XA transaction among MySQL servers
    • mysqlnd_ms_xa_gc - Garbage collects unfinished XA transactions after severe errors
    • mysqlnd_ms_xa_rollback - Rolls back a distributed/XA transaction among MySQL servers
    • mysqlnd_qc_clear_cache - Flush all cache contents
    • mysqlnd_qc_get_available_handlers - Returns a list of available storage handler
    • mysqlnd_qc_get_cache_info - Returns information on the current handler, the number of cache entries and cache entries, if available
    • mysqlnd_qc_get_core_stats - Statistics collected by the core of the query cache
    • mysqlnd_qc_get_normalized_query_trace_log - Returns a normalized query trace log for each query inspected by the query cache
    • mysqlnd_qc_get_query_trace_log - Returns a backtrace for each query inspected by the query cache
    • mysqlnd_qc_set_cache_condition - Set conditions for automatic caching
    • mysqlnd_qc_set_is_select - Installs a callback which decides whether a statement is cached
    • mysqlnd_qc_set_storage_handler - Change current storage handler
    • mysqlnd_qc_set_user_handlers - Sets the callback functions for a user-defined procedural storage handler
    • mysqlnd_uh_convert_to_mysqlnd - Converts a MySQL connection handle into a mysqlnd connection handle
    • mysqlnd_uh_set_connection_proxy - Installs a proxy for mysqlnd connections
    • mysqlnd_uh_set_statement_proxy - Installs a proxy for mysqlnd statements
    • 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_xdevapi\Client::close - Close client
    • m_checkstatus - Check to see if a transaction has completed
    • m_completeauthorizations - Number of complete authorizations in queue, returning an array of their identifiers
    • m_connect - Establish the connection to MCVE
    • m_connectionerror - Get a textual representation of why a connection failed
    • m_deletetrans - Delete specified transaction from MCVE_CONN structure
    • m_destroyconn - Destroy the connection and MCVE_CONN structure
    • m_destroyengine - Free memory associated with IP/SSL connectivity
    • m_getcell - Get a specific cell from a comma delimited response by column name
    • m_getcellbynum - Get a specific cell from a comma delimited response by column number
    • m_getcommadelimited - Get the RAW comma delimited data returned from MCVE
    • m_getheader - Get the name of the column in a comma-delimited response
    • m_initconn - Create and initialize an MCVE_CONN structure
    • m_initengine - Ready the client for IP/SSL Communication
    • m_iscommadelimited - Checks to see if response is comma delimited
    • m_maxconntimeout - The maximum amount of time the API will attempt a connection to MCVE
    • m_monitor - Perform communication with MCVE (send/receive data) Non-blocking
    • m_numcolumns - Number of columns returned in a comma delimited response
    • m_numrows - Number of rows returned in a comma delimited response
    • m_parsecommadelimited - Parse the comma delimited response so m_getcell, etc will work
    • m_responsekeys - Returns array of strings which represents the keys that can be used for response parameters on this transaction
    • m_responseparam - Get a custom response parameter
    • m_returnstatus - Check to see if the transaction was successful
    • m_setblocking - Set blocking/non-blocking mode for connection
    • m_setdropfile - Set the connection method to Drop-File
    • m_setip - Set the connection method to IP
    • m_setssl - Set the connection method to SSL
    • m_setssl_cafile - Set SSL CA (Certificate Authority) file for verification of server certificate
    • m_setssl_files - Set certificate key files and certificates if server requires client certificate verification
    • m_settimeout - Set maximum transaction time (per trans)
    • m_sslcert_gen_hash - Generate hash for SSL client certificate verification
    • m_transactionssent - Check to see if outgoing buffer is clear
    • m_transinqueue - Number of transactions in client-queue
    • m_transkeyval - Add key/value pair to a transaction. Replaces deprecated transparam()
    • m_transnew - Start a new transaction
    • m_transsend - Finalize and send the transaction
    • m_uwait - Wait x microsecs
    • m_validateidentifier - Whether or not to validate the passed identifier on any transaction it is passed to
    • m_verifyconnection - Set whether or not to PING upon connect to verify connection
    • m_verifysslcert - Set whether or not to verify the server ssl certificate
  • n
    • natcasesort - Sort an array using a case insensitive "natural order" algorithm
    • natsort - Sort an array using a "natural order" algorithm
    • ncurses_addch - Add character at current position and advance cursor
    • ncurses_addchnstr - Add attributed string with specified length at current position
    • ncurses_addchstr - Add attributed string at current position
    • ncurses_addnstr - Add string with specified length at current position
    • ncurses_addstr - Output text at current position
    • ncurses_assume_default_colors - Define default colors for color 0
    • ncurses_attroff - Turn off the given attributes
    • ncurses_attron - Turn on the given attributes
    • ncurses_attrset - Set given attributes
    • ncurses_baudrate - Returns baudrate of terminal
    • ncurses_beep - Let the terminal beep
    • ncurses_bkgd - Set background property for terminal screen
    • ncurses_bkgdset - Control screen background
    • ncurses_border - Draw a border around the screen using attributed characters
    • ncurses_bottom_panel - Moves a visible panel to the bottom of the stack
    • ncurses_can_change_color - Checks if terminal color definitions can be changed
    • ncurses_cbreak - Switch off input buffering
    • ncurses_clear - Clear screen
    • ncurses_clrtobot - Clear screen from current position to bottom
    • ncurses_clrtoeol - Clear screen from current position to end of line
    • ncurses_color_content - Retrieves RGB components of a color
    • ncurses_color_set - Set active foreground and background colors
    • ncurses_curs_set - Set cursor state
    • ncurses_define_key - Define a keycode
    • ncurses_def_prog_mode - Saves terminals (program) mode
    • ncurses_def_shell_mode - Saves terminals (shell) mode
    • ncurses_delay_output - Delay output on terminal using padding characters
    • ncurses_delch - Delete character at current position, move rest of line left
    • ncurses_deleteln - Delete line at current position, move rest of screen up
    • ncurses_delwin - Delete a ncurses window
    • ncurses_del_panel - Remove panel from the stack and delete it (but not the associated window)
    • ncurses_doupdate - Write all prepared refreshes to terminal
    • ncurses_echo - Activate keyboard input echo
    • ncurses_echochar - Single character output including refresh
    • ncurses_end - Stop using ncurses, clean up the screen
    • ncurses_erase - Erase terminal screen
    • ncurses_erasechar - Returns current erase character
    • ncurses_filter - Set LINES for iniscr() and newterm() to 1
    • ncurses_flash - Flash terminal screen (visual bell)
    • ncurses_flushinp - Flush keyboard input buffer
    • ncurses_getch - Read a character from keyboard
    • ncurses_getmaxyx - Returns the size of a window
    • ncurses_getmouse - Reads mouse event
    • ncurses_getyx - Returns the current cursor position for a window
    • ncurses_halfdelay - Put terminal into halfdelay mode
    • ncurses_has_colors - Checks if terminal has color capabilities
    • ncurses_has_ic - Check for insert- and delete-capabilities
    • ncurses_has_il - Check for line insert- and delete-capabilities
    • ncurses_has_key - Check for presence of a function key on terminal keyboard
    • ncurses_hide_panel - Remove panel from the stack, making it invisible
    • ncurses_hline - Draw a horizontal line at current position using an attributed character and max. n characters long
    • ncurses_inch - Get character and attribute at current position
    • ncurses_init - Initialize ncurses
    • ncurses_init_color - Define a terminal color
    • ncurses_init_pair - Define a color pair
    • ncurses_insch - Insert character moving rest of line including character at current position
    • ncurses_insdelln - Insert lines before current line scrolling down (negative numbers delete and scroll up)
    • ncurses_insertln - Insert a line, move rest of screen down
    • ncurses_insstr - Insert string at current position, moving rest of line right
    • ncurses_instr - Reads string from terminal screen
    • ncurses_isendwin - Ncurses is in endwin mode, normal screen output may be performed
    • ncurses_keyok - Enable or disable a keycode
    • ncurses_keypad - Turns keypad on or off
    • ncurses_killchar - Returns current line kill character
    • ncurses_longname - Returns terminals description
    • ncurses_meta - Enables/Disable 8-bit meta key information
    • ncurses_mouseinterval - Set timeout for mouse button clicks
    • ncurses_mousemask - Sets mouse options
    • ncurses_mouse_trafo - Transforms coordinates
    • ncurses_move - Move output position
    • ncurses_move_panel - Moves a panel so that its upper-left corner is at [startx, starty]
    • ncurses_mvaddch - Move current position and add character
    • ncurses_mvaddchnstr - Move position and add attributed string with specified length
    • ncurses_mvaddchstr - Move position and add attributed string
    • ncurses_mvaddnstr - Move position and add string with specified length
    • ncurses_mvaddstr - Move position and add string
    • ncurses_mvcur - Move cursor immediately
    • ncurses_mvdelch - Move position and delete character, shift rest of line left
    • ncurses_mvgetch - Move position and get character at new position
    • ncurses_mvhline - Set new position and draw a horizontal line using an attributed character and max. n characters long
    • ncurses_mvinch - Move position and get attributed character at new position
    • ncurses_mvvline - Set new position and draw a vertical line using an attributed character and max. n characters long
    • ncurses_mvwaddstr - Add string at new position in window
    • ncurses_napms - Sleep
    • ncurses_newpad - Creates a new pad (window)
    • ncurses_newwin - Create a new window
    • ncurses_new_panel - Create a new panel and associate it with window
    • ncurses_nl - Translate newline and carriage return / line feed
    • ncurses_nocbreak - Switch terminal to cooked mode
    • ncurses_noecho - Switch off keyboard input echo
    • ncurses_nonl - Do not translate newline and carriage return / line feed
    • ncurses_noqiflush - Do not flush on signal characters
    • ncurses_noraw - Switch terminal out of raw mode
    • ncurses_pair_content - Retrieves foreground and background colors of a color pair
    • ncurses_panel_above - Returns the panel above panel
    • ncurses_panel_below - Returns the panel below panel
    • ncurses_panel_window - Returns the window associated with panel
    • ncurses_pnoutrefresh - Copies a region from a pad into the virtual screen
    • ncurses_prefresh - Copies a region from a pad into the virtual screen
    • ncurses_putp - Apply padding information to the string and output it
    • ncurses_qiflush - Flush on signal characters
    • ncurses_raw - Switch terminal into raw mode
    • ncurses_refresh - Refresh screen
    • ncurses_replace_panel - Replaces the window associated with panel
    • ncurses_resetty - Restores saved terminal state
    • ncurses_reset_prog_mode - Resets the prog mode saved by def_prog_mode
    • ncurses_reset_shell_mode - Resets the shell mode saved by def_shell_mode
    • ncurses_savetty - Saves terminal state
    • ncurses_scrl - Scroll window content up or down without changing current position
    • ncurses_scr_dump - Dump screen content to file
    • ncurses_scr_init - Initialize screen from file dump
    • ncurses_scr_restore - Restore screen from file dump
    • ncurses_scr_set - Inherit screen from file dump
    • ncurses_show_panel - Places an invisible panel on top of the stack, making it visible
    • ncurses_slk_attr - Returns current soft label key attribute
    • ncurses_slk_attroff - Turn off the given attributes for soft function-key labels
    • ncurses_slk_attron - Turn on the given attributes for soft function-key labels
    • ncurses_slk_attrset - Set given attributes for soft function-key labels
    • ncurses_slk_clear - Clears soft labels from screen
    • ncurses_slk_color - Sets color for soft label keys
    • ncurses_slk_init - Initializes soft label key functions
    • ncurses_slk_noutrefresh - Copies soft label keys to virtual screen
    • ncurses_slk_refresh - Copies soft label keys to screen
    • ncurses_slk_restore - Restores soft label keys
    • ncurses_slk_set - Sets function key labels
    • ncurses_slk_touch - Forces output when ncurses_slk_noutrefresh is performed
    • ncurses_standend - Stop using 'standout' attribute
    • ncurses_standout - Start using 'standout' attribute
    • ncurses_start_color - Initializes color functionality
    • ncurses_termattrs - Returns a logical OR of all attribute flags supported by terminal
    • ncurses_termname - Returns terminals (short)-name
    • ncurses_timeout - Set timeout for special key sequences
    • ncurses_top_panel - Moves a visible panel to the top of the stack
    • ncurses_typeahead - Specify different filedescriptor for typeahead checking
    • ncurses_ungetch - Put a character back into the input stream
    • ncurses_ungetmouse - Pushes mouse event to queue
    • ncurses_update_panels - Refreshes the virtual screen to reflect the relations between panels in the stack
    • ncurses_use_default_colors - Assign terminal default colors to color id -1
    • ncurses_use_env - Control use of environment information about terminal size
    • ncurses_use_extended_names - Control use of extended names in terminfo descriptions
    • ncurses_vidattr - Display the string on the terminal in the video attribute mode
    • ncurses_vline - Draw a vertical line at current position using an attributed character and max. n characters long
    • ncurses_waddch - Adds character at current position in a window and advance cursor
    • ncurses_waddstr - Outputs text at current postion in window
    • ncurses_wattroff - Turns off attributes for a window
    • ncurses_wattron - Turns on attributes for a window
    • ncurses_wattrset - Set the attributes for a window
    • ncurses_wborder - Draws a border around the window using attributed characters
    • ncurses_wclear - Clears window
    • ncurses_wcolor_set - Sets windows color pairings
    • ncurses_werase - Erase window contents
    • ncurses_wgetch - Reads a character from keyboard (window)
    • ncurses_whline - Draws a horizontal line in a window at current position using an attributed character and max. n characters long
    • ncurses_wmouse_trafo - Transforms window/stdscr coordinates
    • ncurses_wmove - Moves windows output position
    • ncurses_wnoutrefresh - Copies window to virtual screen
    • ncurses_wrefresh - Refresh window on terminal screen
    • ncurses_wstandend - End standout mode for a window
    • ncurses_wstandout - Enter standout mode for a window
    • ncurses_wvline - Draws a vertical line in a window at current position using an attributed character and max. n characters long
    • newt_bell - Send a beep to the terminal
    • newt_button - Create a new button
    • newt_button_bar - This function returns a grid containing the buttons created
    • newt_centered_window - Open a centered window of the specified size
    • newt_checkbox - Description
    • newt_checkbox_get_value - Retreives value of checkox resource
    • newt_checkbox_set_flags - Configures checkbox resource
    • newt_checkbox_set_value - Sets the value of the checkbox
    • newt_checkbox_tree - Description
    • newt_checkbox_tree_add_item - Adds new item to the checkbox tree
    • newt_checkbox_tree_find_item - Finds an item in the checkbox tree
    • newt_checkbox_tree_get_current - Returns checkbox tree selected item
    • newt_checkbox_tree_get_entry_value - Description
    • newt_checkbox_tree_get_multi_selection - Description
    • newt_checkbox_tree_get_selection - Description
    • newt_checkbox_tree_multi - Description
    • newt_checkbox_tree_set_current - Description
    • newt_checkbox_tree_set_entry - Description
    • newt_checkbox_tree_set_entry_value - Description
    • newt_checkbox_tree_set_width - Description
    • newt_clear_key_buffer - Discards the contents of the terminal's input buffer without waiting for additional input
    • newt_cls - Description
    • newt_compact_button - Description
    • newt_component_add_callback - Description
    • newt_component_takes_focus - Description
    • newt_create_grid - Description
    • newt_cursor_off - Description
    • newt_cursor_on - Description
    • newt_delay - Description
    • newt_draw_form - Description
    • newt_draw_root_text - Displays the string text at the position indicated
    • newt_entry - Description
    • newt_entry_get_value - Description
    • newt_entry_set - Description
    • newt_entry_set_filter - Description
    • newt_entry_set_flags - Description
    • newt_finished - Uninitializes newt interface
    • newt_form - Create a form
    • newt_form_add_component - Adds a single component to the form
    • newt_form_add_components - Add several components to the form
    • newt_form_add_hot_key - Description
    • newt_form_destroy - Destroys a form
    • newt_form_get_current - Description
    • newt_form_run - Runs a form
    • newt_form_set_background - Description
    • newt_form_set_height - Description
    • newt_form_set_size - Description
    • newt_form_set_timer - Description
    • newt_form_set_width - Description
    • newt_form_watch_fd - Description
    • newt_get_screen_size - Fills in the passed references with the current size of the terminal
    • newt_grid_add_components_to_form - Description
    • newt_grid_basic_window - Description
    • newt_grid_free - Description
    • newt_grid_get_size - Description
    • newt_grid_h_close_stacked - Description
    • newt_grid_h_stacked - Description
    • newt_grid_place - Description
    • newt_grid_set_field - Description
    • newt_grid_simple_window - Description
    • newt_grid_v_close_stacked - Description
    • newt_grid_v_stacked - Description
    • newt_grid_wrapped_window - Description
    • newt_grid_wrapped_window_at - Description
    • newt_init - Initialize newt
    • newt_label - Description
    • newt_label_set_text - Description
    • newt_listbox - Description
    • newt_listbox_append_entry - Description
    • newt_listbox_clear - Description
    • newt_listbox_clear_selection - Description
    • newt_listbox_delete_entry - Description
    • newt_listbox_get_current - Description
    • newt_listbox_get_selection - Description
    • newt_listbox_insert_entry - Description
    • newt_listbox_item_count - Description
    • newt_listbox_select_item - Description
    • newt_listbox_set_current - Description
    • newt_listbox_set_current_by_key - Description
    • newt_listbox_set_data - Description
    • newt_listbox_set_entry - Description
    • newt_listbox_set_width - Description
    • newt_listitem - Description
    • newt_listitem_get_data - Description
    • newt_listitem_set - Description
    • newt_open_window - Open a window of the specified size and position
    • newt_pop_help_line - Replaces the current help line with the one from the stack
    • newt_pop_window - Removes the top window from the display
    • newt_push_help_line - Saves the current help line on a stack, and displays the new line
    • newt_radiobutton - Description
    • newt_radio_get_current - Description
    • newt_redraw_help_line - Description
    • newt_reflow_text - Description
    • newt_refresh - Updates modified portions of the screen
    • newt_resize_screen - Description
    • newt_resume - Resume using the newt interface after calling newt_suspend
    • newt_run_form - Runs a form
    • newt_scale - Description
    • newt_scale_set - Description
    • newt_scrollbar_set - Description
    • newt_set_help_callback - Description
    • newt_set_suspend_callback - Set a callback function which gets invoked when user presses the suspend key
    • newt_suspend - Tells newt to return the terminal to its initial state
    • newt_textbox - Description
    • newt_textbox_get_num_lines - Description
    • newt_textbox_reflowed - Description
    • newt_textbox_set_height - Description
    • newt_textbox_set_text - Description
    • newt_vertical_scrollbar - Description
    • newt_wait_for_key - Doesn't return until a key has been pressed
    • newt_win_choice - Description
    • newt_win_entries - Description
    • newt_win_menu - Description
    • newt_win_message - Description
    • newt_win_messagev - Description
    • newt_win_ternary - Description
    • next - Advance the internal pointer of an array
    • ngettext - Plural version of gettext
    • nl2br - Inserts HTML line breaks before all newlines in a string
    • nl_langinfo - Query language and locale information
    • NoRewindIterator::current - Get the current value
    • NoRewindIterator::getInnerIterator - Get the inner iterator
    • NoRewindIterator::key - Get the current key
    • NoRewindIterator::next - Forward to the next element
    • NoRewindIterator::rewind - Prevents the rewind operation on the inner iterator
    • NoRewindIterator::valid - Validates the iterator
    • NoRewindIterator::__construct - Construct a NoRewindIterator
    • 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
    • nsapi_request_headers - Fetch all HTTP request headers
    • nsapi_response_headers - Fetch all HTTP response headers
    • nsapi_virtual - Perform an NSAPI sub-request
    • 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
    • number_format - Format a number with grouped thousands
  • o
    • OAuth::disableDebug - Turn off verbose debugging
    • OAuth::disableRedirects - Turn off redirects
    • OAuth::disableSSLChecks - Turn off SSL checks
    • OAuth::enableDebug - Turn on verbose debugging
    • OAuth::enableRedirects - Turn on redirects
    • OAuth::enableSSLChecks - Turn on SSL checks
    • OAuth::fetch - Fetch an OAuth protected resource
    • OAuth::generateSignature - Generate a signature
    • OAuth::getAccessToken - Fetch an access token
    • OAuth::getCAPath - Gets CA information
    • OAuth::getLastResponse - Get the last response
    • OAuth::getLastResponseHeaders - Get headers for last response
    • OAuth::getLastResponseInfo - Get HTTP information about the last response
    • OAuth::getRequestHeader - Generate OAuth header string signature
    • OAuth::getRequestToken - Fetch a request token
    • OAuth::setAuthType - Set authorization type
    • OAuth::setCAPath - Set CA path and info
    • OAuth::setNonce - Set the nonce for subsequent requests
    • OAuth::setRequestEngine - The setRequestEngine purpose
    • OAuth::setRSACertificate - Set the RSA certificate
    • OAuth::setSSLChecks - Tweak specific SSL checks for requests
    • OAuth::setTimestamp - Set the timestamp
    • OAuth::setToken - Sets the token and secret
    • OAuth::setVersion - Set the OAuth version
    • OAuth::__construct - Create a new OAuth object
    • OAuth::__destruct - The destructor
    • OAuthProvider::addRequiredParameter - Add required parameters
    • OAuthProvider::callconsumerHandler - Calls the consumerNonceHandler callback
    • OAuthProvider::callTimestampNonceHandler - Calls the timestampNonceHandler callback
    • OAuthProvider::calltokenHandler - Calls the tokenNonceHandler callback
    • OAuthProvider::checkOAuthRequest - Check an oauth request
    • OAuthProvider::consumerHandler - Set the consumerHandler handler callback
    • OAuthProvider::generateToken - Generate a random token
    • OAuthProvider::is2LeggedEndpoint - is2LeggedEndpoint
    • OAuthProvider::isRequestTokenEndpoint - Sets isRequestTokenEndpoint
    • OAuthProvider::removeRequiredParameter - Remove a required parameter
    • OAuthProvider::reportProblem - Report a problem
    • OAuthProvider::setParam - Set a parameter
    • OAuthProvider::setRequestTokenPath - Set request token path
    • OAuthProvider::timestampNonceHandler - Set the timestampNonceHandler handler callback
    • OAuthProvider::tokenHandler - Set the tokenHandler handler callback
    • OAuthProvider::__construct - Constructs a new OAuthProvider object
    • oauth_get_sbs - Generate a Signature Base String
    • oauth_urlencode - Encode a URI to RFC 3986
    • ob_clean - Clean (erase) the output buffer
    • ob_end_clean - Clean (erase) the output buffer and turn off output buffering
    • ob_end_flush - Flush (send) the output buffer and turn off output buffering
    • ob_flush - Flush (send) the output buffer
    • ob_get_clean - Get current buffer contents and delete current output buffer
    • ob_get_contents - Return the contents of the output buffer
    • ob_get_flush - Flush the output buffer, return it as a string and turn off output buffering
    • 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_gzhandler - ob_start callback function to gzip output buffer
    • ob_iconv_handler - Convert character encoding as output buffer handler
    • ob_implicit_flush - Turn implicit flush on/off
    • ob_list_handlers - List all output handlers in use
    • ob_start - Turn on output buffering
    • ob_tidyhandler - ob_start callback function to repair the buffer
    • OCI-Collection::append - Appends element to the collection
    • OCI-Collection::assign - Assigns a value to the collection from another existing collection
    • OCI-Collection::assignElem - Assigns a value to the element of the collection
    • OCI-Collection::free - Frees the resources associated with the collection object
    • OCI-Collection::getElem - Returns value of the element
    • OCI-Collection::max - Returns the maximum number of elements in the collection
    • OCI-Collection::size - Returns size of the collection
    • OCI-Collection::trim - Trims elements from the end of the collection
    • OCI-Lob::append - Appends data from the large object to another large object
    • OCI-Lob::close - Closes LOB descriptor
    • OCI-Lob::eof - Tests for end-of-file on a large object's descriptor
    • OCI-Lob::erase - Erases a specified portion of the internal LOB data
    • OCI-Lob::export - Exports LOB's contents to a file
    • OCI-Lob::flush - Flushes/writes buffer of the LOB to the server
    • OCI-Lob::free - Frees resources associated with the LOB descriptor
    • OCI-Lob::getBuffering - Returns current state of buffering for the large object
    • OCI-Lob::import - Imports file data to the LOB
    • OCI-Lob::load - Returns large object's contents
    • OCI-Lob::read - Reads part of the large object
    • OCI-Lob::rewind - Moves the internal pointer to the beginning of the large object
    • OCI-Lob::save - Saves data to the large object
    • OCI-Lob::saveFile - Alias of OCI-Lob::import
    • OCI-Lob::seek - Sets the internal pointer of the large object
    • OCI-Lob::setBuffering - Changes current state of buffering for the large object
    • OCI-Lob::size - Returns size of large object
    • OCI-Lob::tell - Returns the current position of internal pointer of large object
    • OCI-Lob::truncate - Truncates large object
    • OCI-Lob::write - Writes data to the large object
    • OCI-Lob::writeTemporary - Writes a temporary large object
    • OCI-Lob::writeToFile - Alias of OCI-Lob::export
    • ocibindbyname - Alias of oci_bind_by_name
    • ocicancel - Alias of oci_cancel
    • ocicloselob - Alias of OCI-Lob::close
    • ocicollappend - Alias of OCI-Collection::append
    • ocicollassign - Alias of OCI-Collection::assign
    • ocicollassignelem - Alias of OCI-Collection::assignElem
    • ocicollgetelem - Alias of OCI-Collection::getElem
    • ocicollmax - Alias of OCI-Collection::max
    • ocicollsize - Alias of OCI-Collection::size
    • ocicolltrim - Alias of OCI-Collection::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 OCI-Collection::free
    • ocifreecursor - Alias of oci_free_statement
    • ocifreedesc - Alias of OCI-Lob::free
    • ocifreestatement - Alias of oci_free_statement
    • ociinternaldebug - Alias of oci_internal_debug
    • ociloadlob - Alias of OCI-Lob::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 OCI-Lob::save
    • ocisavelobfile - Alias of OCI-Lob::import
    • ociserverversion - Alias of oci_server_version
    • ocisetprefetch - Alias of oci_set_prefetch
    • ocistatementtype - Alias of oci_statement_type
    • ociwritelobtofile - Alias of OCI-Lob::export
    • ociwritetemporarylob - Alias of OCI-Lob::writeTemporary
    • 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 12c Implicit Result Sets
    • oci_internal_debug - Enables or disables internal debug output
    • 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_statement_type - Returns the type of a statement
    • oci_unregister_taf_callback - Unregister a user-defined callback function for Oracle Database TAF
    • octdec - Octal to decimal
    • 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_cursor - Get cursorname
    • odbc_data_source - Returns information about a current connection
    • odbc_do - Alias of odbc_exec
    • odbc_error - Get the last error code
    • odbc_errormsg - Get the last error message
    • odbc_exec - Prepare and 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 resources 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
    • ogg:// - Audio streams
    • 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_reset - Resets the contents of the opcode cache
    • 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
    • opendir - Open directory handle
    • openlog - Open connection to system logger
    • openssl_cipher_iv_length - Gets the cipher iv length
    • 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_pbkdf2 - Generates a PKCS5 v2 PBKDF2 string
    • 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_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_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 assoicated 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_checkpurpose - Verifies if a certificate can be used for a particular purpose
    • openssl_x509_check_private_key - Checks if a private key corresponds to a certificate
    • 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 a resource identifier for it
    • ord - Convert the first byte of a string to a value between 0 and 255
    • OuterIterator::getInnerIterator - Returns the inner iterator for the current entry
    • output_add_rewrite_var - Add URL rewriter values
    • output_reset_rewrite_vars - Reset URL rewriter values
    • override_function - Overrides built-in functions
  • p
    • pack - Pack data into binary string
    • parallel\bootstrap - Bootstrapping
    • parallel\Channel::close - Closing
    • parallel\Channel::make - Access
    • parallel\Channel::open - Access
    • parallel\Channel::recv - Sharing
    • parallel\Channel::send - Sharing
    • parallel\Channel::__construct - Channel Construction
    • parallel\Events::addChannel - Targets
    • parallel\Events::addFuture - Targets
    • parallel\Events::poll - Polling
    • parallel\Events::remove - Targets
    • parallel\Events::setBlocking - Behaviour
    • parallel\Events::setInput - Input
    • parallel\Events::setTimeout - Behaviour
    • parallel\Events\Input::add - Inputs
    • parallel\Events\Input::clear - Inputs
    • parallel\Events\Input::remove - Inputs
    • parallel\Future::cancel - Cancellation
    • parallel\Future::cancelled - State Detection
    • parallel\Future::done - State Detection
    • parallel\Future::value - Resolution
    • parallel\run - Execution
    • parallel\Runtime::close - Runtime Graceful Join
    • parallel\Runtime::kill - Runtime Join
    • parallel\Runtime::run - Execution
    • parallel\Runtime::__construct - Runtime Construction
    • parallel\Sync::get - Access
    • parallel\Sync::notify - Synchronization
    • parallel\Sync::set - Access
    • parallel\Sync::wait - Synchronization
    • parallel\Sync::__construct - Construction
    • parallel\Sync::__invoke - Synchronization
    • ParentIterator::accept - Determines acceptability
    • ParentIterator::getChildren - Return the inner iterator's children contained in a ParentIterator
    • ParentIterator::hasChildren - Check whether the inner iterator's current element has children
    • ParentIterator::next - Move the iterator forward
    • ParentIterator::rewind - Rewind the iterator
    • ParentIterator::__construct - Constructs a ParentIterator
    • Parle\Lexer::advance - Process next lexer rule
    • Parle\Lexer::build - Finalize the lexer rule set
    • Parle\Lexer::callout - Define token callback
    • Parle\Lexer::consume - Pass the data for processing
    • Parle\Lexer::dump - Dump the state machine
    • Parle\Lexer::getToken - Retrieve the current token
    • Parle\Lexer::insertMacro - Insert regex macro
    • Parle\Lexer::push - Add a lexer rule
    • Parle\Lexer::reset - Reset lexer
    • Parle\Parser::advance - Process next parser rule
    • Parle\Parser::build - Finalize the grammar rules
    • Parle\Parser::consume - Consume the data for processing
    • Parle\Parser::dump - Dump the grammar
    • Parle\Parser::errorInfo - Retrieve the error information
    • Parle\Parser::left - Declare a token with left-associativity
    • Parle\Parser::nonassoc - Declare a token with no associativity
    • Parle\Parser::precedence - Declare a precedence rule
    • Parle\Parser::push - Add a grammar rule
    • Parle\Parser::reset - Reset parser state
    • Parle\Parser::right - Declare a token with right-associativity
    • Parle\Parser::sigil - Retrieve a matching part of a rule
    • Parle\Parser::token - Declare a token
    • Parle\Parser::tokenId - Get token id
    • Parle\Parser::trace - Trace the parser operation
    • Parle\Parser::validate - Validate input
    • Parle\RLexer::advance - Process next lexer rule
    • Parle\RLexer::build - Finalize the lexer rule set
    • Parle\RLexer::callout - Define token callback
    • Parle\RLexer::consume - Pass the data for processing
    • Parle\RLexer::dump - Dump the state machine
    • Parle\RLexer::getToken - Retrieve the current token
    • Parle\RLexer::insertMacro - Insert regex macro
    • Parle\RLexer::push - Add a lexer rule
    • Parle\RLexer::pushState - Push a new start state
    • Parle\RLexer::reset - Reset lexer
    • Parle\RParser::advance - Process next parser rule
    • Parle\RParser::build - Finalize the grammar rules
    • Parle\RParser::consume - Consume the data for processing
    • Parle\RParser::dump - Dump the grammar
    • Parle\RParser::errorInfo - Retrieve the error information
    • Parle\RParser::left - Declare a token with left-associativity
    • Parle\RParser::nonassoc - Declare a token with no associativity
    • Parle\RParser::precedence - Declare a precedence rule
    • Parle\RParser::push - Add a grammar rule
    • Parle\RParser::reset - Reset parser state
    • Parle\RParser::right - Declare a token with right-associativity
    • Parle\RParser::sigil - Retrieve a matching part of a rule
    • Parle\RParser::token - Declare a token
    • Parle\RParser::tokenId - Get token id
    • Parle\RParser::trace - Trace the parser operation
    • Parle\RParser::validate - Validate input
    • Parle\Stack::pop - Pop an item from the stack
    • Parle\Stack::push - Push an item into the stack
    • parsekit_compile_file - Compile a PHP file and return the resulting op array
    • parsekit_compile_string - Compile a string of PHP code and return the resulting op array
    • parsekit_func_arginfo - Return information regarding function argument(s)
    • parse_ini_file - Parse a configuration file
    • parse_ini_string - Parse a configuration string
    • parse_str - Parses the string into variables
    • parse_url - Parse a URL and return its components
    • passthru - Execute an external program and display raw output
    • 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
    • pathinfo - Returns information about a file path
    • pclose - Closes process file pointer
    • pcntl_alarm - Set an alarm clock for delivery of a signal
    • pcntl_async_signals - Enable/disable asynchronous signal handling or return the old setting
    • pcntl_errno - Alias of pcntl_get_last_error
    • pcntl_exec - Executes specified program in current process space
    • pcntl_fork - Forks the currently running process
    • pcntl_getpriority - Get the priority of any process
    • pcntl_get_last_error - Retrieve the error number set by the last pcntl function which failed
    • pcntl_setpriority - Change the priority of any process
    • pcntl_signal - Installs a signal handler
    • pcntl_signal_dispatch - Calls signal handlers for pending signals
    • pcntl_signal_get_handler - Get the current handler for specified signal
    • pcntl_sigprocmask - Sets and retrieves blocked signals
    • pcntl_sigtimedwait - Waits for signals, with a timeout
    • pcntl_sigwaitinfo - Waits for signals
    • pcntl_strerror - Retrieve the system error message associated with the given errno
    • pcntl_wait - Waits on or returns the status of a forked child
    • pcntl_waitpid - Waits on or returns the status of a forked child
    • pcntl_wexitstatus - Returns the return code of a terminated child
    • pcntl_wifexited - Checks if status code represents a normal exit
    • pcntl_wifsignaled - Checks whether the status code represents a termination due to a signal
    • pcntl_wifstopped - Checks whether the child process is currently stopped
    • pcntl_wstopsig - Returns the signal which caused the child to stop
    • pcntl_wtermsig - Returns the signal which caused the child to terminate
    • PDF_activate_item - Activate structure element or other content item
    • PDF_add_annotation - Add annotation [deprecated]
    • PDF_add_bookmark - Add bookmark for current page [deprecated]
    • PDF_add_launchlink - Add launch annotation for current page [deprecated]
    • PDF_add_locallink - Add link annotation for current page [deprecated]
    • PDF_add_nameddest - Create named destination
    • PDF_add_note - Set annotation for current page [deprecated]
    • PDF_add_outline - Add bookmark for current page [deprecated]
    • PDF_add_pdflink - Add file link annotation for current page [deprecated]
    • PDF_add_table_cell - Add a cell to a new or existing table
    • PDF_add_textflow - Create Textflow or add text to existing Textflow
    • PDF_add_thumbnail - Add thumbnail for current page
    • PDF_add_weblink - Add weblink for current page [deprecated]
    • PDF_arc - Draw a counterclockwise circular arc segment
    • PDF_arcn - Draw a clockwise circular arc segment
    • PDF_attach_file - Add file attachment for current page [deprecated]
    • PDF_begin_document - Create new PDF file
    • PDF_begin_font - Start a Type 3 font definition
    • PDF_begin_glyph - Start glyph definition for Type 3 font
    • PDF_begin_item - Open structure element or other content item
    • PDF_begin_layer - Start layer
    • PDF_begin_page - Start new page [deprecated]
    • PDF_begin_page_ext - Start new page
    • PDF_begin_pattern - Start pattern definition
    • PDF_begin_template - Start template definition [deprecated]
    • PDF_begin_template_ext - Start template definition
    • PDF_circle - Draw a circle
    • PDF_clip - Clip to current path
    • PDF_close - Close pdf resource [deprecated]
    • PDF_closepath - Close current path
    • PDF_closepath_fill_stroke - Close, fill and stroke current path
    • PDF_closepath_stroke - Close and stroke path
    • PDF_close_image - Close image
    • PDF_close_pdi - Close the input PDF document [deprecated]
    • PDF_close_pdi_page - Close the page handle
    • PDF_concat - Concatenate a matrix to the CTM
    • PDF_continue_text - Output text in next line
    • PDF_create_3dview - Create 3D view
    • PDF_create_action - Create action for objects or events
    • PDF_create_annotation - Create rectangular annotation
    • PDF_create_bookmark - Create bookmark
    • PDF_create_field - Create form field
    • PDF_create_fieldgroup - Create form field group
    • PDF_create_gstate - Create graphics state object
    • PDF_create_pvf - Create PDFlib virtual file
    • PDF_create_textflow - Create textflow object
    • PDF_curveto - Draw Bezier curve
    • PDF_define_layer - Create layer definition
    • PDF_delete - Delete PDFlib object
    • PDF_delete_pvf - Delete PDFlib virtual file
    • PDF_delete_table - Delete table object
    • PDF_delete_textflow - Delete textflow object
    • PDF_encoding_set_char - Add glyph name and/or Unicode value
    • PDF_endpath - End current path
    • PDF_end_document - Close PDF file
    • PDF_end_font - Terminate Type 3 font definition
    • PDF_end_glyph - Terminate glyph definition for Type 3 font
    • PDF_end_item - Close structure element or other content item
    • PDF_end_layer - Deactivate all active layers
    • PDF_end_page - Finish page
    • PDF_end_page_ext - Finish page
    • PDF_end_pattern - Finish pattern
    • PDF_end_template - Finish template
    • PDF_fill - Fill current path
    • PDF_fill_imageblock - Fill image block with variable data
    • PDF_fill_pdfblock - Fill PDF block with variable data
    • PDF_fill_stroke - Fill and stroke path
    • PDF_fill_textblock - Fill text block with variable data
    • PDF_findfont - Prepare font for later use [deprecated]
    • PDF_fit_image - Place image or template
    • PDF_fit_pdi_page - Place imported PDF page
    • PDF_fit_table - Place table on page
    • PDF_fit_textflow - Format textflow in rectangular area
    • PDF_fit_textline - Place single line of text
    • PDF_get_apiname - Get name of unsuccessfull API function
    • PDF_get_buffer - Get PDF output buffer
    • PDF_get_errmsg - Get error text
    • PDF_get_errnum - Get error number
    • PDF_get_font - Get font [deprecated]
    • PDF_get_fontname - Get font name [deprecated]
    • PDF_get_fontsize - Font handling [deprecated]
    • PDF_get_image_height - Get image height [deprecated]
    • PDF_get_image_width - Get image width [deprecated]
    • PDF_get_majorversion - Get major version number [deprecated]
    • PDF_get_minorversion - Get minor version number [deprecated]
    • PDF_get_parameter - Get string parameter
    • PDF_get_pdi_parameter - Get PDI string parameter [deprecated]
    • PDF_get_pdi_value - Get PDI numerical parameter [deprecated]
    • PDF_get_value - Get numerical parameter
    • PDF_info_font - Query detailed information about a loaded font
    • PDF_info_matchbox - Query matchbox information
    • PDF_info_table - Retrieve table information
    • PDF_info_textflow - Query textflow state
    • PDF_info_textline - Perform textline formatting and query metrics
    • PDF_initgraphics - Reset graphic state
    • PDF_lineto - Draw a line
    • PDF_load_3ddata - Load 3D model
    • PDF_load_font - Search and prepare font
    • PDF_load_iccprofile - Search and prepare ICC profile
    • PDF_load_image - Open image file
    • PDF_makespotcolor - Make spot color
    • PDF_moveto - Set current point
    • PDF_new - Create PDFlib object
    • PDF_open_ccitt - Open raw CCITT image [deprecated]
    • PDF_open_file - Create PDF file [deprecated]
    • PDF_open_gif - Open GIF image [deprecated]
    • PDF_open_image - Use image data [deprecated]
    • PDF_open_image_file - Read image from file [deprecated]
    • PDF_open_jpeg - Open JPEG image [deprecated]
    • PDF_open_memory_image - Open image created with PHP's image functions [not supported]
    • PDF_open_pdi - Open PDF file [deprecated]
    • PDF_open_pdi_document - Prepare a pdi document
    • PDF_open_pdi_page - Prepare a page
    • PDF_open_tiff - Open TIFF image [deprecated]
    • PDF_pcos_get_number - Get value of pCOS path with type number or boolean
    • PDF_pcos_get_stream - Get contents of pCOS path with type stream, fstream, or string
    • PDF_pcos_get_string - Get value of pCOS path with type name, string, or boolean
    • PDF_place_image - Place image on the page [deprecated]
    • PDF_place_pdi_page - Place PDF page [deprecated]
    • PDF_process_pdi - Process imported PDF document
    • PDF_rect - Draw rectangle
    • PDF_restore - Restore graphics state
    • PDF_resume_page - Resume page
    • PDF_rotate - Rotate coordinate system
    • PDF_save - Save graphics state
    • PDF_scale - Scale coordinate system
    • PDF_setcolor - Set fill and stroke color
    • PDF_setdash - Set simple dash pattern
    • PDF_setdashpattern - Set dash pattern
    • PDF_setflat - Set flatness
    • PDF_setfont - Set font
    • PDF_setgray - Set color to gray [deprecated]
    • PDF_setgray_fill - Set fill color to gray [deprecated]
    • PDF_setgray_stroke - Set stroke color to gray [deprecated]
    • PDF_setlinecap - Set linecap parameter
    • PDF_setlinejoin - Set linejoin parameter
    • PDF_setlinewidth - Set line width
    • PDF_setmatrix - Set current transformation matrix
    • PDF_setmiterlimit - Set miter limit
    • PDF_setpolydash - Set complicated dash pattern [deprecated]
    • PDF_setrgbcolor - Set fill and stroke rgb color values [deprecated]
    • PDF_setrgbcolor_fill - Set fill rgb color values [deprecated]
    • PDF_setrgbcolor_stroke - Set stroke rgb color values [deprecated]
    • PDF_set_border_color - Set border color of annotations [deprecated]
    • PDF_set_border_dash - Set border dash style of annotations [deprecated]
    • PDF_set_border_style - Set border style of annotations [deprecated]
    • PDF_set_char_spacing - Set character spacing [deprecated]
    • PDF_set_duration - Set duration between pages [deprecated]
    • PDF_set_gstate - Activate graphics state object
    • PDF_set_horiz_scaling - Set horizontal text scaling [deprecated]
    • PDF_set_info - Fill document info field
    • PDF_set_info_author - Fill the author document info field [deprecated]
    • PDF_set_info_creator - Fill the creator document info field [deprecated]
    • PDF_set_info_keywords - Fill the keywords document info field [deprecated]
    • PDF_set_info_subject - Fill the subject document info field [deprecated]
    • PDF_set_info_title - Fill the title document info field [deprecated]
    • PDF_set_layer_dependency - Define relationships among layers
    • PDF_set_leading - Set distance between text lines [deprecated]
    • PDF_set_parameter - Set string parameter
    • PDF_set_text_matrix - Set text matrix [deprecated]
    • PDF_set_text_pos - Set text position
    • PDF_set_text_rendering - Determine text rendering [deprecated]
    • PDF_set_text_rise - Set text rise [deprecated]
    • PDF_set_value - Set numerical parameter
    • PDF_set_word_spacing - Set spacing between words [deprecated]
    • PDF_shading - Define blend
    • PDF_shading_pattern - Define shading pattern
    • PDF_shfill - Fill area with shading
    • PDF_show - Output text at current position
    • PDF_show_boxed - Output text in a box [deprecated]
    • PDF_show_xy - Output text at given position
    • PDF_skew - Skew the coordinate system
    • PDF_stringwidth - Return width of text
    • PDF_stroke - Stroke path
    • PDF_suspend_page - Suspend page
    • PDF_translate - Set origin of coordinate system
    • PDF_utf8_to_utf16 - Convert string from UTF-8 to UTF-16
    • PDF_utf16_to_utf8 - Convert string from UTF-16 to UTF-8
    • PDF_utf32_to_utf16 - Convert string from UTF-32 to UTF-16
    • PDO::beginTransaction - Initiates a transaction
    • PDO::commit - Commits a transaction
    • PDO::cubrid_schema - Get the requested schema information
    • 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::pgsqlCopyFromArray - Copy data from PHP array into table
    • PDO::pgsqlCopyFromFile - Copy data from file into table
    • PDO::pgsqlCopyToArray - Copy data from database table into PHP array
    • PDO::pgsqlCopyToFile - Copy data from table into file
    • PDO::pgsqlGetNotify - Get asynchronous notification
    • PDO::pgsqlGetPid - Get the server PID
    • PDO::pgsqlLOBCreate - Creates a new large object
    • PDO::pgsqlLOBOpen - Opens an existing large object stream
    • PDO::pgsqlLOBUnlink - Deletes the large object
    • PDO::prepare - Prepares a statement for execution and returns a statement object
    • PDO::query - Executes an SQL statement, returning a result set as a PDOStatement object
    • PDO::quote - Quotes a string for use in a query
    • PDO::rollBack - Rolls back a transaction
    • PDO::setAttribute - Set an attribute
    • PDO::sqliteCreateAggregate - Registers an aggregating User Defined Function for use in SQL statements
    • PDO::sqliteCreateCollation - Registers a User Defined Function for use as a collating function in SQL statements
    • PDO::sqliteCreateFunction - Registers a User Defined Function for use in SQL statements
    • PDO::__construct - Creates a PDO instance representing a connection to a database
    • 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 - Returns an array containing all of the result set rows
    • 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::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
    • PDO_4D DSN - Connecting to 4D SQL server
    • PDO_CUBRID DSN - Connecting to CUBRID databases
    • PDO_DBLIB DSN - Connecting to Microsoft SQL Server and Sybase databases
    • PDO_FIREBIRD DSN - Connecting to Firebird databases
    • PDO_IBM DSN - Connecting to IBM databases
    • PDO_INFORMIX DSN - Connecting to Informix databases
    • PDO_MYSQL DSN - Connecting to MySQL databases
    • PDO_OCI DSN - Connecting to Oracle databases
    • PDO_ODBC DSN - Connecting to ODBC or DB2 databases
    • PDO_PGSQL DSN - Connecting to PostgreSQL databases
    • PDO_SQLITE DSN - Connecting to SQLite databases
    • PDO_SQLSRV DSN - Connecting to MS SQL Server and SQL Azure databases
    • pfsockopen - Open persistent Internet or Unix domain socket connection
    • 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_connection_busy - Get connection is busy or not
    • pg_connection_reset - Reset connection (reconnect)
    • pg_connection_status - Get connection status
    • pg_connect_poll - Poll the status of an in-progress asynchronous PostgreSQL connection attempt
    • 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 a 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 resource
    • 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 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_seek - Set internal row offset in result resource
    • 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_client_encoding - Set the client encoding
    • 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)
    • phar:// - PHP Archive
    • 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::compressAllFilesBZIP2 - Compresses all files in the current Phar archive using Bzip2 compression
    • Phar::compressAllFilesGZ - Compresses all files in the current Phar archive using Gzip compression
    • Phar::compressFiles - Compresses all files in the current Phar archive
    • 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::delete - Delete a file within a phar archive
    • Phar::delMetadata - Deletes the global metadata of the phar
    • 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::uncompressAllFiles - Uncompresses all files in the current Phar archive
    • Phar::unlinkArchive - Completely remove a phar archive from disk and from memory
    • Phar::webPhar - mapPhar for web-based phars. front controller for web applications
    • Phar::__construct - Construct a Phar archive object
    • Phar context options - Phar context option listing
    • 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 the filesystem 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::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 phar archive to another new file within the phar
    • PharData::decompress - Decompresses the entire Phar archive
    • PharData::decompressFiles - Decompresses all files in the current zip archive
    • PharData::delete - Delete a file within a tar/zip archive
    • PharData::delMetadata - Deletes the global metadata of a zip archive
    • 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::setStub - Dummy function (Phar::setStub is not valid for PharData)
    • PharData::__construct - Construct a non-executable tar or zip archive object
    • PharFileInfo::chmod - Sets file-specific permission bits
    • PharFileInfo::compress - Compresses the current Phar entry with either zlib or bzip2 compression
    • PharFileInfo::decompress - Decompresses the current Phar entry within the phar
    • PharFileInfo::delMetadata - Deletes the metadata of the entry
    • 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::getCRC32 - Returns CRC32 code or throws an exception if CRC has not been verified
    • 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::isCompressed - Returns whether the entry is compressed
    • PharFileInfo::isCompressedBZIP2 - Returns whether the entry is compressed using bzip2
    • PharFileInfo::isCompressedGZ - Returns whether the entry is compressed using gz
    • PharFileInfo::isCRCChecked - Returns whether file entry has had its CRC verified
    • PharFileInfo::setCompressedBZIP2 - Compresses the current Phar entry within the phar using Bzip2 compression
    • PharFileInfo::setCompressedGZ - Compresses the current Phar entry within the phar using gz compression
    • PharFileInfo::setMetadata - Sets file-specific meta-data saved with a file
    • PharFileInfo::setUncompressed - Uncompresses the current Phar entry within the phar, if it is compressed
    • PharFileInfo::__construct - Construct a Phar entry object
    • phdfs::connect - Description
    • phdfs::copy - Description
    • phdfs::create_directory - Description
    • phdfs::delete - Description
    • phdfs::disconnect - Description
    • phdfs::exists - Description
    • phdfs::file_info - Description
    • phdfs::list_directory - Description
    • phdfs::read - Description
    • phdfs::rename - Description
    • phdfs::tell - Description
    • phdfs::write - Description
    • phdfs::__construct - Description
    • phdfs::__destruct - Description
    • php:// - Accessing various I/O streams
    • phpcredits - Prints out the credits for PHP
    • 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 - Description
    • phpdbg_exec - Attempts to set the execution context
    • phpdbg_get_executable - Description
    • phpdbg_prompt - Sets the command prompt
    • phpdbg_start_oplog - Description
    • phpinfo - Outputs information about PHP's configuration
    • phpversion - Gets the current PHP version
    • php_check_syntax - Check the PHP syntax of (and execute) the specified file
    • 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_logo_guid - Gets the logo guid
    • php_sapi_name - Returns the type of interface between web server and PHP
    • php_strip_whitespace - Return source with stripped comments and whitespace
    • php_uname - Returns information about the operating system PHP is running on
    • php_user_filter::filter - Called when applying the filter
    • php_user_filter::onClose - Called when closing the filter
    • php_user_filter::onCreate - Called when creating the filter
    • pht\AtomicInteger::dec - Decrements the atomic integer's value by one
    • pht\AtomicInteger::get - Gets the atomic integer's value
    • pht\AtomicInteger::inc - Increments the atomic integer's value by one
    • pht\AtomicInteger::lock - Acquires the atomic integer's mutex lock
    • pht\AtomicInteger::set - Sets the atomic integer's value
    • pht\AtomicInteger::unlock - Releases the atomic integer's mutex lock
    • pht\AtomicInteger::__construct - AtomicInteger creation
    • pht\HashTable::lock - Acquires the hash table's mutex lock
    • pht\HashTable::size - Gets the size of the hash table
    • pht\HashTable::unlock - Releases the hash table's mutex lock
    • pht\Queue::front - Returns the first value from a queue
    • pht\Queue::lock - Acquires the queue's mutex lock
    • pht\Queue::pop - Pops a value off of the front of a queue
    • pht\Queue::push - Pushes a value to the end of a queue
    • pht\Queue::size - Gets the size of the queue
    • pht\Queue::unlock - Releases the queue's mutex lock
    • pht\Runnable::run - The entry point of a threaded class
    • pht\Thread::addClassTask - Class threading
    • pht\Thread::addFileTask - File threading
    • pht\Thread::addFunctionTask - Function threading
    • pht\Thread::join - Joins a thread
    • pht\Thread::start - Starts the new thread
    • pht\Thread::taskCount - Gets a thread's task count
    • pht\Threaded::lock - Acquires the mutex lock
    • pht\Threaded::unlock - Releases the mutex lock
    • pht\Vector::deleteAt - Deletes a value in the vector
    • pht\Vector::insertAt - Inserts a value into the vector
    • pht\Vector::lock - Acquires the vector's mutex lock
    • pht\Vector::pop - Pops a value to the vector
    • pht\Vector::push - Pushes a value to the vector
    • pht\Vector::resize - Resizes a vector
    • pht\Vector::shift - Shifts a value from the vector
    • pht\Vector::size - Gets the size of the vector
    • pht\Vector::unlock - Releases the vector's mutex lock
    • pht\Vector::unshift - Unshifts a value to the vector front
    • pht\Vector::updateAt - Updates a value in the vector
    • pht\Vector::__construct - Vector creation
    • pi - Get value of pi
    • png2wbmp - Convert PNG image file to WBMP image file
    • Pool::collect - Collect references to completed tasks
    • Pool::resize - Resize the Pool
    • Pool::shutdown - Shutdown all workers
    • Pool::submit - Submits an object for execution
    • Pool::submitTo - Submits a task to a specific worker for execution
    • Pool::__construct - Creates a new Pool of Workers
    • popen - Opens process file pointer
    • pos - Alias of current
    • posix_access - Determine accessibility of a file
    • posix_ctermid - Get path name of controlling terminal
    • posix_errno - Alias of posix_get_last_error
    • posix_getcwd - Pathname of current directory
    • posix_getegid - Return the effective group ID of the current process
    • posix_geteuid - Return the effective user ID of the current process
    • posix_getgid - Return the real group ID of the current process
    • posix_getgrgid - Return info about a group by group id
    • posix_getgrnam - Return info about a group by name
    • posix_getgroups - Return the group set of the current process
    • posix_getlogin - Return login name
    • posix_getpgid - Get process group id for job control
    • posix_getpgrp - Return the current process group identifier
    • posix_getpid - Return the current process identifier
    • posix_getppid - Return the parent process identifier
    • posix_getpwnam - Return info about a user by username
    • posix_getpwuid - Return info about a user by user id
    • posix_getrlimit - Return info about system resource limits
    • posix_getsid - Get the current sid of the process
    • posix_getuid - Return the real user ID of the current process
    • posix_get_last_error - Retrieve the error number set by the last posix function that failed
    • posix_initgroups - Calculate the group access list
    • posix_isatty - Determine if a file descriptor is an interactive terminal
    • posix_kill - Send a signal to a process
    • posix_mkfifo - Create a fifo special file (a named pipe)
    • posix_mknod - Create a special or ordinary file (POSIX.1)
    • posix_setegid - Set the effective GID of the current process
    • posix_seteuid - Set the effective UID of the current process
    • posix_setgid - Set the GID of the current process
    • posix_setpgid - Set process group id for job control
    • posix_setrlimit - Set system resource limits
    • posix_setsid - Make the current process a session leader
    • posix_setuid - Set the UID of the current process
    • posix_strerror - Retrieve the system error message associated with the given errno
    • posix_times - Get process times
    • posix_ttyname - Determine terminal device name
    • posix_uname - Get system name
    • pow - Exponential expression
    • preg_filter - Perform a regular expression search and replace
    • preg_grep - Return array entries that match the pattern
    • preg_last_error - Returns the error code of the last PCRE regex execution
    • preg_match - Perform a regular expression match
    • preg_match_all - Perform a global regular expression match
    • preg_quote - Quote regular expression characters
    • preg_replace - Perform a regular expression search and replace
    • preg_replace_callback - Perform a regular expression search and replace using a callback
    • preg_replace_callback_array - Perform a regular expression search and replace using callbacks
    • preg_split - Split string by a regular expression
    • prev - Rewind the internal array pointer
    • print - Output a string
    • printf - Output a formatted string
    • print_r - Prints human-readable information about a variable
    • proc_close - Close a process opened by proc_open and return the exit code of that process
    • proc_get_status - Get information about a process opened by proc_open
    • proc_nice - Change the priority of the current process
    • proc_open - Execute a command and open file pointers for input/output
    • proc_terminate - Kills a process opened by proc_open
    • property_exists - Checks if the object or class has a property
    • 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
    • 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_closepath - Closes path
    • ps_closepath_stroke - Closes and strokes path
    • ps_close_image - Closes image and frees memory
    • 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_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_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_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_show2 - Output a text at current position
    • ps_show_boxed - Output text in a box
    • ps_show_xy - Output text at given position
    • ps_show_xy2 - Output text at position
    • ps_stringwidth - Gets width of a string
    • ps_string_geometry - Gets geometry 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
    • putenv - Sets the value of an environment variable
    • px_close - Closes a paradox database
    • px_create_fp - Create a new paradox database
    • px_date2string - Converts a date into a string
    • px_delete - Deletes resource of paradox database
    • px_delete_record - Deletes record from paradox database
    • px_get_field - Returns the specification of a single field
    • px_get_info - Return lots of information about a paradox file
    • px_get_parameter - Gets a parameter
    • px_get_record - Returns record of paradox database
    • px_get_schema - Returns the database schema
    • px_get_value - Gets a value
    • px_insert_record - Inserts record into paradox database
    • px_new - Create a new paradox object
    • px_numfields - Returns number of fields in a database
    • px_numrecords - Returns number of records in a database
    • px_open_fp - Open paradox database
    • px_put_record - Stores record into paradox database
    • px_retrieve_record - Returns record of paradox database
    • px_set_blob_file - Sets the file where blobs are read from
    • px_set_parameter - Sets a parameter
    • px_set_tablename - Sets the name of a table (deprecated)
    • px_set_targetencoding - Sets the encoding for character fields (deprecated)
    • px_set_value - Sets a value
    • px_timestamp2string - Converts the timestamp into a string
    • px_update_record - Updates record in paradox database
  • q
    • QuickHashIntHash::add - This method adds a new entry to the hash
    • QuickHashIntHash::delete - This method deletes am entry from the hash
    • QuickHashIntHash::exists - This method checks whether a key is part of the hash
    • QuickHashIntHash::get - This method retrieves a value from the hash by its key
    • QuickHashIntHash::getSize - Returns the number of elements in the hash
    • QuickHashIntHash::loadFromFile - This factory method creates a hash from a file
    • QuickHashIntHash::loadFromString - This factory method creates a hash from a string
    • QuickHashIntHash::saveToFile - This method stores an in-memory hash to disk
    • QuickHashIntHash::saveToString - This method returns a serialized version of the hash
    • QuickHashIntHash::set - This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
    • QuickHashIntHash::update - This method updates an entry in the hash with a new value
    • QuickHashIntHash::__construct - Creates a new QuickHashIntHash object
    • QuickHashIntSet::add - This method adds a new entry to the set
    • QuickHashIntSet::delete - This method deletes an entry from the set
    • QuickHashIntSet::exists - This method checks whether a key is part of the set
    • QuickHashIntSet::getSize - Returns the number of elements in the set
    • QuickHashIntSet::loadFromFile - This factory method creates a set from a file
    • QuickHashIntSet::loadFromString - This factory method creates a set from a string
    • QuickHashIntSet::saveToFile - This method stores an in-memory set to disk
    • QuickHashIntSet::saveToString - This method returns a serialized version of the set
    • QuickHashIntSet::__construct - Creates a new QuickHashIntSet object
    • QuickHashIntStringHash::add - This method adds a new entry to the hash
    • QuickHashIntStringHash::delete - This method deletes am entry from the hash
    • QuickHashIntStringHash::exists - This method checks whether a key is part of the hash
    • QuickHashIntStringHash::get - This method retrieves a value from the hash by its key
    • QuickHashIntStringHash::getSize - Returns the number of elements in the hash
    • QuickHashIntStringHash::loadFromFile - This factory method creates a hash from a file
    • QuickHashIntStringHash::loadFromString - This factory method creates a hash from a string
    • QuickHashIntStringHash::saveToFile - This method stores an in-memory hash to disk
    • QuickHashIntStringHash::saveToString - This method returns a serialized version of the hash
    • QuickHashIntStringHash::set - This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
    • QuickHashIntStringHash::update - This method updates an entry in the hash with a new value
    • QuickHashIntStringHash::__construct - Creates a new QuickHashIntStringHash object
    • QuickHashStringIntHash::add - This method adds a new entry to the hash
    • QuickHashStringIntHash::delete - This method deletes am entry from the hash
    • QuickHashStringIntHash::exists - This method checks whether a key is part of the hash
    • QuickHashStringIntHash::get - This method retrieves a value from the hash by its key
    • QuickHashStringIntHash::getSize - Returns the number of elements in the hash
    • QuickHashStringIntHash::loadFromFile - This factory method creates a hash from a file
    • QuickHashStringIntHash::loadFromString - This factory method creates a hash from a string
    • QuickHashStringIntHash::saveToFile - This method stores an in-memory hash to disk
    • QuickHashStringIntHash::saveToString - This method returns a serialized version of the hash
    • QuickHashStringIntHash::set - This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
    • QuickHashStringIntHash::update - This method updates an entry in the hash with a new value
    • QuickHashStringIntHash::__construct - Creates a new QuickHashStringIntHash object
    • quoted_printable_decode - Convert a quoted-printable string to an 8 bit string
    • quoted_printable_encode - Convert a 8 bit string to a quoted-printable string
    • quotemeta - Quote meta characters
  • r
    • rad2deg - Converts the radian number to the equivalent number in degrees
    • 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
    • rand - Generate a random integer
    • random_bytes - Generates cryptographically secure pseudo-random bytes
    • random_int - Generates cryptographically secure pseudo-random integers
    • range - Create an array containing a range of elements
    • rar:// - RAR
    • 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::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::isUsingExceptions - Check whether error handling with exceptions is in use
    • RarException::setUsingExceptions - Activate and deactivate error handling with exceptions
    • rar_wrapper_cache_stats - Cache hits and misses for the URL wrapper
    • rawurldecode - Decode URL-encoded strings
    • rawurlencode - URL-encode according to RFC 3986
    • readdir - Read entry from directory handle
    • readfile - Outputs a file
    • readgzfile - Output a gz-file
    • 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
    • readlink - Returns the target of a symbolic link
    • read_exif_data - Alias of exif_read_data
    • realpath - Returns canonicalized absolute pathname
    • realpath_cache_get - Get realpath cache entries
    • realpath_cache_size - Get realpath cache size
    • 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
    • RecursiveArrayIterator::getChildren - Returns an iterator for the current entry if it is an array or an object
    • RecursiveArrayIterator::hasChildren - Returns whether current entry is an array or an object
    • RecursiveCachingIterator::getChildren - Return the inner iterator's children as a RecursiveCachingIterator
    • RecursiveCachingIterator::hasChildren - Check whether the current element of the inner iterator has children
    • RecursiveCachingIterator::__construct - Construct
    • RecursiveCallbackFilterIterator::getChildren - Return the inner iterator's children contained in a RecursiveCallbackFilterIterator
    • RecursiveCallbackFilterIterator::hasChildren - Check whether the inner iterator's current element has children
    • RecursiveCallbackFilterIterator::__construct - Create a RecursiveCallbackFilterIterator from a RecursiveIterator
    • RecursiveDirectoryIterator::getChildren - Returns an iterator for the current entry if it is a directory
    • RecursiveDirectoryIterator::getSubPath - Get sub path
    • RecursiveDirectoryIterator::getSubPathname - Get sub path and name
    • RecursiveDirectoryIterator::hasChildren - Returns whether current entry is a directory and not '.' or '..'
    • RecursiveDirectoryIterator::key - Return path and filename of current dir entry
    • RecursiveDirectoryIterator::next - Move to next entry
    • RecursiveDirectoryIterator::rewind - Rewind dir back to the start
    • RecursiveDirectoryIterator::__construct - Constructs a RecursiveDirectoryIterator
    • RecursiveFilterIterator::getChildren - Return the inner iterator's children contained in a RecursiveFilterIterator
    • RecursiveFilterIterator::hasChildren - Check whether the inner iterator's current element has children
    • RecursiveFilterIterator::__construct - Create a RecursiveFilterIterator from a RecursiveIterator
    • RecursiveIterator::getChildren - Returns an iterator for the current entry
    • RecursiveIterator::hasChildren - Returns if an iterator can be created for the current entry
    • RecursiveIteratorIterator::beginChildren - Begin children
    • RecursiveIteratorIterator::beginIteration - Begin Iteration
    • RecursiveIteratorIterator::callGetChildren - Get children
    • RecursiveIteratorIterator::callHasChildren - Has children
    • RecursiveIteratorIterator::current - Access the current element value
    • RecursiveIteratorIterator::endChildren - End children
    • RecursiveIteratorIterator::endIteration - End Iteration
    • RecursiveIteratorIterator::getDepth - Get the current depth of the recursive iteration
    • RecursiveIteratorIterator::getInnerIterator - Get inner iterator
    • RecursiveIteratorIterator::getMaxDepth - Get max depth
    • RecursiveIteratorIterator::getSubIterator - The current active sub iterator
    • RecursiveIteratorIterator::key - Access the current key
    • RecursiveIteratorIterator::next - Move forward to the next element
    • RecursiveIteratorIterator::nextElement - Next element
    • RecursiveIteratorIterator::rewind - Rewind the iterator to the first element of the top level inner iterator
    • RecursiveIteratorIterator::setMaxDepth - Set max depth
    • RecursiveIteratorIterator::valid - Check whether the current position is valid
    • RecursiveIteratorIterator::__construct - Construct a RecursiveIteratorIterator
    • RecursiveRegexIterator::getChildren - Returns an iterator for the current entry
    • RecursiveRegexIterator::hasChildren - Returns whether an iterator can be obtained for the current entry
    • RecursiveRegexIterator::__construct - Creates a new RecursiveRegexIterator
    • RecursiveTreeIterator::beginChildren - Begin children
    • RecursiveTreeIterator::beginIteration - Begin iteration
    • RecursiveTreeIterator::callGetChildren - Get children
    • RecursiveTreeIterator::callHasChildren - Has children
    • RecursiveTreeIterator::current - Get current element
    • RecursiveTreeIterator::endChildren - End children
    • RecursiveTreeIterator::endIteration - End iteration
    • RecursiveTreeIterator::getEntry - Get current entry
    • RecursiveTreeIterator::getPostfix - Get the postfix
    • RecursiveTreeIterator::getPrefix - Get the prefix
    • RecursiveTreeIterator::key - Get the key of the current element
    • RecursiveTreeIterator::next - Move to next element
    • RecursiveTreeIterator::nextElement - Next element
    • RecursiveTreeIterator::rewind - Rewind iterator
    • RecursiveTreeIterator::setPostfix - Set postfix
    • RecursiveTreeIterator::setPrefixPart - Set a part of the prefix
    • RecursiveTreeIterator::valid - Check validity
    • RecursiveTreeIterator::__construct - Construct a RecursiveTreeIterator
    • Reflection::export - Exports
    • Reflection::getModifierNames - Gets modifier names
    • ReflectionClass::export - Exports a class
    • ReflectionClass::getConstant - Gets defined constant
    • ReflectionClass::getConstants - Gets constants
    • ReflectionClass::getConstructor - Gets the constructor of the class
    • ReflectionClass::getDefaultProperties - Gets default properties
    • ReflectionClass::getDocComment - Gets doc comments
    • ReflectionClass::getEndLine - Gets end line
    • ReflectionClass::getExtension - Gets a ReflectionExtension object for the extension which defined the class
    • ReflectionClass::getExtensionName - Gets the name of the extension which defined the class
    • ReflectionClass::getFileName - Gets the filename of the file in which the class has been defined
    • ReflectionClass::getInterfaceNames - Gets the interface names
    • ReflectionClass::getInterfaces - Gets the interfaces
    • ReflectionClass::getMethod - Gets a ReflectionMethod for a class method
    • ReflectionClass::getMethods - Gets an array of methods
    • ReflectionClass::getModifiers - Gets the class modifiers
    • ReflectionClass::getName - Gets class name
    • ReflectionClass::getNamespaceName - Gets namespace name
    • ReflectionClass::getParentClass - Gets parent class
    • ReflectionClass::getProperties - Gets properties
    • ReflectionClass::getProperty - Gets a ReflectionProperty for a class's property
    • ReflectionClass::getReflectionConstant - Gets a ReflectionClassConstant for a class's constant
    • ReflectionClass::getReflectionConstants - Gets class constants
    • ReflectionClass::getShortName - Gets short name
    • ReflectionClass::getStartLine - Gets starting line number
    • ReflectionClass::getStaticProperties - Gets static properties
    • ReflectionClass::getStaticPropertyValue - Gets static property value
    • ReflectionClass::getTraitAliases - Returns an array of trait aliases
    • ReflectionClass::getTraitNames - Returns an array of names of traits used by this class
    • ReflectionClass::getTraits - Returns an array of traits used by this class
    • ReflectionClass::hasConstant - Checks if constant is defined
    • ReflectionClass::hasMethod - Checks if method is defined
    • ReflectionClass::hasProperty - Checks if property is defined
    • ReflectionClass::implementsInterface - Implements interface
    • ReflectionClass::inNamespace - Checks if in namespace
    • ReflectionClass::isAbstract - Checks if class is abstract
    • ReflectionClass::isAnonymous - Checks if class is anonymous
    • ReflectionClass::isCloneable - Returns whether this class is cloneable
    • ReflectionClass::isFinal - Checks if class is final
    • ReflectionClass::isInstance - Checks class for instance
    • ReflectionClass::isInstantiable - Checks if the class is instantiable
    • ReflectionClass::isInterface - Checks if the class is an interface
    • ReflectionClass::isInternal - Checks if class is defined internally by an extension, or the core
    • ReflectionClass::isIterable - Check whether this class is iterable
    • ReflectionClass::isIterateable - Alias of ReflectionClass::isIterable
    • ReflectionClass::isSubclassOf - Checks if a subclass
    • ReflectionClass::isTrait - Returns whether this is a trait
    • ReflectionClass::isUserDefined - Checks if user defined
    • ReflectionClass::newInstance - Creates a new class instance from given arguments
    • ReflectionClass::newInstanceArgs - Creates a new class instance from given arguments
    • ReflectionClass::newInstanceWithoutConstructor - Creates a new class instance without invoking the constructor
    • ReflectionClass::setStaticPropertyValue - Sets static property value
    • ReflectionClass::__construct - Constructs a ReflectionClass
    • ReflectionClass::__toString - Returns the string representation of the ReflectionClass object
    • ReflectionClassConstant::export - Export
    • ReflectionClassConstant::getDeclaringClass - Gets declaring class
    • ReflectionClassConstant::getDocComment - Gets doc comments
    • ReflectionClassConstant::getModifiers - Gets the class constant modifiers
    • ReflectionClassConstant::getName - Get name of the constant
    • ReflectionClassConstant::getValue - Gets value
    • ReflectionClassConstant::isPrivate - Checks if class constant is private
    • ReflectionClassConstant::isProtected - Checks if class constant is protected
    • ReflectionClassConstant::isPublic - Checks if class constant is public
    • ReflectionClassConstant::__construct - Constructs a ReflectionClassConstant
    • ReflectionClassConstant::__toString - Returns the string representation of the ReflectionClassConstant object
    • ReflectionExtension::export - Export
    • ReflectionExtension::getClasses - Gets classes
    • ReflectionExtension::getClassNames - Gets class names
    • ReflectionExtension::getConstants - Gets constants
    • ReflectionExtension::getDependencies - Gets dependencies
    • ReflectionExtension::getFunctions - Gets extension functions
    • ReflectionExtension::getINIEntries - Gets extension ini entries
    • ReflectionExtension::getName - Gets extension name
    • ReflectionExtension::getVersion - Gets extension version
    • ReflectionExtension::info - Print extension info
    • ReflectionExtension::isPersistent - Returns whether this extension is persistent
    • ReflectionExtension::isTemporary - Returns whether this extension is temporary
    • ReflectionExtension::__clone - Clones
    • ReflectionExtension::__construct - Constructs a ReflectionExtension
    • ReflectionExtension::__toString - To string
    • ReflectionFunction::export - Exports function
    • ReflectionFunction::getClosure - Returns a dynamically created closure for the function
    • ReflectionFunction::invoke - Invokes function
    • ReflectionFunction::invokeArgs - Invokes function args
    • ReflectionFunction::isDisabled - Checks if function is disabled
    • ReflectionFunction::__construct - Constructs a ReflectionFunction object
    • ReflectionFunction::__toString - To string
    • ReflectionFunctionAbstract::getClosureScopeClass - Returns the scope associated to the closure
    • ReflectionFunctionAbstract::getClosureThis - Returns this pointer bound to closure
    • ReflectionFunctionAbstract::getDocComment - Gets doc comment
    • ReflectionFunctionAbstract::getEndLine - Gets end line number
    • ReflectionFunctionAbstract::getExtension - Gets extension info
    • ReflectionFunctionAbstract::getExtensionName - Gets extension name
    • ReflectionFunctionAbstract::getFileName - Gets file name
    • ReflectionFunctionAbstract::getName - Gets function name
    • ReflectionFunctionAbstract::getNamespaceName - Gets namespace name
    • ReflectionFunctionAbstract::getNumberOfParameters - Gets number of parameters
    • ReflectionFunctionAbstract::getNumberOfRequiredParameters - Gets number of required parameters
    • ReflectionFunctionAbstract::getParameters - Gets parameters
    • ReflectionFunctionAbstract::getReturnType - Gets the specified return type of a function
    • ReflectionFunctionAbstract::getShortName - Gets function short name
    • ReflectionFunctionAbstract::getStartLine - Gets starting line number
    • ReflectionFunctionAbstract::getStaticVariables - Gets static variables
    • ReflectionFunctionAbstract::hasReturnType - Checks if the function has a specified return type
    • ReflectionFunctionAbstract::inNamespace - Checks if function in namespace
    • ReflectionFunctionAbstract::isClosure - Checks if closure
    • ReflectionFunctionAbstract::isDeprecated - Checks if deprecated
    • ReflectionFunctionAbstract::isGenerator - Returns whether this function is a generator
    • ReflectionFunctionAbstract::isInternal - Checks if is internal
    • ReflectionFunctionAbstract::isUserDefined - Checks if user defined
    • ReflectionFunctionAbstract::isVariadic - Checks if the function is variadic
    • ReflectionFunctionAbstract::returnsReference - Checks if returns reference
    • ReflectionFunctionAbstract::__clone - Clones function
    • ReflectionFunctionAbstract::__toString - To string
    • ReflectionGenerator::getExecutingFile - Gets the file name of the currently executing generator
    • ReflectionGenerator::getExecutingGenerator - Gets the executing Generator object
    • ReflectionGenerator::getExecutingLine - Gets the currently executing line of the generator
    • ReflectionGenerator::getFunction - Gets the function name of the generator
    • ReflectionGenerator::getThis - Gets the $this value of the generator
    • ReflectionGenerator::getTrace - Gets the trace of the executing generator
    • ReflectionGenerator::__construct - Constructs a ReflectionGenerator object
    • ReflectionMethod::export - Export a reflection method
    • ReflectionMethod::getClosure - Returns a dynamically created closure for the method
    • ReflectionMethod::getDeclaringClass - Gets declaring class for the reflected method
    • ReflectionMethod::getModifiers - Gets the method modifiers
    • ReflectionMethod::getPrototype - Gets the method prototype (if there is one)
    • ReflectionMethod::invoke - Invoke
    • ReflectionMethod::invokeArgs - Invoke args
    • ReflectionMethod::isAbstract - Checks if method is abstract
    • ReflectionMethod::isConstructor - Checks if method is a constructor
    • ReflectionMethod::isDestructor - Checks if method is a destructor
    • ReflectionMethod::isFinal - Checks if method is final
    • ReflectionMethod::isPrivate - Checks if method is private
    • ReflectionMethod::isProtected - Checks if method is protected
    • ReflectionMethod::isPublic - Checks if method is public
    • ReflectionMethod::isStatic - Checks if method is static
    • ReflectionMethod::setAccessible - Set method accessibility
    • ReflectionMethod::__construct - Constructs a ReflectionMethod
    • ReflectionMethod::__toString - Returns the string representation of the Reflection method object
    • ReflectionNamedType::getName - Get the text of the type hint
    • ReflectionObject::export - Export
    • ReflectionObject::__construct - Constructs a ReflectionObject
    • ReflectionParameter::allowsNull - Checks if null is allowed
    • ReflectionParameter::canBePassedByValue - Returns whether this parameter can be passed by value
    • ReflectionParameter::export - Exports
    • ReflectionParameter::getClass - Get the type hinted class
    • ReflectionParameter::getDeclaringClass - Gets declaring class
    • ReflectionParameter::getDeclaringFunction - Gets declaring function
    • ReflectionParameter::getDefaultValue - Gets default parameter value
    • ReflectionParameter::getDefaultValueConstantName - Returns the default value's constant name if default value is constant or null
    • ReflectionParameter::getName - Gets parameter name
    • ReflectionParameter::getPosition - Gets parameter position
    • ReflectionParameter::getType - Gets a parameter's type
    • ReflectionParameter::hasType - Checks if parameter has a type
    • ReflectionParameter::isArray - Checks if parameter expects an array
    • ReflectionParameter::isCallable - Returns whether parameter MUST be callable
    • ReflectionParameter::isDefaultValueAvailable - Checks if a default value is available
    • ReflectionParameter::isDefaultValueConstant - Returns whether the default value of this parameter is a constant
    • ReflectionParameter::isOptional - Checks if optional
    • ReflectionParameter::isPassedByReference - Checks if passed by reference
    • ReflectionParameter::isVariadic - Checks if the parameter is variadic
    • ReflectionParameter::__clone - Clone
    • ReflectionParameter::__construct - Construct
    • ReflectionParameter::__toString - To string
    • ReflectionProperty::export - Export
    • ReflectionProperty::getDeclaringClass - Gets declaring class
    • ReflectionProperty::getDocComment - Gets the property doc comment
    • ReflectionProperty::getModifiers - Gets the property modifiers
    • ReflectionProperty::getName - Gets property name
    • ReflectionProperty::getType - Gets a property's type
    • ReflectionProperty::getValue - Gets value
    • ReflectionProperty::hasType - Checks if property has a type
    • ReflectionProperty::isDefault - Checks if property is a default property
    • ReflectionProperty::isInitialized - Checks whether a property is initialized
    • ReflectionProperty::isPrivate - Checks if property is private
    • ReflectionProperty::isProtected - Checks if property is protected
    • ReflectionProperty::isPublic - Checks if property is public
    • ReflectionProperty::isStatic - Checks if property is static
    • ReflectionProperty::setAccessible - Set property accessibility
    • ReflectionProperty::setValue - Set property value
    • ReflectionProperty::__clone - Clone
    • ReflectionProperty::__construct - Construct a ReflectionProperty object
    • ReflectionProperty::__toString - To string
    • ReflectionType::allowsNull - Checks if null is allowed
    • ReflectionType::isBuiltin - Checks if it is a built-in type
    • ReflectionType::__toString - To string
    • ReflectionZendExtension::export - Export
    • ReflectionZendExtension::getAuthor - Gets author
    • ReflectionZendExtension::getCopyright - Gets copyright
    • ReflectionZendExtension::getName - Gets name
    • ReflectionZendExtension::getURL - Gets URL
    • ReflectionZendExtension::getVersion - Gets version
    • ReflectionZendExtension::__clone - Clone handler
    • ReflectionZendExtension::__construct - Constructor
    • ReflectionZendExtension::__toString - To string handler
    • Reflector::export - Exports
    • Reflector::__toString - To string
    • RegexIterator::accept - Get accept status
    • RegexIterator::getFlags - Get flags
    • RegexIterator::getMode - Returns operation mode
    • RegexIterator::getPregFlags - Returns the regular expression flags
    • RegexIterator::getRegex - Returns current regular expression
    • RegexIterator::setFlags - Sets the flags
    • RegexIterator::setMode - Sets the operation mode
    • RegexIterator::setPregFlags - Sets the regular expression flags
    • RegexIterator::__construct - Create a new RegexIterator
    • register_shutdown_function - Register a function for execution on shutdown
    • register_tick_function - Register a function for execution on each tick
    • rename - Renames a file or directory
    • rename_function - Renames orig_name to new_name in the global function table
    • reset - Set the internal pointer of an array to its first element
    • 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
    • restore_error_handler - Restores the previous error handler function
    • restore_exception_handler - Restores the previously defined exception handler function
    • restore_include_path - Restores the value of the include_path configuration option
    • 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
    • Result::__construct - Result constructor
    • rewind - Rewind the position of a file pointer
    • rewinddir - Rewind directory handle
    • rmdir - Removes directory
    • round - Rounds a float
    • RowResult::fetchAll - Get all rows from result
    • RowResult::fetchOne - Get row from result
    • RowResult::getColumnNames - Get all column names
    • RowResult::getColumns - Get column metadata
    • RowResult::getColumnsCount - Get column count
    • RowResult::getWarnings - Get warnings from last operation
    • RowResult::getWarningsCount - Get warning count from last operation
    • RowResult::__construct - RowResult constructor
    • rpm_close - Closes an RPM file
    • rpm_get_tag - Retrieves a header tag from an RPM file
    • rpm_is_valid - Tests a filename for validity as an RPM file
    • rpm_open - Opens an RPM file
    • rpm_version - Returns a string representing the current version of the rpmreader extension
    • RRDCreator::addArchive - Adds RRA - archive of data values for each data source
    • RRDCreator::addDataSource - Adds data source definition for RRD database
    • RRDCreator::save - Saves the RRD database to a file
    • RRDCreator::__construct - Creates new RRDCreator instance
    • rrdc_disconnect - Close any outstanding connection to rrd caching daemon
    • RRDGraph::save - Saves the result of query into image
    • RRDGraph::saveVerbose - Saves the RRD database query into image and returns the verbose information about generated graph
    • RRDGraph::setOptions - Sets the options for rrd graph export
    • RRDGraph::__construct - Creates new RRDGraph instance
    • RRDUpdater::update - Update the RRD database file
    • RRDUpdater::__construct - Creates new RRDUpdater instance
    • rrd_create - Creates rrd database file
    • rrd_error - Gets latest error message
    • rrd_fetch - Fetch the data for graph as array
    • rrd_first - Gets the timestamp of the first sample from rrd file
    • rrd_graph - Creates image from a data
    • rrd_info - Gets information about rrd file
    • rrd_last - Gets unix timestamp of the last sample
    • rrd_lastupdate - Gets information about last updated data
    • rrd_restore - Restores the RRD file from XML dump
    • rrd_tune - Tunes some RRD database file header options
    • rrd_update - Updates the RRD database
    • rrd_version - Gets information about underlying rrdtool library
    • rrd_xport - Exports the information about RRD database
    • rsort - Sort an array in reverse order
    • rtrim - Strip whitespace (or other characters) from the end of a string
    • runkit7_constant_add - Similar to define(), but allows defining in class definitions as well
    • runkit7_constant_redefine - Description
    • 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
    • runkit_class_adopt - Convert a base class to an inherited class, add ancestral methods when appropriate
    • runkit_class_emancipate - Convert an inherited class to a base class, removes any method whose scope is ancestral
    • runkit_constant_add - Similar to define(), but allows defining in class definitions as well
    • runkit_constant_redefine - Redefine an already defined constant
    • runkit_constant_remove - Remove/Delete an already defined constant
    • runkit_function_add - Add a new function, similar to create_function
    • runkit_function_copy - Copy a function to a new function name
    • runkit_function_redefine - Replace a function definition with a new implementation
    • runkit_function_remove - Remove a function definition
    • runkit_function_rename - Change a function's name
    • runkit_import - Process a PHP file importing function and class definitions, overwriting where appropriate
    • runkit_lint - Check the PHP syntax of the specified php code
    • runkit_lint_file - Check the PHP syntax of the specified file
    • runkit_method_add - Dynamically adds a new method to a given class
    • runkit_method_copy - Copies a method from class to another
    • runkit_method_redefine - Dynamically changes the code of the given method
    • runkit_method_remove - Dynamically removes the given method
    • runkit_method_rename - Dynamically changes the name of the given method
    • runkit_return_value_used - Determines if the current functions return value will be used
    • Runkit_Sandbox - Runkit Sandbox Class -- PHP Virtual Machine
    • runkit_sandbox_output_handler - Specify a function to capture and/or process output from a runkit sandbox
    • Runkit_Sandbox_Parent - Runkit Anti-Sandbox Class
    • runkit_superglobals - Return numerically indexed array of registered superglobals
  • s
    • SAMConnection::commit - Commits (completes) the current unit of work
    • SAMConnection::connect - Establishes a connection to a Messaging Server
    • SAMConnection::disconnect - Disconnects from a Messaging Server
    • SAMConnection::errno - Contains the unique numeric error code of the last executed SAM operation
    • SAMConnection::error - Contains the text description of the last failed SAM operation
    • SAMConnection::isConnected - Queries whether a connection is established to a Messaging Server
    • SAMConnection::peek - Read a message from a queue without removing it from the queue
    • SAMConnection::peekAll - Read one or more messages from a queue without removing it from the queue
    • SAMConnection::receive - Receive a message from a queue or subscription
    • SAMConnection::remove - Remove a message from a queue
    • SAMConnection::rollback - Cancels (rolls back) an in-flight unit of work
    • SAMConnection::send - Send a message to a queue or publish an item to a topic
    • SAMConnection::setDebug - Turn on or off additional debugging output
    • SAMConnection::subscribe - Create a subscription to a specified topic
    • SAMConnection::unsubscribe - Cancel a subscription to a specified topic
    • SAMConnection::__construct - Creates a new connection to a Messaging Server
    • SAMMessage::body - The body of the message
    • SAMMessage::header - The header properties of the message
    • SAMMessage::__construct - Creates a new Message object
    • sapi_windows_cp_conv - Convert string from one codepage to another
    • sapi_windows_cp_get - Get process codepage
    • sapi_windows_cp_is_utf8 - Indicates whether the codepage is UTF-8 compatible
    • sapi_windows_cp_set - Set process codepage
    • sapi_windows_generate_ctrl_event - Send a CTRL event to another process
    • sapi_windows_set_ctrl_handler - Set or remove a CTRL event handler
    • sapi_windows_vt100_support - Get or set VT100 support for the specified stream associated to an output buffer of a Windows console.
    • SCA::createDataObject - Create an SDO
    • SCA::getService - Obtain a proxy for a service
    • scandir - List files and directories inside the specified path
    • SCA_LocalProxy::createDataObject - Create an SDO
    • SCA_SoapProxy::createDataObject - Create an SDO
    • 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 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
    • Schema::__construct - constructor
    • SchemaObject::getSchema - Get schema object
    • scoutapm_get_calls - Returns a list of instrumented calls that have occurred
    • scoutapm_list_instrumented_functions - List functions scoutapm will instrument.
    • SDO_DAS_ChangeSummary::beginLogging - Begin change logging
    • SDO_DAS_ChangeSummary::endLogging - End change logging
    • SDO_DAS_ChangeSummary::getChangedDataObjects - Get the changed data objects from a change summary
    • SDO_DAS_ChangeSummary::getChangeType - Get the type of change made to an SDO_DataObject
    • SDO_DAS_ChangeSummary::getOldContainer - Get the old container for a deleted SDO_DataObject
    • SDO_DAS_ChangeSummary::getOldValues - Get the old values for a given changed SDO_DataObject
    • SDO_DAS_ChangeSummary::isLogging - Test to see whether change logging is switched on
    • SDO_DAS_DataFactory::addPropertyToType - Adds a property to a type
    • SDO_DAS_DataFactory::addType - Add a new type to a model
    • SDO_DAS_DataFactory::getDataFactory - Get a data factory instance
    • SDO_DAS_DataObject::getChangeSummary - Get a data object's change summary
    • SDO_DAS_Relational::applyChanges - Applies the changes made to a data graph back to the database
    • SDO_DAS_Relational::createRootDataObject - Returns the special root object in an otherwise empty data graph. Used when creating a data graph from scratch
    • SDO_DAS_Relational::executePreparedQuery - Executes an SQL query passed as a prepared statement, with a list of values to substitute for placeholders, and return the results as a normalised data graph
    • SDO_DAS_Relational::executeQuery - Executes a given SQL query against a relational database and returns the results as a normalised data graph
    • SDO_DAS_Relational::__construct - Creates an instance of a Relational Data Access Service
    • SDO_DAS_Setting::getListIndex - Get the list index for a changed many-valued property
    • SDO_DAS_Setting::getPropertyIndex - Get the property index for a changed property
    • SDO_DAS_Setting::getPropertyName - Get the property name for a changed property
    • SDO_DAS_Setting::getValue - Get the old value for the changed property
    • SDO_DAS_Setting::isSet - Test whether a property was set prior to being modified
    • SDO_DAS_XML::addTypes - To load a second or subsequent schema file to a SDO_DAS_XML object
    • SDO_DAS_XML::create - To create SDO_DAS_XML object for a given schema file
    • SDO_DAS_XML::createDataObject - Creates SDO_DataObject for a given namespace URI and type name
    • SDO_DAS_XML::createDocument - Creates an XML Document object from scratch, without the need to load a document from a file or string
    • SDO_DAS_XML::loadFile - Returns SDO_DAS_XML_Document object for a given path to xml instance document
    • SDO_DAS_XML::loadString - Returns SDO_DAS_XML_Document for a given xml instance string
    • SDO_DAS_XML::saveFile - Saves the SDO_DAS_XML_Document object to a file
    • SDO_DAS_XML::saveString - Saves the SDO_DAS_XML_Document object to a string
    • SDO_DAS_XML_Document::getRootDataObject - Returns the root SDO_DataObject
    • SDO_DAS_XML_Document::getRootElementName - Returns root element's name
    • SDO_DAS_XML_Document::getRootElementURI - Returns root element's URI string
    • SDO_DAS_XML_Document::setEncoding - Sets the given string as encoding
    • SDO_DAS_XML_Document::setXMLDeclaration - Sets the xml declaration
    • SDO_DAS_XML_Document::setXMLVersion - Sets the given string as xml version
    • SDO_DataFactory::create - Create an SDO_DataObject
    • SDO_DataObject::clear - Clear an SDO_DataObject's properties
    • SDO_DataObject::createDataObject - Create a child SDO_DataObject
    • SDO_DataObject::getContainer - Get a data object's container
    • SDO_DataObject::getSequence - Get the sequence for a data object
    • SDO_DataObject::getTypeName - Return the name of the type for a data object
    • SDO_DataObject::getTypeNamespaceURI - Return the namespace URI of the type for a data object
    • SDO_Exception::getCause - Get the cause of the exception
    • SDO_List::insert - Insert into a list
    • SDO_Model_Property::getContainingType - Get the SDO_Model_Type which contains this property
    • SDO_Model_Property::getDefault - Get the default value for the property
    • SDO_Model_Property::getName - Get the name of the SDO_Model_Property
    • SDO_Model_Property::getType - Get the SDO_Model_Type of the property
    • SDO_Model_Property::isContainment - Test to see if the property defines a containment relationship
    • SDO_Model_Property::isMany - Test to see if the property is many-valued
    • SDO_Model_ReflectionDataObject::export - Get a string describing the SDO_DataObject
    • SDO_Model_ReflectionDataObject::getContainmentProperty - Get the property which defines the containment relationship to the data object
    • SDO_Model_ReflectionDataObject::getInstanceProperties - Get the instance properties of the SDO_DataObject
    • SDO_Model_ReflectionDataObject::getType - Get the SDO_Model_Type for the SDO_DataObject
    • SDO_Model_ReflectionDataObject::__construct - Construct an SDO_Model_ReflectionDataObject
    • SDO_Model_Type::getBaseType - Get the base type for this type
    • SDO_Model_Type::getName - Get the name of the type
    • SDO_Model_Type::getNamespaceURI - Get the namespace URI of the type
    • SDO_Model_Type::getProperties - Get the SDO_Model_Property objects defined for the type
    • SDO_Model_Type::getProperty - Get an SDO_Model_Property of the type
    • SDO_Model_Type::isAbstractType - Test to see if this SDO_Model_Type is an abstract data type
    • SDO_Model_Type::isDataType - Test to see if this SDO_Model_Type is a primitive data type
    • SDO_Model_Type::isInstance - Test for an SDO_DataObject being an instance of this SDO_Model_Type
    • SDO_Model_Type::isOpenType - Test to see if this type is an open type
    • SDO_Model_Type::isSequencedType - Test to see if this is a sequenced type
    • SDO_Sequence::getProperty - Return the property for the specified sequence index
    • SDO_Sequence::insert - Insert into a sequence
    • SDO_Sequence::move - Move an item to another sequence position
    • SeasLog::alert - Record alert log information
    • SeasLog::analyzerCount - Get log count by level, log_path and key_word
    • SeasLog::analyzerDetail - Get log detail by level, log_path, key_word, start, limit, order
    • SeasLog::closeLoggerStream - Manually release stream flow from logger
    • SeasLog::critical - Record critical log information
    • SeasLog::debug - Record debug log information
    • SeasLog::emergency - Record emergency log information
    • SeasLog::error - Record error log information
    • SeasLog::flushBuffer - Flush logs buffer, dump to appender file, or send to remote api with tcp/udp
    • SeasLog::getBasePath - Get SeasLog base path.
    • SeasLog::getBuffer - Get the logs buffer in memory as array
    • SeasLog::getBufferEnabled - Determin if buffer enabled
    • SeasLog::getDatetimeFormat - Get SeasLog datetime format style
    • SeasLog::getLastLogger - Get SeasLog last logger path
    • SeasLog::getRequestID - Get SeasLog request_id differentiated requests
    • SeasLog::getRequestVariable - Get SeasLog request variable
    • SeasLog::info - Record info log information
    • SeasLog::log - The Common Record Log Function
    • SeasLog::notice - Record notice log information
    • SeasLog::setBasePath - Set SeasLog base path
    • SeasLog::setDatetimeFormat - Set SeasLog datetime format style
    • SeasLog::setLogger - Set SeasLog logger name
    • SeasLog::setRequestID - Set SeasLog request_id differentiated requests
    • SeasLog::setRequestVariable - Manually set SeasLog request variable
    • SeasLog::warning - Record warning log information
    • SeasLog::__construct - Description
    • SeasLog::__destruct - Description
    • seaslog_get_author - Get SeasLog author.
    • seaslog_get_version - Get SeasLog version.
    • SeekableIterator::seek - Seeks to a position
    • sem_acquire - Acquire a semaphore
    • sem_get - Get a semaphore id
    • sem_release - Release a semaphore
    • sem_remove - Remove a semaphore
    • Serializable::serialize - String representation of object
    • Serializable::unserialize - Constructs the object
    • serialize - Generates a storable representation of a value
    • Session::close - Close session
    • 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 - Execute SQL query
    • Session::startTransaction - Start transaction
    • Session::__construct - Description constructor
    • SessionHandler::close - Close the session
    • SessionHandler::create_sid - Return a new session ID
    • SessionHandler::destroy - Destroy a session
    • SessionHandler::gc - Cleanup old sessions
    • SessionHandler::open - Initialize session
    • SessionHandler::read - Read session data
    • SessionHandler::write - Write session data
    • SessionHandlerInterface::close - Close the session
    • SessionHandlerInterface::destroy - Destroy a session
    • SessionHandlerInterface::gc - Cleanup old sessions
    • SessionHandlerInterface::open - Initialize session
    • SessionHandlerInterface::read - Read session data
    • SessionHandlerInterface::write - Write session data
    • SessionIdInterface::create_sid - Create session ID
    • SessionUpdateTimestampHandlerInterface::updateTimestamp - Update timestamp
    • SessionUpdateTimestampHandlerInterface::validateId - Validate ID
    • session_abort - Discard session array changes and finish session
    • session_cache_expire - Return current cache expire
    • session_cache_limiter - Get and/or set the current cache limiter
    • session_commit - Alias of session_write_close
    • session_create_id - Create new session id
    • session_decode - Decodes session data from a session encoded string
    • session_destroy - Destroys all data registered to a session
    • session_encode - Encodes the current session data as a session encoded string
    • session_gc - Perform session data garbage collection
    • session_get_cookie_params - Get the session cookie parameters
    • session_id - Get and/or set the current session id
    • session_is_registered - Find out whether a global variable is registered in a session
    • session_module_name - Get and/or set the current session module
    • session_name - Get and/or set the current session name
    • session_pgsql_add_error - Increments error counts and sets last error message
    • session_pgsql_get_error - Returns number of errors and last error message
    • session_pgsql_get_field - Get custom field value
    • session_pgsql_reset - Reset connection to session database servers
    • session_pgsql_set_field - Set custom field value
    • session_pgsql_status - Get current save handler status
    • session_regenerate_id - Update the current session id with a newly generated one
    • session_register - Register one or more global variables with the current session
    • session_register_shutdown - Session shutdown function
    • session_reset - Re-initialize session array with original values
    • session_save_path - Get and/or set the current session save path
    • session_set_cookie_params - Set the session cookie parameters
    • session_set_save_handler - Sets user-level session storage functions
    • session_start - Start new or resume existing session
    • session_status - Returns the current session status
    • session_unregister - Unregister a global variable from the current session
    • session_unset - Free all session variables
    • session_write_close - Write session data and end session
    • setcookie - Send a cookie
    • setlocale - Set locale information
    • setproctitle - Set the process title
    • setrawcookie - Send a cookie without urlencoding the cookie value
    • setthreadtitle - Set the thread title
    • settype - Set the type of a variable
    • set_error_handler - Sets a user-defined error handler function
    • set_exception_handler - Sets a user-defined exception handler function
    • set_file_buffer - Alias of stream_set_write_buffer
    • set_include_path - Sets the include_path configuration option
    • set_magic_quotes_runtime - Sets the current active configuration setting of magic_quotes_runtime
    • set_socket_blocking - Alias of stream_set_blocking
    • set_time_limit - Limits the maximum execution time
    • sha1 - Calculate the sha1 hash of a string
    • sha1_file - Calculate the sha1 hash of a file
    • shell_exec - Execute command via shell and return the complete output as a string
    • shmop_close - Close shared memory block
    • shmop_delete - Delete shared memory block
    • shmop_open - Create or open shared memory block
    • shmop_read - Read data from shared memory block
    • shmop_size - Get size of shared memory block
    • shmop_write - Write data into shared memory block
    • shm_attach - Creates or open a shared memory segment
    • shm_detach - Disconnects from shared memory segment
    • shm_get_var - Returns a variable from shared memory
    • shm_has_var - Check whether a specific entry exists
    • shm_put_var - Inserts or updates a variable in shared memory
    • shm_remove - Removes shared memory from Unix systems
    • shm_remove_var - Removes a variable from shared memory
    • show_source - Alias of highlight_file
    • shuffle - Shuffle an array
    • similar_text - Calculate the similarity between two strings
    • SimpleXMLElement::addAttribute - Adds an attribute to the SimpleXML element
    • SimpleXMLElement::addChild - Adds a child element to the XML node
    • SimpleXMLElement::asXML - Return a well-formed XML string based on SimpleXML element
    • SimpleXMLElement::attributes - Identifies an element's attributes
    • SimpleXMLElement::children - Finds children of given node
    • SimpleXMLElement::count - Counts the children of an element
    • SimpleXMLElement::getDocNamespaces - Returns namespaces declared in document
    • SimpleXMLElement::getName - Gets the name of the XML element
    • SimpleXMLElement::getNamespaces - Returns namespaces used in document
    • SimpleXMLElement::registerXPathNamespace - Creates a prefix/ns context for the next XPath query
    • SimpleXMLElement::saveXML - Alias of SimpleXMLElement::asXML
    • SimpleXMLElement::xpath - Runs XPath query on XML data
    • SimpleXMLElement::__construct - Creates a new SimpleXMLElement object
    • SimpleXMLElement::__toString - Returns the string content
    • SimpleXMLIterator::current - Returns the current element
    • SimpleXMLIterator::getChildren - Returns the sub-elements of the current element
    • SimpleXMLIterator::hasChildren - Checks whether the current element has sub elements
    • SimpleXMLIterator::key - Return current key
    • SimpleXMLIterator::next - Move to next element
    • SimpleXMLIterator::rewind - Rewind to the first element
    • SimpleXMLIterator::valid - Check whether the current element is valid
    • simplexml_import_dom - Get a SimpleXMLElement object from a DOM node
    • simplexml_load_file - Interprets an XML file into an object
    • simplexml_load_string - Interprets a string of XML into an object
    • sin - Sine
    • sinh - Hyperbolic sine
    • sizeof - Alias of count
    • sleep - Delay execution
    • snmp2_get - Fetch an SNMP object
    • snmp2_getnext - Fetch the SNMP object which follows the given object id
    • snmp2_real_walk - Return all objects including their respective object ID within the specified one
    • snmp2_set - Set the value of an SNMP object
    • snmp2_walk - Fetch all the SNMP objects from an agent
    • snmp3_get - Fetch an SNMP object
    • snmp3_getnext - Fetch the SNMP object which follows the given object id
    • snmp3_real_walk - Return all objects including their respective object ID within the specified one
    • snmp3_set - Set the value of an SNMP object
    • snmp3_walk - Fetch all the SNMP objects from an agent
    • SNMP::close - Close SNMP session
    • SNMP::get - Fetch an SNMP object
    • SNMP::getErrno - Get last error code
    • SNMP::getError - Get last error message
    • SNMP::getnext - Fetch an SNMP object which follows the given object id
    • SNMP::set - Set the value of an SNMP object
    • SNMP::setSecurity - Configures security-related SNMPv3 session parameters
    • SNMP::walk - Fetch SNMP object subtree
    • SNMP::__construct - Creates SNMP instance representing session to remote SNMP agent
    • snmpget - Fetch an SNMP object
    • snmpgetnext - Fetch the SNMP object which follows the given object id
    • snmprealwalk - Return all objects including their respective object ID within the specified one
    • snmpset - Set the value of an SNMP object
    • snmpwalk - Fetch all the SNMP objects from an agent
    • snmpwalkoid - Query for a tree of information about a network entity
    • snmp_get_quick_print - Fetches the current value of the UCD library's quick_print setting
    • snmp_get_valueretrieval - Return the method how the SNMP values will be returned
    • snmp_read_mib - Reads and parses a MIB file into the active MIB tree
    • snmp_set_enum_print - Return all values that are enums with their enum value instead of the raw integer
    • snmp_set_oid_numeric_print - Set the OID output format
    • snmp_set_oid_output_format - Set the OID output format
    • snmp_set_quick_print - Set the value of quick_print within the UCD SNMP library
    • snmp_set_valueretrieval - Specify the method how the SNMP values will be returned
    • SoapClient::SoapClient - SoapClient constructor
    • SoapClient::__call - Calls a SOAP function (deprecated)
    • SoapClient::__construct - SoapClient constructor
    • SoapClient::__doRequest - Performs a SOAP request
    • SoapClient::__getCookies - Get list of cookies
    • SoapClient::__getFunctions - Returns list of available SOAP functions
    • SoapClient::__getLastRequest - Returns last SOAP request
    • SoapClient::__getLastRequestHeaders - Returns the SOAP headers from the last request
    • SoapClient::__getLastResponse - Returns last SOAP response
    • SoapClient::__getLastResponseHeaders - Returns the SOAP headers from the last response
    • SoapClient::__getTypes - Returns a list of SOAP types
    • SoapClient::__setCookie - The __setCookie purpose
    • SoapClient::__setLocation - Sets the location of the Web service to use
    • SoapClient::__setSoapHeaders - Sets SOAP headers for subsequent calls
    • SoapClient::__soapCall - Calls a SOAP function
    • SoapFault::SoapFault - SoapFault constructor
    • SoapFault::__construct - SoapFault constructor
    • SoapFault::__toString - Obtain a string representation of a SoapFault
    • SoapHeader::SoapHeader - SoapHeader constructor
    • SoapHeader::__construct - SoapHeader constructor
    • SoapParam::SoapParam - SoapParam constructor
    • SoapParam::__construct - SoapParam constructor
    • SoapServer::addFunction - Adds one or more functions to handle SOAP requests
    • SoapServer::addSoapHeader - Add a SOAP header to the response
    • SoapServer::fault - Issue SoapServer fault indicating an error
    • SoapServer::getFunctions - Returns list of defined functions
    • SoapServer::handle - Handles a SOAP request
    • SoapServer::setClass - Sets the class which handles SOAP requests
    • SoapServer::setObject - Sets the object which will be used to handle SOAP requests
    • SoapServer::setPersistence - Sets SoapServer persistence mode
    • SoapServer::SoapServer - SoapServer constructor
    • SoapServer::__construct - SoapServer constructor
    • SoapVar::SoapVar - SoapVar constructor
    • SoapVar::__construct - SoapVar constructor
    • Socket context options - Socket context option listing
    • socket_accept - Accepts a connection on a socket
    • socket_addrinfo_bind - Create and bind to a socket from a given addrinfo
    • socket_addrinfo_connect - Create and connect to a socket from a given addrinfo
    • socket_addrinfo_explain - Get information about addrinfo
    • socket_addrinfo_lookup - Get array with contents of getaddrinfo about the given hostname
    • socket_bind - Binds a name to a socket
    • socket_clear_error - Clears the error on the socket or the last error code
    • socket_close - Closes a socket resource
    • socket_cmsg_space - Calculate message buffer size
    • socket_connect - Initiates a connection on a socket
    • socket_create - Create a socket (endpoint for communication)
    • socket_create_listen - Opens a socket on port to accept connections
    • socket_create_pair - Creates a pair of indistinguishable sockets and stores them in an array
    • socket_export_stream - Export a socket extension resource into a stream that encapsulates a socket
    • socket_getopt - Alias of socket_get_option
    • socket_getpeername - Queries the remote side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
    • socket_getsockname - Queries the local side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
    • socket_get_option - Gets socket options for the socket
    • socket_get_status - Alias of stream_get_meta_data
    • socket_import_stream - Import a stream
    • socket_last_error - Returns the last error on the socket
    • socket_listen - Listens for a connection on a socket
    • socket_read - Reads a maximum of length bytes from a socket
    • socket_recv - Receives data from a connected socket
    • socket_recvfrom - Receives data from a socket whether or not it is connection-oriented
    • socket_recvmsg - Read a message
    • socket_select - Runs the select() system call on the given arrays of sockets with a specified timeout
    • socket_send - Sends data to a connected socket
    • socket_sendmsg - Send a message
    • socket_sendto - Sends a message to a socket, whether it is connected or not
    • socket_setopt - Alias of socket_set_option
    • socket_set_block - Sets blocking mode on a socket resource
    • socket_set_blocking - Alias of stream_set_blocking
    • socket_set_nonblock - Sets nonblocking mode for file descriptor fd
    • socket_set_option - Sets socket options for the socket
    • socket_set_timeout - Alias of stream_set_timeout
    • socket_shutdown - Shuts down a socket for receiving, sending, or both
    • socket_strerror - Return a string describing a socket error
    • socket_write - Write to a socket
    • socket_wsaprotocol_info_export - Exports the WSAPROTOCOL_INFO Structure
    • socket_wsaprotocol_info_import - Imports a Socket from another Process
    • socket_wsaprotocol_info_release - Releases an exported WSAPROTOCOL_INFO Structure
    • sodium_add - Add large numbers
    • sodium_base642bin - Description
    • sodium_bin2base64 - Description
    • sodium_bin2hex - Encode to hexadecimal
    • sodium_compare - Compare large numbers
    • sodium_crypto_aead_aes256gcm_decrypt - Decrypt in combined mode with precalculation
    • sodium_crypto_aead_aes256gcm_encrypt - Encrypt in combined mode with precalculation
    • sodium_crypto_aead_aes256gcm_is_available - Check if hardware supports AES256-GCM
    • sodium_crypto_aead_aes256gcm_keygen - Get random bytes for key
    • sodium_crypto_aead_chacha20poly1305_decrypt - Verify that the ciphertext includes a valid tag
    • sodium_crypto_aead_chacha20poly1305_encrypt - Encrypt a message
    • 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 - Get random bytes for key
    • sodium_crypto_aead_chacha20poly1305_keygen - Get random bytes for key
    • sodium_crypto_aead_xchacha20poly1305_ietf_decrypt - Description
    • sodium_crypto_aead_xchacha20poly1305_ietf_encrypt - Description
    • sodium_crypto_aead_xchacha20poly1305_ietf_keygen - Description
    • sodium_crypto_auth - Compute a tag for the message
    • sodium_crypto_auth_keygen - Get random bytes for key
    • sodium_crypto_auth_verify - Verifies that the tag is valid for the message
    • sodium_crypto_box - Encrypt a message
    • sodium_crypto_box_keypair - Randomly generate a secret key and a corresponding public key
    • sodium_crypto_box_keypair_from_secretkey_and_publickey - Description
    • sodium_crypto_box_open - Verify and decrypt a ciphertext
    • sodium_crypto_box_publickey - Description
    • sodium_crypto_box_publickey_from_secretkey - Description
    • sodium_crypto_box_seal - Encrypt a message
    • sodium_crypto_box_seal_open - Decrypt the ciphertext
    • sodium_crypto_box_secretkey - Description
    • sodium_crypto_box_seed_keypair - Deterministically derive the key pair from a single key
    • sodium_crypto_generichash - Get a hash of the message
    • sodium_crypto_generichash_final - Complete the hash
    • sodium_crypto_generichash_init - Initialize a hash
    • sodium_crypto_generichash_keygen - Get random bytes for key
    • sodium_crypto_generichash_update - Add message to a hash
    • sodium_crypto_kdf_derive_from_key - Derive a subkey
    • sodium_crypto_kdf_keygen - Get random bytes for key
    • sodium_crypto_kx_client_session_keys - Description
    • sodium_crypto_kx_keypair - Creates a new sodium keypair
    • sodium_crypto_kx_publickey - Description
    • sodium_crypto_kx_secretkey - Description
    • sodium_crypto_kx_seed_keypair - Description
    • sodium_crypto_kx_server_session_keys - Description
    • sodium_crypto_pwhash - Derive a key from a password
    • sodium_crypto_pwhash_scryptsalsa208sha256 - Derives a key from a password
    • 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 - Description
    • 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_secretbox - Encrypt a message
    • sodium_crypto_secretbox_keygen - Get random bytes for key
    • sodium_crypto_secretbox_open - Verify and decrypt a ciphertext
    • sodium_crypto_secretstream_xchacha20poly1305_init_pull - Description
    • sodium_crypto_secretstream_xchacha20poly1305_init_push - Description
    • sodium_crypto_secretstream_xchacha20poly1305_keygen - Description
    • sodium_crypto_secretstream_xchacha20poly1305_pull - Description
    • sodium_crypto_secretstream_xchacha20poly1305_push - Description
    • sodium_crypto_secretstream_xchacha20poly1305_rekey - Description
    • sodium_crypto_shorthash - Compute a fixed-size fingerprint for the message
    • 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 - Description
    • sodium_crypto_sign_open - Check that the signed message has a valid signature
    • sodium_crypto_sign_publickey - Description
    • sodium_crypto_sign_publickey_from_secretkey - Extract the public key from the secret key
    • sodium_crypto_sign_secretkey - Description
    • 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 - Get random bytes for key
    • sodium_crypto_stream_xor - Encrypt a message
    • sodium_hex2bin - Decodes a hexadecimally encoded binary string
    • sodium_increment - Increment large number
    • sodium_memcmp - Test for equality in constant-time
    • sodium_memzero - Overwrite buf with zeros
    • sodium_pad - Add padding data
    • sodium_unpad - Remove padding data
    • SolrClient::addDocument - Adds a document to the index
    • SolrClient::addDocuments - Adds a collection of SolrInputDocument instances to the index
    • SolrClient::commit - Finalizes all add/deletes made to the index
    • SolrClient::deleteById - Delete by Id
    • SolrClient::deleteByIds - Deletes by Ids
    • SolrClient::deleteByQueries - Removes all documents matching any of the queries
    • SolrClient::deleteByQuery - Deletes all documents matching the given query
    • SolrClient::getById - Get Document By Id. Utilizes Solr Realtime Get (RTG)
    • SolrClient::getByIds - Get Documents by their Ids. Utilizes Solr Realtime Get (RTG)
    • SolrClient::getDebug - Returns the debug data for the last connection attempt
    • SolrClient::getOptions - Returns the client options set internally
    • SolrClient::optimize - Defragments the index
    • SolrClient::ping - Checks if Solr server is still up
    • SolrClient::query - Sends a query to the server
    • SolrClient::request - Sends a raw update request
    • SolrClient::rollback - Rollbacks all add/deletes made to the index since the last commit
    • SolrClient::setResponseWriter - Sets the response writer used to prepare the response from Solr
    • SolrClient::setServlet - Changes the specified servlet type to a new value
    • SolrClient::system - Retrieve Solr Server information
    • SolrClient::threads - Checks the threads status
    • SolrClient::__construct - Constructor for the SolrClient object
    • SolrClient::__destruct - Destructor for SolrClient
    • SolrClientException::getInternalInfo - Returns internal information where the Exception was thrown
    • SolrCollapseFunction::getField - Returns the field that is being collapsed on
    • SolrCollapseFunction::getHint - Returns collapse hint
    • SolrCollapseFunction::getMax - Returns max parameter
    • SolrCollapseFunction::getMin - Returns min parameter
    • SolrCollapseFunction::getNullPolicy - Returns null policy
    • SolrCollapseFunction::getSize - Returns size parameter
    • SolrCollapseFunction::setField - Sets the field to collapse on
    • SolrCollapseFunction::setHint - Sets collapse hint
    • SolrCollapseFunction::setMax - Selects the group heads by the max value of a numeric field or function query
    • SolrCollapseFunction::setMin - Sets the initial size of the collapse data structures when collapsing on a numeric field only
    • SolrCollapseFunction::setNullPolicy - Sets the NULL Policy
    • SolrCollapseFunction::setSize - Sets the initial size of the collapse data structures when collapsing on a numeric field only
    • SolrCollapseFunction::__construct - Constructor
    • SolrCollapseFunction::__toString - Returns a string representing the constructed collapse function
    • SolrDisMaxQuery::addBigramPhraseField - Adds a Phrase Bigram Field (pf2 parameter)
    • SolrDisMaxQuery::addBoostQuery - Adds a boost query field with value and optional boost (bq parameter)
    • SolrDisMaxQuery::addPhraseField - Adds a Phrase Field (pf parameter)
    • SolrDisMaxQuery::addQueryField - Add a query field with optional boost (qf parameter)
    • SolrDisMaxQuery::addTrigramPhraseField - Adds a Trigram Phrase Field (pf3 parameter)
    • SolrDisMaxQuery::addUserField - Adds a field to User Fields Parameter (uf)
    • SolrDisMaxQuery::removeBigramPhraseField - Removes phrase bigram field (pf2 parameter)
    • SolrDisMaxQuery::removeBoostQuery - Removes a boost query partial by field name (bq)
    • SolrDisMaxQuery::removePhraseField - Removes a Phrase Field (pf parameter)
    • SolrDisMaxQuery::removeQueryField - Removes a Query Field (qf parameter)
    • SolrDisMaxQuery::removeTrigramPhraseField - Removes a Trigram Phrase Field (pf3 parameter)
    • SolrDisMaxQuery::removeUserField - Removes a field from The User Fields Parameter (uf)
    • SolrDisMaxQuery::setBigramPhraseFields - Sets Bigram Phrase Fields and their boosts (and slops) using pf2 parameter
    • SolrDisMaxQuery::setBigramPhraseSlop - Sets Bigram Phrase Slop (ps2 parameter)
    • SolrDisMaxQuery::setBoostFunction - Sets a Boost Function (bf parameter)
    • SolrDisMaxQuery::setBoostQuery - Directly Sets Boost Query Parameter (bq)
    • SolrDisMaxQuery::setMinimumMatch - Set Minimum "Should" Match (mm)
    • SolrDisMaxQuery::setPhraseFields - Sets Phrase Fields and their boosts (and slops) using pf2 parameter
    • SolrDisMaxQuery::setPhraseSlop - Sets the default slop on phrase queries (ps parameter)
    • SolrDisMaxQuery::setQueryAlt - Set Query Alternate (q.alt parameter)
    • SolrDisMaxQuery::setQueryPhraseSlop - Specifies the amount of slop permitted on phrase queries explicitly included in the user's query string (qf parameter)
    • SolrDisMaxQuery::setTieBreaker - Sets Tie Breaker parameter (tie parameter)
    • SolrDisMaxQuery::setTrigramPhraseFields - Directly Sets Trigram Phrase Fields (pf3 parameter)
    • SolrDisMaxQuery::setTrigramPhraseSlop - Sets Trigram Phrase Slop (ps3 parameter)
    • SolrDisMaxQuery::setUserFields - Sets User Fields parameter (uf)
    • SolrDisMaxQuery::useDisMaxQueryParser - Switch QueryParser to be DisMax Query Parser
    • SolrDisMaxQuery::useEDisMaxQueryParser - Switch QueryParser to be EDisMax
    • SolrDisMaxQuery::__construct - Class Constructor
    • SolrDocument::addField - Adds a field to the document
    • SolrDocument::clear - Drops all the fields in the document
    • SolrDocument::current - Retrieves the current field
    • SolrDocument::deleteField - Removes a field from the document
    • SolrDocument::fieldExists - Checks if a field exists in the document
    • SolrDocument::getChildDocuments - Returns an array of child documents (SolrDocument)
    • SolrDocument::getChildDocumentsCount - Returns the number of child documents
    • SolrDocument::getField - Retrieves a field by name
    • SolrDocument::getFieldCount - Returns the number of fields in this document
    • SolrDocument::getFieldNames - Returns an array of fields names in the document
    • SolrDocument::getInputDocument - Returns a SolrInputDocument equivalent of the object
    • SolrDocument::hasChildDocuments - Checks whether the document has any child documents
    • SolrDocument::key - Retrieves the current key
    • SolrDocument::merge - Merges source to the current SolrDocument
    • SolrDocument::next - Moves the internal pointer to the next field
    • SolrDocument::offsetExists - Checks if a particular field exists
    • SolrDocument::offsetGet - Retrieves a field
    • SolrDocument::offsetSet - Adds a field to the document
    • SolrDocument::offsetUnset - Removes a field
    • SolrDocument::reset - This is an alias to SolrDocument::clear()
    • SolrDocument::rewind - Resets the internal pointer to the beginning
    • SolrDocument::serialize - Used for custom serialization
    • SolrDocument::sort - Sorts the fields in the document
    • SolrDocument::toArray - Returns an array representation of the document
    • SolrDocument::unserialize - Custom serialization of SolrDocument objects
    • SolrDocument::valid - Checks if the current position internally is still valid
    • SolrDocument::__clone - Creates a copy of a SolrDocument object
    • SolrDocument::__construct - Constructor
    • SolrDocument::__destruct - Destructor
    • SolrDocument::__get - Access the field as a property
    • SolrDocument::__isset - Checks if a field exists
    • SolrDocument::__set - Adds another field to the document
    • SolrDocument::__unset - Removes a field from the document
    • SolrDocumentField::__construct - Constructor
    • SolrDocumentField::__destruct - Destructor
    • SolrException::getInternalInfo - Returns internal information where the Exception was thrown
    • SolrGenericResponse::__construct - Constructor
    • SolrGenericResponse::__destruct - Destructor
    • SolrIllegalArgumentException::getInternalInfo - Returns internal information where the Exception was thrown
    • SolrIllegalOperationException::getInternalInfo - Returns internal information where the Exception was thrown
    • SolrInputDocument::addChildDocument - Adds a child document for block indexing
    • SolrInputDocument::addChildDocuments - Adds an array of child documents
    • SolrInputDocument::addField - Adds a field to the document
    • SolrInputDocument::clear - Resets the input document
    • SolrInputDocument::deleteField - Removes a field from the document
    • SolrInputDocument::fieldExists - Checks if a field exists
    • SolrInputDocument::getBoost - Retrieves the current boost value for the document
    • SolrInputDocument::getChildDocuments - Returns an array of child documents (SolrInputDocument)
    • SolrInputDocument::getChildDocumentsCount - Returns the number of child documents
    • SolrInputDocument::getField - Retrieves a field by name
    • SolrInputDocument::getFieldBoost - Retrieves the boost value for a particular field
    • SolrInputDocument::getFieldCount - Returns the number of fields in the document
    • SolrInputDocument::getFieldNames - Returns an array containing all the fields in the document
    • SolrInputDocument::hasChildDocuments - Returns true if the document has any child documents
    • SolrInputDocument::merge - Merges one input document into another
    • SolrInputDocument::reset - This is an alias of SolrInputDocument::clear
    • SolrInputDocument::setBoost - Sets the boost value for this document
    • SolrInputDocument::setFieldBoost - Sets the index-time boost value for a field
    • SolrInputDocument::sort - Sorts the fields within the document
    • SolrInputDocument::toArray - Returns an array representation of the input document
    • SolrInputDocument::__clone - Creates a copy of a SolrDocument
    • SolrInputDocument::__construct - Constructor
    • SolrInputDocument::__destruct - Destructor
    • SolrModifiableParams::__construct - Constructor
    • SolrModifiableParams::__destruct - Destructor
    • SolrObject::getPropertyNames - Returns an array of all the names of the properties
    • SolrObject::offsetExists - Checks if the property exists
    • SolrObject::offsetGet - Used to retrieve a property
    • SolrObject::offsetSet - Sets the value for a property
    • SolrObject::offsetUnset - Unsets the value for the property
    • SolrObject::__construct - Creates Solr object
    • SolrObject::__destruct - Destructor
    • SolrParams::add - This is an alias for SolrParams::addParam
    • SolrParams::addParam - Adds a parameter to the object
    • SolrParams::get - This is an alias for SolrParams::getParam
    • SolrParams::getParam - Returns a parameter value
    • SolrParams::getParams - Returns an array of non URL-encoded parameters
    • SolrParams::getPreparedParams - Returns an array of URL-encoded parameters
    • SolrParams::serialize - Used for custom serialization
    • SolrParams::set - An alias of SolrParams::setParam
    • SolrParams::setParam - Sets the parameter to the specified value
    • SolrParams::toString - Returns all the name-value pair parameters in the object
    • SolrParams::unserialize - Used for custom serialization
    • SolrPingResponse::getResponse - Returns the response from the server
    • SolrPingResponse::__construct - Constructor
    • SolrPingResponse::__destruct - Destructor
    • SolrQuery::addExpandFilterQuery - Overrides main filter query, determines which documents to include in the main group
    • SolrQuery::addExpandSortField - Orders the documents within the expanded groups (expand.sort parameter)
    • SolrQuery::addFacetDateField - Maps to facet.date
    • SolrQuery::addFacetDateOther - Adds another facet.date.other parameter
    • SolrQuery::addFacetField - Adds another field to the facet
    • SolrQuery::addFacetQuery - Adds a facet query
    • SolrQuery::addField - Specifies which fields to return in the result
    • SolrQuery::addFilterQuery - Specifies a filter query
    • SolrQuery::addGroupField - Add a field to be used to group results
    • SolrQuery::addGroupFunction - Allows grouping results based on the unique values of a function query (group.func parameter)
    • SolrQuery::addGroupQuery - Allows grouping of documents that match the given query
    • SolrQuery::addGroupSortField - Add a group sort field (group.sort parameter)
    • SolrQuery::addHighlightField - Maps to hl.fl
    • SolrQuery::addMltField - Sets a field to use for similarity
    • SolrQuery::addMltQueryField - Maps to mlt.qf
    • SolrQuery::addSortField - Used to control how the results should be sorted
    • SolrQuery::addStatsFacet - Requests a return of sub results for values within the given facet
    • SolrQuery::addStatsField - Maps to stats.field parameter
    • SolrQuery::collapse - Collapses the result set to a single document per group
    • SolrQuery::getExpand - Returns true if group expanding is enabled
    • SolrQuery::getExpandFilterQueries - Returns the expand filter queries
    • SolrQuery::getExpandQuery - Returns the expand query expand.q parameter
    • SolrQuery::getExpandRows - Returns The number of rows to display in each group (expand.rows)
    • SolrQuery::getExpandSortFields - Returns an array of fields
    • SolrQuery::getFacet - Returns the value of the facet parameter
    • SolrQuery::getFacetDateEnd - Returns the value for the facet.date.end parameter
    • SolrQuery::getFacetDateFields - Returns all the facet.date fields
    • SolrQuery::getFacetDateGap - Returns the value of the facet.date.gap parameter
    • SolrQuery::getFacetDateHardEnd - Returns the value of the facet.date.hardend parameter
    • SolrQuery::getFacetDateOther - Returns the value for the facet.date.other parameter
    • SolrQuery::getFacetDateStart - Returns the lower bound for the first date range for all date faceting on this field
    • SolrQuery::getFacetFields - Returns all the facet fields
    • SolrQuery::getFacetLimit - Returns the maximum number of constraint counts that should be returned for the facet fields
    • SolrQuery::getFacetMethod - Returns the value of the facet.method parameter
    • SolrQuery::getFacetMinCount - Returns the minimum counts for facet fields should be included in the response
    • SolrQuery::getFacetMissing - Returns the current state of the facet.missing parameter
    • SolrQuery::getFacetOffset - Returns an offset into the list of constraints to be used for pagination
    • SolrQuery::getFacetPrefix - Returns the facet prefix
    • SolrQuery::getFacetQueries - Returns all the facet queries
    • SolrQuery::getFacetSort - Returns the facet sort type
    • SolrQuery::getFields - Returns the list of fields that will be returned in the response
    • SolrQuery::getFilterQueries - Returns an array of filter queries
    • SolrQuery::getGroup - Returns true if grouping is enabled
    • SolrQuery::getGroupCachePercent - Returns group cache percent value
    • SolrQuery::getGroupFacet - Returns the group.facet parameter value
    • SolrQuery::getGroupFields - Returns group fields (group.field parameter values)
    • SolrQuery::getGroupFormat - Returns the group.format value
    • SolrQuery::getGroupFunctions - Returns group functions (group.func parameter values)
    • SolrQuery::getGroupLimit - Returns the group.limit value
    • SolrQuery::getGroupMain - Returns the group.main value
    • SolrQuery::getGroupNGroups - Returns the group.ngroups value
    • SolrQuery::getGroupOffset - Returns the group.offset value
    • SolrQuery::getGroupQueries - Returns all the group.query parameter values
    • SolrQuery::getGroupSortFields - Returns the group.sort value
    • SolrQuery::getGroupTruncate - Returns the group.truncate value
    • SolrQuery::getHighlight - Returns the state of the hl parameter
    • SolrQuery::getHighlightAlternateField - Returns the highlight field to use as backup or default
    • SolrQuery::getHighlightFields - Returns all the fields that Solr should generate highlighted snippets for
    • SolrQuery::getHighlightFormatter - Returns the formatter for the highlighted output
    • SolrQuery::getHighlightFragmenter - Returns the text snippet generator for highlighted text
    • SolrQuery::getHighlightFragsize - Returns the number of characters of fragments to consider for highlighting
    • SolrQuery::getHighlightHighlightMultiTerm - Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries
    • SolrQuery::getHighlightMaxAlternateFieldLength - Returns the maximum number of characters of the field to return
    • SolrQuery::getHighlightMaxAnalyzedChars - Returns the maximum number of characters into a document to look for suitable snippets
    • SolrQuery::getHighlightMergeContiguous - Returns whether or not the collapse contiguous fragments into a single fragment
    • SolrQuery::getHighlightRegexMaxAnalyzedChars - Returns the maximum number of characters from a field when using the regex fragmenter
    • SolrQuery::getHighlightRegexPattern - Returns the regular expression for fragmenting
    • SolrQuery::getHighlightRegexSlop - Returns the deviation factor from the ideal fragment size
    • SolrQuery::getHighlightRequireFieldMatch - Returns if a field will only be highlighted if the query matched in this particular field
    • SolrQuery::getHighlightSimplePost - Returns the text which appears after a highlighted term
    • SolrQuery::getHighlightSimplePre - Returns the text which appears before a highlighted term
    • SolrQuery::getHighlightSnippets - Returns the maximum number of highlighted snippets to generate per field
    • SolrQuery::getHighlightUsePhraseHighlighter - Returns the state of the hl.usePhraseHighlighter parameter
    • SolrQuery::getMlt - Returns whether or not MoreLikeThis results should be enabled
    • SolrQuery::getMltBoost - Returns whether or not the query will be boosted by the interesting term relevance
    • SolrQuery::getMltCount - Returns the number of similar documents to return for each result
    • SolrQuery::getMltFields - Returns all the fields to use for similarity
    • SolrQuery::getMltMaxNumQueryTerms - Returns the maximum number of query terms that will be included in any generated query
    • SolrQuery::getMltMaxNumTokens - Returns the maximum number of tokens to parse in each document field that is not stored with TermVector support
    • SolrQuery::getMltMaxWordLength - Returns the maximum word length above which words will be ignored
    • SolrQuery::getMltMinDocFrequency - Returns the treshold frequency at which words will be ignored which do not occur in at least this many docs
    • SolrQuery::getMltMinTermFrequency - Returns the frequency below which terms will be ignored in the source document
    • SolrQuery::getMltMinWordLength - Returns the minimum word length below which words will be ignored
    • SolrQuery::getMltQueryFields - Returns the query fields and their boosts
    • SolrQuery::getQuery - Returns the main query
    • SolrQuery::getRows - Returns the maximum number of documents
    • SolrQuery::getSortFields - Returns all the sort fields
    • SolrQuery::getStart - Returns the offset in the complete result set
    • SolrQuery::getStats - Returns whether or not stats is enabled
    • SolrQuery::getStatsFacets - Returns all the stats facets that were set
    • SolrQuery::getStatsFields - Returns all the statistics fields
    • SolrQuery::getTerms - Returns whether or not the TermsComponent is enabled
    • SolrQuery::getTermsField - Returns the field from which the terms are retrieved
    • SolrQuery::getTermsIncludeLowerBound - Returns whether or not to include the lower bound in the result set
    • SolrQuery::getTermsIncludeUpperBound - Returns whether or not to include the upper bound term in the result set
    • SolrQuery::getTermsLimit - Returns the maximum number of terms Solr should return
    • SolrQuery::getTermsLowerBound - Returns the term to start at
    • SolrQuery::getTermsMaxCount - Returns the maximum document frequency
    • SolrQuery::getTermsMinCount - Returns the minimum document frequency to return in order to be included
    • SolrQuery::getTermsPrefix - Returns the term prefix
    • SolrQuery::getTermsReturnRaw - Whether or not to return raw characters
    • SolrQuery::getTermsSort - Returns an integer indicating how terms are sorted
    • SolrQuery::getTermsUpperBound - Returns the term to stop at
    • SolrQuery::getTimeAllowed - Returns the time in milliseconds allowed for the query to finish
    • SolrQuery::removeExpandFilterQuery - Removes an expand filter query
    • SolrQuery::removeExpandSortField - Removes an expand sort field from the expand.sort parameter
    • SolrQuery::removeFacetDateField - Removes one of the facet date fields
    • SolrQuery::removeFacetDateOther - Removes one of the facet.date.other parameters
    • SolrQuery::removeFacetField - Removes one of the facet.date parameters
    • SolrQuery::removeFacetQuery - Removes one of the facet.query parameters
    • SolrQuery::removeField - Removes a field from the list of fields
    • SolrQuery::removeFilterQuery - Removes a filter query
    • SolrQuery::removeHighlightField - Removes one of the fields used for highlighting
    • SolrQuery::removeMltField - Removes one of the moreLikeThis fields
    • SolrQuery::removeMltQueryField - Removes one of the moreLikeThis query fields
    • SolrQuery::removeSortField - Removes one of the sort fields
    • SolrQuery::removeStatsFacet - Removes one of the stats.facet parameters
    • SolrQuery::removeStatsField - Removes one of the stats.field parameters
    • SolrQuery::setEchoHandler - Toggles the echoHandler parameter
    • SolrQuery::setEchoParams - Determines what kind of parameters to include in the response
    • SolrQuery::setExpand - Enables/Disables the Expand Component
    • SolrQuery::setExpandQuery - Sets the expand.q parameter
    • SolrQuery::setExpandRows - Sets the number of rows to display in each group (expand.rows). Server Default 5
    • SolrQuery::setExplainOther - Sets the explainOther common query parameter
    • SolrQuery::setFacet - Maps to the facet parameter. Enables or disables facetting
    • SolrQuery::setFacetDateEnd - Maps to facet.date.end
    • SolrQuery::setFacetDateGap - Maps to facet.date.gap
    • SolrQuery::setFacetDateHardEnd - Maps to facet.date.hardend
    • SolrQuery::setFacetDateStart - Maps to facet.date.start
    • SolrQuery::setFacetEnumCacheMinDefaultFrequency - Sets the minimum document frequency used for determining term count
    • SolrQuery::setFacetLimit - Maps to facet.limit
    • SolrQuery::setFacetMethod - Specifies the type of algorithm to use when faceting a field
    • SolrQuery::setFacetMinCount - Maps to facet.mincount
    • SolrQuery::setFacetMissing - Maps to facet.missing
    • SolrQuery::setFacetOffset - Sets the offset into the list of constraints to allow for pagination
    • SolrQuery::setFacetPrefix - Specifies a string prefix with which to limits the terms on which to facet
    • SolrQuery::setFacetSort - Determines the ordering of the facet field constraints
    • SolrQuery::setGroup - Enable/Disable result grouping (group parameter)
    • SolrQuery::setGroupCachePercent - Enables caching for result grouping
    • SolrQuery::setGroupFacet - Sets group.facet parameter
    • SolrQuery::setGroupFormat - Sets the group format, result structure (group.format parameter)
    • SolrQuery::setGroupLimit - Specifies the number of results to return for each group. The server default value is 1
    • SolrQuery::setGroupMain - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
    • SolrQuery::setGroupNGroups - If true, Solr includes the number of groups that have matched the query in the results
    • SolrQuery::setGroupOffset - Sets the group.offset parameter
    • SolrQuery::setGroupTruncate - If true, facet counts are based on the most relevant document of each group matching the query
    • SolrQuery::setHighlight - Enables or disables highlighting
    • SolrQuery::setHighlightAlternateField - Specifies the backup field to use
    • SolrQuery::setHighlightFormatter - Specify a formatter for the highlight output
    • SolrQuery::setHighlightFragmenter - Sets a text snippet generator for highlighted text
    • SolrQuery::setHighlightFragsize - The size of fragments to consider for highlighting
    • SolrQuery::setHighlightHighlightMultiTerm - Use SpanScorer to highlight phrase terms
    • SolrQuery::setHighlightMaxAlternateFieldLength - Sets the maximum number of characters of the field to return
    • SolrQuery::setHighlightMaxAnalyzedChars - Specifies the number of characters into a document to look for suitable snippets
    • SolrQuery::setHighlightMergeContiguous - Whether or not to collapse contiguous fragments into a single fragment
    • SolrQuery::setHighlightRegexMaxAnalyzedChars - Specify the maximum number of characters to analyze
    • SolrQuery::setHighlightRegexPattern - Specify the regular expression for fragmenting
    • SolrQuery::setHighlightRegexSlop - Sets the factor by which the regex fragmenter can stray from the ideal fragment size
    • SolrQuery::setHighlightRequireFieldMatch - Require field matching during highlighting
    • SolrQuery::setHighlightSimplePost - Sets the text which appears after a highlighted term
    • SolrQuery::setHighlightSimplePre - Sets the text which appears before a highlighted term
    • SolrQuery::setHighlightSnippets - Sets the maximum number of highlighted snippets to generate per field
    • SolrQuery::setHighlightUsePhraseHighlighter - Whether to highlight phrase terms only when they appear within the query phrase
    • SolrQuery::setMlt - Enables or disables moreLikeThis
    • SolrQuery::setMltBoost - Set if the query will be boosted by the interesting term relevance
    • SolrQuery::setMltCount - Set the number of similar documents to return for each result
    • SolrQuery::setMltMaxNumQueryTerms - Sets the maximum number of query terms included
    • SolrQuery::setMltMaxNumTokens - Specifies the maximum number of tokens to parse
    • SolrQuery::setMltMaxWordLength - Sets the maximum word length
    • SolrQuery::setMltMinDocFrequency - Sets the mltMinDoc frequency
    • SolrQuery::setMltMinTermFrequency - Sets the frequency below which terms will be ignored in the source docs
    • SolrQuery::setMltMinWordLength - Sets the minimum word length
    • SolrQuery::setOmitHeader - Exclude the header from the returned results
    • SolrQuery::setQuery - Sets the search query
    • SolrQuery::setRows - Specifies the maximum number of rows to return in the result
    • SolrQuery::setShowDebugInfo - Flag to show debug information
    • SolrQuery::setStart - Specifies the number of rows to skip
    • SolrQuery::setStats - Enables or disables the Stats component
    • SolrQuery::setTerms - Enables or disables the TermsComponent
    • SolrQuery::setTermsField - Sets the name of the field to get the Terms from
    • SolrQuery::setTermsIncludeLowerBound - Include the lower bound term in the result set
    • SolrQuery::setTermsIncludeUpperBound - Include the upper bound term in the result set
    • SolrQuery::setTermsLimit - Sets the maximum number of terms to return
    • SolrQuery::setTermsLowerBound - Specifies the Term to start from
    • SolrQuery::setTermsMaxCount - Sets the maximum document frequency
    • SolrQuery::setTermsMinCount - Sets the minimum document frequency
    • SolrQuery::setTermsPrefix - Restrict matches to terms that start with the prefix
    • SolrQuery::setTermsReturnRaw - Return the raw characters of the indexed term
    • SolrQuery::setTermsSort - Specifies how to sort the returned terms
    • SolrQuery::setTermsUpperBound - Sets the term to stop at
    • SolrQuery::setTimeAllowed - The time allowed for search to finish
    • SolrQuery::__construct - Constructor
    • SolrQuery::__destruct - Destructor
    • SolrQueryResponse::__construct - Constructor
    • SolrQueryResponse::__destruct - Destructor
    • SolrResponse::getDigestedResponse - Returns the XML response as serialized PHP data
    • SolrResponse::getHttpStatus - Returns the HTTP status of the response
    • SolrResponse::getHttpStatusMessage - Returns more details on the HTTP status
    • SolrResponse::getRawRequest - Returns the raw request sent to the Solr server
    • SolrResponse::getRawRequestHeaders - Returns the raw request headers sent to the Solr server
    • SolrResponse::getRawResponse - Returns the raw response from the server
    • SolrResponse::getRawResponseHeaders - Returns the raw response headers from the server
    • SolrResponse::getRequestUrl - Returns the full URL the request was sent to
    • SolrResponse::getResponse - Returns a SolrObject representing the XML response from the server
    • SolrResponse::setParseMode - Sets the parse mode
    • SolrResponse::success - Was the request a success
    • SolrServerException::getInternalInfo - Returns internal information where the Exception was thrown
    • SolrUpdateResponse::__construct - Constructor
    • SolrUpdateResponse::__destruct - Destructor
    • SolrUtils::digestXmlResponse - Parses an response XML string into a SolrObject
    • SolrUtils::escapeQueryChars - Escapes a lucene query string
    • SolrUtils::getSolrVersion - Returns the current version of the Solr extension
    • SolrUtils::queryPhrase - Prepares a phrase from an unescaped lucene string
    • solr_get_version - Returns the current version of the Apache Solr extension
    • sort - Sort an array
    • soundex - Calculate the soundex key of a string
    • SphinxClient::addQuery - Add query to multi-query batch
    • SphinxClient::buildExcerpts - Build text snippets
    • SphinxClient::buildKeywords - Extract keywords from query
    • SphinxClient::close - Closes previously opened persistent connection
    • SphinxClient::escapeString - Escape special characters
    • SphinxClient::getLastError - Get the last error message
    • SphinxClient::getLastWarning - Get the last warning
    • SphinxClient::open - Opens persistent connection to the server
    • SphinxClient::query - Execute search query
    • SphinxClient::resetFilters - Clear all filters
    • SphinxClient::resetGroupBy - Clear all group-by settings
    • SphinxClient::runQueries - Run a batch of search queries
    • SphinxClient::setArrayResult - Change the format of result set array
    • SphinxClient::setConnectTimeout - Set connection timeout
    • SphinxClient::setFieldWeights - Set field weights
    • SphinxClient::setFilter - Add new integer values set filter
    • SphinxClient::setFilterFloatRange - Add new float range filter
    • SphinxClient::setFilterRange - Add new integer range filter
    • SphinxClient::setGeoAnchor - Set anchor point for a geosphere distance calculations
    • SphinxClient::setGroupBy - Set grouping attribute
    • SphinxClient::setGroupDistinct - Set attribute name for per-group distinct values count calculations
    • SphinxClient::setIDRange - Set a range of accepted document IDs
    • SphinxClient::setIndexWeights - Set per-index weights
    • SphinxClient::setLimits - Set offset and limit of the result set
    • SphinxClient::setMatchMode - Set full-text query matching mode
    • SphinxClient::setMaxQueryTime - Set maximum query time
    • SphinxClient::setOverride - Sets temporary per-document attribute value overrides
    • SphinxClient::setRankingMode - Set ranking mode
    • SphinxClient::setRetries - Set retry count and delay
    • SphinxClient::setSelect - Set select clause
    • SphinxClient::setServer - Set searchd host and port
    • SphinxClient::setSortMode - Set matches sorting mode
    • SphinxClient::status - Queries searchd status
    • SphinxClient::updateAttributes - Update document attributes
    • SphinxClient::__construct - Create a new SphinxClient object
    • SplDoublyLinkedList::add - Add/insert a new value at the specified index
    • SplDoublyLinkedList::bottom - Peeks at the node from the beginning of the doubly linked list
    • SplDoublyLinkedList::count - Counts the number of elements in the doubly linked list
    • SplDoublyLinkedList::current - Return current array entry
    • SplDoublyLinkedList::getIteratorMode - Returns the mode of iteration
    • SplDoublyLinkedList::isEmpty - Checks whether the doubly linked list is empty
    • SplDoublyLinkedList::key - Return current node index
    • SplDoublyLinkedList::next - Move to next entry
    • SplDoublyLinkedList::offsetExists - Returns whether the requested $index exists
    • SplDoublyLinkedList::offsetGet - Returns the value at the specified $index
    • SplDoublyLinkedList::offsetSet - Sets the value at the specified $index to $newval
    • SplDoublyLinkedList::offsetUnset - Unsets the value at the specified $index
    • SplDoublyLinkedList::pop - Pops a node from the end of the doubly linked list
    • SplDoublyLinkedList::prev - Move to previous entry
    • SplDoublyLinkedList::push - Pushes an element at the end of the doubly linked list
    • SplDoublyLinkedList::rewind - Rewind iterator back to the start
    • SplDoublyLinkedList::serialize - Serializes the storage
    • SplDoublyLinkedList::setIteratorMode - Sets the mode of iteration
    • SplDoublyLinkedList::shift - Shifts a node from the beginning of the doubly linked list
    • SplDoublyLinkedList::top - Peeks at the node from the end of the doubly linked list
    • SplDoublyLinkedList::unserialize - Unserializes the storage
    • SplDoublyLinkedList::unshift - Prepends the doubly linked list with an element
    • SplDoublyLinkedList::valid - Check whether the doubly linked list contains more nodes
    • SplDoublyLinkedList::__construct - Constructs a new doubly linked list
    • SplEnum::getConstList - Returns all consts (possible values) as an array
    • SplFileInfo::getATime - Gets last access time of the file
    • SplFileInfo::getBasename - Gets the base name of the file
    • SplFileInfo::getCTime - Gets the inode change time
    • SplFileInfo::getExtension - Gets the file extension
    • SplFileInfo::getFileInfo - Gets an SplFileInfo object for the file
    • SplFileInfo::getFilename - Gets the filename
    • SplFileInfo::getGroup - Gets the file group
    • SplFileInfo::getInode - Gets the inode for the file
    • SplFileInfo::getLinkTarget - Gets the target of a link
    • SplFileInfo::getMTime - Gets the last modified time
    • SplFileInfo::getOwner - Gets the owner of the file
    • SplFileInfo::getPath - Gets the path without filename
    • SplFileInfo::getPathInfo - Gets an SplFileInfo object for the path
    • SplFileInfo::getPathname - Gets the path to the file
    • SplFileInfo::getPerms - Gets file permissions
    • SplFileInfo::getRealPath - Gets absolute path to file
    • SplFileInfo::getSize - Gets file size
    • SplFileInfo::getType - Gets file type
    • SplFileInfo::isDir - Tells if the file is a directory
    • SplFileInfo::isExecutable - Tells if the file is executable
    • SplFileInfo::isFile - Tells if the object references a regular file
    • SplFileInfo::isLink - Tells if the file is a link
    • SplFileInfo::isReadable - Tells if file is readable
    • SplFileInfo::isWritable - Tells if the entry is writable
    • SplFileInfo::openFile - Gets an SplFileObject object for the file
    • SplFileInfo::setFileClass - Sets the class used with SplFileInfo::openFile
    • SplFileInfo::setInfoClass - Sets the class used with SplFileInfo::getFileInfo and SplFileInfo::getPathInfo
    • SplFileInfo::__construct - Construct a new SplFileInfo object
    • SplFileInfo::__toString - Returns the path to the file as a string
    • SplFileObject::current - Retrieve current line of file
    • SplFileObject::eof - Reached end of file
    • SplFileObject::fflush - Flushes the output to the file
    • SplFileObject::fgetc - Gets character from file
    • SplFileObject::fgetcsv - Gets line from file and parse as CSV fields
    • SplFileObject::fgets - Gets line from file
    • SplFileObject::fgetss - Gets line from file and strip HTML tags
    • SplFileObject::flock - Portable file locking
    • SplFileObject::fpassthru - Output all remaining data on a file pointer
    • SplFileObject::fputcsv - Write a field array as a CSV line
    • SplFileObject::fread - Read from file
    • SplFileObject::fscanf - Parses input from file according to a format
    • SplFileObject::fseek - Seek to a position
    • SplFileObject::fstat - Gets information about the file
    • SplFileObject::ftell - Return current file position
    • SplFileObject::ftruncate - Truncates the file to a given length
    • SplFileObject::fwrite - Write to file
    • SplFileObject::getChildren - No purpose
    • SplFileObject::getCsvControl - Get the delimiter, enclosure and escape character for CSV
    • SplFileObject::getCurrentLine - Alias of SplFileObject::fgets
    • SplFileObject::getFlags - Gets flags for the SplFileObject
    • SplFileObject::getMaxLineLen - Get maximum line length
    • SplFileObject::hasChildren - SplFileObject does not have children
    • SplFileObject::key - Get line number
    • SplFileObject::next - Read next line
    • SplFileObject::rewind - Rewind the file to the first line
    • SplFileObject::seek - Seek to specified line
    • SplFileObject::setCsvControl - Set the delimiter, enclosure and escape character for CSV
    • SplFileObject::setFlags - Sets flags for the SplFileObject
    • SplFileObject::setMaxLineLen - Set maximum line length
    • SplFileObject::valid - Not at EOF
    • SplFileObject::__construct - Construct a new file object
    • SplFileObject::__toString - Alias of SplFileObject::fgets
    • SplFixedArray::count - Returns the size of the array
    • SplFixedArray::current - Return current array entry
    • SplFixedArray::fromArray - Import a PHP array in a SplFixedArray instance
    • SplFixedArray::getSize - Gets the size of the array
    • SplFixedArray::key - Return current array index
    • SplFixedArray::next - Move to next entry
    • SplFixedArray::offsetExists - Returns whether the requested index exists
    • SplFixedArray::offsetGet - Returns the value at the specified index
    • SplFixedArray::offsetSet - Sets a new value at a specified index
    • SplFixedArray::offsetUnset - Unsets the value at the specified $index
    • SplFixedArray::rewind - Rewind iterator back to the start
    • SplFixedArray::setSize - Change the size of an array
    • SplFixedArray::toArray - Returns a PHP array from the fixed array
    • SplFixedArray::valid - Check whether the array contains more elements
    • SplFixedArray::__construct - Constructs a new fixed array
    • SplFixedArray::__wakeup - Reinitialises the array after being unserialised
    • SplHeap::compare - Compare elements in order to place them correctly in the heap while sifting up
    • SplHeap::count - Counts the number of elements in the heap
    • SplHeap::current - Return current node pointed by the iterator
    • SplHeap::extract - Extracts a node from top of the heap and sift up
    • SplHeap::insert - Inserts an element in the heap by sifting it up
    • SplHeap::isCorrupted - Tells if the heap is in a corrupted state
    • SplHeap::isEmpty - Checks whether the heap is empty
    • SplHeap::key - Return current node index
    • SplHeap::next - Move to the next node
    • SplHeap::recoverFromCorruption - Recover from the corrupted state and allow further actions on the heap
    • SplHeap::rewind - Rewind iterator back to the start (no-op)
    • SplHeap::top - Peeks at the node from the top of the heap
    • SplHeap::valid - Check whether the heap contains more nodes
    • SplHeap::__construct - Constructs a new empty heap
    • split - Split string into array by regular expression
    • spliti - Split string into array by regular expression case insensitive
    • SplMaxHeap::compare - Compare elements in order to place them correctly in the heap while sifting up
    • SplMinHeap::compare - Compare elements in order to place them correctly in the heap while sifting up
    • SplObjectStorage::addAll - Adds all objects from another storage
    • SplObjectStorage::attach - Adds an object in the storage
    • SplObjectStorage::contains - Checks if the storage contains a specific object
    • SplObjectStorage::count - Returns the number of objects in the storage
    • SplObjectStorage::current - Returns the current storage entry
    • SplObjectStorage::detach - Removes an object from the storage
    • SplObjectStorage::getHash - Calculate a unique identifier for the contained objects
    • SplObjectStorage::getInfo - Returns the data associated with the current iterator entry
    • SplObjectStorage::key - Returns the index at which the iterator currently is
    • SplObjectStorage::next - Move to the next entry
    • SplObjectStorage::offsetExists - Checks whether an object exists in the storage
    • SplObjectStorage::offsetGet - Returns the data associated with an object
    • SplObjectStorage::offsetSet - Associates data to an object in the storage
    • SplObjectStorage::offsetUnset - Removes an object from the storage
    • SplObjectStorage::removeAll - Removes objects contained in another storage from the current storage
    • SplObjectStorage::removeAllExcept - Removes all objects except for those contained in another storage from the current storage
    • SplObjectStorage::rewind - Rewind the iterator to the first storage element
    • SplObjectStorage::serialize - Serializes the storage
    • SplObjectStorage::setInfo - Sets the data associated with the current iterator entry
    • SplObjectStorage::unserialize - Unserializes a storage from its string representation
    • SplObjectStorage::valid - Returns if the current iterator entry is valid
    • SplObserver::update - Receive update from subject
    • SplPriorityQueue::compare - Compare priorities in order to place elements correctly in the heap while sifting up
    • SplPriorityQueue::count - Counts the number of elements in the queue
    • SplPriorityQueue::current - Return current node pointed by the iterator
    • SplPriorityQueue::extract - Extracts a node from top of the heap and sift up
    • SplPriorityQueue::getExtractFlags - Get the flags of extraction
    • SplPriorityQueue::insert - Inserts an element in the queue by sifting it up
    • SplPriorityQueue::isCorrupted - Tells if the priority queue is in a corrupted state
    • SplPriorityQueue::isEmpty - Checks whether the queue is empty
    • SplPriorityQueue::key - Return current node index
    • SplPriorityQueue::next - Move to the next node
    • SplPriorityQueue::recoverFromCorruption - Recover from the corrupted state and allow further actions on the queue
    • SplPriorityQueue::rewind - Rewind iterator back to the start (no-op)
    • SplPriorityQueue::setExtractFlags - Sets the mode of extraction
    • SplPriorityQueue::top - Peeks at the node from the top of the queue
    • SplPriorityQueue::valid - Check whether the queue contains more nodes
    • SplPriorityQueue::__construct - Constructs a new empty queue
    • SplQueue::dequeue - Dequeues a node from the queue
    • SplQueue::enqueue - Adds an element to the queue
    • SplQueue::setIteratorMode - Sets the mode of iteration
    • SplQueue::__construct - Constructs a new queue implemented using a doubly linked list
    • SplStack::setIteratorMode - Sets the mode of iteration
    • SplStack::__construct - Constructs a new stack implemented using a doubly linked list
    • SplSubject::attach - Attach an SplObserver
    • SplSubject::detach - Detach an observer
    • SplSubject::notify - Notify an observer
    • SplTempFileObject::__construct - Construct a new temporary file object
    • SplType::__construct - Creates a new value of some type
    • spl_autoload - Default implementation for __autoload()
    • spl_autoload_call - Try all registered __autoload() functions to load the requested class
    • spl_autoload_extensions - Register and return default file extensions for spl_autoload
    • spl_autoload_functions - Return all registered __autoload() functions
    • spl_autoload_register - Register given function as __autoload() implementation
    • spl_autoload_unregister - Unregister given function as __autoload() implementation
    • spl_classes - Return available SPL classes
    • spl_object_hash - Return hash id for given object
    • spl_object_id - Return the integer object handle for given object
    • Spoofchecker::areConfusable - Checks if given strings can be confused
    • 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::__construct - Constructor
    • sprintf - Return a formatted string
    • SQL acceptable by 4D - PDO and SQL 4D
    • 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::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::version - Returns the SQLite3 library version as a string constant and as a number
    • SQLite3::__construct - Instantiates an SQLite3 object and opens an SQLite 3 database
    • SQLite3Result::columnName - Returns the name of the nth column
    • SQLite3Result::columnType - Returns the type of the nth column
    • 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
    • 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::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
    • sqlite_array_query - Execute a query against a given database and returns an array
    • sqlite_busy_timeout - Set busy timeout duration, or disable busy handlers
    • sqlite_changes - Returns the number of rows that were changed by the most recent SQL statement
    • sqlite_close - Closes an open SQLite database
    • sqlite_column - Fetches a column from the current row of a result set
    • sqlite_create_aggregate - Register an aggregating UDF for use in SQL statements
    • sqlite_create_function - Registers a "regular" User Defined Function for use in SQL statements
    • sqlite_current - Fetches the current row from a result set as an array
    • sqlite_error_string - Returns the textual description of an error code
    • sqlite_escape_string - Escapes a string for use as a query parameter
    • sqlite_exec - Executes a result-less query against a given database
    • sqlite_factory - Opens an SQLite database and returns an SQLiteDatabase object
    • sqlite_fetch_all - Fetches all rows from a result set as an array of arrays
    • sqlite_fetch_array - Fetches the next row from a result set as an array
    • sqlite_fetch_column_types - Return an array of column types from a particular table
    • sqlite_fetch_object - Fetches the next row from a result set as an object
    • sqlite_fetch_single - Fetches the first column of a result set as a string
    • sqlite_fetch_string - Alias of sqlite_fetch_single
    • sqlite_field_name - Returns the name of a particular field
    • sqlite_has_more - Finds whether or not more rows are available
    • sqlite_has_prev - Returns whether or not a previous row is available
    • sqlite_key - Returns the current row index
    • sqlite_last_error - Returns the error code of the last error for a database
    • sqlite_last_insert_rowid - Returns the rowid of the most recently inserted row
    • sqlite_libencoding - Returns the encoding of the linked SQLite library
    • sqlite_libversion - Returns the version of the linked SQLite library
    • sqlite_next - Seek to the next row number
    • sqlite_num_fields - Returns the number of fields in a result set
    • sqlite_num_rows - Returns the number of rows in a buffered result set
    • sqlite_open - Opens an SQLite database and create the database if it does not exist
    • sqlite_popen - Opens a persistent handle to an SQLite database and create the database if it does not exist
    • sqlite_prev - Seek to the previous row number of a result set
    • sqlite_query - Executes a query against a given database and returns a result handle
    • sqlite_rewind - Seek to the first row number
    • sqlite_seek - Seek to a particular row number of a buffered result set
    • sqlite_single_query - Executes a query and returns either an array for one single column or the value of the first row
    • sqlite_udf_decode_binary - Decode binary data passed as parameters to an UDF
    • sqlite_udf_encode_binary - Encode binary data before returning it from an UDF
    • sqlite_unbuffered_query - Execute a query that does not prefetch and buffer all data
    • sqlite_valid - Returns whether more rows are available
    • 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
    • SqlStatement::bind - Bind statement parameters
    • SqlStatement::execute - Execute the operation
    • SqlStatement::getNextResult - Get next result
    • SqlStatement::getResult - Get result
    • SqlStatement::hasMoreResults - Check for more results
    • SqlStatement::__construct - Description constructor
    • SqlStatementResult::fetchAll - Get all rows from result
    • SqlStatementResult::fetchOne - Get single row
    • SqlStatementResult::getAffectedItemsCount - Get affected row count
    • SqlStatementResult::getColumnNames - Get column names
    • SqlStatementResult::getColumns - Get columns
    • SqlStatementResult::getColumnsCount - Get column count
    • 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
    • SqlStatementResult::__construct - Description constructor
    • SQL types with PDO_4D and PHP - SQL types with PDO_4D and PHP
    • sql_regcase - Make regular expression for case insensitive match
    • sqrt - Square root
    • srand - Seed the random number generator
    • sscanf - Parses input from a string according to a format
    • ssdeep_fuzzy_compare - Calculates the match score between two fuzzy hash signatures
    • ssdeep_fuzzy_hash - Create a fuzzy hash from a string
    • ssdeep_fuzzy_hash_filename - Create a fuzzy hash from a file
    • ssh2:// - Secure Shell 2
    • ssh2_auth_agent - Authenticate over SSH using the ssh agent
    • ssh2_auth_hostbased_file - Authenticate using a public hostkey
    • ssh2_auth_none - Authenticate as "none"
    • ssh2_auth_password - Authenticate over SSH using a plain password
    • ssh2_auth_pubkey_file - Authenticate using a public key
    • ssh2_connect - Connect to an SSH server
    • ssh2_disconnect - Close a connection to a remote SSH server
    • ssh2_exec - Execute a command on a remote server
    • ssh2_fetch_stream - Fetch an extended data stream
    • ssh2_fingerprint - Retrieve fingerprint of remote server
    • ssh2_methods_negotiated - Return list of negotiated methods
    • ssh2_publickey_add - Add an authorized publickey
    • ssh2_publickey_init - Initialize Publickey subsystem
    • ssh2_publickey_list - List currently authorized publickeys
    • ssh2_publickey_remove - Remove an authorized publickey
    • ssh2_scp_recv - Request a file via SCP
    • ssh2_scp_send - Send a file via SCP
    • ssh2_sftp - Initialize SFTP subsystem
    • ssh2_sftp_chmod - Changes file mode
    • ssh2_sftp_lstat - Stat a symbolic link
    • ssh2_sftp_mkdir - Create a directory
    • ssh2_sftp_readlink - Return the target of a symbolic link
    • ssh2_sftp_realpath - Resolve the realpath of a provided path string
    • ssh2_sftp_rename - Rename a remote file
    • ssh2_sftp_rmdir - Remove a directory
    • ssh2_sftp_stat - Stat a file on a remote filesystem
    • ssh2_sftp_symlink - Create a symlink
    • ssh2_sftp_unlink - Delete a file
    • ssh2_shell - Request an interactive shell
    • ssh2_tunnel - Open a tunnel through a remote server
    • SSL context options - SSL context option listing
    • stat - Gives information about a file
    • Statement::getNextResult - Get next result
    • Statement::getResult - Get result
    • Statement::hasMoreResults - Check if more results
    • Statement::__construct - Description constructor
    • 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
    • Stomp::abort - Rolls back a transaction in progress
    • Stomp::ack - Acknowledges consumption of a message
    • Stomp::begin - Starts a transaction
    • Stomp::commit - Commits a transaction in progress
    • Stomp::error - Gets the last stomp error
    • Stomp::getReadTimeout - Gets read timeout
    • Stomp::getSessionId - Gets the current stomp session ID
    • Stomp::hasFrame - Indicates whether or not there is a frame ready to read
    • Stomp::readFrame - Reads the next frame
    • Stomp::send - Sends a message
    • Stomp::setReadTimeout - Sets read timeout
    • Stomp::subscribe - Registers to listen to a given destination
    • Stomp::unsubscribe - Removes an existing subscription
    • Stomp::__construct - Opens a connection
    • Stomp::__destruct - Closes stomp connection
    • StompException::getDetails - Get exception details
    • StompFrame::__construct - Constructor
    • stomp_connect_error - Returns a string description of the last connect error
    • stomp_version - Gets the current stomp extension version
    • strcasecmp - Binary safe case-insensitive string comparison
    • strchr - Alias of strstr
    • strcmp - Binary safe string comparison
    • strcoll - Locale based string comparison
    • strcspn - Find length of initial segment not matching mask
    • streamWrapper::dir_closedir - Close directory handle
    • streamWrapper::dir_opendir - Open directory handle
    • streamWrapper::dir_readdir - Read entry from directory handle
    • streamWrapper::dir_rewinddir - Rewind directory handle
    • streamWrapper::mkdir - Create a directory
    • streamWrapper::rename - Renames a file or directory
    • streamWrapper::rmdir - Removes a directory
    • streamWrapper::stream_cast - Retrieve the underlaying resource
    • streamWrapper::stream_close - Close a resource
    • streamWrapper::stream_eof - Tests for end-of-file on a file pointer
    • streamWrapper::stream_flush - Flushes the output
    • streamWrapper::stream_lock - Advisory file locking
    • streamWrapper::stream_metadata - Change stream metadata
    • streamWrapper::stream_open - Opens file or URL
    • streamWrapper::stream_read - Read from stream
    • streamWrapper::stream_seek - Seeks to specific location in a stream
    • streamWrapper::stream_set_option - Change stream options
    • streamWrapper::stream_stat - Retrieve information about a file resource
    • streamWrapper::stream_tell - Retrieve the current position of a stream
    • streamWrapper::stream_truncate - Truncate stream
    • streamWrapper::stream_write - Write to stream
    • streamWrapper::unlink - Delete a file
    • streamWrapper::url_stat - Retrieve information about a file
    • streamWrapper::__construct - Constructs a new stream wrapper
    • streamWrapper::__destruct - Destructs an existing stream wrapper
    • stream_bucket_append - Append bucket to brigade
    • stream_bucket_make_writeable - Return a bucket object from the brigade for operating on
    • stream_bucket_new - Create a new bucket for use on the current stream
    • stream_bucket_prepend - Prepend bucket to brigade
    • stream_context_create - Creates a stream context
    • stream_context_get_default - Retrieve the default stream context
    • stream_context_get_options - Retrieve options for a stream/wrapper/context
    • stream_context_get_params - Retrieves parameters from a context
    • stream_context_set_default - Set the default stream context
    • stream_context_set_option - Sets an option for a stream/wrapper/context
    • stream_context_set_params - Set parameters for a stream/wrapper/context
    • stream_copy_to_stream - Copies data from one stream to another
    • stream_filter_append - Attach a filter to a stream
    • stream_filter_prepend - Attach a filter to a stream
    • stream_filter_register - Register a user defined stream filter
    • stream_filter_remove - Remove a filter from a stream
    • stream_get_contents - Reads remainder of a stream into a string
    • stream_get_filters - Retrieve list of registered filters
    • stream_get_line - Gets line from stream resource up to a given delimiter
    • stream_get_meta_data - Retrieves header/meta data from streams/file pointers
    • stream_get_transports - Retrieve list of registered socket transports
    • stream_get_wrappers - Retrieve list of registered streams
    • stream_isatty - Check if a stream is a TTY
    • stream_is_local - Checks if a stream is a local stream
    • stream_notification_callback - A callback function for the notification context parameter
    • stream_register_wrapper - Alias of stream_wrapper_register
    • stream_resolve_include_path - Resolve filename against the include path
    • stream_select - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec
    • stream_set_blocking - Set blocking/non-blocking mode on a stream
    • stream_set_chunk_size - Set the stream chunk size
    • stream_set_read_buffer - Set read file buffering on the given stream
    • stream_set_timeout - Set timeout period on a stream
    • stream_set_write_buffer - Sets write file buffering on the given stream
    • stream_socket_accept - Accept a connection on a socket created by stream_socket_server
    • stream_socket_client - Open Internet or Unix domain socket connection
    • stream_socket_enable_crypto - Turns encryption on/off on an already connected socket
    • stream_socket_get_name - Retrieve the name of the local or remote sockets
    • stream_socket_pair - Creates a pair of connected, indistinguishable socket streams
    • stream_socket_recvfrom - Receives data from a socket, connected or not
    • stream_socket_sendto - Sends a message to a socket, whether it is connected or not
    • stream_socket_server - Create an Internet or Unix domain server socket
    • stream_socket_shutdown - Shutdown a full-duplex connection
    • stream_supports_lock - Tells whether the stream supports locking
    • stream_wrapper_register - Register a URL wrapper implemented as a PHP class
    • stream_wrapper_restore - Restores a previously unregistered built-in wrapper
    • stream_wrapper_unregister - Unregister a URL wrapper
    • strftime - Format a local time/date according to locale settings
    • stripcslashes - Un-quote string quoted with addcslashes
    • stripos - Find the position of the first occurrence of a case-insensitive substring in a string
    • stripslashes - Un-quotes a quoted string
    • strip_tags - Strip HTML and PHP tags from a string
    • stristr - Case-insensitive strstr
    • strlen - Get string length
    • strnatcasecmp - Case insensitive string comparisons using a "natural order" algorithm
    • strnatcmp - String comparisons using a "natural order" algorithm
    • strncasecmp - Binary safe case-insensitive string comparison of the first n characters
    • strncmp - Binary safe string comparison of the first n characters
    • strpbrk - Search a string for any of a set of characters
    • strpos - Find the position of the first occurrence of a substring in a string
    • strptime - Parse a time/date generated with strftime
    • strrchr - Find the last occurrence of a character in a string
    • strrev - Reverse a string
    • 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
    • strspn - Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask
    • strstr - Find the first occurrence of a string
    • strtok - Tokenize string
    • strtolower - Make a string lowercase
    • strtotime - Parse about any English textual datetime description into a Unix timestamp
    • strtoupper - Make a string uppercase
    • strtr - Translate characters or replace substrings
    • strval - Get string value of a variable
    • str_getcsv - Parse a CSV string into an array
    • str_ireplace - Case-insensitive version of str_replace
    • str_pad - Pad a string to a certain length with another string
    • str_repeat - Repeat a string
    • str_replace - Replace all occurrences of the search string with the replacement string
    • str_rot13 - Perform the rot13 transform on a string
    • str_shuffle - Randomly shuffles a string
    • str_split - Convert a string to an array
    • str_word_count - Return information about words used in a string
    • substr - Return part of a string
    • substr_compare - Binary safe comparison of two strings from an offset, up to length characters
    • substr_count - Count the number of substring occurrences
    • substr_replace - Replace text within a portion of a string
    • SVM::crossvalidate - Test training params on subsets of the training data
    • SVM::getOptions - Return the current training parameters
    • SVM::setOptions - Set training parameters
    • SVM::train - Create a SVMModel based on training data
    • SVM::__construct - Construct a new SVM object
    • SVMModel::checkProbabilityModel - Returns true if the model has probability information
    • SVMModel::getLabels - Get the labels the model was trained on
    • SVMModel::getNrClass - Returns the number of classes the model was trained with
    • SVMModel::getSvmType - Get the SVM type the model was trained with
    • SVMModel::getSvrProbability - Get the sigma value for regression types
    • SVMModel::load - Load a saved SVM Model
    • SVMModel::predict - Predict a value for previously unseen data
    • SVMModel::predict_probability - Return class probabilities for previous unseen data
    • SVMModel::save - Save a model to a file
    • SVMModel::__construct - Construct a new SVMModel
    • svn_add - Schedules the addition of an item in a working directory
    • svn_auth_get_parameter - Retrieves authentication parameter
    • svn_auth_set_parameter - Sets an authentication parameter
    • svn_blame - Get the SVN blame for a file
    • svn_cat - Returns the contents of a file in a repository
    • svn_checkout - Checks out a working copy from the repository
    • svn_cleanup - Recursively cleanup a working copy directory, finishing incomplete operations and removing locks
    • svn_client_version - Returns the version of the SVN client libraries
    • svn_commit - Sends changes from the local working copy to the repository
    • svn_delete - Delete items from a working copy or repository
    • svn_diff - Recursively diffs two paths
    • svn_export - Export the contents of a SVN directory
    • svn_fs_abort_txn - Abort a transaction, returns true if everything is okay, false otherwise
    • svn_fs_apply_text - Creates and returns a stream that will be used to replace
    • svn_fs_begin_txn2 - Create a new transaction
    • svn_fs_change_node_prop - Return true if everything is ok, false otherwise
    • svn_fs_check_path - Determines what kind of item lives at path in a given repository fsroot
    • svn_fs_contents_changed - Return true if content is different, false otherwise
    • svn_fs_copy - Copies a file or a directory, returns true if all is ok, false otherwise
    • svn_fs_delete - Deletes a file or a directory, return true if all is ok, false otherwise
    • svn_fs_dir_entries - Enumerates the directory entries under path; returns a hash of dir names to file type
    • svn_fs_file_contents - Returns a stream to access the contents of a file from a given version of the fs
    • svn_fs_file_length - Returns the length of a file from a given version of the fs
    • svn_fs_is_dir - Return true if the path points to a directory, false otherwise
    • svn_fs_is_file - Return true if the path points to a file, false otherwise
    • svn_fs_make_dir - Creates a new empty directory, returns true if all is ok, false otherwise
    • svn_fs_make_file - Creates a new empty file, returns true if all is ok, false otherwise
    • svn_fs_node_created_rev - Returns the revision in which path under fsroot was created
    • svn_fs_node_prop - Returns the value of a property for a node
    • svn_fs_props_changed - Return true if props are different, false otherwise
    • svn_fs_revision_prop - Fetches the value of a named property
    • svn_fs_revision_root - Get a handle on a specific version of the repository root
    • svn_fs_txn_root - Creates and returns a transaction root
    • svn_fs_youngest_rev - Returns the number of the youngest revision in the filesystem
    • svn_import - Imports an unversioned path into a repository
    • svn_log - Returns the commit log messages of a repository URL
    • svn_ls - Returns list of directory contents in repository URL, optionally at revision number
    • svn_mkdir - Creates a directory in a working copy or repository
    • svn_repos_create - Create a new subversion repository at path
    • svn_repos_fs - Gets a handle on the filesystem for a repository
    • svn_repos_fs_begin_txn_for_commit - Create a new transaction
    • svn_repos_fs_commit_txn - Commits a transaction and returns the new revision
    • svn_repos_hotcopy - Make a hot-copy of the repos at repospath; copy it to destpath
    • svn_repos_open - Open a shared lock on a repository
    • svn_repos_recover - Run recovery procedures on the repository located at path
    • svn_revert - Revert changes to the working copy
    • svn_status - Returns the status of working copy files and directories
    • svn_update - Update working copy
    • SWFAction::__construct - Creates a new SWFAction
    • SWFBitmap::getHeight - Returns the bitmap's height
    • SWFBitmap::getWidth - Returns the bitmap's width
    • SWFBitmap::__construct - Loads Bitmap object
    • SWFButton::addAction - Adds an action
    • SWFButton::addASound - Associates a sound with a button transition
    • SWFButton::addShape - Adds a shape to a button
    • SWFButton::setAction - Sets the action
    • SWFButton::setDown - Alias for addShape(shape, SWFBUTTON_DOWN)
    • SWFButton::setHit - Alias for addShape(shape, SWFBUTTON_HIT)
    • SWFButton::setMenu - Enable track as menu button behaviour
    • SWFButton::setOver - Alias for addShape(shape, SWFBUTTON_OVER)
    • SWFButton::setUp - Alias for addShape(shape, SWFBUTTON_UP)
    • SWFButton::__construct - Creates a new Button
    • SWFDisplayItem::addAction - Adds this SWFAction to the given SWFSprite instance
    • SWFDisplayItem::addColor - Adds the given color to this item's color transform
    • SWFDisplayItem::endMask - Another way of defining a MASK layer
    • SWFDisplayItem::getRot - Description
    • SWFDisplayItem::getX - Description
    • SWFDisplayItem::getXScale - Description
    • SWFDisplayItem::getXSkew - Description
    • SWFDisplayItem::getY - Description
    • SWFDisplayItem::getYScale - Description
    • SWFDisplayItem::getYSkew - Description
    • SWFDisplayItem::move - Moves object in relative coordinates
    • SWFDisplayItem::moveTo - Moves object in global coordinates
    • SWFDisplayItem::multColor - Multiplies the item's color transform
    • SWFDisplayItem::remove - Removes the object from the movie
    • SWFDisplayItem::rotate - Rotates in relative coordinates
    • SWFDisplayItem::rotateTo - Rotates the object in global coordinates
    • SWFDisplayItem::scale - Scales the object in relative coordinates
    • SWFDisplayItem::scaleTo - Scales the object in global coordinates
    • SWFDisplayItem::setDepth - Sets z-order
    • SWFDisplayItem::setMaskLevel - Defines a MASK layer at level
    • SWFDisplayItem::setMatrix - Sets the item's transform matrix
    • SWFDisplayItem::setName - Sets the object's name
    • SWFDisplayItem::setRatio - Sets the object's ratio
    • SWFDisplayItem::skewX - Sets the X-skew
    • SWFDisplayItem::skewXTo - Sets the X-skew
    • SWFDisplayItem::skewY - Sets the Y-skew
    • SWFDisplayItem::skewYTo - Sets the Y-skew
    • SWFFill::moveTo - Moves fill origin
    • SWFFill::rotateTo - Sets fill's rotation
    • SWFFill::scaleTo - Sets fill's scale
    • SWFFill::skewXTo - Sets fill x-skew
    • SWFFill::skewYTo - Sets fill y-skew
    • SWFFont::getAscent - Returns the ascent of the font, or 0 if not available
    • SWFFont::getDescent - Returns the descent of the font, or 0 if not available
    • SWFFont::getLeading - Returns the leading of the font, or 0 if not available
    • SWFFont::getShape - Returns the glyph shape of a char as a text string
    • SWFFont::getUTF8Width - Calculates the width of the given string in this font at full height
    • SWFFont::getWidth - Returns the string's width
    • SWFFont::__construct - Loads a font definition
    • SWFFontChar::addChars - Adds characters to a font for exporting font
    • SWFFontChar::addUTF8Chars - Adds characters to a font for exporting font
    • SWFGradient::addEntry - Adds an entry to the gradient list
    • SWFGradient::__construct - Creates a gradient object
    • SWFMorph::getShape1 - Gets a handle to the starting shape
    • SWFMorph::getShape2 - Gets a handle to the ending shape
    • SWFMorph::__construct - Creates a new SWFMorph object
    • SWFMovie::add - Adds any type of data to a movie
    • SWFMovie::addExport - Description
    • SWFMovie::addFont - Description
    • SWFMovie::importChar - Description
    • SWFMovie::importFont - Description
    • SWFMovie::labelFrame - Labels a frame
    • SWFMovie::nextFrame - Moves to the next frame of the animation
    • SWFMovie::output - Dumps your lovingly prepared movie out
    • SWFMovie::remove - Removes the object instance from the display list
    • SWFMovie::save - Saves the SWF movie in a file
    • SWFMovie::saveToFile - Description
    • SWFMovie::setbackground - Sets the background color
    • SWFMovie::setDimension - Sets the movie's width and height
    • SWFMovie::setFrames - Sets the total number of frames in the animation
    • SWFMovie::setRate - Sets the animation's frame rate
    • SWFMovie::startSound - Description
    • SWFMovie::stopSound - Description
    • SWFMovie::streamMP3 - Streams a MP3 file
    • SWFMovie::writeExports - Description
    • SWFMovie::__construct - Creates a new movie object, representing an SWF version 4 movie
    • SWFPrebuiltClip::__construct - Returns a SWFPrebuiltClip object
    • SWFShape::addFill - Adds a solid fill to the shape
    • SWFShape::drawArc - Draws an arc of radius r centered at the current location, from angle startAngle to angle endAngle measured clockwise from 12 o'clock
    • SWFShape::drawCircle - Draws a circle of radius r centered at the current location, in a counter-clockwise fashion
    • SWFShape::drawCubic - Draws a cubic bezier curve using the current position and the three given points as control points
    • SWFShape::drawCubicTo - Draws a cubic bezier curve using the current position and the three given points as control points
    • SWFShape::drawCurve - Draws a curve (relative)
    • SWFShape::drawCurveTo - Draws a curve
    • SWFShape::drawGlyph - Draws the first character in the given string into the shape using the glyph definition from the given font
    • SWFShape::drawLine - Draws a line (relative)
    • SWFShape::drawLineTo - Draws a line
    • SWFShape::movePen - Moves the shape's pen (relative)
    • SWFShape::movePenTo - Moves the shape's pen
    • SWFShape::setLeftFill - Sets left rasterizing color
    • SWFShape::setLine - Sets the shape's line style
    • SWFShape::setRightFill - Sets right rasterizing color
    • SWFShape::__construct - Creates a new shape object
    • SWFSound::__construct - Returns a new SWFSound object from given file
    • SWFSoundInstance::loopCount - Description
    • SWFSoundInstance::loopInPoint - Description
    • SWFSoundInstance::loopOutPoint - Description
    • SWFSoundInstance::noMultiple - Description
    • SWFSprite::add - Adds an object to a sprite
    • SWFSprite::labelFrame - Labels frame
    • SWFSprite::nextFrame - Moves to the next frame of the animation
    • SWFSprite::remove - Removes an object to a sprite
    • SWFSprite::setFrames - Sets the total number of frames in the animation
    • SWFSprite::startSound - Description
    • SWFSprite::stopSound - Description
    • SWFSprite::__construct - Creates a movie clip (a sprite)
    • SWFText::addString - Draws a string
    • SWFText::addUTF8String - Writes the given text into this SWFText object at the current pen position, using the current font, height, spacing, and color
    • SWFText::getAscent - Returns the ascent of the current font at its current size, or 0 if not available
    • SWFText::getDescent - Returns the descent of the current font at its current size, or 0 if not available
    • SWFText::getLeading - Returns the leading of the current font at its current size, or 0 if not available
    • SWFText::getUTF8Width - Calculates the width of the given string in this text objects current font and size
    • SWFText::getWidth - Computes string's width
    • SWFText::moveTo - Moves the pen
    • SWFText::setColor - Sets the current text color
    • SWFText::setFont - Sets the current font
    • SWFText::setHeight - Sets the current font height
    • SWFText::setSpacing - Sets the current font spacing
    • SWFText::__construct - Creates a new SWFText object
    • SWFTextField::addChars - Adds characters to a font that will be available within a textfield
    • SWFTextField::addString - Concatenates the given string to the text field
    • SWFTextField::align - Sets the text field alignment
    • SWFTextField::setBounds - Sets the text field width and height
    • SWFTextField::setColor - Sets the color of the text field
    • SWFTextField::setFont - Sets the text field font
    • SWFTextField::setHeight - Sets the font height of this text field font
    • SWFTextField::setIndentation - Sets the indentation of the first line
    • SWFTextField::setLeftMargin - Sets the left margin width of the text field
    • SWFTextField::setLineSpacing - Sets the line spacing of the text field
    • SWFTextField::setMargins - Sets the margins width of the text field
    • SWFTextField::setName - Sets the variable name
    • SWFTextField::setPadding - Sets the padding of this textfield
    • SWFTextField::setRightMargin - Sets the right margin width of the text field
    • SWFTextField::__construct - Creates a text field object
    • SWFVideoStream::getNumFrames - Returns the number of frames in the video
    • SWFVideoStream::setDimension - Sets video dimension
    • SWFVideoStream::__construct - Returns a SWFVideoStream object
    • Swish::getMetaList - Get the list of meta entries for the index
    • Swish::getPropertyList - Get the list of properties for the index
    • Swish::prepare - Prepare a search query
    • Swish::query - Execute a query and return results object
    • Swish::__construct - Construct a Swish object
    • SwishResult::getMetaList - Get a list of meta entries
    • SwishResult::stem - Stems the given word
    • SwishResults::getParsedWords - Get an array of parsed words
    • SwishResults::getRemovedStopwords - Get an array of stopwords removed from the query
    • SwishResults::nextResult - Get the next search result
    • SwishResults::seekResult - Set current seek pointer to the given position
    • SwishSearch::execute - Execute the search and get the results
    • SwishSearch::resetLimit - Reset the search limits
    • SwishSearch::setLimit - Set the search limits
    • SwishSearch::setPhraseDelimiter - Set the phrase delimiter
    • SwishSearch::setSort - Set the sort order
    • SwishSearch::setStructure - Set the structure flag in the search object
    • Swoole\Async::dnsLookup - Async and non-blocking hostname to IP lookup.
    • Swoole\Async::read - Read file stream asynchronously.
    • Swoole\Async::readFile - Read a file asynchronously.
    • Swoole\Async::set - Update the async I/O options.
    • Swoole\Async::write - Write data to a file stream asynchronously.
    • Swoole\Async::writeFile - Description
    • Swoole\Atomic::add - Add a number to the value to the atomic object.
    • Swoole\Atomic::cmpset - Compare and set the value of the atomic object.
    • Swoole\Atomic::get - Get the current value of the atomic object.
    • Swoole\Atomic::set - Set a new value to the atomic object.
    • Swoole\Atomic::sub - Subtract a number to the value of the atomic object.
    • Swoole\Atomic::__construct - Construct a swoole atomic object.
    • Swoole\Buffer::append - Append the string or binary data at the end of the memory buffer and return the new size of memory allocated.
    • Swoole\Buffer::clear - Reset the memory buffer.
    • Swoole\Buffer::expand - Expand the size of memory buffer.
    • Swoole\Buffer::read - Read data from the memory buffer based on offset and length.
    • Swoole\Buffer::recycle - Release the memory to OS which is not used by the memory buffer.
    • Swoole\Buffer::substr - Read data from the memory buffer based on offset and length. Or remove data from the memory buffer.
    • Swoole\Buffer::write - Write data to the memory buffer. The memory allocated for the buffer will not be changed.
    • Swoole\Buffer::__construct - Fixed size memory blocks allocation.
    • Swoole\Buffer::__destruct - Destruct the Swoole memory buffer.
    • Swoole\Buffer::__toString - Get the string value of the memory buffer.
    • Swoole\Channel::pop - Read and pop data from swoole channel.
    • Swoole\Channel::push - Write and push data into Swoole channel.
    • Swoole\Channel::stats - Get stats of swoole channel.
    • Swoole\Channel::__construct - Construct a Swoole Channel
    • Swoole\Channel::__destruct - Destruct a Swoole channel.
    • Swoole\Client::close - Close the connection established.
    • Swoole\Client::connect - Connect to the remote TCP or UDP port.
    • Swoole\Client::getpeername - Get the remote socket name of the connection.
    • Swoole\Client::getsockname - Get the local socket name of the connection.
    • Swoole\Client::isConnected - Check if the connection is established.
    • Swoole\Client::on - Add callback functions triggered by events.
    • Swoole\Client::pause - Pause receiving data.
    • Swoole\Client::pipe - Redirect the data to another file descriptor.
    • Swoole\Client::recv - Receive data from the remote socket.
    • Swoole\Client::resume - Resume receiving data.
    • Swoole\Client::send - Send data to the remote TCP socket.
    • Swoole\Client::sendfile - Send file to the remote TCP socket.
    • Swoole\Client::sendto - Send data to the remote UDP address.
    • Swoole\Client::set - Set the Swoole client parameters before the connection is established.
    • Swoole\Client::sleep - Remove the TCP client from system event loop.
    • Swoole\Client::wakeup - Add the TCP client back into the system event loop.
    • Swoole\Client::__construct - Create Swoole sync or async TCP/UDP client, with or without SSL.
    • Swoole\Client::__destruct - Destruct the Swoole client.
    • Swoole\Connection\Iterator::count - Count connections.
    • Swoole\Connection\Iterator::current - Return current connection entry.
    • Swoole\Connection\Iterator::key - Return key of the current connection.
    • Swoole\Connection\Iterator::next - Move to the next connection.
    • Swoole\Connection\Iterator::offsetExists - Check if offet exists.
    • Swoole\Connection\Iterator::offsetGet - Offset to retrieve.
    • Swoole\Connection\Iterator::offsetSet - Assign a Connection to the specified offset.
    • Swoole\Connection\Iterator::offsetUnset - Unset an offset.
    • Swoole\Connection\Iterator::rewind - Rewinds iterator
    • Swoole\Connection\Iterator::valid - Check if current position is valid.
    • Swoole\Coroutine::call_user_func - Call a callback given by the first parameter
    • Swoole\Coroutine::call_user_func_array - Call a callback with an array of parameters
    • Swoole\Coroutine::cli_wait - Description
    • Swoole\Coroutine::create - Description
    • Swoole\Coroutine::getuid - Description
    • Swoole\Coroutine::resume - Description
    • Swoole\Coroutine::suspend - Description
    • Swoole\Coroutine\Client::close - Description
    • Swoole\Coroutine\Client::connect - Description
    • Swoole\Coroutine\Client::getpeername - Description
    • Swoole\Coroutine\Client::getsockname - Description
    • Swoole\Coroutine\Client::isConnected - Description
    • Swoole\Coroutine\Client::recv - Description
    • Swoole\Coroutine\Client::send - Description
    • Swoole\Coroutine\Client::sendfile - Description
    • Swoole\Coroutine\Client::sendto - Description
    • Swoole\Coroutine\Client::set - Description
    • Swoole\Coroutine\Client::__construct - Description
    • Swoole\Coroutine\Client::__destruct - Description
    • Swoole\Coroutine\Http\Client::addFile - Description
    • Swoole\Coroutine\Http\Client::close - Description
    • Swoole\Coroutine\Http\Client::execute - Description
    • Swoole\Coroutine\Http\Client::get - Description
    • Swoole\Coroutine\Http\Client::getDefer - Description
    • Swoole\Coroutine\Http\Client::isConnected - Description
    • Swoole\Coroutine\Http\Client::post - Description
    • Swoole\Coroutine\Http\Client::recv - Description
    • Swoole\Coroutine\Http\Client::set - Description
    • Swoole\Coroutine\Http\Client::setCookies - Description
    • Swoole\Coroutine\Http\Client::setData - Description
    • Swoole\Coroutine\Http\Client::setDefer - Description
    • Swoole\Coroutine\Http\Client::setHeaders - Description
    • Swoole\Coroutine\Http\Client::setMethod - Description
    • Swoole\Coroutine\Http\Client::__construct - Description
    • Swoole\Coroutine\Http\Client::__destruct - Description
    • Swoole\Coroutine\MySQL::close - Description
    • Swoole\Coroutine\MySQL::connect - Description
    • Swoole\Coroutine\MySQL::getDefer - Description
    • Swoole\Coroutine\MySQL::query - Description
    • Swoole\Coroutine\MySQL::recv - Description
    • Swoole\Coroutine\MySQL::setDefer - Description
    • Swoole\Coroutine\MySQL::__construct - Description
    • Swoole\Coroutine\MySQL::__destruct - Description
    • Swoole\Event::add - Add new callback functions of a socket into the EventLoop.
    • Swoole\Event::defer - Add a callback function to the next event loop.
    • Swoole\Event::del - Remove all event callback functions of a socket.
    • Swoole\Event::exit - Exit the eventloop, only available at client side.
    • Swoole\Event::set - Update the event callback functions of a socket.
    • Swoole\Event::wait - Description
    • Swoole\Event::write - Write data to the socket.
    • Swoole\Http\Client::addFile - Add a file to the post form.
    • Swoole\Http\Client::close - Close the http connection.
    • Swoole\Http\Client::download - Download a file from the remote server.
    • Swoole\Http\Client::execute - Send the HTTP request after setting the parameters.
    • Swoole\Http\Client::get - Send GET http request to the remote server.
    • Swoole\Http\Client::isConnected - Check if the HTTP connection is connected.
    • Swoole\Http\Client::on - Register callback function by event name.
    • Swoole\Http\Client::post - Send POST http request to the remote server.
    • Swoole\Http\Client::push - Push data to websocket client.
    • Swoole\Http\Client::set - Update the HTTP client paramters.
    • Swoole\Http\Client::setCookies - Set the http request cookies.
    • Swoole\Http\Client::setData - Set the HTTP request body data.
    • Swoole\Http\Client::setHeaders - Set the HTTP request headers.
    • Swoole\Http\Client::setMethod - Set the HTTP request method.
    • Swoole\Http\Client::upgrade - Upgrade to websocket protocol.
    • Swoole\Http\Client::__construct - Construct the async HTTP client.
    • Swoole\Http\Client::__destruct - Destruct the HTTP client.
    • Swoole\Http\Request::rawcontent - Get the raw HTTP POST body.
    • Swoole\Http\Request::__destruct - Destruct the HTTP request.
    • Swoole\Http\Response::cookie - Set the cookies of the HTTP response.
    • Swoole\Http\Response::end - Send data for the HTTP request and finish the response.
    • Swoole\Http\Response::gzip - Enable the gzip of response content.
    • Swoole\Http\Response::header - Set the HTTP response headers.
    • Swoole\Http\Response::initHeader - Init the HTTP response header.
    • Swoole\Http\Response::rawcookie - Set the raw cookies to the HTTP response.
    • Swoole\Http\Response::sendfile - Send file through the HTTP response.
    • Swoole\Http\Response::status - Set the status code of the HTTP response.
    • Swoole\Http\Response::write - Append HTTP body content to the HTTP response.
    • Swoole\Http\Response::__destruct - Destruct the HTTP response.
    • Swoole\Http\Server::on - Bind callback function to HTTP server by event name.
    • Swoole\Http\Server::start - Start the swoole http server.
    • Swoole\Lock::lock - Try to acquire the lock. It will block if the lock is not available.
    • Swoole\Lock::lock_read - Lock a read-write lock for reading.
    • Swoole\Lock::trylock - Try to acquire the lock and return straight away even the lock is not available.
    • Swoole\Lock::trylock_read - Try to lock a read-write lock for reading and return straight away even the lock is not available.
    • Swoole\Lock::unlock - Release the lock.
    • Swoole\Lock::__construct - Construct a memory lock.
    • Swoole\Lock::__destruct - Destory a Swoole memory lock.
    • Swoole\Mmap::open - Map a file into memory and return the stream resource which can be used by PHP stream operations.
    • Swoole\MySQL::close - Close the async MySQL connection.
    • Swoole\MySQL::connect - Connect to the remote MySQL server.
    • Swoole\MySQL::getBuffer - Description
    • Swoole\MySQL::on - Register callback function based on event name.
    • Swoole\MySQL::query - Run the SQL query.
    • Swoole\MySQL::__construct - Construct an async MySQL client.
    • Swoole\MySQL::__destruct - Destory the async MySQL client.
    • Swoole\Process::alarm - High precision timer which triggers signal with fixed interval.
    • Swoole\Process::close - Close the pipe to the child process.
    • Swoole\Process::daemon - Change the process to be a daemon process.
    • Swoole\Process::exec - Execute system commands.
    • Swoole\Process::exit - Stop the child processes.
    • Swoole\Process::freeQueue - Destroy the message queue created by swoole_process::useQueue.
    • Swoole\Process::kill - Send signal to the child process.
    • Swoole\Process::name - Set name of the process.
    • Swoole\Process::pop - Read and pop data from the message queue.
    • Swoole\Process::push - Write and push data into the message queue.
    • Swoole\Process::read - Read data sending to the process.
    • Swoole\Process::signal - Send signal to the child processes.
    • Swoole\Process::start - Start the process.
    • Swoole\Process::statQueue - Get the stats of the message queue used as the communication method between processes.
    • Swoole\Process::useQueue - Create a message queue as the communication method between the parent process and child processes.
    • Swoole\Process::wait - Wait for the events of child processes.
    • Swoole\Process::write - Write data into the pipe and communicate with the parent process or child processes.
    • Swoole\Process::__construct - Construct a process.
    • Swoole\Process::__destruct - Destory the process.
    • Swoole\Redis\Server::format - Description
    • Swoole\Redis\Server::setHandler - Description
    • Swoole\Redis\Server::start - Description
    • Swoole\Serialize::pack - Serialize the data.
    • Swoole\Serialize::unpack - Unserialize the data.
    • Swoole\Server::addlistener - Add a new listener to the server.
    • Swoole\Server::addProcess - Add a user defined swoole_process to the server.
    • Swoole\Server::after - Trigger a callback function after a period of time.
    • Swoole\Server::bind - Bind the connection to a user defined user ID.
    • Swoole\Server::clearTimer - Stop and destory a timer.
    • Swoole\Server::close - Close a connection to the client.
    • Swoole\Server::confirm - Check status of the connection.
    • Swoole\Server::connection_info - Get the connection info by file description.
    • Swoole\Server::connection_list - Get all of the established connections.
    • Swoole\Server::defer - Delay execution of the callback function at the end of current EventLoop.
    • Swoole\Server::exist - Check if the connection is existed.
    • Swoole\Server::finish - Used in task process for sending result to the worker process when the task is finished.
    • Swoole\Server::getClientInfo - Get the connection info by file description.
    • Swoole\Server::getClientList - Get all of the established connections.
    • Swoole\Server::getLastError - Get the error code of the most recent error.
    • Swoole\Server::heartbeat - Check all the connections on the server.
    • Swoole\Server::listen - Listen on the given IP and port, socket type.
    • Swoole\Server::on - Register a callback function by event name.
    • Swoole\Server::pause - Stop receiving data from the connection.
    • Swoole\Server::protect - Set the connection to be protected mode.
    • Swoole\Server::reload - Restart all the worker process.
    • Swoole\Server::resume - Start receving data from the connection.
    • Swoole\Server::send - Send data to the client.
    • Swoole\Server::sendfile - Send file to the connection.
    • Swoole\Server::sendMessage - Send message to worker processes by ID.
    • Swoole\Server::sendto - Send data to the remote UDP address.
    • Swoole\Server::sendwait - Send data to the remote socket in the blocking way.
    • Swoole\Server::set - Set the runtime settings of the swoole server.
    • Swoole\Server::shutdown - Shutdown the master server process, this function can be called in worker processes.
    • Swoole\Server::start - Start the Swoole server.
    • Swoole\Server::stats - Get the stats of the Swoole server.
    • Swoole\Server::stop - Stop the Swoole server.
    • Swoole\Server::task - Send data to the task worker processes.
    • Swoole\Server::taskwait - Send data to the task worker processes in blocking way.
    • Swoole\Server::taskWaitMulti - Execute multiple tasks concurrently.
    • Swoole\Server::tick - Repeats a given function at every given time-interval.
    • Swoole\Server::__construct - Construct a Swoole server.
    • Swoole\Server\Port::on - Register callback functions by event.
    • Swoole\Server\Port::set - Set protocol of the server port.
    • Swoole\Server\Port::__construct - Construct a server port
    • Swoole\Server\Port::__destruct - Destory server port
    • Swoole\Table::column - Set the data type and size of the columns.
    • Swoole\Table::count - Count the rows in the table, or count all the elements in the table if $mode = 1.
    • Swoole\Table::create - Create the swoole memory table.
    • Swoole\Table::current - Get the current row.
    • Swoole\Table::decr - Decrement the value in the Swoole table by $row_key and $column_key.
    • Swoole\Table::del - Delete a row in the Swoole table by $row_key.
    • Swoole\Table::destroy - Destroy the Swoole table.
    • Swoole\Table::exist - Check if a row is existed by $row_key.
    • Swoole\Table::get - Get the value in the Swoole table by $row_key and $column_key.
    • Swoole\Table::incr - Increment the value by $row_key and $column_key.
    • Swoole\Table::key - Get the key of current row.
    • Swoole\Table::next - Iterator the next row.
    • Swoole\Table::rewind - Rewind the iterator.
    • Swoole\Table::set - Update a row of the table by $row_key.
    • Swoole\Table::valid - Check current if the current row is valid.
    • Swoole\Table::__construct - Construct a Swoole memory table with fixed size.
    • Swoole\Timer::after - Trigger a callback function after a period of time.
    • Swoole\Timer::clear - Delete a timer by timer ID.
    • Swoole\Timer::exists - Check if a timer is existed.
    • Swoole\Timer::tick - Repeats a given function at every given time-interval.
    • Swoole\WebSocket\Server::exist - Check if the file descriptor exists.
    • Swoole\WebSocket\Server::on - Register event callback function
    • Swoole\WebSocket\Server::pack - Get a pack of binary data to send in a single frame.
    • Swoole\WebSocket\Server::push - Push data to the remote client.
    • Swoole\WebSocket\Server::unpack - Unpack the binary data received from the client.
    • swoole_async_dns_lookup - Async and non-blocking hostname to IP lookup
    • swoole_async_read - Read file stream asynchronously
    • swoole_async_readfile - Read a file asynchronously
    • swoole_async_set - Update the async I/O options
    • swoole_async_write - Write data to a file stream asynchronously
    • swoole_async_writefile - Write data to a file asynchronously
    • swoole_client_select - Get the file description which are ready to read/write or error
    • swoole_cpu_num - Get the number of CPU
    • swoole_errno - Get the error code of the latest system call
    • swoole_event_add - Add new callback functions of a socket into the EventLoop
    • swoole_event_defer - Add callback function to the next event loop
    • swoole_event_del - Remove all event callback functions of a socket
    • swoole_event_exit - Exit the eventloop, only available at the client side
    • swoole_event_set - Update the event callback functions of a socket
    • swoole_event_wait - Start the event loop
    • swoole_event_write - Write data to a socket
    • swoole_get_local_ip - Get the IPv4 IP addresses of each NIC on the machine
    • swoole_last_error - Get the lastest error message
    • swoole_load_module - Load a swoole extension
    • swoole_select - Select the file descriptions which are ready to read/write or error in the eventloop
    • swoole_set_process_name - Set the process name
    • swoole_strerror - Convert the Errno into error messages
    • swoole_timer_after - Trigger a one time callback function in the future
    • swoole_timer_exists - Check if a timer callback function is existed
    • swoole_timer_tick - Trigger a timer tick callback function by time interval
    • swoole_version - Get the version of Swoole
    • sybase_affected_rows - Gets number of affected rows in last query
    • sybase_close - Closes a Sybase connection
    • sybase_connect - Opens a Sybase server connection
    • sybase_data_seek - Moves internal row pointer
    • sybase_deadlock_retry_count - Sets the deadlock retry count
    • sybase_fetch_array - Fetch row as array
    • sybase_fetch_assoc - Fetch a result row as an associative array
    • sybase_fetch_field - Get field information from a result
    • sybase_fetch_object - Fetch a row as an object
    • sybase_fetch_row - Get a result row as an enumerated array
    • sybase_field_seek - Sets field offset
    • sybase_free_result - Frees result memory
    • sybase_get_last_message - Returns the last message from the server
    • sybase_min_client_severity - Sets minimum client severity
    • sybase_min_error_severity - Sets minimum error severity
    • sybase_min_message_severity - Sets minimum message severity
    • sybase_min_server_severity - Sets minimum server severity
    • sybase_num_fields - Gets the number of fields in a result set
    • sybase_num_rows - Get number of rows in a result set
    • sybase_pconnect - Open persistent Sybase connection
    • sybase_query - Sends a Sybase query
    • sybase_result - Get result data
    • sybase_select_db - Selects a Sybase database
    • sybase_set_message_handler - Sets the handler called when a server message is raised
    • sybase_unbuffered_query - Send a Sybase query and do not block
    • symlink - Creates a symbolic link
    • SyncEvent::fire - Fires/sets the event
    • SyncEvent::reset - Resets a manual event
    • SyncEvent::wait - Waits for the event to be fired/set
    • SyncEvent::__construct - Constructs a new SyncEvent object
    • SyncMutex::lock - Waits for an exclusive lock
    • SyncMutex::unlock - Unlocks the mutex
    • SyncMutex::__construct - Constructs a new SyncMutex object
    • SyncReaderWriter::readlock - Waits for a read lock
    • SyncReaderWriter::readunlock - Releases a read lock
    • SyncReaderWriter::writelock - Waits for an exclusive write lock
    • SyncReaderWriter::writeunlock - Releases a write lock
    • SyncReaderWriter::__construct - Constructs a new SyncReaderWriter object
    • SyncSemaphore::lock - Decreases the count of the semaphore or waits
    • SyncSemaphore::unlock - Increases the count of the semaphore
    • SyncSemaphore::__construct - Constructs a new SyncSemaphore object
    • SyncSharedMemory::first - Check to see if the object is the first instance system-wide of named shared memory
    • SyncSharedMemory::read - Copy data from named shared memory
    • SyncSharedMemory::size - Returns the size of the named shared memory
    • SyncSharedMemory::write - Copy data to named shared memory
    • SyncSharedMemory::__construct - Constructs a new SyncSharedMemory object
    • syslog - Generate a system log message
    • system - Execute an external program and display the output
    • sys_getloadavg - Gets system load average
    • sys_get_temp_dir - Returns directory path used for temporary files
  • t
    • 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
    • Table::__construct - Table constructor
    • TableDelete::bind - Bind delete query parameters
    • TableDelete::execute - Execute delete query
    • TableDelete::limit - Limit deleted rows
    • TableDelete::orderby - Set delete sort criteria
    • TableDelete::where - Set delete search condition
    • TableDelete::__construct - TableDelete constructor
    • TableInsert::execute - Execute insert query
    • TableInsert::values - Add insert row values
    • TableInsert::__construct - TableInsert constructor
    • TableSelect::bind - Bind select query parameters
    • 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
    • TableSelect::__construct - TableSelect constructor
    • TableUpdate::bind - Bind update query parameters
    • 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
    • TableUpdate::__construct - TableUpdate constructor
    • taint - Taint a string
    • tan - Tangent
    • tanh - Hyperbolic tangent
    • tcpwrap_check - Performs a tcpwrap check
    • tempnam - Create file with unique file name
    • textdomain - Sets the default domain
    • Thread::detach - Execution
    • Thread::getCreatorId - Identification
    • Thread::getCurrentThread - Identification
    • Thread::getCurrentThreadId - Identification
    • Thread::getThreadId - Identification
    • Thread::globally - Execution
    • Thread::isJoined - State Detection
    • Thread::isStarted - State Detection
    • Thread::join - Synchronization
    • Thread::kill - Execution
    • Thread::start - Execution
    • Threaded::chunk - Manipulation
    • Threaded::count - Manipulation
    • Threaded::extend - Runtime Manipulation
    • Threaded::from - Creation
    • Threaded::getTerminationInfo - Error Detection
    • Threaded::isRunning - State Detection
    • Threaded::isTerminated - State Detection
    • Threaded::isWaiting - State Detection
    • Threaded::lock - Synchronization
    • Threaded::merge - Manipulation
    • Threaded::notify - Synchronization
    • Threaded::notifyOne - Synchronization
    • Threaded::pop - Manipulation
    • Threaded::run - Execution
    • Threaded::shift - Manipulation
    • Threaded::synchronized - Synchronization
    • Threaded::unlock - Synchronization
    • Threaded::wait - Synchronization
    • 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::getMessage - Gets the message
    • Throwable::getPrevious - Returns the previous Throwable
    • Throwable::getTrace - Gets the stack trace
    • Throwable::getTraceAsString - Gets the stack trace as a string
    • Throwable::__toString - Gets a string representation of the thrown object
    • tidy::$errorBuffer - Return warnings and errors which occurred parsing the specified document
    • tidy::body - Returns a tidyNode object starting from the <body> tag of the tidy parse tree
    • tidy::cleanRepair - Execute configured cleanup and repair operations on parsed markup
    • tidy::diagnose - Run configured diagnostics on parsed and repaired markup
    • tidy::getConfig - Get current Tidy configuration
    • tidy::getHtmlVer - Get the Detected HTML version for the specified document
    • tidy::getOpt - Returns the value of the specified configuration option for the tidy document
    • tidy::getOptDoc - Returns the documentation for the given option name
    • tidy::getRelease - Get release date (version) for Tidy library
    • tidy::getStatus - Get status of specified document
    • tidy::head - Returns a tidyNode object starting from the <head> tag of the tidy parse tree
    • tidy::html - Returns a tidyNode object starting from the <html> tag of the tidy parse tree
    • tidy::isXhtml - Indicates if the document is a XHTML document
    • tidy::isXml - Indicates if the document is a generic (non HTML/XHTML) XML document
    • tidy::parseFile - Parse markup in file or URI
    • tidy::parseString - Parse a document stored in a string
    • tidy::repairFile - Repair a file and return it as a string
    • tidy::repairString - Repair a string using an optionally provided configuration file
    • tidy::root - Returns a tidyNode object representing the root of the tidy parse tree
    • tidy::__construct - Constructs a new tidy object
    • tidyNode::getParent - Returns the parent node of the current node
    • tidyNode::hasChildren - Checks if a node has children
    • tidyNode::hasSiblings - Checks if a node has siblings
    • tidyNode::isAsp - Checks if this node is ASP
    • tidyNode::isComment - Checks if a node represents a comment
    • tidyNode::isHtml - Checks if a node is part of a HTML document
    • tidyNode::isJste - Checks if this node is JSTE
    • tidyNode::isPhp - Checks if a node is PHP
    • tidyNode::isText - Checks if a node represents text (no markup)
    • tidyNode::__construct - Private constructor to disallow direct instantiation
    • tidy_access_count - Returns the Number of Tidy accessibility warnings encountered for specified document
    • tidy_config_count - Returns the Number of Tidy configuration errors encountered for specified document
    • tidy_error_count - Returns the Number of Tidy errors encountered for specified document
    • tidy_get_output - Return a string representing the parsed tidy markup
    • tidy_warning_count - Returns the Number of Tidy warnings encountered for specified document
    • 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 the timezone name from abbreviation
    • 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
    • time_nanosleep - Delay for a number of seconds and nanoseconds
    • time_sleep_until - Make the script sleep until the specified time
    • tmpfile - Creates a temporary file
    • token_get_all - Split given source into PHP tokens
    • token_name - Get the symbolic name of a given PHP token
    • TokyoTyrant::add - Adds to a numeric key
    • TokyoTyrant::connect - Connect to a database
    • TokyoTyrant::connectUri - Connects to a database
    • TokyoTyrant::copy - Copies the database
    • TokyoTyrant::ext - Execute a remote script
    • TokyoTyrant::fwmKeys - Returns the forward matching keys
    • TokyoTyrant::get - The get purpose
    • TokyoTyrant::getIterator - Get an iterator
    • TokyoTyrant::num - Number of records in the database
    • TokyoTyrant::out - Removes records
    • TokyoTyrant::put - Puts values
    • TokyoTyrant::putCat - Concatenates to a record
    • TokyoTyrant::putKeep - Puts a record
    • TokyoTyrant::putNr - Puts value
    • TokyoTyrant::putShl - Concatenates to a record
    • TokyoTyrant::restore - Restore the database
    • TokyoTyrant::setMaster - Set the replication master
    • TokyoTyrant::size - Returns the size of the value
    • TokyoTyrant::stat - Get statistics
    • TokyoTyrant::sync - Synchronize the database
    • TokyoTyrant::tune - Tunes connection values
    • TokyoTyrant::vanish - Empties the database
    • TokyoTyrant::__construct - Construct a new TokyoTyrant object
    • TokyoTyrantIterator::current - Get the current value
    • TokyoTyrantIterator::key - Returns the current key
    • TokyoTyrantIterator::next - Move to next key
    • TokyoTyrantIterator::rewind - Rewinds the iterator
    • TokyoTyrantIterator::valid - Rewinds the iterator
    • TokyoTyrantIterator::__construct - Construct an iterator
    • TokyoTyrantQuery::addCond - Adds a condition to the query
    • TokyoTyrantQuery::count - Counts records
    • TokyoTyrantQuery::current - Returns the current element
    • TokyoTyrantQuery::hint - Get the hint string of the query
    • TokyoTyrantQuery::key - Returns the current key
    • TokyoTyrantQuery::metaSearch - Retrieve records with multiple queries
    • TokyoTyrantQuery::next - Moves the iterator to next entry
    • TokyoTyrantQuery::out - Removes records based on query
    • TokyoTyrantQuery::rewind - Rewinds the iterator
    • TokyoTyrantQuery::search - Searches records
    • TokyoTyrantQuery::setLimit - Limit results
    • TokyoTyrantQuery::setOrder - Orders results
    • TokyoTyrantQuery::valid - Checks the validity of current item
    • TokyoTyrantQuery::__construct - Construct a new query
    • TokyoTyrantTable::add - Adds a record
    • TokyoTyrantTable::genUid - Generate unique id
    • TokyoTyrantTable::get - Get a row
    • TokyoTyrantTable::getIterator - Get an iterator
    • TokyoTyrantTable::getQuery - Get a query object
    • TokyoTyrantTable::out - Remove records
    • TokyoTyrantTable::put - Store a row
    • TokyoTyrantTable::putCat - Concatenates to a row
    • TokyoTyrantTable::putKeep - Put a new record
    • TokyoTyrantTable::putNr - Puts value
    • TokyoTyrantTable::putShl - Concatenates to a record
    • TokyoTyrantTable::setIndex - Sets index
    • touch - Sets access and modification time of file
    • 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
    • trait_exists - Checks if the trait exists
    • 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
    • Transliterator::__construct - Private constructor to deny instantiation
    • trigger_error - Generates a user-level error/warning/notice message
    • trim - Strip whitespace (or other characters) from the beginning and end of a string
  • u
    • uasort - Sort an array with a user-defined comparison function and maintain index association
    • ucfirst - Make a string's first character uppercase
    • 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 convertor 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 string from one charset to another
    • UConverter::__construct - Create UConverter object
    • ucwords - Uppercase the first character of each word in a string
    • udm_add_search_limit - Add various search limits
    • udm_alloc_agent - Allocate mnoGoSearch session
    • udm_alloc_agent_array - Allocate mnoGoSearch session
    • udm_api_version - Get mnoGoSearch API version
    • udm_cat_list - Get all the categories on the same level with the current one
    • udm_cat_path - Get the path to the current category
    • udm_check_charset - Check if the given charset is known to mnogosearch
    • udm_clear_search_limits - Clear all mnoGoSearch search restrictions
    • udm_crc32 - Return CRC32 checksum of given string
    • udm_errno - Get mnoGoSearch error number
    • udm_error - Get mnoGoSearch error message
    • udm_find - Perform search
    • udm_free_agent - Free mnoGoSearch session
    • udm_free_ispell_data - Free memory allocated for ispell data
    • udm_free_res - Free mnoGoSearch result
    • udm_get_doc_count - Get total number of documents in database
    • udm_get_res_field - Fetch a result field
    • udm_get_res_param - Get mnoGoSearch result parameters
    • udm_hash32 - Return Hash32 checksum of given string
    • udm_load_ispell_data - Load ispell data
    • udm_set_agent_param - Set mnoGoSearch agent session parameters
    • UI\Area::onDraw - Draw Callback
    • UI\Area::onKey - Key Callback
    • UI\Area::onMouse - Mouse Callback
    • UI\Area::redraw - Redraw Area
    • UI\Area::scrollTo - Area Scroll
    • UI\Area::setSize - Set Size
    • UI\Control::destroy - Destroy Control
    • UI\Control::disable - Disable Control
    • UI\Control::enable - Enable Control
    • UI\Control::getParent - Get Parent Control
    • UI\Control::getTopLevel - Get Top Level
    • UI\Control::hide - Hide Control
    • UI\Control::isEnabled - Determine if Control is enabled
    • UI\Control::isVisible - Determine if Control is visible
    • UI\Control::setParent - Set Parent Control
    • UI\Control::show - Control Show
    • UI\Controls\Box::append - Append Control
    • UI\Controls\Box::delete - Delete Control
    • UI\Controls\Box::getOrientation - Get Orientation
    • UI\Controls\Box::isPadded - Padding Detection
    • UI\Controls\Box::setPadded - Set Padding
    • UI\Controls\Box::__construct - Construct a new Box
    • UI\Controls\Button::getText - Get Text
    • UI\Controls\Button::onClick - Click Handler
    • UI\Controls\Button::setText - Set Text
    • UI\Controls\Button::__construct - Construct a new Button
    • UI\Controls\Check::getText - Get Text
    • UI\Controls\Check::isChecked - Checked Detection
    • UI\Controls\Check::onToggle - Toggle Callback
    • UI\Controls\Check::setChecked - Set Checked
    • UI\Controls\Check::setText - Set Text
    • UI\Controls\Check::__construct - Construct a new Check
    • UI\Controls\ColorButton::getColor - Get Color
    • UI\Controls\ColorButton::onChange - Change Handler
    • UI\Controls\ColorButton::setColor - Set Color
    • UI\Controls\Combo::append - Append Option
    • UI\Controls\Combo::getSelected - Get Selected Option
    • UI\Controls\Combo::onSelected - Selected Handler
    • UI\Controls\Combo::setSelected - Set Selected Option
    • UI\Controls\EditableCombo::append - Append Option
    • UI\Controls\EditableCombo::getText - Get Text
    • UI\Controls\EditableCombo::onChange - Change Handler
    • UI\Controls\EditableCombo::setText - Set Text
    • UI\Controls\Entry::getText - Get Text
    • UI\Controls\Entry::isReadOnly - Detect Read Only
    • UI\Controls\Entry::onChange - Change Handler
    • UI\Controls\Entry::setReadOnly - Set Read Only
    • UI\Controls\Entry::setText - Set Text
    • UI\Controls\Entry::__construct - Construct a new Entry
    • UI\Controls\Form::append - Append Control
    • UI\Controls\Form::delete - Delete Control
    • UI\Controls\Form::isPadded - Padding Detection
    • UI\Controls\Form::setPadded - Set Padding
    • UI\Controls\Grid::append - Append Control
    • UI\Controls\Grid::isPadded - Padding Detection
    • UI\Controls\Grid::setPadded - Set Padding
    • UI\Controls\Group::append - Append Control
    • UI\Controls\Group::getTitle - Get Title
    • UI\Controls\Group::hasMargin - Margin Detection
    • UI\Controls\Group::setMargin - Set Margin
    • UI\Controls\Group::setTitle - Set Title
    • UI\Controls\Group::__construct - Construct a new Group
    • UI\Controls\Label::getText - Get Text
    • UI\Controls\Label::setText - Set Text
    • UI\Controls\Label::__construct - Construct a new Label
    • UI\Controls\MultilineEntry::append - Append Text
    • UI\Controls\MultilineEntry::getText - Get Text
    • UI\Controls\MultilineEntry::isReadOnly - Read Only Detection
    • UI\Controls\MultilineEntry::onChange - Change Handler
    • UI\Controls\MultilineEntry::setReadOnly - Set Read Only
    • UI\Controls\MultilineEntry::setText - Set Text
    • UI\Controls\MultilineEntry::__construct - Construct a new Multiline Entry
    • UI\Controls\Picker::__construct - Construct a new Picker
    • UI\Controls\Progress::getValue - Get Value
    • UI\Controls\Progress::setValue - Set Value
    • UI\Controls\Radio::append - Append Option
    • UI\Controls\Radio::getSelected - Get Selected Option
    • UI\Controls\Radio::onSelected - Selected Handler
    • UI\Controls\Radio::setSelected - Set Selected Option
    • UI\Controls\Separator::__construct - Construct a new Separator
    • UI\Controls\Slider::getValue - Get Value
    • UI\Controls\Slider::onChange - Change Handler
    • UI\Controls\Slider::setValue - Set Value
    • UI\Controls\Slider::__construct - Construct a new Slider
    • UI\Controls\Spin::getValue - Get Value
    • UI\Controls\Spin::onChange - Change Handler
    • UI\Controls\Spin::setValue - Set Value
    • UI\Controls\Spin::__construct - Construct a new Spin
    • UI\Controls\Tab::append - Append Page
    • UI\Controls\Tab::delete - Delete Page
    • UI\Controls\Tab::hasMargin - Margin Detection
    • UI\Controls\Tab::insertAt - Insert Page
    • UI\Controls\Tab::pages - Page Count
    • UI\Controls\Tab::setMargin - Set Margin
    • UI\Draw\Brush::getColor - Get Color
    • UI\Draw\Brush::setColor - Set Color
    • UI\Draw\Brush::__construct - Construct a new Brush
    • UI\Draw\Brush\Gradient::addStop - Stop Manipulation
    • UI\Draw\Brush\Gradient::delStop - Stop Manipulation
    • UI\Draw\Brush\Gradient::setStop - Stop Manipulation
    • UI\Draw\Brush\LinearGradient::__construct - Construct a Linear Gradient
    • UI\Draw\Brush\RadialGradient::__construct - Construct a new Radial Gradient
    • UI\Draw\Color::getChannel - Color Manipulation
    • UI\Draw\Color::setChannel - Color Manipulation
    • UI\Draw\Color::__construct - Construct new Color
    • UI\Draw\Matrix::invert - Invert Matrix
    • UI\Draw\Matrix::isInvertible - Invertible Detection
    • UI\Draw\Matrix::multiply - Multiply Matrix
    • UI\Draw\Matrix::rotate - Rotate Matrix
    • UI\Draw\Matrix::scale - Scale Matrix
    • UI\Draw\Matrix::skew - Skew Matrix
    • UI\Draw\Matrix::translate - Translate Matrix
    • UI\Draw\Path::addRectangle - Draw a Rectangle
    • UI\Draw\Path::arcTo - Draw an Arc
    • UI\Draw\Path::bezierTo - Draw Bezier Curve
    • UI\Draw\Path::closeFigure - Close Figure
    • UI\Draw\Path::end - Finalize Path
    • UI\Draw\Path::lineTo - Draw a Line
    • UI\Draw\Path::newFigure - Draw Figure
    • UI\Draw\Path::newFigureWithArc - Draw Figure with Arc
    • UI\Draw\Path::__construct - Construct a new Path
    • UI\Draw\Pen::clip - Clip a Path
    • UI\Draw\Pen::fill - Fill a Path
    • UI\Draw\Pen::restore - Restore
    • UI\Draw\Pen::save - Save
    • UI\Draw\Pen::stroke - Stroke a Path
    • UI\Draw\Pen::transform - Matrix Transform
    • UI\Draw\Pen::write - Draw Text at Point
    • UI\Draw\Stroke::getCap - Get Line Cap
    • UI\Draw\Stroke::getJoin - Get Line Join
    • UI\Draw\Stroke::getMiterLimit - Get Miter Limit
    • UI\Draw\Stroke::getThickness - Get Thickness
    • UI\Draw\Stroke::setCap - Set Line Cap
    • UI\Draw\Stroke::setJoin - Set Line Join
    • UI\Draw\Stroke::setMiterLimit - Set Miter Limit
    • UI\Draw\Stroke::setThickness - Set Thickness
    • UI\Draw\Stroke::__construct - Construct a new Stroke
    • UI\Draw\Text\Font::getAscent - Font Metrics
    • UI\Draw\Text\Font::getDescent - Font Metrics
    • UI\Draw\Text\Font::getLeading - Font Metrics
    • UI\Draw\Text\Font::getUnderlinePosition - Font Metrics
    • UI\Draw\Text\Font::getUnderlineThickness - Font Metrics
    • UI\Draw\Text\Font::__construct - Construct a new Font
    • UI\Draw\Text\Font\Descriptor::getFamily - Get Font Family
    • UI\Draw\Text\Font\Descriptor::getItalic - Style Detection
    • UI\Draw\Text\Font\Descriptor::getSize - Size Detection
    • UI\Draw\Text\Font\Descriptor::getStretch - Style Detection
    • UI\Draw\Text\Font\Descriptor::getWeight - Weight Detection
    • UI\Draw\Text\Font\Descriptor::__construct - Construct a new Font Descriptor
    • UI\Draw\Text\Font\fontFamilies - Retrieve Font Families
    • UI\Draw\Text\Layout::setColor - Set Color
    • UI\Draw\Text\Layout::setWidth - Set Width
    • UI\Draw\Text\Layout::__construct - Construct a new Text Layout
    • UI\Executor::kill - Stop Executor
    • UI\Executor::onExecute - Execution Callback
    • UI\Executor::setInterval - Interval Manipulation
    • UI\Executor::__construct - Construct a new Executor
    • UI\Menu::append - Append Menu Item
    • UI\Menu::appendAbout - Append About Menu Item
    • UI\Menu::appendCheck - Append Checkable Menu Item
    • UI\Menu::appendPreferences - Append Preferences Menu Item
    • UI\Menu::appendQuit - Append Quit Menu Item
    • UI\Menu::appendSeparator - Append Menu Item Separator
    • UI\Menu::__construct - Construct a new Menu
    • UI\MenuItem::disable - Disable Menu Item
    • UI\MenuItem::enable - Enable Menu Item
    • UI\MenuItem::isChecked - Detect Checked
    • UI\MenuItem::onClick - On Click Callback
    • UI\MenuItem::setChecked - Set Checked
    • UI\Point::at - Size Coercion
    • UI\Point::getX - Retrieves X
    • UI\Point::getY - Retrieves Y
    • UI\Point::setX - Set X
    • UI\Point::setY - Set Y
    • UI\Point::__construct - Construct a new Point
    • UI\quit - Quit UI Loop
    • UI\run - Enter UI Loop
    • UI\Size::getHeight - Retrieves Height
    • UI\Size::getWidth - Retrives Width
    • UI\Size::of - Point Coercion
    • UI\Size::setHeight - Set Height
    • UI\Size::setWidth - Set Width
    • UI\Size::__construct - Construct a new Size
    • UI\Window::add - Add a Control
    • UI\Window::error - Show Error Box
    • UI\Window::getSize - Get Window Size
    • UI\Window::getTitle - Get Title
    • UI\Window::hasBorders - Border Detection
    • UI\Window::hasMargin - Margin Detection
    • UI\Window::isFullScreen - Full Screen Detection
    • UI\Window::msg - Show Message Box
    • UI\Window::onClosing - Closing Callback
    • UI\Window::open - Open Dialog
    • UI\Window::save - Save Dialog
    • UI\Window::setBorders - Border Use
    • UI\Window::setFullScreen - Full Screen Use
    • UI\Window::setMargin - Margin Use
    • UI\Window::setSize - Set Size
    • UI\Window::setTitle - Window Title
    • UI\Window::__construct - Construct a new Window
    • uksort - Sort an array by keys using a user-defined comparison function
    • umask - Changes the current umask
    • uniqid - Generate a unique ID
    • unixtojd - Convert Unix timestamp to Julian Day
    • unlink - Deletes a file
    • unpack - Unpack data from binary string
    • unregister_tick_function - De-register a function for execution on each tick
    • unserialize - Creates a PHP value from a stored representation
    • unset - Unset a given variable
    • untaint - Untaint strings
    • 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_delete - Delete a function
    • uopz_del_function - Deletes previously added function or method
    • 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
    • urldecode - Decodes URL-encoded string
    • urlencode - URL-encodes string
    • user_error - Alias of trigger_error
    • use_soap_error_handler - Set whether to use the SOAP error handler
    • usleep - Delay execution in microseconds
    • usort - Sort an array by values using a user-defined comparison function
    • utf8_decode - Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1
    • utf8_encode - Encodes an ISO-8859-1 string to UTF-8
  • v
    • V8Js::executeString - Execute a string as Javascript code
    • V8Js::getExtensions - Return an array of registered extensions
    • V8Js::getPendingException - Return pending uncaught Javascript exception
    • V8Js::registerExtension - Register Javascript extensions for V8Js
    • V8Js::__construct - Construct a new V8Js object
    • V8JsException::getJsFileName - The getJsFileName purpose
    • V8JsException::getJsLineNumber - The getJsLineNumber purpose
    • V8JsException::getJsSourceLine - The getJsSourceLine purpose
    • V8JsException::getJsTrace - The getJsTrace purpose
    • VARIANT::__construct - VARIANT class constructor
    • variant_abs - Returns the absolute value of a variant
    • variant_add - "Adds" two variant values together and returns the result
    • variant_and - Performs a bitwise AND operation between two variants
    • variant_cast - Convert a variant into a new variant object of another type
    • variant_cat - Concatenates two variant values together and returns the result
    • variant_cmp - Compares two variants
    • variant_date_from_timestamp - Returns a variant date representation of a Unix timestamp
    • variant_date_to_timestamp - Converts a variant date/time value to Unix timestamp
    • variant_div - Returns the result from dividing two variants
    • variant_eqv - Performs a bitwise equivalence on two variants
    • variant_fix - Returns the integer portion of a variant
    • variant_get_type - Returns the type of a variant object
    • variant_idiv - Converts variants to integers and then returns the result from dividing them
    • variant_imp - Performs a bitwise implication on two variants
    • variant_int - Returns the integer portion of a variant
    • variant_mod - Divides two variants and returns only the remainder
    • variant_mul - Multiplies the values of the two variants
    • variant_neg - Performs logical negation on a variant
    • variant_not - Performs bitwise not negation on a variant
    • variant_or - Performs a logical disjunction on two variants
    • variant_pow - Returns the result of performing the power function with two variants
    • variant_round - Rounds a variant to the specified number of decimal places
    • variant_set - Assigns a new value for a variant object
    • variant_set_type - Convert a variant into another type "in-place"
    • variant_sub - Subtracts the value of the right variant from the left variant value
    • variant_xor - Performs a logical exclusion on two variants
    • VarnishAdmin::auth - Authenticate on a varnish instance
    • VarnishAdmin::ban - Ban URLs using a VCL expression
    • VarnishAdmin::banUrl - Ban an URL using a VCL expression
    • VarnishAdmin::clearPanic - Clear varnish instance panic messages
    • VarnishAdmin::connect - Connect to a varnish instance administration interface
    • VarnishAdmin::disconnect - Disconnect from a varnish instance administration interface
    • VarnishAdmin::getPanic - Get the last panic message on a varnish instance
    • VarnishAdmin::getParams - Fetch current varnish instance configuration parameters
    • VarnishAdmin::isRunning - Check if the varnish slave process is currently running
    • VarnishAdmin::setCompat - Set the class compat configuration param
    • VarnishAdmin::setHost - Set the class host configuration param
    • VarnishAdmin::setIdent - Set the class ident configuration param
    • VarnishAdmin::setParam - Set configuration param on the current varnish instance
    • VarnishAdmin::setPort - Set the class port configuration param
    • VarnishAdmin::setSecret - Set the class secret configuration param
    • VarnishAdmin::setTimeout - Set the class timeout configuration param
    • VarnishAdmin::start - Start varnish worker process
    • VarnishAdmin::stop - Stop varnish worker process
    • VarnishAdmin::__construct - VarnishAdmin constructor
    • VarnishLog::getLine - Get next log line
    • VarnishLog::getTagName - Get the log tag string representation by its index
    • VarnishLog::__construct - Varnishlog constructor
    • VarnishStat::getSnapshot - Get the current varnish instance statistics snapshot
    • VarnishStat::__construct - VarnishStat constructor
    • var_dump - Dumps information about a variable
    • var_export - Outputs or returns a parsable string representation of a variable
    • version_compare - Compares two "PHP-standardized" version number strings
    • vfprintf - Write a formatted string to a stream
    • virtual - Perform an Apache sub-request
    • vpopmail_add_alias_domain - Add an alias for a virtual domain
    • vpopmail_add_alias_domain_ex - Add alias to an existing virtual domain
    • vpopmail_add_domain - Add a new virtual domain
    • vpopmail_add_domain_ex - Add a new virtual domain
    • vpopmail_add_user - Add a new user to the specified virtual domain
    • vpopmail_alias_add - Insert a virtual alias
    • vpopmail_alias_del - Deletes all virtual aliases of a user
    • vpopmail_alias_del_domain - Deletes all virtual aliases of a domain
    • vpopmail_alias_get - Get all lines of an alias for a domain
    • vpopmail_alias_get_all - Get all lines of an alias for a domain
    • vpopmail_auth_user - Attempt to validate a username/domain/password
    • vpopmail_del_domain - Delete a virtual domain
    • vpopmail_del_domain_ex - Delete a virtual domain
    • vpopmail_del_user - Delete a user from a virtual domain
    • vpopmail_error - Get text message for last vpopmail error
    • vpopmail_passwd - Change a virtual user's password
    • vpopmail_set_user_quota - Sets a virtual user's quota
    • vprintf - Output a formatted string
    • vsprintf - Return a formatted string
    • 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::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\Excel::__construct - Vtiful\Kernel\Excel constructor
    • 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
  • w
    • Warning::__construct - Warning constructor
    • wddx_add_vars - Add variables to a WDDX packet with the specified ID
    • wddx_deserialize - Unserializes a WDDX packet
    • wddx_packet_end - Ends a WDDX packet with the specified ID
    • wddx_packet_start - Starts a new WDDX packet with structure inside it
    • wddx_serialize_value - Serialize a single value into a WDDX packet
    • wddx_serialize_vars - Serialize variables into a WDDX packet
    • WeakMap::count - Counts the number of live entries in the map
    • WeakMap::current - Returns the current value under iteration
    • WeakMap::key - Returns the current key under iteration
    • WeakMap::next - Advances to the next map element
    • 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
    • WeakMap::rewind - Rewinds the iterator to the beginning of the map
    • WeakMap::valid - Returns whether the iterator is still on a valid map element
    • WeakMap::__construct - Constructs a new map
    • Weakref::acquire - Acquires a strong reference on that object
    • Weakref::get - Returns the object pointed to by the weak reference
    • Weakref::release - Releases a previously acquired reference
    • Weakref::valid - Checks whether the object referenced still exists
    • Weakref::__construct - Constructs a new weak reference
    • WeakReference::create - Create a new weak reference
    • WeakReference::get - Get a weakly referenced Object
    • WeakReference::__construct - Constructor that disallows instantiation
    • win32_continue_service - Resumes a paused service
    • win32_create_service - Creates a new service entry in the SCM database
    • win32_delete_service - Deletes a service entry from the SCM database
    • win32_get_last_control_message - Returns the last control message that was sent to this service
    • win32_pause_service - Pauses a service
    • win32_ps_list_procs - List running processes
    • win32_ps_stat_mem - Stat memory utilization
    • win32_ps_stat_proc - Stat process
    • win32_query_service_status - Queries the status of a service
    • win32_send_custom_control - Send a custom control to the service
    • win32_set_service_exit_code - Define or return the exit code for the current running service
    • win32_set_service_exit_mode - Define or return the exit mode for the current running service
    • win32_set_service_status - Update the service status
    • win32_start_service - Starts a service
    • win32_start_service_ctrl_dispatcher - Registers the script with the SCM, so that it can act as the service with the given name
    • win32_stop_service - Stops a service
    • 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
    • wkhtmltox\Image\Converter::convert - Perform Image conversion
    • wkhtmltox\Image\Converter::getVersion - Determine version of Converter
    • wkhtmltox\Image\Converter::__construct - Create a new Image converter
    • wkhtmltox\PDF\Converter::add - Add an object for conversion
    • wkhtmltox\PDF\Converter::convert - Perform PDF conversion
    • wkhtmltox\PDF\Converter::getVersion - Determine version of Converter
    • wkhtmltox\PDF\Converter::__construct - Create a new PDF converter
    • wkhtmltox\PDF\Object::__construct - Create a new PDF Object
    • wordwrap - Wraps a string to a given number of characters
    • Worker::collect - Collect references to completed tasks
    • Worker::getStacked - Gets the remaining stack size
    • Worker::isShutdown - State Detection
    • Worker::isWorking - State Detection
    • Worker::shutdown - Shutdown the worker
    • Worker::stack - Stacking work
    • Worker::unstack - Unstacking work
  • x
    • 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_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 binary diff of two strings using the Rabin's polynomial fingerprinting algorithm
    • 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
    • XMLDiff\Base::diff - Produce diff of two XML documents
    • XMLDiff\Base::merge - Produce new XML document based on diff
    • XMLDiff\Base::__construct - Constructor
    • XMLDiff\DOM::diff - Diff two DOMDocument objects
    • XMLDiff\DOM::merge - Produce merged DOMDocument
    • XMLDiff\File::diff - Diff two XML files
    • XMLDiff\File::merge - Produce merged XML document
    • XMLDiff\Memory::diff - Diff two XML documents
    • XMLDiff\Memory::merge - Produce merged XML document
    • XMLReader::close - Close the XMLReader input
    • XMLReader::expand - Returns a copy of the current node as a DOM object
    • XMLReader::getAttribute - Get the value of a named attribute
    • XMLReader::getAttributeNo - Get the value of an attribute by index
    • XMLReader::getAttributeNs - Get the value of an attribute by localname and URI
    • XMLReader::getParserProperty - Indicates if specified property has been set
    • XMLReader::isValid - Indicates if the parsed document is valid
    • XMLReader::lookupNamespace - Lookup namespace for a prefix
    • XMLReader::moveToAttribute - Move cursor to a named attribute
    • XMLReader::moveToAttributeNo - Move cursor to an attribute by index
    • XMLReader::moveToAttributeNs - Move cursor to a named attribute
    • XMLReader::moveToElement - Position cursor on the parent Element of current Attribute
    • XMLReader::moveToFirstAttribute - Position cursor on the first Attribute
    • XMLReader::moveToNextAttribute - Position cursor on the next Attribute
    • XMLReader::next - Move cursor to next node skipping all subtrees
    • XMLReader::open - Set the URI containing the XML to parse
    • XMLReader::read - Move to next node in document
    • XMLReader::readInnerXml - Retrieve XML from current node
    • XMLReader::readOuterXml - Retrieve XML from current node, including itself
    • XMLReader::readString - Reads the contents of the current node as a string
    • XMLReader::setParserProperty - Set parser options
    • XMLReader::setRelaxNGSchema - Set the filename or URI for a RelaxNG Schema
    • XMLReader::setRelaxNGSchemaSource - Set the data containing a RelaxNG Schema
    • XMLReader::setSchema - Validate document against XSD
    • XMLReader::XML - Set the data containing the XML to parse
    • xmlrpc_decode - Decodes XML into native PHP types
    • xmlrpc_decode_request - Decodes XML into native PHP types
    • xmlrpc_encode - Generates XML for a PHP value
    • xmlrpc_encode_request - Generates XML for a method request
    • xmlrpc_get_type - Gets xmlrpc type for a PHP value
    • xmlrpc_is_fault - Determines if an array value represents an XMLRPC fault
    • xmlrpc_parse_method_descriptions - Decodes XML into a list of method descriptions
    • xmlrpc_server_add_introspection_data - Adds introspection documentation
    • xmlrpc_server_call_method - Parses XML requests and call methods
    • xmlrpc_server_create - Creates an xmlrpc server
    • xmlrpc_server_destroy - Destroys server resources
    • xmlrpc_server_register_introspection_callback - Register a PHP function to generate documentation
    • xmlrpc_server_register_method - Register a PHP function to resource method matching method_name
    • xmlrpc_set_type - Sets xmlrpc type, base64 or datetime, for a PHP string value
    • XMLWriter::endAttribute - End attribute
    • XMLWriter::endCdata - End current CDATA
    • XMLWriter::endComment - Create end comment
    • XMLWriter::endDocument - End current document
    • XMLWriter::endDtd - End current DTD
    • XMLWriter::endDtdAttlist - End current DTD AttList
    • XMLWriter::endDtdElement - End current DTD element
    • XMLWriter::endDtdEntity - End current DTD Entity
    • XMLWriter::endElement - End current element
    • XMLWriter::endPi - End current PI
    • XMLWriter::flush - Flush current buffer
    • XMLWriter::fullEndElement - End current element
    • XMLWriter::openMemory - Create new xmlwriter using memory for string output
    • XMLWriter::openUri - Create new xmlwriter using source uri for output
    • XMLWriter::outputMemory - Returns current buffer
    • XMLWriter::setIndent - Toggle indentation on/off
    • XMLWriter::setIndentString - Set string used for indenting
    • XMLWriter::startAttribute - Create start attribute
    • XMLWriter::startAttributeNs - Create start namespaced attribute
    • XMLWriter::startCdata - Create start CDATA tag
    • XMLWriter::startComment - Create start comment
    • XMLWriter::startDocument - Create document tag
    • XMLWriter::startDtd - Create start DTD tag
    • XMLWriter::startDtdAttlist - Create start DTD AttList
    • XMLWriter::startDtdElement - Create start DTD element
    • XMLWriter::startDtdEntity - Create start DTD Entity
    • XMLWriter::startElement - Create start element tag
    • XMLWriter::startElementNs - Create start namespaced element tag
    • XMLWriter::startPi - Create start PI tag
    • XMLWriter::text - Write text
    • XMLWriter::writeAttribute - Write full attribute
    • XMLWriter::writeAttributeNs - Write full namespaced attribute
    • XMLWriter::writeCdata - Write full CDATA tag
    • XMLWriter::writeComment - Write full comment tag
    • XMLWriter::writeDtd - Write full DTD tag
    • XMLWriter::writeDtdAttlist - Write full DTD AttList tag
    • XMLWriter::writeDtdElement - Write full DTD element tag
    • XMLWriter::writeDtdEntity - Write full DTD Entity tag
    • XMLWriter::writeElement - Write full element tag
    • XMLWriter::writeElementNs - Write full namespaced element tag
    • XMLWriter::writePi - Writes a PI
    • XMLWriter::writeRaw - Write a raw XML text
    • xml_error_string - Get XML parser error string
    • xml_get_current_byte_index - Get current byte index for an XML parser
    • xml_get_current_column_number - Get current column number for an XML parser
    • xml_get_current_line_number - Get current line number for an XML parser
    • xml_get_error_code - Get XML parser error code
    • xml_parse - Start parsing an XML document
    • xml_parser_create - Create an XML parser
    • xml_parser_create_ns - Create an XML parser with namespace support
    • xml_parser_free - Free an XML parser
    • xml_parser_get_option - Get options from an XML parser
    • xml_parser_set_option - Set options in an XML parser
    • xml_parse_into_struct - Parse XML data into an array structure
    • xml_set_character_data_handler - Set up character data handler
    • xml_set_default_handler - Set up default handler
    • xml_set_element_handler - Set up start and end element handlers
    • xml_set_end_namespace_decl_handler - Set up end namespace declaration handler
    • xml_set_external_entity_ref_handler - Set up external entity reference handler
    • xml_set_notation_decl_handler - Set up notation declaration handler
    • xml_set_object - Use XML Parser within an object
    • xml_set_processing_instruction_handler - Set up processing instruction (PI) handler
    • xml_set_start_namespace_decl_handler - Set up start namespace declaration handler
    • xml_set_unparsed_entity_decl_handler - Set up unparsed entity declaration handler
    • XSLTProcessor::getParameter - Get value of a parameter
    • XSLTProcessor::getSecurityPrefs - Get security preferences
    • XSLTProcessor::hasExsltSupport - Determine if PHP has EXSLT support
    • XSLTProcessor::importStylesheet - Import stylesheet
    • XSLTProcessor::registerPHPFunctions - Enables the ability to use PHP functions as XSLT functions
    • XSLTProcessor::removeParameter - Remove parameter
    • XSLTProcessor::setParameter - Set value for a parameter
    • XSLTProcessor::setProfiling - Sets profiling output file
    • XSLTProcessor::setSecurityPrefs - Set security preferences
    • XSLTProcessor::transformToDoc - Transform to a DOMDocument
    • XSLTProcessor::transformToUri - Transform to URI
    • XSLTProcessor::transformToXml - Transform to XML
    • XSLTProcessor::__construct - Creates a new XSLTProcessor object
  • y
    • Yaconf::get - Retrieve a item
    • Yaconf::has - Determine if a item exists
    • Yaf_Action_Abstract::execute - Action entry point
    • Yaf_Action_Abstract::getController - Retrieve controller object
    • Yaf_Application::app - Retrieve an Application instance
    • Yaf_Application::bootstrap - Call bootstrap
    • Yaf_Application::clearLastError - Clear the last error info
    • Yaf_Application::environ - Retrive environ
    • Yaf_Application::execute - Execute a callback
    • Yaf_Application::getAppDirectory - Get the application directory
    • Yaf_Application::getConfig - Retrive the config instance
    • Yaf_Application::getDispatcher - Get Yaf_Dispatcher instance
    • Yaf_Application::getLastErrorMsg - Get message of the last occurred error
    • Yaf_Application::getLastErrorNo - Get code of last occurred error
    • Yaf_Application::getModules - Get defined module names
    • Yaf_Application::run - Start Yaf_Application
    • Yaf_Application::setAppDirectory - Change the application directory
    • Yaf_Application::__clone - Yaf_Application can not be cloned
    • Yaf_Application::__construct - Yaf_Application constructor
    • Yaf_Application::__destruct - The __destruct purpose
    • Yaf_Application::__sleep - Yaf_Application can not be serialized
    • Yaf_Application::__wakeup - Yaf_Application can not be unserialized
    • Yaf_Config_Abstract::get - Getter
    • Yaf_Config_Abstract::readonly - Find a config whether readonly
    • Yaf_Config_Abstract::set - Setter
    • Yaf_Config_Abstract::toArray - Cast to array
    • Yaf_Config_Ini::count - Count all elements in Yaf_Config.ini
    • Yaf_Config_Ini::current - Retrieve the current value
    • Yaf_Config_Ini::key - Fetch current element's key
    • Yaf_Config_Ini::next - Advance the internal pointer
    • Yaf_Config_Ini::offsetExists - The offsetExists purpose
    • Yaf_Config_Ini::offsetGet - The offsetGet purpose
    • Yaf_Config_Ini::offsetSet - The offsetSet purpose
    • Yaf_Config_Ini::offsetUnset - The offsetUnset purpose
    • Yaf_Config_Ini::readonly - The readonly purpose
    • Yaf_Config_Ini::rewind - The rewind purpose
    • Yaf_Config_Ini::toArray - Return config as a PHP array
    • Yaf_Config_Ini::valid - The valid purpose
    • Yaf_Config_Ini::__construct - Yaf_Config_Ini constructor
    • Yaf_Config_Ini::__get - Retrieve a element
    • Yaf_Config_Ini::__isset - Determine if a key is exists
    • Yaf_Config_Ini::__set - The __set purpose
    • Yaf_Config_Simple::count - The count purpose
    • Yaf_Config_Simple::current - The current purpose
    • Yaf_Config_Simple::key - The key purpose
    • Yaf_Config_Simple::next - The next purpose
    • Yaf_Config_Simple::offsetExists - The offsetExists purpose
    • Yaf_Config_Simple::offsetGet - The offsetGet purpose
    • Yaf_Config_Simple::offsetSet - The offsetSet purpose
    • Yaf_Config_Simple::offsetUnset - The offsetUnset purpose
    • Yaf_Config_Simple::readonly - The readonly purpose
    • Yaf_Config_Simple::rewind - The rewind purpose
    • Yaf_Config_Simple::toArray - Returns a PHP array
    • Yaf_Config_Simple::valid - The valid purpose
    • Yaf_Config_Simple::__construct - The __construct purpose
    • Yaf_Config_Simple::__get - The __get purpose
    • Yaf_Config_Simple::__isset - The __isset purpose
    • Yaf_Config_Simple::__set - The __set purpose
    • Yaf_Controller_Abstract::display - The display purpose
    • Yaf_Controller_Abstract::forward - Foward to another action
    • Yaf_Controller_Abstract::getInvokeArg - The getInvokeArg purpose
    • Yaf_Controller_Abstract::getInvokeArgs - The getInvokeArgs purpose
    • Yaf_Controller_Abstract::getModuleName - Get module name
    • Yaf_Controller_Abstract::getRequest - Retrieve current request object
    • Yaf_Controller_Abstract::getResponse - Retrieve current response object
    • Yaf_Controller_Abstract::getView - Retrieve the view engine
    • Yaf_Controller_Abstract::getViewpath - The getViewpath purpose
    • Yaf_Controller_Abstract::init - Controller initializer
    • Yaf_Controller_Abstract::initView - The initView purpose
    • Yaf_Controller_Abstract::redirect - Redirect to a URL
    • Yaf_Controller_Abstract::render - Render view template
    • Yaf_Controller_Abstract::setViewpath - The setViewpath purpose
    • Yaf_Controller_Abstract::__clone - Yaf_Controller_Abstract can not be cloned
    • Yaf_Controller_Abstract::__construct - Yaf_Controller_Abstract constructor
    • Yaf_Dispatcher::autoRender - Switch on/off autorendering
    • Yaf_Dispatcher::catchException - Switch on/off exception catching
    • Yaf_Dispatcher::disableView - Disable view rendering
    • Yaf_Dispatcher::dispatch - Dispatch a request
    • Yaf_Dispatcher::enableView - Enable view rendering
    • Yaf_Dispatcher::flushInstantly - Switch on/off the instant flushing
    • Yaf_Dispatcher::getApplication - Retrive the application
    • Yaf_Dispatcher::getInstance - Retrive the dispatcher instance
    • Yaf_Dispatcher::getRequest - Retrive the request instance
    • Yaf_Dispatcher::getRouter - Retrive router instance
    • Yaf_Dispatcher::initView - Initialize view and return it
    • Yaf_Dispatcher::registerPlugin - Register a plugin
    • Yaf_Dispatcher::returnResponse - The returnResponse purpose
    • Yaf_Dispatcher::setDefaultAction - Change default action name
    • Yaf_Dispatcher::setDefaultController - Change default controller name
    • Yaf_Dispatcher::setDefaultModule - Change default module name
    • Yaf_Dispatcher::setErrorHandler - Set error handler
    • Yaf_Dispatcher::setRequest - The setRequest purpose
    • Yaf_Dispatcher::setView - Set a custom view engine
    • Yaf_Dispatcher::throwException - Switch on/off exception throwing
    • Yaf_Dispatcher::__clone - Yaf_Dispatcher can not be cloned
    • Yaf_Dispatcher::__construct - Yaf_Dispatcher constructor
    • Yaf_Dispatcher::__sleep - Yaf_Dispatcher can not be serialized
    • Yaf_Dispatcher::__wakeup - Yaf_Dispatcher can not be unserialized
    • Yaf_Exception::getPrevious - The getPrevious purpose
    • Yaf_Exception::__construct - The __construct purpose
    • Yaf_Loader::autoload - The autoload purpose
    • Yaf_Loader::clearLocalNamespace - The clearLocalNamespace purpose
    • Yaf_Loader::getInstance - The getInstance purpose
    • Yaf_Loader::getLibraryPath - Get the library path
    • Yaf_Loader::getLocalNamespace - The getLocalNamespace purpose
    • Yaf_Loader::import - The import purpose
    • Yaf_Loader::isLocalName - The isLocalName purpose
    • Yaf_Loader::registerLocalNamespace - Register local class prefix
    • Yaf_Loader::setLibraryPath - Change the library path
    • Yaf_Loader::__clone - The __clone purpose
    • Yaf_Loader::__construct - The __construct purpose
    • Yaf_Loader::__sleep - The __sleep purpose
    • Yaf_Loader::__wakeup - The __wakeup purpose
    • Yaf_Plugin_Abstract::dispatchLoopShutdown - The dispatchLoopShutdown purpose
    • Yaf_Plugin_Abstract::dispatchLoopStartup - Hook before dispatch loop
    • Yaf_Plugin_Abstract::postDispatch - The postDispatch purpose
    • Yaf_Plugin_Abstract::preDispatch - The preDispatch purpose
    • Yaf_Plugin_Abstract::preResponse - The preResponse purpose
    • Yaf_Plugin_Abstract::routerShutdown - The routerShutdown purpose
    • Yaf_Plugin_Abstract::routerStartup - RouterStartup hook
    • Yaf_Registry::del - Remove an item from registry
    • Yaf_Registry::get - Retrieve an item from registry
    • Yaf_Registry::has - Check whether an item exists
    • Yaf_Registry::set - Add an item into registry
    • Yaf_Registry::__clone - The __clone purpose
    • Yaf_Registry::__construct - Yaf_Registry implements singleton
    • Yaf_Request_Abstract::getActionName - The getActionName purpose
    • Yaf_Request_Abstract::getBaseUri - The getBaseUri purpose
    • Yaf_Request_Abstract::getControllerName - The getControllerName purpose
    • Yaf_Request_Abstract::getEnv - Retrieve ENV varialbe
    • Yaf_Request_Abstract::getException - The getException purpose
    • Yaf_Request_Abstract::getLanguage - Retrieve client's prefered language
    • Yaf_Request_Abstract::getMethod - Retrieve the request method
    • Yaf_Request_Abstract::getModuleName - The getModuleName purpose
    • Yaf_Request_Abstract::getParam - Retrieve calling parameter
    • Yaf_Request_Abstract::getParams - Retrieve all calling parameters
    • Yaf_Request_Abstract::getRequestUri - The getRequestUri purpose
    • Yaf_Request_Abstract::getServer - Retrieve SERVER variable
    • Yaf_Request_Abstract::isCli - Determine if request is CLI request
    • Yaf_Request_Abstract::isDispatched - Determin if the request is dispatched
    • Yaf_Request_Abstract::isGet - Determine if request is GET request
    • Yaf_Request_Abstract::isHead - Determine if request is HEAD request
    • Yaf_Request_Abstract::isOptions - Determine if request is OPTIONS request
    • Yaf_Request_Abstract::isPost - Determine if request is POST request
    • Yaf_Request_Abstract::isPut - Determine if request is PUT request
    • Yaf_Request_Abstract::isRouted - Determin if request has been routed
    • Yaf_Request_Abstract::isXmlHttpRequest - Determine if request is AJAX request
    • Yaf_Request_Abstract::setActionName - The setActionName purpose
    • Yaf_Request_Abstract::setBaseUri - Set base URI
    • Yaf_Request_Abstract::setControllerName - The setControllerName purpose
    • Yaf_Request_Abstract::setDispatched - The setDispatched purpose
    • Yaf_Request_Abstract::setModuleName - The setModuleName purpose
    • Yaf_Request_Abstract::setParam - Set a calling parameter to a request
    • Yaf_Request_Abstract::setRequestUri - The setRequestUri purpose
    • Yaf_Request_Abstract::setRouted - The setRouted purpose
    • Yaf_Request_Http::get - Retrieve variable from client
    • Yaf_Request_Http::getCookie - Retrieve Cookie variable
    • Yaf_Request_Http::getFiles - The getFiles purpose
    • Yaf_Request_Http::getPost - Retrieve POST variable
    • Yaf_Request_Http::getQuery - Fetch a query parameter
    • Yaf_Request_Http::getRaw - Retrieve Raw request body
    • Yaf_Request_Http::getRequest - The getRequest purpose
    • Yaf_Request_Http::isXmlHttpRequest - Determin if request is Ajax Request
    • Yaf_Request_Http::__clone - Yaf_Request_Http can not be cloned
    • Yaf_Request_Http::__construct - Constructor of Yaf_Request_Http
    • Yaf_Request_Simple::get - The get purpose
    • Yaf_Request_Simple::getCookie - The getCookie purpose
    • Yaf_Request_Simple::getFiles - The getFiles purpose
    • Yaf_Request_Simple::getPost - The getPost purpose
    • Yaf_Request_Simple::getQuery - The getQuery purpose
    • Yaf_Request_Simple::getRequest - The getRequest purpose
    • Yaf_Request_Simple::isXmlHttpRequest - Determin if request is AJAX request
    • Yaf_Request_Simple::__clone - The __clone purpose
    • Yaf_Request_Simple::__construct - Constructor of Yaf_Request_Simple
    • Yaf_Response_Abstract::appendBody - Append to response body
    • Yaf_Response_Abstract::clearBody - Discard all exists response body
    • Yaf_Response_Abstract::clearHeaders - Discard all set headers
    • Yaf_Response_Abstract::getBody - Retrieve a exists content
    • Yaf_Response_Abstract::getHeader - The getHeader purpose
    • Yaf_Response_Abstract::prependBody - The prependBody purpose
    • Yaf_Response_Abstract::response - Send response
    • Yaf_Response_Abstract::setAllHeaders - The setAllHeaders purpose
    • Yaf_Response_Abstract::setBody - Set content to response
    • Yaf_Response_Abstract::setHeader - Set reponse header
    • Yaf_Response_Abstract::setRedirect - The setRedirect purpose
    • Yaf_Response_Abstract::__clone - The __clone purpose
    • Yaf_Response_Abstract::__construct - The __construct purpose
    • Yaf_Response_Abstract::__destruct - The __destruct purpose
    • Yaf_Response_Abstract::__toString - Retrieve all bodys as string
    • Yaf_Router::addConfig - Add config-defined routes into Router
    • Yaf_Router::addRoute - Add new Route into Router
    • Yaf_Router::getCurrentRoute - Get the effective route name
    • Yaf_Router::getRoute - Retrieve a route by name
    • Yaf_Router::getRoutes - Retrieve registered routes
    • Yaf_Router::route - The route purpose
    • Yaf_Router::__construct - Yaf_Router constructor
    • Yaf_Route_Interface::assemble - Assemble a request
    • Yaf_Route_Interface::route - Route a request
    • Yaf_Route_Map::assemble - Assemble a url
    • Yaf_Route_Map::route - The route purpose
    • Yaf_Route_Map::__construct - The __construct purpose
    • Yaf_Route_Regex::assemble - Assemble a url
    • Yaf_Route_Regex::route - The route purpose
    • Yaf_Route_Regex::__construct - Yaf_Route_Regex constructor
    • Yaf_Route_Rewrite::assemble - Assemble a url
    • Yaf_Route_Rewrite::route - The route purpose
    • Yaf_Route_Rewrite::__construct - Yaf_Route_Rewrite constructor
    • Yaf_Route_Simple::assemble - Assemble a url
    • Yaf_Route_Simple::route - Route a request
    • Yaf_Route_Simple::__construct - Yaf_Route_Simple constructor
    • Yaf_Route_Static::assemble - Assemble a url
    • Yaf_Route_Static::match - The match purpose
    • Yaf_Route_Static::route - Route a request
    • Yaf_Route_Supervar::assemble - Assemble a url
    • Yaf_Route_Supervar::route - The route purpose
    • Yaf_Route_Supervar::__construct - The __construct purpose
    • Yaf_Session::count - The count purpose
    • Yaf_Session::current - The current purpose
    • Yaf_Session::del - The del purpose
    • Yaf_Session::getInstance - The getInstance purpose
    • Yaf_Session::has - The has purpose
    • Yaf_Session::key - The key purpose
    • Yaf_Session::next - The next purpose
    • Yaf_Session::offsetExists - The offsetExists purpose
    • Yaf_Session::offsetGet - The offsetGet purpose
    • Yaf_Session::offsetSet - The offsetSet purpose
    • Yaf_Session::offsetUnset - The offsetUnset purpose
    • Yaf_Session::rewind - The rewind purpose
    • Yaf_Session::start - The start purpose
    • Yaf_Session::valid - The valid purpose
    • Yaf_Session::__clone - The __clone purpose
    • Yaf_Session::__construct - Constructor of Yaf_Session
    • Yaf_Session::__get - The __get purpose
    • Yaf_Session::__isset - The __isset purpose
    • Yaf_Session::__set - The __set purpose
    • Yaf_Session::__sleep - The __sleep purpose
    • Yaf_Session::__unset - The __unset purpose
    • Yaf_Session::__wakeup - The __wakeup purpose
    • Yaf_View_Interface::assign - Assign value to View engine
    • Yaf_View_Interface::display - Render and output a template
    • Yaf_View_Interface::getScriptPath - The getScriptPath purpose
    • Yaf_View_Interface::render - Render a template
    • Yaf_View_Interface::setScriptPath - The setScriptPath purpose
    • Yaf_View_Simple::assign - Assign values
    • Yaf_View_Simple::assignRef - The assignRef purpose
    • Yaf_View_Simple::clear - Clear Assigned values
    • Yaf_View_Simple::display - Render and display
    • Yaf_View_Simple::eval - Render template
    • Yaf_View_Simple::getScriptPath - Get templates directory
    • Yaf_View_Simple::render - Render template
    • Yaf_View_Simple::setScriptPath - Set tempaltes directory
    • Yaf_View_Simple::__construct - Constructor of Yaf_View_Simple
    • Yaf_View_Simple::__get - Retrieve assigned variable
    • Yaf_View_Simple::__isset - The __isset purpose
    • Yaf_View_Simple::__set - Set value to engine
    • yaml_emit - Returns the YAML representation of a value
    • yaml_emit_file - Send the YAML representation of a value to a file
    • yaml_parse - Parse a YAML stream
    • yaml_parse_file - Parse a YAML stream from a file
    • yaml_parse_url - Parse a Yaml stream from a URL
    • Yar_Client::setOpt - Set calling contexts
    • Yar_Client::__call - Call service
    • Yar_Client::__construct - Create a client
    • Yar_Client_Exception::getType - Retrieve exception's type
    • Yar_Concurrent_Client::call - Register a concurrent call
    • Yar_Concurrent_Client::loop - Send all calls
    • Yar_Concurrent_Client::reset - Clean all registered calls
    • Yar_Server::handle - Start RPC Server
    • Yar_Server::__construct - Register a server
    • Yar_Server_Exception::getType - Retrieve exception's type
    • yaz_addinfo - Returns additional error information
    • yaz_ccl_conf - Configure CCL parser
    • yaz_ccl_parse - Invoke CCL Parser
    • yaz_close - Close YAZ connection
    • yaz_connect - Prepares for a connection to a Z39.50 server
    • yaz_database - Specifies the databases within a session
    • yaz_element - Specifies Element-Set Name for retrieval
    • yaz_errno - Returns error number
    • yaz_error - Returns error description
    • yaz_es - Prepares for an Extended Service Request
    • yaz_es_result - Inspects Extended Services Result
    • yaz_get_option - Returns value of option for connection
    • yaz_hits - Returns number of hits for last search
    • yaz_itemorder - Prepares for Z39.50 Item Order with an ILL-Request package
    • yaz_present - Prepares for retrieval (Z39.50 present)
    • yaz_range - Specifies a range of records to retrieve
    • yaz_record - Returns a record
    • yaz_scan - Prepares for a scan
    • yaz_scan_result - Returns Scan Response result
    • yaz_schema - Specifies schema for retrieval
    • yaz_search - Prepares for a search
    • yaz_set_option - Sets one or more options for connection
    • yaz_sort - Sets sorting criteria
    • yaz_syntax - Specifies the preferred record syntax for retrieval
    • yaz_wait - Wait for Z39.50 requests to complete
    • yp_all - Traverse the map and call a function on each entry
    • yp_cat - Return an array containing the entire map
    • yp_errno - Returns the error code of the previous operation
    • yp_err_string - Returns the error string associated with the given error code
    • yp_first - Returns the first key-value pair from the named map
    • yp_get_default_domain - Fetches the machine's default NIS domain
    • yp_master - Returns the machine name of the master NIS server for a map
    • yp_match - Returns the matched line
    • yp_next - Returns the next key-value pair in the named map
    • yp_order - Returns the order number for a map
  • z
    • zend_logo_guid - Gets the Zend guid
    • zend_thread_id - Returns a unique identifier for the current thread
    • zend_version - Gets the version of the current Zend engine
    • 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::close - Close the active archive (opened or newly created)
    • ZipArchive::count - Counts the number of files in the achive
    • 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::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::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::setArchiveComment - Set the comment 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 context options - Zip context option listing
    • 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 Streams
    • 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
    • ZMQ::__construct - ZMQ constructor
    • ZMQContext::getOpt - Get context option
    • ZMQContext::getSocket - Create a new socket
    • ZMQContext::isPersistent - Whether the context is persistent
    • ZMQContext::setOpt - Set a socket option
    • ZMQContext::__construct - Construct a new ZMQContext object
    • ZMQDevice::getIdleTimeout - Get the idle timeout
    • ZMQDevice::getTimerTimeout - Get the timer timeout
    • ZMQDevice::run - Run the new device
    • ZMQDevice::setIdleCallback - Set the idle callback function
    • ZMQDevice::setIdleTimeout - Set the idle timeout
    • ZMQDevice::setTimerCallback - Set the timer callback function
    • ZMQDevice::setTimerTimeout - Set the timer timeout
    • ZMQDevice::__construct - Construct a new device
    • ZMQPoll::add - Add item to the poll set
    • ZMQPoll::clear - Clear the poll set
    • ZMQPoll::count - Count items in the poll set
    • ZMQPoll::getLastErrors - Get poll errors
    • ZMQPoll::poll - Poll the items
    • ZMQPoll::remove - Remove item from poll set
    • ZMQSocket::bind - Bind the socket
    • ZMQSocket::connect - Connect the socket
    • ZMQSocket::disconnect - Disconnect a socket
    • ZMQSocket::getEndpoints - Get list of endpoints
    • ZMQSocket::getPersistentId - Get the persistent id
    • ZMQSocket::getSocketType - Get the socket type
    • ZMQSocket::getSockOpt - Get socket option
    • ZMQSocket::isPersistent - Whether the socket is persistent
    • ZMQSocket::recv - Receives a message
    • ZMQSocket::recvMulti - Receives a multipart message
    • ZMQSocket::send - Sends a message
    • ZMQSocket::sendmulti - Sends a multipart message
    • ZMQSocket::setSockOpt - Set a socket option
    • ZMQSocket::unbind - Unbind the socket
    • ZMQSocket::__construct - Construct a new ZMQSocket
    • Zookeeper::addAuth - Specify application credentials
    • Zookeeper::close - Close the zookeeper handle and free up any resources
    • Zookeeper::connect - Create a handle to used communicate with zookeeper
    • Zookeeper::create - Create a node synchronously
    • Zookeeper::delete - Delete a node in zookeeper synchronously
    • Zookeeper::exists - Checks the existence of a node in zookeeper synchronously
    • Zookeeper::get - Gets the data associated with a node synchronously
    • Zookeeper::getAcl - Gets the acl associated with a node synchronously
    • Zookeeper::getChildren - Lists the children of a node synchronously
    • Zookeeper::getClientId - Return the client session id, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE)
    • Zookeeper::getConfig - Get instance of ZookeeperConfig
    • Zookeeper::getRecvTimeout - Return the timeout for this session, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE). This value may change after a server re-connect
    • Zookeeper::getState - Get the state of the zookeeper connection
    • Zookeeper::isRecoverable - Checks if the current zookeeper connection state can be recovered
    • Zookeeper::set - Sets the data associated with a node
    • Zookeeper::setAcl - Sets the acl associated with a node synchronously
    • Zookeeper::setDebugLevel - Sets the debugging level for the library
    • Zookeeper::setDeterministicConnOrder - Enable/disable quorum endpoint order randomization
    • Zookeeper::setLogStream - Sets the stream to be used by the library for logging
    • Zookeeper::setWatcher - Set a watcher function
    • Zookeeper::__construct - Create a handle to used communicate with zookeeper
    • ZookeeperConfig::add - Add servers to the ensemble
    • ZookeeperConfig::get - Gets the last committed configuration of the ZooKeeper cluster as it is known to the server to which the client is connected, synchronously
    • ZookeeperConfig::remove - Remove servers from the ensemble
    • ZookeeperConfig::set - Change ZK cluster ensemble membership and roles of ensemble peers
    • zookeeper_dispatch - Calls callbacks for pending operations
  • _
    • __autoload - Attempt to load undefined class
    • __halt_compiler - Halts the compiler execution


Example listing

List of all the examples in the manual

  • Example#0 - An introductory example
  • Example#1 - Our first PHP script: hello.php
  • Example#2 - Get system information from PHP
  • Example#3 - Printing a variable (Array element)
  • Example#4 - Example using control structures and functions
  • Example#5 - Mixing both HTML and PHP modes
  • Example#6 - A simple HTML form
  • Example#7 - Printing data from our form
  • Example#8 - Installation Instructions (Apache Shared Module Version) for PHP
  • Example#9 - Installation Instructions (Static Module Installation for Apache) for PHP
  • Example#10 - Example commands for restarting Apache
  • Example#11 -
  • Example#12 -
  • Example#13 -
  • Example#14 -
  • Example#15 -
  • Example#16 -
  • Example#17 -
  • Example#18 -
  • Example#19 -
  • Example#20 -
  • Example#21 -
  • Example#22 -
  • Example#23 -
  • Example#24 - Partial lighttpd.conf
  • Example#25 - Spawning FastCGI Responders
  • Example#26 - Connecting to remote php-fastcgi instances
  • Example#27 -
  • Example#28 -
  • Example#29 - OpenBSD Package Install Example
  • Example#30 - Debian Install Example with Apache 2
  • Example#31 - Stopping and starting Apache once PHP is installed
  • Example#32 - Methods for listing additional PHP 5 packages
  • Example#33 - Install PHP with MySQL, cURL
  • Example#34 - Recommended OpCache configuration
  • Example#35 - Recommended WinCache configuration
  • Example#36 - Command line to configure IIS and PHP
  • Example#37 - PHP 5 package structure
  • Example#38 - CGI and FastCGI settings in php.ini
  • Example#39 - Configuring FastCGI extension to handle PHP requests
  • Example#40 - Configuring file access permissions
  • Example#41 - Configuring FastCGI and PHP recycling
  • Example#42 - Configuring FastCGI timeout settings
  • Example#43 - Changing the location of php.ini file
  • Example#44 - CGI and FastCGI settings in php.ini
  • Example#45 - Creating IIS FastCGI process pool
  • Example#46 - Creating handler mapping for PHP requests
  • Example#47 - Determining the account used as IIS anonymous identity
  • Example#48 - Configuring file access permissions
  • Example#49 - Set index.php as a default document in IIS
  • Example#50 - Configuring FastCGI and PHP recycling
  • Example#51 - Configuring FastCGI timeout settings
  • Example#52 - Changing the location of php.ini file
  • Example#53 - PHP as an Apache 1.3.x module
  • Example#54 - PHP and Apache 1.3.x as CGI
  • Example#55 - PHP and Apache 2.x as handler
  • Example#56 -
  • Example#57 - PHP and Apache 2.x as CGI
  • Example#58 - Configure Apache to run PHP as FastCGI
  • Example#59 - ISAPI configuration of Sambar
  • Example#60 - Enable Bzip2 extension for PHP-Windows
  • Example#61 - Registry changes
  • Example#62 - Passing environment variables and PHP settings to a pool
  • Example#63 - set PHP settings in nginx.conf
  • Example#64 - phpinfo call
  • Example#65 - php.ini Environment Variables
  • Example#66 - php.ini example
  • Example#67 - Apache configuration example
  • Example#68 - Advanced escaping using conditions
  • Example#69 - PHP Opening and Closing Tags
  • Example#70 - Integer literals
  • Example#71 - Integer overflow on a 32-bit system
  • Example#72 - Integer overflow on a 64-bit system
  • Example#73 - Invalid example
  • Example#74 - Valid example
  • Example#75 - Heredoc string quoting example
  • Example#76 - Heredoc in arguments example
  • Example#77 - Using Heredoc to initialize static values
  • Example#78 - Using double quotes in Heredoc
  • Example#79 - Nowdoc string quoting example
  • Example#80 - Nowdoc string quoting example with variables
  • Example#81 - Static data example
  • Example#82 - Simple syntax example
  • Example#83 - Negative numeric indices
  • Example#84 - Some string examples
  • Example#85 - Differences between PHP 5.3 and PHP 5.4
  • Example#86 - A simple array
  • Example#87 - Type Casting and Overwriting example
  • Example#88 - Mixed integer and string keys
  • Example#89 - Indexed arrays without key
  • Example#90 - Keys not on all elements
  • Example#91 - Accessing array elements
  • Example#92 - Array dereferencing
  • Example#93 - Using array()
  • Example#94 - Collection
  • Example#95 - Changing element in the loop
  • Example#96 - One-based index
  • Example#97 - Filling an array
  • Example#98 - Sorting an array
  • Example#99 - Recursive and multi-dimensional arrays
  • Example#100 - Iterable parameter type example
  • Example#101 - Iterable parameter default value example
  • Example#102 - Iterable return type example
  • Example#103 - Iterable generator return type example
  • Example#104 - Iterable type variance example
  • Example#105 - Callback function examples
  • Example#106 - Callback example using a Closure
  • Example#107 - Default values of uninitialized variables
  • Example#108 - Using global
  • Example#109 - Using $GLOBALS instead of global
  • Example#110 - Example demonstrating superglobals and scope
  • Example#111 - Example demonstrating need for static variables
  • Example#112 - Example use of static variables
  • Example#113 - Static variables with recursive functions
  • Example#114 - Declaring static variables
  • Example#115 - Variable property example
  • Example#116 - A simple HTML form
  • Example#117 - Accessing data from a simple POST HTML form
  • Example#118 - Old methods of accessing user input
  • Example#119 - More complex form variables
  • Example#120 - A setcookie example
  • Example#121 - Valid and invalid constant names
  • Example#122 - Defining Constants
  • Example#123 - Defining Constants using the const keyword
  • Example#124 - Associativity
  • Example#125 - Undefined order of evaluation
  • Example#126 - +, - and . have the same precedence
  • Example#127 - Assigning by reference
  • Example#128 - Bitwise AND, OR and XOR operations on integers
  • Example#129 - Bitwise XOR operations on strings
  • Example#130 - Bit shifting on integers
  • Example#131 - Boolean/null comparison
  • Example#132 - Transcription of standard array comparison
  • Example#133 - Assigning a default value
  • Example#134 - Non-obvious Ternary Behaviour
  • Example#135 - Assigning a default value
  • Example#136 - Nesting null coalescing operator
  • Example#137 - Arithmetic Operations on Character Variables
  • Example#138 - Logical operators illustrated
  • Example#139 - Comparing arrays
  • Example#140 - Using instanceof with classes
  • Example#141 - Using instanceof with inherited classes
  • Example#142 - Using instanceof to check if object is not an instanceof a class
  • Example#143 - Using instanceof with interfaces
  • Example#144 - Using instanceof with other variables
  • Example#145 - Using instanceof to test other variables
  • Example#146 - Avoiding classname lookups and fatal errors with instanceof in PHP 5.0
  • Example#147 - switch structure
  • Example#148 - switch structure allows usage of strings
  • Example#149 - Tick usage example
  • Example#150 - Ticks usage example
  • Example#151 - Declaring an encoding for the script.
  • Example#152 - Basic include example
  • Example#153 - Including within functions
  • Example#154 - include through HTTP
  • Example#155 - Comparing return value of include
  • Example#156 - include and the return statement
  • Example#157 - Using output buffering to include a PHP file into a string
  • Example#158 - goto example
  • Example#159 - goto loop example
  • Example#160 - This will not work
  • Example#161 - Pseudo code to demonstrate function uses
  • Example#162 - Conditional functions
  • Example#163 - Functions within functions
  • Example#164 - Recursive functions
  • Example#165 - Passing arrays to functions
  • Example#166 - Passing function parameters by reference
  • Example#167 - Use of default parameters in functions
  • Example#168 - Using non-scalar types as default values
  • Example#169 - Incorrect usage of default function arguments
  • Example#170 - Correct usage of default function arguments
  • Example#171 -
  • Example#172 - Basic class type declaration
  • Example#173 - Basic interface type declaration
  • Example#174 - Typed pass-by-reference Parameters
  • Example#175 - Nullable type declaration
  • Example#176 - Strict typing
  • Example#177 - Weak typing
  • Example#178 - Catching TypeError
  • Example#179 - Using ... to access variable arguments
  • Example#180 - Using ... to provide arguments
  • Example#181 - Type hinted variable arguments
  • Example#182 - Accessing variable arguments in PHP 5.5 and earlier
  • Example#183 - Use of return
  • Example#184 - Returning an array to get multiple values
  • Example#185 - Returning a reference from a function
  • Example#186 - Basic return type declaration
  • Example#187 - Strict mode in action
  • Example#188 - Returning an object
  • Example#189 - Nullable return type declaration (as of PHP 7.1.0)
  • Example#190 - Variable function example
  • Example#191 - Variable method example
  • Example#192 - Variable method example with static properties
  • Example#193 - Complex callables
  • Example#194 - Anonymous function example
  • Example#195 - Anonymous function variable assignment example
  • Example#196 - Inheriting variables from the parent scope
  • Example#197 - Closures and scoping
  • Example#198 - Automatic binding of $this
  • Example#199 - Attempting to use $this inside a static anonymous function
  • Example#200 - Attempting to bind an object to a static anonymous function
  • Example#201 - Simple Class definition
  • Example#202 - Some examples of the $this pseudo-variable
  • Example#203 - Creating an instance
  • Example#204 - Object Assignment
  • Example#205 - Creating new objects
  • Example#206 - Access member of newly created object
  • Example#207 - Property access vs. method call
  • Example#208 - Calling an anonymous function stored in a property
  • Example#209 - Simple Class Inheritance
  • Example#210 - Class name resolution
  • Example#211 - property declarations
  • Example#212 - Example of using a nowdoc to initialize a property
  • Example#213 - Example of typed properties
  • Example#214 - Defining and using a constant
  • Example#215 - Static data example
  • Example#216 - Namespaced ::class example
  • Example#217 - Constant expression example
  • Example#218 - Class constant visibility modifiers
  • Example#219 - Autoload example
  • Example#220 - Autoload other example
  • Example#221 - Autoloading with exception handling for 5.3.0+
  • Example#222 - Autoloading with exception handling for 5.3.0+ - Missing custom exception
  • Example#223 - using new unified constructors
  • Example#224 - Constructors in namespaced classes
  • Example#225 - Destructor Example
  • Example#226 - Property declaration
  • Example#227 - Method Declaration
  • Example#228 - Constant Declaration as of PHP 7.1.0
  • Example#229 - Accessing private members of the same object type
  • Example#230 - Inheritance Example
  • Example#231 - :: from outside the class definition
  • Example#232 - :: from inside the class definition
  • Example#233 - Calling a parent's method
  • Example#234 - Static method example
  • Example#235 - Static property example
  • Example#236 - Abstract class example
  • Example#237 - Abstract class example
  • Example#238 - Interface example
  • Example#239 - Extendable Interfaces
  • Example#240 - Multiple interface inheritance
  • Example#241 - Interfaces with constants
  • Example#242 - Trait example
  • Example#243 - Precedence Order Example
  • Example#244 - Alternate Precedence Order Example
  • Example#245 - Multiple Traits Usage
  • Example#246 - Conflict Resolution
  • Example#247 - Changing Method Visibility
  • Example#248 - Traits Composed from Traits
  • Example#249 - Express Requirements by Abstract Methods
  • Example#250 - Static Variables
  • Example#251 - Static Methods
  • Example#252 - Defining Properties
  • Example#253 - Conflict Resolution
  • Example#254 - Overloading properties via the __get(), __set(), __isset() and __unset() methods
  • Example#255 - Overloading methods via the __call() and __callStatic() methods
  • Example#256 - Simple Object Iteration
  • Example#257 - Object Iteration implementing Iterator
  • Example#258 - Object Iteration implementing IteratorAggregate
  • Example#259 - Sleep and wakeup
  • Example#260 - Simple example
  • Example#261 - Using __invoke()
  • Example#262 - Using __set_state() (since PHP 5.1.0)
  • Example#263 - Using __debugInfo()
  • Example#264 - Final methods example
  • Example#265 - Final class example
  • Example#266 - Cloning an object
  • Example#267 - Access member of freshly cloned object
  • Example#268 - Example of object comparison in PHP 5
  • Example#269 - self:: usage
  • Example#270 - static:: simple usage
  • Example#271 - static:: usage in a non-static context
  • Example#272 - Forwarding and non-forwarding calls
  • Example#273 - References and Objects
  • Example#274 - Namespace syntax example
  • Example#275 - Declaring a single namespace
  • Example#276 - Declaring a single namespace
  • Example#277 - Declaring a single namespace with hierarchy
  • Example#278 - Declaring multiple namespaces, simple combination syntax
  • Example#279 - Declaring multiple namespaces, bracketed syntax
  • Example#280 - Declaring multiple namespaces and unnamespaced code
  • Example#281 - Declaring multiple namespaces and unnamespaced code
  • Example#282 - Accessing global classes, functions and constants from within a namespace
  • Example#283 - Dynamically accessing elements
  • Example#284 - Dynamically accessing namespaced elements
  • Example#285 - __NAMESPACE__ example, namespaced code
  • Example#286 - __NAMESPACE__ example, global code
  • Example#287 - using __NAMESPACE__ for dynamic name construction
  • Example#288 - the namespace operator, inside a namespace
  • Example#289 - the namespace operator, in global code
  • Example#290 - importing/aliasing with the use operator
  • Example#291 - importing/aliasing with the use operator, multiple use statements combined
  • Example#292 - Importing and dynamic names
  • Example#293 - Importing and fully qualified names
  • Example#294 - Illegal importing rule
  • Example#295 - Using global space specification
  • Example#296 - Accessing global classes inside a namespace
  • Example#297 - global functions/constants fallback inside a namespace
  • Example#298 - Name resolutions illustrated
  • Example#299 - Accessing global classes outside a namespace
  • Example#300 - Accessing global classes outside a namespace
  • Example#301 - Accessing internal classes in namespaces
  • Example#302 - Accessing internal classes, functions or constants in namespaces
  • Example#303 - Fully Qualified names
  • Example#304 - Qualified names
  • Example#305 - Unqualified class names
  • Example#306 - Unqualified function or constant names
  • Example#307 - Dangers of using namespaced names inside a double-quoted string
  • Example#308 - Undefined constants
  • Example#309 - Undefined constants
  • Example#310 - The Built in Exception class
  • Example#311 - Extending the Exception class (PHP 5.3.0+)
  • Example#312 - Throwing an Exception
  • Example#313 - Exception handling with a finally block
  • Example#314 - Interaction between the finally block and return
  • Example#315 - Nested Exception
  • Example#316 - Multi catch exception handling
  • Example#317 - Implementing range as a generator
  • Example#318 - A simple example of yielding values
  • Example#319 - Yielding a key/value pair
  • Example#320 - Yielding NULLs
  • Example#321 - Yielding values by reference
  • Example#322 - yield from with iterator_to_array
  • Example#323 - Basic use of yield from
  • Example#324 - yield from and return values
  • Example#325 - Using references with undefined variables
  • Example#326 - Referencing global variables inside functions
  • Example#327 - References and foreach statement
  • Example#328 - $GLOBALS example
  • Example#329 - $_SERVER example
  • Example#330 - $_GET example
  • Example#331 - $_POST example
  • Example#332 - $_ENV example
  • Example#333 - $_COOKIE example
  • Example#334 - $php_errormsg example
  • Example#335 - $http_response_header example
  • Example#336 - $argc example
  • Example#337 - $argv example
  • Example#338 - Exception::getMessage example
  • Example#339 - Exception::getPrevious example
  • Example#340 - Exception::getCode example
  • Example#341 - Exception::getFile example
  • Example#342 - Exception::getLine example
  • Example#343 - Exception::getTrace example
  • Example#344 - Exception::getTraceAsString example
  • Example#345 - Exception::__toString example
  • Example#346 - Use set_error_handler to change error messages into ErrorException.
  • Example#347 - ErrorException::getSeverity example
  • Example#348 - Error::getMessage example
  • Example#349 - Error::getPrevious example
  • Example#350 - Error::getCode example
  • Example#351 - Error::getFile example
  • Example#352 - Error::getLine example
  • Example#353 - Error::getTrace example
  • Example#354 - Error::getTraceAsString example
  • Example#355 - Error::__toString example
  • Example#356 - Basic usage
  • Example#357 - Basic usage
  • Example#358 - Basic usage
  • Example#359 - ArrayAccess::offsetExists example
  • Example#360 - Basic usage
  • Example#361 - Closure::bind example
  • Example#362 - Closure::bindTo example
  • Example#363 - Closure::call example
  • Example#364 - Generator::getReturn example
  • Example#365 - Generator::key example
  • Example#366 - Using Generator::send to inject values
  • Example#367 - Throwing an exception into a generator
  • Example#368 - Basic WeakReference Usage
  • Example#369 - Basic bindto usage example
  • Example#370 - Fetch a page and send POST data
  • Example#371 - Ignore redirects but fetch headers and content
  • Example#372 - Fetch a page and send POST data
  • Example#373 - Basic password usage example
  • Example#374 - Detecting which URL we ended up on after redirects
  • Example#375 - php://temp/maxmemory
  • Example#376 - php://filter/resource=<stream to be filtered>
  • Example#377 - php://filter/read=<filter list to apply to read chain>
  • Example#378 - php://filter/write=<filter list to apply to write chain>
  • Example#379 - php://memory and php://temp are not reusable
  • Example#380 - Print data:// contents
  • Example#381 - Fetch the media type
  • Example#382 - Basic usage
  • Example#383 - Opening a stream from an active connection
  • Example#384 - This $session variable must be kept available!
  • Example#385 - Traversing a RAR archive
  • Example#386 - Opening an encrypted file (header encryption)
  • Example#387 - Poor variable checking leads to....
  • Example#388 - ... A filesystem attack
  • Example#389 - More secure file name checking
  • Example#390 - More secure file name checking
  • Example#391 - Script vulnerable to null bytes
  • Example#392 - Correctly validating the input
  • Example#393 - Hashing password field
  • Example#394 - Hashing password using crypts
  • Example#395 - Splitting the result set into pages ... and making superusers (PostgreSQL)
  • Example#396 - Listing out articles ... and some passwords (any database server)
  • Example#397 - From resetting a password ... to gaining more privileges (any database server)
  • Example#398 - Attacking the database hosts operating system (MSSQL Server)
  • Example#399 - A more secure way to compose a query for paging
  • Example#400 - Attacking Variables with a custom HTML page
  • Example#401 - Exploiting common debugging variables
  • Example#402 - Finding dangerous variables with E_ALL
  • Example#403 - Example misuse with register_globals = on
  • Example#404 - Example use of sessions with register_globals on or off
  • Example#405 - Detecting simple variable poisoning
  • Example#406 - Dangerous Variable Usage
  • Example#407 - Disabling magic quotes server side
  • Example#408 - Disabling magic quotes at runtime
  • Example#409 - Hiding PHP as another language
  • Example#410 - Using unknown types for PHP extensions
  • Example#411 - Using HTML types for PHP extensions
  • Example#412 - Basic HTTP Authentication example
  • Example#413 - Digest HTTP Authentication example
  • Example#414 - HTTP Authentication example forcing a new name/password
  • Example#415 - A simple XForms search form
  • Example#416 - Using an XForm to populate $_POST
  • Example#417 - File Upload Form
  • Example#418 - Validating file uploads
  • Example#419 - Uploading array of files
  • Example#420 - Uploading multiple files
  • Example#421 - Saving HTTP PUT files
  • Example#422 - Getting the title of a remote page
  • Example#423 - Storing data on a remote server
  • Example#424 - Example showing the difference to the CGI SAPI:
  • Example#425 -
  • Example#426 - Printing built in (and loaded) PHP and Zend modules
  • Example#427 - Getting a syntax error when using double quotes
  • Example#428 - Using single quotes to prevent the shell's variable substitution
  • Example#429 - Using the -B, -R and -E options to count the number of lines of a project.
  • Example#430 - Using -v to get the SAPI name and the version of PHP and Zend
  • Example#431 - --ini example
  • Example#432 - basic --rf usage
  • Example#433 - --rc example
  • Example#434 - --re example
  • Example#435 - --ri example
  • Example#436 - Execute PHP script as shell script
  • Example#437 - Script intended to be run from command line (script.php)
  • Example#438 - Batch file to run a command line PHP script (script.bat)
  • Example#439 - Executing code using the interactive shell
  • Example#440 - Tab completion
  • Example#441 - Setting php.ini settings in the interactive shell
  • Example#442 - Starting the web server
  • Example#443 - Starting with a specific document root directory
  • Example#444 - Using a Router Script
  • Example#445 - Checking for CLI Web Server Use
  • Example#446 - Handling Unsupported File Types
  • Example#447 - Accessing the CLI Web Server From Remote Machines
  • Example#448 - Creating a new zval container
  • Example#449 - Displaying zval information
  • Example#450 - Increasing refcount of a zval
  • Example#451 - Decreasing zval refcount
  • Example#452 - Creating a array zval
  • Example#453 - Adding already existing element to an array
  • Example#454 - Removing an element from an array
  • Example#455 - Adding the array itself as an element of it self
  • Example#456 - Unsetting $a
  • Example#457 - Memory usage example
  • Example#458 - GC performance influences
  • Example#459 - Running the above script
  • Example#460 - Recompiling PHP to enable GC benchmarking
  • Example#461 - GC statistics
  • Example#462 - all_probes.d for tracing all PHP Static Probes with DTrace
  • Example#463 - all_probes.stp for tracing all PHP Static Probes with SystemTap
  • Example#464 - An apc.rfc1867 example
  • Example#465 - A apc_add example
  • Example#466 - apc_bin_load example
  • Example#467 - A apc_cache_info example
  • Example#468 - apc_cas example
  • Example#469 - apc_dec example
  • Example#470 - apc_define_constants example
  • Example#471 - apc_delete_file example
  • Example#472 - A apc_delete example
  • Example#473 - apc_exists example
  • Example#474 - A apc_fetch example
  • Example#475 - apc_inc example
  • Example#476 - apc_load_constants example
  • Example#477 - A apc_sma_info example
  • Example#478 - A apc_store example
  • Example#479 - A APCIterator::__construct example
  • Example#480 - A apcu_add example
  • Example#481 - A apcu_cache_info example
  • Example#482 - apcu_cas example
  • Example#483 - apcu_dec example
  • Example#484 - A apcu_delete example
  • Example#485 - An apcu_entry example
  • Example#486 - apcu_exists example
  • Example#487 - A apcu_fetch example
  • Example#488 - apcu_inc example
  • Example#489 - A apcu_sma_info example
  • Example#490 - A apcu_store example
  • Example#491 - A APCUIterator::__construct example
  • Example#492 - Typical session using tcplisten
  • Example#493 - apd_callstack example
  • Example#494 - apd_clunk example
  • Example#495 - apd_continue example
  • Example#496 - apd_croak example
  • Example#497 - apd_dump_function_table example
  • Example#498 - apd_dump_persistent_resources example
  • Example#499 - apd_dump_regular_resources example
  • Example#500 - apd_echo example
  • Example#501 - apd_get_active_symbols example
  • Example#502 - apd_set_pprof_trace example
  • Example#503 - apd_set_session_trace_socket example
  • Example#504 - apd_set_session_trace example
  • Example#505 - apd_set_session example
  • Example#506 - override_function example
  • Example#507 - rename_function example
  • Example#508 - bcompiler_load_exe example
  • Example#509 - bcompiler_load example
  • Example#510 - bcompiler_parse_class example
  • Example#511 - bcompiler_read example
  • Example#512 - bcompiler_write_class example
  • Example#513 - bcompiler_write_constant example
  • Example#514 - bcompiler_write_exe_footer example
  • Example#515 - bcompiler_write_file example
  • Example#516 - bcompiler_write_footer example
  • Example#517 - bcompiler_write_function example
  • Example#518 - bcompiler_write_functions_from_file example
  • Example#519 - bcompiler_write_header example
  • Example#520 - blenc_encrypt example
  • Example#521 - Using error handling in a script
  • Example#522 - debug_backtrace example
  • Example#523 - debug_print_backtrace example
  • Example#524 - An error_clear_last example
  • Example#525 - An error_get_last example
  • Example#526 - error_log examples
  • Example#527 - error_reporting examples
  • Example#528 - restore_error_handler example
  • Example#529 - restore_exception_handler example
  • Example#530 - Error handling with set_error_handler and trigger_error
  • Example#531 - set_exception_handler example
  • Example#532 - trigger_error example
  • Example#533 - Calling a function from shared library
  • Example#534 - Calling a function, returning a structure through an argument
  • Example#535 - Accessing existing C variables
  • Example#536 - Creating and Modifying C variables
  • Example#537 - Working with C arrays
  • Example#538 -
  • Example#539 -
  • Example#540 - Getting the data within the PHP application itself (function)
  • Example#541 - Example use of gengraph.php
  • Example#542 - Listing data via inclued dumps (configuration)
  • Example#543 - inclued_get_data example
  • Example#544 - Creating large array in a function
  • Example#545 - Output Control example
  • Example#546 - Output rewrite example
  • Example#547 - ob_end_clean example
  • Example#548 - ob_end_flush example
  • Example#549 - A simple ob_get_clean example
  • Example#550 - A simple ob_get_contents example
  • Example#551 - ob_get_flush example
  • Example#552 - A simple ob_get_length example
  • Example#553 - ob_gzhandler example
  • Example#554 - ob_list_handlers example
  • Example#555 - User defined callback function example
  • Example#556 - Creating an uneraseable output buffer in a way compatible with both PHP 5.3 and 5.4
  • Example#557 - output_add_rewrite_var example
  • Example#558 - output_reset_rewrite_vars example
  • Example#559 - assert_options example
  • Example#560 - Handle a failed assertion with a custom handler
  • Example#561 - Using a custom handler to print a description
  • Example#562 - Expectations without a custom exception
  • Example#563 - Expectations with a custom exception
  • Example#564 - cli_get_process_title example
  • Example#565 - cli_set_process_title example
  • Example#566 - dl examples
  • Example#567 - extension_loaded example
  • Example#568 - A gc_enabled example
  • Example#569 - gc_status Usage
  • Example#570 - get_current_user example
  • Example#571 - get_defined_constants Example
  • Example#572 - Prints the XML functions
  • Example#573 - get_include_path example
  • Example#574 - get_included_files example
  • Example#575 - get_loaded_extensions Example
  • Example#576 - get_magic_quotes_gpc example
  • Example#577 - get_magic_quotes_runtime example
  • Example#578 - Unfiltered get_resources
  • Example#579 - Filtered get_resources
  • Example#580 - getenv Example
  • Example#581 - getlastmod example
  • Example#582 - getopt example: The basics
  • Example#583 - getopt example: Introducing long options
  • Example#584 - getopt example: Passing multiple options as one
  • Example#585 - getopt example: Using optind
  • Example#586 - getrusage example
  • Example#587 - ini_get_all examples
  • Example#588 - Disabling details
  • Example#589 - A few ini_get examples
  • Example#590 - ini_restore example
  • Example#591 - Setting an ini option
  • Example#592 - A memory_get_usage example
  • Example#593 - php_ini_loaded_file example
  • Example#594 - A simple example to list the returned ini files
  • Example#595 - php_logo_guid example
  • Example#596 - php_sapi_name example
  • Example#597 - Some php_uname examples
  • Example#598 - A few OS related constant examples
  • Example#599 - Prints the general credits
  • Example#600 - Prints the core developers and the documentation group
  • Example#601 - Printing all the credits
  • Example#602 - phpinfo Example
  • Example#603 - phpversion example
  • Example#604 - PHP_VERSION_ID example and usage
  • Example#605 - Setting an environment variable
  • Example#606 - restore_include_path example
  • Example#607 - set_include_path example
  • Example#608 - Adding to the include path
  • Example#609 - set_magic_quotes_runtime example
  • Example#610 - sys_get_temp_dir example
  • Example#611 - version_compare examples
  • Example#612 - zend_logo_guid example
  • Example#613 - zend_thread_id example
  • Example#614 - zend_version example
  • Example#615 - Custom Superglobals with runkit.superglobal=_FOO,_BAR in php.ini
  • Example#616 - Instantiating a restricted sandbox
  • Example#617 - Working with variables in a sandbox
  • Example#618 - Calling sandbox functions
  • Example#619 - Passing arguments to sandbox functions
  • Example#620 - Working with variables in a sandbox
  • Example#621 - Accessing parental variables
  • Example#622 - A runkit_class_adopt example
  • Example#623 - A runkit_class_emancipate example
  • Example#624 - A runkit_function_add example
  • Example#625 - A runkit_function_copy example
  • Example#626 - A runkit_function_redefine example
  • Example#627 - runkit_import example
  • Example#628 - runkit_method_add example
  • Example#629 - runkit_method_copy example
  • Example#630 - runkit_method_redefine example
  • Example#631 - runkit_method_remove example
  • Example#632 - runkit_method_rename example
  • Example#633 - runkit_return_value_used example
  • Example#634 - Feeding output to a variable
  • Example#635 - A runkit7_function_add example
  • Example#636 - A runkit7_function_copy example
  • Example#637 - A runkit7_function_redefine example
  • Example#638 - runkit7_method_add example
  • Example#639 - runkit7_method_copy example
  • Example#640 - runkit7_method_redefine example
  • Example#641 - runkit7_method_remove example
  • Example#642 - runkit7_method_rename example
  • Example#643 - Enabling and disabling scream at runtime
  • Example#644 - Basic uopz_add_function Usage
  • Example#645 - uopz_allow_exit example
  • Example#646 - uopz_backup example
  • Example#647 - uopz_compose example
  • Example#648 - uopz_copy example
  • Example#649 - Basic uopz_del_function Usage
  • Example#650 - uopz_delete example
  • Example#651 - uopz_delete class example
  • Example#652 - uopz_extend example
  • Example#653 - uopz_flags example
  • Example#654 - uopz_function example
  • Example#655 - uopz_function class example
  • Example#656 - uopz_get_exit_status example
  • Example#657 - Basic uopz_get_hook Usage
  • Example#658 - uopz_get_mock example
  • Example#659 - Basic uopz_get_property Usage
  • Example#660 - uopz_get_return example
  • Example#661 - Basic uopz_get_static Usage
  • Example#662 - uopz_implement example
  • Example#663 - uopz_overload example
  • Example#664 - uopz_redefine example
  • Example#665 - uopz_rename example
  • Example#666 - uopz_rename class example
  • Example#667 - uopz_restore example
  • Example#668 - Basic uopz_set_hook Usage
  • Example#669 - uopz_set_mock example
  • Example#670 - uopz_set_mock example
  • Example#671 - uopz_set_mock and static members
  • Example#672 - Basic uopz_set_property Usage
  • Example#673 - uopz_set_return example
  • Example#674 - uopz_set_return example
  • Example#675 - uopz_set_return class example
  • Example#676 - Basic uopz_set_static Usage
  • Example#677 - uopz_undefine example
  • Example#678 - Basic uopz_unset_hook Usage
  • Example#679 - uopz_unset_mock example
  • Example#680 - uopz_unset_return example
  • Example#681 - Weakref usage example
  • Example#682 - WeakRef usage example
  • Example#683 - Weakref::acquire example
  • Example#684 - Nested acquire/release example
  • Example#685 - Weakref::__construct example
  • Example#686 - Weakref::release example
  • Example#687 - Weakmap usage example
  • Example#688 - wincache.ignorelist example
  • Example#689 - Authentication configuration for wincache.php
  • Example#690 - Enabling WinCache session handler
  • Example#691 - Enabling WinCache functions reroutes
  • Example#692 - Reroute.ini file content
  • Example#693 - A wincache_fcache_fileinfo example
  • Example#694 - A wincache_fcache_meminfo example
  • Example#695 - Using wincache_lock
  • Example#696 - A wincache_ocache_fileinfo example
  • Example#697 - A wincache_ocache_meminfo example
  • Example#698 - A wincache_refresh_if_changed example
  • Example#699 - A wincache_rplist_fileinfo example
  • Example#700 - A wincache_rplist_meminfo example
  • Example#701 - A wincache_scache_info example
  • Example#702 - A wincache_scache_meminfo example
  • Example#703 - wincache_ucache_add with key as a string
  • Example#704 - wincache_ucache_add with key as an array
  • Example#705 - Using wincache_ucache_cas
  • Example#706 - using wincache_ucache_clear
  • Example#707 - Using wincache_ucache_dec
  • Example#708 - Using wincache_ucache_delete with key as a string
  • Example#709 - Usingwincache_ucache_delete with key as an array
  • Example#710 - Using wincache_ucache_delete with key as an array where some elements cannot be deleted
  • Example#711 - Using wincache_ucache_exists
  • Example#712 - wincache_ucache_get with key as a string
  • Example#713 - wincache_ucache_get with key as an array
  • Example#714 - Using wincache_ucache_inc
  • Example#715 - Using wincache_ucache_info
  • Example#716 - A wincache_ucache_meminfo example
  • Example#717 - wincache_ucache_set with key as a string
  • Example#718 - wincache_ucache_set with key as an array
  • Example#719 - Using wincache_unlock
  • Example#720 - Xhprof example with the optional GUI
  • Example#721 - xhprof_disable example
  • Example#722 - xhprof_enable examples
  • Example#723 - xhprof_sample_disable example
  • Example#724 - id3_get_frame_long_name example
  • Example#725 - id3_get_frame_short_name example
  • Example#726 - id3_get_genre_id example
  • Example#727 - id3_get_genre_list example
  • Example#728 - id3_get_genre_name example
  • Example#729 - id3_get_tag example
  • Example#730 - id3_get_tag example
  • Example#731 - id3_get_version example
  • Example#732 - id3_remove_tag example
  • Example#733 - id3_set_tag example
  • Example#734 - Opens a new MP3 file and read the title
  • Example#735 - Reading an OGG/Vorbis file
  • Example#736 - Encode an audio file to OGG/Vorbis
  • Example#737 - KADM5 extension overview example
  • Example#738 - Example of changing principal's password
  • Example#739 - Example of principal's creation
  • Example#740 - kadm5_delete_principal example
  • Example#741 - kadm5_get_policies example
  • Example#742 - kadm5_get_principal example
  • Example#743 - kadm5_get_principals example
  • Example#744 - KADM5 initialization example
  • Example#745 - Example of modifying principal
  • Example#746 - Using CHAP passwords
  • Example#747 - radius_acct_open example
  • Example#748 - radius_add_server example
  • Example#749 - radius_auth_open example
  • Example#750 - radius_create_request example
  • Example#751 - radius_cvt_addr example
  • Example#752 - radius_cvt_int example
  • Example#753 - radius_cvt_string example
  • Example#754 - radius_get_attr example
  • Example#755 - radius_get_tagged_attr_data example
  • Example#756 - radius_get_tagged_attr_tag example
  • Example#757 - radius_get_vendor_attr example
  • Example#758 - radius_put_attr example
  • Example#759 - radius_put_int example
  • Example#760 - radius_put_string example
  • Example#761 - radius_put_vendor_attr example
  • Example#762 - Writing a string with a specified color to the screen
  • Example#763 - ncurses_getmouse example
  • Example#764 - Writing a string with a specified color to the screen
  • Example#765 - Writing a string with a specified color to the screen
  • Example#766 - ncurses_mousemask example
  • Example#767 - Writing a string with a specified color to the screen
  • Example#768 - Newt Usage Example
  • Example#769 - A newt_button example
  • Example#770 - A newt_draw_root_text example
  • Example#771 - A newt_form_add_component example
  • Example#772 - A newt_form_add_components example
  • Example#773 - A newt_form example
  • Example#774 - A newt_get_screen_size example
  • Example#775 - A newt_win_entries example
  • Example#776 - Readline Callback Interface Example
  • Example#777 - readline Example
  • Example#778 - Small bzip2 Example
  • Example#779 - Compressing data
  • Example#780 - Decompressing a String
  • Example#781 - bzerror example
  • Example#782 - bzopen example
  • Example#783 - bzread example
  • Example#784 - bzwrite example
  • Example#785 - Using an external file
  • Example#786 - Using a file within a phar archive
  • Example#787 - Converting a phar archive from phar to tar file format
  • Example#788 - phar.extract_list usage example
  • Example#789 - phar.cache_list usage example
  • Example#790 - A Phar::addEmptyDir example
  • Example#791 - A Phar::addFile example
  • Example#792 - A Phar::addFromString example
  • Example#793 - A Phar::apiVersion example
  • Example#794 - A Phar::buildFromDirectory example
  • Example#795 - A Phar::buildFromIterator with SplFileInfo
  • Example#796 - A Phar::buildFromIterator with other iterators
  • Example#797 - A Phar::canCompress example
  • Example#798 - A Phar::canWrite example
  • Example#799 - A Phar::compress example
  • Example#800 - A Phar::compressAllFilesBZIP2 example
  • Example#801 - A Phar::compressAllFilesGZ example
  • Example#802 - A Phar::compressFiles example
  • Example#803 - A Phar::__construct example
  • Example#804 - A Phar::convertToData example
  • Example#805 - A Phar::convertToExecutable example
  • Example#806 - A Phar::copy example
  • Example#807 - A Phar::count example
  • Example#808 - A Phar::createDefaultStub example
  • Example#809 - A Phar::decompress example
  • Example#810 - A Phar::decompressFiles example
  • Example#811 - A Phar::delMetaData example
  • Example#812 - A Phar::delete example
  • Example#813 - A Phar::extractTo example
  • Example#814 - A Phar::getMetadata example
  • Example#815 - A Phar::getStub example
  • Example#816 - A Phar::hasMetadata example
  • Example#817 - A Phar::interceptFileFuncs example
  • Example#818 - A Phar::interceptFileFuncs example
  • Example#819 - A Phar::isBuffering example
  • Example#820 - A Phar::isCompressed example
  • Example#821 - A Phar::loadPhar example
  • Example#822 - A Phar::mapPhar example
  • Example#823 - A Phar::mount example
  • Example#824 - A Phar::mungServer example
  • Example#825 - A Phar::offsetExists example
  • Example#826 - Phar::offsetGet example
  • Example#827 - A Phar::offsetSet example
  • Example#828 - A Phar::offsetUnset example
  • Example#829 - A Phar::running example
  • Example#830 - A Phar::setAlias example
  • Example#831 - A Phar::setDefaultStub example
  • Example#832 - A Phar::setMetadata example
  • Example#833 - A Phar::setStub example
  • Example#834 - A Phar::startBuffering example
  • Example#835 - A Phar::stopBuffering example
  • Example#836 - A Phar::uncompressAllFiles example
  • Example#837 - A Phar::unlinkArchive example
  • Example#838 - A Phar::webPhar example
  • Example#839 - A PharData::addEmptyDir example
  • Example#840 - A PharData::addFile example
  • Example#841 - A PharData::addFromString example
  • Example#842 - A PharData::buildFromDirectory example
  • Example#843 - A PharData::buildFromIterator with SplFileInfo
  • Example#844 - A PharData::buildFromIterator with other iterators
  • Example#845 - A PharData::compress example
  • Example#846 - A PharData::compressFiles example
  • Example#847 - A PharData::__construct example
  • Example#848 - A PharData::convertToData example
  • Example#849 - A PharData::convertToExecutable example
  • Example#850 - A PharData::copy example
  • Example#851 - A PharData::decompress example
  • Example#852 - A PharData::decompressFiles example
  • Example#853 - A PharData::delMetaData example
  • Example#854 - A PharData::delete example
  • Example#855 - A PharData::extractTo example
  • Example#856 - A PharData::offsetSet example
  • Example#857 - A PharData::offsetUnset example
  • Example#858 - A Phar::setMetadata example
  • Example#859 - A PharFileInfo::chmod example
  • Example#860 - A PharFileInfo::compress example
  • Example#861 - A PharFileInfo::__construct example
  • Example#862 - A PharFileInfo::decompress example
  • Example#863 - A PharFileInfo::delMetaData example
  • Example#864 - A PharFileInfo::getCRC32 example
  • Example#865 - A PharFileInfo::getCompressedSize example
  • Example#866 - A PharFileInfo::getMetadata example
  • Example#867 - A PharFileInfo::getPharFlags example
  • Example#868 - A PharFileInfo::isCRCChecked example
  • Example#869 - A PharFileInfo::isCompressed example
  • Example#870 - A PharFileInfo::isCompressedBZIP2 example
  • Example#871 - A PharFileInfo::isCompressedGZ example
  • Example#872 - A PharFileInfo::setCompressedBZIP2 example
  • Example#873 - A PharFileInfo::setCompressedGZ example
  • Example#874 - A PharFileInfo::setMetadata example
  • Example#875 - A PharFileInfo::setUncompressed example
  • Example#876 - Rar installation
  • Example#877 - On-the-fly decompression
  • Example#878 - RAR extension filesystem extraction example
  • Example#879 - Object oriented style
  • Example#880 - Procedural style
  • Example#881 - Object oriented style
  • Example#882 - Procedural style
  • Example#883 - Object oriented style
  • Example#884 - Procedural style
  • Example#885 - Object oriented style
  • Example#886 - Procedural style
  • Example#887 - Object oriented style
  • Example#888 - Procedural style
  • Example#889 - Object oriented style
  • Example#890 - Procedural style
  • Example#891 - Object oriented style
  • Example#892 - Procedural style
  • Example#893 - Volume Callback
  • Example#894 - Object oriented style
  • Example#895 - Procedural style
  • Example#896 - RarArchive::__toString example
  • Example#897 - RarEntry::extract example
  • Example#898 - How to extract all files in archive:
  • Example#899 - RarEntry::getAttr example
  • Example#900 - RarEntry::getHostOs example (version >= 2.0.0)
  • Example#901 - RarEntry::getHostOs example (version <= 1.0.0)
  • Example#902 - RarEntry::getMethod example
  • Example#903 - RarEntry::getName example
  • Example#904 - RarEntry::getPackedSize example
  • Example#905 - RarEntry::getStream example
  • Example#906 - RarEntry::getUnpackedSize example
  • Example#907 - RarEntry::getVersion example
  • Example#908 - RarException::isUsingExceptions example
  • Example#909 - RarException::setUsingExceptions example
  • Example#910 - Create a Zip archive
  • Example#911 - Dump the archive details and listing
  • Example#912 - Zip stream wrapper, read an OpenOffice meta info
  • Example#913 - Zip Usage Example
  • Example#914 - Create a new directory in an archive
  • Example#915 - Open and add
  • Example#916 - Add an entry to a new archive
  • Example#917 - Add file to a directory inside an archive
  • Example#918 - ZipArchive::addGlob example
  • Example#919 - ZipArchive::addPattern example
  • Example#920 - Delete file from archive using its index
  • Example#921 - Deleting a file and directory from an archive, using names
  • Example#922 - Extract all entries
  • Example#923 - Extract two entries
  • Example#924 - Dump an archive comment
  • Example#925 - Dump an entry comment
  • Example#926 - Dump an entry comment
  • Example#927 - Extract all entries with Unix rights
  • Example#928 - Get the file contents
  • Example#929 - Get the file contents
  • Example#930 - Convert an image from a zip entry
  • Example#931 - ZipArchive::getNameIndex example
  • Example#932 - Get the entry contents with fread and store it
  • Example#933 - Same as the previous example but with fopen and the zip stream wrapper
  • Example#934 - Stream wrapper and image, can be used with the xml function as well
  • Example#935 - Create an archive and then use it with ZipArchive::locateName
  • Example#936 - Open and extract
  • Example#937 - Create an archive
  • Example#938 - Archive a file
  • Example#939 - Archive a file
  • Example#940 - Rename one entry
  • Example#941 - Rename one entry
  • Example#942 - Create an archive and set a comment
  • Example#943 - Open an archive and set a comment for an entry
  • Example#944 - Open an archive and set a comment for an entry
  • Example#945 - Add files with different compression methods to an archive
  • Example#946 - Add files with different compression methods to an archive
  • Example#947 - Archive and encrypt a file
  • Example#948 - Archive a file, with its Unix rights
  • Example#949 - Archive a file
  • Example#950 - Archive a file
  • Example#951 - Dump the stat info of an entry
  • Example#952 - Dump the stat info of an entry
  • Example#953 - Small Zlib Example
  • Example#954 - Working with the incremental compression and decompression API as of PHP 7.0.0
  • Example#955 - gzclose example
  • Example#956 - gzcompress example
  • Example#957 - gzdeflate example
  • Example#958 - Creating a gzip file
  • Example#959 - gzeof example
  • Example#960 - gzfile example
  • Example#961 - gzgetc example
  • Example#962 - gzgets example
  • Example#963 - gzgetss example
  • Example#964 - gzinflate example
  • Example#965 - gzopen Example
  • Example#966 - gzpassthru example
  • Example#967 - gzread example
  • Example#968 - gzseek example
  • Example#969 - gzuncompress example
  • Example#970 - gzwrite example
  • Example#971 - zlib_encode example
  • Example#972 - CrackLib example
  • Example#973 - random_bytes example
  • Example#974 - random_int example
  • Example#975 - hash_algos example
  • Example#976 - hash_copy example
  • Example#977 - hash_equals example
  • Example#978 - Using hash_file
  • Example#979 - hash_final example
  • Example#980 - hash_hkdf example
  • Example#981 - hash_hmac_algos example
  • Example#982 - hash_hmac_file example
  • Example#983 - hash_hmac example
  • Example#984 - Incremental hashing example
  • Example#985 - hash_pbkdf2 example, basic usage
  • Example#986 - hash_update_stream example
  • Example#987 - A hash example
  • Example#988 - Calculate pre PHP-5.4 tiger hashes with PHP-5.4 and higher
  • Example#989 - Encrypt an input value with AES with a 256-bit key under 2.4.x and higher in CBC mode
  • Example#990 - mcrypt_create_iv Example
  • Example#991 - mcrypt_enc_get_algorithms_name example
  • Example#992 - mcrypt_enc_get_modes_name example
  • Example#993 - mcrypt_enc_get_supported_key_sizes example
  • Example#994 - mcrypt_encrypt Example
  • Example#995 - mcrypt_get_block_size example
  • Example#996 - mcrypt_get_cipher_name Example
  • Example#997 - mcrypt_get_iv_size Example
  • Example#998 - mcrypt_get_key_size Example
  • Example#999 - mcrypt_list_algorithms Example
  • Example#1000 - mcrypt_list_modes Example
  • Example#1001 - mcrypt_module_open Examples
  • Example#1002 - Using mcrypt_module_open in encryption
  • Example#1003 - mcrypt_module_self_test example
  • Example#1004 - mdecrypt_generic Example
  • Example#1005 - Computes the MD5 digest and hmac and print it out as hex
  • Example#1006 - Traversing all hashes
  • Example#1007 - mhash_get_block_size Example
  • Example#1008 - mhash_get_hash_name Example
  • Example#1009 - openssl_cipher_iv_length example
  • Example#1010 - openssl_csr_export_to_file() example
  • Example#1011 - openssl_csr_export() example
  • Example#1012 - openssl_csr_get_public_key() example
  • Example#1013 - openssl_csr_get_subject() example
  • Example#1014 - Creating a self-signed certificate
  • Example#1015 - Creating a self-signed ECC certificate (as of PHP 7.1.0)
  • Example#1016 - openssl_csr_sign example - signing a CSR (how to implement your own CA)
  • Example#1017 - Compute a shared secret
  • Example#1018 - Generate a DH public/private keypair in php
  • Example#1019 - AES Authenticated Encryption in GCM mode example for PHP 7.1+
  • Example#1020 - AES Authenticated Encryption example for PHP 5.6+
  • Example#1021 - openssl_error_string example
  • Example#1022 - openssl_get_cert_locations example
  • Example#1023 - openssl_get_cipher_methods example
  • Example#1024 - openssl_get_curve_names example
  • Example#1025 - openssl_get_md_methods example
  • Example#1026 - openssl_open example
  • Example#1027 - openssl_pbkdf2() example
  • Example#1028 - openssl_pkcs12_read example
  • Example#1029 - openssl_pkcs7_decrypt example
  • Example#1030 - openssl_pkcs7_encrypt example
  • Example#1031 - openssl_pkcs7_sign example
  • Example#1032 - openssl_random_pseudo_bytes example
  • Example#1033 - openssl_seal example
  • Example#1034 - openssl_sign example
  • Example#1035 - openssl_sign example
  • Example#1036 - openssl_spki_export_challenge example
  • Example#1037 - openssl_spki_export_challenge example from <keygen>
  • Example#1038 - openssl_spki_export example
  • Example#1039 - openssl_spki_export example from <keygen>
  • Example#1040 - openssl_spki_new example
  • Example#1041 - openssl_spki_verify example
  • Example#1042 - openssl_spki_verify example from <keygen>
  • Example#1043 - openssl_verify example
  • Example#1044 - openssl_verify example
  • Example#1045 - password_hash example
  • Example#1046 - password_hash example setting cost manually
  • Example#1047 - password_hash example finding a good cost
  • Example#1048 - password_hash example using Argon2i
  • Example#1049 - Usage of password_needs_rehash
  • Example#1050 - password_verify example
  • Example#1051 - sodium_crypto_kx_keypair usage
  • Example#1052 - password_hash example
  • Example#1053 - password_hash example
  • Example#1054 - DBA example
  • Example#1055 - Traversing a database
  • Example#1056 - dba_handlers Example
  • Example#1057 - dbx_close example
  • Example#1058 - dbx_compare example
  • Example#1059 - dbx_connect example
  • Example#1060 - dbx_error example
  • Example#1061 - dbx_escape_string example
  • Example#1062 - How to handle the returned value
  • Example#1063 - lists each field's name and type
  • Example#1064 - outputs the content of data property into HTML table
  • Example#1065 - How to handle UNBUFFERED queries
  • Example#1066 - How to handle the returned value
  • Example#1067 - dbx_sort example
  • Example#1068 - DSN-less connections
  • Example#1069 - odbc_execute and odbc_prepare example
  • Example#1070 - odbc_fetch_into examples
  • Example#1071 - odbc_next_result
  • Example#1072 - odbc_execute and odbc_prepare example
  • Example#1073 - odbc_result examples
  • Example#1074 - odbc_setoption examples
  • Example#1075 - using PDO::ATTR_DRIVER_NAME
  • Example#1076 - Connecting to MySQL
  • Example#1077 - Handling connection errors
  • Example#1078 - Closing a connection
  • Example#1079 - Persistent connections
  • Example#1080 - Executing a batch in a transaction
  • Example#1081 - Repeated inserts using prepared statements
  • Example#1082 - Repeated inserts using prepared statements
  • Example#1083 - Fetching data using prepared statements
  • Example#1084 - Calling a stored procedure with an output parameter
  • Example#1085 - Calling a stored procedure with an input/output parameter
  • Example#1086 - Invalid use of placeholder
  • Example#1087 - Create a PDO instance and set the error mode
  • Example#1088 - Create a PDO instance and set the error mode from the constructor
  • Example#1089 - Displaying an image from a database
  • Example#1090 - Inserting an image into a database
  • Example#1091 - Inserting an image into a database: Oracle
  • Example#1092 - Roll back a transaction
  • Example#1093 - Committing a basic transaction
  • Example#1094 - Committing a DDL transaction
  • Example#1095 - Create a PDO instance via driver invocation
  • Example#1096 - Create a PDO instance via URI invocation
  • Example#1097 - Create a PDO instance using an alias
  • Example#1098 - Retrieving an SQLSTATE code
  • Example#1099 - Displaying errorInfo() fields for a PDO_ODBC connection to a DB2 database
  • Example#1100 - Issuing a DELETE statement
  • Example#1101 - Retrieving database connection attributes
  • Example#1102 - A PDO::getAvailableDrivers example
  • Example#1103 - SQL statement template with named parameters
  • Example#1104 - SQL statement template with question mark parameters
  • Example#1105 - Demonstrate PDO::query
  • Example#1106 - Quoting a normal string
  • Example#1107 - Quoting a dangerous string
  • Example#1108 - Quoting a complex string
  • Example#1109 - Roll back a transaction
  • Example#1110 - Binding result set output to PHP variables
  • Example#1111 - Execute a prepared statement with named placeholders
  • Example#1112 - Execute a prepared statement with question mark placeholders
  • Example#1113 - Call a stored procedure with an INOUT parameter
  • Example#1114 - Execute a prepared statement with named placeholders
  • Example#1115 - Execute a prepared statement with question mark placeholders
  • Example#1116 - A PDOStatement::closeCursor example
  • Example#1117 - Counting columns
  • Example#1118 - PDOStatement::debugDumpParams example with named parameters
  • Example#1119 - PDOStatement::debugDumpParams example with unnamed parameters
  • Example#1120 - Retrieving an SQLSTATE code
  • Example#1121 - Displaying errorInfo() fields for a PDO_ODBC connection to a DB2 database
  • Example#1122 - Execute a prepared statement with a bound variable and value
  • Example#1123 - Execute a prepared statement with an array of insert values (named parameters)
  • Example#1124 - Execute a prepared statement with an array of insert values (placeholders)
  • Example#1125 - Execute a prepared statement with question mark placeholders
  • Example#1126 - Execute a prepared statement using array for IN clause
  • Example#1127 - Fetching rows using different fetch styles
  • Example#1128 - Fetching rows with a scrollable cursor
  • Example#1129 - Construction order
  • Example#1130 - Fetch all remaining rows in a result set
  • Example#1131 - Fetching all values of a single column from a result set
  • Example#1132 - Grouping all values by a single column
  • Example#1133 - Instantiating a class for each result
  • Example#1134 - Calling a function for each result
  • Example#1135 - Return first column of the next row
  • Example#1136 - Retrieving column metadata
  • Example#1137 - Fetching multiple rowsets returned from a stored procedure
  • Example#1138 - Return the number of deleted rows
  • Example#1139 - Counting rows returned by a SELECT statement
  • Example#1140 - Setting the fetch mode
  • Example#1141 - Insert LOBs in CUBRID PDO
  • Example#1142 - Fetch LOBs in CUBRID PDO
  • Example#1143 - Insert set in CUBRID PDO with default data type.
  • Example#1144 - Specify data type when insert set in CUBRID PDO
  • Example#1145 - PDO_CUBRID DSN examples
  • Example#1146 - A PDO::cubrid_schema example
  • Example#1147 - PDO_DBLIB DSN examples
  • Example#1148 - PDO_FIREBIRD DSN example with path
  • Example#1149 - PDO_FIREBIRD DSN example with port and path
  • Example#1150 - PDO_FIREBIRD DSN example with localhost and path to employee.fdb on Debian system
  • Example#1151 - PDO_FIREBIRD DSN to connect to a dialect 1 database
  • Example#1152 - PDO_IBM DSN example using db2cli.ini
  • Example#1153 - PDO_IBM DSN example using a connection string
  • Example#1154 - PDO_INFORMIX DSN example using odbc.ini
  • Example#1155 - PDO_INFORMIX DSN example using a connection string
  • Example#1156 - Forcing queries to be buffered in mysql
  • Example#1157 - Setting the connection character set to UTF-8 prior to PHP 5.3.6
  • Example#1158 - PDO_MYSQL DSN examples
  • Example#1159 - PDO_SQLSRV DSN examples
  • Example#1160 - PDO_OCI DSN examples
  • Example#1161 - PDO_ODBC DSN example (ODBC driver manager)
  • Example#1162 - PDO_ODBC DSN example (IBM DB2 uncataloged connection)
  • Example#1163 - PDO_ODBC DSN example (Microsoft Access uncataloged connection)
  • Example#1164 - PDO_PGSQL DSN examples
  • Example#1165 - A PDO::pgsqlLOBCreate example
  • Example#1166 - A PDO::pgsqlLOBOpen example
  • Example#1167 - A PDO::pgsqlLOBUnlink example
  • Example#1168 - PDO_SQLITE DSN examples
  • Example#1169 - max_length aggregation function example
  • Example#1170 - PDO::sqliteCreateCollation example
  • Example#1171 - PDO::sqliteCreateFunction example
  • Example#1172 - DSN examples for PDO_4D
  • Example#1173 - Basic example with PDO_4D
  • Example#1174 - Accessing 4D language from pdo_4d
  • Example#1175 - Escaping 4D table names
  • Example#1176 - Example of Data Retrieval
  • Example#1177 - Example of Data Insertion
  • Example#1178 - cubrid_bind example
  • Example#1179 - cubrid_bind BLOB/CLOB example
  • Example#1180 - cubrid_bind BLOB/CLOB example
  • Example#1181 - cubrid_close_prepare example
  • Example#1182 - cubrid_close_request example
  • Example#1183 - cubrid_col_get example
  • Example#1184 - cubrid_col_size example
  • Example#1185 - cubrid_column_names example
  • Example#1186 - cubrid_column_types example
  • Example#1187 - cubrid_commit example
  • Example#1188 - cubrid_connect_with_url url without properties example
  • Example#1189 - cubrid_connect_with_url url with properties example
  • Example#1190 - cubrid_connect example
  • Example#1191 - cubrid_current_oid example
  • Example#1192 - cubrid_disconnect example
  • Example#1193 - cubrid_drop example
  • Example#1194 - cubrid_error_code_facility example
  • Example#1195 - cubrid_error_code example
  • Example#1196 - cubrid_error_msg example
  • Example#1197 - cubrid_execute example
  • Example#1198 - cubrid_fetch example
  • Example#1199 - cubrid_free_result example
  • Example#1200 - cubrid_get_charset example
  • Example#1201 - cubrid_get_class_name example
  • Example#1202 - cubrid_get_client_info example
  • Example#1203 - cubrid_get_db_parameter example
  • Example#1204 - cubrid_get_query_timeout example
  • Example#1205 - cubrid_get_server_info example
  • Example#1206 - cubrid_get example
  • Example#1207 - cubrid_insert_id example
  • Example#1208 - cubrid_is_instance example
  • Example#1209 - cubrid_lob_close example
  • Example#1210 - cubrid_lob_export example
  • Example#1211 - cubrid_lob_get example
  • Example#1212 - cubrid_lob_send example
  • Example#1213 - cubrid_lob_size example
  • Example#1214 - cubrid_lob2_bind example
  • Example#1215 - cubrid_lob2_export example
  • Example#1216 - cubrid_lob2_export example
  • Example#1217 - cubrid_lob2_read example 1
  • Example#1218 - cubrid_lob2_read example 2
  • Example#1219 - cubrid_lob2_seek64 example
  • Example#1220 - cubrid_lob2_seek example
  • Example#1221 - cubrid_lob2_write example 1
  • Example#1222 - cubrid_lob2_write example 2
  • Example#1223 - cubrid_lock_read example
  • Example#1224 - cubrid_lock_write example
  • Example#1225 - cubrid_move_cursor example
  • Example#1226 - cubrid_next_result example
  • Example#1227 - cubrid_num_cols example
  • Example#1228 - cubrid_num_rows example
  • Example#1229 - cubrid_pconnect_with_url url without properties example
  • Example#1230 - cubrid_pconnect_with_url url with properties example
  • Example#1231 - cubrid_connect example
  • Example#1232 - cubrid_prepare example
  • Example#1233 - cubrid_put example
  • Example#1234 - cubrid_rollback example
  • Example#1235 - cubrid_schema example
  • Example#1236 - cubrid_seq_drop example
  • Example#1237 - cubrid_seq_insert example
  • Example#1238 - cubrid_seq_put example
  • Example#1239 - cubrid_set_add example
  • Example#1240 - cubrid_get_db_parameter example
  • Example#1241 - cubrid_set_drop example
  • Example#1242 - cubrid_version example
  • Example#1243 - cubrid_affected_rows example
  • Example#1244 - cubrid_client_encoding example
  • Example#1245 - cubrid_close example
  • Example#1246 - cubrid_data_seek example
  • Example#1247 - cubrid_db_name example
  • Example#1248 - cubrid_errno example
  • Example#1249 - cubrid_error example
  • Example#1250 - cubrid_fetch_array example
  • Example#1251 - cubrid_fetch_assoc example
  • Example#1252 - cubrid_fetch_field example
  • Example#1253 - cubrid_fetch_lengths example
  • Example#1254 - cubrid_fetch_object example
  • Example#1255 - cubrid_fetch_row example
  • Example#1256 - cubrid_field_flags example
  • Example#1257 - cubrid_field_len example
  • Example#1258 - cubrid_field_name example
  • Example#1259 - cubrid_field_seek example
  • Example#1260 - cubrid_field_table example
  • Example#1261 - cubrid_field_type example
  • Example#1262 - cubrid_list_dbs example
  • Example#1263 - cubrid_num_fields example
  • Example#1264 - cubrid_ping example
  • Example#1265 - Invalid Query
  • Example#1266 - Valid Query
  • Example#1267 - cubrid_real_escape_string example
  • Example#1268 - cubrid_result example
  • Example#1269 - cubrid_unbuffered_query example
  • Example#1270 - cubrid_load_from_glo example
  • Example#1271 - cubrid_new_glo example
  • Example#1272 - cubrid_save_to_glo example
  • Example#1273 - cubrid_send_glo example
  • Example#1274 - Inserting a record in a dBase database
  • Example#1275 - Closing a dBase database file
  • Example#1276 - Creating a dBase database file
  • Example#1277 - Showing header information for a dBase database file
  • Example#1278 - Listing all the registered members in the database
  • Example#1279 - dbase_numfields Example
  • Example#1280 - Looping over all the records of the database
  • Example#1281 - Opening a dBase database file
  • Example#1282 - Emptying a dBase database
  • Example#1283 - Updating a record in the database
  • Example#1284 - ibase_backup example
  • Example#1285 - ibase_backup example with arguments
  • Example#1286 - ibase_blob_get example
  • Example#1287 - ibase_blob_import example
  • Example#1288 - ibase_connect example
  • Example#1289 - ibase_execute example
  • Example#1290 - ibase_fetch_object example
  • Example#1291 - ibase_field_info example
  • Example#1292 - ibase_name_result example
  • Example#1293 - ibase_num_fields example
  • Example#1294 - ibase_query example
  • Example#1295 - ibase_restore example
  • Example#1296 - ibase_restore example with arguments
  • Example#1297 - ibase_service_attach example
  • Example#1298 - ibase_service_attach example
  • Example#1299 - ibase_service_attach example using hostname/port syntax
  • Example#1300 - ibase_service_detach example
  • Example#1301 - ibase_set_event_handler example
  • Example#1302 - fbsql_close example
  • Example#1303 - fbsql_connect example
  • Example#1304 - fbsql_create_blob example
  • Example#1305 - fbsql_create_clob example
  • Example#1306 - fbsql_create_db example
  • Example#1307 - fbsql_data_seek example
  • Example#1308 - fbsql_create_clob example
  • Example#1309 - fbsql_errno Example
  • Example#1310 - fbsql_error Example
  • Example#1311 - fbsql_fetch_array example
  • Example#1312 - fbsql_fetch_assoc example
  • Example#1313 - fbsql_fetch_field example
  • Example#1314 - fbsql_fetch_object example
  • Example#1315 - fbsql_field_name example
  • Example#1316 - fbsql_field_type example
  • Example#1317 - fbsql_list_dbs example
  • Example#1318 - fbsql_list_fields example
  • Example#1319 - fbsql_next_result example
  • Example#1320 - fbsql_num_rows example
  • Example#1321 - fbsql_query example
  • Example#1322 - fbsql_query example
  • Example#1323 - fbsql_read_blob example
  • Example#1324 - fbsql_read_clob example
  • Example#1325 - fbsql_table_name example
  • Example#1326 - Retrieving the AUTOCOMMIT value for a connection
  • Example#1327 - Setting the AUTOCOMMIT value for a connection
  • Example#1328 - Binding PHP variables to a prepared statement
  • Example#1329 - Calling stored procedures with IN and OUT parameters
  • Example#1330 - Inserting a binary large object (BLOB) directly from a file
  • Example#1331 - A db2_client_info example
  • Example#1332 - Closing a connection
  • Example#1333 - Retrieving an SQLSTATE value for a failed connection attempt
  • Example#1334 - Retrieving the error message returned by a failed connection attempt
  • Example#1335 - Creating a cataloged connection
  • Example#1336 - Creating an uncataloged connection
  • Example#1337 - Creating a connection with autocommit off by default
  • Example#1338 - i5/OS best performance
  • Example#1339 - Using trusted context
  • Example#1340 - A db2_escape_string example
  • Example#1341 - Creating a table with db2_exec
  • Example#1342 - Executing a SELECT statement with a scrollable cursor
  • Example#1343 - Returning XML data as an SQL ResultSet
  • Example#1344 - Performing a "JOIN" with XML data
  • Example#1345 - Returning SQL data as part of a larger XML document
  • Example#1346 - Preparing and executing an SQL statement with parameter markers
  • Example#1347 - Calling a stored procedure with an OUT parameter
  • Example#1348 - Returning XML data as an SQL ResultSet
  • Example#1349 - Performing a "JOIN" with XML data
  • Example#1350 - Returning SQL data as part of a larger XML document
  • Example#1351 - Iterating through a forward-only cursor
  • Example#1352 - Retrieving specific rows with db2_fetch_array from a scrollable cursor
  • Example#1353 - Iterating through a forward-only cursor
  • Example#1354 - Retrieving specific rows with db2_fetch_assoc from a scrollable cursor
  • Example#1355 - Iterating through a forward-only cursor
  • Example#1356 - Retrieving specific rows with db2_fetch_both from a scrollable cursor
  • Example#1357 - A db2_fetch_object example
  • Example#1358 - Iterating through a result set
  • Example#1359 - i5/OS recommended alternatives to db2_fetch_row/db2_result
  • Example#1360 - Setting and retrieving parameters through a connection resource
  • Example#1361 - A db2_last_insert_id example
  • Example#1362 - Iterating through different types of data
  • Example#1363 - Calling a stored procedure that returns multiple result sets
  • Example#1364 - Retrieving the number of fields in a result set
  • Example#1365 - Closing a persistent connection
  • Example#1366 - A db2_pconnect example
  • Example#1367 - Using trusted context
  • Example#1368 - Preparing and executing an SQL statement with parameter markers
  • Example#1369 - A db2_result example
  • Example#1370 - Rolling back a DELETE statement
  • Example#1371 - A db2_server_info example
  • Example#1372 - Setting one parameter with a connection resource
  • Example#1373 - Setting multiple parameters with a connection resource
  • Example#1374 - Setting multiple parameters with an invalid key
  • Example#1375 - Setting multiple parameters with an invalid value
  • Example#1376 - Setting multiple parameters with a connection resource and the wrong type
  • Example#1377 - Setting multiple parameters with the wrong resource
  • Example#1378 - Putting it all together
  • Example#1379 - i5/OS cursors are read-only
  • Example#1380 - Informix affected rows
  • Example#1381 - Closing a Informix connection
  • Example#1382 - Connect to a Informix database
  • Example#1383 - ifx_do Example
  • Example#1384 - ifx_errormsg example
  • Example#1385 - Informix fetch rows
  • Example#1386 - Informix SQL fieldproperties
  • Example#1387 - Fieldnames and SQL fieldtypes
  • Example#1388 - Retrieve Informix sqlca.sqlerrd[x] values
  • Example#1389 - Informix results as HTML table
  • Example#1390 - ifx_num_fields Example
  • Example#1391 - Show all rows of the "orders" table as a HTML table
  • Example#1392 - Insert some values into the "catalog" table
  • Example#1393 - Example usage of PassEnv for Ingres
  • Example#1394 - Simple Ingres Example
  • Example#1395 - ingres_charset - Get the installation character set
  • Example#1396 - Open a connection to an Ingres database
  • Example#1397 - Get cursor name for a query resource
  • Example#1398 - Get the last Ingres error number generated
  • Example#1399 - Get a message for the last error generated
  • Example#1400 - Get the last SQLSTATE error code generated
  • Example#1401 - Escape special characters for use in a query
  • Example#1402 - Fetch a row of result into an array
  • Example#1403 - Fetch a row into an associative array
  • Example#1404 - Fetch a row into an object
  • Example#1405 - Get the return value from a procedure call
  • Example#1406 - Fetch a row of result into an enumerated array
  • Example#1407 - Free a result resource
  • Example#1408 - Send a simple select
  • Example#1409 - Passing query parameters to ingres_query
  • Example#1410 - Inserting a BLOB with parameter types
  • Example#1411 - Position the cursor on the 3rd row
  • Example#1412 - Set date_format to ISO4
  • Example#1413 - Set timezone to HONG-KONG
  • Example#1414 - Issue a simple un-buffered select
  • Example#1415 - Passing query parameters to ingres_unbuffered_query
  • Example#1416 - Inserting a BLOB with parameter types
  • Example#1417 - MaxDB extension overview example
  • Example#1418 - Example for use of SELECT INTO statements
  • Example#1419 - Example fore using database procedures
  • Example#1420 - Object oriented style
  • Example#1421 - Procedural style
  • Example#1422 - Object oriented style
  • Example#1423 - Procedural style
  • Example#1424 - Object oriented style
  • Example#1425 - Procedural style
  • Example#1426 - Object oriented style
  • Example#1427 - Procedural style
  • Example#1428 - Object oriented style
  • Example#1429 - Procedural style
  • Example#1430 - maxdb_connect_errno sample
  • Example#1431 - maxdb_connect_error sample
  • Example#1432 - Object oriented style
  • Example#1433 - Procedural style
  • Example#1434 - Object oriented style
  • Example#1435 - Procedural style
  • Example#1436 - Procedural style
  • Example#1437 - Object oriented style
  • Example#1438 - Procedural style
  • Example#1439 - Object oriented style
  • Example#1440 - Procedural style
  • Example#1441 - Object oriented style
  • Example#1442 - Procedural style
  • Example#1443 - Object oriented style
  • Example#1444 - Procedural style
  • Example#1445 - Object oriented style
  • Example#1446 - Procedural style
  • Example#1447 - Object oriented style
  • Example#1448 - Procedural style
  • Example#1449 - Object oriented style
  • Example#1450 - Procedural style
  • Example#1451 - Object oriented style
  • Example#1452 - Procedural style
  • Example#1453 - Object oriented style
  • Example#1454 - Procedural style
  • Example#1455 - Object oriented style
  • Example#1456 - Procedural style
  • Example#1457 - Object oriented style
  • Example#1458 - Procedural style
  • Example#1459 - Object oriented style
  • Example#1460 - Procedural style
  • Example#1461 - Object oriented style
  • Example#1462 - Procedural style
  • Example#1463 - maxdb_get_client_info
  • Example#1464 - maxdb_get_client_version
  • Example#1465 - Object oriented style
  • Example#1466 - Procedural style
  • Example#1467 - Object oriented style
  • Example#1468 - Procedural style
  • Example#1469 - Object oriented style
  • Example#1470 - Procedural style
  • Example#1471 - Object oriented style
  • Example#1472 - Procedural style
  • Example#1473 - Object oriented style
  • Example#1474 - Procedural style
  • Example#1475 - Object oriented style
  • Example#1476 - Procedural style
  • Example#1477 - Object oriented style
  • Example#1478 - Procedural style
  • Example#1479 - Object oriented style
  • Example#1480 - Procedural style
  • Example#1481 - Object oriented style
  • Example#1482 - Procedural style
  • Example#1483 - Object oriented style
  • Example#1484 - Procedural style
  • Example#1485 - Object oriented style
  • Example#1486 - Procedural style
  • Example#1487 - Object oriented style
  • Example#1488 - Procedural style
  • Example#1489 - Object oriented style
  • Example#1490 - Procedural style
  • Example#1491 - Object oriented style
  • Example#1492 - Procedural style
  • Example#1493 - Object oriented style
  • Example#1494 - Procedural style
  • Example#1495 - Procedural style
  • Example#1496 - Object oriented style
  • Example#1497 - Procedural style
  • Example#1498 - Object oriented style
  • Example#1499 - Procedural style
  • Example#1500 - Object oriented style
  • Example#1501 - Procedural style
  • Example#1502 - Object oriented style
  • Example#1503 - Procedural style
  • Example#1504 - Object oriented style
  • Example#1505 - Procedural style
  • Example#1506 - Object oriented style
  • Example#1507 - Procedural style
  • Example#1508 - Procedural style (SELECT INTO)
  • Example#1509 - Procedural style (DB procedure)
  • Example#1510 - Object oriented style (extended syntax)
  • Example#1511 - Object oriented style
  • Example#1512 - Procedural style
  • Example#1513 - Object oriented style
  • Example#1514 - Procedural style
  • Example#1515 - Object oriented style
  • Example#1516 - Procedural style
  • Example#1517 - Object oriented style
  • Example#1518 - Procedural style
  • Example#1519 - Object oriented style
  • Example#1520 - Procedural style
  • Example#1521 - Object oriented style
  • Example#1522 - Procedural style
  • Example#1523 - Object oriented style
  • Example#1524 - Procedural style
  • Example#1525 - Object oriented style
  • Example#1526 - Procedural style
  • Example#1527 - Object oriented style
  • Example#1528 - Procedural style
  • Example#1529 - Object oriented style
  • Example#1530 - Procedural style
  • Example#1531 - Object oriented style
  • Example#1532 - Procedural style
  • Example#1533 - Object oriented style
  • Example#1534 - Procedural style
  • Example#1535 - Object oriented style
  • Example#1536 - Procedural style
  • Example#1537 - Object oriented style
  • Example#1538 - Procedural style
  • Example#1539 - Object oriented style
  • Example#1540 - Procedural style
  • Example#1541 -
  • Example#1542 -
  • Example#1543 -
  • Example#1544 -
  • Example#1545 -
  • Example#1546 -
  • Example#1547 -
  • Example#1548 -
  • Example#1549 -
  • Example#1550 -
  • Example#1551 -
  • Example#1552 -
  • Example#1553 -
  • Example#1554 -
  • Example#1555 -
  • Example#1556 - Connection URI read preferences with query string syntax
  • Example#1557 - Setting read preferences with array syntax for tag sets
  • Example#1558 - Passing a WriteConcern to a write operation
  • Example#1559 - Connection string WriteConcerns
  • Example#1560 - MongoDB::setWriteConcern and MongoCollection::setWriteConcern
  • Example#1561 - Unacknowledged WriteConcern, followed with Acknowledged Write
  • Example#1562 - Acknowledged Writes
  • Example#1563 - Majority Acknowledged Write
  • Example#1564 - Acknowledged and Journaled Write
  • Example#1565 - Connect to MongoDB Instance with SSL Encryption
  • Example#1566 - Connect to MongoDB Instance with SSL Encryption, verifying it is who we think it is
  • Example#1567 - Connect to MongoDB Instance that Requires Client Certificates
  • Example#1568 - Authenticating with X.509 certificates
  • Example#1569 - Authenticating against the "admin" database
  • Example#1570 - Authenticating against normal databases
  • Example#1571 - ReplicaSet seed list
  • Example#1572 - Wrong replica set name duplication
  • Example#1573 - Correct use of two replica set names
  • Example#1574 -
  • Example#1575 -
  • Example#1576 -
  • Example#1577 -
  • Example#1578 -
  • Example#1579 -
  • Example#1580 - Inheriting read preferences from the database level down to the cursor
  • Example#1581 -
  • Example#1582 -
  • Example#1583 -
  • Example#1584 -
  • Example#1585 -
  • Example#1586 -
  • Example#1587 -
  • Example#1588 - MongoClient basic usage
  • Example#1589 - MongoClient::close example
  • Example#1590 - MongoClient::__construct replica set example
  • Example#1591 - Connecting to a domain socket
  • Example#1592 - MongoClient::__construct authentication example
  • Example#1593 - MongoClient::__construct read preference example
  • Example#1594 - MongoClient::__construct options example
  • Example#1595 - MongoClient::__construct read preference example
  • Example#1596 - MongoClient::getConnections example
  • Example#1597 - MongoClient::getReadPreference return value example
  • Example#1598 - MongoClient::getWriteConcern return value example
  • Example#1599 - MongoClient::killCursor example
  • Example#1600 - MongoClient::listDBs example
  • Example#1601 - MongoClient::selectCollection example
  • Example#1602 - MongoClient::setReadPreference tag set array syntax example
  • Example#1603 - MongoClient::setWriteConcern example
  • Example#1604 - Selecting a database
  • Example#1605 - MongoDB::command "distinct" example
  • Example#1606 - MongoDB::command "distinct" example
  • Example#1607 - MongoDB::command MapReduce example
  • Example#1608 - MongoDB::command "geoNear" example
  • Example#1609 - MongoDB::createCollection capped collection example
  • Example#1610 - MongoDB::createDBRef example
  • Example#1611 - MongoDB::createDBRef example
  • Example#1612 - MongoDB::drop example
  • Example#1613 - Simple MongoDB::execute example
  • Example#1614 - Parameter MongoDB::execute example
  • Example#1615 - Scope example
  • Example#1616 - MongoDB::getCollectionInfo example
  • Example#1617 - MongoDB::getCollectionNames example
  • Example#1618 - MongoDB::getDBRef example
  • Example#1619 - MongoDB::getGridFS example
  • Example#1620 - MongoDB::getReadPreference return value example
  • Example#1621 - MongoDB::getWriteConcern return value example
  • Example#1622 - MongoDB::lastError NULL error example
  • Example#1623 - MongoDB::lastError duplicate key example
  • Example#1624 - MongoDB::listCollections example
  • Example#1625 - MongoDB::repair example
  • Example#1626 - MongoDB::setReadPreference tag set array syntax example
  • Example#1627 - MongoDB::setWriteConcern example
  • Example#1628 - MongoCollection::aggregate example
  • Example#1629 - MongoCollection::aggregate example
  • Example#1630 - MongoCollection::aggregate example
  • Example#1631 - MongoCollection::aggregate with command options
  • Example#1632 - MongoCollection::aggregateCursor example
  • Example#1633 - MongoCollection::aggregateCursor example with different initial batch size
  • Example#1634 - MongoCollection::batchInsert example
  • Example#1635 - MongoCollection::batchInsert example with ignoring errors
  • Example#1636 - MongoCollection::count example
  • Example#1637 - MongoCollection::createDBRef example
  • Example#1638 - MongoCollection::createIndex example
  • Example#1639 - Geospatial Indexing
  • Example#1640 - Drop duplicates example
  • Example#1641 - MongoCollection::deleteIndex example
  • Example#1642 - MongoCollection::deleteIndexes example
  • Example#1643 - MongoCollection::distinct example
  • Example#1644 - MongoCollection::distinct example on a embedded document
  • Example#1645 - MongoCollection::drop example
  • Example#1646 - MongoCollection::ensureIndex example
  • Example#1647 - Geospatial Indexing
  • Example#1648 - Drop duplicates example
  • Example#1649 - MongoCollection::find example
  • Example#1650 - MongoCollection::find example
  • Example#1651 - MongoCollection::find example using $where
  • Example#1652 - MongoCollection::find example using $in
  • Example#1653 - Getting results as an array
  • Example#1654 - MongoCollection::findAndModify example
  • Example#1655 - MongoCollection::findAndModify error handling
  • Example#1656 - MongoCollection::findOne document by its id.
  • Example#1657 - MongoCollection::findOne document by some condition.
  • Example#1658 - MongoCollection::getDBRef example
  • Example#1659 - MongoCollection::getIndexInfo example
  • Example#1660 - MongoCollection::getName example
  • Example#1661 - MongoCollection::getReadPreference return value example
  • Example#1662 - MongoCollection::getWriteConcern return value example
  • Example#1663 - MongoCollection::group example
  • Example#1664 - MongoCollection::group example
  • Example#1665 - Passing a keys function
  • Example#1666 - MongoCollection::insert _id example
  • Example#1667 - MongoCollection::insert acknowledged write example
  • Example#1668 - MongoCollection::parallelCollectionScan example
  • Example#1669 - MongoCollection::remove with justOne example
  • Example#1670 - MongoCollection::save example
  • Example#1671 - MongoCollection::setReadPreference tag set array syntax example
  • Example#1672 - MongoDB::setWriteConcern example
  • Example#1673 - MongoCollection::toIndexString example
  • Example#1674 - MongoCollection::__toString example
  • Example#1675 - MongoCollection::update
  • Example#1676 - MongoCollection::update upsert examples
  • Example#1677 - MongoCollection::update multiple example
  • Example#1678 - MongoCursor basic usage
  • Example#1679 - Iterating over MongoCursor
  • Example#1680 - Adding options to MongoCursor
  • Example#1681 - Adding a comment with MongoCursor::addOption example
  • Example#1682 - MongoCursor::addOption example
  • Example#1683 - MongoCursor::awaitData example
  • Example#1684 - MongoCursor::batchSize and combinations with MongoCursor::limit
  • Example#1685 - MongoCursor::count example
  • Example#1686 - MongoCursor::doQuery example
  • Example#1687 - MongoCursor::explain example
  • Example#1688 - MongoCursor::getReadPreference return value example
  • Example#1689 - MongoCursor::info example
  • Example#1690 - MongoCursor::maxTimeMS example
  • Example#1691 - MongoCursor::setFlag example
  • Example#1692 - MongoCursor::setReadPreference tag set array syntax example
  • Example#1693 - MongoCursor::slaveOkay example
  • Example#1694 - MongoCursor::sort example
  • Example#1695 - MongoCursor::tailable example
  • Example#1696 - MongoCursor::timeout example
  • Example#1697 - Adding options to MongoCommandCursor
  • Example#1698 - MongoCommandCursor::batchSize
  • Example#1699 - MongoCommandCursor example
  • Example#1700 - MongoCommandCursor::createFromDocument
  • Example#1701 - MongoCommandCursor::getReadPreference return value example
  • Example#1702 - MongoCommandCursor::info example
  • Example#1703 - MongoCommandCursor::rewind
  • Example#1704 - MongoCommandCursor::setReadPreference tag set array syntax example
  • Example#1705 - MongoCommandCursor::timeout example
  • Example#1706 - MongoId::__construct example
  • Example#1707 - Parameter example
  • Example#1708 - MongoId::__toString example
  • Example#1709 - MongoCode::__construct example
  • Example#1710 - Using MongoCode with $where
  • Example#1711 - MongoCode::__toString example
  • Example#1712 - Storing dates with MongoDate
  • Example#1713 - MongoDate::__construct example
  • Example#1714 - MongoDate::toDateTime example
  • Example#1715 - Regular expression pattern
  • Example#1716 - MongoRegex::__construct example
  • Example#1717 - MongoRegex::__toString example
  • Example#1718 -
  • Example#1719 - Linking documents
  • Example#1720 - Creating MongoDBRef links
  • Example#1721 - MongoDBRef::create example
  • Example#1722 - MongoCollection::createDBRef example
  • Example#1723 - MongoGridFS::findOne example
  • Example#1724 - MongoGridFS::storeBytes with additional metadata
  • Example#1725 - MongoGridFS::storeFile with additional metadata
  • Example#1726 - MongoGridFS::storeUpload HTML form example
  • Example#1727 - MongoGridFSFile::getBytes example
  • Example#1728 - MongoGridFSFile::getResource example
  • Example#1729 - MongoGridFSFile::write example
  • Example#1730 - MongoWriteBatch example
  • Example#1731 - MongoWriteBatch::add example
  • Example#1732 - MongoWriteBatch::add example
  • Example#1733 - MongoWriteBatch::add example
  • Example#1734 - MongoWriteBatch::add example
  • Example#1735 - MongoWriteBatch::add example
  • Example#1736 - MongoWriteBatch::add example
  • Example#1737 - MongoLog::setCallback example
  • Example#1738 - Changing pool size
  • Example#1739 - Mongo::setPoolSize example
  • Example#1740 - Changing pool size
  • Example#1741 - Mongo::setPoolSize example
  • Example#1742 - MongoResultException::getDocument example
  • Example#1743 - Catching MongoDuplicateKeyException
  • Example#1744 - Catching MongoProtocolException
  • Example#1745 - MongoDB\Driver\Manager::__construct basic example
  • Example#1746 - MongoDB\Driver\Manager::__construct basic examples
  • Example#1747 - MongoDB\Driver\Manager::executeBulkWrite example
  • Example#1748 - MongoDB\Driver\Manager::executeCommand with a command returning a single result document
  • Example#1749 - MongoDB\Driver\Manager::executeCommand with a command returning a cursor
  • Example#1750 - Limiting execution time for a command
  • Example#1751 - MongoDB\Driver\Manager::executeQuery example
  • Example#1752 - Limiting execution time for a query
  • Example#1753 - MongoDB\Driver\Manager::getReadConcern example
  • Example#1754 - MongoDB\Driver\Manager::getReadPreference example
  • Example#1755 - MongoDB\Driver\Manager::getServers example
  • Example#1756 - MongoDB\Driver\Manager::getWriteConcern example
  • Example#1757 - Composing MongoDB\Driver\Command to provide a helper to create collections
  • Example#1758 - MongoDB\Driver\Command::__construct example
  • Example#1759 - MongoDB\Driver\Command::__construct example
  • Example#1760 - MongoDB\Driver\Query::__construct example
  • Example#1761 - Mixed write operations are grouped by type
  • Example#1762 - Ordered write operations causing an error
  • Example#1763 - MongoDB\Driver\BulkWrite::__construct example
  • Example#1764 - MongoDB\Driver\BulkWrite::count example
  • Example#1765 - MongoDB\Driver\BulkWrite::delete example
  • Example#1766 - MongoDB\Driver\BulkWrite::insert example
  • Example#1767 - MongoDB\Driver\BulkWrite::update example
  • Example#1768 - MongoDB\Driver\WriteConcern::bsonSerialize with majority write concern
  • Example#1769 - MongoDB\Driver\WriteConcern::bsonSerialize with wtimeout and journal
  • Example#1770 - MongoDB\Driver\WriteConcern::__construct example
  • Example#1771 - MongoDB\Driver\WriteConcern::getJournal example
  • Example#1772 - MongoDB\Driver\WriteConcern::getW example
  • Example#1773 - MongoDB\Driver\WriteConcern::getWtimeout example
  • Example#1774 - MongoDB\Driver\WriteConcern::isDefault example
  • Example#1775 - MongoDB\Driver\ReadPreference::bsonSerialize with primary read preference
  • Example#1776 - MongoDB\Driver\ReadPreference::bsonSerialize with secondary read preference and tag sets
  • Example#1777 - MongoDB\Driver\ReadPreference::bsonSerialize with secondary read preference and max staleness
  • Example#1778 - MongoDB\Driver\ReadPreference::__construct example
  • Example#1779 - MongoDB\Driver\ReadPreference::getMaxStalenessSeconds example
  • Example#1780 - MongoDB\Driver\ReadPreference::getMode example
  • Example#1781 - MongoDB\Driver\ReadPreference::getModeString example
  • Example#1782 - MongoDB\Driver\ReadPreference::getTagSets example
  • Example#1783 - MongoDB\Driver\ReadConcern::bsonSerialize with empty read concern
  • Example#1784 - MongoDB\Driver\ReadConcern::bsonSerialize with local read concern
  • Example#1785 - MongoDB\Driver\ReadConcern::__construct example
  • Example#1786 - MongoDB\Driver\ReadConcern::getLevel example
  • Example#1787 - MongoDB\Driver\ReadConcern::isDefault example
  • Example#1788 - Reading a result set
  • Example#1789 - Reading a result set for a tailable cursor
  • Example#1790 - MongoDB\Driver\Cursor::getId example
  • Example#1791 - MongoDB\Driver\Cursor::getServer example
  • Example#1792 - MongoDB\Driver\Cursor::isDead example
  • Example#1793 - MongoDB\Driver\Cursor::setTypeMap example
  • Example#1794 - MongoDB\Driver\Cursor::toArray example
  • Example#1795 - MongoDB\Driver\CursorId::__toString example
  • Example#1796 - MongoDB\Driver\Server::getHost example
  • Example#1797 - MongoDB\Driver\Server::getInfo example
  • Example#1798 - MongoDB\Driver\Server::getLatency example
  • Example#1799 - MongoDB\Driver\Server::getPort example
  • Example#1800 - MongoDB\Driver\WriteConcernError::getCode example
  • Example#1801 - MongoDB\Driver\WriteConcernError::getInfo example
  • Example#1802 - MongoDB\Driver\WriteConcernError::getMessage example
  • Example#1803 - MongoDB\Driver\WriteError::getCode example
  • Example#1804 - MongoDB\Driver\WriteError::getIndex example
  • Example#1805 - MongoDB\Driver\WriteError::getMessage example
  • Example#1806 - MongoDB\Driver\WriteResult::getDeletedCount example
  • Example#1807 - MongoDB\Driver\WriteResult::getInsertedCount example
  • Example#1808 - MongoDB\Driver\WriteResult::getMatchedCount example
  • Example#1809 - MongoDB\Driver\WriteResult::getModifiedCount example
  • Example#1810 - MongoDB\Driver\WriteResult::getServer example
  • Example#1811 - MongoDB\Driver\WriteResult::getUpsertedCount example
  • Example#1812 - MongoDB\Driver\WriteResult::getUpsertedIds example
  • Example#1813 - MongoDB\Driver\WriteResult::getWriteConcernError example
  • Example#1814 - MongoDB\Driver\WriteResult::getWriteErrors with a single error
  • Example#1815 - MongoDB\Driver\WriteResult::getWriteErrors with multiple errors
  • Example#1816 - MongoDB\Driver\WriteResult::isAcknowledged with acknowledged write concern
  • Example#1817 - MongoDB\Driver\WriteResult::isAcknowledged with unacknowledged write concern
  • Example#1818 - MongoDB\BSON\fromJSON example
  • Example#1819 - MongoDB\BSON\fromPHP example
  • Example#1820 - MongoDB\BSON\toCanonicalExtendedJSON example
  • Example#1821 - MongoDB\BSON\toJSON example
  • Example#1822 - MongoDB\BSON\toPHP example
  • Example#1823 - MongoDB\BSON\toRelaxedExtendedJSON example
  • Example#1824 - MongoDB\BSON\Binary::__construct example
  • Example#1825 - MongoDB\BSON\Binary::getData example
  • Example#1826 - MongoDB\BSON\Binary::getType example
  • Example#1827 - MongoDB\BSON\Binary::__toString example
  • Example#1828 - MongoDB\BSON\Decimal128::__construct example
  • Example#1829 - MongoDB\BSON\Decimal128::__toString example
  • Example#1830 - MongoDB\BSON\Javascript::__construct example
  • Example#1831 - MongoDB\BSON\Javascript::getCode example
  • Example#1832 - MongoDB\BSON\Javascript::getScope example
  • Example#1833 - MongoDB\BSON\Javascript::__toString example
  • Example#1834 - MongoDB\BSON\MaxKey::__construct example
  • Example#1835 - MongoDB\BSON\MinKey::__construct example
  • Example#1836 - MongoDB\BSON\ObjectId::__construct example
  • Example#1837 - MongoDB\BSON\ObjectId::getTimestamp example
  • Example#1838 - MongoDB\BSON\ObjectId::__toString example
  • Example#1839 - MongoDB\BSON\Regex::__construct example
  • Example#1840 - MongoDB\BSON\Regex::getFlags example
  • Example#1841 - MongoDB\BSON\Regex::getPattern example
  • Example#1842 - MongoDB\BSON\Regex::__toString example
  • Example#1843 - MongoDB\BSON\Timestamp::__construct example
  • Example#1844 - MongoDB\BSON\Timestamp::__toString example
  • Example#1845 - MongoDB\BSON\UTCDateTime::__construct example
  • Example#1846 - MongoDB\BSON\UTCDatetime::toDateTime example
  • Example#1847 - MongoDB\BSON\UTCDateTime::__toString example
  • Example#1848 - MongoDB\BSON\Serializable::bsonSerialize returning an associative array for root document
  • Example#1849 - MongoDB\BSON\Serializable::bsonSerialize returning a sequential array for root document
  • Example#1850 - MongoDB\BSON\Serializable::bsonSerialize returning an associative array for document field
  • Example#1851 - MongoDB\BSON\Serializable::bsonSerialize returning a sequential array for document field
  • Example#1852 - MongoDB\BSON\Unserializable::bsonUnserialize example
  • Example#1853 - MongoDB\BSON\Int64::__toString example
  • Example#1854 - MongoDB\Driver\Exception\WriteException::getWriteResult example
  • Example#1855 - mSQL usage example
  • Example#1856 - msql_fetch_array example
  • Example#1857 - msql_fetch_object example
  • Example#1858 - msql_fetch_row example
  • Example#1859 - msql_query example
  • Example#1860 - mssql_bind example
  • Example#1861 - mssql_close example
  • Example#1862 - mssql_connect example
  • Example#1863 - mssql_data_seek example
  • Example#1864 - mssql_execute example
  • Example#1865 - mssql_fetch_array example
  • Example#1866 - mssql_fetch_assoc example
  • Example#1867 - mssql_fetch_batch example
  • Example#1868 - mssql_fetch_field example
  • Example#1869 - mssql_fetch_object example
  • Example#1870 - mssql_fetch_row example
  • Example#1871 - mssql_field_length example
  • Example#1872 - mssql_field_name example
  • Example#1873 - Using mssql_field_seek on the example for mssql_fetch_field
  • Example#1874 - mssql_field_type example
  • Example#1875 - mssql_free_result example
  • Example#1876 - mssql_free_statement example
  • Example#1877 - mssql_get_last_message example
  • Example#1878 - mssql_guid_string example
  • Example#1879 - mssql_init example
  • Example#1880 - mssql_min_error_severity example
  • Example#1881 - mssql_min_message_severity example
  • Example#1882 - mssql_next_result example
  • Example#1883 - mssql_num_fields example
  • Example#1884 - mssql_num_rows example
  • Example#1885 - mssql_pconnect using the new_link parameter
  • Example#1886 - mssql_query example
  • Example#1887 - mssql_result example
  • Example#1888 - Faster alternative to above example
  • Example#1889 - mssql_rows_affected example
  • Example#1890 - mssql_select_db example
  • Example#1891 - Escaping the database name with square brackets
  • Example#1892 - Comparing the three MySQL APIs
  • Example#1893 - Configure commands for using mysqlnd or libmysqlclient
  • Example#1894 - Unbuffered query example: mysqli
  • Example#1895 - Unbuffered query example: pdo_mysql
  • Example#1896 - Unbuffered query example: mysql
  • Example#1897 - Problems with setting the character set with SQL
  • Example#1898 - Setting the character set example: mysqli
  • Example#1899 - Setting the character set example: pdo_mysql
  • Example#1900 - Setting the character set example: mysql
  • Example#1901 - Easy migration from the old mysql extension
  • Example#1902 - Object-oriented and procedural interface
  • Example#1903 - Bad coding style
  • Example#1904 - Special meaning of localhost
  • Example#1905 - Setting defaults
  • Example#1906 - Connecting to MySQL
  • Example#1907 - Navigation through buffered results
  • Example#1908 - Navigation through unbuffered results
  • Example#1909 - Text protocol returns strings by default
  • Example#1910 - Native data types with mysqlnd and connection option
  • Example#1911 - First stage: prepare
  • Example#1912 - Second stage: bind and execute
  • Example#1913 - INSERT prepared once, executed multiple times
  • Example#1914 - Less round trips using multi-INSERT SQL
  • Example#1915 - Native datatypes
  • Example#1916 - Output variable binding
  • Example#1917 - Using mysqli_result to fetch results
  • Example#1918 - Buffered result set for flexible read out
  • Example#1919 - Calling a stored procedure
  • Example#1920 - Using session variables
  • Example#1921 - Fetching results from stored procedures
  • Example#1922 - Stored Procedures and Prepared Statements
  • Example#1923 - Stored Procedures and Prepared Statements using bind API
  • Example#1924 - Multiple Statements
  • Example#1925 - SQL Injection
  • Example#1926 - Setting auto commit mode with SQL and through the API
  • Example#1927 - Commit and rollback
  • Example#1928 - Accessing result set meta data
  • Example#1929 - Prepared statements metadata
  • Example#1930 - MySQLi extension overview example
  • Example#1931 - $mysqli->affected_rows example
  • Example#1932 - mysqli::autocommit example
  • Example#1933 - $mysqli->begin_transaction example
  • Example#1934 - mysqli::change_user example
  • Example#1935 - mysqli::character_set_name example
  • Example#1936 - mysqli::commit example
  • Example#1937 - $mysqli->connect_errno example
  • Example#1938 - $mysqli->connect_error example
  • Example#1939 - mysqli::__construct example
  • Example#1940 - Generating a Trace File
  • Example#1941 - $mysqli->errno example
  • Example#1942 - $mysqli->error_list example
  • Example#1943 - $mysqli->error example
  • Example#1944 - $mysqli->field_count example
  • Example#1945 - mysqli::get_charset example
  • Example#1946 - mysqli_get_client_info
  • Example#1947 - mysqli_get_client_version
  • Example#1948 - A mysqli_get_connection_stats example
  • Example#1949 - $mysqli->host_info example
  • Example#1950 - $mysqli->protocol_version example
  • Example#1951 - $mysqli->server_info example
  • Example#1952 - $mysqli->server_version example
  • Example#1953 - $mysqli->info example
  • Example#1954 - $mysqli->insert_id example
  • Example#1955 - mysqli::kill example
  • Example#1956 - mysqli::multi_query example
  • Example#1957 - mysqli::ping example
  • Example#1958 - A mysqli_poll example
  • Example#1959 - mysqli::prepare example
  • Example#1960 - mysqli::query example
  • Example#1961 - mysqli::real_connect example
  • Example#1962 - mysqli::real_escape_string example
  • Example#1963 - mysqli::rollback example
  • Example#1964 - mysqli::select_db example
  • Example#1965 - mysqli::set_charset example
  • Example#1966 - mysqli::set_local_infile_handler example
  • Example#1967 - $mysqli->sqlstate example
  • Example#1968 - mysqli::stat example
  • Example#1969 - $mysqli->thread_id example
  • Example#1970 - mysqli::use_result example
  • Example#1971 - $mysqli->warning_count example
  • Example#1972 - Object oriented style
  • Example#1973 - Procedural style
  • Example#1974 - Object oriented style
  • Example#1975 - Procedural style
  • Example#1976 - Object oriented style
  • Example#1977 - Procedural style
  • Example#1978 - Object oriented style
  • Example#1979 - Procedural style
  • Example#1980 - Object oriented style
  • Example#1981 - Procedural style
  • Example#1982 - Object oriented style
  • Example#1983 - Procedural style
  • Example#1984 - Object oriented style
  • Example#1985 - Procedural style
  • Example#1986 - Object oriented style
  • Example#1987 - Procedural style
  • Example#1988 - Object oriented style
  • Example#1989 - Procedural style
  • Example#1990 - Object oriented style
  • Example#1991 - Procedural style
  • Example#1992 - Object oriented style
  • Example#1993 - Procedural style
  • Example#1994 - Object oriented style
  • Example#1995 - Procedural style
  • Example#1996 - Object oriented style
  • Example#1997 - Procedural style
  • Example#1998 - Object oriented style
  • Example#1999 - Procedural style
  • Example#2000 - Object oriented style
  • Example#2001 - Object oriented style
  • Example#2002 - Procedural style
  • Example#2003 - Object oriented style
  • Example#2004 - Procedural style
  • Example#2005 - Object oriented style
  • Example#2006 - Procedural style
  • Example#2007 - Object oriented style
  • Example#2008 - Procedural style
  • Example#2009 - Object oriented style
  • Example#2010 - Procedural style
  • Example#2011 - Object oriented style
  • Example#2012 - Procedural style
  • Example#2013 - A mysqli_result example comparing iterator usage
  • Example#2014 - Object oriented style
  • Example#2015 - Procedural style
  • Example#2016 - Object oriented style
  • Example#2017 - Procedural style
  • Example#2018 - Object oriented style
  • Example#2019 - Procedural style
  • Example#2020 - Object oriented style
  • Example#2021 - Procedural style
  • Example#2022 - Object oriented style
  • Example#2023 - Procedural style
  • Example#2024 - Object oriented style
  • Example#2025 - Procedural style
  • Example#2026 - Object oriented style
  • Example#2027 - Procedural style
  • Example#2028 - Object oriented style
  • Example#2029 - Procedural style
  • Example#2030 - Object oriented style
  • Example#2031 - Procedural style
  • Example#2032 - Object oriented style
  • Example#2033 - Procedural style
  • Example#2034 - mysqli_connect example
  • Example#2035 - A mysqli_get_client_stats example
  • Example#2036 - Connecting to a MySQL Server
  • Example#2037 - Creating a Schema and Collection on the MySQL Server
  • Example#2038 - Storing and Retrieving Data
  • Example#2039 - Fetching and Iterating Multiple Documents
  • Example#2040 - mysql_xdevapi\Expression example
  • Example#2041 - URI examples
  • Example#2042 - mysql_xdevapi\getSession example
  • Example#2043 - mysql_xdevapi\RowResult::getWarnings example
  • Example#2044 - mysql_xdevapi\RowResult::getWarningsCount example
  • Example#2045 - mysql_xdevapi\Client::__construct example
  • Example#2046 - mysql_xdevapi\Collection::add example
  • Example#2047 - mysql_xdevapi\Collection::addOrReplaceOne example
  • Example#2048 - mysql_xdevapi\Collection::getOne example
  • Example#2049 - mysql_xdevapi\Collection::count example
  • Example#2050 - mysql_xdevapi\Collection::createIndex example
  • Example#2051 - mysql_xdevapi\Collection::dropIndex example
  • Example#2052 - mysql_xdevapi\Collection::existsInDatabase example
  • Example#2053 - mysql_xdevapi\Collection::find example
  • Example#2054 - mysql_xdevapi\Collection::getName example
  • Example#2055 - mysql_xdevapi\Collection::getOne example
  • Example#2056 - mysql_xdevapi\Collection::getSchema example
  • Example#2057 - mysql_xdevapi\Collection::getSession example
  • Example#2058 - mysql_xdevapi\Collection::modify example
  • Example#2059 - mysql_xdevapi\Collection::remove example
  • Example#2060 - mysql_xdevapi\Collection::removeOne example
  • Example#2061 - mysql_xdevapi\Collection::replaceOne example
  • Example#2062 - mysql_xdevapi\CollectionAdd::__construct example
  • Example#2063 - mysql_xdevapi\CollectionAdd::execute example
  • Example#2064 - mysql_xdevapi\CollectionFind::bind example
  • Example#2065 - CollectionFind example
  • Example#2066 - CollectionFind example
  • Example#2067 - mysql_xdevapi\CollectionFind::fields example
  • Example#2068 - mysql_xdevapi\CollectionFind::groupBy example
  • Example#2069 - mysql_xdevapi\CollectionFind::having example
  • Example#2070 - mysql_xdevapi\CollectionFind::limit example
  • Example#2071 - mysql_xdevapi\CollectionFind::lockExclusive example
  • Example#2072 - mysql_xdevapi\CollectionFind::lockShared example
  • Example#2073 - mysql_xdevapi\CollectionFind::offset example
  • Example#2074 - mysql_xdevapi\CollectionFind::sort example
  • Example#2075 - mysql_xdevapi\CollectionModify::arrayAppend example
  • Example#2076 - mysql_xdevapi\CollectionModify::arrayInsert example
  • Example#2077 - mysql_xdevapi\CollectionModify::bind example
  • Example#2078 - mysql_xdevapi\CollectionModify::__construct example
  • Example#2079 - mysql_xdevapi\CollectionModify::execute example
  • Example#2080 - mysql_xdevapi\CollectionModify::limit example
  • Example#2081 - mysql_xdevapi\CollectionModify::patch example
  • Example#2082 - mysql_xdevapi\CollectionModify::replace example
  • Example#2083 - mysql_xdevapi\CollectionModify::set example
  • Example#2084 - mysql_xdevapi\CollectionModify::skip example
  • Example#2085 - mysql_xdevapi\CollectionModify::sort example
  • Example#2086 - mysql_xdevapi\CollectionModify::unset example
  • Example#2087 - mysql_xdevapi\CollectionRemove::bind example
  • Example#2088 - mysql_xdevapi\Collection::remove example
  • Example#2089 - mysql_xdevapi\CollectionRemove::execute example
  • Example#2090 - mysql_xdevapi\CollectionRemove::limit example
  • Example#2091 - mysql_xdevapi\CollectionRemove::sort example
  • Example#2092 - mysql_xdevapi\ColumnResult::__construct example
  • Example#2093 - mysql_xdevapi\ColumnResult::getCharacterSetName example
  • Example#2094 - mysql_xdevapi\ColumnResult::getCollationName example
  • Example#2095 - mysql_xdevapi\ColumnResult::getColumnLabel example
  • Example#2096 - mysql_xdevapi\ColumnResult::getColumnName example
  • Example#2097 - mysql_xdevapi\ColumnResult::getFractionalDigits example
  • Example#2098 - mysql_xdevapi\ColumnResult::getLength example
  • Example#2099 - mysql_xdevapi\ColumnResult::getSchemaName example
  • Example#2100 - mysql_xdevapi\ColumnResult::getTableLabel example
  • Example#2101 - mysql_xdevapi\ColumnResult::getTableName example
  • Example#2102 - mysql_xdevapi\ColumnResult::getType example
  • Example#2103 - mysql_xdevapi\ColumnResult::isNumberSigned example
  • Example#2104 - mysql_xdevapi\ColumnResult::isPadded example
  • Example#2105 - mysql_xdevapi\CrudOperationBindable::bind example
  • Example#2106 - mysql_xdevapi\CrudOperationLimitable::limit example
  • Example#2107 - mysql_xdevapi\CrudOperationSkippable::skip example
  • Example#2108 - mysql_xdevapi\CrudOperationSortable::sort example
  • Example#2109 - mysql_xdevapi\DatabaseObject::existsInDatabase example
  • Example#2110 - mysql_xdevapi\DatabaseObject::getName example
  • Example#2111 - mysql_xdevapi\DatabaseObject::getSession example
  • Example#2112 - A DocResult example
  • Example#2113 - mysql_xdevapi\DocResult::fetchAll example
  • Example#2114 - mysql_xdevapi\DocResult::fetchOne example
  • Example#2115 - mysql_xdevapi\DocResult::getWarnings example
  • Example#2116 - mysql_xdevapi\DocResult::getWarningsCount example
  • Example#2117 - execute() examples
  • Example#2118 - mysql_xdevapi\ExecutionStatus::__construct example
  • Example#2119 - mysql_xdevapi\Expression::__construct example
  • Example#2120 - mysql_xdevapi\Result::__construct example
  • Example#2121 - mysql_xdevapi\Result::getAffectedItemsCount example
  • Example#2122 - mysql_xdevapi\Result::getAutoIncrementValue example
  • Example#2123 - mysql_xdevapi\Result::getGeneratedIds example
  • Example#2124 - mysql_xdevapi\RowResult::getWarnings example
  • Example#2125 - mysql_xdevapi\RowResult::getWarningsCount example
  • Example#2126 - mysql_xdevapi\RowResult::__construct example
  • Example#2127 - mysql_xdevapi\RowResult::fetchAll example
  • Example#2128 - mysql_xdevapi\RowResult::fetchOne example
  • Example#2129 - mysql_xdevapi\RowResult::getColumnsCount example
  • Example#2130 - mysql_xdevapi\RowResult::getColumnNames example
  • Example#2131 - mysql_xdevapi\RowResult::getColumns example
  • Example#2132 - mysql_xdevapi\RowResult::getWarnings example
  • Example#2133 - mysql_xdevapi\RowResult::getWarningsCount example
  • Example#2134 - Schema::__construct example
  • Example#2135 - Schema::createCollection example
  • Example#2136 - Schema::dropCollection example
  • Example#2137 - Schema::existsInDatabase example
  • Example#2138 - Schema::getCollection example
  • Example#2139 - Schema::getCollectionAsTable example
  • Example#2140 - mysql_xdevapi\Schema::getCollections example
  • Example#2141 - mysql_xdevapi\Schema::getName example
  • Example#2142 - mysql_xdevapi\Schema::getSession example
  • Example#2143 - mysql_xdevapi\Schema::getTable example
  • Example#2144 - mysql_xdevapi\Schema::getTables example
  • Example#2145 - mysql_xdevapi\Session::getSchema example
  • Example#2146 - mysql_xdevapi\Session::close example
  • Example#2147 - mysql_xdevapi\Session::commit example
  • Example#2148 - mysql_xdevapi\Session::__construct example
  • Example#2149 - mysql_xdevapi\Session::createSchema example
  • Example#2150 - mysql_xdevapi\Session::dropSchema example
  • Example#2151 - mysql_xdevapi\Session::generateUuid example
  • Example#2152 - mysql_xdevapi\Session::getSchema example
  • Example#2153 - mysql_xdevapi\Session::getSchema example
  • Example#2154 - mysql_xdevapi\Session::getSchemas example
  • Example#2155 - mysql_xdevapi\Session::getServerVersion example
  • Example#2156 - mysql_xdevapi\Session::listClients example
  • Example#2157 - mysql_xdevapi\Session::quoteName example
  • Example#2158 - mysql_xdevapi\Session::releaseSavepoint example
  • Example#2159 - mysql_xdevapi\Session::rollback example
  • Example#2160 - mysql_xdevapi\Session::rollbackTo example
  • Example#2161 - mysql_xdevapi\Session::setSavepoint example
  • Example#2162 - mysql_xdevapi\Session::sql example
  • Example#2163 - mysql_xdevapi\Session::startTransaction example
  • Example#2164 - mysql_xdevapi\SqlStatement::bind example
  • Example#2165 - mysql_xdevapi\SqlStatement::__construct example
  • Example#2166 - mysql_xdevapi\SqlStatement::execute example
  • Example#2167 - mysql_xdevapi\SqlStatement::getNextResult example
  • Example#2168 - mysql_xdevapi\SqlStatement::getResult example
  • Example#2169 - mysql_xdevapi\SqlStatement::hasMoreResults example
  • Example#2170 - mysql_xdevapi\SqlStatementResult::__construct example
  • Example#2171 - mysql_xdevapi\SqlStatementResult::fetchAll example
  • Example#2172 - mysql_xdevapi\SqlStatementResult::fetchOne example
  • Example#2173 - mysql_xdevapi\SqlStatementResult::getAffectedItemsCount example
  • Example#2174 - mysql_xdevapi\SqlStatementResult::getColumnsCount example
  • Example#2175 - mysql_xdevapi\SqlStatementResult::getColumnNames example
  • Example#2176 - mysql_xdevapi\SqlStatementResult::getColumns example
  • Example#2177 - mysql_xdevapi\SqlStatementResult::getGeneratedIds example
  • Example#2178 - mysql_xdevapi\SqlStatementResult::getLastInsertId example
  • Example#2179 - mysql_xdevapi\SqlStatementResult::getWarnings example
  • Example#2180 - mysql_xdevapi\SqlStatementResult::getWarningsCount example
  • Example#2181 - mysql_xdevapi\SqlStatementResult::hasData example
  • Example#2182 - mysql_xdevapi\SqlStatementResult::nextResult example
  • Example#2183 - mysql_xdevapi\Statement::__construct example
  • Example#2184 - mysql_xdevapi\Statement::getNextResult example
  • Example#2185 - mysql_xdevapi\Statement::getResult example
  • Example#2186 - mysql_xdevapi\Statement::hasMoreResults example
  • Example#2187 - mysql_xdevapi\Table::__construct example
  • Example#2188 - mysql_xdevapi\Table::count example
  • Example#2189 - mysql_xdevapi\Table::delete example
  • Example#2190 - mysql_xdevapi\Table::existsInDatabase example
  • Example#2191 - mysql_xdevapi\Table::getName example
  • Example#2192 - mysql_xdevapi\Table::getSchema example
  • Example#2193 - mysql_xdevapi\Table::getSession example
  • Example#2194 - mysql_xdevapi\Table::insert example
  • Example#2195 - mysql_xdevapi\Table::isView example
  • Example#2196 - mysql_xdevapi\Table::count example
  • Example#2197 - mysql_xdevapi\Table::update example
  • Example#2198 - mysql_xdevapi\TableDelete::bind example
  • Example#2199 - mysql_xdevapi\TableDelete::__construct example
  • Example#2200 - mysql_xdevapi\TableDelete::execute example
  • Example#2201 - mysql_xdevapi\TableDelete::limit example
  • Example#2202 - mysql_xdevapi\TableDelete::orderBy example
  • Example#2203 - mysql_xdevapi\TableDelete::where example
  • Example#2204 - mysql_xdevapi\TableInsert::__construct example
  • Example#2205 - mysql_xdevapi\TableInsert::execute example
  • Example#2206 - mysql_xdevapi\TableInsert::values example
  • Example#2207 - mysql_xdevapi\TableSelect::bind example
  • Example#2208 - mysql_xdevapi\TableSelect::__construct example
  • Example#2209 - mysql_xdevapi\TableSelect::execute example
  • Example#2210 - mysql_xdevapi\TableSelect::groupBy example
  • Example#2211 - mysql_xdevapi\TableSelect::having example
  • Example#2212 - mysql_xdevapi\TableSelect::limit example
  • Example#2213 - mysql_xdevapi\TableSelect::lockExclusive example
  • Example#2214 - mysql_xdevapi\TableSelect::lockShared example
  • Example#2215 - mysql_xdevapi\TableSelect::offset example
  • Example#2216 - mysql_xdevapi\TableSelect::orderBy example
  • Example#2217 - mysql_xdevapi\TableSelect::where example
  • Example#2218 - mysql_xdevapi\TableUpdate::bind example
  • Example#2219 - mysql_xdevapi\TableUpdate::__construct example
  • Example#2220 - mysql_xdevapi\TableUpdate::execute example
  • Example#2221 - mysql_xdevapi\TableUpdate::limit example
  • Example#2222 - mysql_xdevapi\TableUpdate::orderby example
  • Example#2223 - mysql_xdevapi\TableUpdate::set example
  • Example#2224 - mysql_xdevapi\TableUpdate::where example
  • Example#2225 - mysql_xdevapi\Warning::__construct example
  • Example#2226 - MySQL extension overview example
  • Example#2227 - mysql_affected_rows example
  • Example#2228 - mysql_affected_rows example using transactions
  • Example#2229 - mysql_client_encoding example
  • Example#2230 - mysql_close example
  • Example#2231 - mysql_connect example
  • Example#2232 - mysql_connect example using hostname:port syntax
  • Example#2233 - mysql_connect example using ":/path/to/socket" syntax
  • Example#2234 - mysql_create_db alternative example
  • Example#2235 - mysql_data_seek example
  • Example#2236 - mysql_db_name example
  • Example#2237 - mysql_db_query alternative example
  • Example#2238 - mysql_drop_db alternative example
  • Example#2239 - mysql_errno example
  • Example#2240 - mysql_error example
  • Example#2241 - mysql_escape_string example
  • Example#2242 - Query with aliased duplicate field names
  • Example#2243 - mysql_fetch_array with MYSQL_NUM
  • Example#2244 - mysql_fetch_array with MYSQL_ASSOC
  • Example#2245 - mysql_fetch_array with MYSQL_BOTH
  • Example#2246 - An expanded mysql_fetch_assoc example
  • Example#2247 - mysql_fetch_field example
  • Example#2248 - A mysql_fetch_lengths example
  • Example#2249 - mysql_fetch_object example
  • Example#2250 - mysql_fetch_object example
  • Example#2251 - Fetching one row with mysql_fetch_row
  • Example#2252 - A mysql_field_flags example
  • Example#2253 - mysql_field_len example
  • Example#2254 - mysql_field_name example
  • Example#2255 - A mysql_field_table example
  • Example#2256 - mysql_field_type example
  • Example#2257 - A mysql_free_result example
  • Example#2258 - mysql_get_client_info example
  • Example#2259 - mysql_get_host_info example
  • Example#2260 - mysql_get_proto_info example
  • Example#2261 - mysql_get_server_info example
  • Example#2262 - Relevant MySQL Statements
  • Example#2263 - mysql_insert_id example
  • Example#2264 - mysql_list_dbs example
  • Example#2265 - Alternate to deprecated mysql_list_fields
  • Example#2266 - mysql_list_processes example
  • Example#2267 - mysql_list_tables alternative example
  • Example#2268 - A mysql_num_fields example
  • Example#2269 - mysql_num_rows example
  • Example#2270 - A mysql_ping example
  • Example#2271 - Invalid Query
  • Example#2272 - Valid Query
  • Example#2273 - Simple mysql_real_escape_string example
  • Example#2274 - mysql_real_escape_string requires a connection example
  • Example#2275 - An example SQL Injection Attack
  • Example#2276 - mysql_result example
  • Example#2277 - mysql_select_db example
  • Example#2278 - mysql_stat example
  • Example#2279 - Alternative mysql_stat example
  • Example#2280 - mysql_tablename example
  • Example#2281 - mysql_thread_id example
  • Example#2282 - Enabling the plugin (php.ini)
  • Example#2283 - Minimal plugin-specific configuration file (mysqlnd_ms_plugin.ini)
  • Example#2284 - Recommended minimal plugin-specific config (mysqlnd_ms_plugin.ini)
  • Example#2285 - Using one server as a master and as a slave (testing only!)
  • Example#2286 - Plugin specific configuration file (mysqlnd_ms_plugin.ini)
  • Example#2287 - Opening a load balanced connection
  • Example#2288 - Executing statements
  • Example#2289 - Plugin config with one slave and one master
  • Example#2290 - Pitfall: connection state and SQL user variables
  • Example#2291 - Plugin config with one slave and one master
  • Example#2292 - SQL hints to prevent connection switches
  • Example#2293 - Fighting replication lag
  • Example#2294 - Table creation on a slave
  • Example#2295 - Plugin config with one slave and one master
  • Example#2296 - Using SQL hints for transactions
  • Example#2297 - Transaction aware load balancing: trx_stickiness setting
  • Example#2298 - Transaction aware
  • Example#2299 - General pattern for XA transactions
  • Example#2300 - Local and global transactions are mutually exclusive
  • Example#2301 - Transaction coordinator state store
  • Example#2302 - Session consistency: read your writes
  • Example#2303 - Requesting session consistency
  • Example#2304 - Maximum age/slave lag
  • Example#2305 - Limiting slave lag
  • Example#2306 - Fail over not set
  • Example#2307 - No slave within time limit
  • Example#2308 - Create counter table on master
  • Example#2309 - Plugin config: SQL for client-side GTID injection
  • Example#2310 - Transparent global transaction ID injection
  • Example#2311 - Plugin config: SQL for fetching GTID
  • Example#2312 - Obtaining GTID after injection
  • Example#2313 - Plugin config: Checking for a certain GTID
  • Example#2314 - Session consistency service level and GTID combined
  • Example#2315 - Plugin config: using MySQL 5.6.5-m8 built-in GTID feature
  • Example#2316 - Recap: quality of service to request read your writes
  • Example#2317 - Plugin config: no special entries for caching
  • Example#2318 - Caching a slave request
  • Example#2319 - Read your writes and caching combined
  • Example#2320 - Manual failover, automatic optional
  • Example#2321 - Manual failover
  • Example#2322 - Cluster node groups
  • Example#2323 - Manual partitioning using SQL hints
  • Example#2324 - Plugin config: Fabric hosts instead of MySQL servers
  • Example#2325 - Manual partitioning using SQL hints
  • Example#2326 - Provoking a connection error
  • Example#2327 - Connection error on query execution
  • Example#2328 - Provoking a connection error
  • Example#2329 - Most basic failover
  • Example#2330 - Provoking a transient error
  • Example#2331 - Transient error retry loop
  • Example#2332 - Enabling the plugin (php.ini)
  • Example#2333 - Basic plugin configuration (mysqlnd_ms_plugin.ini) for MySQL Replication
  • Example#2334 - Multiple primaries - multi master (php.ini)
  • Example#2335 - Primary copy with multiple primaries and paritioning
  • Example#2336 - Multiple primaries - multi master (php.ini)
  • Example#2337 - Synchronous update anywhere cluster
  • Example#2338 - General pattern for XA transactions
  • Example#2339 - Converting a PHP array (hash) into JSON format
  • Example#2340 - Using section names example
  • Example#2341 - List of anonymous slaves
  • Example#2342 - Master list using symbolic names
  • Example#2343 - Keywords to configure a server
  • Example#2344 - New roundrobin filter, old functionality
  • Example#2345 - The user filter replaces mysqlnd_ms_set_user_pick_server
  • Example#2346 - Common error message in case of configuration file issues (upto version 1.5.0)
  • Example#2347 - Improved configuration file validation since 1.5.0
  • Example#2348 - Possibly more precise error due to mysqlnd_ms.force_config_usage=1
  • Example#2349 - Minimum pluging configuration for use with MySQL Fabric
  • Example#2350 - Optional timeout for communication with Fabric
  • Example#2351 - Warnings about the violation of transaction boundaries
  • Example#2352 - Invalid filter sequence
  • Example#2353 - Random load balancing with random filter
  • Example#2354 - Random once load balancing with random filter
  • Example#2355 - Referencing error
  • Example#2356 - Assigning a weight for load balancing
  • Example#2357 - roundrobin filter
  • Example#2358 - Setting a callback
  • Example#2359 - Using a callback
  • Example#2360 - Returning random masters and slaves
  • Example#2361 - Manual partitioning
  • Example#2362 - Global limit on slave lag
  • Example#2363 - Optional master failover when failing to connect to slave (PECL/mysqlnd_ms < 1.4.0)
  • Example#2364 - New syntax since 1.4.0
  • Example#2365 - Disabling lazy connection
  • Example#2366 - String escaping on a lazy connection handle
  • Example#2367 - Master on write for consistent reads
  • Example#2368 - Using master to execute transactions
  • Example#2369 - No automatic failover, error handling pitfall
  • Example#2370 - Retry loop for transient errors
  • Example#2371 - SQL definition for the MySQL state store transaction table
  • Example#2372 - SQL definition for the MySQL state store transaction table
  • Example#2373 - SQL definition for the MySQL state store garbage collection table
  • Example#2374 - Using section names example
  • Example#2375 - List-like syntax
  • Example#2376 - Verify plugin activity in a non-threaded deployment model
  • Example#2377 - Recording statistics during shutdown
  • Example#2378 - Example demonstrating the usage of mysqlnd_ms constants
  • Example#2379 - mysqlnd_ms_dump_servers example
  • Example#2380 - mysqlnd_ms_get_last_gtid example
  • Example#2381 - mysqlnd_ms_get_last_used_connection example
  • Example#2382 - mysqlnd_ms_get_stats example
  • Example#2383 - mysqlnd_ms_match_wild example
  • Example#2384 - mysqlnd_ms_query_is_select example
  • Example#2385 - mysqlnd_ms_set_qos example
  • Example#2386 - mysqlnd_ms_set_user_pick_server example
  • Example#2387 - Enabling the plugin (php.ini)
  • Example#2388 - Using the MYSQLND_QC_ENABLE_SWITCH SQL hint
  • Example#2389 - Using the MYSQLND_QC_DISABLE_SWITCH SQL hint
  • Example#2390 - Example showing which type of statements are not cached
  • Example#2391 - Enabling caching for all statements using the mysqlnd_qc.cache_no_table ini setting
  • Example#2392 - Setting the TTL with the mysqlnd_qc.ttl ini setting
  • Example#2393 - Setting TTL with SQL hints
  • Example#2394 - Setting a callback with mysqlnd_qc_set_is_select
  • Example#2395 - Enabling the slam defense mechanism
  • Example#2396 - Collecting a query trace
  • Example#2397 - Setting the backtrace depth with the mysqlnd_qc.query_trace_bt_depth ini setting
  • Example#2398 - Collecting statistics data with the mysqlnd_qc.time_statistics ini setting
  • Example#2399 - Example mysqlnd_qc_get_cache_info usage
  • Example#2400 - Example mysqlnd_qc_get_normalized_query_trace_log usage
  • Example#2401 - Using a user-defined storage handler
  • Example#2402 - Using SQL hint constants
  • Example#2403 - Example mysqlnd_qc_set_cache_condition usage
  • Example#2404 - mysqlnd_qc_get_available_handlers example
  • Example#2405 - mysqlnd_qc_get_cache_info example
  • Example#2406 - mysqlnd_qc_get_core_stats example
  • Example#2407 - mysqlnd_qc_get_normalized_query_trace_log example
  • Example#2408 - mysqlnd_qc_get_query_trace_log example
  • Example#2409 - mysqlnd_qc_set_cache_condition example
  • Example#2410 - mysqlnd_qc_set_is_select example
  • Example#2411 - mysqlnd_qc_set_storage_handler example
  • Example#2412 - Enabling the plugin (php.ini)
  • Example#2413 - Pseudo-code: what a built-in class does
  • Example#2414 - Installing a proxy
  • Example#2415 - Proxy registration, mysqlnd_uh.enable=1
  • Example#2416 - Proxy installation disabled
  • Example#2417 - Connection proxy
  • Example#2418 - Prepared statement proxy
  • Example#2419 - Basic Monitoring
  • Example#2420 - MysqlndUhConnection::changeUser example
  • Example#2421 - MysqlndUhConnection::charsetName example
  • Example#2422 - MysqlndUhConnection::close example
  • Example#2423 - MysqlndUhConnection::connect example
  • Example#2424 - MysqlndUhConnection::endPSession example
  • Example#2425 - MysqlndUhConnection::escapeString example
  • Example#2426 - MysqlndUhConnection::getAffectedRows example
  • Example#2427 - MysqlndUhConnection::getErrorNumber example
  • Example#2428 - MysqlndUhConnection::getErrorString example
  • Example#2429 - MysqlndUhConnection::getFieldCount example
  • Example#2430 - MysqlndUhConnection::getHostInformation example
  • Example#2431 - MysqlndUhConnection::getLastInsertId example
  • Example#2432 - MysqlndUhConnection::getLastMessage example
  • Example#2433 - MysqlndUhConnection::getProtocolInformation example
  • Example#2434 - MysqlndUhConnection::getServerInformation example
  • Example#2435 - MysqlndUhConnection::getServerStatistics example
  • Example#2436 - MysqlndUhConnection::getServerVersion example
  • Example#2437 - MysqlndUhConnection::getSqlstate example
  • Example#2438 - MysqlndUhConnection::getStatistics example
  • Example#2439 - MysqlndUhConnection::getThreadId example
  • Example#2440 - MysqlndUhConnection::getWarningCount example
  • Example#2441 - MysqlndUhConnection::init example
  • Example#2442 - MysqlndUhConnection::kill example
  • Example#2443 - MysqlndUhConnection::listFields example
  • Example#2444 - MysqlndUhConnection::listMethod example
  • Example#2445 - MysqlndUhConnection::moreResults example
  • Example#2446 - MysqlndUhConnection::nextResult example
  • Example#2447 - MysqlndUhConnection::ping example
  • Example#2448 - MysqlndUhConnection::query example
  • Example#2449 - MysqlndUhConnection::queryReadResultsetHeader example
  • Example#2450 - MysqlndUhConnection::reapQuery example
  • Example#2451 - MysqlndUhConnection::refreshServer example
  • Example#2452 - MysqlndUhConnection::restartPSession example
  • Example#2453 - MysqlndUhConnection::selectDb example
  • Example#2454 - MysqlndUhConnection::sendClose example
  • Example#2455 - MysqlndUhConnection::sendQuery example
  • Example#2456 - MysqlndUhConnection::serverDumpDebugInformation example
  • Example#2457 - MysqlndUhConnection::setAutocommit example
  • Example#2458 - MysqlndUhConnection::setCharset example
  • Example#2459 - MysqlndUhConnection::setClientOption example
  • Example#2460 - MysqlndUhConnection::setServerOption example
  • Example#2461 - MysqlndUhConnection::simpleCommand example
  • Example#2462 - MysqlndUhConnection::simpleCommandHandleResponse example
  • Example#2463 - MysqlndUhConnection::sslSet example
  • Example#2464 - MysqlndUhConnection::stmtInit example
  • Example#2465 - MysqlndUhConnection::storeResult example
  • Example#2466 - MysqlndUhConnection::txCommit example
  • Example#2467 - MysqlndUhConnection::txRollback example
  • Example#2468 - MysqlndUhConnection::useResult example
  • Example#2469 - MysqlndUhPreparedStatement::execute example
  • Example#2470 - MysqlndUhPreparedStatement::prepare example
  • Example#2471 - mysqlnd_uh_convert_to_mysqlnd example
  • Example#2472 - mysqlnd_uh_set_connection_proxy example
  • Example#2473 - Enabling the plugin (php.ini)
  • Example#2474 - SQL table used for the Quickstart
  • Example#2475 - Basic example.
  • Example#2476 - mysqlnd_memcache_get_config example
  • Example#2477 - mysqlnd_memcache_set example with var_dump as a simple debugging callback.
  • Example#2478 - Basic query
  • Example#2479 - Inserting with bind variables
  • Example#2480 - Binding in the WHERE clause of a query
  • Example#2481 - Inserting and fetching a CLOB
  • Example#2482 - Using a PL/SQL stored function
  • Example#2483 - Using a PL/SQL stored procedure
  • Example#2484 - Calling a PL/SQL function that returns a REF CURSOR
  • Example#2485 -
  • Example#2486 - user_oci8_probes.d for tracing all user-level PHP OCI8 Static Probes with DTrace
  • Example#2487 - oci_bind_array_by_name example
  • Example#2488 - Inserting data with oci_bind_by_name
  • Example#2489 - Binding once for multiple executions
  • Example#2490 - Binding with a foreach loop
  • Example#2491 - Binding in a WHERE clause
  • Example#2492 - Binding with a LIKE clause
  • Example#2493 - Binding with REGEXP_LIKE
  • Example#2494 - Binding Multiple Values in an IN Clause
  • Example#2495 - Binding a ROWID returned by a query
  • Example#2496 - Binding a ROWID on INSERT
  • Example#2497 - Binding for a PL/SQL stored function
  • Example#2498 - Binding parameters for a PL/SQL stored procedure
  • Example#2499 - Binding a CLOB column
  • Example#2500 - Binding a PL/SQL BOOLEAN
  • Example#2501 - oci_client_version example
  • Example#2502 - Closing a connection
  • Example#2503 - Database connections are not closed until all references are closed
  • Example#2504 - Closing a connection opened more than once
  • Example#2505 - Connections are closed when variables go out of scope
  • Example#2506 - oci_commit example
  • Example#2507 - Basic oci_connect using Easy Connect syntax
  • Example#2508 - Basic oci_connect using a Network Connect name
  • Example#2509 - oci_connect with an explicit character set
  • Example#2510 - Using multiple calls to oci_connect
  • Example#2511 - oci_define_by_name example
  • Example#2512 - oci_define_by_name with case sensitive column names
  • Example#2513 - oci_define_by_name with LOB columns
  • Example#2514 - oci_define_by_name with an explicit type
  • Example#2515 - Displaying the Oracle error message after a connection error
  • Example#2516 - Displaying the Oracle error message after a parsing error
  • Example#2517 - Displaying the Oracle error message, the problematic statement, and the position of the problem of an execution error
  • Example#2518 - oci_execute for queries
  • Example#2519 - oci_execute without specifying a mode example
  • Example#2520 - oci_execute with OCI_NO_AUTO_COMMIT example
  • Example#2521 - oci_execute with different commit modes example
  • Example#2522 - oci_execute with OCI_DESCRIBE_ONLY example
  • Example#2523 - oci_fetch_all example
  • Example#2524 - oci_fetch_all example with OCI_FETCHSTATEMENT_BY_ROW
  • Example#2525 - oci_fetch_all with OCI_NUM
  • Example#2526 - oci_fetch_array with OCI_BOTH
  • Example#2527 - oci_fetch_array with OCI_NUM
  • Example#2528 - oci_fetch_array with OCI_ASSOC
  • Example#2529 - oci_fetch_array with OCI_RETURN_NULLS
  • Example#2530 - oci_fetch_array with OCI_RETURN_LOBS
  • Example#2531 - oci_fetch_array with case sensitive column names
  • Example#2532 - oci_fetch_array with columns having duplicate names
  • Example#2533 - oci_fetch_array with DATE columns
  • Example#2534 - oci_fetch_array with REF CURSOR
  • Example#2535 - Pagination with oci_fetch_array using a LIMIT-like query
  • Example#2536 - oci_fetch_array with Oracle Database 12c Implicit Result Sets
  • Example#2537 - oci_fetch_assoc Example
  • Example#2538 - oci_fetch_object example
  • Example#2539 - oci_fetch_object with case sensitive column names
  • Example#2540 - oci_fetch_object with LOBs
  • Example#2541 - oci_fetch_row Example
  • Example#2542 - oci_fetch with defined variables
  • Example#2543 - oci_fetch with oci_result
  • Example#2544 - oci_field_name example
  • Example#2545 - oci_field_name example
  • Example#2546 - oci_field_precision Example
  • Example#2547 - oci_field_scale Example
  • Example#2548 - oci_field_size example
  • Example#2549 - oci_field_type_raw Example
  • Example#2550 - oci_field_type example
  • Example#2551 - Fetching Implicit Result Sets in a loop
  • Example#2552 - Getting child statement handles individually
  • Example#2553 - Explicitly setting the Prefetch Count
  • Example#2554 - Implicit Result Set example without using oci_get_implicit_resultset
  • Example#2555 - oci_new_connect example
  • Example#2556 - Binding a REF CURSOR in an Oracle stored procedure call
  • Example#2557 - oci_new_descriptor example
  • Example#2558 - oci_new_descriptor example
  • Example#2559 - oci_num_fields example
  • Example#2560 - oci_num_rows example
  • Example#2561 - oci_parse example for SQL statements
  • Example#2562 - oci_parse example for PL/SQL statements
  • Example#2563 - oci_password_change example changing the password of an already connected user
  • Example#2564 - oci_password_change example of connecting and changing the password in one step
  • Example#2565 - Basic oci_pconnect Example using Easy Connect syntax
  • Example#2566 - oci_fetch with oci_result
  • Example#2567 - oci_rollback example
  • Example#2568 - Rolling back to a SAVEPOINT example
  • Example#2569 - oci_server_version example
  • Example#2570 - Setting the action
  • Example#2571 - Setting the timeout
  • Example#2572 - Setting the client identifier to the application user
  • Example#2573 - Setting the client information
  • Example#2574 - Setting the DBOP
  • Example#2575 - Two scripts can use different versions of myfunc() at the same time
  • Example#2576 - Setting the module name
  • Example#2577 - Changing the default prefetch value for a query
  • Example#2578 - Changing the default prefetch for a REF CURSOR fetch
  • Example#2579 - Setting the prefetch value when passing a REF CURSOR back to Oracle
  • Example#2580 - oci_statement_type example
  • Example#2581 - Creating a Paradox database with two fields
  • Example#2582 - Turn a paradox date into a human readable form
  • Example#2583 - Set the date/time fields in a paradox database to the current date/time
  • Example#2584 - Opening a Paradox database
  • Example#2585 - Opening a Paradox database
  • Example#2586 - Turn a paradox timestamp into a human readable form
  • Example#2587 - PostgreSQL extension overview example
  • Example#2588 - PostgreSQL user defined functions example
  • Example#2589 - pg_affected_rows example
  • Example#2590 - pg_cancel_query example
  • Example#2591 - pg_client_encoding example
  • Example#2592 - pg_close example
  • Example#2593 - Using pg_connect
  • Example#2594 - pg_connection_busy example
  • Example#2595 - pg_connection_reset example
  • Example#2596 - pg_connection_status example
  • Example#2597 - pg_convert example
  • Example#2598 - pg_copy_from example
  • Example#2599 - pg_copy_to example
  • Example#2600 - pg_dbname example
  • Example#2601 - pg_delete example
  • Example#2602 - pg_end_copy example
  • Example#2603 - pg_escape_bytea example
  • Example#2604 - pg_escape_identifier example
  • Example#2605 - pg_escape_literal example
  • Example#2606 - pg_escape_string example
  • Example#2607 - Using pg_execute
  • Example#2608 - pg_fetch_all_columns example
  • Example#2609 - PostgreSQL fetch all
  • Example#2610 - pg_fetch_array example
  • Example#2611 - pg_fetch_assoc example
  • Example#2612 - pg_fetch_object example
  • Example#2613 - pg_fetch_result example
  • Example#2614 - pg_fetch_row example
  • Example#2615 - pg_field_is_null example
  • Example#2616 - Getting information about fields
  • Example#2617 - Getting information about fields
  • Example#2618 - Getting information about fields
  • Example#2619 - Getting information about fields
  • Example#2620 - Getting table information about a field
  • Example#2621 - Getting information about fields
  • Example#2622 - Getting information about fields
  • Example#2623 - pg_free_result example
  • Example#2624 - PostgreSQL NOTIFY message
  • Example#2625 - PostgreSQL backend PID
  • Example#2626 - pg_get_result example
  • Example#2627 - pg_host example
  • Example#2628 - pg_insert example
  • Example#2629 - pg_last_error example
  • Example#2630 - pg_last_notice example
  • Example#2631 - pg_last_oid example
  • Example#2632 - pg_lo_close example
  • Example#2633 - pg_lo_create example
  • Example#2634 - pg_lo_export example
  • Example#2635 - pg_lo_import example
  • Example#2636 - pg_lo_open example
  • Example#2637 - pg_lo_read_all example
  • Example#2638 - pg_lo_read example
  • Example#2639 - pg_lo_seek example
  • Example#2640 - pg_lo_tell example
  • Example#2641 - pg_lo_truncate example
  • Example#2642 - pg_lo_unlink example
  • Example#2643 - pg_lo_write example
  • Example#2644 - Getting table metadata
  • Example#2645 - pg_num_fields example
  • Example#2646 - pg_num_rows example
  • Example#2647 - pg_options example
  • Example#2648 - pg_parameter_status example
  • Example#2649 - Using pg_pconnect
  • Example#2650 - pg_ping example
  • Example#2651 - pg_port example
  • Example#2652 - Using pg_prepare
  • Example#2653 - pg_put_line example
  • Example#2654 - Using pg_query_params
  • Example#2655 - pg_query example
  • Example#2656 - Using pg_query with multiple statements
  • Example#2657 - pg_result_error_field example
  • Example#2658 - pg_result_error example
  • Example#2659 - pg_result_seek example
  • Example#2660 - pg_result_status example
  • Example#2661 - pg_select example
  • Example#2662 - Using pg_send_execute
  • Example#2663 - Using pg_send_prepare
  • Example#2664 - Using pg_send_query_params
  • Example#2665 - pg_send_query example
  • Example#2666 - pg_set_client_encoding example
  • Example#2667 - pg_set_error_verbosity example
  • Example#2668 - pg_trace example
  • Example#2669 - pg_transaction_status example
  • Example#2670 - pg_tty example
  • Example#2671 - pg_unescape_bytea example
  • Example#2672 - pg_untrace example
  • Example#2673 - pg_update example
  • Example#2674 - pg_version example
  • Example#2675 - Procedural style
  • Example#2676 - Object-oriented style
  • Example#2677 - Procedural style
  • Example#2678 - Object oriented style
  • Example#2679 - Procedural style
  • Example#2680 - Object oriented style
  • Example#2681 - sqlite_close example
  • Example#2682 - max_length aggregation function example
  • Example#2683 - sqlite_create_function example
  • Example#2684 - Example of using the PHP function
  • Example#2685 - Procedural example
  • Example#2686 - Object-oriented example
  • Example#2687 - sqlite_factory example
  • Example#2688 - Procedural example
  • Example#2689 - Object-oriented example
  • Example#2690 - Procedural example
  • Example#2691 - Object-oriented example
  • Example#2692 - Procedural example
  • Example#2693 - Object-oriented example
  • Example#2694 - A sqlite_fetch_single example
  • Example#2695 - Procedural example
  • Example#2696 - Object-oriented example
  • Example#2697 - sqlite_open example
  • Example#2698 - binary-safe max_length aggregation function example
  • Example#2699 - SQLite3::changes example
  • Example#2700 - SQLite3::close example
  • Example#2701 - SQLite3::__construct example
  • Example#2702 - max_length aggregation function example
  • Example#2703 - SQLite3::createCollation example
  • Example#2704 - SQLite3::createFunction example
  • Example#2705 - SQLite3::enableExceptions example
  • Example#2706 - SQLite3::exec example
  • Example#2707 - SQLite3::loadExtension example
  • Example#2708 - SQLite3::open example
  • Example#2709 - SQLite3::openBlob example
  • Example#2710 - Incrementally writing a BLOB
  • Example#2711 - SQLite3::prepare example
  • Example#2712 - SQLite3::query example
  • Example#2713 - SQLite3::querySingle example
  • Example#2714 - SQLite3::version example
  • Example#2715 - SQLite3Stmt::bindParam Usage
  • Example#2716 - SQLite3Stmt::bindValue example
  • Example#2717 - Inspecting the expanded SQL
  • Example#2718 - sqlsrv_begin_transaction example
  • Example#2719 - sqlsrv_cancel example
  • Example#2720 - sqlsrv_client_info example
  • Example#2721 - sqlsrv_close example
  • Example#2722 - sqlsrv_commit example
  • Example#2723 - Connect using Windows Authentication.
  • Example#2724 - Connect by specifying a user name and password.
  • Example#2725 - Connect on a specified port.
  • Example#2726 - functionname example
  • Example#2727 - sqlsrv_execute example
  • Example#2728 - Retrieving an associative array.
  • Example#2729 - Retrieving a numeric array.
  • Example#2730 - sqlsrv_fetch_object example
  • Example#2731 - sqlsrv_fetch example
  • Example#2732 - sqlsrv_field_metadata example
  • Example#2733 - sqlsrv_free_stmt example
  • Example#2734 - sqlsrv_get_field example
  • Example#2735 - sqlsrv_has_rows example
  • Example#2736 - sqlsrv_next_result example
  • Example#2737 - sqlsrv_num_fields example
  • Example#2738 - sqlsrv_num_rows example
  • Example#2739 - sqlsrv_prepare example
  • Example#2740 - sqlsrv_query example
  • Example#2741 - sqlsrv_rollback example
  • Example#2742 - sqlsrv_rows_affected example
  • Example#2743 - sqlsrv_send_stream_data example
  • Example#2744 - sqlsrv_server_info example
  • Example#2745 - Delete-Query
  • Example#2746 - sybase_connect example
  • Example#2747 - Identical fieldnames
  • Example#2748 - sybase_fetch_object return as Foo
  • Example#2749 - sybase_set_message_handler callback function
  • Example#2750 - sybase_set_message_handler callback to a class
  • Example#2751 - sybase_set_message_handler unhandled messages
  • Example#2752 - sybase_unbuffered_query example
  • Example#2753 - Putting and getting a key-value pair
  • Example#2754 - TokyoTyrant::add example
  • Example#2755 - TokyoTyrant::connect example
  • Example#2756 - TokyoTyrant::connectUri example
  • Example#2757 - TokyoTyrant::copy example
  • Example#2758 - TokyoTyrant::ext example
  • Example#2759 - TokyoTyrant::fwmKeys example
  • Example#2760 - TokyoTyrant::get example
  • Example#2761 - TokyoTyrant::getIterator example
  • Example#2762 - TokyoTyrant::num example
  • Example#2763 - TokyoTyrant::out example
  • Example#2764 - TokyoTyrant::put example
  • Example#2765 - TokyoTyrant::putCat example
  • Example#2766 - tokyotyrant::putKeep example
  • Example#2767 - TokyoTyrant::putNr example
  • Example#2768 - TokyoTyrant::putShl example
  • Example#2769 - TokyoTyrant::setMaster example
  • Example#2770 - TokyoTyrant::size example
  • Example#2771 - TokyoTyrant::stat example
  • Example#2772 - TokyoTyrant::vanish example
  • Example#2773 - TokyoTyrantTable::genUid example
  • Example#2774 - TokyoTyrantTable::get example
  • Example#2775 - TokyoTyrantTable::getIterator example
  • Example#2776 - TokyoTyrantTable::getQuery example
  • Example#2777 - TokyoTyrantTable::out example
  • Example#2778 - TokyoTyrantTable::put example
  • Example#2779 - TokyoTyrantTable::putCat example
  • Example#2780 - TokyoTyrantTable::putKeep example
  • Example#2781 - TokyoTyrantQuery::addCond example
  • Example#2782 - TokyoTyrantQuery::__construct example
  • Example#2783 - TokyoTyrantQuery::count example
  • Example#2784 - TokyoTyrantQuery iterator example
  • Example#2785 - TokyoTyrantQuery::hint example
  • Example#2786 - TokyoTyrantQuery iterator example
  • Example#2787 - TokyoTyrantQuery::metaSearch example
  • Example#2788 - TokyoTyrantQuery iterator example
  • Example#2789 - TokyoTyrantQuery::out example
  • Example#2790 - TokyoTyrantQuery iterator example
  • Example#2791 - TokyoTyrantQuery::search example
  • Example#2792 - TokyoTyrantQuery iterator example
  • Example#2793 - TokyoTyrantIterator::__construct example
  • Example#2794 - cal_days_in_month example
  • Example#2795 - cal_from_jd example
  • Example#2796 - cal_info example
  • Example#2797 - easter_date example
  • Example#2798 - easter_days example
  • Example#2799 - Calendar functions
  • Example#2800 - Overflow behavior
  • Example#2801 - jdtojewish Example
  • Example#2802 - DateTime::add/sub add intervals which cover elapsed time
  • Example#2803 - DateTime::modify and strtotime increment or decrement individual component values
  • Example#2804 - Adding or subtracting times can over- or underflow dates
  • Example#2805 - DateTime::add example
  • Example#2806 - Further DateTime::add examples
  • Example#2807 - Beware when adding months
  • Example#2808 - DateTime::__construct example
  • Example#2809 - Intricacies of DateTime::__construct
  • Example#2810 - DateTime::createFromFormat example
  • Example#2811 - Intricacies of DateTime::createFromFormat
  • Example#2812 - Format string with literal characters
  • Example#2813 - Creating a mutable date time object
  • Example#2814 - DateTime::getLastErrors example
  • Example#2815 - DateTime::modify example
  • Example#2816 - Beware when adding or subtracting months
  • Example#2817 - DateTime::setDate example
  • Example#2818 - Values exceeding ranges are added to their parent values
  • Example#2819 - DateTime::setISODate example
  • Example#2820 - Values exceeding ranges are added to their parent values
  • Example#2821 - Finding the month a week is in
  • Example#2822 - DateTime::setTime example
  • Example#2823 - Values exceeding ranges are added to their parent values
  • Example#2824 - DateTime::setTimestamp example
  • Example#2825 - DateTime::setTimestamp alternative in PHP 5.2
  • Example#2826 - DateTime::setTimeZone example
  • Example#2827 - DateTime::sub example
  • Example#2828 - Further DateTime::sub examples
  • Example#2829 - Beware when subtracting months
  • Example#2830 - Creating an immutable date time object
  • Example#2831 - DateTime::diff example
  • Example#2832 - DateTime object comparison
  • Example#2833 - DateTime::format example
  • Example#2834 - DateTime::getOffset example
  • Example#2835 - DateTime::getTimestamp example
  • Example#2836 - DateTime::getTimezone example
  • Example#2837 - Catching errors when instantiating DateTimeZone
  • Example#2838 - DateTimeZone::getLocation example
  • Example#2839 - DateTimeZone::getOffset examples
  • Example#2840 - A timezone_transitions_get example
  • Example#2841 - A timezone_abbreviations_list example
  • Example#2842 - A timezone_identifiers_list example
  • Example#2843 - DateInterval example
  • Example#2844 - Parsing valid date intervals
  • Example#2845 - DateInterval example
  • Example#2846 - DateInterval and carry over points
  • Example#2847 - DateInterval and DateTime::diff with the %a and %d modifiers
  • Example#2848 - DatePeriod example
  • Example#2849 - DatePeriod example with DatePeriod::EXCLUDE_START_DATE
  • Example#2850 - DatePeriod::getDateInterval example
  • Example#2851 - DatePeriod::getEndDate example
  • Example#2852 - DatePeriod::getEndDate without an end date
  • Example#2853 - DatePeriod::getStartDate example
  • Example#2854 - checkdate example
  • Example#2855 - Getting the default timezone
  • Example#2856 - Getting the abbreviation of a timezone
  • Example#2857 - Getting the default timezone
  • Example#2858 - date_parse_from_format example
  • Example#2859 - A date_parse example
  • Example#2860 - date_parse with relative formats
  • Example#2861 - A date_sun_info example
  • Example#2862 - Polar night
  • Example#2863 - Midnight sun
  • Example#2864 - date_sunrise example
  • Example#2865 - No sunrise
  • Example#2866 - date_sunset example
  • Example#2867 - No sunset
  • Example#2868 - date examples
  • Example#2869 - Escaping characters in date
  • Example#2870 - date and mktime example
  • Example#2871 - date Formatting
  • Example#2872 - getdate example
  • Example#2873 - gettimeofday example
  • Example#2874 - gmdate example
  • Example#2875 - gmmktime basic example
  • Example#2876 - gmstrftime example
  • Example#2877 - idate example
  • Example#2878 - localtime example
  • Example#2879 - Timing script execution with microtime
  • Example#2880 - Timing script execution in PHP 5
  • Example#2881 - microtime and REQUEST_TIME_FLOAT (as of PHP 5.4.0)
  • Example#2882 - mktime basic example
  • Example#2883 - mktime example
  • Example#2884 - Last day of a month
  • Example#2885 - strftime locale examples
  • Example#2886 - ISO 8601:1988 week number example
  • Example#2887 - Cross platform compatible example using the %e modifier
  • Example#2888 - Display all known and unknown formats.
  • Example#2889 - strptime example
  • Example#2890 - A strtotime example
  • Example#2891 - Checking for failure
  • Example#2892 - time example
  • Example#2893 - A timezone_name_from_abbr example
  • Example#2894 - Getting the timezonedb version
  • Example#2895 - Measure several code blocks execution and get the total
  • Example#2896 - Closing an open file descriptor
  • Example#2897 - Setting and clearing a lock
  • Example#2898 - Opening a file descriptor
  • Example#2899 - Positioning in a file
  • Example#2900 - Setting the baud rate on a serial port
  • Example#2901 - chdir example
  • Example#2902 - chroot example
  • Example#2903 - closedir example
  • Example#2904 - dir example
  • Example#2905 - getcwd example
  • Example#2906 - opendir example
  • Example#2907 - List all entries in a directory
  • Example#2908 - List all entries in the current directory and strip out . and ..
  • Example#2909 - A simple scandir example
  • Example#2910 - A finfo_buffer example
  • Example#2911 - A finfo_file example
  • Example#2912 - Object oriented style
  • Example#2913 - Procedural style
  • Example#2914 - mime_content_type Example
  • Example#2915 - basename example
  • Example#2916 - Changing a file's group
  • Example#2917 - Simple chown usage
  • Example#2918 - clearstatcache example
  • Example#2919 - copy example
  • Example#2920 - dirname example
  • Example#2921 - disk_free_space example
  • Example#2922 - disk_total_space example
  • Example#2923 - A simple fclose example
  • Example#2924 - Handling timeouts with feof
  • Example#2925 - feof example with an invalid file pointer
  • Example#2926 - File write example using fflush
  • Example#2927 - A fgetc example
  • Example#2928 - Read and print the entire contents of a CSV file
  • Example#2929 - Reading a file line by line
  • Example#2930 - Reading a PHP file line-by-line
  • Example#2931 - Testing whether a file exists
  • Example#2932 - Get and output the source of the homepage of a website
  • Example#2933 - Searching within the include_path
  • Example#2934 - Reading a section of a file
  • Example#2935 - Using stream contexts
  • Example#2936 - Simple usage example
  • Example#2937 - Using flags
  • Example#2938 - file example
  • Example#2939 - fileatime example
  • Example#2940 - A filectime example
  • Example#2941 - Finding the group of a file
  • Example#2942 - Comparing the inode of a file with the current file
  • Example#2943 - filemtime example
  • Example#2944 - Finding the owner of a file
  • Example#2945 - Display permissions as an octal value
  • Example#2946 - Display full permissions
  • Example#2947 - filesize example
  • Example#2948 - filetype example
  • Example#2949 - flock example
  • Example#2950 - flock using the LOCK_NB option
  • Example#2951 - Checking a color name against a shell wildcard pattern
  • Example#2952 - fopen examples
  • Example#2953 - Using fpassthru with binary files
  • Example#2954 - fputcsv example
  • Example#2955 - A simple fread example
  • Example#2956 - Binary fread example
  • Example#2957 - Remote fread examples
  • Example#2958 - fscanf Example
  • Example#2959 - Contents of users.txt
  • Example#2960 - fseek example
  • Example#2961 - fstat example
  • Example#2962 - ftell example
  • Example#2963 - File truncation example
  • Example#2964 - A simple fwrite example
  • Example#2965 - Convenient way how glob can replace opendir and friends.
  • Example#2966 - is_dir example
  • Example#2967 - is_executable example
  • Example#2968 - is_file example
  • Example#2969 - Create and confirm if a file is a symbolic link
  • Example#2970 - is_readable example
  • Example#2971 - is_uploaded_file example
  • Example#2972 - is_writable example
  • Example#2973 - Changing the group of a symbolic link
  • Example#2974 - Changing the owner of a symbolic link
  • Example#2975 - Creating a simple hard link
  • Example#2976 - linkinfo example
  • Example#2977 - Comparison of stat and lstat
  • Example#2978 - mkdir example
  • Example#2979 - mkdir using the recursive parameter
  • Example#2980 - Uploading multiple files
  • Example#2981 - Contents of sample.ini
  • Example#2982 - parse_ini_file example
  • Example#2983 - parse_ini_file parsing a php.ini file
  • Example#2984 - pathinfo Example
  • Example#2985 - pathinfo example showing difference between null and no extension
  • Example#2986 - pathinfo example for a dot-file
  • Example#2987 - pclose example
  • Example#2988 - popen example
  • Example#2989 - popen example
  • Example#2990 - Forcing a download using readfile
  • Example#2991 - readlink example
  • Example#2992 - realpath_cache_get example
  • Example#2993 - realpath_cache_size example
  • Example#2994 - realpath example
  • Example#2995 - realpath on Windows
  • Example#2996 - Example with rename
  • Example#2997 - rewind overwriting example
  • Example#2998 - rmdir example
  • Example#2999 - stat example
  • Example#3000 - Using stat information together with touch
  • Example#3001 - Create a symbolic link
  • Example#3002 - tempnam example
  • Example#3003 - tmpfile example
  • Example#3004 - touch example
  • Example#3005 - touch using the time parameter
  • Example#3006 - umask example
  • Example#3007 - Basic unlink usage
  • Example#3008 - Example usage of inotify
  • Example#3009 - Setting the path to magic.mime
  • Example#3010 - setproctitle example
  • Example#3011 - setthreadtitle example
  • Example#3012 - Checks if system administrator has signed the file
  • Example#3013 - Prints names of all extended attributes of file
  • Example#3014 - Removes all extended attributes of a file
  • Example#3015 - Sets extended attributes on .wav file
  • Example#3016 - xattr_supported example
  • Example#3017 - xdiff_file_bdiff_size example
  • Example#3018 - xdiff_file_bdiff example
  • Example#3019 - xdiff_file_bpatch example
  • Example#3020 - xdiff_file_diff_binary example
  • Example#3021 - xdiff_file_diff example
  • Example#3022 - xdiff_file_merge3 example
  • Example#3023 - xdiff_file_patch_binary example
  • Example#3024 - xdiff_file_patch example
  • Example#3025 - Patch reversing example
  • Example#3026 - xdiff_file_rabdiff example
  • Example#3027 - xdiff_string_bdiff_size example
  • Example#3028 - xdiff_string_diff example
  • Example#3029 - xdiff_string_patch example
  • Example#3030 - Enchant Usage Example
  • Example#3031 - List the backends provided by the given broker
  • Example#3032 - A enchant_broker_dict_exists example
  • Example#3033 - List all available dictionaries for one broker
  • Example#3034 - A enchant_broker_request_dict example
  • Example#3035 - Adding a word to a PWL
  • Example#3036 - A enchant_dict_describe example
  • Example#3037 - A enchant_dict_quick_check example
  • Example#3038 - A enchant_dict_suggest example
  • Example#3039 - Usage example.
  • Example#3040 - Using Gender\Gender::country
  • Example#3041 - bindtextdomain example
  • Example#3042 - gettext-check
  • Example#3043 - ngettext example
  • Example#3044 - iconv_get_encoding example
  • Example#3045 - iconv_mime_decode_headers example
  • Example#3046 - iconv_mime_decode example
  • Example#3047 - iconv_mime_encode example
  • Example#3048 - iconv_set_encoding example
  • Example#3049 - iconv example
  • Example#3050 - ob_iconv_handler example:
  • Example#3051 - Example of using the procedural API
  • Example#3052 - Example of using the object-oriented API
  • Example#3053 - FRENCH_COLLATION rules
  • Example#3054 - ALTERNATE_HANDLING rules
  • Example#3055 - CASE_FIRST rules
  • Example#3056 - CASE_LEVEL rules
  • Example#3057 - collator_asortexample
  • Example#3058 - collator_compareexample
  • Example#3059 - Collator::__construct example
  • Example#3060 - collator_create example
  • Example#3061 - collator_get_attribute example
  • Example#3062 - collator_get_error_code example
  • Example#3063 - collator_get_error_message example
  • Example#3064 - collator_get_locale example
  • Example#3065 - collator_get_sort_keyexample
  • Example#3066 - collator_get_strength example
  • Example#3067 - collator_set_attribute example
  • Example#3068 - collator_set_strength example
  • Example#3069 - collator_sort_with_sort_keys example
  • Example#3070 - collator_sort example
  • Example#3071 - numfmt_create example
  • Example#3072 - NumberFormatter::create example
  • Example#3073 - numfmt_format_currency example
  • Example#3074 - OO example
  • Example#3075 - numfmt_format example
  • Example#3076 - OO example
  • Example#3077 - numfmt_get_attribute example
  • Example#3078 - OO example
  • Example#3079 - numfmt_get_error_code example
  • Example#3080 - OO example
  • Example#3081 - numfmt_get_error_message example
  • Example#3082 - OO example
  • Example#3083 - numfmt_get_locale example
  • Example#3084 - numfmt_get_pattern example
  • Example#3085 - OO example
  • Example#3086 - numfmt_get_symbol example
  • Example#3087 - OO example
  • Example#3088 - numfmt_get_text_attribute example
  • Example#3089 - OO example
  • Example#3090 - numfmt_parse_currency example
  • Example#3091 - OO example
  • Example#3092 - numfmt_parse example
  • Example#3093 - OO example
  • Example#3094 - numfmt_set_attribute example
  • Example#3095 - OO example
  • Example#3096 - numfmt_set_pattern example
  • Example#3097 - OO example
  • Example#3098 - numfmt_set_symbol example
  • Example#3099 - OO example
  • Example#3100 - numfmt_set_text_attribute example
  • Example#3101 - OO example
  • Example#3102 - locale_accept_from_http example
  • Example#3103 - OO example
  • Example#3104 - locale_compose example
  • Example#3105 - OO example
  • Example#3106 - locale_filter_matches example
  • Example#3107 - OO example
  • Example#3108 - locale_get_all_variants example
  • Example#3109 - OO example
  • Example#3110 - locale_get_default example
  • Example#3111 - OO example
  • Example#3112 - locale_get_display_language example
  • Example#3113 - OO example
  • Example#3114 - locale_get_display_name example
  • Example#3115 - OO example
  • Example#3116 - locale_get_display_region example
  • Example#3117 - OO example
  • Example#3118 - locale_get_display_script example
  • Example#3119 - OO example
  • Example#3120 - locale_get_display_variant example
  • Example#3121 - OO example
  • Example#3122 - locale_get_keywords example
  • Example#3123 - OO example
  • Example#3124 - locale_get_primary_language example
  • Example#3125 - OO example
  • Example#3126 - locale_get_region example
  • Example#3127 - OO example
  • Example#3128 - locale_get_script example
  • Example#3129 - OO example
  • Example#3130 - locale_lookup example
  • Example#3131 - OO example
  • Example#3132 - locale_parse example
  • Example#3133 - OO example
  • Example#3134 - locale_set_default example
  • Example#3135 - OO example
  • Example#3136 - Normalizer::getRawDecomposition example
  • Example#3137 - normalizer_is_normalized example
  • Example#3138 - OO example
  • Example#3139 - normalizer_normalize example
  • Example#3140 - OO example
  • Example#3141 - msgfmt_create example
  • Example#3142 - OO example
  • Example#3143 - msgfmt_format_message example
  • Example#3144 - OO example
  • Example#3145 - msgfmt_format example
  • Example#3146 - OO example
  • Example#3147 - msgfmt_get_error_message example
  • Example#3148 - OO example
  • Example#3149 - msgfmt_get_locale example
  • Example#3150 - OO example
  • Example#3151 - msgfmt_get_pattern example
  • Example#3152 - OO example
  • Example#3153 - msgfmt_parse_message example
  • Example#3154 - OO example
  • Example#3155 - msgfmt_parse example
  • Example#3156 - OO example
  • Example#3157 - msgfmt_set_pattern example
  • Example#3158 - OO example
  • Example#3159 - IntlCalendar::add
  • Example#3160 - IntlCalendar::after
  • Example#3161 - IntlCalendar::clear examples
  • Example#3162 - IntlCalendar::createInstance
  • Example#3163 - IntlCalendar::equals
  • Example#3164 - IntlCalendar::fieldDifference
  • Example#3165 - IntlCalendar::fromDateTime
  • Example#3166 - IntlCalendar::get
  • Example#3167 - IntlCalendar::getActualMaximum
  • Example#3168 - IntlCalendar::getAvailableLocales
  • Example#3169 - IntlCalendar::getDayOfWeekType
  • Example#3170 - IntlCalendar::getErrorCode and IntlCalendar::getErrorMessage
  • Example#3171 - IntlCalendar::getErrorMessage
  • Example#3172 - IntlCalendar::getFirstDayOfWeek
  • Example#3173 - IntlCalendar::getKeyworkValuesForLocale
  • Example#3174 - Maxima examples
  • Example#3175 - IntlCalendar::getLocale
  • Example#3176 - IntlCalendar::getMinimalDaysInFirstWeek
  • Example#3177 - IntlCalendar::getNow
  • Example#3178 - IntlCalendar::getRepeatedWallTimeOption
  • Example#3179 - IntlCalendar::getSkippedWallTimeOption
  • Example#3180 - IntlCalendar::getTime
  • Example#3181 - IntlCalendar::getTimeZone
  • Example#3182 - IntlCalendar::getType
  • Example#3183 - IntlCalendar::inDaylightTime
  • Example#3184 - IntlCalendar::isEquivalentTo
  • Example#3185 - IntlCalendar::isLenient
  • Example#3186 - IntlCalendar::isWeekend
  • Example#3187 - IntlCalendar::roll
  • Example#3188 - IntlCalendar::set
  • Example#3189 - IntlCalendar::setFirstDayOfWeek
  • Example#3190 - IntlCalendar::setTime
  • Example#3191 - IntlCalendar::setTimeZone
  • Example#3192 - IntlCalendar::toDateTime
  • Example#3193 - datefmt_create example
  • Example#3194 - OO example
  • Example#3195 - datefmt_format example
  • Example#3196 - OO example
  • Example#3197 - With IntlCalendar object
  • Example#3198 - IntlDateFormatter::formatObject examples
  • Example#3199 - datefmt_get_calendar example
  • Example#3200 - OO example
  • Example#3201 - datefmt_get_datetype example
  • Example#3202 - OO example
  • Example#3203 - datefmt_get_error_code example
  • Example#3204 - OO example
  • Example#3205 - datefmt_get_error_message example
  • Example#3206 - OO example
  • Example#3207 - datefmt_get_locale example
  • Example#3208 - OO example
  • Example#3209 - datefmt_get_pattern example
  • Example#3210 - OO example
  • Example#3211 - datefmt_get_timetype example
  • Example#3212 - OO example
  • Example#3213 - datefmt_get_timezone_id example
  • Example#3214 - OO example
  • Example#3215 - IntlDateFormatter::getCalendarObject example
  • Example#3216 - IntlDateFormatter::getTimeZone examples
  • Example#3217 - datefmt_is_lenient example
  • Example#3218 - OO example
  • Example#3219 - datefmt_localtime example
  • Example#3220 - OO example
  • Example#3221 - OO example
  • Example#3222 - datefmt_parse example
  • Example#3223 - datefmt_set_calendar example
  • Example#3224 - OO example
  • Example#3225 - Example with IntlCalendar argument
  • Example#3226 - datefmt_set_lenient example
  • Example#3227 - OO example
  • Example#3228 - datefmt_set_pattern example
  • Example#3229 - OO example
  • Example#3230 - datefmt_set_timezone_id example
  • Example#3231 - OO example
  • Example#3232 - IntlDateFormatter::setTimeZone examples
  • Example#3233 - resourcebundle_count example
  • Example#3234 - OO example
  • Example#3235 - resourcebundle_create example
  • Example#3236 - ResourceBundle::create example
  • Example#3237 - resourcebundle_get_error_code example
  • Example#3238 - OO example
  • Example#3239 - resourcebundle_get_error_message example
  • Example#3240 - OO example
  • Example#3241 - resourcebundle_get example
  • Example#3242 - OO example
  • Example#3243 - resourcebundle_locales example
  • Example#3244 - OO example
  • Example#3245 - Spoofchecker::areConfusable example
  • Example#3246 - Spoofchecker::isSuspicious example
  • Example#3247 - Converting escaped UTF-16 code units
  • Example#3248 - grapheme_extract example
  • Example#3249 - grapheme_stripos example
  • Example#3250 - grapheme_stristr example
  • Example#3251 - grapheme_strlen example
  • Example#3252 - grapheme_strpos example
  • Example#3253 - grapheme_strripos example
  • Example#3254 - grapheme_strrpos example
  • Example#3255 - grapheme_strstr example
  • Example#3256 - grapheme_substr example
  • Example#3257 - idn_to_ascii example
  • Example#3258 - idn_to_utf8 example
  • Example#3259 - Testing different code points
  • Example#3260 - Testing different code points
  • Example#3261 - Testing different code points
  • Example#3262 - Testing different code points
  • Example#3263 - Testing different code points
  • Example#3264 - Testing different code points
  • Example#3265 - Testing different code points
  • Example#3266 - Testing different code points
  • Example#3267 - Testing different code points
  • Example#3268 - Enumerating over a sample range of code points
  • Example#3269 - Enumerating over a sample range of code points
  • Example#3270 - Testing different code points
  • Example#3271 - Testing different code points
  • Example#3272 - Testing different code points
  • Example#3273 - Testing different code points
  • Example#3274 - Testing different code points
  • Example#3275 - Testing different properties
  • Example#3276 - Testing different properties
  • Example#3277 - Testing different properties
  • Example#3278 - Testing different code points
  • Example#3279 - Testing different properties
  • Example#3280 - Testing different properties
  • Example#3281 - Testing different properties
  • Example#3282 - Testing different properties
  • Example#3283 - Testing different properties
  • Example#3284 - Testing different properties
  • Example#3285 - Testing different code points
  • Example#3286 - Testing different code points
  • Example#3287 - Testing different code points
  • Example#3288 - Testing different code points
  • Example#3289 - Testing different code points
  • Example#3290 - Testing different code points
  • Example#3291 - Testing different code points
  • Example#3292 - Testing different code points
  • Example#3293 - Testing different code points
  • Example#3294 - Testing different code points
  • Example#3295 - Testing different code points
  • Example#3296 - Testing different code points
  • Example#3297 - Testing different code points
  • Example#3298 - Testing different code points
  • Example#3299 - Testing different code points
  • Example#3300 - Testing different code points
  • Example#3301 - Testing different code points
  • Example#3302 - Testing different code points
  • Example#3303 - Testing different code points
  • Example#3304 - Testing different code points
  • Example#3305 - Testing different code points
  • Example#3306 - Testing different code points
  • Example#3307 - Testing different code points
  • Example#3308 - Testing different code points
  • Example#3309 - Testing different code points
  • Example#3310 - Testing different code points
  • Example#3311 - Testing different code points
  • Example#3312 - Testing different code points
  • Example#3313 - Testing different code points
  • Example#3314 - Testing different code points
  • Example#3315 - Testing different code points
  • Example#3316 - Testing different code points
  • Example#3317 - intl_error_name example
  • Example#3318 - intl_get_error_code example
  • Example#3319 - intl_get_error_message example
  • Example#3320 - intl_is_failure example
  • Example#3321 - php.ini setting examples
  • Example#3322 - php.ini setting for EUC-JP users
  • Example#3323 - php.ini setting for SJIS users
  • Example#3324 - Disable HTTP input conversion in php.ini
  • Example#3325 - php.ini setting example
  • Example#3326 - Script example
  • Example#3327 - mb_convert_case example
  • Example#3328 - mb_convert_case example with non-Latin UTF-8 text
  • Example#3329 - mb_convert_encoding example
  • Example#3330 - mb_convert_kana example
  • Example#3331 - mb_convert_variables example
  • Example#3332 - convmap example
  • Example#3333 - convmap example escapes JavaScript string
  • Example#3334 - mb_detect_encoding example
  • Example#3335 - mb_detect_order examples
  • Example#3336 - Example showing useless detect orders
  • Example#3337 - mb_encode_mimeheader example
  • Example#3338 - convmap example
  • Example#3339 - mb_encode_numericentity example
  • Example#3340 - mb_encoding_aliases example
  • Example#3341 - mb_ereg_replace_callback example
  • Example#3342 - mb_ereg_replace_callback using anonymous function supported in PHP 5.3.0 or later
  • Example#3343 - mb_internal_encoding example
  • Example#3344 - mb_list_encodings example
  • Example#3345 - mb_output_handler example
  • Example#3346 - mb_preferred_mime_name example
  • Example#3347 - mb_strimwidth example
  • Example#3348 - mb_strtolower example
  • Example#3349 - mb_strtolower example with non-Latin UTF-8 text
  • Example#3350 - mb_strtoupper example
  • Example#3351 - mb_strtoupper example with non-Latin UTF-8 text
  • Example#3352 - mb_substitute_character example
  • Example#3353 - mb_substr_count example
  • Example#3354 - pspell_add_to_personal
  • Example#3355 - pspell_check Example
  • Example#3356 - pspell_add_to_personal Example
  • Example#3357 - pspell_config_create
  • Example#3358 - pspell_config_ignore
  • Example#3359 - pspell_config_mode Example
  • Example#3360 - pspell_config_personal
  • Example#3361 - pspell_config_repl
  • Example#3362 - pspell_config_runtogether
  • Example#3363 - pspell_new_config
  • Example#3364 - pspell_new_personal
  • Example#3365 - pspell_new
  • Example#3366 - pspell_add_to_personal
  • Example#3367 - pspell_store_replacement
  • Example#3368 - pspell_suggest example
  • Example#3369 - Basic recode_file example
  • Example#3370 - Basic recode_string example
  • Example#3371 - Cairo Example
  • Example#3372 - cairo_create example
  • Example#3373 - cairo_font_options_create example
  • Example#3374 - cairo_font_options_equal example
  • Example#3375 - cairo_font_options_get_antialias example
  • Example#3376 - cairo_font_options_get_hint_metrics example
  • Example#3377 - cairo_font_options_get_hint_style example
  • Example#3378 - cairo_font_options_get_subpixel_order example
  • Example#3379 - cairo_font_options_hash example
  • Example#3380 - cairo_font_options_merge example
  • Example#3381 - cairo_font_options_set_antialias example
  • Example#3382 - cairo_font_options_set_hint_metrics example
  • Example#3383 - cairo_font_options_set_hint_style example
  • Example#3384 - cairo_font_options_set_subpixel_order example
  • Example#3385 - cairo_font_options_status example
  • Example#3386 - cairo_format_stride_for_width example
  • Example#3387 - cairo_image_surface_create_for_data example
  • Example#3388 - cairo_image_surface_create_from_png example
  • Example#3389 - cairo_image_surface_create example
  • Example#3390 - cairo_image_surface_get_data example
  • Example#3391 - cairo_image_surface_get_format example
  • Example#3392 - cairo_image_surface_get_height example
  • Example#3393 - cairo_image_surface_get_stride example
  • Example#3394 - cairo_image_surface_get_width example
  • Example#3395 - cairo_matrix_invert example
  • Example#3396 - cairo_matrix_multiply example
  • Example#3397 - cairo_matrix_transform_distance example
  • Example#3398 - cairo_matrix_transform_point example
  • Example#3399 - cairo_matrix_translate example
  • Example#3400 - cairo_pattern_add_color_stop_rgb example
  • Example#3401 - cairo_pattern_add_color_stop_rgba example
  • Example#3402 - cairo_pattern_create_for_surface example
  • Example#3403 - cairo_pattern_create_linear example
  • Example#3404 - cairo_pattern_create_radial example
  • Example#3405 - cairo_pattern_create_rgb example
  • Example#3406 - cairo_pattern_create_rgba example
  • Example#3407 - cairo_pattern_get_color_stop_count example
  • Example#3408 - cairo_pattern_get_color_stop_rgba example
  • Example#3409 - cairo_pattern_get_extend example
  • Example#3410 - cairo_pattern_get_filter example
  • Example#3411 - cairo_pattern_get_linear_points example
  • Example#3412 - cairo_pattern_get_matrix example
  • Example#3413 - cairo_pattern_get_radial_circles example
  • Example#3414 - cairo_pattern_get_rgba example
  • Example#3415 - cairo_pattern_get_surface example
  • Example#3416 - cairo_pattern_get_type example
  • Example#3417 - cairo_pattern_set_extend example
  • Example#3418 - cairo_pattern_set_filter example
  • Example#3419 - cairo_pattern_set_matrix example
  • Example#3420 - cairo_pattern_status example
  • Example#3421 - cairo_pdf_surface_create example
  • Example#3422 - cairo_pdf_surface_set_size example
  • Example#3423 - cairo_ps_get_levels example
  • Example#3424 - cairo_ps_level_to_string example
  • Example#3425 - cairo_ps_surface_create example
  • Example#3426 - cairo_ps_surface_dsc_begin_page_setup example
  • Example#3427 - cairo_ps_surface_dsc_begin_setup example
  • Example#3428 - cairo_ps_surface_dsc_comment example
  • Example#3429 - cairo_ps_surface_get_eps example
  • Example#3430 - cairo_ps_surface_restrict_to_level example
  • Example#3431 - cairo_ps_surface_set_eps example
  • Example#3432 - cairo_ps_surface_set_size example
  • Example#3433 - cairo_scaled_font_create example
  • Example#3434 - cairo_scaled_font_extents example
  • Example#3435 - cairo_scaled_font_get_ctm example
  • Example#3436 - cairo_scaled_font_get_font_face example
  • Example#3437 - cairo_scaled_font_get_font_matrix example
  • Example#3438 - cairo_scaled_font_get_font_options example
  • Example#3439 - cairo_scaled_font_get_scale_matrix example
  • Example#3440 - cairo_scaled_font_get_type example
  • Example#3441 - cairo_scaled_font_glyph_extents example
  • Example#3442 - cairo_scaled_font_status example
  • Example#3443 - cairo_scaled_font_text_extents example
  • Example#3444 - cairo_surface_copy_page example
  • Example#3445 - cairo_surface_create_similar example
  • Example#3446 - cairo_surface_finish example
  • Example#3447 - cairo_surface_flush example
  • Example#3448 - cairo_surface_get_content example
  • Example#3449 - cairo_surface_get_device_offset example
  • Example#3450 - cairo_surface_get_font_options example
  • Example#3451 - cairo_surface_get_type example
  • Example#3452 - cairo_surface_mark_dirty_rectangle example
  • Example#3453 - cairo_surface_mark_dirty example
  • Example#3454 - cairo_surface_set_device_offset example
  • Example#3455 - cairo_surface_set_fallback_resolution example
  • Example#3456 - cairo_surface_show_page example
  • Example#3457 - cairo_surface_status example
  • Example#3458 - cairo_surface_write_to_png example
  • Example#3459 - cairo_svg_surface_create example
  • Example#3460 - cairo_svg_surface_restrict_to_version example
  • Example#3461 - cairo_svg_version_to_string example
  • Example#3462 - Object oriented style
  • Example#3463 - Procedural style
  • Example#3464 - Object oriented style
  • Example#3465 - Procedural style
  • Example#3466 - Object oriented style
  • Example#3467 - Procedural style
  • Example#3468 - Object oriented style
  • Example#3469 - Procedural style
  • Example#3470 - Object oriented style
  • Example#3471 - Procedural style
  • Example#3472 - Object oriented style
  • Example#3473 - Procedural style
  • Example#3474 - Object oriented style
  • Example#3475 - Procedural style
  • Example#3476 - Object oriented style
  • Example#3477 - Procedural style
  • Example#3478 - Object oriented style
  • Example#3479 - Procedural style
  • Example#3480 - Object oriented style
  • Example#3481 - Procedural style
  • Example#3482 - Object oriented style
  • Example#3483 - Procedural style
  • Example#3484 - Object oriented style
  • Example#3485 - Procedural style
  • Example#3486 - Object oriented style
  • Example#3487 - Procedural style
  • Example#3488 - CairoContext::__construct example
  • Example#3489 - Object oriented style
  • Example#3490 - Procedural style
  • Example#3491 - Object oriented style
  • Example#3492 - Procedural style
  • Example#3493 - Object oriented style
  • Example#3494 - Procedural style
  • Example#3495 - Object oriented style
  • Example#3496 - Procedural style
  • Example#3497 - Object oriented style
  • Example#3498 - Procedural style
  • Example#3499 - Object oriented style
  • Example#3500 - Procedural style
  • Example#3501 - Object oriented style
  • Example#3502 - Procedural style
  • Example#3503 - Object oriented style
  • Example#3504 - Procedural style
  • Example#3505 - Object oriented style
  • Example#3506 - Procedural style
  • Example#3507 - Object oriented style
  • Example#3508 - Procedural style
  • Example#3509 - Object oriented style
  • Example#3510 - Procedural style
  • Example#3511 - Object oriented style
  • Example#3512 - Procedural style
  • Example#3513 - Object oriented style
  • Example#3514 - Procedural style
  • Example#3515 - Object oriented style
  • Example#3516 - Procedural style
  • Example#3517 - Object oriented style
  • Example#3518 - Procedural style
  • Example#3519 - Object oriented style
  • Example#3520 - Procedural style
  • Example#3521 - Object oriented style
  • Example#3522 - Procedural style
  • Example#3523 - Object oriented style
  • Example#3524 - Procedural style
  • Example#3525 - Object oriented style
  • Example#3526 - Procedural style
  • Example#3527 - Object oriented style
  • Example#3528 - Procedural style
  • Example#3529 - Object oriented style
  • Example#3530 - Procedural style
  • Example#3531 - Object oriented style
  • Example#3532 - Procedural style
  • Example#3533 - Object oriented style
  • Example#3534 - Procedural style
  • Example#3535 - Object oriented style
  • Example#3536 - Procedural style
  • Example#3537 - Object oriented style
  • Example#3538 - Procedural style
  • Example#3539 - Object oriented style
  • Example#3540 - Procedural style
  • Example#3541 - Object oriented style
  • Example#3542 - Procedural style
  • Example#3543 - Object oriented style
  • Example#3544 - Procedural style
  • Example#3545 - Object oriented style
  • Example#3546 - Procedural style
  • Example#3547 - Object oriented style
  • Example#3548 - Procedural style
  • Example#3549 - Object oriented style
  • Example#3550 - Procedural style
  • Example#3551 - Object oriented style
  • Example#3552 - Procedural style
  • Example#3553 - Object oriented style
  • Example#3554 - Procedural style
  • Example#3555 - Object oriented style
  • Example#3556 - Procedural style
  • Example#3557 - Object oriented style
  • Example#3558 - Procedural style
  • Example#3559 - Object oriented style
  • Example#3560 - Procedural style
  • Example#3561 - Object oriented style
  • Example#3562 - Procedural style
  • Example#3563 - Object oriented style
  • Example#3564 - Procedural style
  • Example#3565 - Object oriented style
  • Example#3566 - Procedural style
  • Example#3567 - Object oriented style
  • Example#3568 - Procedural style
  • Example#3569 - Object oriented style
  • Example#3570 - Procedural style
  • Example#3571 - Object oriented style
  • Example#3572 - Procedural style
  • Example#3573 - Object oriented style
  • Example#3574 - Procedural style
  • Example#3575 - Object oriented style
  • Example#3576 - Procedural style
  • Example#3577 - Object oriented style
  • Example#3578 - Procedural style
  • Example#3579 - Object oriented style
  • Example#3580 - Procedural style
  • Example#3581 - Object oriented style
  • Example#3582 - Procedural style
  • Example#3583 - Object oriented style
  • Example#3584 - Procedural style
  • Example#3585 - Object oriented style
  • Example#3586 - Procedural style
  • Example#3587 - Object oriented style
  • Example#3588 - Procedural style
  • Example#3589 - Object oriented style
  • Example#3590 - Procedural style
  • Example#3591 - Object oriented style
  • Example#3592 - Procedural style
  • Example#3593 - Object oriented style
  • Example#3594 - Procedural style
  • Example#3595 - Object oriented style
  • Example#3596 - Procedural style
  • Example#3597 - Object oriented style
  • Example#3598 - Procedural style
  • Example#3599 - Object oriented style
  • Example#3600 - Procedural style
  • Example#3601 - Object oriented style
  • Example#3602 - Procedural style
  • Example#3603 - Object oriented style
  • Example#3604 - Procedural style
  • Example#3605 - Object oriented style
  • Example#3606 - Procedural style
  • Example#3607 - Object oriented style
  • Example#3608 - Procedural style
  • Example#3609 - Object oriented style
  • Example#3610 - Procedural style
  • Example#3611 - Object oriented style
  • Example#3612 - Procedural style
  • Example#3613 - Object oriented style
  • Example#3614 - Procedural style
  • Example#3615 - Object oriented style
  • Example#3616 - Procedural style
  • Example#3617 - Object oriented style
  • Example#3618 - Procedural style
  • Example#3619 - Object oriented style
  • Example#3620 - Procedural style
  • Example#3621 - Object oriented style
  • Example#3622 - Procedural style
  • Example#3623 - Object oriented style
  • Example#3624 - Procedural style
  • Example#3625 - Object oriented style
  • Example#3626 - Procedural style
  • Example#3627 - Object oriented style
  • Example#3628 - Procedural style
  • Example#3629 - Object oriented style
  • Example#3630 - Procedural style
  • Example#3631 - Object oriented style
  • Example#3632 - Procedural style
  • Example#3633 - Object oriented style
  • Example#3634 - Procedural style
  • Example#3635 - Object oriented style
  • Example#3636 - Procedural style
  • Example#3637 - Object oriented style
  • Example#3638 - Procedural style
  • Example#3639 - Object oriented style
  • Example#3640 - Procedural style
  • Example#3641 - Object oriented style
  • Example#3642 - Procedural style
  • Example#3643 - Object oriented style
  • Example#3644 - Procedural style
  • Example#3645 - Object oriented style
  • Example#3646 - Procedural style
  • Example#3647 - Object oriented style
  • Example#3648 - Procedural style
  • Example#3649 - Object oriented style
  • Example#3650 - Procedural style
  • Example#3651 - Object oriented style
  • Example#3652 - Procedural style
  • Example#3653 - Object oriented style
  • Example#3654 - Procedural style
  • Example#3655 - Object oriented style
  • Example#3656 - Procedural style
  • Example#3657 - Object oriented style
  • Example#3658 - Procedural style
  • Example#3659 - Object oriented style
  • Example#3660 - Procedural style
  • Example#3661 - Object oriented style
  • Example#3662 - Procedural style
  • Example#3663 - CairoSurface::createSimilar example
  • Example#3664 - CairoSurface::finish example
  • Example#3665 - CairoSurface::flush example
  • Example#3666 - CairoSurface::getContent example
  • Example#3667 - CairoSurface::getDeviceOffset example
  • Example#3668 - Object oriented style
  • Example#3669 - Procedural style
  • Example#3670 - CairoSurface::getType example
  • Example#3671 - CairoSurface::markDirty example
  • Example#3672 - CairoSurface::markDirtyRectangle example
  • Example#3673 - CairoSurface::setDeviceOffset example
  • Example#3674 - CairoSurface::setFallbackResolution example
  • Example#3675 - Object oriented style
  • Example#3676 - Procedural style
  • Example#3677 - Object oriented style
  • Example#3678 - Procedural style
  • Example#3679 - CairoSurface::writeToPng example
  • Example#3680 - CairoSvgSurface::__construct example
  • Example#3681 - CairoSvgSurface::getVersions example
  • Example#3682 - Procedural style
  • Example#3683 - CairoSvgSurface::restrictToVersion example
  • Example#3684 - CairoSvgSurface::versionToString example
  • Example#3685 - CairoImageSurface::__construct example
  • Example#3686 - CairoImageSurface::createForData example
  • Example#3687 - CairoImageSurface::createFromPng example
  • Example#3688 - CairoImageSurface::getData example
  • Example#3689 - CairoImageSurface::getFormat example
  • Example#3690 - CairoImageSurface::getHeight example
  • Example#3691 - CairoImageSurface::getStride example
  • Example#3692 - CairoImageSurface::getWidth example
  • Example#3693 - CairoPdfSurface::__construct example
  • Example#3694 - CairoPdfSurface::setSize example
  • Example#3695 - CairoPsSurface::__construct example
  • Example#3696 - CairoPsSurface::dscBeginPageSetup example
  • Example#3697 - CairoPsSurface::dscBeginSetup example
  • Example#3698 - CairoPsSurface::dscComment example
  • Example#3699 - CairoPsSurface::getEps example
  • Example#3700 - CairoPsSurface::getLevels example
  • Example#3701 - CairoPsSurface::levelToString example
  • Example#3702 - CairoPsSurface::restrictToLevel example
  • Example#3703 - CairoPsSurface::setEps example
  • Example#3704 - CairoPsSurface::setSize example
  • Example#3705 - CairoFontFace::__construct example
  • Example#3706 - CairoFontFace::getType example
  • Example#3707 - Object oriented style
  • Example#3708 - Procedural style
  • Example#3709 - CairoFontOptions::__construct example
  • Example#3710 - CairoFontOptions::equal example
  • Example#3711 - Object oriented style
  • Example#3712 - Procedural style
  • Example#3713 - CairoFontOptions::getHintMetrics example
  • Example#3714 - CairoFontOptions::getHintStyle example
  • Example#3715 - CairoFontOptions::getSubpixelOrder example
  • Example#3716 - CairoFontOptions::hash example
  • Example#3717 - CairoFontOptions::merge example
  • Example#3718 - Object oriented style
  • Example#3719 - Procedural style
  • Example#3720 - CairoFontOptions::setHintMetrics example
  • Example#3721 - CairoFontOptions::setHintStyle example
  • Example#3722 - CairoFontOptions::setSubpixelOrder example
  • Example#3723 - Object oriented style
  • Example#3724 - Procedural style
  • Example#3725 - CairoScaledFont::__construct example
  • Example#3726 - CairoScaledFont::extents example
  • Example#3727 - CairoScaledFont::getCtm example
  • Example#3728 - Object oriented style
  • Example#3729 - Procedural style
  • Example#3730 - Object oriented style
  • Example#3731 - Procedural style
  • Example#3732 - Object oriented style
  • Example#3733 - Procedural style
  • Example#3734 - CairoScaledFont::getScaleMatrix example
  • Example#3735 - CairoScaledFont::getType example
  • Example#3736 - CairoScaledFont::glyphExtents example
  • Example#3737 - Object oriented style
  • Example#3738 - Procedural style
  • Example#3739 - Object oriented style
  • Example#3740 - Procedural style
  • Example#3741 - CairoPattern::__construct example
  • Example#3742 - Object oriented style
  • Example#3743 - Procedural style
  • Example#3744 - CairoPattern::getType example
  • Example#3745 - Object oriented style
  • Example#3746 - Procedural style
  • Example#3747 - Object oriented style
  • Example#3748 - Procedural style
  • Example#3749 - CairoGradientPattern::addColorStopRgb example
  • Example#3750 - CairoGradientPattern::addColorStopRgba example
  • Example#3751 - CairoGradientPattern::getColorStopCount example
  • Example#3752 - CairoGradientPattern::getColorStopRgba example
  • Example#3753 - CairoGradientPattern::getExtend example
  • Example#3754 - CairoGradientPattern::setExtend example
  • Example#3755 - CairoSolidPattern::__construct example
  • Example#3756 - CairoSolidPattern::getRgba example
  • Example#3757 - CairoSurfacePattern::__construct example
  • Example#3758 - CairoSurfacePattern::getExtend example
  • Example#3759 - CairoSurfacePattern::getFilter example
  • Example#3760 - CairoSurfacePattern::getSurface example
  • Example#3761 - CairoSurfacePattern::setExtend example
  • Example#3762 - CairoSurfacePattern::setFilter example
  • Example#3763 - CairoLinearGradient::__construct example
  • Example#3764 - CairoLinearGradient::getPoints example
  • Example#3765 - CairoRadialGradient::__construct example
  • Example#3766 - CairoRadialGradient::getCircles example
  • Example#3767 - CairoFormat::strideForWidth example
  • Example#3768 - Object oriented style
  • Example#3769 - Procedural style
  • Example#3770 - Object oriented style
  • Example#3771 - Procedural style
  • Example#3772 - Object oriented style
  • Example#3773 - Procedural style
  • Example#3774 - Object oriented style
  • Example#3775 - Procedural style
  • Example#3776 - Object oriented style
  • Example#3777 - Procedural style
  • Example#3778 - CairoMatrix::invert example
  • Example#3779 - CairoMatrix::multiply example
  • Example#3780 - Object oriented style
  • Example#3781 - Procedural style
  • Example#3782 - Object oriented style
  • Example#3783 - Procedural style
  • Example#3784 - CairoMatrix::transformDistance example
  • Example#3785 - CairoMatrix::transformPoint example
  • Example#3786 - Object oriented style
  • Example#3787 - Procedural style
  • Example#3788 - exif_imagetype example
  • Example#3789 - exif_read_data example
  • Example#3790 - exif_read_data with streams available as of PHP 7.2.0
  • Example#3791 - exif_tagname example
  • Example#3792 - exif_thumbnail example
  • Example#3793 - PNG creation with PHP
  • Example#3794 - Adding watermarks to images using alpha channels
  • Example#3795 - Using imagecopymerge to create a translucent watermark
  • Example#3796 - Using gd_info
  • Example#3797 - getimagesize and MIME types
  • Example#3798 - getimagesize example
  • Example#3799 - getimagesize (URL)
  • Example#3800 - getimagesize() returning IPTC
  • Example#3801 - getimagesizefromstring example
  • Example#3802 - image_type_to_extension example
  • Example#3803 - image_type_to_mime_type example
  • Example#3804 - image2wbmp example
  • Example#3805 - imageaffinematrixconcat example
  • Example#3806 - imageaffinematrixget example
  • Example#3807 - imagealphablending usage example
  • Example#3808 - A comparison of two lines, one with anti-aliasing switched on
  • Example#3809 - Drawing a circle with imagearc
  • Example#3810 - Saving a BMP file
  • Example#3811 - imagechar example
  • Example#3812 - imagecharup example
  • Example#3813 - imagecolorallocate example
  • Example#3814 - Example of using imagecolorallocatealpha
  • Example#3815 - Convert typical alpha values for use with imagecolorallocatealpha
  • Example#3816 - Access distinct RGB values
  • Example#3817 - Human-readable RGB values using imagecolorsforindex
  • Example#3818 - Search for a set of colors in an image
  • Example#3819 - Search for a set of colors in an image
  • Example#3820 - Example of using imagecolorclosesthwb
  • Example#3821 - Using imagecolordeallocate
  • Example#3822 - Get colors from the GD logo
  • Example#3823 - Get colors from the GD logo
  • Example#3824 - imagecolormatch example
  • Example#3825 - Using imagecoloresolve to get colors from an image
  • Example#3826 - Using imagecoloresolvealpha to get colors from an image
  • Example#3827 - imagecolorset example
  • Example#3828 - imagecolorsforindex example
  • Example#3829 - Getting total number of colors in an image using imagecolorstotal
  • Example#3830 - imagecolortransparent example
  • Example#3831 - Embossing the PHP.net logo
  • Example#3832 - Gaussian blur
  • Example#3833 - Cropping the PHP.net logo
  • Example#3834 - Merging two copies of the PHP.net logo with 75% transparency
  • Example#3835 - imagecopymergegray usage
  • Example#3836 - Simple example
  • Example#3837 - Resampling an image proportionally
  • Example#3838 - Resizing an image
  • Example#3839 - Creating a new GD image stream and outputting an image.
  • Example#3840 - Convert an BMP image to a PNG image using imagecreatefrombmp
  • Example#3841 - imagecreatefromgd2 example
  • Example#3842 - imagecreatefromgd2part example
  • Example#3843 - imagecreatefromgd example
  • Example#3844 - Example to handle an error during loading of a GIF
  • Example#3845 - Example to handle an error during loading of a JPEG
  • Example#3846 - Example to handle an error during loading of a PNG
  • Example#3847 - imagecreatefromstring example
  • Example#3848 - Example to handle an error during loading of a WBMP
  • Example#3849 - Convert an WebP image to a jpeg image using imagecreatefromwebp
  • Example#3850 - Convert an XBM image to a png image using imagecreatefromxbm
  • Example#3851 - Creating an image instance using imagecreatefromxpm
  • Example#3852 - Creating a new GD image stream and outputting an image.
  • Example#3853 - imagecrop example
  • Example#3854 - Proper handling of auto-cropping
  • Example#3855 - imagedashedline example
  • Example#3856 - Alternative to imagedashedline
  • Example#3857 - Using imagedestroy example
  • Example#3858 - imageellipse example
  • Example#3859 - imagefill example
  • Example#3860 - Creating a 3D looking pie
  • Example#3861 - imagefilledellipse example
  • Example#3862 - imagefilledpolygon example
  • Example#3863 - imagefilledrectangle usage
  • Example#3864 - Filling an ellipse with a color
  • Example#3865 - imagefilter grayscale example
  • Example#3866 - imagefilter brightness example
  • Example#3867 - imagefilter colorize example
  • Example#3868 - imagefilter negate example
  • Example#3869 - imagefilter pixelate example
  • Example#3870 - imagefilter scatter example
  • Example#3871 - Flips an image vertically
  • Example#3872 - Flips the image horizontally
  • Example#3873 - Using imagefontheight on built-in fonts
  • Example#3874 - Using imagefontheight together with imageloadfont
  • Example#3875 - Using imagefontwidth on built-in fonts
  • Example#3876 - Using imagefontwidth together with imageloadfont
  • Example#3877 - imageftbbox example
  • Example#3878 - imagefttext example
  • Example#3879 - imagegammacorrect usage
  • Example#3880 - Outputting a GD2 image
  • Example#3881 - Saving a GD2 image
  • Example#3882 - Outputting a GD image
  • Example#3883 - Saving a GD image
  • Example#3884 - imagegetclip example
  • Example#3885 - Outputting an image using imagegif
  • Example#3886 - Converting a PNG image to GIF using imagegif
  • Example#3887 - imagegrabscreen example
  • Example#3888 - imagegrabwindow example
  • Example#3889 - Turn on interlacing using imageinterlace
  • Example#3890 - Simple detection of true color image instances using imageistruecolor
  • Example#3891 - Outputting a JPEG image to the browser
  • Example#3892 - Saving a JPEG image to a file
  • Example#3893 - Outputting the image at 75% quality to the browser
  • Example#3894 - imagelayereffect example
  • Example#3895 - Drawing a thick line
  • Example#3896 - imageloadfont usage example
  • Example#3897 - imageopenpolygon example
  • Example#3898 - imagepalettecopy example
  • Example#3899 - Converts any image resource to true color
  • Example#3900 - imagepolygon example
  • Example#3901 - imagepsbbox usage
  • Example#3902 - imagepsencodefont example
  • Example#3903 - imagepsextendfont example
  • Example#3904 - imagepsfreefont example
  • Example#3905 - imagepsloadfont example
  • Example#3906 - imagepsslantfont example
  • Example#3907 - imagepstext usage
  • Example#3908 - Simple imagerectangle example
  • Example#3909 - Setting and getting the resolution of an image
  • Example#3910 - Rotate an image 180 degrees
  • Example#3911 - Basic imagesavealpha Usage
  • Example#3912 - imagesetbrush example
  • Example#3913 - imagesetinterpolation example
  • Example#3914 - imagesetpixel example
  • Example#3915 - imagesetstyle example
  • Example#3916 - imagesetthickness example
  • Example#3917 - imagesettile example
  • Example#3918 - imagestring example
  • Example#3919 - imagestringup example
  • Example#3920 - Using imagesx
  • Example#3921 - Using imagesy
  • Example#3922 - Converting a true color image to a palette-based image
  • Example#3923 - imagettfbbox example
  • Example#3924 - imagettftext example
  • Example#3925 - Checking for PNG support
  • Example#3926 - Outputting a WBMP image
  • Example#3927 - Saving the WBMP image
  • Example#3928 - Outputting the image with a different foreground
  • Example#3929 - Saving an WebP file
  • Example#3930 - Saving an XBM file
  • Example#3931 - Saving an XBM file with a different foreground color
  • Example#3932 - Embedding IPTC data into a JPEG
  • Example#3933 - iptcparse() used together with getimagesize
  • Example#3934 - jpeg2wbmp example
  • Example#3935 - png2wbmp example
  • Example#3936 - Gmagick Example
  • Example#3937 - Gmagick::despeckleimage example
  • Example#3938 - Gmagick::setCompressionQuality
  • Example#3939 - Creating a thumbnail in Imagick
  • Example#3940 - Make a thumbnail of all JPG files in a directory
  • Example#3941 - Creating a reflection of an image
  • Example#3942 - Filling text with gradient
  • Example#3943 - Read in GIF image and resize all frames
  • Example#3944 - Create a PHP logo
  • Example#3945 - Using Imagick::adaptiveBlurImage:
  • Example#3946 - Using Imagick::adaptiveResizeImage
  • Example#3947 - A Imagick::adaptiveSharpenImage example
  • Example#3948 - Imagick::adaptiveThresholdImage
  • Example#3949 - Imagick::addNoiseImage
  • Example#3950 - Imagick::affineTransformImage
  • Example#3951 - Using Imagick::annotateImage:
  • Example#3952 - Imagick::appendImages example
  • Example#3953 - Imagick::autoLevelImage
  • Example#3954 - Imagick::blackThresholdImage
  • Example#3955 - Imagick::blueShiftImage
  • Example#3956 - Using Imagick::blurImage:
  • Example#3957 - Imagick::borderImage
  • Example#3958 - Imagick::brightnessContrastImage
  • Example#3959 - Imagick::charcoalImage
  • Example#3960 - Using Imagick::chopImage:
  • Example#3961 - Imagick object cloning in different versions of imagick
  • Example#3962 - Using Imagick::clutImage:
  • Example#3963 - Imagick::colorizeImage
  • Example#3964 - Imagick::colorMatrixImage
  • Example#3965 - Using Imagick::commentImage:
  • Example#3966 - Using Imagick::compareImageLayers
  • Example#3967 - Using Imagick::compareImages:
  • Example#3968 - Using Imagick::compositeImage:
  • Example#3969 - Imagick::contrastImage
  • Example#3970 - Imagick::convolveImage
  • Example#3971 - Imagick::cropImage
  • Example#3972 - Imagick::deskewImage
  • Example#3973 - Imagick::despeckleImage
  • Example#3974 - Using Imagick::distortImage:
  • Example#3975 - Imagick::edgeImage
  • Example#3976 - Imagick::embossImage
  • Example#3977 - Imagick::enhanceImage
  • Example#3978 - Imagick::equalizeImage
  • Example#3979 - Using Imagick::evaluateImage
  • Example#3980 - Using Imagick::exportImagePixels
  • Example#3981 - Imagick::filter
  • Example#3982 - Imagick::flipImage
  • Example#3983 - Imagick::floodfillPaintImage example
  • Example#3984 - Imagick::flopImage
  • Example#3985 - Imagick::forwardFourierTransformImage
  • Example#3986 - Imagick::frameImage
  • Example#3987 - Create a sinusoidal gradient
  • Example#3988 - Create a gradient from the polynomial (4x^2 - 4x + 1)
  • Example#3989 - Create a complex gradient from the polynomial (4x^2 - 4x^2 + 1) modulated by a sinusoidal gradient
  • Example#3990 - Imagick::fxImage
  • Example#3991 - Imagick::gammaImage
  • Example#3992 - Imagick::gaussianBlurImage
  • Example#3993 - Imagick::getImageGeometry
  • Example#3994 - Generates Imagick::getImageHistogram
  • Example#3995 - Using Imagick::getImageLength:
  • Example#3996 - Using Imagick::getImageProperties:
  • Example#3997 - Using Imagick::getImageProperty:
  • Example#3998 - Using Imagick::getIteratorIndex:
  • Example#3999 - Imagick::getPixelIterator
  • Example#4000 - Imagick::getPixelRegionIterator example
  • Example#4001 - Getting the size of a raw RGB image set at 200x400, after scaling to 400x800 (compared to width / height)
  • Example#4002 - Imagick::haldClutImage
  • Example#4003 - Imagick::identifyFormat
  • Example#4004 - Example Result Format
  • Example#4005 - Imagick::implodeImage
  • Example#4006 - Imagick::importImagePixels example
  • Example#4007 - Imagick::levelImage
  • Example#4008 - Imagick::linearStretchImage
  • Example#4009 - Imagick::magnifyImage
  • Example#4010 - Imagick::medianFilterImage
  • Example#4011 - Imagick::mergeImageLayers
  • Example#4012 - Imagick::modulateImage
  • Example#4013 - Convolve Imagick::morphology
  • Example#4014 - Correlate Imagick::morphology
  • Example#4015 - Erode Imagick::morphology
  • Example#4016 - Erode Intensity Imagick::morphology
  • Example#4017 - Dilate Imagick::morphology
  • Example#4018 - Dilate intensity Imagick::morphology
  • Example#4019 - Distance with Chebyshev kernel Imagick::morphology
  • Example#4020 - Distance with Manhattan kernel Imagick::morphology
  • Example#4021 - Distance with ocatagonal kernel Imagick::morphology
  • Example#4022 - Distance with Euclidean kernel Imagick::morphology
  • Example#4023 - Edge Imagick::morphology
  • Example#4024 - Open Imagick::morphology
  • Example#4025 - Open intensity Imagick::morphology
  • Example#4026 - Close Imagick::morphology
  • Example#4027 - Close Intensity Imagick::morphology
  • Example#4028 - Smooth Imagick::morphology
  • Example#4029 - Edge in Imagick::morphology
  • Example#4030 - Edge out Imagick::morphology
  • Example#4031 - 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
  • Example#4032 - 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
  • Example#4033 - Hit and Miss Imagick::morphology
  • Example#4034 - Thinning Imagick::morphology
  • Example#4035 - Thicken Imagick::morphology
  • Example#4036 - Thick to generate a convex hull Imagick::morphology
  • Example#4037 - Iterative morphology Imagick::morphology
  • Example#4038 - Helper functon to get an image silhouette Imagick::morphology
  • Example#4039 - Imagick::motionBlurImage
  • Example#4040 - Imagick::negateImage
  • Example#4041 - Using Imagick::newImage:
  • Example#4042 - Imagick::newPseudoImage
  • Example#4043 - Imagick::normalizeImage
  • Example#4044 - Imagick::oilPaintImage
  • Example#4045 - Using Imagick::optimizeImageLayers
  • Example#4046 - Imagick::orderedPosterizeImage
  • Example#4047 - Using Imagick::pingImageBlob
  • Example#4048 - Using Imagick::pingImageFile
  • Example#4049 - A Imagick::polaroidImage example
  • Example#4050 - Imagick::posterizeImage
  • Example#4051 - Imagick::quantizeImage
  • Example#4052 - Using Imagick::queryFontMetrics:
  • Example#4053 - Imagick::queryFonts
  • Example#4054 - Imagick::queryFormats
  • Example#4055 - Imagick::radialBlurImage
  • Example#4056 - Imagick::raiseImage
  • Example#4057 - Imagick::randomThresholdImage
  • Example#4058 - Imagick::readImageBlob
  • Example#4059 - Imagick::recolorImage
  • Example#4060 - Imagick::reduceNoiseImage
  • Example#4061 - Imagick::resampleImage
  • Example#4062 - Imagick::resizeImage
  • Example#4063 - Imagick::rollImage
  • Example#4064 - Imagick::rotateImage
  • Example#4065 - Imagick::rotationalBlurImage
  • Example#4066 - Using Imagick::roundCorners:
  • Example#4067 - Imagick::scaleImage
  • Example#4068 - Imagick::segmentImage
  • Example#4069 - Imagick::selectiveBlurImage
  • Example#4070 - Imagick::separateImageChannel
  • Example#4071 - Imagick::sepiaToneImage
  • Example#4072 - Imagick::setCompressionQuality
  • Example#4073 - A Imagick::setFont example
  • Example#4074 - A Imagick::setImage example
  • Example#4075 - Imagick::setImageArtifact
  • Example#4076 - Imagick::setImageBias
  • Example#4077 - Imagick::setImageClipMask
  • Example#4078 - Imagick::setImageCompressionQuality
  • Example#4079 - Modify animated Gif with Imagick::setImageDelay
  • Example#4080 - Basic Imagick::setImageIterations usage
  • Example#4081 - A Imagick::setImageOpacity example
  • Example#4082 - Imagick::setImageOrientation
  • Example#4083 - Using Imagick::setImageProperty:
  • Example#4084 - Imagick::setImageResolution
  • Example#4085 - Modify animated Gif with Imagick::setImageTicksPerSecond
  • Example#4086 - Using Imagick::setIteratorIndex:
  • Example#4087 - Attempt to reach '$extent' sizeImagick::setOption
  • Example#4088 - Imagick::setOption
  • Example#4089 - Imagick::setOption
  • Example#4090 - A Imagick::setPointSize example
  • Example#4091 - Imagick::setProgressMonitor
  • Example#4092 - Imagick::setSamplingFactors
  • Example#4093 - Imagick::shadeImage
  • Example#4094 - Imagick::shadowImage
  • Example#4095 - Imagick::sharpenImage
  • Example#4096 - Imagick::shaveImage
  • Example#4097 - Imagick::shearImage
  • Example#4098 - Create a gradient image using Imagick::sigmoidalContrastImage suitable for blending two images together smoothly, with the blending defined by $contrast and $the midpoint
  • Example#4099 - Imagick::sketchImage
  • Example#4100 - Imagick::smushImages
  • Example#4101 - Imagick::solarizeImage
  • Example#4102 - SPARSECOLORMETHOD_BARYCENTRIC Imagick::sparseColorImage
  • Example#4103 - SPARSECOLORMETHOD_BILINEAR Imagick::sparseColorImage
  • Example#4104 - SPARSECOLORMETHOD_SPEPARDS Imagick::sparseColorImage
  • Example#4105 - SPARSECOLORMETHOD_VORONOI Imagick::sparseColorImage
  • Example#4106 - SPARSECOLORMETHOD_BARYCENTRIC Imagick::sparseColorImage
  • Example#4107 - createGradientImage is used by other examples. Imagick::sparseColorImage
  • Example#4108 - Imagick::spliceImage
  • Example#4109 - Imagick::spreadImage
  • Example#4110 - Imagick::statisticImage
  • Example#4111 - Imagick::subImageMatch
  • Example#4112 - Imagick::swirlImage
  • Example#4113 - Imagick::textureImage
  • Example#4114 - Imagick::thresholdImage
  • Example#4115 - Imagick::thumbnailImage
  • Example#4116 - Imagick::tintImage
  • Example#4117 - Using Imagick::transformImage:
  • Example#4118 - Imagick::transformImageColorspace example
  • Example#4119 - Imagick::transformImageColorspace
  • Example#4120 - Imagick::transparentPaintImage
  • Example#4121 - Imagick::transposeImage
  • Example#4122 - Imagick::transverseImage
  • Example#4123 - Using Imagick::trimImage:
  • Example#4124 - Imagick::uniqueImageColors
  • Example#4125 - Imagick::unsharpMaskImage
  • Example#4126 - Imagick::vignetteImage
  • Example#4127 - WaveImage can be quite slow Imagick::waveImage
  • Example#4128 - Imagick::whiteThresholdImage
  • Example#4129 - ImagickDraw::affine
  • Example#4130 - ImagickDraw::arc
  • Example#4131 - ImagickDraw::bezier
  • Example#4132 - ImagickDraw::circle
  • Example#4133 - ImagickDraw::composite
  • Example#4134 - ImagickDraw::ellipse
  • Example#4135 - ImagickDraw::line
  • Example#4136 - ImagickDraw::matte
  • Example#4137 - ImagickDraw::pathCurveToQuadraticBezierAbsolute
  • Example#4138 - ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute
  • Example#4139 - ImagickDraw::pathCurveToQuadraticBezierSmoothRelative
  • Example#4140 - ImagickDraw::pathStart
  • Example#4141 - ImagickDraw::point
  • Example#4142 - ImagickDraw::polygon
  • Example#4143 - ImagickDraw::polyline
  • Example#4144 - ImagickDraw::popDefs
  • Example#4145 - ImagickDraw::push
  • Example#4146 - ImagickDraw::pushPattern
  • Example#4147 - ImagickDraw::rectangle
  • Example#4148 - ImagickDraw::rotate
  • Example#4149 - ImagickDraw::roundRectangle
  • Example#4150 - ImagickDraw::scale
  • Example#4151 - ImagickDraw::setClipPath
  • Example#4152 - ImagickDraw::setClipRule
  • Example#4153 - ImagickDraw::setClipUnits
  • Example#4154 - ImagickDraw::setFillAlpha
  • Example#4155 - ImagickDraw::setFillColor
  • Example#4156 - ImagickDraw::setFillOpacity
  • Example#4157 - ImagickDraw::setFillRule
  • Example#4158 - ImagickDraw::setFont
  • Example#4159 - ImagickDraw::setFontFamily
  • Example#4160 - ImagickDraw::setFontSize
  • Example#4161 - ImagickDraw::setFontStretch
  • Example#4162 - ImagickDraw::setFontStyle
  • Example#4163 - ImagickDraw::setFontWeight
  • Example#4164 - ImagickDraw::setGravity
  • Example#4165 - ImagickDraw::setStrokeAlpha
  • Example#4166 - ImagickDraw::setStrokeAntialias
  • Example#4167 - ImagickDraw::setStrokeColor
  • Example#4168 - ImagickDraw::setStrokeDashArray
  • Example#4169 - ImagickDraw::setStrokeDashOffset
  • Example#4170 - ImagickDraw::setStrokeLineCap
  • Example#4171 - ImagickDraw::setStrokeLineJoin
  • Example#4172 - ImagickDraw::setStrokeMiterLimit
  • Example#4173 - ImagickDraw::setStrokeOpacity
  • Example#4174 - ImagickDraw::setStrokeWidth
  • Example#4175 - ImagickDraw::setTextAlignment
  • Example#4176 - ImagickDraw::setTextAntialias
  • Example#4177 - ImagickDraw::setTextDecoration
  • Example#4178 - ImagickDraw::setTextUnderColor
  • Example#4179 - ImagickDraw::setVectorGraphics
  • Example#4180 - ImagickDraw::setViewBox
  • Example#4181 - ImagickDraw::skewX
  • Example#4182 - ImagickDraw::skewY
  • Example#4183 - ImagickDraw::translate
  • Example#4184 - ImagickPixel::construct
  • Example#4185 - Basic Imagick::getColor usage
  • Example#4186 - Basic Imagick::getColorAsString usage
  • Example#4187 - ImagickPixel getColorCount
  • Example#4188 - Basic Imagick::getColorValue usage
  • Example#4189 - ImagickPixel::getColorValueQuantum
  • Example#4190 - Basic Imagick::getHSL example
  • Example#4191 - ImagickPixel::isSimilar
  • Example#4192 - ImagickPixel::setColor
  • Example#4193 - Basic Imagick::setColorValue usage
  • Example#4194 - ImagickPixel::setColorValueQuantum
  • Example#4195 - Use ImagickPixel::setHSL to modify a color
  • Example#4196 - ImagickPixelIterator::clear
  • Example#4197 - ImagickPixelIterator::construct
  • Example#4198 - ImagickPixelIterator::getNextIteratorRow
  • Example#4199 - ImagickPixelIterator::resetIterator
  • Example#4200 - ImagickPixelIterator::setIteratorRow
  • Example#4201 - ImagickKernel::addKernel
  • Example#4202 - ImagickKernel::addUnityKernel
  • Example#4203 - ImagickKernel::addUnityKernel
  • Example#4204 - ImagickKernel::fromBuiltin
  • Example#4205 - ImagickKernel::fromMatrix
  • Example#4206 - ImagickKernel::getMatrix
  • Example#4207 - ImagickKernel::scale
  • Example#4208 - ImagickKernel::separate
  • Example#4209 - imap_append example
  • Example#4210 - imap_check example
  • Example#4211 - imap_createmailbox example
  • Example#4212 - imap_delete example
  • Example#4213 - imap_fetch_overview example
  • Example#4214 - imap_gc example
  • Example#4215 - imap_get_quota example
  • Example#4216 - imap_get_quota 4.3 or greater example
  • Example#4217 - imap_get_quotaroot example
  • Example#4218 - imap_getacl example
  • Example#4219 - imap_getmailboxes example
  • Example#4220 - imap_list example
  • Example#4221 - imap_mail_compose example
  • Example#4222 - imap_mailboxmsginfo example
  • Example#4223 - imap_mime_header_decode example
  • Example#4224 - Different use of imap_open
  • Example#4225 - imap_open example
  • Example#4226 - imap_ping Example
  • Example#4227 - imap_reopen example
  • Example#4228 - imap_rfc822_parse_adrlist example
  • Example#4229 - imap_rfc822_write_address example
  • Example#4230 - imap_search example
  • Example#4231 - imap_set_quota example
  • Example#4232 - imap_setflag_full example
  • Example#4233 - imap_status example
  • Example#4234 - imap_thread Example
  • Example#4235 - imap_timeout example
  • Example#4236 - Calculating the hash and subscribing a user
  • Example#4237 - Sending mail.
  • Example#4238 - Sending mail with extra headers.
  • Example#4239 - Sending mail with extra headers as array
  • Example#4240 - Sending mail with an additional command line parameter.
  • Example#4241 - Sending HTML email
  • Example#4242 - mailparse_determine_best_xfer_encoding example
  • Example#4243 - mailparse_rfc822_parse_addresses example
  • Example#4244 - mailparse_stream_encode example
  • Example#4245 - mailparse_uudecode_all example
  • Example#4246 - bcadd example
  • Example#4247 - bccomp example
  • Example#4248 - bcdiv example
  • Example#4249 - bcmod example
  • Example#4250 - bcmod with decimals
  • Example#4251 - bcmul example
  • Example#4252 - bcmul scale example
  • Example#4253 - bcpow example
  • Example#4254 - bcpow scale example
  • Example#4255 - bcscale example
  • Example#4256 - bcsqrt example
  • Example#4257 - bcsub example
  • Example#4258 - Factorial function using GMP
  • Example#4259 - gmp_abs example
  • Example#4260 - gmp_add example
  • Example#4261 - gmp_and example
  • Example#4262 - gmp_clrbit example
  • Example#4263 - gmp_cmp example
  • Example#4264 - gmp_com example
  • Example#4265 - gmp_div_q example
  • Example#4266 - Division of GMP numbers
  • Example#4267 - gmp_div_r example
  • Example#4268 - gmp_divexact example
  • Example#4269 - gmp_export example
  • Example#4270 - gmp_fact example
  • Example#4271 - gmp_gcd example
  • Example#4272 - Solving a linear Diophantine equation
  • Example#4273 - gmp_hamdist example
  • Example#4274 - gmp_import example
  • Example#4275 - Creating GMP number
  • Example#4276 - gmp_intval example
  • Example#4277 - gmp_invert example
  • Example#4278 - gmp_jacobi example
  • Example#4279 - gmp_legendre example
  • Example#4280 - gmp_mod example
  • Example#4281 - gmp_mul example
  • Example#4282 - gmp_neg example
  • Example#4283 - gmp_nextprime example
  • Example#4284 - gmp_or example
  • Example#4285 - gmp_perfect_square example
  • Example#4286 - gmp_popcount example
  • Example#4287 - gmp_pow example
  • Example#4288 - gmp_powm example
  • Example#4289 - gmp_prob_prime example
  • Example#4290 - gmp_random_bits example
  • Example#4291 - gmp_random_range example
  • Example#4292 - gmp_random_seed example
  • Example#4293 - gmp_random example
  • Example#4294 - gmp_scan0 example
  • Example#4295 - gmp_scan1 example
  • Example#4296 - gmp_setbit example - 0 index
  • Example#4297 - gmp_setbit example - 1 index
  • Example#4298 - gmp_setbit example - clearing a bit
  • Example#4299 - gmp_sign example
  • Example#4300 - gmp_sqrt example
  • Example#4301 - gmp_sqrtrem example
  • Example#4302 - Converting a GMP number to a string
  • Example#4303 - gmp_sub example
  • Example#4304 - gmp_testbit example
  • Example#4305 - gmp_xor example
  • Example#4306 - Using Lapack::eigenValues:
  • Example#4307 - Using Lapack::leastSquaresByFactorisation:
  • Example#4308 - Using Lapack::leastSquaresBySVD:
  • Example#4309 - Using Lapack::pseudoInverse:
  • Example#4310 - Using Lapack::singularValues:
  • Example#4311 - Using Lapack::singularValues:
  • Example#4312 - abs example
  • Example#4313 - base_convert example
  • Example#4314 - bindec example
  • Example#4315 - bindec interprets input as unsigned integers
  • Example#4316 - ceil example
  • Example#4317 - cos example
  • Example#4318 - decbin example
  • Example#4319 - dechex example
  • Example#4320 - dechex example with large integers
  • Example#4321 - decoct example
  • Example#4322 - deg2rad example
  • Example#4323 - exp example
  • Example#4324 - floor example
  • Example#4325 - Using fmod
  • Example#4326 - hexdec example
  • Example#4327 - intdiv example
  • Example#4328 - is_nan example
  • Example#4329 - Example uses of max
  • Example#4330 - Example uses of min
  • Example#4331 - Calculate a random floating-point number
  • Example#4332 - mt_rand example
  • Example#4333 - mt_srand example
  • Example#4334 - octdec example
  • Example#4335 - pi example
  • Example#4336 - Some examples of pow
  • Example#4337 - rad2deg example
  • Example#4338 - rand example
  • Example#4339 - round examples
  • Example#4340 - How precision affects a float
  • Example#4341 - mode examples
  • Example#4342 - mode with precision examples
  • Example#4343 - sin example
  • Example#4344 - sqrt example
  • Example#4345 - srand example
  • Example#4346 - tan example
  • Example#4347 - Evaluating a FDF document
  • Example#4348 - Adding JavaScript code to a FDF
  • Example#4349 - Populating a PDF document
  • Example#4350 - Storing an uploaded file
  • Example#4351 - Detecting all fieldnames in a FDF
  • Example#4352 - Accessing the form data
  • Example#4353 - Accessing the form data
  • Example#4354 - Retrieving FDF as a string
  • Example#4355 - Passing FDF data to a second form
  • Example#4356 - gnupg clearsign example (procedural)
  • Example#4357 - gnupg clearsign example (OO)
  • Example#4358 - keylistiterator
  • Example#4359 - Procedural gnupg_adddecryptkey example
  • Example#4360 - OO gnupg_adddecryptkey example
  • Example#4361 - Procedural gnupg_addencryptkey example
  • Example#4362 - OO gnupg_addencryptkey example
  • Example#4363 - Procedural gnupg_addsignkey example
  • Example#4364 - OO gnupg_addsignkey example
  • Example#4365 - Procedural gnupg_cleardecryptkeys example
  • Example#4366 - OO gnupg_cleardecryptkeys example
  • Example#4367 - Procedural gnupg_clearencryptkeys example
  • Example#4368 - OO gnupg_clearencryptkeys example
  • Example#4369 - Procedural gnupg_clearsignkeys example
  • Example#4370 - OO gnupg_clearsignkeys example
  • Example#4371 - Procedural gnupg_decrypt example
  • Example#4372 - OO gnupg_encrypt example
  • Example#4373 - Procedural gnupg_decryptverify example
  • Example#4374 - OO gnupg_decryptverify example
  • Example#4375 - Procedural gnupg_encrypt example
  • Example#4376 - OO gnupg_encrypt example
  • Example#4377 - Procedural gnupg_encryptsign example
  • Example#4378 - OO gnupg_encryptsign example
  • Example#4379 - Procedural gnupg_export example
  • Example#4380 - OO gnupg_export example
  • Example#4381 - Procedural gnupg_geterror example
  • Example#4382 - OO gnupg_geterror example
  • Example#4383 - Procedural gnupg_getprotocol example
  • Example#4384 - OO gnupg_getprotocol example
  • Example#4385 - Procedural gnupg_import example
  • Example#4386 - OO gnupg_import example
  • Example#4387 - Procedural gnupg_init example
  • Example#4388 - OO gnupg initializer example
  • Example#4389 - Procedural gnupg_keyinfo example
  • Example#4390 - OO gnupg_keyinfo example
  • Example#4391 - Procedural gnupg_setarmor example
  • Example#4392 - OO gnupg_setarmor example
  • Example#4393 - Procedural gnupg_seterrormode example
  • Example#4394 - OO gnupg_seterrormode example
  • Example#4395 - Procedural gnupg_setsignmode example
  • Example#4396 - OO gnupg_setsignmode example
  • Example#4397 - Procedural gnupg_sign example
  • Example#4398 - OO gnupg_sign example
  • Example#4399 - Procedural gnupg_verify example
  • Example#4400 - OO gnupg_verify example
  • Example#4401 - Fancy "Hello world"
  • Example#4402 - swfaction example
  • Example#4403 - swfaction example
  • Example#4404 - swfaction example
  • Example#4405 - swfsprite example
  • Example#4406 - ming_useswfversion example
  • Example#4407 - Importing a DBL file
  • Example#4408 - Using an alpha mask
  • Example#4409 - Usual interactions with buttons
  • Example#4410 - Drag example
  • Example#4411 - swfdisplayitem::multcolor example
  • Example#4412 - swfdisplayitem::rotateto example
  • Example#4413 - swfdisplayitem::setname example
  • Example#4414 - swfgradient example
  • Example#4415 - swfmorph example
  • Example#4416 - Displaying your $movie in a browser
  • Example#4417 - Streaming example
  • Example#4418 - SWFShape::addFill example
  • Example#4419 - swfshape example
  • Example#4420 - swfshape::setline example
  • Example#4421 - swftext example
  • Example#4422 - Hello World example from PDFlib distribution for PHP 4
  • Example#4423 - Hello World example from PDFlib distribution for PHP 5
  • Example#4424 - Creating and using a pattern
  • Example#4425 - Creating and using a template
  • Example#4426 - Hyphennate a text
  • Example#4427 - Drawing a rectangle
  • Example#4428 - Creating and using a spot color
  • Example#4429 - Rotation of the coordinate system
  • Example#4430 - Placing text at a given position
  • Example#4431 - Drawing a dashed line
  • Example#4432 - Translation of the coordinate system
  • Example#4433 - Basic RPMReader Example
  • Example#4434 - rpm_close example
  • Example#4435 - rpm_get_tag example
  • Example#4436 - rpm_is_valid example
  • Example#4437 - rpm_open example
  • Example#4438 - rpm_version example
  • Example#4439 - example
  • Example#4440 - example
  • Example#4441 - example
  • Example#4442 - example
  • Example#4443 - example
  • Example#4444 - example
  • Example#4445 - example
  • Example#4446 - example
  • Example#4447 - example
  • Example#4448 - example
  • Example#4449 - example
  • Example#4450 - example
  • Example#4451 - example
  • Example#4452 - example
  • Example#4453 - example
  • Example#4454 - example
  • Example#4455 - example
  • Example#4456 - example
  • Example#4457 - example
  • Example#4458 - Incorrect requests
  • Example#4459 - Calling request from a request callback
  • Example#4460 - Calling request from a request callback
  • Example#4461 - Using eio with libevent
  • Example#4462 - Cancelling a request
  • Example#4463 - Calling eio_chmod
  • Example#4464 - Making a custom request
  • Example#4465 - Grouping requests
  • Example#4466 - Using eio with libevent extension
  • Example#4467 - Using eio with event extension
  • Example#4468 - eio_cancel example
  • Example#4469 - eio_custom example
  • Example#4470 - eio_event_loop example
  • Example#4471 - eio_lstat example
  • Example#4472 - Using eio with libevent
  • Example#4473 - Grouping requests
  • Example#4474 - eio_grp example
  • Example#4475 - eio_link example
  • Example#4476 - eio_lstat example
  • Example#4477 - eio_mkdir example
  • Example#4478 - eio_mknod example
  • Example#4479 - eio_nreqs example
  • Example#4480 - eio_open example
  • Example#4481 - eio_poll example
  • Example#4482 - eio_read example
  • Example#4483 - eio_readdir example
  • Example#4484 - eio_readlink example
  • Example#4485 - eio_realpath example
  • Example#4486 - eio_rename example
  • Example#4487 - eio_rmdir example
  • Example#4488 - eio_stat example
  • Example#4489 - eio_statvfs example
  • Example#4490 - eio_symlink example
  • Example#4491 - Simple timers
  • Example#4492 - Periodic timer. Tick each 10.5 seconds
  • Example#4493 - Periodic timer. Use reschedule callback
  • Example#4494 - Periodic timer. Tick every 10.5 seconds starting at now
  • Example#4495 - Wait until STDIN is readable
  • Example#4496 - Use some async I/O to access a socket
  • Example#4497 - Embedding one loop into another
  • Example#4498 - Embedding loop created with kqueue backend into the default loop
  • Example#4499 - Handle SIGTERM signal
  • Example#4500 - Monitor changes of /var/log/messages
  • Example#4501 - Monotor changes of /var/log/messages. Avoid missing updates by means of one second delay
  • Example#4502 - Process status changes
  • Example#4503 - Using reschedule callback
  • Example#4504 - Embedding loop created with kqueue backend into the default loop
  • Example#4505 - Embedding one loop into another
  • Example#4506 - Embedding loop created with kqueue backend into the default loop
  • Example#4507 - Embedding loop created with kqueue backend into the default loop
  • Example#4508 - Periodic timer. Use reschedule callback
  • Example#4509 - Periodic timer. Tick every 10.5 seconds starting at now
  • Example#4510 - Hourly watcher
  • Example#4511 - Handle SIGTERM signal
  • Example#4512 - Monitor changes of /var/log/messages
  • Example#4513 - Monitor changes of /var/log/messages
  • Example#4514 - Simple timers
  • Example#4515 - Monotor changes of /var/log/messages. Avoid missing updates by means of one second delay
  • Example#4516 - Register an I/O watcher for some UDP socket but do not keep the event loop from running just because of that watcher.
  • Example#4517 - Expect Usage Example
  • Example#4518 - Another Expect Usage Example
  • Example#4519 - expect_expectl example
  • Example#4520 - expect_popen example
  • Example#4521 - polling STDIN using basic API
  • Example#4522 - polling STDIN using buffered event API
  • Example#4523 - Process Control Example
  • Example#4524 - pcntl_fork example
  • Example#4525 - pcntl_signal_dispatch example
  • Example#4526 - pcntl_signal_get_handler example
  • Example#4527 - pcntl_signal example
  • Example#4528 - pcntl_sigprocmask example
  • Example#4529 - pcntl_sigwaitinfo example
  • Example#4530 - posix_access example
  • Example#4531 - posix_ctermid example
  • Example#4532 - posix_get_last_error example
  • Example#4533 - posix_getcwd example
  • Example#4534 - posix_getegid example
  • Example#4535 - posix_geteuid example
  • Example#4536 - posix_getgid example
  • Example#4537 - Example use of posix_getgrgid
  • Example#4538 - Example use of posix_getgrnam
  • Example#4539 - Example use of posix_getgroups
  • Example#4540 - Example use of posix_getlogin
  • Example#4541 - Example use of posix_getpgid
  • Example#4542 - Example use of posix_getpid
  • Example#4543 - Example use of posix_getppid
  • Example#4544 - Example use of posix_getpwnam
  • Example#4545 - Example use of posix_getpwuid
  • Example#4546 - Example use of posix_getrlimit
  • Example#4547 - Example use of posix_getsid
  • Example#4548 - Example use of posix_getuid
  • Example#4549 - A posix_mknod example
  • Example#4550 - posix_setegid example
  • Example#4551 - posix_setgid example
  • Example#4552 - posix_setuid example
  • Example#4553 - posix_strerror example
  • Example#4554 - Example use of posix_times
  • Example#4555 - Example use of posix_uname
  • Example#4556 - escapeshellarg example
  • Example#4557 - escapeshellcmd example
  • Example#4558 - An exec example
  • Example#4559 - Using proc_nice to set the process priority to high
  • Example#4560 - A proc_open example
  • Example#4561 - A shell_exec example
  • Example#4562 - system example
  • Example#4563 - Example showing Future as return value
  • Example#4564 - Example showing Future as synchronization point
  • Example#4565 - Fetch a chunk of the property table
  • Example#4566 - Counting the properties of an object
  • Example#4567 - Runtime inheritance
  • Example#4568 - Thread safe objects from closures
  • Example#4569 - Detecting fatal errors in Threads
  • Example#4570 - Detect the state of the referenced object
  • Example#4571 - Detect the state of the referenced object
  • Example#4572 - Detect the state of the referenced object
  • Example#4573 - Locking Object Properties
  • Example#4574 - Merging into the property table of a threaded object
  • Example#4575 - Notifications and Waiting
  • Example#4576 - Notifications and Waiting
  • Example#4577 - Popping the last item from the property table of a threaded object
  • Example#4578 - Shifting the first item from the property table of a threaded object
  • Example#4579 - Synchronizing
  • Example#4580 - Locking the property table of a threaded object
  • Example#4581 - Notifications and Waiting
  • Example#4582 - Return the identity of the Thread or Process that created the referenced Thread
  • Example#4583 - Return the currently executing Thread
  • Example#4584 - Return the identity of the currently executing Thread
  • Example#4585 - Return the identity of the referenced Thread
  • Example#4586 - Execute in the global scope
  • Example#4587 - Detect the state of the referenced Thread
  • Example#4588 - Tell if the referenced Thread was started
  • Example#4589 - Join with the referenced Thread
  • Example#4590 - Kill the referenced Thread
  • Example#4591 - Starting Threads
  • Example#4592 - A basic example of Worker::collect
  • Example#4593 - A basic example of Worker::getStacked
  • Example#4594 - Detect the state of a worker
  • Example#4595 - Detect the state of a Worker
  • Example#4596 - Shutdown the referenced worker
  • Example#4597 - Stacking a task for execution onto a worker
  • Example#4598 - Removing objects from the stack of Workers
  • Example#4599 - protected method example: protected methods can only be executed by one Thread at a time.
  • Example#4600 - private method example: private methods may only be executed by the Threaded object during execution
  • Example#4601 - A basic example of Pool::collect
  • Example#4602 - Creating Pools
  • Example#4603 - Shutting down a pool
  • Example#4604 - Submitting Tasks
  • Example#4605 - Submitting tasks to a specific worker
  • Example#4606 - Mutex Creation and Destruction
  • Example#4607 - Mutex Creation and Destruction
  • Example#4608 - Mutex Locking and Unlocking
  • Example#4609 - Mutex Locking and Unlocking
  • Example#4610 - Mutex Locking and Unlocking
  • Example#4611 - Condition Broadcasting
  • Example#4612 - Condition Creation and Destruction
  • Example#4613 - Condition Creation and Destruction
  • Example#4614 - Condition Signalling
  • Example#4615 - Waiting for Conditions
  • Example#4616 - New immutability semantics of Threaded
  • Example#4617 - Volatile use-case
  • Example#4618 - Adding a new class task to a thread
  • Example#4619 - Adding a new file task to a thread
  • Example#4620 - Adding a new function task to a thread
  • Example#4621 - Joining a thread
  • Example#4622 - Starting a new thread
  • Example#4623 - Getting the task count of a thread
  • Example#4624 - Locking a hash table's mutex lock
  • Example#4625 - Getting a hash table's size
  • Example#4626 - Locking a hash table's mutex lock
  • Example#4627 - Creating a new vector
  • Example#4628 - Deleting values in a vector
  • Example#4629 - Inserting a value into a vector
  • Example#4630 - Locking a vector's mutex lock
  • Example#4631 - Popping a value from a vector
  • Example#4632 - Pushing values to a vector
  • Example#4633 - Resizing a vector
  • Example#4634 - Shifting a value from a vector
  • Example#4635 - Getting a vector's size
  • Example#4636 - Locking a vector's mutex lock
  • Example#4637 - Unshifting a value to the front of a vector
  • Example#4638 - Updating a value in a vector
  • Example#4639 - Retrieving the front value of a queue
  • Example#4640 - Retrieving the front value in a loop (bad example - don't do this)
  • Example#4641 - Retrieving the front value in a loop (good example)
  • Example#4642 - Locking a queue's mutex lock
  • Example#4643 - Popping a value from a queue
  • Example#4644 - Pushing a value to a queue
  • Example#4645 - Getting a queue's size
  • Example#4646 - Locking a queue's mutex lock
  • Example#4647 - Creating a new atomic integer
  • Example#4648 - Decrementing an atomic integer's value
  • Example#4649 - Getting an atomic integer's value
  • Example#4650 - Incrementing an atomic integer's value
  • Example#4651 - Grouping together an atomic integer's operations (requiring a mutex lock)
  • Example#4652 - Setting an atomic integer's value
  • Example#4653 - Grouping together an atomic integer's operations (requiring a mutex lock)
  • Example#4654 -
  • Example#4655 - Shared Memory Operations Overview
  • Example#4656 - Closing shared memory block
  • Example#4657 - Deleting shared memory block
  • Example#4658 - Create a new shared memory block
  • Example#4659 - Reading shared memory block
  • Example#4660 - Getting the size of the shared memory block
  • Example#4661 - Writing to shared memory block
  • Example#4662 - SyncMutex::__construct named mutex with lock timeout example
  • Example#4663 - SyncMutex::__construct unnamed mutex example
  • Example#4664 - SyncMutex::lock example
  • Example#4665 - SyncMutex::unlock example
  • Example#4666 - SyncSemaphore::__construct example
  • Example#4667 - SyncSemaphore::lock example
  • Example#4668 - SyncSemaphore::unlock example
  • Example#4669 - SyncEvent::__construct example
  • Example#4670 - SyncEvent::fire example
  • Example#4671 - SyncEvent::reset example
  • Example#4672 - SyncEvent::wait example
  • Example#4673 - SyncReaderWriter::__construct example
  • Example#4674 - SyncReaderWriter::readlock example
  • Example#4675 - SyncReaderWriter::readunlock example
  • Example#4676 - SyncReaderWriter::writelock example
  • Example#4677 - SyncReaderWriter::writeunlock example
  • Example#4678 - SyncSharedMemory::__construct example
  • Example#4679 - SyncSharedMemory::first example
  • Example#4680 - SyncSharedMemory::__construct example
  • Example#4681 - SyncSharedMemory::size example
  • Example#4682 - SyncSharedMemory::write example
  • Example#4683 - A geoip_asnum_by_name example
  • Example#4684 - A geoip_continent_code_by_name example
  • Example#4685 - A geoip_country_code_by_name example
  • Example#4686 - A geoip_country_code3_by_name example
  • Example#4687 - A geoip_country_name_by_name example
  • Example#4688 - A geoip_database_info example
  • Example#4689 - A geoip_db_avail example
  • Example#4690 - A geoip_db_filename example
  • Example#4691 - A geoip_db_get_all_info example
  • Example#4692 - A geoip_db_get_all_info example
  • Example#4693 - A geoip_domain_by_name example
  • Example#4694 - A geoip_id_by_name example
  • Example#4695 - A geoip_isp_by_name example
  • Example#4696 - A geoip_netspeedcell_by_name example
  • Example#4697 - A geoip_org_by_name example
  • Example#4698 - A geoip_record_by_name example
  • Example#4699 - A geoip_region_by_name example
  • Example#4700 - A geoip_region_name_by_code example using region code for US/Canada
  • Example#4701 - A geoip_region_name_by_code example using FIPS codes
  • Example#4702 - A geoip_setup_custom_directory example
  • Example#4703 - A geoip_time_zone_by_country_and_region example using region code for US/Canada
  • Example#4704 - A geoip_time_zone_by_country_and_region example using FIPS codes
  • Example#4705 - xor.data file
  • Example#4706 - Simple train
  • Example#4707 - Simple test
  • Example#4708 - fann_create_train_from_callback example
  • Example#4709 - fann_read_train_from_file example
  • Example#4710 - JsonSerializable::jsonSerialize example returning an array
  • Example#4711 - JsonSerializable::jsonSerialize example returning an associative array
  • Example#4712 - JsonSerializable::jsonSerialize example returning an integer
  • Example#4713 - JsonSerializable::jsonSerialize example returning a string
  • Example#4714 - json_decode examples
  • Example#4715 - Accessing invalid object properties
  • Example#4716 - common mistakes using json_decode
  • Example#4717 - depth errors
  • Example#4718 - json_decode of large integers
  • Example#4719 - A json_encode example
  • Example#4720 - A json_encode example showing some options in use
  • Example#4721 - JSON_NUMERIC_CHECK option example
  • Example#4722 - Sequential versus non-sequential array example
  • Example#4723 - JSON_PRESERVE_ZERO_FRACTION option example
  • Example#4724 - json_last_error example
  • Example#4725 - json_last_error with json_encode
  • Example#4726 - json_last_error and JSON_THROW_ON_ERROR
  • Example#4727 - Judy array example
  • Example#4728 - Lua::assignexample
  • Example#4729 - Lua::callexample
  • Example#4730 - Lua::evalexample
  • Example#4731 - Lua::registerCallbackexample
  • Example#4732 - LuaClosure::__invokeexample
  • Example#4733 - Execute some Lua code
  • Example#4734 - Calling a Lua function
  • Example#4735 - Profiling Lua code
  • Example#4736 - Loading code into Lua
  • Example#4737 - Manipulating the usage timer
  • Example#4738 - Registering PHP functions to call from Lua
  • Example#4739 - Calling a Lua function
  • Example#4740 - Calling a Lua function
  • Example#4741 - constant example
  • Example#4742 - Defining Constants
  • Example#4743 - Constants with Reserved Names
  • Example#4744 - Checking Constants
  • Example#4745 - eval example - simple text merge
  • Example#4746 - exit example
  • Example#4747 - exit status example
  • Example#4748 - Shutdown functions and destructors run regardless
  • Example#4749 - Listing all information about the users browser
  • Example#4750 - A __halt_compiler example
  • Example#4751 - highlight_string example
  • Example#4752 - hrtime usage
  • Example#4753 - A ignore_user_abort example
  • Example#4754 - pack example
  • Example#4755 - php_strip_whitespace example
  • Example#4756 - Basic sapi_windows_generate_ctrl_event Usage
  • Example#4757 - Basic sapi_windows_set_ctrl_handler Usage
  • Example#4758 - sapi_windows_vt100_support default state
  • Example#4759 - sapi_windows_vt100_support changing state
  • Example#4760 - Example usage of VT100 support enabled
  • Example#4761 - sleep example
  • Example#4762 - A sys_getloadavg example
  • Example#4763 - time_nanosleep example
  • Example#4764 - A time_sleep_until example
  • Example#4765 - uniqid Example
  • Example#4766 - unpack example
  • Example#4767 - unpack example with a repeater
  • Example#4768 - unpack example with unnamed keys
  • Example#4769 - usleep example
  • Example#4770 - parsekit_compile_file example
  • Example#4771 - parsekit_compile_string example
  • Example#4772 - parsekit_func_arginfo example
  • Example#4773 - Get and set base path
  • Example#4774 - Get and set logger
  • Example#4775 - Fast write log
  • Example#4776 - Fast count some type of log count value
  • Example#4777 - Acquisit some type of log list
  • Example#4778 - seaslog_get_author example
  • Example#4779 - seaslog_get_version example
  • Example#4780 - SeasLog::alert example
  • Example#4781 - SeasLog::analyzerCount example
  • Example#4782 - SeasLog::analyzerDetail example
  • Example#4783 - SeasLog::closeLoggerStream example
  • Example#4784 - SeasLog::__construct example
  • Example#4785 - SeasLog::critical example
  • Example#4786 - SeasLog::debug example
  • Example#4787 - SeasLog::__destruct example
  • Example#4788 - SeasLog::emergency example
  • Example#4789 - SeasLog::error example
  • Example#4790 - SeasLog::flushBuffer example
  • Example#4791 - SeasLog::getBasePath example
  • Example#4792 - SeasLog::getBuffer example
  • Example#4793 - SeasLog::getBufferEnabled example
  • Example#4794 - SeasLog::getDatetimeFormat example
  • Example#4795 - SeasLog::getLastLogger example
  • Example#4796 - SeasLog::getRequestID example
  • Example#4797 - SeasLog::getRequestVariable example
  • Example#4798 - SeasLog::info example
  • Example#4799 - SeasLog::log example
  • Example#4800 - SeasLog::notice example
  • Example#4801 - SeasLog::setBasePath example
  • Example#4802 - SeasLog::setDatetimeFormat example
  • Example#4803 - SeasLog::setLogger example
  • Example#4804 - SeasLog::setRequestID example
  • Example#4805 - SeasLog::setRequestVariable example
  • Example#4806 - SeasLog::warning example
  • Example#4807 - SplDoublyLinkedList::__construct example
  • Example#4808 - SplStack::__construct example
  • Example#4809 - SplQueue::__construct example
  • Example#4810 - Efficiently handling tasks with SplQueue
  • Example#4811 - SplFixedArray usage example
  • Example#4812 - SplFixedArray::__construct example
  • Example#4813 - SplFixedArray::count example
  • Example#4814 - SplFixedArray::fromArray example
  • Example#4815 - SplFixedArray::getSize example
  • Example#4816 - SplFixedArray::setSize example
  • Example#4817 - SplFixedArray::toArray example
  • Example#4818 - SplObjectStorage as a set
  • Example#4819 - SplObjectStorage as a map
  • Example#4820 - SplObjectStorage::addAll example
  • Example#4821 - SplObjectStorage::attach example
  • Example#4822 - SplObjectStorage::contains example
  • Example#4823 - SplObjectStorage::count example
  • Example#4824 - SplObjectStorage::current example
  • Example#4825 - SplObjectStorage::detach example
  • Example#4826 - SplObjectStorage::getHash example
  • Example#4827 - SplObjectStorage::getInfo example
  • Example#4828 - SplObjectStorage::key example
  • Example#4829 - SplObjectStorage::next example
  • Example#4830 - SplObjectStorage::offsetExists example
  • Example#4831 - SplObjectStorage::offsetGet example
  • Example#4832 - SplObjectStorage::offsetSet example
  • Example#4833 - SplObjectStorage::offsetUnset example
  • Example#4834 - SplObjectStorage::removeAll example
  • Example#4835 - SplObjectStorage::removeAllExcept example
  • Example#4836 - SplObjectStorage::rewind example
  • Example#4837 - SplObjectStorage::serialize example
  • Example#4838 - SplObjectStorage::setInfo example
  • Example#4839 - SplObjectStorage::unserialize example
  • Example#4840 - SplObjectStorage::valid example
  • Example#4841 - AppendIterator::append example
  • Example#4842 - Iterating AppendIterator with foreach
  • Example#4843 - Iterating AppendIterator with the AppendIterator API
  • Example#4844 - AppendIterator::getInnerIterator example
  • Example#4845 - AppendIterator.getIteratorIndex basic example
  • Example#4846 - AppendIterator::key basic example
  • Example#4847 - ArrayIterator::current example
  • Example#4848 - ArrayIterator::key example
  • Example#4849 - ArrayIterator::next example
  • Example#4850 - ArrayIterator::rewind example
  • Example#4851 - ArrayIterator::valid example
  • Example#4852 - CachingIterator::getCache example
  • Example#4853 - Available callback arguments
  • Example#4854 - Callback basic examples
  • Example#4855 - A DirectoryIterator::__construct example
  • Example#4856 - A DirectoryIterator::current example
  • Example#4857 - A DirectoryIterator::getATime example
  • Example#4858 - A DirectoryIterator::getBasename example
  • Example#4859 - DirectoryIterator::getCTime example
  • Example#4860 - DirectoryIterator::getExtension example
  • Example#4861 -
  • Example#4862 - A DirectoryIterator::getFilename example
  • Example#4863 - DirectoryIterator::getGroup example
  • Example#4864 - DirectoryIterator::getInode example
  • Example#4865 - A DirectoryIterator::getMTime example
  • Example#4866 - DirectoryIterator::getOwner example
  • Example#4867 - DirectoryIterator::getPath example
  • Example#4868 - DirectoryIterator::getPathname example
  • Example#4869 - DirectoryIterator::getPerms example
  • Example#4870 - DirectoryIterator::getSize example
  • Example#4871 - DirectoryIterator::getType example
  • Example#4872 - DirectoryIterator::isDir example
  • Example#4873 - A DirectoryIterator::isDot example
  • Example#4874 - DirectoryIterator::isExecutable example
  • Example#4875 - DirectoryIterator::isFile example
  • Example#4876 - A DirectoryIterator::isLink example
  • Example#4877 - DirectoryIterator::isReadable example
  • Example#4878 - DirectoryIterator::isWritable example
  • Example#4879 - A DirectoryIterator::key example
  • Example#4880 - DirectoryIterator::next example
  • Example#4881 - DirectoryIterator::rewind example
  • Example#4882 - DirectoryIterator::seek example
  • Example#4883 - A DirectoryIterator::__toString example
  • Example#4884 - A DirectoryIterator::valid example
  • Example#4885 - FilesystemIterator::__construct example
  • Example#4886 - FilesystemIterator::current example
  • Example#4887 - FilesystemIterator::key example
  • Example#4888 - FilesystemIterator::next example
  • Example#4889 - FilesystemIterator::rewind example
  • Example#4890 - FilesystemIterator::key example
  • Example#4891 - FilterIterator::accept example
  • Example#4892 - GlobIterator example
  • Example#4893 - GlobIterator::count example
  • Example#4894 - InfiniteIterator::__construct example
  • Example#4895 - LimitIterator usage example
  • Example#4896 - LimitIterator::__construct example
  • Example#4897 - LimitIterator::getPosition example
  • Example#4898 - Iterating a MultipleIterator
  • Example#4899 - NoRewindIterator::__construct example
  • Example#4900 - NoRewindIterator::rewind example
  • Example#4901 - RecursiveArrayIterator::getChildren example
  • Example#4902 - RecursiveArrayIterator::hasChildren example
  • Example#4903 - Available callback arguments
  • Example#4904 - Recursive callback basic example
  • Example#4905 - RecursiveCallbackFilterIterator::hasChildren basic usage
  • Example#4906 - RecursiveDirectoryIterator example
  • Example#4907 - getSubPath example
  • Example#4908 - getSubPathname example
  • Example#4909 - Basic RecursiveFilterIterator example
  • Example#4910 - RecursiveFilterIterator example
  • Example#4911 - Iterating a RecursiveIteratorIterator
  • Example#4912 - RecursiveRegexIterator::__construct example
  • Example#4913 - RecursiveRegexIterator::getChildren example
  • Example#4914 - RecursiveRegexIterator::hasChildren example
  • Example#4915 - RegexIterator::accept example
  • Example#4916 - RegexIterator::__construct example
  • Example#4917 - RegexIterator::getFlags example
  • Example#4918 - RegexIterator::getMode example
  • Example#4919 - RegexIterator::getPregFlags example
  • Example#4920 - RegexIterator::setFlags example
  • Example#4921 - RegexIterator::setMode example
  • Example#4922 - RegexIterator::setPregFlags example
  • Example#4923 - Countable::count example
  • Example#4924 - Basic usage
  • Example#4925 - SeekableIterator::seek example
  • Example#4926 - class_implements example
  • Example#4927 - class_parents example
  • Example#4928 - class_uses example
  • Example#4929 - iterator_apply example
  • Example#4930 - iterator_count example
  • Example#4931 - iterator_count modifies position
  • Example#4932 - iterator_count in foreach loops
  • Example#4933 - iterator_to_array example
  • Example#4934 - spl_autoload_extensions example
  • Example#4935 - spl_autoload_register as a replacement for an __autoload function
  • Example#4936 - spl_autoload_register example where the class is not loaded
  • Example#4937 - spl_classes example
  • Example#4938 - A spl_object_hash example
  • Example#4939 - A spl_object_id example
  • Example#4940 - SplFileInfo::__construct example
  • Example#4941 - SplFileInfo::getBasename example
  • Example#4942 - SplFileInfo::getCTime example
  • Example#4943 - SplFileInfo::getExtension example
  • Example#4944 -
  • Example#4945 - SplFileInfo::getFilename example
  • Example#4946 - SplFileInfo::getGroup example
  • Example#4947 - SplFileInfo::getLinkTarget example
  • Example#4948 - SplFileInfo::getOwner example
  • Example#4949 - SplFileInfo::getPath example
  • Example#4950 - SplFileInfo::getPathInfo example
  • Example#4951 - SplFileInfo::getPathname example
  • Example#4952 - SplFileInfo::getPerms example
  • Example#4953 - SplFileInfo::getRealPath example
  • Example#4954 - SplFileInfo::getType example
  • Example#4955 - SplFileInfo::isDir example
  • Example#4956 - SplFileInfo::isExecutable example
  • Example#4957 - SplFileInfo::isFile example
  • Example#4958 - SplFileInfo::isLink example
  • Example#4959 - SplFileInfo::isReadable example
  • Example#4960 - SplFileInfo::openFile example
  • Example#4961 - SplFileInfo::setFileClass example
  • Example#4962 - SplFileInfo::setFileClass example
  • Example#4963 - SplFileInfo::__toString example
  • Example#4964 - SplFileObject::__construct example
  • Example#4965 - SplFileObject::current example
  • Example#4966 - SplFileObject::eof example
  • Example#4967 - SplFileObject::fflush example
  • Example#4968 - SplFileObject::fgetc example
  • Example#4969 - SplFileObject::fgetcsv example
  • Example#4970 - SplFileObject::READ_CSV example
  • Example#4971 - SplFileObject::fgets example
  • Example#4972 - SplFileObject::fgetss example
  • Example#4973 - SplFileObject::flock example
  • Example#4974 - SplFileObject::fpassthru example
  • Example#4975 - SplFileObject::fputcsv example
  • Example#4976 - SplFileObject::fread example
  • Example#4977 - SplFileObject::fscanf example
  • Example#4978 - SplFileObject::fseek example
  • Example#4979 - SplFileObject::fstat example
  • Example#4980 - SplFileObject::ftell example
  • Example#4981 - SplFileObject::ftruncate example
  • Example#4982 - SplFileObject::fwrite example
  • Example#4983 - SplFileObject::getCsvControl example
  • Example#4984 - SplFileObject::getFlags example
  • Example#4985 - SplFileObject::getMaxLineLen example
  • Example#4986 - SplFileObject::key example
  • Example#4987 - SplFileObject::key example with SplFileObject::setMaxLineLen
  • Example#4988 - SplFileObject::next example
  • Example#4989 - SplFileObject::rewind example
  • Example#4990 - SplFileObject::seek example
  • Example#4991 - SplFileObject::setCsvControl example
  • Example#4992 - SplFileObject::setFlags example
  • Example#4993 - SplFileObject::setMaxLineLen example
  • Example#4994 - SplFileObject::valid example
  • Example#4995 - SplTempFileObject example
  • Example#4996 - ArrayObject::append example
  • Example#4997 - ArrayObject::asort example
  • Example#4998 - ArrayObject::__construct example
  • Example#4999 - ArrayObject::count example
  • Example#5000 - ArrayObject::exchangeArray example
  • Example#5001 - ArrayObject::getArrayCopy example
  • Example#5002 - ArrayObject::getFlags example
  • Example#5003 - ArrayObject::getIterator example
  • Example#5004 - ArrayObject::getIteratorClass example
  • Example#5005 - ArrayObject::ksort example
  • Example#5006 - ArrayObject::natcasesort example
  • Example#5007 - ArrayObject::natsort example
  • Example#5008 - ArrayObject::offsetExists example
  • Example#5009 - ArrayObject::offsetGet example
  • Example#5010 - ArrayObject::offsetSet example
  • Example#5011 - ArrayObject::offsetUnset example
  • Example#5012 - ArrayObject::serialize example
  • Example#5013 - ArrayObject::setFlags example
  • Example#5014 - ArrayObject::setIteratorClass example
  • Example#5015 - ArrayObject::uasort example
  • Example#5016 - ArrayObject::uksort example
  • Example#5017 - SplInt usage example
  • Example#5018 - SplFloat usage example
  • Example#5019 - SplEnum usage example
  • Example#5020 - SplEnum::getConstList example
  • Example#5021 - SplBool usage example
  • Example#5022 - SplString usage example
  • Example#5023 - Using file_get_contents to retrieve data from multiple sources
  • Example#5024 - Making a POST request to an https server
  • Example#5025 - Writing data to a compressed file
  • Example#5026 - A Stream for reading/writing global variables
  • Example#5027 - Listing files from tar archives
  • Example#5028 - stream_bucket_prepend examples
  • Example#5029 - Using stream_context_create
  • Example#5030 - Using stream_context_get_default
  • Example#5031 - stream_context_get_options example
  • Example#5032 - stream_context_get_params example
  • Example#5033 - stream_context_set_default example
  • Example#5034 - A stream_copy_to_stream example
  • Example#5035 - Controlling where filters are applied
  • Example#5036 - Filter for capitalizing characters on foo-bar.txt stream
  • Example#5037 - Registering a generic filter class to match multiple filter names.
  • Example#5038 - Dynamically refiltering a stream
  • Example#5039 - stream_get_contents example
  • Example#5040 - Using stream_get_filters
  • Example#5041 - stream_get_meta_data example
  • Example#5042 - Using stream_get_transports
  • Example#5043 - stream_get_wrappers example
  • Example#5044 - Checking for the existence of a stream wrapper
  • Example#5045 - stream_is_local example
  • Example#5046 - stream_isatty example
  • Example#5047 - stream_notification_callback example
  • Example#5048 - Simple progressbar for commandline download client
  • Example#5049 - stream_resolve_include_path example
  • Example#5050 - stream_select Example
  • Example#5051 - stream_set_timeout example
  • Example#5052 - stream_set_write_buffer example
  • Example#5053 - stream_socket_client example
  • Example#5054 - Using UDP connection
  • Example#5055 - stream_socket_enable_crypto example
  • Example#5056 - A stream_socket_pair example
  • Example#5057 - stream_socket_recvfrom example
  • Example#5058 - stream_socket_sendto Example
  • Example#5059 - Using TCP server sockets
  • Example#5060 - Using UDP server sockets
  • Example#5061 - A stream_socket_shutdown example
  • Example#5062 - How to register a stream wrapper
  • Example#5063 - Basic Tidy usage
  • Example#5064 - tidy::getBody example
  • Example#5065 - tidy::cleanrepair example
  • Example#5066 - tidy::__construct example
  • Example#5067 - tidy::diagnose example
  • Example#5068 - tidy_get_error_buffer example
  • Example#5069 - tidy::getConfig example
  • Example#5070 - tidy_getopt example
  • Example#5071 - Print all options along with their documentation and default value
  • Example#5072 - tidy::getStatus example
  • Example#5073 - tidy::head example
  • Example#5074 - tidy::html example
  • Example#5075 - tidy::parseFile example
  • Example#5076 - tidy::parseString example
  • Example#5077 - tidy::repairFile example
  • Example#5078 - tidy::repairString example
  • Example#5079 - tidy::root example
  • Example#5080 - tidyNode::hasChildren example
  • Example#5081 - tidyNode::hasChildren example
  • Example#5082 - tidyNode::hasSiblings example
  • Example#5083 - Extract ASP code from a mixed HTML document
  • Example#5084 - Extract comments from a mixed HTML document
  • Example#5085 - Extract HTML code from a mixed HTML document
  • Example#5086 - Extract JSTE code from a mixed HTML document
  • Example#5087 - Extract PHP code from a mixed HTML document
  • Example#5088 - Extract text from a mixed HTML document
  • Example#5089 - ob_tidyhandler example
  • Example#5090 - tidy_access_count example
  • Example#5091 - tidy_config_count example
  • Example#5092 - tidy_error_count example
  • Example#5093 - tidy_get_output example
  • Example#5094 - tidy_warning_count example
  • Example#5095 - Strip comments with the tokenizer
  • Example#5096 - token_get_all example
  • Example#5097 - token_get_all incorrect usage example
  • Example#5098 - token_get_all on a class using a reserved word example
  • Example#5099 - token_name example
  • Example#5100 - base64_decode example
  • Example#5101 - base64_encode example
  • Example#5102 - get_headers example
  • Example#5103 - get_headers using HEAD example
  • Example#5104 - What get_meta_tags parses
  • Example#5105 - What get_meta_tags returns
  • Example#5106 - Simple usage of http_build_query
  • Example#5107 - http_build_query with numerically index elements.
  • Example#5108 - http_build_query with complex arrays
  • Example#5109 - Using http_build_query with an object
  • Example#5110 - A parse_url example
  • Example#5111 - A parse_url example with missing scheme
  • Example#5112 - rawurldecode example
  • Example#5113 - including a password in an FTP URL
  • Example#5114 - rawurlencode example 2
  • Example#5115 - urldecode example
  • Example#5116 - urlencode example
  • Example#5117 - urlencode and htmlentities example
  • Example#5118 - Basic Javascript execution
  • Example#5119 - Yaml Example
  • Example#5120 - Parse callback example
  • Example#5121 - Emit callback example
  • Example#5122 - yaml_emit example
  • Example#5123 - yaml_parse example
  • Example#5124 - A classic Application directory layout
  • Example#5125 - Entry
  • Example#5126 - Rewrite rule
  • Example#5127 - Application config
  • Example#5128 - Default controller
  • Example#5129 - Default view template
  • Example#5130 - Run the Application
  • Example#5131 - An PHP array example
  • Example#5132 - An ini file example
  • Example#5133 - A Bootstrapexample
  • Example#5134 - Yaf_Application::bootstrapexample
  • Example#5135 - Yaf_Application::clearLastErrorexample
  • Example#5136 - A ini config file example
  • Example#5137 - Yaf_Application::__constructexample
  • Example#5138 - Yaf_Application::__constructexample
  • Example#5139 - Yaf_Application::environexample
  • Example#5140 - Yaf_Application::executeexample
  • Example#5141 - Yaf_Application::getConfigexample
  • Example#5142 - Yaf_Application::getDispatcherexample
  • Example#5143 - Yaf_Application::getLastErrorMsgexample
  • Example#5144 - Yaf_Application::getLastErrorNoexample
  • Example#5145 - Yaf_Application::getModulesexample
  • Example#5146 - Bootstrap example
  • Example#5147 - Yaf_Dispatcher::autoRenderexample
  • Example#5148 - Yaf_Dispatcher::catchExceptionexample
  • Example#5149 - Yaf_Dispatcher::registerPluginexample
  • Example#5150 - A custom View engineexample
  • Example#5151 - Yaf_Dispatcher::setViewexample
  • Example#5152 - Yaf_Dispatcher::throwexceptionexample
  • Example#5153 - Yaf_Dispatcher::throwexceptionexample
  • Example#5154 - Yaf_Config_Iniexample
  • Example#5155 - define action in a separate file
  • Example#5156 - Dummy_action.php
  • Example#5157 - Yaf_Controller_Abstract::forwardexample
  • Example#5158 - Yaf_Action_Abstract::executeexample
  • Example#5159 - Yaf_Action_Abstract::executeexample
  • Example#5160 - Yaf_View_Simple::assignexample
  • Example#5161 - templateexample
  • Example#5162 - Yaf_View_Simple::assignRefexample
  • Example#5163 - templateexample
  • Example#5164 - Yaf_View_Simple::clearexample
  • Example#5165 - Yaf_View_Simple::__constructorexample
  • Example#5166 - Yaf_View_Simple::__setexample
  • Example#5167 - Config example
  • Example#5168 - Register localnamespace
  • Example#5169 - Load class example
  • Example#5170 - Load namespace class example
  • Example#5171 - MVC class loading example
  • Example#5172 - MVC class distinctions
  • Example#5173 - MVC loading example
  • Example#5174 - Yaf_Loader::registerLocalNamespaceexample
  • Example#5175 - Plugin example
  • Example#5176 - Yaf_Plugin_Abstract::routerShutdownexample
  • Example#5177 - Yaf_Response_Abstract::appendBodyexample
  • Example#5178 - Yaf_Response_Abstract::getBodyexample
  • Example#5179 - Yaf_Response_Abstract::prependBodyexample
  • Example#5180 - Yaf_Response_Abstract::responseexample
  • Example#5181 - Yaf_Response_Abstract::setBodyexample
  • Example#5182 - Yaf_Route_Map::assembleexample
  • Example#5183 - Yaf_Route_Mapexample
  • Example#5184 - Yaf_Route_Mapexample
  • Example#5185 - Yaf_Route_Mapexample
  • Example#5186 - Yaf_Route_Regex::assembleexample
  • Example#5187 - Yaf_Route_Regexexample
  • Example#5188 - Yaf_Route_Regex(as of 2.3.0)example
  • Example#5189 - Yaf_Route_Regex and named capture ground(as of 2.3.0)example
  • Example#5190 - Yaf_Route_Regexexample
  • Example#5191 - Yaf_Route_Rewrite::assembleexample
  • Example#5192 - Yaf_Route_Rewriteexample
  • Example#5193 - Yaf_Route_Rewriteexample
  • Example#5194 - Yaf_Route_Rewrite(as of 2.3.0)example
  • Example#5195 - Rewrite rule for Apache
  • Example#5196 - Rewrite rule for Apache
  • Example#5197 - Rewrite rule for Lighttpd
  • Example#5198 - Rewrite rule for Nginx
  • Example#5199 - Yaf_Route_Static(default route)example
  • Example#5200 - application.iniexample
  • Example#5201 - Yaf_Dispatcher::autoConfigexample
  • Example#5202 - Yaf_Dispatcher::autoRenderexample
  • Example#5203 - Register some routes in Bootstrap
  • Example#5204 - plugin Dummy.php (under application.directory/plugins)
  • Example#5205 - Yaf_Route_Simple::assembleexample
  • Example#5206 - Yaf_Route_Simple::routeexample
  • Example#5207 - Yaf_Route_Simple::routeexample
  • Example#5208 - Yaf_Route_Static::assembleexample
  • Example#5209 - Yaf_Route_Static::routeexample
  • Example#5210 - Yaf_Route_Supervar::assembleexample
  • Example#5211 - Yaf_Route_Supervarexample
  • Example#5212 - INI example
  • Example#5213 - INI sections example
  • Example#5214 - INIexample
  • Example#5215 - Taintexample
  • Example#5216 - Vector
  • Example#5217 - Map
  • Example#5218 - Ds\Collection::clear example
  • Example#5219 - Ds\Collection::copy example
  • Example#5220 - Ds\Collection::isEmpty example
  • Example#5221 - Ds\Collection::toArray example
  • Example#5222 - Ds\Hashable::hash example
  • Example#5223 - Ds\Sequence::allocate example
  • Example#5224 - Ds\Sequence::apply example
  • Example#5225 - Ds\Sequence::capacity example
  • Example#5226 - Ds\Sequence::contains example
  • Example#5227 - Ds\Sequence::filter example using callback function
  • Example#5228 - Ds\Sequence::filter example without a callback function
  • Example#5229 - Ds\Sequence::find example
  • Example#5230 - Ds\Sequence::first example
  • Example#5231 - Ds\Sequence::get example
  • Example#5232 - Ds\Sequence::get example using array syntax
  • Example#5233 - Ds\Sequence::insert example
  • Example#5234 - Ds\Sequence::join example using a separator string
  • Example#5235 - Ds\Sequence::join example without a separator string
  • Example#5236 - Ds\Sequence::last example
  • Example#5237 - Ds\Sequence::map example
  • Example#5238 - Ds\Sequence::merge example
  • Example#5239 - Ds\Sequence::pop example
  • Example#5240 - Ds\Sequence::push example
  • Example#5241 - Ds\Sequence::reduce with initial value example
  • Example#5242 - Ds\Sequence::reduce without an initial value example
  • Example#5243 - Ds\Sequence::remove example
  • Example#5244 - Ds\Sequence::reverse example
  • Example#5245 - Ds\Sequence::reversed example
  • Example#5246 - Ds\Sequence::rotate example
  • Example#5247 - Ds\Sequence::set example
  • Example#5248 - Ds\Sequence::set example using array syntax
  • Example#5249 - Ds\Sequence::shift example
  • Example#5250 - Ds\Sequence::slice example
  • Example#5251 - Ds\Sequence::sort example
  • Example#5252 - Ds\Sequence::sort example using a comparator
  • Example#5253 - Ds\Sequence::sorted example
  • Example#5254 - Ds\Sequence::sorted example using a comparator
  • Example#5255 - Ds\Sequence::sum integer example
  • Example#5256 - Ds\Sequence::sum float example
  • Example#5257 - Ds\Sequence::unshift example
  • Example#5258 - Ds\Vector::allocate example
  • Example#5259 - Ds\Vector::apply example
  • Example#5260 - Ds\Vector::capacity example
  • Example#5261 - Ds\Vector::clear example
  • Example#5262 - Ds\Vector::__construct example
  • Example#5263 - Ds\Vector::contains example
  • Example#5264 - Ds\Vector::copy example
  • Example#5265 - Ds\Vector::filter example using callback function
  • Example#5266 - Ds\Vector::filter example without a callback function
  • Example#5267 - Ds\Vector::find example
  • Example#5268 - Ds\Vector::first example
  • Example#5269 - Ds\Vector::get example
  • Example#5270 - Ds\Vector::get example using array syntax
  • Example#5271 - Ds\Vector::insert example
  • Example#5272 - Ds\Vector::isEmpty example
  • Example#5273 - Ds\Vector::join example using a separator string
  • Example#5274 - Ds\Vector::join example without a separator string
  • Example#5275 - Ds\Vector::last example
  • Example#5276 - Ds\Vector::map example
  • Example#5277 - Ds\Vector::merge example
  • Example#5278 - Ds\Vector::pop example
  • Example#5279 - Ds\Vector::push example
  • Example#5280 - Ds\Vector::reduce with initial value example
  • Example#5281 - Ds\Vector::reduce without an initial value example
  • Example#5282 - Ds\Vector::remove example
  • Example#5283 - Ds\Vector::reverse example
  • Example#5284 - Ds\Vector::reversed example
  • Example#5285 - Ds\Vector::rotate example
  • Example#5286 - Ds\Vector::set example
  • Example#5287 - Ds\Vector::set example using array syntax
  • Example#5288 - Ds\Vector::shift example
  • Example#5289 - Ds\Vector::slice example
  • Example#5290 - Ds\Vector::sort example
  • Example#5291 - Ds\Vector::sort example using a comparator
  • Example#5292 - Ds\Vector::sorted example
  • Example#5293 - Ds\Vector::sorted example using a comparator
  • Example#5294 - Ds\Vector::sum integer example
  • Example#5295 - Ds\Vector::sum float example
  • Example#5296 - Ds\Vector::toArray example
  • Example#5297 - Ds\Vector::unshift example
  • Example#5298 - Ds\Deque::allocate example
  • Example#5299 - Ds\Deque::apply example
  • Example#5300 - Ds\Deque::capacity example
  • Example#5301 - Ds\Deque::clear example
  • Example#5302 - Ds\Deque::__construct example
  • Example#5303 - Ds\Deque::contains example
  • Example#5304 - Ds\Deque::copy example
  • Example#5305 - Ds\Deque::filter example using callback function
  • Example#5306 - Ds\Deque::filter example without a callback function
  • Example#5307 - Ds\Deque::find example
  • Example#5308 - Ds\Deque::first example
  • Example#5309 - Ds\Deque::get example
  • Example#5310 - Ds\Deque::get example using array syntax
  • Example#5311 - Ds\Deque::insert example
  • Example#5312 - Ds\Deque::isEmpty example
  • Example#5313 - Ds\Deque::join example using a separator string
  • Example#5314 - Ds\Deque::join example without a separator string
  • Example#5315 - Ds\Deque::last example
  • Example#5316 - Ds\Deque::map example
  • Example#5317 - Ds\Deque::merge example
  • Example#5318 - Ds\Deque::pop example
  • Example#5319 - Ds\Deque::push example
  • Example#5320 - Ds\Deque::reduce with initial value example
  • Example#5321 - Ds\Deque::reduce without an initial value example
  • Example#5322 - Ds\Deque::remove example
  • Example#5323 - Ds\Deque::reverse example
  • Example#5324 - Ds\Deque::reversed example
  • Example#5325 - Ds\Deque::rotate example
  • Example#5326 - Ds\Deque::set example
  • Example#5327 - Ds\Deque::set example using array syntax
  • Example#5328 - Ds\Deque::shift example
  • Example#5329 - Ds\Deque::slice example
  • Example#5330 - Ds\Deque::sort example
  • Example#5331 - Ds\Deque::sort example using a comparator
  • Example#5332 - Ds\Deque::sorted example
  • Example#5333 - Ds\Deque::sorted example using a comparator
  • Example#5334 - Ds\Deque::sum integer example
  • Example#5335 - Ds\Deque::sum float example
  • Example#5336 - Ds\Deque::toArray example
  • Example#5337 - Ds\Deque::unshift example
  • Example#5338 - Ds\Map::allocate example
  • Example#5339 - Ds\Map::apply example
  • Example#5340 - Ds\Map::capacity example
  • Example#5341 - Ds\Map::clear example
  • Example#5342 - Ds\Map::__construct example
  • Example#5343 - Ds\Map::copy example
  • Example#5344 - Ds\Map::diff example
  • Example#5345 - Ds\Map::filter example using callback function
  • Example#5346 - Ds\Map::filter example without a callback function
  • Example#5347 - Ds\Map::first example
  • Example#5348 - Ds\Map::get example
  • Example#5349 - Ds\Map::get example using array syntax
  • Example#5350 - Ds\Map::hasKey example
  • Example#5351 - Ds\Map::hasValue example
  • Example#5352 - Ds\Map::intersect example
  • Example#5353 - Ds\Map::isEmpty example
  • Example#5354 - Ds\Map::keys example
  • Example#5355 - Ds\Map::ksort example
  • Example#5356 - Ds\Map::ksort example using a comparator
  • Example#5357 - Ds\Map::ksorted example
  • Example#5358 - Ds\Map::ksorted example using a comparator
  • Example#5359 - Ds\Map::last example
  • Example#5360 - Ds\Map::map example
  • Example#5361 - Ds\Map::merge example
  • Example#5362 - Ds\Map::pairs example
  • Example#5363 - Ds\Map::put example
  • Example#5364 - Ds\Map::put example using objects as keys
  • Example#5365 - Ds\Map::putAll example
  • Example#5366 - Ds\Map::reduce with initial value example
  • Example#5367 - Ds\Map::reduce without an initial value example
  • Example#5368 - Ds\Map::remove example
  • Example#5369 - Ds\Map::reverse example
  • Example#5370 - Ds\Map::reversed example
  • Example#5371 - Ds\Map::skip example
  • Example#5372 - Ds\Map::slice example
  • Example#5373 - Ds\Map::sort example
  • Example#5374 - Ds\Map::sort example using a comparator
  • Example#5375 - Ds\Map::sort example
  • Example#5376 - Ds\Map::sort example using a comparator
  • Example#5377 - Ds\Map::sum integer example
  • Example#5378 - Ds\Map::sum float example
  • Example#5379 - Ds\Map::toArray example
  • Example#5380 - Ds\Map::union example
  • Example#5381 - Ds\Map::values example
  • Example#5382 - Ds\Map::xor example
  • Example#5383 - Ds\Pair::clear example
  • Example#5384 - Ds\Pair::copy example
  • Example#5385 - Ds\Pair::isEmpty example
  • Example#5386 - Ds\Pair::toArray example
  • Example#5387 - Ds\Set::add example using integers
  • Example#5388 - Ds\Set::add example using objects
  • Example#5389 - Ds\Set::allocate example
  • Example#5390 - Ds\Set::capacity example
  • Example#5391 - Ds\Set::clear example
  • Example#5392 - Ds\Set::__construct example
  • Example#5393 - Ds\Set::contains example
  • Example#5394 - Ds\Set::copy example
  • Example#5395 - Ds\Set::diff example
  • Example#5396 - Ds\Set::filter example using callback function
  • Example#5397 - Ds\Set::filter example without a callback function
  • Example#5398 - Ds\Set::first example
  • Example#5399 - Ds\Set::get example
  • Example#5400 - Ds\Set::get example using array syntax
  • Example#5401 - Ds\Set::intersect example
  • Example#5402 - Ds\Set::isEmpty example
  • Example#5403 - Ds\Set::join example using a separator string
  • Example#5404 - Ds\Set::join example without a separator string
  • Example#5405 - Ds\Set::last example
  • Example#5406 - Ds\Set::merge example
  • Example#5407 - Ds\Set::reduce with initial value example
  • Example#5408 - Ds\Set::reduce without an initial value example
  • Example#5409 - Ds\Set::remove example
  • Example#5410 - Ds\Set::reverse example
  • Example#5411 - Ds\Set::reversed example
  • Example#5412 - Ds\Set::slice example
  • Example#5413 - Ds\Set::sort example
  • Example#5414 - Ds\Set::sort example using a comparator
  • Example#5415 - Ds\Set::sorted example
  • Example#5416 - Ds\Set::sorted example using a comparator
  • Example#5417 - Ds\Set::sum integer example
  • Example#5418 - Ds\Set::sum float example
  • Example#5419 - Ds\Set::toArray example
  • Example#5420 - Ds\Set::union example
  • Example#5421 - Ds\Set::xor example
  • Example#5422 - Ds\Stack::clear example
  • Example#5423 - Ds\Stack::__construct example
  • Example#5424 - Ds\Stack::copy example
  • Example#5425 - Ds\Stack::isEmpty example
  • Example#5426 - Ds\Stack::peek example
  • Example#5427 - Ds\Stack::pop example
  • Example#5428 - Ds\Stack::push example
  • Example#5429 - Ds\Stack::toArray example
  • Example#5430 - Ds\Queue::allocate example
  • Example#5431 - Ds\Queue::capacity example
  • Example#5432 - Ds\Queue::clear example
  • Example#5433 - Ds\Queue::__construct example
  • Example#5434 - Ds\Queue::copy example
  • Example#5435 - Ds\Queue::isEmpty example
  • Example#5436 - Ds\Queue::peek example
  • Example#5437 - Ds\Queue::pop example
  • Example#5438 - Ds\Queue::push example
  • Example#5439 - Ds\Queue::toArray example
  • Example#5440 - Ds\PriorityQueue::allocate example
  • Example#5441 - Ds\PriorityQueue::capacity example
  • Example#5442 - Ds\PriorityQueue::clear example
  • Example#5443 - Ds\PriorityQueue::__construct example
  • Example#5444 - Ds\PriorityQueue::copy example
  • Example#5445 - Ds\PriorityQueue::isEmpty example
  • Example#5446 - Ds\PriorityQueue::peek example
  • Example#5447 - Ds\PriorityQueue::pop example
  • Example#5448 - Ds\PriorityQueue::push example
  • Example#5449 - Ds\PriorityQueue::toArray example
  • Example#5450 - Creating a chdb file
  • Example#5451 - Loading and looking up a chdb file
  • Example#5452 - chdb::get example
  • Example#5453 - chdb_create example
  • Example#5454 - Using PHP's cURL module to fetch the example.com homepage
  • Example#5455 - Initializing a new cURL session and fetching a web page
  • Example#5456 - Copying a cURL handle
  • Example#5457 - curl_errno example
  • Example#5458 - curl_error example
  • Example#5459 - curl_escape example
  • Example#5460 - Fetching a web page
  • Example#5461 - curl_getinfo example
  • Example#5462 - curl_getinfo example with opt parameter
  • Example#5463 - Initializing a new cURL session and fetching a web page
  • Example#5464 - curl_multi_add_handle example
  • Example#5465 - curl_multi_close example
  • Example#5466 - curl_multi_exec example
  • Example#5467 - A curl_multi_info_read example
  • Example#5468 - curl_multi_init example
  • Example#5469 - curl_multi_strerror example
  • Example#5470 - curl_reset example
  • Example#5471 - Initializing a new cURL session and fetching a web page
  • Example#5472 - Our own implementation of curl_setopt_array
  • Example#5473 - Initializing a new cURL session and fetching a web page
  • Example#5474 - Uploading file (deprecated as of PHP 5.5.0)
  • Example#5475 - curl_share_setopt example
  • Example#5476 - curl_share_init example
  • Example#5477 - curl_share_setopt example
  • Example#5478 - curl_errno example
  • Example#5479 - curl_escape example
  • Example#5480 - curl_version example
  • Example#5481 - CURLFile::__construct example
  • Example#5482 - Simple HTTP client
  • Example#5483 - HTTP client using asynchronous DNS resolver
  • Example#5484 - Echo server
  • Example#5485 - SSL echo server
  • Example#5486 - Signal handler
  • Example#5487 - Use libevent's loop to process requests of `eio' extension
  • Example#5488 - Miscellaneous
  • Example#5489 - Simple HTTP server
  • Example#5490 - Simple HTTPS server
  • Example#5491 - OpenSSL connection
  • Example#5492 - EventHttpConnection::makeRequest example
  • Example#5493 - Connection listener based on a UNIX domain socket
  • Example#5494 - Simple SMTP server
  • Example#5495 - Handling SIGTERM signal
  • Example#5496 - Event::addSignal example
  • Example#5497 - Event::addTimer example
  • Example#5498 - EventBase::getFeatures example
  • Example#5499 - EventBase::getMethod example
  • Example#5500 - EventBuffer::search example
  • Example#5501 - EventBufferEvent::connect example
  • Example#5502 - Connect to UNIX domain socket which presumably is served by a server, read response from the server and output it to the console
  • Example#5503 - EventBufferEvent::connectHost example
  • Example#5504 - Buffer event's read callback
  • Example#5505 - EventBufferEvent::getOutput example
  • Example#5506 - EventBufferEvent::sslError example
  • Example#5507 - Simple SMTP server
  • Example#5508 - EventConfig::avoidMethod example
  • Example#5509 - EventConfig::__construct example
  • Example#5510 - EventConfig::requireFeatures example
  • Example#5511 - EventHttp::accept example
  • Example#5512 - EventHttp::addServerAlias example
  • Example#5513 - EventHttp::bind example
  • Example#5514 - Simple HTTP server
  • Example#5515 - EventHttp::setCallback example
  • Example#5516 - EventHttp::setDefaultCallback example
  • Example#5517 - EventHttpConnection::makeRequest example
  • Example#5518 - EventHttpConnection::setCloseCallback example
  • Example#5519 - EventHttpRequest::__construct example
  • Example#5520 - EventHttpRequest::sendError example
  • Example#5521 - EventListener::__construct example
  • Example#5522 - EventSslContext::__construct example
  • Example#5523 - FTP example
  • Example#5524 - ftp_alloc example
  • Example#5525 - ftp_cdup example
  • Example#5526 - ftp_chdir example
  • Example#5527 - ftp_chmod example
  • Example#5528 - ftp_close example
  • Example#5529 - ftp_connect example
  • Example#5530 - ftp_delete example
  • Example#5531 - ftp_exec example
  • Example#5532 - ftp_fget example
  • Example#5533 - ftp_fput example
  • Example#5534 - ftp_get_option example
  • Example#5535 - ftp_get example
  • Example#5536 - ftp_login example
  • Example#5537 - ftp_mdtm example
  • Example#5538 - ftp_mkdir example
  • Example#5539 - ftp_mlsd example
  • Example#5540 - ftp_nb_continue example
  • Example#5541 - ftp_nb_fget example
  • Example#5542 - ftp_nb_fput example
  • Example#5543 - ftp_nb_get example
  • Example#5544 - Resuming a download with ftp_nb_get
  • Example#5545 - Resuming a download at position 100 to a new file with ftp_nb_get
  • Example#5546 - ftp_nb_put example
  • Example#5547 - Resuming an upload with ftp_nb_put
  • Example#5548 - ftp_nlist example
  • Example#5549 - ftp_pasv example
  • Example#5550 - ftp_put example
  • Example#5551 - ftp_pwd example
  • Example#5552 - Using ftp_raw to login to an FTP server manually.
  • Example#5553 - ftp_rawlist example
  • Example#5554 - ftp_rename example
  • Example#5555 - ftp_rmdir example
  • Example#5556 - ftp_set_option example
  • Example#5557 - Sending a SITE command to an ftp server
  • Example#5558 - ftp_size example
  • Example#5559 - ftp_ssl_connect example
  • Example#5560 - ftp_systype example
  • Example#5561 - Basic Gearman client and worker
  • Example#5562 - Basic Gearman client and worker, background
  • Example#5563 - Basic Gearman client and worker, submitting tasks
  • Example#5564 - Adding two job servers
  • Example#5565 - Add two job servers
  • Example#5566 - Basic submission of two tasks
  • Example#5567 - Basic submission of two tasks with passing application context
  • Example#5568 - Two tasks, one background and one not
  • Example#5569 - A high priority task along with two normal tasks
  • Example#5570 - A low priority task along with two normal tasks
  • Example#5571 - Monitor completion of multiple background tasks
  • Example#5572 - Simple job submission with immediate return
  • Example#5573 - Submitting a job and retrieving incremental status
  • Example#5574 - Submit and monitor a background job
  • Example#5575 - Simple job submission with immediate return
  • Example#5576 - Submitting a job and retrieving incremental status
  • Example#5577 - Get the status of a long running job
  • Example#5578 - Monitor the status of a long running background job
  • Example#5579 - Simple worker making use of extra application context data
  • Example#5580 - Add alternate Gearman servers
  • Example#5581 - Add two job servers
  • Example#5582 - GearmanWorker::setId example
  • Example#5583 - A simple worker with a 5 second timeout
  • Example#5584 - Running worker in non-blocking mode
  • Example#5585 - GearmanWorker::work example
  • Example#5586 - Hypothetical output from gopher://gopher.example.com/
  • Example#5587 - Using gopher_parsedir
  • Example#5588 - Search for all UPnP devices and services.
  • Example#5589 - Implementing light server
  • Example#5590 - Implementing light client
  • Example#5591 - Create new UPnP context and get IP address of the host
  • Example#5592 - Create new UPnP context and get port number
  • Example#5593 - Create new UPnP context and set host path
  • Example#5594 - Create new UPnP context
  • Example#5595 - Create new UPnP context and set callback
  • Example#5596 - Create new UPnP context and start browsing
  • Example#5597 - Create new UPnP context and start browsing
  • Example#5598 - Create new UPnP context and get device info service
  • Example#5599 - Create new UPnP context and get device info service
  • Example#5600 - Retrieve an object
  • Example#5601 - Testing support for paged result control
  • Example#5602 - LDAP search example
  • Example#5603 - Bind with ppolicy information
  • Example#5604 - Modify description only if it's not empty
  • Example#5605 - Read some values before deletion
  • Example#5606 - Delete a reference
  • Example#5607 - Use pagination for a search
  • Example#5608 - Complete example with authenticated bind
  • Example#5609 - Using LDAP Bind
  • Example#5610 - Using LDAP Bind Anonymously
  • Example#5611 - Complete example of password check
  • Example#5612 - Example of connecting to LDAP server.
  • Example#5613 - Example of connecting securely to LDAP server.
  • Example#5614 - LDAP pagination
  • Example#5615 - LDAP pagination
  • Example#5616 - ldap-count-entries example
  • Example#5617 - Enumerating all LDAP error messages
  • Example#5618 - Generating and catching an error
  • Example#5619 - Searching for an email address
  • Example#5620 - PASSWD extended operation
  • Example#5621 - Whoami extended operation
  • Example#5622 - Show the list of attributes held for a particular directory entry
  • Example#5623 - Check protocol version
  • Example#5624 - List all values of the "mail" attribute for a directory entry
  • Example#5625 - Produce a list of all organizational units of an organization
  • Example#5626 - Add a telephone number to a contact
  • Example#5627 - Rename a user
  • Example#5628 - Add two e-mail addresses to a user
  • Example#5629 - Change a user's password
  • Example#5630 - Change a user's password (Active Directory)
  • Example#5631 - ldap_parse_result example
  • Example#5632 - LDAP search
  • Example#5633 - Set protocol version
  • Example#5634 - Set server controls
  • Example#5635 - LDAP sort
  • Example#5636 - memcache extension overview example
  • Example#5637 - Using memcache session handler
  • Example#5638 - Memcache::add example
  • Example#5639 - Memcache::addServer example
  • Example#5640 - Memcache::close example
  • Example#5641 - Memcache::connect example
  • Example#5642 - Memcache::decrement example
  • Example#5643 - Memcache::delete example
  • Example#5644 - Memcache::flush example
  • Example#5645 - Memcache::get example
  • Example#5646 - Memcache::getExtendedStats example
  • Example#5647 - Memcache::getServerStatus example
  • Example#5648 - Memcache::getVersion example
  • Example#5649 - Memcache::increment example
  • Example#5650 - Memcache::pconnect example
  • Example#5651 - Memcache::replace example
  • Example#5652 - Memcache::set example
  • Example#5653 - Memcache::set example
  • Example#5654 - Memcache::setCompressThreshold example
  • Example#5655 - Memcache::setServerParams example
  • Example#5656 - Result callback example
  • Example#5657 - Read-through callback example
  • Example#5658 - Memcached::addServer example
  • Example#5659 - Memcached::addServers example
  • Example#5660 - Memcached::append example
  • Example#5661 - Memcached::cas example
  • Example#5662 - Creating a Memcached object
  • Example#5663 - Memcached::decrement example
  • Example#5664 - Memcached::delete example
  • Example#5665 - Memcached::fetch example
  • Example#5666 - Memcached::getDelayed example
  • Example#5667 - Memcached::flush example
  • Example#5668 - Memcached::get example #1
  • Example#5669 - Memcached::get example #2
  • Example#5670 - Memcached::getDelayed example
  • Example#5671 - Memcached::getMulti example for Memcached v3
  • Example#5672 - Memcached::getMulti example for Memcached v1 and v2
  • Example#5673 - Memcached::GET_PRESERVE_ORDER example for Memcached v3
  • Example#5674 - Memcached::GET_PRESERVE_ORDER example for Memcached v1 and v2
  • Example#5675 - Retrieving Memcached options
  • Example#5676 - Memcached::getResultCode example
  • Example#5677 - Memcached::getResultMessage example
  • Example#5678 - Memcached::getServerByKey example
  • Example#5679 - Memcached::getServerList example
  • Example#5680 - Memcached::getStats example
  • Example#5681 - Memcached::getVersion example
  • Example#5682 - Memcached::increment example
  • Example#5683 - Memcached::prepend example
  • Example#5684 - Memcached::set example
  • Example#5685 - Memcached::setByKey example
  • Example#5686 - Memcached::setMulti example
  • Example#5687 - Setting a Memcached option
  • Example#5688 - Setting Memcached options
  • Example#5689 - mqseries_back example
  • Example#5690 - mqseries_begin example
  • Example#5691 - mqseries_close example
  • Example#5692 - mqseries_cmit example
  • Example#5693 - mqseries_conn example
  • Example#5694 - mqseries_connx example
  • Example#5695 - mqseries_connx example using SSL connection & OCSP Responder URL
  • Example#5696 - mqseries_disc example
  • Example#5697 - mqseries_get example
  • Example#5698 - mqseries_inq example
  • Example#5699 - mqseries_open example
  • Example#5700 - mqseries_put example
  • Example#5701 - mqseries_strerror example
  • Example#5702 - define_syslog_variables example
  • Example#5703 - Using dns_get_record
  • Example#5704 - Using dns_get_record and DNS_ANY
  • Example#5705 - fsockopen Example
  • Example#5706 - Using UDP connection
  • Example#5707 - A simple gethostbyaddr example
  • Example#5708 - A simple gethostbyname example
  • Example#5709 - gethostbynamel example
  • Example#5710 - A simple gethostname example
  • Example#5711 - getprotobyname example
  • Example#5712 - getservbyname example
  • Example#5713 - header_register_callback example
  • Example#5714 - Unsetting specific header.
  • Example#5715 - Unsetting all previously set headers.
  • Example#5716 - Download dialog
  • Example#5717 - Caching directives
  • Example#5718 - Examples using headers_list
  • Example#5719 - Examples using headers_sent
  • Example#5720 - Using http_response_code in a web server environment
  • Example#5721 - Using http_response_code in a CLI environment
  • Example#5722 - inet_ntop Example
  • Example#5723 - inet_pton Example
  • Example#5724 - ip2long Example
  • Example#5725 - Displaying an IP address
  • Example#5726 - setcookie send example
  • Example#5727 - setcookie delete example
  • Example#5728 - setcookie and arrays
  • Example#5729 - Using syslog
  • Example#5730 - Procedural usage of rrd
  • Example#5731 - OO usage of rrd
  • Example#5732 - RRDGraph::setOptions example
  • Example#5733 - Set multiple color options
  • Example#5734 - RRDUpdater::update examples
  • Example#5735 - Creating a connection and connecting to a remote WebSphere MQSeries Messaging Server
  • Example#5736 - Creating a connection and connecting to a remote WebSphere Application Server
  • Example#5737 - Creating a connection and connecting to an MQTT server
  • Example#5738 - Creating a message with a simple text body
  • Example#5739 - Setting a text format property using the default syntax
  • Example#5740 - Setting a property using a type hint
  • Example#5741 - Retrieving a property from a message header
  • Example#5742 - Adding a message to a queue and receiving a response
  • Example#5743 - Creating a durable subscription to a topic
  • Example#5744 - Subscribing to a topic using a WebSphere Platform Messaging (WPM) server
  • Example#5745 - Receiving published data using a durable subscription
  • Example#5746 - Deleting a durable subscription to a topic
  • Example#5747 - Handling an error from a method that returns no result
  • Example#5748 - Handling an error from a method that returns a result
  • Example#5749 - Committing the current unit of work
  • Example#5750 - Creating a connection to a Messaging Server using the IBM MQSeries protocol (WMQ)
  • Example#5751 - Creating a connection with application transaction control and default host and port values
  • Example#5752 - Creating a connection to a Messaging Server using the IBM WebSphere Platform Messaging protocol (WPM)
  • Example#5753 - Creating a connection object and connecting to a Messaging Server
  • Example#5754 - Disconnecting from a Messaging Server
  • Example#5755 - Using the error number and description properties
  • Example#5756 - Using the error number and description properties
  • Example#5757 - Checking whether there us a connection to a Messaging Server
  • Example#5758 - Retrieve the next message from a queue without removing it
  • Example#5759 - Retrieve a specific message from a queue without removing it from the queue
  • Example#5760 - Retrieve all messages in a queue without removing them
  • Example#5761 - Retrieve all messages from a queue with a matching correlation id
  • Example#5762 - Receiving a message from a queue
  • Example#5763 - Receiving a message from a queue with options
  • Example#5764 - Receiving a message from a subscription
  • Example#5765 - Removing a message from a queue by message id
  • Example#5766 - Cancelling an in-flight unit of work
  • Example#5767 - Send a message to a queue
  • Example#5768 - Publish a message to a topic
  • Example#5769 - Send a request and receive a response
  • Example#5770 - Turn on debugging output
  • Example#5771 - Turn off debugging output
  • Example#5772 - Subscribe to a topic
  • Example#5773 - Delete a subscription
  • Example#5774 - Setting a text string into the body of a message
  • Example#5775 - Creating a message
  • Example#5776 - Creating a message with a simple text payload
  • Example#5777 - Setting a text format property using the default syntax
  • Example#5778 - Setting a text format property using a type hint
  • Example#5779 - Setting properties as the sender of a message
  • Example#5780 - Retreiving property values from a message
  • Example#5781 - Fetch instrumented calls
  • Example#5782 - Fetch the list of functions scoutapm will instrument
  • Example#5783 - snmp_get_quick_print example
  • Example#5784 - Using snmp_get_valueretrieval
  • Example#5785 - Using snmp_read_mib
  • Example#5786 - Using snmp_set_enum_print
  • Example#5787 - Using snmprealwalk
  • Example#5788 - Using snmp_set_quick_print
  • Example#5789 - Using snmp_set_valueretrieval
  • Example#5790 - Using snmp2_get
  • Example#5791 - Using snmp2_get_next
  • Example#5792 - Using snmp2_real_walk
  • Example#5793 - Using snmp2_set
  • Example#5794 - Using snmp2_set for setting BITS SNMP object id
  • Example#5795 - snmp2_walk Example
  • Example#5796 - Using snmp3_get
  • Example#5797 - Using snmp3_getnext
  • Example#5798 - Using snmp3_real_walk
  • Example#5799 - Using snmp3_set
  • Example#5800 - Using snmp3_set for setting BITS SNMP object id
  • Example#5801 - snmp3_walk Example
  • Example#5802 - Using snmpget
  • Example#5803 - Using snmpgetnext
  • Example#5804 - Using snmprealwalk
  • Example#5805 - Using snmpset
  • Example#5806 - Using snmpset for setting BITS SNMP object id
  • Example#5807 - snmpwalk Example
  • Example#5808 - snmpwalkoid Example
  • Example#5809 - SNMP::close example
  • Example#5810 - Fetching sysLocation
  • Example#5811 - Single SNMP object
  • Example#5812 - Multiple SNMP objects
  • Example#5813 - SNMP::getErrno example
  • Example#5814 - SNMP::getError example
  • Example#5815 - Single SNMP object
  • Example#5816 - Miltiple SNMP objects
  • Example#5817 - Set single SNMP object id
  • Example#5818 - Set multiple values using single SNMP::set call
  • Example#5819 - Using SNMP::set for setting BITS SNMP object id
  • Example#5820 - SNMP::setSecurity example
  • Example#5821 - SNMP::walk example
  • Example#5822 - suffix_as_key example
  • Example#5823 - Socket example: Simple TCP/IP server
  • Example#5824 - Socket example: Simple TCP/IP client
  • Example#5825 - Using socket_bind to set the source address
  • Example#5826 - socket_create_pair example
  • Example#5827 - socket_create_pair IPC example
  • Example#5828 - socket_get_option example
  • Example#5829 - socket_import_stream example
  • Example#5830 - socket_last_error example
  • Example#5831 - socket_recv example
  • Example#5832 - socket_recvfrom example
  • Example#5833 - Using NULL with socket_select
  • Example#5834 - Understanding socket_select's result
  • Example#5835 - socket_select example
  • Example#5836 - socket_sendto Example
  • Example#5837 - socket_set_block example
  • Example#5838 - socket_set_nonblock example
  • Example#5839 - socket_set_option example
  • Example#5840 - socket_strerror example
  • Example#5841 - Authenticating with a ssh agent
  • Example#5842 - Authentication using a public hostkey
  • Example#5843 - Retrieving a list of authentication methods
  • Example#5844 - Authenticating with a password
  • Example#5845 - Authentication using a public key
  • Example#5846 - ssh2_connect example
  • Example#5847 - Executing a command
  • Example#5848 - Opening a shell and retrieving the stderr stream associated with it
  • Example#5849 - Checking the fingerprint against a known value
  • Example#5850 - Determining what methods were negotiated
  • Example#5851 - Adding a publickey with ssh2_publickey_add
  • Example#5852 - Listing authorized keys with ssh2_publickey_list
  • Example#5853 - Downloading a file via SCP
  • Example#5854 - Uploading a file via SCP
  • Example#5855 - Changing the mode of a file on a remote server
  • Example#5856 - Stating a symbolic link via SFTP
  • Example#5857 - Creating a directory on a remote server
  • Example#5858 - Reading a symbolic link
  • Example#5859 - Resolving a pathname
  • Example#5860 - Renaming a file via sftp
  • Example#5861 - Removing a directory on a remote server
  • Example#5862 - Stating a file via SFTP
  • Example#5863 - Creating a symbolic link
  • Example#5864 - Deleting a file
  • Example#5865 - Opening a file via SFTP
  • Example#5866 - Requesting an interactive shell
  • Example#5867 - Opening a tunnel to an arbitrary host
  • Example#5868 - Object oriented style
  • Example#5869 - Procedural style
  • Example#5870 - stomp_connect_error example
  • Example#5871 - stomp_version example
  • Example#5872 - Object oriented style
  • Example#5873 - Procedural style
  • Example#5874 - Object oriented style
  • Example#5875 - Procedural style
  • Example#5876 - Object oriented style
  • Example#5877 - Procedural style
  • Example#5878 - Object oriented style
  • Example#5879 - Procedural style
  • Example#5880 - Object oriented style
  • Example#5881 - Procedural style
  • Example#5882 - Object oriented style
  • Example#5883 - Procedural style
  • Example#5884 - Object oriented style
  • Example#5885 - Procedural style
  • Example#5886 - Object oriented style
  • Example#5887 - Procedural style
  • Example#5888 - Object oriented style
  • Example#5889 - Procedural style
  • Example#5890 - Train from array
  • Example#5891 - Train from a file
  • Example#5892 - svn_add example
  • Example#5893 - Default authentication example
  • Example#5894 - svn_blame example
  • Example#5895 - Basic example
  • Example#5896 - Basic example
  • Example#5897 - Basic example
  • Example#5898 - Basic example
  • Example#5899 - Basic example
  • Example#5900 - Basic example
  • Example#5901 - Diffing two revisions of a repository path
  • Example#5902 - Portably diffing two local files
  • Example#5903 - svn_export example
  • Example#5904 - Basic example
  • Example#5905 - svn_log example
  • Example#5906 - svn_ls example
  • Example#5907 - Basic example
  • Example#5908 - Basic example
  • Example#5909 - Deny all connections from localhost
  • Example#5910 - Ban an URL
  • Example#5911 - Get statistic snapshot
  • Example#5912 - Read varnish shared memory log
  • Example#5913 - VarnishAdmin::__construct example
  • Example#5914 - Parallel searching using Yaz
  • Example#5915 - CCL configuration
  • Example#5916 - CCL Parsing
  • Example#5917 - Record Update
  • Example#5918 - Array for GRS-1 record
  • Example#5919 - Working with MARCXML
  • Example#5920 - PHP function that scans titles
  • Example#5921 - Query Examples
  • Example#5922 - Sort Criterias
  • Example#5923 - Example for NIS errors
  • Example#5924 - Example for the NIS first
  • Example#5925 - Example for the default domain
  • Example#5926 - Example for the NIS master
  • Example#5927 - Example for NIS match
  • Example#5928 - Example for NIS next
  • Example#5929 - Example for the NIS order
  • Example#5930 - A ZMQContext example
  • Example#5931 - A ZMQContext example
  • Example#5932 - A ZMQContext example
  • Example#5933 - A ZMQSocket example
  • Example#5934 - A send/recv example
  • Example#5935 - A ZMQPoll example
  • Example#5936 - zookeeper_dispatch example #1
  • Example#5937 - zookeeper_dispatch example #2
  • Example#5938 - Zookeeper::addAuth example
  • Example#5939 - Zookeeper::create example
  • Example#5940 - Zookeeper::delete example
  • Example#5941 - Zookeeper::exists example
  • Example#5942 - Zookeeper::get example
  • Example#5943 - Zookeeper::get stat example
  • Example#5944 - Zookeeper::getAcl example
  • Example#5945 - Zookeeper::getChildren example
  • Example#5946 - Zookeeper::set example
  • Example#5947 - Zookeeper::setAcl example
  • Example#5948 - Zookeeper::setDebugLevel example
  • Example#5949 - ZookeeperConfig::add example
  • Example#5950 - ZookeeperConfig::get example
  • Example#5951 - ZookeeperConfig::remove example
  • Example#5952 - ZookeeperConfig::set example
  • Example#5953 -
  • Example#5954 - udm_api_version example
  • Example#5955 - udm_cat_listexample
  • Example#5956 - Specifying path to the current category in the following format: '> Root > Sport > Auto > Ferrari'
  • Example#5957 - udm_load_ispell_data example
  • Example#5958 - udm_load_ispell_data example
  • Example#5959 - solr_get_version example
  • Example#5960 - Contents of the BootStrap file
  • Example#5961 - Adding a document to the index
  • Example#5962 - Merging one document into another document
  • Example#5963 - Searching for documents - SolrObject responses
  • Example#5964 - Searching for documents - SolrDocument responses
  • Example#5965 - Simple TermsComponent example - basic
  • Example#5966 - Simple TermsComponent example - using a prefix
  • Example#5967 - Simple TermsComponent example - specifying a minimum frequency
  • Example#5968 - Simple Facet Example
  • Example#5969 - Simple Facet Example - with optional field override for mincount
  • Example#5970 - Facet Date Example
  • Example#5971 - Connecting to SSL-Enabled Server
  • Example#5972 - Collapsing a SolrQuery
  • Example#5973 - Solr Real Time Get (RTG) example SolrClient::getById
  • Example#5974 - SolrInputDocument::addChildDocument example
  • Example#5975 - SolrInputDocument::addChildDocuments example
  • Example#5976 - SolrDocument::toArray example
  • Example#5977 - SolrObject::__construct example
  • Example#5978 - SolrObject::offsetUnset example
  • Example#5979 - SolrClient::addDocument example
  • Example#5980 - SolrClient::addDocument example 2
  • Example#5981 - SolrClient::addDocuments example
  • Example#5982 - SolrClient::__construct example
  • Example#5983 - SolrQuery::deleteByQuery example
  • Example#5984 - SolrClient::getById example
  • Example#5985 - SolrClient::getByIds example
  • Example#5986 - SolrClient::ping example
  • Example#5987 - SolrClient::query example
  • Example#5988 - SolrClient::request example
  • Example#5989 - SolrClient::setResponseWriter example
  • Example#5990 - SolrParams::setParam example
  • Example#5991 - SolrQuery::addFacetField example
  • Example#5992 - SolrQuery::addFacetField example
  • Example#5993 - SolrQuery::addFilterQuery example
  • Example#5994 - SolrQuery::addGroupSortField example
  • Example#5995 - SolrQuery::collapse example
  • Example#5996 - SolrQuery::setExpand example
  • Example#5997 - SolrDisMaxQuery::addBigramPhraseField example
  • Example#5998 - SolrDisMaxQuery::addBoostQuery example
  • Example#5999 - SolrDisMaxQuery::addPhraseField example
  • Example#6000 - SolrDisMaxQuery::addQueryField example
  • Example#6001 - SolrDisMaxQuery::addTrigramPhraseField example
  • Example#6002 - SolrDisMaxQuery::addUserField example
  • Example#6003 - SolrDisMaxQuery::__construct example
  • Example#6004 - SolrDisMaxQuery::removeBigramPhraseField example
  • Example#6005 - SolrDisMaxQuery::removeBoostQuery example
  • Example#6006 - SolrDisMaxQuery::removePhraseField example
  • Example#6007 - SolrDisMaxQuery::removeQueryField example
  • Example#6008 - SolrDisMaxQuery::removeTrigramPhraseField example
  • Example#6009 - SolrDisMaxQuery::removeUserField example
  • Example#6010 - SolrDisMaxQuery::setBigramPhraseFields example
  • Example#6011 - SolrDisMaxQuery::setBigramPhraseSlop example
  • Example#6012 - SolrDisMaxQuery::setBoostFunction example
  • Example#6013 - SolrDisMaxQuery::setBoostQuery example
  • Example#6014 - SolrDisMaxQuery::setMinimumMatch example
  • Example#6015 - SolrDisMaxQuery::setPhraseFields example
  • Example#6016 - SolrDisMaxQuery::setPhraseSlop example
  • Example#6017 - SolrDisMaxQuery::setQueryAlt example
  • Example#6018 - SolrDisMaxQuery::setQueryPhraseSlop example
  • Example#6019 - SolrDisMaxQuery::setTieBreaker example
  • Example#6020 - SolrDisMaxQuery::setTrigramPhraseFields example
  • Example#6021 - SolrDisMaxQuery::setTrigramPhraseSlop example
  • Example#6022 - SolrDisMaxQuery::setUserFields example
  • Example#6023 - SolrDisMaxQuery::useDisMaxQueryParser example
  • Example#6024 - SolrDisMaxQuery::useEDisMaxQueryParser example
  • Example#6025 - SolrCollapseFunction::__construct example
  • Example#6026 - SolrCollapseFunction::setHint example
  • Example#6027 - SolrCollapseFunction::setMax example
  • Example#6028 - Basic usage example
  • Example#6029 - Basic search query
  • Example#6030 - A Swish::__construct example
  • Example#6031 - Basic Swish::getMetaList example
  • Example#6032 - Basic Swish::getPropertyList example
  • Example#6033 - Basic Swish::prepare example
  • Example#6034 - Basic Swish::query example
  • Example#6035 - Basic SwishResult::stem example
  • Example#6036 - Basic SwishResults::getParsedWords example
  • Example#6037 - Basic SwishResults::nextResult example
  • Example#6038 - Basic SwishResults::seekResult example
  • Example#6039 - Basic SwishSearch::execute example
  • Example#6040 - Basic SwishSearch::resetLimit example
  • Example#6041 - Basic SwishSearch::setLimit example
  • Example#6042 - Basic SwishSearch::setPhraseDelimiter example
  • Example#6043 - Basic SwishSearch::setSort example
  • Example#6044 - Basic SwishSearch::setStructure example
  • Example#6045 - Turning off PHP parsing for a directory using .htaccess
  • Example#6046 - apache_get_modules example
  • Example#6047 - apache_get_version example
  • Example#6048 - apache_getenv example
  • Example#6049 - apache_lookup_uri example
  • Example#6050 - Passing information between PHP and Perl
  • Example#6051 - Logging values in access.log
  • Example#6052 - apache_request_headers example
  • Example#6053 - apache_response_headers example
  • Example#6054 - Setting an Apache environment variable using apache_setenv
  • Example#6055 - getallheaders example
  • Example#6056 - nsapi_request_headers example
  • Example#6057 - Registering a variable with $_SESSION.
  • Example#6058 - Unregistering a variable with $_SESSION.
  • Example#6059 - Counting the number of hits of a single user
  • Example#6060 - Example information
  • Example#6061 - session_cache_expire example
  • Example#6062 - session_cache_limiter example
  • Example#6063 - session_create_id example with session_regenerate_id
  • Example#6064 - Destroying a session with $_SESSION
  • Example#6065 - session_gc example for task managers like cron
  • Example#6066 - session_gc example for user accessible script
  • Example#6067 - session_name example
  • Example#6068 - A session_regenerate_id example
  • Example#6069 - Avoiding lost session by session_regenerate_id
  • Example#6070 - Custom session handler: see full code in SessionHandlerInterface synopsis.
  • Example#6071 - Custom session save handler using objects
  • Example#6072 - page1.php
  • Example#6073 - page2.php
  • Example#6074 - Overriding the cookie lifetime
  • Example#6075 - Reading the session and closing it
  • Example#6076 - Using SessionHandler to add encryption to internal PHP save handlers.
  • Example#6077 - Example using SessionHandlerInterface
  • Example#6078 - bbcode_add_smiley usage example
  • Example#6079 - bbcode_create example
  • Example#6080 - bbcode_set_arg_parser usage example
  • Example#6081 - bbcode_set_flags usage example
  • Example#6082 - Tokenize comma separated integer list
  • Example#6083 - Tokenize assign statement
  • Example#6084 - Simple calculator
  • Example#6085 - Parse words out from a sentence
  • Example#6086 - Examples of valid patterns
  • Example#6087 - Examples of invalid patterns
  • Example#6088 - Example comparing preg_filter with preg_replace
  • Example#6089 - preg_grep example
  • Example#6090 - preg_last_error example
  • Example#6091 - Getting all phone numbers out of some text.
  • Example#6092 - Find matching HTML tags (greedy)
  • Example#6093 - Using named subpattern
  • Example#6094 - Find the string of text "php"
  • Example#6095 - Find the word "web"
  • Example#6096 - Getting the domain name out of a URL
  • Example#6097 - Using named subpattern
  • Example#6098 - preg_quote example
  • Example#6099 - Italicizing a word within some text
  • Example#6100 - preg_replace_callback_array example
  • Example#6101 - preg_replace_callback and anonymous function
  • Example#6102 - preg_replace_callback example
  • Example#6103 - preg_replace_callback using recursive structure to handle encapsulated BB code
  • Example#6104 - Using backreferences followed by numeric literals
  • Example#6105 - Using indexed arrays with preg_replace
  • Example#6106 - Replacing several values
  • Example#6107 - Strip whitespace
  • Example#6108 - Using the count parameter
  • Example#6109 - preg_split example : Get the parts of a search string
  • Example#6110 - Splitting a string into component characters
  • Example#6111 - Splitting a string into matches and their offsets
  • Example#6112 - Regular Expression Examples
  • Example#6113 - ereg_replace example
  • Example#6114 - ereg_replace example
  • Example#6115 - Replace URLs with links
  • Example#6116 - ereg example
  • Example#6117 - Highlight search results
  • Example#6118 - eregi example
  • Example#6119 - split example
  • Example#6120 - split example
  • Example#6121 - spliti example
  • Example#6122 - sql_regcase example
  • Example#6123 - addcslashes example
  • Example#6124 - An addslashes example
  • Example#6125 - chr example
  • Example#6126 - Overflow behavior
  • Example#6127 - Building a UTF-8 string from individual bytes
  • Example#6128 - chunk_split example
  • Example#6129 - convert_uudecode example
  • Example#6130 - convert_uuencode example
  • Example#6131 - count_chars example
  • Example#6132 - Displaying a crc32 checksum
  • Example#6133 - crypt examples
  • Example#6134 - Using crypt with htpasswd
  • Example#6135 - Using crypt with different hash types
  • Example#6136 - echo examples
  • Example#6137 - explode examples
  • Example#6138 - explode return examples
  • Example#6139 - limit parameter examples
  • Example#6140 - fprintf: zero-padded integers
  • Example#6141 - fprintf: formatting currency
  • Example#6142 - Translation Table Example
  • Example#6143 - hex2bin example
  • Example#6144 - Decoding HTML entities
  • Example#6145 - A htmlentities example
  • Example#6146 - Usage of ENT_IGNORE
  • Example#6147 - A htmlspecialchars_decode example
  • Example#6148 - htmlspecialchars example
  • Example#6149 - implode example
  • Example#6150 - lcfirst example
  • Example#6151 - levenshtein example
  • Example#6152 - localeconv example
  • Example#6153 - Usage example of ltrim
  • Example#6154 - Usage example of md5_file
  • Example#6155 - A md5 example
  • Example#6156 - metaphone basic example
  • Example#6157 - Using the phonemes parameter
  • Example#6158 - money_format Example
  • Example#6159 - Using nl2br
  • Example#6160 - Generating valid HTML markup using the is_xhtml parameter
  • Example#6161 - Various newline separators
  • Example#6162 - number_format Example
  • Example#6163 - ord example
  • Example#6164 - Examining the individual bytes of a UTF-8 string
  • Example#6165 - Using parse_str
  • Example#6166 - parse_str name mangling
  • Example#6167 - print examples
  • Example#6168 - printf: various examples
  • Example#6169 - printf: string specifiers
  • Example#6170 - Usage example of rtrim
  • Example#6171 - setlocale Examples
  • Example#6172 - setlocale Examples for Windows
  • Example#6173 - sha1_file example
  • Example#6174 - A sha1 example
  • Example#6175 - similar_text argument swapping example
  • Example#6176 - Soundex Examples
  • Example#6177 - Argument swapping
  • Example#6178 - Specifying padding character
  • Example#6179 - Position specifier with other specifiers
  • Example#6180 - sprintf: zero-padded integers
  • Example#6181 - sprintf: formatting currency
  • Example#6182 - sprintf: scientific notation
  • Example#6183 - sscanf Example
  • Example#6184 - sscanf - using optional parameters
  • Example#6185 - str_ireplace example
  • Example#6186 - str_pad example
  • Example#6187 - str_repeat example
  • Example#6188 - Basic str_replace examples
  • Example#6189 - Examples of potential str_replace gotchas
  • Example#6190 - str_rot13 example
  • Example#6191 - str_shuffle example
  • Example#6192 - Example uses of str_split
  • Example#6193 - A str_word_count example
  • Example#6194 - strcasecmp example
  • Example#6195 - strcmp example
  • Example#6196 - strcspn example
  • Example#6197 - strip_tags example
  • Example#6198 - stripos examples
  • Example#6199 - A stripslashes example
  • Example#6200 - Using stripslashes on an array
  • Example#6201 - stristr example
  • Example#6202 - Testing if a string is found or not
  • Example#6203 - Using a non "string" needle
  • Example#6204 - A strlen example
  • Example#6205 - strpbrk example
  • Example#6206 - Using ===
  • Example#6207 - Using !==
  • Example#6208 - Using an offset
  • Example#6209 - strrchr example
  • Example#6210 - Reversing a string with strrev
  • Example#6211 - A simple strripos example
  • Example#6212 - Checking if a needle is in the haystack
  • Example#6213 - Searching with offsets
  • Example#6214 - strspn example
  • Example#6215 - strstr example
  • Example#6216 - strtok example
  • Example#6217 - strtok behavior on empty part found
  • Example#6218 - strtolower example
  • Example#6219 - strtoupper example
  • Example#6220 - strtr example
  • Example#6221 - strtr example with two arguments
  • Example#6222 - strtr behavior comparison
  • Example#6223 - A substr_compare example
  • Example#6224 - A substr_count example
  • Example#6225 - Simple substr_replace examples
  • Example#6226 - Using substr_replace to replace multiple strings at once
  • Example#6227 - Using a negative start
  • Example#6228 - Using a negative length
  • Example#6229 - Basic substr usage
  • Example#6230 - substr casting behaviour
  • Example#6231 -
  • Example#6232 - Usage example of trim
  • Example#6233 - Trimming array values with trim
  • Example#6234 - ucfirst example
  • Example#6235 - ucwords example
  • Example#6236 - ucwords example with custom delimiter
  • Example#6237 - vfprintf: zero-padded integers
  • Example#6238 - vprintf: zero-padded integers
  • Example#6239 - vsprintf: zero-padded integers
  • Example#6240 - wordwrap example
  • Example#6241 - wordwrap example
  • Example#6242 - wordwrap example
  • Example#6243 - array_change_key_case example
  • Example#6244 - array_chunk example
  • Example#6245 - Get the column of first names from a recordset
  • Example#6246 - Get the column of last names from a recordset, indexed by the "id" column
  • Example#6247 - Get the column of usernames from the public "username" property of an object
  • Example#6248 - Get the column of names from the private "name" property of an object using the magic __get method.
  • Example#6249 - A simple array_combine example
  • Example#6250 - array_count_values example
  • Example#6251 - array_diff_assoc example
  • Example#6252 - array_diff_assoc example
  • Example#6253 - array_diff_key example
  • Example#6254 - array_diff_uassoc example
  • Example#6255 - array_diff_ukey example
  • Example#6256 - array_diff example
  • Example#6257 - array_fill_keys example
  • Example#6258 - array_fill example
  • Example#6259 - array_filter example
  • Example#6260 - array_filter without callback
  • Example#6261 - array_filter with flag
  • Example#6262 - array_flip example
  • Example#6263 - array_flip example : collision
  • Example#6264 - array_intersect_assoc example
  • Example#6265 - array_intersect_key example
  • Example#6266 - array_intersect_uassoc example
  • Example#6267 - array_intersect_ukey example
  • Example#6268 - array_intersect example
  • Example#6269 - array_key_exists example
  • Example#6270 - array_key_exists vs isset
  • Example#6271 - Basic array_key_first Usage
  • Example#6272 - array_keys example
  • Example#6273 - array_map example
  • Example#6274 - array_map using a lambda function (as of PHP 5.3.0)
  • Example#6275 - array_map - using more arrays
  • Example#6276 - Performing a zip operation of arrays
  • Example#6277 - NULL callback with only array1
  • Example#6278 - array_map - with string keys
  • Example#6279 - array_merge_recursive example
  • Example#6280 - array_merge example
  • Example#6281 - Simple array_merge example
  • Example#6282 - array_merge with non-array types
  • Example#6283 - Sorting multiple arrays
  • Example#6284 - Sorting multi-dimensional array
  • Example#6285 - Sorting database results
  • Example#6286 - Case insensitive sorting
  • Example#6287 - array_pad example
  • Example#6288 - array_pop example
  • Example#6289 - array_product examples
  • Example#6290 - array_push example
  • Example#6291 - array_rand example
  • Example#6292 - array_reduce example
  • Example#6293 - array_replace_recursive example
  • Example#6294 - array_replace_recursive and recursive behavior
  • Example#6295 - array_replace example
  • Example#6296 - array_reverse example
  • Example#6297 - array_search example
  • Example#6298 - array_shift example
  • Example#6299 - array_slice examples
  • Example#6300 - array_slice and one-based array
  • Example#6301 - array_slice and array with mixed keys
  • Example#6302 - array_splice examples
  • Example#6303 - Equivalent statements to various array_splice examples
  • Example#6304 - array_sum examples
  • Example#6305 - array_udiff_assoc example
  • Example#6306 - array_udiff_uassoc example
  • Example#6307 - array_udiff example using stdClass Objects
  • Example#6308 - array_udiff example using DateTime Objects
  • Example#6309 - array_uintersect_assoc example
  • Example#6310 - array_uintersect_uassoc example
  • Example#6311 - array_uintersect example
  • Example#6312 - array_unique example
  • Example#6313 - array_unique and types
  • Example#6314 - array_unshift example
  • Example#6315 - array_values example
  • Example#6316 - array_walk_recursive example
  • Example#6317 - array_walk example
  • Example#6318 - array example
  • Example#6319 - Automatic index with array
  • Example#6320 - 1-based index with array
  • Example#6321 - Accessing an array inside double quotes
  • Example#6322 - arsort example
  • Example#6323 - asort example
  • Example#6324 - compact example
  • Example#6325 - count example
  • Example#6326 - Recursive count example
  • Example#6327 - Example use of current and friends
  • Example#6328 - each examples
  • Example#6329 - Traversing an array with each
  • Example#6330 - end example
  • Example#6331 - extract example
  • Example#6332 - in_array example
  • Example#6333 - in_array with strict example
  • Example#6334 - in_array with an array as needle
  • Example#6335 - key example
  • Example#6336 - krsort example
  • Example#6337 - ksort example
  • Example#6338 - list examples
  • Example#6339 - An example use of list
  • Example#6340 - Using nested list
  • Example#6341 - Using list with array indices
  • Example#6342 - list and order of index definitions
  • Example#6343 - list with keys
  • Example#6344 - natcasesort example
  • Example#6345 - natsort examples demonstrating basic usage
  • Example#6346 - natsort examples demonstrating potential gotchas
  • Example#6347 - Example use of next and friends
  • Example#6348 - Example use of prev and friends
  • Example#6349 - range examples
  • Example#6350 - reset example
  • Example#6351 - rsort example
  • Example#6352 - shuffle example
  • Example#6353 - sort example
  • Example#6354 - sort example using case-insensitive natural ordering
  • Example#6355 - Basic uasort example
  • Example#6356 - uksort example
  • Example#6357 - usort example
  • Example#6358 - usort example using multi-dimensional array
  • Example#6359 - usort example using a member function of an object
  • Example#6360 - usort example using a closure to sort a multi-dimensional array
  • Example#6361 - classes.inc
  • Example#6362 - test_script.php
  • Example#6363 - call_user_method_array alternative
  • Example#6364 - call_user_method alternative
  • Example#6365 - class_alias example
  • Example#6366 - class_exists example
  • Example#6367 - autoload parameter example
  • Example#6368 - Using get_called_class
  • Example#6369 - get_class_methods example
  • Example#6370 - get_class_vars example
  • Example#6371 - get_class_vars and scoping behaviour
  • Example#6372 - Using get_class
  • Example#6373 - Using get_class in superclass
  • Example#6374 - Using get_class with namespaced classes
  • Example#6375 - get_declared_classes example
  • Example#6376 - get_declared_interfaces example
  • Example#6377 - Use of get_object_vars
  • Example#6378 - Using get_parent_class
  • Example#6379 - interface_exists example
  • Example#6380 - is_a example
  • Example#6381 - Using the instanceof operator in PHP 5
  • Example#6382 - is_subclass_of example
  • Example#6383 - is_subclass_of using interface example
  • Example#6384 - method_exists example
  • Example#6385 - Static method_exists example
  • Example#6386 - A property_exists example
  • Example#6387 - classkit_import example
  • Example#6388 - classkit_method_add example
  • Example#6389 - classkit_method_copy example
  • Example#6390 - classkit_method_redefine example
  • Example#6391 - classkit_method_remove example
  • Example#6392 - classkit_method_rename example
  • Example#6393 - A ctype_alnum example (using the default locale)
  • Example#6394 - A ctype_alpha example (using the default locale)
  • Example#6395 - A ctype_cntrl example
  • Example#6396 - A ctype_digit example
  • Example#6397 - A ctype_digit example comparing strings with integers
  • Example#6398 - A ctype_graph example
  • Example#6399 - A ctype_lower example (using the default locale)
  • Example#6400 - A ctype_print example
  • Example#6401 - A ctype_punct example
  • Example#6402 - A ctype_space example
  • Example#6403 - A ctype_upper example (using the default locale)
  • Example#6404 - A ctype_xdigit example
  • Example#6405 - Configuring the default filter to act like htmlspecialchars
  • Example#6406 - Configuring the default filter to act like htmlspecialchars
  • Example#6407 - Validating email addresses with filter_var
  • Example#6408 - Validating IP addresses with filter_var
  • Example#6409 - Passing options to filter_var
  • Example#6410 - Sanitizing and validating email addresses
  • Example#6411 - Configuring a default filter
  • Example#6412 - A filter_input_array example
  • Example#6413 - A filter_input example
  • Example#6414 - A filter_list example
  • Example#6415 - A filter_var_array example
  • Example#6416 - A filter_var example
  • Example#6417 - call_user_func_array example
  • Example#6418 - call_user_func_array using namespace name
  • Example#6419 - Using lambda function
  • Example#6420 - Passing values by reference
  • Example#6421 - call_user_func example and references
  • Example#6422 - call_user_func example
  • Example#6423 - call_user_func using namespace name
  • Example#6424 - Using a class method with call_user_func
  • Example#6425 - Using lambda function with call_user_func
  • Example#6426 - Creating an anonymous function with create_function
  • Example#6427 - Making a general processing function with create_function
  • Example#6428 - Using anonymous functions as callback functions
  • Example#6429 - forward_static_call_array example
  • Example#6430 - forward_static_call example
  • Example#6431 - func_get_arg example
  • Example#6432 - func_get_arg example before and after PHP 5.3
  • Example#6433 - func_get_arg example of byref and byval arguments
  • Example#6434 - func_get_args example
  • Example#6435 - func_get_args example before and after PHP 5.3
  • Example#6436 - func_get_args example of byref and byval arguments
  • Example#6437 - func_num_args example
  • Example#6438 - func_num_args example before and after PHP 5.3
  • Example#6439 - function_exists example
  • Example#6440 - get_defined_functions example
  • Example#6441 - register_shutdown_function example
  • Example#6442 - register_tick_function example
  • Example#6443 - Quickhash Example
  • Example#6444 - Quickhash ArrayAccess Example
  • Example#6445 - Quickhash Iterator Example
  • Example#6446 - Quickhash String Values Example
  • Example#6447 - QuickHashIntSet::add example
  • Example#6448 - QuickHashIntSet::__construct example
  • Example#6449 - QuickHashIntSet::delete example
  • Example#6450 - QuickHashIntSet::exists example
  • Example#6451 - QuickHashIntSet::getSize example
  • Example#6452 - QuickHashIntSet::loadFromFile example
  • Example#6453 - QuickHashIntSet::loadFromString example
  • Example#6454 - QuickHashIntSet::saveToFile example
  • Example#6455 - QuickHashIntSet::saveToString example
  • Example#6456 - QuickHashIntHash::add example
  • Example#6457 - QuickHashIntHash::__construct example
  • Example#6458 - QuickHashIntHash::delete example
  • Example#6459 - QuickHashIntHash::exists example
  • Example#6460 - QuickHashIntHash::get example
  • Example#6461 - QuickHashIntHash::getSize example
  • Example#6462 - QuickHash IntHash file format
  • Example#6463 - QuickHash IntHash file format
  • Example#6464 - QuickHashIntHash::loadFromFile example
  • Example#6465 - QuickHashIntHash::loadFromString example
  • Example#6466 - QuickHashIntHash::saveToFile example
  • Example#6467 - QuickHashIntHash::saveToString example
  • Example#6468 - QuickHashIntHash::set example
  • Example#6469 - QuickHashIntHash::update example
  • Example#6470 - QuickHashStringIntHash::add example
  • Example#6471 - QuickHashStringIntHash::__construct example
  • Example#6472 - QuickHashStringIntHash::delete example
  • Example#6473 - QuickHashStringIntHash::get example
  • Example#6474 - QuickHashStringIntHash::getSize example
  • Example#6475 - QuickHash StringIntHash file format
  • Example#6476 - QuickHash IntHash file format
  • Example#6477 - QuickHashStringIntHash::loadFromFile example
  • Example#6478 - QuickHashStringIntHash::loadFromString example
  • Example#6479 - QuickHashStringIntHash::saveToFile example
  • Example#6480 - QuickHashStringIntHash::saveToString example
  • Example#6481 - QuickHashStringIntHash::set example
  • Example#6482 - QuickHashStringIntHash::update example
  • Example#6483 - QuickHashIntStringHash::add example
  • Example#6484 - QuickHashIntStringHash::__construct example
  • Example#6485 - QuickHashIntStringHash::delete example
  • Example#6486 - QuickHashIntStringHash::get example
  • Example#6487 - QuickHashIntStringHash::getSize example
  • Example#6488 - QuickHash IntString file format
  • Example#6489 - QuickHash IntString file format
  • Example#6490 - QuickHashIntStringHash::loadFromFile example
  • Example#6491 - QuickHashIntStringHash::loadFromString example
  • Example#6492 - QuickHashIntStringHash::saveToFile example
  • Example#6493 - QuickHashIntStringHash::saveToString example
  • Example#6494 - QuickHashIntStringHash::set example
  • Example#6495 - QuickHashIntStringHash::update example
  • Example#6496 - Reflection Example from Shell (a Terminal)
  • Example#6497 - Extending the built-in classes
  • Example#6498 - Reflection::getModifierNames example
  • Example#6499 - Basic usage ReflectionClass
  • Example#6500 - Basic usage of ReflectionClass::export
  • Example#6501 - Usage of ReflectionClass::getConstant
  • Example#6502 - Basic usage of ReflectionClass::getConstructor
  • Example#6503 - ReflectionClass::getDefaultProperties example
  • Example#6504 - ReflectionClass::getDocComment example
  • Example#6505 - ReflectionClass::getEndLine example
  • Example#6506 - Basic usage of ReflectionClass::getExtension
  • Example#6507 - Basic usage of ReflectionClass::getExtensionName
  • Example#6508 - ReflectionClass::getInterfaceNames example
  • Example#6509 - ReflectionClass::getInterfaces example
  • Example#6510 - Basic usage of ReflectionClass::getMethod
  • Example#6511 - Basic usage of ReflectionClass::getMethods
  • Example#6512 - Filtering results from ReflectionClass::getMethods
  • Example#6513 - ReflectionClass::getName example
  • Example#6514 - ReflectionClass::getNamespaceName example
  • Example#6515 - ReflectionClass::getProperties filtering example
  • Example#6516 - Basic usage of ReflectionClass::getProperty
  • Example#6517 - Basic ReflectionClass::getReflectionConstants example
  • Example#6518 - ReflectionClass::getShortName example
  • Example#6519 - Basic usage of ReflectionClass::getStaticPropertyValue
  • Example#6520 - ReflectionClass::hasConstant example
  • Example#6521 - ReflectionClass::hasMethod example
  • Example#6522 - ReflectionClass::hasProperty example
  • Example#6523 - ReflectionClass::inNamespace example
  • Example#6524 - ReflectionClass::isAbstract example
  • Example#6525 - ReflectionClass::isAnonymous example
  • Example#6526 - Basic usage of ReflectionClass::isCloneable
  • Example#6527 - ReflectionClass::isFinal example
  • Example#6528 - ReflectionClass::isInstance related examples
  • Example#6529 - ReflectionClass::isInstantiable example
  • Example#6530 - Basic usage of ReflectionClass::isInterface
  • Example#6531 - Basic usage of ReflectionClass::isInternal
  • Example#6532 - Basic ReflectionClass::isIterable Usage
  • Example#6533 - Basic usage of ReflectionClass::newInstanceArgs
  • Example#6534 - ReflectionClass::__toString example
  • Example#6535 - ReflectionExtension example
  • Example#6536 - ReflectionExtension::getClasses example
  • Example#6537 - ReflectionExtension::getClassNames example
  • Example#6538 - ReflectionExtension::getConstants example
  • Example#6539 - ReflectionExtension::getDependencies example
  • Example#6540 - ReflectionExtension::getFunctions example
  • Example#6541 - ReflectionExtension::getINIEntries example
  • Example#6542 - ReflectionExtension::getName example
  • Example#6543 - ReflectionExtension::getVersion example
  • Example#6544 - ReflectionExtension::info example
  • Example#6545 - ReflectionFunction::__construct example
  • Example#6546 - ReflectionFunction::invoke example
  • Example#6547 - ReflectionFunction::invokeArgs example
  • Example#6548 - ReflectionFunction::invokeArgs with references example
  • Example#6549 - ReflectionFunction::__toString example
  • Example#6550 - ReflectionFunctionAbstract::getReturnType example
  • Example#6551 - Usage on built-in functions
  • Example#6552 - ReflectionFunctionAbstract::hasReturnType example
  • Example#6553 - Usage on built-in functions
  • Example#6554 - ReflectionFunctionAbstract::isClosure example
  • Example#6555 - ReflectionFunctionAbstract::isDeprecated example
  • Example#6556 - ReflectionMethod::__construct example
  • Example#6557 - ReflectionMethod::getDeclaringClass example
  • Example#6558 - ReflectionMethod::getModifiers example
  • Example#6559 - ReflectionMethod::getPrototype example
  • Example#6560 - ReflectionMethod::invoke example
  • Example#6561 - ReflectionMethod::invokeArgs example
  • Example#6562 - ReflectionMethod::__toString example
  • Example#6563 - Using the ReflectionParameter class
  • Example#6564 - Using the ReflectionParameter class
  • Example#6565 - Getting the class that declared the method
  • Example#6566 - Getting default values of function parameters
  • Example#6567 - Getting default values' constant names of function parameters
  • Example#6568 - ReflectionParameter::getType Usage as of PHP 7.1.0
  • Example#6569 - ReflectionParameter::getType Usage before PHP 7.1.0
  • Example#6570 - ReflectionParameter::hasType example
  • Example#6571 - ReflectionProperty::__construct example
  • Example#6572 - Getting value from private and protected properties using ReflectionProperty class
  • Example#6573 - ReflectionProperty::getDocComment example
  • Example#6574 - Multiple property declarations
  • Example#6575 - ReflectionProperty::getType example
  • Example#6576 - ReflectionProperty::getValue example
  • Example#6577 - ReflectionProperty::hasType example
  • Example#6578 - ReflectionClass::isDefault example
  • Example#6579 - ReflectionProperty::isInitialized example
  • Example#6580 - ReflectionProperty::setValue example
  • Example#6581 - ReflectionType::allowsNull example
  • Example#6582 - ReflectionType::isBuiltin example
  • Example#6583 - ReflectionType::__toString example
  • Example#6584 - ReflectionGenerator::__construct example
  • Example#6585 - ReflectionGenerator::getExecutingFile example
  • Example#6586 - ReflectionGenerator::getExecutingGenerator example
  • Example#6587 - ReflectionGenerator::getExecutingLine example
  • Example#6588 - ReflectionGenerator::getFunction example
  • Example#6589 - ReflectionGenerator::getThis example
  • Example#6590 - ReflectionGenerator::getTrace example
  • Example#6591 - boolval examples
  • Example#6592 - debug_zval_dump example
  • Example#6593 -
  • Example#6594 -
  • Example#6595 - A simple empty / isset comparison.
  • Example#6596 - empty on String Offsets
  • Example#6597 - floatval Example
  • Example#6598 - floatval non-numeric leftmost characters Example
  • Example#6599 - get_defined_vars Example
  • Example#6600 - get_resource_type example
  • Example#6601 - gettype example
  • Example#6602 - import_request_variables example
  • Example#6603 - intval examples
  • Example#6604 - Check that variable is an array
  • Example#6605 - is_bool examples
  • Example#6606 - is_callable example
  • Example#6607 - is_callable and constructors
  • Example#6608 - is_countable examples
  • Example#6609 - is_float example
  • Example#6610 - is_int example
  • Example#6611 - is_iterable examples
  • Example#6612 - is_null example
  • Example#6613 - is_numeric examples
  • Example#6614 - is_object example
  • Example#6615 - is_resource example
  • Example#6616 - is_scalar example
  • Example#6617 - is_string example
  • Example#6618 - isset Examples
  • Example#6619 - isset on String Offsets
  • Example#6620 - print_r example
  • Example#6621 - return parameter example
  • Example#6622 - serialize example
  • Example#6623 - settype example
  • Example#6624 - strval example using PHP 5's magic __toString() method.
  • Example#6625 - unserialize example
  • Example#6626 - unserialize_callback_func example
  • Example#6627 - unset example
  • Example#6628 - Using (unset) casting
  • Example#6629 - var_dump example
  • Example#6630 - var_export Examples
  • Example#6631 - Exporting classes since PHP 5.1.0
  • Example#6632 - Using __set_state() (since PHP 5.1.0)
  • Example#6633 -
  • Example#6634 - OAuth::fetch example
  • Example#6635 - OAuth::getAccessToken example
  • Example#6636 - OAuth::getRequestToken example
  • Example#6637 - OAuth::setRequestEngine example
  • Example#6638 - An OAuth::setRsaCertificate example
  • Example#6639 - OAuth::setToken example
  • Example#6640 - OAuthProvider::__construct example
  • Example#6641 - Example OAuthProvider::consumerHandler callback
  • Example#6642 - OAuthProvider::generateToken example
  • Example#6643 - OAuthProvider::is2LeggedEndpoint example
  • Example#6644 - Example OAuthProvider::timestampNonceHandler callback
  • Example#6645 - Example OAuthProvider::tokenHandler callback
  • Example#6646 - A sample SCA component
  • Example#6647 - The structure of an SCA for PHP component
  • Example#6648 - Obtaining a proxy for a local PHP class
  • Example#6649 - Obtaining a proxy for a web service
  • Example#6650 - Calling services
  • Example#6651 - Obtaining a proxy using getService
  • Example#6652 - Making calls on the proxy
  • Example#6653 - StockQuote Service
  • Example#6654 - Generated WSDL
  • Example#6655 - Generated WSDL
  • Example#6656 - location attribute
  • Example#6657 - method with two arguments
  • Example#6658 - types section illustrating named parameters
  • Example#6659 - A Component that uses Data Structures
  • Example#6660 - An SCA::getService example
  • Example#6661 - is_soap_fault example
  • Example#6662 - SOAP's standard method for error reporting is exceptions
  • Example#6663 - SoapClient::__doRequest example
  • Example#6664 - SoapClient::__getFunctions example
  • Example#6665 - SoapClient::__getLastRequest() example
  • Example#6666 - SoapClient::__getLastRequestHeaders() example
  • Example#6667 - SoapClient::__getLastResponse() example
  • Example#6668 - SoapClient::__getLastResponse() example
  • Example#6669 - SoapClient::__getTypes example
  • Example#6670 - SoapClient::__setLocation example
  • Example#6671 - SoapClient::__setSoapHeaders example
  • Example#6672 - Set Multiple Headers
  • Example#6673 - SoapClient::__soapCall example
  • Example#6674 - SoapClient::SoapClient example
  • Example#6675 - SoapServer::addFunction example
  • Example#6676 - SoapServer::getFunctions example
  • Example#6677 - SoapServer::handle example
  • Example#6678 - SoapServer::setPersistence example
  • Example#6679 - SoapServer::SoapServer example
  • Example#6680 - Some examples
  • Example#6681 - Some examples
  • Example#6682 - SoapHeader::SoapHeader example
  • Example#6683 - SoapParam::SoapParam example
  • Example#6684 - SoapVar::SoapVar example
  • Example#6685 - Yar Server Example
  • Example#6686 - Access the server in borwser(GET request)
  • Example#6687 - Yar Client Example
  • Example#6688 - Yar Concurrent Client Example
  • Example#6689 - Yar_Server::__construct example
  • Example#6690 - Yar_Server::handle example
  • Example#6691 - Yar_Client::__call example
  • Example#6692 - Yar_Client::__construct example
  • Example#6693 - Yar_Client::setOpt example
  • Example#6694 - Yar_Concurrent_Client::call example
  • Example#6695 - Yar_Concurrent_Client::loop example
  • Example#6696 - Yar_Concurrent_Client::reset example
  • Example#6697 - Yar_Server_Exception::getType example
  • Example#6698 - Yar_Client_Exception::getType example
  • Example#6699 - XMLRPC client functions example
  • Example#6700 - XML-RPC type example
  • Example#6701 - A xmlrpc_set_type example
  • Example#6702 - For Each in ASP
  • Example#6703 - foreach in PHP
  • Example#6704 - COM example (1)
  • Example#6705 - COM example (2)
  • Example#6706 - DOTNET example
  • Example#6707 - Variant example
  • Example#6708 - COM event sink example
  • Example#6709 - Statistics about the current PHP process
  • Example#6710 - Statistics about global memory utilization
  • Example#6711 - Registering a PHP script to run as a service
  • Example#6712 - Unregistering a service
  • Example#6713 - Running as a service
  • Example#6714 - A win32_create_service example
  • Example#6715 - A win32_create_service example with dependencies
  • Example#6716 - A win32_create_service example with recovery
  • Example#6717 - A win32_delete_service example
  • Example#6718 - A win32_start_service_ctrl_dispatcher example
  • Example#6719 - book.xml
  • Example#6720 - Creating a new DOMAttr object
  • Example#6721 - DOMAttr::isId() Example
  • Example#6722 - Creating a new DOMCdataSection object
  • Example#6723 - Creating a new DOMComment
  • Example#6724 - Creating a new DOMDocument
  • Example#6725 - Creating a new element and inserting it as root
  • Example#6726 - Passing text containing an unescaped & as value
  • Example#6727 - Creating a new element and inserting it as root
  • Example#6728 - A namespace prefix example
  • Example#6729 - DOMDocument::getElementById() Example
  • Example#6730 - Basic Usage Example
  • Example#6731 - Get all the XInclude elements
  • Example#6732 - DOMDocument::importNode example
  • Example#6733 - Creating a Document
  • Example#6734 - Creating a Document
  • Example#6735 - Creating a Document
  • Example#6736 - Creating a Document
  • Example#6737 - Static invocation of loadXML
  • Example#6738 - Adding a new method to DOMElement to ease our code
  • Example#6739 - Retrieving elements as custom class
  • Example#6740 - Retrieving owner document
  • Example#6741 - Saving a DOM tree into a file
  • Example#6742 - Saving a HTML tree into a string
  • Example#6743 - Saving a HTML tree into a file
  • Example#6744 - Saving a DOM tree into a string
  • Example#6745 - Example of DTD validation
  • Example#6746 - DOMDocument::xinclude() example
  • Example#6747 - Appending XML data to your document
  • Example#6748 - Creating a new DOMElement
  • Example#6749 - Setting an attribute
  • Example#6750 - Creating a new DOMEntityReference
  • Example#6751 - Creating a document with an attached DTD
  • Example#6752 - Testing your DOM Implementation
  • Example#6753 - Adding a child
  • Example#6754 - Nested children
  • Example#6755 - DOMNode::getLineNo example
  • Example#6756 - DOMNode::getNodePath example
  • Example#6757 - Removing a child
  • Example#6758 - Traversing all the entries of the table
  • Example#6759 - Creating a new DOMProcessingInstruction object
  • Example#6760 - Creating a new DOMText
  • Example#6761 - Getting the count of all the english books
  • Example#6762 - Getting all the english books
  • Example#6763 - book.xml
  • Example#6764 - DOMXPath::registerPHPFunctions with php:functionString
  • Example#6765 - DOMXPath::registerPHPFunctions with php:function
  • Example#6766 - Import SimpleXML into DOM with dom_import_simplexml
  • Example#6767 - A libxml_get_errors example
  • Example#6768 - libxml_set_external_entity_loader example
  • Example#6769 - A libxml_set_streams_context example
  • Example#6770 - A libxml_use_internal_errors example
  • Example#6771 - Access via property name
  • Example#6772 - Access via property name as array index
  • Example#6773 - Data Object iteration
  • Example#6774 - Access many-valued property by name
  • Example#6775 - Many-valued element access
  • Example#6776 - Many-valued property iteration
  • Example#6777 - Chained property access
  • Example#6778 - XPath navigation
  • Example#6779 - XPath querying
  • Example#6780 - Creating child data objects
  • Example#6781 - Unset a primitive property
  • Example#6782 - Unset a data object
  • Example#6783 - Unset a referenced data object
  • Example#6784 - Access via property index
  • Example#6785 - Getting the SDO_Sequence interface
  • Example#6786 - Get/set sequence values
  • Example#6787 - Sequence iteration
  • Example#6788 - Sequence versus Data Object
  • Example#6789 - Adding to a sequence
  • Example#6790 - Removing from a sequence
  • Example#6791 - Reflecting on a Data Object
  • Example#6792 - Accessing the type information
  • Example#6793 - A SDO_DAS_DataFactory::addPropertyToType example
  • Example#6794 - A SDO_DAS_DataFactory::addType example
  • Example#6795 - Creating a data object
  • Example#6796 - Retrieving a data object
  • Example#6797 - Updating a data object
  • Example#6798 - Deleting a data object
  • Example#6799 - One company, one department - Create
  • Example#6800 - One company, one department - Retrieve and Update
  • Example#6801 - One company, two departments - Retrieve and Delete
  • Example#6802 - One company, one department, one employee - Create
  • Example#6803 - One company, one department, one employee - Retrieve and update
  • Example#6804 - One company, two departments, two employees - Retrieve and delete
  • Example#6805 - Retrieving a data object using executePreparedQuery
  • Example#6806 - Loading, altering, and saving an XML document
  • Example#6807 - Creating a new XML document
  • Example#6808 - Setting XML document properties
  • Example#6809 - Using an open type
  • Example#6810 - Finding out what you can from the document
  • Example#6811 - Printing the SDO model
  • Example#6812 - Include file example.php with XML string
  • Example#6813 - Getting <plot>
  • Example#6814 - Getting <line>
  • Example#6815 - Accessing non-unique elements in SimpleXML
  • Example#6816 - Using attributes
  • Example#6817 - Comparing Elements and Attributes with Text
  • Example#6818 - Comparing Two Elements
  • Example#6819 - Using XPath
  • Example#6820 - Setting values
  • Example#6821 - Adding elements and attributes
  • Example#6822 - DOM Interoperability
  • Example#6823 - Loading broken XML string
  • Example#6824 - Add attributes and children to a SimpleXML element
  • Example#6825 - Add attributes and children to a SimpleXML element
  • Example#6826 - Get XML
  • Example#6827 - Using asXML() on SimpleXMLElement::xpath results
  • Example#6828 - Interpret an XML string
  • Example#6829 - Traversing a children() pseudo-array
  • Example#6830 - Using namespaces
  • Example#6831 - Create a SimpleXMLElement object
  • Example#6832 - Create a SimpleXMLElement object from a URL
  • Example#6833 - Counting the number of children
  • Example#6834 - Get document namespaces
  • Example#6835 - Working with multiple namespaces
  • Example#6836 - Get XML element names
  • Example#6837 - Get document namespaces in use
  • Example#6838 - Setting a namespace prefix to use in an XPath query
  • Example#6839 - Get string content
  • Example#6840 - Xpath
  • Example#6841 - Return the current element
  • Example#6842 - Return the sub-elements of the current element
  • Example#6843 - Check whether the current element has sub-elements
  • Example#6844 - Get the current XML tag key
  • Example#6845 - Move to the next element
  • Example#6846 - Rewind to the first element
  • Example#6847 - Check whether the current element is valid
  • Example#6848 - Importing DOM
  • Example#6849 - Interpret an XML document
  • Example#6850 - Interpret an XML string
  • Example#6851 - Serializing a single value with WDDX
  • Example#6852 - Using incremental packets with WDDX
  • Example#6853 - wddx_serialize_vars example
  • Example#6854 - Show XML Element Structure
  • Example#6855 - Map XML to HTML
  • Example#6856 - External Entity Example
  • Example#6857 - xmltest.xml
  • Example#6858 - xmltest2.xml
  • Example#6859 - xml_parse_into_struct example
  • Example#6860 - moldb.xml - small database of molecular information
  • Example#6861 - parsemoldb.php - parses moldb.xml into an array of molecular objects
  • Example#6862 - Chunked parsing of large XML documents
  • Example#6863 - xml_set_object example
  • Example#6864 - Validating XML
  • Example#6865 - Creating a simple XML document
  • Example#6866 - Working with XML namespaces
  • Example#6867 - Working with the OO API
  • Example#6868 - collection.xml
  • Example#6869 - collection.xsl
  • Example#6870 - fruits.xml
  • Example#6871 - fruits.xsl
  • Example#6872 - Collating and printing errors
  • Example#6873 - Creating an XSLTProcessor
  • Example#6874 - Testing EXSLT support
  • Example#6875 - Simple PHP Function call from a stylesheet
  • Example#6876 - Changing the owner before the transformation
  • Example#6877 - Example profiling output
  • Example#6878 - Transforming to a DOMDocument
  • Example#6879 - Transforming to a HTML file
  • Example#6880 - Transforming to a string
  • Example#6881 - Leak Detection in Action
  • Example#6882 - Accessor macros for per-module globals
  • Example#6883 - "counter"'s basic interface
  • Example#6884 - "counter"'s extended interface
  • Example#6885 - "counter"'s objective interface
  • Example#6886 - An example config.m4 file
  • Example#6887 - Sample configure output
  • Example#6888 - counter's config.m4 file
  • Example#6889 - An example config.w32 file
  • Example#6890 - counter's config.w32 file
  • Example#6891 - Files in the counter extension, in no particular order
  • Example#6892 - zend_module declaration in the counter extension
  • Example#6893 - zend_module definition in PHP 5.3
  • Example#6894 - Counter extension module definition
  • Example#6895 - The wrong way to store the basic counter interface's value
  • Example#6896 - The counter module's globals
  • Example#6897 - The counter module's global structure declaration
  • Example#6898 - Accessor macros for per-module globals
  • Example#6899 - The right way to store the basic counter interface's value
  • Example#6900 - counter's PHP_MINFO function
  • Example#6901 - Example macros for invoking pdo_SKEL_error
  • Example#6902 - Using pdo_parse_params
  • Example#6903 - Implementing preparer for drivers that don't support native prepared statements
  • Example#6904 - simple stream example that displays the PHP home page
  • Example#6905 - How to accept a stream as a parameter
  • Example#6906 - How to return a stream from a function
  • Example#6907 - The default config.m4.
  • Example#6908 - A simple extension.
  • Example#6909 - A test file for first_module.so.
  • Example#6910 - Internal declaration of zend_function_entry.
  • Example#6911 - Internal declaration of zend_module_entry.
  • Example#6912 - PHP's implementation of variable arguments in fsockopen().
  • Example#6913 - PHP/Zend zval type definition.
  • Example#6914 - Testing for referenced parameter passing.
  • Example#6915 - Creating variables with different scopes.
  • Example#6916 - Creation of a long.
  • Example#6917 - Adding an element to an associative array.
  • Example#6918 - Adding an element to an indexed array.
  • Example#6919 - Source code and screenshot for output in phpinfo.
  • Example#6920 - Printing execution information.
  • Example#6921 - Calling user functions.
  • Example#6922 - A hidden HTML form element
  • Example#6923 - Data to be edited by the user
  • Example#6924 - In a URL
  • Example#6925 - Generating Javascript with PHP
  • Example#6926 - Emulating Register Globals
  • Example#6927 - Example PHP/FI Code
  • Example#6928 - In PHP Core
  • Example#6929 - Object Oriented Code in PHP Core
  • Example#6930 - In the bzip2 Extension
  • Example#6931 - In the datetime Extension
  • Example#6932 - In the dBase Extension
  • Example#6933 - In the mcrypt Extension
  • Example#6934 - In the oci8 Extension
  • Example#6935 - In the SPL Extension
  • Example#6936 - In the Semaphore (sysvmsg) extension
  • Example#6937 - A 5.2.1+ Zip Example
  • Example#6938 - strrpos and strripos now use the entire string as a needle
  • Example#6939 - An object with no properties is no longer considered "empty"
  • Example#6940 - In some cases classes must be declared before used
  • Example#6941 - Migrating Apache configuration files for PHP 5
  • Example#6942 - Migrating Apache configuration files for PHP 5, CGI mode
  • Example#6943 - Activate full on-screen error reporting for dev. domain
  • Example#6944 - Add security script for protected areas
  • Example#6945 - Unix include_path
  • Example#6946 - Windows include_path
  • Example#6947 - Unix include_path using ${USER} env variable
  • Example#6948 - string.rot13
  • Example#6949 - string.toupper
  • Example#6950 - string.tolower
  • Example#6951 - string.strip_tags
  • Example#6952 - convert.base64-encode & convert.base64-decode
  • Example#6953 - convert.quoted-printable-encode & convert.quoted-printable-decode
  • Example#6954 - convert.iconv.*
  • Example#6955 - zlib.deflate and zlib.inflate
  • Example#6956 - zlib.deflate simple
  • Example#6957 - bzip2.compress and bzip2.decompress
  • Example#6958 - Encrypt/Decrypt with Blowfish
  • Example#6959 - Encrypt file using AES-128 CBC with SHA256 HMAC in PHP 5.5+


Changelog

The following changes have been made to functions of bundled extensions.

Version | Function | Description
7.4.0 | array_merge | This function can now be called without any parameter. Formerly, at least one parameter has been required.
array_merge_recursive | This function can now be called without any parameter. Formerly, at least one parameter has been required.
base_convert | Passing invalid characters will now generate a deprecation notice. The result will still be computed as if the invalid characters did not exist.
bindec | Passing invalid characters will now generate a deprecation notice. The result will still be computed as if the invalid characters did not exist.
fgetcsv | The escape parameter now also accepts an empty string to disable the proprietary escape mechanism.
fputcsv | The escape_char parameter now also accepts an empty string to disable the proprietary escape mechanism.
get_magic_quotes_gpc | This function has been deprecated.
get_magic_quotes_runtime | This function has been deprecated.
hexdec | Passing invalid characters will now generate a deprecation notice. The result will still be computed as if the invalid characters did not exist.
idn_to_ascii | The default value of variant is now INTL_IDNA_VARIANT_UTS46 instead of the deprecated INTL_IDNA_VARIANT_2003.
idn_to_utf8 | The default value of variant is now INTL_IDNA_VARIANT_UTS46 instead of the deprecated INTL_IDNA_VARIANT_2003.
imagecropauto | 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.
imagecropauto | 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.
imagefilter | Scatter support (IMG_FILTER_SCATTER) was added.
implode | Passing the glue after the pieces (i.e. not using the documented order of parameters) has been deprecated.
ldap_control_paged_result | This function has been deprecated.
ldap_control_paged_result_response | This function has been deprecated.
octdec | Passing invalid characters will now generate a deprecation notice. The result will still be computed as if the invalid characters did not exist.
proc_open | Added the create_process_group option to the other_options parameter.
str_getcsv | The escape parameter now interprets an empty string as signal to disable the proprietary escape mechanism. Formerly, an empty string was treated like the default parameter value.
SplFileObject::fgetcsv | The escape parameter now also accepts an empty string to disable the proprietary escape mechanism.
SplFileObject::fputcsv | The escape parameter now also accepts an empty string to disable the proprietary escape mechanism.
SplFileObject::getCsvControl | The escape character can now be an empty string.
SplFileObject::setCsvControl | The escape parameter now also accepts an empty string to disable the proprietary escape mechanism.
SQLite3Stmt::bindParam | sql_param now also supports the @param notation.
SQLite3Stmt::bindValue | sql_param now also supports the @param notation.
7.3.15, 7.4.3 | curl_setopt | Introduced CURLOPT_HTTP09_ALLOWED .
7.3.14, 7.4.2 | dba_open | The lmdb driver now supports an additional $mapsize parameter.
7.3.0 | DateTime::createFromFormat | The v format specifier has been added.
apache_request_headers | This function became available in the FPM SAPI.
array_push | This function can now be called with only one parameter. Formerly, at least two parameters have been required.
array_unshift | This function can now be called with only one parameter. Formerly, at least two parameters have been required.
bcmul | bcmul now returns numbers with the requested scale. Formerly, the returned numbers may have omitted trailing decimal zeroes.
bcpow | bcpow now returns numbers with the requested scale. Formerly, the returned numbers may have omitted trailing decimal zeroes.
bcscale | 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.
compact | compact now issues an E_NOTICE level error if a given string refers to an unset variable. Formerly, such strings have been silently skipped.
curl_getinfo | Introduced CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, CURLINFO_CONTENT_LENGTH_UPLOAD_T, CURLINFO_HTTP_VERSION, CURLINFO_PROTOCOL, CURLINFO_PROXY_SSL_VERIFYRESULT, CURLINFO_SCHEME, CURLINFO_SIZE_DOWNLOAD_T, CURLINFO_SIZE_UPLOAD_T, CURLINFO_SPEED_DOWNLOAD_T, CURLINFO_SPEED_UPLOAD_T, CURLINFO_APPCONNECT_TIME_T, CURLINFO_CONNECT_TIME_T, CURLINFO_FILETIME_T, CURLINFO_NAMELOOKUP_TIME_T, CURLINFO_PRETRANSFER_TIME_T, CURLINFO_REDIRECT_TIME_T, CURLINFO_STARTTRANSFER_TIME_T, CURLINFO_TOTAL_TIME_T.
curl_setopt | Introduced CURLOPT_ABSTRACT_UNIX_SOCKET, CURLOPT_KEEP_SENDING_ON_ERROR, CURLOPT_PRE_PROXY, CURLOPT_PROXY_CAINFO, CURLOPT_PROXY_CAPATH, CURLOPT_PROXY_CRLFILE, CURLOPT_PROXY_KEYPASSWD, CURLOPT_PROXY_PINNEDPUBLICKEY, CURLOPT_PROXY_SSLCERT, CURLOPT_PROXY_SSLCERTTYPE, CURLOPT_PROXY_SSL_CIPHER_LIST, CURLOPT_PROXY_SSLKEY, CURLOPT_PROXY_SSLKEYTYPE, CURLOPT_PROXY_SSL_OPTIONS, CURLOPT_PROXY_SSL_VERIFYHOST, CURLOPT_PROXY_SSL_VERIFYPEER, CURLOPT_PROXY_SSLVERSION, CURLOPT_PROXY_TLSAUTH_PASSWORD, CURLOPT_PROXY_TLSAUTH_TYPE, CURLOPT_PROXY_TLSAUTH_USERNAME, CURLOPT_SOCKS5_AUTH, CURLOPT_SUPPRESS_CONNECT_HEADERS, CURLOPT_DISALLOW_USERNAME_IN_URL, CURLOPT_DNS_SHUFFLE_ADDRESSES, CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS, CURLOPT_HAPROXYPROTOCOL, CURLOPT_PROXY_TLS13_CIPHERS, CURLOPT_SSH_COMPRESSION, CURLOPT_TIMEVALUE_LARGE and CURLOPT_TLS13_CIPHERS.
define | case_insensitive has been deprecated and will be removed in version 8.0.0.
ftp_fget | The mode parameter is now optional. Formerly it has been mandatory.
ftp_fput | The mode parameter is now optional. Formerly it has been mandatory.
ftp_get | The mode parameter is now optional. Formerly it has been mandatory.
ftp_nb_fget | The mode parameter is now optional. Formerly it has been mandatory.
ftp_nb_fput | The mode parameter is now optional. Formerly it has been mandatory.
ftp_nb_get | The mode parameter is now optional. Formerly it has been mandatory.
ftp_nb_put | The mode parameter is now optional. Formerly it has been mandatory.
ftp_put | The mode parameter is now optional. Formerly it has been mandatory.
getallheaders | This function became available in the FPM SAPI.
is_countable | is_countable has been added.
json_decode | JSON_THROW_ON_ERROR options was added.
json_encode | JSON_THROW_ON_ERROR options was added.
password_hash | Support for Argon2id passwords using PASSWORD_ARGON2ID was added.
preg_quote | The # character is now quoted
session_get_cookie_params | The "samesite" entry was added in the returned array.
session_set_cookie_params | An alternative signature supporting an options array has been added. This signature supports also setting of the SameSite cookie attribute.
setcookie | An alternative signature supporting an options array has been added. This signature supports also setting of the SameSite cookie attribute.
setrawcookie | An alternative signature supporting an options array has been added. This signature supports also setting of the SameSite cookie attribute.
unlink | 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.
xml_set_external_entity_ref_handler | The return value of the handler is no longer ignored if the extension has been built against libxml. Formerly, the return value has been ignored, and parsing did never stop.
7.3 | ldap_add | Support for serverctrls added
ldap_compare | Support for serverctrls added
ldap_delete | Support for serverctrls added
ldap_exop | Support for serverctrls added
ldap_exop_passwd | Support for serverctrls added
ldap_list | Support for serverctrls added
ldap_mod_add | Support for serverctrls added
ldap_mod_del | Support for serverctrls added
ldap_mod_replace | Support for serverctrls added
ldap_modify_batch | Support for serverctrls added
ldap_parse_result | Support for serverctrls added
ldap_read | Support for serverctrls added
ldap_rename | Support for serverctrls added
ldap_search | Support for serverctrls added
7.2.19, 7.3.6 | SplFileObject::__toString | Changed from an alias of SplFileObject::current to an alias of SplFileObject::fgets.
7.2.18, 7.3.5 | substr_compare | offset may now be equal to the length of main_str.
7.2.0 | array_unique | If sort_flags is SORT_STRING, formerly array has been copied and non-unique elements have been removed (without packing the array afterwards), but now a new array is built by adding the unique elements. This can result in different numeric indexes.
assert | 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.
bcmod | The scale parameter was added.
bcmod | dividend and divisor are no longer truncated to integer, so now the behavior of bcmod follows fmod rather than the % operator.
count | count will now yield a warning on invalid countable types passed to the array_or_countable parameter.
date_parse | The zone element of the returned array represents seconds instead of minutes now, and its sign is inverted. For instance -120 is now 7200.
date_parse_from_format | The zone element of the returned array represents seconds instead of minutes now, and its sign is inverted. For instance -120 is now 7200.
exif_read_data | Support for the following EXIF formats were added: Samsung DJI Panasonic Sony Pentax Minolta Sigma/Foveon AGFA Kyocera Ricoh Epson
exif_read_data | The filename parameter was renamed to stream and now supports both local files or stream resources.
exif_thumbnail | The filename parameter was renamed to stream and now supports both local files or stream resources.
get_class | NULL was removed as the default value for object, and is no longer a valid input.
gettype | Closed resources are now reported as 'resource (closed)'. Previously the returned value for closed resources were 'unknown type'.
hash_copy | Accept and return HashContext instead of resource.
hash_final | Accept HashContext instead of resource.
hash_hmac | Usage of non-cryptographic hash functions (adler32, crc32, crc32b, fnv132, fnv1a32, fnv164, fnv1a64, joaat) was disabled.
hash_hmac_file | Usage of non-cryptographic hash functions (adler32, crc32, crc32b, fnv132, fnv1a32, fnv164, fnv1a64, joaat) was disabled.
hash_init | Return HashContext instead of resource.
hash_init | Usage of non-cryptographic hash functions (adler32, crc32, crc32b, fnv132, fnv1a32, fnv164, fnv1a64, joaat) with HASH_HMAC was disabled.
hash_pbkdf2 | Usage of non-cryptographic hash functions (adler32, crc32, crc32b, fnv132, fnv1a32, fnv164, fnv1a64, joaat) was disabled.
hash_update | Accept HashContext instead of resource.
hash_update_file | Accept HashContext instead of resource.
hash_update_stream | Accept HashContext instead of resource.
idn_to_ascii | INTL_IDNA_VARIANT_2003 has been deprecated; use INTL_IDNA_VARIANT_UTS46 instead.
idn_to_utf8 | INTL_IDNA_VARIANT_2003 has been deprecated; use INTL_IDNA_VARIANT_UTS46 instead.
imageantialias | imageantialias is now generally available. Formerly it was only available if PHP was compiled with the bundled version of the GD library.
imagegd | imagegd now allows to output truecolor images. Formerly, these have been implicitly converted to palette.
imagelayereffect | Added IMG_EFFECT_MULTIPLY (requires system libgd >= 2.1.1 or the bundled libgd).
imagetypes | IMG_BMP added.
is_object | is_object now returns TRUE for unserialized objects without a class definition (class of __PHP_Incomplete_Class). Previously FALSE was returned.
json_decode | JSON_INVALID_UTF8_IGNORE, and JSON_INVALID_UTF8_SUBSTITUTE options were added.
json_encode | JSON_INVALID_UTF8_IGNORE, and JSON_INVALID_UTF8_SUBSTITUTE options were added.
mail | The additional_headers parameter now also accepts an array.
mb_check_encoding | This function now also accepts an array as var. Formerly, only strings have been supported.
mb_convert_encoding | This function now also accepts an array as val. Formerly, only strings have been supported.
mb_send_mail | The additional_headers parameter now also accepts an array.
mt_rand | mt_rand has received a bug fix for a modulo bias bug. This means that sequences generated with a specific seed may differ from PHP 7.1 on 64-bit machines.
number_format | number_format was changed to not being able to return -0, previously -0 could be returned for cases like where number would be -0.01.
openssl_pkcs7_verify | The p7bfilename parameter was added.
pack | float and double types supports both Big Endian and Little Endian.
parse_str | Usage of parse_str without a second parameter now emits an E_DEPRECATED notice.
password_hash | Support for Argon2i passwords using PASSWORD_ARGON2I was added.
preg_match | The PREG_UNMATCHED_AS_NULL is now supported for the $flags parameter.
preg_match_all | The PREG_UNMATCHED_AS_NULL is now supported for the $flags parameter.
proc_nice | This function is now available on Windows.
rand | rand has received a bug fix for a modulo bias bug. This means that sequences generated with a specific seed may differ from PHP 7.1 on 64-bit machines.
read_exif_data | This function alias was deprecated.
session_abort | The return type of this function is bool now. Formerly, it has been void.
session_module_name | It is now explicitly forbidden to set the module name to "user". Formerly, this has been silently ignored.
session_name | session_name checks session status, previously it only checked cookie status. Therefore, older session_name allows to call session_name after session_start which may crash PHP and may result in misbehaviors.
session_reset | The return type of this function is bool now. Formerly, it has been void.
session_set_cookie_params | Returns TRUE on success or FALSE on failure. Formerly the function returned void.
session_unset | The return type of this function is bool now. Formerly, it has been void.
session_write_close | The return type of this function is bool now. Formerly, it has been void.
set_error_handler | errcontext became deprecated. Usage of this parameter now emits an E_DEPRECATED notice.
unpack | float and double types supports both Big Endian and Little Endian.
utf8_decode | This function has been moved to the core of PHP, and therefore lifting the requirement on the XML extension for this function to be available.
utf8_encode | This function has been moved to the core of PHP, and therefore lifting the requirement on the XML extension for this function to be available.
PDOStatement::debugDumpParams | 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.
SQLite3::openBlob | The flags parameter has been added, allowing to write BLOBs; formerly only reading was supported.
7.1.24, 7.2.12, 7.3.0 | xml_parser_get_option | options now supports XML_OPTION_SKIP_TAGSTART and XML_OPTION_SKIP_WHITE.
7.1.5 | IntlDateFormatter::format | Support for providing general DateTimeInterface objects to the value parameter was added. Formerly, only proper DateTime objects were supported.
7.1.4 | PDO::sqliteCreateFunction | The flags parameter has been added.
SQLite3::createFunction | The flags parameter has been added.
7.1.0 | DateInterval::format | The F and f format characters were added.
DateTime::setTime | The microseconds parameter was added.
array_rand | The internal randomization algorithm has been changed to use the Mersenne Twister Random Number Generator instead of the libc rand function.
curl_multi_setopt | Introduced CURLMOPT_PUSHFUNCTION.
exif_imagetype | Added WebP support.
file_get_contents | Support for negative offsets has been added.
get_headers | The context parameter was added.
getenv | The varname can now be omitted to retrieve an associative array of all environment variables.
getimagesize | Added WebP support.
getopt | Added the optind parameter.
grapheme_extract | Support for negative starts has been added.
grapheme_stripos | Support for negative offsets has been added.
grapheme_strpos | Support for negative offsets has been added.
hash_algos | Support for sha512/224, sha512/256, sha3-224, sha3-256, sha3-384 and sha3-512 has been added.
iconv_strpos | Support for negative offsets has been added.
json_decode | An empty JSON key ("") can be encoded to the empty object property instead of using a key with value _empty_.
json_encode | JSON_UNESCAPED_LINE_TERMINATORS options was added.
json_encode | serialize_precision is used instead of precision when encoding double values.
list | It is now possible to specify keys in list. This enables destructuring of arrays with non-integer or non-sequential keys.
long2ip | The parameter type of proper_address has been changed from string to integer.
mb_ereg | mb_ereg will now set regs to an empty array, if nothing matched. Formerly, regs was not modified in that case.
mb_ereg_replace | The e modifier has been deprecated.
mb_ereg_search_setpos | Support for negative positions has been added.
mb_eregi | mb_eregi will now set regs to an empty array, if nothing matched. Formerly, regs was not modified in that case.
mb_eregi_replace | The e modifier has been deprecated.
mb_strimwidth | Support for negative starts and widths has been added.
mb_stripos | Support for negative offsets has been added.
mb_strpos | Support for negative offsets has been added.
mt_rand | rand has been made an alias of mt_rand.
mt_rand | mt_rand has been updated to use the fixed, correct, version of the Mersenne Twister algorithm. To fall back to the old behaviour, use mt_srand with MT_RAND_PHP as the second parameter.
mt_srand | srand has been made an alias of mt_srand.
mt_srand | mt_rand has been updated to use the fixed, correct, version of the Mersenne Twister algorithm. To fall back to the old behaviour, use mt_srand with MT_RAND_PHP as the second parameter.
openssl_csr_new | configargs now also supports curve_name.
openssl_decrypt | The tag and aad parameters were added.
openssl_encrypt | The tag, aad and tag_length parameters were added.
openssl_pkey_new | The curve_name configarg was added to make it possible to create EC keys.
output_add_rewrite_var | 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, url_rewriter.tags is used solely for output functions, url_rewriter.hosts is added.
output_reset_rewrite_vars | 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.
pcntl_signal | As of PHP 7.1.0 the handler callback is given a second argument containing the signinfo of the specific signal. This data is only supplied if the operating system has the signinfo_t structure. If the OS does not implement siginfo_t NULL is supplied.
pcntl_signal_get_handler | pcntl_signal_get_handler has been added.
pg_fetch_all | The result_type parameter was added.
pg_last_notice | The option parameter was added.
pg_select | The result_type parameter was added.
rand | rand has been made an alias of mt_rand.
session_start | session_start now returns FALSE and no longer initializes $_SESSION when it failed to start the session.
shuffle | The internal randomization algorithm has been changed to use the Mersenne Twister Random Number Generator instead of the libc rand function.
srand | srand has been made an alias of mt_srand.
str_shuffle | The internal randomization algorithm has been changed to use the Mersenne Twister Random Number Generator instead of the libc rand function.
stripos | Support for negative offsets has been added.
strpos | Support for negative offsets has been added.
substr_count | Support for negative offsets and lengths has been added. length may also be 0 now.
unpack | The optional offset has been added.
unserialize | The allowed_classes element of options) is now strictly typed, i.e. if anything other than an array or a boolean is given, unserialize returns FALSE and issues an E_WARNING.
7.1 | DateTime::__construct | From now on microseconds are filled with actual value. Not with '00000'.
7.0.16, 7.1.2 | dns_get_record | Added support for CAA record type.
fopen | The 'e' option was added.
7.0.15, 7.1.1 | get_defined_functions | The exclude_disabled parameter has been added.
7.0.15,7.1.1 | pack | The "e", "E", "g" and "G" codes were added to enable byte order support for float and double.
7.0.11 | iconv_substr | If str is equal to offset characters long, an empty string will be returned. Prior to this version, FALSE was returned in this case.
7.0.10 | SQLite3::__construct | The filename can now be empty to use a private, temporary on-disk database.
7.0.7 | curl_multi_setopt | Introduced CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE, CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE, CURLMOPT_MAX_HOST_CONNECTIONS, CURLMOPT_MAX_PIPELINE_LENGTH and CURLMOPT_MAX_TOTAL_CONNECTIONS.
curl_setopt | Introduced CURL_HTTP_VERSION_2, CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE, CURL_HTTP_VERSION_2TLS, CURL_REDIR_POST_301, CURL_REDIR_POST_302, CURL_REDIR_POST_303, CURL_REDIR_POST_ALL, CURL_VERSION_KERBEROS5, CURL_VERSION_PSL, CURL_VERSION_UNIX_SOCKETS, CURLAUTH_NEGOTIATE, CURLAUTH_NTLM_WB, CURLFTP_CREATE_DIR, CURLFTP_CREATE_DIR_NONE, CURLFTP_CREATE_DIR_RETRY, CURLHEADER_SEPARATE, CURLHEADER_UNIFIED, CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE, CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE, CURLMOPT_MAX_HOST_CONNECTIONS, CURLMOPT_MAX_PIPELINE_LENGTH, CURLMOPT_MAX_TOTAL_CONNECTIONS, CURLOPT_CONNECT_TO, CURLOPT_DEFAULT_PROTOCOL, CURLOPT_DNS_INTERFACE, CURLOPT_DNS_LOCAL_IP4, CURLOPT_DNS_LOCAL_IP6, CURLOPT_EXPECT_100_TIMEOUT_MS, CURLOPT_HEADEROPT, CURLOPT_LOGIN_OPTIONS, CURLOPT_PATH_AS_IS, CURLOPT_PINNEDPUBLICKEY, CURLOPT_PIPEWAIT, CURLOPT_PROXY_SERVICE_NAME, CURLOPT_PROXYHEADER, CURLOPT_SASL_IR, CURLOPT_SERVICE_NAME, CURLOPT_SSL_ENABLE_ALPN, CURLOPT_SSL_ENABLE_NPN, CURLOPT_SSL_FALSESTART, CURLOPT_SSL_VERIFYSTATUS, CURLOPT_STREAM_WEIGHT, CURLOPT_TCP_FASTOPEN, CURLOPT_TFTP_NO_OPTIONS, CURLOPT_UNIX_SOCKET_PATH, CURLOPT_XOAUTH2_BEARER, CURLPROTO_SMB, CURLPROTO_SMBS, CURLPROXY_HTTP_1_0, CURLSSH_AUTH_AGENT and CURLSSLOPT_NO_REVOKE.
7.0.0 | array_column | Added the ability for the input parameter to be an array of objects.
assert | assert is now a language construct and not a function. assertion can now be an expression. The second parameter is now interpreted either as an exception (if a Throwable object is given), or as the description supported from PHP 5.4.8 onwards.
curl_setopt | Support for disabling the CURLOPT_SAFE_UPLOAD option has been removed. All curl file uploads must use CURLFile.
current | array is now always passed by value. Prior to this version, it was passed by reference if possible, and by value otherwise.
define | array values are allowed.
dirname | Added the optional levels parameter.
dl | dl is disabled in PHP-FPM.
getrusage | This function is now supported on Windows.
gmmktime | is_dst parameter has been removed.
imagepsbbox | T1Lib support was removed from PHP, thus this function was removed.
imagepsencodefont | T1Lib support was removed from PHP, thus this function was removed.
imagepsextendfont | T1Lib support was removed from PHP, thus this function was removed.
imagepsfreefont | T1Lib support was removed from PHP, thus this function was removed.
imagepsloadfont | T1Lib support was removed from PHP, thus this function was removed.
imagepsslantfont | T1Lib support was removed from PHP, thus this function was removed.
imagepstext | T1Lib support was removed from PHP, thus this function was removed.
is_numeric | Strings in hexadecimal (e.g. 0xf4c3b00c) notation are no longer regarded as numeric strings, i.e. is_numeric returns FALSE now.
json_decode | Rejected RFC 7159 incompatible number formats - top level (07, 0xff, .1, -.1) and all levels ([1.], [1.e1])
json_decode | An empty PHP string or value that after casting to string is an empty string (NULL, FALSE) results in JSON syntax error.
key | array is now always passed by value. Prior to this version, it was passed by reference if possible, and by value otherwise.
list | list expressions can no longer be completely empty.
list | Strings can no longer be unpacked.
list | The order that the assignment operations are performed in has changed.
mktime | is_dst parameter has been removed.
ob_start | In case ob_start is used inside an output buffer callback, this function will no longer issue an E_ERROR but instead an E_RECOVERABLE_ERROR, allowing custom error handlers to catch such errors.
openssl_open | The iv has been added.
openssl_seal | The iv has been added.
parse_ini_file | Hash marks (#) are no longer recognized as comments.
preg_replace | Support for the /e modifier has been removed. Use preg_replace_callback instead.
proc_open | Added the blocking_pipes option to the other_options parameter.
session_regenerate_id | session_regenerate_id saves old session data before closing.
session_set_save_handler | Added the optional validate_sid and update_timestamp parameters.
session_start | The options parameter was added.
set_exception_handler | The type of parameter passed into exception_handler changed from Exception to Throwable
setlocale | Support for the category parameter passed as a string has been removed. Only LC_* constants can be used as of this version.
shmop_close | The type of shmid has been changed from int to resource.
shmop_delete | The type of shmid has been changed from int to resource.
shmop_open | The return type of shmop_open has been changed from int to resource.
shmop_read | The type of shmid has been changed from int to resource.
shmop_size | The type of shmid has been changed from int to resource.
shmop_write | The type of shmid has been changed from int to resource.
substr | If string is equal to start characters long, an empty string will be returned. Prior to this version, FALSE was returned in this case.
token_get_all | Added the optional flags parameter along with the TOKEN_PARSE flag.
unserialize | The options parameter has been added.
IntlDateFormatter::setTimeZoneId | This function has been removed.
5.6.25, 7.0.10 | imagetypes | IMG_WEBP added.
SplFileObject::getCsvControl | Added the escape character to the returned array.
5.6.16 | mysqli::real_connect | Added the MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT flag for MySQL Native Driver
5.6.12 | gd_info | WebP Support added.
5.6.6 | json_encode | JSON_PRESERVE_ZERO_FRACTION options was added.
5.6.5 | crypt | When the failure string "*0" is given as the salt, "*1" will now be returned for consistency with other crypt implementations. Prior to this version, PHP 5.6 would incorrectly return a DES hash.
5.6.3 | pack | The "q", "Q", "J" and "P" codes were added to enable working with 64-bit numbers.
5.6.1 | parse_ini_file | Added new INI_SCANNER_TYPED mode.
sem_acquire | The $nowait parameter was added.
5.6.0 | array_fill | num may now be zero. Previously, num was required to be greater than zero.
array_filter | Added optional flag parameter and constants ARRAY_FILTER_USE_KEY and ARRAY_FILTER_USE_BOTH
crypt | Raise E_NOTICE security warning if salt is omitted.
curl_setopt | Removed CURLOPT_CLOSEPOLICY and associated values.
curl_setopt | CURLOPT_SAFE_UPLOAD is now TRUE by default.
hash_algos | Support for gost-crypto was added. This implements the GOST hash function using the CryptoPro S-box tables as specified by RFC 4357, section 11.2.
html_entity_decode | The default value for the encoding parameter was changed to be the value of the default_charset configuration option.
htmlentities | The default value for the encoding parameter was changed to be the value of the default_charset configuration option.
htmlspecialchars | The default value for the encoding parameter was changed to be the value of the default_charset configuration option.
json_decode | Invalid non-lowercased variants of the true, false and null literals are no longer accepted as valid input, and will generate warnings.
mb_regex_encoding | Default encoding is changed to UTF-8. It was EUC-JP Previously.
mcrypt_create_iv | MCRYPT_DEV_URANDOM is now the default value of source.
mcrypt_decrypt | Invalid key and iv sizes are no longer accepted. mcrypt_decrypt will now throw a warning and return FALSE if the inputs are invalid. Previously keys and IVs were padded with '\0' bytes to the next valid size.
mcrypt_encrypt | Invalid key and iv sizes are no longer accepted. mcrypt_encrypt will now throw a warning and return FALSE if the inputs are invalid. Previously keys and IVs were padded with '\0' bytes to the next valid size.
pg_connect | Support for giving the PGSQL_CONNECT_ASYNC constant as the connect_type was added.
pg_convert | No longer experimental. Boolean/NULL data types are supported. Unknown/unsupported data types are escaped without validation. pg_convert can be used with any data types.
pg_delete | No longer experimental. Added PGSQL_DML_ESCAPE constant, TRUE/FALSE and NULL data type support.
pg_insert | Unless PGSQL_DML_STRING is passed, the function now returns the connection resource instead of TRUE on success.
pg_insert | No longer experimental. Added PGSQL_DML_ESCAPE constant, TRUE/FALSE and NULL data type support.
pg_lo_seek | Added PostgreSQL 9.3's 64bit large object support. Both client and server must support PostgreSQL 9.3 and PHP must be 64bit build to use 64bit large object.
pg_lo_tell | Added PostgreSQL 9.3's 64bit large object support. Both client and server must support PostgreSQL 9.3 and PHP must be 64bit build to use 64bit large object.
pg_lo_truncate | Added truncate function. It supports PostgreSQL 9.3's 64bit large object. Both client and server must support PostgreSQL 9.3 and PHP must be 64bit build to use 64bit large object.
pg_meta_data | No longer experimental. Added "is enum" as default attribute. extended flag is added.
pg_select | No longer experimental. Added PGSQL_DML_ESCAPE constant, TRUE/FALSE and NULL data type support.
pg_update | No longer experimental. Added PGSQL_DML_ESCAPE constant, TRUE/FALSE and NULL data type support.
stream_socket_enable_crypto | The crypto_type is now optional.
stream_socket_enable_crypto | Introduce STREAM_CRYPTO_METHOD_ANY_CLIENT, STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT, STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT, STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT, STREAM_CRYPTO_METHOD_ANY_SERVER, STREAM_CRYPTO_METHOD_TLSv1_0_SERVER, STREAM_CRYPTO_METHOD_TLSv1_1_SERVER, STREAM_CRYPTO_METHOD_TLSv1_2_SERVER.
unserialize | Manipulating the serialised data by replacing C: with O: to force object instantiation without calling the constructor will now fail.
ReflectionClass::newInstanceWithoutConstructor | All internal classes can now be instantiated except for those declared final.
XMLReader::getAttributeNo | XMLReader::getAttributeNo now returns NULL if the attribute doesn't exist.
XMLReader::getAttributeNs | XMLReader::getAttributeNS now returns NULL if the attribute doesn't exist.
5.5.38, 5.6.24, 7.0.9 | getenv | The local_only parameter has been added.
5.5.22, 5.6.6 | flock | Added support for the wouldblock parameter on Windows.
SplFileObject::flock | Added support for the wouldblock parameter on Windows.
5.5.21, 5.6.5 | SplFileObject::fputcsv | Added the escape parameter.
5.5.21 | crypt | When the failure string "*0" is given as the salt, "*1" will now be returned for consistency with other crypt implementations. Prior to this version, PHP 5.5 (and earlier branches) would incorrectly return a DES hash.
5.5.19/5.6.3 | imagescale | The calculation of the height if new_height was negative or omitted was fixed; prior to these versions, the aspect ratio was not maintained correctly.
5.5.19, 5.6.3 | DateTimeZone::getOffset | datetime type changed to DateTimeInterface. Previously, DateTime.
5.5.11 | substr_compare | length may now be 0.
5.5.10 | DateTimeZone::__construct | The timezone parameter accepts offset values.
5.5.8 | DatePeriod::__construct | end type changed to DateTimeInterface. Previously, DateTime.
5.5.7 | apache_request_headers | This function became available in the CLI server.
apache_response_headers | This function became available in the CLI server.
getallheaders | This function became available in the CLI server.
5.5.4 | fputcsv | The escape_char parameter was added
5.5.3/5.4.19 | pg_delete | Direct SQL injection to table_name and Indirect SQL injection to identifiers are fixed.
pg_insert | Direct SQL injection to table_name and Indirect SQL injection to identifiers are fixed.
pg_select | Direct SQL injection to table_name and Indirect SQL injection to identifiers are fixed.
pg_update | Direct SQL injection to table_name and Indirect SQL injection to identifiers are fixed.
5.5.2 | DOMDocument::schemaValidate | Added the flags parameter
DOMDocument::schemaValidateSource | Added the flags parameter
5.5.1 | hex2bin | A warning is thrown if the input string is invalid hexadecimal string.
pg_unescape_bytea | A warning is thrown if the input string is invalid.
session_set_save_handler | Added the optional create_sid parameter.
5.5.0/PECL 3.0.0 | IntlDateFormatter::create | An IntlCalendar object is allowed for calendar. Objects of type IntlTimeZone and DateTimeZone are allowed for timezone. Invalid timezone identifiers (including empty strings) are no longer allowed for timezone. If NULL is given for timezone, the timezone identifier given by date_default_timezone_get will be used instead of ICUʼs default.
IntlDateFormatter::format | Support for providing IntlCalendar objects to the value parameter was added.
IntlDateFormatter::setCalendar | It became possible to pass an IntlCalendar object.
5.5.0 | DatePeriod::__construct | start type changed to DateTimeInterface. Previously, DateTime.
curl_getinfo | Introduced CURLINFO_RESPONSE_CODE, CURLINFO_HTTP_CONNECTCODE, CURLINFO_HTTPAUTH_AVAIL, CURLINFO_PROXYAUTH_AVAIL, CURLINFO_OS_ERRNO, CURLINFO_NUM_CONNECTS, CURLINFO_SSL_ENGINES, CURLINFO_COOKIELIST, CURLINFO_FTP_ENTRY_PATH, CURLINFO_APPCONNECT_TIME, CURLINFO_CONDITION_UNMET, CURLINFO_RTSP_CLIENT_CSEQ, CURLINFO_RTSP_CSEQ_RECV, CURLINFO_RTSP_SERVER_CSEQ and CURLINFO_RTSP_SESSION_ID.
curl_setopt | Added the cURL resource as the first argument to the CURLOPT_PROGRESSFUNCTION callback.
curl_setopt | Introduced CURLOPT_SHARE.
empty | empty now supports expressions, rather than only variables.
imagerotate | The ignore_transparent is now silently ignored.
imagerotate | This function is now affected by the interpolation method set by the imagesetinterpolation function.
ip2long | Prior to this version, on Windows ip2long would sometimes return a valid number even if passed a value which was not an (IPv4) Internet Protocol dotted address.
iterator_to_array | iterator_to_array gained support for key types other than integer and string when the use_keys parameter is enabled.
json_encode | depth parameter was added.
json_encode | JSON_PARTIAL_OUTPUT_ON_ERROR options was added.
json_encode | The return value on failure was changed from null string to FALSE.
mysql_connect | This function will generate an E_DEPRECATED error.
mysql_db_name | The mysql_list_dbs function is deprecated, and emits an E_DEPRECATED level error.
mysql_pconnect | This function will generate an E_DEPRECATED error.
mysql_tablename | The mysql_tablename function is deprecated, and emits an E_DEPRECATED level error.
pack | The "Z" code was added with equivalent functionality to "a" for Perl compatibility.
php_logo_guid | php_logo_guid has been removed from PHP.
phpinfo | Logo GUIDs were replaced with data URIs, and so turning off expose_php now has no effect on the result of phpinfo(). Credits are also now embedded within the output itself instead of linked.
preg_replace | The /e modifier is deprecated. Use preg_replace_callback instead. See the PREG_REPLACE_EVAL documentation for additional information about security risks.
set_error_handler | error_handler now accepts NULL.
set_exception_handler | Previously, if NULL was passed then this function returned TRUE. It returns the previous handler since PHP 5.5.0.
setcookie | A Max-Age attribute is now included in the Set-Cookie header sent to the client.
setrawcookie | A Max-Age attribute is now included in the Set-Cookie header sent to the client.
unpack | Changes were made to bring this function into line with Perl: The "a" code now retains trailing NULL bytes. The "A" code now strips all trailing ASCII whitespace (spaces, tabs, newlines, carriage returns, and NULL bytes). The "Z" code was added for NULL-padded strings, and removes trailing NULL bytes.
zend_logo_guid | zend_logo_guid has been removed from PHP.
IntlDateFormatter::setTimeZoneId | This function has been deprecated.
mysqli::commit | Added flags and name parameters.
mysqli::options | The MYSQLI_SERVER_PUBLIC_KEY and MYSQLI_SERVER_PUBLIC_KEY options were added.
mysqli::rollback | Added flags and name parameters.
SoapClient::SoapClient | New ssl_method option.
5.4.43, 5.5.27, 5.6.11 | escapeshellarg | Exclamation marks are replaced by spaces.
escapeshellcmd | Exclamation marks are replaced by spaces.
5.4.42, 5.5.27 | mail | Header injection protection has been added for the additional_headers parameter. This means that multiple consecutive newlines are no longer allowed.
5.4.32, 5.5.16 | ucwords | Added the delimiters parameter.
5.4.8 | assert | The description parameter was added. The description is also now provided to a callback function in ASSERT_CALLBACK mode as the fourth argument.
mb_strcut | Passing NULL as length extracts all bytes to the end of the string. Prior to this version NULL was treated the same as 0.
mb_substr | Passing NULL as length extracts all characters to the end of the string. Prior to this version NULL was treated the same as 0.
5.4.7 | curl_getinfo | Introduced CURLINFO_PRIMARY_IP, CURLINFO_PRIMARY_PORT, CURLINFO_LOCAL_IP and CURLINFO_LOCAL_PORT.
parse_url | Fixed host recognition when scheme is omitted and a leading component separator is present.
5.4.4 | hex2bin | A warning is thrown if the input string is of odd length. In PHP 5.4.0 the string was silently accepted, but the last byte was truncated.
5.4.0/PECL 2.0.0b1 | idn_to_ascii | Added the parameters variant and idna_info; UTS #46 support (requires ICU ≥ 4.6).
idn_to_utf8 | Added the parameters variant and idna_info; UTS #46 support (requires ICU ≥ 4.6).
5.4.0 | DOMDocument::loadHTML | Added options parameter.
DOMDocument::loadHTMLFile | Added options parameter.
apache_child_terminate | This function became available under FastCGI. Previously, it was supported only when PHP was installed as an Apache module.
apache_request_headers | This function became available under FastCGI. Previously, it was supported when PHP was installed as an Apache module or by the NSAPI server module in Netscape/iPlanet/SunONE webservers.
apache_response_headers | This function became available under FastCGI. Previously, it was supported when PHP was installed as an Apache module or by the NSAPI server module in Netscape/iPlanet/SunONE webservers.
array_combine | Previous versions issued E_WARNING and returned FALSE for empty arrays.
array_multisort | The SORT_NATURAL and SORT_FLAG_CASE were added to array1_sort_flags as possible sort flags.
date_default_timezone_get | The timezone is no longer guessed from information available through the operating system as the guessed timezone can not be relied on.
date_default_timezone_get | The TZ environment variable is no longer used to guess the timezone.
debug_backtrace | Added the optional parameter limit.
debug_print_backtrace | Added the optional parameter limit.
define_syslog_variables | This function was removed from PHP.
dns_get_record | Added raw parameter.
empty | Checking non-numeric offsets of strings returns TRUE.
error_reporting | E_STRICT became part of E_ALL.
filter_input_array | Added add_empty parameter.
filter_var_array | Added add_empty parameter.
get_html_translation_table | The default value for the encoding parameter was changed to UTF-8.
get_html_translation_table | The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
get_magic_quotes_gpc | Always returns FALSE because the magic quotes feature was removed from PHP.
get_magic_quotes_runtime | Always returns FALSE because the magic quotes feature was removed from PHP.
getallheaders | This function became available under FastCGI. Previously, it was supported when PHP was installed as an Apache module or by the NSAPI server module in Netscape/iPlanet/SunONE webservers.
gzcompress | Added encoding parameter.
gzdeflate | Added encoding parameter.
gzencode | FORCE_DEFLATE now generates RFC 1950 compliant output.
hash | The tiger algorithm now uses big-endian byte ordering. See also example below.
hash_algos | Support for joaat, fnv132 and fnv164 was added. Support for Salsa10 and Salsa20 was removed.
html_entity_decode | The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
html_entity_decode | Default encoding changed from ISO-8859-1 to UTF-8.
htmlentities | The default value for the encoding parameter was changed to UTF-8.
htmlentities | The constants ENT_SUBSTITUTE, ENT_DISALLOWED, ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
htmlspecialchars | The constants ENT_SUBSTITUTE, ENT_DISALLOWED, ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
htmlspecialchars | The default value for the encoding parameter was changed to UTF-8.
htmlspecialchars_decode | The constants ENT_HTML401, ENT_XML1, ENT_XHTML and ENT_HTML5 were added.
http_build_query | The enc_type parameter was added.
iconv | Since this version, the function returns FALSE on illegal characters, unless //IGNORE is specified in output charset. Before, it returned partial output string.
imagecolorset | The alpha parameter was added.
imagegd | Added support for passing a stream resource to to.
imagegd2 | Added support for passing a stream resource to to.
imagegif | Added support for passing a stream resource to to.
imagejpeg | Disallowed passing an empty string to to to skip this argument.
imagejpeg | Added support for passing a stream resource to to.
imagepng | Added support for passing a stream resource to to.
imagewbmp | Added support for passing a stream resource to to.
isset | Checking non-numeric offsets of strings now returns FALSE.
json_decode | The options parameter was added.
json_decode | JSON_BIGINT_AS_STRING, and JSON_OBJECT_AS_ARRAY options were added.
json_encode | JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, and JSON_UNESCAPED_UNICODE options were added.
mb_decode_numericentity | Added is_hex parameter.
mb_encode_numericentity | Added is_hex parameter.
mysqli_get_cache_stats | The mysqli_get_cache_stats was removed.
number_format | This function now supports multiple bytes in dec_point and thousands_sep. Only the first byte of each separator was used in older versions.
ob_start | The third parameter of ob_start changed from a boolean parameter called erase (which, if set to FALSE, would prevent the output buffer from being deleted until the script finished executing) to an integer parameter called flags. Unfortunately, this results in an API compatibility break for code written prior to PHP 5.4.0 that uses the third parameter. See the flags example for an example of how to handle this with code that needs to be compatible with both.
ob_start | A chunk size of 1 now results in chunks of 1 byte being sent to the output buffer.
openssl_decrypt | The raw_output was changed to options.
openssl_encrypt | The raw_output was changed to options.
preg_match_all | The matches parameter became optional.
scandir | sorting_order constants were added. Any nonzero value caused descending order in previous versions. So for all PHP versions, use 0 for ascending order, and 1 for descending order. An option for SCANDIR_SORT_NONE behavior did not exist prior to PHP 5.4.0.
session_set_save_handler | Added SessionHandlerInterface for implementing session handlers and SessionHandler to expose internal PHP session handlers.
snmp_set_valueretrieval | Constants SNMP_VALUE_PLAIN or SNMP_VALUE_LIBRARY may be combined with SNMP_VALUE_OBJECT resulting different way of representing contents of value array element in return value of GET-function. If no SNMP_VALUE_{PLAIN,LIBRARY} constant is accompanying SNMP_VALUE_OBJECT, SNMP_VALUE_LIBRARY is used. Prior to 5.4.0 SNMP_VALUE_OBJECT effecively meant SNMP_VALUE_OBJECT|SNMP_VALUE_PLAIN.
sort | Added support for SORT_NATURAL and SORT_FLAG_CASE as sort_flags
PDOStatement::getColumnMeta | PDO_DBLIB driver support added
Phar::setStub | Added len parameter.
PharData::setStub | Added len parameter.
SimpleXMLElement::getDocNamespaces | Added from_root parameter.
SoapClient::SoapClient | New keep_alive option.
5.4 | grapheme_substr | If length is given and positive and the argument string is shorter than the specified length, all the rest of the string according to start parameter is returned. Previously, FALSE was returned.
5.3.19 | imagecreatefromxpm | imagecreatefromxpm is available on Windows.
5.3.9 | DateTime::createFromFormat | The + format specifier has been added.
dl | dl is enabled in PHP-FPM, albeit discouraged.
is_a | Added allow_string parameter
is_subclass_of | Added allow_string parameter
5.3.7 | crypt | Added $2x$ and $2y$ Blowfish modes to deal with potential high-bit attacks.
curl_getinfo | Introduced CURLINFO_REDIRECT_URL.
is_subclass_of | Added support for class_name to work with interfaces
5.3.6 | DateTime::modify | Absolute date/time statements now take effect. Previously, only relative parts were used.
DOMDocument::saveHTML | The node parameter was added.
array_product | The product of an empty array is now 1, when before this function would return 0 for an empty array.
debug_backtrace | The parameter provide_object changed to options and additional option DEBUG_BACKTRACE_IGNORE_ARGS is added.
debug_print_backtrace | Added the optional parameter options.
preg_match | Returns FALSE if offset is higher than subject length.
preg_match_all | Returns FALSE if offset is higher than subject length.
PDO_MYSQL DSN | Prior to version 5.3.6, charset was ignored.
5.3.4 | copy | Changed the context parameter to actually have an effect. Previously, any context was ignored.
get_html_translation_table | The encoding parameter was added.
mt_rand | Issues an E_WARNING and returns FALSE if max < min.
rawurlencode | Tilde characters are no longer encoded when rawurlencode is used with EBCDIC strings.
sleep | Before PHP 5.3.4, on Windows, sleep always returns NULL when sleep has occurred, regardless of whether the sleep was interrupted or not.
strip_tags | strip_tags ignores self-closing XHTML tags in allowable_tags.
IntlDateFormatter::format | Support for providing DateTime objects to the value parameter was added.
mysqli_driver::$report_mode | Changing the reporting mode is now be per-request, rather than per-process.
5.3.3 | DOMXPath::evaluate | The registerNodeNS parameter was added.
DOMXPath::query | The registerNodeNS parameter was added.
imap_fetch_overview | Add the udate property.
json_encode | JSON_NUMERIC_CHECK options was added.
ldap_sasl_bind | Support on Windows was added.
openssl_decrypt | The iv parameter was added.
openssl_encrypt | The iv parameter was added.
parse_url | Removed the E_WARNING that was emitted when URL parsing failed.
5.3.2 (PECL OCI8 1.4) | oci_set_prefetch | Before this release, rows must be >= 1.
5.3.2 | crypt | Fixed Blowfish behaviour on invalid rounds to return "failure" string ("*0" or "*1"), instead of falling back to DES.
crypt | Added SHA-256 and SHA-512 crypt based on Ulrich Drepper's implementation.
flock | The automatic unlocking when the file's resource handle is closed was removed. Unlocking now always has to be done manually.
gmp_init | The base was extended from 2 to 36, to 2 to 62 and -2 to -36.
gmp_strval | The base was extended from 2 to 36, to 2 to 62 and -2 to -36.
imap_append | Added INTERNALDATE support to imap_append.
imap_open | params added
SplFileObject::flock | The automatic unlocking when the file's resource handle is closed was removed. Unlocking now always has to be done manually.
5.3.1 | get_defined_constants | Windows only: Core constants are categorized under Core, previously mhash.
ibase_query | On success the function now returns TRUE if there were no affected rows, where it previously returned 0 (a zero followed by an empty space).
rename | rename can now rename files across drives in Windows.
5.3.0 (PECL OCI8 1.3.4) | oci_set_prefetch | Before this release, prefetching was limited to the lesser of rows rows and 1024 * rows bytes. The byte size restriction has now been removed.
5.3.0 | DateTime::__construct | If time contains an invalid date/time format, then an exception is now thrown. Previously an error was emitted.
DateTime::modify | Changed the return value on success from NULL to DateTime.
DateTime::setDate | Changed the return value on success from NULL to DateTime.
DateTime::setISODate | Changed the return value on success from NULL to DateTime.
DateTime::setTime | Changed the return value on success from NULL to DateTime.
DateTime::setTimezone | Changed the return value on success from NULL to DateTime.
DateTimeZone::getTransitions | The optional timestamp_begin and timestamp_end were added.
DateTimeZone::listIdentifiers | Added the optional what and country parameters.
DirectoryIterator::__construct | Throws UnexpectedValueException if the path cannot be opened.
acosh | This function is now available on all platforms
array_multisort | The SORT_LOCALE_STRING was added to array1_sort_flags as possible sort flags.
array_reduce | Changed initial to allow mixed, previously integer.
array_search | As with all internal PHP functions as of 5.3.0, array_search returns NULL if invalid parameters are passed to it.
asinh | This function is now available on all platforms
atanh | This function is now available on all platforms
call_user_func | If the called function expects a parameter to be passed by reference, an E_WARNING is now issued.
call_user_func | The interpretation of object oriented keywords like parent and self has changed. Previously, calling them using the double colon syntax would emit an E_STRICT warning because they were interpreted as static.
call_user_func_array | The interpretation of object oriented keywords like parent and self has changed. Previously, calling them using the double colon syntax would emit an E_STRICT warning because they were interpreted as static.
checkdnsrr | This function is now available on Windows platforms.
clearstatcache | Added optional clear_realpath_cache and filename parameters.
copy | Added context support.
crypt | PHP now contains its own implementation for the MD5 crypt, Standard DES, Extended DES and the Blowfish algorithms and will use that if the system lacks of support for one or more of the algorithms.
curl_getinfo | Introduced CURLINFO_CERTINFO.
curl_setopt | Introduced CURLOPT_PROGRESSFUNCTION.
date_default_timezone_set | Now throws E_WARNING rather than E_STRICT.
define_syslog_variables | This function now throws an E_DEPRECATED notice.
dl | dl is now disabled in some SAPIs due to stability issues. The only SAPIs that allow dl are CLI and Embed. Use the Extension Loading Directives instead.
dns_get_record | This function is now available on Windows platforms.
dns_get_record | Prior to this release, if the authns parameter was given, the addtl parameter was also required.
error_reporting | E_DEPRECATED and E_USER_DEPRECATED introduced.
exif_imagetype | Added icon support.
expm1 | This function is now available on all platforms
fgetcsv | The escape parameter was added
fnmatch | This function is now available on Windows platforms.
func_get_arg | If this function is called from the outermost scope of a file which has been included by calling include or require from within a function in the calling file, it now generates a warning and returns FALSE.
func_get_arg | This function can now be used in parameter lists.
func_get_args | This function can now be used in parameter lists.
func_get_args | If this function is called from the outermost scope of a file which has been included by calling include or require from within a function in the calling file, it now generates a warning and returns FALSE.
func_num_args | If this function is called from the outermost scope of a file which has been included by calling include or require from within a function in the calling file, it now generates a warning and returns -1.
func_num_args | This function can now be used in parameter lists.
gd_info | JPG Support attribute renamed to JPEG Support.
get_cfg_var | get_cfg_var was fixed to be able to return "array" ini options.
get_class | NULL became the default value for object, so passing NULL to object now has the same result as not passing any value.
get_defined_constants | Core constants are categorized under Core, previously internal. On Windows, the Core Constants are categorized under mhash.
get_object_vars | This function now returns NULL if the object isn't an object. Previously FALSE was returned.
get_resource_type | If handle is not a resource this functions returns NULL. Formerly, FALSE has been returned.
getimagesize | Added icon support.
getmxrr | This function is now available on Windows platforms.
getopt | Added support for "=" as argument/value separator.
getopt | Added support for optional values (specified with "::").
getopt | Parameter longopts is available on all systems.
getopt | This function is no longer system dependent, and now works on Windows, too.
hash_algos | Support for md2, ripemd256, ripemd320, salsa10, salsa20, snefru256 and sha224 was added
htmlentities | The constant ENT_IGNORE was added.
htmlspecialchars | The constant ENT_IGNORE was added.
imagecolorclosesthwb | This function is now available on Windows
imagefilter | Pixelation support (IMG_FILTER_PIXELATE) was added.
inet_ntop | This function is now available on Windows platforms.
inet_pton | This function is now available on Windows platforms.
ini_get | Previously, the empty string was returned if the configuration option didn't exist. now, FALSE is returned instead.
ini_get_all | Added details.
is_a | This function is no longer deprecated, and will therefore no longer throw E_STRICT warnings.
json_decode | Added the optional depth. The default recursion depth was increased from 128 to 512
json_encode | JSON_FORCE_OBJECT, JSON_HEX_AMP, JSON_HEX_APOS, JSON_HEX_QUOT, and JSON_HEX_TAG, options were added.
json_encode | The options parameter was added.
link | This function is now available on Windows platforms (Vista, Server 2008 or greater).
linkinfo | This function is now available on Windows platforms (Vista, Server 2008 or greater).
log1p | This function is now available on all platforms
mb_get_info | The entry "http_output_conv_mimetypes" was made available.
mcrypt_create_iv | MCRYPT_DEV_RANDOM and MCRYPT_DEV_URANDOM became available on Windows platforms.
mcrypt_create_iv | It is no longer required to call srand first. This is now done automatically.
mktime | mktime now throws E_DEPRECATED notice if the is_dst parameter is used.
mysql_db_query | This function now throws an E_DEPRECATED notice.
mysql_escape_string | This function now throws an E_DEPRECATED notice.
mysqli_get_cache_stats | The mysqli_get_cache_stats was added as stub.
nl2br | Added the optional is_xhtml parameter. Before this version '<br />' was always inserted.
openssl_open | The method has been added.
openssl_seal | The method has been added.
parse_ini_file | Added optional scanner_mode parameter. Single quotes may now be used around variable assignments. Hash marks (#) should no longer be used as comments and will throw a deprecation warning if used.
pg_lo_create | The optional object_id was added.
pg_lo_import | The optional object_id was added.
preg_quote | The - character is now quoted
property_exists | This function checks the existence of a property independent of accessibility.
rawurlencode | Now conforms to RFC 3986.
readlink | This function is now available on Windows platforms (Vista, Server 2008 or greater).
realpath | Prior to this release, if only the last path component did not exist, realpath would not fail on *BSD systems. realpath now fails in this case.
register_tick_function | Ticks are now supported on threaded web server modules.
round | The mode parameter was introduced.
session_start | If a session fails to start, then FALSE is returned. Previously TRUE was returned.
setlocale | This function now throws an E_DEPRECATED notice if a string is passed to the category parameter instead of one of the LC_* constants.
shm_attach | This function now returns a resource instead of an integer.
socket_create_pair | This function is now available on Windows platforms.
spl_autoload_register | The prepend parameter was added.
spl_autoload_register | Namespaces support was introduced.
stream_context_create | Added the optional params argument.
stream_socket_pair | This function is now available on Windows platforms.
stristr | Added the optional parameter before_needle.
strlen | Prior versions treated arrays as the string Array, thus returning a string length of 5 and emitting an E_NOTICE level error.
strstr | Added the optional parameter before_needle.
strtotime | Prior to PHP 5.3.0, 24:00 was not a valid format and strtotime returned FALSE.
strtotime | Prior to PHP 5.3.0, relative time formats supplied to the time argument of strtotime such as this week, previous week, last week, and next week were interpreted to mean a 7 day period relative to the current date/time, rather than a week period of Monday through Sunday.
sybase_connect | The new parameter was added.
symlink | This function is now available on Windows platforms (Vista, Server 2008 or greater).
time_nanosleep | This function is now available on Windows platforms.
time_sleep_until | This function is now available on Windows platforms.
touch | It became possible to change the modification time of a directory under Windows.
mysqli::__construct | Added the ability of persistent connections.
mysqli::options | The MYSQLI_OPT_INT_AND_FLOAT_NATIVE, MYSQLI_OPT_NET_CMD_BUFFER_SIZE, MYSQLI_OPT_NET_READ_BUFFER_SIZE, and MYSQLI_OPT_SSL_VERIFY_SERVER_CERT options were added.
mysqli::query | Added the ability of async queries.
PDO::__construct | Classes which extends PDO and implements the __call magic method will now receive the method name in the declared casing. Previously this was always lower case.
ReflectionFunction::__construct | name can now be a closure.
SplFileObject::setCsvControl | Added the escape parameter.
SplObjectStorage::attach | Added the data parameter.
XMLReader::expand | The parameter basenode was added.
5.2.15 | mysqli_driver::$report_mode | Changing the reporting mode is now be per-request, rather than per-process.
5.2.11 | get_defined_constants | The categorize parameter now operates appropriately. Previously, the categorize parameter was interpreted as !is_null($categorize), making any value other than NULL force the constants to be categorized.
5.2.10 | array_rand | The resulting array of keys is no longer shuffled.
array_unique | Changed the default value of sort_flags back to SORT_STRING.
curl_setopt | Introduced CURLOPT_PROTOCOLS, and CURLOPT_REDIR_PROTOCOLS.
ip2long | Prior to this version, ip2long would sometimes return a valid number even if passed a value which was not an (IPv4) Internet Protocol dotted address.
natsort | Zero padded numeric strings (e.g., '00005') now essentially ignore the 0 padding.
5.2.9 | array_unique | Added the optional sort_flags defaulting to SORT_REGULAR. Prior to 5.2.9, this function used to sort the array with SORT_STRING internally.
5.2.8 | XSLTProcessor::importStylesheet | Accepts SimpleXMLElement again which was broken since PHP 5.2.6.
5.2.7 | error_log | The possible value of 4 was added to message_type.
parse_ini_file | On syntax error this function will return FALSE rather than an empty array.
round | The inner workings of round was changed to conform to the C99 standard.
strtotime | In PHP 5 prior to 5.2.7, requesting a given occurrence of a given weekday in a month where that weekday was the first day of the month would incorrectly add one week to the returned timestamp. This has been corrected in 5.2.7 and later versions.
5.2.6 | fopen | The 'c' and 'c+' options were added
5.2.5 | addcslashes | The escape sequences \v and \f were added.
debug_backtrace | Added the optional parameter provide_object.
imagefilter | Alpha support for IMG_FILTER_COLORIZE was added.
5.2.4 | array_slice | The default value of the length parameter was changed to NULL. A NULL length now tells the function to use the length of array. Prior to this version, a NULL length was taken to mean a zero length (nothing will be returned).
checkdnsrr | TXT type was added.
curl_getinfo | Introduced CURLINFO_PRIVATE.
curl_setopt | Introduced CURLOPT_PRIVATE.
get_loaded_extensions | The optional zend_extensions parameter was added
ldap_first_attribute | The ber_identifier was removed. This is now handled automatically by PHP.
ldap_next_attribute | The ber_identifier was removed. This is now handled automatically by PHP.
parse_ini_file | Keys and section names consisting of numbers are now evaluated as PHP integers thus numbers starting by 0 are evaluated as octals and numbers starting by 0x are evaluated as hexadecimals.
stream_wrapper_register | Added the flags parameter.
5.2.3 | getimagesize | Read errors generated by this function downgraded to E_NOTICE from E_WARNING.
htmlentities | The double_encode parameter was added.
htmlspecialchars | The double_encode parameter was added.
json_decode | The nesting limit was increased from 20 to 128
XMLWriter::writeElement | The content parameter became optional.
XMLWriter::writeElementNs | The content parameter became optional.
PDOStatement::getColumnMeta | table field
5.2.2 - 5.2.6 | substr | If the start parameter indicates the position of a negative truncation or beyond, false is returned. Other versions get the string from start.
5.2.2 | DOMDocument::registerNodeClass | Prior to 5.2.2, a previously registered extendedclass had to be unregistered before being able to register a new class extending the same baseclass.
date_sun_info | The order of latitude and longitude has been swapped.
ftp_ssl_connect | The function was changed to return FALSE when it can't use an SSL connection, instead of falling back to a non-SSL one as previously.
phpinfo | The "Loaded Configuration File" information was added, when before only "Configuration File (php.ini) Path" existed.
preg_match | Named subpatterns now accept the syntax (?<name>) and (?'name') as well as (?P<name>). Previous versions accepted only (?P<name>).
preg_match_all | Named subpatterns now accept the syntax (?<name>) and (?'name') as well as (?P<name>). Previous versions accepted only (?P<name>).
proc_terminate | Previous versions used to destroy the given process resource.
token_get_all | Line numbers are returned in element 2
5.2.1 | iterator_to_array | The use_keys parameter was added.
json_decode | Added support for JSON decoding of basic types.
memory_get_peak_usage | Compiling with --enable-memory-limit is no longer required for this function to exist.
memory_get_usage | Compiling with --enable-memory-limit is no longer required for this function to exist.
mt_srand | The Mersenne Twister implementation in PHP now uses a new seeding algorithm by Richard Wagner. Identical seeds no longer produce the same sequence of values they did in previous versions. This behavior is not expected to change again, but it is considered unsafe to rely upon it nonetheless.
proc_open | Added the bypass_shell option to the other_options parameter.
realpath | Prior to this version, realpath returned FALSE if path is an empty string or NULL.
5.2.0 | base64_decode | strict added
curl_multi_info_read | msgs_in_queue was added.
error_reporting | E_RECOVERABLE_ERROR introduced.
imagettftext | It is now possible to specify an hexadecimal entity in text.
imap_open | n_retries added
imap_reopen | n_retries added
mb_strrpos | Added the optional parameter offset.
memory_get_peak_usage | real_usage was added.
memory_get_usage | real_usage was added.
openssl_verify | The signature_alg parameter was added.
pathinfo | The PATHINFO_FILENAME constant was added.
pg_escape_bytea | connection added
pg_escape_string | connection added
session_get_cookie_params | The "httponly" entry was added in the returned array.
session_set_cookie_params | The httponly parameter was added.
set_error_handler | The error handler must return FALSE to populate $php_errormsg.
setcookie | The httponly parameter was added.
setrawcookie | The httponly parameter was added.
snmp_set_oid_numeric_print | Since PHP 5.2.0.
PDOStatement::execute | The keys from input_parameters must match the ones declared in the SQL. Before PHP 5.2.0 this was silently ignored.
SimpleXMLElement::children | The optional parameter is_prefix was added.
SimpleXMLElement::__construct | Added the ns and is_prefix parameters.
SoapServer::SoapServer | Added the typemap option.
XMLReader::open | encoding and options were added.
XMLReader::XML | encoding and options were added.
5.1.3 | DirectoryIterator::__construct | Throws RuntimeException if the path is an empty string.
curl_getinfo | Introduced CURLINFO_HEADER_OUT.
get_headers | This function now uses the default stream context, which can be set/changed with the stream_context_set_default function.
http_build_query | Square brackets are escaped.
imagecolorallocate | Returns FALSE if the allocation failed. Previously -1 was returned.
imagecolorallocatealpha | Returns FALSE if the allocation failed. Previously -1 was returned.
imagepng | Added the filters parameter.
mb_get_info | The entries "mail_charset", "mail_header_encoding", and "mail_body_encoding" were made available.
SoapClient::__doRequest | The one_way parameter was added.
XMLReader::getAttribute | Return NULL if no attribute found. Previously, returned an empty string.
5.1.2 | date_default_timezone_set | The function started to validate the timezone_identifier parameter.
header | This function now prevents more than one header to be sent at once as a protection against header injection attacks.
http_build_query | The arg_separator parameter was added.
imagepng | Added the quality parameter.
parse_url | Added the component parameter.
SimpleXMLElement::__construct | Added the options and data_is_url parameters.
5.1.1 | date | There are useful constants of standard date/time formats that can be used to specify the format parameter.
debug_backtrace | Added the current object as a possible return element.
gmdate | There are useful constants of standard date/time formats that can be used to specify the format parameter.
5.1.0 | DirectoryIterator::__construct | Throws RuntimeException on error. Previously, threw Exception.
DOMDocument::save | Added the options parameter
DOMDocument::saveXML | Added the options parameter
class_implements | Added the option to pass the class parameter as a string. Added the autoload parameter.
class_parents | Added the option to pass the class parameter as a string. Added the autoload parameter.
ctype_digit | Before PHP 5.1.0, this function returned TRUE when text was an empty string.
curl_setopt | Introduced CURLOPT_AUTOREFERER, CURLOPT_BINARYTRANSFER, CURLOPT_FTPSSLAUTH, CURLOPT_PROXYAUTH, and CURLOPT_TIMECONDITION.
date | Now issues the E_STRICT and E_NOTICE time zone errors.
date | The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer). However, before PHP 5.1.0 this range was limited from 01-01-1970 to 19-01-2038 on some systems (e.g. Windows).
date_sunrise | Now issues the E_STRICT and E_NOTICE time zone errors.
date_sunset | Now issues the E_STRICT and E_NOTICE time zone errors.
explode | Support for negative limits was added
fgetcsv | The length is now optional. Default is 0, meaning no length limit.
file_get_contents | Added the offset and maxlen parameters.
file_put_contents | Added support for LOCK_EX and the ability to pass a stream resource to the data parameter
get_parent_class | If called without parameter outside object, this function would have returned NULL with a warning, but now returns FALSE.
gettimeofday | The return_float parameter was added.
glob | GLOB_ERR was added
gmdate | The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer). However, before PHP 5.1.0 this range was limited from 01-01-1970 to 19-01-2038 on some systems (e.g. Windows).
gmmktime | As of PHP 5.1.0, the is_dst parameter became deprecated. As a result, the new timezone handling features should be used instead.
idate | Now issues the E_STRICT and E_NOTICE time zone errors.
imagerotate | ignore_transparent was added.
intval | Throws E_NOTICE and returns 1, when an object is passed to var.
localtime | Now issues the E_STRICT and E_NOTICE time zone errors.
md5_file | Changed the function to use the streams API. It means that you can use it with wrappers, like md5_file('http://example.com/..')
mktime | The is_dst parameter became deprecated. Made the function return FALSE on error, instead of -1. Fixed the function to accept the year, month and day to be all passed as zero.
mktime | When called with no arguments, mktime throws E_STRICT notice. Use the time function instead.
mktime | Now issues the E_STRICT and E_NOTICE time zone errors.
mssql_connect | The new_link parameter was added
openssl_pkcs7_verify | The content parameter was added.
preg_replace | Added the count parameter
preg_replace_callback | The count parameter was added
session_regenerate_id | Added the delete_old_session parameter.
sha1_file | Changed the function to use the streams API. It means that you can use it with wrappers, like sha1_file('http://example.com/..')
str_word_count | Added the charlist parameter
stream_copy_to_stream | Added the offset parameter
stream_filter_append | Prior to PHP 5.1.0, this function returns TRUE on success or FALSE on failure.
stream_filter_prepend | Prior to PHP 5.1.0, this function returns TRUE on success or FALSE on failure.
stream_get_contents | The offset was added.
strftime | Now issues the E_STRICT and E_NOTICE time zone errors.
strtotime | Now issues the E_STRICT and E_NOTICE time zone errors.
strtotime | Now returns FALSE on failure, instead of -1.
substr_compare | Added the possibility to use a negative offset.
substr_count | Added the offset and the length parameters
var_export | Possibility to export classes and arrays containing classes using the __set_state() magic method.
XSLTProcessor::registerPHPFunctions | The restrict parameter was added.
5.0.5 | php_check_syntax | This function was removed from PHP.
5.0.4 | msql_fetch_array | A bug was fixed when retrieving data from columns containing NULL values. Such columns were not placed into the resulting array.
msql_fetch_object | A bug was fixed when retrieving data from columns containing NULL values. Such columns were not placed into the resulting array.
msql_fetch_row | A bug was fixed when retrieving data from columns containing NULL values. Such columns were not placed into the resulting array.
5.0.3 | get_class_vars | get_class_vars will only return the properties that can be accessed from the current scope.
is_subclass_of | You may also specify the object parameter as a string (the name of the class)
php_check_syntax | Calling exit after php_check_syntax resulted in a Segfault.
5.0.2 | array_slice | The optional preserve_keys parameter was added.
class_exists | No longer returns TRUE for defined interfaces. Use interface_exists.
get_class_vars | Calling get_class_vars will now expose all the properties as an array, unlike previous behaviour where protected and private properties were prefixed with nul bytes.
sort | Added SORT_LOCALE_STRING
strtotime | In PHP 5 up to 5.0.2, "now" and other relative times are wrongly computed from today's midnight. This differs from other versions where it is correctly computed from current time.
5.0.1 | get_class_vars | Calling get_class_vars will expose all properties, as when converting an object to a class.
php_check_syntax | error_message is passed by reference.
5.0.0 | curl_setopt | Introduced CURLOPT_FTP_USE_EPRT, CURLOPT_NOSIGNAL, CURLOPT_UNRESTRICTED_AUTH, CURLOPT_BUFFERSIZE, CURLOPT_HTTPAUTH, CURLOPT_PROXYPORT, CURLOPT_PROXYTYPE, CURLOPT_SSLCERTTYPE, and CURLOPT_HTTP200ALIASES.
is_a | This function became deprecated in favour of the instanceof operator. Calling this function will result in an E_STRICT warning.
strtotime | Microseconds began to be allowed, but they are ignored.


HTML Help Edition

  • About This Edition
  • Using PHP Manual CHM Edition
    • The HTML Help Toolbar
    • The Navigation Pane
    • Keyboard Shortcuts
  • The Full Text Search
    • General searching rules
    • Searching for words or phrases
    • Defining search terms
    • Using nested expressions when searching
  • Integrating the PHP Manual


About This Edition

The Windows HTML Help Edition of the PHP Manual is aimed at developers, who want the manual at hand every time, and would like to read manual pages and user notes without waiting for a remote web page to download. This edition gives you the full content of the manual plus the user notes, with some great features provided by the viewer application by the scripts we use to generate this format and by other contributors in the form of skins.

This distribution of the PHP Manual contains many files, including the main manual file php_manual_en.chm. You can view the manual by double clicking on this file (as you already guessed). You may also see a php_manual_en.chw file in the directory, it's generated the first time you use the index tab, and it contains an index with the manual's pages.

For those interested in technical details about Microsoft HTML Help, » http://www.helpware.net/ is a great resource. For more information and positioning of Windows HTML Help in the Microsoft help formats and services history, see this » WinWriters article.


Using PHP Manual CHM Edition

Table of Contents

  • The HTML Help Toolbar
  • The Navigation Pane
  • Keyboard Shortcuts

When you double click on a CHM, a HTML Help Viewer window opens with three panes. On the left side of the window is the Navigation pane. It contains four navigational tabs: the Contents, Index, Search and Favorites tabs. On the right side of the window is the Topic pane. It displays the selected help topic, or the default help topic on startup. The help pages are all separate HTML files, your Internet Explorer displays the pages in the Topic pane. The third pane is the toolbar, which is located below the help window title bar. You can adjust the horizontal layout with dragging the vertical border between the Navigation pane and the Topic pane.

Note, that when you open the CHM the first time, it may appear in a strange position and size. From then, Windows remembers the window position, size and the last opened tab. All these including your favorites are stored in a file named hh.dat. If you move your file to another directory, all these remembered settings will be lost (including your favorites listing!). If you replace your CHM file with a new one, with the same name, this is not a problem though. The file names and path values are stored in hh.dat.


The HTML Help Toolbar

The HTML Help Toolbar contains the following icons, when you view the PHP Manual:

  • Hide/Show - Hides/shows the navigation pane.
  • Locate - Locates a topic in the contents tab (in case you reached a topic with search, index or favorites, and would like to see where it is in the table of contents tree view).
  • Back - Goes back in the history.
  • Forward - Goes forward in the history.
  • Refresh - Reloads the current page.
  • Home - Opens the startup page of the CHM.
  • Print - Opens the print dialog box.
  • Options - Provides a dropdown with more options.
Using this toolbar is really easy, many of the toolbar icons are strongly related to their Internet Explorer equivalents.


The Navigation Pane

The Navigation Pane contains four navigational tabs: the Contents, Index, Search and Favorites tabs. These all provide different methods to access a topic in the help file.

  • The contents tab reveals a tree like table of contents, where you can navigate to the desired topic by opening and closing parts of the tree. You can even access the deepest sections using this TOC. If you right click on an item here and choose "Print...", you'll have the option to print the selected topic or the selected topic and all subtopics. However printing is not the initial goal of this representation of the manual (the PDF version is suitable for printing).
  • The index tab lists a huge number of "keywords" (actually manual page titles). You can pick one, or start to type a keyword, see the list adjusting to your input, and then click on a topic, or press enter if the selected topic is the one you would like to see.
  • The search tab shows one of the most powerful features of the HTML Help Viewer, the full text search (also known as FTS). Here you can type in your search expression, optionally connecting words with AND/OR/NEAR/NOT. Before you click 'List topics', you can also set some options at the bottom. After the search results are displayed, you'll realize that manual text and user note results are separated. To sort out the two types, click on the 'Location' column header. Now from the search results list, you can pick a topic, and see it's page. The keywords you searched for are highlighted on the page.
  • The favorites tab enables you to store your most used topics in a list, easily accessible. Here you can see the list, add the current topic to it, remove one, or display a selected item. You can also specify your own title for the favorite, by typing it into the 'Current topic:' box. The user note page titles are prepended with a 'N:' string so you can distinguish them from normal manual pages in the favorites listing.


Keyboard Shortcuts

There are many keyboard shortcuts you can use to increase your productivity. Many users find it more appropriate to use these keyboard shortcuts to access topics, instead of clicking.

General Help Viewer Shortcuts
To | Press
Close the Help Viewer | ALT+F4
Display the Options menu | ALT+O
Hide or show the Navigation pane | ALT+O, and then T
Print a topic | ALT+O, and then P
Move back to the previous topic | ALT+LEFT ARROW
Move forward to the next topic (provided you have viewed it just previously) | ALT+RIGHT ARROW
Turn on or off search highlighting. | ALT+O, and then O
Return to the help file home page | ALT+O, and then H
Switch between the Navigation pane and the Topic pane | F6
Scroll through all the links in a topic or through all the options on a Navigation pane tab | TAB
Display context (right click) menu | SHIFT+F10
Contents Tab Shortcuts
To | Press
Display the Contents tab | ALT+C
Open and close a book or folder | PLUS SIGN and MINUS SIGN, or LEFT ARROW and RIGHT ARROW
Select a topic | DOWN ARROW and UP ARROW
Display the selected topic | ENTER
Index Tab Shortcuts
To | Press
Display the Index tab | ALT+N
Type a keyword to search for | ALT+W, and then type the word
Select a keyword in the list | UP ARROW and DOWN ARROW
Display the associated topic | ENTER or ALT+D
Search Tab shortcuts
To | Press
Display the Search tab | ALT+S
Type a keyword to search for | ALT+W, and then type the word
Start a search | ALT+L
Select a topic in the results list | ALT+T, and then UP ARROW and DOWN ARROW
Display the selected topic | ENTER or ALT+D
Search for a keyword in the result list of a prior search | ALT+U
Search for words similar to the keyword. For example, to find words like "running" and "runs" for the keyword "run" | ALT+M
Only search through topic titles | ALT+R
Favorites Tab Shortcuts
To | Press
Display the Favorites tab | ALT+I
Add the currently displayed topic to the Favorites list | ALT+A
Select a topic in the Favorites list | ALT+P, and then UP ARROW and DOWN ARROW
Display the selected topic | ENTER or ALT+D
Remove the selected topic from the list | ALT+R
Topic Pane Shortcuts
To | Press
Index Lookup | Select the words you would like to look up and press F1
Find on page | CTRL+F, and then adjust options
Refresh page | F5


The Full Text Search

Table of Contents

  • General searching rules
  • Searching for words or phrases
  • Defining search terms
  • Using nested expressions when searching

This edition of the PHP Manual includes an advanced full text search possibility provided by the viewer application. This enables users to search through every word in the help file to find a match. For example, if a user does a full-text search on the word "Apache", every topic that contains the word "Apache" will be listed. Advanced full-text search allows a user to search using boolean, wildcard, and nested expressions. A user can also limit the search to previous results, match similar words, or search topic titles only.

The usage of the search feature is fairly straightforward. Click on the search tab, type in the desired words and press ENTER (or click on "List Topics"). Then you'll receive a list of matches from the PHP Manual (and the notes). You can use the button with a right arrow on it to add boolean operators to your search (or you can type them in). As you see the results, you can use the column headings (Title, Location and Rank) to sort the topic list. The default order is by Rank. You can also adjust some parameters at the bottom of this tab.

The words found are highlighted on the current page in the Topic pane by default. You can turn off this feature by choosing the "Search Highlight Off" menu item in the Options menu. To can get this feature back similarly. If you are viewing a long topic, only the first 500 instances of a search word or phrase will be highlighted, due to a limitation of the viewer.


General searching rules

A basic search consists of the word or phrase you want to find. You can use wildcard expressions, nested expressions, boolean operators, similar word matches, a previous results list, or topic titles to further define your search.

The basic rules for formulating queries are as follows:

  • Searches are not case-sensitive, so you can type your search in uppercase or lowercase characters.
  • You may search for any combination of letters (a-z) and numbers (0-9). You cannot search for single letters (a, b, c, etc.) and common words, like: an, and, as, at, be, but, by, do, for, from, have, he, in, it, not, of, on, or, she, that, the, there, they, this, to, we, which, with, you.
  • Punctuation marks such as the period (.), colon (:), semicolon (;), comma (,), and hyphen (-) are ignored during a search.
  • Group the elements of your search using double quotes or parentheses to set apart each element. You cannot search for quotation marks.

Note:

If you are searching for a file name with an extension, you should group the entire string in double quotes, ("filename.ext"). Otherwise, the period will break the file name into two separate terms. The default operation between terms is AND, so you will create the logical equivalent to "filename AND ext."


Searching for words or phrases

You can search for words or phrases and use wildcard expressions. Wildcard expressions allow you to search for one or more characters using a question mark or asterisk. The table below describes the results of these different kinds of searches.

Word and phrase searches
Search for | Example | Results
A single word | select | Topics that contain the word "select". (You will also find its grammatical variations, such as "selector" and "selection".)
A phrase | "new operator" or new operator | Topics that contain the literal phrase "new operator" and all its grammatical variations. Without the quotation marks, the query is equivalent to specifying "new AND operator," which will find topics containing both of the individual words, instead of the phrase.
Wildcard expressions | esc* or HT?? | Results for the first example include topics that contain the terms "ESC", "escape", "escalation", and so on. The asterisk cannot be the only character in the term. Results for the second example include topics that contain the terms "HTTP", "HTML" and so on. The question mark cannot be the only character in the term.

Note:

Select the Match similar words check box to include minor grammatical variations for the phrase you search. This feature only locates variations of the word with common suffixes. For example, a search on the word "add" will find "added," but it will not find "additive". This option is independent of other options or syntax. If you do a titles-only search, variations in titles will be matched. If you use quotes (or any other query operator) any variation of the word can appear; for example, "stemmed search" will also match "stemming search".


Defining search terms

The AND, OR, NOT, and NEAR operators enable you to precisely define your search by creating a relationship between search terms. The following table shows how you can use each of these operators. If no operator is specified, AND is used. For example, the query "server cgi security" is equivalent to "server AND cgi AND security".

Search operators
Search for | Example | Results
Both terms in the same topic | http AND apache | Topics containing both the words "http" and "apache".
Either term in a topic | ming OR swflib | Topics containing either the word "ming" or the word "swflib" or both.
The first term without the second term | xml NOT expat | Topics containing the word "xml" but not the word "expat".
Both terms in the same topic, close together | database NEAR security | Topics containing the word "database" within eight words of the word "security".

Note:

The |, &, and ! characters can also be used in place of OR AND and NOT respectively. This may not work if you use a very old version of the viewer.


Using nested expressions when searching

Nested expressions allow you to create complex searches for information. For example, "html AND ((smtp OR pop3) NEAR mail)" finds topics containing the word "html" along with the words "smtp" and "mail" close together, or containing "html" along with the words "pop3" and "mail" close together.

The basic rules for searching help topics using nested expressions are as follows:

  • You can use parentheses to nest expressions within a query. The expressions in parentheses are evaluated before the rest of the query.
  • If a query does not contain a nested expression, it is evaluated from left to right. For example: "mail NOT pop3 OR smtp" finds topics containing the word "mail" without the word "pop3" or topics containing the word "smtp". On the other hand, "mail NOT (pop3 OR smtp)" finds topics containing the word "mail" without either of the words "pop3" or "smtp".
  • You cannot nest expressions more than five levels deep.


Integrating the PHP Manual

Note:

The information provided here is mainly aimed at IDE authors, or advanced users who would like to integrate this CHM file to their favorite IDEs or other production environment components.

There are several editors out there with support for CHM integration, but you may need to know a few things about what the CHM contains to successfully integrate the manual into your environment.

The CHM is built using XSL style sheets from XML sources. This is unique currently in the PHP Manual family, as all other versions are generated using DSSSL style sheets. This also means, that non-intentional rendering differences may come up. A special conversion script is run on the XSLT output, adding several cute features, and packing up the manual with the preferences files and skin examples.

If you never worked with CHMs, you can think of them as compressed files with OS supported access for files inside and some added search and index support. However CHMs can only be viewed using the HTML Help Viewer, you can directly access files inside them using a special URL prefix, the CHM file name and the file you request from inside. As all the help content is stored in HTML files, you can show pages of the CHM in Internet Explorer.

Assume that you placed your php_manual_en.chm to c:\phpmanual the index file in the manual (which you see the first time) can be accessed with the following URL: mk:@MSITStore:C:\phpmanual\php_manual_en.chm::/_index.html. Here mk:@MSITStore: is the special "protocol", C:\phpmanual\php_manual_en.chm is the CHM with it's full path. The /_index.html part is the path to the index file inside the CHM and :: is just what you need to put between the CHM path and this file path.

Note:

All files are in the root directory of the CHM, unlike the previous CHM versions which included a language directory. Images, style sheets and other supplemental files have names starting with an underscore (like the main index shown above), to avoid name collisions.

The names of generated files follow the same rules as the online manual, except that the extension is .html and not .php. The most important is that function documentation files are named function.FUNCNAME.html where FUNCNAME is the function name, with all underscores converted to hyphens. Some examples are function.echo.html, function.mysql-close.html, function.imagecopy.html.

Using all this information, you can show a manual page for a function requested by a user. A simple example is included in the distribution, named php_quickref.hta. This is a » HTML Application to demonstrate the simple process of showing a manual page for a function. The quickRef() function defined therein does the job.

If you would like to integrate the manual into an IDE without direct support for the PHP manual (actually the underscore to hyphen conversion), you can use the included _function.html file to access a function page. This file is simply a redirector, and can be parameterized via the URL, as _function.html#mysql_close. This page will redirect you to the mysql_close function page (function.mysql-close.html) automatically. You can provide the full path of this file if your IDE supports context sensitive help, and provide the IDE specified string as the parameter. An example for this is the UltraEdit 9 intergation (see the edition's website).

The index of the manual (accessible via the index tab on the navigation pane) can also be used for integrational purposes. All the HTML pages are included in the index with their titles as index terms (including function description pages).

If you are a desktop application developer and would like to tightly integrate the CHM into your program (such as displaying the TOC tree in your IDE's help box), you can find more information at » http://www.helpware.net/, as well as links to other useful resources. The official site for HTML Help is at » http://www.microsoft.com/download/en/details.aspx?id=21138.